Skip to main content

03. Contracts for CLI plugins

Philosophy​

A contract is a syscall ABI: versioned (semver), changed only through an explicit procedure, documented as a catalog. A plugin written against contract version N keeps working on N+1.

Replacement contract — accepted target​

Decision: 2026-11-10. The only fixed product mechanism is tiling: window-tree ownership, geometry, workspaces, focus routing, and drag/resize. All other UI and agent behavior must be replaceable without editing the host. This decision supersedes earlier rules that made the composer and system dialogs permanently host-owned. Existing exceptions below describe the implementation during the migration, not the target architecture.

ComponentRequired replacement surface
Message editor, completions and non-tiling shortcutsRendering, input handling, draft state, submission/steering intents and teardown
Approval, question and settings dialogsRendering, editing, validation, explicit results, cancellation and pending-request cleanup
Conversation, tools, status controls and window decorationContent, interaction and presentation within compositor-owned rectangles
Commands, providers, auth and model selectionDefault and extension implementations use the same public service paths
Tool definitions and executionExplicit replacement of schemas/handlers; rewritten calls reach execution and permission evaluation consistently
Agent execution, recovery and context managementReplaceable orchestration strategies, rather than observers around fixed algorithms
Session and other state servicesReplaceable persistence/control implementations with explicit lifecycle contracts

Implementation requirements:

  • Defaults and extensions use the same selection and lifecycle mechanisms. Selection must identify the active provider and report missing or conflicting providers; duplicate names must not silently discard a requested replacement.
  • A visual override must not retain obsolete default hit areas or key handling. Components return semantic actions/results; the tiling manager retains control of window geometry and focus routing.
  • Private editor/form state belongs to its selected implementation and does not become a broadcast event payload. Replacing a component does not require exposing passwords to unrelated render hooks or recording drafts in logs.
  • Reload, disable, session switching and cancellation must dispose old instances, resolve or cancel pending interactions, and remove stale contributions.
  • Replacement preserves the negotiated contract and the user's configured policy. A new dialog must return an explicit decision through the normal permission path; changing its appearance is not implicit authorization.

Acceptance requires actual external extensions, not only constructor injection in tests: replace an editor and a dialog (including their input behavior), a built-in tool definition, an auth flow, an agent strategy and a session service; then verify unload/reload, cancellation and resumption with the same tiling manager. Tests must also prove that rewritten tool arguments reach execution, rendering cannot mutate agent state, and an unresponsive async hook cannot hold the chain indefinitely. Until those checks exist and pass, describe the system as extensible at selected seams rather than universally replaceable.

1. Event catalog​

A machine-readable schema plus a human-readable document (docs/events.md). Every event: a name in the plugin.foo:bar format (namespaces instead of flat strings), a version, a payload schema, response forms, a default budget. Legacy names exist only as aliases in the schema — no multiplying handlers.

Base domains:

EventWhenResponse forms
session.start / session.reload / session.shutdownSession lifecycle; reload is a state-recovery point—
tool.callTool executionresult, deny
tool.checkPre-execution checkallow, ask, deny
agent.spawnLaunching a child agentagentId, deny
prompt.composeSystem prompt assemblysections[{id, text, scope}]
ui.renderPane rendering— (writing plugin state during render is forbidden)

2. Hook contract​

  • Onion chain: a handler receives the event and next(); it may call next(rewrittenEvent). Whoever doesn't call next() is the terminal.
  • Order: explicit priority, not registration order (otherwise determinism breaks when the plugin set changes).
  • Budgets: an own-time limit per handler; the clock pauses while awaiting downstream work. Ordinary middleware failures continue downstream without replaying a continuation that already started. Failed explicitly selected providers report errors. Asynchronous deadlines revoke host capabilities; synchronous trusted JavaScript cannot be forcibly preempted.

3. Trust model — three classes​

ClassExecutionPurpose
trustedNode.js, full accessprovider plugins, first-party
sandboxedExplicit language host required; TS modules currently refusedgenerated code through a replaceable sandbox provider
render-onlyno state mutationsthemes, layouts, visualizations

The class is declared in the manifest and enforced by the runtime.

4. Plugin manifest​

plugin.json: name, version, declared events, trust class, capabilities (model | auth | workflow | tool | render), status-bar contribution. Loader-only fields include main (entry file, default hooks.ts → index.ts → index.js → index.mjs), tier (chain tier, default user), mcpServers (validated stdio declarations/config references) and resources (additional package-local runtime files retained in bundles). A package can combine hooks/services, UI, tools, skills and MCP; skill-only/MCP-only packages need no dummy hook entry. See composition and ownership.

{
"name": "safety",
"version": "0.1.0",
"trust": "trusted",
"tier": "append",
"main": "./index.ts"
}

The hooks module exports a named hooks object: event name → (event, $) => response | undefined.

Search dirs, in precedence order (first hit wins name collisions): ./plugins, ./.agent-compositor/plugins, $XDG_CONFIG_HOME/agent-compositor/plugins. One corrupt manifest never blocks the rest; sandboxed plugin modules are refused until an explicit language host is linked. Monty is selected for generated Python, separately from trusted TypeScript module loading.

Replaceable service providers declare provides in their manifest. The app's serviceProviders maps canonical event names to a selected plugin, while guard hooks remain in the chain. disabledPlugins removes a plugin and its tools. For example, callix provides service.project.query through the native CLI's JSON graph. Trusted providers may declare bounded hookTimeouts for slow operations; cancellation is exposed through $.signal. User ui.press and ui.change chains, including nested service calls, use their own hook budgets and plugin lifetimes, independently of the foreground agent's cancellation signal. Plugin unload still aborts them; agent-turn hooks retain foreground cancellation.

The default $.exec.run service owns a foreground process group. It kills owned descendants on cancellation, timeout, plugin unload and foreground process exit, and waits for process closure before settling. The default timeout is 30 seconds; captured stdout and stderr share a 1 MiB bound. Timeout/output overflow returns a nonzero result with a diagnostic; cancellation and spawn failures reject. Use the background-shell API for managed asynchronous jobs. This is process ownership, not OS containment. Replacement execution services must preserve these semantics. ToolContext.request propagates the tool's signal to host services without serializing it into catalog payloads. SDK callers may likewise pass an optional third AbortSignal argument to HooksHost.emit. The dispatcher also accepts an optional third signal on Runtime.emit. Caller cancellation settles the pending hook wait, including an asynchronous hook that ignores its signal; it revokes that invocation instead of treating cancellation as a plugin fault and falling through to a resolver. Late next() calls cannot start another effect. Plugin removal and host closure cancel their active emissions and release dispatcher timers. Independent user operations and retained background capabilities keep their existing ownership boundaries until their own owner or host closes. Already-started external effects are not rolled back, and synchronous JavaScript is not forcibly preempted.

Catalog 0.21 adds service.extension.control and service.marketplace.control for the TUI management lane. They accept the corresponding control tool's arguments plus an optional cancellation signal and return {value: data} or {deny: reason}. Extension data is the inventory for list, {updates} for checks, or the operation result (name/changed/removed, scope, optional version, reloadRequired, unchanged); a busy deferred file operation returns {name,scope,queued:true}. Marketplace data is a registration list or a refresh/ removal result. Guard hooks can deny operations; serviceProviders and a provider manifest's provides can replace either service. Model-facing control tools keep their ordinary permission, journal and tool-turn path. UI management does not create model messages or tool-result messages.

Reload = reverse teardown (hooks + per-plugin state) + cache-busted re-import. State does not survive a reload — session.reload with the new composition is the documented recovery point.

Installing/enabling a plugin → a session.start event with its composition (udev analogy: the module saw the device). Disabling → session.reload without it; the plugin's in-memory state is recreated.

5. Model provider contract​

A minimal model plugin: name, endpoint/interface, context limits, message format. Override is by name: a provider registers my-model, and the core can call it from workflows by that name. Prompt optimizations for their own model are an optional layer of the same plugin.

6. Authorization contract​

Capability auth: a login() method. The base distribution ships form login; a corporate provider brings a plugin with their own SSO/OAuth — the core doesn't change.

7. Workflow contract​

A workflow = data + a script in the sandbox (class sandboxed):

  • nouns — domain entities (extending the language via a name table, with ownership);
  • $-API — spawn, emit, state, ui: every call goes through the event bus;
  • journal — an append-only log of steps: resume after a crash without losing progress;
  • limits — a shared tokenBudget, concurrency (1–64), stagger delays against thundering herd.

8. Core ↔ renderer protocol​

JSONL, semver. Messages:

DirectionMessagePurpose
core → rendererdeclareSurface declarations (pane, site, status bar)
core → rendererrenderFull or incremental diff of a pane
renderer → coreinputInput → the focused pane
bothfocus, invalidateFocus transfer, damaged-region marking

The renderer never calls the core outside the protocol. hello/hello-ack negotiate version and shared surfaces at session start.

Text input data may include paste: true when the renderer can distinguish pasted text from typing. The Ink renderer preserves bracketed paste through this optional marker, including single-character pastes. Editors and search fields can insert the text normally; window-mode shortcuts ignore marked pastes. Unmarked text remains compatible with existing renderers.

The acceptance test is behavioral: two renderers on the same event log must produce identical user-visible output. @agent-compositor/renderer-ink is the reference terminal implementation (Ink 8, grid state machine + React view); a web/desktop renderer can replace it without touching the core.

Native presentation profile​

Protocol 0.7 keeps the 0.6 cell messages compatible and adds an explicitly negotiated native presentation profile. Both peers advertise native-presentation-v1 and native-input-v1 in hello.capabilities.elements. An ordinary grid peer never receives native messages. The configured OpenTUI application uses this profile over an asynchronous JSONL-decoded message stream, including when the host and renderer share a process.

DirectionMessagePurpose
host → renderernative-stateRevisioned conversation, window, surface, layout, appearance and public-view data
renderer → hostnative-inputAn identified input addressed to an opaque current port or a declared host control
host → renderernative-receiptAccepted or rejected input admission, with optional controller ticket or navigation decision
host → renderernative-mediaSeparate bounded RGBA frames and cell dimensions for subscribed composer media

When both peers advertise native-steer-v1, a session may advertise steer as an optional method. A peer sends the steer operation only for an advertised session. Legacy peers never receive the new method or operation. submit and steer receipts reflect the Core admission result, which can arrive asynchronously after journal writes. The broker deduplicates in-flight input IDs; an unaccepted input remains editable in the frontend. Layout and other independent inputs remain available while a receipt is pending.

The optional native-pending-work-v1 capability adds a pending conversation state for admitted work waiting before a model turn. It lets the frontend show queued work and offer Stop while the Core is idle. Legacy peers receive the original strict snapshot without that field.

The optional native-session-restoring-v1 capability adds restoring while an interactive session switch is still starting. Peers without it retain the original strict snapshot; rejected input must remain recoverable.

The optional composer-media-status-v1 element adds selected-producer presentation (label, alt, hasImage) to native-media and an expanded flag to media subscription input. Both peers must advertise it before either new field is sent. A peer without the element keeps the original strict packet shape. This does not change the mandatory native profile or protocol version. Presentation labels and alt text are bounded to 512 characters; raster limits remain unchanged. Metadata is revisioned and revoked with the same connection epoch as pixels.

An absent presentation is unknown, as with a legacy peer, rather than proof of a text-only producer. Only explicit hasImage:false describes that case. A normal unsubscribe drops cached RGBA; bounded presentation can remain for a later subscription on the same connection. Epoch and connection revocation clear both; renegotiating the optional capability clears presentation metadata. Hidden frontend components also release their pixel snapshot before reopening.

A compact subscription receives presentation updates without RGBA frames and reports one visible status row with zero image columns. Any expanded subscriber keeps the selected producer's full image visibility; hidden subscriptions do not keep its clock running. Removing or unloading a replacement producer reports the newly selected producer's visibility before it resumes. Presentation is private frontend data, like raster frames, not a model message or public hook property. Without the optional element, a legacy host may still send RGBA to a compact frontend; the old protocol has no expanded/compact subscription distinction.

The schemas describe data only. The host retains Core objects, plugin functions, controller factories, private checkpoints and leases. A renderer is a trusted private presentation endpoint: visible selected-editor text and private request frames may cross this connection. They are not added to public ui.render props, model context or broadcast events. This profile does not expose a network server or grant an external peer access.

Each connection has an epoch, each state has a monotonic revision, and each source identity has an opaque port. Replacing a source revokes its old port even when its visible window ID stays the same. Ordinary snapshot updates retain renderer-local widgets and subscriptions. A Core generation change also fences queued native input. The host remains authoritative for visibility, focus, navigation policy, declared actions, request IDs and permissions. For a current selected lease, key/text input is relative to its current view; an admitted same-lease mouse completion cannot discard the following paste just because it advanced the view revision. Field changes additionally require the current field ID. Mouse and declared-action inputs still require the exact painted revision. Future revisions, retired leases, replaced ports and input outside the focused normal-mode pane remain rejected. Main replacement revokes its descendant requests; independent managed request sources retain their own Core lifetime and port until they settle or their producer closes.

Input IDs are monotonic within a connection. The broker retains the last 512 receipts: an identical duplicate returns its original receipt, a changed payload with that ID is rejected, and older IDs outside the cache cannot run again. Acceptance means frontend admission; it does not claim that a tool, model turn or asynchronous controller task has finished. Controller tickets are acknowledged by later frame inputRevision values. The client maps those host tickets to local FIFO field changes so an intermediate frame cannot overwrite newer typing. Later keyboard/paste input waits for admission, not model completion. A rejected submission leaves its draft available; an accepted receipt cannot clear a newer draft or a replacement editor.

Native host snapshots intentionally omit the built-in textarea's local draft, caret and undo stack. Native replay evidence therefore includes duplex protocol ordering and the real terminal input stream; host snapshots alone cannot replay all local editing. The unchanged grid profile retains the same-log acceptance rule above, including full/diff, flush, cursor, styling and raster fallback.

The OpenTUI module exports runOpenTuiRenderer (also named runOpenTuiWireRenderer) for the grid source/send contract and runOpenTuiNativeRenderer for this negotiated application profile. The direct port-based runConversationPrototype remains a development fixture. Renderers clean up on EOF, abort, source failure or explicit stop without waiting forever for an uncooperative source iterator. The public agent SessionPane emits schema-valid grid messages; its declarePane(columns, rows) dimension hints must be integers between 1 and 10000 inclusive.

The OpenTUI grid client can advertise Raster when native image output is selected; SIXEL also requires pixel geometry. tmux and screen use the grid fallback until image passthrough is implemented, including when AGENT_GRAPHICS explicitly requests a protocol. Explicit Kitty selection still permits the protocol before capability probing completes.

Renderers own: cell-grid semantics (full/diff ops, scroll, cursor), style mapping to their toolkit, input key mapping. Renderers never own: focus policy for panes they didn't draw, event ordering, plugin state.

Cell-grid text and titles are literal display data. Both grid renderers paint control, unpaired-surrogate, bidirectional-control and line/paragraph-separator characters as visible \uXXXX text, including in titles. Raw grid state is preserved; cell text never becomes a terminal escape or an extra layout instruction. This shared display rule replaces the older Ink-only interpretation of control characters and prevents the two frontends from applying different text policies.

Implementation status​

Current core composition and strategy replacements are documented in core-customization.md. Catalog 0.18 adds these services; the older milestone list below is historical. Explicit within-tier priorities, awaited middleware continuations, bounded asynchronous hooks and atomic plugin registration are now implemented. Selected editor/dialog/placement/history controllers and full session repository replacement are described in ui-controllers.md, including privacy, lifecycle and limits.

The design originated in the kimi-code fork; the active core in this repository was subsequently written independently. The historical package milestones below are complemented by the current architecture map:

  • events — versioned catalog, generated docs + JSON schema, CI-frozen shapes;
  • runtime — onion-chain dispatcher with thread/own/yield budgets, fail-operational faults, chain trace (--plugin-trace);
  • hooks — mods-style (event, $) layer; service-backed $ methods are service.* events; private UI capabilities bypass broadcasts; per-plugin state; workspace confinement for fs/exec;
  • loader — disk discovery, manifest validation, tiered registration, hot reload with reverse teardown;
  • protocol — JSONL wire codec + handshake with version negotiation;
  • renderer-ink — reference terminal renderer (grid state machine + Ink view); runs the full contour disk → runtime → protocol → Ink with input routed back;
  • agent — reference agent loop: prompt.submit → turn.start → service.model.complete → tool.call → tool.check → service.exec.run/service.fs.* → turn.complete. Builtin tools ride the $ API events, so core operations are interceptable like anything else. Providers: OpenAI-compatible streaming (fetch, no SDK) + scripted provider for tests. SessionPane streams assistant text to the wire as grid diff ops.

Open items:

  1. Explicit priority instead of registration order — implemented with manifest priority within each tier;
  2. Structured core→renderer delta channel (today streaming renders as grid diffs; a web/desktop renderer may want a protocol minor with typed deltas);
  3. Porting the kimi-code agent core — superseded by 06-core-blueprint.md: the core is written greenfield as a best-of harvest over 8 local reference codebases; the fork is one reference among them.