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 pass debugging flags only to the Teams launch; recover clears an interrupted setup; clear-flags removes debugging flags from the user-wide WebView2 setting after confirmation",
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" | "people search" => CONVERSATION_READ,
147        "messages send" | "chats create" => &[
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        "people search" => (&["people", "search", "Alex", "--limit", "20"], None),
197        "chats create" => (
198            &["chats", "create", "--recipient", "PERSON_ID", "--yes"],
199            None,
200        ),
201        "messages list" => (
202            &["messages", "list", "--chat", "CHAT_ID", "--limit", "20"],
203            None,
204        ),
205        "messages send" => (
206            &[
207                "messages", "send", "--chat", "CHAT_ID", "--body", "-", "--yes",
208            ],
209            Some("On it."),
210        ),
211        "messages status" => (
212            &[
213                "messages",
214                "status",
215                "--chat",
216                "CHAT_ID",
217                "--client-message-id",
218                "100000000000000001",
219            ],
220            None,
221        ),
222        "desktop status" => (&["desktop", "status", "--port", "9222"], None),
223        "desktop login" => (
224            &["desktop", "login", "--desktop-client", "browser", "--yes"],
225            None,
226        ),
227        "desktop connect" => (&["desktop", "connect", "--port", "9222", "--yes"], None),
228        "desktop disconnect" => (&["desktop", "disconnect", "--port", "9222", "--yes"], None),
229        "desktop recover" => (&["desktop", "recover", "--port", "9222"], None),
230        "tui" => (&["tui", "--demo", "--snapshot"], None),
231        "doctor" => (&["doctor", "--offline"], None),
232        "capabilities" => (&["capabilities"], None),
233        "schema" => (&["schema", "--command", "messages send"], None),
234        "completions" => (&["completions", "bash"], None),
235        _ => return Value::Null,
236    };
237    let mut value = json!({"args": args});
238    if let Some(stdin) = stdin {
239        value["stdin"] = json!(stdin);
240    }
241    value
242}
243
244pub fn generate(command_filter: Option<&str>) -> Value {
245    let identity = vec![
246        field("id", "string"),
247        field("displayName", "string"),
248        field("userPrincipalName", "string"),
249        nullable_field("mail", "string"),
250    ];
251    let mut commands = vec![
252        {
253            let mut value = single(
254                "init",
255                "Guided account setup in a terminal without connection flags; otherwise configure a Graph or experimental desktop profile. Browser setup verifies a chat read; native setup may restart Teams after confirmation",
256                "non_idempotent",
257                vec![
258                    field("profile", "string"),
259                    field("backend", "string"),
260                    field("config_path", "string"),
261                    nullable_field("signed_in", "boolean"),
262                    field("client_id", "string"),
263                    field("tenant", "string"),
264                    field("channel_history_requested", "boolean"),
265                    nullable_field("credential_store", "string"),
266                    nullable_field("pass_store_dir", "string"),
267                    field("read_only", "boolean"),
268                    nullable_field("desktop_port", "integer"),
269                    nullable_field("desktop_account", "string"),
270                    nullable_field("desktop_client", "string"),
271                    nullable_field("browser_auto_start", "boolean"),
272                    nullable_field("endpoint_available", "boolean"),
273                    nullable_field("connection", "object"),
274                    field("session_verified", "boolean"),
275                    nullable_field("send_capability_verified", "boolean"),
276                    nullable_field("teams_restarted", "boolean"),
277                    nullable_field("browser_started", "boolean"),
278                    nullable_field("chat_list_empty", "boolean"),
279                ],
280            );
281            value["args"] = json!([
282                {"name":"--backend","type":"string","enum":["graph","desktop"],"default":"graph","description":"Connection method; default Graph in scripts, guided account selection in a terminal with no connection flags"},
283                {"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},
284                {"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"},
285                {"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"},
286                arg(
287                    "--client-id",
288                    "string",
289                    "Override the maintained teams-cli public-client application ID"
290                ),
291                arg("--tenant", "string", "Tenant ID, domain, or organizations"),
292                arg(
293                    "--no-login",
294                    "boolean",
295                    "Save configuration without sign-in or contacting Teams"
296                ),
297                {"name":"--credential-store","type":"string","enum":["native","pass"],"description":"Graph only: OS credential store (Windows DPAPI under WSL) or an initialized GPG-encrypted pass store. Saved per profile; existing profiles keep their choice"},
298                arg("--pass-store-dir", "string", "Existing pass directory (Graph/pass only); resolved to an absolute path and saved per profile"),
299                arg("--device-code", "boolean", "Use device-code sign-in"),
300                arg(
301                    "--channel-history",
302                    "boolean",
303                    "Request admin-consented channel-history access"
304                ),
305                {"name":"--read-only","type":"boolean","x-conflicts":["--allow-send"],"description":"Block remote write operations"},
306                {"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)"},
307                {"name":"--auto-start","type":"boolean","x-requires":{"--backend":"desktop"},"description":"Opt in to reopening a dedicated browser when the interactive inbox starts; never applies to native Teams or CLI read commands"}
308            ]);
309            value["confirmation_bypass_arg"] = json!("--yes");
310            value
311        },
312        {
313            let mut value = single(
314                "auth login",
315                "Sign in with delegated Microsoft OAuth and protect credentials in the profile's saved credential store",
316                "idempotent",
317                vec![
318                    field("profile", "string"),
319                    field("expires_at", "integer"),
320                    nullable_field("scope", "string"),
321                    field("channel_history_requested", "boolean"),
322                ],
323            );
324            value["args"] = json!([
325                arg(
326                    "--device-code",
327                    "boolean",
328                    "Use device-code sign-in for headless and remote environments"
329                ),
330                arg(
331                    "--channel-history",
332                    "boolean",
333                    "Request admin-consented channel-history access"
334                )
335            ]);
336            value
337        },
338        single(
339            "auth logout",
340            "Remove locally stored delegated credentials",
341            "idempotent",
342            vec![field("profile", "string"), field("signed_in", "boolean")],
343        ),
344        {
345            let mut value = single(
346                "auth status",
347                "Verify authentication and inspect credential state",
348                "read_only",
349                vec![
350                    field("profile", "string"),
351                    field("configured", "boolean"),
352                    field("backend", "string"),
353                    nullable_field("signed_in", "boolean"),
354                    nullable_field("credential_store", "string"),
355                    nullable_field("credential_error", "string"),
356                    field("verified", "boolean"),
357                    nullable_field("identity", "object"),
358                    field("config_path", "string"),
359                    field("read_only", "boolean"),
360                    nullable_array_field("granted_scopes", "string"),
361                    nullable_field("channel_history", "boolean"),
362                    nullable_field("endpoint_available", "boolean"),
363                    nullable_field("connection", "object"),
364                    field("session_verified", "boolean"),
365                ],
366            );
367            value["args"] = json!([arg(
368                "--offline",
369                "boolean",
370                "Inspect local state without contacting Graph or the desktop endpoint"
371            )]);
372            value
373        },
374        single(
375            "profile list",
376            "List configured profiles and identify the active one",
377            "read_only",
378            vec![
379                json!({"name": "items", "type": "array", "items": {"type": "object", "fields": [
380                    field("name", "string"),
381                    field("active", "boolean"),
382                    json!({"name": "backend", "type": "string", "enum": ["graph", "desktop"]}),
383                    field("client_id", "string"),
384                    field("tenant", "string"),
385                    field("read_only", "boolean")
386                ]}}),
387                field("total", "integer"),
388            ],
389        ),
390        {
391            let mut value = single(
392                "profile use",
393                "Select the default profile for future commands",
394                "idempotent",
395                vec![field("profile", "string"), field("active", "boolean")],
396            );
397            value["args"] = json!([required_arg("name", "string", "Profile name")]);
398            value
399        },
400        {
401            let mut value = single(
402                "profile remove",
403                "Remove a profile and its stored credential",
404                "idempotent",
405                vec![field("profile", "string"), field("removed", "boolean")],
406            );
407            value["args"] = json!([required_arg("name", "string", "Profile name")]);
408            value["confirmation_bypass_arg"] = json!("--yes");
409            value
410        },
411        single(
412            "config show",
413            "Print the resolved profile without credentials",
414            "read_only",
415            vec![
416                field("profile", "string"),
417                field("backend", "string"),
418                nullable_field("desktop_port", "integer"),
419                nullable_field("desktop_account", "string"),
420                nullable_field("desktop_client", "string"),
421                field("browser_auto_start", "boolean"),
422                nullable_field("credential_store", "string"),
423                nullable_field("pass_store_dir", "string"),
424                field("client_id", "string"),
425                field("tenant", "string"),
426                field("read_only", "boolean"),
427                field("config_path", "string"),
428            ],
429        ),
430        single(
431            "config path",
432            "Print the absolute configuration file path",
433            "read_only",
434            vec![],
435        ),
436        single(
437            "whoami",
438            "Show the signed-in Microsoft 365 identity",
439            "read_only",
440            identity,
441        ),
442        offset_paged(
443            "list",
444            "List teams joined by the signed-in user",
445            vec![
446                field("id", "string"),
447                field("displayName", "string"),
448                nullable_field("description", "string"),
449            ],
450        ),
451        {
452            let mut value = offset_paged(
453                "channels list",
454                "List channels in a team",
455                vec![
456                    field("id", "string"),
457                    field("displayName", "string"),
458                    nullable_field("description", "string"),
459                    field("membershipType", "string"),
460                ],
461            );
462            value["args"]
463                .as_array_mut()
464                .unwrap()
465                .insert(0, required_arg("team", "string", "Team ID"));
466            value
467        },
468        {
469            let mut value = single(
470                "people search",
471                "Find up to 50 verified people by name or email; refine the query when truncated; never sends or creates a chat",
472                "read_only",
473                vec![
474                    field("id", "string"),
475                    field("displayName", "string"),
476                    nullable_field("email", "string"),
477                    field("source", "string"),
478                ],
479            );
480            value["cardinality"] = json!("bounded");
481            value["args"] = json!([
482                {"name":"query","type":"string","required":true,"x-min-length":2,"x-max-length":256,"description":"Name or email prefix; 2–256 characters, no control characters"},
483                {"name":"--limit","type":"integer","default":20,"x-minimum":1,"x-maximum":50,"description":"Maximum matching people; refine the query for more specific results"}
484            ]);
485            value
486        },
487        {
488            let mut value = single(
489                "chats create",
490                "Create or reuse a one-to-one conversation with a verified person; requires a writable profile and confirmation; sends no message",
491                "idempotent",
492                vec![
493                    field("id", "string"),
494                    field("chatType", "string"),
495                    nullable_field("topic", "string"),
496                    nullable_field("source", "string"),
497                ],
498            );
499            value["args"] = json!([required_arg(
500                "--recipient",
501                "string",
502                "Exact person ID from people search in the same profile"
503            )]);
504            value["confirmation_bypass_arg"] = json!("--yes");
505            value
506        },
507        paged(
508            "chats list",
509            "List one-to-one, group, and meeting chats",
510            vec![
511                described(
512                    field("id", "string"),
513                    "Chat ID for messages list/send; the chat with yourself is 48:notes on desktop",
514                ),
515                json!({"name": "chatType", "type": "string", "enum": ["oneOnOne", "group", "meeting"]}),
516                nullable_field("topic", "string"),
517                described(field("lastUpdatedDateTime", "string"), "RFC 3339"),
518                json!({"name": "members", "type": "array", "items": {"type": "object", "fields": [
519                    field("userId", "string"),
520                    nullable_field("displayName", "string"),
521                    described(field("avatarData", "string"), "Optional desktop-only raster data URI, from a photo already loaded by the selected Teams page; absent when unavailable")
522                ]}}),
523                described(
524                    field("avatarData", "string"),
525                    "Optional desktop-only one-to-one chat avatar as a raster data URI; member photos may be available for groups",
526                ),
527                object_field(
528                    "viewpoint",
529                    true,
530                    "The signed-in user's read state",
531                    vec![nullable_field("lastMessageReadDateTime", "string")],
532                ),
533                object_field(
534                    "lastMessagePreview",
535                    true,
536                    "Latest message; desktop only",
537                    vec![
538                        field("id", "string"),
539                        field("createdDateTime", "string"),
540                        sender(),
541                        body(),
542                    ],
543                ),
544            ],
545        ),
546        {
547            let mut value = paged(
548                "messages list",
549                "List messages from one chat, or from a channel with optional admin-consented access",
550                vec![
551                    field("id", "string"),
552                    described(
553                        field("createdDateTime", "string"),
554                        "RFC 3339; pages are newest first",
555                    ),
556                    sender(),
557                    body(),
558                    described(nullable_field("deleted", "boolean"), "Desktop only"),
559                    described(
560                        nullable_field("clientMessageId", "string"),
561                        "Desktop cache only; exact send correlation ID",
562                    ),
563                    described(
564                        nullable_field("status", "string"),
565                        "Desktop cache only; raw Teams status",
566                    ),
567                ],
568            );
569            let args = value["args"].as_array_mut().unwrap();
570            args.splice(0..0, conversation_args());
571            value
572        },
573        {
574            let mut value = single(
575                "messages send",
576                "Send one plain-text message as the signed-in user",
577                "non_idempotent",
578                vec![
579                    described(field("id", "string"), "Message ID"),
580                    nullable_field("createdDateTime", "string"),
581                    nullable_field("webUrl", "string"),
582                    nullable_field("chatId", "string"),
583                    described(
584                        nullable_field("source", "string"),
585                        "\"desktop\" for desktop sends",
586                    ),
587                    described(
588                        nullable_field("clientMessageId", "string"),
589                        "Desktop only; correlation ID, not an idempotency key",
590                    ),
591                    described(
592                        nullable_field("delivery_state", "string"),
593                        "Desktop only: submitted, queued, delivered, failed or unknown",
594                    ),
595                    described(
596                        nullable_field("status", "string"),
597                        "Desktop only; Teams' own delivery label, e.g. Delivered",
598                    ),
599                ],
600            );
601            let mut args = conversation_args();
602            args.push(json!({"name": "--body", "type": "string", "required": true, "x-max-length": crate::desktop::MAX_BODY,
603                "description": "Plain-text message body, or - to read it from stdin; must not be blank"}));
604            value["args"] = json!(args);
605            value["confirmation_bypass_arg"] = json!("--yes");
606            value
607        },
608        json!({"name":"tui", "description":"Open the keyboard-first terminal interface; reopens an opted-in browser session on an interactive terminal; 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")]}),
609        {
610            let mut value = single(
611                "doctor",
612                "Check configuration and the selected backend's access (desktop checks endpoint metadata)",
613                "read_only",
614                vec![
615                    field("backend", "string"),
616                    array_field("checks", "object"),
617                    field("healthy", "boolean"),
618                    nullable_field("connection", "object"),
619                    nullable_field("endpoint_available", "boolean"),
620                    field("session_verified", "boolean"),
621                    debugging_setup(),
622                ],
623            );
624            value["args"] = json!([arg(
625                "--offline",
626                "boolean",
627                "Check local state without contacting Graph or the desktop endpoint"
628            )]);
629            value
630        },
631        single(
632            "capabilities",
633            "Describe supported and deliberately unsupported capabilities",
634            "read_only",
635            vec![
636                array_field("supported", "string"),
637                array_field("unsupported", "string"),
638                array_field("account_types", "string"),
639                field("api", "string"),
640                array_field("notes", "string"),
641                field("backends", "object"),
642            ],
643        ),
644        json!({
645            "name":"schema",
646            "description":"Emit the offline CLI Spec v0.3 contract",
647            "effects":"read_only",
648            "cardinality":"single",
649            "stdout_schema":{},
650            "args":[arg("--command", "string", "Return only one complete command path")]
651        }),
652        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")]}),
653    ];
654    let mut status = single(
655        "messages status",
656        "Reconcile one client message ID against the newest 50 cached desktop messages; absence remains unknown",
657        "read_only",
658        vec![
659            field("chatId", "string"),
660            field("clientMessageId", "string"),
661            field("found", "boolean"),
662            nullable_field("id", "string"),
663            nullable_field("status", "string"),
664            field("delivery_state", "string"),
665            field("source", "string"),
666            field("scope", "string"),
667            field("retryable", "boolean"),
668        ],
669    );
670    status["args"] = json!([
671        required_arg("--chat", "string", "Chat ID"),
672        required_arg(
673            "--client-message-id",
674            "string",
675            "18-digit correlation ID returned by send or unconfirmed error"
676        )
677    ]);
678    commands.push(status);
679    for (name, description, effects) in [
680        (
681            "desktop login",
682            "Sign in visibly, verify chats, then restart headless with the same dedicated profile; browser only, requires confirmation",
683            "non_idempotent",
684        ),
685        (
686            "desktop status",
687            "Inspect endpoint metadata and managed-session state; does not verify sign-in",
688            "read_only",
689        ),
690        (
691            "desktop connect",
692            "Open a dedicated browser, or restart native Teams with debugging; requires confirmation",
693            "non_idempotent",
694        ),
695        (
696            "desktop disconnect",
697            "Close the verified dedicated browser, or restart managed native Teams normally; requires confirmation",
698            "non_idempotent",
699        ),
700        (
701            "desktop recover",
702            "Restore interrupted native settings; browser recovery may close a verified dedicated browser and requires confirmation",
703            "idempotent",
704        ),
705    ] {
706        let mut value = single(
707            name,
708            description,
709            effects,
710            vec![
711                field("port", "integer"),
712                nullable_field("endpoint_available", "boolean"),
713                field("session_verified", "boolean"),
714                field("management", "object"),
715                nullable_field("connection", "object"),
716                nullable_field("browser_profile", "string"),
717            ],
718        );
719        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"}]);
720        if name == "desktop connect" {
721            value["args"].as_array_mut().expect("args").push(arg(
722                "--visible",
723                "boolean",
724                "Open the browser visibly for sign-in; browser client only",
725            ));
726        }
727        if matches!(
728            name,
729            "desktop login" | "desktop connect" | "desktop disconnect" | "desktop recover"
730        ) {
731            value["confirmation_bypass_arg"] = json!("--yes");
732        }
733        commands.push(value);
734    }
735    for command in &mut commands {
736        let name = command["name"].as_str().unwrap_or_default().to_string();
737        let mut errors = vec!["invalid_input", "unexpected_error"];
738        errors.extend(command_errors(&name));
739        command["errors"] = json!(errors);
740        let example = example(&name);
741        if !example.is_null() {
742            command["example"] = example;
743        }
744        command["extensions"] = json!({"backends": match command["name"].as_str().unwrap_or_default() {
745            "auth login" | "auth logout" | "whoami" | "list" | "channels list" => vec!["graph"],
746            "desktop status" | "desktop login" | "desktop connect" | "desktop disconnect" | "desktop recover" | "messages status" => vec!["desktop"],
747            _ => vec!["graph", "desktop"],
748        }});
749        match command["name"].as_str().unwrap_or_default() {
750            "tui" => {
751                command["extensions"]["desktop"] = json!(
752                    "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"
753                )
754            }
755            "chats list" | "messages list" => {
756                command["extensions"]["desktop"] = json!(
757                    "macOS/Windows/WSL (browser client also on Linux); chats, not channels; read from the Teams client's local cache; pages carry source \"desktop_cache\""
758                )
759            }
760            "messages send" => {
761                command["extensions"]["desktop"] = json!(
762                    "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"
763                )
764            }
765            "people search" => {
766                command["extensions"]["graph"] = json!(
767                    "Work/school directory profiles; User.ReadBasic.All consent required; guest callers and personal accounts unsupported"
768                );
769                command["extensions"]["desktop"] = json!(
770                    "Uses the selected Teams client's own people search; IDs belong to that account and must not be reused with another profile"
771                );
772            }
773            "chats create" => {
774                command["extensions"]["graph"] = json!(
775                    "Chat.Create; includes the signed-in user and verified recipient; returns an existing one-on-one chat when present; no automatic retry after an unconfirmed response"
776                );
777                command["extensions"]["desktop"] = json!(
778                    "Needs a profile created with --allow-send; opens or creates a one-to-one chat through the selected Teams client; requires --yes without a terminal; sends no message"
779                );
780            }
781            _ => {}
782        }
783    }
784    if let Some(filter) = command_filter {
785        commands.retain(|value| value["name"] == filter);
786    }
787    json!({
788        "$schema": "https://clispec.dev/schema/v0.3.json",
789        "clispec": "0.3",
790        "name": "teams",
791        "version": env!("CARGO_PKG_VERSION"),
792        "description": "A Microsoft Teams CLI and TUI designed equally for humans and agents",
793        "output": {"tty": "text", "piped": "json"},
794        "global_args": [
795            {"name":"--output", "short":"-o", "type":"string", "enum":["auto","text","json"], "default":"auto", "description":"Output format"},
796            {"name":"--profile", "type":"string", "x-env":"TEAMS_PROFILE", "description":"Configuration profile; defaults to the active one"},
797            {"name":"--quiet", "type":"boolean", "description":"Suppress informational stderr output"},
798            {"name":"--yes", "short":"-y", "type":"boolean", "description":"Confirm without prompting (conversation creation, desktop sends, profile removal)"}
799        ],
800        "commands": commands,
801        "errors": error::ALL.iter().map(|e| json!({"kind":e.kind,"exit_code":e.exit_code,"retryable":e.retryable,"description":e.description})).collect::<Vec<_>>(),
802        "extensions": {
803            "backends":backend_capabilities(),
804            "authentication":"delegated_oauth",
805            "api":"Microsoft Graph v1.0",
806            "default_client_id": crate::config::DEFAULT_CLIENT_ID,
807            "login_modes":["browser_pkce","device_code"],
808            "read_only_env":"TEAMS_READ_ONLY",
809            "environment":{
810                "TEAMS_PROFILE":"Profile to use when --profile is not given",
811                "TEAMS_READ_ONLY":"true blocks every remote write; false cannot unlock a desktop profile",
812                "TEAMS_ACCESS_TOKEN":"Graph access token that overrides the stored credential for this run",
813                "TEAMS_CLIENT_ID":"Graph application ID override",
814                "TEAMS_TENANT":"Graph tenant override",
815                "TEAMS_DESKTOP_HELPER":"Path to a teams.exe speaking the same helper protocol to use as the WSL desktop helper"
816            },
817            "collection_envelope":{
818                "items":"array of records described by the command's output_fields",
819                "next_cursor":"cursor-paged commands: pass to --cursor for the next page; absent on the last page",
820                "next_offset":"offset-paged commands: pass to --offset for the next page; absent on the last page",
821                "truncated":"true when more records exist",
822                "source":"\"desktop_cache\" when records come from the Teams client's local cache; absent for Graph"
823            },
824            "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",
825            "idempotency":"Sends cannot be made idempotent: neither Graph nor Teams accepts a caller-supplied key. Never resend after unconfirmed without reading the conversation first.",
826            "baseline_scopes": crate::auth::BASE_SCOPES.split_whitespace().collect::<Vec<_>>(),
827            "privileged_scopes":[crate::auth::CHANNEL_HISTORY_SCOPE]
828        }
829    })
830}
831
832pub fn backend_capabilities() -> Value {
833    json!({
834        "graph":{"default":true,"authentication":"delegated_oauth","api":"Microsoft Graph v1.0","account_types":["Microsoft 365 work or school"]},
835        "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"]},
836            "account_types":["Microsoft 365 work or school","personal Microsoft accounts"],"account_selection":"account_type_then_single_account_only",
837            "authentication":"teams_desktop_session_unverified","supported":["configuration","connection metadata","doctor","auth status","managed connect/status/disconnect/recover","delivery reconciliation by client message ID","people search","create or reuse one-to-one chats (opt-in)","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)"],
838            "unsupported":["teams and channels","identity","channel messages, replies, mentions, attachments and edits","subscriptions","unconfirmed Teams launch or restart"],
839            "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",
840            "transport":{"macos":"native_loopback","windows":"windows_native","wsl":"windows_helper_stdio","browser":"dedicated_chromium_loopback"},
841            "chat_source":"desktop_cache","session_verified":false,"default_port":crate::config::DEFAULT_DESKTOP_PORT}
842    })
843}