diff --git a/assets/macos/WezTerm.app/Contents/Info.plist b/assets/macos/WezTerm.app/Contents/Info.plist
index 78c4c9564..c089545e8 100644
--- a/assets/macos/WezTerm.app/Contents/Info.plist
+++ b/assets/macos/WezTerm.app/Contents/Info.plist
@@ -5,13 +5,14 @@
CFBundleDevelopmentRegion
en
CFBundleExecutable
- wezterm-gui
+
+ llembas-tty-gui
CFBundleIdentifier
- com.github.wez.wezterm
+ eu.llembas.tty
CFBundleInfoDictionaryVersion
6.0
CFBundleName
- WezTerm
+ LLeMbas TTY
CFBundlePackageType
APPL
CFBundleShortVersionString
@@ -33,7 +34,7 @@
NSSupportsAutomaticGraphicsSwitching
CFBundleDisplayName
- WezTerm
+ LLeMbas TTY
NSRequiresAquaSystemAppearance
NO
NSAppleEventsUsageDescription
diff --git a/config/src/config.rs b/config/src/config.rs
index f92aade56..afd092659 100644
--- a/config/src/config.rs
+++ b/config/src/config.rs
@@ -1025,9 +1025,10 @@ impl Config {
// multiple. In addition, it spawns a lot of subprocesses,
// so we do this bit "by-hand"
- let mut paths = vec![PathPossibility::optional(HOME_DIR.join(".wezterm.lua"))];
+ // LLeMbas TTY: its own file names, never WezTerm's
+ let mut paths = vec![PathPossibility::optional(HOME_DIR.join(".llembas-tty.lua"))];
for dir in CONFIG_DIRS.iter() {
- paths.push(PathPossibility::optional(dir.join("wezterm.lua")))
+ paths.push(PathPossibility::optional(dir.join("llembas-tty.lua")))
}
if cfg!(windows) {
@@ -1041,12 +1042,17 @@ impl Config {
// dir as the executable that will take precedence.
if let Ok(exe_name) = std::env::current_exe() {
if let Some(exe_dir) = exe_name.parent() {
- paths.insert(0, PathPossibility::optional(exe_dir.join("wezterm.lua")));
+ // LLeMbas TTY: its own file name
+ paths.insert(
+ 0,
+ PathPossibility::optional(exe_dir.join("llembas-tty.lua")),
+ );
}
}
}
- if let Some(path) = std::env::var_os("WEZTERM_CONFIG_FILE") {
- log::trace!("Note: WEZTERM_CONFIG_FILE is set in the environment");
+ // LLeMbas TTY: its own variable, WEZTERM_CONFIG_FILE is not honoured
+ if let Some(path) = std::env::var_os("LLEMBAS_TTY_CONFIG_FILE") {
+ log::trace!("Note: LLEMBAS_TTY_CONFIG_FILE is set in the environment");
paths.insert(0, PathPossibility::required(path.into()));
}
@@ -1077,8 +1083,23 @@ impl Config {
// We didn't find (or were asked to skip) a wezterm.lua file, so
// update the environment to make it simpler to understand this
// state.
- std::env::remove_var("WEZTERM_CONFIG_FILE");
- std::env::remove_var("WEZTERM_CONFIG_DIR");
+ // LLeMbas TTY: its own variables
+ std::env::remove_var("LLEMBAS_TTY_CONFIG_FILE");
+ std::env::remove_var("LLEMBAS_TTY_CONFIG_DIR");
+
+ // LLeMbas TTY: with no configuration file (and not asked to skip one),
+ // the built-in configuration applies the LLeMbas layer.
+ if !CONFIG_SKIP.load(Ordering::Relaxed) {
+ return match Self::try_builtin(overrides) {
+ Err(err) => LoadedConfig {
+ config: Err(err),
+ file_name: None,
+ lua: None,
+ warnings: vec![],
+ },
+ Ok(cfg) => cfg,
+ };
+ }
match Self::try_default() {
Err(err) => LoadedConfig {
@@ -1105,6 +1126,44 @@ impl Config {
})
}
+ /// LLeMbas TTY: evaluate the configuration that is built into the binary
+ /// (`llembas/lua/default-config.lua`). The same steps as `try_load`, with
+ /// the script taken from memory rather than from a file.
+ fn try_builtin(overrides: &wezterm_dynamic::Value) -> anyhow::Result {
+ let lua = make_lua_context(Path::new(""))?;
+
+ let (config, warnings) =
+ wezterm_dynamic::Error::capture_warnings(|| -> anyhow::Result {
+ let cfg: Config;
+
+ let config: mlua::Value = smol::block_on(
+ lua.load(crate::llembas::DEFAULT_CONFIG)
+ .set_name("=llembas-tty/default-config.lua")
+ .eval_async(),
+ )?;
+ let config = Config::apply_overrides_to(&lua, config)?;
+ let config = Config::apply_overrides_obj_to(&lua, config, overrides)?;
+ cfg = Config::from_lua(config, &lua).context(
+ "Error converting lua value returned by the built-in configuration \
+ to Config struct",
+ )?;
+ cfg.check_consistency()?;
+
+ // Compute but discard the key bindings here so that we raise any
+ // problems earlier than we use them.
+ let _ = cfg.key_bindings();
+ Ok(cfg)
+ });
+ let cfg = config?;
+
+ Ok(LoadedConfig {
+ config: Ok(cfg.compute_extra_defaults(None)),
+ file_name: None,
+ lua: Some(lua),
+ warnings,
+ })
+ }
+
fn try_load(
path_item: &PathPossibility,
overrides: &wezterm_dynamic::Value,
@@ -1149,9 +1208,10 @@ impl Config {
// problems earlier than we use them.
let _ = cfg.key_bindings();
- std::env::set_var("WEZTERM_CONFIG_FILE", p);
+ // LLeMbas TTY: its own variables
+ std::env::set_var("LLEMBAS_TTY_CONFIG_FILE", p);
if let Some(dir) = p.parent() {
- std::env::set_var("WEZTERM_CONFIG_DIR", dir);
+ std::env::set_var("LLEMBAS_TTY_CONFIG_DIR", dir);
}
Ok(cfg)
});
@@ -1620,11 +1680,15 @@ impl Config {
// de-facto standard for identifying the terminal.
cmd.env("TERM_PROGRAM", "WezTerm");
cmd.env("TERM_PROGRAM_VERSION", crate::wezterm_version());
+ // LLeMbas TTY: how a program knows that it runs in this terminal
+ cmd.env("LLEMBAS_TTY", crate::llembas_tty_version());
}
}
fn default_check_for_updates() -> bool {
- cfg!(not(feature = "distro-defaults"))
+ // LLeMbas TTY: off. Upstream's check asks GitHub about WezTerm's releases,
+ // which are not this program's, and nothing leaves the machine unasked.
+ false
}
fn default_pane_select_fg_color() -> RgbaColor {
@@ -1756,28 +1820,29 @@ fn default_font_size() -> f64 {
12.0
}
+// LLeMbas TTY: its own cache, data and runtime directories, never WezTerm's
pub(crate) fn compute_cache_dir() -> anyhow::Result {
if let Some(runtime) = dirs_next::cache_dir() {
- return Ok(runtime.join("wezterm"));
+ return Ok(runtime.join("llembas-tty"));
}
- Ok(crate::HOME_DIR.join(".local/share/wezterm"))
+ Ok(crate::HOME_DIR.join(".local/share/llembas-tty"))
}
pub(crate) fn compute_data_dir() -> anyhow::Result {
if let Some(runtime) = dirs_next::data_dir() {
- return Ok(runtime.join("wezterm"));
+ return Ok(runtime.join("llembas-tty"));
}
- Ok(crate::HOME_DIR.join(".local/share/wezterm"))
+ Ok(crate::HOME_DIR.join(".local/share/llembas-tty"))
}
pub(crate) fn compute_runtime_dir() -> anyhow::Result {
if let Some(runtime) = dirs_next::runtime_dir() {
- return Ok(runtime.join("wezterm"));
+ return Ok(runtime.join("llembas-tty"));
}
- Ok(crate::HOME_DIR.join(".local/share/wezterm"))
+ Ok(crate::HOME_DIR.join(".local/share/llembas-tty"))
}
pub fn pki_dir() -> anyhow::Result {
diff --git a/config/src/lib.rs b/config/src/lib.rs
index 802059c4f..8ad198781 100644
--- a/config/src/lib.rs
+++ b/config/src/lib.rs
@@ -31,6 +31,8 @@ mod font;
mod frontend;
pub mod keyassignment;
mod keys;
+// LLeMbas TTY: the built-in Lua layer
+pub mod llembas;
pub mod lua;
pub mod meta;
mod scheme_data;
@@ -383,9 +385,10 @@ pub fn create_user_owned_dirs(p: &Path) -> anyhow::Result<()> {
}
fn xdg_config_home() -> PathBuf {
- match std::env::var_os("XDG_CONFIG_HOME").map(|s| PathBuf::from(s).join("wezterm")) {
+ // LLeMbas TTY: its own directory, never WezTerm's
+ match std::env::var_os("XDG_CONFIG_HOME").map(|s| PathBuf::from(s).join("llembas-tty")) {
Some(p) => p,
- None => HOME_DIR.join(".config").join("wezterm"),
+ None => HOME_DIR.join(".config").join("llembas-tty"),
}
}
@@ -395,7 +398,8 @@ fn config_dirs() -> Vec {
#[cfg(unix)]
if let Some(d) = std::env::var_os("XDG_CONFIG_DIRS") {
- dirs.extend(std::env::split_paths(&d).map(|s| PathBuf::from(s).join("wezterm")));
+ // LLeMbas TTY: its own directory, never WezTerm's
+ dirs.extend(std::env::split_paths(&d).map(|s| PathBuf::from(s).join("llembas-tty")));
}
dirs
diff --git a/config/src/llembas.rs b/config/src/llembas.rs
new file mode 100644
index 000000000..d797ab77b
--- /dev/null
+++ b/config/src/llembas.rs
@@ -0,0 +1,44 @@
+//! LLeMbas TTY: the LLeMbas layer, built into the binary.
+//!
+//! The layer is Lua (`llembas/lua/` at the top of the repository). It is
+//! compiled in as text and offered to every Lua context through
+//! `package.preload`, so that a configuration file can say
+//! `require('llembas').apply(config)`. With no configuration file at all,
+//! `DEFAULT_CONFIG` is evaluated instead (see `Config::try_builtin`).
+//!
+//! Nothing here runs the layer: a module is only evaluated when it is
+//! required.
+
+use anyhow::Context;
+use mlua::{Lua, Table};
+
+/// The configuration used when the person has no configuration file.
+pub const DEFAULT_CONFIG: &str = include_str!("../../llembas/lua/default-config.lua");
+
+/// Module name as given to `require`, and its source.
+const MODULES: &[(&str, &str)] = &[
+ (
+ "llembas",
+ include_str!("../../llembas/lua/llembas/init.lua"),
+ ),
+ (
+ "llembas.core",
+ include_str!("../../llembas/lua/llembas/core.lua"),
+ ),
+];
+
+pub fn register(lua: &Lua) -> anyhow::Result<()> {
+ let package: Table = lua.globals().get("package").context("get _G.package")?;
+ let preload: Table = package.get("preload").context("get package.preload")?;
+ for (name, source) in MODULES {
+ let loader = lua
+ .load(*source)
+ .set_name(format!("=llembas-tty/{}.lua", name))
+ .into_function()
+ .with_context(|| format!("compiling the built-in module {}", name))?;
+ preload
+ .set(*name, loader)
+ .with_context(|| format!("registering the built-in module {}", name))?;
+ }
+ Ok(())
+}
diff --git a/config/src/lua.rs b/config/src/lua.rs
index 4f0319467..1a505919d 100644
--- a/config/src/lua.rs
+++ b/config/src/lua.rs
@@ -227,7 +227,8 @@ pub fn make_lua_context(config_file: &Path) -> anyhow::Result {
array.insert(1, format!("{}/?/init.lua", path.display()));
}
- prefix_path(&mut path_array, &crate::HOME_DIR.join(".wezterm"));
+ // LLeMbas TTY: its own directory, never WezTerm's
+ prefix_path(&mut path_array, &crate::HOME_DIR.join(".llembas-tty"));
for dir in crate::CONFIG_DIRS.iter() {
prefix_path(&mut path_array, dir);
}
@@ -385,6 +386,9 @@ end
func(&lua).context("calling SETUP_FUNCS")?;
}
+ // LLeMbas TTY: make the built-in layer available as `require 'llembas'`
+ crate::llembas::register(&lua).context("registering the llembas module")?;
+
Ok(lua)
}
diff --git a/config/src/unix.rs b/config/src/unix.rs
index 123691987..9f169c868 100644
--- a/config/src/unix.rs
+++ b/config/src/unix.rs
@@ -118,10 +118,11 @@ impl UnixDomain {
Some(cmd) => Ok(cmd.iter().map(Into::into).collect()),
None => Ok(vec![
std::env::current_exe()?
+ // LLeMbas TTY: its own binary names
.with_file_name(if cfg!(windows) {
- "wezterm-mux-server.exe"
+ "llembas-tty-mux-server.exe"
} else {
- "wezterm-mux-server"
+ "llembas-tty-mux-server"
})
.into_os_string(),
OsString::from("--daemonize"),
diff --git a/config/src/version.rs b/config/src/version.rs
index d009f1e13..453cf8781 100644
--- a/config/src/version.rs
+++ b/config/src/version.rs
@@ -14,6 +14,27 @@ pub fn wezterm_version() -> &'static str {
.unwrap_or(&"someone forgot to call assign_version_info")
}
+/// LLeMbas TTY: this program's own version, from the `VERSION` file at
+/// the top of the repository at build time. `wezterm_version` stays
+/// WezTerm's: programs and scripts compare it to detect features.
+pub fn llembas_tty_version() -> &'static str {
+ include_str!("../../VERSION").trim()
+}
+
+/// LLeMbas TTY: what `--version` shows: our version and the WezTerm
+/// version that it is based on.
+pub fn llembas_tty_long_version() -> &'static str {
+ static LONG: OnceLock = OnceLock::new();
+ match VERSION.get() {
+ // Not assigned yet (the gui parses its arguments before it is):
+ // our own version alone.
+ None => llembas_tty_version(),
+ Some(wezterm) => LONG
+ .get_or_init(|| format!("{} (based on WezTerm {})", llembas_tty_version(), wezterm))
+ .as_str(),
+ }
+}
+
pub fn wezterm_target_triple() -> &'static str {
TRIPLE
.get()
diff --git a/env-bootstrap/src/lib.rs b/env-bootstrap/src/lib.rs
index 490f54e96..fd7ae907b 100644
--- a/env-bootstrap/src/lib.rs
+++ b/env-bootstrap/src/lib.rs
@@ -3,11 +3,33 @@ pub use ringlog::setup_logger;
use std::path::{Path, PathBuf};
pub fn set_wezterm_executable() {
+ // LLeMbas TTY: its own variable names. A WezTerm that started us must
+ // not be mistaken for us by what runs in our panes, so what it exported
+ // is dropped rather than passed on.
+ for name in [
+ "WEZTERM_EXECUTABLE",
+ "WEZTERM_EXECUTABLE_DIR",
+ "WEZTERM_CONFIG_FILE",
+ "WEZTERM_CONFIG_DIR",
+ "WEZTERM_PANE",
+ "WEZTERM_UNIX_SOCKET",
+ ] {
+ std::env::remove_var(name);
+ }
if let Ok(exe) = std::env::current_exe() {
if let Some(dir) = exe.parent() {
- std::env::set_var("WEZTERM_EXECUTABLE_DIR", dir);
+ std::env::set_var("LLEMBAS_TTY_EXECUTABLE_DIR", dir);
}
- std::env::set_var("WEZTERM_EXECUTABLE", exe);
+ // LLeMbas TTY: always the launcher (the one with the `cli`
+ // subcommand), whichever of our binaries this process is.
+ std::env::set_var(
+ "LLEMBAS_TTY_EXECUTABLE",
+ exe.with_file_name(if cfg!(windows) {
+ "llembas-tty.exe"
+ } else {
+ "llembas-tty"
+ }),
+ );
}
}
@@ -52,9 +74,10 @@ pub fn fixup_appimage() {
// Since our AppImage includes multiple utilities, we want to
// be able to use them, so add that location to the PATH!
- // WEZTERM_EXECUTABLE_DIR is set by `set_wezterm_executable`
+ // LLEMBAS_TTY_EXECUTABLE_DIR is set by `set_wezterm_executable`
// which is called before `fixup_appimage`
- if let Some(dir) = std::env::var_os("WEZTERM_EXECUTABLE_DIR") {
+ // LLeMbas TTY: its own variable name
+ if let Some(dir) = std::env::var_os("LLEMBAS_TTY_EXECUTABLE_DIR") {
if let Some(path) = std::env::var_os("PATH") {
let mut paths = std::env::split_paths(&path).collect::>();
paths.insert(0, PathBuf::from(dir));
@@ -86,8 +109,9 @@ pub fn fixup_appimage() {
/// However, if we are using the system wezterm to spawn a portable
/// AppImage then we want these to not take effect.
fn clean_wezterm_config_env() {
- std::env::remove_var("WEZTERM_CONFIG_FILE");
- std::env::remove_var("WEZTERM_CONFIG_DIR");
+ // LLeMbas TTY: its own variable names
+ std::env::remove_var("LLEMBAS_TTY_CONFIG_FILE");
+ std::env::remove_var("LLEMBAS_TTY_CONFIG_DIR");
}
if config::HOME_DIR.starts_with(append_extra_file_name_suffix(&appimage, ".home")) {
diff --git a/llembas/lua/default-config.lua b/llembas/lua/default-config.lua
new file mode 100644
index 000000000..a8b4b56e5
--- /dev/null
+++ b/llembas/lua/default-config.lua
@@ -0,0 +1,8 @@
+-- LLeMbas TTY: the configuration used when the person has none of their own
+-- ($XDG_CONFIG_HOME/llembas-tty/llembas-tty.lua or ~/.llembas-tty.lua).
+-- It is the terminal's defaults with the LLeMbas layer applied. A person's
+-- own file starts from the same four lines.
+local wezterm = require 'wezterm'
+local config = wezterm.config_builder()
+require('llembas').apply(config)
+return config
diff --git a/llembas/lua/llembas/core.lua b/llembas/lua/llembas/core.lua
new file mode 100644
index 000000000..d553a0f82
--- /dev/null
+++ b/llembas/lua/llembas/core.lua
@@ -0,0 +1,1019 @@
+-- LLeMbas TTY: the pure half of the LLeMbas layer.
+--
+-- Nothing in this file touches the terminal, the file system or a process:
+-- every function takes plain values and returns plain values, so that all of
+-- it can be tested without a terminal (llembas/tests/run.lua).
+--
+-- Written in the subset that Lua 5.1 (LuaJIT) and Lua 5.4 share: the terminal
+-- embeds 5.4, the tests also run under LuaJIT.
+
+local M = {}
+
+M.CONTEXT_VERSION = 1
+
+-- The oldest LLeMbas CLI that knows about terminals: it publishes the session
+-- to the terminal, takes --terminal-context and /terminal-context, and has
+-- `lembas complete --shell`. See M.cli_supports_terminal.
+M.MIN_CLI_VERSION = '2.0.0-beta.18'
+
+M.LIMITS = {
+ max_blocks = 20, -- the most command blocks a context may carry
+ total_bytes = 256 * 1024, -- the context file stays under this
+ stale_seconds = 600, -- context files older than this are swept
+ value_chars = 64, -- one value in the session bar
+ title_chars = 80,
+ question_bytes = 16 * 1024,
+}
+
+M.STATES = {
+ idle = 'idle',
+ waiting = 'waiting',
+ thinking = 'thinking',
+ tools = 'tools',
+ writing = 'writing',
+ asking = 'needs you',
+}
+
+M.BAR_FIELDS = {
+ session = true,
+ title = true,
+ model = true,
+ mode = true,
+ effort = true,
+ state = true,
+ context = true,
+ tokens = true,
+ spend = true,
+}
+
+-- What the layer does when nothing is said. A person's own configuration
+-- passes a table of the same shape to apply(); only what it names changes.
+function M.defaults()
+ return {
+ enabled = true,
+ -- Path of the LLeMbas CLI. nil: the one shipped beside this terminal,
+ -- then `lembas` on PATH.
+ cli = nil,
+ session_bar = true,
+ tab_marker = true,
+ palette = true,
+ bar = {
+ fields = { 'model', 'mode', 'state', 'context' },
+ },
+ keys = {
+ ask = { key = 'A', mods = 'CTRL|SHIFT' },
+ new_session = { key = 'S', mods = 'CTRL|SHIFT' },
+ resume = { key = 'O', mods = 'CTRL|SHIFT' },
+ toggle_display = { key = 'D', mods = 'CTRL|SHIFT' },
+ private = { key = 'H', mods = 'CTRL|SHIFT' },
+ },
+ split = {
+ direction = 'Right',
+ size = 0.45,
+ },
+ new_session_in = 'split',
+ context = {
+ enabled = true,
+ blocks = 5,
+ output_lines = 200,
+ output_bytes = 16 * 1024,
+ screen_lines = 200,
+ alt_screen = false,
+ },
+ autocomplete = false,
+ }
+end
+
+----------------------------------------------------------------------------
+-- Text that came from somewhere else
+
+local function is_cont(b)
+ return b ~= nil and b >= 0x80 and b <= 0xBF
+end
+
+-- The length in bytes of the well-formed UTF-8 sequence at i, or nil.
+local function utf8_len_at(s, i)
+ local b = s:byte(i)
+ if b < 0x80 then
+ return 1
+ end
+ local b2, b3, b4 = s:byte(i + 1, i + 3)
+ if b >= 0xC2 and b <= 0xDF then
+ if is_cont(b2) then
+ return 2
+ end
+ elseif b >= 0xE0 and b <= 0xEF then
+ if is_cont(b2) and is_cont(b3) then
+ if b == 0xE0 and b2 < 0xA0 then
+ return nil -- overlong
+ end
+ if b == 0xED and b2 > 0x9F then
+ return nil -- surrogate
+ end
+ return 3
+ end
+ elseif b >= 0xF0 and b <= 0xF4 then
+ if is_cont(b2) and is_cont(b3) and is_cont(b4) then
+ if b == 0xF0 and b2 < 0x90 then
+ return nil -- overlong
+ end
+ if b == 0xF4 and b2 > 0x8F then
+ return nil -- beyond U+10FFFF
+ end
+ return 4
+ end
+ end
+ return nil
+end
+
+local REPLACEMENT = '\239\191\189' -- U+FFFD
+
+-- Clean text for the eye or for a file.
+-- keep_newlines: keep \n and \t (multi-line text); otherwise every control
+-- character goes and the result is one line.
+-- Always: C0 and C1 control characters and DEL are removed (so no escape
+-- sequence survives), bytes that are not UTF-8 become U+FFFD.
+function M.clean(text, keep_newlines)
+ if type(text) ~= 'string' then
+ return ''
+ end
+ local out = {}
+ local n = 0
+ local i = 1
+ local len = #text
+ while i <= len do
+ local b = text:byte(i)
+ if b < 0x20 or b == 0x7F then
+ if keep_newlines and (b == 0x0A or b == 0x09) then
+ n = n + 1
+ out[n] = string.char(b)
+ elseif not keep_newlines and (b == 0x0A or b == 0x09 or b == 0x0D) then
+ -- a line break in one-line text reads as a space
+ n = n + 1
+ out[n] = ' '
+ end
+ i = i + 1
+ else
+ local l = utf8_len_at(text, i)
+ if not l then
+ n = n + 1
+ out[n] = REPLACEMENT
+ i = i + 1
+ elseif l == 2 and b == 0xC2 and text:byte(i + 1) <= 0x9F then
+ -- C1 control characters (U+0080..U+009F), among them the 8-bit CSI and OSC
+ i = i + 2
+ else
+ n = n + 1
+ out[n] = text:sub(i, i + l - 1)
+ i = i + l
+ end
+ end
+ end
+ return table.concat(out)
+end
+
+-- Cut text to at most max characters (not bytes), never inside a character.
+-- Expects clean UTF-8 (M.clean's result).
+function M.cap_chars(text, max)
+ local i = 1
+ local len = #text
+ local count = 0
+ while i <= len do
+ if count == max then
+ return text:sub(1, i - 1) .. '…'
+ end
+ local l = utf8_len_at(text, i) or 1
+ i = i + l
+ count = count + 1
+ end
+ return text
+end
+
+-- A value shown on one line: cleaned, trimmed, capped.
+function M.one_line(text, max)
+ local s = M.clean(text, false)
+ s = s:gsub('^%s+', ''):gsub('%s+$', '')
+ return M.cap_chars(s, max or M.LIMITS.value_chars)
+end
+
+-- The end of text: at most max_lines lines and max_bytes bytes, cut at a line
+-- start when one is there, and never inside a character.
+function M.tail(text, max_lines, max_bytes)
+ local s = text
+ if max_bytes and #s > max_bytes then
+ local from = #s - max_bytes + 1
+ -- do not start inside a UTF-8 character
+ while from <= #s and is_cont(s:byte(from)) do
+ from = from + 1
+ end
+ s = s:sub(from)
+ local nl = s:find('\n', 1, true)
+ if nl and nl < #s then
+ s = s:sub(nl + 1)
+ end
+ end
+ if max_lines then
+ local pos = #s
+ -- a final newline does not count as an empty last line
+ if pos > 0 and s:byte(pos) == 0x0A then
+ pos = pos - 1
+ end
+ local lines = 0
+ while pos > 0 do
+ if s:byte(pos) == 0x0A then
+ lines = lines + 1
+ if lines == max_lines then
+ s = s:sub(pos + 1)
+ break
+ end
+ end
+ pos = pos - 1
+ end
+ end
+ return s
+end
+
+----------------------------------------------------------------------------
+-- JSON, written here so that the file is the same whatever the terminal's
+-- own encoder does with key order, nil and invalid text.
+
+M.null = setmetatable({}, {
+ __tostring = function()
+ return 'null'
+ end,
+})
+
+local JSON_ESCAPES = {
+ ['"'] = '\\"',
+ ['\\'] = '\\\\',
+ ['\n'] = '\\n',
+ ['\r'] = '\\r',
+ ['\t'] = '\\t',
+}
+
+local function json_string(s)
+ s = M.clean(s, true)
+ s = s:gsub('[%c"\\\127]', function(c)
+ return JSON_ESCAPES[c] or string.format('\\u%04x', c:byte())
+ end)
+ return '"' .. s .. '"'
+end
+
+local function json_number(v)
+ if v ~= v or v == math.huge or v == -math.huge then
+ return 'null'
+ end
+ if v == math.floor(v) and v > -1e15 and v < 1e15 then
+ return string.format('%d', v)
+ end
+ return string.format('%.14g', v)
+end
+
+-- encode(value, key_order): tables with a [1] are arrays, M.array() marks an
+-- empty array, other tables are objects whose keys are written in key_order
+-- first (when given) and then alphabetically.
+local ARRAY = {}
+
+function M.array(t)
+ return setmetatable(t or {}, ARRAY)
+end
+
+local function json_value(v, order, depth)
+ if depth > 16 then
+ error('json: nested too deeply')
+ end
+ local t = type(v)
+ if v == nil or v == M.null then
+ return 'null'
+ elseif t == 'boolean' then
+ return v and 'true' or 'false'
+ elseif t == 'number' then
+ return json_number(v)
+ elseif t == 'string' then
+ return json_string(v)
+ elseif t == 'table' then
+ if getmetatable(v) == ARRAY or v[1] ~= nil then
+ local parts = {}
+ for i = 1, #v do
+ parts[i] = json_value(v[i], order, depth + 1)
+ end
+ return '[' .. table.concat(parts, ',') .. ']'
+ end
+ local keys = {}
+ local seen = {}
+ if order then
+ for _, k in ipairs(order) do
+ if v[k] ~= nil then
+ keys[#keys + 1] = k
+ seen[k] = true
+ end
+ end
+ end
+ local rest = {}
+ for k in pairs(v) do
+ if type(k) == 'string' and not seen[k] then
+ rest[#rest + 1] = k
+ end
+ end
+ table.sort(rest)
+ for _, k in ipairs(rest) do
+ keys[#keys + 1] = k
+ end
+ local parts = {}
+ for i, k in ipairs(keys) do
+ parts[i] = json_string(k) .. ':' .. json_value(v[k], order, depth + 1)
+ end
+ return '{' .. table.concat(parts, ',') .. '}'
+ end
+ error('json: cannot encode a ' .. t)
+end
+
+function M.json_encode(value, key_order)
+ return json_value(value, key_order, 0)
+end
+
+----------------------------------------------------------------------------
+-- Options
+
+local function is_array(t)
+ return type(t) == 'table' and (t[1] ~= nil or next(t) == nil)
+end
+
+local function merge_into(base, over, path, warnings)
+ for k, v in pairs(over) do
+ local where = path .. tostring(k)
+ local d = base[k]
+ if d == nil and not (path == '' and k == 'cli') then
+ warnings[#warnings + 1] = where .. ': not an option of the LLeMbas layer'
+ elseif path == 'keys.' then
+ -- a key: false turns it off, a table { key =, mods = } sets it
+ if v == false then
+ base[k] = false
+ elseif type(v) == 'table' and type(v.key) == 'string' and v.key ~= '' then
+ base[k] = { key = v.key, mods = type(v.mods) == 'string' and v.mods or 'NONE' }
+ else
+ warnings[#warnings + 1] = where .. ': expected false or { key = …, mods = … }'
+ end
+ elseif type(d) == 'table' and not is_array(d) then
+ if type(v) == 'table' then
+ merge_into(d, v, where .. '.', warnings)
+ else
+ warnings[#warnings + 1] = where .. ': expected a table'
+ end
+ elseif d ~= nil and type(v) ~= type(d) then
+ warnings[#warnings + 1] = where .. ': expected a ' .. type(d) .. ', got a ' .. type(v)
+ else
+ base[k] = v
+ end
+ end
+end
+
+local function clamp(v, lo, hi, fallback)
+ if type(v) ~= 'number' or v ~= v then
+ return fallback
+ end
+ if v < lo then
+ return lo
+ end
+ if v > hi then
+ return hi
+ end
+ return v
+end
+
+-- options(user) -> the effective options, and a list of what was wrong with
+-- what the person passed (never an error: a typo must not take the terminal's
+-- configuration down).
+function M.options(user)
+ local o = M.defaults()
+ local warnings = {}
+ if user ~= nil and type(user) ~= 'table' then
+ warnings[1] = 'options: expected a table'
+ elseif user then
+ merge_into(o, user, '', warnings)
+ end
+
+ local d = M.defaults()
+ local c = o.context
+ c.blocks = math.floor(clamp(c.blocks, 0, M.LIMITS.max_blocks, d.context.blocks))
+ c.output_lines = math.floor(clamp(c.output_lines, 1, 5000, d.context.output_lines))
+ c.output_bytes = math.floor(clamp(c.output_bytes, 256, 64 * 1024, d.context.output_bytes))
+ c.screen_lines = math.floor(clamp(c.screen_lines, 1, 1000, d.context.screen_lines))
+
+ local size = o.split.size
+ if type(size) ~= 'number' or size ~= size or size <= 0 then
+ size = d.split.size
+ elseif size > 0.9 and size < 1 then
+ size = 0.9
+ end
+ o.split.size = size
+ local directions = { Right = true, Left = true, Top = true, Bottom = true }
+ if not directions[o.split.direction] then
+ warnings[#warnings + 1] = 'split.direction: expected Right, Left, Top or Bottom'
+ o.split.direction = d.split.direction
+ end
+ if o.new_session_in ~= 'split' and o.new_session_in ~= 'tab' then
+ warnings[#warnings + 1] = "new_session_in: expected 'split' or 'tab'"
+ o.new_session_in = d.new_session_in
+ end
+
+ local fields = {}
+ if type(o.bar.fields) == 'table' then
+ for _, f in ipairs(o.bar.fields) do
+ if M.BAR_FIELDS[f] then
+ fields[#fields + 1] = f
+ else
+ warnings[#warnings + 1] = 'bar.fields: ' .. M.one_line(tostring(f), 32) .. ' is not a field'
+ end
+ end
+ end
+ o.bar.fields = fields
+
+ if o.cli ~= nil and (type(o.cli) ~= 'string' or o.cli == '') then
+ warnings[#warnings + 1] = 'cli: expected a path'
+ o.cli = nil
+ end
+ return o, warnings
+end
+
+----------------------------------------------------------------------------
+-- The session a pane publishes
+
+-- session_from_vars(user_vars) -> nil when the pane is not a LLeMbas pane,
+-- else a table of cleaned values. Everything in user_vars was written by
+-- whatever runs in the pane: it is text, and only ever shown as text.
+function M.session_from_vars(vars)
+ if type(vars) ~= 'table' then
+ return nil
+ end
+ local function get(name, max)
+ local v = vars[name]
+ if type(v) ~= 'string' or v == '' then
+ return nil
+ end
+ v = M.one_line(v, max)
+ if v == '' then
+ return nil
+ end
+ return v
+ end
+ local session = get('lembas_session')
+ local state = get('lembas_state')
+ if not session and not state then
+ return nil
+ end
+ local s = {
+ session = session,
+ title = get('lembas_title', M.LIMITS.title_chars),
+ model = get('lembas_model'),
+ mode = get('lembas_mode', 16),
+ effort = get('lembas_effort', 16),
+ tokens = get('lembas_tokens', 24),
+ spend = get('lembas_spend', 24),
+ }
+ if state and M.STATES[state] then
+ s.state = state
+ end
+ local ctx = get('lembas_context', 8)
+ if ctx then
+ local n = tonumber((ctx:gsub('%%$', '')))
+ if n and n == n and n >= 0 and n <= 100 then
+ s.context = math.floor(n + 0.5)
+ end
+ end
+ return s
+end
+
+-- The session bar as a list of { text =, attention = } parts.
+function M.bar_parts(session, fields, private)
+ local parts = {}
+ if session then
+ for _, f in ipairs(fields) do
+ local text
+ if f == 'state' then
+ text = session.state and M.STATES[session.state]
+ elseif f == 'context' then
+ text = session.context and string.format('ctx %d%%', session.context)
+ else
+ text = session[f]
+ end
+ if text then
+ parts[#parts + 1] = { text = text, attention = (f == 'state' and session.state == 'asking') }
+ end
+ end
+ end
+ if private then
+ parts[#parts + 1] = { text = 'private', private = true }
+ end
+ return parts
+end
+
+-- The same as items for the terminal's format function. Only Text items carry
+-- text from the pane, and that text has no control character left in it.
+function M.bar_items(session, fields, private)
+ local parts = M.bar_parts(session, fields, private)
+ if #parts == 0 then
+ return nil
+ end
+ local items = { { Text = ' ' } }
+ for i, p in ipairs(parts) do
+ if i > 1 then
+ items[#items + 1] = { Attribute = { Intensity = 'Half' } }
+ items[#items + 1] = { Text = ' · ' }
+ items[#items + 1] = 'ResetAttributes'
+ end
+ if p.attention then
+ items[#items + 1] = { Attribute = { Intensity = 'Bold' } }
+ items[#items + 1] = { Foreground = { AnsiColor = 'Yellow' } }
+ items[#items + 1] = { Text = p.text }
+ items[#items + 1] = 'ResetAttributes'
+ elseif p.private then
+ items[#items + 1] = { Foreground = { AnsiColor = 'Fuchsia' } }
+ items[#items + 1] = { Text = p.text }
+ items[#items + 1] = 'ResetAttributes'
+ else
+ items[#items + 1] = { Text = p.text }
+ end
+ end
+ items[#items + 1] = { Text = ' ' }
+ return items
+end
+
+-- Does a pane of this tab wait for the person?
+function M.tab_needs_person(panes)
+ if type(panes) ~= 'table' then
+ return false
+ end
+ for _, p in ipairs(panes) do
+ local s = M.session_from_vars(p.user_vars)
+ if s and s.state == 'asking' then
+ return true
+ end
+ end
+ return false
+end
+
+-- The title of a tab that waits for the person, or nil for "leave the tab to
+-- the terminal". tab: { tab_index, tab_title, active_pane = { title }, panes }.
+function M.tab_title(tab, opts)
+ if type(tab) ~= 'table' or not M.tab_needs_person(tab.panes) then
+ return nil
+ end
+ opts = opts or {}
+ local title = tab.tab_title
+ if type(title) ~= 'string' or title == '' then
+ title = tab.active_pane and tab.active_pane.title or ''
+ end
+ title = M.one_line(title, 200)
+ if opts.show_index ~= false and type(tab.tab_index) == 'number' then
+ local index = tab.tab_index + (opts.zero_based and 0 or 1)
+ title = string.format('%d: %s', index, title)
+ end
+ local max = type(opts.max_width) == 'number' and opts.max_width or 16
+ -- two cells for the mark, two for the padding
+ local room = math.floor(max) - 4
+ if room < 1 then
+ room = 1
+ end
+ local cut = M.cap_chars(title, room)
+ if cut ~= title then
+ -- cap_chars added an ellipsis: make room for it
+ cut = M.cap_chars(title, room > 1 and room - 1 or 1)
+ end
+ return {
+ { Text = ' ' },
+ { Attribute = { Intensity = 'Bold' } },
+ { Foreground = { AnsiColor = 'Yellow' } },
+ { Text = '● ' },
+ 'ResetAttributes',
+ { Text = cut .. ' ' },
+ }
+end
+
+-- Which pane of a tab runs LLeMbas. panes: a list of { pane_id =, user_vars = }.
+-- Prefers one that is not `except` (the pane the person is in).
+function M.find_session_pane(panes, except)
+ local found
+ for _, p in ipairs(panes or {}) do
+ if M.session_from_vars(p.user_vars) then
+ if p.pane_id ~= except then
+ return p.pane_id
+ end
+ found = found or p.pane_id
+ end
+ end
+ return found
+end
+
+----------------------------------------------------------------------------
+-- Terminal context
+
+local SHELLS = {
+ bash = true,
+ zsh = true,
+ fish = true,
+ sh = true,
+ dash = true,
+ ksh = true,
+ mksh = true,
+ tcsh = true,
+ csh = true,
+ nu = true,
+ elvish = true,
+ xonsh = true,
+ pwsh = true,
+ powershell = true,
+ cmd = true,
+}
+
+-- '/usr/bin/zsh' -> 'zsh'; nil when the program is not a shell.
+function M.shell_name(path)
+ if type(path) ~= 'string' then
+ return nil
+ end
+ local base = path:match('([^/\\]+)$') or path
+ base = base:gsub('%.[Ee][Xx][Ee]$', ''):gsub('^%-', ''):lower()
+ if SHELLS[base] then
+ return base
+ end
+ return nil
+end
+
+local function percent_decode(s)
+ return (s:gsub('%%(%x%x)', function(h)
+ return string.char(tonumber(h, 16))
+ end))
+end
+
+-- The directory of a pane from what the terminal reports: a Url object with
+-- a file_path, or a string 'file://host/path'. nil when it is not a local path.
+function M.cwd_from(value)
+ local t = type(value)
+ if t == 'string' then
+ local rest = value:match('^file://[^/]*(/.*)$')
+ if rest then
+ return M.clean(percent_decode(rest), false)
+ end
+ if value:sub(1, 1) == '/' then
+ return M.clean(value, false)
+ end
+ return nil
+ elseif t == 'table' or t == 'userdata' then
+ local ok, scheme = pcall(function()
+ return value.scheme
+ end)
+ if ok and scheme ~= nil and scheme ~= 'file' then
+ return nil
+ end
+ local ok2, path = pcall(function()
+ return value.file_path
+ end)
+ if ok2 and type(path) == 'string' and path ~= '' then
+ return M.clean(path, false)
+ end
+ end
+ return nil
+end
+
+local function zone_before(a, b)
+ if a.start_y ~= b.start_y then
+ return a.start_y < b.start_y
+ end
+ return (a.start_x or 0) < (b.start_x or 0)
+end
+
+-- blocks_from_zones(zones, text_of, limits) -> the last command blocks.
+-- zones: the pane's semantic zones, each { start_y, start_x, end_y, end_x,
+-- semantic_type = 'Prompt' | 'Input' | 'Output' }
+-- text_of: function(zone) -> text; called only for the zones that are used
+-- limits: { blocks, output_lines, output_bytes }
+-- A block is a command line (an Input zone) that was run, with the output
+-- that followed it. The line still being typed (the last Input zone, with
+-- nothing after it) is not a block. The exit status is null: the terminal
+-- does not tell the layer.
+function M.blocks_from_zones(zones, text_of, limits)
+ local blocks = M.array({})
+ if type(zones) ~= 'table' or limits.blocks <= 0 then
+ return blocks
+ end
+ local sorted = {}
+ for _, z in ipairs(zones) do
+ if type(z) == 'table' and type(z.start_y) == 'number' then
+ sorted[#sorted + 1] = z
+ end
+ end
+ table.sort(sorted, zone_before)
+
+ -- group: an Input zone, the Output zones up to the next Input or Prompt
+ local groups = {}
+ local current
+ for _, z in ipairs(sorted) do
+ local kind = z.semantic_type
+ if kind == 'Input' then
+ current = { input = z, outputs = {}, closed = false }
+ groups[#groups + 1] = current
+ elseif kind == 'Output' then
+ if current and not current.ended then
+ current.outputs[#current.outputs + 1] = z
+ current.closed = true
+ end
+ elseif kind == 'Prompt' then
+ if current then
+ current.closed = true
+ current.ended = true
+ end
+ end
+ end
+
+ local first = 1
+ local run = {}
+ for _, g in ipairs(groups) do
+ if g.closed then
+ run[#run + 1] = g
+ end
+ end
+ if #run > limits.blocks then
+ first = #run - limits.blocks + 1
+ end
+ for i = first, #run do
+ local g = run[i]
+ local command = M.clean(text_of(g.input) or '', true)
+ command = command:gsub('%s+$', '')
+ command = M.tail(command, 50, 4096)
+ local out = {}
+ for _, z in ipairs(g.outputs) do
+ out[#out + 1] = text_of(z) or ''
+ end
+ local output = M.clean(table.concat(out, '\n'), true)
+ output = output:gsub('%s+$', '')
+ output = M.tail(output, limits.output_lines, limits.output_bytes)
+ blocks[#blocks + 1] = { command = command, exit = M.null, output = output }
+ end
+ return blocks
+end
+
+M.CONTEXT_KEYS = { 'version', 'pane', 'cwd', 'shell', 'blocks', 'screen', 'command', 'exit', 'output' }
+
+-- context(args) -> the table that becomes the context file.
+-- args: { pane = , cwd = |nil, shell = |nil,
+-- blocks = , screen = |nil }
+-- `screen` is only kept when there is no block (a shell with no integration).
+function M.context(args)
+ local blocks = args.blocks or M.array({})
+ local ctx = {
+ version = M.CONTEXT_VERSION,
+ pane = args.pane,
+ cwd = args.cwd or '',
+ blocks = blocks,
+ }
+ if args.shell then
+ ctx.shell = args.shell
+ end
+ if #blocks == 0 and type(args.screen) == 'string' and args.screen ~= '' then
+ ctx.screen = args.screen
+ end
+ return ctx
+end
+
+-- encode_context(ctx, max_bytes) -> JSON text under max_bytes: the oldest
+-- blocks go first, then the screen is cut from its start.
+function M.encode_context(ctx, max_bytes)
+ max_bytes = max_bytes or M.LIMITS.total_bytes
+ local json = M.json_encode(ctx, M.CONTEXT_KEYS)
+ while #json >= max_bytes and #ctx.blocks > 0 do
+ table.remove(ctx.blocks, 1)
+ json = M.json_encode(ctx, M.CONTEXT_KEYS)
+ end
+ while #json >= max_bytes and ctx.screen and #ctx.screen > 0 do
+ -- how much the file holds without the screen, and how many bytes of
+ -- file one byte of screen costs (a line break is two in JSON)
+ local screen = ctx.screen
+ ctx.screen = nil
+ local base = #M.json_encode(ctx, M.CONTEXT_KEYS)
+ local room = max_bytes - base - 16
+ local keep = 0
+ if room > 0 then
+ local cost = (#json - base) / #screen
+ keep = math.min(math.floor(room / cost) - 1, #screen - 1)
+ end
+ if keep > 0 then
+ ctx.screen = M.tail(screen, nil, keep)
+ end
+ json = M.json_encode(ctx, M.CONTEXT_KEYS)
+ end
+ return json
+end
+
+-- Context files are named so that their age can be read from the name:
+-- context--.json
+function M.context_file_name(now, random_hex)
+ return string.format('context-%d-%s.json', math.floor(now), random_hex)
+end
+
+-- The age in seconds of a context file by its name; nil when the name is not
+-- one of ours (and so must never be removed).
+function M.context_file_age(name, now)
+ local base = name:match('([^/\\]+)$') or name
+ local stamp = base:match('^context%-(%d+)%-%x+%.json$')
+ if not stamp then
+ return nil
+ end
+ return now - tonumber(stamp)
+end
+
+function M.is_stale_context_file(name, now)
+ local age = M.context_file_age(name, now)
+ return age ~= nil and age > M.LIMITS.stale_seconds
+end
+
+function M.hex(bytes)
+ return (bytes:gsub('.', function(c)
+ return string.format('%02x', c:byte())
+ end))
+end
+
+----------------------------------------------------------------------------
+-- What is sent into a LLeMbas pane
+
+-- The question as it is pasted: no control character but a line break can be
+-- in it, so nothing in it can end the paste or act as a key.
+function M.question_text(line)
+ local s = M.clean(line, true)
+ s = s:gsub('^%s+', ''):gsub('%s+$', '')
+ if #s > M.LIMITS.question_bytes then
+ s = M.tail(s, nil, M.LIMITS.question_bytes)
+ end
+ return s
+end
+
+-- The line that hands a context file to a running session.
+function M.context_command(path)
+ return '/terminal-context ' .. M.clean(path, false)
+end
+
+----------------------------------------------------------------------------
+-- The LLeMbas CLI
+
+-- '2.0.0-beta.17' -> { 2, 0, 0, pre = { 'beta', 17 } }; nil when it is not a
+-- version. Reads the first thing that looks like one in the text.
+function M.parse_version(text)
+ if type(text) ~= 'string' then
+ return nil
+ end
+ local a, b, c, rest = text:match('(%d+)%.(%d+)%.(%d+)([%w%.%-]*)')
+ if not a then
+ return nil
+ end
+ local v = { tonumber(a), tonumber(b), tonumber(c) }
+ local pre = rest:match('^%-([%w%.%-]+)')
+ if pre then
+ v.pre = {}
+ for part in pre:gmatch('[^%.]+') do
+ v.pre[#v.pre + 1] = tonumber(part) or part
+ end
+ end
+ return v
+end
+
+-- compare_versions(a, b) -> -1, 0 or 1 by the rules of semantic versioning
+-- (a pre-release sorts before its release); nil when either is not a version.
+function M.compare_versions(a, b)
+ local va = type(a) == 'table' and a or M.parse_version(a)
+ local vb = type(b) == 'table' and b or M.parse_version(b)
+ if not va or not vb then
+ return nil
+ end
+ for i = 1, 3 do
+ if va[i] ~= vb[i] then
+ return va[i] < vb[i] and -1 or 1
+ end
+ end
+ if not va.pre and not vb.pre then
+ return 0
+ elseif not va.pre then
+ return 1
+ elseif not vb.pre then
+ return -1
+ end
+ local n = math.max(#va.pre, #vb.pre)
+ for i = 1, n do
+ local x, y = va.pre[i], vb.pre[i]
+ if x == nil then
+ return -1
+ elseif y == nil then
+ return 1
+ elseif x ~= y then
+ local nx, ny = type(x) == 'number', type(y) == 'number'
+ if nx and ny then
+ return x < y and -1 or 1
+ elseif nx then
+ return -1
+ elseif ny then
+ return 1
+ end
+ return tostring(x) < tostring(y) and -1 or 1
+ end
+ end
+ return 0
+end
+
+-- THE capability check, in one place: does this LLeMbas CLI know about
+-- terminals (publishes its session, takes a terminal context, completes a
+-- shell line)? Today that is read from its version; when the CLI names a
+-- capability, this is the one function to change.
+-- version_text: what `lembas --version` printed
+-- Returns true, false, or nil when it cannot tell (then the layer tries).
+function M.cli_supports_terminal(version_text)
+ local cmp = M.compare_versions(version_text, M.MIN_CLI_VERSION)
+ if cmp == nil then
+ return nil
+ end
+ return cmp >= 0
+end
+
+-- Where the CLI may be, in the order tried.
+-- explicit: the `cli` option
+-- executable_dir: where this terminal's own binaries are
+-- path: $PATH
+-- windows: true on Windows
+function M.cli_candidates(explicit, executable_dir, path, windows)
+ local list = {}
+ if explicit then
+ list[1] = explicit
+ return list
+ end
+ local name = windows and 'lembas.exe' or 'lembas'
+ local sep = windows and '\\' or '/'
+ if type(executable_dir) == 'string' and executable_dir ~= '' then
+ list[#list + 1] = executable_dir .. sep .. name
+ end
+ if type(path) == 'string' then
+ local pattern = windows and '[^;]+' or '[^:]+'
+ for dir in path:gmatch(pattern) do
+ list[#list + 1] = dir .. sep .. name
+ end
+ end
+ return list
+end
+
+-- The choices of the "resume a session" list from what
+-- `lembas sessions --json` printed, already decoded: a list of objects with
+-- at least an `id`. nil when it is not that (an older CLI prints plain text).
+function M.session_choices(decoded)
+ if type(decoded) ~= 'table' then
+ return nil
+ end
+ local list = decoded
+ if type(decoded.sessions) == 'table' then
+ list = decoded.sessions
+ end
+ local choices = {}
+ for _, s in ipairs(list) do
+ if type(s) == 'table' and M.is_session_id(s.id) then
+ local parts = {}
+ local title = type(s.title) == 'string' and M.one_line(s.title, M.LIMITS.title_chars) or ''
+ parts[1] = title ~= '' and title or s.id
+ if type(s.model) == 'string' and s.model ~= '' then
+ parts[#parts + 1] = M.one_line(s.model, 48)
+ end
+ if type(s.root) == 'string' and s.root ~= '' then
+ parts[#parts + 1] = M.one_line(s.root, 64)
+ end
+ choices[#choices + 1] = { id = s.id, label = table.concat(parts, ' · ') }
+ end
+ end
+ if #choices == 0 then
+ return nil
+ end
+ return choices
+end
+
+-- A session id goes onto a command line as one argument; still, only what
+-- looks like an id is passed on.
+function M.is_session_id(id)
+ return type(id) == 'string' and #id > 0 and #id <= 128 and id:match('^[%w][%w%._:%-]*$') ~= nil
+end
+
+----------------------------------------------------------------------------
+-- Words
+
+M.INSTALL_COMMAND = 'curl -fsSL https://github.com/LLeMbas/LLeMbas-CLI/releases/latest/download/get.sh | bash'
+
+M.messages = {
+ cli_missing = 'The LLeMbas CLI (lembas) was not found: not beside this terminal and not on PATH.\r\n'
+ .. 'Install it with:\r\n\r\n '
+ .. M.INSTALL_COMMAND
+ .. '\r\n\r\nor set its path: require("llembas").apply(config, { cli = "/path/to/lembas" })',
+ cli_missing_short = 'The LLeMbas CLI (lembas) is still not found. Install it, or set the `cli` option.',
+ cli_too_old = 'This LLeMbas CLI is too old to work with the terminal: it is %s, and %s or newer is needed.\r\n'
+ .. 'Update it with: lembas update',
+ private = 'This pane is private: nothing of it is passed on. The question was sent alone.',
+ password = 'The pane is asking for a password: nothing of it is passed on. The question was sent alone.',
+ remote = 'LLeMbas works in local panes for now: this pane runs somewhere else.',
+ write_failed = 'The terminal context could not be written (%s). The question was sent alone.',
+ no_session_pane = 'There is no LLeMbas pane in this tab.',
+ private_on = 'This pane is now private: nothing of it is passed to LLeMbas.',
+ private_off = 'This pane is no longer private.',
+}
+
+return M
diff --git a/llembas/lua/llembas/init.lua b/llembas/lua/llembas/init.lua
new file mode 100644
index 000000000..36f8c54e5
--- /dev/null
+++ b/llembas/lua/llembas/init.lua
@@ -0,0 +1,659 @@
+-- LLeMbas TTY: the LLeMbas layer.
+--
+-- local wezterm = require 'wezterm'
+-- local config = wezterm.config_builder()
+-- require('llembas').apply(config) -- or apply(config, { … })
+-- return config
+--
+-- A plain terminal by default: applying the layer binds keys, adds entries to
+-- the command palette and registers event handlers, and that is all. No
+-- process is started, no text of any pane is read and nothing leaves the
+-- machine until the person presses one of those keys or picks one of those
+-- entries. The session bar reads only the variables that a program in the
+-- pane set for the terminal (OSC 1337 SetUserVar), never the pane's text.
+--
+-- Everything that decides something is in llembas.core (pure, tested);
+-- this file is the part that talks to the terminal.
+
+local wezterm = require 'wezterm'
+local core = require 'llembas.core'
+
+local M = {}
+M.core = core
+
+local act = wezterm.action
+local opts = core.defaults()
+local registered = false
+
+-- Events of the layer. A key or a palette entry emits one of these.
+local EV = {
+ ask = 'llembas-ask',
+ ask_screen = 'llembas-ask-screen',
+ ask_line = 'llembas-ask-line',
+ ask_screen_line = 'llembas-ask-screen-line',
+ new_session = 'llembas-new-session',
+ resume = 'llembas-resume',
+ resume_pick = 'llembas-resume-pick',
+ toggle_display = 'llembas-toggle-display',
+ private = 'llembas-private',
+ login = 'llembas-login',
+ dismiss = 'llembas-dismiss',
+}
+M.events = EV
+
+----------------------------------------------------------------------------
+-- State that outlives a configuration reload. wezterm.GLOBAL holds only
+-- strings, numbers, booleans and tables with string keys.
+
+local function global(section)
+ local name = 'llembas_' .. section
+ if wezterm.GLOBAL[name] == nil then
+ wezterm.GLOBAL[name] = {}
+ end
+ return wezterm.GLOBAL[name]
+end
+
+local function pane_key(pane_id)
+ return 'p' .. tostring(pane_id)
+end
+
+function M.is_private(pane_id)
+ return global('private')[pane_key(pane_id)] == true
+end
+
+local function set_private(pane_id, on)
+ global('private')[pane_key(pane_id)] = on and true or false
+end
+
+----------------------------------------------------------------------------
+-- Talking to the person
+
+local function is_windows()
+ return wezterm.target_triple:find('windows', 1, true) ~= nil
+end
+
+-- A message in the terminal itself: an overlay with one line to dismiss it.
+local function tell(window, pane, message)
+ wezterm.log_warn('LLeMbas: ' .. message:gsub('\r\n', ' '))
+ window:perform_action(
+ act.InputSelector {
+ title = 'LLeMbas',
+ description = message .. '\r\n',
+ choices = { { label = 'OK', id = 'ok' } },
+ action = act.EmitEvent(EV.dismiss),
+ },
+ pane
+ )
+end
+
+----------------------------------------------------------------------------
+-- The LLeMbas CLI
+
+local function file_exists(path)
+ local f = io.open(path, 'r')
+ if f then
+ f:close()
+ return true
+ end
+ return false
+end
+
+-- The path of the CLI, or nil. Looks at files only; starts nothing.
+function M.find_cli()
+ local list = core.cli_candidates(opts.cli, wezterm.executable_dir, os.getenv 'PATH', is_windows())
+ for _, candidate in ipairs(list) do
+ if file_exists(candidate) then
+ return candidate
+ end
+ end
+ return nil
+end
+
+-- The CLI, or nil after telling the person why not.
+local function need_cli(window, pane)
+ local cli = M.find_cli()
+ if cli then
+ return cli
+ end
+ local told = global('told')
+ if told.cli_missing then
+ tell(window, pane, core.messages.cli_missing_short)
+ else
+ told.cli_missing = true
+ tell(window, pane, core.messages.cli_missing)
+ end
+ return nil
+end
+
+-- Does this CLI know about terminals? Asked once per CLI path, at the first
+-- thing that needs it (never at startup). The decision itself is
+-- core.cli_supports_terminal.
+local function cli_knows_terminals(window, pane, cli)
+ local cache = global('cli_version')
+ local key = 'v:' .. cli
+ local version = cache[key]
+ if version == nil then
+ local ok, stdout = wezterm.run_child_process { cli, '--version' }
+ version = ok and core.one_line(stdout or '', 64) or ''
+ cache[key] = version
+ end
+ local supports = core.cli_supports_terminal(version)
+ if supports == false then
+ tell(window, pane, string.format(core.messages.cli_too_old, version, core.MIN_CLI_VERSION))
+ return false
+ end
+ return true
+end
+
+----------------------------------------------------------------------------
+-- Panes
+
+local function pane_session(pane)
+ return core.session_from_vars(pane:get_user_vars())
+end
+
+local function pane_cwd(pane)
+ local ok, value = pcall(function()
+ return pane:get_current_working_dir()
+ end)
+ if ok then
+ return core.cwd_from(value)
+ end
+ return nil
+end
+
+-- The LLeMbas pane of the tab that `pane` is in (another pane rather than
+-- `pane` itself when there are several), or nil.
+local function session_pane_of_tab(pane)
+ local tab = pane:tab()
+ if not tab then
+ return nil
+ end
+ local by_id = {}
+ local list = {}
+ for _, p in ipairs(tab:panes()) do
+ local id = p:pane_id()
+ by_id[id] = p
+ list[#list + 1] = { pane_id = id, user_vars = p:get_user_vars() }
+ end
+ local id = core.find_session_pane(list, pane:pane_id())
+ return id and by_id[id] or nil
+end
+
+local function is_local(pane)
+ local ok, name = pcall(function()
+ return pane:get_domain_name()
+ end)
+ return not ok or name == 'local'
+end
+
+-- Start the CLI in a new pane beside `pane`.
+local function split_with(pane, args)
+ return pane:split {
+ direction = opts.split.direction,
+ size = opts.split.size,
+ args = args,
+ cwd = pane_cwd(pane),
+ }
+end
+
+local function spawn_cli(window, pane, args)
+ if opts.new_session_in == 'tab' then
+ window:perform_action(act.SpawnCommandInNewTab { args = args, cwd = pane_cwd(pane) }, pane)
+ return nil
+ end
+ return split_with(pane, args)
+end
+
+-- Text for a session that is still starting: it is sent when the pane first
+-- says that it is idle (user-var-changed, below), and dropped after a minute.
+local PENDING_SECONDS = 60
+
+local function send_when_ready(pane, kind, text)
+ local key = pane_key(pane:pane_id())
+ global('pending_kind')[key] = kind
+ global('pending_at')[key] = os.time()
+ global('pending_text')[key] = text
+end
+
+local function send_question(pane, question)
+ pane:send_paste(question)
+ pane:send_text '\r'
+end
+
+local function deliver_pending(pane)
+ local key = pane_key(pane:pane_id())
+ local texts = global('pending_text')
+ local text = texts[key]
+ if type(text) ~= 'string' or text == '' then
+ return
+ end
+ texts[key] = ''
+ local at = global('pending_at')[key]
+ if type(at) ~= 'number' or os.time() - at > PENDING_SECONDS then
+ return
+ end
+ if global('pending_kind')[key] == 'question' then
+ send_question(pane, text)
+ else
+ pane:send_text(text .. '\r')
+ end
+end
+
+----------------------------------------------------------------------------
+-- Terminal context
+
+-- The directory the context files live in: the terminal's own runtime
+-- directory (where its socket is), which only the person can read.
+local function runtime_dir()
+ local sock = os.getenv 'LLEMBAS_TTY_UNIX_SOCKET'
+ if sock and sock ~= '' then
+ local dir = sock:match('^(.*)[/\\][^/\\]+$')
+ if dir and dir ~= '' then
+ return dir
+ end
+ end
+ local xdg = os.getenv 'XDG_RUNTIME_DIR'
+ if xdg and xdg ~= '' then
+ return xdg .. '/llembas-tty'
+ end
+ return wezterm.home_dir .. '/.local/share/llembas-tty'
+end
+
+local function random_hex()
+ local f = io.open('/dev/urandom', 'rb')
+ if f then
+ local bytes = f:read(16)
+ f:close()
+ if bytes and #bytes == 16 then
+ return core.hex(bytes)
+ end
+ end
+ local parts = {}
+ for i = 1, 4 do
+ parts[i] = string.format('%08x', math.random(0, 0x7fffffff))
+ end
+ return table.concat(parts)
+end
+
+local function sweep(dir, now)
+ local ok, entries = pcall(wezterm.read_dir, dir)
+ if not ok or type(entries) ~= 'table' then
+ return
+ end
+ for _, path in ipairs(entries) do
+ if core.is_stale_context_file(path, now) then
+ os.remove(path)
+ end
+ end
+end
+
+-- What the pane shows, as the table of the context file; or nil and why not.
+-- explicit_screen: the person asked about the screen itself, so the visible
+-- screen is taken even from a full-screen program.
+function M.gather_context(pane, explicit_screen)
+ if not opts.context.enabled then
+ return nil, 'off'
+ end
+ if M.is_private(pane:pane_id()) then
+ return nil, 'private'
+ end
+ local meta = pane:get_metadata() or {}
+ if meta.password_input then
+ return nil, 'password'
+ end
+
+ local limits = opts.context
+ local alt = pane:is_alt_screen_active()
+ local blocks = core.array {}
+ local screen
+
+ -- Asked about the screen: the screen alone. Otherwise the command blocks,
+ -- and the screen only when the shell marks none. A full-screen program
+ -- (the alternate screen) gives nothing unless asked.
+ local want_screen
+ if alt then
+ want_screen = explicit_screen or limits.alt_screen
+ elseif explicit_screen then
+ want_screen = true
+ else
+ blocks = core.blocks_from_zones(pane:get_semantic_zones(), function(zone)
+ return pane:get_text_from_semantic_zone(zone)
+ end, limits)
+ want_screen = #blocks == 0
+ end
+ if want_screen then
+ screen = core.tail(core.clean(pane:get_lines_as_text(), true), limits.screen_lines, limits.output_bytes)
+ end
+
+ local shell
+ local ok, program = pcall(function()
+ return pane:get_foreground_process_name()
+ end)
+ if ok then
+ shell = core.shell_name(program)
+ end
+
+ return core.context {
+ pane = pane:pane_id(),
+ cwd = pane_cwd(pane),
+ shell = shell,
+ blocks = blocks,
+ screen = screen,
+ }
+end
+
+-- Write a context to a new file that only the person can read.
+-- Returns its path, or nil and why not.
+local function write_context(ctx)
+ local dir = runtime_dir()
+ local now = os.time()
+ sweep(dir, now)
+ local json = core.encode_context(ctx)
+ local sep = is_windows() and '\\' or '/'
+ local path = dir .. sep .. core.context_file_name(now, random_hex())
+
+ -- Made empty first and closed to everybody else before anything is written.
+ local f, err = io.open(path, 'w')
+ if not f then
+ return nil, tostring(err)
+ end
+ f:close()
+ if not is_windows() then
+ local ok = wezterm.run_child_process { 'chmod', '600', path }
+ if not ok then
+ os.remove(path)
+ return nil, 'chmod failed'
+ end
+ end
+ f, err = io.open(path, 'w')
+ if not f then
+ os.remove(path)
+ return nil, tostring(err)
+ end
+ f:write(json)
+ f:close()
+ return path
+end
+
+----------------------------------------------------------------------------
+-- Ask the model
+
+local function ask(window, pane, line, explicit_screen)
+ local question = core.question_text(line or '')
+ if question == '' then
+ return
+ end
+ local cli = need_cli(window, pane)
+ if not cli then
+ return
+ end
+ if not is_local(pane) then
+ tell(window, pane, core.messages.remote)
+ return
+ end
+ if not cli_knows_terminals(window, pane, cli) then
+ return
+ end
+
+ -- Asked from inside the LLeMbas pane: it is simply typed there.
+ if pane_session(pane) then
+ send_question(pane, question)
+ return
+ end
+
+ local path
+ local ctx, why = M.gather_context(pane, explicit_screen)
+ if ctx then
+ local err
+ path, err = write_context(ctx)
+ if not path then
+ tell(window, pane, string.format(core.messages.write_failed, core.one_line(err or '', 120)))
+ end
+ elseif why == 'private' then
+ tell(window, pane, core.messages.private)
+ elseif why == 'password' then
+ tell(window, pane, core.messages.password)
+ end
+
+ local target = session_pane_of_tab(pane)
+ if target then
+ if path then
+ target:send_text(core.context_command(path) .. '\r')
+ end
+ send_question(target, question)
+ return
+ end
+
+ local args = { cli }
+ if path then
+ args[#args + 1] = '--terminal-context'
+ args[#args + 1] = path
+ end
+ local new_pane = split_with(pane, args)
+ if new_pane then
+ send_when_ready(new_pane, 'question', question)
+ end
+end
+
+local function prompt_for(event, description)
+ return function(window, pane)
+ window:perform_action(
+ act.PromptInputLine {
+ description = description,
+ prompt = 'ask> ',
+ action = act.EmitEvent(event),
+ },
+ pane
+ )
+ end
+end
+
+----------------------------------------------------------------------------
+-- Sessions
+
+local function new_session(window, pane)
+ local cli = need_cli(window, pane)
+ if cli then
+ spawn_cli(window, pane, { cli })
+ end
+end
+
+local function login(window, pane)
+ local cli = need_cli(window, pane)
+ if cli then
+ split_with(pane, { cli, 'login' })
+ end
+end
+
+local function resume(window, pane)
+ local cli = need_cli(window, pane)
+ if not cli then
+ return
+ end
+ local choices
+ local ok, stdout = wezterm.run_child_process { cli, 'sessions', '--json' }
+ if ok and type(stdout) == 'string' then
+ local decode = wezterm.serde and wezterm.serde.json_decode or wezterm.json_parse
+ local parsed, decoded = pcall(decode, stdout)
+ if parsed then
+ choices = core.session_choices(decoded)
+ end
+ end
+ if choices then
+ window:perform_action(
+ act.InputSelector {
+ title = 'LLeMbas: resume a session',
+ choices = choices,
+ fuzzy = true,
+ action = act.EmitEvent(EV.resume_pick),
+ },
+ pane
+ )
+ return
+ end
+ -- A CLI with no list for programs: its own session list, in a new pane.
+ local new_pane = split_with(pane, { cli })
+ if new_pane then
+ send_when_ready(new_pane, 'command', '/sessions')
+ end
+end
+
+local function resume_pick(window, pane, id)
+ if not core.is_session_id(id) then
+ return
+ end
+ local cli = need_cli(window, pane)
+ if cli then
+ spawn_cli(window, pane, { cli, '-s', id })
+ end
+end
+
+local function toggle_display(window, pane)
+ local target = pane_session(pane) and pane or session_pane_of_tab(pane)
+ if not target then
+ tell(window, pane, core.messages.no_session_pane)
+ return
+ end
+ window:perform_action(act.SendKey { key = 'd', mods = 'ALT' }, target)
+end
+
+local function toggle_private(window, pane)
+ local id = pane:pane_id()
+ local on = not M.is_private(id)
+ set_private(id, on)
+ if not opts.session_bar then
+ tell(window, pane, on and core.messages.private_on or core.messages.private_off)
+ end
+end
+
+----------------------------------------------------------------------------
+-- The session bar and the tab mark
+
+local function update_status(window, pane)
+ local shown = global('bar')
+ local key = 'w' .. tostring(window:window_id())
+ local items = core.bar_items(pane_session(pane), opts.bar.fields, M.is_private(pane:pane_id()))
+ if items then
+ window:set_right_status(wezterm.format(items))
+ shown[key] = true
+ elseif shown[key] then
+ -- only what the layer itself put there is ever cleared
+ window:set_right_status ''
+ shown[key] = false
+ end
+end
+
+local function format_tab_title(tab, _, _, config, _, max_width)
+ local show_index, zero_based = true, false
+ pcall(function()
+ show_index = config.show_tab_index_in_tab_bar
+ zero_based = config.tab_and_split_indices_are_zero_based
+ end)
+ return core.tab_title(tab, { max_width = max_width, show_index = show_index, zero_based = zero_based })
+end
+
+local PALETTE = {
+ { 'LLeMbas: ask the model', 'ask', 'md_comment_question_outline' },
+ { 'LLeMbas: ask about this screen', 'ask_screen', 'md_monitor_eye' },
+ { 'LLeMbas: new session here', 'new_session', 'md_plus_box_outline' },
+ { 'LLeMbas: resume a session', 'resume', 'md_history' },
+ { 'LLeMbas: toggle side display', 'toggle_display', 'md_dock_right' },
+ { 'LLeMbas: private pane on/off', 'private', 'md_eye_off_outline' },
+ { 'LLeMbas: log in', 'login', 'md_login' },
+}
+
+local function palette()
+ local entries = {}
+ for i, e in ipairs(PALETTE) do
+ entries[i] = { brief = e[1], action = act.EmitEvent(EV[e[2]]), icon = e[3] }
+ end
+ return entries
+end
+
+----------------------------------------------------------------------------
+
+local function register_events()
+ if registered then
+ return
+ end
+ registered = true
+
+ wezterm.on(EV.ask, prompt_for(EV.ask_line, 'Ask LLeMbas. It is given the last commands of this pane and their output.'))
+ wezterm.on(EV.ask_screen, prompt_for(EV.ask_screen_line, 'Ask LLeMbas about what is on this screen.'))
+ wezterm.on(EV.ask_line, function(window, pane, line)
+ ask(window, pane, line, false)
+ end)
+ wezterm.on(EV.ask_screen_line, function(window, pane, line)
+ ask(window, pane, line, true)
+ end)
+ wezterm.on(EV.new_session, new_session)
+ wezterm.on(EV.resume, resume)
+ wezterm.on(EV.resume_pick, resume_pick)
+ wezterm.on(EV.toggle_display, toggle_display)
+ wezterm.on(EV.private, toggle_private)
+ wezterm.on(EV.login, login)
+ wezterm.on(EV.dismiss, function() end)
+
+ wezterm.on('user-var-changed', function(_, pane, name, value)
+ if name == 'lembas_state' and value == 'idle' then
+ deliver_pending(pane)
+ end
+ end)
+
+ if opts.session_bar then
+ wezterm.on('update-status', update_status)
+ end
+ if opts.tab_marker then
+ wezterm.on('format-tab-title', format_tab_title)
+ end
+ if opts.palette then
+ wezterm.on('augment-command-palette', palette)
+ end
+end
+
+local KEY_EVENTS = {
+ ask = EV.ask,
+ new_session = EV.new_session,
+ resume = EV.resume,
+ toggle_display = EV.toggle_display,
+ private = EV.private,
+}
+
+-- apply(config, options): add the layer to a configuration. Returns config.
+function M.apply(config, options)
+ local warnings
+ opts, warnings = core.options(options)
+ for _, w in ipairs(warnings) do
+ wezterm.log_warn('llembas: ' .. w)
+ end
+ M.options = opts
+ if not opts.enabled then
+ return config
+ end
+
+ local keys = config.keys or {}
+ for _, name in ipairs { 'ask', 'new_session', 'resume', 'toggle_display', 'private' } do
+ local k = opts.keys[name]
+ if k then
+ keys[#keys + 1] = { key = k.key, mods = k.mods, action = act.EmitEvent(KEY_EVENTS[name]) }
+ end
+ end
+ config.keys = keys
+
+ if opts.autocomplete then
+ -- The shipped shell integration completes the prompt only when it sees this.
+ local env = config.set_environment_variables or {}
+ env.LLEMBAS_TTY_AUTOCOMPLETE = '1'
+ local cli = M.find_cli()
+ if cli then
+ env.LLEMBAS_TTY_CLI = cli
+ end
+ config.set_environment_variables = env
+ end
+
+ register_events()
+ return config
+end
+
+return M
diff --git a/mux/src/domain.rs b/mux/src/domain.rs
index 12109666e..a44fd4d1b 100644
--- a/mux/src/domain.rs
+++ b/mux/src/domain.rs
@@ -476,10 +476,12 @@ impl LocalDomain {
if let Some(dir) = command_dir {
cmd.cwd(dir);
}
- if let Ok(sock) = std::env::var("WEZTERM_UNIX_SOCKET") {
- cmd.env("WEZTERM_UNIX_SOCKET", sock);
+ // LLeMbas TTY: its own variable names, so that neither this program
+ // nor a WezTerm running beside it talks to the other's panes.
+ if let Ok(sock) = std::env::var("LLEMBAS_TTY_UNIX_SOCKET") {
+ cmd.env("LLEMBAS_TTY_UNIX_SOCKET", sock);
}
- cmd.env("WEZTERM_PANE", pane_id.to_string());
+ cmd.env("LLEMBAS_TTY_PANE", pane_id.to_string());
if let Some(agent) = Mux::get().agent.as_ref() {
cmd.env("SSH_AUTH_SOCK", agent.path());
}
diff --git a/wezterm-client/src/client.rs b/wezterm-client/src/client.rs
index df3351365..de527fb85 100644
--- a/wezterm-client/src/client.rs
+++ b/wezterm-client/src/client.rs
@@ -1223,7 +1223,9 @@ impl Client {
prefer_mux: bool,
class_name: &str,
) -> anyhow::Result {
- match std::env::var_os("WEZTERM_UNIX_SOCKET") {
+ // LLeMbas TTY: its own variable names here and below; WezTerm's own
+ // are never read, so a WezTerm pane that starts us is not taken for ours.
+ match std::env::var_os("LLEMBAS_TTY_UNIX_SOCKET") {
Some(path) if !path.is_empty() => Ok(config::UnixDomain {
socket_path: Some(path.into()),
..Default::default()
@@ -1245,7 +1247,7 @@ impl Client {
.first()
.ok_or_else(|| {
anyhow!(
- "no default unix domain is configured and WEZTERM_UNIX_SOCKET \
+ "no default unix domain is configured and LLEMBAS_TTY_UNIX_SOCKET \
is not set in the environment"
)
})?
@@ -1315,7 +1317,7 @@ impl Client {
let pane_id: PaneId = match pane_id {
Some(p) => p,
None => {
- if let Ok(pane) = std::env::var("WEZTERM_PANE") {
+ if let Ok(pane) = std::env::var("LLEMBAS_TTY_PANE") {
pane.parse()?
} else {
let mut clients = self.list_clients().await?.clients;
@@ -1323,7 +1325,7 @@ impl Client {
clients.sort_by(|a, b| b.last_input.cmp(&a.last_input));
if clients.is_empty() {
anyhow::bail!(
- "--pane-id was not specified and $WEZTERM_PANE
+ "--pane-id was not specified and $LLEMBAS_TTY_PANE
is not set in the environment, and I couldn't
determine which pane was currently focused"
);
diff --git a/wezterm-gui-subcommands/src/lib.rs b/wezterm-gui-subcommands/src/lib.rs
index da42ac66c..7229fad86 100644
--- a/wezterm-gui-subcommands/src/lib.rs
+++ b/wezterm-gui-subcommands/src/lib.rs
@@ -4,7 +4,8 @@ use config::{GuiPosition, SshParameters};
use std::ffi::OsString;
use std::path::PathBuf;
-pub const DEFAULT_WINDOW_CLASS: &str = "org.wezfurlong.wezterm";
+// LLeMbas TTY: its own window class / app id
+pub const DEFAULT_WINDOW_CLASS: &str = "eu.llembas.tty";
/// Helper for parsing config overrides
pub fn name_equals_value(arg: &str) -> Result<(String, String), String> {
@@ -62,7 +63,7 @@ pub struct StartCommand {
pub _cmd: bool,
/// Override the default windowing system class.
- /// The default is "org.wezfurlong.wezterm".
+ /// The default is "eu.llembas.tty".
/// Under X11 and Windows this changes the window class.
/// Under Wayland this changes the app_id.
/// This changes the class for all windows spawned by this
@@ -143,7 +144,7 @@ pub struct SshCommand {
pub verbose: bool,
/// Override the default windowing system class.
- /// The default is "org.wezfurlong.wezterm".
+ /// The default is "eu.llembas.tty".
/// Under X11 and Windows this changes the window class.
/// Under Wayland this changes the app_id.
/// This changes the class for all windows spawned by this
@@ -175,7 +176,7 @@ pub struct SerialCommand {
pub baud: Option,
/// Override the default windowing system class.
- /// The default is "org.wezfurlong.wezterm".
+ /// The default is "eu.llembas.tty".
/// Under X11 and Windows this changes the window class.
/// Under Wayland this changes the app_id.
/// This changes the class for all windows spawned by this
@@ -213,7 +214,7 @@ pub struct ConnectCommand {
pub new_tab: bool,
/// Override the default windowing system class.
- /// The default is "org.wezfurlong.wezterm".
+ /// The default is "eu.llembas.tty".
/// Under X11 and Windows this changes the window class.
/// Under Wayland this changes the app_id.
/// This changes the class for all windows spawned by this
diff --git a/wezterm-gui/Cargo.toml b/wezterm-gui/Cargo.toml
index a9f6cdf8d..2c2ed6158 100644
--- a/wezterm-gui/Cargo.toml
+++ b/wezterm-gui/Cargo.toml
@@ -9,6 +9,12 @@ publish = false
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
+# LLeMbas TTY: its own binary name, so that it installs beside WezTerm.
+# The package keeps upstream's name.
+[[bin]]
+name = "llembas-tty-gui"
+path = "src/main.rs"
+
[features]
default = ["vendored-fonts", "wayland"]
wayland = ["window/wayland"]
diff --git a/wezterm-gui/src/main.rs b/wezterm-gui/src/main.rs
index 5e7ca47b3..1fb27eab7 100644
--- a/wezterm-gui/src/main.rs
+++ b/wezterm-gui/src/main.rs
@@ -66,9 +66,11 @@ pub use selection::SelectionMode;
pub use termwindow::{set_window_class, set_window_position, TermWindow, ICON_DATA};
#[derive(Debug, Parser)]
+// LLeMbas TTY: its own name and version
#[command(
- about = "Wez's Terminal Emulator\nhttp://github.com/wezterm/wezterm",
- version = config::wezterm_version()
+ name = "llembas-tty-gui",
+ about = "LLeMbas TTY: a terminal with LLeMbas built in, based on Wez's Terminal Emulator\nhttp://github.com/wezterm/wezterm",
+ version = config::llembas_tty_long_version()
)]
struct Opt {
/// Skip loading wezterm.lua
@@ -412,7 +414,8 @@ async fn async_run_terminal_gui(
) -> anyhow::Result<()> {
let unix_socket_path =
config::RUNTIME_DIR.join(format!("gui-sock-{}", unsafe { libc::getpid() }));
- std::env::set_var("WEZTERM_UNIX_SOCKET", unix_socket_path.clone());
+ // LLeMbas TTY: its own variable name
+ std::env::set_var("LLEMBAS_TTY_UNIX_SOCKET", unix_socket_path.clone());
wezterm_blob_leases::register_storage(Arc::new(
wezterm_blob_leases::simple_tempdir::SimpleTempDir::new_in(&*config::CACHE_DIR)?,
))?;
@@ -561,7 +564,8 @@ impl Publish {
"Running GUI is a different executable from us, will start a new one");
}
if vers.config_file_path
- != std::env::var_os("WEZTERM_CONFIG_FILE").map(Into::into)
+ // LLeMbas TTY: its own variable name
+ != std::env::var_os("LLEMBAS_TTY_CONFIG_FILE").map(Into::into)
{
*self = Publish::NoConnectNoPublish;
anyhow::bail!(
@@ -1172,7 +1176,8 @@ fn run() -> anyhow::Result<()> {
{
unsafe {
::windows::Win32::UI::Shell::SetCurrentProcessExplicitAppUserModelID(
- ::windows::core::PCWSTR(wide_string("org.wezfurlong.wezterm").as_ptr()),
+ // LLeMbas TTY: its own application id
+ ::windows::core::PCWSTR(wide_string("eu.llembas.tty").as_ptr()),
)
.unwrap();
}
diff --git a/wezterm-mux-server-impl/src/sessionhandler.rs b/wezterm-mux-server-impl/src/sessionhandler.rs
index 5dc535f86..481981924 100644
--- a/wezterm-mux-server-impl/src/sessionhandler.rs
+++ b/wezterm-mux-server-impl/src/sessionhandler.rs
@@ -868,7 +868,8 @@ impl SessionHandler {
codec_vers: CODEC_VERSION,
version_string: config::wezterm_version().to_owned(),
executable_path,
- config_file_path: std::env::var_os("WEZTERM_CONFIG_FILE")
+ // LLeMbas TTY: its own variable name
+ config_file_path: std::env::var_os("LLEMBAS_TTY_CONFIG_FILE")
.map(Into::into),
})))
}
diff --git a/wezterm-mux-server/Cargo.toml b/wezterm-mux-server/Cargo.toml
index 6513b6145..250d65993 100644
--- a/wezterm-mux-server/Cargo.toml
+++ b/wezterm-mux-server/Cargo.toml
@@ -8,6 +8,12 @@ publish = false
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
+# LLeMbas TTY: its own binary name, so that it installs beside WezTerm.
+# The package keeps upstream's name.
+[[bin]]
+name = "llembas-tty-mux-server"
+path = "src/main.rs"
+
[dependencies]
anyhow.workspace = true
async_ossl.workspace = true
diff --git a/wezterm-mux-server/src/main.rs b/wezterm-mux-server/src/main.rs
index ba6e66fec..ec19a0a0b 100644
--- a/wezterm-mux-server/src/main.rs
+++ b/wezterm-mux-server/src/main.rs
@@ -15,9 +15,11 @@ use wezterm_mux_server_impl::update_mux_domains_for_server;
mod daemonize;
#[derive(Debug, Parser)]
+// LLeMbas TTY: its own name and version
#[command(
- about = "Wez's Terminal Emulator\nhttp://github.com/wezterm/wezterm",
- version = config::wezterm_version(),
+ name = "llembas-tty-mux-server",
+ about = "LLeMbas TTY: a terminal with LLeMbas built in, based on Wez's Terminal Emulator\nhttp://github.com/wezterm/wezterm",
+ version = config::llembas_tty_long_version(),
trailing_var_arg = true,
)]
struct Opt {
@@ -195,8 +197,9 @@ fn run() -> anyhow::Result<()> {
"OLDPWD",
"PWD",
"SHLVL",
- "WEZTERM_PANE",
- "WEZTERM_UNIX_SOCKET",
+ // LLeMbas TTY: its own variable names
+ "LLEMBAS_TTY_PANE",
+ "LLEMBAS_TTY_UNIX_SOCKET",
"_",
] {
std::env::remove_var(name);
@@ -311,7 +314,8 @@ mod ossl;
pub fn spawn_listener() -> anyhow::Result<()> {
let config = configuration();
for unix_dom in &config.unix_domains {
- std::env::set_var("WEZTERM_UNIX_SOCKET", unix_dom.socket_path());
+ // LLeMbas TTY: its own variable name
+ std::env::set_var("LLEMBAS_TTY_UNIX_SOCKET", unix_dom.socket_path());
let mut listener = wezterm_mux_server_impl::local::LocalListener::with_domain(unix_dom)?;
thread::spawn(move || {
listener.run();
diff --git a/wezterm-toast-notification/src/dbus.rs b/wezterm-toast-notification/src/dbus.rs
index abde9ed37..2ff36cc63 100644
--- a/wezterm-toast-notification/src/dbus.rs
+++ b/wezterm-toast-notification/src/dbus.rs
@@ -105,9 +105,10 @@ async fn show_notif_impl(notif: ToastNotification) -> Result<(), Box Result<(), Box> {
*/
let notifier = ToastNotificationManager::CreateToastNotifierWithId(HSTRING::from(
- "org.wezfurlong.wezterm",
+ // LLeMbas TTY: its own application id
+ "eu.llembas.tty",
))?;
notifier.Show(¬if)?;
diff --git a/wezterm/Cargo.toml b/wezterm/Cargo.toml
index 979a84323..dccb73902 100644
--- a/wezterm/Cargo.toml
+++ b/wezterm/Cargo.toml
@@ -7,6 +7,12 @@ publish = false
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
+# LLeMbas TTY: its own binary name, so that it installs beside WezTerm.
+# The package keeps upstream's name.
+[[bin]]
+name = "llembas-tty"
+path = "src/main.rs"
+
[dependencies]
anyhow.workspace = true
chrono.workspace = true
diff --git a/wezterm/src/cli/activate_pane.rs b/wezterm/src/cli/activate_pane.rs
index 86e827af9..ab1e25435 100644
--- a/wezterm/src/cli/activate_pane.rs
+++ b/wezterm/src/cli/activate_pane.rs
@@ -6,7 +6,7 @@ use wezterm_client::client::Client;
pub struct ActivatePane {
/// Specify the target pane.
/// The default is to use the current pane based on the
- /// environment variable WEZTERM_PANE.
+ /// environment variable LLEMBAS_TTY_PANE.
#[arg(long)]
pane_id: Option,
}
diff --git a/wezterm/src/cli/activate_pane_direction.rs b/wezterm/src/cli/activate_pane_direction.rs
index f552a6728..c77adc059 100644
--- a/wezterm/src/cli/activate_pane_direction.rs
+++ b/wezterm/src/cli/activate_pane_direction.rs
@@ -8,7 +8,7 @@ use wezterm_client::client::Client;
pub struct ActivatePaneDirection {
/// Specify the current pane.
/// The default is to use the current pane based on the
- /// environment variable WEZTERM_PANE.
+ /// environment variable LLEMBAS_TTY_PANE.
#[arg(long)]
pane_id: Option,
diff --git a/wezterm/src/cli/activate_tab.rs b/wezterm/src/cli/activate_tab.rs
index 7cb32b348..0b9045d41 100644
--- a/wezterm/src/cli/activate_tab.rs
+++ b/wezterm/src/cli/activate_tab.rs
@@ -36,7 +36,7 @@ pub struct ActivateTab {
/// Specify the current pane.
/// The default is to use the current pane based on the
- /// environment variable WEZTERM_PANE.
+ /// environment variable LLEMBAS_TTY_PANE.
///
/// The pane is used to figure out which window
/// contains appropriate tabs
diff --git a/wezterm/src/cli/adjust_pane_size.rs b/wezterm/src/cli/adjust_pane_size.rs
index 73fe6c1a8..bd0f67170 100644
--- a/wezterm/src/cli/adjust_pane_size.rs
+++ b/wezterm/src/cli/adjust_pane_size.rs
@@ -9,7 +9,7 @@ use wezterm_client::client::Client;
pub struct CliAdjustPaneSize {
/// Specify the target pane.
/// The default is to use the current pane based on the
- /// environment variable WEZTERM_PANE.
+ /// environment variable LLEMBAS_TTY_PANE.
#[arg(long)]
pane_id: Option,
/// Specify the direction to resize in
diff --git a/wezterm/src/cli/get_pane_direction.rs b/wezterm/src/cli/get_pane_direction.rs
index 5e62241bc..6a6c6b14e 100644
--- a/wezterm/src/cli/get_pane_direction.rs
+++ b/wezterm/src/cli/get_pane_direction.rs
@@ -8,7 +8,7 @@ use wezterm_client::client::Client;
pub struct GetPaneDirection {
/// Specify the current pane.
/// The default is to use the current pane based on the
- /// environment variable WEZTERM_PANE.
+ /// environment variable LLEMBAS_TTY_PANE.
#[arg(long)]
pane_id: Option,
diff --git a/wezterm/src/cli/get_text.rs b/wezterm/src/cli/get_text.rs
index a73f012c3..efa6ed761 100644
--- a/wezterm/src/cli/get_text.rs
+++ b/wezterm/src/cli/get_text.rs
@@ -8,7 +8,7 @@ use wezterm_term::{ScrollbackOrVisibleRowIndex, StableRowIndex};
pub struct GetText {
/// Specify the target pane.
/// The default is to use the current pane based on the
- /// environment variable WEZTERM_PANE.
+ /// environment variable LLEMBAS_TTY_PANE.
#[arg(long)]
pane_id: Option,
diff --git a/wezterm/src/cli/kill_pane.rs b/wezterm/src/cli/kill_pane.rs
index a3b1a2406..e79763a56 100644
--- a/wezterm/src/cli/kill_pane.rs
+++ b/wezterm/src/cli/kill_pane.rs
@@ -6,7 +6,7 @@ use wezterm_client::client::Client;
pub struct KillPane {
/// Specify the target pane.
/// The default is to use the current pane based on the
- /// environment variable WEZTERM_PANE.
+ /// environment variable LLEMBAS_TTY_PANE.
#[arg(long)]
pane_id: Option,
}
diff --git a/wezterm/src/cli/move_pane_to_new_tab.rs b/wezterm/src/cli/move_pane_to_new_tab.rs
index 61ae5da63..b32fbcb42 100644
--- a/wezterm/src/cli/move_pane_to_new_tab.rs
+++ b/wezterm/src/cli/move_pane_to_new_tab.rs
@@ -7,7 +7,7 @@ use wezterm_client::client::Client;
pub struct MovePaneToNewTab {
/// Specify the pane that should be moved.
/// The default is to use the current pane based on the
- /// environment variable WEZTERM_PANE.
+ /// environment variable LLEMBAS_TTY_PANE.
#[arg(long)]
pane_id: Option,
diff --git a/wezterm/src/cli/rename_workspace.rs b/wezterm/src/cli/rename_workspace.rs
index 03c3018fa..7d8f601be 100644
--- a/wezterm/src/cli/rename_workspace.rs
+++ b/wezterm/src/cli/rename_workspace.rs
@@ -11,7 +11,7 @@ pub struct RenameWorkspace {
/// Specify the current pane.
/// The default is to use the current pane based on the
- /// environment variable WEZTERM_PANE.
+ /// environment variable LLEMBAS_TTY_PANE.
///
/// The pane is used to figure out which workspace
/// should be renamed.
diff --git a/wezterm/src/cli/send_text.rs b/wezterm/src/cli/send_text.rs
index d9651bf5d..c6f54bc2b 100644
--- a/wezterm/src/cli/send_text.rs
+++ b/wezterm/src/cli/send_text.rs
@@ -8,7 +8,7 @@ use wezterm_client::client::Client;
pub struct SendText {
/// Specify the target pane.
/// The default is to use the current pane based on the
- /// environment variable WEZTERM_PANE.
+ /// environment variable LLEMBAS_TTY_PANE.
#[arg(long)]
pane_id: Option,
diff --git a/wezterm/src/cli/set_tab_title.rs b/wezterm/src/cli/set_tab_title.rs
index 6cf231222..4979c3fb8 100644
--- a/wezterm/src/cli/set_tab_title.rs
+++ b/wezterm/src/cli/set_tab_title.rs
@@ -11,7 +11,7 @@ pub struct SetTabTitle {
tab_id: Option,
/// Specify the current pane.
/// The default is to use the current pane based on the
- /// environment variable WEZTERM_PANE.
+ /// environment variable LLEMBAS_TTY_PANE.
///
/// The pane is used to figure out which tab should be renamed.
#[arg(long)]
diff --git a/wezterm/src/cli/set_window_title.rs b/wezterm/src/cli/set_window_title.rs
index 089c87a2c..012b54169 100644
--- a/wezterm/src/cli/set_window_title.rs
+++ b/wezterm/src/cli/set_window_title.rs
@@ -11,7 +11,7 @@ pub struct SetWindowTitle {
window_id: Option,
/// Specify the current pane.
/// The default is to use the current pane based on the
- /// environment variable WEZTERM_PANE.
+ /// environment variable LLEMBAS_TTY_PANE.
///
/// The pane is used to figure out which window
/// should be renamed.
diff --git a/wezterm/src/cli/spawn_command.rs b/wezterm/src/cli/spawn_command.rs
index 0e6e490ca..9de676e0a 100644
--- a/wezterm/src/cli/spawn_command.rs
+++ b/wezterm/src/cli/spawn_command.rs
@@ -12,7 +12,7 @@ use wezterm_client::client::Client;
pub struct SpawnCommand {
/// Specify the current pane.
/// The default is to use the current pane based on the
- /// environment variable WEZTERM_PANE.
+ /// environment variable LLEMBAS_TTY_PANE.
/// The pane is used to determine the current domain
/// and window.
#[arg(long)]
diff --git a/wezterm/src/cli/split_pane.rs b/wezterm/src/cli/split_pane.rs
index e51f50820..8afc086c1 100644
--- a/wezterm/src/cli/split_pane.rs
+++ b/wezterm/src/cli/split_pane.rs
@@ -10,7 +10,7 @@ use wezterm_client::client::Client;
pub struct SplitPane {
/// Specify the pane that should be split.
/// The default is to use the current pane based on the
- /// environment variable WEZTERM_PANE.
+ /// environment variable LLEMBAS_TTY_PANE.
#[arg(long)]
pane_id: Option,
diff --git a/wezterm/src/cli/zoom_pane.rs b/wezterm/src/cli/zoom_pane.rs
index e8b8f7558..a30f4a4d9 100644
--- a/wezterm/src/cli/zoom_pane.rs
+++ b/wezterm/src/cli/zoom_pane.rs
@@ -9,7 +9,7 @@ use wezterm_client::client::Client;
pub struct ZoomPane {
/// Specify the target pane.
/// The default is to use the current pane based on the
- /// environment variable WEZTERM_PANE.
+ /// environment variable LLEMBAS_TTY_PANE.
#[arg(long)]
pane_id: Option,
diff --git a/wezterm/src/main.rs b/wezterm/src/main.rs
index 0661d803d..453eaac4c 100644
--- a/wezterm/src/main.rs
+++ b/wezterm/src/main.rs
@@ -2,7 +2,8 @@ use anyhow::{anyhow, Context};
use clap::builder::ValueParser;
use clap::{Parser, ValueEnum, ValueHint};
use clap_complete::{generate as generate_completion, shells, Generator as CompletionGenerator};
-use config::{wezterm_version, ConfigHandle};
+// LLeMbas TTY: its own version for --version
+use config::{llembas_tty_long_version, ConfigHandle};
use mux::Mux;
use std::ffi::OsString;
use std::io::Read;
@@ -22,9 +23,11 @@ mod cli;
// let message = "; ❤ 😍🤢\n\x1b[91;mw00t\n\x1b[37;104;m bleet\x1b[0;m.";
#[derive(Debug, Parser)]
+// LLeMbas TTY: its own name and version
#[command(
- about = "Wez's Terminal Emulator\nhttp://github.com/wezterm/wezterm",
- version = wezterm_version()
+ name = "llembas-tty",
+ about = "LLeMbas TTY: a terminal with LLeMbas built in, based on Wez's Terminal Emulator\nhttp://github.com/wezterm/wezterm",
+ version = llembas_tty_long_version()
)]
pub struct Opt {
/// Skip loading wezterm.lua
@@ -771,10 +774,11 @@ fn delegate_to_gui(saver: UmaskSaver) -> anyhow::Result<()> {
// Restore the original umask
drop(saver);
+ // LLeMbas TTY: its own binary names
let exe_name = if cfg!(windows) {
- "wezterm-gui.exe"
+ "llembas-tty-gui.exe"
} else {
- "wezterm-gui"
+ "llembas-tty-gui"
};
let exe = std::env::current_exe()?