fauna-api 1.0.815

The Fauna SDK for Rust: accounts, Drive, groups, calendar, chats, payments, Parrot and live rooms.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
//! A live machine: one running boot of a Repository. It's a PageRoom whose
//! page is the machine's desktop, one HTML page that is the whole OS, so it
//! streams like any browser room. Window tools, file tools, exec, and stop ride
//! the same socket as `machine-call`.

use std::collections::{HashMap, HashSet};
use std::ops::Deref;
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::time::Duration;

use chrono::{DateTime, Utc};
use futures_util::future::BoxFuture;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value, json};
use tokio::sync::oneshot;

use super::versioning::Repository;
use crate::authentification::CredentialsOrApiKey;
use crate::billing::PageQuery;
use crate::error::{Error, Result};
use crate::groups::Group;
use crate::marmot::browser::{
    BrowserRoomHooks, BrowserTool, PageRoom, js_number, js_string,
    parrot_tools as browser_parrot_tools, present, tool,
};
use crate::marmot::web::{BootstrapMeta, HtmlPointer};
use crate::parrot::generative::{Function, Tool, Usage};
use crate::shared::schema::Schema;
use crate::shared::server::{Authorization, Hooks, Presence, Room, connect as connect_server};

/// `'web' | 'files' | 'file' | 'terminal'` in the TypeScript SDK.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum WindowApp {
    Web,
    Files,
    File,
    Terminal,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "lowercase")]
pub enum WindowTool {
    Windows,
    Focus {
        window: f64,
    },
    Place {
        window: f64,
        x: f64,
        y: f64,
    },
    Resize {
        window: f64,
        width: f64,
        height: f64,
    },
    Close {
        window: f64,
    },
    /// Load a Web window's page again, after its files change. Previews follow their file on their own.
    Reload {
        window: f64,
    },
    /// A web window at `url`; a files window at `path` (a folder of /repository); a preview of the
    /// file at `path`, which follows the file as it changes; or a terminal, running `command` in
    /// view and staying open at a prompt when it ends.
    Open {
        app: WindowApp,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        url: Option<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        path: Option<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        command: Option<String>,
    },
    /// A chord like ['ctrl', 's']. Focuses `window` first when given.
    Key {
        keys: Vec<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        window: Option<f64>,
    },
}

/// `'files' | 'lines' | 'count'` in the TypeScript SDK.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum GrepOutput {
    Files,
    Lines,
    Count,
}

/// Paths are relative to /repository, and `/` is the repository root.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(
    tag = "kind",
    rename_all = "lowercase",
    rename_all_fields = "camelCase"
)]
pub enum FileTool {
    List {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        path: Option<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pattern: Option<String>,
    },
    Grep {
        pattern: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        path: Option<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        glob: Option<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        ignore_case: Option<bool>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        context: Option<f64>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        output: Option<GrepOutput>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        max: Option<f64>,
    },
    Read {
        path: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        line: Option<f64>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        before: Option<f64>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        after: Option<f64>,
    },
    Write {
        path: String,
        text: String,
    },
    Replace {
        path: String,
        old: String,
        new: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        all: Option<bool>,
    },
    Insert {
        path: String,
        after: f64,
        text: String,
    },
    Remove {
        path: String,
        start: f64,
        end: f64,
    },
}

/// `'cpu' | 'memory'` in the TypeScript SDK.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ProcessSort {
    Cpu,
    Memory,
}

/// `'TERM' | 'KILL'` in the TypeScript SDK.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum ProcessSignal {
    Term,
    Kill,
}

/// The guest's processes. `kill` stops only the agent user's own, never the machine's or the desktop's.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "lowercase")]
pub enum ProcessTool {
    Processes {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        sort: Option<ProcessSort>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        limit: Option<f64>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        filter: Option<String>,
    },
    Kill {
        pid: f64,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        signal: Option<ProcessSignal>,
    },
}

/// `'private' | 'public'` in the TypeScript SDK.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum InternetMode {
    Private,
    Public,
}

/// How the machine reaches the internet: `private` only from a residential address, billed per
/// GB to whoever pays for the machine, or `public` from its own.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "lowercase")]
pub enum InternetTool {
    Internet { mode: InternetMode },
}

/// Pointer and keyboard input on the desktop: the browser tools but
/// `executeJavascript`, which would run on the desktop page itself, and `search`
/// and `exit`, which belong to a web page's agent.
pub type DesktopTool = BrowserTool;

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
#[allow(clippy::large_enum_variant)]
pub enum MachineTool {
    Desktop(DesktopTool),
    Window(WindowTool),
    File(FileTool),
    Process(ProcessTool),
    Internet(InternetTool),
}

/// `'app' | 'web' | 'files' | 'preview'` in the TypeScript SDK.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum WindowKind {
    App,
    Web,
    Files,
    Preview,
}

/// Metadata for one desktop window. Its pixels live in the desktop HTML.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Window {
    /// Same id as the element's data-window and the window tools.
    pub id: u64,
    pub kind: WindowKind,
    /// WM_CLASS for apps ('xterm'), 'web', 'files', or 'preview'.
    pub app: String,
    pub title: String,
    pub x: f64,
    pub y: f64,
    pub width: f64,
    pub height: f64,
    pub focused: bool,
}

fn truthy(value: &Value) -> bool {
    match value {
        Value::Null => false,
        Value::Bool(value) => *value,
        Value::Number(number) => number
            .as_f64()
            .is_some_and(|number| number != 0.0 && !number.is_nan()),
        Value::String(text) => !text.is_empty(),
        _ => true,
    }
}

impl Window {
    pub fn from_json(json: &Value) -> Window {
        let kind = match json["kind"].as_str() {
            Some("web") => WindowKind::Web,
            Some("files") => WindowKind::Files,
            Some("preview") => WindowKind::Preview,
            _ => WindowKind::App,
        };
        let kind_name = match kind {
            WindowKind::App => "app",
            WindowKind::Web => "web",
            WindowKind::Files => "files",
            WindowKind::Preview => "preview",
        };
        Window {
            id: js_number(json.get("id")) as u64,
            kind,
            app: js_string(json.get("app"), kind_name),
            title: js_string(json.get("title"), ""),
            x: json["x"].as_f64().unwrap_or_default(),
            y: json["y"].as_f64().unwrap_or_default(),
            width: json["width"].as_f64().unwrap_or_default(),
            height: json["height"].as_f64().unwrap_or_default(),
            focused: truthy(&json["focused"]),
        }
    }
}

/// `'list' | 'cozy'` in the TypeScript SDK.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum FilesView {
    List,
    Cozy,
}

/// The folder and view a Files window is on. The controller sets it; every seat follows.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FilesState {
    pub path: String,
    pub view: FilesView,
}

impl FilesState {
    pub fn from_json(json: &Value) -> FilesState {
        FilesState {
            path: js_string(json.get("path"), ""),
            view: if json["view"] == "cozy" {
                FilesView::Cozy
            } else {
                FilesView::List
            },
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum MachineStatus {
    Booting,
    Running,
    Stopping,
    Stopped,
    Failed,
}

#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct Viewport {
    pub width: f64,
    pub height: f64,
}

/// `{ min, max }` in the TypeScript SDK.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct ViewportBounds {
    pub min: Viewport,
    pub max: Viewport,
}

/// The smallest and largest desktop a machine draws. The largest is the guest's X screen.
pub const VIEWPORT: ViewportBounds = ViewportBounds {
    min: Viewport {
        width: 640.0,
        height: 400.0,
    },
    max: Viewport {
        width: 2560.0,
        height: 1600.0,
    },
};

/// A desktop size inside `VIEWPORT`, in whole pixels.
pub fn clamp_viewport(size: Viewport) -> Viewport {
    Viewport {
        width: size
            .width
            .clamp(VIEWPORT.min.width, VIEWPORT.max.width)
            .round(),
        height: size
            .height
            .clamp(VIEWPORT.min.height, VIEWPORT.max.height)
            .round(),
    }
}

/// Machine room hooks: the page room's, plus the machine's own. Every method
/// defaults to a no-op.
pub trait MachineRoomHooks: BrowserRoomHooks {
    /// A window opened, moved, resized, retitled, or changed focus.
    fn on_window(&self, _room: &MachineRoom, _window: &Window) {}
    fn on_window_closed(&self, _room: &MachineRoom, _id: u64) {}
    /// A Files window's folder or view changed.
    fn on_files(&self, _room: &MachineRoom, _window: u64, _files: &FilesState) {}
    fn on_status(&self, _room: &MachineRoom) {}
    /// Private turned on or off, paused while it reconnects (`private_reason` says why), or came back.
    fn on_private(&self, _room: &MachineRoom) {}
    /// An agent holding the machine took a step.
    fn on_agent_step(&self, _room: &MachineRoom, _step: &AgentStep) {}
}

impl MachineRoomHooks for () {}

/// One tool call of an agent working the machine: the tool, with what, and what came back. A turn
/// with several calls arrives as several steps. Args and result are capped at about 2 KB; larger
/// args arrive as `{ truncated }`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AgentStep {
    /// The agent's id, as in the room's control state.
    pub agent: String,
    /// The turn, counting from 1.
    pub step: u64,
    /// The call's place in its turn, from 0.
    pub call: u64,
    pub tool: String,
    #[serde(default)]
    pub args: Map<String, Value>,
    #[serde(default)]
    pub result: String,
    /// The turn's model time and usage ride on its first call, so totals add up.
    #[serde(default)]
    pub model_ms: f64,
    #[serde(default)]
    pub tool_ms: f64,
    #[serde(default)]
    pub usage: Usage,
}

const DESKTOP_TOOLS: [&str; 5] = ["move", "click", "drag", "scroll", "type"];
const CALL_MS: u64 = 60_000;
const EXEC_MS: u64 = 120_000;
const STOP_MS: u64 = 10 * 60_000;

/// Runs one machine tool and returns its result as text.
pub type MachineToolInvoker =
    Arc<dyn Fn(MachineTool) -> BoxFuture<'static, Result<String>> + Send + Sync>;

/// Runs a shell command, with an optional timeout in milliseconds, and returns its result as text.
pub type ExecInvoker =
    Arc<dyn Fn(String, Option<f64>) -> BoxFuture<'static, Result<String>> + Send + Sync>;

fn optional_text(p: &Value, key: &str) -> Option<String> {
    present(p.get(key)).map(|value| js_string(Some(value), ""))
}

fn optional_number(p: &Value, key: &str) -> Option<f64> {
    present(p.get(key)).map(|value| js_number(Some(value)))
}

/// Every machine tool for a model: desktop input, windows, files, processes, the internet switch, and exec.
/// `invoke` runs a tool; `exec` runs a shell command and returns its result as text.
pub fn parrot_tools(invoke: MachineToolInvoker, exec: ExecInvoker) -> Vec<Tool> {
    let desktop = invoke.clone();
    let mut tools = browser_parrot_tools(
        &DESKTOP_TOOLS
            .iter()
            .map(|kind| kind.to_string())
            .collect::<HashSet<_>>(),
        Arc::new(move |tool| desktop(MachineTool::Desktop(tool))),
    );
    let mut add = |name: &str,
                   description: &str,
                   properties: Value,
                   required: &[&str],
                   build: fn(&Value) -> MachineTool| {
        let mut parameters = json!({ "type": "OBJECT", "properties": properties });
        if !required.is_empty() {
            parameters["required"] = json!(required);
        }
        let invoke = invoke.clone();
        tools.push(tool(name, description, parameters, move |params: Value| {
            let params = if params.is_null() { json!({}) } else { params };
            invoke(build(&params))
        }));
    };

    add(
        "windows",
        "List every open desktop window with its id, kind, app, title, position, size, and focus.",
        json!({}),
        &[],
        |_| MachineTool::Window(WindowTool::Windows),
    );
    add(
        "focus",
        "Bring a window to the front and give it keyboard focus.",
        json!({
            "window": { "type": "NUMBER", "description": "Window id" },
        }),
        &["window"],
        |p| {
            MachineTool::Window(WindowTool::Focus {
                window: js_number(p.get("window")),
            })
        },
    );
    add(
        "place",
        "Move a window so its top left corner is at desktop coordinates.",
        json!({
            "window": { "type": "NUMBER", "description": "Window id" },
            "x": { "type": "NUMBER", "description": "Desktop X pixel" },
            "y": { "type": "NUMBER", "description": "Desktop Y pixel" },
        }),
        &["window", "x", "y"],
        |p| {
            MachineTool::Window(WindowTool::Place {
                window: js_number(p.get("window")),
                x: js_number(p.get("x")),
                y: js_number(p.get("y")),
            })
        },
    );
    add(
        "resize",
        "Resize a window. Apps redraw at the new size.",
        json!({
            "window": { "type": "NUMBER", "description": "Window id" },
            "width": { "type": "NUMBER", "description": "Width in pixels" },
            "height": { "type": "NUMBER", "description": "Height in pixels" },
        }),
        &["window", "width", "height"],
        |p| {
            MachineTool::Window(WindowTool::Resize {
                window: js_number(p.get("window")),
                width: js_number(p.get("width")),
                height: js_number(p.get("height")),
            })
        },
    );
    add(
        "close",
        "Close a window.",
        json!({
            "window": { "type": "NUMBER", "description": "Window id" },
        }),
        &["window"],
        |p| {
            MachineTool::Window(WindowTool::Close {
                window: js_number(p.get("window")),
            })
        },
    );
    add(
        "reload",
        "Reload a Web window after its page's files change, so it shows them. Previews follow their file on their own, and reload too.",
        json!({
            "window": { "type": "NUMBER", "description": "Window id" },
        }),
        &["window"],
        |p| {
            MachineTool::Window(WindowTool::Reload {
                window: js_number(p.get("window")),
            })
        },
    );
    add(
        "open",
        "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 previews a file (images, PDFs, video, audio, text); 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. A preview follows its file as it changes.",
        json!({
            "app": { "type": "STRING", "enum": ["web", "files", "file", "terminal"], "description": "web, files, file or terminal" },
            "url": { "type": "STRING", "description": "http or https address for a web window" },
            "path": { "type": "STRING", "description": "Folder for files, or the file to preview, relative to /repository" },
            "command": { "type": "STRING", "description": "Command for a terminal to run in view" },
        }),
        &["app"],
        |p| {
            MachineTool::Window(WindowTool::Open {
                app: match p.get("app").and_then(Value::as_str) {
                    Some("files") => WindowApp::Files,
                    Some("file") => WindowApp::File,
                    Some("terminal") => WindowApp::Terminal,
                    _ => WindowApp::Web,
                },
                url: optional_text(p, "url"),
                path: optional_text(p, "path"),
                command: optional_text(p, "command"),
            })
        },
    );
    add(
        "key",
        "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.",
        json!({
            "keys": { "type": "ARRAY", "items": { "type": "STRING" }, "description": "Keys held together, e.g. [\"ctrl\", \"s\"]" },
            "window": { "type": "NUMBER", "description": "Window id to focus first" },
        }),
        &["keys"],
        |p| {
            MachineTool::Window(WindowTool::Key {
                keys: p
                    .get("keys")
                    .and_then(Value::as_array)
                    .map(|keys| keys.iter().map(|key| js_string(Some(key), "")).collect())
                    .unwrap_or_default(),
                window: optional_number(p, "window"),
            })
        },
    );

    add(
        "list",
        "List files under a folder of /repository. Folders end in a slash. With pattern (like **/*.ts) it matches recursively.",
        json!({
            "path": { "type": "STRING", "description": "Folder relative to /repository. Defaults to the root." },
            "pattern": { "type": "STRING", "description": "Glob to match recursively" },
        }),
        &[],
        |p| {
            MachineTool::File(FileTool::List {
                path: optional_text(p, "path"),
                pattern: optional_text(p, "pattern"),
            })
        },
    );
    add(
        "grep",
        "Search file contents in /repository with ripgrep. Output is matching files by default, or lines with context, or counts.",
        json!({
            "pattern": { "type": "STRING", "description": "Regular expression" },
            "path": { "type": "STRING", "description": "Folder or file to search" },
            "glob": { "type": "STRING", "description": "Only files matching this glob" },
            "ignoreCase": { "type": "BOOLEAN", "description": "Case insensitive" },
            "context": { "type": "NUMBER", "description": "Lines of context around each match" },
            "output": { "type": "STRING", "enum": ["files", "lines", "count"], "description": "files, lines, or count" },
            "max": { "type": "NUMBER", "description": "Result cap, default 50" },
        }),
        &["pattern"],
        |p| {
            MachineTool::File(FileTool::Grep {
                pattern: js_string(p.get("pattern"), ""),
                path: optional_text(p, "path"),
                glob: optional_text(p, "glob"),
                ignore_case: present(p.get("ignoreCase")).map(truthy),
                context: optional_number(p, "context"),
                output: present(p.get("output"))
                    .and_then(|output| serde_json::from_value(output.clone()).ok()),
                max: optional_number(p, "max"),
            })
        },
    );
    add(
        "read",
        "Read numbered lines of a file: from line minus before to line plus after. Defaults to the first 100 lines.",
        json!({
            "path": { "type": "STRING", "description": "File relative to /repository" },
            "line": { "type": "NUMBER", "description": "Line to center on, default 1" },
            "before": { "type": "NUMBER", "description": "Lines before, default 0" },
            "after": { "type": "NUMBER", "description": "Lines after, default 100" },
        }),
        &["path"],
        |p| {
            MachineTool::File(FileTool::Read {
                path: js_string(p.get("path"), ""),
                line: optional_number(p, "line"),
                before: optional_number(p, "before"),
                after: optional_number(p, "after"),
            })
        },
    );
    add(
        "write",
        "Create or overwrite a file, creating missing folders.",
        json!({
            "path": { "type": "STRING", "description": "File relative to /repository" },
            "text": { "type": "STRING", "description": "Full file contents" },
        }),
        &["path", "text"],
        |p| {
            MachineTool::File(FileTool::Write {
                path: js_string(p.get("path"), ""),
                text: js_string(p.get("text"), ""),
            })
        },
    );
    add(
        "replace",
        "Replace an exact string in a file. old must match exactly once unless all is true. Prefer this for edits.",
        json!({
            "path": { "type": "STRING", "description": "File relative to /repository" },
            "old": { "type": "STRING", "description": "Exact text to find" },
            "new": { "type": "STRING", "description": "Replacement text" },
            "all": { "type": "BOOLEAN", "description": "Replace every match" },
        }),
        &["path", "old", "new"],
        |p| {
            MachineTool::File(FileTool::Replace {
                path: js_string(p.get("path"), ""),
                old: js_string(p.get("old"), ""),
                new: js_string(p.get("new"), ""),
                all: present(p.get("all")).map(truthy),
            })
        },
    );
    add(
        "insert",
        "Insert text after a line number. 0 inserts at the top. Read the file first.",
        json!({
            "path": { "type": "STRING", "description": "File relative to /repository" },
            "after": { "type": "NUMBER", "description": "Line to insert after" },
            "text": { "type": "STRING", "description": "Text to insert" },
        }),
        &["path", "after", "text"],
        |p| {
            MachineTool::File(FileTool::Insert {
                path: js_string(p.get("path"), ""),
                after: js_number(p.get("after")),
                text: js_string(p.get("text"), ""),
            })
        },
    );
    add(
        "remove",
        "Delete lines start through end, inclusive. Read the file first.",
        json!({
            "path": { "type": "STRING", "description": "File relative to /repository" },
            "start": { "type": "NUMBER", "description": "First line" },
            "end": { "type": "NUMBER", "description": "Last line" },
        }),
        &["path", "start", "end"],
        |p| {
            MachineTool::File(FileTool::Remove {
                path: js_string(p.get("path"), ""),
                start: js_number(p.get("start")),
                end: js_number(p.get("end")),
            })
        },
    );

    add(
        "processes",
        "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.",
        json!({
            "sort": { "type": "STRING", "enum": ["cpu", "memory"], "description": "cpu or memory, default cpu" },
            "limit": { "type": "NUMBER", "description": "How many to list, default 25" },
            "filter": { "type": "STRING", "description": "Only commands containing this text" },
        }),
        &[],
        |p| {
            MachineTool::Process(ProcessTool::Processes {
                sort: match p.get("sort").and_then(Value::as_str) {
                    Some("memory") => Some(ProcessSort::Memory),
                    Some("cpu") => Some(ProcessSort::Cpu),
                    _ => None,
                },
                limit: optional_number(p, "limit"),
                filter: optional_text(p, "filter"),
            })
        },
    );
    add(
        "kill",
        "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.",
        json!({
            "pid": { "type": "NUMBER", "description": "Process id from processes" },
            "signal": { "type": "STRING", "enum": ["TERM", "KILL"], "description": "TERM (default) or KILL" },
        }),
        &["pid"],
        |p| {
            MachineTool::Process(ProcessTool::Kill {
                pid: js_number(p.get("pid")),
                signal: match p.get("signal").and_then(Value::as_str) {
                    Some("KILL") => Some(ProcessSignal::Kill),
                    Some("TERM") => Some(ProcessSignal::Term),
                    _ => None,
                },
            })
        },
    );

    add(
        "internet",
        "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.",
        json!({
            "mode": { "type": "STRING", "enum": ["private", "public"], "description": "private or public" },
        }),
        &["mode"],
        |p| {
            MachineTool::Internet(InternetTool::Internet {
                mode: if p.get("mode").and_then(Value::as_str) == Some("public") {
                    InternetMode::Public
                } else {
                    InternetMode::Private
                },
            })
        },
    );

    tools.push(tool(
        "exec",
        "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.",
        json!({
            "type": "OBJECT",
            "properties": {
                "command": { "type": "STRING", "description": "Bash command" },
                "timeoutMs": { "type": "NUMBER", "description": "Timeout in ms, default 120000; pass more for installs and builds" },
            },
            "required": ["command"],
        }),
        move |params: Value| exec(js_string(params.get("command"), ""), optional_number(&params, "timeoutMs")),
    ));
    tools
}

/// `use_desktop`'s result when the person chose not to make a repository for it.
pub const DESKTOP_DECLINED: &str =
    "They chose not to use a computer for this. Do it without one if you can.";

const DESKTOP_CAPTURE: &str = "Everything it captures is attached to the chat for people to see, and comes back to you too. Set video to record the whole job as a captioned video, for when someone asks to see it done. Slower and costlier than the other tools; use it only when the screen matters.";

/// The `use_desktop` tool for a Parrot chat: a desktop agent does a job on the
/// repository's machine. Without a repository it also takes `name`, what to call
/// the repository the person is asked to make for it.
pub fn desktop_tool(repository: Option<&Repository>) -> Function {
    let mut properties = json!({
        "goal": { "type": "STRING", "description": "What the desktop agent should do, in full, with what to capture" },
        "video": { "type": "BOOLEAN", "description": "Record the whole job as a captioned video" },
    });
    if repository.is_some() {
        return Function {
            name: "use_desktop".to_string(),
            description: Some(format!(
                "Do something on the repository's desktop that needs a screen, like using an app on the machine or working across its windows. A desktop agent does it and reports back. For a website alone, use_browser is quicker. {DESKTOP_CAPTURE}"
            )),
            parameters: serde_json::from_value::<Schema>(
                json!({ "type": "OBJECT", "properties": properties, "required": ["goal"] }),
            )
            .expect("tool schemas are valid"),
            default: None,
            example: None,
            behavior: None,
        };
    }
    properties["name"] = json!({ "type": "STRING", "description": "What to call the repository this makes: two to four words about the task, like Invoice spreadsheet cleanup" });
    Function {
        name: "use_desktop".to_string(),
        description: Some(format!(
            "Do something on a computer that needs a screen, like running an app or working across windows. This chat has no computer yet, so the person is asked first to make a repository for it: a Linux machine with a desktop. If they agree, a desktop agent does it and reports back; if they don't, do that request without a computer. For a website alone, use use_browser, which needs no computer. {DESKTOP_CAPTURE}"
        )),
        parameters: serde_json::from_value::<Schema>(
            json!({ "type": "OBJECT", "properties": properties, "required": ["goal", "name"] }),
        )
        .expect("tool schemas are valid"),
        default: None,
        example: None,
        behavior: None,
    }
}

/// What Termite charges, in dollars.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Pricing {
    /// A running machine, per hour.
    pub machine_per_hour: f64,
    /// A repository's stored files, per GB a month.
    pub storage_per_gb_month: f64,
}

/// Termite's current prices. Anyone can read them, signed in or not.
pub async fn pricing() -> Result<Pricing> {
    let response = crate::http::client()
        .get(format!("{}/termite/pricing", super::get_url()))
        .send()
        .await?;
    let json: Value = crate::http::ok(response).await?.json().await?;
    Ok(Pricing {
        machine_per_hour: js_number(json.get("machinePerHour")),
        storage_per_gb_month: js_number(json.get("storagePerGbMonth")),
    })
}

/// `'called' | 'crashed' | 'skipped'` in the TypeScript SDK.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum WakeReason {
    Called,
    Crashed,
    Skipped,
}

/// One time a repository woke its machine agent: its code ran wake.sh (`called`),
/// entry.sh crashed (`crashed`), or the hourly limit left it out (`skipped`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Wake {
    pub id: String,
    pub reason: WakeReason,
    /// What the agent was told: wake.sh's prompt, or how entry.sh ended.
    pub prompt: String,
    pub started: DateTime<Utc>,
    /// When the woken run ended, or None while it works.
    pub finished: Option<DateTime<Utc>>,
    pub ok: bool,
    /// What the agent said when it finished, or why it stopped.
    pub answer: String,
}

impl Wake {
    pub fn from_json(json: &Value) -> Wake {
        Wake {
            id: js_string(json.get("id"), "undefined"),
            reason: match json["reason"].as_str() {
                Some("crashed") => WakeReason::Crashed,
                Some("skipped") => WakeReason::Skipped,
                _ => WakeReason::Called,
            },
            prompt: js_string(json.get("prompt"), ""),
            started: crate::tickets::parse_date(&json["started"]).unwrap_or_default(),
            finished: if truthy(&json["finished"]) {
                crate::tickets::parse_date(&json["finished"])
            } else {
                None
            },
            ok: truthy(&json["ok"]),
            answer: js_string(json.get("answer"), ""),
        }
    }
}

/// The `opts` argument of the machine calls that take only a group.
#[derive(Debug, Clone, Default)]
pub struct GroupOptions {
    pub group: Option<Group>,
}

fn authorized(
    request: reqwest::RequestBuilder,
    authorization: &CredentialsOrApiKey,
    group: Option<&Group>,
) -> reqwest::RequestBuilder {
    let request = request.header(
        "Authorization",
        match authorization {
            CredentialsOrApiKey::Credentials(credentials) => format!("Token {}", credentials.token),
            CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
        },
    );
    match group {
        Some(group) => request.header("Group", &group.id),
        None => request,
    }
}

/// The times a repository woke its agent, newest first.
pub async fn wakes(
    authorization: &CredentialsOrApiKey,
    repository: u64,
    query: PageQuery,
    opts: GroupOptions,
) -> Result<Vec<Wake>> {
    let response = authorized(
        crate::http::client().get(format!(
            "{}/termite/repositories/{repository}/wakes?cursor={}&max={}",
            super::get_url(),
            query.cursor,
            query.max
        )),
        authorization,
        opts.group.as_ref(),
    )
    .send()
    .await?;
    let json: Value = crate::http::ok(response).await?.json().await?;
    Ok(json
        .as_array()
        .into_iter()
        .flatten()
        .map(Wake::from_json)
        .collect())
}

struct Machine {
    windows: HashMap<u64, Window>,
    files: HashMap<u64, FilesState>,
    status: MachineStatus,
    error: String,
    name: String,
    private: bool,
    private_reason: String,
}

struct MachineState {
    machine: u64,
    repository: u64,
    state: Mutex<Machine>,
    hooks: Mutex<Arc<dyn MachineRoomHooks>>,
    calls: Mutex<HashMap<String, oneshot::Sender<Result<Value>>>>,
}

fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
    mutex.lock().unwrap_or_else(PoisonError::into_inner)
}

/// `{ code, stdout, stderr }` in the TypeScript SDK: how a command ended.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ExecResult {
    pub code: i64,
    pub stdout: String,
    pub stderr: String,
}

/// The `opts` argument of `exec`.
#[derive(Debug, Clone, Copy, Default)]
pub struct ExecOptions {
    pub timeout_ms: Option<u64>,
}

/// The `opts` argument of `MachineRoom::start`.
#[derive(Default)]
pub struct StartOptions {
    pub group: Option<Group>,
    pub hooks: Option<Arc<dyn MachineRoomHooks>>,
    pub private: Option<bool>,
}

/// The `opts` argument of `MachineRoom::connect` and `MachineRoom::join`
/// (which takes no group).
#[derive(Default)]
pub struct MachineOptions {
    pub group: Option<Group>,
    pub hooks: Option<Arc<dyn MachineRoomHooks>>,
}

/// `{ id } | { reference }` in the TypeScript SDK: a machine by id, or by its
/// `termite:machine:{id}` reference.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MachineTarget {
    Id { id: u64 },
    Reference { reference: String },
}

/// `{ on, reason }` in the TypeScript SDK.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PrivateState {
    pub on: bool,
    pub reason: String,
}

#[derive(Clone)]
pub struct MachineRoom {
    page: PageRoom,
    inner: Arc<MachineState>,
}

impl Deref for MachineRoom {
    type Target = PageRoom;
    fn deref(&self) -> &PageRoom {
        &self.page
    }
}

impl MachineRoom {
    fn create(room: &Room, hooks: Arc<dyn MachineRoomHooks>, state: &Value) -> MachineRoom {
        let page_hooks: Arc<dyn BrowserRoomHooks> = hooks.clone();
        let page = PageRoom::create(
            room,
            page_hooks,
            state,
            Some(DESKTOP_TOOLS.iter().map(|kind| kind.to_string()).collect()),
        );
        let machine = MachineRoom {
            page,
            inner: Arc::new(MachineState {
                machine: js_number(Some(&state["machine"]["id"])) as u64,
                repository: js_number(Some(&state["machine"]["repository"])) as u64,
                state: Mutex::new(Machine {
                    windows: HashMap::new(),
                    files: HashMap::new(),
                    status: MachineStatus::Booting,
                    error: String::new(),
                    name: String::new(),
                    private: false,
                    private_reason: String::new(),
                }),
                hooks: Mutex::new(hooks),
                calls: Mutex::new(HashMap::new()),
            }),
        };
        machine.hydrate(state);
        machine
    }

    fn machine_state(&self) -> MutexGuard<'_, Machine> {
        lock(&self.inner.state)
    }

    fn machine_hooks(&self) -> Arc<dyn MachineRoomHooks> {
        lock(&self.inner.hooks).clone()
    }

    /// The machine id, the number `connect` takes.
    pub fn machine(&self) -> u64 {
        self.inner.machine
    }

    pub fn repository(&self) -> u64 {
        self.inner.repository
    }

    pub fn windows(&self) -> HashMap<u64, Window> {
        self.machine_state().windows.clone()
    }

    /// Each Files window's folder and view, by window id.
    pub fn files(&self) -> HashMap<u64, FilesState> {
        self.machine_state().files.clone()
    }

    pub fn status(&self) -> MachineStatus {
        self.machine_state().status
    }

    /// Why the machine failed, when it did.
    pub fn error(&self) -> String {
        self.machine_state().error.clone()
    }

    /// The repository's name, so a guest who joined by code knows what it is.
    pub fn name(&self) -> String {
        self.machine_state().name.clone()
    }

    /// Its connections go out only from a residential address, billed per GB to whoever pays for
    /// the machine. Stays true while private is paused.
    pub fn private(&self) -> bool {
        self.machine_state().private
    }

    /// Why private is paused while it reconnects, like a payer out of balance. Its internet is cut
    /// until then. Empty while private carries traffic, or is off.
    pub fn private_reason(&self) -> String {
        self.machine_state().private_reason.clone()
    }

    /// Apply a connection snapshot `{ machine, bootstrap, cursor, windows }`.
    pub fn hydrate(&self, state: &Value) {
        self.page.apply_control(&state["control"]);
        let mut machine = self.machine_state();
        if let Ok(status) = serde_json::from_value(state["machine"]["status"].clone()) {
            machine.status = status;
        }
        if state["machine"].is_object() {
            machine.error = js_string(state["machine"].get("error"), "");
            machine.name = js_string(state["machine"].get("name"), "");
        }
        if let Some(windows) = state["windows"].as_array() {
            machine.windows = windows
                .iter()
                .map(Window::from_json)
                .map(|window| (window.id, window))
                .collect();
        }
        if let Some(files) = state["files"].as_array() {
            machine.files = files
                .iter()
                .map(|row| {
                    (
                        js_number(row.get("window")) as u64,
                        FilesState::from_json(row),
                    )
                })
                .collect();
        }
        if truthy(&state["private"]) {
            machine.private = truthy(&state["private"]["on"]);
            machine.private_reason = js_string(state["private"].get("reason"), "");
        }
    }

    pub fn watch(&self, hooks: Arc<dyn MachineRoomHooks>) {
        *lock(&self.inner.hooks) = hooks.clone();
        self.page.watch(hooks);
    }

    pub async fn invoke_tool(&self, tool: &MachineTool) -> Result<String> {
        if let MachineTool::Desktop(tool) = tool
            && DESKTOP_TOOLS.contains(&tool.kind())
        {
            return self.page.invoke_tool(tool).await;
        }
        let result = self
            .call(json!({ "kind": "tool", "tool": tool }), CALL_MS)
            .await?;
        Ok(match result {
            Value::Null => String::new(),
            Value::String(result) => result,
            result => result.to_string(),
        })
    }

    /// Run a shell command as `agent` in /repository with DISPLAY=:0, so GUI apps open as desktop windows.
    pub async fn exec(&self, command: &str, opts: ExecOptions) -> Result<ExecResult> {
        let timeout_ms = opts.timeout_ms.unwrap_or(EXEC_MS);
        let result = self
            .call(
                json!({ "kind": "exec", "command": command, "timeoutMs": timeout_ms }),
                timeout_ms + 15_000,
            )
            .await?;
        Ok(ExecResult {
            code: match result.get("code") {
                None | Some(Value::Null) => -1,
                code => js_number(code) as i64,
            },
            stdout: js_string(result.get("stdout"), ""),
            stderr: js_string(result.get("stderr"), ""),
        })
    }

    /// Size the machine's desktop to this seat's screen, clamped to `VIEWPORT`. Only the controller can.
    pub async fn set_viewport(&self, width: f64, height: f64) -> Result<()> {
        let size = clamp_viewport(Viewport { width, height });
        self.call(
            json!({ "kind": "viewport", "width": size.width, "height": size.height }),
            CALL_MS,
        )
        .await?;
        Ok(())
    }

    /// Open a file in an app on the machine, for everyone to see: text in nano inside an
    /// xterm, anything else with an installed opener. Only the controller can.
    pub async fn open(&self, path: &str) -> Result<()> {
        self.call(json!({ "kind": "open", "path": path }), CALL_MS)
            .await?;
        Ok(())
    }

    /// Put a Files window on a folder and view for every seat. Only the controller can.
    pub async fn set_files(&self, window: u64, files: &FilesState) -> Result<()> {
        self.call(
            json!({ "kind": "files", "window": window, "path": files.path, "view": files.view }),
            CALL_MS,
        )
        .await?;
        Ok(())
    }

    /// Save a new revision and shut down. The room closes afterwards.
    pub async fn stop(&self) -> Result<()> {
        match self.call(json!({ "kind": "stop" }), STOP_MS).await {
            Ok(_) => Ok(()),
            // The machine announces it closed before it answers the stop itself.
            Err(_) if self.status() == MachineStatus::Stopped => Ok(()),
            Err(error) => Err(error),
        }
    }

    async fn call(&self, call: Value, timeout_ms: u64) -> Result<Value> {
        let id = uuid::Uuid::new_v4().to_string();
        let (resolve, result) = oneshot::channel();
        lock(&self.inner.calls).insert(id.clone(), resolve);
        self.post(&json!({ "event": "machine-call", "data": { "id": id, "call": call } }));
        match tokio::time::timeout(Duration::from_millis(timeout_ms), result).await {
            Ok(Ok(result)) => result,
            Ok(Err(_)) => Err(Error::Message("Machine closed.".to_string())),
            Err(_) => {
                lock(&self.inner.calls).remove(&id);
                Err(Error::Message("Machine call timed out.".to_string()))
            }
        }
    }

    pub fn parrot_tools(&self) -> Vec<Tool> {
        let invoking = self.clone();
        let executing = self.clone();
        parrot_tools(
            Arc::new(move |tool| {
                let room = invoking.clone();
                Box::pin(async move { room.invoke_tool(&tool).await })
            }),
            Arc::new(move |command, timeout_ms| {
                let room = executing.clone();
                Box::pin(async move {
                    let result = room
                        .exec(
                            &command,
                            ExecOptions {
                                timeout_ms: timeout_ms.map(|ms| ms as u64),
                            },
                        )
                        .await?;
                    Ok(serde_json::to_string(&result)?)
                })
            }),
        )
    }

    pub fn handle_event(&self, packet: &Value) -> bool {
        let data = &packet["data"];
        let hooks = self.machine_hooks();
        match packet["event"].as_str().unwrap_or_default() {
            "machine-status" => {
                if let Ok(status) = serde_json::from_value(data["status"].clone()) {
                    self.machine_state().status = status;
                }
                hooks.on_status(self);
                true
            }
            "machine-window" => {
                if !truthy(&data["window"]) {
                    return true;
                }
                let window = Window::from_json(&data["window"]);
                self.machine_state()
                    .windows
                    .insert(window.id, window.clone());
                hooks.on_window(self, &window);
                true
            }
            "machine-window-closed" => {
                let id = js_number(data.get("id")) as u64;
                {
                    let mut machine = self.machine_state();
                    machine.windows.remove(&id);
                    machine.files.remove(&id);
                }
                hooks.on_window_closed(self, id);
                true
            }
            "machine-files" => {
                let window = js_number(data.get("window")) as u64;
                let files = FilesState::from_json(data);
                self.machine_state().files.insert(window, files.clone());
                hooks.on_files(self, window, &files);
                true
            }
            "machine-private" => {
                {
                    let mut machine = self.machine_state();
                    machine.private = truthy(&data["on"]);
                    machine.private_reason = js_string(data.get("reason"), "");
                }
                hooks.on_private(self);
                true
            }
            "machine-agent-step" => {
                if let Ok(step) = serde_json::from_value::<AgentStep>(data.clone()) {
                    hooks.on_agent_step(self, &step);
                }
                true
            }
            "machine-result" => {
                let Some(id) = data["id"].as_str() else {
                    return true;
                };
                let Some(pending) = lock(&self.inner.calls).remove(id) else {
                    return true;
                };
                let _ = pending.send(if truthy(&data["error"]) {
                    Err(Error::Message(js_string(data.get("error"), "")))
                } else {
                    Ok(data["result"].clone())
                });
                true
            }
            "machine-closed" => {
                {
                    let mut machine = self.machine_state();
                    if let Ok(status) = serde_json::from_value(data["status"].clone()) {
                        machine.status = status;
                    }
                    machine.error = js_string(data.get("error"), "");
                }
                hooks.on_status(self);
                for (_, pending) in lock(&self.inner.calls).drain() {
                    let _ = pending.send(Err(Error::Message("Machine closed.".to_string())));
                }
                self.page
                    .handle_event(&json!({ "event": "browser-closed", "data": {} }))
            }
            _ => self.page.handle_event(packet),
        }
    }

    /// Boot the repository's machine, or return the one already live, and connect to it.
    /// `private` sends its connections out from a residential address, billed per GB to
    /// whoever pays for the machine; on a live machine it switches it.
    pub async fn start(
        authorization: &CredentialsOrApiKey,
        repository: u64,
        opts: StartOptions,
    ) -> Result<(MachineRoom, Presence)> {
        let body = match opts.private {
            Some(private) => json!({ "private": private }),
            None => json!({}),
        };
        let response = authorized(
            crate::http::client().post(format!(
                "{}/termite/repositories/{repository}/machine",
                super::get_url()
            )),
            authorization,
            opts.group.as_ref(),
        )
        .json(&body)
        .send()
        .await?;
        let json: Value = crate::http::ok(response).await?.json().await?;
        MachineRoom::connect(
            authorization,
            &MachineTarget::Id {
                id: js_number(json.get("id")) as u64,
            },
            MachineOptions {
                group: opts.group,
                hooks: opts.hooks,
            },
        )
        .await
    }

    /// Save and shut down a repository's machine without joining its room. For its owner or group members.
    pub async fn shutdown(
        authorization: &CredentialsOrApiKey,
        repository: u64,
        opts: GroupOptions,
    ) -> Result<()> {
        let response = authorized(
            crate::http::client().post(format!(
                "{}/termite/repositories/{repository}/machine/stop",
                super::get_url()
            )),
            authorization,
            opts.group.as_ref(),
        )
        .json(&json!({}))
        .send()
        .await?;
        crate::http::ok(response).await?;
        Ok(())
    }

    /// Turn private on or off for a repository's live machine, for its owner or group members.
    /// Resolves to the machine's private state and, while it's paused, why.
    pub async fn set_private(
        authorization: &CredentialsOrApiKey,
        repository: u64,
        on: bool,
        opts: GroupOptions,
    ) -> Result<PrivateState> {
        let response = authorized(
            crate::http::client().post(format!(
                "{}/termite/repositories/{repository}/machine/private",
                super::get_url()
            )),
            authorization,
            opts.group.as_ref(),
        )
        .json(&json!({ "on": on }))
        .send()
        .await?;
        let json: Value = crate::http::ok(response).await?.json().await?;
        Ok(PrivateState {
            on: truthy(&json["on"]),
            reason: js_string(json.get("reason"), ""),
        })
    }

    /// Connect to a live machine by id, or by its `termite:machine:{id}` reference.
    pub async fn connect(
        authorization: &CredentialsOrApiKey,
        target: &MachineTarget,
        opts: MachineOptions,
    ) -> Result<(MachineRoom, Presence)> {
        MachineRoom::open_room(
            Authorization::Server {
                authorization: authorization.clone(),
                server: match target {
                    MachineTarget::Id { id } => format!("termite:machine:{id}"),
                    MachineTarget::Reference { reference } => reference.clone(),
                },
                group: opts.group.as_ref().map(|group| group.id.clone()),
            },
            opts.hooks.unwrap_or_else(|| Arc::new(())),
        )
        .await
    }

    /// Join a machine someone shared with an access code.
    pub async fn join(
        authorization: &CredentialsOrApiKey,
        access_code: &str,
        opts: MachineOptions,
    ) -> Result<(MachineRoom, Presence)> {
        MachineRoom::open_room(
            Authorization::AccessCode {
                authorization: authorization.clone(),
                access_code: access_code.to_string(),
            },
            opts.hooks.unwrap_or_else(|| Arc::new(())),
        )
        .await
    }

    async fn open_room(
        auth: Authorization,
        hooks: Arc<dyn MachineRoomHooks>,
    ) -> Result<(MachineRoom, Presence)> {
        let machine_hooks = Arc::new(MachineHooks {
            room: Mutex::new(None),
            hooks,
        });
        let me = connect_server(
            auth,
            &format!("{}/termite/machine/live", super::get_url()),
            machine_hooks.clone(),
        )
        .await?;
        let room = machine_hooks
            .room()
            .ok_or_else(|| Error::Message("Room not found".to_string()))?;
        room.emit_presence();
        Ok((room, me))
    }
}

struct MachineHooks {
    room: Mutex<Option<MachineRoom>>,
    hooks: Arc<dyn MachineRoomHooks>,
}

impl MachineHooks {
    fn room(&self) -> Option<MachineRoom> {
        lock(&self.room).clone()
    }
}

impl Hooks for MachineHooks {
    fn create_room(&self, room: &Room, state: &Value) {
        *lock(&self.room) = Some(MachineRoom::create(room, self.hooks.clone(), state));
    }

    fn on_presence(&self, _room: &Room) {
        if let Some(room) = self.room() {
            room.emit_presence();
        }
    }

    fn on_connection(&self, _room: &Room, state: &Value) {
        let Some(room) = self.room() else {
            return;
        };
        if let Ok(bootstrap) = serde_json::from_value::<BootstrapMeta>(state["bootstrap"].clone()) {
            room.web().ingest_bootstrap(bootstrap);
        }
        if let Ok(cursor) = serde_json::from_value::<HtmlPointer>(state["cursor"].clone()) {
            room.page.set_cursor(cursor.clone());
            room.machine_hooks().on_cursor(&room.page, &cursor);
        }
        room.hydrate(state);
    }

    fn on_event(&self, _room: &Room, packet: &Value) -> bool {
        self.room().is_some_and(|room| room.handle_event(packet))
    }

    fn on_closed(&self, _room: &Room, _reason: Option<&str>) {
        if let Some(room) = self.room() {
            room.emit_closed();
        }
    }
}