[Update] bulk update

This commit is contained in:
2026-09-17 20:45:06 +02:00
committed by Coja
parent 3ec2503f38
commit ed7e34552d
158 changed files with 3258 additions and 2419 deletions
+72 -10
View File
@@ -56,15 +56,70 @@ have a slash command to disable them for the current session without deleting.
| Extension | What it adds | Origin | Remove |
|---|---|---|---|
| `statusbar.ts` | Replaces the footer with a Claude-Code-style status line (cwd, git branch, model, context %, decode t/s, token counts) in Nerd Font glyphs; adds a streaming pulse + a ≥80%-context warning widget | **custom** | delete file → default footer returns; or `/statusbar` to toggle off for the session |
| `vim-editor.ts` | Modal (vim-like) input editor with `[I]/[N]/[V]` indicator, hjkl/word/line motions, counts, yank/paste via the kill-ring | **local fork** of pi's bundled `examples/extensions/modal-editor.ts` | delete file → default editor; or `/vim` to toggle |
| `plan-mode/` | Read-only "plan" mode (disables edit/write, restricts bash) bound to **Shift+Tab**; `/plan` toggles, `--plan` starts in it | **vendored** copy of pi's bundled `examples/extensions/plan-mode/`, rebound from upstream `Ctrl+Alt+P` | delete the folder **and** revert the `keybindings.json` `app.thinking.cycle` remap (see below) |
| `vim-toggle.ts` | `/vim` — drops the modal editor for the rest of the session, and brings it back via `ctx.reload()`. Pairs with the **`pi-vim` package** (below), which registers no command of its own | **custom** | delete file → you lose the toggle, not the editor; remove the package to drop modal editing itself |
| `plan-mode/` | Read-only "plan" mode (disables edit/write, restricts bash) bound to **Shift+Tab**; `/plan` toggles, `--plan` starts in it, `/plan-done` clears a stuck progress checklist | **vendored** copy of pi's bundled `examples/extensions/plan-mode/`, rebound from upstream `Ctrl+Alt+P` | delete the folder **and** revert the `keybindings.json` `app.thinking.cycle` remap (see below) |
| `notify.ts` | Native terminal notification (OSC 777/99, Windows toast) when the agent goes idle | **verbatim** from pi's `examples/extensions/notify.ts` | delete file |
| `questionnaire.ts` | Interactive multi-question overlay the model can call as a tool | **near-verbatim** from pi's `examples/extensions/questionnaire.ts` (one-line fix) | delete file |
| `permission-gate.ts` | Prompts before dangerous `bash` commands (blocks outright with no UI). Local list covers git history rewrites, package managers, `systemctl` and irreversible disk ops on top of upstream's `rm -rf`/`sudo`/`chmod 777` | **adapted** from pi's `examples/extensions/permission-gate.ts` | delete file |
| `protected-paths.ts` | Blocks `write`/`edit` to secrets and repo plumbing (`secrets.fish`, `auth.json`, `.env`, `.ssh/`, `.git/`, …) | **adapted** from pi's `examples/extensions/protected-paths.ts` | delete file |
| `compaction-watch.ts` | Surfaces every compaction and its `reason`; loudly flags `overflow` (recovery rather than prevention), which means `reserveTokens` is below the model's `maxTokens` | **custom** | delete file |
| `confirm-destructive.ts` | Confirms before session clear / switch / fork | **verbatim** from pi's `examples/extensions/confirm-destructive.ts` | delete file |
| `session-name.ts` | `/session-name [name]` — friendly names in the session picker instead of the first message | **verbatim** from pi's `examples/extensions/session-name.ts` | delete file |
| `todo.ts` | A `todo` tool the model calls (add/toggle/list/clear) plus `/todos` to view it; state lives in tool results, so forking rewinds it correctly. Distinct from plan-mode's checklist | **verbatim** from pi's `examples/extensions/todo.ts` | delete file (it also adds a tool schema to every request) |
> The bundled examples live at `/opt/pi-coding-agent/examples/extensions/` — that's
> where `notify`/`questionnaire`/`modal-editor`/`plan-mode` came from, and where to
> re-pull the two forks after a pi upgrade before re-applying the local edits (the
> forks' own headers document those edits).
> where `notify`/`questionnaire`/`plan-mode` came from. `plan-mode/` is now the only
> **fork** left, so it's the only one to re-pull after a pi upgrade before re-applying
> the local edits (its header documents them). `notify`/`questionnaire` carry no edits
> worth keeping — just re-copy them. The modal editor used to be a fork of
> `modal-editor.ts` too; it was replaced by the `pi-vim` package on 2026-08-05 and the
> fork deleted on 2026-08-09 — `git show c6566af^:common/.pi/agent/extensions/vim-editor.ts`
> brings it back if ever wanted.
### Modal (vim) input — the `pi-vim` package
Modal editing is **not** an extension in this tree any more; it's the npm package
[`pi-vim`](https://github.com/lajarre/pi-vim), pinned by `settings.json > packages`
and installed into the gitignored `agent/npm/`. That swap is the point: `pi update
npm:pi-vim` instead of re-pulling and re-patching a fork on every pi upgrade.
Five modes (INSERT/NORMAL/VISUAL/V-LINE/EX) with the usual motions, operators, text
objects, undo and `.` repeat; the mode renders as a word label at the editor's
bottom-right, doubling as a pending-command display (` NORMAL 3d2w_ `). `:` dispatches
real pi commands and shells out with `:!`. No search (`/`, `?`, `n`), macros or
visual-block — upstream implements none of those.
```fish
pi install npm:pi-vim
```
> ⚠️ **This pi build needs pi-vim's peer dep installed by hand.** pi ships as a
> Bun-compiled ELF with the `@earendil-works/*` packages *embedded*, not on disk.
> pi-vim's `clipboard-mirror.ts` calls `import.meta.resolve("@earendil-works/pi-coding-agent")`
> at **module top level**, so after a bare `pi install` the resolve throws and the whole
> extension fails to load with `Cannot find module '@earendil-works/pi-coding-agent'`.
> No setting avoids it — the call runs at import time. Once per host, matching
> `pi --version` exactly:
>
> ```fish
> cd ~/.pi/agent/npm
> fnm exec --using=22 -- npm install --save-exact @earendil-works/pi-coding-agent@0.83.0
> ```
>
> `pi install` deliberately doesn't pull peers (it would duplicate the runtime). Costs
> ~170 MB, and wants re-pinning after every pi upgrade — hence `--save-exact`, since a
> caret range would quietly drift off `pi --version`.
Configured under `settings.json > piVim`: `modeColors` (theme tokens, not raw ANSI),
`borderSync`/`labelSync` pinned so only the label is tinted, and
`clipboardMirror: "yank"` — upstream's default `"all"` mirrors deletes too, so every
`dd`/`x` would clobber the OS clipboard. `exCommand.copyInputToClipboard` is left
**off**: it copies the composed prompt out, so upstream only honours it from the
user-global settings file.
**Remove:** `pi remove npm:pi-vim`, and delete `agent/extensions/vim-toggle.ts` plus the
`piVim` block. `@burneikis/pi-vim` and `pi-vimmode` are alternatives that need no peer
install.
### Theme
@@ -110,11 +165,14 @@ Beyond pointing at local models, these values deviate from pi's defaults:
| Key | Value here | Stock default | Why |
|---|---|---|---|
| `compaction.reserveTokens` | `6144` | 16384 | small local windows (24k128k) — don't let the response reserve dominate a short window |
| `compaction.keepRecentTokens` | `6000` | 20000 | keep less verbatim so short windows don't thrash into repeated compaction |
| `compaction.reserveTokens` | `8192` | 16384 | small local windows (24k128k), but **≥ every model's `maxTokens`** — otherwise a turn can overflow the window before compaction even fires |
| `compaction.keepRecentTokens` | `4000` | 20000 | keep less verbatim, to pay for the larger reserve and leave room after a compaction for the next one |
| `npmCommand` | `fnm exec --using=22 -- npm` | `npm` | pin extension npm installs to Node 22 via fnm |
| `retry` / `httpIdleTimeoutMs` | long (1h provider timeout, 10m idle) | shorter | local models can be slow to first token |
| `defaultThinkingLevel` | `off` | — | most local models here are non-reasoning |
| `packages` | `["npm:pi-vim"]` | `[]` | the modal editor — see the pi-vim section above |
| `piVim` | mode colors, `clipboardMirror: "yank"`, `:` → pi bridge | — | package config, not a pi setting; ignored if the package is removed |
| `collapseChangelog` | `true` | `false` | condensed changelog after an upgrade instead of the full screen |
**Remove:** delete each key to fall back to pi's default (or drop the whole
`compaction`/`retry` block).
@@ -140,8 +198,9 @@ model.
> config. `auth.json` is **not tracked** (gitignored as of 2026-08-08): pi's interactive
> `/login` rewrites it with the **literal** key, and a tracked copy would be one stray
> `/login` away from committing a real token. Bootstrap a new host with
> `cp auth.json.example auth.json`. For bash its `.bash_profile` since it's not tracked by
> git, stow not applied.
> `cp auth.json.example auth.json`. The key itself lives in a shell file that is *not*
> tracked and *not* stowed, so it never reaches this repo — `conf.d/secrets.fish` for
> fish, `~/.bash_profile` for bash.
---
@@ -150,7 +209,10 @@ model.
- **Just the status bar:** copy `agent/extensions/statusbar.ts` into your
`~/.pi/agent/extensions/`, re-stow/restart, `/reload`. Colors follow your active
theme automatically. Needs a Nerd Font terminal for the glyphs.
- **Just vim input:** copy `agent/extensions/vim-editor.ts`, `/reload`, `/vim`.
- **Just vim input:** `pi install npm:pi-vim`, then the peer-dep install above (this
build needs it), then `/reload`. Copy the `piVim` block from `settings.json` for the
same colors and clipboard behaviour, and `agent/extensions/vim-toggle.ts` if you want
`/vim` to toggle it.
- **Just plan mode:** copy `agent/extensions/plan-mode/` **and** add the
`app.thinking.cycle` remap to your `keybindings.json` (else Shift+Tab collides).
- **Just the theme:** copy `agent/themes/catppuccin-mocha.json`, set
+22
View File
@@ -0,0 +1,22 @@
# Global agent instructions
You are a coding assistant running on small, locally-hosted models. Be precise and economical with tokens.
## Working style
- Act with tools instead of describing what you would do. Keep prose short.
- Do the task that was asked. Don't add unrequested changes, refactors, or files.
- When done, stop. A one- or two-line summary is enough; no recaps of obvious steps.
## Files & edits
- Read a file before you edit it. Never guess at file paths, function names, or APIs — verify first.
- Use the edit tool for changes. Make minimal, targeted diffs; never paste an entire file back to the user.
- Match the surrounding code's style, naming, and imports.
## Shell
- Run one command at a time and check its output before the next.
- Prefer `rg` and `fd` for search. Use read-only commands when exploring.
- Never run destructive or system-changing commands (`rm -rf`, `sudo`, package installs, force-push) unless explicitly asked.
## Honesty
- If you're unsure, say so and check rather than inventing an answer.
- Report failures plainly with the actual error; don't claim success you didn't verify.
@@ -0,0 +1,60 @@
/**
* Compaction Watch
*
* Compaction is otherwise silent, which is why "compacting fails a lot" took code
* reading and arithmetic to diagnose rather than a glance at a log. This makes it
* visible, and specifically names the failure mode that was breaking it here before
* 2026-08-16.
*
* pi reports a `reason` on every compaction:
* "manual" - you ran /compact
* "threshold" - the healthy path: contextTokens passed contextWindow - reserveTokens
* "overflow" - the window was ALREADY full; this is recovery, not prevention
*
* An "overflow" compaction means the turn blew past contextWindow before the threshold
* could fire, which happens whenever `compaction.reserveTokens` is smaller than the
* model's `maxTokens`. pi then gets one recovery attempt, summarizing from an
* already-overflowed context — and when that does not fit either, the session dies with
* "Context overflow recovery failed after one compact-and-retry attempt".
*
* So: seeing "threshold" is fine. Seeing "overflow" means the settings are wrong for the
* model in use, and this says so at the moment it happens instead of leaving you to
* infer it later. See CLAUDE.md > Compaction tuning.
*
* Note there is no event for a *failed* auto-compaction — `onError` exists only on the
* manual `ctx.compact()` call — so catching the overflow entry is the earliest reliable
* warning available.
*/
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
export default function (pi: ExtensionAPI) {
let overflowCount = 0;
pi.on("session_before_compact", async (event, ctx) => {
if (!ctx.hasUI) return undefined;
if (event.reason === "overflow") {
overflowCount++;
ctx.ui.notify(
`Compacting in OVERFLOW recovery (#${overflowCount}) — the context window was already ` +
`full before compaction could fire. Raise compaction.reserveTokens above this model's ` +
`maxTokens, or cap maxTokens in models.json. See CLAUDE.md > Compaction tuning.`,
"warning",
);
}
// Never alter the compaction itself — observe only.
return undefined;
});
pi.on("session_compact", async (event, ctx) => {
if (!ctx.hasUI) return;
const reason = event.reason ?? "unknown";
const retrying = event.willRetry ? ", retrying the aborted turn" : "";
const level = reason === "overflow" ? "warning" : "info";
ctx.ui.notify(`Compacted (${reason}${retrying})`, level);
});
}
@@ -0,0 +1,59 @@
/**
* Confirm Destructive Actions Extension
*
* Prompts for confirmation before destructive session actions (clear, switch, branch).
* Demonstrates how to cancel session events using the before_* events.
*/
import type { ExtensionAPI, SessionBeforeSwitchEvent, SessionMessageEntry } from "@earendil-works/pi-coding-agent";
export default function (pi: ExtensionAPI) {
pi.on("session_before_switch", async (event: SessionBeforeSwitchEvent, ctx) => {
if (!ctx.hasUI) return;
if (event.reason === "new") {
const confirmed = await ctx.ui.confirm(
"Clear session?",
"This will delete all messages in the current session.",
);
if (!confirmed) {
ctx.ui.notify("Clear cancelled", "info");
return { cancel: true };
}
return;
}
// reason === "resume" - check if there are unsaved changes (messages since last assistant response)
const entries = ctx.sessionManager.getEntries();
const hasUnsavedWork = entries.some(
(e): e is SessionMessageEntry => e.type === "message" && e.message.role === "user",
);
if (hasUnsavedWork) {
const confirmed = await ctx.ui.confirm(
"Switch session?",
"You have messages in the current session. Switch anyway?",
);
if (!confirmed) {
ctx.ui.notify("Switch cancelled", "info");
return { cancel: true };
}
}
});
pi.on("session_before_fork", async (event, ctx) => {
if (!ctx.hasUI) return;
const choice = await ctx.ui.select(`Fork from entry ${event.entryId.slice(0, 8)}?`, [
"Yes, create fork",
"No, stay in current session",
]);
if (choice !== "Yes, create fork") {
ctx.ui.notify("Fork cancelled", "info");
return { cancel: true };
}
});
}
@@ -0,0 +1,69 @@
/**
* Permission Gate Extension
*
* Prompts for confirmation before running potentially dangerous bash commands.
*
* Adapted from pi's bundled `examples/extensions/permission-gate.ts`. Upstream checks
* three patterns (rm -rf, sudo, chmod/chown 777); the list below is extended to cover
* the rules AGENTS.md only *asks* for. That distinction is the whole point of running
* this: AGENTS.md is a prompt, and the small local models this config targets follow
* prompts unreliably. This is the enforcement half — the same trick plan-mode already
* uses when it disables edit/write outright.
*
* In the TUI a match prompts (so "Yes" still gets you through); with no UI it blocks.
*/
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
export default function (pi: ExtensionAPI) {
const dangerousPatterns = [
// --- upstream ---
/\brm\s+(-rf?|--recursive)/i,
/\bsudo\b/i,
/\b(chmod|chown)\b.*777/i,
// --- LOCAL: git history is the user's to write, never the agent's ---
// The standing rule is that commits and pushes are made by hand, after review.
/\bgit\s+(commit|push|revert)\b/i,
/\bgit\s+reset\s+--hard\b/i,
/\bgit\s+(rebase|cherry-pick)\b/i,
/\bgit\s+clean\s+-[a-z]*[fd]/i,
/\bgit\s+stash\s+(drop|clear|pop)\b/i,
/--force\b|--force-with-lease\b/i,
// --- LOCAL: system-changing commands AGENTS.md rules out ---
/\b(pacman|yay|paru)\s+-[A-Za-z]*[SRU]/,
/\b(npm|pnpm|yarn)\s+(install|i|add|remove|uninstall)\b/i,
/\bpip3?\s+(install|uninstall)\b/i,
/\bcargo\s+(install|uninstall)\b/i,
/\bsystemctl\s+(start|stop|restart|enable|disable|mask)\b/i,
// --- LOCAL: irreversible disk / process operations ---
/\bmkfs\b|\bdd\s+if=|\bshred\b|\bwipefs\b/i,
/\b(reboot|shutdown|poweroff|halt)\b/i,
/\b(killall|pkill)\b/i,
/>\s*\/dev\/(sd|nvme|vd)/i,
];
pi.on("tool_call", async (event, ctx) => {
if (event.toolName !== "bash") return undefined;
const command = event.input.command as string;
const matched = dangerousPatterns.find((p) => p.test(command));
if (matched) {
if (!ctx.hasUI) {
// Non-interactive (`pi -p`): nothing can confirm, so refuse.
return { block: true, reason: "Dangerous command blocked (no UI for confirmation)" };
}
const choice = await ctx.ui.select(`⚠️ Dangerous command:\n\n ${command}\n\nAllow?`, ["Yes", "No"]);
if (choice !== "Yes") {
return { block: true, reason: "Blocked by user" };
}
}
return undefined;
});
}
@@ -142,6 +142,25 @@ export default function planModeExtension(pi: ExtensionAPI): void {
handler: async (_args, ctx) => togglePlanMode(ctx),
});
// LOCAL EDIT: the checklist widget only tears itself down once every step is
// marked complete, which needs the model to emit a [DONE:n] tag per step. When
// one is missed the widget sticks around after the work is finished, so give
// the user a way out that doesn't involve toggling plan mode on and off again.
pi.registerCommand("plan-done", {
description: "Clear a stuck plan checklist (stops execution tracking)",
handler: async (_args, ctx) => {
if (!executionMode && todoItems.length === 0) {
ctx.ui.notify("No plan is being tracked.");
return;
}
executionMode = false;
todoItems = [];
updateStatus(ctx);
persistState();
ctx.ui.notify("Plan tracking cleared.");
},
});
pi.registerCommand("todos", {
description: "Show current plan todo list",
handler: async (_args, ctx) => {
+10 -3
View File
@@ -151,9 +151,16 @@ export function extractTodoItems(message: string): TodoItem[] {
export function extractDoneSteps(message: string): number[] {
const steps: number[] = [];
for (const match of message.matchAll(/\[DONE:(\d+)\]/gi)) {
const step = Number(match[1]);
if (Number.isFinite(step)) steps.push(step);
// LOCAL EDIT: upstream matched only the literal `[DONE:3]`. Small local models
// drift on it, and one missed tag pins the plan widget on screen forever, so
// also accept `[DONE 3]`, `[DONE-3]` and comma lists `[DONE:1,2]`. The brackets
// stay required on purpose: a bare "done 3" in prose must not mark a step.
for (const match of message.matchAll(/\[\s*DONE\s*[:\-=]?\s*([\d,\s]+?)\s*\]/gi)) {
for (const part of match[1].split(/[,\s]+/)) {
if (part === "") continue;
const step = Number(part);
if (Number.isFinite(step)) steps.push(step);
}
}
return steps;
}
@@ -0,0 +1,58 @@
/**
* Protected Paths Extension
*
* Blocks write and edit operations to protected paths.
*
* Adapted from pi's bundled `examples/extensions/protected-paths.ts`. Upstream ships a
* three-entry demo list (.env, .git/, node_modules/); the list below names the files
* that actually matter in this dotfiles tree — the ones holding secrets, and the git
* metadata the agent has no business rewriting.
*
* Scope, so this isn't over-trusted: it guards against the *model* calling write/edit.
* It cannot stop pi's own `/login`, which rewrites auth.json with the literal key —
* that is why auth.json is gitignored and auth.json.example is the tracked copy.
*/
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
export default function (pi: ExtensionAPI) {
const protectedPaths = [
// Secrets. `secrets.fish` holds $DUSKADIY_API_KEY; auth.json is pi's own
// credential map and must keep $VAR references rather than literals.
"secrets.fish",
"auth.json",
".env",
"fish_variables",
// Credentials outside the repo.
".ssh/",
".gnupg/",
".aws/",
".netrc",
// Repo plumbing and vendored trees — never hand-edited.
".git/",
"node_modules/",
];
pi.on("tool_call", async (event, ctx) => {
if (event.toolName !== "write" && event.toolName !== "edit") {
return undefined;
}
const path = event.input.path as string;
// Substring match, like upstream: cheap, and these names are distinctive enough.
// Note `auth.json.example` is intentionally caught too — it is a tracked file
// whose whole job is to contain no secret, so an agent rewrite is worth a look.
const isProtected = protectedPaths.some((p) => path.includes(p));
if (isProtected) {
if (ctx.hasUI) {
ctx.ui.notify(`Blocked write to protected path: ${path}`, "warning");
}
return { block: true, reason: `Path "${path}" is protected` };
}
return undefined;
});
}
@@ -0,0 +1,27 @@
/**
* Session naming example.
*
* Shows setSessionName/getSessionName to give sessions friendly names
* that appear in the session selector instead of the first message.
*
* Usage: /session-name [name] - set or show session name
*/
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
export default function (pi: ExtensionAPI) {
pi.registerCommand("session-name", {
description: "Set or show session name (usage: /session-name [new name])",
handler: async (args, ctx) => {
const name = args.trim();
if (name) {
pi.setSessionName(name);
ctx.ui.notify(`Session named: ${name}`, "info");
} else {
const current = pi.getSessionName();
ctx.ui.notify(current ? `Session: ${current}` : "No session name set", "info");
}
},
});
}
+297
View File
@@ -0,0 +1,297 @@
/**
* Todo Extension - Demonstrates state management via session entries
*
* This extension:
* - Registers a `todo` tool for the LLM to manage todos
* - Registers a `/todos` command for users to view the list
*
* State is stored in tool result details (not external files), which allows
* proper branching - when you branch, the todo state is automatically
* correct for that point in history.
*/
import { StringEnum } from "@earendil-works/pi-ai";
import type { ExtensionAPI, ExtensionContext, Theme } from "@earendil-works/pi-coding-agent";
import { matchesKey, Text, truncateToWidth } from "@earendil-works/pi-tui";
import { Type } from "typebox";
interface Todo {
id: number;
text: string;
done: boolean;
}
interface TodoDetails {
action: "list" | "add" | "toggle" | "clear";
todos: Todo[];
nextId: number;
error?: string;
}
const TodoParams = Type.Object({
action: StringEnum(["list", "add", "toggle", "clear"] as const),
text: Type.Optional(Type.String({ description: "Todo text (for add)" })),
id: Type.Optional(Type.Number({ description: "Todo ID (for toggle)" })),
});
/**
* UI component for the /todos command
*/
class TodoListComponent {
private todos: Todo[];
private theme: Theme;
private onClose: () => void;
private cachedWidth?: number;
private cachedLines?: string[];
constructor(todos: Todo[], theme: Theme, onClose: () => void) {
this.todos = todos;
this.theme = theme;
this.onClose = onClose;
}
handleInput(data: string): void {
if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) {
this.onClose();
}
}
render(width: number): string[] {
if (this.cachedLines && this.cachedWidth === width) {
return this.cachedLines;
}
const lines: string[] = [];
const th = this.theme;
lines.push("");
const title = th.fg("accent", " Todos ");
const headerLine =
th.fg("borderMuted", "─".repeat(3)) + title + th.fg("borderMuted", "─".repeat(Math.max(0, width - 10)));
lines.push(truncateToWidth(headerLine, width));
lines.push("");
if (this.todos.length === 0) {
lines.push(truncateToWidth(` ${th.fg("dim", "No todos yet. Ask the agent to add some!")}`, width));
} else {
const done = this.todos.filter((t) => t.done).length;
const total = this.todos.length;
lines.push(truncateToWidth(` ${th.fg("muted", `${done}/${total} completed`)}`, width));
lines.push("");
for (const todo of this.todos) {
const check = todo.done ? th.fg("success", "✓") : th.fg("dim", "○");
const id = th.fg("accent", `#${todo.id}`);
const text = todo.done ? th.fg("dim", todo.text) : th.fg("text", todo.text);
lines.push(truncateToWidth(` ${check} ${id} ${text}`, width));
}
}
lines.push("");
lines.push(truncateToWidth(` ${th.fg("dim", "Press Escape to close")}`, width));
lines.push("");
this.cachedWidth = width;
this.cachedLines = lines;
return lines;
}
invalidate(): void {
this.cachedWidth = undefined;
this.cachedLines = undefined;
}
}
export default function (pi: ExtensionAPI) {
// In-memory state (reconstructed from session on load)
let todos: Todo[] = [];
let nextId = 1;
/**
* Reconstruct state from session entries.
* Scans tool results for this tool and applies them in order.
*/
const reconstructState = (ctx: ExtensionContext) => {
todos = [];
nextId = 1;
for (const entry of ctx.sessionManager.getBranch()) {
if (entry.type !== "message") continue;
const msg = entry.message;
if (msg.role !== "toolResult" || msg.toolName !== "todo") continue;
const details = msg.details as TodoDetails | undefined;
if (details) {
todos = details.todos;
nextId = details.nextId;
}
}
};
// Reconstruct state on session events
pi.on("session_start", async (_event, ctx) => reconstructState(ctx));
pi.on("session_tree", async (_event, ctx) => reconstructState(ctx));
// Register the todo tool for the LLM
pi.registerTool({
name: "todo",
label: "Todo",
description: "Manage a todo list. Actions: list, add (text), toggle (id), clear",
parameters: TodoParams,
async execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
switch (params.action) {
case "list":
return {
content: [
{
type: "text",
text: todos.length
? todos.map((t) => `[${t.done ? "x" : " "}] #${t.id}: ${t.text}`).join("\n")
: "No todos",
},
],
details: { action: "list", todos: [...todos], nextId } as TodoDetails,
};
case "add": {
if (!params.text) {
return {
content: [{ type: "text", text: "Error: text required for add" }],
details: { action: "add", todos: [...todos], nextId, error: "text required" } as TodoDetails,
};
}
const newTodo: Todo = { id: nextId++, text: params.text, done: false };
todos.push(newTodo);
return {
content: [{ type: "text", text: `Added todo #${newTodo.id}: ${newTodo.text}` }],
details: { action: "add", todos: [...todos], nextId } as TodoDetails,
};
}
case "toggle": {
if (params.id === undefined) {
return {
content: [{ type: "text", text: "Error: id required for toggle" }],
details: { action: "toggle", todos: [...todos], nextId, error: "id required" } as TodoDetails,
};
}
const todo = todos.find((t) => t.id === params.id);
if (!todo) {
return {
content: [{ type: "text", text: `Todo #${params.id} not found` }],
details: {
action: "toggle",
todos: [...todos],
nextId,
error: `#${params.id} not found`,
} as TodoDetails,
};
}
todo.done = !todo.done;
return {
content: [{ type: "text", text: `Todo #${todo.id} ${todo.done ? "completed" : "uncompleted"}` }],
details: { action: "toggle", todos: [...todos], nextId } as TodoDetails,
};
}
case "clear": {
const count = todos.length;
todos = [];
nextId = 1;
return {
content: [{ type: "text", text: `Cleared ${count} todos` }],
details: { action: "clear", todos: [], nextId: 1 } as TodoDetails,
};
}
default:
return {
content: [{ type: "text", text: `Unknown action: ${params.action}` }],
details: {
action: "list",
todos: [...todos],
nextId,
error: `unknown action: ${params.action}`,
} as TodoDetails,
};
}
},
renderCall(args, theme, _context) {
let text = theme.fg("toolTitle", theme.bold("todo ")) + theme.fg("muted", args.action);
if (args.text) text += ` ${theme.fg("dim", `"${args.text}"`)}`;
if (args.id !== undefined) text += ` ${theme.fg("accent", `#${args.id}`)}`;
return new Text(text, 0, 0);
},
renderResult(result, { expanded }, theme, _context) {
const details = result.details as TodoDetails | undefined;
if (!details) {
const text = result.content[0];
return new Text(text?.type === "text" ? text.text : "", 0, 0);
}
if (details.error) {
return new Text(theme.fg("error", `Error: ${details.error}`), 0, 0);
}
const todoList = details.todos;
switch (details.action) {
case "list": {
if (todoList.length === 0) {
return new Text(theme.fg("dim", "No todos"), 0, 0);
}
let listText = theme.fg("muted", `${todoList.length} todo(s):`);
const display = expanded ? todoList : todoList.slice(0, 5);
for (const t of display) {
const check = t.done ? theme.fg("success", "✓") : theme.fg("dim", "○");
const itemText = t.done ? theme.fg("dim", t.text) : theme.fg("muted", t.text);
listText += `\n${check} ${theme.fg("accent", `#${t.id}`)} ${itemText}`;
}
if (!expanded && todoList.length > 5) {
listText += `\n${theme.fg("dim", `... ${todoList.length - 5} more`)}`;
}
return new Text(listText, 0, 0);
}
case "add": {
const added = todoList[todoList.length - 1];
return new Text(
theme.fg("success", "✓ Added ") +
theme.fg("accent", `#${added.id}`) +
" " +
theme.fg("muted", added.text),
0,
0,
);
}
case "toggle": {
const text = result.content[0];
const msg = text?.type === "text" ? text.text : "";
return new Text(theme.fg("success", "✓ ") + theme.fg("muted", msg), 0, 0);
}
case "clear":
return new Text(theme.fg("success", "✓ ") + theme.fg("muted", "Cleared all todos"), 0, 0);
}
},
});
// Register the /todos command for users
pi.registerCommand("todos", {
description: "Show all todos on the current branch",
handler: async (_args, ctx) => {
if (ctx.mode !== "tui") {
ctx.ui.notify("/todos requires interactive mode", "error");
return;
}
await ctx.ui.custom<void>((_tui, theme, _kb, done) => {
return new TodoListComponent(todos, theme, () => done());
});
},
});
}
+26 -6
View File
@@ -52,7 +52,7 @@
"reasoning": false,
"input": ["text", "image"],
"contextWindow": 24576,
"maxTokens": 8192,
"maxTokens": 4096,
"cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0 }
},
{
@@ -62,7 +62,7 @@
"compat": { "thinkingFormat": "qwen-chat-template" },
"input": ["text", "image"],
"contextWindow": 24576,
"maxTokens": 8192,
"maxTokens": 4096,
"cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0 }
},
{
@@ -75,6 +75,16 @@
"maxTokens": 8192,
"cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0 }
},
{
"id": "Qwen3.8-27B-UD-IQ3_XXS",
"name": "Qwen3.8 27B · 24k · vision — hybrid reasoner",
"reasoning": true,
"compat": { "thinkingFormat": "qwen-chat-template" },
"input": ["text", "image"],
"contextWindow": 24576,
"maxTokens": 8192,
"cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0 }
},
{
"id": "GLM-4.7-Flash-UD-Q4_K_XL",
"name": "GLM-4.7 Flash · 24k — quality coder",
@@ -82,7 +92,7 @@
"compat": { "thinkingFormat": "qwen-chat-template" },
"input": ["text"],
"contextWindow": 24576,
"maxTokens": 8192,
"maxTokens": 4096,
"cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0 }
},
{
@@ -157,7 +167,7 @@
"reasoning": false,
"input": ["text", "image"],
"contextWindow": 24576,
"maxTokens": 8192,
"maxTokens": 4096,
"cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0 }
},
{
@@ -167,7 +177,7 @@
"compat": { "thinkingFormat": "qwen-chat-template" },
"input": ["text", "image"],
"contextWindow": 24576,
"maxTokens": 8192,
"maxTokens": 4096,
"cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0 }
},
{
@@ -180,6 +190,16 @@
"maxTokens": 8192,
"cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0 }
},
{
"id": "Qwen3.8-27B-UD-IQ3_XXS",
"name": "Qwen3.8 27B · 24k · vision — hybrid reasoner",
"reasoning": true,
"compat": { "thinkingFormat": "qwen-chat-template" },
"input": ["text", "image"],
"contextWindow": 24576,
"maxTokens": 8192,
"cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0 }
},
{
"id": "GLM-4.7-Flash-UD-Q4_K_XL",
"name": "GLM-4.7 Flash · 24k — quality coder",
@@ -187,7 +207,7 @@
"compat": { "thinkingFormat": "qwen-chat-template" },
"input": ["text"],
"contextWindow": 24576,
"maxTokens": 8192,
"maxTokens": 4096,
"cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0 }
},
{
+3 -2
View File
@@ -4,6 +4,7 @@
"defaultThinkingLevel": "off",
"theme": "catppuccin-mocha",
"quietStartup": false,
"collapseChangelog": true,
"defaultProjectTrust": "ask",
"enableInstallTelemetry": false,
"enabledModels": [
@@ -12,8 +13,8 @@
],
"compaction": {
"enabled": true,
"reserveTokens": 6144,
"keepRecentTokens": 6000
"reserveTokens": 8192,
"keepRecentTokens": 4000
},
"retry": {
"enabled": true,