From d6b9067020795ebe0135b3c07b5ede69841e7a11 Mon Sep 17 00:00:00 2001 From: "Thomas Marchand (agent)" Date: Mon, 30 Nov 2026 13:50:23 +0000 Subject: [PATCH 1/2] fix: VPN launch refusals and Mythos/Daybreak account gaps - Local Claude Code/Codex/Grok without the router are refused only by a VPN route on an account of their own provider (one helper, anyVpnConfiguredFor?). - Core-host Antigravity turns choose the account like node dispatch (chooseAntigravityAccount?), pass over a busy route, and run as the chosen account with its own login. - An occupied exit answers vpn_exit_in_use; refusals say exits needed vs configured. - A request needing Daybreak/CVP with no marked account gets 403 no_cyber_access_account; opt-in per-account reserve for marked requests. - HTTP contract test for /api/ai/providers/:id/cyber-access. --- docs/specs/account-vpn.md | 28 ++++ docs/specs/subscription-cyber-access.md | 33 +++- lean/OrbCore/OrbCore/AccountVpnApi.lean | 12 +- lean/OrbCore/OrbCore/AccountVpnPool.lean | 28 +++- lean/OrbCore/OrbCore/Control.lean | 132 ++++++++++----- lean/OrbCore/OrbCore/Cyber.lean | 43 +++-- lean/OrbCore/OrbCore/HarnessProxyTests.lean | 11 +- .../OrbCore/ProviderContractTests.lean | 135 +++++++++++++-- lean/OrbCore/OrbCore/Proxy.lean | 59 ++++--- lean/OrbCore/OrbCore/RemoteDispatch.lean | 95 ++++++++--- lean/OrbCore/OrbCore/Store.lean | 4 +- orb/src/AccountCyberAccessSetting.tsx | 44 +++-- orb/src/accountCyberAccess.ts | 19 ++- orb/src/api.ts | 7 +- orb/tests/account-cyber-access.test.tsx | 32 +++- .../fixtures/account-cyber-access.json | 157 +++++++++++++++--- 16 files changed, 669 insertions(+), 170 deletions(-) diff --git a/docs/specs/account-vpn.md b/docs/specs/account-vpn.md index 0467d578a..467051614 100644 --- a/docs/specs/account-vpn.md +++ b/docs/specs/account-vpn.md @@ -263,6 +263,34 @@ the waiting account is kept, so the refusal names its route: the answer is `409` with the `error` code, a `message` in plain words and `retry_after_secs`. See [refused-launch.md](refused-launch.md). +A turn that runs on the Core host itself (`Control.resolveLocalCoreHarnessSetup`) +uses the same choice, `RemoteDispatch.chooseAntigravityAccount?`. While no +Antigravity account is VPN-routed it keeps the host's own `agy` login. Once one +is, the host login could belong to any of them, so the turn runs as the chosen +account: its login is written to a private home of the mission +(`/core-turns/agy-home/`, `HOME` for that turn), and a +VPN-routed account goes only through its relay. Until 30 Nov 2026 this path +accepted exactly one enabled VPN account and otherwise failed with +`antigravity_vpn_requires_account_binding`. + +A local Claude Code, Codex or Grok turn without Core's router uses the host's +login of its own provider. Only a VPN route on an account of that provider +(`RemoteDispatch.harnessVpnCategory?`, `anyVpnConfiguredFor?`) refuses it with +`local_harness_vpn_requires_router`; OpenCode and Pi, which can reach any +provider, are refused by a route on any account. Until 30 Nov 2026 any route +refused every local harness. + +### Exits needed against exits configured + +Two accounts of one provider category never share an exit, so a country needs +one server per VPN-routed account of the category. Allocation walks every +running and configured profile of the country before refusing; when a profile +exists but its exit is held by another account of the category, the answer is +`vpn_exit_in_use` (it used to be `vpn_no_compatible_profile`, which account +selection does not pass over). When the accounts routed to a country outnumber +its distinct configured servers, the refusal says so in numbers, in the account +row and in a refused launch (`AccountVpnPool.exitDemand`, `exitShortageNote`). + The WireGuard test changes the actual source address using SNAT inside the test namespace. Each tunnel has IPv4 and IPv6 addresses. An IPv6-only collision forces one ChatGPT account onto a verified third peer even though diff --git a/docs/specs/subscription-cyber-access.md b/docs/specs/subscription-cyber-access.md index 4d9d79ac4..db8579139 100644 --- a/docs/specs/subscription-cyber-access.md +++ b/docs/specs/subscription-cyber-access.md @@ -133,8 +133,9 @@ one value: | `available` | the access this provider can hold, so a client knows what to offer | | `source` | `operator` (set by hand) or `detected` (learned by Orb); `null` for `none` | | `updated_at` | when it was last set, ISO 8601 UTC; `null` for `none` | +| `reserved` | `true`: kept for requests that ask for the access; ordinary requests never use it. Always `false` for `none` | -Storage: table `account_cyber_access(account_id, access, source, updated_at)` +Storage: table `account_cyber_access(account_id, access, source, updated_at, reserved)` in the missions database. A row exists only for an account that has the access. API: @@ -144,7 +145,9 @@ API: and holds no secret. - `GET /api/ai/providers/:id/cyber-access` returns the object above. - `PUT /api/ai/providers/:id/cyber-access` with `{"access": "none" | "daybreak" - | "cvp"}` sets it with `source = operator`. Admin only. The access must be the + | "cvp", "reserved"?: bool}` sets it with `source = operator`. Without + `reserved` the saved choice is kept; clearing the mark clears it, and + `reserved: true` with `access: "none"` is `400 cyber_access_reserve_needs_mark`. Admin only. The access must be the one the account's provider can hold, else `400 cyber_access_not_applicable`. The change is written to the provider audit log (field name only). @@ -177,12 +180,20 @@ place accounts are ordered or excluded by cyber access. - **Request that asks for the access**: only accounts recorded with that access are used. If none is enabled and allowed for the mission's owner, the request fails with `403 no_cyber_access_account` and a sentence that names the access - and says nothing was sent to another account. + and says nothing was sent to another account. This includes the case where no + account is marked at all: until 30 Nov 2026 such a request (a + `claude-mythos-*` model, say) went to whichever subscription the pool picked; + now the message asks the operator to mark the account that has the access. +- **Reserved account** (opt-in, per marked account, `reserved` below): an + ordinary request never uses it, not even as the last resort. A pool that + contains a reserved login and cannot be split login by login is dropped, since + the sidecar could pick that login. When only reserved accounts serve the model + the request fails with `403 only_reserved_accounts` and a sentence saying so. - **Failover**: the proxy walks the resulting list in order and skips cooled accounts, so quota failover obeys the same rule with no second code path. -- **Nothing recorded, nothing changes**: while no account is recorded with an - access, routing is exactly what it was. Orb then knows nothing and the - provider decides. Deploying this changes no mission until an account is marked. +- **Nothing recorded**: an ordinary request is routed exactly as before. A + request that asks for an access no account is recorded with is refused (see + above): Orb never guesses which login has it. - **API-key accounts** are outside the rule: they are neither marked nor filtered. The provider enforces access per key, as today. @@ -269,9 +280,13 @@ takes effect for missions started from mobile, but mobile does not show it. - `orb/tests/account-cyber-access.test.tsx`: the view model against the shared fixture; the switch, its confirmation, its rollback and Retry; the member view. -Missing: an HTTP contract test for the new endpoint and for `cyber_access` on -the list, and a proxy test that sends a `claude-mythos-*` and a -`gpt-5.6-cyber` request through `handleProxyRequest` with a marked account. +- `ProviderContractTests.lean`, VPN settings block: the HTTP contract of + `/api/ai/providers/:id/cyber-access` (member read, admin-only write, wrong + family, API-key account, unknown account, reserve round trip, clearing) and + `cyber_access` on the list. + +Missing: a proxy test that sends a `claude-mythos-*` and a `gpt-5.6-cyber` +request through `handleProxyRequest` with a marked account. ## Open questions diff --git a/lean/OrbCore/OrbCore/AccountVpnApi.lean b/lean/OrbCore/OrbCore/AccountVpnApi.lean index 45f82f6ee..c1842dd17 100644 --- a/lean/OrbCore/OrbCore/AccountVpnApi.lean +++ b/lean/OrbCore/OrbCore/AccountVpnApi.lean @@ -37,7 +37,8 @@ private def observed? (pool : AccountVpnPool.Pool) (account : String) (pref : Pr def route (store : CoreStore) (pool? : Option AccountVpnPool.Pool) (dir account provider : String) (canConfigure : Bool) (method : String) (body : ByteArray) - (configure? : Option (Bool → IO (Except String Unit)) := none) : IO (Nat × JVal) := do + (configure? : Option (Bool → IO (Except String Unit)) := none) + (accounts : Array (String × String) := #[]) : IO (Nat × JVal) := do let err := fun (code : Nat) (reason : String) => (code, JVal.obj #[("error", .str reason)]) if method != "GET" && method != "PUT" then return err 405 "method_not_allowed" if method == "PUT" then @@ -63,8 +64,13 @@ def route (store : CoreStore) (pool? : Option AccountVpnPool.Pool) (dir account fields := fields ++ #[("mode", .str "vpn"), ("country", .str pref.country)] let mut reason := "vpn_awaiting_verification" if dir.isEmpty || pool?.isNone then reason := "vpn_coordinator_unconfigured" - let blocked := fun cause => (200, JVal.obj (fields ++ #[("status", .str "blocked"), ("reason", .str cause), - ("message", .str (reasonMessage cause))])) + let (needed, configured) ← AccountVpnPool.exitDemand store.rootDir store.missionsDb accounts + (canonicalCategory provider) pref.country + let blocked := fun cause => + let note := if cause == "vpn_exit_in_use" || cause == "vpn_no_compatible_profile" then + AccountVpnPool.exitShortageNote needed configured pref.country else "" + (200, JVal.obj (fields ++ #[("status", .str "blocked"), ("reason", .str cause), + ("message", .str (if note.isEmpty then reasonMessage cause else note))])) if let some pool := pool? then if method == "PUT" then if let .error e ← AccountVpnPool.allocate pool store.rootDir dir store.missionsDb account provider pref then return blocked e diff --git a/lean/OrbCore/OrbCore/AccountVpnPool.lean b/lean/OrbCore/OrbCore/AccountVpnPool.lean index afe8b2c84..e5790f812 100644 --- a/lean/OrbCore/OrbCore/AccountVpnPool.lean +++ b/lean/OrbCore/OrbCore/AccountVpnPool.lean @@ -191,7 +191,11 @@ private def allocateLocked (root dir : String) (db : SqliteDb) (account provider for endpoint in candidates do if let some t := available.find? (fun a => a.endpoint.device == endpoint.device) then let ready := available.flatMap (fun a => a.occupants.map (·.binding)) - if (choose req ready [t.evidence]).isNone then continue + if (choose req ready [t.evidence]).isNone then + -- Another account of this category holds this exit. Try the next profile; if none is + -- left the answer is that the exit is in use, not that a profile is missing. + if failure == "vpn_no_compatible_profile" then failure := "vpn_exit_in_use" + continue let others := available.filter (fun a => a.tunnel.port != t.tunnel.port) if (← t.tunnel.verify root endpoint.server pref.country) == some t.evidence then match ← install dir db account cat pref t others with @@ -238,6 +242,28 @@ def allocate (pool : Pool) (root dir : String) (db : SqliteDb) (account provider (pref : Preference) : IO (Except String UInt16) := do return (← allocateGateway pool root dir db account provider pref).map (·.port) +/-- Exits a provider category needs in a country, and how many it can have there. Accounts of one +category never share an exit, so each enabled account routed to `country` needs its own; two device +profiles on one server share its exit, so only distinct configured servers count. `accounts` are the +enabled accounts as `(id, providerType)`. -/ +def exitDemand (root : String) (db : SqliteDb) (accounts : Array (String × String)) + (category country : String) : IO (Nat × Nat) := do + let mut needed := 0 + for (id, providerType) in accounts do + if canonicalCategory providerType == category then + if let .ok (some p) ← AccountVpnRoutes.read db id then + if p.country == country then needed := needed + 1 + let servers := (((← endpoints root).filter (·.country == country)).map (·.server)).eraseDups + return (needed, servers.length) + +/-- Sentence added to an exit refusal when the country has fewer servers than accounts need, empty +otherwise. -/ +def exitShortageNote (needed configured : Nat) (country : String) : String := + if needed ≤ configured then "" + else + let servers := if configured == 1 then "1 server is" else s!"{configured} servers are" + s!"{needed} accounts of this provider use {country}, and each needs its own exit, but only {servers} configured for {country}. Import a device profile for another {country} server in AirVPN Settings, or move one account to another country." + def resolve (pool? : Option Pool) (store : OrbCore.Store.CoreStore) (dir account : String) : OrbBin.HttpClient.ResolveTransport := AccountVpnRoutes.resolve store.missionsDb account fun pref => do diff --git a/lean/OrbCore/OrbCore/Control.lean b/lean/OrbCore/OrbCore/Control.lean index 3d2979397..c5fe3d1e7 100644 --- a/lean/OrbCore/OrbCore/Control.lean +++ b/lean/OrbCore/OrbCore/Control.lean @@ -2362,10 +2362,16 @@ private def handleProxyRequest (st : CoreAppState) (req : HttpRequest) (cleanPat | .ok rows => pure rows | .error _ => return mkJson 503 "{\"error\":\"cyber_access_store_unavailable\"}" let activeChain := applyCyberAccountPolicy prefsChain (accountAccessPairs cyberRows) cyberNeed? - if let some need := cyberNeed? then - if !prefsChain.targets.isEmpty && activeChain.targets.isEmpty then + (reservedAccountIds cyberRows) + if !prefsChain.targets.isEmpty && activeChain.targets.isEmpty then + match cyberNeed? with + | some need => return mkJson 403 (renderCompact (.obj #[ - ("error", .str "no_cyber_access_account"), ("message", .str (noCompatibleAccountMessage need))])) + ("error", .str "no_cyber_access_account"), + ("message", .str (noCompatibleAccountMessage need (cyberRows.any (·.access == need))))])) + | none => + return mkJson 403 (renderCompact (.obj #[ + ("error", .str "only_reserved_accounts"), ("message", .str onlyReservedAccountsMessage)])) let proxySecretBearer := !st.cfg.proxySecret.isEmpty && match extractBearerToken? req.headers nowEpochSec with @@ -3157,7 +3163,8 @@ private def resolveConfinedCoreMissionGitDir (st : CoreAppState) (m : MissionRec /-- Resolve proxy environment variables, CLI args, and model name for a local Core harness turn (`launchLocalCoreMissionTurn`). Routes router-backed harnesses (`opencode`, `claudecode`, `codex`, `grok`) through Core's local router when bound - and fails closed if `boundPort == 0` while any account VPN route is configured. + and fails closed if `boundPort == 0` while an account the harness could reach without the router + (`RemoteDispatch.harnessVpnCategory?`) has a VPN route. For native `antigravity`, binds the account's verified AirVPN SOCKS5 tunnel when VPN-routed and fails closed whenever the coordinator, tunnel, or binding is unavailable. -/ def resolveLocalCoreHarnessSetup @@ -3196,22 +3203,27 @@ def resolveLocalCoreHarnessSetup else pure #[] return .ok { s with env := s.env ++ hostEnv } else - match ← AccountVpnRoutes.anyVpnConfigured st.store.missionsDb with + -- Without the router the harness uses Core's own login of its provider: only a VPN route + -- on an account of that provider stops it (any account for OpenCode and Pi). + match ← OrbCore.RemoteDispatch.anyVpnConfiguredFor? st.store st.cfg.workingDir + (OrbCore.RemoteDispatch.harnessVpnCategory? normHarness) with | .error _ => return .error "local_harness_vpn_route_store_unavailable" | .ok true => return .error "local_harness_vpn_requires_router" | .ok false => return .ok { model := model? } else if normHarness == "antigravity" then let .ok bound? ← nativeMissionAccount? st.store missionId | return .error "antigravity_binding_unavailable" + let allocate := fun (acctId : String) (pref : AccountVpnRoutes.Preference) => do + match allocateVpn? with + | some fn => fn acctId pref + | none => + let some pool := st.vpnPool? + | return .error "antigravity_vpn_coordinator_unavailable" + AccountVpnPool.allocate pool st.store.rootDir st.vpnCoordinatorDir st.store.missionsDb acctId "antigravity" pref let allocateSocks := fun (acctId : String) (pref : AccountVpnRoutes.Preference) => do - let allocRes ← match allocateVpn? with - | some fn => fn acctId pref - | none => - let some pool := st.vpnPool? - | return .error "antigravity_vpn_coordinator_unavailable" - AccountVpnPool.allocate pool st.store.rootDir st.vpnCoordinatorDir st.store.missionsDb acctId "antigravity" pref - match allocRes with - | .error e => return .error s!"antigravity_vpn_unavailable:{e}" + match ← allocate acctId pref with + | .error e => + return .error (if e.startsWith "antigravity_" then e else s!"antigravity_vpn_unavailable:{e}") | .ok _ => let some proxyUrl := st.vpnRelayPort?.bind (fun port => AccountVpnRelay.proxyUrl (effectiveJwtSecret st.cfg) port "antigravity" acctId "127.0.0.1" "socks5h") @@ -3240,26 +3252,36 @@ def resolveLocalCoreHarnessSetup let hydrated ← loadHydratedProviders st.store st.cfg.workingDir let agAccounts := hydrated.filter (·.providerType == "antigravity") let mut anyVpn := false - let mut enabledVpn : Array (String × AccountVpnRoutes.Preference) := #[] - let mut enabledCount : Nat := 0 for hp in agAccounts do match ← AccountVpnRoutes.snapshot st.store.missionsDb hp.id with | .error _ => return .error "antigravity_vpn_route_store_unavailable" - | .ok (.direct _) => - if hp.enabled then enabledCount := enabledCount + 1 - | .ok (.vpn pref) => - anyVpn := true - if hp.enabled then - enabledCount := enabledCount + 1 - enabledVpn := enabledVpn.push (hp.id, pref) + | .ok (.vpn _) => anyVpn := true + | .ok (.direct _) => pure () if !anyVpn then return .ok { model := model? } - if enabledCount == 1 && enabledVpn.size == 1 then - match enabledVpn[0]? with - | some (acctId, pref) => allocateSocks acctId pref - | none => return .error "antigravity_vpn_requires_account_binding" - else - return .error "antigravity_vpn_requires_account_binding" + -- With a VPN route on any account, the host's own login could be that account (or another + -- one) reaching Google from Core's address. Choose the account as node dispatch does, in + -- priority order, passing over one whose route cannot be had now, and run as that account + -- with its own login and, when VPN-routed, only through its exit. + let prefs ← getUserProviderPrefs st.store ownerUserId + let candidates := agAccounts.filter fun hp => hp.enabled && isUserProviderEnabled prefs hp.id + let vpnBlocked := fun (acctId : String) => do + match ← AccountVpnRoutes.read st.store.missionsDb acctId with + | .ok (some pref) => return (← allocate acctId pref).toOption.isNone + | _ => return false + let some hp ← OrbCore.RemoteDispatch.chooseAntigravityAccount? st.store st.providerHub? nowSec + candidates vpnBlocked + | return .error "antigravity_vpn_requires_account_binding" + let route ← match ← AccountVpnRoutes.read st.store.missionsDb hp.id with + | .ok r => pure r + | .error _ => return .error "antigravity_vpn_route_store_unavailable" + let routed ← match route with + | some pref => allocateSocks hp.id pref + | none => pure (.ok { model := model? }) + let .ok setup := routed | return routed + match ← OrbCore.RemoteDispatch.installCoreHostAntigravityLogin st.store.rootDir missionId hp.boundOauthFile with + | .error e => return .error e + | .ok home => return .ok { setup with env := setup.env.push ("HOME", home) } else return .ok { model := model? } @@ -3583,9 +3605,28 @@ private def launchRefusalHttpStatus (error : String) : Nat := if error.startsWith "antigravity_" || error.startsWith "native_" then 409 else remoteDispatchHttpStatus error +/-- When a refusal is an Antigravity VPN exit in use, the sentence saying how many exits the + accounts need against the servers configured, for the first country that has too few. -/ +private def vpnExitShortageNote (st : CoreAppState) (error : String) : IO String := do + unless error == "antigravity_vpn_unavailable:vpn_exit_in_use" do return "" + let accounts := ((← loadHydratedProviders st.store st.cfg.workingDir).filter + (fun p => p.enabled && Orb.AccountVpn.canonicalCategory p.providerType == "google")).map + (fun p => (p.id, p.providerType)) + let mut seen : Array String := #[] + for (id, _) in accounts do + if let .ok (some pref) ← AccountVpnRoutes.read st.store.missionsDb id then + unless seen.contains pref.country do + seen := seen.push pref.country + let (needed, configured) ← AccountVpnPool.exitDemand st.store.rootDir st.store.missionsDb + accounts "google" pref.country + let note := AccountVpnPool.exitShortageNote needed configured pref.country + if !note.isEmpty then return note + return "" + /-- Body of a refused remote dispatch. A VPN route that is only temporarily unavailable is - explained in plain words and carries `retry_after_secs`; `error` keeps the code. -/ -private def remoteDispatchErrorBody (error : String) : String := + explained in plain words and carries `retry_after_secs`; `error` keeps the code. `exitNote` + (`vpnExitShortageNote`) says when the accounts need more exits than are configured. -/ +private def remoteDispatchErrorBody (error : String) (exitNote : String := "") : String := let vpnPrefix := "antigravity_vpn_unavailable:" let reason := if error.startsWith vpnPrefix then (error.drop vpnPrefix.length).toString else "" match OrbCore.AccountVpnPool.transientRetrySecs? reason with @@ -3599,7 +3640,8 @@ private def remoteDispatchErrorBody (error : String) : String := let wait := if secs < 90 then s!"{secs} seconds" else s!"{(secs + 59) / 60} minutes" renderCompact (.obj #[ ("error", .str error), - ("message", .str s!"{cause}, and no other Antigravity account can take this request. Nothing was started. Try again in about {wait}."), + ("message", .str (s!"{cause}, and no other Antigravity account can take this request. Nothing was started. Try again in about {wait}." ++ + (if exitNote.isEmpty then "" else " " ++ exitNote))), ("retry_after_secs", .num (toString secs))]) private def hungNodeJsonBody (nodeId cause : String) : String := @@ -3752,7 +3794,7 @@ private def launchBtwSideAgent (st : CoreAppState) (caller : CallerPrincipal) (s discard <| runConfiguredManagedLifecycle mst { store := st.store, fleet := mf0, override? := st.managedProvisioningOverride? } rentedVmId "destroy" nowEpochSec cleanupUnbornBtw - return (launchRefusalHttpStatus dispErr, remoteDispatchErrorBody dispErr) + return (launchRefusalHttpStatus dispErr, remoteDispatchErrorBody dispErr (← vpnExitShortageNote st dispErr)) | none => if st.warmMgr?.isSome then let effModel := @@ -5543,13 +5585,22 @@ private def dispatchCoreRequestRaw (st : CoreAppState) (req : HttpRequest) (nowE unless isAdm do return .ok (mkJson 403 "{\"error\":\"admin_required\"}") let body := req.bodySlice.toByteArray if body.size > 1024 then return .ok (mkJson 413 "{\"error\":\"request_too_large\"}") - let some access := ((OrbBin.Json.parseBytes body).toOption.bind (fun j => j.fieldStr? "access")).bind parseAccountAccess? + let parsed? := (OrbBin.Json.parseBytes body).toOption + let some access := (parsed?.bind (fun j => j.fieldStr? "access")).bind parseAccountAccess? | return .ok (mkJson 400 "{\"error\":\"invalid_cyber_access\"}") unless access == "none" || access == available do return .ok (mkJson 400 "{\"error\":\"cyber_access_not_applicable\"}") - if let .error _ ← setAccountAccess st.store account access "operator" (formatEpochIso8601Utc nowEpochSec) then + -- `reserved` is optional: absent keeps the saved choice, and only a marked account holds one. + let reserved? ← match parsed?.bind (·.field? "reserved") with + | none | some .null => pure none + | some (.bool b) => pure (some b) + | some _ => return .ok (mkJson 400 "{\"error\":\"invalid_cyber_access\"}") + if access == "none" && reserved? == some true then + return .ok (mkJson 400 "{\"error\":\"cyber_access_reserve_needs_mark\"}") + if let .error _ ← setAccountAccess st.store account access "operator" (formatEpochIso8601Utc nowEpochSec) reserved? then return .ok (mkJson 503 "{\"error\":\"cyber_access_store_unavailable\"}") - appendProviderAuditLog st.store caller.userId "admin" "edit" account #["cyber_access"] s!"{nowEpochSec}" + let fields := if reserved?.isSome then #["cyber_access", "cyber_access_reserved"] else #["cyber_access"] + appendProviderAuditLog st.store caller.userId "admin" "edit" account fields s!"{nowEpochSec}" else if req.method != "GET" then return .ok (mkJson 405 "{\"error\":\"method_not_allowed\"}") let cyberRows ← match ← listAccountAccess st.store with @@ -5603,6 +5654,7 @@ private def dispatchCoreRequestRaw (st : CoreAppState) (req : HttpRequest) (nowE configure? := some (AccountVpnSidecar.configure base key file url) let (status, result) ← AccountVpnApi.route st.store st.vpnPool? st.vpnCoordinatorDir account hp.providerType (coreOwned || configure?.isSome) req.method req.bodySlice.toByteArray configure? + ((providers.filter (·.enabled)).map (fun p => (p.id, p.providerType))) if req.method == "PUT" && status == 200 then let refreshed ← loadRoutingChainsFromStore st.store st.cfg.workingDir discard <| publishRoutingChainsUpdate st refreshed @@ -6609,7 +6661,7 @@ private def dispatchCoreRequestRaw (st : CoreAppState) (req : HttpRequest) (nowE discard <| runConfiguredManagedLifecycle mst { store := st.store, fleet := mf0, override? := st.managedProvisioningOverride? } rentedVmId "destroy" nowEpochSec cleanupUnbornFork - return .ok (mkJson (launchRefusalHttpStatus dispErr) (remoteDispatchErrorBody dispErr)) + return .ok (mkJson (launchRefusalHttpStatus dispErr) (remoteDispatchErrorBody dispErr (← vpnExitShortageNote st dispErr))) | _, none => let effModel := if (out.backend == "opencode" || out.backend == "pi") && out.modelOverride.trimAscii.toString.isEmpty then "builtin/smart" @@ -7240,7 +7292,7 @@ private def dispatchCoreRequestRaw (st : CoreAppState) (req : HttpRequest) (nowE discard <| runConfiguredManagedLifecycle mst { store := st.store, fleet := mf0, override? := st.managedProvisioningOverride? } rentedVmId "destroy" nowEpochSec let refusalStatus := launchRefusalHttpStatus dispErr - let refusalBody := remoteDispatchErrorBody dispErr + let refusalBody := remoteDispatchErrorBody dispErr (← vpnExitShortageNote st dispErr) rollbackUnbornCreate refusalStatus refusalBody return .ok (mkJson refusalStatus refusalBody) if controller then @@ -7683,7 +7735,7 @@ private def dispatchCoreRequestRaw (st : CoreAppState) (req : HttpRequest) (nowE let mf0 ← st.managedRef.get discard <| runConfiguredManagedLifecycle mst { store := st.store, fleet := mf0, override? := st.managedProvisioningOverride? } rentedVmId "destroy" nowEpochSec - return .ok (mkJson (remoteDispatchHttpStatus dispErr) (remoteDispatchErrorBody dispErr)) + return .ok (mkJson (remoteDispatchHttpStatus dispErr) (remoteDispatchErrorBody dispErr (← vpnExitShortageNote st dispErr))) | _, _ => discard <| appendMissionEvent st.store mid "user_message" pl nowIso if let some tSink := st.telemetrySink? then @@ -9116,7 +9168,7 @@ private def dispatchCoreRequestRaw (st : CoreAppState) (req : HttpRequest) (nowE dispErr.startsWith "remote_accept_persist_failed:")) then if keyed && rentedVmId.isEmpty && !dispErr.startsWith "remote_dispatch_uncertain:" && !dispErr.startsWith "remote_accept_persist_failed:" then discard <| abortIdempotencySlot st.store receiptScope msgId - return .ok (mkJson (remoteDispatchHttpStatus dispErr) (remoteDispatchErrorBody dispErr)) + return .ok (mkJson (remoteDispatchHttpStatus dispErr) (remoteDispatchErrorBody dispErr (← vpnExitShortageNote st dispErr))) else if let some m := mission? then let localSend := (bodyJv.fieldBool? "spawn_harness").getD (m.placementKind == "managed" && !isCloudBackendName m.backend) @@ -9313,7 +9365,7 @@ private def dispatchCoreRequestRaw (st : CoreAppState) (req : HttpRequest) (nowE let mf0 ← st.managedRef.get discard <| runConfiguredManagedLifecycle mst { store := st.store, fleet := mf0, override? := st.managedProvisioningOverride? } rentedVmId "destroy" nowEpochSec - return .ok (mkJson (remoteDispatchHttpStatus dispErr) (remoteDispatchErrorBody dispErr)) + return .ok (mkJson (remoteDispatchHttpStatus dispErr) (remoteDispatchErrorBody dispErr (← vpnExitShortageNote st dispErr))) else let spawnWanted := (bodyJv.fieldBool? "spawn_harness").getD false if spawnWanted then diff --git a/lean/OrbCore/OrbCore/Cyber.lean b/lean/OrbCore/OrbCore/Cyber.lean index 557f8dd5a..fda64b5ca 100644 --- a/lean/OrbCore/OrbCore/Cyber.lean +++ b/lean/OrbCore/OrbCore/Cyber.lean @@ -425,20 +425,31 @@ def requiredAccountAccess? (model : String) (program? : Option String) : Option def accountAccessLabel (access : String) : String := if access == "cvp" then "CVP" else if access == "daybreak" then "Daybreak" else access -/-- Shown when a request needs an access no usable account is recorded with. -/ -def noCompatibleAccountMessage (access : String) : String := - s!"This request needs {accountAccessLabel access} access, and no enabled subscription account recorded with {accountAccessLabel access} is available to you. Mark the account in Settings, Inference, or choose another model. Nothing was sent to another account." +/-- Shown when a request needs an access no usable account is recorded with. `anyMarked`: some + account is recorded with the access, but none that may serve this request is available. -/ +def noCompatibleAccountMessage (access : String) (anyMarked : Bool := true) : String := + let label := accountAccessLabel access + if anyMarked then + s!"This request needs {label} access, and no enabled subscription account recorded with {label} is available to you. Mark the account in Settings, Inference, or choose another model. Nothing was sent to another account." + else + s!"This request needs {label} access, and no subscription account is marked with {label}. Mark the account that has it in Settings, Inference, or choose another model. Nothing was sent to another account." + +/-- Shown when an ordinary request finds only accounts kept for Daybreak/CVP requests. -/ +def onlyReservedAccountsMessage : String := + "Every subscription account that serves this model is kept for Daybreak or CVP requests. Turn off \"Keep for marked requests\" on one of them in Settings, Inference, or choose another model. Nothing was sent." structure AccountAccessRow where accountId : String access : String source : String updatedAt : String + /-- Ordinary requests never use this account (`Proxy.applyCyberAccountPolicy`). -/ + reserved : Bool := false deriving Repr, DecidableEq, Inhabited def listAccountAccess (st : CoreStore) : IO (Except String (Array AccountAccessRow)) := do match ← execParamQuery st.missionsDb - "SELECT account_id, access, source, updated_at FROM account_cyber_access;" #[] with + "SELECT account_id, access, source, updated_at, CAST(reserved AS TEXT) FROM account_cyber_access;" #[] with | .error e => return .error e | .ok rows => let mut out : Array AccountAccessRow := #[] @@ -446,24 +457,32 @@ def listAccountAccess (st : CoreStore) : IO (Except String (Array AccountAccessR let r := rows[i]! out := out.push { accountId := (r[0]?).getD "", access := (r[1]?).getD "", - source := (r[2]?).getD "", updatedAt := (r[3]?).getD "" } + source := (r[2]?).getD "", updatedAt := (r[3]?).getD "", reserved := (r[4]?).getD "0" == "1" } return .ok out /-- `(accountId, access)` pairs in the shape `OrbCore.Proxy.applyCyberAccountPolicy` reads. -/ def accountAccessPairs (rows : Array AccountAccessRow) : Array (String × String) := rows.map (fun r => (r.accountId, r.access)) +/-- Accounts that ordinary requests never use, in the shape `applyCyberAccountPolicy` reads. -/ +def reservedAccountIds (rows : Array AccountAccessRow) : Array String := + (rows.filter (·.reserved)).map (·.accountId) + /-- Record or clear (`access = "none"`) an account's access. `source` is `operator` or `detected`. -/ -def setAccountAccess (st : CoreStore) (accountId access source updatedAt : String) : - IO (Except String Unit) := do +def setAccountAccess (st : CoreStore) (accountId access source updatedAt : String) + (reserved? : Option Bool := none) : IO (Except String Unit) := do let res ← if access == "none" then execParamQuery st.missionsDb "DELETE FROM account_cyber_access WHERE account_id=?1;" #[accountId] else + -- `reserved? = none` keeps the saved choice; a new row starts unreserved. + let flag := match reserved? with | some true => "1" | some false => "0" | none => "" execParamQuery st.missionsDb - ("INSERT INTO account_cyber_access(account_id,access,source,updated_at) VALUES(?1,?2,?3,?4) " ++ - "ON CONFLICT(account_id) DO UPDATE SET access=excluded.access, source=excluded.source, updated_at=excluded.updated_at;") - #[accountId, access, source, updatedAt] + ("INSERT INTO account_cyber_access(account_id,access,source,updated_at,reserved) " ++ + "VALUES(?1,?2,?3,?4,CASE WHEN ?5='1' THEN 1 ELSE 0 END) " ++ + "ON CONFLICT(account_id) DO UPDATE SET access=excluded.access, source=excluded.source, updated_at=excluded.updated_at, " ++ + "reserved=CASE WHEN ?5='' THEN account_cyber_access.reserved ELSE excluded.reserved END;") + #[accountId, access, source, updatedAt, flag] return res.map (fun _ => ()) /-- The `cyber_access` object of a provider row. `available` is the access this account's @@ -472,10 +491,10 @@ def accountAccessJv (available : String) (row? : Option AccountAccessRow) : JVal match row? with | some r => .obj #[("access", .str r.access), ("available", .str available), - ("source", .str r.source), ("updated_at", .str r.updatedAt)] + ("source", .str r.source), ("updated_at", .str r.updatedAt), ("reserved", .bool r.reserved)] | none => .obj #[("access", .str "none"), ("available", .str available), - ("source", .null), ("updated_at", .null)] + ("source", .null), ("updated_at", .null), ("reserved", .bool false)] /-- Validate Codex `/goal` prompt shape (`non-empty objective` and `no images`) via `orb_codex_goal_launch_step`. -/ def validateGoalMessage (prompt : String) (hasImages : Bool) : Except String Unit := do diff --git a/lean/OrbCore/OrbCore/HarnessProxyTests.lean b/lean/OrbCore/OrbCore/HarnessProxyTests.lean index ec249de93..a5da5d455 100644 --- a/lean/OrbCore/OrbCore/HarnessProxyTests.lean +++ b/lean/OrbCore/OrbCore/HarnessProxyTests.lean @@ -80,13 +80,18 @@ def run : IO Unit := do IO.ofExcept (← OrbCore.Store.upsertAIProvider store { id := "xai-vpn-1", name := "xAI VPN", providerType := "xai", apiKey := "fixture-only" }) - check ((← anyXaiVpnConfigured? store root).toOption == some false) + check ((← anyVpnConfiguredFor? store root (harnessVpnCategory? "grok")).toOption == some false) "Direct xAI account allows fallback check" IO.ofExcept (← OrbCore.AccountVpnRoutes.set store.missionsDb "xai-vpn-1" (some "NL")) - check ((← anyXaiVpnConfigured? store root).toOption == some true) + check ((← anyVpnConfiguredFor? store root (harnessVpnCategory? "grok")).toOption == some true) "VPN-routed xAI account blocks direct Grok managedAuth fallback" + -- An xAI route blocks only harnesses that can reach xAI without the router. + check ((← anyVpnConfiguredFor? store root (harnessVpnCategory? "claudecode")).toOption == some false && + (← anyVpnConfiguredFor? store root (harnessVpnCategory? "codex")).toOption == some false && + (← anyVpnConfiguredFor? store root (harnessVpnCategory? "opencode")).toOption == some true) + "a VPN route of one provider does not block a harness of another provider" IO.ofExcept (← OrbCore.AccountVpnRoutes.set store.missionsDb "xai-vpn-1" none) - check ((← anyXaiVpnConfigured? store root).toOption == some false) + check ((← anyVpnConfiguredFor? store root (harnessVpnCategory? "grok")).toOption == some false) "Switching xAI account back to Direct clears VPN block" finally OrbCore.Store.closeCoreStore store diff --git a/lean/OrbCore/OrbCore/ProviderContractTests.lean b/lean/OrbCore/OrbCore/ProviderContractTests.lean index 5e10a7474..a5c75bd74 100644 --- a/lean/OrbCore/OrbCore/ProviderContractTests.lean +++ b/lean/OrbCore/OrbCore/ProviderContractTests.lean @@ -2459,11 +2459,25 @@ private def v2RoutingEndToEndContract -- Request that needs Daybreak: only the recorded account, pinned; the API-key fallback stays. ids cyberTrio == #["oa-1", "or-1"] && (cyberTrio.targets[0]?.bind (·.sidecarCredential?)) == some oaCred1 && - -- Nothing recorded, or nothing recorded with the needed access: unchanged. + -- Nothing recorded: an ordinary request is unchanged. applyCyberAccountPolicy oaTrio #[] none == oaTrio && - applyCyberAccountPolicy oaTrio #[] (some "daybreak") == oaTrio && - applyCyberAccountPolicy oaTrio #[("claude-1", "cvp")] (some "daybreak") == oaTrio && applyCyberAccountPolicy oaTrio #[("claude-1", "cvp")] none == oaTrio && + -- Nothing recorded with the needed access: no subscription account is guessed (the caller + -- answers `403 no_cyber_access_account`); the API-key target of another provider stays. + ids (applyCyberAccountPolicy oaTrio #[] (some "daybreak")) == #["or-1"] && + ids (applyCyberAccountPolicy oaTrio #[("claude-1", "cvp")] (some "daybreak")) == #["or-1"] && + (applyCyberAccountPolicy { oaTrio with targets := #[oaTarget3] } #[] (some "daybreak")).targets.isEmpty && + -- Reserved for marked requests: an ordinary request never reaches the reserved account, + -- even as the last resort; a request that needs the access still gets it. + ids (applyCyberAccountPolicy oaTrio daybreakOnFirst none #["oa-1"]) == #["oa-2", "oa-3", "or-1"] && + ids (applyCyberAccountPolicy oaTrio daybreakOnFirst (some "daybreak") #["oa-1"]) == #["oa-1", "or-1"] && + -- A reserve on an unmarked account means nothing. + applyCyberAccountPolicy oaTrio #[] none #["oa-1"] == oaTrio && + -- Every account reserved: nothing is left for an ordinary request (the caller answers 403). + (applyCyberAccountPolicy { oaTrio with targets := #[oaTarget3] } + #[("oa-1", "daybreak"), ("oa-2", "daybreak"), ("oa-3", "daybreak")] none #["oa-1", "oa-2", "oa-3"]).targets.isEmpty && + -- A pool that cannot be split while one login is reserved is dropped, never sent whole. + (applyCyberAccountPolicy oaUnprefixedChain daybreakOnFirst none #["oa-1"]).targets.isEmpty && -- Every account is special: an ordinary request falls back to them rather than failing. ids (applyCyberAccountPolicy oaTrio #[("oa-1", "daybreak"), ("oa-2", "daybreak"), ("oa-3", "daybreak")] none) == #["cliproxyapi:openai", "or-1"] && @@ -2666,6 +2680,8 @@ private def v1LocalHarnessAndChainRefreshContract let agId := "v1-refresh-ag" let agFile := "antigravity-v1-refresh.json" let agPath := s!"{root}/auth-empty/{agFile}" + let agId2 := "v1-second-ag" + let agFile2 := "antigravity-v1-second.json" let staleLegId := "v1-stale-legacy-openai" let liveCodexFile := "codex-live-v1.json" let liveCodexPath := s!"{root}/auth-empty/{liveCodexFile}" @@ -2692,8 +2708,17 @@ private def v1LocalHarnessAndChainRefreshContract -- alongside a disabled Antigravity row (verifying unbound local turns resolve enabled logins). let updatedOrig := origArr.map fun row => if row.fieldStr? "provider_type" == some "antigravity" then row.setField "enabled" (.bool false) else row - IO.FS.writeFile s!"{root}/.sandboxed-sh/ai_providers.json" - (renderCompact (.arr ((updatedOrig.push agLegacy).push staleLegacy))) + -- A second Antigravity login, disabled until the account-choice replay below enables it. + IO.FS.writeFile s!"{root}/auth-empty/{agFile2}" + "{\"type\":\"antigravity\",\"email\":\"v1-second@fixture.invalid\",\"access_token\":\"fixture-tok-2\",\"refresh_token\":\"fixture-refresh-2\",\"timestamp\":1700000000000,\"expires_in\":3600}" + let agLegacy2 := fun (enabled : Bool) => JVal.obj #[ + ("id", .str agId2), ("provider_type", .str "antigravity"), ("name", .str "V1 Second AG"), + ("enabled", .bool enabled), ("cli_proxy_auth_file", .str agFile2) + ] + let writeProviders := fun (secondEnabled : Bool) => + IO.FS.writeFile s!"{root}/.sandboxed-sh/ai_providers.json" + (renderCompact (.arr (((updatedOrig.push agLegacy).push staleLegacy).push (agLegacy2 secondEnabled)))) + writeProviders false IO.ofExcept (← upsertAIProvider store { id := agId, providerType := "antigravity", name := "V1 Refresh AG", enabled := true, apiKey := "cli-proxy-managed", updatedAt := "1700001000" @@ -2732,13 +2757,28 @@ private def v1LocalHarnessAndChainRefreshContract if !hasBase || !hasKey || setup.model != some "grok-4" then failures := failures.push s!"v1 local grok setup mismatch: env={setup.env} model={setup.model}" if let some t := tok? then revokeSingleMissionProxyToken store t - -- With a VPN route configured, `boundPort == 0` fails closed for router-backed harnesses. - IO.ofExcept (← AccountVpnRoutes.set store.missionsDb xaiId (some "NL")) - for h in #["Grok", "claudecode", "codex", "opencode"] do + -- With a VPN route configured, `boundPort == 0` fails closed for a harness that could reach + -- that account's provider without the router, and only for it. Replays the refusal order of + -- 30 Nov 2026: an xAI route used to refuse every local Claude Code and Codex mission. + let localNoRouter := fun (h : String) => do tokRef.set none - match ← resolveLocalCoreHarnessSetup app "v1-mid" "" h "" 0 now tokRef with + resolveLocalCoreHarnessSetup app "v1-mid" "" h "" 0 now tokRef + IO.ofExcept (← AccountVpnRoutes.set store.missionsDb xaiId (some "NL")) + for h in #["Grok", "opencode", "pi"] do + match ← localNoRouter h with | .error "local_harness_vpn_requires_router" => pure () - | other => failures := failures.push s!"v1 local {h} boundPort=0 with VPN must fail closed, got {other.isOk}" + | other => failures := failures.push s!"v1 local {h} boundPort=0 with an xAI VPN must fail closed, got {other.isOk}" + for h in #["claudecode", "codex"] do + unless (← localNoRouter h).isOk do + failures := failures.push s!"v1 local {h} boundPort=0 must not be refused for an xAI account's VPN" + -- A ChatGPT route then stops Codex, still not Claude Code. + IO.ofExcept (← AccountVpnRoutes.set store.missionsDb liveCodexId (some "NL")) + match ← localNoRouter "codex" with + | .error "local_harness_vpn_requires_router" => pure () + | other => failures := failures.push s!"v1 local codex boundPort=0 with a ChatGPT VPN must fail closed, got {other.isOk}" + unless (← localNoRouter "claudecode").isOk do + failures := failures.push "v1 local claudecode boundPort=0 must not be refused for a ChatGPT account's VPN" + IO.ofExcept (← AccountVpnRoutes.set store.missionsDb liveCodexId none) IO.ofExcept (← AccountVpnRoutes.set store.missionsDb xaiId none) -- Bound local `antigravity` mission + unbound with 1 enabled VPN login alongside a disabled login. let boundJob ← startNativeFixtureJob store boundMid @@ -2768,6 +2808,42 @@ private def v1LocalHarnessAndChainRefreshContract if !okRelay || setup.env.any (fun kv => (kv.2.splitOn ":39999").length > 1) then failures := failures.push s!"v1 bound local antigravity must use authenticated socks5h AccountVpnRelay URL, got {setup.env}" revokeSingleMissionProxyToken store boundTok + -- (e) Refusal order of 30 Nov 2026, unbound Core-host turn with two enabled Antigravity accounts: + -- the first is VPN-routed and its exit is in use. It used to fail with + -- `antigravity_vpn_requires_account_binding`; the next account takes the turn, with its own + -- login in the mission's private home and no proxy (it is Direct). + writeProviders true + let busyFirst : String → AccountVpnRoutes.Preference → IO (Except String UInt16) := fun acct _ => + pure (if acct == agId then .error "vpn_exit_in_use" else .ok 39999) + let agyHome := s!"{root}/core-turns/agy-home/v1-unbound-mid" + match ← resolveLocalCoreHarnessSetup { app with vpnRelayPort? := some 43210 } "v1-unbound-mid" "" "antigravity" + "gemini-4-carbon" 3123 now tokRef (some busyFirst) with + | .error e => failures := failures.push s!"v1 local antigravity must pass over a busy VPN account, got {e}" + | .ok setup => + let token ← IO.FS.readFile s!"{agyHome}/.gemini/antigravity-cli/antigravity-oauth-token" + unless setup.env.contains ("HOME", agyHome) && !setup.env.any (·.1 == "HTTPS_PROXY") && + (token.splitOn "fixture-refresh-2").length == 2 && (token.splitOn "fixture-tok\"").length == 1 do + failures := failures.push s!"v1 local antigravity must run as the next account with its own login: {setup.env}" + -- (f) Both VPN-routed and both exits in use: refused, naming the first account's route. + IO.ofExcept (← AccountVpnRoutes.set store.missionsDb agId2 (some "CH")) + let allBusy : String → AccountVpnRoutes.Preference → IO (Except String UInt16) := fun _ _ => + pure (.error "vpn_exit_in_use") + match ← resolveLocalCoreHarnessSetup { app with vpnRelayPort? := some 43210 } "v1-unbound-mid" "" "antigravity" + "gemini-4-carbon" 3123 now tokRef (some allBusy) with + | .error "antigravity_vpn_unavailable:vpn_exit_in_use" => pure () + | other => failures := failures.push s!"v1 local antigravity with every exit in use must be refused with the route, got {other.isOk}" + -- (g) The second account's exit is free: it runs through its own relay URL, as itself. + let busyFirstOnly : String → AccountVpnRoutes.Preference → IO (Except String UInt16) := fun acct _ => + pure (if acct == agId then .error "airvpn_device_in_use" else .ok 39999) + let expectedRelay2? := AccountVpnRelay.proxyUrl app.cfg.jwtSecret 43210 "antigravity" agId2 "127.0.0.1" "socks5h" + match ← resolveLocalCoreHarnessSetup { app with vpnRelayPort? := some 43210 } "v1-unbound-mid" "" "antigravity" + "gemini-4-carbon" 3123 now tokRef (some busyFirstOnly) with + | .error e => failures := failures.push s!"v1 local antigravity must use the next VPN account, got {e}" + | .ok setup => + unless expectedRelay2?.any (fun u => setup.env.contains ("HTTPS_PROXY", u)) && setup.env.contains ("HOME", agyHome) do + failures := failures.push s!"v1 local antigravity next VPN account must use its own relay and login: {setup.env}" + IO.ofExcept (← AccountVpnRoutes.set store.missionsDb agId2 none) + writeProviders false IO.ofExcept (← AccountVpnRoutes.set store.missionsDb agId none) -- When all routes are Direct, local `grok` (boundPort=0) and `antigravity` succeed. discard <| execParamQuery store.missionsDb "DELETE FROM account_vpn_routes;" #[] @@ -5646,6 +5722,45 @@ def run : IO Unit := do unless memberCode == 200 && saved.fieldStr? "country" == some "NL" && adminView.fieldStr? "country" == some "NL" do failures := failures.push "An administrator must see the shared country saved by a member" + -- `/api/ai/providers/:id/cyber-access` (`docs/specs/subscription-cyber-access.md`): anyone + -- who sees the account reads the mark; only an admin sets it or reserves the account. + let subRow : AIProviderRecord := { + id := "cyber-sub-fixture", name := "Codex subscription fixture", providerType := "openai", + enabled := true, apiKey := "cli-proxy-managed" } + IO.ofExcept (← upsertAIProvider store subRow) + let cyberRoute := s!"/api/ai/providers/{subRow.id}/cyber-access" + let unmarked ← getJson app memberJwt cyberRoute now + unless unmarked.fieldStr? "access" == some "none" && unmarked.fieldStr? "available" == some "daybreak" && + unmarked.fieldBool? "reserved" == some false && (unmarked.field? "source") == some .null do + failures := failures.push s!"cyber-access GET of an unmarked account: {renderCompact unmarked}" + let (memberPut, _) ← putJson app memberJwt cyberRoute "{\"access\":\"daybreak\"}" now + let (wrongFamily, wrongBody) ← putJson app jwt cyberRoute "{\"access\":\"cvp\"}" now + let (badBody, _) ← putJson app jwt cyberRoute "{\"access\":\"maybe\"}" now + let (reserveUnmarked, _) ← putJson app jwt cyberRoute "{\"access\":\"none\",\"reserved\":true}" now + let (apiKeyPut, _) ← putJson app jwt s!"/api/ai/providers/{ownerRow.id}/cyber-access" "{\"access\":\"daybreak\"}" now + let (missingPut, _) ← putJson app jwt "/api/ai/providers/missing-account/cyber-access" "{\"access\":\"daybreak\"}" now + let (anonPut, _) ← putJson app "" cyberRoute "{\"access\":\"daybreak\"}" now + unless memberPut == 403 && wrongFamily == 400 && wrongBody.fieldStr? "error" == some "cyber_access_not_applicable" && + badBody == 400 && reserveUnmarked == 400 && apiKeyPut == 409 && missingPut == 404 && anonPut == 401 do + failures := failures.push s!"cyber-access PUT refusals: member={memberPut} family={wrongFamily} bad={badBody} reserveUnmarked={reserveUnmarked} apiKey={apiKeyPut} missing={missingPut} anon={anonPut}" + let (markCode, marked) ← putJson app jwt cyberRoute "{\"access\":\"daybreak\",\"reserved\":true}" now + let (remarkCode, remarked) ← putJson app jwt cyberRoute "{\"access\":\"daybreak\"}" now + let memberView ← getJson app memberJwt cyberRoute now + let listed := (((← getJson app memberJwt "/api/ai/providers" now).asArr?.getD #[]).find? + (·.fieldStr? "id" == some subRow.id)).bind (·.field? "cyber_access") + unless markCode == 200 && marked.fieldStr? "access" == some "daybreak" && marked.fieldStr? "source" == some "operator" && + marked.fieldBool? "reserved" == some true && + -- A PUT without `reserved` keeps the saved choice. + remarkCode == 200 && remarked.fieldBool? "reserved" == some true && + memberView == remarked && listed == some remarked do + failures := failures.push s!"cyber-access mark/reserve round trip: {markCode} {renderCompact marked} {remarkCode} {renderCompact remarked} list={listed.map renderCompact}" + let (clearCode, cleared) ← putJson app jwt cyberRoute "{\"access\":\"none\"}" now + let (remark2, again) ← putJson app jwt cyberRoute "{\"access\":\"daybreak\"}" now + unless clearCode == 200 && cleared.fieldStr? "access" == some "none" && cleared.fieldBool? "reserved" == some false && + -- Clearing the mark also clears the reserve: marking again starts unreserved. + remark2 == 200 && again.fieldBool? "reserved" == some false do + failures := failures.push s!"cyber-access clear: {clearCode} {renderCompact cleared} {remark2} {renderCompact again}" + discard <| putJson app jwt cyberRoute "{\"access\":\"none\"}" now let configuredIdentities := fun (session : String) => do let rows := (← getJson app session "/api/ai/providers" now).asArr?.getD #[] return (rows.filter (·.fieldBool? "has_credentials" == some true)).map fun row => diff --git a/lean/OrbCore/OrbCore/Proxy.lean b/lean/OrbCore/OrbCore/Proxy.lean index 06fbf5cc0..c8439c5d0 100644 --- a/lean/OrbCore/OrbCore/Proxy.lean +++ b/lean/OrbCore/OrbCore/Proxy.lean @@ -4005,47 +4005,54 @@ def targetUnpinnedModel (tgt : ProviderTarget) : String := /-- The one place subscription accounts are ordered or excluded by cyber access. - * `need? = some access` (the request asks for that access): once any account is recorded with - it, subscription targets keep only the accounts recorded with it. A pooled target is narrowed - to those accounts; one that cannot be narrowed is dropped. API-key targets are left alone. - While no account is recorded with it, the chain is unchanged: Orb then knows nothing and the - provider decides. - * `need? = none` (an ordinary request): accounts without special access are tried first and - the special ones last, inside each run of consecutive targets for the same provider and - model, so the request never changes model or provider earlier than it did before. A pooled - target mixing both kinds is split; if its accounts cannot be addressed one by one it stays - pooled. A chain with no recorded account is returned unchanged. + * `need? = some access` (the request asks for that access): subscription targets keep only + the accounts recorded with it. A pooled target is narrowed to those accounts; one that + cannot be narrowed is dropped. API-key targets are left alone. While no account is recorded + with it, every subscription target is dropped: an unmarked account may lack the access, and + the caller answers `403 no_cyber_access_account` rather than guessing. + * `need? = none` (an ordinary request): an account in `reserved` that holds a special access + is never used. Of the others, accounts without special access are tried first and the + special ones last, inside each run of consecutive targets for the same provider and model, + so the request never changes model or provider earlier than it did before. A pooled target + mixing both kinds is split; if its accounts cannot be addressed one by one it stays pooled, + unless one of them is reserved: then it is dropped, since the pool could pick that login. + A chain with no recorded account is returned unchanged. The proxy walks the result in order and skips cooled accounts, so quota failover follows the same rule. -/ def applyCyberAccountPolicy (chain : RoutingChain) (caps : Array (String × String)) - (need? : Option String) : RoutingChain := + (need? : Option String) (reserved : Array String := #[]) : RoutingChain := let isSpecial (accountId : String) : Bool := subscriptionCyberAccessOf caps accountId != "none" + let isReserved (accountId : String) : Bool := isSpecial accountId && reserved.contains accountId match need? with | some need => - if !caps.any (fun (_, access) => access == need) then chain - else - let kept : Array ProviderTarget := Id.run do - let mut out : Array ProviderTarget := #[] - for tgt in chain.targets do - if !targetUsesSubscription tgt then + let kept : Array ProviderTarget := Id.run do + let mut out : Array ProviderTarget := #[] + for tgt in chain.targets do + if !targetUsesSubscription tgt then + out := out.push tgt + else + let ids := targetBackingAccountIds tgt + let okIds := ids.filter (fun aid => subscriptionCyberAccessOf caps aid == need) + if okIds.size == ids.size then out := out.push tgt else - let ids := targetBackingAccountIds tgt - let okIds := ids.filter (fun aid => subscriptionCyberAccessOf caps aid == need) - if okIds.size == ids.size then - out := out.push tgt - else - out := out ++ okIds.filterMap (narrowPooledTarget? tgt) - return out - { chain with targets := kept } + out := out ++ okIds.filterMap (narrowPooledTarget? tgt) + return out + { chain with targets := kept } | none => if !chain.targets.any (fun tgt => (targetBackingAccountIds tgt).any isSpecial) then chain else let tagged : Array (ProviderTarget × Bool) := Id.run do let mut out : Array (ProviderTarget × Bool) := #[] for tgt in chain.targets do - let ids := targetBackingAccountIds tgt + let allIds := targetBackingAccountIds tgt + let ids := allIds.filter (fun aid => !isReserved aid) + if ids.size < allIds.size then + -- Some account behind this target is reserved: keep only the others, one by one. + let narrowed := ids.filterMap (fun aid => (narrowPooledTarget? tgt aid).map (·, isSpecial aid)) + if narrowed.size == ids.size then out := out ++ narrowed + continue let specialIds := ids.filter isSpecial if specialIds.isEmpty then out := out.push (tgt, false) diff --git a/lean/OrbCore/OrbCore/RemoteDispatch.lean b/lean/OrbCore/OrbCore/RemoteDispatch.lean index 4ef9bf76c..fc108c28f 100644 --- a/lean/OrbCore/OrbCore/RemoteDispatch.lean +++ b/lean/OrbCore/OrbCore/RemoteDispatch.lean @@ -688,17 +688,30 @@ def resolveAntigravityVpnProxyEnvs ("no_proxy", noProxy) ] -/-- Check whether any xAI/Grok provider account has a VPN route configured so direct - `managed_auth` fallback can never bypass a configured AirVPN exit when `proxyBase` is empty. -/ -def anyXaiVpnConfigured? (store : CoreStore) (coreWorkDir : String) : IO (Except String Bool) := do - let hydrated ← loadHydratedProviders store coreWorkDir - for hp in hydrated do - let pt := hp.providerType.toLower - if pt == "xai" || pt == "grok" then +/-- Provider category (`Orb.AccountVpn.canonicalCategory`) whose login a harness uses when it + runs without Core's router: Claude Code uses a Claude login, Codex a ChatGPT login, Grok an xAI + login. `none` for harnesses that can reach any provider (OpenCode, Pi). -/ +def harnessVpnCategory? (harness : String) : Option String := + match harness.trimAscii.toString.toLower with + | "claudecode" | "claude" => some "anthropic" + | "codex" => some "openai" + | "grok" => some "xai" + | _ => none + +/-- Whether an account a harness could reach without Core's router has a VPN route: an account of + `category?` (`harnessVpnCategory?`), or any account at all when `none`. A harness that bypasses + the router must not run then, since it would reach the provider from Core's own address. An + account of another provider does not block it. Fails closed when a route cannot be read. -/ +def anyVpnConfiguredFor? (store : CoreStore) (coreWorkDir : String) (category? : Option String) : + IO (Except String Bool) := do + let some category := category? + | return (← OrbCore.AccountVpnRoutes.anyVpnConfigured store.missionsDb) + for hp in ← loadHydratedProviders store coreWorkDir do + if Orb.AccountVpn.canonicalCategory hp.providerType == category then match ← OrbCore.AccountVpnRoutes.snapshot store.missionsDb hp.id with | .ok (.vpn _) => return .ok true | .ok (.direct _) => pure () - | .error _ => return .error "grok_vpn_route_store_unavailable" + | .error e => return .error e return .ok false private def wrapWithRemoteMcp (harness innerCmd : String) : String := @@ -934,6 +947,30 @@ private def readAdminAntigravitySyncPayload? (boundFile : String) : IO (Option J ]) return none +/-- Give a Core-host `agy` turn the login of `oauthFile` (a sidecar credential), in a private home of + its mission (`/core-turns/agy-home/`, like Codex's `CODEX_HOME`), in the shape a + node writes for an account slot (`OrbNode.FileBrowser.installAntigravityAuth`). Returns the + directory to use as `HOME`. A turn then runs as the account Core chose, never as whatever login + the host has. -/ +def installCoreHostAntigravityLogin (root missionId oauthFile : String) : IO (Except String String) := do + let some payload ← readAdminAntigravitySyncPayload? oauthFile + | return .error "antigravity_login_unavailable" + let safeMission := String.ofList (missionId.toList.filter fun c => c.isAlphanum || c == '-' || c == '_') + if safeMission.isEmpty then return .error "antigravity_login_unavailable" + let home := System.FilePath.mk root / "core-turns" / "agy-home" / safeMission + let expiresSec := ((payload.fieldNat? "expires_at").getD 0) / 1000 + let doc := renderCompact (.obj #[ + ("auth_method", .str "consumer"), + ("token", .obj #[ + ("access_token", .str ((payload.fieldStr? "access_token").getD "")), + ("token_type", .str "Bearer"), + ("refresh_token", .str ((payload.fieldStr? "refresh_token").getD "")), + ("expiry", .str (formatEpochIso8601Utc expiresSec.toUInt64))])]) + if let .error _ ← ensurePrivateDir0700 home then return .error "antigravity_login_unavailable" + let file := home / ".gemini" / "antigravity-cli" / "antigravity-oauth-token" + if let .error _ ← writeAtomicPrivate0600 file doc.toUTF8 then return .error "antigravity_login_unavailable" + return .ok home.toString + private def antigravityWindowExhaustedAt (w : JVal) (nowSec : UInt64) : Bool := Id.run do let rawPct := match w.field? "used_percent" with | some (.num raw) => raw.trimAscii.toString @@ -1038,6 +1075,25 @@ def antigravityVpnBlocked (store : CoreStore) (sup : RemoteJobSupervisor) (accou | .error e => return (OrbCore.AccountVpnPool.transientRetrySecs? e).isSome | .ok _ => return false +/-- The Antigravity account to run a turn on, among `candidates` (enabled and allowed, in priority + order; only accounts with a login of their own count). The first one that is neither out of + quota nor rejected and whose VPN route is not waiting (`vpnBlocked`) wins. `vpnBlocked` is asked + in priority order and only for usable accounts, because the check starts the tunnel. When none + qualifies: the first usable account whose route is waiting, so the refusal names its route and + when it clears; else the first candidate. A waiting account never runs without its route: the + caller still resolves the route and fails closed. One rule for node dispatch + (`adminDirectAntigravityStaticTarget?`) and Core-host turns (`Control.resolveLocalCoreHarnessSetup`). -/ +def chooseAntigravityAccount? (store : CoreStore) (hub? : Option ProviderRuntimeHub) (nowSec : UInt64) + (candidates : Array HydratedProvider) (vpnBlocked : String → IO Bool) : + IO (Option HydratedProvider) := do + let withOauth := candidates.filter fun h => !h.boundOauthFile.isEmpty + let mut waiting? : Option HydratedProvider := none + for hp in withOauth do + if !(← antigravityAccountExhaustedOrRejected? store hub? hp nowSec) then + if !(← vpnBlocked hp.id) then return some hp + if waiting?.isNone then waiting? := some hp + return waiting?.orElse (fun _ => withOauth[0]?) + /-- Determine whether an admin-owned Antigravity CLI turn on `effNodeId` may run through the node's `managed_auth` (`agy` with full workspace & MCP tools, provisioned via `PUT /managed-auth/antigravity`) because: @@ -1100,23 +1156,8 @@ def adminDirectAntigravityStaticTarget? let activeAdminAg := directAg.filter fun hp => hp.enabled && isUserProviderEnabled prefs hp.id if activeAdminAg.isEmpty then return none - let withOauth := activeAdminAg.filter fun h => !h.boundOauthFile.isEmpty - let mut chosen? : Option String := none - -- The first usable account whose VPN route is only waiting: when nothing else can serve the - -- turn, it is the one to report, with the time after which its route clears. - let mut waiting? : Option String := none - for hp in withOauth do - if chosen?.isNone then - if !(← antigravityAccountExhaustedOrRejected? store hub? hp nowSec) then - -- Asked in priority order and only for usable accounts: the check starts the tunnel. - let blocked ← vpnBlocked hp.id - if !blocked then - chosen? := some hp.boundOauthFile - else if waiting?.isNone then - waiting? := some hp.boundOauthFile - let fallback? := waiting?.orElse (fun _ => withOauth[0]?.map (·.boundOauthFile)) - let oauthFile := chosen?.orElse (fun _ => fallback?) |>.getD "" - return some oauthFile + let chosen? ← chooseAntigravityAccount? store hub? nowSec activeAdminAg vpnBlocked + return some ((chosen?.map (·.boundOauthFile)).getD "") /-- When a multi-turn mission starts a fresh harness session (`resumeSid? = none`, e.g. after migrating `backend` via `PATCH /api/control/missions/:id/settings`), carry over the mission @@ -1435,8 +1476,8 @@ def prepareRemoteHarnessCommand ("NO_COLOR", "1") ] return .ok { command := cmd, envPairs := envs, managedAuth := #[], proxyToken := pTok } - match ← anyXaiVpnConfigured? store coreWorkDir with - | .error e => return .error e + match ← anyVpnConfiguredFor? store coreWorkDir (harnessVpnCategory? "grok") with + | .error _ => return .error "grok_vpn_route_store_unavailable" | .ok true => return .error "grok_vpn_requires_proxy_base_url" | .ok false => let envs := skillEnvs ++ promptEnvs ++ mcpEnvs ++ #[("NO_COLOR", "1")] diff --git a/lean/OrbCore/OrbCore/Store.lean b/lean/OrbCore/OrbCore/Store.lean index 1da250865..ac44c907e 100644 --- a/lean/OrbCore/OrbCore/Store.lean +++ b/lean/OrbCore/OrbCore/Store.lean @@ -254,7 +254,7 @@ def missionsSchemaSql : String := "CREATE INDEX IF NOT EXISTS remote_message_pending ON remote_message_queue(state,sequence);" ++ "CREATE TABLE IF NOT EXISTS ai_providers (id TEXT PRIMARY KEY, provider_type TEXT NOT NULL, name TEXT NOT NULL, enabled INTEGER NOT NULL DEFAULT 1, base_url TEXT NOT NULL DEFAULT '', api_key TEXT NOT NULL DEFAULT '', rpm_limit INTEGER, max_concurrency INTEGER, custom_models_json TEXT NOT NULL DEFAULT '[]', sort_order INTEGER NOT NULL DEFAULT 0, updated_at TEXT NOT NULL DEFAULT '', created_by_user_id TEXT NOT NULL DEFAULT '', cli_proxy_auth_file TEXT NOT NULL DEFAULT '', account_email TEXT NOT NULL DEFAULT '');" ++ "CREATE TABLE IF NOT EXISTS account_vpn_routes (account_id TEXT PRIMARY KEY, country TEXT NOT NULL, generation INTEGER NOT NULL DEFAULT 1 CHECK(generation > 0), preferred_server TEXT NOT NULL DEFAULT '');" ++ - "CREATE TABLE IF NOT EXISTS account_cyber_access (account_id TEXT PRIMARY KEY, access TEXT NOT NULL CHECK(access IN ('daybreak','cvp')), source TEXT NOT NULL CHECK(source IN ('operator','detected')), updated_at TEXT NOT NULL DEFAULT '');" ++ + "CREATE TABLE IF NOT EXISTS account_cyber_access (account_id TEXT PRIMARY KEY, access TEXT NOT NULL CHECK(access IN ('daybreak','cvp')), source TEXT NOT NULL CHECK(source IN ('operator','detected')), updated_at TEXT NOT NULL DEFAULT '', reserved INTEGER NOT NULL DEFAULT 0);" ++ "CREATE TABLE IF NOT EXISTS provider_audit_log (id INTEGER PRIMARY KEY AUTOINCREMENT, user_id TEXT NOT NULL, role TEXT NOT NULL, action TEXT NOT NULL, provider_id TEXT NOT NULL, fields TEXT NOT NULL DEFAULT '', created_at TEXT NOT NULL);" ++ "CREATE TABLE IF NOT EXISTS deferred_message_batches (mission_id TEXT NOT NULL, batch_seq INTEGER NOT NULL, message_id TEXT NOT NULL, content TEXT NOT NULL, source TEXT NOT NULL DEFAULT '', unpacked INTEGER NOT NULL DEFAULT 1, created_at TEXT NOT NULL DEFAULT '', PRIMARY KEY(mission_id, batch_seq, message_id));" ++ "CREATE UNIQUE INDEX IF NOT EXISTS deferred_message_batches_uuid ON deferred_message_batches(mission_id, message_id);" ++ @@ -490,6 +490,8 @@ def missionsAdditiveAlters : Array String := #[ -- Last authentication verdict of real proxied requests, per upstream account -- (`cliproxyapi:` when CLIProxyAPI holds the login). A row means "rejected". "CREATE TABLE IF NOT EXISTS provider_auth_health (account_key TEXT PRIMARY KEY, code TEXT NOT NULL DEFAULT '', observed_at TEXT NOT NULL DEFAULT '');", + -- An account kept for requests that need its Daybreak/CVP access (`docs/specs/subscription-cyber-access.md`). + "ALTER TABLE account_cyber_access ADD COLUMN reserved INTEGER NOT NULL DEFAULT 0;", "CREATE INDEX IF NOT EXISTS idx_mission_search_docs_mission ON mission_search_docs(mission_id);", "CREATE INDEX IF NOT EXISTS idx_mission_runs_mission ON mission_runs(mission_id);", "CREATE UNIQUE INDEX IF NOT EXISTS deferred_message_batches_uuid ON deferred_message_batches(mission_id, message_id);" diff --git a/orb/src/AccountCyberAccessSetting.tsx b/orb/src/AccountCyberAccessSetting.tsx index 432625098..1adda9706 100644 --- a/orb/src/AccountCyberAccessSetting.tsx +++ b/orb/src/AccountCyberAccessSetting.tsx @@ -5,27 +5,37 @@ import { providerWriteError } from "./providerPermissions"; import { SettingsRow } from "./SettingsCard"; import { Toggle } from "./Toggle"; -/** The Daybreak/CVP mark of one subscription account. The provider list owns the - * value; the switch shows the new state at once and returns to the listed one, - * with the reason and Retry, when Core refuses the change. */ +type Pending = { access: AccountCyberAccess["access"]; reserved?: boolean }; + +/** The Daybreak/CVP mark of one subscription account, and whether it is kept for + * missions that ask for it. The provider list owns the value; a switch shows the + * new state at once and returns to the listed one, with the reason and Retry, + * when Core refuses the change. */ export function AccountCyberAccessSetting(p: { account: string; value: AccountCyberAccess; canManage: boolean; onChanged: () => void }) { - const [override, setOverride] = createSignal(null); + const [override, setOverride] = createSignal(null); const [saving, setSaving] = createSignal(false); - const [failed, setFailed] = createSignal<{ message: string; next: boolean } | null>(null); - createEffect(on(() => [p.account, p.value.access], () => { setOverride(null); setFailed(null); }, { defer: true })); + const [failed, setFailed] = createSignal<{ message: string; next: Pending } | null>(null); + createEffect(on(() => [p.account, p.value.access, p.value.reserved], () => { setOverride(null); setFailed(null); }, { defer: true })); const listed = () => accountCyberAccessView(p.value); - const isOn = () => override() ?? listed().on; - const view = () => override() === null || override() === listed().on - ? listed() - : accountCyberAccessView({ ...p.value, access: override() ? p.value.available : "none", source: "operator", updated_at: null }); - const save = async (next: boolean) => { + const view = () => { + const o = override(); + if (!o) return listed(); + return accountCyberAccessView({ + ...p.value, access: o.access, source: "operator", + updated_at: o.access === p.value.access ? p.value.updated_at : null, + reserved: o.access === "none" ? false : o.reserved ?? p.value.reserved, + }); + }; + const save = async (next: Pending) => { if (saving()) return; const account = p.account; setSaving(true); setFailed(null); setOverride(next); try { - await setProviderCyberAccess(account, next ? p.value.available : "none"); + await (next.reserved === undefined + ? setProviderCyberAccess(account, next.access) + : setProviderCyberAccess(account, next.access, next.reserved)); if (account === p.account) p.onChanged(); } catch (e) { if (account === p.account) { @@ -36,16 +46,24 @@ export function AccountCyberAccessSetting(p: { account: string; value: AccountCy setSaving(false); } }; + const mark = (on: boolean): Pending => ({ access: on ? p.value.available : "none" }); return ( - void save(!isOn())} /> + void save(mark(!view().on))} /> {f => {f().message} } + + + void save({ access: p.value.available, reserved: !view().reserved })} /> + + ); } diff --git a/orb/src/accountCyberAccess.ts b/orb/src/accountCyberAccess.ts index 26fc57070..05cbf1037 100644 --- a/orb/src/accountCyberAccess.ts +++ b/orb/src/accountCyberAccess.ts @@ -11,6 +11,8 @@ export interface AccountCyberAccess { available: AccountCyberAccessKind; source?: "operator" | "detected" | null; updated_at?: string | null; + /** Ordinary missions never use this account, not even as the last resort. */ + reserved?: boolean; } export interface AccountCyberAccessView { @@ -22,6 +24,10 @@ export interface AccountCyberAccessView { on: boolean; /** How it was learned and what it changes, in one or two sentences. */ detail: string; + /** The account is kept only for missions that ask for the access. */ + reserved: boolean; + /** Title of the reserve switch, "" when the account is not marked. */ + reserveTitle: string; } const labels: Record = { daybreak: "Daybreak", cvp: "CVP" }; @@ -29,15 +35,22 @@ const labels: Record = { daybreak: "Daybreak", c export const accountCyberAccessRule = "Kept for missions that ask for it; other missions use this account only when no other account is available."; +export const accountCyberAccessReservedRule = + "Only missions that ask for it use this account; other missions never fall back to it."; + export function accountCyberAccessView(value: AccountCyberAccess | null | undefined): AccountCyberAccessView { const name = value ? labels[value.available] : undefined; - if (!value || !name) return { offered: false, badge: "", title: "", on: false, detail: "" }; + if (!value || !name) return { offered: false, badge: "", title: "", on: false, detail: "", reserved: false, reserveTitle: "" }; const title = `${name} access`; if (value.access !== value.available) { return { offered: true, badge: "", title, on: false, - detail: `Turn on if this account has ${name}. Orb then keeps it for missions that ask for ${name} and uses your other accounts first.` }; + detail: `Turn on if this account has ${name}. Orb then keeps it for missions that ask for ${name} and uses your other accounts first.`, + reserved: false, reserveTitle: "" }; } const day = /^\d{4}-\d{2}-\d{2}/.exec(value.updated_at ?? "")?.[0]; const learned = `${value.source === "detected" ? "Detected" : "Set manually"}${day ? ` on ${day}` : ""}.`; - return { offered: true, badge: name, title, on: true, detail: `${learned} ${accountCyberAccessRule}` }; + const reserved = value.reserved === true; + return { offered: true, badge: name, title, on: true, + detail: `${learned} ${reserved ? accountCyberAccessReservedRule : accountCyberAccessRule}`, + reserved, reserveTitle: `Keep for ${name} missions` }; } diff --git a/orb/src/api.ts b/orb/src/api.ts index 91924a669..6a92ef97e 100644 --- a/orb/src/api.ts +++ b/orb/src/api.ts @@ -1519,9 +1519,12 @@ export async function setProviderUserPreference(id: string, enabled: boolean): P } /** Record (or clear with "none") that a subscription account has Daybreak or CVP access. Admin only. */ -export async function setProviderCyberAccess(id: string, access: AccountCyberAccess["access"]): Promise { +/** Set an account's Daybreak/CVP mark. `reserved` (optional) keeps a marked account for missions + * that ask for the access; leaving it out keeps the saved choice. */ +export async function setProviderCyberAccess(id: string, access: AccountCyberAccess["access"], reserved?: boolean): Promise { return api(`/api/ai/providers/${encodeURIComponent(id)}/cyber-access`, { - method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ access }), + method: "PUT", headers: { "Content-Type": "application/json" }, + body: JSON.stringify(reserved === undefined ? { access } : { access, reserved }), }); } diff --git a/orb/tests/account-cyber-access.test.tsx b/orb/tests/account-cyber-access.test.tsx index 19858a2b8..24b747235 100644 --- a/orb/tests/account-cyber-access.test.tsx +++ b/orb/tests/account-cyber-access.test.tsx @@ -2,7 +2,7 @@ import { fireEvent, render, screen } from "@solidjs/testing-library"; import { createSignal } from "solid-js"; import { beforeEach, expect, it, vi } from "vitest"; import fixture from "../../shared/orb-spec/fixtures/account-cyber-access.json"; -import { accountCyberAccessRule, accountCyberAccessView, type AccountCyberAccess } from "../src/accountCyberAccess"; +import { accountCyberAccessReservedRule, accountCyberAccessRule, accountCyberAccessView, type AccountCyberAccess } from "../src/accountCyberAccess"; import { AccountCyberAccessSetting } from "../src/AccountCyberAccessSetting"; import { setProviderCyberAccess } from "../src/api"; @@ -17,6 +17,7 @@ beforeEach(() => vi.mocked(setProviderCyberAccess).mockReset()); it("matches the shared account cyber access fixture", () => { expect(accountCyberAccessRule).toBe(fixture.rule); + expect(accountCyberAccessReservedRule).toBe(fixture.reserved_rule); for (const c of fixture.views) { expect(accountCyberAccessView(c.payload as AccountCyberAccess | null), c.name).toEqual(c.view); } @@ -63,3 +64,32 @@ it("shows a member the mark without a switch, and nothing for an unmarked accoun render(() => {}} />); expect(screen.queryByText("Daybreak access")).toBeNull(); }); + +it("keeps a marked account for its missions, and an admin can release it", async () => { + const kept: AccountCyberAccess = { ...on, reserved: true }; + vi.mocked(setProviderCyberAccess).mockResolvedValueOnce(kept).mockRejectedValueOnce(new Error("offline")); + const [value, setValue] = createSignal(on); + const changed = vi.fn(() => setValue(kept)); + render(() => ); + const keep = screen.getByRole("switch", { name: "Keep for Daybreak missions" }); + expect(keep.getAttribute("aria-checked")).toBe("false"); + fireEvent.click(keep); + expect(keep.getAttribute("aria-checked")).toBe("true"); + await vi.waitFor(() => expect(changed).toHaveBeenCalledOnce()); + expect(setProviderCyberAccess).toHaveBeenCalledWith("a", "daybreak", true); + await screen.findByText(/never fall back to it\.$/); + // A refused release returns to the listed state with the reason. + fireEvent.click(keep); + await screen.findByRole("alert"); + expect(keep.getAttribute("aria-checked")).toBe("true"); + expect(setProviderCyberAccess).toHaveBeenLastCalledWith("a", "daybreak", false); +}); + +it("offers no reserve on an unmarked account, nor to a member", () => { + const first = render(() => {}} />); + expect(screen.queryByRole("switch", { name: /^Keep for/ })).toBeNull(); + first.unmount(); + render(() => {}} />); + expect(screen.queryByRole("switch")).toBeNull(); + expect(screen.getByText(/never fall back to it\.$/)).toBeTruthy(); +}); diff --git a/shared/orb-spec/fixtures/account-cyber-access.json b/shared/orb-spec/fixtures/account-cyber-access.json index ce0821c15..f72fdc7ee 100644 --- a/shared/orb-spec/fixtures/account-cyber-access.json +++ b/shared/orb-spec/fixtures/account-cyber-access.json @@ -1,46 +1,165 @@ { "rule": "Kept for missions that ask for it; other missions use this account only when no other account is available.", + "reserved_rule": "Only missions that ask for it use this account; other missions never fall back to it.", "views": [ { "name": "field absent: the account's provider has no special access", "payload": null, - "view": {"offered": false, "badge": "", "title": "", "on": false, "detail": ""} + "view": { + "offered": false, + "badge": "", + "title": "", + "on": false, + "detail": "", + "reserved": false, + "reserveTitle": "" + } }, { "name": "Codex account without Daybreak", - "payload": {"access": "none", "available": "daybreak", "source": null, "updated_at": null}, - "view": {"offered": true, "badge": "", "title": "Daybreak access", "on": false, - "detail": "Turn on if this account has Daybreak. Orb then keeps it for missions that ask for Daybreak and uses your other accounts first."} + "payload": { + "access": "none", + "available": "daybreak", + "source": null, + "updated_at": null + }, + "view": { + "offered": true, + "badge": "", + "title": "Daybreak access", + "on": false, + "detail": "Turn on if this account has Daybreak. Orb then keeps it for missions that ask for Daybreak and uses your other accounts first.", + "reserved": false, + "reserveTitle": "" + } }, { "name": "Codex account marked by the operator", - "payload": {"access": "daybreak", "available": "daybreak", "source": "operator", "updated_at": "2026-11-30T09:15:00Z"}, - "view": {"offered": true, "badge": "Daybreak", "title": "Daybreak access", "on": true, - "detail": "Set manually on 2026-11-30. Kept for missions that ask for it; other missions use this account only when no other account is available."} + "payload": { + "access": "daybreak", + "available": "daybreak", + "source": "operator", + "updated_at": "2026-11-30T09:15:00Z" + }, + "view": { + "offered": true, + "badge": "Daybreak", + "title": "Daybreak access", + "on": true, + "detail": "Set manually on 2026-11-30. Kept for missions that ask for it; other missions use this account only when no other account is available.", + "reserved": false, + "reserveTitle": "Keep for Daybreak missions" + } }, { "name": "Claude account without CVP", - "payload": {"access": "none", "available": "cvp", "source": null, "updated_at": null}, - "view": {"offered": true, "badge": "", "title": "CVP access", "on": false, - "detail": "Turn on if this account has CVP. Orb then keeps it for missions that ask for CVP and uses your other accounts first."} + "payload": { + "access": "none", + "available": "cvp", + "source": null, + "updated_at": null + }, + "view": { + "offered": true, + "badge": "", + "title": "CVP access", + "on": false, + "detail": "Turn on if this account has CVP. Orb then keeps it for missions that ask for CVP and uses your other accounts first.", + "reserved": false, + "reserveTitle": "" + } }, { "name": "Claude account detected by Orb", - "payload": {"access": "cvp", "available": "cvp", "source": "detected", "updated_at": "2026-12-01T00:00:00Z"}, - "view": {"offered": true, "badge": "CVP", "title": "CVP access", "on": true, - "detail": "Detected on 2026-12-01. Kept for missions that ask for it; other missions use this account only when no other account is available."} + "payload": { + "access": "cvp", + "available": "cvp", + "source": "detected", + "updated_at": "2026-12-01T00:00:00Z" + }, + "view": { + "offered": true, + "badge": "CVP", + "title": "CVP access", + "on": true, + "detail": "Detected on 2026-12-01. Kept for missions that ask for it; other missions use this account only when no other account is available.", + "reserved": false, + "reserveTitle": "Keep for CVP missions" + } }, { "name": "marked without a date", - "payload": {"access": "cvp", "available": "cvp", "source": "operator", "updated_at": ""}, - "view": {"offered": true, "badge": "CVP", "title": "CVP access", "on": true, - "detail": "Set manually. Kept for missions that ask for it; other missions use this account only when no other account is available."} + "payload": { + "access": "cvp", + "available": "cvp", + "source": "operator", + "updated_at": "" + }, + "view": { + "offered": true, + "badge": "CVP", + "title": "CVP access", + "on": true, + "detail": "Set manually. Kept for missions that ask for it; other missions use this account only when no other account is available.", + "reserved": false, + "reserveTitle": "Keep for CVP missions" + } }, { "name": "unknown access value is not shown as a badge", - "payload": {"access": "platinum", "available": "daybreak", "source": "operator", "updated_at": null}, - "view": {"offered": true, "badge": "", "title": "Daybreak access", "on": false, - "detail": "Turn on if this account has Daybreak. Orb then keeps it for missions that ask for Daybreak and uses your other accounts first."} + "payload": { + "access": "platinum", + "available": "daybreak", + "source": "operator", + "updated_at": null + }, + "view": { + "offered": true, + "badge": "", + "title": "Daybreak access", + "on": false, + "detail": "Turn on if this account has Daybreak. Orb then keeps it for missions that ask for Daybreak and uses your other accounts first.", + "reserved": false, + "reserveTitle": "" + } + }, + { + "name": "Codex account marked and kept for Daybreak missions", + "payload": { + "access": "daybreak", + "available": "daybreak", + "source": "operator", + "updated_at": "2026-11-30T09:15:00Z", + "reserved": true + }, + "view": { + "offered": true, + "badge": "Daybreak", + "title": "Daybreak access", + "on": true, + "detail": "Set manually on 2026-11-30. Only missions that ask for it use this account; other missions never fall back to it.", + "reserved": true, + "reserveTitle": "Keep for Daybreak missions" + } + }, + { + "name": "a reserve on an unmarked account means nothing", + "payload": { + "access": "none", + "available": "cvp", + "source": null, + "updated_at": null, + "reserved": true + }, + "view": { + "offered": true, + "badge": "", + "title": "CVP access", + "on": false, + "detail": "Turn on if this account has CVP. Orb then keeps it for missions that ask for CVP and uses your other accounts first.", + "reserved": false, + "reserveTitle": "" + } } ] } From f374f304eaf502779325ed4488cce852dad63b47 Mon Sep 17 00:00:00 2001 From: "Thomas Marchand (agent)" Date: Mon, 30 Nov 2026 14:49:41 +0000 Subject: [PATCH 2/2] test: account-choice replay uses the store root; clean up added fixture accounts --- lean/OrbCore/OrbCore/ProviderContractTests.lean | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/lean/OrbCore/OrbCore/ProviderContractTests.lean b/lean/OrbCore/OrbCore/ProviderContractTests.lean index a5c75bd74..24b5730a7 100644 --- a/lean/OrbCore/OrbCore/ProviderContractTests.lean +++ b/lean/OrbCore/OrbCore/ProviderContractTests.lean @@ -2815,7 +2815,7 @@ private def v1LocalHarnessAndChainRefreshContract writeProviders true let busyFirst : String → AccountVpnRoutes.Preference → IO (Except String UInt16) := fun acct _ => pure (if acct == agId then .error "vpn_exit_in_use" else .ok 39999) - let agyHome := s!"{root}/core-turns/agy-home/v1-unbound-mid" + let agyHome := s!"{store.rootDir}/core-turns/agy-home/v1-unbound-mid" match ← resolveLocalCoreHarnessSetup { app with vpnRelayPort? := some 43210 } "v1-unbound-mid" "" "antigravity" "gemini-4-carbon" 3123 now tokRef (some busyFirst) with | .error e => failures := failures.push s!"v1 local antigravity must pass over a busy VPN account, got {e}" @@ -2968,6 +2968,7 @@ private def v1LocalHarnessAndChainRefreshContract discard <| deleteAIProvider store xaiId IO.FS.writeFile s!"{root}/.sandboxed-sh/ai_providers.json" origProvidersRaw discard <| (IO.FS.removeFile agPath).toBaseIO + discard <| (IO.FS.removeFile s!"{root}/auth-empty/{agFile2}").toBaseIO discard <| (IO.FS.removeFile liveCodexPath).toBaseIO return failures @@ -5761,6 +5762,7 @@ def run : IO Unit := do remark2 == 200 && again.fieldBool? "reserved" == some false do failures := failures.push s!"cyber-access clear: {clearCode} {renderCompact cleared} {remark2} {renderCompact again}" discard <| putJson app jwt cyberRoute "{\"access\":\"none\"}" now + IO.ofExcept (← deleteAIProvider store subRow.id) let configuredIdentities := fun (session : String) => do let rows := (← getJson app session "/api/ai/providers" now).asArr?.getD #[] return (rows.filter (·.fieldBool? "has_credentials" == some true)).map fun row =>