package wire import ( "encoding/json" "errors" "fmt" "reflect" "regexp" "slices" "strings" "time" ) // Runner stream protocols. 1 is the slice 4 wire: a hello without // protocol. 2 adds roles, capabilities, placement, the attempt-specific // start authorization, pack transfers and publication (Mac runners spec // §3.3). 3 adds a fix round's Feedback (DispatchCommand) and a usage // row's Turns (ProtocolSpend). 4 adds what merge authority needs (spec // 2026-11-11, ProtocolMergeFacts): the review's change facts, the merge's // provenance, the merge request's own confirmation naming the attempt, // and a revert's target. 7 adds the person's choice to run a Mac's // checks outside the sandbox (ProtocolSandboxConsent). 8 adds the // merge step's refusal for an unborn default branch (ProtocolEmptyMerge) // and 9 adds preview steps (ProtocolPreview). Code asks for a capability // by name, never by number. Each end speaks the lower of the two on // each connection and encodes every frame for it with Encode; nothing an // older peer does not know ever reaches it. const ( Protocol1 = 1 Protocol2 = 2 Protocol3 = 3 Protocol4 = 4 Protocol5 = 5 Protocol6 = 6 Protocol7 = 7 Protocol8 = 8 Protocol9 = 9 Protocol10 = 10 Protocol11 = 11 Protocol12 = 12 Protocol13 = 13 Protocol14 = 14 Protocol15 = 15 Protocol16 = 16 Protocol17 = 17 Protocol18 = 18 Protocol19 = 19 Protocol20 = 20 Protocol21 = 21 Protocol22 = 22 Protocol23 = 23 Protocol24 = 24 Protocol25 = 25 Protocol26 = 26 Protocol27 = 27 Protocol28 = 28 Protocol29 = 29 Protocol30 = 30 Protocol31 = 31 Protocol32 = 32 Protocol33 = 33 Protocol34 = 34 Protocol35 = 35 Protocol36 = 36 Protocol37 = 37 Protocol38 = 38 // ProtocolSpend is the first protocol with a fix round's Feedback and // a usage row's Turns; Encode drops both below it. ProtocolSpend = Protocol3 // ProtocolMergeFacts is the first protocol with merge authority's // fields; Encode drops them below it, and Equipo merges on its own // only with a runner that speaks it. ProtocolMergeFacts = Protocol4 // ProtocolHostedChecks is the first protocol with hosted checks (a // checks dispatch's offer and the report's hosted binding); Encode // drops both below it, so the runner runs its own gate as before. ProtocolHostedChecks = Protocol5 // ProtocolEmptyRepos is the first protocol whose catalog lists a // reachable repository with no commits yet (RepoInfo.Empty); Encode // drops those entries below it, so an older instance sees the catalog // it always did. ProtocolEmptyRepos = Protocol6 // ProtocolSandboxConsent is the first protocol with the person's // choice to run a Mac's checks outside the sandbox // (DispatchCommand.Unsandboxed) and the worker's refusal to run them // otherwise (ReasonSandboxUnproven). Encode drops the choice below it, // so an older peer never carries consent, and turns the refusal into // placement_refused, which an older instance places elsewhere. ProtocolSandboxConsent = Protocol7 // ProtocolEmptyMerge is the first protocol with the merge step's // refusal for a repository whose default branch is unborn and a hub // that cannot make the first merge yet (ReasonMergeUnbornDefault). // Encode says it as merge_failed below it, the reason an older // instance gives every other hub refusal. ProtocolEmptyMerge = Protocol8 // ProtocolPreview is the first protocol with preview steps: Review's // has_preview, the step's result and the publish check's digest. // Encode drops those below it and refuses a preview dispatch outright. ProtocolPreview = Protocol9 // ProtocolExplore is the first protocol with exploration tasks' // fields: the primary's previews capability and record_task's kind. // Encode drops both below it, except a kind that says explore, which // it keeps so an older instance refuses the call. ProtocolExplore = Protocol10 // ProtocolPreviewHost is the first protocol whose hello says which // preview host the runner is paired with (Capabilities.PreviewHost). // Encode drops it below; the previews flag stays. ProtocolPreviewHost = Protocol11 // ProtocolMetered is the first protocol with metered connections // (connectors spec 2026-11-12, S1): API-key connections and their // facts in hello and sync, a usage row's cost, the probe's usage, and // the model, budget and resume_spend frames. Encode drops an API-key // connection and the cost fields below it, says a probe's usage as a // check, and refuses the new frames and an API-key connect: an older // runner is refused metered connections rather than downgraded. ProtocolMetered = Protocol12 // ProtocolResearch is the first protocol with the Research specialist // (spec 2026-11-12-equipo-research-specialist.md): the coordinator's // propose_specialist, and later slices' research dispatch, fetch // reports, file chunks and findings. Encode drops or refuses all of it // below (downgradeResearch); the runner answers the coordinator's // research tools itself on an older connection. ProtocolResearch = Protocol13 // ProtocolScheduler is the first protocol with the scheduler // (connectors spec 2026-11-12, S3): a dispatch's priority, deadline // and release, a held step's hold, the release and priority frames and // a preference's end. Below it Encode refuses the frames, a held // report and a preference with an end, and drops the dispatch fields: // an older runner has no leave to spend, so it is never handed one. ProtocolScheduler = Protocol14 // ProtocolReadings is the first protocol whose headroom says when it // was read (Headroom.CheckedAt, connectors spec rev 3.2 §6): the // Usage page and the hold line show each reading's age. Encode drops // it below (downgradeReadings); the runner's first hello never // carries it (WithoutReadingTimes). ProtocolReadings = Protocol15 // ProtocolPublish is the first protocol that publishes a merged // website (publish.go): the hello's sites capability, a publish // step's dispatch, check and result. Encode refuses the dispatch and // the check below it and drops the rest. ProtocolPublish = Protocol16 // ProtocolOpenCode is the first protocol with the OpenCode Go // provider behind the OpenCode harness (connectors spec §4.2, slice // S5). Below it Encode drops that provider's connections from hello // and sync and its usage rows from every report, and refuses a // connect or a connection report about one (downgradeOpenCode): an // older instance never sees a provider it cannot read, and an older // runner is never asked to connect one. ProtocolOpenCode = Protocol17 // ProtocolModels is the first protocol with a metered connection's // allowed set of models, each chosen per step (connectors spec rev // 3.3 §16, slice S5b): the models frame and prompt, each held // connection's applied set and model states, a usage row's family, // tier, tier version and model_mismatch, Review's dispatch naming // Engineering's family, and a question's model_unavailable. Below it // Encode refuses the models frame, says the models prompt as the old // one-model pick, drops the rest and says model_unavailable as // account_unavailable (downgradeModels): an older runner keeps its // one model and is refused any change to the set. ProtocolModels = Protocol18 // ProtocolAssistant is the first protocol with the Assistant's lane // (spec 2026-11-12-equipo-assistant-design.md): a message's and a // session's lane and a forget_task's keep_preview. Below it Encode // refuses an Assistant message, drops the Assistant's sessions from // sync and drops keep_preview (downgradeAssistant). ProtocolAssistant = Protocol19 // ProtocolUsageRefresh adds fetched readings and usage availability. ProtocolUsageRefresh = Protocol20 // ProtocolCopy adds the Copy specialist, a dispatch's avoided // families and a step's failure. Below it Encode refuses a Copy // dispatch or report and drops avoided families and failures. ProtocolCopy = Protocol21 // ProtocolJobs is the first protocol with job lanes (spec // 2026-11-13-assistant-jobs-design.md): a message's and a session's // lane may be a job's thread (JobLane). Below it Encode refuses a // job-lane message and drops job-lane sessions from sync // (downgradeJobs). ProtocolJobs = Protocol22 // ProtocolGlance adds the glance frame (runner to instance): the // Assistant's instant first line for a person turn. Below it Encode // refuses the frame, so it is not sent. ProtocolGlance = Protocol23 // ProtocolWarm adds the warm command (instance to runner): the // person opened Base, so their primary warms their Assistant now. // Below it Encode refuses the frame, so it is not sent. ProtocolWarm = Protocol24 // ProtocolPlacement adds durable notebook corrections for project moves. ProtocolPlacement = Protocol25 ProtocolAccess = Protocol26 ProtocolInjectionDefences = Protocol28 // ProtocolPinnedRelease is the first protocol whose Run now names the // connection the person was told it would use (paused work, // 2026-11-24): ReleaseCommand.Connection and a dispatch's // ReleaseConnection. The runner admits such a release only there. // Below it Encode refuses a pinned release frame and drops a pinned // dispatch's release with its pin: an older runner would honour the // leave anywhere, metered included, so it is never handed one. The // instance offers an older runner plain Run now, with no promise. ProtocolPinnedRelease = Protocol29 // ProtocolStuckTasks adds the coordinator's powers for stuck tasks // (stuck.go): a hello's tool health and the coordinator's offer_retry. // Below it Encode drops the tool health and refuses the tool's call // (downgradeStuck). ProtocolStuckTasks = Protocol30 // ProtocolChangeFiles adds bounded Engineering file-list facts. ProtocolChangeFiles = Protocol31 // ProtocolUnfinishedWork is the first protocol whose instance takes an // Engineering step done with the reason step_timeout as unfinished // work (stopped-jobs audit, 2026-11-25): it keeps the reason, tells // Review, and shows it. A runner keeps a timed-out step's work only // when the instance speaks it; below it the step fails step_timeout // as before (Encode, WithoutUnfinished). ProtocolUnfinishedWork = Protocol32 // ProtocolAssistantFiles is the first protocol whose Assistant turns // carry the person's files and the files they attached earlier in the // conversation (assistant attachments spec 2026-11-26, A6): a message's // attachments in the Assistant's lane, its earlier and earlier_more. // Below it Encode refuses an Assistant message with attachments and // drops earlier and earlier_more (downgradeAssistantFiles); the // Coordinator's and a job's frames are unchanged. ProtocolAssistantFiles = Protocol33 // ProtocolPlaces adds places (places.go): a hello's reach and carlos // health, a publish bound to its confirmed place in dispatch, check // and report, and the place tools. Below it Encode drops the hello's // fields and refuses a publish dispatch and the tools' calls // (downgradePlaces). ProtocolPlaces = Protocol34 // ProtocolChangeDiffs adds separate bounded display patches: a step // report's change_diffs and the change_diff_upload frame. Below it // Encode drops the report's diffs and refuses the upload. ProtocolChangeDiffs = Protocol35 // ProtocolLookup adds the lookups' two isolated model steps (spec // 2026-11-26-assistant-abilities §4.2): the live-only lookup_step and // lookup_result frames (lookup.go). Below it Encode refuses both. ProtocolLookup = Protocol36 // ProtocolMacEngineering adds Engineering on a Mac worker // (mac_engineering.go, spec §8): the prepare_base and base frames, // Engineering transfers, a dispatch's and a report's Xcode access, a // report's kept session and outcome, publication-bound change files // and diffs, a pinned question, a worker's Engineering status, F // probes and connections. It sits above ProtocolLookup, so a peer at // 36 has lookups but not Mac Engineering. Below it Encode refuses the // frames, the transfers and a publication's diffs and drops the fields // (downgradeMacEngineering). ProtocolMacEngineering = Protocol37 // ProtocolDesign adds the Design specialist (spec // 2026-11-28-dynamic-specialists.md, slice 1): a dispatch's specialist // binding (id, revision, project, profile, capabilities), the // page_render lease check, the render_file chunk, a step report's // options and render records, and propose_specialist's project. Below // it Encode refuses a bound dispatch, a render check, a render_file // chunk and a proposal for one project, and drops a report's options // and render records and a proposal's empty project (downgradeDesign). ProtocolDesign = Protocol38 ProtocolCurrent = ProtocolDesign ) // Runner roles. A person's first runner is the primary: the coordinator, // the forge credential, publication and merges live there. Later runners // are workers and run steps placed on them. const ( RolePrimary = "primary" RoleWorker = "worker" ) // Sandboxes a runner reports: how it confines a step. const ( SandboxBubblewrap = "bubblewrap" SandboxSeatbelt = "seatbelt" // SandboxNone is the test-build fake worker only: it runs checks in a // process group without a sandbox. SandboxNone = "none" // SandboxHosted is the instance's record that a checks verdict came // from the hub's hosted CI (release slice 1); runners never report it. SandboxHosted = "hosted" ) // Capability tags, a fixed set. A step's needs are a subset. const ( TagLinux = "linux" TagMacOS = "macos" TagXcode = "xcode" TagIOSSimulator = "ios_simulator" TagClaude = "claude" TagCodex = "codex" TagGo = "go" ) // Tags is the whole tag set. var Tags = []string{TagLinux, TagMacOS, TagXcode, TagIOSSimulator, TagClaude, TagCodex, TagGo} // Capability bounds. const ( MaxSimulators = 40 MaxCapabilityString = 300 // MaxHoldingItems bounds Capabilities.HoldingItems. MaxHoldingItems = 8 MaxCapabilityBytes = 8 << 10 ) // Platform is a runner's operating system and architecture, as Go names // them (linux/amd64, darwin/arm64). type Platform struct { OS string `json:"os"` Arch string `json:"arch"` } // Capabilities is what a runner can do, computed at start, re-probed // hourly and sent with every heartbeat. No path, credential or raw tool // output: ValidCapabilities checks every field. type Capabilities struct { Xcode Xcode `json:"xcode"` Simulators []Simulator `json:"simulators"` Toolchains Toolchains `json:"toolchains"` Harness Harness `json:"harness"` Tags []string `json:"tags"` // Probes are a Mac worker's self-probes (P1 to P7), run after // enrolment and on demand; absent on Linux. Probes []Probe `json:"probes,omitempty"` // Tainted: a check has run outside the sandbox on this runner, so it // never labels one sandboxed again (a Mac worker; sticky). Tainted bool `json:"tainted,omitempty"` // Previews: this runner loaded a preview credential, so it can // publish previews (ProtocolExplore; a primary at it without this has // previews off). Previews bool `json:"previews,omitempty"` // PreviewHost (ProtocolPreviewHost) is the CARLOS preview host the // runner is paired with; only with Previews. PreviewHost *PreviewHost `json:"preview_host,omitempty"` // Research (ProtocolResearch) is what the primary detected for the // Research site inventory: its interfaces' global addresses. Withheld // until the welcome says 13, like Previews. Research *ResearchCapability `json:"research,omitempty"` // Sites (ProtocolPublish): this runner is paired with a site host and // can publish a merged website. Withheld until the welcome says 16. Sites bool `json:"sites,omitempty"` // Tools (ProtocolStuckTasks): whether the runner's pinned tools are // installed and match their pins. Withheld until the welcome says 30. Tools *ToolHealth `json:"tools,omitempty"` // Reach (ProtocolPlaces): the CARLOS logins and deploy keys this // runner holds, no secret. Withheld until the welcome says 31. Reach *Reach `json:"reach,omitempty"` // Engineering (ProtocolMacEngineering): a Mac worker's word on // whether it can take Engineering. Withheld until the welcome says 37, // with the F probes (WithoutMacEngineering). Engineering *EngineeringStatus `json:"engineering,omitempty"` // Unproven (ProtocolMacEngineering) is a code for an attempt whose // end this runner can never prove (UnprovenRecordIncomplete). Unproven string `json:"unproven,omitempty"` // UnprovenCount is how many processes keep it so // (UnprovenProcessesLeft only); never names, pids or paths. UnprovenCount int `json:"unproven_count,omitempty"` // ModelHold (ProtocolMacEngineering): a Mac worker holds, or may // hold, a model credential: an attempt connecting, a connection's // files, a Keychain item a launch left, or a launch not yet proven // ended (spec §8.3 (4), D1). HoldingItems names the Keychain items // (their services) that hold it, at most MaxHoldingItems. ModelHold bool `json:"model_hold,omitempty"` HoldingItems []string `json:"holding_items,omitempty"` // RunnerUser (ProtocolMacEngineering) is a Mac worker's runner user, // its short name, so the Machines page can say as whom to change a // folder (ValidRunnerUser). RunnerUser string `json:"runner_user,omitempty"` } // UnprovenRecordIncomplete: an attempt's turn record was not complete // (its final write failed, or the runner stopped first), so its end is // never proven. const UnprovenRecordIncomplete = "record_incomplete" // UnprovenCredential: a Mac could not prove that an earlier launch that // had a model credential (a sign-in, a token check) ended, so it keeps // its Claude connections closed until it restarts. const UnprovenCredential = "credential_unproven" // MaxUnprovenCount bounds UnprovenCount. const MaxUnprovenCount = 100000 // UnprovenProcessesLeft: an idle read found UnprovenCount processes of // the runner user that no record accounts for; a restart clears it. const UnprovenProcessesLeft = "processes_left" // PreviewHost is a preview host a runner pairs with: its kind (an // adapter: CARLOS devbox on the tailnet, or Carloku temporary sites) and // the domain its links live under, "" until known. type PreviewHost struct { Kind string `json:"kind"` Domain string `json:"domain,omitempty"` } // Preview host kinds. const ( PreviewHostDevbox = "devbox" PreviewHostCarlokuTemp = "carloku-temp" ) var previewHostDomain = regexp.MustCompile(`^[a-z0-9-]+(\.[a-z0-9-]+)+$`) // Probe is one self-probe's result: its ID (P1 to P7, or F1 to F7 at // ProtocolMacEngineering), a verdict and a // short detail in the capability string rules (no path, one line). type Probe struct { ID string `json:"id"` Verdict string `json:"verdict"` Detail string `json:"detail"` } // ProbeDetailTurnBusy is a probe's detail when the probe run could not // take the Mac's turn: a code, which the instance words (copy.go). const ProbeDetailTurnBusy = "turn_busy" // Probe verdicts. ProbeDenied is P2's pass: every hostile attempt was // denied, so checks run in the sandbox; anything else and they run // outside it, labelled so (Paul's ruling 2). const ( ProbePassed = "passed" ProbeDenied = "denied" ProbeFailed = "failed" ProbeSkipped = "skipped" ProbeUnavailable = "unavailable" ) // ProbeIDs are the Mac probes of the spec, in order. var ProbeIDs = []string{"P1", "P2", "P3", "P4", "P5", "P6", "P7"} var probeVerdicts = []string{ProbePassed, ProbeDenied, ProbeFailed, ProbeSkipped, ProbeUnavailable} // Xcode is xcodebuild -version's two lines; empty on Linux. type Xcode struct { Version string `json:"version"` Build string `json:"build"` } // Simulator is one available simulator device. type Simulator struct { Name string `json:"name"` Runtime string `json:"runtime"` UDID string `json:"udid"` State string `json:"state"` } // Toolchains are versions, "" when absent. type Toolchains struct { Go string `json:"go"` Swift string `json:"swift"` Node string `json:"node"` } // Harness are the coding harnesses' versions, "" when absent. type Harness struct { Claude string `json:"claude"` Codex string `json:"codex"` SRT string `json:"srt"` } // ErrCapabilities refuses a capability report out of bounds. var ErrCapabilities = errors.New("wire: capability report out of bounds") // ValidCapabilities checks the bounds and that no string could be a path, // a credential or tool output: short, one line, no path separator. func ValidCapabilities(c Capabilities) error { if len(c.Simulators) > MaxSimulators { return ErrCapabilities } for _, t := range c.Tags { if !slices.Contains(Tags, t) { return ErrCapabilities } } seen := map[string]bool{} for _, p := range c.Probes { if seen[p.ID] || !validProbeVerdict(p.ID, p.Verdict) { return ErrCapabilities } seen[p.ID] = true } if h := c.PreviewHost; h != nil && (!c.Previews || h.Kind != PreviewHostDevbox && h.Kind != PreviewHostCarlokuTemp || h.Domain != "" && (len(h.Domain) > 253 || !previewHostDomain.MatchString(h.Domain))) { return ErrCapabilities } if h := c.Tools; h != nil && !validToolHealth(*h) || c.Unproven != "" && c.Unproven != UnprovenRecordIncomplete && c.Unproven != UnprovenCredential && c.Unproven != UnprovenProcessesLeft || (c.UnprovenCount != 0) != (c.Unproven == UnprovenProcessesLeft) || c.UnprovenCount < 0 || c.UnprovenCount > MaxUnprovenCount { return ErrCapabilities } if r := c.Reach; r != nil && !validReach(*r) { return ErrCapabilities } if e := c.Engineering; e != nil && !validEngineeringStatus(*e) { return ErrCapabilities } if len(c.HoldingItems) > MaxHoldingItems || c.RunnerUser != "" && !ValidRunnerUser(c.RunnerUser) { return ErrCapabilities } if err := checkStrings(reflect.ValueOf(c)); err != nil { return err } raw, _ := json.Marshal(c) if len(raw) > MaxCapabilityBytes { return ErrCapabilities } return nil } func checkStrings(v reflect.Value) error { switch v.Kind() { case reflect.String: s := v.String() if len(s) > MaxCapabilityString || strings.ContainsAny(s, "/\\~\n\r\t\x00=") { return ErrCapabilities } case reflect.Bool: case reflect.Int: // A count (UnprovenCount): bounded, never negative. if v.Int() < 0 || v.Int() > MaxUnprovenCount { return ErrCapabilities } case reflect.Pointer: if !v.IsNil() { return checkStrings(v.Elem()) } case reflect.Struct: for i := range v.NumField() { if err := checkStrings(v.Field(i)); err != nil { return err } } case reflect.Slice: for i := range v.Len() { if err := checkStrings(v.Index(i)); err != nil { return err } } default: return ErrCapabilities } return nil } // Covers reports whether tags include every need. func Covers(tags, needs []string) bool { for _, n := range needs { if !slices.Contains(tags, n) { return false } } return true } // Placement of a step: "" placed on its runner; waiting_runner while the // only runners that fit are offline; waiting_sandbox while the only Macs // online that fit have not proven their sandbox (probe P2) or are // tainted, and nobody chose to run the checks outside it; waiting_mac // while Mac work (checks that need macOS, Engineering for a repository // whose gate needs Xcode) has no enrolled runner that fits, so it waits // for one rather than run on a Linux primary; waiting_mac_engineering // while the only runners that fit Mac Engineering are Mac workers, which // do not take Engineering yet. const ( PlacementWaiting = "waiting_runner" PlacementSandbox = "waiting_sandbox" PlacementMac = "waiting_mac" PlacementMacEngineering = "waiting_mac_engineering" ) // Publication of a worker's Engineering candidate: only the primary // publishes (pushes) it. const ( PublicationNone = "none" PublicationPending = "pending" PublicationPublished = "published" PublicationFailed = "failed" ) // Termination kinds: how a step attempt's end was proven. const ( TerminationNamespace = "namespace" TerminationProcessGroup = "process_group" // TerminationUnverified: settled by the creator's Recover after the // machine was removed; nothing proved the end. TerminationUnverified = "unverified" ) // Transfer directions: inbound (primary to worker) carries the candidate // a worker judges; outbound (worker to primary) carries a worker's commit. const ( TransferInbound = "inbound" TransferOutbound = "outbound" ) // Transfer bounds: a chunk's data is base64 under 192 KB so a frame stays // under MaxFrameBytes; a transfer is at most 64 MB. const ( MaxBlobData = 192 << 10 MaxBlobChunk = MaxBlobData / 4 * 3 MaxTransferBytes = 64 << 20 TransferTTL = 24 * time.Hour // MaxTransferChunks is the most chunks a transfer within the bound // has. A sender declares a pack too large to relay by a total past it, // and the receiver refuses such a transfer at its first chunk. MaxTransferChunks = (MaxTransferBytes + MaxBlobChunk - 1) / MaxBlobChunk ) // Protocol 2 frames. const ( // FrameBlob is one chunk of a transfer, both ways, durable. FrameBlob = "blob" // FrameSendPack asks the primary to upload an inbound transfer's pack. FrameSendPack = "send_pack" // FramePublish asks the primary to publish a worker's commit; // FramePublished is its answer. Both durable. FramePublish = "publish" FramePublished = "published" // FrameRefused answers a lease the instance will not grant (the start // authorization of a withdrawn or superseded attempt). Not durable. FrameRefused = "refused" // FrameResearchFile (runner to instance, durable, protocol 13) carries // one chunk of an image a Research step kept. FrameResearchFile = "research_file" // FrameRenderFile (runner to instance, durable, ProtocolDesign) // carries one chunk of a capture a Design step named in its options. FrameRenderFile = "render_file" ) // TransferHeader binds a transfer to one attempt of one step. The // receiver checks it against its own step row before index-pack. type TransferHeader struct { ID string `json:"id"` Direction string `json:"direction"` Repo string `json:"repo"` TaskID string `json:"task_id"` StepID string `json:"step_id"` Attempt int64 `json:"attempt"` BaseSHA string `json:"base_sha"` CandidateSHA string `json:"candidate_sha"` // Protocol 37: Kind is "" (checks, or a worker's outbound commit) or // TransferKindEngineering; an Engineering rebase round also names the // base the candidate was made on (OldBaseSHA). Commits and Valid. Kind string `json:"kind,omitempty"` OldBaseSHA string `json:"old_base_sha,omitempty"` } // Blob is one chunk of a transfer's pack: Index of Total, SHA256 of the // whole pack (hex), Data base64. type Blob struct { Transfer TransferHeader `json:"transfer"` Index int `json:"index"` Total int `json:"total"` SHA256 string `json:"sha256"` Data string `json:"data"` } // SendPackCommand asks the primary for the pack of CandidateSHA, which // it uploads as the transfer's blobs (Have: commits the receiver holds). type SendPackCommand struct { Transfer TransferHeader `json:"transfer"` Have []string `json:"have"` } // PublishCommand asks the primary to push a worker's commit, received in // Transfer, onto the task branch. type PublishCommand struct { Publication string `json:"publication"` TaskID string `json:"task_id"` StepID string `json:"step_id"` Attempt int64 `json:"attempt"` Repo string `json:"repo"` Branch string `json:"branch"` Person string `json:"person"` BaseSHA string `json:"base_sha"` CandidateSHA string `json:"candidate_sha"` Transfer string `json:"transfer"` // OutcomePhase (protocol 37) is the worker's outcome, which the // primary echoes in published. OutcomePhase string `json:"outcome_phase,omitempty"` } // PublishedReport is the primary's answer to a publish: Pushed, or the // reason it was not (push_failed, push_conflict, candidate_unavailable, // cancelled). // A successful push may carry proposal_failed as a diagnostic only. type PublishedReport struct { Publication string `json:"publication"` TaskID string `json:"task_id"` StepID string `json:"step_id"` Attempt int64 `json:"attempt"` CandidateSHA string `json:"candidate_sha"` Pushed bool `json:"pushed"` Reason string `json:"reason"` // Protocol 37: the change files and display diffs the primary computed // for the pushed candidate (the diffs travel as change_diff uploads // naming this publication), and the publish command's OutcomePhase. ChangeFiles *ChangeFiles `json:"change_files,omitempty"` DiffCollection string `json:"diff_collection,omitempty"` OutcomePhase string `json:"outcome_phase,omitempty"` } // Refused answers a lease frame (ID) the instance would not grant. type Refused struct { ID string `json:"id"` Reason string `json:"reason"` } // protocol2Only are the frame types a protocol 1 runner never receives // or sends. var protocol2Only = map[string]bool{FrameBlob: true, FrameSendPack: true, FramePublish: true, FramePublished: true, FrameRefused: true} // RunnerProtocolPath answers the runner protocol this instance speaks, so // a worker can refuse to enrol with an instance that has no workers. const RunnerProtocolPath = "/api/runner/protocol" // RunnerProtocol is GET RunnerProtocolPath. type RunnerProtocol struct { Protocol int `json:"protocol"` } // Speaks reports whether a frame type exists at protocol. func Speaks(protocol int, kind string) bool { if kind == FrameRequestAccess || kind == FrameAccess { return protocol >= ProtocolAccess } if macEngineeringOnly[kind] { return protocol >= ProtocolMacEngineering } return protocol >= Protocol2 || !protocol2Only[kind] } // ErrProtocol means a frame cannot be spoken at the connection's protocol. var ErrProtocol = errors.New("wire: frame not in this protocol") // Encode returns f as the given protocol speaks it. Below ProtocolJobs // a job-lane message is refused and job-lane sessions dropped from sync // (downgradeJobs); below ProtocolUsageRefresh the fetched readings and // usage availability are dropped (downgradeUsageRefresh); below // ProtocolAssistant an Assistant message is refused and the lane fields // dropped (downgradeAssistant); below ProtocolModels the models frame is // refused and the per-step model fields dropped (downgradeModels); below // ProtocolOpenCode the OpenCode Go connections and usage are dropped and // a connect or connection report about one refused (downgradeOpenCode); // below ProtocolPublish a publish dispatch and check are refused and the // publish fields dropped (downgradePublish); below ProtocolReadings a // headroom's reading time is dropped; below ProtocolScheduler the // scheduler's frames are refused and its fields dropped; below // ProtocolResearch the Research frames and fields are refused or dropped // (downgradeResearch); below ProtocolMetered the metered frames, an // API-key connect and a metered report are refused and the metered // fields dropped (downgradeMetered); below ProtocolPreviewHost a hello's // preview host is dropped; below ProtocolExplore the explore fields; // below ProtocolPreview the preview fields are dropped and a preview dispatch // is refused (ErrProtocol); below ProtocolEmptyMerge the unborn-default // refusal is merge_failed too; below ProtocolSandboxConsent the sandbox // consent and refusal are dropped; // below ProtocolEmptyRepos a hello's empty repositories are dropped; below // ProtocolHostedChecks the hosted checks fields too; below // ProtocolMergeFacts the merge authority fields too; below // ProtocolSpend the spend fields too; at protocol 1 it is exactly the // slice 4 frame and field set: protocol 2 fields are dropped and a // protocol 2 frame type is refused (ErrProtocol). // // Below ProtocolGlance a glance frame is refused, and below ProtocolWarm // a warm command. Below ProtocolAssistantFiles an Assistant message with // attachments is refused and a message's earlier files are dropped // (downgradeAssistantFiles); below ProtocolPlaces the places fields are // dropped and their frames refused (downgradePlaces); below // ProtocolChangeDiffs a change_diff upload is refused and a step report's // change_diffs dropped; below ProtocolLookup the lookup frames are refused. // Below ProtocolMacEngineering the prepare_base and base frames, an // Engineering transfer and a publication's diff upload are refused and // slice F's fields dropped (downgradeMacEngineering). Below ProtocolDesign // a bound dispatch, a render check, a render_file chunk and a proposal // for one project are refused and a report's options and render records // dropped (downgradeDesign). func Encode(f Frame, protocol int) (Frame, error) { if protocol >= ProtocolCurrent { return f, nil } if !Speaks(protocol, f.Type) { return Frame{}, fmt.Errorf("%w: %s at protocol %d", ErrProtocol, f.Type, protocol) } body, err := f.Decode() if err != nil { return Frame{}, err } if protocol < ProtocolGlance && f.Type == FrameGlance || protocol < ProtocolWarm && f.Type == FrameWarm { return Frame{}, fmt.Errorf("%w: %s at protocol %d", ErrProtocol, f.Type, protocol) } if v, ok := body.(*ToolCall); ok && protocol < ProtocolAccess && v.Name == ToolRequestAccess { return Frame{}, ErrProtocol } if v, ok := body.(*LeaseCheck); ok && v.AccessCard != "" && protocol < ProtocolAccess { return Frame{}, ErrProtocol } if protocol < ProtocolLookup && (f.Type == FrameLookupStep || f.Type == FrameLookupResult) { return Frame{}, fmt.Errorf("%w: %s at protocol %d", ErrProtocol, f.Type, protocol) } changed := false if protocol < ProtocolDesign { dropped, err := downgradeDesign(body, protocol) if err != nil { return Frame{}, err } changed = dropped } if protocol < ProtocolMacEngineering { dropped, err := downgradeMacEngineering(body, protocol) if err != nil { return Frame{}, err } changed = changed || dropped } if protocol < ProtocolChangeDiffs { switch v := body.(type) { case *ChangeDiffUpload: return Frame{}, ErrProtocol case *StepReport: if v.ChangeDiffs != "" { v.ChangeDiffs = "" changed = true } } } if protocol < ProtocolPlaces { dropped, err := downgradePlaces(body, protocol) if err != nil { return Frame{}, err } changed = changed || dropped } if protocol < ProtocolAssistantFiles { dropped, err := downgradeAssistantFiles(body, protocol) if err != nil { return Frame{}, err } changed = changed || dropped } if protocol < ProtocolStuckTasks { dropped, err := downgradeStuck(body, protocol) if err != nil { return Frame{}, err } changed = changed || dropped } if protocol < ProtocolUnfinishedWork { if v, ok := body.(*StepReport); ok && WithoutUnfinished(v) { changed = true } } if protocol < ProtocolChangeFiles { if v, ok := body.(*StepReport); ok && v.ChangeFiles != nil { v.ChangeFiles = nil changed = true } } if protocol < ProtocolPinnedRelease { if v, ok := body.(*ReleaseCommand); ok && v.Connection != "" { return Frame{}, fmt.Errorf("%w: a pinned release at protocol %d", ErrProtocol, protocol) } if d, ok := body.(*DispatchCommand); ok && d.ReleaseConnection != "" { d.Release, d.ReleaseConnection = "", "" changed = true } } if protocol < ProtocolInjectionDefences { // Older runners consume fix-round context from Brief, including runners // that predate the separate Feedback field. Protocol 28 keeps sources apart. if d, ok := body.(*DispatchCommand); ok && d.Feedback != "" && !strings.HasSuffix(d.Brief, d.Feedback) { d.Brief = strings.TrimSpace(d.Brief + "\n\n" + d.Feedback) if len(d.Brief) > MaxTaskBrief+4000 { d.Brief = strings.ToValidUTF8(d.Brief[:MaxTaskBrief+4000], "") } changed = true } if d, ok := body.(*DispatchCommand); ok && d.PreviewUnsafeDigest != "" { return Frame{}, ErrProtocol } if d, ok := body.(*DispatchCommand); ok && len(d.PersonWords) > 0 { d.PersonWords = nil changed = true } if r, ok := body.(*StepReport); ok { if r.BaseChecks != "" { r.BaseChecks = "" changed = true } if r.Reason == "base_checks_failed" { r.Reason = "" changed = true } if r.BaseChecksSHA != "" { r.BaseChecksSHA = "" changed = true } if r.Change != nil && (r.Change.GateFilesChanged || r.Change.ReviewTruncated) { r.Change.GateFilesChanged = false r.Change.ReviewTruncated = false changed = true } } } if protocol < ProtocolPlacement { if v, ok := body.(*MessageCommand); ok && len(v.PlacementNotes) > 0 { v.PlacementNotes = nil changed = true } } if protocol < ProtocolJobs { dropped, err := downgradeJobs(body, protocol) if err != nil { return Frame{}, err } changed = dropped || changed } if protocol < ProtocolCopy { switch v := body.(type) { case *DispatchCommand: if v.Specialist == SpecialistCopy || v.Copy != nil { return Frame{}, ErrProtocol } if len(v.AvoidFamilies) > 0 { v.AvoidFamilies = nil changed = true } case *StepReport: if v.Copy != nil { return Frame{}, ErrProtocol } if v.Failure != nil { v.Failure = nil changed = true } } } if protocol < ProtocolUsageRefresh { changed = downgradeUsageRefresh(body) || changed } if protocol < ProtocolAssistant { dropped, err := downgradeAssistant(body, protocol) if err != nil { return Frame{}, err } changed = dropped || changed } if protocol < ProtocolModels { dropped, err := downgradeModels(body, protocol) if err != nil { return Frame{}, err } changed = dropped || changed } if protocol < ProtocolOpenCode { dropped, err := downgradeOpenCode(body, protocol) if err != nil { return Frame{}, err } changed = dropped || changed } if protocol < ProtocolPublish { dropped, err := downgradePublish(body, protocol) if err != nil { return Frame{}, err } changed = dropped || changed } if protocol < ProtocolReadings { changed = downgradeReadings(body) || changed } if protocol < ProtocolScheduler { if schedulerOnly[f.Type] { return Frame{}, fmt.Errorf("%w: %s at protocol %d", ErrProtocol, f.Type, protocol) } if r, ok := body.(*StepReport); ok && r.Hold != nil { return Frame{}, fmt.Errorf("%w: a held step at protocol %d", ErrProtocol, protocol) } if p, ok := body.(*PreferenceCommand); ok && p.Until != nil { return Frame{}, fmt.Errorf("%w: a preference with an end at protocol %d", ErrProtocol, protocol) } changed = downgradeScheduler(body) || changed } if protocol < ProtocolResearch { dropped, err := downgradeResearch(body, protocol) if err != nil { return Frame{}, err } changed = dropped || changed } if protocol < ProtocolMetered { if meteredOnly[f.Type] { return Frame{}, fmt.Errorf("%w: %s at protocol %d", ErrProtocol, f.Type, protocol) } if c, ok := body.(*ConnectCommand); ok && c.Kind == KindAPIKey { return Frame{}, fmt.Errorf("%w: an API-key connection at protocol %d", ErrProtocol, protocol) } if meteredReport(body) { return Frame{}, fmt.Errorf("%w: a metered report at protocol %d", ErrProtocol, protocol) } changed = downgradeMetered(body) || changed } if h, ok := body.(*Hello); ok && protocol < ProtocolPreviewHost { changed = WithoutPreviewHost(h) || changed } if protocol < ProtocolExplore { changed = downgradeExplore(body) || changed } if protocol < ProtocolPreview { if d, ok := body.(*DispatchCommand); ok && d.Specialist == SpecialistPreview { return Frame{}, fmt.Errorf("%w: a preview step at protocol %d", ErrProtocol, protocol) } changed = downgradePreview(body) || changed } if r, ok := body.(*StepReport); ok && protocol < ProtocolEmptyMerge && r.Reason == ReasonMergeUnbornDefault { r.Reason, changed = "merge_failed", true } if protocol < ProtocolSandboxConsent { changed = downgradeSandboxConsent(body) || changed } if h, ok := body.(*Hello); ok && protocol < ProtocolEmptyRepos { changed = WithoutEmptyRepos(h) || changed } if protocol < ProtocolHostedChecks { changed = downgradeHostedChecks(body) || changed } if protocol < ProtocolMergeFacts { changed = downgradeMergeFacts(body) || changed } if protocol < ProtocolSpend { changed = downgradeSpend(body) || changed } if protocol < Protocol2 { changed = downgrade(body) || changed } if !changed { return f, nil } raw, err := json.Marshal(body) if err != nil { return Frame{}, err } f.Data = raw return f, nil } // meteredReport says a report only a metered connection makes, which an // older instance has no words for: an API-key attempt's report (its // provider, its key or model card, its refusal reasons) and a question // held by the metered guard (queued, or ended, with a hold reason). It // is refused below ProtocolMetered, never translated. func meteredReport(body any) bool { switch v := body.(type) { case *ConnectionReport: _, apiKey := APIKeyProviders[v.Provider] prompt := v.Prompt != nil && (v.Prompt.Kind == PromptAPIKey || v.Prompt.Kind == PromptModel || v.Prompt.Models != nil) return apiKey || prompt || v.Reason == "key_refused" || v.Reason == "no_priced_model" case *AnswerReport: return v.State == QuestionQueued || v.Reason == HoldBusy || v.Reason == HoldBudget || v.Reason == HoldSpendUnknown } return false } // downgradeOpenCode takes the OpenCode Go provider out of what a peer // below ProtocolOpenCode is sent (in new values; the caller's are // untouched): its held connections and its usage rows go, and a connect // or a connection report about it is refused. It reports whether // anything changed. func downgradeOpenCode(body any, protocol int) (bool, error) { held := func(cs *[]HeldConnection) bool { gone := func(h HeldConnection) bool { return openCodeOnly(h.Provider) || h.Harness == HarnessOpenCode } if !slices.ContainsFunc(*cs, gone) { return false } *cs = slices.DeleteFunc(slices.Clone(*cs), gone) return true } rows := func(us *[]Usage) bool { gone := func(u Usage) bool { return openCodeOnly(u.Provider) } if !slices.ContainsFunc(*us, gone) { return false } *us = slices.DeleteFunc(slices.Clone(*us), gone) return true } switch v := body.(type) { case *Hello: return held(&v.Connections), nil case *Sync: return held(&v.Connections), nil case *ConnectCommand: if openCodeOnly(v.Provider) { return false, fmt.Errorf("%w: an OpenCode Go connection at protocol %d", ErrProtocol, protocol) } case *ConnectionReport: if openCodeOnly(v.Provider) { return false, fmt.Errorf("%w: an OpenCode Go report at protocol %d", ErrProtocol, protocol) } case *UsageReport: return rows(&v.Rows), nil case *StepReport: return rows(&v.Usage), nil case *AnswerReport: return rows(&v.Usage), nil case *Reply: return rows(&v.Usage), nil } return false, nil } // schedulerOnly are the frame types below ProtocolScheduler never carries. var schedulerOnly = map[string]bool{FrameRelease: true, FramePriority: true} // downgradeScheduler clears a dispatch's scheduler fields (an older // runner runs every step as before and never spends). It reports whether // anything changed. func downgradeScheduler(body any) bool { switch v := body.(type) { case *DispatchCommand: set := v.Priority != "" || v.By != nil || v.Release != "" || v.PriorityRevision != 0 || v.Housekeeping v.Priority, v.By, v.Release, v.PriorityRevision, v.Housekeeping = "", nil, "", 0, false return set case *ToolCall: // record_task's and start_task's priority and deadline: an older // instance decodes their arguments strictly. if v.Name != ToolRecordTask && v.Name != ToolStartTask { return false } var args map[string]json.RawMessage if json.Unmarshal(v.Args, &args) != nil { return false } _, p := args["priority"] _, b := args["by"] if !p && !b { return false } delete(args, "priority") delete(args, "by") raw, err := json.Marshal(args) if err != nil { return false } v.Args = raw return true } return false } // meteredOnly are the frame types below ProtocolMetered never carries. var meteredOnly = map[string]bool{FrameModel: true, FrameBudget: true, FrameResumeSpend: true} // downgradeMetered clears a body's ProtocolMetered fields: API-key // connections leave hello and sync (an older instance knows none), a // usage row's cost goes, and a probe's usage is said as a check. It // reports whether anything changed. func downgradeMetered(body any) bool { held := func(cs *[]HeldConnection) bool { if !slices.ContainsFunc(*cs, func(h HeldConnection) bool { return h.Kind == KindAPIKey || h.Billing != "" }) { return false } *cs = slices.DeleteFunc(slices.Clone(*cs), func(h HeldConnection) bool { return h.Kind == KindAPIKey || h.Billing != "" }) return true } cost := func(rows []Usage) bool { set := false for i := range rows { u := &rows[i] set = set || u.CostMicros != nil || u.Currency != "" || u.PriceVersion != "" || u.CostReportedMicros != nil u.CostMicros, u.Currency, u.PriceVersion, u.CostReportedMicros = nil, "", "", nil } return set } switch v := body.(type) { case *Hello: return held(&v.Connections) case *Sync: return held(&v.Connections) case *ConnectCommand: set := v.Billing != "" || v.Budget != nil v.Billing, v.Budget = "", nil return set case *UsageReport: set := cost(v.Rows) if v.ProbeID != "" { v.CheckID, v.ProbeID, set = v.ProbeID, "", true } return set case *StepReport: return cost(v.Usage) case *AnswerReport: return cost(v.Usage) case *Reply: return cost(v.Usage) } return false } // downgradeSandboxConsent clears a dispatch's consent to run outside the // sandbox (an older peer never carries one), and says a worker's refusal // to run unproven as placement_refused, which an older instance knows: // it places the step elsewhere, never counts a failure and never taints. func downgradeSandboxConsent(body any) bool { switch v := body.(type) { case *DispatchCommand: set := v.Unsandboxed v.Unsandboxed = false return set case *StepReport: if v.Reason != ReasonSandboxUnproven { return false } v.Reason = "placement_refused" return true } return false } // downgradePreview clears a body's ProtocolPreview fields (omitempty). It // reports whether the body had any. func downgradePreview(body any) bool { switch v := body.(type) { case *StepReport: set := v.HasPreview || v.Preview != nil v.HasPreview, v.Preview = false, nil return set case *LeaseCheck: set := v.Digest != "" v.Digest = "" return set } return false } // downgradeHostedChecks clears a body's ProtocolHostedChecks fields // (omitempty). It reports whether the body had any. func downgradeHostedChecks(body any) bool { switch v := body.(type) { case *DispatchCommand: set := v.HostedChecks v.HostedChecks = false return set case *StepReport: // A hosted verdict means nothing without its binding: an older // instance gets checks that could not run, never a bare pass. if v.Hosted == nil && v.Gate != GateHosted { return false } v.Hosted, v.Gate, v.ExitCode = nil, "", nil if v.Checks != "" { v.Checks, v.Reason = ChecksCannotRun, "checks_unavailable" } return true } return false } // downgradeMergeFacts clears a body's ProtocolMergeFacts fields (all // omitempty). It reports whether the body has any. func downgradeMergeFacts(body any) bool { switch v := body.(type) { case *DispatchCommand: set := v.RevertSHA != "" v.RevertSHA = "" return set case *LeaseCheck: set := v.Purpose != "" v.Purpose = "" return set case *StepReport: set := v.Change != nil || v.MergeSource != "" || v.MergeParents != nil v.Change, v.MergeSource, v.MergeParents = nil, "", nil return set } return false } // downgradeSpend clears a body's ProtocolSpend fields (omitempty, so // absent once zero). It reports whether any was set. func downgradeSpend(body any) bool { turns := func(rows []Usage) bool { set := false for i := range rows { set = set || rows[i].Turns != nil rows[i].Turns = nil } return set } switch v := body.(type) { case *DispatchCommand: set := v.Feedback != "" v.Feedback = "" return set case *StepReport: return turns(v.Usage) case *AnswerReport: return turns(v.Usage) case *Reply: return turns(v.Usage) case *UsageReport: return turns(v.Rows) } return false } // downgrade clears a body's protocol 2 fields (all omitempty, so they // are absent once zero). It reports whether the body has any. func downgrade(body any) bool { switch v := body.(type) { case *Hello: v.Protocol, v.Platform, v.Label, v.Sandbox, v.Capabilities, v.SealKey = 0, nil, "", "", nil, "" for i := range v.Connections { v.Connections[i].ExpiresAt, v.Connections[i].ExpiresEstimated = nil, false } for i := range v.Catalog { v.Catalog[i].NeedsMacOS, v.Catalog[i].Simulator = false, false } case *Welcome: v.Protocol, v.Role, v.Release, v.Tainted = 0, "", "", false case *DispatchCommand: v.Needs, v.RunnerID = nil, "" case *LeaseCheck: v.StepID, v.Attempt, v.Publication = "", 0, "" case *StepReport: v.TerminationKind, v.Have, v.Phase, v.Apple, v.ChecksSandbox = "", nil, "", false, "" default: return false } return true } // HelloProtocol is the protocol a hello speaks: absent means 1. func HelloProtocol(h Hello) int { if h.Protocol <= Protocol1 { return Protocol1 } return h.Protocol } // Spoken is the protocol both ends speak: the lower of the runner's and // this build's. func Spoken(runner int) int { return max(Protocol1, min(runner, ProtocolCurrent)) } // WithoutEmptyRepos drops a hello's empty repositories from its catalog // (in a new slice, so the caller's catalog is untouched). The runner's // first hello on a connection is sent before the instance says which // protocol it speaks, and an older instance's strict decoder would refuse // it; the runner sends them once the welcome says protocol 6. It reports // whether any was dropped. func WithoutEmptyRepos(h *Hello) bool { if !slices.ContainsFunc(h.Catalog, func(e RepoInfo) bool { return e.Empty }) { return false } h.Catalog = slices.DeleteFunc(slices.Clone(h.Catalog), func(e RepoInfo) bool { return e.Empty }) return true }