envelope

package
v0.32.2 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2026 License: Apache-2.0 Imports: 10 Imported by: 0 modules, 0 packages

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

Documentation

Overview

Package envelope is the C4 event envelope, frozen at v1 (programme C4). SP2 owns it.

Index

Constants

View Source
const (
	Version         = 1
	MaxPayload      = 64 << 10 // C4
	MaxToolOutput   = 16 << 10 // SP2 §4
	MaxHumanMessage = 16 << 10 // SP2 §4
)

Envelope version and the size limits the broker enforces.

View Source
const (
	EndJudgeImpossible = "judge_impossible"
	EndStalled         = "stalled"
	EndNotMet          = "not_met"
)

The loop policy's end reasons, as agent-run sends them on its final read (harness R13).

View Source
const (
	OutcomeSucceeded       = "succeeded"
	OutcomeFailed          = "failed"
	OutcomeBudgetExhausted = "budget_exhausted"
	OutcomeRevoked         = "revoked"
	OutcomeLost            = "lost"
	OutcomeEnded           = "ended"
)

A run's outcome, once it has ended. An empty Outcome is a run that has not.

View Source
const (
	ScopeReady    = "ready"
	ScopeQuestion = "question"
)

The scope's states (scoper design SC6, SC7): ready, the implementer can start; question, the task waits for its issue's author.

View Source
const (
	MinChildren   = 2
	MaxChildren   = 5
	MaxSplitBytes = 21 << 10
)

A split's bounds (splitter design SL2, "The split"): 2 to 5 parts, 21 KiB in all, well under the broker's 64 KiB event beside the scope and the summary.

View Source
const EndBudgetCalls = "budget_calls"

EndBudgetCalls is the harness's end of a scoper run stopped at its tool-call limit before any handoff (harness roles HR2). The factory fails it open, as a missing scope.

View Source
const HarnessEnd = "harness_end"

HarnessEnd is the state_changed kind a bridge records when agent-run reports why the loop policy, or the scoper's tool-call limit, ended its run (loops design, "How a run ends"): {"kind":"harness_end","reason":…}.

View Source
const HarnessStatus = "harness_status"

HarnessStatus is the state_changed kind a bridge records for a change of its harness's execution_status: {"kind":"harness_status","status","previous"}, plus effort once the harness has told it.

View Source
const MaxMicroUSD int64 = 1_000_000_000_000

MaxMicroUSD bounds every dollar amount in the facts ($1,000,000), so sums of them cannot overflow.

View Source
const MaxProgressNote = 280

MaxProgressNote bounds a progress note, in characters.

View Source
const MaxRuns = 20

MaxRuns bounds TaskFacts.Runs.

View Source
const MaxScopeBytes = 4096

MaxScopeBytes bounds a scope as canonical JSON (SC6).

View Source
const MaxVerdict = 32

MaxVerdict bounds RunFact.Verdict, in bytes, as the Task CRD bounds RunRecord.Verdict.

View Source
const ScopeSchema = `{"type":"object","additionalProperties":false,"required":["state","task","touches","plan","acceptance"],"properties":{` +
	`"state":{"enum":["ready","question"]},` +
	`"task":{"type":"string","minLength":1,"maxLength":1000},` +
	`"touches":{"type":"array","minItems":1,"maxItems":10,"items":{"type":"string","minLength":1,"maxLength":200}},` +
	`"leave":{"type":"array","maxItems":10,"items":{"type":"string","minLength":1,"maxLength":200}},` +
	`"plan":{"type":"array","minItems":1,"maxItems":7,"items":{"type":"string","minLength":1,"maxLength":300}},` +
	`"assumptions":{"type":"array","maxItems":5,"items":{"type":"string","minLength":1,"maxLength":300}},` +
	`"acceptance":{"type":"array","minItems":1,"maxItems":5,"items":{"type":"object","additionalProperties":false,"required":["check","proves"],` +
	`"properties":{"check":{"type":"string","minLength":1,"maxLength":300},"proves":{"type":"string","minLength":1,"maxLength":200}}}},` +
	`"question":{"type":"string","maxLength":500}}}`

ScopeSchema is the scope property of room_handoff's input schema, listed to the triager only.

Variables

View Source
var Efforts = []string{"none", "minimal", "low", "medium", "high", "xhigh", "max"}

Efforts are the reasoning efforts a run may report: the gateway's providers' vocabularies, merged. A closed set of seven, so a value the sandbox chose is still a bounded metric label.

View Source
var ErrScope = errors.New("scope: state ready or question; task 1-1000 bytes; touches 1-10 and leave 0-10, each 1-200; " +
	"plan 1-7 and assumptions 0-5, each 1-300; acceptance 1-5 of {check 1-300, proves 1-200}; question 1-500 exactly when " +
	"state is question, with at least one assumption; at most 4096 bytes as JSON")

ErrScope is every refusal of Validate: the broker returns it to the model as an argument error.

View Source
var ErrSplit = errors.New("split: why 1-500 bytes; children 2-5, in the order they merge, each a scope in state ready " +
	"with no question; at most 21504 bytes as JSON; and beside it scope, in state ready: the whole task")

ErrSplit is every refusal of a split: Validate's, and a split handed off without the whole task.

View Source
var SplitSchema = `{"type":"object","additionalProperties":false,"required":["why","children"],"properties":{` +
	`"why":{"type":"string","minLength":1,"maxLength":500},` +
	`"children":{"type":"array","minItems":2,"maxItems":5,"items":` +
	strings.Replace(ScopeSchema, `"enum":["ready","question"]`, `"enum":["ready"]`, 1) + `}}}`

SplitSchema is the split property of room_handoff's input schema, listed to the triager only: each part is the scope's schema in state ready.

Functions

func Control

func Control(r rune) bool

Control is a control character other than tab and newline, or a Unicode format character (zero-width, bidi): the same runes steering.Validate refuses, since a scope is agent-influencing text in later implementer briefs.

func GitHubURL

func GitHubURL(s string) bool

GitHubURL reports whether s is the URL of a github.com issue or pull request.

func LoopEnd

func LoopEnd(reason string) bool

LoopEnd reports whether reason is one of the harness's end reasons: the loop policy's three and the scoper's tool-call limit.

func Must

func Must(v any) json.RawMessage

Must marshals a payload struct; the structs here cannot fail to marshal.

func Oversize

func Oversize(t Type, n int) json.RawMessage

Oversize is stored in place of a payload over MaxPayload (ruling P20): refusing a harness event would block the bridge's cursor forever.

func StatePayload

func StatePayload(kind string, fields map[string]any) json.RawMessage

StatePayload builds a state_changed payload: {kind, …fields}.

func TaskStatePayload

func TaskStatePayload(f TaskFacts) json.RawMessage

TaskStatePayload is the state_changed payload of a TaskFacts: {"kind":"task", ...facts}.

func ValidEffort

func ValidEffort(s string) bool

ValidEffort reports whether s is one of Efforts.

func ValidID

func ValidID(s string) bool

ValidID reports whether s is a C2 id: 8 characters of lowercase unpadded base32.

func ValidLogin

func ValidLogin(s string) bool

ValidLogin reports whether s is a GitHub login in that rule's shape: a user, or an App's "<slug>[bot]". Facts are not refused for an author outside it (legacy logins with double or trailing hyphens, Enterprise Managed Users' "name_shortcode" exist): a view that names the author in a sentence of its own checks it here, and says "the issue's author" otherwise.

func ValidModel

func ValidModel(s string) bool

ValidModel reports whether s is 1 to 64 letters, digits and ._:/@+- characters, starting with a letter or digit. spec.model is the claim's, never the sandbox's; this is defence in depth.

Types

type Acceptance

type Acceptance struct {
	Check  string `json:"check"`
	Proves string `json:"proves"`
}

Acceptance is one check the judge reads: a command or an observation, and what it proves.

type Actor

type Actor struct {
	Kind ActorKind `json:"kind"`
	ID   string    `json:"id"`
	Role string    `json:"role,omitempty"`
}

Actor is stamped by the broker from the authenticated credential, never taken from a client.

type ActorKind

type ActorKind string

ActorKind is who acted: an agent run, a human, or the platform.

const (
	ActorAgent  ActorKind = "agent"
	ActorHuman  ActorKind = "human"
	ActorSystem ActorKind = "system"
)

The three actor kinds.

type ApprovalDecidedPayload

type ApprovalDecidedPayload struct {
	ApprovalID string `json:"approvalId"`
	Decision   string `json:"decision"` // approved | denied | expired
	Reason     string `json:"reason,omitempty"`
}

ApprovalDecidedPayload is an approval_decided event's payload.

type ApprovalRequestedPayload

type ApprovalRequestedPayload struct {
	ApprovalID string          `json:"approvalId"`
	CallID     string          `json:"callId"`
	Class      string          `json:"class"`
	Action     json.RawMessage `json:"action"` // the raw, redacted call (T3)
	ExpiresAt  time.Time       `json:"expiresAt"`
	// Prompters are the principals who prompted the turn: with four-eyes on, none of
	// them may decide it. The page reads them to say who may.
	Prompters []string `json:"prompters,omitempty"`
}

ApprovalRequestedPayload is an approval_requested event's payload.

type BudgetFact

type BudgetFact struct {
	UsedTokens  int64 `json:"usedTokens"`
	LimitTokens int64 `json:"limitTokens"`
}

BudgetFact is the token budget and usage of a task.

type Delivery

type Delivery string

Delivery is how a message reaches a running agent.

const (
	DeliveryNone     Delivery = "none"
	DeliveryQueued   Delivery = "queued"
	DeliverySteering Delivery = "steering"
)

The delivery modes.

type Draft

type Draft struct {
	RoomID       string
	RunID        string
	Actor        Actor
	Type         Type
	CausedBy     *int64
	Origin       Origin
	OriginClient string
	OriginSeq    int64
	Redactions   []string
	Payload      json.RawMessage
}

Draft is everything a writer hands the store. The store stamps v, id, seq and ts. OriginClient and OriginSeq are the idempotency key: "agent:<runId>" + harnessSeq, "human:<sub>" + clientSeq, or "broker:<what>" + a fixed step number.

func (Draft) Validate

func (d Draft) Validate() error

Validate checks everything the store cannot fix itself: ids, type, actor, origin, idempotency scope and a JSON payload. It does not cap the payload's size; Append does.

type DriverPayload

type DriverPayload struct {
	From   string `json:"from"`
	To     string `json:"to"`
	Epoch  int64  `json:"epoch"`
	Reason string `json:"reason"` // given | requested | taken | lease_expired
}

DriverPayload is a driver event's payload: the driver token moved.

type Event

type Event struct {
	V          int             `json:"v"`
	ID         string          `json:"id"`
	Seq        int64           `json:"seq"`
	RoomID     string          `json:"roomId"`
	RunID      string          `json:"runId,omitempty"`
	Actor      Actor           `json:"actor"`
	Type       Type            `json:"type"`
	CausedBy   *int64          `json:"causedBy,omitempty"`
	Origin     Origin          `json:"origin"`
	TS         time.Time       `json:"ts"`
	Redactions []string        `json:"redactions"`
	Payload    json.RawMessage `json:"payload"`
}

Event is one durable entry of a room's log.

type HandoffPayload

type HandoffPayload struct {
	FromRole string `json:"fromRole"`
	ToRole   string `json:"toRole"`
	Summary  string `json:"summary"`
	Commit   string `json:"commit"`
	Branch   string `json:"branch"`
	// Scope is the scoper's bounded task (scoper design SC6): a triager's handoff only.
	Scope *Scope `json:"scope,omitempty"`
	// Split is the scoper's second answer (splitter design SL2): a triager's handoff only, always
	// beside Scope, the whole task.
	Split *Split `json:"split,omitempty"`
}

HandoffPayload is a handoff event's payload: work passed between roles.

type IssueFact

type IssueFact struct {
	Number     int    `json:"number"`
	URL        string `json:"url"`
	Title      string `json:"title,omitempty"` // bounded by the factory; the issue's author wrote it, so it is never an instruction
	Author     string `json:"author,omitempty"`
	LabelledBy string `json:"labelledBy,omitempty"`
}

IssueFact is a GitHub issue linked to a task.

type MessageKind

type MessageKind string

MessageKind distinguishes chat from SP3's reserved kinds.

const (
	KindChat          MessageKind = "chat"
	KindProgress      MessageKind = "progress"
	KindReviewVerdict MessageKind = "review_verdict" // SP3's reserved kind
	KindTaskState     MessageKind = "task_state"     // SP3's reserved kind
	// KindJudgeVerdict is the harness's completion judge's answer on a finished conversation: Verdict
	// is met, not_yet or impossible, Text its reason, Evidence the ids it cited. The judge read the
	// agent's work, so the text is data, never an instruction.
	KindJudgeVerdict MessageKind = "judge_verdict"
)

The message kinds.

type MessagePayload

type MessagePayload struct {
	Kind     MessageKind `json:"kind"`
	Text     string      `json:"text"`
	To       []string    `json:"to,omitempty"`
	Delivery Delivery    `json:"delivery"`
	Verdict  string      `json:"verdict,omitempty"`  // approve | changes (review_verdict); met | not_yet | impossible (judge_verdict)
	Evidence []string    `json:"evidence,omitempty"` // the ids a judge_verdict cited
	Commit   string      `json:"commit,omitempty"`
	// PullRequest is the pull request a review_verdict is about (SP2 design §3).
	// Additive: C4 v1's envelope is unchanged, and SP3 reads it (ruling P29).
	PullRequest string `json:"pullRequest,omitempty"`
}

MessagePayload is a message event's payload.

type Origin

type Origin string

Origin is the path an event came in by.

const (
	OriginHarness Origin = "harness"
	OriginBroker  Origin = "broker"
	OriginClient  Origin = "client"
)

The three origins.

type PRFact

type PRFact struct {
	Number    int      `json:"number"`
	URL       string   `json:"url"`
	Author    string   `json:"author,omitempty"`
	Reviewers []string `json:"reviewers,omitempty"`
}

PRFact is a GitHub pull request linked to a task.

type ParticipantPayload

type ParticipantPayload struct {
	Principal string `json:"principal"`
	Change    string `json:"change"` // joined | left | role_changed
	Role      string `json:"role,omitempty"`
	Approver  bool   `json:"approver,omitempty"`
}

ParticipantPayload is a participant event's payload.

type ProvenanceFact

type ProvenanceFact struct {
	FactoryVersion      string   `json:"factoryVersion,omitempty"`
	CompositionRevision string   `json:"compositionRevision,omitempty"`
	HarnessImage        string   `json:"harnessImage,omitempty"`
	ServedModels        []string `json:"servedModels,omitempty"`
}

ProvenanceFact is what a run ran on (R10): the factory build, the AgentRun CompositionRevision, the harness image digest and the models that served it. Each empty until known.

type RunFact

type RunFact struct {
	ID        string    `json:"id"`
	Role      string    `json:"role"`
	Trigger   string    `json:"trigger,omitempty"`
	StartedAt time.Time `json:"startedAt,omitzero"`
	// EndedAt, Outcome, Verdict and MicroUSD are set once the run has ended.
	EndedAt  time.Time `json:"endedAt,omitzero"`
	Outcome  string    `json:"outcome,omitempty"`
	Verdict  string    `json:"verdict,omitempty"`
	MicroUSD int64     `json:"microUSD,omitempty"`
	// What the run ran on (R10), as far as the factory knows it yet.
	Provenance *ProvenanceFact `json:"provenance,omitempty"`
}

RunFact is a run's role, trigger, and lifecycle in a task.

type Scope

type Scope struct {
	State       string       `json:"state"`
	Task        string       `json:"task"`
	Touches     []string     `json:"touches"`
	Leave       []string     `json:"leave,omitempty"`
	Plan        []string     `json:"plan"`
	Assumptions []string     `json:"assumptions,omitempty"`
	Acceptance  []Acceptance `json:"acceptance"`
	Question    string       `json:"question,omitempty"`
}

Scope is the scoper's bounded task (SC6), carried by a triager's room_handoff. The broker validates it; the factory re-injects it into every implementer brief (SC9).

func (Scope) Validate

func (s Scope) Validate() error

Validate checks the scope's shape and bounds (SC6). Bytes, not characters: the bound is the brief's, which is bytes.

type SpendFact

type SpendFact struct {
	UsedMicroUSD  int64 `json:"usedMicroUSD"`
	LimitMicroUSD int64 `json:"limitMicroUSD,omitempty"`
}

SpendFact is the dollars a task has spent and, when it has one, its dollar limit.

type Split

type Split struct {
	Why      string  `json:"why"`
	Children []Scope `json:"children"`
}

Split is the scoper's second answer (SL1, SL2): the task as two to five bounded tasks, in the order they merge, each a scope in state ready. It rides a triager's room_handoff beside the scope of the whole task, which /factory retry runs when a maintainer declines the split.

func (Split) Validate

func (s Split) Validate() error

Validate checks the split's shape and bounds (SL2). Each part is a scope, held to Scope.Validate.

type TaskFacts

type TaskFacts struct {
	Phase  string      `json:"phase"`
	Reason string      `json:"reason,omitempty"`
	Run    *RunFact    `json:"run,omitempty"`
	Budget *BudgetFact `json:"budget,omitempty"`
	// Spend is the task's dollars, beside Budget's tokens (BudgetFact is unchanged).
	Spend *SpendFact `json:"spend,omitempty"`
	// Runs is the task's run history, oldest first, at most MaxRuns.
	Runs  []RunFact  `json:"runs,omitempty"`
	Issue *IssueFact `json:"issue,omitempty"`
	PR    *PRFact    `json:"pr,omitempty"`
	// Origin is the room of the investigate task this task's issue was published from (RunLore
	// agent-to-agent RA10), a C2 id; the webhook tracker repeats it on every event of the room.
	Origin string `json:"origin,omitempty"`
}

TaskFacts are what the factory knows about a room's task, written as state_changed{kind:task} so the room summary depends on the room log alone.

func (TaskFacts) Validate

func (f TaskFacts) Validate() error

Validate refuses facts a broker should not store.

type ToolCallPayload

type ToolCallPayload struct {
	CallID    string          `json:"callId"`
	Tool      string          `json:"tool"`
	Args      json.RawMessage `json:"args"`
	Class     string          `json:"class,omitempty"`
	Risk      string          `json:"risk,omitempty"`
	DecidedBy *string         `json:"decidedBy"` // policy | human | null
}

ToolCallPayload is a tool_call event's payload.

type ToolResultPayload

type ToolResultPayload struct {
	CallID    string `json:"callId"`
	Status    string `json:"status"` // ok | error | rejected
	Output    string `json:"output"`
	Truncated bool   `json:"truncated"`
	Bytes     int    `json:"bytes"`
}

ToolResultPayload is a tool_result event's payload.

type TurnPayload

type TurnPayload struct {
	RunID  string `json:"runId"`
	TurnID string `json:"turnId"`
	Phase  string `json:"phase"` // started | completed | cancelled | failed
}

TurnPayload is a turn event's payload.

type Type

type Type string

Type is an event's kind, one of the ten C4 types.

const (
	Message           Type = "message"
	Turn              Type = "turn"
	ToolCall          Type = "tool_call"
	ToolResult        Type = "tool_result"
	ApprovalRequested Type = "approval_requested"
	ApprovalDecided   Type = "approval_decided"
	Participant       Type = "participant"
	Driver            Type = "driver"
	Handoff           Type = "handoff"
	StateChanged      Type = "state_changed"
)

The ten C4 event types.

func (Type) Valid

func (t Type) Valid() bool

Valid reports whether t is one of the ten C4 types.

Jump to

Keyboard shortcuts

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