Documentation
¶
Overview ¶
Package bridge is the room bridge inside the sandbox: the only client of the harness's local API besides agent-run, and the run's one pipe to the room.
Index ¶
- Constants
- Variables
- func SeqFor(eventIndex int64, k int) int64
- func Stricter(a, b wire.ApprovalPolicy) wire.ApprovalPolicy
- type Admission
- type ApprovalRequester
- type Bridge
- type Broker
- func (b *Broker) Hello(ctx context.Context) (wire.Resume, Reply, error)
- func (b *Broker) RequestApproval(ctx context.Context, r wire.ApprovalRequest) (wire.ApprovalAck, int, error)
- func (b *Broker) Send(ctx context.Context, items []json.RawMessage) (Reply, error)
- func (b *Broker) Stream(ctx context.Context, handle func(event string, data []byte) error) error
- type Class
- type Classifier
- type Confirmer
- func (c *Confirmer) ClassOf(tool string, action json.RawMessage, risk string) string
- func (c *Confirmer) Decision(ctx context.Context, d wire.Decision) error
- func (c *Confirmer) Gate(ctx context.Context, send func(run bool) error) error
- func (c *Confirmer) Observe(e RawEvent)
- func (c *Confirmer) OnStatus(ctx context.Context, status string)
- func (c *Confirmer) Ready(ctx context.Context) error
- func (c *Confirmer) SetPolicy(p wire.ApprovalPolicy)
- type Conversation
- type Cursor
- type FinalReadResult
- type Harness
- func (h *Harness) AlwaysConfirm(ctx context.Context) error
- func (h *Harness) Conversation(ctx context.Context) (Conversation, error)
- func (h *Harness) Interrupt(ctx context.Context) error
- func (h *Harness) Message(ctx context.Context, text string, run bool) error
- func (h *Harness) Next(ctx context.Context, c Cursor) ([]RawEvent, Cursor, error)
- func (h *Harness) Page(ctx context.Context, pageID string) ([]RawEvent, string, error)
- func (h *Harness) Ready(ctx context.Context) error
- func (h *Harness) Respond(ctx context.Context, accept bool, reason string) error
- func (h *Harness) Run(ctx context.Context) error
- func (h *Harness) Send(ctx context.Context, text string) error
- func (h *Harness) Skip(ctx context.Context, n int64) (Cursor, error)
- func (h *Harness) Status(ctx context.Context) (string, error)
- type Mapped
- type RawEvent
- type Reply
- type StatusError
- type StatusItem
- type StatusTracker
- type Steering
- type Verdict
Constants ¶
const ( // MemoryLimit is the soft heap limit room-bridge sets (GOMEMLIMIT) inside // the sidecar's 64 Mi limit, leaving the rest to the runtime and stacks. MemoryLimit = 48 << 20 // DefaultMaxBuffer is the MaxBuffer a zero value means. The heap's worst // case is the buffer before a poll, plus what that poll's Next retains and // reads, plus the items it maps; TestTheWorstCaseHeapFitsTheMemoryLimit // pins the sum under MemoryLimit. DefaultMaxBuffer = 3 << 20 )
const ( StallEventTooLarge = "event_too_large" StallCursorLost = "cursor_lost" StallNextPageUnreadable = "next_page_unreadable" )
The reasons the harness's log stops moving: each is an adapter error that holds the cursor where it is (Task 1.10). They label rooms_bridge_harness_stalls_total and are the code of the harness_error the room is told.
const ( StubOversize = "oversize" // alone over the broker's body cap StubRefused = "refused" // refused by the broker for what it is (400) )
The reasons an item is replaced by a stub in its slot, labelling rooms_bridge_items_stubbed_total.
const ( // DefaultMaxPages is the MaxPages NewHarness sets. A Next call retains at // most MaxPages × maxResponseBytes of events and reads one more body on top // of that: 32 MiB at the default, inside the sidecar's 64 Mi limit. DefaultMaxPages = 1 )
const ItemsPerEvent = 4
ItemsPerEvent is how many seqs each harness event owns: event i (1-based) owns 4i … 4i+3, so a resumed bridge re-maps from event afterHarnessSeq/4 and the store's idempotency drops what already landed. Map yields at most two.
Variables ¶
var ( // ErrEventTooLarge is one event alone over the response cap. The walk stops // before it and never moves past it: the next event's id sits in the same // unreadable body, and skipping blind would shift every later seq. The // bridge reports it (harness_error event_too_large) rather than drop it. ErrEventTooLarge = errors.New("a harness event is over the response cap") // ErrCursorLost is agent-server answering the cursor's page_id without that // event first. page_id is inclusive, so the server ignored it; accepting // the page would append events already in the log under new seqs. ErrCursorLost = errors.New("agent-server did not return the cursor's event first") // ErrNextPageUnreadable is a page that must have a next page but names none // that can be asked for: a next_page_id that is not a string, or none after // a halved read (the larger read had more events). Ending the walk there // would stall the cursor silently on every poll. ErrNextPageUnreadable = errors.New("agent-server named no readable next page") )
Functions ¶
func Stricter ¶
func Stricter(a, b wire.ApprovalPolicy) wire.ApprovalPolicy
Stricter decides every class as the stricter of a and b, deny over human over allow, written as attended plus the overrides that differ from its row. A fork its source's owner did not make takes it against a new room's default, so a watcher never drives under a weaker gate than a room of their own (ruling M2).
Types ¶
type Admission ¶
type Admission struct {
Admitted bool // the broker handed this run the room's bridge lease
Refused string // why it never will: wire.ReasonRoomBusy or wire.ReasonSealed
}
Admission is what the bridge's first hellos decided (F15). The zero value is pending. room-bridge gate holds the harness until it is decided, and fails the pod on a refusal, so no run executes unless its bridge holds the room.
type ApprovalRequester ¶
type ApprovalRequester interface {
RequestApproval(ctx context.Context, r wire.ApprovalRequest) (wire.ApprovalAck, int, error)
}
ApprovalRequester opens an approval in the room (Broker.RequestApproval).
type Bridge ¶
type Bridge struct {
Harness *Harness
Broker *Broker
RunID string
// Interval is the poll period; zero means 1 s.
Interval time.Duration
// MaxBuffer caps the encoded bytes waiting for the broker; past it the
// harness's events are not mapped (back-pressure), so the buffer holds at
// most MaxBuffer plus one poll's items. Status changes are still recorded
// up to twice MaxBuffer. Zero means DefaultMaxBuffer.
//
// Past the cap the bridge stops buffering, not reading: local policy
// verdicts are still answered; human decisions wait for the broker.
MaxBuffer int
// FlushGrace bounds the drain after SIGTERM; zero means 25 s.
FlushGrace time.Duration
// MinBackoff and MaxBackoff bound the retry of a failed call; zero means
// 250 ms and 30 s.
MinBackoff, MaxBackoff time.Duration
Logger *slog.Logger
// Meter makes the rooms_bridge_* instruments; nil means a no-op meter.
// room-bridge passes none: nothing scrapes a sandbox (C4), so the broker
// counts the same signals from the events it appends (Ruling AP).
Meter metric.Meter
// Now is the clock; nil means time.Now.
Now func() time.Time
// Ticker times the loop's wait between two steps; it is called once per
// wait and returns the channel a tick arrives on and its stop. Tests inject
// it; nil means a one-shot timer per wait.
Ticker func(d time.Duration) (<-chan time.Time, func())
// The stream's hooks. An error ends the stream, which is re-dialled and
// replays from the log's last acknowledgement.
OnDeliver func(ctx context.Context, d wire.Deliver) error // phase 4
OnInterrupt func(ctx context.Context, i wire.Interrupt) error // phase 4
OnDecision func(ctx context.Context, d wire.Decision) error // phase 5
OnResume func(ctx context.Context, r wire.Resume) // phase 5
// The confirmation loop's hooks (phase 5), called on the loop except OnReady.
//
// OnReady runs from the start, before the broker's hello and whatever it
// answers, until it succeeds (review C2). OnRaw sees every harness event read, those a restart skips
// included, before it is mapped. OnStatus gets a status only after an
// events poll that started after that status was read and reached the
// log's end, so every action the harness wrote before it was passed to
// OnRaw. Classify sets each tool_call's class.
OnReady func(ctx context.Context) error
OnRaw func(e RawEvent)
OnStatus func(ctx context.Context, status string)
Classify func(tool string, action json.RawMessage, risk string) string
// contains filtered or unexported fields
}
Bridge mirrors one run's harness into its room: it polls the harness, maps its events, and pushes them to the broker in batches, never dropping one. A broker outage never stops the sandbox (§3): the harness keeps its own store, and the bridge resumes from the log's cursor.
func (*Bridge) FinalRead ¶
FinalRead asks the loop to read the harness log to its end and mirror it now, and waits for the answer or ctx. agent-run calls it on SIGTERM before it stops agent-server (F11, the harness half; disruption design §2): the bridge's own SIGTERM drain comes only once the harness has exited, when agent-server is gone. It does not stop the loop. end is the loop policy's end reason agent-run reported, "" for none: one of envelope.LoopEnd's reasons is recorded on the status stream as harness_end before the log is read, any other ignored.
func (*Bridge) Healthy ¶
Healthy backs /healthz (ruling P6): a native sidecar must not fail before the harness starts, since its startup probe gates the harness container. A sealed room has nothing left to mirror, which is not a failure.
func (*Bridge) PastCap ¶
PastCap reports that the last events poll found the buffer full: the broker is behind, so only what policy decides alone is answered (Confirmer.PastCap). Safe for concurrent use.
type Broker ¶
type Broker struct {
// contains filtered or unexported fields
}
Broker is the bridge's client of the broker's :8443, over TLS trusting only the broker's CA (GP-18). The token is re-read before every request and never watched: under gVisor, kubelet's host-side rotation raises no inotify, but a plain read sees the new file (SP1 spike Q2).
func NewBroker ¶
NewBroker returns the client of the broker at base, which must be https://. caFile holds the PEM CA the broker's certificate chains to, and is the only root trusted. It refuses to start without one.
func (*Broker) RequestApproval ¶
func (b *Broker) RequestApproval(ctx context.Context, r wire.ApprovalRequest) (wire.ApprovalAck, int, error)
RequestApproval asks the room's approvers to decide a pending action, and returns the approval the broker opened (idempotent per call id) with the status code of its answer. An error means the request got no answer.
func (*Broker) Send ¶
Send posts one batch of items, each already a marshalled wire.Item, so the bytes the caller measured are the bytes sent.
type Classifier ¶
type Classifier struct {
Branch string
Egress map[string]bool
// ReadOnlyMCP holds the MCP tools that only read, as <server>__<tool>.
// Anything else is mcp.write; the zero value gates every MCP tool.
ReadOnlyMCP map[string]bool
// SearchBuiltin is AGENT_SEARCH=1: the run was given the harness's search tool, so a bare
// "search" is that tool and plain. Without it a bare "search" is an MCP tool like any other.
// It assumes MCP tools reach the bridge prefixed (server_tool): an unprefixed MCP "search" on a
// run given search would also class plain, and makes the SDK refuse the run at start anyway
// (duplicate tool names).
SearchBuiltin bool
}
Classifier knows the run's own branch, the egress profiles it was given and the MCP tools it may call without asking.
func (Classifier) Classify ¶
func (c Classifier) Classify(tool string, action json.RawMessage, risk string) Class
Classify maps one harness action to its class, deterministically: the harness's own risk label only matters when nothing else matched.
type Confirmer ¶
type Confirmer struct {
Harness *Harness
Broker ApprovalRequester
Classifier Classifier
RunID string
Push func(wire.Item)
Logger *slog.Logger
// Now is the clock; nil means time.Now.
Now func() time.Time
// Suspendable is a run whose pod may be suspended and resumed on its PVC
// (AGENT_SUSPENDABLE, v2 plan P6). Its new pod's conversation reloads
// paused, as the previous pod's SIGTERM path left it, and nothing but this
// bridge continues it: agent-run sends nothing, a message would reject the
// pending call and a bare /run would execute it.
Suspendable bool
// PastCap reports that the bridge's buffer is full (Bridge.PastCap): the
// broker is behind, maybe down, so a step needing a human decision is not
// asked for, which an outage would reject, but left waiting until it drains;
// allows and denies are still answered. Nil means never.
PastCap func() bool
// contains filtered or unexported fields
}
Confirmer answers the harness's confirmations (§6). Under AlwaysConfirm every action waits; the bridge allows or denies it locally, or escalates it to the room's approvers. OpenHands answers all pending actions at once (spec open item), so one deny rejects the whole step and one human class holds its siblings. A message sent with run:true confirms every pending action implicitly, so steering goes through Gate (review C1).
Approvals are oversight, not a boundary (S9), and the loop fails closed: a classifier panic is forge.other, an unreadable action is denied, and a broker outage, a missing decision or any other failure rejects the step or leaves it waiting, never accepts it.
Its methods are safe for concurrent use: the bridge's loop calls Observe and OnStatus, the stream calls Decision and, through steering, Gate.
func (*Confirmer) ClassOf ¶
ClassOf is the class a tool_call is logged with: the one the confirmation loop decides by.
func (*Confirmer) Decision ¶
Decision records an approver's decision from the broker's stream, and answers the step if it completes it. A decision no pending action names is held, a few at most, for a request re-sent after a restart; one for an answered step is dropped. It never fails the stream: an answer the harness refuses is retried at the next status.
func (*Confirmer) Gate ¶
Gate delivers a steering message without ever confirming a step (review C1, re-reviews C1 and SAW). A message sent with run:true, or a /run, on a conversation waiting for a confirmation confirms every pending action; and the bridge's own view lags the harness. So the message goes in with run false first, then the harness is asked:
- waiting or paused: reject every pending action, read by the bridge or not, then /run;
- running: nothing more. The live loop takes the message, and a step that parks later goes through the loop's classification (re-review 2 M8);
- anything else (idle, finished, stuck, error): /run alone.
A send that fails returns its error and the delivery is replayed. Once the message is in, the loop's next status predates it and is skipped, so the resume retry never acts on a status read before the gate wrote (re-review 2 I1). A failed status read leaves the run to that retry, from a fresh idle status (M9); a failed rejection leaves the step to the loop.
func (*Confirmer) Observe ¶
Observe tracks which actions still wait for a result. An action it cannot read is still tracked, and denied: the harness answers every pending action at once, so one left out would run unclassified.
func (*Confirmer) OnStatus ¶
OnStatus answers the step the harness waits on, when the bridge has read every event it wrote before status. It runs on the bridge's loop.
func (*Confirmer) Ready ¶
Ready switches the conversation to AlwaysConfirm (ruling P5). The bridge calls it until it succeeds, before and whatever the broker answers.
func (*Confirmer) SetPolicy ¶
func (c *Confirmer) SetPolicy(p wire.ApprovalPolicy)
SetPolicy sets the room's approval profile, handed over at hello.
type Conversation ¶
type Conversation struct {
Status string // execution_status
// Effort is the reasoning effort agent-run put in the conversation's tags; empty from an older
// agent-run, and unchecked: StatusTracker.Tell keeps only a valid one. No other tag is read: the
// agent can rewrite them, and the room takes the run's model from its claim.
Effort string
}
Conversation is what one read of the conversation tells the bridge.
type Cursor ¶
type Cursor struct {
// LastID is the last well-formed event returned: the page the next walk
// asks for. It is never a Malformed event's id, so it never rewinds.
LastID string
// Count is how many events were returned, Malformed ones included: the
// event index SeqFor keys on.
Count int64
// Unkeyed is how many Malformed events after LastID were returned; the next
// walk passes over them.
Unkeyed int64
}
Cursor walks the append-only event log.
type FinalReadResult ¶
type FinalReadResult struct {
Events int64 `json:"events"`
Unmirrored int `json:"unmirrored"`
Sealed bool `json:"sealed"`
}
FinalReadResult is what a final read reached: the harness events read so far, the items still unmirrored when it answered, and whether the room is sealed.
type Harness ¶
type Harness struct {
// MaxPages caps one Next call, so a backlog after a restart is read a few
// pages per poll rather than all at once into a 64 Mi container (review M13).
// NewHarness sets DefaultMaxPages; a value below one reads one page.
MaxPages int
// contains filtered or unexported fields
}
Harness speaks agent-server 1.56.0 on loopback (ruling P4). It is not safe for concurrent Next and Skip calls on one cursor; the bridge owns its cursor.
func NewHarness ¶
NewHarness returns the adapter for one conversation of the agent-server at base.
func (*Harness) AlwaysConfirm ¶
AlwaysConfirm makes every pending action wait for the bridge (§6; ruling P5).
func (*Harness) Conversation ¶
func (h *Harness) Conversation(ctx context.Context) (Conversation, error)
Conversation reads the conversation's status and agent-run's effort tag.
func (*Harness) Message ¶
Message appends a user message, and with run starts the conversation. A run on a conversation waiting for a confirmation confirms every pending action, so the confirmation loop sends with run false (Confirmer.Gate).
func (*Harness) Next ¶
Next returns the events after c, at most MaxPages pages of them. On error it returns what it read so far and the cursor advanced over exactly those.
func (*Harness) Page ¶
Page reads up to 100 events from pageID, inclusive, and the id of the first event of the next page ("" on the last page). A page over the response cap is asked again with half the limit; one event alone over it is ErrEventTooLarge. With ErrNextPageUnreadable it still returns the page's events.
func (*Harness) Run ¶
Run resumes the conversation: after a rejected confirmation OpenHands sets it idle and does not run on its own. A 409 means a run is in progress.
type Mapped ¶
type Mapped struct {
Type envelope.Type
Payload json.RawMessage
}
Mapped is one C4 item a harness event becomes, ready for the bridge to push. Its payload is always a JSON object within envelope.MaxPayload.
func Map ¶
Map turns one harness event into zero, one or two C4 items, following the spec table (§3 Event mapping). It is total: fields of the wrong type read as empty, a kind agent-server 1.56.0 did not have becomes a harness_event state_changed that records the kind and nothing the event said, and a Malformed event one that records only "malformed".
func StallNotice ¶
StallNotice is the status item that tells the room the harness's log stopped moving for reason. Nothing after that point is mirrored until it moves again.
func Stub ¶
Stub stands in for an item of type t and n payload bytes that the broker cannot take as sent (why is StubOversize or StubRefused; reason is the broker's wire reason, if any). Its slot is kept so the cursor moves on and nothing after it is lost (ruling P20, review I6). Only turn, tool_call and tool_result accept the store's oversize stub; any other item becomes a harness_event naming why, the item's type (detail), its size and the reason.
type RawEvent ¶
type RawEvent struct {
ID string `json:"id"`
Kind string `json:"kind"`
Source string `json:"source"`
Raw json.RawMessage
// Malformed is an event without a non-empty string id, or with a kind or
// source that is not a string. It is returned and counted, so the event
// positions stay aligned, but it never keys the cursor.
Malformed bool
}
RawEvent is one OpenHands event, kept whole for the mapping.
func (*RawEvent) UnmarshalJSON ¶
UnmarshalJSON reads the id, kind and source and keeps the whole event in Raw. It never fails: an event it cannot read is Malformed, so one bad event cannot fail its page and wedge every event after it.
type Reply ¶
Reply is the broker's answer to a request that reached it. Reason is the wire.Error reason of a refusal; RetryAfter is the raw Retry-After header.
type StatusError ¶
StatusError is agent-server answering with a non-2xx status. A 404 on Ready means agent-run has not created the conversation yet.
func (*StatusError) Error ¶
func (e *StatusError) Error() string
Error names the request and the status, never a response body.
type StatusItem ¶
StatusItem is one item of the status stream and its seq there.
type StatusTracker ¶
type StatusTracker struct {
// contains filtered or unexported fields
}
StatusTracker turns polled execution_status values into state_changed and turn items (§3: state events → turn/state_changed), numbered on the status stream. The zero value starts the stream at seq 1; it is not safe for concurrent use.
func (*StatusTracker) Emit ¶
func (t *StatusTracker) Emit(m Mapped) StatusItem
Emit numbers an item the bridge adds to the status stream itself.
func (*StatusTracker) Observe ¶
func (t *StatusTracker) Observe(status, runID string) []StatusItem
Observe records one polled status. An unchanged status yields nothing; a change yields a harness_status item, with the effort Tell recorded, and a turn item when it starts or ends a turn. waiting_for_confirmation stays inside the turn it interrupts.
func (*StatusTracker) Resume ¶
func (t *StatusTracker) Resume(afterSeq int64)
Resume continues the status stream after afterSeq, the log's cursor at hello. Turn ids derive from these seqs, so a restarted bridge never reuses one (Ruling AL b).
func (*StatusTracker) Tell ¶
func (t *StatusTracker) Tell(effort string)
Tell records the reasoning effort the harness reported, for every harness_status after it. A value outside envelope.Efforts is left out, so a bad tag costs that field, never the item.
type Steering ¶
type Steering struct {
Harness *Harness
RunID string
Push func(wire.Item)
// Gate runs each steering send (Confirmer.Gate), deciding its run flag: a message with run:true
// would confirm a waiting step implicitly, so the step is rejected first.
Gate func(ctx context.Context, send func(run bool) error) error
// contains filtered or unexported fields
}
Steering injects the driver's messages and interrupts into the harness, once each, and acknowledges them on the status stream (§2 Steering, Interrupt).
A transient failure returns its error, which ends the broker stream: the re-dialled stream replays from the log's last acknowledgement, so the failed ref is retried before any later one is handed over. Acknowledging a later ref first would move LastAck past the failed one for good. A permanent refusal (review 4.3 I2; for an interrupt, any 4xx) is acknowledged as undeliverable instead, with the harness's status code: retrying it would block every later ref. Delivery is at least once: a ref injected but not yet acknowledged in the log when the bridge restarts is injected again.
func (*Steering) Deliver ¶
Deliver sends a steering message, consumed by OpenHands at its next step (run: true).