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