返回 CodeWhale
avatars.rs
根目录 / crates / engine / src / extension_host / avatars.rs
1 //! Declarative art registered through the existing reviewed Native owner.
2 //! No script, lifecycle event, input handler, URL, or filesystem authority is
3 //! delivered to clients. Named actions are clips on the caller's existing clock.
4 use super::ManagerShared;
5 use super::protocol::{RegisterParams, RegisterResult};
6 use super::supervisor::HostRequestContext;
7 use super::tier::{HostCohort, HostTier};
8 use base64::{Engine as _, engine::general_purpose::STANDARD};
9 use codewhale_config::PluginAuthority;
10 use codewhale_config::{EntryRef, OwnerRef};
11 use codewhale_plugins::{
12 activation::PluginActivationCapability,
13 manifest::{PluginManifest, ValidatedManifest},
14 };
15 use codewhale_protocol::avatar::{MAX_PACK_BYTES, MAX_PNG_BYTES, Pack, RegisteredPack};
16 use sha2::{Digest, Sha256};
17 use std::{
18 io::Read,
19 path::Path,
20 sync::{Arc, atomic::Ordering},
21 };
22
23 #[derive(Clone, Debug)]
24 pub struct AvatarRegistration {
25 pub handle: u64,
26 pub owner: OwnerRef,
27 pub scope: Option<EntryRef>,
28 pub host_generation: u64,
29 pub content_hash: String,
30 pub pack: Pack,
31 pub png: Arc<Vec<Vec<u8>>>,
32 }
33
34 fn reviewed_bytes(
35 review: &ValidatedManifest,
36 relative: &Path,
37 limit: usize,
38 ) -> Result<Vec<u8>, String> {
39 let expected = review
40 .file_hashes
41 .get(relative)
42 .ok_or("avatar file is outside reviewed inventory")?;
43 let path = review.canonical_root.join(relative);
44 codewhale_util::files::reject_linked_path(&review.canonical_root, &path)
45 .map_err(|e| e.to_string())?;
46 let file = codewhale_util::fs_confined::open_read(&review.canonical_root, &path)
47 .map_err(|e| e.to_string())?;
48 if !file.metadata().map_err(|e| e.to_string())?.is_file() {
49 return Err("avatar asset is not a regular file".into());
50 }
51 let mut bytes = Vec::new();
52 file.take(limit as u64 + 1)
53 .read_to_end(&mut bytes)
54 .map_err(|e| e.to_string())?;
55 if bytes.len() > limit {
56 return Err("avatar file exceeds its byte budget".into());
57 }
58 let mut digest = Sha256::new();
59 digest.update(b"codewhale-plugin-file-bytes-v1\0");
60 digest.update(&bytes);
61 if digest
62 .finalize()
63 .iter()
64 .map(|b| format!("{b:02x}"))
65 .collect::<String>()
66 != *expected
67 {
68 return Err("avatar asset changed since review".into());
69 }
70 Ok(bytes)
71 }
72
73 fn snapshot(authority: &PluginAuthority, relative: &Path) -> Result<(Pack, Vec<Vec<u8>>), String> {
74 codewhale_plugins::registry::verify_plugin_component_authority(
75 authority,
76 PluginActivationCapability::Native,
77 )?;
78 let review = PluginManifest::validate_from_path(&authority.staged_manifest)?;
79 if review.content_hash != authority.content_hash
80 || review.capability_hash != authority.capability_hash
81 {
82 return Err("avatar bundle no longer matches its review".into());
83 }
84 let pack = Pack::parse(&reviewed_bytes(&review, relative, MAX_PACK_BYTES)?)?;
85 let mut images = Vec::new();
86 let mut total = 0;
87 for atlas in &pack.atlases {
88 let path = relative.parent().unwrap_or(Path::new("")).join(atlas);
89 let png = reviewed_bytes(&review, &path, MAX_PNG_BYTES)?;
90 total += png.len();
91 if total > 16 * 1024 * 1024 {
92 return Err("avatar pages exceed the pack byte budget".into());
93 }
94 pack.validate_png(&png)?;
95 image::load_from_memory_with_format(&png, image::ImageFormat::Png)
96 .map_err(|_| "avatar PNG cannot be decoded")?;
97 images.push(png);
98 }
99 codewhale_plugins::registry::verify_plugin_component_authority(
100 authority,
101 PluginActivationCapability::Native,
102 )?;
103 Ok((pack, images))
104 }
105
106 pub(super) async fn admit(
107 shared: &Arc<ManagerShared>,
108 cohort: &HostCohort,
109 host_generation: u64,
110 params: RegisterParams,
111 cx: &HostRequestContext,
112 ) -> RegisterResult {
113 let result = async {
114 params.check_spec()?;
115 if cohort.tier() != HostTier::Plugin || !params.spec.description.is_empty() {
116 return Err("avatar packs require a reviewed Native bundle and a manifest path".into());
117 }
118 if !codewhale_protocol::avatar::relative_asset(&params.spec.name)
119 || !params.spec.name.ends_with(".json")
120 {
121 return Err("avatar manifest must be a bounded bundle-relative JSON path".into());
122 }
123 let authority = shared
124 .live_owner_authority(cohort, |registry| {
125 registry
126 .authority_for(&params.owner)
127 .ok_or("stale avatar owner")?;
128 Ok(params.owner.clone())
129 })?
130 .ok_or("avatar owner has no reviewed authority")?;
131 let relative = std::path::PathBuf::from(&params.spec.name);
132 let (pack, png) = super::skills::bounded_review_check(
133 Arc::clone(&shared.skill_admission),
134 &cx.cancel,
135 move || snapshot(&authority, &relative),
136 )
137 .await?;
138 shared.ready_host(cohort).map_err(|s| s.to_string())?;
139 let runtime = shared
140 .cohort_runtime(cohort)
141 .ok_or_else(|| "cohort runtime gone".to_string())?;
142 let _slot = runtime.host.lock().expect("host lock");
143 if runtime.host_generation.load(Ordering::SeqCst) != host_generation
144 || cx.cancel.is_cancelled()
145 {
146 return Err("avatar admission cancelled or host replaced".into());
147 }
148 shared
149 .registry
150 .lock()
151 .expect("registry lock")
152 .register_avatar(&params, pack, png, host_generation)
153 }
154 .await;
155 match result {
156 Ok(handle) => RegisterResult::Admitted { handle },
157 Err(refused) => {
158 shared.plugin_diagnostic(
159 &params.owner.plugin_id,
160 format!("avatar pack refused: {refused}"),
161 );
162 RegisterResult::Refused { refused }
163 }
164 }
165 }
166
167 /// Workspace-wide decorative catalog: every entry still needs a live owner,
168 /// live composition scope, current host, and current persisted Native receipt.
169 /// Each request is bounded by the same disk-admission semaphore as Native Skills.
170 async fn live(workspace: std::path::PathBuf) -> Vec<AvatarRegistration> {
171 if !super::activation::extension_host_policy_enabled() {
172 return Vec::new();
173 }
174 let manager = super::manager();
175 let shared = Arc::clone(&manager.shared);
176 let admission = Arc::clone(&shared.skill_admission);
177 super::skills::bounded_review_check(
178 admission,
179 &tokio_util::sync::CancellationToken::new(),
180 move || {
181 let entries = shared
182 .registry
183 .lock()
184 .expect("registry lock")
185 .live_avatars();
186 let mut catalog = Vec::new();
187 for entry in entries {
188 let authority = shared
189 .registry
190 .lock()
191 .expect("registry lock")
192 .authority_for(&entry.owner);
193 let Some(authority) = authority else { continue };
194 if authority.workspace != workspace
195 || authority.content_hash != entry.content_hash
196 || codewhale_plugins::registry::verify_plugin_component_authority(
197 &authority,
198 PluginActivationCapability::Native,
199 )
200 .is_err()
201 {
202 continue;
203 }
204 let cohort = shared
205 .registry
206 .lock()
207 .expect("registry lock")
208 .cohort_of(&entry.owner);
209 let Some(cohort) = cohort else {
210 continue;
211 };
212 let Ok(host) = shared.ready_host(&cohort) else {
213 continue;
214 };
215 if host.generation != entry.host_generation {
216 continue;
217 }
218 if !shared
219 .registry
220 .lock()
221 .expect("registry lock")
222 .live_avatars()
223 .iter()
224 .any(|r| r.handle == entry.handle)
225 {
226 continue;
227 }
228 catalog.push(entry);
229 }
230 Ok(catalog)
231 },
232 )
233 .await
234 .unwrap_or_default()
235 }
236
237 pub async fn catalog(workspace: std::path::PathBuf) -> Vec<RegisteredPack> {
238 let mut packs: Vec<_> = live(workspace)
239 .await
240 .into_iter()
241 .map(|entry| RegisteredPack {
242 key: format!("plugin:{}:{}", entry.owner.plugin_id, entry.pack.id),
243 handle: entry.handle,
244 content_hash: entry.content_hash,
245 pack: entry.pack,
246 })
247 .collect();
248 packs.sort_by(|a, b| a.key.cmp(&b.key).then(a.handle.cmp(&b.handle)));
249 packs.dedup_by(|a, b| a.key == b.key);
250 packs
251 }
252 pub async fn atlas(
253 workspace: std::path::PathBuf,
254 handle: u64,
255 page: usize,
256 content_hash: &str,
257 ) -> Option<String> {
258 live(workspace)
259 .await
260 .into_iter()
261 .find(|r| r.handle == handle && r.content_hash == content_hash)
262 .and_then(|r| r.png.get(page).map(|png| STANDARD.encode(png)))
263 }
264
265 #[cfg(test)]
266 mod tests {
267 use super::super::{
268 protocol::{RegisterKind, RegisterSpecWire},
269 registry::OwnerRegistry,
270 test_support::fake_authority,
271 };
272 use super::*;
273 fn params(owner: OwnerRef) -> RegisterParams {
274 RegisterParams {
275 owner,
276 scope: None,
277 kind: RegisterKind::AvatarPack,
278 spec: RegisterSpecWire {
279 name: "avatars/avatar.json".into(),
280 description: String::new(),
281 input_schema: None,
282 argument_hint: None,
283 },
284 }
285 }
286 #[test]
287 fn avatar_registration_is_native_owned_and_revocation_removes_it() {
288 let mut registry = OwnerRegistry::new();
289 let a = registry
290 .begin_owner(
291 HostCohort::reviewed(),
292 "a",
293 "a",
294 Some(fake_authority("a")),
295 "hash-a",
296 )
297 .unwrap();
298 let b = registry
299 .begin_owner(
300 HostCohort::reviewed(),
301 "b",
302 "b",
303 Some(fake_authority("b")),
304 "hash-b",
305 )
306 .unwrap();
307 let pack = Pack::parse(br#"{"version":1,"id":"fixture","name":"Fixture","atlases":["atlas.png"],"columns":1,"rows":1,"tileWidth":8,"tileHeight":8,"actions":{"rest":{"frames":[0],"durationsMs":[100],"poster":0}},"states":{"rest":"rest"}}"#).unwrap();
308 // Ownership does not depend on native artwork. Generate a valid page
309 // so the test also works from a package without repository-only PNGs.
310 let mut page = std::io::Cursor::new(Vec::new());
311 image::RgbaImage::new(
312 u32::from(pack.columns) * u32::from(pack.tile_width),
313 u32::from(pack.rows) * u32::from(pack.tile_height),
314 )
315 .write_to(&mut page, image::ImageFormat::Png)
316 .unwrap();
317 let png = vec![page.into_inner(); pack.atlases.len()];
318 assert!(
319 registry.register(&params(a.clone())).is_err(),
320 "synchronous admission cannot skip review"
321 );
322 let handle = registry
323 .register_avatar(&params(a.clone()), pack.clone(), png.clone(), 7)
324 .unwrap();
325 assert!(
326 registry.live_avatars().is_empty(),
327 "activation must settle first"
328 );
329 registry.mark_active(&a);
330 assert_eq!(registry.live_avatars().len(), 1);
331 registry.unregister(&b, handle);
332 assert_eq!(registry.live_avatars().len(), 1);
333 assert!(
334 registry
335 .register_avatar(&params(a.clone()), pack.clone(), png.clone(), 7)
336 .is_err(),
337 "duplicate"
338 );
339 registry.unregister(&a, handle);
340 assert!(registry.live_avatars().is_empty());
341 let new_handle = registry
342 .register_avatar(&params(a.clone()), pack.clone(), png.clone(), 7)
343 .unwrap();
344 assert_ne!(handle, new_handle);
345 registry.revoke_owner("a");
346 assert!(registry.live_avatars().is_empty());
347 let replacement = registry
348 .begin_owner(
349 HostCohort::reviewed(),
350 "a",
351 "a",
352 Some(fake_authority("a")),
353 "hash-a",
354 )
355 .unwrap();
356 assert_ne!(a.generation, replacement.generation);
357 assert!(
358 registry.register_avatar(&params(a), pack, png, 7).is_err(),
359 "stale owner"
360 );
361 }
362 #[test]
363 fn avatar_snapshot_requires_inventory_hash_and_bounded_file() {
364 use std::io::Write;
365 let dir = tempfile::tempdir().unwrap();
366 let root = dir.path().canonicalize().unwrap();
367 // Reuse a real validated Native bundle; admission also checks its receipt.
368 std::fs::write(root.join("plugin.json"),r#"{"$schema":"https://agent-plugins.org/schemas/plugin.json","name":"avatar-fixture","version":"1.0.0","extensions":{"net.codewhale":{"native":{"path":"index.mjs"}}}}"#).unwrap();
369 std::fs::write(root.join("index.mjs"), "export default () => {};").unwrap();
370 std::fs::write(root.join("avatar.json"), "{}").unwrap();
371 let review = PluginManifest::validate_from_path(&root.join("plugin.json")).unwrap();
372 assert_eq!(
373 reviewed_bytes(&review, Path::new("avatar.json"), 2).unwrap(),
374 b"{}"
375 );
376 assert!(reviewed_bytes(&review, Path::new("avatar.json"), 1).is_err());
377 assert!(reviewed_bytes(&review, Path::new("missing.json"), 100).is_err());
378 std::fs::OpenOptions::new()
379 .append(true)
380 .open(root.join("avatar.json"))
381 .unwrap()
382 .write_all(b" ")
383 .unwrap();
384 assert!(reviewed_bytes(&review, Path::new("avatar.json"), 100).is_err());
385 }
386 }
387
387 lines RUST