# Extension footer segments

[Project overview](../README.md) · [Configuration](./configuration.md#english) · [Implementation and compatibility](./implementation.md#english)

Other Pi extensions can use `pi.events` to inject custom text directly into either main footer row—including the editor borders when `inlineFooter` is enabled—without adding an extra status row.

## Events

| Event | Payload | Purpose |
| --- | --- | --- |
| `open-tui:footer:set` | `{ lifecycle, key, position, text, compactText?, order?, priority? }` | Insert or completely replace the segment for `key` |
| `open-tui:footer:remove` | `{ lifecycle, key }` | Remove a segment (no-op if `key` doesn't exist) |
| `open-tui:footer:query` | `undefined` | Ask `pi-open-tui` for its current availability and lifecycle |
| `open-tui:footer:state` | `{ available: true, lifecycle: string }` or `{ available: false }` | Broadcast availability changes and answer queries |

**Payload rules**

- Choose a nonempty, extension-prefixed `key` (for example, `system-memory:usage`) to avoid collisions.
- `text` and optional `compactText` are strings. Supported ANSI color codes are preserved, while terminal control commands and line breaks are stripped. Empty or style-only strings are treated as invisible.
- `open-tui:footer:set` replaces the entire entry, so omitting an optional field resets it to its default.
- Malformed payloads, unknown anchors, and stale lifecycles are silently ignored; extra unrecognized fields are tolerated. Event names and payloads are unversioned, so future additions stay backwards-compatible.

## Placement and width

Provide a `position` using one of these three forms:

| `position` | Meaning |
| --- | --- |
| `{ row: 1, side: "left", edge: "end" }` | Explicit region: `row` (`1` or `2`), `side` (`"left"` or `"right"`), and optional `edge` (`"start"` or `"end"`, default `"end"`) |
| `{ before: "git" }` | Before a built-in anchor |
| `{ after: "cost" }` | After a built-in anchor |

In inline mode, rows `1` and `2` map to the top and bottom editor borders. Explicit regions stay on their specified side, while relative positions travel with their anchor. All built-in anchors remain valid even when their built-in field is hidden or empty:

| Mode | Row 1 left | Row 1 right | Row 2 left | Row 2 right |
| --- | --- | --- | --- | --- |
| Regular | `cwd`, `hostname`, `sessionName`, `git`, `runtime`, `timer` | `context` | `model` | `tokens`, `cost` |
| Inline | `sessionName`, `git` | `cwd`, `hostname`, `runtime`, `timer`, `context` | `model` | `tokens`, `cost` |

Here, `tokens` represents the full token statistics group. Region `start` entries render before the region's built-in anchors, and `end` entries render after them; relative entries render before or after their target anchor. Within the same placement slot, segments sort by ascending `order` (default `0`), then by standard string order on `key` (independent of extension load order or locale).

**Priority and shrinking**

- `priority` defaults to `-1`; higher values survive longer when horizontal space is tight. Both `order` and `priority` must be finite numbers.
- Built-in priorities are `cwd: 4`, `hostname/timer: 3`, `sessionName: 2`, `git: 1`, `runtime/context: 0` on row 1, and `tokens: 2`, `cost: 1`, `model: 0` on row 2.
- Both sides share the row's available width. Under space pressure, shorter nonempty `compactText` variants are swapped in by ascending priority before truncating or dropping lower-priority segments (ties follow display order). Rows without visible contributions keep their normal built-in layout.

## Lifecycle and visibility

Follow this lifecycle pattern to stay cleanly in sync with `pi-open-tui`:

1. **Subscribe early, query on start**: Register your `open-tui:footer:state` listener in the extension factory. Save the context in `session_start`, then emit `open-tui:footer:query`. Ignore announcements that arrive before initialization or repeat the current lifecycle.
2. **Publish against the active lifecycle**: Whenever a new available `lifecycle` arrives, publish your current segment using that identifier. `lifecycle` identifies the current footer mount (not a protocol version); disabling `pi-open-tui`, replacing its footer, or ending the session invalidates it and clears all contributions.
3. **Guard async work**: Capture `lifecycle` before starting an async request and discard stale results if it changes. If your data also depends on the active provider/model, check that identity and a request sequence number too. Cancel pending timers or requests on `session_shutdown`, and never publish through a Pi instance whose runtime has been replaced.

**Visibility and fallback**

`footerSegments.extensionSegments` defaults to `true` and controls visibility only—hidden segments still receive updates, and availability and lifecycle remain active. Separately, `footerSegments.extensionStatuses` controls standard `ctx.ui.setStatus()` rows. When `pi-open-tui` is unavailable, you can fall back to `ctx.ui.setStatus()` and clear that fallback row as soon as a footer lifecycle becomes available.

## System memory example

Save the snippet below as `system-memory.ts` and run `pi -e ./system-memory.ts` alongside `pi-open-tui`. It polls system memory every 5 seconds, places the reading right after `cost`, falls back to a regular status row when `pi-open-tui` isn't active, and cleans up on shutdown.

```typescript
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
import { freemem, totalmem } from "node:os";

export default function (pi: ExtensionAPI) {
	const key = "system-memory:usage";
	let ctx: ExtensionContext | undefined;
	let lifecycle: string | undefined;
	let timer: ReturnType<typeof setInterval> | undefined;

	const publish = () => {
		if (!ctx) return;
		const total = totalmem();
		const used = total - freemem();
		const text = `RAM ${(used / 2 ** 30).toFixed(1)}/${(total / 2 ** 30).toFixed(1)} GiB`;
		if (lifecycle === undefined) {
			ctx.ui.setStatus(key, text);
			return;
		}
		ctx.ui.setStatus(key, undefined);
		pi.events.emit("open-tui:footer:set", {
			lifecycle,
			key,
			position: { after: "cost" },
			text,
			compactText: `RAM ${Math.round(used / total * 100)}%`,
		});
	};

	pi.events.on("open-tui:footer:state", (data) => {
		if (!ctx || data === null || typeof data !== "object" || !("available" in data)) return;
		if (data.available === true && "lifecycle" in data
			&& typeof data.lifecycle === "string" && data.lifecycle.length > 0) {
			if (lifecycle === data.lifecycle) return;
			lifecycle = data.lifecycle;
		} else if (data.available === false) {
			if (lifecycle === undefined) return;
			lifecycle = undefined;
		} else {
			return;
		}
		publish();
	});

	pi.on("session_start", (_event, nextCtx) => {
		if (!nextCtx.hasUI || nextCtx.mode !== "tui") return;
		ctx = nextCtx;
		publish();
		pi.events.emit("open-tui:footer:query", undefined);
		timer = setInterval(publish, 5_000);
		timer.unref();
	});

	pi.on("session_shutdown", () => {
		if (timer) clearInterval(timer);
		timer = undefined;
		const previousCtx = ctx;
		const previousLifecycle = lifecycle;
		ctx = undefined;
		lifecycle = undefined;
		if (previousLifecycle !== undefined) {
			pi.events.emit("open-tui:footer:remove", { key, lifecycle: previousLifecycle });
		}
		previousCtx?.ui.setStatus(key, undefined);
	});
}
```
