beet_agent 0.0.8

ECS agentic workflow patterns
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
use base64::prelude::*;
use beet_core::prelude::*;
use beet_net::prelude::*;
use bevy::ecs::spawn::SpawnIter;
use serde::Deserialize;
use serde::Serialize;
use std::fmt::Debug;
use std::path::PathBuf;

#[derive(Debug, Clone)]
pub enum ContentView<'a> {
	Text(&'a TextContent),
	File(&'a FileContent),
}

/// Portable version of [`Content`]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ContentEnum {
	Text(TextContent),
	File(FileContent),
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ContentVec(pub Vec<ContentEnum>);

impl ContentVec {
	pub fn new() -> Self { Self(Vec::new()) }

	pub fn into_bundle(self) -> impl Bundle {
		let mut texts: Vec<TextContent> = Vec::new();
		let mut files: Vec<FileContent> = Vec::new();
		for content in self.0.into_iter() {
			match content {
				ContentEnum::Text(t) => texts.push(t),
				ContentEnum::File(f) => files.push(f),
			}
		}
		Children::spawn((
			SpawnIter(
				texts
					.into_iter()
					.map(|content| (content, ContentEnded::default())),
			),
			(SpawnIter(
				files
					.into_iter()
					.map(|content| (content, ContentEnded::default())),
			)),
		))
	}

	pub fn first_text(&self) -> Option<&TextContent> {
		self.0.iter().find_map(|c| {
			if let ContentEnum::Text(t) = c {
				Some(t)
			} else {
				None
			}
		})
	}
	pub fn first_file(&self) -> Option<&FileContent> {
		self.0.iter().find_map(|c| {
			if let ContentEnum::File(f) = c {
				Some(f)
			} else {
				None
			}
		})
	}
}


pub trait IntoContentEnum {
	fn into_content_enum(self) -> ContentEnum;
}
impl<'a> IntoContentEnum for &'a str {
	fn into_content_enum(self) -> ContentEnum {
		ContentEnum::Text(TextContent::new(self))
	}
}

impl IntoContentEnum for TextContent {
	fn into_content_enum(self) -> ContentEnum { ContentEnum::Text(self) }
}
impl IntoContentEnum for FileContent {
	fn into_content_enum(self) -> ContentEnum { ContentEnum::File(self) }
}

pub trait IntoContentVec<M> {
	fn into_content_vec(self) -> ContentVec;
}
impl IntoContentVec<Self> for ContentVec {
	fn into_content_vec(self) -> ContentVec { self }
}

impl<T> IntoContentVec<Self> for T
where
	T: IntoContentEnum,
{
	fn into_content_vec(self) -> ContentVec {
		ContentVec(vec![self.into_content_enum()])
	}
}
impl<T> IntoContentVec<Self> for Vec<T>
where
	T: IntoContentEnum,
{
	fn into_content_vec(self) -> ContentVec {
		ContentVec(
			self.into_iter()
				.map(|item| item.into_content_enum())
				.collect(),
		)
	}
}
impl<T1, T2> IntoContentVec<Self> for (T1, T2)
where
	T1: IntoContentEnum,
	T2: IntoContentEnum,
{
	fn into_content_vec(self) -> ContentVec {
		ContentVec(vec![self.0.into_content_enum(), self.1.into_content_enum()])
	}
}
impl<T1, T2, M1, M2> IntoContentVec<(Self, M1, M2)> for (T1, T2)
where
	T1: IntoContentVec<M1>,
	T2: IntoContentVec<M2>,
{
	fn into_content_vec(self) -> ContentVec {
		ContentVec(
			self.0
				.into_content_vec()
				.0
				.into_iter()
				.chain(self.1.into_content_vec().0)
				.collect(),
		)
	}
}

impl ContentView<'_> {
	pub fn as_text(&self) -> Option<&TextContent> {
		match self {
			ContentView::Text(text) => Some(text),
			_ => None,
		}
	}
	pub fn as_file(&self) -> Option<&FileContent> {
		match self {
			ContentView::File(file) => Some(file),
			_ => None,
		}
	}
}

/// Marker component indicating the root entity for an actor's message.
/// Messages must be (possibly nested) descendents of an [`Actor`], and may
/// contain Content either in its entity its descendents.
#[derive(Debug, Default, Clone, Copy, Component)]
pub struct Content {
	pub created: Timestamp,
}

#[derive(Debug, Clone, Copy, Deref)]
pub struct Timestamp(Instant);

impl Default for Timestamp {
	fn default() -> Self { Self(Instant::now()) }
}

/// Added to a [`Content`] when it is finished, and no more content
/// will be added to it.
#[derive(Debug, Default, Clone, Copy, Component)]
pub struct ContentEnded {
	pub completed: Timestamp,
}

#[derive(Default, Component)]
#[require(Content)]
pub struct ReasoningContent;


#[derive(
	Debug, Default, Clone, Deref, DerefMut, Serialize, Deserialize, Component,
)]
#[require(Content)]
#[component(on_add=handle_text_delta)]
pub struct TextContent(pub String);

impl TextContent {
	pub fn new(text: impl AsRef<str>) -> Self {
		TextContent(text.as_ref().to_string())
	}
}

impl std::fmt::Display for TextContent {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		write!(f, "{}", self.0)
	}
}

/// Emitted on a piece of content like a TextContent to indicate a new piece of text
/// was added.
#[derive(Clone, EntityEvent)]
pub struct TextDelta {
	entity: Entity,
	pub value: String,
}


impl TextDelta {
	pub fn new(
		text: impl AsRef<str>,
	) -> impl 'static + Send + Sync + FnOnce(Entity) -> Self {
		let text = text.as_ref().to_string();
		move |entity| Self {
			entity,
			value: text,
		}
	}
}

fn handle_text_delta(mut world: DeferredWorld, cx: HookContext) {
	let initial_text = world
		.entity(cx.entity)
		.get::<TextContent>()
		.unwrap()
		.0
		.clone();
	let mut commands = world.commands();
	let mut entity = commands.entity(cx.entity);

	if !initial_text.is_empty() {
		entity.trigger(TextDelta::new(initial_text));
	}
	entity.insert(OnSpawn::observe(
		|ev: On<TextDelta>,
		 mut text_content: Query<&mut TextContent>|
		 -> Result {
			text_content
				.get_mut(ev.event_target())?
				.0
				.push_str(&ev.value);
			Ok(())
		},
	));
}



#[derive(Debug, Clone, Serialize, Deserialize, Component)]
#[require(Content)]
pub struct FileContent {
	/// The mime type of the data, for example `image/png` or `text/plain`
	pub mime_type: String,
	/// The file path, primarily used for extracting the file name
	pub filename: PathBuf,
	/// The data encoded as a base64 string
	pub data: FileData,
}

impl FileContent {
	/// Create new file content, either from a file path or url
	pub async fn new(path: impl AsRef<str>) -> Result<Self> {
		let path = path.as_ref();
		let mime_type = mime_guess::from_path(path)
			.first_or_octet_stream()
			.essence_str()
			.to_string();
		let filename = PathBuf::from(path);
		let data = FileData::new(path, &mime_type).await?;
		Ok(Self {
			mime_type,
			data,
			filename,
		})
	}

	pub fn new_b64(file_stem: &str, ext: &str, b64: &str) -> Self {
		let mime_type = mime_guess::from_ext(ext)
			.first_or_octet_stream()
			.essence_str()
			.to_string();
		let filename = format!("{}.{}", file_stem, ext).into();
		Self {
			mime_type,
			filename,
			data: FileData::Base64(b64.to_string()),
		}
	}

	pub fn extension(&self) -> &str {
		self.filename.extension().unwrap().to_str().unwrap()
	}

	pub fn is_image(&self) -> bool { self.mime_type.starts_with("image/") }

	/// Returns the file url, or creates a base64 data url
	pub fn into_url(&self) -> String {
		match &self.data {
			FileData::Base64(base_64) => {
				format!("data:{};base64,{}", self.mime_type, base_64)
			}
			FileData::Utf8(utf8) => {
				format!("data:{};charset=utf-8,{}", self.mime_type, utf8)
			}
			FileData::Uri(uri) => uri.clone(),
		}
	}
}


#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum FileData {
	Utf8(String),
	Base64(String),
	Uri(String),
}
impl FileData {
	pub fn new_uri(uri: impl AsRef<str>) -> Self {
		Self::Uri(uri.as_ref().to_string())
	}
	/// Create new file data, either from a file path or url
	pub async fn new(path: impl AsRef<str>, mime_type: &str) -> Result<Self> {
		let path = path.as_ref();
		// If it's a url or already a data: url, keep as Uri
		if is_uri(path) {
			Self::new_uri(path)
		} else if mime_type.starts_with("text/") {
			let bytes = fs_ext::read_async(path).await?;
			let utf8 = String::from_utf8(bytes)?;
			Self::Utf8(utf8)
		} else {
			let bytes = fs_ext::read_async(path).await?;
			let base_64 = BASE64_STANDARD.encode(bytes);
			Self::Base64(base_64)
		}
		.xok()
	}
	pub async fn get(&self) -> Result<Vec<u8>> {
		match self {
			FileData::Utf8(utf8) => Ok(utf8.as_bytes().to_vec()),
			FileData::Base64(b64) => {
				let bytes = BASE64_STANDARD.decode(b64)?;
				Ok(bytes)
			}
			FileData::Uri(uri) => {
				if uri.starts_with("data:") {
					let parts: Vec<&str> = uri.splitn(2, ",").collect();
					if parts.len() != 2 {
						bevybail!("Invalid data URL: {}", uri);
					} else if !parts[0].ends_with(";base64") {
						bevybail!(
							"Only base64-encoded data URLs are supported: {}",
							uri
						);
					} else {
						BASE64_STANDARD.decode(parts[1])?.xok()
					}
				} else if is_uri(uri) {
					Request::get(uri)
						.send()
						.await?
						.into_result()
						.await?
						.bytes()
						.await
						.map(|b| b.to_vec())
				} else {
					// assume workspace relative file path
					AbsPathBuf::new_workspace_rel(uri)?
						.xmap(fs_ext::read_async)
						.await?
						.xok()
				}
			}
		}
	}
}

impl std::fmt::Display for FileContent {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		write!(f, "{} ({})", self.filename.display(), self.data)
	}
}

impl std::fmt::Display for FileData {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		match self {
			FileData::Base64(b64) => {
				write!(f, "base64:{}", &b64[..16.min(b64.len())])
			}
			FileData::Utf8(utf8) => {
				let snippet = if utf8.len() > 16 { &utf8[..16] } else { &utf8 };
				write!(f, "utf8:{}", snippet.escape_debug())
			}
			FileData::Uri(uri) => write!(f, "uri:{}", uri),
		}
	}
}

fn is_uri(path: &str) -> bool {
	let path_lower = path.to_ascii_lowercase();
	path_lower.starts_with("http://")
		|| path_lower.starts_with("https://")
		|| path_lower.starts_with("data:")
}