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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
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
# ===== file: bin/flatkey.js =====
#!/usr/bin/env node
import { main } from "../src/cli.js";

main(process.argv.slice(2)).catch((error) => {
  if (process.argv.includes("--json")) {
    process.stderr.write(`${JSON.stringify({ error: { message: error.message } })}\n`);
  } else {
    process.stderr.write(`${error.message}\n`);
  }
  process.exitCode = 1;
});

# ===== file: rust/flatkey-depth/src/main.rs =====
use anyhow::{bail, Context, Result};
use clap::Parser;
use image::{imageops::FilterType, DynamicImage, ImageBuffer, Rgb};
use ndarray::Array4;
use ort::{session::Session, value::Tensor};
use serde::Serialize;
use std::{
    io::{Read, Write},
    path::{Path, PathBuf},
    process::{Child, Command, Stdio},
};

const MODEL_URL: &str =
    "https://huggingface.co/onnx-community/depth-anything-v2-small/resolve/main/onnx/model_quantized.onnx";
const MODEL_INPUT: u32 = 364;

#[derive(Debug, Parser)]
#[command(name = "flatkey-depth", version)]
struct Args {
    #[arg(long)]
    source: PathBuf,
    #[arg(long)]
    output: PathBuf,
    #[arg(long, default_value_t = 100)]
    frame_ratio: u8,
    #[arg(long, default_value = "480p")]
    resolution: String,
    #[arg(long)]
    work_dir: PathBuf,
    #[arg(long)]
    model: Option<PathBuf>,
}

#[derive(Debug, Serialize)]
struct ResultJson {
    output: PathBuf,
    frame_ratio: u8,
    resolution: String,
    model: String,
    inference: String,
}

fn main() -> Result<()> {
    let args = Args::parse();
    if !(20..=100).contains(&args.frame_ratio) {
        bail!("--frame-ratio must be between 20 and 100");
    }
    if !matches!(args.resolution.as_str(), "original" | "480p" | "320p") {
        bail!("--resolution must be original, 480p, or 320p");
    }

    std::fs::create_dir_all(&args.work_dir)?;
    let model = args
        .model
        .or_else(|| std::env::var_os("FLATKEY_DEPTH_MODEL").map(PathBuf::from))
        .ok_or_else(|| anyhow::anyhow!(
            "Depth Anything V2 model is required; pass --model <model_quantized.onnx> \
             or set FLATKEY_DEPTH_MODEL (official model: {MODEL_URL})"
        ))?;
    if !model.is_file() {
        bail!("Depth Anything V2 model does not exist: {}", model.display());
    }

    let (width, height, fps) = probe_video(&args.source)?;
    let (output_width, output_height) = output_size(width, height, &args.resolution);
    let decoder = spawn_decoder(&args.source)?;
    let encoder = spawn_encoder(&args.output, output_width, output_height, fps)?;
    let mut session = Session::builder()?.commit_from_file(&model)?;
    infer_frames(
        decoder,
        encoder,
        &mut session,
        output_width,
        output_height,
        args.frame_ratio,
    )?;

    println!(
        "{}",
        serde_json::to_string(&ResultJson {
            output: args.output,
            frame_ratio: args.frame_ratio,
            resolution: args.resolution,
            model: model.display().to_string(),
            inference: "depth-anything-v2-small-onnx".to_string(),
        })?
    );
    Ok(())
}

fn probe_video(path: &Path) -> Result<(u32, u32, f64)> {
    let out = Command::new("ffprobe")
        .args([
            "-v", "error",
            "-select_streams", "v:0",
            "-show_entries", "stream=width,height,avg_frame_rate",
            "-of", "csv=p=0",
        ])
        .arg(path)
        .output()
        .with_context(|| "failed to start ffprobe")?;
    if !out.status.success() {
        bail!("ffprobe failed: {}", String::from_utf8_lossy(&out.stderr));
    }
    let fields: Vec<_> = String::from_utf8_lossy(&out.stdout)
        .trim()
        .split(',')
        .map(str::to_owned)
        .collect();
    if fields.len() < 3 {
        bail!("ffprobe returned invalid video metadata");
    }
    Ok((fields[0].parse()?, fields[1].parse()?, parse_rate(&fields[2])?))
}

fn parse_rate(value: &str) -> Result<f64> {
    if let Some((a, b)) = value.split_once('/') {
        return Ok(a.parse::<f64>()? / b.parse::<f64>()?);
    }
    Ok(value.parse()?)
}

fn output_size(width: u32, height: u32, resolution: &str) -> (u32, u32) {
    let max_height = match resolution {
        "320p" => Some(320),
        "480p" => Some(480),
        _ => None,
    };
    let Some(max_height) = max_height else {
        return (width, height);
    };
    if height <= max_height {
        return (width, height);
    }
    let scaled_width =
        ((width as f64 * max_height as f64 / height as f64) / 2.0).floor() as u32 * 2;
    (scaled_width.max(2), max_height)
}

fn spawn_decoder(source: &Path) -> Result<Child> {
    let filter = "scale=364:364:flags=lanczos,format=rgb24";
    Command::new("ffmpeg")
        .args(["-v", "error", "-i"])
        .arg(source)
        .args(["-an", "-vf", &filter, "-f", "rawvideo", "-pix_fmt", "rgb24", "-"])
        .stdout(Stdio::piped())
        .spawn()
        .with_context(|| "failed to start ffmpeg decoder")
}

fn spawn_encoder(output: &Path, width: u32, height: u32, fps: f64) -> Result<Child> {
    let fps_arg = if fps.is_finite() && fps > 0.0 {
        format!("{fps:.6}")
    } else {
        "30".to_string()
    };
    Command::new("ffmpeg")
        .args([
            "-v", "error", "-y",
            "-f", "rawvideo", "-pix_fmt", "gray",
            "-s", &format!("{width}x{height}"),
            "-r", &fps_arg, "-i", "-",
            "-an", "-c:v", "libx264", "-pix_fmt", "yuv420p",
            "-preset", "veryfast", "-crf", "18", "-movflags", "+faststart",
        ])
        .arg(output)
        .stdin(Stdio::piped())
        .spawn()
        .with_context(|| "failed to start ffmpeg encoder")
}

fn infer_frames(
    mut decoder: Child,
    mut encoder: Child,
    session: &mut Session,
    output_width: u32,
    output_height: u32,
    frame_ratio: u8,
) -> Result<()> {
    let mut input = decoder.stdout.take().context("decoder stdout unavailable")?;
    let mut encoded = encoder.stdin.take().context("encoder stdin unavailable")?;
    let frame_bytes = (MODEL_INPUT * MODEL_INPUT * 3) as usize;
    let mut frame = vec![0_u8; frame_bytes];
    let mut last_frame = vec![0_u8; frame_bytes];
    let mut previous_depth: Option<Vec<u8>> = None;
    let mut previous_index = 0_u64;
    let mut frame_index = 0_u64;
    let mut selection_accumulator = 100_u16;

    loop {
        let mut read = 0;
        while read < frame.len() {
            let count = input.read(&mut frame[read..])?;
            if count == 0 {
                break;
            }
            read += count;
        }
        if read == 0 {
            break;
        }
        if read != frame.len() {
            bail!("decoder ended with a partial RGB frame");
        }

        last_frame.copy_from_slice(&frame);
        selection_accumulator += frame_ratio as u16;
        let selected = selection_accumulator >= 100;
        if selected {
            selection_accumulator -= 100;
            let depth = infer_depth(&frame, session, output_width, output_height)?;
            if let Some(previous) = previous_depth.replace(depth) {
                write_repeated(&mut encoded, &previous, frame_index - previous_index)?;
            }
            previous_index = frame_index;
        }
        frame_index += 1;
    }

    if frame_index > 0 {
        let last_index = frame_index - 1;
        if previous_index != last_index {
            let last_depth = infer_depth(&last_frame, session, output_width, output_height)?;
            if let Some(previous) = previous_depth.take() {
                write_repeated(&mut encoded, &previous, last_index - previous_index)?;
            }
            encoded.write_all(&last_depth)?;
        } else if let Some(previous) = previous_depth.take() {
            write_repeated(&mut encoded, &previous, 1)?;
        }
    }

    drop(encoded);
    if !decoder.wait()?.success() {
        bail!("ffmpeg decoder failed");
    }
    if !encoder.wait()?.success() {
        bail!("ffmpeg encoder failed");
    }
    Ok(())
}

fn infer_depth(
    frame: &[u8],
    session: &mut Session,
    output_width: u32,
    output_height: u32,
) -> Result<Vec<u8>> {
    let plane = (MODEL_INPUT * MODEL_INPUT) as usize;
    let mut chw = vec![0_f32; plane * 3];
    for index in 0..plane {
        let pixel = index * 3;
        chw[index] = (frame[pixel] as f32 / 255.0 - 0.485) / 0.229;
        chw[plane + index] = (frame[pixel + 1] as f32 / 255.0 - 0.456) / 0.224;
        chw[2 * plane + index] = (frame[pixel + 2] as f32 / 255.0 - 0.406) / 0.225;
    }

    let tensor = Tensor::from_array(Array4::from_shape_vec(
        (1, 3, MODEL_INPUT as usize, MODEL_INPUT as usize),
        chw,
    )?)?;
    let outputs = session.run(ort::inputs!["pixel_values" => tensor])?;
    let (shape, data) = outputs[0].try_extract_tensor::<f32>()?;
    let depth_height = shape[shape.len() - 2] as u32;
    let depth_width = shape[shape.len() - 1] as u32;
    let (mut min, mut max) = (f32::INFINITY, f32::NEG_INFINITY);
    for value in data.iter().copied() {
        min = min.min(value);
        max = max.max(value);
    }
    let range = (max - min).max(1e-6);
    let mut image = ImageBuffer::<Rgb<u8>, Vec<u8>>::new(depth_width, depth_height);
    for (index, pixel) in image.pixels_mut().enumerate() {
        let value = ((data[index] - min) / range * 255.0).clamp(0.0, 255.0) as u8;
        *pixel = Rgb([value, value, value]);
    }
    let resized = DynamicImage::ImageRgb8(image).resize_exact(
        output_width,
        output_height,
        FilterType::Lanczos3,
    );
    Ok(resized.to_luma8().into_raw())
}

fn write_repeated(output: &mut impl Write, frame: &[u8], count: u64) -> Result<()> {
    for _ in 0..count {
        output.write_all(frame)?;
    }
    Ok(())
}

# ===== file: src/animation.js =====
const FRAMES = [
  "[FLATKEY]  .    ",
  "[FLATKEY]  ..   ",
  "[FLATKEY]  ...  ",
  "[FLATKEY]  .... ",
  "[FLATKEY]  >>>> ",
];

export function createAnimation({
  json = false,
  stream = process.stderr,
  setIntervalFn = setInterval,
  clearIntervalFn = clearInterval,
} = {}) {
  let timer;
  let active = false;
  let frame = 0;

  return {
    start(kind = "media") {
      if (json) return;
      if (!stream.isTTY) {
        stream.write(`flatkey ${kind} generation started\n`);
        return;
      }
      active = true;
      stream.write(`${FRAMES[0]}\r`);
      timer = setIntervalFn(() => {
        if (!active) return;
        frame = (frame + 1) % FRAMES.length;
        stream.write(`${FRAMES[frame]}\r`);
      }, 120);
    },
    stop() {
      active = false;
      if (timer) clearIntervalFn(timer);
      if (!json && stream.isTTY) stream.write("                 \r");
    },
  };
}

# ===== file: src/api.js =====
import { withCliRequestHeaders } from "./requestHeaders.js";

export const DEFAULT_BASE_URL = "https://router.flatkey.ai";
export const DEFAULT_MODELS_BASE_URL = "https://console.flatkey.ai";
export const DEFAULT_CONSOLE_URL = "https://console.flatkey.ai";

export class FlatkeyError extends Error {
  constructor(message, { status, code } = {}) {
    super(message);
    this.name = "FlatkeyError";
    this.status = status;
    this.code = code;
  }
}

export async function generateImage(options) {
  return requestJsonFromPlan(options, planImageRequest(options));
}

export async function uploadTempMediaImage(options) {
  return uploadTempMediaByKind(options, "images");
}

export async function uploadTempMediaVideo(options) {
  return uploadTempMediaByKind(options, "videos");
}

async function uploadTempMediaByKind(options, kind) {
  const form = new FormData();
  form.append("file", new Blob([options.file], cleanObject({
    type: options.contentType,
  })), options.filename ?? (kind === "videos" ? "video" : "image"));
  return requestJsonFromPlan(options, planRequest(options, `/v1/temp-media/${kind}`, {
    method: "POST",
    headers: authHeaders(options.apiKey),
    body: form,
  }));
}

export function planImageRequest(options) {
  const model = options.model ?? "nano-banana-pro-preview";
  const mediaInputs = orderedMediaInputs(options);
  assertReferenceLimits(mediaInputs, "image", model);
  if (mediaInputs.some((entry) => entry.kind === "video")) {
    throw new Error("Image models only accept image inputs.");
  }
  const imageUrls = mediaInputs
    .map((entry) => entry.url);
  if (model.startsWith("gpt")) {
    const responseFormat = options.response_format ?? options.responseFormat ?? "url";
    const tempUrl = options.temp_url ?? options.tempUrl;
    return planJsonPost(options, "/v1/images/generations", cleanObject({
      model,
      prompt: options.prompt,
      size: options.size,
      n: parseOptionalInteger(options.n),
      quality: options.quality,
      response_format: responseFormat,
      temp_url: tempUrl ?? true,
      images: imageUrls.length > 0 ? imageUrls : undefined,
    }));
  }

  const path = `/v1beta/models/${encodeURIComponent(model)}:generateContent?key=${encodeURIComponent(options.apiKey)}`;
  return planRequest(options, path, {
    method: "POST",
    headers: {
      ...jsonHeaders(options.apiKey),
      "x-goog-api-key": options.apiKey,
    },
    body: {
      contents: [{
        parts: [
          { text: options.prompt },
          ...imageUrls.map((url) => ({ type: "image_url", image_url: { url } })),
        ],
      }],
      temp_url: true,
    },
  });
}

export function generateVideo(options) {
  return requestJsonFromPlan(options, planVideoRequest(options));
}

export function getVideo(options, taskId) {
  return requestJsonFromPlan(options, planVideoStatusRequest(options, taskId));
}

export function planVideoRequest(options) {
  const model = options.model ?? "seedance-2.0-pro";
  const mediaInputs = orderedMediaInputs(options);
  assertReferenceLimits(mediaInputs, "video", model);
  if (mediaInputs.some((entry) => entry.role === "first_frame" && entry.kind === "video")
    || mediaInputs.some((entry) => entry.role === "last_frame" && entry.kind === "video")) {
    throw new Error("Video first-frame and last-frame inputs must be images.");
  }
  const imageUrls = mediaInputs
    .filter((entry) => entry.kind !== "video")
    .map((entry) => entry.url);
  const videoUrls = mediaInputs
    .filter((entry) => entry.kind === "video")
    .map((entry) => entry.url);
  const ratio = validateOptionalValue(
    optionValue(options, "ratio", "aspect")
      ?? (isMiniMaxModel(model) ? "16:9" : isSeedance25Model(model) ? "adaptive" : undefined),
    ["16:9", "9:16", "4:3", "3:4", "21:9", "1:1", "adaptive"],
    "ratio",
  );
  const resolution = validateOptionalValue(
    options.resolution ?? (isMiniMaxModel(model) ? "768P" : undefined),
    isMiniMaxModel(model) ? ["768P", "2K"] : ["480p", "720p", "1080p"],
    "resolution",
  );
  const basePayload = cleanObject({
    model,
    prompt: options.prompt,
    duration: options.duration === undefined && isMiniMaxModel(model)
      ? 5
      : options.duration === undefined && isSeedance25Model(model)
        ? -1
      : parseOptionalFloat(options.duration),
    aspect: ratio,
    ratio,
    resolution,
    quality: resolution,
    fps: parseOptionalInteger(options.fps),
    generate_audio: parseOptionalBoolean(options.generate_audio) ?? true,
    omni_reference_task_type: isSeedance25Model(model) && mediaInputs.some((entry) => entry.kind === "video" || entry.role === "reference_image")
      ? "auto"
      : undefined,
    temp_url: true,
    images: !isSeedanceModel(model) && imageUrls.length > 0 ? imageUrls : undefined,
  });
  const seedanceContent = buildSeedanceContent(options, mediaInputs);
  if ((isSeedanceModel(model) || isMiniMaxModel(model)) && seedanceContent.length > 0) {
    return planJsonPost(options, videoGenerationPath(model, videoUrls), cleanObject({
      ...basePayload,
      content: seedanceContent,
    }));
  }
  return planJsonPost(options, "/v1/video/generations", basePayload);
}

export function planVideoStatusRequest(options, taskId) {
  return planRequest(options, `/v1/videos/${encodeURIComponent(taskId)}`);
}

export function generateAudio(options) {
  return requestBinaryArtifactFromPlan(options, planAudioRequest(options));
}

export function planAudioRequest(options) {
  const voiceId = optionValue(options, "voiceId", "voice_id") ?? "EXAVITQu4vr4xnSDxMaL";
  return planJsonPost(options, `/v1/text-to-speech/${encodeURIComponent(voiceId)}`, cleanObject({
    text: options.text ?? options.prompt,
    model_id: options.model ?? options.model_id ?? "eleven_multilingual_v2",
    voice_settings: cleanObject({
      stability: parseOptionalFloat(options.stability),
      similarity_boost: parseOptionalFloat(optionValue(options, "similarityBoost", "similarity_boost")),
      style: parseOptionalFloat(options.style),
    }),
  }));
}

export function generateAudioSfx(options) {
  return requestBinaryArtifactFromPlan(options, planAudioSfxRequest(options));
}

export function planAudioSfxRequest(options) {
  return planJsonPost(options, "/v1/sound-generation", cleanObject({
    text: options.text ?? options.prompt,
    duration_seconds: parseOptionalFloat(optionValue(options, "durationSeconds", "duration_seconds", "duration")),
  }));
}

export function generateAudioMusic(options) {
  return requestBinaryArtifactFromPlan(options, planAudioMusicRequest(options));
}

export function planAudioMusicRequest(options) {
  return planJsonPost(options, "/v1/music", cleanObject({
    prompt: options.prompt,
    music_length_ms: parseOptionalInteger(optionValue(options, "musicLengthMs", "music_length_ms")),
  }));
}

export function getVoices(options) {
  return requestJson(options, "/v1/voices");
}

export function planVoicesRequest(options) {
  return planRequest(options, "/v1/voices");
}

export function generateText(options) {
  return requestJsonFromPlan(options, planTextRequest(options));
}

export function planTextRequest(options) {
  return planJsonPost(options, "/v1/chat/completions", {
    model: options.model ?? "gpt-5.5",
    messages: [{ role: "user", content: options.prompt }],
  });
}

export function getCredits(options) {
  return requestJson({
    ...options,
    baseUrl: options.baseUrl ?? DEFAULT_CONSOLE_URL,
  }, "/v1/credits");
}

export function getStatus(options) {
  return requestJson({
    ...options,
    baseUrl: options.baseUrl ?? DEFAULT_CONSOLE_URL,
  }, "/v1/status");
}

export function getModels(options) {
  return requestJson({
    ...options,
    baseUrl: options.baseUrl ?? DEFAULT_MODELS_BASE_URL,
  }, "/v1/available_models");
}

export async function createDeviceAuthorization(options) {
  return requestJson({
    ...options,
    baseUrl: options.consoleUrl ?? DEFAULT_CONSOLE_URL,
  }, "/api/cli/device_authorizations", {
    method: "POST",
    body: JSON.stringify({
      client_name: options.clientName ?? "flatkey-cli",
      client_version: options.clientVersion,
      device_id: options.deviceId,
    }),
  });
}

export async function pollDeviceAuthorization(options) {
  return requestJson({
    ...options,
    baseUrl: options.consoleUrl ?? DEFAULT_CONSOLE_URL,
  }, "/api/cli/device_authorizations/token", {
    method: "POST",
    body: JSON.stringify({
      device_code: options.deviceCode,
    }),
  });
}

async function postJson(options, path, payload) {
  return requestJsonFromPlan(options, planJsonPost(options, path, payload));
}

function planJsonPost(options, path, payload) {
  return planRequest(options, path, {
    method: "POST",
    headers: jsonHeaders(options.apiKey),
    body: payload,
  });
}

function planRequest(options, path, init = {}) {
  return {
    url: buildUrl(options.baseUrl, path),
    method: init.method ?? "GET",
    headers: withCliRequestHeaders(init.headers ?? authHeaders(options.apiKey)),
    body: init.body,
  };
}

async function requestJsonFromPlan(options, plan) {
  const fetchImpl = options.fetch ?? fetch;
  const request = {
    method: plan.method,
    headers: plan.headers,
    body: plan.body === undefined
      ? undefined
      : isFormData(plan.body)
        ? plan.body
        : JSON.stringify(plan.body),
  };
  logRequest(options, plan.url, request);
  const response = await fetchImpl(plan.url, request);
  logResponse(options, response);
  const body = await readJson(response);
  logResponseBody(options, body);
  if (!response.ok || body?.success === false) {
    throw new FlatkeyError(extractErrorMessage(body, response.status), {
      status: response.status,
      code: body?.code ?? body?.error?.code,
    });
  }
  return body;
}

function isFormData(value) {
  return typeof FormData !== "undefined" && value instanceof FormData;
}

async function requestBinaryArtifactFromPlan(options, plan) {
  const fetchImpl = options.fetch ?? fetch;
  const request = {
    method: plan.method,
    headers: plan.headers,
    body: plan.body === undefined ? undefined : JSON.stringify(plan.body),
  };
  logRequest(options, plan.url, request);
  const response = await fetchImpl(plan.url, request);
  logResponse(options, response);
  if (!response.ok) {
    const body = await readJson(response);
    logResponseBody(options, body);
    throw new FlatkeyError(extractErrorMessage(body, response.status), {
      status: response.status,
      code: body?.code ?? body?.error?.code,
    });
  }
  return {
    data: [{ data: Buffer.from(await response.arrayBuffer()).toString("base64") }],
  };
}

function logRequest(options, url, request) {
  if (!options?.verbose) return;
  const safeHeaders = redactHeaders(request.headers);
  const safeBody = request.body === undefined
    ? undefined
    : isFormData(request.body)
      ? "<form-data>"
      : request.body;
  options.verboseLog?.(`-> ${request.method} ${url}`);
  options.verboseLog?.(`headers: ${JSON.stringify(safeHeaders)}`);
  if (safeBody !== undefined) {
    options.verboseLog?.(`body: ${safeBody}`);
  }
}

function logResponse(options, response) {
  if (!options?.verbose) return;
  options.verboseLog?.(`<- ${response.status} ${response.statusText || ""}`.trim());
}

function logResponseBody(options, body) {
  if (!options?.verbose) return;
  options.verboseLog?.(`response: ${truncateLogValue(JSON.stringify(body))}`);
}

function redactHeaders(headers) {
  return Object.fromEntries(Object.entries(headers ?? {}).map(([key, value]) => [
    key,
    key.toLowerCase() === "authorization" ? "Bearer <redacted>" : `${value}`,
  ]));
}

function truncateLogValue(value) {
  if (value === undefined) return "";
  return value.length > 1200 ? `${value.slice(0, 1200)}…` : value;
}

async function requestJson(options, path, init = {}) {
  return requestJsonFromPlan(options, planRequest(options, path, {
    method: init.method ?? "GET",
    headers: {
      ...authHeaders(options.apiKey),
      ...init.headers,
    },
    body: init.body ? JSON.parse(init.body) : undefined,
  }));
}

function buildUrl(baseUrl = DEFAULT_BASE_URL, path) {
  return `${baseUrl.replace(/\/$/, "")}${path}`;
}

function authHeaders(apiKey) {
  return apiKey ? { Authorization: `Bearer ${apiKey}` } : {};
}

function jsonHeaders(apiKey) {
  return {
    ...authHeaders(apiKey),
    "content-type": "application/json",
  };
}

function parseOptionalInteger(value) {
  if (value === undefined) return undefined;
  return Number.parseInt(value, 10);
}

function parseOptionalFloat(value) {
  if (value === undefined) return undefined;
  return Number.parseFloat(value);
}

function parseOptionalBoolean(value) {
  if (value === undefined) return undefined;
  if (value === true || value === "true") return true;
  if (value === false || value === "false") return false;
  throw new Error(`Invalid boolean value: ${value}. Allowed values: true, false`);
}

function optionValue(options, ...keys) {
  for (const key of keys) {
    if (options[key] !== undefined) return options[key];
  }
  return undefined;
}

function validateOptionalValue(value, allowed, name) {
  if (value === undefined) return undefined;
  if (allowed.includes(value)) return value;
  throw new Error(`Invalid ${name}: ${value}. Allowed values: ${allowed.join(", ")}`);
}

function isSeedanceModel(model) {
  return /seedance/i.test(model);
}

function isMiniMaxModel(model) {
  return /^minimax-h3$/i.test(model);
}

function videoGenerationPath(model, videoUrls = []) {
  // Seedance keeps text, image, and video-reference content on /v1/videos.
  // The legacy route does not reliably fetch video references upstream.
  if (isSeedanceModel(model)) return "/v1/videos";
  return "/v1/video/generations";
}

function buildSeedanceContent(options, mediaInputs = orderedMediaInputs(options)) {
  const content = [];
  if (options.prompt !== undefined) {
    content.push({ type: "text", text: options.prompt });
  }
  for (const entry of mediaInputs) {
    if (entry.kind === "video") {
      content.push({ type: "video_url", video_url: { url: entry.url }, role: entry.role ?? "reference_video" });
      continue;
    }
    content.push({ type: "image_url", image_url: { url: entry.url }, role: entry.role ?? "reference_image" });
  }
  return content;
}

function arrayOption(value) {
  if (value === undefined) return [];
  return Array.isArray(value) ? value : [value];
}

function cleanObject(value) {
  return Object.fromEntries(
    Object.entries(value).filter(([, entry]) => entry !== undefined),
  );
}

function assertReferenceLimits(mediaInputs, kind, model) {
  const imageInputs = mediaInputs.filter((entry) => entry.kind !== "video");
  const videoInputs = mediaInputs.filter((entry) => entry.kind === "video");
  if (isSeedance25Model(model)) {
    if (imageInputs.length > 30) {
      throw new Error(`Too many reference images for flatkey ${kind} generate with Seedance 2.5: maximum 30.`);
    }
    if (videoInputs.length > 10) {
      throw new Error(`Too many reference videos for flatkey ${kind} generate with Seedance 2.5: maximum 10.`);
    }
    return;
  }
  if (imageInputs.length > 5) {
    throw new Error(`Too many reference images for flatkey ${kind} generate: maximum 5.`);
  }
}

function orderedMediaInputs(options) {
  const hidden = Array.isArray(options.__media_inputs) ? options.__media_inputs : [];
  if (hidden.length > 0 && hidden[0] && Object.prototype.hasOwnProperty.call(hidden[0], "url")) {
    return hidden;
  }
  if (hidden.length > 0) {
    return hidden.map((entry) => ({
      ...entry,
      url: entry.url ?? entry.value,
      kind: entry.kind ?? inferMediaKindFromName(entry.name, entry.value),
    }));
  }

  const legacy = [];
  const push = (name, value, kind = "image", role) => {
    for (const item of arrayOption(value)) {
      legacy.push({ name, url: item, kind: kind === "image" ? inferMediaKindFromName(name, item) : kind, role });
    }
  };
  push("file", options.file, "image");
  push("image", options.image, "image");
  push("image_url", options.image_url, "image");
  push("first_frame", options.first_frame, "image", "first_frame");
  push("first_frame_url", options.first_frame_url, "image", "first_frame");
  push("last_frame", options.last_frame, "image", "last_frame");
  push("last_frame_url", options.last_frame_url, "image", "last_frame");
  push("video_url", options.video_url, "video", "reference_video");
  return legacy;
}

function inferMediaKindFromName(name, value) {
  const lowerName = String(name ?? "").toLowerCase();
  if (lowerName.includes("video")) return "video";
  if (typeof value === "string" && /\.(mp4|mov)$/i.test(value)) return "video";
  return "image";
}

function isSeedance25Model(model) {
  return String(model ?? "").toLowerCase().replaceAll(/[-_.]/g, "").includes("seedance25");
}

async function readJson(response) {
  try {
    return await response.json();
  } catch {
    return {};
  }
}

function extractErrorMessage(body, status) {
  const message = typeof body?.error?.message === "string"
    ? body.error.message
    : typeof body?.message === "string"
      ? body.message
      : undefined;
  if (isAuthTokenError(message)) return missingApiKeyMessage();
  if (message) return message;
  return `Flatkey API request failed with HTTP ${status}`;
}

function isAuthTokenError(message) {
  return message === "Token not provided" || /^Invalid token\b/i.test(message ?? "");
}

function missingApiKeyMessage() {
  return "Missing or invalid Flatkey API key. Run `flatkey login`, or create a key at https://console.flatkey.ai/keys and run `flatkey onboard --api-key <key>`.";
}

# ===== file: src/artifacts.js =====
import { mkdir, readdir, writeFile } from "node:fs/promises";
import { homedir } from "node:os";
import { dirname, extname, join } from "node:path";

import { CLI_REQUEST_HEADERS } from "./requestHeaders.js";

const DEFAULT_EXTENSIONS = {
  audio: "mp3",
  image: "png",
  video: "mp4",
};

const MIME_EXTENSIONS = {
  "audio/aac": "aac",
  "audio/flac": "flac",
  "audio/mpeg": "mp3",
  "audio/mp3": "mp3",
  "audio/wav": "wav",
  "image/jpeg": "jpg",
  "image/png": "png",
  "video/mp4": "mp4",
};

export async function persistArtifacts({
  kind,
  response,
  outDir = "flatkey-output",
  output,
  fetch: fetchImpl = fetch,
}) {
  output = expandHomePath(output);
  const items = extractItems(response);
  const artifacts = [];
  await mkdir(output ? dirname(output) : outDir, { recursive: true });
  const startIndex = output ? 0 : await nextArtifactIndex({ kind, outDir });

  for (const [index, item] of items.entries()) {
    const artifact = await persistItem({ kind, item, outDir, output, index: index + startIndex, fetchImpl });
    if (artifact) artifacts.push(artifact);
  }

  return artifacts;
}

export async function nextArtifactPath({ kind, outDir = "flatkey-output" }) {
  const extension = DEFAULT_EXTENSIONS[kind] ?? "bin";
  const index = await nextArtifactIndex({ kind, outDir });
  const number = String(index + 1).padStart(2, "0");
  return join(outDir, `${kind}-${number}.${extension}`);
}

function expandHomePath(path) {
  if (typeof path !== "string") return path;
  if (path === "~") return homedir();
  if (path.startsWith("~/")) return join(homedir(), path.slice(2));
  return path;
}

async function persistItem({ kind, item, outDir, output, index, fetchImpl }) {
  const dataUrl = getString(item, ["url", "video_url", "data_url", "dataUrl", "temp_url"]);
  if (dataUrl?.startsWith("data:")) {
    const parsed = parseDataUrl(dataUrl);
    const path = artifactPath({ kind, outDir, output, index, extension: parsed.extension });
    await writeFile(path, parsed.buffer);
    return { path };
  }
  if (dataUrl?.startsWith("http://") || dataUrl?.startsWith("https://")) {
    if (output) {
      const path = artifactPath({
        kind,
        outDir,
        output,
        index,
        extension: DEFAULT_EXTENSIONS[kind] ?? "bin",
      });
      await downloadArtifact({ url: dataUrl, path, fetchImpl });
      return { path };
    }
    return { url: dataUrl };
  }

  const base64 = getString(item, ["b64_json", "base64", "data"]);
  if (base64) {
    const path = artifactPath({ kind, outDir, output, index, extension: DEFAULT_EXTENSIONS[kind] });
    await writeFile(path, Buffer.from(base64, "base64"));
    return { path };
  }

  return undefined;
}

async function downloadArtifact({ url, path, fetchImpl }) {
  const response = await fetchImpl(url, { headers: CLI_REQUEST_HEADERS });
  if (!response.ok) {
    throw new Error(`Failed to download artifact ${url}: HTTP ${response.status}`);
  }
  await writeFile(path, Buffer.from(await response.arrayBuffer()));
}

function extractItems(response) {
  if (Array.isArray(response?.data)) return response.data;
  if (Array.isArray(response?.artifacts)) return response.artifacts;
  if (Array.isArray(response?.content)) return response.content;
  if (Array.isArray(response?.candidates)) {
    return response.candidates.flatMap((candidate) => candidate.content?.parts ?? []);
  }
  if (typeof response?.temp_url === "string") return [{ url: response.temp_url }];
  if (typeof response?.metadata?.temp_url === "string") return [{ url: response.metadata.temp_url }];
  if (typeof response?.metadata?.url === "string") return [{ url: response.metadata.url }];
  if (typeof response?.url === "string") return [response];
  if (typeof response?.video_url?.url === "string") return [{ url: response.video_url.url }];
  if (typeof response?.video?.url === "string") return [{ url: response.video.url }];
  if (typeof response?.video?.temp_url === "string") return [{ url: response.video.temp_url }];
  return [];
}

function getString(item, keys) {
  for (const key of keys) {
    if (typeof item?.[key] === "string") return item[key];
    if (typeof item?.[key]?.url === "string") return item[key].url;
    if (typeof item?.inlineData?.[key] === "string") return item.inlineData[key];
    if (typeof item?.inline_data?.[key] === "string") return item.inline_data[key];
  }
  return undefined;
}

function parseDataUrl(value) {
  const match = /^data:([^;,]+);base64,(.+)$/s.exec(value);
  if (!match) throw new Error("Unsupported data URL artifact.");
  return {
    extension: MIME_EXTENSIONS[match[1]] ?? "bin",
    buffer: Buffer.from(match[2], "base64"),
  };
}

function artifactPath({ kind, outDir, output, index, extension }) {
  if (output) {
    if (index === 0) return output;
    const existingExtension = extname(output);
    const base = existingExtension ? output.slice(0, -existingExtension.length) : output;
    const suffix = String(index + 1).padStart(2, "0");
    return `${base}-${suffix}${existingExtension || `.${extension}`}`;
  }
  const number = String(index + 1).padStart(2, "0");
  return join(outDir, `${kind}-${number}.${extension}`);
}

async function nextArtifactIndex({ kind, outDir }) {
  const extension = DEFAULT_EXTENSIONS[kind] ?? "bin";
  const pattern = new RegExp(`^${escapeRegExp(kind)}-(\\d+)\\.${escapeRegExp(extension)}$`);
  let max = 0;
  try {
    for (const entry of await readdir(outDir)) {
      const match = pattern.exec(entry);
      if (!match) continue;
      max = Math.max(max, Number.parseInt(match[1], 10));
    }
  } catch {
    return 0;
  }
  return max;
}

function escapeRegExp(value) {
  return String(value).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}

# ===== file: src/cli.js =====
import { join } from "node:path";
import { DEFAULT_BASE_URL } from "./api.js";
import { nextArtifactPath, persistArtifacts } from "./artifacts.js";

const COMMANDS = new Set([
  "audio",
  "credits",
  "help",
  "image",
  "login",
  "models",
  "onboard",
  "logout",
  "auth",
  "status",
  "text",
  "version",
  "video",
]);

const GROUP_ACTIONS = new Set(["audio", "auth", "image", "text", "video"]);
const GLOBAL_OPTIONS = new Set(["api_key", "base_url", "console_url", "dry_run", "help", "json", "output", "out", "verbose"]);
const REPEATABLE_OPTIONS = new Set(["image", "image_url", "video_url"]);
const MEDIA_INPUT_OPTIONS = new Set(["file", "image", "image_url", "video_url", "first_frame", "first_frame_url", "last_frame", "last_frame_url"]);
const MAX_REFERENCE_IMAGES = 5;
const COMMAND_OPTIONS = {
  "audio generate": new Set(["model", "prompt", "similarity_boost", "stability", "style", "voice_id"]),
  "audio music": new Set(["music_length_ms", "prompt"]),
  "audio sfx": new Set(["duration", "prompt"]),
  "audio voices": new Set([]),
  "auth status": new Set([]),
  credits: new Set([]),
  help: new Set(["ai", "command"]),
  image: new Set([]),
  "image generate": new Set(["file", "image", "image_url", "model", "n", "prompt", "quality", "size"]),
  "image upload": new Set(["file"]),
  login: new Set(["console_url", "no_open", "open"]),
  logout: new Set([]),
  models: new Set(["type"]),
  onboard: new Set(["api_key"]),
  status: new Set([]),
  text: new Set([]),
  "text generate": new Set(["model", "prompt"]),
  version: new Set([]),
  video: new Set([]),
  "video generate": new Set(["aspect", "duration", "file", "first_frame", "first_frame_url", "fps", "generate_audio", "image", "image_url", "last_frame", "last_frame_url", "model", "prompt", "ratio", "resolution", "video_url"]),
  "video copy": new Set(["aspect", "depth_location", "depth_model", "depth_resolution", "duration", "fps", "frame_ratio", "generate_audio", "keep_depth", "model", "prompt", "ratio", "resolution", "source"]),
};

export function parseArgv(argv) {
  const [group, maybeAction, ...rest] = argv;
  if (!group) {
    return { group: "help", action: undefined, options: {} };
  }
  if (group === "--help" || group === "-h") {
    return { group: "help", action: undefined, options: {} };
  }
  if (group === "--version" || group === "-v") {
    return { group: "version", action: undefined, options: {} };
  }
  if (!COMMANDS.has(group)) {
    throw new Error(`Unknown command: ${group}`);
  }
  if (group === "help" && maybeAction && !maybeAction.startsWith("--")) {
    return validateCommandOptions({
      group: "help",
      action: undefined,
      options: { command: maybeAction, ...parseOptions(rest, repeatableOptionsFor("help")) },
    });
  }

  const hasAction = GROUP_ACTIONS.has(group);
  if (hasAction && isHelpToken(maybeAction)) {
    return { group, action: undefined, options: { help: true } };
  }
  if (!hasAction && isHelpToken(maybeAction)) {
    return { group, action: undefined, options: { help: true } };
  }
  const action = hasAction ? maybeAction : undefined;
  const optionTokens = hasAction ? rest : argv.slice(1);
  const hasHelpOption = optionTokens.some((token) => token === "--help" || token === "-h")
    || (optionTokens.length === 1 && optionTokens[0] === "help");
  if (hasHelpOption) {
    return validateCommandOptions({
      group,
      action,
      options: {
        ...parseOptions(optionTokens.filter((token) => token !== "help" && token !== "--help" && token !== "-h"), repeatableOptionsFor(group, action)),
        help: true,
      },
    });
  }

  return validateCommandOptions({
    group,
    action,
    options: parseOptions(optionTokens, repeatableOptionsFor(group, action)),
  });
}

function isHelpToken(token) {
  return token === "help" || token === "--help" || token === "-h";
}

function parseOptions(tokens, repeatableOptions = REPEATABLE_OPTIONS) {
  const options = {};
  const mediaInputs = [];
  for (let index = 0; index < tokens.length; index += 1) {
    const token = tokens[index];
    if (token === "-o") {
      const output = tokens[index + 1];
      if (!output || output.startsWith("-")) {
        throw new Error("Missing value for -o.");
      }
      options.output = output;
      index += 1;
      continue;
    }
    if (!token.startsWith("--")) {
      throw new Error(`Unexpected argument: ${token}`);
    }
    const name = token.slice(2).replaceAll("-", "_");
    const next = tokens[index + 1];
    if (!next || next.startsWith("--")) {
      options[name] = true;
      continue;
    }
    if (repeatableOptions.has(name)) {
      options[name] = [...asArray(options[name]), next];
    } else {
      options[name] = next;
    }
    if (MEDIA_INPUT_OPTIONS.has(name)) {
      mediaInputs.push({ name, value: next });
    }
    index += 1;
  }
  if (mediaInputs.length > 0) {
    Object.defineProperty(options, "__media_inputs", {
      value: mediaInputs,
      enumerable: false,
      writable: true,
    });
  }
  return options;
}

function repeatableOptionsFor(group, action) {
  if (group === "image" && action === "generate") {
    return new Set([...REPEATABLE_OPTIONS, "file"]);
  }
  if (group === "video" && action === "generate") {
    return new Set([...REPEATABLE_OPTIONS, "file"]);
  }
  if (group === "video" && action === "copy") {
    return REPEATABLE_OPTIONS;
  }
  return REPEATABLE_OPTIONS;
}

function asArray(value) {
  if (value === undefined) return [];
  return Array.isArray(value) ? value : [value];
}

function validateCommandOptions(command) {
  const key = command.action ? `${command.group} ${command.action}` : command.group;
  const allowed = COMMAND_OPTIONS[key] ?? new Set();
  for (const option of Object.keys(command.options)) {
    if (option.startsWith("_")) continue;
    if (GLOBAL_OPTIONS.has(option) || allowed.has(option)) continue;
    const flag = `--${option.replaceAll("_", "-")}`;
    const helpCommand = command.action
      ? `flatkey ${command.group} ${command.action} --help`
      : `flatkey ${command.group} --help`;
    throw new Error(`Unknown option ${flag} for flatkey ${key}. Run \`${helpCommand}\` to see supported options.`);
  }
  return command;
}

export async function main(argv, deps = {}) {
  const stdout = deps.stdout ?? process.stdout;
  const stderr = deps.stderr ?? process.stderr;
  const command = parseArgv(argv);
  if (command.options.help) {
    const result = await runCommand(command, { ...deps, stdout, stderr });
    stdout.write(`${formatHuman(result)}\n`);
    return;
  }
  if (command.group === "onboard") {
    const { writeConfig } = await import("./config.js");
    const configPath = await writeConfig({ apiKey: command.options.api_key, configDir: deps.configDir });
    stdout.write(`Saved Flatkey config: ${configPath}\n`);
    await maybeWriteUpdateNotice(command, { ...deps, stderr });
    return;
  }

  const result = await runCommand(command, { ...deps, stdout, stderr });
  if (result !== undefined) {
    stdout.write(
      command.options.json ? `${JSON.stringify(result)}\n` : `${formatHuman(result)}\n`,
    );
  }
  await maybeWriteUpdateNotice(command, { ...deps, stderr });
}

export async function runCommand(command, deps = {}) {
  const stdout = deps.stdout ?? process.stdout;
  const stderr = deps.stderr ?? process.stderr;

  if (command.group === "help") {
    const { getAiHelp, getCommandHelp, getHumanHelp } = await import("./help.js");
    if (command.options.command) return getCommandHelp(command.options.command);
    return command.options.ai ? getAiHelp() : getHumanHelp();
  }
  if (command.options.help) {
    const { getCommandHelp } = await import("./help.js");
    return getCommandHelp(command.group, command.action);
  }
  if (command.group === "version") {
    const version = await readPackageVersion();
    return command.options.json ? { version } : version;
  }

  if (command.group === "models") {
    return handleModels(command, { ...deps, stdout, stderr });
  }

  if (command.group === "login") {
    return handleLogin(command, { ...deps, stdout, stderr });
  }

  if (command.group === "logout") {
    return handleLogout(command, deps);
  }

  if (command.group === "auth") {
    if (command.action !== "status") {
      throw new Error(`Unknown action for auth: ${command.action}`);
    }
    return handleAuthStatus(command, deps);
  }

  if (command.group === "credits" || command.group === "status") {
    return handleUtility(command, { ...deps, stdout, stderr });
  }

  if (["image", "video", "audio", "text"].includes(command.group)) {
    if (command.group === "audio" && command.action === "voices") {
      return handleVoices(command, { ...deps, stdout, stderr });
    }
    const validAction = command.group === "audio"
      ? ["generate", "sfx", "music"].includes(command.action)
      : command.group === "image"
        ? ["generate", "upload"].includes(command.action)
        : command.group === "video"
          ? ["generate", "copy"].includes(command.action)
          : command.action === "generate";
    if (!validAction) {
      throw new Error(`Unknown action for ${command.group}: ${command.action}`);
    }
    if (command.group === "image" && command.action === "upload") {
      return handleImageUpload(command, { ...deps, stdout, stderr });
    }
    return handleGenerate(command, { ...deps, stdout, stderr });
  }

  throw new Error(`Unknown command: ${command.group}`);
}

async function handleLogin(command, deps) {
  const { ensureDeviceId, readConfig, resolveOrigins, writeAuthConfig } = await import("./config.js");
  const { DEFAULT_CONSOLE_URL, createDeviceAuthorization, pollDeviceAuthorization } = await import("./api.js");
  const deviceId = await ensureDeviceId({ configDir: deps.configDir });
  const version = await readPackageVersion();
  const { consoleOrigin } = await resolveOrigins({
    consoleUrl: command.options.console_url,
    env: deps.env ?? process.env,
    configDir: deps.configDir,
  });
  const requestOptions = {
    consoleUrl: consoleOrigin ?? DEFAULT_CONSOLE_URL,
    fetch: deps.fetch,
    verbose: command.options.verbose,
    verboseLog: verboseLogger(deps.stderr, command.options.verbose),
  };
  const authorization = await createDeviceAuthorization({
    deviceId,
    clientName: "flatkey-cli",
    clientVersion: version,
    ...requestOptions,
  });
  const data = authorization?.data ?? authorization;
  if (!data?.device_code || !data?.verification_uri_complete) {
    throw new Error("Flatkey login failed: missing device authorization response.");
  }

  if (!command.options.json) {
    deps.stdout?.write?.(`Open this URL to approve Flatkey CLI:\n${data.verification_uri_complete}\n\n`);
  }
  if (command.options.open !== false && command.options.no_open !== true) {
    await openBrowser(data.verification_uri_complete, deps);
  }

  const initialIntervalMs = Math.max(Number(data.interval ?? 5), 5) * 1000;
  const deadline = Date.now() + Math.max(Number(data.expires_in ?? 600), 1) * 1000;
  const startedAt = Date.now();
  while (Date.now() < deadline) {
    await delay(nextLoginPollDelay(startedAt, initialIntervalMs), deps);
    const poll = await pollDeviceAuthorization({
      deviceCode: data.device_code,
      ...requestOptions,
    });
    const pollData = poll?.data ?? poll;
    if (pollData?.status === "approved") {
      const account = accountFromAuthData(pollData);
      if (!pollData.api_key) {
        const saved = await readConfig(deps.configDir);
        if (typeof saved?.apiKey === "string" && saved.apiKey.trim() !== "") {
          const configPath = await writeAuthConfig({
            apiKey: saved.apiKey,
            auth: {
              deviceId,
              userId: pollData.user_id ?? saved.auth?.userId,
              tokenId: pollData.token_id ?? saved.auth?.tokenId,
              account: account ?? saved.auth?.account,
              loginAt: Math.floor(Date.now() / 1000),
            },
            configDir: deps.configDir,
          });
          return command.options.json
            ? {
              success: true,
              configPath,
              account: stripDisplayOnlyIds(account ?? saved.auth?.account),
              reusedConfig: true,
            }
            : `Flatkey CLI already authorized. Saved config: ${configPath}`;
        }
        throw new Error("Flatkey login was approved, but no API key was returned. The authorization may have already been consumed. Run `flatkey login` again.");
      }
      const configPath = await writeAuthConfig({
        apiKey: pollData.api_key,
        auth: {
          deviceId,
          userId: pollData.user_id,
          tokenId: pollData.token_id,
          account,
          loginAt: Math.floor(Date.now() / 1000),
        },
        configDir: deps.configDir,
      });
      return command.options.json
        ? {
          success: true,
          configPath,
          account: stripDisplayOnlyIds(account),
        }
        : `Flatkey CLI authorized. Saved config: ${configPath}`;
    }
    if (pollData?.status === "denied") {
      throw new Error("Flatkey login denied.");
    }
    if (pollData?.status === "expired") {
      throw new Error("Flatkey login expired. Run `flatkey login` again.");
    }
  }
  throw new Error("Flatkey login timed out. Run `flatkey login` again.");
}

function nextLoginPollDelay(startedAt, initialIntervalMs) {
  const elapsed = Date.now() - startedAt;
  const base = elapsed < 30_000
    ? initialIntervalMs
    : elapsed < 120_000
      ? Math.max(initialIntervalMs, 10_000)
      : Math.max(initialIntervalMs, 15_000);
  return base + Math.floor(Math.random() * 800);
}

async function delay(ms, deps = {}) {
  const sleep = deps.sleep ?? ((duration) => new Promise((resolve) => setTimeout(resolve, duration)));
  return sleep(ms);
}

async function openBrowser(url, deps = {}) {
  if (deps.openBrowser) return deps.openBrowser(url);
  const { spawn } = await import("node:child_process");
  const platform = deps.platform ?? process.platform;
  const command = platform === "darwin"
    ? "open"
    : platform === "win32"
      ? "cmd"
      : "xdg-open";
  const args = platform === "win32" ? ["/c", "start", "", url] : [url];
  try {
    const child = spawn(command, args, { stdio: "ignore", detached: true });
    child.unref();
  } catch {
    // Printed URL is enough when open is unavailable.
  }
}

function maskKey(key) {
  if (!key) return "";
  if (key.length <= 8) return `${key.slice(0, 2)}****${key.slice(-2)}`;
  return `${key.slice(0, 6)}...${key.slice(-4)}`;
}

function formatAuthStatus(status) {
  if (!status.authenticated) return "Not authenticated";
  return `Authenticated via ${status.source}: ${status.key}`;
}

function firstNonEmpty(...values) {
  return values.find((value) => typeof value === "string" && value.trim() !== "");
}

async function handleLogout(command, deps = {}) {
  const { clearSavedApiKey } = await import("./config.js");
  const configPath = await clearSavedApiKey({ configDir: deps.configDir });
  return command.options.json
    ? { success: true, configPath }
    : `Removed saved Flatkey API key from ${configPath}`;
}

async function handleAuthStatus(command, deps) {
  const { readConfig, resolveApiKey } = await import("./config.js");
  const saved = await readConfig(deps.configDir);
  let apiKey;
  try {
    apiKey = await resolveApiKey({
      apiKey: command.options.api_key,
      env: deps.env ?? process.env,
      configDir: deps.configDir,
    });
  } catch {
    apiKey = "";
  }
  const status = {
    authenticated: Boolean(apiKey),
    source: command.options.api_key
      ? "option"
      : saved?.apiKey
        ? "config"
        : (deps.env ?? process.env).FLATKEY_API_KEY
          ? "env"
          : "none",
    key: maskKey(apiKey),
    auth: saved?.auth ?? null,
  };
  return command.options.json ? status : formatAuthStatus(status);
}

async function handleImageUpload(command, deps) {
  const { basename } = await import("node:path");
  const { readFile } = await import("node:fs/promises");
  const { resolveApiKey, resolveOrigins } = await import("./config.js");
  const { DEFAULT_CONSOLE_URL, uploadTempMediaImage } = await import("./api.js");
  const file = command.options.file;
  if (typeof file !== "string" || file.trim() === "") {
    throw new Error("Missing --file value. Run `flatkey image upload --help` to see supported options.");
  }
  const media = mediaInfoFromPath(file);
  if (!media || media.kind !== "image") {
    throw new Error(`Unsupported image file type: ${file}`);
  }
  const apiKey = await resolveApiKey({
    apiKey: command.options.api_key,
    env: deps.env ?? process.env,
    configDir: deps.configDir,
  });
  const { consoleOrigin } = await resolveOrigins({
    consoleUrl: command.options.console_url,
    env: deps.env ?? process.env,
    configDir: deps.configDir,
  });
  const response = await uploadTempMediaImage({
    apiKey,
    baseUrl: consoleOrigin ?? DEFAULT_CONSOLE_URL,
    file: await readFile(await expandHomePath(file)),
    filename: basename(file),
    contentType: media.contentType,
    fetch: deps.fetch,
    verbose: command.options.verbose,
    verboseLog: verboseLogger(deps.stderr, command.options.verbose),
  });
  const data = response?.data ?? response;
  const signedUrl = extractUploadedMediaUrl(response);
  if (!signedUrl) {
    throw new Error("Image upload failed: missing signed_url.");
  }
  return {
    kind: "upload",
    url: signedUrl,
    objectKey: data?.object_key,
    expiresAt: data?.expires_at,
    expiresIn: data?.expires_in,
    response,
  };
}

async function handleGenerate(command, deps) {
  const { resolveApiKey, resolveOrigins } = await import("./config.js");
  const {
    generateAudio,
    generateAudioMusic,
    generateAudioSfx,
    generateImage,
    generateText,
    generateVideo,
    DEFAULT_CONSOLE_URL,
    getVideo,
    planAudioMusicRequest,
    planAudioRequest,
    planAudioSfxRequest,
    planImageRequest,
    planTextRequest,
    planVideoRequest,
    uploadTempMediaImage,
    uploadTempMediaVideo,
  } = await import("./api.js");
  const { createAnimation } = await import("./animation.js");
  const { prepareVideoCopy } = await import("./video-copy.js");
  const apiKey = command.options.dry_run
    ? (command.options.api_key ?? "FLATKEY_API_KEY")
    : await resolveApiKey({
        apiKey: command.options.api_key,
        env: deps.env ?? process.env,
        configDir: deps.configDir,
      });
  const { routerOrigin } = await resolveOrigins({
    baseUrl: command.options.base_url,
    consoleUrl: command.options.console_url,
    env: deps.env ?? process.env,
    configDir: deps.configDir,
  });
  const { consoleOrigin: tempMediaBaseUrl } = await resolveOrigins({
    consoleUrl: command.options.console_url,
    env: deps.env ?? process.env,
    configDir: deps.configDir,
  });
  const options = {
    ...command.options,
    apiKey,
    baseUrl: routerOrigin ?? DEFAULT_BASE_URL,
    tempMediaBaseUrl: tempMediaBaseUrl ?? DEFAULT_CONSOLE_URL,
    env: deps.env ?? process.env,
    fetch: deps.fetch,
    verboseLog: verboseLogger(deps.stderr, command.options.verbose),
  };
  if (Array.isArray(command.options.__media_inputs)) {
    options.__media_inputs = command.options.__media_inputs;
  }
  let videoCopy;
  if (command.group === "video" && command.action === "copy") {
    if (!command.options.source) {
      throw new Error("Missing --source value. Run `flatkey video copy --help` to see supported options.");
    }
    videoCopy = await (deps.prepareVideoCopy ?? prepareVideoCopy)(command.options, deps);
    options.prompt ??= "Recreate the reference video as faithfully as possible while following the supplied depth motion.";
    options.duration = videoCopy.duration;
    options.__media_inputs = [{
      name: "depth_video",
      value: videoCopy.depthPath,
      kind: "local",
      optionName: "file",
      role: "reference_video",
    }];
    options.__copy_reference_mode = "depth-video";
  }
  if (command.group === "image" || command.group === "video") {
    try {
      await prepareMediaInputs(command, options, {
        apiKey,
        baseUrl: options.baseUrl,
        tempMediaBaseUrl: tempMediaBaseUrl ?? DEFAULT_CONSOLE_URL,
        fetch: deps.fetch,
        verbose: command.options.verbose,
        verboseLog: verboseLogger(deps.stderr, command.options.verbose),
        uploadTempMediaImage,
        uploadTempMediaVideo,
      });
    } catch (error) {
      await videoCopy?.cleanup?.();
      throw error;
    }
  }
  if (command.group === "video" && command.action === "copy"
    && !options.__media_inputs?.some((entry) => entry.kind === "video")) {
    throw new Error("Video copy failed to prepare its depth-video reference.");
  }
  if (command.options.dry_run) {
    const request = command.group === "image"
      ? planImageRequest(options)
      : command.group === "video"
        ? planVideoRequest(options)
        : command.group === "audio"
          ? command.action === "sfx"
            ? planAudioSfxRequest(options)
            : command.action === "music"
              ? planAudioMusicRequest(options)
              : planAudioRequest(options)
          : planTextRequest(options);
    await videoCopy?.cleanup?.();
    return {
      dryRun: true,
      kind: command.group,
      request: redactRequest(request),
      videoCopy: scrubVideoCopy(videoCopy),
      copyReferenceMode: options.__copy_reference_mode,
    };
  }
  const animation = createAnimation({
    json: Boolean(command.options.json),
    stream: deps.stderr,
  });
  animation.start(command.group);
  try {
    let response;
    try {
      response = command.group === "image"
        ? await generateImage(options)
        : command.group === "video"
          ? await generateVideo(options)
          : command.group === "audio"
            ? command.action === "sfx"
              ? await generateAudioSfx(options)
              : command.action === "music"
                ? await generateAudioMusic(options)
                : await generateAudio(options)
            : await generateText(options);
      response = command.group === "video"
        ? await waitForVideoResult(response, { ...options, getVideo, sleep: deps.sleep })
        : response;
    } catch (error) {
      if (!videoCopy || options.__copy_reference_mode !== "depth-video" || !isDepthVideoFetchFailure(error)) {
        throw error;
      }
      options.__media_inputs = (videoCopy.referencePaths ?? []).map((value, index) => ({
        name: `depth_frame_${String(index + 1).padStart(2, "0")}`,
        value,
        kind: "local",
        optionName: "image",
        role: index === 0
          ? "first_frame"
          : index === (videoCopy.referencePaths.length - 1)
            ? "last_frame"
            : "reference_image",
      }));
      await prepareMediaInputs(command, options, {
        apiKey,
        baseUrl: options.baseUrl,
        tempMediaBaseUrl: tempMediaBaseUrl ?? DEFAULT_CONSOLE_URL,
        fetch: deps.fetch,
        verbose: command.options.verbose,
        verboseLog: verboseLogger(deps.stderr, command.options.verbose),
        uploadTempMediaImage,
        uploadTempMediaVideo,
      });
      options.__copy_reference_mode = "depth-keyframes-fallback";
      response = await generateVideo(options);
      response = await waitForVideoResult(response, { ...options, getVideo, sleep: deps.sleep });
    }
    const artifactResponse = response;
    if (command.group === "text") {
      const text = extractText(response);
      const output = await writeTextOutput(text, command.options.output);
      return { kind: command.group, text, output, response };
    }
    const outDir = command.options.out ?? "flatkey-output";
    const output = command.options.output
      ?? (command.group === "video" ? await nextArtifactPath({ kind: command.group, outDir }) : undefined);
    const artifacts = await persistArtifacts({
      kind: command.group,
      response: artifactResponse,
      outDir,
      output,
      fetch: deps.fetch,
    });
    return {
      kind: command.group,
      artifacts,
      response: scrubArtifactResponse(artifactResponse),
      ...(videoCopy ? { copyReferenceMode: options.__copy_reference_mode } : {}),
    };
  } finally {
    animation.stop();
    await videoCopy?.cleanup?.();
  }
}

async function prepareMediaInputs(command, options, deps) {
  const mediaInputs = orderedMediaInputs(command, options);
  if (mediaInputs.length === 0) return;
  assertMediaReferenceLimit(mediaInputs, command.group, options.model);

  const resolved = [];
  for (const input of mediaInputs) {
    if (input.kind === "local") {
      resolved.push(await uploadLocalMedia(input.value, command.group, deps, input.optionName ?? input.name));
    } else {
      resolved.push(await confirmRemoteMediaUrl(input.value, command.group, deps, input.name));
    }
  }
  options.__media_inputs = resolved;
}

function assertMediaReferenceLimit(mediaInputs, commandGroup, model) {
  const imageInputs = mediaInputs.filter((entry) => entry.kind !== "video");
  const videoInputs = mediaInputs.filter((entry) => entry.kind === "video");
  if (isSeedance25Model(model)) {
    if (imageInputs.length > 30) {
      throw new Error(`Too many reference images for flatkey ${commandGroup} generate with Seedance 2.5: maximum 30.`);
    }
    if (videoInputs.length > 10) {
      throw new Error(`Too many reference videos for flatkey ${commandGroup} generate with Seedance 2.5: maximum 10.`);
    }
    return;
  }
  if (imageInputs.length > MAX_REFERENCE_IMAGES) {
    throw new Error(`Too many reference images for flatkey ${commandGroup} generate: maximum ${MAX_REFERENCE_IMAGES}.`);
  }
}

function isSeedance25Model(model) {
  return String(model ?? "").toLowerCase().replaceAll(/[-_.]/g, "").includes("seedance25");
}

function orderedMediaInputs(command, options) {
  const mediaInputs = Array.isArray(options.__media_inputs) ? options.__media_inputs : [];
  if (mediaInputs.length > 0 && mediaInputs[0] && Object.prototype.hasOwnProperty.call(mediaInputs[0], "kind")) {
    return mediaInputs;
  }
  if (mediaInputs.length > 0) {
    return mediaInputs.map((entry) => ({
      name: entry.name,
      value: entry.value,
      kind: entry.name.endsWith("_url") ? "url" : "local",
    }));
  }

  const legacyInputs = [];
  const pushLocal = (name, value) => {
    for (const file of asArray(value)) {
      legacyInputs.push({ name, value: file, kind: "local" });
    }
  };
  const pushUrl = (name, value) => {
    for (const url of asArray(value)) {
      legacyInputs.push({ name, value: url, kind: "url" });
    }
  };

  pushLocal("file", options.file);
  pushLocal("image", options.image);
  pushUrl("image_url", options.image_url);
  if (command.group === "video") {
    pushUrl("video_url", options.video_url);
    pushLocal("first_frame", options.first_frame);
    pushUrl("first_frame_url", options.first_frame_url);
    pushLocal("last_frame", options.last_frame);
    pushUrl("last_frame_url", options.last_frame_url);
  }
  return legacyInputs;
}

async function uploadLocalMedia(file, commandGroup, deps, optionName) {
  const { basename } = await import("node:path");
  const { readFile } = await import("node:fs/promises");
  const media = mediaInfoFromPath(file);
  const allowedKinds = allowedMediaKindsForOption(commandGroup, optionName);
  if (!media || !allowedKinds.has(media.kind)) {
    throw new Error(`Unsupported --${optionName.replaceAll("_", "-")} file type for flatkey ${commandGroup} generate: ${file}`);
  }
  const uploader = media.kind === "video" ? deps.uploadTempMediaVideo : deps.uploadTempMediaImage;
  const response = await uploader({
    apiKey: deps.apiKey,
    baseUrl: deps.tempMediaBaseUrl ?? deps.baseUrl,
    file: await readFile(await expandHomePath(file)),
    filename: basename(file),
    contentType: media.contentType,
    fetch: deps.fetch,
    verbose: deps.verbose,
    verboseLog: deps.verboseLog,
  });
  const url = extractUploadedMediaUrl(response);
  if (!url) throw new Error(`Media upload failed: missing signed_url for ${file}`);
  return {
    name: optionName,
    value: url,
    kind: media.kind,
    role: mediaRoleFromOption(optionName, media.kind),
    mime: media.contentType,
  };
}

async function confirmRemoteMediaUrl(url, commandGroup, deps, optionName) {
  const fetchImpl = deps.fetch ?? fetch;
  const response = await fetchImpl(url, { method: "HEAD" });
  const media = mediaInfoFromMime(headerValue(response?.headers, "content-type"));
  const allowedKinds = allowedMediaKindsForOption(commandGroup, optionName);
  if (!media || !allowedKinds.has(media.kind)) {
    throw new Error(`Unsupported --${optionName.replaceAll("_", "-")} MIME type for flatkey ${commandGroup} generate: ${headerValue(response?.headers, "content-type") ?? "unknown"}`);
  }
  return {
    name: optionName,
    value: url,
    kind: media.kind,
    role: mediaRoleFromOption(optionName, media.kind),
    mime: media.contentType,
  };
}

function extractUploadedMediaUrl(response) {
  const data = response?.data ?? response;
  return data?.signed_url ?? data?.signedUrl ?? data?.url ?? response?.signed_url ?? response?.signedUrl ?? response?.url;
}

function mediaInfoFromPath(file) {
  const lower = String(file).toLowerCase();
  if (lower.endsWith(".jpg") || lower.endsWith(".jpeg")) return { kind: "image", contentType: "image/jpeg" };
  if (lower.endsWith(".png")) return { kind: "image", contentType: "image/png" };
  if (lower.endsWith(".webp")) return { kind: "image", contentType: "image/webp" };
  if (lower.endsWith(".mp4")) return { kind: "video", contentType: "video/mp4" };
  if (lower.endsWith(".mov")) return { kind: "video", contentType: "video/quicktime" };
  if (lower.endsWith(".bmp")) return { kind: "image", contentType: "image/bmp" };
  if (lower.endsWith(".tif") || lower.endsWith(".tiff")) return { kind: "image", contentType: "image/tiff" };
  if (lower.endsWith(".gif")) return { kind: "image", contentType: "image/gif" };
  if (lower.endsWith(".heic")) return { kind: "image", contentType: "image/heic" };
  if (lower.endsWith(".heif")) return { kind: "image", contentType: "image/heif" };
  return undefined;
}

function mediaInfoFromMime(contentType) {
  if (typeof contentType !== "string") return undefined;
  const lower = contentType.toLowerCase();
  if (lower.startsWith("image/jpeg")) return { kind: "image", contentType: "image/jpeg" };
  if (lower.startsWith("image/png")) return { kind: "image", contentType: "image/png" };
  if (lower.startsWith("image/webp")) return { kind: "image", contentType: "image/webp" };
  if (lower.startsWith("video/mp4")) return { kind: "video", contentType: "video/mp4" };
  if (lower.startsWith("video/quicktime")) return { kind: "video", contentType: "video/quicktime" };
  if (lower.startsWith("image/bmp")) return { kind: "image", contentType: "image/bmp" };
  if (lower.startsWith("image/tiff")) return { kind: "image", contentType: "image/tiff" };
  if (lower.startsWith("image/gif")) return { kind: "image", contentType: "image/gif" };
  if (lower.startsWith("image/heic")) return { kind: "image", contentType: "image/heic" };
  if (lower.startsWith("image/heif")) return { kind: "image", contentType: "image/heif" };
  return undefined;
}

function mediaRoleFromOption(optionName, kind) {
  if (optionName === "first_frame" || optionName === "first_frame_url") return "first_frame";
  if (optionName === "last_frame" || optionName === "last_frame_url") return "last_frame";
  if (kind === "video") return "reference_video";
  return "reference_image";
}

function allowedMediaKindsForOption(commandGroup, optionName) {
  if (commandGroup === "image") return new Set(["image"]);
  if (optionName === "file") return new Set(["image", "video"]);
  if (optionName === "video_url") return new Set(["video"]);
  if (optionName === "first_frame" || optionName === "first_frame_url" || optionName === "last_frame" || optionName === "last_frame_url" || optionName === "image" || optionName === "image_url") {
    return new Set(["image"]);
  }
  return new Set(["image"]);
}

function headerValue(headers, name) {
  if (!headers) return undefined;
  if (typeof headers.get === "function") {
    return headers.get(name) ?? headers.get(name.toLowerCase());
  }
  return headers[name] ?? headers[name.toLowerCase()];
}

async function waitForVideoResult(response, options) {
  if (hasArtifact(response)) return response;
  const taskId = videoTaskId(response);
  if (!taskId) return response;

  const timeoutMs = parsePositiveInteger(
    options.video_wait_timeout_ms ?? options.env?.FLATKEY_VIDEO_WAIT_TIMEOUT_MS,
    600_000,
  );
  const intervalMs = parsePositiveInteger(
    options.video_poll_interval_ms ?? options.env?.FLATKEY_VIDEO_POLL_INTERVAL_MS,
    5_000,
  );
  const deadline = Date.now() + timeoutMs;
  let last = response;

  while (Date.now() <= deadline) {
    last = await options.getVideo(options, taskId);
    if (hasArtifact(last)) return last;
    if (isVideoDone(last)) return withVideoContentFallback(last, options, taskId);
    if (isVideoFailed(last)) {
      const message = last?.error?.message ?? last?.message ?? `Video generation failed: ${taskId}`;
      throw new Error(message);
    }
    await delay(intervalMs, { sleep: options.sleep });
  }

  throw new Error(`Video task still processing after ${Math.round(timeoutMs / 1000)}s: ${taskId}`);
}

function withVideoContentFallback(response, options, taskId) {
  const baseUrl = String(options.baseUrl ?? "").replace(/\/$/, "");
  if (!baseUrl || !taskId) return response;
  return {
    ...response,
    metadata: {
      ...(response.metadata ?? {}),
      url: `${baseUrl}/v1/videos/${encodeURIComponent(taskId)}/content`,
    },
  };
}

function hasArtifact(response) {
  return Boolean(
    response?.metadata?.url
      || response?.metadata?.temp_url
      || response?.url
      || response?.temp_url
      || response?.video_url?.url
      || response?.video?.url
      || response?.video?.temp_url
      || response?.data?.some?.((item) => item?.url || item?.temp_url || item?.b64_json || item?.base64 || item?.data)
      || response?.artifacts?.some?.((item) => item?.url || item?.temp_url || item?.path)
      || response?.content?.some?.((item) => item?.url || item?.video_url?.url || item?.data_url || item?.b64_json || item?.base64 || item?.data),
  );
}

function videoTaskId(response) {
  return firstNonEmpty(response?.id, response?.task_id, response?.taskId, response?.data?.id, response?.data?.task_id);
}

function isVideoDone(response) {
  return ["completed", "done", "succeeded", "success"].includes(String(response?.status ?? "").toLowerCase());
}

function isVideoFailed(response) {
  return ["failed", "failure", "cancelled", "canceled"].includes(String(response?.status ?? "").toLowerCase())
    || Boolean(response?.error);
}

function parsePositiveInteger(value, fallback) {
  const parsed = Number.parseInt(value, 10);
  return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
}

function scrubArtifactResponse(value) {
  if (Array.isArray(value)) return value.map(scrubArtifactResponse);
  if (!value || typeof value !== "object") {
    if (typeof value === "string" && value.startsWith("data:")) return "<artifact omitted>";
    return value;
  }
  return Object.fromEntries(
    Object.entries(value).map(([key, entry]) => {
      if (["b64_json", "base64", "data"].includes(key) && typeof entry === "string") {
        return [key, "<artifact omitted>"];
      }
      if (["url", "data_url", "dataUrl"].includes(key)
        && typeof entry === "string"
        && entry.startsWith("data:")) {
        return [key, "<artifact omitted>"];
      }
      return [key, scrubArtifactResponse(entry)];
    }),
  );
}

function scrubVideoCopy(value) {
  if (!value) return undefined;
  return {
    source: value.source,
    depthPath: value.depthPath,
    referencePaths: value.referencePaths,
    duration: value.duration,
    sourceInfo: value.sourceInfo,
    helper: value.helper,
  };
}

function isDepthVideoFetchFailure(error) {
  const code = String(error?.code ?? "").toLowerCase();
  const message = String(error?.message ?? error).toLowerCase();
  return code.includes("fail_to_fetch")
    || code.includes("video_fetch")
    || message.includes("fail_to_fetch")
    || message.includes("failed to fetch")
    || message.includes("unable to fetch")
    || message.includes("video reference");
}

async function handleVoices(command, deps) {
  const { resolveApiKey, resolveOrigins } = await import("./config.js");
  const { getVoices } = await import("./api.js");
  const apiKey = await resolveApiKey({
    apiKey: command.options.api_key,
    env: deps.env ?? process.env,
    configDir: deps.configDir,
  });
  const { routerOrigin } = await resolveOrigins({
    baseUrl: command.options.base_url,
    env: deps.env ?? process.env,
    configDir: deps.configDir,
  });
  return getVoices({
    apiKey,
    baseUrl: routerOrigin,
    fetch: deps.fetch,
    verbose: command.options.verbose,
    verboseLog: verboseLogger(deps.stderr, command.options.verbose),
  });
}

function extractText(response) {
  return response?.choices?.[0]?.message?.content
    ?? response?.output_text
    ?? response?.text
    ?? "";
}

async function writeTextOutput(text, output) {
  if (!output) return undefined;
  output = await expandHomePath(output);
  const { mkdir, writeFile } = await import("node:fs/promises");
  const { dirname } = await import("node:path");
  await mkdir(dirname(output), { recursive: true });
  await writeFile(output, text);
  return output;
}

async function expandHomePath(path) {
  if (typeof path !== "string") return path;
  if (path !== "~" && !path.startsWith("~/")) return path;
  const { homedir } = await import("node:os");
  const { join } = await import("node:path");
  if (path === "~") return homedir();
  return join(homedir(), path.slice(2));
}

function redactRequest(request) {
  return {
    ...request,
    headers: Object.fromEntries(
      Object.entries(request.headers ?? {}).map(([key, value]) => [
        key,
        key.toLowerCase() === "authorization" ? "Bearer <redacted>" : value,
      ]),
    ),
  };
}

async function handleUtility(command, deps) {
  const { readConfig, resolveApiKey, resolveOrigins } = await import("./config.js");
  const saved = await readConfig(deps.configDir);
  const { getCredits, getStatus } = await import("./api.js");
  const apiKey = await resolveApiKey({
    apiKey: command.options.api_key,
    env: deps.env ?? process.env,
    configDir: deps.configDir,
  });
  const { consoleOrigin } = await resolveOrigins({
    baseUrl: command.options.base_url,
    env: deps.env ?? process.env,
    configDir: deps.configDir,
  });
  const options = {
    apiKey,
    baseUrl: consoleOrigin,
    fetch: deps.fetch,
    verbose: command.options.verbose,
    verboseLog: verboseLogger(deps.stderr, command.options.verbose),
  };
  if (command.group === "credits") return getCredits(options);

  const status = sanitizeStatusResponse(await getStatus(options));
  const account = effectiveAccountForStatus({ command, saved, apiKey });
  if (!account || !status || typeof status !== "object" || Array.isArray(status) || status.account !== undefined) {
    return command.options.json ? status : extractStatusDisplayFields(status);
  }
  const mergedStatus = sanitizeStatusResponse({ ...status, account });
  return command.options.json ? mergedStatus : extractStatusDisplayFields(mergedStatus);
}

function effectiveAccountForStatus({ command, saved, apiKey }) {
  if (command.options.api_key || !saved?.apiKey || saved.apiKey !== apiKey) return null;
  if (saved.auth?.account !== undefined) return saved.auth.account;
  return accountFromAuthData(saved.auth);
}

function accountFromAuthData(data) {
  if (!data || typeof data !== "object") return null;
  const email = data.account?.email ?? data.email ?? data.userEmail ?? data.user_email;
  const name = data.account?.name ?? data.name;
  const userId = data.account?.userId ?? data.account?.user_id ?? data.userId ?? data.user_id;
  if (email === undefined && name === undefined && userId === undefined) return null;
  return Object.fromEntries(
    Object.entries({
      email,
      name,
      userId,
    }).filter(([, value]) => value !== undefined && value !== null),
  );
}

function sanitizeStatusResponse(status) {
  if (!status || typeof status !== "object") return status;
  if (Array.isArray(status)) {
    return status.map((entry) => sanitizeStatusResponse(entry));
  }
  return Object.fromEntries(
    Object.entries(status)
      .filter(([key]) => !["userId", "user_id"].includes(key))
      .map(([key, value]) => [key, sanitizeStatusResponse(value)]),
  );
}

function stripDisplayOnlyIds(value) {
  if (!value || typeof value !== "object") return value;
  if (Array.isArray(value)) {
    return value.map((entry) => stripDisplayOnlyIds(entry));
  }
  return Object.fromEntries(
    Object.entries(value)
      .filter(([key]) => !["userId", "user_id", "tokenId", "token_id"].includes(key))
      .map(([key, nested]) => [key, stripDisplayOnlyIds(nested)]),
  );
}

function extractStatusDisplayFields(status) {
  if (!status || typeof status !== "object") return status;
  const email = status.email ?? status.account?.email ?? status.user?.email;
  const name = status.name ?? status.account?.name ?? status.user?.name;
  const result = {};
  if (email !== undefined) result.email = email;
  if (name !== undefined) result.name = name;
  return result;
}

async function handleModels(command, deps) {
  const { resolveApiKey, resolveOrigins } = await import("./config.js");
  const { getModels } = await import("./api.js");
  const { normalizeModels } = await import("./models.js");

  const apiKey = await resolveApiKey({
    apiKey: command.options.api_key,
    env: deps.env ?? process.env,
    configDir: deps.configDir,
  });
  const { consoleOrigin } = await resolveOrigins({
    baseUrl: command.options.base_url,
    env: deps.env ?? process.env,
    configDir: deps.configDir,
  });
  const response = await getModels({
    apiKey,
    baseUrl: consoleOrigin,
    fetch: deps.fetch,
    verbose: command.options.verbose,
    verboseLog: verboseLogger(deps.stderr, command.options.verbose),
  });
  return { models: normalizeModels(response, command.options.type) };
}

function verboseLogger(stream, enabled) {
  if (!enabled) return () => {};
  return (line) => {
    if (typeof line === "string") {
      stream?.write?.(`${line}\n`);
    }
  };
}

function formatHuman(result) {
  if (typeof result === "string") return result;
  if (!result || typeof result !== "object") return String(result);
  if (result.dryRun && result.request) return formatDryRun(result);
  if (result.kind === "upload") return formatUploadResult(result);
  if (result.kind) return formatGenerationResult(result);
  if (Array.isArray(result.models)) return formatModels(result.models);
  if (Array.isArray(result.voices)) return formatVoices(result.voices);
  if (typeof result.authenticated === "boolean") return formatAuthStatus(result);
  return formatKeyValues(result);
}

function formatDryRun(result) {
  const lines = [
    `Dry run: ${result.kind}`,
    `${result.request.method ?? "GET"} ${result.request.url}`,
  ];
  if (result.request.body !== undefined) {
    lines.push("Body:");
    lines.push(JSON.stringify(result.request.body, null, 2));
  }
  return lines.join("\n");
}

function formatUploadResult(result) {
  const lines = ["Image uploaded:"];
  if (result.url) lines.push(`URL: ${result.url}`);
  if (result.expiresIn) lines.push(`Expires in: ${result.expiresIn}s`);
  return lines.join("\n");
}

function formatGenerationResult(result) {
  if (result.kind === "text") {
    const lines = [result.text || "(empty text)"];
    if (result.output) lines.push(`Saved: ${result.output}`);
    return lines.join("\n");
  }
  const artifacts = Array.isArray(result.artifacts) ? result.artifacts : [];
  if (artifacts.length === 0) return `${titleCase(result.kind)} generated. No artifacts returned.`;
  const lines = [`${titleCase(result.kind)} generated:`];
  for (const artifact of artifacts) {
    if (artifact.path) lines.push(`- Saved: ${artifact.path}`);
    else if (artifact.url) lines.push(`- URL: ${artifact.url}`);
    else lines.push(`- ${JSON.stringify(artifact)}`);
  }
  return lines.join("\n");
}

function formatModels(models) {
  if (models.length === 0) return "No models available.";
  return [
    `Available models (${models.length}):`,
    formatTable(
      ["Model", "Type", "Source"],
      models.map((model) => [
        model.id,
        model.type ?? "",
        model.source ?? "",
      ]),
    ),
  ].join("\n");
}

function formatVoices(voices) {
  if (voices.length === 0) return "No voices available.";
  const lines = [`Available voices (${voices.length}):`];
  for (const voice of voices) {
    const id = voice.voice_id ?? voice.id;
    const name = voice.name ? `${voice.name} ` : "";
    lines.push(`- ${name}${id ? `(${id})` : ""}`.trim());
  }
  return lines.join("\n");
}

function formatKeyValues(result) {
  const entries = Object.entries(result);
  if (entries.length === 0) return "OK";
  const lines = entries
    .map(([key, value]) => `${humanLabel(key)}: ${formatScalar(value)}`)
  const warning = lowCreditWarning(result);
  if (warning) lines.push(warning);
  return lines.join("\n");
}

function lowCreditWarning(result) {
  const credits = extractCreditAmount(result);
  if (credits === undefined || credits >= 10) return "";
  return `Low credit warning: remaining credits are ${credits}. Top up soon.`;
}

function extractCreditAmount(result) {
  const creditKeys = new Set([
    "credit",
    "credits",
    "remaining",
    "balance",
    "total_available",
    "totalAvailable",
    "available_balance",
    "availableBalance",
  ]);
  const stack = [result];
  const seen = new Set();
  while (stack.length > 0) {
    const value = stack.shift();
    if (!value || typeof value !== "object" || seen.has(value)) continue;
    seen.add(value);
    for (const [key, entry] of Object.entries(value)) {
      if (creditKeys.has(key)) {
        const number = Number(entry);
        if (Number.isFinite(number)) return number;
      }
      if (entry && typeof entry === "object") stack.push(entry);
    }
  }
  return undefined;
}

function formatScalar(value) {
  if (value === null || value === undefined) return "";
  if (typeof value === "object") return JSON.stringify(value);
  return String(value);
}

function humanLabel(key) {
  return key
    .replaceAll("_", " ")
    .replace(/([a-z])([A-Z])/g, "$1 $2")
    .replace(/^./, (char) => char.toUpperCase());
}

function titleCase(value) {
  return String(value).replace(/^./, (char) => char.toUpperCase());
}

function formatTable(headers, rows) {
  const widths = headers.map((header, index) => Math.max(
    header.length,
    ...rows.map((row) => String(row[index] ?? "").length),
  ));
  const line = (cells) => cells
    .map((cell, index) => String(cell ?? "").padEnd(widths[index]))
    .join("  ")
    .trimEnd();
  return [
    line(headers),
    line(widths.map((width) => "-".repeat(width))),
    ...rows.map(line),
  ].join("\n");
}

async function readPackageVersion() {
  const { readFile } = await import("node:fs/promises");
  const packageUrl = new URL("../package.json", import.meta.url);
  return JSON.parse(await readFile(packageUrl, "utf8")).version;
}

async function maybeWriteUpdateNotice(command, deps = {}) {
  if (command.options.json || command.options.help || command.group === "help" || command.group === "version") {
    return;
  }
  try {
    const current = await readPackageVersion();
    const latest = await fetchLatestPackageVersion(deps);
    if (!latest || compareVersions(latest, current) <= 0) return;
    deps.stderr?.write?.([
      `\nFlatkey CLI update available: ${current} -> ${latest}`,
      "Upgrade: npm install -g @flatkey-ai/cli",
      "",
    ].join("\n"));
  } catch {
    // Update checks must never break normal CLI commands.
  }
}

async function fetchLatestPackageVersion(deps = {}) {
  const { CLI_REQUEST_HEADERS } = await import("./requestHeaders.js");
  const fetchImpl = deps.fetch ?? globalThis.fetch;
  if (typeof fetchImpl !== "function") return undefined;
  const response = await fetchImpl("https://registry.npmjs.org/@flatkey-ai%2fcli/latest", {
    headers: CLI_REQUEST_HEADERS,
    signal: typeof AbortSignal !== "undefined" && typeof AbortSignal.timeout === "function"
      ? AbortSignal.timeout(750)
      : undefined,
  });
  if (!response?.ok) return undefined;
  const body = await response.json();
  return typeof body?.version === "string" ? body.version : undefined;
}

function compareVersions(left, right) {
  const leftParts = parseVersionParts(left);
  const rightParts = parseVersionParts(right);
  for (let index = 0; index < Math.max(leftParts.length, rightParts.length); index += 1) {
    const difference = (leftParts[index] ?? 0) - (rightParts[index] ?? 0);
    if (difference !== 0) return difference;
  }
  return 0;
}

function parseVersionParts(version) {
  return String(version)
    .split("-", 1)[0]
    .split(".")
    .map((part) => Number.parseInt(part, 10))
    .map((part) => Number.isFinite(part) ? part : 0);
}

# ===== file: src/config.js =====
import { mkdir, readFile, writeFile, chmod } from "node:fs/promises";
import { randomUUID } from "node:crypto";
import { homedir } from "node:os";
import { join } from "node:path";

export const ROUTER_ORIGIN_KEY = "routerOrigin";
export const CONSOLE_ORIGIN_KEY = "consoleOrigin";

export function getDefaultConfigDir() {
  return join(homedir(), ".config", "flatkey");
}

export function getConfigPath(configDir = getDefaultConfigDir()) {
  return join(configDir, "config.json");
}

export async function resolveApiKey({
  apiKey,
  env = process.env,
  configDir = getDefaultConfigDir(),
} = {}) {
  if (apiKey) return apiKey;

  const saved = await readSavedConfig(configDir);
  if (saved?.apiKey) return saved.apiKey;
  if (env.FLATKEY_API_KEY) return env.FLATKEY_API_KEY;

  throw new Error(
    "Missing or invalid Flatkey API key. Run `flatkey login`, or create a key at https://console.flatkey.ai/keys and run `flatkey onboard --api-key <key>`.",
  );
}

export async function resolveOrigins({
  baseUrl,
  consoleUrl,
  env = process.env,
  configDir = getDefaultConfigDir(),
} = {}) {
  const saved = await readSavedConfig(configDir);
  return {
    routerOrigin: firstNonEmpty(
      baseUrl,
      saved?.[ROUTER_ORIGIN_KEY],
      saved?.ROUTER_ORIGIN,
      env.ROUTER_ORIGIN,
    ),
    consoleOrigin: firstNonEmpty(
      consoleUrl,
      baseUrl,
      saved?.[CONSOLE_ORIGIN_KEY],
      saved?.CONSOLE_ORIGIN,
      env.CONSOLE_ORIGIN,
    ),
  };
}

export async function writeConfig({ apiKey, configDir = getDefaultConfigDir() }) {
  if (typeof apiKey !== "string" || apiKey.trim() === "") {
    throw new Error("Missing --api-key value. Create a key at https://console.flatkey.ai/keys, then run `flatkey onboard --api-key <key>`.");
  }

  await mkdir(configDir, { recursive: true });
  const configPath = getConfigPath(configDir);
  const saved = await readSavedConfig(configDir) ?? {};
  await writeFile(configPath, `${JSON.stringify({ ...saved, apiKey }, null, 2)}\n`, {
    mode: 0o600,
  });
  try {
    await chmod(configPath, 0o600);
  } catch (error) {
    if (process.platform !== "win32") throw error;
  }
  return configPath;
}

export async function writeAuthConfig({
  apiKey,
  auth,
  configDir = getDefaultConfigDir(),
}) {
  if (typeof apiKey !== "string" || apiKey.trim() === "") {
    throw new Error("Missing API key from Flatkey login response.");
  }
  const saved = await readSavedConfig(configDir) ?? {};
  const next = {
    ...saved,
    apiKey,
    auth: {
      ...(saved.auth ?? {}),
      ...auth,
      type: "device",
    },
  };
  await mkdir(configDir, { recursive: true });
  const configPath = getConfigPath(configDir);
  await writeFile(configPath, `${JSON.stringify(next, null, 2)}\n`, {
    mode: 0o600,
  });
  try {
    await chmod(configPath, 0o600);
  } catch (error) {
    if (process.platform !== "win32") throw error;
  }
  return configPath;
}

export async function ensureDeviceId({ configDir = getDefaultConfigDir() } = {}) {
  const saved = await readSavedConfig(configDir);
  if (typeof saved?.auth?.deviceId === "string" && saved.auth.deviceId) {
    return saved.auth.deviceId;
  }
  return randomUUID();
}

export async function clearSavedApiKey({ configDir = getDefaultConfigDir() } = {}) {
  const saved = await readSavedConfig(configDir);
  if (!saved) return getConfigPath(configDir);
  const next = { ...saved };
  delete next.apiKey;
  await mkdir(configDir, { recursive: true });
  const configPath = getConfigPath(configDir);
  await writeFile(configPath, `${JSON.stringify(next, null, 2)}\n`, {
    mode: 0o600,
  });
  return configPath;
}

export async function readConfig(configDir = getDefaultConfigDir()) {
  return readSavedConfig(configDir);
}

async function readSavedConfig(configDir) {
  try {
    return JSON.parse(await readFile(getConfigPath(configDir), "utf8"));
  } catch (error) {
    if (error.code === "ENOENT") return undefined;
    throw error;
  }
}

function firstNonEmpty(...values) {
  return values.find((value) => typeof value === "string" && value.trim() !== "");
}

# ===== file: src/help.js =====
export function getAiHelp() {
  return `Flatkey CLI protocol for agents

Setup:
- Prefer browser auth: flatkey login
- Or env: FLATKEY_API_KEY=<key>
- Create a key at https://console.flatkey.ai/keys
- Or save key: flatkey onboard --api-key <key>
- Use --json for machine-readable output.

JSON mode:
- stdout contains only JSON.
- stderr contains JSON errors on failure.
- ASCII animation and human logs are disabled.

Commands:
- flatkey image generate --prompt "<prompt>" --json [--model <model>] [--file <path>] [--image-url <url>] [--output image.png]
- flatkey video generate --prompt "<prompt>" --json [--model seedance2] [--file <path>] [--image-url <url>] [--video-url <url>] [--ratio 16:9] [--resolution 720p] [--output video.mp4]
- flatkey video copy --source input.mp4 --json [--model seedance2] [--frame-ratio 80] [--depth-resolution 480p] [--output video.mp4]
- flatkey audio generate --prompt "<text>" --json [--voice-id <voice_id>] [--model eleven_multilingual_v2] [--output speech.mp3]
- flatkey audio sfx --prompt "<sound>" --json [--duration <seconds>] [--output sfx.mp3]
- flatkey audio music --prompt "<music prompt>" --json [--music-length-ms <ms>] [--output music.mp3]
- flatkey audio voices --json
- flatkey text generate --prompt "<prompt>" --json [--model gpt-5.5] [--output text.txt]
- flatkey credits --json
- flatkey status --json
- flatkey models --json [--type image|video|audio|text]
- flatkey login [--no-open] [--console-url <url>]
- flatkey logout
- flatkey auth status --json
- flatkey help --ai

Environment:
- FLATKEY_API_KEY: Flatkey API key.
- ROUTER_ORIGIN: Override generation router origin, e.g. staging router.
- CONSOLE_ORIGIN: Override console API origin, e.g. staging console.
- Default router: https://router.flatkey.ai

Recovery:
- Missing key: create one at https://console.flatkey.ai/keys, then run flatkey onboard --api-key <key> or set FLATKEY_API_KEY.
- Unknown model: run flatkey models --json, then retry with a listed model id.
- Unknown voice: run flatkey audio voices --json, then retry with a listed voice_id.
- API failure: inspect stderr JSON or HTTP message, then retry only after fixing request or credits.
`;
}

export function getHumanHelp() {
  return `Usage: flatkey <command> [options]

Commands:
  login                         Authorize CLI in browser
  logout                        Remove saved Flatkey API key
  auth status                    Show saved auth state
  onboard --api-key <key>        Save Flatkey API key from https://console.flatkey.ai/keys
  image generate --prompt <txt>  Generate image
  image upload --file <path>     Upload local image and return a temporary URL
  video generate --prompt <txt>  Generate video
  video copy --source <mp4>       Recreate a 5-15s video from Depth Anything V2 motion
  audio generate --prompt <txt>  Generate speech with ElevenLabs voices
  audio sfx --prompt <txt>       Generate sound effects
  audio music --prompt <txt>     Generate music
  audio voices                   List available voices
  text generate --prompt <txt>   Generate text
  credits                        Show remaining credits
  status                         Show usage/status
  models                         List available models
  help --ai                      Print agent-focused usage guide

Global options:
  --json                         Print machine-readable JSON
  --file <path>                   Attach local media input
  --image-url <url>               Add remote image input, repeatable
  --video-url <url>               Add remote video input, repeatable
  --output, -o <file>             Write generated output to a local file
  --verbose                      Print request/response logs to stderr
  --base-url <url>               Override Flatkey router URL

Environment:
  ROUTER_ORIGIN                  Override generation router origin
  CONSOLE_ORIGIN                 Override console API origin
  --console-url <url>            Override Flatkey console URL for login

Video options:
  --ratio <value>                 16:9, 9:16, 4:3, 3:4, 21:9, 1:1, or adaptive
  --resolution <value>            480p, 720p, or 1080p
`;
}

const COMMAND_HELP = {
  audio: `Usage: flatkey audio <action> [options]

Actions:
  generate --prompt <txt>        Generate speech
  sfx --prompt <txt>             Generate sound effects
  music --prompt <txt>           Generate music
  voices                         List available voices

Options:
  --json                         Print machine-readable JSON
  --output, -o <file>             Write generated output to a local file
  --model <model>                Override model id
  --voice-id <voice_id>           Voice id for speech generation
  --duration <seconds>            Duration for sound effects
  --music-length-ms <ms>          Music length in milliseconds
  --help                         Show audio help`,
  "audio generate": `Usage: flatkey audio generate --prompt <txt> [options]

Options:
  --voice-id <voice_id>           Voice id
  --model <model>                Model id, default eleven_multilingual_v2
  --stability <0..1>              Voice stability
  --similarity-boost <0..1>       Voice similarity boost
  --style <0..1>                 Voice style
  --output, -o <file>             Write speech file
  --json                         Print machine-readable JSON`,
  "audio music": `Usage: flatkey audio music --prompt <txt> [options]

Options:
  --music-length-ms <ms>          Music length in milliseconds
  --output, -o <file>             Write music file
  --json                         Print machine-readable JSON`,
  "audio sfx": `Usage: flatkey audio sfx --prompt <txt> [options]

Options:
  --duration <seconds>            Sound effect duration
  --output, -o <file>             Write sound effect file
  --json                         Print machine-readable JSON`,
  "audio voices": `Usage: flatkey audio voices [options]

Options:
  --json                         Print machine-readable JSON`,
  credits: `Usage: flatkey credits [options]

Options:
  --json                         Print machine-readable JSON`,
  auth: `Usage: flatkey auth <action> [options]

Actions:
  status                         Show saved auth state

Options:
  --json                         Print machine-readable JSON`,
  "auth status": `Usage: flatkey auth status [options]

Options:
  --json                         Print machine-readable JSON`,
  help: `Usage: flatkey help [command] [options]

Options:
  --ai                           Print agent-focused usage guide`,
  image: `Usage: flatkey image <command> [options]

Commands:
  generate --prompt <txt>        Generate image
  upload --file <path>           Upload local image and return a temporary URL

Options:
  --json                         Print machine-readable JSON`,
  "image upload": `Usage: flatkey image upload --file <path> [options]

Options:
  --file <path>                  Local image file to upload
  --json                         Print machine-readable JSON`,
  "image generate": `Usage: flatkey image generate --prompt <txt> [options]

Options:
  --model <model>                Model id
  --size <size>                  Image size for OpenAI-style image models
  --quality <quality>             Image quality for supported models
  --n <count>                    Number of images for supported models
  --file <path>                  Local image input, repeatable
  --image-url <url>               Remote image input, repeatable
  --output, -o <file>             Write image file
  --json                         Print machine-readable JSON`,
  models: `Usage: flatkey models [options]

Options:
  --type <type>                  Filter: image, video, audio, or text
  --json                         Print machine-readable JSON`,
  login: `Usage: flatkey login [options]

Options:
  --no-open                      Print approval URL without opening a browser
  --console-url <url>            Override Flatkey console URL
  --json                         Print machine-readable JSON`,
  logout: `Usage: flatkey logout [options]

Options:
  --json                         Print machine-readable JSON`,
  onboard: `Usage: flatkey onboard --api-key <key>

Create a Flatkey API key first:
  https://console.flatkey.ai/keys

Options:
  --api-key <key>                Flatkey API key to save`,
  status: `Usage: flatkey status [options]

Options:
  --json                         Print machine-readable JSON`,
  text: `Usage: flatkey text generate --prompt <txt> [options]

Options:
  --model <model>                Model id, default gpt-5.5
  --output, -o <file>             Write text file
  --json                         Print machine-readable JSON`,
  "text generate": `Usage: flatkey text generate --prompt <txt> [options]

Options:
  --model <model>                Model id, default gpt-5.5
  --output, -o <file>             Write text file
  --json                         Print machine-readable JSON`,
  version: `Usage: flatkey version [options]

Aliases:
  flatkey --version
  flatkey -v

Options:
  --json                         Print machine-readable JSON`,
  video: `Usage: flatkey video <command> [options]

Commands:
  generate --prompt <txt>        Generate video
  copy --source <mp4>            Recreate a 5-15s video from local depth motion

Options:
  --model <model>                Model id, default seedance-2.0-pro
  --duration <seconds>            Video duration
  --ratio <value>                 16:9, 9:16, 4:3, 3:4, 21:9, 1:1, or adaptive
  --resolution <value>            480p, 720p, or 1080p
  --generate-audio <true|false>   Generate audio, default true
  --output, -o <file>             Write video file
  --json                         Print machine-readable JSON`,
  "video copy": `Usage: flatkey video copy --source <mp4> [options]

Options:
  --source <mp4>                  Local source video, must be 5-15 seconds
  --frame-ratio <20..100>         Percent of frames kept for depth, default 100
  --depth-resolution <value>      original, 480p, or 320p; default 480p
  --depth-location <dir>          Directory for temporary depth video files
  --keep-depth                    Keep generated depth video and reference frames
  --model <model>                Model id, default seedance-2.0-pro
  --prompt <txt>                 Prompt override for copy generation
  --duration <seconds>            Must match source duration, 5-15 seconds
  --ratio <value>                 16:9, 9:16, 4:3, 3:4, 21:9, or 1:1
  --resolution <value>            480p, 720p, or 1080p
  --generate-audio <true|false>   Generate audio, default true
  --fps <fps>                    Frames per second
  --output, -o <file>             Write video file
  --json                         Print machine-readable JSON`,
  "video generate": `Usage: flatkey video generate --prompt <txt> [options]

Options:
  --model <model>                Model id, default seedance-2.0-pro
  --duration <seconds>            Video duration
  --ratio <value>                 16:9, 9:16, 4:3, 3:4, 21:9, or 1:1
  --resolution <value>            480p, 720p, or 1080p
  --generate-audio <true|false>   Generate audio, default true
  --image <file>                  Upload local reference image, repeatable
  --image-url <url>               Add reference image URL, repeatable
  --file <path>                   Local image or video input, repeatable
  --first-frame <file>            Upload local first frame image
  --video-url <url>               Add reference video URL, repeatable; Seedance 2.5 supports up to 10
  --first-frame-url <url>         Add first frame image URL
  --last-frame <file>             Upload local last frame image
  --last-frame-url <url>          Add last frame image URL
  --fps <fps>                    Frames per second
  --output, -o <file>             Write video file
  --json                         Print machine-readable JSON`,
};

export function getCommandHelp(group, action) {
  const key = action ? `${group} ${action}` : group;
  const help = COMMAND_HELP[key];
  if (!help) {
    throw new Error(`Unknown help topic: ${key}`);
  }
  return help;
}

# ===== file: src/models.js =====
export function normalizeModels(response, type) {
  const rawModels = Array.isArray(response?.data)
    ? response.data
    : Array.isArray(response?.models)
      ? response.models
      : [];

  return rawModels
    .map((model) => ({
      id: model.id,
      type: model.type ?? inferType(model),
      source: "remote",
    }))
    .filter((model) => model.id && model.type)
    .filter((model) => !type || model.type === type);
}

function inferType(model) {
  if (model.capabilities?.includes("video")) return "video";
  if (model.capabilities?.includes("audio")) return "audio";
  if (model.capabilities?.includes("image")) return "image";
  if (model.capabilities?.includes("text")) return "text";
  if (/image|nano-banana/i.test(model.id)) return "image";
  if (/seedance|veo|sora|video/i.test(model.id)) return "video";
  if (/tts|audio|voice|speech/i.test(model.id)) return "audio";
  if (model.object === "model") return "text";
  return undefined;
}

# ===== file: src/requestHeaders.js =====
export const CLI_REQUEST_HEADERS = {
  "x-flatkey-client": "cli",
};

export function withCliRequestHeaders(headers = {}) {
  return {
    ...headers,
    ...CLI_REQUEST_HEADERS,
  };
}

# ===== file: src/video-copy.js =====
import { access, mkdir, rm } from "node:fs/promises";
import { homedir, tmpdir } from "node:os";
import { join } from "node:path";
import { spawn } from "node:child_process";

export const MIN_COPY_DURATION_SECONDS = 5;
export const MAX_COPY_DURATION_SECONDS = 15;
export const DEFAULT_FRAME_RATIO = 100;
export const DEFAULT_DEPTH_RESOLUTION = "480p";

export async function prepareVideoCopy(options, deps = {}) {
  const source = await expandHomePath(options.source);
  const sourceInfo = await inspectVideo(source, deps);
  const duration = sourceInfo.duration;
  validateCopyDuration(duration, "source video");

  const requestedDuration = options.duration === undefined
    ? duration
    : parseDuration(options.duration, "--duration");
  validateCopyDuration(requestedDuration, "--duration");
  if (Math.abs(requestedDuration - duration) > 0.01) {
    throw new Error(
      `--duration must match the source video duration (${formatSeconds(duration)}s); time stretching is not supported by video copy.`,
    );
  }

  const depthRoot = await resolveDepthLocation(options.depth_location, deps);
  const workDir = join(depthRoot, `copy-${Date.now()}-${Math.random().toString(16).slice(2)}`);
  await mkdir(workDir, { recursive: true });
  const depthPath = join(workDir, "depth.mp4");
  let helperResult;
  try {
    helperResult = await runDepthHelper({
      source,
      output: depthPath,
      frameRatio: parseFrameRatio(options.frame_ratio),
      resolution: parseDepthResolution(options.depth_resolution),
      model: options.depth_model,
      workDir,
    }, deps);
  } catch (error) {
    if (!options.keep_depth) await rm(workDir, { recursive: true, force: true });
    throw error;
  }
  let referencePaths;
  try {
    referencePaths = await (deps.extractReferenceFrames ?? extractReferenceFrames)({
      source: helperResult.output ?? depthPath,
      outputDir: workDir,
      duration,
      ffmpegPath: deps.ffmpegPath,
      env: deps.env,
    }, deps);
  } catch (error) {
    if (!options.keep_depth) await rm(workDir, { recursive: true, force: true });
    throw error;
  }

  return {
    source,
    depthPath: helperResult.output ?? depthPath,
    referencePaths,
    workDir,
    duration: requestedDuration,
    sourceInfo,
    helper: helperResult,
    cleanup: async () => {
      if (!options.keep_depth) {
        await rm(workDir, { recursive: true, force: true });
      }
    },
  };
}

export function validateCopyDuration(value, label = "duration") {
  const duration = parseDuration(value, label);
  if (duration < MIN_COPY_DURATION_SECONDS || duration > MAX_COPY_DURATION_SECONDS) {
    throw new Error(
      `${label} must be between ${MIN_COPY_DURATION_SECONDS} and ${MAX_COPY_DURATION_SECONDS} seconds; received ${formatSeconds(duration)}s.`,
    );
  }
  return duration;
}

export function parseDuration(value, label = "duration") {
  const duration = Number(value);
  if (!Number.isFinite(duration) || duration <= 0) {
    throw new Error(`${label} must be a positive number of seconds.`);