vta-cli-common 0.73.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
//! `pnm findtime …` — finding a time with contacts across communities (`vta/findtime/*/0.1`,
//! VTI-PEV-050 – 063).
//!
//! As a host: `create` asks contacts when they are free (2 – 30 candidate times, the voters
//! setting fixed when made), `show` / `list` read the answers the voters setting lets you see,
//! `close` stops it — naming the time chosen makes a draft event of it — and `delete` removes it.
//!
//! As an invitee: `invited` lists the requests your VTA holds (it tells no host), `read` reads
//! one from its host and `answer` answers it — both sent **as the identifier the host invited**,
//! so the host learns of each. `auto` lets your VTA answer one host's requests from your
//! calendar, one word per time; your own answer always wins.
//!
//! 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.
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: &str) -> Option<String> {
    Some(match code {
        "syncOff" => format!(
            "Answers come from the synced calendar. Turn reading on first:\n    \
             pnm calendar settings update --context {context} --sync on"
        ),
        "hostUnknown" => format!(
            "`--host` must be a persona your VTA holds in this context. List them with:\n    \
             pnm persona list --context {context}"
        ),
        "inviteeInvalid" => "Invite only your contacts, each once, and never the host itself. \
             File a contact with `pnm persona contact put` first."
            .to_string(),
        "alreadyClosed" => "The request is already closed; make a new one to ask again:\n    \
             pnm findtime create …"
            .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(),
        "notFound" => format!(
            "Nothing by that identifier is held in {context}. List what is:\n    \
             pnm findtime list --context {context}\n    pnm findtime invited --context {context}"
        ),
        _ => return None,
    })
}

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

/// `--slot <id>=<YYYY-MM-DDTHH:MM[:SS]>` in `zone`, lasting `duration`.
fn slot_of(spec: &str, zone: &str, duration: &str) -> Result<Value, Box<dyn std::error::Error>> {
    let (id, start) = spec
        .split_once('=')
        .ok_or_else(|| format!("`{spec}`: expected <id>=<YYYY-MM-DDTHH:MM>"))?;
    let start = if start.len() == 16 {
        format!("{start}:00")
    } else {
        start.to_string()
    };
    Ok(json!({ "slotId": id, "when": { "start": start, "timeZone": zone, "duration": duration } }))
}

/// `--answer <id>=yes|if-need-be|no`.
fn answer_of(spec: &str) -> Result<Value, Box<dyn std::error::Error>> {
    let (id, choice) = spec
        .split_once('=')
        .ok_or_else(|| format!("`{spec}`: expected <id>=yes|if-need-be|no"))?;
    let choice = match choice {
        "yes" => "yes",
        "if-need-be" | "ifNeedBe" | "maybe" => "ifNeedBe",
        "no" => "no",
        other => return Err(format!("`{other}`: expected yes, if-need-be or no").into()),
    };
    Ok(json!({ "slotId": id, "choice": choice }))
}

/// What `pnm findtime create` sends.
pub struct CreateOptions {
    pub context: String,
    pub host: String,
    pub title: String,
    pub description: Option<String>,
    pub voters: String,
    pub slots: Vec<String>,
    pub time_zone: String,
    pub duration: String,
    pub invitees: Vec<String>,
    pub closes_at: Option<String>,
}

fn print_request(r: &Value) {
    println!(
        "{BOLD}{}{RESET}  {DIM}{} · {} · voters {}{RESET}",
        r["title"].as_str().unwrap_or_default(),
        r["requestId"].as_str().unwrap_or_default(),
        r["state"].as_str().unwrap_or_default(),
        r["voters"].as_str().unwrap_or_default(),
    );
    let tallies = r["tallies"].as_array().cloned().unwrap_or_default();
    for s in r["slots"].as_array().cloned().unwrap_or_default() {
        let id = s["slotId"].as_str().unwrap_or_default();
        let t = tallies
            .iter()
            .find(|t| t["slotId"] == id)
            .cloned()
            .unwrap_or(Value::Null);
        let chosen = if r["chosenSlotId"] == id {
            format!(" {GREEN}chosen{RESET}")
        } else {
            String::new()
        };
        println!(
            "  {CYAN}{id}{RESET} {} {}  {GREEN}{} yes{RESET} · {YELLOW}{} if need be{RESET} · {} no{chosen}",
            s["when"]["start"].as_str().unwrap_or_default(),
            s["when"]["timeZone"].as_str().unwrap_or_default(),
            t["yes"].as_u64().unwrap_or(0),
            t["ifNeedBe"].as_u64().unwrap_or(0),
            t["no"].as_u64().unwrap_or(0),
        );
        for a in t["answers"].as_array().cloned().unwrap_or_default() {
            let who = a["displayName"]
                .as_str()
                .or_else(|| a["invitee"].as_str())
                .unwrap_or("someone");
            println!(
                "      {DIM}{who}: {}{RESET}",
                a["choice"].as_str().unwrap_or_default()
            );
        }
    }
    if let Some(e) = r["eventId"].as_str() {
        println!("  {DIM}draft event {e} — publish and invite with `pnm events …`{RESET}");
    }
    if let Some(mine) = r["myAnswers"].as_array() {
        let by = r["myAnswersBy"].as_str().unwrap_or("you");
        let list: Vec<String> = mine
            .iter()
            .map(|a| {
                format!(
                    "{}={}",
                    a["slotId"].as_str().unwrap_or_default(),
                    a["choice"].as_str().unwrap_or_default()
                )
            })
            .collect();
        println!("  {DIM}your answers ({by}): {}{RESET}", list.join(", "));
    }
}

/// `create` → `vta/findtime/create/0.1`.
pub async fn cmd_findtime_create(client: &VtaClient, o: &CreateOptions) -> CmdResult {
    let slots = o
        .slots
        .iter()
        .map(|s| slot_of(s, &o.time_zone, &o.duration))
        .collect::<Result<Vec<_>, _>>()?;
    let mut req = json!({
        "contextId": o.context,
        "host": o.host,
        "title": o.title,
        "voters": o.voters,
        "slots": slots,
        "invitees": o.invitees,
    });
    if let Some(d) = &o.description {
        req["description"] = json!(d);
    }
    if let Some(c) = &o.closes_at {
        req["closesAt"] = json!(c);
    }
    let resp = call(
        client,
        tt::TASK_VTA_FINDTIME_CREATE_0_1,
        req,
        &o.context,
        20,
    )
    .await?;
    if is_json_output() {
        return Ok(print_json(&resp)?);
    }
    println!(
        "{GREEN}\u{2713}{RESET} Asked {} contact(s). Each is told by a notification sent as the host.",
        o.invitees.len()
    );
    print_request(&resp["request"]);
    Ok(())
}

/// `show` → `vta/findtime/show/0.1`.
pub async fn cmd_findtime_show(client: &VtaClient, context: &str, request_id: &str) -> CmdResult {
    let resp = call(
        client,
        tt::TASK_VTA_FINDTIME_SHOW_0_1,
        json!({ "contextId": context, "requestId": request_id }),
        context,
        20,
    )
    .await?;
    if is_json_output() {
        return Ok(print_json(&resp)?);
    }
    print_request(&resp["request"]);
    Ok(())
}

/// `list` → `vta/findtime/list/0.1`.
pub async fn cmd_findtime_list(
    client: &VtaClient,
    context: &str,
    state: Option<&str>,
) -> CmdResult {
    let mut req = json!({ "contextId": context });
    if let Some(s) = state {
        req["state"] = json!(s);
    }
    let resp = call(client, tt::TASK_VTA_FINDTIME_LIST_0_1, req, context, 20).await?;
    if is_json_output() {
        return Ok(print_json(&resp)?);
    }
    let items = resp["requests"].as_array().cloned().unwrap_or_default();
    if items.is_empty() {
        println!("{DIM}No requests to find a time in {context}.{RESET}");
    }
    for r in &items {
        print_request(r);
    }
    Ok(())
}

/// `close` → `vta/findtime/close/0.1`; naming `chosen` makes a draft event of that time.
pub async fn cmd_findtime_close(
    client: &VtaClient,
    context: &str,
    request_id: &str,
    chosen: Option<&str>,
) -> CmdResult {
    let mut req = json!({ "contextId": context, "requestId": request_id });
    if let Some(c) = chosen {
        req["chosenSlotId"] = json!(c);
    }
    let resp = call(client, tt::TASK_VTA_FINDTIME_CLOSE_0_1, req, context, 20).await?;
    if is_json_output() {
        return Ok(print_json(&resp)?);
    }
    println!("{GREEN}\u{2713}{RESET} Closed; every invitee's notification is withdrawn.");
    print_request(&resp["request"]);
    Ok(())
}

/// `delete` → `vta/findtime/delete/0.1`.
pub async fn cmd_findtime_delete(client: &VtaClient, context: &str, request_id: &str) -> CmdResult {
    let resp = call(
        client,
        tt::TASK_VTA_FINDTIME_DELETE_0_1,
        json!({ "contextId": context, "requestId": request_id }),
        context,
        20,
    )
    .await?;
    if is_json_output() {
        return Ok(print_json(&resp)?);
    }
    println!("{GREEN}\u{2713}{RESET} Deleted, with its answers.");
    Ok(())
}

/// `invited` → `vta/findtime/invited/list/0.1`: tells no host.
pub async fn cmd_findtime_invited(
    client: &VtaClient,
    context: &str,
    status: Option<&str>,
) -> CmdResult {
    let mut req = json!({ "contextId": context });
    if let Some(s) = status {
        req["status"] = json!(s);
    }
    let resp = call(
        client,
        tt::TASK_VTA_FINDTIME_INVITED_LIST_0_1,
        req,
        context,
        20,
    )
    .await?;
    if is_json_output() {
        return Ok(print_json(&resp)?);
    }
    let items = resp["requests"].as_array().cloned().unwrap_or_default();
    if items.is_empty() {
        println!("{DIM}No requests to find a time held in {context}.{RESET}");
    }
    for h in items {
        println!(
            "{BOLD}{}{RESET} from {CYAN}{}{RESET} — {}, answered by {}",
            h["requestId"].as_str().unwrap_or_default(),
            h["host"].as_str().unwrap_or_default(),
            h["status"].as_str().unwrap_or_default(),
            h["answeredBy"].as_str().unwrap_or_default(),
        );
        println!(
            "  {DIM}to {}{RESET}",
            h["invited"].as_str().unwrap_or_default()
        );
    }
    Ok(())
}

/// `read` → `vta/findtime/invited/show/0.1`: read from the host as the invited identifier.
pub async fn cmd_findtime_read(
    client: &VtaClient,
    context: &str,
    host: &str,
    request_id: &str,
) -> CmdResult {
    let resp = call(
        client,
        tt::TASK_VTA_FINDTIME_INVITED_SHOW_0_1,
        json!({ "contextId": context, "host": host, "requestId": request_id }),
        context,
        60,
    )
    .await?;
    if is_json_output() {
        return Ok(print_json(&resp)?);
    }
    print_request(&resp["request"]);
    Ok(())
}

/// `answer` → `vta/findtime/invited/answer/0.1`: your answers, as the invited identifier; your
/// VTA answers this request for you no more.
pub async fn cmd_findtime_answer(
    client: &VtaClient,
    context: &str,
    host: &str,
    request_id: &str,
    answers: &[String],
    display_name: Option<&str>,
) -> CmdResult {
    let answers = answers
        .iter()
        .map(|a| answer_of(a))
        .collect::<Result<Vec<_>, _>>()?;
    let mut req = json!({
        "contextId": context, "host": host, "requestId": request_id, "answers": answers,
    });
    if let Some(n) = display_name {
        req["displayName"] = json!(n);
    }
    let resp = call(
        client,
        tt::TASK_VTA_FINDTIME_INVITED_ANSWER_0_1,
        req,
        context,
        60,
    )
    .await?;
    if is_json_output() {
        return Ok(print_json(&resp)?);
    }
    println!("{GREEN}\u{2713}{RESET} Answered. Your VTA answers this request for you no more.");
    print_request(&resp["request"]);
    Ok(())
}

/// `auto show` → `vta/findtime/settings/show/0.1`.
pub async fn cmd_findtime_auto_show(client: &VtaClient, context: &str) -> CmdResult {
    let resp = call(
        client,
        tt::TASK_VTA_FINDTIME_SETTINGS_SHOW_0_1,
        json!({ "contextId": context }),
        context,
        20,
    )
    .await?;
    if is_json_output() {
        return Ok(print_json(&resp)?);
    }
    let choices = resp["choices"].as_array().cloned().unwrap_or_default();
    if choices.is_empty() {
        println!(
            "{DIM}Your VTA answers nobody's requests to find a time in {context}. Turn it on with\n  \
             pnm findtime auto set --context {context} --host <did> --on{RESET}"
        );
    }
    for c in choices {
        let on = c["enabled"] == true;
        println!(
            "  {}{}{RESET}  {}",
            if on { GREEN } else { DIM },
            if on { "answers" } else { "off" },
            c["host"].as_str().unwrap_or_default()
        );
    }
    Ok(())
}

/// `auto set` → `vta/findtime/settings/set/0.1`: let your VTA answer one host's requests from
/// your calendar (VTI-PEV-060), or stop it.
pub async fn cmd_findtime_auto_set(
    client: &VtaClient,
    context: &str,
    host: &str,
    enabled: bool,
    also_count: &[String],
) -> CmdResult {
    let mut req = json!({ "contextId": context, "host": host, "enabled": enabled });
    if !also_count.is_empty() {
        req["alsoCount"] = json!(also_count);
    }
    let resp = call(
        client,
        tt::TASK_VTA_FINDTIME_SETTINGS_SET_0_1,
        req,
        context,
        60,
    )
    .await?;
    if is_json_output() {
        return Ok(print_json(&resp)?);
    }
    if enabled {
        println!(
            "{GREEN}\u{2713}{RESET} Your VTA will answer this host's requests from your calendar, \
             one word per time. Answering one yourself always wins."
        );
    } else {
        println!(
            "{GREEN}\u{2713}{RESET} Your VTA no longer answers this host's requests; answers \
             already given stand."
        );
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_slot_and_an_answer_from_the_command_line() {
        let s = slot_of("sat-am=2026-12-05T10:00", "Europe/London", "PT1H").unwrap();
        assert_eq!(s["when"]["start"], "2026-12-05T10:00:00");
        assert_eq!(s["slotId"], "sat-am");
        assert!(slot_of("nope", "Etc/UTC", "PT1H").is_err());
        assert_eq!(
            answer_of("sat-am=if-need-be").unwrap()["choice"],
            "ifNeedBe"
        );
        assert!(answer_of("sat-am=perhaps").is_err());
    }
}