1use adk_core::{Agent, Content, ErrorComponent, Event, EventStream, InvocationContext, Result};
23use adk_gcp::{GcpErrorCodes, GcpErrorContext, GcpHttpClient};
24use async_trait::async_trait;
25use reqwest::Method;
26use serde_json::{Value, json};
27use std::sync::Arc;
28
29const API_VERSION: &str = "v1";
30const DEFAULT_CLASS_METHOD: &str = "streaming_agent_run_with_events";
31const DEFAULT_FALLBACK_CLASS_METHOD: &str = "stream_query";
32const RUNTIME_REFERENCE_ATTRIBUTE: &str = "agentregistry.googleapis.com/system/RuntimeReference";
33
34const GCP_ERROR_CODES: GcpErrorCodes = GcpErrorCodes {
35 invalid_input: "server.remote_engine.invalid_input",
36 unauthorized: "server.remote_engine.unauthorized",
37 forbidden: "server.remote_engine.forbidden",
38 not_found: "server.remote_engine.not_found",
39 rate_limited: "server.remote_engine.rate_limited",
40 timeout: "server.remote_engine.timeout",
41 unavailable: "server.remote_engine.unavailable",
42 credentials_unavailable: "server.remote_engine.credentials_unavailable",
43 invalid_response: "server.remote_engine.invalid_response",
44 invalid_request: "server.remote_engine.invalid_request",
45 upstream_error: "server.remote_engine.upstream_error",
46 operation_failed: "server.remote_engine.operation_failed",
47};
48
49fn gcp_error_context() -> GcpErrorContext {
50 GcpErrorContext::new(ErrorComponent::Server, GCP_ERROR_CODES, "remote reasoning engine")
51}
52
53pub struct RemoteReasoningEngineAgentBuilder {
70 name: String,
71 description: String,
72 resource_name: Option<String>,
73 urn: Option<String>,
74 registry: Option<adk_tool::AgentRegistryClient>,
75 class_method: String,
76 fallback_class_method: Option<String>,
77 endpoint: Option<String>,
78 credentials: Option<google_cloud_auth::credentials::Credentials>,
79}
80
81impl RemoteReasoningEngineAgentBuilder {
82 fn new(name: impl Into<String>) -> Self {
83 Self {
84 name: name.into(),
85 description: "Remote Agent Engine agent".to_string(),
86 resource_name: None,
87 urn: None,
88 registry: None,
89 class_method: DEFAULT_CLASS_METHOD.to_string(),
90 fallback_class_method: Some(DEFAULT_FALLBACK_CLASS_METHOD.to_string()),
91 endpoint: None,
92 credentials: None,
93 }
94 }
95
96 #[must_use]
98 pub fn description(mut self, description: impl Into<String>) -> Self {
99 self.description = description.into();
100 self
101 }
102
103 #[must_use]
106 pub fn resource_name(mut self, resource_name: impl Into<String>) -> Self {
107 self.resource_name = Some(resource_name.into());
108 self
109 }
110
111 #[must_use]
114 pub fn urn(mut self, urn: impl Into<String>) -> Self {
115 self.urn = Some(urn.into());
116 self
117 }
118
119 #[must_use]
121 pub fn registry(mut self, registry: adk_tool::AgentRegistryClient) -> Self {
122 self.registry = Some(registry);
123 self
124 }
125
126 #[must_use]
131 pub fn class_method(mut self, class_method: impl Into<String>) -> Self {
132 self.class_method = class_method.into();
133 self.fallback_class_method = None;
134 self
135 }
136
137 #[must_use]
139 pub fn endpoint(mut self, endpoint: impl Into<String>) -> Self {
140 self.endpoint = Some(endpoint.into());
141 self
142 }
143
144 #[must_use]
146 pub fn credentials(mut self, credentials: google_cloud_auth::credentials::Credentials) -> Self {
147 self.credentials = Some(credentials);
148 self
149 }
150
151 pub async fn build(self) -> Result<RemoteReasoningEngineAgent> {
159 let errors = gcp_error_context();
160 let resource_name = match (self.resource_name, self.urn) {
161 (Some(resource_name), _) => resource_name,
162 (None, Some(urn)) => {
163 let registry = self.registry.as_ref().ok_or_else(|| {
164 errors.invalid_input(
165 "a URN address requires a registry client; call registry(...) or use resource_name(...)",
166 )
167 })?;
168 resolve_urn(registry, &urn).await?
169 }
170 (None, None) => {
171 return Err(errors.invalid_input(
172 "the remote engine address is required; call resource_name(...) or urn(...) + registry(...)",
173 ));
174 }
175 };
176
177 let location = location_of(&resource_name).ok_or_else(|| {
178 errors.invalid_input(format!(
179 "'{resource_name}' is not a projects/*/locations/*/reasoningEngines/* resource name",
180 ))
181 })?;
182 let endpoint = self
183 .endpoint
184 .unwrap_or_else(|| format!("https://{location}-aiplatform.googleapis.com"));
185
186 let mut builder =
187 GcpHttpClient::builder(gcp_error_context(), endpoint).api_version(API_VERSION);
188 if let Some(credentials) = self.credentials {
189 builder = builder.credentials(credentials);
190 }
191 let client = builder.build()?;
192
193 Ok(RemoteReasoningEngineAgent {
194 name: self.name,
195 description: self.description,
196 resource_name,
197 class_method: self.class_method,
198 fallback_class_method: self.fallback_class_method,
199 client: Arc::new(client),
200 })
201 }
202}
203
204pub struct RemoteReasoningEngineAgent {
206 name: String,
207 description: String,
208 resource_name: String,
209 class_method: String,
210 fallback_class_method: Option<String>,
211 client: Arc<GcpHttpClient>,
212}
213
214impl RemoteReasoningEngineAgent {
215 pub fn builder(name: impl Into<String>) -> RemoteReasoningEngineAgentBuilder {
217 RemoteReasoningEngineAgentBuilder::new(name)
218 }
219
220 pub fn resource_name(&self) -> &str {
222 &self.resource_name
223 }
224
225 fn input_for(&self, class_method: &str, ctx: &dyn InvocationContext) -> Value {
226 let message = user_text(ctx.user_content());
227 if class_method == DEFAULT_CLASS_METHOD {
228 let request = json!({
231 "appName": ctx.app_name(),
232 "userId": ctx.user_id(),
233 "sessionId": ctx.session_id(),
234 "newMessage": { "role": "user", "parts": [{ "text": message }] },
235 "streaming": true,
236 });
237 json!({ "request_json": request.to_string() })
238 } else {
239 json!({
240 "user_id": ctx.user_id(),
241 "session_id": ctx.session_id(),
242 "message": message,
243 })
244 }
245 }
246
247 async fn open_stream(
248 &self,
249 class_method: &str,
250 ctx: &dyn InvocationContext,
251 ) -> Result<reqwest::Response> {
252 let errors = gcp_error_context();
253 let body = json!({
254 "classMethod": class_method,
257 "input": self.input_for(class_method, ctx),
258 });
259 let request = self
260 .client
261 .request(Method::POST, &format!("{}:streamQuery", self.resource_name))
262 .await?
263 .query(&[("alt", "sse")])
264 .json(&body);
265 let response = request.send().await.map_err(|error| {
266 errors.unavailable(format!(
267 "failed to send remote reasoning engine request: {}",
268 adk_gcp::truncate_for_error(&error.without_url().to_string()),
269 ))
270 })?;
271 let status = response.status();
272 if !status.is_success() {
273 let body = response.text().await.unwrap_or_default();
274 return Err(errors.status_error(status, &body));
275 }
276 Ok(response)
277 }
278
279 fn should_fall_back(error: &adk_core::AdkError) -> bool {
281 matches!(error.details.upstream_status_code, Some(400 | 404 | 422 | 501))
282 }
283}
284
285#[async_trait]
286impl Agent for RemoteReasoningEngineAgent {
287 fn name(&self) -> &str {
288 &self.name
289 }
290
291 fn description(&self) -> &str {
292 &self.description
293 }
294
295 fn sub_agents(&self) -> &[Arc<dyn Agent>] {
296 &[]
297 }
298
299 async fn run(&self, ctx: Arc<dyn InvocationContext>) -> Result<EventStream> {
300 let agent = RemoteReasoningEngineAgent {
301 name: self.name.clone(),
302 description: self.description.clone(),
303 resource_name: self.resource_name.clone(),
304 class_method: self.class_method.clone(),
305 fallback_class_method: self.fallback_class_method.clone(),
306 client: Arc::clone(&self.client),
307 };
308 let invocation_id = ctx.invocation_id().to_string();
309 let agent_name = self.name.clone();
310
311 let stream = async_stream::stream! {
312 let response = match agent.open_stream(&agent.class_method, ctx.as_ref()).await {
313 Ok(response) => Ok(response),
314 Err(error)
315 if RemoteReasoningEngineAgent::should_fall_back(&error)
316 && agent.fallback_class_method.is_some() =>
317 {
318 let fallback = agent.fallback_class_method.as_deref().unwrap();
319 tracing::debug!(
320 remote.class_method = %agent.class_method,
321 remote.fallback = %fallback,
322 "primary class method rejected; retrying with fallback"
323 );
324 agent.open_stream(fallback, ctx.as_ref()).await
325 }
326 Err(error) => Err(error),
327 };
328 let mut response = match response {
329 Ok(response) => response,
330 Err(error) => {
331 yield Err(error);
332 return;
333 }
334 };
335
336 let mut parser = SseFrameParser::default();
337 loop {
338 let chunk = match response.chunk().await {
339 Ok(Some(chunk)) => chunk,
340 Ok(None) => break,
341 Err(error) => {
342 yield Ok(stream_error_event(
343 &invocation_id,
344 &agent_name,
345 &format!(
346 "remote reasoning engine stream failed: {}",
347 adk_gcp::truncate_for_error(&error.without_url().to_string()),
348 ),
349 ));
350 return;
351 }
352 };
353 for payload in parser.push(&chunk) {
354 match parse_remote_event(&payload) {
355 Ok(event) => yield Ok(event),
356 Err(message) => {
357 yield Ok(stream_error_event(&invocation_id, &agent_name, &message));
358 return;
359 }
360 }
361 }
362 }
363 for payload in parser.finish() {
364 match parse_remote_event(&payload) {
365 Ok(event) => yield Ok(event),
366 Err(message) => {
367 yield Ok(stream_error_event(&invocation_id, &agent_name, &message));
368 return;
369 }
370 }
371 }
372 };
373 Ok(Box::pin(stream))
374 }
375}
376
377#[derive(Default)]
383struct SseFrameParser {
384 buffer: String,
385}
386
387impl SseFrameParser {
388 fn push(&mut self, chunk: &[u8]) -> Vec<String> {
389 self.buffer.push_str(&String::from_utf8_lossy(chunk));
390 let mut payloads = Vec::new();
391 while let Some(boundary) = self
392 .buffer
393 .find("\n\n")
394 .map(|i| (i, 2))
395 .or_else(|| self.buffer.find("\r\n\r\n").map(|i| (i, 4)))
396 {
397 let frame: String = self.buffer.drain(..boundary.0 + boundary.1).collect();
398 if let Some(payload) = frame_payload(&frame) {
399 payloads.push(payload);
400 }
401 }
402 payloads
403 }
404
405 fn finish(&mut self) -> Vec<String> {
406 let rest = std::mem::take(&mut self.buffer);
407 frame_payload(&rest).into_iter().collect()
408 }
409}
410
411fn frame_payload(frame: &str) -> Option<String> {
413 let mut data_lines = Vec::new();
414 for line in frame.lines() {
415 let line = line.trim_end_matches('\r');
416 if let Some(data) = line.strip_prefix("data:") {
417 data_lines.push(data.strip_prefix(' ').unwrap_or(data));
418 } else if !line.is_empty() && !line.starts_with(':') && !line.contains(':') {
419 data_lines.push(line);
421 }
422 }
423 if data_lines.is_empty() {
424 let trimmed = frame.trim();
425 if trimmed.is_empty() {
426 return None;
427 }
428 return Some(trimmed.to_string());
430 }
431 Some(data_lines.join("\n"))
432}
433
434fn parse_remote_event(payload: &str) -> std::result::Result<Event, String> {
436 let value: Value = serde_json::from_str(payload).map_err(|error| {
437 format!(
438 "failed to parse remote reasoning engine event JSON: {}",
439 adk_gcp::truncate_for_error(&error.to_string()),
440 )
441 })?;
442 if let Some(error) = value.get("error") {
443 return Err(format!(
444 "remote reasoning engine reported an error mid-stream: {}",
445 adk_gcp::truncate_for_error(&error.to_string()),
446 ));
447 }
448 serde_json::from_value(value).map_err(|error| {
449 format!(
450 "remote reasoning engine event does not match the ADK event shape: {}",
451 adk_gcp::truncate_for_error(&error.to_string()),
452 )
453 })
454}
455
456fn stream_error_event(invocation_id: &str, agent_name: &str, message: &str) -> Event {
457 let mut event = Event::new(invocation_id.to_string());
458 event.author = agent_name.to_string();
459 event.llm_response.error_message = Some(message.to_string());
460 event.llm_response.turn_complete = true;
461 event
462}
463
464fn user_text(content: &Content) -> String {
466 content
467 .parts
468 .iter()
469 .filter_map(|part| match part {
470 adk_core::Part::Text { text, .. } => Some(text.as_str()),
471 _ => None,
472 })
473 .collect::<Vec<_>>()
474 .join("\n")
475}
476
477async fn resolve_urn(registry: &adk_tool::AgentRegistryClient, urn: &str) -> Result<String> {
480 let errors = gcp_error_context();
481 let agent = registry.get_agent(urn).await?;
482 let uri = agent
483 .attributes
484 .as_ref()
485 .and_then(|attributes| attributes.get(RUNTIME_REFERENCE_ATTRIBUTE))
486 .and_then(|attribute| attribute.get("uri"))
487 .and_then(Value::as_str)
488 .ok_or_else(|| {
489 errors.invalid_input(format!(
490 "registry entry '{urn}' carries no RuntimeReference attribute; only Agent Engine deployments can be invoked as remote reasoning engines",
491 ))
492 })?;
493 let resource_name = uri.trim_start_matches('/');
494 let resource_name = resource_name
495 .strip_prefix("aiplatform.googleapis.com/")
496 .unwrap_or(resource_name)
497 .to_string();
498 if location_of(&resource_name).is_none() {
499 return Err(errors.invalid_input(format!(
500 "registry entry '{urn}' resolves to '{resource_name}', which is not a reasoningEngines resource name",
501 )));
502 }
503 Ok(resource_name)
504}
505
506fn location_of(resource_name: &str) -> Option<&str> {
508 let mut segments = resource_name.split('/');
509 let (
510 Some("projects"),
511 Some(_),
512 Some("locations"),
513 Some(location),
514 Some("reasoningEngines"),
515 Some(id),
516 ) = (
517 segments.next(),
518 segments.next(),
519 segments.next(),
520 segments.next(),
521 segments.next(),
522 segments.next(),
523 )
524 else {
525 return None;
526 };
527 if location.is_empty() || id.is_empty() { None } else { Some(location) }
528}
529
530#[cfg(test)]
531mod tests {
532 use super::*;
533
534 #[test]
535 fn locations_parse_only_from_engine_resource_names() {
536 assert_eq!(
537 location_of("projects/p/locations/us-central1/reasoningEngines/42"),
538 Some("us-central1"),
539 );
540 assert_eq!(location_of("projects/p/locations/us-central1/reasoningEngines/"), None);
541 assert_eq!(location_of("projects/p/locations/us-central1/agents/42"), None);
542 assert_eq!(location_of("us-central1"), None);
543 }
544
545 #[test]
546 fn sse_frames_survive_chunk_splits_and_bare_lines() {
547 let mut parser = SseFrameParser::default();
548 let mut payloads = parser.push(b"data: {\"a\":");
549 assert!(payloads.is_empty(), "incomplete frame must buffer");
550 payloads.extend(parser.push(b" 1}\n\ndata: {\"b\": 2}\n\n"));
551 assert_eq!(payloads, vec!["{\"a\": 1}".to_string(), "{\"b\": 2}".to_string()]);
552
553 let mut parser = SseFrameParser::default();
554 let payloads = parser.push(b"{\"bare\": true}\n\n");
555 assert_eq!(payloads, vec!["{\"bare\": true}".to_string()]);
556 }
557
558 #[test]
559 fn multi_line_data_frames_join_per_sse_spec() {
560 let mut parser = SseFrameParser::default();
561 let payloads = parser.push(b"data: {\"a\":\ndata: 1}\n\n");
562 assert_eq!(payloads, vec!["{\"a\":\n1}".to_string()]);
563 }
564
565 #[test]
566 fn error_payloads_terminate_with_a_message() {
567 let error = parse_remote_event("{\"error\": {\"code\": 404, \"message\": \"gone\"}}")
568 .expect_err("error payloads must not parse as events");
569 assert!(error.contains("mid-stream"), "{error}");
570 }
571}