vta-cli-common 0.74.0

Shared CLI command handlers and rendering helpers for VTA CLIs
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
//! `pnm calendar …` — the member's calendar the VTA keeps (`vta/calendar/*/0.1`,
//! VTI-CAL-001 – 071).
//!
//! `list` shows the events you registered for (`mine`, read from each community as your
//! membership identifier there) and those you hold only a notification of (`notified`), across
//! every trust context you have standing in. `sync` reads the communities now; `settings`
//! turns reading on or off per context and sets default reminders and quiet hours; `alerts`
//! sets one event's own reminders; `feeds` manages private iCalendar subscriptions; `export`
//! writes an `.ics` file and the receipts kept; `polls` lets the VTA answer a community's
//! scheduling polls from your calendar — find-a-time (VTI-CAL-062 – 066).
//!
//! A refusal whose fix is another command prints that command (workspace rule: operator
//! errors suggest the fix).

use serde_json::{Value, json};
use vta_sdk::error::VtaError;
use vta_sdk::prelude::*;
use vta_sdk::trust_tasks as tt;

use crate::render::{BOLD, CYAN, DIM, GREEN, RESET, YELLOW, is_json_output, print_json};

type CmdResult = Result<(), Box<dyn std::error::Error>>;

/// The local part of a declared refusal's code (`…:eventNotHeld` → `eventNotHeld`).
fn local_code(e: &VtaError) -> Option<&str> {
    e.rejection_code()
        .map(|c| c.rsplit_once(':').map_or(c, |(_, l)| l))
}

/// The command that fixes a refusal, when the operator's intent maps to one.
fn fix_for(code: &str, context: Option<&str>) -> Option<String> {
    let ctx = context.unwrap_or("<context>");
    Some(match code {
        "syncOff" => format!(
            "Busy times and poll answers come from the synced calendar. Turn reading on first:\n    \
             pnm calendar settings update --context {ctx} --sync on"
        ),
        "eventNotHeld" => format!(
            "The calendar does not hold that event yet. Read your communities, then list:\n    \
             pnm calendar sync --context {ctx}\n    pnm calendar list --context {ctx}"
        ),
        "limitReached" => "Revoke a feed you no longer use first:\n    \
             pnm calendar feeds list\n    pnm calendar feeds revoke <feed-id>"
            .to_string(),
        "expiryInvalid" => {
            "A feed expires after now and within a year, e.g. --expires 90d".to_string()
        }
        "alreadyRevoked" => {
            "Nothing to do; `pnm calendar feeds create` makes a new one.".to_string()
        }
        "feedNotFound" => {
            "List the feeds you may see:\n    pnm calendar feeds list --include-revoked".to_string()
        }
        "quietHoursInvalid" => "Quiet hours take HH:MM times and an IANA zone, e.g.\n    \
             --quiet 22:00-07:00 --time-zone Europe/Berlin"
            .to_string(),
        "rangeInvalid" => "`--to` must come after `--from` (at most 400 days later).".to_string(),
        "contextUnknown" => "`--also-count` names only contexts this VTA holds that you have \
             standing in:\n    pnm contexts list"
            .to_string(),
        _ => return None,
    })
}

/// Pass `r` through, adding the fix to a refusal that has one.
fn explain<T>(
    r: Result<T, VtaError>,
    context: Option<&str>,
) -> Result<T, Box<dyn std::error::Error>> {
    match r {
        Ok(v) => Ok(v),
        Err(e) => {
            if let Some(fix) = local_code(&e).and_then(|c| fix_for(c, context)) {
                Err(format!("{e}\n  {fix}").into())
            } else {
                Err(Box::new(e))
            }
        }
    }
}

async fn call(
    client: &VtaClient,
    uri: &str,
    payload: Value,
    context: Option<&str>,
) -> Result<Value, Box<dyn std::error::Error>> {
    let timeout = if uri == tt::TASK_VTA_CALENDAR_SYNC_0_1 {
        120
    } else {
        20
    };
    explain(
        client.dispatch_trust_task(uri, payload, timeout).await,
        context,
    )
}

/// A duration such as `90d`, `12h` or `30m`.
fn parse_span(s: &str) -> Result<chrono::Duration, String> {
    let (n, unit) = s.split_at(s.len().saturating_sub(1));
    let n: i64 = n
        .parse()
        .map_err(|_| format!("`{s}` is not a duration like 90d, 12h or 30m"))?;
    match unit {
        "d" => Ok(chrono::Duration::days(n)),
        "h" => Ok(chrono::Duration::hours(n)),
        "m" => Ok(chrono::Duration::minutes(n)),
        _ => Err(format!("`{s}` is not a duration like 90d, 12h or 30m")),
    }
}

/// Options for `calendar list`.
#[derive(Debug, Clone, Default)]
pub struct ListOptions {
    pub contexts: Vec<String>,
    pub from: Option<String>,
    pub to: Option<String>,
    pub tiers: Vec<String>,
    pub limit: Option<u32>,
    pub cursor: Option<String>,
}

/// `list` → `vta/calendar/list/0.4`.
pub async fn cmd_calendar_list(client: &VtaClient, opts: &ListOptions) -> CmdResult {
    let mut req = json!({});
    if !opts.contexts.is_empty() {
        req["contextIds"] = json!(opts.contexts);
    }
    if let Some(f) = &opts.from {
        req["from"] = json!(f);
    }
    if let Some(t) = &opts.to {
        req["to"] = json!(t);
    }
    if !opts.tiers.is_empty() {
        req["tiers"] = json!(opts.tiers);
    }
    if let Some(l) = opts.limit {
        req["limit"] = json!(l);
    }
    if let Some(c) = &opts.cursor {
        req["cursor"] = json!(c);
    }
    let ctx = opts.contexts.first().map(String::as_str);
    let resp = call(client, tt::TASK_VTA_CALENDAR_LIST_0_4, req, ctx).await?;
    if is_json_output() {
        return Ok(print_json(&resp)?);
    }
    let items = resp["items"].as_array().cloned().unwrap_or_default();
    if items.is_empty() {
        println!("Nothing in the calendar for this range.");
        if opts.tiers.is_empty() || opts.tiers.iter().any(|t| t == "mine") {
            println!(
                "{DIM}Registered events appear once the communities are read: \
                 `pnm calendar sync`.{RESET}"
            );
        }
    } else {
        println!();
        for item in &items {
            println!("  {}", entry_line(item));
        }
        println!();
    }
    if let Some(c) = resp["nextCursor"].as_str() {
        println!("{DIM}More remain: pass --cursor {c}{RESET}");
    }
    Ok(())
}

fn entry_line(item: &Value) -> String {
    let tier = item["tier"].as_str().unwrap_or("?");
    let start = item
        .pointer("/period/startsAt")
        .and_then(Value::as_str)
        .unwrap_or("?");
    let title = item
        .pointer("/event/title")
        .or_else(|| item.pointer("/actionItem/title"))
        .and_then(Value::as_str)
        .unwrap_or("(notified)");
    let mut flags = Vec::new();
    if item["hosting"].as_bool() == Some(true) {
        flags.push("hosting".into());
    }
    if let Some(s) = item.pointer("/actionItem/status").and_then(Value::as_str) {
        flags.push(format!("action item, {s}"));
    }
    if item["overlaps"].as_bool() == Some(true) {
        flags.push(format!("{YELLOW}overlaps{RESET}"));
    }
    if let Some(s) = item["registrationStatus"].as_str() {
        flags.push(s.to_string());
    }
    if item["withdrawn"].as_bool() == Some(true) {
        flags.push("withdrawn".into());
    }
    format!(
        "{CYAN}{start}{RESET}  {BOLD}{title}{RESET}  {DIM}[{tier}] {} · {} · {}{}{RESET}",
        item["contextId"].as_str().unwrap_or("?"),
        item["community"]
            .as_str()
            .or_else(|| item["host"].as_str())
            .unwrap_or("?"),
        item["eventId"].as_str().unwrap_or("?"),
        if flags.is_empty() {
            String::new()
        } else {
            format!(" · {}", flags.join(", "))
        },
    )
}

/// `sync` → `vta/calendar/sync/0.1`.
pub async fn cmd_calendar_sync(client: &VtaClient, context: Option<&str>) -> CmdResult {
    let mut req = json!({});
    if let Some(c) = context {
        req["contextId"] = json!(c);
    }
    let resp = call(client, tt::TASK_VTA_CALENDAR_SYNC_0_1, req, context).await?;
    if is_json_output() {
        return Ok(print_json(&resp)?);
    }
    let results = resp["results"].as_array().cloned().unwrap_or_default();
    if results.is_empty() {
        println!(
            "No community was read: no context with reading on holds a membership credential.\n\
             {DIM}Turn reading on with `pnm calendar settings update --context <id> --sync on`.{RESET}"
        );
    }
    for r in &results {
        println!(
            "  {} {}  {DIM}{}{}{}{RESET}",
            r["status"].as_str().unwrap_or("?"),
            r["community"].as_str().unwrap_or("?"),
            r["contextId"].as_str().unwrap_or("?"),
            r["changed"]
                .as_u64()
                .map_or(String::new(), |n| format!(" · {n} changed")),
            r["code"]
                .as_str()
                .map_or(String::new(), |c| format!(" · {c}")),
        );
    }
    Ok(())
}

/// `settings show` → `vta/calendar/settings/show/0.1`.
pub async fn cmd_calendar_settings_show(client: &VtaClient, context: &str) -> CmdResult {
    let resp = call(
        client,
        tt::TASK_VTA_CALENDAR_SETTINGS_SHOW_0_1,
        json!({ "contextId": context }),
        Some(context),
    )
    .await?;
    if is_json_output() {
        return Ok(print_json(&resp)?);
    }
    print_settings(&resp["settings"]);
    Ok(())
}

fn print_settings(s: &Value) {
    println!();
    println!(
        "  {BOLD}{}{RESET}  sync {}",
        s["contextId"].as_str().unwrap_or("?"),
        if s["sync"].as_bool() == Some(true) {
            "on"
        } else {
            "off"
        }
    );
    println!(
        "  default reminders (minutes before): {}",
        s["defaultReminderMinutes"]
    );
    match s.get("quietHours") {
        Some(q) if !q.is_null() => println!(
            "  quiet hours {}–{} {}",
            q["startsAt"].as_str().unwrap_or("?"),
            q["endsAt"].as_str().unwrap_or("?"),
            q["timeZone"].as_str().unwrap_or("?")
        ),
        _ => println!("  {DIM}no quiet hours{RESET}"),
    }
    println!();
}

/// Options for `calendar settings update`.
#[derive(Debug, Clone, Default)]
pub struct SettingsUpdate {
    pub sync: Option<bool>,
    pub default_reminders: Option<Vec<u32>>,
    /// `HH:MM-HH:MM`; `Some("")` or `Some("none")` clears quiet hours.
    pub quiet: Option<String>,
    pub time_zone: Option<String>,
}

/// `settings update` → `vta/calendar/settings/update/0.1`.
pub async fn cmd_calendar_settings_update(
    client: &VtaClient,
    context: &str,
    upd: &SettingsUpdate,
) -> CmdResult {
    let mut req = json!({ "contextId": context });
    if let Some(s) = upd.sync {
        req["sync"] = json!(s);
    }
    if let Some(d) = &upd.default_reminders {
        req["defaultReminderMinutes"] = json!(d);
    }
    if let Some(q) = &upd.quiet {
        if q.is_empty() || q == "none" {
            req["quietHours"] = Value::Null;
        } else {
            let (a, b) = q
                .split_once('-')
                .ok_or("--quiet takes HH:MM-HH:MM, or `none` to clear")?;
            let Some(tz) = &upd.time_zone else {
                return Err(
                    "--quiet needs --time-zone (an IANA zone such as Europe/Berlin)".into(),
                );
            };
            req["quietHours"] = json!({ "startsAt": a, "endsAt": b, "timeZone": tz });
        }
    }
    let resp = call(
        client,
        tt::TASK_VTA_CALENDAR_SETTINGS_UPDATE_0_1,
        req,
        Some(context),
    )
    .await?;
    if is_json_output() {
        return Ok(print_json(&resp)?);
    }
    println!("{GREEN}\u{2713}{RESET} Settings saved.");
    print_settings(&resp["settings"]);
    Ok(())
}

/// `polls show` → `vta/calendar/polls/settings/show/0.1`: the communities whose scheduling
/// polls the VTA answers for you in `context`.
pub async fn cmd_calendar_polls_show(client: &VtaClient, context: &str) -> CmdResult {
    let resp = call(
        client,
        tt::TASK_VTA_CALENDAR_POLLS_SETTINGS_SHOW_0_1,
        json!({ "contextId": context }),
        Some(context),
    )
    .await?;
    if is_json_output() {
        return Ok(print_json(&resp)?);
    }
    let choices = resp["choices"].as_array().cloned().unwrap_or_default();
    println!();
    if choices.is_empty() {
        println!(
            "  {DIM}Your VTA answers no community's polls in {context}. Turn it on with\n    \
             pnm calendar polls set --context {context} --community <did> --on{RESET}"
        );
    }
    for c in &choices {
        print_poll_choice(c);
    }
    println!();
    Ok(())
}

fn print_poll_choice(c: &Value) {
    let on = c["enabled"].as_bool() == Some(true);
    println!(
        "  {}{}{RESET}  {}",
        if on { GREEN } else { DIM },
        if on { "answers" } else { "off" },
        c["community"].as_str().unwrap_or("?")
    );
    if let Some(also) = c["alsoCount"].as_array().filter(|a| !a.is_empty()) {
        let names: Vec<&str> = also.iter().filter_map(Value::as_str).collect();
        println!("        {DIM}also counting {}{RESET}", names.join(", "));
    }
}

/// `polls set` → `vta/calendar/polls/settings/set/0.1`: let the VTA answer `community`'s
/// scheduling polls from your calendar, or stop it (VTI-CAL-062). Only one answer per time
/// leaves the VTA, and your own answer always wins.
pub async fn cmd_calendar_polls_set(
    client: &VtaClient,
    context: &str,
    community: &str,
    enabled: bool,
    also_count: &[String],
) -> CmdResult {
    let mut req = json!({ "contextId": context, "community": community, "enabled": enabled });
    if !also_count.is_empty() {
        req["alsoCount"] = json!(also_count);
    }
    let resp = call(
        client,
        tt::TASK_VTA_CALENDAR_POLLS_SETTINGS_SET_0_1,
        req,
        Some(context),
    )
    .await?;
    if is_json_output() {
        return Ok(print_json(&resp)?);
    }
    if enabled {
        println!(
            "{GREEN}\u{2713}{RESET} Your VTA will answer this community's scheduling polls from \
             your calendar. Answering one yourself always wins."
        );
    } else {
        println!(
            "{GREEN}\u{2713}{RESET} Your VTA no longer answers this community's polls; answers \
             already given stand."
        );
    }
    print_poll_choice(&resp["choice"]);
    Ok(())
}

/// `alerts set` → `vta/calendar/alerts/set/0.1`. An empty `minutes` means no reminders.
pub async fn cmd_calendar_alerts_set(
    client: &VtaClient,
    context: &str,
    community: &str,
    event_id: &str,
    minutes: &[u32],
) -> CmdResult {
    let resp = call(
        client,
        tt::TASK_VTA_CALENDAR_ALERTS_SET_0_1,
        json!({
            "contextId": context,
            "community": community,
            "eventId": event_id,
            "reminderMinutes": minutes,
        }),
        Some(context),
    )
    .await?;
    if is_json_output() {
        return Ok(print_json(&resp)?);
    }
    if minutes.is_empty() {
        println!("{GREEN}\u{2713}{RESET} No reminders for {BOLD}{event_id}{RESET}.");
    } else {
        println!(
            "{GREEN}\u{2713}{RESET} Reminders for {BOLD}{event_id}{RESET}: {minutes:?} minutes before."
        );
    }
    Ok(())
}

/// `alerts clear` → `vta/calendar/alerts/clear/0.1`.
pub async fn cmd_calendar_alerts_clear(
    client: &VtaClient,
    context: &str,
    community: &str,
    event_id: &str,
) -> CmdResult {
    let resp = call(
        client,
        tt::TASK_VTA_CALENDAR_ALERTS_CLEAR_0_1,
        json!({ "contextId": context, "community": community, "eventId": event_id }),
        Some(context),
    )
    .await?;
    if is_json_output() {
        return Ok(print_json(&resp)?);
    }
    if resp["changed"].as_bool() == Some(true) {
        println!(
            "{GREEN}\u{2713}{RESET} {event_id} follows the context's default reminders again."
        );
    } else {
        println!("{event_id} had no reminders of its own.");
    }
    Ok(())
}

/// Options for `calendar feeds create`.
#[derive(Debug, Clone, Default)]
pub struct FeedCreate {
    pub contexts: Vec<String>,
    pub label: Option<String>,
    pub detail: Option<String>,
    pub tiers: Vec<String>,
    pub expires: String,
}

/// `feeds create` → `vta/calendar/feeds/create/0.1`. The URL is printed once.
pub async fn cmd_calendar_feeds_create(client: &VtaClient, opts: &FeedCreate) -> CmdResult {
    let span = parse_span(&opts.expires)?;
    let expires = (chrono::Utc::now() + span).to_rfc3339_opts(chrono::SecondsFormat::Secs, true);
    let mut req = json!({ "contextIds": opts.contexts, "expiresAt": expires });
    if let Some(l) = &opts.label {
        req["label"] = json!(l);
    }
    if let Some(d) = &opts.detail {
        req["detail"] = json!(d);
    }
    if !opts.tiers.is_empty() {
        req["tiers"] = json!(opts.tiers);
    }
    let ctx = opts.contexts.first().map(String::as_str);
    let resp = call(client, tt::TASK_VTA_CALENDAR_FEEDS_CREATE_0_1, req, ctx).await?;
    if is_json_output() {
        return Ok(print_json(&resp)?);
    }
    println!(
        "{GREEN}\u{2713}{RESET} Feed {BOLD}{}{RESET} expires {}.",
        resp["feed"]["feedId"].as_str().unwrap_or("?"),
        resp["feed"]["expiresAt"].as_str().unwrap_or("?")
    );
    println!();
    println!("  {}", resp["url"].as_str().unwrap_or("?"));
    println!();
    println!(
        "{YELLOW}This address is the credential and is shown only now.{RESET} Give it to your \
         calendar application and keep it nowhere else; anyone holding it reads the feed until \
         `pnm calendar feeds revoke`."
    );
    Ok(())
}

/// `feeds list` → `vta/calendar/feeds/list/0.1`.
pub async fn cmd_calendar_feeds_list(client: &VtaClient, include_revoked: bool) -> CmdResult {
    let resp = call(
        client,
        tt::TASK_VTA_CALENDAR_FEEDS_LIST_0_1,
        json!({ "includeRevoked": include_revoked }),
        None,
    )
    .await?;
    if is_json_output() {
        return Ok(print_json(&resp)?);
    }
    let items = resp["items"].as_array().cloned().unwrap_or_default();
    if items.is_empty() {
        println!("No feeds. `pnm calendar feeds create --context <id>` makes one.");
    }
    for f in &items {
        println!(
            "  {CYAN}{}{RESET}  {BOLD}{}{RESET}  {DIM}{} · expires {} · last read {} ({} reads){}{RESET}",
            f["feedId"].as_str().unwrap_or("?"),
            f["label"].as_str().unwrap_or(""),
            f["detail"].as_str().unwrap_or("?"),
            f["expiresAt"].as_str().unwrap_or("?"),
            f["lastFetchedAt"].as_str().unwrap_or("never"),
            f["fetchCount"].as_u64().unwrap_or(0),
            if f.get("revokedAt").is_some_and(|v| !v.is_null()) {
                " · revoked"
            } else {
                ""
            },
        );
    }
    Ok(())
}

/// `feeds revoke` → `vta/calendar/feeds/revoke/0.1`.
pub async fn cmd_calendar_feeds_revoke(client: &VtaClient, feed_id: &str) -> CmdResult {
    let resp = call(
        client,
        tt::TASK_VTA_CALENDAR_FEEDS_REVOKE_0_1,
        json!({ "feedId": feed_id }),
        None,
    )
    .await?;
    if is_json_output() {
        return Ok(print_json(&resp)?);
    }
    println!(
        "{GREEN}\u{2713}{RESET} Feed {BOLD}{feed_id}{RESET} revoked; its address reads nothing from now on."
    );
    Ok(())
}

/// `export` → `vta/calendar/export/0.1`: the iCalendar object to `out` (`-` for stdout), and
/// the receipts, exactly as received, to `receipts_out` when given.
pub async fn cmd_calendar_export(
    client: &VtaClient,
    contexts: &[String],
    out: &str,
    receipts_out: Option<&str>,
) -> CmdResult {
    let mut req = json!({ "includeReceipts": receipts_out.is_some() });
    if !contexts.is_empty() {
        req["contextIds"] = json!(contexts);
    }
    let ctx = contexts.first().map(String::as_str);
    let resp = call(client, tt::TASK_VTA_CALENDAR_EXPORT_0_1, req, ctx).await?;
    if is_json_output() {
        return Ok(print_json(&resp)?);
    }
    let ics = resp["ics"].as_str().unwrap_or_default();
    if out == "-" {
        print!("{ics}");
    } else {
        std::fs::write(out, ics)?;
        println!("{GREEN}\u{2713}{RESET} Wrote {out}.");
    }
    if let Some(path) = receipts_out {
        // As received: the receipts' proofs cover these bytes (VTI-CAL-030).
        std::fs::write(path, serde_json::to_vec_pretty(&resp["receipts"])?)?;
        println!("{GREEN}\u{2713}{RESET} Wrote the receipts to {path}.");
        if let Some(c) = resp["nextCursor"].as_str() {
            println!(
                "{DIM}More receipts remain (cursor {c}); pass `--json` to `pnm calendar export` to see them.{RESET}"
            );
        }
    }
    Ok(())
}

// ─── invitations from people hosting events (`vta/events/invited/*`, VTI-PEV-032 – 036) ──

/// The command that fixes a refusal of an invited task, when there is one.
fn invited_fix(code: &str, context: &str) -> Option<String> {
    Some(match code {
        "notFound" => format!(
            "No invitation from that host for that event is held here. List what is held:\n    \
             pnm calendar invited list --context {context}"
        ),
        "invitationWithdrawn" => {
            "The host withdrew this invitation; there is nothing to open or answer.".to_string()
        }
        "noMatchingProtocol" => "The invited identifier and the host share no transport, so \
             nothing was sent. The identifier's DID document has to advertise a transport \
             the host also does."
            .to_string(),
        "hostUnreachable" => "The host did not answer. Run the same command again: an answer \
             resends the same document, so the host sees it once."
            .to_string(),
        _ => return None,
    })
}

async fn invited_call(
    client: &VtaClient,
    uri: &str,
    payload: Value,
    context: &str,
) -> Result<Value, Box<dyn std::error::Error>> {
    match client.dispatch_trust_task(uri, payload, 60).await {
        Ok(v) => Ok(v),
        Err(e) => match local_code(&e).and_then(|c| invited_fix(c, context)) {
            Some(fix) => Err(format!("{e}\n  {fix}").into()),
            None => Err(Box::new(e)),
        },
    }
}

/// `invited list` → `vta/events/invited/list/0.1`: the invitations held in `context`. Sends
/// nothing to any host.
pub async fn cmd_calendar_invited_list(
    client: &VtaClient,
    context: &str,
    states: &[String],
) -> CmdResult {
    let mut req = json!({ "contextId": context });
    if !states.is_empty() {
        req["states"] = json!(states);
    }
    let resp = invited_call(client, tt::TASK_VTA_EVENTS_INVITED_LIST_0_1, req, context).await?;
    if is_json_output() {
        return Ok(print_json(&resp)?);
    }
    let items = resp["items"].as_array().cloned().unwrap_or_default();
    if items.is_empty() {
        println!("{DIM}No invitations held in {context}.{RESET}");
        return Ok(());
    }
    for i in items {
        let opened = if i["opened"] == true {
            ""
        } else {
            " (unopened)"
        };
        let reg = i["registration"]
            .as_str()
            .map(|r| format!(" {GREEN}{r}{RESET}"))
            .unwrap_or_default();
        println!(
            "{BOLD}{}{RESET} from {CYAN}{}{RESET} — {}{opened}{reg}",
            i["eventId"].as_str().unwrap_or_default(),
            i["host"].as_str().unwrap_or_default(),
            i["state"].as_str().unwrap_or_default(),
        );
        println!(
            "  {DIM}to {}{RESET}",
            i["invitee"].as_str().unwrap_or_default()
        );
    }
    if let Some(c) = resp["nextCursor"].as_str() {
        println!("{DIM}More remain (cursor {c}).{RESET}");
    }
    Ok(())
}

/// `invited show` → `vta/events/invited/show/0.1`: open an invitation. The VTA reads the event
/// from its host as the invited identifier, so the host learns it was opened.
pub async fn cmd_calendar_invited_show(
    client: &VtaClient,
    context: &str,
    host: &str,
    event_id: &str,
) -> CmdResult {
    let req = json!({ "contextId": context, "host": host, "eventId": event_id });
    let resp = invited_call(client, tt::TASK_VTA_EVENTS_INVITED_SHOW_0_1, req, context).await?;
    if is_json_output() {
        return Ok(print_json(&resp)?);
    }
    let e = &resp["event"];
    println!("{BOLD}{}{RESET}", e["title"].as_str().unwrap_or_default());
    println!(
        "  {} {}",
        e["when"]["start"].as_str().unwrap_or_default(),
        e["when"]["timeZone"].as_str().unwrap_or_default()
    );
    if let Some(s) = resp["registration"]["status"].as_str() {
        println!("  {GREEN}You are {s}.{RESET}");
    } else {
        println!(
            "  {YELLOW}Not answered.{RESET} Answer with:\n    pnm calendar invited respond \
             --context {context} --host {host} {event_id} going"
        );
    }
    Ok(())
}

/// Options for `invited respond`.
#[derive(Debug, Clone, Default)]
pub struct RespondOptions {
    pub context: String,
    pub host: String,
    pub event_id: String,
    /// `going`, `maybe` or `withdraw`.
    pub answer: String,
    pub guests: Option<u32>,
    pub display_name: Option<String>,
}

/// `invited respond` → `vta/events/invited/respond/0.1`: answer as the invited identifier. Run
/// under one idempotency key, so a retry after a lost reply sends the same document.
pub async fn cmd_calendar_invited_respond(client: &VtaClient, o: &RespondOptions) -> CmdResult {
    let mut req = json!({ "contextId": o.context, "host": o.host, "eventId": o.event_id,
                          "answer": o.answer });
    if let Some(g) = o.guests {
        req["guests"] = json!(g);
    }
    if let Some(n) = &o.display_name {
        req["displayName"] = json!(n);
    }
    let resp = client
        .idempotent(|| {
            client.dispatch_trust_task(tt::TASK_VTA_EVENTS_INVITED_RESPOND_0_1, req.clone(), 60)
        })
        .await;
    let resp = match resp {
        Ok(v) => v,
        Err(e) => {
            return match local_code(&e).and_then(|c| invited_fix(c, &o.context)) {
                Some(fix) => Err(format!("{e}\n  {fix}").into()),
                None => Err(Box::new(e)),
            };
        }
    };
    if is_json_output() {
        return Ok(print_json(&resp)?);
    }
    println!(
        "{GREEN}\u{2713}{RESET} {} — you are {}. The host's reply is kept as a receipt.",
        resp["event"]["title"].as_str().unwrap_or_default(),
        resp["registration"]["status"].as_str().unwrap_or_default()
    );
    Ok(())
}