/** * Widget registry: the one place info and status widgets are declared. * * A widget is a small object with an id and a render function. The TUI decides where it shows up * (sidebar section, footer segment, or both) from its `slots`, orders it by `order`, and refreshes * it on `refreshMs` or when the widget calls `handle.refresh()`. * * import { registerWidget } from "../chassis/api.ts"; * * registerWidget(pi, { * id: "deploy", * title: "Deploy", * slots: ["footer", "sidebar"], * order: 10, * refreshMs: 30_000, * render: () => ({ icon: "\uF0E7", text: "staging·v42", color: "brand" }), * detail: () => ["Last deploy 12m ago"], * }); * * The registry lives on globalThis because pi loads every extension file in its own module scope * (jiti, moduleCache off), so a plain module-level Map would give each extension its own copy. * Widgets registered before chassis loads are kept and shown once it starts. * * Plain `ctx.ui.setStatus()` from other extensions still works: the TUI shows those statuses as * footer segments too, unless a registered widget claims the same key (`statusKey`). */ import type { ExtensionAPI, ExtensionContext, Theme } from "@earendil-works/pi-coding-agent"; import type { IconLike } from "./icons.ts"; /** A render or detail call slower than this counts as a strike against the widget. */ export declare const SLOW_RENDER_MS = 50; /** This many slow calls in a row suspend the widget until `/widgets enable ID`. */ export declare const SLOW_RENDER_STRIKES = 3; /** An `update` that has not settled after this long is abandoned and reported as an error. */ export declare const DEFAULT_UPDATE_TIMEOUT_MS = 10000; /** Where a widget can appear. */ export type WidgetSlot = "sidebar" | "footer"; /** * Colours a widget can ask for: theme tokens, the brand colours (`brand`, `brandDark`, `plan`; see * brand.ts), or any `#RRGGBB` value. */ export type WidgetColor = "text" | "muted" | "dim" | "accent" | "success" | "warning" | "error" | "brand" | "brandDark" | "plan" | `#${string}`; /** Status level: drives the dot colour in the sidebar heading when no colour is given. */ export type WidgetLevel = "ok" | "warn" | "error" | "off" | "info"; /** What a widget renders: one short line for the footer and the sidebar heading row. */ export interface WidgetView { /** Optional leading glyph. A string is used as given with a Nerd Font and dropped (private-use characters removed) without one; `{ nerd, plain }` gives one for each set. */ icon?: IconLike; /** * Short status text, e.g. "staging·v42". Plain text: the TUI applies the colour. May be omitted by * a `sidebar: "section"` widget that only has detail lines. */ text?: string; /** * Footer-only label shown between icon and text (e.g. "Deploy" gives " Deploy staging·v42"). * The sidebar shows the widget title in its own column instead. */ label?: string; /** * Sidebar row only: already-styled text drawn after `text`, separated by a space, in its own * colours (e.g. a role name coloured by what it allows). Not shown in the footer. */ tag?: string; /** Colour for icon and text. Defaults from `level`, else "text". */ color?: WidgetColor; /** Status level, used for colour defaults and the sidebar dot. */ level?: WidgetLevel; } /** Something the user can run from the command palette (ctrl+p), shown as ": <label>". */ export interface WidgetAction { /** Unique within the widget. */ id: string; label: string; description?: string; /** A thrown error or rejection is shown as a notification and recorded on the widget. */ run: (ctx: ExtensionContext) => void | Promise<void>; } export interface WidgetRenderContext { theme: Theme; /** The latest session context, if a session is running. */ ctx: ExtensionContext | undefined; /** Width available to this widget's line(s), in terminal columns. */ width: number; } export interface WidgetSpec { /** Unique id; registering the same id again replaces the widget. */ id: string; /** Sidebar section heading. Defaults to the id. */ title?: string; /** * Glyph in front of the widget in the sidebar: before a `sidebar: "section"` heading, or, for a * row, as its marker in place of the bullet (and of the level marker). A row then leaves * `view.icon` out of the value; the footer still draws it. A string is used as given with a Nerd * Font and dropped without one; `{ nerd, plain }` gives one for each icon set. With no icon in * the current set, a row shows its level marker or the bullet and a section shows no glyph. */ icon?: IconLike; /** Where it shows. Default ["footer", "sidebar"]. */ slots?: WidgetSlot[]; /** Lower comes first. Default 100. Built-ins: container 0, mcp 30, subagents 35, todo 40 and session-todos 50. */ order?: number; /** Re-render interval while a session runs. Omit for event-driven widgets. */ refreshMs?: number; /** Give up on a slow `update` after this many ms (default 10000). The widget shows the error. */ updateTimeoutMs?: number; /** * Called on each refresh tick (and on `handle.refresh()`), before rendering. Use it to poll * slow sources; rendering itself should be cheap and synchronous. */ update?: (ctx: ExtensionContext) => void | Promise<void>; /** * Opt in to caching: `render` and `detail` then run again only when this string, the registry * version (any widget update or refresh), the width, the theme or the context changes. Use it * for widgets that read session state (return something that changes with it) and are costly * to compute. Do not use it when the output depends on the clock. */ cacheKey?: (rc: WidgetRenderContext) => string; /** Return the one-line view, or undefined to hide the widget. */ render: (rc: WidgetRenderContext) => WidgetView | undefined; /** * Extra sidebar lines under the heading (plain or themed strings). A line can also be a list of * pieces, each a string or a `{ text, url }` link, for a line that links part of its text; see * `DetailLine`. A link shows as its label alone where the terminal cannot show links, and is * left out unless `url` is a plain https URL. */ detail?: (rc: WidgetRenderContext) => DetailLine[] | undefined; /** * Called when the user clicks a line returned by `detail`, with that line's index. Only the * lines `detail` returned are clickable, not the heading or an error line. A thrown error or * rejection is shown as a notification. */ onDetailClick?: (index: number, ctx: ExtensionContext) => void | Promise<void>; /** Palette actions, listed while the widget is enabled and not suspended. */ actions?: WidgetAction[]; /** A setStatus() key this widget replaces, so the raw status isn't shown twice. Default: the id. */ statusKey?: string; /** More setStatus() keys this widget replaces, for a widget that covers several raw statuses. */ statusKeys?: string[]; /** * Sidebar layout. "row" (default): one "• Title value" line in the status list, detail lines * indented under it. "section": its own sidebar section, with a bold title, the value beside * it, and the detail lines as the section body (plain or themed strings, shown as given). */ sidebar?: "row" | "section"; } /** A link inside a detail line: the visible `text`, and the https `url` it opens. */ export interface DetailLink { text: string; url: string; } /** * One detail line: a string, or a list of pieces. A piece is a string or a `DetailLink`. Links only * work as pieces: chassis removes every escape sequence from text, so a link written into a string * is shown as its label alone. That keeps text that came from outside (a ticket summary, an * incident title) from drawing a link of its own. */ export type DetailLine = string | Array<string | DetailLink>; export interface WidgetHandle { /** Run `update` (if any) and re-render now. */ refresh(): void; /** Remove the widget. */ dispose(): void; } /** The last failure of a widget, kept for the sidebar and `/widgets`. */ export interface WidgetError { phase: "update" | "render" | "detail" | "action"; message: string; at: number; } interface RegistryEntry { spec: WidgetSpec; timer?: ReturnType<typeof setInterval>; /** Unsubscribe functions for the pi.on handlers this widget added. */ offs: Array<() => void>; /** An `update` is running; ticks are skipped until it settles or times out. */ inflight?: boolean; lastUpdateAt?: number; lastDurationMs?: number; error?: WidgetError; /** Cached output for widgets with `cacheKey`. */ cache?: { key: string; theme: unknown; ctx: unknown; width: number; version: number; view?: { value: WidgetView | undefined; }; lines?: { value: string[]; }; }; /** Consecutive slow render/detail calls. */ strikes: number; /** Set after too many slow calls; cleared by `/widgets enable`. */ suspended?: boolean; lastRenderMs?: number; } /** The result of a tool call as a tool row spec sees it. Anything in it can be influenced from outside. */ export interface ToolRowResult { content?: Array<{ type: string; text?: string; }>; details?: any; } /** * How chassis draws the rows of a tool that belongs to another extension: one line per call * ("<icon> <title> <describe>" on the left, `summarize` on the right) and, when the row is opened * with ctrl+o, the lines `expand` returns. * * `args` and `result` come from the model and the tool, so treat them as untrusted and possibly * partial: a call is drawn while its arguments are still streaming. Every string a spec returns is * cleaned before it is drawn (escape sequences, control characters and bidi controls removed, line * breaks turned into spaces; SGR colour from `theme` is kept), and a spec that throws makes chassis * draw that call with the tool's own renderer instead. */ export interface ToolRowSpec { /** * Glyph in front of the row. A string is used as given in the Nerd Font set; in the plain set * its private-use (Nerd Font) characters are dropped, so a string of ordinary characters such as * "#" is kept in both and a bare Nerd Font glyph shows nothing. `{ nerd, plain }` gives one for * each icon set. Omit for no glyph. */ icon?: IconLike; /** Short verb or noun before the description, drawn in the text colour. May be empty. */ title: string; /** What the call is about, from its arguments: a path, a query, an id. One line. */ describe: (args: any, cwd: string, theme: Theme) => string; /** The right-aligned outcome of a finished call, for example "3 matches". `isError` is whether the tool reported an error. One line. */ summarize: (result: ToolRowResult, args: any, theme: Theme, isError: boolean) => string; /** Body lines shown when the row is opened (ctrl+o or a click). More than 120 lines are cut. */ expand?: (result: ToolRowResult, args: any, theme: Theme) => string[]; } /** Tool row specs by tool name. */ export type ToolRowSpecs = Record<string, ToolRowSpec>; /** Options for `registerToolRows`. */ export interface ToolRowsOptions { /** * Names the registrant. Registering again with the same id replaces that registrant's earlier * group, so a package that registers on every `session_start` (and again after /reload) never * piles up groups. Without an id each call adds a group that lives until its remover is called. */ id?: string; } /** One registration: the specs of one `registerToolRows` call. */ export interface ToolRowGroup { id?: string; specs: Map<string, ToolRowSpec>; } /** Shared state between chassis and widget extensions. */ export interface Registry { widgets: Map<string, RegistryEntry>; /** Set by chassis while a session runs. */ ctx: ExtensionContext | undefined; /** Set by chassis: asks the TUI to repaint. */ requestRender: () => void; /** Subscribers to registry changes (chassis's renderers). */ listeners: Set<() => void>; /** Bumped on every change, so renderers can cache. */ version: number; /** Widget ids the user switched off (persisted, see `/widgets`). */ disabled: Set<string>; /** Set by chassis's `installHost()`: the version of this API. Absent when chassis isn't loaded. */ apiVersion?: number; /** * Set by `installHost()`: what client.ts calls to register a widget with the host. `ctx` is * optional: a caller inside a `session_start` handler passes the handler's context, so the * widget's first `update` and its timer start even if chassis's own handler has not run yet. */ register?: (pi: ExtensionAPI, spec: WidgetSpec, ctx?: ExtensionContext) => WidgetHandle; /** Set by `installHost()`: the version of the tool row API. Absent when the host predates it, so a client can feature-detect. */ toolRowsVersion?: number; /** Set by `installHost()`: registers tool row specs and returns a function that removes them. */ registerToolRows?: (specs: ToolRowSpecs, options?: ToolRowsOptions) => () => void; /** Registered tool row groups, oldest first. Absent until the first registration; read through `toolRowGroups`. */ toolRows?: ToolRowGroup[]; } /** Bumped on a breaking change to the registry or WidgetSpec; client.ts checks it. */ export declare const API_VERSION = 1; /** Version of the tool row API (`registerToolRows`). Bumped on a breaking change to it or to ToolRowSpec. */ export declare const TOOL_ROWS_VERSION = 1; /** A registration made (through client.ts) before chassis had loaded. */ export interface PendingRegistration { pi: ExtensionAPI; spec: WidgetSpec; /** Hands the real handle back to the client once the host has registered the widget. */ attach(handle: WidgetHandle): void; } /** Tool rows registered (through client.ts or the raw protocol) before chassis had loaded. */ export interface PendingToolRows { specs: ToolRowSpecs; /** The registrant's id, as in `ToolRowsOptions`. */ id?: string; /** Hands the host's unregister function back to the registrant once the host has taken the rows. */ attach(unregister: () => void): void; } /** Register everything that client.ts queued before the host loaded. */ export declare function drainPending(): void; /** * Called once by chassis when it loads: announces the host (so client.ts registers straight into * the registry) and takes over widgets that were queued before it loaded. */ export declare function installHost(): void; /** Where the settings file is stored. PI_CHASSIS_STATE overrides it (used by tests). */ export declare function statePath(): string; export declare function getRegistry(): Registry; /** The registered tool row groups, oldest first (created on first use, so an older registry works). */ export declare function toolRowGroups(): ToolRowGroup[]; /** A spec that failed this many finished calls is no longer used until it is registered again. */ export declare const TOOL_ROW_FAILURE_LIMIT = 3; /** Count a failure of `spec` on a finished call (not while arguments or output were still arriving). */ export declare function noteToolRowFailure(spec: ToolRowSpec): void; /** Whether `spec` failed too many finished calls to be used for new ones. */ export declare function toolRowBroken(spec: ToolRowSpec): boolean; /** * Register chassis-styled rows for tools that belong to another extension, by tool name. Returns a * function that removes them (calling it twice is harmless). * * The rows are looked up when a call is drawn, so it does not matter whether the extension that * owns the tool, the one registering the rows or chassis loads first. A call already on screen keeps * the renderer it was created with. * * chassis's own rows for pi's built-in tools (read, write, edit, bash, grep, find, ls) always win: a * spec registered under one of those names is never used. For any other name the most recently * registered spec wins, and removing it brings back the one before it. An entry is used only if * it has a string `title`, function `describe` and `summarize`, and `expand` is a function when * given; any other entry is skipped. * * Pass `{ id }` when the registrant can run more than once in a process (an extension that * registers on every `session_start`, or is loaded again by /reload): registering again with the * same id replaces its earlier group instead of adding another. Without an id, call the returned * remover (for example on `session_shutdown`) before registering again. */ export declare function registerToolRows(specs: ToolRowSpecs, options?: ToolRowsOptions): () => void; /** The registered row spec for a tool, newest registration first, or undefined. */ export declare function toolRowFor(toolName: string): ToolRowSpec | undefined; /** Make every widget render again (an icon set change, say), dropping cached output. */ export declare function invalidateWidgets(): void; /** * Register (or replace) a widget. Returns a handle for on-demand refresh and removal. * * Pass `pi` so the widget's timers follow the session lifecycle: they start on session_start and * stop on session_shutdown. The widget itself stays registered across /reload of chassis. * * Registering from inside a `session_start` handler (as a package that does not import chassis does) * misses that session's own `session_start` event for the widget, so pass the handler's `ctx`. */ export declare function registerWidget(pi: ExtensionAPI, spec: WidgetSpec, ctx?: ExtensionContext): WidgetHandle; /** Widgets for a slot, sorted by order then id. */ export declare function widgetsFor(slot: WidgetSlot): WidgetSpec[]; /** setStatus() keys claimed by registered widgets. */ export declare function claimedStatusKeys(): Set<string>; /** * Render a widget without letting it throw: a failure is recorded on the widget and returned as * an "error" view. Returns undefined when the widget itself returns undefined (hidden). * Widgets with `cacheKey` are only re-rendered when the key, width, theme, context or registry * version changes; a widget that renders slowly several times in a row is suspended. */ export declare function renderWidget(spec: WidgetSpec, rc: WidgetRenderContext): WidgetView | undefined; /** Detail lines of a widget; a failure is recorded and yields no lines. Cached like `renderWidget`. */ export declare function detailWidget(spec: WidgetSpec, rc: WidgetRenderContext): string[]; /** The last recorded failure of a widget, if any. */ export declare function widgetError(id: string): WidgetError | undefined; /** Turn a widget off or on. The choice is saved and survives restarts. */ export declare function setWidgetDisabled(id: string, disabled: boolean): boolean; /** Run a widget's update now, even outside its timer. */ export declare function refreshWidget(id: string): boolean; export interface WidgetInfo { id: string; title: string; slots: WidgetSlot[]; disabled: boolean; refreshMs?: number; lastUpdateAt?: number; lastDurationMs?: number; inflight: boolean; suspended: boolean; lastRenderMs?: number; error?: WidgetError; } /** Snapshot of every registered widget, for `/widgets`. */ export declare function widgetInfo(): WidgetInfo[]; /** Plain-text table for `/widgets list`. */ export declare function formatWidgetList(list: WidgetInfo[], now?: number): string; export interface WidgetActionInfo { widgetId: string; widgetTitle: string; id: string; label: string; description?: string; } /** Palette actions of every enabled, non-suspended widget, in widget order. */ export declare function widgetActions(): WidgetActionInfo[]; /** Palette value for an action: ids are encoded, so they may contain any character. */ export declare function widgetActionValue(widgetId: string, actionId: string): string; export declare function parseWidgetActionValue(value: string): { widgetId: string; actionId: string; } | undefined; /** * Run a widget's `onDetailClick` for the clicked detail line. Resolves to undefined on success, or * to a short message when it failed (also recorded on the widget as an "action" error). */ export declare function runWidgetClick(widgetId: string, index: number, ctx: ExtensionContext): Promise<string | undefined>; /** * Run a widget action. Resolves to undefined on success, or to a short message when the action * is unknown or failed (the failure is also recorded on the widget). */ export declare function runWidgetAction(widgetId: string, actionId: string, ctx: ExtensionContext): Promise<string | undefined>; export {};