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