klui-code 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,251 @@
1
+ // Subagents, like OpenCode's task tool and Codex's spawn_agent: the model hands a self-contained job
2
+ // to a fresh Klui with its own context window. Each one is a child `klui --mode json` process, so
3
+ // several can run at once. Each runs on the same model and reasoning level as the main agent
4
+ // unless the task asks for a different model. "explore" agents only read;
5
+ // "general" agents can also edit files and run commands. A background agent returns right away and
6
+ // reports back as a message when it's done, so the main agent can keep working meanwhile.
7
+ import { spawn } from "node:child_process";
8
+ import { join } from "node:path";
9
+ import { StringEnum } from "@earendil-works/pi-ai";
10
+ import { getMarkdownTheme } from "@earendil-works/pi-coding-agent";
11
+ import { Container, Markdown, Text } from "@earendil-works/pi-tui";
12
+ import { Type } from "typebox";
13
+ import { PACKAGE_DIR, PROVIDER } from "../paths.js";
14
+ import { PERMISSIONS_ENV } from "./permissions.js";
15
+ import { state } from "./state.js";
16
+ /** Set in a subagent's environment: subagents don't start subagents of their own. */
17
+ export const SUBAGENT_ENV = "KLUI_SUBAGENT";
18
+ export const AGENT_MESSAGE = "klui-agent";
19
+ const WIDGET = "klui-agents";
20
+ const KINDS = {
21
+ explore: {
22
+ tools: "read,grep,find,ls",
23
+ prompt: "You are a Klui subagent exploring a codebase for another agent. You can only read: never try to change files. Search broadly, read what matters, and finish with a compact report: the answer, the exact file paths and line numbers, and short code excerpts where they help. The other agent can't see your work, only that report.",
24
+ },
25
+ general: {
26
+ tools: "read,bash,edit,write,grep,find,ls",
27
+ prompt: "You are a Klui subagent doing one task for another agent. Do the task completely, check your work, and finish with a short report: what you changed (file paths), how you verified it, and anything left undone. The other agent can't see your work, only that report.",
28
+ },
29
+ };
30
+ export function registerAgents(pi) {
31
+ const running = new Map();
32
+ let nextId = 1;
33
+ let ui;
34
+ const showRunning = () => {
35
+ if (!ui)
36
+ return;
37
+ const list = [...running.values()];
38
+ ui.setWidget(WIDGET, list.length === 0
39
+ ? undefined
40
+ : [` ◌ ${list.length === 1 ? "1 background agent" : `${list.length} background agents`} working · ${list.map((r) => `${r.details.kind} #${r.details.background}`).join(", ")}`]);
41
+ };
42
+ pi.registerTool({
43
+ name: "subagent",
44
+ label: "Subagent",
45
+ description: [
46
+ "Hand a self-contained task to a fresh subagent with its own context window, and get its final report back.",
47
+ 'kind "explore" (default) can only read and search: use it for broad codebase questions so your own context stays small.',
48
+ 'kind "general" can also edit files and run commands: use it for an independent piece of work.',
49
+ "The subagent can't see this conversation, so put everything it needs in the task.",
50
+ "Call it several times in one turn to run independent tasks in parallel.",
51
+ "Set background to true to keep working while it runs; its report arrives later as a message.",
52
+ `It runs on your model and reasoning level. Set model only when the user asks for a different one: ${state.config.models.map(modelHint).join("; ")}.`,
53
+ ].join(" "),
54
+ promptSnippet: "subagent: delegate a self-contained task to a fresh agent (explore = read-only, general = can edit); several can run in parallel",
55
+ promptGuidelines: [
56
+ "Use subagent for wide searches or independent sub-tasks, not for a single quick lookup you can do yourself.",
57
+ ],
58
+ parameters: Type.Object({
59
+ task: Type.String({ description: "Everything the subagent needs: the goal, relevant paths and what to report back" }),
60
+ kind: Type.Optional(StringEnum(["explore", "general"], { description: "explore (read-only, default) or general (can edit and run commands)" })),
61
+ model: Type.Optional(Type.String({ description: "Only when the user asks for a different model: its id or name. Leave it out to use your own model" })),
62
+ background: Type.Optional(Type.Boolean({ description: "Return right away and deliver the report as a message later" })),
63
+ }),
64
+ executionMode: "parallel",
65
+ async execute(_toolCallId, params, signal, onUpdate, ctx) {
66
+ const kind = params.kind ?? "explore";
67
+ // Your own model, exactly, unless the task names another event model.
68
+ const own = ctx.model?.provider === PROVIDER ? state.config.models.find((m) => m.id === ctx.model.id) : undefined;
69
+ const model = params.model ? resolveModel(params.model) : (own ?? resolveModel(state.config.defaultModel));
70
+ const run = { model: `${PROVIDER}/${model.id}`, thinking: pi.getThinkingLevel() };
71
+ const details = { kind, task: params.task, model: model.name, tools: 0, elapsedMs: 0 };
72
+ const startedAt = Date.now();
73
+ if (params.background) {
74
+ ui = ctx.hasUI ? ctx.ui : undefined;
75
+ const id = nextId++;
76
+ const controller = new AbortController();
77
+ details.background = id;
78
+ running.set(id, { controller, details });
79
+ showRunning();
80
+ void runAgent(ctx.cwd, kind, run, params.task, controller.signal, (p) => Object.assign(details, p)).then((outcome) => {
81
+ running.delete(id);
82
+ showRunning();
83
+ if (controller.signal.aborted)
84
+ return;
85
+ const done = { ...details, tools: outcome.tools, progress: undefined, error: outcome.error, elapsedMs: Date.now() - startedAt };
86
+ pi.sendMessage({
87
+ customType: AGENT_MESSAGE,
88
+ content: `Background agent #${id} (${kind}) ${outcome.error ? `failed: ${outcome.error}` : "finished"}.\n\n${outcome.output}`,
89
+ display: true,
90
+ details: done,
91
+ }, { triggerTurn: true, deliverAs: "followUp" });
92
+ });
93
+ return {
94
+ content: [{ type: "text", text: `Started background agent #${id}. Its report will arrive as a message when it finishes; carry on meanwhile.` }],
95
+ details,
96
+ };
97
+ }
98
+ let lastUpdate = 0;
99
+ const outcome = await runAgent(ctx.cwd, kind, run, params.task, signal, (p) => {
100
+ Object.assign(details, p, { elapsedMs: Date.now() - startedAt });
101
+ if (Date.now() - lastUpdate < 200)
102
+ return;
103
+ lastUpdate = Date.now();
104
+ onUpdate?.({ content: [{ type: "text", text: "" }], details: { ...details } });
105
+ });
106
+ if (signal?.aborted)
107
+ throw new Error("Subagent stopped");
108
+ if (outcome.error && !outcome.output)
109
+ throw new Error(outcome.error);
110
+ return {
111
+ content: [{ type: "text", text: outcome.output || "(the subagent finished without a report)" }],
112
+ details: { ...details, tools: outcome.tools, progress: undefined, error: outcome.error, elapsedMs: Date.now() - startedAt },
113
+ };
114
+ },
115
+ renderCall(args, theme) {
116
+ const kind = args.kind ?? "explore";
117
+ return new Text(`${theme.bold(theme.fg("toolTitle", "agent"))} ${theme.fg("accent", kind)}\n${theme.fg("muted", args.task ?? "")}`, 0, 0);
118
+ },
119
+ renderResult(result, _options, theme) {
120
+ const text = result.content.find((c) => c.type === "text")?.text ?? "";
121
+ return text.trim() ? new Markdown(text, 0, 1, getMarkdownTheme()) : new Text(theme.fg("dim", "no report"), 0, 0);
122
+ },
123
+ });
124
+ pi.registerMessageRenderer(AGENT_MESSAGE, (message, options, theme) => {
125
+ const d = message.details;
126
+ if (!d)
127
+ return undefined;
128
+ const dot = d.error ? theme.fg("error", "⏺") : theme.fg("success", "⏺");
129
+ const meta = [d.error ?? `${d.tools} tool${d.tools === 1 ? "" : "s"}`, `${Math.round(d.elapsedMs / 1000)}s`].join(" · ");
130
+ const pad = " ".repeat(options.outputPad);
131
+ const head = `${pad}${dot} ${theme.bold("Agent")}${theme.fg("muted", "(")}${d.kind} #${d.background}: ${clip(firstLine(d.task), 48)}${theme.fg("muted", ")")}`;
132
+ const row = new Container();
133
+ row.addChild(new Text(`${head}\n${pad} ${theme.fg("dim", "⎿")} Reported back ${theme.fg("dim", `· ${meta}`)}`, 0, 0));
134
+ if (options.expanded) {
135
+ const report = typeof message.content === "string" ? message.content : "";
136
+ row.addChild(new Markdown(report.replace(/^[^\n]*\n\n/, ""), options.outputPad + 2, 1, getMarkdownTheme()));
137
+ }
138
+ return row;
139
+ });
140
+ pi.on("session_shutdown", async () => {
141
+ for (const { controller } of running.values())
142
+ controller.abort();
143
+ running.clear();
144
+ });
145
+ }
146
+ function modelHint(m) {
147
+ return `${m.id} (${m.name}${m.tagline ? `, ${m.tagline}` : ""})`;
148
+ }
149
+ /** The event model asked for, by id or name. */
150
+ function resolveModel(requested) {
151
+ const models = state.config.models;
152
+ const want = requested.trim().toLowerCase();
153
+ const found = models.find((m) => m.id.toLowerCase() === want) ??
154
+ models.find((m) => m.name.toLowerCase() === want) ??
155
+ models.find((m) => m.id.toLowerCase().endsWith(`@${want}`)) ??
156
+ models.find((m) => m.name.toLowerCase().includes(want));
157
+ if (!found)
158
+ throw new Error(`Unknown model "${requested}". Pick one of: ${models.map((m) => m.id).join(", ")}`);
159
+ return found;
160
+ }
161
+ /** Run one subagent to completion, reporting its tool calls as it goes. */
162
+ function runAgent(cwd, kind, run, task, signal, onProgress) {
163
+ const args = [
164
+ join(PACKAGE_DIR, "bin", "klui.js"),
165
+ "--mode",
166
+ "json",
167
+ "-p",
168
+ "--no-session",
169
+ "--model",
170
+ run.model,
171
+ "--thinking",
172
+ run.thinking,
173
+ "--tools",
174
+ KINDS[kind].tools,
175
+ "--append-system-prompt",
176
+ KINDS[kind].prompt,
177
+ `Task: ${task}`,
178
+ ];
179
+ return new Promise((resolve) => {
180
+ const child = spawn(process.execPath, args, { cwd, env: { ...process.env, [SUBAGENT_ENV]: "1", [PERMISSIONS_ENV]: state.mode }, stdio: ["ignore", "pipe", "pipe"] });
181
+ let tools = 0;
182
+ let output = "";
183
+ let error;
184
+ let stderr = "";
185
+ let buffer = "";
186
+ const onLine = (line) => {
187
+ let event;
188
+ try {
189
+ event = JSON.parse(line);
190
+ }
191
+ catch {
192
+ return;
193
+ }
194
+ if (event.type === "tool_execution_start") {
195
+ tools++;
196
+ onProgress({ tools, progress: activity(event.toolName ?? "tool", event.args) });
197
+ }
198
+ else if (event.type === "message_end" && event.message?.role === "assistant") {
199
+ const text = (event.message.content ?? [])
200
+ .filter((c) => c.type === "text")
201
+ .map((c) => c.text ?? "")
202
+ .join("")
203
+ .trim();
204
+ if (text)
205
+ output = text;
206
+ error = event.message.stopReason === "error" ? (event.message.errorMessage ?? "the model returned an error") : undefined;
207
+ onProgress({ tools, progress: "thinking" });
208
+ }
209
+ };
210
+ child.stdout.setEncoding("utf8");
211
+ child.stdout.on("data", (chunk) => {
212
+ buffer += chunk;
213
+ let newline = buffer.indexOf("\n");
214
+ while (newline !== -1) {
215
+ onLine(buffer.slice(0, newline).replace(/\r$/, ""));
216
+ buffer = buffer.slice(newline + 1);
217
+ newline = buffer.indexOf("\n");
218
+ }
219
+ });
220
+ child.stderr.setEncoding("utf8");
221
+ child.stderr.on("data", (chunk) => {
222
+ stderr = (stderr + chunk).slice(-2000);
223
+ });
224
+ const stop = () => child.kill("SIGTERM");
225
+ signal?.addEventListener("abort", stop, { once: true });
226
+ child.on("error", (e) => {
227
+ signal?.removeEventListener("abort", stop);
228
+ resolve({ output, tools, error: e.message });
229
+ });
230
+ child.on("close", (code) => {
231
+ signal?.removeEventListener("abort", stop);
232
+ if (buffer.trim())
233
+ onLine(buffer);
234
+ if (code !== 0 && !error && !signal?.aborted)
235
+ error = stderr.trim().split("\n").pop() || `exited with code ${code}`;
236
+ resolve({ output, tools, error });
237
+ });
238
+ });
239
+ }
240
+ function activity(toolName, args) {
241
+ const a = args ?? {};
242
+ const arg = [a.path, a.pattern, a.command].find((v) => typeof v === "string");
243
+ return arg ? `${toolName} ${firstLine(arg).slice(0, 40)}` : toolName;
244
+ }
245
+ function clip(text, max) {
246
+ return text.length > max ? `${text.slice(0, max - 1)}…` : text;
247
+ }
248
+ function firstLine(text) {
249
+ const [first = "", ...rest] = text.trim().split("\n");
250
+ return rest.length > 0 ? `${first} …` : first;
251
+ }
@@ -0,0 +1,110 @@
1
+ // When Klui is about to finish a run in which it changed files, it checks them (see ../checks.ts)
2
+ // and, if its changes broke something, hands the problems back so it can fix them first. Only
3
+ // problems the run introduced count: each TypeScript project is checked once before its first
4
+ // change, and errors that were already there are left alone. At most two rounds per run, and a
5
+ // report the model has already seen isn't sent again.
6
+ import { Container, Text } from "@earendil-works/pi-tui";
7
+ import { existsSync } from "node:fs";
8
+ import { isAbsolute, relative } from "node:path";
9
+ import { checkFile, formatProblem, newProblems, tsProjects, typecheck } from "../checks.js";
10
+ import { piModule } from "../pi-patches.js";
11
+ // The path edit and write actually use: Pi expands "~/", drops a leading "@" and so on.
12
+ const { resolveToCwd } = await piModule("./core/tools/path-utils.js");
13
+ export const CHECKS_MESSAGE = "klui-checks";
14
+ const MAX_ROUNDS = 2;
15
+ const MAX_LINES = 20;
16
+ const PREVIEW = 3;
17
+ export function registerChecks(pi, onChecking = () => { }) {
18
+ let touched = new Set();
19
+ let baselines = new Map();
20
+ let dirty = false;
21
+ let rounds = 0;
22
+ let lastReport = "";
23
+ // A run lasts until Pi settles: the continuation a report asks for starts another agent loop
24
+ // (and fires agent_start) but keeps the same rounds and baselines.
25
+ pi.on("agent_settled", async () => {
26
+ touched = new Set();
27
+ baselines = new Map();
28
+ dirty = false;
29
+ rounds = 0;
30
+ lastReport = "";
31
+ });
32
+ // Each project's errors before the run first changes it. Registered after the permission
33
+ // prompt, so a declined edit never waits on this.
34
+ pi.on("tool_call", async (event, ctx) => {
35
+ if (event.toolName !== "edit" && event.toolName !== "write")
36
+ return;
37
+ for (const config of tsProjects(resolveToCwd(String(event.input.path ?? ""), ctx.cwd))) {
38
+ if (!baselines.has(config))
39
+ baselines.set(config, typecheck(config));
40
+ await baselines.get(config);
41
+ }
42
+ });
43
+ pi.on("tool_result", async (event, ctx) => {
44
+ if ((event.toolName !== "edit" && event.toolName !== "write") || event.isError)
45
+ return;
46
+ touched.add(resolveToCwd(String(event.input.path ?? ""), ctx.cwd));
47
+ dirty = true;
48
+ });
49
+ pi.on("agent_before_settle", async (event, ctx) => {
50
+ if (event.outcome !== "completed" || !dirty)
51
+ return;
52
+ dirty = false;
53
+ onChecking(true);
54
+ let problems;
55
+ try {
56
+ problems = await findProblems([...touched].filter((f) => existsSync(f)), baselines);
57
+ }
58
+ finally {
59
+ onChecking(false);
60
+ }
61
+ const lines = problems.map((p) => formatProblem(p, (file) => shortPath(file, ctx.cwd)));
62
+ const report = lines.join("\n");
63
+ if (!report || report === lastReport || rounds >= MAX_ROUNDS)
64
+ return;
65
+ rounds++;
66
+ lastReport = report;
67
+ const shown = lines.slice(0, MAX_LINES);
68
+ const more = lines.length - shown.length;
69
+ const content = [
70
+ "Klui ran the project's checks on the files you changed. Your changes left these problems:",
71
+ ...shown.map((l) => `- ${l}`),
72
+ ...(more ? [`(and ${more} more)`] : []),
73
+ "Fix them before you finish. If one is intended, say why instead.",
74
+ ].join("\n");
75
+ return {
76
+ entries: [{ type: "custom_message", customType: CHECKS_MESSAGE, content, display: true, details: { lines: shown, more } }],
77
+ continue: true,
78
+ };
79
+ });
80
+ pi.registerMessageRenderer(CHECKS_MESSAGE, (message, options, theme) => {
81
+ const d = message.details;
82
+ if (!d)
83
+ return undefined;
84
+ const pad = " ".repeat(options.outputPad);
85
+ const total = d.lines.length + d.more;
86
+ const shown = options.expanded ? d.lines : d.lines.slice(0, PREVIEW);
87
+ const hidden = total - shown.length;
88
+ const rows = [
89
+ `${pad}${theme.fg("warning", "⏺")} ${theme.bold("Checks")}`,
90
+ `${pad} ${theme.fg("dim", "⎿")} ${total} problem${total === 1 ? "" : "s"} to fix`,
91
+ ...shown.map((l) => `${pad} ${theme.fg("muted", l)}`),
92
+ ...(hidden ? [`${pad} ${theme.fg("dim", `… +${hidden} more`)}`] : []),
93
+ ];
94
+ const row = new Container();
95
+ row.addChild(new Text(rows.join("\n"), 0, 0));
96
+ return row;
97
+ });
98
+ }
99
+ /** New type errors in the touched files' projects, plus syntax errors in the files themselves. */
100
+ async function findProblems(files, baselines) {
101
+ const projects = [...new Set(files.flatMap(tsProjects))].map(async (config) => {
102
+ const after = await typecheck(config);
103
+ return after ? newProblems((await baselines.get(config)) ?? [], after) : [];
104
+ });
105
+ return (await Promise.all([...projects, ...files.map(checkFile)])).flat();
106
+ }
107
+ function shortPath(path, cwd) {
108
+ const rel = relative(cwd, path);
109
+ return rel && !rel.startsWith("..") && !isAbsolute(rel) ? rel : path;
110
+ }
@@ -0,0 +1,183 @@
1
+ // /klui: an about card, plus quick pickers for the event models and Klui themes. /sessions: the
2
+ // earlier chats, to pick one up again. /usage: tokens used in the last 24 hours and overall.
3
+ import { SessionManager, SessionSelectorComponent } from "@earendil-works/pi-coding-agent";
4
+ import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
5
+ import { bigKlui } from "../mascot.js";
6
+ import { PROVIDER, VERSION } from "../paths.js";
7
+ import { showThinkingMenu } from "../pi-patches.js";
8
+ import { renderPixels } from "../pixels.js";
9
+ import { update } from "../update.js";
10
+ import { readUsage } from "../usage.js";
11
+ import { creditsLabel, modelLabel, state } from "./state.js";
12
+ const THEMES = [
13
+ { value: "klui-dark", label: "klui-dark", description: "sky blue on midnight" },
14
+ { value: "klui-light", label: "klui-light", description: "crisp blue on white" },
15
+ { value: "klui-arcade", label: "klui-arcade", description: "neon, for late-night hacking" },
16
+ ];
17
+ const SUBCOMMANDS = [
18
+ { value: "model", label: "model", description: "pick one of the event models" },
19
+ { value: "theme", label: "theme", description: "switch Klui themes" },
20
+ { value: "credits", label: "credits", description: "check the credits left on your key" },
21
+ { value: "retry", label: "retry", description: "reconnect to Klui after a network hiccup" },
22
+ ];
23
+ export function registerCommands(pi, actions) {
24
+ pi.registerCommand("klui", {
25
+ description: "About Klui, models, themes and credits",
26
+ getArgumentCompletions: (prefix) => SUBCOMMANDS.filter((s) => s.value.startsWith(prefix.trim())),
27
+ handler: async (args, ctx) => {
28
+ const sub = args.trim().toLowerCase();
29
+ if (sub === "model" || sub === "models")
30
+ return pickModel(pi, ctx);
31
+ if (sub === "theme" || sub === "themes")
32
+ return pickTheme(ctx);
33
+ if (sub === "retry")
34
+ return actions.reconnect(ctx);
35
+ if (sub === "credits") {
36
+ await actions.refreshCredits();
37
+ ctx.ui.notify(creditsLabel() ? `Klui credits: ${creditsLabel()}` : "Couldn't read your credits right now.", "info");
38
+ return;
39
+ }
40
+ if (sub && sub !== "about") {
41
+ ctx.ui.notify(`Unknown /klui ${sub}. Try: ${SUBCOMMANDS.map((s) => s.value).join(", ")}`, "warning");
42
+ return;
43
+ }
44
+ if (ctx.mode !== "tui") {
45
+ ctx.ui.notify(`klui v${VERSION} · ${state.config.event.name} · ${modelLabel()}`, "info");
46
+ return;
47
+ }
48
+ void actions.refreshCredits();
49
+ await ctx.ui.custom((_tui, theme, _keys, done) => aboutCard(theme, done), {
50
+ overlay: true,
51
+ overlayOptions: { anchor: "center", width: 74 },
52
+ });
53
+ },
54
+ });
55
+ pi.registerCommand("usage", {
56
+ description: "Tokens used in the last 24 hours and overall, subagents included",
57
+ handler: async (_args, ctx) => {
58
+ ctx.ui.notify(usageReport(readUsage()), "info");
59
+ },
60
+ });
61
+ pi.registerCommand("update", {
62
+ description: "Update Klui Code to the latest version",
63
+ handler: async (_args, ctx) => {
64
+ ctx.ui.notify("Checking for updates…", "info");
65
+ const result = await update((to) => ctx.ui.notify(`Updating Klui Code ${VERSION} → ${to}…`, "info"));
66
+ if (result.status === "current")
67
+ ctx.ui.notify(`Klui Code ${result.version} is the latest version.`, "info");
68
+ else if (result.status === "updated")
69
+ ctx.ui.notify(`Klui Code ${result.to} is installed. Restart klui to use it.`, "info");
70
+ else
71
+ ctx.ui.notify(result.message, "error");
72
+ },
73
+ });
74
+ pi.registerCommand("sessions", {
75
+ description: "Pick up one of your earlier chats",
76
+ handler: async (_args, ctx) => {
77
+ if (ctx.mode !== "tui")
78
+ return;
79
+ const sessions = ctx.sessionManager;
80
+ const path = await ctx.ui.custom((tui, _theme, keybindings, done) => {
81
+ const selector = new SessionSelectorComponent((onProgress, signal) => SessionManager.list(sessions.getCwd(), sessions.getSessionDir(), onProgress, signal), (onProgress, signal) => SessionManager.listAll(onProgress, signal), (picked) => done(picked), () => done(undefined), () => {
82
+ done(undefined);
83
+ ctx.shutdown();
84
+ }, () => tui.requestRender(), {
85
+ renameSession: async (file, name) => {
86
+ const next = (name ?? "").trim();
87
+ if (next)
88
+ SessionManager.open(file).appendSessionInfo(next);
89
+ },
90
+ showRenameHint: true,
91
+ keybindings,
92
+ }, sessions.getSessionFile());
93
+ return selector;
94
+ });
95
+ if (path && path !== sessions.getSessionFile())
96
+ await ctx.switchSession(path);
97
+ },
98
+ });
99
+ }
100
+ async function pickModel(pi, ctx) {
101
+ const models = state.config.models;
102
+ const labels = models.map((m) => `${m.name}${m.tagline ? ` — ${m.tagline}` : ""}${m.id === state.config.defaultModel ? " (default)" : ""}`);
103
+ const choice = await ctx.ui.select("Pick a model", labels);
104
+ if (choice === undefined)
105
+ return;
106
+ const picked = models[labels.indexOf(choice)];
107
+ const model = picked && ctx.modelRegistry.find(PROVIDER, picked.id);
108
+ if (!model || !(await pi.setModel(model))) {
109
+ ctx.ui.notify("That model isn't available right now.", "error");
110
+ return;
111
+ }
112
+ ctx.ui.notify(`Switched to ${picked.name}`, "info");
113
+ showThinkingMenu();
114
+ }
115
+ async function pickTheme(ctx) {
116
+ const labels = THEMES.map((t) => `${t.label} — ${t.description}`);
117
+ const choice = await ctx.ui.select("Pick a theme", labels);
118
+ if (choice === undefined)
119
+ return;
120
+ const theme = THEMES[labels.indexOf(choice)];
121
+ const result = ctx.ui.setTheme(theme.value);
122
+ if (!result.success)
123
+ ctx.ui.notify(result.error ?? "Couldn't switch themes.", "error");
124
+ }
125
+ function aboutCard(theme, done) {
126
+ const border = (s) => theme.fg("borderAccent", s);
127
+ return {
128
+ render(width) {
129
+ const inner = width - 4;
130
+ const event = state.config.event;
131
+ if (inner < 44) {
132
+ // Too narrow for Klui and the details side by side: just the details.
133
+ return [
134
+ theme.bold(theme.fg("accent", "klui")) + theme.fg("dim", ` v${VERSION}`),
135
+ theme.fg("text", modelLabel()),
136
+ creditsLabel() ? theme.fg("success", creditsLabel()) : theme.fg("muted", event.name),
137
+ theme.fg("dim", "any key to close"),
138
+ ].map((line) => truncateToWidth(line, width));
139
+ }
140
+ const mascot = renderPixels(bigKlui("happy"), theme.getColorMode());
141
+ const credits = creditsLabel();
142
+ const lines = [
143
+ "",
144
+ theme.bold(theme.fg("accent", "klui")) + theme.fg("dim", ` v${VERSION}`),
145
+ theme.fg("muted", event.name),
146
+ "",
147
+ `${theme.fg("dim", "model ")}${theme.fg("text", modelLabel())}`,
148
+ `${theme.fg("dim", "credits ")}${credits ? theme.fg("success", credits) : theme.fg("muted", "on the house")}`,
149
+ `${theme.fg("dim", "network ")}${theme.fg("text", "AntSeed")}`,
150
+ event.url ? `${theme.fg("dim", "more ")}${theme.fg("accent", event.url)}` : "",
151
+ "",
152
+ ];
153
+ const body = mascot.map((row, i) => `${row} ${lines[i] ?? ""}`);
154
+ body.push("", theme.fg("dim", "/klui model · /klui theme · /klui credits any key to close"));
155
+ const pad = (line) => {
156
+ const fitted = truncateToWidth(line, inner, "");
157
+ return `${border("│")} ${fitted}${" ".repeat(Math.max(0, inner - visibleWidth(fitted)))} ${border("│")}`;
158
+ };
159
+ return [border(`╭${"─".repeat(inner + 2)}╮`), ...body.map(pad), border(`╰${"─".repeat(inner + 2)}╯`)];
160
+ },
161
+ handleInput() {
162
+ done();
163
+ },
164
+ invalidate() { },
165
+ };
166
+ }
167
+ /** Three rows: the header, total tokens (736.8K) and messages, last 24 hours next to lifetime. */
168
+ export function usageReport({ day, lifetime }) {
169
+ const line = (label, a, b) => `${label.padEnd(14)}${a.padStart(10)} ${b.padStart(10)}`;
170
+ return [
171
+ line("Usage", "Last 24h", "Lifetime"),
172
+ line("Total tokens", compact(day.total), compact(lifetime.total)),
173
+ line("Messages", day.requests.toLocaleString("en-US"), lifetime.requests.toLocaleString("en-US")),
174
+ ].join("\n");
175
+ }
176
+ /** 950, 736.8K, 1.2M, 3.4B: one decimal at most. */
177
+ function compact(value) {
178
+ for (const [size, unit] of [[1e9, "B"], [1e6, "M"], [1e3, "K"]]) {
179
+ if (value >= size)
180
+ return `${(Math.floor((value / size) * 10) / 10).toFixed(1)}${unit}`;
181
+ }
182
+ return String(value);
183
+ }
@@ -0,0 +1,60 @@
1
+ // A one-line footer under the editor, like Claude Code's: the permission mode on the left; the
2
+ // model, context used and event credits on the right.
3
+ import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
4
+ import { PROVIDER } from "../paths.js";
5
+ import { modeLabel } from "./permissions.js";
6
+ import { creditsLabel, modelLabel, state, subscribe } from "./state.js";
7
+ export function createFooter(pi, ctx, tui, theme, footerData) {
8
+ const unsubscribe = subscribe(() => tui.requestRender());
9
+ return {
10
+ render(width) {
11
+ const level = pi.getThinkingLevel();
12
+ const think = ctx.model?.reasoning && level && level !== "off" ? ` · think ${level}` : "";
13
+ const usage = ctx.getContextUsage();
14
+ const statuses = [...footerData.getExtensionStatuses().values()].filter(Boolean);
15
+ // Event credits only pay for the event's models.
16
+ const eventModel = state.model?.provider === PROVIDER;
17
+ const credits = eventModel ? creditsLabel(true) : undefined;
18
+ const status = !eventModel
19
+ ? undefined
20
+ : state.connection.kind === "connecting"
21
+ ? theme.fg("dim", "connecting…")
22
+ : state.connection.kind !== "ready"
23
+ ? theme.fg(state.connection.kind === "closed" ? "warning" : "error", `● ${state.connection.message}`)
24
+ : credits
25
+ ? theme.fg("success", credits)
26
+ : undefined;
27
+ const tail = (full) => {
28
+ const right = [modelLabel() + (full ? think : "")];
29
+ if (full && usage?.percent != null)
30
+ right.push(`${usage.percent.toFixed(0)}% context`);
31
+ right.push(...statuses);
32
+ let text = theme.fg("dim", right.join(" · "));
33
+ if (usage?.percent != null && usage.percent > 70)
34
+ text += theme.fg(usage.percent > 90 ? "error" : "warning", " ●");
35
+ return status ? `${text}${theme.fg("dim", " · ")}${status}` : text;
36
+ };
37
+ // Narrower terminals lose the shift+tab hint first, then the reasoning level and context.
38
+ const full = ` ${modeLabel(theme)}`;
39
+ const short = ` ${modeLabel(theme, undefined, false)}`;
40
+ return [spread([[full, tail(true)], [short, tail(true)], [short, tail(false)]], width)];
41
+ },
42
+ invalidate() { },
43
+ dispose() {
44
+ unsubscribe();
45
+ },
46
+ };
47
+ }
48
+ /**
49
+ * The first layout whose sides fit together; when none does, the last, with its right side cut
50
+ * to what's left.
51
+ */
52
+ function spread(layouts, width) {
53
+ const [left, right] = layouts.find(([l, r]) => visibleWidth(l) + visibleWidth(r) + 3 <= width) ?? layouts.at(-1);
54
+ const room = width - visibleWidth(left) - 3;
55
+ if (room < 12)
56
+ return truncateToWidth(left, width);
57
+ const fitted = truncateToWidth(right, room);
58
+ // The last column stays empty: a full-width line wraps the moment the terminal narrows.
59
+ return `${left}${" ".repeat(width - visibleWidth(left) - visibleWidth(fitted) - 1)}${fitted}`;
60
+ }