Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(cursor): surface walkthrough artifacts as ordinary ACP text (#6435)
Wolf Mermelsteineeb529dfd22d
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.jsonindex e10f3c7fe6..d2aecade59 100644--- a/.github/workspace-dep-closures.json+++ b/.github/workspace-dep-closures.json@@ -227,6 +227,7 @@"crates/models_pagination","crates/models_permissions","crates/models_properties",+ "crates/models_sfs","crates/models_team","crates/non_empty","crates/notification",@@ -239,6 +240,7 @@"crates/secretsmanager_client","crates/share_permission_db_utils","crates/sqs_worker",+ "crates/static_file_service_client","crates/sync_service","crates/sync_service_client","crates/system_properties",@@ -358,6 +360,7 @@"crates/models_properties","crates/models_search","crates/models_search_cursor",+ "crates/models_sfs","crates/models_soup","crates/models_team","crates/non_empty",@@ -382,6 +385,7 @@"crates/soup","crates/sqs_client","crates/sqs_worker",+ "crates/static_file_service_client","crates/sync_service","crates/sync_service_client","crates/system_properties",@@ -1222,6 +1226,7 @@"crates/models_pagination","crates/models_permissions","crates/models_properties",+ "crates/models_sfs","crates/models_team","crates/native_app_service","crates/non_empty",@@ -1240,6 +1245,7 @@"crates/share_permission_db_utils","crates/sqs_client","crates/sqs_worker",+ "crates/static_file_service_client","crates/sync_service","crates/sync_service_client","crates/system_properties",@@ -2639,6 +2645,7 @@"crates/last_online_tracker","crates/macro_auth","crates/macro_authorization",+ "crates/macro_aws_config","crates/macro_entrypoint","crates/macro_env","crates/macro_env_var",@@ -2660,6 +2667,7 @@"crates/models_entity_access_management","crates/models_pagination","crates/models_permissions",+ "crates/models_sfs","crates/non_empty","crates/notification","crates/notification_state",@@ -2668,6 +2676,7 @@"crates/remote_env_var","crates/share_permission_db_utils","crates/sqs_worker",+ "crates/static_file_service_client","crates/workspace-hack"],"database_env_vars": [@@ -8333,6 +8342,8 @@"services/static_file_service"],"static_file_service_client": [+ "crates/macro_aws_config",+ "crates/macro_env_var","crates/models_sfs","crates/static_file_service_client","crates/workspace-hack"diff --git a/Cargo.lock b/Cargo.lockindex 662a987643..f98728af59 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -364,6 +364,7 @@ dependencies = ["serde","serde_json","sqlx",+ "static_file_service_client","tokio","tokio-retry","tokio-util",@@ -4642,6 +4643,7 @@ dependencies = ["agent_fold","agent_runtime_protocol","agent_session",+ "bytes","futures","insta","macro_env_var",@@ -4651,11 +4653,13 @@ dependencies = ["serde_json","sqlx","sse-core",+ "static_file_service_client","thiserror 2.0.18","tokio","tokio-util","tracing","tracing-subscriber",+ "urlencoding","uuid","workspace-hack","zeroize",@@ -16176,6 +16180,7 @@ version = "0.1.0"dependencies = ["anyhow","bytes",+ "macro_aws_config","macro_service_urls","models_sfs","reqwest 0.13.4",diff --git a/crates/agent_harness/src/outbound/cursor/manager.rs b/crates/agent_harness/src/outbound/cursor/manager.rsindex 633b9bc997..e79f466d72 100644--- a/crates/agent_harness/src/outbound/cursor/manager.rs+++ b/crates/agent_harness/src/outbound/cursor/manager.rs@@ -25,11 +25,14 @@ use agent_client_protocol::schema::v1::SessionId;use agent_session::domain::model::{AgentSession, AgentSessionId, ExternalSession, ReplicaId};use agent_session::domain::ports::{AgentSessionRepo, ExternalSessionRepo};use cursor_cloud_agents::api::{ApiKey, CursorClient, CursorConfig};+use cursor_cloud_agents::domain::artifact::{ArtifactListing, FetchedArtifact};use cursor_cloud_agents::domain::model::RepoUrl as CursorRepoUrl;use cursor_cloud_agents::domain::model::{CursorAgentId, CursorModel, CursorRunId, McpServer, ModelChoice,};-use cursor_cloud_agents::domain::ports::{CursorAgents, RunStream};+use cursor_cloud_agents::domain::ports::{+ ArtifactStore, CursorAgents, CursorArtifacts, NoArtifactStore, RunStream,+};use cursor_cloud_agents::domain::service::CursorSessionService;use cursor_cloud_agents::inbound::acp::{AcpNotifier, serve};use futures::Stream;@@ -115,8 +118,11 @@ fn interval_from_now(every: std::time::Duration) -> tokio::time::Interval {/// [`HaikuRepositoryChooser`] built in [`Self::serve_session`] answers. The/// manager holds only what building one takes.#[derive(Clone)]-pub struct CursorContainerManager<Sessions, Keys, Repositories> {+pub struct CursorContainerManager<Sessions, Keys, Repositories, Store> {keys: Keys,+ /// Where a session's walkthrough artifacts are re-hosted, handed to every+ /// session this manager serves.+ artifacts: Store,base_url: String,sessions: Sessions,repositories: Arc<Repositories>,@@ -167,13 +173,17 @@ struct RestoredCursorSession {last_run: Option<CursorRunId>,}-impl<Sessions, Keys, Repositories> CursorContainerManager<Sessions, Keys, Repositories>+impl<Sessions, Keys, Repositories>+ CursorContainerManager<Sessions, Keys, Repositories, NoArtifactStore>whereSessions: AgentSessionRepo + ExternalSessionRepo + Clone,Keys: CursorApiKeys,Repositories: ReachableRepositories,{/// Build a manager with required durable journal storage and replica identity.+ ///+ /// Sessions it serves re-host no artifacts until one is given to+ /// [`Self::with_artifact_store`].pub fn new(keys: Keys,base_url: String,@@ -185,6 +195,7 @@ where) -> Self {Self {keys,+ artifacts: NoArtifactStore,base_url,sessions,repositories,@@ -198,15 +209,49 @@ where}}+ /// Re-host every session's walkthrough artifacts through `artifacts`.+ ///+ /// Changes the manager's store type rather than taking an option, so a+ /// deployment without a static file service cannot accidentally be+ /// handed one that fails per file.+ #[must_use]+ pub fn with_artifact_store<Store>(+ self,+ artifacts: Store,+ ) -> CursorContainerManager<Sessions, Keys, Repositories, Store> {+ CursorContainerManager {+ keys: self.keys,+ artifacts,+ base_url: self.base_url,+ sessions: self.sessions,+ repositories: self.repositories,+ usage: self.usage,+ pull_requests: self.pull_requests,+ journal_storage: self.journal_storage,+ pending: self.pending,+ }+ }+}++impl<Sessions, Keys, Repositories, Store>+ CursorContainerManager<Sessions, Keys, Repositories, Store>+where+ Sessions: AgentSessionRepo + ExternalSessionRepo + Clone,+ Keys: CursorApiKeys,+ Repositories: ReachableRepositories,+ Store: ArtifactStore + Clone + 'static,+{#[cfg(test)]fn with_memory_journal(keys: Keys,base_url: String,sessions: Sessions,repositories: Arc<Repositories>,+ artifacts: Store,) -> Self {Self {keys,+ artifacts,base_url,sessions,repositories,@@ -331,8 +376,14 @@ wheresession_id,);let service = Arc::new(- CursorSessionService::new(cursor, notifier.clone(), chooser, journal)- .with_default_model(default_model_id),+ CursorSessionService::new(+ cursor,+ notifier.clone(),+ chooser,+ journal,+ self.artifacts.clone(),+ )+ .with_default_model(default_model_id),);if let Some(restored) = restore {service.restore_session_with_watermark(@@ -457,12 +508,13 @@ where}}-impl<Sessions, Keys, Repositories> ContainerManager- for CursorContainerManager<Sessions, Keys, Repositories>+impl<Sessions, Keys, Repositories, Store> ContainerManager+ for CursorContainerManager<Sessions, Keys, Repositories, Store>whereSessions: AgentSessionRepo + ExternalSessionRepo + Clone,Keys: CursorApiKeys,Repositories: ReachableRepositories,+ Store: ArtifactStore + Clone + 'static,{type Transport = PipeTransport;@@ -704,6 +756,26 @@ where}}+impl<Sessions> CursorArtifacts for RecordingCursor<Sessions>+where+ Sessions: ExternalSessionRepo + Clone,+{+ async fn list_artifacts(+ &self,+ agent: &CursorAgentId,+ ) -> std::result::Result<Vec<ArtifactListing>, rootcause::Report> {+ CursorArtifacts::list_artifacts(&self.client, agent).await+ }++ async fn fetch_artifact(+ &self,+ agent: &CursorAgentId,+ path: &str,+ ) -> std::result::Result<FetchedArtifact, rootcause::Report> {+ CursorArtifacts::fetch_artifact(&self.client, agent, path).await+ }+}+impl<Sessions> RunStream for RecordingCursor<Sessions>whereSessions: ExternalSessionRepo + Clone,diff --git a/crates/agent_harness/src/outbound/cursor/manager/test.rs b/crates/agent_harness/src/outbound/cursor/manager/test.rsindex acff87e6d5..afe5e3bbf7 100644--- a/crates/agent_harness/src/outbound/cursor/manager/test.rs+++ b/crates/agent_harness/src/outbound/cursor/manager/test.rs@@ -14,6 +14,7 @@ use agent_session::domain::model::{};use bot_id::BotId;use cursor_api_key::cipher::CursorApiKey;+use cursor_cloud_agents::domain::ports::NoArtifactStore;use macro_user_id::user_id::MacroUserIdStr;use std::collections::HashMap;use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};@@ -413,7 +414,7 @@ impl ReachableRepositories for NoRepositories {fn manager(base_url: String,sessions: StubSessions,-) -> CursorContainerManager<StubSessions, StubKeys, NoRepositories> {+) -> CursorContainerManager<StubSessions, StubKeys, NoRepositories, NoArtifactStore> {manager_with_keys(base_url, sessions, StubKeys::connected())}@@ -421,8 +422,14 @@ fn manager_with_keys(base_url: String,sessions: StubSessions,keys: StubKeys,-) -> CursorContainerManager<StubSessions, StubKeys, NoRepositories> {- CursorContainerManager::with_memory_journal(keys, base_url, sessions, Arc::new(NoRepositories))+) -> CursorContainerManager<StubSessions, StubKeys, NoRepositories, NoArtifactStore> {+ CursorContainerManager::with_memory_journal(+ keys,+ base_url,+ sessions,+ Arc::new(NoRepositories),+ NoArtifactStore,+ )}async fn next_acp(diff --git a/crates/cursor_cloud_agents/Cargo.toml b/crates/cursor_cloud_agents/Cargo.tomlindex 9c82c9daaa..c06aa6a644 100644--- a/crates/cursor_cloud_agents/Cargo.toml+++ b/crates/cursor_cloud_agents/Cargo.toml@@ -15,11 +15,14 @@ test-utils = []name = "cursor_cloud_agents"[dependencies]+urlencoding = { workspace = true }agent_session = { path = "../agent_session", optional = true }agent_runtime_protocol = { path = "../agent_runtime_protocol", default-features = false }sqlx = { workspace = true }uuid = { workspace = true }agent-client-protocol = { workspace = true }+bytes = { workspace = true }+static_file_service_client = { path = "../static_file_service_client" }futures = { workspace = true }macro_env_var = { path = "../macro_env_var" }# `stream` on top of the workspace features: the run stream is consumed asdiff --git a/crates/cursor_cloud_agents/src/api.rs b/crates/cursor_cloud_agents/src/api.rsindex 33c82dfecd..3ea87dd03d 100644--- a/crates/cursor_cloud_agents/src/api.rs+++ b/crates/cursor_cloud_agents/src/api.rs@@ -22,16 +22,19 @@ pub mod wire;use crate::api::record::SseRecording;use crate::api::wire::{- AgentSummary, ArchiveAgentResponse, ConversationResponse, CreateAgentRequest,- CreateAgentResponse, CreateRunRequest, CreateRunResponse, ListAgentsResponse,- ListModelsResponse, ListRunsResponse, McpServerSelection, MeResponse, ModelSelection,- PromptBody, RepoSelection,+ AgentSummary, ArchiveAgentResponse, ArtifactDownloadResponse, ConversationResponse,+ CreateAgentRequest, CreateAgentResponse, CreateRunRequest, CreateRunResponse,+ ListAgentsResponse, ListArtifactsResponse, ListModelsResponse, ListRunsResponse,+ McpServerSelection, MeResponse, ModelSelection, PromptBody, RepoSelection,};+use crate::domain::artifact::{ArtifactListing, FetchedArtifact};use crate::domain::model::{ConversationLine, ConversationSpeaker, CursorAgentId, CursorModel, CursorRunId, McpServer,ModelChoice, ModelParam, ModelVariant, RepoUrl, RunListing,};-use crate::domain::ports::{ConnectedStream, CursorAgents, RunStream, StreamConnectError};+use crate::domain::ports::{+ ConnectedStream, CursorAgents, CursorArtifacts, RunStream, StreamConnectError,+};use futures::{Stream, StreamExt as _};use sse_core::SseEvent;use std::collections::VecDeque;@@ -63,6 +66,24 @@ pub(crate) const MAX_SSE_PAYLOAD: NonZeroUsize = match NonZeroUsize::new(16 * 10/// choose between.pub const CURSOR_API_BASE_URL: &str = "https://api.cursor.com";+macro_env_var::maybe_env_vars! {+ /// Overrides [`CURSOR_API_BASE_URL`] when set. Only a local stack sets+ /// it, to point every Cursor call at a stand-in server; deployed+ /// environments leave it unset and talk to Cursor.+ pub struct CursorApiBaseUrl;+}++/// The Cursor API base url this process should call: the+/// `CURSOR_API_BASE_URL` override when set, else the one real+/// [`CURSOR_API_BASE_URL`].+#[must_use]+pub fn cursor_api_base_url() -> String {+ CursorApiBaseUrl::new()+ .map(|url| url.trim_end_matches('/').to_owned())+ .filter(|url| !url.is_empty())+ .unwrap_or_else(|| CURSOR_API_BASE_URL.to_owned())+}+/// A Cursor API key that never prints itself and does not outlive its client.////// The key used to be a bare `String` in a `Debug`-deriving config, so a@@ -343,6 +364,75 @@ impl CursorClient {Ok(())}+ /// List the files an agent has written to its `artifacts/` directory —+ /// the screenshots and screen recordings a walkthrough produces.+ ///+ /// The listing is agent-scoped and cumulative: artifacts survive their+ /// run, and Cursor offers no run filter, so every turn sees everything+ /// every earlier turn wrote. A caller that wants "new since last turn"+ /// has to diff `path` plus `updated_at` against what it saw before —+ /// `path` alone is not enough, because an agent that reshoots a+ /// screenshot writes the same path again.+ #[tracing::instrument(skip(self), err)]+ pub async fn list_artifacts(+ &self,+ agent: &CursorAgentId,+ ) -> Result<ListArtifactsResponse, rootcause::Report> {+ self.get_json(&format!("/v1/agents/{agent}/artifacts"))+ .await+ }++ /// Ask for a presigned url to one artifact's bytes.+ ///+ /// `path` is a [`wire::ArtifactListing::path`] exactly as the listing gave it;+ /// Cursor requires it to be under `artifacts/` and rejects anything else.+ /// The url it answers with is good for fifteen minutes, so it is worth+ /// requesting when a caller is ready to fetch and not worth storing.+ #[tracing::instrument(skip(self), err)]+ pub async fn artifact_download_url(+ &self,+ agent: &CursorAgentId,+ path: &str,+ ) -> Result<ArtifactDownloadResponse, rootcause::Report> {+ self.get_json(&format!(+ "/v1/agents/{agent}/artifacts/download?path={}",+ urlencoding::encode(path)+ ))+ .await+ }++ /// Fetch an artifact's bytes from the presigned url+ /// [`Self::artifact_download_url`] handed back.+ ///+ /// Its own method rather than another `get_*` because everything about+ /// the request differs from a Cursor API call: the url is S3's, not this+ /// client's base url; its credentials are already in its query string, so+ /// the Cursor key must *not* be attached — sending a live API key to a+ /// third-party host is a credential leak, not a harmless extra header —+ /// and it stops working fifteen minutes after it was minted.+ ///+ /// The response is returned unread. Artifact videos run to tens of+ /// megabytes, so the caller decides whether to stream the body somewhere+ /// or buffer it; this method will not buffer it for them.+ #[tracing::instrument(skip(self, url), err)]+ pub async fn fetch_artifact(&self, url: &str) -> Result<reqwest::Response, rootcause::Report> {+ let response = self+ .http+ .get(url)+ .send()+ .await+ .map_err(|error| rootcause::report!(error))?;+ let status = response.status();+ if !status.is_success() {+ // S3 answers a stale or malformed presigned url with an XML body+ // naming the reason, which is the only diagnostic there is — the+ // same bargain `get_json` makes with Cursor's error bodies.+ let text = response.text().await.unwrap_or_default();+ return Err(rootcause::report!("artifact fetch -> {status}: {text}"));+ }+ Ok(response)+ }+/// Identify the configured API key. The cheap call that proves the key is/// live, for a boot-time health check.#[tracing::instrument(skip(self), err)]@@ -569,6 +659,51 @@ impl CursorAgents for CursorClient {}}+impl CursorArtifacts for CursorClient {+ #[tracing::instrument(skip(self), err)]+ async fn list_artifacts(+ &self,+ agent: &CursorAgentId,+ ) -> Result<Vec<ArtifactListing>, rootcause::Report> {+ let reply = CursorClient::list_artifacts(self, agent).await?;+ Ok(reply+ .items+ .into_iter()+ .map(|listing| ArtifactListing {+ path: listing.path,+ size_bytes: listing.size_bytes,+ updated_at: listing.updated_at,+ })+ .collect())+ }++ #[tracing::instrument(skip(self), err)]+ async fn fetch_artifact(+ &self,+ agent: &CursorAgentId,+ path: &str,+ ) -> Result<FetchedArtifact, rootcause::Report> {+ // Minted and spent inside this method: the url carries credentials in+ // its query string and stops working in fifteen minutes, so it is+ // never returned, logged, or stored.+ let download = self.artifact_download_url(agent, path).await?;+ let response = CursorClient::fetch_artifact(self, &download.url).await?;+ let content_type = response+ .headers()+ .get(reqwest::header::CONTENT_TYPE)+ .and_then(|value| value.to_str().ok())+ .map(str::to_owned);+ let bytes = response+ .bytes()+ .await+ .map_err(|error| rootcause::report!(error))?;+ Ok(FetchedArtifact {+ content_type,+ bytes,+ })+ }+}+/// How many times a run's stream is connected before an unavailable stream/// is the turn's failure.const STREAM_CONNECT_ATTEMPTS: usize = 5;diff --git a/crates/cursor_cloud_agents/src/api/test.rs b/crates/cursor_cloud_agents/src/api/test.rsindex adbc9d891b..23e99cc391 100644--- a/crates/cursor_cloud_agents/src/api/test.rs+++ b/crates/cursor_cloud_agents/src/api/test.rs@@ -70,6 +70,18 @@ fn a_placeholder_key_is_rejected_with_a_diagnostic() {/// status and body, then closes. Enough to exercise how a create-agent/// failure is classified without a mock-HTTP dependency.fn stand_in_server(status_line: &str, body: &'static str) -> String {+ stand_in_server_capturing(status_line, body).0+}++/// [`stand_in_server`] that also hands back the request it was sent, for the+/// tests that are about what went out rather than what came back — a+/// percent-encoded query string, or an `Authorization` header that must not+/// be there at all.+fn stand_in_server_capturing(+ status_line: &str,+ body: &'static str,+) -> (String, std::sync::mpsc::Receiver<String>) {+ let (sender, receiver) = std::sync::mpsc::channel();let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("a loopback port");let base_url = format!("http://{}", listener.local_addr().expect("a bound address"));let response = format!(@@ -107,10 +119,11 @@ fn stand_in_server(status_line: &str, body: &'static str) -> String {Ok(read) => remaining = remaining.saturating_sub(read),}}+ let _ = sender.send(String::from_utf8_lossy(&request).into_owned());let _ = socket.write_all(response.as_bytes());let _ = socket.flush();});- base_url+ (base_url, receiver)}fn client_against(base_url: String) -> CursorClient {@@ -176,3 +189,107 @@ async fn an_unrelated_client_error_is_still_a_plain_rejection() {rejected.0);}++fn agent() -> CursorAgentId {+ CursorAgentId::new("bc-00000000-0000-0000-0000-000000000001".to_owned())+}++/// The documented listing body reads, and an extra field Cursor may add+/// later does not break it.+#[tokio::test]+async fn artifact_listings_read_the_documented_body() {+ let base_url = stand_in_server(+ "200 OK",+ r#"{"items":[{"path":"artifacts/mobile_selection_menu_format_option.png","sizeBytes":12345,"updatedAt":"2026-04-13T18:45:00.000Z","contentType":"image/png"}]}"#,+ );+ let listing = client_against(base_url)+ .list_artifacts(&agent())+ .await+ .expect("the documented body parses");+ assert_eq!(listing.items.len(), 1);+ assert_eq!(+ listing.items[0].path,+ "artifacts/mobile_selection_menu_format_option.png"+ );+ assert_eq!(listing.items[0].size_bytes, 12345);+ assert_eq!(listing.items[0].updated_at, "2026-04-13T18:45:00.000Z");+}++/// An agent that has written nothing is the ordinary case for most sessions,+/// so an empty list must be a clean empty answer, not a parse failure.+#[tokio::test]+async fn an_agent_with_no_artifacts_lists_nothing() {+ let base_url = stand_in_server("200 OK", r#"{"items":[]}"#);+ let listing = client_against(base_url)+ .list_artifacts(&agent())+ .await+ .expect("an empty page parses");+ assert!(listing.items.is_empty());+}++/// The artifact path travels as a percent-encoded query parameter. Spelled+/// into the path by hand, a name with a space or a `#` would arrive+/// truncated or as a different file.+#[tokio::test]+async fn the_download_request_percent_encodes_the_artifact_path() {+ let (base_url, requests) = stand_in_server_capturing(+ "200 OK",+ r#"{"url":"https://cloud-agent-artifacts.s3.us-east-1.amazonaws.com/x?sig=1","expiresAt":"2026-04-13T19:00:00.000Z"}"#,+ );+ let download = client_against(base_url)+ .artifact_download_url(&agent(), "artifacts/walkthrough one.mp4")+ .await+ .expect("the documented body parses");+ assert!(+ download+ .url+ .starts_with("https://cloud-agent-artifacts.s3."),+ "got {}",+ download.url+ );+ assert_eq!(download.expires_at, "2026-04-13T19:00:00.000Z");++ let request = requests.recv().expect("the stand-in saw the request");+ let request_line = request.lines().next().expect("a request line");+ assert!(+ request_line.contains("path=artifacts%2Fwalkthrough%20one.mp4"),+ "got {request_line}"+ );+}++/// The presigned url authenticates itself in its query string, and it points+/// at S3 rather than Cursor. Attaching our API key to it would hand a live+/// credential to a third-party host.+#[tokio::test]+async fn fetching_an_artifact_sends_no_api_key() {+ let (base_url, requests) = stand_in_server_capturing("200 OK", "bytes");+ let response = client_against(config().base_url)+ .fetch_artifact(&format!("{base_url}/artifacts/screenshot.png?sig=1"))+ .await+ .expect("the stand-in serves the bytes");+ assert!(response.status().is_success());++ let request = requests.recv().expect("the stand-in saw the request");+ assert!(+ !request.to_lowercase().contains("authorization:"),+ "the presigned fetch must be unauthenticated: {request}"+ );+}++/// A presigned url outlives its usefulness after fifteen minutes, and S3+/// answers a stale one with a 403. The status has to survive into the report,+/// since that is what tells an expiry apart from a genuinely missing file.+#[tokio::test]+async fn an_expired_presigned_url_fails_with_its_status() {+ let (base_url, _requests) = stand_in_server_capturing(+ "403 Forbidden",+ "<Error><Code>AccessDenied</Code><Message>Request has expired</Message></Error>",+ );+ let error = client_against(config().base_url)+ .fetch_artifact(&format!("{base_url}/artifacts/screenshot.png?sig=stale"))+ .await+ .expect_err("a 403 is not bytes");+ let printed = format!("{error}");+ assert!(printed.contains("403"), "got {printed}");+ assert!(printed.contains("Request has expired"), "got {printed}");+}diff --git a/crates/cursor_cloud_agents/src/api/wire.rs b/crates/cursor_cloud_agents/src/api/wire.rsindex 9ce7f477ee..263125827d 100644--- a/crates/cursor_cloud_agents/src/api/wire.rs+++ b/crates/cursor_cloud_agents/src/api/wire.rs@@ -355,3 +355,55 @@ pub struct ApiErrorCode {/// Cursor's error code, e.g. `repository_access`.pub code: String,}++/// `GET /v1/agents/{id}/artifacts` response.+///+/// The listing is the agent's whole artifact directory, not one run's output:+/// artifacts persist across runs and Cursor offers no run filter, so `items`+/// on a later turn still contains everything earlier turns wrote.+#[derive(Debug, Deserialize)]+pub struct ListArtifactsResponse {+ /// Every artifact the agent has written so far. Defaulted so a bare `{}`+ /// for an agent that has written none reads as empty; the docs show only+ /// the populated shape, so this is a guard, not an observed answer.+ #[serde(default)]+ pub items: Vec<ArtifactListing>,+}++/// One artifact in a `GET /v1/agents/{id}/artifacts` page.+#[derive(Debug, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct ArtifactListing {+ /// Workspace-relative path, always under `artifacts/`, e.g.+ /// `artifacts/screenshot.png`. This is both the artifact's identity and+ /// the value the download endpoint takes.+ pub path: String,+ /// Size in bytes. Videos run to tens of megabytes, so a caller deciding+ /// whether to fetch something has this before it commits to the body.+ #[serde(default)]+ pub size_bytes: u64,+ /// When Cursor last wrote the artifact, as the RFC 3339 string it sends.+ ///+ /// Kept as text because nothing in this crate reads a Cursor timestamp as+ /// a moment in time — parsing one here would mean adding a date library+ /// to serve a field that is currently only compared for equality, which is+ /// exactly what a change detector needs it for.+ #[serde(default)]+ pub updated_at: String,+}++/// `GET /v1/agents/{id}/artifacts/download` response.+#[derive(Debug, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct ArtifactDownloadResponse {+ /// A presigned S3 GET url. It carries its own credentials in the query+ /// string, so it must be fetched without this crate's API key.+ pub url: String,+ /// When the presigned url stops working, as the RFC 3339 string Cursor+ /// sends. Text for the same reason as [`ArtifactListing::updated_at`];+ /// the expiry that matters in practice is the documented 15 minutes,+ /// which a caller honours by fetching promptly rather than by storing+ /// the url.+ #[serde(default)]+ pub expires_at: String,+}diff --git a/crates/cursor_cloud_agents/src/api/wire/test.rs b/crates/cursor_cloud_agents/src/api/wire/test.rsindex e6cb7298e3..c1a038f6f6 100644--- a/crates/cursor_cloud_agents/src/api/wire/test.rs+++ b/crates/cursor_cloud_agents/src/api/wire/test.rs@@ -145,3 +145,35 @@ fn me_reads_user_and_service_account_shapes() {.expect("service-account key");assert!(service.user_email.is_none());}++/// Artifact fields arrive camel-cased, and an agent that has written none may+/// answer with a bare object rather than an empty `items` array.+#[test]+fn artifact_listings_read_camel_case_and_an_absent_items_key() {+ let listing: ListArtifactsResponse = serde_json::from_value(serde_json::json!({+ "items": [{+ "path": "artifacts/mobile_selection_menu_formatting_walkthrough.mp4",+ "sizeBytes": 48_500_000_u64,+ "updatedAt": "2026-04-13T18:45:00.000Z",+ }],+ }))+ .expect("a documented listing");+ assert_eq!(listing.items[0].size_bytes, 48_500_000);+ assert_eq!(listing.items[0].updated_at, "2026-04-13T18:45:00.000Z");++ let empty: ListArtifactsResponse =+ serde_json::from_value(serde_json::json!({})).expect("no artifacts yet");+ assert!(empty.items.is_empty());+}++/// The download body is the presigned url plus its expiry, both camel-cased.+#[test]+fn an_artifact_download_reads_the_documented_body() {+ let download: ArtifactDownloadResponse = serde_json::from_value(serde_json::json!({+ "url": "https://cloud-agent-artifacts.s3.us-east-1.amazonaws.com/a?sig=1",+ "expiresAt": "2026-04-13T19:00:00.000Z",+ }))+ .expect("a documented download");+ assert!(download.url.contains("cloud-agent-artifacts"));+ assert_eq!(download.expires_at, "2026-04-13T19:00:00.000Z");+}diff --git a/crates/cursor_cloud_agents/src/bin/cursor_cloud_agents.rs b/crates/cursor_cloud_agents/src/bin/cursor_cloud_agents.rsindex 0f81ebd279..c01a42b550 100644--- a/crates/cursor_cloud_agents/src/bin/cursor_cloud_agents.rs+++ b/crates/cursor_cloud_agents/src/bin/cursor_cloud_agents.rs@@ -142,6 +142,7 @@ async fn main() -> ExitCode {notifier.clone(),chooser,Arc::new(cursor_cloud_agents::outbound::memory_journal::MemoryJournal::default()),+ cursor_cloud_agents::domain::ports::NoArtifactStore,).with_default_model(configured_model),);diff --git a/crates/cursor_cloud_agents/src/domain/artifact.rs b/crates/cursor_cloud_agents/src/domain/artifact.rsnew file mode 100644index 0000000000..d0b1fb2076--- /dev/null+++ b/crates/cursor_cloud_agents/src/domain/artifact.rs@@ -0,0 +1,213 @@+//! Walkthrough artifacts: what Cursor wrote, what Macro re-hosted, and the+//! markdown that puts them in the conversation.+//!+//! Cursor's agents save screenshots and screen recordings to an agent-scoped+//! artifacts store that nothing in the ACP stream mentions. A turn that+//! produced any collects them, re-hosts them somewhere permanent, and says so+//! in ordinary assistant text — artifacts are not a new kind of update, they+//! are a paragraph of markdown like any other.++use serde::{Deserialize, Serialize};++/// One file in the agent's artifacts store, as Cursor lists it.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct ArtifactListing {+ /// Workspace-relative path, always under `artifacts/`.+ pub path: String,+ /// Size in bytes, so a caller can decline a body before fetching it.+ pub size_bytes: u64,+ /// When Cursor last wrote it, as the timestamp string it sent. Compared,+ /// never interpreted: an agent that reshoots a screenshot writes the same+ /// path again, so the pair is the artifact's identity.+ pub updated_at: String,+}++impl ArtifactListing {+ /// This version of this artifact, as the key a diff is kept in.+ #[must_use]+ pub fn key(&self) -> String {+ format!("{}@{}", self.path, self.updated_at)+ }++ /// The file name a reader sees, without the `artifacts/` prefix.+ #[must_use]+ pub fn name(&self) -> &str {+ self.path.rsplit('/').next().unwrap_or(&self.path)+ }+}++/// An artifact's bytes, with whatever the store said they were.+pub struct FetchedArtifact {+ /// The download's `Content-Type`, when it sent a usable one.+ pub content_type: Option<String>,+ /// The bytes themselves.+ pub bytes: bytes::Bytes,+}++/// One artifact this session re-hosted, durable in the journal.+///+/// The URI is the whole point: Cursor's own download links expire in fifteen+/// minutes, and a conversation outlives that by years.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct CollectedArtifact {+ /// `path@updated_at`, what later turns diff against.+ pub key: String,+ /// File name, as shown to the reader.+ pub name: String,+ /// The media type it was stored with.+ pub mime_type: String,+ /// Permanent URL the markdown points at.+ pub uri: String,+ /// Size in bytes, as Cursor listed it.+ pub size_bytes: u64,+}++/// Media types this crate infers from a file extension, when the download did+/// not say what it was serving.+const MIME_BY_EXTENSION: [(&str, &str); 14] = [+ ("png", "image/png"),+ ("jpg", "image/jpeg"),+ ("jpeg", "image/jpeg"),+ ("gif", "image/gif"),+ ("webp", "image/webp"),+ ("mp4", "video/mp4"),+ ("webm", "video/webm"),+ ("mov", "video/quicktime"),+ ("txt", "text/plain"),+ ("log", "text/plain"),+ ("json", "application/json"),+ ("md", "text/markdown"),+ ("pdf", "application/pdf"),+ ("svg", "image/svg+xml"),+];++/// What a store answers with when it is serving bytes it cannot identify.+const OPAQUE_MIME_TYPES: [&str; 2] = ["application/octet-stream", "binary/octet-stream"];++/// The media type to store `name` under.+///+/// The download's own header wins when it says anything specific. S3 serves+/// an object uploaded without a type as `binary/octet-stream`, which is true+/// and useless: it would render a screenshot as a file to download rather+/// than an image, so the extension decides instead.+#[must_use]+pub fn mime_type(name: &str, served: Option<&str>) -> String {+ let served = served+ .map(str::trim)+ .filter(|mime| !mime.is_empty())+ .filter(|mime| {+ let base = mime.split(';').next().unwrap_or(mime).trim();+ !OPAQUE_MIME_TYPES.contains(&base.to_ascii_lowercase().as_str())+ });+ if let Some(served) = served {+ return served.to_owned();+ }+ let extension = name.rsplit('.').next().unwrap_or_default().to_lowercase();+ MIME_BY_EXTENSION+ .iter()+ .find(|(candidate, _)| *candidate == extension)+ .map_or("application/octet-stream", |(_, mime)| mime)+ .to_owned()+}++/// The assistant text that presents `artifacts` to the reader.+///+/// A pure function of the collected list, because live delivery and a later+/// `session/load` replay both go through it and a session that renders+/// differently on reload is a bug the reader sees.+///+/// Images inline as markdown; videos use the editor's `<m-video>` block,+/// which is what Macro's document format renders a player from; everything+/// else is a link, which is the honest rendering of a file nobody can preview.+#[must_use]+pub fn artifact_markdown(artifacts: &[CollectedArtifact]) -> String {+ // A blank line before each entry: the first separates this from whatever+ // sentence the run's answer ended on, the rest make one paragraph per+ // file.+ let mut markdown = String::new();+ for artifact in artifacts {+ markdown.push_str("\n\n");+ markdown.push_str(&entry_markdown(artifact));+ }+ markdown+}++/// The `<m-video>` payload the Macro editor reads: a URL and how to read it.+#[derive(Serialize)]+#[serde(rename_all = "camelCase")]+struct VideoBlock<'a> {+ url: &'a str,+ src_type: &'a str,+}++fn entry_markdown(artifact: &CollectedArtifact) -> String {+ if artifact.mime_type.starts_with("image/") {+ return format!("", artifact.name, artifact.uri);+ }+ if artifact.mime_type.starts_with("video/") {+ // A serialized struct rather than `json!`, whose map orders its keys+ // by whichever features the build happened to unify; this text is+ // compared byte for byte against a replay of it.+ let video = serde_json::to_string(&VideoBlock {+ url: &artifact.uri,+ src_type: "url",+ })+ .unwrap_or_default();+ return format!("<m-video>{video}</m-video>");+ }+ format!("[{}]({})", artifact.name, artifact.uri)+}++#[cfg(test)]+mod test {+ use super::*;++ fn collected(name: &str, mime_type: &str) -> CollectedArtifact {+ CollectedArtifact {+ key: format!("artifacts/{name}@2026-09-16T00:00:00Z"),+ name: name.to_owned(),+ mime_type: mime_type.to_owned(),+ uri: format!("https://files.macro.com/{name}"),+ size_bytes: 12,+ }+ }++ #[test]+ fn images_inline_videos_embed_and_the_rest_link() {+ let markdown = artifact_markdown(&[+ collected("shot.png", "image/png"),+ collected("walkthrough.mp4", "video/mp4"),+ collected("notes.txt", "text/plain"),+ ]);+ assert_eq!(+ markdown,+ "\n\n\+ \n\n<m-video>{\"url\":\"https://files.macro.com/walkthrough.mp4\",\"srcType\":\"url\"}</m-video>\+ \n\n[notes.txt](https://files.macro.com/notes.txt)"+ );+ }++ #[test]+ fn an_opaque_served_type_falls_back_to_the_extension() {+ assert_eq!(+ mime_type("shot.png", Some("binary/octet-stream")),+ "image/png"+ );+ assert_eq!(mime_type("shot.png", Some("")), "image/png");+ assert_eq!(mime_type("clip.mov", None), "video/quicktime");+ assert_eq!(mime_type("mystery.bin", None), "application/octet-stream");+ assert_eq!(mime_type("shot.png", Some("image/webp")), "image/webp");+ }++ #[test]+ fn a_listing_keys_on_path_and_write_time() {+ let listing = ArtifactListing {+ path: "artifacts/shot.png".into(),+ size_bytes: 1,+ updated_at: "2026-09-16T00:00:00Z".into(),+ };+ assert_eq!(listing.key(), "artifacts/shot.png@2026-09-16T00:00:00Z");+ assert_eq!(listing.name(), "shot.png");+ }+}diff --git a/crates/cursor_cloud_agents/src/domain/journal.rs b/crates/cursor_cloud_agents/src/domain/journal.rsindex 41d5a4a14b..cff049f169 100644--- a/crates/cursor_cloud_agents/src/domain/journal.rs+++ b/crates/cursor_cloud_agents/src/domain/journal.rs@@ -1,4 +1,5 @@//! Native capture contract and the shared live/load processing machine.+use super::artifact::{CollectedArtifact, artifact_markdown};use super::event::{CursorEvent, InteractionUpdate};use super::model::{CursorRunId, RunOutcome, RunStatus};use super::translate::TranslateMachine;@@ -72,6 +73,16 @@ pub enum JournalInput {Poll(String),/// A local terminal decision (e.g. stop during a disconnected poll).Interrupted(String),+ /// The walkthrough files this run produced, re-hosted and durable.+ ///+ /// Journaled before the text announcing them is sent, so a crash between+ /// the two re-announces on replay rather than losing files nobody can+ /// fetch again — Cursor's own download links last fifteen minutes.+ /// Carries the collected list rather than the rendered markdown because+ /// the rendering is a pure function of it+ /// ([`artifact_markdown`](super::artifact::artifact_markdown)), and one+ /// copy of it is the only way live and replay cannot disagree.+ ArtifactsCollected(Vec<CollectedArtifact>),/// Capture has reconciled this run; distinct from ACP delivery checkpoint.Reconciled,}@@ -185,6 +196,14 @@ impl ReplayMachine {.collect())}JournalInput::Sse(record) => self.event(run, record.decode()),+ JournalInput::ArtifactsCollected(artifacts) => {+ if artifacts.is_empty() {+ return Ok(Vec::new());+ }+ Ok(vec![SessionUpdate::AgentMessageChunk(ContentChunk::new(+ ContentBlock::Text(TextContent::new(artifact_markdown(artifacts))),+ ))])+ }JournalInput::Poll(raw) => {let value: serde_json::Value =serde_json::from_str(raw).map_err(|e| rootcause::report!(e))?;diff --git a/crates/cursor_cloud_agents/src/domain/mod.rs b/crates/cursor_cloud_agents/src/domain/mod.rsindex 69b769e0cc..251b4d27f6 100644--- a/crates/cursor_cloud_agents/src/domain/mod.rs+++ b/crates/cursor_cloud_agents/src/domain/mod.rs@@ -1,5 +1,8 @@//! The domain: vocabulary, translation, ports, and the session service.+/// Walkthrough artifacts and the markdown that presents them.+pub mod artifact;+/// Errors the domain can produce.pub mod error;diff --git a/crates/cursor_cloud_agents/src/domain/ports.rs b/crates/cursor_cloud_agents/src/domain/ports.rsindex e5dc71a509..e179a46789 100644--- a/crates/cursor_cloud_agents/src/domain/ports.rs+++ b/crates/cursor_cloud_agents/src/domain/ports.rs@@ -9,6 +9,7 @@//! contracts for capture before decoding; HTTP I/O, SSE framing, JSON-RPC, and//! subprocesses remain outside the service.+use crate::domain::artifact::{ArtifactListing, FetchedArtifact};use crate::domain::model::{ConversationLine, CursorAgentId, CursorModel, CursorRunId, McpServer, ModelChoice, RepoUrl,RunListing,@@ -110,6 +111,85 @@ pub trait CursorAgents: Sync {) -> impl Future<Output = Result<Vec<ConversationLine>, rootcause::Report>> + Send;}+/// Read the walkthrough files a Cursor agent saved.+///+/// A sibling of [`CursorAgents`] rather than more methods on it: the agent+/// lifecycle is what every session needs, and artifacts are what one optional+/// step at the end of a turn needs. Splitting them keeps a fake that scripts+/// a listing from having to script an agent lifecycle too.+pub trait CursorArtifacts: Sync {+ /// Every artifact the agent has written, across all of its runs.+ ///+ /// Cursor offers no run filter, so a later turn still sees everything+ /// earlier turns wrote; the caller diffs.+ fn list_artifacts(+ &self,+ agent: &CursorAgentId,+ ) -> impl Future<Output = Result<Vec<ArtifactListing>, rootcause::Report>> + Send;++ /// Fetch one artifact's bytes by its listed path.+ ///+ /// One call rather than "mint a url" then "fetch it": the url is a+ /// credential with a fifteen-minute life, and nothing above this port has+ /// any business holding one.+ fn fetch_artifact(+ &self,+ agent: &CursorAgentId,+ path: &str,+ ) -> impl Future<Output = Result<FetchedArtifact, rootcause::Report>> + Send;+}++/// Re-host an artifact's bytes somewhere that outlives the provider's link.+///+/// The domain's only opinion about storage is this trade: bytes in, a URL out+/// that is still good when someone reopens the conversation next year. Which+/// service that is, what it names the object, and how it authenticates are+/// all outside.+pub trait ArtifactStore: Send + Sync {+ /// Whether this deployment can re-host anything at all.+ ///+ /// A service built without a store — the standalone binary, most tests —+ /// skips artifact collection whole rather than listing files it would+ /// only fail to store one at a time. `false` is a configuration fact, not+ /// a failure, which is why it is a question and not an error.+ fn is_available(&self) -> bool {+ true+ }++ /// Store `bytes` under `file_name` and answer with their permanent URI.+ fn store(+ &self,+ file_name: &str,+ mime_type: &str,+ bytes: bytes::Bytes,+ ) -> impl Future<Output = Result<String, rootcause::Report>> + Send;+}++/// The store for a deployment that has nowhere to put artifacts.+///+/// Reports itself unavailable, so a session built with it never lists an+/// agent's artifacts; the error exists only for a caller that ignores that+/// and asks anyway.+#[derive(Debug, Clone, Copy, Default)]+pub struct NoArtifactStore;++impl ArtifactStore for NoArtifactStore {+ fn is_available(&self) -> bool {+ false+ }++ async fn store(+ &self,+ _file_name: &str,+ _mime_type: &str,+ _bytes: bytes::Bytes,+ ) -> Result<String, rootcause::Report> {+ Err(rootcause::report!(+ "this session has no artifact store configured"+ ))+ }+}+/// One connected run stream, with what the provider said about resuming it.pub struct ConnectedStream<Records> {/// Complete native records, captured before decoding or translation.diff --git a/crates/cursor_cloud_agents/src/domain/service.rs b/crates/cursor_cloud_agents/src/domain/service.rsindex 9dc8661630..465afd08d2 100644--- a/crates/cursor_cloud_agents/src/domain/service.rs+++ b/crates/cursor_cloud_agents/src/domain/service.rs@@ -38,6 +38,7 @@#[cfg(test)]mod test;+use crate::domain::artifact::{ArtifactListing, CollectedArtifact, mime_type};use crate::domain::error::SessionError;use crate::domain::event::CursorEvent;use crate::domain::journal::{CursorJournal, JournalEntry, JournalInput, ReplayMachine};@@ -46,7 +47,8 @@ use crate::domain::model::{ModelChoice, RepoUrl, RunStatus,};use crate::domain::ports::{- CursorAgents, RepositoryChooser, RunStream, SessionNotifier, StreamConnectError,+ ArtifactStore, CursorAgents, CursorArtifacts, RepositoryChooser, RunStream, SessionNotifier,+ StreamConnectError,};use agent_client_protocol::schema::v1::{ContentBlock, SessionId, SessionUpdate, StopReason, TextContent,@@ -101,6 +103,24 @@ const STREAM_RECONNECT_ATTEMPTS: usize = 5;/// agent is drivable from cursor.com) before giving up, in poll intervals.const BUSY_ATTEMPTS: usize = 450;+/// How long a turn that saw no new artifacts waits before listing once more.+///+/// Cursor uploads a run's artifacts as the run finishes, so the listing can+/// still be empty a moment after the terminal frame that ended the turn. The+/// trade is plain: every turn that produced nothing pays this before it+/// answers, and without it a walkthrough's screenshots are silently missing+/// from the turn that took them. Five seconds is long enough to cover the+/// upload lag seen in practice and short enough to read as the turn ending.+const ARTIFACT_LISTING_RETRY_DELAY: std::time::Duration = std::time::Duration::from_secs(5);++/// The largest artifact this service will pull into memory, 64 MiB.+///+/// Read from the listing's `sizeBytes`, so an oversized recording is declined+/// before a byte of it is fetched. Well past any screenshot and past most+/// screen recordings; a run that produces something bigger loses that one+/// file, loudly, rather than the process losing its memory.+const MAX_ARTIFACT_BYTES: u64 = 64 * 1024 * 1024;+#[derive(Clone, Copy)]struct IngestMode {emit: bool,@@ -281,11 +301,14 @@ struct Session {/// The service behind the ACP handlers.#[derive(Debug)]-pub struct CursorSessionService<Cursor, Notifier, Chooser> {+pub struct CursorSessionService<Cursor, Notifier, Chooser, Store> {journal: Arc<dyn CursorJournal>,cursor: Cursor,notifier: Notifier,chooser: Chooser,+ /// Where a turn's walkthrough files are re-hosted. A store that reports+ /// itself unavailable turns artifact collection off entirely.+ artifacts: Store,sessions: Mutex<HashMap<SessionId, Arc<Session>>>,/// Monotonic counter for minting session ids without a clock or RNG.next_session: Mutex<u64>,@@ -297,11 +320,12 @@ pub struct CursorSessionService<Cursor, Notifier, Chooser> {models: tokio::sync::Mutex<Option<Vec<CursorModel>>>,}-impl<Cursor, Notifier, Chooser> CursorSessionService<Cursor, Notifier, Chooser>+impl<Cursor, Notifier, Chooser, Store> CursorSessionService<Cursor, Notifier, Chooser, Store>where- Cursor: CursorAgents + RunStream,+ Cursor: CursorAgents + CursorArtifacts + RunStream,Notifier: SessionNotifier,Chooser: RepositoryChooser,+ Store: ArtifactStore,{/// Wire the service to its ports.pub fn new(@@ -309,12 +333,14 @@ wherenotifier: Notifier,chooser: Chooser,journal: Arc<dyn CursorJournal>,+ artifacts: Store,) -> Self {Self {journal,cursor,notifier,chooser,+ artifacts,sessions: Mutex::new(HashMap::new()),next_session: Mutex::new(0),default_model_id: None,@@ -832,6 +858,14 @@ where).await?;}+ // The run's walkthrough files, collected once its outcome is known+ // and before the turn answers, so the fold appends their markdown to+ // this turn's reply like any other streamed text. A failed turn+ // collects nothing: there is no reply for the text to land in.+ if outcome.is_ok() {+ self.collect_artifacts(session_id, &session, &agent, &run, &cancel)+ .await?;+ }let reconciled = session.state.lock()@@ -1785,6 +1819,164 @@ whereOk(mirrored)}+ /// Re-host the walkthrough files this run produced and say so in the+ /// turn's own text.+ ///+ /// Artifacts never fail a turn: a listing that cannot be read, a file+ /// that cannot be fetched or stored, is reported and skipped, and the+ /// prompt still answers with the run's stop reason. Only a journal+ /// failure propagates, and that is already fatal to the session by the+ /// time it is seen here.+ #[tracing::instrument(+ name = "cursor.artifacts.collect",+ skip_all,+ fields(+ cursor.agent.id = %agent,+ artifacts.known = tracing::field::Empty,+ artifacts.collected = tracing::field::Empty,+ artifacts.retried = tracing::field::Empty,+ ),+ )]+ async fn collect_artifacts(+ &self,+ session_id: &SessionId,+ session: &Session,+ agent: &CursorAgentId,+ run: &CursorRunId,+ cancel: &tokio_util::sync::CancellationToken,+ ) -> Result<(), SessionError> {+ if !self.artifacts.is_available() {+ return Ok(());+ }+ let span = tracing::Span::current();+ // Every earlier collection in this session, because the provider's+ // listing is agent-scoped and repeats everything older turns wrote.+ let known: std::collections::HashSet<String> = session+ .state+ .lock()+ .expect("session state poisoned")+ .journal_entries+ .iter()+ .filter_map(|entry| match &entry.input {+ JournalInput::ArtifactsCollected(artifacts) => Some(artifacts),+ _ => None,+ })+ .flatten()+ .map(|artifact| artifact.key.clone())+ .collect();+ span.record("artifacts.known", known.len());++ let Some(mut fresh) = self.new_artifacts(agent, &known).await else {+ return Ok(());+ };+ let retried = fresh.is_empty();+ span.record("artifacts.retried", retried);+ if retried {+ // A cancelled turn skips the wait and lists once more anyway:+ // `sleep_unless_cancelled` returns immediately, and the second+ // listing is the cheap half of this.+ sleep_unless_cancelled(cancel, ARTIFACT_LISTING_RETRY_DELAY).await;+ let Some(second) = self.new_artifacts(agent, &known).await else {+ return Ok(());+ };+ fresh = second;+ }+ if fresh.is_empty() {+ return Ok(());+ }++ let mut collected = Vec::new();+ for listing in fresh {+ if listing.size_bytes > MAX_ARTIFACT_BYTES {+ tracing::warn!(+ artifact.path = %listing.path,+ artifact.size_bytes = listing.size_bytes,+ artifact.size_limit = MAX_ARTIFACT_BYTES,+ "skipping an artifact larger than this service will buffer"+ );+ continue;+ }+ let fetched = match self.cursor.fetch_artifact(agent, &listing.path).await {+ Ok(fetched) => fetched,+ Err(error) => {+ tracing::warn!(+ artifact.path = %listing.path,+ %error,+ "could not fetch an artifact from Cursor"+ );+ continue;+ }+ };+ let mime_type = mime_type(listing.name(), fetched.content_type.as_deref());+ match self+ .artifacts+ .store(listing.name(), &mime_type, fetched.bytes)+ .await+ {+ Ok(uri) => collected.push(CollectedArtifact {+ key: listing.key(),+ name: listing.name().to_owned(),+ mime_type,+ uri,+ size_bytes: listing.size_bytes,+ }),+ Err(error) => tracing::warn!(+ artifact.path = %listing.path,+ %error,+ "could not re-host an artifact"+ ),+ }+ }+ span.record("artifacts.collected", collected.len());+ if collected.is_empty() {+ return Ok(());+ }+ tracing::info!(+ %agent,+ %run,+ artifacts.collected = collected.len(),+ "re-hosted this run's artifacts"+ );+ // Journalled and projected in one step, which is what puts the+ // markdown on the wire: capture appends before it emits, so a crash+ // between the two re-announces on replay instead of losing files+ // whose provider links have since expired.+ self.capture(+ session_id,+ session,+ Some(run),+ JournalInput::ArtifactsCollected(collected),+ true,+ )+ .await+ }++ /// The agent's artifacts this session has not collected yet, oldest+ /// first. `None` means the listing itself failed and the turn carries on.+ async fn new_artifacts(+ &self,+ agent: &CursorAgentId,+ known: &std::collections::HashSet<String>,+ ) -> Option<Vec<ArtifactListing>> {+ let listings = match self.cursor.list_artifacts(agent).await {+ Ok(listings) => listings,+ Err(error) => {+ tracing::warn!(%agent, %error, "could not list this agent's artifacts");+ return None;+ }+ };+ let mut fresh: Vec<_> = listings+ .into_iter()+ .filter(|listing| !known.contains(&listing.key()))+ .collect();+ // Write order, as far as the provider's timestamps show it, so a+ // walkthrough's screenshots read in the order they were taken.+ fresh.sort_by(|left, right| {+ (&left.updated_at, &left.path).cmp(&(&right.updated_at, &right.path))+ });+ Some(fresh)+ }+async fn ensure_journal(&self, id: &SessionId, session: &Session) -> Result<(), SessionError> {if session.state@@ -2341,6 +2533,20 @@ enum HistoryGap {IsServedAnyway,}+/// Whether `run` collects artifacts after `entry`, so its turn outcome has to+/// wait for them.+fn collects_artifacts_later(+ entries: &[JournalEntry],+ entry: &JournalEntry,+ run: &CursorRunId,+) -> bool {+ entries.iter().any(|later| {+ later.sequence > entry.sequence+ && later.run.as_ref() == Some(run)+ && matches!(later.input, JournalInput::ArtifactsCollected(_))+ })+}+fn history_projection(entries: &[JournalEntry],gap: HistoryGap,@@ -2367,6 +2573,10 @@ fn history_projection(// Intent position is audit order, not conversation order. Accepted// prompts project immediately before their first native run input.let mut updates = Vec::new();+ // Turn outcomes held back past their run's terminal frame, keyed by run;+ // see the artifact case below.+ let mut deferred: HashMap<CursorRunId, agent_runtime_protocol::domain::turn::TurnOutcome> =+ HashMap::new();for entry in entries {let before = entry.run@@ -2384,6 +2594,21 @@ fn history_projection(} else {None};+ // A run's artifacts are collected after its terminal frame but belong+ // to the turn that produced them, and live delivery only ends the+ // turn when the prompt answers - after that text. Holding the outcome+ // back to the artifacts entry is what makes a reloaded session read+ // in the same order the person watched it arrive.+ let outcome = match (entry.run.as_ref(), outcome) {+ (Some(run), Some(outcome)) if collects_artifacts_later(entries, entry, run) => {+ deferred.insert(run.clone(), outcome);+ None+ }+ (Some(run), None) if matches!(entry.input, JournalInput::ArtifactsCollected(_)) => {+ deferred.remove(run)+ }+ (_, outcome) => outcome,+ };updates.push((projected, outcome));}// Acceptance can be durable before the first stream observation. Itsdiff --git a/crates/cursor_cloud_agents/src/domain/service/test.rs b/crates/cursor_cloud_agents/src/domain/service/test.rsindex 912595488d..8cc08614f7 100644--- a/crates/cursor_cloud_agents/src/domain/service/test.rs+++ b/crates/cursor_cloud_agents/src/domain/service/test.rs@@ -6,12 +6,12 @@ use crate::domain::model::{ConversationLine, ConversationSpeaker, McpHeader, McpServer, McpTransport, RepoUrl, RunListing,RunOutcome, RunStatus,};-use crate::domain::ports::StreamConnectError;+use crate::domain::ports::{NoArtifactStore, StreamConnectError};use crate::testing::{CursorCall, FakeCursor, FixedChooser, RecordingNotifier};use agent_client_protocol::schema::v1::{SessionUpdate, StopReason, ToolCallStatus};use std::path::Path;-type Service = CursorSessionService<FakeCursor, RecordingNotifier, FixedChooser>;+type Service = CursorSessionService<FakeCursor, RecordingNotifier, FixedChooser, NoArtifactStore>;fn service(repo: Option<RepoUrl>) -> (Arc<Service>, FakeCursor, RecordingNotifier) {let cursor = FakeCursor::new();@@ -21,6 +21,7 @@ fn service(repo: Option<RepoUrl>) -> (Arc<Service>, FakeCursor, RecordingNotifienotifier.clone(),FixedChooser(repo.clone(), repo.is_some()),Arc::new(crate::outbound::memory_journal::MemoryJournal::default()),+ NoArtifactStore,));(service, cursor, notifier)}@@ -1287,6 +1288,7 @@ async fn restore_recovers_runs_after_the_durable_watermark_once() {notifier.clone(),FixedChooser(None, false),Arc::new(crate::outbound::memory_journal::MemoryJournal::default()),+ NoArtifactStore,);let session = SessionId::new("cursor-acp-restored");service.restore_session_with_watermark(@@ -1403,6 +1405,7 @@ async fn restore_without_a_watermark_hydrates_every_run_on_load() {notifier.clone(),FixedChooser(None, false),Arc::new(crate::outbound::memory_journal::MemoryJournal::default()),+ NoArtifactStore,);let session = SessionId::new("cursor-acp-restored");service.restore_session_with_watermark(@@ -1466,6 +1469,7 @@ async fn restore_waits_for_session_load_before_recovering_runs() {notifier.clone(),FixedChooser(None, false),Arc::new(crate::outbound::memory_journal::MemoryJournal::default()),+ NoArtifactStore,);let session = SessionId::new("cursor-acp-restored");service.restore_session_with_watermark(@@ -1794,6 +1798,7 @@ async fn durable_multiturn_load_replays_full_history_and_supports_continuation()live.clone(),FixedChooser(None, false),journal.clone(),+ NoArtifactStore,);let id = service.new_session(Path::new(""), vec![]);for (prompt, fixture) in [@@ -1820,6 +1825,7 @@ async fn durable_multiturn_load_replays_full_history_and_supports_continuation()replayed.clone(),FixedChooser(None, false),journal.clone(),+ NoArtifactStore,));restored.restore_session(id.clone(), Some(CursorAgentId::new("bc-fake")), None, None);restored.replay_session(&id).await.unwrap().complete();@@ -1903,6 +1909,7 @@ async fn append_failure_publishes_nothing_and_never_advances_delivery_or_retriesoutput.clone(),FixedChooser(None, false),journal.clone(),+ NoArtifactStore,);let id = service.new_session(Path::new(""), vec![]);let tx = cursor.script_stream();@@ -2455,6 +2462,7 @@ async fn model_resolution_precedes_intent_and_definite_rejection_aborts_it() {RecordingNotifier::new(),FixedChooser(None, false),journal.clone(),+ NoArtifactStore,).with_default_model(Some("model".into())),);@@ -2484,6 +2492,7 @@ async fn model_resolution_precedes_intent_and_definite_rejection_aborts_it() {service.replay_session(&id).await.unwrap().complete();}+mod artifacts;mod fold;#[tokio::test]@@ -2709,6 +2718,7 @@ async fn repository_setup_failure_is_retryable_and_not_reported_as_prompt_ambiguRecordingNotifier::new(),UnavailableChooser,Arc::new(crate::outbound::memory_journal::MemoryJournal::default()),+ NoArtifactStore,);let id = service.new_session(Path::new(""), vec![]);for _ in 0..2 {@@ -2782,6 +2792,7 @@ async fn repository_choice_receives_each_sessions_working_directory() {RecordingNotifier::new(),RecordingChooser::default(),Arc::new(crate::outbound::memory_journal::MemoryJournal::default()),+ NoArtifactStore,);for cwd in ["/workspace/one", "/workspace/two"] {let id = service.new_session(Path::new(cwd), vec![]);@@ -2895,6 +2906,7 @@ async fn giving_up_on_an_unfinished_run_is_still_journalled_as_interrupted() {RecordingNotifier::new(),FixedChooser(None, false),journal.clone(),+ NoArtifactStore,));let session = service.new_session(Path::new(""), Vec::new());diff --git a/crates/cursor_cloud_agents/src/domain/service/test/artifacts.rs b/crates/cursor_cloud_agents/src/domain/service/test/artifacts.rsnew file mode 100644index 0000000000..bea896cf95--- /dev/null+++ b/crates/cursor_cloud_agents/src/domain/service/test/artifacts.rs@@ -0,0 +1,314 @@+//! Walkthrough artifacts reaching the client as ordinary assistant text.+use super::*;+use crate::domain::artifact::ArtifactListing;+use crate::outbound::memory_journal::MemoryJournal;+use crate::testing::FakeArtifactStore;++type ArtifactService =+ CursorSessionService<FakeCursor, RecordingNotifier, FixedChooser, FakeArtifactStore>;++struct Harness {+ service: Arc<ArtifactService>,+ cursor: FakeCursor,+ notifier: RecordingNotifier,+ store: FakeArtifactStore,+ journal: Arc<MemoryJournal>,+}++fn harness() -> Harness {+ let cursor = FakeCursor::new();+ let notifier = RecordingNotifier::new();+ let store = FakeArtifactStore::new();+ let journal = Arc::new(MemoryJournal::default());+ let service = Arc::new(CursorSessionService::new(+ cursor.clone(),+ notifier.clone(),+ FixedChooser(None, false),+ journal.clone(),+ store.clone(),+ ));+ Harness {+ service,+ cursor,+ notifier,+ store,+ journal,+ }+}++fn listing(path: &str, updated_at: &str, size_bytes: u64) -> ArtifactListing {+ ArtifactListing {+ path: path.to_owned(),+ size_bytes,+ updated_at: updated_at.to_owned(),+ }+}++/// Run one turn whose stream says `text` and then finishes.+async fn turn(harness: &Harness, session: &SessionId, run: &str, text: &str) -> StopReason {+ let events = harness.cursor.script_stream();+ events+ .send(CursorEvent::Assistant {+ text: text.to_owned(),+ })+ .expect("stream open");+ events.send(finished(run)).expect("stream open");+ events.send(CursorEvent::Done).expect("stream open");+ harness+ .service+ .prompt(session, "take a walkthrough")+ .await+ .expect("prompt runs")+}++/// Everything the client was told, as agent text.+fn chunks(notifier: &RecordingNotifier) -> Vec<String> {+ agent_texts(¬ifier.updates())+}++#[tokio::test]+async fn a_turns_artifacts_arrive_as_one_chunk_of_markdown() {+ let harness = harness();+ harness.cursor.script_artifact_listing(vec![+ listing("artifacts/walkthrough.mp4", "2026-09-16T00:00:02Z", 2048),+ listing("artifacts/shot.png", "2026-09-16T00:00:01Z", 512),+ ]);+ harness+ .cursor+ .script_artifact_body("artifacts/shot.png", Some("image/png"), b"png-bytes");+ harness.cursor.script_artifact_body(+ "artifacts/walkthrough.mp4",+ Some("binary/octet-stream"),+ b"mp4-bytes",+ );+ let session = harness.service.new_session(Path::new(""), Vec::new());++ let stop = turn(&harness, &session, "run-fake-1", "here you go").await;++ assert_eq!(stop, StopReason::EndTurn);+ assert_eq!(+ chunks(&harness.notifier),+ vec\+ \n\n<m-video>{\"url\":\"https://files.test/walkthrough.mp4\",\"srcType\":\"url\"}</m-video>"+ .to_owned(),+ ],+ "the artifacts follow the run's own text, oldest first"+ );+ // The mp4 was served as opaque bytes; its extension is what named it.+ assert_eq!(+ harness+ .store+ .stored()+ .iter()+ .map(|stored| (stored.name.clone(), stored.mime_type.clone()))+ .collect::<Vec<_>>(),+ vec![+ ("shot.png".to_owned(), "image/png".to_owned()),+ ("walkthrough.mp4".to_owned(), "video/mp4".to_owned()),+ ]+ );+ let journalled: Vec<_> = harness+ .journal+ .read(&session)+ .await+ .expect("journal read")+ .into_iter()+ .filter_map(|entry| match entry.input {+ JournalInput::ArtifactsCollected(artifacts) => Some(artifacts),+ _ => None,+ })+ .collect();+ assert_eq!(journalled.len(), 1);+ assert_eq!(+ journalled[0]+ .iter()+ .map(|artifact| artifact.key.clone())+ .collect::<Vec<_>>(),+ vec![+ "artifacts/shot.png@2026-09-16T00:00:01Z".to_owned(),+ "artifacts/walkthrough.mp4@2026-09-16T00:00:02Z".to_owned(),+ ]+ );+}++#[tokio::test]+async fn a_later_turn_announces_only_what_it_has_not_announced_before() {+ let harness = harness();+ harness+ .cursor+ .script_artifact_listing(vec![listing("artifacts/one.png", "t1", 8)]);+ harness.cursor.script_artifact_listing(vec![+ listing("artifacts/one.png", "t1", 8),+ listing("artifacts/two.png", "t2", 8),+ ]);+ for path in ["artifacts/one.png", "artifacts/two.png"] {+ harness+ .cursor+ .script_artifact_body(path, Some("image/png"), b"bytes");+ }+ let session = harness.service.new_session(Path::new(""), Vec::new());++ turn(&harness, &session, "run-fake-1", "first").await;+ turn(&harness, &session, "run-fake-2", "second").await;++ assert_eq!(+ chunks(&harness.notifier),+ vec".to_owned(),+ "second".to_owned(),+ "\n\n".to_owned(),+ ]+ );+}++#[tokio::test(start_paused = true)]+async fn an_empty_first_listing_is_listed_once_more() {+ let harness = harness();+ harness.cursor.script_artifact_listing(Vec::new());+ harness+ .cursor+ .script_artifact_listing(vec![listing("artifacts/late.png", "t1", 8)]);+ harness+ .cursor+ .script_artifact_body("artifacts/late.png", Some("image/png"), b"bytes");+ let session = harness.service.new_session(Path::new(""), Vec::new());++ turn(&harness, &session, "run-fake-1", "done").await;++ assert_eq!(+ chunks(&harness.notifier),+ vec".to_owned(),+ ]+ );+ assert_eq!(+ harness+ .cursor+ .calls()+ .iter()+ .filter(|call| matches!(call, CursorCall::ListArtifacts(_)))+ .count(),+ 2+ );+}++#[tokio::test]+async fn one_file_that_cannot_be_stored_does_not_cost_the_others() {+ let harness = harness();+ harness.cursor.script_artifact_listing(vec![+ listing("artifacts/broken.png", "t1", 8),+ listing("artifacts/fine.png", "t2", 8),+ listing("artifacts/huge.mp4", "t3", 128 * 1024 * 1024),+ ]);+ for path in ["artifacts/broken.png", "artifacts/fine.png"] {+ harness+ .cursor+ .script_artifact_body(path, Some("image/png"), b"bytes");+ }+ harness.store.fail_for("broken.png");+ let session = harness.service.new_session(Path::new(""), Vec::new());++ let stop = turn(&harness, &session, "run-fake-1", "done").await;++ assert_eq!(stop, StopReason::EndTurn);+ assert_eq!(+ chunks(&harness.notifier),+ vec".to_owned(),+ ]+ );+ assert!(+ !harness.cursor.calls().contains(&CursorCall::FetchArtifact(+ CursorAgentId::new("bc-fake"),+ "artifacts/huge.mp4".to_owned()+ )),+ "a file over the size cap is declined before it is fetched"+ );+}++#[tokio::test(start_paused = true)]+async fn a_failed_listing_leaves_the_turn_alone() {+ let harness = harness();+ harness+ .cursor+ .script_artifact_listing_error("artifacts unavailable");+ let session = harness.service.new_session(Path::new(""), Vec::new());++ let stop = turn(&harness, &session, "run-fake-1", "done").await;++ assert_eq!(stop, StopReason::EndTurn);+ assert_eq!(chunks(&harness.notifier), vec!["done".to_owned()]);+}++#[tokio::test]+async fn a_reloaded_session_re_announces_the_same_artifacts() {+ let harness = harness();+ harness+ .cursor+ .script_artifact_listing(vec![listing("artifacts/shot.png", "t1", 8)]);+ harness+ .cursor+ .script_artifact_body("artifacts/shot.png", Some("image/png"), b"bytes");+ let session = harness.service.new_session(Path::new(""), Vec::new());+ turn(&harness, &session, "run-fake-1", "done").await;+ let live = chunks(&harness.notifier);++ let replayed = RecordingNotifier::new();+ let cursor = FakeCursor::new();+ let restored = Arc::new(CursorSessionService::new(+ cursor.clone(),+ replayed.clone(),+ FixedChooser(None, false),+ harness.journal.clone(),+ FakeArtifactStore::new(),+ ));+ restored.restore_session(+ session.clone(),+ Some(CursorAgentId::new("bc-fake")),+ None,+ None,+ );+ restored+ .replay_session(&session)+ .await+ .expect("load")+ .complete();++ assert_eq!(chunks(&replayed), live);+ assert!(+ cursor.calls().is_empty(),+ "a load re-announces from the journal, never from the provider"+ );+}++#[tokio::test]+async fn a_session_without_a_store_never_lists_artifacts() {+ let cursor = FakeCursor::new();+ let notifier = RecordingNotifier::new();+ let service = Arc::new(CursorSessionService::new(+ cursor.clone(),+ notifier.clone(),+ FixedChooser(None, false),+ Arc::new(MemoryJournal::default()),+ NoArtifactStore,+ ));+ let session = service.new_session(Path::new(""), Vec::new());+ let events = cursor.script_stream();+ events.send(finished("run-fake-1")).expect("stream open");+ events.send(CursorEvent::Done).expect("stream open");++ let stop = service.prompt(&session, "go").await.expect("prompt runs");++ assert_eq!(stop, StopReason::EndTurn);+ assert!(+ !cursor+ .calls()+ .iter()+ .any(|call| matches!(call, CursorCall::ListArtifacts(_)))+ );+}diff --git a/crates/cursor_cloud_agents/src/domain/service/test/fold.rs b/crates/cursor_cloud_agents/src/domain/service/test/fold.rsindex 52cc10d313..5450763f66 100644--- a/crates/cursor_cloud_agents/src/domain/service/test/fold.rs+++ b/crates/cursor_cloud_agents/src/domain/service/test/fold.rs@@ -36,6 +36,7 @@ pub(super) async fn replay_with_runs(notifier.clone(),FixedChooser(None, false),journal,+ crate::domain::ports::NoArtifactStore,));service.restore_session(id.clone(), Some(CursorAgentId::new("agent")), None, None);let (agent, mut client) = Channel::duplex();@@ -190,6 +191,7 @@ async fn actual_live_backfill_keeps_older_answer_out_of_pending_or_cancelled_pronotifier.clone(),FixedChooser(None, false),journal.clone(),+ crate::domain::ports::NoArtifactStore,));let id = service.new_session(Path::new(""), vec![]);service.session(&id).unwrap().state.lock().unwrap().agent =@@ -520,6 +522,7 @@ async fn load_waiting_for_an_active_backfill_replays_one_copy_through_fold() {notifier.clone(),FixedChooser(None, false),journal.clone(),+ crate::domain::ports::NoArtifactStore,));let id = service.new_session(Path::new(""), vec![]);service.session(&id).unwrap().state.lock().unwrap().agent = Some(CursorAgentId::new("agent"));diff --git a/crates/cursor_cloud_agents/src/inbound/acp.rs b/crates/cursor_cloud_agents/src/inbound/acp.rsindex 817050acde..1044791c39 100644--- a/crates/cursor_cloud_agents/src/inbound/acp.rs+++ b/crates/cursor_cloud_agents/src/inbound/acp.rs@@ -30,7 +30,9 @@ mod test;use crate::domain::model::{McpHeader, McpServer, McpTransport};use crate::domain::model_options::{MODEL_CONFIG_ID, cursor_model_config_options};-use crate::domain::ports::{CursorAgents, RepositoryChooser, RunStream, SessionNotifier};+use crate::domain::ports::{+ ArtifactStore, CursorAgents, CursorArtifacts, RepositoryChooser, RunStream, SessionNotifier,+};use crate::domain::service::CursorSessionService;use agent_client_protocol::schema::ProtocolVersion;use agent_client_protocol::schema::v1::{@@ -310,8 +312,8 @@ fn agent_capabilities() -> AgentCapabilities {////// A clean EOF from the client is `Ok`; transport and protocol-level failures/// are the SDK's error.-pub async fn serve<Reader, Writer, Cursor, Notifier, Chooser>(- service: Arc<CursorSessionService<Cursor, Notifier, Chooser>>,+pub async fn serve<Reader, Writer, Cursor, Notifier, Chooser, Store>(+ service: Arc<CursorSessionService<Cursor, Notifier, Chooser, Store>>,notifier: AcpNotifier,reader: Reader,writer: Writer,@@ -319,9 +321,10 @@ pub async fn serve<Reader, Writer, Cursor, Notifier, Chooser>(whereReader: tokio::io::AsyncRead + Send + 'static,Writer: tokio::io::AsyncWrite + Send + 'static,- Cursor: CursorAgents + RunStream + Send + Sync + 'static,+ Cursor: CursorAgents + CursorArtifacts + RunStream + Send + Sync + 'static,Notifier: SessionNotifier + Send + Sync + 'static,Chooser: RepositoryChooser + 'static,+ Store: ArtifactStore + 'static,{serve_transport(service,@@ -339,16 +342,17 @@ where////// A clean EOF from the client is `Ok`; transport and protocol-level failures/// are the SDK's error.-pub async fn serve_transport<Transport, Cursor, Notifier, Chooser>(- service: Arc<CursorSessionService<Cursor, Notifier, Chooser>>,+pub async fn serve_transport<Transport, Cursor, Notifier, Chooser, Store>(+ service: Arc<CursorSessionService<Cursor, Notifier, Chooser, Store>>,notifier: AcpNotifier,transport: Transport,) -> Result<(), AcpError>whereTransport: ConnectTo<Agent> + 'static,- Cursor: CursorAgents + RunStream + Send + Sync + 'static,+ Cursor: CursorAgents + CursorArtifacts + RunStream + Send + Sync + 'static,Notifier: SessionNotifier + Send + Sync + 'static,Chooser: RepositoryChooser + 'static,+ Store: ArtifactStore + 'static,{let startup_notifier = notifier.clone();Agent@@ -547,14 +551,15 @@ where/// A failure to reach `GET /v1/models` costs the picker, not the session: the/// options come back empty and the client simply has nothing to offer, which is/// the state it was in before any of this existed.-async fn session_config_options<Cursor, Notifier, Chooser>(- service: &CursorSessionService<Cursor, Notifier, Chooser>,+async fn session_config_options<Cursor, Notifier, Chooser, Store>(+ service: &CursorSessionService<Cursor, Notifier, Chooser, Store>,session: &SessionId,) -> Vec<SessionConfigOption>where- Cursor: CursorAgents + RunStream,+ Cursor: CursorAgents + CursorArtifacts + RunStream,Notifier: SessionNotifier,Chooser: RepositoryChooser,+ Store: ArtifactStore,{let models = match service.models().await {Ok(models) => models,diff --git a/crates/cursor_cloud_agents/src/inbound/acp/test.rs b/crates/cursor_cloud_agents/src/inbound/acp/test.rsindex f1134def03..dc14cef598 100644--- a/crates/cursor_cloud_agents/src/inbound/acp/test.rs+++ b/crates/cursor_cloud_agents/src/inbound/acp/test.rs@@ -19,7 +19,12 @@ use futures::channel::mpsc;use tokio::io::AsyncBufReadExt as _;use tokio::io::AsyncWriteExt as _;-type Service = CursorSessionService<FakeCursor, AcpNotifier, FixedChooser>;+type Service = CursorSessionService<+ FakeCursor,+ AcpNotifier,+ FixedChooser,+ crate::domain::ports::NoArtifactStore,+>;/// The client's end of a served connection.struct TestClient {@@ -115,6 +120,7 @@ fn serve_over_channel_with_default_model(notifier.clone(),FixedChooser(None, false),Arc::new(crate::outbound::memory_journal::MemoryJournal::default()),+ crate::domain::ports::NoArtifactStore,).with_default_model(default_model.map(str::to_owned)),);@@ -374,6 +380,7 @@ async fn serve_runs_a_whole_conversation_over_an_in_process_pipe() {notifier.clone(),FixedChooser(None, false),Arc::new(crate::outbound::memory_journal::MemoryJournal::default()),+ crate::domain::ports::NoArtifactStore,));let serve_task = tokio::spawn(serve(service, notifier, agent_reader, agent_writer));diff --git a/crates/cursor_cloud_agents/src/outbound/mod.rs b/crates/cursor_cloud_agents/src/outbound/mod.rsindex 197eaab665..37f6d4149a 100644--- a/crates/cursor_cloud_agents/src/outbound/mod.rs+++ b/crates/cursor_cloud_agents/src/outbound/mod.rs@@ -5,3 +5,5 @@ pub mod memory_journal;/// Fenced durable journal for hosted sessions.#[cfg(feature = "postgres")]pub mod postgres_journal;+/// Re-hosts artifacts on Macro's static file service.+pub mod static_file_artifacts;diff --git a/crates/cursor_cloud_agents/src/outbound/static_file_artifacts.rs b/crates/cursor_cloud_agents/src/outbound/static_file_artifacts.rsnew file mode 100644index 0000000000..8a17096196--- /dev/null+++ b/crates/cursor_cloud_agents/src/outbound/static_file_artifacts.rs@@ -0,0 +1,36 @@+//! Re-hosting artifacts on Macro's static file service.++use crate::domain::ports::ArtifactStore;+use static_file_service_client::StaticFileServiceClient;++/// Stores artifacts on the static file service, which is where every other+/// user-visible blob in Macro already lives — so an artifact is served,+/// permissioned, and expired exactly like an uploaded image is.+#[derive(Clone)]+pub struct StaticFileArtifactStore {+ client: StaticFileServiceClient,+}++impl StaticFileArtifactStore {+ /// Wire the store to a client of the static file service.+ #[must_use]+ pub fn new(client: StaticFileServiceClient) -> Self {+ Self { client }+ }+}++impl ArtifactStore for StaticFileArtifactStore {+ async fn store(+ &self,+ file_name: &str,+ mime_type: &str,+ bytes: bytes::Bytes,+ ) -> Result<String, rootcause::Report> {+ let stored = self+ .client+ .put_named_bytes(file_name, bytes, mime_type)+ .await+ .map_err(|error| rootcause::report!("{error}"))?;+ Ok(stored.file_location)+ }+}diff --git a/crates/cursor_cloud_agents/src/testing.rs b/crates/cursor_cloud_agents/src/testing.rsindex 08d6c9c39e..58e7aea392 100644--- a/crates/cursor_cloud_agents/src/testing.rs+++ b/crates/cursor_cloud_agents/src/testing.rs@@ -1,5 +1,6 @@//! In-memory port implementations and recorded fixtures, for tests.+use crate::domain::artifact::{ArtifactListing, FetchedArtifact};use crate::domain::event::CursorEvent;use crate::domain::journal::NativeRecord;use crate::domain::model::{@@ -7,8 +8,8 @@ use crate::domain::model::{RunListing, RunOutcome,};use crate::domain::ports::{- ConnectedStream, CursorAgents, RepositoryChooser, RunStream, SessionIntent, SessionNotifier,- StreamConnectError,+ ArtifactStore, ConnectedStream, CursorAgents, CursorArtifacts, RepositoryChooser, RunStream,+ SessionIntent, SessionNotifier, StreamConnectError,};use agent_client_protocol::schema::v1::{SessionId, SessionUpdate};use futures::Stream;@@ -158,6 +159,10 @@ pub enum CursorCall {RunResult(CursorAgentId, CursorRunId),/// `conversation(agent)`.Conversation(CursorAgentId),+ /// `list_artifacts(agent)`.+ ListArtifacts(CursorAgentId),+ /// `fetch_artifact(agent, path)`.+ FetchArtifact(CursorAgentId, String),}/// A scripted Cursor: hands out ids, records calls, and streams whatever the@@ -192,6 +197,17 @@ struct FakeCursorState {model_gate: Option<tokio::sync::oneshot::Receiver<()>>,reject_create: bool,reject_create_for_repository: bool,+ /// Answers for `list_artifacts`, consumed in order; the last one sticks.+ artifact_listings: Vec<Result<Vec<ArtifactListing>, String>>,+ /// Bodies `fetch_artifact` answers with, by artifact path.+ artifact_bodies: std::collections::HashMap<String, FetchedBody>,+}++/// One scripted artifact download.+#[derive(Debug, Clone)]+struct FetchedBody {+ content_type: Option<String>,+ bytes: Result<bytes::Bytes, String>,}impl FakeCursor {@@ -328,6 +344,58 @@ impl FakeCursor {.run_listings = listings;}+ /// Queue the answer the next `list_artifacts` call gets.+ ///+ /// Calls past the last scripted answer get that answer again, which is+ /// what a real agent-scoped listing does: it keeps returning everything+ /// the agent has ever written.+ pub fn script_artifact_listing(&self, listings: Vec<ArtifactListing>) {+ self.inner+ .lock()+ .expect("fake cursor poisoned")+ .artifact_listings+ .push(Ok(listings));+ }++ /// Queue a `list_artifacts` failure.+ pub fn script_artifact_listing_error(&self, message: &str) {+ self.inner+ .lock()+ .expect("fake cursor poisoned")+ .artifact_listings+ .push(Err(message.to_owned()));+ }++ /// Give an artifact path a body, with the content type S3 would serve.+ pub fn script_artifact_body(&self, path: &str, content_type: Option<&str>, bytes: &[u8]) {+ self.inner+ .lock()+ .expect("fake cursor poisoned")+ .artifact_bodies+ .insert(+ path.to_owned(),+ FetchedBody {+ content_type: content_type.map(str::to_owned),+ bytes: Ok(bytes::Bytes::copy_from_slice(bytes)),+ },+ );+ }++ /// Make one artifact path fail to download.+ pub fn script_artifact_body_error(&self, path: &str, message: &str) {+ self.inner+ .lock()+ .expect("fake cursor poisoned")+ .artifact_bodies+ .insert(+ path.to_owned(),+ FetchedBody {+ content_type: None,+ bytes: Err(message.to_owned()),+ },+ );+ }+/// Everything the service asked of the API, in order.#[must_use]pub fn calls(&self) -> Vec<CursorCall> {@@ -530,6 +598,123 @@ enum ScriptedStream {ConnectError(StreamConnectError),}+impl CursorArtifacts for FakeCursor {+ async fn list_artifacts(+ &self,+ agent: &CursorAgentId,+ ) -> Result<Vec<ArtifactListing>, rootcause::Report> {+ self.record(CursorCall::ListArtifacts(agent.clone()));+ let mut state = self.inner.lock().expect("fake cursor poisoned");+ let answer = if state.artifact_listings.len() > 1 {+ state.artifact_listings.remove(0)+ } else {+ state+ .artifact_listings+ .first()+ .cloned()+ .unwrap_or(Ok(vec![]))+ };+ answer.map_err(|message| rootcause::report!("{message}"))+ }++ async fn fetch_artifact(+ &self,+ agent: &CursorAgentId,+ path: &str,+ ) -> Result<FetchedArtifact, rootcause::Report> {+ self.record(CursorCall::FetchArtifact(agent.clone(), path.to_owned()));+ let body = self+ .inner+ .lock()+ .expect("fake cursor poisoned")+ .artifact_bodies+ .get(path)+ .cloned();+ let body = body.ok_or_else(|| rootcause::report!("no scripted body for {path}"))?;+ Ok(FetchedArtifact {+ content_type: body.content_type,+ bytes: body+ .bytes+ .map_err(|message| rootcause::report!("{message}"))?,+ })+ }+}++/// An artifact store that keeps every file in memory and hands back a URL+/// derived from its name.+#[derive(Debug, Clone, Default)]+pub struct FakeArtifactStore {+ stored: Arc<Mutex<Vec<StoredArtifact>>>,+ failing: Arc<Mutex<Vec<String>>>,+}++/// One file a [`FakeArtifactStore`] was given.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct StoredArtifact {+ /// The name it was stored under.+ pub name: String,+ /// The media type it was stored with.+ pub mime_type: String,+ /// Its bytes.+ pub bytes: Vec<u8>,+}++impl FakeArtifactStore {+ /// An empty store that accepts everything.+ #[must_use]+ pub fn new() -> Self {+ Self::default()+ }++ /// Make every attempt to store `name` fail.+ pub fn fail_for(&self, name: &str) {+ self.failing+ .lock()+ .expect("fake store poisoned")+ .push(name.to_owned());+ }++ /// Everything stored so far, in order.+ #[must_use]+ pub fn stored(&self) -> Vec<StoredArtifact> {+ self.stored.lock().expect("fake store poisoned").clone()+ }++ /// The URL this store answers with for `name`.+ #[must_use]+ pub fn uri(name: &str) -> String {+ format!("https://files.test/{name}")+ }+}++impl ArtifactStore for FakeArtifactStore {+ async fn store(+ &self,+ file_name: &str,+ mime_type: &str,+ bytes: bytes::Bytes,+ ) -> Result<String, rootcause::Report> {+ if self+ .failing+ .lock()+ .expect("fake store poisoned")+ .iter()+ .any(|name| name == file_name)+ {+ return Err(rootcause::report!("scripted store failure for {file_name}"));+ }+ self.stored+ .lock()+ .expect("fake store poisoned")+ .push(StoredArtifact {+ name: file_name.to_owned(),+ mime_type: mime_type.to_owned(),+ bytes: bytes.to_vec(),+ });+ Ok(Self::uri(file_name))+ }+}+impl RunStream for FakeCursor {async fn raw_stream(&self,diff --git a/crates/static_file_service_client/Cargo.toml b/crates/static_file_service_client/Cargo.tomlindex 4cb8f87d8f..58c095c217 100644--- a/crates/static_file_service_client/Cargo.toml+++ b/crates/static_file_service_client/Cargo.toml@@ -7,6 +7,7 @@ version = "0.1.0"[dependencies]anyhow = { workspace = true }bytes = { workspace = true }+macro_aws_config = { path = "../macro_aws_config" }models_sfs = { path = "../models_sfs" }reqwest = { workspace = true }serde = { workspace = true }diff --git a/crates/static_file_service_client/src/put_file.rs b/crates/static_file_service_client/src/put_file.rsindex 71dc24de02..b24b355c04 100644--- a/crates/static_file_service_client/src/put_file.rs+++ b/crates/static_file_service_client/src/put_file.rs@@ -51,12 +51,50 @@ impl StaticFileServiceClient {file_bytes: Bytes,content_type: String,) -> Result<PutFileResponse> {- let body = PutFileRequest {- file_name: file_url.to_string(),- content_type: Some(content_type.to_string()),- extension_data: None,- };+ self.upload(+ PutFileRequest {+ file_name: file_url.to_string(),+ content_type: Some(content_type.clone()),+ extension_data: None,+ },+ file_bytes,+ &content_type,+ )+ .await+ }+ /// Store `bytes` under a name of the caller's choosing.+ ///+ /// [`Self::put_file_with_bytes`] passes the source URL as the file name,+ /// which is right for a file mirrored from somewhere else and wrong for+ /// bytes that were never at a URL — an artifact downloaded from a+ /// presigned link, whose name is `screenshot.png` and whose link must not+ /// end up in the stored metadata.+ pub async fn put_named_bytes(+ &self,+ file_name: &str,+ bytes: Bytes,+ content_type: &str,+ ) -> Result<PutFileResponse> {+ self.upload(+ PutFileRequest {+ file_name: file_name.to_string(),+ content_type: Some(content_type.to_string()),+ extension_data: None,+ },+ bytes,+ content_type,+ )+ .await+ }++ /// Reserve a file and PUT its bytes to the upload URL that comes back.+ async fn upload(+ &self,+ body: PutFileRequest,+ bytes: Bytes,+ content_type: &str,+ ) -> Result<PutFileResponse> {let full_url = format!("{}/internal/file", self.url);let res = self.client.put(&full_url).json(&body).send().await?;@@ -76,13 +114,18 @@ impl StaticFileServiceClient {let put_file_data: PutFileResponse = serde_json::from_value(res)?;- let presigned_url = put_file_data.upload_url.clone();+ // The service mints the presigned URL for a browser on the host+ // (`localhost:4566`); an uploader inside the Docker network has to+ // use LocalStack's own hostname to reach the same object. No-op+ // outside local AWS.+ let presigned_url =+ macro_aws_config::transform_aws_url_for_internal_fetch(&put_file_data.upload_url);let upload_response = self.client.put(&presigned_url)- .header(CONTENT_TYPE, &content_type)- .body(file_bytes.to_vec())+ .header(CONTENT_TYPE, content_type)+ .body(bytes.to_vec()).send().await?;diff --git a/services/agent_harness_service/Cargo.toml b/services/agent_harness_service/Cargo.tomlindex ebdfe98b19..812cfd1a6f 100644--- a/services/agent_harness_service/Cargo.toml+++ b/services/agent_harness_service/Cargo.toml@@ -55,6 +55,7 @@ macro_event_broker = { path = "../../crates/macro_event_broker", features = ["oumacro_queues = { path = "../../crates/macro_queues" }lexical_client = { path = "../../crates/lexical_client" }macro_service_urls = { path = "../../crates/macro_service_urls" }+static_file_service_client = { path = "../../crates/static_file_service_client" }macro_tower_layers = { path = "../../crates/macro_tower_layers" }notification = { path = "../../crates/notification" }rdkafka = { workspace = true }diff --git a/services/agent_harness_service/src/internal_mcp.rs b/services/agent_harness_service/src/internal_mcp.rsindex 10f88bc73f..c0d7717cfc 100644--- a/services/agent_harness_service/src/internal_mcp.rs+++ b/services/agent_harness_service/src/internal_mcp.rs@@ -82,7 +82,8 @@ impl ServerHandler for InternalTools {).with_title("Macro Internal MCP");info.instructions = Some(- "When you create or start working on a pull request, register its URL with Macro using macro_internal.set_pull_request.".into(),+ "When you create or start working on a pull request, register its URL with Macro using macro_internal.set_pull_request. \+ Save any screenshot or screen recording meant for the user into your artifacts directory and refer to it in prose by file name only, never by a sandbox path: Macro re-hosts uploaded artifacts and cannot reach files anywhere else.".into(),);info}diff --git a/services/agent_harness_service/src/main.rs b/services/agent_harness_service/src/main.rsindex a3bd31cb7a..bbcda93a12 100644--- a/services/agent_harness_service/src/main.rs+++ b/services/agent_harness_service/src/main.rs@@ -93,7 +93,7 @@ use config::{Config, Environment};use connection_gateway_client::ConnectionGatewayClient;use containers::{InMemRuntime, RoutedContainers};use cursor_api_key::cipher::{AwsKmsCiphertexts, KmsCursorApiKeyCipher};-use cursor_cloud_agents::api::CURSOR_API_BASE_URL;+use cursor_cloud_agents::api::cursor_api_base_url;use github::domain::service::{InstallationTokenConfig, InstallationTokenService, ReachableRepositoriesService,};@@ -460,7 +460,7 @@ async fn run() -> anyhow::Result<()> {);let cursor_manager = CursorContainerManager::new(cursor_keys.clone(),- CURSOR_API_BASE_URL.to_owned(),+ cursor_api_base_url(),session_repo.clone(),reachable_repositories,ai_usage::pg_recorder(pool.clone()),@@ -470,6 +470,17 @@ async fn run() -> anyhow::Result<()> {},pending_commands.clone(),)+ // Cursor's own artifact links expire in fifteen minutes, so a+ // walkthrough's screenshots and recordings are re-hosted where every+ // other user-visible blob in Macro lives.+ .with_artifact_store(+ cursor_cloud_agents::outbound::static_file_artifacts::StaticFileArtifactStore::new(+ static_file_service_client::StaticFileServiceClient::new(+ config.internal_api_key.clone(),+ macro_service_urls::StaticFileServiceUrl::new()?.to_string(),+ ),+ ),+ ).with_pull_requests(session_pull_requests.clone());let codex_connections: Option<Arc<dyn codex_connection::domain::ConnectionService>> = config.codex_oauth_kms_key_id()@@ -757,7 +768,7 @@ async fn run() -> anyhow::Result<()> {let model_service = Arc::new(AgentModelsServiceImpl::new(VisibleHarnessAccess::new(PgHarnessRepo::new(pool.clone())),InMemoryModels::new(Some(inmem_model_engine), config.inmem_model.clone()),- CursorModels::new(cursor_keys, CURSOR_API_BASE_URL.to_owned()),+ CursorModels::new(cursor_keys, cursor_api_base_url()),macrod_models,model_probe_timeout,));diff --git a/services/authentication_service/src/api/cursor_api_key/list_cursor_models.rs b/services/authentication_service/src/api/cursor_api_key/list_cursor_models.rsindex 6da25be812..47a30767f2 100644--- a/services/authentication_service/src/api/cursor_api_key/list_cursor_models.rs+++ b/services/authentication_service/src/api/cursor_api_key/list_cursor_models.rs@@ -81,7 +81,7 @@ pub async fn handler(let client = CursorClient::new(CursorConfig {api_key: ApiKey::new(key.expose()),- base_url: cursor_cloud_agents::api::CURSOR_API_BASE_URL.to_owned(),+ base_url: cursor_cloud_agents::api::cursor_api_base_url(),model: None,starting_ref: "main".to_owned(),record_dir: None,