Skip to main content

teams_cli/
schema.rs

1use serde_json::{Value, json};
2
3use crate::error;
4
5fn field(name: &str, kind: &str) -> Value {
6    json!({"name": name, "type": kind})
7}
8fn array_field(name: &str, item_kind: &str) -> Value {
9    json!({"name": name, "type": "array", "items": {"type": item_kind}})
10}
11fn nullable_field(name: &str, kind: &str) -> Value {
12    json!({"name": name, "type": kind, "nullable": true})
13}
14fn nullable_array_field(name: &str, item_kind: &str) -> Value {
15    json!({"name": name, "type": "array", "items": {"type": item_kind}, "nullable": true})
16}
17fn object_field(name: &str, nullable: bool, description: &str, fields: Vec<Value>) -> Value {
18    json!({"name": name, "type": "object", "nullable": nullable, "description": description, "fields": fields})
19}
20fn described(mut field: Value, description: &str) -> Value {
21    field["description"] = json!(description);
22    field
23}
24fn debugging_setup() -> Value {
25    object_field(
26        "debugging_setup",
27        true,
28        "Managed connection commands, available when no endpoint listens. Restart commands require confirmation and preserve prior settings; recover restores interrupted setup settings",
29        vec![
30            described(
31                field("shell", "string"),
32                "zsh, bash, wsl or powershell: where the commands run",
33            ),
34            field("open", "string"),
35            field("close", "string"),
36        ],
37    )
38}
39fn sender() -> Value {
40    object_field(
41        "from",
42        true,
43        "Sender; null for system events",
44        vec![object_field(
45            "user",
46            true,
47            "The sending user",
48            vec![
49                field("id", "string"),
50                nullable_field("displayName", "string"),
51            ],
52        )],
53    )
54}
55fn body() -> Value {
56    object_field(
57        "body",
58        false,
59        "Message content",
60        vec![
61            json!({"name": "contentType", "type": "string", "enum": ["text", "html"]}),
62            field("content", "string"),
63        ],
64    )
65}
66fn arg(name: &str, kind: &str, description: &str) -> Value {
67    json!({"name": name, "type": kind, "description": description})
68}
69fn required_arg(name: &str, kind: &str, description: &str) -> Value {
70    json!({"name": name, "type": kind, "description": description, "required": true})
71}
72
73fn single(name: &str, description: &str, effects: &str, fields: Vec<Value>) -> Value {
74    json!({"name": name, "description": description, "effects": effects, "cardinality": "single", "output_fields": fields})
75}
76
77fn paged(name: &str, description: &str, fields: Vec<Value>) -> Value {
78    json!({
79        "name": name, "description": description, "effects": "read_only", "cardinality": "unbounded",
80        "pagination": {"style": "cursor", "cursor_field": "next_cursor", "cursor_arg": "--cursor", "limit_arg": "--limit"},
81        "fields_arg": "--fields",
82        "args": [
83            {"name": "--limit", "type": "integer", "default": 50, "x-minimum": 1, "x-maximum": 50, "description": "Maximum records in this page"},
84            arg("--cursor", "string", "Opaque next_cursor value from the previous page; omit for the newest page"),
85            arg("--fields", "string", "Comma-separated top-level output fields to keep; unknown names are omitted")
86        ],
87        "output_fields": fields
88    })
89}
90
91fn offset_paged(name: &str, description: &str, fields: Vec<Value>) -> Value {
92    json!({
93        "name": name, "description": description, "effects": "read_only", "cardinality": "unbounded",
94        "pagination": {"style": "offset", "offset_arg": "--offset", "limit_arg": "--limit"},
95        "fields_arg": "--fields",
96        "args": [
97            {"name": "--limit", "type": "integer", "default": 50, "x-minimum": 1, "x-maximum": 100, "description": "Maximum records in this page"},
98            {"name": "--offset", "type": "integer", "default": 0, "x-minimum": 0, "description": "Number of records to skip; use next_offset from the previous page"},
99            arg("--fields", "string", "Comma-separated top-level output fields to keep; unknown names are omitted")
100        ],
101        "output_fields": fields
102    })
103}
104
105fn conversation_args() -> Vec<Value> {
106    vec![
107        json!({"name": "--chat", "type": "string", "x-conflicts": ["--team", "--channel"], "description": "Chat ID from chats list; give this, or --team with --channel"}),
108        json!({"name": "--team", "type": "string", "x-requires": ["--channel"], "description": "Team ID (Graph only)"}),
109        json!({"name": "--channel", "type": "string", "x-requires": ["--team"], "description": "Channel ID within --team (Graph only)"}),
110    ]
111}
112
113/// Error kinds each command can return, beyond `invalid_input` and `unexpected_error`,
114/// which every command can.
115fn command_errors(name: &str) -> &'static [&'static str] {
116    const GRAPH_READ: &[&str] = &[
117        "auth",
118        "permission_denied",
119        "not_found",
120        "rate_limit",
121        "api_error",
122        "unsupported",
123    ];
124    const CONVERSATION_READ: &[&str] = &[
125        "auth",
126        "permission_denied",
127        "not_found",
128        "rate_limit",
129        "api_error",
130        "unsupported",
131        "desktop_error",
132    ];
133    match name {
134        "init" => &[
135            "auth",
136            "tty_required",
137            "confirmation_required",
138            "unsupported",
139            "desktop_error",
140        ],
141        "auth login" => &["auth", "tty_required", "unsupported"],
142        "auth logout" => &["unsupported"],
143        "auth status" => &["auth", "rate_limit", "api_error", "desktop_error"],
144        "profile remove" => &["confirmation_required"],
145        "whoami" | "list" | "channels list" => GRAPH_READ,
146        "chats list" | "messages list" => CONVERSATION_READ,
147        "messages send" => &[
148            "auth",
149            "read_only",
150            "permission_denied",
151            "not_found",
152            "rate_limit",
153            "api_error",
154            "confirmation_required",
155            "unconfirmed",
156            "unsupported",
157            "desktop_error",
158        ],
159        "messages status" => &["unsupported", "desktop_error"],
160        "desktop status" => &["desktop_error", "unsupported"],
161        "desktop login" | "desktop connect" | "desktop disconnect" | "desktop recover" => {
162            &["desktop_error", "unsupported", "confirmation_required"]
163        }
164        "tui" => &["tty_required"],
165        "doctor" => &["unhealthy"],
166        "schema" => &["not_found"],
167        _ => &[],
168    }
169}
170
171fn example(name: &str) -> Value {
172    let (args, stdin): (&[&str], Option<&str>) = match name {
173        "init" => (&["init", "--no-login"], None),
174        "auth login" => (&["auth", "login", "--device-code"], None),
175        "auth logout" => (&["auth", "logout"], None),
176        "auth status" => (&["auth", "status", "--offline"], None),
177        "profile list" => (&["profile", "list"], None),
178        "profile use" => (&["profile", "use", "work"], None),
179        "profile remove" => (&["profile", "remove", "old", "--yes"], None),
180        "config show" => (&["config", "show"], None),
181        "config path" => (&["config", "path"], None),
182        "whoami" => (&["whoami"], None),
183        "list" => (&["list", "--limit", "20"], None),
184        "channels list" => (&["channels", "list", "TEAM_ID"], None),
185        "chats list" => (
186            &[
187                "chats",
188                "list",
189                "--limit",
190                "20",
191                "--fields",
192                "id,topic,lastUpdatedDateTime",
193            ],
194            None,
195        ),
196        "messages list" => (
197            &["messages", "list", "--chat", "CHAT_ID", "--limit", "20"],
198            None,
199        ),
200        "messages send" => (
201            &[
202                "messages", "send", "--chat", "CHAT_ID", "--body", "-", "--yes",
203            ],
204            Some("On it."),
205        ),
206        "messages status" => (
207            &[
208                "messages",
209                "status",
210                "--chat",
211                "CHAT_ID",
212                "--client-message-id",
213                "100000000000000001",
214            ],
215            None,
216        ),
217        "desktop status" => (&["desktop", "status", "--port", "9222"], None),
218        "desktop login" => (
219            &["desktop", "login", "--desktop-client", "browser", "--yes"],
220            None,
221        ),
222        "desktop connect" => (&["desktop", "connect", "--port", "9222", "--yes"], None),
223        "desktop disconnect" => (&["desktop", "disconnect", "--port", "9222", "--yes"], None),
224        "desktop recover" => (&["desktop", "recover", "--port", "9222"], None),
225        "tui" => (&["tui", "--demo", "--snapshot"], None),
226        "doctor" => (&["doctor", "--offline"], None),
227        "capabilities" => (&["capabilities"], None),
228        "schema" => (&["schema", "--command", "messages send"], None),
229        "completions" => (&["completions", "bash"], None),
230        _ => return Value::Null,
231    };
232    let mut value = json!({"args": args});
233    if let Some(stdin) = stdin {
234        value["stdin"] = json!(stdin);
235    }
236    value
237}
238
239pub fn generate(command_filter: Option<&str>) -> Value {
240    let identity = vec![
241        field("id", "string"),
242        field("displayName", "string"),
243        field("userPrincipalName", "string"),
244        nullable_field("mail", "string"),
245    ];
246    let mut commands = vec![
247        {
248            let mut value = single(
249                "init",
250                "Configure a Graph or experimental desktop profile; desktop init opens Teams' debugging port (restarting Teams after confirmation) and verifies a chat read",
251                "non_idempotent",
252                vec![
253                    field("profile", "string"),
254                    field("backend", "string"),
255                    field("config_path", "string"),
256                    nullable_field("signed_in", "boolean"),
257                    field("client_id", "string"),
258                    field("tenant", "string"),
259                    field("channel_history_requested", "boolean"),
260                    field("read_only", "boolean"),
261                    nullable_field("desktop_port", "integer"),
262                    nullable_field("desktop_account", "string"),
263                    nullable_field("desktop_client", "string"),
264                    nullable_field("endpoint_available", "boolean"),
265                    nullable_field("connection", "object"),
266                    field("session_verified", "boolean"),
267                    nullable_field("teams_restarted", "boolean"),
268                    nullable_field("browser_started", "boolean"),
269                    nullable_field("chat_list_empty", "boolean"),
270                ],
271            );
272            value["args"] = json!([
273                {"name":"--backend","type":"string","enum":["graph","desktop"],"default":"graph","description":"Connection method; desktop supports diagnostics, chats and opt-in chat sending"},
274                {"name":"--desktop-port","type":"integer","description":"Loopback endpoint port (desktop only; native/browser default 9222, browser-core default 9223)","x-minimum":1024,"x-maximum":65535},
275                {"name":"--desktop-client","type":"string","enum":["native","browser","browser-core"],"default":"native","description":"Native Teams, installed Chrome/Edge, or a managed lightweight browser; core defaults to personal and downloads a matching browser pair on first sign-in"},
276                {"name":"--desktop-account","type":"string","enum":["auto","personal","work-school"],"default":"auto","description":"Select the Teams account surface; defaults to personal for browser-core, auto otherwise; multiple cached accounts remain unsupported"},
277                arg(
278                    "--client-id",
279                    "string",
280                    "Override the maintained teams-cli public-client application ID"
281                ),
282                arg("--tenant", "string", "Tenant ID, domain, or organizations"),
283                arg(
284                    "--no-login",
285                    "boolean",
286                    "Save configuration without sign-in or contacting Teams"
287                ),
288                arg("--device-code", "boolean", "Use device-code sign-in"),
289                arg(
290                    "--channel-history",
291                    "boolean",
292                    "Request admin-consented channel-history access"
293                ),
294                {"name":"--read-only","type":"boolean","x-conflicts":["--allow-send"],"description":"Block remote write operations"},
295                {"name":"--allow-send","type":"boolean","x-requires":{"--backend":"desktop"},"x-conflicts":["--read-only"],"description":"Allow a desktop profile to send chat messages (desktop profiles are read-only otherwise)"}
296            ]);
297            value["confirmation_bypass_arg"] = json!("--yes");
298            value
299        },
300        {
301            let mut value = single(
302                "auth login",
303                "Sign in with delegated Microsoft OAuth and protect credentials in the OS store",
304                "idempotent",
305                vec![
306                    field("profile", "string"),
307                    field("expires_at", "integer"),
308                    nullable_field("scope", "string"),
309                    field("channel_history_requested", "boolean"),
310                ],
311            );
312            value["args"] = json!([
313                arg(
314                    "--device-code",
315                    "boolean",
316                    "Use device-code sign-in for headless and remote environments"
317                ),
318                arg(
319                    "--channel-history",
320                    "boolean",
321                    "Request admin-consented channel-history access"
322                )
323            ]);
324            value
325        },
326        single(
327            "auth logout",
328            "Remove locally stored delegated credentials",
329            "idempotent",
330            vec![field("profile", "string"), field("signed_in", "boolean")],
331        ),
332        {
333            let mut value = single(
334                "auth status",
335                "Verify authentication and inspect credential state",
336                "read_only",
337                vec![
338                    field("profile", "string"),
339                    field("configured", "boolean"),
340                    field("backend", "string"),
341                    nullable_field("signed_in", "boolean"),
342                    field("verified", "boolean"),
343                    nullable_field("identity", "object"),
344                    field("config_path", "string"),
345                    field("read_only", "boolean"),
346                    nullable_array_field("granted_scopes", "string"),
347                    nullable_field("channel_history", "boolean"),
348                    nullable_field("endpoint_available", "boolean"),
349                    nullable_field("connection", "object"),
350                    field("session_verified", "boolean"),
351                ],
352            );
353            value["args"] = json!([arg(
354                "--offline",
355                "boolean",
356                "Inspect local state without contacting Graph or the desktop endpoint"
357            )]);
358            value
359        },
360        single(
361            "profile list",
362            "List configured profiles and identify the active one",
363            "read_only",
364            vec![
365                json!({"name": "items", "type": "array", "items": {"type": "object", "fields": [
366                    field("name", "string"),
367                    field("active", "boolean"),
368                    json!({"name": "backend", "type": "string", "enum": ["graph", "desktop"]}),
369                    field("client_id", "string"),
370                    field("tenant", "string"),
371                    field("read_only", "boolean")
372                ]}}),
373                field("total", "integer"),
374            ],
375        ),
376        {
377            let mut value = single(
378                "profile use",
379                "Select the default profile for future commands",
380                "idempotent",
381                vec![field("profile", "string"), field("active", "boolean")],
382            );
383            value["args"] = json!([required_arg("name", "string", "Profile name")]);
384            value
385        },
386        {
387            let mut value = single(
388                "profile remove",
389                "Remove a profile and its stored credential",
390                "idempotent",
391                vec![field("profile", "string"), field("removed", "boolean")],
392            );
393            value["args"] = json!([required_arg("name", "string", "Profile name")]);
394            value["confirmation_bypass_arg"] = json!("--yes");
395            value
396        },
397        single(
398            "config show",
399            "Print the resolved profile without credentials",
400            "read_only",
401            vec![
402                field("profile", "string"),
403                field("backend", "string"),
404                nullable_field("desktop_port", "integer"),
405                nullable_field("desktop_account", "string"),
406                nullable_field("desktop_client", "string"),
407                field("client_id", "string"),
408                field("tenant", "string"),
409                field("read_only", "boolean"),
410                field("config_path", "string"),
411            ],
412        ),
413        single(
414            "config path",
415            "Print the absolute configuration file path",
416            "read_only",
417            vec![],
418        ),
419        single(
420            "whoami",
421            "Show the signed-in Microsoft 365 identity",
422            "read_only",
423            identity,
424        ),
425        offset_paged(
426            "list",
427            "List teams joined by the signed-in user",
428            vec![
429                field("id", "string"),
430                field("displayName", "string"),
431                nullable_field("description", "string"),
432            ],
433        ),
434        {
435            let mut value = offset_paged(
436                "channels list",
437                "List channels in a team",
438                vec![
439                    field("id", "string"),
440                    field("displayName", "string"),
441                    nullable_field("description", "string"),
442                    field("membershipType", "string"),
443                ],
444            );
445            value["args"]
446                .as_array_mut()
447                .unwrap()
448                .insert(0, required_arg("team", "string", "Team ID"));
449            value
450        },
451        paged(
452            "chats list",
453            "List one-to-one, group, and meeting chats",
454            vec![
455                described(
456                    field("id", "string"),
457                    "Chat ID for messages list/send; the chat with yourself is 48:notes on desktop",
458                ),
459                json!({"name": "chatType", "type": "string", "enum": ["oneOnOne", "group", "meeting"]}),
460                nullable_field("topic", "string"),
461                described(field("lastUpdatedDateTime", "string"), "RFC 3339"),
462                json!({"name": "members", "type": "array", "items": {"type": "object", "fields": [
463                    field("userId", "string"),
464                    nullable_field("displayName", "string"),
465                    described(field("avatarData", "string"), "Optional desktop-only raster data URI, from a photo already loaded by the selected Teams page; absent when unavailable")
466                ]}}),
467                described(
468                    field("avatarData", "string"),
469                    "Optional desktop-only one-to-one chat avatar as a raster data URI; member photos may be available for groups",
470                ),
471                object_field(
472                    "viewpoint",
473                    true,
474                    "The signed-in user's read state",
475                    vec![nullable_field("lastMessageReadDateTime", "string")],
476                ),
477                object_field(
478                    "lastMessagePreview",
479                    true,
480                    "Latest message; desktop only",
481                    vec![
482                        field("id", "string"),
483                        field("createdDateTime", "string"),
484                        sender(),
485                        body(),
486                    ],
487                ),
488            ],
489        ),
490        {
491            let mut value = paged(
492                "messages list",
493                "List messages from one chat, or from a channel with optional admin-consented access",
494                vec![
495                    field("id", "string"),
496                    described(
497                        field("createdDateTime", "string"),
498                        "RFC 3339; pages are newest first",
499                    ),
500                    sender(),
501                    body(),
502                    described(nullable_field("deleted", "boolean"), "Desktop only"),
503                    described(
504                        nullable_field("clientMessageId", "string"),
505                        "Desktop cache only; exact send correlation ID",
506                    ),
507                    described(
508                        nullable_field("status", "string"),
509                        "Desktop cache only; raw Teams status",
510                    ),
511                ],
512            );
513            let args = value["args"].as_array_mut().unwrap();
514            args.splice(0..0, conversation_args());
515            value
516        },
517        {
518            let mut value = single(
519                "messages send",
520                "Send one plain-text message as the signed-in user",
521                "non_idempotent",
522                vec![
523                    described(field("id", "string"), "Message ID"),
524                    nullable_field("createdDateTime", "string"),
525                    nullable_field("webUrl", "string"),
526                    nullable_field("chatId", "string"),
527                    described(
528                        nullable_field("source", "string"),
529                        "\"desktop\" for desktop sends",
530                    ),
531                    described(
532                        nullable_field("clientMessageId", "string"),
533                        "Desktop only; correlation ID, not an idempotency key",
534                    ),
535                    described(
536                        nullable_field("delivery_state", "string"),
537                        "Desktop only: submitted, queued, delivered, failed or unknown",
538                    ),
539                    described(
540                        nullable_field("status", "string"),
541                        "Desktop only; Teams' own delivery label, e.g. Delivered",
542                    ),
543                ],
544            );
545            let mut args = conversation_args();
546            args.push(json!({"name": "--body", "type": "string", "required": true, "x-max-length": crate::desktop::MAX_BODY,
547                "description": "Plain-text message body, or - to read it from stdin; must not be blank"}));
548            value["args"] = json!(args);
549            value["confirmation_bypass_arg"] = json!("--yes");
550            value
551        },
552        json!({"name":"tui", "description":"Open the keyboard-first terminal interface; offers a confirmed Teams debugging restart on WSL when no endpoint listens; Enter sends a chat message on a profile that allows writes", "effects":"non_idempotent", "output_kind":"opaque", "media_type":"text/plain", "requires_tty":true, "args":[arg("--demo", "boolean", "Use deterministic sample data"), arg("--snapshot", "boolean", "Print one ANSI-free demo frame")]}),
553        {
554            let mut value = single(
555                "doctor",
556                "Check configuration and the selected backend's access (desktop checks endpoint metadata)",
557                "read_only",
558                vec![
559                    field("backend", "string"),
560                    array_field("checks", "object"),
561                    field("healthy", "boolean"),
562                    nullable_field("connection", "object"),
563                    nullable_field("endpoint_available", "boolean"),
564                    field("session_verified", "boolean"),
565                    debugging_setup(),
566                ],
567            );
568            value["args"] = json!([arg(
569                "--offline",
570                "boolean",
571                "Check local state without contacting Graph or the desktop endpoint"
572            )]);
573            value
574        },
575        single(
576            "capabilities",
577            "Describe supported and deliberately unsupported capabilities",
578            "read_only",
579            vec![
580                array_field("supported", "string"),
581                array_field("unsupported", "string"),
582                array_field("account_types", "string"),
583                field("api", "string"),
584                array_field("notes", "string"),
585                field("backends", "object"),
586            ],
587        ),
588        json!({
589            "name":"schema",
590            "description":"Emit the offline CLI Spec v0.3 contract",
591            "effects":"read_only",
592            "cardinality":"single",
593            "stdout_schema":{},
594            "args":[arg("--command", "string", "Return only one complete command path")]
595        }),
596        json!({"name":"completions", "description":"Generate a shell completion script", "effects":"read_only", "output_kind":"opaque", "media_type":"text/plain", "args":[arg("shell", "string", "Shell name")]}),
597    ];
598    let mut status = single(
599        "messages status",
600        "Reconcile one client message ID against the newest 50 cached desktop messages; absence remains unknown",
601        "read_only",
602        vec![
603            field("chatId", "string"),
604            field("clientMessageId", "string"),
605            field("found", "boolean"),
606            nullable_field("id", "string"),
607            nullable_field("status", "string"),
608            field("delivery_state", "string"),
609            field("source", "string"),
610            field("scope", "string"),
611            field("retryable", "boolean"),
612        ],
613    );
614    status["args"] = json!([
615        required_arg("--chat", "string", "Chat ID"),
616        required_arg(
617            "--client-message-id",
618            "string",
619            "18-digit correlation ID returned by send or unconfirmed error"
620        )
621    ]);
622    commands.push(status);
623    for (name, description, effects) in [
624        (
625            "desktop login",
626            "Sign in visibly, verify chats, then restart headless with the same dedicated profile; browser only, requires confirmation",
627            "non_idempotent",
628        ),
629        (
630            "desktop status",
631            "Inspect endpoint metadata and managed-session state; does not verify sign-in",
632            "read_only",
633        ),
634        (
635            "desktop connect",
636            "Open a dedicated browser, or restart native Teams with debugging; requires confirmation",
637            "non_idempotent",
638        ),
639        (
640            "desktop disconnect",
641            "Close the verified dedicated browser, or restart managed native Teams normally; requires confirmation",
642            "non_idempotent",
643        ),
644        (
645            "desktop recover",
646            "Restore interrupted native settings; browser recovery may close a verified dedicated browser and requires confirmation",
647            "idempotent",
648        ),
649    ] {
650        let mut value = single(
651            name,
652            description,
653            effects,
654            vec![
655                field("port", "integer"),
656                nullable_field("endpoint_available", "boolean"),
657                field("session_verified", "boolean"),
658                field("management", "object"),
659                nullable_field("connection", "object"),
660                nullable_field("browser_profile", "string"),
661            ],
662        );
663        value["args"] = json!([{"name":"--desktop-client","type":"string","enum":["native","browser","browser-core"],"description":"Override the configured desktop client"},{"name":"--port","type":"integer","x-minimum":1024,"x-maximum":65535,"description":"Override selected profile port"}]);
664        if name == "desktop connect" {
665            value["args"].as_array_mut().expect("args").push(arg(
666                "--visible",
667                "boolean",
668                "Open the browser visibly for sign-in; browser client only",
669            ));
670        }
671        if matches!(
672            name,
673            "desktop login" | "desktop connect" | "desktop disconnect" | "desktop recover"
674        ) {
675            value["confirmation_bypass_arg"] = json!("--yes");
676        }
677        commands.push(value);
678    }
679    for command in &mut commands {
680        let name = command["name"].as_str().unwrap_or_default().to_string();
681        let mut errors = vec!["invalid_input", "unexpected_error"];
682        errors.extend(command_errors(&name));
683        command["errors"] = json!(errors);
684        let example = example(&name);
685        if !example.is_null() {
686            command["example"] = example;
687        }
688        command["extensions"] = json!({"backends": match command["name"].as_str().unwrap_or_default() {
689            "auth login" | "auth logout" | "whoami" | "list" | "channels list" => vec!["graph"],
690            "desktop status" | "desktop login" | "desktop connect" | "desktop disconnect" | "desktop recover" | "messages status" => vec!["desktop"],
691            _ => vec!["graph", "desktop"],
692        }});
693        match command["name"].as_str().unwrap_or_default() {
694            "tui" => {
695                command["extensions"]["desktop"] = json!(
696                    "macOS/Windows/WSL (browser client also on Linux); chats and chat messages from the Teams client's local cache; sending needs a profile created with --allow-send"
697                )
698            }
699            "chats list" | "messages list" => {
700                command["extensions"]["desktop"] = json!(
701                    "macOS/Windows/WSL (browser client also on Linux); chats, not channels; read from the Teams client's local cache; pages carry source \"desktop_cache\""
702                )
703            }
704            "messages send" => {
705                command["extensions"]["desktop"] = json!(
706                    "macOS/Windows/WSL (browser client also on Linux); plain-text chat messages through the running Teams window; needs a profile created with `init --allow-send`; prompts on a terminal and needs --yes otherwise; results carry source \"desktop\", clientMessageId and Teams' status"
707                )
708            }
709            _ => {}
710        }
711    }
712    if let Some(filter) = command_filter {
713        commands.retain(|value| value["name"] == filter);
714    }
715    json!({
716        "$schema": "https://clispec.dev/schema/v0.3.json",
717        "clispec": "0.3",
718        "name": "teams",
719        "version": env!("CARGO_PKG_VERSION"),
720        "description": "A Microsoft Teams CLI and TUI designed equally for humans and agents",
721        "output": {"tty": "text", "piped": "json"},
722        "global_args": [
723            {"name":"--output", "short":"-o", "type":"string", "enum":["auto","text","json"], "default":"auto", "description":"Output format"},
724            {"name":"--profile", "type":"string", "x-env":"TEAMS_PROFILE", "description":"Configuration profile; defaults to the active one"},
725            {"name":"--quiet", "type":"boolean", "description":"Suppress informational stderr output"},
726            {"name":"--yes", "short":"-y", "type":"boolean", "description":"Confirm without prompting (desktop sends, profile removal)"}
727        ],
728        "commands": commands,
729        "errors": error::ALL.iter().map(|e| json!({"kind":e.kind,"exit_code":e.exit_code,"retryable":e.retryable,"description":e.description})).collect::<Vec<_>>(),
730        "extensions": {
731            "backends":backend_capabilities(),
732            "authentication":"delegated_oauth",
733            "api":"Microsoft Graph v1.0",
734            "default_client_id": crate::config::DEFAULT_CLIENT_ID,
735            "login_modes":["browser_pkce","device_code"],
736            "read_only_env":"TEAMS_READ_ONLY",
737            "environment":{
738                "TEAMS_PROFILE":"Profile to use when --profile is not given",
739                "TEAMS_READ_ONLY":"true blocks every remote write; false cannot unlock a desktop profile",
740                "TEAMS_ACCESS_TOKEN":"Graph access token that overrides the stored credential for this run",
741                "TEAMS_CLIENT_ID":"Graph application ID override",
742                "TEAMS_TENANT":"Graph tenant override",
743                "TEAMS_DESKTOP_HELPER":"Path to a teams.exe speaking the same helper protocol to use as the WSL desktop helper"
744            },
745            "collection_envelope":{
746                "items":"array of records described by the command's output_fields",
747                "next_cursor":"cursor-paged commands: pass to --cursor for the next page; absent on the last page",
748                "next_offset":"offset-paged commands: pass to --offset for the next page; absent on the last page",
749                "truncated":"true when more records exist",
750                "source":"\"desktop_cache\" when records come from the Teams client's local cache; absent for Graph"
751            },
752            "error_envelope":"stderr carries {\"error\":{\"kind\",\"message\",\"retryable\"}} when stdout is not a terminal or --output json is given; rate_limit adds retry_after_seconds when Microsoft sends it; uncertain desktop sends add chatId, clientMessageId and delivery_state unknown",
753            "idempotency":"Sends cannot be made idempotent: neither Graph nor Teams accepts a caller-supplied key. Never resend after unconfirmed without reading the conversation first.",
754            "baseline_scopes": crate::auth::BASE_SCOPES.split_whitespace().collect::<Vec<_>>(),
755            "privileged_scopes":[crate::auth::CHANNEL_HISTORY_SCOPE]
756        }
757    })
758}
759
760pub fn backend_capabilities() -> Value {
761    json!({
762        "graph":{"default":true,"authentication":"delegated_oauth","api":"Microsoft Graph v1.0","account_types":["Microsoft 365 work or school"]},
763        "desktop":{"experimental":true,"read_only_by_default":true,"platforms":["macos","windows","wsl","linux"],"clients":{"native":["macos","windows","wsl"],"browser":["macos","linux","wsl"],"browser-core":["macos","linux","wsl"]},"browser_validation":"experimental; core personal messaging validated on macOS only","browser_core":{"account_types":["personal"],"bootstrap":"build-pinned; unknown builds refused","browser_versions":"automatically installed matching Chrome for Testing and chrome-headless-shell; paired path overrides supported","live_validation":["macos-personal"]},
764            "account_types":["Microsoft 365 work or school","personal Microsoft accounts"],"account_selection":"account_type_then_single_account_only",
765            "authentication":"teams_desktop_session_unverified","supported":["configuration","connection metadata","doctor","auth status","managed connect/status/disconnect/recover","delivery reconciliation by client message ID","chats (macos, windows, wsl; browser also on linux)","chat messages (macos, windows, wsl; browser also on linux)","send plain-text chat messages (macos, windows, wsl; browser also on linux; opt-in)","TUI (macos, windows, wsl; browser also on linux)"],
766            "unsupported":["teams and channels","identity","channel messages, replies, mentions, attachments and edits","subscriptions","unconfirmed Teams launch or restart"],
767            "requires":"native: Teams-owned loopback debugging endpoint (WSL needs Windows interop); browser: installed Chrome/Chromium/Edge with a dedicated profile and visible initial sign-in",
768            "transport":{"macos":"native_loopback","windows":"windows_native","wsl":"windows_helper_stdio","browser":"dedicated_chromium_loopback"},
769            "chat_source":"desktop_cache","session_verified":false,"default_port":crate::config::DEFAULT_DESKTOP_PORT}
770    })
771}