bcode_command 0.0.1-alpha.0

Command contract types and service interface for bcode
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
#![cfg_attr(feature = "fail-on-warnings", deny(warnings))]
#![warn(clippy::all, clippy::pedantic, clippy::nursery, clippy::cargo)]
#![allow(clippy::multiple_crate_versions)]

//! Command contract types and `bcode.command/v1` service interface for Bcode.
//!
//! Plugins declare this interface in their manifest to contribute commands
//! discoverable via the control panel and slash commands.

#[cfg(test)]
mod bpdl_contract_tests;

pub mod completion;

use bcode_model::ReasoningEffort;
use bcode_session_models::SessionId;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};

/// Plugin service interface for command providers / core command registry.
pub const COMMAND_INTERFACE_ID: &str = "bcode.command/v1";

/// Operation to list available commands (returns `CommandList`).
pub const OP_LIST_COMMANDS: &str = "list";

/// Operation to invoke a command (request `InvokeCommandRequest`, response `InvokeCommandResponse`).
pub const OP_INVOKE_COMMAND: &str = "invoke";

/// Command metadata for palette / slash discovery.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CommandInfo {
    pub id: String,
    pub name: String,
    #[serde(default)]
    pub description: Option<String>,
    #[serde(default)]
    pub requires_args: bool,
    #[serde(default)]
    pub category: Option<String>,
}

/// Response to `OP_LIST_COMMANDS`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CommandList {
    pub commands: Vec<CommandInfo>,
}

/// Canonical application context supplied by the host for command invocation.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CommandInvocationContext {
    /// Active canonical session, when the command was invoked from one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub session_id: Option<SessionId>,
    /// Canonical session or launch working directory selected by the host.
    pub working_directory: std::path::PathBuf,
}

/// Request payload for `OP_INVOKE_COMMAND`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct InvokeCommandRequest {
    pub command_id: String,
    #[serde(default)]
    pub args: BTreeMap<String, String>,
    /// Trusted application context supplied independently from user arguments.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub context: Option<CommandInvocationContext>,
}

/// Response from command invocation.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct InvokeCommandResponse {
    pub success: bool,
    #[serde(default)]
    pub message: Option<String>,
    #[serde(default)]
    pub updated_model: Option<String>,
    #[serde(default)]
    pub updated_provider: Option<String>,
    #[serde(default)]
    pub updated_thinking: Option<ReasoningEffort>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub effects: Vec<CommandEffect>,
}

/// Renderer-neutral format for command-contributed transcript text.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CommandTextFormat {
    /// Preserve text literally.
    #[default]
    PlainText,
    /// Render Markdown-compatible text.
    Markdown,
    /// Pretty-print valid JSON and preserve invalid JSON literally.
    Json,
}

/// Generic effect requested by a plugin-owned command.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum CommandEffect {
    /// Copy literal text to the frontend's clipboard. Report write failures to the user.
    CopyText {
        /// Complete text to copy without presentation formatting.
        text: String,
    },
    /// Show a user-facing status message.
    Status {
        /// Message to show.
        message: String,
    },
    /// Append text to the current transcript.
    ///
    /// `format` is renderer-neutral and explicit. Omit it for backward-compatible plain text;
    /// use `markdown` or `json` only when the command owns those semantics.
    AppendText {
        /// Text to append.
        text: String,
        /// Explicit renderer-neutral text format. Omitted legacy values remain plain text.
        #[serde(default, skip_serializing_if = "is_plain_text_format")]
        format: CommandTextFormat,
    },
    /// Toggle a generic host surface by stable surface id.
    ToggleSurface {
        /// Surface id to toggle.
        surface_id: String,
    },
    /// Open a plugin-contributed TUI surface.
    OpenPluginSurface {
        /// Surface kind declared by the owning plugin.
        surface_kind: String,
        /// Surface instance id.
        instance_id: String,
        /// Plugin-defined JSON options.
        #[serde(default)]
        options: serde_json::Value,
    },
    /// Open one canonical session through the host application boundary.
    OpenSession {
        /// Canonical destination session identity.
        session_id: SessionId,
        /// Optional frontend-neutral focus request.
        #[serde(default)]
        focus: SessionOpenFocus,
    },
}

/// Frontend-neutral focus target applied after opening a session.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SessionOpenFocus {
    /// Let the frontend choose its ordinary session focus.
    #[default]
    Default,
    /// Focus the session composer when supported.
    Composer,
}

#[allow(clippy::trivially_copy_pass_by_ref)]
fn is_plain_text_format(format: &CommandTextFormat) -> bool {
    *format == CommandTextFormat::PlainText
}

/// Command owner identity.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum CommandOwner {
    /// Host-owned command contribution.
    Host,
    /// Plugin-owned command contribution.
    Plugin {
        /// Owning plugin id.
        plugin_id: String,
    },
}

/// Command execution target.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum CommandAction {
    /// Host-routed command action.
    Host {
        /// Opaque host route.
        route: String,
    },
    /// Plugin-routed command action.
    Plugin {
        /// Owning plugin id.
        plugin_id: String,
        /// Plugin-owned command id.
        command_id: String,
    },
}

/// Command contribution surface.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CommandSurface {
    /// Command palette surface.
    Palette,
    /// Slash command surface.
    Slash,
    /// Named custom surface.
    Custom(String),
}

impl CommandSurface {
    /// Parse a manifest surface string.
    #[must_use]
    pub fn parse(value: &str) -> Self {
        match value {
            "palette" => Self::Palette,
            "slash" => Self::Slash,
            other => Self::Custom(other.to_owned()),
        }
    }
}

/// Host scheduling class for command execution.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CommandExecution {
    /// Ordinary command execution.
    #[default]
    Normal,
    /// Control-plane command that must execute directly rather than entering model-turn queues.
    Immediate,
}

/// Slash-command discovery metadata owned by a command contribution.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SlashCommandContribution {
    /// Primary user-facing name without a leading slash.
    pub name: String,
    /// Additional user-facing names without leading slashes.
    #[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
    pub aliases: BTreeSet<String>,
}

/// Whether a command may be invoked without an active session.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CommandSessionRequirement {
    /// The command supports invocation with or without an active session.
    #[default]
    Optional,
    /// The command requires canonical active-session context.
    Required,
    /// The command is only applicable when no session is active.
    Absent,
}

/// Why a command may not be dispatched against the current session context.
///
/// Hosts evaluate this before performing any command side effect so declared applicability is
/// enforced uniformly instead of being re-implemented by each command owner.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CommandSessionRefusal {
    /// The command requires an active session and none is available.
    SessionRequired,
    /// The command only applies without an active session.
    SessionMustBeAbsent,
}

impl CommandSessionRefusal {
    /// Return a renderer-neutral explanation for the refusal.
    #[must_use]
    pub const fn message(self) -> &'static str {
        match self {
            Self::SessionRequired => "this command requires an active session",
            Self::SessionMustBeAbsent => "this command only applies without an active session",
        }
    }
}

impl std::fmt::Display for CommandSessionRefusal {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(self.message())
    }
}

impl CommandSessionRequirement {
    /// Evaluate declared session applicability against the dispatching context.
    ///
    /// `has_active_session` reports whether the host can supply canonical active-session context
    /// for the invocation. Returns the refusal reason when dispatch must not proceed.
    #[must_use]
    pub const fn refusal(self, has_active_session: bool) -> Option<CommandSessionRefusal> {
        match self {
            Self::Optional => None,
            Self::Required => {
                if has_active_session {
                    None
                } else {
                    Some(CommandSessionRefusal::SessionRequired)
                }
            }
            Self::Absent => {
                if has_active_session {
                    Some(CommandSessionRefusal::SessionMustBeAbsent)
                } else {
                    None
                }
            }
        }
    }
}

/// Portable command argument value kind.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CommandArgumentKind {
    /// Arbitrary UTF-8 text.
    String,
    /// Boolean text parsed by the command owner.
    Boolean,
    /// Signed integer text parsed by the command owner.
    Integer,
    /// JSON text validated by the command owner.
    Json,
}

/// One named command argument declaration.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CommandArgumentContribution {
    /// Stable argument name.
    pub name: String,
    /// Portable value kind.
    pub kind: CommandArgumentKind,
    /// Whether invocation requires the argument.
    #[serde(default)]
    pub required: bool,
    /// Optional user-facing description.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

/// Registry contribution for a user-visible command.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CommandContribution {
    /// Stable command id.
    pub id: String,
    /// Display title.
    pub title: String,
    /// Optional display description.
    #[serde(default)]
    pub description: Option<String>,
    /// Optional category.
    #[serde(default)]
    pub category: Option<String>,
    /// Surfaces this command appears on.
    #[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
    pub surfaces: BTreeSet<CommandSurface>,
    /// Slash-command names contributed by this command.
    ///
    /// Contributions on the slash surface must provide this metadata. Keeping the user-facing
    /// name separate from `id` allows stable namespaced command identities.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub slash: Option<SlashCommandContribution>,
    /// Portable user argument declarations in presentation order.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub arguments: Vec<CommandArgumentContribution>,
    /// Active-session applicability requirement.
    #[serde(default)]
    pub session: CommandSessionRequirement,
    /// Host scheduling class.
    #[serde(default)]
    pub execution: CommandExecution,
    /// Command owner.
    pub owner: CommandOwner,
    /// Command action.
    pub action: CommandAction,
}

impl CommandContribution {
    /// Build a host-owned command contribution.
    #[must_use]
    pub fn host_palette(id: &str, title: &str, description: &str, category: &str) -> Self {
        Self {
            id: id.to_owned(),
            title: title.to_owned(),
            description: Some(description.to_owned()),
            category: Some(category.to_owned()),
            surfaces: BTreeSet::from([CommandSurface::Palette]),
            slash: None,
            arguments: Vec::new(),
            session: CommandSessionRequirement::Optional,
            execution: CommandExecution::Normal,
            owner: CommandOwner::Host,
            action: CommandAction::Host {
                route: id.to_owned(),
            },
        }
    }

    /// Return true when this command contributes to `surface`.
    #[must_use]
    pub fn supports_surface(&self, surface: &CommandSurface) -> bool {
        self.surfaces.contains(surface)
    }

    /// Return the contributed slash name when this command supports the slash surface.
    #[must_use]
    pub fn slash_name(&self) -> Option<&str> {
        self.supports_surface(&CommandSurface::Slash)
            .then(|| self.slash.as_ref().map(|slash| slash.name.as_str()))
            .flatten()
    }

    /// Return whether this contribution owns the supplied slash name or alias.
    #[must_use]
    pub fn matches_slash_name(&self, name: &str) -> bool {
        self.slash_name().is_some_and(|primary| primary == name)
            || self
                .slash
                .as_ref()
                .is_some_and(|slash| slash.aliases.contains(name))
    }
}

/// In-memory command contribution registry.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct CommandRegistry {
    contributions: BTreeMap<String, CommandContribution>,
}

impl CommandRegistry {
    /// Create an empty command registry.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            contributions: BTreeMap::new(),
        }
    }

    /// Register or replace a command contribution by id.
    pub fn register(&mut self, contribution: CommandContribution) {
        self.contributions
            .insert(contribution.id.clone(), contribution);
    }

    /// Extend this registry with command contributions.
    pub fn extend(&mut self, contributions: impl IntoIterator<Item = CommandContribution>) {
        for contribution in contributions {
            self.register(contribution);
        }
    }

    /// Return commands for a given surface in stable id order.
    #[must_use]
    pub fn commands_for_surface(&self, surface: &CommandSurface) -> Vec<CommandContribution> {
        self.contributions
            .values()
            .filter(|contribution| contribution.supports_surface(surface))
            .cloned()
            .collect()
    }

    /// Return a command contribution by id.
    #[must_use]
    pub fn get(&self, id: &str) -> Option<&CommandContribution> {
        self.contributions.get(id)
    }
}

/// Return host-owned command contributions bundled with the default TUI distribution.
#[must_use]
#[allow(clippy::too_many_lines)]
pub fn bundled_host_palette_commands() -> Vec<CommandContribution> {
    vec![
        CommandContribution::host_palette(
            "session.new",
            "New Session",
            "Create a new chat session",
            "session",
        ),
        CommandContribution::host_palette(
            "session.switch",
            "Switch Session",
            "Open the session picker",
            "session",
        ),
        CommandContribution::host_palette(
            "session.search",
            "Search Sessions",
            "Search local session transcripts",
            "session",
        ),
        CommandContribution::host_palette(
            "theme.select",
            "Theme: Select",
            "List themes and show preview/apply commands",
            "theme",
        ),
        CommandContribution::host_palette(
            "streaming.configure",
            "Streaming: Configure",
            "Compare raw provider chunks and tune smoothed presentation",
            "streaming",
        ),
        CommandContribution::host_palette("help", "Help", "Show TUI help", "help"),
        CommandContribution::host_palette(
            "session.rename",
            "Session: Rename",
            "Rename an existing session",
            "session",
        ),
        CommandContribution::host_palette(
            "session.delete",
            "Session: Delete",
            "Delete an existing session",
            "session",
        ),
        CommandContribution::host_palette(
            "turn.cancel",
            "Turn: Cancel",
            "Cancel the active assistant turn",
            "turn",
        ),
        CommandContribution::host_palette(
            "context.compact",
            "Context: Compact",
            "Compact the current conversation context",
            "context",
        ),
    ]
}

/// Errors returned by command operations.
///
/// * Invalid command ID or arguments.
/// * Underlying provider / session error.
/// * Permission denied for the action.
#[derive(Debug, Clone, thiserror::Error, Serialize, Deserialize)]
pub enum CommandError {
    #[error("unknown command: {0}")]
    UnknownCommand(String),
    #[error("invalid arguments: {0}")]
    InvalidArguments(String),
    #[error("execution failed: {0}")]
    ExecutionFailed(String),
}

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

    #[test]
    fn optional_session_requirement_never_refuses_dispatch() {
        assert_eq!(CommandSessionRequirement::Optional.refusal(true), None);
        assert_eq!(CommandSessionRequirement::Optional.refusal(false), None);
    }

    #[test]
    fn required_session_requirement_refuses_without_active_session() {
        assert_eq!(CommandSessionRequirement::Required.refusal(true), None);
        assert_eq!(
            CommandSessionRequirement::Required.refusal(false),
            Some(CommandSessionRefusal::SessionRequired)
        );
    }

    #[test]
    fn absent_session_requirement_refuses_with_active_session() {
        assert_eq!(CommandSessionRequirement::Absent.refusal(false), None);
        assert_eq!(
            CommandSessionRequirement::Absent.refusal(true),
            Some(CommandSessionRefusal::SessionMustBeAbsent)
        );
    }

    #[test]
    fn session_refusal_messages_are_distinguishable() {
        assert_ne!(
            CommandSessionRefusal::SessionRequired.message(),
            CommandSessionRefusal::SessionMustBeAbsent.message()
        );
    }

    #[test]
    fn bundled_palette_exposes_session_search_route() {
        assert!(bundled_host_palette_commands().iter().any(|contribution| {
            contribution.id == "session.search"
                && contribution.action
                    == CommandAction::Host {
                        route: "session.search".to_owned(),
                    }
        }));
    }

    #[test]
    fn bundled_palette_exposes_theme_selection_route() {
        assert!(bundled_host_palette_commands().iter().any(|contribution| {
            contribution.id == "theme.select"
                && contribution.action
                    == CommandAction::Host {
                        route: "theme.select".to_owned(),
                    }
        }));
    }

    #[test]
    fn bundled_palette_exposes_streaming_configurator_route() {
        assert!(bundled_host_palette_commands().iter().any(|contribution| {
            contribution.id == "streaming.configure"
                && contribution.action
                    == CommandAction::Host {
                        route: "streaming.configure".to_owned(),
                    }
        }));
    }

    #[test]
    fn append_text_defaults_legacy_payloads_to_plain_text() {
        let effect = serde_json::from_value::<CommandEffect>(serde_json::json!({
            "type": "append_text",
            "text": "* literal"
        }))
        .expect("legacy append text");

        assert_eq!(
            effect,
            CommandEffect::AppendText {
                text: "* literal".to_owned(),
                format: CommandTextFormat::PlainText,
            }
        );
        assert_eq!(
            serde_json::to_value(effect).expect("serialize legacy-compatible effect"),
            serde_json::json!({"type": "append_text", "text": "* literal"})
        );
    }

    #[test]
    fn append_text_serializes_explicit_markdown_format() {
        let effect = CommandEffect::AppendText {
            text: "* rendered".to_owned(),
            format: CommandTextFormat::Markdown,
        };

        assert_eq!(
            serde_json::to_value(&effect).expect("serialize markdown effect"),
            serde_json::json!({
                "type": "append_text",
                "text": "* rendered",
                "format": "markdown"
            })
        );
        assert_eq!(
            serde_json::from_value::<CommandEffect>(
                serde_json::to_value(effect).expect("serialize markdown effect")
            )
            .expect("deserialize markdown effect"),
            CommandEffect::AppendText {
                text: "* rendered".to_owned(),
                format: CommandTextFormat::Markdown,
            }
        );
    }

    #[test]
    fn slash_metadata_decouples_user_facing_name_from_command_identity() {
        let contribution = CommandContribution {
            id: "bcode.example.open".to_owned(),
            title: "Example".to_owned(),
            description: None,
            category: None,
            surfaces: BTreeSet::from([CommandSurface::Slash]),
            slash: Some(SlashCommandContribution {
                name: "example".to_owned(),
                aliases: BTreeSet::from(["ex".to_owned()]),
            }),
            arguments: Vec::new(),
            session: CommandSessionRequirement::Optional,
            execution: CommandExecution::Immediate,
            owner: CommandOwner::Host,
            action: CommandAction::Host {
                route: "example".to_owned(),
            },
        };

        assert_eq!(contribution.slash_name(), Some("example"));
        assert!(contribution.matches_slash_name("example"));
        assert!(contribution.matches_slash_name("ex"));
        assert!(!contribution.matches_slash_name("bcode.example.open"));
    }

    #[test]
    fn command_invocation_context_is_separate_from_user_arguments() {
        let session_id = SessionId::new();
        let request = InvokeCommandRequest {
            command_id: "bcode.example.open".to_owned(),
            args: BTreeMap::from([("target".to_owned(), "user input".to_owned())]),
            context: Some(CommandInvocationContext {
                session_id: Some(session_id),
                working_directory: std::path::PathBuf::from("/workspace"),
            }),
        };

        let value = serde_json::to_value(&request).expect("serialize request");
        assert_eq!(value["args"]["target"], "user input");
        assert_eq!(value["context"]["session_id"], session_id.to_string());
        assert!(value["args"].get("session_id").is_none());
        assert!(value["args"].get("cwd").is_none());
        assert_eq!(
            serde_json::from_value::<InvokeCommandRequest>(value).expect("deserialize request"),
            request
        );
    }

    #[test]
    fn registry_filters_commands_by_surface() {
        let mut registry = CommandRegistry::new();
        registry.register(CommandContribution {
            id: "example.palette".to_owned(),
            title: "Palette".to_owned(),
            description: None,
            category: None,
            surfaces: BTreeSet::from([CommandSurface::Palette]),
            slash: None,
            arguments: Vec::new(),
            session: CommandSessionRequirement::Optional,
            execution: CommandExecution::Normal,
            owner: CommandOwner::Host,
            action: CommandAction::Host {
                route: "example.palette".to_owned(),
            },
        });
        registry.register(CommandContribution {
            id: "example.slash".to_owned(),
            title: "Slash".to_owned(),
            description: None,
            category: None,
            surfaces: BTreeSet::from([CommandSurface::Slash]),
            slash: Some(SlashCommandContribution {
                name: "example".to_owned(),
                aliases: BTreeSet::new(),
            }),
            arguments: Vec::new(),
            session: CommandSessionRequirement::Optional,
            execution: CommandExecution::Normal,
            owner: CommandOwner::Host,
            action: CommandAction::Host {
                route: "example.slash".to_owned(),
            },
        });

        let palette = registry.commands_for_surface(&CommandSurface::Palette);

        assert_eq!(palette.len(), 1);
        assert_eq!(palette[0].id, "example.palette");
    }
}