| 1 | package wire |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "errors" |
| 6 | "fmt" |
| 7 | "reflect" |
| 8 | "regexp" |
| 9 | "slices" |
| 10 | "strings" |
| 11 | "time" |
| 12 | ) |
| 13 | |
| 14 | // Runner stream protocols. 1 is the slice 4 wire: a hello without |
| 15 | // protocol. 2 adds roles, capabilities, placement, the attempt-specific |
| 16 | // start authorization, pack transfers and publication (Mac runners spec |
| 17 | // §3.3). 3 adds a fix round's Feedback (DispatchCommand) and a usage |
| 18 | // row's Turns (ProtocolSpend). 4 adds what merge authority needs (spec |
| 19 | // 2026-11-11, ProtocolMergeFacts): the review's change facts, the merge's |
| 20 | // provenance, the merge request's own confirmation naming the attempt, |
| 21 | // and a revert's target. 7 adds the person's choice to run a Mac's |
| 22 | // checks outside the sandbox (ProtocolSandboxConsent). 8 adds the |
| 23 | // merge step's refusal for an unborn default branch (ProtocolEmptyMerge) |
| 24 | // and 9 adds preview steps (ProtocolPreview). Code asks for a capability |
| 25 | // by name, never by number. Each end speaks the lower of the two on |
| 26 | // each connection and encodes every frame for it with Encode; nothing an |
| 27 | // older peer does not know ever reaches it. |
| 28 | const ( |
| 29 | Protocol1 = 1 |
| 30 | Protocol2 = 2 |
| 31 | Protocol3 = 3 |
| 32 | Protocol4 = 4 |
| 33 | Protocol5 = 5 |
| 34 | Protocol6 = 6 |
| 35 | Protocol7 = 7 |
| 36 | Protocol8 = 8 |
| 37 | Protocol9 = 9 |
| 38 | Protocol10 = 10 |
| 39 | Protocol11 = 11 |
| 40 | Protocol12 = 12 |
| 41 | Protocol13 = 13 |
| 42 | Protocol14 = 14 |
| 43 | Protocol15 = 15 |
| 44 | Protocol16 = 16 |
| 45 | Protocol17 = 17 |
| 46 | Protocol18 = 18 |
| 47 | Protocol19 = 19 |
| 48 | Protocol20 = 20 |
| 49 | Protocol21 = 21 |
| 50 | Protocol22 = 22 |
| 51 | Protocol23 = 23 |
| 52 | Protocol24 = 24 |
| 53 | Protocol25 = 25 |
| 54 | Protocol26 = 26 |
| 55 | Protocol27 = 27 |
| 56 | Protocol28 = 28 |
| 57 | Protocol29 = 29 |
| 58 | Protocol30 = 30 |
| 59 | Protocol31 = 31 |
| 60 | Protocol32 = 32 |
| 61 | Protocol33 = 33 |
| 62 | Protocol34 = 34 |
| 63 | Protocol35 = 35 |
| 64 | Protocol36 = 36 |
| 65 | Protocol37 = 37 |
| 66 | Protocol38 = 38 |
| 67 | // ProtocolSpend is the first protocol with a fix round's Feedback and |
| 68 | // a usage row's Turns; Encode drops both below it. |
| 69 | ProtocolSpend = Protocol3 |
| 70 | // ProtocolMergeFacts is the first protocol with merge authority's |
| 71 | // fields; Encode drops them below it, and Equipo merges on its own |
| 72 | // only with a runner that speaks it. |
| 73 | ProtocolMergeFacts = Protocol4 |
| 74 | // ProtocolHostedChecks is the first protocol with hosted checks (a |
| 75 | // checks dispatch's offer and the report's hosted binding); Encode |
| 76 | // drops both below it, so the runner runs its own gate as before. |
| 77 | ProtocolHostedChecks = Protocol5 |
| 78 | // ProtocolEmptyRepos is the first protocol whose catalog lists a |
| 79 | // reachable repository with no commits yet (RepoInfo.Empty); Encode |
| 80 | // drops those entries below it, so an older instance sees the catalog |
| 81 | // it always did. |
| 82 | ProtocolEmptyRepos = Protocol6 |
| 83 | // ProtocolSandboxConsent is the first protocol with the person's |
| 84 | // choice to run a Mac's checks outside the sandbox |
| 85 | // (DispatchCommand.Unsandboxed) and the worker's refusal to run them |
| 86 | // otherwise (ReasonSandboxUnproven). Encode drops the choice below it, |
| 87 | // so an older peer never carries consent, and turns the refusal into |
| 88 | // placement_refused, which an older instance places elsewhere. |
| 89 | ProtocolSandboxConsent = Protocol7 |
| 90 | // ProtocolEmptyMerge is the first protocol with the merge step's |
| 91 | // refusal for a repository whose default branch is unborn and a hub |
| 92 | // that cannot make the first merge yet (ReasonMergeUnbornDefault). |
| 93 | // Encode says it as merge_failed below it, the reason an older |
| 94 | // instance gives every other hub refusal. |
| 95 | ProtocolEmptyMerge = Protocol8 |
| 96 | // ProtocolPreview is the first protocol with preview steps: Review's |
| 97 | // has_preview, the step's result and the publish check's digest. |
| 98 | // Encode drops those below it and refuses a preview dispatch outright. |
| 99 | ProtocolPreview = Protocol9 |
| 100 | // ProtocolExplore is the first protocol with exploration tasks' |
| 101 | // fields: the primary's previews capability and record_task's kind. |
| 102 | // Encode drops both below it, except a kind that says explore, which |
| 103 | // it keeps so an older instance refuses the call. |
| 104 | ProtocolExplore = Protocol10 |
| 105 | // ProtocolPreviewHost is the first protocol whose hello says which |
| 106 | // preview host the runner is paired with (Capabilities.PreviewHost). |
| 107 | // Encode drops it below; the previews flag stays. |
| 108 | ProtocolPreviewHost = Protocol11 |
| 109 | // ProtocolMetered is the first protocol with metered connections |
| 110 | // (connectors spec 2026-11-12, S1): API-key connections and their |
| 111 | // facts in hello and sync, a usage row's cost, the probe's usage, and |
| 112 | // the model, budget and resume_spend frames. Encode drops an API-key |
| 113 | // connection and the cost fields below it, says a probe's usage as a |
| 114 | // check, and refuses the new frames and an API-key connect: an older |
| 115 | // runner is refused metered connections rather than downgraded. |
| 116 | ProtocolMetered = Protocol12 |
| 117 | // ProtocolResearch is the first protocol with the Research specialist |
| 118 | // (spec 2026-11-12-equipo-research-specialist.md): the coordinator's |
| 119 | // propose_specialist, and later slices' research dispatch, fetch |
| 120 | // reports, file chunks and findings. Encode drops or refuses all of it |
| 121 | // below (downgradeResearch); the runner answers the coordinator's |
| 122 | // research tools itself on an older connection. |
| 123 | ProtocolResearch = Protocol13 |
| 124 | // ProtocolScheduler is the first protocol with the scheduler |
| 125 | // (connectors spec 2026-11-12, S3): a dispatch's priority, deadline |
| 126 | // and release, a held step's hold, the release and priority frames and |
| 127 | // a preference's end. Below it Encode refuses the frames, a held |
| 128 | // report and a preference with an end, and drops the dispatch fields: |
| 129 | // an older runner has no leave to spend, so it is never handed one. |
| 130 | ProtocolScheduler = Protocol14 |
| 131 | // ProtocolReadings is the first protocol whose headroom says when it |
| 132 | // was read (Headroom.CheckedAt, connectors spec rev 3.2 §6): the |
| 133 | // Usage page and the hold line show each reading's age. Encode drops |
| 134 | // it below (downgradeReadings); the runner's first hello never |
| 135 | // carries it (WithoutReadingTimes). |
| 136 | ProtocolReadings = Protocol15 |
| 137 | // ProtocolPublish is the first protocol that publishes a merged |
| 138 | // website (publish.go): the hello's sites capability, a publish |
| 139 | // step's dispatch, check and result. Encode refuses the dispatch and |
| 140 | // the check below it and drops the rest. |
| 141 | ProtocolPublish = Protocol16 |
| 142 | // ProtocolOpenCode is the first protocol with the OpenCode Go |
| 143 | // provider behind the OpenCode harness (connectors spec §4.2, slice |
| 144 | // S5). Below it Encode drops that provider's connections from hello |
| 145 | // and sync and its usage rows from every report, and refuses a |
| 146 | // connect or a connection report about one (downgradeOpenCode): an |
| 147 | // older instance never sees a provider it cannot read, and an older |
| 148 | // runner is never asked to connect one. |
| 149 | ProtocolOpenCode = Protocol17 |
| 150 | // ProtocolModels is the first protocol with a metered connection's |
| 151 | // allowed set of models, each chosen per step (connectors spec rev |
| 152 | // 3.3 §16, slice S5b): the models frame and prompt, each held |
| 153 | // connection's applied set and model states, a usage row's family, |
| 154 | // tier, tier version and model_mismatch, Review's dispatch naming |
| 155 | // Engineering's family, and a question's model_unavailable. Below it |
| 156 | // Encode refuses the models frame, says the models prompt as the old |
| 157 | // one-model pick, drops the rest and says model_unavailable as |
| 158 | // account_unavailable (downgradeModels): an older runner keeps its |
| 159 | // one model and is refused any change to the set. |
| 160 | ProtocolModels = Protocol18 |
| 161 | // ProtocolAssistant is the first protocol with the Assistant's lane |
| 162 | // (spec 2026-11-12-equipo-assistant-design.md): a message's and a |
| 163 | // session's lane and a forget_task's keep_preview. Below it Encode |
| 164 | // refuses an Assistant message, drops the Assistant's sessions from |
| 165 | // sync and drops keep_preview (downgradeAssistant). |
| 166 | ProtocolAssistant = Protocol19 |
| 167 | // ProtocolUsageRefresh adds fetched readings and usage availability. |
| 168 | ProtocolUsageRefresh = Protocol20 |
| 169 | // ProtocolCopy adds the Copy specialist, a dispatch's avoided |
| 170 | // families and a step's failure. Below it Encode refuses a Copy |
| 171 | // dispatch or report and drops avoided families and failures. |
| 172 | ProtocolCopy = Protocol21 |
| 173 | // ProtocolJobs is the first protocol with job lanes (spec |
| 174 | // 2026-11-13-assistant-jobs-design.md): a message's and a session's |
| 175 | // lane may be a job's thread (JobLane). Below it Encode refuses a |
| 176 | // job-lane message and drops job-lane sessions from sync |
| 177 | // (downgradeJobs). |
| 178 | ProtocolJobs = Protocol22 |
| 179 | // ProtocolGlance adds the glance frame (runner to instance): the |
| 180 | // Assistant's instant first line for a person turn. Below it Encode |
| 181 | // refuses the frame, so it is not sent. |
| 182 | ProtocolGlance = Protocol23 |
| 183 | // ProtocolWarm adds the warm command (instance to runner): the |
| 184 | // person opened Base, so their primary warms their Assistant now. |
| 185 | // Below it Encode refuses the frame, so it is not sent. |
| 186 | ProtocolWarm = Protocol24 |
| 187 | // ProtocolPlacement adds durable notebook corrections for project moves. |
| 188 | ProtocolPlacement = Protocol25 |
| 189 | ProtocolAccess = Protocol26 |
| 190 | ProtocolInjectionDefences = Protocol28 |
| 191 | // ProtocolPinnedRelease is the first protocol whose Run now names the |
| 192 | // connection the person was told it would use (paused work, |
| 193 | // 2026-11-24): ReleaseCommand.Connection and a dispatch's |
| 194 | // ReleaseConnection. The runner admits such a release only there. |
| 195 | // Below it Encode refuses a pinned release frame and drops a pinned |
| 196 | // dispatch's release with its pin: an older runner would honour the |
| 197 | // leave anywhere, metered included, so it is never handed one. The |
| 198 | // instance offers an older runner plain Run now, with no promise. |
| 199 | ProtocolPinnedRelease = Protocol29 |
| 200 | // ProtocolStuckTasks adds the coordinator's powers for stuck tasks |
| 201 | // (stuck.go): a hello's tool health and the coordinator's offer_retry. |
| 202 | // Below it Encode drops the tool health and refuses the tool's call |
| 203 | // (downgradeStuck). |
| 204 | ProtocolStuckTasks = Protocol30 |
| 205 | // ProtocolChangeFiles adds bounded Engineering file-list facts. |
| 206 | ProtocolChangeFiles = Protocol31 |
| 207 | // ProtocolUnfinishedWork is the first protocol whose instance takes an |
| 208 | // Engineering step done with the reason step_timeout as unfinished |
| 209 | // work (stopped-jobs audit, 2026-11-25): it keeps the reason, tells |
| 210 | // Review, and shows it. A runner keeps a timed-out step's work only |
| 211 | // when the instance speaks it; below it the step fails step_timeout |
| 212 | // as before (Encode, WithoutUnfinished). |
| 213 | ProtocolUnfinishedWork = Protocol32 |
| 214 | // ProtocolAssistantFiles is the first protocol whose Assistant turns |
| 215 | // carry the person's files and the files they attached earlier in the |
| 216 | // conversation (assistant attachments spec 2026-11-26, A6): a message's |
| 217 | // attachments in the Assistant's lane, its earlier and earlier_more. |
| 218 | // Below it Encode refuses an Assistant message with attachments and |
| 219 | // drops earlier and earlier_more (downgradeAssistantFiles); the |
| 220 | // Coordinator's and a job's frames are unchanged. |
| 221 | ProtocolAssistantFiles = Protocol33 |
| 222 | // ProtocolPlaces adds places (places.go): a hello's reach and carlos |
| 223 | // health, a publish bound to its confirmed place in dispatch, check |
| 224 | // and report, and the place tools. Below it Encode drops the hello's |
| 225 | // fields and refuses a publish dispatch and the tools' calls |
| 226 | // (downgradePlaces). |
| 227 | ProtocolPlaces = Protocol34 |
| 228 | // ProtocolChangeDiffs adds separate bounded display patches: a step |
| 229 | // report's change_diffs and the change_diff_upload frame. Below it |
| 230 | // Encode drops the report's diffs and refuses the upload. |
| 231 | ProtocolChangeDiffs = Protocol35 |
| 232 | // ProtocolLookup adds the lookups' two isolated model steps (spec |
| 233 | // 2026-11-26-assistant-abilities §4.2): the live-only lookup_step and |
| 234 | // lookup_result frames (lookup.go). Below it Encode refuses both. |
| 235 | ProtocolLookup = Protocol36 |
| 236 | // ProtocolMacEngineering adds Engineering on a Mac worker |
| 237 | // (mac_engineering.go, spec §8): the prepare_base and base frames, |
| 238 | // Engineering transfers, a dispatch's and a report's Xcode access, a |
| 239 | // report's kept session and outcome, publication-bound change files |
| 240 | // and diffs, a pinned question, a worker's Engineering status, F |
| 241 | // probes and connections. It sits above ProtocolLookup, so a peer at |
| 242 | // 36 has lookups but not Mac Engineering. Below it Encode refuses the |
| 243 | // frames, the transfers and a publication's diffs and drops the fields |
| 244 | // (downgradeMacEngineering). |
| 245 | ProtocolMacEngineering = Protocol37 |
| 246 | // ProtocolDesign adds the Design specialist (spec |
| 247 | // 2026-11-28-dynamic-specialists.md, slice 1): a dispatch's specialist |
| 248 | // binding (id, revision, project, profile, capabilities), the |
| 249 | // page_render lease check, the render_file chunk, a step report's |
| 250 | // options and render records, and propose_specialist's project. Below |
| 251 | // it Encode refuses a bound dispatch, a render check, a render_file |
| 252 | // chunk and a proposal for one project, and drops a report's options |
| 253 | // and render records and a proposal's empty project (downgradeDesign). |
| 254 | ProtocolDesign = Protocol38 |
| 255 | ProtocolCurrent = ProtocolDesign |
| 256 | ) |
| 257 | |
| 258 | // Runner roles. A person's first runner is the primary: the coordinator, |
| 259 | // the forge credential, publication and merges live there. Later runners |
| 260 | // are workers and run steps placed on them. |
| 261 | const ( |
| 262 | RolePrimary = "primary" |
| 263 | RoleWorker = "worker" |
| 264 | ) |
| 265 | |
| 266 | // Sandboxes a runner reports: how it confines a step. |
| 267 | const ( |
| 268 | SandboxBubblewrap = "bubblewrap" |
| 269 | SandboxSeatbelt = "seatbelt" |
| 270 | // SandboxNone is the test-build fake worker only: it runs checks in a |
| 271 | // process group without a sandbox. |
| 272 | SandboxNone = "none" |
| 273 | // SandboxHosted is the instance's record that a checks verdict came |
| 274 | // from the hub's hosted CI (release slice 1); runners never report it. |
| 275 | SandboxHosted = "hosted" |
| 276 | ) |
| 277 | |
| 278 | // Capability tags, a fixed set. A step's needs are a subset. |
| 279 | const ( |
| 280 | TagLinux = "linux" |
| 281 | TagMacOS = "macos" |
| 282 | TagXcode = "xcode" |
| 283 | TagIOSSimulator = "ios_simulator" |
| 284 | TagClaude = "claude" |
| 285 | TagCodex = "codex" |
| 286 | TagGo = "go" |
| 287 | ) |
| 288 | |
| 289 | // Tags is the whole tag set. |
| 290 | var Tags = []string{TagLinux, TagMacOS, TagXcode, TagIOSSimulator, TagClaude, TagCodex, TagGo} |
| 291 | |
| 292 | // Capability bounds. |
| 293 | const ( |
| 294 | MaxSimulators = 40 |
| 295 | MaxCapabilityString = 300 |
| 296 | // MaxHoldingItems bounds Capabilities.HoldingItems. |
| 297 | MaxHoldingItems = 8 |
| 298 | MaxCapabilityBytes = 8 << 10 |
| 299 | ) |
| 300 | |
| 301 | // Platform is a runner's operating system and architecture, as Go names |
| 302 | // them (linux/amd64, darwin/arm64). |
| 303 | type Platform struct { |
| 304 | OS string `json:"os"` |
| 305 | Arch string `json:"arch"` |
| 306 | } |
| 307 | |
| 308 | // Capabilities is what a runner can do, computed at start, re-probed |
| 309 | // hourly and sent with every heartbeat. No path, credential or raw tool |
| 310 | // output: ValidCapabilities checks every field. |
| 311 | type Capabilities struct { |
| 312 | Xcode Xcode `json:"xcode"` |
| 313 | Simulators []Simulator `json:"simulators"` |
| 314 | Toolchains Toolchains `json:"toolchains"` |
| 315 | Harness Harness `json:"harness"` |
| 316 | Tags []string `json:"tags"` |
| 317 | // Probes are a Mac worker's self-probes (P1 to P7), run after |
| 318 | // enrolment and on demand; absent on Linux. |
| 319 | Probes []Probe `json:"probes,omitempty"` |
| 320 | // Tainted: a check has run outside the sandbox on this runner, so it |
| 321 | // never labels one sandboxed again (a Mac worker; sticky). |
| 322 | Tainted bool `json:"tainted,omitempty"` |
| 323 | // Previews: this runner loaded a preview credential, so it can |
| 324 | // publish previews (ProtocolExplore; a primary at it without this has |
| 325 | // previews off). |
| 326 | Previews bool `json:"previews,omitempty"` |
| 327 | // PreviewHost (ProtocolPreviewHost) is the CARLOS preview host the |
| 328 | // runner is paired with; only with Previews. |
| 329 | PreviewHost *PreviewHost `json:"preview_host,omitempty"` |
| 330 | // Research (ProtocolResearch) is what the primary detected for the |
| 331 | // Research site inventory: its interfaces' global addresses. Withheld |
| 332 | // until the welcome says 13, like Previews. |
| 333 | Research *ResearchCapability `json:"research,omitempty"` |
| 334 | // Sites (ProtocolPublish): this runner is paired with a site host and |
| 335 | // can publish a merged website. Withheld until the welcome says 16. |
| 336 | Sites bool `json:"sites,omitempty"` |
| 337 | // Tools (ProtocolStuckTasks): whether the runner's pinned tools are |
| 338 | // installed and match their pins. Withheld until the welcome says 30. |
| 339 | Tools *ToolHealth `json:"tools,omitempty"` |
| 340 | // Reach (ProtocolPlaces): the CARLOS logins and deploy keys this |
| 341 | // runner holds, no secret. Withheld until the welcome says 31. |
| 342 | Reach *Reach `json:"reach,omitempty"` |
| 343 | // Engineering (ProtocolMacEngineering): a Mac worker's word on |
| 344 | // whether it can take Engineering. Withheld until the welcome says 37, |
| 345 | // with the F probes (WithoutMacEngineering). |
| 346 | Engineering *EngineeringStatus `json:"engineering,omitempty"` |
| 347 | // Unproven (ProtocolMacEngineering) is a code for an attempt whose |
| 348 | // end this runner can never prove (UnprovenRecordIncomplete). |
| 349 | Unproven string `json:"unproven,omitempty"` |
| 350 | // UnprovenCount is how many processes keep it so |
| 351 | // (UnprovenProcessesLeft only); never names, pids or paths. |
| 352 | UnprovenCount int `json:"unproven_count,omitempty"` |
| 353 | // ModelHold (ProtocolMacEngineering): a Mac worker holds, or may |
| 354 | // hold, a model credential: an attempt connecting, a connection's |
| 355 | // files, a Keychain item a launch left, or a launch not yet proven |
| 356 | // ended (spec §8.3 (4), D1). HoldingItems names the Keychain items |
| 357 | // (their services) that hold it, at most MaxHoldingItems. |
| 358 | ModelHold bool `json:"model_hold,omitempty"` |
| 359 | HoldingItems []string `json:"holding_items,omitempty"` |
| 360 | // RunnerUser (ProtocolMacEngineering) is a Mac worker's runner user, |
| 361 | // its short name, so the Machines page can say as whom to change a |
| 362 | // folder (ValidRunnerUser). |
| 363 | RunnerUser string `json:"runner_user,omitempty"` |
| 364 | } |
| 365 | |
| 366 | // UnprovenRecordIncomplete: an attempt's turn record was not complete |
| 367 | // (its final write failed, or the runner stopped first), so its end is |
| 368 | // never proven. |
| 369 | const UnprovenRecordIncomplete = "record_incomplete" |
| 370 | |
| 371 | // UnprovenCredential: a Mac could not prove that an earlier launch that |
| 372 | // had a model credential (a sign-in, a token check) ended, so it keeps |
| 373 | // its Claude connections closed until it restarts. |
| 374 | const UnprovenCredential = "credential_unproven" |
| 375 | |
| 376 | // MaxUnprovenCount bounds UnprovenCount. |
| 377 | const MaxUnprovenCount = 100000 |
| 378 | |
| 379 | // UnprovenProcessesLeft: an idle read found UnprovenCount processes of |
| 380 | // the runner user that no record accounts for; a restart clears it. |
| 381 | const UnprovenProcessesLeft = "processes_left" |
| 382 | |
| 383 | // PreviewHost is a preview host a runner pairs with: its kind (an |
| 384 | // adapter: CARLOS devbox on the tailnet, or Carloku temporary sites) and |
| 385 | // the domain its links live under, "" until known. |
| 386 | type PreviewHost struct { |
| 387 | Kind string `json:"kind"` |
| 388 | Domain string `json:"domain,omitempty"` |
| 389 | } |
| 390 | |
| 391 | // Preview host kinds. |
| 392 | const ( |
| 393 | PreviewHostDevbox = "devbox" |
| 394 | PreviewHostCarlokuTemp = "carloku-temp" |
| 395 | ) |
| 396 | |
| 397 | var previewHostDomain = regexp.MustCompile(`^[a-z0-9-]+(\.[a-z0-9-]+)+$`) |
| 398 | |
| 399 | // Probe is one self-probe's result: its ID (P1 to P7, or F1 to F7 at |
| 400 | // ProtocolMacEngineering), a verdict and a |
| 401 | // short detail in the capability string rules (no path, one line). |
| 402 | type Probe struct { |
| 403 | ID string `json:"id"` |
| 404 | Verdict string `json:"verdict"` |
| 405 | Detail string `json:"detail"` |
| 406 | } |
| 407 | |
| 408 | // ProbeDetailTurnBusy is a probe's detail when the probe run could not |
| 409 | // take the Mac's turn: a code, which the instance words (copy.go). |
| 410 | const ProbeDetailTurnBusy = "turn_busy" |
| 411 | |
| 412 | // Probe verdicts. ProbeDenied is P2's pass: every hostile attempt was |
| 413 | // denied, so checks run in the sandbox; anything else and they run |
| 414 | // outside it, labelled so (Paul's ruling 2). |
| 415 | const ( |
| 416 | ProbePassed = "passed" |
| 417 | ProbeDenied = "denied" |
| 418 | ProbeFailed = "failed" |
| 419 | ProbeSkipped = "skipped" |
| 420 | ProbeUnavailable = "unavailable" |
| 421 | ) |
| 422 | |
| 423 | // ProbeIDs are the Mac probes of the spec, in order. |
| 424 | var ProbeIDs = []string{"P1", "P2", "P3", "P4", "P5", "P6", "P7"} |
| 425 | |
| 426 | var probeVerdicts = []string{ProbePassed, ProbeDenied, ProbeFailed, ProbeSkipped, ProbeUnavailable} |
| 427 | |
| 428 | // Xcode is xcodebuild -version's two lines; empty on Linux. |
| 429 | type Xcode struct { |
| 430 | Version string `json:"version"` |
| 431 | Build string `json:"build"` |
| 432 | } |
| 433 | |
| 434 | // Simulator is one available simulator device. |
| 435 | type Simulator struct { |
| 436 | Name string `json:"name"` |
| 437 | Runtime string `json:"runtime"` |
| 438 | UDID string `json:"udid"` |
| 439 | State string `json:"state"` |
| 440 | } |
| 441 | |
| 442 | // Toolchains are versions, "" when absent. |
| 443 | type Toolchains struct { |
| 444 | Go string `json:"go"` |
| 445 | Swift string `json:"swift"` |
| 446 | Node string `json:"node"` |
| 447 | } |
| 448 | |
| 449 | // Harness are the coding harnesses' versions, "" when absent. |
| 450 | type Harness struct { |
| 451 | Claude string `json:"claude"` |
| 452 | Codex string `json:"codex"` |
| 453 | SRT string `json:"srt"` |
| 454 | } |
| 455 | |
| 456 | // ErrCapabilities refuses a capability report out of bounds. |
| 457 | var ErrCapabilities = errors.New("wire: capability report out of bounds") |
| 458 | |
| 459 | // ValidCapabilities checks the bounds and that no string could be a path, |
| 460 | // a credential or tool output: short, one line, no path separator. |
| 461 | func ValidCapabilities(c Capabilities) error { |
| 462 | if len(c.Simulators) > MaxSimulators { |
| 463 | return ErrCapabilities |
| 464 | } |
| 465 | for _, t := range c.Tags { |
| 466 | if !slices.Contains(Tags, t) { |
| 467 | return ErrCapabilities |
| 468 | } |
| 469 | } |
| 470 | seen := map[string]bool{} |
| 471 | for _, p := range c.Probes { |
| 472 | if seen[p.ID] || !validProbeVerdict(p.ID, p.Verdict) { |
| 473 | return ErrCapabilities |
| 474 | } |
| 475 | seen[p.ID] = true |
| 476 | } |
| 477 | if h := c.PreviewHost; h != nil && (!c.Previews || h.Kind != PreviewHostDevbox && h.Kind != PreviewHostCarlokuTemp || h.Domain != "" && (len(h.Domain) > 253 || !previewHostDomain.MatchString(h.Domain))) { |
| 478 | return ErrCapabilities |
| 479 | } |
| 480 | 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 { |
| 481 | return ErrCapabilities |
| 482 | } |
| 483 | if r := c.Reach; r != nil && !validReach(*r) { |
| 484 | return ErrCapabilities |
| 485 | } |
| 486 | if e := c.Engineering; e != nil && !validEngineeringStatus(*e) { |
| 487 | return ErrCapabilities |
| 488 | } |
| 489 | if len(c.HoldingItems) > MaxHoldingItems || c.RunnerUser != "" && !ValidRunnerUser(c.RunnerUser) { |
| 490 | return ErrCapabilities |
| 491 | } |
| 492 | if err := checkStrings(reflect.ValueOf(c)); err != nil { |
| 493 | return err |
| 494 | } |
| 495 | raw, _ := json.Marshal(c) |
| 496 | if len(raw) > MaxCapabilityBytes { |
| 497 | return ErrCapabilities |
| 498 | } |
| 499 | return nil |
| 500 | } |
| 501 | |
| 502 | func checkStrings(v reflect.Value) error { |
| 503 | switch v.Kind() { |
| 504 | case reflect.String: |
| 505 | s := v.String() |
| 506 | if len(s) > MaxCapabilityString || strings.ContainsAny(s, "/\\~\n\r\t\x00=") { |
| 507 | return ErrCapabilities |
| 508 | } |
| 509 | case reflect.Bool: |
| 510 | case reflect.Int: |
| 511 | // A count (UnprovenCount): bounded, never negative. |
| 512 | if v.Int() < 0 || v.Int() > MaxUnprovenCount { |
| 513 | return ErrCapabilities |
| 514 | } |
| 515 | case reflect.Pointer: |
| 516 | if !v.IsNil() { |
| 517 | return checkStrings(v.Elem()) |
| 518 | } |
| 519 | case reflect.Struct: |
| 520 | for i := range v.NumField() { |
| 521 | if err := checkStrings(v.Field(i)); err != nil { |
| 522 | return err |
| 523 | } |
| 524 | } |
| 525 | case reflect.Slice: |
| 526 | for i := range v.Len() { |
| 527 | if err := checkStrings(v.Index(i)); err != nil { |
| 528 | return err |
| 529 | } |
| 530 | } |
| 531 | default: |
| 532 | return ErrCapabilities |
| 533 | } |
| 534 | return nil |
| 535 | } |
| 536 | |
| 537 | // Covers reports whether tags include every need. |
| 538 | func Covers(tags, needs []string) bool { |
| 539 | for _, n := range needs { |
| 540 | if !slices.Contains(tags, n) { |
| 541 | return false |
| 542 | } |
| 543 | } |
| 544 | return true |
| 545 | } |
| 546 | |
| 547 | // Placement of a step: "" placed on its runner; waiting_runner while the |
| 548 | // only runners that fit are offline; waiting_sandbox while the only Macs |
| 549 | // online that fit have not proven their sandbox (probe P2) or are |
| 550 | // tainted, and nobody chose to run the checks outside it; waiting_mac |
| 551 | // while Mac work (checks that need macOS, Engineering for a repository |
| 552 | // whose gate needs Xcode) has no enrolled runner that fits, so it waits |
| 553 | // for one rather than run on a Linux primary; waiting_mac_engineering |
| 554 | // while the only runners that fit Mac Engineering are Mac workers, which |
| 555 | // do not take Engineering yet. |
| 556 | const ( |
| 557 | PlacementWaiting = "waiting_runner" |
| 558 | PlacementSandbox = "waiting_sandbox" |
| 559 | PlacementMac = "waiting_mac" |
| 560 | PlacementMacEngineering = "waiting_mac_engineering" |
| 561 | ) |
| 562 | |
| 563 | // Publication of a worker's Engineering candidate: only the primary |
| 564 | // publishes (pushes) it. |
| 565 | const ( |
| 566 | PublicationNone = "none" |
| 567 | PublicationPending = "pending" |
| 568 | PublicationPublished = "published" |
| 569 | PublicationFailed = "failed" |
| 570 | ) |
| 571 | |
| 572 | // Termination kinds: how a step attempt's end was proven. |
| 573 | const ( |
| 574 | TerminationNamespace = "namespace" |
| 575 | TerminationProcessGroup = "process_group" |
| 576 | // TerminationUnverified: settled by the creator's Recover after the |
| 577 | // machine was removed; nothing proved the end. |
| 578 | TerminationUnverified = "unverified" |
| 579 | ) |
| 580 | |
| 581 | // Transfer directions: inbound (primary to worker) carries the candidate |
| 582 | // a worker judges; outbound (worker to primary) carries a worker's commit. |
| 583 | const ( |
| 584 | TransferInbound = "inbound" |
| 585 | TransferOutbound = "outbound" |
| 586 | ) |
| 587 | |
| 588 | // Transfer bounds: a chunk's data is base64 under 192 KB so a frame stays |
| 589 | // under MaxFrameBytes; a transfer is at most 64 MB. |
| 590 | const ( |
| 591 | MaxBlobData = 192 << 10 |
| 592 | MaxBlobChunk = MaxBlobData / 4 * 3 |
| 593 | MaxTransferBytes = 64 << 20 |
| 594 | TransferTTL = 24 * time.Hour |
| 595 | // MaxTransferChunks is the most chunks a transfer within the bound |
| 596 | // has. A sender declares a pack too large to relay by a total past it, |
| 597 | // and the receiver refuses such a transfer at its first chunk. |
| 598 | MaxTransferChunks = (MaxTransferBytes + MaxBlobChunk - 1) / MaxBlobChunk |
| 599 | ) |
| 600 | |
| 601 | // Protocol 2 frames. |
| 602 | const ( |
| 603 | // FrameBlob is one chunk of a transfer, both ways, durable. |
| 604 | FrameBlob = "blob" |
| 605 | // FrameSendPack asks the primary to upload an inbound transfer's pack. |
| 606 | FrameSendPack = "send_pack" |
| 607 | // FramePublish asks the primary to publish a worker's commit; |
| 608 | // FramePublished is its answer. Both durable. |
| 609 | FramePublish = "publish" |
| 610 | FramePublished = "published" |
| 611 | // FrameRefused answers a lease the instance will not grant (the start |
| 612 | // authorization of a withdrawn or superseded attempt). Not durable. |
| 613 | FrameRefused = "refused" |
| 614 | // FrameResearchFile (runner to instance, durable, protocol 13) carries |
| 615 | // one chunk of an image a Research step kept. |
| 616 | FrameResearchFile = "research_file" |
| 617 | // FrameRenderFile (runner to instance, durable, ProtocolDesign) |
| 618 | // carries one chunk of a capture a Design step named in its options. |
| 619 | FrameRenderFile = "render_file" |
| 620 | ) |
| 621 | |
| 622 | // TransferHeader binds a transfer to one attempt of one step. The |
| 623 | // receiver checks it against its own step row before index-pack. |
| 624 | type TransferHeader struct { |
| 625 | ID string `json:"id"` |
| 626 | Direction string `json:"direction"` |
| 627 | Repo string `json:"repo"` |
| 628 | TaskID string `json:"task_id"` |
| 629 | StepID string `json:"step_id"` |
| 630 | Attempt int64 `json:"attempt"` |
| 631 | BaseSHA string `json:"base_sha"` |
| 632 | CandidateSHA string `json:"candidate_sha"` |
| 633 | // Protocol 37: Kind is "" (checks, or a worker's outbound commit) or |
| 634 | // TransferKindEngineering; an Engineering rebase round also names the |
| 635 | // base the candidate was made on (OldBaseSHA). Commits and Valid. |
| 636 | Kind string `json:"kind,omitempty"` |
| 637 | OldBaseSHA string `json:"old_base_sha,omitempty"` |
| 638 | } |
| 639 | |
| 640 | // Blob is one chunk of a transfer's pack: Index of Total, SHA256 of the |
| 641 | // whole pack (hex), Data base64. |
| 642 | type Blob struct { |
| 643 | Transfer TransferHeader `json:"transfer"` |
| 644 | Index int `json:"index"` |
| 645 | Total int `json:"total"` |
| 646 | SHA256 string `json:"sha256"` |
| 647 | Data string `json:"data"` |
| 648 | } |
| 649 | |
| 650 | // SendPackCommand asks the primary for the pack of CandidateSHA, which |
| 651 | // it uploads as the transfer's blobs (Have: commits the receiver holds). |
| 652 | type SendPackCommand struct { |
| 653 | Transfer TransferHeader `json:"transfer"` |
| 654 | Have []string `json:"have"` |
| 655 | } |
| 656 | |
| 657 | // PublishCommand asks the primary to push a worker's commit, received in |
| 658 | // Transfer, onto the task branch. |
| 659 | type PublishCommand struct { |
| 660 | Publication string `json:"publication"` |
| 661 | TaskID string `json:"task_id"` |
| 662 | StepID string `json:"step_id"` |
| 663 | Attempt int64 `json:"attempt"` |
| 664 | Repo string `json:"repo"` |
| 665 | Branch string `json:"branch"` |
| 666 | Person string `json:"person"` |
| 667 | BaseSHA string `json:"base_sha"` |
| 668 | CandidateSHA string `json:"candidate_sha"` |
| 669 | Transfer string `json:"transfer"` |
| 670 | // OutcomePhase (protocol 37) is the worker's outcome, which the |
| 671 | // primary echoes in published. |
| 672 | OutcomePhase string `json:"outcome_phase,omitempty"` |
| 673 | } |
| 674 | |
| 675 | // PublishedReport is the primary's answer to a publish: Pushed, or the |
| 676 | // reason it was not (push_failed, push_conflict, candidate_unavailable, |
| 677 | // cancelled). |
| 678 | // A successful push may carry proposal_failed as a diagnostic only. |
| 679 | type PublishedReport struct { |
| 680 | Publication string `json:"publication"` |
| 681 | TaskID string `json:"task_id"` |
| 682 | StepID string `json:"step_id"` |
| 683 | Attempt int64 `json:"attempt"` |
| 684 | CandidateSHA string `json:"candidate_sha"` |
| 685 | Pushed bool `json:"pushed"` |
| 686 | Reason string `json:"reason"` |
| 687 | // Protocol 37: the change files and display diffs the primary computed |
| 688 | // for the pushed candidate (the diffs travel as change_diff uploads |
| 689 | // naming this publication), and the publish command's OutcomePhase. |
| 690 | ChangeFiles *ChangeFiles `json:"change_files,omitempty"` |
| 691 | DiffCollection string `json:"diff_collection,omitempty"` |
| 692 | OutcomePhase string `json:"outcome_phase,omitempty"` |
| 693 | } |
| 694 | |
| 695 | // Refused answers a lease frame (ID) the instance would not grant. |
| 696 | type Refused struct { |
| 697 | ID string `json:"id"` |
| 698 | Reason string `json:"reason"` |
| 699 | } |
| 700 | |
| 701 | // protocol2Only are the frame types a protocol 1 runner never receives |
| 702 | // or sends. |
| 703 | var protocol2Only = map[string]bool{FrameBlob: true, FrameSendPack: true, FramePublish: true, FramePublished: true, FrameRefused: true} |
| 704 | |
| 705 | // RunnerProtocolPath answers the runner protocol this instance speaks, so |
| 706 | // a worker can refuse to enrol with an instance that has no workers. |
| 707 | const RunnerProtocolPath = "/api/runner/protocol" |
| 708 | |
| 709 | // RunnerProtocol is GET RunnerProtocolPath. |
| 710 | type RunnerProtocol struct { |
| 711 | Protocol int `json:"protocol"` |
| 712 | } |
| 713 | |
| 714 | // Speaks reports whether a frame type exists at protocol. |
| 715 | func Speaks(protocol int, kind string) bool { |
| 716 | if kind == FrameRequestAccess || kind == FrameAccess { |
| 717 | return protocol >= ProtocolAccess |
| 718 | } |
| 719 | if macEngineeringOnly[kind] { |
| 720 | return protocol >= ProtocolMacEngineering |
| 721 | } |
| 722 | return protocol >= Protocol2 || !protocol2Only[kind] |
| 723 | } |
| 724 | |
| 725 | // ErrProtocol means a frame cannot be spoken at the connection's protocol. |
| 726 | var ErrProtocol = errors.New("wire: frame not in this protocol") |
| 727 | |
| 728 | // Encode returns f as the given protocol speaks it. Below ProtocolJobs |
| 729 | // a job-lane message is refused and job-lane sessions dropped from sync |
| 730 | // (downgradeJobs); below ProtocolUsageRefresh the fetched readings and |
| 731 | // usage availability are dropped (downgradeUsageRefresh); below |
| 732 | // ProtocolAssistant an Assistant message is refused and the lane fields |
| 733 | // dropped (downgradeAssistant); below ProtocolModels the models frame is |
| 734 | // refused and the per-step model fields dropped (downgradeModels); below |
| 735 | // ProtocolOpenCode the OpenCode Go connections and usage are dropped and |
| 736 | // a connect or connection report about one refused (downgradeOpenCode); |
| 737 | // below ProtocolPublish a publish dispatch and check are refused and the |
| 738 | // publish fields dropped (downgradePublish); below ProtocolReadings a |
| 739 | // headroom's reading time is dropped; below ProtocolScheduler the |
| 740 | // scheduler's frames are refused and its fields dropped; below |
| 741 | // ProtocolResearch the Research frames and fields are refused or dropped |
| 742 | // (downgradeResearch); below ProtocolMetered the metered frames, an |
| 743 | // API-key connect and a metered report are refused and the metered |
| 744 | // fields dropped (downgradeMetered); below ProtocolPreviewHost a hello's |
| 745 | // preview host is dropped; below ProtocolExplore the explore fields; |
| 746 | // below ProtocolPreview the preview fields are dropped and a preview dispatch |
| 747 | // is refused (ErrProtocol); below ProtocolEmptyMerge the unborn-default |
| 748 | // refusal is merge_failed too; below ProtocolSandboxConsent the sandbox |
| 749 | // consent and refusal are dropped; |
| 750 | // below ProtocolEmptyRepos a hello's empty repositories are dropped; below |
| 751 | // ProtocolHostedChecks the hosted checks fields too; below |
| 752 | // ProtocolMergeFacts the merge authority fields too; below |
| 753 | // ProtocolSpend the spend fields too; at protocol 1 it is exactly the |
| 754 | // slice 4 frame and field set: protocol 2 fields are dropped and a |
| 755 | // protocol 2 frame type is refused (ErrProtocol). |
| 756 | // |
| 757 | // Below ProtocolGlance a glance frame is refused, and below ProtocolWarm |
| 758 | // a warm command. Below ProtocolAssistantFiles an Assistant message with |
| 759 | // attachments is refused and a message's earlier files are dropped |
| 760 | // (downgradeAssistantFiles); below ProtocolPlaces the places fields are |
| 761 | // dropped and their frames refused (downgradePlaces); below |
| 762 | // ProtocolChangeDiffs a change_diff upload is refused and a step report's |
| 763 | // change_diffs dropped; below ProtocolLookup the lookup frames are refused. |
| 764 | // Below ProtocolMacEngineering the prepare_base and base frames, an |
| 765 | // Engineering transfer and a publication's diff upload are refused and |
| 766 | // slice F's fields dropped (downgradeMacEngineering). Below ProtocolDesign |
| 767 | // a bound dispatch, a render check, a render_file chunk and a proposal |
| 768 | // for one project are refused and a report's options and render records |
| 769 | // dropped (downgradeDesign). |
| 770 | func Encode(f Frame, protocol int) (Frame, error) { |
| 771 | if protocol >= ProtocolCurrent { |
| 772 | return f, nil |
| 773 | } |
| 774 | if !Speaks(protocol, f.Type) { |
| 775 | return Frame{}, fmt.Errorf("%w: %s at protocol %d", ErrProtocol, f.Type, protocol) |
| 776 | } |
| 777 | body, err := f.Decode() |
| 778 | if err != nil { |
| 779 | return Frame{}, err |
| 780 | } |
| 781 | if protocol < ProtocolGlance && f.Type == FrameGlance || protocol < ProtocolWarm && f.Type == FrameWarm { |
| 782 | return Frame{}, fmt.Errorf("%w: %s at protocol %d", ErrProtocol, f.Type, protocol) |
| 783 | } |
| 784 | if v, ok := body.(*ToolCall); ok && protocol < ProtocolAccess && v.Name == ToolRequestAccess { |
| 785 | return Frame{}, ErrProtocol |
| 786 | } |
| 787 | if v, ok := body.(*LeaseCheck); ok && v.AccessCard != "" && protocol < ProtocolAccess { |
| 788 | return Frame{}, ErrProtocol |
| 789 | } |
| 790 | if protocol < ProtocolLookup && (f.Type == FrameLookupStep || f.Type == FrameLookupResult) { |
| 791 | return Frame{}, fmt.Errorf("%w: %s at protocol %d", ErrProtocol, f.Type, protocol) |
| 792 | } |
| 793 | changed := false |
| 794 | if protocol < ProtocolDesign { |
| 795 | dropped, err := downgradeDesign(body, protocol) |
| 796 | if err != nil { |
| 797 | return Frame{}, err |
| 798 | } |
| 799 | changed = dropped |
| 800 | } |
| 801 | if protocol < ProtocolMacEngineering { |
| 802 | dropped, err := downgradeMacEngineering(body, protocol) |
| 803 | if err != nil { |
| 804 | return Frame{}, err |
| 805 | } |
| 806 | changed = changed || dropped |
| 807 | } |
| 808 | if protocol < ProtocolChangeDiffs { |
| 809 | switch v := body.(type) { |
| 810 | case *ChangeDiffUpload: |
| 811 | return Frame{}, ErrProtocol |
| 812 | case *StepReport: |
| 813 | if v.ChangeDiffs != "" { |
| 814 | v.ChangeDiffs = "" |
| 815 | changed = true |
| 816 | } |
| 817 | } |
| 818 | } |
| 819 | if protocol < ProtocolPlaces { |
| 820 | dropped, err := downgradePlaces(body, protocol) |
| 821 | if err != nil { |
| 822 | return Frame{}, err |
| 823 | } |
| 824 | changed = changed || dropped |
| 825 | } |
| 826 | if protocol < ProtocolAssistantFiles { |
| 827 | dropped, err := downgradeAssistantFiles(body, protocol) |
| 828 | if err != nil { |
| 829 | return Frame{}, err |
| 830 | } |
| 831 | changed = changed || dropped |
| 832 | } |
| 833 | if protocol < ProtocolStuckTasks { |
| 834 | dropped, err := downgradeStuck(body, protocol) |
| 835 | if err != nil { |
| 836 | return Frame{}, err |
| 837 | } |
| 838 | changed = changed || dropped |
| 839 | } |
| 840 | if protocol < ProtocolUnfinishedWork { |
| 841 | if v, ok := body.(*StepReport); ok && WithoutUnfinished(v) { |
| 842 | changed = true |
| 843 | } |
| 844 | } |
| 845 | if protocol < ProtocolChangeFiles { |
| 846 | if v, ok := body.(*StepReport); ok && v.ChangeFiles != nil { |
| 847 | v.ChangeFiles = nil |
| 848 | changed = true |
| 849 | } |
| 850 | } |
| 851 | if protocol < ProtocolPinnedRelease { |
| 852 | if v, ok := body.(*ReleaseCommand); ok && v.Connection != "" { |
| 853 | return Frame{}, fmt.Errorf("%w: a pinned release at protocol %d", ErrProtocol, protocol) |
| 854 | } |
| 855 | if d, ok := body.(*DispatchCommand); ok && d.ReleaseConnection != "" { |
| 856 | d.Release, d.ReleaseConnection = "", "" |
| 857 | changed = true |
| 858 | } |
| 859 | } |
| 860 | if protocol < ProtocolInjectionDefences { |
| 861 | // Older runners consume fix-round context from Brief, including runners |
| 862 | // that predate the separate Feedback field. Protocol 28 keeps sources apart. |
| 863 | if d, ok := body.(*DispatchCommand); ok && d.Feedback != "" && !strings.HasSuffix(d.Brief, d.Feedback) { |
| 864 | d.Brief = strings.TrimSpace(d.Brief + "\n\n" + d.Feedback) |
| 865 | if len(d.Brief) > MaxTaskBrief+4000 { |
| 866 | d.Brief = strings.ToValidUTF8(d.Brief[:MaxTaskBrief+4000], "") |
| 867 | } |
| 868 | changed = true |
| 869 | } |
| 870 | |
| 871 | if d, ok := body.(*DispatchCommand); ok && d.PreviewUnsafeDigest != "" { |
| 872 | return Frame{}, ErrProtocol |
| 873 | } |
| 874 | if d, ok := body.(*DispatchCommand); ok && len(d.PersonWords) > 0 { |
| 875 | d.PersonWords = nil |
| 876 | changed = true |
| 877 | } |
| 878 | if r, ok := body.(*StepReport); ok { |
| 879 | if r.BaseChecks != "" { |
| 880 | r.BaseChecks = "" |
| 881 | changed = true |
| 882 | } |
| 883 | if r.Reason == "base_checks_failed" { |
| 884 | r.Reason = "" |
| 885 | changed = true |
| 886 | } |
| 887 | if r.BaseChecksSHA != "" { |
| 888 | r.BaseChecksSHA = "" |
| 889 | changed = true |
| 890 | } |
| 891 | if r.Change != nil && (r.Change.GateFilesChanged || r.Change.ReviewTruncated) { |
| 892 | r.Change.GateFilesChanged = false |
| 893 | r.Change.ReviewTruncated = false |
| 894 | changed = true |
| 895 | } |
| 896 | } |
| 897 | } |
| 898 | if protocol < ProtocolPlacement { |
| 899 | if v, ok := body.(*MessageCommand); ok && len(v.PlacementNotes) > 0 { |
| 900 | v.PlacementNotes = nil |
| 901 | changed = true |
| 902 | } |
| 903 | } |
| 904 | if protocol < ProtocolJobs { |
| 905 | dropped, err := downgradeJobs(body, protocol) |
| 906 | if err != nil { |
| 907 | return Frame{}, err |
| 908 | } |
| 909 | changed = dropped || changed |
| 910 | } |
| 911 | if protocol < ProtocolCopy { |
| 912 | switch v := body.(type) { |
| 913 | case *DispatchCommand: |
| 914 | if v.Specialist == SpecialistCopy || v.Copy != nil { |
| 915 | return Frame{}, ErrProtocol |
| 916 | } |
| 917 | if len(v.AvoidFamilies) > 0 { |
| 918 | v.AvoidFamilies = nil |
| 919 | changed = true |
| 920 | } |
| 921 | case *StepReport: |
| 922 | if v.Copy != nil { |
| 923 | return Frame{}, ErrProtocol |
| 924 | } |
| 925 | if v.Failure != nil { |
| 926 | v.Failure = nil |
| 927 | changed = true |
| 928 | } |
| 929 | } |
| 930 | } |
| 931 | if protocol < ProtocolUsageRefresh { |
| 932 | changed = downgradeUsageRefresh(body) || changed |
| 933 | } |
| 934 | if protocol < ProtocolAssistant { |
| 935 | dropped, err := downgradeAssistant(body, protocol) |
| 936 | if err != nil { |
| 937 | return Frame{}, err |
| 938 | } |
| 939 | changed = dropped || changed |
| 940 | } |
| 941 | if protocol < ProtocolModels { |
| 942 | dropped, err := downgradeModels(body, protocol) |
| 943 | if err != nil { |
| 944 | return Frame{}, err |
| 945 | } |
| 946 | changed = dropped || changed |
| 947 | } |
| 948 | if protocol < ProtocolOpenCode { |
| 949 | dropped, err := downgradeOpenCode(body, protocol) |
| 950 | if err != nil { |
| 951 | return Frame{}, err |
| 952 | } |
| 953 | changed = dropped || changed |
| 954 | } |
| 955 | if protocol < ProtocolPublish { |
| 956 | dropped, err := downgradePublish(body, protocol) |
| 957 | if err != nil { |
| 958 | return Frame{}, err |
| 959 | } |
| 960 | changed = dropped || changed |
| 961 | } |
| 962 | if protocol < ProtocolReadings { |
| 963 | changed = downgradeReadings(body) || changed |
| 964 | } |
| 965 | if protocol < ProtocolScheduler { |
| 966 | if schedulerOnly[f.Type] { |
| 967 | return Frame{}, fmt.Errorf("%w: %s at protocol %d", ErrProtocol, f.Type, protocol) |
| 968 | } |
| 969 | if r, ok := body.(*StepReport); ok && r.Hold != nil { |
| 970 | return Frame{}, fmt.Errorf("%w: a held step at protocol %d", ErrProtocol, protocol) |
| 971 | } |
| 972 | if p, ok := body.(*PreferenceCommand); ok && p.Until != nil { |
| 973 | return Frame{}, fmt.Errorf("%w: a preference with an end at protocol %d", ErrProtocol, protocol) |
| 974 | } |
| 975 | changed = downgradeScheduler(body) || changed |
| 976 | } |
| 977 | if protocol < ProtocolResearch { |
| 978 | dropped, err := downgradeResearch(body, protocol) |
| 979 | if err != nil { |
| 980 | return Frame{}, err |
| 981 | } |
| 982 | changed = dropped || changed |
| 983 | } |
| 984 | if protocol < ProtocolMetered { |
| 985 | if meteredOnly[f.Type] { |
| 986 | return Frame{}, fmt.Errorf("%w: %s at protocol %d", ErrProtocol, f.Type, protocol) |
| 987 | } |
| 988 | if c, ok := body.(*ConnectCommand); ok && c.Kind == KindAPIKey { |
| 989 | return Frame{}, fmt.Errorf("%w: an API-key connection at protocol %d", ErrProtocol, protocol) |
| 990 | } |
| 991 | if meteredReport(body) { |
| 992 | return Frame{}, fmt.Errorf("%w: a metered report at protocol %d", ErrProtocol, protocol) |
| 993 | } |
| 994 | changed = downgradeMetered(body) || changed |
| 995 | } |
| 996 | if h, ok := body.(*Hello); ok && protocol < ProtocolPreviewHost { |
| 997 | changed = WithoutPreviewHost(h) || changed |
| 998 | } |
| 999 | if protocol < ProtocolExplore { |
| 1000 | changed = downgradeExplore(body) || changed |
| 1001 | } |
| 1002 | if protocol < ProtocolPreview { |
| 1003 | if d, ok := body.(*DispatchCommand); ok && d.Specialist == SpecialistPreview { |
| 1004 | return Frame{}, fmt.Errorf("%w: a preview step at protocol %d", ErrProtocol, protocol) |
| 1005 | } |
| 1006 | changed = downgradePreview(body) || changed |
| 1007 | } |
| 1008 | if r, ok := body.(*StepReport); ok && protocol < ProtocolEmptyMerge && r.Reason == ReasonMergeUnbornDefault { |
| 1009 | r.Reason, changed = "merge_failed", true |
| 1010 | } |
| 1011 | if protocol < ProtocolSandboxConsent { |
| 1012 | changed = downgradeSandboxConsent(body) || changed |
| 1013 | } |
| 1014 | if h, ok := body.(*Hello); ok && protocol < ProtocolEmptyRepos { |
| 1015 | changed = WithoutEmptyRepos(h) || changed |
| 1016 | } |
| 1017 | if protocol < ProtocolHostedChecks { |
| 1018 | changed = downgradeHostedChecks(body) || changed |
| 1019 | } |
| 1020 | if protocol < ProtocolMergeFacts { |
| 1021 | changed = downgradeMergeFacts(body) || changed |
| 1022 | } |
| 1023 | if protocol < ProtocolSpend { |
| 1024 | changed = downgradeSpend(body) || changed |
| 1025 | } |
| 1026 | if protocol < Protocol2 { |
| 1027 | changed = downgrade(body) || changed |
| 1028 | } |
| 1029 | if !changed { |
| 1030 | return f, nil |
| 1031 | } |
| 1032 | raw, err := json.Marshal(body) |
| 1033 | if err != nil { |
| 1034 | return Frame{}, err |
| 1035 | } |
| 1036 | f.Data = raw |
| 1037 | return f, nil |
| 1038 | } |
| 1039 | |
| 1040 | // meteredReport says a report only a metered connection makes, which an |
| 1041 | // older instance has no words for: an API-key attempt's report (its |
| 1042 | // provider, its key or model card, its refusal reasons) and a question |
| 1043 | // held by the metered guard (queued, or ended, with a hold reason). It |
| 1044 | // is refused below ProtocolMetered, never translated. |
| 1045 | func meteredReport(body any) bool { |
| 1046 | switch v := body.(type) { |
| 1047 | case *ConnectionReport: |
| 1048 | _, apiKey := APIKeyProviders[v.Provider] |
| 1049 | prompt := v.Prompt != nil && (v.Prompt.Kind == PromptAPIKey || v.Prompt.Kind == PromptModel || v.Prompt.Models != nil) |
| 1050 | return apiKey || prompt || v.Reason == "key_refused" || v.Reason == "no_priced_model" |
| 1051 | case *AnswerReport: |
| 1052 | return v.State == QuestionQueued || v.Reason == HoldBusy || v.Reason == HoldBudget || v.Reason == HoldSpendUnknown |
| 1053 | } |
| 1054 | return false |
| 1055 | } |
| 1056 | |
| 1057 | // downgradeOpenCode takes the OpenCode Go provider out of what a peer |
| 1058 | // below ProtocolOpenCode is sent (in new values; the caller's are |
| 1059 | // untouched): its held connections and its usage rows go, and a connect |
| 1060 | // or a connection report about it is refused. It reports whether |
| 1061 | // anything changed. |
| 1062 | func downgradeOpenCode(body any, protocol int) (bool, error) { |
| 1063 | held := func(cs *[]HeldConnection) bool { |
| 1064 | gone := func(h HeldConnection) bool { return openCodeOnly(h.Provider) || h.Harness == HarnessOpenCode } |
| 1065 | if !slices.ContainsFunc(*cs, gone) { |
| 1066 | return false |
| 1067 | } |
| 1068 | *cs = slices.DeleteFunc(slices.Clone(*cs), gone) |
| 1069 | return true |
| 1070 | } |
| 1071 | rows := func(us *[]Usage) bool { |
| 1072 | gone := func(u Usage) bool { return openCodeOnly(u.Provider) } |
| 1073 | if !slices.ContainsFunc(*us, gone) { |
| 1074 | return false |
| 1075 | } |
| 1076 | *us = slices.DeleteFunc(slices.Clone(*us), gone) |
| 1077 | return true |
| 1078 | } |
| 1079 | switch v := body.(type) { |
| 1080 | case *Hello: |
| 1081 | return held(&v.Connections), nil |
| 1082 | case *Sync: |
| 1083 | return held(&v.Connections), nil |
| 1084 | case *ConnectCommand: |
| 1085 | if openCodeOnly(v.Provider) { |
| 1086 | return false, fmt.Errorf("%w: an OpenCode Go connection at protocol %d", ErrProtocol, protocol) |
| 1087 | } |
| 1088 | case *ConnectionReport: |
| 1089 | if openCodeOnly(v.Provider) { |
| 1090 | return false, fmt.Errorf("%w: an OpenCode Go report at protocol %d", ErrProtocol, protocol) |
| 1091 | } |
| 1092 | case *UsageReport: |
| 1093 | return rows(&v.Rows), nil |
| 1094 | case *StepReport: |
| 1095 | return rows(&v.Usage), nil |
| 1096 | case *AnswerReport: |
| 1097 | return rows(&v.Usage), nil |
| 1098 | case *Reply: |
| 1099 | return rows(&v.Usage), nil |
| 1100 | } |
| 1101 | return false, nil |
| 1102 | } |
| 1103 | |
| 1104 | // schedulerOnly are the frame types below ProtocolScheduler never carries. |
| 1105 | var schedulerOnly = map[string]bool{FrameRelease: true, FramePriority: true} |
| 1106 | |
| 1107 | // downgradeScheduler clears a dispatch's scheduler fields (an older |
| 1108 | // runner runs every step as before and never spends). It reports whether |
| 1109 | // anything changed. |
| 1110 | func downgradeScheduler(body any) bool { |
| 1111 | switch v := body.(type) { |
| 1112 | case *DispatchCommand: |
| 1113 | set := v.Priority != "" || v.By != nil || v.Release != "" || v.PriorityRevision != 0 || v.Housekeeping |
| 1114 | v.Priority, v.By, v.Release, v.PriorityRevision, v.Housekeeping = "", nil, "", 0, false |
| 1115 | return set |
| 1116 | case *ToolCall: |
| 1117 | // record_task's and start_task's priority and deadline: an older |
| 1118 | // instance decodes their arguments strictly. |
| 1119 | if v.Name != ToolRecordTask && v.Name != ToolStartTask { |
| 1120 | return false |
| 1121 | } |
| 1122 | var args map[string]json.RawMessage |
| 1123 | if json.Unmarshal(v.Args, &args) != nil { |
| 1124 | return false |
| 1125 | } |
| 1126 | _, p := args["priority"] |
| 1127 | _, b := args["by"] |
| 1128 | if !p && !b { |
| 1129 | return false |
| 1130 | } |
| 1131 | delete(args, "priority") |
| 1132 | delete(args, "by") |
| 1133 | raw, err := json.Marshal(args) |
| 1134 | if err != nil { |
| 1135 | return false |
| 1136 | } |
| 1137 | v.Args = raw |
| 1138 | return true |
| 1139 | } |
| 1140 | return false |
| 1141 | } |
| 1142 | |
| 1143 | // meteredOnly are the frame types below ProtocolMetered never carries. |
| 1144 | var meteredOnly = map[string]bool{FrameModel: true, FrameBudget: true, FrameResumeSpend: true} |
| 1145 | |
| 1146 | // downgradeMetered clears a body's ProtocolMetered fields: API-key |
| 1147 | // connections leave hello and sync (an older instance knows none), a |
| 1148 | // usage row's cost goes, and a probe's usage is said as a check. It |
| 1149 | // reports whether anything changed. |
| 1150 | func downgradeMetered(body any) bool { |
| 1151 | held := func(cs *[]HeldConnection) bool { |
| 1152 | if !slices.ContainsFunc(*cs, func(h HeldConnection) bool { return h.Kind == KindAPIKey || h.Billing != "" }) { |
| 1153 | return false |
| 1154 | } |
| 1155 | *cs = slices.DeleteFunc(slices.Clone(*cs), func(h HeldConnection) bool { return h.Kind == KindAPIKey || h.Billing != "" }) |
| 1156 | return true |
| 1157 | } |
| 1158 | cost := func(rows []Usage) bool { |
| 1159 | set := false |
| 1160 | for i := range rows { |
| 1161 | u := &rows[i] |
| 1162 | set = set || u.CostMicros != nil || u.Currency != "" || u.PriceVersion != "" || u.CostReportedMicros != nil |
| 1163 | u.CostMicros, u.Currency, u.PriceVersion, u.CostReportedMicros = nil, "", "", nil |
| 1164 | } |
| 1165 | return set |
| 1166 | } |
| 1167 | switch v := body.(type) { |
| 1168 | case *Hello: |
| 1169 | return held(&v.Connections) |
| 1170 | case *Sync: |
| 1171 | return held(&v.Connections) |
| 1172 | case *ConnectCommand: |
| 1173 | set := v.Billing != "" || v.Budget != nil |
| 1174 | v.Billing, v.Budget = "", nil |
| 1175 | return set |
| 1176 | case *UsageReport: |
| 1177 | set := cost(v.Rows) |
| 1178 | if v.ProbeID != "" { |
| 1179 | v.CheckID, v.ProbeID, set = v.ProbeID, "", true |
| 1180 | } |
| 1181 | return set |
| 1182 | case *StepReport: |
| 1183 | return cost(v.Usage) |
| 1184 | case *AnswerReport: |
| 1185 | return cost(v.Usage) |
| 1186 | case *Reply: |
| 1187 | return cost(v.Usage) |
| 1188 | } |
| 1189 | return false |
| 1190 | } |
| 1191 | |
| 1192 | // downgradeSandboxConsent clears a dispatch's consent to run outside the |
| 1193 | // sandbox (an older peer never carries one), and says a worker's refusal |
| 1194 | // to run unproven as placement_refused, which an older instance knows: |
| 1195 | // it places the step elsewhere, never counts a failure and never taints. |
| 1196 | func downgradeSandboxConsent(body any) bool { |
| 1197 | switch v := body.(type) { |
| 1198 | case *DispatchCommand: |
| 1199 | set := v.Unsandboxed |
| 1200 | v.Unsandboxed = false |
| 1201 | return set |
| 1202 | case *StepReport: |
| 1203 | if v.Reason != ReasonSandboxUnproven { |
| 1204 | return false |
| 1205 | } |
| 1206 | v.Reason = "placement_refused" |
| 1207 | return true |
| 1208 | } |
| 1209 | return false |
| 1210 | } |
| 1211 | |
| 1212 | // downgradePreview clears a body's ProtocolPreview fields (omitempty). It |
| 1213 | // reports whether the body had any. |
| 1214 | func downgradePreview(body any) bool { |
| 1215 | switch v := body.(type) { |
| 1216 | case *StepReport: |
| 1217 | set := v.HasPreview || v.Preview != nil |
| 1218 | v.HasPreview, v.Preview = false, nil |
| 1219 | return set |
| 1220 | case *LeaseCheck: |
| 1221 | set := v.Digest != "" |
| 1222 | v.Digest = "" |
| 1223 | return set |
| 1224 | } |
| 1225 | return false |
| 1226 | } |
| 1227 | |
| 1228 | // downgradeHostedChecks clears a body's ProtocolHostedChecks fields |
| 1229 | // (omitempty). It reports whether the body had any. |
| 1230 | func downgradeHostedChecks(body any) bool { |
| 1231 | switch v := body.(type) { |
| 1232 | case *DispatchCommand: |
| 1233 | set := v.HostedChecks |
| 1234 | v.HostedChecks = false |
| 1235 | return set |
| 1236 | case *StepReport: |
| 1237 | // A hosted verdict means nothing without its binding: an older |
| 1238 | // instance gets checks that could not run, never a bare pass. |
| 1239 | if v.Hosted == nil && v.Gate != GateHosted { |
| 1240 | return false |
| 1241 | } |
| 1242 | v.Hosted, v.Gate, v.ExitCode = nil, "", nil |
| 1243 | if v.Checks != "" { |
| 1244 | v.Checks, v.Reason = ChecksCannotRun, "checks_unavailable" |
| 1245 | } |
| 1246 | return true |
| 1247 | } |
| 1248 | return false |
| 1249 | } |
| 1250 | |
| 1251 | // downgradeMergeFacts clears a body's ProtocolMergeFacts fields (all |
| 1252 | // omitempty). It reports whether the body has any. |
| 1253 | func downgradeMergeFacts(body any) bool { |
| 1254 | switch v := body.(type) { |
| 1255 | case *DispatchCommand: |
| 1256 | set := v.RevertSHA != "" |
| 1257 | v.RevertSHA = "" |
| 1258 | return set |
| 1259 | case *LeaseCheck: |
| 1260 | set := v.Purpose != "" |
| 1261 | v.Purpose = "" |
| 1262 | return set |
| 1263 | case *StepReport: |
| 1264 | set := v.Change != nil || v.MergeSource != "" || v.MergeParents != nil |
| 1265 | v.Change, v.MergeSource, v.MergeParents = nil, "", nil |
| 1266 | return set |
| 1267 | } |
| 1268 | return false |
| 1269 | } |
| 1270 | |
| 1271 | // downgradeSpend clears a body's ProtocolSpend fields (omitempty, so |
| 1272 | // absent once zero). It reports whether any was set. |
| 1273 | func downgradeSpend(body any) bool { |
| 1274 | turns := func(rows []Usage) bool { |
| 1275 | set := false |
| 1276 | for i := range rows { |
| 1277 | set = set || rows[i].Turns != nil |
| 1278 | rows[i].Turns = nil |
| 1279 | } |
| 1280 | return set |
| 1281 | } |
| 1282 | switch v := body.(type) { |
| 1283 | case *DispatchCommand: |
| 1284 | set := v.Feedback != "" |
| 1285 | v.Feedback = "" |
| 1286 | return set |
| 1287 | case *StepReport: |
| 1288 | return turns(v.Usage) |
| 1289 | case *AnswerReport: |
| 1290 | return turns(v.Usage) |
| 1291 | case *Reply: |
| 1292 | return turns(v.Usage) |
| 1293 | case *UsageReport: |
| 1294 | return turns(v.Rows) |
| 1295 | } |
| 1296 | return false |
| 1297 | } |
| 1298 | |
| 1299 | // downgrade clears a body's protocol 2 fields (all omitempty, so they |
| 1300 | // are absent once zero). It reports whether the body has any. |
| 1301 | func downgrade(body any) bool { |
| 1302 | switch v := body.(type) { |
| 1303 | case *Hello: |
| 1304 | v.Protocol, v.Platform, v.Label, v.Sandbox, v.Capabilities, v.SealKey = 0, nil, "", "", nil, "" |
| 1305 | for i := range v.Connections { |
| 1306 | v.Connections[i].ExpiresAt, v.Connections[i].ExpiresEstimated = nil, false |
| 1307 | } |
| 1308 | for i := range v.Catalog { |
| 1309 | v.Catalog[i].NeedsMacOS, v.Catalog[i].Simulator = false, false |
| 1310 | } |
| 1311 | case *Welcome: |
| 1312 | v.Protocol, v.Role, v.Release, v.Tainted = 0, "", "", false |
| 1313 | case *DispatchCommand: |
| 1314 | v.Needs, v.RunnerID = nil, "" |
| 1315 | case *LeaseCheck: |
| 1316 | v.StepID, v.Attempt, v.Publication = "", 0, "" |
| 1317 | case *StepReport: |
| 1318 | v.TerminationKind, v.Have, v.Phase, v.Apple, v.ChecksSandbox = "", nil, "", false, "" |
| 1319 | default: |
| 1320 | return false |
| 1321 | } |
| 1322 | return true |
| 1323 | } |
| 1324 | |
| 1325 | // HelloProtocol is the protocol a hello speaks: absent means 1. |
| 1326 | func HelloProtocol(h Hello) int { |
| 1327 | if h.Protocol <= Protocol1 { |
| 1328 | return Protocol1 |
| 1329 | } |
| 1330 | return h.Protocol |
| 1331 | } |
| 1332 | |
| 1333 | // Spoken is the protocol both ends speak: the lower of the runner's and |
| 1334 | // this build's. |
| 1335 | func Spoken(runner int) int { return max(Protocol1, min(runner, ProtocolCurrent)) } |
| 1336 | |
| 1337 | // WithoutEmptyRepos drops a hello's empty repositories from its catalog |
| 1338 | // (in a new slice, so the caller's catalog is untouched). The runner's |
| 1339 | // first hello on a connection is sent before the instance says which |
| 1340 | // protocol it speaks, and an older instance's strict decoder would refuse |
| 1341 | // it; the runner sends them once the welcome says protocol 6. It reports |
| 1342 | // whether any was dropped. |
| 1343 | func WithoutEmptyRepos(h *Hello) bool { |
| 1344 | if !slices.ContainsFunc(h.Catalog, func(e RepoInfo) bool { return e.Empty }) { |
| 1345 | return false |
| 1346 | } |
| 1347 | h.Catalog = slices.DeleteFunc(slices.Clone(h.Catalog), func(e RepoInfo) bool { return e.Empty }) |
| 1348 | return true |
| 1349 | } |
| 1350 | |