From 9092b0c66765fdb8d71b0a8bd7add52abc05a03d Mon Sep 17 00:00:00 2001 From: Nicky Leach Date: Wed, 2 Dec 2026 01:49:46 +0000 Subject: [PATCH] Support live Antigravity credential writeback for both token stores (#23397) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip manages the connections agents use to work. > - A run can outlive the Google refresh token that started it. > - Antigravity writes a rotated token to a private file. Its two runtimes use different paths and JSON layouts. > - The task already records which connection supplied its sign-in. > - Runner reports a rotation on PRP. Core saves it to that connection if the saved generation still matches. > - The next run can start with the rotated token. ## Linked Issues or Issue Description Refs #23395. Refs #23168. This PR targets `master` and includes the capability-based handler from #23395. Merging this PR lands the handler and Antigravity writeback together. **Current behavior** A managed Antigravity sign-in reaches the plugin as an environment credential. Core waits for task retirement to collect a refresh. **Proposed behavior** Seed a private auth-file. Observe refresh-token changes for the ordinary ACP server and the unified CLI. Use the existing credential update event to save them during execution. **Reason and benefit** A long-running task can keep its source connection current across successive rotations. ## What Changed - Dispatch PRP credential updates to the live writeback capability declared for the bound harness and execution target. - Send Antigravity subscriptions as auth-file credentials to environment task providers. Keep Gemini API keys and previously admitted environment credentials on their existing paths. - Watch the ACP token file and the unified CLI token file. Compare the refresh token, copy it to the bound file, and emit the existing secret-free event. - Bind writeback to the original grant, secret, session epoch, and credential generation. Save the next generation in the same transaction. ## Verification - Reproduced the failed final Google save hanging on the next session close. After commit `2b3e7897cd`, both focused cleanup suites passed (43 tests). The regression covers two overlapping close retries after the credential home is released and checks that the saved credential is removed only after persistence succeeds. - All 21 Rust observer tests passed on both builds. They cover interruption between the host file and event journal writes, a further rotation before restart, and a reconnect that supersedes the task. - On the legacy build, 422 Runner TypeScript tests passed. With the merged unified CLI on this branch, all 126 tests in the auth, credential staging, and runtime host suites passed. - The two plugin writeback database suites passed (39 tests). A refresh that starts before task stop cannot overwrite the final token after stop. - One run timed out in an unrelated process-retirement test. All three suites passed together on repeat. All OAuth documents in these tests are fixtures. No live Google sign-in was exercised. ## Risks - The agent and any process it starts are trusted not to substitute another account’s refresh token in the harness credential file. Core accepts the file’s refresh token for the original connection only while the grant, secret, session epoch, and expected credential generation still match. Substitution within that boundary is an accepted risk. [Review finding](https://github.com/paperclipai/paperclip/pull/23397#discussion_r4759261984) - Deploy with a plugin and Launcher that support the new auth-file provider. This branch includes the unified CLI from #23168 and still observes the legacy token format. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used OpenAI GPT-6 in Codex, with local code execution and GitHub CLI. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip --- doc/plugins/PLUGIN_ENVIRONMENT_TASKS.md | 36 ++- doc/runner-internals.md | 16 +- packages/paperclip-runner/protocol/README.md | 2 +- .../runner-core/src/acpx_sidecar_transport.rs | 6 +- .../runner-core/src/credential_observer.rs | 212 ++++++++++++++++-- .../runner-core/src/credential_write_back.rs | 10 +- .../src/tests/credential_observer.rs | 89 +++++++- .../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.test.ts | 27 +++ .../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 | 46 +++- .../plugin-task-credential-writeback.test.ts | 2 +- server/src/services/agent-environment-test.ts | 2 +- .../managed-ai-credential-writeback.ts | 72 ++++-- .../antigravity-run-start.test.ts | 5 +- .../antigravity-runner-credentials.test.ts | 24 +- .../antigravity-runner-credentials.ts | 8 +- .../native-credential-store.test.ts | 14 +- .../native-runtime/native-credential-store.ts | 11 +- .../native-credential-updates.test.ts | 20 +- .../native-credential-updates.ts | 9 +- .../native-credential-writeback.ts | 110 +++++++++ .../native-session-executor.test.ts | 39 +++- .../native-runtime/native-session-executor.ts | 102 +++------ .../plugin-runner-credentials.test.ts | 18 +- .../plugin-runner-credentials.ts | 10 +- .../plugin-runner-probe-antigravity.test.ts | 6 +- .../plugin-task-credential-writeback.ts | 35 ++- .../retained-ai-credential-cleanup.ts | 10 +- .../runner-e2e/source-sdk-public-inputs.json | 2 +- 34 files changed, 764 insertions(+), 207 deletions(-) create mode 100644 server/src/services/native-runtime/native-credential-writeback.ts diff --git a/doc/plugins/PLUGIN_ENVIRONMENT_TASKS.md b/doc/plugins/PLUGIN_ENVIRONMENT_TASKS.md index 8da8a514d92..a06a2d8bf9a 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 4097fcde5e2..9bf3116f7e2 100644 --- a/doc/runner-internals.md +++ b/doc/runner-internals.md @@ -705,10 +705,18 @@ pnpm exec vitest run server/src/__tests__/native-session-resumption.test.ts -t ' ## Native Runner credential refreshes -Core handles PRP `auth.credentials.updated` notifications for managed Codex and -Grok subscriptions across local, SSH, sandbox, and supported plugin Runner tasks. -After validating the company, agent, run, session, and Runner binding, it exports -the selected account and writes newer credentials directly to the tenant secret. +Native credential preparation opts a harness into PRP `auth.credentials.updated` +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, 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 agent and any +process it starts are trusted not to substitute another account's token in the +harness credential file. Core accepts a rotation from that file for the connection +that seeded the run. 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..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,10 +408,14 @@ 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..452544b45c9 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 @@ -47,6 +47,8 @@ struct State { pending: Option, #[serde(default, skip_serializing_if = "Option::is_none")] host_file: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + write_intent: Option, #[serde(default, skip_serializing_if = "std::ops::Not::not")] silent: bool, } @@ -111,12 +113,21 @@ 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.write_intent.as_ref().is_some_and(|digest| { + state.provider != "antigravity" + || state.host_file.is_none() + || state.pending.is_some() + || !valid_digest(digest) + }) || state.revision > MAX_REVISION || state .snapshot @@ -153,11 +164,12 @@ 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(); next.host_file = host_file; + next.write_intent = None; self.save(&next)?; self.state = Some(next); self.written.clear(); @@ -187,11 +199,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 +222,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 +245,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,13 +272,28 @@ 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)) - .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); } + 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(), @@ -265,6 +303,7 @@ impl CredentialObserver { revision: 0, armed: false, pending: None, + write_intent: None, host_file, silent: !observe, }; @@ -285,7 +324,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 +354,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 +406,108 @@ impl CredentialObserver { Ok(()) } + fn poll_antigravity(&mut self) -> Result<(), DurableRunnerError> { + let state = self.state.clone().expect("configured observer"); + if state.pending.is_some() { + return Ok(()); + } + if let (Some(intent), Some(file)) = (&state.write_intent, &state.host_file) { + let (mut bytes, _) = credential_write_back::read_host_credential(file) + .map_err(|_| observer_error("cannot recover the bound Google credential"))?; + let host = parse_snapshot("antigravity", &bytes); + bytes.fill(0); + if let Some(host) = host.filter(|host| &host.fingerprint == intent) { + return self.finish_antigravity_rotation(state, host); + } + } + 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(()); + } + 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 { + 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 mut intent = state.clone(); + intent.write_intent = Some(snapshot.fingerprint.clone()); + self.save(&intent)?; + self.state = Some(intent); + 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")) + } + } + } + } + } + self.finish_antigravity_rotation(state, snapshot) + } + + fn finish_antigravity_rotation( + &mut self, + mut next: State, + snapshot: Snapshot, + ) -> Result<(), DurableRunnerError> { + if !next.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.write_intent = None; + next.snapshot = Some(snapshot); + self.save(&next)?; + self.state = Some(next); + Ok(()) + } + fn write_back( &mut self, provider: &str, @@ -460,7 +612,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 +655,31 @@ fn acpx_session_directory(session: &str) -> String { ) } +fn antigravity_refresh_token(value: &Value) -> Option<&str> { + value + .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) + }) +} + +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..71facf2db2f 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 @@ -24,6 +24,7 @@ impl Fixture { armed: false, pending: None, host_file: None, + write_intent: None, silent: false, }); observer.save(observer.state.as_ref().unwrap()).unwrap(); @@ -457,7 +458,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 +560,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 +596,87 @@ 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 { + 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(); + }; + 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(); + let mut interrupted = resumed.state.clone().unwrap(); + interrupted.write_intent = Some(antigravity_snapshot("intermediate").fingerprint); + resumed.save(&interrupted).unwrap(); + f.write( + "host.json", + &json!({"client_id":"selected-client","refresh_token":"intermediate"}), + ); + let mut resumed = CredentialObserver::new(&state_dir, "session"); + resumed + .restore_with_host_file(|| Ok(Some(host.clone()))) + .unwrap(); + write("rotated-again", "other-access"); + resumed.poll(true).unwrap(); + assert_eq!(resumed.pending(), Some(update_event("antigravity", 2))); + resumed.acknowledge(1).unwrap(); + resumed.poll(true).unwrap(); + assert_eq!(resumed.pending(), Some(update_event("antigravity", 3))); + assert_eq!( + serde_json::from_slice::(&fs::read(&host).unwrap()).unwrap()["refresh_token"], + "rotated-again" + ); + 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 0f64ac43df5..6878e157f08 100644 --- a/packages/paperclip-runner/src/drivers/acpx/codex-credentials.ts +++ b/packages/paperclip-runner/src/drivers/acpx/codex-credentials.ts @@ -800,7 +800,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.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" }), diff --git a/packages/paperclip-runner/src/drivers/acpx/runtime-host.ts b/packages/paperclip-runner/src/drivers/acpx/runtime-host.ts index 3ba77222c6b..2679e31f998 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"; @@ -48,6 +48,7 @@ import { } from "../runner-tool-bridge.js"; import { acquireAcpxProviderLifetimeLease, + readManagedCredential, stageManagedCodexCredential, type AcpxProviderLifetimeLease, } from "./codex-credentials.js"; @@ -403,6 +404,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") { @@ -458,7 +469,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 32b9104bcb8..397095dc17e 100644 --- a/server/src/__tests__/antigravity-plugin-task-credential-writeback.test.ts +++ b/server/src/__tests__/antigravity-plugin-task-credential-writeback.test.ts @@ -2,7 +2,7 @@ import { createHash, randomUUID } from "node:crypto"; import { mkdtemp, realpath, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { and, eq } from "drizzle-orm"; +import { and, eq, sql } from "drizzle-orm"; import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; import { activityLog, agents, companies, companyMemberships, connectionGrants, createDb, environmentLeases, environments, heartbeatRuns, plugins, toolConnections, @@ -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,45 @@ 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({ needsWriteback: 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("keeps a live export that overlaps task stop from consuming the final generation", async () => { + const f = await fixture(undefined, true); + const file = (token: string) => ({ type: "auth-file" as const, provider: "antigravity" as const, content: signIn(token) }); + const live = syncPluginTaskCredentialHandoff(db, f, async () => { + await db.update(environmentLeases).set({ + metadata: sql`${environmentLeases.metadata} || '{"runnerTaskExecutionStopped":true}'::jsonb`, + }).where(eq(environmentLeases.id, f.leaseId)); + return file("fixture-refreshed"); + }); + await expect(live).rejects.toThrow("authority changed"); + const exportAfterStop = vi.fn(async () => file("fixture-refreshed")); + await syncPluginTaskCredentialHandoff(db, f, exportAfterStop); + expect(exportAfterStop).not.toHaveBeenCalled(); + f.exportCredential(file("fixture-rotated")); + expect(await f.settle()).toBe("completed"); + expect(await f.credential()).toBe(signIn("fixture-rotated", { project_id: "fixture-project" })); + expect((await f.lease()).metadata?.runnerTaskCredentialHandoff).toMatchObject({ state: "complete", outcome: "rotated" }); + }); + 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/__tests__/plugin-task-credential-writeback.test.ts b/server/src/__tests__/plugin-task-credential-writeback.test.ts index 32b2fda0de4..182af3d3b22 100644 --- a/server/src/__tests__/plugin-task-credential-writeback.test.ts +++ b/server/src/__tests__/plugin-task-credential-writeback.test.ts @@ -150,7 +150,7 @@ suite("durable plugin task credential handoff", () => { payload: { schema: "paperclip.auth.credentials.updated.v1", provider: "codex", bindingId: "harness-auth", revision: 1, detection: "credential_store" }, }; const notification = { companyId: f.companyId, agentId: f.agentId, runnerInstanceId, normalizedSessionId, - event, synchronizeCredentials: f.synchronize }; + event, liveWriteback: { provider: "codex", synchronize: f.synchronize } }; f.failExport(true); await expect(appendNativeCredentialUpdate(db, notification)).rejects.toThrow(); expect(await f.credential()).toBe(auth("fixture-original")); 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 9b703a6a2d7..4f961e0b18b 100644 --- a/server/src/services/managed-ai-credential-writeback.ts +++ b/server/src/services/managed-ai-credential-writeback.ts @@ -6,8 +6,8 @@ import { createHash } from "node:crypto"; import { mkdir, mkdtemp, writeFile, rm, realpath } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { decideCodexAuthMerge, readSubscriptionAccountId, withAccountHomeSecretMutationLock } from "@paperclipai/adapter-codex-local/server"; -import { decideGrokAuthMerge, parseGrokAuthPayload, hasUsableGrokAuthValue } from "@paperclipai/adapter-grok-local/server"; +import { copyBackCodexAuth, decideCodexAuthMerge, readSubscriptionAccountId, withAccountHomeSecretMutationLock } from "@paperclipai/adapter-codex-local/server"; +import { copyBackGrokAuth, decideGrokAuthMerge, parseGrokAuthPayload, hasUsableGrokAuthValue } from "@paperclipai/adapter-grok-local/server"; import { WORKSPACE_RESTORE_LOCK_TIMEOUT_CODE } from "@paperclipai/adapter-utils/workspace-restore-merge"; import { aiConnectionService } from "./ai-connections.js"; import { secretService } from "./secrets.js"; @@ -24,15 +24,44 @@ export const managedAiCredentialWritebackBindingSchema = z.object({ }).strict(); export type ManagedAiCredentialWritebackBinding = z.infer; +type ReadAuth = () => Promise; + +const authFileStrategies = { + codex: { + provider: "codex", connectionProvider: "openai", decideMerge: decideCodexAuthMerge, + usable: (content: string) => readSubscriptionAccountId(Buffer.from(content)) !== null, + copyBack: async (home: string, readSandboxAuth: ReadAuth) => { + await copyBackCodexAuth({ hostAuthPath: join(home, "auth.json"), readSandboxAuth, log: () => {} }); + }, + }, + grok: { + provider: "grok", connectionProvider: "xai", decideMerge: decideGrokAuthMerge, + usable: (content: string) => { + try { + const parsed = parseGrokAuthPayload(JSON.parse(content)); + return parsed !== null && hasUsableGrokAuthValue(parsed.value); + } catch { return false; } + }, + copyBack: async (home: string, readSandboxAuth: ReadAuth) => { + await copyBackGrokAuth({ hostHomeDir: home, readSandboxAuth, log: () => {} }); + }, + }, +} as const; + +export function managedAuthFileStrategy(harness: string) { + return Object.hasOwn(authFileStrategies, harness) ? authFileStrategies[harness as keyof typeof authFileStrategies] : undefined; +} + /** Credential ownership survives the invocation home; reconnects and revocations win. */ export async function syncManagedAiCredentials( db: Db, companyId: string, binding: ManagedAiCredentialWritebackBinding, - provider: "codex" | "grok", + provider: keyof typeof authFileStrategies, fetchCredential: () => Promise, ) { managedAiCredentialWritebackBindingSchema.parse(binding); + const strategy = authFileStrategies[provider]; const home = await mkdtemp(join(await realpath(tmpdir()), "paperclip-ai-credential-")); try { // Revocation or an explicit account replacement intentionally discards an old refresh. @@ -52,7 +81,7 @@ export async function syncManagedAiCredentials( eq(toolConnections.companyId, companyId), eq(toolConnections.id, grant.connectionId), )); const ai = aiConnectionMetadataSchema.safeParse(connection?.config.ai); - if (!connection || !ai.success || ai.data.provider !== (provider === "codex" ? "openai" : "xai") || ai.data.method !== "subscription") return null; + if (!connection || !ai.success || ai.data.provider !== strategy.connectionProvider || ai.data.method !== "subscription") return null; return { connection, grant }; }; const mutate = (operation: (database: Db) => Promise) => withAccountHomeSecretMutationLock( @@ -64,15 +93,7 @@ export async function syncManagedAiCredentials( const credential = await fetchCredential(); if (credential === null) return "no_credentials" as const; // A partial provider write must replay, not be acknowledged as unchanged. - let usable = false; - if (provider === "codex") usable = readSubscriptionAccountId(Buffer.from(credential)) !== null; - else { - try { - const parsed = parseGrokAuthPayload(JSON.parse(credential)); - usable = parsed !== null && hasUsableGrokAuthValue(parsed.value); - } catch { /* Do not expose credential bytes through JSON parser errors. */ } - } - if (!usable) throw new Error("Managed credential snapshot invalid"); + if (!strategy.usable(credential)) throw new Error("Managed credential snapshot invalid"); const incoming = join(home, "incoming.json"), destination = join(home, "current.json"); await writeFile(incoming, credential, { mode: 0o600 }); const writeBack = () => mutate(async database => { @@ -80,7 +101,7 @@ export async function syncManagedAiCredentials( if (!selected) return "binding_changed" as const; const value = await aiConnectionService(database).credential(selected); await writeFile(destination, value, { mode: 0o600 }); - if (await (provider === "codex" ? decideCodexAuthMerge : decideGrokAuthMerge)(incoming, destination, { errorLabel: "AI account refresh" }) !== 10) return "unchanged" as const; + if (await strategy.decideMerge(incoming, destination, { errorLabel: "AI account refresh" }) !== 10) return "unchanged" as const; await secretService(database).rotate(binding.secretId, { value: credential, preserveAiSessionEpoch: true, }, { userId: selected.grant.subjectUserId }); @@ -108,6 +129,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"); @@ -132,7 +157,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( @@ -146,6 +171,23 @@ 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; + 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.test.ts b/server/src/services/native-runtime/antigravity-runner-credentials.test.ts index 67f979662bd..6f22d6e316b 100644 --- a/server/src/services/native-runtime/antigravity-runner-credentials.test.ts +++ b/server/src/services/native-runtime/antigravity-runner-credentials.test.ts @@ -7,7 +7,7 @@ import { antigravityAccountDigest, antigravityCredentialTurn, antigravitySwarmCh import { sanitizeAntigravityCredential } from "../../vendor/paperclip-runner/index.js"; import { completeManagedNativeCredentialTurn } from "./managed-native-credentials.js"; import type { NativeSession, createRunnerdCodexTransport } from "../../vendor/paperclip-runner/index.js"; -import { bindRetainedGoogleCredentialHome } from "../retained-google-credential-cleanup.js"; +import { bindRetainedGoogleCredentialHome, reconcileRetainedGoogleCleanup } from "../retained-google-credential-cleanup.js"; import { AntigravityConnectionConfigurationError, antigravityConnectionRefusal } from "./antigravity-connection-policy.js"; import { NATIVE_PROVIDER_STARTUP_REJECTED, nativeSessionFailureDisposition, nativeSessionFailureSourceCode } from "./native-session-executor.js"; @@ -273,6 +273,28 @@ describe("Antigravity managed Runner credentials", () => { expect(await readFile(destination, "utf8")).toBe(credential("fixture-refreshed")); await expect(access(source)).rejects.toMatchObject({ code: "ENOENT" }); }); + it("retries a failed final Google save through the retained account cleanup", async () => { + const managedHome = await home(), runtimeHome = await home(); + const scope = { companyId: "company", accountKey: managedHome }; + const release = bindRetainedGoogleCredentialHome(managedHome, scope); + const persist = vi.fn().mockRejectedValueOnce(new Error("save failed")).mockResolvedValue(undefined); + const runtimeStore = { read: vi.fn(), remove: vi.fn() }; + const close = vi.fn(async () => {}); + const session = bindAntigravityCredentialTurn({ close } as unknown as NativeSession, { + managedHome, runtimeHome, credential: credential("fixture-original"), runtimeStore, + saveRotation: async () => { await reconcileRetainedGoogleCleanup(scope); await persist(); }, + }); + try { + await expect(session.close({ reason: "final save" })).rejects.toThrow("save failed"); + expect(runtimeStore.remove).not.toHaveBeenCalled(); + } finally { release(); } + const retry = () => session.close({ reason: "retry final save" }); + await Promise.all([retry(), retry()]); + await reconcileRetainedGoogleCleanup(scope); + expect(persist).toHaveBeenCalledTimes(2); + expect(runtimeStore.remove).toHaveBeenCalledOnce(); + expect(close).toHaveBeenCalledOnce(); + }); it("settles the retained runtime refresh before reusing its original home", async () => { const managedHome = await home(), runtimeHome = await home(); const release = bindRetainedGoogleCredentialHome(managedHome, { companyId: "company", accountKey: managedHome }); diff --git a/server/src/services/native-runtime/antigravity-runner-credentials.ts b/server/src/services/native-runtime/antigravity-runner-credentials.ts index c840bfb3ac0..28244ee2b9c 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 }; }) { @@ -376,7 +377,8 @@ export function bindAntigravityCredentialTurn(session: NativeSession, input: Par await proveRetirement(); retired = true; }; - const retain = () => retainGoogleCredentialCleanupForHome(input.managedHome, { + let retryHandoff: (() => Promise) | undefined; + const retain = () => retryHandoff ??= retainGoogleCredentialCleanupForHome(input.managedHome, { cleanup: handoff, ...(retired ? {} : { retired: retirement, ...(proveRetirement ? { retryRetirement } : {}) }), }); const retire: NativeSession["close"] = options => retirement ??= Promise.resolve().then(() => close(options)).catch(error => { @@ -395,7 +397,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 @@ -416,7 +418,7 @@ export function bindAntigravityCredentialTurn(session: NativeSession, input: Par await managedClose(options); // The shared turn manager settles a failed turn once. Google retains its // failed handoff, so a later close also retries the original private files. - if (!removed) await handoff(); + if (!removed) await (retryHandoff ?? handoff)(); }; return session; } diff --git a/server/src/services/native-runtime/native-credential-store.test.ts b/server/src/services/native-runtime/native-credential-store.test.ts index 0be089e8d34..de4e5c1edf0 100644 --- a/server/src/services/native-runtime/native-credential-store.test.ts +++ b/server/src/services/native-runtime/native-credential-store.test.ts @@ -8,7 +8,7 @@ import { createNativeCredentialStore } from "./native-credential-store.js"; const execute = promisify(execFile), roots: string[] = []; afterEach(async () => { await Promise.all(roots.splice(0).map(root => rm(root, { recursive: true, force: true }))); }); -async function fixture(target: "local" | "ssh" | "sandbox", provider: "codex" | "grok" | "antigravity" = "codex") { +async function fixture(target: "local" | "ssh" | "sandbox", filename: "auth.json" | "acp_token.json" = "auth.json") { const root = await realpath(await mkdtemp(join(tmpdir(), "native-credential-store-"))); roots.push(root); const localHome = join(root, "local"), remoteHome = join(root, "remote"); await mkdir(localHome); await mkdir(remoteHome); @@ -22,7 +22,7 @@ async function fixture(target: "local" | "ssh" | "sandbox", provider: "codex" | return { exitCode: (error as { code: number }).code, stdout: "", stderr: "" }; } }) }; - return { home, runner, store: createNativeCredentialStore({ provider, localHome, + return { home, runner, store: createNativeCredentialStore({ filename, localHome, ...(target === "local" ? {} : { remoteHome, runner: runner as never }) }) }; } @@ -35,8 +35,8 @@ it.each(["local", "ssh", "sandbox"] as const)("exports %s snapshots only on dema await expect(store.read()).rejects.toMatchObject({ code: "ENOENT" }); }); -it.each((["codex", "grok", "antigravity"] as const).flatMap(provider => (["local", "ssh", "sandbox"] as const).map(target => ({ provider, target }))))("uses the $provider close handoff for $target when primary token file is absent", async ({ target, provider }) => { - const { home, store } = await fixture(target, provider); +it.each((["auth.json", "acp_token.json"] as const).flatMap(filename => (["local", "ssh", "sandbox"] as const).map(target => ({ filename, target }))))("uses the $filename close handoff for $target when primary token file is absent", async ({ target, filename }) => { + const { home, store } = await fixture(target, filename); await writeFile(join(home, "auth-refresh.json"), '{"synthetic":"refresh"}', { mode: 0o600 }); expect(await store.read()).toBe('{"synthetic":"refresh"}'); await store.remove(); @@ -44,7 +44,7 @@ it.each((["codex", "grok", "antigravity"] as const).flatMap(provider => (["local }); it.each(["local", "ssh", "sandbox"] as const)("reads and removes antigravity acp_token.json on %s targets", async target => { - const { home, store } = await fixture(target, "antigravity"); + const { home, store } = await fixture(target, "acp_token.json"); await writeFile(join(home, "acp_token.json"), '{"refresh_token":"synthetic"}', { mode: 0o600 }); expect(await store.read()).toBe('{"refresh_token":"synthetic"}'); await store.remove(); @@ -52,7 +52,7 @@ it.each(["local", "ssh", "sandbox"] as const)("reads and removes antigravity acp }); it.each(["local", "ssh", "sandbox"] as const)("rejects unsafe %s files without falling back to another credential", async target => { - const { home, store } = await fixture(target, "grok"); + const { home, store } = await fixture(target, "auth.json"); await writeFile(join(home, "auth-refresh.json"), "must-not-read", { mode: 0o600 }); await writeFile(join(home, "auth.json"), "unsafe", { mode: 0o644 }); await expect(store.read()).rejects.toThrow(); @@ -66,7 +66,7 @@ it.each(["local", "ssh", "sandbox"] as const)("rejects unsafe %s files without f it("rejects truncated remote replies and timeouts", async () => { const runner = { execute: vi.fn(async () => ({ exitCode: 0, stdout: "not-base64!", timedOut: false })) }; - const store = createNativeCredentialStore({ provider: "codex", localHome: "/unused", remoteHome: "/owned", runner: runner as never }); + const store = createNativeCredentialStore({ filename: "auth.json", localHome: "/unused", remoteHome: "/owned", runner: runner as never }); await expect(store.read()).rejects.toThrow("export invalid"); runner.execute.mockResolvedValue({ exitCode: 0, stdout: "", timedOut: true }); await expect(store.read()).rejects.toThrow("export unavailable"); diff --git a/server/src/services/native-runtime/native-credential-store.ts b/server/src/services/native-runtime/native-credential-store.ts index c6775c0b5ad..479b0d9ef25 100644 --- a/server/src/services/native-runtime/native-credential-store.ts +++ b/server/src/services/native-runtime/native-credential-store.ts @@ -37,13 +37,12 @@ try { }`; export function createNativeCredentialStore(input: { - provider: "codex" | "grok" | "antigravity"; + filename: "auth.json" | "acp_token.json" | "antigravity-oauth-token"; localHome: string; remoteHome?: string; runner?: Pick; }) { if (Boolean(input.remoteHome) !== Boolean(input.runner)) throw new Error("native_credential_store_target_unavailable"); - const names = input.provider === "antigravity" ? ["acp_token.json", "auth-refresh.json"] : ["auth.json", "auth-refresh.json"]; const read = async (name: string): Promise => { if (!input.runner || !input.remoteHome) return readLocalAiCredentialFile(join(input.localHome, name)); // Remote isolated-home preparation already requires Node. Read only on a refresh or retirement. @@ -57,14 +56,14 @@ export function createNativeCredentialStore(input: { }; return { read: async () => { - try { return await read(names[0]!); } + try { return await read(input.filename); } catch (error) { - if (names.length !== 2 || (error as NodeJS.ErrnoException).code !== "ENOENT") throw error; - return read(names[1]!); + if (input.filename === "antigravity-oauth-token" || (error as NodeJS.ErrnoException).code !== "ENOENT") throw error; + return read("auth-refresh.json"); } }, remove: async () => { - for (const name of [...names, "auth-refresh.json.tmp"]) { + for (const name of [input.filename, "auth-refresh.json", "auth-refresh.json.tmp"]) { await rm(join(input.localHome, name), { force: true }); if (input.runner && input.remoteHome) { const result = await input.runner.execute({ command: "rm", args: ["-f", "--", posix.join(input.remoteHome, name)], bypassSession: true, timeoutMs: 10_000 }); diff --git a/server/src/services/native-runtime/native-credential-updates.test.ts b/server/src/services/native-runtime/native-credential-updates.test.ts index 970bf5fdf8a..a21f9c2d14e 100644 --- a/server/src/services/native-runtime/native-credential-updates.test.ts +++ b/server/src/services/native-runtime/native-credential-updates.test.ts @@ -66,14 +66,28 @@ it("retries credential writeback after the event is durably recorded", async () const synchronizeCredentials = vi.fn().mockRejectedValueOnce(new Error("synthetic writeback failure")) .mockResolvedValue(undefined); const update = { ...event, sourceSeq: 10, sourceEventId: "credential_update_retry", payload: { ...event.payload, revision: 2 } }; - await expect(appendNativeCredentialUpdate(db, { ...binding, event: update, synchronizeCredentials })) + const liveWriteback = { provider: "codex", synchronize: synchronizeCredentials }; + await expect(appendNativeCredentialUpdate(db, { ...binding, event: update, liveWriteback })) .rejects.toThrow("synthetic writeback failure"); - await appendNativeCredentialUpdate(db, { ...binding, event: update, synchronizeCredentials }); + await appendNativeCredentialUpdate(db, { ...binding, event: update, liveWriteback }); expect(synchronizeCredentials).toHaveBeenCalledTimes(2); const rows = await db.select().from(heartbeatRunEvents).where(eq(heartbeatRunEvents.runId, runId)); expect(rows.filter(row => row.sourceEventId === `credentials:${update.sourceEventId}`)).toHaveLength(1); synchronizeCredentials.mockClear(); - await expect(appendNativeCredentialUpdate(db, { ...binding, companyId: randomUUID(), event: update, synchronizeCredentials })) + await expect(appendNativeCredentialUpdate(db, { ...binding, companyId: randomUUID(), event: update, liveWriteback })) .rejects.toThrow("binding_mismatch"); expect(synchronizeCredentials).not.toHaveBeenCalled(); }); + +it("dispatches only the selected harness-auth live writeback capability", async () => { + const synchronize = vi.fn(async () => {}); + const update = { ...event, sourceSeq: 11, sourceEventId: "new-harness-update", + payload: { ...event.payload, provider: "fixture-harness" } }; + const input = { ...binding, event: update, liveWriteback: { provider: "fixture-harness", synchronize } }; + await appendNativeCredentialUpdate(db, input); + expect(synchronize).toHaveBeenCalledOnce(); + for (const payload of [{ ...update.payload, provider: "other" }, { ...update.payload, bindingId: "other" }]) { + await expect(appendNativeCredentialUpdate(db, { ...input, event: { ...update, payload } })).rejects.toThrow("mismatch"); + } + expect(synchronize).toHaveBeenCalledOnce(); +}); diff --git a/server/src/services/native-runtime/native-credential-updates.ts b/server/src/services/native-runtime/native-credential-updates.ts index 5ac9b5a2c97..04a56ec3a36 100644 --- a/server/src/services/native-runtime/native-credential-updates.ts +++ b/server/src/services/native-runtime/native-credential-updates.ts @@ -3,13 +3,15 @@ import { heartbeatRuns, type Db } from "@paperclipai/db"; import { validatePrpEvent, type PrpEvent, type NativeSession } from "../../vendor/paperclip-runner/index.js"; import { appendHeartbeatRunEvent } from "../heartbeat-run-events.js"; +export type LiveCredentialWriteback = { provider: string; synchronize: () => Promise }; + export async function appendNativeCredentialUpdate(db: Db, input: { companyId: string; agentId: string; normalizedSessionId: string; runnerInstanceId: string; event: PrpEvent; - synchronizeCredentials?: () => Promise; + liveWriteback?: LiveCredentialWriteback; }): Promise { const parsed = validatePrpEvent(input.event); if (!parsed.ok || parsed.event.eventType !== "auth.credentials.updated" @@ -19,6 +21,9 @@ export async function appendNativeCredentialUpdate(db: Db, input: { throw new Error("native_credential_update_binding_mismatch"); } const event = parsed.event; + if (input.liveWriteback && (event.payload.provider !== input.liveWriteback.provider || event.payload.bindingId !== "harness-auth")) { + throw new Error("native_credential_update_binding_mismatch"); + } await db.transaction(async tx => { const [run] = await tx.select({ id: heartbeatRuns.id }).from(heartbeatRuns) .where(and(eq(heartbeatRuns.id, event.runId), eq(heartbeatRuns.companyId, input.companyId), @@ -43,7 +48,7 @@ export async function appendNativeCredentialUpdate(db: Db, input: { }, }); }); - await input.synchronizeCredentials?.(); + await input.liveWriteback?.synchronize(); } type CredentialUpdateOwner = { handle: (event: PrpEvent) => Promise; detached: boolean; closing: boolean }; diff --git a/server/src/services/native-runtime/native-credential-writeback.ts b/server/src/services/native-runtime/native-credential-writeback.ts new file mode 100644 index 00000000000..f87d5a23c62 --- /dev/null +++ b/server/src/services/native-runtime/native-credential-writeback.ts @@ -0,0 +1,110 @@ +import { join, posix, resolve } from "node:path"; +import type { CommandManagedRuntimeRunner } from "@paperclipai/adapter-utils/command-managed-runtime"; +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, 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"; +import type { LiveCredentialWriteback } from "./native-credential-updates.js"; + +type NativeCredentialWriteback = { + liveWriteback?: LiveCredentialWriteback; + bindTurn?: (session: NativeSession) => NativeSession; +}; + +export function prepareNativeCredentialWriteback(input: { + db: Db; + companyId: string; + runId: string; + binding?: ManagedAiCredentialWritebackBinding; + provider: NativeExecutionInput["provider"]; + root: string; + sessionId: string; + preconfiguredHome: boolean; + destinationHome?: string | null; + antigravityCredential?: { home: string | null; credential?: string } | null; + remote?: { root: string; runner: Pick }; +}): NativeCredentialWriteback | undefined { + const { provider, binding, destinationHome, remote, antigravityCredential } = input; + const harness = provider.kind === "acpx" ? provider.agent : provider.kind; + const strategy = managedAuthFileStrategy(harness); + if (!strategy && !antigravityCredential?.credential) return; + if (strategy && input.preconfiguredHome) return {}; + const relativeHome = provider.kind === "acpx" + ? `acpx/acpx/${acpxRuntimeSessionDirectoryName(input.sessionId)}/${harness}-home` : "codex-home"; + const runtimeHome = provider.kind === "acpx" + ? resolve(resolvePaperclipInstanceRoot(), "runtime", "paperclip-runner", relativeHome) : join(input.root, relativeHome); + + if (antigravityCredential?.home && antigravityCredential.credential) { + const { home: managedHome, credential } = antigravityCredential; + const runtimeStore = createNativeCredentialStore({ + filename: "acp_token.json", localHome: join(runtimeHome, "antigravity-acp"), + ...(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; + const store = createNativeCredentialStore({ filename: "auth.json", localHome: runtimeHome, + ...(remote ? { remoteHome: posix.join(remote.root, relativeHome), runner: remote.runner } : {}) }); + const synchronize = binding ? async () => { + const outcome = await syncManagedAiCredentials(input.db, input.companyId, binding, strategy.provider, store.read); + if (outcome === "no_credentials") throw new Error("Native credential snapshot unavailable"); + } : undefined; + return { + liveWriteback: synchronize ? { provider: harness, synchronize } : undefined, + bindTurn: destinationHome ? session => bindManagedNativeCredentialTurn(session, { + copyBack: synchronize ? async () => {} : async () => { + await strategy.copyBack(destinationHome, async () => Buffer.from(await store.read())); + }, + retire: synchronize, remove: store.remove, + }) : undefined, + }; +} diff --git a/server/src/services/native-runtime/native-session-executor.test.ts b/server/src/services/native-runtime/native-session-executor.test.ts index bf2662d1463..b0450fe54a2 100644 --- a/server/src/services/native-runtime/native-session-executor.test.ts +++ b/server/src/services/native-runtime/native-session-executor.test.ts @@ -139,6 +139,7 @@ import { canonicalProviderPackJson } from "./remote-provider-pack-verification.j import * as providerPackAdmission from "./native-provider-pack-admission.js"; import * as providerArtifactStorage from "./native-provider-artifacts.js"; import * as providerArtifactCapture from "./native-provider-artifact-capture.js"; +import * as nativeCredentialWriteback from "./native-credential-writeback.js"; import * as nativeCredentialEvents from "./native-credential-updates.js"; import * as nativeCredentialStores from "./native-credential-store.js"; import * as antigravityRelease from "./antigravity-release.js"; @@ -18773,7 +18774,7 @@ describe("runnerd provider runtime wiring", () => { expect(transport.environment?.GOOGLE_API_KEY).toBeUndefined(); const session = await backend.openSession({} as never); expect(storeSpy).toHaveBeenCalledWith(expect.objectContaining({ - provider: "antigravity", + filename: "acp_token.json", remoteHome: expect.stringMatching(/\/acpx\/acpx\/[^/]+\/antigravity-home\/antigravity-acp$/), })); await session.close({ reason: "completed" }); @@ -20496,6 +20497,37 @@ describe("runnerd provider runtime wiring", () => { } finally { portable?.mockRestore(); } }); + it.each([true, false])("routes OpenCode credential events with live writeback capability %s", async enabled => { + const current = scopedNativeExecution("credential-capability"); + const run: NativeExecutionInput = { ...current, provider: { kind: "opencode", model: "openai/test" } }; + const synchronize = vi.fn(async () => {}); + const liveWriteback = enabled ? { provider: "opencode", synchronize } : undefined; + const prepared = vi.spyOn(nativeCredentialWriteback, "prepareNativeCredentialWriteback").mockReturnValue(liveWriteback ? { liveWriteback } : undefined); + const append = vi.spyOn(nativeCredentialEvents, "appendNativeCredentialUpdate").mockResolvedValue(undefined); + try { + await createRunnerdBackend({ db: leaseDb(current), execution: run, runnerInstanceId: "capability-runner" }); + state.createBackend.mock.calls.at(-1)![1].codexTransportFactory!(); + const event: PrpEvent = { + schema: "paperclip.prp.event.v3", schemaVersion: 3, sourceKind: "runner", sourceInstanceId: "capability-runner", + sourceEventId: "refresh", sourceSeq: 1, emittedAt: "2020-01-01T00:00:00Z", priority: 0, + runId: run.binding.runId, normalizedSessionId: run.session.normalizedSessionId!, eventType: "auth.credentials.updated", + payload: { schema: "paperclip.auth.credentials.updated.v1", provider: "opencode", bindingId: "harness-auth", + revision: 1, detection: "native_hook" }, + }; + const handler = state.createTransport.mock.calls.at(-1)![0].onCredentialsUpdated; + if (enabled) { + await handler!(event); + expect(append).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ event, liveWriteback })); + } else { + expect(handler).toBeUndefined(); + expect(append).not.toHaveBeenCalled(); + } + } finally { + append.mockRestore(); + prepared.mockRestore(); + } + }); + it.each(["codex", "acpx-codex", "grok"] as const)("writes managed %s events through the current warm exporter without per-turn reads", async provider => { const root = await realpath(await mkdtemp(join(tmpdir(), "native-managed-refresh-"))); const previousRoot = process.env.PAPERCLIP_RUNNER_STATE_DIR; @@ -20515,7 +20547,7 @@ describe("runnerd provider runtime wiring", () => { const persist = vi.spyOn(managedCredentialWriteback, "syncManagedAiCredentials").mockImplementation(async (_db, _company, _binding, _provider, read) => { await read(); return "rotated"; }); - const append = vi.spyOn(nativeCredentialEvents, "appendNativeCredentialUpdate").mockImplementation(async (_db, input) => { await input.synchronizeCredentials?.(); }); + const append = vi.spyOn(nativeCredentialEvents, "appendNativeCredentialUpdate").mockImplementation(async (_db, input) => { await input.liveWriteback?.synchronize(); }); const binding = { grantId: "10000000-0000-4000-8000-000000000001", secretId: "10000000-0000-4000-8000-000000000002", sessionEpoch: 1, versionSelector: "latest" as const }; const session = { close: vi.fn(async () => {}) } as unknown as NativeSession; try { @@ -20553,9 +20585,6 @@ describe("runnerd provider runtime wiring", () => { expect(nextStore.read).toHaveBeenCalledTimes(2); expect(firstStore.remove).not.toHaveBeenCalled(); expect(nextStore.remove).toHaveBeenCalledOnce(); expect(stores.mock.calls[0]![0].localHome).toContain(provider === "grok" ? "grok-home" : "codex-home"); - persist.mockClear(); - await expect(retainedHook({ ...notification, payload: { provider: "unexpected" } })).rejects.toThrow("provider_mismatch"); - expect(persist).not.toHaveBeenCalled(); } finally { stores.mockRestore(); persist.mockRestore(); append.mockRestore(); if (previousRoot === undefined) delete process.env.PAPERCLIP_RUNNER_STATE_DIR; diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index 0dd0ab70436..f5535d2da5c 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -125,8 +125,7 @@ import { prepareGrokRunnerCredentials } from "./grok-runner-credentials.js"; import { AntigravityConnectionConfigurationError, antigravityConnectionRefusal } from "./antigravity-connection-policy.js"; import { antigravityCandidateTarget, antigravityForcesSameSessionRecovery, antigravityReleasePending, antigravityUsesRunScopedState, assertAntigravityExecutionAdmissible } from "./antigravity-release.js"; import { ANTIGRAVITY_SWARM_UNAVAILABLE } from "../antigravity-swarm-refusal.js"; -import { bindAntigravityCredentialTurn, bindAntigravityTransportRetirement, prepareAntigravityRunnerCredentials } from "./antigravity-runner-credentials.js"; -import { copyBackGrokAuth } from "@paperclipai/adapter-grok-local/server"; +import { bindAntigravityTransportRetirement, prepareAntigravityRunnerCredentials } from "./antigravity-runner-credentials.js"; import { inferOpenAiCompatibleBiller, type AdapterUsageCheckpoint } from "@paperclipai/adapter-utils"; import { createAgentIdentityRedactor } from "../agent-identity-redaction.js"; @@ -143,14 +142,13 @@ import { createNativeDeliverableTextObservation } from "./native-deliverable-tex import { reconcileControllerJournalWithRunner, refreshRetiredWarmOwnerProjection } from "./warm-controller-journal.js"; import { createNativeGitHubAccess, type NativeGitHubAccess } from "./native-github-access.js"; import { resolveGitHubOperationCredentials } from "../github-operation-credentials.js"; -import { syncManagedAiCredentials, type ManagedAiCredentialWritebackBinding } from "../managed-ai-credential-writeback.js"; -import { createNativeCredentialStore } from "./native-credential-store.js"; -import { bindManagedNativeCredentialTurn, completeManagedNativeCredentialTurn } from "./managed-native-credentials.js"; +import type { ManagedAiCredentialWritebackBinding } from "../managed-ai-credential-writeback.js"; +import { prepareNativeCredentialWriteback } from "./native-credential-writeback.js"; +import { completeManagedNativeCredentialTurn } from "./managed-native-credentials.js"; import { createLocalNativeQuestionBridge } from "./local-native-question-bridge.js"; import { createArtifactInstaller } from "./artifact-transfer.js"; import { imageGenerationBindingForRun } from "./generate-image-tool.js"; import { readVerifiedRemoteWorkspaceFile } from "./remote-deliverable-file.js"; -import { copyBackCodexAuth } from "@paperclipai/adapter-codex-local/server"; import { nativeCompletionFeedback } from "./native-completion-feedback.js"; import { hasAcknowledgedNativeLifecycleStopIntent, hasAcknowledgedNativeReassignmentStopIntent, hasAcknowledgedNativeStopIntent, hasAcknowledgedNativeRunStopReceipt } from "../acknowledged-native-stop.js"; import { stoppedCodexTurnIsTextOnly } from "./stopped-codex-turn.js"; @@ -17130,13 +17128,14 @@ async function createRunnerdBackendWithinSessionClaim( }); if (refusal) throw new AntigravityConnectionConfigurationError(refusal); } + const harness = provider.kind === "acpx" ? provider.agent : provider.kind; const credentials = await preparePluginRunnerCredentials({ - provider: provider.kind === "acpx" ? provider.agent : provider.kind, + provider: harness, identity: input.managedAiCredentialIdentity, accountIdentity: input.managedAiAccountIdentity, home: input.managedAiCredentialHome, environment: input.runnerEnvironment ?? {}, }); - if (credentials.needsWriteback && (!input.managedAiCredentialWriteback - || (credentials.credential?.type === "provider-env") !== Boolean(input.managedAiCredentialWriteback.google))) { + if (credentials.writeback && (!input.managedAiCredentialWriteback + || Boolean(credentials.writeback.requiresGoogleGeneration) !== Boolean(input.managedAiCredentialWriteback.google))) { throw new Error("Plugin Runner credential writeback authority unavailable"); } // Same-lease recovery already has a writeback binding. A portable move creates a new lease. @@ -17160,13 +17159,16 @@ async function createRunnerdBackendWithinSessionClaim( normalizedSessionId: nativeSessionKey(input.execution), runnerInstanceId: adoptionIdentity?.runnerInstanceId ?? prior?.runnerInstanceId ?? effectiveRunnerInstanceId, event, - synchronizeCredentials: credentials.credential?.type === "auth-file" && event.payload.provider === credentials.credential.provider ? () => syncPluginTaskCredentialHandoff(input.db, { - companyId: input.execution.binding.companyId, leaseId: remoteTarget.leaseId!, expectedTaskId: description.taskId, - }, async accountIdentity => { - const snapshot = environmentTaskResultSchema.parse(await pluginTask({ kind: "credentials", accountIdentity }, { expectedTaskId: description.taskId })); - if (snapshot.kind !== "credentials") throw new Error("Plugin Runner credential snapshot unavailable"); - return snapshot.credential; - }) : undefined, + liveWriteback: credentials.writeback?.mode === "live" ? { + provider: harness, + synchronize: () => syncPluginTaskCredentialHandoff(input.db, { + companyId: input.execution.binding.companyId, leaseId: remoteTarget.leaseId!, expectedTaskId: description.taskId, + }, async accountIdentity => { + const snapshot = environmentTaskResultSchema.parse(await pluginTask({ kind: "credentials", accountIdentity }, { expectedTaskId: description.taskId })); + if (snapshot.kind !== "credentials") throw new Error("Plugin Runner credential snapshot unavailable"); + return snapshot.credential; + }), + } : undefined, }), warmTaskVersion: description.warmTaskVersion, githubCredentialBrokerVersion: description.githubCredentialBrokerVersion, @@ -17187,7 +17189,7 @@ async function createRunnerdBackendWithinSessionClaim( runId: prior.runId, normalizedSessionId: prior.normalizedSessionId, turnId: prior.turnId ?? "", itemId: prior.itemId ?? "", } : undefined), projectAuthCheckVersion: description.projectAuthCheckVersion, task: pluginTask, projectIds: remoteTarget.runnerTaskProjectIds ?? [], - harness: provider.kind === "acpx" ? provider.agent : provider.kind, resumeFrom, priorIdentity: prior ? { + harness, resumeFrom, priorIdentity: prior ? { runnerInstanceId: prior.runnerInstanceId, environmentLeaseId: prior.environmentLeaseId, runId: prior.runId, normalizedSessionId: prior.normalizedSessionId, turnId: typeof prior.turnId === "string" ? prior.turnId : "", @@ -19044,33 +19046,16 @@ async function createRunnerdBackendWithinSessionClaim( owner => logger.warn({ companyId: owner.companyId, runId: owner.runId }, "Native session diagnostic recording failed")); const diagnosticLease = diagnostics.activate(diagnosticOwner, input.onLog); input.onDiagnosticLease?.(diagnosticLease); - const credentialProvider = input.execution.provider.kind === "codex" ? "codex" - : input.execution.provider.kind === "acpx" && (input.execution.provider.agent === "codex" || input.execution.provider.agent === "grok") - ? input.execution.provider.agent : null; - const acpxCredential = input.execution.provider.kind === "acpx"; - const credentialRelativeHome = credentialProvider && acpxCredential - ? `acpx/acpx/${acpxRuntimeSessionDirectoryName(nativeSessionKey(input.execution))}/${credentialProvider}-home` : "codex-home"; - const credentialStore = credentialProvider && !preconfiguredHome ? createNativeCredentialStore({ - provider: credentialProvider, - localHome: acpxCredential ? resolve(resolvePaperclipInstanceRoot(), "runtime", "paperclip-runner", credentialRelativeHome) : join(root, "codex-home"), - ...(remoteRunnerFilesystemRoot && remoteCommandRunner ? { - remoteHome: posix.join(remoteRunnerFilesystemRoot, credentialRelativeHome), runner: remoteCommandRunner, - } : {}), - }) : null; - const synchronizeCredentials = input.managedAiCredentialWriteback && credentialProvider && credentialStore - ? async () => { - const outcome = await syncManagedAiCredentials(input.db, input.execution.binding.companyId, - input.managedAiCredentialWriteback!, credentialProvider, credentialStore.read); - if (outcome === "no_credentials") throw new Error("Native credential snapshot unavailable"); - } : undefined; - const credentialUpdates = credentialProvider ? createNativeCredentialUpdateOwner(event => appendNativeCredentialUpdate(input.db, { + const credentials = prepareNativeCredentialWriteback({ + 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, + }); + const credentialUpdates = credentials && createNativeCredentialUpdateOwner(event => appendNativeCredentialUpdate(input.db, { companyId: input.execution.binding.companyId, agentId: input.execution.binding.agentId, - normalizedSessionId: nativeSessionKey(input.execution), runnerInstanceId: effectiveRunnerInstanceId, event, - synchronizeCredentials: synchronizeCredentials ? async () => { - if (event.payload.provider !== credentialProvider) throw new Error("native_credential_update_provider_mismatch"); - await synchronizeCredentials(); - } : undefined, - })) : null; + normalizedSessionId: nativeSessionKey(input.execution), runnerInstanceId: effectiveRunnerInstanceId, event, liveWriteback: credentials.liveWriteback, + })); const backend = createNativeSessionBackend(runnerExecution, { retainedSystemInstructions, runnerInstanceId: @@ -19438,36 +19423,11 @@ async function createRunnerdBackendWithinSessionClaim( const detach = session.detachControllerForRestart?.bind(session); if (detach) session.detachControllerForRestart = async () => { cursorCloudRuntime.unregister(); return detach(); }; } - if (antigravityCredential?.home && antigravityCredential.credential && !boundManagedSessions.has(session)) { + if (credentials?.bindTurn && !boundManagedSessions.has(session)) { boundManagedSessions.add(session); - const relativeHome = `acpx/acpx/${acpxRuntimeSessionDirectoryName(nativeSessionKey(input.execution))}/antigravity-home`; - const runtimeHome = resolve(resolvePaperclipInstanceRoot(), "runtime", "paperclip-runner", relativeHome); - const runtimeStore = remoteRunnerFilesystemRoot && remoteCommandRunner - ? createNativeCredentialStore({ - provider: "antigravity", - localHome: join(runtimeHome, "antigravity-acp"), - remoteHome: posix.join(remoteRunnerFilesystemRoot, relativeHome, "antigravity-acp"), - runner: remoteCommandRunner, - }) - : undefined; - return bindAntigravityCredentialTurn(session, { - managedHome: antigravityCredential.home, credential: antigravityCredential.credential, runtimeHome, - ...(runtimeStore ? { runtimeStore } : {}), - }); + return credentials.bindTurn(session); } - const destinationHome = credentialProvider === "grok" ? grokCredential?.home : input.managedAiCredentialHome; - if (!credentialProvider || !credentialStore || !destinationHome || boundManagedSessions.has(session)) return session; - boundManagedSessions.add(session); - return bindManagedNativeCredentialTurn(session, { - copyBack: synchronizeCredentials ? async () => {} : async () => { - if (credentialProvider === "grok") await copyBackGrokAuth({ hostHomeDir: destinationHome, - readSandboxAuth: async () => Buffer.from(await credentialStore.read()), log: () => {} }); - else await copyBackCodexAuth({ hostAuthPath: join(destinationHome, "auth.json"), - readSandboxAuth: async () => Buffer.from(await credentialStore.read()), log: () => {} }); - }, - retire: synchronizeCredentials, - remove: credentialStore.remove, - }); + return session; }; input.executionContext?.signal.throwIfAborted(); const priorAuthorityEpoch = sessionToolAuthorityEpochs.get(sessionScopeId); 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 dccf6001724..c33b4c03a95 100644 --- a/server/src/services/native-runtime/plugin-runner-credentials.test.ts +++ b/server/src/services/native-runtime/plugin-runner-credentials.test.ts @@ -17,7 +17,7 @@ describe("plugin Runner selected credentials", () => { const directory = await home(auth); const transfer = await preparePluginRunnerCredentials({ provider: "codex", identity: "revision", accountIdentity: "account", home: directory, environment: {} }); expect(transfer.accountIdentity).toBe("account"); - expect(transfer.needsWriteback).toBe(true); + expect(transfer.writeback?.mode).toBe("live"); expect(transfer.credential).toEqual({ type: "auth-file", provider: "codex", content: JSON.stringify(auth) }); const refreshed = { ...auth, tokens: { ...auth.tokens, refresh_token: "fixture-rotated" }, last_refresh: "2021-01-01T00:00:00Z" }; await transfer.onCredentials!({ type: "auth-file", provider: "codex", content: JSON.stringify(refreshed) }); @@ -26,7 +26,7 @@ describe("plugin Runner selected credentials", () => { it("transfers a selected API key without requiring refresh authority", async () => { const directory = await home({ OPENAI_API_KEY: "fixture-key" }); const transfer = await preparePluginRunnerCredentials({ provider: "codex", identity: "revision", accountIdentity: "account", home: directory, environment: {} }); - expect(transfer.needsWriteback).toBe(false); + expect(transfer.writeback).toBeUndefined(); expect(transfer.credential).toEqual({ type: "auth-file", provider: "codex", content: JSON.stringify({ OPENAI_API_KEY: "fixture-key" }) }); }); it("transfers only the selected Claude authentication variable", async () => { @@ -61,7 +61,7 @@ describe("plugin Runner Google Antigravity credentials", () => { GOOGLE_GEMINI_BASE_URL: "https://router.example.test", GEMINI_HOME: "/controller/private/gemini", XAI_API_KEY: "fixture-xai", HOME: "/controller/private", OTHER_SECRET: "fixture-unrelated" } }); expect(transfer).toEqual({ accountIdentity: "account", credential: { type: "provider-env", provider: "antigravity", environment: { GEMINI_API_KEY: "fixture-gemini" } } }); - expect(transfer.needsWriteback).toBeUndefined(); + expect(transfer.writeback).toBeUndefined(); expect(transfer.onCredentials).toBeUndefined(); }); it.each([ @@ -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", needsWriteback: 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(); @@ -84,7 +84,7 @@ describe("plugin Runner Google Antigravity credentials", () => { const transfer = await preparePluginRunnerCredentials({ provider: "antigravity", identity: "revision", home: directory, environment: { ...blankManagedEnvironment, GEMINI_API_KEY: "fixture-gemini" } }); expect(transfer.credential).toEqual({ type: "provider-env", provider: "antigravity", environment: { GEMINI_API_KEY: "fixture-gemini" } }); - expect(transfer.needsWriteback).toBeUndefined(); + expect(transfer.writeback).toBeUndefined(); }); it.each([ ["a sign-in supplied through the environment", { PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET: "{\"refresh_token\":\"fixture-refresh\"}" }, "selected credential unavailable"], @@ -128,7 +128,7 @@ describe("plugin Runner provider environment credentials", () => { const transfer = await preparePluginRunnerCredentials({ provider, identity: "revision", accountIdentity: "account", environment: { ...blanks, ...environment, OPENCODE_CONFIG_CONTENT: "{\"provider\":{}}" } }); expect(transfer).toEqual({ accountIdentity: "account", credential: { type: "provider-env", provider, environment } }); - expect(transfer.needsWriteback).toBeUndefined(); + expect(transfer.writeback).toBeUndefined(); }); it("uses the credential revision as the account when no account identity is supplied", async () => { const transfer = await preparePluginRunnerCredentials({ provider: "copilot", identity: "revision", environment: { COPILOT_GITHUB_TOKEN: "fixture-copilot" } }); @@ -145,7 +145,7 @@ describe("plugin Runner provider environment credentials", () => { const directory = await home(grokAuth); const transfer = await preparePluginRunnerCredentials({ provider: "grok", identity: "revision", accountIdentity: "account", home: directory, environment: blanks }); - expect(transfer).toEqual({ accountIdentity: "account", needsWriteback: true, + expect(transfer).toEqual({ accountIdentity: "account", writeback: { mode: "live" }, credential: { type: "auth-file", provider: "grok", content: JSON.stringify(grokAuth) } }); }); it("refuses a Grok subscription without a usable sign-in file", async () => { diff --git a/server/src/services/native-runtime/plugin-runner-credentials.ts b/server/src/services/native-runtime/plugin-runner-credentials.ts index d6b00a98085..49fe41cef4f 100644 --- a/server/src/services/native-runtime/plugin-runner-credentials.ts +++ b/server/src/services/native-runtime/plugin-runner-credentials.ts @@ -15,7 +15,7 @@ interface PreparedPluginRunnerCredentials { githubBroker?: { url: string; token: string }; accountIdentity?: string; credential?: PluginEnvironmentTaskCredential; - needsWriteback?: boolean; + writeback?: { mode: "live" | "on_stop"; requiresGoogleGeneration?: true }; onCredentials?: (snapshot: PluginEnvironmentTaskCredential) => Promise; } @@ -40,7 +40,7 @@ export async function preparePluginRunnerCredentials(input: { const parsed = JSON.parse(authJson); if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("Plugin Runner selected credential invalid"); const credential = environmentTaskCredentialSchema.parse({ type: "auth-file", provider: "codex", content: authJson }); - return { ...github, accountIdentity, credential, needsWriteback: !!parsed.tokens, + return { ...github, accountIdentity, credential, writeback: parsed.tokens ? { mode: "live" } : undefined, onCredentials: async (snapshot: PluginEnvironmentTaskCredential) => { if (snapshot.type !== "auth-file" || snapshot.provider !== "codex") throw new Error("Plugin Runner credential provider mismatch"); await copyBackCodexAuth({ hostAuthPath, readSandboxAuth: async () => Buffer.from(snapshot.content), log: () => {} }); @@ -57,7 +57,7 @@ export async function preparePluginRunnerCredentials(input: { usable = parsed !== null && hasUsableGrokAuthValue(parsed.value); } catch { /* Do not expose credential bytes through JSON parser errors. */ } if (!usable) throw new Error("Plugin Runner selected credential invalid"); - return { ...github, accountIdentity, needsWriteback: true, + return { ...github, accountIdentity, writeback: { mode: "live" }, credential: environmentTaskCredentialSchema.parse({ type: "auth-file", provider: "grok", content }) }; } if (input.provider === "claude") { @@ -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, needsWriteback: 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 f8d91ee53d1..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", - needsWriteback: 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..30a55fdac52 100644 --- a/server/src/services/plugin-task-credential-writeback.ts +++ b/server/src/services/plugin-task-credential-writeback.ts @@ -65,17 +65,45 @@ 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); + if (handoff.provider === "antigravity" && lease.metadata.runnerTaskExecutionStopped === true) return; + 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`coalesce(${environmentLeases.metadata}->>'runnerTaskExecutionStopped', 'false') = ${metadata.runnerTaskExecutionStopped === true ? "true" : "false"}`, + 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 +112,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 +135,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({ diff --git a/server/src/services/retained-ai-credential-cleanup.ts b/server/src/services/retained-ai-credential-cleanup.ts index 78566c9ca6e..87221b00cdf 100644 --- a/server/src/services/retained-ai-credential-cleanup.ts +++ b/server/src/services/retained-ai-credential-cleanup.ts @@ -66,10 +66,11 @@ export function retainAiCredentialCleanup(input: { // Accept legacy Google home metadata for compatibility. Only the explicit // bindRetainedAiCredentialHome mapping grants home-to-account authority. scope: RetainedAiCleanupScope; cleanup: () => Promise; retired?: Promise; retryRetirement?: () => Promise; home?: string; -}): void { +}): () => Promise { const scopeKey = key(input.scope); const entries = retained.get(scopeKey) ?? new Set(); - if ([...entries].some(entry => entry.cleanup === input.cleanup)) return; + const existing = [...entries].find(entry => entry.cleanup === input.cleanup); + if (existing) return () => attempt(existing); const entry: Cleanup = { scope: { ...input.scope }, home: input.home, cleanup: input.cleanup, retryRetirement: input.retryRetirement, retired: input.retired ? "pending" : "confirmed" }; entries.add(entry); retained.set(scopeKey, entries); @@ -77,6 +78,7 @@ export function retainAiCredentialCleanup(input: { entry.retired = "confirmed"; return attempt(entry).catch(() => undefined); }, () => { entry.retired = "failed"; warn(entry); }); + return () => attempt(entry); } export async function reconcileRetainedAiCleanup(scope: RetainedAiCleanupScope): Promise { @@ -100,7 +102,7 @@ export async function reconcileRetainedAiCleanupForHome(home: string): Promise Promise; retired?: Promise; retryRetirement?: () => Promise; -}): void { +}): (() => Promise) | undefined { const scope = homes.get(home); - if (scope) retainAiCredentialCleanup({ ...input, scope, home }); + if (scope) return retainAiCredentialCleanup({ ...input, scope, home }); } diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index 0d9733fbc09..786d5203237 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",