zidane/ chat
The renderer-agnostic chat engine that backs the TUI and GUI hosts.
import { … } from 'zidane/chat'src/chat/index.ts
Use zidane/chat to build your own chat app on createChatHost, the engine the terminal and desktop apps share (one engine). It owns runs, the queue, approvals, todos, profile switching and session operations behind one API. cacheImpact and cacheReport tell a picker what a switch would re-read and how much of each request hit the prompt cache, and cacheHintText turns an estimate into the picker hint (re-reads ~452k tokens). The daemon and zidane-server wrap the engine, so zidane/chat never imports zidane/ipc. In a browser bundle, zidane/chat resolves to its browser build through the browser export condition: every type, plus the values that need no Node built-in (React contexts, settings, themes, formatters). The host engine, providers, credentials, discovery and stores are only in the Node build. zidane/chat/pure is the subset without React.
import { resolveConfig } from 'zidane/chat'
import { createMemoryStore } from 'zidane/session'
const config = resolveConfig({ prefix: '.myapp', store: createMemoryStore() })
console.log(Object.keys(config.providers), config.initialAgentId)The Node code of the setup wizard is here too. detectOnboardingEnvironment reads what a computer already has: provider keys, the setups of other agents, the GitHub login and local model servers. previewClaudeImport lists what importFromClaudeCode copies, before it runs. The model of the wizard, which both apps run on, is in zidane/chat/pure.
Functions#
accountCredKeyFunction#
File key holding one of a provider's non-active OAuth accounts.
Same sibling-key reasoning as alternateCredKey: the canonical key is
the active one, so a provider with three OAuth grants stores the active one
canonically and the other two under #account:N. #alt stays dedicated to
the other-kind (API key) alternate so files written by builds that predate
multi-account keep meaning the same thing.
acquireUpdateLockFunction#
Takes the install lock, replacing a stale one. Never throws: a cache dir
that cannot be written yields acquired: true with a no-op release, since
a lock that cannot be created protects nothing and must not block the
install.
addToSafelistFunction#
Append one or more entries to the safelist for projectDir, dedup-aware.
Accepts a single string or a list (a compound shell command needs one
entry per command head — see suggestSafelistEntries). Writes once
and returns the updated entry list (post-write) so callers can render it
without re-reading. No write happens when every entry already exists.
addToSafelistForCwdFunction#
addToSafelist under the project key for cwd — the write every host's gate uses.
alternateCredKeyFunction#
File key holding a provider's second credential, when it has one of each kind.
The canonical key always holds the credential the user prefers; this sibling
holds the other. That one invariant is what makes preference selection free:
every existing reader (applyApiKeyEnv, the harness provider factories)
already resolves the canonical key, so "switch priority" is just moving two
objects between two keys — no precedence flag to interpret, no resolution
order to keep in sync across layers.
A sibling key rather than a nested field because the canonical entry gets
REPLACED wholesale on token refresh; anything nested inside it would be
dropped by the next rotation. And older zidane versions look credentials up
by credKeyOf, so a suffixed key is simply invisible to them — they read the
preferred credential and behave exactly as before, which is why this needs no
migration or schema version.
applyApiKeyEnvFunction#
Reconcile process.env with the stored credentials so the harness providers
pick up the wizard's output via their existing env-var resolution. Each
host (TUI, daemon, desktop app) calls it at launch after the credentials file
has been resolved, and again after a credential change.
Precedence: stored credential > ambient env. When the user has run the
auth wizard, that's an explicit, recent action — it MUST win over whatever
ambient value is already in process.env. Otherwise an upgrade reliably
breaks for anyone whose cwd happens to contain a stale .env: Bun
auto-loads .env from cwd into process.env before our code runs, older
versions of bun run auth upserted tokens into cwd/.env, and even a
one-off export ANTHROPIC_API_KEY=… from months ago in the user's shell rc
can outlive its usefulness. None of those should override a key the user
just typed into the wizard.
Three cases per registered provider with an envKey:
- Stored
kind: 'apikey'→ overwrite env with the stored value. Wizard wins. A debug log fires when this clobbers a different ambient value. - Stored
kind: 'oauth'→ DELETE env, soresolveOAuthApiKeyfalls through to the file-read + refresh path. A stale OAuth token in env would otherwise short-circuit refresh and get rejected. - No stored entry → leave env alone. Env-only setups (no wizard run yet, hosts driving zidane purely from secrets management) keep working.
To opt out and force ambient env to win again, the user signs the provider out via the wizard (which deletes the stored entry → case 3 above).
Descriptors without an envKey (OAuth-only providers, custom providers
that bypass env-var resolution) are skipped silently.
applyEnvironmentSettingsChangeFunction#
Validate change against the kind's schema and turn it into a settings
patch + secret writes. Throws with a user-facing message on an unknown
kind or field, a value that doesn't fit its type, or disabling local.
applyMarkdownSubagentsFunction#
Fold markdown/builtin agents into the preset's spawn tool, filling gaps
only: an agent the profile or an extension already registered keeps its
definition. Runs after composeExtensionPreset, so precedence is
builtin < file < extension without threading files through composition.
assembleDiffFunction#
Tracked patch + untracked files as new-file diffs, within WORKSPACE_MAX_DIFF_BYTES.
Stops at a file boundary once the budget is spent, so the result is always
a valid patch (only an oversized FIRST file is cut, at a hunk boundary).
Untracked files are read concurrency at a time in listing order and
reading stops as soon as the budget or the file cap is reached.
Shared with sandbox workspaces.
assertEnvironmentReadyFunction#
Throws EnvironmentNotReadyError unless the environment can run.
autoInstallUpdateFunction#
Installs the release a background check found, unless something says not
to (see isAutoInstallCandidate) or another install holds the lock.
Never throws. Records a failure so the same version is not retried, and
clears the record on success.
autoInstallViaWorkerFunction#
An autoInstallUpdate-shaped function that runs the install in the
detached worker, for useAutoInstallUpdate's install seam. A lost
worker reads as a failed install.
autoTitleActionFunction#
What auto-titling should do for this session now:
generate: no title yet and the first exchange happened.check: an auto title, with enough new prompts since the last check.skip: a user title, too few turns, or checked recently.
availableAgentsFunction#
The profiles available under settings: those without a
AgentProfile.requiresSetting, or whose setting is on. Returns the
same registry object when nothing is filtered out.
availableEnvironmentActionsFunction#
The actions environment's kind offers for it right now (a ready, owned-or-shared environment).
backfillAccountEmailsFunction#
Look up the email of the stored Claude OAuth accounts that have none, and
store it on the account (or that there is none to find). Skips accounts
already looked up, accounts whose lookup failed less than
RETRY_AFTER_MS ago, expired tokens (a refresh comes first) and
tokens that are not Claude OAuth tokens. Resolves when done; never rejects.
bootProfileEnabledFunction#
Returns true when ZIDANE_BOOT_PROFILE is set. Useful for guarding
heavier instrumentation (e.g. wrapping a costly call in a span) that
you don't want paying its own cost in the default path.
bootTickFunction#
Record a checkpoint. No-op unless ZIDANE_BOOT_PROFILE is truthy in
the environment.
The leading delta is the time since the PREVIOUS tick (so a long delta highlights the immediately-preceding work); the trailing total is the time since the profiler started. Both round to one decimal of a millisecond.
buildBuildSystemFunction#
Compose the Build-mode system prompt.
Layout (top to bottom):
identity → doctrine → guidance → user instructions ─── SYSTEM_PROMPT_BOUNDARY ─── env (cwd / project root / date / platform)
Everything ABOVE the boundary is byte-stable for the lifetime of the run and rides the prompt cache across turns + sessions. The env block sits BELOW so a moved cwd or rolled-over date doesn't invalidate the doctrine.
The fragments are joined with blank lines so the model sees clean section breaks. Don't reorder lightly — every reorder costs one cache miss across every active session.
buildEditOutcomesAnnotationFunction#
Render an EditOutcome[] as the wire-format annotation block. Returns
the body to APPEND to a tool result; callers join with a leading
\n\n separator. Idempotent on missing reasons — bare applied lines
stay terse.
buildHintsFunction#
Build the footer's shortcut hints for the current screen. On the chat
screen the model id rides next to its ctrl+m shortcut and the agent
label rides next to shift+tab, each in its accent color — the bar
doubles as the status display without needing separate badges. When
the active model exposes reasoning, the ctrl+m hint grows a
secondary /l chord with the current effort label, surfacing the
effort picker as a discoverable, in-place affordance.
buildMcpServersFunction#
Map a user-toggled enable list onto the mcpServers array the agent
receives. Conventions match buildSkillsConfig:
enabled === undefined→ every discovered server enabled (default).enabled === []→ no servers (the agent runs MCP-less).enabled === [names]→ allowlist; servers not in the list are dropped.
disabledTools is the per-server tool deny-list from
Settings.disabledMcpTools. For each server that survives the
server-level enable filter, the per-tool names are merged into
McpServerConfig.disabledTools via union with anything the JSON
file already pinned — a tool listed in either source is dropped.
Union (not override) keeps JSON-side policy stable: a server file
that pins disabledTools: ['dangerous_tool'] can't be re-enabled
via the UI by accident.
enabledTools (JSON-side allowlist) takes precedence over the
UI-side deny-list when both are set on the same server — the
allowlist's "only these" semantics would be meaningless if a UI
deny-list could subtract from it again. We don't emit disabledTools
when enabledTools is present.
Returns a fresh array — callers can mutate without affecting the
underlying discovery list. Per-server config objects are also fresh
copies (shallow), so the merged disabledTools doesn't leak back
onto the discovery catalog.
buildPlanSystemFunction#
Compose the Plan-mode system prompt. Subset of Build: identity, plan-mode
doctrine (instead of DOING_TASKS_DOCTRINE), read-only token discipline,
communication, and plan-mode interaction guidance. It drops the
conventions, actions-with-care, git and subagent fragments (no shell, no
spawn in plan mode). Same boundary layout as buildBuildSystem.
buildPluginContributionsFunction#
Map the user's enabled-plugin list onto the contributions a host merges into the agent.
Conventions match enabledSkills / enabledMcps:
undefined→ every discovered plugin is enabled (default)[]→ all off[names]→ allowlist
A plugin that failed to load contributes nothing regardless of the
allowlist — ok: false means components were never discovered.
buildRestartHintFunction#
↻ v7.0.31 — a newer build is on disk than the one running (this
process is stale; see auto-update-restart.ts). Takes precedence over
the ↑ chip: once the release is installed, "available" is old news and
"restart" is the one action left. Same color contract as buildUpdateHint.
buildResumedToolResultsTurnFunction#
Build a protocol-valid user SessionTurn that closes a batch of
resumed pending interactions.
requestsMUST be the same list returned bypendingInteractionsFromTurnsfor the session, in order.responsesMUST contain an entry for every request id; throws otherwise (caller bug — flush before all answers collected).
Pure: reads no store. Tested in isolation so the batching invariant doesn't regress without the resumed-flow integration noticing.
buildRunModelFunction#
Assemble the agent.run model option from a chain.
- Single-entry chain → the bare model id string (what a single-model run passes).
- Multi-entry chain → pinned
{ provider, model }targets, whereprovideris the runtimeProvider.nameresolved viaproviderNameFor(chain entries carry chat-levelProviderKeys, which need not equal the instance names the agent loop matches on).
Throws only on an empty chain — a programmer error, since chains always carry a primary. Stale or unresolvable entries degrade defensively instead (never throw, never produce an entry the agent would reject):
- Entries whose key has no resolvable name (provider not constructed into the current agent) are dropped.
- If the PRIMARY itself doesn't resolve, or fewer than two entries survive, fall back to the bare primary model string.
contextWindowFor (optional) stamps each target with its model's
context window from the host catalog, so the loop re-bases the
auto-compact trigger when a fallback advances onto it (the host's
explicit window is sized for the PRIMARY otherwise).
buildSkillsConfigFunction#
Map a user-toggled enable list onto the format createAgent expects.
Conventions:
enabled === undefined→ all discovered skills enabled (default).enabled === []→ fully off; the agent will not scan or inject the skills tools.enabled === [names]→ allowlist; skills not in the list are left out of the catalog.
scan is the resolved scan-path list (passed through verbatim). Pass
defaultSkillScanPaths() for the standard project + user paths, or
supply a host-specific list.
buildSpawnEndEventFunction#
spawn-end marker. The facts ride on spawn.end (status, elapsed
wall-clock time, USD cost summed across the child's whole turn tree, token
totals); renderers read them through describeSpawnEnd. Most providers
don't populate cost, so it is usually absent: no "$0.00" lies. timeout
maps to done, matching the TUI.
text keeps its stored shape for clients that predate spawn.end; see
spawnEndText.
buildSpawnStartEventFunction#
spawn-start marker for a child that just launched. previewLine
collapses inline newlines/tabs so the marker stays on one visual row.
Resumed children carry the label of the run they continue in
spawn.resumes, as the reload path does.
buildToolToggleFunction#
Pure factory shared by both hook flavors. Captures persistedDenyAll
setDisabledMcpToolsat the call site so toggle handlers stay referentially stable across renders that don't touch the underlying settings entry — important foruseKeyboardto avoid re-binding on every catalog change.
Exported for direct use by non-React consumers (CLI, GUI shells) that want the same write semantics without the hook plumbing.
buildUpdateHintFunction#
Builds the ↑ vX.Y.Z hint for an available update.
Returns null when there is no newer version.
buildVisibleMcpRowsFunction#
Flatten a server catalog plus the per-server expanded set into the visible-row list a renderer cycles through.
catalog— filtered / ordered server list (post-search, post-allow-list).expanded— names of servers whose tool list is open. Servers not in this set render as a single server-header row.toolsByServer— per-server full tool catalog (fromchat/mcp-tools-cache.ts). Missing key →'tool-empty'placeholder under the expanded server.
builtinEnvironmentProvidersFunction#
Creates the built-in environment providers: local, worktree, Docker, E2B and Daytona.
builtInPromptOfFunction#
The built-in prompt a profile runs, undefined for a profile with its own.
Decided by the preset's prompt, never the profile's id: a preset that uses
Build's or Plan's built-in prompt (BUILD_AGENT.preset.system) gets it
composed with the session's environment, AGENTS.md and SYSTEM.md; a host
profile that happens to be called build keeps its own prompt.
cacheBreakNoticeTextFunction#
Transcript-row text for a persisted cache-break notice. Multi-line, one fact per line, so both hosts can show a short headline and fold or list the rest:
cache break ↑116.9k tokens ~$0.48 messagePrefix: message 16 of 41→43 rewritten likely compaction or history trimming
The footer chip stays terse; the row carries the culprit so a break is diagnosable from the transcript. Only the headline on a TTL / eviction break (nothing was done wrong).
cachedRepoKeyOfFunction#
repoKeyOf, reused for a few minutes per folder. Session lists ask
it for every row, and most rows share a few folders.
changedCatalogItemsFunction#
Every item of a catalog that extensions changed, for a Settings list.
chatAutoCompactBehaviorFunction#
Build the per-run behavior.autoCompact a chat host passes to agent.run.
Loop-native auto-compaction is the only mechanism; the TUI + GUI just
translate the user's enable/threshold settings plus the picked model's raw
context window (the SDK core has no model catalog) into the config the loop
consumes. Returns false when disabled. rawContextWindow: null (unknown
model) still enables it but leaves the trigger inert — the loop skips with
unknown-window rather than guessing.
chatReferenceTokensForPromptFunction#
Extracts the #<chat> reference tokens from a prompt.
chatWindowBehaviorFunction#
The per-run window knobs a chat host spreads into agent.run's behavior:
the auto-compaction config from chatAutoCompactBehavior PLUS the
picked model's raw window as behavior.contextWindow, so window-relative
wire budgets (compactThresholdWindowFraction) see the window even when the
user has auto-compaction switched off. Both hosts go through this so they
cannot drift: the TUI and the GUI/daemon engine hand the loop the same
shape for the same settings.
checkForUpdateFunction#
Resolve the latest available version of packageName, honoring an
on-disk TTL cache so the warm path costs zero network. Never throws —
registry failures degrade to { source: 'error', latest: null }.
Designed for boot-path usage: short timeout, swallows errors, opt-outs
for CI / restricted shells. Consumers driving the explicit upgrade
subcommand should set force: true to ignore env opt-outs.
checkPlanInvariantsFunction#
Every rule a bag must satisfy after any sequence of events. Returns the
broken rules (empty when sound). The gate's tests run random event
sequences through applyPlanEvent and assert this stays empty.
checkTarballAvailableFunction#
Whether <packageName>@<version> can actually be DOWNLOADED right now, not
merely resolved. Right after a publish the registry serves the new
manifest minutes before the tarball reaches the CDN; a package manager
that hits that window on an optionalDependencies platform binary
silently skips it and leaves a bin with nothing behind it. upgrade asks
this before spawning the PM so it can wait instead of breaking the install.
'ok'tarball responds 2xx'missing'manifest or tarball 404 (published, not propagated)'unknown'network / registry error; the caller decides
claudeImportHostNoteFunction#
What to tell the user when the window's sessions live on a remote host:
the import went to this computer, so the host's list won't show it.
null for a host on this machine (it shares the store).
cleanTitleFunction#
Normalize a model-generated title into the shape we want to persist:
- Collapse internal whitespace + take the first line only (some models emit "Title: foo\n\nReason: …" despite instructions).
- Strip surrounding quotes, a leading
Title:/title -preamble, and auser:/assistant:role prefix echoed from the transcript — repeatedly, in any nesting order. - Reject placeholders and answer-shaped replies (see
ANSWER_SHAPED_OPENER) by throwing. - Strip trailing punctuation (
.,!,?) — titles read cleaner without it. - Truncate to
TITLE_MAX_CHARSwith a trailing…when over.
Exported as cleanTitle so tests can pin the normalization rules
without going through a mock provider.
clearExtensionSourceCacheFunction#
Forgets every cached listing.
clearFailedUpdateFunction#
Forgets the failed install, so the next check may try again. Called by every manual install.
clearMcpToolsCacheFunction#
Drop entries for one or more servers, or wipe the cache when no server is named. Idempotent — entries that aren't present are silently skipped. Returns the resulting cache so callers can refresh any in-memory mirror without re-reading from disk.
Meant for a "rescan server" affordance in the settings UI
(clear → trigger a real bootstrap → cache repopulates on the
mcp:tools:list hook).
clearProviderUsageCacheFunction#
Drop every cached snapshot. Entries are keyed by credential KEY, not by the token itself, so signing out and back in (or re-authing to another account) would otherwise keep serving the previous account's numbers for the rest of the TTL. The TUI calls this when it re-reads credentials.
clipHintsToWidthFunction#
Return the longest prefix of hints whose rendered width fits within
budget. Used to degrade hint rows gracefully at narrow terminal
widths instead of letting an absolutely-positioned hint row wrap
mid-segment (which paints the overflow over surrounding borders and
looks like garbled glyphs in a TUI).
Prefix-only (no reordering, no last-hint priority) so the survivors keep their authored order — the user's muscle memory for "leftmost hint = primary action" stays intact as the terminal shrinks.
cloneRepositoryFunction#
Clones input (a git or forge URL, or owner/repo) into a new folder of
parent, calling onProgress as git reports. A folder that already holds
the same repository is opened, not cloned (existed).
commandStepsFunction#
Normalize a command to its ordered step list (steps wins over run).
commitPlanEventFunction#
Applies event to a live session's plans and persists the key before
returning. A refused or no-op event writes nothing. Without a store (a
memory-only session) the change stays in memory.
commitPlanEventToStoreFunction#
Applies event to stored session data and writes only the plans key. For
the host when no agent is live; call it under the session's run lease so
no run writes the key at the same time.
compactSummaryEventFunction#
Map a compact-summary content block to its compact-summary StreamEvent —
the single source of truth for the compaction boundary card. Used by
eventsFromTurns (reload / TUI live repaint) AND by chat hosts that
surface the boundary live without a full reload (the GUI broadcasts this
from the loop's compact:end hook), so the live card and the reloaded card
are byte-identical regardless of who created the marker (manual compaction or
loop-native auto-compaction — both share this block shape).
compareSemverFunction#
Returns -1 / 0 / 1. Unparseable inputs sort as 0 (assume equal).
compositionByKeyFunction#
The composition a key names in registry, undefined when none of its
profiles is registered any more.
compositionFitsFunction#
Whether profile runs on composition without a new agent: it is the
profile's own composition, or the profile's tools are a strict subset of
the composition's (same names and specs). Codemode scripts reach the same
tools, so a composition's tools count whether they are on the wire or not.
compositionToolsFunction#
The profile tools a composition's agent can call, by name: its base's, then each other member's that the base doesn't have.
computeTurnAnchorsFunction#
Per-item anchor ids for auto-scroll. Walks items in render order
and, for each event, returns either:
'turn-anchor-<turnId>'— the first event of this turn (the scroll target).undefined— later event of an already-tagged turn (or a synthetic event with noturnId).
ids[i] is a tuple per item: length 1 for plain events, length N
for subagent runs (one entry per inner event). idByTurn is the
inverse lookup used by the scroll effect. lastTurnId is the
most-recently-rendered turn — the scroll effect special-cases it to
snap to bottom rather than scroll the anchor into view (which would
stop short of the actual tail).
Exported so the anchor-tagging matrix can be unit-tested without rendering anything.
ConfigProviderFunction#
Provides a ResolvedConfig to the components below it.
configuredProviderFieldsFunction#
The values of a provider's non-secret custom fields set now: the stored
credential's, else the environment's. undefined when it takes none.
configureProviderCredentialFunction#
Stores a provider's API key and custom fields (a local server's URL, a
cloud's region), merged into what is stored: a field left out keeps its
value, an empty one is removed (a secret one is kept, it is never shown to
be edited), a required one may not be emptied. No value keeps the
stored key.
confineToWorkspaceFunction#
rel inside cwd (both resolved, the final symlink followed): its real path, or null when it leaves the folder.
connectorGithubTokenFunction#
A GitHub token zidane already knows (GH_TOKEN, GITHUB_TOKEN or the
gh CLI), for the GitHub connector's "Use my gh login". null when there
is none.
containedEntryPathFunction#
path (relative to cwd) as an absolute path inside it: refused (throws)
when it leaves the folder lexically or its parent folder real-paths out.
countClaudeSessionFilesFunction#
Detection-preview counts — scoped and all-projects figures from ONE
directory walk (the naive two-listing approach reads every project dir
twice). The scoped classification (with its per-file cwd peek for
candidate dirs) runs at most once per file via the lazy scoped()
thunk.
createApprovalHubFunction#
Creates an approval hub that broadcasts requests and persists them until they are resolved.
createArtifactKindsHostFunction#
Creates the kind registry of one registry build.
createArtifactsCompletionProviderFunction#
Creates a completion provider for # artifact references.
The provider only suggests. It inserts the artifact's locator as plain text, so it parses no references back.
createAutomaticInteractionResponseFunction#
Build the deterministic response used when the host skips interaction UI.
createCapabilityProbeFunction#
Builds the host.capabilities probe: call it for the cached result (a minute old at most), or with refresh to probe again.
createCatalogPortsFunction#
Builds the base port of every extension catalog from zidane's sources. The
extension runtime passes each to its catalog factory, then links models to providers
with linkCatalogs.
createChatHostFunction#
The composition root: creates the shared host state (context.ts) and the
feature modules, wires them to each other, and assembles the ChatHost.
Features never import this module. Where a feature needs one built after
it, it gets one of the hoisted forwarders at the bottom of this function
(only ever called at runtime, after construction).
createChatTurnsReadToolFunction#
Creates the read_chat_turns tool, which reads turns of a previous chat the user referenced with #<chat>. Chats that were not referenced are refused.
createDiscoverySlotFunction#
Creates a slot that loads a list lazily and keeps it fresh.
ensure() starts the first walk once and schedules throttled background refreshes. refresh() forces a walk. Every successful walk result goes to onLoad.
createEnvironmentRegistryFunction#
A registry of providers. Hosts pass the chat layer's built-ins
(builtinEnvironmentProviders, which include local) plus any extras; a
registry without local can still create local sessions (an absent
environment IS local) but can't resolve their execution.
createExtensionMcpHostFunction#
Creates the MCP host behind ctx.mcp. Connections are pooled per (cwd, server config) and closed after idleMs without a call.
createFileEnvironmentSecretsFunction#
Creates EnvironmentSecrets backed by environment-credentials.json in dataDir.
Reads tolerate a missing or corrupt file. A write to a corrupt file moves it aside first. Setting a value to null removes it.
createFileMcpCredentialStoreFunction#
Build a file-backed McpCredentialStore. All per-server reads / writes
funnel through the single mcp-credentials.json file — this keeps
concurrent flows for different servers from clobbering each other since
each save reads-modifies-writes the full file atomically.
Two flows for the same server name CAN race (last write wins). MCP OAuth flows are user-driven and serial in practice (one login modal at a time), so this is acceptable; a per-server file split + cross-process lock would be required to handle a multi-process scenario.
createGitWatchesFunction#
Repository watchers keyed by folder, shared by counted owners.
createHostRegistryFunction#
Creates a host registry backed by hosts.json and the credentials store in options.dataDir.
createInteractionHubFunction#
Creates an interaction hub backed by a session store.
createInteractionToolsFunction#
Create the present_plan and ask_user tools as a record, ready to
spread into createAgent({ tools }) or composed into a Preset.
createMainSessionFunction#
Create the orchestration main session; returns its id.
Directory-less on purpose. The main is GLOBAL — one per store, orchestrating sessions in many directories — so binding it to whichever cwd happened to be active when the toggle flipped put it in that project's group and hid it from every other project's list. With no cwd it sits in the "Chats" bucket and its own tools run from HOME, which is the only directory that is always the user's and never a project's.
createMcpStatusTrackerFunction#
A host's MCP server states.
createMemoryApprovalsStoreFunction#
In-memory fallback when the host doesn't provide durable persistence.
createMemoryEnvironmentSecretsFunction#
In-memory secrets — tests and hosts without a data dir.
createPathAutocompleteProviderFunction#
Built-in provider: complete filesystem paths under cwd (or absolute /
~ paths). Given the token src/chat/comp, lists src/chat/ and
returns every matching continuation of comp as a candidate list —
directories first, alphabetical, /-terminated for directories so
typing can continue. The host ghosts the first candidate and rotates
through the rest on up/down.
Bare tokens (no / yet) are matched against the cwd listing too, so
a directory ghost appears as soon as the first characters of src
are typed — but only from the second character on, so 1-letter prose
words don't ghost-spam.
Dotfiles are only offered when the typed fragment itself starts with
. — the usual completion convention.
createPlanLifecycleHooksFunction#
Hooks that close plans when runs end, and remind a run once about open steps.
createPlanToolsFunction#
The { todowrite, todoread } tools plus the plan lifecycle hooks (the
open-steps reminder, closing a run's plans when it ends).
createAgent({ ...composePresets(basic, createPlanTools()), provider })
createPromptSubmissionsFunction#
The submit entry points over a host.
createProviderBuilderFunction#
The host's ProviderBuilder: it applies stored credentials to the
environment before each build, so a provider always sees the current ones.
createSessionExecutionCacheFunction#
Creates an empty SessionExecutionCache.
Handles are spawned lazily on first use and destroyed on release, key replacement, or host shutdown.
createSessionInStoreFunction#
Create and persist a session; returns its id.
createStateStoreFunction#
Creates a StateStoreApi backed by the JSON file at path.
createWorktreeEnvironmentProviderFunction#
Creates the provider for worktree environments: each session gets its own branch in a linked git worktree.
credentialSlotOfFunction#
The slot key currently holding the credential whose stable id is id, or
undefined when none of fileKey's slots does (signed out, removed).
Slot keys are positional — promoting an account swaps entries between them — so anything that must keep naming ONE account (a session pinned to it) stores the id and asks here on every use, never the key.
credentialsPathFunction#
Resolve the credentials file path given the resolved TUI data directory
(typically ~/.zidane, i.e. config.paths.dir).
Matches the convention used elsewhere in the TUI (sessions.db, state.json)
so a single ZIDANE_STORAGE_DIR override moves the entire data root.
credKeyOfFunction#
Convenience accessor — returns credentialFileKey ?? key.
decideEventFunction#
The decide event for a plan request's answer, or null for a response
that is not a plan decision.
dedupMcpServersByNameFunction#
Dedup a merged MCP-server list by name. First entry wins.
Applied at agent build across every source that can contribute a server —
mcps.json, Agent Plugins, launch options, extensions — so the earliest
source in that order takes precedence.
Drops are REPORTED rather than silent, via onDropped. A plugin shipping a
github server loses to a github in mcps.json, and nothing downstream
says so: the plugin's settings row still counts the server it shipped,
because the row renders what the PACKAGE declares and only this merge knows
what survived. That mirrors how the skills side reports the same class of
event — resolveSkills emits name-collision-shadowed on the winner rather
than annotating the loser.
The reporter is injected rather than calling a logger directly so this stays
a pure function of its input, testable without a logging shim. It lives here
beside buildMcpServers rather than in the TUI because merge
precedence is a config concern, not a rendering one.
defaultEnvironmentKindFunction#
The default kind for new sessions: the configured one when registered and enabled, else local.
defaultMcpsConfigPathsFunction#
Search order for MCP config files — see projectUserPaths.
Both mcps.json (zidane's canonical name) and mcp.json (Cursor /
common ecosystem alias) are picked up from every search root. The
canonical name wins within the same directory; across files the
usual first-found-by-name dedup applies, so mcp.json effectively
merges its non-overlapping entries on top of mcps.json.
Order per scope (project beats user):
{project}/.agents/mcps.json{project}/.agents/mcp.json{project}/.{prefix}/mcps.json{project}/.{prefix}/mcp.json~/.agents/mcps.json~/.agents/mcp.json~/.{prefix}/mcps.json~/.{prefix}/mcp.json
Non-existent files are skipped without error.
defaultModelOfFunction#
The model a session with no pick runs on: the descriptor's default, else
DEFAULT_MODEL_PICK.
defaultSkillScanPathsFunction#
Resolve the default skill scan paths for a project. First-found wins on collision; earlier entries take precedence.
Search order — see projectUserPaths. Non-existent paths are
returned so downstream code can choose whether to create them;
discoverSkills itself skips missing dirs without error.
deleteSessionDataFunction#
Delete a session's persisted data: the store row, then every on-disk
artifact it owns — the session-first tree (<userDir>/sessions/<id>/:
blobs, task logs, MCP warnings) plus the two pre-session-first locations
migration leaves behind. Blob cleanup is best-effort and never throws; it
runs AFTER the row delete so a cleanup failure can't leave a live row
pointing at removed blobs.
Does NOT stop a live agent — hosts must retire it first (see
ChatHost.deleteSession), or its next save resurrects the row.
deriveSessionTitleFunction#
Display title for a session — preferred sources, in order:
metadata.titleif it's a non-empty string (typically set by the session-details modal's "generate title" action), on one line (oneLineTitle): whatever wrote it, a title never wraps.titleFromTurns— the first user message, one-line + clipped.DEFAULT_SESSION_TITLE('New session').
Total / pure / defensive on non-string metadata values.
describeEnvironmentsFunction#
Every registered kind, described for cwd — what environments.list returns.
describeForkFailureFunction#
The error a user sees when a fork is refused, the same on every surface.
describeTitleStatusFunction#
Session details' title facts, one badge each: where the title came from and
what the last auto-title attempt did, e.g. auto checked 5m ago, still fits or auto check failed 2m ago (unavailable: needs a platform key).
describeUpdateLockHolderFunction#
One line for people: the desktop app (pid 4242, started 3 min ago).
detectAuthFunction#
Detect available auth for every registered provider.
A method appears in methods for every layer that has a credential:
kind: 'apikey'fromcredentials.json(injected into env at TUI launch)- explicit env var (descriptor's
envKey) kind: 'oauth'fromcredentials.json(migrated on first read from a legacy.credentials.json, seereadCredentials), one per stored account
The preferred credential lives in the canonical file key and is flagged
AuthMethod.active; the others sit in sibling slots and are reported
too, keyed by AuthMethod.key, so the UI can offer to promote or
remove them. Order within methods is presentational — active first — not a
resolution order, because the active flag answers that directly.
Never refreshes tokens or rewrites existing credentials. The one write is
the first-read migration of a legacy .credentials.json when
credentials.json does not exist yet (see readCredentials).
detectLibcFunction#
Mirrors tui/bin/zidane.mjs#detectLibc. Reports 'glibc' off Linux and 'musl' when ldd --version fails or names musl.
detectOnboardingEnvironmentFunction#
Everything the wizard shows it found: providers and their credentials, other agents, the GitHub login, local model servers and the install signals. The GitHub lookup and the server probe run in parallel.
detectOtherAgentsFunction#
The coding agents whose setup exists on this computer, for the user or for
the current project. They are Claude Code (~/.claude, .claude/), Codex
(.codex/) and Pi (.pi/).
detectPackageManagerFunction#
Chooses the package manager command that installs the package globally.
Checks the binary path, then the npm user agent, then environment hints such as VOLTA_HOME, and falls back to npm.
discoverAgentsMdFunction#
Walk the candidate paths and load every AGENTS.md that exists.
Project paths anchor at the git root when one exists above cwd,
else at cwd itself — same anchor logic as projectUserPaths so the
three discovery surfaces (skills, mcps, AGENTS.md) stay in lock-step.
All matching files are loaded (no shadowing within a scope). Empty or whitespace-only files are skipped. Render order matches the search order — broader scopes first, narrower scopes last so the project-specific file lands closest to the conversation.
Tolerant on read failures: an unreadable file is skipped silently
(logged under ZIDANE_DEBUG). The loader never throws — bootstrap
paths can't afford to crash on a permission glitch.
Defensive dedup: when <git-root> === ~ (the user launched zidane
directly from $HOME and $HOME happens to be a git repo) the
project + user candidate sets would otherwise overlap. We dedup by
absolute path so the same file never lands in the block twice.
discoverProjectMcpsFunction#
Walk the default config paths, parse every file that exists, and return
{ servers, errors } in source-priority order. Project entries appear
before user entries; first occurrence of a name wins (later
duplicates dropped).
Parse failures are captured into errors rather than thrown — the picker
surfaces them while still showing whatever DID parse. A ZIDANE_DEBUG
log line is also emitted for ops visibility.
discoverProjectPluginsFunction#
Load every plugin reachable from the default search roots.
Each immediate child directory of a root is one plugin — the same
depth-1 rule the spec applies inside skills/. A child that isn't a
directory, or that holds no plugin.json, is silently skipped: dropping a
README next to your plugins is not an error.
Dedup is by plugin NAME, not directory name, because the manifest owns
identity — two directories called tools/ shipping different plugins are
two plugins, and one plugin vendored at two scopes is one plugin.
discoverProjectSkillsFunction#
Discover every skill reachable from the default scan paths. Returns
parsed SkillConfigs with name, description, frontmatter, and
lenient-load diagnostics. Pure I/O — does not activate or write.
signal is forwarded to discoverSkills so the TUI's directory-watch
effect can cancel a long scan when the user switches cwd rapidly.
Errors during parse are surfaced as diagnostics on the returned
skill, not thrown — keeps the picker usable even when a single
SKILL.md is malformed.
discoverSystemMdFunction#
Find the active SYSTEM.md override, if any.
Project paths anchor at the git root when one exists above cwd, else at
cwd — the same anchor as skills / mcps / AGENTS.md discovery, so all four
surfaces agree on what "this project" means.
Tolerant: an unreadable or empty file is treated as absent (logged under
ZIDANE_DEBUG) and the next candidate gets its turn. Never throws — this
runs on the session-activation path.
Candidates are filtered by DiscoverSystemMdOptions.scope, mirroring
how discoverAgentsMd builds its own list.
DiscoveryProviderFunction#
Provides a DiscoveryContextValue to the components below it.
emptyPlansBagFunction#
An empty bag.
enabledModelOptionsFunction#
Normalize a model-options blob to an enabled-only { id: true } map.
Single source of truth shared by every surface that reads or persists model
options — the TUI run path, the GUI engine reader, and the GUI IPC handlers.
Tolerant of arbitrary input (persisted JSON metadata may be anything): a
non-object → {}, and only entries strictly equal to true survive. This
keeps the persisted shape minimal (no { fast: false } noise) and means
callers never forward a disabled option to agent.run.
ensureCredentialIdsFunction#
Give every stored credential its stable id, once. Files from before ids (and entries written by tools that replace them wholesale) are otherwise only id-less until their next write; run at config resolve so pickers can pin any listed account. No-op (no write) when every entry has one, or no file exists.
ensureKeybindingsFileFunction#
Create the user-level keybindings.json if it doesn't exist,
prefilled with every default. Returns the absolute file path either
way so the caller can open it in $EDITOR. Idempotent: an existing
user file is NEVER overwritten — the user's customizations are
sacred.
environmentActionSummariesFunction#
availableEnvironmentActions, wire-safe.
environmentCredentialsPathFunction#
Returns the path of the environment credentials file inside the data directory.
envSectionFunction#
Render the env anchor block. Plain text — XML tags only because models lean on them as structural cues, not because we parse them anywhere.
Kept narrow on purpose: cwd / projectRoot / date / platform are the knobs the model can't infer from the conversation. Anything else (git branch, project name) belongs in CLAUDE.md / project-level prompts where the user opts in.
Cache-stability: outputs are byte-stable per (cwd, projectRoot, date, platform) tuple. Repeated session activations against the
same workspace produce the same prefix → provider's prompt cache
hits across turns + across sessions in the same host process.
eventsFromTurnsFunction#
Replays persisted turns as a viewable transcript. Equivalent to replayTurns(turns, runs).events.
Mirrors the event shape produced live by the agent hooks so loaded and
streaming history render identically, including subagent ancestry when
runs is supplied:
- Every turn carries a
runId, looked up inrunsto get the run'sdepth. The resulting events carry{ depth, childId }, the same shape the livechild:*bubble hooks produce. spawn-start/spawn-endmarkers land at each child-run boundary, so the transcript reads the same as a live run did.- For child runs (
depth > 0), the user-role "task" text is suppressed becausespawn-startalready shows it.
executeCommandFunction#
Run a command's steps in order, threading ctx.data. Stops at the first
step that throws (error isolated + returned, not rethrown) or when the
signal aborts. Pure orchestration — all I/O lives in the host-supplied
ctx capabilities.
exportFilenameFunction#
Compose the on-disk filename for (sessionId, format). Rejects
empty ids and path-traversal-ish values so the caller can't escape
.{prefix}/sessions/.
extractEditPayloadForGateFunction#
Gate-time extractEditPayload wrapper — same as tool:before but
without the prior-content second pass for write_file. The gate
only needs the payload shape (hunk count, paths) to drive the
approval surface; the diff resolver works against the freshly-read
priorContent passed to previewEditPayload directly.
fetchAllProviderUsageFunction#
Usage for every registered provider that has both a usage surface and a usable credential, in registry order, every account included.
fetchGithubUsageFunction#
GitHub's limits per host, in the shape the Usage panel renders. Never rejects.
fetchOAuthRedirectFunction#
Treat pasted as a callback-URL paste. Validates it's a loopback URL,
fires a GET, returns the status.
Pass authUrl (the authorization URL currently on screen) to accept
partial pastes — a bare code, a query string, a path — via
normalizeRedirectPaste. Without it only a full absolute URL is
accepted.
Throws when:
pasteddoesn't parse as a URL (and can't be completed fromauthUrl).- The URL host isn't loopback (rejects SSRF).
- The fetch errors out (network, timeout).
Returns success/failure for non-2xx responses; the caller decides whether a 4xx is fatal (state mismatch is a 400 the user can retry from).
fetchProviderUsageFunction#
Usage for one provider, probed with the credential requests use — or, when that one is not the kind the probe needs (an API key in use, OAuth accounts parked beside it), the first stored one that is. What the footer shows.
null means there is nothing to show: the provider has no usage surface,
no credential of the kind its probe needs (file or, for API keys, env), or
the environment opted out (see usageChecksOptedOut).
Never rejects. Transport and parse failures land in the snapshot.
fetchProviderUsageAccountsFunction#
Usage for EVERY credential of a provider the probe can use — one snapshot
per stored OAuth account, the active one first. What the panel renders.
Empty under the same conditions fetchProviderUsage returns null.
fetchRepoInfoFunction#
The info of the repository input names (what the import dialog would clone); null when there is none.
fileEntriesFromPathsFunction#
File entries (plus their ancestor dirs) from relative paths — what
listProjectFiles returns, for lists produced elsewhere (a remote
sandbox's git ls-files).
filterChainFallbacksFunction#
Filter candidate fallback entries against a primary pick, preserving
picked order: entries whose provider isAvailable rejects, entries
equal to the primary, and exact duplicates drop. Shared by the
picker's apply path (live-auth availability) and persisted-chain
restore (registry availability).
One account per provider: a chain runs each provider as ONE instance bound to one account, so an entry naming another account of a provider already in the chain (the primary's, or an earlier fallback's) drops — it would otherwise run on the wrong account.
findGitRootFunction#
Walk parents of cwd looking for a .git entry. Returns the
absolute path of the directory containing .git — the CHECKOUT root
(a linked worktree's own dir, not its main checkout) — or null when
no git repo is found above cwd.
Stops at the filesystem root (/) — no infinite loop on dirname's
idempotent root case (dirname('/') returns /).
findInstalledCompanionFunction#
Locate a globally installed companion. null when its bin is not on PATH
or no package.json with that name can be found behind it.
findProjectRootFunction#
The project cwd belongs to: the main checkout for a linked worktree,
the checkout root otherwise, null outside git. See the module header
for when to use this vs findGitRoot.
folderlessCwdFunction#
Process cwd used for sessions with no folder binding.
folderLocationFunction#
The checkout and the project of cwd: @ lists the checkout's files, # the project's chats.
followRunningUpdateFunction#
Attaches to an install that is already running (a surface that starts while
another one's worker installs). null when no live install holds the lock.
Otherwise resolves once the lock is released: the worker's result, or
null when the holder was not a worker (zidane upgrade --in-place) or
left no result.
forgetGitCachesFunction#
The repository at at moved (git:refs): its default branch is read
again. A remote changed (git:config): its pull requests are another
repository's, so those go too. PR answers otherwise stay on a refs change:
the window already asks fresh then, and their backoff must outlive a
burst of commits.
forkSessionFunction#
Create and persist a new session whose history is the parent's turns up to
and including turnId. The parent is untouched.
Carries: the protocol-clean turn prefix, the run records those turns
reference (so run stats survive and the next run can't re-mint run_1
over an existing reference), persisted-output blobs (copied and re-pointed),
projectRoot (a fork belongs to its parent's project, wherever it was
forked from), agentId, FORK_INHERITED_METADATA_KEYS, and the
parent's environment — marked not-owned: the fork runs in the same
worktree / sandbox but deleting it never tears that down. Refused while
the parent's environment isn't ready: nothing would provision the fork's
copy, and provisioning it would mint an environment nobody owns.
formatBindingForDisplayFunction#
Render a binding spec ("ctrl+return", "backspace", "delete") as a
compact display string the user recognizes at a glance. Substitutes
arrow / enter / backspace glyphs for their verbose names so the hint
row stays narrow; modifier names + plain keys pass through unchanged.
Empty / missing specs return an empty string — callers decide whether
to render a placeholder (e.g. '—' for an unbound action in the
keybindings panel) or hide the surface entirely (e.g. hint rows that
fall back to a different chord when the binding is empty).
formatPathForCwdFunction#
Convert a project-root-relative path (as emitted by listProjectFiles)
into the form the agent's tools — and the user — will actually find
given the current cwd.
Inputs:
projectRelativePath— forward-slashed, no leading slash. Returned verbatim when it's empty or already absolute (defensive — the absolute-input branch is the de-facto "outside the project" escape; the catalog itself never emits absolute paths).projectRoot— absolute path of the discovery anchor.cwd— absolute path ofprocess.cwd()at the moment of insertion.
Output is always either an absolute path (only when the input arrived
absolute) OR a CWD-relative path. The relative form may include
../ segments when the target sits above cwd within the project,
which keeps cross-tree references short and scannable
(e.g. ../EDIT_THIS.md instead of /Users/.../zidane/EDIT_THIS.md).
formatPlanForModelFunction#
The plan as the model reads it: a header, then one line per step. Goes into tool results and transcript notes, which never change once written, so it costs the prompt cache nothing. Never includes times.
formatStoppedNoticeFunction#
The one line the agent gets on the next prompt about a plan that stopped: how to continue it, and that leaving it is fine.
generateStructuredDataFunction#
Drive one schema-pinned provider call and return the conforming payload. Throws when the provider returns no structured payload (and rethrows aborts verbatim). The caller owns presentation — nothing is rendered or persisted here.
Pass a zod v4 schema and the return type is inferred from it; pass a plain JSON Schema object and name the type via the generic.
getContextWindowFunction#
Look up the model's max context window via the descriptor's model source.
Falls back to ProviderDescriptor.contextWindowEnvVar (parsed via
resolveContextWindow, which supports a per-model map) when the
registry has nothing — this is how local LLMs, whose runtimes don't
advertise a window, get one. Returns null when neither source resolves a
value (custom slugs, providers without a registry or a configured window);
callers should hide the context indicator and skip auto-compaction then.
getMcpAuthStatusFunction#
Convenience getter — treats undefined as idle.
getModelInfoFunction#
Resolve a single model's metadata via the descriptor's model source.
Mirrors modelsForDescriptor routing: descriptor's own list wins,
pi-ai's registry is the fallback. Returns null when the model isn't
known.
getSafelistFunction#
Read the safelist for one project. Returns [] for unknown projects.
getSafelistForCwdFunction#
The safelist in effect for a working directory — what every host's gate
must read. The project's entries (safelistProjectKey), plus
entries saved under older keys for the same place, still honored but never
written again:
- the CHECKOUT root — the TUI keyed a linked worktree by its own dir before worktrees resolved to their main checkout;
- the exact
cwd— the daemon/GUI keyed by raw cwd before keys were normalized to the project.
getSessionHeaderFunction#
One session's header, without reading its turns when the store keeps a
header index (getMeta). A full load when it doesn't, or when the title
still has to be derived from the first message.
gitBranchesFunction#
The local branches, most recently committed first, each against the default branch (the recent ones within a budget).
gitCommitFunction#
One commit's subject, author, date and size. Only a sha-shaped argument reaches git (never an option or a range).
gitCreateBranchFunction#
git switch -c <name> from where the checkout stands, uncommitted changes
carried. Refused while running, for a name git rejects, or one that exists.
gitDiffFunction#
Unified diff of the working tree vs HEAD (staged + unstaged), plus untracked
files as new-file diffs.
context is the unified-context line count; Infinity yields whole
files so a viewer can show every line with the changes marked.
githubRepoOfFunction#
The owner and repository of a GitHub clone URL (https, scp-like or ssh); null for another host.
gitInfoFunction#
Where the checkout at cwd stands (branch, upstream, ahead / behind, uncommitted changes), the composer's git bar; null outside a checkout.
gitOriginUrlFunction#
The origin URL of the checkout holding dir, as written in its config; null outside git, without an
origin, or when git is missing. Clone on send hands it to a server to clone.
gitPrFunction#
The branch's open PR. None for the default branch (gh is not asked:
pull requests come from other branches). Cached per branch: a minute while
one is open; five minutes when there is none; half an hour once it is merged
or closed (history doesn't move); a push or a branch switch asks again with
fresh. After failures the wait doubles up to ten minutes. While GitHub
rate-limits gh, the cached answer stands.
gitPrListFunction#
Open pull requests for the switcher; null when gh is missing or signed
out; { rateLimited } when GitHub refused and nothing is cached.
- no query: three lists fetched apart, so a busy repository never pushes
yours or the ones waiting on you out of view:
review-requested:@me(your teams included),--author @me, and the most recent others. - a query: GitHub's own search over every open PR (
--search), so a repository with thousands of them is searchable from here.
gitShowHeadFunction#
Contents of path at HEAD (for split views of tracked changes).
gitStatusFunction#
Each changed path's status against HEAD, untracked files included; empty outside a repository.
gitStatusOfFunction#
File entries from run (git status --porcelain=v1 -z --untracked-files=<mode>; null: it failed). Every untracked file
first; when that fails (a folder nobody ignored, like a fresh
node_modules, overflows the output or the time) again with such
folders as one record, which parseGitStatus drops: the tracked changes
survive. Shared with sandbox workspaces.
gitSwitchFunction#
git switch <branch>. Refused while running (the session's agent is at
work: its files must not change under it); otherwise git decides, and its
refusal comes back summarized.
gitSyncFunction#
One sync per folder at a time: a second click joins the first.
groupArtifactsFunction#
Group by kind (built-ins first in a fixed order, then extension kinds alphabetically); rows inside a group keep the store's newest-first order.
groupBindingsFunction#
Walk KEYBINDING_DEFS in order and bucket rows into contiguous
sections by group. Shared between the standalone KeybindingsModal
and the Keybindings tab inside SettingsModal so both surfaces
render the same catalog with the same ordering rules.
Pass extensionRows (resolved extension keybindings paired with
their definitions) to append an "Extensions" section at the end so
extension-contributed shortcuts are discoverable in the same UI.
hasClaudeCodeSetupFunction#
Whether ~/.claude exists. The setup wizard uses it to detect Claude Code.
hasUntimedOpenCallsFunction#
Whether a call, a subagent's included, has neither a result nor a start: a call that may still be running, untimed. A page without one needs no running work.
hasUpdateAppliedMarkerFunction#
Quick existence check so hosts can decide whether to read the marker at all.
headerFromDataFunction#
SessionHeader of a fully materialized session.
hintsLengthFunction#
Plain-text width estimate for a list of Hints rendered as a
hint row (keys, labels, HINT_GAP between hints). Exported so
prompt-box overlays can run the same responsive math as the bottom-bar
footer when deciding whether trigger hints fit. Pure / total.
hostCredentialKeyFunction#
Where a host's token lives in the credentials store.
hostImportItemsFunction#
Absolute paths of this machine as import items (a drop headed for a folder
elsewhere: a sandbox, a server): files read when their turn comes, folders
walked one entry at a time. Symlinks and special files are left out.
The walk stops once the import limits are passed: what it returns then is
still over them, so importEntries refuses it without a whole tree read.
hostsFilePathFunction#
Returns the path of the file that stores the saved hosts.
imageGenerationToolsFunction#
The generate_image tool for a chat session, keyed by name: empty when
Settings.imageGeneration is off or no connected provider can generate
images. Settings.imageModel picks the default model; a stale pick falls
back to the first available provider's default.
imageModelSourcesFunction#
The providers a session can generate images with: every provider with
image models whose instance builds and reports itself available, keyed by
provider key (the <provider> of generate_image's model argument).
importFromClaudeCodeFunction#
Import Claude Code data from THIS machine into THIS machine: store must
be the local session store (never a remote host's), MCP servers, skills,
commands and subagents go to this machine's .zidane files. Pass activeHost (the
window's host) to get the remote-host note in notes.
indexOfServerRowFunction#
Index in rows of the server header for the given parent name. -1
when not present. Used by collapse handlers to snap the cursor up
to the parent BEFORE shrinking the row list — otherwise the cursor
would land on whichever sibling row now occupies the same flat
index.
InteractionsProviderFunction#
React provider that holds the FIFO queue of pending interactions. Pending entries are cancelled when it unmounts.
invalidateDiagnosticsFunction#
Forget cached runs for cwd (after our own writes / tool results). A run in progress still answers the requests it has, but no later one.
isAccountCredKeyFunction#
True when key is one of fileKey's #account:N slots.
isAutoInstallCandidateFunction#
Whether a check result is one an automatic install may act on: a newer
release on the latest dist-tag read from the registry just now (not a
stale cache), not a prerelease, not opted out by env, and not a version
that failed before (see AUTO_INSTALL_RETRY_BACKOFF_MS).
isEnvironmentEnabledFunction#
Whether kind may be picked. local always can: it is the fallback. An
offByDefault provider needs turning on first — pass it to honour that.
isInteractionToolFunction#
True when name is one of the interaction tool canonical names.
isMcpAuthRefusalFunction#
A refusal for want of credentials: HTTP 401 / 403, however the SDK words it.
isModelInteractionFunction#
Whether a queued request came from a model tool call. Automatic mode answers on the model's behalf, so it must leave host-originated prompts alone: their consumer is local code awaiting a real decision, with no model on the other end to act on an instruction sentence.
isOnSafelistFunction#
True when a call matches ANY entry in the project's safelist (or is implicitly safe).
For shell commands, the full command string is parsed into individual
commands (handling &&, ||, ;, |, $(…), backticks, subshells).
Every command head must be covered by at least one safelist entry for
the call to pass. If parsing fails, returns false (prompt the user).
isReservedCredKeyFunction#
True when a key claims a reserved slot namespace.
Built-in keys are plain identifiers (anthropic, openai-codex), but
ProviderDescriptor.key / credentialFileKey are open strings — so the
reservation is checked, not assumed.
isSecretCustomFieldFunction#
Whether a provider's custom field holds a secret (never sent back, kept when left blank).
isStaleRunMarkerFunction#
A stored running status older than STALE_RUN_MARKER_MS whose
owner no longer holds it, or held by a dead owner: a run whose process
died before settling it. Lists show it idle unless a host says the session
runs.
isTitleStaleFunction#
Ask the decision model whether title is stale. A failed decision comes
back as failure (no answer is not a "keep": the caller retries later).
isTodoToolFunction#
True when name is one of the todo tool canonical names.
isTransientFailureFunction#
Whether every failure in the run may pass on its own: the registry could not be read, the release is not downloadable yet, or the package manager timed out. A package-manager error or a wrong version on disk is not.
isUpdateLockStaleFunction#
Whether a lock no longer protects a running install: its process is gone
on this host, a live one is older than UPDATE_LOCK_LIVE_STALE_MS,
or a holder that can't be probed is older than UPDATE_LOCK_STALE_MS.
isWindowOnlySettingFunction#
Tells whether a settings key stays with the window instead of the host.
keybindingsPathFunction#
Path of the user-level keybindings file.
lastContextSizeFromTurnsFunction#
Effective context size of the most recent assistant turn — drives the footer
indicator. Walk from the end of turns and return the cache-aware input-token total
of the most recent parent (depth-0) assistant turn. Subagent turns
are skipped because their context window is the child's, not the parent's
— surfacing a subagent's usage.input as the footer's "context used"
after a session ends mid-spawn would be misleading. The next prompt
feeds the parent, so the parent's last view is what matters.
Zero-context placeholder turns are also skipped. executeTurn
synthesizes an assistant turn with usage: { input: 0, output: 0 }
when the provider stream throws / aborts before any usage is reported
(see src/loop-turn-stream.ts's catch path) — that turn is purely a shape
contract for resume, not a real context-window measurement. Without
the skip, an abort mid-stream shadows the prior real turn and the
footer reads ctx 0 on the next session load even though earlier
turns accumulated meaningful context (and run.cost).
runs is optional. Without it depth is unknown, so every assistant turn
qualifies.
linkCatalogsFunction#
Keeps the models catalog in step with the providers catalog: the models base is the providers' models after their transforms, so every provider change reloads it. Returns the unsubscribe.
listDecisionModelsFunction#
Decision models of the signed-in providers, in provider order. Providers
whose credentials can't send decisions are listed with available: false
and a reason, so pickers can say why.
listDiagnosticsToolsFunction#
The diagnostics tools and whether each runs for cwd.
listExtensionSourceFunction#
Lists the extensions of a source, with what installs each one. Never
throws: a source that cannot be read gives an empty list and error,
except the default source (Tahul/zidane), which then lists the native
catalog shipped in the app (builtin: true) with the error.
listImageModelsFunction#
Image models of the signed-in providers, in provider order. Providers whose
credentials cannot generate images are listed with available: false and a
reason, so pickers can say why.
listProjectFilesFunction#
Discover every non-ignored file under cwd, plus the directories that
contain them (derived from the file paths, kind: 'dir'). Tries
git ls-files first; on failure (no git, not a repo, abort) walks the
fs with a hand-rolled skip list.
Errors are not thrown — the function always returns an array (possibly
empty). Callers wanting failure diagnostics can opt into them via
ZIDANE_DEBUG.
listSafelistsFunction#
Every project with at least one safelist entry.
listSessionMetaFunction#
Load every session and project it to the compact SessionMeta shape used by
the picker. Sorted by recency via the underlying store's list() contract
(sqlite store returns by updated_at DESC). /side sessions are left out,
like every session list (isSideSession).
Robust to per-row failures: Promise.allSettled so a single corrupt or
unreadable row (malformed JSON, partial write, transient I/O error)
doesn't take down the entire picker. Failed rows are silently skipped;
a stderr line is emitted under ZIDANE_DEBUG for diagnosis.
listWorkspaceFunction#
Whole tree as relative paths (dirs implied, explicit trailing / for
empty dirs), bounded. .gitignore is honoured through one
git ls-files call (instant, unlike git status --ignored, which walks
node_modules and can take tens of seconds on a real repo); pass
showIgnored to include ignored entries, flagged so the tree can dim
them. .git itself is never listed.
An ignored folder is one node (dist/, ignored), never walked: list it
with dir when the user opens it, which walks that folder the same way
(its ignored subfolders one node each again), so a node_modules-sized
folder costs one readdir per level opened. Past the entry cap the
listing is cut and says so (truncated).
liveAgentProfilesFunction#
A resolved config's agent profiles as the extension agents catalog has
them now. config.agents is overlaid once, when the config is resolved;
an extension registers profiles later too (one per bot it creates), and a
host that caches its config would never offer or build them. Read profiles
through this wherever a config outlives a catalog change.
loadMarkdownAgentsFunction#
Builtin Explore/Plan plus markdown agents. User-scope files override builtins (project files are refused with a diagnostic); among files, first-wins by name in root order. Never throws.
loadMarkdownCommandsFunction#
Markdown slash commands, first-wins by name in root order. Never throws.
loadMcpToolsCacheFunction#
Best-effort cache read. Returns {} when the file is missing, when
JSON.parse rejects, or when the top-level shape isn't a plain object —
a corrupt cache must never crash the host on startup.
Per-entry shape validation is light (presence of an array tools):
deeper validation would lock the cache to a single zidane version,
which is the opposite of what a long-lived cache wants. Entries that
survive the light check feed back through McpToolSchema's unknown
inputSchema so downstream readers stay tolerant of upstream churn.
loadStateFunction#
Reads the TUI state file. Returns {} when it is missing or unreadable.
localDayStringFunction#
Local YYYY-MM-DD of a date, as SQLite's date(…, 'localtime') buckets it.
mainCheckoutRootFunction#
The main checkout a LINKED WORKTREE belongs to, or null when
checkoutRoot is not one. Does not walk: checkoutRoot must be a
checkout root (what findGitRoot returns).
A linked worktree's .git is a file (gitdir: <main>/.git/worktrees/<name>)
and that gitdir holds a commondir file pointing back at the shared
<main>/.git. Everything else resolves to null and stays its own
project:
- a regular checkout (
.gitis a directory); - a submodule (its gitdir has no
commondir— a submodule IS a separate repo); - a worktree of a bare repo or of a
--separate-git-dirrepo (the common dir isn't a.gitinside a working tree, so there is no main checkout to belong to); - anything unreadable or malformed.
makeRequestInteractionFunction#
Build the requestInteraction callback for createInteractionTools from
the React-side InteractionsActions. Each call adds a fresh entry
to the queue whose resolve / cancel route back to one Promise that
the tool's execute awaits.
makeToolContextFunction#
A folder's files: listing, guarded reads and writes, git status and diffs, search, diagnostics, path resolution.
marginTopForFunction#
Resolve the top margin (in rows) for an event given the one rendered just before it. Context-aware rules:
- A
tool/tool-resultevent right after anothertool/tool-resultcollapses to a tight list — call→result pairs and back-to-back calls read as one logical block. - Consecutive
task-notificationbanners stack tight — a burst of background-task completions reads as one log column rather than scattered banners.
NB: parent-level events (depth === 0) following a subagent block
(depth > 0) get their normal default margin. The subagent's
🌳 end-marker does not provide enough visual separation to
collapse the transition to 0: a 2-cell emoji on the same row as the
close marker doesn't create a vertical break, and in
hide-subagent-output mode the SubagentBlock box isn't rendered
either, so the parent's follow-up markdown would be glued directly
against the close line. Subagents should READ like
tool calls: open with breathing room, close tight inside, and open
a clean gap before the parent's next thought — that's the contract
the tool-call → markdown transition uses, mirrored here.
Renderer-agnostic — TUI uses it as Yoga marginTop; a CSS host can
use the same number as the row's top margin in em / rem.
maskToOutcomeKindsFunction#
Convert a per-hunk approval mask into an EditOutcome[]. true →
applied; false → denied with the supplied reason.
Length is Math.max(mask.length, fallbackLength) so callers passing a
shorter mask still get a fully-populated array — missing entries
default to applied, matching the "no decision => keep" convention.
matchesBindingFunction#
Test a KeyEvent against a parsed-or-string binding. Accepts either form so callers can pre-parse (hot path) or pass the raw spec for one-off checks.
Modifier semantics: ALL declared modifiers must be pressed AND no
extra modifiers may be pressed. So 'o' does NOT match ctrl+o,
and 'ctrl+o' does NOT match ctrl+shift+o. This avoids surprises
where a binding that should be specific accidentally fires for a
superset of key combinations.
matchesSafelistEntryFunction#
Test whether a { tool, input } pair is covered by one safelist entry.
Supported entry shapes:
"<tool>"— broad match on tool name."<tool>:<token>:*"— match when the primary arg's first token equals<token>."browser_open:<host>"/"browser_navigate:<host>"— match a load of that host (port included).
This function matches a single command against a single entry.
For shell commands that chain multiple programs (&&, ||, ;,
$(…), etc.), use isOnSafelist which parses the full command
and checks every head token independently.
Entries that don't fit either shape are ignored (forward-compat for future pattern syntax — readers shouldn't choke on entries written by a newer version of the TUI).
McpAuthProviderFunction#
Mount once near the top of the React tree (above ModalRoot). Children
use useMcpAuthState() to read and useMcpAuthDispatch() to fire events.
mcpCredentialsPathFunction#
Returns the path of the MCP credentials file inside dataDir.
mcpFailureEventFunction#
The status a failed connection leaves, from classifyMcpTest's answer
(never called with ok: a connection that worked leaves no failure).
A server that asked for OAuth keeps "sign-in failed" for an unexplained
failure (its tokens are the likely cause, and sign-in stays offered).
mcpFailureLineFunction#
The first line of a failure, never empty.
mcpsWritePathFunction#
Resolve the CANONICAL write target for a scope — always the
.{prefix}/mcps.json flavor, never .agents (we don't own that
convention) and never mcp.json (Cursor's spelling is read-compat
only).
mcpToolsCachePathFunction#
Resolve the on-disk cache path under a host's data directory. Exposed for tests + advanced hosts that want to inspect / delete the file without re-implementing the path convention.
mergeApprovalAndBodyOutcomesFunction#
Merge body-side outcomes (keyed against the approved subset the tool
actually ran on, in subset-position order) into approval-side outcomes
(1:1 with the model's ORIGINAL edits list, with denied entries for
every hunk the user dropped).
Algorithm: walk the approval array; every applied placeholder
corresponds to one approved hunk that the body ran. Consume body's
outcomes in order against those placeholders. Non-applied approval
entries (denied, skipped) stay untouched — they describe gate-
level decisions the body never saw.
Pure. Returns a fresh array; never mutates either input.
Edge cases:
bodyis empty / shorter than the approved count → remaining approvalappliedplaceholders stay asapplied(the body ran happily; absence of a body entry means nothing failed).bodylonger than approved count → trailing body entries are ignored. Shouldn't happen in practice (body sees the rebound subset), but the guard keeps the merge total-pure.
mergeKeybindingsFunction#
Merge a partial map of user overrides into the defaults. Unknown action keys are dropped (a future TUI version may have retired the action); invalid spec strings (parse fails) fall back to the default for that action.
migrateStoredSettingsFunction#
Bring a stored settings slice (state.json) up to date: maps the
legacy allowInteraction and showToolCalls booleans (never over the
modern key), the interim runReceipt mode, the legacy safeMode and
queueMessages booleans, drops
retired keys and, once per defaults revision, drops values equal to a
since-changed default. The result carries the
SETTINGS_DEFAULTS_VERSION_KEY marker, so writers that persist it
never migrate the same slice twice (a value the user picks later, even an
old default, then sticks).
migrateTodosBagFunction#
Converts the old session.metadata.todos bag. Never produces an
applying plan: an open list becomes stopped (migrated), which a run
that resumes it reopens by writing the same step ids. A finished list
becomes done (or dropped when everything was cancelled). Sub-agent
slots (byRun) are dropped: their runs ended long ago.
modelChainMetadataFunction#
Assemble the metadata.modelChain value for a model pick — the full
canonical chain when at least one valid fallback survives filtering,
undefined for a single-model pick (metadata merges JSON-serialize,
so undefined REMOVES a previously persisted chain).
modelLabelFunction#
The name the model picker shows for a model (Opus 4.5): the provider's
catalog name when registry knows the model, else the id made readable.
Without a provider key, or with one registry doesn't hold, the first
provider that knows the id names it. Memoized per registry: surfaces call
it on every render.
modelOptionsForFunction#
Custom ModelOptions the given model supports (e.g. fast mode), or []
when none. Drives the TUI/GUI options picker visibility — surfaces only when
non-empty.
modelsForDescriptorFunction#
Resolve the model list for a given provider. Honors descriptor.models
when set; otherwise queries pi-ai via descriptor.piProviderId. Returns
[] for descriptors with no known mapping (custom providers without a
model list) — callers should hide the model picker in that case.
modelSupportsReasoningFunction#
Whether the given model exposes a reasoning / extended-thinking knob.
Drives the TUI's effort picker visibility — the footer's effort segment
(effortLabel) and its shortcut only surface when this is true.
Returns false for unknown models (no registry entry → no advertised
capability).
newSessionFunction#
Build a new, UNSAVED session with every creation-time field stamped:
projectRoot (git root of cwd), cwd, agentId, title, the model and
its fallback chain, the authoring markers, and the environment.
Unsaved on purpose: the TUI's local runtime creates the session when a chat
opens but only persists it on the first run, so opening and abandoning
/new never leaves an empty row behind. Everyone else wants
createSessionInStore.
store may be undefined for an in-memory-only session (ACP without a
store): same stamping, no persistence.
normalizeBindingValueFunction#
A keybindings.json value as one spec: a string, or an array of chords
(["ctrl+w", "cmd+w"]) joined as alternatives. Chords that don't parse
are dropped; null when none is left.
normalizeLaunchOverridesFunction#
The overrides that shape an agent, or null when none do (no system,
no MCP server, no non-process context, no cwd). The one rule for "are launch
overrides set", shared by the host, the daemon dispatcher, and the TUI.
normalizeRedirectPasteFunction#
Widen what counts as an acceptable paste. The happy path is the full redirect URL out of the browser's address bar, but users on SSH routinely end up holding less than that: some authorization servers render the code on the page instead of redirecting, and copying from a "can't reach this site" error page loses everything but the query.
Accepted forms, given the authorization URL for context:
http://127.0.0.1:5123/callback?code=x&state=y— passthrough (any absolute URL is returned untouched; the loopback guard infetchOAuthRedirectstill has final say, so a pastedhttps://evil.testis rejected there, not silently rewritten)./callback?code=x&state=y— path + query onto the callback origin.?code=x&state=y/code=x&state=y— query onto the callback URL.x— a bare authorization code;stateis taken from the authorization URL when it carried one (the loopback server forwardsstateverbatim and the SDK owns verification, so a missing one is not fatal). Anything with whitespace inside is prose (an error page fragment), not a code — refused with a clearer error than a server 400 would give.
Throws when the input can't be turned into a URL — no authUrl context
for a partial paste, or an unusable authorization URL.
normalizeRemoteUrlFunction#
The repository a remote URL names, as host/owner/repo in lower case:
the same key for the HTTPS, SSH and scp forms of one remote. null
for a local remote (a path or file://), which names no shared repository.
oauthUsesManualCodePasteFunction#
True when the provider's OAuth flow needs the user to paste a code back into the TUI (no loopback callback).
onboardingInstallSignalsFunction#
The signs of an install that predates the wizard.
onboardingProvidersFunction#
The providers Connect lists, featured ones first, then the provider extensions that are not installed.
overlayHostSettingsFunction#
local with the host's values for every key the host owns.
parentPlanScopeFunction#
The scope a sub-agent run's plans nest under: its parent run's scope.
undefined for a top-level run.
parentServerNameFunction#
Server name a row "belongs to" for catalog / toggle / auth lookups. For a server row that's its own name; for tool / tool-empty rows it's the parent server's name.
parseDecisionModelFunction#
Split a stored "providerKey/modelId" pick (first slash; model ids may contain slashes).
parseEditorCommandFunction#
Split an editor command line into [executable, ...args].
Whitespace-separated, with single and double quotes honored so an editor
living under a path with spaces still works
("/Applications/My App/bin/ed" -w). Quotes group and are stripped;
backslash escaping is deliberately NOT implemented, because on Windows
backslash is the path separator and treating C:\tools\ed as escapes would
corrupt far more command lines than it would rescue.
Returns [] for an empty or whitespace-only spec, so callers can fall back
to the platform opener rather than spawning ''.
parseEditOutcomesFromResultFunction#
Parse an <edit-outcomes>…</edit-outcomes> annotation block out of a
tool result body. Returns the outcomes keyed by 1-based hunk index, or
null when the block is missing / malformed.
Anchored on the explicit tag pair so the parser doesn't false-positive
on natural prose that happens to contain #1 applied.
parseMcpsFileFunction#
Parse one mcps.json file. Canonical zidane shape is a flat array; the
other shapes exist for copy-paste from neighboring tools:
McpServerConfig[]— flat array (recommended).{ name: {...} }— name-keyed map.{ "mcpServers": { name: {...} } }— Claude Desktop / Claude Code / Cursor wrapper. Unwrapped before normalization (otherwisenormalizeMcpServerswould treat the whole wrapper as a single server).
Per-entry enabled: false (Cursor runtime state) drops the entry — same
intent as the source tool. Use the TUI toggle list for "show but disabled".
Tolerant to common copy-paste artifacts: when strict JSON.parse fails,
retries after normalizing invisible whitespace that's valid Unicode but
not valid JSON whitespace (BOM, NBSP, zero-width spaces, line/paragraph
separators) — only OUTSIDE string literals, so user data isn't mutated.
If the sanitized version still fails, throws the original error with a
targeted hint when NBSPs are present.
Validation flows through normalizeMcpServers so the result matches
what createAgent accepts. Throws on truly malformed JSON; the caller
decides whether to surface or swallow.
parseSemverFunction#
Parses a semantic version string into its parts.
Accepts an optional leading v, a prerelease and build metadata. Returns null when the input is not a valid version.
parseSessionEventXmlFunction#
Inverse of renderSessionEventXml. Untrusted input — it comes off disk
and outlives this module's versions — so it validates each field and returns
null for anything malformed, in which case the turn replays as the plain
user text it structurally is.
patchMcpCredentialFunction#
Convenience patches for individual sub-fields. The provider class uses
these so a saveTokens call doesn't have to round-trip clientInformation
discoveryStateit never touched.
pendingInteractionsFromTurnsFunction#
Scan turns and return every interaction tool call without a matching
tool_result, ordered by turn appearance. Works equally for live mid-run
inspection and reload-from-disk.
Malformed payloads (input that doesn't match the tool's schema) are
skipped silently — the call still lives in the persisted history, but
the renderer wouldn't know how to display it. The next agent.run() on
the session will see the orphan and synthesize an error tool_result via
the loop's normal recovery path.
performInPlaceSelfUpdateFunction#
Replace the running binary with the latest tarball-shipped one. Works on
macOS + Linux (POSIX unlink-while-running); refuses on Windows. Returns
a result object instead of throwing — callers usually want to print
result.reason and fall back to a PM-driven update.
performSelfUpdateFunction#
Re-install the package globally via the host's package manager. Resolves
with the spawned command's exit code. It does not reject: a spawn failure
comes back as spawnError, an abort of the caller's signal kills the
child (exitCode: null), a PM still running after timeoutMs is killed
(timedOut), and PM failures surface as a non-zero exitCode.
The caller decides whether to retry or fall back to in-place.
piIdOfFunction#
Convenience accessor — returns piProviderId ?? key.
planRunNotesFunction#
Notes for a run that starts on a session with these plans and turns.
planScopeForRunFunction#
The plan scope of a run: its own id for a sub-agent run (it has a
parentRunId), else the session scope. An unknown run is top-level.
planWorktreeProjectRootRemapsFunction#
For persisted project roots that predate worktree-aware identity: the
{ from, to } pairs where a stored root is a linked worktree's checkout
root and should be its main checkout's. Only exact linked-worktree roots
remap — a plain directory that later ended up inside some repo keeps its
own identity (no parent walk here). Stores apply the pairs as a bulk
column update at open; idempotent, so a row reverted by a stale
full-document save converges on the next open.
previewClaudeImportFunction#
What importFromClaudeCode would bring over and skip, per piece,
without writing anything: the setup wizard's Bring your setup step shows
it before the user picks. Names already in zidane are skipped, as the
import skips them; a server listed in several Claude files counts once.
probeInstalledVersionFunction#
Compute the state once — the pure heart of the watcher, exported so a host without a lifecycle (a one-shot IPC handler) can answer "is a restart pending?" without holding a watcher.
probeLocalModelServersFunction#
The local model servers answering on their default ports (Ollama, LM Studio, vLLM), with the base URL the Local LLM provider takes.
profileCompositionFunction#
A profile's own composition: its family (every registered member, in registry order) or the profile alone.
profileToolsFunction#
A profile's own tools by name. Tools the host gives every profile (interaction, skills, MCP, …) are not part of it.
projectRootOfFunction#
findProjectRoot with a fallback: outside git, a
directory is its own project. The value to stamp as
SessionData.projectRoot and to key per-project state on.
projectsFilePathFunction#
Resolve projects.json's on-disk path given the TUI data directory.
projectUserPathsFunction#
Resolve the four search paths for a given subdirectory (skills,
mcps.json, …). Returns absolute paths regardless of whether they
exist — the caller chooses to existsSync-filter or feed straight
into a tolerant discovery routine.
proposeEventFunction#
The propose event of a present_plan request. Its id is the request id,
so a request proposed twice (the tool, then a rehydrate) is one plan.
providerFactoryOptionsFunction#
Factory options that build descriptor on its stored account account
(a credential id), or undefined for the provider's active account: no
account asked for, or a provider whose factory cannot take one
(descriptor.accounts). An OAuth account rides as account and is resolved
to its slot on every token read; an API-key account as its key. An account
no longer stored still rides as account, so the call fails with the
pinned-account error instead of quietly running on the active account.
providerFieldViewsFunction#
A provider's custom fields as a settings form asks for them; undefined when it takes none.
providerKeySetChangedFunction#
Did the SET of provider instances change between two chains? The agent is built with one provider instance per distinct chain provider (bound to its account), so a set change requires a session re-activation (rebuild); a pure model / order change within the same providers and accounts does not.
providerUsageSupportedFunction#
Whether this provider can report subscription usage at all.
provisionSessionEnvironmentFunction#
Runs one provisioning attempt for a session's environment and persists each state change.
Sets the state to provisioning, calls the provider's prepare, then persists ready or failed. Resolves instead of throwing when the provider fails.
quoteForShellFunction#
Re-quote a single argv token for a shell that will re-parse the joined command
line — i.e. spawn(..., { shell: true }), which Node uses on Windows so that
.cmd / .bat wrappers (how code, cursor and friends ship there) resolve.
Node does NOT re-quote when shell is set: it joins [cmd, ...args] with
spaces and hands the string over. Since parseEditorCommand has already
STRIPPED the user's quotes, handing tokens back unquoted would split
C:\Program Files\ed.exe at the space and try to run C:\Program. This puts
the quotes back.
Only tokens that need it are quoted, so a plain code stays code. A literal
double quote is doubled, which is how cmd.exe escapes one inside a quoted
run.
The test covers cmd.exe METACHARACTERS, not just whitespace: &, |, ^,
<, > and friends carry none of the obvious "needs quoting" signals, so a
repo cloned into C:\work\a&b would otherwise hand C:\work\a&b\AGENTS.md
over bare, and cmd would split it at the & and run the tail as a second
command.
% and ! are in the class so such a token is quoted rather than passed
bare — but be clear about the limit: quoting does NOT stop cmd.exe expanding
%VAR%, nor !VAR! where delayed expansion is on. Double quotes suppress
splitting and other syntax, not expansion. That is a property of the shell
which no amount of quoting can close; the worst case is a wrong path, not an
injected command.
readCredentialEntryFunction#
Read one entry by its file key, whatever owns it. For stores that keep a
secret beside the provider slots under their own namespace (the host
registry: hosts:<id>).
readCredentialsFunction#
Read credentials from disk.
Returns {} when the file is missing or corrupt (last-ditch tolerance —
a hand-edit gone wrong shouldn't lock the user out of re-authing). On first
call with no file present, attempts a migration from a legacy
.credentials.json in the current directory (the location older bun run auth
versions used), when that directory is the home dir or the data dir.
readEnvironmentSettingsFunction#
Tolerant read of Settings.environments.
readFailedUpdateFunction#
Reads the failed-install record. null when there is none or it does not
parse. Falls back to the record this process could not write to disk.
readFileSafeFunction#
Reads a UTF-8 file, resolving to an empty string when it cannot be read.
readKeybindingsFunction#
Load + merge the user's keybindings file (when present). Always
returns a fully-resolved KeyBindings — defaults fill in for
any missing / invalid entries so consumers can treat the result as
total.
Failure modes (all tolerated, all fall back to defaults):
- File missing
- File not valid JSON / JSONC (after comment stripping)
- Top-level is not an object
- Individual entries have invalid spec strings
readKeybindingsRawFunction#
Read the raw on-disk JSON object from keybindings.json after the
JSONC stripper. Used by extension-keybinding resolution so the
user's overrides for extension-owned ids flow through the same file
the built-in actions use.
Returns an empty object on missing / malformed / non-object files
— same fault-tolerance contract as readKeybindings.
readPlansBagFunction#
Reads the plans bag from session metadata. The metadata is untrusted (an
older build, a hand edit): malformed plans and steps drop out rather than
throw. A session that has no plans yet but has the old todos key is
converted in memory (migrateTodosBag); nothing is written here, the
converted bag is stored with the next real change.
readProjectsFunction#
Reads projects.json. Returns {} when the file is missing or unreadable.
readProviderCredentialFunction#
Read a single provider's credential (translating via the descriptor).
readProviderCredentialPairFunction#
Both stored credentials for a provider: active is the one every reader
resolves, alternate is the stored-but-not-preferred one (if any).
Predates multi-account and only sees the #alt slot; use
readProviderCredentials to list every stored account.
readProviderCredentialsFunction#
Every stored credential of a provider, active first.
Tolerant of any kind in any slot: #alt is meant for the API key and
#account:N for OAuth accounts, but a file written by an older build (which
parked the OAuth alternate in #alt) must still list everything it holds.
readSessionEnvironmentFunction#
The session's environment, from its metadata. Tolerant: absent or
malformed reads as LOCAL_ENVIRONMENT — what every session was
before environments existed.
readSessionPlansFunction#
The session's plans (the old todos key converted in memory when no plans exist yet).
readUpdateAppliedMarkerFunction#
Reads the update-applied marker.
Returns null when the file is missing, unreadable or malformed. Package entries with a non-string name or version are dropped.
readUpdateLockFunction#
Reads the lock file. Returns null when there is none. A file that does
not parse (another process is still writing it, or garbage) yields a holder
with pid: 0, dated by the file's mtime, so only age makes it stale.
readUpdateWorkerResultFunction#
Reads the last worker result. null when there is none, it does not parse,
or it has another protocol version.
readWorkspaceFileFunction#
A file of the folder for a viewer; null when it is gone or outside the folder.
redeemProviderResetFunction#
Redeem one banked reset on a provider's credential (Codex only): empties its rate-limit windows now. Spends a reset, so call it only on an explicit user action. The credential's cached snapshot is dropped, so the next fetch shows the new windows and count.
Never rejects: failures come back as code: 'failed' with a short error.
redirectUriFromAuthUrlFunction#
The redirect_uri the authorization server was told to come back to,
read out of the authorization URL itself. That's our loopback callback
(http://127.0.0.1:<port>/callback) — the UI shows it so an SSH user
knows which address to fish out of the browser's URL bar, and
normalizeRedirectPaste uses it to rebuild a full callback URL
from a partial paste.
Returns null when the URL doesn't parse or carries no usable
redirect_uri — callers degrade to "paste the whole URL".
reduceMcpAuthFunction#
Apply one event to the state map. Pure, immutable — returns a new map with only the affected key reassigned.
State transitions are simple "last write wins"; we don't gate (e.g.) a
login:start from overriding authorizing because the loop layer
never doubles those up — interactive login is serialized in the TUI.
refreshMcpToolsCatalogFunction#
Force-refresh the on-disk tools cache by opening a transient MCP
connection to every server, capturing the mcp:tools:list hook on
the way through, and closing the connection immediately. The
underlying connectMcpServers runs every server's bootstrap in
parallel, so the wall-clock cost collapses to the slowest server.
Two design choices worth noting:
- Shared hook bus. The caller passes the SAME
Hookableinstance that has the cache subscriber wired (typicallyagent.hooksaftersubscribeMcpToolsCache(agent.hooks, …)ran). That waymcp:tools:listfires on the bus the subscriber is listening to and the cache lands on disk without a separate write path. - Transient, NOT shared with the live agent. The connection opened here is closed immediately. The agent's own MCP connection is untouched, so a refresh never disrupts an in-flight tool call.
The function intentionally swallows per-server failures (they're
already surfaced via mcp:bootstrap:end ok: false for any host
that wired the listener). The Promise resolves once every server's
bootstrap settles, success or otherwise.
removeFromSafelistFunction#
Removes one safelist entry of a project, dropping the project's record once
it holds nothing else (its last entry gone, and no other setting such as
durability). Synchronous, so two removals in one process never drop each
other's change.
removeMcpServerFunction#
Remove the entry named name from the mcps config at filePath,
preserving the file's shape and everything else in it — the removal
counterpart of upsertMcpServer. Throws when the file is
missing, malformed, an unrecognized shape, or has no entry of that
name (the caller shows the message on the settings op line; silently
"succeeding" on a no-op would lie about what happened).
removeProviderCredentialFunction#
Sign a provider out — drops EVERY stored credential.
"Signed out" has to mean the provider resolves nothing afterwards, which is
what this guarantees; promoting a survivor instead would silently leave the
provider authenticated through another source. Callers that want that behavior use
removeStoredCredential on the one slot they mean.
removeStoredCredentialFunction#
Drop ONE stored credential. Removing the active one promotes a survivor —
another credential of the same kind when there is one (a second OAuth
account), else whatever is left — so the provider does not go dark while it
still holds a working credential. Returns false when key was not stored.
renderAgentsMdBlockFunction#
Render one or more AgentsMdFile into a system-prompt block.
Top header tells the model what's coming + that it's user-authored (so it's treated as guidance, not as a system constraint that can't be questioned). Each file becomes a sub-section with its absolute path so the model can cite it back when asking follow-up questions.
Exported separately so callers building custom profiles can inject their own discovery list (e.g. an SDK consumer pulling AGENTS.md from a remote source) without re-implementing the rendering.
renderSessionFunction#
Render a session into a string in the requested format.
markdown produces a human-readable transcript: a YAML-free header
block with the title and a one-line id, turns, runs summary,
a ## Metadata list (id, created, updated, status, turns, runs, tokens,
cost), then a ## Conversation block where each turn renders as ### N. role over an
italic ISO-date, run run_X, tokens … line, with text, thinking, tool
calls, and tool results formatted as appropriate fenced blocks. Useful for sharing a session
with a teammate or pasting into an issue tracker.
json returns a 2-space-indented, deterministic dump of the full
SessionData blob. Useful for re-importing into the store or for
post-hoc analysis tooling.
renderSessionEventXmlFunction#
Wire format between the harness and the model — and, because it is persisted inside the user turn's text block, between a live session and its replay.
Follows <task-notification> exactly: child-tag XML, one block per event,
escaped with escapeXml. The model already knows this shape as "the harness
telling me something", which is the point — a main that mistook a worker
report for a human instruction would act on it as one. eventsFromTurns
detects the block on replay and re-synthesizes the structured row instead of
painting the raw XML as a user prompt.
renderSystemMdSeedFunction#
Seed contents for a freshly created SYSTEM.md override, built from the
built-in doctrine.
Seeding with the real doctrine (rather than an empty file) means creating the override is a behavioral no-op until the user edits it. An empty seed would silently delete every line of doctrine the moment the file appeared, making the agent measurably worse with no visible cause.
currentSystem should be DOCTRINE ONLY — callers pass
splitSystemPrompt(doctrineOnlySystem()).static, which excludes both the
generated <env> block (rebuilt per turn) and the AGENTS.md block. Baking
the latter in would duplicate it, since it is re-appended below the override
on every compose.
scope is the active userInstructionsScope; it decides whether the seed's
precedence note is true — see projectScopeOverridesLoad.
replayTurnsFunction#
The whole replay, and where each turn's events start in it
(turnStarts[turns.length] = the end). A page of turns [from, to) is
events.slice(turnStarts[from], turnStarts[to]): consecutive pages
concatenate to exactly eventsFromTurns (exchange separators, run
receipts, subagent markers, tool names and command state as the whole
replay has them), because what a run or the turn before decides lands in
the page of the turn whose replay emitted it.
repoKeyOfFunction#
The repository dir is a checkout of (normalizeRemoteUrl of its
origin, else of its first remote), read from the git config without
running git. Two copies of one repository on two machines have the same
key. null outside git, or for a repository without a shared remote.
resolveAgentIdFunction#
Resolve an agent id against a registry with sensible fallbacks: the
requested id wins when present, then defaultId, then the first key.
Returns null when the registry is empty (host misconfiguration —
the caller should surface this rather than silently failing).
resolveApprovalForPayloadFunction#
Resolves an approval decision into per-hunk outcomes and a gate verdict. A deny blocks every hunk. A partial decision applies the hunks its mask keeps and blocks when none are kept. Any accept decision applies every hunk.
resolveChipColorFunction#
Look up the chip color pair for a provider id, falling back to
chips.default when the theme has no kind-specific entry. Mirrors
resolveChipStyleId so both rendering surfaces (submitted echo +
live textarea) share one canonical lookup rule.
resolveConfigFunction#
Resolve user options into a fully-bound runtime config.
NOT pure: besides disk reads, this mutates process.env so the harness
providers pick up the chat engine's credential store — it sets
ZIDANE_CREDENTIALS_PATH and reconciles stored API keys / OAuth entries
into env via applyApiKeyEnv (which can overwrite or delete ambient keys
like ANTHROPIC_API_KEY; see its JSDoc for the precedence rationale).
resolveCwdPathFunction#
Resolve a workspace-relative path against the session's cwd. Absolute paths pass through.
resolveDecisionsOptionFunction#
AgentOptions.decisions from settings:
- off (
decisionsEnabled) →false(every decision returnsunavailable). - the picked model when its provider builds and its credentials allow it.
- otherwise the first available decision-capable provider (silent fallback, like the compaction model), preferring a provider with a native decisions endpoint over one that only approximates them.
- otherwise the first decision-capable provider that builds, so failures
explain the missing credential;
undefinedwhen there is none.
resolveExecutionFunction#
THE way a host gets a session's execution context: its environment's provider decides. The key is namespaced by kind so two providers can't collide on the same configuration string.
resolveExtensionKeybindingsFunction#
Resolve the live spec string for each extension-contributed
keybinding. The user's keybindings.json is consulted for an
override on the binding's id; absent / invalid entries fall back
to the binding's default.
A chord that is reserved or a bare printable character
(see isReservedExtensionBinding, isBareCharExtensionBinding)
is refused: a user override falls back to the default, and such a default
resolves to unbound.
Pass the raw object (from readKeybindingsRaw) — passing
KeyBindings here wouldn't help because the typed map only carries
built-in KeyAction entries.
Returns one entry per input binding, in source order. Empty spec
(binding declared default: '' and the user didn't bind it) is a
legitimate "unbound" state — the dispatcher never matches an empty
spec, so the action stays accessible via re-binding through
keybindings.json.
resolveInlineSuggestionFunction#
Query providers in order; the first provider yielding a non-empty
candidate list wins (a bare string normalizes to a 1-element list).
Provider errors are swallowed (a broken extension provider must not
break typing), and each provider races its deadline —
PROVIDER_DEADLINE_MS by default, a provider's own deadlineMs
(capped at MAX_PROVIDER_DEADLINE_MS) when declared — so one
hung provider can't permanently suppress the ghosts of providers
behind it. Returns null when aborted or nothing matched.
resolvePathsFunction#
Resolve each text against cwd; answers line up with texts. A cwd that
does not exist resolves everything as missing.
resolvePlatformPackageFunction#
Resolves the platform-specific tarball package name for the current machine.
Supports macOS on arm64 and x64, and Linux on arm64 and x64 with glibc. Returns null for other targets.
resolveProviderConfigFunction#
A kind's effective options: bound settings, stored values, secrets, env-var fallbacks, then schema defaults — in that order.
resolveSessionCwdFunction#
Effective process cwd for a persisted session row: the GUI-recorded
metadata.cwd when present, else the canonical projectRoot
(TUI-created sessions), else the directory-less HOME anchor. Empty
strings count as unset — forks of directory-less sessions persist
cwd: ''.
resolveSessionExportTargetFunction#
Resolve the export target for a session id + format. Pure: no fs
write happens here, the caller decides whether to existsSync the
directory or hand the path to writeSessionExport.
Anchor selection walks upward from cwd looking for a .git entry;
the first hit anchors to that repo's root (project). When the walk
exits without finding .git, the destination anchors to home: the
user's storage data dir.
resolveSessionModelFunction#
A session's provider, pinned account, model and fallback chain. With
config, a session without a model pick on an account (pinned, else the
provider's active one) that has its own model list runs on the provider's
default when the list has it, else on the list's first model.
resolveStorageDirsFunction#
Resolve the four storage slots according to the precedence above.
Pure aside from one filesystem probe (readdirSync(home/<prefix>),
see holdsLegacyStorage). No directories are created here; the
relevant write paths (state store, credentials writer, persist
dir) handle their own lazy mkdirSync already.
resolveStoragePathsFunction#
Compute the on-disk layout for a single TUI session. Public so hosts
(CLI tools, tests, scripted bootstraps) can ask "where will sessions
land?" without going through resolveConfig's full machinery.
Storage-slot resolution (config / data / state / cache) is delegated
to resolveStorageDirs. In legacy modes the four slots collapse
to a single <storageDir>/<prefix> directory; in XDG mode they fan
out into $XDG_CONFIG_HOME/zidane, $XDG_DATA_HOME/zidane,
$XDG_STATE_HOME/zidane, $XDG_CACHE_HOME/zidane. See the module
doc on ./xdg.ts for the full precedence chain.
Decision logic for project mode (least → most specific):
- Default: OFF — sessions live in the user-scoped
dataDirand get scoped per-project via theSessionData.projectRoottag. <configDir>/config.jsonprojectDbflag (when present).ZIDANE_PROJECT_DBenv var (0/false/off/no→ off,1/true/on/yes→ on, any other value ignored with a warning).options.projectDb(host call site).
Project mode activates only when the resolution above lands on
true AND a git repo is found above cwd. Outside git or with the
flag off, sessions + state stay at the user-scoped slots.
Auto-creates the project .{prefix}/ directory when mode resolves
to ON (silent — mirrors ensureStateDir), with a .gitignore of * when
it creates the directory. User slots are created
lazily by the state-store + credentials writers; we don't pre-touch
them here so a read-only invocation stays read-only.
resolveThemeFunction#
Resolve a theme id to its full Theme, falling back to default on unknown ids.
restoreChainFallbacksFunction#
Restore the fallback tail of a persisted chain for a resolved primary
pair. Returns entries 1+ only when the persisted chain's entry 0
matches primary — a divergent chain belongs to a different selection
(e.g. a --model launch override) and silently attaching it would
surprise. Entries whose provider isn't registered, entries equal to
the primary, and exact duplicates drop. Accepts the raw persisted
value (state.json is user-editable) — shape validation included.
restoreModelOptionsFunction#
Resolve a model's remembered options for a (re)pick: keep only options the
model still declares AND that are enabled, dropping any that no longer apply
(e.g. switching away from a model that supported fast). Returns undefined
when nothing applies so callers can omit the field entirely.
Shared by the TUI pick path and the launch-time resume path so "which options survive a model switch / relaunch" is decided in exactly one place.
rewriteMultiEditHeaderFunction#
Rewrite a multi_edit body header so the totals reflect the model's
ORIGINAL edit list (the merged outcomes count) instead of the subset
the body actually saw after gate rebinding. Without this, a partially
approved call surfaces a misleading applied 2 of 2 edits (subset
counts) on the wire even when the original was applied 2 of 3.
Three body-side shapes are handled (matching multi_edit's emit):
Edited <path>: applied N edits (R replacements).Edited <path>: applied N of M edits (R replacements).multi_edit error: no edits applied to <path> (M attempted).
The replacements count is preserved verbatim — it's a body-side stat the chat layer can't recompute. When the first line doesn't look like any of the three shapes (e.g. an unrelated error preamble bubbled up), the text is returned unchanged.
runCompactionFunction#
Compact the session through agent.compact() (the SDK's cached
compaction path) and emit a compact-summary stream event. Brackets the
in-flight window with compacting:start / compacting:end signals.
Resolves what it did, or null when nothing was compacted (nothing to
summarize, cancelled, failed: reported as an event).
runDiagnosticsFunction#
Runs the project's own tools on paths, cached until the files move.
runEndNoticeFunction#
Structured stop notice for an abnormal finishReason, or undefined for a
normal end.
Normal completions (stop / tool-calls) and user aborts return
undefined — and so does a SUCCESSFUL auto-resume, because recovery ends
the run on stop. That is what keeps the notice quiet exactly when the
ceiling was handled rather than hit. error runs already surface their own
error event, so a second notice would double-report.
runInProgressFunction#
The session's top-level run in progress: the latest running run without
a parent (subagent runs share the session).
runIntegrationSignInFunction#
Run the sign-in of a provider that signs in with an integration
(ProviderDescriptor.integration): the integration's connect flow, on the
same callbacks as runOAuthLogin. The registry that holds the
integration stores the connection (another account adds one); the caller
persists nothing. Rejects when no extension in this process registers it.
runOAuthLoginFunction#
Run the OAuth login flow for a provider.
Returns the OAuth credentials on success; caller persists them via
setProviderCredential(dataDir, descriptor, { kind: 'oauth', ...credentials }).
Throws when the descriptor has no oauthProvider configured.
runProgressFunction#
The top-level run in progress as its agent saved it: when it began and the
output its settled turns produced. A window that missed run:start
(opened or reattached mid-run) starts its run readout from these, so the
time and the count don't restart at zero. undefined when no top-level
run is in progress.
runSessionEnvironmentActionFunction#
Run actionId for a session on execution — the session's own (hosts pass
the cached one, so the action runs exactly where the agent does). Throws
when the environment isn't ready or doesn't offer the action.
runUpdateCommandFunction#
Run the upgrade subcommand. Exit code contract:
0— update succeeded,--checkreported no update, or--checkreported an update (informational only).1— update failed (PM exit non-zero, in-place download failed, registry check failed without--force, release not downloadable yet, or the installed version did not change).2— argv parse error (unknown flag).
Output is a short ledger, one line per package, led by a status mark
(src/cli-style.ts):
· zidane-tui 7.0.7 → 7.0.8
$ volta install zidane-tui@latest
…
✓ zidane-tui 7.0.8 installed
Diagnostics go to stderr and say what to do next.
runUpdateWorkerMainFunction#
Entry of the worker process. Returns the exit code: 0 once a result is
written, 3 when another install holds the lock, 2 for a bad request.
safelistProjectKeyFunction#
The projects.json key for a working directory: its project root (the
main checkout for a linked worktree; the dir itself outside git) — the
same "project" the TUI scopes its safelist to, so a subdirectory session,
every worktree of the repo, and every host share one safelist.
SafeModeProviderFunction#
Owns the queue + actions. Splits the value across two contexts so a queue change doesn't invalidate every callback memo that closes over the actions.
sanitizeModelChainFunction#
Validate a persisted chain read back from state.json. The state file
is user-editable JSON, so the value can be arbitrarily malformed —
return only the well-shaped { provider, model } entries (both
non-empty strings), or [] for anything else. Never throws.
sanitizeTodoItemsFunction#
Validates untrusted todo items: rows without a string id and content and a known status drop out, then the list is capped. The same validator guards the tool input and user edits.
saveMcpToolsCacheFunction#
Atomic full-cache write. Used by subscribeMcpToolsCache after
each upsert. Failures bubble up as the underlying writeFileAtomic
error — the caller logs under ZIDANE_DEBUG and swallows.
saveStateFunction#
Writes the TUI state file atomically, creating its directory when needed.
scopeCwdFunction#
Map a renderer-supplied scope cwd to the directory the main process
should actually operate in. The renderer signals "no folder" with an
empty string (SidebarSession.cwd is '' for directory-less
sessions); catalogs (@-files, skills, commands, extensions, MCPs)
then root at HOME, matching what the TUI offers when run from ~.
scoreArtifactsFunction#
Filters and ranks artifacts for a query. An empty query returns every artifact. Otherwise it matches the kind aliases, kind label and a fuzzy text match.
searchWorkspaceFunction#
Lines holding query (a fixed string) under cwd: ripgrep, else git grep, else a capped walk.
selectionAfterTurnRemovalFunction#
Keep turn-selection mode alive after deleting its active row. Prefer the row that slides into the deleted index; at the tail, select the new last row. Returns null only when no selectable rows survive.
serializeInteractionResponseFunction#
Format an InteractionResponse as the tool_result content. JSON
keeps the envelope parseable and explicit. Empty fields are stripped so
the model doesn't waste tokens reading absent values.
serializePreviewFunction#
Strip readonly markers so the PreviewResult survives structured-clone
and JSON transports. Field-for-field copy — the resolver output is
already JSON-safe primitives.
serveWorkspaceMediaFunction#
The response for one media address: its bytes, a range of them (206), or
404 (not media, not found, outside the folder), 413 (over maxBytes), 416
(a range past the end).
sessionCompositionFunction#
The composition a session on profileId builds with: the one it ran on
(currentKey) while the profile fits it, else the profile's own.
undefined when profileId is not registered.
sessionEnvironmentSummaryFunction#
The environment summary for list rows — omitted for local sessions (the common case).
sessionModelFallbacksFunction#
Validated fallback tail for list rows/pickers — head-matched against the session's persisted primary, unregistered providers kept (the caller filters against its own registry when it has one).
setCredentialEmailFunction#
Record what the profile lookup found for the stored OAuth account holding
access: its email, or (undefined) that there is none to find, so it is
not looked up again. Returns false when no slot holds that token any more
(refreshed, re-signed in or removed meanwhile).
setCredentialLabelFunction#
Name a stored OAuth account. An empty label drops the field, which reads
back as DEFAULT_OAUTH_ACCOUNT_LABEL. Returns false when key holds
no OAuth credential.
setPreferredCredentialFunction#
Make one of the provider's stored credentials the preferred one.
Swaps the target into the canonical slot and parks the previous active one
(see parkDemoted). Returns which of the three outcomes happened so a
caller cannot report a swap that provably did not occur — the write is
silent either way, and a void return would look like success to a caller
that trusted it instead of refetching.
setProviderCredentialFunction#
Store a credential as the provider's preferred one.
The previous active credential is demoted, not destroyed: otherwise
authenticating with OAuth would silently delete a working API key (and vice
versa), and a second OAuth login would overwrite the first account. An API key moves to
alternateCredKey; an OAuth grant moves to the next free account slot.
Replacing an API key with an API key is a plain overwrite — there is only
ever one — and so is an OAuth login that names its predecessor via
replaceKey.
settingsFromStoredFunction#
The explicitly-set settings of a stored slice, migrated, without the
storage marker: what readers layer over DEFAULT_SETTINGS.
SettingsProviderFunction#
Holds the settings state, applies enforceSettingsInvariants on every write and reports each change to onChange.
settingsToWireFunction#
Settings as sent to a host or to a window. Peers older than approvalMode
know tool approvals only as the legacy safeMode boolean, so it rides
along; a current peer drops it (settingsFromWire).
shortChordFunction#
Shorten a binding spec for display as a "chord continuation" — the
/l after ctrl+m model in the chat footer. We only strip the
ctrl+ prefix so user-customized chords (alt+n, meta+shift+n)
still render in full. Falls back to the verbatim spec when no
ctrl+ prefix is found, which keeps the visual contract honest:
the rendered key always matches the bound trigger.
shouldAutoGenerateTitleFunction#
Decide whether a session is ready for one-shot automatic titling.
Returns true iff the conversation has had its first exchange — at
least two turns, i.e. the opening user message plus the assistant's
reply (this is exactly the "N turns" count the sessions list shows) —
AND no explicit title has been set yet. An existing metadata.title
(a previous auto-generation, or a manual title from the session-details
"generate title" action) is never clobbered.
Pure + total. The runtime layers its own "is one already in flight?"
and "is a provider picked?" guards on top of this; the predicate only
encodes the content-level rule so it can be pinned in tests without a
mock provider — same rationale as the exported cleanTitle.
signsInWithIntegrationFunction#
Whether the provider's sign-in is an integration's connect flow. Then
runIntegrationSignIn runs it and stores the connection itself:
nothing is persisted under the provider's credential key.
singleAgentRegistryFunction#
Wrap a single Preset into a single-profile registry. Used by
resolveConfig when the host passed preset without agents. The
registry has one entry, so the picker has only one option.
sparseSettingsUpdateFunction#
The slice a settings writer persists: the stored keys (migrated) plus the keys it sets, never the defaults, so a later default change reaches every key the user did not set.
splitHostSettingsPatchFunction#
Split a settings patch into the window's part and the host's part.
startUpdateWorkerFunction#
Starts the worker detached and follows it until it reports. The worker keeps going when this process exits. Never rejects.
A held lock answers skipped / locked without starting anything. A worker
that cannot start, or stops without a result, answers lost; for an
automatic install that also records the version as a transient failure (in
memory when the cache dir can't be written), so it is retried on the
backoff, not on every check.
stepTranscriptCapFunction#
capTranscriptEvents, at most step events (extended to the next
turn boundary) at a time. Applied again and again it trims until the
transcript is back within max, then returns events itself; it stops
there rather than at the cap's hysteresis floor, so the end keeps at least
what one full cap keeps. Each cut keeps the cap's seams (no split turn,
never starting on a turn-less row), so a reveal anchors on it like on a
full cap.
storedCredentialByIdFunction#
One stored credential of a provider by its stable id (see
CredentialIdentity), wherever it sits now; undefined when it is
no longer stored.
storedCredentialsOfFunction#
Pure form of readProviderCredentials over an already-read file.
storeHasDurabilityFunction#
Whether a host on store can apply the setting: only a SQLite store has a
durable runtime (sqliteRuntimeForStore). The settings rows show
Crash recovery as Unavailable when it is false.
stripEditOutcomesAnnotationFunction#
Strip the first <edit-outcomes>…</edit-outcomes> block out of a tool
result body, returning the surrounding text. Used by the
tool:transform hook to peel a body-emitted annotation before
re-appending the merged (approval ∪ body) version — otherwise the
result would carry two annotation blocks and
parseEditOutcomesFromResult would only see the first.
Anchored on the same \n<edit-outcomes>\n / start-of-string newline
shape the parser uses, so prose that incidentally mentions
<edit-outcomes> (e.g. a model summarizing its own format) isn't
mistakenly stripped. Trims a single leading \n\n separator when
present so successive strips don't leave dangling blank lines.
Idempotent on inputs that don't contain a properly-anchored block.
stripJsonCommentsFunction#
Strip // line comments and /* … */ block comments from a JSONC
source string. Stays out of string literals so a "foo // bar" value
keeps its slashes. Exported for unit-tests; the only runtime caller
is readKeybindingsRaw.
Trade-off: this is a tiny state-machine, not a full JSONC parser. It
doesn't understand \\ outside strings (irrelevant for JSON) and
doesn't track line numbers in error messages. Good enough for a
config file — corruption in production gracefully falls back to the
defaults via the try/catch in readKeybindingsRaw.
stripSpawnTokensLineFunction#
Strip the Tokens: … line from a spawn tool-result. The spawn-end marker
displayed right above already shows the same stats; keeping the line in the
rendered tool-result body just produces a visible duplicate (and, on
reloaded older sessions, an inconsistent duplicate — the persisted line
can use the 13 in / 4075 out shape while the freshly synthesized
spawn-end uses the cache-aware in 92615 (cache 92602) / 4075 out shape).
Display-only: the persisted tool_result content is untouched, so the LLM
still sees the full string in its context window. Anchored to start-of-line
and matches both Tokens: 13 in / 4075 out (older) and Tokens: in 13 …
(formatTokenUsage) shapes.
subscribeMcpToolsCacheFunction#
Subscribe to mcp:tools:list and persist every successful bootstrap
into the on-disk cache. Returns an unsubscribe function — call it
during agent teardown so a long-lived host (Settings modal that
outlives one agent) doesn't accumulate stale subscribers.
Each write loads the current cache, upserts the named entry, then atomic-writes the full file. The read-modify-write is safe under Node single-threaded event loop semantics — concurrent bootstraps in the same process serialize through the hook bus.
Optional onChange callback fires synchronously after every
successful disk write with the entry that was just upserted. Lets a
React host trigger a state refresh without polling the disk.
Write failures are swallowed (logged under ZIDANE_DEBUG): the cache
is an accelerator, not a correctness boundary. If the disk is full
the agent run still works — the settings UI just shows stale data
until the next successful write.
suggestSafelistEntriesFunction#
Suggest the safelist entries to persist when the user picks "accept and
remember" (or "accept for session") for a { tool, input }. Heuristic:
shell→ oneshell:<head>:*per DISTINCT command head, parsing the command the SAME wayisOnSafelistmatches it (&&,||,;,|,$(…), subshells, backticks). Socd dir && cat fileyields["shell:cd:*", "shell:cat:*"]— persisting the whole set is what lets the next identical call skip the gate. A single first-token entry would only covercd, soisOnSafelist'severy-headcheck would fail oncatand re-prompt forever.shellwith an unparseable / empty command → first-token heuristic, else the bare tool name.browser_open/browser_navigateto a non-loopback address →<tool>:<host>: approving one site does not approve the web.- anything else → bare tool name (broad).
Always returns a non-empty list so the UI has a concrete set to render and persist.
summarizeArtifactCountsFunction#
One count per kind, a badge each: ['3 pull requests', '2 files']; empty
for none.
summarizeUsageFunction#
The summary of range, cut from a database's day buckets.
sumRunCostsFunction#
Sum provider-reported USD cost across every run in a session. Used to
seed the live cost indicator on session activation. Returns 0 when no
run carries a cost (most providers — only OpenRouter reports today).
supersededToolsFunction#
Tool ids to skip because a runnable language server covers them.
supportsOAuthFunction#
Whether the provider has a browser sign-in: its own OAuth flow, or the
integration it signs in with (ProviderDescriptor.integration).
testDecisionModelFunction#
Send one tiny decision to check a decision model works with this host's
credentials. decisionModel ("providerKey/modelId") is tested exactly,
with no fallback, so a broken pick is reported as broken; empty tests the
model agents would get. Never throws.
testModelFunction#
Send one tiny prompt to check a model answers with this host's
credentials. model ("providerKey[@account]/modelId") is tested
exactly, on its account, with no fallback, so a broken pick is reported as
broken. Never throws.
ThemeProviderFunction#
Provides theme to the subtree.
titleFromTurnsFunction#
Derive a short title from the first user message — returns null when empty.
tokenEndingAtCursorFunction#
Extract the whitespace-delimited token that ends at cursor. Returns
null when the cursor sits right after whitespace (nothing to complete).
toolCallPreviewFunction#
Formats a tool call as name(json args), or just the name when the input is empty.
toolResultTextFunction#
Render tool output as plain text, whether it's a string or structured content.
truncateTrailingFunction#
Truncate text to at most max characters, replacing the trailing
overflow with …. Edge cases:
max <= 0→ empty string (no room to render at all).max === 1→ just the ellipsis glyph.text.length <= max→ unchanged.
Trailing-style truncation matches the natural read order of titles: the prefix carries enough signal to identify the surface.
tryOpenBrowserFunction#
Opens a URL in the default browser, without waiting for it.
Uses open on macOS, start on Windows and xdg-open elsewhere. Failures to launch are ignored.
unwrapCallToolFunction#
Unwrap a call_tool envelope. null when name is not the dispatcher or
the envelope is malformed (missing / non-string name, non-object
arguments) — callers then treat the call as a plain call_tool call and
let the dispatcher's own schema validation produce the error the model
needs to fix its input.
arguments may be omitted for zero-argument tools: it defaults to {}.
updateAppliedMarkerPathFunction#
Returns the path of the update-applied marker file.
updateChecksOptedOutFunction#
Whether an env var (ZIDANE_NO_UPDATE, NO_UPDATE_NOTIFIER, CI) turns
background update work off. Background checks and automatic installs both
honor it; zidane upgrade does not.
updateLockPathFunction#
Returns the path of the install lock file.
updateToolEventOutcomesFunction#
Update the trailing 'tool' event matching callId so its
edit.outcomes reflects the canonical merged outcomes the chat
layer's tool:transform hook just computed. Without this, the live
diff badges stay frozen at whatever the gate set (approval-side
outcomes) and never reflect body-side failures from multi_edit's
best-effort run — only a session reload re-attaches the merged
outcomes via eventsFromTurns.
Walks back-to-front because the matching event is overwhelmingly the most recent (we're updating right after the body returned). Returns the same reference when no match is found (or the event already carries the target outcomes), so React skips the re-render.
upgradeErrorFunction#
Why an upgrade run did not land, one package per line; null when it did.
A run that found no package on PATH failed too: nothing was installed.
upgradeInstalledPackagesFunction#
Upgrades each installed target package through its own package manager.
Skips targets whose bin is not on PATH, checks the registry for each one, reports unavailable instead of installing when the tarball is not downloadable yet, runs the install, and verifies the new version on disk. Writes the applied marker when something was installed and cacheDir is set.
upsertMcpServerFunction#
Upsert entry (matched by name) into the mcps config at filePath.
Preserves the existing file's shape and every field the writer doesn't
own; creates a canonical flat-array file when none exists. Throws on
malformed JSON — silently rewriting a broken file the user is mid-edit
on would destroy their work.
usageByModelFunction#
Aggregate per-model token + spend totals across every run in a session.
Parent and subagent runs alike: each turn carries its own modelId, so
cost-tiered delegation (cheap spawn workers) shows up as separate rows
priced at their own rates. Sorted by cost (desc), then total tokens, so
the biggest spender reads first.
usageChecksOptedOutFunction#
Whether the environment forbids usage probes outright.
usageSourceForFunction#
The probe for a descriptor, or null when it has no usage surface.
useAutoInstallUpdateFunction#
Installs the release useUpdateCheck found, in the background, when
the user turned autoInstallUpdates on. One attempt per check result; the
failure record decides whether a version that failed is tried again. The
check itself runs after first paint, so this never competes with it.
Never restarts anything: the applied marker wakes useRestartRequired.
Returns the last outcome, null before the first attempt.
useColorsFunction#
Color palette only — equivalent to useTheme().colors.
useCompletionFunction#
Drive a prompt-completion popover from React state.
Inputs are pull-style — the caller owns text + cursor (typically
mirroring an OpenTUI TextareaRenderable or a <textarea> element) and
passes them in each render. Providers are matched by their trigger
character; every provider that shares the trigger at the cursor is bound
and their suggestions merge into one list.
Asynchronous suggest calls are aborted when the query changes or the popover closes, so providers that hit a backend don't leak.
useConfigFunction#
Reads the ResolvedConfig from the nearest ConfigProvider. Throws when used outside one.
useDiscoveryFunction#
Read live discovery state + actions. Throws if used outside a
<DiscoveryProvider> — discovery is a load-bearing dependency for
settings + completion popovers; bailing loud here surfaces wiring
mistakes at mount instead of producing empty catalogs at first
keystroke.
useDiscoveryOptionalFunction#
Non-throwing variant — returns null when no provider is mounted.
Used by composable modals (<SettingsModal>, …) that accept catalog
props as a fallback for embedders who don't wire the full TUI
shell. The in-app flow always mounts <DiscoveryProvider> so the
modal sees live state; standalone embeds get the prop snapshot.
useEnabledToggleSetFunction#
Bind an "enabled allowlist" setting to a discovered catalog.
keyOf extracts the persisted identity from a catalog entry (skill name,
MCP server name, …). Pass a stable, collision-free key — the persisted
allowlist is keyed against it forever.
useInteractionsActionsFunction#
Read the stable actions object.
useInteractionsQueueFunction#
Read the live queue (re-renders on every push/pop).
useMcpAuthDispatchFunction#
Returns the function that applies an McpAuthEvent to the auth state. Throws when used outside McpAuthProvider.
useMcpAuthStateFunction#
Returns the current auth state map, keyed by server name.
useMcpToolToggleMapFunction#
Bind every server in catalogByServer to its own per-tool toggle in
a single hook call. Returns a serverName → McpToolToggleSet map.
Use this when a host needs handlers for multiple servers at once
(the TUI's MCP settings panel keyboard dispatcher is the canonical
example) — calling useMcpToolToggleSet in a for / .map
over a dynamic catalog would change the hook-call order whenever a
server is added or removed, violating React's rules-of-hooks. This
hook calls useMemo exactly once regardless of server count.
Servers absent from catalogByServer get no entry in the result.
The persisted deny-list still keeps their entries on disk — they
just stay invisible to this consumer until the catalog re-includes
them.
useMcpToolToggleSetFunction#
Bind a single MCP server's per-tool toggle to
Settings.disabledMcpTools[serverName].
catalog is the FULL list of tools the server advertises (i.e. the
cached listTools() payload from chat/mcp-tools-cache.ts). The
hook needs it both to render enabledSet (every catalog tool not in
the persisted deny-list) and to garbage-collect stale deny-list
entries on every write.
useRestartRequiredFunction#
null until the first probe (or when disabled / no spec), then the live
state. Flipping enabled off tears the watcher down and clears the state
so no stale "restart" chip lingers.
userPromptCountFunction#
User turns carrying text — the prompts the user actually typed.
userScopeOverridesLoadFunction#
Whether a USER-scope SYSTEM.md would be loaded under scope.
Mirrors the candidate filter in discoverSystemMd so a host can ask
"would writing ~/.{prefix}/SYSTEM.md accomplish anything?" without
re-deriving the rule and drifting from it. 'project' excludes the user
candidate and 'none' skips discovery altogether, so under either setting
creating that file is a silent no-op.
userSystemMdPathFunction#
Absolute path of the USER-scope SYSTEM.md — the file the TUI creates when
the user asks for an override and none exists yet.
Exported so the host doesn't hardcode the layout and can't drift from what discovery actually reads.
useSafeModeActionsFunction#
Returns the approval actions. Throws when used outside SafeModeProvider.
useSafeModeQueueFunction#
Returns the pending approval requests, oldest first.
useSelectStyleFunction#
Select-row styling — equivalent to useTheme().select: the ▶ marker and accent text carry the cursor.
useSettingsFunction#
Returns the settings context value. Throws when used outside SettingsProvider.
useStreamBufferFunction#
Buffers streaming deltas and commits them to the transcript on a ticker, in smooth or batched mode.
useSurfacesFunction#
Panel / surface backgrounds — equivalent to useTheme().surfaces.
useSyntaxStylesFunction#
Raw syntax style table — useTheme().syntax. Renderer converts to its native style type.
useThemeFunction#
Returns the current theme. Falls back to DEFAULT_THEME outside a ThemeProvider.
useUpdateCheckFunction#
Returns the current update status. The check fires:
- Once per mount (every TUI launch).
- Every
recheckMsafter that, when set. - Every time
enabledflips fromfalse→true(user re-enabling the setting expects an immediate refresh).
The check is async and deferred by delayMs so it never competes with
first paint. Result is null until the first check resolves; flipping
enabled to false resets to null so any chip rendered against
hasUpdate disappears immediately.
The hook owns its own AbortController so an unmount cancels any in-flight registry request cleanly.
verifyEnvironmentFunction#
"Test connection" for kind; a throwing or missing verify reads as a failure with the reason.
viewPlansFunction#
What a session's readers see: every kept plan, with an applying plan whose run is not live marked as possibly interrupted. Never writes.
watchInstalledVersionFunction#
Starts watching the disk for a newer install of the running package.
The watcher probes once on creation, then on every poll and on changes to the applied marker. It calls onChange only when the installed version, the restart flag or installing changes. It stays idle when currentVersion is empty.
With cacheDir, an install holding the lock there (auto-update-lock.ts) holds the probe: the state says installing, never restartRequired, and is checked again every installingPollMs until the lock is released.
withRunningCallStartsFunction#
events with each running call's start from the host's running work, a
subagent's call matched by its childId, and its resuming mark (a
call of a batch a durable run resumed after a process death). events
itself when nothing is stamped.
workspaceEntryOpsFunction#
The entry actions of cwd, a folder of this machine.
workspacePathFunction#
path in a session workspace rooted at root (POSIX resolve): relative
paths against root, absolute paths as given. The same resolution the
execution contexts apply against their handle's cwd, so a workspace call
means what the agent's own tools mean; containment is the context's own
(sandboxes confine to their workspace root, the local process context
doesn't). Clients that must stay inside the workspace (the GUI's file
panels) guard their paths themselves.
writeCredentialEntryFunction#
Write (or, undefined, delete) one entry by its file key, under the same
lock, mode and atomic write as every credential write. Refuses provider
slot keys (#): those go through the provider writers above.
writeCredentialsFunction#
Write credentials atomically (write-then-rename) with mode 0o600.
Atomic on the same filesystem — readers either see the previous file or the
new one, never a half-written intermediate. Creates the parent dir if needed
(first launch on a fresh machine: ~/.zidane/ may not exist yet).
writeFailedUpdateFunction#
Records a failed automatic install. When the cache dir can't be written, the record is kept in memory for this process, so a broken cache never turns into a package-manager run on every check.
writeProjectsFunction#
Writes projects.json atomically, creating the directory when needed.
writeSessionExportFunction#
Render session and write the resulting bytes to disk. Returns the
resolved target so the caller can show the user where the file
landed. The parent directory is created on demand (recursive: true)
— first-time exports don't need any pre-flight setup.
writeUpdateAppliedMarkerFunction#
Record that an install just landed. Best-effort: a failure to write the marker must never fail the upgrade that succeeded — the poll catches up.
writeWorkspaceFileFunction#
Atomic, guarded write for the panel editor: temp file + rename in the same
directory, only when the on-disk mtime still equals expectedMtimeMs.
A small race window remains between the stat and the rename; acceptable
for a human-driven save.
Classes#
EditOutcomeLedgerClass#
Holds the per-edit approval outcomes of in-flight tool calls, keyed by call id.
EnvironmentNotReadyErrorClass#
A session whose environment can't run yet (provisioning) or can't run at all (failed).
Constants#
ACCOUNT_CRED_KEY_INFIXConstant#
Reserved infix marking one of a provider's ADDITIONAL OAuth accounts:
foo#account:1, foo#account:2, …
ACTIONS_WITH_CARE_DOCTRINEConstant#
Reversibility / blast-radius doctrine. Mirrors claude-code's # Executing actions with care (255-267). The TUI's safe-mode already gates risky
tool calls behind explicit approval, but this prompt teaches the model
to anticipate the gate rather than be surprised by it — and to ask
before reaching for destructive shortcuts.
ALTERNATE_CRED_KEY_SUFFIXConstant#
Reserved suffix marking a provider's SECOND credential slot.
Not usable as (or as the tail of) a descriptor's credential key: foo#alt
holds foo's alternate credential, so a provider claiming that name would
share storage with it.
anthropicDescriptorConstant#
Descriptor for Anthropic, with OAuth and API-key accounts.
ARTIFACTS_COMPLETION_PROVIDER_IDConstant#
Id of the artifacts completion provider.
ASK_USER_TOOLConstant#
Canonical name of the tool that asks the user one or more questions.
AUTO_INSTALL_RETRY_BACKOFF_MSConstant#
Waits before retrying a version whose install failed in a way that may pass on its own: after the 1st, 2nd and 3rd such failure. A 4th is final.
AUTOMATIC_INTERACTION_INSTRUCTIONConstant#
Instruction sent to the model when automatic mode answers an interaction on the user's behalf.
BUILD_AGENTConstant#
Build agent — the default profile. Full read/write/shell access plus
subagent spawning. Its tools are those of the basic preset plus glob,
grep, web_search and fetch_url.
The system prompt is the cwd-less variant of buildBuildSystem;
the TUI overrides it per-session with an env-anchored composition so
the prompt carries the current project root + date. SDK consumers
calling createAgent({ ...BUILD_AGENT.preset }) directly get the
cwd-less prompt and can wrap their own env section.
BUILD_CODEMODE_AGENTConstant#
Codemode — Build's tools, reached through scripts. codemode in
'only' mode: every native tool a script can call leaves the wire and is
declared inside the codemode description, so the model works in scripts
by default. spawn is callable from scripts, so it leaves the wire too.
Tools scripts cannot call stay declared. Shown only while the Codemode
setting is on.
BUILTIN_AGENTSConstant#
Default registry of the built-in profiles. Insertion order = picker order.
Hosts that want only one profile can pass { agents: { build: BUILD_AGENT } },
or a fully custom registry of their own profiles.
BUILTIN_PROVIDERSConstant#
Default provider registry. Passed verbatim when runTui is invoked without
an explicit providers option. Hosts that want to override per-provider
metadata can spread this and replace specific entries:
runTui({ providers: { ...BUILTIN_PROVIDERS, anthropic: myOwnAnthropicDescriptor } })
cursor is intentionally NOT registered here: OAuth works, but inference
isn't wired (cursor.stream() throws — Cursor speaks a protobuf/HTTP-2
agent protocol, not OpenAI-compat). Shipping it in the picker only lets users
select a model that errors every turn. The descriptor stays exported so a
host can opt in ({ ...BUILTIN_PROVIDERS, cursor: cursorDescriptor }) once
the transport lands — re-add it here at that point.
BUILTIN_SUBAGENTSConstant#
Claude-trained models emit subagent_type: 'Explore' / 'Plan'. Shipping
both gives those calls a target. No model: the subagentModels setting
or the parent model applies. A file agent with the same name overrides.
BUILTIN_THEMESConstant#
Built-in theme registry, keyed by theme.id. The TUI looks up the active
theme here using Settings.theme; unknown ids fall back to
DEFAULT_THEME. Extensions add themes with ctx.registerTheme. The
resolver receives them as extraThemes, and built-ins win on an id collision.
Insertion order is the picker cycle order — keep default first so a
fresh install (no theme in state.json) sees the default theme
before the others.
CALL_TOOL_NAMEConstant#
Name of the call_tool dispatcher tool.
CATPPUCCIN_FRAPPEConstant#
Catppuccin Frappe, the lightest of the dark Catppuccin flavors.
CATPPUCCIN_LATTEConstant#
Catppuccin Latte, the light Catppuccin flavor. It assumes a light terminal background.
CATPPUCCIN_MACCHIATOConstant#
Catppuccin Macchiato, a dark flavor between Frappe and Mocha.
CATPPUCCIN_MOCHAConstant#
Catppuccin Mocha, the darkest Catppuccin flavor.
cerebrasDescriptorConstant#
Descriptor for Cerebras, defaulting to gpt-oss-120b.
CLAUDE_IMPORT_NOTESConstant#
What an import from Claude Code deliberately leaves alone, spelled out for the UI.
COMMUNICATION_DOCTRINEConstant#
User-facing communication style. Lifted from claude-code's
# Communicating with the user + # Tone and style sections (~404-442).
The "no colon before tool calls" rule matters because the TUI renders
the model's text and the tool call as separate blocks — a trailing
colon reads as a broken sentence.
CRED_KEY_SLOT_SEPARATORConstant#
Separator between a provider's canonical key and a slot qualifier. Every
non-canonical slot (#alt, #account:N) starts with it, so the character is
reserved in descriptor credential keys outright.
DEFAULT_AGENT_IDConstant#
Id of the profile activated on first launch when nothing is persisted.
DEFAULT_BUDGET_EXCLUDE_TOOLSConstant#
Tools whose output is exempt from the per-turn toolOutputBudget accounting,
for SDK consumers that turn the budget on. The built-in profiles leave it
off.
These tools exist to LOAD context into the conversation — their text output
IS the value of the call. Counting it against the budget steers the model
away from the very tool it needs to make progress (e.g. a 78 KiB
tool_search response for a 20-tool Notion MCP server would trigger the
"summarize before calling more tools" nudge on the very turn that
unlocked those tools, making them effectively unusable).
Note this list is intentionally narrower than DEFAULT_PERSIST_EXCLUDE_TOOLS:
read_file is NOT exempt — a 200 KiB file load is exactly the case the
budget should steer against. Same for spawn (a sprawling subagent
report should still nudge a consolidation pass).
Exported so SDK consumers building custom profiles can extend the list for host-defined context-loading tools.
DEFAULT_KEYBINDINGSConstant#
Defaults, derived from KEYBINDING_DEFS so the two never drift.
DEFAULT_MAX_TODO_ITEMSConstant#
Ceiling on one list; every write boundary caps identically.
DEFAULT_PERSIST_EXCLUDE_TOOLSConstant#
Tools the chat layer never persists to disk, regardless of output size.
Rationale per entry:
read_file— our reader is already paginated (offset+limit). Persisting the slice the model asked for and pointing it at the persisted path is circular; if the model wants more, it pages.tool_search— short metadata envelope. Never large.skills_use/skills_read— the<skill_content>body is intentionally part of the prompt; persisting it defeats the purpose.read_chat_turns— previous-chat excerpts are explicitly loaded conversation context; persisting them defeats the purpose.present_plan/ask_user— short JSON envelopes (decision + answers). Never large.spawn— the subagent's final report IS the value of the call; stubbing it out would defeat the orchestration pattern.codemode— a script prints what the model asked for, as a read does, and caps its own output (max_output_tokens: start and end inline, the full text in a file). Persisting it would force a re-read.
Exported so SDK consumers building custom profiles can extend the list
(e.g. host-defined screenshot tool whose base64 payload should stay
inline). Set behavior.persistExcludeTools to your own list to fully
override.
DEFAULT_THEMEConstant#
The default dark theme.
DOING_TASKS_DOCTRINEConstant#
Software-engineering doctrine. Lifted in spirit from claude-code's
# Doing tasks (constants/prompts.ts:199-253). Key levers:
- Stick to scope — prevents speculative refactors that double output tokens.
- No narration comments — prevents inflating diffs with
// Import the modulelines. - Verify before claiming done — prevents false-positive reports that force a follow-up turn.
EMPTY_HINTSConstant#
Stable empty list so callers can compare by reference. Exported so
any consumer that needs to feed "no primary hints" into the same
clipHintsToWidth / renderHintSpans pipeline (e.g. the TUI's
minimal UI mode, where the prompt overlay shows only @ / /
triggers) reuses the same frozen array instead of allocating a new
one each render.
ENTRY_EMPTY_DIRS_LIMITConstant#
Most empty folders a listing adds.
ENVIRONMENT_METADATA_KEYConstant#
Session metadata key that stores the SessionEnvironment.
FEATURED_PROVIDERSConstant#
Providers shown first in Connect. The rest sit under "More".
GRUVBOX_DARKConstant#
Gruvbox with a dark background.
GRUVBOX_LIGHTConstant#
Gruvbox with a light background.
HOST_ENABLED_LISTSConstant#
The per-server lists a host leaving unset means its defaults for: everything enabled, each server's own shared.
HOST_INTERACTION_ID_PREFIXConstant#
Id prefix for interactions the HOST synthesizes — slash commands and
extension ctx.interaction.* share the prompt slot with the tools but
never pass through createInteractionTools. Model-originated
requests carry the provider's tool_call.id instead. Naming only:
origin policy reads BaseRequest.origin, never the id.
IDENTITY_PREFIXConstant#
Lead line — short, version-stable. The first sentence matches the key of Claude Code's identity prefix (models anchor faster on familiar shapes). The rest sets the register: token-earning sentences with byte-exact code ("small mouth, full brain"), and a hard rule that speed never widens scope (the leeroy-jenkins fix). Keep changes rare — each one costs a cache miss across active sessions.
IMPLICITLY_SAFE_TOOLSConstant#
Tools that always pass without prompting. Four categories, plus the dev-browser, terminal-read and side-session tools noted inline in the list:
- Pure reads (
read_file,list_files,glob,grep) — no side effects on disk or the model's own state. - Interaction tools (
ask_user,present_plan) — the call itself surfaces a TUI picker the user has to answer, so prompting for approval first would mean "approve this prompt before you see the prompt": redundant + breaks the flow. The picker IS the gate. - Todos (
todowrite,todoread) — write to a slot onsession.metadata.todosand nothing else. No shell, no disk, no network. The model uses these for checkpointing every few steps; a per-call approval prompt would drown the conversation in interruptions that buy no safety since the tool's surface is read/write on a metadata bag we already trust the agent with. - Skill activation (
skills_use) — mutates a small per-agent Map of active skills and returns the activated skill's bundled instructions (or releases an entry onmode: "deactivate"). Pure state on the agent — no shell, no disk writes, no network. Gating it would also defeat the "model recovers fromAgentToolNotAllowedErrorby callingskills_use({ mode: "deactivate", name })" path: a stuck model would have to ask the user permission to unstick itself on every retry.skills_readandskills_run_scriptare intentionally NOT on this list — the former touches disk and the latter executes arbitrary scripts, so both keep going through the regular gate.
Users who want to gate any of these must disable safe-mode entirely (or fork this list in their own embedding).
INTERACTION_GUIDANCEConstant#
How to use present_plan / ask_user. Kept short — the tool descriptions
carry the schema details; this prompt covers the cross-cutting when.
Exported so a custom profile can pull it in independently.
INTERACTION_GUIDANCE_NO_PROMPTSConstant#
Variant of INTERACTION_GUIDANCE for the no-interactive-prompts
configuration (Settings.interactionMode = 'disabled'). The two tools are
stripped from the agent's tool set; this section tells the model to
operate autonomously and surface assumptions / open questions in its
final prose message rather than via tool calls.
KEYBINDING_DEF_BY_ACTIONConstant#
Index by action for O(1) lookup of label / description / default.
KEYBINDING_DEFSConstant#
The canonical action catalog. Order is the source of truth for the generated keybindings file and the settings UI.
KEYBINDING_KEY_COL_WIDTHConstant#
Width (in cells) of the fixed key column used by every binding-row
renderer. Derived once from KEYBINDING_DEFS so a new action
with a wider default spec (ctrl+shift+x, …) automatically grows
the column instead of truncating the label.
LOCAL_ENVIRONMENTConstant#
The local environment: the current checkout, always ready. Sessions without environment metadata read as this.
localDescriptorConstant#
Local OpenAI-compatible LLM (Ollama, vLLM, LM Studio, Lemonade, llama.cpp).
No fixed base URL or model catalogue — both come from the user via
customFields. No envKey, so the wizard skips the API-key prompt and
treats the customFields-only credential as the auth signal (see
applyApiKeyEnv + detectAuth).
Vision / cache / reasoning are off by default in the factory — flip them
by passing a custom descriptor that calls local({ capabilities }).
models is a getter, not a static list: there's no fixed catalogue to ship,
but once the user has configured a default model (mirrored into
LOCAL_LLM_DEFAULT_MODEL by applyApiKeyEnv), we surface it as a
single-entry list so the model picker + footer aren't empty. Resolved at
access time because the env var is populated at TUI launch, after this
module loads. Empty list when unconfigured — the picker hides, the user
types a slug at the prompt as before.
localEnvironmentProviderConstant#
The provider for the local environment: the current checkout, with commands on this machine.
MAX_CLOSED_PLANS_PER_SCOPEConstant#
Closed plans kept per scope; older ones are pruned (the transcript keeps them).
MAX_PLAN_HISTORYConstant#
Earlier proposals kept on a revised plan.
MAX_PLAN_STEPSConstant#
Steps per plan; matches the todowrite cap.
openaiDescriptorConstant#
Descriptor for OpenAI through the Codex credentials, with accounts.
openrouterDescriptorConstant#
Descriptor for OpenRouter, with a metadata alias for retired Claude slugs.
PLAN_AGENTConstant#
Plan agent — read-only exploration mode. Locked down to file reading and codebase search; no shell, no edits, no spawning. The system prompt frames the conversation as planning rather than execution so the model outputs proposals instead of attempting mutations.
In Build's family: a session switching between them keeps Build's agent, a gate enforces Plan's tools and its rules arrive as a note.
PLAN_EDITED_NOTE_KINDConstant#
Note kind of user edits delivered at run start.
PLAN_MODE_DOCTRINEConstant#
Plan-mode framing with explicit phases (explore → ask → propose), drawing
on claude-code's iterative-plan mode (utils/messages.ts:3323-3383).
Paired with the read-only tool set in PLAN_AGENT.
PLAN_MODE_DOCTRINE_NO_PROMPTSConstant#
Variant of PLAN_MODE_DOCTRINE for the no-interactive-prompts
configuration. It has no "Ask" step, and "Propose" tells the model to
write the plan directly in its final message instead of calling
present_plan.
PLAN_STOPPED_NOTE_KINDConstant#
Note kind of a stopped plan's notice.
PLANS_METADATA_KEYConstant#
session.metadata[PLANS_METADATA_KEY]: PlansBag.
PRESENT_PLAN_TOOLConstant#
Canonical name of the tool that presents a plan for approval.
SELF_UPDATE_TIMEOUT_MSConstant#
Default for PerformSelfUpdateOptions.timeoutMs.
SETTINGS_CATEGORIESConstant#
Ordered list of categories. Display order in any consumer (TUI tabs, GUI sidebar, settings JSON dump) should match this array — keeps mental model consistent across surfaces.
SETTINGS_DEFAULTS_VERSIONConstant#
Current defaults revision. Bump it with a new PREVIOUS_DEFAULTS entry when a default changes.
SETTINGS_DEFAULTS_VERSION_KEYConstant#
Key of the stored settings slice naming the defaults revision it was migrated to.
SETTINGS_INPUTSConstant#
Every free-text setting the settings UI lists, in display order.
SETTINGS_SECTIONSConstant#
Section headers for the settings lists: each tab shows its rows grouped
under these titles, in this order. A key missing from the table lands in
Other at the end, so a new setting still shows up somewhere.
SUBAGENT_GUIDANCEConstant#
How to brief a subagent. Spawning a child agent is the highest-leverage token move in zidane — a 5k-token research dive becomes a 200-token summary in the parent's context. But shallow prompts produce shallow work, so the doctrine is mostly about quality of the briefing.
Lifted from claude-code's ## Writing the prompt tool-prompt
(tools/AgentTool/prompt.ts:99-113).
TITLE_CHECK_KEYConstant#
The last auto-title attempt's outcome (TitleCheckRecord), shown in session details.
TITLE_CHECKED_KEYConstant#
User-prompt count at the last staleness check (or generation).
TITLE_SOURCE_KEYConstant#
Metadata key that records whether the title was set by auto-titling or by the user.
TODOREAD_TOOLConstant#
Canonical name of the tool that reads the todo list.
TODOWRITE_TOOLConstant#
Canonical name of the tool that replaces the todo list.
TOKEN_DISCIPLINE_DOCTRINEConstant#
zidane-specific token-economy doctrine. No claude-code analog — this is
the prose half of the behavior.{compactStrategy, elideStaleReads, toolDisclosure, readFileDefaults} defaults. The behavior flags do the
heavy lifting at the wire level; this prompt nudges the model away from
the access patterns that defeat them.
TRANSCRIPT_TRIM_STEP_EVENTSConstant#
Most events one stepTranscriptCap drops. A cap that has thousands
of rows to cut (the history a reveal brought in, once the viewport is back
at the bottom) unmounts them over several commits of this size instead of
freezing one frame on all of them.
UPDATE_APPLIED_MARKERConstant#
File name of the update-applied marker inside the cache directory.
UPDATE_FAILED_FILEConstant#
File name of the failed-install record inside the cache directory.
UPDATE_LOCK_FILEConstant#
File name of the install lock inside the cache directory.
UPDATE_LOCK_STALE_MSConstant#
A lock older than this is stale when its holder can't be probed (another host, or no pid).
UPDATE_LOG_FILEConstant#
File name of the worker's log inside the cache directory.
UPDATE_RESULT_FILEConstant#
File name of the worker's result inside the cache directory.
USAGE_CACHE_TTL_MSConstant#
How long a snapshot stays fresh. Usage windows move in minutes, not seconds.
VAPORWAVE_THEMEConstant#
Vaporwave, a dark theme with neon colors.
watchGitRepositoryConstant#
Watches cwd's repository; resolves the stop, or null when cwd is not in one.
On macOS a recursive watch rides the thread's FSEvents stream, which every start and stop rebuilds, and a stop waits for that rebuild: seconds when the system's file events are busy. A process that must not wait (the desktop app's main thread) runs it on a thread of its own.
WINDOW_LOCAL_SETTINGSConstant#
Settings that belong to the window even while a host owns the settings file (daemon or remote mode): which host the next launch uses.
WORKSPACE_MAX_ENTRIESConstant#
Most entries a listing returns.
WORKSPACE_MAX_FILE_BYTESConstant#
Largest file read whole; past it a read is cut.
WORKTREE_ENVIRONMENT_KINDConstant#
Environment kind of worktree sessions.
Interfaces#
ActivePlanSummaryInterface#
The one-line summary the composer pill and the TUI footer show.
AgentCompositionInterface#
What a session's agent is built with: tools and prompt. key names it
(family:<name> or profile:<id>) and keys the session's frozen prompt.
AgentProfileInterface#
A selectable agent profile: a labelled preset the user can switch between.
AgentsMdFileInterface#
A single loaded AGENTS.md file.
AgentsMdResultInterface#
Result of discoverAgentsMd. files is empty when none were found.
ApiKeyCredentialInterface#
A stored API key credential.
ApplyPlanResultInterface#
Result of applyPlanEvent.
ApprovalHubInterface#
Safe-mode gate that holds tool calls until a client approves or denies them.
ApprovalRequestInterface#
A tool call waiting for the user's decision.
ApprovalRequestInputInterface#
What the agent loop hands the hub to request approval for a tool call.
ArtifactKindsHostInterface#
One registry build's artifact kinds.
ArtifactReferenceDataInterface#
Provider payload for an artifact reference.
ArtifactReferenceEntryInterface#
An artifact that can be referenced from a prompt.
ArtifactViewGroupInterface#
Artifacts of one kind, ready to display.
ArtifactViewRowInterface#
One artifact paired with its rendered row.
AutoUpdateConfigInterface#
Host-supplied auto-update settings. The check itself is gated on
Settings.checkForUpdates; passing a config wires the React plumbing.
Hosts that want to publish their own consumer-facing package can pass different values without forking anything — the registry / channel / platform-package-prefix are all knobs.
BuildHintsOptionsInterface#
Options bag for buildHints. Flat shape so call sites read as a
checklist of "what state do I have to surface" — easy to thread
through React useMemo deps and to construct fresh in tests.
BuildSystemOptionsInterface#
Options for buildBuildSystem and buildPlanSystem.
BuildUpdateHintOptionsInterface#
Display options for the update and restart hints.
BuiltinEnvironmentOptionsInterface#
Options for builtinEnvironmentProviders.
CachedMcpToolListInterface#
One server's cached entry.
tools— verbatim copy of the rawtools/listpayload (pre anydisabledTools/toolFilterfiltering). The settings UI ranges over this to render the full server surface; the host applies its own deny-list on top viaSettings.disabledMcpTools(seebuildMcpServersinmcps-discovery.ts).updatedAt— ms-epoch of the bootstrap that populated this entry. Useful for "last seen N hours ago" affordances and for cache eviction policies a host might layer on later.transport— informational only; lets the UI distinguish a stdio server's tool list from an http server with the same name in "stale catalog" warnings.
ChatHostInterface#
The transport-agnostic chat engine. It owns sessions, runs, approvals and queues, and talks to clients through the broadcast of its ChatHostEnvironment. Create one with createChatHost.
ChatHostEnvironmentInterface#
What an embedder supplies to createChatHost: how to reach clients, the session store, settings and runtime configuration.
ChatOptionsInterface#
Options accepted by resolveConfig() (and, transitively, by runTui() and
any future GUI launcher). Every field is optional — defaults boot a working
chat against the built-in providers with sessions stored under ~/.zidane/.
ChatTurnsReadToolOptionsInterface#
Options for createChatTurnsReadTool.
CheckForUpdateOptionsInterface#
Options for checkForUpdate.
ChipColorInterface#
Background + foreground pair for a completion-reference chip pill.
ClaudeCopyResultInterface#
Result of copying one category of Claude Code definitions into zidane.
ClaudeImportActiveHostInterface#
The host a window is using, as far as the import note cares.
ClaudeImportOptionsInterface#
Options for locating and importing Claude Code data.
ClaudeImportSummaryInterface#
What importFromClaudeCode imported. A category is absent when it was switched off.
ClaudeSessionImportResultInterface#
Result of importing Claude Code session transcripts.
CloneRunInterface#
A clone in flight.
CommandAgentResultInterface#
Result of driving the agent from within a step via ctx.runAgent.
CommandArgSuggestionSummaryInterface#
Wire-safe projection of canonical CommandArgSuggestion.
CommandAttachmentInterface#
A prompt attachment forwarded into a command invocation — captured when
the user submits /cmd … with pasted images/files attached. data is
base64 for EVERY media type (including text/plain): one encoding keeps
the contract lossless for binary and host-agnostic, at the cost of a
trivial decode for text consumers.
CommandExecutionInterface#
Outcome of a command run. error is set when a step threw (pipeline stops).
CommandInteractionInterface#
User-interaction surface for commands — the same prompt-slot primitives
the ask_user / present_plan TOOLS render, but WITHOUT the tools: a
command enqueues directly into the host's interaction queue. No tool
calls, no turns, no model involvement — the answer routes straight back
to the awaiting step. Every method rejects on cancel/esc, which the
executor classifies as a quiet abort.
CommandOutputBlockInterface#
A block of local output a step renders into the chat.
Plain blocks (text only) render as full markdown, both live and on
reload — use them for the output the user should read in full (e.g. a
final commit message). Blocks with detail render as a collapsed
command-detail row instead (dim â–¸ label + line-capped body with
"… N more lines") — use them for bulky supporting output (diffs, logs,
listings) that shouldn't drown the transcript.
CommandSpawnResultInterface#
Outcome of one CommandSpawnTask.
CommandSpawnTaskInterface#
One task for CommandStepContext.spawnAgents — an isolated child agent run.
CommandStepInterface#
One step of a command pipeline.
CommandStepContextInterface#
Capabilities + inputs handed to every step.
CommandStepResultInterface#
Optional per-step return — data is merged into the shared bag for later steps.
CommandSummaryInterface#
Wire-safe summary of an extension-contributed / command — the
projection of canonical Command (src/chat/commands.ts) minus its
function-valued fields (steps, completeArgs).
CompactionEntryInterface#
The live session state a compaction needs.
CompactionReportInterface#
What a compaction did, for the caller's confirmation (the TUI's "compacted N turns" banner).
CompanionSpecInterface#
Identifies a companion package and its executable.
CompletionStateInterface#
State surface returned by useCompletion().
ConfirmQuestionInterface#
A yes/no question.
ContentMatchInterface#
One matching line.
ContentSearchOptionsInterface#
Options of searchWorkspace.
ContentSearchResultInterface#
A search in files.
ContextSegmentsReportInterface#
Instructions-tab payload. Mirrors the TUI's getContextSegments contract so
both settings surfaces render identical rows and identical explanations for
why a SYSTEM.md override can or cannot apply.
CreateExtensionMcpHostOptionsInterface#
Options for createExtensionMcpHost.
CreateInteractionToolsOptionsInterface#
Options for createInteractionTools.
CreatePlanToolsOptionsInterface#
Options for createPlanTools.
CreateSessionInStoreParamsInterface#
Fields stamped on a new session at creation.
CustomFieldInterface#
Free-form configuration field that a provider needs the user to supply alongside (or instead of) an API key — e.g. a self-hosted base URL, an Azure deployment name, a default model id.
The wizard prompts for each field in order. Submitted values are persisted
into the apikey credential (as customFields[key]) and mirrored into
process.env[envVar] so the provider's factory can read them via the same
env-var convention as envKey.
Descriptors without an envKey use customFields as the sole credential
mechanism — the wizard skips its API-key step in that case.
DecisionModelEntryInterface#
A model that can serve agent decisions, with its availability.
DecisionTestResultInterface#
Outcome of testDecisionModel.
DetectOnboardingOptionsInterface#
What detectOnboardingEnvironment reads.
DetectOtherAgentsOptionsInterface#
Where to look for other agents' configuration.
DetectPackageManagerOptionsInterface#
Options for detectPackageManager. Every field overrides a value read from the running process, which keeps detection testable.
DiagnosticInterface#
One finding from a project tool, positions 1-based like editors show them.
DiagnosticsResultInterface#
A diagnostics run.
DiagnosticsToolContextInterface#
What a tool's detection and run work with.
DiagnosticsToolInfoInterface#
A diagnostics tool, as found for a folder.
DiscoverAgentsMdOptionsInterface#
Options for discoverAgentsMd.
DiscoveredMcpInterface#
One entry in the discovered list. path is the source file (one of
the mcp(s).json variants under .agents/ or .{prefix}/) so a
Settings picker can show "Defined in ~/.zidane/mcp.json" tooltips
and the user can tell which file declared what.
DiscoveredPluginInterface#
One plugin found on disk, loaded (successfully or not).
DiscoverSystemMdOptionsInterface#
Options for discoverSystemMd.
DiscoveryContextValueInterface#
Skills, plugins and MCP servers found on disk, shared with the UI.
DiscoveryErrorInterface#
Per-file failure surfaced from discoverProjectMcps. The TUI shows
these in the MCP settings empty / preamble state so a malformed
mcps.json doesn't look identical to a missing one.
DiscoveryResultInterface#
Result of discoverProjectMcps. servers is the per-source-priority
merged list (project beats user, first-found wins on name collision).
errors is one entry per file that existed but failed to parse, plus
informational entries for servers a security gate skipped (ruler stdio
without the foreign-agent opt-in) — empty on the happy path.
DiscoverySlotInterface#
Handle returned by createDiscoverySlot.
DiscoverySlotOptionsInterface#
Options for createDiscoverySlot.
EditHunkInterface#
One old-to-new replacement of an edit.
EditOutcomeInterface#
Result of one edit hunk.
EditPayloadInterface#
Structured edit data attached to a tool event for edit /
multi_edit / write_file. Lets the renderer compute a unified diff
without re-parsing the JSON input string.
editproduces one hunk withreplaceAlldefaulting to false.multi_editproduces one hunk peredits[]step (in order).write_fileproduces a single hunk whereoldStringis the pre-write file content (empty for a fresh create) andnewStringis the new content;replaceAllis meaningless here and absent.
Live capture happens in the host's tool:before hook (where the
pre-write snapshot can be read off disk before the tool runs).
Historical replay from persisted turns can only reconstruct the
edit/multi_edit shape — write_file historical events have no
pre-write content and render with oldString: '' (= every line is
an addition), matching git's "new file" diff convention.
EnabledToggleSetInterface#
Reactive handle over a persisted enabled-names allowlist, returned by useEnabledToggleSet.
EnvironmentActionInterface#
A per-session command a kind offers (session menus): push the branch, open a PR, …
EnvironmentActionInputInterface#
Input to an EnvironmentAction's run.
EnvironmentActionResultInterface#
Outcome of running an EnvironmentAction.
EnvironmentActionSummaryInterface#
Wire-safe EnvironmentAction — what session menus list.
EnvironmentAvailabilityInputInterface#
Input to a provider's available and note checks.
EnvironmentCheckoutInterface#
A worktree on an existing branch: the local branch when there is one, else origin's (untracked), else, with
pullRequest, that pull request's head fetched into the branch. When none of them exists, the branch is cut
from base as usual (a ticket's branch nobody started yet).
EnvironmentConfigFieldInterface#
One option a provider declares. Settings UIs render these generically
(no per-kind UI code); environment-settings.ts stores, validates and
resolves them.
EnvironmentDescriptorInterface#
Wire-safe description of one environment kind, as returned by describeEnvironments.
EnvironmentExecutionInterface#
The execution context a provider builds for a ready environment, with its cache key.
EnvironmentExecutionInputInterface#
Input to a provider's execution factory.
EnvironmentFieldDescriptorInterface#
Wire-safe description of one environment option, for pickers and settings sections.
EnvironmentPrepareInputInterface#
Input to a provider's prepare step.
EnvironmentPrepareResultInterface#
What a provider's prepare step produced.
EnvironmentProviderInterface#
One kind of session environment: how it is offered, prepared, executed in, acted on, and torn down. Register providers with createEnvironmentRegistry.
EnvironmentRegistryInterface#
Lookup and registration of EnvironmentProviders by kind.
EnvironmentRequestInterface#
What a creator asks for — the host turns it into a SessionEnvironment.
EnvironmentSecretsInterface#
Where secret fields live — see environment-credentials.ts.
EnvironmentSettingsInterface#
Settings.environments. Every part optional: absent = defaults.
EnvironmentSettingsChangeInterface#
One edit from a settings UI.
EnvironmentSettingsWriteInterface#
Result of applyEnvironmentSettingsChange: the settings and secret writes to perform.
EnvironmentTeardownResultInterface#
Outcome of tearing down a session's environment.
EnvSectionOptionsInterface#
Options for envSection.
FailedUpdateRecordInterface#
The automatic install that failed last.
FetchGithubUsageOptionsInterface#
Options for fetchGithubUsage.
FetchOAuthRedirectResultInterface#
Outcome of calling the loopback callback server.
FetchProviderUsageOptionsInterface#
Options for the provider usage fetchers.
FetchRepoInfoOptionsInterface#
Options of fetchRepoInfo.
FileEntryInterface#
One row in the project file catalog. path is forward-slashed + relative to cwd.
FolderLocationInterface#
Where a folder sits: its checkout, and the project that checkout belongs to.
FollowRunningUpdateOptionsInterface#
Options for followRunningUpdate.
ForkSessionParamsInterface#
Inputs to forkSession.
GenerateStructuredDataOptionsInterface#
Options for generateStructuredData.
GitBranchRowInterface#
A local branch in the switcher: when it last moved, and how it stands against the default branch.
GitCommitInfoInterface#
One commit, for a sha chip's hover card.
GitInfoInterface#
The composer's git bar: where the checkout stands.
GitPrInterface#
The branch's open (or draft) pull request, from gh.
GitPrItemInterface#
An open pull request in the switcher (gh pr list).
GitStatusEntryInterface#
One path's git status.
GitWatchesInterface#
Shared repository watchers, from createGitWatches.
HintInterface#
Single hint entry — <key> <label>, optionally followed by an inline
secondary chord (<key><extra.key> <label> <extra.label>) for compound
shortcuts like ctrl+m/l model effort.
Colour fields are advisory hex strings (resolved against the active
theme by the renderer); leaving them undefined lets the renderer pick
its conventional fallback (e.g. warn for keys, dim for labels; the
secondary chord takes its key's color).
HostRegistryInterface#
Saved remote hosts and their tokens, persisted under the data directory.
ImageModelEntryInterface#
An image model for the pickers, with its availability.
InlineAutocompleteContextInterface#
Input handed to an InlineAutocompleteProvider on each query.
InlineAutocompleteProviderInterface#
Source of inline ghost-text suggestions. Providers are queried in order by resolveInlineSuggestion.
InPlaceUpdateResultInterface#
Outcome of performInPlaceSelfUpdate.
InstalledCompanionInterface#
A companion package found on disk.
InstalledVersionStateInterface#
Snapshot of the running version against the version installed on disk.
InstalledVersionWatcherInterface#
Handle returned by watchInstalledVersion.
InteractionHubInterface#
Holds interactive requests from the model (questions, plans) until a client answers them.
InteractionsActionsInterface#
Stable queue actions exposed by InteractionsProvider. Read them with useInteractionsActions.
KeyBindingDefInterface#
Static metadata for one action — used by the loader, hint rows, settings UI.
KeyBindingSectionInterface#
One contiguous section of the catalog — every adjacent action of a single
group rendered together with the section header inserted once.
Non-adjacent runs of the same group are NOT merged: catalog order
wins so the on-screen story matches the on-disk file.
rows may carry built-in KeyBindingDefs (the common case) or
extension-owned ones (when an extension contributes a keybinding).
Both share label / description / spec — see KeyBindingRow.
ListExtensionSourceOptionsInterface#
Options of listExtensionSource.
ListProjectFilesOptionsInterface#
Options for listProjectFiles.
LocalEntryOpsInterface#
The entry actions of a local folder, plus copying in paths of this machine.
MarkdownDefDiagnosticInterface#
A non-fatal problem with one markdown definition file. The file may still load.
McpServerStatusInterface#
One server's state beside its config.
McpTestOutcomeInterface#
The last Test of a server: how it answered, and when.
McpToolToggleSetInterface#
Per-tool enable state and toggle handler for one MCP server.
ModelAliasContextInterface#
Context for resolving Claude model: aliases in agent files.
ModelApprovalInterface#
A decision model's verdict on one tool call: what it chose and how sure it
was (p, absent when the provider reports no probability). On a tool
event: the call was auto-approved (approve) or auto-denied (deny_*).
On an approval request: the model's concern when it handed the call to you.
ModelFallbackTargetInterface#
The model a session runs on, wire-named: provider, model and (optionally) the stored account of the provider (a credential's stable id; absent = the provider's active account).
ModelInfoInterface#
Structural model metadata — compatible with pi-ai's Model interface but
not coupled to it, so hosts can pass either pi-ai-shaped objects or a
custom registry of their own.
Deliberately a structural duplicate of pi-ai's Model rather than a
re-export: keeps the public API stable when pi-ai bumps shape, and lets
hosts implement their own registry without depending on pi-ai's types.
Lives here (rather than ./config) because ProviderDescriptor.models
needs it — defining it in ./config would create an import cycle.
ModelOptionInterface#
A single toggleable model option. Declarative metadata only — the provider
owns the actual request-body translation (keyed on id). Kept generic
(not "fast mode"-specific) so new per-model knobs land without a type change.
ModelTestResultInterface#
Outcome of testModel.
ModelUsageSummaryInterface#
Per-model token/spend totals across a session — see usageByModel.
OAuthCredentialInterface#
A stored OAuth credential.
OAuthFlowOptionsInterface#
Callbacks and switches for runOAuthLogin.
OnboardingInstallSignalsInputInterface#
What onboardingInstallSignals reads.
PackageManagerCommandInterface#
A package manager install command.
PendingAnnotationInterface#
An annotation waiting to be appended to an edit tool's output.
PendingApprovalsStoreInterface#
Durable persistence for pending safe-mode approvals so a request raised before a crash still surfaces after restart. Implementations: sqlite repo (GUI), JSON file (daemon), in-memory no-op (tests).
PendingInteractionInterface#
Pending interaction row as returned by interactions.list.
PendingInteractionEntryInterface#
A queued interaction request with the callbacks that settle it.
PerformInPlaceUpdateOptionsInterface#
Options for performInPlaceSelfUpdate.
PerformSelfUpdateOptionsInterface#
Options for performSelfUpdate.
PickedInterface#
A model pick made in the picker.
PlanInterface#
A plan.
PlanLifecycleHooksOptionsInterface#
Options for createPlanLifecycleHooks.
PlanProgressInterface#
Step counts of a plan.
PlanProposalInterface#
Parsed input of a present_plan call.
PlanProposalStepInterface#
One step of a PlanProposal.
PlanRequestInterface#
A pending request to approve a plan.
PlanResponseInterface#
The user's answer to a PlanRequest.
PlanRevisionInterface#
An earlier proposal of a revised plan.
PlanRunNotesInterface#
The notes a run starting now needs, and the edits they deliver.
PlansBagInterface#
On-disk shape at session.metadata.plans.
PlansSnapshotInterface#
What a window shows of a session's plans.
PlanStepInterface#
One step of a plan; the todo item the agent tracks.
PlanViewInterface#
The plan a session shows as "in progress", with a display-only liveness flag.
PlatformTarballOptionsInterface#
Options for resolvePlatformPackage.
ProbeLocalModelServersOptionsInterface#
How to probe for local model servers.
ProfileSwitchNoteContextInterface#
What a AgentProfile.switchNote function is given.
ProjectEntryInterface#
Per-project settings stored in projects.json.
ProjectUserPathInterface#
A discovered path tagged with whether it lives in the project or the user dir.
PromptAttachmentInterface#
Attachment carried alongside the prompt text (base64, no data-URL prefix).
PromptSubmissionsInterface#
A host's submit entry points, each running the prompt transforms once
before the host method it stands for. consumed says an extension took
the prompt instead: handled (nothing ran or queued), or steer /
followUp (delivered to the live run).
ProviderDescriptorInterface#
Describes one provider: how to build it, how it authenticates and which models it offers.
ProviderFactoryOptionsInterface#
What a provider instance is built FOR beyond its defaults: one stored
account of the provider instead of the active one. Built by the host from a
session's pinned account (credentials.providerFactoryOptions): an OAuth
account rides as account (resolved to its slot on every token read), an
API-key account as its apiKey.
ProviderFieldViewInterface#
A provider's custom field as a settings form asks for it.
ProviderUsageProbeInterface#
A provider's own subscription-usage probe (see ProviderDescriptor.usage).
ProviderUsageReportInterface#
What a ProviderUsageProbe reports; the host stamps identity and time.
ProvisionSessionEnvironmentInputInterface#
Input for provisionSessionEnvironment.
ProvisionSessionEnvironmentResultInterface#
Outcome of provisionSessionEnvironment.
QuestionChoiceInterface#
One option of a select question.
QuestionPayloadInterface#
Parsed input of an ask_user call.
QuestionRequestInterface#
A pending request to answer questions.
QuestionResponseInterface#
The user's answers to a QuestionRequest.
QueuedAttachmentInterface#
An attachment on a queued prompt, without its bytes.
QueuedItemInterface#
One entry in the shared type-ahead queue.
RemoveMcpResultInterface#
Result of removeMcpServer.
RepoInfoInterface#
What the import dialog shows about a GitHub repository before cloning it (fetchRepoInfo).
RepoProgressInterface#
A clone's progress, from git's own --progress lines.
ResolvedApprovalInterface#
Result of resolveApprovalForPayload: the resolved per-hunk
outcomes + the gate-level verdict.
The TUI's applyGate consumes the result: stashes outcomes in the pending-annotation map
(keyed by callId) so tool:transform can append the
<edit-outcomes> block to the tool result, rebinds ctx.input.edits
to the approved subset for partial, and emits the syntheticEvent
for fully-denied or fully-blocked calls.
ResolvedConfigInterface#
Fully resolved chat configuration produced by resolveConfig.
ResolvedExtensionKeybindingInterface#
Resolved spec string for one extension-contributed keybinding. Same
shape as a built-in KeyBindings entry but the id is
extension-owned (no KeyAction union member). The TUI dispatcher
iterates these alongside the built-ins; user overrides flow through
the same keybindings.json file by matching on id.
ResolvedPathsInterface#
Resolved on-disk layout produced by resolveConfig.
ResolveStorageDirsOptionsInterface#
Options for resolveStorageDirs.
RunningWorkItemInterface#
Parent-level cancellable tool call or background task.
RunProgressInterface#
What a run readout shows of the run in progress: see runProgress.
RunUpdateCommandOptionsInterface#
Options for runUpdateCommand.
RunUpdateCommandResultInterface#
Result of runUpdateCommand.
SafelistProjectInterface#
The "Always allow" entries of one project, as listSafelists lists them.
SafeModeActionsInterface#
Functions that drive the approval queue.
SelectQuestionInterface#
A question answered by picking from fixed choices.
SelfUpdateResultInterface#
Outcome of performSelfUpdate.
SendOptionsInterface#
chat.send options.
SerializedPreviewInterface#
Serializable mirror of PreviewResult — readonly arrays widened so the
payload round-trips without TypeScript friction on the client side.
SessionEnvironmentInterface#
metadata.environment — absent on sessions that predate it (read as local).
SessionEnvironmentSummaryInterface#
The list-row slice of a session's environment (SessionMeta.environment).
SessionExecutionInterface#
A session's execution context and the lazy handle resolver bound to it, as returned by SessionExecutionCache.
SessionExecutionCacheInterface#
Registry of host-owned execution contexts and handles, one per session. Created by createSessionExecutionCache.
SessionExportTargetInterface#
Resolved file destination for a session export.
SessionHeaderInterface#
One session's header as sessions.getHeader serves it: the list row plus
the raw metadata (model, effort, environment) and profile, without the
turns and runs sessions.get carries.
SessionLaunchOverridesInterface#
ChatHost.setLaunchOverrides: what the window overrides on a session's agent.
SessionMetaInterface#
One row of the sessions list.
SessionPresenceInterface#
Live per-session presence — which sessions have attached windows and what state they're in. Drives the session list's "active" scope and per-row status icons. A session appears here when it has ≥1 attached window, a run in flight, or pending HITL state.
SetProviderCredentialOptionsInterface#
Options for setProviderCredential.
SettingsInterface#
The user's persisted settings.
SettingsCategoryDescriptorInterface#
Display data for one SettingsCategory.
SettingsInputInterface#
Free-text settings edited via a single-line input. The SettingsModal
renders these as a row showing the current value (or placeholder when
empty); enter opens an inline editor. Same shape a GUI can consume as
a text field.
SpawnEndInfoInterface#
How a worker ended, carried on its spawn-end marker (StreamEvent.spawn.end).
SpawnStartRecordInterface#
Wall-clock start + task preview per in-flight child, keyed by spawn id.
Captured at spawn:before and read back at spawn:complete — drives
the elapsed time on the spawn-end marker and copies the stable task
preview onto the terminal marker.
StartUpdateWorkerOptionsInterface#
Options for startUpdateWorker.
StateStoreApiInterface#
Reads and writes the persisted TuiState.
StorageDirsInterface#
Per-slot directories. In legacy / default modes the four fields all point at the same path; in XDG mode they fan out into their spec-conventional locations.
mode carries the resolution branch so a host that wants to print
a startup banner ("zidane is using XDG paths") can detect the
layout without re-running the logic.
StoredCredentialInterface#
One stored credential of a provider, addressed by the file key it lives at.
StreamBufferInterface#
Handle returned by useStreamBuffer.
StreamEventInterface#
One row of the transcript, live or replayed from persisted turns.
StreamProgressInfoInterface#
Payload of the stream:progress signal — see the variant's doc.
StreamSourceInterface#
Which agent and turn a streaming delta came from.
SyntaxTokenStyleInterface#
One entry in a SyntaxStyles map — what OpenTUI's SyntaxStyle.fromStyles
accepts, minus the RGBA conversion. Renderer-agnostic JSON.
SystemMdFileInterface#
A discovered SYSTEM.md.
SystemMdResultInterface#
Result of discoverSystemMd.
TarballAvailabilityOptionsInterface#
Options for checkTarballAvailable.
TextMatchOptionsInterface#
How text matches.
TextQuestionInterface#
A free-text question.
ThemeInterface#
Full theme bundle.
ThemeColorsInterface#
Role-named color palette. Reused throughout the UI for text, borders, accents.
ThemeSelectInterface#
Select-component styling. Plain prop shape; both OpenTUI's <select> and any GUI equivalent can consume this.
ThemeSurfacesInterface#
Panel / surface backgrounds.
TitleCheckRecordInterface#
What the last auto-title attempt did. Failures are recorded too: auto- titling never surfaces an error mid-conversation, so this is where a missing key or a timeout shows up.
TodoItemInterface#
One item of a todowrite call.
TuiStateInterface#
Settings the terminal UI remembers between launches.
UnwrappedToolCallInterface#
The inner call a call_tool envelope carries.
UpdateAppliedMarkerInterface#
Record written after an install lands, so running processes can notice it before the next poll.
UpdateLockHolderInterface#
What the lock file records about the install that holds it.
UpdateStatusInterface#
Result of checkForUpdate.
UpdateWorkerRequestInterface#
What a worker is asked to do.
UpdateWorkerResultInterface#
<cacheDir>/update-result.json.
UpgradeInstalledPackagesOptionsInterface#
Options for upgradeInstalledPackages.
UpgradePackageResultInterface#
Outcome of upgrading one package.
UpgradeReportInterface#
Outcome of upgradeInstalledPackages.
UpsertMcpResultInterface#
Result of upsertMcpServer.
UsageSummaryInterface#
Usage and spend over a range. The heatmap always spans the last ~26 weeks, whatever the range.
UseRestartRequiredOptionsInterface#
Options for useRestartRequired.
UseUpdateCheckOptionsInterface#
Options for useUpdateCheck.
WatchInstalledVersionOptionsInterface#
Options for watchInstalledVersion.
WireApprovalRequestInterface#
Wire-safe approval request. Canonical ApprovalRequest minus its live
resolve callback (kept host-side, keyed by id), plus the context a
remote approval surface needs: owning session, safelist cwd, precomputed
safelist suggestions, and the edit preview byproducts.
WorkspaceEntryInterface#
One entry of a folder listing.
WorkspaceFileInterface#
A file as read for a viewer.
WorkspaceListingInterface#
A folder's listing (listWorkspace).
WorkspaceMediaOptionsInterface#
Options of serveWorkspaceMedia.
WorkspaceMediaRequestInterface#
What to serve.
WorktreeRefInterface#
Provider-owned state on environment.ref.
Types#
AgentRegistryType#
Agent profiles keyed by profile id.
AnswerValueType#
Per-question answer value — string for text/textarea/select, boolean
for confirm, string[] for multi-select. A secret question answers with
a SecretAnswer from the client, which the host replaces with a
SecretReference before anything records it.
ApprovalDecisionType#
Outcome of an approval prompt. Four bulk decisions match the original
single-edit modal contract; partial is the multi-edit branch — the
user accepted a subset of an edit / multi_edit / write_file call.
partial.mask is 1:1 with the call's hunks (in input order): true
means apply, false means deny. The gate handler walks the mask to
build per-hunk outcomes; the TUI rebinds ctx.input.edits to the
approved subset and the renderer reconstructs the full per-hunk view
from the <edit-outcomes> annotation appended to the tool result.
ApprovalModeType#
Who approves tool calls: ask the user, decide the decision model (unsure calls still ask), off nobody (full access).
ApprovalOriginatorType#
Caller attribution for approvals raised by subagents.
ArtifactScopeType#
Whether artifacts are listed for the current session or the whole project.
AutoInstallOutcomeType#
Outcome of autoInstallUpdate.
AutoInstallSkipReasonType#
Why autoInstallUpdate did nothing.
AutoTitleActionType#
What auto-titling should do next: leave the title, generate one, or check whether it is stale.
BuiltInPromptType#
The built-in prompts the chat host composes (with env, AGENTS.md and SYSTEM.md).
ChipColorMapType#
Map of provider id → chip color pair. default is required so callers
always have a fallback; every other key is optional so direct indexing
(chips['unknown']) surfaces as ChipColor | undefined and nudges
consumers toward resolveChipColor, which encodes the fallback.
CommandStepFnType#
Handler for a single CommandStep. May return a CommandStepResult to merge data into the shared bag, synchronously or as a promise.
CommitType#
Notification: a fresh walk has resolved. Host is expected to commit to its own state store.
CreateSessionRequestType#
ChatHost.createSession input: the factory params, with the environment as a request the host resolves.
CredentialsFileType#
Top-level shape of credentials.json — keys are credential-file keys.
DiagnosticSeverityType#
How bad a finding is.
DurabilityModeType#
Whether runs survive a crash: on keeps a checkpoint of each run and
resumes an interrupted one by itself, resume-ask keeps the checkpoint
and asks before resuming, off keeps none (an interrupted run's tool
calls are reported interrupted on the next run).
EditDiffDisplayType#
How edit / multi_edit / write_file diffs render in the transcript.
Gated by Settings.showEditDiffs; when that's off, the raw ↳ name(args)
line is used regardless of this setting.
'full'— the entire unified diff body, with line numbers in the gutter. Uses real file line numbers when the pre-write snapshot is available (live calls), synthetic when not (historical replay).'compact'— header line + one short summary line per hunk (L42,+2 −1,old → new). The full diff body is dropped from the transcript; users open the approval modal or scroll the file to see the changes in detail.
EditOutcomeKindType#
Per-hunk lifecycle state surfaced in the diff/apply viewer. Mirrors the
states a multi_edit step can be in across the approve → apply pipeline:
applied— the gate let it through and the tool wrote it.denied— the user (or an auto-deny rule) refused this specific edit.skipped— the user explicitly stepped past this edit in the modal, or an earlier edit failed and the batch unwound.failed— the gate let it through but the tool body rejected the edit (old_stringnot found, ambiguous, etc.).pending— placeholder used while the modal is open. Never persisted.
EnabledAllowlistKeyType#
Settings keys whose value type is readonly string[] | undefined.
EnvironmentAvailabilityType#
Whether a kind can be offered now: ok, or not with a reason to show.
EnvironmentConfigType#
A kind's resolved options — see environment-settings.ts (resolveProviderConfig).
EnvironmentConfigValueType#
A provider option's value, as stored in settings (secrets resolve to strings).
EnvironmentStateType#
Lifecycle state of a session's environment: being set up, usable, or failed to set up.
EnvironmentVerifyResultType#
"Test connection" outcome — detail is what it connected to (account, region, version).
ForkSessionResultType#
Outcome of forkSession: the new session id, or the reason the fork was refused.
ForkSourceType#
What a fork reads from its parent — satisfied by SessionData and a live Session.
GitChangeType#
What moved: the refs (HEAD, branches, remote-tracking refs) or the config (remotes, upstreams).
GitPrListResultType#
The switcher's PR list: the PRs, null when gh is missing or signed out,
or rateLimited when GitHub refused and nothing is cached (retryAt: when
it resumes, epoch ms).
GitSwitchResultType#
A switch or a new branch: git's refusal summed up; worktree: another worktree holds the branch, at this path.
GitSwitchTargetType#
What to switch to: a local branch by name, or a pull request by number.
GitSyncResultType#
What a sync (pull, merging, then push) or a publish answered; conflicts: the files a refused pull left conflicted.
HostProbeType#
Connects to url with token, says who answered (or why it failed), disconnects. Never throws.
HostSettingsType#
Host settings — canonical Settings plus the extension allowlist.
HostSignalType#
The single push channel. Chat stream signals mirror the agent loop hooks;
interaction/approval signals carry the HITL queues so every window renders
the same pending state; sessions:changed keeps session lists in sync
across windows.
InteractionModeType#
How questions to the user are handled: ask prompts normally, skip answers from the repository without asking, disabled removes the interaction tools.
InteractionOriginType#
Who raised a request. model is a tool call awaiting a tool_result;
host is a slash command or extension prompt whose consumer is local
code. Automatic mode may only answer on the model's behalf, so this is
carried as data rather than inferred from the id — a missing value is a
compile error at the construction site instead of a silent mis-answer.
InteractionRequestType#
A request for user input raised by the model or the host.
InteractionResponseType#
The user's answer to an InteractionRequest.
KeyActionType#
Every action the keybindings system can drive. Adding a new action here forces every consumer (TUI keyboard handler, hint rows, settings UI) to handle it, and ships a default that the user can override.
KeyBindingsType#
Resolved keybindings — every action has a current spec string.
McpAuthEventType#
Events the reducer accepts. Most names mirror the agent hooks
(mcp:connect, mcp:auth:*). login:start / login:cancel / logout /
reset are UI-only verbs: login:start lets the renderer
optimistically flip a row to authorizing before the SDK has emitted
mcp:auth:url — useful when the loopback callback is slow to bind.
McpAuthStateType#
A server's sign-in: none needed, wanted, under way, done, or the last one failed.
McpAuthStateMapType#
Map of server name → status. idle is the implicit default for any
server NOT present in the map, so the renderer treats undefined as
{ kind: 'idle' } and the map can stay sparse.
McpConfigScopeType#
Which config root to write to: the git root of the project, or the user's home.
McpNeedsAuthReasonType#
Why a server needs sign-in: no stored tokens, a server answer that promoted it to OAuth, or a refused request.
McpStatusTrackerType#
The MCP servers' live state for one data dir (see createMcpStatusTracker).
McpToolsCacheType#
serverName → catalog. Map shape on disk so adding / removing
servers is an O(1) JSON edit instead of an array rewrite.
MessageDeliveryType#
What happens to a message sent while a run works: it goes into the run (steer), or waits for the run to end (queue).
ModelApprovalChoiceType#
The decision model's answer on a tool call under Model decision approvals.
OpenInTargetType#
Where a clicked file or diff opens: the external editor or the host's own panel. See Settings.openIn.
OwnerType#
Identifies the agent that produced a streaming event.
PackageManagerIdType#
Identifier of a supported package manager.
PlanDecisionType#
How the user answered a plan: approve it, reject it, or ask for a revision.
PlanEditOpType#
A user edit to a plan's steps.
PlanEventType#
A change to the plans of one session.
PlanSessionType#
A session as the plan helpers need it; saveMetaKeys and store are used when present.
PlanStateType#
Lifecycle state of a Plan.
PlanStopReasonType#
Why a plan stopped.
PreferCredentialResultType#
Outcome of setPreferredCredential.
Three states rather than a boolean because the two non-promoting cases need
opposite handling: already-active is a harmless idempotent call (the UI
repaints and moves on), while not-stored means the caller asked for a
credential that does not exist and should say so.
PreferredCredentialTargetType#
What setPreferredCredential promotes: a stored credential by file
key (from readProviderCredentials / AuthMethod.key), or the first
stored credential of a kind — the right form when the caller only knows
"switch to the API key".
ProjectsFileType#
Contents of projects.json: project entries keyed by project root path.
PromptConsumedType#
What an extension did with a submission instead of the asked path: handled it, or delivered it to the live run.
PromptSubmitHostType#
The host methods a submission ends in.
ProviderCredentialType#
Either an API key or an OAuth credential stored for a provider.
ProviderKeyType#
Provider identifier as known to the TUI. Built-in keys include anthropic,
openai, openrouter and cerebras, and hosts can register additional
keys via ProviderDescriptor — so the type is open.
ProviderRegistryType#
Provider registry — a map keyed by descriptor.key. Passed verbatim to the
chat engine; there is no implicit merge with built-ins. Hosts that want the
default providers spread BUILTIN_PROVIDERS; hosts that only want
their own pass exactly their own.
QuestionType#
One question in an ask_user form, discriminated by type.
QuestionTypeType#
Kind of an ask_user question, the discriminator of Question:
text— single-line free-text answer (rendered via<input>).textarea— multi-line free-text answer (rendered via<textarea>).select— single pick from a fixed set ofchoices.confirm— yes/no boolean (rendered as a 2-option select).secret— a value the host saves to the secret store; the model reads only a reference (SecretQuestion).
The model batches related clarifications into one tool call instead of pinging the user N times with N round-trips.
RepoCloneResultType#
What a clone answered; existed: the folder already held that repository (same origin), so it was opened, not cloned.
RequestApprovalType#
Function signature consumed by tool:gate handlers + the child-tool wrap.
ResolvedPathType#
What a name in prose points at: a file or folder on disk, or else a git
branch of the repo (main, origin/main: name is the branch, remote
the remote of a remote-tracking one). candidates: when a bare name matched
several files or folders, all of them, best first (path is the first), so
a chip can ask which one.
ScreenType#
Top-level screen the terminal UI shows. onboarding is the setup wizard.
SendTransformType#
The transform step of a host's submit paths (see createSendTransforms).
SessionExportAnchorType#
Anchor for the resolved destination directory:
project— the nearest enclosing git repository (<repoRoot>/.{prefix}/sessions)home— fallback when no repo was found (<dataDir>/sessions;~/.{prefix}/sessionsoutside an XDG layout)
SessionExportFormatType#
File format supported by the exporter.
SettingsCategoryType#
Setting categories — drives the tab grouping in the TUI's
SettingsModal and, more importantly, gives any embedder (GUI,
web settings panel, …) a stable taxonomy to bucket settings under
without re-hardcoding the split.
'agent'— agent behaviour, capabilities, persistence, data handling, auth. "What zidane DOES."'ui'— display, rendering, theming, animations, chrome density, keybindings. "How zidane LOOKS and feels."
Borderline calls (showAllProjects, hideSubagentOutput) are documented
inline at their rows.
StartGitWatchType#
Starts watching a folder's repository: resolves its stop, or null when the folder is not in one.
StepCancelledByType#
Who cancelled a step.
StorageModeType#
Which resolution branch produced the layout — surfaced for debugging + tests.
StorageSlotType#
The four slot kinds we resolve. Names match the XDG spec.
StringSettingKeyType#
Keys of Settings whose value type is exactly string. Bounds the
input table's key the same way BooleanSettingKey bounds the
toggle table — a free-text row can only point at a string-valued
setting.
SyntaxStylesType#
Map of Tree-sitter / markdown capture group → token style.
Two flavours of keys live in the same table:
markup.*— the markdown structure captures (heading, bold, italic, list, quote, raw inline + block, link). OpenTUI's markdown parser emits these for the markdown text itself.- bare token names (
keyword,string,function, …) — emitted by the embedded language Tree-sitter grammars when a code fence declares a language. OpenTUI passes the sameSyntaxStyledown to the fenced-code renderable, so this map drives both surfaces.
TitleSourceType#
Who set a session's title: auto-titling or the user.
TodoStatusType#
Progress of one todo (one plan step).
ToolCallDisplayType#
How tool events render in the transcript. Drives Settings.toolCallDisplay.
'hidden'—toolevents filtered out entirely (the matchingtool-resultblock still shows unless its own toggle suppresses it). Use when the transcript should read like a chat log.'formatted'(default) — each tool renders a clean per-tool summary line (e.g.↳ Read src/foo.ts,↳ Shell git status). Native tools have curated formatters; unknown / MCP tools fall back to a compact↳ <name>line.'full'— debug view:↳ <name>header plus the entire rawinputrendered as syntax-highlighted JSON. Useful for inspecting what the model actually sent.
TranscriptDensityType#
How the transcript lays an exchange out.
full: every row where it happened (thinking, tool calls, batches, subagent blocks, text).compact: between two user prompts only the prompt and the assistant's text stay visible; thinking, tool calls and worker output fold behind one "Worked …" row that expands in place.
TranscriptItemType#
One entry in the partitioned transcript-row list. Single events
render as a normal row; a child-run groups ONE subagent's events
from a consecutive run of subagent output into one bordered box
(concurrent siblings get a child-run each, so their rows never
braid together inside a shared frame); tool-groups
collect ALL parent-owned tool/tool-result events of one exchange
into a single collapsible summary row (Settings.groupToolCalls);
an exchange-fold goes further (Settings.transcriptDensity: 'compact') and takes every thinking, tool and worker event of the
exchange, leaving only the prompt and the assistant's prose in place.
key is stable across re-partitions of the same stream (derived
from the first grouped event) so expand state survives appends.
Currently produced by the TUI's partitionTranscript; a GUI shell
grouping subagent runs the same way can produce the same shape.
UpdateWorkerOutcomeType#
How a run ended, as its starter sees it.
UpdateWorkerUpgradeCommandType#
Runs zidane upgrade <argv> in the worker; the host wires it (it knows its
package, version and companions). Must not take the install lock: the
worker holds it.
UpgradeProgressEventType#
Progress event emitted while packages are upgraded: a version check, an install start, a line of package manager output, or a finished package.
UsageRangeType#
The summary's window.
VisibleMcpRowType#
One row in the flattened MCP settings list. Three kinds:
'server'— server header with the chevron + checkbox + transport detail. Always present.'tool'— checkbox + description for a tool advertised by the parent server. Present only when the server is expanded AND its tool cache is populated.'tool-empty'— placeholder shown when an expanded server has no cached tool list yet (first launch before any session has bootstrapped the server). Lets the renderer surface a one-line "send a prompt to populate" hint WITHOUT changing the server's expand affordance.
WalkType#
Walk function — takes an abort signal, returns the discovered list.
WorkspaceWriteResultType#
What a guarded write did: changed: the file on disk is newer than expected; denied: outside cwd or unwritable.
Re-exports#
These names are documented on the entry point that owns them.
- accentColor
- activePlanSummary
- activeSnapshotFor
- activeSpaceOf
- ActiveTrigger
- AgentAccent
- ageString
- API_KEY_ACCOUNT_LABEL
- applyEditPayload
- applyingPlan
- applyInsert
- applyPlanEvent
- applySettingsPatch
- APPROVAL_MODE_OPTIONS
- APPROVAL_MODE_TRADEOFFS
- AuthMethod
- autoTextModelId
- bindingAlternatives
- blendHsl
- BooleanSettingKey
- buildContextBreakdown
- buildContextSegments
- buildContextualDiff
- buildLinearRamp
- buildModelCatalog
- buildOnboardingResult
- buildSessionSearchIndex
- buildSessionSearchIndexAsync
- buildUnifiedDiff
- CACHE_HINT_MIN_TOKENS
- cacheBreakChip
- CacheChipContent
- CacheChipTone
- cacheHintText
- calibrationFactor
- canSkipOnboardingStep
- capTranscriptEvents
- CatalogEntry
- chainAccountConflict
- chainEntryKey
- chainPositionOf
- chainsEqual
- ChatReferenceData
- ChatReferenceEntry
- ChatReferenceScope
- chatReferenceTokensFromText
- CHATS_TRIGGER
- chunkMarkdownForRender
- classifyMcpTest
- CLOSED_PLAN_STATES
- collectReferences
- Command
- CommandArgSuggestion
- CommandInvocation
- COMMANDS_TRIGGER
- compactingLabel
- compactPath
- compareModelVersion
- compileQuery
- CompletionContext
- CompletionItem
- CompletionProvider
- CompletionReference
- computeInlineDiff
- computeLineDiff
- CONNECTOR_CATEGORIES
- ConnectorAuth
- connectorAuthText
- ConnectorAuthWords
- connectorById
- ConnectorCategory
- ConnectorCategoryMeta
- ConnectorEntry
- ConnectorInput
- connectorInputError
- connectorInstalled
- CONNECTORS
- connectorServerConfig
- connectorsFromImport
- ConnectorTokenAuth
- ConnectorTransport
- ContextBreakdown
- ContextBreakdownContributionContext
- ContextBreakdownContributor
- ContextBreakdownOptions
- ContextCategory
- ContextCategoryId
- ContextExactCounts
- ContextExtensionRow
- ContextExtensionSection
- ContextItem
- ContextMcpGroup
- ContextSegment
- ContextSegmentFile
- ContextSegmentOrigin
- ContextSegmentsInput
- ContextSnapshot
- ContextUsageSplit
- copyNames
- countNeighbors
- createChatsCompletionProvider
- createCommandsCompletionProvider
- createEntryOps
- createFilesCompletionProvider
- createOnboardingFlow
- createOnboardingRun
- createSkillsCompletionProvider
- currentModelKeys
- currentModels
- currentOnboardingStep
- CustomModelTarget
- customModelTargets
- DAEMON_HEALTH_GLYPH
- DAEMON_HEALTH_STYLE
- daemonGate
- DaemonHealth
- DaemonHealthStyle
- DaemonHealthTone
- decisionsEnabled
- DEFAULT_EXTENSION_SOURCE
- DEFAULT_EXTENSION_SOURCE_UNREACHABLE
- DEFAULT_OAUTH_ACCOUNT_LABEL
- DEFAULT_SETTINGS
- DEFAULT_SPACE_ID
- DEFAULT_SPACE_NAME
- defaultExtensionSource
- defaultImportSelection
- defaultSessionAgent
- defaultSessionKnobs
- defaultSessionModel
- defineFeatureGate
- deleteTurnSafely
- DiffLine
- DiffOp
- displayNameFor
- DURABILITY_OPTIONS
- editableTurnText
- EditHunkSummary
- EditSummary
- effectiveOnboardingMode
- enabledMcpsWith
- enabledMcpsWithout
- enforceSettingsInvariants
- engagedKillSwitches
- ENTRY_IMPORT_MAX_BYTES
- ENTRY_IMPORT_MAX_ENTRIES
- ENTRY_IMPORT_MAX_FILE_BYTES
- EntryCreateOptions
- EntryImportItem
- EntryImportLimits
- EntryImportResult
- entryName
- EntryOps
- entryParent
- entryPath
- EntryRefusal
- EntryResult
- escapeTemplate
- estimateReadout
- EstimateReadout
- EXCLUDED_NATIVE_EXTENSIONS
- extensionMark
- ExtensionMark
- ExtensionMarkInput
- ExtensionSourceEntry
- ExtensionSourceErrorCode
- ExtensionSourceInfo
- ExtensionSourceKind
- ExtensionSourceListing
- extensionSpace
- ExtensionSpaceSource
- extractEditPayload
- FacetPath
- FEATURE_GATES
- FeatureGate
- FeatureGateOptions
- FILES_TRIGGER
- filetypeFromPath
- filterModelCatalog
- filterSessionSearchCatalog
- finalizeStreamingMarkdown
- finalizeStreamingMarkdownForOwner
- findActiveTrigger
- findSpace
- fitRunReceiptCells
- fmtCost
- fmtTokens
- formatCostUsd
- formatDuration
- formatEstimate
- formatModelSetting
- formatRunDuration
- formatRunReceiptCells
- formatRunReceiptLine
- formatTaskStatus
- formatTaskSummary
- formatTokenCount
- formatTokensPerSecond
- formatToolCall
- formatUsagePercent
- freeEntryName
- generateSessionTitle
- GenerateSessionTitleOptions
- hasRunReceipt
- HighlightRange
- HighlightSegment
- highlightSegments
- HostEntry
- HostErrorCode
- HostIdentity
- HostProbeResult
- HostRegistryError
- HostTestResult
- HunkResolution
- importEntries
- importsSomething
- IndexedSearchTurn
- indexOfEntry
- inferPromptRefs
- InlineDiff
- InlineGhost
- InlineSegment
- InstalledServerRef
- isEditErrorResult
- isExistingInstall
- isExtensionSpaceId
- isKillSwitchEngaged
- isMainSession
- isTurnHighlighted
- isVisible
- joinEntry
- joinFewNames
- joinNames
- LineupEntry
- LiveRunStatus
- LOCAL_SERVER_BRANDS
- LOCAL_SERVER_NAMES
- MARKDOWN_RENDER_CHUNK_TARGET_BYTES
- MarkdownSegment
- MAX_TRANSCRIPT_EVENTS
- MCP_KEY_REFUSED_HINT
- MCP_STATUS_LABEL
- McpAuthStatus
- McpTestOutcomeKind
- McpTestResult
- mergeOnboardingState
- mergeReferences
- mergeSuggestions
- MESSAGE_DELIVERY_OPTIONS
- MESSAGE_DELIVERY_TRADEOFFS
- migratedOnboardingRecords
- ModelChainEntry
- modelConcern
- ModelIdParts
- ModelNamer
- modelPickKey
- ModelSettingPick
- mostConstrainedWindow
- nameFromModelId
- NATIVE_EXTENSION_GROUPS
- NATIVE_EXTENSIONS
- NATIVE_EXTENSIONS_REPO
- nativeExtensionByName
- NativeExtensionCommandNeed
- nativeExtensionEntry
- NativeExtensionEntry
- NativeExtensionGroup
- NativeExtensionGroupMeta
- nativeExtensionListing
- NativeExtensionNeed
- nativeExtensionNeedText
- NativeExtensionNeedWords
- nativeExtensionSource
- needsOnboarding
- newSessionModel
- newSpaceId
- normalizeMarkdownCodeFences
- normalizeSpaces
- oauthAccountLabel
- ONBOARDING_AGENT_BRANDS
- ONBOARDING_AGENT_NAMES
- ONBOARDING_FEATURE_GROUPS
- ONBOARDING_FEATURES
- ONBOARDING_PREVIEW_ATTACHMENTS
- ONBOARDING_PREVIEW_EVENTS
- ONBOARDING_SETTING_KEYS
- ONBOARDING_STEP_SETTINGS
- ONBOARDING_STEPS
- ONBOARDING_VERSION
- ONBOARDING_WORDS
- OnboardingAction
- OnboardingAgentId
- OnboardingAppearance
- OnboardingCredentialSource
- OnboardingCustomField
- OnboardingDetection
- OnboardingDraft
- OnboardingFeature
- OnboardingFeatureBadge
- onboardingFeatureCopy
- OnboardingFeatureCopy
- OnboardingFeatureGroup
- OnboardingFeatureGroupMeta
- onboardingFeatures
- OnboardingFlowState
- OnboardingGate
- OnboardingGateInput
- OnboardingGithubIdentity
- OnboardingImportCategory
- onboardingImportParts
- OnboardingImportPreview
- OnboardingImportPreviewState
- OnboardingImportSelection
- OnboardingImportSessionCounts
- OnboardingImportWords
- OnboardingInstallSignals
- OnboardingLocalServer
- OnboardingMode
- OnboardingPhase
- OnboardingPlanContext
- onboardingProgress
- OnboardingProgress
- OnboardingProvider
- OnboardingProviderPick
- OnboardingReadable
- onboardingRecord
- OnboardingRecord
- onboardingRecords
- onboardingReducer
- OnboardingResult
- OnboardingRun
- OnboardingRunHost
- OnboardingRunOptions
- OnboardingRunSetup
- OnboardingRunStart
- onboardingSettingsChange
- OnboardingSettingsChange
- OnboardingSignInState
- OnboardingStart
- OnboardingState
- onboardingStep
- OnboardingStepId
- OnboardingStepMeta
- OnboardingStepScope
- OnboardingSurface
- onboardingSwitchedFeatures
- OnboardingSwitchedFeatures
- OnboardingTask
- OnboardingTaskKind
- OnboardingTaskStatus
- OnboardingTradeoff
- OnboardingWords
- oneLineTitle
- ORCHESTRATED_BY_KEY
- orchestratedBy
- otherDelivery
- parseBindingSpec
- parseBindingSpecs
- parseCommandInvocation
- ParsedBinding
- parseModelId
- parseModelSetting
- parseRemoteHostUrl
- patchInlineGhost
- planOnboarding
- planProgress
- planProgressLabel
- previewEditPayload
- previewLine
- PreviewResult
- PromptSegment
- PromptSegmentRef
- PROVIDER_BRANDS
- ProviderAccount
- ProviderAuth
- providerBrand
- ProviderResetCredit
- ProviderResetOutcome
- ProviderUsageCredits
- ProviderUsageResets
- ProviderUsageSnapshot
- ProviderUsageStatus
- ProviderUsageWindow
- QueryBound
- querySessions
- QueryValue
- readSessionAccount
- readSessionSpaceId
- ReconcilableEvent
- reconcileEvents
- RemoteHostError
- remoteHostsGate
- replaceTurnTextBlocks
- requirementMet
- resolveSessionSpace
- retryLabel
- RUN_RECEIPT_GLYPH
- RUN_STATUS_TIME_MS
- RUN_WAITING_DELAY_MS
- RUN_WAITING_LABEL
- runEstimateView
- RunEstimateView
- runFoldStatus
- RunFoldStatus
- runningEstimateViews
- RunReceipt
- RunReceiptCell
- RunReceiptCellKind
- runReceiptFromRun
- RunReceiptSegment
- RunReceiptSegmentKind
- RunRetry
- runRetryingLabel
- runStatusKey
- runTailActivity
- RunTailActivity
- searchableTurnText
- SearchExcerpt
- searchHighlightRanges
- searchSessionHistory
- searchSessionHistoryIndex
- searchSessionHistoryIndexAsync
- searchSessionIndex
- searchSessionIndexAsync
- SearchSessionResult
- searchSessionTurns
- SearchTurnResult
- searchTurns
- selectableTurnIds
- SESSION_ACCOUNT_METADATA_KEY
- SESSION_EVENT_STATUS_STYLE
- SESSION_ROLE_KEY
- SESSION_SCOPE
- SessionCondition
- sessionDirLabel
- SessionEvent
- sessionEventExcerpt
- sessionEventLabel
- sessionEventMeta
- SessionEventStatus
- SessionEventStatusStyle
- SessionEventTone
- SessionFieldName
- SessionFieldPath
- SessionGroupBy
- SessionGroupOrder
- SessionHistoryMatch
- SessionKnobs
- SessionQuery
- SessionQueryAll
- SessionQueryAny
- SessionQueryEnvironment
- SessionQueryError
- SessionQueryIssue
- SessionQueryNot
- SessionSearchExcerpt
- SessionSearchIndex
- SessionSort
- sessionSpaceFilter
- SETTING_TRADEOFFS
- settingKeywords
- SETTINGS_CHOICES
- SETTINGS_TOGGLES
- SettingsChoice
- SettingsToggle
- SETUP_PALETTE_ITEM
- SetupPaletteItem
- shortId
- shortSessionId
- showsAccount
- sideSessionParent
- SKILLS_TRIGGER
- Space
- SPACE_METADATA_KEY
- SpaceIcon
- spaceIdForNewSession
- spaceMetadata
- spaceModelDefault
- SpaceModelDefault
- spaceOfSwitchItem
- spacesEnabled
- SpacesSettings
- spaceSwitchItems
- spawnLane
- spawnLaneResolver
- spawnParents
- SpawnTreeRow
- splitLines
- splitMarkdownCodeBlocks
- splitPromptSegments
- summarizeEditPayload
- summarizeOutcomes
- TextModelCandidate
- TextModelOptions
- TextModelPick
- TextModelSource
- titleFromText
- TODO_STATUS_GLYPHS
- toggleApplies
- toggleChainEntry
- toggleHeldOn
- tokenize
- TOOL_DISPLAY
- ToolDisplayMeta
- ToolFormatLine
- toolInputCode
- TRANSCRIPT_PRESET_KEYS
- TRANSCRIPT_PRESET_PALETTE_ID
- TRANSCRIPT_PRESETS
- TRANSCRIPT_TRIM_TO_EVENTS
- transcriptPreset
- TranscriptPreset
- TranscriptPresetId
- TranscriptPresetKey
- transcriptPresetNotice
- transcriptPresetOf
- transcriptPresetOfPaletteItem
- transcriptPresetPaletteItem
- transcriptPresetPalettePicker
- TranscriptPresetSettings
- truncateTitle
- truncateTurnsAt
- turnAsText
- turnContextSize
- turnSelectionOwnership
- TUTORIAL_TOPICS
- tutorialOnServer
- TUTORIALS
- TutorialStep
- TutorialTopic
- TutorialWords
- uniqueChatIdsFromReferences
- uniqueFilesFromReferences
- uniqueSkillNamesFromReferences
- WORKER_REPORT_FRAGMENT
- AccessScope
- ActionSetting
- ActionSettingContext
- ActionSettingResult
- ActionSettingStatus
- ActionSettingStatusContext
- ActionSettingValue
- AddFn
- AgentEditor
- AgentsDomain
- AppInfo
- ArtifactsDomain
- BadgeAction
- BadgeActionEffect
- BadgeActionsMatch
- BadgeActionSpec
- BadgeActionWire
- BadgeTarget
- BadgeTargetKind
- Bindable
- BooleanSetting
- buildExtensionPreset
- buildExtensionRegistry
- BuildExtensionRegistryOptions
- CatalogDomain
- CatalogEditor
- Cleanup
- CommandListing
- CommandsDomain
- CommandSource
- CommandSpec
- ComponentRef
- ComponentWire
- composeExtensionPreset
- ComposerDomain
- Connection
- ContextSection
- ContextSectionItem
- ContextSectionWire
- Contract
- ContractsDomain
- ContractToken
- Credential
- defaultExtensionScanPaths
- defineExtension
- DesktopDomain
- DialogOptions
- DialogRequest
- DialogTimeoutError
- discoverExtensions
- Disposable
- DisposedError
- disposeExtensionRegistry
- EMPTY_EXTENSION_REGISTRY
- EnumSetting
- EXTENSION_API_VERSION
- ExtensionApiVersion
- ExtensionApprovalDecision
- ExtensionArtifactDetection
- ExtensionArtifactKindRegistration
- ExtensionArtifactQuery
- ExtensionArtifactRow
- ExtensionArtifactRowFact
- ExtensionBadgeActions
- ExtensionBadgeColor
- ExtensionBadgeIcon
- ExtensionBadgeTone
- ExtensionBehaviorTransform
- ExtensionContext
- ExtensionContextPanelSection
- ExtensionContributions
- ExtensionCreateSessionParams
- ExtensionDefinition
- ExtensionFooterHint
- ExtensionHostKind
- ExtensionInfo
- ExtensionInstallOrigin
- ExtensionKeybinding
- ExtensionKeybindingDispatchContext
- ExtensionManifest
- ExtensionMcpConfigTransform
- ExtensionOrderedContribution
- ExtensionPanel
- ExtensionPaths
- ExtensionReferenceCard
- ExtensionReferenceCardFact
- ExtensionReferencePattern
- ExtensionReferenceProvider
- ExtensionReferenceSurface
- ExtensionReferenceView
- ExtensionRegistry
- ExtensionRuntimeEnv
- ExtensionRunTransform
- ExtensionSkillPolicy
- ExtensionSource
- ExtensionToolCatalogTransform
- ExtensionToolResultMetadataRegistration
- filterExtensionRegistry
- GeneratedImage
- GenerateDomain
- GenerateImageOptions
- Handle
- HookEvents
- HooksDomain
- HttpRequestInput
- HttpResponseInput
- Infer
- inlineLoadedExtension
- InstructionsDomain
- IntegrationCustomMethod
- IntegrationCustomResult
- IntegrationFlowIO
- IntegrationHandle
- IntegrationMethod
- integrationMethodFromOAuthProvider
- IntegrationsDomain
- IntegrationSpec
- IntegrationSpecPatch
- InterceptOptions
- InterceptorHandler
- Interceptors
- ItemOrigin
- Json
- JsonSchema
- KeymapDomain
- KeymapEntry
- KeyScope
- KeyValue
- LinkHandler
- LinkHandlerItem
- LinkSource
- Live
- LiveAccessor
- LoadedExtension
- LoadedExtensionSource
- McpDomain
- McpToolDescriptor
- Menu
- MenuItem
- MenuWire
- ModelEditor
- ModelsDomain
- ModelSetting
- NamedTool
- NoUiError
- NumberSetting
- OnOptions
- PaletteProviderSpec
- Panel
- PanelAction
- PanelBarsItem
- PanelBarsPoint
- PanelBarsSeries
- PanelContent
- PanelContentItem
- PanelControl
- PanelControlOption
- PanelCustomItem
- PanelFocus
- PanelHeatmapDay
- PanelHeatmapItem
- PanelHomeLayout
- PanelIcon
- PanelItem
- PanelKeyValueItem
- PanelKeyValueRow
- PanelLoadContext
- PanelLoadScope
- PanelMarkdownItem
- PanelMore
- PanelRowAction
- PanelRowItem
- PanelSearch
- PanelSection
- PanelStartSession
- PanelStat
- PanelStatsItem
- PanelSurface
- PanelView
- panelViewValue
- panelViewValues
- PanelWire
- partitionExtensionCatalog
- PluginsDomain
- PromptInput
- ProviderEditor
- ProvidersDomain
- Readable
- Reference
- Registry
- RegistryToken
- Renderer
- RendererItem
- RendererTarget
- RendererWire
- Rpc
- RpcCallContext
- RpcCallError
- RpcClient
- RpcContract
- RpcDomain
- RpcError
- RpcEvent
- RpcEvents
- RpcEventSpec
- RpcImplementation
- RpcMethodSpec
- RpcRegistration
- RunSettledEvent
- scanExtensionDirectories
- ScheduleFireEvent
- SchedulesDomain
- Schema
- ScreenItem
- ScreenWire
- SelectOption
- SessionFacetsDomain
- SessionFacetSpec
- SessionFacetTrigger
- SessionFields
- SessionInfo
- SessionListPage
- SessionListQuery
- SessionListRow
- SessionListStatus
- SessionsDomain
- SessionSnapshot
- Setting
- SettingApply
- SettingBase
- SettingScope
- SettingsDomain
- SettingsPage
- SettingsPageItem
- SettingsPageSpec
- SettingsPageWire
- SettingsSchema
- SettingValue
- SidebarBadge
- SidebarChip
- SidebarDecoration
- SidebarDecorationItem
- SidebarDecorationWire
- SidebarFilter
- SidebarFilterItem
- SidebarFilterOption
- SidebarFilterWire
- SidebarGroup
- SidebarGroupItem
- SidebarGroupWire
- SidebarRow
- SidebarRowAction
- SidebarRowActionWire
- SidebarRowItem
- SidebarRowOpen
- SidebarRowStatus
- SidebarRowWire
- SidebarSort
- SidebarSortItem
- SidebarSortWire
- SidebarText
- SkillsDomain
- Slot
- SlotItem
- SlotName
- SlotWire
- SpaceItem
- SpaceNewSession
- SpaceWire
- StorageDomain
- StoragePathScope
- StorageScope
- Store
- StoreOptions
- StringSetting
- SyncInterceptorName
- ThemeToken
- ToolCall
- ToolCallDecision
- ToolCallResult
- ToolEditor
- ToolMetadataNamespace
- ToolResultDecision
- ToolsDomain
- Transform
- TuiContributions
- UiDomain
- UiEntry
- UiToken
- ValueKeys
- Webview
- WebviewItem
- WebviewWire
- WireSettings
- WireSettingsExtension
- WorkspaceDomain
- OAuthPrompt