PiG Documentation

Guides and references for configuring, using, and extending PiG.

Extension views

An extension view is a GUI that an extension describes once, as data. The extension mounts the view with ctx.ui.mountView, and every client attached to the session draws it with its own controls: the terminal draws rows, and a web page draws HTML. A view is a tree of nodes (text, lists, inputs, buttons, a grid), the intents a user can raise, and optionally alternatives for different clients, key bindings and a drawing. A view fills a slot such as a panel, a widget row or a dialog. No client runs extension code.

Differs from Pi. Pi has no views: its ctx.ui.custom components draw in the terminal only. Views are the PiG-additive feature D614. Stock PiG attaches no view client, so ctx.ui.viewAbilities() returns null and ctx.ui.mountView rejects with code unsupported until a Piglet attaches one.

This page uses the Node SDK, because a .mjs extension loads without a build. The calls in each SDK names the same calls for Go, Python, Rust and Lisp. What the clients draw says what each client does with a view at this version.

Try it

The terminal draws views when the active Piglet sets viewClient: terminal. Save this Piglet in the directory of the extension file and start it there with pig --piglet ./views.yaml.

name: views
description: "Draw extension views in the terminal and serve them to other clients."
viewClient: terminal
viewEndpoint: socket
extensions:
  - name: todo
    origins:
      - local:./todo.mjs

A Piglet's extensions and the -e option load a .mjs file. The extensions folders load only .ts and .js files (Extensions). After you edit the extension, type /reload.

viewEndpoint: socket serves the session's views on the Unix socket <agent directory>/view-endpoint/<pid>.sock, for example under ~/.pig/agent/view-endpoint/. A client program of the same user attaches there. The pig binary contains no web page and no web server. The reference web client is in a checkout of the PiG repository, in examples/ui-view-web, and needs Node:

node examples/ui-view-web/bridge.mjs --connect ~/.pig/agent/view-endpoint
node examples/ui-view-web/bridge.mjs -- -e ./todo.mjs

The first command attaches a web page to the running terminal session. The second command starts a pig of its own for each page and needs no Piglet. Both print one line that names the file to open: ui-view-web: http://127.0.0.1:<port>/ (open: <dir>/open.html).

Open that file with the path the line printed: open <path> on macOS, xdg-open <path> on Linux, Start-Process <path> in PowerShell on Windows. The file sends your browser to the page's address, http://127.0.0.1:<port>/#<code>. The path holds no code, and only you can read the file. The address works once: the page takes the code out of the address bar at once, hands it to the bridge in a request body and is given a session secret in exchange, which it keeps for that tab only. No address holds a secret after the first load, and the browser's history may keep the used address, which opens nothing. A code lasts ten minutes. When it is used, or when the ten minutes pass unused, the bridge writes the next one into open.html and address (in the same private directory), so to open another tab, open open.html again. A replayed, expired or wrong code is refused, and the page then says to open the file again. This is why: a log, a terminal recording, a shared screen or a browser's history must not hold an address that still works. Do not hand the address itself to a command: the argument list of a command can be read by every user of a Linux machine. Keep the secret to yourself: with the second command, a process on your machine that has it can prompt the pig the bridge starts, as you. The bridge removes the files when it ends. --print-token, or UI_VIEW_WEB_PRINT_TOKEN=1, prints ui-view-web: http://127.0.0.1:<port>/#<code> as the line instead and makes no file; one run gives one code for one exchange.

A complete extension

This extension mounts a todo list in the panel slot. A terminal draws the plain view. A web page draws the alternative. Both show the same state. The key c opens a second mount, a dialog that asks before it removes the done items.

// todo.mjs: one todo list for the terminal and a web page.
export default function todo(pi) {
  const items = [
    { id: "milk", label: "Buy milk", done: false },
    { id: "letter", label: "Send the letter", done: true },
    { id: "plants", label: "Water the plants", done: false },
  ];
  let mount = null;
  let confirm = null;

  const open = () => items.filter((item) => !item.done).length;
  const list = () => ({
    kind: "select-list",
    id: "items",
    items: items.map((item) => ({ value: item.id, label: `${item.done ? "[x]" : "[ ]"} ${item.label}` })),
  });
  const plain = () => ({ root: { kind: "vstack", children: [{ kind: "text", text: `Todo: ${open()} open. Press c to clear the done items.` }, list()] } });
  const rich = () => ({ root: { kind: "vstack", gap: 1, children: [{ kind: "markdown", text: `# Todo\n\n**${open()}** of ${items.length} open.` }, list()] } });
  const removed = { type: "object", properties: { removed: { type: "integer" } }, required: ["removed"] };
  const content = () => ({
    title: "Todo",
    view: plain(),
    alternatives: [{ when: { any: [{ all: [{ claim: "client.kind", op: "equals", value: "web" }] }] }, view: rich() }],
    intents: [
      { name: "todo.toggle", nodeKey: "items", arg: { type: "object", properties: { value: { type: "string" } }, required: ["value"] } },
      { name: "todo.clear", arg: { type: "object" }, answer: removed },
    ],
    bindings: [{ key: "c", intent: "todo.clear", name: "Clear done" }],
    a11y: [{ node: "items", name: "Todo items", role: "list" }],
    focus: [{ node: "items", request: "mount" }],
    fallback: { kind: "text", text: "The todo list does not fit this client." },
  });

  // The dialog. Its two bindings raise one intent with different arguments.
  const question = () => ({
    title: "Clear done items",
    view: { root: { kind: "text", text: `Remove ${items.length - open()} done items? Press y or n.` } },
    intents: [
      { name: "todo.confirm", arg: { type: "object", properties: { yes: { type: "boolean" } }, required: ["yes"] }, answer: removed },
      { name: "todo.cancel", arg: { type: "object" }, answer: removed, dismiss: true },
    ],
    bindings: [{ key: "y", intent: "todo.confirm", arg: { yes: true }, name: "Remove" }, { key: "n", intent: "todo.confirm", arg: { yes: false }, name: "Keep" }],
  });
  const clear = () => {
    const before = items.length;
    items.splice(0, items.length, ...items.filter((item) => !item.done));
    return { removed: before - items.length };
  };

  // Mount once, when a client that draws panels is attached.
  const show = async (abilities, ctx) => {
    if (!abilities || mount || !abilities.slots.includes("panel")) return;
    mount = (await ctx.ui.mountView({ key: "todo", slot: "panel", ...content() })).mount;
  };
  pi.onViewAbilities(show);
  pi.on("session_start", (_event, ctx) => show(ctx.ui.viewAbilities(), ctx));

  pi.onViewIntent(async (inv, ctx) => {
    let answer;
    if (inv.intent === "todo.toggle") {
      const item = items.find((entry) => entry.id === inv.arg.value);
      if (!item) return { outcome: "refused", error: "no such item" };
      item.done = !item.done;
    } else if (inv.intent === "todo.clear") {
      // Ask in a dialog when a client draws dialogs. Only the extension closes a dialog.
      if (ctx.ui.viewAbilities()?.slots.includes("dialog")) {
        if (!confirm) confirm = (await ctx.ui.mountView({ key: "todo-confirm", slot: "dialog", ...question() })).mount;
        return { outcome: "done", answer: { removed: 0 } };
      }
      answer = clear();
    } else if (inv.intent === "todo.confirm" || inv.intent === "todo.cancel") {
      answer = inv.arg.yes ? clear() : { removed: 0 };
      await ctx.ui.removeView(confirm);
      confirm = null;
    } else return { outcome: "refused", error: "unknown intent" };
    mount = (await ctx.ui.updateView(mount, content())).mount;
    return { outcome: "done", answer };
  });
}

The same extension in Go

A Go extension is a package with func Extension() *sdk.Extension, in a module that requires github.com/MichaelKinsy/PiG/extensions/sdk. pig extension init ./todo --lang go creates the module (Extensions). PiG builds the package when it loads it and at every /reload. Name the directory in the Piglet's origins (local:./todo) or with -e ./todo.

The Go SDK takes the records of this page as structs with the same member names, and the kit package builds the nodes. Go names lists them. A handler runs on a goroutine of its own, so guard your state. This example is todo.mjs without the dialog.

// todo/extension.go: the todo list of todo.mjs as a Go extension.
package todo

import (
    "encoding/json"
    "fmt"
    "slices"
    "sync"

    "github.com/MichaelKinsy/PiG/extensions/sdk"
    "github.com/MichaelKinsy/PiG/extensions/sdk/kit"
)

type item struct {
    id, label string
    done      bool
}

// Extension returns a new instance. PiG calls it at every load and reload.
func Extension() *sdk.Extension {
    var (
        mu    sync.Mutex
        mount *sdk.ViewRef
        items = []*item{{id: "milk", label: "Buy milk"}, {id: "letter", label: "Send the letter", done: true}, {id: "plants", label: "Water the plants"}}
    )
    content := func() sdk.ViewContent {
        open := 0
        rows := make([]kit.SelectItem, len(items))
        for i, it := range items {
            box := "[x]"
            if !it.done {
                box = "[ ]"
                open++
            }
            rows[i] = kit.SelectItem{Value: it.id, Label: box + " " + it.label}
        }
        list := func() kit.Node { return kit.NewSelectList("items", rows, 8) }
        web := sdk.ViewWhen{Any: []sdk.ViewWhenAll{{All: []sdk.ViewClause{{Claim: "client.kind", Op: "equals", Value: "web"}}}}}
        rich := kit.NewMarkdown(fmt.Sprintf("# Todo\n\n**%d** of %d open.", open, len(items)), 1, 0)
        return sdk.ViewContent{
            Title:        "Todo",
            View:         kit.View{Root: kit.NewContainer(kit.NewText(fmt.Sprintf("Todo: %d open. Press c to clear the done items.", open), 1, 0), list())},
            Alternatives: []sdk.ViewAlternative{{When: web, View: kit.View{Root: kit.NewContainer(rich, list())}}},
            Intents: []sdk.ViewIntent{
                {Name: "todo.toggle", NodeKey: "items", Arg: sdk.ViewShape{Type: "object", Properties: map[string]sdk.ViewShape{"value": {Type: "string"}}, Required: []string{"value"}}},
                {Name: "todo.clear", Arg: sdk.ViewShape{Type: "object"}, Answer: &sdk.ViewShape{Type: "object", Properties: map[string]sdk.ViewShape{"removed": {Type: "integer"}}, Required: []string{"removed"}}},
            },
            Bindings: []sdk.ViewBinding{{Key: "c", Intent: "todo.clear", Name: "Clear done"}},
            A11y:     []sdk.ViewA11y{{Node: "items", Name: "Todo items", Role: "list"}},
            Focus:    []sdk.ViewFocus{{Node: "items", Request: "mount"}},
            Fallback: kit.NewText("The todo list does not fit this client.", 1, 0),
        }
    }
    // Mount once, when a client that draws panels is attached.
    show := func(ctx sdk.Context, abilities *sdk.ViewAbilities) {
        mu.Lock()
        defer mu.Unlock()
        if abilities == nil || mount != nil || !slices.Contains(abilities.Slots, sdk.ViewSlotPanel) {
            return
        }
        status, err := ctx.MountView(sdk.ViewMount{Key: "todo", Slot: sdk.ViewSlotPanel, ViewContent: content()})
        if err != nil {
            ctx.Notify("todo: "+err.Error(), "error")
            return
        }
        mount = &status.Mount
    }

    ext := sdk.New("todo")
    ext.OnViewAbilities(show)
    ext.OnSessionStart(func(ctx sdk.Context, _ map[string]any) (any, error) {
        show(ctx, ctx.ViewAbilities())
        return nil, nil
    })
    ext.OnViewIntent(func(in sdk.ViewIntentInvocation) sdk.ViewIntentResult {
        mu.Lock()
        defer mu.Unlock()
        result := sdk.ViewIntentResult{Outcome: "done"}
        switch in.Intent {
        case "todo.toggle":
            var arg struct {
                Value string `json:"value"`
            }
            if err := json.Unmarshal(in.Arg, &arg); err != nil {
                return sdk.ViewIntentResult{Outcome: "failed", Error: err.Error()}
            }
            i := slices.IndexFunc(items, func(it *item) bool { return it.id == arg.Value })
            if i < 0 {
                return sdk.ViewIntentResult{Outcome: "refused", Error: "no such item"}
            }
            items[i].done = !items[i].done
        case "todo.clear":
            before := len(items)
            items = slices.DeleteFunc(items, func(it *item) bool { return it.done })
            // The answer is JSON of the declared shape.
            result.Answer = json.RawMessage(fmt.Sprintf(`{"removed":%d}`, before-len(items)))
        default:
            return sdk.ViewIntentResult{Outcome: "refused", Error: "unknown intent"}
        }
        // Update through the handler's context, then answer.
        status, err := in.Context.UpdateView(sdk.ViewUpdate{Mount: *mount, ViewContent: content()})
        if err != nil {
            return sdk.ViewIntentResult{Outcome: "failed", Error: err.Error()}
        }
        mount = &status.Mount
        return result
    })
    return ext
}

Go names

  • Nodes: kit.NewContainer(children...) (a column), kit.NewBox(paddingX, paddingY, children...), kit.NewText(text, paddingX, paddingY), kit.NewTruncatedText(text, paddingX, paddingY), kit.NewMarkdown(text, paddingX, paddingY), kit.NewLines(lines), kit.NewSpacer(lines), kit.NewDynamicBorder(color), kit.NewSelectList(id, items, maxVisible), kit.NewSettingsList(id, items, maxVisible), kit.NewInput(id), kit.NewEditor(id), kit.NewMouseRegion(id, child), kit.NewScrollView(id, child) and kit.NewGrid(id, columns, cells). Set the other members on the struct that a constructor returns.
  • Images: kit.NewImage(data, mimeType) takes the decoded bytes of a photograph and returns a *kit.Image. Set MaxWidthCells, MaxHeightCells and ImageID (all *int), Filename, FallbackColor and ID on the struct. The node carries the bytes in the view's images list; the kit does this for you.
  • Ids: only the constructors with an id argument make a node with an id. A box, a text, a container and a markdown node have none in Go. To give a drawing a node, name a kit.NewScrollView(id, child) in Node, or leave Node empty.
  • Content: sdk.ViewContent{Title, View, Intents, Bindings, Alternatives, Drawing, A11y, Focus, Fallback}. View is a kit.View{Root: node}, Fallback is a node and Drawing is a *sdk.ViewDrawing. sdk.ViewMount{Key, Slot, Target, ViewContent} and sdk.ViewUpdate{Mount, ViewContent} embed it. The slots are constants such as sdk.ViewSlotPanel and sdk.ViewSlotDialog.
  • Intents: sdk.ViewIntent{Name, NodeKey, Arg, Answer, Cancellable, TimeoutMs, WhenHidden, Dismiss}. Arg is a sdk.ViewShape and Answer is a *sdk.ViewShape. In the handler, in.Arg and the result's Answer are json.RawMessage.
  • Other records: sdk.ViewBinding{Key, Gesture, Intent, Arg, Name}, sdk.ViewA11y{Node, Name, Role, ...}, sdk.ViewFocus{Node, Request}, sdk.ViewAlternative{When, View, Drawing}.
  • Drawings: sdk.ViewDrawing{Profile, Node, Viewport, Shapes, Regions}, *sdk.ViewViewport{X, Y, Width, Height, Fit}, sdk.ViewDrawShape{Kind, Key, Fill, Stroke, X, Y, Width, Height, ...} (one struct for every kind, with float64 numbers) and sdk.ViewRegion{Key, Shape, Gestures, Intent, Name, Role}. abilities.Drawing is nil when no client draws a profile, and abilities.Drawing.Profiles is a []string.
  • Errors: a rejected operation returns a *sdk.ViewError. Match it with errors.As and read its Code, for example sdk.ViewErrorUnsupported.

Mount, update and end

  • ctx.ui.viewAbilities() returns what the attached clients draw, or null when no client is attached: { slots, nodes, markdown, imageFormats, limits, input, claims, slotClaims, drawing }. slots and nodes are arrays of strings. drawing is absent when no client draws a profile. With several clients the record is their merge: the union of the slots, node kinds and drawing profiles, the largest limits, and the claims that every client states with the same value.
  • pi.onViewAbilities((abilities, ctx) => ...) runs when the first client attaches, when the abilities change and when the last client leaves (null). It does not run for the state the extension starts in, so also read ctx.ui.viewAbilities() at session_start. A mount stays live while no client is attached, and a client that attaches later is sent it.
  • ctx.ui.mountView({ key, slot, target, title, view, intents, bindings, alternatives, drawing, a11y, focus, fallback }) mounts the view. Only key, slot and view are required. Omit a member that you do not use. key is 1 to 128 bytes and names the mount inside your extension. view is { root: node }. title is the label of the mount in a tab or a list of views: at most 64 bytes on one line. target is required for three slots only: { toolCallId } for tool-card, { messageType } for message and { entryType } for entry. fallback is one node: a client that cannot draw the content is sent it, marked degraded, when another attached client can draw the content.
  • Every operation returns a promise of { mount, state }. mount is the ref { key, epoch, rev }. Pass the newest ref to the next operation: an older ref rejects with code stale.
  • ctx.ui.updateView(mount, content) replaces the whole content. content has the members of a mount without key, slot and target. Send every member again, title included: an update without a member clears it.
  • ctx.ui.hideView(mount) and ctx.ui.showView(mount) hide and show a mount without ending it.
  • ctx.ui.finishView(mount, result) ends a mount as completed, and result is any JSON value of at most 65536 bytes. ctx.ui.removeView(mount) ends it as withdrawn. After either, an operation on the mount rejects with code terminal, and you can mount the same key again.
  • ctx.ui.viewState(key) returns { mount, state, reason, result }. state is live, hidden, finished, removed or broken. The host breaks a mount with reason session_replaced, owner_gone or shutdown.
  • ctx.ui.viewDiagnostics(key) returns the notices of a mount: which update the host rejected, which intent it ended, what a client did not draw (undrawn) and why a client did not give the focus (unfocused). The host keeps 32 notices for a mount.
  • /reload loads the extension as a new instance. The mounts of the old instance are broken with reason owner_gone. The new instance holds no mount and mounts again.

Nodes

A node is a JSON object with a kind. Give a node an id when an intent, an a11y record, a focus record or a drawing names it. Omit a member that you do not set. A kind that no attached client lists in abilities.nodes rejects the mount with code invalid, and so does an unknown member. The sizes of a node are terminal cells.

Kind
What it is
Members
vstack, hstackchildren in a column or a rowchildren, gap; a child's stack: { basis, grow, shrink, minSize, maxSize }
containerchildren in a columnchildren
boxpadded children on a backgroundchildren, paddingX, paddingY (1 when absent), bg
textwrapped texttext, paddingX, paddingY (1 when absent), bg
truncated-textone row of text, cut at the widthtext
markdownrendered markdowntext, defaultTextStyle: { color, bgColor, bold, italic, underline, strikethrough }
linesrows that your extension drew, shown verbatimcontent (an array of strings)
spacerempty rowslines
dynamic-bordera horizontal rulecolor
select-lista list with one highlighted item; the user chooses an itemitems: [{ value, label, description }], selectedIndex, maxVisible
settings-listsettings that step through their valuesitems: [{ id, label, currentValue, values }]
inputone line of text; Enter submitsvalue, placeholder
editorseveral lines of textvalue
mouse-regiona button: a click activates it. It needs a pointer (abilities.input.pointer), which the terminal has only in fullscreen mode, so also give its action a bindingchildren (an array of one node, for example a text with the label), region: { types: ["press"] }
scroll-viewone child that scrollschildren (an array of one node), follow: "end"
grida calendar-style grid of equal columns; the user chooses a cellid (required), columns (1 to 16), head (one label for each column), chipRows (1 to 8, default 3), selected (a cell's value), cells: [{ value, label, mark: "current", dim, color, chips: [{ text, color }], more }]
imagea photograph or other bitmap. The bytes ride in the view's images list, not in the noderef (the lowercase hex SHA-256 of the bytes), mimeType (image/png, image/jpeg, image/gif or image/webp), maxWidthCells (60 when absent), maxHeightCells, imageId (the Kitty image id of the transmission; absent, the host allocates one; a terminal that draws the image with placeholder cells allocates its own and ignores it), filename, fallbackColor (a theme token); the view carries images: [{ ref, mimeType, data }] with data in base64

A grid has at most 128 cells in at most 32 rows, and a cell has at most 8 chips. A cell without a value cannot be chosen. more counts the events that you left out. A bg, a color and the colors of a defaultTextStyle name theme tokens (Themes); a grid color is a theme token, #rrggbb or #rrggbbaa.

A photograph or any other bitmap belongs in an image node. The pixels and shapes drawing profiles (Drawings) are for drawings that your extension computes. The terminal draws no drawing profile, and it draws an image node.

The bytes of an image are not text: they count in the snapshot bytes of the mount and not in its text bytes. The terminal's 262144 snapshot bytes hold a photograph of about 195,000 bytes. The ref is the SHA-256 of the bytes. The terminal declares abilities.imageFormats as ["png", "jpeg", "gif", "webp"]. Pi has no mount view; this node is the D107 view kit's image node (Pi's Image component) under D614.

// week.mjs: a grid, and a view that the user hides and opens again.
export default function week(pi) {
  const days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
  let picked = "Wed";
  let mount = null;

  const content = () => ({
    title: "Week",
    view: {
      root: {
        kind: "grid",
        id: "days",
        columns: 7,
        head: days,
        selected: picked,
        cells: days.map((day, i) => ({ value: day, label: String(i + 10), mark: day === "Wed" ? "current" : undefined, chips: day === "Fri" ? [{ text: "Demo", color: "#3366ff" }] : [] })),
      },
    },
    intents: [
      { name: "week.pick", nodeKey: "days", arg: { type: "object", properties: { value: { type: "string" } }, required: ["value"] } },
      { name: "week.hide", arg: { type: "object" } },
      { name: "week.open", arg: { type: "object" }, whenHidden: true },
    ],
    bindings: [{ key: "h", intent: "week.hide", name: "Hide" }],
    focus: [{ node: "days", request: "mount" }],
  });

  const show = async (abilities, ctx) => {
    if (!abilities || mount || !abilities.slots.includes("panel") || !abilities.nodes.includes("grid")) return;
    mount = (await ctx.ui.mountView({ key: "week", slot: "panel", ...content() })).mount;
  };
  pi.onViewAbilities(show);
  pi.on("session_start", (_event, ctx) => show(ctx.ui.viewAbilities(), ctx));

  pi.onViewIntent(async (inv, ctx) => {
    if (inv.intent === "week.hide") mount = (await ctx.ui.hideView(mount)).mount;
    else if (inv.intent === "week.open") mount = (await ctx.ui.showView(mount)).mount;
    else {
      picked = inv.arg.value;
      mount = (await ctx.ui.updateView(mount, content())).mount;
    }
    return { outcome: "done" };
  });
}

Intents

An intent is an action that the user raises on a mount. Declare every intent in intents, as the examples do.

  • name is unique in the mount. Write it as <extension>.<verb>.
  • nodeKey binds the intent to the node with that id. Choosing a select-list item or a grid cell, changing a settings-list value, submitting an input or an editor, and clicking a mouse-region raise the intent. The host refuses an intent that has a nodeKey when a client raises it on another node or on none.
  • An intent without nodeKey belongs to the whole mount. A binding, a drawing region and whenHidden need such an intent.
  • arg is the shape of the argument. The host checks the argument against it before your handler runs. Declare an object with a string value for a select-list (the item's value), a grid (the cell's value), an input and an editor (the text). Declare an object with strings item and value for a settings-list (the setting's id and its new value). Declare { type: "object" } for a mouse-region: it accepts only {}.
  • A shape is { type }, where type is boolean, string, integer, number, enum (with enum: an array of at most 32 strings), object (with properties and required; at most 32 properties, and the value may hold no other property) or array (with items and maxItems; at most 64 items). A shape nests at most 4 deep.
  • answer is the optional shape of the handler's answer. An answer outside it settles the intent failed.
  • timeoutMs is 100 to 300000 and defaults to 30000. cancellable: true lets the host abort inv.signal at the timeout.
  • dismiss: true names the intent that a client raises, with {}, when the user dismisses a dialog or overlay mount, for example with Escape. Your handler closes the mount. At most one intent of a mount has it. It has no nodeKey, and its arg accepts {}. Without one, the mount stays open until your own key or node closes it. In another slot the member has no effect.
  • whenHidden: true lets a client raise the intent while the mount is hidden. A client lists the hidden mount by its title, and when the user chooses it your handler shows the mount. At most one intent of a mount has it. It has no nodeKey, and its arg accepts {}.

One handler answers every intent: pi.onViewIntent(async (inv, ctx) => ...). inv has intent, arg, nodeKey, mount, rev, ticket and signal. Return { outcome: "done", answer }, { outcome: "refused", error } or { outcome: "failed", error }. Change your state, call ctx.ui.updateView through the handler's ctx with the ref that you keep, wait for it, then answer. The client is sent the new view before it is told that the intent is done. A hide, a show, a finish and a remove in the handler are also part of the answer. An update from outside the handler while it answers settles the intent stale.

Bindings

bindings (at most 32) ties a key or a gesture to an intent without nodeKey: { key, intent, arg, name } or { gesture, intent, arg, name }.

  • key is a key id such as d, shift+left or ctrl+shift+p. gesture is swipe-left, swipe-right, swipe-up or swipe-down. A key or a gesture is bound once.
  • arg is the constant argument ({} when absent), so several bindings can raise one intent with different arguments. name is the label that a client shows.
  • A binding works only while the mount holds the focus, and after the focused node had the key. An input or an editor takes every key, so give such a view another way to its actions.
  • The keys escape, tab, f6 and ctrl with c, d or z are reserved: a binding of one rejects with code invalid.
  • A client that does not honour a binding leaves an unsupported notice with the path bindings[i].

Alternatives

A client states facts about itself as claims. alternatives (at most 8) gives a client another view when its claims match. The host sends each client the first alternative whose when holds, otherwise view. One mount and one state serve every client.

Client
Claims
terminalclient.kind = "terminal", size.columns (integer), size.rows (integer; the rows of the mount's slot)
reference web pageclient.kind = "web"

when is { any: [{ all: [clause, ...] }, ...] }: it holds when every clause of one group holds. A when has at most 8 groups of 8 clauses. A clause is { claim, op, value }, and op is one of:

  • present: the client states the claim. It takes no value.
  • equals: the claim equals value, a boolean, an integer or a string.
  • contains: the claimed list holds every string of the array value.
  • atLeast: the claimed integer is at least value.
const wideTerminal = { any: [{ all: [{ claim: "client.kind", op: "equals", value: "terminal" }, { claim: "size.columns", op: "atLeast", value: 100 }] }] };

An alternative is { when, view, drawing }. It shares the mount's intents, bindings, a11y and focus, so use the same node ids in every view. A client is sent the a11y and focus entries of the nodes that its view has. The mount's drawing belongs to view: an alternative does not inherit it.

Accessibility and focus

  • a11y: [{ node, name, description, role, selected, checked, expanded, busy, disabled, readOnly, required, invalid, relations }] describes the node with id node. Only node is required. role is one of alert, button, checkbox, dialog, group, heading, image, link, list, listitem, menu, menuitem, progressbar, radio, region, status, switch, tab, tablist, tabpanel, textbox, toolbar, tree and treeitem. A relation is { kind, target } with labelledBy, describedBy, controls or owns.
  • focus: [{ node, request }] makes nodes focusable. The order of the entries is the focus order. request: "mount" asks for the focus when the mount is first drawn. request: "update" asks when the revision that carries it is first drawn, so send it only with the update that moves the focus. At most one entry requests the focus. The client decides: when it does not give the focus, it leaves an unfocused notice.
  • Each list has at most 256 entries. A node that no view of the mount has rejects the mount with code invalid.

Drawings

A drawing adds vector shapes or a pixel grid to a view. Send a drawing only when abilities.drawing.profiles lists its profile: without a client that draws the profile, the mount rejects with code unsupported.

// meter.mjs: a level meter. A client that draws the scene profile is sent a drawing. Every other client is sent text.
export default function meter(pi) {
  let level = 3;
  let mount = null;
  let scene = false;

  const drawing = () => ({
    profile: "scene",
    node: "canvas",
    viewport: { x: 0, y: 0, width: 100, height: 20, fit: "contain" },
    shapes: [
      { kind: "rect", x: 0, y: 0, width: 100, height: 20, radius: 4, fill: "#20242c" },
      { kind: "rect", key: "bar", x: 0, y: 0, width: level * 10, height: 20, radius: 4, fill: "accent" },
      { kind: "text", x: 50, y: 14, size: 10, align: "center", text: `${level * 10}%`, fill: "#ffffff" },
    ],
    regions: [{ key: "raise", shape: { kind: "rect", x: 0, y: 0, width: 100, height: 20 }, gestures: ["activate"], intent: "meter.raise", name: "Raise the level" }],
  });
  const text = () => ({ kind: "text", text: `Level ${level} of 10. Press r to raise it.` });
  // The region and the binding raise the intent, so the intent has no nodeKey.
  const content = () => ({
    view: { root: scene ? { kind: "box", id: "canvas" } : text() },
    ...(scene ? { drawing: drawing() } : {}),
    intents: [{ name: "meter.raise", arg: { type: "object" }, answer: { type: "object", properties: { level: { type: "integer" } }, required: ["level"] } }],
    bindings: [{ key: "r", intent: "meter.raise", name: "Raise" }],
    fallback: text(),
  });

  const show = async (abilities, ctx) => {
    if (!abilities || mount || !abilities.slots.includes("panel")) return;
    scene = abilities.drawing?.profiles.includes("scene") ?? false;
    try {
      mount = (await ctx.ui.mountView({ key: "meter", slot: "panel", ...content() })).mount;
    } catch (err) {
      ctx.ui.notify(`meter: ${err.code ?? err.message}`, "error");
    }
  };
  pi.onViewAbilities(show);
  pi.on("session_start", (_event, ctx) => show(ctx.ui.viewAbilities(), ctx));

  pi.onViewIntent(async (inv, ctx) => {
    if (inv.intent !== "meter.raise") return { outcome: "refused", error: "unknown intent" };
    level = Math.min(10, level + 1);
    mount = (await ctx.ui.updateView(mount, content())).mount;
    return { outcome: "done", answer: { level } };
  });
}
  • profile is scene (vector shapes) or pixels (pixels: { width, height, asset, scaling: "nearest" | "smooth" } over an image asset declared in assets).
  • node is the id of the view node that the drawing fills. Without node, the drawing follows the view.
  • viewport is optional: { x, y, width, height, fit } is the rectangle of drawing coordinates that the client shows. width and height are positive, and fit is contain, cover or stretch.
  • A shape has a kind and the members of that kind. A member of another kind rejects the drawing.
Shape
Members
rectx, y, width, height, radius (optional)
ellipsecx, cy, rx, ry
linex1, y1, x2, y2
polylinepoints: [{ x, y }] (2 to 1024), closed
pathcommands: [{ op, ... }] (1 to 1024, the first is move); op is move or line (x, y), quad (x1, y1, x, y), cubic (x1, y1, x2, y2, x, y) or close
textx, y, text, size, align: "start" | "center" | "end"
imagex, y, width, height, asset
groupchildren
  • Every shape also takes the optional key, fill, stroke: { color, width }, opacity and transform (six numbers). A color is #rrggbb, #rrggbbaa or a theme color token.
  • regions: [{ key, shape, gestures, intent, name, role }] turns a gesture inside shape into a declared intent. key is unique among the regions. shape is a rect, an ellipse or a closed polyline. gestures lists activate, press, release or drag. name is required, and role is optional. The client tests which region a pointer is in, and it raises the intent with an argument of the intent's arg shape. Declare a region's intent without nodeKey.
  • A client fills the argument from the intent's arg shape and sets only the properties that shape names: x and y (the pointer in the drawing's coordinates; for an activate made with the keyboard, the centre of the region), dx and dy (for drag, the movement since the last event of that drag; 0 for every other gesture), gesture (activate, press, release or drag) and region (the region's key). A shape that names none of them is sent {}, and a property of type integer takes the nearest whole number. Only the reference web page (examples/ui-view-web, which runs with Node and is not part of the pig binary) raises the gesture of a region of a drawing. The terminal view client draws no drawings, so it raises none, and nothing else in this repository does.
  • A client raises a region's activate for a click, and a web page also raises it when Enter or Space reaches the focused region. The web page puts that activate at the centre of the region's shape, and its argument carries no mark that tells it from a click. Keep a separate button for the default action, or give the region a shape whose centre is a place you can act on.
  • A drawing has at most 4096 shapes nested 8 deep, 1048576 pixels and 64 regions, and never more shapes or pixels than abilities.drawing.shapes and abilities.drawing.pixels (code limit).

Slots

slot is one of notify, status, widget-above, widget-below, header, footer, dialog, overlay, panel, tool-card, message and entry. A mount has one slot. To show the same state in a panel and in a dialog, make two mounts with two keys. Mount only in a slot that abilities.slots lists: another slot rejects with code unsupported.

A mount in the slot dialog is a dialog over the screen, as todo.mjs shows. Give it a title. Only your extension closes a dialog: hide, finish or remove the mount in a handler. Declare one intent with dismiss: true for the user's Escape or close control, and also bind a key with a name, because a client that does not raise the dismiss intent leaves the mount open. escape cannot be bound.

Errors

A rejected operation rejects its promise with an Error whose code is one of:

Code
Meaning
invalidThe record is malformed or past a bound of the host: an unknown member, node kind, slot or operator, a key that is already mounted, or a list that is too long. Nothing changes.
unsupportedNo attached client can draw the mount: no client is attached, no client draws the slot or the drawing profile, or the mount declares intents and the client delivers no input.
limitThe content exceeds what the client states in abilities.limits (nodes, depth, snapshotBytes, textBytes, mounts) or in abilities.drawing.
staleThe ref is not the newest ref of the mount.
terminalThe mount has ended.
not_foundThe extension has no mount under this key.

The calls in each SDK

Every SDK has every call, and its mount takes the same members. The Go, Python, Rust and Lisp SDKs build the view with their component kit.

Call
Node
Go
Python and Rust
Lisp
read the abilitiesctx.ui.viewAbilities()ctx.ViewAbilities()ctx.view_abilities()ctx-view-abilities
abilities changedpi.onViewAbilitiesext.OnViewAbilitiesext.on_view_abilitieson-view-abilities
mountctx.ui.mountViewctx.MountViewctx.mount_viewctx-mount-view
updatectx.ui.updateViewctx.UpdateViewctx.update_viewctx-update-view
hide, showhideView, showViewHideView, ShowViewhide_view, show_viewctx-hide-view, ctx-show-view
finishfinishView(mount, result)FinishView, FinishViewWithPython finish_view(mount, result=...); Rust finish_view, finish_view_withctx-finish-view (:result)
removeremoveViewRemoveViewremove_viewctx-remove-view
stateviewStateViewStateview_statectx-view-state
diagnosticsviewDiagnosticsViewDiagnosticsview_diagnosticsctx-view-diagnostics
answer intentspi.onViewIntentext.OnViewIntentext.on_view_intenton-view-intent

Every SDK builds the image node. Go: kit.NewImage(data, mimeType). Rust: kit::Image::new(data, mime_type), with max_width_cells, max_height_cells, image_id, filename and fallback_color as builder methods. Python: kit.Image(data, mime_type, max_width_cells=..., max_height_cells=..., image_id=..., filename=..., fallback_color=...). Lisp: kit-image (data mime-type &key max-width-cells max-height-cells image-id filename fallback-color id). Node: write the { kind: "image", ref, mimeType } node as JSON and the bytes in images: [{ ref, mimeType, data }] of the view. A ctx.ui.custom component of a Node extension may use Pi's own Image component instead.

What the clients draw

Capability
Terminal (viewClient: terminal)
Reference web page (examples/ui-view-web)
Slotswidget-above and widget-below (at most 10 rows each), panel (at most half the terminal's rows), dialog; every other slot is not drawn at this versionall twelve slots, each in its own section of the page
dialoga titled frame centred over the screen, eight tenths of the terminal's columns and rows; its size.columns and size.rows claims are the cells inside the frame. It takes the keys when it is shown, unless the user types in the editor: then it waits as one row above the editor (<title>: F6 to enter) and leaves an unfocused notice. Escape returns the keys to the editor, and the mount stays live; with a dismiss intent, the first Escape raises it instead. Several dialogs stack, the last on top. A hidden dialog is not listeddrawn in its section of the page, like every other slot
Node kindsevery kind of Nodesevery kind of Nodes
Image nodedrawn from png, jpeg, gif and webp bytes, at most as tall as the slot's rows. In kitty and Ghostty: one Kitty transmission, then placeholder cells that scroll and erase like text. In another Kitty terminal and in iTerm2: the image in its rows. Without an image protocol (tmux, a plain terminal): half-block cells. Bytes that cannot be decoded: one line of text with the file name, the type and the sizedrawn as an image
Limits of one mount512 nodes, depth 16, 262144 snapshot bytes, 65536 text bytes, 16 mounts, 4096 intent argument bytes2048 nodes, depth 32, 4194304 snapshot bytes, 65536 text bytes, 32 mounts, 65536 intent argument bytes
titlepanels are tabs, labelled by title, or by key without one; a dialog frame carries itthe heading of the mount, and the label of a panel's tab, or key without one
Intents with nodeKeyraised by the keys and clicks of the noderaised by the keys and clicks of the node
Intents without nodeKeyraised by a binding only, apart from the whenHidden and dismiss intents of the rows below; for any other the plugin gets a notice that the terminal offers no controla button in the mount's header, labelled with the intent's verb in words and titled with its name, unless a binding, a region of a drawing or whenHidden raises the intent
bindingskeys work in a focused panel or dialog, and the named bindings are listed under it; gestures are not offered, and the plugin gets an unsupported noticekey bindings fire while the focus is in the mount, and a named one is also a button that shows its key; swipes are not offered, and the plugin gets an unsupported notice
Hidden mount with whenHiddena dim tab; Enter raises the intenta button that reads the mount's title, in the list of hidden views above the prompt
dismiss intentraised with {} by Escape in a focused dialog; a second Escape returns the keys to the editorraised with {} by Escape in a dialog or overlay mount
FocusF6 walks from the editor through the tabs and back, Escape returns to the editor; a focus record that requests it moves the keys to its nodethe focus order is the tab order, and a changed focus record moves the focus to its node
a11ynot used at this versionname, description, role, the states and the relations become ARIA attributes
Drawingsnot drawn at this version: the terminal states no drawing profiledrawn: the scene and pixels profiles, with each region of a drawing as a focusable element that takes the pointer and the keyboard

Terminal UI lists the terminal's rows and keys. Piglets describes viewClient and viewEndpoint.

PiG project documentation · MIT License