1use std::collections::HashMap;
6use std::ops::Deref;
7use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
8use std::time::Duration;
9
10use chrono::{DateTime, Utc};
11use futures_util::future::BoxFuture;
12use serde::{Deserialize, Serialize};
13use serde_json::{Map, Value, json};
14use tokio::sync::oneshot;
15
16use super::spec::Spec;
17use super::versioning::Repository;
18use crate::authentification::CredentialsOrApiKey;
19use crate::billing::{PageQuery, Rate};
20use crate::error::{Error, Result};
21use crate::groups::Group;
22use crate::js::{js_number, js_string, present};
23use crate::marmot::web::{HtmlPointer, WebRoom, WebRoomHooks};
24use crate::parrot::generative::{Function, Tool, Usage, tool};
25use crate::shared::schema::{ObjectSchema, Schema};
26use crate::shared::server::{Authorization, Hooks, Presence, Room, connect as connect_server};
27
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
29#[serde(rename_all = "lowercase")]
30pub enum MouseButton {
31 Left,
32 Right,
33 Middle,
34}
35
36#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
38pub struct Point {
39 pub x: f64,
40 pub y: f64,
41}
42
43#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
45#[serde(rename_all = "lowercase")]
46pub enum WindowApp {
47 Web,
48 Files,
49 File,
50 Terminal,
51}
52
53#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
55#[serde(rename_all = "lowercase")]
56pub enum GrepOutput {
57 Files,
58 Lines,
59 Count,
60}
61
62#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
64#[serde(rename_all = "lowercase")]
65pub enum ProcessSort {
66 Cpu,
67 Memory,
68}
69
70#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
72#[serde(rename_all = "UPPERCASE")]
73pub enum ProcessSignal {
74 Term,
75 Kill,
76}
77
78#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
80#[serde(rename_all = "lowercase")]
81pub enum InternetMode {
82 Private,
83 Public,
84}
85
86#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
89pub struct KeyStroke {
90 pub key: String,
91 pub down: bool,
92}
93
94#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
97#[serde(
98 tag = "kind",
99 rename_all = "camelCase",
100 rename_all_fields = "camelCase"
101)]
102pub enum MachineTool {
103 Move {
104 x: f64,
105 y: f64,
106 },
107 Click {
110 #[serde(default, skip_serializing_if = "Option::is_none")]
111 x: Option<f64>,
112 #[serde(default, skip_serializing_if = "Option::is_none")]
113 y: Option<f64>,
114 #[serde(default, skip_serializing_if = "Option::is_none")]
115 down_ms: Option<f64>,
116 #[serde(default, skip_serializing_if = "Option::is_none")]
117 button: Option<MouseButton>,
118 #[serde(default, skip_serializing_if = "Option::is_none")]
119 count: Option<f64>,
120 },
121 Drag {
122 to: Point,
123 #[serde(default, skip_serializing_if = "Option::is_none")]
124 from: Option<Point>,
125 #[serde(default, skip_serializing_if = "Option::is_none")]
126 down_ms: Option<f64>,
127 },
128 Scroll {
129 #[serde(default, skip_serializing_if = "Option::is_none")]
130 delta_x: Option<f64>,
131 #[serde(default, skip_serializing_if = "Option::is_none")]
132 delta_y: Option<f64>,
133 },
134 Type {
135 text: String,
136 },
137 Fill {
141 secret: String,
142 },
143 RequestSecret {
147 name: String,
148 description: String,
149 #[serde(default, skip_serializing_if = "Option::is_none")]
150 sites: Option<Vec<String>>,
151 #[serde(default, skip_serializing_if = "Option::is_none")]
152 hosts: Option<Vec<String>>,
153 },
154 Press {
158 x: f64,
159 y: f64,
160 #[serde(default, skip_serializing_if = "Option::is_none")]
161 button: Option<MouseButton>,
162 },
163 Pointer {
164 x: f64,
165 y: f64,
166 },
167 Release {
168 x: f64,
169 y: f64,
170 #[serde(default, skip_serializing_if = "Option::is_none")]
171 button: Option<MouseButton>,
172 },
173 Wheel {
174 x: f64,
175 y: f64,
176 delta_x: f64,
177 delta_y: f64,
178 },
179 Keys {
180 strokes: Vec<KeyStroke>,
181 },
182 Windows,
183 Focus {
184 window: f64,
185 },
186 Place {
187 window: f64,
188 x: f64,
189 y: f64,
190 },
191 Resize {
192 window: f64,
193 width: f64,
194 height: f64,
195 },
196 Close {
197 window: f64,
198 },
199 Reload {
201 window: f64,
202 },
203 Open {
208 app: WindowApp,
209 #[serde(default, skip_serializing_if = "Option::is_none")]
210 url: Option<String>,
211 #[serde(default, skip_serializing_if = "Option::is_none")]
212 path: Option<String>,
213 #[serde(default, skip_serializing_if = "Option::is_none")]
214 command: Option<String>,
215 },
216 Key {
218 keys: Vec<String>,
219 #[serde(default, skip_serializing_if = "Option::is_none")]
220 window: Option<f64>,
221 },
222 PageHtml {
225 #[serde(default, skip_serializing_if = "Option::is_none")]
226 window: Option<f64>,
227 },
228 PageScript {
231 script: String,
232 #[serde(default, skip_serializing_if = "Option::is_none")]
233 window: Option<f64>,
234 },
235 List {
236 #[serde(default, skip_serializing_if = "Option::is_none")]
237 path: Option<String>,
238 #[serde(default, skip_serializing_if = "Option::is_none")]
239 pattern: Option<String>,
240 },
241 Grep {
242 pattern: String,
243 #[serde(default, skip_serializing_if = "Option::is_none")]
244 path: Option<String>,
245 #[serde(default, skip_serializing_if = "Option::is_none")]
246 glob: Option<String>,
247 #[serde(default, skip_serializing_if = "Option::is_none")]
248 ignore_case: Option<bool>,
249 #[serde(default, skip_serializing_if = "Option::is_none")]
250 context: Option<f64>,
251 #[serde(default, skip_serializing_if = "Option::is_none")]
252 output: Option<GrepOutput>,
253 #[serde(default, skip_serializing_if = "Option::is_none")]
254 max: Option<f64>,
255 },
256 Read {
257 path: String,
258 #[serde(default, skip_serializing_if = "Option::is_none")]
259 line: Option<f64>,
260 #[serde(default, skip_serializing_if = "Option::is_none")]
261 before: Option<f64>,
262 #[serde(default, skip_serializing_if = "Option::is_none")]
263 after: Option<f64>,
264 },
265 Write {
267 path: String,
268 text: String,
269 #[serde(default, skip_serializing_if = "Option::is_none")]
270 line: Option<f64>,
271 },
272 Replace {
273 path: String,
274 old: String,
275 new: String,
276 #[serde(default, skip_serializing_if = "Option::is_none")]
277 all: Option<bool>,
278 },
279 Remove {
280 path: String,
281 start: f64,
282 end: f64,
283 },
284 Processes {
285 #[serde(default, skip_serializing_if = "Option::is_none")]
286 sort: Option<ProcessSort>,
287 #[serde(default, skip_serializing_if = "Option::is_none")]
288 limit: Option<f64>,
289 #[serde(default, skip_serializing_if = "Option::is_none")]
290 filter: Option<String>,
291 },
292 Kill {
294 pid: f64,
295 #[serde(default, skip_serializing_if = "Option::is_none")]
296 signal: Option<ProcessSignal>,
297 },
298 Internet {
301 mode: InternetMode,
302 },
303 Wait {
306 seconds: f64,
307 },
308}
309
310impl MachineTool {
311 fn is_input(&self) -> bool {
313 matches!(
314 self,
315 MachineTool::Move { .. }
316 | MachineTool::Click { .. }
317 | MachineTool::Drag { .. }
318 | MachineTool::Scroll { .. }
319 | MachineTool::Type { .. }
320 | MachineTool::Press { .. }
321 | MachineTool::Pointer { .. }
322 | MachineTool::Release { .. }
323 | MachineTool::Wheel { .. }
324 | MachineTool::Keys { .. }
325 )
326 }
327}
328
329pub const WAIT_MAX_SECONDS: u64 = 600;
331
332#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
334#[serde(rename_all = "lowercase")]
335pub enum WindowKind {
336 App,
337 Web,
338 Files,
339 Preview,
340 Terminal,
341 Editor,
342}
343
344#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
346pub struct Window {
347 pub id: u64,
349 pub kind: WindowKind,
350 pub app: String,
352 pub title: String,
353 pub x: f64,
354 pub y: f64,
355 pub width: f64,
356 pub height: f64,
357 pub focused: bool,
358}
359
360fn truthy(value: &Value) -> bool {
361 match value {
362 Value::Null => false,
363 Value::Bool(value) => *value,
364 Value::Number(number) => number
365 .as_f64()
366 .is_some_and(|number| number != 0.0 && !number.is_nan()),
367 Value::String(text) => !text.is_empty(),
368 _ => true,
369 }
370}
371
372impl Window {
373 pub fn from_json(json: &Value) -> Window {
374 let kind = match json["kind"].as_str() {
375 Some("web") => WindowKind::Web,
376 Some("files") => WindowKind::Files,
377 Some("preview") => WindowKind::Preview,
378 Some("terminal") => WindowKind::Terminal,
379 Some("editor") => WindowKind::Editor,
380 _ => WindowKind::App,
381 };
382 let kind_name = match kind {
383 WindowKind::App => "app",
384 WindowKind::Web => "web",
385 WindowKind::Files => "files",
386 WindowKind::Preview => "preview",
387 WindowKind::Terminal => "terminal",
388 WindowKind::Editor => "editor",
389 };
390 Window {
391 id: js_number(json.get("id")) as u64,
392 kind,
393 app: js_string(json.get("app"), kind_name),
394 title: js_string(json.get("title"), ""),
395 x: json["x"].as_f64().unwrap_or_default(),
396 y: json["y"].as_f64().unwrap_or_default(),
397 width: json["width"].as_f64().unwrap_or_default(),
398 height: json["height"].as_f64().unwrap_or_default(),
399 focused: truthy(&json["focused"]),
400 }
401 }
402}
403
404#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
406#[serde(rename_all = "lowercase")]
407pub enum FilesView {
408 List,
409 Cozy,
410}
411
412#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
414pub struct FilesState {
415 pub path: String,
416 pub view: FilesView,
417}
418
419impl FilesState {
420 pub fn from_json(json: &Value) -> FilesState {
421 FilesState {
422 path: js_string(json.get("path"), ""),
423 view: if json["view"] == "cozy" {
424 FilesView::Cozy
425 } else {
426 FilesView::List
427 },
428 }
429 }
430}
431
432#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
433#[serde(rename_all = "UPPERCASE")]
434pub enum MachineStatus {
435 Booting,
436 Running,
437 Stopping,
438 Stopped,
439 Failed,
440}
441
442#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
443pub struct Viewport {
444 pub width: f64,
445 pub height: f64,
446}
447
448#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
450pub struct ViewportBounds {
451 pub min: Viewport,
452 pub max: Viewport,
453}
454
455pub const VIEWPORT: ViewportBounds = ViewportBounds {
457 min: Viewport {
458 width: 640.0,
459 height: 400.0,
460 },
461 max: Viewport {
462 width: 2560.0,
463 height: 1600.0,
464 },
465};
466
467pub fn clamp_viewport(size: Viewport) -> Viewport {
469 Viewport {
470 width: size
471 .width
472 .clamp(VIEWPORT.min.width, VIEWPORT.max.width)
473 .round(),
474 height: size
475 .height
476 .clamp(VIEWPORT.min.height, VIEWPORT.max.height)
477 .round(),
478 }
479}
480
481const APP_FRAME: u8 = 1;
483const APP_FRAME_KEY: u8 = 1;
485const APP_FRAME_HEADER: usize = 22;
488
489#[derive(Debug, Clone, PartialEq, Eq)]
495pub struct AppFrame {
496 pub window: u32,
497 pub seq: u32,
498 pub key: bool,
499 pub window_width: u32,
500 pub window_height: u32,
501 pub x: u32,
502 pub y: u32,
503 pub width: u32,
504 pub height: u32,
505 pub jpeg: Vec<u8>,
506}
507
508impl AppFrame {
509 pub fn from_bytes(data: &[u8]) -> Option<AppFrame> {
511 if data.len() < APP_FRAME_HEADER || data[0] != APP_FRAME {
512 return None;
513 }
514 let u32_at =
515 |at: usize| u32::from_be_bytes([data[at], data[at + 1], data[at + 2], data[at + 3]]);
516 let u16_at = |at: usize| u32::from(u16::from_be_bytes([data[at], data[at + 1]]));
517 Some(AppFrame {
518 window: u32_at(2),
519 seq: u32_at(6),
520 key: data[1] & APP_FRAME_KEY != 0,
521 window_width: u16_at(10),
522 window_height: u16_at(12),
523 x: u16_at(14),
524 y: u16_at(16),
525 width: u16_at(18),
526 height: u16_at(20),
527 jpeg: data[APP_FRAME_HEADER..].to_vec(),
528 })
529 }
530}
531
532#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
534pub struct RoomAgent {
535 pub id: String,
536 pub name: String,
537 #[serde(default, skip_serializing_if = "Option::is_none")]
538 pub icon: Option<String>,
539}
540
541impl RoomAgent {
542 pub fn from_json(json: &Value) -> RoomAgent {
543 RoomAgent {
544 id: match &json["id"] {
545 Value::String(id) => id.clone(),
546 id => id.to_string(),
547 },
548 name: match &json["name"] {
549 Value::Null => "Agent".to_string(),
550 Value::String(name) => name.clone(),
551 name => name.to_string(),
552 },
553 icon: json["icon"]
554 .as_str()
555 .filter(|icon| !icon.is_empty())
556 .map(str::to_string),
557 }
558 }
559}
560
561pub trait MachineRoomHooks: Send + Sync {
564 fn on_cursor(&self, _room: &MachineRoom, _cursor: &HtmlPointer) {}
566 fn on_tool(&self, _room: &MachineRoom, _tool: &MachineTool) {}
569 fn on_closed(&self, _room: &MachineRoom) {}
570 fn on_presence(&self, _room: &MachineRoom) {}
571 fn on_control(&self, _room: &MachineRoom) {}
573 fn web(&self) -> Option<Arc<dyn WebRoomHooks>> {
574 None
575 }
576 fn on_window(&self, _room: &MachineRoom, _window: &Window) {}
578 fn on_window_closed(&self, _room: &MachineRoom, _id: u64) {}
579 fn on_files(&self, _room: &MachineRoom, _window: u64, _files: &FilesState) {}
581 fn on_status(&self, _room: &MachineRoom) {}
582 fn on_private(&self, _room: &MachineRoom) {}
584 fn on_agent_step(&self, _room: &MachineRoom, _step: &AgentStep) {}
586 fn on_app_frame(&self, _room: &MachineRoom, _frame: &AppFrame) {}
588}
589
590impl MachineRoomHooks for () {}
591
592#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
596#[serde(rename_all = "camelCase")]
597pub struct AgentStep {
598 pub agent: String,
600 pub step: u64,
602 pub call: u64,
604 pub tool: String,
605 #[serde(default)]
606 pub args: Map<String, Value>,
607 #[serde(default)]
609 pub result: String,
610 #[serde(default, skip_serializing_if = "Option::is_none")]
612 pub error: Option<String>,
613 #[serde(default)]
615 pub model_ms: f64,
616 #[serde(default)]
617 pub tool_ms: f64,
618 #[serde(default)]
619 pub usage: Usage,
620}
621
622#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
624#[serde(rename_all = "camelCase")]
625pub struct Caption {
626 pub start_ms: f64,
627 pub end_ms: f64,
628 pub text: String,
629}
630
631impl Caption {
632 pub fn from_json(json: &Value) -> Caption {
633 let ms = |key: &str| present(json.get(key)).map_or(0.0, |ms| js_number(Some(ms)));
634 Caption {
635 start_ms: ms("startMs"),
636 end_ms: ms("endMs"),
637 text: js_string(json.get("text"), ""),
638 }
639 }
640}
641
642#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
644#[serde(rename_all = "lowercase")]
645pub enum MediaKind {
646 Video,
647 Photo,
648}
649
650#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
655#[serde(rename_all = "camelCase")]
656pub struct Media {
657 pub kind: MediaKind,
658 pub title: String,
659 pub path: String,
660 #[serde(default, skip_serializing_if = "Option::is_none")]
661 pub duration_ms: Option<f64>,
662 #[serde(default, skip_serializing_if = "Option::is_none")]
663 pub captions: Option<Vec<Caption>>,
664 #[serde(default, skip_serializing_if = "Option::is_none")]
665 pub frame_rate: Option<f64>,
666}
667
668impl Media {
669 pub fn from_json(json: &Value) -> Media {
670 Media {
671 kind: if json["kind"] == "video" {
672 MediaKind::Video
673 } else {
674 MediaKind::Photo
675 },
676 title: js_string(json.get("title"), ""),
677 path: js_string(json.get("path"), ""),
678 duration_ms: present(json.get("durationMs")).map(|ms| js_number(Some(ms))),
679 captions: json["captions"]
680 .as_array()
681 .map(|captions| captions.iter().map(Caption::from_json).collect()),
682 frame_rate: present(json.get("frameRate")).map(|rate| js_number(Some(rate))),
683 }
684 }
685}
686
687const INPUT_MS: u64 = 30_000;
688const CONTROL_MS: u64 = 30_000;
689const CALL_MS: u64 = 60_000;
690const EXEC_MS: u64 = 120_000;
691const STOP_MS: u64 = 10 * 60_000;
692
693pub type MachineToolInvoker =
695 Arc<dyn Fn(MachineTool) -> BoxFuture<'static, Result<Map<String, Value>>> + Send + Sync>;
696
697pub type ExecInvoker = Arc<
700 dyn Fn(String, Option<f64>) -> BoxFuture<'static, Result<Map<String, Value>>> + Send + Sync,
701>;
702
703fn says(text: &str) -> Value {
705 json!({
706 "type": "OBJECT",
707 "properties": { "text": { "type": "STRING", "description": text } },
708 "required": ["text"],
709 })
710}
711
712fn optional_text(p: &Value, key: &str) -> Option<String> {
713 present(p.get(key)).map(|value| js_string(Some(value), ""))
714}
715
716fn optional_number(p: &Value, key: &str) -> Option<f64> {
717 present(p.get(key)).map(|value| js_number(Some(value)))
718}
719
720const FILE_PATH: &str = "The file";
721const FILE_LINES: &str = "The file's lines now";
722
723fn list_returns() -> Value {
725 json!({
726 "type": "OBJECT",
727 "properties": {
728 "path": { "type": "STRING", "description": "The folder" },
729 "entries": {
730 "type": "ARRAY",
731 "description": "Its files and folders by name, the first 500",
732 "items": {
733 "type": "OBJECT",
734 "properties": {
735 "name": { "type": "STRING", "description": "Its path from the folder" },
736 "folder": { "type": "BOOLEAN", "description": "A folder" },
737 "size": { "type": "INTEGER", "description": "Bytes, 0 for a folder" },
738 "writable": { "type": "BOOLEAN", "description": "You may write over the file, or add to the folder" },
739 },
740 "required": ["name", "folder", "size", "writable"],
741 },
742 },
743 "more": { "type": "INTEGER", "description": "Entries past the first 500" },
744 },
745 "required": ["path", "entries", "more"],
746 })
747}
748
749fn grep_returns() -> Value {
751 json!({
752 "type": "OBJECT",
753 "properties": {
754 "files": { "type": "ARRAY", "description": "With output files: the matching files", "items": { "type": "STRING" } },
755 "counts": {
756 "type": "ARRAY",
757 "description": "With output count: each matching file's count of matching lines",
758 "items": {
759 "type": "OBJECT",
760 "properties": {
761 "path": { "type": "STRING", "description": FILE_PATH },
762 "count": { "type": "INTEGER", "description": "Matching lines" },
763 },
764 "required": ["path", "count"],
765 },
766 },
767 "lines": {
768 "type": "ARRAY",
769 "description": "With output lines: the matching lines, with context lines around them",
770 "items": {
771 "type": "OBJECT",
772 "properties": {
773 "path": { "type": "STRING", "description": FILE_PATH },
774 "line": { "type": "INTEGER", "description": "Its line number" },
775 "text": { "type": "STRING", "description": "The line, at most 2,000 characters" },
776 "match": { "type": "BOOLEAN", "description": "It matched; false for a context line" },
777 "cut": { "type": "BOOLEAN", "description": "It was longer than 2,000 characters and was cut" },
778 },
779 "required": ["path", "line", "text", "match"],
780 },
781 },
782 "more": { "type": "INTEGER", "description": "Results past max" },
783 },
784 "required": ["more"],
785 })
786}
787
788fn read_returns() -> Value {
790 json!({
791 "type": "OBJECT",
792 "properties": {
793 "path": { "type": "STRING", "description": FILE_PATH },
794 "text": { "type": "STRING", "description": "Lines from to to, exactly as the file has them, line breaks included" },
795 "from": { "type": "INTEGER", "description": "The first line returned, 0 for an empty file" },
796 "to": { "type": "INTEGER", "description": "The last line returned. It stops early when the lines pass 100,000 characters" },
797 "total": { "type": "INTEGER", "description": "The file's lines" },
798 "cut": { "type": "BOOLEAN", "description": "The one line returned is longer than 100,000 characters and was cut" },
799 },
800 "required": ["path", "text", "from", "to", "total"],
801 })
802}
803
804fn write_returns() -> Value {
806 json!({
807 "type": "OBJECT",
808 "properties": {
809 "path": { "type": "STRING", "description": FILE_PATH },
810 "created": { "type": "BOOLEAN", "description": "Without line: it made a new file" },
811 "from": { "type": "INTEGER", "description": "With line: the first inserted line" },
812 "to": { "type": "INTEGER", "description": "With line: the last inserted line" },
813 "total": { "type": "INTEGER", "description": FILE_LINES },
814 },
815 "required": ["path", "total"],
816 })
817}
818
819fn replace_returns() -> Value {
821 json!({
822 "type": "OBJECT",
823 "properties": {
824 "path": { "type": "STRING", "description": FILE_PATH },
825 "replaced": { "type": "INTEGER", "description": "Matches replaced" },
826 "from": { "type": "INTEGER", "description": "The first line of the first replacement" },
827 "to": { "type": "INTEGER", "description": "Its last line" },
828 "total": { "type": "INTEGER", "description": FILE_LINES },
829 },
830 "required": ["path", "replaced", "from", "to", "total"],
831 })
832}
833
834fn remove_returns() -> Value {
836 json!({
837 "type": "OBJECT",
838 "properties": {
839 "path": { "type": "STRING", "description": FILE_PATH },
840 "removed": { "type": "INTEGER", "description": "Lines removed" },
841 "total": { "type": "INTEGER", "description": FILE_LINES },
842 },
843 "required": ["path", "removed", "total"],
844 })
845}
846
847pub fn parrot_tools(invoke: MachineToolInvoker, exec: ExecInvoker) -> Vec<Tool> {
852 let mut tools = Vec::new();
853 let mut add = |name: &str,
854 description: &str,
855 properties: Value,
856 required: &[&str],
857 returns: Value,
858 build: fn(&Value) -> MachineTool| {
859 let mut parameters = json!({ "type": "OBJECT", "properties": properties });
860 if !required.is_empty() {
861 parameters["required"] = json!(required);
862 }
863 let invoke = invoke.clone();
864 tools.push(tool(
865 name,
866 description,
867 parameters,
868 returns,
869 move |params: Value, _progress| {
870 let params = if params.is_null() { json!({}) } else { params };
871 let run = invoke(build(¶ms));
872 Box::pin(run)
873 },
874 ));
875 };
876
877 add(
878 "move",
879 "Move the pointer to desktop coordinates. Does not click.",
880 json!({
881 "x": { "type": "NUMBER", "description": "X pixel" },
882 "y": { "type": "NUMBER", "description": "Y pixel" },
883 }),
884 &["x", "y"],
885 says("Where the pointer went"),
886 |p| MachineTool::Move {
887 x: js_number(p.get("x")),
888 y: js_number(p.get("y")),
889 },
890 );
891 add(
892 "click",
893 "Click. Optional coordinates move there first. downMs is how long the button stays down. button right opens context menus; count 2 double clicks.",
894 json!({
895 "x": { "type": "NUMBER", "description": "X pixel" },
896 "y": { "type": "NUMBER", "description": "Y pixel" },
897 "downMs": { "type": "NUMBER", "description": "Hold duration in ms" },
898 "button": { "type": "STRING", "enum": ["left", "right", "middle"], "description": "Mouse button, default left" },
899 "count": { "type": "NUMBER", "description": "Clicks in a row: 2 double clicks, 3 triple clicks. Default 1" },
900 }),
901 &[],
902 says("What the click landed on, or that nothing on the screen changed"),
903 |p| MachineTool::Click {
904 x: optional_number(p, "x"),
905 y: optional_number(p, "y"),
906 down_ms: optional_number(p, "downMs"),
907 button: match p.get("button").and_then(Value::as_str) {
908 Some("right") => Some(MouseButton::Right),
909 Some("middle") => Some(MouseButton::Middle),
910 _ => None,
911 },
912 count: optional_number(p, "count"),
913 },
914 );
915 add(
916 "drag",
917 "Drag from an optional start point to a destination.",
918 json!({
919 "to": { "type": "OBJECT", "description": "Destination {x,y}" },
920 "from": { "type": "OBJECT", "description": "Start {x,y}" },
921 "downMs": { "type": "NUMBER", "description": "Hold at the end in ms" },
922 }),
923 &["to"],
924 says("What the drag did"),
925 |p| MachineTool::Drag {
926 to: Point {
927 x: js_number(p.get("to").and_then(|to| to.get("x"))),
928 y: js_number(p.get("to").and_then(|to| to.get("y"))),
929 },
930 from: p.get("from").filter(|from| truthy(from)).map(|from| Point {
931 x: js_number(from.get("x")),
932 y: js_number(from.get("y")),
933 }),
934 down_ms: optional_number(p, "downMs"),
935 },
936 );
937 add(
938 "scroll",
939 "Scroll with the wheel at the current pointer.",
940 json!({
941 "deltaX": { "type": "NUMBER", "description": "Horizontal wheel delta" },
942 "deltaY": { "type": "NUMBER", "description": "Vertical wheel delta" },
943 }),
944 &[],
945 says("Whether anything moved, and what is under the pointer when nothing did"),
946 |p| MachineTool::Scroll {
947 delta_x: optional_number(p, "deltaX"),
948 delta_y: optional_number(p, "deltaY"),
949 },
950 );
951 add(
952 "type",
953 "Type text at the current focus.",
954 json!({
955 "text": { "type": "STRING", "description": "Text to type" },
956 }),
957 &["text"],
958 says("Whether the text went in, and which window took it"),
959 |p| MachineTool::Type {
960 text: js_string(p.get("text"), ""),
961 },
962 );
963 add(
964 "fill",
965 "Type one of the repository's secrets into the focused field of a Web window, by its name. You never see its value: the page shows dots, and text holding it reads [NAME]. Click the field first. Only on the sites the secret allows.",
966 json!({
967 "secret": { "type": "STRING", "description": "The secret's name, like AMAZON_PASSWORD" },
968 }),
969 &["secret"],
970 says("That the secret went into the focused field, or why it couldn't"),
971 |p| MachineTool::Fill {
972 secret: js_string(p.get("secret"), ""),
973 },
974 );
975 add(
976 "requestSecret",
977 "Ask the repository's owner for a secret it doesn't have yet, like a password or an API key: they're texted a link to add it. Never ask for one in a message or type one in yourself. Do what you can meanwhile; the task picks back up once they answer.",
978 json!({
979 "name": { "type": "STRING", "description": "Its name: capital letters, digits and underscores, like AMAZON_PASSWORD" },
980 "description": { "type": "STRING", "description": "What it is and why you need it, for the owner" },
981 "sites": { "type": "ARRAY", "items": { "type": "STRING" }, "description": "Sites it would be typed into, as hosts like amazon.com" },
982 "hosts": { "type": "ARRAY", "items": { "type": "STRING" }, "description": "API hosts programs would send it to, like api.openai.com" },
983 }),
984 &["name", "description"],
985 says("That the owner was asked, or why not"),
986 |p| {
987 let strings = |key: &str| {
988 p.get(key).and_then(Value::as_array).map(|list| {
989 list.iter()
990 .map(|value| js_string(Some(value), ""))
991 .collect::<Vec<String>>()
992 })
993 };
994 MachineTool::RequestSecret {
995 name: js_string(p.get("name"), ""),
996 description: js_string(p.get("description"), ""),
997 sites: strings("sites"),
998 hosts: strings("hosts"),
999 }
1000 },
1001 );
1002
1003 add(
1004 "windows",
1005 "List every open desktop window with its id, kind, app, title, position, size, and focus.",
1006 json!({}),
1007 &[],
1008 says("Every open window, one per line: id, kind, app, title, position, size and focus"),
1009 |_| MachineTool::Windows,
1010 );
1011 add(
1012 "focus",
1013 "Bring a window to the front and give it keyboard focus.",
1014 json!({
1015 "window": { "type": "NUMBER", "description": "Window id" },
1016 }),
1017 &["window"],
1018 says("Which window has focus now"),
1019 |p| MachineTool::Focus {
1020 window: js_number(p.get("window")),
1021 },
1022 );
1023 add(
1024 "place",
1025 "Move a window so its top left corner is at desktop coordinates.",
1026 json!({
1027 "window": { "type": "NUMBER", "description": "Window id" },
1028 "x": { "type": "NUMBER", "description": "Desktop X pixel" },
1029 "y": { "type": "NUMBER", "description": "Desktop Y pixel" },
1030 }),
1031 &["window", "x", "y"],
1032 says("Where the window is now"),
1033 |p| MachineTool::Place {
1034 window: js_number(p.get("window")),
1035 x: js_number(p.get("x")),
1036 y: js_number(p.get("y")),
1037 },
1038 );
1039 add(
1040 "resize",
1041 "Resize a window. Apps redraw at the new size.",
1042 json!({
1043 "window": { "type": "NUMBER", "description": "Window id" },
1044 "width": { "type": "NUMBER", "description": "Width in pixels" },
1045 "height": { "type": "NUMBER", "description": "Height in pixels" },
1046 }),
1047 &["window", "width", "height"],
1048 says("The window's new size"),
1049 |p| MachineTool::Resize {
1050 window: js_number(p.get("window")),
1051 width: js_number(p.get("width")),
1052 height: js_number(p.get("height")),
1053 },
1054 );
1055 add(
1056 "close",
1057 "Close a window.",
1058 json!({
1059 "window": { "type": "NUMBER", "description": "Window id" },
1060 }),
1061 &["window"],
1062 says("That the window closed"),
1063 |p| MachineTool::Close {
1064 window: js_number(p.get("window")),
1065 },
1066 );
1067 add(
1068 "reload",
1069 "Reload a Web window after its page's files change, so it shows them. Previews follow their file on their own, and reload too.",
1070 json!({
1071 "window": { "type": "NUMBER", "description": "Window id" },
1072 }),
1073 &["window"],
1074 says("That the window reloaded"),
1075 |p| MachineTool::Reload {
1076 window: js_number(p.get("window")),
1077 },
1078 );
1079 add(
1080 "open",
1081 "Open a window on the desktop: web opens a Web window at url (http or https; serve local pages over HTTP first, since file:// pages don't load); files opens a Files window at a folder; file opens a file, text and code in an editor (save with ctrl s) and images, PDFs, video and audio in a preview; terminal opens a terminal, running command in view; when it ends the window stays open at a prompt, so people can read the result and you can type more. Editors and previews follow their file as it changes.",
1082 json!({
1083 "app": { "type": "STRING", "enum": ["web", "files", "file", "terminal"], "description": "web, files, file or terminal" },
1084 "url": { "type": "STRING", "description": "http or https address for a web window" },
1085 "path": { "type": "STRING", "description": "Folder for files, or the file to open, relative to /repository" },
1086 "command": { "type": "STRING", "description": "Command for a terminal to run in view" },
1087 }),
1088 &["app"],
1089 says("The window that opened"),
1090 |p| MachineTool::Open {
1091 app: match p.get("app").and_then(Value::as_str) {
1092 Some("files") => WindowApp::Files,
1093 Some("file") => WindowApp::File,
1094 Some("terminal") => WindowApp::Terminal,
1095 _ => WindowApp::Web,
1096 },
1097 url: optional_text(p, "url"),
1098 path: optional_text(p, "path"),
1099 command: optional_text(p, "command"),
1100 },
1101 );
1102 add(
1103 "key",
1104 "Press a key chord, like ctrl and s together. Focuses the window first when given. ctrl r or f5 on a Web window reloads it.",
1105 json!({
1106 "keys": { "type": "ARRAY", "items": { "type": "STRING" }, "description": "Keys held together, e.g. [\"ctrl\", \"s\"]" },
1107 "window": { "type": "NUMBER", "description": "Window id to focus first" },
1108 }),
1109 &["keys"],
1110 says("Which window took the keys"),
1111 |p| MachineTool::Key {
1112 keys: p
1113 .get("keys")
1114 .and_then(Value::as_array)
1115 .map(|keys| keys.iter().map(|key| js_string(Some(key), "")).collect())
1116 .unwrap_or_default(),
1117 window: optional_number(p, "window"),
1118 },
1119 );
1120 add(
1121 "pageHtml",
1122 "Read the page in a Web window: its address and its HTML, trimmed to the body without styles, scripts and SVG. Reads the focused Web window unless window is given.",
1123 json!({
1124 "window": { "type": "NUMBER", "description": "Web window id" },
1125 }),
1126 &[],
1127 says("The page's address and its trimmed HTML"),
1128 |p| MachineTool::PageHtml {
1129 window: optional_number(p, "window"),
1130 },
1131 );
1132 add(
1133 "pageScript",
1134 "Run JavaScript in the page of a Web window and get its result: a string as it is, anything else as JSON. Runs in the focused Web window unless window is given.",
1135 json!({
1136 "script": { "type": "STRING", "description": "JavaScript to run in the page" },
1137 "window": { "type": "NUMBER", "description": "Web window id" },
1138 }),
1139 &["script"],
1140 says("The script's result: a string as it is, anything else as JSON"),
1141 |p| MachineTool::PageScript {
1142 script: js_string(p.get("script"), ""),
1143 window: optional_number(p, "window"),
1144 },
1145 );
1146
1147 add(
1148 "list",
1149 "List a folder of /repository: each entry's name, whether it's a folder, its size and whether you may change it. With pattern (like **/*.ts) it matches recursively, and names are paths from the folder.",
1150 json!({
1151 "path": { "type": "STRING", "description": "Folder relative to /repository. Defaults to the root." },
1152 "pattern": { "type": "STRING", "description": "Glob to match recursively" },
1153 }),
1154 &[],
1155 list_returns(),
1156 |p| MachineTool::List {
1157 path: optional_text(p, "path"),
1158 pattern: optional_text(p, "pattern"),
1159 },
1160 );
1161 add(
1162 "grep",
1163 "Search file contents in /repository with ripgrep: the matching files by default, each file's count of matching lines, or the matching lines with context lines around them.",
1164 json!({
1165 "pattern": { "type": "STRING", "description": "Regular expression" },
1166 "path": { "type": "STRING", "description": "Folder or file to search" },
1167 "glob": { "type": "STRING", "description": "Only files matching this glob" },
1168 "ignoreCase": { "type": "BOOLEAN", "description": "Case insensitive" },
1169 "context": { "type": "NUMBER", "description": "Lines of context around each match" },
1170 "output": { "type": "STRING", "enum": ["files", "lines", "count"], "description": "files, lines, or count" },
1171 "max": { "type": "NUMBER", "description": "Result cap, default 50" },
1172 }),
1173 &["pattern"],
1174 grep_returns(),
1175 |p| MachineTool::Grep {
1176 pattern: js_string(p.get("pattern"), ""),
1177 path: optional_text(p, "path"),
1178 glob: optional_text(p, "glob"),
1179 ignore_case: present(p.get("ignoreCase")).map(truthy),
1180 context: optional_number(p, "context"),
1181 output: present(p.get("output"))
1182 .and_then(|output| serde_json::from_value(output.clone()).ok()),
1183 max: optional_number(p, "max"),
1184 },
1185 );
1186 add(
1187 "read",
1188 "Read lines of a file exactly as they are, from line minus before to line plus after; the first 100 lines by default. from, to and total say where they sit, so read on from to plus 1.",
1189 json!({
1190 "path": { "type": "STRING", "description": "File relative to /repository" },
1191 "line": { "type": "NUMBER", "description": "Line to center on, default 1" },
1192 "before": { "type": "NUMBER", "description": "Lines before, default 0" },
1193 "after": { "type": "NUMBER", "description": "Lines after, default 100" },
1194 }),
1195 &["path"],
1196 read_returns(),
1197 |p| MachineTool::Read {
1198 path: js_string(p.get("path"), ""),
1199 line: optional_number(p, "line"),
1200 before: optional_number(p, "before"),
1201 after: optional_number(p, "after"),
1202 },
1203 );
1204 add(
1205 "write",
1206 "Create or overwrite a file, creating missing folders. With line, insert text after that line instead (0 inserts at the top); read the file first.",
1207 json!({
1208 "path": { "type": "STRING", "description": "File relative to /repository" },
1209 "text": { "type": "STRING", "description": "Full file contents, or with line, the lines to insert" },
1210 "line": { "type": "NUMBER", "description": "Line to insert after, leaving the rest of the file as it is" },
1211 }),
1212 &["path", "text"],
1213 write_returns(),
1214 |p| MachineTool::Write {
1215 path: js_string(p.get("path"), ""),
1216 text: js_string(p.get("text"), ""),
1217 line: optional_number(p, "line"),
1218 },
1219 );
1220 add(
1221 "replace",
1222 "Replace an exact string in a file. old must match exactly once unless all is true. Prefer this for edits.",
1223 json!({
1224 "path": { "type": "STRING", "description": "File relative to /repository" },
1225 "old": { "type": "STRING", "description": "Exact text to find" },
1226 "new": { "type": "STRING", "description": "Replacement text" },
1227 "all": { "type": "BOOLEAN", "description": "Replace every match" },
1228 }),
1229 &["path", "old", "new"],
1230 replace_returns(),
1231 |p| MachineTool::Replace {
1232 path: js_string(p.get("path"), ""),
1233 old: js_string(p.get("old"), ""),
1234 new: js_string(p.get("new"), ""),
1235 all: present(p.get("all")).map(truthy),
1236 },
1237 );
1238 add(
1239 "remove",
1240 "Delete lines start through end, inclusive. Read the file first.",
1241 json!({
1242 "path": { "type": "STRING", "description": "File relative to /repository" },
1243 "start": { "type": "NUMBER", "description": "First line" },
1244 "end": { "type": "NUMBER", "description": "Last line" },
1245 }),
1246 &["path", "start", "end"],
1247 remove_returns(),
1248 |p| MachineTool::Remove {
1249 path: js_string(p.get("path"), ""),
1250 start: js_number(p.get("start")),
1251 end: js_number(p.get("end")),
1252 },
1253 );
1254
1255 add(
1256 "processes",
1257 "List running processes with their CPU right now, memory, running time, command and listening ports, plus the machine's CPU load, memory and free disk. Default: the 25 busiest by CPU.",
1258 json!({
1259 "sort": { "type": "STRING", "enum": ["cpu", "memory"], "description": "cpu or memory, default cpu" },
1260 "limit": { "type": "NUMBER", "description": "How many to list, default 25" },
1261 "filter": { "type": "STRING", "description": "Only commands containing this text" },
1262 }),
1263 &[],
1264 says("The busiest processes and the machine's load, memory and free disk"),
1265 |p| MachineTool::Processes {
1266 sort: match p.get("sort").and_then(Value::as_str) {
1267 Some("memory") => Some(ProcessSort::Memory),
1268 Some("cpu") => Some(ProcessSort::Cpu),
1269 _ => None,
1270 },
1271 limit: optional_number(p, "limit"),
1272 filter: optional_text(p, "filter"),
1273 },
1274 );
1275 add(
1276 "kill",
1277 "Stop one of your processes. TERM asks it to exit, KILL forces it. The machine's own processes, including the desktop's browser, can't be stopped.",
1278 json!({
1279 "pid": { "type": "NUMBER", "description": "Process id from processes" },
1280 "signal": { "type": "STRING", "enum": ["TERM", "KILL"], "description": "TERM (default) or KILL" },
1281 }),
1282 &["pid"],
1283 says("Whether the process stopped"),
1284 |p| MachineTool::Kill {
1285 pid: js_number(p.get("pid")),
1286 signal: match p.get("signal").and_then(Value::as_str) {
1287 Some("KILL") => Some(ProcessSignal::Kill),
1288 Some("TERM") => Some(ProcessSignal::Term),
1289 _ => None,
1290 },
1291 },
1292 );
1293
1294 add(
1295 "internet",
1296 "Choose how the machine reaches the internet. private sends every connection out from a residential address, billed per GB; public uses the machine's own address. While private reconnects the internet is paused and connections are refused; switch to public if the work can't wait.",
1297 json!({
1298 "mode": { "type": "STRING", "enum": ["private", "public"], "description": "private or public" },
1299 }),
1300 &["mode"],
1301 says("How the machine reaches the internet now"),
1302 |p| MachineTool::Internet {
1303 mode: if p.get("mode").and_then(Value::as_str) == Some("public") {
1304 InternetMode::Public
1305 } else {
1306 InternetMode::Private
1307 },
1308 },
1309 );
1310 tools.push(tool(
1311 "wait",
1312 &format!("Wait, then look at the screen again: for a page to load, an app to start, or a build running in a terminal to finish. Nothing watches the screen meanwhile, so wait about as long as it should take and wait again if it isn't done. At most {WAIT_MAX_SECONDS} seconds a call. To wait for a command, run it with exec instead, which returns when it ends."),
1313 json!({
1314 "type": "OBJECT",
1315 "properties": {
1316 "seconds": { "type": "NUMBER", "description": format!("Seconds to wait, at most {WAIT_MAX_SECONDS}") },
1317 },
1318 "required": ["seconds"],
1319 }),
1320 says("How long it waited"),
1321 {
1322 let invoke = invoke.clone();
1323 move |params: Value, _progress| {
1324 invoke(MachineTool::Wait {
1325 seconds: js_number(params.get("seconds")),
1326 })
1327 }
1328 },
1329 ));
1330
1331 tools.push(tool(
1332 "exec",
1333 "Run a Bash command as the agent user in /repository. Each call is a new shell: cd, exported variables and activated environments don't carry over, and there's no input or terminal. Output comes back when the command exits, and nothing shows on screen; to let people watch a command run, open a terminal with it instead. Start servers and GUI apps in the background with & (or nohup ... &) so they keep running; a timeout stops everything the command started. GUI apps open as desktop windows.",
1334 json!({
1335 "type": "OBJECT",
1336 "properties": {
1337 "command": { "type": "STRING", "description": "Bash command" },
1338 "timeoutMs": { "type": "NUMBER", "description": "Timeout in ms, default 120000; pass more for installs and builds" },
1339 },
1340 "required": ["command"],
1341 }),
1342 json!({
1343 "type": "OBJECT",
1344 "properties": {
1345 "code": { "type": "INTEGER", "description": "Exit code" },
1346 "stdout": { "type": "STRING", "description": "Standard output" },
1347 "stderr": { "type": "STRING", "description": "Standard error" },
1348 },
1349 "required": ["code", "stdout", "stderr"],
1350 }),
1351 move |params: Value, _progress| {
1352 exec(
1353 js_string(params.get("command"), ""),
1354 optional_number(¶ms, "timeoutMs"),
1355 )
1356 },
1357 ));
1358 tools
1359}
1360
1361pub const COMPUTER_DECLINED: &str =
1363 "They chose not to use a computer for this. Do it without one if you can.";
1364
1365const COMPUTER_JOB: &str = "It's for work that needs a screen: using apps and websites, taking screenshots, recording a video. A subagent does the job on the computer and reports back. It sees nothing of this chat except goal, so goal must carry everything: what to do, where, which files, and what to capture or record (screenshots, or a video of the job). Everything it captures is attached to the chat for people to see, and comes back to you too. Slower and costlier than the other tools; use it only when the screen matters.";
1366
1367pub fn computer_tool(repository: Option<&Repository>) -> Function {
1372 let place = if repository.is_some() {
1373 "Do something on the repository's computer, a Linux machine with a desktop."
1374 } else {
1375 "Do something on a computer, a Linux machine with a desktop. This chat has no computer yet, so the person is asked first to make one; if they don't, do the request without a computer."
1376 };
1377 Function {
1378 name: "use_computer".to_string(),
1379 description: Some(format!("{place} {COMPUTER_JOB}")),
1380 parameters: serde_json::from_value::<Schema>(json!({
1381 "type": "OBJECT",
1382 "properties": {
1383 "goal": { "type": "STRING", "description": "Everything the subagent needs: what to do, where, which files, and what to capture or record" },
1384 "spec": {
1385 "type": "OBJECT",
1386 "description": "Only the fields that should change. Omitted fields stay as the computer already is. A new computer starts at the standard size.",
1387 "properties": {
1388 "vcpus": { "type": "NUMBER", "description": "vCPUs" },
1389 "memoryBytes": { "type": "NUMBER", "description": "Memory in bytes" },
1390 "storageBytes": { "type": "NUMBER", "description": "Disk in bytes" },
1391 "tflops": { "type": "NUMBER", "description": "GPU TFLOPS (dense BF16), 0 for no GPU" },
1392 "gpuMemoryBytes": { "type": "NUMBER", "description": "GPU memory in bytes, 0 for no GPU" },
1393 },
1394 },
1395 },
1396 "required": ["goal"],
1397 }))
1398 .expect("tool schemas are valid"),
1399 returns: serde_json::from_value::<ObjectSchema>(says(
1400 "What the subagent did and found, or that the person chose not to use a computer",
1401 ))
1402 .expect("tool returns are valid"),
1403 default: None,
1404 example: None,
1405 behavior: None,
1406 }
1407}
1408
1409#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1411#[serde(rename_all = "camelCase")]
1412pub struct PoolPricing {
1413 pub name: String,
1414 pub node_type: String,
1416 pub node: Rate,
1418 pub node_vcpus: u32,
1420 pub node_memory_bytes: u64,
1421 pub machines: u32,
1423 pub nodes: u32,
1424}
1425
1426#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1428#[serde(rename_all = "camelCase")]
1429pub struct Quote {
1430 pub pool: String,
1431 pub alone: f64,
1433 pub now: f64,
1435}
1436
1437#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1440#[serde(rename_all = "camelCase")]
1441pub struct Pricing {
1442 pub rates: Vec<Rate>,
1445 pub pools: Vec<PoolPricing>,
1446 pub quote: Option<Quote>,
1448}
1449
1450pub async fn pricing(spec: Option<&Spec>) -> Result<Pricing> {
1453 let mut request = crate::http::client().get(format!("{}/termite/pricing", super::get_url()));
1454 if let Some(spec) = spec {
1455 request = request.query(&[
1456 ("vcpus", spec.vcpus.to_string()),
1457 ("memoryBytes", spec.memory_bytes.to_string()),
1458 ("storageBytes", spec.storage_bytes.to_string()),
1459 ("tflops", spec.tflops.to_string()),
1460 ("gpuMemoryBytes", spec.gpu_memory_bytes.to_string()),
1461 ]);
1462 }
1463 let response = request.send().await?;
1464 Ok(crate::http::ok(response).await?.json().await?)
1465}
1466
1467#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
1469#[serde(rename_all = "lowercase")]
1470pub enum WakeReason {
1471 Called,
1472 Crashed,
1473 Answered,
1474 Skipped,
1475}
1476
1477#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
1481pub struct Wake {
1482 pub id: String,
1483 pub reason: WakeReason,
1484 pub prompt: String,
1486 pub started: DateTime<Utc>,
1487 pub finished: Option<DateTime<Utc>>,
1489 pub ok: bool,
1490 pub answer: String,
1492}
1493
1494impl Wake {
1495 pub fn from_json(json: &Value) -> Wake {
1496 Wake {
1497 id: js_string(json.get("id"), "undefined"),
1498 reason: match json["reason"].as_str() {
1499 Some("crashed") => WakeReason::Crashed,
1500 Some("answered") => WakeReason::Answered,
1501 Some("skipped") => WakeReason::Skipped,
1502 _ => WakeReason::Called,
1503 },
1504 prompt: js_string(json.get("prompt"), ""),
1505 started: crate::tickets::parse_date(&json["started"]).unwrap_or_default(),
1506 finished: if truthy(&json["finished"]) {
1507 crate::tickets::parse_date(&json["finished"])
1508 } else {
1509 None
1510 },
1511 ok: truthy(&json["ok"]),
1512 answer: js_string(json.get("answer"), ""),
1513 }
1514 }
1515}
1516
1517#[derive(Debug, Clone, Default)]
1519pub struct GroupOptions {
1520 pub group: Option<Group>,
1521}
1522
1523fn authorized(
1524 request: reqwest::RequestBuilder,
1525 authorization: &CredentialsOrApiKey,
1526 group: Option<&Group>,
1527) -> reqwest::RequestBuilder {
1528 let request = request.header(
1529 "Authorization",
1530 match authorization {
1531 CredentialsOrApiKey::Credentials(credentials) => format!("Token {}", credentials.token),
1532 CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
1533 },
1534 );
1535 match group {
1536 Some(group) => request.header("Group", &group.id),
1537 None => request,
1538 }
1539}
1540
1541pub async fn wakes(
1543 authorization: &CredentialsOrApiKey,
1544 repository: u64,
1545 query: PageQuery,
1546 opts: GroupOptions,
1547) -> Result<Vec<Wake>> {
1548 let response = authorized(
1549 crate::http::client().get(format!(
1550 "{}/termite/repositories/{repository}/wakes?cursor={}&max={}",
1551 super::get_url(),
1552 query.cursor,
1553 query.max
1554 )),
1555 authorization,
1556 opts.group.as_ref(),
1557 )
1558 .send()
1559 .await?;
1560 let json: Value = crate::http::ok(response).await?.json().await?;
1561 Ok(json
1562 .as_array()
1563 .into_iter()
1564 .flatten()
1565 .map(Wake::from_json)
1566 .collect())
1567}
1568
1569struct Machine {
1570 cursor: HtmlPointer,
1571 controller: Option<String>,
1572 agent: Option<RoomAgent>,
1573 windows: HashMap<u64, Window>,
1574 files: HashMap<u64, FilesState>,
1575 status: MachineStatus,
1576 error: String,
1577 name: String,
1578 private: bool,
1579 private_reason: String,
1580}
1581
1582struct MachineState {
1583 machine: u64,
1584 repository: u64,
1585 spec: Spec,
1586 web: WebRoom,
1587 state: Mutex<Machine>,
1588 hooks: Mutex<Arc<dyn MachineRoomHooks>>,
1589 calls: Mutex<HashMap<String, oneshot::Sender<Result<Value>>>>,
1590}
1591
1592fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
1593 mutex.lock().unwrap_or_else(PoisonError::into_inner)
1594}
1595
1596#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1598pub struct ExecResult {
1599 pub code: i64,
1600 pub stdout: String,
1601 pub stderr: String,
1602}
1603
1604#[derive(Debug, Clone, Copy, Default)]
1606pub struct ExecOptions {
1607 pub timeout_ms: Option<u64>,
1608}
1609
1610pub struct StartOptions {
1612 pub spec: Spec,
1613 pub group: Option<Group>,
1614 pub hooks: Option<Arc<dyn MachineRoomHooks>>,
1615 pub private: Option<bool>,
1616}
1617
1618#[derive(Default)]
1621pub struct MachineOptions {
1622 pub group: Option<Group>,
1623 pub hooks: Option<Arc<dyn MachineRoomHooks>>,
1624}
1625
1626#[derive(Debug, Clone, PartialEq, Eq)]
1629pub enum MachineTarget {
1630 Id { id: u64 },
1631 Reference { reference: String },
1632}
1633
1634#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1636pub struct PrivateState {
1637 pub on: bool,
1638 pub reason: String,
1639}
1640
1641#[derive(Clone)]
1642pub struct MachineRoom {
1643 room: Room,
1644 inner: Arc<MachineState>,
1645}
1646
1647impl Deref for MachineRoom {
1648 type Target = Room;
1649 fn deref(&self) -> &Room {
1650 &self.room
1651 }
1652}
1653
1654impl MachineRoom {
1655 fn create(room: &Room, hooks: Arc<dyn MachineRoomHooks>, state: &Value) -> MachineRoom {
1656 MachineRoom {
1657 room: room.clone(),
1658 inner: Arc::new(MachineState {
1659 machine: js_number(Some(&state["machine"]["id"])) as u64,
1660 repository: js_number(Some(&state["machine"]["repository"])) as u64,
1661 spec: Spec::from_json(&state["machine"]["spec"]),
1662 web: WebRoom::from_parent(room, hooks.web(), state),
1663 state: Mutex::new(Machine {
1664 cursor: HtmlPointer::default(),
1665 controller: None,
1666 agent: None,
1667 windows: HashMap::new(),
1668 files: HashMap::new(),
1669 status: MachineStatus::Booting,
1670 error: String::new(),
1671 name: String::new(),
1672 private: false,
1673 private_reason: String::new(),
1674 }),
1675 hooks: Mutex::new(hooks),
1676 calls: Mutex::new(HashMap::new()),
1677 }),
1678 }
1679 }
1680
1681 fn machine_state(&self) -> MutexGuard<'_, Machine> {
1682 lock(&self.inner.state)
1683 }
1684
1685 fn hooks(&self) -> Arc<dyn MachineRoomHooks> {
1686 lock(&self.inner.hooks).clone()
1687 }
1688
1689 pub fn machine(&self) -> u64 {
1691 self.inner.machine
1692 }
1693
1694 pub fn repository(&self) -> u64 {
1695 self.inner.repository
1696 }
1697
1698 pub fn spec(&self) -> Spec {
1700 self.inner.spec
1701 }
1702
1703 pub fn web(&self) -> &WebRoom {
1705 &self.inner.web
1706 }
1707
1708 pub fn cursor(&self) -> HtmlPointer {
1709 self.machine_state().cursor.clone()
1710 }
1711
1712 pub fn controller(&self) -> Option<String> {
1714 self.machine_state().controller.clone()
1715 }
1716
1717 pub fn agent(&self) -> Option<RoomAgent> {
1719 self.machine_state().agent.clone()
1720 }
1721
1722 pub fn windows(&self) -> HashMap<u64, Window> {
1723 self.machine_state().windows.clone()
1724 }
1725
1726 pub fn files(&self) -> HashMap<u64, FilesState> {
1728 self.machine_state().files.clone()
1729 }
1730
1731 pub fn status(&self) -> MachineStatus {
1732 self.machine_state().status
1733 }
1734
1735 pub fn error(&self) -> String {
1737 self.machine_state().error.clone()
1738 }
1739
1740 pub fn name(&self) -> String {
1742 self.machine_state().name.clone()
1743 }
1744
1745 pub fn private(&self) -> bool {
1748 self.machine_state().private
1749 }
1750
1751 pub fn private_reason(&self) -> String {
1754 self.machine_state().private_reason.clone()
1755 }
1756
1757 pub fn hydrate(&self, state: &Value) {
1760 if state["control"].is_object() {
1761 self.apply_control(&state["control"]);
1762 }
1763 let cursor = serde_json::from_value::<HtmlPointer>(state["cursor"].clone()).ok();
1764 {
1765 let mut machine = self.machine_state();
1766 if let Ok(status) = serde_json::from_value(state["machine"]["status"].clone()) {
1767 machine.status = status;
1768 }
1769 if state["machine"].is_object() {
1770 machine.error = js_string(state["machine"].get("error"), "");
1771 machine.name = js_string(state["machine"].get("name"), "");
1772 }
1773 if let Some(cursor) = &cursor {
1774 machine.cursor = cursor.clone();
1775 }
1776 if let Some(windows) = state["windows"].as_array() {
1777 machine.windows = windows
1778 .iter()
1779 .map(Window::from_json)
1780 .map(|window| (window.id, window))
1781 .collect();
1782 }
1783 if let Some(files) = state["files"].as_array() {
1784 machine.files = files
1785 .iter()
1786 .map(|row| {
1787 (
1788 js_number(row.get("window")) as u64,
1789 FilesState::from_json(row),
1790 )
1791 })
1792 .collect();
1793 }
1794 if truthy(&state["private"]) {
1795 machine.private = truthy(&state["private"]["on"]);
1796 machine.private_reason = js_string(state["private"].get("reason"), "");
1797 }
1798 }
1799 if let Some(cursor) = cursor {
1800 self.hooks().on_cursor(self, &cursor);
1801 }
1802 }
1803
1804 pub fn watch(&self, hooks: Arc<dyn MachineRoomHooks>) {
1805 if let Some(web) = hooks.web() {
1806 self.inner.web.set_hooks(web);
1807 }
1808 *lock(&self.inner.hooks) = hooks;
1809 }
1810
1811 pub fn controlling(&self, me: &Presence) -> bool {
1813 let machine = self.machine_state();
1814 machine.agent.is_none() && machine.controller == Some(me.id())
1815 }
1816
1817 pub async fn set_controller(&self, seat: Option<&str>) -> Result<()> {
1819 let data = match seat.filter(|seat| !seat.is_empty()) {
1820 Some(seat) => json!({ "seat": seat }),
1821 None => json!({}),
1822 };
1823 self.request("control-call", data, CONTROL_MS, "Control timed out.")
1824 .await?;
1825 Ok(())
1826 }
1827
1828 pub fn emit_presence(&self) {
1830 self.hooks().on_presence(self);
1831 }
1832
1833 pub fn emit_closed(&self) {
1834 self.hooks().on_closed(self);
1835 }
1836
1837 fn apply_control(&self, control: &Value) {
1838 let mut machine = self.machine_state();
1839 machine.controller = control["controller"].as_str().map(str::to_string);
1840 machine.agent = if control["agent"].is_object() {
1841 Some(RoomAgent::from_json(&control["agent"]))
1842 } else {
1843 None
1844 };
1845 }
1846
1847 pub async fn invoke_tool(&self, tool: &MachineTool) -> Result<Map<String, Value>> {
1851 if let MachineTool::Wait { seconds } = tool {
1852 let seconds = if seconds.is_nan() {
1853 0.0
1854 } else {
1855 seconds.clamp(0.0, WAIT_MAX_SECONDS as f64)
1856 };
1857 tokio::time::sleep(Duration::from_secs_f64(seconds)).await;
1858 return Ok(Map::from_iter([(
1859 "text".to_string(),
1860 Value::String(format!("Waited {seconds} seconds.")),
1861 )]));
1862 }
1863 let kind = js_string(Some(&serde_json::to_value(tool)?["kind"]), "");
1864 let result = if tool.is_input() {
1865 self.request(
1866 "machine-tool-call",
1867 json!({ "tool": tool }),
1868 INPUT_MS,
1869 &format!("Tool timed out: {kind}"),
1870 )
1871 .await?
1872 } else {
1873 self.call(json!({ "kind": "tool", "tool": tool }), CALL_MS)
1874 .await?
1875 };
1876 match result {
1877 Value::Object(result) => Ok(result),
1878 _ => Err(Error::Message(format!(
1879 "The machine answered {kind} without an object."
1880 ))),
1881 }
1882 }
1883
1884 pub async fn exec(&self, command: &str, opts: ExecOptions) -> Result<ExecResult> {
1886 let timeout_ms = opts.timeout_ms.unwrap_or(EXEC_MS);
1887 let result = self
1888 .call(
1889 json!({ "kind": "exec", "command": command, "timeoutMs": timeout_ms }),
1890 timeout_ms + 15_000,
1891 )
1892 .await?;
1893 Ok(ExecResult {
1894 code: match result.get("code") {
1895 None | Some(Value::Null) => -1,
1896 code => js_number(code) as i64,
1897 },
1898 stdout: js_string(result.get("stdout"), ""),
1899 stderr: js_string(result.get("stderr"), ""),
1900 })
1901 }
1902
1903 pub async fn set_viewport(&self, width: f64, height: f64) -> Result<()> {
1905 let size = clamp_viewport(Viewport { width, height });
1906 self.call(
1907 json!({ "kind": "viewport", "width": size.width, "height": size.height }),
1908 CALL_MS,
1909 )
1910 .await?;
1911 Ok(())
1912 }
1913
1914 pub async fn open(&self, path: &str) -> Result<()> {
1918 self.call(json!({ "kind": "open", "path": path }), CALL_MS)
1919 .await?;
1920 Ok(())
1921 }
1922
1923 pub async fn set_files(&self, window: u64, files: &FilesState) -> Result<()> {
1925 self.call(
1926 json!({ "kind": "files", "window": window, "path": files.path, "view": files.view }),
1927 CALL_MS,
1928 )
1929 .await?;
1930 Ok(())
1931 }
1932
1933 pub async fn stop(&self) -> Result<()> {
1935 match self.call(json!({ "kind": "stop" }), STOP_MS).await {
1936 Ok(_) => Ok(()),
1937 Err(_) if self.status() == MachineStatus::Stopped => Ok(()),
1939 Err(error) => Err(error),
1940 }
1941 }
1942
1943 async fn call(&self, call: Value, timeout_ms: u64) -> Result<Value> {
1944 self.request(
1945 "machine-call",
1946 json!({ "call": call }),
1947 timeout_ms,
1948 "Machine call timed out.",
1949 )
1950 .await
1951 }
1952
1953 async fn request(
1956 &self,
1957 event: &str,
1958 mut data: Value,
1959 timeout_ms: u64,
1960 timed_out: &str,
1961 ) -> Result<Value> {
1962 let id = uuid::Uuid::new_v4().to_string();
1963 let (resolve, result) = oneshot::channel();
1964 lock(&self.inner.calls).insert(id.clone(), resolve);
1965 data["id"] = json!(id);
1966 self.post(&json!({ "event": event, "data": data }));
1967 match tokio::time::timeout(Duration::from_millis(timeout_ms), result).await {
1968 Ok(Ok(result)) => result,
1969 Ok(Err(_)) => Err(Error::Message("Machine closed.".to_string())),
1970 Err(_) => {
1971 lock(&self.inner.calls).remove(&id);
1972 Err(Error::Message(timed_out.to_string()))
1973 }
1974 }
1975 }
1976
1977 fn settle(&self, data: &Value) {
1978 let Some(id) = data["id"].as_str() else {
1979 return;
1980 };
1981 let Some(pending) = lock(&self.inner.calls).remove(id) else {
1982 return;
1983 };
1984 let _ = pending.send(if truthy(&data["error"]) {
1985 Err(Error::Message(js_string(data.get("error"), "")))
1986 } else {
1987 Ok(data["result"].clone())
1988 });
1989 }
1990
1991 pub fn parrot_tools(&self) -> Vec<Tool> {
1992 let invoking = self.clone();
1993 let executing = self.clone();
1994 parrot_tools(
1995 Arc::new(move |tool| {
1996 let room = invoking.clone();
1997 Box::pin(async move { room.invoke_tool(&tool).await })
1998 }),
1999 Arc::new(move |command, timeout_ms| {
2000 let room = executing.clone();
2001 Box::pin(async move {
2002 let result = room
2003 .exec(
2004 &command,
2005 ExecOptions {
2006 timeout_ms: timeout_ms.map(|ms| ms as u64),
2007 },
2008 )
2009 .await?;
2010 Ok(serde_json::from_value(serde_json::to_value(result)?)?)
2011 })
2012 }),
2013 )
2014 }
2015
2016 pub fn handle_binary(&self, data: &[u8]) -> bool {
2018 let Some(frame) = AppFrame::from_bytes(data) else {
2019 return false;
2020 };
2021 self.hooks().on_app_frame(self, &frame);
2022 true
2023 }
2024
2025 pub fn repaint(&self, window: u32) {
2028 self.post(&json!({ "event": "app-repaint", "data": { "window": window } }));
2029 }
2030
2031 pub fn handle_event(&self, packet: &Value) -> bool {
2032 if self.inner.web.handle_event(packet) {
2033 return true;
2034 }
2035 let data = &packet["data"];
2036 let hooks = self.hooks();
2037 match packet["event"].as_str().unwrap_or_default() {
2038 "room-control" => {
2039 let empty = json!({});
2040 self.apply_control(if data.is_object() { data } else { &empty });
2041 hooks.on_control(self);
2042 true
2043 }
2044 "machine-cursor" => {
2045 if let Ok(cursor) = serde_json::from_value::<HtmlPointer>(data["cursor"].clone()) {
2046 self.machine_state().cursor = cursor.clone();
2047 hooks.on_cursor(self, &cursor);
2048 }
2049 true
2050 }
2051 "machine-tool-call" => {
2052 if let Ok(tool) = serde_json::from_value::<MachineTool>(data["tool"].clone()) {
2053 hooks.on_tool(self, &tool);
2054 }
2055 true
2056 }
2057 "control-result" | "machine-tool-result" | "machine-result" => {
2058 self.settle(data);
2059 true
2060 }
2061 "machine-status" => {
2062 if let Ok(status) = serde_json::from_value(data["status"].clone()) {
2063 self.machine_state().status = status;
2064 }
2065 hooks.on_status(self);
2066 true
2067 }
2068 "machine-window" => {
2069 if !truthy(&data["window"]) {
2070 return true;
2071 }
2072 let window = Window::from_json(&data["window"]);
2073 self.machine_state()
2074 .windows
2075 .insert(window.id, window.clone());
2076 hooks.on_window(self, &window);
2077 true
2078 }
2079 "machine-window-closed" => {
2080 let id = js_number(data.get("id")) as u64;
2081 {
2082 let mut machine = self.machine_state();
2083 machine.windows.remove(&id);
2084 machine.files.remove(&id);
2085 }
2086 hooks.on_window_closed(self, id);
2087 true
2088 }
2089 "machine-files" => {
2090 let window = js_number(data.get("window")) as u64;
2091 let files = FilesState::from_json(data);
2092 self.machine_state().files.insert(window, files.clone());
2093 hooks.on_files(self, window, &files);
2094 true
2095 }
2096 "machine-private" => {
2097 {
2098 let mut machine = self.machine_state();
2099 machine.private = truthy(&data["on"]);
2100 machine.private_reason = js_string(data.get("reason"), "");
2101 }
2102 hooks.on_private(self);
2103 true
2104 }
2105 "machine-agent-step" => {
2106 if let Ok(step) = serde_json::from_value::<AgentStep>(data.clone()) {
2107 hooks.on_agent_step(self, &step);
2108 }
2109 true
2110 }
2111 "machine-closed" => {
2112 {
2113 let mut machine = self.machine_state();
2114 if let Ok(status) = serde_json::from_value(data["status"].clone()) {
2115 machine.status = status;
2116 }
2117 if let Some(error) = data.get("error") {
2118 machine.error = js_string(Some(error), "");
2119 }
2120 }
2121 hooks.on_status(self);
2122 for (_, pending) in lock(&self.inner.calls).drain() {
2123 let _ = pending.send(Err(Error::Message("Machine closed.".to_string())));
2124 }
2125 hooks.on_closed(self);
2126 true
2127 }
2128 _ => false,
2129 }
2130 }
2131
2132 pub async fn start(
2137 authorization: &CredentialsOrApiKey,
2138 repository: u64,
2139 opts: StartOptions,
2140 ) -> Result<(MachineRoom, Presence)> {
2141 let mut body = json!({ "spec": opts.spec });
2142 if let Some(private) = opts.private {
2143 body["private"] = json!(private);
2144 }
2145 let response = authorized(
2146 crate::http::client().post(format!(
2147 "{}/termite/repositories/{repository}/machine",
2148 super::get_url()
2149 )),
2150 authorization,
2151 opts.group.as_ref(),
2152 )
2153 .json(&body)
2154 .send()
2155 .await?;
2156 let json: Value = crate::http::ok(response).await?.json().await?;
2157 MachineRoom::connect(
2158 authorization,
2159 &MachineTarget::Id {
2160 id: js_number(json.get("id")) as u64,
2161 },
2162 MachineOptions {
2163 group: opts.group,
2164 hooks: opts.hooks,
2165 },
2166 )
2167 .await
2168 }
2169
2170 pub async fn shutdown(
2172 authorization: &CredentialsOrApiKey,
2173 repository: u64,
2174 opts: GroupOptions,
2175 ) -> Result<()> {
2176 let response = authorized(
2177 crate::http::client().post(format!(
2178 "{}/termite/repositories/{repository}/machine/stop",
2179 super::get_url()
2180 )),
2181 authorization,
2182 opts.group.as_ref(),
2183 )
2184 .json(&json!({}))
2185 .send()
2186 .await?;
2187 crate::http::ok(response).await?;
2188 Ok(())
2189 }
2190
2191 pub async fn set_private(
2194 authorization: &CredentialsOrApiKey,
2195 repository: u64,
2196 on: bool,
2197 opts: GroupOptions,
2198 ) -> Result<PrivateState> {
2199 let response = authorized(
2200 crate::http::client().post(format!(
2201 "{}/termite/repositories/{repository}/machine/private",
2202 super::get_url()
2203 )),
2204 authorization,
2205 opts.group.as_ref(),
2206 )
2207 .json(&json!({ "on": on }))
2208 .send()
2209 .await?;
2210 let json: Value = crate::http::ok(response).await?.json().await?;
2211 Ok(PrivateState {
2212 on: truthy(&json["on"]),
2213 reason: js_string(json.get("reason"), ""),
2214 })
2215 }
2216
2217 pub async fn connect(
2219 authorization: &CredentialsOrApiKey,
2220 target: &MachineTarget,
2221 opts: MachineOptions,
2222 ) -> Result<(MachineRoom, Presence)> {
2223 MachineRoom::open_room(
2224 Authorization::Server {
2225 authorization: authorization.clone(),
2226 server: match target {
2227 MachineTarget::Id { id } => format!("termite:machine:{id}"),
2228 MachineTarget::Reference { reference } => reference.clone(),
2229 },
2230 group: opts.group.as_ref().map(|group| group.id.clone()),
2231 },
2232 opts.hooks.unwrap_or_else(|| Arc::new(())),
2233 )
2234 .await
2235 }
2236
2237 pub async fn join(
2239 authorization: &CredentialsOrApiKey,
2240 access_code: &str,
2241 opts: MachineOptions,
2242 ) -> Result<(MachineRoom, Presence)> {
2243 MachineRoom::open_room(
2244 Authorization::AccessCode {
2245 authorization: authorization.clone(),
2246 access_code: access_code.to_string(),
2247 },
2248 opts.hooks.unwrap_or_else(|| Arc::new(())),
2249 )
2250 .await
2251 }
2252
2253 async fn open_room(
2254 auth: Authorization,
2255 hooks: Arc<dyn MachineRoomHooks>,
2256 ) -> Result<(MachineRoom, Presence)> {
2257 let machine_hooks = Arc::new(MachineHooks {
2258 room: Mutex::new(None),
2259 hooks,
2260 });
2261 let me = connect_server(
2262 auth,
2263 &format!("{}/termite/machine/live", super::get_url()),
2264 machine_hooks.clone(),
2265 )
2266 .await?;
2267 let room = machine_hooks
2268 .room()
2269 .ok_or_else(|| Error::Message("Room not found".to_string()))?;
2270 room.emit_presence();
2271 Ok((room, me))
2272 }
2273}
2274
2275struct MachineHooks {
2276 room: Mutex<Option<MachineRoom>>,
2277 hooks: Arc<dyn MachineRoomHooks>,
2278}
2279
2280impl MachineHooks {
2281 fn room(&self) -> Option<MachineRoom> {
2282 lock(&self.room).clone()
2283 }
2284}
2285
2286impl Hooks for MachineHooks {
2287 fn create_room(&self, room: &Room, state: &Value) {
2288 *lock(&self.room) = Some(MachineRoom::create(room, self.hooks.clone(), state));
2289 }
2290
2291 fn on_presence(&self, _room: &Room) {
2292 if let Some(room) = self.room() {
2293 room.emit_presence();
2294 }
2295 }
2296
2297 fn on_connection(&self, _room: &Room, state: &Value) {
2298 if let Some(room) = self.room() {
2299 room.hydrate(state);
2300 }
2301 }
2302
2303 fn on_event(&self, _room: &Room, packet: &Value) -> bool {
2304 self.room().is_some_and(|room| room.handle_event(packet))
2305 }
2306
2307 fn on_binary(&self, _room: &Room, data: &[u8]) {
2308 if let Some(room) = self.room() {
2309 room.handle_binary(data);
2310 }
2311 }
2312
2313 fn on_closed(&self, _room: &Room, _reason: Option<&str>) {
2314 if let Some(room) = self.room() {
2315 room.emit_closed();
2316 }
2317 }
2318}
2319
2320#[cfg(test)]
2321mod tests {
2322 use super::*;
2323
2324 #[test]
2325 fn reads_an_app_frames_header_and_its_jpeg() {
2326 let mut data = vec![1u8, 1];
2327 data.extend(0x0040_0007u32.to_be_bytes());
2328 data.extend(9u32.to_be_bytes());
2329 for n in [640u16, 400, 0, 0, 640, 400] {
2330 data.extend(n.to_be_bytes());
2331 }
2332 data.extend([0xff, 0xd8, 0xff]);
2333 let frame = AppFrame::from_bytes(&data).unwrap();
2334 assert_eq!(
2335 frame,
2336 AppFrame {
2337 window: 0x0040_0007,
2338 seq: 9,
2339 key: true,
2340 window_width: 640,
2341 window_height: 400,
2342 x: 0,
2343 y: 0,
2344 width: 640,
2345 height: 400,
2346 jpeg: vec![0xff, 0xd8, 0xff],
2347 }
2348 );
2349 data[1] = 0;
2350 assert!(!AppFrame::from_bytes(&data).unwrap().key);
2351 assert_eq!(AppFrame::from_bytes(&data[..21]), None);
2352 data[0] = 2;
2353 assert_eq!(AppFrame::from_bytes(&data), None);
2354 }
2355
2356 #[test]
2357 fn reads_media_with_its_captions() {
2358 let video = Media::from_json(&json!({
2359 "kind": "video", "title": "Signup", "path": "/termite/repositories/1/media/2.mp4",
2360 "durationMs": 7_200, "captions": [{ "startMs": 1_200, "endMs": 3_000, "text": "Typing" }],
2361 "frameRate": 24.5,
2362 }));
2363 assert_eq!(
2364 video,
2365 Media {
2366 kind: MediaKind::Video,
2367 title: "Signup".into(),
2368 path: "/termite/repositories/1/media/2.mp4".into(),
2369 duration_ms: Some(7_200.0),
2370 captions: Some(vec![Caption {
2371 start_ms: 1_200.0,
2372 end_ms: 3_000.0,
2373 text: "Typing".into(),
2374 }]),
2375 frame_rate: Some(24.5),
2376 }
2377 );
2378 let photo =
2379 Media::from_json(&json!({ "kind": "photo", "title": "Saved", "path": "/p.jpg" }));
2380 assert_eq!(photo.kind, MediaKind::Photo);
2381 assert_eq!(
2382 (photo.duration_ms, photo.captions, photo.frame_rate),
2383 (None, None, None)
2384 );
2385 }
2386}