Skip to main content

adk_memory/
vertex.rs

1//! Vertex AI Agent Engine Memory Bank backend.
2//!
3//! Rust analog of Python ADK's `VertexAiMemoryBankService`: long-term
4//! memories are generated from conversation content with
5//! `memories:generate` (a long-running operation) and retrieved with
6//! `memories:retrieve` (similarity search), scoped to
7//! `{"app_name", "user_id"}` so one engine can serve many users.
8//!
9//! Endpoints are the v1beta1 Memory Bank surface under
10//! `projects/{project}/locations/{location}/reasoningEngines/{engine}`.
11//!
12//! # Ids and expiry
13//!
14//! A memory's [`MemoryEntry::id`] is its resource name, which
15//! [`delete_memory`](MemoryService::delete_memory) takes. Memory Bank generates memories
16//! from the content it is given, so a memory's expiry is its `expireTime`: when an entry
17//! carries an expiry, or [`with_default_ttl`](VertexAiMemoryBankService::with_default_ttl)
18//! sets one, each memory the generation creates or updates is patched to expire then.
19//! Without either, the engine's own TTL configuration (`memoryBankConfig.ttlConfig`,
20//! set on the reasoning engine outside this client) decides. Memory Bank deletes a memory
21//! at its `expireTime`; search skips one that has passed before then, and
22//! [`purge_expired`](MemoryService::purge_expired) has nothing to remove.
23//!
24//! Transport, credential caching, and operation polling come from
25//! [`adk_gcp`]: [`GcpHttpClient`] carries the ADC/auth-header/bounded-read
26//! plumbing and [`LroPoller`] the identity-pinned operation polling, both
27//! branded with this backend's error identity via [`GcpErrorContext`].
28//!
29//! # Example
30//!
31//! ```rust,no_run
32//! use adk_memory::{VertexAiMemoryBankService, VertexAiMemoryConfig};
33//!
34//! # fn main() -> adk_core::Result<()> {
35//! // Inside a deployed engine container the platform sets the env vars.
36//! let config = VertexAiMemoryConfig::from_env()?;
37//! let memory = VertexAiMemoryBankService::new_with_adc(config)?;
38//! # Ok(())
39//! # }
40//! ```
41//!
42//! `ToolContext::search_memory` works unchanged through the existing
43//! adapter: wrap the service in
44//! [`MemoryServiceAdapter`](crate::MemoryServiceAdapter) to obtain an
45//! `adk_core::Memory`.
46
47use crate::{MemoryEntry, MemoryService, SearchRequest, SearchResponse, UserMemory};
48use adk_core::{AdkError, Content, ErrorCategory, ErrorComponent, Event, Result};
49use adk_gcp::{
50    GcpErrorCodes, GcpErrorContext, GcpHttpClient, LroPoller, VertexResourceName,
51    is_canonical_reasoning_engine_id, truncate_for_error,
52};
53use async_trait::async_trait;
54use chrono::{DateTime, Utc};
55use google_cloud_auth::credentials::Credentials;
56use reqwest::Method;
57use serde::Deserialize;
58use serde_json::{Value, json};
59use std::time::Duration;
60use tracing::debug;
61
62const MEMORY_API_VERSION: &str = "v1beta1";
63const CLOUD_PLATFORM_SCOPE: &str = "https://www.googleapis.com/auth/cloud-platform";
64const HTTP_CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
65const HTTP_REQUEST_TIMEOUT: Duration = Duration::from_secs(120);
66const AUTH_HEADERS_TIMEOUT: Duration = Duration::from_secs(30);
67// Same backoff policy as adk-session's wait_for_operation: 100 ms initial,
68// 2 s cap, bounded deadline.
69const OPERATION_POLL_TIMEOUT: Duration = Duration::from_secs(120);
70const OPERATION_POLL_INITIAL_DELAY: Duration = Duration::from_millis(100);
71const OPERATION_POLL_MAX_DELAY: Duration = Duration::from_secs(2);
72const MAX_RESPONSE_BYTES: usize = 64 * 1024 * 1024;
73/// Page size used when enumerating a scope's memories for deletion.
74const DELETE_PAGE_SIZE: usize = 100;
75/// Upper bound on delete pagination rounds, so a server that keeps returning
76/// page tokens cannot spin this client forever.
77const DELETE_MAX_PAGES: usize = 1_000;
78
79/// Environment variable holding the GCP project (set inside deployed engines).
80const ENV_GOOGLE_CLOUD_PROJECT: &str = "GOOGLE_CLOUD_PROJECT";
81/// Environment variable holding the GCP location.
82const ENV_GOOGLE_CLOUD_LOCATION: &str = "GOOGLE_CLOUD_LOCATION";
83/// Environment variable holding the bare numeric engine ID.
84const ENV_GOOGLE_CLOUD_AGENT_ENGINE_ID: &str = "GOOGLE_CLOUD_AGENT_ENGINE_ID";
85
86/// The machine-readable codes this backend stamps on shared-plumbing errors.
87const ERROR_CODES: GcpErrorCodes = GcpErrorCodes {
88    invalid_input: "memory.vertex.invalid_input",
89    unauthorized: "memory.vertex.unauthorized",
90    forbidden: "memory.vertex.forbidden",
91    not_found: "memory.vertex.not_found",
92    rate_limited: "memory.vertex.rate_limited",
93    timeout: "memory.vertex.timeout",
94    unavailable: "memory.vertex.unavailable",
95    credentials_unavailable: "memory.vertex.credentials_unavailable",
96    invalid_response: "memory.vertex.invalid_response",
97    invalid_request: "memory.vertex.invalid_request",
98    upstream_error: "memory.vertex.upstream_error",
99    operation_failed: "memory.vertex.operation_failed",
100};
101
102/// This backend's error identity: component Memory, provider `vertex_ai`.
103fn error_context() -> GcpErrorContext {
104    GcpErrorContext::new(ErrorComponent::Memory, ERROR_CODES, "vertex memory")
105}
106
107/// Configuration for [`VertexAiMemoryBankService`].
108///
109/// Mirrors `VertexAiSessionConfig`: project, location, optional reasoning
110/// engine, optional endpoint override, and a [`from_env`](Self::from_env)
111/// constructor reading the platform's container environment.
112///
113/// # Example
114///
115/// ```rust
116/// use adk_memory::VertexAiMemoryConfig;
117///
118/// let config = VertexAiMemoryConfig::new("my-project", "us-central1")
119///     .with_reasoning_engine("1234567890");
120/// ```
121#[derive(Debug, Clone)]
122pub struct VertexAiMemoryConfig {
123    project_id: String,
124    location: String,
125    reasoning_engine: Option<String>,
126    endpoint: Option<String>,
127}
128
129impl VertexAiMemoryConfig {
130    /// Creates a config for the given project and location.
131    pub fn new(project_id: impl Into<String>, location: impl Into<String>) -> Self {
132        Self {
133            project_id: project_id.into(),
134            location: location.into(),
135            reasoning_engine: None,
136            endpoint: None,
137        }
138    }
139
140    /// Builds a config from the environment variables the platform sets
141    /// inside deployed containers: `GOOGLE_CLOUD_PROJECT`,
142    /// `GOOGLE_CLOUD_LOCATION`, and `GOOGLE_CLOUD_AGENT_ENGINE_ID` (the bare
143    /// numeric engine ID). Values are trimmed; blank counts as missing.
144    ///
145    /// # Errors
146    ///
147    /// Returns an invalid-input error naming every missing or blank variable.
148    pub fn from_env() -> Result<Self> {
149        let read = |key: &str| {
150            std::env::var(key)
151                .ok()
152                .map(|value| value.trim().to_string())
153                .filter(|value| !value.is_empty())
154        };
155        let project_id = read(ENV_GOOGLE_CLOUD_PROJECT);
156        let location = read(ENV_GOOGLE_CLOUD_LOCATION);
157        let agent_engine_id = read(ENV_GOOGLE_CLOUD_AGENT_ENGINE_ID);
158
159        match (project_id, location, agent_engine_id) {
160            (Some(project_id), Some(location), Some(agent_engine_id)) => {
161                Ok(Self::new(project_id, location).with_reasoning_engine(agent_engine_id))
162            }
163            (project_id, location, agent_engine_id) => {
164                let missing = [
165                    (ENV_GOOGLE_CLOUD_PROJECT, project_id.is_none()),
166                    (ENV_GOOGLE_CLOUD_LOCATION, location.is_none()),
167                    (ENV_GOOGLE_CLOUD_AGENT_ENGINE_ID, agent_engine_id.is_none()),
168                ]
169                .into_iter()
170                .filter_map(|(key, is_missing)| is_missing.then_some(key))
171                .collect::<Vec<_>>()
172                .join(", ");
173                Err(AdkError::new(
174                    ErrorComponent::Memory,
175                    ErrorCategory::InvalidInput,
176                    "memory.vertex.missing_env",
177                    format!(
178                        "missing or blank environment variable(s): {missing}. The Agent Engine platform sets these inside deployed containers; set them explicitly elsewhere, or construct the config with VertexAiMemoryConfig::new",
179                    ),
180                )
181                .with_provider("vertex_ai"))
182            }
183        }
184    }
185
186    /// Sets the reasoning engine numeric ID or full resource name.
187    #[must_use]
188    pub fn with_reasoning_engine(mut self, reasoning_engine: impl Into<String>) -> Self {
189        self.reasoning_engine = Some(reasoning_engine.into());
190        self
191    }
192
193    /// Sets a custom API origin.
194    ///
195    /// The origin receives Google authorization headers plus memory content.
196    /// Use only a trusted HTTPS origin, or loopback HTTP for local tests.
197    /// Userinfo, paths, queries, and fragments are rejected before transport.
198    #[must_use]
199    pub fn with_endpoint(mut self, endpoint: impl Into<String>) -> Self {
200        self.endpoint = Some(endpoint.into());
201        self
202    }
203
204    fn endpoint(&self) -> String {
205        self.endpoint
206            .clone()
207            .unwrap_or_else(|| format!("https://{}-aiplatform.googleapis.com", self.location))
208    }
209}
210
211/// Vertex AI Agent Engine Memory Bank service.
212///
213/// Implements [`MemoryService`] over the platform's `memories:generate` and
214/// `memories:retrieve` endpoints. Memories are scoped to
215/// `{"app_name": ..., "user_id": ...}`, matching adk-python's
216/// `VertexAiMemoryBankService` so both runtimes share one Memory Bank.
217pub struct VertexAiMemoryBankService {
218    client: GcpHttpClient,
219    poller: LroPoller,
220    project_id: String,
221    location: String,
222    reasoning_engine: Option<String>,
223    default_ttl: Option<Duration>,
224}
225
226impl VertexAiMemoryBankService {
227    /// Creates a new service using Application Default Credentials (ADC).
228    ///
229    /// # Errors
230    ///
231    /// Returns an error when ADC cannot be constructed, the endpoint is not
232    /// a valid secure origin, or the HTTP client cannot be built.
233    pub fn new_with_adc(config: VertexAiMemoryConfig) -> Result<Self> {
234        Self::build(config, None)
235    }
236
237    /// Creates a new service with explicit credentials.
238    ///
239    /// # Errors
240    ///
241    /// Returns an error when the endpoint is not a valid secure origin or
242    /// the redirect-disabled HTTP client cannot be built.
243    pub fn with_credentials(
244        config: VertexAiMemoryConfig,
245        credentials: Credentials,
246    ) -> Result<Self> {
247        Self::build(config, Some(credentials))
248    }
249
250    fn build(config: VertexAiMemoryConfig, credentials: Option<Credentials>) -> Result<Self> {
251        let mut builder = GcpHttpClient::builder(error_context(), config.endpoint())
252            .api_version(MEMORY_API_VERSION)
253            .scopes([CLOUD_PLATFORM_SCOPE])
254            .connect_timeout(HTTP_CONNECT_TIMEOUT)
255            .request_timeout(HTTP_REQUEST_TIMEOUT)
256            .auth_timeout(AUTH_HEADERS_TIMEOUT)
257            .max_response_bytes(MAX_RESPONSE_BYTES);
258        if let Some(credentials) = credentials {
259            builder = builder.credentials(credentials);
260        }
261        let poller = LroPoller::new()
262            .with_poll_timeout(OPERATION_POLL_TIMEOUT)
263            .with_initial_delay(OPERATION_POLL_INITIAL_DELAY)
264            .with_max_delay(OPERATION_POLL_MAX_DELAY);
265        Ok(Self {
266            client: builder.build()?,
267            poller,
268            project_id: config.project_id,
269            location: config.location,
270            reasoning_engine: config.reasoning_engine,
271            default_ttl: None,
272        })
273    }
274
275    /// Expires each memory generated from entries without an expiry `ttl` after it is
276    /// generated, by setting its `expireTime`.
277    ///
278    /// # Example
279    ///
280    /// ```rust,no_run
281    /// use adk_memory::{VertexAiMemoryBankService, VertexAiMemoryConfig};
282    /// use std::time::Duration;
283    ///
284    /// # fn main() -> adk_core::Result<()> {
285    /// let memory = VertexAiMemoryBankService::new_with_adc(VertexAiMemoryConfig::from_env()?)?
286    ///     .with_default_ttl(Duration::from_secs(30 * 24 * 3600));
287    /// # Ok(())
288    /// # }
289    /// ```
290    pub fn with_default_ttl(mut self, ttl: Duration) -> Self {
291        self.default_ttl = Some(ttl);
292        self
293    }
294
295    /// Generates memories from an explicit slice of events.
296    ///
297    /// Mirrors adk-python's `VertexAiMemoryBankService.add_events_to_memory`
298    /// so callers can persist only recent turns instead of a whole session.
299    /// Events without content are skipped; an all-skipped or empty slice is
300    /// a no-op.
301    ///
302    /// This is an inherent method, not part of [`MemoryService`] — the trait
303    /// has no subset-of-events operation.
304    ///
305    /// # Errors
306    ///
307    /// Returns an error when the request fails or the returned long-running
308    /// operation reports failure or does not finish within the poll deadline.
309    pub async fn add_events_to_memory(
310        &self,
311        app_name: &str,
312        user_id: &str,
313        events: &[Event],
314    ) -> Result<()> {
315        let contents: Vec<&Content> =
316            events.iter().filter_map(|event| event.llm_response.content.as_ref()).collect();
317        let expire_time = self.default_ttl.map(|ttl| crate::expiry::expiry_after(Utc::now(), ttl));
318        self.generate_memories(app_name, user_id, &contents, expire_time).await
319    }
320
321    /// Generates memories from `contents`, then sets `expire_time` on each memory the
322    /// generation created or updated.
323    async fn generate_memories(
324        &self,
325        app_name: &str,
326        user_id: &str,
327        contents: &[&Content],
328        expire_time: Option<DateTime<Utc>>,
329    ) -> Result<()> {
330        if contents.is_empty() {
331            debug!("no content-bearing entries; skipping memories:generate");
332            return Ok(());
333        }
334        let parent = self.memories_parent(app_name)?;
335        let events: Vec<Value> =
336            contents.iter().map(|content| json!({ "content": content })).collect();
337        let body = json!({
338            "directContentsSource": { "events": events },
339            "scope": memory_scope(app_name, user_id),
340        });
341        let request = self
342            .client
343            .request(Method::POST, &format!("{parent}/memories:generate"))
344            .await?
345            .json(&body);
346        let operation = self.client.send_value(request).await?;
347        let response = self.wait_for_operation(operation, "memories generate").await?;
348        let Some(expire_time) = expire_time else { return Ok(()) };
349        let generated: GenerateMemoriesResponse = response
350            .map(serde_json::from_value)
351            .transpose()
352            .map_err(|error| {
353                let error = truncate_for_error(&error.to_string());
354                self.client.errors().invalid_response(format!(
355                    "failed to parse memories:generate response: {error}"
356                ))
357            })?
358            .unwrap_or_default();
359        for generated in generated.generated_memories {
360            if matches!(generated.action.as_deref(), Some("CREATED" | "UPDATED")) {
361                self.set_expire_time(&generated.memory.name, expire_time).await?;
362            }
363        }
364        Ok(())
365    }
366
367    /// Sets the `expireTime` of the memory `memory_name`.
368    async fn set_expire_time(&self, memory_name: &str, expire_time: DateTime<Utc>) -> Result<()> {
369        validate_memory_resource_name(memory_name, &self.project_id, &self.location)?;
370        let request = self
371            .client
372            .request(Method::PATCH, memory_name)
373            .await?
374            .query(&[("updateMask", "expireTime")])
375            .json(&json!({
376                "expireTime": expire_time.to_rfc3339_opts(chrono::SecondsFormat::Millis, true)
377            }));
378        let operation = self.client.send_value(request).await?;
379        self.wait_for_operation(operation, "memory update").await?;
380        Ok(())
381    }
382
383    async fn retrieve_page(
384        &self,
385        parent: &str,
386        scope: &Value,
387        retrieval_params_key: &str,
388        retrieval_params: Value,
389    ) -> Result<RetrieveMemoriesResponse> {
390        let body = json!({
391            "scope": scope,
392            retrieval_params_key: retrieval_params,
393        });
394        let request = self
395            .client
396            .request(Method::POST, &format!("{parent}/memories:retrieve"))
397            .await?
398            .json(&body);
399        let value = self.client.send_value(request).await?;
400        serde_json::from_value(value).map_err(|error| {
401            let error = truncate_for_error(&error.to_string());
402            self.client
403                .errors()
404                .invalid_response(format!("failed to parse memories:retrieve response: {error}"))
405        })
406    }
407
408    async fn delete_memory_resource(&self, memory_name: &str) -> Result<()> {
409        validate_memory_resource_name(memory_name, &self.project_id, &self.location)?;
410        let request = self.client.request(Method::DELETE, memory_name).await?;
411        let operation = self.client.send_value(request).await?;
412        self.wait_for_operation(operation, "memory delete").await?;
413        Ok(())
414    }
415
416    /// Polls a long-running operation to completion, scoped to this
417    /// service's project and location so a compromised or buggy server
418    /// cannot redirect polling elsewhere.
419    async fn wait_for_operation(
420        &self,
421        initial: Value,
422        operation_kind: &str,
423    ) -> Result<Option<Value>> {
424        self.poller
425            .wait_for_operation(
426                &self.client,
427                initial,
428                operation_kind,
429                false,
430                &self.project_id,
431                &self.location,
432            )
433            .await
434    }
435
436    fn memories_parent(&self, app_name: &str) -> Result<String> {
437        let reasoning_engine = self.resolve_reasoning_engine_id(app_name)?;
438        Ok(VertexResourceName::new(&self.project_id, &self.location, reasoning_engine).to_string())
439    }
440
441    fn resolve_reasoning_engine_id(&self, app_name: &str) -> Result<String> {
442        let Some(candidate) = self.reasoning_engine.as_deref() else {
443            if is_canonical_reasoning_engine_id(app_name) {
444                return Ok(app_name.to_string());
445            }
446            return Err(self.client.errors().invalid_input(
447                "when no fixed reasoning engine is configured, app_name must be its canonical numeric reasoning-engine ID without leading zeros; configure with_reasoning_engine for logical app names or full resource names",
448            ));
449        };
450        if is_canonical_reasoning_engine_id(candidate) {
451            return Ok(candidate.to_string());
452        }
453        let prefix =
454            format!("projects/{}/locations/{}/reasoningEngines/", self.project_id, self.location);
455        if let Some(id) = candidate.strip_prefix(&prefix)
456            && is_canonical_reasoning_engine_id(id)
457        {
458            return Ok(id.to_string());
459        }
460        let candidate = truncate_for_error(candidate);
461        Err(self.client.errors().invalid_input(format!(
462            "reasoning engine '{candidate}' is invalid. Provide a numeric ID or the exact resource name '{prefix}<numeric-id>'",
463        )))
464    }
465}
466
467#[async_trait]
468impl MemoryService for VertexAiMemoryBankService {
469    async fn add_session(
470        &self,
471        app_name: &str,
472        user_id: &str,
473        _session_id: &str,
474        entries: Vec<MemoryEntry>,
475    ) -> Result<()> {
476        // One generation per distinct expiry, so each generated memory takes its sources'
477        // expiry; entries without one form a single generation, as before expiry existed.
478        let now = Utc::now();
479        let mut groups: Vec<(Option<DateTime<Utc>>, Vec<&Content>)> = Vec::new();
480        for entry in &entries {
481            let expiry = crate::expiry::resolve_expiry(entry, self.default_ttl, now);
482            match groups.iter_mut().find(|(at, _)| *at == expiry) {
483                Some((_, contents)) => contents.push(&entry.content),
484                None => groups.push((expiry, vec![&entry.content])),
485            }
486        }
487        for (expiry, contents) in groups {
488            self.generate_memories(app_name, user_id, &contents, expiry).await?;
489        }
490        Ok(())
491    }
492
493    async fn search(&self, req: SearchRequest) -> Result<SearchResponse> {
494        if let Some(project_id) = &req.project_id {
495            // Memory Bank scopes are exact-match maps; a project dimension
496            // would need its own scope key, which no other runtime writes.
497            let project_id = truncate_for_error(project_id);
498            return Err(self.client.errors().invalid_input(format!(
499                "project-scoped search (project_id '{project_id}') is not supported by the Memory Bank backend; memories are scoped by app_name and user_id only",
500            )));
501        }
502        let parent = self.memories_parent(&req.app_name)?;
503        let scope = memory_scope(&req.app_name, &req.user_id);
504        let top_k = req.limit.unwrap_or(10);
505        let response = self
506            .retrieve_page(
507                &parent,
508                &scope,
509                "similaritySearchParams",
510                json!({ "searchQuery": req.query, "topK": top_k }),
511            )
512            .await?;
513        // Memory Bank deletes an expired memory on its own schedule; until then it is skipped.
514        let now = Utc::now();
515        let memories = response
516            .retrieved_memories
517            .into_iter()
518            .map(retrieved_to_entry)
519            .filter(|entry| !entry.is_expired_at(now))
520            .collect();
521        Ok(SearchResponse { memories })
522    }
523
524    async fn export_user(&self, app_name: &str, user_id: &str) -> Result<Vec<UserMemory>> {
525        let parent = self.memories_parent(app_name)?;
526        let scope = memory_scope(app_name, user_id);
527        let mut memories = Vec::new();
528        let mut page_token: Option<String> = None;
529        for _ in 0..DELETE_MAX_PAGES {
530            let mut params = json!({ "pageSize": DELETE_PAGE_SIZE });
531            if let Some(token) = &page_token {
532                params["pageToken"] = json!(token);
533            }
534            let response =
535                self.retrieve_page(&parent, &scope, "simpleRetrievalParams", params).await?;
536            memories.extend(response.retrieved_memories.into_iter().map(|retrieved| UserMemory {
537                entry: retrieved_to_entry(retrieved),
538                session_id: None,
539                project_id: None,
540            }));
541            match response.next_page_token {
542                Some(token) if !token.is_empty() => page_token = Some(token),
543                _ => {
544                    memories.sort_by_key(|memory| memory.entry.timestamp);
545                    return Ok(memories);
546                }
547            }
548        }
549        Err(self.client.errors().invalid_response(format!(
550            "vertex memory listing did not end after {DELETE_MAX_PAGES} pages",
551        )))
552    }
553
554    async fn delete_user(&self, app_name: &str, user_id: &str) -> Result<()> {
555        let parent = self.memories_parent(app_name)?;
556        let scope = memory_scope(app_name, user_id);
557        let mut page_token: Option<String> = None;
558        for _ in 0..DELETE_MAX_PAGES {
559            let mut params = json!({ "pageSize": DELETE_PAGE_SIZE });
560            if let Some(token) = &page_token {
561                params["pageToken"] = json!(token);
562            }
563            let response =
564                self.retrieve_page(&parent, &scope, "simpleRetrievalParams", params).await?;
565            for retrieved in &response.retrieved_memories {
566                self.delete_memory_resource(&retrieved.memory.name).await?;
567            }
568            match response.next_page_token {
569                Some(token) if !token.is_empty() => page_token = Some(token),
570                _ => return Ok(()),
571            }
572        }
573        Err(self.client.errors().invalid_response(format!(
574            "vertex memory deletion did not converge after {DELETE_MAX_PAGES} pages; remaining memories for this scope must be deleted in Google Cloud",
575        )))
576    }
577
578    /// Deletes the memory whose resource name is `memory_id`, after reading it to confirm it
579    /// belongs to `user_id` in `app_name`. A memory of another scope, or one that does not
580    /// exist, is reported as 0 removed.
581    async fn delete_memory(&self, app_name: &str, user_id: &str, memory_id: &str) -> Result<u64> {
582        let parent = self.memories_parent(app_name)?;
583        if !memory_id.starts_with(&format!("{parent}/memories/")) {
584            return Ok(0);
585        }
586        validate_memory_resource_name(memory_id, &self.project_id, &self.location)?;
587        let request = self.client.request(Method::GET, memory_id).await?;
588        let Some(memory) = self.client.send_value_allow_not_found(request).await? else {
589            return Ok(0);
590        };
591        if memory.get("scope") != Some(&memory_scope(app_name, user_id)) {
592            return Ok(0);
593        }
594        self.delete_memory_resource(memory_id).await?;
595        Ok(1)
596    }
597
598    /// Memory Bank deletes a memory at its `expireTime` itself, so there is nothing to purge.
599    async fn purge_expired(&self) -> Result<u64> {
600        Ok(0)
601    }
602
603    async fn health_check(&self) -> Result<()> {
604        // Credential acquisition exercises ADC and token refresh — the
605        // failure mode a readiness probe needs to catch.
606        self.client.auth_headers().await.map(|_| ())
607    }
608}
609
610/// The exact scope map both adk-python and adk-rust write, so one Memory
611/// Bank serves both runtimes.
612fn memory_scope(app_name: &str, user_id: &str) -> Value {
613    json!({ "app_name": app_name, "user_id": user_id })
614}
615
616fn retrieved_to_entry(retrieved: RetrievedMemory) -> MemoryEntry {
617    let parse =
618        |value: Option<&str>| value.and_then(|value| DateTime::parse_from_rfc3339(value).ok());
619    let memory = retrieved.memory;
620    // updateTime survives as the entry timestamp.
621    let timestamp = parse(memory.update_time.as_deref().or(memory.create_time.as_deref()))
622        .map_or_else(Utc::now, |parsed| parsed.with_timezone(&Utc));
623    let mut entry = MemoryEntry::new(Content::new("model").with_text(memory.fact), "memory_bank")
624        .with_timestamp(timestamp);
625    entry.expires_at = parse(memory.expire_time.as_deref())
626        .map(|at| crate::expiry::to_millis(at.with_timezone(&Utc)));
627    entry.id = Some(memory.name);
628    entry
629}
630
631#[derive(Debug, Deserialize)]
632#[serde(rename_all = "camelCase")]
633struct RetrieveMemoriesResponse {
634    #[serde(default)]
635    retrieved_memories: Vec<RetrievedMemory>,
636    #[serde(default)]
637    next_page_token: Option<String>,
638}
639
640#[derive(Debug, Deserialize)]
641struct RetrievedMemory {
642    memory: VertexMemory,
643}
644
645#[derive(Debug, Deserialize)]
646#[serde(rename_all = "camelCase")]
647struct VertexMemory {
648    name: String,
649    #[serde(default)]
650    fact: String,
651    #[serde(default)]
652    create_time: Option<String>,
653    #[serde(default)]
654    update_time: Option<String>,
655    #[serde(default)]
656    expire_time: Option<String>,
657}
658
659/// The `response` of a finished `memories:generate` operation.
660#[derive(Debug, Default, Deserialize)]
661#[serde(rename_all = "camelCase")]
662struct GenerateMemoriesResponse {
663    #[serde(default)]
664    generated_memories: Vec<GeneratedMemory>,
665}
666
667#[derive(Debug, Deserialize)]
668struct GeneratedMemory {
669    memory: GeneratedMemoryName,
670    /// `CREATED`, `UPDATED` or `DELETED`.
671    #[serde(default)]
672    action: Option<String>,
673}
674
675#[derive(Debug, Deserialize)]
676struct GeneratedMemoryName {
677    name: String,
678}
679
680/// Rejects memory resource names outside this service's project and
681/// location before issuing a DELETE. Crate-specific: the shared scope check
682/// does not know Memory Bank names must carry a `/memories/` segment.
683fn validate_memory_resource_name(name: &str, project_id: &str, location: &str) -> Result<()> {
684    let prefix = format!("projects/{project_id}/locations/{location}/reasoningEngines/");
685    if name.starts_with(&prefix)
686        && name.contains("/memories/")
687        && !name.contains("://")
688        && !name.contains("..")
689    {
690        return Ok(());
691    }
692    let name = truncate_for_error(name);
693    Err(error_context().invalid_response(format!(
694        "memory resource name '{name}' does not belong to projects/{project_id}/locations/{location}; refusing to delete it",
695    )))
696}
697
698#[cfg(test)]
699mod tests {
700    use super::*;
701
702    #[test]
703    fn scope_matches_python_shape() {
704        assert_eq!(
705            memory_scope("weather-app", "u-1"),
706            json!({"app_name": "weather-app", "user_id": "u-1"}),
707        );
708    }
709
710    #[test]
711    fn memory_names_outside_the_scope_are_rejected() {
712        assert!(
713            validate_memory_resource_name(
714                "projects/p/locations/l/reasoningEngines/1/memories/m",
715                "p",
716                "l",
717            )
718            .is_ok()
719        );
720        assert!(
721            validate_memory_resource_name(
722                "projects/p/locations/l/reasoningEngines/1/sessions/s",
723                "p",
724                "l",
725            )
726            .is_err()
727        );
728        assert!(
729            validate_memory_resource_name(
730                "projects/other/locations/l/reasoningEngines/1/memories/m",
731                "p",
732                "l",
733            )
734            .is_err()
735        );
736    }
737
738    #[test]
739    fn endpoint_defaults_to_regional_origin() {
740        let config = VertexAiMemoryConfig::new("p", "us-central1");
741        assert_eq!(config.endpoint(), "https://us-central1-aiplatform.googleapis.com");
742    }
743}