bmaexecutor

package module
v1.23.0 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2026 License: Apache-2.0 Imports: 49 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.

README

bma-executor-sdk

Connect your machine (hands) or your own agent (brain) to BMA — the executor, harness and agent ends of the bma.executor protocol.

bma-sdk drives and uses agents (REST / façade client); bma-executor-sdk connects hands or brains to BMA.

Go, TypeScript and Python SDKs for the BMA (BeeOS Managed Agents) Executor Protocol bma.executor.v1.1, with protocol types generated from the contract in contracts/bma/executor and handwritten runtimes. bmad is built on the Go SDK, and the BMA server speaks the same contract.

Moved from beeos-ai/bma-sdks (archived) in 0.4.9. The Go import path changed from github.com/beeos-ai/bma-sdks/executor to github.com/beeos-ai/bma-executor-sdk; the npm and PyPI package names are unchanged.

Language Package Install
Go Go Reference github.com/beeos-ai/bma-executor-sdk (package bmaexecutor, this directory) go get github.com/beeos-ai/bma-executor-sdk@v1.0.2
TypeScript npm @beeos-ai/bma-executor-sdk npm install @beeos-ai/bma-executor-sdk@1.0.2
Python PyPI bma-executor-sdk (bma_executor_sdk) pip install bma-executor-sdk==1.0.2
Version 1.0.0 (tag v1.0.0, all three languages), see CHANGELOG
Protocol bma.executor.v1.1 (the harness also accepts v1; contract 1.1.0, lock.json)
Runtimes Go 1.24+, Node.js 20+ (ESM), Python 3.10+
Integration guide docs/executor
I want to Start here
Understand roles, deployment shapes and what is available Overview
Write an executor (a "hand" the BMA cloud or a local brain drives) Quick start, then the protocol reference
Drive an executor (be the harness / local brain) Local connection and auth and Harness below and in the TypeScript and Python READMEs
Connect a full local agent (turns in, agent events out) Agent capability

The rest of this README is the Go module; see typescript/README.md and python/README.md for the other languages.

Connect your computer (bma)

curl -fsSL https://beeos.ai/bma/install.sh | sh    # or: brew install beeos-ai/tap/bma
bma up                                            # add --api <console origin> for another deployment

bma up prints a short code and opens the console, where you approve this computer and choose its workspace, name and labels (no token is copied). It asks which harnesses to use (bma harness list), downloads their pinned releases into ~/.bma/harnesses/<id>/<version>/, verifies them, checks that you are signed in to each with your own account (offering its sign-in), and installs a user service that keeps this computer connected: a LaunchAgent on macOS (it runs while you are logged in; turn on automatic login for an unattended Mac), a systemd user unit on Linux. Run it again at any time; it only does what is missing.

Command
bma status [--json] connection, service, harness logins, labels
bma harness list | add <id> | login <id> the harnesses this computer runs
bma disconnect stop the service and remove this computer from BMA
bma upgrade [--check] replace bma with the latest release (sha256 checked against its manifest) and restart the service
bma uninstall [--yes] disconnect, remove the service, ~/.bma, the CLI profiles and bma itself
bma run the executor in the foreground (the service runs this)

Your harness credentials stay on this computer and are never sent to BMA. Other machines' brains may use this computer as their hands only if you pass --remote-brain (or answer yes in bma up).

The BMA command line (bma)

The same binary is the command line of the public BMA API (ADR-0102 of beeos-managed-agents). Every API operation is one command, generated from the public OpenAPI document (contracts/bma-api/bma.openapi.yaml) by tools/cligen; requests go through github.com/beeos-ai/bma-sdk/v3.

bma login                                   # approve in the dashboard; or: bma login --with-token < key
bma machines list                           # a table on a terminal, JSON otherwise
bma machines get mch_123 --query .status    # --json, --format json|jsonl|yaml|table, --query <jq>
bma agents apply -f agent.yaml              # create the agent, or a new version only when the file changed
bma sessions launch -f session.yaml --wait  # a session from a file: agent, environment, files, first message
bma sessions send sesn_123 "hello" --wait   # send a message (--file to attach), print the reply and deliverables
bma sessions chat sesn_123                  # talk in the terminal; answer tool approvals; Ctrl-C interrupts
bma sessions events stream sesn_123         # follow events; resumes with Last-Event-ID
bma files upload ./report.pdf
bma skills push ./my-skill                  # a new skill, or --skill <id> for a new version
bma completion zsh > "${fpath[1]}/_bma"

Credentials: --api-key > BMA_API_KEY > the profile's credential (login keychain on macOS, else ~/.config/bma/credentials.json, 0600). Profiles live in ~/.config/bma/config.yaml (bma profiles list|use|set|delete, --profile, BMA_PROFILE; BMA_BASE_URL and BMA_WORKSPACE_ID override one setting). Exit codes: 0 success, 1 failure, 2 usage, 3 not authenticated or permitted, 4 not found, 5 conflict, 6 rate limited/server/network, 7 the followed turn waits for input, 8 the turn failed, 124 timeout, 130 interrupted. The session and agent files are described by cmd/bma/schema/*.schema.json (examples in cmd/bma/examples/). bma docs <dir> writes the full command reference as Markdown.

Regenerate the commands after refreshing the document: go run ./tools/cligen -spec contracts/bma-api/bma.openapi.yaml -out cmd/bma/api_gen.go (the tests fail while api_gen.go is stale or an operation has no command).

Executor quick start

An executor registers with BMA (or a local harness) and answers tool calls:

package main

import (
	"context"
	"errors"
	"log"
	"os"
	"os/exec"

	bmaexecutor "github.com/beeos-ai/bma-executor-sdk"
)

func main() {
	client, err := bmaexecutor.NewClient(bmaexecutor.Options{
		BaseURL:        os.Getenv("BMA_BASE_URL"),
		EnvironmentKey: os.Getenv("BMA_ENVIRONMENT_KEY"),
		EnvironmentID:  os.Getenv("BMA_ENVIRONMENT_ID"),
		Executor:       bmaexecutor.ExecutorInfo{Name: "my-executor", OS: "linux", Arch: "arm64", Version: "0.1.0"},
	})
	if err != nil {
		log.Fatal(err)
	}
	// One typed slot per built-in tool; only registered tools are advertised.
	client.Tools.Bash.Handle(func(ctx context.Context, in bmaexecutor.BashInput, tool bmaexecutor.ToolContext) (bmaexecutor.ToolOutput, error) {
		out, err := exec.CommandContext(ctx, "bash", "-lc", in.Command).Output()
		code := 0
		var exitErr *exec.ExitError
		if errors.As(err, &exitErr) {
			code = exitErr.ExitCode()
		} else if err != nil {
			return bmaexecutor.ToolOutput{}, err // outcome failed
		}
		return bmaexecutor.BashResult{Stdout: string(out), ExitCode: code}.Output(), nil
	})
	if _, err := client.Start(context.Background()); err != nil {
		log.Fatal(err)
	}
	select {}
}

Set Options.BaseURL to your BMA deployment: the default DefaultBaseURL is https://executor.beeos.ai; a base URL on the retired bma API hosts is moved to the executor host; the SDK posts an environment key to {BaseURL}/v1/environments/{EnvironmentID}/token and a machine daemon token to {BaseURL}/v1/machines/{MachineID}/token (the channel URL comes back in the token response as ws_url), uploads artifacts to {BaseURL}/v1/environments/{EnvironmentID}/artifacts, and drops a trailing /api/v1 (the 0.x bma-sdk API-root form) instead of nesting the paths. The SDK does not read BMA_BASE_URL itself; the example passes it through. A TokenSource (for example StaticToken) carries its own channel URL.

A machine-scoped executor sets Options.MachineID (empty reads BMA_MACHINE_ID; EnvironmentID and MachineID are alternatives) with the machine daemon token in EnvironmentKey, or uses a machine token through Options.TokenSource. Without a machine id the client falls back to the legacy machine token alias /api/v1/executors/token (/v1/executors/token is the environment key alias and answers a machine token 401). Go clients negotiate bma.executor.v1.1 by default (Options.Protocol).

A machine-scoped executor must declare process or agent

The platform binds a machine-scoped connection as the machine's runtime, and refuses the registration of an executor that advertises neither the process nor the agent capability: it answers executor.register, then closes with 4002 "runtime registration refused". The default Options.Capabilities (shell and files only) is such an executor. Declare process (and serve process.*) or agent (ServeAgent), and give Executor.Version as MAJOR.MINOR.PATCH:

core, _ := bmaexecutor.NewCore(bmaexecutor.CoreOptions{WorkRoot: dir})
_ = core.Register(bmaexecutor.NewProcessCapability(core, bmaexecutor.ProcessOptions{})) // advertises process.enabled
client, _ := bmaexecutor.NewClient(bmaexecutor.Options{
	TokenSource:  bmaexecutor.StaticToken(wsURL, machineToken), // or a token source that exchanges the machine token
	Executor:     bmaexecutor.ExecutorInfo{Name: "my-machine", OS: "linux", Arch: "arm64", Version: "1.0.0"},
	Capabilities: core.Capabilities(),
})
_ = core.Attach("cloud", client)
_, _ = client.Start(ctx)
if err := client.WaitReady(ctx); err != nil { // registered and still open one heartbeat later
	log.Fatal(err)
}

The SDK treats this as a configuration error: after 3 registrations in a row refused right after executor.register (close 4002 "runtime registration refused", or an executor.register error capability_unavailable / invalid_params), the client ends and Done closes with Err() wrapping ErrRegistrationRefused; other 4002 closes (for example "daemon runtime ended") reconnect as before. State() is ready as soon as executor.register returns, which a refused registration also does; WaitReady(ctx) returns only after the registration stayed open for one heartbeat interval, or with the error of a client that ended.

Executor types follow one mapping: required members are values, optional members are values with omitempty (named structs and nullable members are pointers), enums are untyped constants (Code* error codes on RPCError.Code), and opaque payloads such as ToolCallParams.Input stay json.RawMessage. Tool handlers receive the decoded per-tool input (BashInput, ReadInput, ...) through client.Tools.<Name>.Handle; return TextOutput, BashResult{...}.Output() (rendered like Core: stdout, stderr, exit_code: N) or a ToolOutput, NewToolError(text) for a tool-level error the model sees (is_error: true), any other error for outcome: "failed". The harness calls them as session.Tools.Bash.Call(ctx, BashInput{Command: "ls"}, CallToolOptions{}). Other protocol methods are typed too: Requests.ProcessStart.Handle(client, fn), Calls.SessionEvent.Call(ctx, client, params), Notifications.ToolProgress.Notify(ctx, client, params) (tables generated from the contract by tools/gen_methods.py).

Lifecycle, cancellation, and results
  • tool.cancel from the harness cancels the context.Context passed to the tool handler. The client responds {"canceled":true} and reports the result with outcome: "canceled"; handlers must stop their process group when the context is done.
  • A repeated tool.call with the same tool_call_id is acknowledged but not executed twice.
  • Call SessionReady after workspace and MCP setup, and SessionEnded after every child process and MCP server has stopped. The SDK does not infer these transitions because only the adapter knows when setup and cleanup finished.
  • tool.result is retried with exponential backoff on -32009 (executor_busy), -32004 (timeout), or data.retryable: true. Results are idempotent by tool_call_id. When every attempt fails, OnToolResultLost is called with the original result so the adapter can persist and replay it; the client never drops a result silently.
  • Large output is reported as artifact references, not base64 in tool.result: NewArtifactRef and NewArtifactContentBlock build the blocks for an artifact your own store holds; the SDK has no upload call, and Core truncates bash output over InlineResultBytes.
  • OpenMCPChannel opens the MCP channel for a session and server key and exchanges raw MCP JSON-RPC frames over whatever transport the control channel uses.
  • Session handler errors that are an *RPCError keep their code and data on the wire (for example retryable executor_busy).

Execution core: one hand, any brain

Core is the executor's execution core, independent of who drives it. core.Attach(brain, client) installs the session and tool handlers on a Client; attach one Client per harness, so one executor process serves the BMA cloud and a local harness at the same time:

core, _ := bmaexecutor.NewCore(bmaexecutor.CoreOptions{WorkRoot: dir, MaxSessions: 8, MaxSessionsPerBrain: 4})
_ = core.Register(bmaexecutor.NewProcessCapability(core, bmaexecutor.ProcessOptions{}))
cloud, _ := bmaexecutor.NewClient(bmaexecutor.Options{EnvironmentKey: key, EnvironmentID: env, Executor: info, Capabilities: core.Capabilities()})
local, _ := bmaexecutor.NewClient(bmaexecutor.Options{EnvironmentID: "local", Executor: info, Capabilities: core.Capabilities(),
	TokenSource: bmaexecutor.StaticToken("ws://127.0.0.1:7777", localToken)})
_ = core.Attach("cloud", cloud)
_ = core.Attach("local", local)
  • Tools: bash (login shell in its own process group; env limited to PATH/HOME/USER/LANG/TMPDIR plus request env and CoreOptions.Env; tool.cancel, the deadline, timeout_ms and session.stop kill the whole group; a non-zero exit is a succeeded call reporting exit_code; CoreOptions.Launch, the same hook type as ProcessOptions.Launch, may wrap or refuse each bash command, also those of LocalToolRoute and ACPAgent) and read/write/edit/glob/grep, confined to the session workspace WorkRoot/<brain>/<session> (override with CoreOptions.Workspace) through an os.Root: .., absolute paths outside it and symbolic links leading out of it are refused, also when swapped in after a check; CoreOptions.FileAccess lets the host refuse a file tool call (read-only session, protected path, revoked grant) with a reason before it runs. Other tools return capability_unavailable.
  • Capabilities: core.Register(cap) before Attach adds methods behind capability bits; core.Capabilities() advertises them. NewProcessCapability(core, ProcessOptions{...}) serves process.* (PTY where supported; FileTransfer and GitCredentials hooks enable those process.start fields; Launch chooses the directory, wraps argv in a sandbox or refuses a command process or package install with a data.reason; SessionFiles syncs per-session files under a declared session_files.root, see session context); NewSkillInstallCapability(installer) serves skill.install; NewTerminals(TerminalOptions{...}) serves terminal.* on a machine-scoped executor (Capability() to register, Close() on shutdown): PTYs (ConPTY on Windows) with a 1 MiB resume buffer, one writer lease and the bma.terminal.v1 host socket of each attach; Launch chooses the directory, wraps the shell in a sandbox or refuses the open; implement Capability for your own methods. A SessionScoped capability gets the brain's *CoreSession and OnSessionEnd runs before session.ended.
  • Private environment: CoreOptions.DenyEnv names executor-private variables (for example machine tokens) that no bash tool, process, terminal or stdio MCP server inherits and no request may set.
  • stdio MCP: every session.assign.mcp_servers[] entry with connection_origin: environment starts one process per (brain, session, server_key), verifies command_sha256 when given, runs the command without a shell with only its configured transport.env plus transport.secret_env (server-resolved secret values, advertised as capabilities.mcp.secret_env, injected into that process only; nothing is inherited from the executor; a secret: value left in env, a loader variable or a DenyEnv name fails session.assign with invalid_params), and bridges stdin/stdout lines to that server's MCP channel. If either side ends both are restarted, until the session ends, with jittered exponential backoff capped at 30s (reset once a channel stays open for 1s); after 5 consecutive failures the core sends session.status error / mcp_unavailable: <key> once per outage and keeps retrying.
  • Isolation: sessions are keyed by (brain, session_id); a tool.call reaches only sessions its own brain assigned; MCP channels and workspaces are per brain and session. Bash is not a sandbox: every brain runs as the executor's OS user, so only attach brains you trust with this machine (or confine bash with CoreOptions.Launch).
  • Capacity: MaxSessions (default 16) across brains and MaxSessionsPerBrain (default MaxSessions) per brain. A full core answers session.assign with executor_busy (-32009, retryable: true).

Harness quick start

Harness is the harness ("brain") end: an http.Handler that accepts executor control and MCP channels, plus the API that drives them. It speaks the same protocol as the BMA service, so an executor cannot tell them apart.

harness := bmaexecutor.NewHarness(bmaexecutor.HarnessOptions{
	Authenticate: authenticate, // func(*http.Request) (bmaexecutor.Principal, error); nil only on loopback
})
go http.Serve(listener, harness)

executor, _ := harness.WaitExecutor(ctx)
session, _ := executor.AssignSession(ctx, bmaexecutor.SessionAssignParams{SessionID: "sess_1"})
_ = session.Ready(ctx)
result, _ := session.CallTool(ctx, bmaexecutor.ToolCallParams{
	Tool: bmaexecutor.ToolNameBash, Input: bmaexecutor.NewToolInput(bmaexecutor.ToolInput{Command: "ls"}),
})
mcp, _ := session.MCP(ctx, "echo") // raw MCP JSON-RPC: Write/Read
_ = session.Stop(ctx, "done")
  • Authenticate sees every upgrade (control and MCP). A returned Principal.ExecutorID pins the identity: resume.executor_id must match and only that executor may open MCP channels for its sessions.
  • CallTool is idempotent by tool_call_id (generated when empty): a repeat joins the in-flight call or returns the recorded result. Canceling its context stops waiting only; CancelTool sends tool.cancel.
  • Resume: a disconnected executor keeps its sessions and pending calls for LeaseTTL (default 60s). A newer connection replaces the old one with close code 4004. Lease expiry, executor.close or a dropped session fails pending calls with ErrToolOutcomeUnknown: the tool may or may not have run.
  • Pending calls live in harness memory; there is no durable result store.

Local socket and in-process transports

Options.Dial defaults to WebSocket on ws://, wss://, unix:///path.sock or npipe:////./pipe/<name> (Windows; ListenNamedPipe, NamedPipeListener, NamedPipeDialer).

Shape Executor Harness
Executor dials a local harness StaticToken("ws://127.0.0.1:port", token) or StaticToken("unix:///path.sock", token) (UnixSocketDialer(path)) or StaticToken("npipe:////./pipe/<name>", token) (NamedPipeDialer(name)) http.Serve(listener, harness) on a TCP or unix listener
Harness dials the executor (executor listens) dial, closeFn, _ := ListenUnixSocket(path, token) → Options.Dial: dial (0700 directory, 0600 socket, bearer token) harness.DialExecutor(ctx, path, token); the harness also dials the sessions' MCP channels
Same process Options.Dial: InProcessDialer(harness, principal) Harness.ServeConn (used by InProcessDialer)

Details and authentication rules: local connection.

Agent executors

An executor that runs its own model loop and tools (for example a desktop app) serves the agent capability: the platform sends natural-language turns, the executor streams Anthropic Managed Agents events back.

client.ServeAgent(myAgent, bmaexecutor.AgentCapability{
	Models:          []bmaexecutor.AgentModel{{ID: "my-model", ThinkingLevels: []string{"low", "high"}}},
	PermissionModes: []string{"default", "accept_edits"},
})

myAgent implements AgentHandler: OpenTurn reports the effective configuration, RunTurn does the work with turn.Emit (durable events), turn.Delta (streaming previews), turn.Inputs() (turn.input) and turn.RequestInteraction (approvals and questions), and CloseSession releases the local conversation. The SDK assigns event ids and sequences, resends unacknowledged events after a reconnect, and frames every turn with session.status_running and a final session.status_idle whose turn_outcome is completed, canceled or failed.

The harness side is HarnessOptions.Agent (AgentPlatform) plus Executor.StartTurn, SendTurnInput, CancelTurn, CloseAgentSession and RespondInteraction. The BMA platform side is in preview: the binding of an agent to the machine is made by the BMA team (the public /v1 API has no route for it yet); its sessions accept text input only. See agent capability.

Writing your own brain or hands (Go, ADR-0029)

A third-party brain implements AgentHandler and depends on this SDK and the contract only; a third-party hands is a Core (or your own tool handlers) behind a Client. Minimal, runnable skeletons: examples/third-party-brain and examples/third-party-hand, each with tests that run it against the SDK's Harness and against the tool route conformance suite.

The brain's tools go through AgentTurn.Tools():

func (b myBrain) RunTurn(ctx context.Context, turn *bmaexecutor.AgentTurn) error {
	tools := turn.Tools() // nil: the hands are this machine - run your tools yourself
	if tools == nil { /* local */ }
	id := turn.ApprovalID(callID) // deterministic across reconnects and restarts
	answer, _ := turn.RequestInteraction(ctx, bmaexecutor.InteractionRequestParams{InteractionID: id, /* ... */})
	res := tools.Call(ctx, bmaexecutor.RouteCall{ID: callID, Name: "bash", Input: input, ApprovalID: answer.InteractionID})
	// res.Outcome: RouteOutcomeExecuted | RouteOutcomeNotForwarded | RouteOutcomeUnknown
	return nil
}

Declare AgentCapability.PlatformCredentials: []string{bmaexecutor.PlatformCredentialBrainTools} so the platform may give this machine a session whose hands are elsewhere. With the platform's tools endpoint in turn.start metadata, Tools() is a PlatformToolRoute (every call goes through the platform's tool gateway; the token stays in memory and is refreshed with tools_token.refresh); a half credential gives a route that refuses every call (tools_unavailable), never a local run. NewPlatformToolRoute builds the same route from a credential you manage yourself. Every call needs a unique RouteCall.ID: it is the idempotency identity, so a call asked again after a restart is answered with the first result (Replayed) instead of running twice, and an outcome of unknown means it may have run.

A hands' owner chooses what may use the machine: Options.Labels (placement filters, never an authorization) and Options.RemoteBrain (off by default; the platform cannot enable it).

LocalToolRoute is the same route for the case where the hands are this machine (Tools() is nil there): NewLocalToolRoute(LocalToolRouteOptions{Core, StateDir, SessionID, TurnID, Workspace, ...}) runs the six tools in a Core behind the executor's own gate, which is what the platform's gateway does for a remote machine: a call after its turn ended is stale_turn, deny is permission_denied, an ask tool needs the user's allow for this very call (record it with RecordApproval after RequestInteraction; without one approval_required, for another tool, input or approval id approval_invalid), and a call id runs at most once, across executor restarts too (state under StateDir; a call whose result was lost with the process answers outcome_unknown). ACPAgent uses this route for its own local turns; ACPAgentOptions.ToolPolicy is the host's ceiling on tool permissions (deny over ask over allow) that the platform's tool_policy and the mode can only tighten.

Testing a route: the conformance suite

Package conformance holds the tool route conformance suite (cases T1–T11, ADR-0029 §5). One set of cases, run against every route, so that a brain cannot tell which one its calls took. Run it in the tests of your own brain or hands:

import "github.com/beeos-ai/bma-executor-sdk/conformance"

func TestMyHandsConformToTheGateway(t *testing.T) {
	conformance.RunToolRouteConformance(t, conformance.PlatformFactory(func(t *testing.T, turn context.Context) (gatewaystub.Hands, string) {
		// your hands: run a call that passed the gateway, in the returned directory
	}))
}

RunToolRouteConformance(t, factory) takes a Factory that builds a Rig (your route and the levers the cases pull: the user's approval, a restart, a newer epoch, a cancel, offline hands). conformance.PlatformFactory builds the SDK's PlatformToolRoute against conformance/gatewaystub, a contract double of the platform's tool gateway (token and epoch, policy, one-time approval, idempotency, three outcomes, background bash), with hands you choose (conformance.CoreHands runs the calls in a Core: examples/third-party-hand). examples/third-party-brain runs the route a brain gets from AgentTurn.Tools(). The SDK runs it against its own two routes in toolroute_conformance_test.go. The packages import package testing and are for tests only: production code must not import them (arch_test.go checks the SDK's own), and they are not built on Windows (the cases start POSIX commands).

Brain and hands on different machines, and Claude Code (Go)

Brain host and adapters. BrainHost (Go) is the one implementation of the platform semantics of a local brain: turns and their single terminal state, deterministic approval ids and platform interactions, tool policy, the tool route, host tools and custom tools, CMA events, stop codes, user images, the resume ledger and resident sessions. A BrainAdapter only drives one kind of brain process (start and self-check, open / resume / suspend / close a conversation, hand it an input, report what it does through a BrainSink); what differs between brains is stated by its BrainCapabilities (model credentials, model choice and thinking levels, images, host tools, custom tools, input skills), and the host never asks which brain it hosts (a test fails when the host's source names one). NewBrainHost(ctx, adapter, opts) hosts any adapter; NewACPAgent is a BrainHost with the adapter of ACPAgentOptions.Profile, and ACPAgent is the same type.

Claude Code (ACPAgentOptions.Profile: bmaexecutor.ACPProfileClaudeCode, or NewClaudeCLIAdapter) drives the official claude binary directly, unmodified, over its stream-json input/output and control protocol: one claude -p process per conversation with --tools "" (no built-in tool), the platform tools and the turn's tools (host tools, custom tools, ask_user_question) on a loopback MCP server (--mcp-config, --strict-mcp-config), --setting-sources "", --permission-mode default, the platform's complete system prompt (--system-prompt), and every permission request (can_use_tool) answered by the host. The conversation id is a UUID v5 of the platform session id (--session-id, --resume after a restart; an unknown one is not created anew). The binary must be a pinned release, checked by claude --version and its sha256 (claudeCLIPins; ClaudeCLIOptions.Executable when Command is the owner's launcher of it); the system init message must list exactly the injected tools in the mode default. It uses only the node owner's own Claude credentials (their Claude Code login under HOME, or ANTHROPIC_API_KEY / a third-party provider's variables in ACPAgentOptions.Env); they never pass through BMA: no model proxy, no harness_model (model_credentials: owner). The models and effort levels are the ones the CLI reports at initialize (AgentHarnessCapability.models); a turn's model and thinking_level are checked against them and passed unchanged (--model, CLAUDE_CODE_EFFORT_LEVEL). User images go to the model as image blocks; turn.cancel is a control interrupt. Its stops follow the contract as for every brain (output_limit_reached without automatic continuation, model_stream_idle after a 90 s stall, no retry of a refused request, context_too_large). Tests use the pinned binary (tools/fetch_claude_cli.sh, checked against Anthropic's release manifest). See examples/local-dsh -profile claude-code.

Codex (ACPAgentOptions.Profile: bmaexecutor.ACPProfileCodex, or NewCodexAppServerAdapter) drives the official codex binary, unmodified, through its app server (codex app-server, JSON-RPC over stdio): one app server per conversation, a codex thread per platform session (thread/start, thread/resume after a restart; an unknown one is not created anew; executor_session_ref is the platform session id). The platform tools and the turn's tools are the thread's dynamic tools (codex fixes them when the thread starts: a later turn may offer fewer, never another), and every call comes to the host as item/tool/call, approved and run by it. ACPAgentOptions.Env must set CODEX_HOME to the BMA Codex home, a home of its own that holds nothing but the owner's login (CODEX_HOME=<home> codex login): a config.toml, AGENTS.md or hooks.json there is refused, since such a file adds MCP servers, hooks or instructions no command-line setting can take away. Every built-in tool (shell, apply_patch, web search, view image, sub-agents, apps, plugins, skills, hooks, memories) and injected instruction is turned off on the command line, and codex runs with its model catalog with each model's tool mode, apply_patch and extra tools cleared, so the model is offered exactly the host's tools, called directly; an item of a built-in tool or another server request ends the turn with agent_protocol_error. A project's AGENTS.md in the working directory is read as project instructions. Command is the pinned binary (codexPins, checked by codex --version and its sha256), optionally followed by -c settings of the owner's model provider (model_provider=…, model_providers.…). It uses only the owner's own credentials (model_credentials: owner); the models and reasoning efforts are those model/list reports, and a turn's model and thinking_level are passed unchanged (a turn without a level runs at the model's default). User images go to the model as input images; turn.cancel is turn/interrupt. Its stops follow the contract (output_limit_reached, model_stream_idle with one retry of a stream that stalled before any content, agent_auth_required at the first refused credential, context_too_large after one compaction). Tests use the pinned binary (tools/fetch_codex_cli.sh, checked against the digest GitHub publishes for the release asset). See examples/local-dsh -profile codex.

ACPAgent (Go) hosts an ACP agent process as the brain of a session. Its tool calls go through one seam, the tool route:

  • Hands on this machine (no tools_mcp_* in turn.start metadata): the call runs in this executor's Core, after the executor's own re-check (policy, approval, turn) and at most once.
  • Hands on another machine (turn.start metadata carries tools_mcp_url and tools_mcp_token, contract 1.4.0, handed only to an executor that declared ACPAgentOptions.PlatformTools): every call goes to the platform's tool gateway, which re-checks and runs it on the session's hands machine. The turn never falls back to this machine. The token lives in memory only, is replaced with tools_token.refresh before it expires (a failed refresh is logged and retried with backoff), and a refused token (an older epoch, expired) answers not_forwarded / stale_turn.

Both routes behave the same (the conformance suite, package conformance, runs T1–T11 against each). In particular bash: timeout is how long the call waits (default 120 s, at most 600 s, and at most 55 s per call); a command that outlives the wait keeps running and the call returns its pid and the file its output goes to (on_timeout: "kill" stops it instead). It ends when it exits, after 1 h, when its turn is canceled or runs out of time, or when the session closes.

Options.Labels and Options.RemoteBrain are the machine owner's local configuration (ExecutorInfo.labels, Capabilities.remote_brain). Labels only narrow where the platform may place sessions; RemoteBrain is off unless the owner turns it on here — it lets a brain on another machine use this one as its hands, and the platform has no way to switch it on.

User images. An image the user attached arrives as a file block (file_id, mime_type, size_bytes); ACPAgent downloads it and passes it to the agent as an ACP image content block when the agent's initialize declared promptCapabilities.image (bma-dsh-acp >= 0.2.2). It fetches the bytes with ACPAgentOptions.InputFiles, or, with PlatformTools, from the turn's tools endpoint (<tools_mcp_url without /mcp>/files/<file_id>/content, tools_mcp_token); file_inputs / image_inputs are declared only when both the agent and a file source exist. Limits are the Anthropic API's (png, jpeg, gif, webp; 5 MB; 8000 px longest side; 100 images per input; the bytes must be the declared type). An image that cannot be passed on ends the turn with a session.error instead of being dropped.

Model requests by session. With the DSH profile the agent's model requests go through a loopback proxy to the host's own endpoint (ACPAgentOptions.Upstream), which adds the host's credential (Upstream.Header). Set Upstream.SessionHeader to a header name and every forwarded request also carries the platform session id of its turn (turn.start session_id) under that name, so the endpoint can account the request to its session. The agent cannot set the value, and requests to the platform's own model endpoint (model_base_url) never carry it.

Slots and resident sessions. ACPAgentOptions.MaxSessions (default 8, declared as max_sessions) bounds the turns running at once; an idle session holds no slot. ACPAgentOptions.MaxResidentSessions (default 75 % of the Core's MaxSessions, at least MaxSessions) bounds the sessions whose agent session and Core session are held. Past it the least recently used idle session (not one with a bash command left running) is released with ACP session/close (the agent keeps its conversation, bma-dsh-acp its JSONL) and loaded again with session/load by its next turn; the platform keeps the session and its event numbering. A custom AgentHandler can do the same by implementing AgentSessionSuspender.

TypeScript and Python have no equivalent: they have no ACP host and no execution core, and no model_token.refresh client either; the generated types carry the 1.4.0 members (executor.labels, capabilities.remote_brain, tools_token.refresh) for code that sets or calls them by hand.

Examples

Run from the repository root:

Example What it shows Run
examples/local-brain a local harness with a scripted "model" drives Core over loopback: bash, then the stdio echo-mcp server through the MCP channel go run ./examples/local-brain
examples/cloud-hand the same Core as a hand for the BMA cloud harness BMA_BASE_URL=... BMA_ENVIRONMENT_ID=... BMA_ENVIRONMENT_KEY=... go run ./examples/cloud-hand -work-root ~/bma-work
examples/agentexecutor the agent capability against a simulated platform, including a dropped connection go run ./examples/agentexecutor
examples/third-party-brain the smallest brain: declares brain_tools, asks approval under AgentTurn.ApprovalID, sends the call through AgentTurn.Tools() to the platform's tool gateway BMA_MACHINE_TOKEN=... go run ./examples/third-party-brain -base-url ... -machine-id mch_...
examples/third-party-hand the smallest hands: Core with the process capability, Options.Labels, Options.RemoteBrain BMA_MACHINE_TOKEN=... go run ./examples/third-party-hand -base-url ... -machine-id mch_... -labels team-a -remote-brain
examples/sandboxed-folder a machine executor whose Launch hook reads the session context, checks the owner, picks the local folder for a metadata reference and wraps the command in macOS sandbox-exec BMA_BASE_URL=... BMA_MACHINE_TOKEN=... go run ./examples/sandboxed-folder -owner u_42 -folder ws_7=$HOME/projects/site

Tests

go vet ./... && go test -race ./...

The tests cover the conformance examples in contracts/bma/executor/examples, executor ↔ harness over every transport with reconnect and lease, Core, capabilities and the agent capability. The TypeScript and Python packages run interop suites against the Go peers in internal/interop.

Development

The executor contract snapshot and the generated types (generated.go, typescript/src/generated/executor.ts, python/src/bma_executor_sdk/generated.py) are generated in the BMA repository: make contract-sdk SDK_DIR=<this checkout>. tools/check_contract.py verifies them against contracts/bma/executor/lock.json; --source <beeos-managed-agents checkout> also compares the snapshot with BMA.

python3 tools/check_contract.py [--source ../beeos-managed-agents]
go vet ./... && go test -race ./...
(cd python && uv sync && uv run pytest -q)                        # interop tests need Go
(cd typescript && npm ci && npm run build && npm test)            # Go + Python interop

Release

One tag v<version> releases all three languages at the same version: it must be on main and match typescript/package.json and python/pyproject.toml. release.yaml first runs ci.yaml, then publishes.

Channel Publishes Credentials
Go nothing; the module comes from the tag none
npm @beeos-ai/bma-executor-sdk with provenance secret NPM_TOKEN in the releases environment
PyPI bma-executor-sdk a PyPI Trusted Publisher on bma-executor-sdk: owner beeos-ai, repository bma-executor-sdk, workflow release.yaml, environment releases

License

Apache License 2.0. See LICENSE and NOTICE.

Input-scoped selected skills (executor contract 1.5.0)

An agent opts in with input_skills: true only after implementing exact skill-byte installation and input-bound receipts. A request then carries config.input_skills; the handler returns effective.input_skill_receipt identifying the opening input and every applied skill ID, frozen revision and SKILL.md byte hash. Installing the selection must not change the next input's default context. The platform must validate current grants and frozen versions before dispatch, then compare and persist the returned receipt.

Without the capability, all three SDK runtimes reject a valid selection before invoking the handler. Malformed or empty selections and caller-supplied effective receipts (including JSON null) are invalid parameters. These checks establish transport behavior; they do not load skills or validate product authorization for a host.

Before scheduling work, each SDK compares the applied receipt with the opening input and ordered selected revisions/hashes; a missing or mismatched receipt prevents execution. Cached turn-start replays undergo the same check. Another input cannot join a selected-skill turn, while replay of the opening input is still acknowledged. Refused preparation also settles the turn completion signal, allowing concurrent session closure to finish.

Documentation

Overview

Package bmaexecutor implements the BMA Executor Protocol (bma.executor.v1.1, generated from contracts/bma): the executor end (Client: token bootstrap, pluggable transport, JSON-RPC 2.0, registration, heartbeat, reconnect with resume, dispatch, tool cancellation, retried results, artifacts, MCP channel), the execution Core with registrable capabilities (process.*, skill.install, ...), and the harness end (Harness).

Index

Constants

View Source
const (
	// ACPProfileDSH is bma-dsh-acp (ADR-0027), the default.
	ACPProfileDSH = "dsh"
	// ACPProfileClaudeCode is the official claude CLI, unmodified, driven
	// directly (brain_claude_cli.go); Command[0] is the pinned binary. It uses
	// only the node owner's own Claude credentials and never the platform's
	// model endpoint. A host whose Command is the owner's launcher of that
	// binary uses NewBrainHost with NewClaudeCLIAdapter(ClaudeCLIOptions{Executable}).
	ACPProfileClaudeCode = "claude-code"
	// ACPProfileCodex is the official codex CLI, unmodified, driven through
	// its app server (brain_codex_app_server.go); Command[0] is the pinned
	// binary and ACPAgentOptions.Env sets CODEX_HOME to the BMA Codex home
	// the owner signed in to. It uses only the owner's own credentials.
	ACPProfileCodex = "codex"
)

ACP profiles: which brain NewACPAgent hosts.

View Source
const (
	BrainKindMessage  = "message"
	BrainKindThinking = "thinking"
)

Kinds of brain text.

View Source
const (
	BrainAllow    = "allow"
	BrainDeny     = "deny"
	BrainCanceled = "canceled"
)

BrainDecision outcomes.

View Source
const (
	// DefaultACPCancelGrace is how long a canceled turn waits for the brain
	// to end the input before its process is killed.
	DefaultACPCancelGrace = 10 * time.Second
	// DefaultACPKillGrace is the wait between SIGTERM and SIGKILL of the brain's process group.
	DefaultACPKillGrace = 3 * time.Second
	// DefaultACPMaxSessions bounds the running turns of one host.
	DefaultACPMaxSessions = 8
	// DefaultACPResidentSessions is the share of the Core's MaxSessions (in
	// percent) that resident sessions may use by default; the rest stays for
	// sessions assigned to the Core as hands.
	DefaultACPResidentSessions = 75

	// PlatformCredentialHarnessModel is the agent capability's
	// platform_credentials entry for the per-turn model endpoint and token
	// (turn.start metadata model_base_url, model_token, model_token_expires_at).
	PlatformCredentialHarnessModel = "harness_model"
	// PlatformCredentialBrainTools is the platform_credentials entry for the
	// per-turn tools endpoint and token (turn.start metadata tools_mcp_url,
	// tools_mcp_token, tools_mcp_token_expires_at), contract 1.4.0.
	PlatformCredentialBrainTools = "brain_tools"
	// PlatformCredentialPlatformTools is the platform_credentials entry for
	// the platform's web tools of a brain that runs its tools here (turn.start
	// config.platform_tools with metadata platform_tools_mcp_url,
	// platform_tools_mcp_token, platform_tools_mcp_token_expires_at),
	// contract 2.4.0.
	PlatformCredentialPlatformTools = "platform_tools"
)
View Source
const (
	// BrainModelPlatform: the brain's model requests go through the host's
	// route (the platform's per-turn credential, or the node owner's Upstream).
	BrainModelPlatform = "platform"
	// BrainModelOwner: the brain uses only its node owner's own credentials;
	// the host never hands it the platform's (no harness_model).
	BrainModelOwner = "owner"
)

Model credential kinds (BrainCapabilities.ModelCredentials).

View Source
const (
	// MachineIDEnv is the environment variable that carries the machine id of
	// a machine-scoped executor (injected by the machine pool template).
	MachineIDEnv = "BMA_MACHINE_ID"

	// DefaultBaseURL is the executor origin of the hosted deployment.
	DefaultBaseURL        = "https://executor.beeos.ai"
	DefaultRequestTimeout = 30 * time.Second
	// DefaultMaxReconnectAttempts is 0: reconnect until Stop, as gRPC's
	// connection backoff and long-running agents (GitHub Actions runner,
	// Buildkite agent) do.
	DefaultMaxReconnectAttempts = 0
	DefaultReconnectBaseDelay   = time.Second
	// DefaultToolResultRetryAttempts is the total number of tool.result attempts.
	DefaultToolResultRetryAttempts = 5
	// DefaultToolResultRetryBaseDelay is the first retry backoff for tool.result.
	DefaultToolResultRetryBaseDelay = 250 * time.Millisecond
)
View Source
const (
	DefaultCoreMaxSessions       = 16
	DefaultCoreMaxMCPServers     = 4
	DefaultCoreBashTimeout       = 10 * time.Minute
	DefaultCoreMaxOutputBytes    = 1024 * 1024
	DefaultCoreInlineResultBytes = 48 * 1024
)
View Source
const (
	FileOperationRead  = "read"
	FileOperationWrite = "write"
)

File operations a FileAccessFunc is asked about.

View Source
const (
	SessionMountUploads = "uploads"
	SessionMountSkills  = "skills"
	SessionMountOutputs = "outputs"
	SessionMountMemory  = "memory"
)

The mounted directories of a session.

View Source
const (
	DesktopScaleMin = 100
	DesktopScaleMax = 400
)

The scale a resize may carry (devicePixelRatio × 100): 1× to 4×.

View Source
const (
	AgentErrorCodeOutputLimitReached      = "output_limit_reached"
	AgentErrorCodeContextTooLarge         = "context_too_large"
	AgentErrorCodeModelStreamIdle         = "model_stream_idle"
	AgentErrorCodeAgentError              = "agent_error"
	AgentErrorCodeAgentUnavailable        = "agent_unavailable"
	AgentErrorCodeAgentAuthRequired       = "agent_auth_required"
	AgentErrorCodeAgentProtocolError      = "agent_protocol_error"
	AgentErrorCodeModelOverloadedError    = "model_overloaded_error"
	AgentErrorCodeModelRateLimitedError   = "model_rate_limited_error"
	AgentErrorCodeModelRequestFailedError = "model_request_failed_error"
	AgentErrorCodeBillingError            = "billing_error"
)

AgentErrorCode values. Stop code table: the error types an agent executor reports for a turn that ended failed, so every agent (Go ACP harness, brain hosts, local desktop agents) says the same thing for the same cause. output_limit_reached: the model reply was cut at its output-token limit (ACP stopReason max_tokens, DSH max-tokens, finish_reason length). context_too_large: the conversation does not fit the model context window even after compaction. model_stream_idle: the model stream sent no data for the idle limit (default 90 s). agent_error: any other failure of the agent. agent_unavailable: the agent process is gone or did not answer a cancel in time. agent_auth_required: the agent needs credentials it does not have. agent_protocol_error: the agent rejected the request as malformed or unsupported. The model endpoint failed the turn's model request (no more retries): model_overloaded_error: it answered 5xx or 529, or was unreachable; model_rate_limited_error: it answered 429; billing_error: it answered 402 (the account has no credit); model_request_failed_error: it refused the request otherwise (any other 4xx, including 401/403 for a rejected credential). These four are official session.error types and are projected as themselves. A code is the type of session.error; an executor whose SDK cannot set the type yet (structured_errors false) puts it first in the message as '<code>: <detail>', and the platform reads both forms. The platform keeps the code in error.code and projects a type outside the official session.error union to unknown_error; a platform may map a code to an official type itself (context_too_large to compaction_limit_reached_error, ADR-0010). Executors report only these values; a new cause adds a value here first.

View Source
const (
	AgentEventTypeAgentMessage         = "agent.message"
	AgentEventTypeAgentThinking        = "agent.thinking"
	AgentEventTypeAgentToolUse         = "agent.tool_use"
	AgentEventTypeAgentToolResult      = "agent.tool_result"
	AgentEventTypeAgentCustomToolUse   = "agent.custom_tool_use"
	AgentEventTypeAgentMcpToolUse      = "agent.mcp_tool_use"
	AgentEventTypeAgentMcpToolResult   = "agent.mcp_tool_result"
	AgentEventTypeSessionStatusRunning = "session.status_running"
	AgentEventTypeSessionStatusIdle    = "session.status_idle"
	AgentEventTypeSessionError         = "session.error"
)

AgentEventType values. Durable events an agent executor emits with session.event. Names and members follow Anthropic Managed Agents session events. user.* events are written by the platform, never by the executor.

View Source
const (
	AgentInputBlockTypeText     = "text"
	AgentInputBlockTypeFile     = "file"
	AgentInputBlockTypeInputRef = "input_ref"
)

AgentInputBlockType values. Agent input block type. input_ref (contract 1.7.0) stands for a whole input the platform did not inline; see AgentInputBlock.

View Source
const (
	ChannelControl = "control"
	ChannelMCP     = "mcp"
)

ChannelScope values. Channels a short-lived executor JWT may open.

View Source
const (
	ComputerActionClick          = "click"
	ComputerActionType           = "type"
	ComputerActionKey            = "key"
	ComputerActionScroll         = "scroll"
	ComputerActionDrag           = "drag"
	ComputerActionMouseMove      = "mouse_move"
	ComputerActionHoldKey        = "hold_key"
	ComputerActionWait           = "wait"
	ComputerActionBatch          = "batch"
	ComputerActionClipboardRead  = "clipboard_read"
	ComputerActionClipboardWrite = "clipboard_write"
)

ComputerAction values. Input actions accepted by the computer_action tool. mouse_move, hold_key, wait and batch are contract 1.17.0 (additive); clipboard_read and clipboard_write are contract 1.24.0 (additive).

View Source
const (
	ConnectionStateDisconnected = "disconnected"
	ConnectionStateConnecting   = "connecting"
	ConnectionStateRegistered   = "registered"
	ConnectionStateReady        = "ready"
	ConnectionStateDraining     = "draining"
	ConnectionStateClosed       = "closed"
)

ConnectionState values. Executor control channel state machine.

View Source
const (
	ContentBlockTypeText     = "text"
	ContentBlockTypeImage    = "image"
	ContentBlockTypeResource = "resource"
	ContentBlockTypeArtifact = "artifact"
)

ContentBlockType values. Tool result content block type.

View Source
const (
	EventDeltaTypeAgentMessage  = "agent.message"
	EventDeltaTypeAgentThinking = "agent.thinking"
)

EventDeltaType values. Durable event type a streaming preview belongs to.

View Source
const (
	FileTransferUpload   = "upload"
	FileTransferDownload = "download"
)

FileTransferDirection values. File transfer direction relative to the machine.

View Source
const (
	InteractionCancelReasonResolvedLocally = "resolved_locally"
	InteractionCancelReasonTurnCanceled    = "turn_canceled"
	InteractionCancelReasonExpired         = "expired"
	InteractionCancelReasonToolCanceled    = "tool_canceled"
)

InteractionCancelReason values. Why the executor withdrew an open interaction.

View Source
const (
	InteractionKindPermission = "permission"
	InteractionKindQuestion   = "question"
)

InteractionKind values. Interaction kinds; they map 1:1 to platform agent interactions.

View Source
const (
	InteractionOutcomeAllow    = "allow"
	InteractionOutcomeDeny     = "deny"
	InteractionOutcomeAnswered = "answered"
	InteractionOutcomeExpired  = "expired"
	InteractionOutcomeCanceled = "canceled"
)

InteractionOutcome values. How the platform resolved an interaction. allow/deny answer permission, answered answers question, expired and canceled close either kind without an answer.

View Source
const (
	InteractionScopeOnce    = "once"
	InteractionScopeSession = "session"
)

InteractionScope values. How long a permission grant lasts: this tool use only, or the rest of the session. A session grant is recorded by the platform (the single source) under a grant id (tgr_...) with a rule: the tool and, for the shell tool, the program of a simple command or one exact command. Later permission requests of the same session that a grant's rule covers are answered allow by the platform without asking (responder platform), whichever executor or brain asks, until the grant is revoked by its id; the executor may also apply it locally.

View Source
const (
	CodeParseError            = -32700
	CodeInvalidRequest        = -32600
	CodeMethodNotFound        = -32601
	CodeInvalidParams         = -32602
	CodeInternalError         = -32603
	CodeUnauthorized          = -32000
	CodeForbidden             = -32001
	CodeNotFound              = -32002
	CodeLeaseExpired          = -32003
	CodeTimeout               = -32004
	CodeCanceled              = -32005
	CodePayloadTooLarge       = -32006
	CodeSessionNotActive      = -32007
	CodeMCPUnavailable        = -32008
	CodeExecutorBusy          = -32009
	CodeUnsupportedProtocol   = -32010
	CodeResourceUnavailable   = -32011
	CodeCapabilityUnavailable = -32012
	CodeConflict              = -32013
)

JSONRPCErrorCode values. Executor protocol JSON-RPC error codes. -32011..-32013 are v1.1 additions.

View Source
const (
	MCPConnectionOriginService     = "service"
	MCPConnectionOriginEnvironment = "environment"
)

MCPConnectionOrigin values. Who connects the MCP server. environment means the executor starts/connects it; service means the harness connects.

View Source
const (
	MCPTransportTypeStdio = "stdio"
	MCPTransportTypeHttp  = "http"
)

MCPTransportType values.

View Source
const (
	PackageManagerApt = "apt"
	PackageManagerPip = "pip"
	PackageManagerNpm = "npm"
)

PackageManager values. Package manager for process.start package_install.

View Source
const (
	PermissionModeAlwaysAllow = "always_allow"
	PermissionModeAlwaysAsk   = "always_ask"
)

PermissionMode values. Tool permission mode; always_ask means the harness already resolved approval.

View Source
const (
	ProcessRunning = "running"
	ProcessExited  = "exited"
	ProcessFailed  = "failed"
	ProcessKilled  = "killed"
)

ProcessStateName values. Process state (v1.1 §3.3).

View Source
const (
	StreamStdout = "stdout"
	StreamStderr = "stderr"
)

ProcessStream values. Process output stream (v1.1 §3.2).

View Source
const (
	ProtocolV1  = "bma.executor.v1"
	ProtocolV11 = "bma.executor.v1.1"
)

ProtocolVersion values. Value of both the WebSocket subprotocol and executor.register protocol. A v1.1 server serves v1 executors and never sends them v1.1 methods.

View Source
const (
	SessionEventTypeAgentToolResult      = "agent.tool_result"
	SessionEventTypeAgentMessage         = "agent.message"
	SessionEventTypeAgentThinking        = "agent.thinking"
	SessionEventTypeAgentToolUse         = "agent.tool_use"
	SessionEventTypeAgentCustomToolUse   = "agent.custom_tool_use"
	SessionEventTypeAgentMcpToolUse      = "agent.mcp_tool_use"
	SessionEventTypeAgentMcpToolResult   = "agent.mcp_tool_result"
	SessionEventTypeSessionStatusRunning = "session.status_running"
	SessionEventTypeSessionStatusIdle    = "session.status_idle"
	SessionEventTypeSessionError         = "session.error"
)

SessionEventType values. Durable event types an executor may emit. Event names follow Anthropic Managed Agents; the executor must not invent new names. A tool executor emits agent.tool_result only; an agent executor (capability agent) emits every type, shaped as schemas/agent.json AgentEvent.

View Source
const (
	SessionStatusStarting = "starting"
	SessionStatusRunning  = "running"
	SessionStatusIdle     = "idle"
	SessionStatusStopping = "stopping"
	SessionStatusStopped  = "stopped"
	SessionStatusError    = "error"
)

SessionStatus values. Lifecycle status reported by the executor.

View Source
const (
	StdinOpen   = "open"
	StdinClosed = "closed"
)

StdinMode values. process.start stdin mode. Empty or "closed" closes stdin at start; "open" keeps it open for process.write.

View Source
const (
	StopReasonTypeEndTurn          = "end_turn"
	StopReasonTypeRetriesExhausted = "retries_exhausted"
)

StopReasonType values. Anthropic stop_reason types an executor may report. requires_action is not in the list: the platform projects it from open interactions.

View Source
const (
	TerminalFrameTypeAttach   = "attach"
	TerminalFrameTypeAttached = "attached"
	TerminalFrameTypeOutput   = "output"
	TerminalFrameTypeGap      = "gap"
	TerminalFrameTypeAck      = "ack"
	TerminalFrameTypeInput    = "input"
	TerminalFrameTypeResize   = "resize"
	TerminalFrameTypeResized  = "resized"
	TerminalFrameTypeClose    = "close"
	TerminalFrameTypeExit     = "exit"
	TerminalFrameTypeClosed   = "closed"
	TerminalFrameTypeError    = "error"
)

TerminalFrameType values. Frame discriminator. Receivers ignore frames of unknown type except as noted (the reference relay answers an unknown type with error terminal_invalid_frame).

View Source
const (
	ToolNameBash            = "bash"
	ToolNameRead            = "read"
	ToolNameWrite           = "write"
	ToolNameEdit            = "edit"
	ToolNameGlob            = "glob"
	ToolNameGrep            = "grep"
	ToolNameListFiles       = "list_files"
	ToolNameComputerObserve = "computer_observe"
	ToolNameComputerAction  = "computer_action"
)

ToolName values. Built-in tool names. bmad serves bash only and answers -32012 for the rest.

View Source
const (
	ToolOutcomeSucceeded = "succeeded"
	ToolOutcomeFailed    = "failed"
	ToolOutcomeCanceled  = "canceled"
)

ToolOutcome values. Tool outcome.

View Source
const (
	TurnOutcomeCompleted = "completed"
	TurnOutcomeCanceled  = "canceled"
	TurnOutcomeFailed    = "failed"
)

TurnOutcome values. BMA extension on session.status_idle: how the turn ended.

View Source
const (
	MethodScreenStart                = "screen.start"
	MethodScreenStop                 = "screen.stop"
	MethodScreenLive                 = "screen.live"
	MethodScreenControl              = "screen.control"
	MethodExecutorRegister           = "executor.register"
	MethodExecutorHeartbeat          = "executor.heartbeat"
	MethodExecutorTokenRefresh       = "executor.token.refresh"
	MethodExecutorCapabilitiesUpdate = "executor.capabilities.update"
	MethodExecutorDrain              = "executor.drain"
	MethodExecutorClose              = "executor.close"
	MethodSessionAssign              = "session.assign"
	MethodSessionReady               = "session.ready"
	MethodSessionEvent               = "session.event"
	MethodSessionStatus              = "session.status"
	MethodSessionStop                = "session.stop"
	MethodSessionEnded               = "session.ended"
	MethodToolCall                   = "tool.call"
	MethodToolResult                 = "tool.result"
	MethodToolCancel                 = "tool.cancel"
	MethodToolProgress               = "tool.progress"
	MethodProcessStart               = "process.start"
	MethodProcessRead                = "process.read"
	MethodProcessWrite               = "process.write"
	MethodProcessInterrupt           = "process.interrupt"
	MethodProcessTerminate           = "process.terminate"
	MethodProcessList                = "process.list"
	MethodProcessStatus              = "process.status"
	MethodTerminalOpen               = "terminal.open"
	MethodTerminalAttach             = "terminal.attach"
	MethodTerminalClose              = "terminal.close"
	MethodDesktopAttach              = "desktop.attach"
	MethodDesktopWallpaper           = "desktop.wallpaper"
	MethodSkillInstall               = "skill.install"
	MethodWorkspaceBackup            = "workspace.backup"
	MethodSessionFilesFlush          = "session_files.flush"
	MethodSessionFilesSync           = "session_files.sync"
	MethodTurnStart                  = "turn.start"
	MethodTurnInput                  = "turn.input"
	MethodTurnCancel                 = "turn.cancel"
	MethodSessionCompact             = "session.compact"
	MethodSessionCompactCancel       = "session.compact_cancel"
	MethodSessionClose               = "session.close"
	MethodSessionEventDelta          = "session.event_delta"
	MethodSessionHistory             = "session.history"
	MethodInteractionRequest         = "interaction.request"
	MethodInteractionResponse        = "interaction.response"
	MethodAgentCustomToolResult      = "agent.custom_tool_result"
	MethodInteractionCancel          = "interaction.cancel"
	MethodModelTokenRefresh          = "model_token.refresh"
	MethodToolsTokenRefresh          = "tools_token.refresh"
	MethodWorkingLogRead             = "working_log.read"
	MethodWorkingLogAppend           = "working_log.append"
)
View Source
const (
	DefaultHarnessHeartbeatInterval = 15 * time.Second
	DefaultHarnessLeaseTTL          = 60 * time.Second
)
View Source
const (
	// MaxProcessesPerSession bounds running processes; ended processes are
	// retained separately (see retainEndedLocked).
	MaxProcessesPerSession = 64
	ProcessBufferBytes     = 1024 * 1024
)

Process limits (v1.1 §1.3, §3). They match DefaultLimits.

View Source
const (
	// The referenced workspace is gone or its directory does not exist.
	ReasonWorkspaceUnavailable = "workspace_unavailable"
	// The request leaves what the executor's local policy allows.
	ReasonWorkspaceBoundary = "workspace_boundary"
	// The request writes where the local policy only allows reads.
	ReasonWorkspaceReadOnly = "workspace_read_only"
	// The session is not one this machine serves (an owner check failed).
	ReasonSessionRejected = "session_rejected"
	// The local user denied the access.
	ReasonLocalConfirmationDenied = "local_confirmation_denied"
	// Nobody answered the local confirmation in time.
	ReasonLocalConfirmationExpired = "local_confirmation_expired"
	// The process could not be started.
	ReasonSpawnFailed = "spawn_failed"
	// A process.start replay changed the spec of an existing process id.
	ReasonProcessIDSpecMismatch = "process_id_spec_mismatch"
)

Recommended error.data.reason values (contracts/bma README, open set): an executor that refuses a process.start or a tool.call answers with a JSON-RPC error whose data.reason is one of these, and BMA passes it to the tool result's error_code and the turn's session.error.code unchanged. Any other value is passed through as well. TypeScript ErrorReason and Python ErrorReason carry the same names and values.

View Source
const (
	// RouteOutcomeNotForwarded: the call was refused and certainly did not
	// run (policy, approval, a stale turn, hands offline); it is safe to ask
	// again, for example once approved.
	RouteOutcomeNotForwarded = "not_forwarded"
	// RouteOutcomeExecuted: the tool ran; RouteResult.IsError says whether the
	// tool itself failed.
	RouteOutcomeExecuted = "executed"
	// RouteOutcomeUnknown: the call may have run (the connection broke after
	// it was sent, the hands restarted); do not blindly run it again.
	RouteOutcomeUnknown = "unknown"
)

The three outcomes of a tool call, as the platform's tool gateway says them (ADR-0005).

View Source
const AgentSessionLostReason = "lease_expired"

AgentSessionLostReason is the reason AgentHandler.CloseSession gets for a session the executor gave up because the harness lease expired while it was disconnected (a sleeping laptop, a long network outage).

View Source
const ComputerActionMenu = "menu"

ComputerActionMenu runs an item of an app's menu bar by its labels (ComputerActionRequest.MenuPath, for example ["Window", "Weixin"]) in the window PID/WindowID names. Like open_app it is an action of the host tool only.

View Source
const ComputerActionOpenApp = "open_app"

ComputerActionOpenApp opens an app (ComputerActionRequest.App: a name or a bundle id) and brings it to the front. It is an action of the host tool computer_action of a local brain, not of the contract's ComputerAction enum.

View Source
const ComputerErrorWindowFrameRequired = "window_frame_required"

ComputerErrorWindowFrameRequired is the error code of a click, scroll or drag without pid and window_id while the session's last observation was a window: its coordinates would be read as screen pixels although the model looked at window pixels.

View Source
const DefaultACPSystemPrompt = "You are an agent running on the user's computer through BMA (BeeOS Managed Agents).\n" +
	"Your tools run on this computer, in the working directory %s; use paths under it.\n" +
	"Be concise. When a task is done, say what you did."

DefaultACPSystemPrompt is the base system prompt of a local brain; the agent definition's system instructions follow it.

View Source
const DesktopControlMethod = "screen.control"
View Source
const DesktopResizeTimeout = 15 * time.Second

DesktopResizeTimeout bounds the existing native desktop fit operation.

View Source
const DesktopTextMaxBytes = 1024

DesktopTextMaxBytes bounds one text event (UTF-8 bytes).

View Source
const EnvMemoryDir = "BMA_MEMORY_DIR"

EnvMemoryDir names <Root>/<agent session id>/memory in the environment of the processes of a session that mounts memory stores.

View Source
const (
	IOModePTY = "pty"
)

IOMode values. process.start io_mode. "pty" runs the command on a 24x80 pseudo-terminal: stdout is the PTY output, stdin writes go to the PTY and close_stdin is rejected. Requires process.pty.

View Source
const MaxFileTransferBytes = 1 << 30

MaxFileTransferBytes bounds one file transfer (v1.1 §6.2): 1 GiB.

View Source
const (

	// MaxTerminals is how many live terminals one executor serves.
	MaxTerminals = 16
)
View Source
const MetadataAgentSessionID = "agent_session_id"

MetadataAgentSessionID is the process.start metadata key naming the agent session a process runs for (the session SessionContext and SessionFiles look up).

View Source
const ScreenLiveMethod = "screen.live"
View Source
const (
	StderrMerge = "merge"
)

StderrMode values. process.start stderr mode. "merge" redirects stderr into stdout at the OS level so one cursor covers both.

View Source
const (
	// TerminalSubprotocol is the WebSocket subprotocol of terminal sockets.
	TerminalSubprotocol = "bma.terminal.v1"
)
View Source
const ToolNameAskUserQuestion = "ask_user_question"

ToolNameAskUserQuestion is the host tool of a local brain that asks the user (see agent_acp_host_tools.go).

Variables

View Source
var (
	// ErrNotConnected is returned when a call is attempted before the channel opens.
	ErrNotConnected = errors.New("bmaexecutor: executor channel is not connected")
	// ErrClientStopped is returned after Stop or a terminal close code.
	ErrClientStopped = errors.New("bmaexecutor: client stopped")
	// ErrReplaced is Err after the harness closed with 4004: a newer
	// connection for this executor is authoritative and this one must stop.
	ErrReplaced = errors.New("bmaexecutor: executor connection was replaced (4004)")

	// ErrReconnectExhausted is Err after a positive MaxReconnectAttempts
	// failed; it wraps the last failure.
	ErrReconnectExhausted = errors.New("bmaexecutor: executor reconnect attempts exhausted")
	// ErrCredentialRejected is wrapped by the token request error when the
	// token endpoint answers 401 or 403 (an invalid or revoked environment
	// key or machine token). A reconnect does not retry it: the client ends
	// with it as Err. A TokenSource may wrap it for the same effect.
	ErrCredentialRejected = errors.New("bmaexecutor: executor credential rejected")
	// ErrRegistrationRefused is Err after the platform refused the
	// executor's registration maxRefusedRegistrations times in a row: the
	// close 4002 "runtime registration refused" right after
	// executor.register, or an executor.register error for the executor's
	// capabilities. It is a configuration error (a machine-scoped executor
	// must declare the process or agent capability) that reconnecting
	// cannot fix. It wraps the last refusal.
	ErrRegistrationRefused = errors.New("bmaexecutor: executor registration refused")
)
View Source
var (
	// ErrSessionEnded is returned for requests on a session that has ended.
	ErrSessionEnded = errors.New("bmaexecutor: session ended")
	// ErrToolOutcomeUnknown means the executor was lost (lease expiry,
	// executor.close, session ended, or a restarted executor that no longer
	// reports the session) before a tool.result arrived. The tool may or may
	// not have run; the caller decides whether a retry is safe.
	ErrToolOutcomeUnknown = errors.New("bmaexecutor: tool outcome unknown: executor lost before tool.result")
	// ErrAssignRejected is returned when session.assign answers accepted=false.
	ErrAssignRejected = errors.New("bmaexecutor: executor rejected session.assign")
)
View Source
var Calls = struct {
	SessionReady       CallMethod[SessionReadyParams, Ack]
	SessionEvent       CallMethod[SessionEventParams, SessionEventResult]
	SessionEnded       CallMethod[SessionEndedParams, Ack]
	ToolResult         CallMethod[ToolResultParams, Ack]
	SessionHistory     CallMethod[SessionHistoryParams, SessionHistoryResult]
	InteractionRequest CallMethod[InteractionRequestParams, InteractionRequestResult]
	InteractionCancel  CallMethod[InteractionCancelParams, Ack]
	ModelTokenRefresh  CallMethod[ModelTokenRefreshParams, ModelTokenRefreshResult]
	ToolsTokenRefresh  CallMethod[ToolsTokenRefreshParams, ToolsTokenRefreshResult]
	WorkingLogRead     CallMethod[WorkingLogReadParams, WorkingLogReadResult]
	WorkingLogAppend   CallMethod[WorkingLogAppendParams, WorkingLogAppendResult]
}{
	SessionReady:       CallMethod[SessionReadyParams, Ack]{Method: "session.ready"},
	SessionEvent:       CallMethod[SessionEventParams, SessionEventResult]{Method: "session.event"},
	SessionEnded:       CallMethod[SessionEndedParams, Ack]{Method: "session.ended"},
	ToolResult:         CallMethod[ToolResultParams, Ack]{Method: "tool.result"},
	SessionHistory:     CallMethod[SessionHistoryParams, SessionHistoryResult]{Method: "session.history"},
	InteractionRequest: CallMethod[InteractionRequestParams, InteractionRequestResult]{Method: "interaction.request"},
	InteractionCancel:  CallMethod[InteractionCancelParams, Ack]{Method: "interaction.cancel"},
	ModelTokenRefresh:  CallMethod[ModelTokenRefreshParams, ModelTokenRefreshResult]{Method: "model_token.refresh"},
	ToolsTokenRefresh:  CallMethod[ToolsTokenRefreshParams, ToolsTokenRefreshResult]{Method: "tools_token.refresh"},
	WorkingLogRead:     CallMethod[WorkingLogReadParams, WorkingLogReadResult]{Method: "working_log.read"},
	WorkingLogAppend:   CallMethod[WorkingLogAppendParams, WorkingLogAppendResult]{Method: "working_log.append"},
}

Calls are the executor-to-harness requests a client sends: Calls.SessionEvent.Call(ctx, client, params).

View Source
var ErrAgentSessionClosed = errors.New("bmaexecutor: agent session closed")

ErrAgentSessionClosed is returned by AgentTurn methods after session.close.

View Source
var ErrComputerActionRejected = errors.New("computer_action_rejected")

ErrComputerActionRejected means the driver explicitly refused the action before input. Transport errors and incomplete/undecodable results never use this classification, even if their text mentions a known rejection.

View Source
var ErrComputerUseUnavailable = errors.New("bmaexecutor: computer use backend is unavailable")

ErrComputerUseUnavailable is returned by NewCuaDriver when the driver or its interactive-session daemon cannot be used; leave CoreOptions.ComputerUse nil then.

View Source
var ErrConversationLost = errors.New("the local conversation is gone")

ErrConversationLost is what Open answers for a req.Ref whose local state the brain does not have: the host opens a new conversation instead and tells the platform (turn.start resumed false, another executor_session_ref).

View Source
var ErrDesktopControl = errors.New("desktop_control_not_current")
View Source
var ErrDesktopDraining = errors.New("human_takeover_pending")
View Source
var ErrDesktopInputUnknown = errors.New("desktop_input_outcome_unknown")
View Source
var ErrDesktopObservation = errors.New("desktop_observation_required")
View Source
var ErrDesktopRecoveryRequired = errors.New("desktop_input_recovery_required")
View Source
var ErrDesktopResizeUnsupported = errors.New("desktop_resize_unsupported")

ErrDesktopResizeUnsupported means no resize was dispatched. Other native errors remain uncertain and block input until cleanup is confirmed.

View Source
var ErrMachineTokenRequired = errors.New("bmaexecutor: a machine-scoped executor (machine daemon token in EnvironmentKey, empty EnvironmentID) is required")

ErrMachineTokenRequired is returned by the machine-token HTTP features (SessionContext, SessionContextByID, SessionFiles) of a client that is not a machine-scoped executor: Options.EnvironmentKey must hold the machine daemon token and Options.EnvironmentID must be empty.

View Source
var ErrNamedPipeUnsupported = errors.New("bmaexecutor: Windows named pipes are not supported on this platform")

ErrNamedPipeUnsupported is returned by the named pipe transport on platforms other than Windows.

View Source
var ErrNotSteered = errors.New("the brain does not take this input in the running prompt")

ErrNotSteered is what BrainSession.Steer answers for an input the running Prompt does not take; the host prompts it on its own instead.

View Source
var ErrSessionContextNotFound = errors.New("bmaexecutor: session context not found")

ErrSessionContextNotFound is returned when the process is not on this machine (or ended more than 15 minutes ago), or the session is not bound to this machine.

View Source
var Methods = map[string]MethodSpec{
	MethodScreenStart:                {Name: MethodScreenStart, Direction: DirectionHarnessToExecutor, Notification: false, Since: "bma.executor.v1.1", Capability: "display.native_webrtc", IdempotentBy: "session_id"},
	MethodScreenStop:                 {Name: MethodScreenStop, Direction: DirectionHarnessToExecutor, Notification: false, Since: "bma.executor.v1.1", Capability: "display.native_webrtc", IdempotentBy: "session_id"},
	MethodScreenLive:                 {Name: MethodScreenLive, Direction: DirectionHarnessToExecutor, Notification: false, Since: "bma.executor.v1.1", Capability: "display.screen_live", IdempotentBy: "session_id"},
	MethodScreenControl:              {Name: MethodScreenControl, Direction: DirectionHarnessToExecutor, Notification: false, Since: "bma.executor.v1.1", Capability: "display.screen_control", IdempotentBy: "lease_id"},
	MethodExecutorRegister:           {Name: MethodExecutorRegister, Direction: DirectionExecutorToHarness, Notification: false, Since: "bma.executor.v1", Capability: "", IdempotentBy: ""},
	MethodExecutorHeartbeat:          {Name: MethodExecutorHeartbeat, Direction: DirectionExecutorToHarness, Notification: false, Since: "bma.executor.v1", Capability: "", IdempotentBy: ""},
	MethodExecutorTokenRefresh:       {Name: MethodExecutorTokenRefresh, Direction: DirectionExecutorToHarness, Notification: false, Since: "bma.executor.v1.1", Capability: "", IdempotentBy: ""},
	MethodExecutorCapabilitiesUpdate: {Name: MethodExecutorCapabilitiesUpdate, Direction: DirectionExecutorToHarness, Notification: true, Since: "bma.executor.v1", Capability: "", IdempotentBy: ""},
	MethodExecutorDrain:              {Name: MethodExecutorDrain, Direction: DirectionHarnessToExecutor, Notification: false, Since: "bma.executor.v1", Capability: "", IdempotentBy: ""},
	MethodExecutorClose:              {Name: MethodExecutorClose, Direction: DirectionBidirectional, Notification: true, Since: "bma.executor.v1", Capability: "", IdempotentBy: ""},
	MethodSessionAssign:              {Name: MethodSessionAssign, Direction: DirectionHarnessToExecutor, Notification: false, Since: "bma.executor.v1", Capability: "", IdempotentBy: ""},
	MethodSessionReady:               {Name: MethodSessionReady, Direction: DirectionExecutorToHarness, Notification: false, Since: "bma.executor.v1", Capability: "", IdempotentBy: ""},
	MethodSessionEvent:               {Name: MethodSessionEvent, Direction: DirectionExecutorToHarness, Notification: false, Since: "bma.executor.v1", Capability: "", IdempotentBy: "jsonrpc_id"},
	MethodSessionStatus:              {Name: MethodSessionStatus, Direction: DirectionExecutorToHarness, Notification: true, Since: "bma.executor.v1", Capability: "", IdempotentBy: ""},
	MethodSessionStop:                {Name: MethodSessionStop, Direction: DirectionHarnessToExecutor, Notification: false, Since: "bma.executor.v1", Capability: "", IdempotentBy: ""},
	MethodSessionEnded:               {Name: MethodSessionEnded, Direction: DirectionExecutorToHarness, Notification: false, Since: "bma.executor.v1", Capability: "", IdempotentBy: ""},
	MethodToolCall:                   {Name: MethodToolCall, Direction: DirectionHarnessToExecutor, Notification: false, Since: "bma.executor.v1", Capability: "", IdempotentBy: ""},
	MethodToolResult:                 {Name: MethodToolResult, Direction: DirectionExecutorToHarness, Notification: false, Since: "bma.executor.v1", Capability: "", IdempotentBy: "tool_call_id"},
	MethodToolCancel:                 {Name: MethodToolCancel, Direction: DirectionHarnessToExecutor, Notification: false, Since: "bma.executor.v1", Capability: "", IdempotentBy: ""},
	MethodToolProgress:               {Name: MethodToolProgress, Direction: DirectionExecutorToHarness, Notification: true, Since: "bma.executor.v1", Capability: "", IdempotentBy: ""},
	MethodProcessStart:               {Name: MethodProcessStart, Direction: DirectionHarnessToExecutor, Notification: false, Since: "bma.executor.v1.1", Capability: "process.enabled", IdempotentBy: "session_id+process_id"},
	MethodProcessRead:                {Name: MethodProcessRead, Direction: DirectionHarnessToExecutor, Notification: false, Since: "bma.executor.v1.1", Capability: "process.enabled", IdempotentBy: ""},
	MethodProcessWrite:               {Name: MethodProcessWrite, Direction: DirectionHarnessToExecutor, Notification: false, Since: "bma.executor.v1.1", Capability: "process.enabled", IdempotentBy: ""},
	MethodProcessInterrupt:           {Name: MethodProcessInterrupt, Direction: DirectionHarnessToExecutor, Notification: false, Since: "bma.executor.v1.1", Capability: "process.enabled", IdempotentBy: ""},
	MethodProcessTerminate:           {Name: MethodProcessTerminate, Direction: DirectionHarnessToExecutor, Notification: false, Since: "bma.executor.v1.1", Capability: "process.enabled", IdempotentBy: ""},
	MethodProcessList:                {Name: MethodProcessList, Direction: DirectionHarnessToExecutor, Notification: false, Since: "bma.executor.v1.1", Capability: "process.enabled", IdempotentBy: ""},
	MethodProcessStatus:              {Name: MethodProcessStatus, Direction: DirectionExecutorToHarness, Notification: true, Since: "bma.executor.v1.1", Capability: "process.enabled", IdempotentBy: ""},
	MethodTerminalOpen:               {Name: MethodTerminalOpen, Direction: DirectionHarnessToExecutor, Notification: false, Since: "bma.executor.v1.1", Capability: "terminal.enabled", IdempotentBy: "terminal_id"},
	MethodTerminalAttach:             {Name: MethodTerminalAttach, Direction: DirectionHarnessToExecutor, Notification: false, Since: "bma.executor.v1.1", Capability: "terminal.enabled", IdempotentBy: ""},
	MethodTerminalClose:              {Name: MethodTerminalClose, Direction: DirectionHarnessToExecutor, Notification: false, Since: "bma.executor.v1.1", Capability: "terminal.enabled", IdempotentBy: "terminal_id"},
	MethodDesktopAttach:              {Name: MethodDesktopAttach, Direction: DirectionHarnessToExecutor, Notification: false, Since: "bma.executor.v1.1", Capability: "display.desktop", IdempotentBy: "session_id"},
	MethodDesktopWallpaper:           {Name: MethodDesktopWallpaper, Direction: DirectionHarnessToExecutor, Notification: false, Since: "bma.executor.v1.1", Capability: "display.desktop", IdempotentBy: ""},
	MethodSkillInstall:               {Name: MethodSkillInstall, Direction: DirectionHarnessToExecutor, Notification: false, Since: "bma.executor.v1.1", Capability: "skills.install", IdempotentBy: "skill_id+revision_id+digest"},
	MethodWorkspaceBackup:            {Name: MethodWorkspaceBackup, Direction: DirectionHarnessToExecutor, Notification: false, Since: "bma.executor.v1.1", Capability: "workspace.backup", IdempotentBy: "backup_id"},
	MethodSessionFilesFlush:          {Name: MethodSessionFilesFlush, Direction: DirectionHarnessToExecutor, Notification: false, Since: "bma.executor.v1.1", Capability: "session_files", IdempotentBy: ""},
	MethodSessionFilesSync:           {Name: MethodSessionFilesSync, Direction: DirectionHarnessToExecutor, Notification: false, Since: "bma.executor.v1.1", Capability: "session_files.memory", IdempotentBy: "agent_session_id"},
	MethodTurnStart:                  {Name: MethodTurnStart, Direction: DirectionHarnessToExecutor, Notification: false, Since: "bma.executor.v1.1", Capability: "agent", IdempotentBy: "turn_id"},
	MethodTurnInput:                  {Name: MethodTurnInput, Direction: DirectionHarnessToExecutor, Notification: false, Since: "bma.executor.v1.1", Capability: "agent", IdempotentBy: "input_id"},
	MethodTurnCancel:                 {Name: MethodTurnCancel, Direction: DirectionHarnessToExecutor, Notification: false, Since: "bma.executor.v1.1", Capability: "agent", IdempotentBy: ""},
	MethodSessionCompact:             {Name: MethodSessionCompact, Direction: DirectionHarnessToExecutor, Notification: false, Since: "bma.executor.v1.1", Capability: "agent.context_maintenance", IdempotentBy: "operation_id"},
	MethodSessionCompactCancel:       {Name: MethodSessionCompactCancel, Direction: DirectionHarnessToExecutor, Notification: false, Since: "bma.executor.v1.1", Capability: "agent.context_maintenance", IdempotentBy: ""},
	MethodSessionClose:               {Name: MethodSessionClose, Direction: DirectionHarnessToExecutor, Notification: false, Since: "bma.executor.v1.1", Capability: "agent", IdempotentBy: ""},
	MethodSessionEventDelta:          {Name: MethodSessionEventDelta, Direction: DirectionExecutorToHarness, Notification: true, Since: "bma.executor.v1.1", Capability: "agent", IdempotentBy: ""},
	MethodSessionHistory:             {Name: MethodSessionHistory, Direction: DirectionExecutorToHarness, Notification: false, Since: "bma.executor.v1.1", Capability: "agent", IdempotentBy: ""},
	MethodInteractionRequest:         {Name: MethodInteractionRequest, Direction: DirectionExecutorToHarness, Notification: false, Since: "bma.executor.v1.1", Capability: "agent", IdempotentBy: "interaction_id"},
	MethodInteractionResponse:        {Name: MethodInteractionResponse, Direction: DirectionHarnessToExecutor, Notification: false, Since: "bma.executor.v1.1", Capability: "agent", IdempotentBy: "interaction_id"},
	MethodAgentCustomToolResult:      {Name: MethodAgentCustomToolResult, Direction: DirectionHarnessToExecutor, Notification: false, Since: "bma.executor.v1.1", Capability: "agent", IdempotentBy: "tool_use_id"},
	MethodInteractionCancel:          {Name: MethodInteractionCancel, Direction: DirectionExecutorToHarness, Notification: false, Since: "bma.executor.v1.1", Capability: "agent", IdempotentBy: "interaction_id"},
	MethodModelTokenRefresh:          {Name: MethodModelTokenRefresh, Direction: DirectionExecutorToHarness, Notification: false, Since: "bma.executor.v1.1", Capability: "agent", IdempotentBy: ""},
	MethodToolsTokenRefresh:          {Name: MethodToolsTokenRefresh, Direction: DirectionExecutorToHarness, Notification: false, Since: "bma.executor.v1.1", Capability: "agent", IdempotentBy: ""},
	MethodWorkingLogRead:             {Name: MethodWorkingLogRead, Direction: DirectionExecutorToHarness, Notification: false, Since: "bma.executor.v1.1", Capability: "agent", IdempotentBy: ""},
	MethodWorkingLogAppend:           {Name: MethodWorkingLogAppend, Direction: DirectionExecutorToHarness, Notification: false, Since: "bma.executor.v1.1", Capability: "agent", IdempotentBy: ""},
}

Methods is the complete method catalog.

View Source
var Notifications = struct {
	ExecutorCapabilitiesUpdate NotificationMethod[ExecutorCapabilitiesUpdateParams]
	SessionStatus              NotificationMethod[SessionStatusParams]
	ToolProgress               NotificationMethod[ToolProgressParams]
	ProcessStatus              NotificationMethod[ProcessStatusParams]
	SessionEventDelta          NotificationMethod[SessionEventDeltaParams]
}{
	ExecutorCapabilitiesUpdate: NotificationMethod[ExecutorCapabilitiesUpdateParams]{Method: "executor.capabilities.update"},
	SessionStatus:              NotificationMethod[SessionStatusParams]{Method: "session.status"},
	ToolProgress:               NotificationMethod[ToolProgressParams]{Method: "tool.progress"},
	ProcessStatus:              NotificationMethod[ProcessStatusParams]{Method: "process.status"},
	SessionEventDelta:          NotificationMethod[SessionEventDeltaParams]{Method: "session.event_delta"},
}

Notifications are the executor-to-harness notifications a client sends: Notifications.ToolProgress.Notify(ctx, client, params).

View Source
var Requests = struct {
	ScreenStart           RequestMethod[ScreenStartParams, ScreenStartResult]
	ScreenStop            RequestMethod[ScreenStopParams, ScreenStopResult]
	ScreenLive            RequestMethod[ScreenLiveParams, ScreenLiveResult]
	ScreenControl         RequestMethod[ScreenControlParams, ScreenControlResult]
	ProcessStart          RequestMethod[ProcessStartParams, ProcessState]
	ProcessRead           RequestMethod[ProcessReadParams, ProcessReadResult]
	ProcessWrite          RequestMethod[ProcessWriteParams, ProcessWriteResult]
	ProcessInterrupt      RequestMethod[ProcessSignalParams, ProcessState]
	ProcessTerminate      RequestMethod[ProcessSignalParams, ProcessState]
	ProcessList           RequestMethod[ProcessListParams, ProcessListResult]
	TerminalOpen          RequestMethod[TerminalOpenParams, TerminalOpenResult]
	TerminalAttach        RequestMethod[TerminalAttachParams, TerminalAttachResult]
	TerminalClose         RequestMethod[TerminalCloseParams, TerminalCloseResult]
	DesktopAttach         RequestMethod[DesktopAttachParams, DesktopAttachResult]
	DesktopWallpaper      RequestMethod[DesktopWallpaperParams, DesktopWallpaperResult]
	SkillInstall          RequestMethod[SkillInstallParams, SkillInstallResult]
	WorkspaceBackup       RequestMethod[WorkspaceBackupParams, WorkspaceBackupResult]
	SessionFilesFlush     RequestMethod[SessionFilesFlushParams, SessionFilesFlushResult]
	SessionFilesSync      RequestMethod[SessionFilesSyncParams, SessionFilesSyncResult]
	SessionCompact        RequestMethod[SessionCompactParams, SessionCompactResult]
	SessionCompactCancel  RequestMethod[SessionCompactCancelParams, SessionCompactCancelResult]
	AgentCustomToolResult RequestMethod[AgentCustomToolResultParams, CustomToolResultResult]
}{
	ScreenStart:           RequestMethod[ScreenStartParams, ScreenStartResult]{Method: "screen.start"},
	ScreenStop:            RequestMethod[ScreenStopParams, ScreenStopResult]{Method: "screen.stop"},
	ScreenLive:            RequestMethod[ScreenLiveParams, ScreenLiveResult]{Method: "screen.live"},
	ScreenControl:         RequestMethod[ScreenControlParams, ScreenControlResult]{Method: "screen.control"},
	ProcessStart:          RequestMethod[ProcessStartParams, ProcessState]{Method: "process.start"},
	ProcessRead:           RequestMethod[ProcessReadParams, ProcessReadResult]{Method: "process.read"},
	ProcessWrite:          RequestMethod[ProcessWriteParams, ProcessWriteResult]{Method: "process.write"},
	ProcessInterrupt:      RequestMethod[ProcessSignalParams, ProcessState]{Method: "process.interrupt"},
	ProcessTerminate:      RequestMethod[ProcessSignalParams, ProcessState]{Method: "process.terminate"},
	ProcessList:           RequestMethod[ProcessListParams, ProcessListResult]{Method: "process.list"},
	TerminalOpen:          RequestMethod[TerminalOpenParams, TerminalOpenResult]{Method: "terminal.open"},
	TerminalAttach:        RequestMethod[TerminalAttachParams, TerminalAttachResult]{Method: "terminal.attach"},
	TerminalClose:         RequestMethod[TerminalCloseParams, TerminalCloseResult]{Method: "terminal.close"},
	DesktopAttach:         RequestMethod[DesktopAttachParams, DesktopAttachResult]{Method: "desktop.attach"},
	DesktopWallpaper:      RequestMethod[DesktopWallpaperParams, DesktopWallpaperResult]{Method: "desktop.wallpaper"},
	SkillInstall:          RequestMethod[SkillInstallParams, SkillInstallResult]{Method: "skill.install"},
	WorkspaceBackup:       RequestMethod[WorkspaceBackupParams, WorkspaceBackupResult]{Method: "workspace.backup"},
	SessionFilesFlush:     RequestMethod[SessionFilesFlushParams, SessionFilesFlushResult]{Method: "session_files.flush"},
	SessionFilesSync:      RequestMethod[SessionFilesSyncParams, SessionFilesSyncResult]{Method: "session_files.sync"},
	SessionCompact:        RequestMethod[SessionCompactParams, SessionCompactResult]{Method: "session.compact"},
	SessionCompactCancel:  RequestMethod[SessionCompactCancelParams, SessionCompactCancelResult]{Method: "session.compact_cancel"},
	AgentCustomToolResult: RequestMethod[AgentCustomToolResultParams, CustomToolResultResult]{Method: "agent.custom_tool_result"},
}

Requests are the harness-to-executor requests a client serves: Requests.ProcessStart.Handle(client, fn).

Functions

func ApprovalID added in v1.4.0

func ApprovalID(sessionID, turnID, callID string) string

ApprovalID is the interaction id to ask a tool call's approval under (InteractionRequestParams.InteractionID) and to present with the call (RouteCall.ApprovalID): "appr_" and 24 hex characters of sha256 over session, turn and call id, NUL separated (ADR-0027). It is the same after a reconnect or an executor restart, so the platform keeps one interaction per call and an approval already answered is not asked again. The turn is part of it because providers may reuse call ids such as "call_0" in every turn.

func CloseCode

func CloseCode(err error) int

CloseCode returns the close code carried by err, or -1.

func FileWriteApproval added in v1.23.0

func FileWriteApproval(ctx context.Context) (path string, approve func(string))

FileWriteApproval returns the path approved for this tool call at commit. At preflight it returns a callback that can record the authorized absolute path after asking the user. The host must check it against the final target.

func MigrateExecutorURL added in v1.9.0

func MigrateExecutorURL(base string) (string, bool)

MigrateExecutorURL answers the executor origin for a stored base URL and whether it changed: callers that persist the URL write the answer back.

func NamedPipeListener

func NamedPipeListener(name string) (net.Listener, error)

NamedPipeListener listens on the Windows named pipe \\.\pipe\<name> for the current user only (remote clients are refused). Serve Harness on it, as on a Unix socket listener.

func NewParams

func NewParams(method string) any

NewParams returns a pointer to a zero params object for method, or nil for an unknown method.

func NewResult

func NewResult(method string) any

NewResult returns a pointer to a zero result for a request method, or nil for a notification or an unknown method.

func NewToolInput

func NewToolInput(input ToolInput) json.RawMessage

NewToolInput encodes a built-in tool input for ToolCallParams.Input.

func Pipe

func Pipe(protocol string) (executor Conn, harness Conn)

Pipe returns the two ends of an in-process connection that negotiated protocol: one for the executor (Client), one for the harness (Harness.ServeConn). Frames are copied, so neither side can mutate the other's buffers.

func RequestID

func RequestID(ctx context.Context) string

RequestID returns the JSON-RPC id of the inbound request whose handler received ctx (the idempotency key of retried requests), or "".

func RunNativeDesktopInputWorker added in v1.6.5

func RunNativeDesktopInputWorker() bool

func ScreenInputRefusal added in v1.6.53

func ScreenInputRefusal(err error) string

ScreenInputRefusal is the code of a refused screen_input (empty when it succeeded): why the gate or the native input did not take it.

func SendExecutorCapabilitiesUpdate

func SendExecutorCapabilitiesUpdate(ctx context.Context, rpc RPC, params ExecutorCapabilitiesUpdateParams) error

SendExecutorCapabilitiesUpdate sends the executor.capabilities.update notification.

func SendExecutorClose

func SendExecutorClose(ctx context.Context, rpc RPC, params ExecutorCloseParams) error

SendExecutorClose sends the executor.close notification.

func SendProcessStatus

func SendProcessStatus(ctx context.Context, rpc RPC, params ProcessStatusParams) error

SendProcessStatus sends the process.status notification.

func SendSessionEventDelta

func SendSessionEventDelta(ctx context.Context, rpc RPC, params SessionEventDeltaParams) error

SendSessionEventDelta sends the session.event_delta notification.

func SendSessionStatus

func SendSessionStatus(ctx context.Context, rpc RPC, params SessionStatusParams) error

SendSessionStatus sends the session.status notification.

func SendToolProgress

func SendToolProgress(ctx context.Context, rpc RPC, params ToolProgressParams) error

SendToolProgress sends the tool.progress notification.

func StaticToken

func StaticToken(wsURL, token string) func(context.Context) (ExecutorTokenResponse, error)

StaticToken is a TokenSource for a harness reached directly, typically a local harness. token may be empty when the harness has no Authenticate hook.

Types

type ACPAgent added in v1.3.0

type ACPAgent = BrainHost

ACPAgent is the BrainHost NewACPAgent returns.

func NewACPAgent added in v1.3.0

func NewACPAgent(ctx context.Context, opts ACPAgentOptions) (*ACPAgent, error)

NewACPAgent starts the brain of opts.Profile, checks it and returns its host. Serve it with client.ServeAgent(agent, agent.Capability()).

type ACPAgentOptions added in v1.3.0

type ACPAgentOptions struct {
	// Profile selects the hosted brain of NewACPAgent: ACPProfileDSH (default)
	// or ACPProfileClaudeCode (agent_acp_profiles.go). NewBrainHost ignores it.
	Profile string
	// Command is the brain's argv, for example {"/opt/bma/bma-dsh-acp"} or
	// {"/opt/bma/node", "/opt/bma/bma-dsh-acp.mjs"}. Command[0] must be an
	// absolute path: the brain is never looked up on PATH (a user's own one
	// there must not be started by mistake).
	Command []string
	// Env adds KEY=VALUE entries to the brain's environment (PATH, HOME, USER, LANG and TMPDIR come from the executor).
	Env []string
	// StateDir holds the brain's state.
	StateDir string
	// Core runs the tools.
	Core *Core
	// AllowedRoots bound a turn's cwd (default: Core's work root). A turn
	// without cwd works in Core's per-session workspace.
	AllowedRoots []string
	// Upstream is the model endpoint used when the platform hands none, for
	// a brain whose model requests the host forwards. Required for such a
	// brain unless PlatformModel.
	Upstream ACPModelUpstream
	// PlatformModel asks the platform for the per-turn model credential
	// (agent capability platform_credentials: harness_model), as a sandbox
	// machine of the platform does. Without Upstream a turn the platform
	// hands no credential fails (session.error); it is never sent elsewhere.
	// Refused for a brain that uses only its owner's credentials.
	PlatformModel bool
	// PlatformTools declares platform_credentials brain_tools: this machine
	// may be the brain of a session whose hands are on another machine
	// (ADR-0029). The platform then hands the turn its tools endpoint and token
	// (turn.start metadata tools_mcp_*) and every tool call of that turn goes
	// there, never to this machine's Core (fail closed). A turn without
	// tools_mcp_* runs its tools here.
	PlatformTools bool
	// AskUserQuestion offers the brain the ask_user_question tool (see
	// agent_acp_host_tools.go): a question is a custom tool call of the session
	// (capability custom_tools), so turn it on only when the session's clients
	// answer custom tool calls (user.custom_tool_result); a client that does not
	// leaves the session waiting.
	AskUserQuestion bool
	// ToolPolicy is the host's ceiling on the permission of tools (tool name
	// to allow, ask or deny): the permission of a tool in a turn is the
	// stricter of this value and what the platform's turn.start
	// metadata.tool_policy and the permission mode give (deny over ask over
	// allow), so the platform and the mode can only tighten it, never loosen
	// it. A tool it does not name is not capped. A host sets deny on tools it
	// cannot yet check (fail closed). Applies to the six tools and to host
	// tools, and is enforced by the executor's gate whatever the brain does.
	// Other values are rejected. Nil caps nothing.
	ToolPolicy map[string]string
	// SessionFilesRoot is the executor's capabilities.session_files.root: the
	// directory below which the platform mounts each session's files as
	// <root>/<session id>/{uploads,skills,outputs,memory}. When set, the
	// file tools of a turn whose tools run on this machine reach, besides the
	// workspace, exactly these directories of that session: read, glob and
	// grep in uploads, skills and memory (read-only; memory is the mirror of
	// the session's memory stores, which the platform describes in the system
	// prompt) and in outputs, and write and edit in outputs (deliverables the
	// platform collects). Another session's directories, a path below the
	// root that is none of them, a "..", and a symbolic link that leaves a
	// directory stay refused; write and edit anywhere else stay confined to
	// the workspace. The session id must be a single safe directory name.
	// Absolute, or empty for the workspace only.
	SessionFilesRoot string
	// SessionMounts limits the session's directories below SessionFilesRoot
	// that the file tools reach and the model is told about to these of
	// "uploads", "skills", "outputs" and "memory"; nil means all four (the
	// note names uploads, skills and outputs; memory is named by the
	// platform). A host whose local turns get only the skills view and do not
	// sync uploads or outputs sets []string{"skills"}, so the model is not
	// told to write deliverables nobody collects.
	SessionMounts []string
	// InputFiles fetches the bytes of an image the user attached (a file
	// block of turn.start / turn.input; see agent_acp_images.go) when the
	// platform hands the turn no tools endpoint to download it from. With it
	// (or PlatformTools) and a brain that takes images the agent capability
	// declares file_inputs and the harness image_inputs, and the platform
	// then sends image input. Without both, the platform is told the brain
	// takes no image and refuses an image input.
	InputFiles ACPInputFiles
	// HarnessID is the declared harness id (default: the brain's own id).
	HarnessID string
	// Model is the model name the brain uses when the turn config has none (default Upstream.Model).
	Model string
	// Models are the models the host lets a turn choose (agent capability
	// models), for example the models the node owner's account may use: a
	// turn.start config.model must be one of their ids or the turn is refused
	// (-32602, never another model). A model's ThinkingLevels are the
	// reasoning effort values (acpReasoningEfforts: none, minimal, low,
	// medium, high, xhigh, max) a turn may set with config.thinking_level, or
	// DefaultThinkingLevel when it sets none; levels the brain does not take
	// are not declared, so a turn naming one is refused rather than run
	// without it. A model without levels ignores config.thinking_level.
	// Empty: config.model and config.thinking_level are ignored (contract)
	// and every turn runs on Model. Refused for a brain that takes no
	// per-turn model (BrainCapabilities.ModelChoice).
	Models []AgentModel
	// SystemPrompt is the base system prompt, with one %s for the working directory (default DefaultACPSystemPrompt).
	SystemPrompt string
	// MaxSessions bounds the turns running at once (default
	// DefaultACPMaxSessions): a turn.start past it answers executor_busy, and an
	// idle session holds no slot.
	MaxSessions int64
	// MaxResidentSessions bounds the sessions whose brain conversation and Core
	// session are held, running or idle (default DefaultACPResidentSessions of the
	// Core's capacity, at least MaxSessions; it must not exceed the Core's
	// MaxSessions). Past it the least recently used idle session is suspended
	// (BrainSession.Suspend; the brain keeps its conversation) and loaded again
	// by its next turn (with the executor_session_ref). A session with a bash
	// command left running is not suspended.
	MaxResidentSessions int
	CancelGrace         time.Duration
	KillGrace           time.Duration
	OnLog               func(LogEvent)
	// OnInteraction, when set, is told when an approval is asked of the
	// platform and when it ends (answered on any client, expired or
	// withdrawn), so a local UI can show the same card under the same id and
	// drop it when it is settled elsewhere. It is a view only: the answer
	// still comes from the platform. It must not block.
	OnInteraction func(ACPInteractionEvent)
}

ACPAgentOptions configures NewACPAgent and NewBrainHost.

type ACPInputFile added in v1.5.1

type ACPInputFile struct {
	SessionID string
	TurnID    string
	// Block is the file block as the platform sent it (FileID is set).
	Block AgentInputBlock
	// Metadata is the turn.start metadata of the turn.
	Metadata map[string]string
}

ACPInputFile is one file block the executor must fetch the bytes of.

type ACPInputFiles added in v1.5.1

type ACPInputFiles func(ctx context.Context, file ACPInputFile) (io.ReadCloser, error)

ACPInputFiles returns the content of a file block (the caller closes it and reads at most the image limit). It sets ACPAgentOptions.InputFiles.

type ACPInteractionEvent added in v1.3.0

type ACPInteractionEvent struct {
	// Phase is "requested" or "ended".
	Phase string
	// Kind is InteractionKindPermission (an approval; InteractionID is the
	// platform interaction) or InteractionKindQuestion (ask_user_question;
	// InteractionID is the agent.custom_tool_use event id the session waits on).
	Kind          string
	SessionID     string
	InteractionID string
	ToolName      string
	// ToolInput is the tool call's input (Phase "requested" only).
	ToolInput map[string]any
	// Outcome is the platform answer when Phase is "ended" (allow, deny,
	// expired, canceled), or "withdrawn" when the turn ended first.
	Outcome string
}

ACPInteractionEvent is one step of a platform interaction asked by the local brain.

type ACPModelUpstream added in v1.3.0

type ACPModelUpstream struct {
	// BaseURL ends in /v1; requests go to BaseURL + "/chat/completions".
	BaseURL string
	// Model is the default model of a turn (ACPAgentOptions.Model defaults
	// to it). A request goes upstream with the turn's model: this one, or the
	// one of ACPAgentOptions.Models the turn chose.
	Model string
	// Header adds the credential (for example Authorization) to a forwarded request.
	Header func(*http.Request)
	// SessionHeader, when set, names a request header that every request
	// forwarded to this endpoint carries, with the platform session id of the
	// turn it belongs to (turn.start session_id) as its value, so the endpoint
	// can account a request to its session. It is set before Header runs. The
	// value never comes from the brain: a forwarded request is built anew and
	// takes no such header from the brain's request. Requests that go to the
	// platform's own model endpoint (turn.start metadata model_base_url) do
	// not carry it.
	SessionHeader string
}

ACPModelUpstream is where model requests go when turn.start carries no platform model endpoint: the node owner's own OpenAI-compatible endpoint.

type Ack

type Ack struct {
	Accepted bool `json:"accepted"`
}

Ack Generic acknowledgement returned by executor RPC methods.

func SendInteractionCancel

func SendInteractionCancel(ctx context.Context, rpc RPC, params InteractionCancelParams) (Ack, error)

SendInteractionCancel calls interaction.cancel.

func SendSessionEnded

func SendSessionEnded(ctx context.Context, rpc RPC, params SessionEndedParams) (Ack, error)

SendSessionEnded calls session.ended.

func SendSessionReady

func SendSessionReady(ctx context.Context, rpc RPC, params SessionReadyParams) (Ack, error)

SendSessionReady calls session.ready.

func SendToolResult

func SendToolResult(ctx context.Context, rpc RPC, params ToolResultParams) (Ack, error)

SendToolResult calls tool.result.

type AgentCapability

type AgentCapability struct {
	Enabled bool `json:"enabled"`
	// Models the local agent can run. An empty list means the executor picks its own model and ignores AgentTurnConfig.model.
	Models []AgentModel `json:"models,omitempty"`
	// Permission mode ids the local agent understands, for example default, accept_edits, plan, bypass_permissions. The executor defines the ids; the platform only passes one back in AgentTurnConfig.permission_mode.
	PermissionModes []string `json:"permission_modes,omitempty"`
	// Interaction kinds the executor may open with interaction.request.
	InteractionKinds []string `json:"interaction_kinds,omitempty"`
	// The executor fetches the bytes of the file blocks (file_id) of turn.start and turn.input itself. Declare it only when it can: through the tools endpoint of the turn (tools_mcp_url and tools_mcp_token in turn.start metadata, GET <tools_mcp_url without /mcp>/files/<file_id>/content), or, on a machine daemon token, through the turn input files routes (GET /v1/machines/{machine_id}/sessions/{session_id}/turns/{turn_id}/input_files and .../{file_id}/content, docs/architecture/executor-turn-input-files.md). Together with the agent accepting images (harness.image_inputs) it is what lets the platform accept an image input for the agent: without it the input is refused with 400, with it the platform sends the file blocks and never refuses an image the agent accepts. Absent means false.
	FileInputs bool `json:"file_inputs,omitempty"`
	// Contract 1.7.0. The executor fetches a turn input the platform does not inline: when turn.start or turn.input would serialize to more than 48 KiB (the 64 KiB control frame limit with headroom), its input is a single input_ref block (AgentInputBlock type input_ref: input_id, size_bytes, sha256) instead of the blocks, and the executor reads them with its machine credential: GET /v1/machines/{machine_id}/inputs/{input_id} on the executor domain answers 200 with the AgentInputBlock array the input would have carried (404 unless the input belongs to a session of the credential's machine; readable until its turn ends). The executor checks size_bytes and sha256 and handles the blocks exactly as if they had come inline. Declare it only when it can make that request. Without it such an input ends its turn: session.error (bma_error_code input_too_large, not retried) and the turn fails; the platform never retries a request that cannot fit. Absent means false.
	InputByReference bool `json:"input_by_reference,omitempty"`
	// Contract 1.25.0. The local agent takes a turn.input at the running turn's next step boundary: after the results of the tool calls of its current step and before its next model request, so the input can change what the agent does next in the same turn. When the model answers without a tool call, the agent reads an input that arrived meanwhile before it ends the turn; once it ends the turn it answers a later turn.input -32013 conflict. The platform hands a steering user.message (bma_delivery_mode steering) to the running turn as turn.input only when its brain declares it; otherwise it re-files the message as queued (bma_delivery_reason harness_no_steering) and runs it as a turn of its own. Absent means false.
	Steering bool `json:"steering,omitempty"`
	// Contract 2.2.0. When the agent opens a session it has no local state for, it reads the conversation with session.history and rebuilds its context from it before running the turn (answering turn.start with context_rebuilt true when there was a past); it never runs such a turn without that context. The platform forks a session (POST /v1/sessions/{session_id}/fork: a new session that starts with a copy of the conversation) only when the session's brain runs on an executor that declares it, else 400 fork_unsupported; the fork's first turn reaches the brain with no local state and the copied conversation in session.history. Absent means false.
	HistoryRebuild bool `json:"history_rebuild,omitempty"`
	// Turns the executor runs at once. A turn.start while that many turns are running answers -32009 executor_busy (retryable). A session with no running turn holds no slot; an executor may release the local resources of its least recently used idle sessions and load them again from executor_session_ref on the next turn.start.
	MaxSessions int64 `json:"max_sessions,omitempty"`
	// The executor keeps the state of its turns across a process restart. When it registers again without a session whose turn was running, the platform starts the same turn again in a new event epoch (turn.start with the same turn_id, input_id and executor_session_ref, then the turn.input the turn already received) and the executor continues the turn from its own state. Without it such a turn ends failed (session.error, session.status_idle retries_exhausted) and is not sent again: an executor without that state would run the turn again from its opening input and repeat tool calls whose effects already happened.
	TurnResume bool `json:"turn_resume,omitempty"`
	// Per-turn credentials the executor asks the platform to hand it in turn.start metadata: brain_tools (tools_mcp_url, tools_mcp_token: the session's tools endpoint) and harness_model (model_base_url, model_token: the session's model endpoint; optionally model_context_window and model_max_output_tokens, positive integer strings: the resolved model's context window and output ceiling, absent when the platform has no catalog entry for the model, in which case the executor uses its own defaults; contract 1.27.0: model_input_images, true or false (strings): whether the turn's model accepts images, from its provider's model list, absent when unknown; with false the brain sends the model no image of a tool result (screenshots, generate_image previews), only their text). A declaration only states what the executor can use; the platform decides by the executor's identity: a platform service executor gets what it declares; on a platform-managed pool machine an ACP harness turn gets harness_model by default, without a declaration; a BYO machine gets harness_model only when it declares it, and an undeclared BYO machine gets nothing, so it keeps using the model endpoint configured on it and the platform never overrides that upstream. brain_tools (contract 1.4.0) is handed to a tenant executor only when the session binds this machine as the brain machine and a different machine as the hands machine (brain and hands apart, ADR-0029) and the executor declared brain_tools; the token is bound to the org, the session, the turn, this machine and the brain epoch of the turn (the event epoch of the turn.start that carries it), so a turn started again in a new epoch gets a new token and calls made with the previous epoch's token are refused. When one machine is both brain and hands nothing is handed (the executor runs its tools itself); a platform service executor and an executor that did not declare brain_tools never get it. Until contract 1.4.0 brain_tools was never handed to a tenant executor. The harness_model token is a bma-model token bound to the turn's org, session, turn and machine (model_base_url is the machine's proxy path). Tokens are computed for each turn.start, are valid until the turn ends, and are never stored. platform_tools (contract 2.4.0): for a turn whose brain runs on this machine and runs its own tools here (no tools_mcp_*), platform_tools_mcp_url (the platform tools endpoint of this machine, https://executor.<domain>/v1/machines/{machine_id}/mcp), platform_tools_mcp_token and platform_tools_mcp_token_expires_at, handed with AgentTurnConfig.platform_tools only, to an executor that also declares agent.platform_tools, when the turn's agent enables a platform tool offered to brains on a machine (web_search, web_fetch). The token is bound to the org, the session, the turn, this machine and the turn's epoch, lives 1 hour and is renewed with tools_token.refresh; with it the endpoint lists and runs only the turn's platform_tools (any other tool name answers invalid params), so it can be handed to a tenant executor: it never reaches a machine tool. An executor that does not declare it gets neither the credential nor those tools and its turns run as before.
	PlatformCredentials []string `json:"platform_credentials,omitempty"`
	// The executor runs custom tools defined by the platform agent: it emits agent.custom_tool_use for a call to one and waits for agent.custom_tool_result. The platform sends the definitions of the turn's agent with every turn.start (AgentTurnConfig.custom_tools, contract 1.7.0) and only to an executor that declares this member. Without it the platform never sends agent.custom_tool_result and answers a user.custom_tool_result for the session with an error; a turn of an agent that has custom tools sent to an executor without it ends failed with session.error (bma_error_code custom_tools_unsupported), never with the tools silently dropped.
	CustomTools bool `json:"custom_tools,omitempty"`
	// Contract 1.8.0. The executor's brain offers the model the host tools a turn.start declares (AgentTurnConfig.host_tools) and runs them through the turn's tools endpoint. Without it the platform does not send host_tools, and a session whose hands machine has computer use gets no computer use tools from this brain. Absent means false.
	HostTools bool `json:"host_tools,omitempty"`
	// Contract 1.14.0. The executor's brain offers the model the MCP tools a turn.start declares (AgentTurnConfig.mcp_tools), runs them through the turn's tools endpoint under their name, and reports each call as agent.mcp_tool_use and agent.mcp_tool_result (not agent.tool_use). Without it the platform does not send mcp_tools, and a turn of an agent whose mcp_toolset enables tools, sent with tools_mcp_* to this executor, ends failed with session.error (bma_error_code mcp_tools_unsupported), never with the tools silently dropped. An executor that runs its tools itself (no tools_mcp_* in turn.start) is never sent the agent's MCP tools, declared or not, and its turns run without them. Absent means false.
	MCPTools bool `json:"mcp_tools,omitempty"`
	// Contract 1.26.0. The executor's brain offers the model the platform tools a turn.start declares (AgentTurnConfig.platform_tools), runs them through the turn's tools endpoint under their name, reports each call as agent.tool_use and agent.tool_result, and copies the files of the answer's structuredContent.files into agent.tool_result.bma_files. Without it the platform does not send platform_tools and the turn runs without them (they are added by the platform, not declared tools of the executor). Absent means false. Contract 2.4.0: on an executor whose brain runs its tools on its own machine, with platform_credentials platform_tools, the tools endpoint of those calls is platform_tools_mcp_url with platform_tools_mcp_token; only these calls leave the machine.
	PlatformTools bool `json:"platform_tools,omitempty"`
	// Deprecated: one hosted agent. Use harnesses; an executor that sets both lists this one in harnesses too.
	Harness *AgentHarnessCapability `json:"harness,omitempty"`
	// Every third-party agent the executor can host, by distinct id (for example dsh and claude-code). The platform picks one per turn with AgentTurnConfig.harness; an executor declares only agents that are installed and passed their self-check.
	Harnesses []AgentHarnessCapability `json:"harnesses,omitempty"`
	// Accepts exact, input-bound selected skill documents and reports their installed versions in TurnStartResult.effective.input_skill_receipt. Absent or false: do not send selected skills.
	InputSkills bool `json:"input_skills,omitempty"`
	// Contract 1.22.0. The executor keeps its working log of a session (the events it forwards, its local markers, its copy of the inputs, the highest local sequence the platform acknowledged) on the platform with working_log.read and working_log.append instead of its own disk, so that any instance of a brain fleet can go on with the session (ADR-0083). Informational: the platform serves the methods to the session's brain whether or not it declares the member.
	WorkingLog bool `json:"working_log,omitempty"`
	// Contract 1.19.0. Explicit idle session.compact and session.compact_cancel with durable versioned receipts. Absent means unsupported. The executor reserves the session independently of ordinary turns, preserves original history, and publishes replacement context only after durable success. It must not declare this before the complete maintenance contract is implemented.
	ContextMaintenance bool `json:"context_maintenance,omitempty"`
}

AgentCapability agent capability. Present with enabled=true when the executor runs a complete agent and accepts turn.start, turn.input, turn.cancel, session.close and interaction.response (and agent.custom_tool_result when custom_tools is true).

type AgentCustomToolResultParams added in v1.3.0

type AgentCustomToolResultParams struct {
	SessionID string `json:"session_id"`
	// The event_id of the agent.custom_tool_use this result answers.
	ToolUseID string         `json:"tool_use_id"`
	Content   []ContentBlock `json:"content"`
	// The user's application reports the call failed; the content explains why.
	IsError bool `json:"is_error,omitempty"`
}

AgentCustomToolResultParams is the params object of agent.custom_tool_result.

type AgentCustomToolUseEvent added in v1.3.0

type AgentCustomToolUseEvent struct {
	Type  string         `json:"type"`
	Name  string         `json:"name"`
	Input map[string]any `json:"input"`
}

AgentCustomToolUseEvent A custom tool the local agent is calling: a tool the user's application runs and answers (capability agent.custom_tools). Its event_id is the tool_use_id. The platform shows the session as waiting (session.status_idle with stop_reason requires_action naming the event) and delivers the user's result with agent.custom_tool_result. The turn stays open while the executor waits: the executor does not send session.status_idle for it. If its own timeout passes first, the executor ends the call with a failed agent.tool_result naming this event.

type AgentError added in v1.4.0

type AgentError struct {
	// Code is an AgentErrorCode value.
	Code    string
	Message string
}

AgentError is an error of RunTurn that names its cause with one of the contract's AgentErrorCode values (AgentErrorCodeAgentUnavailable, AgentErrorCodeAgentAuthRequired, ...): the turn ends failed with session.error of that type, so every agent says the same thing for the same cause. Any other error ends the turn with AgentErrorCodeAgentError.

func (*AgentError) Error added in v1.4.0

func (e *AgentError) Error() string

type AgentErrorInfo

type AgentErrorInfo struct {
	// An AgentErrorCode value; other strings are tolerated (objects accept unknown members) and projected as unknown_error.
	Type    string `json:"type"`
	Message string `json:"message,omitempty"`
}

AgentErrorInfo Typed session error.

type AgentEventRecord

type AgentEventRecord struct {
	SessionID string
	TurnID    string
	EventID   string
	Sequence  int64
	Type      string
	// Event is the event object as sent, for example an AgentMessageEvent.
	Event json.RawMessage
}

AgentEventRecord is one validated durable agent event.

type AgentHandler

type AgentHandler interface {
	// OpenTurn decides whether to accept a turn.start and reports the
	// configuration the agent will actually apply. It runs before turn.start
	// is answered, and the platform answers turn.start with a timeout, so it
	// must be quick: refuse what can be refused for certain (unknown
	// harness, a cwd outside the allowed roots) and leave anything slow, such as
	// starting a process or opening the local conversation, to RunTurn, whose
	// failure ends the turn with session.error (AgentError picks its type) and
	// whose canceled ctx ends it canceled. An *RPCError keeps its
	// code (for example -32001 for a cwd outside the allowed roots).
	OpenTurn(ctx context.Context, params TurnStartParams) (TurnStartResult, error)
	// RunTurn does the turn's work and returns when the turn is over. ctx is
	// canceled by turn.cancel and session.close. A nil error ends the turn as
	// completed, a canceled ctx as canceled, any other error as failed (the
	// SDK emits session.error first).
	RunTurn(ctx context.Context, turn *AgentTurn) error
	// CloseSession releases the local conversation after session.close.
	CloseSession(ctx context.Context, sessionID, reason string) error
}

AgentHandler is a complete local agent (model loop and tools) served over the executor protocol. The SDK owns the wire: turn.start/input/cancel, session.close, event ids and sequences, ACK tracking and resend after reconnect, interactions, and the session.status_running / status_idle events that frame every turn.

type AgentHarnessCapability added in v1.0.0

type AgentHarnessCapability struct {
	// Agent profile id, for example dsh.
	ID string `json:"id"`
	// Installed agent package version.
	Version string `json:"version"`
	// Protocol the executor speaks to the agent, for example acp/1.
	Protocol string `json:"protocol,omitempty"`
	// Name the agent reported about itself (ACP initialize agentInfo.name).
	AgentName string `json:"agent_name,omitempty"`
	// Version the agent reported about itself (ACP initialize agentInfo.version); may differ from version.
	AgentVersion string `json:"agent_version,omitempty"`
	// token: agent.message and agent.thinking stream as deltas. committed: each message arrives whole once the agent committed it.
	Streaming string `json:"streaming,omitempty"`
	// A conversation continues in a new agent process (ACP session/resume).
	SessionResume bool `json:"session_resume,omitempty"`
	// A conversation can be reloaded with its history replayed (ACP session/load).
	SessionLoad bool `json:"session_load,omitempty"`
	// The agent accepts image input.
	ImageInputs bool `json:"image_inputs,omitempty"`
	// Which tool calls reach interaction.request. full: every call the agent's policy asks about. escalation_only: only calls that leave the agent's own sandbox; calls inside it (including workspace writes) are never asked. none: the agent never asks, so platform approval covers no tool call.
	PermissionRelay string `json:"permission_relay,omitempty"`
	// The agent reports typed errors; false means session.error carries agent_error with the agent's text.
	StructuredErrors bool `json:"structured_errors,omitempty"`
	// tokens: the agent reports token usage. context_only: it reports context window occupancy only; usage is metered by the model proxy.
	Usage string `json:"usage,omitempty"`
	// Whose model access the agent uses. platform (or absent): the platform's model endpoint and per-turn credentials (platform_credentials harness_model), models from the platform catalog. owner: only the machine owner's own credentials configured on the machine; the platform never hands this harness harness_model credentials, never routes it through its model proxy and does not bill its model usage; the session's model must be one of this harness's models.
	ModelCredentials string `json:"model_credentials,omitempty"`
	// The models this agent offers when model_credentials is owner (for example the Claude Code model IDs), each with its thinking levels. The platform accepts AgentTurnConfig.model and thinking_level for a session on this harness only from this list and passes them unchanged. Ignored for model_credentials platform.
	Models []AgentModel `json:"models,omitempty"`
}

AgentHarnessCapability What the third-party agent the executor hosts (for example an ACP agent) supports; an omitted boolean is false. Sent with executor.capabilities.update once the agent has started; absent until then and after a reconnect until the next turn. Informational: the platform records it and reflects it in the session harness capabilities.

type AgentInputBlock

type AgentInputBlock struct {
	Type      string `json:"type"`
	Text      string `json:"text,omitempty"`
	FileID    string `json:"file_id,omitempty"`
	Name      string `json:"name,omitempty"`
	MimeType  string `json:"mime_type,omitempty"`
	SizeBytes int64  `json:"size_bytes,omitempty"`
	// input_ref only: the platform input id to fetch (ain_; in session.history the user.message event id).
	InputID string `json:"input_id,omitempty"`
	// input_ref only: lowercase hex SHA-256 of the fetched JSON array.
	SHA256 string `json:"sha256,omitempty"`
}

AgentInputBlock One block of user input. A file block references a platform session file by file_id; the executor downloads it through the executor files API. File bytes never travel on the control channel. An input_ref block (contract 1.7.0, only to an executor that declared agent.input_by_reference) is the only block of an input the platform did not inline: input_id, size_bytes and sha256 describe the AgentInputBlock array that GET /v1/machines/{machine_id}/inputs/{input_id} answers.

type AgentMCPToolResultEvent

type AgentMCPToolResultEvent struct {
	Type         string         `json:"type"`
	MCPToolUseID string         `json:"mcp_tool_use_id"`
	Content      []ContentBlock `json:"content,omitempty"`
	IsError      bool           `json:"is_error,omitempty"`
}

AgentMCPToolResultEvent Result of an agent.mcp_tool_use.

type AgentMCPToolUseEvent

type AgentMCPToolUseEvent struct {
	Type                string               `json:"type"`
	MCPServerName       string               `json:"mcp_server_name"`
	Name                string               `json:"name"`
	Input               map[string]any       `json:"input"`
	EvaluatedPermission *EvaluatedPermission `json:"evaluated_permission,omitempty"`
}

AgentMCPToolUseEvent An MCP tool the local agent is calling. Its event_id is the mcp_tool_use_id. A brain reports a call of an AgentTurnConfig.mcp_tools entry with this event (mcp_server_name and name: the entry's mcp_server_name and tool_name), never as agent.tool_use (contract 1.14.0).

type AgentMessageEvent

type AgentMessageEvent struct {
	Type    string         `json:"type"`
	Content []ContentBlock `json:"content"`
}

AgentMessageEvent Final assistant text. Streaming previews for the same event_id arrive earlier as session.event_delta.

type AgentModel

type AgentModel struct {
	ID          string `json:"id"`
	DisplayName string `json:"display_name,omitempty"`
	// Thinking or reasoning-effort levels the model accepts, lowest first. Use the reasoning effort values of the model APIs: none, minimal, low, medium, high, xhigh, max (OpenAI reasoning_effort; Claude Code effort levels are low, medium, high, xhigh, max). An executor that drives an OpenAI-compatible endpoint sends the level as reasoning_effort unchanged. Empty or absent: the model takes no level and AgentTurnConfig.thinking_level is not applied.
	ThinkingLevels []string `json:"thinking_levels,omitempty"`
	// Level applied when the turn names none; one of thinking_levels. Absent: no level is sent and the model uses its own default.
	DefaultThinkingLevel string `json:"default_thinking_level,omitempty"`
}

AgentModel One model the local agent can run.

type AgentModelTokens added in v1.3.0

type AgentModelTokens interface {
	RefreshModelToken(ctx context.Context, executor *Executor, params ModelTokenRefreshParams) (ModelTokenRefreshResult, error)
}

AgentModelTokens is implemented by an AgentPlatform that answers model_token.refresh: a fresh model credential for a running turn. A returned *RPCError is sent as is. Without it the method is not handled.

type AgentPlatform

type AgentPlatform interface {
	// AckedSequence is the highest contiguous sequence already persisted for
	// the session (0 when none). The harness asks once per session per process
	// so a restarted platform keeps deduplicating resent events.
	AckedSequence(ctx context.Context, sessionID string) (int64, error)
	// AgentEvent persists one durable event and returns once it is durable;
	// only then is it acknowledged to the executor and may be published to
	// clients. It is called once per event, in sequence order per session.
	AgentEvent(ctx context.Context, executor *Executor, event AgentEventRecord) error
	// AgentDelta relays a transient preview (Anthropic event_start /
	// event_delta). Never persisted.
	AgentDelta(executor *Executor, delta SessionEventDeltaParams)
	// InteractionRequested opens (or, for a repeated interaction_id, returns)
	// the platform interaction and returns its id. Answer it later with
	// Executor.RespondInteraction.
	InteractionRequested(ctx context.Context, executor *Executor, request InteractionRequestParams) (string, error)
	// InteractionCanceled closes the platform interaction without an answer.
	InteractionCanceled(ctx context.Context, executor *Executor, cancel InteractionCancelParams) error
}

AgentPlatform is the platform half of the agent capability: where durable agent events, previews and interactions go. BMA implements it on top of its session event log and agent interactions; tests and local tools can keep everything in memory.

type AgentSessionCompactor added in v1.6.37

type AgentSessionCompactor interface {
	CompactSession(context.Context, SessionCompactParams) (SessionCompactResult, error)
	// Persist a fence against late publication, or return the applied receipt.
	// The SDK owns Settled and overwrites that field after this returns.
	CancelSessionCompaction(context.Context, SessionCompactCancelParams) (SessionCompactCancelResult, error)
}

AgentSessionCompactor is optional. Implementations own durable context and receipt publication; a failed preparation must keep the original context. No tool may run and the operation must honor cancellation before publication.

type AgentSessionHistory added in v1.15.0

type AgentSessionHistory interface {
	SessionHistory(ctx context.Context, executor *Executor, params SessionHistoryParams) (SessionHistoryResult, error)
}

AgentSessionHistory is implemented by an AgentPlatform that answers session.history: a page of a session's conversation before a turn's opening input. A returned *RPCError is sent as is. Without it the method is not handled (-32601: the executor's agent has no history to rebuild from).

type AgentSessionSuspender added in v1.5.0

type AgentSessionSuspender interface {
	// MaxResidentSessions is the limit; 0 means unbounded.
	MaxResidentSessions() int
	// SuspendSession releases the resources of an idle session and keeps its
	// conversation so that a later OpenTurn can continue it. It must be safe
	// for a session the handler no longer has. An error keeps the session
	// resident; the SDK then suspends the next candidate.
	SuspendSession(ctx context.Context, sessionID string) error
}

AgentSessionSuspender is an optional extension of AgentHandler for a handler that holds local resources per session (a process, a conversation in memory, a Core session). The SDK counts two things apart:

  • running turns, bounded by AgentCapability.MaxSessions: a turn.start that would exceed it answers executor_busy, and the slot is free again when the turn ends;
  • resident sessions, bounded by MaxResidentSessions: sessions whose resources are held, running or idle. A session with no running turn costs no slot; it only keeps its resources until it is the least recently used idle one when the limit is passed.

Past the limit the SDK calls SuspendSession for the least recently used idle session before it opens the next turn. A suspended session is not ended: the platform still has it, its events keep their numbering, and its next turn.start goes to OpenTurn like any other, where the handler loads the conversation again (turn.start carries the executor_session_ref). Without this extension resident sessions are not bounded.

type AgentThinkingEvent

type AgentThinkingEvent struct {
	Type    string         `json:"type"`
	Content []ContentBlock `json:"content,omitempty"`
}

AgentThinkingEvent Model thinking. content may be empty when the model only reports that it thought.

type AgentToolResultEvent

type AgentToolResultEvent struct {
	Type      string         `json:"type"`
	ToolUseID string         `json:"tool_use_id"`
	Content   []ContentBlock `json:"content,omitempty"`
	IsError   bool           `json:"is_error,omitempty"`
	// Contract 1.26.0. Session files the call created (a platform tool's structuredContent.files, for example the images of generate_image), so a client shows them with the call. Absent: none.
	BmaFiles []ToolResultFile `json:"bma_files,omitempty"`
}

AgentToolResultEvent Result of an agent.tool_use.

type AgentToolUseEvent

type AgentToolUseEvent struct {
	Type                string               `json:"type"`
	Name                string               `json:"name"`
	Input               map[string]any       `json:"input"`
	EvaluatedPermission *EvaluatedPermission `json:"evaluated_permission,omitempty"`
}

AgentToolUseEvent A built-in or custom tool the local agent is calling. Its event_id is the tool_use_id.

type AgentTurn

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

AgentTurn is the handle RunTurn uses to talk to the platform.

func (*AgentTurn) ApprovalID added in v1.4.0

func (t *AgentTurn) ApprovalID(callID string) string

ApprovalID is the interaction id to ask a tool call's approval under (InteractionRequestParams.InteractionID) and to present with the call (RouteCall.ApprovalID): "appr_" and 24 hex characters of sha256 over session, turn and call id (ADR-0027). It is the same after a reconnect or an executor restart, so the platform keeps one interaction per call and an approval already answered is not asked again.

func (*AgentTurn) CancelInteraction

func (t *AgentTurn) CancelInteraction(interactionID, reason string)

CancelInteraction withdraws an open interaction, for example after the user answered it in the local UI (InteractionCancelReasonResolvedLocally). A later interaction.response for it answers accepted=false.

func (*AgentTurn) Delta

func (t *AgentTurn) Delta(eventID, eventType string, index int64, text string)

Delta streams a transient preview of the durable event eventID. It is best-effort: dropped while disconnected and never resent.

func (*AgentTurn) Emit

func (t *AgentTurn) Emit(event any) (string, error)

Emit queues one durable event (one of the Agent*Event / Session*Event structs) and returns its event id. Delivery is asynchronous, ordered and at-least-once; the platform deduplicates by event id.

func (*AgentTurn) EmitWithID

func (t *AgentTurn) EmitWithID(eventID string, event any) (string, error)

EmitWithID is Emit with a caller-chosen event id (from NewEventID).

func (*AgentTurn) EnvironmentInfo added in v1.4.0

func (t *AgentTurn) EnvironmentInfo() *EnvironmentInfo

EnvironmentInfo describes the hands machine when brain and hands are on different machines (turn.start config.environment_info, contract 1.4.0); nil when the tools run on this machine.

func (*AgentTurn) Flush

func (t *AgentTurn) Flush(ctx context.Context) error

Flush waits until every event emitted so far is acknowledged.

func (*AgentTurn) Inputs

func (t *AgentTurn) Inputs() <-chan TurnInputParams

Inputs delivers turn.input messages in arrival order.

func (*AgentTurn) NewEventID

func (t *AgentTurn) NewEventID() string

NewEventID returns a fresh event id, for a message that is streamed with Delta before it is emitted with EmitWithID.

func (*AgentTurn) Params

func (t *AgentTurn) Params() TurnStartParams

func (*AgentTurn) RefreshModelToken added in v1.3.0

func (t *AgentTurn) RefreshModelToken(ctx context.Context) (ModelTokenRefreshResult, error)

RefreshModelToken asks the platform for a fresh model credential for this turn (Client.RefreshModelToken).

func (*AgentTurn) RefreshToolsToken added in v1.4.0

func (t *AgentTurn) RefreshToolsToken(ctx context.Context) (ToolsTokenRefreshResult, error)

RefreshToolsToken asks the platform for a fresh credential for this turn's platform tool calls (Client.RefreshToolsToken).

func (*AgentTurn) RequestCustomTool added in v1.3.0

func (t *AgentTurn) RequestCustomTool(ctx context.Context, name string, input map[string]any) (string, AgentCustomToolResultParams, error)

RequestCustomTool emits agent.custom_tool_use for a tool the user's application runs (capability CustomTools) and waits for the platform's agent.custom_tool_result. It returns the call's event id with the result so the agent can reference it. The turn stays open while it waits: do not end it, and do not emit session.status_idle. When ctx ends first it returns ctx.Err() and a later result answers accepted=false; to give up on a call the agent emits a failed AgentToolResultEvent naming the returned id (empty when the event could not be emitted). Use ctx with a timeout for an executor-side limit.

func (*AgentTurn) RequestInteraction

func (t *AgentTurn) RequestInteraction(ctx context.Context, params InteractionRequestParams) (InteractionResponseParams, error)

RequestInteraction asks the platform for an approval or an answer and waits for interaction.response. It flushes first so the platform already has the agent.tool_use the request references. When ctx ends or ExpiresAt passes, it withdraws the interaction with interaction.cancel; an expiry returns outcome expired, which the agent must treat as a deny. The answer is advice: the local agent still makes the final decision.

func (*AgentTurn) SessionID

func (t *AgentTurn) SessionID() string

func (*AgentTurn) Tools added in v1.4.0

func (t *AgentTurn) Tools() ToolRoute

Tools returns the route this turn's tool calls go through when the hands are on another machine (ADR-0029), or nil when they are this machine.

A turn started with the platform's tools endpoint (turn.start metadata tools_mcp_url and tools_mcp_token, contract 1.4.0; the executor declared AgentCapability.platform_credentials brain_tools) gets a PlatformToolRoute: every call goes to the platform's tool gateway and none may run on this machine. The token stays in memory and is replaced through tools_token.refresh before it expires. One of the two metadata keys without the other gives a route that refuses every call (tools_unavailable) instead of nil, so a half credential never turns into a local run.

nil means the turn carries no tools endpoint: the brain's tools run here, on the brain's own account (ACPAgent does it through Core with its own re-checks; a brain of your own runs them itself). The route is the same value for every call of the turn.

func (*AgentTurn) TurnID

func (t *AgentTurn) TurnID() string

type AgentTurnConfig

type AgentTurnConfig struct {
	// Model the turn runs on. When the capability lists models it must be one of models[].id: an executor answers any other with -32602 invalid params and never substitutes another model. When the capability lists no models the executor picks its own model and ignores this member; effective then reports the model it used.
	Model string `json:"model,omitempty"`
	// Reasoning effort of the turn: one of the thinking_levels of the turn's model (AgentModel). Absent: the model's default_thinking_level, or none. A level the model does not list answers -32602 invalid params; for a model that lists no levels the member is ignored and effective omits it.
	ThinkingLevel string `json:"thinking_level,omitempty"`
	// One of the capability permission_modes. Absent: the executor's default mode. turn.start metadata tool_policy, when present, refines the permission of single tools on top of the mode.
	PermissionMode string `json:"permission_mode,omitempty"`
	// Working directory on the executor host. The executor rejects a directory outside its allowed roots with -32001 forbidden. When turn.start metadata carries tools_mcp_* (brain and hands on different machines, contract 1.4.0) cwd is a path on the hands machine: the executor does not check it against its own allowed roots and does not create a workspace for it on this machine; the hands machine's own policy applies when a tool runs there.
	Cwd string `json:"cwd,omitempty"`
	// Contract 1.4.0, optional. Sent only when brain and hands are on different machines (turn.start metadata carries tools_mcp_*): describes the hands machine, so the brain can tell the model where its tools run. Omitted when brain and hands are the same machine, and absent from TurnStartResult.effective.
	EnvironmentInfo *EnvironmentInfo `json:"environment_info,omitempty"`
	// Extra system instructions from the platform agent definition.
	System string `json:"system,omitempty"`
	// Contract 1.8.0. Requested only, sent only to an executor that declared agent.host_tools and only with tools_mcp_* in metadata. Tools of the session's hands machine the brain offers the model next to its own tools: computer_observe and computer_action when the hands machine declared computer_use, absent otherwise (absent = none, so a session without a desktop never sees them). Every entry is offered under its name and input_schema exactly, and runs like the brain's other tools through tools_mcp_url under that name. Its permission is metadata tool_policy[name] when present, else the entry's permission: an ask call is approved once per call (interaction kind permission, the brain's deterministic interaction id). A tool result image (an image content block of the tools endpoint answer) reaches the model with that result as an image and is never written to a session event (agent.tool_result carries the text only); the brain keeps the images of the session's such calls in memory and prunes them in batches: once more than 28 calls have images, the oldest 25 drop together (keep 3, interval 25), so the request prefix stays unchanged between two prunes (pruned calls, and every call after a brain restart, keep their text). An invalid entry (a name that is not one of these two tools, a repeated name, a missing description, an input_schema that is not an object schema, a permission other than allow or ask) answers -32602 invalid params. The set may differ from turn to turn; a turn sees the set of its own turn.start.
	HostTools []HostTool `json:"host_tools,omitempty"`
	// Contract 1.14.0. Requested only, sent only to an executor that declared agent.mcp_tools and only with tools_mcp_* in metadata (omitted when the turn has none). The enabled tools of the MCP servers of the turn's agent version (official mcp_servers with an mcp_toolset): the platform connects each server with its credential (the server's bma_auth, else the session's vaults), lists its tools when the turn starts and evaluates the mcp_toolset permission of each. The brain offers every entry to the model under name with input_schema exactly, next to its own tools, and runs a call like its other tools through tools_mcp_url under that name; the brain never connects an MCP server itself and never sees its credential. A server that could not be listed contributes no entry; the platform reports it as session.error (mcp_connection_failed_error or mcp_authentication_failed_error) and the turn goes on. A name that collides with one of the brain's own tools answers -32602 invalid params. The set may differ from turn to turn; a turn sees the set of its own turn.start.
	MCPTools []MCPToolDefinition `json:"mcp_tools,omitempty"`
	// Contract 1.26.0. Requested only, sent only to an executor that declared agent.platform_tools and only with tools_mcp_* in metadata (omitted when the turn has none). Tools the platform runs itself, on no machine, that the turn's agent enables (generate_image: agent tools entry bma_image_generation_20261201 and a session model route that lists image models). The brain offers every entry to the model under name with input_schema exactly (the platform fills turn-specific values such as the generate_image model enum), next to its own tools, and runs a call like its other tools through tools_mcp_url under that name, with the same _meta approval, idempotency key and sync_wait_ms; ask is asked once per call (interaction kind permission). A result image (an image content block of the answer, the preview of a generated image) reaches the model with that result only when the model accepts images and is never written to a session event; the brain copies structuredContent.files of the answer into agent.tool_result.bma_files. A name that collides with one of the brain's own tools answers -32602 invalid params. The set may differ from turn to turn; a turn sees the set of its own turn.start. Contract 2.4.0: also sent, with platform_tools_mcp_* in metadata instead, to a brain that runs its tools on the session's machine (its executor declared agent.platform_tools and platform_credentials platform_tools), with only web_search and web_fetch; that brain runs these entries through platform_tools_mcp_url exactly like a brain with tools_mcp_* runs them through tools_mcp_url (same _meta, approval, idempotency key and events) and keeps running every other tool on its machine.
	PlatformTools []PlatformTool `json:"platform_tools,omitempty"`
	// Id of the hosted agent (one of the capability harnesses[].id) the turn runs on. Omitted: the executor's only harness. An id the executor does not host answers -32012 capability_unavailable.
	Harness string `json:"harness,omitempty"`
	// Requested only. Exact authorized skill revisions for this opening input; never mutates session defaults. Requires agent.input_skills. The platform revalidates grants and the session frozen subset before dispatch.
	InputSkills []InputSkillDocument `json:"input_skills,omitempty"`
	// Effective only. Returned after exact selected skill bytes have been installed for the opening input. Missing or mismatched receipt is not successful skill preparation.
	InputSkillReceipt *InputSkillReceipt `json:"input_skill_receipt,omitempty"`
	// Contract 1.7.0. Requested only. The custom tools of the turn's agent version, sent with every turn.start and only to an executor that declared agent.custom_tools (omitted when the agent has none). The executor exposes exactly these next to its own tools for the turn; a name that collides with one of its own tools answers -32602 invalid params.
	CustomTools []CustomToolDefinition `json:"custom_tools,omitempty"`
}

AgentTurnConfig Requested (turn.start) or effective (TurnStartResult.effective) turn configuration. Every member is optional in a request; the executor reports the values it actually applied.

type ArtifactCapability

type ArtifactCapability struct {
	Upload   bool  `json:"upload"`
	MaxBytes int64 `json:"max_bytes,omitempty"`
}

ArtifactCapability v1.1 artifact upload (POST /v1/environments/{environment_id}/artifacts; legacy alias POST /v1/executors/artifacts). Environment-scoped executors only.

type ArtifactRef

type ArtifactRef struct {
	ArtifactID string `json:"artifact_id"`
	Name       string `json:"name,omitempty"`
	MimeType   string `json:"mime_type"`
	SizeBytes  int64  `json:"size_bytes"`
	// sha256:<hex> of the content.
	Digest    string `json:"digest"`
	CreatedAt string `json:"created_at,omitempty"`
}

ArtifactRef Artifact reference returned by POST /v1/environments/{environment_id}/artifacts (legacy alias POST /v1/executors/artifacts) and listed in tool.result artifacts (v1.1 §6.5).

func NewArtifactRef

func NewArtifactRef(artifactID, name, mimeType string, sizeBytes int64) ArtifactRef

NewArtifactRef builds an artifact reference for tool.result.

type BashInput added in v1.0.0

type BashInput struct {
	// Shell command line.
	Command string `json:"command"`
	// Working directory, relative to the session workspace.
	Cwd string `json:"cwd,omitempty"`
	// Per-call timeout; the executor default applies when absent.
	TimeoutMS int64 `json:"timeout_ms,omitempty"`
	// Extra environment variables.
	Env map[string]string `json:"env,omitempty"`
}

BashInput bash input: run command with a login shell.

type BashResult added in v1.0.0

type BashResult struct {
	Stdout   string
	Stderr   string
	ExitCode int
	// Truncated reports that the handler already cut the output short.
	Truncated bool
}

BashResult is a finished command, rendered as Core renders it.

func (BashResult) Output added in v1.0.0

func (r BashResult) Output() ToolOutput

Output renders stdout and stderr (when not empty) and `exit_code: N`, as Core does. Output larger than DefaultCoreInlineResultBytes, or marked Truncated, is cut to Core's preview: half the limit of stdout, a quarter of stderr, and `exit_code: N (output truncated to fit the result; M bytes total)`.

type BrainAdapter added in v1.6.4

type BrainAdapter interface {
	// Start starts and checks the brain (its process, pinned version and tool
	// catalog) and reports what it can do. It is called once, before any Open.
	// Options the brain cannot honor (BrainEnv.PlatformModel for a brain on its
	// owner's credentials, BrainEnv.Models for a brain without ModelChoice) are
	// refused before anything starts.
	Start(ctx context.Context, env BrainEnv) (BrainCapabilities, error)
	// Open makes the brain's conversation of a platform session ready for a
	// turn: a new conversation named req.New (req.Ref empty), the conversation
	// req.Ref names, or req.Current when that is still ready. A conversation
	// to resume that the brain no longer holds (its local state is gone) is
	// ErrConversationLost, returned before anything of it is created: the
	// brain holds it only when its own state for that handle exists, and the
	// host then asks for a new one. The handle of a conversation is the
	// executor_session_ref (BrainSession.Ref).
	Open(ctx context.Context, req BrainOpen) (BrainSession, error)
	// Close stops the brain and everything it started.
	Close() error
}

BrainAdapter drives one kind of local brain.

func NewClaudeCLIAdapter added in v1.6.5

func NewClaudeCLIAdapter(opts ClaudeCLIOptions) BrainAdapter

NewClaudeCLIAdapter is the adapter of the official claude CLI.

func NewCodexAppServerAdapter added in v1.6.17

func NewCodexAppServerAdapter() BrainAdapter

NewCodexAppServerAdapter is the adapter of the official codex CLI. Its Command is the pinned codex binary, optionally followed by -c settings of the owner's model provider (codexOwnerSettings); ACPAgentOptions.Env must set CODEX_HOME to the BMA Codex home.

type BrainCall added in v1.6.4

type BrainCall struct {
	// ID is the call's id in the brain's own transcript (ACP toolCallId,
	// Claude tool_use_id): the call_id of its approval id.
	ID    string
	Name  string
	Input map[string]any
}

BrainCall is one tool call of the brain, by the platform's tool name.

type BrainCapabilities added in v1.6.4

type BrainCapabilities struct {
	// Harness is the agent capability's harness entry (id, versions,
	// protocol, streaming, permission relay, session load, usage).
	Harness AgentHarnessCapability
	// ModelCredentials is BrainModelPlatform (the brain's model requests go
	// through the host's route, BrainInput.Model) or BrainModelOwner (the
	// brain uses only its node owner's own credentials).
	ModelCredentials string
	// ModelChoice: a turn may choose the model (config.model) and the brain
	// runs it. Without it config.model and thinking_level are ignored.
	ModelChoice bool
	// Models are the models the brain itself reports, for a brain on its
	// owner's credentials (nil: the host's ACPAgentOptions.Models).
	Models []AgentModel
	// ThinkingLevels are the reasoning effort values the brain takes.
	ThinkingLevels []string
	// ImageInputs: the brain takes user images.
	ImageInputs bool
	// HostTools: the brain offers a turn's host tools (BrainOpen.Tools).
	HostTools bool
	// CustomTools: the brain offers a turn's custom tools (BrainOpen.Tools).
	CustomTools bool
	// InputSkills: the brain takes the selected skills of an input (BrainInput.Skills).
	InputSkills bool
	// Steering: BrainSession.Steer hands a running Prompt its input at the
	// brain's next step boundary; the host declares agent.steering.
	Steering bool
	// HistoryRebuild: a new conversation opened with BrainOpen.History
	// starts from that conversation (the brain's own transcript of it), so
	// the host rebuilds a session it holds no conversation for from the
	// platform's log and declares agent.history_rebuild.
	HistoryRebuild bool
}

BrainCapabilities is what a started brain can do. The host reads these fields only; it never asks which brain it is.

type BrainDecision added in v1.6.4

type BrainDecision struct {
	// Outcome is BrainAllow, BrainDeny or BrainCanceled (the turn ended or
	// the interaction expired first).
	Outcome string
	// Message is the refusal the model reads (deny only).
	Message string
}

BrainDecision answers a permission request.

type BrainEnv added in v1.6.4

type BrainEnv struct {
	// Command is the brain's argv; Command[0] is absolute.
	Command  []string
	Env      []string
	StateDir string
	// RunAs is the identity the brain process runs as (CoreOptions.RunAs).
	RunAs *RunAs
	// PlatformModel and Upstream are the model routes the host can hand a
	// turn (BrainInput.Model); an adapter whose brain uses only its owner's
	// credentials refuses PlatformModel.
	PlatformModel bool
	Upstream      ACPModelUpstream
	// Models are the models the host lets a turn choose (ACPAgentOptions.Models).
	Models      []AgentModel
	CancelGrace time.Duration
	KillGrace   time.Duration
	// HarnessID is the declared harness id ("" for the adapter's own).
	HarnessID string
	Log       func(LogLevel, string, error)
}

BrainEnv is what the host gives an adapter at Start.

type BrainHost added in v1.6.4

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

BrainHost hosts a local brain through a BrainAdapter; see the comment at the top of brain_host.go.

func NewBrainHost added in v1.6.4

func NewBrainHost(ctx context.Context, adapter BrainAdapter, opts ACPAgentOptions) (*BrainHost, error)

NewBrainHost starts the brain through adapter (BrainAdapter.Start) and returns its host. Serve it with client.ServeAgent(host, host.Capability()).

func (*BrainHost) Capability added in v1.6.4

func (a *BrainHost) Capability() AgentCapability

Capability is the agent capability to serve: one harness, in harnesses[] and in the deprecated harness member.

func (*BrainHost) Close added in v1.6.4

func (a *BrainHost) Close() error

Close stops the brain.

func (*BrainHost) CloseSession added in v1.6.4

func (a *BrainHost) CloseSession(ctx context.Context, sessionID, _ string) error

func (*BrainHost) MaxResidentSessions added in v1.6.4

func (a *BrainHost) MaxResidentSessions() int

MaxResidentSessions implements AgentSessionSuspender.

func (*BrainHost) OpenTurn added in v1.6.4

func (a *BrainHost) OpenTurn(ctx context.Context, params TurnStartParams) (TurnStartResult, error)

func (*BrainHost) RunTurn added in v1.6.4

func (a *BrainHost) RunTurn(ctx context.Context, turn *AgentTurn) error

func (*BrainHost) SuspendSession added in v1.6.4

func (a *BrainHost) SuspendSession(ctx context.Context, sessionID string) error

SuspendSession implements AgentSessionSuspender: it releases an idle session's brain conversation (BrainSession.Suspend: the brain frees the memory or process and keeps the conversation) and its Core session. The next OpenTurn of the session loads the conversation again.

type BrainImage added in v1.6.4

type BrainImage struct {
	MimeType string
	Data     []byte
}

BrainImage is one user image, downloaded and checked by the host.

type BrainInput added in v1.6.4

type BrainInput struct {
	InputID string
	Text    string
	Images  []BrainImage
	// ToolPolicy is the turn's metadata.tool_policy (tool to allow, ask or deny).
	ToolPolicy map[string]string
	// Effort is the turn's thinking level ("" for none).
	Effort string
	// Model is where the brain's model requests go, for a brain whose model
	// requests the host forwards (nil otherwise).
	Model *BrainModelRoute
	// Skills are the skills selected for this input (turn.start
	// config.input_skills of the opening input; their bodies are checked):
	// context for this input only.
	Skills []InputSkillDocument
}

BrainInput is one input of a turn.

type BrainModelRoute added in v1.6.4

type BrainModelRoute = acpRoute

BrainModelRoute is where one turn's model requests go: the platform's per-turn credential, or the node owner's Upstream with the turn's model.

type BrainOpen added in v1.6.4

type BrainOpen struct {
	// SessionID is the platform session id.
	SessionID string
	// Ref is the conversation to resume ("" for a new one).
	Ref string
	// New is the handle of the new conversation to create when Ref is empty:
	// "<session id>@<random>", never one this session was answered before.
	New string
	// Current is the conversation the host holds from an earlier turn (nil
	// when none); Open returns it when it is still ready.
	Current BrainSession
	// Cwd is the brain's working directory on this machine.
	Cwd string
	// SystemPrompt is the complete system prompt of the conversation.
	SystemPrompt string
	// Mode is the platform permission mode of the turn.
	Mode string
	// Model is the turn's model ("" when the brain picks its own).
	Model string
	// Effort is the turn's thinking level ("" for none).
	Effort string
	// Metadata is the turn.start metadata (model limits).
	Metadata map[string]string
	// Tools are the turn's tools besides the six (host tools, custom tools).
	Tools []BrainTool
	// History is the session's conversation before this turn, from the
	// platform's log (session.history), for a new conversation (Ref empty)
	// of a brain with BrainCapabilities.HistoryRebuild; nil otherwise. The
	// new conversation starts with it.
	History []SessionHistoryEvent
}

BrainOpen is what a turn asks the conversation to be.

type BrainSession added in v1.6.4

type BrainSession interface {
	// Ref is the executor_session_ref: the id the conversation is resumed by.
	Ref() string
	// Ready reports whether the brain still holds the conversation open.
	Ready() bool
	// Prompt hands the brain one input and returns when the brain is done
	// with it. When ctx ends (turn.cancel, deadline) the adapter makes the
	// brain stop within BrainEnv.CancelGrace, killing it after that, and
	// returns ctx.Err(). Errors carry the contract's stop codes: an
	// *AgentError, or an error whose text starts with "<code>: ".
	Prompt(ctx context.Context, in BrainInput, sink BrainSink) error
	// Steer hands the running Prompt one more input (agent.steering): the
	// brain reads it at its next step boundary, after the results of its
	// current tool calls and before its next model request, and its reply
	// comes in that Prompt. ErrNotSteered: the brain cannot take it now (no
	// Prompt runs, it is ending, the input has what the brain does not take
	// mid-prompt, or the brain never takes input mid-prompt, without
	// BrainCapabilities.Steering); the host prompts it after the running one.
	Steer(ctx context.Context, in BrainInput) error
	// Suspend releases what the conversation holds in the brain; the next
	// Open with its Ref loads it again.
	Suspend(ctx context.Context) error
	// Close ends the conversation in the brain.
	Close(ctx context.Context) error
}

BrainSession is one open conversation of the brain.

type BrainSink added in v1.6.4

type BrainSink interface {
	// Delta streams text or thinking (kind BrainKindMessage or
	// BrainKindThinking) of the brain's message messageID.
	Delta(kind, messageID, text string)
	// Message commits the durable text of the brain's message messageID.
	Message(kind, messageID, text string)
	// ToolUse reports a tool call of the brain, once its input is known.
	// permission is what the brain's own policy evaluated ("allow", "ask"),
	// or "" when the brain applies no policy and the host's decides.
	ToolUse(call BrainCall, permission string)
	// ToolResult reports the end of a tool call the brain reported.
	ToolResult(callID string, content []ContentBlock, isError bool)
	// Permission decides whether the brain may run a call: the turn's tool
	// policy, the host's approver, an earlier decision of the turn, or the
	// platform's user through an interaction.
	Permission(ctx context.Context, call BrainCall) BrainDecision
	// Call runs one tool call through the turn's route (a platform tool, a
	// host tool or a custom tool) and returns its result.
	Call(ctx context.Context, call BrainCall) *RouteResult
}

BrainSink is how an adapter reports the brain's work of one input and asks the host for decisions. The host implements it; an adapter writes no event itself. Calls are safe from any goroutine.

type BrainTool added in v1.6.5

type BrainTool struct {
	Name        string         `json:"name"`
	Description string         `json:"description"`
	Parameters  map[string]any `json:"parameters"`
	// ReadOnly: the tool has no side effects (it may run concurrently).
	ReadOnly bool `json:"readOnly"`
	// Kind is the ACP tool kind (read, other, ...).
	Kind string `json:"kind"`
	// Permission is a host tool's default permission (allow or ask).
	Permission string `json:"permission,omitempty"`
	// Custom marks a custom tool of the agent: the user's application
	// answers it (agent.custom_tool_use); it is never approved.
	Custom bool `json:"-"`
	// Platform marks a platform tool (web_search, web_fetch): the platform
	// runs it through the turn's platform tools endpoint.
	Platform bool `json:"-"`
}

BrainTool is one tool a turn offers the model besides the six platform tools: a host tool (computer use of the session's hands machine, ask_user_question) or a custom tool of the session's agent. The brain offers exactly the six and these, under these names and schemas, and runs every call through BrainSink.Call.

type CallMethod added in v1.0.0

type CallMethod[P, R any] struct{ Method string }

CallMethod is an executor-to-harness request with params P and result R.

func (CallMethod[P, R]) Call added in v1.0.0

func (m CallMethod[P, R]) Call(ctx context.Context, client *Client, params P) (R, error)

Call sends the request on the client's control channel and decodes its result; a JSON-RPC error answer is an *RPCError.

type CallToolOptions added in v1.0.0

type CallToolOptions struct {
	// ToolCallID is the idempotency id of the call; generated when empty.
	ToolCallID string
	DeadlineMS int64
	Permission *ToolPermission
}

CallToolOptions are the optional fields of a typed harness tool call.

type Capabilities

type Capabilities struct {
	Shell       *ShellCapability `json:"shell,omitempty"`
	Files       *FilesCapability `json:"files,omitempty"`
	MCP         *MCPCapability   `json:"mcp,omitempty"`
	Chrome      bool             `json:"chrome,omitempty"`
	ComputerUse bool             `json:"computer_use,omitempty"`
	// v1 boolean or v1.1 DisplayCapability object.
	Display      json.RawMessage         `json:"display,omitempty"`
	Process      *ProcessCapability      `json:"process,omitempty"`
	Artifacts    *ArtifactCapability     `json:"artifacts,omitempty"`
	Terminal     *TerminalCapability     `json:"terminal,omitempty"`
	Skills       *SkillsCapability       `json:"skills,omitempty"`
	Workspace    *WorkspaceCapability    `json:"workspace,omitempty"`
	Agent        *AgentCapability        `json:"agent,omitempty"`
	SessionFiles *SessionFilesCapability `json:"session_files,omitempty"`
	RemoteBrain  *RemoteBrainCapability  `json:"remote_brain,omitempty"`
	Egress       *EgressCapability       `json:"egress,omitempty"`
}

Capabilities Executor capability object. The server only sends a method to an executor that advertised its capability; otherwise the executor answers -32012 capability_unavailable.

type Capability

type Capability struct {
	// Advertise sets the capability bits on the register capabilities.
	Advertise     func(*Capabilities)
	Methods       map[string]Handler
	SessionScoped bool
	// UnscopedMethods are methods of the capability that name no executor
	// session (Request.Session nil), whatever SessionScoped says.
	UnscopedMethods map[string]Handler
	OnSessionEnd    func(*CoreSession)
}

Capability is an extension of the core: a set of methods behind one or more capability bits. The core advertises the bits through Capabilities, routes the methods for every attached brain and, for SessionScoped capabilities, answers session_not_active (-32007) for unknown sessions and calls OnSessionEnd before a session reports session.ended.

func NewProcessCapability

func NewProcessCapability(core *Core, opts ProcessOptions) Capability

NewProcessCapability serves process.start/read/write/interrupt/terminate/list and process.status (v1.1 §3) on core sessions: pipes or a PTY, bounded cursor-addressed output, idempotent starts and writes, timeouts, process group signals, and file transfers and Git credentials through opts. A session's processes are terminated when it stops.

func NewSkillInstallCapability

func NewSkillInstallCapability(install SkillInstaller) (Capability, error)

NewSkillInstallCapability serves skill.install (skills.install) with install. Installs run one at a time.

type ChannelTarget

type ChannelTarget struct {
	Channel   string // ChannelControl or ChannelMCP
	SessionID string
	ServerKey string
}

ChannelTarget names the channel a Dialer opens: the control channel, or the MCP channel of one session.assign mcp_servers entry (?channel=mcp&session_id=&server_key= on WebSocket transports).

type ClaudeCLIOptions added in v1.6.5

type ClaudeCLIOptions struct {
	// Executable is the official claude binary whose digest is checked
	// against the pins (default: ACPAgentOptions.Command[0]). Set it when
	// Command is the owner's launcher that runs that binary.
	Executable string
}

ClaudeCLIOptions configures the Claude adapter.

type Client

type Client struct {
	// Tools has one typed slot per built-in tool: Tools.Bash.Handle(...).
	// Capabilities shell, files and computer_use follow what is registered.
	Tools Tools
	// contains filtered or unexported fields
}

Client is an outbound executor client.

func NewClient

func NewClient(options Options) (*Client, error)

NewClient validates options and returns a disconnected client.

func (*Client) ActiveSessions

func (c *Client) ActiveSessions() []string

ActiveSessions returns the sessions currently assigned to this executor.

func (*Client) ConnectionID

func (c *Client) ConnectionID() string

ConnectionID returns the current connection id.

func (*Client) Done

func (c *Client) Done() <-chan struct{}

Done is closed when the client stops for good: Stop, executor.close, a terminal close code (4004 replaced, 4003 unsupported protocol, ...), a credential rejected on reconnect, or exhausted reconnects.

func (*Client) Err

func (c *Client) Err() error

Err explains Done: nil after Stop or executor.close, ErrReplaced after 4004, ErrCredentialRejected, ErrReconnectExhausted, or the terminal close error.

func (*Client) ExecutorID

func (c *Client) ExecutorID() string

ExecutorID returns the id assigned by executor.register.

func (*Client) OnDrain

func (c *Client) OnDrain(handler DrainHandler)

OnDrain registers the executor.drain handler.

func (*Client) OnSessionAssign

func (c *Client) OnSessionAssign(handler SessionAssignHandler)

OnSessionAssign registers the session.assign handler.

func (*Client) OnSessionStop

func (c *Client) OnSessionStop(handler SessionStopHandler)

OnSessionStop registers the session.stop handler.

func (*Client) OnToolCallAccept

func (c *Client) OnToolCallAccept(accept func(ToolCallParams) error)

OnToolCallAccept registers a check run before a tool.call is acknowledged. An error answers the request instead (a *RPCError keeps its code, for example session_not_active or capability_unavailable) and the tool does not run.

func (*Client) OpenMCPChannel

func (c *Client) OpenMCPChannel(ctx context.Context, sessionID, serverKey string) (*MCPChannel, error)

OpenMCPChannel opens the MCP channel (?channel=mcp on WebSocket transports) with a fresh executor token through Options.Dial. sessionID and serverKey identify the environment-owned MCP server from session.assign.mcp_servers.

func (*Client) RefreshModelToken added in v1.3.0

func (c *Client) RefreshModelToken(ctx context.Context, sessionID, turnID string) (ModelTokenRefreshResult, error)

RefreshModelToken asks the platform for a fresh model credential for the running turn (model_token.refresh, contract 1.3.0): call it before the turn.start model_token expires (ModelTokenRefreshResult.ExpiresAt). A turn that already ended answers an *RPCError with reason turn_inactive; a platform that cannot mint one answers forbidden or model_token_unavailable. It makes one attempt; the caller owns retry and backoff.

func (*Client) RefreshToolsToken added in v1.4.0

func (c *Client) RefreshToolsToken(ctx context.Context, sessionID, turnID string) (ToolsTokenRefreshResult, error)

RefreshToolsToken asks the platform for a fresh credential for the running turn's platform tool calls (tools_token.refresh, contract 1.4.0): call it before the turn.start tools_mcp_token expires (ToolsTokenRefreshResult.ExpiresAt). A turn that already ended, or one that was started again in a newer epoch, answers an *RPCError with reason turn_inactive or forbidden; a platform that cannot mint one answers tools_token_unavailable. It makes one attempt; the caller owns retry and backoff.

func (*Client) ReportToolResult

func (c *Client) ReportToolResult(ctx context.Context, params ToolResultParams) (Ack, error)

ReportToolResult sends tool.result once per tool_call_id, retrying retryable failures (executor_busy, timeout, a disconnect) with exponential backoff across reconnects. A duplicate call for an accepted tool_call_id returns accepted without sending another frame.

func (*Client) ServeAgent

func (c *Client) ServeAgent(handler AgentHandler, capability AgentCapability)

ServeAgent advertises the agent capability and routes the agent methods to handler. Call it before Start.

func (*Client) ServeDesktopControl added in v1.6.5

func (c *Client) ServeDesktopControl(g *DesktopControlGate) error

func (*Client) ServeScreenLive added in v1.6.5

func (c *Client) ServeScreenLive(handler ScreenLiveHandler) error

ServeScreenLive must be configured before Start. It is deliberately limited to a machine-scoped client, not a harness's workspace session.

func (*Client) SessionContext added in v1.1.0

func (c *Client) SessionContext(ctx context.Context, processID string) (SessionContext, error)

SessionContext returns the context of the agent session processID runs for (process.start metadata names it as agent_session_id). It needs a machine-scoped executor (ErrMachineTokenRequired). Results are cached per session; a failure is not.

func (*Client) SessionContextByID added in v1.1.0

func (c *Client) SessionContextByID(ctx context.Context, sessionID string) (SessionContext, error)

SessionContextByID returns the context of an agent session bound to this machine, for capabilities without a process (an agent turn.start carries only the session id). Cached like SessionContext.

func (*Client) SessionEnded

func (c *Client) SessionEnded(ctx context.Context, params SessionEndedParams) (Ack, error)

SessionEnded reports that every process and MCP server for the session has stopped. The session leaves ActiveSessions after the harness accepts.

func (*Client) SessionReady

func (c *Client) SessionReady(ctx context.Context, params SessionReadyParams) (Ack, error)

SessionReady reports that the executor accepted session.assign and has prepared the session. Call it after workspace and MCP setup complete.

func (*Client) Start

Start fetches an executor token, connects, registers, and starts heartbeats. After a failed Start the client may be started again.

func (*Client) State

func (c *Client) State() ConnectionState

State returns the current connection state.

func (*Client) Stop

func (c *Client) Stop(ctx context.Context, reason string) error

Stop sends executor.close, closes the connection, and fails pending calls.

func (*Client) WaitReady added in v1.0.4

func (c *Client) WaitReady(ctx context.Context) error

WaitReady blocks until the executor is registered and the registration stayed open for one heartbeat interval. State() is ready as soon as executor.register returns, but a machine-scoped executor that declared neither the process nor the agent capability is closed with 4002 right after that, so only WaitReady separates a usable executor from a registration that is about to be refused. It returns the error of a client that ended (Err, or ErrClientStopped after Stop) and ctx.Err() on timeout.

type CloseError

type CloseError struct {
	Code   int
	Reason string
}

CloseError is the error Read returns after the peer closed with a code.

func (*CloseError) Error

func (e *CloseError) Error() string

type ComputerActionInput added in v1.0.0

type ComputerActionInput struct {
	Action string `json:"action"`
	// Display to act on.
	Display string `json:"display,omitempty"`
	// [x, y] for click, scroll and the end of drag.
	Coordinate []float64 `json:"coordinate,omitempty"`
	// [x, y] where drag starts.
	StartCoordinate []float64 `json:"start_coordinate,omitempty"`
	// Text to type (any language), or a key or chord such as Return or ctrl+s; for clipboard_write the text to put on the clipboard.
	Text            string `json:"text,omitempty"`
	Button          string `json:"button,omitempty"`
	ClickCount      int64  `json:"click_count,omitempty"`
	ScrollDirection string `json:"scroll_direction,omitempty"`
	ScrollAmount    int64  `json:"scroll_amount,omitempty"`
	// Process id of the target window (with window_id).
	PID int64 `json:"pid,omitempty"`
	// Target window id (with pid); input then goes to that window in the background.
	WindowID int64 `json:"window_id,omitempty"`
	// Contract 1.17.0. Seconds to hold the keys (hold_key) or to wait (wait).
	Duration float64 `json:"duration,omitempty"`
	// Contract 1.17.0. The steps of action batch (each a computer_action input other than batch), run in order; the first failure stops the batch and the rest are not executed. The result reports every step and ends with a screenshot of the last step's target.
	Actions []ComputerActionInput `json:"actions,omitempty"`
}

ComputerActionInput computer_action input, after Anthropic's computer-use tool over the ComputerAction enum. Coordinates are pixels of the last computer_observe screenshot (window-local with pid and window_id). The members after display are contract 1.8.0 (additive). duration and actions are contract 1.17.0: action batch with actions runs those steps in order, stops at the first failure and ends with a screenshot of the last step's target (the screen, or its window).

type ComputerActionRequest added in v1.3.0

type ComputerActionRequest struct {
	// SessionID keeps observation and action in the same driver context.
	SessionID     string
	Action        string
	PID, WindowID int
	Coordinate    *[2]float64
	Start         *[2]float64
	Text          string
	Button        string
	ClickCount    int
	ScrollDir     string
	ScrollAmount  int
	// App is the app open_app opens: a name such as "TextEdit" or a bundle
	// id such as "com.apple.TextEdit".
	App string
	// MenuPath are the menu labels of a menu action, from the menu bar to
	// the item (2-16 labels, each 1-200 characters, trimmed).
	MenuPath []string
	// Duration is how long hold_key holds its keys (contract 1.14.0).
	Duration time.Duration
	// Frame is the screenshot the coordinates refer to, filled by Core: for
	// an action with PID/WindowID the session's last observation of that
	// window, otherwise its last observation. Nil when there was none.
	Frame *ComputerFrame
	// contains filtered or unexported fields
}

ComputerActionRequest is a computer_action call. Coordinates are pixels of the last observation: screen pixels, or window-local ones with PID/WindowID.

type ComputerFrame added in v1.6.9

type ComputerFrame struct {
	PID, WindowID int
	Width, Height int
	Scale         float64
}

ComputerFrame is a screenshot a computer use call's coordinates refer to: the session's last successful observation of the screen (PID and WindowID zero) or of one window. Width and Height are the pixels of the screenshot the model was given (zero when the observation returned no readable image). Scale is the screen pixels per screenshot pixel (1 when the screenshot was not scaled down to fit the model's image limits); Core has already mapped an action's coordinates to screen (or window) pixels with it.

type ComputerInputRecovery added in v1.6.5

type ComputerInputRecovery interface{ RecoverInput(context.Context) error }

ComputerInputRecovery is an optional trusted driver capability. Success must mean all dispatched Agent actions have stopped AND that driver's held input has been cleared. An observation, CLI exit, or human ReleaseAll is not proof.

type ComputerObserveInput added in v1.0.0

type ComputerObserveInput struct {
	// Display to observe.
	Display string `json:"display,omitempty"`
	// Contract 1.8.0. Process id of the window to observe (with window_id).
	PID int64 `json:"pid,omitempty"`
	// Additive. Window id from the window list (with pid).
	WindowID int64 `json:"window_id,omitempty"`
	// Contract 1.17.0. [x0, y0, x1, y1]: the top-left and bottom-right corners, in pixels of the last screenshot of the same target, of the area to return at full resolution (zoom). Coordinates of later actions stay those of the full screenshot.
	Region []float64 `json:"region,omitempty"`
}

ComputerObserveInput computer_observe input. The result is a screenshot (an image content block) with the list of the screen's windows as text. pid and window_id (both or neither, contract 1.8.0) observe one window of that list. region (contract 1.17.0) zooms: the result is that part of the screenshot at full screen resolution.

type ComputerObserveRequest added in v1.3.0

type ComputerObserveRequest struct {
	// SessionID is assigned by Core, not taken from model tool arguments.
	SessionID string
	// PID and WindowID name one window; both zero observes the whole screen.
	PID, WindowID int
	// ImageFormat optionally requests JPEG for a viewer. Empty keeps lossless PNG.
	// Encoding never changes the screenshot dimensions or coordinate space.
	ImageFormat string
}

ComputerObserveRequest is a computer_observe call.

type ComputerUseApprover added in v1.6.3

type ComputerUseApprover interface {
	// NeedsObserveApproval and NeedsActionApproval report whether the user
	// must approve the call. A host that cannot tell should say true.
	NeedsObserveApproval(ctx context.Context, req ComputerObserveRequest) bool
	NeedsActionApproval(ctx context.Context, req ComputerActionRequest) bool
}

ComputerUseApprover is optionally implemented by a ComputerUseBackend whose host decides which computer use calls the user must approve, for example only actions that may send, submit, pay or delete. Without it every call is asked (the tools' declared default). The platform's turn tool_policy and ACPAgentOptions.ToolPolicy still win: a call is let through without asking only while the ask comes from that default, never when either names the tool.

type ComputerUseBackend added in v1.3.0

type ComputerUseBackend interface {
	Observe(ctx context.Context, req ComputerObserveRequest) ([]ContentBlock, error)
	Action(ctx context.Context, req ComputerActionRequest) ([]ContentBlock, error)
}

ComputerUseBackend performs computer use on the machine's interactive desktop. Results are tool result content blocks (an image block carries the screenshot as base64).

type ComputerUsePreflighter added in v1.6.9

type ComputerUsePreflighter interface {
	PreflightObserve(ctx context.Context, req ComputerObserveRequest) error
	PreflightAction(ctx context.Context, req ComputerActionRequest) error
}

ComputerUsePreflighter is optionally implemented by a ComputerUseBackend whose host can refuse a computer use call before anyone is asked to approve it, for example a click that lands on another app or a window on another Space. Core calls it after checking the input and before approval (ComputerUseApprover or the platform's policy) and execution. An error refuses the call: nobody is asked, the backend does not run, and the tool result is an error whose text is "<reason>: <message>" for an *RPCError with a data reason (NewReasonError) and the error's text otherwise. For a platform brain's tool.call the approval happened on the platform before the call arrived, so there the order is check, preflight, execution.

type ComputerVision added in v1.6.9

type ComputerVision string

ComputerVision is whether a model takes images (CoreOptions.ComputerVision).

const (
	// ComputerVisionUnknown: not known; screenshots are sent.
	ComputerVisionUnknown ComputerVision = ""
	// ComputerVisionImages: the model reads images; screenshots are sent.
	ComputerVisionImages ComputerVision = "images"
	// ComputerVisionTextOnly: the model reads text only; screenshots are
	// not sent.
	ComputerVisionTextOnly ComputerVision = "text_only"
)

type ComputerVisionAnswer added in v1.6.9

type ComputerVisionAnswer struct {
	Model  string
	Vision ComputerVision
}

ComputerVisionAnswer is the host's answer. Model names the model in the note the model reads (empty: the query's model, else "this model").

type ComputerVisionQuery added in v1.6.9

type ComputerVisionQuery struct {
	SessionID string
	Model     string
}

ComputerVisionQuery asks CoreOptions.ComputerVision about one session's model. Model is the turn's model for a local brain's turn (BrainHost), empty for a platform brain's tool.call, whose model the host knows from the platform.

type ComputerWindow added in v1.6.9

type ComputerWindow struct {
	PID, WindowID       int
	App, Title          string
	X, Y, Width, Height float64
}

ComputerWindow is a window open_app found on the current desktop.

type Conn

type Conn interface {
	Read(ctx context.Context) ([]byte, error)
	Write(ctx context.Context, frame []byte) error
	// Close ends the connection with a WebSocket-style close code; the peer
	// reads it as a *CloseError.
	Close(code int, reason string) error
	// Subprotocol is the negotiated executor protocol.
	Subprotocol() string
}

Conn is one executor control connection: ordered JSON-RPC text frames in both directions. The protocol does not depend on the transport; the SDK ships WebSocket (cloud, executor dials out), a local socket (Unix domain socket carrying the same WebSocket upgrade) and an in-process pipe.

func NewWebSocketConn

func NewWebSocketConn(ws *websocket.Conn) Conn

NewWebSocketConn wraps an accepted or dialed WebSocket as a Conn.

type ConnectionState

type ConnectionState string

ConnectionState is the executor control channel state (ConnectionState* values).

type ContentBlock

type ContentBlock struct {
	Type       string `json:"type"`
	Text       string `json:"text,omitempty"`
	Data       string `json:"data,omitempty"`
	MimeType   string `json:"mime_type,omitempty"`
	URL        string `json:"url,omitempty"`
	ArtifactID string `json:"artifact_id,omitempty"`
}

ContentBlock Tool result content block. An artifact block carries artifact_id and mime_type instead of text (v1.1 §6.5).

func NewArtifactContentBlock

func NewArtifactContentBlock(ref ArtifactRef) ContentBlock

NewArtifactContentBlock builds the content block that points at an artifact from inside tool.result content.

type Core

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

Core is the executor's execution core ("hands"): bash with process-group cancellation, file tools, a stdio MCP supervisor, per-session cleanup and registered capabilities (process.*, terminal.*, skill.install, ...). It is independent of who drives it: Attach it to one Client per harness ("brain"), whether that is the BMA cloud or a local harness on a local socket, and every brain gets the same protocol behavior.

Isolation: sessions are keyed by (brain, session_id), so two brains may use the same session id without seeing each other; a request can only reach sessions its own brain assigned, and each session has its own workspace, processes and MCP servers. Capacity is shared: MaxSessions across brains, MaxSessionsPerBrain per brain. Bash is not a sandbox: every brain runs as the executor's OS user.

func NewCore

func NewCore(opts CoreOptions) (*Core, error)

NewCore validates options and creates WorkRoot.

func (*Core) Attach

func (c *Core) Attach(brain string, client *Client) error

Attach serves session.assign, session.stop, tool.call and every registered capability method for one brain on client. Call it before client.Start. brain names the harness ("cloud", "local", ...) and must be unique per core.

func (*Core) Capabilities

func (c *Core) Capabilities() Capabilities

Capabilities is what an attached Client should advertise.

func (*Core) Close

func (c *Core) Close()

Close stops every session of every brain without reporting session.ended.

func (*Core) Env

func (c *Core) Env(explicit map[string]string) ([]string, error)

Env builds a bash or process environment: baseEnv from the executor, the request env (bounded, loader and DenyEnv variables rejected), then CoreOptions.Env.

func (*Core) Register

func (c *Core) Register(capability Capability) error

Register adds a capability. Call it before Attach; a method may be registered once.

func (*Core) SetFileCommitHook added in v1.6.52

func (c *Core) SetFileCommitHook(hook func(ctx context.Context, sessionID string, commit func() error) error)

SetFileCommitHook lets a host serialize built-in write and edit commits with revocation of the same agent session. Set it before serving sessions. The hook either refuses with an error or invokes commit exactly once before returning and propagates its result. The callback rechecks FileAccess and performs all file mutations, including creating parent directories. When no separate agent session ID was supplied, the hook sees the core session ID. A nil hook runs the callback directly. Read tools never call the hook.

type CoreOptions

type CoreOptions struct {
	// WorkRoot holds every session workspace: WorkRoot/<brain>/<session>.
	WorkRoot string
	// Workspace overrides the per-session directory (for example a machine
	// executor whose sessions all share one directory, or a desktop app
	// mapping a brain to a project folder). Tools are confined to it.
	Workspace func(brain, sessionID string) string
	// MaxSessions bounds active sessions across all attached brains;
	// MaxSessionsPerBrain bounds one brain (defaults to MaxSessions). A full
	// core answers session.assign with executor_busy (-32009, retryable).
	MaxSessions         int
	MaxSessionsPerBrain int
	// MaxMCPServersPerSession bounds session.assign.mcp_servers (default 4).
	MaxMCPServersPerSession int
	// BashTimeout applies when neither tool.call deadline_ms nor the bash
	// timeout_ms is set (default 10 minutes).
	BashTimeout time.Duration
	// MaxOutputBytes caps each captured bash stream (default 1 MiB).
	MaxOutputBytes int
	// InlineResultBytes is the largest bash output returned inline (default
	// 48 KiB, under the 64 KiB control frame). Larger output is truncated.
	InlineResultBytes int
	// ComputerUse serves computer_observe and computer_action and advertises
	// capabilities.computer_use (for example NewCuaDriver). Nil leaves
	// computer use off: the harness then sends no computer_* tool.
	ComputerUse ComputerUseBackend
	// ComputerVision tells whether the model that reads a session's
	// computer use results takes images. When it answers
	// ComputerVisionTextOnly, an observation's screenshot is still taken
	// (actions use its pixels) but not sent: the result carries its text and
	// a note that the model cannot read images. Nil, or
	// ComputerVisionUnknown, sends the screenshot.
	ComputerVision func(ctx context.Context, q ComputerVisionQuery) ComputerVisionAnswer
	// Env is set on every bash tool and process and cannot be overridden by
	// a request (for example BMA_HOME).
	Env map[string]string
	// DenyEnv reports executor-private variables (credentials, state paths)
	// that no bash tool, process or stdio MCP server may see: they are
	// dropped from the inherited environment and a request setting one is
	// rejected. NewCore rejects an Env entry it denies.
	DenyEnv func(name string) bool
	// RunAs, when set, is the OS identity every bash tool, process and stdio
	// MCP server runs as, so a privileged executor (for example root) keeps
	// its own credentials and state out of the workload's reach. HOME and
	// USER in bash and process environments are the workload's. On Linux,
	// the file tools (read, write, edit, glob, grep) use the workload's file
	// identity. Unix only.
	RunAs *RunAs
	// Launch runs before each bash tool command starts (tool.call and
	// LocalToolRoute, so also ACPAgent's own tools), with the semantics of
	// ProcessOptions.Launch: it may change the directory, argv and
	// environment, or refuse the start; see LaunchFunc. File tools run inside
	// the executor and do not call it (they stay within the session
	// workspace). Nil starts commands as before.
	Launch LaunchFunc
	// FileAccess runs before every file tool (read, write, edit, glob, grep)
	// of this machine: a tool.call and the tools of a LocalToolRoute (so also
	// ACPAgent's). It gets the session, the tool, the operation (read or
	// write) and the workspace-relative path, and refuses by returning an
	// error: an *RPCError (NewReasonError) gives its data.reason as the
	// refusal code, any other error permission_denied. A LocalToolRoute call
	// is then not_forwarded with the code as Code, recorded like a result (the
	// same call id is answered with it again); a tool.call fails with
	// "<code>: <message>". Nothing is read or written when it refuses. A host
	// uses it for read-only sessions, protected paths, revoked grants and
	// stopped turns. The tools stay within the workspace with or without it,
	// unless OutsideFiles is set.
	// Nil allows every file tool call as before. See FileAccessRequest.
	FileAccess FileAccessFunc
	// OutsideFiles lets a file tool use an absolute path outside the session
	// workspace and mounts (as the user this executor runs as) when
	// FileAccess allows that call: the request then has Outside set and the
	// absolute path. FileAccess is required with it. Off, such a path fails
	// without asking FileAccess, as before. A host sets it for a session
	// that has full access to the computer; relative paths stay in the
	// workspace either way.
	OutsideFiles bool
	// ToolOutputDir, when set, holds the output files of the bash commands
	// of a LocalToolRoute (so also ACPAgent's own tools):
	// ToolOutputDir/<short hash of the session>/, created 0700 (owned by
	// RunAs when set). Empty keeps them in .bma-bash/ under the turn's
	// working directory. A host whose Launch sandboxes commands sets it to a
	// directory outside every folder a session may write, so the executor
	// writes nothing into the user's folders. The read tool of the session
	// may read its own output files there. tool.call bash keeps its output
	// in memory and does not use it.
	ToolOutputDir string
	// EndAfterToolCall marks sessions that carry exactly one tool call: the
	// core ends them (session.ended "completed") after the result is
	// delivered. BMA's durable selfhost queue assigns such sessions.
	EndAfterToolCall func(SessionAssignParams) bool
	// OnAssign runs on every accepted session.assign of the core, the first
	// one of a session (the session exists, workspace and MCP servers not yet
	// prepared) and each replay (sent again before tool calls, on reconnect,
	// to renew a grant). A host keeps per-session state from params.Metadata
	// here: a replay carries the whole metadata again, a key it no longer
	// holds is gone, and the session's Assignment shows the newest assign's
	// once OnAssign returns. A returned error refuses the assign (invalid
	// params naming it): a first assign creates no session, a replay leaves
	// the previous metadata. End of the session is the session's Context.
	// Nil does nothing.
	OnAssign func(session *CoreSession, params SessionAssignParams) error
	OnLog    func(LogEvent)
}

CoreOptions configures the execution core.

type CoreSession

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

CoreSession is one assigned session of one brain.

func (*CoreSession) Assignment

func (s *CoreSession) Assignment() SessionAssignParams

Assignment is the session.assign that created the session. A replayed session.assign replaces its metadata (the latest wins), so this is the newest assign's, not necessarily the first's.

func (*CoreSession) Brain

func (s *CoreSession) Brain() string

func (*CoreSession) Client

func (s *CoreSession) Client() *Client

func (*CoreSession) Context

func (s *CoreSession) Context() context.Context

Context is canceled when the session stops.

func (*CoreSession) ID

func (s *CoreSession) ID() string

func (*CoreSession) ResolveCwd

func (s *CoreSession) ResolveCwd(cwd string) (string, error)

ResolveCwd returns the real directory for a working directory request: a relative cwd is under the workspace, an absolute one must resolve (through symlinks) under it. An absolute cwd that is exactly the executor work root (what a machine's configured cwd is, for example C:\bma\work) is the session's workspace, since the work root holds every session's workspace and is no place to run a command.

func (*CoreSession) Value

func (s *CoreSession) Value(key any, create func() any) any

Value returns the per-session value for key, creating it with create on first use. Capabilities keep their session state here.

func (*CoreSession) Workspace

func (s *CoreSession) Workspace() string

type CuaDriver added in v1.3.0

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

CuaDriver is the ComputerUseBackend on Cua Driver (https://github.com/trycua/cua, MIT; only the MIT driver is used, not its AGPL perception extension or its FSL space daemon): every call is `cua-driver call <tool> <json>` against the driver daemon that runs in the interactive session (Windows: a logon scheduled task, `cua-driver autostart enable`). The executor itself may run in session 0 or session 1; the daemon owns the desktop. Input is delivered in the background when a window is named; screenshots and the accessibility tree come from the same daemon.

func NewCuaDriver added in v1.3.0

func NewCuaDriver(ctx context.Context, opts CuaDriverOptions) (*CuaDriver, error)

NewCuaDriver checks that the driver and its daemon work (a screen-size call) and returns the backend, or an error wrapping ErrComputerUseUnavailable.

func (*CuaDriver) Action added in v1.3.0

Action performs one computer_action and returns the driver's summary, with the driver's advice in terms of the computer use tools.

func (*CuaDriver) Observe added in v1.3.0

Observe returns a screenshot with a text description: the screen size and the window list, or one window's accessibility tree (UIA on Windows).

func (*CuaDriver) OpenApp added in v1.6.9

OpenApp launches the app (launch_app starts it in the background) and brings it to the front. When that fails or the app has no window on the current desktop it recovers, in order: on macOS it reopens the app (as a click on its Dock icon: an app that runs without a window shows its main window then; launch_app of a running app does not), elsewhere it launches it again; it brings the app to the front, and then brings its largest hidden window forward. Only windows on the current desktop are returned.

type CuaDriverError added in v1.6.9

type CuaDriverError struct {
	Tool, Code string
	// contains filtered or unexported fields
}

CuaDriverError is a structured driver failure (exit status 1 with a JSON result that has a code). Its text is "<code>: <advice>", with the advice in terms of the computer use tools. A refusal that delivered no input (Is ErrComputerActionRejected) is told apart from a failure that may have.

func (*CuaDriverError) Error added in v1.6.9

func (e *CuaDriverError) Error() string

func (*CuaDriverError) Is added in v1.6.9

func (e *CuaDriverError) Is(target error) bool

Is reports ErrComputerActionRejected for a refusal before input.

type CuaDriverOptions added in v1.3.0

type CuaDriverOptions struct {
	// Path is the cua-driver executable (default: cua-driver on PATH).
	Path string
	// Socket overrides the daemon's socket or named pipe (default: the
	// driver's own, \\.\pipe\cua-driver on Windows).
	Socket string
	// Env is added to the driver's environment (CUA_TELEMETRY=0 is always set).
	Env []string
	// Timeout bounds one driver call (default 30 s).
	Timeout time.Duration
	// NoClipboard keeps the clipboard out of typing: non-ASCII text into a
	// window with web content is then typed with the window briefly in
	// front instead of pasted (see typeText). A clipboard history app may
	// record pasted text.
	NoClipboard bool
}

CuaDriverOptions configures NewCuaDriver.

type Cursors

type Cursors struct {
	Stdout int64 `json:"stdout"`
	Stderr int64 `json:"stderr"`
}

Cursors Per-stream byte cursors.

type CustomToolDefinition added in v1.6.5

type CustomToolDefinition struct {
	Name        string `json:"name"`
	Description string `json:"description"`
	// JSON Schema of the tool input (an object schema).
	InputSchema map[string]any `json:"input_schema"`
}

CustomToolDefinition Contract 1.7.0. One custom tool of the turn's agent: an Anthropic Managed Agents agent tools entry of type custom, as the agent version defines it (name, description, input_schema). The executor offers it to the model next to its own tools; a call to it is an agent.custom_tool_use.

type CustomToolResultResult added in v1.3.0

type CustomToolResultResult struct {
	Accepted bool `json:"accepted"`
}

CustomToolResultResult agent.custom_tool_result result. accepted=true: the executor took the result for the call it was waiting on. accepted=false: it no longer waits (unknown tool_use_id, already answered, timed out, or canceled with its turn); the platform marks its copy stale and does not send it again.

type DaemonHTTPError added in v1.1.0

type DaemonHTTPError struct {
	StatusCode int
	// Code and Message are BMA's error body when it sent one.
	Code    string
	Message string
}

DaemonHTTPError is a non-2xx answer of a BMA daemon route.

func (*DaemonHTTPError) Error added in v1.1.0

func (e *DaemonHTTPError) Error() string

type DesktopAttachParams added in v1.6.34

type DesktopAttachParams struct {
	SessionID string            `json:"session_id"`
	CaptureID string            `json:"capture_id,omitempty"`
	MachineID string            `json:"machine_id"`
	RelayURL  string            `json:"relay_url"`
	Ticket    string            `json:"ticket"`
	Width     int               `json:"width,omitempty"`
	Height    int               `json:"height,omitempty"`
	Wallpaper *DesktopWallpaper `json:"wallpaper,omitempty"`
}

DesktopAttachParams is the params object of desktop.attach.

type DesktopAttachResult added in v1.6.34

type DesktopAttachResult struct {
	Accepted  bool   `json:"accepted"`
	Wallpaper string `json:"wallpaper,omitempty"`
}

DesktopAttachResult desktop.attach result. wallpaper is need when the attach named a wallpaper the machine does not have; the harness then sends it with desktop.wallpaper.

type DesktopControlCommand added in v1.6.5

type DesktopControlCommand struct {
	SessionID   string `json:"session_id"`
	Action      string `json:"action"`
	MachineID   string `json:"machine_id"`
	Epoch       uint64 `json:"epoch"`
	LeaseID     string `json:"lease_id"`
	Identity    string `json:"identity,omitempty"`
	InputKey    string `json:"input_key,omitempty"`
	ExpiresAtMS int64  `json:"expires_at_ms,omitempty"`
}

type DesktopControlGate added in v1.6.5

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

DesktopControlGate guards the physical input device, not model/file work. The platform alone grants authority. Media IPC may only use that authority.

func NewDesktopControlGate added in v1.6.5

func NewDesktopControlGate(backend ComputerUseBackend, native NativeDesktopInput) *DesktopControlGate

func (*DesktopControlGate) Action added in v1.6.5

func (*DesktopControlGate) Close added in v1.6.5

func (g *DesktopControlGate) Close()

func (*DesktopControlGate) Grant added in v1.6.5

func (g *DesktopControlGate) Grant(ctx context.Context, epoch uint64, lease, identity string, deadline time.Time) error

func (*DesktopControlGate) Heartbeat added in v1.6.5

func (g *DesktopControlGate) Heartbeat(epoch uint64, lease, identity string) error

Heartbeat proves controller liveness only; it cannot renew platform authority.

func (*DesktopControlGate) HumanInput added in v1.6.5

func (g *DesktopControlGate) HumanInput(ctx context.Context, epoch uint64, lease, identity string, seq uint64, event DesktopInputEvent) error

HumanInput receives the authenticated LiveKit participant identity from the capture host, never from the payload. Heartbeats cannot extend the platform lease.

func (*DesktopControlGate) Observe added in v1.6.5

func (*DesktopControlGate) Recover added in v1.6.5

func (g *DesktopControlGate) Recover(ctx context.Context) error

Recover does not grant input or resume tasks. A new platform grant and explicit handback are required afterwards. Unknown Agent actions require the Agent driver's own quiescence proof, separately from human input cleanup.

func (*DesktopControlGate) Release added in v1.6.5

func (g *DesktopControlGate) Release(ctx context.Context, epoch uint64, lease string, resume bool) error

func (*DesktopControlGate) SignedInput added in v1.6.5

func (g *DesktopControlGate) SignedInput(ctx context.Context, identity string, raw json.RawMessage, w, h float64) error

func (*DesktopControlGate) StopMedia added in v1.6.5

func (g *DesktopControlGate) StopMedia(ctx context.Context, id string) error

type DesktopInputEvent added in v1.6.5

type DesktopInputEvent struct {
	Type    string  `json:"type"`
	X       float64 `json:"x,omitempty"`
	Y       float64 `json:"y,omitempty"`
	W       float64 `json:"w,omitempty"`
	H       float64 `json:"h,omitempty"`
	Buttons uint8   `json:"buttons,omitempty"`
	Keysym  uint32  `json:"keysym,omitempty"`
	Down    bool    `json:"down,omitempty"`
	DY      float64 `json:"dy,omitempty"`
	Width   uint16  `json:"width,omitempty"`
	Height  uint16  `json:"height,omitempty"`
	// Scale of a resize: the viewer's devicePixelRatio × 100 (DesktopScaleMin–DesktopScaleMax); 0 = not sent (1×).
	Scale uint16 `json:"scale,omitempty"`
	Text  string `json:"text,omitempty"`
}

type DesktopInputGrant added in v1.6.5

type DesktopInputGrant struct {
	Epoch      string `json:"epoch"`
	Generation uint64 `json:"generation"`
	LeaseID    string `json:"lease_id"`
	Holder     string `json:"holder"`
	InputKey   []byte `json:"input_key"`
	ExpiresAt  uint64 `json:"expires_at"`
}

type DesktopInputMessage added in v1.6.5

type DesktopInputMessage struct {
	Epoch    uint64            `json:"epoch"`
	LeaseID  string            `json:"lease_id"`
	Identity string            `json:"identity"`
	Sequence uint64            `json:"seq"`
	Event    DesktopInputEvent `json:"event"`
	Packet   json.RawMessage   `json:"packet,omitempty"`
	Width    float64           `json:"width,omitempty"`
	Height   float64           `json:"height,omitempty"`
}

type DesktopSignedInput added in v1.6.5

type DesktopSignedInput struct {
	Grant    DesktopInputGrant `json:"grant"`
	Sequence uint64            `json:"sequence"`
	Input    struct {
		Type    string `json:"type"`
		X       uint16 `json:"x"`
		Y       uint16 `json:"y"`
		Buttons uint8  `json:"buttons"`
		Keysym  uint32 `json:"keysym"`
		Down    bool   `json:"down"`
		Width   uint16 `json:"width"`
		Height  uint16 `json:"height"`
		// Scale is the viewer's devicePixelRatio × 100 of a resize (100–400); 0 = not sent.
		Scale uint16 `json:"scale,omitempty"`
		Text  string `json:"text"`
	} `json:"input"`
	Signature string `json:"signature"`
}

func (DesktopSignedInput) SigningBytes added in v1.6.42

func (p DesktopSignedInput) SigningBytes() ([]byte, error)

SigningBytes are the bytes the packet's Ed25519 signature covers, with the grant's own input key (contracts/bma/desktop-relay.md §5b).

type DesktopWallpaper added in v1.6.34

type DesktopWallpaper struct {
	SHA256 string `json:"sha256"`
	Ext    string `json:"ext"`
	Size   int64  `json:"size"`
}

DesktopWallpaper The environment's default wallpaper: sha256 (lowercase hex) of the image, its extension (png, jpg or webp) and size in bytes.

type DesktopWallpaperParams added in v1.6.34

type DesktopWallpaperParams struct {
	SHA256 string `json:"sha256"`
	Ext    string `json:"ext"`
	Offset int64  `json:"offset"`
	Data   string `json:"data"`
	Done   bool   `json:"done"`
}

DesktopWallpaperParams is the params object of desktop.wallpaper.

type DesktopWallpaperResult added in v1.6.34

type DesktopWallpaperResult struct {
	Accepted bool `json:"accepted"`
}

DesktopWallpaperResult desktop.wallpaper result.

type Dialer

type Dialer func(ctx context.Context, token ExecutorTokenResponse, protocol string, target ChannelTarget) (Conn, error)

Dialer opens an executor channel after the token source returned token. The default dials token.WSURL over WebSocket: ws://, wss:// or unix:///path/to.sock or npipe:////./pipe/<name> (the same WebSocket upgrade on a Unix domain socket or a Windows named pipe, as in the TypeScript and Python SDKs).

func InProcessDialer

func InProcessDialer(h *Harness, principal Principal) Dialer

InProcessDialer connects the executor to h in the same process: every dial creates a fresh Pipe and serves its harness end with principal, as the control channel or as an MCP channel.

func ListenNamedPipe

func ListenNamedPipe(name, token string) (Dialer, func() error, error)

ListenNamedPipe is ListenUnixSocket on a Windows named pipe \\.\pipe\<name>: the executor listens and the next local harness that dials it with Authorization: Bearer token (Harness.DialExecutor with the pipe name or an npipe:// URL) becomes its brain.

func ListenUnixSocket

func ListenUnixSocket(path, token string) (Dialer, func() error, error)

ListenUnixSocket makes the executor the listening side on a local machine: it creates a 0700 directory and a 0600 Unix socket at path and returns a Dialer that waits for the next local harness ("brain") to connect with Authorization: Bearer token. The roles do not change: the brain is still the harness and the executor still registers. The brain (Harness. DialExecutor) also dials the MCP channels of its sessions; an MCP dial waits for that connection. Use it as Options.Dial with TokenSource StaticToken("ws://local/", "") so the executor reconnects by accepting again. Close the returned closer to stop listening.

func NamedPipeDialer

func NamedPipeDialer(name string) Dialer

NamedPipeDialer dials a harness serving Harness.ServeHTTP on the Windows named pipe \\.\pipe\<name> (NamedPipeListener). token.WSURL is ignored; StaticToken("npipe:////./pipe/"+name, token) with the default dialer is equivalent.

func UnixSocketDialer

func UnixSocketDialer(path string) Dialer

UnixSocketDialer dials a harness listening on the Unix domain socket at path (the harness serves Harness.ServeHTTP on that listener). token.WSURL is ignored; StaticToken("unix://"+path, token) with the default dialer is equivalent.

func WebSocketDialer

func WebSocketDialer(httpClient *http.Client) Dialer

WebSocketDialer dials token.WSURL (ws://, wss://, unix:// or npipe://) with the bearer token in the Authorization header. httpClient may carry a proxy or a custom transport; nil uses http.DefaultClient. A unix:// URL always dials its socket.

type DisplayCapability

type DisplayCapability struct {
	RFB bool `json:"rfb,omitempty"`
	// The machine runs its own desktop (bmad supervises bma-desktop-session from machine start) and serves desktop.attach. Absent means unknown (an executor that predates the field).
	Desktop bool `json:"desktop,omitempty"`
	// Deprecated (screen_live replaces it; removed once no executor declares it). Native screen producer supports screen.start/stop and the bma desktop relay, without process execution. Does not grant input authority.
	NativeWebrtc bool `json:"native_webrtc,omitempty"`
	// The executor's screen publisher serves screen.live: it publishes the machine's screen into the SFU (a desktop, or a physical screen such as a phone's). Not together with native_webrtc.
	ScreenLive bool `json:"screen_live,omitempty"`
	// With screen_live: the executor serves screen.control and admits a lease holder's signed input (desktop-relay.md §5b).
	ScreenControl bool `json:"screen_control,omitempty"`
}

DisplayCapability v1.1 display object. v1 sent a boolean; the server accepts both.

type DrainHandler

type DrainHandler func(ctx context.Context, params ExecutorDrainParams) (ExecutorDrainResult, error)

DrainHandler handles an inbound executor.drain.

type EditInput added in v1.0.0

type EditInput struct {
	// File path, relative to the session workspace.
	Path string `json:"path"`
	// Text that must occur exactly once.
	OldString string `json:"old_string"`
	// Replacement text.
	NewString string `json:"new_string"`
}

EditInput edit input: replace the single occurrence of old_string.

type EgressCapability added in v1.6.5

type EgressCapability struct {
	Forwarder bool `json:"forwarder"`
}

EgressCapability Contract 1.9.0. The executor runs the local egress forwarder (docs/architecture/env-networking-egress.md E6): a loopback HTTP proxy that the processes and terminals of a session are pointed at (HTTP(S)_PROXY, NO_PROXY and a trust store that includes the handoff's ca_bundle), and that tunnels each of their connections to executor.<domain>/v1/machines/{machine_id}/egress?host=<host>&port=<port> (WebSocket, Authorization: Bearer <the session's egress token>). The platform hands an egress handoff (EgressHandoff, session.assign and turn.start metadata egress) only to an executor that declared forwarder=true; a session that needs egress (limited networking or vault environment variables) on an executor that did not declare it is never run there: its turn ends with session.error bma_error_code egress_unsupported (fail closed). Machine-scoped executors only. Absent or forwarder=false: no forwarder, which is also what an executor that predates 1.9.0 means.

type EgressHandoff added in v1.6.5

type EgressHandoff struct {
	Token     string `json:"token"`
	ExpiresAt string `json:"expires_at"`
	// PEM of the egress CA (the gateway terminates TLS only on hosts with a credential to substitute).
	CaBundle string            `json:"ca_bundle"`
	Env      map[string]string `json:"env,omitempty"`
}

EgressHandoff Contract 1.9.0. The egress of one session, carried as the JSON text of metadata egress (session.assign, turn.start). token is secret material: the executor keeps it in memory for the forwarder only, never puts it in a process environment, a log, a session.event or a tool result, and never uses one session's token for another session's connections (several sessions may share the machine). env maps a vault environment variable name to its placeholder: the executor sets these variables in the processes and terminals it starts for the session; the gateway replaces a placeholder with the secret only on hosts the credential allows, so the plaintext never reaches the machine. A refused host is not a protocol error: the forwarder answers the client with the gateway's HTTP status and body (403 naming the host; 401 expired or unknown token; 404 machine is not the token's; 502 unreachable).

type EnvironmentInfo added in v1.3.0

type EnvironmentInfo struct {
	// Operating system of the hands machine, as ExecutorInfo.os (for example linux, darwin, windows).
	OS string `json:"os,omitempty"`
	// CPU architecture, as ExecutorInfo.arch.
	Arch string `json:"arch,omitempty"`
	// Shell the bash tool runs commands with on the hands machine (for example bash, zsh, powershell).
	Shell string `json:"shell,omitempty"`
	// Default working directory of tools on the hands machine; the same value as AgentTurnConfig.cwd when that is set.
	Cwd string `json:"cwd,omitempty"`
	// Directory on the hands machine where the session's files are mounted, when the hands executor declared session_files.
	SessionFilesRoot string `json:"session_files_root,omitempty"`
}

EnvironmentInfo Contract 1.4.0. The hands machine as the platform knows it (AgentTurnConfig.environment_info), from the hands executor's registration and the session's file mounts. Every member is optional; an omitted member is unknown, not empty. Values describe the machine at the time of turn.start.

type EvaluatedPermission

type EvaluatedPermission struct {
	Type string `json:"type"`
}

EvaluatedPermission Permission decision the executor applied to a tool use. ask means the executor opened an interaction.request for it.

type EventRejectedError added in v1.6.2

type EventRejectedError struct {
	EventID string
	Cause   *RPCError
}

EventRejectedError is the cause (context.Cause) of a turn the SDK ended because the platform rejected one of its events for good: the turn cannot go on without that event, so it ends with session.error (agent_error, "event_rejected: ...") and session.status_idle (retries_exhausted, failed) at the rejected sequence, and its later events are not sent.

func (*EventRejectedError) Error added in v1.6.2

func (e *EventRejectedError) Error() string

func (*EventRejectedError) Unwrap added in v1.6.2

func (e *EventRejectedError) Unwrap() error

type Executor

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

Executor is one registered executor. It outlives a single connection: a reconnect with resume.executor_id within the lease attaches to the same Executor and keeps its sessions and pending tool calls.

func (*Executor) AgentCapability

func (e *Executor) AgentCapability() (*AgentCapability, error)

AgentCapability returns the advertised agent capability, nil when absent.

func (*Executor) AssignSession

func (e *Executor) AssignSession(ctx context.Context, params SessionAssignParams) (*Session, error)

AssignSession binds a session to this executor and sends session.assign. WorkID and the lease token are generated when empty. The session is bound before the request is sent, so session.ready and MCP channels that race the assign response are accepted.

func (*Executor) Call

func (e *Executor) Call(ctx context.Context, method string, params, out any) error

Call sends a harness-to-executor request for a capability method (process.*, terminal.*, skill.install, ...) and decodes its result. A JSON-RPC error answer is an *RPCError.

func (*Executor) CancelTurn

func (e *Executor) CancelTurn(ctx context.Context, params TurnCancelParams) (TurnCancelResult, error)

CancelTurn sends turn.cancel. The turn's end is still reported by its session.status_idle event.

func (*Executor) Capabilities

func (e *Executor) Capabilities(out any) error

Capabilities decodes the advertised capabilities into out (for example *Capabilities, or a v1.1 capability struct).

func (*Executor) CloseAgentSession

func (e *Executor) CloseAgentSession(ctx context.Context, params SessionCloseParams) (SessionCloseResult, error)

CloseAgentSession sends session.close.

func (*Executor) Drain

func (e *Executor) Drain(ctx context.Context, reason string) (ExecutorDrainResult, error)

Drain asks the executor to stop accepting sessions; existing sessions run to completion. Heartbeats report drain=true from now on.

func (*Executor) ID

func (e *Executor) ID() string

func (*Executor) Info

func (e *Executor) Info() ExecutorInfo

func (*Executor) Protocol

func (e *Executor) Protocol() string

Protocol is the negotiated subprotocol of the current connection.

func (*Executor) RespondCustomToolResult added in v1.3.0

func (e *Executor) RespondCustomToolResult(ctx context.Context, params AgentCustomToolResultParams) (CustomToolResultResult, error)

RespondCustomToolResult delivers the user's result for an agent.custom_tool_use. accepted=false means the executor no longer waits (unknown tool_use_id, answered already, timed out, or canceled with its turn); mark the platform's copy stale and do not send it again.

func (*Executor) RespondInteraction

func (e *Executor) RespondInteraction(ctx context.Context, params InteractionResponseParams) (InteractionResponseResult, error)

RespondInteraction delivers the platform's answer. accepted=false means the executor no longer waits for it (answered already, withdrawn, or unknown); mark the platform interaction stale.

func (*Executor) SendTurnInput

func (e *Executor) SendTurnInput(ctx context.Context, params TurnInputParams) (Ack, error)

SendTurnInput sends turn.input; a conflict means the turn is over and the input belongs in a new turn.start.

func (*Executor) Sessions

func (e *Executor) Sessions() []*Session

Sessions returns the sessions bound to this executor.

func (*Executor) StartTurn

func (e *Executor) StartTurn(ctx context.Context, params TurnStartParams) (TurnStartResult, error)

StartTurn sends turn.start. It is safe to repeat with the same turn_id after a timeout or reconnect.

type ExecutorCapabilitiesUpdateParams

type ExecutorCapabilitiesUpdateParams struct {
	Capabilities Capabilities `json:"capabilities"`
}

ExecutorCapabilitiesUpdateParams is the params object of executor.capabilities.update.

type ExecutorCloseParams

type ExecutorCloseParams struct {
	Reason string `json:"reason"`
}

ExecutorCloseParams is the params object of executor.close.

type ExecutorDrainParams

type ExecutorDrainParams struct {
	Reason     string `json:"reason"`
	DeadlineMS int64  `json:"deadline_ms,omitempty"`
}

ExecutorDrainParams is the params object of executor.drain.

type ExecutorDrainResult

type ExecutorDrainResult struct {
	Accepted       bool     `json:"accepted"`
	ActiveSessions []string `json:"active_sessions"`
}

ExecutorDrainResult executor.drain result.

type ExecutorHeartbeatParams

type ExecutorHeartbeatParams struct {
	ConnectionID   string        `json:"connection_id"`
	ActiveSessions []string      `json:"active_sessions"`
	Load           *ExecutorLoad `json:"load,omitempty"`
}

ExecutorHeartbeatParams is the params object of executor.heartbeat.

type ExecutorHeartbeatResult

type ExecutorHeartbeatResult struct {
	ServerTime string `json:"server_time"`
	LeaseTTLMS int64  `json:"lease_ttl_ms"`
	Drain      bool   `json:"drain"`
}

ExecutorHeartbeatResult executor.heartbeat result.

func SendExecutorHeartbeat

func SendExecutorHeartbeat(ctx context.Context, rpc RPC, params ExecutorHeartbeatParams) (ExecutorHeartbeatResult, error)

SendExecutorHeartbeat calls executor.heartbeat.

type ExecutorInfo

type ExecutorInfo struct {
	Name    string `json:"name"`
	OS      string `json:"os"`
	Arch    string `json:"arch"`
	Version string `json:"version"`
	// Contract 1.4.0, optional. Labels the executor reports about itself (at most 32, each 1-64 characters of a-z 0-9 . _ -), set by the machine's owner in the executor's local configuration (for example BMA_LABELS or the SDK Options.Labels). The platform accepts them as given and does not validate their meaning, and it adds its own os:<os> and arch:<arch> labels from os and arch. Labels only narrow a choice among machines the project is already authorized to use (environment placement selectors); no authorization or security decision depends on them. Omitted: no labels.
	Labels []string `json:"labels,omitempty"`
}

ExecutorInfo Executor identity reported at token bootstrap and registration.

type ExecutorLoad

type ExecutorLoad struct {
	CPUPercent    float64 `json:"cpu_percent,omitempty"`
	MemoryPercent float64 `json:"memory_percent,omitempty"`
}

ExecutorLoad Advisory executor load reported with executor.heartbeat. The server does not act on it.

type ExecutorRegisterParams

type ExecutorRegisterParams struct {
	Protocol string `json:"protocol"`
	// Selfhost environment id; empty for a machine-scoped executor.
	EnvironmentID string          `json:"environment_id"`
	Executor      ExecutorInfo    `json:"executor"`
	Capabilities  Capabilities    `json:"capabilities"`
	Resume        *ExecutorResume `json:"resume,omitempty"`
}

ExecutorRegisterParams is the params object of executor.register.

type ExecutorRegisterResult

type ExecutorRegisterResult struct {
	ExecutorID           string  `json:"executor_id"`
	ConnectionID         string  `json:"connection_id"`
	ServerTime           string  `json:"server_time"`
	HeartbeatIntervalMS  int64   `json:"heartbeat_interval_ms"`
	LeaseTTLMS           int64   `json:"lease_ttl_ms"`
	MaxControlFrameBytes int64   `json:"max_control_frame_bytes"`
	MaxMCPFrameBytes     int64   `json:"max_mcp_frame_bytes"`
	Drain                bool    `json:"drain"`
	Protocol             string  `json:"protocol,omitempty"`
	Limits               *Limits `json:"limits,omitempty"`
}

ExecutorRegisterResult executor.register result. protocol and limits are v1.1 only.

func SendExecutorRegister

func SendExecutorRegister(ctx context.Context, rpc RPC, params ExecutorRegisterParams) (ExecutorRegisterResult, error)

SendExecutorRegister calls executor.register.

type ExecutorResume

type ExecutorResume struct {
	ExecutorID       string   `json:"executor_id,omitempty"`
	LastConnectionID string   `json:"last_connection_id,omitempty"`
	ActiveSessions   []string `json:"active_sessions,omitempty"`
}

ExecutorResume Reattach state sent on reconnect.

type ExecutorTokenRefreshParams

type ExecutorTokenRefreshParams struct {
	Token string `json:"token"`
}

ExecutorTokenRefreshParams is the params object of executor.token.refresh.

type ExecutorTokenRefreshResult

type ExecutorTokenRefreshResult struct {
	// RFC 3339 time of the new connection deadline.
	ExpiresAt string `json:"expires_at"`
}

ExecutorTokenRefreshResult executor.token.refresh result: the connection now closes with 4001 at expires_at.

func SendExecutorTokenRefresh

func SendExecutorTokenRefresh(ctx context.Context, rpc RPC, params ExecutorTokenRefreshParams) (ExecutorTokenRefreshResult, error)

SendExecutorTokenRefresh calls executor.token.refresh.

type ExecutorTokenRequest

type ExecutorTokenRequest struct {
	EnvironmentID string       `json:"environment_id"`
	Executor      ExecutorInfo `json:"executor"`
	// Contract 1.23.0, optional (ADR-0083). One instance of a platform brain fleet: the instances of a platform brain machine share its machine credential, and each exchanges it for a token of its own instance (for example its pod name), so each holds its own control channel and the platform spreads sessions over them. Only the deployment's platform brain machines may send it (others: 400 invalid_request_error). Omitted: the machine's own executor.
	InstanceID string `json:"instance_id,omitempty"`
}

ExecutorTokenRequest Token request body for POST /v1/machines/{machine_id}/token (bearer: machine daemon token) and POST /v1/environments/{environment_id}/token (bearer: environment key); the legacy aliases take one bearer each: POST /api/v1/executors/token a machine daemon token, POST /v1/executors/token an environment key (the other kind is answered 401). The id in the path must equal the credential's machine or environment, otherwise 404; on the new paths environment_id may be empty or absent for a machine and, when sent for an environment, must equal the path id. An empty environment_id with a machine token requests a machine-scoped executor: its executor_id is exec_<machine_id>, stable across refreshes, and the JWT carries machine_id and daemon_token_id.

type ExecutorTokenResponse

type ExecutorTokenResponse struct {
	ExecutorID string `json:"executor_id"`
	// Short-lived executor JWT, sent only in the Authorization header of the channel upgrade.
	Token string `json:"token"`
	// Seconds.
	ExpiresIn    int64    `json:"expires_in"`
	WSURL        string   `json:"ws_url"`
	ChannelScope []string `json:"channel_scope"`
}

ExecutorTokenResponse Token response of POST /v1/machines/{machine_id}/token, POST /v1/environments/{environment_id}/token and the legacy aliases POST /api/v1/executors/token and POST /v1/executors/token.

type FileAccessFunc added in v1.4.0

type FileAccessFunc func(ctx context.Context, req FileAccessRequest) error

FileAccessFunc is CoreOptions.FileAccess.

type FileAccessRequest added in v1.4.0

type FileAccessRequest struct {
	// SessionID is the executor's session id. AgentSessionID is the agent
	// session: for a LocalToolRoute the same id, for a tool.call the
	// session.assign metadata agent_session_id (empty when it has none).
	SessionID, AgentSessionID string
	// Tool is read, write, edit, glob or grep; ToolCallID the call.
	Tool, ToolCallID string
	// Operation is FileOperationRead or FileOperationWrite. read, glob and
	// grep read; write writes; edit reads and writes, so the hook is called
	// twice for it, read first. glob and grep are asked about their search
	// directory, not about each file under it.
	Operation string
	// Path is the file or directory, relative to the session workspace,
	// cleaned and slash-separated ("." is the workspace itself); when Mount
	// is set it is relative to that mount's directory instead. A call whose
	// path is outside the workspace and the session's mounts fails without
	// asking the hook.
	Path string
	// Mount names the session's mounted directory Path is in: "uploads",
	// "skills" or "outputs" (see ACPAgentOptions.SessionFilesRoot). Empty for
	// the workspace. A hook that guards the workspace only should treat a
	// request with a Mount as outside its scope or check it explicitly.
	Mount string
	// Outside marks a path beyond the workspace and mounts, asked only with
	// CoreOptions.OutsideFiles: Path is then absolute, in OS form. A hook
	// allows it only for a session that may use any file of the computer.
	Outside bool
}

FileAccessRequest is what CoreOptions.FileAccess is asked before a file tool runs.

type FileTransferError

type FileTransferError struct {
	Code          string `json:"code"`
	Message       string `json:"error"`
	CurrentDigest string `json:"current_digest,omitempty"`
}

FileTransferError Failed file transfer.

type FileTransferResult

type FileTransferResult struct {
	Path   string             `json:"path,omitempty"`
	Digest string             `json:"digest,omitempty"`
	Error  *FileTransferError `json:"error,omitempty"`
}

FileTransferResult Ended file transfer outcome: the uploaded path and digest, the downloaded digest, or an error.

type FileTransferer

type FileTransferer interface {
	TransferFile(ctx context.Context, processID string, transfer ProcessFileTransfer) (FileTransferResult, error)
}

FileTransferer moves one file for a process.start file_transfer. A failure is returned both as the error (the process output, exit code 1) and as FileTransferResult.Error, which the harness reports.

type FilesCapability

type FilesCapability struct {
	Enabled    bool     `json:"enabled"`
	ReadRoots  []string `json:"read_roots,omitempty"`
	WriteRoots []string `json:"write_roots,omitempty"`
}

FilesCapability v1 file tools.

type GenerateImageInput added in v1.15.0

type GenerateImageInput struct {
	// What to create or how to change the input image: subject, style, composition, lighting, exact text in quotes; for an edit, what must stay the same.
	Prompt string `json:"prompt"`
	// Input images: absolute paths in the session's uploads or outputs directory, or file ids (file_…). The first is the image to edit, the others are references. Each at most 20 MB and 16,777,216 pixels.
	Images []string `json:"images,omitempty"`
	// Width:height of the image; auto lets the model choose. The platform offers these values as an enum.
	AspectRatio string `json:"aspect_ratio,omitempty"`
	Background  string `json:"background,omitempty"`
	// Image model id; one of the turn's available image models. Absent: the default image model.
	Model string `json:"model,omitempty"`
	// File name stem, for example hero-banner.
	Name string `json:"name,omitempty"`
	// One line telling the user what is being made.
	Description string `json:"description,omitempty"`
}

GenerateImageInput Contract 1.26.0. Input of the platform tool generate_image. The platform offers it with model as an enum of the turn's available image models (contracts/bma/platform-tool-image.vectors.json); format (PNG) and count (1) are the platform's; the platform requests resolution 2K, which only models that declare a resolution parameter honor (OpenAI gpt-image-* output follows aspect_ratio, 1024x1024 for 1:1).

type GenerateImageInputRef added in v1.15.0

type GenerateImageInputRef struct {
	FileID string `json:"file_id"`
	SHA256 string `json:"sha256"`
}

GenerateImageInputRef Contract 1.26.0. An input image of a generate_image call as sent: its file and content digest.

type GenerateImageResult added in v1.15.0

type GenerateImageResult struct {
	Outcome  string `json:"outcome"`
	Replayed bool   `json:"replayed"`
	// Open set: content_policy_violation, invalid_image_input, rate_limited, image_model_unavailable, image_model_not_allowed, billing_suspended and the platform tool codes (permission_denied, approval_required, approval_invalid, in_progress, idempotency_key_reused).
	ErrorCode string `json:"error_code,omitempty"`
	// The generated images: session output files at output_path generated/<name>.png, also mounted at <session root>/uploads/generated/<name>.png.
	Files []ToolResultFile `json:"files,omitempty"`
	// The input images as sent.
	Inputs []GenerateImageInputRef `json:"inputs,omitempty"`
	// The image model used.
	Model             string `json:"model,omitempty"`
	RevisedPrompt     string `json:"revised_prompt,omitempty"`
	UpstreamRequestID string `json:"upstream_request_id,omitempty"`
	// The provider-reported cost (usage.cost) when it reported one.
	CostUsd float64 `json:"cost_usd,omitempty"`
	// With image_model_not_allowed: the models the call may name.
	AvailableModels []string `json:"available_models,omitempty"`
}

GenerateImageResult Contract 1.26.0. structuredContent of a generate_image answer (its outputSchema). The answer's content is a text (paths, file ids, sizes, model, revised prompt) and, per image, a preview image (at most 1024 px, annotations.audience [assistant]) plus this object serialized as text.

type GitCredentialGranter

type GitCredentialGranter interface {
	Grant(processID string, env []string) ([]string, func(), error)
}

GitCredentialGranter backs process.start git_credentials: Grant returns the environment that lets processID fetch Git credentials while it runs, and a release function called when the process ends.

type GlobInput added in v1.0.0

type GlobInput struct {
	// Glob pattern.
	Pattern string `json:"pattern"`
	// Base directory, relative to the session workspace.
	Path string `json:"path,omitempty"`
}

GlobInput glob input: list paths matching pattern.

type GrepInput added in v1.0.0

type GrepInput struct {
	// Regular expression.
	Pattern string `json:"pattern"`
	// Directory to search, relative to the session workspace.
	Path string `json:"path,omitempty"`
	// File name filter.
	Glob string `json:"glob,omitempty"`
}

GrepInput grep input: search file lines with a regular expression.

type Handler

type Handler func(ctx context.Context, req Request) (any, error)

Handler serves one harness-to-executor request method registered by a Capability. A *RPCError result is sent as is; any other error becomes internal_error.

type Harness

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

Harness is the harness ("brain") end of the executor protocol: an http.Handler that accepts executor control and MCP channels, plus the session.assign / tool.call / tool.cancel / session.stop API that drives them. It is the same protocol the BMA service speaks, so an executor built on this SDK cannot tell a local harness from the cloud.

func NewHarness

func NewHarness(opts HarnessOptions) *Harness

NewHarness returns a harness with defaults applied.

func (*Harness) DialExecutor

func (h *Harness) DialExecutor(ctx context.Context, path, token string) error

DialExecutor connects this harness to an executor that listens on the local Unix socket at path (ListenUnixSocket) or Windows named pipe (ListenNamedPipe; path is \\.\pipe\<name> or an npipe:// URL) and serves the connection until it closes. A local brain uses it to drive the hand already running on the machine instead of starting another one.

func (*Harness) Executors

func (h *Harness) Executors() []*Executor

Executors returns the executors currently registered (connected or within their reconnect lease).

func (*Harness) ServeConn

func (h *Harness) ServeConn(transport Conn, principal Principal)

ServeConn serves one executor control connection on any transport (an in-process Pipe end, a dialed local socket, ...) until it closes. The caller authenticated the peer; principal pins its identity.

func (*Harness) ServeHTTP

func (h *Harness) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP accepts /v1/executors/channel style upgrades: the control channel by default, the MCP channel with ?channel=mcp&session_id=...&server_key=...

func (*Harness) WaitExecutor

func (h *Harness) WaitExecutor(ctx context.Context) (*Executor, error)

WaitExecutor returns a connected executor, waiting for one to register.

type HarnessArtifact added in v1.6.13

type HarnessArtifact struct {
	URL    string
	SHA256 string
}

HarnessArtifact is the binary of one release for one platform.

type HarnessKind added in v1.6.13

type HarnessKind struct {
	// ID is the declared harness id (agent.harnesses[].id), e.g. claude-code.
	ID string
	// DisplayName is the name shown to the owner.
	DisplayName string
	// Adapter names the adapter family (claude-cli, codex-app-server, acp).
	Adapter string
	// Releases are the pinned releases, newest last; only these run.
	Releases []HarnessRelease
	// AuthStatus are the arguments that exit 0 when the owner is signed in
	// (the harness's own check; no credential is read by the SDK).
	AuthStatus []string
	// Login are the arguments that start the owner's interactive sign-in.
	Login []string
	// OwnerEnv are the prefixes of this process's variables handed to the
	// harness as they are (the owner's own credentials and settings).
	OwnerEnv []string
	// contains filtered or unexported fields
}

HarnessKind is a coding harness a node runs as its brain with the owner's own credentials (ADR-0066: each harness has one BrainAdapter; callers never branch on the harness). The catalog is the single description a node manager (the bma CLI, a desktop app) needs: where a pinned release comes from and how it is verified, how the owner's login is checked and started, which of this process's variables carry the owner's credentials, and the adapter that runs it.

func HarnessByID added in v1.6.13

func HarnessByID(id string) (HarnessKind, bool)

HarnessByID finds a harness of the catalog.

func Harnesses added in v1.6.13

func Harnesses() []HarnessKind

Harnesses is the catalog, in the order a node manager offers them.

func (HarnessKind) Latest added in v1.6.13

func (h HarnessKind) Latest() HarnessRelease

Latest is the newest pinned release.

func (HarnessKind) NewBrain added in v1.6.13

func (h HarnessKind) NewBrain(ctx context.Context, executable string, opts ACPAgentOptions) (*BrainHost, error)

NewBrain starts the harness at executable (a pinned release's binary) as the brain of opts.Core: the harness id is declared, the owner's variables of this process are handed over, and the adapter checks the binary against the pins before anything runs (fail-closed).

func (HarnessKind) OwnerEnviron added in v1.6.13

func (h HarnessKind) OwnerEnviron(environ []string) []string

OwnerEnviron is the part of environ handed to the harness.

func (HarnessKind) Release added in v1.6.13

func (h HarnessKind) Release(version string) (HarnessRelease, bool)

Release finds a pinned release.

type HarnessMCPChannel

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

HarnessMCPChannel is the harness end of one MCP channel, isolated by (session_id, server_key), on any transport. Frames are raw MCP JSON-RPC exactly as the MCP server sent them: the harness is the MCP client.

func (*HarnessMCPChannel) Close

func (m *HarnessMCPChannel) Close() error

func (*HarnessMCPChannel) Read

func (m *HarnessMCPChannel) Read(ctx context.Context) ([]byte, error)

Read returns the next raw MCP frame. A closed channel returns an error; the executor reopens a fresh one (and a fresh MCP server process), so call Session.MCP again and re-initialize.

func (*HarnessMCPChannel) Write

func (m *HarnessMCPChannel) Write(ctx context.Context, frame []byte) error

type HarnessOptions

type HarnessOptions struct {
	// Authenticate verifies every WebSocket upgrade (control and MCP). nil
	// accepts every connection: use that only on a loopback listener.
	Authenticate func(r *http.Request) (Principal, error)
	// HeartbeatInterval and LeaseTTL are returned by executor.register. A
	// disconnected executor keeps its sessions and pending tool calls for
	// LeaseTTL; then they end and pending calls fail with
	// ErrToolOutcomeUnknown.
	HeartbeatInterval time.Duration
	LeaseTTL          time.Duration
	// RequestTimeout bounds harness-to-executor requests. Defaults to 30s.
	RequestTimeout time.Duration
	// Protocols are the accepted subprotocols in preference order. Defaults
	// to ProtocolV11 then ProtocolV1.
	Protocols []string

	// OnExecutor runs after each successful executor.register.
	OnExecutor func(*Executor)
	// OnSessionEvent persists session.event. nil accepts with a generated id.
	// The harness answers a retried JSON-RPC id with the first result.
	OnSessionEvent  func(ctx context.Context, executor *Executor, params SessionEventParams) (SessionEventResult, error)
	OnSessionStatus func(executor *Executor, params SessionStatusParams)
	OnToolProgress  func(executor *Executor, params ToolProgressParams)
	// OnProcessStatus receives the advisory process.status notification.
	OnProcessStatus func(executor *Executor, params ProcessStatusParams)
	OnLog           func(LogEvent)
	// Agent receives agent-capability traffic: agent session events,
	// previews and interactions. nil rejects them as unknown methods.
	Agent AgentPlatform
}

HarnessOptions configures a Harness.

type HarnessRelease added in v1.6.13

type HarnessRelease struct {
	Version   string
	Binary    string // file name of the executable inside the release directory
	Platforms map[string]HarnessArtifact
}

HarnessRelease is one pinned release: its version, and per GOOS/GOARCH the URL of the binary and its sha256.

func (HarnessRelease) Artifact added in v1.6.13

func (r HarnessRelease) Artifact() (HarnessArtifact, error)

Artifact is the release's binary for this platform.

type HarnessToolSlot added in v1.0.0

type HarnessToolSlot[In any] struct {
	// contains filtered or unexported fields
}

HarnessToolSlot calls one built-in tool from the harness end.

func (HarnessToolSlot[In]) Call added in v1.0.0

func (s HarnessToolSlot[In]) Call(ctx context.Context, input In, options CallToolOptions) (ToolResultParams, error)

Call sends tool.call with a typed input and waits for tool.result, as Session.CallTool.

type HarnessTools added in v1.0.0

HarnessTools has one typed entry per built-in tool: session.Tools.Bash.Call(...). computer_observe and computer_action have none until the contract defines their input members.

type HostTool added in v1.6.5

type HostTool struct {
	// Tool name the model sees and the tools endpoint runs (tool.json ToolName).
	Name string `json:"name"`
	// Tool description the model sees.
	Description string `json:"description"`
	// JSON Schema of the input object (type object), offered to the model as is.
	InputSchema map[string]any `json:"input_schema"`
	// The tool has no side effects on the machine (computer_observe), so the brain may run it concurrently with other read-only calls.
	ReadOnly bool `json:"read_only"`
	// Permission when turn.start metadata tool_policy does not name the tool. Absent: ask.
	Permission string `json:"permission,omitempty"`
}

HostTool Contract 1.8.0. One host tool of AgentTurnConfig.host_tools: the fields of the ACP initialize _meta.bma.hostTools entries the executor SDK declares for bma-dsh-acp (ADR-0027 2026-11-10), so a platform brain and a local brain offer the model the same tool. The platform sends the definitions of the executor SDK (computer_observe: input tool.json ComputerObserveInput; computer_action: input tool.json ComputerActionInput).

type InputSkillDocument added in v1.6.0

type InputSkillDocument struct {
	SkillID    string `json:"skill_id"`
	RevisionID string `json:"revision_id"`
	Name       string `json:"name"`
	Body       string `json:"body"`
	BodySHA256 string `json:"body_sha256"`
}

InputSkillDocument Exact SKILL.md bytes for one authorized frozen revision. Hash covers UTF-8 body bytes, independently verified by the executor. At most 256 KiB across the selected documents.

type InputSkillReceipt added in v1.6.0

type InputSkillReceipt struct {
	InputID string                     `json:"input_id"`
	Skills  []InputSkillVersionReceipt `json:"skills"`
}

InputSkillReceipt

type InputSkillVersionReceipt added in v1.6.0

type InputSkillVersionReceipt struct {
	SkillID    string `json:"skill_id"`
	RevisionID string `json:"revision_id"`
	BodySHA256 string `json:"body_sha256"`
}

InputSkillVersionReceipt

type InteractionCancelParams

type InteractionCancelParams struct {
	SessionID     string `json:"session_id"`
	InteractionID string `json:"interaction_id"`
	Reason        string `json:"reason"`
}

InteractionCancelParams is the params object of interaction.cancel.

type InteractionQuestion

type InteractionQuestion struct {
	Prompt        string                      `json:"prompt"`
	Options       []InteractionQuestionOption `json:"options,omitempty"`
	MultiSelect   bool                        `json:"multi_select,omitempty"`
	AllowFreeText bool                        `json:"allow_free_text,omitempty"`
}

InteractionQuestion Question shown to the user.

type InteractionQuestionOption

type InteractionQuestionOption struct {
	ID    string `json:"id"`
	Label string `json:"label"`
}

InteractionQuestionOption One answer option of a question interaction.

type InteractionRequestParams

type InteractionRequestParams struct {
	SessionID string `json:"session_id"`
	TurnID    string `json:"turn_id"`
	// Executor-assigned, unique within the session and stable for the same tool call or question across executor and brain restarts (derive it from the session, the turn and the call, for example appr_ + the first 24 hex chars of sha256(session_id, NUL, turn_id, NUL, call_id); the turn is part of it because some providers reuse call ids such as call_0 in every turn), so a restarted executor asks again with the same id and gets the same platform interaction, and an answer given while it was offline, back. The platform interaction is the one card every client of the session shows; a local UI shows the same interaction rather than a separate local prompt.
	InteractionID string `json:"interaction_id"`
	Kind          string `json:"kind"`
	// Required for permission.
	ToolUseID string         `json:"tool_use_id,omitempty"`
	ToolName  string         `json:"tool_name,omitempty"`
	ToolInput map[string]any `json:"tool_input,omitempty"`
	// Grant scopes the user may pick for permission; defaults to once.
	Scopes []string `json:"scopes,omitempty"`
	// Required for question.
	Question *InteractionQuestion `json:"question,omitempty"`
	// RFC 3339 time after which the executor stops waiting.
	ExpiresAt string `json:"expires_at,omitempty"`
}

InteractionRequestParams is the params object of interaction.request.

type InteractionRequestResult

type InteractionRequestResult struct {
	Accepted              bool   `json:"accepted"`
	PlatformInteractionID string `json:"platform_interaction_id"`
}

InteractionRequestResult interaction.request result. Idempotent by interaction_id: a repeat returns the same platform interaction. platform_interaction_id equals interaction_id when that is an appr_ plus 24 lower-case hex id (adopted); otherwise it is the platform-assigned int_ id.

func SendInteractionRequest

func SendInteractionRequest(ctx context.Context, rpc RPC, params InteractionRequestParams) (InteractionRequestResult, error)

SendInteractionRequest calls interaction.request.

type InteractionResponder

type InteractionResponder struct {
	ActorID string `json:"actor_id,omitempty"`
	Surface string `json:"surface,omitempty"`
}

InteractionResponder Who answered, for local audit. surface is the client that resolved it, for example desktop, mobile, web, slack.

type InteractionResponseParams

type InteractionResponseParams struct {
	SessionID     string `json:"session_id"`
	InteractionID string `json:"interaction_id"`
	Outcome       string `json:"outcome"`
	// Granted scope for allow.
	Scope       string `json:"scope,omitempty"`
	DenyMessage string `json:"deny_message,omitempty"`
	// Selected option ids or free text for answered.
	Answers   []string              `json:"answers,omitempty"`
	Responder *InteractionResponder `json:"responder,omitempty"`
}

InteractionResponseParams is the params object of interaction.response.

type InteractionResponseResult

type InteractionResponseResult struct {
	Accepted bool `json:"accepted"`
}

InteractionResponseResult interaction.response result. accepted=false when the interaction is unknown or already resolved (first answer wins); the platform then marks its copy stale.

type JSONRPCError

type JSONRPCError struct {
	Code    int               `json:"code"`
	Message string            `json:"message"`
	Data    *JSONRPCErrorData `json:"data,omitempty"`
}

JSONRPCError JSON-RPC 2.0 error object.

type JSONRPCErrorData

type JSONRPCErrorData struct {
	// Capacity or timeout failure the caller should retry with backoff.
	Retryable bool   `json:"retryable,omitempty"`
	Detail    string `json:"detail,omitempty"`
	// Missing capability for -32012, for example "tool:read" or "process.pty".
	Capability string `json:"capability,omitempty"`
	// Machine-readable cause; an open set that the harness passes through unchanged (process.start: the tool result error_code and the process state reason; turn.start: the session.error code). Recommended values: workspace_unavailable, workspace_boundary, workspace_read_only, session_rejected, local_confirmation_denied, local_confirmation_expired, spawn_failed / process_id_spec_mismatch for process.start, capability_missing for executor.register, and turn_inactive / forbidden / model_token_unavailable for model_token.refresh and turn_inactive / forbidden / tools_token_unavailable for tools_token.refresh (contract 1.4.0). The tool result error_code of a platform tool call (the platform tools endpoint, ToolErrorCode in the AsyncAPI x-bma-platform-tools) is an open set that also includes environment_unavailable, machine_starting, machine_rebuilding, permission_denied, approval_required, approval_invalid, in_progress and idempotency_key_reused (contract 1.4.0), and for computer use calls desktop_busy (another session's turn holds the machine's desktop) and desktop_human_control (a person holds the desktop's control lease: computer_observe and computer_action are both refused, nothing runs and no screenshot is taken; after the hand-back the caller observes again before acting). generate_image adds content_policy_violation, invalid_image_input, rate_limited, image_model_unavailable, image_model_not_allowed and billing_suspended (contract 1.26.0). Receivers must accept values they do not know.
	Reason string `json:"reason,omitempty"`
	// bma.terminal.v1 error code for a failed terminal.* call.
	TerminalCode string `json:"terminal_code,omitempty"`
	// Agent session.event gap (-32013): the sequence the harness expects next.
	ExpectedSequence int64 `json:"expected_sequence,omitempty"`
}

JSONRPCErrorData JSON-RPC error.data. Members are code-specific; unknown members are ignored.

type JSONRPCErrorResponse

type JSONRPCErrorResponse struct {
	JSONRPC string       `json:"jsonrpc"`
	ID      string       `json:"id"`
	Error   JSONRPCError `json:"error"`
}

JSONRPCErrorResponse JSON-RPC 2.0 error response envelope.

type JSONRPCNotification

type JSONRPCNotification struct {
	JSONRPC string          `json:"jsonrpc"`
	Method  string          `json:"method"`
	Params  json.RawMessage `json:"params"`
}

JSONRPCNotification JSON-RPC 2.0 notification envelope (no id).

type JSONRPCRequest

type JSONRPCRequest struct {
	JSONRPC string          `json:"jsonrpc"`
	ID      string          `json:"id"`
	Method  string          `json:"method"`
	Params  json.RawMessage `json:"params"`
}

JSONRPCRequest JSON-RPC 2.0 request envelope.

type JSONRPCSuccessResponse

type JSONRPCSuccessResponse struct {
	JSONRPC string          `json:"jsonrpc"`
	ID      string          `json:"id"`
	Result  json.RawMessage `json:"result"`
}

JSONRPCSuccessResponse JSON-RPC 2.0 success response envelope.

type LaunchFunc added in v1.1.0

type LaunchFunc func(ctx context.Context, req LaunchRequest) (LaunchSpec, error)

LaunchFunc is called once per new command process or package install (not for replays or file transfers), after the session's files are synced and before it is spawned. A package install calls the package manager and may run install scripts, so a hook that confines or refuses commands should check LaunchRequest.PackageInstall too. It may choose the directory (for example from the session's metadata), wrap argv in a sandbox command (sandbox-exec, bwrap) and change the environment. Returning an error refuses the start: an *RPCError (NewReasonError) is answered as is, so the harness sees its data.reason; any other error is answered as spawn_failed.

As CoreOptions.Launch it is called once per bash tool call, before its command starts (Core's tool.call and LocalToolRoute, so ACPAgent's own tools). Argv is then the shell command (bash -lc <command>; cmd.exe /d /s /c <command> on Windows). A refusal ends the call with an error result "<reason>: <message>" (the route's Code is the reason) and nothing starts. Use the same function for both options to give the brain's own commands and process.* one admission check and one sandbox.

type LaunchRequest added in v1.1.0

type LaunchRequest struct {
	// ProcessContext is the process.start's. For a bash tool (Tool set),
	// SessionID is the tool call's session and ProcessID is empty (a tool call
	// is no process.* process); a tool.call fills AgentSessionID, Metadata and
	// Client from the session.assign, a LocalToolRoute (ACPAgent) sets
	// AgentSessionID to its session and has no Metadata or Client.
	ProcessContext
	// Tool is "bash" when a bash tool call is about to start its command
	// (CoreOptions.Launch), "" for process.start. ToolCallID is then the
	// call's id.
	Tool       string
	ToolCallID string
	// WritePath is the additional file a local bash call asks to write.
	WritePath string
	// PackageInstall is set for a process.start package_install and nil for
	// a command. Argv, Cwd and Env are then the installer's fixed command
	// (PackageInstallCommand): the hook may wrap it, change its environment
	// or directory, or refuse it, but the packages come from here.
	PackageInstall *ProcessPackageInstall
	Argv           []string
	// Cwd is the requested cwd as sent (not resolved or confined); for a
	// package install, the installer command's Dir.
	Cwd string
	// DefaultCwd is the session workspace, the cwd used when the hook
	// returns no Dir and the request names none.
	DefaultCwd string
	// Env is the complete environment the process would get.
	Env []string
}

LaunchRequest is one command process, package install or bash tool command about to start.

type LaunchSpec added in v1.1.0

type LaunchSpec struct {
	// Dir is an absolute directory; it is not confined to the workspace.
	Dir  string
	Argv []string
	// Env is the complete environment.
	Env []string
}

LaunchSpec is how the process starts. An empty field keeps the request's value: no Dir resolves the requested cwd inside the session workspace as without a hook, no Argv runs the requested command, a nil Env keeps the computed environment.

type Lease

type Lease struct {
	Token        string `json:"token"`
	FencingToken int64  `json:"fencing_token"`
}

Lease Fencing lease for a session assignment.

type Limits

type Limits struct {
	MaxInflightRequests       int   `json:"max_inflight_requests"`
	MaxConcurrentProcessReads int   `json:"max_concurrent_process_reads"`
	MaxProcessReadBytes       int   `json:"max_process_read_bytes"`
	MaxProcessWriteBytes      int   `json:"max_process_write_bytes"`
	MaxProcessesPerSession    int   `json:"max_processes_per_session"`
	MaxArtifactBytes          int64 `json:"max_artifact_bytes"`
}

Limits Limits the executor must enforce, advertised in the v1.1 executor.register result (v1.1 §1.3).

type ListFilesInput added in v1.0.0

type ListFilesInput struct {
	// Directory, relative to the session workspace.
	Path string `json:"path,omitempty"`
}

ListFilesInput list_files input.

type LocalToolRoute added in v1.4.0

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

LocalToolRoute runs a brain's tool calls on this machine, in a Core: the hands are here. It is the counterpart of PlatformToolRoute, and the two are held to the same conformance suite (package conformance, cases T1–T11): a brain cannot tell which one it is talking to. What the platform's tool gateway does for a remote machine (ADR-0005), this route does for itself, because the brain is not trusted to have asked:

  • the call must belong to the turn the route was made for: a call after the turn ended or was canceled, or from an older brain process once a newer turn of the session began, is refused (stale_turn);
  • the tool's permission is re-evaluated from the permission mode and ToolPolicy: deny refuses (permission_denied), and ask needs the user's allow for this very call: the answer the platform gave under the deterministic approval id (ApprovalID), for the same tool and the same input, recorded with RecordApproval. Without one the call is refused (approval_required); with another tool, input or approval it is refused (approval_invalid). One approval is good for one call id;
  • a call id runs at most once, also across restarts of the executor: the route keeps a small ledger per session under StateDir ("started" before the tool runs, "done" with its result after). A repeated call is answered with the first result (RouteResult.Replayed); one that was started and whose result was lost with the process has an unknown outcome and is not run again (outcome_unknown, ADR-0013). A refused call is not recorded: it did not run and may be asked for again once approved.

Its tools are the CMA agent_toolset (bash, read, write, edit, glob, grep) in the session's Workspace, through the Core's file roots. bash waits at most its timeout (and 55 s) and leaves a command that outlives the wait running: the call then answers with its pid and the file its output goes to (RouteResult.Background), like the platform gateway. When the Core has a CoreOptions.Launch hook, every bash command starts through it, as a process.start does; a command it refuses did not run: the call is not_forwarded with the hook's reason as Code (spawn_failed for a plain error). That answer is recorded like a result (the same call id is answered with it again), as the platform gateway records what the hands answered.

A LocalToolRoute is bound to one turn of one session and is safe for concurrent use. ACPAgent uses it for the turns whose hands are this machine.

func NewLocalToolRoute added in v1.4.0

func NewLocalToolRoute(opts LocalToolRouteOptions) (*LocalToolRoute, error)

NewLocalToolRoute returns the route of one turn to this machine's Core. It opens the session in the Core (idempotent) and begins the turn in the session's ledger: the same TurnID again (a restart) keeps what the ledger knows, another TurnID replaces it.

func (*LocalToolRoute) Call added in v1.4.0

Call implements ToolRoute.

func (*LocalToolRoute) CloseSession added in v1.4.0

func (r *LocalToolRoute) CloseSession()

CloseSession ends the session on this machine: its running tools and background commands stop, and its workspace state and turn state are released. It ends the session for every route of it.

func (*LocalToolRoute) Complete added in v1.4.0

func (r *LocalToolRoute) Complete()

Complete says the turn ended without being canceled or running out of time. A bash command left in the background then lives on after the turn's Context ends (until it exits, until an hour has passed or CloseSession); otherwise it is killed with the turn. Call it before canceling the Context.

func (*LocalToolRoute) RecordApproval added in v1.4.0

func (r *LocalToolRoute) RecordApproval(callID string, request InteractionRequestParams, answer InteractionResponseParams) error

RecordApproval records the platform's answer to the permission interaction of a call, which is what the route's gate checks before it runs an ask tool. request is what the brain asked the platform (AgentTurn.RequestInteraction) and answer what came back: only an allow or a deny is recorded (anything else, such as expired, leaves the call without an approval). The answer must be for the interaction asked; its id should be ApprovalID(session, turn, call), or the call is refused as approval_invalid.

type LocalToolRouteOptions added in v1.4.0

type LocalToolRouteOptions struct {
	// Core runs the tools. Required. The route opens the session in it
	// (Workspace) and CloseSession closes it.
	Core *Core
	// StateDir holds the turn state: one small file per session, written
	// atomically. Required. Make it survive the executor's restarts to get the
	// at-most-once guarantee across them.
	StateDir string
	// SessionID and TurnID are the platform session and turn the route is for.
	// Required. A route made for a turn after another one of the same session
	// started makes the earlier route stale.
	SessionID string
	TurnID    string
	// Workspace is the tools' working directory: relative paths and bash start
	// there. It must be an existing absolute directory. Required.
	Workspace string
	// PermissionMode is the session's permission mode: "default" (also "") or
	// "accept_edits" (write and edit are allowed without approval).
	PermissionMode string
	// ToolPolicy overrides the permission of tools (tool name to allow, ask or
	// deny). A tool no mode default or override names is ask (fail-closed).
	ToolPolicy map[string]string
	// SessionFilesRoot is the executor's capabilities.session_files.root. When
	// set, the file tools also reach this session's <root>/<SessionID>/uploads,
	// skills (read-only) and outputs (writable), and nothing else below the
	// root; see ACPAgentOptions.SessionFilesRoot. Absolute, or empty.
	SessionFilesRoot string
	// Context ends with the turn: a canceled Context ends the calls in flight,
	// makes later calls stale_turn and ends commands left in the background
	// (unless Complete was called first). Default: never ends.
	Context context.Context
	// OnLog tells about turn state problems.
	OnLog func(level LogLevel, message string, err error)
}

LocalToolRouteOptions configures NewLocalToolRoute.

type LogEvent

type LogEvent struct {
	Level   LogLevel
	Message string
	Err     error
}

LogEvent is emitted through Options.OnLog.

type LogLevel

type LogLevel string
const (
	LogDebug LogLevel = "debug"
	LogInfo  LogLevel = "info"
	LogWarn  LogLevel = "warn"
	LogError LogLevel = "error"
)

type MCPCapability

type MCPCapability struct {
	Stdio      bool `json:"stdio,omitempty"`
	HTTP       bool `json:"http,omitempty"`
	MaxServers int  `json:"max_servers,omitempty"`
	// The executor accepts transport.secret_env on stdio servers: resolved secret values it injects only into the server process environment, never persisting, logging or echoing them. Without it the server keeps secret: references in env, which the executor rejects.
	SecretEnv bool `json:"secret_env,omitempty"`
}

MCPCapability Environment-origin MCP servers.

type MCPChannel

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

MCPChannel is a raw MCP JSON-RPC transport on the executor MCP channel. The payload is unframed MCP JSON-RPC: the caller sends initialize, notifications/initialized, tools/list and tools/call directly, exactly as the protocol appendix defines. It runs on the client's transport: WebSocket, a Unix socket or in-process.

func (*MCPChannel) Close

func (m *MCPChannel) Close() error

Close closes the MCP channel.

func (*MCPChannel) Read

func (m *MCPChannel) Read(ctx context.Context) ([]byte, error)

Read returns one MCP JSON-RPC frame: one transport message per call.

func (*MCPChannel) Write

func (m *MCPChannel) Write(ctx context.Context, payload []byte) error

Write sends one MCP JSON-RPC frame as a text message.

type MCPContentBlock

type MCPContentBlock struct {
	Type     string `json:"type"`
	Text     string `json:"text,omitempty"`
	Data     string `json:"data,omitempty"`
	MimeType string `json:"mimeType,omitempty"`
	Resource any    `json:"resource,omitempty"`
}

MCPContentBlock MCP tool content block. Large binary content must go to artifact storage.

type MCPImplementation

type MCPImplementation struct {
	Name    string `json:"name"`
	Version string `json:"version"`
}

MCPImplementation

type MCPInitializeParams

type MCPInitializeParams struct {
	ProtocolVersion string            `json:"protocolVersion"`
	Capabilities    map[string]any    `json:"capabilities"`
	ClientInfo      MCPImplementation `json:"clientInfo"`
}

MCPInitializeParams

type MCPInitializeResult

type MCPInitializeResult struct {
	ProtocolVersion string            `json:"protocolVersion"`
	Capabilities    map[string]any    `json:"capabilities"`
	ServerInfo      MCPImplementation `json:"serverInfo"`
}

MCPInitializeResult

type MCPJSONRPCError

type MCPJSONRPCError struct {
	Code    int64  `json:"code"`
	Message string `json:"message"`
	Data    any    `json:"data,omitempty"`
}

MCPJSONRPCError

type MCPJSONRPCErrorResponse

type MCPJSONRPCErrorResponse struct {
	JSONRPC string          `json:"jsonrpc"`
	ID      json.RawMessage `json:"id"`
	Error   MCPJSONRPCError `json:"error"`
}

MCPJSONRPCErrorResponse

type MCPJSONRPCNotification

type MCPJSONRPCNotification struct {
	JSONRPC string         `json:"jsonrpc"`
	Method  string         `json:"method"`
	Params  map[string]any `json:"params,omitempty"`
}

MCPJSONRPCNotification

type MCPJSONRPCRequest

type MCPJSONRPCRequest struct {
	JSONRPC string          `json:"jsonrpc"`
	ID      json.RawMessage `json:"id"`
	Method  string          `json:"method"`
	Params  map[string]any  `json:"params,omitempty"`
}

MCPJSONRPCRequest

type MCPJSONRPCSuccessResponse

type MCPJSONRPCSuccessResponse struct {
	JSONRPC string          `json:"jsonrpc"`
	ID      json.RawMessage `json:"id"`
	Result  any             `json:"result"`
}

MCPJSONRPCSuccessResponse

type MCPProgressParams

type MCPProgressParams struct {
	ProgressToken json.RawMessage `json:"progressToken"`
	Progress      float64         `json:"progress"`
	Total         float64         `json:"total,omitempty"`
}

MCPProgressParams

type MCPServerConfig

type MCPServerConfig struct {
	ServerKey        string             `json:"server_key"`
	ConnectionOrigin string             `json:"connection_origin"`
	Transport        MCPServerTransport `json:"transport"`
}

MCPServerConfig

type MCPServerTransport

type MCPServerTransport struct {
	Type string `json:"type"`
	// stdio: absolute or allowlisted executable. No shell, no sh -c.
	Command string   `json:"command,omitempty"`
	Args    []string `json:"args,omitempty"`
	// stdio: working directory under the session workspace.
	Cwd string            `json:"cwd,omitempty"`
	Env map[string]string `json:"env,omitempty"`
	// stdio: sensitive variables the server resolved from env secret: references for this session, sent only to an executor that advertises capabilities.mcp.secret_env. The executor adds them to the server process environment only; it must not write them to disk, logs, argv or events, and drops them when the session ends. A name must not also appear in env.
	SecretEnv map[string]string `json:"secret_env,omitempty"`
	TimeoutMS int64             `json:"timeout_ms,omitempty"`
	// Pins the executable when supplied.
	CommandSHA256 string `json:"command_sha256,omitempty"`
	// http: Streamable HTTP MCP endpoint.
	URL string `json:"url,omitempty"`
}

MCPServerTransport Transport for one MCP server. stdio requires command; http requires url. Fields for the other transport are omitted.

type MCPTool

type MCPTool struct {
	Name        string         `json:"name"`
	Description string         `json:"description,omitempty"`
	InputSchema map[string]any `json:"inputSchema"`
}

MCPTool

type MCPToolDefinition added in v1.6.34

type MCPToolDefinition struct {
	// Name the model sees and the tools endpoint runs: mcp__<mcp_server_name>__<tool_name>, at most 64 characters. A tool whose name would not fit the pattern is not offered.
	Name string `json:"name"`
	// The agent's name of the MCP server (mcp_servers[].name); agent.mcp_tool_use.mcp_server_name.
	MCPServerName string `json:"mcp_server_name"`
	// The server's own name of the tool (MCP tools/list name); agent.mcp_tool_use.name.
	ToolName string `json:"tool_name"`
	// The server's description of the tool; absent when it gave none.
	Description string `json:"description,omitempty"`
	// The server's JSON Schema of the input object (type object), offered to the model as is.
	InputSchema map[string]any `json:"input_schema"`
	// The mcp_toolset permission of the tool (always_allow: allow, always_ask: ask). ask: the brain asks once per call (interaction kind permission, the brain's deterministic interaction id) and sends the answer as ai.beeos.bma/approval; the tools endpoint evaluates the same policy again.
	Permission string `json:"permission"`
}

MCPToolDefinition Contract 1.14.0. One tool of an MCP server of the turn's agent, as AgentTurnConfig.mcp_tools carries it.

type MCPToolsCallParams

type MCPToolsCallParams struct {
	Name      string         `json:"name"`
	Arguments map[string]any `json:"arguments"`
}

MCPToolsCallParams

type MCPToolsCallResult

type MCPToolsCallResult struct {
	Content           []MCPContentBlock `json:"content"`
	IsError           bool              `json:"isError,omitempty"`
	StructuredContent any               `json:"structuredContent,omitempty"`
}

MCPToolsCallResult

type MCPToolsListParams

type MCPToolsListParams struct {
	Cursor string `json:"cursor,omitempty"`
}

MCPToolsListParams

type MCPToolsListResult

type MCPToolsListResult struct {
	Tools      []MCPTool `json:"tools"`
	NextCursor *string   `json:"nextCursor,omitempty"`
}

MCPToolsListResult

type MethodDirection

type MethodDirection string

MethodDirection is the direction a JSON-RPC method travels.

const (
	DirectionExecutorToHarness MethodDirection = "executor-to-harness"
	DirectionHarnessToExecutor MethodDirection = "harness-to-executor"
	DirectionBidirectional     MethodDirection = "bidirectional"
)

type MethodSpec

type MethodSpec struct {
	Name         string
	Direction    MethodDirection
	Notification bool
	Since        string
	Capability   string
	IdempotentBy string
}

MethodSpec describes one executor protocol method. Since is the first protocol that has it; Capability is the capability bit the harness checks before sending it (empty: always available).

type ModelTokenRefreshParams added in v1.3.0

type ModelTokenRefreshParams struct {
	// Platform session id of the turn.
	SessionID string `json:"session_id"`
	// Platform id of the running turn the token is for.
	TurnID string `json:"turn_id"`
}

ModelTokenRefreshParams is the params object of model_token.refresh.

type ModelTokenRefreshResult added in v1.3.0

type ModelTokenRefreshResult struct {
	// Bearer token for model_base_url. Valid until expires_at.
	ModelToken string `json:"model_token"`
	// Base URL the token is for (an OpenAI / Anthropic base URL path).
	ModelBaseURL string `json:"model_base_url"`
	// RFC 3339 time the token stops being accepted.
	ExpiresAt string `json:"expires_at"`
}

ModelTokenRefreshResult model_token.refresh result: the credential for the turn's next model calls, in the form of the turn.start metadata model_base_url and model_token.

func SendModelTokenRefresh added in v1.3.0

func SendModelTokenRefresh(ctx context.Context, rpc RPC, params ModelTokenRefreshParams) (ModelTokenRefreshResult, error)

SendModelTokenRefresh calls model_token.refresh.

type NativeDesktopInput added in v1.6.5

type NativeDesktopInput interface {
	Apply(context.Context, DesktopInputEvent) error
	ReleaseAll(context.Context) error
}

NativeDesktopInput must perform one bounded synchronous native operation. ReleaseAll releases only keys/buttons this executor injected, not local input.

func NewNativeDesktopInput added in v1.6.5

func NewNativeDesktopInput() (NativeDesktopInput, error)

type NativeDesktopLease added in v1.12.0

type NativeDesktopLease interface {
	Hold(ctx context.Context, until time.Time) error
	Drop(ctx context.Context, resume bool) error
}

NativeDesktopLease is optional: an input device that keeps its own exclusive control lease, such as a phone whose own agent must stop while a person controls it. Hold takes or extends that lease until the human lease's deadline: on a grant before the human's first input, and on every renew. Drop gives it up when the human lease ends, after the human's input was released; resume is true for a handback (the device lets its agent act again), false for a release or an expiry. A failed Drop is retried by the next release of the same lease.

type NativeDesktopResizer added in v1.6.38

type NativeDesktopResizer interface {
	Resize(ctx context.Context, width, height, scale uint16) error
}

NativeDesktopResizer is optional. Resize fits the desktop to a viewer of width x height device pixels whose devicePixelRatio × 100 is scale (0 = not sent: 1×). It must return only after its native operation has ended, including after cancellation. Unsupported is a refusal before dispatch; it must never represent an uncertain native outcome.

type NativeDesktopRestorer added in v1.6.39

type NativeDesktopRestorer interface {
	RestoreDesktop(context.Context) error
}

NativeDesktopRestorer is optional. RestoreDesktop undoes every Resize since the previous restore (a no-op when there was none). The gate calls it when a human lease ends, after its input is released; it reports its own failures, which never change the control outcome.

type NotificationMethod added in v1.0.0

type NotificationMethod[P any] struct{ Method string }

NotificationMethod is an executor-to-harness notification with params P.

func (NotificationMethod[P]) Notify added in v1.0.0

func (m NotificationMethod[P]) Notify(ctx context.Context, client *Client, params P) error

Notify sends the notification on the client's control channel.

type OpenAppResult added in v1.6.9

type OpenAppResult struct {
	PID            int
	BundleID, Name string
	// Front reports that the app was brought to the front; FrontError is
	// the reason it was not.
	Front      bool
	FrontError string
	// Recovery are the steps taken because the app was not brought to the
	// front or showed no usable window, in order.
	Recovery []string
	// Windows are the app's windows on the current desktop: the ones the
	// model can observe and act on. Hidden counts the others (minimized,
	// hidden or on another Space).
	Windows []ComputerWindow
	Hidden  int
	// contains filtered or unexported fields
}

OpenAppResult is what CuaDriver.OpenApp did.

type Options

type Options struct {
	// EnvironmentKey is the bearer of the token exchange: an environment key
	// (POST /v1/environments/{EnvironmentID}/token), or a machine daemon token
	// for a machine-scoped executor (POST /v1/machines/{MachineID}/token).
	EnvironmentKey string
	// EnvironmentID is the selfhost environment. EnvironmentID and MachineID
	// are alternatives: setting both is an error. With neither the client
	// registers a machine-scoped executor on the legacy machine token alias
	// POST /api/v1/executors/token; an environment key always needs
	// EnvironmentID.
	EnvironmentID string
	// MachineID is the machine of a machine-scoped executor, taken from
	// BMA_MACHINE_ID (MachineIDEnv) when empty and EnvironmentID is empty.
	// The id must equal the machine of the credential, otherwise the server
	// answers 404.
	MachineID    string
	Executor     ExecutorInfo
	Capabilities Capabilities
	// Labels are reported with executor.register (ExecutorInfo.Labels, contract
	// 1.4.0) and added to Executor.Labels: at most 32, each 1-64 characters of
	// a-z 0-9 . _ - . They are the machine owner's local configuration; the
	// platform accepts them as given and uses them only to narrow a choice
	// among machines the project is already authorized to use, never for an
	// authorization or security decision.
	Labels []string
	// RemoteBrain is the machine owner's consent to let a brain that runs on
	// another machine use this machine as its hands (Capabilities.RemoteBrain,
	// contract 1.4.0). It is off unless the owner turns it on here, in the
	// executor's local configuration; the platform only reads it back and has
	// no way to switch it on. It applies to a machine the tenant owns; a
	// platform-hosted brain driving this machine does not need it.
	RemoteBrain bool
	// Protocol is the WebSocket subprotocol and executor.register protocol.
	// Defaults to ProtocolV11.
	Protocol string

	BaseURL string
	WSURL   string
	// TokenSource replaces the token exchange bootstrap, for example
	// StaticToken for a local harness. When set, EnvironmentKey and BaseURL
	// are not used.
	TokenSource func(ctx context.Context) (ExecutorTokenResponse, error)
	// Dial opens the control connection. Defaults to WebSocketDialer with
	// HTTPClient; see UnixSocketDialer, ListenUnixSocket and InProcessDialer.
	Dial Dialer
	// HTTPClient is used for the token request, artifact uploads and the
	// default WebSocket dial. Defaults to http.DefaultClient.
	HTTPClient *http.Client
	// RequestTimeout bounds one JSON-RPC request. Defaults to 30s.
	RequestTimeout time.Duration
	// HeartbeatInterval overrides the interval returned by executor.register.
	HeartbeatInterval time.Duration
	// HeartbeatLoad is sampled for each heartbeat.
	HeartbeatLoad func() *ExecutorLoad
	// MaxReconnectAttempts bounds consecutive failed reconnects; the client
	// then ends with ErrReconnectExhausted (see Done and Err). Zero (the
	// default) or a negative value reconnects until Stop.
	MaxReconnectAttempts int
	// ReconnectBaseDelay is the first reconnect backoff (default 1s); it
	// doubles per failed attempt up to ReconnectMaxDelay, with jitter.
	ReconnectBaseDelay time.Duration
	// ReconnectMaxDelay caps the reconnect backoff before jitter. Defaults
	// to 60s.
	ReconnectMaxDelay time.Duration
	Random            func() float64
	// ToolResultRetryAttempts is the total number of attempts for tool.result,
	// session.ready and session.ended, including the first. It defaults to 5;
	// set it to 1 to disable retries.
	ToolResultRetryAttempts int
	// ToolResultRetryBaseDelay is the first backoff for retryable failures.
	// It defaults to 250ms and doubles per attempt up to 10s.
	ToolResultRetryBaseDelay time.Duration
	// OnToolResultLost is called by the dispatch path when a tool result could
	// not be accepted after all retries, or the error is not retryable. The
	// adapter must persist the result and replay it with the same
	// tool_call_id; the client never drops a result silently.
	OnToolResultLost func(params ToolResultParams, err error)
	OnLog            func(LogEvent)
}

Options configures a Client.

type PackageInstallCommand

type PackageInstallCommand struct {
	Argv       []string
	Dir        string
	Env        []string
	Privileged bool
}

PackageInstallCommand is the fixed command one package install runs. Env is its complete environment. Privileged runs it with the executor's own identity instead of CoreOptions.RunAs: system package managers need root, user-level ones must not get it.

type PackageInstaller

type PackageInstaller interface {
	PackageInstallCommand(processID string, install ProcessPackageInstall) (PackageInstallCommand, error)
}

PackageInstaller builds the command for a process.start package_install. The core has already checked manager and packages against the contract (one of apt, pip, npm; plain package names only), so the installer passes the packages as separate arguments after its own fixed options.

type PlatformTool added in v1.15.0

type PlatformTool struct {
	// Tool name the model sees and the tools endpoint runs. generate_image: input tool.json GenerateImageInput (with the turn's model enum), structuredContent tool.json GenerateImageResult.
	Name string `json:"name"`
	// Tool description the model sees.
	Description string `json:"description"`
	// JSON Schema of the input object (type object), offered to the model as is.
	InputSchema map[string]any `json:"input_schema"`
	// The agent's permission policy of the tool (always_allow: allow, always_ask: ask), used when turn.start metadata tool_policy does not name it; the tools endpoint evaluates the same policy again.
	Permission string `json:"permission"`
}

PlatformTool Contract 1.26.0. One tool of AgentTurnConfig.platform_tools: a tool the platform runs on no machine (x-bma-platform-tools platform-tools).

type PlatformToolRoute added in v1.4.0

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

PlatformToolRoute sends a brain's tool calls to the platform's execute-only tool gateway (ADR-0005), an MCP Streamable HTTP endpoint, instead of running them here: the hands are on another machine. The gateway does what the local route does for itself (token and epoch, policy re-check, approval check, at-most-once by idempotency key) and runs the tool in the session's machine; this side only speaks its wire and maps the answer to the same RouteResult as the local route.

The tool credential (session x turn x epoch) lives in memory only: it is never written to the state directory, to a log, to an error text or by String/%v. It is replaced before it expires (toolsCredential).

A brain gets one from AgentTurn.Tools for a turn whose turn.start metadata carries tools_mcp_* (the hands are on another machine), with the token refreshed through tools_token.refresh; NewPlatformToolRoute builds one from a credential the caller manages itself. ACPAgent uses it the same way; any other turn gets its local route.

func NewPlatformToolRoute added in v1.4.0

func NewPlatformToolRoute(opts PlatformToolRouteOptions) (*PlatformToolRoute, error)

NewPlatformToolRoute returns the route of one turn to the platform's tool gateway. Endpoint, Token, SessionID and TurnID are required. Most brains use AgentTurn.Tools instead, which fills this from turn.start and keeps the token fresh; use this when the credential comes from somewhere else.

func (*PlatformToolRoute) Call added in v1.4.0

Call implements ToolRoute.

func (*PlatformToolRoute) GoString added in v1.4.0

func (r *PlatformToolRoute) GoString() string

GoString keeps the credential out of %#v.

func (*PlatformToolRoute) String added in v1.4.0

func (r *PlatformToolRoute) String() string

String keeps the credential out of %v / %+v / %s.

type PlatformToolRouteOptions added in v1.4.0

type PlatformToolRouteOptions struct {
	// Endpoint is the gateway's MCP URL.
	Endpoint string
	// Token is the turn's tool credential.
	Token string
	// ExpiresAt is when Token stops being accepted (zero: not said, never refreshed).
	ExpiresAt time.Time
	// Refresh replaces the credential before it expires (tools_token.refresh); nil: never refreshed.
	Refresh func(ctx context.Context) (ToolsTokenRefreshResult, error)
	// OnLog tells about a failed refresh (it is also retried; see toolsCredential).
	OnLog  func(level LogLevel, message string, err error)
	TurnID string
	// SessionID is the platform session of the turn (required by NewPlatformToolRoute).
	SessionID string
	// ApprovalFor returns the interaction id of the user's approval of a call,
	// or "" when there is none (ADR-0005: presented in _meta, checked by the gateway).
	ApprovalFor func(callID string) string
	// SyncWait, when set, is sent as the call's synchronous wait ceiling.
	SyncWait time.Duration
	// HTTPClient defaults to a client without a timeout; ctx ends a call.
	HTTPClient *http.Client
}

type Principal

type Principal struct {
	ExecutorID string
}

Principal is what HarnessOptions.Authenticate learns from an upgrade request. A non-empty ExecutorID pins the executor identity: register and MCP channels must belong to it.

type ProcessCapability

type ProcessCapability struct {
	Enabled      bool `json:"enabled"`
	MaxProcesses int  `json:"max_processes,omitempty"`
	BufferBytes  int  `json:"buffer_bytes,omitempty"`
	// Accepts process.start io_mode "pty".
	PTY bool `json:"pty,omitempty"`
	// Accepts process.start file_transfer.
	FileTransfer bool `json:"file_transfer,omitempty"`
	// Accepts process.start git_credentials.
	GitCredentials bool `json:"git_credentials,omitempty"`
	// Accepts process.start package_install.
	PackageInstall bool `json:"package_install,omitempty"`
}

ProcessCapability v1.1 process.* support. pty, file_transfer, package_install and git_credentials are additive: the harness only sends the matching process.start fields to an executor that set them, and fails the process explicitly otherwise.

type ProcessContext added in v1.1.0

type ProcessContext struct {
	// SessionID is the executor session (session.assign) of the process.
	SessionID string
	ProcessID string
	// AgentSessionID is process.start metadata agent_session_id: the agent
	// session the process runs for ("" when the harness named none). Pass it
	// to Client.SessionContextByID, or the process id to
	// Client.SessionContext, to read the session's metadata.
	AgentSessionID string
	Metadata       map[string]string
	// Client is the connection of the brain that started the process (for
	// machine-token requests such as a file transfer).
	Client *Client
}

ProcessContext identifies the process a hook runs for.

type ProcessFileTransfer

type ProcessFileTransfer struct {
	Direction string `json:"direction"`
	LocalPath string `json:"local_path"`
}

ProcessFileTransfer Replaces argv: the executor moves one file between the machine and the process BMA file endpoint and reports the outcome in ProcessState.file_transfer. Requires process.file_transfer.

type ProcessListParams

type ProcessListParams struct {
	SessionID string `json:"session_id"`
}

ProcessListParams is the params object of process.list.

type ProcessListResult

type ProcessListResult struct {
	Processes []ProcessState `json:"processes"`
}

ProcessListResult process.list result.

type ProcessOptions

type ProcessOptions struct {
	// Env is set on every process (not on bash tools) over the request env,
	// for example a canonical skill root such as BMA_HOME.
	Env            map[string]string
	FileTransfer   FileTransferer
	GitCredentials GitCredentialGranter
	// PackageInstaller serves process.start package_install.
	PackageInstaller PackageInstaller
	// Launch runs before each new command process starts; see LaunchFunc.
	Launch LaunchFunc
	// SessionFiles syncs each agent session's files below its root, which
	// is advertised as capabilities.session_files.root; see SessionFiles.
	SessionFiles *SessionFiles
}

ProcessOptions configures the process capability. Nil hooks leave the matching capability bit unset, and the core rejects those process.start fields with capability_unavailable.

type ProcessPackageInstall

type ProcessPackageInstall struct {
	Manager  string   `json:"manager"`
	Packages []string `json:"packages"`
}

ProcessPackageInstall Replaces argv: the executor installs packages with a fixed command it builds itself, streaming the package manager output as the process output. apt installs from the machine's configured (official) sources with the executor's own privileges; pip (--user) and npm (global under the workload user's ~/.local) run as the workload user. Package names are plain names only: no options, versions, paths or URLs. Requires process.package_install.

type ProcessReadParams

type ProcessReadParams struct {
	SessionID string `json:"session_id"`
	ProcessID string `json:"process_id"`
	Stream    string `json:"stream"`
	Cursor    int64  `json:"cursor"`
	MaxBytes  int    `json:"max_bytes,omitempty"`
	WaitMS    int64  `json:"wait_ms,omitempty"`
}

ProcessReadParams is the params object of process.read.

type ProcessReadResult

type ProcessReadResult struct {
	ProcessID string `json:"process_id"`
	Stream    string `json:"stream"`
	// Base64 bytes from from_cursor to next_cursor.
	Data           string              `json:"data"`
	FromCursor     int64               `json:"from_cursor"`
	NextCursor     int64               `json:"next_cursor"`
	EarliestCursor int64               `json:"earliest_cursor"`
	Gap            bool                `json:"gap"`
	Truncated      bool                `json:"truncated"`
	EOF            bool                `json:"eof"`
	State          string              `json:"state"`
	EndedAt        string              `json:"ended_at,omitempty"`
	Reason         string              `json:"reason,omitempty"`
	ExitCode       *int                `json:"exit_code"`
	ExitSignal     *string             `json:"exit_signal"`
	FileTransfer   *FileTransferResult `json:"file_transfer,omitempty"`
	// Contract 2.5.0. Only on a read that reports an ended process of an agent session (metadata agent_session_id) on an executor with session_files: the outputs of that session the executor found changed since their last upload when the process ended, after it tried to upload them (retrying transient failures within its bound) and before it answered. uploaded=false means the upload has not gone through yet: the executor keeps retrying on its periodic scan, and a later read of the same ended process tries again and reports what is still pending. digest is the content the session left at path on the machine. Absent: the executor reports nothing (an older executor, or a process of no agent session).
	SessionOutputs []SessionOutputReport `json:"session_outputs,omitempty"`
}

ProcessReadResult process.read result.

type ProcessSignalParams

type ProcessSignalParams struct {
	SessionID string `json:"session_id"`
	ProcessID string `json:"process_id"`
	// Only meaningful for process.terminate.
	GraceMS *int64 `json:"grace_ms,omitempty"`
}

ProcessSignalParams is the params object of process.interrupt and process.terminate.

type ProcessStartParams

type ProcessStartParams struct {
	SessionID string `json:"session_id"`
	ProcessID string `json:"process_id"`
	// Command and arguments (at most 256 entries, 4 KiB each, 16 KiB total). Must be empty when file_transfer or package_install is set.
	Argv  []string          `json:"argv"`
	Cwd   string            `json:"cwd,omitempty"`
	Env   map[string]string `json:"env,omitempty"`
	Stdin string            `json:"stdin,omitempty"`
	// Empty keeps separate stdout/stderr streams.
	Stderr string `json:"stderr,omitempty"`
	WaitMS int64  `json:"wait_ms,omitempty"`
	// Kills the process and ends it as failed with reason "timeout".
	TimeoutMS int64 `json:"timeout_ms,omitempty"`
	// Who started the process. A process an agent tool started (a command, a file transfer, a package install) always carries agent_session_id (the public agent session id) and tool_call_id; it carries no initiator. A process the platform started on its own carries initiator "platform" and no agent_session_id. A process with neither is not started by the harness: an executor that resolves a directory, files or owner per session refuses it (reason session_rejected) instead of using a default. Human console terminals are terminal.attach, not process.start.
	Metadata map[string]string `json:"metadata,omitempty"`
	// Requires capability process.pty.
	IOMode string `json:"io_mode,omitempty"`
	// Requires capability process.file_transfer. Excludes argv entries, io_mode and git_credentials.
	FileTransfer *ProcessFileTransfer `json:"file_transfer,omitempty"`
	// Requires capability process.package_install. Excludes argv entries, io_mode, file_transfer and git_credentials.
	PackageInstall *ProcessPackageInstall `json:"package_install,omitempty"`
	// Installs a per-process Git credential helper for https://github.com that fetches short-lived tokens for this process while it runs. Requires capability process.git_credentials.
	GitCredentials bool `json:"git_credentials,omitempty"`
}

ProcessStartParams is the params object of process.start.

type ProcessState

type ProcessState struct {
	ProcessID    string              `json:"process_id"`
	State        string              `json:"state"`
	PID          int                 `json:"pid,omitempty"`
	StartedAt    string              `json:"started_at,omitempty"`
	EndedAt      string              `json:"ended_at,omitempty"`
	Reason       string              `json:"reason,omitempty"`
	Cursors      Cursors             `json:"cursors"`
	ExitCode     *int                `json:"exit_code"`
	ExitSignal   *string             `json:"exit_signal"`
	Stderr       string              `json:"stderr,omitempty"`
	Accepted     bool                `json:"accepted,omitempty"`
	FileTransfer *FileTransferResult `json:"file_transfer,omitempty"`
}

ProcessState Result of process.start/interrupt/terminate and one process.list entry. ended_at (RFC 3339, executor clock) is set once the process is no longer running; reason explains a "failed" state (for example "timeout"). A spawn failure never creates a state: it is the process.start error with data.reason "spawn_failed".

type ProcessStatusParams

type ProcessStatusParams struct {
	SessionID  string  `json:"session_id"`
	ProcessID  string  `json:"process_id"`
	State      string  `json:"state"`
	ExitCode   *int    `json:"exit_code,omitempty"`
	ExitSignal *string `json:"exit_signal,omitempty"`
	EndedAt    string  `json:"ended_at,omitempty"`
	Reason     string  `json:"reason,omitempty"`
	ObservedAt string  `json:"observed_at"`
}

ProcessStatusParams is the params object of process.status.

type ProcessWriteParams

type ProcessWriteParams struct {
	SessionID  string `json:"session_id"`
	ProcessID  string `json:"process_id"`
	Data       string `json:"data,omitempty"`
	CloseStdin bool   `json:"close_stdin,omitempty"`
}

ProcessWriteParams is the params object of process.write.

type ProcessWriteResult

type ProcessWriteResult struct {
	Accepted bool `json:"accepted"`
}

ProcessWriteResult process.write result.

type RPC

type RPC interface {
	Call(ctx context.Context, method string, params any, result any) error
	Notify(ctx context.Context, method string, params any) error
}

RPC is the transport contract implemented by the handwritten client.

type RPCError

type RPCError struct {
	Code    int
	Message string
	Data    *JSONRPCErrorData
}

RPCError is a JSON-RPC error returned by the peer, or returned by a handler to answer with a specific code and data.

func NewReasonError added in v1.1.0

func NewReasonError(code int, reason, message string) *RPCError

NewReasonError returns the JSON-RPC error a handler or a Launch hook returns to refuse a request with a machine-readable reason, for example NewReasonError(CodeForbidden, ReasonSessionRejected, "not this machine's user").

func (*RPCError) Error

func (e *RPCError) Error() string

type ReadInput added in v1.0.0

type ReadInput struct {
	// File path, relative to the session workspace.
	Path string `json:"path"`
	// First line to return, 1-based.
	Offset int64 `json:"offset,omitempty"`
	// Maximum number of lines.
	Limit int64 `json:"limit,omitempty"`
}

ReadInput read input: return lines of a text file.

type RemoteBrainCapability added in v1.3.0

type RemoteBrainCapability struct {
	Enabled bool `json:"enabled"`
}

RemoteBrainCapability Contract 1.4.0. The machine's owner allows a brain that runs on another machine to use this machine as its hands (platform tools routed here for a session whose brain machine is a different one). Set only by the executor's local configuration (bmad configuration or SDK Options.RemoteBrain); the platform reads it back and cannot switch it on through any API. Absent or enabled=false: off, which is also what an executor that predates 1.4.0 means. It applies to a BYO (tenant-owned) machine; a platform pool machine does not need it. It does not restrict a platform-hosted brain driving this machine (project authorization is enough there), and a brain and hands on one machine never need it.

type Request

type Request struct {
	Brain  string
	Method string
	// ID is the JSON-RPC request id, the idempotency key of retried writes.
	ID     string
	Params json.RawMessage
	// Session is the active session named by params.session_id for a
	// SessionScoped capability, nil otherwise.
	Session *CoreSession
	Client  *Client
}

Request is one inbound request routed to a Capability handler.

type RequestMethod added in v1.0.0

type RequestMethod[P, R any] struct{ Method string }

RequestMethod is a harness-to-executor request with params P and result R.

func (RequestMethod[P, R]) Handle added in v1.0.0

func (m RequestMethod[P, R]) Handle(client *Client, handler func(ctx context.Context, params P) (R, error))

Handle serves the request on client, replacing an earlier handler. Params that do not decode are answered -32602; return an *RPCError for another JSON-RPC error. RequestID(ctx) is the request's JSON-RPC id.

type RouteBackground added in v1.4.0

type RouteBackground struct {
	PID        int
	OutputFile string
}

RouteBackground is a command still running after its call returned.

type RouteCall added in v1.4.0

type RouteCall struct {
	// ID is the brain's tool call id. It is the call's idempotency identity:
	// the same ID in the same turn is run once, also when the brain process
	// restarts and asks again. It must be unique within the turn.
	ID string
	// ToolUseID is the event id of the call's agent.tool_use event (optional;
	// it ties the gateway's audit record to the event).
	ToolUseID string
	// Name is the tool: bash, read, write, edit, glob or grep.
	Name string
	// Input is the tool's input as the brain's JSON decoder produced it.
	Input map[string]any
	// ApprovalID is the interaction id of the user's approval of this call
	// (AgentTurn.RequestInteraction answered allow), or "" when the call needs
	// none. The gateway verifies it: one approval is good for one call, the
	// same tool and the same input.
	ApprovalID string
}

RouteCall is one tool call of a brain, in the CMA agent_toolset input shape (bash, read, write, edit, glob, grep; for example {"command": "ls"} for bash).

type RouteResult added in v1.4.0

type RouteResult struct {
	// Outcome is a RouteOutcome* value.
	Outcome string
	// Code is the reason of a refusal or an unclear outcome, for example
	// permission_denied, approval_required, approval_invalid, stale_turn,
	// environment_unavailable, in_progress, idempotency_key_reused,
	// tools_unavailable (open set; contract schemas/common.json lists them).
	Code string
	// Text is the tool's output, or "<Code>: <detail>" when Code is set.
	Text string
	// IsError: the call failed, was refused or its outcome is unknown.
	IsError bool
	// Replayed: the answer was saved from an earlier call with the same ID
	// (not run again).
	Replayed bool
	// Background: a command left running when the call stopped waiting
	// (bash past its synchronous wait).
	Background *RouteBackground
	// Images are image blocks of the result (computer_observe screenshots),
	// for the model with Text. A replayed result has none.
	Images []ContentBlock
}

RouteResult is the answer to a RouteCall.

type RunAs

type RunAs struct {
	UID, GID uint32
	// Groups are the supplementary groups (for example one that may write a
	// shared session directory); empty means none.
	Groups []uint32
	// Home and User replace the executor's HOME and USER.
	Home, User string
}

RunAs is a workload OS identity (CoreOptions.RunAs).

type ScreenControlParams added in v1.15.0

type ScreenControlParams struct {
	SessionID   string `json:"session_id"`
	Action      string `json:"action"`
	MachineID   string `json:"machine_id"`
	Epoch       int64  `json:"epoch"`
	LeaseID     string `json:"lease_id"`
	Identity    string `json:"identity,omitempty"`
	InputKey    string `json:"input_key,omitempty"`
	ExpiresAtMS int64  `json:"expires_at_ms,omitempty"`
}

ScreenControlParams is the params object of screen.control.

type ScreenControlResult added in v1.15.0

type ScreenControlResult struct {
	Accepted bool `json:"accepted"`
}

ScreenControlResult

type ScreenLiveCommand added in v1.6.5

type ScreenLiveCommand struct {
	Type              string `json:"type"`
	RequestID         string `json:"request_id"`
	SessionID         string `json:"session_id"`
	MachineID         string `json:"machine_id"`
	Generation        int64  `json:"generation"`
	Room              string `json:"room"`
	URL               string `json:"url,omitempty"`
	Token             string `json:"token,omitempty"`
	PublisherIdentity string `json:"publisher_identity,omitempty"`
	ExpiresAtMS       int64  `json:"expires_at_ms"`
	// Width x Height is the desktop size the session asked for, on
	// screen_live_start only; both are zero when the session left it to the machine.
	Width  uint16 `json:"width,omitempty"`
	Height uint16 `json:"height,omitempty"`
}

type ScreenLiveHandler added in v1.6.5

type ScreenLiveHandler func(context.Context, ScreenLiveCommand) (ScreenLiveResult, error)

type ScreenLiveParams added in v1.15.0

type ScreenLiveParams struct {
	Type              string `json:"type"`
	RequestID         string `json:"request_id"`
	SessionID         string `json:"session_id"`
	DesktopSessionID  string `json:"desktop_session_id,omitempty"`
	MachineID         string `json:"machine_id"`
	Generation        int64  `json:"generation"`
	Room              string `json:"room"`
	URL               string `json:"url,omitempty"`
	Token             string `json:"token,omitempty"`
	PublisherIdentity string `json:"publisher_identity,omitempty"`
	ExpiresAtMS       int64  `json:"expires_at_ms"`
	Width             int32  `json:"width,omitempty"`
	Height            int32  `json:"height,omitempty"`
}

ScreenLiveParams is the params object of screen.live.

type ScreenLivePipe added in v1.6.5

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

ScreenLivePipe multiplexes bounded, private parent IPC over stdout/stdin. Diagnostics remain on stderr. EOF cancels pending calls and lets the parent lifeline stop the executor. Tokens must never be copied into diagnostic logs.

func NewScreenLivePipe added in v1.6.5

func NewScreenLivePipe(reader io.Reader, writer io.WriteCloser) *ScreenLivePipe

func (*ScreenLivePipe) Call added in v1.6.5

func (*ScreenLivePipe) Done added in v1.6.5

func (p *ScreenLivePipe) Done() <-chan struct{}

func (*ScreenLivePipe) ParentDone added in v1.6.5

func (p *ScreenLivePipe) ParentDone() <-chan struct{}

ParentDone is the supervisor lifeline. Media timeout alone must not end Agent tasks.

func (*ScreenLivePipe) SetInputHandler added in v1.6.5

func (p *ScreenLivePipe) SetInputHandler(handler func(context.Context, DesktopInputMessage) error)

SetInputHandler is a private parent lane, not a renderer-authorized grant.

type ScreenLiveResult added in v1.6.5

type ScreenLiveResult struct {
	Accepted  bool `json:"accepted"`
	Published bool `json:"published"`
}

ScreenLiveResult accepted: the command took effect. published: true exactly for an accepted screen_live_start (the track is published), false for renew and stop.

type ScreenStartParams added in v1.6.19

type ScreenStartParams struct {
	SessionID   string `json:"session_id"`
	RelayURL    string `json:"relay_url"`
	RelayTicket string `json:"relay_ticket"`
}

ScreenStartParams is the params object of screen.start.

type ScreenStartResult added in v1.6.19

type ScreenStartResult struct {
	Accepted bool `json:"accepted"`
}

ScreenStartResult

type ScreenStopParams added in v1.6.19

type ScreenStopParams struct {
	SessionID string `json:"session_id"`
	// Suspend capture for a bounded reopen only after confirming native peer cleanup. Missing means ordinary full stop.
	RetainProjection bool `json:"retain_projection,omitempty"`
	// Confirm full capture stop for this exact session, including after the viewer was closed.
	ForceProjectionStop bool `json:"force_projection_stop,omitempty"`
}

ScreenStopParams is the params object of screen.stop.

type ScreenStopResult added in v1.6.19

type ScreenStopResult struct {
	Stopped bool `json:"stopped"`
	// Confirmed suspended capture after clean viewer detachment. The detached peer does not publish video or accept input.
	ProjectionRetained bool `json:"projection_retained,omitempty"`
	// Confirmed full capture stop or confirmed absence for the exact requested session.
	ProjectionStopped bool `json:"projection_stopped,omitempty"`
}

ScreenStopResult

type Session

type Session struct {
	// Tools has one typed entry per built-in tool: Tools.Bash.Call(...).
	Tools HarnessTools
	// contains filtered or unexported fields
}

Session is one session bound to an executor.

func (*Session) CallTool

func (s *Session) CallTool(ctx context.Context, params ToolCallParams) (ToolResultParams, error)

CallTool sends tool.call and waits for its tool.result. It is idempotent by ToolCallID (generated when empty): repeating an id joins the in-flight call or returns the recorded result without re-dispatching. Canceling ctx stops waiting only; use CancelTool to abort the tool. The result is recorded even if nobody is waiting, so a later CallTool with the same id returns it.

func (*Session) CancelTool

func (s *Session) CancelTool(ctx context.Context, toolCallID, reason string) (bool, error)

CancelTool sends tool.cancel. The waiting CallTool still receives the executor's tool.result (outcome canceled when the abort won the race).

func (*Session) Done

func (s *Session) Done() <-chan struct{}

func (*Session) EndReason

func (s *Session) EndReason() string

EndReason is set once Done is closed.

func (*Session) Executor

func (s *Session) Executor() *Executor

func (*Session) ID

func (s *Session) ID() string

func (*Session) MCP

func (s *Session) MCP(ctx context.Context, serverKey string) (*HarnessMCPChannel, error)

MCP waits for the MCP channel for serverKey (one of the session.assign mcp_servers) and returns it. A newer channel for the same key replaces the old one; the session's end closes all of them.

func (*Session) Ready

func (s *Session) Ready(ctx context.Context) error

Ready waits for session.ready.

func (*Session) Stop

func (s *Session) Stop(ctx context.Context, reason string) error

Stop sends session.stop; the executor terminates the session's processes and MCP servers before answering. The session ends locally on success.

func (*Session) WorkID

func (s *Session) WorkID() string

type SessionAssignHandler

type SessionAssignHandler func(ctx context.Context, params SessionAssignParams) (SessionAssignResult, error)

SessionAssignHandler handles an inbound session.assign.

type SessionAssignParams

type SessionAssignParams struct {
	SessionID     string            `json:"session_id"`
	WorkID        string            `json:"work_id"`
	AgentID       string            `json:"agent_id,omitempty"`
	EnvironmentID string            `json:"environment_id"`
	DeadlineMS    int64             `json:"deadline_ms,omitempty"`
	Lease         Lease             `json:"lease"`
	Resources     []json.RawMessage `json:"resources,omitempty"`
	MCPServers    []MCPServerConfig `json:"mcp_servers,omitempty"`
	// String key/value pairs. egress (contract 1.9.0, only to an executor that declared egress.forwarder): the JSON text of the session's EgressHandoff (schemas/executor.json), for an executor that runs the session's tools without running its turns (hands of a session whose brain is elsewhere). The harness sends session.assign before the session's tool calls and again on reconnect; every session.assign of a session, a repeated one included, replaces the session's handoff with the one it carries, and one without egress removes it (the session's connections go direct, so the sandbox's own network applies). The harness renews the token by a repeated session.assign before expires_at. The handoff ends with the session on this executor (session.stop, session.close). Never logged or echoed.
	Metadata map[string]string `json:"metadata,omitempty"`
}

SessionAssignParams is the params object of session.assign.

type SessionAssignResult

type SessionAssignResult struct {
	Accepted  bool   `json:"accepted"`
	SessionID string `json:"session_id"`
}

SessionAssignResult session.assign result.

type SessionCloseParams

type SessionCloseParams struct {
	SessionID string `json:"session_id"`
	Reason    string `json:"reason"`
}

SessionCloseParams is the params object of session.close.

type SessionCloseResult

type SessionCloseResult struct {
	Closed bool `json:"closed"`
}

SessionCloseResult session.close result.

type SessionCompactCancelParams added in v1.6.37

type SessionCompactCancelParams struct {
	SessionID              string `json:"session_id"`
	OperationID            string `json:"operation_id"`
	ExpectedContextVersion int64  `json:"expected_context_version"`
	ExpectedLastInputID    string `json:"expected_last_input_id"`
	Model                  string `json:"model"`
}

SessionCompactCancelParams is the params object of session.compact_cancel.

type SessionCompactCancelResult added in v1.6.37

type SessionCompactCancelResult struct {
	SessionID   string                `json:"session_id"`
	OperationID string                `json:"operation_id"`
	Canceled    bool                  `json:"canceled"`
	Settled     bool                  `json:"settled"`
	Receipt     *SessionCompactResult `json:"receipt,omitempty"`
}

SessionCompactCancelResult A durable publication fence or the already-applied receipt. settled is filled by the SDK, independently from the handler's fence.

type SessionCompactParams added in v1.6.37

type SessionCompactParams struct {
	SessionID              string `json:"session_id"`
	OperationID            string `json:"operation_id"`
	ExpectedContextVersion int64  `json:"expected_context_version"`
	// Exact platform input whose settled context the reservation owns.
	ExpectedLastInputID string            `json:"expected_last_input_id"`
	Model               string            `json:"model"`
	DeadlineMS          int64             `json:"deadline_ms"`
	Metadata            map[string]string `json:"metadata"`
}

SessionCompactParams is the params object of session.compact.

type SessionCompactResult added in v1.6.37

type SessionCompactResult struct {
	SessionID              string `json:"session_id"`
	OperationID            string `json:"operation_id"`
	PreviousContextVersion int64  `json:"previous_context_version"`
	ContextVersion         int64  `json:"context_version"`
	Summary                string `json:"summary"`
	SummarySHA256          string `json:"summary_sha256"`
	SourceEventCount       int64  `json:"source_event_count"`
}

SessionCompactResult Contract 1.19.0. Durable context replacement receipt. No user message or ordinary turn is created. The operation id and original version identify an immutable retry even after newer compactions.

type SessionContext added in v1.1.0

type SessionContext struct {
	ID            string            `json:"id"`
	EnvironmentID string            `json:"environment_id"`
	Metadata      map[string]string `json:"metadata"`
	CreatedAt     time.Time         `json:"created_at"`
}

SessionContext is what BMA tells this machine about an agent session it serves (GET /api/v1/daemon/processes/{process_id}/session and GET /api/v1/daemon/sessions/{session_id}): the session's environment and the metadata its creator set, never agent configuration or credentials. Executors read it to resolve a reference the caller put in metadata (a project folder, an owner) before running anything, as Claude Managed Agents workers read the session's metadata for a claimed work item.

type SessionEndedParams

type SessionEndedParams struct {
	SessionID string `json:"session_id"`
	Reason    string `json:"reason"`
}

SessionEndedParams is the params object of session.ended.

type SessionErrorEvent

type SessionErrorEvent struct {
	Type  string         `json:"type"`
	Error AgentErrorInfo `json:"error"`
}

SessionErrorEvent A turn-level error. A failed turn still ends with session.status_idle turn_outcome=failed.

type SessionEvent

type SessionEvent struct {
	Type      string         `json:"type"`
	ToolUseID string         `json:"tool_use_id,omitempty"`
	Content   []ContentBlock `json:"content,omitempty"`
	IsError   bool           `json:"is_error,omitempty"`
}

SessionEvent Durable session event emitted by the executor.

type SessionEventDeltaParams

type SessionEventDeltaParams struct {
	SessionID string `json:"session_id"`
	TurnID    string `json:"turn_id"`
	EventID   string `json:"event_id"`
	EventType string `json:"event_type"`
	// Content block index within the event.
	Index int64 `json:"index"`
	// Text appended to the block.
	Text string `json:"text"`
}

SessionEventDeltaParams is the params object of session.event_delta.

type SessionEventParams

type SessionEventParams struct {
	SessionID string `json:"session_id"`
	// Agent sessions; the turn that produced the event.
	TurnID string `json:"turn_id,omitempty"`
	// Agent sessions; executor-assigned, unique within the session, stable across resends.
	EventID string `json:"event_id,omitempty"`
	// Agent sessions; starts at 1 and increases by 1 per durable event within the session.
	Sequence int64 `json:"sequence,omitempty"`
	// Agent sessions; optional key the executor keeps for this event across process restarts (its outbox entry id, for example). A new executor epoch renumbers sequence and suffixes event_id, so only this key lets the harness recognize an event it stored just before the executor crashed. The harness acknowledges an event whose key the session already stored as a duplicate (sequence advanced, nothing added to the session log), in any epoch. Without it an event resent in a new epoch is stored again (at-least-once).
	IdempotencyKey string          `json:"idempotency_key,omitempty"`
	Event          json.RawMessage `json:"event"`
}

SessionEventParams is the params object of session.event.

type SessionEventResult

type SessionEventResult struct {
	Accepted bool   `json:"accepted"`
	EventID  string `json:"event_id"`
	// Agent sessions: highest contiguous sequence the platform has persisted for the session. A duplicate event is accepted and reports the current value.
	AckedSequence int64 `json:"acked_sequence,omitempty"`
}

SessionEventResult session.event result.

func SendSessionEvent

func SendSessionEvent(ctx context.Context, rpc RPC, params SessionEventParams) (SessionEventResult, error)

SendSessionEvent calls session.event.

type SessionFileTransferer added in v1.1.0

type SessionFileTransferer interface {
	FileTransferer
	TransferSessionFile(ctx context.Context, process ProcessContext, transfer ProcessFileTransfer) (FileTransferResult, error)
}

SessionFileTransferer is a FileTransferer that also learns which session the transfer runs for (for example to check the path against the folder that session may use). When ProcessOptions.FileTransfer implements it, TransferSessionFile is called instead of TransferFile.

func NewFileTransferer added in v1.3.0

func NewFileTransferer() SessionFileTransferer

NewFileTransferer returns the FileTransferer for ProcessOptions.FileTransfer of a machine-scoped executor (ErrMachineTokenRequired otherwise, on the first transfer). An upload streams a regular file (at most MaxFileTransferBytes) and is checked against the digest BMA stored. A download streams into a temporary file next to the destination and replaces it only after the length and sha256 match, keeping the destination's permissions (on Windows: its read-only attribute); a leading "~" in the path is the user's home directory (USERPROFILE on Windows). The workload's own permissions are the executor's: a privileged executor should give a Launch hook, not this, the job of confining paths. edit_file downloads are not supported (BMA then answers the agent that the executor cannot edit).

type SessionFiles added in v1.1.0

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

SessionFiles syncs the session files of an executor that declares capabilities.session_files. Pass it as ProcessOptions.SessionFiles (the process capability then advertises the root and syncs before each process of an agent session) and run Run for the output uploads. It needs a machine-scoped executor (ErrMachineTokenRequired).

func NewSessionFiles added in v1.1.0

func NewSessionFiles(opts SessionFilesOptions) (*SessionFiles, error)

NewSessionFiles validates the root and creates it (0700) if needed.

func (*SessionFiles) Dirs added in v1.1.0

func (f *SessionFiles) Dirs(sessionID string) (uploads, outputs string)

Dirs returns the uploads and outputs directories of an agent session, for example for a Launch hook that confines a sandbox to them.

func (*SessionFiles) MemoryDir added in v1.23.0

func (f *SessionFiles) MemoryDir(sessionID string) string

MemoryDir is <Root>/<sessionID>/memory, where the session's memory stores are mirrored (one directory per store slug), for example for a Launch hook that lets a sandbox read it.

func (*SessionFiles) Root added in v1.1.0

func (f *SessionFiles) Root() string

Root is the advertised capabilities.session_files.root.

func (*SessionFiles) Run added in v1.1.0

func (f *SessionFiles) Run(ctx context.Context)

Run uploads changed outputs until ctx ends, then uploads what is left.

type SessionFilesCapability added in v1.1.0

type SessionFilesCapability struct {
	// Absolute, already-expanded, clean path on the executor host (no ~, no . or .. segments, no trailing /).
	Root string `json:"root"`
	// Contract 2.6.0. The executor materializes the session's memory stores: before every process.start of an agent session and on session_files.sync it mirrors the memory_stores of the session files manifest into <root>/<agent_session_id>/memory/<slug>/ (files 0444, platform wins, anything not in the manifest removed, marker <root>/<agent_session_id>/memory/.bma-memory.json) and exports BMA_MEMORY_DIR=<root>/<agent_session_id>/memory to that session's processes. Absent or false: the platform sends no session_files.sync, records one non-terminal session.error memory_unsupported per turn of a session with memory stores, and tells the model memory is not available there.
	Memory bool `json:"memory,omitempty"`
}

SessionFilesCapability Executor-owned per-session file layout. The harness derives <root>/<agent_session_id>/uploads (read-only session inputs) and <root>/<agent_session_id>/outputs (deliverables) from it, with agent_session_id as sent in process.start metadata, and uses these real paths in prompts, tool descriptions, write rules and the session files manifest. Absent: the executor has no session files; the harness names no session path to it. There is no fixed /mnt/session/uploads or /mnt/session/outputs layout: the per-session <root>/<agent_session_id>/{uploads,outputs} is the only one, and platform-hosted machines declare root /mnt/session. With the fs capability skills_per_session or copy_views the same tree also holds <root>/<agent_session_id>/skills (the session's skills view, read-only). Fixed at executor.register: executor.capabilities.update does not change it. Machine-scoped executors only.

type SessionFilesFlushParams added in v1.6.34

type SessionFilesFlushParams struct {
}

SessionFilesFlushParams is the params object of session_files.flush.

type SessionFilesFlushResult added in v1.6.34

type SessionFilesFlushResult struct {
	State string `json:"state"`
	// Outputs uploaded by this request.
	Uploaded int64  `json:"uploaded,omitempty"`
	Error    string `json:"error,omitempty"`
}

SessionFilesFlushResult session_files.flush result. state flushed: every changed output was uploaded; failed: at least one upload failed (error names it) and the request may be repeated.

type SessionFilesOptions added in v1.1.0

type SessionFilesOptions struct {
	// Root is the absolute, already-expanded directory that holds every
	// session's files; it is advertised as capabilities.session_files.root
	// and BMA shows the agent <Root>/<session id>/{uploads,outputs}. Keep it
	// apart from the executor's own state and IPC directories.
	Root string
	// MaxOutputBytes is the largest output uploaded (default and maximum
	// 1 GiB); larger files are skipped and logged.
	MaxOutputBytes int64
	OnLog          func(LogEvent)
}

SessionFilesOptions configures NewSessionFiles.

type SessionFilesSyncParams added in v1.23.0

type SessionFilesSyncParams struct {
	// The public session id; the directory <root>/<agent_session_id>/memory.
	AgentSessionID string `json:"agent_session_id"`
	// The anchor process the manifest and content downloads name (one per session and 10-minute window, as skill.install).
	DownloadToken string `json:"download_token"`
}

SessionFilesSyncParams is the params object of session_files.sync.

type SessionFilesSyncResult added in v1.23.0

type SessionFilesSyncResult struct {
	State string `json:"state"`
	Error string `json:"error,omitempty"`
}

SessionFilesSyncResult session_files.sync result (contract 2.6.0). state synced: the session's memory directory equals the manifest's memory_stores; failed: the mirror could not be completed (error names why) and the platform fails the call or turn with memory_sync_failed.

type SessionHistoryEvent added in v1.6.34

type SessionHistoryEvent struct {
	BmaSequence int64 `json:"bma_sequence"`
	// The event id.
	ID   string `json:"id"`
	Type string `json:"type"`
	// The official event body without id, type and bma_sequence.
	Payload map[string]any `json:"payload"`
}

SessionHistoryEvent Contract 1.15.0. One durable event of a session's conversation as the platform's log keeps it. A tool result names its call by the id of the call's event (tool_use_id, custom_tool_use_id, mcp_tool_use_id).

func ReadSessionHistory added in v1.15.0

func ReadSessionHistory(ctx context.Context, sessionID, turnID string) ([]SessionHistoryEvent, error)

ReadSessionHistory reads every event of the conversation of sessionID before the opening input of turnID, in log order: messages, tool calls and their results. Call it from AgentHandler.OpenTurn (the ctx it is given). A platform that does not serve the method (-32601) has no history to give: nil.

type SessionHistoryParams added in v1.6.34

type SessionHistoryParams struct {
	// Platform session id.
	SessionID string `json:"session_id"`
	// The running turn whose past is read; its opening input is not part of the history.
	TurnID string `json:"turn_id"`
	// Read the events with a bma_sequence greater than this (default 0, from the start).
	After int64 `json:"after,omitempty"`
	// At most this many events (1-500, default 500); a page also stays within 512 KiB of event bodies (one event always fits).
	Limit int64 `json:"limit,omitempty"`
}

SessionHistoryParams is the params object of session.history.

type SessionHistoryResult added in v1.6.34

type SessionHistoryResult struct {
	Events []SessionHistoryEvent `json:"events"`
	// More events follow: read again with after = the last bma_sequence of this page.
	HasMore bool `json:"has_more"`
}

SessionHistoryResult Contract 1.15.0. session.history result: a page of the session's conversation before the turn's opening input, in log order.

func SendSessionHistory added in v1.6.34

func SendSessionHistory(ctx context.Context, rpc RPC, params SessionHistoryParams) (SessionHistoryResult, error)

SendSessionHistory calls session.history.

type SessionMemoryResource

type SessionMemoryResource struct {
	Type          string `json:"type"`
	MemoryStoreID string `json:"memory_store_id"`
	MountPath     string `json:"mount_path"`
}

SessionMemoryResource A memory store mounted into the session workspace.

type SessionOutputReport added in v1.19.0

type SessionOutputReport struct {
	// Path relative to the session's outputs directory, with / separators.
	Path string `json:"path"`
	// sha256:<64 lowercase hex> of the file's content on the machine.
	Digest string `json:"digest"`
	// The platform stored this content (or refused it for good: too large, quota, scratch name).
	Uploaded bool `json:"uploaded"`
}

SessionOutputReport One session output an ended process left: its path relative to the session's outputs directory, the sha256 digest of its content on the machine, and whether its upload went through.

type SessionReadyParams

type SessionReadyParams struct {
	SessionID  string `json:"session_id"`
	WorkID     string `json:"work_id"`
	LeaseToken string `json:"lease_token"`
}

SessionReadyParams is the params object of session.ready.

type SessionStatusIdleEvent

type SessionStatusIdleEvent struct {
	Type        string     `json:"type"`
	StopReason  StopReason `json:"stop_reason"`
	TurnOutcome string     `json:"turn_outcome"`
}

SessionStatusIdleEvent The turn ended. It is the last event of its turn_id; the platform publishes the turn as finished only after it accepted this event and every lower sequence.

type SessionStatusParams

type SessionStatusParams struct {
	SessionID string `json:"session_id"`
	Status    string `json:"status"`
	Detail    string `json:"detail,omitempty"`
}

SessionStatusParams is the params object of session.status.

type SessionStatusRunningEvent

type SessionStatusRunningEvent struct {
	Type string `json:"type"`
}

SessionStatusRunningEvent The local agent started working on the turn.

type SessionStopHandler

type SessionStopHandler func(ctx context.Context, params SessionStopParams) (SessionStopResult, error)

SessionStopHandler handles an inbound session.stop.

type SessionStopParams

type SessionStopParams struct {
	SessionID  string `json:"session_id"`
	Reason     string `json:"reason"`
	DeadlineMS int64  `json:"deadline_ms,omitempty"`
}

SessionStopParams is the params object of session.stop.

type SessionStopResult

type SessionStopResult struct {
	Stopped bool `json:"stopped"`
}

SessionStopResult session.stop result.

type ShellCapability

type ShellCapability struct {
	Enabled bool `json:"enabled"`
}

ShellCapability v1 one-shot shell tools.

type SkillInstallParams

type SkillInstallParams struct {
	MachineID     string `json:"machine_id"`
	SkillID       string `json:"skill_id"`
	RevisionID    string `json:"revision_id"`
	Digest        string `json:"digest"`
	DownloadToken string `json:"download_token"`
	// Unix seconds.
	DownloadExpiresAt int64 `json:"download_expires_at"`
}

SkillInstallParams is the params object of skill.install.

type SkillInstallResult

type SkillInstallResult struct {
	State     string `json:"state"`
	ErrorCode string `json:"error_code,omitempty"`
	Error     string `json:"error,omitempty"`
}

SkillInstallResult skill.install result. state is "ready", or "failed" with error_code and error.

type SkillInstaller

type SkillInstaller func(ctx context.Context, params SkillInstallParams) SkillInstallResult

SkillInstaller installs one skill revision; the result state is "ready" or "failed" with error_code and error. It must be idempotent by (skill_id, revision_id, digest).

type SkillsCapability

type SkillsCapability struct {
	Install bool `json:"install"`
}

SkillsCapability skill.install support. Machine-scoped executors only.

type StopReason

type StopReason struct {
	Type string `json:"type"`
}

StopReason Why the turn stopped.

type TerminalAttachParams

type TerminalAttachParams struct {
	TerminalID string       `json:"terminal_id"`
	Epoch      int64        `json:"epoch"`
	StreamID   string       `json:"stream_id"`
	CanWrite   bool         `json:"can_write"`
	FromSeq    int64        `json:"from_seq"`
	AckSeq     int64        `json:"ack_seq"`
	Host       TerminalHost `json:"host"`
}

TerminalAttachParams is the params object of terminal.attach.

type TerminalAttachResult

type TerminalAttachResult struct {
	Accepted    bool   `json:"accepted"`
	WriterEpoch uint64 `json:"writer_epoch"`
}

TerminalAttachResult terminal.attach result, returned after the host socket is connected and the attached frame was written on it.

type TerminalCapability

type TerminalCapability struct {
	Enabled     bool     `json:"enabled"`
	Kinds       []string `json:"kinds,omitempty"`
	MaxSessions int      `json:"max_sessions,omitempty"`
}

TerminalCapability v1.1 terminal.* support. Machine-scoped executors only.

type TerminalCloseParams

type TerminalCloseParams struct {
	TerminalID string `json:"terminal_id"`
	Reason     string `json:"reason,omitempty"`
}

TerminalCloseParams is the params object of terminal.close.

type TerminalCloseResult

type TerminalCloseResult struct {
	Closed   bool `json:"closed"`
	ExitCode *int `json:"exit_code,omitempty"`
}

TerminalCloseResult terminal.close result. Idempotent: closing an unknown or closed terminal returns closed=true.

type TerminalErrorData

type TerminalErrorData struct {
	TerminalCode string `json:"terminal_code,omitempty"`
}

TerminalErrorData JSON-RPC error.data of a failed terminal.* call. terminal_code is the bma.terminal.v1 code the harness relays to the attach (for example terminal_writer_busy).

type TerminalFrameAck added in v1.6.5

type TerminalFrameAck struct {
	Type string `json:"type"`
	// Terminal session id (tsn_...). The platform fills it toward clients; an executor may omit it on the host socket.
	SessionID string `json:"session_id,omitempty"`
	// Offset after the last consumed byte.
	AckSeq int64 `json:"ack_seq"`
}

TerminalFrameAck Consumer acknowledgement: every byte before ack_seq was processed. Direction: client to platform to executor.

type TerminalFrameAttach added in v1.6.5

type TerminalFrameAttach struct {
	Type string `json:"type"`
	// Terminal session id (tsn_...). The platform fills it toward clients; an executor may omit it on the host socket.
	SessionID string `json:"session_id,omitempty"`
	Rows      uint16 `json:"rows,omitempty"`
	Cols      uint16 `json:"cols,omitempty"`
	// Resume point (byte offset).
	FromSeq int64 `json:"from_seq,omitempty"`
	// Last consumed byte offset.
	AckSeq int64 `json:"ack_seq,omitempty"`
	// Request the writer lease; omitted means true.
	CanWrite bool `json:"can_write,omitempty"`
}

TerminalFrameAttach First and only first frame a client sends on the relay socket (any other first frame is answered with error terminal_internal_error). Not sent on the host socket: terminal.attach carries the same fields as params. from_seq is the first output byte the client still needs and ack_seq the last byte it has consumed; from_seq above latest_seq is answered with error terminal_invalid_frame. Exactly one attachment per terminal at a time: while one is attached, another attach (can_write false included) is answered with error terminal_writer_busy and the socket is closed. Direction: client to platform.

type TerminalFrameAttached added in v1.6.5

type TerminalFrameAttached struct {
	Type string `json:"type"`
	// Terminal session id (tsn_...). The platform fills it toward clients; an executor may omit it on the host socket.
	SessionID   string `json:"session_id,omitempty"`
	Rows        uint16 `json:"rows"`
	Cols        uint16 `json:"cols"`
	PID         int    `json:"pid"`
	WriterEpoch uint64 `json:"writer_epoch"`
	CanWrite    bool   `json:"can_write"`
	// Oldest byte offset still buffered.
	EarliestSeq int64 `json:"earliest_seq,omitempty"`
	// Byte offset after the last output byte.
	LatestSeq int64 `json:"latest_seq"`
}

TerminalFrameAttached Answer to an attach; on the host socket the executor writes it first, before answering terminal.attach. writer_epoch increases on every attach of the terminal (attempts that fail may consume a value too) and fences input. earliest_seq is omitted when 0. Output from from_seq follows (preceded by gap when from_seq < earliest_seq). Direction: executor to platform to client.

type TerminalFrameClose added in v1.6.5

type TerminalFrameClose struct {
	Type string `json:"type"`
	// Terminal session id (tsn_...). The platform fills it toward clients; an executor may omit it on the host socket.
	SessionID string `json:"session_id,omitempty"`
	Reason    string `json:"reason,omitempty"`
}

TerminalFrameClose Close the terminal (the PTY ends, not only this attachment); answered with closed. Closing the socket instead only detaches. Direction: client to platform to executor.

type TerminalFrameClosed added in v1.6.5

type TerminalFrameClosed struct {
	Type string `json:"type"`
	// Terminal session id (tsn_...). The platform fills it toward clients; an executor may omit it on the host socket.
	SessionID string `json:"session_id,omitempty"`
	// closed, or the terminal.close reason; open set.
	Reason string `json:"reason,omitempty"`
}

TerminalFrameClosed The terminal was closed (close frame or terminal.close); the socket closes after it. Direction: executor or platform to client.

type TerminalFrameError added in v1.6.5

type TerminalFrameError struct {
	Type string `json:"type"`
	// Terminal session id (tsn_...). The platform fills it toward clients; an executor may omit it on the host socket.
	SessionID string `json:"session_id,omitempty"`
	Code      string `json:"code"`
	Message   string `json:"message"`
}

TerminalFrameError A refused frame or attach. After terminal_writer_busy, terminal_invalid_frame on attach, or terminal_internal_error the socket is closed; other errors leave the attachment open. Peers must also tolerate a socket that ends without a close frame. Direction: executor or platform to client.

type TerminalFrameExit added in v1.6.5

type TerminalFrameExit struct {
	Type string `json:"type"`
	// Terminal session id (tsn_...). The platform fills it toward clients; an executor may omit it on the host socket.
	SessionID string `json:"session_id,omitempty"`
	// Offset after the last output byte.
	EndSeq   int64 `json:"end_seq"`
	ExitCode *int  `json:"exit_code,omitempty"`
	// exited (normal exit) or signaled; open set.
	ExitReason string `json:"exit_reason,omitempty"`
	Exited     int64  `json:"exited"`
}

TerminalFrameExit The PTY process exited; end_seq is the offset after its last output byte. The socket closes after it. Direction: executor to platform to client.

type TerminalFrameGap added in v1.6.5

type TerminalFrameGap struct {
	Type string `json:"type"`
	// Terminal session id (tsn_...). The platform fills it toward clients; an executor may omit it on the host socket.
	SessionID string `json:"session_id,omitempty"`
	// Where output resumes.
	EarliestSeq int64 `json:"earliest_seq"`
	// Offset after the last output byte.
	LatestSeq int64 `json:"latest_seq"`
	Truncated int64 `json:"truncated"`
}

TerminalFrameGap Sent before output when the requested from_seq fell out of the ring buffer (the reference executor keeps 1 MiB): output resumes at earliest_seq. Direction: executor to platform to client.

type TerminalFrameInput added in v1.6.5

type TerminalFrameInput struct {
	Type string `json:"type"`
	// Terminal session id (tsn_...). The platform fills it toward clients; an executor may omit it on the host socket.
	SessionID   string `json:"session_id,omitempty"`
	Data        string `json:"data"`
	WriterEpoch uint64 `json:"writer_epoch,omitempty"`
}

TerminalFrameInput Bytes for the PTY, base64 in data. Accepted only from the attachment holding the writer lease; writer_epoch, when present, must equal the lease's epoch (attached.writer_epoch) or the frame is dropped with error terminal_stale_writer. Clients send the epoch of their attached frame. Direction: client to platform to executor.

type TerminalFrameOutput added in v1.6.5

type TerminalFrameOutput struct {
	Type string `json:"type"`
	// Terminal session id (tsn_...). The platform fills it toward clients; an executor may omit it on the host socket.
	SessionID string `json:"session_id,omitempty"`
	// Offset of the first byte in data; omitted when 0.
	FromSeq int64 `json:"from_seq,omitempty"`
	// Offset after the last byte in data.
	EndSeq int64  `json:"end_seq"`
	Data   string `json:"data"`
}

TerminalFrameOutput PTY output bytes [from_seq, end_seq), base64 (standard, padded) in data. Sequence numbers are byte offsets of the PTY output since the PTY was created; chunks are contiguous and at most 32768 bytes. from_seq is omitted when 0. The producer stops sending after a window of unacknowledged bytes until the consumer acks, so consumers ack every end_seq they processed. Direction: executor to platform to client.

type TerminalFrameResize added in v1.6.5

type TerminalFrameResize struct {
	Type string `json:"type"`
	// Terminal session id (tsn_...). The platform fills it toward clients; an executor may omit it on the host socket.
	SessionID string `json:"session_id,omitempty"`
	Rows      uint16 `json:"rows"`
	Cols      uint16 `json:"cols"`
}

TerminalFrameResize Resize the PTY; answered with resized. Direction: client to platform to executor.

type TerminalFrameResized added in v1.6.5

type TerminalFrameResized struct {
	Type string `json:"type"`
	// Terminal session id (tsn_...). The platform fills it toward clients; an executor may omit it on the host socket.
	SessionID string `json:"session_id,omitempty"`
	Rows      uint16 `json:"rows"`
	Cols      uint16 `json:"cols"`
}

TerminalFrameResized The PTY size after a resize. Direction: executor to platform to client.

type TerminalHost

type TerminalHost struct {
	URL    string `json:"url"`
	Ticket string `json:"ticket"`
}

TerminalHost Outbound host socket for one attach. The ticket is a single-use, short-lived bearer credential sent only in the Authorization header, never in the URL.

type TerminalLaunchFunc added in v1.20.0

type TerminalLaunchFunc func(ctx context.Context, req TerminalLaunchRequest) (LaunchSpec, error)

TerminalLaunchFunc is called once per new PTY (terminal.open of a new or ended terminal_id), before it is spawned. It may choose the directory, wrap argv in a sandbox command and change the environment; an empty field of the LaunchSpec keeps the request's. Returning an error refuses the open: an *RPCError (NewReasonError) is answered as is, any other error as resource_unavailable with terminal_internal_error.

type TerminalLaunchRequest added in v1.20.0

type TerminalLaunchRequest struct {
	TerminalID string
	// Kind is human or agent.
	Kind string
	// Argv is the requested argv, else the requested or default shell.
	Argv []string
	// Dir is the absolute directory it would start in: the requested cwd,
	// else TerminalOptions.Dir.
	Dir string
	// Env is the complete environment it would get.
	Env []string
}

TerminalLaunchRequest is one terminal about to start: the command the executor would run and where.

type TerminalOpenParams

type TerminalOpenParams struct {
	TerminalID string `json:"terminal_id"`
	// human or agent.
	Kind  string            `json:"kind"`
	Shell string            `json:"shell,omitempty"`
	Argv  []string          `json:"argv,omitempty"`
	Cwd   string            `json:"cwd,omitempty"`
	Env   map[string]string `json:"env,omitempty"`
	Rows  uint16            `json:"rows,omitempty"`
	Cols  uint16            `json:"cols,omitempty"`
}

TerminalOpenParams is the params object of terminal.open.

type TerminalOpenResult

type TerminalOpenResult struct {
	TerminalID  string `json:"terminal_id"`
	Epoch       int64  `json:"epoch"`
	PID         int    `json:"pid"`
	Rows        uint16 `json:"rows"`
	Cols        uint16 `json:"cols"`
	EarliestSeq int64  `json:"earliest_seq"`
	LatestSeq   int64  `json:"latest_seq"`
	CreatedAt   string `json:"created_at"`
}

TerminalOpenResult terminal.open result. epoch starts at 1 and increments when the executor recreates the PTY under the same terminal_id; attach is fenced by it.

type TerminalOptions added in v1.20.0

type TerminalOptions struct {
	// Env is the base environment of every terminal. Nil: this process's.
	Env []string
	// Dir is the directory a terminal starts in when the request names none.
	// Empty: HOME of Env.
	Dir string
	// RunAs, when set, is the OS identity the PTY's process runs as. Unix only.
	RunAs *RunAs
	// DenyEnv reports variables a terminal.open env entry may not set; they
	// are dropped. Nil allows every name.
	DenyEnv func(name string) bool
	// Launch runs before each new PTY starts; see TerminalLaunchFunc. Nil
	// starts the request's command as is.
	Launch TerminalLaunchFunc
	// OnLog receives a warning when a PTY's process cannot be waited for.
	OnLog func(LogEvent)
}

TerminalOptions configures NewTerminals.

type Terminals added in v1.20.0

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

Terminals serves terminal.open, terminal.attach and terminal.close on a machine-scoped executor: PTYs (ConPTY on Windows) that outlive a client, keep 1 MiB of output for a resume, and stream it over the host socket each terminal.attach names, one writer at a time. Register Capability on the Core and Close it when the executor stops.

func NewTerminals added in v1.20.0

func NewTerminals(opts TerminalOptions) *Terminals

NewTerminals returns the terminal capability's state.

func (*Terminals) Capability added in v1.20.0

func (s *Terminals) Capability() Capability

Capability advertises terminal (kinds human and agent) and serves its methods.

func (*Terminals) Close added in v1.20.0

func (s *Terminals) Close()

Close ends every terminal (executor shutdown).

func (*Terminals) CloseTerminal added in v1.21.0

func (s *Terminals) CloseTerminal(terminalID, reason string) *int

CloseTerminal ends one terminal the way terminal.close does, for the embedding executor: its attached consumer gets a closed frame carrying reason (empty: "closed"), not the exit of a shell killed behind its back. Unknown ids are ignored. It returns the shell's exit code, nil when a signal ended it.

type ToolCallParams

type ToolCallParams struct {
	SessionID  string          `json:"session_id"`
	ToolCallID string          `json:"tool_call_id"`
	Tool       string          `json:"tool"`
	Input      json.RawMessage `json:"input"`
	DeadlineMS int64           `json:"deadline_ms,omitempty"`
	Permission *ToolPermission `json:"permission,omitempty"`
}

ToolCallParams is the params object of tool.call.

func (ToolCallParams) DecodeInput

func (p ToolCallParams) DecodeInput() (ToolInput, error)

DecodeInput decodes tool.call input into the built-in ToolInput shape. The wire keeps input raw because each tool defines which members it reads.

type ToolCancelParams

type ToolCancelParams struct {
	SessionID  string `json:"session_id"`
	ToolCallID string `json:"tool_call_id"`
	Reason     string `json:"reason,omitempty"`
}

ToolCancelParams is the params object of tool.cancel.

type ToolCancelResult

type ToolCancelResult struct {
	Canceled bool `json:"canceled"`
}

ToolCancelResult tool.cancel result.

type ToolContext added in v1.0.0

type ToolContext struct {
	SessionID  string
	ToolCallID string
	Permission *ToolPermission
	// Progress sends tool.progress for this call (best-effort).
	Progress func(message string)
	// contains filtered or unexported fields
}

ToolContext describes the call a handler serves.

type ToolError added in v1.0.0

type ToolError struct {
	Content []ContentBlock
}

ToolError is a tool-level error reported to the model (outcome succeeded, is_error true), as Core reports a missing file. Same role as the Anthropic SDK ToolError.

func NewToolError added in v1.0.0

func NewToolError(text string) *ToolError

NewToolError returns a ToolError with one text block.

func (*ToolError) Error added in v1.0.0

func (e *ToolError) Error() string

type ToolInput

type ToolInput struct {
	Command   string            `json:"command,omitempty"`
	Cwd       string            `json:"cwd,omitempty"`
	TimeoutMS int64             `json:"timeout_ms,omitempty"`
	Env       map[string]string `json:"env,omitempty"`
	Path      string            `json:"path,omitempty"`
	Offset    int64             `json:"offset,omitempty"`
	Limit     int64             `json:"limit,omitempty"`
	Content   string            `json:"content,omitempty"`
	OldString string            `json:"old_string,omitempty"`
	NewString string            `json:"new_string,omitempty"`
	Pattern   string            `json:"pattern,omitempty"`
	Glob      string            `json:"glob,omitempty"`
	Display   string            `json:"display,omitempty"`
	Action    string            `json:"action,omitempty"`
}

ToolInput Superset of every built-in tool input, decoded by executors that read input generically. tool.call selects the exact per-tool schema through x-bma-params-discriminator; unknown members are ignored.

type ToolOutput added in v1.0.0

type ToolOutput struct {
	Content   []ContentBlock
	IsError   bool
	Artifacts []ArtifactRef
	// Outcome is empty for succeeded; ToolOutcomeCanceled reports a call the
	// handler abandoned because ctx was canceled.
	Outcome string
}

ToolOutput is a handler's result; the client fills in the ids and duration.

func TextOutput added in v1.0.0

func TextOutput(text string) ToolOutput

TextOutput is a ToolOutput of one text block.

type ToolPermission

type ToolPermission struct {
	Mode string `json:"mode"`
}

ToolPermission Tool permission resolved by the harness.

type ToolProgressParams

type ToolProgressParams struct {
	SessionID  string `json:"session_id"`
	ToolCallID string `json:"tool_call_id"`
	Message    string `json:"message"`
}

ToolProgressParams is the params object of tool.progress.

type ToolResultFile added in v1.15.0

type ToolResultFile struct {
	// Public file id.
	FileID string `json:"file_id"`
	// File name (last segment of its output path).
	Filename string `json:"filename"`
	// MIME type, for example image/png.
	MediaType string `json:"media_type"`
	SizeBytes int64  `json:"size_bytes"`
	// Image width in pixels (images only).
	Width int64 `json:"width,omitempty"`
	// Image height in pixels (images only).
	Height int64 `json:"height,omitempty"`
	// The model that generated the file (generated files only).
	Model string `json:"model,omitempty"`
}

ToolResultFile Contract 1.26.0. A session file a tool call created (agent.tool_result.bma_files, GenerateImageResult.files). The file is readable with GET /v1/files/{file_id}/content like any session file.

type ToolResultParams

type ToolResultParams struct {
	SessionID  string         `json:"session_id"`
	ToolCallID string         `json:"tool_call_id"`
	Outcome    string         `json:"outcome"`
	IsError    bool           `json:"is_error"`
	Content    []ContentBlock `json:"content"`
	DurationMS int64          `json:"duration_ms,omitempty"`
	Artifacts  []ArtifactRef  `json:"artifacts,omitempty"`
}

ToolResultParams is the params object of tool.result.

type ToolRoute added in v1.4.0

type ToolRoute interface {
	// Call runs one tool call and always answers: a refusal, a transport
	// failure or an unclear outcome is a RouteResult with IsError set, never
	// a Go error. A repeated Call with the same RouteCall.ID is answered with
	// the first result (RouteResult.Replayed), not run again.
	Call(ctx context.Context, call RouteCall) *RouteResult
}

ToolRoute is where a brain's tool calls go to run (ADR-0029, brain-hands split): the seam between a brain and its hands. A brain written against the SDK gets the route of its turn from AgentTurn.Tools and never needs to know where the hands are.

There are two routes. PlatformToolRoute is the platform's execute-only tool gateway (ADR-0005): it checks the turn's credential and epoch, re-evaluates the tool policy, verifies the user's approval, runs each call id at most once and runs the tool on the session's hands machine, which may refuse it again by its own policy. LocalToolRoute (the hands are this machine) answers with the same outcomes and refuses for the same reasons with the same error codes. Both are held to the tool route conformance suite (package conformance, cases T1–T11), which a route of your own can run too.

A ToolRoute is bound to one turn of one session and is safe for concurrent use. Its calls end with ctx: a canceled ctx abandons the call, which does not kill a process already started on the hands (the platform's turn cancel does).

type ToolSlot added in v1.0.0

type ToolSlot[In any] struct {
	// contains filtered or unexported fields
}

ToolSlot serves tool.call for one built-in tool.

func (ToolSlot[In]) Handle added in v1.0.0

func (s ToolSlot[In]) Handle(handler func(ctx context.Context, input In, tool ToolContext) (ToolOutput, error))

Handle registers the handler of this tool, replacing an earlier one. The shell and files capabilities follow the registered handlers; registering after Start sends executor.capabilities.update, as MCP servers announce tools registered after connecting (tools/list_changed). Input missing a member the contract requires fails the call before the handler runs.

type Tools added in v1.0.0

type Tools struct {
	Bash      ToolSlot[BashInput]
	Read      ToolSlot[ReadInput]
	Write     ToolSlot[WriteInput]
	Edit      ToolSlot[EditInput]
	Glob      ToolSlot[GlobInput]
	Grep      ToolSlot[GrepInput]
	ListFiles ToolSlot[ListFilesInput]
}

Tools has one typed slot per built-in tool: client.Tools.Bash.Handle(...). computer_observe and computer_action have no slot until the contract defines their input members.

type ToolsTokenRefreshParams added in v1.3.0

type ToolsTokenRefreshParams struct {
	// Platform session id of the turn.
	SessionID string `json:"session_id"`
	// Platform id of the running turn the token is for.
	TurnID string `json:"turn_id"`
}

ToolsTokenRefreshParams is the params object of tools_token.refresh.

type ToolsTokenRefreshResult added in v1.3.0

type ToolsTokenRefreshResult struct {
	// Bearer token for tools_mcp_url, bound to the org, session, turn, brain machine and brain epoch of the turn. Valid until expires_at.
	ToolsMCPToken string `json:"tools_mcp_token"`
	// The session's platform tools endpoint the token is for (https://<executor host>/v1/machines/{brain_machine_id}/mcp).
	ToolsMCPURL string `json:"tools_mcp_url"`
	// RFC 3339 time the token stops being accepted.
	ExpiresAt string `json:"expires_at"`
}

ToolsTokenRefreshResult Contract 1.4.0. tools_token.refresh result: the credential for the turn's next platform tool calls, in the form of the turn.start metadata tools_mcp_url, tools_mcp_token and tools_mcp_token_expires_at. Contract 2.4.0: for a turn started with platform_tools_mcp_* it is that credential renewed (the same members, used as platform_tools_mcp_url and platform_tools_mcp_token).

func SendToolsTokenRefresh added in v1.3.0

func SendToolsTokenRefresh(ctx context.Context, rpc RPC, params ToolsTokenRefreshParams) (ToolsTokenRefreshResult, error)

SendToolsTokenRefresh calls tools_token.refresh.

type TurnCancelParams

type TurnCancelParams struct {
	SessionID string `json:"session_id"`
	TurnID    string `json:"turn_id"`
	Reason    string `json:"reason,omitempty"`
}

TurnCancelParams is the params object of turn.cancel.

type TurnCancelResult

type TurnCancelResult struct {
	Canceled bool `json:"canceled"`
}

TurnCancelResult turn.cancel result. canceled=false when the turn is unknown or already ended; the turn still ends with its own session.status_idle event.

type TurnInputParams

type TurnInputParams struct {
	SessionID string            `json:"session_id"`
	TurnID    string            `json:"turn_id"`
	InputID   string            `json:"input_id"`
	Input     []AgentInputBlock `json:"input"`
}

TurnInputParams is the params object of turn.input.

type TurnStartParams

type TurnStartParams struct {
	// Platform session id.
	SessionID string `json:"session_id"`
	TurnID    string `json:"turn_id"`
	// Platform input id of the user message that starts the turn.
	InputID            string            `json:"input_id"`
	Input              []AgentInputBlock `json:"input"`
	ExecutorSessionRef string            `json:"executor_session_ref,omitempty"`
	Config             *AgentTurnConfig  `json:"config,omitempty"`
	DeadlineMS         int64             `json:"deadline_ms,omitempty"`
	// String key/value pairs the platform adds to the turn. Per-turn credentials the executor declared in AgentCapability.platform_credentials: model_base_url, model_token (and optionally model_context_window, model_max_output_tokens, model_input_images) for harness_model; for brain_tools (contract 1.4.0, only when this machine is the brain and a different machine the hands of the session) tools_mcp_url (https://executor.<domain>/v1/machines/{brain_machine_id}/mcp), tools_mcp_token and tools_mcp_token_expires_at (RFC 3339, 1 hour after turn.start). With tools_mcp_* present every tool call of the turn must go to that endpoint as an MCP tools/call (tools bash, read, write, edit, glob, grep) and none may run on this machine: when the endpoint cannot be reached or refuses the token the call fails and the executor never falls back to running the tool locally (fail closed). The token is bound to the turn's event epoch: the same turn started again after an executor restart (turn.start with the same turn_id, a new epoch) carries a new token and the previous token is refused. Refresh with tools_token.refresh. tool_policy is a JSON object of tool name to allow, ask or deny (for example {"bash":"ask","write":"deny"}): the permission of those tools for this turn, applied over AgentTurnConfig.permission_mode; an executor may only make a tool stricter than its own ceiling, never looser, and a tool the object does not name keeps the mode's permission. Keys the executor does not know are ignored. For platform_tools (contract 2.4.0, only when this machine runs the turn's brain and its tools itself and the turn's config.platform_tools is not empty): platform_tools_mcp_url (the same endpoint, https://executor.<domain>/v1/machines/{machine_id}/mcp), platform_tools_mcp_token and platform_tools_mcp_token_expires_at (RFC 3339, 1 hour after turn.start). Only the calls of config.platform_tools go there, as an MCP tools/call with the same _meta as with tools_mcp_*; every other tool of the turn runs on this machine as before. The endpoint answers this token's tools/list with the turn's platform_tools only and any other tool name with invalid params. When the endpoint cannot be reached or refuses the token the platform tool call fails; it never runs on this machine. egress (contract 1.9.0, only to an executor that declared egress.forwarder): the JSON text of the session's EgressHandoff (schemas/executor.json) for an executor that runs the turn and its tools itself; it replaces the session's handoff as session.assign metadata egress does, and a turn.start without it removes the handoff.
	Metadata map[string]string `json:"metadata,omitempty"`
}

TurnStartParams is the params object of turn.start.

type TurnStartResult

type TurnStartResult struct {
	Accepted bool   `json:"accepted"`
	TurnID   string `json:"turn_id"`
	// Opaque local session handle (for example the local agent's conversation id). The platform stores it and sends it back in the next turn.start so the executor can resume the local conversation after a restart. It names the local conversation, not only the session: an executor that no longer has the session's local state (state directory or volume lost, another instance without it) starts a new conversation and answers resumed false with a handle different from every one it answered before for the session (for example the session id qualified by a generation of its state directory). A different handle with resumed false is how the platform learns the earlier context is gone and tells the user (agent.message with bma_user_notice harness_context_lost); a handle the executor keeps is a continuation whatever resumed says.
	ExecutorSessionRef string `json:"executor_session_ref"`
	// true when the executor continued an existing local conversation, false when it started a new one.
	Resumed   bool            `json:"resumed"`
	Effective AgentTurnConfig `json:"effective"`
	// Contract 1.15.0. true when the executor had no local state for the session and rebuilt the conversation from the session's history (session.history) instead: the turn continues with the earlier context, and the platform tells the user once (agent.message with bma_user_notice harness_context_rebuilt). Answered with resumed false. Absent means false: with resumed false and a new executor_session_ref the context is lost (harness_context_lost).
	ContextRebuilt bool `json:"context_rebuilt,omitempty"`
}

TurnStartResult turn.start result. Idempotent by turn_id: a repeated turn.start for a turn the executor already accepted returns the same result without starting a second run.

type WebFetchInput added in v1.15.0

type WebFetchInput struct {
	// An http or https URL without credentials.
	URL string `json:"url"`
	// Default 20000.
	MaxChars int64 `json:"max_chars,omitempty"`
	// Default markdown.
	Format string `json:"format,omitempty"`
}

WebFetchInput Contract 2.1.0. Input of the platform tool web_fetch (agent_toolset_20260401): a public page the platform fetches through its SSRF guard (every connection and redirect hop to a public address only; at most 5 redirects; robots.txt respected; no cookies or credentials; 5 MB and 20 s at most; HTML, text, markdown, JSON and XML only; no JavaScript).

type WebFetchResult added in v1.15.0

type WebFetchResult struct {
	Outcome  string `json:"outcome"`
	Replayed bool   `json:"replayed"`
	// Open set: url_not_allowed, unsupported_content_type, content_too_large, fetch_failed, search_unavailable, rate_limited, max_uses_exceeded, billing_suspended and the platform tool codes (permission_denied, approval_required, approval_invalid, in_progress, idempotency_key_reused).
	ErrorCode string `json:"error_code,omitempty"`
	URL       string `json:"url,omitempty"`
	// The URL after redirects.
	FinalURL string `json:"final_url,omitempty"`
	Title    string `json:"title,omitempty"`
	// The media type served.
	ContentType string `json:"content_type,omitempty"`
	// The content was cut at max_chars.
	Truncated    bool  `json:"truncated,omitempty"`
	ContentChars int64 `json:"content_chars,omitempty"`
}

WebFetchResult Contract 2.1.0. structuredContent of a web_fetch answer. The answer's text names the final URL, title and content type and carries the extracted content inside <untrusted_web_content source="<final_url>"> … </untrusted_web_content> (the tag escaped inside the content).

type WebSearchInput added in v1.15.0

type WebSearchInput struct {
	Query string `json:"query"`
	// Default 5.
	NumResults int64 `json:"num_results,omitempty"`
	// Only results published within this period.
	Recency string `json:"recency,omitempty"`
	// Only results from these domains and their subdomains; not with blocked_domains.
	AllowedDomains []string `json:"allowed_domains,omitempty"`
	// No results from these domains and their subdomains; not with allowed_domains.
	BlockedDomains []string `json:"blocked_domains,omitempty"`
	// Language and country to favor (zh-CN, en-US).
	Locale string `json:"locale,omitempty"`
}

WebSearchInput Contract 2.1.0. Input of the platform tool web_search (agent_toolset_20260401): a web search the platform runs with its own provider. The turn offers exactly this schema.

type WebSearchResult added in v1.15.0

type WebSearchResult struct {
	Outcome  string `json:"outcome"`
	Replayed bool   `json:"replayed"`
	// Open set: url_not_allowed, unsupported_content_type, content_too_large, fetch_failed, search_unavailable, rate_limited, max_uses_exceeded, billing_suspended and the platform tool codes (permission_denied, approval_required, approval_invalid, in_progress, idempotency_key_reused).
	ErrorCode string `json:"error_code,omitempty"`
	Query     string `json:"query,omitempty"`
	// The search provider that answered (exa, bocha, brave, exa-keyless).
	Provider          string                `json:"provider,omitempty"`
	Results           []WebSearchResultItem `json:"results,omitempty"`
	ProviderRequestID string                `json:"provider_request_id,omitempty"`
}

WebSearchResult Contract 2.1.0. structuredContent of a web_search answer. The answer's text lists the same results as [n] title — url (published date) and snippet, inside <untrusted_web_content source="web_search"> … </untrusted_web_content> (the tag escaped inside the results), after a line telling the model the block is external data and to cite sources as markdown links.

type WebSearchResultItem added in v1.15.0

type WebSearchResultItem struct {
	Rank  int64  `json:"rank"`
	URL   string `json:"url"`
	Title string `json:"title"`
	// At most 600 characters of the page's text.
	Snippet string `json:"snippet,omitempty"`
	// When the page was published, when the provider knows it.
	PublishedAt string `json:"published_at,omitempty"`
}

WebSearchResultItem Contract 2.1.0. One ranked web_search result.

type WorkingLogAppendParams added in v1.6.44

type WorkingLogAppendParams struct {
	// Platform session id.
	SessionID string `json:"session_id"`
	// The entries to append, in order (sequence is ignored). Omitted or empty with acked_sequence only moves the mark.
	Entries []WorkingLogEntry `json:"entries,omitempty"`
	// The highest local sequence the platform has acknowledged so far.
	AckedSequence int64 `json:"acked_sequence,omitempty"`
}

WorkingLogAppendParams is the params object of working_log.append.

type WorkingLogAppendResult added in v1.6.44

type WorkingLogAppendResult struct {
	// The sequence of the log's last entry after the append.
	LastSequence int64 `json:"last_sequence"`
}

WorkingLogAppendResult Contract 1.22.0. working_log.append result.

func SendWorkingLogAppend added in v1.6.44

func SendWorkingLogAppend(ctx context.Context, rpc RPC, params WorkingLogAppendParams) (WorkingLogAppendResult, error)

SendWorkingLogAppend calls working_log.append.

type WorkingLogEntry added in v1.6.44

type WorkingLogEntry struct {
	// The platform's number of the entry (read only; ignored in an append).
	Sequence int64 `json:"sequence,omitempty"`
	// The executor's id of the entry (for a forwarded event, its event_id).
	ID string `json:"id"`
	// The executor's type of the entry (an AgentEvent type or a local marker type).
	Type string `json:"type"`
	// Idempotency key: an append of an entry whose key the log already has skips it. Omitted or empty: no key.
	Key string `json:"key,omitempty"`
	// When the executor wrote the entry; the platform's time of the append when omitted.
	OccurredAt string `json:"occurred_at,omitempty"`
	// The entry's body, stored as given.
	Payload map[string]any `json:"payload"`
}

WorkingLogEntry Contract 1.22.0. One entry of a session's working log. The platform stores entries verbatim, never shows them to tenants and numbers them 1, 2, ... per session in append order.

type WorkingLogReadParams added in v1.6.44

type WorkingLogReadParams struct {
	// Platform session id.
	SessionID string `json:"session_id"`
	// Read the entries with a sequence greater than this (default 0, the whole log).
	After int64 `json:"after,omitempty"`
	// At most this many entries (1-500, default 500).
	Limit int64 `json:"limit,omitempty"`
}

WorkingLogReadParams is the params object of working_log.read.

type WorkingLogReadResult added in v1.6.44

type WorkingLogReadResult struct {
	// The entries after the requested sequence, in order: at most limit, and at most about 512 KiB of payload (always at least one entry when any follows).
	Entries []WorkingLogEntry `json:"entries"`
	// More entries follow the last one returned: read again after its sequence.
	HasMore bool `json:"has_more"`
	// The highest local sequence the platform has acknowledged, as the last working_log.append set it (0 for none).
	AckedSequence int64 `json:"acked_sequence"`
}

WorkingLogReadResult Contract 1.22.0. working_log.read result.

func SendWorkingLogRead added in v1.6.44

func SendWorkingLogRead(ctx context.Context, rpc RPC, params WorkingLogReadParams) (WorkingLogReadResult, error)

SendWorkingLogRead calls working_log.read.

type WorkspaceBackupArchiveStored added in v1.6.5

type WorkspaceBackupArchiveStored struct {
	// sha256 of the compressed archive bytes exactly as stored (not of the tar stream).
	Digest string `json:"digest"`
	// Length of the compressed archive in bytes.
	SizeBytes int64 `json:"size_bytes"`
}

WorkspaceBackupArchiveStored PUT …/archive 200 answer: the archive as the server stored it; the executor copies both into WorkspaceBackupResult.

type WorkspaceBackupParams

type WorkspaceBackupParams struct {
	BackupID          string   `json:"backup_id"`
	Paths             []string `json:"paths"`
	Exclude           []string `json:"exclude,omitempty"`
	SkipIfFingerprint string   `json:"skip_if_fingerprint,omitempty"`
}

WorkspaceBackupParams is the params object of workspace.backup.

type WorkspaceBackupResult

type WorkspaceBackupResult struct {
	State       string `json:"state"`
	Fingerprint string `json:"fingerprint,omitempty"`
	Digest      string `json:"digest,omitempty"`
	SizeBytes   int64  `json:"size_bytes,omitempty"`
	Entries     int    `json:"entries,omitempty"`
	Skipped     int    `json:"skipped,omitempty"`
	Error       string `json:"error,omitempty"`
}

WorkspaceBackupResult workspace.backup result. digest and size_bytes describe the archive as the server stored it; skipped counts entries that could not be read (missing from the archive).

type WorkspaceCapability

type WorkspaceCapability struct {
	Backup bool `json:"backup"`
}

WorkspaceCapability workspace.backup support and the startup restore of a pending backup. Machine-scoped executors only.

type WorkspacePendingRestore added in v1.6.5

type WorkspacePendingRestore struct {
	BackupID string `json:"backup_id"`
	// sha256 of the compressed archive bytes exactly as stored (not of the tar stream).
	Digest string `json:"digest"`
	// Length of the compressed archive in bytes.
	SizeBytes int64 `json:"size_bytes"`
	// Absolute roots the backup covered; only entries under them are restored.
	Paths []string `json:"paths"`
}

WorkspacePendingRestore GET …/restore 200 answer: the backup a recreated machine restores before executor.register. The executor downloads GET …/backups/{backup_id}/archive, checks length = size_bytes and sha256 = digest before writing anything, restores it (WorkspaceArchive), then posts the result. Failures are retried with backoff before registering; when giving up it posts state failed.

type WorkspaceRestoreReport added in v1.6.5

type WorkspaceRestoreReport struct {
	State string `json:"state"`
	// Entries written (directories, files, symbolic links).
	Entries int `json:"entries,omitempty"`
	// Entries not written (WorkspaceArchive restore rules).
	Skipped int `json:"skipped,omitempty"`
	// Why state is failed.
	Error string `json:"error,omitempty"`
}

WorkspaceRestoreReport POST …/restore/result body. Unknown members are rejected (400). state restored also when some entries were skipped.

type WriteInput added in v1.0.0

type WriteInput struct {
	// File path, relative to the session workspace.
	Path string `json:"path"`
	// Full file content.
	Content string `json:"content"`
}

WriteInput write input: create or replace a file.

Directories

Path Synopsis
cmd
bma command
Command bma is the BMA command line (ADR-0102): one static binary that is both the API client and the BYO executor.
Command bma is the BMA command line (ADR-0102): one static binary that is both the API client and the BYO executor.
Package conformance is the tool route conformance suite of the SDK (ADR-0029 §5, cases T1–T11), for the tests of anything that is a bmaexecutor.ToolRoute: the SDK's LocalToolRoute and PlatformToolRoute, and the route of a brain or hands of your own.
Package conformance is the tool route conformance suite of the SDK (ADR-0029 §5, cases T1–T11), for the tests of anything that is a bmaexecutor.ToolRoute: the SDK's LocalToolRoute and PlatformToolRoute, and the route of a brain or hands of your own.
gatewaystub
Package gatewaystub is a contract double of the platform's execute-only tool gateway (ADR-0005) and of the hands behind it, for tests of brains, of hands and of the SDK's tool routes.
Package gatewaystub is a contract double of the platform's execute-only tool gateway (ADR-0005) and of the hands behind it, for tests of brains, of hands and of the SDK's tool routes.
examples
agentexecutor command
Command agentexecutor is a scripted local agent ("brain and hands" on this machine) served to the platform through the executor SDK's agent capability.
Command agentexecutor is a scripted local agent ("brain and hands" on this machine) served to the platform through the executor SDK's agent capability.
cloud-hand command
Command cloud-hand runs this machine as an executor ("hand") for the BMA cloud harness: the cloud assigns sessions and sends tool calls; the SDK execution core runs bash/file tools and the stdio MCP servers named in session.assign, and reports results back over the same connection.
Command cloud-hand runs this machine as an executor ("hand") for the BMA cloud harness: the cloud assigns sessions and sends tool calls; the SDK execution core runs bash/file tools and the stdio MCP servers named in session.assign, and reports results back over the same connection.
echo-mcp command
Command echo-mcp is a minimal stdio MCP server with one tool, "echo".
Command echo-mcp is a minimal stdio MCP server with one tool, "echo".
local-brain command
Command local-brain is a minimal local harness ("brain") driving the same executor execution core as the cloud, over loopback with the same protocol:
Command local-brain is a minimal local harness ("brain") driving the same executor execution core as the cloud, over loopback with the same protocol:
local-dsh command
Command local-dsh runs a local DSH brain on this computer for BMA: one executor connection (a BYO machine) that hosts bma-dsh-acp over ACP and runs its tools here, in the turn's working directory.
Command local-dsh runs a local DSH brain on this computer for BMA: one executor connection (a BYO machine) that hosts bma-dsh-acp over ACP and runs its tools here, in the turn's working directory.
sandboxed-folder command
Command sandboxed-folder runs this machine as a BMA executor whose processes work in a local folder chosen per session, inside a macOS sandbox-exec profile that only allows writes to that folder and the session's outputs.
Command sandboxed-folder runs this machine as a BMA executor whose processes work in a local folder chosen per session, inside a macOS sandbox-exec profile that only allows writes to that folder and the session's outputs.
third-party-brain command
Command third-party-brain is the smallest brain a third party can write against the SDK and the executor contract alone (ADR-0029): it takes a turn, decides what to do, asks the user's approval, runs the tool wherever the session's hands are, and reports events.
Command third-party-brain is the smallest brain a third party can write against the SDK and the executor contract alone (ADR-0029): it takes a turn, decides what to do, asks the user's approval, runs the tool wherever the session's hands are, and reports events.
third-party-hand command
Command third-party-hand is the smallest "hands" a third party can write against the SDK and the executor contract alone (ADR-0029): this computer registers with BMA, and whichever brain a session binds - on the platform, on another computer, or in a sandbox - uses it to run bash and file tools (read, write, edit, glob, grep) and processes in the session's workspace.
Command third-party-hand is the smallest "hands" a third party can write against the SDK and the executor contract alone (ADR-0029): this computer registers with BMA, and whichever brain a session binds - on the platform, on another computer, or in a sandbox - uses it to run bash and file tools (read, write, edit, glob, grep) and processes in the session's workspace.
windows-hand command
Command windows-hand is the machine executor for a Windows machine ("hand"): the SDK execution core (cmd.exe bash tool, file tools, stdio MCP), the process capability (Job Object process trees, ConPTY terminals, interrupts, file transfers), session files and, when Cua Driver runs in the desktop session, computer use.
Command windows-hand is the machine executor for a Windows machine ("hand"): the SDK execution core (cmd.exe bash tool, file tools, stdio MCP), the process capability (Job Object process trees, ConPTY terminals, interrupts, file transfers), session files and, when Cua Driver runs in the desktop session, computer use.
internal
conformance/agentharness command
Command agentharness is the Go agent-platform peer of the cross-language tests: a Go SDK Harness with an in-memory AgentPlatform that prints "LISTEN <ws-url>", starts one turn ("hello") on the first executor, allows its permission interaction, and expects the durable events session.status_running, agent.message "<language>:hello:allow", session.status_idle (completed) with sequences 1..3.
Command agentharness is the Go agent-platform peer of the cross-language tests: a Go SDK Harness with an in-memory AgentPlatform that prints "LISTEN <ws-url>", starts one turn ("hello") on the first executor, allows its permission interaction, and expects the durable events session.status_running, agent.message "<language>:hello:allow", session.status_idle (completed) with sequences 1..3.
conformance/executor command
Command executor is the Go executor peer of the cross-language tests: a Go SDK Client that dials the harness at os.Args[1] (bearer "conformance"), answers bash with "go:<command>", blocks on the bash command "block" until canceled, echoes MCP frames on server key "echo", and serves an agent that asks for permission, then emits agent.message "go:<first input text>".
Command executor is the Go executor peer of the cross-language tests: a Go SDK Client that dials the harness at os.Args[1] (bearer "conformance"), answers bash with "go:<command>", blocks on the bash command "block" until canceled, echoes MCP frames on server key "echo", and serves an agent that asks for permission, then emits agent.message "go:<first input text>".
conformance/harness command
Command harness is the cross-language conformance peer: a Go SDK Harness that prints "LISTEN <ws-url>", waits for one executor and drives the standard scenario.
Command harness is the cross-language conformance peer: a Go SDK Harness that prints "LISTEN <ws-url>", waits for one executor and drives the standard scenario.
interop/goexecutor command
Command goexecutor is the Go executor peer of the cross-language interop tests (python/tests/test_executor_interop.py).
Command goexecutor is the Go executor peer of the cross-language interop tests (python/tests/test_executor_interop.py).
interop/goharness command
Command goharness is the Go harness peer of the cross-language interop tests (python/tests/test_executor_interop.py).
Command goharness is the Go harness peer of the cross-language interop tests (python/tests/test_executor_interop.py).
interop/mcpexecutor command
Command mcpexecutor is the Go executor peer of the cross-language interop tests (TypeScript and Python).
Command mcpexecutor is the Go executor peer of the cross-language interop tests (TypeScript and Python).
interop/mcpharness command
Command mcpharness is the Go harness peer of the cross-language interop tests (TypeScript and Python).
Command mcpharness is the Go harness peer of the cross-language interop tests (TypeScript and Python).
tools
cligen command
Command cligen generates the resource commands of the bma CLI (cmd/bma/api_gen.go) from the public BMA OpenAPI document (ADR-0102): every operation becomes one entry of apiOperations, from which cmd/bma builds a cobra command.
Command cligen generates the resource commands of the bma CLI (cmd/bma/api_gen.go) from the public BMA OpenAPI document (ADR-0102): every operation becomes one entry of apiOperations, from which cmd/bma builds a cobra command.

Jump to

Keyboard shortcuts

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