Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

uji. A coding agent you can shape with Lua.

Introduction

uji is a coding agent for your terminal, configured in Lua. This is a complete ~/.config/uji/init.lua:

require("uji.builtin.defaults")

uji.pack.add({ "uji-labs/uji-plugins" })
require("statusline").setup({})
require("planmode").setup({})

uji.tool.policy({
  run_command = { allow = { "git status", "cargo test*" } },
})

uji.keymap.add("normal", "<C-p>", { command = "models" })

uji.command.add("standup", function()
  uji.session.submit("Summarise the commits since yesterday.")
end)

Getting started

This chapter installs uji, signs you in to a provider, and lists the commands and keys you use while you work.

Installation

On a Mac with Apple silicon, or on 64-bit Intel or ARM Linux, this installs the latest release:

curl -fsSL https://raw.githubusercontent.com/uji-labs/uji/main/install.sh | sh
VariableEffect
UJI_INSTALL_DIRThe folder uji goes in, instead of ~/.local/bin.
UJI_VERSIONA release such as v0.3.0 instead of the latest one.

The Linux builds need glibc 2.34 or newer. On Alpine, other musl systems and older releases such as Ubuntu 20.04, build uji with Cargo.

With Homebrew

brew install uji-labs/uji/uji

Homebrew installs the same ready-made build as the script. brew upgrade uji moves to a newer release.

On Fedora with COPR

sudo dnf copr enable @uji-labs/Uji
sudo dnf install uji

With Nix

nix profile add github:uji-labs/uji

With home-manager, add the flakes of uji and its plugins to your inputs:

inputs = {
  uji.url = "github:uji-labs/uji";
  uji-plugins.url = "github:uji-labs/uji-plugins";
};

Then import their modules and turn uji on:

{ inputs, ... }:
{
  imports = [
    inputs.uji.homeModules.default
    inputs.uji-plugins.homeModules.default
  ];

  programs.uji.enable = true;
}

programs.uji.plugins.<name>.enable turns a plugin on or off.

With Cargo

cargo install --git https://github.com/uji-labs/uji --locked uji

The build needs Rust 1.88 or newer, a C compiler and make. Cargo puts the uji binary in ~/.cargo/bin, and uji --version prints the version once your shell finds it.

From a clone of the repository, run cargo install --path crates/uji --locked in its top folder instead. Adding --force to either command replaces an installed uji with a newer one.

First run

Start uji in the directory you want to work on.

cd ~/code/project
uji

Signing in

Type /login and pick a provider from the list.

  • Anthropic and OpenAI ask how you want to sign in. “Subscription (sign in with browser)” opens the provider’s sign-in page, and “API key” asks for a key.
  • OpenAI also offers “Subscription (sign in with device code)”. Open the displayed link on any device and enter the one-time code within 15 minutes. Enable device code login in your ChatGPT security settings or workspace permissions first. This works without a browser or a callback port on the machine running uji.
  • A provider that needs a key asks for it. The prompt names the environment variable uji also reads, such as ANTHROPIC_API_KEY, and pressing Enter on an empty prompt uses that variable instead.
  • GitHub Copilot starts device code sign-in without a method picker. Open the displayed link and enter the one-time code. uji uses your Copilot subscription and loads its chat models with tool support. GitHub Models remains a separate provider.
  • Custom asks for the base_url and model of a server that takes OpenAI chat requests.
  • A provider you are signed in to asks whether to sign in again or sign out.

uji saves keys and subscription sign-ins in auth.toml in the data directory, readable only by you. To keep them in the system keychain instead, call uji.auth.configure in your config.

Choosing a model

/models lists the models of every provider you are signed in to. /effort sets how much the model reasons, from the levels that model accepts.

Making it yours

/setup writes a starter config and asks what you want in it. Starting a config shows what it writes.

Working with the model

  • Enter sends your message. Shift+Enter, Alt+Enter or Ctrl+J start a new line.
  • A message you send while the model works waits, and goes out when the turn ends.
  • Esc clears the input line. On an empty line, Esc stops the turn.
  • A line that starts with ! runs in your shell, in the session’s directory. Its output shows in the transcript, and the model does not see it.
  • When a tool call needs your approval, y lets it run. n or Esc refuses it, and you can then tell the model what to do instead.

Sending images

Ctrl+V attaches the image on the clipboard, or pastes its text when it holds no image. Pasting the path of an image file attaches that file, which is what dragging a file into most terminals does, and @screenshot.png in a message attaches the file when you send it.

Each attached image shows as [image #1] on the input line, and deleting the marker drops the image. uji takes PNG, JPEG, GIF and WebP files. It turns photos upright and scales images down to 1568 pixels on their long side, then to a smaller size or JPEG when they would still pass 5 MB.

A request carries the 20 newest images of the conversation, and a note takes the place of older ones. A model that takes no images gets the text with the same kind of note. uji knows this for most built-in models, and learns it for others the first time a model refuses a request with images.

The model can open images on its own as well. read_file on a PNG, JPEG, GIF or WebP file in the working directory gives it the image.

uji saves every conversation as a session. Commands shows how to go back to one.

Commands

Running uji

RunDoes
uji, uji newStarts a new session.
uji resumeResumes the latest session in the current directory.
uji resume --id <ID>Resumes the session with that id.
uji listOpens a picker of the sessions in the current directory.
uji delete <ID>Deletes a session.
uji run <PROMPT>Sends one prompt without the screen and prints the answer. See Running without the screen.
uji --helpPrints the usage.
uji --versionPrints the version.

Any of them takes these options. Where uji keeps its files lists the environment variables that do the same.

OptionSets
--config-dir <DIR>The config directory.
--data-dir <DIR>The data directory.
--db <FILE>The session database.

Slash commands

CommandDoes
/loginAdds a provider.
/setupWrites a starter config, then asks what you want in it. It is there until you have a config. See Configuration.
/modelsPicks the model.
/effortSets the reasoning effort, from the levels the current model accepts.
/thinkingShows or hides the model’s reasoning.
/compactSummarises earlier messages to free context.
/listLists the sessions in this directory. Enter starts uji again in the one you pick.
/resumeStarts uji again in the latest session here, or /resume <ID> in that one.
/syncUpdates installed packs and reloads.
/reloadStarts uji again with your current config and files, keeping the conversation and your draft.
/helpLists every command, including the ones plugins add.
/jobsOpens the background jobs list under the input, finished ones included, and closes it when run again. It picks the first job: Enter opens it, ↑ and ↓ pick another, x stops or drops one, Esc closes the list.
/diagnosticsLists the errors uji ran into while drawing the screen, newest first, with the details of each.
/quitQuits.

Keys

Default bindings lists every key uji binds, and uji.keymap changes them.

Running a prompt without the screen

uji run sends one prompt, lets the model work until it answers, prints the answer and exits. Scripts and other programs use it, and so do the agents of the subagent plugin. It reads the same config, plugins and packs as uji does on the screen, and saves the conversation as a session.

uji run "Summarise what changed in the last commit"

The words after the options form the prompt. The exit code is 0 when the model answers and 1 when the turn fails, with the reason on standard error.

OptionDoes
--jsonPrints every event as a line of JSON instead of the answer alone.
--model <PROVIDER/ID>Uses this model instead of the one you picked with /models.
--effort <LEVEL>Uses this reasoning effort: off, minimal, low, medium, high, xhigh or max. uji uses the nearest level the model accepts.
--tools <A,B>Offers the model only these tools, separated by commas.
--append-prompt <TEXT>Adds the text to the end of the system prompt.
--title <TEXT>Titles the session. The default is the first line of the prompt.
--parent <ID>Saves the session under another one. uji list leaves it out, and uji resume --id opens it.

Nobody can answer an approval question here, so a call your policy would ask about runs without asking. Calls your policy denies stay denied.

The options --config-dir, --data-dir and --db work as they do for the other commands.

JSON events

With --json, each line is one event.

typeFieldsWhen
sessionidFirst, with the id of the new session.
messagemessageA message joined the conversation, in the form uji saves it.
progresstool, lineA running tool printed a line.
noticetext, secondsuji has something to tell you, such as a plugin error. seconds is there when the notice asked for its own time.
donetext or error, and usageLast. usage has input, output, cache_read and cache_write tokens for the whole run.
uji run --json --tools read_file "What does src/main.rs do?" | jq -r 'select(.type == "done") | .text'

Configuration

uji reads ~/.config/uji, or the directory in UJI_CONFIG_DIR.

~/.config/uji/
  init.lua        runs first
  plugin/*.lua    runs after init.lua, sorted by file name
  lua/            modules for require()

init.lua replaces the default config. Start it with require("uji.builtin.defaults") to keep the default screen.

require("uji.builtin.defaults")

uji.keymap.add("normal", "<C-p>", { command = "models" })

Starting a config

Until you have an init.lua, /setup writes one for you. Sign in with /login first, because the model does the asking.

/setup does three things.

  1. It writes an init.lua that keeps the defaults, adds the uji-plugins pack and turns on skills. An init.lua you already have is left as it is.
  2. It writes the uji-config skill to .agents/skills/uji-config in the config directory. The skill holds a guide to changing the config and a copy of this book for your version of uji.
  3. It asks what you want, one question at a time: what uji may run without asking, which plugins to turn on, the theme and the keys. It writes each answer into init.lua as you give it, which you approve like any other change, and reloads so that you see it take effect.

Text after the command says what you want up front, such as /setup only a dark theme and the status line.

/setup is gone once you have a config, and the skill takes over: ask uji in plain words to change its own setup.

Changing the config from inside uji

Start uji in the config directory and ask for the change. There the model has the reload_config tool. After it edits the config, uji restarts on the same conversation when the turn ends and tells the model which notices loading the config raised, so it can fix an error it made and carry on.

Anywhere else the model cannot restart uji, and you run /reload yourself.

Where uji keeps its files

FilesDefaultChanged by
Config directory~/.config/uji--config-dir, UJI_CONFIG_DIR or XDG_CONFIG_HOME
Data directory~/.local/share/uji--data-dir, UJI_DATA_DIR or XDG_DATA_HOME
Session databaseuji.db in the data directory--db or UJI_DB
Installed packssite/ in the data directory
Pack versionsuji-lock.json in the config directory
Credentialsauth.toml in the data directoryuji.auth.configure
Auth fileauth.env in the config directoryuji.auth.configure or UJI_AUTH_FILE
Diagnosticsdiagnostics.log in the data directory

An option on the command line wins over the UJI_ variable, which wins over the XDG_ one. uji adds /uji to the XDG_ directories.

Packs

uji.pack.add installs a directory or git repository with its own lua/ and plugin/. /sync updates them.

uji.pack.add({
  "uji-labs/uji-plugins",
  { "someone/tool", tag = "v1.2" },
  { dir = "~/code/my-plugin" },
})

Themes

uji starts out in default, or in the theme you saved, and uji.ui.configure switches to another one by name.

uji.ui.configure({ theme = "harbor" })

A name loads lua/uji/themes/<name>.lua from your config directory or from a pack, and that file returns the theme. You can also pass the theme itself.

Choosing and keeping a theme

uji.modules("uji.themes") lists every theme uji can load, from uji, your config directory and your packs. uji.ui.save_theme keeps one for the next start.

local names = {}
for index, module in ipairs(uji.modules("uji.themes")) do
  names[index] = module:match("[^.]+$")
end
uji.ui.select({ title = "Theme", items = names }, function(name)
  if name then
    uji.ui.configure({ theme = name })
    uji.ui.save_theme(name)
  end
end)

uji puts the saved theme on before it runs your config, so a theme your config sets still wins.

Building a theme

require("uji.themes.default") is a function that takes the parts you change and returns a whole theme. Everything you leave out keeps its default.

local ito = require("ito")

return require("uji.themes.default")({
  name = "harbor",
  colors = {
    text = ito.rgb(0xc0caf5),
    muted = ito.rgb(0x565f89),
    accent = ito.rgb(0x7aa2f7),
    user_bg = ito.rgb(0x24283b),
  },
  styles = function(colors)
    return {
      user = ito.TextStyle({ foreground = colors.text, background = colors.user_bg, italic = true }),
    }
  end,
  symbols = { pointer = "▸" },
})

Changing a colour also changes every default style drawn in it, so a new accent recolours the headings, the chosen items and the rest. styles is a table of the styles you change, or a function that takes the theme’s colours and returns that table.

A theme that builds on another one reads its values:

local ito = require("ito")
local harbor = require("uji.themes.harbor")

return require("uji.themes.default")({
  name = "harbor_warm",
  colors = {
    text = harbor.colors.text,
    muted = harbor.colors.muted,
    accent = ito.rgb(0xff9e64),
  },
})

The theme table

KeyMeaning
nameThe theme’s name. Error messages use it.
colorsNamed colours.
stylesNamed text styles.
symbolsThe symbols uji draws. See Symbols, words and sizes.
bordersThe characters of each kind of box. See Borders.
textThe words uji draws.
limitsSizes and timings.
optionsAnything the theme wants to keep for itself.
viewsReplacements for the views uji draws. See The screen and Views.

Build a theme with uji.themes.default, which fills in everything you leave out. colors and styles can also hold names of your own, for your own views.

Colours

A colour is an ito.Color value, made in one of three ways:

  • ito.rgb(0xd4d4d4) gives a colour from its red, green and blue parts.
  • ito.Color.indexed(245) gives one of the terminal’s 256 colours, numbered from 0 to 255.
  • ito.Color.cyan is one of the terminal’s named colours. The names are black, red, green, yellow, blue, magenta, cyan, white, gray, dark_gray, light_red, light_green, light_yellow, light_blue, light_magenta and light_cyan.

The default theme has these colours.

ColourDefault
textito.rgb(0xd4d4d4)
mutedito.rgb(0x808080)
codeito.rgb(0xe0af68)
accentito.Color.cyan
user_bgito.rgb(0x343541)
selected_bgito.rgb(0x3a3a4a)
cursorito.Color.white
errorito.Color.red
noticeito.Color.red
warningito.Color.yellow
syntax.keyword, syntax.string, syntax.number, syntax.commentito.Color.cyan, ito.rgb(0xe0af68), ito.rgb(0xe0af68), ito.rgb(0x808080)
syntax.func, syntax.type, syntax.constantito.rgb(0xdcdcaa), ito.rgb(0x4ec9b0), ito.rgb(0x569cd6)
call.doneito.rgb(0x87d787)
diff.added, diff.removedito.rgb(0x5fd75f), ito.rgb(0xd75f5f)
diff.added_bg, diff.removed_bgito.rgb(0x005f00), ito.rgb(0x5f0000)
diff.added_word_bg, diff.removed_word_bgito.rgb(0x008700), ito.rgb(0x870000)

syntax and diff are groups: tables of colours under one name. syntax colours the code in replies and diffs, and diff colours the lines a diff adds and removes. A theme that sets a group sets every colour in it.

A theme can also set these colours, which the default theme leaves out.

ColourPaintsWithout it
backgroundThe screen style.The terminal’s own background.
linkLinks in the link style.Links in the text’s colour.

A theme with a background colour paints every cell. A terminal draws a painted cell fully opaque unless it applies its opacity to painted cells too, which Ghostty does with background-opacity-cells = true.

local ito = require("ito")

return require("uji.themes.default")({
  name = "night",
  colors = { background = ito.rgb(0x1a1b26), link = ito.rgb(0x7dcfff) },
})

Styles

A style is an ito.TextStyle value. It takes a table with foreground, background and any of the flags bold, dim, italic, underline, reverse, strikethrough and blink. The colours are ito.Color values, and every field can be left out.

local ito = require("ito")

local note = ito.TextStyle({ foreground = ito.Color.yellow, italic = true })

style:merge(other) gives a style with the colours and flags of other on top of those of style.

Styles come in groups too, such as styles.syntax and styles.diff. A theme that sets a group sets every style in it.

The default theme has these styles.

StyleUsed forDefault
plainText with the terminal’s own style.no style
screenThe background of the whole screen, and of the lists and boxes drawn over it.on background
textBody text.text
boldTitles and tool calls.text, bold
mutedSecondary text.muted
dimHints and counts.muted, dim
faintThe model’s thinking.muted, italic, dim
systemSystem messages.muted, italic
codeCode and maths.code
accentLarge headings and the chosen item.accent, bold
highlightKeywords in code and keys in hints.accent
userYour messages.text on user_bg
selectedThe background of a chosen row.on selected_bg
chosenA chosen row in a picker.text on selected_bg
chosen_nameThe name on a chosen suggestion.accent on selected_bg
chosen_descThe description on a chosen suggestion.muted on selected_bg
errorErrors and failed tool output.error
noticeA notice a uji.ui.Notice draws.notice
warningA warning drawn above the input, such as a deprecated plugin.warning
cursorThe cursor block, drawn over the character it sits on.cursor on cursor, blink
inputText on the input line.text
borderBorders.muted
reverseSelected text and the copy message.reverse
confirm_titleThe approval question’s title.text, bold
confirm_bodyThe approval question’s details.text
confirm_selectedThe chosen answer.accent, bold
confirm_unselectedThe other answer.muted
heading1 to heading6Markdown headings of each level.accent, bold for 1 and 2, text, bold for the rest
strong, emphasis, strikethrough, linkMarkdown bold, italic, struck and linked text, merged on top of the text around it.bold, italic, strikethrough, link underlined
table_headThe header row of a table, merged on top of each cell.bold
syntax.keyword, syntax.string, syntax.number, syntax.comment, syntax.func, syntax.type, syntax.constantHighlighted code, in replies and in diffs.the syntax colour of the same name, syntax.comment in italic
selectionText you select with the mouse.reverse
call.label, call.detailA tool call’s name and, in brackets after it, its subject.text, bold, and text
call.running, call.done, call.failedThe mark before a tool call while it runs, after it worked and after it failed. call.done also marks a job that finished.muted, call.done, error
diff.added, diff.removedAdded and removed lines in a diff, across the whole row.on diff.added_bg, text on diff.removed_bg
diff.added_sign, diff.removed_signThe number and the + or - of those lines.diff.added on diff.added_bg, diff.removed on diff.removed_bg
diff.added_word, diff.removed_wordThe words that changed on those lines, merged on top.on diff.added_word_bg, on diff.removed_word_bg

Symbols, words and sizes

KeyMeaningDefault
symbols.spinnerThe frames of the waiting animation.⠋ ⠙ ⠹ ⠸ ⠼ ⠴ ⠦ ⠧ ⠇ ⠏
symbols.toolThe mark before a tool call.⏺
symbols.branchThe mark before a tool’s output.⎿
symbols.moreThe mark before the count of hidden output lines.…
symbols.shellThe mark before a command you ran.!
symbols.ruleThe line drawn where the session was compacted.─
symbols.noticeThe mark uji.ui.Notice puts before its text.!
symbols.thinkingThe bar beside the model’s thinking.│
symbols.queuedThe mark before a queued message.›
symbols.runningThe mark before the tool that is running, and before a job that runs in the jobs list.⋯
symbols.doneThe mark before a job in the jobs list that finished cleanly.✓
symbols.stoppedThe mark before a job in the jobs list that you stopped.⊘
symbols.failedThe mark before a job in the jobs list that failed or timed out.✗
symbols.separatorThe mark between the parts of the status line.·
symbols.jumpThe arrow on the jump to the bottom.↓
symbols.bulletsThe bullets of each list level, used in turn.• ◦ ▪
symbols.quoteThe bar beside a quote.│
symbols.columnThe line between table columns.│
symbols.task_done, symbols.task_openThe marks of a done and an open task.[x], [ ]
symbols.inputThe mark in front of each row of the input line, in the accent style.""
symbols.maskWhat hidden input, such as a key, shows instead of each character.•
symbols.pointerThe mark beside the chosen item in a list or an approval.›
symbols.promptThe mark before what you type in a picker or prompt.>
text.confirm_yesThe word that allows a tool call."Yes"
text.confirm_noThe word that refuses it."No"
text.exitThe word before a command’s exit status."exit"
text.compactedThe label where the session was compacted."compacted"
text.hiddenThe count of hidden output lines. %d is the count."+%d lines"
text.jumpThe label that takes you back to the bottom."Jump to bottom"
text.orderedThe number of an ordered list item. %d is the number."%d."
text.currentThe label beside the item in use, such as the current model."(current)"
text.rangeThe count under a long list. The numbers are the first and last shown and the total."%d–%d of %d"
text.confirm_allow, text.confirm_denyThe rest of each approval answer, after confirm_yes and confirm_no."proceed", "and tell uji what to do differently"
text.scrollThe line an approval shows when its details do not fit."lines %d-%d of %d, scroll for more"
text.workingThe line shown while the model works. %d is the seconds so far."Working (%ds)"
text.jobThe name of a background job wherever uji shows one: the jobs list, its notices and the job_output and stop_job lines. %d is its number."job %d"
text.jobs_hintThe line under the input once a job finishes, naming where its output went."/jobs to see finished jobs"
text.jobs_titleThe title of the jobs list that /jobs opens."Jobs"
text.jobs_countThe count beside that title. The first number is how many jobs run and the second how many jobs there are, those it names below included."%d/%d running"
text.jobs_moreThe line under a full jobs list, after symbols.more, naming the jobs it left out. %d is the count."%d more"
text.output, text.stop, text.closeWhat Enter, x and Esc do in the jobs list, after their keys."output", "stop", "close"
text.added, text.removedThe parts of the line above a diff, joined by a comma when both are there. %d is the count and %s is text.line or text.lines. The line starts with a capital letter."Added %d %s", "removed %d %s"
text.line, text.linesThe word for one line and for more."line", "lines"
text.copied, text.copied_terminalThe message after you copy a selection. %d is the line count."copied %d line(s)", "copied %d line(s) via the terminal"
text.pasted_lines, text.pasted_charsThe placeholder for a long paste in the input line. The numbers are the paste’s number and its size."[paste #%d +%d lines]", "[paste #%d %d chars]"
text.imageThe placeholder for an attached image."[image #%d]"
text.sessions_titleThe title of uji list. %s is the directory."Sessions in %s"
text.sessions_emptyWhat uji list says when there is nothing to show."No sessions in current directory"
text.column_title, text.column_updated, text.column_idThe column heads of uji list."TITLE", "UPDATED", "ID"
text.key_move, text.key_open, text.key_quitThe keys in the hint under uji list and the jobs list."↑/↓", "enter", "esc"
text.key_stopThe key in the jobs list hint that stops the chosen job."x"
text.navigate, text.resume, text.quitWhat those keys do."navigate", "resume", "quit"
limits.spinner_intervalSeconds between spinner frames.0.08
limits.suggest_rowsRows the command suggestions may use.5
limits.tool_previewRows of tool output shown before you open it.8
limits.diff_previewRows of a diff shown before you open it.20
limits.diff_contextUnchanged lines that uji.diff keeps around each change.3
limits.argument_previewCharacters of a tool call’s arguments shown when it has no subject.200
limits.message_gapBlank rows between messages.1
limits.section_gapBlank rows before the queue and the running tool.1
limits.bottom_gapRows kept free under the transcript, where the jump shows.1
limits.indentColumns each list or quote level is indented by.2
limits.rule_widthThe longest a markdown rule is drawn.60
limits.block_gapBlank rows between markdown blocks.1
limits.reply_marginColumns to the left of a reply.1
limits.input_rowsThe most rows the input line grows to.10
limits.select_rowsThe most rows a list takes, with the line under it that counts its items.13
limits.suggest_nameThe width of a command’s name in the suggestions.12
limits.preview_minThe width a picker needs on each side before it shows a preview.24
limits.sessions_updated, limits.sessions_idThe widths of the UPDATED and ID columns of uji list.14, 36
limits.float_width, limits.float_heightThe share of the screen, in percent, that a floating picker or overlay takes.90, 80
limits.flashSeconds a notice stays up, until one asks for its own time.1
limits.paste_lines, limits.paste_charsThe size a paste can be before the input line shows a placeholder for it.1, 80

A key uji does not know is an error, so a misspelled one does not go unnoticed.

Borders

borders.plain and borders.rounded give the characters a box of that kind is drawn with. A horizontal border uses the plain border’s horizontal.

borders = {
  rounded = {
    top_left = "╭",
    top_right = "╮",
    bottom_left = "╰",
    bottom_right = "╯",
    horizontal = "─",
    vertical = "│",
  },
}

The default plain border is ┌ ┐ └ ┘ ─ │, and the rounded one is ╭ ╮ ╰ ╯ ─ │, in the same order as above.

The screen

uji.ui.Screen is the view of the whole screen, and a theme replaces it in views. The replacement takes screen, which holds uji’s parts, and each call gives a fresh view of that part:

CallWhat it shows
screen.transcript()The messages.
screen.composer()The input line, or the approval question, which takes the input line’s place while it is open.
screen.jobs()The jobs list under the input; takes no room while it is closed.
screen.status()The status line, or the bar a plugin set with uji.ui.status.
screen.modals()The lists to choose from, the prompts, the command suggestions and overlays opened with float = false. They take no room while none is open, and on a screen without this part they float in a box instead.
screen.activity()The line shown while the model works, with no room while the model is idle.
screen.greeting()The theme’s uji.ui.Greeting.

Plugins put their views in toolbar sections, and the screen decides where each section sits with ito.ToolbarItems(ito.ToolbarPlacement.x). A section the screen leaves out is not drawn. The theme never names a plugin, and no plugin names a part of the screen.

This screen puts the input line in a rounded box at the top, the row of keyboard items under it, and the bottom bar’s items side by side:

local ito = require("ito")

return require("uji.themes.default")({
  views = {
    [uji.ui.Screen] = function(screen)
      local placement = ito.ToolbarPlacement
      return ito.VStack({
        screen.composer():border(ito.theme().borders.rounded),
        screen.modals(),
        ito.ToolbarItems(placement.keyboard, ito.HStack),
        screen.transcript():grow(),
        screen.activity(),
        screen.jobs(),
        screen.status(),
        ito.ToolbarItems(placement.bottom_bar, ito.HStack),
      })
    end,
  },
})

The default screen is this view:

function(screen)
  local placement = ito.ToolbarPlacement
  return ito.VStack({
    ito.HStack({
      ito.ToolbarItems(placement.top_bar_leading, ito.HStack),
      ito.Spacer(),
      ito.ToolbarItems(placement.top_bar_trailing, ito.HStack),
    }),
    screen.greeting(),
    screen.transcript():grow(),
    screen.activity():padding({ vertical = 1 }),
    screen.modals(),
    ito.ToolbarItems(placement.keyboard),
    screen.composer():border(ito.theme().borders.plain, { edges = ito.Edges.horizontal }),
    screen.jobs(),
    screen.status(),
    ito.ToolbarItems(placement.bottom_bar),
  })
end

A screen that raises an error is replaced by the default screen for that frame, and uji records the problem once, where /diagnostics shows it.

Views

Everything uji draws is a view in uji.ui, and a theme replaces any of them in views, keyed by the view itself. A replacement is a function that takes the view’s props and returns a view.

local ito = require("ito")

return require("uji.themes.default")({
  views = {
    [uji.ui.Queued] = function(props)
      local styles = ito.theme().styles
      return ito.HStack({ ito.Text("note: "):style(styles.accent), ito.Text(props.text):style(styles.text) })
    end,
  },
})
ViewPropsWhat it draws
uji.ui.Screenthe partsThe whole screen. See The screen.
uji.ui.GreetingnoneWhat the screen shows before you start, such as a logo. It draws nothing until a theme replaces it.
uji.ui.UserMessagemessageOne of your messages.
uji.ui.ToolCallcall, with name and argumentsA tool call, described the way its tool asks.
uji.ui.ToolOutputcontent, summary, diff, failed, expanded, toggleA tool’s result. It shows the diff when the result has one with changes, otherwise the summary until it is opened, otherwise the content. toggle opens or folds it, and the default view calls it when you click a line.
uji.ui.Diffdiff, limit, toggleThe lines of a diff, with their numbers and colours, in a tool’s result and in the approval question. diff is what uji.diff gives, limit, when given, folds it after that many rows, and toggle opens or folds it.
uji.ui.Shellcommand, code, output, failed, expanded, toggleA command you ran with !.
uji.ui.SystemMessage, uji.ui.ErrorMessage, uji.ui.Queued, uji.ui.ThinkingtextA message or line of that kind.
uji.ui.PartialtextThe last line of a reply that is still arriving.
uji.ui.CompactionnoneThe place where the session was compacted.
uji.ui.Runningname, lineThe tool that is running and the last line it printed.
uji.ui.JobjobA background job that is running. job has id, command and last, the last line it printed.
uji.ui.JumpfollowThe label that takes you back to the bottom, centred in the bottom row of the transcript. follow goes back.
uji.ui.Paragraphtokens, indent, hangingA markdown paragraph or list item. Each token has text, style and spaced, and indent and hanging start the first and the following lines.
uji.ui.Headinglevel, contentA markdown heading. content is the heading’s text as a view.
uji.ui.CodeBlocklanguage, linesA fenced code block: its language, then its code. lines holds the lines of code, and language can be nil.
uji.ui.Codelanguage, linesThe lines of a code block, highlighted for language, without the language above them.
uji.ui.MathBlocklinesDisplay maths, already turned into text.
uji.ui.TablerowsA table, its columns lined up. Each row has cells, one list of spans per cell, and head, which is true for the header row.
uji.ui.RulenoneA markdown rule.
uji.ui.ActivitynoneThe line shown while the model works.
uji.ui.FlashnoneThe copy message in the top right corner.
uji.ui.InputnoneThe input line.
uji.ui.SelectListtitle, query, items, matches, selection, currentA list to choose from. matches are the indexes into items that fit the query, and selection is a state that holds the chosen match, ready for ito.List.
uji.ui.PromptFieldtitle, valueA question with a text answer.
uji.ui.Suggestionsitems, selectionThe command suggestions. Its items have name and desc.
uji.ui.Approvaltitle, body, preview, allow, keys, scrollAn approval. scroll is the ito.ScrollState of its body.
uji.ui.Pickertitle, items, matches, selection, current, preview, query, totalThe picker with a preview.
uji.ui.Sessionsdirectory, sessions, selection, nowThe screen uji list shows. selection holds the chosen session’s index, ready for ito.List.

ito.theme() gives the theme’s colors, styles, symbols, borders, text, limits and options. Asking its styles for a name the theme does not have raises an error, such as the theme has no style named heading7. It also has these helpers.

HelperReturns
ctx:typed(field, styles)The spans of a text field with the cursor in it. field has text, cursor and hidden, and styles has text and cursor.
ctx:measure(text)The number of columns text takes.
ctx:first(text, count)The first count characters of text.

A replacement that raises an error is skipped, uji draws the view’s own default instead, and the problem is recorded once, such as theme view: no queue today, where /diagnostics shows it. A plugin’s views are replaced the same way: the plugin exports its view, and a theme keys its replacement by it.

A theme from a base16 palette

A base16 scheme gives sixteen colours, base00 to base0F. Keep them in a local table and pick the theme’s colours from it:

local ito = require("ito")

local base = {
  base03 = ito.rgb(0x707880),
  base05 = ito.rgb(0xc5c8c6),
  base08 = ito.rgb(0xcc6666),
  base0A = ito.rgb(0xf0c674),
  base0D = ito.rgb(0x81a2be),
}

return require("uji.themes.default")({
  name = "dusk",
  colors = {
    text = base.base05,
    muted = base.base03,
    code = base.base0A,
    accent = base.base0D,
    error = base.base08,
    notice = base.base08,
  },
})

Mistakes

A theme with a mistake raises an error that says where it is, such as theme.styles.user: must be an ito.TextStyle, not a table, and the theme in use stays on.

Plugins

The uji-plugins pack holds optional features. Install it once, then call setup for each plugin you want.

uji.pack.add({ "uji-labs/uji-plugins" })

statusline

Deprecated: uji draws its own status line now. The views below still work for custom bars.

setup draws the default bar as uji’s status line: directory, model, reasoning effort, context use, tokens, cache hit rate and turns. Calling it again replaces the bar.

require("statusline").setup()

Segments

Each segment is an ito view that draws nothing while it has nothing to show.

ViewShows
statusline.Cwd()The session’s directory.
statusline.Model()The provider and model.
statusline.Effort()The reasoning effort, while reasoning is on.
statusline.Context()The context use, in the theme’s notice colour from 80%.
statusline.Tokens()The tokens spent.
statusline.Cache()The cache hit rate of the last request.
statusline.Turns()The number of your messages.
statusline.Logo()The uji logo while the session is empty. A screen shows it over the transcript with screen.transcript():overlay(statusline.Logo()).

statusline.Bar(children)

A one-row ito.HStack that puts a separator between neighbouring segments. A segment that draws nothing gets none, and neither does an ito.Spacer, so spacers split the bar into left, centre and right. separator in the props changes the text between segments, " · " by default.

statusline.Default is the bar setup adds.

local ito = require("ito")
local statusline = require("statusline")

local branch = ito.state("")
uji.job.start({
  cmd = { "git", "branch", "--show-current" },
  on_stdout = function(line)
    branch.value = line
  end,
})

local Branch = ito.view(function()
  return branch.value ~= "" and ito.Text(branch.value):foreground(ito.theme().colors.accent)
end)

uji.ui.status(statusline.Bar({ statusline.Cwd(), Branch(), ito.Spacer(), statusline.Context() }))

uji.ui.toolbar({
  ito.ToolbarItem(ito.ToolbarPlacement.keyboard, function()
    return statusline.Bar({ statusline.Model(), ito.Spacer(), statusline.Effort() })
  end),
})

planmode

A read-only mode. The model investigates and writes a plan, then you accept it, keep planning, or leave.

require("planmode").setup({ allow = { "npm test" } })
OptionMeaningDefault
allowCommand prefixes that run without asking while planning.none
confirmfalse skips the accept picker at the end of a turn.true
badgefalse leaves planmode.Badge off the screen, for a bar that shows it itself.true
keysfalse leaves Ctrl+B unbound.true
priorityThe priority of its before_tool hook.10

Commands are /plan and /plan <task>. Ctrl+B toggles plan mode.

planmode.Badge() is a view that says plan while plan mode is on. planmode declares it as a bottom_bar item, and a statusline bar can show it instead:

local ito = require("ito")
local statusline = require("statusline")

require("planmode").setup({ badge = false })

uji.ui.toolbar({
  ito.ToolbarItem(ito.ToolbarPlacement.bottom_bar, function()
    return statusline.Bar({ require("planmode").Badge(), statusline.Cwd(), ito.Spacer(), statusline.Context() })
  end),
})

mcp

Tools from MCP servers, over stdio or HTTP.

require("mcp").setup({
  servers = {
    files = { cmd = { "npx", "-y", "@modelcontextprotocol/server-filesystem", "." } },
    linear = { url = "https://mcp.linear.app/mcp" },
  },
})

A server has cmd and optional cwd, or url and optional token. Its tools are named server__tool, and each call asks you first unless your policy allows it. /mcp add URL connects a server and signs you in when it asks, /mcp remove disconnects one, and /mcp lists them.

telescope

A fuzzy finder.

require("telescope").setup({})
KeyActionDoes
Ctrl+Ptelescope_findOpens a file in your editor.
Ctrl+Rtelescope_historyRefills the input with a past message.
Ctrl+Ftelescope_searchSearches file contents as you type.

editor sets the program that opens files. It defaults to UJI_EDITOR, then VISUAL, then EDITOR. keys = false leaves the keys unbound.

skills

Announces Agent Skills folders to the model.

require("skills").setup({ roots = { "~/.agents/skills", ".agents/skills" } })

roots defaults to ~/.agents/skills, .uji/skills and .agents/skills. /skills lists what it found.

websearch

web_search and web_fetch tools, through one of two services.

require("websearch").setup({ count = 8 })
require("websearch").setup({ backend = "searxng", url = "http://localhost:8888" })

With backend = "exa", the default, both go through Exa’s public search service, so they need no key. The free service is rate limited, though; with a key from Exa in EXA_API_KEY, or in the key option, the limit goes away.

With backend = "searxng", web_search asks your own SearXNG instance, at url or SEARXNG_URL, and web_fetch reads the page itself and turns its HTML into text. SearXNG answers JSON only once it is allowed, under search.formats in its settings.yml:

search:
  formats:
    - html
    - json

Its limiter expects a proxy in front that sets X-Forwarded-For, and blocks requests that arrive without one. For an instance only you use, turn it off with server.limiter: false, or give url the proxy’s address rather than the SearXNG container’s.

OptionMeaningDefault
backendWhere searches go: "exa" or "searxng". Each is a module in websearch/backend/."exa"
urlThe SearXNG instance, for backend = "searxng".SEARXNG_URL
keyAn Exa API key, for backend = "exa".EXA_API_KEY
policyWhether the tools ask before they run: "allow", "ask" or "deny"."allow"
countResults per search.5
charsCharacters of a page that web_fetch returns at most.20000
timeoutSeconds per request.30

subagent

A subagent tool that hands tasks to agents. Each agent runs as a separate uji process with uji run, in a context of its own, and only its final answer comes back.

require("subagent").setup({ concurrency = 2 })
OptionMeaningDefault
policyWhether starting agents asks first: "allow", "ask" or "deny"."allow"
scopeWhere agents come from when the model does not say: "user", "project" or "both"."user"
confirm_projectAsk before running an agent from the project.true
max_tasksThe most tasks one call may run at the same time.8
concurrencyHow many of them run at once.4
outputBytes of each answer kept when several run at once.51200

Agents

An agent is a markdown file. The front matter describes it and the text below is added to its system prompt.

---
name: scout
description: Looks things up in the code and reports back with paths and lines
tools: read_file, run_command
model: anthropic/claude-haiku-4-5
effort: low
---
You are a scout. Find what you were asked for and report it briefly.
FieldMeaning
nameThe agent’s name. The default is the file name.
descriptionRequired. The model reads it to choose an agent.
toolsThe tools the agent gets, separated by commas, with or without brackets. The default is every tool.
modelThe model, written as provider/model. The default is yours.
effortThe reasoning effort. The default is yours.

uji looks for agents in agents/ in your config directory and in each pack. With the project or both scope, it also reads .uji/agents/ in the session’s directory, or in the nearest directory above it that has one. An agent there replaces one of yours with the same name. A project’s agents ask before they run, unless confirm_project is false, because the repository controls them.

The tool

ArgumentsRuns
agent and taskOne task.
tasksA list of { agent, task } that run at the same time.
chainA list of { agent, task } that run in order. {previous} in a task is replaced by the answer of the step before, and a failed step stops the chain.

Each item may also have cwd, the directory it works in. scope picks where agents come from for this call.

An agent’s tool calls run without asking, except the ones your policy denies. Its conversation is saved as a session under yours, which uji resume --id <ID> opens. Interrupting the turn stops every agent it started. The agents themselves do not get the subagent tool.

readonly

Refuses edits in the directories you list, so the model can read them but not change them.

require("readonly").setup({ "~/reference/other-project" })

It also takes one table, setup({ paths = { ... } }).

Examples

Each example is Lua that goes in ~/.config/uji/init.lua or in a file in ~/.config/uji/plugin/.

A tool of your own

Put these tools in ~/.config/uji/plugin/tools.lua, or in init.lua.

A tool that answers at once

run returns the result as a string.

uji.tool.add("branch", {
  description = "Name of the current git branch.",
  parameters = { type = "object", properties = {} },
  policy = "allow",
  display = { label = "Branch" },
  run = function()
    return io.popen("git branch --show-current"):read("*l") or "not a git repository"
  end,
})

A tool that waits on a process

run starts a job and returns job.stop, so an interrupt kills it. The job calls ctx.done when it exits.

uji.tool.add("count_todos", {
  description = "Count TODO comments per file in the working directory.",
  parameters = { type = "object", properties = {} },
  policy = "allow",
  display = { label = "TODOs" },
  run = function(_, ctx)
    local lines = {}
    local job = uji.job.start({
      cmd = { "rg", "--count-matches", "TODO" },
      on_stdout = function(line)
        lines[#lines + 1] = line
        ctx.progress(line)
      end,
      on_exit = function(code)
        if code == 1 then
          ctx.done("no TODO comments")
        else
          ctx.done(table.concat(lines, "\n"))
        end
      end,
    })
    return job.stop
  end,
})

A tool with arguments and a subject

subject returns the URL, so the approval question shows it and the policy matches it.

uji.tool.add("fetch_url", {
  description = "Download a web page and return its body.",
  parameters = {
    type = "object",
    properties = { url = { type = "string", description = "The page to fetch." } },
    required = { "url" },
  },
  subject = function(args)
    return args.url
  end,
  policy = "ask",
  display = { label = "Fetch", question = "Fetch this page?" },
  run = function(args, ctx)
    return uji.http.request({ url = args.url }, function(response, err)
      if not response then
        ctx.done("error: " .. err)
      else
        ctx.done(response.body:sub(1, 20000))
      end
    end)
  end,
})

uji.tool.policy({
  fetch_url = { allow = { "https://docs.rs/*" } },
})

A slash command

/switch lists your git branches in a picker and switches to the one you choose. Alt+G opens it.

uji.command.add("switch", {
  desc = "switch git branch",
  handler = function()
    local branches = {}
    uji.job.start({
      cmd = { "git", "branch", "--format=%(refname:short)" },
      on_stdout = function(line)
        branches[#branches + 1] = line
      end,
      on_exit = function()
        uji.ui.select({ title = "Switch to", items = branches }, function(choice)
          if not choice then
            return
          end
          uji.job.start({
            cmd = { "git", "switch", choice },
            on_exit = function(code)
              uji.notify(code == 0 and ("on " .. choice) or ("git switch failed with " .. code))
              uji.emit("status_changed", {})
            end,
          })
        end)
      end,
    })
  end,
})

uji.keymap.add("normal", "<A-g>", { command = "switch" })

The handler receives the text typed after the command name.

uji.command.add("ask", function(args)
  uji.session.submit("Investigate before changing anything. " .. args)
end)

A footer

A one-line footer with the model on the left and the tokens spent on the right.

require("uji.builtin.defaults")

local ito = require("ito")

uji.ui.toolbar({
  ito.ToolbarItem(ito.ToolbarPlacement.bottom_bar, function()
    local usage = uji.session.usage()
    return ito.HStack({
      ito.Text(uji.model.current().model or "no model"):foreground(ito.Color.cyan),
      ito.Spacer(),
      usage.total > 0 and ito.Text(usage.total .. " tokens"):foreground(ito.Color.gray),
    })
  end),
})

uji draws the footer again whenever the model, the session or the running state changes.

A provider

An OpenAI-compatible endpoint

A LiteLLM proxy on your machine, or any server that speaks the OpenAI chat format.

uji.provider.add({
  id = "litellm",
  name = "LiteLLM",
  api = uji.api.openai(),
  base_url = os.getenv("LITELLM_BASE_URL") or "http://localhost:4000",
  auth_env = { "LITELLM_API_KEY" },
  models = {
    { id = "claude-sonnet-4-5", context = 1000000, output = 64000, reasoning = true },
    { id = "glm-4.6", context = 204800, output = 131072, reasoning = true },
  },
})

An endpoint with its own quirks

Some differences need only an option. This server wants the output limit in max_completion_tokens:

uji.provider.add({
  id = "gateway",
  name = "Gateway",
  api = uji.api.openai({ max_tokens_field = "max_completion_tokens" }),
  base_url = "https://gateway.example.com/v1",
  auth_env = { "GATEWAY_API_KEY" },
  models = { { id = "qwen3-coder", reasoning = true, efforts = { "off", "high" } } },
})

For anything else, make a class from the API and redefine the method that differs. This server turns thinking on and off with enable_thinking:

local Qwen = uji.class(uji.api.openai)

function Qwen:thinking(body, request)
  body.enable_thinking = request.effort ~= "off"
end

uji.provider.add({
  id = "dashscope",
  name = "DashScope",
  api = Qwen(),
  base_url = "https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
  auth_env = { "DASHSCOPE_API_KEY" },
  models = { { id = "qwen3-max", reasoning = true, efforts = { "off", "high" } } },
})

Provider APIs lists the options and methods of each API.

Reading model sizes from the endpoint

A LiteLLM proxy reports each model’s context and output limits at /model/info. This plugin reads them when uji starts and corrects the models the provider lists. It sends back each model whole, with its reasoning and other fields, because uji.provider.add replaces a model with the same id as a whole.

local BASE_URL = os.getenv("LITELLM_BASE_URL") or "http://localhost:4000"

uji.provider.add({
  id = "litellm",
  name = "LiteLLM",
  api = uji.api.openai(),
  base_url = BASE_URL,
  auth_env = { "LITELLM_API_KEY" },
  models = {
    { id = "claude-sonnet-4-5", reasoning = true },
  },
})

local function listed(id)
  for _, provider in ipairs(uji.provider.list()) do
    if provider.id == id then
      local models = {}
      for _, model in ipairs(provider.models) do
        models[model.id] = model
      end
      return models
    end
  end
  return {}
end

uji.http.request({
  url = BASE_URL .. "/model/info",
  headers = { Authorization = "Bearer " .. (os.getenv("LITELLM_API_KEY") or "") },
}, function(response)
  if not response or response.status ~= 200 then
    return
  end
  local ok, info = pcall(uji.json.decode, response.body, { nulls = false })
  if not ok or type(info) ~= "table" or type(info.data) ~= "table" then
    return
  end
  local known, changed = listed("litellm"), {}
  for _, entry in ipairs(info.data) do
    local model = known[entry.model_name]
    local limits = entry.model_info or {}
    if model and (limits.max_input_tokens or limits.max_output_tokens) then
      model.context = limits.max_input_tokens or model.context
      model.output = limits.max_output_tokens or model.output
      changed[#changed + 1] = model
    end
  end
  if #changed > 0 then
    uji.provider.add({ id = "litellm", models = changed })
    uji.emit("status_changed", {})
  end
end)

Changing a built-in provider

With the id of a built-in provider, uji.provider.add changes only the fields you give.

uji.provider.add({ id = "openai", base_url = "https://llm-proxy.internal/v1" })

uji.provider.add({
  id = "anthropic",
  models = { { id = "claude-fable-5-1", context = 1000000, output = 128000, reasoning = true } },
})

An approval rule

Rules in the policy

Read-only git commands and the tests run without asking, and force-pushes are refused.

uji.tool.policy({
  run_command = {
    allow = { "git status", "git diff*", "git log*", "cargo test*" },
    deny = { "/git push.*(--force|-f)/" },
  },
})

A hook for decisions that need code

Refuses git push, and asks before commands that reach the network.

uji.on("before_tool", function(call)
  if call.name ~= "run_command" then
    return nil
  end
  local command = call.arguments.command or ""
  if command:match("^git push") then
    return { deny = "Pushing is my job. Tell me when the branch is ready." }
  end
  if command:match("curl") or command:match("wget") then
    return { ask = "This command reaches the network. Run it?" }
  end
end, { priority = 10 })

The system prompt

Your config can change the instructions that the model gets with every message you send.

Adding project notes

Adds NOTES.md from the working directory to the system prompt on every turn.

uji.context.add("notes", function()
  local file = io.open(uji.session.info().directory .. "/NOTES.md")
  if not file then
    return nil
  end
  local notes = file:read("a")
  file:close()
  return "Project notes from NOTES.md:\n\n" .. notes
end)

A reminder at the end of the turn

Text returned with at = "turn" goes after the conversation instead of into the system prompt.

uji.context.add("reminder", function()
  return { text = "Run the tests before you say you are done.", at = "turn" }
end)

Rewriting the whole prompt

A before_turn hook returns a new system prompt.

uji.on("before_turn", function(turn)
  return turn.system .. "\n\nWrite commit messages in the imperative mood."
end)

To replace the prompt entirely, override the built-in uji.core.prompt module, as Rebuilding uji shows.

Rebuilding uji

Everything uji does, from startup to the screen, is written in Lua in the uji module tree, and you can replace any file in it. A file at lua/uji/<path>.lua in your config directory or in a pack replaces the built-in module uji.<path>. A module that is a folder, such as uji.core.agent, lives in lua/uji/core/agent/init.lua.

A replacement is a whole file. uji loads yours instead of the built-in one, so the easiest start is a copy of the original from the lua/uji folder of the uji source.

For example, ~/.config/uji/lua/uji/core/prompt.lua:

local M = {}

function M.system(env)
  return "You are a careful coding agent. Work in " .. env.directory .. "."
end

return M

Where things live

The tree has three parts. core/ is the engine. api/ is the uji.* table that plugins use. builtin/ is what uji ships on top of the engine, written as plugins are: the providers, request formats, tools, commands and the default screen.

Path in lua/uji/What it does
boot.luaStarts uji. It reads the command line, opens the session and starts the screen.
api/The uji.* functions in the API reference.
core/cli.luaThe command line and uji --help.
core/run.luauji run, one prompt without the screen.
core/paths.luaWhere the config, the data and the session database are.
core/config.luaLoads your config and plugins, and runs /reload.
core/packs.luauji.pack, and finding modules in your config and packs.
core/scaffold.luaThe starter config and the uji-config skill that /setup writes.
core/agent/, core/loop.luaRuns a turn, which sends the conversation, runs tools, compacts and picks a title.
core/prompt.luaThe system prompt.
core/model.lua, core/catalog.lua, core/decision.luaProviders, models, choosing between them, and asking one for decisions.
core/tool.lua, core/system/Registering tools, the tool policy, file access and processes.
core/command.luaRegistering slash commands.
core/store/Sessions and messages in the database.
core/auth/API keys, auth.toml, the optional keychain and subscription sign-in.
core/ui/Draws the screen, with its parts, input line, markdown, keys and theme engine.
core/ui/views/The transcript, the input line, pickers, prompts and the approval question.
core/images.luaAttaching images from files, pasted paths and the clipboard.
core/event.lua, core/task.lua, core/plugin.lua, core/registry.lua, core/class.luaEvents, tasks, plugin ownership and the building blocks the rest is made of.
builtin/providers/The providers /login lists, each with the API it speaks and its own changes to it.
builtin/apis/The Chat Completions, Responses, Anthropic, Gemini and Jev API classes, and the streaming they share.
builtin/tools/read_file, edit_file, write_file, run_command, ask_user, reload_config, job_output and stop_job.
builtin/commands/The built-in slash commands, one file each.
builtin/defaults.luaThe default tool policy and bindings that require("uji.builtin.defaults") loads.
themes/default.luaThe default theme, and the function other themes build on.
sys/require("uji.sys"), a table with a field for each Runtime module, such as fs or json. A field loads its module, uji.sys.fs or uji.sys.json, the first time it is read. uji.* falls back to the same fields for anything api/ does not define.

The Runtime modules are built into the uji program, and a module with the same name replaces any of them, as Native modules describes. Everything built on them, sys/ included, can be replaced too.

Adding a module

uji loads every file in the builtin/commands/, builtin/tools/, builtin/providers/ and api/ folders of lua/uji/, and each file registers itself. A new file such as ~/.config/uji/lua/uji/builtin/commands/hello.lua adds a command without a change to any other file, and the same works in a pack.

The files in builtin/ use only the uji.* API, the same calls a plugin makes.

FolderWhat a file there calls
builtin/commands/uji.command.add(name, spec).
builtin/tools/uji.tool.add(name, spec).
builtin/providers/uji.provider.add(spec), with an api made from a class in builtin/apis/, or from a class of its own.
api/Nothing. It sets its own table on uji, such as uji.session.

Files in a folder load in alphabetical order, so /login lists providers in that order. uji.modules gives the same list uji loads from.

builtin/apis/ holds the API classes. uji loads one the first time something reads uji.api.<name>.

When a replacement takes effect

A replacement is used from the first file uji loads, boot.lua included. The first time a pack that replaces modules is added, uji starts over once while it starts up, so that the pack’s files are used from the beginning. It remembers those packs for later starts.

/reload and /sync restart uji with your current files. The conversation, what you are typing and the screen stay as they are. A turn in progress has to finish, or be interrupted with Esc, before a reload. When the model asks for one with reload_config, uji reloads as that turn ends. Processes that plugins started, such as MCP servers, are started again.

Replacing everything

Copy the whole lua/uji folder of the uji source into ~/.config/uji/lua/uji. Every module then comes from your copy. A file you delete from your copy falls back to the built-in one.

To run a complete tree kept somewhere else, set UJI_RUNTIME to the directory that contains its uji folder. uji then uses none of its built-in files, and replacements in your config and packs still apply on top.

Such a tree needs one module. uji.boot returns the function that uji runs with the command line as the first task. uji stops when no task is left, or after uji.os.exit or uji.os.restart. The modules built into uji stay available to the tree, such as require("uji.sys.fs"), and Native modules describes how to replace them.

If a replacement breaks uji

When uji cannot start, it prints the error and the file it came from. Fix or remove that file, or start uji with --config-dir pointing at another directory.

Available APIs

Every function lives under the global uji table. A function that finishes later takes a callback as its last argument, which receives the result, or nil and an error message. Called without the callback from a slash command, a key binding, a timer or a click handler, it waits and returns the result instead. A function that starts background work returns a function that stops it. Wrong arguments raise an error at the call.

Tools

NameDoes
uji.tool.add(name, spec)Registers a tool the model can call, or replaces the tool with the same name.
uji.tool.display(name, opts)Describes a tool that uji does not run itself, so the transcript and the approval question can name its calls.
uji.tool.remove(name)Removes a tool and returns true if it existed.
uji.tool.list()Returns the names of every registered tool.
uji.tool.disable(names)Turns tools off. The model still sees them, and uji denies any call to them.
uji.tool.enable(names)Turns tools back on after uji.tool.disable.
uji.tool.policy(rules, opts)Sets which tool calls run without asking, which ask first, and which uji refuses.
uji.diff(old, new, path)Compares two texts line by line and returns the change, for a tool result or an approval preview.

Commands

NameDoes
uji.command.add(name, spec)Registers /name, or replaces the command with the same name, built-in or not.
uji.command.remove(name)Removes a command and returns true if it existed.
uji.command.list()Returns the names of every command in alphabetical order.

Keys

NameDoes
uji.keymap.add(mode, key, binding)Binds a key in one mode, replacing what the key did there.
uji.keymap.remove(mode, key)Unbinds a key in one mode, including a default binding.
uji.keymap.reset()Restores the default bindings.
uji.keymap.list()Returns one row per binding, with mode, key, and one of action, command or unbound = true.

Actions

NameDoes
uji.action.add(name, handler)Registers an action.
uji.action.remove(name)Removes an action you added and returns true if it existed.
uji.action.list()Returns the names of every action, built-in and added, in alphabetical order.

Windows, pickers and appearance

NameDoes
uji.ui.toolbar(items)Declares toolbar items on the screen and returns a handle that removes them.
uji.ui.status(content)Draws a view as the status line and returns a handle that puts the built-in line back.
uji.ui.size()Returns the width and height of the terminal.
uji.ui.select(opts, on_done)Shows a list to choose from.
uji.ui.pick(opts, on_done)Shows a fuzzy finder with a preview pane.
uji.ui.prompt(opts, on_done)Asks for a line of text.
uji.ui.confirm(opts, on_done)Asks a yes or no question, including uji’s approval questions.
uji.ui.overlay(content, opts)Shows a view in a box over the screen until you close it.
uji.ui.Markdown(text)A view that draws markdown.
uji.ui.toggle_thinking()Shows or hides the model’s reasoning in the transcript.
uji.ui.exec(cmd)Hides uji, runs a program in the terminal, and comes back when it exits.
uji.ui.open(target)Opens a file or link in the app the system uses for it.
uji.ui.configure(opts)Sets colours and screen behaviour.
uji.ui.theme()Returns the theme in use.
uji.ui.save_theme(name)Keeps a theme for the next time uji starts.

Model context

NameDoes
uji.context.add(name, provide, opts)Registers a function that uji calls at the start of every turn.
uji.context.remove(name)Removes a context function and returns true if it existed.
uji.context.list()Returns the names of the context functions, in the order uji calls them.
uji.context.configure(opts)Sets how long the provider caches the conversation, and when uji compacts.

Events

NameDoes
uji.on(event, handler, opts)Adds a handler for an event and returns the handler’s name.
uji.off(event, name)Removes the handler with that name and returns true if it existed.
uji.emit(event, payload)Runs the handlers of any event with the payload you give.

Session

NameDoes
uji.session.info()Returns a table with the session’s id, title, directory and short_directory.
uji.session.messages()Returns the transcript as a list of tables with type and text.
uji.session.usage()Returns the tokens spent in this session.
uji.session.context()Returns a table with used, the estimated tokens in the conversation, and window, the model’s context size when uji knows it.
uji.session.queue()Returns the messages you typed while the model worked, which uji has not sent yet.
uji.session.state()Returns "working" while a turn runs and "idle" otherwise.
uji.session.elapsed()Returns the seconds since the current turn started, or nil when idle.
uji.session.set_title(title)Renames the session, saves the name, and fires session_titled.
uji.session.submit(text)Sends a message as if you typed it.
uji.session.interrupt()Stops the current turn, or the running ! command.
uji.session.compact()Summarises earlier messages to free context.
uji.session.resume(id)Starts uji again in the session the id names.

Input line

NameDoes
uji.input.get()Returns the text on the input line.
uji.input.set(text)Replaces the text on the input line.
uji.input.append(text)Adds text to the end of the input line.
uji.input.clear()Empties the input line.
uji.input.attach(path)Attaches an image file to the message on the input line.
uji.input.capture(handler)Sends every key press to handler instead of the normal bindings, until uji.input.release runs.
uji.input.release()Returns the keyboard to the normal bindings.

Models

NameDoes
uji.model.current()Returns the provider, model, API root and effort the next turn uses.
uji.model.use(opts)Changes the provider, model, API root or effort, and saves the choice.
uji.model.efforts()Returns the reasoning efforts the current model accepts.
uji.model.decide(opts)Asks a provider how likely it is that each question about a state is yes.

Providers

NameDoes
uji.provider.add(spec)Adds a provider, or merges spec into the provider with the same id.
uji.provider.remove(id)Removes a provider and returns true if it existed.
uji.provider.list()Returns one table per provider with its settings and models.
uji.auth.configure(opts)Chooses between auth.toml and the system keychain for API keys and sign-ins.
uji.auth.authenticated(id)Returns true when uji has a key or sign-in for a provider.
uji.auth.save_key(id, key)Saves an API key for a provider.
uji.auth.login(id, opts, on_done)Signs in to a provider in the browser or with a device code.

Provider APIs

NameDoes
uji.class(parent)Makes a class, optionally from a parent class whose methods it keeps.
uji.api.openai, uji.api.responses, uji.api.anthropic, uji.api.geminiThe API classes a provider’s api is made from.
uji.api.stream.run(spec, reply)Sends a request to a streaming endpoint and reads the events into an answer.

Processes

NameDoes
uji.job.start(opts)Starts a process and returns a job table.
uji.jobs.list()Returns the background jobs.
uji.jobs.stop(id)Stops a running background job.
uji.jobs.show()Opens the jobs list under the input, running ones first.
uji.jobs.configure(opts)Sets whether a finished job wakes the model, how many jobs run at once, and how long they may run.

HTTP

NameDoes
uji.http.request(opts, on_done)Sends an HTTP request and returns a function that cancels it.

Files

NameDoes
uji.fs.read(path, on_done)Reads a whole file.
uji.fs.lines(path, opts, on_done)Reads a range of lines from a text file.
uji.fs.write(path, content, on_done)Writes a file, creating missing directories.
uji.fs.list(path, on_done)Lists a directory.
uji.fs.glob(pattern, on_done)Lists the paths that match a pattern.
uji.fs.join(base, ...)Joins parts into one path.
uji.data.read(name, on_done)Reads a plugin’s file in the data directory.
uji.data.write(name, text, on_done)Writes a plugin’s file in the data directory.
uji.config.files(folder, opts, on_done)Reads the files in a folder of your config, your packs and, if asked, the project.

JSON

NameDoes
uji.json.encode(value)Turns a Lua value into a JSON string.
uji.json.decode(text, opts)Turns a JSON string into a Lua value.
uji.json.array(table)Marks a table as a JSON array, so it encodes as [] even when empty.

Packs

NameDoes
uji.pack.add(specs)Installs and loads packs.
uji.pack.list()Returns every directory uji searches for modules and plugin/ files, starting with your config directory.
uji.pack.update()Pulls every installed git pack and records the new commits in the lock file.

Timers and notices

NameDoes
uji.schedule(callback)Runs callback once the code that called it has finished.
uji.defer(seconds, callback)Runs callback after a delay and returns a function that cancels it.
uji.notify(message, seconds)Shows a notice at the top right of the screen, seconds by default the theme’s limits.flash.

Diagnostics

NameDoes
uji.diagnostics.list(on_done)Returns the errors uji recorded, newest first.

Quitting and reloading

NameDoes
uji.quit()Exits uji.
uji.reload()Restarts uji on the same session with your config read again.

Runtime

NameDoes
uji.task.spawn(fn, ...)Starts a function as a task that runs alongside the rest of uji.
uji.sleep(seconds)Pauses the current task.
uji.task.race(fn, ...)Runs functions at once and returns the first to finish.
uji.task.timeout(seconds, fn)Runs a function with a time limit.
uji.promise()Returns a promise that tasks can wait on.
uji.net.request(opts)Sends an HTTP request and returns the answer.
uji.net.open(opts)Sends an HTTP request and streams the answer.
uji.net.listen(port)Accepts connections on a local port.
uji.proc.spawn(argv, opts)Starts a process.
uji.db.open(path)Opens a SQLite database.
uji.osReads the platform, the environment and the clock.
uji.modules(namespace)Lists the modules inside a namespace.
uji.keychainReads and writes secrets in the system keychain.
uji.clipboardReads and writes the system clipboard, and reads images from it.
uji.regex(pattern)Compiles a regular expression.
uji.glob(pattern, opts)Compiles a glob.
uji.fuzzy(query, items)Ranks strings against a query.
uji.markdown(source)Parses Markdown into events.
uji.width(text)Measures text in terminal columns.
uji.lossy(data)Turns bytes into valid UTF-8.
uji.base64Encodes and decodes base64.
uji.tomlReads and writes TOML.
uji.sha256(data)Hashes data.
uji.random(count)Returns random bytes.
uji.image.fit(data, edge, bytes)Checks an image and fits it to a size and a byte limit.

uji.tool

uji ships seven tools: read_file, edit_file, write_file, run_command, ask_user, which puts a question to you, and job_output and stop_job for background jobs. An eighth, reload_config, is there when uji runs in its config directory, where the model can reload after it changes your config. The functions below add your own, switch tools off and on, and decide which calls need your approval.

uji.tool.add(name, spec)

Registers a tool the model can call, or replaces the tool with the same name.

FieldTypeRequiredMeaning
descriptionstringnoWhat the tool does. The model reads this to decide when to call it.
parameterstablenoA JSON Schema for the arguments, written as a Lua table.
runfunctionyesRuns the call. See below.
resolvefunctionnoReceives the arguments before the policy is checked and returns the ones to use from then on, or nil and an error message, which becomes the result.
subjectstring or functionnoWhat policy rules match against, and what the transcript shows unless display.detail is set. A function receives the arguments and returns a string. The default is the tool’s name.
policystringno"allow", "ask" or "deny". Used when no policy rule matches.
pathbooleannotrue when the subject is a file path, so policy rules match it the way they match the file tools.
display.labelstringnoThe name the transcript shows for a call, such as "Read", followed by the subject or display.detail in brackets. The default is the tool’s name.
display.detailfunctionnoReceives the arguments and returns the text in brackets after the label, in place of the subject. The approval question shows it too.
display.questionstringnoThe title of the approval question.
display.previewfunctionnoReceives the arguments and returns the change the call would make, as uji.diff gives it. The approval question shows it.

run(args, ctx) receives the decoded arguments and a context table. It returns the result in one of three ways:

  • It returns a string, which becomes the result at once.
  • It returns nothing and calls ctx.done(text) later.
  • It returns a function and calls ctx.done(text) later. uji calls that function to stop the work if you interrupt the turn.

A result may also be a table, in any of the three ways. Only text is required.

FieldTypeMeaning
textstringThe result the model reads.
imageslistImages in the format the provider API request describes. The model gets them with the text.
difftableA change to a file, as uji.diff gives it. The transcript draws it in place of the text.
summarystringA short line, such as "Read 40 lines", that the transcript shows in place of the text until you click it.

The model never sees diff or summary, and after_tool handlers see only the text. An image with no supported media_type, no data or more than 5 MB is left out, and a note at the end of the text says so.

ctx.progress(line) shows a line under the running tool while it works.

Raises an error when run is missing, policy is not one of the three values, or subject is neither a string nor a function.

uji.tool.add("branch", {
  description = "Name of the current git branch.",
  parameters = { type = "object", properties = {} },
  policy = "allow",
  display = { label = "Branch", question = "Read the current branch?" },
  run = function()
    return io.popen("git branch --show-current"):read("*l")
  end,
})

uji.tool.display(name, opts)

Describes a tool that uji does not run itself, such as one that a provider’s own loop runs, so the transcript and the approval question can name its calls. The model is never offered it. opts takes label, subject, question, preview and detail, as uji.tool.add does.

uji.tool.display("Edit", {
  label = "Update",
  subject = function(args)
    return args.file_path
  end,
})

uji.tool.remove(name)

Removes a tool and returns true if it existed.

uji.tool.remove("write_file")

uji.tool.list()

Returns the names of every registered tool.

for _, name in ipairs(uji.tool.list()) do
  uji.notify(name)
end

uji.tool.disable(names)

Turns tools off. The model still sees them, and uji denies any call to them. Plan mode uses this to take away the editing tools.

uji.tool.disable({ "edit_file", "write_file" })

uji.tool.enable(names)

Turns tools back on after uji.tool.disable.

uji.tool.enable({ "edit_file", "write_file" })

uji.tool.policy(rules, opts)

Sets which tool calls run without asking, which ask first, and which uji refuses. rules maps a tool name to a table with allow, ask and deny lists and an optional default. A top-level default applies to every tool.

uji.tool.policy({
  default = "ask",
  run_command = {
    allow = { "git status", "git diff *", "cargo test*" },
    deny = { "/^rm\\s+-rf/" },
  },
})

Each rule matches the tool’s subject: the path for the file tools, the command line for run_command, the job’s name for job_output and stop_job, and the subject of a tool you add. A job’s name follows the theme’s text.job, such as job 3. A rule is an exact string, a glob when it contains *, ? or [, or a regular expression between slashes. For the file tools, a rule also matches the file’s full path, and a rule that starts with ~/ starts at your home folder. A rule can also be a table with pattern and message, and the model reads message when that rule refuses a call.

uji checks deny rules first, then allow, then ask, and uses the first match. With no match, it uses the tool’s default, then the top-level default, then the policy the tool declares, then ask. read_file, job_output and stop_job declare allow and the other built-in tools declare ask. A top-level default = "allow" runs every tool without asking, except the calls a rule matches.

uji.tool.policy({
  default = "allow",
  run_command = { deny = { "/^\\s*rm\\s+-rf/" } },
})

Rules may name a tool uji does not register, such as a tool of a provider that runs its own loop. They match the subject that loop passes to agent:approve.

Each call replaces the tools it names and keeps the others. With opts.name, the rules go in a separate set under that name, which calls without it, or with another name, leave alone. uji checks the deny rules of every set first, and when sets give different defaults, the strictest wins.

uji.tool.policy({
  edit_file = {
    deny = { { pattern = "~/reference/**", message = "~/reference is read-only" } },
  },
}, { name = "reference" })

A before_tool hook runs before the policy and overrides it.

uji.diff(old, new, path)

Compares two texts line by line and returns the change as a table, for a result’s diff or a display.preview. path names the file, and its extension, or its name when it has none, picks the colours for the code. The table has path and changes. Each change is a list of lines: the lines that changed and, around them, up to the theme’s limits.diff_context lines that did not. A line has:

FieldMeaning
kind"context", "removed" or "added".
old, newThe line’s number before and after the change. A removed line has no new, and an added line has no old.
partsThe line’s text in pieces, each { text, changed }, where changed marks the words that differ.

Raises an error when old or new is not a string.

uji.tool.add("upcase", {
  description = "Uppercase a file.",
  parameters = { type = "object", properties = { path = { type = "string" } } },
  run = function(args)
    local before = uji.fs.read(args.path)
    local after = before:upper()
    uji.fs.write(args.path, after)
    return { text = "uppercased " .. args.path, diff = uji.diff(before, after, args.path) }
  end,
})

uji.command

These functions manage the slash commands. The built-in ones, listed in Slash commands, are added the same way, so a plugin can replace or remove any of them.

uji.command.add(name, spec)

Registers /name, or replaces the command with the same name, built-in or not. spec is a function, or a table with these fields.

FieldTypeRequiredMeaning
handlerfunctionyesRuns the command. It receives the text typed after the name.
descstringnoThe description in the suggestion list.

Raises an error when spec is neither a function nor a table with a handler.

uji.command.add("standup", {
  desc = "summarise yesterday's commits",
  handler = function(args)
    uji.session.submit("Summarise the commits since yesterday. " .. args)
  end,
})

This replaces /help with a notice that names every command:

uji.command.add("help", {
  desc = "list commands",
  handler = function()
    uji.notify(table.concat(uji.command.list(), "  "))
  end,
})

uji.command.remove(name)

Removes a command and returns true if it existed.

uji.command.remove("standup")

uji.command.list()

Returns the names of every command, built-in and added, in alphabetical order.

local names = uji.command.list()

uji.keymap

A binding belongs to one of six modes.

ModeWhere it applies
normalThe input line.
suggestThe command list that opens when you type /.
selectPickers and lists.
promptText prompts.
confirmThe approval question.
overlayAn overlay on top.

A key is a single character such as "q", or a chord in angle brackets. <C-x> is Ctrl, <A-x> or <M-x> is Alt, <S-x> is Shift, and they combine, as in <C-A-x>. The named keys are CR, Esc, BS, Del, Tab, S-Tab, Left, Right, Up, Down, Home, End, PageUp, PageDown, Insert, Space, lt for <, gt for >, and F1 to F12.

uji.keymap.add(mode, key, binding)

Binds a key in one mode, replacing what the key did there.

ArgumentTypeMeaning
modestringOne of the six modes.
keystringA key or chord.
bindingstring, table or functionAn action name from the list below, { command = "name" } to run a slash command, or a function.

Raises an error for an unknown mode, a key uji cannot parse, or a binding of another type.

uji.keymap.add("normal", "<C-p>", { command = "models" })
uji.keymap.add("normal", "<C-l>", "clear_input")
uji.keymap.add("normal", "<A-i>", function()
  uji.session.interrupt()
end)

uji.keymap.remove(mode, key)

Unbinds a key in one mode, including a default binding.

uji.keymap.remove("normal", "<C-t>")

uji.keymap.reset()

Restores the default bindings.

uji.keymap.reset()

uji.keymap.list()

Returns one row per binding, with mode, key, and one of action, command or unbound = true.

for _, row in ipairs(uji.keymap.list()) do
  if row.command then
    uji.notify(row.key .. " runs /" .. row.command)
  end
end

Default bindings

KeysActionModes
Ctrl+Cquitall
Ctrl+A, Ctrl+Ecursor_start, cursor_endnormal, suggest, prompt, select
Ctrl+B, Ctrl+Fcursor_left, cursor_rightnormal, suggest, prompt, select
Alt+B, Alt+Fword_left, word_rightnormal, suggest, prompt, select
Ctrl+Hbackspacenormal, suggest, prompt, select
Ctrl+Ddelete_forwardnormal, suggest, prompt, select
Ctrl+W, Alt+Backspacedelete_word_backnormal, suggest, prompt, select
Alt+Ddelete_word_forwardnormal, suggest, prompt, select
Ctrl+U, Ctrl+Kdelete_to_start, delete_to_endnormal, suggest, prompt, select
Ctrl+Yyanknormal, suggest, prompt, select
Ctrl+Ttransposenormal, suggest, prompt, select
Ctrl+P, Ctrl+Nhistory_prev, history_nextnormal
Ctrl+P, Ctrl+Nmodal_up, modal_downselect, suggest, confirm
Ctrl+Gmodal_cancelselect, suggest, confirm
Shift+Enter, Alt+Enter, Ctrl+Jinsert_newlinenormal
Ctrl+Vpaste_imagenormal
Ctrl+Zbackgroundnormal

Enter, Esc, Tab, the arrow keys, and y and n in the approval question work without a binding. A binding on one of these keys overrides it.

Actions

nothing, quit, interrupt, background, toggle_thinking, submit, clear_input, backspace, delete_forward, delete_word_back, delete_word_forward, delete_to_start, delete_to_end, yank, paste_image, transpose, insert_newline, cursor_left, cursor_right, cursor_start, cursor_end, word_left, word_right, scroll_up, scroll_down, page_up, page_down, scroll_top, scroll_bottom, history_prev, history_next, modal_up, modal_down, modal_accept, modal_cancel, suggest_complete, confirm_allow, confirm_deny, confirm_toggle.

uji.action.add adds your own.

uji.action

Actions are named functions that keys can run. uji has built-in actions, listed in Keys, and you can add your own.

uji.action.add(name, handler)

Registers an action. A key bound to name then runs handler with no arguments. Raises an error when name belongs to a built-in action.

uji.action.add("insert_date", function()
  uji.input.append(os.date("%Y-%m-%d"))
end)
uji.keymap.add("normal", "<A-d>", "insert_date")

uji.action.remove(name)

Removes an action you added and returns true if it existed.

uji.action.remove("insert_date")

uji.action.list()

Returns the names of every action, built-in and added, in alphabetical order.

local actions = uji.action.list()

uji.ui

uji.ui.toolbar(items)

Declares toolbar items on uji’s screen and gives back a handle. items is a list of ito.ToolbarItem, and each one names the section it belongs in. The theme’s screen decides where each section sits. The default screen shows them like this:

PlacementWhere
ito.ToolbarPlacement.top_bar_leadingThe left end of the top row.
ito.ToolbarPlacement.top_bar_trailingThe right end of the top row.
ito.ToolbarPlacement.keyboardDirectly above the input line.
ito.ToolbarPlacement.bottom_barUnder the input line, at the bottom of the screen.

Items in one section stack in the order they were declared. A section with no items takes no room.

An item draws again when something it reads changes: its state, or what it reads through uji.session and uji.model.

HandleMeaning
handle:remove()Takes the items off the screen, and returns true if they were on it.

Raises an error when items is not a list of ito.ToolbarItem. An item that raises an error draws nothing, and uji records why once, where /diagnostics shows it.

local ito = require("ito")

local branch = ito.state("")
uji.job.start({
  cmd = { "git", "branch", "--show-current" },
  on_stdout = function(line)
    branch.value = line
  end,
})

uji.ui.toolbar({
  ito.ToolbarItem(ito.ToolbarPlacement.keyboard, function()
    return ito.Text(branch.value):foreground(ito.Color.green):align(ito.Alignment.trailing)
  end),
})

The branch name sits at the right end of the row above the input, and it redraws when the job sets branch.value, as State describes.

uji.ui.status(content)

Draws content as uji’s status line and gives back a handle. content is an ito view or a function that returns one. Bottom bar toolbar items draw under it.

HandleMeaning
handle:remove()Puts uji’s status line back, and returns true if content was shown.

Raises an error when content is neither a view nor a function.

local bar = uji.ui.status(function()
  return ito.Text(uji.session.info().short_directory)
end)
bar:remove()

uji.ui.size()

Returns the width and height of the terminal in cells, or nothing when the screen is not open, as in uji run.

local width, height = uji.ui.size()

uji.ui.select(opts, on_done)

Shows a list to choose from. on_done receives the chosen item, or nil if you cancel. Without on_done, the call waits and returns the chosen item.

OptionTypeMeaning
titlestringThe title.
itemslistThe items to choose from: strings, or any values when label is given.
labelfunctionReceives an item and returns the text to show for it. on_done still receives the item itself.
currentanyThe item in use. The list opens on it and labels it with the theme’s text.current.
uji.ui.select({ title = "Branch", items = { "main", "dev" }, current = "main" }, function(choice)
  if choice then
    uji.notify("picked " .. choice)
  end
end)

uji.ui.pick(opts, on_done)

Shows a fuzzy finder with a preview pane. on_done receives the chosen item, or nil if you cancel. Without on_done, the call waits and returns the chosen item.

OptionTypeMeaning
titlestringThe title.
itemslistThe items to filter: strings, or any values when label is given.
labelfunctionReceives an item and returns the text to show and filter on. preview and on_done still receive the item itself.
currentanyThe item in use. The list opens on it and labels it with the theme’s text.current.
previewfunctionReceives the highlighted item and returns lines to show. Without it, an item like path:line: shows that part of the file.
on_queryfunctionMakes the list live. Receives the query each time typing pauses, and a show(items) function that replaces the list.
uji.ui.pick({
  title = "Search",
  on_query = function(query, show)
    local hits = {}
    uji.job.start({
      cmd = { "rg", "--line-number", "--no-heading", query },
      on_stdout = function(line)
        hits[#hits + 1] = line
      end,
      on_exit = function()
        show(hits)
      end,
    })
  end,
}, function(choice)
  if choice then
    uji.notify(choice)
  end
end)

uji.ui.prompt(opts, on_done)

Asks for a line of text. opts.title is the question, opts.value fills the line, and opts.hidden = true masks the input. on_done receives the text, or nil if you cancel. Without on_done, the call waits and returns the text.

uji.ui.prompt({ title = "Commit message" }, function(message)
  if message and message ~= "" then
    uji.session.submit("Commit the staged changes with the message: " .. message)
  end
end)

uji.ui.confirm(opts, on_done)

Asks a yes or no question and gives true for yes and false for no. uji asks its approval questions through this function, so a plugin that replaces uji.ui.confirm answers them, or shows them its own way.

FieldMeaning
titleThe question.
bodyText under the question, such as the command a tool wants to run.
timeoutSeconds to wait. When they pass, the question closes and gives nil.
local yes = uji.ui.confirm({ title = "Delete the build folder?" })

This replacement rings the terminal bell before each question, then asks it the usual way:

local ask = uji.ui.confirm
uji.ui.confirm = function(request)
  io.stdout:write("\a")
  return ask(request)
end

uji.ui.overlay(content, opts)

Shows content, a function that returns a view, in a box over the middle of the screen, and returns a handle. Esc closes it, and so does Enter when no control in it uses the key.

OptionMeaningDefault
floatfalse shows the box with the other pickers, above the input line on the default screen. A screen with no place for pickers floats it anyway.true
HandleMeaning
handle:close(value)Closes the overlay and gives value to wait.
handle:wait()Waits until the overlay closes, then returns the value close gave, or nil after Esc or Enter.

Raises an error when content is not a function.

Overlays, pickers, prompts and approvals stack. Opening one keeps the ones already open, and closing it shows the one under it again. Only the one on top gets the keys, so a focused control on the screen or in a lower overlay waits until the top one closes. The command suggestions are the exception: they close when anything else opens.

The content can declare its own toolbar items with :toolbar. Items placed at top_bar_leading and top_bar_trailing show at the top of the box, and items placed at bottom_bar show at its bottom.

local ito = require("ito")

uji.command.add("commands", {
  desc = "list every command",
  handler = function()
    uji.ui.overlay(function()
      local rows = {}
      for _, name in ipairs(uji.command.list()) do
        rows[#rows + 1] = ito.Text("/" .. name)
      end
      return ito.VStack(rows):padding({ horizontal = 1 }):border(ito.theme().borders.rounded):title("Commands")
    end)
  end,
})

Controls has an overlay with a text field that returns what you type.

uji.ui.Markdown(text)

A view that draws text as markdown, the way the transcript draws replies.

local ito = require("ito")

uji.ui.overlay(function()
  return uji.ui.Markdown("# Release\n\n- tag `v0.4.0`\n- push the tag"):padding(1):border(ito.theme().borders.rounded)
end)

Raises an error when text is not a string.

uji.ui.toggle_thinking()

Shows the model’s reasoning in the transcript, or hides it again, and says which in a notice. /thinking calls this.

uji.keymap.add("normal", "<C-t>", function()
  uji.ui.toggle_thinking()
end)

uji.ui.exec(cmd)

Hides uji, runs a program in the terminal, and comes back when it exits. cmd is a shell command, or a list of the program and its arguments.

uji.ui.exec("git log --oneline | less")

uji.ui.open(target)

Opens target, a file or a link, in the app the system uses for it, such as the browser for a web address, and returns at once. A relative path starts at the working directory. Raises an error when target is not a string or is empty.

uji.ui.open("https://github.com/uji-labs/uji")

uji.ui.configure(opts)

Sets the theme and screen behaviour. Each call changes only the keys it names. Raises an error for an unknown key or a theme with a mistake, and keeps the theme in use.

local ito = require("ito")

uji.ui.configure({
  theme = require("uji.themes.default")({
    colors = { accent = ito.rgb(0xc65036), user_bg = ito.rgb(0x2b2b2b) },
  }),
  show_thinking = true,
})
KeyMeaningDefault
themeA theme name or a theme table. See Themes."default"
show_thinkingShow the model’s reasoning. /thinking toggles it.false
suggest.enabledShow command suggestions when you type /.true

The cursor, the spinner, the size of the suggestion list and the words of an approval belong to the theme, under styles, symbols, limits and text, as Themes describes.

uji.ui.theme()

Returns the theme in use: its name, or the table you gave uji.ui.configure.

local before = uji.ui.theme()
uji.ui.configure({ theme = "harbor" })
uji.ui.configure({ theme = before })

uji.ui.save_theme(name)

Keeps name as your theme for the next time uji starts. It doesn’t change the theme in use, so call uji.ui.configure for that.

uji.ui.configure({ theme = "harbor" })
uji.ui.save_theme("harbor")

uji puts the saved theme on before it runs your config, so a theme your config sets with uji.ui.configure still wins. When the saved theme no longer loads, for example after you remove the pack it came from, uji shows a notice and starts without it.

Raises an error when name is empty or not a string.

uji.context

These functions control what the model sees besides the conversation. They add your own lines to each turn and decide when uji compacts old messages.

uji.context.add(name, provide, opts)

Registers a function that uji calls at the start of every turn. What it returns decides where the text goes.

ReturnEffect
a stringuji appends it to the system prompt.
{ text = "...", at = "turn" }uji adds the text after your message and keeps it in the conversation. The transcript does not show it.
niluji adds nothing this turn.

Text added with at = "turn" stays in the conversation. When it stops being true, return a line that says so once, such as Plan mode is off. Return text that changes between turns this way, not as a string. When the system prompt changes, the provider cannot reuse its cache for the conversation.

opts.priority orders the functions, lowest first. The default is 50. A function with the same name replaces the earlier one.

uji.context.add("branch", function()
  local branch = io.popen("git branch --show-current"):read("*l")
  if branch and branch ~= "" then
    return "The current git branch is " .. branch .. "."
  end
end, { priority = 20 })

uji.context.remove(name)

Removes a context function and returns true if it existed.

uji.context.remove("branch")

uji.context.list()

Returns the names of the context functions, in the order uji calls them.

local names = uji.context.list()

uji.context.configure(opts)

Sets how long the provider caches the conversation, and when uji compacts. When the conversation grows past the model’s context window minus a reserve, uji summarises older messages before the next turn.

KeyMeaningDefault
cacheHow long the provider keeps the conversation cached between turns. "off", "short" for 5 minutes, or "long" for 1 hour. A cache write costs more with "long", and the cache survives longer pauses. It applies to models with cache = true in uji.provider.add."short"
compaction.enabledCompact automatically. /compact works either way.true
compaction.reserveTokens to keep free for the reply.the model’s output limit, or 20,000 when unknown, at most a quarter of the window
compaction.keep_recentTokens of recent messages to keep word for word.20000

Raises an error for an unknown key or an unknown cache value.

uji.context.configure({
  cache = "long",
  compaction = { keep_recent = 40000 },
})

Events

Handlers run lowest priority first. For the events under Hooks, uji uses what the handlers return.

uji.on("tool_started", function(event)
  uji.notify("running " .. event.name)
end)

Every payload also has an event field that holds the event’s name.

uji.on(event, handler, opts)

Adds a handler for an event and returns the handler’s name.

ArgumentTypeRequiredMeaning
eventstringyesThe event name.
handlerfunctionyesReceives the payload table.
opts.priorityintegernoLower runs first. The default is 50.
opts.namestringnoA name for the handler. A handler with the same name replaces this one. uji picks a name when you leave it out.
uji.on("turn_finished", function()
  uji.notify("done")
end, { name = "notify-done", priority = 90 })

uji.off(event, name)

Removes the handler with that name and returns true if it existed.

local name = uji.on("turn_finished", function() end)
uji.off("turn_finished", name)

uji.emit(event, payload)

Runs the handlers of any event with the payload you give. Plugins use it for events of their own, and to redraw the screen through status_changed.

uji.emit("status_changed", {})

Notifications

uji ignores what these handlers return.

session_created

A new session started. The payload has session_id.

session_resumed

You resumed a saved session. The payload has session_id.

session_titled

The session got a title. The payload has title.

session_compacted

uji summarised earlier messages to free context. The payload has count, the number of messages it folded into the summary.

message_submitted

You sent a message. The payload has text.

message_appended

A message joined the transcript. The payload has type and text. The type is one of user, assistant, tool, system, shell, error, compaction and context.

queue_changed

The queue of messages you typed while the model worked changed. The payload has count.

shell_started

A ! command started. The payload has command.

shell_finished

A ! command finished. The payload has command and code, its exit code.

tool_started

A tool call passed approval and started. The payload has name.

turn_finished

The model finished its turn, or you interrupted it.

model_changed

The provider or model changed. The payload has provider and model.

status_changed

The running state, the model or the queue changed, and uji draws a new frame.

before_quit

uji is about to exit.

Hooks

before_turn

Runs before each turn. The payload has text, the message you sent, and system, the system prompt. Return a string to replace the system prompt. Each handler receives the prompt as the previous handler left it.

uji.on("before_turn", function(turn)
  return turn.system .. "\n\nAnswer in British English."
end)

before_tool

Runs before each tool call, before the tool policy. The payload has name and arguments. The first handler to return a decision wins, and uji then skips the policy. Return nil to leave the decision to the next handler.

ReturnEffect
{ allow = true }Run the tool without asking.
{ deny = "reason" }Refuse the call. The model sees the reason.
{ ask = true }Ask you before running it.
{ ask = "question" }Ask you, with your own question as the title.
uji.on("before_tool", function(call)
  if call.name == "run_command" and call.arguments.command:match("^git push") then
    return { deny = "Pushing is my job." }
  end
end, { priority = 10 })

after_tool

Runs after each tool call, before the result reaches the model. The payload has name and content. Return a string to replace the result. Each handler receives the result as the previous handler left it.

uji.on("after_tool", function(result)
  return (result.content:gsub("sk%-%w+", "[redacted]"))
end)

render_message

Runs when uji draws a block of the transcript. The payload has type, text and width, the columns the transcript has, and also name for tool results and tool_calls for assistant messages. Besides the message types, type can be pending, thinking or queued. Return a view to draw instead of the default. The first handler to return a view wins, and a handler that returns something else is skipped with a notice.

local ito = require("ito")

uji.on("render_message", function(block)
  if block.type == "tool" and block.name == "todo" then
    return ito.Text("  task list updated"):style(ito.theme().styles.muted)
  end
end)

uji.session

These functions read the open conversation, and can post to it, rename it, compact it or stop the running turn.

uji.session.info()

Returns a table with the session’s id, title and directory, and short_directory, the directory with your home folder written as ~.

local here = uji.session.info().directory

uji.session.messages()

Returns the transcript as a list of tables with type and text, and tool results also carry the tool’s name.

local count = 0
for _, message in ipairs(uji.session.messages()) do
  if message.type == "user" then
    count = count + 1
  end
end

uji.session.usage()

Counts the tokens spent in this session. The table it gives has input, output, cache_read, cache_write and total, plus last, a table of the same fields for the latest request, and requests, the number of requests so far.

local usage = uji.session.usage()
local line = string.format("%d tokens over %d requests", usage.total, usage.requests)

uji.session.context()

Returns a table with used, the tokens the conversation takes up, window, the model’s context size when uji knows it, and usable, the tokens the conversation may use before uji compacts it. used is what the provider counted for its last reply plus an estimate of the messages after it, from the last compaction on, or the estimate of those messages when that is larger.

local context = uji.session.context()
if context.usable then
  uji.notify(string.format("%d%% of context used", context.used * 100 // context.usable))
end

uji.session.queue()

Lists the messages you typed while the model worked that uji has not sent yet.

local waiting = #uji.session.queue()

uji.session.state()

Gives "working" during a turn, and "idle" otherwise.

local busy = uji.session.state() == "working"

uji.session.elapsed()

Counts the seconds since the current turn started. When idle, the result is nil.

local seconds = math.floor(uji.session.elapsed() or 0)

uji.session.set_title(title)

Renames the session, saves the name, and fires session_titled. An empty title raises an error.

uji.session.set_title("fix the flaky login test")

uji.session.submit(text)

Sends a message as if you typed it. While the model works, uji queues it until the turn ends. Empty text raises an error.

uji.session.submit("Run the tests and fix what fails.")

uji.session.interrupt()

Stops the current turn, or the running ! command.

uji.session.interrupt()

uji.session.compact()

Starts summarising the earlier messages to free context, the way /compact does, and returns true. It returns false and the reason when a turn is running, when there is nothing to compact yet, or when the provider runs its own loop and keeps its own context. uji fires session_compacted when the summary is saved.

local started, reason = uji.session.compact()
if not started then
  uji.notify(reason)
end

uji.session.list(opts)

Returns the stored sessions, newest first, as a list of tables with id, title, directory and updated (milliseconds since the Unix epoch). Sessions saved under another one with uji run --parent are not listed. opts is optional, and without directory the list covers every directory.

OptionTypeMeaning
directorystringList only the sessions started in this directory.
local here = uji.session.info().directory
for _, session in ipairs(uji.session.list({ directory = here })) do
  uji.notify(session.title)
end

uji.session.delete(id)

Deletes a stored session and the sessions saved under it, and returns true. It returns nil and a message when the id is not a session id, when no session has that id, or when deleting it would delete the session open in this uji. Anything other than a string raises an error.

local ok, err = uji.session.delete(id)
if not ok then
  uji.notify(err)
end

uji.session.resume(id)

Opens another session: uji starts again in the session id names, the way uji resume --id does, and leaves this one. It returns true, or nil and a message when the id is not a session id, when no session has that id, when it is the session already open, or while a turn is running. Anything other than a string raises an error. /list and /resume are built on it.

uji.session.resume(id)

uji.input

These functions read and change what you have typed, and can take over the keyboard.

uji.input.get()

Returns the text on the input line.

local draft = uji.input.get()

uji.input.set(text)

Replaces the text on the input line and puts the cursor at the end. Text such as /models opens the command list, as typing it would.

uji.input.set("/models")

uji.input.append(text)

Adds text at the end, with the cursor after it.

uji.input.append(" and add a test")

uji.input.clear()

Empties the input line.

uji.input.clear()

uji.input.attach(path)

Attaches the image at path to the message on the input line and adds its [image #n] marker, then gives true, or nil and an error message when the file is not a PNG, JPEG, GIF or WebP image. Relative paths start at the session’s directory.

uji.input.attach("screenshots/login.png")

uji.input.capture(handler)

Sends every key press to handler instead of the normal bindings, until uji.input.release runs. The handler receives a table with key, such as "<C-x>", char for a printable key, and ctrl, alt and shift. uji releases the capture if the handler raises an error.

uji.input.capture(function(event)
  if event.key == "<Esc>" then
    uji.input.release()
  end
end)

uji.input.release()

Returns the keyboard to the normal bindings.

uji.input.release()

uji.model

These functions read and change the provider and model that uji sends turns to, the reasoning effort it asks for, and the decisions it asks a provider for. /models, /effort and /login use them.

uji.model.current()

Returns a table that describes what the next turn uses.

FieldMeaning
providerThe provider’s id, or "" before one is set.
nameThe provider’s name, or nil before one is set.
modelThe model id.
base_urlThe API root the request goes to.
effortThe reasoning effort the next turn sends, or nil when the model does not reason.
imagestrue or false when uji knows whether the model takes images, and nil when it does not.
local current = uji.model.current()
uji.notify(current.provider .. "/" .. current.model)

uji.model.use(opts)

Changes the provider, model, API root or effort, saves the choice for the next time uji starts, and fires model_changed.

FieldTypeMeaning
providerstringThe id of the provider to switch to.
modelstringThe model to use. Switching provider without a model picks the one you used last with that provider, or its first model.
base_urlstringAn API root that overrides the provider’s. "" goes back to the provider’s own. Switching provider clears it unless you give one.
effortstringOne of off, minimal, low, medium, high, xhigh and max. uji saves it, and each turn uses the nearest effort the current model accepts, so medium on a model that offers only low and high sends high.

Fields you leave out stay as they are. Raises an error for an unknown provider or effort.

uji.model.use({ provider = "anthropic", model = "claude-sonnet-4-5", effort = "high" })

uji.model.efforts()

Returns the reasoning efforts the current model accepts, from the least thinking to the most, such as { "off", "low", "medium", "high", "xhigh", "max" }. A model that does not reason gives an empty list. The model’s efforts in uji.provider.add set the list, and the provider’s API supplies it for a model without one.

local efforts = uji.model.efforts()

uji.model.decide(opts)

Asks a decision model how likely yes is the answer to each question about one state, from 0 to 1. Returns { probabilities, calibrated }, with a number for each question it could answer, or nil and a { kind, message } failure. uji ships the jev provider, which answers decisions itself and gives calibrated true; every other provider is asked over chat, as the model in use, and gives false.

FieldTypeMeaning
statestring or tableWhat the questions are about. A list of strings joins as paragraphs.
questionstableInstructions per question id, each a string.
providerstringThe provider to ask. The provider in use by default.
modelstringThe model to ask, when the provider answers decisions itself — its first model by default. Over chat, the model in use answers.
timeoutnumberSeconds for the whole answer, including the provider’s own retries.

uji.provider

uji ships built-in providers, and /login and /models offer every one you add here as well.

uji.provider.add(spec)

Adds a provider, or merges spec into the provider with the same id.

FieldTypeMeaning
idstringRequired. The provider’s id.
namestringThe name /login shows. Required for a new provider.
apiobjectThe API the provider speaks, such as uji.api.openai(). Provider APIs lists the built-in ones and how to change them. Required for a new provider.
loopclassRuns the turn instead of uji’s own loop, for a provider that runs the model and the tools itself, such as a coding agent CLI. See Your own loop.
base_urlstringThe API root, such as "https://api.openai.com/v1". Required for a new provider without a loop.
auth_envlist of stringsEnvironment variables that may hold the API key. uji also reads the file <name>_FILE names, and the auth file.
auth_filestringA file that holds the API key alone, read when the names give nothing.
modelslist or functionModel ids, or tables with id, context, output, reasoning, cache, images and efforts. images is true or false when you know whether the model takes images. efforts lists the reasoning efforts the model accepts, from off, minimal, low, medium, high, xhigh and max. Without it, uji asks the provider’s api. A function returns that list, and uji calls it once, the first time it needs the provider’s models. The function may wait, for example on uji.http.request.
context_windowintegerThe context size to assume for a model that does not set one.
oauthtableSubscription sign-in settings. The built-in Anthropic, OpenAI and GitHub Copilot providers show the format.

When the provider exists, each field you give replaces the old one, except models, which merge by id. A model whose id is already listed replaces the old one whole.

Raises an error for an unknown field, for an api without a stream or decision method, for a loop that is not a class with a run method, for models that are neither a list nor a function, for an unknown effort, and for a new provider that lacks name or api, or has neither base_url nor loop.

uji.provider.add({
  id = "litellm",
  name = "LiteLLM",
  api = uji.api.openai(),
  base_url = "http://localhost:4000",
  auth_env = { "LITELLM_API_KEY" },
  models = {
    { id = "claude-sonnet-4-5", context = 200000, output = 64000, reasoning = true },
  },
})

uji.provider.add({ id = "openai", base_url = "https://proxy.example.com/v1" })

uji.provider.add({
  id = "ollama",
  models = function()
    local response = uji.http.request({ url = "http://localhost:11434/api/tags", timeout = 5 })
    local models = {}
    for _, entry in ipairs(uji.json.decode(response.body).models) do
      models[#models + 1] = entry.name
    end
    return models
  end,
})

uji calls the function with the provider when it is the current one, when /models lists it, and before the first request to it. The models it returns merge with the ones the provider already has. When it raises an error, the provider keeps its models, and uji calls it again the next time it needs them.

Your own loop

A provider with a loop runs each turn itself. When you send a message, uji makes a loop with Loop(agent, turn) and calls loop:run() in a task.

turn holds:

FieldMeaning
promptThe message you sent, as a table with text and images.
model, effortThe model and reasoning effort in use.
systemThe system prompt uji built.
messagesThe session so far, in uji’s own format.
toolsuji’s tools.
reasoning, max_output, cacheWhether the model reasons, its output limit and the prompt cache setting.

A loop that keeps its own history and runs its own tools can leave system, messages and tools alone.

run must end the turn with agent:done or agent:failed. When run returns without either, uji fails the turn with loop: the turn ended without an answer, and when it raises, uji fails the turn with loop: and the error.

When you stop the turn, uji first stops the loop’s task, then calls loop:interrupt() if the loop has one. interrupt must return at once, so anything that takes time, such as killing a process that does not quit, goes in uji.defer.

The loop reports back through agent:

CallMeaning
agent:delta(kind, text)Streams a piece of "text" or "reasoning" to the screen.
agent:assistant_step(message)Stores an assistant message with text, tool_calls and reasoning, when the turn goes on after it.
agent:tool_running(call)Names the call that runs now, so an interrupt can say so.
agent:approve(name, arguments, subject)Runs uji’s approval: the tool policy, before_tool handlers and the question on screen. subject is what policy rules match, such as a command line or a path, and defaults to the tool’s own subject or its name. Returns { allow = true, arguments = ... } or { deny = "reason" }.
agent:after_tool(name, content)Runs the after_tool handlers over a result.
agent:tool_result(call, result)Stores a tool message for a call. result is a string, or a table with text, images, diff and summary, the same as a tool’s result.
agent:usage(spent)Adds input, output, cache_read and cache_write tokens to the session.
agent:done(message)Stores the last assistant message and ends the turn.
agent:failed(text)Stores an error message and ends the turn.
agent:queued()Returns true when you sent more messages during the turn.
agent:steer()Stores the next of those messages and returns it, or returns nil. If the loop never calls it, uji sends those messages as new turns once the turn is done.

The provider still needs its api. uji asks it for the session’s title and for the reasoning efforts of models that do not list them. uji does not compact the session of a provider with a loop, since the loop keeps its own context, and /compact says so.

uji.provider.remove(id)

Removes a provider and returns true if it existed.

uji.provider.remove("perplexity")

uji.provider.list()

Returns one table per provider with id, name, api, base_url, auth_env, auth_file, context_window, models, oauth, which is true when the provider offers subscription sign-in, browser_auth, which is true when it offers browser sign-in, api_key, which is true when it accepts an API key, device_auth, which is true when its oauth.device settings support device code sign-in, loop, which is true when the provider runs its own agent loop, state and error. Each model has id, context, output, reasoning, cache, images and efforts.

state is one of the values in uji.provider.STATE:

ValueMeaning
STATE.IDLEThe provider has a models function that uji has not called yet.
STATE.LOADINGThe function is running.
STATE.LOADEDThe models are in. A provider with a plain list starts here.
STATE.FAILEDThe function raised an error, and error holds its message. uji calls it again the next time it needs the models.
for _, provider in ipairs(uji.provider.list()) do
  if provider.base_url:find("localhost", 1, true) then
    uji.notify(provider.name)
  end
end

uji.provider.get(id)

Returns the row for one provider, in the format uji.provider.list() uses, or nil when no provider has that id. It does not load anything.

uji.provider.load(id, on_done)

Calls the provider’s models function if its models are not loaded yet, waits for it, and returns the provider’s row. The row’s state is STATE.LOADED, or STATE.FAILED with error set. With on_done, it returns at once and calls on_done with the row. Raises an error when no provider has that id.

local ollama = uji.provider.load("ollama")
if ollama.state == uji.provider.STATE.FAILED then
  uji.notify("could not list Ollama models: " .. ollama.error)
end

uji.auth

These functions choose where credentials live, save them, and sign in to the providers that offer a subscription.

uji.auth.configure(opts)

Chooses where uji keeps API keys and subscription sign-ins, and which auth file it reads.

FieldTypeMeaning
keychainbooleanWith true, uji saves credentials in the system keychain and looks there first. The default is false.
filestringThe auth file to read. The default is auth.env in the config directory, and UJI_AUTH_FILE wins over this.

Without the keychain, uji keeps credentials in auth.toml in the data directory, readable only by you. Each provider gets a table named by its id, and a provider can also be a plain string, which uji reads as an API key. A keychain that refuses a save sends the credential to auth.toml as well.

Raises an error for an unknown field, and for a keychain that is not a boolean or a file that is not a string.

The auth file

One dotenv file can hold the keys for every provider. For each name in a provider’s auth_env, uji reads it after the environment, the file <name>_FILE names, and the provider’s auth_file; a credential you saved with /login wins over all of them. Both of those files hold the key alone.

The file is auth.env in the config directory, unless uji.auth.configure({ file = … }) or UJI_AUTH_FILE names another. A path may start with ~. Lines are NAME=value:

# comments start with a hash
TYPESAFE_API_KEY=sk-…
OPENROUTER_API_KEY="sk-or-v1-…"

export before a name, one pair of quotes around a value, and a # comment after an unquoted value are all understood. There are no escapes and no variable expansion.

uji.auth.authenticated(id)

Returns true when uji has a saved key or sign-in for the provider id, or finds its key in one of the provider’s auth_env variables. Raises an error for an unknown provider.

if not uji.auth.authenticated("anthropic") then
  uji.notify("run /login to set up Anthropic")
end

uji.auth.save_key(id, key)

Saves an API key for the provider id and returns true, or nil and an error message when the key could not be saved. Raises an error for an unknown provider or an empty key.

local ok, err = uji.auth.save_key("openrouter", os.getenv("MY_OPENROUTER_KEY"))

uji.auth.remove(id)

Deletes the saved key or sign-in of the provider id, from the keychain and from auth.toml. Returns true when it deleted one, false when nothing was saved, or nil and an error message. A key in one of the provider’s auth_env variables stays. Raises an error for an unknown provider.

uji.auth.remove("openrouter")

uji.auth.login(id, opts, on_done)

Signs in to the provider id with its subscription. uji opens your browser, waits for the sign-in to finish, saves it, and gives true, or nil and an error message. A provider without oauth settings gives an error message too. Raises an error for an unknown provider.

opts is optional. Its method is "browser" by default, or "device" for device code sign-in. OpenAI supports both. Device sign-in displays a link and a one-time code, then waits up to 15 minutes. It does not open a browser or bind a local callback port. Both OpenAI sign-in methods save ChatGPT OAuth tokens and refresh them when they expire. Model requests use your ChatGPT subscription; saving an API key instead uses the OpenAI API. Enable device code login in your ChatGPT security settings or workspace permissions first, as described in the OpenAI authentication guide.

The device sign-in panel keeps the link and code visible until sign-in finishes. Escape cancels sign-in and closes the panel.

GitHub Copilot (github-copilot) uses device sign-in by default and does not support browser or API key sign-in.

An unsupported sign-in method for a provider returns nil and an error message. An unknown option or a method other than "browser" or "device" raises an error. With a callback, the function returns a cancellation function.

uji.auth.login("anthropic", function(ok, err)
  uji.notify(ok and "signed in" or "sign-in failed: " .. err)
end)

local cancel = uji.auth.login("openai", { method = "device" }, function(ok, err)
  uji.notify(ok and "signed in" or "sign-in failed: " .. err)
end)

Provider APIs

A provider’s api turns a model call into a request in one HTTP API’s format and streams the answer back. It’s an object with a stream method, or a decision method for a provider that answers decisions, and you set it with the api field of uji.provider.add.

uji ships five API classes under uji.api, and calling a class makes an object.

ClassAPI
uji.api.openaiOpenAI Chat Completions, /chat/completions. Most providers use it.
uji.api.responsesOpenAI Responses, /responses. The OpenAI and xAI providers use it.
uji.api.anthropicAnthropic Messages, /messages.
uji.api.geminiGemini streamGenerateContent.
uji.api.jevTypeSafe’s Jev decision API, /systemone, for the jev provider. It has a decision method and no stream, and asks jev-latest when nothing names another model.

uji.api.<name> loads lua/uji/builtin/apis/<name>.lua, so a file of your own in that folder of your config adds uji.api.<name> too.

uji.provider.add({
  id = "litellm",
  name = "LiteLLM",
  api = uji.api.openai(),
  base_url = "http://localhost:4000",
  auth_env = { "LITELLM_API_KEY" },
  models = { { id = "claude-sonnet-4-5", reasoning = true } },
})

uji.class(parent)

Makes a class from parent, such as uji.api.openai, that keeps the parent’s methods until it defines its own. The next section shows it in use.

Changing an API for one provider

A provider whose API differs in a few places gets a class of its own, made from the closest built-in class with uji.class. It redefines only the methods that differ. This is how the built-in DeepSeek provider turns thinking on and off and sends each reply’s reasoning back:

local OpenAI = uji.api.openai

local DeepSeek = uji.class(OpenAI)

function DeepSeek:efforts()
  return { "off", "low", "high", "max" }
end

function DeepSeek:thinking(body, request)
  body.thinking = { type = request.effort == "off" and "disabled" or "enabled" }
  if request.effort ~= "off" then
    body.reasoning_effort = request.effort
  end
end

function DeepSeek:assistant(item, request)
  local out = OpenAI.assistant(self, item, request)
  out.reasoning_content = item.reasoning or ""
  return out
end

uji.provider.add({
  id = "deepseek",
  name = "DeepSeek",
  api = DeepSeek(),
  base_url = "https://api.deepseek.com",
  models = { { id = "deepseek-v4-pro", reasoning = true } },
})

The OpenAI Chat Completions class

uji.api.openai(opts) makes an object. Each field of opts is set on the object, so these options can be given there or changed in a class of your own.

OptionDefaultMeaning
max_tokens_field"max_tokens"The body field for the output limit, such as "max_completion_tokens". false leaves the limit out.
finish_reasontrueWith false, a stream that ends without a finish_reason still counts as complete.
cache_keyfalseWith true, sends the session id as prompt_cache_key.
tool_result_namefalseWith true, sends the tool’s name with each tool result.
bridge_tool_imagesfalseWith true, puts a short assistant message between tool results and the images they returned. Mistral needs this.

These methods are the ones a provider most often redefines:

MethodDoes
efforts(model)Returns the efforts a model accepts, used when the model does not list its own.
thinking(body, request)Adds the reasoning fields to the request body. The default sends reasoning_effort.
user(item, request), assistant(item, request), tool(item, request)Turn one message into the API’s format.
headers(request)Returns the request headers. The default sends the key as a bearer token.
url(request)Returns the endpoint.
body(request)Builds the whole request body.
reasoning(delta)Returns the reasoning text in a streamed delta. The default reads reasoning_content, reasoning and reasoning_text.

The other classes follow the same shape. The Responses class has the cache_key option, on by default, and a reasoning(request) method that returns the reasoning field. The Anthropic class picks adaptive thinking or a thinking budget from the model id, and the Gemini class picks a thinking level or a budget the same way.

The request

uji calls api:stream(request, reply). The method may return a function that cancels the call. The request has these fields:

  • model, the model id
  • system, the system prompt
  • messages, the conversation in uji’s message format, where a user or tool message may have images, a list of tables with media_type, base64 data, name, width and height
  • tools, a list of name, description and parameters
  • reasoning, true when the model reasons
  • effort, one of the model’s efforts, or nil for the provider’s default
  • max_output, the output token limit
  • cache, one of off, short and long
  • ctx, a table with session, the session the request is for, whose id is the session id. It is empty for a request made outside a session.
  • provider, with id and base_url
  • auth, with key, and oauth for subscription sign-in

An assistant message carries the replay its API returned, described below.

A provider whose api answers decisions is called as api:decision(request) instead, from uji.model.decide. That request has model, state, questions, a table of instructions by question id, timeout, provider and auth, as above. Its answer is a table of answers by question id, each a probability from 0 to 1 or a table with that number in noul, or nil and a failure.

The reply

The reply table has four functions:

  • reply.text(delta) streams answer text.
  • reply.reasoning(delta) streams reasoning text.
  • reply.done(answer) finishes the call. answer has text, and optionally reasoning, tool_calls, usage and replay. Each tool call has id, name and arguments, where arguments is a JSON string, and may have a signature. usage has input, output, cache_read and cache_write.
  • reply.fail(failure) ends the call with an error. failure.kind is "http", with status, message and retry_after, or "auth", with status, or "provider", with message. uji retries http failures with a status of 408, 409, 425, 429 or 5xx, and http failures with no status, such as a dropped connection.

Replay

Some APIs need data from an earlier reply sent back with the conversation, such as Anthropic’s signed thinking blocks or the encrypted reasoning of the Responses API. An API puts that data in answer.replay, and uji saves it on the assistant message. When the API builds a later request, it finds the data in item.replay and sends it back. The built-in classes tag their replay with their name and the model, and send it back only to the same model. A tool call’s signature is saved the same way, and the Gemini class sends it back with the call.

uji.api.stream

uji.api.stream.run(spec, reply) sends a JSON POST to an endpoint that answers with server-sent events, reads the stream into an answer, and ends the call through reply. It returns the answer, or nil and the failure, so a stream method can return what it returns. The built-in classes all use it.

FieldTypeMeaning
urlstringRequired. The endpoint.
headerstableRequest headers. uji adds Content-Type: application/json.
bodytableThe request body, which uji encodes as JSON.
readfunctionRequired. uji calls read(event, parts) with each data: event, decoded from JSON.
finishedfunctionCalled as finished(parts) when the stream ends. It may return a failure.
settlefunctionCalled as settle(parts, calls) once the tool calls are complete. It may return a failure.

read builds the answer on parts:

  • parts:push_text(delta) adds answer text and streams it to the transcript.
  • parts:push_reasoning(delta) does the same for reasoning text.
  • parts:call(index) returns the tool call at index, creating it with an empty id, name and arguments. Set id and name, and append each fragment of JSON to arguments as it arrives. A signature set on it stays with the call.
  • parts:finish() marks the reply as complete. A data: [DONE] line does the same.
  • parts.usage is a table with input, output, cache_read and cache_write, which read sets from what the provider reports.
  • parts.hit_limit = true records that the model stopped at its output limit.
  • parts.failure set to a failure ends the call with it.
  • parts.replay becomes the answer’s replay.
  • parts:has_text() returns true once any answer text has arrived.

uji ends the call with a failure in these cases:

  • The status is not 2xx. A 401 or 403 is an auth failure, and anything else is an http failure with the status, the retry-after seconds and the start of the body. An API that reads its answer without run makes the same failure with uji.api.stream.status_error(response), from a response with status, headers and body.
  • No data arrives for 120 seconds.
  • The stream ends before parts:finish(). A provider that never says it finished can call parts:finish() from finished.
  • A tool call’s arguments are not complete JSON.
  • The model hit its output limit and made no tool calls.
local Plain = uji.class()

function Plain:stream(request, reply)
  local messages = { { role = "system", content = request.system } }
  for _, message in ipairs(request.messages) do
    if message.type == "user" or message.type == "assistant" then
      messages[#messages + 1] = { role = message.type, content = message.text }
    end
  end
  return uji.api.stream.run({
    url = request.provider.base_url .. "/chat/completions",
    headers = { Authorization = "Bearer " .. (request.auth.key or "") },
    body = { model = request.model, messages = messages, stream = true },
    read = function(event, parts)
      local choice = event.choices and event.choices[1]
      if choice and choice.delta and choice.delta.content then
        parts:push_text(choice.delta.content)
      end
      if choice and choice.finish_reason then
        parts.hit_limit = choice.finish_reason == "length"
        parts:finish()
      end
    end,
  }, reply)
end

uji.provider.add({ id = "plain", name = "Plain", api = Plain(), base_url = "http://localhost:8080/v1" })

uji.job

uji.job runs a process in the background and streams its output to Lua.

uji.job.start(opts)

Starts a process and returns a job table.

OptionTypeMeaning
cmdstring or listRequired. A string is a shell command. A list is the program and its arguments.
cwdstringThe directory to run in. The default is uji’s working directory.
timeoutnumberSeconds before uji kills the process.
on_stdoutfunctionReceives each line the process writes to standard output.
on_stderrfunctionReceives each line the process writes to standard error.
on_exitfunctionReceives the exit code. When uji stopped the process, it receives -1 and "timeout" or "stopped".

The job table has three functions:

  • job.send(text) writes a line to the process’s standard input, adding a newline if text lacks one.
  • job.close() closes standard input.
  • job.stop() kills the process and every process it started.

Raises an error when cmd is missing or empty.

local job = uji.job.start({
  cmd = { "git", "status", "--short" },
  on_stdout = function(line)
    uji.notify(line)
  end,
  on_exit = function(code)
    if code ~= 0 then
      uji.notify("git status failed with " .. code)
    end
  end,
})
job.close()

uji.jobs

A command the model runs can keep going in the background while you talk to the model. A command becomes a background job in one of three ways:

  • The model sets run_in_background on run_command, which suits dev servers and watch builds.
  • A command still running at its timeout moves to the background instead of stopping. The timeout is 120 seconds unless the model gives its own. A command that starts with sleep stops at its timeout instead.
  • You press Ctrl+Z while the command runs, and the model’s turn carries on at once.

While jobs run, the status line counts them, and the list under the input stays out of the way until you open it. When a job ends, uji shows a notice and tells the model the exit code and the last lines of output. If no turn is running, uji starts one so the model can react; otherwise the report goes with the next turn. A job that you or the model stop starts no turn.

The model reads a job’s output with the job_output tool and stops it with stop_job. /jobs opens a list under the input, running ones first, with a title that counts them and a hint that names the keys. Tapping the count on the status line opens the same list, and tapping it again closes it; typing or Esc closes it too.

The list shows five jobs at a time and names the rest. It picks the first job: Enter opens its output, ↑ and ↓ pick another, and x stops a running job or drops a finished one. Dropping the last job closes the list.

A background job stops after 30 minutes, or after the timeout the model gives with run_in_background, and never runs longer than two hours. At most 8 jobs run in the background at once. Esc stops the turn and its foreground command, and leaves background jobs running. Quitting, /reload, or closing the terminal stops them all. Stopping a job also stops every process it started, such as the server a dev server command launches.

uji.jobs.list()

Returns one table per background job, oldest first, with these fields:

FieldMeaning
idThe job’s number, which the model uses with job_output and stop_job.
commandThe shell command.
staterunning, finished, stopped or timed out.
codeThe exit code, once the job ends.
statusA short description, such as "running for 42s" or "finished, exit 0".
tailThe last lines of output.

uji.jobs.stop(id)

Stops a running job and returns true. Returns false when no job with that id is running.

uji.jobs.show()

Opens the jobs list under the input, running ones first and then the newest, and picks the first. Running it again closes the list. /jobs runs this, and it notices when there are no jobs at all.

uji.jobs.configure(opts)

OptionMeaningDefault
wakeStart a turn when a job ends and no turn is running.true
maxThe most jobs that run in the background at once.8
limitSeconds a background job may run when the model gives no timeout.1800
uji.jobs.configure({ wake = false, limit = 3600 })

Raises an error for an unknown option, a wake that is not true or false, and a max or limit that is not a number above 0.

uji.http

uji.http.request(opts, on_done)

Sends an HTTP request and returns a function that cancels it. on_done receives a response table with status, headers and body, or nil and an error message. Header names are lower case.

OptionTypeMeaning
urlstringRequired. The URL.
methodstringThe HTTP method. The default is "GET".
headerstableRequest headers, name to value.
bodystringThe request body.
timeoutnumberSeconds before the request fails. The default is 30 for a plain request and none for a streamed one.
on_linefunctionStreams the response. uji calls it with each line of the body as it arrives. Return false for a line that is not progress, such as a keep-alive.
idlenumberFor a streamed request, the seconds without progress before uji gives up. The default is 120.

A non-2xx status still counts as a response. Check status yourself. An invalid URL, method or header raises an error.

uji.http.request({
  url = "https://api.github.com/repos/uji-labs/uji",
  headers = { Accept = "application/vnd.github+json" },
}, function(response, err)
  if not response then
    uji.notify("request failed: " .. err)
  elseif response.status == 200 then
    uji.notify(uji.json.decode(response.body).description)
  end
end)

uji.fs

Reading, writing, listing and globbing go through the same checks as the file tools, and their relative paths start at the working directory.

uji.fs.read(path, on_done)

Reads a whole file. on_done receives the contents, or nil and an error message.

uji.fs.read("Cargo.toml", function(text, err)
  if text then
    uji.notify(#text .. " bytes")
  end
end)

uji.fs.lines(path, opts, on_done)

Reads a range of lines from a text file. It refuses directories and binary files.

OptionTypeMeaning
offsetintegerThe first line to return, counting from 1. The default is 1.
limitintegerThe most lines to return. The default is all of them.
max_lineintegerCuts lines longer than this many bytes.

on_done receives a table with lines, the list of lines, cut, whose keys are the positions of lines that max_line cut, and total, the number of lines in the file.

uji.fs.lines("README.md", { offset = 1, limit = 20 }, function(page, err)
  if page then
    uji.notify(string.format("showing %d of %d lines", #page.lines, page.total))
  end
end)

uji.fs.write(path, content, on_done)

Writes a file, creating missing directories. on_done receives a table whose created field is true when the file did not exist, or nil and an error message.

uji.fs.write("notes/todo.md", "- write the docs\n", function(result, err)
  if result and result.created then
    uji.notify("created notes/todo.md")
  end
end)

uji.fs.list(path, on_done)

Lists a directory. on_done receives a list of tables with name and type, which is "file", "dir", "link" or "other", sorted by name, or nil and an error message.

uji.fs.list("src", function(entries, err)
  if entries then
    uji.notify(#entries .. " entries in src")
  end
end)

uji.fs.glob(pattern, on_done)

Lists the paths that match pattern, in alphabetical order. * stands for any part of a name, ? for one character, [abc] for one of the characters between the brackets, and ** for any number of directories. A relative pattern gives paths relative to the working directory for matches inside it. on_done receives the list, or nil and an error message when the pattern is not valid.

uji.fs.glob("src/**/*.rs", function(found, err)
  if found then
    uji.notify(#found .. " Rust files")
  end
end)

uji.fs.join(base, …)

Joins base and the parts after it into one path, with the separator the system uses.

local projects = uji.fs.join("~", ".claude", "projects")

uji.data

Files a plugin keeps in the data directory, readable only by you.

uji.data.read(name, on_done)

Reads the file name. on_done receives its text, or nil and an error message. Raises an error when name is not a plain file name.

uji.data.read("bookmarks.json", function(text)
  local saved = text and uji.json.decode(text) or {}
  uji.notify(#saved .. " bookmarks")
end)

uji.data.write(name, text, on_done)

Writes text to the file name, replacing what was there. on_done receives true, or nil and an error message. Raises an error when name is not a plain file name or text is not a string.

uji.data.write("bookmarks.json", uji.json.encode({ "notes.md" }))

uji.json

Plugins use these to build request bodies and to read saved files and HTTP answers.

uji.json.encode(value)

Turns a Lua value into a JSON string, where an empty table becomes {} unless uji.json.array marked it. A string that is not valid UTF-8 keeps its valid parts, and each invalid byte sequence becomes U+FFFD. A function, a table that contains itself, or a key that is not a string or a number raises an error.

local body = uji.json.encode({ model = "gpt-4.1", stream = true })

uji.json.decode(text, opts)

Turns a JSON string into a Lua value. A JSON null becomes uji.json.null, so it survives a round trip through uji.json.encode, unless you pass opts.nulls = false, which turns it into nil and drops the key. Invalid JSON raises an error.

local value = uji.json.decode('{"a": 1, "b": null}', { nulls = false })

uji.json.array(table)

Marks a table as a JSON array, so it encodes as [] even when empty, and returns the same table.

local body = uji.json.encode({ tools = uji.json.array({}) })

uji.json.null stands for JSON null.

uji.pack

Packs installed here come from GitHub, any git URL or a local folder, and /sync updates them.

uji.pack.add(specs)

Installs and loads packs. specs is a list, and each entry is one of these:

  • a "user/repo" GitHub shorthand or a git URL
  • a table with the URL or shorthand first, and one of tag, branch or commit
  • a table with url instead of the first entry
  • a table with dir, a local directory that uji never clones

A table may also set name, which defaults to the repository or directory name. uji reports a pack it cannot install as a notice and keeps going. Raises an error when specs is not a list.

uji.pack.add({
  { dir = "~/code/my-plugin" },
})

uji.pack.list()

Returns every directory uji searches for modules and plugin/ files, starting with your config directory.

for _, root in ipairs(uji.pack.list()) do
  uji.notify(root)
end

uji.pack.update()

Pulls every installed git pack and records the new commits in the lock file. /sync does the same and then reloads.

uji.pack.update()

uji.config

uji.config.files(folder, opts, on_done)

Reads the files in folder of your config directory and of each pack, in the order uji.pack.list gives. on_done receives a list of tables with name, the file name, path, the full path, and text, the contents. Folders inside folder are left out. These reads are not limited to the working directory, because the files belong to your config.

OptionTypeMeaning
projectbooleanWith true, also reads .uji/<folder> in the session’s directory, or in the nearest directory above it that has one. Those files come last and have project = true.

Raises an error when folder is empty, absolute or reaches outside with ...

uji.config.files("agents", { project = true }, function(files)
  for _, file in ipairs(files) do
    uji.notify((file.project and "project: " or "") .. file.name)
  end
end)

Timers and notices

Both timers run their function as a task, so it can wait.

uji.schedule(callback)

Runs callback once the code that called it has finished. Called from your config, it runs after uji has loaded the whole config and every plugin.

uji.schedule(function()
  uji.notify("config loaded")
end)

uji.defer(seconds, callback)

Runs callback after a delay and returns a function that cancels it.

local cancel = uji.defer(30, function()
  uji.notify("thirty seconds passed")
end)

uji.notify(message, seconds)

Shows a notice: a line at the top right of the screen that fades on its own. seconds is how long it stays, the theme’s limits.flash by default.

uji.notify("hello from init.lua")
uji.notify("this one is worth reading", 10)

uji.diagnostics

When drawing the screen goes wrong, uji keeps going and records what happened in diagnostics.log in the data directory, instead of showing it in the transcript. That covers:

  • a frame that fails to draw;
  • a screen, view replacement or toolbar item that raises an error;
  • a list or box that fails to open.

Each entry has the time, where the error came from, the error, and the stack of calls when uji has one. An error that repeats is recorded once. Once the file passes one megabyte, uji keeps only the newest half megabyte of it. /diagnostics lists the entries, newest first, with the whole entry in the preview.

uji.diagnostics.list(on_done)

Returns the recorded entries, newest first. Each is a table with time, such as "2026-10-07 02:51:34", source, which is one of render, screen, modal and view, and text, the error followed by its stack of calls. on_done receives the list. Without it, the call waits and returns the list.

for _, entry in ipairs(uji.diagnostics.list()) do
  uji.notify(entry.time .. " " .. entry.source)
end

Quitting and reloading

uji.quit()

Fires before_quit, restores the terminal and exits uji. /quit calls this.

uji.keymap.add("normal", "<C-q>", function()
  uji.quit()
end)

uji.reload()

Restarts uji on the same session, reading your config and plugins again, and keeps the text on the input line. While a turn runs, uji doesn’t restart and says so in a notice. /reload calls this.

uji.keymap.add("normal", "<A-r>", function()
  uji.reload()
end)

ito

ito is the terminal UI library uji draws its screen with, and require("ito") gives it to your config, your plugins and your themes. You build what the screen shows out of views, change how each view looks with modifiers, and keep values between frames with state. uji draws a new frame whenever one of those values changes.

local ito = require("ito")

local Clock = ito.view(function()
  local shown = ito.state(os.date("%H:%M"))
  return ito.HStack({
    ito.Text("uji"):bold(),
    ito.Spacer(),
    ito.Text(shown.value):foreground(ito.Color.cyan),
  }):on_tap(function()
    shown.value = os.date("%H:%M:%S")
  end)
end)

uji.ui.toolbar({ ito.ToolbarItem(ito.ToolbarPlacement.top_bar_leading, Clock) })

This puts a bar at the top of the screen with the time on the right. A click on the bar adds the seconds.

Where views go

PlaceHow
A section of the screenuji.ui.toolbar declares toolbar items for the top bar, the row above the input or the bottom bar.
A box over the screenuji.ui.overlay shows a view until you close it.
A part a theme can replaceAny view made with ito.view. A theme gives its own in views, keyed by the view. See Views.
The whole screenA theme replaces uji.ui.Screen. See The screen.

Pages

PageContents
Viewsito.view, the stacks, text, lines and layouts of your own.
ModifiersBorders, padding, colours, sizes, alignment, overlays and clicks.
StateValues a view keeps between frames, values it hands to the views inside it, and the theme.
ToolbarsItems a plugin puts in a section of the screen, and the sections that show them.
ControlsA text field, a list, a scrolling view and a spinner, and which of them gets the keys.
ImagesA picture in a view, and the viewer that zooms and pans it.
TerminalThe screen and the input uji draws on.

Views

Each one fills a rectangle of the screen. One built from a list skips any false entry in it, so busy and ito.Spinner() shows a spinner only while busy is true. A nil ends the list.

ito.view(body)

Makes a view out of body, a function that takes the view’s props and returns the view to draw. Calling the result with a props table gives a view to place inside another.

local ito = require("ito")

local Branch = ito.view(function(props)
  return ito.Text(props.name):foreground(ito.Color.green)
end)

uji.ui.toolbar({
  ito.ToolbarItem(ito.ToolbarPlacement.bottom_bar, function()
    return Branch({ name = "main" })
  end),
})

A view of your own takes the same modifiers as ito’s views, and they apply to the view its body returns.

A view keeps its state by its place among its siblings. Give it an id with :id, on ito’s views and your own alike, and the state follows the view when the list around it changes order.

ito.view raises an error when body is not a function.

ito.VStack(children)

Stacks children from the top down. A child is as tall as its content, unless it has height, share or grow. The children that grow split the rows the others leave, by their weights.

ito.VStack({
  ito.Text("Build"):bold(),
  ito.Text("3 warnings"):foreground(ito.Color.yellow),
  ito.Spacer(),
  ito.Text("updated just now"):dim(),
})

:spacing(cells) leaves cells blank rows between each child and the next, skipping the hidden ones.

ito.HStack(children)

Places children side by side from the left. A child is as wide as its width, its share, or its text, and one that has grow or no natural width takes a part of the columns the others leave. :spacing(cells) leaves cells blank columns between each child and the next.

ito.HStack({ ito.Text("main"), ito.Spacer(), ito.Text("3 files changed") })
ito.HStack({ ito.Text("enter"):bold(), ito.Text("open") }):spacing(1)

ito.Grid(rows) and ito.GridRow(cells)

Stacks rows like ito.VStack and lines up the cells of each ito.GridRow in columns. A column is as wide as its widest cell, and a column with a cell that has grow takes a part of the columns the others leave. A cell with :align keeps its own size inside its column. When the columns are wider than the grid, the columns with a cell that has :shrink narrow, the widest first, until they fit, and the narrower ones keep their width. A row that is not an ito.GridRow takes the whole width.

ito.Grid({
  ito.GridRow({ ito.Text("9"):align(ito.Alignment.top_trailing), ito.Text("main.lua"):grow() }),
  ito.GridRow({ ito.Text("120"):align(ito.Alignment.top_trailing), ito.Text("README.md"):grow() }),
})

ito.Spacer()

Fills the room the rest of its stack leaves. Whatever follows it sits at the far edge.

ito.Text(text)

Draws text, one row for each line in it. text is a string, or a list of spans, each { text, style }, for text in more than one style. A tab takes four columns. A line too long for the view is cut at its edge unless the text wraps. Text with more rows than its room shows the first ones, and text from ctx:typed shows the rows up to its cursor. These modifiers style the whole text, and a span’s own style goes on top.

ModifierEffect
:foreground(colour)The text colour, an ito.Color.
:bold(), :dim(), :italic(), :underline(), :reverse(), :strikethrough(), :blink()Turns on that attribute.
:style(style)Merges an ito.TextStyle on top of the text’s style so far.
:wrap()Wraps each line to the width the view gets.
:repeating()Repeats the text across and down all the room the view gets, such as a bar beside a column or a rule across a row.
ito.Text("build failed"):foreground(ito.Color.red):bold()
ito.Text("3 files"):style(ito.theme().styles.muted)
ito.HStack({
  ito.Text("│"):repeating():padding({ trailing = 1 }),
  ito.Text({ { "Note", ito.theme().styles.bold }, { " the build is slow on a cold cache" } }):wrap():grow(),
})

ito.Text raises an error when text is neither a string nor a list.

ito.Fold(content, opts)

Shows content up to opts.rows rows. When content is taller, it shows the first opts.rows rows and, under them, the view opts.more(hidden) gives, where hidden is the number of rows left out. Without opts.rows it shows all of content.

ito.Fold(ito.Text(log):wrap(), {
  rows = 8,
  more = function(hidden)
    return ito.Text("… " .. hidden .. " more"):dim()
  end,
})

Raises an error when opts.rows is not a whole number or opts.more is not a function.

ito.Lines(lines, value)

Draws lines, a list of lines, where each line is a list of spans. lines can also be a function that takes the width the view gets and value, and returns the lines, for text that wraps. Its lines are kept until the function, value or the width changes. A span is { text, style }, and the style is an ito.TextStyle, such as one of the theme’s ito.theme().styles.muted. A span without a style is drawn in the terminal’s own style. A line with an on_click function calls it when you click that line.

local ito = require("ito")

local Summary = ito.view(function()
  local styles = ito.theme().styles
  return ito.Lines({
    { { "tests ", styles.muted }, { "passing", styles.accent } },
    {
      { "open the build log", styles.highlight },
      on_click = function()
        uji.ui.exec("less build.log")
      end,
    },
  })
end)

Styles lists the styles every theme has.

ito.spans.wrap(line, width)

Breaks one line of spans into lines no wider than width, and keeps each piece in its span’s style. It breaks at the last space that fits and drops that space, keeps leading spaces with the text after them, and cuts a word that is wider than width. A line’s on_click and a span’s other fields go to every piece. It suits an ito.Lines function, which gets the width.

local function code(width, value)
  local out = {}
  for _, line in ipairs(value.lines) do
    for _, row in ipairs(ito.spans.wrap(line, width)) do
      out[#out + 1] = row
    end
  end
  return out
end

local Code = ito.view(function(props)
  return ito.Lines(code, { lines = props.lines })
end)

ito.Group(children)

Draws children one under another, like ito.VStack. Inside an ito.LazyVStack, each child becomes a row of its own, and only the ones that show are built.

ito.ZStack(children)

Draws children on top of each other in the order of the list, so the last one is in front. Each child sits at the stack’s alignment, center unless the props name another from ito.Alignment, and a child’s own :align wins over it. A child takes its fixed size, the whole stack when it grows, or else the size its content needs.

ito.ZStack({
  alignment = ito.Alignment.top_trailing,
  ito.Lines(log):grow(),
  ito.Text(" 3 new "):background(ito.theme().colors.accent),
})

ito.Subviews(children, builder)

Builds children, then calls builder(subviews) with the ones that drew something, in order. The builder returns the view to draw and places each subview in it at most once. A subview keeps its state, and it carries the hints its parent would read: weight, width, height, alignment and layout_id. Modifiers on ito.Subviews(...) apply to the view the builder returns.

This puts a bar between neighbours, but not next to a spacer or a segment that drew nothing:

local function joined(children)
  return ito.Subviews(children, function(subviews)
    local row = {}
    for index, subview in ipairs(subviews) do
      local before = subviews[index - 1]
      if before and not before.weight and not subview.weight then
        row[#row + 1] = ito.Text(" | ")
      end
      row[#row + 1] = subview
    end
    return ito.HStack(row)
  end)
end

Placing one subview twice raises “a subview can be placed once”.

ito.Layout(measure)

Makes a container from one function. measure(children, room) returns the container’s width, its height and a place(x, y) function. room.width and room.height are cells, or nil while the parent asks for a natural size. Each child has child:measure(room), which gives the width and height it wants, and child:place(x, y, width, height), plus the weight, alignment and layout_id hints. A child that place never places is not drawn.

Lay children out from children and room alone. ito lays a container out again only when its room or its children change.

local Corners = ito.Layout(function(children, room)
  return room.width, room.height, function(x, y)
    for _, child in ipairs(children) do
      local width, height = child:measure(room)
      if child.layout_id == "end" then
        child:place(x + room.width - width, y + room.height - height, width, height)
      else
        child:place(x, y, width, height)
      end
    end
  end
end)

uji.ui.toolbar({
  ito.ToolbarItem(ito.ToolbarPlacement.bottom_bar, function()
    return Corners({ ito.Text("uji"), ito.Text("v0.4"):layout_id("end") }):height(1)
  end),
})

ito.SubcomposeLayout(build, opts)

Calls build(room) with the room the view gets, { width, height } in cells, and draws the view it returns. While its parent measures it, the height is math.huge. The content keeps its state across frames. An error while building is passed to opts.failed(message) when you give one, and the view then draws nothing. In an ito.HStack it takes the room the other views leave, unless it has a width.

ito.SubcomposeLayout(function(room)
  if room.width < 60 then
    return ito.Text(uji.model.current().model)
  end
  return ito.Text(uji.model.current().name .. "/" .. uji.model.current().model)
end)

Modifiers

A modifier changes one view and gives the same view back, so modifiers chain one after another with :.

ito.Text("3 files changed")
  :foreground(ito.Color.yellow)
  :padding({ horizontal = 1 })
  :border(ito.theme().borders.rounded)
  :title("git")

A value a modifier cannot use raises an error that names it, such as grow takes a weight above 0, not -1.

:padding(cells)

Leaves cells blank cells on every side of the content. A table sets only the sides it names: top, bottom, leading and trailing one at a time, vertical for the rows above and below, and horizontal for the columns on the left and right. A side it leaves out keeps what it had.

Order matters, as it reads. Padding added before :background or :border sits inside them, and padding added after sits outside, so the background and the box leave it blank.

ito.Text("note"):padding({ leading = 2 })
ito.Text("panel"):padding({ vertical = 1, horizontal = 2 })

:border(set, opts)

Draws a box around the view with the characters in set. A theme’s borders are in ito.theme().borders, such as plain and rounded, and a table of your own needs all six fields that Borders lists.

OptionMeaningDefault
edgesito.Edges.all for the whole box, or ito.Edges.horizontal for only the lines above and below.ito.Edges.all
colorThe box’s colour, an ito.Color.the theme’s border style
ito.Text("ready"):border(ito.theme().borders.plain, { edges = ito.Edges.horizontal, color = ito.Color.green })

:title(title)

Puts title in the top border, with a space on each side. It is a string, or a line of spans as ito.Lines takes.

:background(colour)

Fills the whole view with colour, an ito.Color, before its content is drawn. An ito.TextStyle works too, and sets the text colour and flags of the whole view as well.

ito.Text(" deploying "):background(ito.rgb(0x2b2b2b))

:opaque()

Clears the view’s whole rectangle before it draws, so nothing drawn under it shows through.

:hidden(hide)

Keeps the view and its state but neither draws it nor gives it room. false shows it again.

Editor():hidden(not open.value)

:invisible(hide)

Keeps the view’s room and state but draws nothing there, so the views beside it stay where they are. false draws it again.

ito.HStack({ ito.Text("›"):invisible(not active), ito.Text(name) }):spacing(1)

:focus_scope(value)

Marks the controls drawn inside the view with value. A window gives the keys only to controls in its own scope.

:height(rows) and :width(columns)

Fix the view’s size in cells, whatever its content needs.

:max_height(rows)

Caps the view’s height at rows, and leaves a view that needs fewer rows at its own height. An ito.ScrollView capped this way scrolls what does not fit. math.huge sets no cap.

ito.ScrollView(ito.Lines(log)):max_height(10)

:share(fraction)

Gives the view fraction of the room in its stack, from 0 to 1. :share(0.3) in an ito.HStack takes 30% of the columns.

:grow(weight)

Gives the view a part of the room the other views in its stack leave. The parts follow the weights, and a view with no weight given has 1.

ito.HStack({
  ito.Lines(files):grow(),
  ito.Lines(diff):grow(2),
})

:shrink()

Keeps the view at its own size until its stack runs out of room, then takes the missing rows or columns from it first, so the views around it keep theirs. An ito.ScrollView that shrinks scrolls what no longer fits.

ito.VStack({
  ito.Text(question):wrap(),
  ito.ScrollView(details):shrink(),
  ito.Text("y to proceed"),
})

:align(alignment)

Places the view at one of ito.Alignment: top_leading, top, top_trailing, leading, center, trailing, bottom_leading, bottom or bottom_trailing. In an ito.VStack the view keeps its own width and moves left or right, and in an ito.HStack it keeps its own height and moves up or down. An ito.ZStack and an overlay use both directions. Without it, a stack stretches the view across.

ito.VStack({
  ito.Text("uji"),
  ito.Text("v0.4"):align(ito.Alignment.trailing),
})

:overlay(content, alignment)

Draws content in front of the view, at alignment, center by default. The view keeps its own size, and content is fitted inside it. false draws nothing. Several overlays are drawn in the order you add them.

ito.Text("build"):overlay(ito.Text("●"):foreground(ito.theme().colors.accent), ito.Alignment.trailing)

:layout_id(tag)

Gives the view a tag that an ito.Layout it sits in reads as layout_id. Unlike :id, it has nothing to do with state.

:id(…)

Gives the view an identity of its own. Its state, and the state of the views inside it, then stays with it when the views around it change order, and starts fresh when the id changes.

Several values make one id, so :id(job.kind, job.number) tells two jobs with the same number apart. An id only has to differ from its siblings’ ids. Two siblings with one id raise an error, and so does an id of nil, false or NaN. Your own views take an id the same way, as in Badge():id(name).

for _, job in ipairs(jobs) do
  rows[#rows + 1] = JobRow({ job = job }):id(job.kind, job.number)
end

:on_tap(handler)

Calls handler when you click anywhere on the view.

ito.Text("[run the tests]"):on_tap(function()
  uji.session.submit("Run the tests and fix what fails.")
end)

:hover(style)

Draws style over the view while the pointer is on it. It takes an ito.TextStyle, or an ito.Color for the background.

ito.Text("[run the tests]"):on_tap(run):hover(ito.theme().styles.selected)

Colours

A colour is an ito.Color value. ito.rgb(0xff8800) gives one from its red, green and blue parts and raises an error for a number outside 0x000000 to 0xffffff. ito.Color.indexed(245) gives one of the terminal’s 256 colours, and ito.Color.cyan one of its named colours, which Colours lists. A string or a number where a colour belongs raises an error, such as foreground must be an ito.Color, not a string. The theme’s own colours are in ito.theme().colors.

ito.Text("warning"):foreground(ito.rgb(0xff8800))
ito.Text("note"):foreground(ito.theme().colors.accent)

State

When a view runs again

A view’s body runs again only when one of these changes:

  • its props, compared value by value,
  • the theme, or a Local it reads,
  • a state, or a field of an observable object, that it or a view inside it read.

Otherwise the view keeps what it built on the last frame. So a value that changes reaches a view through its props, a state or an observable object. A plain table changed in place does not count as a change.

ito.state(initial)

Gives a value you read and set through .value, starting with the one you pass. Set a different one and every view that read it while it was built draws again.

Inside the body of a view, the view keeps the same state from one frame to the next, for as long as it stays on the screen. Made anywhere else, such as at the top of a plugin, a state holds data the plugin sets from outside its views.

local ito = require("ito")

local Output = ito.view(function(props)
  local open = ito.state(false)
  local shown = open.value and props.lines or { props.lines[#props.lines] }
  local rows = {}
  for index, line in ipairs(shown) do
    rows[index] = { { line, ito.theme().styles.muted } }
  end
  return ito.Lines(rows):on_tap(function()
    open.value = not open.value
  end)
end)

Order matters. A view finds its states by the order of its calls, so a body calls ito.state the same number of times, in the same order, on every frame.

local ito = require("ito")

local tests = ito.state("not run")

uji.command.add("test", {
  desc = "run the tests",
  handler = function()
    tests.value = "running"
    uji.job.start({
      cmd = { "cargo", "test", "--quiet" },
      on_exit = function(code)
        tests.value = code == 0 and "passing" or "failing"
      end,
    })
  end,
})

uji.ui.toolbar({
  ito.ToolbarItem(ito.ToolbarPlacement.bottom_bar, function()
    return ito.Text("tests " .. tests.value):dim()
  end),
})

ito.remember(factory, …)

Calls factory the first time the view is built and gives the same value back on every later frame. Values passed after factory are its keys: when one of them changes, factory runs again. Unlike a state, it never draws a new frame. Use it only inside the body of a view. Anywhere else it raises an error.

local Opened = ito.view(function()
  local opened = ito.remember(os.date)
  return ito.Text("opened " .. opened)
end)

local Words = ito.view(function(props)
  local count = ito.remember(function()
    local total = 0
    for _ in props.text:gmatch("%S+") do
      total = total + 1
    end
    return total
  end, props.text)
  return ito.Text(count .. " words")
end)

ito.observable(object)

Makes the fields of a table or object observable, and returns it. A view that reads a field runs again when that field is set to a different value. Methods work as before.

Setting a field is what counts. Changing a table stored in a field, such as adding to a list, does not, so set the field to a new table instead. A field set with rawset is not observed, which suits values a view never shows, such as caches.

local ito = require("ito")

local Queue = {}
Queue.__index = Queue

function Queue.new()
  return ito.observable(setmetatable({ items = {} }, Queue))
end

function Queue:push(item)
  local items = { table.unpack(self.items) }
  items[#items + 1] = item
  self.items = items
end

local queue = Queue.new()

local Pending = ito.view(function()
  return ito.Text(#queue.items .. " queued")
end)

ito.Local(default)

Makes a value a view hands down to every view inside it, while the frame is built. :provide(value, view) gives view with value set for itself and everything inside it, and .current reads the value inside a body. Where no view above provided one, .current is default.

local ito = require("ito")

local Accent = ito.Local(ito.Color.cyan)

local Label = ito.view(function(props)
  return ito.Text(props.text):foreground(Accent.current)
end)

local Panel = ito.view(function()
  return Accent:provide(ito.Color.magenta, ito.VStack({
    Label({ text = "plan" }),
    Label({ text = "build" }),
  }))
end)

ito.theme()

Returns the theme in use. It has styles, colors, symbols, borders, text, limits, options and views, and the helpers that Views lists. It works in views, toolbar items and render_message handlers alike.

local ito = require("ito")

local Status = ito.view(function(props)
  local theme = ito.theme()
  return ito.Lines({
    { { theme.symbols.pointer .. " ", theme.styles.accent }, { props.text, theme.styles.text } },
  })
end)

Changing themes redraws every view that used the old one.

ito.PreferenceKey(spec)

Makes a key for a value that views hand up to the views around them. spec has default, the value when nothing reports one, and reduce(value, next_value), which combines two values. Views report in the order they appear in the tree.

ModifierEffect
view:preference(key, value)Reports value for key.
view:overlay_preference_value(key, build, alignment)Combines what the views inside report for key, and draws build(value) in front of the view at alignment, in the same frame.
local ito = require("ito")

local Failing = ito.PreferenceKey({
  default = 0,
  reduce = function(value, next_value)
    return value + next_value
  end,
})

local Suite = ito.view(function(props)
  local rows = {}
  for index, result in ipairs(props.results) do
    rows[index] = ito.Text(result.name):preference(Failing, result.ok and 0 or 1)
  end
  return ito.VStack(rows):overlay_preference_value(Failing, function(count)
    return ito.Text(count .. " failing")
  end, ito.Alignment.top_trailing)
end)

Controls

Controls are the views you type into and move through.

ito.TextField(state)

A line you type into. state comes from ito.state and holds the text, so typing changes state.value and setting state.value changes the line.

ModifierEffect
:placeholder(text)Shows text dimmed while the line is empty.
:hidden()Draws the theme’s mask symbol for each character, for secrets.
:on_submit(handler)Calls handler(text) when you press Enter.
:focused()Asks for the keys when the field first shows.

Typed characters go in at the cursor. Left, Right, Home and End move the cursor, and Backspace and Delete erase. ito.TextField raises an error when state is not a state.

local ito = require("ito")

uji.command.add("branch", {
  desc = "create a branch",
  handler = function()
    local overlay
    overlay = uji.ui.overlay(function()
      local name = ito.state("")
      return ito.VStack({
        ito.Text("New branch"):bold(),
        ito.TextField(name):placeholder("feature/name"):focused():on_submit(function(text)
          overlay:close(text)
        end),
      }):padding({ horizontal = 1 }):border(ito.theme().borders.rounded)
    end)
    local branch = overlay:wait()
    if branch and branch ~= "" then
      uji.session.submit("Create the branch " .. branch .. " and switch to it.")
    end
  end,
})

ito.List(items, row)

Shows items, one row for each. ito calls row(item, index, selected) to build each row as a view, and only for the rows that fit. selected is true for the chosen row. The list scrolls to keep the chosen row in view.

ModifierEffect
:selection(state)Keeps the chosen index in a state, so you can read or set it. Without it, the list keeps the index itself.
:on_choose(handler)Calls handler(item, index) when you press Enter.
:focused()Asks for the keys when the list first shows.
:passive()Leaves the keys to the views around the list, which move it through :selection.
:footer(builder)Draws builder(first, last, total) under the rows while some items do not fit, where first and last are the rows in view.
:item_id(fn)Gives each item the id fn(item, index). A row’s state, the chosen row and the first row in view then follow their items when items are added, removed or moved. Without it they stay at their positions.

Up and Down move the choice by one row, Page Up and Page Down by a page, and Home and End go to the first and last rows. The mouse wheel over the list moves it too. ito.List raises an error unless items is a list and row is a function, and :item_id raises one when two items share an id.

local ito = require("ito")

local overlay
overlay = uji.ui.overlay(function()
  local styles = ito.theme().styles
  return ito.List(uji.session.list(), function(session, _, selected)
    local style = selected and styles.chosen or styles.text
    return ito.Lines({ { { session.title, style } } })
  end)
    :item_id(function(session)
      return session.id
    end)
    :focused()
    :on_choose(function(session)
      overlay:close(session)
    end)
    :footer(function(first, last, total)
      return ito.Text(first .. "-" .. last .. " of " .. total):dim()
    end)
    :border(ito.theme().borders.rounded)
    :title("Sessions")
end)

ito.ScrollView(child)

Shows child at its full height and scrolls it with the mouse wheel. :state(scroll) scrolls by an ito.ScrollState instead, so code of your own can move it too. :follow_end() keeps the bottom in view while the content grows, stops when you scroll up, and follows again once you scroll back to the bottom.

local ito = require("ito")

uji.fs.read("CHANGELOG.md", function(text)
  if not text then
    return
  end
  uji.ui.overlay(function()
    return ito.ScrollView(ito.Text(text)):border(ito.theme().borders.plain):title("CHANGELOG")
  end)
end)

ito.ScrollState(opts)

Holds where a scrolling view is. opts.follow starts it at the end. Pass it to ito.ScrollView(child):state(scroll) or ito.LazyVStack(...):state(scroll).

MemberMeaning
scroll:scroll(rows)Moves down by rows, or up when it is negative.
scroll:to_top()Goes to the top.
scroll:to_end()Goes to the end and follows it while the content grows.
scroll.followingWhether it is at the end and following it.
scroll.pageThe rows that show, for paging.
scroll.offsetThe first row that shows, counted from 0.
scroll.totalThe rows the content of an ito.ScrollView has.

page, offset and total are set when the scrolling view is laid out. A view that shows them, such as a “rows 1-10 of 40” line under it, reads them in an ito.SubcomposeLayout, which is built after the views above it are laid out.

ito.LazyVStack(items, row)

Shows items one under another and builds only the rows that show, so a list of thousands stays fast. row(item, index) gives the view of an item, and an ito.Group makes each of its children a row. Without a state it follows nothing and starts at the top.

ModifierMeaning
:item_id(id)Gives each item a lasting id, so its place and state follow it when items come and go. Two items with one id raise an error.
:state(scroll)The ito.ScrollState it scrolls by.
:footer(view)A view under the rows, right after the last one when they do not fill the room.
:more(load)Calls load when a move up reaches the first row, so the list can put the rows before it in items. The row you were on stays where it was.
local ito = require("ito")

local scroll = ito.ScrollState({ follow = true })

local Log = ito.view(function(props)
  return ito.LazyVStack(props.lines, function(line)
    return ito.Text(line.text)
  end)
    :item_id(function(line)
      return line.id
    end)
    :state(scroll)
end)

ito.Spinner()

Draws the frames of the theme’s symbols.spinner, one after another every limits.spinner_interval seconds, in the theme’s accent style.

ito.HStack({ ito.Spinner(), ito.Text(" indexing"):dim() })

Focus

Keys go to one control at a time. The control that has them keeps them while it is on the screen. When no control has them, the first one drawn with :focused() takes them, or else the first one drawn. A key the control does not use, such as Ctrl-C, goes on to uji’s keymap.

While a picker, prompt, approval or overlay is open, only the controls inside the one on top can take the keys. A control on the screen gets them back once it closes.

Images

ito.Image shows a picture. ito.ImageViewer adds keyboard and optional wheel controls for zooming and panning it. Both take the same modifiers as every other view and work inside stacks, grids, scroll views, overlays and ito.view functions of your own.

This page is about drawing a picture. Preparing one to send to a model is the runtime image helpers.

Turning graphics on

The screen asks for a graphics protocol, and it starts off:

screen:configure_images({ protocol = "kitty" })

kitty asserts that the terminal supports Kitty Unicode placeholders, which arrived in Kitty 0.28: plain Kitty graphics support is not enough. The image id travels in the cell’s foreground colour, so graphics also need a truecolor terminal. Nothing inspects stdin or probes the terminal, so a terminal that does not support them shows the fallback without ever receiving graphics commands.

uji owns the screen it draws on, so whether graphics are on is uji’s call; while they are off, an image draws its text or fallback.

Cell dimensions come from the terminal’s window-size ioctl when it answers, and 8 × 16 pixels otherwise. A host that knows them supplies both:

screen:configure_images({
  protocol = "kitty",
  cell_width = 10,
  cell_height = 20,
  tmux = false,
})

Explicit dimensions stay fixed until they are set again. Measured ones are re-read whenever the screen size is read, including after a font change. Supplying one of the two without the other is an error. screen:image_capabilities() returns the configured protocol, the cell dimensions, whether they are measured (auto) and the tmux setting. It is not a probe result.

tmux = true wraps each graphics command in tmux passthrough sequences, which the tmux the user runs has to allow. SSH needs nothing shared with the terminal: image bytes travel inside the escape codes.

Sources

local photo = ito.ImageSource.file("photo.jpg")
local uploaded = ito.ImageSource.bytes(png_or_jpeg_bytes)
local pixels = ito.ImageSource.rgba(width, height, rgba_bytes)

Files and encoded bytes load in the background. Only still PNG and JPEG are decoded; an EXIF orientation is applied before any crop. Raw RGBA data must hold exactly width * height * 4 bytes. A source never changes and can be shown by several views; asking for a file again makes a new source that reads it again.

source:status() answers { phase = "loading" }, { phase = "ready", width = ..., height = ... } or { phase = "failed", error = ... }, with the dimensions in pixels after the EXIF orientation.

Keep sources outside functions that are composed often, or remember them by their arguments:

local Photo = ito.view(function(props)
  local source = ito.remember(function()
    return ito.ImageSource.file(props.path)
  end, props.path)
  return ito.Image(source):alt(props.description)
end)

Fetching a URL, saving, copying and opening another application are yours to arrange: pass callbacks in through props and :on_tap(handler).

Presentation and placement

ito.Image(photo)
  :content_mode(ito.ImageMode.fill)
  :content_alignment(ito.Alignment.top)
  :crop({ x = 100, y = 50, width = 400, height = 300 })
  :rotate(90)
  :opacity(0.8)
  :sampling(ito.ImageSampling.linear)
  :width(40)
  :height(12)
  :align(ito.Alignment.leading)
  :padding(1)
SettingEffect
ImageMode.fitDefault. Keeps the proportions and shows the whole image, with transparent space left over.
ImageMode.fillKeeps the proportions and crops to fill the rectangle.
ImageMode.stretchFills the rectangle without keeping the proportions.
ImageMode.originalOne source pixel per terminal pixel, clipped to the rectangle.
content_alignmentPlaces the image in its rectangle, including which edge stays visible when it is cropped.
cropA rectangle inside the oriented source, in pixels. nil removes it.
rotateClockwise multiples of 90 degrees, applied after the crop.
opacityA number from 0 to 1, multiplied into the source alpha.
ImageSampling.linearDefault. Bilinear interpolation with premultiplied alpha.
ImageSampling.nearestKeeps hard pixel edges, for pixel art.

width, height, padding and layout positions count cells. align moves the view inside its parent; content_alignment moves the pixels inside the view. The cell proportions are part of how an image measures its own height, and explicit dimensions keep the space stable while the image loads.

A transform belongs to the view and never changes the source, so one source can be a cropped thumbnail in one place and a full preview in another. Identical prepared images share one upload. Scrolling clips the original rectangle and keeps its image coordinates, rather than fitting the visible fragment again.

Image cells replace the text cells under them, and later text or an opaque overlay covers them again. Text styling cannot overwrite the colours that carry image identity. Text selection, screen:text, styled snapshots and virtual-terminal frames hold spaces where image cells are, never protocol characters. Copying the pixels of an image is something the application arranges.

Loading and fallback views

ito.Image(photo)
  :height(12)
  :alt("Mountain at sunset")
  :placeholder(ito.Text("Loading image…"))
  :fallback(function(status)
    return ito.Text("Could not load image")
  end)
  :unsupported(ito.Text("Image preview unavailable"))

Each of the three takes a view or a function returning one. The function receives { phase, error, source }. Loading covers decoding and preparing the current size and transform. fallback handles failures, and is used for a terminal without graphics when no unsupported view is given. The default in every phase is the alt text, which starts as Image.

Changing a transform keeps the previous ready image on screen until the replacement is prepared, as long as the source and the rectangle size stay the same and the previous variant is still cached. Changing the source shows the loading view, so unrelated pixels are never left behind.

A visible image that is still loading asks for the next frame through frame.wake, the same deadline ito.Spinner uses, and the host honours it. Decoding and encoding happen on a worker; terminal writes stay in frame order.

Interactive viewer

local viewport = ito.ImageViewport()

ito.ImageViewer(photo)
  :state(viewport)
  :focused()
  :content_mode(ito.ImageMode.fit)
  :wheel(ito.ImageWheel.zoom)
  :on_change(function(state)
    -- Update application controls or labels.
  end)
  :grow()

Without state, the viewer keeps its own viewport between frames. A viewport you supply can be shared by several viewers or driven from a toolbar:

viewport:zoom_to(2)
viewport:zoom_by(1.25)
viewport:pan_to(0, 0.5)
viewport:pan_by(0.1, 0)
viewport:reset()

Zoom is relative to the selected content mode and is clamped to 0.1–64. Pan coordinates run from -1 to 1 and shift the alignment across the difference between the image and the viewport, so zero leaves content_alignment as it is and positive values move the viewed region right or down for an overflowing image. Read zoom, x and y for toolbar labels. As with ito.ScrollState, a change made outside the viewer needs the host to draw again.

InputAction
+ or =Zoom in
-Zoom out
Arrow keysPan
0 or HomeReset zoom and pan

Ctrl, Alt and Meta combinations are left to you. ImageWheel.pass is the default and leaves the wheel to the scrolling container; ImageWheel.zoom and ImageWheel.pan take it inside the visible viewer. Dragging the mouse still selects text.

Bounds and lifecycle

  • Encoded input: at most 16 MiB. Source dimensions: at most 8192 per side and 16 megapixels in total.
  • Each prepared placement: at most 4 megapixels and 297 cells per axis, the limit of the placeholder coordinate table.
  • A screen caches at most 64 prepared variants within a 64 MiB budget, and evicts the offscreen ones first. A source the application keeps has its own lifetime.
  • One worker and eight queued jobs bound the work in flight. A full queue defers a placement to a later frame or status check, and work whose result nobody waits for any more is skipped.
  • Uploads are made from the cells that are left after composing, so a covered image is never uploaded. Every cell carries its own image coordinates, so clipping and overlays do not depend on neighbouring placeholders.
  • Commands carry the bytes directly, in payload chunks of at most 4096 base64 bytes, and ask for no reply from the terminal.
  • Suspending, closing, reclaiming the screen and evicting a variant delete only the image ids ito owns. Resuming, and a write that fails, mark the images for upload again.

The implementation follows the Kitty graphics protocol, including its published Unicode coordinate table. Whether a terminal supports Unicode placeholders, and whether tmux passes them through, is worth checking in each terminal an application supports.

Toolbars

A toolbar item is a view that names the section of the screen it belongs in. The screen decides where each section sits, so a plugin says what it shows and which section it goes in, never a row or a column.

ito.ToolbarPlacement

PlacementWhere uji’s default screen shows it
top_bar_leadingThe left end of the top row.
top_bar_trailingThe right end of the top row.
keyboardDirectly above the input line, the section for things that go with typing.
bottom_barUnder the input line, at the bottom of the screen.

A theme’s screen can put any section somewhere else, or leave it out.

ito.ToolbarItem(placement, content)

Makes one item. content is a view of your own, or a function that returns a view, and it is built again on every frame. Layout modifiers go on the view you return, so the item reads as both the section and the place inside it:

local ito = require("ito")

uji.ui.toolbar({
  ito.ToolbarItem(ito.ToolbarPlacement.keyboard, function()
    return ito.Text("ctrl+b toggles plan mode"):dim():align(ito.Alignment.leading)
  end),
})

item:id(...) gives the item an id, so its state stays with it when items before it come and go. An item that draws nothing takes no room. An item that raises an error draws nothing either, and the error is reported once while the other items keep drawing.

ito.ToolbarItem raises an error when placement is not one of ito.ToolbarPlacement, or when content is neither a view nor a function.

view:toolbar(items)

Declares items, a list of ito.ToolbarItem, from inside the screen. The items go to the nearest ito.ToolbarHost around the view. On uji’s screen, uji.ui.toolbar declares items the same way from a plugin.

local Editor = ito.view(function(props)
  return ito.Lines(props.lines):toolbar({
    ito.ToolbarItem(ito.ToolbarPlacement.bottom_bar, function()
      return ito.Text(#props.lines .. " lines"):dim()
    end),
  })
end)

ito.ToolbarHost(content)

Collects the items that the views in content declare, its own first and then in the order the views appear, and shows them in the sections inside content. A host inside another host keeps the items declared inside it for itself, so an overlay can have its own bar. uji’s screen is a host already.

When a host has items for a placement that no section shows, it says so once: toolbar: nothing shows the items placed at bottom_bar.

ito.ToolbarItems(placement, arrange)

The section that shows the host’s items for placement. arrange lays them out: ito.VStack, the default, puts them in a column, and ito.HStack puts them in a row. A section with no items takes no room.

ito.VStack({
  slots.transcript():grow(),
  ito.ToolbarItems(ito.ToolbarPlacement.keyboard, ito.HStack),
  slots.composer(),
  ito.ToolbarItems(ito.ToolbarPlacement.bottom_bar),
})

Window

ito.Window(screen, invalidate)

Draws views on a screen and sends input to them. screen comes from ito.open(), and invalidate is called whenever a state changes and the window needs a new frame. uji draws its own screen through a window, and a window of your own draws a tree that replaces everything.

MemberMeaning
window:render(view, theme)Builds view with theme and draws it on the whole screen, then gives the keys to a control.
window:key(chord)Gives a key to the control that has the keys, and returns true when it used it.
window:wheel(row, col, rows)Scrolls whatever scrolls at that position, and returns true when something did.
window:press(row, col), window:drag(row, col)Start and extend a selection, or a click.
window:release(event)Ends the selection and returns its text, or calls the click target under the press.
window.scopeThe focus scope whose controls get the keys. nil means controls outside any scope.
window.focusedThe key handler of the control that has the keys.

ito.SelectionHighlight()

Paints the window’s selection in the theme’s selection style. Put it last in a ito.ZStack over the screen.

local ito = require("ito")

local screen, input = ito.open()
local window = ito.Window(screen, function() end)
local themes = ito.Themes({ default = require("uji.themes.default")() })

local function draw()
  window:render(
    ito.ZStack({ ito.Text("select me with the mouse"), ito.SelectionHighlight() }),
    themes:context()
  )
  screen:flush()
end

Terminal

ito.open()

Opens the terminal and gives two values, one to draw with and one that reads keys and clicks. Every call gives the same two, and they survive /reload. uji draws on this terminal too, so anything else drawn on it is replaced at uji’s next frame. It is mainly for a tree that replaces everything.

Rows and columns count from 0 at the top left. Drawing only changes the screen in memory, and screen:flush() shows the changes. A position outside the screen draws nothing.

local ito = require("ito")

return function()
    local screen, input = ito.open()
    local title = ito.TextStyle({ foreground = ito.Color.cyan, bold = true })
    local width, height = screen:size()
    screen:clear()
    screen:line(0, 0, { { "hello ", title }, "from uji" })
    screen:line(1, 0, "the screen is " .. width .. " by " .. height)
    screen:line(2, 0, "press q to quit")
    screen:cursor(3, 0, "bar")
    screen:flush()
    for event in input:events() do
        if event.type == "key" and event.key == "q" then
            break
        end
        screen:line(3, 0, "you pressed " .. (event.key or event.type) .. "      ")
        screen:flush()
    end
    screen:close()
end

The screen

MemberMeaning
screen:size()The width and the height, in columns and rows.
screen:line(row, col, spans, width)Draws spans from row and col, and gives the column after the last character. spans is a string, or a list whose items are strings or { text, style } pairs, where the style is an ito.TextStyle or is left out for the terminal’s own style. width stops the text after that many columns. The list’s on_click field is a function that screen:clicked gives for a click anywhere on the line.
screen:clicked(row, col)The on_click function of the line drawn last at the position, or nil when that line has none.
screen:fill(area, style, symbol)Fills area, a table with x, y, width and height, with symbol in style, an ito.TextStyle. With no style it uses the terminal’s own, and symbol is a space when it is left out.
screen:paint(area, style)Sets the style of area to style, an ito.TextStyle, and keeps its text.
screen:text(row)The text on row, or nil outside the screen.
screen:spans(row)The text on row split where the style changes, as a list of { text, fg, bg, modifiers }, or nil outside the screen. fg and bg are left out for the terminal’s default colour, and modifiers lists names such as "bold".
screen:clear()Empties the whole screen.
screen:cursor(row, col, shape)Shows the cursor at the position, as "block", the default, "bar" or "underline". With no position it hides the cursor.
screen:flush()Shows what changed since the last flush, and puts the cursor in place.
screen:write(bytes)Sends bytes to the terminal as they are.
screen:suspend()Gives the terminal back, for a program that needs it.
screen:resume()Takes the terminal again and clears it, ready for the next flush.
screen:close()Gives the terminal back for good.

Colours come from ito.Color and ito.rgb, as Colours describes.

A span that is neither a string nor a pair, a style that is not an ito.TextStyle, and an unknown cursor shape all raise an error.

The input

MemberMeaning
input:event()Waits for the next event and gives it as a table.
input:events()An iterator over the events, for a for loop.

Each event has a type field.

typeFields
"key"key, and ctrl, alt, shift, meta and repeat as booleans.
"mouse"kind, button, row, col, and ctrl, alt and shift as booleans.
"paste"text, the pasted text.
"resize"width and height, the new size.
"focus"focused, true when the terminal gains focus and false when it loses it.

key is the character typed, such as "a" or "A", or one of "enter", "esc", "backspace", "delete", "tab", "backtab", "left", "right", "up", "down", "home", "end", "pageup", "pagedown", "insert" and "f1" to "f12".

A mouse kind is "down", "up", "drag", "move", "scroll_up", "scroll_down", "scroll_left" or "scroll_right". button is "left", "right" or "middle" for presses, releases and drags, and nil otherwise.

A click handler sees the frame on the screen. The lines that one frame draws keep their handlers until the next frame starts drawing after a flush, and a later line or fill over the same cells hides the handler under it.

local screen, input = require("ito").open()
local count = 0
local function draw()
    screen:clear()
    screen:line(0, 0, {
        "clicked " .. count .. " times",
        on_click = function()
            count = count + 1
        end,
    })
    screen:flush()
end
draw()
for event in input:events() do
    if event.type == "mouse" and event.kind == "up" then
        local click = screen:clicked(event.row, event.col)
        if click then
            click(event)
            draw()
        end
    end
end

Runtime

A plugin uses these functions to run work in the background, talk to the network, start processes, keep data in SQLite and read the system.

Tasks

Your config, slash commands, key bindings, actions, tool functions and the timers from uji.schedule and uji.defer run as tasks. Any of them can wait on the network, a process, the keychain or a timer while the screen keeps working.

One task runs at a time, until it waits, so a loop that never waits holds up the screen and every other task. Waiting outside a task raises an error, and a coroutine you create yourself cannot wait.

uji.task.spawn(fn, …)

Starts fn as a new task with the arguments that follow, and returns a task object. It begins once the current task waits. Errors show as notices.

task:cancel()

Stops the task where it waits, together with the functions that uji.task.race and uji.task.timeout run for it. What it was waiting on stops too, and uji closes the connections and processes that only this task used. A task that cancels itself stops at its next wait.

uji.sleep(seconds)

Pauses the task for seconds. Fractions work. With 0 the task pauses only long enough for every other task that is ready to run first, which is how a long loop can give the screen and the rest of uji their turn. With math.huge it waits until it is cancelled. Anything other than a number of seconds raises an error.

uji.task.race(fn, …)

Runs every function at once inside the current task, and waits for the first to finish. The result is its position followed by what it returned, and the others stop there. An error in the first to finish is raised again, and cancelling the current task stops all of them.

uji.task.timeout(seconds, fn)

Runs fn inside the current task for at most seconds, where math.huge means no limit. When fn finishes in time the result is true followed by what it returned. Otherwise fn stops and the result is false.

uji.promise()

Creates a promise. Tasks wait on it until another task settles it.

MemberMeaning
promise:resolve(...)Settles the promise with the values given, and wakes every task waiting on it. The result is true the first time and false after.
promise:await()Waits until the promise is settled and gives back its values. A settled promise gives them back at once.
promise.settledtrue once the promise is settled.

Network

Each call here waits inside the current task, so the rest of uji keeps drawing and taking keys meanwhile.

uji.net.request(opts)

Sends an HTTP request and waits for the answer, a table with status, headers and body. When no answer comes back the result is nil and an error message. An error status still counts as an answer.

OptionTypeMeaning
urlstringThe address. Required.
methodstringThe method. The default is "GET".
headerstableHeader names and values.
bodystringThe request body.
timeoutnumberSeconds to wait for the whole answer.

uji.net.open(opts)

Sends a request like uji.net.request, but hands back a response object as soon as the headers arrive, so the body can be read while it streams. It takes the same options plus idle, the seconds without data after which reading fails, 120 by default. A failed request gives nil and an error message.

MemberMeaning
response.statusThe status code.
response.headersHeader names and values.
response:line(seconds)The next line, nil at the end of the body, or false if seconds pass first. Without seconds it waits as long as the line takes.
response:lines()An iterator over the remaining lines, for a for loop.
response:read()Everything left in the body, once it has arrived.

uji.net.listen(port)

Listens on port on the local machine, or on a free port when port is 0. The result is a server, or nil and an error message.

MemberMeaning
server.portThe port it listens on.
server:accept()The next connection, or nil and an error message once the server is closed.
server:close()Stops listening.
conn:line(seconds)The next line, nil when the other side closes, or false if seconds pass first. Without seconds it waits as long as the line takes.
conn:read(count)Exactly count bytes.
conn:write(data)Sends data.
conn:close()Closes the connection.

uji.net.url(text)

Parses text into a url with the parser the requests use, and gives nil when text is not an address with a host.

MemberMeaning
url.uriThe whole address.
url.schemeThe scheme, https and the like, in lower case.
url.hostThe host, in lower case, an address in brackets when it is one, without a user name.
url.portThe port it names, or nil.
url.pathThe path, / when it names none.
url.queryEverything after ?, or nil.
url.fragmentEverything after #, or nil.

Processes

uji.proc.spawn(argv, opts)

Starts the program named by the first item of the list argv, with the rest as its arguments. The result is a process, or nil and an error message. If the process is still running when nothing refers to it any more, uji kills it and every process it started. A process given the terminal is killed alone.

A process that is not given the terminal has none: a program that asks for a password on the terminal, such as ssh or sudo, fails at once instead of waiting for an answer.

OptionTypeMeaning
cwdstringThe directory to run in.
envtableExtra environment variables.
stdiostring"pipe", the default, to read and write the process, or "inherit" to give it the terminal.
MemberMeaning
proc.pidThe process id.
proc:line()The next line of output with "stdout" or "stderr", or nil once both streams end.
proc:lines()An iterator over the remaining lines and their streams.
proc:write(data)Writes data to the process’s input.
proc:close()Closes the process’s input.
proc:kill()Kills the process and every process it started. A process given the terminal is killed alone.
proc:wait()Waits for the process to exit and gives a table with code, signal and success.

Storage

uji.db.open(path)

Opens or creates the SQLite database at path. The result is a database, or nil and an error message. Parameters are a list that fills the ? marks in the statement, and uji.db.null stands for NULL in that list. A statement that SQLite rejects raises an error, in every method below.

MemberMeaning
db:exec(sql, params)Runs a statement and gives the number of rows it changed. Without params, sql may hold several statements.
db:query(sql, params)The rows, as a list of tables keyed by column name.
db:transaction(fn)Runs fn in a transaction and gives back what it returns. An error inside fn rolls the transaction back and raises again. fn cannot wait, so no other task can write in the middle of the transaction.
db:close()Closes the database.

System

These describe the machine and the current run, and give access to saved passwords and to what you last copied.

FunctionGives
uji.os.platform"macos", "linux", "windows" or "other".
uji.os.env(name)The value of an environment variable, or nil when it is unset or empty.
uji.os.cwd()The directory uji started in.
uji.os.home()Your home directory, or nil.
uji.os.now()The time in milliseconds since the Unix epoch.
uji.os.clock()Seconds since uji started, for measuring how long something took.
uji.os.executableThe path of the program running uji, or nil when the system cannot tell.
uji.os.argvThe arguments uji started with, the program name first.
uji.os.rootsThe directories whose lua/ and native/ folders are searched before the built-in modules.
uji.os.carryThe text handed over by the last uji.os.restart, or nil.
uji.os.libraryThe file extension of a native module on this system, "dylib" or "so".
uji.message(err)The text of an error caught with pcall, without the stack trace that errors from the runtime carry.

uji.os.restart(opts)

Restarts uji once the current code waits, keeping the screen. Every task, connection and process from this run stops. opts.args is the command line for the new run, opts.roots sets uji.os.roots for it, and opts.carry is text it can read from uji.os.carry.

uji.modules(namespace)

Lists the modules directly inside namespace, such as "uji.builtin.commands", as full names in alphabetical order. It looks in the lua/ folder of every directory in uji.os.roots and in the built-in modules. A folder with an init.lua counts as one module.

uji.keychain.get(service, account)

Looks up the secret saved in the system keychain for service and account, and gives nil when there is none.

uji.keychain.set(service, account, secret)

Saves secret in the system keychain, then gives true, or nil and an error message.

uji.keychain.delete(service, account)

Removes the secret, with the same result as uji.keychain.set.

uji.clipboard.get()

Reads the text on the system clipboard, or gives nil and an error message.

uji.clipboard.set(text)

Puts text on the system clipboard and gives true, or nil and an error message.

uji.clipboard.image(edge, bytes)

Takes the image on the system clipboard and fits it the way uji.image.fit does, and gives the same table. A clipboard without an image gives nil and “the clipboard has no image”.

Text

uji.regex(pattern)

Compiles a regular expression into a matcher, or gives nil and an error message.

uji.glob(pattern, opts)

Compiles a glob such as *.rs into a matcher, or gives nil and an error message. With opts.separator = true, * does not match /.

MemberMeaning
matcher:test(text)true when the pattern matches somewhere in text.
matcher:find(text)The start and end positions of the first match, or nil.

uji.fuzzy(query, items)

Ranks the list of strings items against query the way the pickers do, as positions in items with the best match first. An empty query gives every position in order.

uji.highlight(language, text)

Highlights text away from the screen’s thread and gives the tokens of each line, or nil when uji does not know language. language is a name such as "python", a file extension such as "rs", or a file name such as "Makefile". Each token has text and kind, which is one of "plain", "keyword", "string", "number", "comment", "func", "type" and "constant". Call it from a task, since it waits for the result.

uji.task.spawn(function()
  local lines = uji.highlight("lua", "local n = 42 -- answer")
  local kinds = {}
  for _, token in ipairs(lines[1]) do
    kinds[#kinds + 1] = token.kind .. ": " .. token.text
  end
  uji.notify(table.concat(kinds, ", "))
end)

uji.markdown(source)

Parses Markdown into a list of events. Each event is itself a list that starts with its kind, one of "start", "end", "text", "code", "html", "math", "break", "rule" and "task". The details of that event come next, then its start and end byte positions in source.

Math between $ and $, or \( and \), gives a "math" event with its TeX source and false. Math between $$ and $$, or \[ and \], gives one with true.

uji.width(text)

Counts the terminal columns text takes.

uji.lossy(data)

Turns data into valid UTF-8, replacing each invalid byte sequence with U+FFFD.

Encoding

FunctionGives
uji.base64.encode(data, opts)data in base64. opts.url = true uses the URL alphabet and opts.pad = false leaves out padding.
uji.base64.decode(text, opts)The decoded bytes. It takes the same options and raises an error for text that is not base64.
uji.sha256(data)The SHA-256 digest of data, as 32 raw bytes.
uji.random(count)count random bytes.
uji.toml.decode(text)A table with the values in the TOML document text. It raises an error for text that is not valid TOML.
uji.toml.encode(table)table written as a TOML document. It raises an error for a value TOML cannot hold, such as a list at the top.

Images

uji.image.fit(data, edge, bytes)

Checks that data holds a PNG, JPEG, GIF or WebP image and returns it ready to send. A photo with an EXIF orientation is turned upright, and an image whose long side passes edge pixels is scaled down. When the result is still larger than bytes, it is saved as JPEG at lower quality, and then at half the size until it fits.

The result is a table with four fields. data holds the image encoded as base64, media_type names its type such as "image/png", and width and height give its size in pixels. An image that needs no change keeps its original bytes. Anything else gives nil and an error message.

local image = uji.image.fit(uji.fs.read("shot.png"), 1568, 3 * 1024 * 1024)

Native modules

A native module is a shared library that Lua loads with require. uji looks for it in native/ in the config directory and in every pack. require("name") finds name.dylib on macOS and name.so on Linux. A dotted name looks in folders, so require("tools.fast") finds native/tools/fast.dylib. Native modules work on macOS and Linux only.

The library is a Lua C module for LuaJIT. It exports a function named luaopen_ followed by the module name, with each dot written as an underscore, and whatever that function returns is the module. A module can be written in any language that can export such a function, such as C, Zig or Rust.

The library does not link LuaJIT itself. It uses the LuaJIT inside uji, which on macOS needs the linker flag -undefined dynamic_lookup.

A native function runs while every task waits, so a slow one holds up the screen until it returns.

Loading

uji loads a library the first time require asks for it, and keeps it until uji restarts. After you rebuild a library, /reload loads the new one.

Errors

An error raised inside a native function, such as an argument of the wrong type, reaches Lua like any other error. pcall catches it, and uji.message(err) gives its text without a stack trace.

local ok, err = pcall(require("loadavg").get)
if not ok then
    uji.notify(uji.message(err))
end

Writing one in C

The module needs LuaJIT’s headers, for example from brew install luajit or a libluajit-5.1-dev package. This one gives a status segment the system’s load average.

#include <stdlib.h>
#include <lua.h>
#include <lauxlib.h>

static int get(lua_State *L) {
    double average;
    if (getloadavg(&average, 1) != 1) {
        return luaL_error(L, "the load average is not available");
    }
    lua_pushnumber(L, average);
    return 1;
}

int luaopen_loadavg(lua_State *L) {
    lua_newtable(L);
    lua_pushcfunction(L, get);
    lua_setfield(L, -2, "get");
    return 1;
}

On macOS:

cc -shared -undefined dynamic_lookup -I"$(brew --prefix luajit)/include/luajit-2.1" -o loadavg.dylib loadavg.c
mkdir -p ~/.config/uji/native && cp loadavg.dylib ~/.config/uji/native/

On Linux:

cc -shared -fPIC -I/usr/include/luajit-2.1 -o loadavg.so loadavg.c
mkdir -p ~/.config/uji/native && cp loadavg.so ~/.config/uji/native/
local ito = require("ito")

uji.ui.toolbar({
  ito.ToolbarItem(ito.ToolbarPlacement.bottom_bar, function()
    return ito.Text(string.format("load %.2f", require("loadavg").get())):foreground(ito.Color.gray)
  end),
})

Writing one in Rust

A Rust module is a crate with crate-type = ["cdylib"] that depends on mlua with the luajit52 and module features. #[mlua::lua_module] on a function that takes &Lua and returns the module exports it as luaopen_ followed by the function’s name, and #[mlua::lua_module(name = "tools_fast")] exports it under the name you give instead. This one gives the number of CPU cores, which sizes how many subagents run at once.

Cargo.toml:

[package]
name = "cpus"
version = "0.1.0"
edition = "2024"

[lib]
crate-type = ["cdylib"]

[dependencies]
mlua = { version = "0.12", features = ["luajit52", "module"] }

build.rs, which passes the macOS linker flag:

fn main() {
    if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("macos") {
        println!("cargo::rustc-cdylib-link-arg=-undefined");
        println!("cargo::rustc-cdylib-link-arg=dynamic_lookup");
    }
}

src/lib.rs:

#![allow(unused)]
fn main() {
use mlua::prelude::*;

#[mlua::lua_module]
fn cpus(lua: &Lua) -> LuaResult<LuaTable> {
    let module = lua.create_table()?;
    module.set(
        "count",
        lua.create_function(|_, ()| {
            Ok(std::thread::available_parallelism().map_or(1, std::num::NonZero::get))
        })?,
    )?;
    Ok(module)
}
}

Build it and copy the library under the module’s name, cpus.dylib on macOS or cpus.so on Linux:

cargo build --release
cp target/release/libcpus.dylib ~/.config/uji/native/cpus.dylib
require("subagent").setup({ concurrency = require("cpus").count() })

Replacing a built-in module

Every part of the Runtime is a module named uji.sys. followed by its name. require looks in these places, in order, and uses the first module it finds:

  1. Lua in your config and packs, such as ~/.config/uji/lua/uji/sys/fs.lua.
  2. The Lua that comes with uji.
  3. Native modules in native/ in your config and packs, such as native/uji/sys/fs.dylib, which exports luaopen_uji_sys_fs.
  4. The modules built into uji.

A module you provide under one of these names replaces the built-in one, and everything in uji that uses it uses yours. The other modules stay built in.

ModuleWhat it is
uji.sys.taskspawn, race, timeout and on_error, in Tasks.
uji.sys.sleepThe sleep function, in Tasks.
uji.sys.promiseThe promise function, in Tasks.
uji.sys.fsFiles and folders, in uji.fs.
uji.sys.netRequests and the local server, in Network.
uji.sys.procProcesses, in Processes.
uji.sys.dbSQLite databases, in Storage.
uji.sys.osThe system and restarting, in System.
uji.sys.keychainThe keychain, in System.
uji.sys.clipboardThe clipboard, in System.
uji.sys.modulesThe modules function, in System.
uji.sys.messageThe message function, in System.
uji.sys.jsonJSON, in uji.json.
uji.sys.tomlTOML, in Encoding.
uji.sys.base64Base64, in Encoding.
uji.sys.sha256The sha256 function, in Encoding.
uji.sys.randomThe random function, in Encoding.
uji.sys.regexThe regex function, in Text.
uji.sys.globThe glob function, in Text.
uji.sys.fuzzyThe fuzzy function, in Text.
uji.sys.widthThe width function, in Text.
uji.sys.lossyThe lossy function, in Text.
uji.sys.markdownThe markdown function, in Text.
uji.sys.imageImage fitting, in Images.

This file at ~/.config/uji/lua/uji/sys/width.lua counts every character as one column. /reload puts it to use.

return function(text)
    local _, count = text:gsub("[^\128-\191]", "")
    return count
end