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, Rate};
20use crate::error::{Error, Result};
21use crate::groups::Group;
22use crate::js::{js_number, js_string, present};
23use crate::marmot::web::{HtmlPointer, WebRoom, WebRoomHooks};
24use crate::parrot::generative::{Function, Tool, Usage, tool};
25use crate::shared::schema::{ObjectSchema, Schema};
26use crate::shared::server::{Authorization, Hooks, Presence, Room, connect as connect_server};
27
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
29#[serde(rename_all = "lowercase")]
30pub enum MouseButton {
31    Left,
32    Right,
33    Middle,
34}
35
36/// `{ 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: Rate,
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, as callers are charged. Machines share what their pool's nodes cost by
1439/// how much 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    /// `storage` (a repository's saved files, a GB month), `private` (what a private machine
1444    /// sends through the residential proxy) and `internet` (what a machine sends out).
1445    pub rates: Vec<Rate>,
1446    pub pools: Vec<PoolPricing>,
1447    /// What the spec asked about pays an hour, or none when none was asked.
1448    pub quote: Option<Quote>,
1449}
1450
1451/// Termite's current prices, and with `spec`, what a machine of it pays an hour. Anyone can
1452/// read them, signed in or not.
1453pub async fn pricing(spec: Option<&Spec>) -> Result<Pricing> {
1454    let mut request = crate::http::client().get(format!("{}/termite/pricing", super::get_url()));
1455    if let Some(spec) = spec {
1456        request = request.query(&[
1457            ("vcpus", spec.vcpus.to_string()),
1458            ("memoryBytes", spec.memory_bytes.to_string()),
1459            ("storageBytes", spec.storage_bytes.to_string()),
1460            ("tflops", spec.tflops.to_string()),
1461            ("gpuMemoryBytes", spec.gpu_memory_bytes.to_string()),
1462        ]);
1463    }
1464    let response = request.send().await?;
1465    Ok(crate::http::ok(response).await?.json().await?)
1466}
1467
1468/// `'called' | 'crashed' | 'answered' | 'skipped'` in the TypeScript SDK.
1469#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
1470#[serde(rename_all = "lowercase")]
1471pub enum WakeReason {
1472    Called,
1473    Crashed,
1474    Answered,
1475    Skipped,
1476}
1477
1478/// One time a repository woke its machine agent: its code ran wake.sh (`called`),
1479/// entry.sh crashed (`crashed`), the owner answered a secret it asked for (`answered`), or the
1480/// hourly limit left it out (`skipped`).
1481#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
1482pub struct Wake {
1483    pub id: String,
1484    pub reason: WakeReason,
1485    /// What the agent was told: wake.sh's prompt, or how entry.sh ended.
1486    pub prompt: String,
1487    pub started: DateTime<Utc>,
1488    /// When the woken run ended, or None while it works.
1489    pub finished: Option<DateTime<Utc>>,
1490    pub ok: bool,
1491    /// What the agent said when it finished, or why it stopped.
1492    pub answer: String,
1493}
1494
1495impl Wake {
1496    pub fn from_json(json: &Value) -> Wake {
1497        Wake {
1498            id: js_string(json.get("id"), "undefined"),
1499            reason: match json["reason"].as_str() {
1500                Some("crashed") => WakeReason::Crashed,
1501                Some("answered") => WakeReason::Answered,
1502                Some("skipped") => WakeReason::Skipped,
1503                _ => WakeReason::Called,
1504            },
1505            prompt: js_string(json.get("prompt"), ""),
1506            started: crate::tickets::parse_date(&json["started"]).unwrap_or_default(),
1507            finished: if truthy(&json["finished"]) {
1508                crate::tickets::parse_date(&json["finished"])
1509            } else {
1510                None
1511            },
1512            ok: truthy(&json["ok"]),
1513            answer: js_string(json.get("answer"), ""),
1514        }
1515    }
1516}
1517
1518/// The `opts` argument of the machine calls that take only a group.
1519#[derive(Debug, Clone, Default)]
1520pub struct GroupOptions {
1521    pub group: Option<Group>,
1522}
1523
1524fn authorized(
1525    request: reqwest::RequestBuilder,
1526    authorization: &CredentialsOrApiKey,
1527    group: Option<&Group>,
1528) -> reqwest::RequestBuilder {
1529    let request = request.header(
1530        "Authorization",
1531        match authorization {
1532            CredentialsOrApiKey::Credentials(credentials) => format!("Token {}", credentials.token),
1533            CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
1534        },
1535    );
1536    match group {
1537        Some(group) => request.header("Group", &group.id),
1538        None => request,
1539    }
1540}
1541
1542/// The times a repository woke its agent, newest first.
1543pub async fn wakes(
1544    authorization: &CredentialsOrApiKey,
1545    repository: u64,
1546    query: PageQuery,
1547    opts: GroupOptions,
1548) -> Result<Vec<Wake>> {
1549    let response = authorized(
1550        crate::http::client().get(format!(
1551            "{}/termite/repositories/{repository}/wakes?cursor={}&max={}",
1552            super::get_url(),
1553            query.cursor,
1554            query.max
1555        )),
1556        authorization,
1557        opts.group.as_ref(),
1558    )
1559    .send()
1560    .await?;
1561    let json: Value = crate::http::ok(response).await?.json().await?;
1562    Ok(json
1563        .as_array()
1564        .into_iter()
1565        .flatten()
1566        .map(Wake::from_json)
1567        .collect())
1568}
1569
1570struct Machine {
1571    cursor: HtmlPointer,
1572    controller: Option<String>,
1573    agent: Option<RoomAgent>,
1574    windows: HashMap<u64, Window>,
1575    files: HashMap<u64, FilesState>,
1576    status: MachineStatus,
1577    error: String,
1578    name: String,
1579    private: bool,
1580    private_reason: String,
1581}
1582
1583struct MachineState {
1584    machine: u64,
1585    repository: u64,
1586    spec: Spec,
1587    web: WebRoom,
1588    state: Mutex<Machine>,
1589    hooks: Mutex<Arc<dyn MachineRoomHooks>>,
1590    calls: Mutex<HashMap<String, oneshot::Sender<Result<Value>>>>,
1591}
1592
1593fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
1594    mutex.lock().unwrap_or_else(PoisonError::into_inner)
1595}
1596
1597/// `{ code, stdout, stderr }` in the TypeScript SDK: how a command ended.
1598#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1599pub struct ExecResult {
1600    pub code: i64,
1601    pub stdout: String,
1602    pub stderr: String,
1603}
1604
1605/// The `opts` argument of `exec`.
1606#[derive(Debug, Clone, Copy, Default)]
1607pub struct ExecOptions {
1608    pub timeout_ms: Option<u64>,
1609}
1610
1611/// The `opts` argument of `MachineRoom::start`.
1612pub struct StartOptions {
1613    pub spec: Spec,
1614    pub group: Option<Group>,
1615    pub hooks: Option<Arc<dyn MachineRoomHooks>>,
1616    pub private: Option<bool>,
1617}
1618
1619/// The `opts` argument of `MachineRoom::connect` and `MachineRoom::join`
1620/// (which takes no group).
1621#[derive(Default)]
1622pub struct MachineOptions {
1623    pub group: Option<Group>,
1624    pub hooks: Option<Arc<dyn MachineRoomHooks>>,
1625}
1626
1627/// `{ id } | { reference }` in the TypeScript SDK: a machine by id, or by its
1628/// `termite:machine:{id}` reference.
1629#[derive(Debug, Clone, PartialEq, Eq)]
1630pub enum MachineTarget {
1631    Id { id: u64 },
1632    Reference { reference: String },
1633}
1634
1635/// `{ on, reason }` in the TypeScript SDK.
1636#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1637pub struct PrivateState {
1638    pub on: bool,
1639    pub reason: String,
1640}
1641
1642#[derive(Clone)]
1643pub struct MachineRoom {
1644    room: Room,
1645    inner: Arc<MachineState>,
1646}
1647
1648impl Deref for MachineRoom {
1649    type Target = Room;
1650    fn deref(&self) -> &Room {
1651        &self.room
1652    }
1653}
1654
1655impl MachineRoom {
1656    fn create(room: &Room, hooks: Arc<dyn MachineRoomHooks>, state: &Value) -> MachineRoom {
1657        MachineRoom {
1658            room: room.clone(),
1659            inner: Arc::new(MachineState {
1660                machine: js_number(Some(&state["machine"]["id"])) as u64,
1661                repository: js_number(Some(&state["machine"]["repository"])) as u64,
1662                spec: Spec::from_json(&state["machine"]["spec"]),
1663                web: WebRoom::from_parent(room, hooks.web(), state),
1664                state: Mutex::new(Machine {
1665                    cursor: HtmlPointer::default(),
1666                    controller: None,
1667                    agent: None,
1668                    windows: HashMap::new(),
1669                    files: HashMap::new(),
1670                    status: MachineStatus::Booting,
1671                    error: String::new(),
1672                    name: String::new(),
1673                    private: false,
1674                    private_reason: String::new(),
1675                }),
1676                hooks: Mutex::new(hooks),
1677                calls: Mutex::new(HashMap::new()),
1678            }),
1679        }
1680    }
1681
1682    fn machine_state(&self) -> MutexGuard<'_, Machine> {
1683        lock(&self.inner.state)
1684    }
1685
1686    fn hooks(&self) -> Arc<dyn MachineRoomHooks> {
1687        lock(&self.inner.hooks).clone()
1688    }
1689
1690    /// The machine id, the number `connect` takes.
1691    pub fn machine(&self) -> u64 {
1692        self.inner.machine
1693    }
1694
1695    pub fn repository(&self) -> u64 {
1696        self.inner.repository
1697    }
1698
1699    /// What the machine was granted: its vCPUs, memory, disk and GPU.
1700    pub fn spec(&self) -> Spec {
1701        self.inner.spec
1702    }
1703
1704    /// The desktop page's HTML stream, on the same socket.
1705    pub fn web(&self) -> &WebRoom {
1706        &self.inner.web
1707    }
1708
1709    pub fn cursor(&self) -> HtmlPointer {
1710        self.machine_state().cursor.clone()
1711    }
1712
1713    /// The seat (presence id) whose actions run.
1714    pub fn controller(&self) -> Option<String> {
1715        self.machine_state().controller.clone()
1716    }
1717
1718    /// Set while an agent holds the machine.
1719    pub fn agent(&self) -> Option<RoomAgent> {
1720        self.machine_state().agent.clone()
1721    }
1722
1723    pub fn windows(&self) -> HashMap<u64, Window> {
1724        self.machine_state().windows.clone()
1725    }
1726
1727    /// Each Files window's folder and view, by window id.
1728    pub fn files(&self) -> HashMap<u64, FilesState> {
1729        self.machine_state().files.clone()
1730    }
1731
1732    pub fn status(&self) -> MachineStatus {
1733        self.machine_state().status
1734    }
1735
1736    /// Why the machine failed, when it did.
1737    pub fn error(&self) -> String {
1738        self.machine_state().error.clone()
1739    }
1740
1741    /// The repository's name, so a guest who joined by code knows what it is.
1742    pub fn name(&self) -> String {
1743        self.machine_state().name.clone()
1744    }
1745
1746    /// Its connections go out only from a residential address, billed per GB to whoever pays for
1747    /// the machine. Stays true while private is paused.
1748    pub fn private(&self) -> bool {
1749        self.machine_state().private
1750    }
1751
1752    /// Why private is paused while it reconnects, like a payer out of balance. Its internet is cut
1753    /// until then. Empty while private carries traffic, or is off.
1754    pub fn private_reason(&self) -> String {
1755        self.machine_state().private_reason.clone()
1756    }
1757
1758    /// Apply a connection snapshot `{ machine, control, cursor, windows, files, private }`. The
1759    /// desktop's copy follows the connection as a bootstrap of this seat's own.
1760    pub fn hydrate(&self, state: &Value) {
1761        if state["control"].is_object() {
1762            self.apply_control(&state["control"]);
1763        }
1764        let cursor = serde_json::from_value::<HtmlPointer>(state["cursor"].clone()).ok();
1765        {
1766            let mut machine = self.machine_state();
1767            if let Ok(status) = serde_json::from_value(state["machine"]["status"].clone()) {
1768                machine.status = status;
1769            }
1770            if state["machine"].is_object() {
1771                machine.error = js_string(state["machine"].get("error"), "");
1772                machine.name = js_string(state["machine"].get("name"), "");
1773            }
1774            if let Some(cursor) = &cursor {
1775                machine.cursor = cursor.clone();
1776            }
1777            if let Some(windows) = state["windows"].as_array() {
1778                machine.windows = windows
1779                    .iter()
1780                    .map(Window::from_json)
1781                    .map(|window| (window.id, window))
1782                    .collect();
1783            }
1784            if let Some(files) = state["files"].as_array() {
1785                machine.files = files
1786                    .iter()
1787                    .map(|row| {
1788                        (
1789                            js_number(row.get("window")) as u64,
1790                            FilesState::from_json(row),
1791                        )
1792                    })
1793                    .collect();
1794            }
1795            if truthy(&state["private"]) {
1796                machine.private = truthy(&state["private"]["on"]);
1797                machine.private_reason = js_string(state["private"].get("reason"), "");
1798            }
1799        }
1800        if let Some(cursor) = cursor {
1801            self.hooks().on_cursor(self, &cursor);
1802        }
1803    }
1804
1805    pub fn watch(&self, hooks: Arc<dyn MachineRoomHooks>) {
1806        if let Some(web) = hooks.web() {
1807            self.inner.web.set_hooks(web);
1808        }
1809        *lock(&self.inner.hooks) = hooks;
1810    }
1811
1812    /// Whether your actions run: you control it and no agent holds it.
1813    pub fn controlling(&self, me: &Presence) -> bool {
1814        let machine = self.machine_state();
1815        machine.agent.is_none() && machine.controller == Some(me.id())
1816    }
1817
1818    /// Hand control to a seat, or take it yourself without one. While an agent holds the machine this stops the agent.
1819    pub async fn set_controller(&self, seat: Option<&str>) -> Result<()> {
1820        let data = match seat.filter(|seat| !seat.is_empty()) {
1821            Some(seat) => json!({ "seat": seat }),
1822            None => json!({}),
1823        };
1824        self.request("control-call", data, CONTROL_MS, "Control timed out.")
1825            .await?;
1826        Ok(())
1827    }
1828
1829    /// Presence changed: tell whoever is watching now.
1830    pub fn emit_presence(&self) {
1831        self.hooks().on_presence(self);
1832    }
1833
1834    pub fn emit_closed(&self) {
1835        self.hooks().on_closed(self);
1836    }
1837
1838    fn apply_control(&self, control: &Value) {
1839        let mut machine = self.machine_state();
1840        machine.controller = control["controller"].as_str().map(str::to_string);
1841        machine.agent = if control["agent"].is_object() {
1842            Some(RoomAgent::from_json(&control["agent"]))
1843        } else {
1844            None
1845        };
1846    }
1847
1848    /// Run a tool as this seat and resolve with what it answers: a file tool's data, or
1849    /// `{ text }`, the machine's own words. Only the controller's tools run. `wait` pauses here,
1850    /// at most `WAIT_MAX_SECONDS`.
1851    pub async fn invoke_tool(&self, tool: &MachineTool) -> Result<Map<String, Value>> {
1852        if let MachineTool::Wait { seconds } = tool {
1853            let seconds = if seconds.is_nan() {
1854                0.0
1855            } else {
1856                seconds.clamp(0.0, WAIT_MAX_SECONDS as f64)
1857            };
1858            tokio::time::sleep(Duration::from_secs_f64(seconds)).await;
1859            return Ok(Map::from_iter([(
1860                "text".to_string(),
1861                Value::String(format!("Waited {seconds} seconds.")),
1862            )]));
1863        }
1864        let kind = js_string(Some(&serde_json::to_value(tool)?["kind"]), "");
1865        let result = if tool.is_input() {
1866            self.request(
1867                "machine-tool-call",
1868                json!({ "tool": tool }),
1869                INPUT_MS,
1870                &format!("Tool timed out: {kind}"),
1871            )
1872            .await?
1873        } else {
1874            self.call(json!({ "kind": "tool", "tool": tool }), CALL_MS)
1875                .await?
1876        };
1877        match result {
1878            Value::Object(result) => Ok(result),
1879            _ => Err(Error::Message(format!(
1880                "The machine answered {kind} without an object."
1881            ))),
1882        }
1883    }
1884
1885    /// Run a shell command as `agent` in /repository with DISPLAY=:0, so GUI apps open as desktop windows.
1886    pub async fn exec(&self, command: &str, opts: ExecOptions) -> Result<ExecResult> {
1887        let timeout_ms = opts.timeout_ms.unwrap_or(EXEC_MS);
1888        let result = self
1889            .call(
1890                json!({ "kind": "exec", "command": command, "timeoutMs": timeout_ms }),
1891                timeout_ms + 15_000,
1892            )
1893            .await?;
1894        Ok(ExecResult {
1895            code: match result.get("code") {
1896                None | Some(Value::Null) => -1,
1897                code => js_number(code) as i64,
1898            },
1899            stdout: js_string(result.get("stdout"), ""),
1900            stderr: js_string(result.get("stderr"), ""),
1901        })
1902    }
1903
1904    /// Size the machine's desktop to this seat's screen, clamped to `VIEWPORT`. Only the controller can.
1905    pub async fn set_viewport(&self, width: f64, height: f64) -> Result<()> {
1906        let size = clamp_viewport(Viewport { width, height });
1907        self.call(
1908            json!({ "kind": "viewport", "width": size.width, "height": size.height }),
1909            CALL_MS,
1910        )
1911        .await?;
1912        Ok(())
1913    }
1914
1915    /// Open a file in an app on the machine, for everyone to see: text and code in an editor
1916    /// window, images, PDFs, video and audio in a preview, anything else with an installed
1917    /// opener. Only the controller can.
1918    pub async fn open(&self, path: &str) -> Result<()> {
1919        self.call(json!({ "kind": "open", "path": path }), CALL_MS)
1920            .await?;
1921        Ok(())
1922    }
1923
1924    /// Put a Files window on a folder and view for every seat. Only the controller can.
1925    pub async fn set_files(&self, window: u64, files: &FilesState) -> Result<()> {
1926        self.call(
1927            json!({ "kind": "files", "window": window, "path": files.path, "view": files.view }),
1928            CALL_MS,
1929        )
1930        .await?;
1931        Ok(())
1932    }
1933
1934    /// Save a new revision and shut down. The room closes afterwards.
1935    pub async fn stop(&self) -> Result<()> {
1936        match self.call(json!({ "kind": "stop" }), STOP_MS).await {
1937            Ok(_) => Ok(()),
1938            // The machine announces it closed before it answers the stop itself.
1939            Err(_) if self.status() == MachineStatus::Stopped => Ok(()),
1940            Err(error) => Err(error),
1941        }
1942    }
1943
1944    async fn call(&self, call: Value, timeout_ms: u64) -> Result<Value> {
1945        self.request(
1946            "machine-call",
1947            json!({ "call": call }),
1948            timeout_ms,
1949            "Machine call timed out.",
1950        )
1951        .await
1952    }
1953
1954    /// Posts `event` with a new id; its answer (`control-result`, `machine-tool-result` or
1955    /// `machine-result`) settles it.
1956    async fn request(
1957        &self,
1958        event: &str,
1959        mut data: Value,
1960        timeout_ms: u64,
1961        timed_out: &str,
1962    ) -> Result<Value> {
1963        let id = uuid::Uuid::new_v4().to_string();
1964        let (resolve, result) = oneshot::channel();
1965        lock(&self.inner.calls).insert(id.clone(), resolve);
1966        data["id"] = json!(id);
1967        self.post(&json!({ "event": event, "data": data }));
1968        match tokio::time::timeout(Duration::from_millis(timeout_ms), result).await {
1969            Ok(Ok(result)) => result,
1970            Ok(Err(_)) => Err(Error::Message("Machine closed.".to_string())),
1971            Err(_) => {
1972                lock(&self.inner.calls).remove(&id);
1973                Err(Error::Message(timed_out.to_string()))
1974            }
1975        }
1976    }
1977
1978    fn settle(&self, data: &Value) {
1979        let Some(id) = data["id"].as_str() else {
1980            return;
1981        };
1982        let Some(pending) = lock(&self.inner.calls).remove(id) else {
1983            return;
1984        };
1985        let _ = pending.send(if truthy(&data["error"]) {
1986            Err(Error::Message(js_string(data.get("error"), "")))
1987        } else {
1988            Ok(data["result"].clone())
1989        });
1990    }
1991
1992    pub fn parrot_tools(&self) -> Vec<Tool> {
1993        let invoking = self.clone();
1994        let executing = self.clone();
1995        parrot_tools(
1996            Arc::new(move |tool| {
1997                let room = invoking.clone();
1998                Box::pin(async move { room.invoke_tool(&tool).await })
1999            }),
2000            Arc::new(move |command, timeout_ms| {
2001                let room = executing.clone();
2002                Box::pin(async move {
2003                    let result = room
2004                        .exec(
2005                            &command,
2006                            ExecOptions {
2007                                timeout_ms: timeout_ms.map(|ms| ms as u64),
2008                            },
2009                        )
2010                        .await?;
2011                    Ok(serde_json::from_value(serde_json::to_value(result)?)?)
2012                })
2013            }),
2014        )
2015    }
2016
2017    /// A binary frame: an app frame reaches `on_app_frame`.
2018    pub fn handle_binary(&self, data: &[u8]) -> bool {
2019        let Some(frame) = AppFrame::from_bytes(data) else {
2020            return false;
2021        };
2022        self.hooks().on_app_frame(self, &frame);
2023        true
2024    }
2025
2026    /// Ask for a whole picture of app window `window`, after a frame of it was skipped. Anyone
2027    /// in the room can.
2028    pub fn repaint(&self, window: u32) {
2029        self.post(&json!({ "event": "app-repaint", "data": { "window": window } }));
2030    }
2031
2032    pub fn handle_event(&self, packet: &Value) -> bool {
2033        if self.inner.web.handle_event(packet) {
2034            return true;
2035        }
2036        let data = &packet["data"];
2037        let hooks = self.hooks();
2038        match packet["event"].as_str().unwrap_or_default() {
2039            "room-control" => {
2040                let empty = json!({});
2041                self.apply_control(if data.is_object() { data } else { &empty });
2042                hooks.on_control(self);
2043                true
2044            }
2045            "machine-cursor" => {
2046                if let Ok(cursor) = serde_json::from_value::<HtmlPointer>(data["cursor"].clone()) {
2047                    self.machine_state().cursor = cursor.clone();
2048                    hooks.on_cursor(self, &cursor);
2049                }
2050                true
2051            }
2052            "machine-tool-call" => {
2053                if let Ok(tool) = serde_json::from_value::<MachineTool>(data["tool"].clone()) {
2054                    hooks.on_tool(self, &tool);
2055                }
2056                true
2057            }
2058            "control-result" | "machine-tool-result" | "machine-result" => {
2059                self.settle(data);
2060                true
2061            }
2062            "machine-status" => {
2063                if let Ok(status) = serde_json::from_value(data["status"].clone()) {
2064                    self.machine_state().status = status;
2065                }
2066                hooks.on_status(self);
2067                true
2068            }
2069            "machine-window" => {
2070                if !truthy(&data["window"]) {
2071                    return true;
2072                }
2073                let window = Window::from_json(&data["window"]);
2074                self.machine_state()
2075                    .windows
2076                    .insert(window.id, window.clone());
2077                hooks.on_window(self, &window);
2078                true
2079            }
2080            "machine-window-closed" => {
2081                let id = js_number(data.get("id")) as u64;
2082                {
2083                    let mut machine = self.machine_state();
2084                    machine.windows.remove(&id);
2085                    machine.files.remove(&id);
2086                }
2087                hooks.on_window_closed(self, id);
2088                true
2089            }
2090            "machine-files" => {
2091                let window = js_number(data.get("window")) as u64;
2092                let files = FilesState::from_json(data);
2093                self.machine_state().files.insert(window, files.clone());
2094                hooks.on_files(self, window, &files);
2095                true
2096            }
2097            "machine-private" => {
2098                {
2099                    let mut machine = self.machine_state();
2100                    machine.private = truthy(&data["on"]);
2101                    machine.private_reason = js_string(data.get("reason"), "");
2102                }
2103                hooks.on_private(self);
2104                true
2105            }
2106            "machine-agent-step" => {
2107                if let Ok(step) = serde_json::from_value::<AgentStep>(data.clone()) {
2108                    hooks.on_agent_step(self, &step);
2109                }
2110                true
2111            }
2112            "machine-closed" => {
2113                {
2114                    let mut machine = self.machine_state();
2115                    if let Ok(status) = serde_json::from_value(data["status"].clone()) {
2116                        machine.status = status;
2117                    }
2118                    if let Some(error) = data.get("error") {
2119                        machine.error = js_string(Some(error), "");
2120                    }
2121                }
2122                hooks.on_status(self);
2123                for (_, pending) in lock(&self.inner.calls).drain() {
2124                    let _ = pending.send(Err(Error::Message("Machine closed.".to_string())));
2125                }
2126                hooks.on_closed(self);
2127                true
2128            }
2129            _ => false,
2130        }
2131    }
2132
2133    /// Boot the repository's machine, or return the one already live, and connect to it.
2134    /// `spec` is what it asks for; `room.spec()` is what it was granted, and a live machine
2135    /// keeps its own. `private` sends its connections out from a residential address, billed
2136    /// per GB to whoever pays for the machine; on a live machine it switches it.
2137    pub async fn start(
2138        authorization: &CredentialsOrApiKey,
2139        repository: u64,
2140        opts: StartOptions,
2141    ) -> Result<(MachineRoom, Presence)> {
2142        let mut body = json!({ "spec": opts.spec });
2143        if let Some(private) = opts.private {
2144            body["private"] = json!(private);
2145        }
2146        let response = authorized(
2147            crate::http::client().post(format!(
2148                "{}/termite/repositories/{repository}/machine",
2149                super::get_url()
2150            )),
2151            authorization,
2152            opts.group.as_ref(),
2153        )
2154        .json(&body)
2155        .send()
2156        .await?;
2157        let json: Value = crate::http::ok(response).await?.json().await?;
2158        MachineRoom::connect(
2159            authorization,
2160            &MachineTarget::Id {
2161                id: js_number(json.get("id")) as u64,
2162            },
2163            MachineOptions {
2164                group: opts.group,
2165                hooks: opts.hooks,
2166            },
2167        )
2168        .await
2169    }
2170
2171    /// Save and shut down a repository's machine without joining its room. For its owner or group members.
2172    pub async fn shutdown(
2173        authorization: &CredentialsOrApiKey,
2174        repository: u64,
2175        opts: GroupOptions,
2176    ) -> Result<()> {
2177        let response = authorized(
2178            crate::http::client().post(format!(
2179                "{}/termite/repositories/{repository}/machine/stop",
2180                super::get_url()
2181            )),
2182            authorization,
2183            opts.group.as_ref(),
2184        )
2185        .json(&json!({}))
2186        .send()
2187        .await?;
2188        crate::http::ok(response).await?;
2189        Ok(())
2190    }
2191
2192    /// Turn private on or off for a repository's live machine, for its owner or group members.
2193    /// Resolves to the machine's private state and, while it's paused, why.
2194    pub async fn set_private(
2195        authorization: &CredentialsOrApiKey,
2196        repository: u64,
2197        on: bool,
2198        opts: GroupOptions,
2199    ) -> Result<PrivateState> {
2200        let response = authorized(
2201            crate::http::client().post(format!(
2202                "{}/termite/repositories/{repository}/machine/private",
2203                super::get_url()
2204            )),
2205            authorization,
2206            opts.group.as_ref(),
2207        )
2208        .json(&json!({ "on": on }))
2209        .send()
2210        .await?;
2211        let json: Value = crate::http::ok(response).await?.json().await?;
2212        Ok(PrivateState {
2213            on: truthy(&json["on"]),
2214            reason: js_string(json.get("reason"), ""),
2215        })
2216    }
2217
2218    /// Connect to a live machine by id, or by its `termite:machine:{id}` reference.
2219    pub async fn connect(
2220        authorization: &CredentialsOrApiKey,
2221        target: &MachineTarget,
2222        opts: MachineOptions,
2223    ) -> Result<(MachineRoom, Presence)> {
2224        MachineRoom::open_room(
2225            Authorization::Server {
2226                authorization: authorization.clone(),
2227                server: match target {
2228                    MachineTarget::Id { id } => format!("termite:machine:{id}"),
2229                    MachineTarget::Reference { reference } => reference.clone(),
2230                },
2231                group: opts.group.as_ref().map(|group| group.id.clone()),
2232            },
2233            opts.hooks.unwrap_or_else(|| Arc::new(())),
2234        )
2235        .await
2236    }
2237
2238    /// Join a machine someone shared with an access code.
2239    pub async fn join(
2240        authorization: &CredentialsOrApiKey,
2241        access_code: &str,
2242        opts: MachineOptions,
2243    ) -> Result<(MachineRoom, Presence)> {
2244        MachineRoom::open_room(
2245            Authorization::AccessCode {
2246                authorization: authorization.clone(),
2247                access_code: access_code.to_string(),
2248            },
2249            opts.hooks.unwrap_or_else(|| Arc::new(())),
2250        )
2251        .await
2252    }
2253
2254    async fn open_room(
2255        auth: Authorization,
2256        hooks: Arc<dyn MachineRoomHooks>,
2257    ) -> Result<(MachineRoom, Presence)> {
2258        let machine_hooks = Arc::new(MachineHooks {
2259            room: Mutex::new(None),
2260            hooks,
2261        });
2262        let me = connect_server(
2263            auth,
2264            &format!("{}/termite/machine/live", super::get_url()),
2265            machine_hooks.clone(),
2266        )
2267        .await?;
2268        let room = machine_hooks
2269            .room()
2270            .ok_or_else(|| Error::Message("Room not found".to_string()))?;
2271        room.emit_presence();
2272        Ok((room, me))
2273    }
2274}
2275
2276struct MachineHooks {
2277    room: Mutex<Option<MachineRoom>>,
2278    hooks: Arc<dyn MachineRoomHooks>,
2279}
2280
2281impl MachineHooks {
2282    fn room(&self) -> Option<MachineRoom> {
2283        lock(&self.room).clone()
2284    }
2285}
2286
2287impl Hooks for MachineHooks {
2288    fn create_room(&self, room: &Room, state: &Value) {
2289        *lock(&self.room) = Some(MachineRoom::create(room, self.hooks.clone(), state));
2290    }
2291
2292    fn on_presence(&self, _room: &Room) {
2293        if let Some(room) = self.room() {
2294            room.emit_presence();
2295        }
2296    }
2297
2298    fn on_connection(&self, _room: &Room, state: &Value) {
2299        if let Some(room) = self.room() {
2300            room.hydrate(state);
2301        }
2302    }
2303
2304    fn on_event(&self, _room: &Room, packet: &Value) -> bool {
2305        self.room().is_some_and(|room| room.handle_event(packet))
2306    }
2307
2308    fn on_binary(&self, _room: &Room, data: &[u8]) {
2309        if let Some(room) = self.room() {
2310            room.handle_binary(data);
2311        }
2312    }
2313
2314    fn on_closed(&self, _room: &Room, _reason: Option<&str>) {
2315        if let Some(room) = self.room() {
2316            room.emit_closed();
2317        }
2318    }
2319}
2320
2321#[cfg(test)]
2322mod tests {
2323    use super::*;
2324
2325    #[test]
2326    fn reads_an_app_frames_header_and_its_jpeg() {
2327        let mut data = vec![1u8, 1];
2328        data.extend(0x0040_0007u32.to_be_bytes());
2329        data.extend(9u32.to_be_bytes());
2330        for n in [640u16, 400, 0, 0, 640, 400] {
2331            data.extend(n.to_be_bytes());
2332        }
2333        data.extend([0xff, 0xd8, 0xff]);
2334        let frame = AppFrame::from_bytes(&data).unwrap();
2335        assert_eq!(
2336            frame,
2337            AppFrame {
2338                window: 0x0040_0007,
2339                seq: 9,
2340                key: true,
2341                window_width: 640,
2342                window_height: 400,
2343                x: 0,
2344                y: 0,
2345                width: 640,
2346                height: 400,
2347                jpeg: vec![0xff, 0xd8, 0xff],
2348            }
2349        );
2350        data[1] = 0;
2351        assert!(!AppFrame::from_bytes(&data).unwrap().key);
2352        assert_eq!(AppFrame::from_bytes(&data[..21]), None);
2353        data[0] = 2;
2354        assert_eq!(AppFrame::from_bytes(&data), None);
2355    }
2356
2357    #[test]
2358    fn reads_media_with_its_captions() {
2359        let video = Media::from_json(&json!({
2360            "kind": "video", "title": "Signup", "path": "/termite/repositories/1/media/2.mp4",
2361            "durationMs": 7_200, "captions": [{ "startMs": 1_200, "endMs": 3_000, "text": "Typing" }],
2362            "frameRate": 24.5,
2363        }));
2364        assert_eq!(
2365            video,
2366            Media {
2367                kind: MediaKind::Video,
2368                title: "Signup".into(),
2369                path: "/termite/repositories/1/media/2.mp4".into(),
2370                duration_ms: Some(7_200.0),
2371                captions: Some(vec![Caption {
2372                    start_ms: 1_200.0,
2373                    end_ms: 3_000.0,
2374                    text: "Typing".into(),
2375                }]),
2376                frame_rate: Some(24.5),
2377            }
2378        );
2379        let photo =
2380            Media::from_json(&json!({ "kind": "photo", "title": "Saved", "path": "/p.jpg" }));
2381        assert_eq!(photo.kind, MediaKind::Photo);
2382        assert_eq!(
2383            (photo.duration_ms, photo.captions, photo.frame_rate),
2384            (None, None, None)
2385        );
2386    }
2387}