fundaia 0.19.1

Command line for the Fundaia deployment platform: projects, services, variables, deployments, logs and metrics
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
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
mod api;
mod changelog;
mod commands;
mod config;
mod output;
mod render;
mod update;

use anyhow::{Context, Result};
use clap::{CommandFactory, Parser, Subcommand};
use owo_colors::OwoColorize;

use api::client::ApiClient;
use config::Config;
use output::Format;
use render::theme;

/// The command line for the Fundaia deployment platform.
///
/// Shaped around the two questions a deployment platform actually gets asked —
/// *what is the state of things* and *make this change* — rather than around
/// the REST endpoints underneath. `status` answers the first for the whole
/// instance in one screen; `deploy` answers the second and then stays to show
/// the pipeline, which is the one thing a terminal does better than a browser
/// tab you have to keep switching to.
#[derive(Parser)]
#[command(
    name = "fundaia",
    version,
    about = "Proyectos, servicios, variables, despliegues, logs y métricas",
    long_about = None,
    propagate_version = true
)]
struct Cli {
    /// Which configured instance to talk to.
    #[arg(long, short, global = true, env = "FUNDAIA_PROFILE")]
    profile: Option<String>,

    /// Override the address, without saving it. Useful in CI.
    #[arg(long, global = true, env = "FUNDAIA_URL")]
    url: Option<String>,

    /// Override the token, without saving it. Useful in CI.
    #[arg(long, global = true, env = "FUNDAIA_TOKEN", hide_env_values = true)]
    token: Option<String>,

    /// Never colour the output, whatever the terminal says.
    #[arg(long, global = true)]
    no_color: bool,

    /// Answer in JSON: one compact value, or one object per line on a stream.
    /// For scripts and AI agents; `FUNDAIA_JSON=1` says the same thing.
    #[arg(long, global = true)]
    json: bool,

    #[command(subcommand)]
    command: Command,
}

#[derive(Subcommand)]
enum Command {
    /// Authorise this terminal through the browser.
    Login {
        /// The instance to sign in to.
        #[arg(long, default_value = "https://infrastructure.fundaia.com")]
        url: String,

        /// The name to save it under.
        #[arg(long, default_value = "default")]
        as_profile: String,

        /// Print the address instead of opening it.
        #[arg(long)]
        no_browser: bool,
    },

    /// Forget a profile on this machine.
    Logout {
        #[arg(long)]
        profile: Option<String>,
    },

    /// Replace this binary with the newest published release.
    ///
    /// Rarely needed: every command already checks once a day and installs what
    /// it finds. This is the same work without waiting for that, and the way to
    /// see what happened when the automatic one stayed quiet.
    Upgrade {
        /// Only say whether there is a newer one.
        #[arg(long)]
        check: bool,
    },

    /// What each version brought, and which ones this machine has run.
    ///
    /// The file travels inside the binary, so this answers with no instance, no
    /// token and no network. With no arguments it tells what the version you
    /// are running brought — which is the question the self-update leaves
    /// behind when it replaces the binary halfway through an afternoon.
    Changelog {
        /// One version, with or without its `v`. The running one by default.
        ///
        /// Positional, and named `release` in the code, because `--version` is
        /// clap's and `propagate_version` hands it to every subcommand: an
        /// argument called `version` collides with it before the parser is even
        /// built. The word somebody types is still a version.
        #[arg(value_name = "VERSION")]
        release: Option<String>,

        /// Every version, newest first.
        #[arg(long)]
        all: bool,

        /// What was published after a version: everything an upgrade brought.
        #[arg(long)]
        since: Option<String>,

        /// How many to show.
        #[arg(short = 'n', long)]
        count: Option<usize>,

        /// Which versions have run here, and since when.
        ///
        /// A different question from the changelog: that one says what was
        /// published, this says what was on this machine.
        #[arg(long)]
        history: bool,
    },

    /// Who this terminal is signed in as.
    Whoami,

    /// The completion script for a shell, on stdout.
    ///
    /// `fundaia completions zsh > "${fpath[1]}/_fundaia"`, or the bash and
    /// fish equivalents. Generated from the real argument definitions, so it
    /// can never disagree with what the parser accepts.
    Completions { shell: clap_complete::Shell },

    /// Everything, in one screen.
    Status,

    /// Projects on this instance.
    Projects,

    /// Make one, rename one, delete one, or hand one to another space.
    Project {
        #[command(subcommand)]
        command: ProjectCommand,
    },

    /// Services in a project.
    Services { project: String },

    /// One service in detail.
    Service { project: String, service: String },

    /// The picture of a project: where each service sits, and how to move it.
    Canvas {
        #[command(subcommand)]
        command: CanvasCommand,
    },

    /// Create a service.
    New {
        project: String,
        name: String,

        /// A GitHub repository, as `owner/name`.
        #[arg(long)]
        repo: Option<String>,

        /// A container image.
        #[arg(long)]
        image: Option<String>,

        /// A component from the catalogue: a database, a bucket or Claude Code.
        /// `fundaia templates` lists the ones this account may add.
        #[arg(long)]
        template: Option<String>,

        #[arg(long, default_value = "main")]
        branch: String,

        /// Services it should be able to talk to, by name.
        #[arg(long = "connect-to", value_delimiter = ',')]
        connect_to: Vec<String>,

        /// Create it without starting it.
        ///
        /// Creating a service deploys it — that is what adding one asks for.
        /// This is for the service that cannot start until somebody types a
        /// variable it has no way to guess, where deploying on sight buys a
        /// failed build instead of an empty node.
        #[arg(long = "no-deploy")]
        no_deploy: bool,
    },

    /// Rename a service.
    ///
    /// A contract change rather than a label: the expressions that name it and
    /// the internal addresses that call it are rewritten with it, and its public
    /// hostname follows on the next deployment.
    Rename {
        project: String,
        service: String,
        name: String,
    },

    /// The components on offer: databases, storage and Claude Code.
    ///
    /// What it lists is what *this account* may add. An instance offers some
    /// components to its owner only, and they are absent rather than shown and
    /// refused.
    Templates,

    /// Deploy a service, and watch the pipeline.
    Deploy {
        project: String,
        service: String,

        /// Reuse the current image instead of building.
        #[arg(long)]
        restart: bool,

        /// Start it and return, without watching.
        #[arg(long)]
        detach: bool,
    },

    /// Build one deployment's own commit again, with today's variables.
    ///
    /// Between `deploy`, which reads the branch and ships whatever landed on it
    /// since, and `rollback`, which reuses the image and never builds.
    Redeploy {
        project: String,
        service: String,
        /// The number shown by `history`.
        number: u32,
    },

    /// Put a previous deployment back, by its number.
    Rollback {
        project: String,
        service: String,
        /// The number shown by `history`.
        number: u32,
    },

    /// Put a service to sleep. The next request wakes it.
    Stop { project: String, service: String },

    /// The deployments of a service, newest first.
    History {
        project: String,
        service: String,

        #[arg(long, default_value_t = 15)]
        limit: usize,
    },

    /// The code one commit changed, file by file.
    ///
    /// Without a hash, the commit the newest deployment shipped — which is what
    /// answers "what went out". `--stat` stops before the patches when the list
    /// of files is all you wanted, and `--file` prints one of them.
    #[command(alias = "show")]
    Commit {
        project: String,
        service: String,

        /// The commit hash, abbreviated or whole.
        commit: Option<String>,

        /// One file, by the path the list reports.
        #[arg(long)]
        file: Option<String>,

        /// The list of files and nothing else.
        #[arg(long)]
        stat: bool,
    },

    /// What has been done in a project, newest first.
    ///
    /// Deployments, variables, domains and who read which logs — manual and
    /// through this tool alike, because both go through the same services.
    Activity {
        project: String,

        #[arg(long, default_value_t = 30)]
        limit: usize,
    },

    /// Who has been getting into your account, and from where.
    ///
    /// The failed attempts are in the list on purpose: a successful sign-in
    /// nobody recognises is normally preceded by attempts nobody recognises.
    /// Always your own account — the token decides whose, and there is nowhere
    /// else to point it.
    #[command(alias = "logins")]
    SignIns {
        #[arg(long, short = 'n', default_value_t = 50)]
        limit: usize,
    },

    /// The sessions open right now, and closing one.
    ///
    /// A different question from `sign-ins`, which is history: this is the
    /// present tense, and the only one of the two with anything to press.
    Sessions {
        #[command(subcommand)]
        command: Option<SessionCommand>,
    },

    /// Follow what the platform is doing, live.
    ///
    /// The terminal half of the notices the web interface shows: a deployment
    /// somebody else started, a push that deployed on its own, a variable that
    /// changed under you. With no arguments it is everything this account can
    /// reach; name a project — or a project and a service — to narrow it.
    Watch {
        project: Option<String>,
        service: Option<String>,
    },

    /// A service's log.
    Logs {
        project: String,
        service: String,

        /// Follow the live output.
        #[arg(long, short)]
        follow: bool,

        #[arg(long, short = 'n', default_value_t = 200)]
        tail: usize,

        /// Only one stream: build, deploy, runtime or system.
        #[arg(long)]
        stream: Option<String>,

        /// Only one step of the deployment: queue, checkout, build, start,
        /// health or live — the same six the pipeline draws.
        #[arg(long)]
        step: Option<String>,

        /// Which deployment, by the number `history` shows. The newest by default.
        #[arg(long)]
        deployment: Option<u32>,

        /// Prefix each line with the time the platform recorded it.
        #[arg(long, short = 't')]
        timestamps: bool,

        /// Only one request, by its trace id. The lines print theirs in the
        /// gutter, so this is what you paste after reading one.
        #[arg(long)]
        trace: Option<String>,
    },

    /// What a service keeps getting wrong, folded and counted.
    Incidents {
        project: String,
        service: String,

        /// Include the ones already resolved or ignored.
        #[arg(long)]
        decided: bool,
    },

    /// Commits waiting for somebody to say they may deploy.
    ///
    /// A push from outside the workspace is held rather than deployed, the way
    /// Railway holds one from outside the team. Whoever pushed is not a member
    /// here — or GitHub matched no account to their commit at all, which is
    /// almost always a `git config user.email` nobody added to their account.
    Approvals {
        project: String,

        /// One service. Omit for everything waiting in the project.
        service: Option<String>,
    },

    /// Approve a held commit and deploy it.
    Approve {
        /// The id `approvals` prints.
        id: String,
    },

    /// Refuse a held commit. It is never offered again.
    Reject {
        /// The id `approvals` prints.
        id: String,
    },

    /// Ask the platform to fix an incident now.
    Fix {
        /// The id `incidents` prints.
        id: String,
    },

    /// Record what you concluded about an incident.
    Incident {
        /// The id `incidents` prints.
        id: String,

        /// `resolved` if it is fixed, `ignored` to stop hearing about it, or
        /// `open` to put it back in play.
        #[arg(value_parser = ["resolved", "ignored", "open"])]
        status: String,
    },

    /// What the platform has tried to fix on its own, and how it is configured.
    Autofix {
        project: String,
        service: String,

        /// `off`, `diagnose` or `pullRequest`.
        #[arg(long, value_parser = ["off", "diagnose", "pullRequest"])]
        mode: Option<String>,

        /// The Claude Code component that does the work, by id.
        #[arg(long)]
        agent: Option<String>,

        /// Which model it runs on.
        #[arg(long)]
        model: Option<String>,

        /// How many times a failure has to happen before it is worth an agent.
        #[arg(long)]
        min_occurrences: Option<u32>,

        /// Runs per day, per service.
        #[arg(long)]
        daily_limit: Option<u32>,
    },

    /// CPU and memory, now and over a window.
    Metrics {
        project: String,
        service: String,

        #[arg(long, default_value_t = 60)]
        minutes: u32,
    },

    /// Tokens and dollars an agent component has spent.
    #[command(alias = "usage")]
    Consumption {
        project: String,
        service: String,

        /// The window: 24h, 7d, 30d or 90d.
        #[arg(long, default_value = "7d")]
        range: String,
    },

    /// Every prompt an agent has been asked, and what it is doing now.
    ///
    /// `prompts` is the alias because that is what somebody types when they
    /// want this and `activity` is already the project history.
    #[command(name = "agent-activity", alias = "prompts")]
    AgentActivity {
        project: String,
        service: String,

        /// The window: 24h, 7d, 30d or 90d.
        #[arg(long, default_value = "24h")]
        range: String,

        /// Narrows the list: answered, failed or rejected. The counts do not move.
        #[arg(long)]
        outcome: Option<String>,
    },

    /// A service's environment variables.
    #[command(alias = "vars")]
    Variables {
        #[command(subcommand)]
        command: VariableCommand,
    },

    /// Read access to a service's repository, when its owner is somebody else.
    ///
    /// A private repository belonging to another account is invisible to this
    /// platform until that account grants it, and GitHub reports the refusal as a
    /// 403 about *write* access on a command that asked to read. Only the owner
    /// can grant it, so `access request` emails them a link that does it — and the
    /// service redeploys itself the moment the permission lands.
    Access {
        #[command(subcommand)]
        command: AccessCommand,
    },

    /// Copies of a service's volume, and putting one back.
    #[command(alias = "backup")]
    Backups {
        #[command(subcommand)]
        command: BackupCommand,
    },

    /// Hostnames a service answers on.
    Domains {
        #[command(subcommand)]
        command: DomainCommand,
    },

    /// Wire one service to another.
    Connect {
        project: String,
        /// The service that will read the variables.
        service: String,
        /// The service it should be able to reach.
        provider: String,
    },

    /// Undo a connection: the consumer stops reading the provider's variables.
    Disconnect {
        project: String,
        /// The service that was reading the variables.
        service: String,
        /// The one it was reading them from.
        provider: String,
    },

    /// What a service could be connected to.
    Connectable { project: String, service: String },

    /// Directories that outlive the container.
    Volumes {
        #[command(subcommand)]
        command: VolumeCommand,
    },

    /// The Containerfile a service builds with.
    Recipe {
        #[command(subcommand)]
        command: RecipeCommand,
    },

    /// The routes a load balancer or an API gateway serves.
    Config {
        #[command(subcommand)]
        command: ConfigCommand,
    },

    /// What a service turned out to offer: framework, port, endpoints.
    #[command(alias = "offers")]
    Capabilities { project: String, service: String },

    /// The shared spaces this account belongs to.
    #[command(alias = "workspaces")]
    Workspace {
        #[command(subcommand)]
        command: WorkspaceCommand,
    },

    /// How much of the machine is left.
    Capacity,

    /// Change a service's settings. Only what you pass is touched.
    Settings {
        project: String,
        service: String,

        /// Memory ceiling, in MB.
        #[arg(long)]
        memory: Option<u32>,

        /// How many containers to run behind the one hostname.
        #[arg(long)]
        replicas: Option<u32>,

        /// Which directory of the repository this service is, in a monorepo.
        #[arg(long)]
        root: Option<String>,

        /// What to run instead of the image's own entrypoint.
        #[arg(long = "start-command")]
        start_command: Option<String>,

        /// The path a deployment is considered live once it answers. Setting
        /// one is also how a service is moved onto HTTP checks.
        #[arg(long = "health-path")]
        health_path: Option<String>,

        /// What to ask: `auto`, `http`, `tcp`, or `none` for a worker that
        /// serves nothing. `tcp` is what a database brought in as a plain
        /// image needs — asking it for HTTP burns the whole budget.
        #[arg(long = "health-probe")]
        health_probe: Option<String>,

        /// The whole wait, in seconds, before the deployment is called failed.
        #[arg(long = "health-timeout")]
        health_timeout_seconds: Option<u32>,

        /// How often it is asked again, in seconds.
        #[arg(long = "health-interval")]
        health_interval_seconds: Option<u32>,

        /// How long no answer is believed. A server can open its port before
        /// it has a database connection, and pass its check broken.
        #[arg(long = "health-grace")]
        health_grace_seconds: Option<u32>,

        /// Exactly this status. Unset accepts anything under 500, including a
        /// 404 on the health path itself.
        #[arg(long = "health-status")]
        health_expected_status: Option<u32>,

        /// `always`, `on-failure` or `no`.
        #[arg(long = "restart")]
        restart_policy: Option<String>,

        /// How many times the platform tries to bring it back after a crash,
        /// each attempt further apart than the last. Ten by default.
        #[arg(long = "restart-retries")]
        restart_max_retries: Option<u32>,

        /// Sleep when no traffic arrives, and wake on the next request.
        #[arg(long)]
        sleep: Option<bool>,

        /// Deploy on its own when the branch moves.
        #[arg(long = "auto-deploy")]
        auto_deploy: Option<bool>,

        /// Let the gateway hold this service's answers.
        #[arg(long = "cache")]
        cache_enabled: Option<bool>,

        /// How long a cached answer stays fresh, in seconds.
        #[arg(long = "cache-ttl")]
        cache_ttl_seconds: Option<u32>,
    },

    /// Publish a service on the internet, or take it off.
    ///
    /// Every service is always reachable inside its project by name; this is
    /// only about the hostname on top. A database behind an API wants none.
    Expose {
        project: String,
        service: String,

        /// Take it off the internet. Its domains are removed.
        #[arg(long)]
        off: bool,
    },

    /// Encryption at rest for a storage service's buckets.
    Encrypt {
        project: String,
        service: String,

        /// Turn it off instead. What is already encrypted stays encrypted.
        #[arg(long)]
        off: bool,
    },

    /// Remove a service and everything under it.
    Delete {
        project: String,
        service: String,

        /// The service's own name, typed back.
        #[arg(long)]
        confirm: Option<String>,
    },
}

/// Sharing a space, from a terminal.
///
/// The workspace is optional everywhere: most people are in one, and making
/// them name it on every call would be ceremony. Given, it takes an id, a slug
/// or the name shown on screen, the same as a project does.
#[derive(Subcommand)]
enum WorkspaceCommand {
    /// The spaces you are in.
    List,

    /// Who shares a space, and who has been invited to.
    #[command(alias = "who")]
    Members { workspace: Option<String> },

    /// The prepaid credit the agents of a space run on.
    #[command(alias = "saldo")]
    Credits { workspace: Option<String> },

    /// Invite somebody by email.
    Invite {
        email: String,

        #[arg(long)]
        workspace: Option<String>,

        /// Let them invite others too.
        #[arg(long)]
        admin: bool,
    },

    /// Withdraw an invitation that has not been accepted.
    Revoke {
        /// The id shown by `members`.
        invitation_id: String,

        #[arg(long)]
        workspace: Option<String>,
    },

    /// Remove somebody from the space.
    Remove {
        /// The user id shown by `members`.
        user_id: String,

        #[arg(long)]
        workspace: Option<String>,
    },
}

/// A project is where everything else hangs from, so this is the first command
/// somebody runs on a new instance and was the one thing the tool could not do.
#[derive(Subcommand)]
enum ProjectCommand {
    /// Create one.
    New {
        name: String,

        #[arg(long)]
        description: Option<String>,

        /// Which shared space it belongs to. Yours, if you say nothing.
        #[arg(long)]
        workspace: Option<String>,
    },

    /// Change its name, its description, or both.
    Rename {
        project: String,
        /// The new name. Leave it out to only change the description.
        name: Option<String>,

        #[arg(long)]
        description: Option<String>,
    },

    /// Delete it, with everything under it. There is no archive.
    Delete {
        project: String,

        /// The project's own name, typed back.
        #[arg(long)]
        confirm: Option<String>,
    },

    /// Hand it to another shared space, which is the whole of sharing it.
    Move { project: String, workspace: String },
}

#[derive(Subcommand)]
enum CanvasCommand {
    /// Where every service sits, with its coordinates.
    ///
    /// The coordinates are what `move` takes back, so this is the command to
    /// run before arranging anything by hand.
    Show {
        project: String,

        /// Draw it as well as list it.
        #[arg(long)]
        map: bool,
    },

    /// Put one service somewhere, in canvas units.
    ///
    /// x runs to the right and y downwards, the first column sits at 80, and a
    /// node is 208 wide by 76 tall — so 300 apart horizontally and 130
    /// vertically is what the automatic arrangements leave between two of them.
    /// Positions are snapped to the same 8-unit grid a drag snaps to.
    Move {
        project: String,
        service: String,

        #[arg(long, allow_negative_numbers = true)]
        x: i64,

        #[arg(long, allow_negative_numbers = true)]
        y: i64,
    },

    /// Lay the whole project out again, overwriting every position in it.
    ///
    /// `layered` reads the arrows and puts what a service depends on to its
    /// left, which is how the picture is meant to be read. `grid` ignores them
    /// and lines everything up in creation order, for a canvas that has been
    /// dragged into a heap.
    Arrange {
        project: String,

        #[arg(long, default_value = "layered", value_parser = ["layered", "grid"])]
        layout: String,
    },
}

#[derive(Subcommand)]
enum VolumeCommand {
    List {
        project: String,
        service: String,
    },

    /// Attach one. Nothing is deployed: it is inside the container from the
    /// next deployment on.
    Add {
        project: String,
        service: String,
        /// Where it is mounted, as an absolute path: `/data`.
        mount_path: String,
    },

    /// Change how much disk it may hold, by the id `list` shows.
    ///
    /// Nothing is deployed: the size is what the plan reserves, not a mount
    /// option. It is refused when the plan has no room left and when the volume
    /// already holds more than the new size.
    Resize {
        volume_id: String,
        /// The new size in whole gigabytes.
        #[arg(long)]
        gb: u64,
    },

    /// Take one off, by the id `list` shows.
    Remove {
        volume_id: String,
    },
}

#[derive(Subcommand)]
enum RecipeCommand {
    /// Print it, with what generated it.
    Show {
        project: String,
        service: String,

        /// Only the Containerfile, so it can be redirected into one.
        #[arg(long)]
        plain: bool,
    },

    /// Replace it. From then on it is never regenerated.
    Edit {
        project: String,
        service: String,

        /// The file to send, or `-` for standard input.
        #[arg(long, default_value = "-")]
        file: String,
    },
}

#[derive(Subcommand)]
enum ConfigCommand {
    /// Print it, with where the container reads it.
    Show {
        project: String,
        service: String,

        /// Only the file, so it can be redirected into one.
        #[arg(long)]
        plain: bool,
    },

    /// Replace it. From then on the form never overwrites it again.
    Edit {
        project: String,
        service: String,

        /// The file to send, or `-` for standard input.
        #[arg(long, default_value = "-")]
        file: String,
    },
}

#[derive(Subcommand)]
enum VariableCommand {
    /// List them.
    List {
        project: String,
        service: String,

        /// Decrypt the secrets. Each one is recorded on the server.
        #[arg(long)]
        reveal: bool,
    },

    /// Set one.
    Set {
        project: String,
        service: String,
        key: String,
        value: String,

        /// Store it encrypted, and never show it again.
        #[arg(long)]
        secret: bool,

        /// Seal it on the way in: unreadable and unchangeable from the start.
        #[arg(long)]
        sealed: bool,
    },

    /// Seal one: the container keeps receiving it, nobody can read or change it.
    Seal {
        project: String,
        service: String,
        key: String,

        /// The key again. Sealing cannot be undone.
        #[arg(long)]
        confirm: Option<String>,
    },

    /// Remove one.
    Unset {
        project: String,
        service: String,
        key: String,
    },

    /// Read a `.env` and set every variable in it, in one request.
    Import {
        project: String,
        service: String,

        /// The file to read, or `-` for standard input.
        file: String,

        /// Store them all encrypted.
        #[arg(long)]
        secret: bool,
    },
}

#[derive(Subcommand)]
enum AccessCommand {
    /// Whether the repository can be read, and who is being asked.
    Status { project: String, service: String },

    /// Email the owner a link that grants read access.
    Request {
        project: String,
        service: String,

        /// The owner's address. Omit to reuse one this space has already used.
        ///
        /// GitHub publishes an address for almost no account, so this is usually
        /// the one thing that has to be typed: the platform can find out whose
        /// repository it is and never how to reach them.
        #[arg(long)]
        email: Option<String>,
    },
}

#[derive(Subcommand)]
enum BackupCommand {
    /// List them, with the schedule and when the next one lands.
    List { project: String, service: String },

    /// Take one now. Waits for it.
    New { project: String, service: String },

    /// Which schedules run: daily, weekly, monthly. With none, it stops copying.
    Schedule {
        project: String,
        service: String,

        /// Any of `daily`, `weekly`, `monthly`, comma separated.
        #[arg(value_delimiter = ',')]
        schedules: Vec<String>,
    },

    /// Put one back. Overwrites the volume; the server copies it first.
    Restore {
        /// The id `backups list` shows.
        backup_id: String,

        /// The id again. This overwrites data.
        #[arg(long)]
        confirm: Option<String>,
    },

    /// Keep one past its retention.
    Keep { backup_id: String },

    /// Let retention have it again.
    Unkeep { backup_id: String },

    /// Delete one now.
    Remove { backup_id: String },
}

/// What can be done to a session other than look at it.
#[derive(Subcommand)]
enum SessionCommand {
    /// Sign one out, by the id `fundaia sessions` printed.
    ///
    /// The id is the session token's digest rather than the token: holding it
    /// opens nothing, which is what makes it safe to print in a table.
    Revoke { session_id: String },
}

#[derive(Subcommand)]
enum DomainCommand {
    List {
        project: String,
        service: String,
    },

    /// Add one. With no host, generates one under the platform's domain.
    Add {
        project: String,
        service: String,
        host: Option<String>,
    },

    /// Check a custom domain now: its DNS record and its certificate.
    Verify {
        domain_id: String,
    },

    Remove {
        domain_id: String,
    },
}

#[tokio::main]
async fn main() {
    let cli = Cli::parse();
    let format = output::chosen(cli.json);

    // JSON is for a parser, and a parser has no use for colour — an escape
    // inside a value it did not expect is exactly the kind of bug `--json`
    // exists to prevent.
    if cli.no_color || format.is_json() {
        // Both, and they are not the same switch: the override governs
        // `if_supports_color`, which is what the progress bars ask, and
        // `theme::silence` governs the styles every screen applies directly.
        owo_colors::set_override(false);
        theme::silence();
    }

    // What is running, noted before the command rather than when an upgrade
    // installs one: a binary arrives three ways — `cargo install`, `install.sh`
    // and the self-update — and only the third passes through the installer.
    // Skipped for `completions` for the reason the update check is.
    if !matches!(cli.command, Command::Completions { .. }) {
        changelog::history::record(env!("CARGO_PKG_VERSION"));
    }

    // Started before the command and collected after it, so asking crates.io
    // overlaps the work rather than being added to it. Every command talks to a
    // server, so in practice the answer is already in by the time it is read.
    //
    // Not for `completions`, which runs from shell start-up files: a network
    // check — let alone an install — behind every new terminal is not a
    // courtesy any more.
    let update = match cli.command {
        Command::Completions { .. } => None,
        _ => Some(update::UpdateCheck::start(
            env!("CARGO_PKG_VERSION"),
            format.is_json(),
        )),
    };
    let outcome = run(cli, format).await;
    if let Some(update) = update {
        update.finish().await;
    }

    if let Err(error) = outcome {
        if format.is_json() {
            // The same failure as one object on stderr, so an agent branches
            // on `error.code` instead of parsing a sentence meant for a person.
            output::emit_error(&error, hint_for(&error));
            std::process::exit(1);
        }

        // One line, on stderr, so a failure never lands in a pipe as data.
        eprintln!();
        eprintln!("  {} {error}", theme::CROSS.style(theme::danger()));

        // The chain is where the useful part usually is: "could not reach X"
        // over "connection refused" says both what was attempted and why not.
        for cause in error.chain().skip(1) {
            eprintln!("    {}", cause.style(theme::muted()));
        }

        if let Some(hint) = hint_for(&error) {
            eprintln!("    {}", hint.style(theme::muted()));
        }

        eprintln!();
        std::process::exit(1);
    }
}

/// What to try next, for the failures where there is an obvious answer.
///
/// Keyed on the server's own error code rather than on the message, because the
/// message is written for a person and is allowed to be reworded.
fn hint_for(error: &anyhow::Error) -> Option<&'static str> {
    let api = error.downcast_ref::<api::client::ApiError>()?;

    match api.code.as_str() {
        "unauthorized" => Some("Ejecuta `fundaia login` para volver a entrar."),
        "rate_limited" => Some("Demasiadas peticiones seguidas: espera un minuto."),
        "conflict" => Some("Ya hay algo con ese nombre, o hay un despliegue en curso."),
        _ => None,
    }
}

async fn run(cli: Cli, format: Format) -> Result<()> {
    match &cli.command {
        Command::Login {
            url,
            as_profile,
            no_browser,
        } => return commands::login::run(url, as_profile, !no_browser).await,
        Command::Logout { profile } => return commands::login::logout(profile.as_deref()),
        // Nothing here needs an instance, a profile or a token: the registry
        // and the release are the only two things it talks to.
        Command::Upgrade { check } => {
            return update::upgrade(env!("CARGO_PKG_VERSION"), *check).await
        }
        // The changelog is compiled into this binary and the history is a file
        // beside the profiles, so neither of them has an instance to reach.
        Command::Changelog {
            release,
            all,
            since,
            count,
            history,
        } => {
            return if *history {
                commands::changelog::show_history(format)
            } else {
                commands::changelog::show(
                    &commands::changelog::Query {
                        all: *all,
                        version: release.clone(),
                        since: since.clone(),
                        count: *count,
                    },
                    format,
                )
            }
        }
        Command::Completions { shell } => {
            clap_complete::generate(
                *shell,
                &mut Cli::command(),
                "fundaia",
                &mut std::io::stdout(),
            );
            return Ok(());
        }
        _ => {}
    }

    let client = connect(&cli)?;

    match cli.command {
        Command::Login { .. }
        | Command::Logout { .. }
        | Command::Upgrade { .. }
        | Command::Changelog { .. }
        | Command::Completions { .. } => {
            unreachable!("handled above")
        }

        Command::Whoami => {
            let identity = client.whoami().await?;
            if format.is_json() {
                output::emit(&serde_json::json!({
                    "url": client.base(),
                    "principal": identity,
                }));
                return Ok(());
            }
            match identity {
                Some(principal) => println!(
                    "  {} en {}",
                    principal.display_name.style(theme::strong()),
                    client.base().style(theme::muted()),
                ),
                None => println!("  No hay sesión."),
            }
            Ok(())
        }

        Command::Status => commands::read::status(&client, format).await,
        Command::Projects => commands::read::projects(&client, format).await,

        Command::Project { command } => match command {
            ProjectCommand::New {
                name,
                description,
                workspace,
            } => {
                commands::write::create_project(
                    &client,
                    &name,
                    description.as_deref(),
                    workspace.as_deref(),
                )
                .await
            }
            ProjectCommand::Rename {
                project,
                name,
                description,
            } => {
                commands::manage::rename_project(
                    &client,
                    &project,
                    name.as_deref(),
                    description.as_deref(),
                )
                .await
            }
            ProjectCommand::Delete { project, confirm } => {
                commands::manage::delete_project(&client, &project, confirm.as_deref()).await
            }
            ProjectCommand::Move { project, workspace } => {
                commands::manage::move_project(&client, &project, &workspace).await
            }
        },
        Command::Services { project } => commands::read::services(&client, &project, format).await,
        Command::Service { project, service } => {
            commands::read::service(&client, &project, &service, format).await
        }
        Command::Canvas { command } => match command {
            CanvasCommand::Show { project, map } => {
                commands::read::canvas(&client, &project, map, format).await
            }
            CanvasCommand::Move {
                project,
                service,
                x,
                y,
            } => commands::write::move_on_canvas(&client, &project, &service, x, y, format).await,
            CanvasCommand::Arrange { project, layout } => {
                commands::write::arrange_canvas(&client, &project, &layout, format).await
            }
        },

        Command::Templates => commands::write::templates(&client, format).await,

        Command::New {
            project,
            name,
            repo,
            image,
            template,
            branch,
            connect_to,
            no_deploy,
        } => {
            commands::write::create_service(
                &client,
                commands::write::ServiceRequest {
                    project: &project,
                    name: &name,
                    repo: repo.as_deref(),
                    image: image.as_deref(),
                    template: template.as_deref(),
                    branch: &branch,
                    connect_to: &connect_to,
                    no_deploy,
                },
            )
            .await
        }

        Command::Rename {
            project,
            service,
            name,
        } => commands::manage::rename_service(&client, &project, &service, &name).await,

        Command::Deploy {
            project,
            service,
            restart,
            detach,
        } => commands::deploy::run(&client, &project, &service, restart, !detach, format).await,

        Command::Redeploy {
            project,
            service,
            number,
        } => commands::deploy::redeploy(&client, &project, &service, number, format).await,

        Command::Rollback {
            project,
            service,
            number,
        } => commands::deploy::rollback(&client, &project, &service, number, format).await,

        Command::Stop { project, service } => {
            commands::write::stop(&client, &project, &service).await
        }

        Command::History {
            project,
            service,
            limit,
        } => commands::read::history(&client, &project, &service, limit, format).await,

        Command::Commit {
            project,
            service,
            commit,
            file,
            stat,
        } => commands::read::commit(&client, &project, &service, commit, file, stat, format).await,

        Command::Watch { project, service } => {
            commands::watch::run(&client, project.as_deref(), service.as_deref(), format).await
        }

        Command::Logs {
            project,
            service,
            follow,
            tail,
            stream,
            step,
            deployment,
            timestamps,
            trace,
        } => {
            commands::logs::run(
                &client,
                &project,
                &service,
                commands::logs::LogQuery {
                    follow,
                    tail,
                    stream_filter: stream.as_deref(),
                    stage: step.as_deref(),
                    number: deployment,
                    timestamps,
                    trace: trace.as_deref(),
                },
                format,
            )
            .await
        }

        Command::Incidents {
            project,
            service,
            decided,
        } => commands::read::incidents(&client, &project, &service, decided, format).await,

        Command::Approvals { project, service } => {
            commands::read::approvals(&client, &project, service.as_deref(), format).await
        }

        Command::Approve { id } => commands::write::approve_deployment(&client, &id, format).await,

        Command::Reject { id } => commands::write::reject_deployment(&client, &id, format).await,

        Command::Autofix {
            project,
            service,
            mode,
            agent,
            model,
            min_occurrences,
            daily_limit,
        } => {
            let mut changes = serde_json::Map::new();
            if let Some(value) = mode {
                changes.insert("mode".into(), value.into());
            }
            if let Some(value) = agent {
                changes.insert("agentServiceEnvironmentId".into(), value.into());
            }
            if let Some(value) = model {
                changes.insert("model".into(), value.into());
            }
            if let Some(value) = min_occurrences {
                changes.insert("minimumOccurrences".into(), value.into());
            }
            if let Some(value) = daily_limit {
                changes.insert("dailyLimit".into(), value.into());
            }

            commands::read::autofix(
                &client,
                &project,
                &service,
                serde_json::Value::Object(changes),
                format,
            )
            .await
        }

        Command::Fix { id } => commands::write::fix_incident(&client, &id, format).await,

        Command::Incident { id, status } => {
            commands::write::decide_incident(&client, &id, &status, format).await
        }

        Command::SignIns { limit } => commands::read::sign_ins(&client, limit, format).await,

        Command::Sessions { command } => match command {
            None => commands::read::auth_sessions(&client, format).await,
            Some(SessionCommand::Revoke { session_id }) => {
                client.revoke_session(&session_id).await?;
                println!("Sesión cerrada.");
                Ok(())
            }
        },

        Command::Activity { project, limit } => {
            commands::read::activity(&client, &project, limit, format).await
        }

        Command::Metrics {
            project,
            service,
            minutes,
        } => commands::read::metrics(&client, &project, &service, minutes, format).await,

        Command::Consumption {
            project,
            service,
            range,
        } => commands::read::consumption(&client, &project, &service, &range, format).await,

        Command::AgentActivity {
            project,
            service,
            range,
            outcome,
        } => {
            commands::read::agent_activity(
                &client,
                &project,
                &service,
                &range,
                outcome.as_deref(),
                format,
            )
            .await
        }

        Command::Variables { command } => match command {
            VariableCommand::List {
                project,
                service,
                reveal,
            } => commands::read::variables(&client, &project, &service, reveal, format).await,
            VariableCommand::Set {
                project,
                service,
                key,
                value,
                secret,
                sealed,
            } => {
                commands::write::set_variable(
                    &client, &project, &service, &key, &value, secret, sealed,
                )
                .await
            }
            VariableCommand::Seal {
                project,
                service,
                key,
                confirm,
            } => {
                commands::write::seal_variable(
                    &client,
                    &project,
                    &service,
                    &key,
                    confirm.as_deref(),
                )
                .await
            }
            VariableCommand::Unset {
                project,
                service,
                key,
            } => commands::write::unset_variable(&client, &project, &service, &key).await,
            VariableCommand::Import {
                project,
                service,
                file,
                secret,
            } => {
                commands::write::import_variables(&client, &project, &service, &file, secret).await
            }
        },

        Command::Access { command } => match command {
            AccessCommand::Status { project, service } => {
                commands::read::repository_access(&client, &project, &service, format).await
            }
            AccessCommand::Request {
                project,
                service,
                email,
            } => {
                commands::write::request_repository_access(
                    &client,
                    &project,
                    &service,
                    email.as_deref(),
                    format,
                )
                .await
            }
        },

        Command::Backups { command } => match command {
            BackupCommand::List { project, service } => {
                commands::read::backups(&client, &project, &service, format).await
            }
            BackupCommand::New { project, service } => {
                commands::write::take_backup(&client, &project, &service).await
            }
            BackupCommand::Schedule {
                project,
                service,
                schedules,
            } => commands::write::schedule_backups(&client, &project, &service, &schedules).await,
            BackupCommand::Restore { backup_id, confirm } => {
                commands::write::restore_backup(&client, &backup_id, confirm.as_deref()).await
            }
            BackupCommand::Keep { backup_id } => {
                commands::write::lock_backup(&client, &backup_id, true).await
            }
            BackupCommand::Unkeep { backup_id } => {
                commands::write::lock_backup(&client, &backup_id, false).await
            }
            BackupCommand::Remove { backup_id } => {
                commands::write::delete_backup(&client, &backup_id).await
            }
        },

        Command::Domains { command } => match command {
            DomainCommand::List { project, service } => {
                commands::read::domains(&client, &project, &service, format).await
            }
            DomainCommand::Add {
                project,
                service,
                host,
            } => commands::write::add_domain(&client, &project, &service, host.as_deref()).await,
            DomainCommand::Verify { domain_id } => {
                commands::read::verify_domain(&client, &domain_id, format).await
            }
            DomainCommand::Remove { domain_id } => {
                commands::write::remove_domain(&client, &domain_id).await
            }
        },

        Command::Connect {
            project,
            service,
            provider,
        } => commands::write::connect(&client, &project, &service, &provider).await,

        Command::Disconnect {
            project,
            service,
            provider,
        } => commands::manage::disconnect(&client, &project, &service, &provider).await,

        Command::Connectable { project, service } => {
            commands::write::candidates(&client, &project, &service, format).await
        }

        Command::Volumes { command } => match command {
            VolumeCommand::List { project, service } => {
                commands::read::volumes(&client, &project, &service, format).await
            }
            VolumeCommand::Add {
                project,
                service,
                mount_path,
            } => commands::write::attach_volume(&client, &project, &service, &mount_path).await,
            VolumeCommand::Resize { volume_id, gb } => {
                commands::write::resize_volume(&client, &volume_id, gb).await
            }
            VolumeCommand::Remove { volume_id } => {
                commands::manage::detach_volume(&client, &volume_id).await
            }
        },

        Command::Recipe { command } => match command {
            RecipeCommand::Show {
                project,
                service,
                plain,
            } => commands::read::recipe(&client, &project, &service, plain, format).await,
            RecipeCommand::Edit {
                project,
                service,
                file,
            } => commands::write::edit_recipe(&client, &project, &service, &file).await,
        },

        Command::Config { command } => match command {
            ConfigCommand::Show {
                project,
                service,
                plain,
            } => commands::read::service_config(&client, &project, &service, plain, format).await,
            ConfigCommand::Edit {
                project,
                service,
                file,
            } => commands::write::edit_service_config(&client, &project, &service, &file).await,
        },

        Command::Capabilities { project, service } => {
            commands::read::capabilities(&client, &project, &service, format).await
        }

        Command::Capacity => commands::manage::capacity(&client, format).await,

        Command::Settings {
            project,
            service,
            memory,
            replicas,
            root,
            start_command,
            health_path,
            health_probe,
            health_timeout_seconds,
            health_interval_seconds,
            health_grace_seconds,
            health_expected_status,
            restart_policy,
            restart_max_retries,
            sleep,
            auto_deploy,
            cache_enabled,
            cache_ttl_seconds,
        } => {
            commands::manage::set_settings(
                &client,
                &project,
                &service,
                api::models::SettingsPatch {
                    memory_mb: memory,
                    replicas,
                    root_directory: root,
                    start_command,
                    health_path,
                    health_probe,
                    health_timeout_seconds,
                    health_interval_seconds,
                    health_grace_seconds,
                    health_expected_status,
                    restart_policy,
                    restart_max_retries,
                    sleep_enabled: sleep,
                    auto_deploy,
                    cache_enabled,
                    cache_ttl_seconds,
                },
            )
            .await
        }

        Command::Expose {
            project,
            service,
            off,
        } => commands::manage::expose(&client, &project, &service, !off).await,

        Command::Encrypt {
            project,
            service,
            off,
        } => commands::manage::encryption(&client, &project, &service, !off).await,

        Command::Delete {
            project,
            service,
            confirm,
        } => commands::manage::delete(&client, &project, &service, confirm.as_deref()).await,

        Command::Workspace { command } => match command {
            WorkspaceCommand::List => commands::workspace::list(&client, format).await,
            WorkspaceCommand::Members { workspace } => {
                commands::workspace::members(&client, workspace.as_deref(), format).await
            }
            WorkspaceCommand::Credits { workspace } => {
                commands::workspace::credits(&client, workspace.as_deref(), format).await
            }
            WorkspaceCommand::Invite {
                email,
                workspace,
                admin,
            } => commands::workspace::invite(&client, workspace.as_deref(), &email, admin).await,
            WorkspaceCommand::Revoke {
                invitation_id,
                workspace,
            } => commands::workspace::revoke(&client, workspace.as_deref(), &invitation_id).await,
            WorkspaceCommand::Remove { user_id, workspace } => {
                commands::workspace::remove(&client, workspace.as_deref(), &user_id).await
            }
        },
    }
}

/// The client for this invocation.
///
/// Flags beat the environment beats the saved profile, which is the order every
/// tool of this shape uses and the order that makes a one-off `--url` work
/// without disturbing what is saved.
fn connect(cli: &Cli) -> Result<ApiClient> {
    if let (Some(url), Some(token)) = (&cli.url, &cli.token) {
        return ApiClient::new(url, Some(token.clone()));
    }

    let config = Config::load().context("could not read the configuration")?;
    let (_, profile) = config.profile(cli.profile.as_deref())?;

    ApiClient::new(
        cli.url.as_deref().unwrap_or(&profile.url),
        Some(cli.token.clone().unwrap_or_else(|| profile.token.clone())),
    )
}