bcode_tui 0.0.1-alpha.0

Terminal user 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
//! Slash command registry metadata for the TUI.

use bcode_client::BcodeClient;
use bcode_command::CommandContribution;
use bcode_skill_models::SkillId;

/// Stable identity for a host-owned slash command.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BuiltinCommandId {
    Version,
    Sessions,
    Monitor,
    Search,
    Resync,
    RescanImports,
    New,
    Agent,
    Compact,
    Theme,
    Streaming,
    Model,
    AuthPool,
    Provider,
    Context,
    Cwd,
    Worktree,
    Ralph,
    Skills,
    Skill,
    Thinking,
    Timeline,
    Stop,
    CancelRuntime,
    Runtime,
}

/// Resolved host-owned slash command.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BuiltinSlashCommand {
    id: BuiltinCommandId,
}

impl BuiltinSlashCommand {
    /// Return the stable command identity.
    #[must_use]
    pub const fn id(self) -> BuiltinCommandId {
        self.id
    }
}

/// Static metadata for a slash completion item.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SlashCompletion {
    command: &'static str,
    description: &'static str,
}

impl SlashCompletion {
    /// Return replacement command text.
    #[must_use]
    pub const fn command(self) -> &'static str {
        self.command
    }

    /// Return completion description.
    #[must_use]
    pub const fn description(self) -> &'static str {
        self.description
    }
}

#[derive(Debug, Clone, Copy)]
struct BuiltinCommandSpec {
    id: BuiltinCommandId,
    names: &'static [&'static str],
    completions: &'static [SlashCompletion],
}

macro_rules! completion {
    ($command:literal, $description:literal) => {
        SlashCompletion {
            command: $command,
            description: $description,
        }
    };
}

const BUILTIN_COMMANDS: &[BuiltinCommandSpec] = &[
    BuiltinCommandSpec {
        id: BuiltinCommandId::Version,
        names: &["version"],
        completions: &[completion!("/version", "Show detailed build information")],
    },
    BuiltinCommandSpec {
        id: BuiltinCommandId::Sessions,
        names: &["sessions"],
        completions: &[completion!("/sessions", "Open session picker")],
    },
    BuiltinCommandSpec {
        id: BuiltinCommandId::Monitor,
        names: &["monitor"],
        completions: &[completion!("/monitor", "Open child-session monitor")],
    },
    BuiltinCommandSpec {
        id: BuiltinCommandId::Search,
        names: &["search"],
        completions: &[completion!("/search", "Search session transcripts")],
    },
    BuiltinCommandSpec {
        id: BuiltinCommandId::Resync,
        names: &["resync"],
        completions: &[completion!("/resync", "Resynchronize the active session")],
    },
    BuiltinCommandSpec {
        id: BuiltinCommandId::RescanImports,
        names: &["rescan-imports"],
        completions: &[completion!(
            "/rescan-imports",
            "Rescan and open importable sessions"
        )],
    },
    BuiltinCommandSpec {
        id: BuiltinCommandId::New,
        names: &["new"],
        completions: &[completion!("/new", "Create and switch to a new session")],
    },
    BuiltinCommandSpec {
        id: BuiltinCommandId::Agent,
        names: &["plan", "build", "agent"],
        completions: &[
            completion!("/plan", "Switch to plan agent"),
            completion!("/build", "Switch to build agent"),
            completion!("/agent ", "Set session agent by id"),
        ],
    },
    BuiltinCommandSpec {
        id: BuiltinCommandId::Compact,
        names: &["compact"],
        completions: &[completion!("/compact", "Compact current session context")],
    },
    BuiltinCommandSpec {
        id: BuiltinCommandId::Theme,
        names: &["theme"],
        completions: &[
            completion!("/theme", "Open interactive theme picker"),
            completion!("/theme preview ", "Preview bundled theme"),
            completion!("/theme apply ", "Persist bundled theme"),
            completion!("/theme cancel", "Cancel theme preview"),
        ],
    },
    BuiltinCommandSpec {
        id: BuiltinCommandId::Streaming,
        names: &["streaming"],
        completions: &[completion!(
            "/streaming",
            "Compare and tune streaming presentation"
        )],
    },
    BuiltinCommandSpec {
        id: BuiltinCommandId::Model,
        names: &["model", "models", "set-model"],
        completions: &[
            completion!("/model", "Open model picker"),
            completion!("/models", "Open model picker"),
            completion!("/set-model ", "Set model by id"),
        ],
    },
    BuiltinCommandSpec {
        id: BuiltinCommandId::AuthPool,
        names: &["auth-pool", "subscriptions"],
        completions: &[
            completion!("/auth-pool", "Choose preferred provider subscription"),
            completion!("/subscriptions", "Choose preferred provider subscription"),
        ],
    },
    BuiltinCommandSpec {
        id: BuiltinCommandId::Provider,
        names: &["provider", "set-provider"],
        completions: &[
            completion!("/provider", "Show current provider"),
            completion!("/set-provider ", "Set provider by id"),
        ],
    },
    BuiltinCommandSpec {
        id: BuiltinCommandId::Context,
        names: &["context-strategy", "context"],
        completions: &[
            completion!("/context", "Show session context strategy"),
            completion!("/context-strategy", "Show session context strategy"),
        ],
    },
    BuiltinCommandSpec {
        id: BuiltinCommandId::Cwd,
        names: &["cwd"],
        completions: &[completion!("/cwd", "Change session working directory")],
    },
    BuiltinCommandSpec {
        id: BuiltinCommandId::Worktree,
        names: &["worktree", "worktrees"],
        completions: &[
            completion!("/worktree", "Create worktree"),
            completion!("/worktrees", "Create worktree"),
            completion!("/worktree list", "List Git worktrees"),
            completion!("/worktree create", "Open worktree create dialog"),
            completion!("/worktree attach ", "Set session working directory"),
        ],
    },
    BuiltinCommandSpec {
        id: BuiltinCommandId::Ralph,
        names: &["ralph"],
        completions: &[
            completion!("/ralph", "Open Ralph UI"),
            completion!("/ralph ui", "Open Ralph UI"),
            completion!("/ralph start", "Start/setup Ralph loop"),
            completion!("/ralph run", "Prepare Ralph run"),
            completion!("/ralph approve", "Approve prepared Ralph run"),
            completion!("/ralph status", "Show Ralph status"),
            completion!("/ralph runs", "List Ralph runs"),
            completion!("/ralph iterations", "List Ralph iterations"),
            completion!("/ralph stop", "Stop active Ralph run"),
            completion!("/ralph resume", "Resume interrupted Ralph run"),
            completion!("/ralph audit", "Build Ralph audit prompt"),
            completion!("/ralph replan", "Build Ralph replan prompt"),
            completion!("/ralph open", "Open Ralph progress doc"),
        ],
    },
    BuiltinCommandSpec {
        id: BuiltinCommandId::Skills,
        names: &["skills"],
        completions: &[completion!("/skills", "Open skill picker")],
    },
    BuiltinCommandSpec {
        id: BuiltinCommandId::Skill,
        names: &["skill"],
        completions: &[
            completion!("/skill ", "Invoke skill by id"),
            completion!("/skill describe ", "Describe skill by id"),
        ],
    },
    BuiltinCommandSpec {
        id: BuiltinCommandId::Thinking,
        names: &["thinking"],
        completions: &[
            completion!("/thinking", "Open reasoning output settings"),
            completion!("/thinking status", "Show reasoning output status"),
            completion!(
                "/thinking capabilities",
                "Show model reasoning capabilities"
            ),
            completion!(
                "/thinking effort",
                "Open reasoning settings focused on effort"
            ),
            completion!(
                "/thinking summary",
                "Open reasoning settings focused on summary"
            ),
        ],
    },
    BuiltinCommandSpec {
        id: BuiltinCommandId::Timeline,
        names: &["timeline"],
        completions: &[completion!("/timeline", "Browse user messages")],
    },
    BuiltinCommandSpec {
        id: BuiltinCommandId::Stop,
        names: &["stop"],
        completions: &[completion!("/stop", "Stop the active turn")],
    },
    BuiltinCommandSpec {
        id: BuiltinCommandId::CancelRuntime,
        names: &["cancel-runtime"],
        completions: &[completion!("/cancel-runtime ", "Cancel runtime work by id")],
    },
    BuiltinCommandSpec {
        id: BuiltinCommandId::Runtime,
        names: &["runtime", "status"],
        completions: &[
            completion!("/runtime", "Show runtime status"),
            completion!("/status", "Show runtime status"),
        ],
    },
];

/// Resolution for a submitted slash command.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SlashResolution {
    /// Command resolved to a builtin slash command.
    Builtin(BuiltinSlashCommand),
    /// Command resolved to a non-conflicting skill alias.
    SkillAlias {
        skill_id: SkillId,
        arguments: String,
    },
    /// Command resolved to a plugin-owned slash contribution.
    PluginCommand(Box<CommandContribution>),
    /// Command did not resolve to any known slash command.
    Unknown,
}

impl SlashResolution {}

/// Return slash completion metadata derived from the builtin command catalog.
pub fn static_completions() -> impl Iterator<Item = SlashCompletion> {
    BUILTIN_COMMANDS
        .iter()
        .flat_map(|command| command.completions.iter().copied())
}

/// Return the builtin command matching a command name without a leading slash.
#[must_use]
pub fn builtin_command(command: &str) -> Option<BuiltinSlashCommand> {
    BUILTIN_COMMANDS
        .iter()
        .find(|candidate| candidate.names.contains(&command))
        .map(|candidate| BuiltinSlashCommand { id: candidate.id })
}

/// Return true when the command name is a builtin slash command.
#[must_use]
pub fn is_builtin_command_name(command: &str) -> bool {
    builtin_command(command).is_some()
}

/// Return the first slash command token without its leading slash.
#[must_use]
pub fn slash_command_name(message: &str) -> Option<&str> {
    message
        .strip_prefix('/')
        .and_then(|command| command.split_whitespace().next())
}

fn slash_command_arguments(message: &str) -> String {
    message
        .strip_prefix('/')
        .and_then(|command| command.split_once(char::is_whitespace))
        .map_or_else(String::new, |(_command, arguments)| {
            arguments.trim_start().to_owned()
        })
}

/// Return true when a skill ID can be exposed as a top-level slash alias.
#[must_use]
pub fn is_non_conflicting_skill_alias(skill_id: &SkillId) -> bool {
    !is_builtin_command_name(skill_id.as_str())
}

/// Resolve a submitted slash command without executing side effects.
///
/// # Errors
///
/// Returns an error when dynamic skill discovery fails.
pub async fn resolve(
    client: &BcodeClient,
    message: &str,
) -> Result<SlashResolution, bcode_client::ClientError> {
    let Some(command) = slash_command_name(message) else {
        return Ok(SlashResolution::Unknown);
    };
    if let Some(builtin) = builtin_command(command) {
        return Ok(SlashResolution::Builtin(builtin));
    }
    let contributions = client.plugin_contributions().await?;
    if let Some(contribution) = contributions
        .command_contributions
        .into_iter()
        .find(|candidate| candidate.matches_slash_name(command))
    {
        return Ok(SlashResolution::PluginCommand(Box::new(contribution)));
    }
    let skills = client.list_skills().await?;
    let Some(skill) = skills
        .skills
        .into_iter()
        .find(|skill| skill.id.as_str() == command && is_non_conflicting_skill_alias(&skill.id))
    else {
        return Ok(SlashResolution::Unknown);
    };
    Ok(SlashResolution::SkillAlias {
        skill_id: skill.id,
        arguments: slash_command_arguments(message),
    })
}

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

    #[test]
    fn goal_is_available_to_plugin_command_resolution() {
        assert!(builtin_command("goal").is_none());
        assert!(!is_builtin_command_name("goal"));
        assert!(static_completions().all(|completion| completion.command() != "/goal"));
    }

    #[test]
    fn monitor_is_discoverable_and_resolves_to_builtin() {
        assert_eq!(
            builtin_command("monitor").unwrap().id(),
            BuiltinCommandId::Monitor
        );
        assert!(static_completions().any(|completion| completion.command() == "/monitor"));
        assert!(!is_non_conflicting_skill_alias(&SkillId::new("monitor")));
    }

    #[test]
    fn search_is_discoverable_and_reserved_as_a_builtin() {
        assert!(static_completions().any(|completion| {
            completion.command() == "/search"
                && completion.description().contains("session transcripts")
        }));
        assert!(is_builtin_command_name("search"));
        assert!(!is_non_conflicting_skill_alias(&SkillId::new("search")));
    }

    #[test]
    fn fork_and_clone_are_not_host_builtins() {
        assert!(!is_builtin_command_name("fork"));
        assert!(!is_builtin_command_name("clone"));
        assert!(
            static_completions()
                .all(|completion| !matches!(completion.command(), "/fork" | "/clone"))
        );
    }

    #[test]
    fn every_builtin_name_is_discoverable_and_unique() {
        let mut names = std::collections::BTreeSet::new();
        for spec in BUILTIN_COMMANDS {
            assert!(
                !spec.completions.is_empty(),
                "builtin {:?} has no slash completion",
                spec.id
            );
            for name in spec.names {
                assert!(names.insert(*name), "duplicate builtin slash name: {name}");
                assert!(
                    spec.completions.iter().any(|completion| {
                        completion
                            .command()
                            .trim_start_matches('/')
                            .split_whitespace()
                            .next()
                            == Some(*name)
                    }),
                    "builtin slash name is not discoverable: {name}"
                );
                assert_eq!(
                    builtin_command(name).map(BuiltinSlashCommand::id),
                    Some(spec.id)
                );
            }
        }
    }

    #[test]
    fn cwd_opens_an_interactive_command() {
        assert!(static_completions().any(|completion| {
            completion.command() == "/cwd" && completion.description().contains("working directory")
        }));
        assert_eq!(
            builtin_command("cwd").map(BuiltinSlashCommand::id),
            Some(BuiltinCommandId::Cwd)
        );
    }

    #[test]
    fn version_is_discoverable() {
        assert!(static_completions().any(|completion| {
            completion.command() == "/version"
                && completion.description().contains("build information")
        }));
    }
}