返回 CodeWhale
tool_media.rs
根目录 / crates / engine / src / core / engine / tool_media.rs
1 //! Publish the rich tool image already admitted to model history through the
2 //! existing immutable session evidence store for authenticated UI retrieval.
3
4 use std::io;
5 use std::path::PathBuf;
6
7 use base64::Engine as _;
8 use base64::engine::general_purpose::STANDARD;
9 use codewhale_tools::ToolResultContentBlock;
10 use serde_json::{Value, json};
11
12 use crate::tools::large_output_router::{
13 EVIDENCE_RETENTION_SECS, EvidenceArtifact, EvidenceRetentionState, evidence_is_expired,
14 publish_evidence_metadata, read_evidence_metadata, unix_millis_now,
15 };
16 use crate::tools::spec::RichToolResult;
17
18 /// No plugin-supplied descriptor may cross this authority boundary. Publication
19 /// failure only omits the UI image; the validated model content remains intact.
20 pub(super) async fn project(
21 mut rich: RichToolResult,
22 session_id: &str,
23 call_id: &str,
24 tool_name: &str,
25 ) -> RichToolResult {
26 if let Some(metadata) = rich.result.metadata.as_mut().and_then(Value::as_object_mut) {
27 metadata.remove("tool_media");
28 }
29 if rich.content_blocks.is_empty() {
30 return rich;
31 }
32 let fallback = rich.result.clone();
33 let session_id = session_id.to_owned();
34 let call_id = call_id.to_owned();
35 let tool_name = tool_name.to_owned();
36 // Image decoding and confined disk publication must not block the reactor.
37 tokio::task::spawn_blocking(move || {
38 let mut rich = crate::image_attach::bound_rich_tool_result(rich);
39 if rich.content_blocks.is_empty() {
40 return rich;
41 }
42 match publish_image(&rich.content_blocks[0], &session_id, &call_id, &tool_name) {
43 Ok(descriptor) => {
44 let metadata = rich.result.metadata.get_or_insert_with(|| json!({}));
45 if !metadata.is_object() {
46 *metadata = json!({});
47 }
48 metadata["tool_media"] = json!([descriptor]);
49 }
50 Err(_) => rich.result.content.push_str(
51 "\n[Tool image preview unavailable: session evidence could not be published.]",
52 ),
53 }
54 rich
55 })
56 .await
57 .unwrap_or_else(|_| {
58 let mut rich = RichToolResult::plain(fallback);
59 rich.result
60 .content
61 .push_str("\n[Tool image omitted: image preparation failed.]");
62 rich
63 })
64 }
65
66 fn publish_image(
67 block: &ToolResultContentBlock,
68 session_id: &str,
69 call_id: &str,
70 tool_name: &str,
71 ) -> io::Result<Value> {
72 let ToolResultContentBlock::Image { mime_type, data } = block;
73 let invalid = || io::Error::new(io::ErrorKind::InvalidData, "invalid tool image evidence");
74 let bytes = STANDARD.decode(data).map_err(|_| invalid())?;
75 // The caller passed the shared rich-image validator; retain the shared decode
76 // guard when deriving dimensions rather than trusting metadata or headers.
77 let (_, width, height) =
78 crate::image_attach::decode_and_guard_image(&bytes).map_err(|_| invalid())?;
79 let identity = serde_json::to_vec(&(session_id, call_id, 0u8)).map_err(|_| invalid())?;
80 let handle = format!(
81 "art_image_{}",
82 codewhale_runtime::hashing::sha256_hex(&identity)
83 );
84 let storage_path = PathBuf::from(codewhale_runtime::artifacts::ARTIFACTS_DIR_NAME)
85 .join(format!("{handle}.image"));
86 let digest = codewhale_runtime::hashing::sha256_hex(&bytes);
87 let now = unix_millis_now();
88 let proposed = EvidenceArtifact {
89 handle: handle.clone(),
90 digest: digest.clone(),
91 size_bytes: bytes.len() as u64,
92 content_type: mime_type.clone(),
93 tool_name: tool_name.to_owned(),
94 call_id: call_id.to_owned(),
95 origin_session: session_id.to_owned(),
96 generation: 1,
97 redacted: false,
98 encoding: "binary".to_owned(),
99 retention_state: EvidenceRetentionState::Live,
100 created_at_unix_ms: now,
101 retain_until_unix_ms: now.saturating_add(EVIDENCE_RETENTION_SECS * 1_000),
102 storage_path: storage_path.clone(),
103 };
104 let matches_image = |existing: &EvidenceArtifact| {
105 existing.digest == digest
106 && existing.size_bytes == bytes.len() as u64
107 && existing.content_type == *mime_type
108 && existing.call_id == call_id
109 && existing.tool_name == tool_name
110 && existing.origin_session == session_id
111 && existing.handle == handle
112 && existing.storage_path == storage_path
113 && existing.generation == 1
114 && existing.encoding == "binary"
115 && !existing.redacted
116 && !evidence_is_expired(existing, unix_millis_now())
117 };
118 let artifact = match read_evidence_metadata(session_id, &handle) {
119 Ok(existing) if matches_image(&existing) => existing,
120 Ok(_) => return Err(invalid()),
121 Err(error) if error.kind() == io::ErrorKind::NotFound => proposed,
122 Err(error) => return Err(error),
123 };
124 codewhale_runtime::artifacts::write_session_relative_immutable(
125 session_id,
126 &storage_path,
127 &bytes,
128 )?;
129 if let Err(error) = publish_evidence_metadata(session_id, &artifact) {
130 // Concurrent identical replays can propose different timestamps. Keep
131 // the winner's immutable lifetime, never replace or extend it.
132 if error.kind() != io::ErrorKind::AlreadyExists
133 || !matches_image(&read_evidence_metadata(session_id, &handle)?)
134 {
135 return Err(error);
136 }
137 }
138 Ok(json!({
139 "version": 1, "session_id": session_id, "artifact_id": handle,
140 "tool_call_id": call_id, "media_type": mime_type, "byte_size": bytes.len(),
141 "sha256": digest, "width": width, "height": height,
142 }))
143 }
144
145 #[cfg(test)]
146 mod tests {
147 use super::*;
148 use crate::tools::spec::ToolResult;
149
150 struct ArtifactRoot(Option<PathBuf>);
151 impl Drop for ArtifactRoot {
152 fn drop(&mut self) {
153 codewhale_runtime::artifacts::set_test_artifact_sessions_root(self.0.take());
154 }
155 }
156
157 fn image_result(pixel: u8, mime: &str) -> RichToolResult {
158 let mut bytes = std::io::Cursor::new(Vec::new());
159 image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(
160 2,
161 1,
162 image::Rgba([pixel, 0, 0, 255]),
163 ))
164 .write_to(&mut bytes, image::ImageFormat::Png)
165 .unwrap();
166 let mut result = ToolResult::success("Captured observation".to_owned());
167 result.metadata = Some(json!({"tool_media":[{"artifact_id":"forged"}],"keep":true}));
168 RichToolResult::with_content_blocks(
169 result,
170 vec![ToolResultContentBlock::Image {
171 mime_type: mime.to_owned(),
172 data: STANDARD.encode(bytes.into_inner()),
173 }],
174 )
175 }
176
177 #[test]
178 fn tool_media_publication_is_immutable_and_replay_preserves_manifest() {
179 // Serialize the shared disk fixture before entering the async runtime.
180 let _guard = codewhale_runtime::artifacts::TEST_ARTIFACT_SESSIONS_GUARD
181 .lock()
182 .unwrap();
183 tokio::runtime::Builder::new_current_thread()
184 .enable_all()
185 .build()
186 .unwrap()
187 .block_on(check_tool_media_publication_is_immutable_and_replay_preserves_manifest());
188 }
189
190 async fn check_tool_media_publication_is_immutable_and_replay_preserves_manifest() {
191 let temp = tempfile::tempdir().unwrap();
192 let _root = ArtifactRoot(
193 codewhale_runtime::artifacts::set_test_artifact_sessions_root(Some(
194 temp.path().to_owned(),
195 )),
196 );
197 let first = project(
198 image_result(3, "image/png"),
199 "media_owner",
200 "call/a",
201 "screenshot",
202 )
203 .await;
204 let metadata = first.result.metadata.as_ref().unwrap();
205 let descriptor = &metadata["tool_media"][0];
206 assert_eq!(descriptor["version"], 1);
207 assert_eq!(descriptor["width"], 2);
208 assert_eq!(descriptor["height"], 1);
209 assert_eq!(metadata["keep"], true);
210 assert_eq!(first.content_blocks.len(), 1);
211 let handle = descriptor["artifact_id"].as_str().unwrap();
212 let manifest_before = read_evidence_metadata("media_owner", handle).unwrap();
213 let replay = project(
214 image_result(3, "image/png"),
215 "media_owner",
216 "call/a",
217 "screenshot",
218 )
219 .await;
220 assert_eq!(replay.result.metadata, first.result.metadata);
221 assert_eq!(
222 serde_json::to_value(read_evidence_metadata("media_owner", handle).unwrap()).unwrap(),
223 serde_json::to_value(&manifest_before).unwrap()
224 );
225 let (parallel_a, parallel_b) = tokio::join!(
226 project(
227 image_result(9, "image/png"),
228 "media_owner",
229 "concurrent",
230 "screenshot"
231 ),
232 project(
233 image_result(9, "image/png"),
234 "media_owner",
235 "concurrent",
236 "screenshot"
237 ),
238 );
239 assert!(
240 parallel_a
241 .result
242 .metadata
243 .as_ref()
244 .unwrap()
245 .get("tool_media")
246 .is_some()
247 );
248 assert_eq!(parallel_a.result.metadata, parallel_b.result.metadata);
249 let conflict = project(
250 image_result(4, "image/png"),
251 "media_owner",
252 "call/a",
253 "screenshot",
254 )
255 .await;
256 assert!(
257 conflict
258 .result
259 .metadata
260 .as_ref()
261 .unwrap()
262 .get("tool_media")
263 .is_none()
264 );
265 assert_eq!(
266 conflict.content_blocks.len(),
267 1,
268 "UI publication conflict must retain validated model image"
269 );
270 assert!(conflict.result.content.contains("preview unavailable"));
271 let other_call = project(
272 image_result(4, "image/png"),
273 "media_owner",
274 "call:a",
275 "screenshot",
276 )
277 .await;
278 assert_ne!(
279 other_call.result.metadata.unwrap()["tool_media"][0]["artifact_id"],
280 descriptor["artifact_id"],
281 "raw call IDs must not collide after sanitization"
282 );
283 let other_session = project(
284 image_result(3, "image/png"),
285 "other_owner",
286 "call/a",
287 "screenshot",
288 )
289 .await;
290 assert_ne!(
291 other_session.result.metadata.unwrap()["tool_media"][0]["artifact_id"],
292 descriptor["artifact_id"]
293 );
294 assert!(
295 !temp.path().join("media_owner.json").exists(),
296 "publication must not create a second session state authority"
297 );
298 }
299
300 #[test]
301 fn tool_media_rejects_spoofed_mime_bytes_and_plugin_descriptors() {
302 // Serialize the shared disk fixture before entering the async runtime.
303 let _guard = codewhale_runtime::artifacts::TEST_ARTIFACT_SESSIONS_GUARD
304 .lock()
305 .unwrap();
306 tokio::runtime::Builder::new_current_thread()
307 .enable_all()
308 .build()
309 .unwrap()
310 .block_on(check_tool_media_rejects_spoofed_mime_bytes_and_plugin_descriptors());
311 }
312
313 async fn check_tool_media_rejects_spoofed_mime_bytes_and_plugin_descriptors() {
314 let temp = tempfile::tempdir().unwrap();
315 let _root = ArtifactRoot(
316 codewhale_runtime::artifacts::set_test_artifact_sessions_root(Some(
317 temp.path().to_owned(),
318 )),
319 );
320 let mime = project(
321 image_result(0, "image/jpeg"),
322 "media_owner",
323 "bad-mime",
324 "screenshot",
325 )
326 .await;
327 assert!(mime.content_blocks.is_empty());
328 assert!(mime.result.metadata.unwrap().get("tool_media").is_none());
329 let mut bad = image_result(0, "image/png");
330 bad.content_blocks = vec![ToolResultContentBlock::Image {
331 mime_type: "image/png".to_owned(),
332 data: STANDARD.encode(b"not an image"),
333 }];
334 let bytes = project(bad, "media_owner", "bad-bytes", "screenshot").await;
335 assert!(bytes.content_blocks.is_empty());
336 assert!(bytes.result.metadata.unwrap().get("tool_media").is_none());
337 let mut plain = image_result(0, "image/png");
338 plain.content_blocks.clear();
339 let plain = project(plain, "media_owner", "no-image", "screenshot").await;
340 assert!(plain.result.metadata.unwrap().get("tool_media").is_none());
341 assert!(!temp.path().join("media_owner").exists());
342 }
343 }
344
344 lines RUST