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

// Derived from the canonical workspace list so retiring a bootstrap file cannot
// leave the Control UI advertising a file the runtime no longer reads.
// IDENTITY.md is excluded: it is a parsed record that `agents.update` rewrites via
// mergeIdentityMarkdownContent, so a second freeform editor would clobber fields
// (Creature/Vibe, unfilled placeholders) that the identity form round-trips.
// It stays writable through agents.files.set for clients that want raw access.
const CORE_FILE_NAMES = WORKSPACE_BOOTSTRAP_FILENAMES.filter(
  (name) => name !== DEFAULT_IDENTITY_FILENAME,
);
const CORE_FILE_NAMES_POST_ONBOARDING = CORE_FILE_NAMES.filter(
  (name) => name !== DEFAULT_BOOTSTRAP_FILENAME,
);

const agentsHandlerDeps = {
  root,
  isWorkspaceSetupCompleted,
};

export const testing = {
  setDepsForTests(
    overrides: Partial<{
      root: typeof root;
      isWorkspaceSetupCompleted: typeof isWorkspaceSetupCompleted;
    }>,
  ) {
    if (overrides.isWorkspaceSetupCompleted) {
      agentsHandlerDeps.isWorkspaceSetupCompleted = overrides.isWorkspaceSetupCompleted;
    }
    if (overrides.root) {
      agentsHandlerDeps.root = overrides.root;
    }
  },
  resetDepsForTests() {
    agentsHandlerDeps.root = root;
    agentsHandlerDeps.isWorkspaceSetupCompleted = isWorkspaceSetupCompleted;
  },
};

// Writes stay capped to canonical workspace files, and deliberately remain wider
// than the listed core files: IDENTITY.md is not offered as an editor tab but is
// still writable for clients that manage it directly.
const ALLOWED_FILE_NAMES = new Set<string>(WORKSPACE_BOOTSTRAP_FILENAMES);

function resolveAgentWorkspaceFileOrRespondError(
  params: Record<string, unknown>,
  respond: RespondFn,
  cfg: OpenClawConfig,
): {
  cfg: OpenClawConfig;
  agentId: string;
  workspaceDir: string;
  name: string;
} | null {
  const rawAgentId = params.agentId;
  const agentId = resolveAgentIdOrError(
    typeof rawAgentId === "string" || typeof rawAgentId === "number" ? String(rawAgentId) : "",
    cfg,
  );
  if (!agentId) {
    respondAgentNotFound(respond, String(rawAgentId));
    return null;
  }
  const rawName = params.name;
  const name = (
    typeof rawName === "string" || typeof rawName === "number" ? String(rawName) : ""
  ).trim();
  if (!ALLOWED_FILE_NAMES.has(name)) {
    respond(false, undefined, errorShape(ErrorCodes.INVALID_REQUEST, `unsupported file "${name}"`));
    return null;
  }
  const workspaceDir = resolveAgentWorkspaceDir(cfg, agentId);
  return { cfg, agentId, workspaceDir, name };
}

type FileMeta = {
  size: number;
  updatedAtMs: number;
};

type WorkspaceRoot = Awaited<ReturnType<typeof root>>;

function isRegularWorkspaceFileStat(stat: {
  isFile: boolean | (() => boolean);
  isSymbolicLink: boolean | (() => boolean);
  nlink: number;
}): boolean {
  const isFile = typeof stat.isFile === "function" ? stat.isFile() : stat.isFile;
  const isSymbolicLink =
    typeof stat.isSymbolicLink === "function" ? stat.isSymbolicLink() : stat.isSymbolicLink;
  // Reject links even after path-root containment so workspace reads cannot follow shared files.
  return isFile && !isSymbolicLink && stat.nlink <= 1;
}

function toWorkspaceFileMeta(
  stat: {
    size: number;
    mtimeMs: number;
  } & Parameters<typeof isRegularWorkspaceFileStat>[0],
): FileMeta | null {
  if (!isRegularWorkspaceFileStat(stat)) {
    return null;
  }
  return {
    size: stat.size,
    updatedAtMs: Math.floor(stat.mtimeMs),
  };
}

async function statWorkspaceFileSafely(
  workspaceRoot: WorkspaceRoot | null,
  workspaceDir: string,
  name: string,
): Promise<FileMeta | null> {
  try {
    const stat = workspaceRoot
      ? await workspaceRoot.stat(name)
      : await fs.lstat(path.join(workspaceDir, name));
    return toWorkspaceFileMeta(stat);
  } catch {
    if (!workspaceRoot) {
      return null;
    }
    try {
      // fs-safe roots can reject fixtures that are still valid regular files for listing metadata.
      const stat = await fs.lstat(path.join(workspaceDir, name));
      return toWorkspaceFileMeta(stat);
    } catch {
      return null;
    }
  }
}

async function openWorkspaceRootSafely(workspaceDir: string): Promise<WorkspaceRoot | null> {
  try {
    return await agentsHandlerDeps.root(workspaceDir);
  } catch {
    return null;
  }
}

async function listAgentFiles(workspaceDir: string, options?: { hideBootstrap?: boolean }) {
  const files: Array<{
    name: string;
    path: string;
    missing: boolean;
    expectedAbsent?: boolean;
    size?: number;
    updatedAtMs?: number;
  }> = [];

  const workspaceRoot = await openWorkspaceRootSafely(workspaceDir);
  if (!workspaceRoot) {
    // Keep the UI shape stable when the workspace path is missing or unsafe.
    const missingNames = options?.hideBootstrap ? CORE_FILE_NAMES_POST_ONBOARDING : CORE_FILE_NAMES;
    return missingNames.map((name) => ({
      name,
      path: path.join(workspaceDir, name),
      missing: true,
      expectedAbsent: isExpectedAbsentBootstrapFile(name),
    }));
  }

  const coreFileNames = options?.hideBootstrap ? CORE_FILE_NAMES_POST_ONBOARDING : CORE_FILE_NAMES;
  for (const name of coreFileNames) {
    const filePath = path.join(workspaceDir, name);
    const meta = await statWorkspaceFileSafely(workspaceRoot, workspaceDir, name);
    if (meta) {
      files.push({
        name,
        path: filePath,
        missing: false,
        size: meta.size,
        updatedAtMs: meta.updatedAtMs,
      });
    } else {
      files.push({
        name,
        path: filePath,
        missing: true,
        expectedAbsent: isExpectedAbsentBootstrapFile(name),
      });
    }
  }

  return files;
}

function resolveAgentIdOrError(agentIdRaw: string, cfg: OpenClawConfig) {
  const normalized = normalizeAgentIdStrict(agentIdRaw);
  if (!normalized.ok) {
    return null;
  }
  const agentId = normalized.value;
  const allowed = new Set(listAgentIds(cfg));
  if (!allowed.has(agentId)) {
    return null;
  }
  return agentId;
}

function respondAgentNotFound(respond: RespondFn, agentId: string): void {
  respond(false, undefined, errorShape(ErrorCodes.INVALID_REQUEST, `agent "${agentId}" not found`));
}

type AgentDeleteRemovedPath = NonNullable<AgentsDeleteResult["removed"]>[number];
type AgentDeleteFailedPath = NonNullable<AgentsDeleteResult["failed"]>[number];

type AgentDeletePathOutcome =
  | { removed: AgentDeleteRemovedPath }
  | { skipped: AgentDeleteFailedPath }
  | { failed: AgentDeleteFailedPath };

class AgentCleanupIdentityMismatchError extends Error {}
class AgentSharedAuthStoreOwnerError extends Error {}

function agentOwnsSharedAuthStore(cfg: OpenClawConfig, agentId: string): boolean {
  const agentDir = resolveAgentDir(cfg, agentId);
  return isSharedAuthStoreOwner({
    ownership: resolveSharedAuthStoreOwnership(),
    agentAuthDbPath: resolveAuthProfileDatabasePath(agentDir),
    sharedAuthDbPath: resolveSharedAuthStorePath(),
  });
}

function cleanupFailure(pathname: string, error: unknown): AgentDeletePathOutcome {
  const reason = error instanceof Error && error.message ? error.message : String(error);
  return { failed: { path: pathname, reason: reason || "unknown error" } };
}

function cleanupPathIdentity(stat: { dev?: number | bigint; ino?: number | bigint } | undefined) {
  if (
    (typeof stat?.dev !== "number" && typeof stat?.dev !== "bigint") ||
    (typeof stat.ino !== "number" && typeof stat.ino !== "bigint")
  ) {
    return null;
  }
  const dev = Number(stat.dev);
  const ino = Number(stat.ino);
  if (!Number.isSafeInteger(dev) || !Number.isSafeInteger(ino)) {
    throw new Error("cleanup path identity exceeds the safe integer range");
  }
  return { dev, ino };
}

async function statAgentCleanupPath(cleanupPath: AgentDeleteCleanupPath) {
  const parentPath = cleanupPath.parentPath;
  const parentRoot = await agentsHandlerDeps.root(parentPath, {
    hardlinks: "reject",
    symlinks: "reject",
  });
  if (path.resolve(parentRoot.rootReal) !== parentPath) {
    throw new FsSafeError("path-mismatch", "cleanup path parent changed before deletion");
  }
  const stat = await parentRoot.stat(path.basename(cleanupPath.trashPath));
  const isSymlink = stat.isSymbolicLink;
  if (isSymlink !== (cleanupPath.kind === "symlink")) {
    throw new AgentCleanupIdentityMismatchError(
      `cleanup path changed from ${cleanupPath.kind} before deletion`,
    );
  }
  if (stat.isFile && stat.nlink > 1) {
    throw new AgentCleanupIdentityMismatchError("hardlinked cleanup replacement preserved");
  }
  const identity = cleanupPathIdentity(stat);
  if (cleanupPath.preparedIdentity === null) {
    // The journal fence blocks legitimate claims on prepared-absent paths, so a
    // file that appeared here is leaked deleted-agent state (recreated WAL
    // sidecars, runtime home rewrites). Adopt it and sweep it; preserving it
    // cascades ancestor protection and finishes over a surviving tree.
    cleanupPath.preparedIdentity = identity;
  } else if (
    identity === null ||
    identity.dev !== cleanupPath.preparedIdentity.dev ||
    identity.ino !== cleanupPath.preparedIdentity.ino
  ) {
    throw new AgentCleanupIdentityMismatchError("cleanup path identity changed before deletion");
  }
}

async function removeAgentPath(
  cleanupPath: AgentDeleteCleanupPath,
  assertCurrent: () => void,
): Promise<AgentDeletePathOutcome> {
  const pathname = cleanupPath.path;
  const trashPath = cleanupPath.trashPath;
  try {
    await statAgentCleanupPath(cleanupPath);
  } catch (error) {
    if (error instanceof AgentCleanupIdentityMismatchError) {
      return { skipped: { path: pathname, reason: error.message } };
    }
    return isMissingPathError(error)
      ? { removed: { path: pathname, method: "missing" } }
      : cleanupFailure(pathname, error);
  }
  try {
    // fs-safe pins traversal and identity for validation; Trash has no fd-relative move API, so
    // replacement after this check and before its rename is the accepted residual race bound.
    assertCurrent();
    // statAgentCleanupPath verified the declared parent; fs-safe's default roots (home/tmp)
    // alone refuse every path of a volume-backed state dir. Keep those defaults so the
    // directory behind a workspace symlink stays fenced exactly as shipped, while the link
    // itself may always move (accepted edge: a link target beside its link is trashed too).
    await movePathToTrash(trashPath, {
      allowedRoots: [
        ...trashAllowedRoots(
          cleanupPath.sourcePaths,
          cleanupPath.kind === "symlink" ? cleanupPath.canonicalPath : undefined,
        ),
        os.homedir(),
        os.tmpdir(),
      ],
    });
    return { removed: { path: pathname, method: "trash" } };
  } catch (error) {
    if (!isMissingPathError(error)) {
      return cleanupFailure(pathname, error);
    }
    try {
      await statAgentCleanupPath(cleanupPath);
      return cleanupFailure(pathname, error);
    } catch (statError) {
      return isMissingPathError(statError)
        ? { removed: { path: pathname, method: "missing" } }
        : cleanupFailure(pathname, statError);
    }
  }
}

type AgentDeleteCleanupPath = {
  path: string;
  parentPath: string;
  canonicalPath: string;
  trashPath: string;
  trashCoversDescendants: boolean;
  kind: "target" | "symlink";
  preparedIdentity: { dev: number; ino: number } | null;
  done: boolean;
  note?: string;
  preparationError?: unknown;
  sourcePaths: string[];
};

async function resolveAgentDeleteCleanupTarget(pathname: string): Promise<string> {
  let candidate = path.resolve(pathname);
  const missingSuffix: string[] = [];
  while (true) {
    try {
      return path.resolve(await fs.realpath(candidate), ...missingSuffix);
    } catch (error) {
      if (!isMissingPathError(error)) {
        throw error;
      }
      let candidateStat: Awaited<ReturnType<typeof fs.lstat>> | undefined;
      try {
        candidateStat = await fs.lstat(candidate);
      } catch (statError) {
        if (!isMissingPathError(statError)) {
          throw statError;
        }
      }
      if (candidateStat?.isSymbolicLink()) {
        const linkTarget = await fs.readlink(candidate);
        const resolvedLinkTarget = await resolveAgentDeleteCleanupTarget(
          path.isAbsolute(linkTarget)
            ? linkTarget
            : path.resolve(path.dirname(candidate), linkTarget),
        );
        return path.resolve(resolvedLinkTarget, ...missingSuffix);
      }
      const parent = path.dirname(candidate);
      if (parent === candidate) {
        throw error;
      }
      missingSuffix.unshift(path.basename(candidate));
      candidate = parent;
    }
  }
}

async function prepareAgentDeleteCleanupPaths(
  paths: readonly string[],
  persistedPaths: readonly AgentDeletionJournalCleanupPath[] = [],
): Promise<AgentDeleteCleanupPath[]> {
  const uniquePaths = new Map<string, AgentDeleteCleanupPath>();
  const addPath = (candidate: AgentDeleteCleanupPath) => {
    const existing = uniquePaths.get(candidate.trashPath);
    if (!existing) {
      uniquePaths.set(candidate.trashPath, candidate);
      return;
    }
    existing.sourcePaths = [...new Set([...existing.sourcePaths, ...candidate.sourcePaths])];
    existing.done ||= candidate.done;
    existing.note ??= candidate.note;
    existing.preparationError ??= candidate.preparationError;
    if (candidate.kind === "target") {
      existing.kind = "target";
      existing.canonicalPath = candidate.canonicalPath;
      existing.parentPath = candidate.parentPath;
      existing.trashCoversDescendants ||= candidate.trashCoversDescendants;
    }
  };
  if (persistedPaths.length > 0) {
    for (const persistedPath of persistedPaths) {
      const journalPath = path.resolve(persistedPath.path);
      const trashPath = path.resolve(persistedPath.canonicalPath);
      addPath({
        path: journalPath,
        parentPath: path.resolve(persistedPath.parentPath),
        canonicalPath: normalizeAgentDirRegistryPath(trashPath),
        trashPath,
        trashCoversDescendants: persistedPath.coversDescendants,
        kind: persistedPath.kind,
        preparedIdentity:
          persistedPath.dev === null || persistedPath.ino === null
            ? null
            : { dev: persistedPath.dev, ino: persistedPath.ino },
        done: persistedPath.done,
        note: persistedPath.note,
        sourcePaths: persistedPath.sourcePaths.map((sourcePath) => path.resolve(sourcePath)),
      });
    }
  }
  for (const pathname of paths) {
    const sourcePath = path.resolve(pathname);
    let sourceParentPath = path.dirname(sourcePath);
    let resolvedPath = sourcePath;
    let preparationError: unknown;
    try {
      resolvedPath = await resolveAgentDeleteCleanupTarget(pathname);
      sourceParentPath = await resolveAgentDeleteCleanupTarget(path.dirname(sourcePath));
    } catch (error) {
      preparationError = error;
    }
    let sourceStat: Awaited<ReturnType<typeof fs.lstat>> | undefined;
    try {
      sourceStat = await fs.lstat(pathname);
    } catch (error) {
      if (!isMissingPathError(error)) {
        preparationError ??= error;
      }
    }
    let targetStat = sourceStat;
    if (resolvedPath !== sourcePath) {
      try {
        targetStat = await fs.lstat(resolvedPath);
      } catch (error) {
        if (!isMissingPathError(error)) {
          preparationError ??= error;
        }
        targetStat = undefined;
      }
    }
    const canonicalPath = normalizeAgentDirRegistryPath(resolvedPath);
    let trashCoversDescendants = false;
    if (targetStat) {
      trashCoversDescendants = !targetStat.isSymbolicLink();
    }
    addPath({
      path: resolvedPath,
      parentPath: path.dirname(resolvedPath),
      canonicalPath,
      trashPath: resolvedPath,
      trashCoversDescendants,
      kind: "target",
      preparedIdentity: cleanupPathIdentity(targetStat),
      done: false,
      preparationError,
      sourcePaths: [sourcePath],
    });
    if (sourceStat?.isSymbolicLink() && sourcePath !== resolvedPath) {
      addPath({
        path: sourcePath,
        parentPath: sourceParentPath,
        canonicalPath,
        trashPath: path.join(sourceParentPath, path.basename(sourcePath)),
        trashCoversDescendants: false,
        kind: "symlink",
        preparedIdentity: cleanupPathIdentity(sourceStat),
        done: false,
        sourcePaths: [sourcePath],
      });
    }
  }
  const depth = (pathname: string) =>
    path.relative(path.parse(pathname).root, pathname).split(path.sep).filter(Boolean).length;
  const cleanupDepth = (cleanupPath: AgentDeleteCleanupPath) =>
    Math.max(
      depth(cleanupPath.canonicalPath),
      depth(cleanupPath.trashPath),
      ...cleanupPath.sourcePaths.map(depth),
    );
  const compareFallback = (left: AgentDeleteCleanupPath, right: AgentDeleteCleanupPath) => {
    if (left.kind !== right.kind) {
      return left.kind === "target" ? -1 : 1;
    }
    const depthDifference = cleanupDepth(right) - cleanupDepth(left);
    if (depthDifference !== 0) {
      return depthDifference;
    }
    const trashDepth = depth(right.trashPath) - depth(left.trashPath);
    return trashDepth || left.trashPath.localeCompare(right.trashPath);
  };
  const mustPrecede = (left: AgentDeleteCleanupPath, right: AgentDeleteCleanupPath) => {
    if (left.kind !== right.kind) {
      return left.kind === "target";
    }
    if (isPathInside(right.trashPath, left.trashPath)) {
      return true;
    }
    if (isPathInside(left.trashPath, right.trashPath)) {
      return false;
    }
    const rightRoots = [right.trashPath, ...right.sourcePaths];
    return left.sourcePaths.some((leftSource) =>
      rightRoots.some((rightRoot) => isPathInside(rightRoot, leftSource)),
    );
  };
  const remaining = [...uniquePaths.values()].toSorted(compareFallback);
  const ordered: AgentDeleteCleanupPath[] = [];
  // Snapshot real targets and clean every physical or lexical descendant first; moving an
  // ancestor symlink would otherwise hide surviving child data and let recovery finalize.
  while (remaining.length > 0) {
    const nextIndex = remaining.findIndex((candidate, candidateIndex) =>
      remaining.every(
        (other, otherIndex) => otherIndex === candidateIndex || !mustPrecede(other, candidate),
      ),
    );
    ordered.push(...remaining.splice(Math.max(0, nextIndex), 1));
  }
  return ordered;
}

function cleanupPathCovers(
  cleanupPath: AgentDeleteCleanupPath,
  targetPath: string,
  canonicalTargetPath: string,
): boolean {
  const trashTargetPath = path.resolve(targetPath);
  return (
    cleanupPath.sourcePaths.includes(trashTargetPath) ||
    cleanupPath.trashPath === trashTargetPath ||
    (cleanupPath.trashCoversDescendants &&
      (cleanupPath.kind === "target" || isPathInside(cleanupPath.trashPath, trashTargetPath)) &&
      isPathInside(cleanupPath.canonicalPath, canonicalTargetPath))
  );
}

function unregisterAgentDeleteDatabases(agentId: string, databasePaths: string[]): void {
  for (const databasePath of databasePaths) {
    unregisterOpenClawAgentDatabase({ agentId, path: databasePath });
  }
}

function prepareJournaledAgentDirOwnership(
  cfg: OpenClawConfig,
  agentId: string,
  agentDir: string,
): void {
  for (const configuredAgentId of listAgentIds(cfg)) {
    resolveAgentDir(cfg, configuredAgentId);
  }
  const registeredOwner = resolveRegisteredAgentIdForDir(agentDir);
  if (registeredOwner !== undefined) {
    return;
  }
  // The durable journal retains ownership across restarts after the roster entry is gone.
  registerResolvedAgentDir({ agentId, agentDir });
}

function respondWorkspaceFileUnsafe(respond: RespondFn, name: string): void {
  respond(
    false,
    undefined,
    errorShape(ErrorCodes.INVALID_REQUEST, `unsafe workspace file "${name}"`),
  );
}

function respondWorkspaceFileMissing(params: {
  respond: RespondFn;
  agentId: string;
  workspaceDir: string;
  name: string;
  filePath: string;
}): void {
  params.respond(
    true,
    {
      agentId: params.agentId,
      workspace: params.workspaceDir,
      // Clients merge this entry over the listed one, so it must carry the same
      // absence classification or a picked optional file re-renders as a fault.
      file: {
        name: params.name,
        path: params.filePath,
        missing: true,
        expectedAbsent: isExpectedAbsentBootstrapFile(params.name),
      },
    },
    undefined,
  );
}

async function writeWorkspaceFileOrRespond(params: {
  respond: RespondFn;
  workspaceDir: string;
  name: string;
  content: string;
}): Promise<boolean> {
  await fs.mkdir(params.workspaceDir, { recursive: true });
  try {
    const workspaceRoot = await agentsHandlerDeps.root(params.workspaceDir);
    await workspaceRoot.write(params.name, params.content, { encoding: "utf8" });
  } catch (err) {
    if (err instanceof FsSafeError) {
      respondWorkspaceFileUnsafe(params.respond, params.name);
      return false;
    }
    throw err;
  }
  return true;
}

function hashWorkspaceFileContent(content: Buffer | string): string {
  return createHash("sha256").update(content).digest("hex");
}

async function readWorkspaceFileHash(
  workspaceRoot: WorkspaceRoot,
  name: string,
): Promise<string | undefined> {
  try {
    const safeRead = await workspaceRoot.read(name, {
      hardlinks: "reject",
      nonBlockingRead: true,
    });
    return hashWorkspaceFileContent(safeRead.buffer);
  } catch (err) {
    if (isMissingPathError(err)) {
      return undefined;
    }
    throw err;
  }
}

function respondWorkspaceFileConflict(
  respond: RespondFn,
  name: string,
  currentHash: string | undefined,
) {
  respond(
    false,
    undefined,
    errorShape(ErrorCodes.INVALID_REQUEST, `agent file "${name}" changed since it was read`, {
      details: {
        type: "agent_file_conflict",
        name,
        ...(currentHash ? { currentHash } : {}),
      },
    }),
  );
}

async function readWorkspaceFileContent(
  workspaceDir: string,
  name: string,
): Promise<string | undefined> {
  try {
    const workspaceRoot = await agentsHandlerDeps.root(workspaceDir);
    const safeRead = await workspaceRoot.read(name, {
      hardlinks: "reject",
      nonBlockingRead: true,
    });
    return safeRead.buffer.toString("utf-8");
  } catch (err) {
    if (isMissingPathError(err)) {
      return undefined;
    }
    throw err;
  }
}

async function buildIdentityMarkdownForWrite(params: {
  workspaceDir: string;
  identity: IdentityConfig;
  fallbackWorkspaceDir?: string;
  preferFallbackWorkspaceContent?: boolean;
}): Promise<string> {
  let baseContent: string | undefined;
  if (params.preferFallbackWorkspaceContent && params.fallbackWorkspaceDir) {
    // Workspace moves may create a blank identity file; merge into the previous user-edited file.
    baseContent = await readWorkspaceFileContent(
      params.fallbackWorkspaceDir,
      DEFAULT_IDENTITY_FILENAME,
    );
    if (baseContent === undefined) {
      baseContent = await readWorkspaceFileContent(params.workspaceDir, DEFAULT_IDENTITY_FILENAME);
    }
  } else {
    baseContent = await readWorkspaceFileContent(params.workspaceDir, DEFAULT_IDENTITY_FILENAME);
    if (baseContent === undefined && params.fallbackWorkspaceDir) {
      baseContent = await readWorkspaceFileContent(
        params.fallbackWorkspaceDir,
        DEFAULT_IDENTITY_FILENAME,
      );
    }
  }

  return mergeIdentityMarkdownContent(baseContent, params.identity);
}

async function buildIdentityMarkdownOrRespondUnsafe(params: {
  respond: RespondFn;
  workspaceDir: string;
  identity: IdentityConfig;
  fallbackWorkspaceDir?: string;
  preferFallbackWorkspaceContent?: boolean;
}): Promise<string | null> {
  try {
    return await buildIdentityMarkdownForWrite(params);
  } catch (err) {
    if (err instanceof FsSafeError) {
      respondWorkspaceFileUnsafe(params.respond, DEFAULT_IDENTITY_FILENAME);
      return null;
    }
    throw err;
  }
}

export const agentsHandlers: GatewayRequestHandlers = {
  "agents.list": async ({ params, respond, context, client }) => {
    if (!assertValidParams(params, validateAgentsListParams, "agents.list", respond)) {
      return;
    }

    const cfg = context.getRuntimeConfig();
    const modelCatalogByAgentId = new Map(
      await Promise.all(
        listAgentIds(cfg).map(
          async (agentId) =>
            [agentId, await readPreparedServerMethodModelCatalog(context, { agentId })] as const,
        ),
      ),
    );
    respond(
      true,
      listAgentsForGateway(cfg, undefined, {
        modelCatalogByAgentId,
        includeSystem: hasGatewayClientCap(client?.connect.caps, GATEWAY_CLIENT_CAPS.AGENT_KIND),
        httpAvatarBasePath:
          client?.connect.client.id === GATEWAY_CLIENT_IDS.CONTROL_UI
            ? (cfg.gateway?.controlUi?.basePath ?? "")
            : undefined,
      }),
      undefined,
    );
  },
  "agents.create": async ({ params, respond }) => {
    if (!assertValidParams(params, validateAgentsCreateParams, "agents.create", respond)) {
      return;
    }

    const result = await createAgent({
      name: params.name,
      workspace: params.workspace,
      model: params.model,
      emoji: params.emoji,
      avatar: params.avatar,
    });
    if (result.status === "error") {
      respond(false, undefined, errorShape(ErrorCodes.INVALID_REQUEST, result.message));
      return;
    }
    respond(
      true,
      {
        ok: true,
        agentId: result.agentId,
        name: result.name,
        workspace: result.workspace,
        ...(result.model ? { model: result.model } : {}),
      },
      undefined,
    );
  },
  "agents.update": async ({ params, respond, context }) => {
    if (!assertValidParams(params, validateAgentsUpdateParams, "agents.update", respond)) {
      return;
    }

    const cfg = context.getRuntimeConfig();
    const normalized = normalizeAgentIdStrict(params.agentId);
    if (!normalized.ok) {
      respondAgentNotFound(respond, params.agentId);
      return;
    }
    const agentId = normalized.value;
    if (!isConfiguredAgent(cfg, agentId)) {
      respondAgentNotFound(respond, agentId);
      return;
    }

    const workspaceDir =
      typeof params.workspace === "string" && params.workspace.trim()
        ? resolveUserPath(params.workspace.trim())
        : undefined;

    const model = params.model === null ? null : resolveOptionalStringParam(params.model);

    const safeName =
      typeof params.name === "string" && params.name.trim()
        ? sanitizeAgentIdentityLine(params.name.trim())
        : undefined;

    const identity = createAgentIdentityConfig({
      name: safeName,
      emoji: params.emoji,
      avatar: params.avatar,
    });
    const hasIdentityFields = Boolean(identity);

    const agentConfigUpdate: Parameters<typeof updateAgentConfigEntry>[0] = {
      agentId,
      ...(safeName ? { name: safeName } : {}),
      ...(workspaceDir ? { workspace: workspaceDir } : {}),
      ...(model !== undefined ? { model } : {}),
      ...(identity ? { identity } : {}),
    };
    const nextConfig = applyAgentConfig(cfg, agentConfigUpdate);

    let ensuredWorkspace: Awaited<ReturnType<typeof ensureAgentWorkspace>> | undefined;
    if (workspaceDir) {
      const skipBootstrap = Boolean(nextConfig.agents?.defaults?.skipBootstrap);
      ensuredWorkspace = await ensureAgentWorkspace({
        dir: workspaceDir,
        ensureBootstrapFiles: !skipBootstrap,
        skipOptionalBootstrapFiles: nextConfig.agents?.defaults?.skipOptionalBootstrapFiles,
      });
    }

    const persistedIdentity = normalizeIdentityForFile(resolveAgentIdentity(nextConfig, agentId));
    if (persistedIdentity && (workspaceDir || hasIdentityFields)) {
      const identityWorkspaceDir = resolveAgentWorkspaceDir(nextConfig, agentId);
      const previousWorkspaceDir = resolveAgentWorkspaceDir(cfg, agentId);
      const fallbackWorkspaceDir =
        workspaceDir && identityWorkspaceDir !== previousWorkspaceDir
          ? previousWorkspaceDir
          : undefined;
      const identityContent = await buildIdentityMarkdownOrRespondUnsafe({
        respond,
        workspaceDir: identityWorkspaceDir,
        identity: persistedIdentity,
        fallbackWorkspaceDir,
        preferFallbackWorkspaceContent:
          Boolean(fallbackWorkspaceDir) && ensuredWorkspace?.identityPathCreated === true,
      });
      if (identityContent === null) {
        return;
      }
      if (
        !(await writeWorkspaceFileOrRespond({
          respond,
          workspaceDir: identityWorkspaceDir,
          name: DEFAULT_IDENTITY_FILENAME,
          content: identityContent,
        }))
      ) {
        return;
      }
    }

    try {
      await updateAgentConfigEntry(agentConfigUpdate);
    } catch (error) {
      if (error instanceof AgentConfigPreconditionError) {
        respondAgentNotFound(respond, agentId);
        return;
      }
      throw error;
    }

    respond(true, { ok: true, agentId }, undefined);
  },
  "agents.delete": async ({ params, respond, context }) => {
    if (!assertValidParams(params, validateAgentsDeleteParams, "agents.delete", respond)) {
      return;
    }

    const cfg = context.getRuntimeConfig();
    const normalized = normalizeAgentIdStrict(params.agentId);
    if (!normalized.ok) {
      respondAgentNotFound(respond, params.agentId);
      return;
    }
    const agentId = normalized.value;
    if (agentOwnsSharedAuthStore(cfg, agentId)) {
      respond(
        false,
        undefined,
        errorShape(ErrorCodes.INVALID_REQUEST, formatSharedAuthStoreOwnerDeleteError(agentId)),
      );
      return;
    }
    const existingJournal = readAgentDeletionJournal(agentId);
    if (
      !isConfiguredAgent(cfg, agentId) &&
      (!existingJournal || existingJournal.cleanupCompleted)
    ) {
      respondAgentNotFound(respond, agentId);
      return;
    }
    if (agentId === tryResolveSoleAgentId(cfg)) {
      respond(
        false,
        undefined,
        errorShape(
          ErrorCodes.INVALID_REQUEST,
          `Agent "${agentId}" is the only configured agent and cannot be deleted.`,
        ),
      );
      return;
    }
    if (isInheritedAuthStoreOwner(cfg, agentId)) {
      respond(
        false,
        undefined,
        errorShape(
          ErrorCodes.INVALID_REQUEST,
          `Agent "${agentId}" owns inherited credentials through agents.defaults.authInheritance.agentId and cannot be deleted. Relocate those credentials, then re-point or remove that binding before retrying.`,
        ),
      );
      return;
    }

    const requestedDeleteFiles =
      typeof params.deleteFiles === "boolean" ? params.deleteFiles : true;
    try {
      const result = await withAgentDeletion(agentId, async (begin) =>
        withConfigMutationExclusive(async (lockedConfig) => {
          assertAgentSessionStoreDeletionSafe(lockedConfig, agentId);
          let lockedJournal = readAgentDeletionJournal(agentId);
          const configured = isConfiguredAgent(lockedConfig, agentId);
          if (agentOwnsSharedAuthStore(lockedConfig, agentId)) {
            throw new AgentSharedAuthStoreOwnerError(
              formatSharedAuthStoreOwnerDeleteError(agentId),
            );
          }
          if (!configured && (!lockedJournal || lockedJournal.cleanupCompleted)) {
            throw new AgentConfigPreconditionError(`agent "${agentId}" not found`);
          }
          if (agentId === tryResolveSoleAgentId(lockedConfig)) {
            throw new AgentConfigPreconditionError(
              `agent "${agentId}" is the only configured agent`,
            );
          }
          if (isInheritedAuthStoreOwner(lockedConfig, agentId)) {
            throw new AgentConfigPreconditionError(
              `agent "${agentId}" owns agents.defaults.authInheritance.agentId; relocate credentials and re-point it first`,
            );
          }
          if (configured && lockedJournal?.cleanupCompleted) {
            const claimed = claimCompletedAgentDeletion(agentId, lockedJournal.operationId);
            const remainingJournal = readAgentDeletionJournal(agentId);
            if (!claimed && remainingJournal) {
              throw new Error(
                `agent "${agentId}" deletion tombstone changed before fresh deletion`,
              );
            }
            lockedJournal = undefined;
          }
          const deleteFiles = lockedJournal?.deleteFiles ?? requestedDeleteFiles;
          const deletion = begin(
            lockedJournal ?? {
              agentId,
              agentDir: resolveAgentDir(lockedConfig, agentId),
              workspaceDir: resolveAgentWorkspaceDir(lockedConfig, agentId),
              sessionsDir: resolveSessionTranscriptsDirForAgent(agentId),
              deleteFiles,
            },
          );
          const journal = deletion.entry;
          let rosterCommitted = !configured;
          let committed: Awaited<ReturnType<typeof deleteAgentConfigEntry>> | undefined;
          let databasePlan: AgentDeleteDatabasePlan | undefined;
          try {
            prepareJournaledAgentDirOwnership(lockedConfig, agentId, journal.agentDir);
            databasePlan = await prepareAgentDeleteDatabases(
              lockedConfig,
              agentId,
              journal.agentDir,
            );
            deletion.assertCurrent();
            deletion.fenceDatabasePaths([
              ...journal.databasePaths,
              ...databasePlan.fileGroups.flat(),
            ]);
            if (deleteFiles) {
              const fencedSourcePaths = new Set(
                journal.cleanupPaths.flatMap((cleanupPath) =>
                  cleanupPath.sourcePaths.map((sourcePath) => path.resolve(sourcePath)),
                ),
              );
              const unfencedSourcePaths = [
                journal.workspaceDir,
                journal.agentDir,
                journal.sessionsDir,
                ...journal.databasePaths,
              ].filter((sourcePath) => !fencedSourcePaths.has(path.resolve(sourcePath)));
              if (unfencedSourcePaths.length > 0) {
                const unfencedSourcePathSet = new Set(
                  unfencedSourcePaths.map((sourcePath) => path.resolve(sourcePath)),
                );
                const cleanupPlan = await prepareAgentDeleteCleanupPaths(
                  unfencedSourcePaths,
                  journal.cleanupPaths,
                );
                const unresolvedPath = cleanupPlan.find(
                  (cleanupPath) =>
                    cleanupPath.preparationError !== undefined &&
                    cleanupPath.sourcePaths.some((sourcePath) =>
                      unfencedSourcePathSet.has(path.resolve(sourcePath)),
                    ),
                );
                if (unresolvedPath) {
                  throw unresolvedPath.preparationError;
                }
                deletion.fenceCleanupPaths(
                  cleanupPlan.map(
                    ({
                      path: cleanupPath,
                      trashPath,
                      parentPath,
                      kind,
                      preparedIdentity,
                      trashCoversDescendants,
                      done,
                      note,
                      sourcePaths,
                    }) => {
                      const journalPath: AgentDeletionJournalCleanupPath = {
                        path: cleanupPath,
                        canonicalPath: trashPath,
                        parentPath,
                        kind,
                        sourcePaths,
                        dev: preparedIdentity?.dev ?? null,
                        ino: preparedIdentity?.ino ?? null,
                        coversDescendants: trashCoversDescendants,
                        done,
                      };
                      if (note) {
                        journalPath.note = note;
                      }
                      return journalPath;
                    },
                  ),
                );
              }
            }
            await context.cron.removeAgentJobsTransactional(
              agentId,
              async () =>
                await withAgentExecApprovalsRemoved(agentId, async () => {
                  deletion.assertCurrent();
                  if (!rosterCommitted) {
                    try {
                      committed = await deleteAgentConfigEntry({
                        agentId,
                        assertCurrent: deletion.assertCurrent,
                      });
                    } catch (error) {
                      try {
                        const persisted = await readConfigFileSnapshotForWrite();
                        if (!isConfiguredAgent(persisted.snapshot.sourceConfig, agentId)) {
                          rosterCommitted = true;
                          throw new AgentDeletionCommitUncertainError(error);
                        }
                      } catch (readError) {
                        if (readError instanceof AgentDeletionCommitUncertainError) {
                          throw readError;
                        }
                        throw new AgentDeletionCommitUncertainError(error);
                      }
                      throw error;
                    }
                    if (!committed.result) {
                      rosterCommitted = !isConfiguredAgent(committed.nextConfig, agentId);
                      const missingResultError = new Error(
                        "agent delete config mutation did not return its target",
                      );
                      if (rosterCommitted) {
                        throw new AgentDeletionCommitUncertainError(missingResultError);
                      }
                      throw missingResultError;
                    }
                    rosterCommitted = true;
                  }
                }),
            );
            deletion.assertCurrent();
          } catch (error) {
            let canReleaseFence =
              !rosterCommitted &&
              !lockedJournal &&
              !(error instanceof AgentDeletionAuthorityRollbackError) &&
              !(error instanceof AgentDeletionCommitUncertainError);
            if (canReleaseFence) {
              try {
                const persisted = await readConfigFileSnapshotForWrite();
                canReleaseFence = isConfiguredAgent(persisted.snapshot.sourceConfig, agentId);
              } catch {
                canReleaseFence = false;
              }
            }
            if (canReleaseFence) {
              deletion.rollback();
            }
            throw error;
          }

          const deleteResult = committed?.result ?? {
            agentDir: journal.agentDir,
            workspaceDir: journal.workspaceDir,
            sessionsDir: journal.sessionsDir,
            removedBindings: 0,
          };
          const nextConfig = committed?.nextConfig ?? lockedConfig;

          // A journaled path is trash-eligible only while registry ownership still points at the
          // deleted agent; recovery must not consume a path claimed by a surviving agent.
          const agentDirRegistryPath = normalizeAgentDirRegistryPath(deleteResult.agentDir);
          const purgeFailed = await purgeAgentSessionStoreEntries(lockedConfig, agentId, {
            runDatabaseCleanup: deletion.runDatabaseCleanup,
          });
          deletion.assertCurrent();

          const removed: AgentDeleteRemovedPath[] = [];
          const failed: AgentDeleteFailedPath[] = [];

          if (deleteFiles && !purgeFailed) {
            const survivingDatabaseFilePaths = resolveSurvivingDatabaseFilePaths(
              readAgentDeleteDatabaseRegistry(),
              agentId,
            );
            const workspaceTrashEligible = !isPathOwnedBySurvivingAgent(
              nextConfig,
              agentId,
              deleteResult.workspaceDir,
              survivingDatabaseFilePaths,
            );
            // The config mutation lock and durable journal fence block new roster and database
            // claims across this final ownership recheck and the filesystem cleanup below.
            const agentDirTrashEligible =
              resolveRegisteredAgentIdForDir(deleteResult.agentDir) === agentId &&
              !isPathOwnedBySurvivingAgent(
                nextConfig,
                agentId,
                deleteResult.agentDir,
                survivingDatabaseFilePaths,
              );
            const sessionsDirTrashEligible = !isPathOwnedBySurvivingAgent(
              nextConfig,
              agentId,
              deleteResult.sessionsDir,
              survivingDatabaseFilePaths,
            );
            const databaseFilePaths = [
              ...(agentDirTrashEligible
                ? (databasePlan?.relocatedFileGroups ?? [])
                : (databasePlan?.fileGroups ?? [])
              ).flat(),
              ...journal.databasePaths,
            ].filter(
              (pathname) =>
                !isPathOwnedBySurvivingAgent(
                  nextConfig,
                  agentId,
                  pathname,
                  survivingDatabaseFilePaths,
                ),
            );
            const eligibleSourcePaths = new Set(
              [
                ...(workspaceTrashEligible ? [deleteResult.workspaceDir] : []),
                ...(agentDirTrashEligible ? [deleteResult.agentDir] : []),
                ...(sessionsDirTrashEligible ? [deleteResult.sessionsDir] : []),
                ...databaseFilePaths,
              ].map((sourcePath) => path.resolve(sourcePath)),
            );
            const cleanupPaths = (
              await prepareAgentDeleteCleanupPaths([], journal.cleanupPaths)
            ).filter(
              (cleanupPath) =>
                cleanupPath.sourcePaths.some((sourcePath) => eligibleSourcePaths.has(sourcePath)) &&
                (agentDirTrashEligible ||
                  !cleanupPathCovers(cleanupPath, deleteResult.agentDir, agentDirRegistryPath)),
            );
            const workspaceCanonicalPath = normalizeAgentDirRegistryPath(deleteResult.workspaceDir);
            const workspaceCleanupPaths = cleanupPaths.filter((cleanupPath) =>
              cleanupPathCovers(cleanupPath, deleteResult.workspaceDir, workspaceCanonicalPath),
            );
            const legacyPlan =
              workspaceCleanupPaths.length > 0
                ? prepareLegacyWorkspaceStateReset(deleteResult.workspaceDir)
                : undefined;
            const statePlan =
              workspaceCleanupPaths.length > 0
                ? prepareWorkspaceStateDeletion(deleteResult.workspaceDir)
                : undefined;
            const outcomes: Array<{
              cleanupPath: AgentDeleteCleanupPath;
              outcome: AgentDeletePathOutcome;
            }> = [];
            const completedCleanupPaths = new Set(
              cleanupPaths.filter((cleanupPath) => cleanupPath.done),
            );
            const markCleanupPathDone = (cleanupPath: AgentDeleteCleanupPath, note?: string) => {
              const canonicalPath = path.resolve(cleanupPath.trashPath);
              deletion.fenceCleanupPaths(
                journal.cleanupPaths.map((entry) => {
                  if (
                    path.resolve(entry.canonicalPath) !== canonicalPath ||
                    entry.kind !== cleanupPath.kind
                  ) {
                    return entry;
                  }
                  const updated = Object.assign({}, entry, { done: true });
                  if (note) {
                    updated.note = note;
                  }
                  return updated;
                }),
              );
              cleanupPath.done = true;
              cleanupPath.note = note;
              completedCleanupPaths.add(cleanupPath);
            };
            const protectedCleanupPaths: Array<{
              cleanupPath: AgentDeleteCleanupPath;
              protectAliases: boolean;
              terminal: boolean;
              note?: string;
            }> = [];
            for (const cleanupPath of cleanupPaths) {
              deletion.assertCurrent();
              if (cleanupPath.done) {
                let replacementPresent = true;
                let note =
                  cleanupPath.note ?? "completed cleanup path is occupied; replacement preserved";
                try {
                  await statAgentCleanupPath(cleanupPath);
                } catch (error) {
                  if (isMissingPathError(error)) {
                    replacementPresent = false;
                  } else if (!(error instanceof AgentCleanupIdentityMismatchError)) {
                    note = "completed cleanup path could not be verified; replacement preserved";
                  }
                }
                if (replacementPresent) {
                  markCleanupPathDone(cleanupPath, note);
                  protectedCleanupPaths.push({
                    cleanupPath,
                    protectAliases: true,
                    terminal: true,
                    note,
                  });
                }
                continue;
              }
              const refreshedDatabaseFilePaths = resolveSurvivingDatabaseFilePaths(
                readAgentDeleteDatabaseRegistry(),
                agentId,
              );
              const blockingProtection = protectedCleanupPaths.find(
                ({ cleanupPath: protectedPath, protectAliases }) =>
                  ((cleanupPath.kind !== "symlink" || protectAliases) &&
                    (protectedPath.canonicalPath === cleanupPath.canonicalPath ||
                      isPathInside(cleanupPath.canonicalPath, protectedPath.canonicalPath))) ||
                  [
                    protectedPath.trashPath,
                    ...(protectAliases ? protectedPath.sourcePaths : []),
                  ].some(
                    (protectedSourcePath) =>
                      protectedSourcePath === cleanupPath.trashPath ||
                      isPathInside(cleanupPath.trashPath, protectedSourcePath),
                  ),
              );
              const ownedBySurvivor =
                isPathOwnedBySurvivingAgent(
                  nextConfig,
                  agentId,
                  cleanupPath.path,
                  refreshedDatabaseFilePaths,
                ) ||
                (cleanupPathCovers(cleanupPath, deleteResult.agentDir, agentDirRegistryPath) &&
                  resolveRegisteredAgentIdForDir(deleteResult.agentDir) !== agentId);
              if (blockingProtection || ownedBySurvivor) {
                const terminal = ownedBySurvivor || blockingProtection?.terminal === true;
                const note = ownedBySurvivor
                  ? "replacement owned by a surviving agent"
                  : blockingProtection?.note;
                if (terminal) {
                  markCleanupPathDone(cleanupPath, note ?? "protected replacement preserved");
                }
                protectedCleanupPaths.push({
                  cleanupPath,
                  protectAliases: blockingProtection?.protectAliases ?? false,
                  terminal,
                  note,
                });
                continue;
              }
              const outcome = cleanupPath.preparationError
                ? cleanupFailure(cleanupPath.path, cleanupPath.preparationError)
                : await removeAgentPath(cleanupPath, deletion.assertCurrent);
              outcomes.push({
                cleanupPath,
                outcome,
              });
              if ("removed" in outcome) {
                markCleanupPathDone(cleanupPath);
              } else if ("skipped" in outcome) {
                markCleanupPathDone(cleanupPath, outcome.skipped.reason);
                protectedCleanupPaths.push({
                  cleanupPath,
                  protectAliases: true,
                  terminal: true,
                  note: outcome.skipped.reason,
                });
              } else {
                protectedCleanupPaths.push({
                  cleanupPath,
                  protectAliases: true,
                  terminal: false,
                });
              }
            }
            for (const { outcome } of outcomes) {
              if ("removed" in outcome) {
                removed.push(outcome.removed);
              } else if ("failed" in outcome) {
                failed.push(outcome.failed);
              }
            }
            if (
              workspaceCleanupPaths.length > 0 &&
              workspaceCleanupPaths.every((cleanupPath) =>
                completedCleanupPaths.has(cleanupPath),
              ) &&
              legacyPlan &&
              statePlan
            ) {
              try {
                await removeLegacyWorkspaceStateForReset(legacyPlan, {
                  assertCurrent: deletion.assertCurrent,
                });
                deletion.assertCurrent();
                await deleteWorkspaceState(statePlan, { assertCurrent: deletion.assertCurrent });
              } catch {
                // Best-effort cleanup. A later explicit reset can remove stale rows.
              }
            }
            deletion.assertCurrent();
            const agentDirCleanupPaths = cleanupPaths.filter((cleanupPath) =>
              cleanupPathCovers(cleanupPath, deleteResult.agentDir, agentDirRegistryPath),
            );
            if (
              agentDirCleanupPaths.length > 0 &&
              agentDirCleanupPaths.every((cleanupPath) => completedCleanupPaths.has(cleanupPath))
            ) {
              unregisterResolvedAgentDir({ agentId, agentDir: agentDirRegistryPath });
            }
          }
          deletion.assertCurrent();
          if (failed.length === 0 && !purgeFailed) {
            unregisterResolvedAgentDir({ agentId, agentDir: agentDirRegistryPath });
            if (deleteFiles) {
              unregisterAgentDeleteDatabases(agentId, databasePlan?.registrationPaths ?? []);
            }
            deletion.finish();
          }
          return {
            ok: true,
            agentId,
            removedBindings: deleteResult.removedBindings,
            removed,
            failed,
            ...(purgeFailed ? { purgeFailed: true as const } : {}),
          };
        }),
      );
      respond(true, result, undefined);
    } catch (error) {
      if (
        error instanceof AgentSharedAuthStoreOwnerError ||
        error instanceof AgentSharedStoreOwnerError
      ) {
        respond(false, undefined, errorShape(ErrorCodes.INVALID_REQUEST, error.message));
        return;
      }
      if (error instanceof AgentConfigPreconditionError) {
        respondAgentNotFound(respond, agentId);
        return;
      }
      throw error;
    }
  },
  "agents.files.list": async ({ params, respond, context }) => {
    if (!assertValidParams(params, validateAgentsFilesListParams, "agents.files.list", respond)) {
      return;
    }
    const cfg = context.getRuntimeConfig();
    const agentId = resolveAgentIdOrError(params.agentId, cfg);
    if (!agentId) {
      respondAgentNotFound(respond, params.agentId);
      return;
    }
    const workspaceDir = resolveAgentWorkspaceDir(cfg, agentId);
    let hideBootstrap = false;
    try {
      hideBootstrap = await agentsHandlerDeps.isWorkspaceSetupCompleted(workspaceDir);
    } catch {
      // Fall back to showing BOOTSTRAP if workspace state cannot be read.
    }
    const files = await listAgentFiles(workspaceDir, { hideBootstrap });
    respond(true, { agentId, workspace: workspaceDir, files }, undefined);
  },
  "agents.files.get": async ({ params, respond, context }) => {
    if (!assertValidParams(params, validateAgentsFilesGetParams, "agents.files.get", respond)) {
      return;
    }
    const resolved = resolveAgentWorkspaceFileOrRespondError(
      params,
      respond,
      context.getRuntimeConfig(),
    );
    if (!resolved) {
      return;
    }
    const { agentId, workspaceDir, name } = resolved;
    const filePath = path.join(workspaceDir, name);
    let safeRead: ReadResult;
    try {
      const workspaceRoot = await agentsHandlerDeps.root(workspaceDir);
      safeRead = await workspaceRoot.read(name, {
        hardlinks: "reject",
        nonBlockingRead: true,
      });
    } catch (err) {
      if (isMissingPathError(err)) {
        respondWorkspaceFileMissing({ respond, agentId, workspaceDir, name, filePath });
        return;
      }
      if (err instanceof FsSafeError) {
        respondWorkspaceFileUnsafe(respond, name);
        return;
      }
      throw err;
    }
    respond(
      true,
      {
        agentId,
        workspace: workspaceDir,
        file: {
          name,
          path: filePath,
          missing: false,
          size: safeRead.stat.size,
          updatedAtMs: Math.floor(safeRead.stat.mtimeMs),
          hash: hashWorkspaceFileContent(safeRead.buffer),
          content: safeRead.buffer.toString("utf-8"),
        },
      },
      undefined,
    );
  },
  "agents.files.set": async ({ params, respond, context }) => {
    if (!assertValidParams(params, validateAgentsFilesSetParams, "agents.files.set", respond)) {
      return;
    }
    const resolved = resolveAgentWorkspaceFileOrRespondError(
      params,
      respond,
      context.getRuntimeConfig(),
    );
    if (!resolved) {
      return;
    }
    const { agentId, workspaceDir, name } = resolved;
    await fs.mkdir(workspaceDir, { recursive: true });
    const filePath = path.join(workspaceDir, name);
    const content = params.content;
    let workspaceRoot: WorkspaceRoot;
    let conflict: { currentHash: string | undefined } | undefined;
    try {
      workspaceRoot = await agentsHandlerDeps.root(workspaceDir);
      const writeRoot = workspaceRoot;
      const expectedHash = params.expectedHash?.toLowerCase();
      conflict = await enqueueWorkspaceFileUpdate(async () => {
        if (expectedHash) {
          const currentHash = await readWorkspaceFileHash(writeRoot, name);
          if (currentHash !== expectedHash) {
            return { currentHash };
          }
        }
        await writeRoot.write(name, content, { encoding: "utf8" });
        return undefined;
      });
    } catch (err) {
      if (!(err instanceof FsSafeError)) {
        throw err;
      }
      respondWorkspaceFileUnsafe(respond, name);
      return;
    }
    if (conflict) {
      respondWorkspaceFileConflict(respond, name, conflict.currentHash);
      return;
    }
    const meta = await statWorkspaceFileSafely(workspaceRoot, workspaceDir, name);
    respond(
      true,
      {
        ok: true,
        agentId,
        workspace: workspaceDir,
        file: {
          name,
          path: filePath,
          missing: false,
          size: meta?.size,
          updatedAtMs: meta?.updatedAtMs,
          hash: hashWorkspaceFileContent(content),
          content,
        },
      },
      undefined,
    );
  },
};
/* oxlint-disable max-lines -- TODO: split this grandfathered oversized file. */