Skip to content

A modern terminal with a built-in multiplexer: close it and your sessions keep running. Run shells and tons of AI agents across your machines, then pick them up from desktop, browser, TUI and more. Written in Rust with no UI framework: interface drawn straight on the GPU. No Electron, GPUI or webview.

feat(cli): add thinkterm plugin

RoversXe9fbf4c80522
diff --git a/wezterm/Cargo.toml b/wezterm/Cargo.toml
index 5aa9a76a..c9be6d12 100644
--- a/wezterm/Cargo.toml
+++ b/wezterm/Cargo.toml
@@ -43,6 +43,7 @@ tempfile.workspace = true
termwiz-funcs.workspace = true
termwiz.workspace = true
textwrap.workspace =true
+thinkterm-plugin-channel = { workspace = true, features = ["native"] }
thinkterm-proto.workspace = true
thinkterm-tui = { path = "../thinkterm-tui" }
thinkterm-update.workspace = true
diff --git a/wezterm/src/main.rs b/wezterm/src/main.rs
index b97c4e45..c89d22ef 100644
--- a/wezterm/src/main.rs
+++ b/wezterm/src/main.rs
@@ -18,6 +18,7 @@ use wezterm_gui_subcommands::*;
mod asciicast;
mod cli;
+mod plugin;
// let message = "; ❤ 😍🤢\n\x1b[91;mw00t\n\x1b[37;104;m bleet\x1b[0;m.";
@@ -256,6 +257,12 @@ enum SubCommand {
#[command(name = "update", about = "Check for a newer release and install it")]
Update(UpdateCommand),
+ #[command(
+ name = "plugin",
+ about = "List, turn on and off, reload and run plugins"
+ )]
+ Plugin(plugin::PluginCommand),
+
/// Write a project's file listing for search. The desktop runs this on a
/// remote host over ssh; it is not meant to be run by hand.
#[command(name = "list-files", hide = true)]
@@ -1070,6 +1077,7 @@ fn run() -> anyhow::Result<()> {
SubCommand::Record(cmd) => cmd.run(init_config(&opts)?),
SubCommand::Replay(cmd) => cmd.run(),
SubCommand::Update(cmd) => cmd.run(),
+ SubCommand::Plugin(cmd) => cmd.run(),
SubCommand::ListFiles(cmd) => cmd.run(),
SubCommand::Tui(cmd) => thinkterm_tui::run(
init_config(&opts)?,
diff --git a/wezterm/src/plugin.rs b/wezterm/src/plugin.rs
new file mode 100644
index 00000000..de1b3f7d
--- /dev/null
+++ b/wezterm/src/plugin.rs
@@ -0,0 +1,171 @@
+//! `thinkterm plugin`: the plugin host from the command line, for looking
+//! at plugins and trying one out while writing it
+//! (docs/thinkterm/plugins.md).
+
+use anyhow::{anyhow, Context};
+use clap::{Parser, Subcommand};
+use serde_json::Value;
+use std::time::Duration;
+use thinkterm_plugin_channel::client::{Host, Session, CALL_TIMEOUT};
+use thinkterm_plugin_channel::registry::{self as api, Info, State};
+
+#[derive(Debug, Parser, Clone)]
+pub struct PluginCommand {
+ #[command(subcommand)]
+ sub: Sub,
+}
+
+#[derive(Debug, Subcommand, Clone)]
+enum Sub {
+ /// List the plugins and their states
+ List,
+ /// Turn a plugin on
+ Enable { id: String },
+ /// Turn a plugin off
+ Disable { id: String },
+ /// Stop a plugin and read its manifest again; every installed plugin
+ /// when no id is given
+ Reload { id: Option<String> },
+ /// Send a plugin a call, and print its answer
+ Call {
+ id: String,
+ #[arg(value_name = "JSON")]
+ body: String,
+ },
+ /// Print the directory plugins are installed in
+ Dir,
+}
+
+impl PluginCommand {
+ pub fn run(&self) -> anyhow::Result<()> {
+ if let Sub::Dir = self.sub {
+ println!(
+ "{}",
+ thinkterm_plugin_channel::paths::plugins_dir().display()
+ );
+ return Ok(());
+ }
+ let host = Host::for_this_build().context("finding the plugin host")?;
+ let session = Session::start(host, |_| {}).context("starting a plugin session")?;
+ match &self.sub {
+ Sub::List => {
+ let listed = manage(&session, api::Request::List { locale: locale() })?;
+ let listed: Vec<Info> = serde_json::from_value(listed)?;
+ print_list(&listed);
+ }
+ Sub::Enable { id } | Sub::Disable { id } => {
+ let enabled = matches!(self.sub, Sub::Enable { .. });
+ manage(
+ &session,
+ api::Request::SetEnabled {
+ id: id.clone(),
+ enabled,
+ },
+ )?;
+ println!("{id} is {}", if enabled { "on" } else { "off" });
+ }
+ Sub::Reload { id } => {
+ manage(&session, api::Request::Reload { id: id.clone() })?;
+ println!(
+ "reloaded {}",
+ id.as_deref().unwrap_or("every installed plugin")
+ );
+ }
+ Sub::Call { id, body } => {
+ let body: Value = serde_json::from_str(body).context("the call is not JSON")?;
+ let answer = ask(&session, id, body, CALL_TIMEOUT)?;
+ println!("{}", serde_json::to_string_pretty(&answer)?);
+ }
+ Sub::Dir => unreachable!("answered above"),
+ }
+ Ok(())
+ }
+}
+
+fn ask(session: &Session, plugin: &str, body: Value, wait: Duration) -> anyhow::Result<Value> {
+ let (tx, rx) = std::sync::mpsc::channel();
+ session.call_within(plugin, body, wait, move |answer| {
+ let _ = tx.send(answer);
+ });
+ rx.recv()
+ .context("the plugin session ended")?
+ .map_err(|why| anyhow!(why))
+}
+
+fn manage(session: &Session, request: api::Request) -> anyhow::Result<Value> {
+ ask(
+ session,
+ api::PLUGIN,
+ serde_json::to_value(request)?,
+ CALL_TIMEOUT,
+ )
+}
+
+/// The language plugins name themselves in, from the environment:
+/// `zh_CN.UTF-8` is `zh-CN`.
+fn locale() -> String {
+ ["LC_ALL", "LC_MESSAGES", "LANG"]
+ .iter()
+ .filter_map(|name| std::env::var(name).ok())
+ .find(|value| !value.is_empty())
+ .map(|value| {
+ let tag = value.split(['.', '@']).next().unwrap_or_default();
+ match tag {
+ "C" | "POSIX" => String::new(),
+ tag => tag.replace('_', "-"),
+ }
+ })
+ .unwrap_or_default()
+}
+
+fn state_label(info: &Info) -> &'static str {
+ match info.state {
+ State::Off => "off",
+ State::Idle => "idle",
+ State::Starting => "starting",
+ State::Running => "running",
+ State::Crashed { .. } => "crashed",
+ State::Failed { .. } => "failed",
+ State::Invalid { .. } => "invalid",
+ State::Unsupported { .. } => "unsupported",
+ }
+}
+
+fn print_list(listed: &[Info]) {
+ let id_width = listed
+ .iter()
+ .map(|info| info.id.chars().count())
+ .max()
+ .unwrap_or(0)
+ .max(2);
+ println!("{:id_width$} {:11} {:10} NAME", "ID", "STATE", "VERSION");
+ for info in listed {
+ let version = if info.builtin {
+ "built in"
+ } else if info.version.is_empty() {
+ "-"
+ } else {
+ &info.version
+ };
+ println!(
+ "{:id_width$} {:11} {:10} {}",
+ info.id,
+ state_label(info),
+ version,
+ info.name
+ );
+ if let Some(reason) = info.state.reason() {
+ println!("{:id_width$} {reason}", "");
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ #[test]
+ fn a_locale_comes_from_the_environment_as_a_tag() {
+ // Only the shape: the variables belong to whoever runs the tests.
+ let locale = super::locale();
+ assert!(!locale.contains('_') && !locale.contains('.'), "{}", locale);
+ }
+}