use std::collections::{BTreeMap, VecDeque};
use std::sync::Arc;
use std::time::Duration;
use async_trait::async_trait;
use base64::engine::general_purpose::STANDARD as BASE64;
use base64::Engine as _;
use futures::stream::{self, BoxStream};
use serde::Deserialize;
use serde_json::json;
use tracing::warn;
use crate::error::{ErrorData, Result};
use crate::traits::{
Binding, CommandOutput, CreateSandboxRequest, JobError, JobExit, JobPoll, JobStart,
PreviewCapability, ResolvedSandbox, RunCommandRequest, Sandbox, SandboxInstance, SandboxState,
};
use alien_core::{SandboxCapabilities, SandboxEgress};
use alien_error::{AlienError, Context, ContextError};
use alien_gcp_clients::gcp::agent_platform::{
AgentPlatformApi, AgentPlatformErrorData, EgressControlConfig, SandboxCreateRequest,
SandboxEnvironment, SandboxSnapshot,
};
use alien_gcp_clients::gcp::longrunning::{Operation, OperationResult};
const AGENT_PROTOCOL_VERSION: u32 = 1;
const MAX_SYNCHRONOUS_TIMEOUT: Duration = Duration::from_secs(30);
const MAX_SANDBOX_ID: usize = 63;
pub const GCP_STREAM_REPLY_BUDGET: usize = 800_000;
pub const GCP_READ_PAGE_BYTES: usize = 900_000;
#[cfg(test)]
const GCP_REPLY_LIMIT_BYTES: usize = 2_000_000;
const SANDBOX_READY_ATTEMPTS: u32 = 150;
const SANDBOX_READY_INTERVAL: Duration = Duration::from_secs(2);
#[cfg(not(test))]
const AGENT_READY_TIMEOUT: Duration = Duration::from_secs(60);
#[cfg(not(test))]
const AGENT_READY_POLL: Duration = Duration::from_secs(1);
#[cfg(test)]
const AGENT_READY_TIMEOUT: Duration = Duration::from_millis(50);
#[cfg(test)]
const AGENT_READY_POLL: Duration = Duration::from_millis(5);
const OPERATION_POLL_ATTEMPTS: u32 = 150;
const OPERATION_POLL_INTERVAL: Duration = Duration::from_secs(2);
const LIFECYCLE_POLL_ATTEMPTS: u32 = 60;
#[cfg(not(test))]
const LIFECYCLE_POLL_INTERVAL: Duration = Duration::from_secs(2);
#[cfg(test)]
const LIFECYCLE_POLL_INTERVAL: Duration = Duration::from_millis(5);
const TERMINATE_POLL_ATTEMPTS: u32 = 30;
const TERMINATE_POLL_INTERVAL: Duration = Duration::from_secs(2);
const JOB_POLL_INTERVAL: Duration = Duration::from_secs(1);
const JOB_POLL_GRACE: Duration = Duration::from_secs(15);
const CONTENTION_WINDOW: Duration = Duration::from_secs(15);
const CLOCK_SKEW_ALLOWANCE: Duration = Duration::from_secs(5);
const RECHECK_ATTEMPTS: u32 = 4;
#[cfg(not(test))]
const RECHECK_BACKOFF: Duration = Duration::from_secs(2);
#[cfg(test)]
const RECHECK_BACKOFF: Duration = Duration::from_millis(5);
const CREATE: &str = "sandbox.create";
const GET: &str = "sandbox.get";
const GET_OR_CREATE: &str = "sandbox.getOrCreate";
const RUN_COMMAND: &str = "sandbox.runCommand";
const JOB_START: &str = "sandbox.jobStart";
const JOB_POLL: &str = "sandbox.jobPoll";
const READ_FILE: &str = "sandbox.readFile";
const JOB_CANCEL: &str = "sandbox.jobCancel";
const TERMINATE: &str = "sandbox.terminate";
const PAUSE_MARKER_DIRS: [&str; 2] = ["/dev/shm", "/tmp"];
const PAUSE_MARKER_NAME: &str = ".alien-pause-generation";
const PAUSE: &str = "sandbox.pause";
const RESUME: &str = "sandbox.resume";
const NO_GENERATION: u64 = 0;
const AGENT_PROBE_BUDGET: Duration = Duration::from_secs(60);
pub fn egress_control_config(
sandbox_label: &str,
egress: &SandboxEgress,
) -> Result<EgressControlConfig> {
let Some(internet_access) = egress.internet_access_switch() else {
return Err(AlienError::new(ErrorData::InvalidInput {
operation_context: "sandbox.template".to_string(),
details: format!(
"sandbox '{sandbox_label}' asked for domain-scoped egress, which Agent \
Platform cannot express; it offers only 'allow' (open) and 'deny' (closed)"
),
field_name: Some("egress".to_string()),
}));
};
Ok(EgressControlConfig {
internet_access: Some(internet_access),
extra: Default::default(),
})
}
#[derive(Debug)]
pub struct GcpAgentPlatformSandbox {
egress: Option<alien_core::SandboxEgress>,
client: Arc<dyn AgentPlatformApi>,
engine: String,
template: String,
max_lifetime_seconds: Option<u32>,
preview_signer: Option<Arc<dyn EdgeTokenSigner>>,
preview_ports: Vec<u16>,
grants: std::sync::Mutex<std::collections::HashMap<(String, u16), CachedGrant>>,
}
#[async_trait]
pub trait EdgeTokenSigner: Send + Sync + std::fmt::Debug {
async fn sign(&self) -> Result<SignedEdgeToken>;
}
pub struct SignedEdgeToken {
pub jwt: String,
pub expires_at: i64,
}
impl std::fmt::Debug for SignedEdgeToken {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SignedEdgeToken")
.field("jwt", &"<redacted>")
.field("expires_at", &self.expires_at)
.finish()
}
}
#[derive(Debug, Clone)]
struct CachedGrant {
capability: String,
expires_at: i64,
}
const GRANT_REFRESH_MARGIN_SECONDS: i64 = 30;
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct PreviewGrantReply {
capability: String,
expires_at: i64,
}
const EDGE_JWT_AUDIENCE: &str = "https://aiplatform.googleapis.com/";
const EDGE_JWT_LIFETIME_SECONDS: i64 = 300;
#[derive(Debug)]
pub struct IamEdgeTokenSigner {
iam: Arc<dyn alien_gcp_clients::gcp::iam::IamApi>,
service_account: String,
}
impl IamEdgeTokenSigner {
pub fn new(
iam: Arc<dyn alien_gcp_clients::gcp::iam::IamApi>,
service_account: impl Into<String>,
) -> Self {
Self {
iam,
service_account: service_account.into(),
}
}
fn claims(&self, now: i64) -> String {
json!({
"iat": now,
"exp": now + EDGE_JWT_LIFETIME_SECONDS,
"iss": self.service_account,
"sub": self.service_account,
"nonce": uuid::Uuid::new_v4().as_u128() % 1_000_000_000 + 1,
"aud": EDGE_JWT_AUDIENCE,
})
.to_string()
}
}
#[async_trait]
impl EdgeTokenSigner for IamEdgeTokenSigner {
async fn sign(&self) -> Result<SignedEdgeToken> {
let now = chrono::Utc::now().timestamp();
let request = alien_gcp_clients::gcp::iam::SignJwtRequest {
payload: self.claims(now),
};
let response = self
.iam
.sign_jwt(self.service_account.clone(), request)
.await
.context(ErrorData::Other {
message: "Failed to sign the sandbox edge credential".to_string(),
})?;
Ok(SignedEdgeToken {
jwt: response.signed_jwt,
expires_at: now + EDGE_JWT_LIFETIME_SECONDS,
})
}
}
impl GcpAgentPlatformSandbox {
async fn delete_until_gone(&self, sandbox_id: &str) -> Result<()> {
Self::checked_sandbox_id(TERMINATE, sandbox_id)?;
if let Err(error) = self.client.delete_sandbox(&self.engine, sandbox_id).await {
if !is_not_found(&error) {
return Err(error.context(ErrorData::SandboxUnreachable {
operation: TERMINATE.to_string(),
reason: format!("the delete of sandbox '{sandbox_id}' was not accepted"),
}));
}
return Ok(());
}
for _ in 0..TERMINATE_POLL_ATTEMPTS {
match self.client.get_sandbox(&self.engine, sandbox_id).await {
Err(error) if is_not_found(&error) => return Ok(()),
Err(error) => {
warn!(sandbox = %sandbox_id, %error, "could not confirm a sandbox is gone")
}
Ok(_) => {}
}
tokio::time::sleep(TERMINATE_POLL_INTERVAL).await;
}
Err(AlienError::new(ErrorData::SandboxUnreachable {
operation: TERMINATE.to_string(),
reason: format!(
"deletion of '{sandbox_id}' was accepted but the sandbox was still present after \
{}s; it may still be running",
TERMINATE_POLL_ATTEMPTS as u64 * TERMINATE_POLL_INTERVAL.as_secs()
),
}))
}
fn forget_grants(&self, sandbox_id: &str) {
self.grants
.lock()
.expect("grant cache lock")
.retain(|(sandbox, _), _| sandbox != sandbox_id);
}
pub fn with_preview_signer(mut self, signer: Arc<dyn EdgeTokenSigner>) -> Self {
self.preview_signer = Some(signer);
self
}
pub fn with_preview_from_binding(
mut self,
preview_ports: Vec<u16>,
preview_service_account: Option<alien_core::bindings::BindingValue<String>>,
binding_name: &str,
iam: Arc<dyn alien_gcp_clients::gcp::iam::IamApi>,
) -> Result<Self> {
self.preview_ports = preview_ports;
if let Some(account) = preview_service_account {
let account = account
.into_value(binding_name, "previewServiceAccount")
.context(ErrorData::config_invalid(
binding_name,
"Failed to resolve previewServiceAccount from the Agent Platform sandbox binding",
))?;
self.preview_signer = Some(Arc::new(IamEdgeTokenSigner::new(iam, account)));
}
Ok(self)
}
pub fn with_preview_ports(mut self, ports: Vec<u16>) -> Self {
self.preview_ports = ports;
self
}
pub fn with_egress(mut self, egress: Option<alien_core::SandboxEgress>) -> Self {
self.egress = egress;
self
}
fn lifetime_seconds(&self, timeout_ms: Option<u64>, operation: &str) -> Result<Option<u32>> {
match timeout_ms {
Some(timeout_ms) => {
super::requested_lifetime_seconds(timeout_ms, self.max_lifetime_seconds, operation)
.map(Some)
}
None => Ok(self.max_lifetime_seconds),
}
}
pub fn new(
client: Arc<dyn AgentPlatformApi>,
engine: String,
template: String,
max_lifetime_seconds: Option<u32>,
) -> Self {
let engine = engine.rsplit('/').next().unwrap_or(&engine).to_string();
Self {
egress: None,
client,
engine,
template,
max_lifetime_seconds,
preview_signer: None,
preview_ports: Vec::new(),
grants: Default::default(),
}
}
#[cfg(test)]
pub(crate) fn engine(&self) -> &str {
&self.engine
}
fn unsupported(&self, capability: &str, reason: &str) -> AlienError<ErrorData> {
AlienError::new(ErrorData::OperationNotSupported {
operation: capability.to_string(),
reason: reason.to_string(),
})
}
async fn request_pause(&self, sandbox_id: &str) -> Result<()> {
match self.client.pause_sandbox(&self.engine, sandbox_id).await {
Ok(started) => self.await_operation(PAUSE, started).await.map(|_| ()),
Err(error) => {
let raced = self
.read_sandbox(PAUSE, sandbox_id)
.await?
.is_some_and(|s| {
matches!(s.state.as_deref(), Some("STATE_PAUSING" | "STATE_PAUSED"))
});
if raced {
return Ok(());
}
Err(error.context(ErrorData::SandboxCommandFailed {
failure: "pauseFailed".to_string(),
reason: format!("{PAUSE}: sandbox '{sandbox_id}' could not be paused"),
}))
}
}
}
async fn paused_and_holding(&self, sandbox_id: &str) -> Result<bool> {
for attempt in 0..LIFECYCLE_POLL_ATTEMPTS {
if attempt > 0 {
tokio::time::sleep(LIFECYCLE_POLL_INTERVAL).await;
}
let state = self.state_for_pause(sandbox_id).await?;
match state.as_deref() {
Some("STATE_PAUSED") => {
tokio::time::sleep(LIFECYCLE_POLL_INTERVAL).await;
let again = self.state_for_pause(sandbox_id).await?;
return Ok(again.as_deref() == Some("STATE_PAUSED"));
}
Some("STATE_PAUSING") => {}
other => {
if sandbox_state(PAUSE, other)? == SandboxState::Terminated {
return Err(AlienError::new(ErrorData::SandboxCommandFailed {
failure: "sandboxTerminated".to_string(),
reason: format!(
"{PAUSE}: sandbox '{sandbox_id}' reached a terminal state"
),
}));
}
return Ok(false);
}
}
}
Err(AlienError::new(ErrorData::SandboxUnreachable {
operation: PAUSE.to_string(),
reason: format!(
"sandbox '{sandbox_id}' was not STATE_PAUSED after {}s",
LIFECYCLE_POLL_ATTEMPTS as u64 * LIFECYCLE_POLL_INTERVAL.as_secs()
),
}))
}
async fn state_for_pause(&self, sandbox_id: &str) -> Result<Option<String>> {
match self.read_sandbox(PAUSE, sandbox_id).await? {
Some(sandbox) => Ok(sandbox.state),
None => Err(AlienError::new(ErrorData::SandboxCommandFailed {
failure: "sandboxGone".to_string(),
reason: format!("{PAUSE}: sandbox '{sandbox_id}' does not exist"),
})),
}
}
async fn wait_for_state(&self, operation: &str, sandbox_id: &str, wanted: &str) -> Result<()> {
for attempt in 0..LIFECYCLE_POLL_ATTEMPTS {
if attempt > 0 {
tokio::time::sleep(LIFECYCLE_POLL_INTERVAL).await;
}
let Some(sandbox) = self.read_sandbox(operation, sandbox_id).await? else {
return Err(AlienError::new(ErrorData::SandboxCommandFailed {
failure: "sandboxGone".to_string(),
reason: format!("{operation}: sandbox '{sandbox_id}' does not exist"),
}));
};
let state = sandbox.state.as_deref();
if state == Some(wanted) {
return Ok(());
}
if sandbox_state(operation, state)? == SandboxState::Terminated {
return Err(AlienError::new(ErrorData::SandboxCommandFailed {
failure: "sandboxTerminated".to_string(),
reason: format!("{operation}: sandbox '{sandbox_id}' reached a terminal state"),
}));
}
}
Err(AlienError::new(ErrorData::SandboxUnreachable {
operation: operation.to_string(),
reason: format!(
"sandbox '{sandbox_id}' was not {wanted} after {}s",
LIFECYCLE_POLL_ATTEMPTS as u64 * LIFECYCLE_POLL_INTERVAL.as_secs()
),
}))
}
async fn get_by_id(&self, sandbox_id: &str) -> Result<Option<SandboxInstance>> {
let Some(sandbox) = self.read_sandbox(GET, sandbox_id).await? else {
return Ok(None);
};
let state = sandbox_state(GET, sandbox.state.as_deref())?;
let generation = if state == SandboxState::Running {
self.probe_agent(GET, sandbox_id).await?
} else {
NO_GENERATION
};
Ok(Some(SandboxInstance {
sandbox_id: sandbox_id.to_string(),
state,
generation,
}))
}
async fn reach(&self, id: &str) -> Result<Option<SandboxInstance>> {
match self.get_by_id(id).await {
Ok(Some(sandbox)) if sandbox.state == SandboxState::Running => Ok(Some(sandbox)),
Ok(Some(sandbox)) if sandbox.state == SandboxState::Starting => {
let generation = self.settle(CREATE, id).await?;
Ok(Some(SandboxInstance {
sandbox_id: id.to_string(),
state: SandboxState::Running,
generation,
}))
}
Ok(_) => Ok(None),
Err(error) if error.code == "SANDBOX_UNREACHABLE" => Ok(None),
Err(error) => Err(error.context(ErrorData::SandboxCommandFailed {
failure: "getOrCreateFailed".to_string(),
reason: format!("{GET_OR_CREATE}: reaching sandbox '{id}' failed"),
})),
}
}
async fn request_key_candidates(
&self,
requested_id: &str,
operation: &str,
) -> Result<Vec<KeyedSandbox>> {
let display_name = request_key_display_name(requested_id);
let tagged_name = tagged_display_name(&display_name);
let listed = self
.client
.list_sandboxes_by_display_names(
&self.engine,
&[display_name.clone(), tagged_name.clone()],
)
.await
.context(ErrorData::SandboxUnreachable {
operation: operation.to_string(),
reason: "the Agent Platform API did not answer a sandbox list".to_string(),
})?;
let mut candidates: Vec<_> = listed
.into_iter()
.filter(|sandbox| {
sandbox
.display_name
.as_deref()
.is_some_and(|name| name == display_name || name == tagged_name)
&& sandbox.state.as_deref().is_some_and(is_live_state)
})
.filter_map(|sandbox| {
let id = sandbox
.name
.as_deref()
.and_then(sandbox_segment)?
.to_string();
let created = sandbox
.create_time
.as_deref()
.and_then(|time| chrono::DateTime::parse_from_rfc3339(time).ok());
Some(KeyedSandbox { id, created })
})
.collect();
candidates.sort_by(|a, b| {
(a.created.is_none(), a.created, &a.id).cmp(&(b.created.is_none(), b.created, &b.id))
});
Ok(candidates)
}
async fn settled_candidates(
&self,
requested_id: &str,
operation: &str,
) -> Result<Vec<KeyedSandbox>> {
let candidates = self.request_key_candidates(requested_id, operation).await?;
let Some(age) = candidates.first().and_then(KeyedSandbox::age) else {
return Ok(candidates);
};
let settled = CONTENTION_WINDOW + CLOCK_SKEW_ALLOWANCE;
match settled.checked_sub(age) {
Some(rest) if !rest.is_zero() => {
tokio::time::sleep(rest.min(settled)).await;
let candidates = self.request_key_candidates(requested_id, operation).await?;
warn_on_duplicates(requested_id, &candidates);
Ok(candidates)
}
_ => {
warn_on_duplicates(requested_id, &candidates);
Ok(candidates)
}
}
}
async fn recheck_candidates(&self, key: &str) -> Result<Vec<KeyedSandbox>> {
let mut attempt = 1;
loop {
match self.request_key_candidates(key, GET_OR_CREATE).await {
Err(error) if attempt < RECHECK_ATTEMPTS => {
warn!(%error, attempt, "could not list the sandboxes for a key after a create");
attempt += 1;
tokio::time::sleep(RECHECK_BACKOFF).await;
}
Ok(candidates) => {
warn_on_duplicates(key, &candidates);
return Ok(candidates);
}
outcome => return outcome,
}
}
}
async fn reach_first(
&self,
candidates: &[KeyedSandbox],
own: Option<&str>,
) -> Result<Option<SandboxInstance>> {
for candidate in candidates {
if Some(candidate.id.as_str()) == own {
return Ok(None);
}
if let Some(found) = self.reach_candidate(&candidate.id).await? {
return Ok(Some(found));
}
}
Ok(None)
}
async fn reach_candidate(&self, id: &str) -> Result<Option<SandboxInstance>> {
let Some(sandbox) = self.read_sandbox(GET_OR_CREATE, id).await? else {
return Ok(None);
};
match sandbox_state(GET_OR_CREATE, sandbox.state.as_deref())? {
SandboxState::Running | SandboxState::Starting => {}
SandboxState::Paused => {
return Ok(Some(SandboxInstance {
sandbox_id: id.to_string(),
state: SandboxState::Paused,
generation: NO_GENERATION,
}));
}
SandboxState::Terminated => return Ok(None),
}
match self.settle(CREATE, id).await {
Ok(generation) => Ok(Some(SandboxInstance {
sandbox_id: id.to_string(),
state: SandboxState::Running,
generation,
})),
Err(error)
if matches!(
&error.error,
Some(ErrorData::SandboxCommandFailed { failure, .. })
if failure == "sandboxGone" || failure == "sandboxTerminated"
) =>
{
Ok(None)
}
Err(error) => Err(error.context(ErrorData::SandboxUnreachable {
operation: GET_OR_CREATE.to_string(),
reason: format!(
"sandbox '{id}' holds this key but is not answering; terminate it to free \
the key, or retry"
),
})),
}
}
fn checked_sandbox_id(operation: &str, sandbox_id: &str) -> Result<()> {
if is_addressable_id(sandbox_id) {
return Ok(());
}
Err(AlienError::new(ErrorData::InvalidInput {
operation_context: operation.to_string(),
details: format!(
"sandbox id '{sandbox_id}' must be a single segment of letters, digits, '-' and \
'_', at most {MAX_SANDBOX_ID} characters"
),
field_name: Some("sandboxId".to_string()),
}))
}
async fn read_sandbox(
&self,
operation: &str,
sandbox_id: &str,
) -> Result<Option<SandboxEnvironment>> {
match self.client.get_sandbox(&self.engine, sandbox_id).await {
Ok(sandbox) => Ok(Some(sandbox)),
Err(error) if is_not_found(&error) => Ok(None),
Err(error) => Err(error.context(ErrorData::SandboxUnreachable {
operation: operation.to_string(),
reason: "the Agent Platform API did not answer a sandbox read".to_string(),
})),
}
}
async fn await_operation(
&self,
operation: &str,
started: Operation,
) -> Result<serde_json::Value> {
let Some(name) = started.name.clone() else {
return Err(AlienError::new(ErrorData::UnexpectedResponseFormat {
provider: "gcp-agent-platform".to_string(),
binding_name: operation.to_string(),
field: "name".to_string(),
response_json: "the operation carried no resource name to poll".to_string(),
}));
};
let mut current = started;
for _ in 0..OPERATION_POLL_ATTEMPTS {
if current.done == Some(true) {
return finish_operation(operation, &name, current);
}
tokio::time::sleep(OPERATION_POLL_INTERVAL).await;
current =
self.client
.get_operation(&name)
.await
.context(ErrorData::SandboxUnreachable {
operation: operation.to_string(),
reason: format!("could not read operation '{name}'"),
})?;
}
if current.done == Some(true) {
return finish_operation(operation, &name, current);
}
Err(AlienError::new(ErrorData::SandboxUnreachable {
operation: operation.to_string(),
reason: format!("operation '{name}' did not complete within its polling budget"),
}))
}
async fn execute_op(
&self,
sandbox_id: &str,
operation: &str,
envelope: serde_json::Value,
) -> Result<Vec<u8>> {
let body = serde_json::to_vec(&envelope).map_err(|error| {
AlienError::new(ErrorData::SerializationFailed {
message: format!("could not encode the {operation} envelope: {error}"),
})
})?;
self.client
.execute(&self.engine, sandbox_id, &body)
.await
.map_err(|error| Self::execute_failed(operation, error))
}
fn execute_failed(
operation: &str,
error: AlienError<AgentPlatformErrorData>,
) -> AlienError<ErrorData> {
if let Some(answer) = agent_answer(&error) {
return error.context(ErrorData::SandboxCommandFailed {
failure: "agentRefused".to_string(),
reason: format!("{operation} was refused: {answer}"),
});
}
if is_not_found(&error) {
return error.context(ErrorData::SandboxCommandFailed {
failure: "sandboxGone".to_string(),
reason: format!("{operation}: the sandbox does not exist"),
});
}
if is_reply_unreadable(&error) {
return reply_too_large(operation, error);
}
if operation == RUN_COMMAND || operation == JOB_START {
return error.context(ErrorData::SandboxOutcomeUnknown {
operation: operation.to_string(),
reason: "the sandbox did not complete the call".to_string(),
});
}
error.context(ErrorData::SandboxCommandFailed {
failure: "executeFailed".to_string(),
reason: format!("{operation} could not be completed against the sandbox"),
})
}
async fn probe_agent(&self, operation: &str, sandbox_id: &str) -> Result<u64> {
let unreachable = |reason: String| {
AlienError::new(ErrorData::SandboxUnreachable {
operation: operation.to_string(),
reason,
})
};
let body = tokio::time::timeout(
AGENT_PROBE_BUDGET,
self.client.execute(
&self.engine,
sandbox_id,
&serde_json::to_vec(&json!({ "v": AGENT_PROTOCOL_VERSION, "op": "health" }))
.unwrap_or_default(),
),
)
.await
.map_err(|_| {
unreachable(format!(
"the sandbox's agent did not answer a health probe within {}s",
AGENT_PROBE_BUDGET.as_secs()
))
})?
.map_err(|error| {
if is_permission_denied(&error) && (operation == PAUSE || operation == RESUME) {
return error.context(ErrorData::SandboxCommandFailed {
failure: "executePermissionMissing".to_string(),
reason: format!(
"{operation}: on Google Cloud, pause and resume talk to the sandbox's agent \
to check that memory survived, so the caller needs sandbox/execute (or \
sandbox/remote-execute) as well as sandbox/management; the agent call was \
refused with 403"
),
});
}
error.context(ErrorData::SandboxUnreachable {
operation: operation.to_string(),
reason: "the sandbox's agent did not answer a health probe".to_string(),
})
})?;
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Health {
protocol_version: u32,
boot_id: String,
}
let health: Health = serde_json::from_slice(&body).map_err(|_| {
unreachable(format!(
"the sandbox's agent answered a health probe with a body this provider cannot \
read: {}",
truncated(&body)
))
})?;
if health.protocol_version != AGENT_PROTOCOL_VERSION {
return Err(unreachable(format!(
"the sandbox's agent speaks protocol {} where this provider speaks {}",
health.protocol_version, AGENT_PROTOCOL_VERSION
)));
}
if health.boot_id.is_empty() {
return Err(unreachable(
"the sandbox's agent reported no container boot id, so its identity cannot be \
established"
.to_string(),
));
}
Ok(generation_from_boot_id(&health.boot_id))
}
async fn discard(
&self,
sandbox_id: &str,
reason: AlienError<ErrorData>,
) -> AlienError<ErrorData> {
let Err(error) = self.client.delete_sandbox(&self.engine, sandbox_id).await else {
return reason;
};
warn!(
sandbox = %sandbox_id,
%error,
"could not delete a sandbox that was never handed to its caller"
);
reason.context(ErrorData::SandboxCommandFailed {
failure: "sandboxLeftBehind".to_string(),
reason: format!(
"sandbox '{sandbox_id}' was not handed to its caller and could not be deleted, so \
it is still running"
),
})
}
async fn settle(&self, operation: &str, sandbox_id: &str) -> Result<u64> {
for _ in 0..SANDBOX_READY_ATTEMPTS {
let Some(sandbox) = self.read_sandbox(operation, sandbox_id).await? else {
return Err(AlienError::new(ErrorData::SandboxCommandFailed {
failure: "sandboxGone".to_string(),
reason: format!("sandbox '{sandbox_id}' disappeared while it was coming up"),
}));
};
match sandbox_state(operation, sandbox.state.as_deref())? {
SandboxState::Running => {
return self.wait_until_servable(operation, sandbox_id).await
}
SandboxState::Terminated => {
return Err(AlienError::new(ErrorData::SandboxCommandFailed {
failure: "sandboxTerminated".to_string(),
reason: format!(
"sandbox '{sandbox_id}' reached a terminal state while starting"
),
}));
}
SandboxState::Starting | SandboxState::Paused => {}
}
tokio::time::sleep(SANDBOX_READY_INTERVAL).await;
}
Err(AlienError::new(ErrorData::SandboxUnreachable {
operation: operation.to_string(),
reason: format!(
"sandbox '{sandbox_id}' was not running after {}s",
SANDBOX_READY_ATTEMPTS as u64 * SANDBOX_READY_INTERVAL.as_secs()
),
}))
}
async fn wait_until_servable(&self, operation: &str, sandbox_id: &str) -> Result<u64> {
let deadline = tokio::time::Instant::now() + AGENT_READY_TIMEOUT;
let mut last_error = None;
loop {
match tokio::time::timeout_at(deadline, self.probe_agent(operation, sandbox_id)).await {
Ok(Ok(generation)) => return Ok(generation),
Ok(Err(error)) if error.code == "SANDBOX_COMMAND_FAILED" => return Err(error),
Ok(Err(error)) => {
last_error = Some(error);
if tokio::time::Instant::now() + AGENT_READY_POLL >= deadline {
break;
}
tokio::time::sleep(AGENT_READY_POLL).await;
}
Err(_) => break,
}
}
let timed_out = ErrorData::SandboxUnreachable {
operation: operation.to_string(),
reason: format!(
"sandbox '{sandbox_id}' was running but its agent did not become servable within {}s",
AGENT_READY_TIMEOUT.as_secs()
),
};
Err(match last_error {
Some(error) => error.context(timed_out),
None => AlienError::new(timed_out),
})
}
async fn marker_script(
&self,
operation: &str,
sandbox_id: &str,
script: String,
) -> Result<String> {
let request = RunCommandRequest {
command: "/bin/sh".to_string(),
args: vec!["-c".to_string(), script],
cwd: None,
env: BTreeMap::new(),
timeout: Duration::from_secs(20),
};
use futures::StreamExt;
let mut frames = self.run_synchronous(sandbox_id, &request).await?;
let mut stdout = Vec::new();
let mut exit = None;
while let Some(frame) = frames.next().await {
match frame? {
CommandOutput::Stdout { data, .. } => stdout.extend(data),
CommandOutput::Exit { code, .. } => exit = Some(code),
_ => {}
}
}
if exit != Some(0) {
return Err(AlienError::new(ErrorData::SandboxCommandFailed {
failure: "pauseMarkerFailed".to_string(),
reason: format!(
"{operation}: the pause marker script in sandbox '{sandbox_id}' did not \
succeed (exit {exit:?}); it needs /bin/sh in the image"
),
}));
}
Ok(String::from_utf8_lossy(&stdout).trim().to_string())
}
async fn write_marker_with_retries(
&self,
operation: &str,
sandbox_id: &str,
generation: u64,
) -> Result<()> {
let mut attempt = 1;
loop {
match self
.write_pause_marker(operation, sandbox_id, generation)
.await
{
Ok(()) => return Ok(()),
Err(_) if attempt < 3 => {
attempt += 1;
tokio::time::sleep(LIFECYCLE_POLL_INTERVAL).await;
}
Err(error) => return Err(error),
}
}
}
async fn write_pause_marker(
&self,
operation: &str,
sandbox_id: &str,
generation: u64,
) -> Result<()> {
let candidates = PAUSE_MARKER_DIRS
.iter()
.map(|dir| format!("{dir}/{PAUSE_MARKER_NAME}"))
.collect::<Vec<_>>();
let script = format!(
"for f in {all}; do d=$(dirname \"$f\"); t=\"$f.tmp.$$\"; \
if [ -d \"$d\" ] && [ -w \"$d\" ] && printf %s '{generation}' > \"$t\" && mv -f \"$t\" \"$f\"; then \
for o in {all}; do [ \"$o\" = \"$f\" ] || rm -f \"$o\" 2>/dev/null; done; exit 0; fi; \
rm -f \"$t\" 2>/dev/null; done; exit 1",
all = candidates.join(" ")
);
self.marker_script(operation, sandbox_id, script)
.await
.map(|_| ())
}
async fn read_pause_marker(&self, sandbox_id: &str) -> Result<Option<u64>> {
let candidates = PAUSE_MARKER_DIRS
.iter()
.map(|dir| format!("{dir}/{PAUSE_MARKER_NAME}"))
.collect::<Vec<_>>();
let script = format!(
"for f in {all}; do if [ -e \"$f\" ]; then v=$(cat \"$f\" 2>/dev/null) || {{ echo unreadable; exit 0; }}; \
echo \"gen:$v\"; exit 0; fi; done; echo none",
all = candidates.join(" ")
);
let mut attempt = 1;
let text = loop {
match self.marker_script(RESUME, sandbox_id, script.clone()).await {
Ok(text) => break text,
Err(_) if attempt < 3 => {
attempt += 1;
tokio::time::sleep(LIFECYCLE_POLL_INTERVAL).await;
}
Err(error) => return Err(error),
}
};
if text == "none" {
return Ok(None);
}
text.strip_prefix("gen:")
.and_then(|value| value.trim().parse::<u64>().ok())
.map(Some)
.ok_or_else(|| {
AlienError::new(ErrorData::SandboxCommandFailed {
failure: "pauseMarkerUnreadable".to_string(),
reason: format!(
"{RESUME}: the pause marker in sandbox '{sandbox_id}' exists but cannot \
be read ({}); the sandbox was not reported as kept or lost",
truncated(text.as_bytes())
),
})
})
}
async fn run_synchronous(
&self,
sandbox_id: &str,
request: &RunCommandRequest,
) -> Result<BoxStream<'static, Result<CommandOutput>>> {
let envelope = exec_envelope("exec", sandbox_id, request);
let body = self.execute_op(sandbox_id, RUN_COMMAND, envelope).await?;
let frames = parse_exec_frames(&body)?;
Ok(Box::pin(stream::iter(frames)))
}
async fn run_detached(
&self,
sandbox_id: &str,
request: RunCommandRequest,
) -> Result<BoxStream<'static, Result<CommandOutput>>> {
let timeout = request.timeout;
let started = self.start_job(sandbox_id, request).await?;
let state = JobPollState {
client: self.client.clone(),
engine: self.engine.clone(),
sandbox_id: sandbox_id.to_string(),
job_id: started.job_id,
since_seq: None,
pending: VecDeque::new(),
finished: false,
stopped: false,
deadline_at: tokio::time::Instant::now() + timeout + JOB_POLL_GRACE,
draining: false,
};
Ok(Box::pin(stream::unfold(state, job_poll_step)))
}
fn checked_command(operation: &str, request: &RunCommandRequest) -> Result<()> {
if request.command.is_empty() {
return Err(AlienError::new(ErrorData::InvalidInput {
operation_context: operation.to_string(),
details: "a command must name a program to run".to_string(),
field_name: Some("command".to_string()),
}));
}
if timeout_millis(request.timeout) == 0 {
return Err(AlienError::new(ErrorData::SandboxCommandFailed {
failure: "invalidRequest".to_string(),
reason: "a command must carry a timeout of at least one millisecond".to_string(),
}));
}
Ok(())
}
}
impl Binding for GcpAgentPlatformSandbox {}
fn refuse_runtime_policy(
requested: Option<&alien_core::EgressPolicy>,
declaration: Option<&SandboxEgress>,
) -> Result<()> {
let Some(requested) = requested else {
return Ok(());
};
super::egress::validate(requested, declaration)?;
if *requested == alien_core::EgressPolicy::Internet {
return Ok(());
}
Err(AlienError::new(
ErrorData::SandboxEgressAllowlistUnsupported {
reason: alien_core::GCP_NO_EGRESS_ALLOWLIST.to_string(),
},
))
}
#[async_trait]
impl Sandbox for GcpAgentPlatformSandbox {
fn egress_declaration(&self) -> Option<&alien_core::SandboxEgress> {
self.egress.as_ref()
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
async fn update_egress(
&self,
_sandbox_id: &str,
egress: alien_core::EgressPolicy,
) -> Result<()> {
refuse_runtime_policy(Some(&egress), self.egress_declaration())
}
fn capabilities(&self) -> SandboxCapabilities {
SandboxCapabilities::gcp_agent_platform()
}
async fn create(&self, request: CreateSandboxRequest) -> Result<SandboxInstance> {
refuse_runtime_policy(request.egress.as_ref(), self.egress_declaration())?;
if !request.env.is_empty() {
return Err(AlienError::new(ErrorData::OperationNotSupported {
operation: CREATE.to_string(),
reason: "Agent Platform sandboxes take no sandbox-level env; set env per command \
instead"
.to_string(),
}));
}
if request.tenant_key.is_some() {
return Err(AlienError::new(ErrorData::OperationNotSupported {
operation: CREATE.to_string(),
reason: "Agent Platform sandboxes take no tenantKey; create one sandbox per \
tenant instead"
.to_string(),
}));
}
let ttl = self
.lifetime_seconds(request.timeout_ms, CREATE)?
.map(|seconds| format!("{seconds}s"));
let started = self
.client
.create_sandbox(
&self.engine,
SandboxCreateRequest {
display_name: Some(tagged_display_name(
&request
.sandbox_id
.as_deref()
.map(request_key_display_name)
.unwrap_or_else(|| UNKEYED_DISPLAY_NAME.to_string()),
)),
sandbox_environment_template: Some(self.template.clone()),
sandbox_environment_snapshot: None,
ttl,
},
)
.await
.context(ErrorData::SandboxUnreachable {
operation: CREATE.to_string(),
reason: "the Agent Platform API refused a sandbox create".to_string(),
})?;
let created: SandboxEnvironment = serde_json::from_value(
self.await_operation(CREATE, started).await?,
)
.map_err(|error| {
AlienError::new(ErrorData::UnexpectedResponseFormat {
provider: "gcp-agent-platform".to_string(),
binding_name: CREATE.to_string(),
field: "response".to_string(),
response_json: format!("the create operation resolved to a non-sandbox: {error}"),
})
})?;
let Some(sandbox_id) = created.name.as_deref().and_then(sandbox_segment) else {
return Err(AlienError::new(ErrorData::UnexpectedResponseFormat {
provider: "gcp-agent-platform".to_string(),
binding_name: CREATE.to_string(),
field: "name".to_string(),
response_json: format!("{:?}", created.name),
}));
};
let sandbox_id = sandbox_id.to_string();
match self.settle(CREATE, &sandbox_id).await {
Ok(generation) => {
if let Err(error) = self
.write_marker_with_retries(CREATE, &sandbox_id, generation)
.await
{
warn!(%sandbox_id, %error, "the first pause marker could not be written; pause will write it");
}
Ok(SandboxInstance {
sandbox_id,
state: SandboxState::Running,
generation,
})
}
Err(error) => Err(self.discard(&sandbox_id, error).await),
}
}
async fn get(&self, sandbox_id: &str) -> Result<Option<SandboxInstance>> {
Self::checked_sandbox_id(GET, sandbox_id)?;
if is_google_id(sandbox_id) {
return self.get_by_id(sandbox_id).await;
}
for candidate in self.settled_candidates(sandbox_id, GET).await? {
let Some(sandbox) = self.read_sandbox(GET, &candidate.id).await? else {
continue;
};
let state = sandbox_state(GET, sandbox.state.as_deref())?;
if state == SandboxState::Terminated {
continue;
}
let generation = if state == SandboxState::Running {
match self.probe_agent(GET, &candidate.id).await {
Ok(generation) => generation,
Err(error) if error.code == "SANDBOX_UNREACHABLE" => {
warn!(sandbox_id = %candidate.id, %error, "the sandbox holding a key does not answer");
NO_GENERATION
}
Err(error) => return Err(error),
}
} else {
NO_GENERATION
};
return Ok(Some(SandboxInstance {
sandbox_id: candidate.id,
state,
generation,
}));
}
Ok(None)
}
async fn get_or_create(&self, request: CreateSandboxRequest) -> Result<ResolvedSandbox> {
refuse_runtime_policy(request.egress.as_ref(), self.egress_declaration())?;
let Some(key) = request.sandbox_id.clone() else {
return self.create(request).await.map(ResolvedSandbox::created);
};
Self::checked_sandbox_id(GET_OR_CREATE, &key)?;
if is_google_id(&key) {
if let Some(found) = self.reach(&key).await? {
return Ok(ResolvedSandbox::found(found));
}
return self.create(request).await.map(ResolvedSandbox::created);
}
let candidates = self.settled_candidates(&key, GET_OR_CREATE).await?;
if let Some(found) = self.reach_first(&candidates, None).await? {
return Ok(ResolvedSandbox::found(found));
}
let wait = match self.lifetime_seconds(request.timeout_ms, GET_OR_CREATE)? {
Some(seconds) => CONTENTION_WINDOW.min(Duration::from_secs(u64::from(seconds)) / 2),
None => CONTENTION_WINDOW,
};
let created = self.create(request).await?;
let decide_at = tokio::time::Instant::now() + wait;
let own = created.sandbox_id.clone();
tokio::time::sleep_until(decide_at).await;
let candidates = match self.recheck_candidates(&key).await {
Ok(candidates) => candidates,
Err(error) => {
let mut error = error.context(ErrorData::SandboxUnreachable {
operation: GET_OR_CREATE.to_string(),
reason: format!(
"sandbox '{own}' was created for this key but could not be checked \
against a concurrent create; retry, which finds it by the key"
),
});
let mut context = match error.context.take() {
Some(serde_json::Value::Object(map)) => map,
_ => serde_json::Map::new(),
};
context.insert("sandboxId".to_string(), own.clone().into());
error.context = Some(serde_json::Value::Object(context));
return Err(error);
}
};
let outcome = self.reach_first(&candidates, Some(&own)).await;
if matches!(outcome, Ok(None)) {
return match self.read_sandbox(GET_OR_CREATE, &own).await? {
Some(sandbox)
if sandbox_state(GET_OR_CREATE, sandbox.state.as_deref())?
!= SandboxState::Terminated =>
{
Ok(ResolvedSandbox::created(created))
}
_ => Err(AlienError::new(ErrorData::SandboxCommandFailed {
failure: "sandboxTerminated".to_string(),
reason: format!(
"sandbox '{own}' reached its lifetime while the call checked for a \
concurrent create; retry, or ask for a longer timeout"
),
})),
};
}
if let Err(error) = self.terminate(&own).await {
warn!(sandbox_id = %own, %error, "could not delete the losing duplicate create");
}
outcome.map(|winner| match winner {
Some(winner) => ResolvedSandbox::found(winner),
None => ResolvedSandbox::created(created),
})
}
async fn list(&self) -> Result<Vec<SandboxInstance>> {
let sandboxes = self.client.list_sandboxes(&self.engine).await.context(
ErrorData::SandboxUnreachable {
operation: "sandbox.list".to_string(),
reason: "the Agent Platform API did not answer a sandbox list".to_string(),
},
)?;
Ok(sandboxes
.into_iter()
.filter_map(|sandbox| {
let sandbox_id = sandbox.name.as_deref().and_then(sandbox_segment)?;
let state = sandbox_state("sandbox.list", sandbox.state.as_deref()).ok()?;
Some(SandboxInstance {
sandbox_id: sandbox_id.to_string(),
state,
generation: NO_GENERATION,
})
})
.collect())
}
async fn run_command(
&self,
sandbox_id: &str,
request: RunCommandRequest,
) -> Result<BoxStream<'static, Result<CommandOutput>>> {
Self::checked_sandbox_id(RUN_COMMAND, sandbox_id)?;
Self::checked_command(RUN_COMMAND, &request)?;
if request.timeout <= MAX_SYNCHRONOUS_TIMEOUT {
self.run_synchronous(sandbox_id, &request).await
} else {
self.run_detached(sandbox_id, request).await
}
}
async fn start_job(&self, sandbox_id: &str, request: RunCommandRequest) -> Result<JobStart> {
Self::checked_sandbox_id(JOB_START, sandbox_id)?;
Self::checked_command(JOB_START, &request)?;
let envelope = exec_envelope("jobStart", sandbox_id, &request);
let body = self.execute_op(sandbox_id, JOB_START, envelope).await?;
let started: JobStartReply = serde_json::from_slice(&body).map_err(|_| {
AlienError::new(ErrorData::UnexpectedResponseFormat {
provider: "gcp-agent-platform".to_string(),
binding_name: JOB_START.to_string(),
field: "jobId".to_string(),
response_json: truncated(&body),
})
.context(ErrorData::SandboxOutcomeUnknown {
operation: JOB_START.to_string(),
reason: "the job started and its id could not be read, so it cannot be polled"
.to_string(),
})
})?;
Ok(JobStart {
job_id: started.job_id,
})
}
async fn poll_job(
&self,
sandbox_id: &str,
job_id: &str,
since_seq: Option<u64>,
) -> Result<JobPoll> {
Self::checked_sandbox_id(JOB_POLL, sandbox_id)?;
let reply = poll_once(
self.client.as_ref(),
&self.engine,
sandbox_id,
job_id,
since_seq,
)
.await?;
let settled = !reply.running;
Ok(JobPoll {
running: reply.running,
frames: reply
.frames
.into_iter()
.map(WireFrame::into_output)
.collect::<Result<Vec<_>>>()?,
exit: reply.exit_code.filter(|_| settled).map(|code| JobExit {
code,
truncated: reply.truncated.unwrap_or(false),
}),
error: reply.error.filter(|_| settled).map(|error| JobError {
code: error.code,
message: error.message,
}),
})
}
async fn cancel_job(&self, sandbox_id: &str, job_id: &str) -> Result<()> {
Self::checked_sandbox_id(JOB_CANCEL, sandbox_id)?;
let body = self
.client
.execute(&self.engine, sandbox_id, &cancel_body(job_id))
.await
.map_err(|error| unanswered_job(JOB_CANCEL, error))?;
if !cancel_confirmed(&body) {
return Err(AlienError::new(ErrorData::SandboxCommandFailed {
failure: "agentRefused".to_string(),
reason: format!("{JOB_CANCEL}: {}", truncated(&body)),
}));
}
Ok(())
}
async fn read_file(&self, sandbox_id: &str, path: &str) -> Result<Vec<u8>> {
Self::checked_sandbox_id(READ_FILE, sandbox_id)?;
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct ReadFile {
contents_base64: String,
total_bytes: Option<u64>,
version: Option<String>,
}
let mut contents = Vec::new();
let mut identity: Option<(Option<String>, u64)> = None;
let mut restarted = false;
loop {
let body = self
.execute_op(
sandbox_id,
READ_FILE,
json!({
"v": AGENT_PROTOCOL_VERSION,
"op": "readFile",
"path": path,
"offset": contents.len(),
"length": GCP_READ_PAGE_BYTES,
}),
)
.await?;
let read: ReadFile = serde_json::from_slice(&body).map_err(|_| {
AlienError::new(ErrorData::SandboxCommandFailed {
failure: "agentRefused".to_string(),
reason: format!("{READ_FILE} was refused: {}", truncated(&body)),
})
})?;
let page = BASE64
.decode(read.contents_base64.as_bytes())
.map_err(|error| {
AlienError::new(ErrorData::UnexpectedResponseFormat {
provider: "gcp-agent-platform".to_string(),
binding_name: READ_FILE.to_string(),
field: "contentsBase64".to_string(),
response_json: format!(
"the agent returned data that is not base64: {error}"
),
})
})?;
let Some(total) = read.total_bytes else {
return Ok(page);
};
let seen = (read.version, total);
match &identity {
Some(first) if *first != seen => {
if restarted {
return Err(AlienError::new(ErrorData::SandboxFileChanged {
path: path.to_string(),
}));
}
restarted = true;
contents.clear();
identity = None;
continue;
}
Some(_) => {}
None => identity = Some(seen),
}
let page_empty = page.is_empty();
contents.extend_from_slice(&page);
if contents.len() as u64 >= total || page_empty {
return Ok(contents);
}
}
}
async fn write_files(&self, sandbox_id: &str, files: BTreeMap<String, Vec<u8>>) -> Result<()> {
Self::checked_sandbox_id("sandbox.writeFiles", sandbox_id)?;
for (path, contents) in files {
let body = self
.execute_op(
sandbox_id,
"sandbox.writeFiles",
json!({
"v": AGENT_PROTOCOL_VERSION,
"op": "writeFile",
"path": path,
"contentsBase64": BASE64.encode(&contents),
}),
)
.await?;
confirm_empty_ok("sandbox.writeFiles", &body)?;
}
Ok(())
}
async fn preview(&self, sandbox_id: &str, port: u16) -> Result<PreviewCapability> {
const PREVIEW: &str = "sandbox.preview";
Self::checked_sandbox_id(PREVIEW, sandbox_id)?;
if self.preview_ports.is_empty() && self.preview_signer.is_none() {
return Err(self.unsupported(
PREVIEW,
"this binding carries no preview setup; a remote binding cannot preview on GCP \
because its lease cannot sign the edge credential. Use the binding the \
deployment itself provides",
));
}
if !self.preview_ports.contains(&port) {
return Err(self.unsupported(
PREVIEW,
&format!(
"port {port} is not one of this sandbox's declared preview ports {:?}",
self.preview_ports
),
));
}
let Some(signer) = &self.preview_signer else {
return Err(self.unsupported(
PREVIEW,
"this deployment has no preview signing identity; re-run setup so it is created",
));
};
let unreachable = |reason: &str| {
AlienError::new(ErrorData::SandboxUnreachable {
operation: PREVIEW.to_string(),
reason: reason.to_string(),
})
};
let sandbox = self
.read_sandbox(PREVIEW, sandbox_id)
.await?
.ok_or_else(|| unreachable("the sandbox does not exist"))?;
let connection = sandbox.connection_info.as_ref();
let host = connection
.and_then(|info| info.load_balancer_hostname.clone())
.ok_or_else(|| unreachable("the sandbox has no edge host yet"))?;
let routing_token = connection
.and_then(|info| info.routing_token.clone())
.ok_or_else(|| unreachable("the sandbox has no routing token yet"))?;
let deadline = sandbox
.expire_time
.as_deref()
.and_then(|time| chrono::DateTime::parse_from_rfc3339(time).ok())
.map(|time| time.timestamp());
let now = chrono::Utc::now().timestamp();
let key = (sandbox_id.to_string(), port);
let cached = {
let mut grants = self.grants.lock().expect("grant cache lock");
grants.retain(|_, grant| grant.expires_at > now);
grants
.get(&key)
.filter(|grant| grant.expires_at - now > GRANT_REFRESH_MARGIN_SECONDS)
.cloned()
};
let grant = match cached {
Some(grant) => grant,
None => {
let body = self
.execute_op(
sandbox_id,
PREVIEW,
json!({
"v": AGENT_PROTOCOL_VERSION,
"op": "previewGrant",
"sandbox": sandbox_id,
"port": port,
"deadline": deadline,
"declaredPorts": self.preview_ports,
}),
)
.await
.context(ErrorData::SandboxCommandFailed {
failure: "previewNeedsExecute".to_string(),
reason: format!(
"{PREVIEW}: preview is gated by the right to run commands in this \
sandbox, and that call was not accepted. {}",
alien_core::GCP_PREVIEW_IS_COMMAND_ACCESS
),
})?;
let reply: PreviewGrantReply = serde_json::from_slice(&body).map_err(|_| {
AlienError::new(ErrorData::SandboxCommandFailed {
failure: "agentRefused".to_string(),
reason: "the agent's preview grant could not be read".to_string(),
})
})?;
let grant = CachedGrant {
capability: reply.capability,
expires_at: reply.expires_at,
};
self.grants
.lock()
.expect("grant cache lock")
.insert(key, grant.clone());
tracing::info!(sandbox = sandbox_id, port, "preview granted");
grant
}
};
let edge = signer.sign().await?;
let edge_jwt = edge.jwt;
let agent_port = alien_core::sandbox_image::AGENT_PORT.to_string();
let mut headers = BTreeMap::new();
headers.insert("Authorization".to_string(), format!("Bearer {edge_jwt}"));
headers.insert("X-Sandbox-Routing-Token".to_string(), routing_token.clone());
headers.insert("X-Sandbox-Port".to_string(), agent_port.clone());
headers.insert(
alien_core::sandbox_image::PREVIEW_CAPABILITY_HEADER.to_string(),
grant.capability,
);
headers.insert(
alien_core::sandbox_image::PREVIEW_PORT_HEADER.to_string(),
port.to_string(),
);
let built = chrono::Utc::now().timestamp();
let expires_in_seconds = (grant.expires_at - built)
.min(edge.expires_at - built)
.clamp(0, alien_core::sandbox_image::PREVIEW_CAPABILITY_MAX_SECONDS)
as u64;
Ok(PreviewCapability {
endpoint: format!("https://{host}/v1/preview/{port}"),
headers,
allowed_ports: vec![port],
expires_in_seconds,
caller_authorization_header: alien_core::sandbox_image::CALLER_AUTHORIZATION_HEADER
.to_string(),
subprotocols: vec!["v1.stream".to_string(), edge_jwt, routing_token, agent_port],
})
}
async fn pause(&self, sandbox_id: &str) -> Result<()> {
Self::checked_sandbox_id(PAUSE, sandbox_id)?;
const PAUSE_ATTEMPTS: usize = 3;
let mut last_probe_error = None;
for attempt in 1..=PAUSE_ATTEMPTS {
let Some(sandbox) = self.read_sandbox(PAUSE, sandbox_id).await? else {
return Err(AlienError::new(ErrorData::SandboxCommandFailed {
failure: "sandboxGone".to_string(),
reason: format!("{PAUSE}: sandbox '{sandbox_id}' does not exist"),
}));
};
if !matches!(
sandbox.state.as_deref(),
Some("STATE_PAUSED" | "STATE_PAUSING")
) {
if sandbox_state(PAUSE, sandbox.state.as_deref())? != SandboxState::Running {
return Err(AlienError::new(ErrorData::SandboxCommandFailed {
failure: "sandboxNotRunning".to_string(),
reason: format!(
"{PAUSE}: sandbox '{sandbox_id}' is not running, so there is nothing \
to pause"
),
}));
}
match self.probe_agent(PAUSE, sandbox_id).await {
Ok(generation) => {
let step = async {
self.write_pause_marker(PAUSE, sandbox_id, generation)
.await?;
self.request_pause(sandbox_id).await
}
.await;
last_probe_error = step.err();
}
Err(error) => last_probe_error = Some(error),
}
}
if self.paused_and_holding(sandbox_id).await? {
return Ok(());
}
if attempt < PAUSE_ATTEMPTS {
tokio::time::sleep(LIFECYCLE_POLL_INTERVAL).await;
}
}
if let Some(error) = last_probe_error {
return Err(error);
}
Err(AlienError::new(ErrorData::SandboxCommandFailed {
failure: "pauseDidNotHold".to_string(),
reason: format!(
"{PAUSE}: pause did not hold: something keeps waking sandbox '{sandbox_id}'"
),
}))
}
async fn resume(&self, sandbox_id: &str) -> Result<()> {
Self::checked_sandbox_id(RESUME, sandbox_id)?;
let mut attempt = 0;
let mut running_on_entry = None;
let mut carries_marker: Option<bool> = None;
loop {
let Some(sandbox) = self.read_sandbox(RESUME, sandbox_id).await? else {
return Err(AlienError::new(ErrorData::SandboxCommandFailed {
failure: "sandboxGone".to_string(),
reason: format!("{RESUME}: sandbox '{sandbox_id}' does not exist"),
}));
};
running_on_entry.get_or_insert(sandbox.state.as_deref() == Some("STATE_RUNNING"));
carries_marker.get_or_insert(
sandbox
.display_name
.as_deref()
.is_some_and(is_tagged_display_name),
);
match sandbox.state.as_deref() {
Some("STATE_RUNNING" | "STATE_RESUMING") => break,
Some("STATE_PAUSING") => {}
other => {
if sandbox_state(RESUME, other)? == SandboxState::Terminated {
return Err(AlienError::new(ErrorData::SandboxCommandFailed {
failure: "sandboxTerminated".to_string(),
reason: format!(
"{RESUME}: sandbox '{sandbox_id}' has ended and cannot be resumed"
),
}));
}
match self.client.resume_sandbox(&self.engine, sandbox_id).await {
Ok(started) => {
self.await_operation(RESUME, started).await?;
break;
}
Err(error) if is_wake_in_progress(&error) => break,
Err(error) if http_status(&error) == Some(400) => {}
Err(error) => {
return Err(error.context(ErrorData::SandboxCommandFailed {
failure: "resumeFailed".to_string(),
reason: format!(
"{RESUME}: sandbox '{sandbox_id}' could not be resumed"
),
}))
}
}
}
}
attempt += 1;
if attempt >= LIFECYCLE_POLL_ATTEMPTS {
return Err(AlienError::new(ErrorData::SandboxUnreachable {
operation: RESUME.to_string(),
reason: format!(
"sandbox '{sandbox_id}' was still pausing after {}s, so it could not be \
resumed",
LIFECYCLE_POLL_ATTEMPTS as u64 * LIFECYCLE_POLL_INTERVAL.as_secs()
),
}));
}
tokio::time::sleep(LIFECYCLE_POLL_INTERVAL).await;
}
self.wait_for_state(RESUME, sandbox_id, "STATE_RUNNING")
.await?;
let generation = self.settle(RESUME, sandbox_id).await?;
let memory_lost = |reason: &str| {
AlienError::new(ErrorData::SandboxMemoryLost {
sandbox_id: sandbox_id.to_string(),
reason: reason.to_string(),
})
};
match self.read_pause_marker(sandbox_id).await? {
Some(paused_as) if paused_as == generation => Ok(()),
Some(_) => Err(memory_lost(
"the container that answers is not the one that was paused; it runs a container \
that holds only what its image provides",
)),
None if carries_marker == Some(true) => Err(memory_lost(
"the container that answers has no pause marker, so it is not the one this \
sandbox started with; it runs a container that holds only what its image \
provides",
)),
None if running_on_entry == Some(true) => Ok(()),
None => Err(memory_lost(
"it restarted while it was paused, or was not paused by this binding, so its \
memory cannot be confirmed kept; it runs a container that holds only what its \
image provides",
)),
}
}
async fn snapshot(&self, sandbox_id: &str) -> Result<String> {
Self::checked_sandbox_id("sandbox.snapshot", sandbox_id)?;
let display_name = format!("snap-{}", uuid::Uuid::new_v4().simple());
let started = self
.client
.snapshot(&self.engine, sandbox_id, &display_name)
.await
.context(ErrorData::SandboxCommandFailed {
failure: "snapshotFailed".to_string(),
reason: format!("sandbox.snapshot: sandbox '{sandbox_id}' could not be captured"),
})?;
let snapshot: SandboxSnapshot =
serde_json::from_value(self.await_operation("sandbox.snapshot", started).await?)
.map_err(|error| {
AlienError::new(ErrorData::UnexpectedResponseFormat {
provider: "gcp-agent-platform".to_string(),
binding_name: "sandbox.snapshot".to_string(),
field: "response".to_string(),
response_json: format!(
"the snapshot operation resolved to a non-snapshot: {error}"
),
})
})?;
snapshot.name.ok_or_else(|| {
AlienError::new(ErrorData::UnexpectedResponseFormat {
provider: "gcp-agent-platform".to_string(),
binding_name: "sandbox.snapshot".to_string(),
field: "name".to_string(),
response_json: "the snapshot completed without a resource name".to_string(),
})
})
}
async fn terminate(&self, sandbox_id: &str) -> Result<()> {
let outcome = self.delete_until_gone(sandbox_id).await;
if outcome.is_ok() {
self.forget_grants(sandbox_id);
}
outcome
}
}
async fn job_poll_step(mut state: JobPollState) -> Option<(Result<CommandOutput>, JobPollState)> {
loop {
if let Some(item) = state.pending.pop_front() {
return Some((item, state));
}
if state.finished {
return None;
}
if !state.draining && tokio::time::Instant::now() >= state.deadline_at {
let cancelled = state
.client
.execute(
&state.engine,
&state.sandbox_id,
&cancel_body(&state.job_id),
)
.await;
let confirmed = cancelled.as_ref().is_ok_and(|body| cancel_confirmed(body));
state.pending.push_back(Err(match cancelled {
Ok(_) if confirmed => AlienError::new(ErrorData::SandboxCommandFailed {
failure: "timeoutExceeded".to_string(),
reason: "the command's deadline elapsed before its job reported an outcome"
.to_string(),
}),
Ok(_) => AlienError::new(ErrorData::SandboxOutcomeUnknown {
operation: RUN_COMMAND.to_string(),
reason: "the command's deadline elapsed and its job did not confirm the cancel"
.to_string(),
}),
Err(error) => error.context(ErrorData::SandboxOutcomeUnknown {
operation: RUN_COMMAND.to_string(),
reason: "the command's deadline elapsed and its job could not be cancelled"
.to_string(),
}),
}));
state.finished = true;
state.stopped = confirmed;
continue;
}
let poll = match poll_once(
state.client.as_ref(),
&state.engine,
&state.sandbox_id,
&state.job_id,
state.since_seq,
)
.await
{
Ok(poll) => poll,
Err(error) => {
state.pending.push_back(Err(if is_reply_unreadable(&error) {
error
} else {
error.context(ErrorData::SandboxOutcomeUnknown {
operation: RUN_COMMAND.to_string(),
reason: "the job is no longer watched".to_string(),
})
}));
state.finished = true;
continue;
}
};
if poll.finished {
state.draining = true;
}
if !poll.frames.is_empty() {
state.deadline_at = state
.deadline_at
.max(tokio::time::Instant::now() + JOB_POLL_GRACE);
}
for frame in poll.frames {
state.since_seq = state.since_seq.max(frame.seq());
let output = frame.into_output();
let failed = output.is_err();
state.pending.push_back(output);
if failed {
state.finished = true;
break;
}
}
if !poll.running {
let terminal = match poll.error {
Some(error) => Err(AlienError::new(ErrorData::SandboxCommandFailed {
failure: error.code,
reason: error.message,
})),
None => match poll.exit_code {
Some(code) => Ok(CommandOutput::Exit {
code,
truncated: poll.truncated.unwrap_or(false),
}),
None => Err(AlienError::new(ErrorData::SandboxOutcomeUnknown {
operation: RUN_COMMAND.to_string(),
reason: "the job finished without reporting an exit code".to_string(),
})),
},
};
state.pending.push_back(terminal);
state.finished = true;
state.stopped = true;
continue;
}
if state.pending.is_empty() {
tokio::time::sleep(JOB_POLL_INTERVAL).await;
}
}
}
async fn poll_once(
client: &dyn AgentPlatformApi,
engine: &str,
sandbox_id: &str,
job_id: &str,
since_seq: Option<u64>,
) -> Result<JobPollReply> {
let body = client
.execute(engine, sandbox_id, &poll_body(job_id, since_seq))
.await
.map_err(|error| unanswered_job(JOB_POLL, error))?;
serde_json::from_slice(&body).map_err(|_| {
AlienError::new(ErrorData::UnexpectedResponseFormat {
provider: "gcp-agent-platform".to_string(),
binding_name: JOB_POLL.to_string(),
field: "jobPoll".to_string(),
response_json: truncated(&body),
})
})
}
fn unanswered_job(
operation: &str,
error: AlienError<AgentPlatformErrorData>,
) -> AlienError<ErrorData> {
if is_not_found(&error) {
return error.context(ErrorData::SandboxCommandFailed {
failure: "sandboxGone".to_string(),
reason: format!("{operation}: the sandbox does not exist"),
});
}
if is_reply_unreadable(&error) {
return reply_too_large(operation, error);
}
error.context(ErrorData::SandboxUnreachable {
operation: operation.to_string(),
reason: "the sandbox did not complete the call".to_string(),
})
}
fn cancel_confirmed(body: &[u8]) -> bool {
serde_json::from_slice::<serde_json::Value>(body)
.is_ok_and(|value| value.as_object().is_some_and(serde_json::Map::is_empty))
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct JobStartReply {
job_id: String,
}
struct JobPollState {
client: Arc<dyn AgentPlatformApi>,
engine: String,
sandbox_id: String,
job_id: String,
since_seq: Option<u64>,
pending: VecDeque<Result<CommandOutput>>,
finished: bool,
stopped: bool,
deadline_at: tokio::time::Instant,
draining: bool,
}
impl Drop for JobPollState {
fn drop(&mut self) {
if self.stopped {
return;
}
let Ok(runtime) = tokio::runtime::Handle::try_current() else {
warn!(
sandbox = %self.sandbox_id,
job = %self.job_id,
"a job's stream was dropped outside a runtime, so the job runs to its timeout"
);
return;
};
let client = self.client.clone();
let engine = self.engine.clone();
let sandbox_id = self.sandbox_id.clone();
let job_id = self.job_id.clone();
runtime.spawn(async move {
match tokio::time::timeout(
AGENT_PROBE_BUDGET,
client.execute(&engine, &sandbox_id, &cancel_body(&job_id)),
)
.await
{
Ok(Ok(body)) if cancel_confirmed(&body) => {}
Ok(Ok(body)) => warn!(
sandbox = %sandbox_id,
job = %job_id,
reply = %truncated(&body),
"a dropped job's cancel was refused, so the job runs to its timeout"
),
Ok(Err(error)) => warn!(
sandbox = %sandbox_id,
job = %job_id,
%error,
"a dropped job's cancel did not land, so the job may run to its timeout"
),
Err(_) => warn!(
sandbox = %sandbox_id,
job = %job_id,
budget_secs = AGENT_PROBE_BUDGET.as_secs(),
"a dropped job's cancel went unanswered, so the job may run to its timeout"
),
}
});
}
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct JobPollReply {
running: bool,
#[serde(default)]
finished: bool,
#[serde(default)]
frames: Vec<WireFrame>,
#[serde(default)]
exit_code: Option<i32>,
#[serde(default)]
truncated: Option<bool>,
#[serde(default)]
error: Option<JobErrorReply>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct JobErrorReply {
code: String,
message: String,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase", tag = "t")]
enum WireFrame {
Stdout {
seq: u64,
data: String,
},
Stderr {
seq: u64,
data: String,
},
Exit {
code: i32,
#[serde(default)]
truncated: bool,
},
Error {
code: String,
message: String,
},
}
impl WireFrame {
fn is_terminal(&self) -> bool {
matches!(self, Self::Exit { .. } | Self::Error { .. })
}
fn seq(&self) -> Option<u64> {
match self {
Self::Stdout { seq, .. } | Self::Stderr { seq, .. } => Some(*seq),
_ => None,
}
}
fn into_output(self) -> Result<CommandOutput> {
match self {
Self::Stdout { seq, data } => Ok(CommandOutput::Stdout {
seq,
data: decode_frame_data(&data)?,
}),
Self::Stderr { seq, data } => Ok(CommandOutput::Stderr {
seq,
data: decode_frame_data(&data)?,
}),
Self::Exit { code, truncated } => Ok(CommandOutput::Exit { code, truncated }),
Self::Error { code, message } => {
Err(AlienError::new(ErrorData::SandboxCommandFailed {
failure: code,
reason: message,
}))
}
}
}
}
fn decode_frame_data(data: &str) -> Result<Vec<u8>> {
BASE64.decode(data).map_err(|error| {
AlienError::new(ErrorData::UnexpectedResponseFormat {
provider: "gcp-agent-platform".to_string(),
binding_name: RUN_COMMAND.to_string(),
field: "data".to_string(),
response_json: format!("an output frame's data is not base64: {error}"),
})
.context(ErrorData::SandboxOutcomeUnknown {
operation: RUN_COMMAND.to_string(),
reason: "an output frame did not decode".to_string(),
})
})
}
fn parse_exec_frames(body: &[u8]) -> Result<Vec<Result<CommandOutput>>> {
let mut frames = Vec::new();
let mut saw_any = false;
let mut saw_terminal = false;
for line in body.split(|byte| *byte == b'\n') {
if line.is_empty() {
continue;
}
match serde_json::from_slice::<WireFrame>(line) {
Ok(frame) => {
saw_any = true;
saw_terminal |= frame.is_terminal();
let output = frame.into_output();
let failed = output.is_err();
frames.push(output);
if failed {
saw_terminal = true;
break;
}
}
Err(error) => {
if !saw_any {
return Err(AlienError::new(ErrorData::SandboxCommandFailed {
failure: "agentRefused".to_string(),
reason: format!("run_command was refused: {}", truncated(body)),
}));
}
frames.push(Err(AlienError::new(ErrorData::UnexpectedResponseFormat {
provider: "gcp-agent-platform".to_string(),
binding_name: RUN_COMMAND.to_string(),
field: "frame".to_string(),
response_json: format!("an output frame did not parse: {error}"),
})
.context(ErrorData::SandboxOutcomeUnknown {
operation: RUN_COMMAND.to_string(),
reason: "an output frame did not parse".to_string(),
})));
saw_terminal = true;
break;
}
}
}
if !saw_any {
return Err(AlienError::new(ErrorData::SandboxCommandFailed {
failure: "agentRefused".to_string(),
reason: "run_command returned an empty body".to_string(),
}));
}
if !saw_terminal {
frames.push(Err(AlienError::new(ErrorData::SandboxOutcomeUnknown {
operation: RUN_COMMAND.to_string(),
reason: "the command's output ended without a terminal frame".to_string(),
})));
}
Ok(frames)
}
fn exec_envelope(op: &str, _sandbox_id: &str, request: &RunCommandRequest) -> serde_json::Value {
json!({
"v": AGENT_PROTOCOL_VERSION,
"op": op,
"command": request.argv(),
"timeoutMs": timeout_millis(request.timeout),
"cwd": request.cwd,
"env": request.env,
"replyBudget": (op == "exec").then_some(GCP_STREAM_REPLY_BUDGET),
})
}
fn poll_body(job_id: &str, since_seq: Option<u64>) -> Vec<u8> {
serde_json::to_vec(&json!({
"v": AGENT_PROTOCOL_VERSION,
"op": "jobPoll",
"jobId": job_id,
"sinceSeq": since_seq,
"replyBudget": GCP_STREAM_REPLY_BUDGET,
}))
.unwrap_or_default()
}
fn cancel_body(job_id: &str) -> Vec<u8> {
serde_json::to_vec(&json!({
"v": AGENT_PROTOCOL_VERSION,
"op": "jobCancel",
"jobId": job_id,
}))
.unwrap_or_default()
}
fn timeout_millis(timeout: Duration) -> u64 {
u64::try_from(timeout.as_millis()).unwrap_or(u64::MAX)
}
fn confirm_empty_ok(operation: &str, body: &[u8]) -> Result<()> {
if body.iter().all(|byte| byte.is_ascii_whitespace()) {
return Ok(());
}
Err(AlienError::new(ErrorData::SandboxCommandFailed {
failure: "agentRefused".to_string(),
reason: format!("{operation} was refused: {}", truncated(body)),
}))
}
struct KeyedSandbox {
id: String,
created: Option<chrono::DateTime<chrono::FixedOffset>>,
}
impl KeyedSandbox {
fn age(&self) -> Option<Duration> {
let created = self.created?;
Some(
(wall_now() - created.with_timezone(&chrono::Utc))
.to_std()
.unwrap_or(Duration::ZERO),
)
}
}
#[cfg(not(test))]
fn wall_now() -> chrono::DateTime<chrono::Utc> {
chrono::Utc::now()
}
#[cfg(test)]
pub(crate) fn wall_now() -> chrono::DateTime<chrono::Utc> {
let advanced = tokio::time::Instant::now()
.into_std()
.saturating_duration_since(std::time::Instant::now());
chrono::Utc::now() + chrono::Duration::from_std(advanced).unwrap_or_default()
}
fn warn_on_duplicates(key: &str, candidates: &[KeyedSandbox]) {
let settled = duplicates_past_the_window(candidates);
if settled.len() > 1 {
warn!(
request_key = %request_key_display_name(key),
sandbox_ids = ?settled,
"more than one live sandbox holds this key; callers get the oldest, the others are \
not deleted: terminate them, or set a maximum lifetime"
);
}
}
fn duplicates_past_the_window(candidates: &[KeyedSandbox]) -> Vec<&str> {
candidates
.iter()
.filter(|sandbox| sandbox.age().is_some_and(|age| age > CONTENTION_WINDOW))
.map(|sandbox| sandbox.id.as_str())
.collect()
}
fn sandbox_segment(name: &str) -> Option<&str> {
let segment = name.rsplit('/').next()?;
is_addressable_id(segment).then_some(segment)
}
fn request_key(requested_id: &str) -> String {
use sha2::{Digest, Sha256};
format!("{:x}", Sha256::digest(requested_id.as_bytes()))[..32].to_string()
}
fn request_key_display_name(requested_id: &str) -> String {
format!(
"{}-{}",
alien_core::SANDBOX_REQUEST_KEY_LABEL,
request_key(requested_id)
)
}
const UNKEYED_DISPLAY_NAME: &str = "alienSandbox";
const PAUSE_CONTRACT_SUFFIX: &str = "-pm1";
fn tagged_display_name(display_name: &str) -> String {
format!("{display_name}{PAUSE_CONTRACT_SUFFIX}")
}
fn is_tagged_display_name(display_name: &str) -> bool {
display_name.ends_with(PAUSE_CONTRACT_SUFFIX)
}
fn is_google_id(id: &str) -> bool {
!id.is_empty() && id.chars().all(|c| c.is_ascii_digit())
}
fn is_live_state(state: &str) -> bool {
!matches!(
state,
"STATE_STOPPED"
| "STATE_FAILED"
| "STATE_DELETING"
| "STATE_DELETED"
| "STATE_TERMINATED"
| "STATE_DEPROVISIONING"
| "STATE_STOPPING"
)
}
fn is_addressable_id(id: &str) -> bool {
!id.is_empty()
&& id.len() <= MAX_SANDBOX_ID
&& id
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
}
fn generation_from_boot_id(boot_id: &str) -> u64 {
const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325;
const FNV_PRIME: u64 = 0x0000_0100_0000_01b3;
let mut hash = FNV_OFFSET_BASIS;
for byte in boot_id.as_bytes() {
hash ^= u64::from(*byte);
hash = hash.wrapping_mul(FNV_PRIME);
}
hash | 1
}
fn sandbox_state(operation: &str, state: Option<&str>) -> Result<SandboxState> {
match state {
Some("STATE_RUNNING") => Ok(SandboxState::Running),
Some("STATE_CREATING" | "STATE_PENDING" | "STATE_PROVISIONING" | "STATE_RESUMING") => {
Ok(SandboxState::Starting)
}
Some("STATE_PAUSED" | "STATE_PAUSING" | "STATE_SUSPENDED") => Ok(SandboxState::Paused),
Some(
"STATE_STOPPED"
| "STATE_STOPPING"
| "STATE_FAILED"
| "STATE_TERMINATED"
| "STATE_DEPROVISIONING"
| "STATE_DELETING"
| "STATE_DELETED",
) => Ok(SandboxState::Terminated),
other => Err(AlienError::new(ErrorData::UnexpectedResponseFormat {
provider: "gcp-agent-platform".to_string(),
binding_name: operation.to_string(),
field: "state".to_string(),
response_json: other
.map_or_else(|| "absent".to_string(), |state| format!("\"{state}\"")),
})),
}
}
fn finish_operation(operation: &str, name: &str, op: Operation) -> Result<serde_json::Value> {
match op.result {
Some(OperationResult::Response { response }) => Ok(response),
Some(OperationResult::Error { error }) => {
Err(AlienError::new(ErrorData::SandboxCommandFailed {
failure: "operationFailed".to_string(),
reason: format!(
"{operation}: operation '{name}' failed (grpc {}): {}",
error.code, error.message
),
}))
}
None => Err(AlienError::new(ErrorData::UnexpectedResponseFormat {
provider: "gcp-agent-platform".to_string(),
binding_name: operation.to_string(),
field: "response".to_string(),
response_json: format!("operation '{name}' reported done without a result"),
})),
}
}
fn agent_answer(error: &AlienError<AgentPlatformErrorData>) -> Option<String> {
const RELAYED: &str = "Error Details: ";
let message = super::refusal::captured_refusal(error)?;
let details = message.split_once(RELAYED)?.1.trim();
let code = details.split(':').next()?;
let is_agent_code =
!code.is_empty() && code.chars().all(|ch| ch.is_ascii_uppercase() || ch == '_');
is_agent_code.then(|| truncated(details.as_bytes()))
}
fn is_not_found(error: &AlienError<AgentPlatformErrorData>) -> bool {
chain_has_code(error, "REMOTE_RESOURCE_NOT_FOUND")
}
fn is_reply_unreadable<
T: alien_error::AlienErrorData + Clone + std::fmt::Debug + serde::Serialize,
>(
error: &AlienError<T>,
) -> bool {
const TOO_LARGE: &str = "Response size too large";
if error.code == "REMOTE_RESOURCE_CONFLICT" && error.message.contains(TOO_LARGE) {
return true;
}
let mut node = error.source.as_deref();
while let Some(current) = node {
if current.code == "REMOTE_RESOURCE_CONFLICT" && current.message.contains(TOO_LARGE) {
return true;
}
node = current.source.as_deref();
}
false
}
fn http_status(error: &AlienError<AgentPlatformErrorData>) -> Option<u16> {
let mut context = error.context.as_ref();
let mut layer = error.source.as_deref();
loop {
if let Some(status) = context
.and_then(|context| context.get("http_status"))
.and_then(serde_json::Value::as_u64)
{
return u16::try_from(status).ok();
}
let current = layer?;
context = current.context.as_ref();
layer = current.source.as_deref();
}
}
fn is_permission_denied(error: &AlienError<AgentPlatformErrorData>) -> bool {
if http_status(error) != Some(403) {
return false;
}
let text = super::refusal::response_text(error)
.unwrap_or_default()
.to_lowercase();
text.contains("permission")
&& !text.contains("service_disabled")
&& !text.contains("has not been used")
}
fn is_wake_in_progress(error: &AlienError<AgentPlatformErrorData>) -> bool {
http_status(error) == Some(503)
&& super::refusal::response_text(error)
.is_some_and(|text| text.contains("resume has been initiated"))
}
fn chain_has_code<T: alien_error::AlienErrorData + Clone + std::fmt::Debug + serde::Serialize>(
error: &AlienError<T>,
code: &str,
) -> bool {
if error.code == code {
return true;
}
let mut node = error.source.as_deref();
while let Some(current) = node {
if current.code == code {
return true;
}
node = current.source.as_deref();
}
false
}
fn reply_too_large(
operation: &str,
error: AlienError<AgentPlatformErrorData>,
) -> AlienError<ErrorData> {
error.context(ErrorData::SandboxCommandFailed {
failure: "outputTooLarge".to_string(),
reason: if operation == READ_FILE {
format!(
"{operation}: the file is larger than one call can carry on this cloud and the \
sandbox image predates paged reads, so rebuild it with the current agent"
)
} else {
format!(
"{operation}: the sandbox's reply was larger than one call can carry on this \
cloud; the sandbox image predates the output budget, so rebuild it with the \
current agent"
)
},
})
}
fn truncated(body: &[u8]) -> String {
const LIMIT: usize = 200;
let text = String::from_utf8_lossy(body);
let text = text.trim();
if text.len() <= LIMIT {
return text.to_string();
}
let end = (0..=LIMIT)
.rev()
.find(|at| text.is_char_boundary(*at))
.unwrap_or(0);
format!("{}…", &text[..end])
}
#[cfg(test)]
#[path = "gcp_agent_platform_tests.rs"]
mod tests;