From fc663a25ff179dcaac8335771063f47dbc78d9b4 Mon Sep 17 00:00:00 2001 From: Nicky Leach Date: Tue, 1 Dec 2026 10:22:57 -0800 Subject: [PATCH 1/3] Support live Antigravity auth-file writeback for both token stores Co-Authored-By: Paperclip --- doc/plugins/PLUGIN_ENVIRONMENT_TASKS.md | 36 ++-- doc/runner-internals.md | 7 +- packages/paperclip-runner/protocol/README.md | 2 +- .../runner-core/src/acpx_sidecar_transport.rs | 3 +- .../runner-core/src/credential_observer.rs | 177 ++++++++++++++++-- .../runner-core/src/credential_write_back.rs | 10 +- .../src/tests/credential_observer.rs | 66 ++++++- .../tests/acpx_sidecar_transport.rs | 2 +- .../src/drivers/acpx/codex-credentials.ts | 2 +- .../src/drivers/acpx/credential-file.ts | 5 +- .../src/drivers/acpx/runtime-host.ts | 15 +- .../src/live/runnerd-codex-transport.test.ts | 2 +- packages/plugins/sdk/src/environment-tasks.ts | 2 +- ...y-plugin-task-credential-writeback.test.ts | 25 ++- server/src/services/agent-environment-test.ts | 2 +- .../managed-ai-credential-writeback.ts | 24 ++- .../antigravity-run-start.test.ts | 5 +- .../antigravity-runner-credentials.ts | 3 +- .../native-runtime/native-credential-store.ts | 4 +- .../native-credential-writeback.ts | 58 +++++- .../native-runtime/native-session-executor.ts | 2 +- .../plugin-runner-credentials.test.ts | 6 +- .../plugin-runner-credentials.ts | 4 +- .../plugin-runner-probe-antigravity.test.ts | 6 +- .../plugin-task-credential-writeback.ts | 33 +++- 25 files changed, 414 insertions(+), 87 deletions(-) diff --git a/doc/plugins/PLUGIN_ENVIRONMENT_TASKS.md b/doc/plugins/PLUGIN_ENVIRONMENT_TASKS.md index f8cee7970c0..8105add55f3 100644 --- a/doc/plugins/PLUGIN_ENVIRONMENT_TASKS.md +++ b/doc/plugins/PLUGIN_ENVIRONMENT_TASKS.md @@ -75,12 +75,11 @@ The `credential` field has one of these types: | `type` | Contents | Harness | | --- | --- | --- | -| `auth-file` | `provider` and `content`: the provider's saved sign-in file, as written | `codex` or `grok` | +| `auth-file` | `provider` and `content`: the provider's saved sign-in file, as written | `codex`, `grok`, or `antigravity` | | `claude-env` | `environment`: exactly one of `CLAUDE_CODE_OAUTH_TOKEN` or `ANTHROPIC_API_KEY` | `claude` | | `provider-env` | `provider` and `environment`: one complete variable set for that provider | `grok`, `copilot`, `opencode` or `antigravity` | -An `auth-file` credential is the `auth.json` that the provider's sign-in saved: -a Codex subscription or API-key account, or a Grok subscription. Install it as +An `auth-file` carries a saved Codex, Grok, or Google sign-in. Install it as written in the provider's home. When the provider refreshes it, the `credentials` operation returns the refreshed copy in the same form, and Core saves it to the account. `ENVIRONMENT_TASK_AUTH_FILE_PROVIDERS` exports the provider list. @@ -115,18 +114,12 @@ binding. For `antigravity`, the Runner also removes every other `GOOGLE_*` and `GEMINI_*` variable before it starts the provider, so a configured variable cannot redirect the key. -For a Google Antigravity agent bound to a Google sign-in, the -`antigravity` credential carries `PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET`. -Its value is the saved sign-in as a JSON document: the client ID, client -secret, refresh token, token URI, the `scopes` list, and `project_id` when the -account has one. It never contains an access token or the account email. Set it -in the private environment of that task's Runner process only, and name it in -`PAPERCLIP_ACPX_CREDENTIAL_BINDING`. Never put it in a file, a log, a -configured environment, or the environment of another task. The Runner writes -it to `/antigravity-home/antigravity-acp/acp_token.json` (directory -0700, file 0600) and does not pass it to the provider process. When the provider -lease closes, the Runner writes the newest sign-in to `auth-refresh.json` in -the same directory and removes `acp_token.json`. See "Credential writeback". +For a saved Google sign-in, install the canonical OAuth document in a private +task-owned file (mode 0600) and pass its absolute path to Runner in +`PAPERCLIP_ACPX_AUTH_JSON_FILE`. The ACP server uses +`antigravity-acp/acp_token.json`. The unified CLI uses +`antigravity-cli/antigravity-oauth-token`. Runner observes the native file and +writes refresh-token changes back to the bound file before notifying Core. ## Configured environment @@ -534,14 +527,11 @@ restarted. It uses the existing account comparison and secret service. A revoked grant, replaced account, or changed session epoch discards the old refresh. -For a Google sign-in, `credentials` returns the same `provider-env` type with -`provider: "antigravity"` and only `PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET`, -set to the contents of the Runner's `auth-refresh.json` (or `acp_token.json` -if the lease has not closed). Core saves it only when the saved connection -still holds the exact sign-in that the task started with, and only after -Google confirms that the refreshed sign-in belongs to the connection's account. -A sign-in for another account is not saved; Core records that in the activity -log. +For a Google sign-in sent as an `auth-file`, return the current private file +with `provider: "antigravity"` on both live and final export. Core accepts a +rotation only while the original grant and saved credential generation still +match. Previously admitted `provider-env` sign-ins retain their stopped export +and Google account verification. Keep file synchronization and backup outside this API. The provider must retain recoverable credential state until task completion succeeds. diff --git a/doc/runner-internals.md b/doc/runner-internals.md index 085176efaec..4d5f910af6f 100644 --- a/doc/runner-internals.md +++ b/doc/runner-internals.md @@ -710,9 +710,10 @@ handling. Core validates the company, agent, run, session, and Runner binding before recording the event. A credential that supports live writeback also supplies its provider and synchronization callback. Core uses it only for a matching provider and the `harness-auth` binding. -Managed Codex and Grok subscriptions supply live writeback on local, SSH, -sandbox, and supported plugin Runner tasks. Antigravity subscriptions export -at retirement because Google account verification can rotate the token again. +Managed Codex, Grok, and Antigravity subscriptions support live writeback on +local, SSH, sandbox, and compatible plugin Runner tasks. Antigravity keeps the +original OAuth settings and replaces only the refresh token. The account update +and the run's expected credential hash advance in the same database transaction. Grant, secret, version-selector, session-epoch, and provider freshness checks are shared across execution targets. Explicit reconnects and revoked grants win over old refreshes. Providers that do not emit this event keep their existing flow; diff --git a/packages/paperclip-runner/protocol/README.md b/packages/paperclip-runner/protocol/README.md index b106adef5b0..836860b779a 100644 --- a/packages/paperclip-runner/protocol/README.md +++ b/packages/paperclip-runner/protocol/README.md @@ -63,7 +63,7 @@ unknown optional property. Existing runner binaries ignore the optional flag and do not provide observation; absence of an event does not establish support. The current Unix runner observes native Codex's managed `CODEX_HOME/auth.json` -and the Codex/Grok ACPX session homes. It uses a non-recursive directory watch +and the Codex/Grok ACPX session homes. For Antigravity it compares the refresh token in the ACP server or unified CLI credential file against the session seed. It uses a non-recursive directory watch plus a one-second polling fallback, so atomic file replacement is handled. Grok's initial inline subscription credential is the baseline, allowing a refresh during launcher startup to be detected. A first valid credential file diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/acpx_sidecar_transport.rs b/packages/paperclip-runner/runner/crates/runner-core/src/acpx_sidecar_transport.rs index d6c33c02e0a..fbb80311648 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/acpx_sidecar_transport.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/acpx_sidecar_transport.rs @@ -408,10 +408,11 @@ impl AcpxSidecarTransport { "OPENAI_API_KEY", "CODEX_API_KEY", ], + "antigravity" => &["PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET", "GEMINI_API_KEY"], "grok" => &["PAPERCLIP_ACPX_GROK_AUTH_JSON_SECRET", "XAI_API_KEY"], _ => { return Err(LocalRunnerError::invalid( - "Managed credential files require the Codex or Grok ACPX profile", + "Managed credential files require a supported ACPX profile", )) } }; diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/credential_observer.rs b/packages/paperclip-runner/runner/crates/runner-core/src/credential_observer.rs index 63eebf93bd3..8068f1150fd 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/credential_observer.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/credential_observer.rs @@ -111,12 +111,15 @@ impl CredentialObserver { |value: &str| value.len() == 64 && value.bytes().all(|b| b.is_ascii_hexdigit()); if state.schema != SCHEMA || state.session_id != self.session_id - || !matches!(state.provider.as_str(), "codex" | "grok") + || !matches!(state.provider.as_str(), "codex" | "grok" | "antigravity") || !state.path.is_absolute() - || state - .path - .file_name() - .is_none_or(|name| name != "auth.json") + || state.path.file_name().is_none_or(|name| { + name != if state.provider == "antigravity" { + "acp_token.json" + } else { + "auth.json" + } + }) || state.revision > MAX_REVISION || state .snapshot @@ -153,7 +156,7 @@ impl CredentialObserver { } if host_file.is_some() && !is_acpx_credential_path(&state.provider, &state.path) { return Err(observer_error( - "credential file requires a Codex or Grok ACPX session", + "credential file requires a supported ACPX session", )); } let mut next = state.clone(); @@ -187,11 +190,14 @@ impl CredentialObserver { .get("kind") .or_else(|| provider.get("provider")) .and_then(Value::as_str); - let acpx_file_agent = - kind == Some("acpx") && (provider["agent"] == "grok" || provider["agent"] == "codex"); + let acpx_file_agent = kind == Some("acpx") + && matches!( + provider["agent"].as_str(), + Some("grok" | "codex" | "antigravity") + ); if host_file.is_some() && kind.is_some() && !acpx_file_agent { return Err(observer_error( - "credential file requires a Codex or Grok ACPX session", + "credential file requires a supported ACPX session", )); } let (name, path, mut seed) = match kind { @@ -207,7 +213,7 @@ impl CredentialObserver { .map_err(|_| observer_error("credential home is unavailable"))?; ("codex", home.join("auth.json"), None) } - Some("acpx") if provider["agent"] == "grok" || provider["agent"] == "codex" => { + Some("acpx") if acpx_file_agent => { let Some(root) = provider["runtimeDirectory"].as_str() else { return Ok(()); }; @@ -230,15 +236,23 @@ impl CredentialObserver { .join("acpx") .join(acpx_session_directory(session)) .join(format!("{name}-home")) - .join("auth.json"); + .join(if name == "antigravity" { + "antigravity-acp/acp_token.json" + } else { + "auth.json" + }); let seed = if let Some(file) = host_file.as_deref() { credential_write_back::read_host_credential(file) .ok() .map(|(bytes, _)| bytes) - } else if name == "grok" { - std::env::var("PAPERCLIP_ACPX_GROK_AUTH_JSON_SECRET") - .ok() - .map(String::into_bytes) + } else if name == "grok" || name == "antigravity" { + std::env::var(if name == "grok" { + "PAPERCLIP_ACPX_GROK_AUTH_JSON_SECRET" + } else { + "PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET" + }) + .ok() + .map(String::into_bytes) } else { None }; @@ -249,6 +263,12 @@ impl CredentialObserver { if !path.is_absolute() { return Err(observer_error("credential home is not absolute")); } + if name == "antigravity" && seed.is_none() { + if host_file.is_some() { + return Err(observer_error("bound Google credential unavailable")); + } + return Ok(()); + } let snapshot = seed .as_ref() .and_then(|bytes| parse_snapshot(name, bytes)) @@ -256,6 +276,9 @@ impl CredentialObserver { if let Some(bytes) = seed.as_mut() { bytes.fill(0); } + if name == "antigravity" && snapshot.is_none() { + return Err(observer_error("invalid Google credential seed")); + } let state = State { schema: SCHEMA.to_owned(), session_id: self.session_id.clone(), @@ -285,7 +308,15 @@ impl CredentialObserver { if let Ok(mut watcher) = notify::recommended_watcher(move |_| { dirty.store(true, Ordering::Relaxed); }) { - if watcher.watch(parent, RecursiveMode::NonRecursive).is_ok() { + let cli = self + .state + .as_ref() + .filter(|state| state.provider == "antigravity") + .and_then(|_| parent.parent()) + .map(|home| home.join("antigravity-cli")); + let watching_cli = + cli.is_some_and(|dir| watcher.watch(&dir, RecursiveMode::NonRecursive).is_ok()); + if watcher.watch(parent, RecursiveMode::NonRecursive).is_ok() || watching_cli { self.watcher = Some(watcher); } } @@ -307,6 +338,9 @@ impl CredentialObserver { self.last_scan = Instant::now(); self.watch_directory(); let state = self.state.as_ref().expect("configured observer"); + if state.provider == "antigravity" { + return self.poll_antigravity(); + } let auth = read_private_credential(&state.path); let auth_missing = auth.is_none() && fs::symlink_metadata(&state.path) @@ -356,6 +390,90 @@ impl CredentialObserver { Ok(()) } + // The CLI stores a nested token and the ACP server stores a canonical Google credential. + // Only the refresh token crosses back into the originally seeded document. + fn poll_antigravity(&mut self) -> Result<(), DurableRunnerError> { + let state = self.state.as_ref().expect("configured observer"); + if state.pending.is_some() { + return Ok(()); + } + let acp = state + .path + .parent() + .ok_or_else(|| observer_error("missing credential directory"))?; + let home = acp + .parent() + .ok_or_else(|| observer_error("missing harness home"))?; + let cli = home.join("antigravity-cli/antigravity-oauth-token"); + let mut bytes = None; + for path in [&cli, &state.path, &acp.join("auth-refresh.json")] { + if fs::symlink_metadata(path) + .is_err_and(|error| error.kind() == std::io::ErrorKind::NotFound) + { + continue; + } + bytes = read_private_credential(path); + break; + } + let Some(mut bytes) = bytes else { + return Ok(()); + }; + let candidate = serde_json::from_slice::(&bytes).ok(); + bytes.fill(0); + let Some(token) = candidate.as_ref().and_then(antigravity_refresh_token) else { + return Ok(()); + }; + let snapshot = antigravity_snapshot(token); + if state.snapshot.as_ref() == Some(&snapshot) { + return Ok(()); + } + let mut next = state.clone(); + if let Some(previous) = &state.snapshot { + if let Some(file) = &state.host_file { + let (mut content, metadata) = credential_write_back::read_host_credential(file) + .map_err(|_| observer_error("cannot read the bound Google credential"))?; + let doc = serde_json::from_slice::(&content); + content.fill(0); + let mut doc = doc.map_err(|_| observer_error("invalid bound Google credential"))?; + let current = doc + .get("refresh_token") + .and_then(Value::as_str) + .ok_or_else(|| observer_error("missing bound Google token"))?; + if current != token { + if antigravity_snapshot(current) != *previous { + // The file owner replaced the seed. This session no longer owns it. + return Ok(()); + } + doc["refresh_token"] = Value::String(token.to_owned()); + let mut output = serde_json::to_vec(&doc) + .map_err(|_| observer_error("invalid Google credential"))?; + let written = + credential_write_back::replace_if_unchanged(&output, file, &metadata); + output.fill(0); + match written { + Ok(WriteBack::Written) => {} + Ok(_) => return Ok(()), + Err(_) => { + return Err(observer_error("cannot save the bound Google credential")) + } + } + } + } + if !state.silent { + next.revision = next + .revision + .checked_add(1) + .filter(|n| *n <= MAX_REVISION) + .ok_or_else(|| observer_error("revision exhausted"))?; + next.pending = Some(update_event(&next.provider, next.revision)); + } + } + next.snapshot = Some(snapshot); + self.save(&next)?; + self.state = Some(next); + Ok(()) + } + fn write_back( &mut self, provider: &str, @@ -460,7 +578,11 @@ fn update_event(provider: &str, revision: u64) -> PolledEvent { } fn is_acpx_credential_path(provider: &str, path: &Path) -> bool { - let home = path.parent(); + let home = if provider == "antigravity" { + path.parent().and_then(Path::parent) + } else { + path.parent() + }; home.and_then(Path::file_name) .is_some_and(|name| name == format!("{provider}-home").as_str()) && home @@ -499,11 +621,32 @@ fn acpx_session_directory(session: &str) -> String { ) } +fn antigravity_refresh_token(value: &Value) -> Option<&str> { + value + .get("token") + .unwrap_or(value) + .get("refresh_token")? + .as_str() + .filter(|token| { + !token.is_empty() && token.len() <= 16384 && !token.bytes().any(|b| b <= 32 || b == 127) + }) +} + +fn antigravity_snapshot(token: &str) -> Snapshot { + Snapshot { + identity: format!("{:x}", Sha256::digest(b"antigravity")), + fingerprint: format!("{:x}", Sha256::digest(token.as_bytes())), + } +} + fn parse_snapshot(provider: &str, bytes: &[u8]) -> Option { if bytes.len() as u64 > MAX_BYTES { return None; } let value: Value = serde_json::from_slice(bytes).ok()?; + if provider == "antigravity" { + return antigravity_refresh_token(&value).map(antigravity_snapshot); + } let nonempty = |v: &Value| { v.as_str() .filter(|s| !s.trim().is_empty()) diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/credential_write_back.rs b/packages/paperclip-runner/runner/crates/runner-core/src/credential_write_back.rs index f8e99618116..8cf92036103 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/credential_write_back.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/credential_write_back.rs @@ -282,7 +282,7 @@ pub(crate) fn write_back( } #[cfg(unix)] -fn replace_if_unchanged( +pub(crate) fn replace_if_unchanged( source: &[u8], destination: &Path, metadata: &fs::Metadata, @@ -326,6 +326,14 @@ fn replace_if_unchanged( result } +#[cfg(not(unix))] +pub(crate) fn replace_if_unchanged(_: &[u8], _: &Path, _: &fs::Metadata) -> io::Result { + Err(io::Error::new( + io::ErrorKind::Unsupported, + "credential files require Unix", + )) +} + #[cfg(not(unix))] pub(crate) fn write_back( _provider: &str, diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/tests/credential_observer.rs b/packages/paperclip-runner/runner/crates/runner-core/src/tests/credential_observer.rs index a4a0e49f2dd..145903fd7a2 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/tests/credential_observer.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/tests/credential_observer.rs @@ -457,7 +457,7 @@ fn host_file_binding_seeds_the_baseline_and_needs_an_acpx_file_session() { observer.configure_with_host_file(&json!({"provider":provider}), Some(host.clone())); if !accepted { let error = result.unwrap_err(); - assert!(error.to_string().contains("Codex or Grok ACPX"), "{error}"); + assert!(error.to_string().contains("supported ACPX"), "{error}"); assert!(observer.state.is_none()); continue; } @@ -559,7 +559,7 @@ fn recovery_rejects_a_host_file_for_a_native_codex_home() { .restore_with_host_file(|| Ok(Some(f.root.join("host/auth.json")))) .err() .expect("a native home has no file credential"); - assert!(error.to_string().contains("Codex or Grok ACPX"), "{error}"); + assert!(error.to_string().contains("supported ACPX"), "{error}"); } static CLOCK_MS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); @@ -595,3 +595,65 @@ fn a_kept_refresh_is_decided_again_once_its_decision_expires() { f.observer.poll(true).unwrap(); assert_eq!(fs::read(&host).unwrap(), bytes(&ahead)); } + +#[test] +fn antigravity_reports_only_refresh_rotation_for_both_native_formats() { + for cli in [false, true] { + let f = Fixture::new("codex", &codex("unused")); + let state_dir = f.root.join("state"); + fs::create_dir(&state_dir).unwrap(); + fs::set_permissions(&state_dir, fs::Permissions::from_mode(0o700)).unwrap(); + let seed = json!({"refresh_token":"seed-token","client_id":"selected-client"}); + f.write("host.json", &seed); + let host = f.root.join("host.json"); + let mut observer = CredentialObserver::new(&state_dir, "session"); + observer.restore().unwrap(); + observer.configure_with_host_file(&json!({"observeCredentials":true,"provider":{ + "kind":"acpx","agent":"antigravity","runtimeDirectory":f.root.join("runtime"),"normalizedSessionId":"session" + }}), Some(host.clone())).unwrap(); + let path = observer.state.as_ref().unwrap().path.clone(); + let path = if cli { + path.parent() + .unwrap() + .parent() + .unwrap() + .join("antigravity-cli/antigravity-oauth-token") + } else { + path + }; + fs::create_dir_all(path.parent().unwrap()).unwrap(); + let write = |refresh: &str, access: &str| { + let token = json!({"refresh_token":refresh,"access_token":access}); + let payload = if cli { json!({"token":token}) } else { token }; + fs::write(&path, serde_json::to_vec(&payload).unwrap()).unwrap(); + fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).unwrap(); + }; + write("seed-token", "renewed-access"); + observer.activate().unwrap(); + assert!(observer.pending().is_none()); + write("rotated-token", "renewed-access"); + observer.poll(true).unwrap(); + assert_eq!(observer.pending(), Some(update_event("antigravity", 1))); + assert_eq!( + serde_json::from_slice::(&fs::read(&host).unwrap()).unwrap(), + json!({"refresh_token":"rotated-token","client_id":"selected-client"}) + ); + let mut resumed = CredentialObserver::new(&state_dir, "session"); + resumed + .restore_with_host_file(|| Ok(Some(host.clone()))) + .unwrap(); + resumed.acknowledge(1).unwrap(); + write("rotated-again", "other-access"); + resumed.poll(true).unwrap(); + assert_eq!(resumed.pending(), Some(update_event("antigravity", 2))); + resumed.acknowledge(1).unwrap(); + f.write("host.json", &json!({"refresh_token":"reconnected"})); + write("stale-run", "access"); + resumed.poll(true).unwrap(); + assert!(resumed.pending().is_none()); + assert_eq!( + serde_json::from_slice::(&fs::read(&host).unwrap()).unwrap()["refresh_token"], + "reconnected" + ); + } +} diff --git a/packages/paperclip-runner/runner/crates/runner-core/tests/acpx_sidecar_transport.rs b/packages/paperclip-runner/runner/crates/runner-core/tests/acpx_sidecar_transport.rs index 62119a1d820..0264b464967 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/tests/acpx_sidecar_transport.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/tests/acpx_sidecar_transport.rs @@ -826,7 +826,7 @@ fn host_credential_file_reaches_only_file_credential_sidecars() { } if !matches!(agent.as_str(), "codex" | "grok") { let error = started.err().expect("other agents fail closed"); - assert!(error.to_string().contains("Codex or Grok ACPX"), "{error}"); + assert!(error.to_string().contains("supported ACPX"), "{error}"); return; } let mut transport = started.unwrap(); diff --git a/packages/paperclip-runner/src/drivers/acpx/codex-credentials.ts b/packages/paperclip-runner/src/drivers/acpx/codex-credentials.ts index a0303794365..9a8ec97f204 100644 --- a/packages/paperclip-runner/src/drivers/acpx/codex-credentials.ts +++ b/packages/paperclip-runner/src/drivers/acpx/codex-credentials.ts @@ -782,7 +782,7 @@ function boundedInlineCredential(value: string): Buffer { return bytes; } -async function readManagedCredential(sourcePath: string): Promise { +export async function readManagedCredential(sourcePath: string): Promise { let handle: FileHandle; try { handle = await open( diff --git a/packages/paperclip-runner/src/drivers/acpx/credential-file.ts b/packages/paperclip-runner/src/drivers/acpx/credential-file.ts index 420260104f0..7635d144680 100644 --- a/packages/paperclip-runner/src/drivers/acpx/credential-file.ts +++ b/packages/paperclip-runner/src/drivers/acpx/credential-file.ts @@ -2,7 +2,7 @@ import type { QualifiedAcpxAgent } from "./qualified-profiles.js"; export const ACPX_AUTH_JSON_FILE_ENV = "PAPERCLIP_ACPX_AUTH_JSON_FILE"; -export const ACPX_CREDENTIAL_FILE_AGENTS: readonly QualifiedAcpxAgent[] = ["codex", "grok"]; +export const ACPX_CREDENTIAL_FILE_AGENTS: readonly QualifiedAcpxAgent[] = ["codex", "grok", "antigravity"]; export function supportsAcpxCredentialFile(agent: QualifiedAcpxAgent): boolean { return ACPX_CREDENTIAL_FILE_AGENTS.includes(agent); @@ -10,6 +10,7 @@ export function supportsAcpxCredentialFile(agent: QualifiedAcpxAgent): boolean { const CONFLICTING_CREDENTIAL_SOURCES: Readonly>> = { codex: ["PAPERCLIP_ACPX_CODEX_AUTH_JSON_SECRET", "OPENAI_API_KEY", "CODEX_API_KEY"], + antigravity: ["PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET", "GEMINI_API_KEY"], grok: ["PAPERCLIP_ACPX_GROK_AUTH_JSON_SECRET", "XAI_API_KEY"], }; @@ -20,7 +21,7 @@ export function assertAcpxCredentialFileAdmissible( const file = acpxCredentialFileSourcePath(environment); if (file === undefined) return undefined; if (!supportsAcpxCredentialFile(agent)) { - throw new Error("Managed credential files require the Codex or Grok ACPX profile"); + throw new Error("Managed credential files require a supported ACPX profile"); } if ((CONFLICTING_CREDENTIAL_SOURCES[agent] ?? []).some(name => Boolean(environment?.[name]))) { throw new Error("Managed credential file source is ambiguous"); diff --git a/packages/paperclip-runner/src/drivers/acpx/runtime-host.ts b/packages/paperclip-runner/src/drivers/acpx/runtime-host.ts index 403f450bf41..d5855bf41b4 100644 --- a/packages/paperclip-runner/src/drivers/acpx/runtime-host.ts +++ b/packages/paperclip-runner/src/drivers/acpx/runtime-host.ts @@ -15,7 +15,7 @@ import { resolveAcpxProviderMode } from "./provider-mode.js"; import { resolvePiThinkingLevel, type PiThinkingLevel } from "./pi-thinking.js"; import { preparedHarnessHome, preconfiguredHomeEnvironment, usesPreconfiguredHome } from "../preconfigured-home.js"; import { mkdir } from "node:fs/promises"; -import { dirname, join } from "node:path"; +import { dirname, isAbsolute, join } from "node:path"; import { bindAcpxAgentFiles } from "./agent-files-binding.js"; import { assertAcpxProfileEnvironment, assertAcpxProfileWorkspace, classifyAcpxProfileError, verifyAcpxProfileInstallation } from "./profile-installation.js"; import { createAcpxRuntimeSkillLease } from "./runtime-skill-lease.js"; @@ -47,6 +47,7 @@ import { } from "../runner-tool-bridge.js"; import { acquireAcpxProviderLifetimeLease, + readManagedCredential, stageManagedCodexCredential, type AcpxProviderLifetimeLease, } from "./codex-credentials.js"; @@ -402,6 +403,16 @@ export class AcpxRuntimeHost { if (options.agent === "pi" && typeof options.providerPolicy?.readOnly !== "boolean") { throw new Error("Pi admission requires an explicit task execution policy"); } + if (options.agent === "antigravity" && options.managedCredentialSourcePath) { + const file = options.managedCredentialSourcePath; + if (!isAbsolute(file) || options.environment?.GEMINI_API_KEY || options.environment?.PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET) { + throw new Error("Antigravity requires one absolute credential file or one inline credential"); + } + const content = await readManagedCredential(file); + try { + options = { ...options, environment: { ...options.environment, PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET: content.toString("utf8") } }; + } finally { content.fill(0); } + } const preconfigured = usesPreconfiguredHome(options.environment); const preparedHome = preparedHarnessHome(options.environment, options.agent); if (preconfigured && options.permissionMode !== "approve-all") { @@ -457,7 +468,7 @@ export class AcpxRuntimeHost { !supportsAcpxCredentialFile(options.agent) ) { throw new Error( - "Managed credential files require the Codex or Grok ACPX profile", + "Managed credential files require a supported ACPX profile", ); } diff --git a/packages/paperclip-runner/src/live/runnerd-codex-transport.test.ts b/packages/paperclip-runner/src/live/runnerd-codex-transport.test.ts index 642d5f8234a..935e6bb3e0c 100644 --- a/packages/paperclip-runner/src/live/runnerd-codex-transport.test.ts +++ b/packages/paperclip-runner/src/live/runnerd-codex-transport.test.ts @@ -3257,7 +3257,7 @@ it.each([ ); it.each([ - ["codex", undefined, null], ["grok", undefined, null], ["claude", undefined, "require the Codex or Grok ACPX profile"], + ["codex", undefined, null], ["grok", undefined, null], ["antigravity", undefined, null], ["antigravity", "GEMINI_API_KEY", "ambiguous"], ["claude", undefined, "require a supported ACPX profile"], ["codex", "PAPERCLIP_ACPX_CODEX_AUTH_JSON_SECRET", "ambiguous"], ["codex", "OPENAI_API_KEY", "ambiguous"], ["codex", "CODEX_API_KEY", "ambiguous"], ["grok", "PAPERCLIP_ACPX_GROK_AUTH_JSON_SECRET", "ambiguous"], ["grok", "XAI_API_KEY", "ambiguous"], ] as const)("checks a %s host credential file beside %s before filtering", (agent, conflicting, error) => { diff --git a/packages/plugins/sdk/src/environment-tasks.ts b/packages/plugins/sdk/src/environment-tasks.ts index d8ff7e00e98..19aab0dfc57 100644 --- a/packages/plugins/sdk/src/environment-tasks.ts +++ b/packages/plugins/sdk/src/environment-tasks.ts @@ -76,7 +76,7 @@ const providerCredential = z.object({ } }); -export const ENVIRONMENT_TASK_AUTH_FILE_PROVIDERS = ["codex", "grok"] as const; +export const ENVIRONMENT_TASK_AUTH_FILE_PROVIDERS = ["codex", "grok", "antigravity"] as const; export type PluginEnvironmentTaskAuthFileProvider = typeof ENVIRONMENT_TASK_AUTH_FILE_PROVIDERS[number]; /** Only provider authentication is transferred. Paths and executable settings remain provider-owned. */ diff --git a/server/src/__tests__/antigravity-plugin-task-credential-writeback.test.ts b/server/src/__tests__/antigravity-plugin-task-credential-writeback.test.ts index 08ac36eea67..9ad73497bf3 100644 --- a/server/src/__tests__/antigravity-plugin-task-credential-writeback.test.ts +++ b/server/src/__tests__/antigravity-plugin-task-credential-writeback.test.ts @@ -10,7 +10,7 @@ import { import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; import { aiConnectionService } from "../services/ai-connections.js"; import { prepareManagedAiRuntime } from "../services/ai-connection-runtime.js"; -import { registerPluginTaskCredentialHandoff } from "../services/plugin-task-credential-writeback.js"; +import { registerPluginTaskCredentialHandoff, syncPluginTaskCredentialHandoff } from "../services/plugin-task-credential-writeback.js"; import { settleDispatchedEnvironmentTask } from "../services/environment-task-runtime.js"; import { secretService } from "../services/secrets.js"; import { preparePluginRunnerCredentials } from "../services/native-runtime/plugin-runner-credentials.js"; @@ -57,7 +57,7 @@ suite("Google sign-in task credential writeback for plugin Runners", () => { afterAll(async () => { await database?.cleanup(); vi.unstubAllEnvs(); if (home) await rm(home, { recursive: true, force: true }); }); afterEach(() => { vi.unstubAllGlobals(); secretRead.fail = false; Object.assign(google, { email: "alice@example.test", rotate: undefined, fail: false, calls: 0 }); }); - async function fixture(saved = signIn("fixture-original", { project_id: "fixture-project" })) { + async function fixture(saved = signIn("fixture-original", { project_id: "fixture-project" }), authFile = false) { stubGoogle(); const companyId = randomUUID(), agentId = randomUUID(), runId = randomUUID(), pluginId = randomUUID(), environmentId = randomUUID(), leaseId = randomUUID(); const owner = `fixture-${randomUUID()}`; @@ -79,7 +79,7 @@ suite("Google sign-in task credential writeback for plugin Runners", () => { await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, invocationSource: "manual", status: "running" }); await db.insert(environmentLeases).values({ id: leaseId, companyId, environmentId, heartbeatRunId: runId, provider: `plugin:${pluginId}:tasks`, providerLeaseId: "fixture-task", status: "active", metadata: { driver: "plugin", pluginId, driverKey: "tasks", runnerTaskLease: true, runnerTaskDispatched: true, runnerTaskExecutionStopped: false } }); - await registerPluginTaskCredentialHandoff(db, { companyId, leaseId }, managed.sessionIdentity, managed.credentialWriteback!); + await registerPluginTaskCredentialHandoff(db, { companyId, leaseId }, managed.sessionIdentity, managed.credentialWriteback!, authFile ? "antigravity" : undefined); await managed.cleanup(); const calls: string[] = []; let exported: unknown = { type: "provider-env", provider: "antigravity", environment: { [SIGN_IN]: signIn("fixture-refreshed", { project_id: "fixture-project" }) } }; @@ -102,7 +102,7 @@ suite("Google sign-in task credential writeback for plugin Runners", () => { const [connection] = await db.select().from(toolConnections).where(eq(toolConnections.id, grant!.connectionId)); return service.credential({ connection: connection!, grant: grant! }); }; - return { companyId, owner, managed, transfer, calls, lease, activity, credential, + return { companyId, leaseId, owner, managed, transfer, calls, lease, activity, credential, exportCredential(value: unknown) { exported = value; }, failExport(value: boolean) { failExport = value; }, settle: () => settleDispatchedEnvironmentTask(db, workers, { companyId, id: leaseId }) }; @@ -113,11 +113,26 @@ suite("Google sign-in task credential writeback for plugin Runners", () => { it("delivers the sanitized saved sign-in and binds writeback to its exact generation", async () => { const saved = signIn("fixture-original", { project_id: "fixture-project" }); const f = await fixture(saved); - expect(f.transfer).toMatchObject({ writeback: { mode: "on_stop", requiresGoogleGeneration: true }, credential: { type: "provider-env", provider: "antigravity", environment: { [SIGN_IN]: saved } } }); + expect(f.transfer).toMatchObject({ writeback: { mode: "live", requiresGoogleGeneration: true }, credential: { type: "auth-file", provider: "antigravity", content: saved } }); expect(f.managed.credentialWriteback).toMatchObject({ google: { credentialSha256: createHash("sha256").update(saved).digest("hex") } }); expect(leaked(JSON.stringify((await f.lease()).metadata))).toEqual([]); }); + it("saves successive live rotations to the seeded connection and discards updates after reconnect", async () => { + const f = await fixture(undefined, true); + const sync = (token: string) => syncPluginTaskCredentialHandoff(db, f, async () => ({ + type: "auth-file", provider: "antigravity", content: signIn(token), + })); + expect(await sync("fixture-refreshed")).toBe("rotated"); + expect(await sync("fixture-refreshed")).toBe("unchanged"); + expect(await sync("fixture-rotated")).toBe("rotated"); + expect(await f.credential()).toBe(signIn("fixture-rotated", { project_id: "fixture-project" })); + expect(google.calls).toBe(0); + await secretService(db).rotate(f.managed.credentialWriteback!.secretId, { value: signIn("fixture-reconnected") }, { userId: f.owner }); + expect(await sync("fixture-other")).toBe("binding_changed"); + expect(await f.credential()).toBe(signIn("fixture-reconnected")); + }); + it("saves a rotated refresh token for the same Google account and records it without the token", async () => { const f = await fixture(); expect(await f.settle()).toBe("completed"); diff --git a/server/src/services/agent-environment-test.ts b/server/src/services/agent-environment-test.ts index 8ed39bdab9a..9ddf1b2a6ff 100644 --- a/server/src/services/agent-environment-test.ts +++ b/server/src/services/agent-environment-test.ts @@ -547,7 +547,7 @@ export function agentEnvironmentTestService(db: Db, pluginWorkerManager?: Plugin const target = context.executionTarget; if (managed.credentialWriteback && target?.kind === "remote" && target.transport === "sandbox" && target.runnerTask && target.leaseId) { await registerPluginTaskCredentialHandoff(db, { companyId: context.companyId, leaseId: target.leaseId }, managed.sessionIdentity, managed.credentialWriteback, - binding.provider === "xai" ? "grok" : undefined); + managed.credentialWriteback.google ? "antigravity" : binding.provider === "xai" ? "grok" : undefined); } const result = await probeManagedEnvironment(adapterType, context, binding, managed); // A provider rejection invalidates the tested credential generation. A diff --git a/server/src/services/managed-ai-credential-writeback.ts b/server/src/services/managed-ai-credential-writeback.ts index 75108488cc4..b87e582c92a 100644 --- a/server/src/services/managed-ai-credential-writeback.ts +++ b/server/src/services/managed-ai-credential-writeback.ts @@ -127,6 +127,10 @@ export async function syncManagedAntigravityCredential( companyId: string, binding: ManagedAiCredentialWritebackBinding, fetchCredential: () => Promise, + seeded?: { + expectedHash: string; + advance: (database: Db, nextHash: string) => Promise; + }, ) { const base = managedAiCredentialWritebackBindingSchema.parse(binding).google?.credentialSha256; if (!base) throw new Error("Managed credential binding is not a Google sign-in"); @@ -150,7 +154,7 @@ export async function syncManagedAntigravityCredential( let stored: string; try { stored = sanitizeAntigravityCredential(saved); } catch { return null; } - if (createHash("sha256").update(stored, "utf8").digest("hex") !== base) return null; + if (createHash("sha256").update(stored, "utf8").digest("hex") !== (seeded?.expectedHash ?? base)) return null; return { connection, grant, stored }; }; const mutate = (operation: (database: Db) => Promise) => withAccountHomeSecretMutationLock( @@ -164,6 +168,24 @@ export async function syncManagedAntigravityCredential( try { incoming = sanitizeAntigravityCredential(credential); } catch { throw new Error("Managed credential snapshot invalid"); } if (incoming === current.stored) return "unchanged" as const; + if (seeded) { + const previous = JSON.parse(current.stored); + const token = JSON.parse(incoming).refresh_token; + if (token === previous.refresh_token) return "unchanged" as const; + // The task may replace only the refresh token in its selected credential. + const rotated = sanitizeAntigravityCredential(JSON.stringify({ ...previous, refresh_token: token })); + return mutate(async database => { + const selected = await account(database); + if (!selected) return "binding_changed" as const; + await secretService(database).rotate(binding.secretId, { value: rotated, preserveAiSessionEpoch: true }, + { userId: selected.grant.subjectUserId }); + await seeded.advance(database, antigravityCredentialSha256(rotated)); + await logActivity(database, { companyId, actorType: "system", actorId: "credential_refresh", + action: "ai_connection.credential_refreshed", entityType: "tool_connection", entityId: selected.connection.id, + details: { provider: "google", grantId: selected.grant.id } }); + return "rotated" as const; + }); + } const accountEmail = current.grant.providerTenant?.name; const refuse = async (reason: string) => { await mutate(database => logActivity(database, { companyId, actorType: "system", actorId: "credential_refresh", diff --git a/server/src/services/native-runtime/antigravity-run-start.test.ts b/server/src/services/native-runtime/antigravity-run-start.test.ts index 8d240fa34fc..e52c6d591a3 100644 --- a/server/src/services/native-runtime/antigravity-run-start.test.ts +++ b/server/src/services/native-runtime/antigravity-run-start.test.ts @@ -152,8 +152,9 @@ describe("Antigravity run start once the profile is released", () => { runnerExecutionTarget: pluginTarget() }); await backend.options!.codexTransportFactory!(); expect(ownerFactory).toHaveBeenCalledOnce(); - expect(ownerFactory).toHaveBeenCalledWith(expect.objectContaining({ credential: { type: "provider-env", provider: "antigravity", - environment: method === "api_key" ? { GEMINI_API_KEY: "fixture-gemini" } : { PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET: signIn } } })); + expect(ownerFactory).toHaveBeenCalledWith(expect.objectContaining({ credential: method === "api_key" + ? { type: "provider-env", provider: "antigravity", environment: { GEMINI_API_KEY: "fixture-gemini" } } + : { type: "auth-file", provider: "antigravity", content: signIn } })); expect(handoff).toHaveBeenCalledTimes(method === "sign_in" ? 1 : 0); } finally { handoff.mockRestore(); diff --git a/server/src/services/native-runtime/antigravity-runner-credentials.ts b/server/src/services/native-runtime/antigravity-runner-credentials.ts index c840bfb3ac0..bdcf0c40e80 100644 --- a/server/src/services/native-runtime/antigravity-runner-credentials.ts +++ b/server/src/services/native-runtime/antigravity-runner-credentials.ts @@ -178,6 +178,7 @@ export function antigravityCredentialTurn(input: { managedHome: string; runtimeHome: string; credential: string; + saveRotation?: () => Promise; /** Remote Core sandbox runs export and scrub rotated tokens over the sandbox runner. */ runtimeStore?: { read: () => Promise; remove: () => Promise }; }) { @@ -395,7 +396,7 @@ export function bindAntigravityCredentialTurn(session: NativeSession, input: Par await retire({ reason: "Google Antigravity subscription credential handoff" }); retired = true; } - if (!copied) { await callbacks.copyBack(); copied = true; } + if (!copied) { await (input.saveRotation ?? callbacks.copyBack)(); copied = true; } if (!removed) { await callbacks.remove(); removed = true; } } catch (error) { // Until copy-back succeeds, this private runtime can hold the only valid diff --git a/server/src/services/native-runtime/native-credential-store.ts b/server/src/services/native-runtime/native-credential-store.ts index 0e0d39ba139..479b0d9ef25 100644 --- a/server/src/services/native-runtime/native-credential-store.ts +++ b/server/src/services/native-runtime/native-credential-store.ts @@ -37,7 +37,7 @@ try { }`; export function createNativeCredentialStore(input: { - filename: "auth.json" | "acp_token.json"; + filename: "auth.json" | "acp_token.json" | "antigravity-oauth-token"; localHome: string; remoteHome?: string; runner?: Pick; @@ -58,7 +58,7 @@ export function createNativeCredentialStore(input: { read: async () => { try { return await read(input.filename); } catch (error) { - if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; + if (input.filename === "antigravity-oauth-token" || (error as NodeJS.ErrnoException).code !== "ENOENT") throw error; return read("auth-refresh.json"); } }, diff --git a/server/src/services/native-runtime/native-credential-writeback.ts b/server/src/services/native-runtime/native-credential-writeback.ts index e9ad37688f3..f87d5a23c62 100644 --- a/server/src/services/native-runtime/native-credential-writeback.ts +++ b/server/src/services/native-runtime/native-credential-writeback.ts @@ -1,9 +1,10 @@ import { join, posix, resolve } from "node:path"; import type { CommandManagedRuntimeRunner } from "@paperclipai/adapter-utils/command-managed-runtime"; -import type { Db } from "@paperclipai/db"; +import { heartbeatRuns, type Db } from "@paperclipai/db"; +import { and, eq, sql } from "drizzle-orm"; import { resolvePaperclipInstanceRoot } from "../../home-paths.js"; import { acpxRuntimeSessionDirectoryName, type NativeExecutionInput, type NativeSession } from "../../vendor/paperclip-runner/index.js"; -import { managedAuthFileStrategy, syncManagedAiCredentials, type ManagedAiCredentialWritebackBinding } from "../managed-ai-credential-writeback.js"; +import { managedAuthFileStrategy, syncManagedAiCredentials, syncManagedAntigravityCredential, type ManagedAiCredentialWritebackBinding } from "../managed-ai-credential-writeback.js"; import { bindAntigravityCredentialTurn } from "./antigravity-runner-credentials.js"; import { bindManagedNativeCredentialTurn } from "./managed-native-credentials.js"; import { createNativeCredentialStore } from "./native-credential-store.js"; @@ -17,6 +18,7 @@ type NativeCredentialWriteback = { export function prepareNativeCredentialWriteback(input: { db: Db; companyId: string; + runId: string; binding?: ManagedAiCredentialWritebackBinding; provider: NativeExecutionInput["provider"]; root: string; @@ -38,11 +40,55 @@ export function prepareNativeCredentialWriteback(input: { if (antigravityCredential?.home && antigravityCredential.credential) { const { home: managedHome, credential } = antigravityCredential; - const runtimeStore = remote ? createNativeCredentialStore({ + const runtimeStore = createNativeCredentialStore({ filename: "acp_token.json", localHome: join(runtimeHome, "antigravity-acp"), - remoteHome: posix.join(remote.root, relativeHome, "antigravity-acp"), runner: remote.runner, - }) : undefined; - return { bindTurn: session => bindAntigravityCredentialTurn(session, { managedHome, credential, runtimeHome, runtimeStore }) }; + ...(remote && { remoteHome: posix.join(remote.root, relativeHome, "antigravity-acp"), runner: remote.runner }), + }); + const google = binding?.google; + if (!google || !binding) return { bindTurn: session => bindAntigravityCredentialTurn(session, { + managedHome, credential, runtimeHome, runtimeStore: remote ? runtimeStore : undefined, + }) }; + const cli = createNativeCredentialStore({ + filename: "antigravity-oauth-token", localHome: join(runtimeHome, "antigravity-cli"), + ...(remote && { remoteHome: posix.join(remote.root, relativeHome, "antigravity-cli"), runner: remote.runner }), + }); + const read = async () => { + let token: string; + try { token = await cli.read(); } + catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; + return runtimeStore.read(); + } + const refresh: unknown = JSON.parse(token)?.token?.refresh_token; + if (typeof refresh !== "string" || !refresh) throw new Error("Invalid AGY refresh token"); + return JSON.stringify({ ...JSON.parse(credential), refresh_token: refresh }); + }; + const synchronize = async (retiring = false) => { + const run = and(eq(heartbeatRuns.id, input.runId), eq(heartbeatRuns.companyId, input.companyId)); + const [owner] = await input.db.select({ hash: sql`${heartbeatRuns.contextSnapshot}->>'runnerGoogleCredentialHash'` }) + .from(heartbeatRuns).where(run); + if (!owner) throw new Error("Google credential run unavailable"); + const outcome = await syncManagedAntigravityCredential(input.db, input.companyId, binding, async () => { + try { return await read(); } + catch (error) { if (retiring && (error as NodeJS.ErrnoException).code === "ENOENT") return null; throw error; } + }, { + expectedHash: owner.hash ?? google.credentialSha256, + advance: async (database, hash) => { + const updated = await database.update(heartbeatRuns).set({ + contextSnapshot: sql`coalesce(${heartbeatRuns.contextSnapshot}, '{}'::jsonb) || ${JSON.stringify({ runnerGoogleCredentialHash: hash })}::jsonb`, + }).where(and(run, sql`${heartbeatRuns.contextSnapshot}->>'runnerGoogleCredentialHash' is not distinct from ${owner.hash}`)) + .returning({ id: heartbeatRuns.id }); + if (!updated.length) throw new Error("Google credential run changed"); + }, + }); + if (!retiring && outcome === "no_credentials") throw new Error("Native credential snapshot unavailable"); + }; + return { + liveWriteback: { provider: harness, synchronize }, + bindTurn: session => bindAntigravityCredentialTurn(session, { + managedHome, credential, runtimeHome, runtimeStore, saveRotation: () => synchronize(true), + }), + }; } if (!strategy) return; diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index 2b25425d02e..f5535d2da5c 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -19047,7 +19047,7 @@ async function createRunnerdBackendWithinSessionClaim( const diagnosticLease = diagnostics.activate(diagnosticOwner, input.onLog); input.onDiagnosticLease?.(diagnosticLease); const credentials = prepareNativeCredentialWriteback({ - db: input.db, companyId: input.execution.binding.companyId, binding: input.managedAiCredentialWriteback, + runId: input.execution.binding.runId, db: input.db, companyId: input.execution.binding.companyId, binding: input.managedAiCredentialWriteback, provider: input.execution.provider, sessionId: nativeSessionKey(input.execution), root, preconfiguredHome, destinationHome: grokCredential ? grokCredential.home : input.managedAiCredentialHome, antigravityCredential, remote: remoteRunnerFilesystemRoot && remoteCommandRunner ? { root: remoteRunnerFilesystemRoot, runner: remoteCommandRunner } : undefined, diff --git a/server/src/services/native-runtime/plugin-runner-credentials.test.ts b/server/src/services/native-runtime/plugin-runner-credentials.test.ts index 870688744cd..c33b4c03a95 100644 --- a/server/src/services/native-runtime/plugin-runner-credentials.test.ts +++ b/server/src/services/native-runtime/plugin-runner-credentials.test.ts @@ -72,9 +72,9 @@ describe("plugin Runner Google Antigravity credentials", () => { const directory = await googleHome(JSON.stringify({ ...JSON.parse(saved), access_token: "fixture-access", expiry: "2020-01-01T00:00:00Z", email: "alice@example.test" })); const transfer = await preparePluginRunnerCredentials({ provider: "antigravity", identity: "revision", accountIdentity: "account", home: directory, environment: blankManagedEnvironment }); - expect(transfer).toEqual({ accountIdentity: "account", writeback: { mode: "on_stop", requiresGoogleGeneration: true }, - credential: { type: "provider-env", provider: "antigravity", environment: { PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET: saved } } }); - const delivered = transfer.credential!.type === "provider-env" ? transfer.credential!.environment.PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET : ""; + expect(transfer).toEqual({ accountIdentity: "account", writeback: { mode: "live", requiresGoogleGeneration: true }, + credential: { type: "auth-file", provider: "antigravity", content: saved } }); + const delivered = transfer.credential!.type === "auth-file" ? transfer.credential!.content : ""; expect(delivered).not.toContain("fixture-access"); expect(delivered).not.toContain("alice@example.test"); expect(transfer.onCredentials).toBeUndefined(); diff --git a/server/src/services/native-runtime/plugin-runner-credentials.ts b/server/src/services/native-runtime/plugin-runner-credentials.ts index ebcf467ac28..49fe41cef4f 100644 --- a/server/src/services/native-runtime/plugin-runner-credentials.ts +++ b/server/src/services/native-runtime/plugin-runner-credentials.ts @@ -83,8 +83,8 @@ export async function preparePluginRunnerCredentials(input: { } catch { throw new Error("The selected Google Antigravity account is unavailable. Reconnect the Google account, then retry."); } - const credential = environmentTaskCredentialSchema.parse({ type: "provider-env", provider, environment: { [ANTIGRAVITY_SIGN_IN_ENV]: authJson } }); - return { ...github, accountIdentity, credential, writeback: { mode: "on_stop", requiresGoogleGeneration: true } }; + const credential = environmentTaskCredentialSchema.parse({ type: "auth-file", provider, content: authJson }); + return { ...github, accountIdentity, credential, writeback: { mode: "live", requiresGoogleGeneration: true } }; } } const names = new Set(provider === "antigravity" ? ["GEMINI_API_KEY"] : ENVIRONMENT_TASK_PROVIDER_CREDENTIAL_KEY_SETS[provider].flat()); diff --git a/server/src/services/native-runtime/plugin-runner-probe-antigravity.test.ts b/server/src/services/native-runtime/plugin-runner-probe-antigravity.test.ts index 8af05ea8fb4..4679e05f111 100644 --- a/server/src/services/native-runtime/plugin-runner-probe-antigravity.test.ts +++ b/server/src/services/native-runtime/plugin-runner-probe-antigravity.test.ts @@ -161,11 +161,11 @@ describe("plugin Runner probe for Google Antigravity", () => { harness: "antigravity", credentialIdentity: "google-id", accountIdentity: "google-session", - writeback: { mode: "on_stop", requiresGoogleGeneration: true }, + writeback: { mode: "live", requiresGoogleGeneration: true }, credential: { - type: "provider-env", + type: "auth-file", provider: "antigravity", - environment: { [SIGN_IN_ENV]: signInJson }, + content: signInJson, }, })); expect(mocks.probe).toHaveBeenCalledWith(expect.objectContaining({ diff --git a/server/src/services/plugin-task-credential-writeback.ts b/server/src/services/plugin-task-credential-writeback.ts index 941bafad4fd..e625dcf7aaf 100644 --- a/server/src/services/plugin-task-credential-writeback.ts +++ b/server/src/services/plugin-task-credential-writeback.ts @@ -65,17 +65,43 @@ export async function syncPluginTaskCredentialHandoff( if (!lease.metadata?.[key]) return; const handoff = handoffSchema.parse(lease.metadata[key]); if (handoff.state === "complete") return; - const outcome = await writeBackCredentials(db, scope.companyId, handoff, fetchCredential); + const outcome = await writeBackCredentials(db, scope, lease.metadata, handoff, fetchCredential); if (outcome === "no_credentials") throw new Error("Plugin task credential snapshot unavailable"); return outcome; } async function writeBackCredentials( db: Db, - companyId: string, + scope: Scope, + metadata: Record, handoff: z.infer, fetchCredential: (accountIdentity: string) => Promise, ) { + const { companyId } = scope; + const provider = handoff.provider ?? "codex"; + if (provider === "antigravity") { + const base = handoff.binding.google?.credentialSha256; + if (!base) throw new Error("Plugin task Google credential authority unavailable"); + const previous = metadata.runnerTaskGoogleCredentialHash; + return syncManagedAntigravityCredential(db, companyId, handoff.binding, async () => { + const credential = await fetchCredential(handoff.accountIdentity); + if (credential === null) return null; + if (credential.type !== "auth-file" || credential.provider !== provider) throw new Error("Plugin task credential provider mismatch"); + return credential.content; + }, { + expectedHash: typeof previous === "string" ? previous : base, + advance: async (database, nextHash) => { + const updated = await database.update(environmentLeases).set({ + metadata: sql`coalesce(${environmentLeases.metadata}, '{}'::jsonb) || ${JSON.stringify({ runnerTaskGoogleCredentialHash: nextHash })}::jsonb`, + }).where(and( + eq(environmentLeases.companyId, companyId), eq(environmentLeases.id, scope.leaseId), + sql`${environmentLeases.metadata}->${key} = ${JSON.stringify(handoff)}::jsonb`, + sql`${environmentLeases.metadata}->>'runnerTaskGoogleCredentialHash' is not distinct from ${previous ?? null}`, + )).returning({ id: environmentLeases.id }); + if (!updated.length) throw new Error("Plugin task Google credential authority changed"); + }, + }); + } if (handoff.binding.google) return syncManagedAntigravityCredential(db, companyId, handoff.binding, async () => { const credential = await fetchCredential(handoff.accountIdentity); if (credential === null) return null; @@ -84,7 +110,6 @@ async function writeBackCredentials( if (!value) throw new Error("Plugin task credential provider mismatch"); return value; }); - const provider = handoff.provider ?? "codex"; return syncManagedAiCredentials(db, companyId, handoff.binding, provider, async () => { const credential = await fetchCredential(handoff.accountIdentity); if (credential === null) return null; @@ -108,7 +133,7 @@ export async function settlePluginTaskCredentialHandoff( throw new Error("Plugin task credential process termination is unconfirmed"); } const outcome = dispatched - ? await writeBackCredentials(db, scope.companyId, handoff, fetchCredential) + ? await writeBackCredentials(db, scope, metadata, handoff, fetchCredential) : "not_dispatched"; const settled = { ...handoff, state: "complete" as const, outcome }; const completed = await db.update(environmentLeases).set({ From 1b550d2ff37c6b5106070480fc0a68b1b563888b Mon Sep 17 00:00:00 2001 From: Nicky Leach Date: Tue, 1 Dec 2026 10:46:55 -0800 Subject: [PATCH 2/3] Refresh the source SDK input for the auth-file provider Co-Authored-By: Paperclip --- tests/runner-e2e/source-sdk-public-inputs.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index 7c0dc5a22fe..be529dd6018 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -13,7 +13,7 @@ "packages/plugins/sdk/src/environment-stop-error.ts": "b0e03f8aa2b2170ba095da5c7138050fced3f3cb", "packages/plugins/sdk/src/environment-sync-error.ts": "7d6a51a95da49a7da4525aebbab6382dc5c44ae8", "packages/plugins/sdk/src/environment-task-error.ts": "98aae8a06743b38884b68cb9a3ec44c57b34c0e4", - "packages/plugins/sdk/src/environment-tasks.ts": "d8ff7e00e98c02e671fe60fb7f7eda887a34371b", + "packages/plugins/sdk/src/environment-tasks.ts": "19aab0dfc57564809326459b5a8b74a4f6545e78", "packages/plugins/sdk/src/host-client-factory.ts": "8f76d518b4b43a41436b516cb2929165611bd483", "packages/plugins/sdk/src/idle-drain.test.ts": "cc59f7881e7d46c89395a1d93d74f6c6b9b0a64a", "packages/plugins/sdk/src/idle-drain.ts": "ae6e4c6be4657a3d541396922b3bc551b8db557f", From d1dc82317018a95f611c464d7611aa6dcb6dfb6b Mon Sep 17 00:00:00 2001 From: Nicky Leach Date: Tue, 1 Dec 2026 10:49:11 -0800 Subject: [PATCH 3/3] Handle the legacy Google access-token field during refresh observation Co-Authored-By: Paperclip --- .../runner-core/src/acpx_sidecar_transport.rs | 5 +++- .../runner-core/src/credential_observer.rs | 13 ++++++--- .../src/tests/credential_observer.rs | 6 ++++- .../src/drivers/acpx/runtime-host.test.ts | 27 +++++++++++++++++++ 4 files changed, 45 insertions(+), 6 deletions(-) diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/acpx_sidecar_transport.rs b/packages/paperclip-runner/runner/crates/runner-core/src/acpx_sidecar_transport.rs index fbb80311648..332208229b6 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/acpx_sidecar_transport.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/acpx_sidecar_transport.rs @@ -408,7 +408,10 @@ impl AcpxSidecarTransport { "OPENAI_API_KEY", "CODEX_API_KEY", ], - "antigravity" => &["PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET", "GEMINI_API_KEY"], + "antigravity" => &[ + "PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET", + "GEMINI_API_KEY", + ], "grok" => &["PAPERCLIP_ACPX_GROK_AUTH_JSON_SECRET", "XAI_API_KEY"], _ => { return Err(LocalRunnerError::invalid( diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/credential_observer.rs b/packages/paperclip-runner/runner/crates/runner-core/src/credential_observer.rs index 8068f1150fd..e74d997d156 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/credential_observer.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/credential_observer.rs @@ -272,7 +272,13 @@ impl CredentialObserver { let snapshot = seed .as_ref() .and_then(|bytes| parse_snapshot(name, bytes)) - .or_else(|| read_snapshot(name, &path)); + .or_else(|| { + if name == "antigravity" { + None + } else { + read_snapshot(name, &path) + } + }); if let Some(bytes) = seed.as_mut() { bytes.fill(0); } @@ -623,9 +629,8 @@ fn acpx_session_directory(session: &str) -> String { fn antigravity_refresh_token(value: &Value) -> Option<&str> { value - .get("token") - .unwrap_or(value) - .get("refresh_token")? + .get("refresh_token") + .or_else(|| value.get("token")?.get("refresh_token"))? .as_str() .filter(|token| { !token.is_empty() && token.len() <= 16384 && !token.bytes().any(|b| b <= 32 || b == 127) diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/tests/credential_observer.rs b/packages/paperclip-runner/runner/crates/runner-core/src/tests/credential_observer.rs index 145903fd7a2..030a3b43a09 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/tests/credential_observer.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/tests/credential_observer.rs @@ -624,7 +624,11 @@ fn antigravity_reports_only_refresh_rotation_for_both_native_formats() { fs::create_dir_all(path.parent().unwrap()).unwrap(); let write = |refresh: &str, access: &str| { let token = json!({"refresh_token":refresh,"access_token":access}); - let payload = if cli { json!({"token":token}) } else { token }; + let payload = if cli { + json!({"token":token}) + } else { + json!({"refresh_token":refresh,"token":access}) + }; fs::write(&path, serde_json::to_vec(&payload).unwrap()).unwrap(); fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).unwrap(); }; diff --git a/packages/paperclip-runner/src/drivers/acpx/runtime-host.test.ts b/packages/paperclip-runner/src/drivers/acpx/runtime-host.test.ts index b9ebe9b1187..81a31f5bb1b 100644 --- a/packages/paperclip-runner/src/drivers/acpx/runtime-host.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/runtime-host.test.ts @@ -1518,6 +1518,33 @@ describe("ACPX runtime host", () => { expect(fixture.commandClose).toHaveBeenCalledOnce(); }); + it("seeds Antigravity from its private host file and keeps both the secret and source path out of the harness environment", async () => { + const fixture = await hostFixture(); + const source = join(fixture.root, "host-auth.json"); + const credential = { + client_id: "1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com", + client_secret: "fixture-client", refresh_token: "fixture-refresh", token_uri: "https://oauth2.googleapis.com/token", + scopes: ["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/aicode"], + }; + await writeFile(source, JSON.stringify(credential), { mode: 0o600 }); + const openRuntime = vi.fn(async (options: Parameters[0]) => { + const home = options.launchEnvironment.GEMINI_HOME!; + const unified = options.launchEnvironment.AGY_CLI_FORCE_FILE_TOKEN_STORAGE === "1"; + const file = unified ? join(home, "antigravity-cli", "antigravity-oauth-token") : join(home, "antigravity-acp", "acp_token.json"); + const saved = JSON.parse(await readFile(file, "utf8")); + expect((unified ? saved.token : saved).refresh_token).toBe(credential.refresh_token); + expect((await stat(file)).mode & 0o777).toBe(0o600); + expect(JSON.stringify(options.launchEnvironment)).not.toContain(source); + expect(JSON.stringify(options.launchEnvironment)).not.toContain(credential.refresh_token); + throw new Error("fixture finished"); + }); + await expect(AcpxRuntimeHost.open({ ...fixture.options, agent: "antigravity", model: "gemini-3.8-flash-low", + permissionMode: "approve-all", providerPolicy: { readOnly: false }, + environment: { PAPERCLIP_ACPX_AUTH_JSON_FILE: source }, managedCredentialSourcePath: source, + }, fixture.dependencies({ openRuntime }))).rejects.toThrow("fixture finished"); + expect(openRuntime).toHaveBeenCalledOnce(); + }); + const hostCredentialFiles = { codex: { model: "gpt-5.6-sol", permissionMode: "approve-all" as const, home: "CODEX_HOME", document: JSON.stringify({ tokens: { account_id: "account-1", access_token: "host-access", refresh_token: "host-refresh" }, last_refresh: "2026-01-01T00:00:00Z" }),