| /* | |
| * Licensed to the Apache Software Foundation (ASF) under one | |
| * or more contributor license agreements. See the NOTICE file | |
| * distributed with this work for additional information | |
| * regarding copyright ownership. The ASF licenses this file | |
| * to you under the Apache License, Version 2.0 (the | |
| * "License"); you may not use this file except in compliance | |
| * with the License. You may obtain a copy of the License at | |
| * | |
| * http://www.apache.org/licenses/LICENSE-2.0 | |
| * | |
| * Unless required by applicable law or agreed to in writing, | |
| * software distributed under the License is distributed on an | |
| * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | |
| * KIND, either express or implied. See the License for the | |
| * specific language governing permissions and limitations | |
| * under the License. | |
| */ | |
| use super::*; | |
| use base64::{Engine, engine::general_purpose::STANDARD}; | |
| use maka_agent_facts::{ | |
| executor::{Output, ToolResultDetails, TurnUsage}, | |
| model::ModelUsage, | |
| }; | |
| use maka_external_agent::AcpV1Projection; | |
| use runtime::Pipe; | |
| use runtime::string; | |
| use serde_json::json; | |
| use std::borrow::Cow; | |
| const HOST_SERVER: &str = "maka"; | |
| const HOST_GUIDANCE: &str = "Use Maka MCP tools (mcp_maka_* or mcp_maka_exec) to read, write, \ | |
| and edit workspace files, run commands, coordinate sessions and Rooms, ask the user questions \ | |
| (AskUserQuestion), and manage automation. Pass maka:// resource URIs directly to Maka's Read tool. \ | |
| For read-only local attachment files or prior conversation context files provided in the prompt \ | |
| outside the workspace, use Antigravity's built-in read_file tool (which natively supports text, \ | |
| images, PDFs, video, and audio), since Maka's Read tool only decodes UTF-8 text and common images \ | |
| and sandboxed workspace modes deny Host private task directories. Otherwise, avoid Antigravity's \ | |
| built-in file, terminal, and interactive question tools. You can use the built-in search_web for \ | |
| web searches. Do not spawn subagents or leave background processes or tasks running. Maka shuts \ | |
| down this agy process tree at the end of each turn."; | |
| #[expect( | |
| clippy::too_many_arguments, | |
| reason = "one invocation owns the original process, protocol and Host bridge" | |
| )] | |
| pub(super) async fn execute( | |
| config: &NativeCommand, | |
| cwd: &str, | |
| request: &Value, | |
| journal: &mut journal::ProtocolSession, | |
| output: Arc<dyn OutputSink>, | |
| bridge: Arc<mcp::Bridge>, | |
| cancellation: CancellationToken, | |
| owner: maka_process::isolated::TaskOwner, | |
| ) -> Result<Outcome, Error> { | |
| let observation = journal.observation(); | |
| let descriptor = owner.descriptor(); | |
| let (session, ticket) = | |
| match agy_front::open(config, cwd, owner, &cancellation, &observation.retired).await { | |
| Ok(session) => { | |
| let mut ticket = observation | |
| .resources | |
| .reserve() | |
| .map_err(|_| Error::ObservationRetired)?; | |
| ticket.start(); | |
| (session, ticket) | |
| } | |
| Err(agy_front::OpenError::BeforeLaunch(owner, error)) => { | |
| let error = if cancellation.is_cancelled() { | |
| Error::Cancelled | |
| } else if observation.retired.is_cancelled() { | |
| Error::ObservationRetired | |
| } else { | |
| error | |
| }; | |
| return runtime::fail_without_launch(&observation, *owner, error).await; | |
| } | |
| Err(agy_front::OpenError::Closed(error)) => { | |
| let mut ticket = observation | |
| .resources | |
| .reserve() | |
| .map_err(|_| Error::ObservationRetired)?; | |
| ticket.start(); | |
| ticket.complete(Ok(())); | |
| observation | |
| .binding | |
| .cleanup(OperationCleanup::Confirmed) | |
| .await?; | |
| return if cancellation.is_cancelled() { | |
| Err(Error::Cancelled) | |
| } else if observation.retired.is_cancelled() { | |
| Err(Error::ObservationRetired) | |
| } else { | |
| runtime::preparation_failure(error) | |
| }; | |
| } | |
| Err(agy_front::OpenError::Unconfirmed(error)) => { | |
| let mut ticket = observation | |
| .resources | |
| .reserve() | |
| .map_err(|_| Error::ObservationRetired)?; | |
| ticket.start(); | |
| ticket.unconfirmed(error.to_string(), descriptor); | |
| return Err(Error::CleanupUnconfirmed); | |
| } | |
| }; | |
| let agy_front::Session { | |
| stdin, | |
| stdout, | |
| child, | |
| } = session; | |
| let mut io = Pipe::session( | |
| stdin, | |
| stdout, | |
| observation.clone(), | |
| cancellation, | |
| bridge.failed.clone(), | |
| ); | |
| let protocol = Protocol { | |
| cwd, | |
| request, | |
| journal, | |
| output, | |
| bridge: bridge.clone(), | |
| }; | |
| let stop = io.stop.clone(); | |
| let outcome = { | |
| let result = protocol.converse(&mut io); | |
| tokio::pin!(result); | |
| tokio::select! { | |
| biased; | |
| () = stop.cancelled() => { bridge.close_admission(); result.await } | |
| outcome = &mut result => outcome, | |
| } | |
| }; | |
| bridge.close_admission(); | |
| drop(io); // EOF asks this Run's supervisor to close and reap its agy process tree. | |
| let (closed, bridge_closed) = tokio::join!( | |
| agy_front::wait_for_close(&descriptor, child), | |
| bridge.close() | |
| ); | |
| bridge.clone().original_root_cleanup_signal().await; | |
| if let Err(error) = closed { | |
| ticket.unconfirmed(error.to_string(), descriptor); | |
| return Err(Error::CleanupUnconfirmed); | |
| } | |
| ticket.complete(Ok(())); | |
| observation | |
| .binding | |
| .cleanup(OperationCleanup::Confirmed) | |
| .await?; | |
| bridge_closed?; | |
| if matches!(outcome, Err(Error::CleanupUnconfirmed)) | |
| && observation.binding.stop_requested().await? | |
| { | |
| let cancelled = Outcome::Cancelled { | |
| reason: Some("native_stopped".into()), | |
| }; | |
| observation.closed(cancelled.clone()).await?; | |
| return Ok(cancelled); | |
| } | |
| outcome | |
| } | |
| struct Protocol<'a> { | |
| cwd: &'a str, | |
| request: &'a Value, | |
| journal: &'a mut journal::ProtocolSession, | |
| output: Arc<dyn OutputSink>, | |
| bridge: Arc<mcp::Bridge>, | |
| } | |
| impl Protocol<'_> { | |
| async fn converse(mut self, io: &mut Pipe) -> Result<Outcome, Error> { | |
| let instructions = turn_instructions(self.request["instructions"].as_str()); | |
| let setup = self.prepare(io, &instructions).await; | |
| let (session, blocks, model, system_prompt_append, setup_title) = match setup { | |
| Ok(setup) => setup, | |
| Err( | |
| error @ (Error::Cancelled | |
| | Error::ObservationRetired | |
| | Error::Persistence(_) | |
| | Error::CleanupUnconfirmed | |
| | Error::Unknown), | |
| ) => return Err(error), | |
| Err(error) => return runtime::preparation_failure(error), | |
| }; | |
| let instruction_update = (!system_prompt_append) | |
| .then(|| self.journal.instruction_update(Some(&instructions))) | |
| .flatten(); | |
| let prompt = prompt_params( | |
| &session, | |
| blocks, | |
| instruction_update | |
| .as_ref() | |
| .map(|update| update.text.as_str()), | |
| ); | |
| io.turn_started(); | |
| let clock = crate::model_time::ModelTime::new(); | |
| let prompt_id = io | |
| .begin("session/prompt", prompt) | |
| .await | |
| .map_err(unconfirmed)?; | |
| self.journal | |
| .bind_task(NativeTask::AntigravityAcp { | |
| session: session.clone(), | |
| prompt_id, | |
| }) | |
| .await?; | |
| let mut turn = Turn::new(session.clone(), prompt_id, true, true); | |
| turn.clock = Some(clock); | |
| turn.model = model; | |
| if let Some(event) = io | |
| .setup_usage | |
| .take() | |
| .filter(|e| e["params"]["sessionId"] == session) | |
| { | |
| turn.event(event, self.output.as_ref()).await?; | |
| } | |
| if let Some(title) = setup_title { | |
| turn.emit_setup_title(title, self.output.as_ref()).await?; | |
| } | |
| let outcome = turn | |
| .observe(io, self.output.as_ref(), &self.bridge) | |
| .await | |
| .map_err(unconfirmed)?; | |
| if matches!(outcome, Outcome::Completed { .. }) | |
| && let Some(update) = instruction_update | |
| { | |
| self.journal.confirm_instructions(update).await?; | |
| } | |
| self.journal.closed(outcome.clone()).await?; | |
| io.turn_finished(); | |
| self.bridge.close_admission(); | |
| Ok(outcome) | |
| } | |
| async fn prepare( | |
| &mut self, | |
| io: &mut Pipe, | |
| instructions: &str, | |
| ) -> Result<(String, Vec<Value>, Option<String>, bool, Option<String>), Error> { | |
| let initialized = io.request("initialize", initialize_params()).await?; | |
| if initialized["protocolVersion"] != 1 | |
| || initialized.pointer("/agentCapabilities/mcpCapabilities/http") | |
| != Some(&Value::Bool(true)) | |
| { | |
| return Err(Error::Invalid( | |
| "agy must support ACP 1 with HTTP MCP".into(), | |
| )); | |
| } | |
| let system_prompt_append = supports_system_prompt_append(&initialized); | |
| let system_prompt = system_prompt_append | |
| .then(|| system_prompt_text(instructions, self.journal.has_delivered_instructions())); | |
| let (method, params) = open_params( | |
| self.cwd, | |
| &self.bridge.url, | |
| self.bridge.bearer(), | |
| self.journal.native_session(), | |
| system_prompt.as_deref(), | |
| ); | |
| let mut setup_title = None; | |
| let expected_session = self.journal.native_session().map(str::to_owned); | |
| let opened = io | |
| .request_with(method, params, |event| { | |
| capture_setup_title(&mut setup_title, expected_session.as_deref(), event); | |
| }) | |
| .await?; | |
| let session = match self.journal.native_session() { | |
| Some(previous) => opened["sessionId"].as_str().unwrap_or(previous), | |
| None => string(&opened, "/sessionId")?, | |
| } | |
| .to_owned(); | |
| self.journal.opened(session.clone())?; | |
| if !self.bridge.listed.is_cancelled() { | |
| return Err(Error::Invalid( | |
| "agy ACP did not discover Maka's MCP tools".into(), | |
| )); | |
| } | |
| let model = select_model(io, &session, opened, self.request, &mut setup_title).await?; | |
| let message = string(self.request, "/message")?; | |
| let blocks = prompt_blocks(message, &self.request["images"]).await?; | |
| self.bridge.admit()?; | |
| let setup_title = setup_title.and_then(|(id, title)| (id == session).then_some(title)); | |
| Ok((session, blocks, model, system_prompt_append, setup_title)) | |
| } | |
| } | |
| fn supports_system_prompt_append(initialized: &Value) -> bool { | |
| initialized.pointer("/agentCapabilities/_meta/antigravity/systemPrompt/append") | |
| == Some(&Value::Bool(true)) | |
| } | |
| fn turn_instructions(instructions: Option<&str>) -> Cow<'static, str> { | |
| match instructions.filter(|text| !text.trim().is_empty()) { | |
| Some(text) => format!("{HOST_GUIDANCE}\n\n{text}").into(), | |
| None => HOST_GUIDANCE.into(), | |
| } | |
| } | |
| fn system_prompt_text(instructions: &str, had_user_block: bool) -> Cow<'_, str> { | |
| if had_user_block { | |
| journal::instruction_text(Some(instructions)).into() | |
| } else { | |
| instructions.into() | |
| } | |
| } | |
| fn open_params( | |
| cwd: &str, | |
| bridge_url: &str, | |
| bearer: impl std::fmt::Display, | |
| session: Option<&str>, | |
| system_prompt: Option<&str>, | |
| ) -> (&'static str, Value) { | |
| let mut antigravity = json!({"eagerMcpServers":[HOST_SERVER]}); | |
| if let Some(instructions) = system_prompt { | |
| antigravity["systemPrompt"] = json!({"append": instructions}); | |
| } | |
| let mut params = json!({ | |
| "cwd":cwd, | |
| "mcpServers":[{ | |
| "type":"http", "name":HOST_SERVER, "url":bridge_url, | |
| "headers":[{"name":"Authorization", "value":format!("Bearer {bearer}")}] | |
| }], | |
| "_meta":{"antigravity":antigravity} | |
| }); | |
| let method = if let Some(session) = session { | |
| params["sessionId"] = session.into(); | |
| "session/resume" | |
| } else { | |
| "session/new" | |
| }; | |
| (method, params) | |
| } | |
| fn prompt_params(session: &str, mut blocks: Vec<Value>, instruction_update: Option<&str>) -> Value { | |
| if let Some(text) = instruction_update { | |
| blocks.insert( | |
| 0, | |
| json!({"type":"text","text":runtime::instruction_message(text)}), | |
| ); | |
| } | |
| json!({"sessionId":session,"prompt":blocks}) | |
| } | |
| fn initialize_params() -> Value { | |
| json!({"protocolVersion":1,"clientCapabilities":{},"clientInfo":{ | |
| "name":"maka","title":"Maka","version":env!("CARGO_PKG_VERSION") | |
| }}) | |
| } | |
| fn unconfirmed(error: Error) -> Error { | |
| match error { | |
| Error::Invalid(_) | Error::Provider(_) | Error::Cancelled => { | |
| tracing::debug!(%error, "agy ACP prompt could not be confirmed"); | |
| Error::Unknown | |
| } | |
| other => other, | |
| } | |
| } | |
| fn config_value<'a>(config: &'a Value, category: &str) -> Option<(&'a str, &'a str)> { | |
| let option = config["configOptions"] | |
| .as_array()? | |
| .iter() | |
| .find(|option| option["category"] == category)?; | |
| Some((option["id"].as_str()?, option["currentValue"].as_str()?)) | |
| } | |
| async fn select_model( | |
| io: &mut Pipe, | |
| session: &str, | |
| mut config: Value, | |
| request: &Value, | |
| setup_title: &mut Option<(String, String)>, | |
| ) -> Result<Option<String>, Error> { | |
| let mut model_id = active_model(&config); | |
| if let Some(model) = request["model"] | |
| .as_str() | |
| .filter(|&model| model != "default") | |
| && config | |
| .pointer("/models/currentModelId") | |
| .and_then(Value::as_str) | |
| != Some(model) | |
| { | |
| let (id, _) = config_value(&config, "model") | |
| .ok_or_else(|| Error::Invalid("agy ACP did not advertise model selection".into()))?; | |
| config = io | |
| .request_with( | |
| "session/set_config_option", | |
| json!({"sessionId":session,"configId":id,"value":model}), | |
| |event| capture_setup_title(setup_title, Some(session), event), | |
| ) | |
| .await?; | |
| model_id = active_model(&config).or(model_id); | |
| let selected = config_value(&config, "model").map(|(_, value)| value); | |
| // agy exposes a combined ID in its model catalog and separate config values. | |
| let confirmed = selected.is_some_and(|selected| { | |
| selected == model | |
| || config_value(&config, "thought_level").is_some_and(|(_, level)| { | |
| model | |
| .strip_prefix(selected) | |
| .and_then(|suffix| suffix.strip_prefix('-')) | |
| == Some(level) | |
| }) | |
| }); | |
| if !confirmed { | |
| return Err(Error::Invalid(format!( | |
| "agy ACP did not select model {model}" | |
| ))); | |
| } | |
| } | |
| if let Some(level) = request["effort"].as_str() { | |
| let (id, current) = config_value(&config, "thought_level").ok_or_else(|| { | |
| Error::Invalid("agy ACP did not advertise a thinking level for this model".into()) | |
| })?; | |
| if current != level { | |
| let updated = io | |
| .request_with( | |
| "session/set_config_option", | |
| json!({"sessionId":session,"configId":id,"value":level}), | |
| |event| capture_setup_title(setup_title, Some(session), event), | |
| ) | |
| .await?; | |
| model_id = active_model(&updated).or(model_id); | |
| if config_value(&updated, "thought_level").map(|(_, value)| value) != Some(level) { | |
| return Err(Error::Invalid(format!( | |
| "agy ACP did not select thinking level {level}" | |
| ))); | |
| } | |
| } | |
| } | |
| Ok(model_id) | |
| } | |
| fn active_model(config: &Value) -> Option<String> { | |
| config_value(config, "model") | |
| .map(|(_, current)| current) | |
| .or_else(|| config.pointer("/models/currentModelId")?.as_str()) | |
| .map(str::to_owned) | |
| } | |
| async fn prompt_blocks(message: &str, images: &Value) -> Result<Vec<Value>, Error> { | |
| let mut blocks = vec![json!({"type":"text","text":message})]; | |
| for image in images.as_array().into_iter().flatten() { | |
| let path = string(image, "/path")?; | |
| let mime = string(image, "/mediaType")?; | |
| let bytes = tokio::fs::read(path) | |
| .await | |
| .map_err(|error| Error::Provider(format!("Cannot read agy ACP image: {error}")))?; | |
| let data = tokio::task::spawn_blocking(move || STANDARD.encode(bytes)) | |
| .await | |
| .map_err(|error| Error::Provider(format!("Cannot encode agy ACP image: {error}")))?; | |
| blocks.push(json!({"type":"image","data":data,"mimeType":mime})); | |
| } | |
| Ok(blocks) | |
| } | |
| struct Turn { | |
| session: String, | |
| prompt_id: u64, | |
| projection: AcpV1Projection, | |
| context: bool, | |
| session_title: bool, | |
| model: Option<String>, | |
| clock: Option<crate::model_time::ModelTime>, | |
| host_calls: std::collections::BTreeSet<String>, | |
| } | |
| impl Turn { | |
| fn new(session: String, prompt_id: u64, context: bool, session_title: bool) -> Self { | |
| Self { | |
| context, | |
| session_title, | |
| model: None, | |
| clock: None, | |
| projection: AcpV1Projection::new(session.clone(), format!("agy:{prompt_id}")), | |
| session, | |
| prompt_id, | |
| host_calls: Default::default(), | |
| } | |
| } | |
| async fn emit_setup_title( | |
| &mut self, | |
| title: String, | |
| output: &dyn OutputSink, | |
| ) -> Result<(), Error> { | |
| if self.session_title { | |
| self.projection.emit_normalized_title(title, output).await?; | |
| } | |
| Ok(()) | |
| } | |
| async fn observe( | |
| &mut self, | |
| io: &mut Pipe, | |
| output: &dyn OutputSink, | |
| bridge: &mcp::Bridge, | |
| ) -> Result<Outcome, Error> { | |
| let mut cancel_deadline = None; | |
| loop { | |
| let event = if let Some(deadline) = cancel_deadline { | |
| tokio::time::timeout_at(deadline, io.next()) | |
| .await | |
| .map_err(|_| Error::CleanupUnconfirmed)?? | |
| } else { | |
| match io.next().await { | |
| Err(Error::Cancelled) if io.stop.is_cancelled() => { | |
| bridge.close_admission(); | |
| io.cancellation = CancellationToken::new(); | |
| io.failed = CancellationToken::new(); | |
| io.control("session/cancel", json!({"sessionId":self.session})) | |
| .await; | |
| cancel_deadline = | |
| Some(tokio::time::Instant::now() + runtime::INTERRUPT_TIMEOUT); | |
| continue; | |
| } | |
| event => event?, | |
| } | |
| }; | |
| if event.get("method").is_some() && event.get("id").is_some() { | |
| return io.unsupported(event).await; | |
| } | |
| if let Some(outcome) = self.event(event, output).await? { | |
| return Ok(outcome); | |
| } | |
| } | |
| } | |
| async fn event( | |
| &mut self, | |
| mut event: Value, | |
| output: &dyn OutputSink, | |
| ) -> Result<Option<Outcome>, Error> { | |
| if is_response(&event, self.prompt_id) { | |
| let result = &event["result"]; | |
| let reason = result["stopReason"].as_str(); | |
| let completed = reason == Some("end_turn"); | |
| let failure = match reason { | |
| Some("end_turn" | "cancelled") => None, | |
| Some("max_tokens" | "max_turn_requests" | "refusal") => reason, | |
| _ if event | |
| .pointer("/error/code") | |
| .and_then(Value::as_i64) | |
| .is_some() | |
| && event | |
| .pointer("/error/message") | |
| .and_then(Value::as_str) | |
| .is_some() => | |
| { | |
| event.pointer("/error/message").and_then(Value::as_str) | |
| } | |
| _ => return Err(Error::Unknown), | |
| }; | |
| self.projection.finish(output, completed).await?; | |
| if let Some(usage) = usage(result) { | |
| output | |
| .turn_usage( | |
| usage, | |
| self.clock | |
| .as_ref() | |
| .and_then(crate::model_time::ModelTime::millis), | |
| ) | |
| .await?; | |
| } | |
| return Ok(Some(match (reason, failure) { | |
| (Some("end_turn"), _) => Outcome::Completed { | |
| message_id: self.projection.last_body_message_id(), | |
| }, | |
| (Some("cancelled"), _) => Outcome::Cancelled { | |
| reason: Some("native_interrupted".into()), | |
| }, | |
| (_, Some(message)) => Outcome::Failed { | |
| message: format!("agy ACP turn ended: {message}"), | |
| code: Some("native_turn_failed".into()), | |
| recoverable: false, | |
| }, | |
| _ => return Err(Error::Unknown), | |
| })); | |
| } | |
| if event["method"] == "session/update" { | |
| let mut params = event["params"].take(); | |
| if params["sessionId"] != self.session { | |
| return Err(Error::Unknown); | |
| } | |
| let update = ¶ms["update"]; | |
| if update["sessionUpdate"] == "plan" | |
| && let Some(entries) = update["entries"].as_array() | |
| { | |
| output.current_plan_item( | |
| entries | |
| .iter() | |
| .find(|entry| entry["status"] == "in_progress") | |
| .and_then(|entry| entry["content"].as_str()), | |
| ); | |
| } | |
| if update["sessionUpdate"] == "usage_update" { | |
| if self.context | |
| && let (Some(used), Some(window)) = ( | |
| update["used"].as_u64(), | |
| update["size"].as_u64().and_then(std::num::NonZeroU64::new), | |
| ) | |
| { | |
| output | |
| .emit(Output::ContextUsage( | |
| maka_agent_facts::executor::ContextUsage { | |
| used, | |
| window, | |
| model: self.model.clone(), | |
| }, | |
| )) | |
| .await?; | |
| } | |
| return Ok(None); | |
| } | |
| if update["sessionUpdate"] == "session_info_update" && !self.session_title { | |
| return Ok(None); | |
| } | |
| if matches!( | |
| update["sessionUpdate"].as_str(), | |
| Some("tool_call" | "tool_call_update") | |
| ) { | |
| let id = string(update, "/toolCallId")?; | |
| if let Some(clock) = &mut self.clock { | |
| if matches!( | |
| update["status"].as_str(), | |
| Some("completed" | "failed" | "cancelled") | |
| ) { | |
| clock.tool_finished(id); | |
| } else if update["sessionUpdate"] == "tool_call" { | |
| clock.tool_started(id); | |
| } | |
| } | |
| // The Host bridge already emits the canonical Maka tool card. | |
| if update["name"] | |
| .as_str() | |
| .is_some_and(|name| name.starts_with("mcp_maka_")) | |
| { | |
| self.host_calls.insert(id.into()); | |
| } | |
| if self.host_calls.contains(id) { | |
| self.projection.close_message(output).await?; | |
| return Ok(None); | |
| } | |
| } | |
| if let Some(exit_code) = command_result(&mut params["update"]) { | |
| self.projection | |
| .update_json(params, &CommandResult { output, exit_code }) | |
| .await?; | |
| } else { | |
| self.projection.update_json(params, output).await?; | |
| } | |
| } | |
| Ok(None) | |
| } | |
| } | |
| fn command_result(update: &mut Value) -> Option<i32> { | |
| if update["name"] != "run_command" | |
| || !matches!(update["status"].as_str(), Some("completed" | "failed")) | |
| { | |
| return None; | |
| } | |
| let exit_code = i32::try_from(update["rawOutput"]["exit_code"].as_i64()?).ok()?; | |
| if let Some(raw) = update["rawOutput"]["output"].as_str() { | |
| let (body, _) = command_output(raw); | |
| update["content"] = json!([{ | |
| "type":"content", | |
| "content":{"type":"text","text":body.replace('\0', "\\0")} | |
| }]); | |
| } | |
| if exit_code != 0 { | |
| update["status"] = "failed".into(); | |
| } | |
| Some(exit_code) | |
| } | |
| fn command_output(raw: &str) -> (&str, Option<i32>) { | |
| let mut body = raw; | |
| for label in ["Created At: ", "Completed At: "] { | |
| if body.starts_with(label) { | |
| let Some((_, rest)) = body.split_once('\n') else { | |
| return (raw, None); | |
| }; | |
| body = rest; | |
| } | |
| } | |
| let (status, rest) = body.split_once('\n').unwrap_or((body, "")); | |
| let code = status | |
| .strip_prefix("Command exited with code ") | |
| .and_then(|code| code.trim_end_matches('\r').strip_suffix('.')) | |
| .and_then(|code| code.parse::<i32>().ok()); | |
| match (code, rest.trim_start_matches(['\r', '\n'])) { | |
| (Some(code), "") => ("", Some(code)), | |
| (Some(code), rest) | |
| if let Some(output) = rest | |
| .strip_prefix("Command output:\n") | |
| .or_else(|| rest.strip_prefix("Command output:\r\n")) => | |
| { | |
| (output, Some(code)) | |
| } | |
| _ => (raw, None), | |
| } | |
| } | |
| struct CommandResult<'a> { | |
| output: &'a dyn OutputSink, | |
| exit_code: i32, | |
| } | |
| impl OutputSink for CommandResult<'_> { | |
| fn emit(&self, mut event: Output) -> BoxFuture<'_, Result<(), Error>> { | |
| if let Output::ToolResult { details, .. } = &mut event { | |
| *details = Some(ToolResultDetails { | |
| exit_code: Some(self.exit_code), | |
| duration_ms: None, | |
| }); | |
| } | |
| self.output.emit(event) | |
| } | |
| } | |
| fn is_response(row: &Value, id: u64) -> bool { | |
| row["id"].as_u64() == Some(id) && row.get("method").is_none() | |
| } | |
| fn usage(result: &Value) -> Option<TurnUsage> { | |
| let usage = result["usage"].as_object()?; | |
| let counter = |key| usage.get(key).and_then(Value::as_u64); | |
| Some(TurnUsage { | |
| tokens: ModelUsage { | |
| input_tokens: counter("inputTokens"), | |
| output_tokens: counter("outputTokens"), | |
| cache_read_tokens: counter("cachedReadTokens"), | |
| cache_write_tokens: counter("cachedWriteTokens"), | |
| reasoning_tokens: counter("thoughtTokens"), | |
| }, | |
| total_tokens: counter("totalTokens"), | |
| duration_ms: None, | |
| }) | |
| } | |
| fn capture_setup_title( | |
| slot: &mut Option<(String, String)>, | |
| expected_session: Option<&str>, | |
| event: &Value, | |
| ) { | |
| if event["method"] != "session/update" | |
| || event | |
| .pointer("/params/update/sessionUpdate") | |
| .and_then(Value::as_str) | |
| != Some("session_info_update") | |
| { | |
| return; | |
| } | |
| let Some(session_id) = event.pointer("/params/sessionId").and_then(Value::as_str) else { | |
| return; | |
| }; | |
| if expected_session.is_some_and(|expected| expected != session_id) { | |
| return; | |
| } | |
| if let Some(title) = event | |
| .pointer("/params/update/title") | |
| .and_then(Value::as_str) | |
| .and_then(maka_session_title::normalize) | |
| { | |
| *slot = Some((session_id.to_owned(), title)); | |
| } | |
| } | |
| pub(super) async fn replay( | |
| context: bool, | |
| session_title: bool, | |
| session: &str, | |
| prompt_id: u64, | |
| input: &mut replay::Stream, | |
| stream: &mut replay::Stream, | |
| output: &dyn OutputSink, | |
| ) -> Result<Outcome, Error> { | |
| if prompt_id < 3 { | |
| return Err(Error::Unknown); | |
| } | |
| loop { | |
| let row = input.required().await?; | |
| if row["id"].as_u64() == Some(prompt_id) { | |
| if row["method"] != "session/prompt" | |
| || row["params"]["sessionId"] != session | |
| || !row["params"]["prompt"].is_array() | |
| { | |
| return Err(Error::Unknown); | |
| } | |
| break; | |
| } | |
| } | |
| while let Some(row) = input.next().await? { | |
| if row["params"]["sessionId"] != session | |
| || !matches!( | |
| row["method"].as_str(), | |
| Some("session/cancel" | "session/close") | |
| ) | |
| { | |
| return Err(Error::Unknown); | |
| } | |
| } | |
| // Setup may replay history or a prior instructions-only prompt. Its final RPC | |
| // acknowledgement precedes the current prompt, which is the only turn projected. | |
| let mut setup_usage = None; | |
| let mut setup_title = None; | |
| let mut model = None; | |
| loop { | |
| let event = stream.required().await?; | |
| if let Some(current) = active_model(&event["result"]) { | |
| model = Some(current); | |
| } | |
| if session_title { | |
| capture_setup_title(&mut setup_title, Some(session), &event); | |
| } | |
| if context | |
| && event["method"] == "session/update" | |
| && event["params"]["sessionId"] == session | |
| && event | |
| .pointer("/params/update/sessionUpdate") | |
| .and_then(Value::as_str) | |
| == Some("usage_update") | |
| { | |
| setup_usage = Some(event); | |
| continue; | |
| } | |
| if is_response(&event, prompt_id - 1) && event.get("result").is_some() { | |
| break; | |
| } | |
| } | |
| let mut turn = Turn::new(session.into(), prompt_id, context, session_title); | |
| turn.model = model; | |
| if let Some(event) = setup_usage { | |
| turn.event(event, output).await?; | |
| } | |
| if let Some((_, title)) = setup_title { | |
| turn.emit_setup_title(title, output).await?; | |
| } | |
| loop { | |
| let event = stream.required().await?; | |
| if let Some(outcome) = turn.event(event, output).await? { | |
| return Ok(outcome); | |
| } | |
| } | |
| } | |
| #[cfg(test)] | |
| mod tests { | |
| use super::*; | |
| #[derive(Default)] | |
| struct Sink(std::sync::Mutex<Vec<Output>>); | |
| impl OutputSink for Sink { | |
| fn emit(&self, event: Output) -> BoxFuture<'_, Result<(), Error>> { | |
| Box::pin(async move { | |
| self.0.lock().unwrap().push(event); | |
| Ok(()) | |
| }) | |
| } | |
| } | |
| fn spool(rows: impl IntoIterator<Item = Value>) -> replay::Stream { | |
| use std::io::{Seek, Write}; | |
| let mut file = tempfile::tempfile().unwrap(); | |
| for row in rows { | |
| writeln!(file, "{row}").unwrap(); | |
| } | |
| file.rewind().unwrap(); | |
| replay::Stream::new(file, CancellationToken::new(), CancellationToken::new()) | |
| } | |
| fn update(update: Value) -> Value { | |
| json!({"method":"session/update","params":{"sessionId":"session","update":update}}) | |
| } | |
| #[tokio::test] | |
| async fn worker_progress_uses_acp_plan_and_active_tool() { | |
| let (sink, rows) = crate::owner::worker_progress::tests::worker(); | |
| let mut turn = Turn::new("session".into(), 4, true, true); | |
| for (event, expected) in [ | |
| ( | |
| json!({"sessionUpdate":"plan","entries":[{"status":"in_progress","content":"Run all tests","priority":"high"}]}), | |
| "Run all tests", | |
| ), | |
| ( | |
| json!({"sessionUpdate":"tool_call","toolCallId":"cmd","name":"run_command","status":"in_progress","title":"cargo test","rawInput":{"CommandLine":"cargo test","toolSummary":"Test agent"}}), | |
| "test", | |
| ), | |
| ( | |
| json!({"sessionUpdate":"tool_call_update","toolCallId":"cmd","status":"completed"}), | |
| "Run all tests", | |
| ), | |
| ] { | |
| turn.event(update(event), sink.as_ref()).await.unwrap(); | |
| assert_eq!(rows.borrow()["child"].detail, expected); | |
| } | |
| } | |
| #[tokio::test] | |
| async fn replays_only_the_bound_prompt_with_the_same_activity_as_live() { | |
| let prior = update(json!({"sessionUpdate":"agent_message_chunk", | |
| "content":{"type":"text","text":"prior instructions acknowledgement"}})); | |
| let setup_context = update(json!({"sessionUpdate":"usage_update","used":0,"size":10000})); | |
| let events = [ | |
| update(json!({"sessionUpdate":"usage_update","used":1200,"size":10000})), | |
| update( | |
| json!({"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"checking"}}), | |
| ), | |
| update( | |
| json!({"sessionUpdate":"tool_call","toolCallId":"host","name":"mcp_maka_ModelList", | |
| "status":"in_progress","title":"Run ModelList"}), | |
| ), | |
| update( | |
| json!({"sessionUpdate":"tool_call_update","toolCallId":"host","status":"completed"}), | |
| ), | |
| update( | |
| json!({"sessionUpdate":"tool_call","toolCallId":"shell","name":"run_command", | |
| "status":"in_progress","title":"false","rawInput":{"CommandLine":"false","toolSummary":"Check status"}}), | |
| ), | |
| update( | |
| json!({"sessionUpdate":"tool_call_update","toolCallId":"shell","name":"run_command", | |
| "status":"completed","rawOutput":{"exit_code":1,"output":"Command exited with code 1.\n\nCommand output:\nfailed"}}), | |
| ), | |
| update( | |
| json!({"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"Result: "}}), | |
| ), | |
| update( | |
| json!({"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"failed."}}), | |
| ), | |
| json!({"id":4,"result":{"stopReason":"end_turn","usage":{"cachedReadTokens":50,"totalTokens":70}}}), | |
| ]; | |
| let live = Sink::default(); | |
| let mut turn = Turn::new("session".into(), 4, true, true); | |
| turn.model = Some("test".into()); | |
| turn.event(setup_context.clone(), &live).await.unwrap(); | |
| let mut terminal = None; | |
| for event in &events { | |
| terminal = turn.event(event.clone(), &live).await.unwrap(); | |
| } | |
| let replayed = Sink::default(); | |
| let outcome = replay( | |
| true, | |
| true, | |
| "session", | |
| 4, | |
| &mut spool([ | |
| json!({"id":1,"method":"initialize"}), | |
| json!({"id":2,"method":"session/resume","params":{"sessionId":"session"}}), | |
| json!({"id":3,"method":"session/prompt","params":{"sessionId":"session","prompt":[{"type":"text","text":"instructions"}]}}), | |
| json!({"id":4,"method":"session/prompt","params":{"sessionId":"session","prompt":[{"type":"text","text":"task"}]}}), | |
| json!({"id":5,"method":"session/close","params":{"sessionId":"session"}}), | |
| ]), | |
| &mut spool([json!({"id":2,"result":{"models":{"currentModelId":"test"}}}),prior,setup_context, json!({"id":3,"result":{"stopReason":"end_turn"}})].into_iter().chain(events)), | |
| &replayed, | |
| ) | |
| .await | |
| .unwrap(); | |
| assert!(replay::same_outcome(&terminal.unwrap(), &outcome)); | |
| let observations = live.0.into_inner().unwrap(); | |
| assert_eq!(observations, replayed.0.into_inner().unwrap()); | |
| assert!(matches!(&observations[..], [ | |
| Output::ContextUsage(initial), | |
| Output::ContextUsage(current), | |
| Output::MessageStart { .. }, | |
| Output::ThinkingDelta { text: thought, .. }, | |
| Output::MessageEnd { .. }, | |
| Output::ToolStart { input, .. }, | |
| Output::ToolResult { is_error: true, text: error, details: Some(ToolResultDetails { exit_code: Some(1), .. }), .. }, | |
| Output::MessageStart { .. }, | |
| Output::OutputDelta { text: first, .. }, | |
| Output::OutputDelta { text: second, .. }, | |
| Output::MessageEnd { .. }, | |
| Output::TurnUsage { usage: TurnUsage { tokens: ModelUsage { cache_read_tokens: Some(50), .. }, .. } }, | |
| ] if initial.used == 0 && current.used == 1200 && current.model.as_deref() == Some("test") && thought == "checking" && input["toolSummary"] == "Check status" && error == "failed" && first == "Result: " && second == "failed.")); | |
| } | |
| #[test] | |
| fn system_prompt_append_includes_host_guidance_on_new_and_resumed_sessions() { | |
| assert!(supports_system_prompt_append(&json!({ | |
| "agentCapabilities": { "_meta": { "antigravity": { "systemPrompt": { "append": true } } } } | |
| }))); | |
| assert!(!supports_system_prompt_append(&json!({ | |
| "agentCapabilities": { "mcpCapabilities": { "http": true } } | |
| }))); | |
| for (native_session, expected_method, had_user_block) in [ | |
| (None, "session/new", false), | |
| (Some("s1"), "session/resume", true), | |
| ] { | |
| for user in [None, Some(""), Some(" \t"), Some("Be concise.")] { | |
| let instructions = turn_instructions(user); | |
| let append = system_prompt_text(&instructions, had_user_block); | |
| let (method, params) = open_params( | |
| "/ws", | |
| "http://127.0.0.1:1/mcp", | |
| "tok", | |
| native_session, | |
| Some(&append), | |
| ); | |
| assert_eq!(method, expected_method); | |
| assert_eq!(params["sessionId"].as_str(), native_session); | |
| assert_eq!(params["cwd"], "/ws"); | |
| let text = params["_meta"]["antigravity"]["systemPrompt"]["append"] | |
| .as_str() | |
| .unwrap(); | |
| assert_eq!( | |
| text.contains("replace all earlier Maka instruction blocks"), | |
| had_user_block | |
| ); | |
| assert!(text.contains("mcp_maka_exec")); | |
| assert!( | |
| text.contains("Maka shuts down this agy process tree at the end of each turn.") | |
| ); | |
| assert_eq!( | |
| text.ends_with("\n\nBe concise."), | |
| user == Some("Be concise.") | |
| ); | |
| } | |
| } | |
| } | |
| #[test] | |
| fn fallback_prompt_includes_host_guidance_before_the_task() { | |
| let (_, opened) = open_params("/ws", "http://127.0.0.1:1/mcp", "tok", None, None); | |
| assert_eq!(opened.pointer("/_meta/antigravity/systemPrompt"), None); | |
| let task = json!({"type":"text","text":"Run the tests"}); | |
| for user in [None, Some(""), Some(" \t"), Some("Be concise.")] { | |
| let instructions = turn_instructions(user); | |
| let update = journal::instruction_text(Some(&instructions)); | |
| let prompt = prompt_params("s1", vec![task.clone()], Some(&update)); | |
| let [block, user_block] = prompt["prompt"].as_array().unwrap().as_slice() else { | |
| panic!("expected an instructions block followed by the task"); | |
| }; | |
| assert_eq!(block["type"], "text"); | |
| let text = block["text"].as_str().unwrap(); | |
| assert!(text.starts_with("<maka_system_instructions>\n")); | |
| assert!(text.contains("replace all earlier Maka instruction blocks")); | |
| assert!(text.contains("mcp_maka_exec")); | |
| assert!( | |
| text.contains("Maka shuts down this agy process tree at the end of each turn.") | |
| ); | |
| assert_eq!( | |
| text.contains("\n\nBe concise.\n"), | |
| user == Some("Be concise.") | |
| ); | |
| assert_eq!(user_block, &task); | |
| } | |
| } | |
| #[tokio::test] | |
| async fn session_info_update_matches_between_live_and_replay_including_setup() { | |
| let setup_title = | |
| update(json!({"sessionUpdate":"session_info_update","title":"Setup ACP Title"})); | |
| let events = [ | |
| update( | |
| json!({"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"Done"}}), | |
| ), | |
| update(json!({"sessionUpdate":"session_info_update","title":"Setup ACP Title"})), | |
| update(json!({"sessionUpdate":"session_info_update","title":"Fixing ACP Title Sync"})), | |
| json!({"id":3,"result":{"stopReason":"end_turn"}}), | |
| ]; | |
| let live = Sink::default(); | |
| let mut turn = Turn::new("session".into(), 3, true, true); | |
| turn.event(setup_title.clone(), &live).await.unwrap(); | |
| let mut terminal = None; | |
| for event in &events { | |
| terminal = turn.event(event.clone(), &live).await.unwrap(); | |
| } | |
| let requests = [ | |
| json!({"id":1,"method":"initialize"}), | |
| json!({"id":2,"method":"session/resume","params":{"sessionId":"session"}}), | |
| json!({"id":3,"method":"session/prompt","params":{"sessionId":"session","prompt":[{"type":"text","text":"task"}]}}), | |
| ]; | |
| let setup_events = [ | |
| setup_title, | |
| update(json!({"sessionUpdate":"session_info_update","title":null})), | |
| json!({"id":2,"result":{"sessionId":"session"}}), | |
| ]; | |
| let replayed = Sink::default(); | |
| let outcome = replay( | |
| true, | |
| true, | |
| "session", | |
| 3, | |
| &mut spool(requests.clone()), | |
| &mut spool(setup_events.iter().cloned().chain(events.iter().cloned())), | |
| &replayed, | |
| ) | |
| .await | |
| .unwrap(); | |
| assert!(replay::same_outcome(&terminal.unwrap(), &outcome)); | |
| let observations = live.0.into_inner().unwrap(); | |
| assert_eq!(observations, replayed.0.into_inner().unwrap()); | |
| let titles: Vec<_> = observations | |
| .iter() | |
| .filter_map(|o| match o { | |
| Output::SessionTitle { title } => Some(title.as_str()), | |
| _ => None, | |
| }) | |
| .collect(); | |
| assert_eq!(titles, vec!["Setup ACP Title", "Fixing ACP Title Sync"]); | |
| // Pre-SESSION_TITLE_VERSION spools must omit SessionTitle so prefix hashes match. | |
| let legacy = Sink::default(); | |
| let legacy_outcome = replay( | |
| true, | |
| false, | |
| "session", | |
| 3, | |
| &mut spool(requests), | |
| &mut spool(setup_events.into_iter().chain(events)), | |
| &legacy, | |
| ) | |
| .await | |
| .unwrap(); | |
| assert!(replay::same_outcome(&outcome, &legacy_outcome)); | |
| assert!( | |
| !legacy | |
| .0 | |
| .into_inner() | |
| .unwrap() | |
| .iter() | |
| .any(|o| matches!(o, Output::SessionTitle { .. })) | |
| ); | |
| } | |
| } |