localharness 0.54.0

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

use crate::app::chat::access::{
    build_actor_setup, transfer_selector, u256_be, withdraw_credits_selector,
};
use crate::encoding::parse_address;
use crate::tools::ClosureTool;

/// Resolve a `recipient` arg (raw 0x… address or subdomain name) to the
/// 0x… address that receives $LH (a name pays its on-chain OWNER).
async fn resolve_lh_recipient(recipient_arg: &str) -> Result<String, crate::error::Error> {
    use crate::encoding::Recipient;
    let kind = crate::encoding::classify_recipient(recipient_arg)
        .map_err(crate::error::Error::other)?;
    match kind {
        Recipient::Address(addr) => Ok(addr),
        Recipient::Name(name) => crate::app::registry::owner_of_name(&name)
            .await
            .map_err(crate::error::Error::other)?
            .ok_or_else(|| {
                crate::error::Error::other(format!(
                    "no on-chain owner for subdomain \"{name}\" — is it registered?"
                ))
            }),
    }
}

/// Resolve a $LH recipient to a NOTIFIABLE subdomain name (#50): the name
/// directly if `recipient_arg` was a name, else the owner address's MAIN name
/// (reverse `main_of` → `name_of_id`). `None` when the recipient has no
/// registered identity to notify (a bare address). The proxy `/api/notify`
/// only routes to a name, so this is how a raw-address transfer still pings.
async fn notifiable_recipient_name(recipient_arg: &str, to_hex: &str) -> Option<String> {
    use crate::encoding::Recipient;
    if let Ok(Recipient::Name(name)) = crate::encoding::classify_recipient(recipient_arg) {
        return Some(name);
    }
    // Raw address: reverse-resolve to its MAIN identity's name, if any.
    let main_id = crate::app::registry::main_of(to_hex).await.ok()?;
    if main_id == 0 {
        return None;
    }
    crate::app::registry::name_of_id(main_id).await.ok().filter(|n| !n.is_empty())
}

/// Fire-and-forget a cross-agent notification to the $LH recipient that funds
/// arrived (#50): piggybacks the existing cross-agent notify (`notify_cross_agent`
/// → proxy `/api/notify`, which lands in the recipient's bell + buzzes any
/// enrolled phone). Best-effort — it must NEVER fail or block the transfer that
/// already settled on-chain; an unregistered/un-enrolled recipient is silently
/// skipped. NOT a transfer-watch system — it just rides the send.
fn notify_recipient_of_incoming_lh(recipient_arg: String, to_hex: String, amount: String) {
    wasm_bindgen_futures::spawn_local(async move {
        let Some(name) = notifiable_recipient_name(&recipient_arg, &to_hex).await else {
            return;
        };
        let title = format!("+{amount} $LH received");
        let body = "incoming $LH transfer — check your wallet".to_string();
        // The proxy stamps the SENDER's chain-verified identity into the title,
        // so the recipient sees who paid them. Swallow any error (no identity /
        // not enrolled / metered-out): the money already moved.
        let _ = crate::app::chat::tools::misc::notify_cross_agent(&name, &title, &body).await;
    });
}

/// ERC-20 `transfer(to, amount)` TempoCall against the $LH token.
fn lh_transfer_call(
    to_hex: &str,
    amount_wei: u128,
) -> Result<crate::tempo_tx::TempoCall, crate::error::Error> {
    let to_bytes = parse_address(to_hex).map_err(crate::error::Error::other)?;
    let mut to_padded = [0u8; 32];
    to_padded[12..].copy_from_slice(&to_bytes);
    let mut calldata = Vec::with_capacity(4 + 64);
    calldata.extend_from_slice(&transfer_selector());
    calldata.extend_from_slice(&to_padded);
    calldata.extend_from_slice(&u256_be(amount_wei));
    let token_addr = parse_address(crate::registry::LOCALHARNESS_TOKEN_ADDRESS())
        .map_err(crate::error::Error::other)?;
    Ok(crate::tempo_tx::TempoCall {
        to: token_addr,
        value_wei: 0,
        input: calldata,
    })
}

/// The meter auto-bridge for direct transfers (on-chain feedback #48): when
/// the sender's wallet can't cover `needed_wei` but their unspent chat-meter
/// credits can, return a `withdrawCredits(shortfall)` call to PREPEND to the
/// SAME Tempo tx — bridge + spend land atomically in one sponsored
/// submission (0x76 carries a calls array). Pot-aware error when both pots
/// together are short.
async fn meter_bridge_call(
    from_hex: &str,
    needed_wei: u128,
) -> Result<Option<crate::tempo_tx::TempoCall>, crate::error::Error> {
    // The pot math (0 = wallet covers / shortfall = meter covers / pot-aware
    // error) is the SAME pre-flight every escrow path runs — never re-fork it.
    let shortfall = crate::app::chat::access::escrow_bridge_wei(from_hex, needed_wei)
        .await
        .map_err(crate::error::Error::other)?;
    if shortfall == 0 {
        return Ok(None);
    }
    let mut calldata = Vec::with_capacity(4 + 32);
    calldata.extend_from_slice(&withdraw_credits_selector());
    calldata.extend_from_slice(&u256_be(shortfall));
    let diamond = parse_address(crate::registry::REGISTRY_ADDRESS())
        .map_err(crate::error::Error::other)?;
    Ok(Some(crate::tempo_tx::TempoCall {
        to: diamond,
        value_wei: 0,
        input: calldata,
    }))
}

/// `create_subdomain(name)` — register `<name>.localharness.xyz` on the
/// LocalharnessRegistry diamond, signed by the owner's apex wallet via
/// the iframe signer. Returns the tx hash. Sanitises the input the same
/// way `tenant::sanitize` does for the apex claim form.
pub(crate) fn create_subdomain_tool() -> std::sync::Arc<dyn crate::tools::Tool> {
    let schema = serde_json::json!({
        "type": "object",
        "properties": {
            "name": {
                "type": "string",
                "description": "Subdomain to register, e.g. \"alice\" \
                    becomes alice.localharness.xyz. 3-32 chars; lowercase \
                    letters, digits, and hyphens only."
            },
            "persona": {
                "type": "string",
                "description": "OPTIONAL system instruction / persona for the new \
                    agent — published on-chain as its system prompt (the persona \
                    that headless `call`s and the public face read). Omit to leave \
                    the default."
            },
            "prefund_lh": {
                "type": "string",
                "description": "OPTIONAL amount of $LH to prefund the new agent with, \
                    as a decimal string (\"5\", \"1.5\"). Transferred from YOUR \
                    wallet to the new subdomain's token-bound account (its own \
                    spendable wallet — used to pay other agents via x402). Omit, or \
                    pass \"0\", to skip. Must not exceed your $LH balance."
            }
        },
        "required": ["name"]
    });
    ClosureTool::new(
        "create_subdomain",
        "Register a new <name>.localharness.xyz subdomain on-chain (the ACTOR MODEL). \
         The owner's master wallet pays gas and ends up holding the resulting ERC-721 \
         NFT. OPTIONALLY spawn the actor WITH behavior + funds in one call: `persona` \
         publishes its on-chain system instruction; `prefund_lh` moves that much $LH \
         from your wallet into the new agent's token-bound account (its own wallet). \
         Returns { name, url, owner, tx_hash, persona_set?, prefunded_lh?, tba? }.",
        schema,
        |args: serde_json::Value, _ctx| async move {
            let name = args.get("name").and_then(|v| v.as_str()).unwrap_or("").trim();
            let persona = args.get("persona").and_then(|v| v.as_str());
            let prefund_lh = args.get("prefund_lh").and_then(|v| v.as_str());
            // Validate (don't silently mangle) — an invalid name returns a clear
            // reason to the agent instead of minting a DIFFERENT name (#66/#60).
            let cleaned = crate::subdomain::validate(name)
                .map_err(|why| crate::error::Error::other(format!("invalid subdomain name: {why}")))?;
            // Register the name first (master wallet ends up holding the new id).
            let (owner, claim_tx) = crate::app::verify::claim_name_via_iframe(&cleaned)
                .await
                .map_err(|e| crate::error::Error::other(format!("claim failed: {e}")))?;
            // Proactively push this device's Gemini key to the MAIN slot so the
            // new subdomain inherits it (no re-save).
            {
                let n = cleaned.clone();
                wasm_bindgen_futures::spawn_local(async move {
                    crate::app::events::sync_local_key_to_main(&n).await;
                });
            }

            // Optional ACTOR-MODEL extras: persona + prefund. Only if asked.
            let want_persona = persona.map(|p| !p.trim().is_empty()).unwrap_or(false);
            let want_prefund = prefund_lh
                .map(|p| {
                    let t = p.trim();
                    !t.is_empty() && t != "0"
                })
                .unwrap_or(false);
            let mut result = serde_json::json!({
                "name": cleaned,
                "url": format!("https://{cleaned}.localharness.xyz/"),
                "owner": owner,
                "tx_hash": claim_tx,
            });
            if want_persona || want_prefund {
                // Resolve the freshly-minted tokenId for the metadata/TBA ops.
                let token_id = match crate::app::registry::id_of_name(&cleaned).await {
                    Ok(id) if id != 0 => id,
                    Ok(_) => {
                        return Err(crate::error::Error::other(
                            "registered but tokenId not yet visible on-chain — retry \
                             persona/prefund shortly",
                        ))
                    }
                    Err(e) => return Err(crate::error::Error::other(format!("id_of_name: {e}"))),
                };
                let setup = build_actor_setup(
                    &owner,
                    token_id,
                    &cleaned,
                    persona,
                    prefund_lh,
                )
                .await?;
                if !setup.calls.is_empty() {
                    let tx_hash = crate::app::events::run_sponsored_tempo_call(
                        &owner,
                        setup.calls,
                        setup.extra_gas,
                        "spawn actor (persona + prefund)",
                    )
                    .await
                    .map_err(|e| {
                        crate::error::Error::other(format!("actor setup failed: {e}"))
                    })?;
                    result["setup_tx_hash"] = serde_json::json!(tx_hash);
                    result["persona_set"] = serde_json::json!(setup.persona_set);
                    if let Some(amt) = setup.prefunded_lh {
                        result["prefunded_lh"] = serde_json::json!(amt);
                    }
                    if let Some(tba) = setup.tba {
                        result["tba"] = serde_json::json!(tba);
                    }
                }
            }
            Ok(result)
        },
    )
}

/// Max bytes a compiled cartridge may be to publish on-chain (mirrors the
/// admin studio + CLI `PUBLISH_CAP`).
const APP_PUBLISH_CAP: usize = 16_384;

/// Compile + bounds-check a rustlite cartridge into the publish call batch
/// (`setMetadata(app.wasm)` then `setMetadata(public_face="app")`) plus
/// length-scaled gas — the ONE publish-app shape shared by
/// `create_and_publish_app` (fresh + update) and `publish_app_to`
/// (cross-subdomain). Mirrors the admin publish-app flow.
fn build_publish_app_calls(
    token_id: u64,
    source: &str,
) -> Result<(Vec<crate::tempo_tx::TempoCall>, u128), crate::error::Error> {
    if source.trim().is_empty() {
        return Err(crate::error::Error::other("source cannot be empty"));
    }
    // Compile FIRST — a bad cartridge fails before any on-chain write. Surface
    // the FULL rendering (LH code + line/col + caret) so the agent fixes it.
    let wasm = crate::rustlite::compile(source).map_err(|e| {
        crate::error::Error::other(format!("compile failed: {}", e.render(source)))
    })?;
    if wasm.len() > APP_PUBLISH_CAP {
        return Err(crate::error::Error::other(format!(
            "app wasm too large to publish: {} bytes (max {APP_PUBLISH_CAP})",
            wasm.len()
        )));
    }
    let registry_addr = parse_address(crate::app::registry::REGISTRY_ADDRESS())
        .map_err(crate::error::Error::other)?;
    let mk = |input: Vec<u8>| crate::tempo_tx::TempoCall {
        to: registry_addr,
        value_wei: 0,
        input,
    };
    let calls = vec![
        mk(crate::app::registry::encode_set_app_wasm(token_id, &wasm)),
        mk(crate::app::registry::encode_set_public_face(token_id, "app")),
    ];
    // Length-scaled (~7.6k gas/BYTE); a flat cap silently OOG-reverts any
    // non-trivial publish (see `gas::set_metadata_gas`).
    let gas = crate::app::gas::set_metadata_gas(wasm.len());
    Ok((calls, gas))
}

/// Resolve a registered name's `(token_id, owner)` for an OWNER-AUTHORIZED
/// write, asserting the master wallet that signs (`signer_owner`) holds it.
/// `None` = unregistered (caller decides whether to register). `Err` = the
/// name is owned by someone ELSE (refuse) or an RPC failure.
async fn owned_token_for_publish(
    name: &str,
    signer_owner: &str,
) -> Result<Option<(u64, String)>, crate::error::Error> {
    let owner = match crate::app::registry::owner_of_name(name).await {
        Ok(Some(o)) => o,
        Ok(None) => return Ok(None),
        Err(e) => return Err(crate::error::Error::other(format!("owner_of_name: {e}"))),
    };
    if !owner.eq_ignore_ascii_case(signer_owner) {
        return Err(crate::error::Error::other(format!(
            "\"{name}\" is owned by {owner}, not you ({signer_owner}) — you can only \
             publish to subdomains you own"
        )));
    }
    let token_id = match crate::app::registry::id_of_name(name).await {
        Ok(id) if id != 0 => id,
        Ok(_) => {
            return Err(crate::error::Error::other(format!(
                "\"{name}\" has an owner but no tokenId yet — retry shortly"
            )))
        }
        Err(e) => return Err(crate::error::Error::other(format!("id_of_name: {e}"))),
    };
    Ok(Some((token_id, owner)))
}

/// `create_and_publish_app(name, source)` — OWNERSHIP-AWARE one-shot publish:
/// - `name` UNREGISTERED → register `<name>.localharness.xyz` + publish the
///   compiled cartridge as its public face (a fresh subdomain for the app).
/// - `name` already owned by THE CALLER → UPDATE in place: re-publish app.wasm
///   + public_face via setMetadata, NO re-register, no duplicate.
/// - `name` owned by SOMEONE ELSE → refuse with a clear error.
///
/// Compiles `source` first (so a bad cartridge fails before any on-chain
/// write), then publishes via a SPONSORED setMetadata batch (app.wasm bytes +
/// public_face="app") in ONE Tempo tx — exactly like the admin publish-app
/// flow. A brand-new app never silently overwrites the owner's MAIN. Returns
/// `{ name, url, tx_hash, updated }`.
pub(crate) fn create_and_publish_app_tool() -> std::sync::Arc<dyn crate::tools::Tool> {
    let schema = serde_json::json!({
        "type": "object",
        "properties": {
            "name": {
                "type": "string",
                "description": "Subdomain to register, e.g. \"clock\" \
                    becomes clock.localharness.xyz. 3-32 chars; lowercase \
                    letters, digits, and hyphens only."
            },
            "source": {
                "type": "string",
                "description": "rustlite cartridge source — the SAME dialect as \
                    run_cartridge. Exports `fn frame(t: i32)` (animated) or \
                    `fn render()` and draws via `use host::display;`. This becomes \
                    the subdomain's fullscreen public face."
            },
            "persona": {
                "type": "string",
                "description": "OPTIONAL system instruction / persona for the new \
                    agent — published on-chain as its system prompt (read by \
                    headless `call`s). Omit to leave the default."
            },
            "prefund_lh": {
                "type": "string",
                "description": "OPTIONAL amount of $LH to prefund the new agent with, \
                    as a decimal string (\"5\", \"1.5\"). Transferred from YOUR \
                    wallet to the new subdomain's token-bound account (its own \
                    spendable wallet). Omit, or pass \"0\", to skip. Must not exceed \
                    your $LH balance."
            }
        },
        "required": ["name", "source"]
    });
    ClosureTool::new(
        "create_and_publish_app",
        "Publish a compiled rustlite cartridge as <name>.localharness.xyz's fullscreen \
         public face (compile + sponsored setMetadata publish). OWNERSHIP-AWARE: if \
         `name` is UNREGISTERED it registers a NEW subdomain first; if YOU already own \
         `name` it UPDATES that app in place (no re-register, no duplicate); if someone \
         ELSE owns `name` it refuses. Use this for \"make me a clock subdomain\" AND \
         \"update my <name> app\". The ACTOR MODEL (fresh names only): optionally also \
         set the new agent's `persona` (on-chain system instruction) and `prefund_lh` it \
         with $LH (into its token-bound account), all in the SAME sponsored tx. \
         create_subdomain remains for registering a name-only subdomain. Returns \
         { name, url, tx_hash, updated, persona_set?, prefunded_lh?, tba? }.",
        schema,
        |args: serde_json::Value, _ctx| async move {
            let name = args.get("name").and_then(|v| v.as_str()).unwrap_or("").trim();
            let source = args.get("source").and_then(|v| v.as_str()).unwrap_or("");
            let persona = args.get("persona").and_then(|v| v.as_str());
            let prefund_lh = args.get("prefund_lh").and_then(|v| v.as_str());
            let cleaned = crate::subdomain::validate(name)
                .map_err(|why| crate::error::Error::other(format!("invalid subdomain name: {why}")))?;
            // Compile FIRST (also bounds-checks size) so a bad cartridge fails
            // before any register/setMetadata write. This is the SAME shape the
            // update path uses; resolve the tokenId after we know it compiles.
            // (token_id is patched in once known — encode below.)
            if source.trim().is_empty() {
                return Err(crate::error::Error::other("source cannot be empty"));
            }
            // Who would sign? The owner of the current host subdomain — the
            // master wallet that holds ALL this identity's names. Used to decide
            // OWN vs SOMEONE-ELSE for an already-registered target.
            let signer_owner = crate::app::tenant::current_tenant_owner()
                .await
                .map(|(_, o)| o)
                .ok();

            // Branch on the target's on-chain ownership.
            let existing = match &signer_owner {
                Some(o) => owned_token_for_publish(&cleaned, o).await?,
                // Off a tenant host (preview/localhost) we can't prove the
                // signer's identity; fall back to "register if free", and a
                // taken name will be refused by the claim path.
                None => match crate::app::registry::owner_of_name(&cleaned).await {
                    Ok(Some(_)) => {
                        return Err(crate::error::Error::other(format!(
                            "\"{cleaned}\" is already registered — run this on your own \
                             subdomain so ownership can be verified before updating it"
                        )))
                    }
                    Ok(None) => None,
                    Err(e) => return Err(crate::error::Error::other(format!("owner_of_name: {e}"))),
                },
            };

            // UPDATE path: the caller already owns `name` → re-publish in place,
            // NO re-register (which would fail), NO persona/prefund (those are
            // spawn-time actor setup). One sponsored setMetadata batch.
            if let Some((token_id, owner)) = existing {
                let (calls, gas) = build_publish_app_calls(token_id, source)?;
                let tx_hash = crate::app::events::run_sponsored_tempo_call(
                    &owner,
                    calls,
                    gas,
                    "update published app",
                )
                .await
                .map_err(|e| crate::error::Error::other(format!("update failed: {e}")))?;
                return Ok(serde_json::json!({
                    "name": cleaned,
                    "url": format!("https://{cleaned}.localharness.xyz/"),
                    "tx_hash": tx_hash,
                    "updated": true,
                }));
            }

            // FRESH path: register the name, then publish. The owner's master
            // wallet ends up holding the new tokenId, so it's authorized to
            // setMetadata below.
            let (owner, _claim_tx) = crate::app::verify::claim_name_via_iframe(&cleaned)
                .await
                .map_err(|e| crate::error::Error::other(format!("claim failed: {e}")))?;
            // Inherit this device's Gemini key onto the new subdomain.
            {
                let n = cleaned.clone();
                wasm_bindgen_futures::spawn_local(async move {
                    crate::app::events::sync_local_key_to_main(&n).await;
                });
            }
            // Resolve the freshly-minted tokenId.
            let token_id = match crate::app::registry::id_of_name(&cleaned).await {
                Ok(id) if id != 0 => id,
                Ok(_) => {
                    return Err(crate::error::Error::other(
                        "registered but tokenId not yet visible on-chain — retry publish shortly",
                    ))
                }
                Err(e) => return Err(crate::error::Error::other(format!("id_of_name: {e}"))),
            };
            // Publish: app wasm bytes + public_face="app" in ONE sponsored
            // Tempo tx (two setMetadata calls), exactly like the admin
            // publish-app flow. Owner signs the sender_hash via the apex
            // iframe; the sponsor pays gas.
            let (mut calls, mut gas) = build_publish_app_calls(token_id, source)?;
            // ACTOR MODEL: fold optional persona + prefund into the SAME tx.
            let setup =
                build_actor_setup(&owner, token_id, &cleaned, persona, prefund_lh).await?;
            calls.extend(setup.calls);
            gas += setup.extra_gas;
            let tx_hash = crate::app::events::run_sponsored_tempo_call(
                &owner,
                calls,
                gas,
                "create + publish app",
            )
            .await
            .map_err(|e| crate::error::Error::other(format!("publish failed: {e}")))?;
            let mut result = serde_json::json!({
                "name": cleaned,
                "url": format!("https://{cleaned}.localharness.xyz/"),
                "tx_hash": tx_hash,
                "updated": false,
            });
            if setup.persona_set {
                result["persona_set"] = serde_json::json!(true);
            }
            if let Some(amt) = setup.prefunded_lh {
                result["prefunded_lh"] = serde_json::json!(amt);
            }
            if let Some(tba) = setup.tba {
                result["tba"] = serde_json::json!(tba);
            }
            Ok(result)
        },
    )
}

/// `publish_app_to(name, source, confirmation)` — UPDATE-FROM-MAIN: publish a
/// compiled cartridge to ANY subdomain the caller OWNS, even one DIFFERENT from
/// the current host. The owner's master wallet (the one that signs the current
/// host's sponsored writes) holds all their subdomain NFTs, so it can sign a
/// `setMetadata` for any owned tokenId — no new ownership/actor model needed,
/// just targeting a chosen owned name. From a MAIN session this updates any
/// alt's app. The target MUST already be registered AND owned by the caller
/// (refuses unregistered names — use `create_and_publish_app` to mint a fresh
/// one — and names owned by someone else). MOVES on-chain state, so it rides
/// the typed-confirmation gate (`chat::confirm_guard`). NOT granted to
/// subagents. Returns `{ name, url, tx_hash, updated: true }`.
pub(crate) fn publish_app_to_tool() -> std::sync::Arc<dyn crate::tools::Tool> {
    let schema = serde_json::json!({
        "type": "object",
        "properties": {
            "name": {
                "type": "string",
                "description": "The subdomain to publish to — MUST be one you already \
                    own (e.g. \"clock\" → clock.localharness.xyz). Can be different from \
                    the subdomain you are currently on. To create a NEW subdomain, use \
                    create_and_publish_app instead."
            },
            "source": {
                "type": "string",
                "description": "rustlite cartridge source — the SAME dialect as \
                    run_cartridge / create_and_publish_app. Exports `fn frame(t: i32)` \
                    (animated) or `fn render()` and draws via `use host::display;`. \
                    Becomes the target subdomain's fullscreen public face."
            },
            "confirmation": {
                "type": "string",
                "description": "Single-use confirmation code. OMIT (or pass \"\") on the \
                    first call — it returns a challenge code shown to the owner. State \
                    which subdomain you will update, ask the owner to TYPE the code in \
                    chat, then retry with it. Never invent it; only the platform issues it."
            }
        },
        "required": ["name", "source"]
    });
    ClosureTool::new(
        "publish_app_to",
        "Publish (UPDATE) a rustlite cartridge to ANOTHER subdomain you OWN — the \
         update-from-MAIN path. The owner's master wallet holds all their subdomain \
         NFTs, so from one session you can re-publish any of your alts' apps. The \
         target must ALREADY exist and be owned by you (to mint a NEW subdomain use \
         create_and_publish_app; that tool also updates the CURRENT name in place). \
         CHANGES on-chain state — the first call does NOT execute: it returns a \
         single-use confirmation code (also shown to the owner in the UI). Say which \
         subdomain you'll update, ask the owner to TYPE the code, then retry with \
         `confirmation` set to it. Returns { name, url, tx_hash, updated: true }.",
        schema,
        |args: serde_json::Value, _ctx| async move {
            let name = args.get("name").and_then(|v| v.as_str()).unwrap_or("").trim();
            let source = args.get("source").and_then(|v| v.as_str()).unwrap_or("");
            // Belt-and-suspenders: the confirm_guard hook denies any unconfirmed
            // call before this body runs; this guards a registration path that
            // forgot the hook (same posture as send_lh / release_subdomain).
            let confirmed = args
                .get("confirmation")
                .and_then(|v| v.as_str())
                .map(|s| !s.trim().is_empty())
                .unwrap_or(false);
            if !confirmed {
                return Err(crate::error::Error::other(
                    "publish_app_to requires the platform-issued confirmation code",
                ));
            }
            let cleaned = crate::subdomain::validate(name)
                .map_err(|why| crate::error::Error::other(format!("invalid subdomain name: {why}")))?;
            if source.trim().is_empty() {
                return Err(crate::error::Error::other("source cannot be empty"));
            }
            // The signer = the current host's owner (the master wallet holding
            // ALL this identity's names). Required so we can prove ownership of a
            // DIFFERENT target name before writing to it.
            let (_, signer_owner) = crate::app::tenant::current_tenant_owner()
                .await
                .map_err(crate::error::Error::other)?;
            // Resolve + ownership-gate the target. None = unregistered (refuse —
            // this tool only UPDATES owned names); Err = owned-by-other / RPC.
            let (token_id, owner) = owned_token_for_publish(&cleaned, &signer_owner)
                .await?
                .ok_or_else(|| {
                    crate::error::Error::other(format!(
                        "\"{cleaned}\" is not registered — use create_and_publish_app to \
                         mint and publish a new subdomain"
                    ))
                })?;
            let (calls, gas) = build_publish_app_calls(token_id, source)?;
            let tx_hash = crate::app::events::run_sponsored_tempo_call(
                &owner,
                calls,
                gas,
                "publish app to owned subdomain",
            )
            .await
            .map_err(|e| crate::error::Error::other(format!("publish failed: {e}")))?;
            Ok(serde_json::json!({
                "name": cleaned,
                "url": format!("https://{cleaned}.localharness.xyz/"),
                "tx_hash": tx_hash,
                "updated": true,
            }))
        },
    )
}

/// `embed_app(name)` — fetch ANOTHER subdomain's published cartridge and
/// render it INLINE in the chat transcript as a live, interactive card (NOT
/// an iframe — cartridges are framebuffer wasm; an iframe of a subdomain that
/// itself boots a cartridge hits recursion/partitioning limits). Resolves
/// `name` → tokenId → on-chain `app.wasm`; if the subdomain has a published
/// cartridge, stashes its bytes for the transcript's `#embed-canvas` card to
/// launch (via `display::run_in_canvas`) and returns `{ name, url,
/// embedded: true }`. A subdomain with no published app (directory/html face,
/// or never published) returns a clear error.
///
/// v1 limitations (documented for the agent): (1) SINGLE-WORKER — embedding
/// replaces any cartridge already running (a prior embed or the fullscreen
/// overlay); only one live embed at a time. (2) The embedded cartridge's
/// host_agent FEED context (subscribe/viewer_is_owner/…) resolves against the
/// HOST page's subdomain, not the embedded one — cross-subdomain feed identity
/// is a follow-up.
pub(crate) fn embed_app_tool() -> std::sync::Arc<dyn crate::tools::Tool> {
    let schema = serde_json::json!({
        "type": "object",
        "properties": {
            "name": {
                "type": "string",
                "description": "Subdomain whose published cartridge to embed, \
                    e.g. \"pong\" embeds pong.localharness.xyz's app inline."
            }
        },
        "required": ["name"]
    });
    ClosureTool::new(
        "embed_app",
        "Embed another subdomain's published cartridge INLINE in this chat as a \
         live, interactive card (the cartridge runs in the framebuffer, like the \
         display — NOT an iframe). Use this to show/play <name>'s app right here \
         (\"embed pong\", \"show me <name>'s app\"). Single live embed at a time: \
         embedding replaces any cartridge already running. Only works when <name> \
         has PUBLISHED a cartridge (an app public face) — directory/html faces or \
         unpublished names return an error. Returns { name, url, embedded: true }.",
        schema,
        |args: serde_json::Value, _ctx| async move {
            let name = args.get("name").and_then(|v| v.as_str()).unwrap_or("").trim();
            let cleaned = crate::app::tenant::sanitize(name);
            if cleaned.is_empty() {
                return Err(crate::error::Error::other("name cannot be empty"));
            }
            let token_id = match crate::app::registry::id_of_name(&cleaned).await {
                Ok(id) if id != 0 => id,
                Ok(_) => {
                    return Err(crate::error::Error::other(format!(
                        "\"{cleaned}\" is not registered"
                    )))
                }
                Err(e) => return Err(crate::error::Error::other(format!("id_of_name: {e}"))),
            };
            let wasm = match crate::app::registry::app_wasm_of(token_id).await {
                Ok(Some(bytes)) if !bytes.is_empty() => bytes,
                Ok(_) => {
                    return Err(crate::error::Error::other(format!(
                        "{cleaned} has no published cartridge — only directory/html \
                         faces or unpublished"
                    )))
                }
                Err(e) => return Err(crate::error::Error::other(format!("app_wasm_of: {e}"))),
            };
            // Stash the bytes; `chat::stream_turn` launches them into the
            // `#embed-canvas` card once the inline card has painted.
            crate::app::display::stash_pending_embed(wasm);
            Ok(serde_json::json!({
                "name": cleaned,
                "url": format!("https://{cleaned}.localharness.xyz/"),
                "embedded": true,
            }))
        },
    )
}

/// `publish_public_face(choice)` — publish THIS agent's OWN public face
/// on-chain from chat (the agent-tool mirror of admin → public face, on-chain
/// feature request #27). `choice` is "directory" | "app" | "html": "app"
/// compiles + publishes this device's local `app.rl` cartridge, "html"
/// publishes local `index.html`, "directory" sets the profile-landing face —
/// each writes the choice under `keccak256("localharness.public_face")` (which
/// every visitor honours) plus the bytes, in ONE sponsored Tempo tx. Owner-only,
/// own subdomain only. Mirrors `events::public_face::run_set_public_face` minus
/// the DOM; submits through the same `run_sponsored_tempo_call` path as
/// `create_and_publish_app` (so it covers the common EOA-owner case; the admin
/// UI still owns the TBA-consolidation path). Reversible — republish anytime.
pub(crate) fn publish_public_face_tool() -> std::sync::Arc<dyn crate::tools::Tool> {
    let schema = serde_json::json!({
        "type": "object",
        "properties": {
            "choice": {
                "type": "string",
                "description": "Which face to publish: \"app\" (compile + publish \
                    this device's local app.rl as a fullscreen cartridge), \
                    \"html\" (publish local index.html), or \"directory\" (a \
                    profile landing listing your sibling agents)."
            }
        },
        "required": ["choice"]
    });
    ClosureTool::new(
        "publish_public_face",
        "Publish YOUR OWN public face on-chain — what a visitor to \
         https://<you>.localharness.xyz/ sees — the chat equivalent of admin → \
         public face. `choice`: \"app\" compiles + publishes this device's local \
         app.rl as a fullscreen cartridge; \"html\" publishes local index.html; \
         \"directory\" sets a profile landing. Publishes the bytes AND sets the \
         on-chain face choice in ONE sponsored (free, zero-click) tx. Works only \
         on your own subdomain. After it succeeds, give the user the returned \
         `url`. Returns { choice, url, tx_hash }.",
        schema,
        |args: serde_json::Value, _ctx| async move {
            let choice = args
                .get("choice")
                .and_then(|v| v.as_str())
                .unwrap_or("")
                .trim()
                .to_lowercase();
            if !matches!(choice.as_str(), "directory" | "app" | "html") {
                return Err(crate::error::Error::other(
                    "choice must be \"directory\", \"app\", or \"html\"",
                ));
            }
            let Some(name) = crate::app::tenant::current_name() else {
                return Err(crate::error::Error::other(
                    "publish_public_face only works on your own subdomain",
                ));
            };
            let token_id = match crate::app::registry::id_of_name(&name).await {
                Ok(id) if id != 0 => id,
                _ => return Err(crate::error::Error::other("name isn't registered on-chain")),
            };
            let owner = match crate::app::registry::owner_of_name(&name).await {
                Ok(Some(o)) => o,
                _ => return Err(crate::error::Error::other("name isn't registered on-chain")),
            };
            let registry_addr = parse_address(crate::app::registry::REGISTRY_ADDRESS())
                .map_err(crate::error::Error::other)?;
            let mk = |input: Vec<u8>| crate::tempo_tx::TempoCall {
                to: registry_addr,
                value_wei: 0,
                input,
            };
            // Build the call batch + gas for the chosen face — the same shapes
            // as the admin flow (storing bytes is ~7.6k gas/BYTE on top of the
            // ~275k Tempo sponsorship; `set_metadata_gas` length-scales it).
            let (calls, gas): (Vec<crate::tempo_tx::TempoCall>, u128) = match choice.as_str() {
                "directory" => (
                    vec![mk(crate::app::registry::encode_set_public_face(token_id, "directory"))],
                    500_000,
                ),
                "app" => {
                    let fs = crate::app::shared_opfs();
                    let src = match fs.read("app.rl").await {
                        Ok(b) if !b.is_empty() => String::from_utf8_lossy(&b).into_owned(),
                        _ => {
                            return Err(crate::error::Error::other(
                                "no app.rl on this device — build one first (run_cartridge), \
                                 then publish",
                            ))
                        }
                    };
                    let wasm = crate::rustlite::compile(&src).map_err(|e| {
                        let loc = e.location(&src).map(|l| format!(" ({l})")).unwrap_or_default();
                        crate::error::Error::other(format!("app.rl compile error: {e}{loc}"))
                    })?;
                    if wasm.len() > 16_384 {
                        return Err(crate::error::Error::other(
                            "app wasm too large to publish (max 16 KB)",
                        ));
                    }
                    (
                        vec![
                            mk(crate::app::registry::encode_set_app_wasm(token_id, &wasm)),
                            mk(crate::app::registry::encode_set_public_face(token_id, "app")),
                        ],
                        crate::app::gas::set_metadata_gas(wasm.len()),
                    )
                }
                "html" => {
                    let fs = crate::app::shared_opfs();
                    let html = match fs.read("index.html").await {
                        Ok(b) if !b.is_empty() => b,
                        _ => {
                            return Err(crate::error::Error::other(
                                "no index.html on this device — create one first, then publish",
                            ))
                        }
                    };
                    if html.len() > 24_576 {
                        return Err(crate::error::Error::other(
                            "index.html too large to publish (max 24 KB)",
                        ));
                    }
                    (
                        vec![
                            mk(crate::app::registry::encode_set_public_html(token_id, &html)),
                            mk(crate::app::registry::encode_set_public_face(token_id, "html")),
                        ],
                        crate::app::gas::set_metadata_gas(html.len()),
                    )
                }
                _ => unreachable!(),
            };
            let tx_hash =
                crate::app::events::run_sponsored_tempo_call(&owner, calls, gas, "publish public face")
                    .await
                    .map_err(|e| crate::error::Error::other(format!("publish failed: {e}")))?;
            Ok(serde_json::json!({
                "choice": choice,
                "url": format!("https://{name}.localharness.xyz/"),
                "tx_hash": tx_hash,
            }))
        },
    )
}

/// `release_subdomain(name, confirmation)` — DESTRUCTIVE: burn the NFT +
/// free the name. Gated by the dispatch-layer typed-confirmation challenge
/// (`chat::confirm_guard`): the first call is denied with a single-use code
/// the OWNER must type in chat; only the retry carrying that code executes.
/// The model cannot auto-fill it (the code is random and must appear in the
/// latest USER message).
pub(crate) fn release_subdomain_tool() -> std::sync::Arc<dyn crate::tools::Tool> {
    let schema = serde_json::json!({
        "type": "object",
        "properties": {
            "name": {
                "type": "string",
                "description": "Subdomain to release/recycle — burns the NFT, frees the name."
            },
            "confirmation": {
                "type": "string",
                "description": "Single-use confirmation code. OMIT (or pass \"\") on the \
                    first call — it returns a challenge code that is shown to the owner. \
                    Relay it, wait for the owner to TYPE that code in chat, then retry \
                    with the code here. Never invent it; only the platform issues it."
            }
        },
        "required": ["name"]
    });
    ClosureTool::new(
        "release_subdomain",
        "DESTRUCTIVE + IRREVERSIBLE: burn a subdomain NFT and free its name. The first \
         call does NOT execute: it returns a single-use confirmation code (also shown to \
         the owner in the UI). Ask the owner to TYPE that code in chat, then retry with \
         `confirmation` set to it — the call only executes after the owner's message \
         contains the code. Refuses your MAIN. Returns the tx hash.",
        schema,
        |args: serde_json::Value, _ctx| async move {
            let name = args.get("name").and_then(|v| v.as_str()).unwrap_or("").trim().to_string();
            if name.is_empty() {
                return Err(crate::error::Error::other("name is required"));
            }
            // The typed-confirmation gate (confirm_guard) runs BEFORE this body
            // and denies any call without a user-typed challenge code. This
            // belt-and-suspenders check only guards a registration path that
            // forgot the hook.
            let confirmed = args
                .get("confirmation")
                .and_then(|v| v.as_str())
                .map(|s| !s.trim().is_empty())
                .unwrap_or(false);
            if !confirmed {
                return Err(crate::error::Error::other(
                    "release_subdomain requires the platform-issued confirmation code",
                ));
            }
            match crate::app::events::run_release_subdomain(&name).await {
                Ok(tx) => Ok(serde_json::json!({ "released": name, "tx_hash": tx })),
                Err(e) => Err(crate::error::Error::other(format!("release failed: {e}"))),
            }
        },
    )
}

/// `bulk_release_subdomains(confirmation, names?)` — DESTRUCTIVE batch burn.
/// With no `names`, targets EVERY non-MAIN subdomain the owner holds; with
/// `names`, only that subset. Gated by the dispatch-layer typed-confirmation
/// challenge (`chat::confirm_guard`) — ONE single-use code for the whole
/// batch, typed by the owner. Refuses the MAIN. Withheld from subagents
/// (only registered on the main agent).
pub(crate) fn bulk_release_subdomains_tool() -> std::sync::Arc<dyn crate::tools::Tool> {
    let schema = serde_json::json!({
        "type": "object",
        "properties": {
            "names": {
                "type": "array",
                "items": { "type": "string" },
                "description": "OPTIONAL subset of subdomain names to release in one \
                    batch. Omit to target EVERY non-MAIN subdomain the owner holds."
            },
            "confirmation": {
                "type": "string",
                "description": "Single-use confirmation code. OMIT (or pass \"\") on the \
                    first call — it returns a challenge code shown to the owner. Show the \
                    owner the exact list that will be burned (list_subdomains is the \
                    read-only source), ask them to TYPE the code, then retry with it. \
                    Never invent it; only the platform issues it."
            }
        },
        "required": []
    });
    ClosureTool::new(
        "bulk_release_subdomains",
        "DESTRUCTIVE + IRREVERSIBLE: burn MANY subdomain NFTs and free their names in \
         ONE batch. With no `names`, releases EVERY non-MAIN subdomain the owner holds; \
         with `names`, only that subset. The first call does NOT execute: it returns a \
         single-use confirmation code (also shown to the owner in the UI). Show the owner \
         the exact list that will be burned (use list_subdomains), ask them to TYPE the \
         code, then retry with `confirmation` set to it. ONE code for the whole batch. \
         Always refuses your MAIN. Returns the released names + tx hash.",
        schema,
        |args: serde_json::Value, _ctx| async move {
            // The typed-confirmation gate (confirm_guard) runs BEFORE this
            // body; an unconfirmed call never reaches it. Belt-and-suspenders
            // for any registration path that forgot the hook.
            let confirmed = args
                .get("confirmation")
                .and_then(|v| v.as_str())
                .map(|s| !s.trim().is_empty())
                .unwrap_or(false);
            if !confirmed {
                return Err(crate::error::Error::other(
                    "bulk_release_subdomains requires the platform-issued confirmation code",
                ));
            }

            // Resolve the kill-list: explicit subset, else all non-MAIN holdings.
            let (_, owner) = crate::app::tenant::current_tenant_owner()
                .await
                .map_err(crate::error::Error::other)?;
            let main_id = crate::app::registry::main_of(&owner)
                .await
                .map_err(crate::error::Error::other)?;

            let explicit: Vec<String> = args
                .get("names")
                .and_then(|v| v.as_array())
                .map(|a| {
                    a.iter()
                        .filter_map(|v| v.as_str())
                        .map(|s| s.trim().to_string())
                        .filter(|s| !s.is_empty())
                        .collect()
                })
                .unwrap_or_default();

            let targets: Vec<String> = if explicit.is_empty() {
                let tokens = crate::app::registry::list_owned_tokens(&owner)
                    .await
                    .map_err(crate::error::Error::other)?;
                tokens
                    .into_iter()
                    .filter(|t| main_id == 0 || t.token_id != main_id)
                    .map(|t| t.name)
                    .collect()
            } else {
                explicit
            };

            if targets.is_empty() {
                return Ok(serde_json::json!({
                    "status": "nothing_to_release",
                    "note": "no non-MAIN subdomains to release"
                }));
            }

            match crate::app::events::run_bulk_release(&targets).await {
                Ok((released, tx)) => Ok(serde_json::json!({
                    "released": released,
                    "count": released.len(),
                    "tx_hash": tx,
                })),
                Err(e) => Err(crate::error::Error::other(format!("bulk release failed: {e}"))),
            }
        },
    )
}

/// `batch_create_subdomains(names)` — register MANY subdomains in ONE
/// sponsored multi-call tx (the mirror of `bulk_release_subdomains`, but
/// ADDITIVE: NO destructive confirmation). The sanctioned mass-registration
/// path — one tx instead of an N-deep `create_subdomain` loop. Names are
/// sanitised + availability-checked; taken/invalid names are skipped and
/// reported. Capped at MAX_BATCH_CREATE to bound a confused model. Not
/// granted to subagents (same restraint as bulk_release).
pub(crate) fn batch_create_subdomains_tool() -> std::sync::Arc<dyn crate::tools::Tool> {
    let schema = serde_json::json!({
        "type": "object",
        "properties": {
            "names": {
                "type": "array",
                "items": { "type": "string" },
                "description": "Subdomain names to register in ONE tx, e.g. \
                    [\"alice\",\"bob\"] -> alice.localharness.xyz, \
                    bob.localharness.xyz. Each: 3-32 chars, lowercase letters, \
                    digits, hyphens. Already-taken or invalid names are skipped \
                    and reported back. Max 20 per call."
            }
        },
        "required": ["names"]
    });
    ClosureTool::new(
        "batch_create_subdomains",
        "Register MANY <name>.localharness.xyz subdomains on-chain in a SINGLE \
         sponsored transaction. PREFER THIS over calling create_subdomain in a \
         loop when registering more than one name — it is one tx, not N. The \
         owner's master wallet ends up holding every resulting ERC-721 NFT. \
         Taken or invalid names are skipped (not an error) and listed in \
         `skipped`. Max 20 names per call. Returns { registered, skipped, \
         count, tx_hash, urls }.",
        schema,
        |args: serde_json::Value, _ctx| async move {
            const MAX_BATCH_CREATE: usize = 20;
            let requested: Vec<String> = args
                .get("names")
                .and_then(|v| v.as_array())
                .map(|a| {
                    a.iter()
                        .filter_map(|v| v.as_str())
                        .map(|s| s.trim().to_string())
                        .filter(|s| !s.is_empty())
                        .collect()
                })
                .unwrap_or_default();
            if requested.is_empty() {
                return Err(crate::error::Error::other("names cannot be empty"));
            }
            if requested.len() > MAX_BATCH_CREATE {
                return Err(crate::error::Error::other(format!(
                    "too many names: {} (max {MAX_BATCH_CREATE} per batch) — \
                     split into multiple calls",
                    requested.len()
                )));
            }
            match crate::app::events::run_batch_create_subdomains(&requested).await {
                Ok((registered, tx)) => {
                    let skipped: Vec<&String> = requested
                        .iter()
                        .filter(|r| {
                            let c = crate::app::tenant::sanitize(r);
                            !registered.iter().any(|reg| reg == &c)
                        })
                        .collect();
                    Ok(serde_json::json!({
                        "registered": registered,
                        "skipped": skipped,
                        "count": registered.len(),
                        "tx_hash": tx,
                        "urls": registered.iter()
                            .map(|n| format!("https://{n}.localharness.xyz/"))
                            .collect::<Vec<_>>(),
                    }))
                }
                Err(e) => Err(crate::error::Error::other(format!(
                    "batch create failed: {e}"
                ))),
            }
        },
    )
}

/// `list_subdomains()` — enumerate every subdomain this agent's owner
/// holds (their identity's holdings). Read-only.
pub(crate) fn list_subdomains_tool() -> std::sync::Arc<dyn crate::tools::Tool> {
    ClosureTool::new(
        "list_subdomains",
        "List every subdomain owned by this agent's owner (their identity's holdings on \
         the registry). Read-only. Use when the user asks what subdomains/agents they have.",
        serde_json::json!({ "type": "object", "properties": {} }),
        |_args: serde_json::Value, _ctx| async move {
            let (_, owner) = crate::app::tenant::current_tenant_owner()
                .await
                .map_err(crate::error::Error::other)?;
            let tokens = crate::app::registry::list_owned_tokens(&owner)
                .await
                .map_err(crate::error::Error::other)?;
            let subdomains: Vec<_> = tokens
                .iter()
                .map(|t| {
                    serde_json::json!({
                        "name": t.name,
                        "url": format!("https://{}.localharness.xyz/", t.name),
                        "token_id": t.token_id,
                    })
                })
                .collect();
            Ok(serde_json::json!({
                "owner": owner,
                "count": subdomains.len(),
                "subdomains": subdomains,
            }))
        },
    )
}

/// `discover_agents(query)` — find peer agents by capability/persona. The
/// browser twin of the `localharness discover` CLI command: a read-only
/// registry scan (no `$LH`, no tx) that reuses [`registry::discover_agents`]
/// (which ranks `(name, persona)` matches — name hits above persona hits). The
/// agent uses it to LOCATE a peer to delegate to, then `call_agent`s it.
/// Returns `{ agents: [{ name, persona }], count }`; persona snippets are
/// truncated to a char-safe ~160-char preview. Safe to grant broadly.
pub(crate) fn discover_agents_tool() -> std::sync::Arc<dyn crate::tools::Tool> {
    /// Char-safe truncation of a persona to a short preview (never splits a
    /// UTF-8 codepoint; appends an ellipsis when clipped).
    fn snippet(persona: &str) -> String {
        const MAX: usize = 160;
        let trimmed = persona.trim();
        if trimmed.chars().count() <= MAX {
            return trimmed.to_string();
        }
        let mut s: String = trimmed.chars().take(MAX).collect();
        s.push('');
        s
    }
    ClosureTool::new(
        "discover_agents",
        "Find peer agents by capability or persona. Read-only registry scan: \
         returns the agents whose subdomain NAME or on-chain persona matches \
         `query`. MULTI-KEYWORD: the query is split on whitespace and an agent \
         matches ANY keyword, ranked by how many it matches (name matches above \
         persona matches) — so ONE call with \"game tool puzzle\" replaces a \
         sequential call per keyword. Use this to LOCATE an agent to delegate \
         to, then call_agent it. Returns { agents: [ { name, persona } ], \
         count } (persona is a short preview).",
        serde_json::json!({
            "type": "object",
            "properties": {
                "query": {
                    "type": "string",
                    "description": "What to look for — capabilities, topics, or \
                        keywords matched (case-insensitively) against agent names \
                        and personas. Several keywords are ORed and ranked by \
                        overlap (e.g. \"solidity audit security\"). \
                        Empty returns recent agents."
                }
            },
            "required": ["query"]
        }),
        |args: serde_json::Value, _ctx| async move {
            let query = args
                .get("query")
                .and_then(|v| v.as_str())
                .unwrap_or("")
                .to_string();
            // Reuse the registry's ranked discovery (same core as the
            // `localharness discover` CLI). 100 = how many recent agents to scan.
            let matches = crate::app::registry::discover_agents(&query, 100)
                .await
                .map_err(crate::error::Error::other)?;
            let agents: Vec<_> = matches
                .iter()
                .map(|(name, persona)| {
                    serde_json::json!({
                        "name": name,
                        "persona": snippet(persona),
                    })
                })
                .collect();
            Ok(serde_json::json!({
                "count": agents.len(),
                "agents": agents,
            }))
        },
    )
}

/// `send_lh(recipient, amount)` — transfer real `$LH` credits from the owner's
/// wallet. `recipient` is either a raw `0x…` address or a subdomain name (whose
/// on-chain OWNER address receives the funds). `amount` is a human-typed `$LH`
/// figure (18-decimal token; "5", "1.5", "0.000001"). Builds an ERC-20
/// `transfer(to, amount_wei)` against the `$LH` token and routes it through the
/// SAME sponsored Tempo path as the per-turn payment + the "act" panel
/// (`run_sponsored_tempo_call`): the owner's apex wallet signs the intent, the
/// bundle sponsor pays gas in AlphaUSD. NOT granted to subagents (it moves
/// value). Gated by the dispatch-layer typed-confirmation challenge
/// (`chat::confirm_guard`): the owner types a single-use code before any
/// transfer executes. Amount must parse to > 0.
pub(crate) fn send_lh_tool() -> std::sync::Arc<dyn crate::tools::Tool> {
    let schema = serde_json::json!({
        "type": "object",
        "properties": {
            "recipient": {
                "type": "string",
                "description": "Who receives the $LH: either a raw 0x… 20-byte \
                    address, or a subdomain name like \"alice\" (the funds go to \
                    that subdomain's on-chain OWNER address)."
            },
            "amount": {
                "type": "string",
                "description": "Amount of $LH to send, as a decimal string \
                    (e.g. \"5\", \"1.5\", \"0.01\"). Must be greater than 0."
            },
            "confirmation": {
                "type": "string",
                "description": "Single-use confirmation code. OMIT (or pass \"\") on the \
                    first call — it returns a challenge code shown to the owner. Relay \
                    it, wait for the owner to TYPE the code in chat, then retry with it. \
                    Never invent it; only the platform issues it."
            }
        },
        "required": ["recipient", "amount"]
    });
    ClosureTool::new(
        "send_lh",
        "Transfer real $LH credits from the owner's wallet to a recipient. \
         `recipient` is a raw 0x… address OR a subdomain name (funds go to that \
         name's on-chain owner). `amount` is a decimal $LH figure (must be > 0). \
         MOVES VALUE — the first call does NOT execute: it returns a single-use \
         confirmation code (also shown to the owner in the UI). State the \
         recipient + amount, ask the owner to TYPE the code, then retry with \
         `confirmation` set to it. Returns { amount, recipient (input), \
         resolved_recipient, tx_hash }.",
        schema,
        |args: serde_json::Value, _ctx| async move {
            use crate::encoding::parse_token_amount;

            let recipient_arg = args
                .get("recipient")
                .and_then(|v| v.as_str())
                .unwrap_or("")
                .trim()
                .to_string();
            let amount_arg = args
                .get("amount")
                .and_then(|v| v.as_str())
                .unwrap_or("")
                .trim()
                .to_string();

            // Amount: parse to 18-decimal wei (same units as the act panel /
            // per-turn payment), reject zero / garbage.
            let amount_wei = parse_token_amount(&amount_arg).ok_or_else(|| {
                crate::error::Error::other(format!(
                    "could not parse amount \"{amount_arg}\" — pass a decimal $LH \
                     figure like \"5\" or \"1.5\""
                ))
            })?;
            if amount_wei == 0 {
                return Err(crate::error::Error::other(
                    "amount must be greater than 0",
                ));
            }

            // Recipient: address used directly; name → on-chain owner address.
            let to_hex = resolve_lh_recipient(&recipient_arg).await?;

            // Sender = this subdomain's on-chain owner (the apex wallet that
            // signs via the iframe), matching list_subdomains / bulk_release.
            let (_, from) = crate::app::tenant::current_tenant_owner()
                .await
                .map_err(crate::error::Error::other)?;

            // Meter auto-bridge (feedback #48): a wallet shortfall covered by
            // unspent chat credits rides as a withdrawCredits call in the SAME
            // tx, so the transfer lands atomically. Then the ERC-20
            // transfer(to, amount) — the same calldata shape the per-turn
            // payment + act panel build.
            let mut calls = Vec::with_capacity(2);
            let bridged = match meter_bridge_call(&from, amount_wei).await? {
                Some(bridge) => {
                    calls.push(bridge);
                    true
                }
                None => false,
            };
            calls.push(lh_transfer_call(&to_hex, amount_wei)?);

            let amount_display = amount_arg.clone();
            let purpose = format!("send {amount_display} $LH to {to_hex}");
            // 500k mirrors the per-turn payment's ERC-20 transfer budget (+150k
            // when the bridge call rides along); the sponsor is billed on gas
            // USED, not the limit.
            let gas = if bridged { 650_000 } else { 500_000 };
            let tx_hash =
                crate::app::events::run_sponsored_tempo_call(&from, calls, gas, &purpose)
                    .await
                    .map_err(|e| crate::error::Error::other(format!("send_lh failed: {e}")))?;

            // #50: ping the recipient that funds arrived (best-effort, rides the
            // send — never a transfer-watch system). Fire-and-forget so it can't
            // fail or delay the tool result for a settled transfer.
            notify_recipient_of_incoming_lh(
                recipient_arg.clone(),
                to_hex.clone(),
                amount_display.clone(),
            );

            Ok(serde_json::json!({
                "amount": amount_display,
                "recipient": recipient_arg,
                "resolved_recipient": to_hex,
                "bridged_from_meter": bridged,
                "tx_hash": tx_hash,
            }))
        },
    )
}

/// `batch_send_lh(transfers)` — N transfers in ONE sponsored Tempo tx
/// (feedback #49: tx type 0x76 natively carries a calls array, so batching
/// costs one submission instead of N). The meter auto-bridge covers the
/// TOTAL if the wallet is short. Gated by the dispatch-layer
/// typed-confirmation challenge (`chat::confirm_guard`), same as `send_lh`.
pub(crate) fn batch_send_lh_tool() -> std::sync::Arc<dyn crate::tools::Tool> {
    let schema = serde_json::json!({
        "type": "object",
        "properties": {
            "transfers": {
                "type": "array",
                "description": "Up to 20 transfers, executed atomically in one \
                    on-chain transaction.",
                "items": {
                    "type": "object",
                    "properties": {
                        "recipient": {
                            "type": "string",
                            "description": "0x… address or subdomain name (funds \
                                go to the name's on-chain owner)."
                        },
                        "amount": {
                            "type": "string",
                            "description": "Decimal $LH amount, e.g. \"1\" or \
                                \"0.5\". Must be greater than 0."
                        }
                    },
                    "required": ["recipient", "amount"]
                }
            },
            "confirmation": {
                "type": "string",
                "description": "Single-use confirmation code. OMIT (or pass \"\") on the \
                    first call — it returns a challenge code shown to the owner. Show the \
                    full transfer list, ask the owner to TYPE the code in chat, then \
                    retry with it. Never invent it; only the platform issues it."
            }
        },
        "required": ["transfers"]
    });
    ClosureTool::new(
        "batch_send_lh",
        "Transfer $LH to MULTIPLE recipients in ONE on-chain transaction (up \
         to 20). Each transfer names a 0x… address or a subdomain (paid to its \
         on-chain owner). Far cheaper than repeated send_lh calls. MOVES VALUE \
         — the first call does NOT execute: it returns a single-use confirmation \
         code (also shown to the owner in the UI). Show the full list, ask the \
         owner to TYPE the code, then retry with `confirmation` set to it. ONE \
         code for the whole batch. Returns { count, total, transfers: \
         [{recipient, resolved, amount}], tx_hash }.",
        schema,
        |args: serde_json::Value, _ctx| async move {
            use crate::encoding::parse_token_amount;

            let items = args
                .get("transfers")
                .and_then(|v| v.as_array())
                .cloned()
                .unwrap_or_default();
            if items.is_empty() {
                return Err(crate::error::Error::other(
                    "batch_send_lh: transfers must be a non-empty array",
                ));
            }
            if items.len() > 20 {
                return Err(crate::error::Error::other(
                    "batch_send_lh: at most 20 transfers per batch",
                ));
            }

            let mut resolved: Vec<(String, String, u128, String)> =
                Vec::with_capacity(items.len());
            let mut total_wei: u128 = 0;
            for item in &items {
                let recipient = item
                    .get("recipient")
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .trim()
                    .to_string();
                let amount_str = item
                    .get("amount")
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .trim()
                    .to_string();
                let amount_wei = parse_token_amount(&amount_str).ok_or_else(|| {
                    crate::error::Error::other(format!(
                        "could not parse amount \"{amount_str}\" for \"{recipient}\""
                    ))
                })?;
                if amount_wei == 0 {
                    return Err(crate::error::Error::other(format!(
                        "amount for \"{recipient}\" must be greater than 0"
                    )));
                }
                let to_hex = resolve_lh_recipient(&recipient).await?;
                // checked, not saturating: a hostile/overflowing total must be a
                // clear error (matching parse_token_amount's reject-don't-wrap
                // contract), not a silently-clamped wrong bridge/display amount.
                total_wei = total_wei.checked_add(amount_wei).ok_or_else(|| {
                    crate::error::Error::other(
                        "batch total exceeds the maximum representable amount — split the batch",
                    )
                })?;
                resolved.push((recipient, to_hex, amount_wei, amount_str));
            }

            let (_, from) = crate::app::tenant::current_tenant_owner()
                .await
                .map_err(crate::error::Error::other)?;

            let mut calls = Vec::with_capacity(resolved.len() + 1);
            let bridged = match meter_bridge_call(&from, total_wei).await? {
                Some(bridge) => {
                    calls.push(bridge);
                    true
                }
                None => false,
            };
            for (_, to_hex, amount_wei, _) in &resolved {
                calls.push(lh_transfer_call(to_hex, *amount_wei)?);
            }

            let purpose = format!(
                "batch-send {} $LH to {} recipients",
                crate::app::format_wei_as_test_eth(total_wei),
                resolved.len()
            );
            // 500k base (first transfer + sponsorship overhead) + ~80k per
            // additional warm transfer + 150k when the bridge rides along.
            let gas = 500_000
                + 80_000 * (resolved.len() as u128 - 1)
                + if bridged { 150_000 } else { 0 };
            let tx_hash =
                crate::app::events::run_sponsored_tempo_call(&from, calls, gas, &purpose)
                    .await
                    .map_err(|e| {
                        crate::error::Error::other(format!("batch_send_lh failed: {e}"))
                    })?;

            // #50: ping each recipient that funds arrived (best-effort, rides
            // the batch). One fire-and-forget notify per transfer.
            for (recipient, to_hex, _, amount_str) in &resolved {
                notify_recipient_of_incoming_lh(
                    recipient.clone(),
                    to_hex.clone(),
                    amount_str.clone(),
                );
            }

            let transfers: Vec<serde_json::Value> = resolved
                .iter()
                .map(|(recipient, to_hex, _, amount_str)| {
                    serde_json::json!({
                        "recipient": recipient,
                        "resolved": to_hex,
                        "amount": amount_str,
                    })
                })
                .collect();
            Ok(serde_json::json!({
                "count": transfers.len(),
                "total": crate::app::format_wei_as_test_eth(total_wei),
                "bridged_from_meter": bridged,
                "transfers": transfers,
                "tx_hash": tx_hash,
            }))
        },
    )
}

/// `check_balances()` — read-only snapshot of every $LH pot the agent can
/// spend from (feedback #47: agents could not inspect their own balances,
/// making insufficient-funds reverts undiagnosable). No arguments.
pub(crate) fn check_balances_tool() -> std::sync::Arc<dyn crate::tools::Tool> {
    let schema = serde_json::json!({
        "type": "object",
        "properties": {}
    });
    ClosureTool::new(
        "check_balances",
        "Read this agent's $LH balances: the owner WALLET (pays send_lh and \
         x402 agent calls), the chat METER (pays model usage; auto-bridges \
         into the wallet when it is short), and this subdomain's token-bound \
         account (TBA — where bounty rewards and x402 earnings land). The meter \
         splits into a WITHDRAWABLE portion (sendable / bridgeable to the wallet) \
         and a LOCKED portion (fiat-minted $LH, spend-only on inference until its \
         unlock time) — so a send_lh/bridge that would revert InsufficientCredits \
         (LH2024) is visible BEFORE attempting it. Read-only, costs nothing. \
         Returns decimal $LH figures plus raw wei.",
        schema,
        |_args: serde_json::Value, _ctx| async move {
            let (name, owner) = crate::app::tenant::current_tenant_owner()
                .await
                .map_err(crate::error::Error::other)?;
            let wallet = crate::app::registry::token_balance_of(&owner)
                .await
                .unwrap_or(0);
            let meter = crate::app::registry::credit_balance_of(&owner)
                .await
                .unwrap_or(0);
            // Lock split: `withdrawableOf` is the unlocked part the meter→wallet
            // bridge can pull; the rest is locked fiat-origin $LH (spend-only).
            let withdrawable = crate::app::registry::withdrawable_credit_of(&owner)
                .await
                .unwrap_or(meter);
            let meter_locked = meter.saturating_sub(withdrawable);
            // Raw recorded lock (amount, unlockAt) so the agent can say WHEN it frees.
            let (_lock_amt, unlock_at) = crate::app::registry::fiat_locked_of(&owner)
                .await
                .unwrap_or((0, 0));
            let tba_hex = crate::app::registry::tba_of_name(&name)
                .await
                .ok()
                .flatten();
            let tba_balance = match &tba_hex {
                Some(addr) => crate::app::registry::token_balance_of(addr)
                    .await
                    .unwrap_or(0),
                None => 0,
            };
            Ok(serde_json::json!({
                "owner_address": owner,
                "wallet_lh": crate::app::format_wei_as_test_eth(wallet),
                "wallet_wei": wallet.to_string(),
                "meter_lh": crate::app::format_wei_as_test_eth(meter),
                "meter_wei": meter.to_string(),
                "meter_withdrawable_lh": crate::app::format_wei_as_test_eth(withdrawable),
                "meter_withdrawable_wei": withdrawable.to_string(),
                "meter_locked_lh": crate::app::format_wei_as_test_eth(meter_locked),
                "meter_locked_wei": meter_locked.to_string(),
                "meter_lock_unlock_at": unlock_at,
                "tba_address": tba_hex,
                "tba_lh": crate::app::format_wei_as_test_eth(tba_balance),
                "tba_wei": tba_balance.to_string(),
                // Spendable on the WALLET path (send_lh / x402): wallet + the
                // UNLOCKED meter only — locked fiat-$LH can't be bridged out.
                "spendable_total_lh": crate::app::format_wei_as_test_eth(
                    wallet.saturating_add(withdrawable)
                ),
            }))
        },
    )
}

/// `query_balance(target)` — read the LIVE on-chain $LH balance of ANY agent
/// (by name) or 0x address. Agents were guessing peers' balances instead of
/// reading them (krafto on-chain #263); this is the read tool so they stop.
/// Read-only, costs nothing.
pub(crate) fn query_balance_tool() -> std::sync::Arc<dyn crate::tools::Tool> {
    let schema = serde_json::json!({
        "type": "object",
        "properties": {
            "target": {
                "type": "string",
                "description": "an agent NAME (e.g. \"binglescan\") or a 0x address"
            }
        },
        "required": ["target"]
    });
    ClosureTool::new(
        "query_balance",
        "Read the LIVE on-chain $LH balance of ANY agent (by name) or 0x address — \
         use this instead of GUESSING a peer's balance. For a name it returns both \
         the owner WALLET and the agent's token-bound account (TBA, where earnings \
         land); for a raw address, that address's balance. Read-only, costs nothing. \
         Decimal $LH plus raw wei.",
        schema,
        |args: serde_json::Value, _ctx| async move {
            let target = args
                .get("target")
                .and_then(|v| v.as_str())
                .unwrap_or("")
                .trim()
                .to_string();
            if target.is_empty() {
                return Err(crate::error::Error::other(
                    "query_balance: target (an agent name or 0x address) is required",
                ));
            }
            // A raw 0x address is queried directly; anything else is a name.
            if target.starts_with("0x") && target.len() == 42 {
                let bal = crate::app::registry::token_balance_of(&target)
                    .await
                    .unwrap_or(0);
                return Ok(serde_json::json!({
                    "target": target,
                    "resolved_as": "address",
                    "lh": crate::app::format_wei_as_test_eth(bal),
                    "wei": bal.to_string(),
                }));
            }
            let name = target
                .trim_end_matches(".localharness.xyz")
                .to_lowercase();
            let owner = crate::app::registry::owner_of_name(&name)
                .await
                .ok()
                .flatten();
            let Some(owner) = owner else {
                return Err(crate::error::Error::other(format!(
                    "query_balance: no agent named '{name}' is registered on-chain"
                )));
            };
            let tba = crate::app::registry::tba_of_name(&name).await.ok().flatten();
            let wallet = crate::app::registry::token_balance_of(&owner)
                .await
                .unwrap_or(0);
            let tba_balance = match &tba {
                Some(addr) => crate::app::registry::token_balance_of(addr)
                    .await
                    .unwrap_or(0),
                None => 0,
            };
            Ok(serde_json::json!({
                "target": name,
                "resolved_as": "name",
                "owner_address": owner,
                "wallet_lh": crate::app::format_wei_as_test_eth(wallet),
                "wallet_wei": wallet.to_string(),
                "tba_address": tba,
                "tba_lh": crate::app::format_wei_as_test_eth(tba_balance),
                "tba_wei": tba_balance.to_string(),
            }))
        },
    )
}