Skip to main content

fauna_api/termite/
os.rs

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