klui-code 0.0.0-stage → 0.1.0

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,161 @@
1
+ // The startup header, laid out like Claude Code's: a small pixel Klui beside the name, the model
2
+ // and the folder, then a greeting it types out. Klui blinks and glances around until the chat starts; then the
3
+ // header holds still, since it scrolls up into the terminal's own scrollback.
4
+ import { keyText } from "@earendil-works/pi-coding-agent";
5
+ import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
6
+ import { smallKlui } from "../mascot.js";
7
+ import { VERSION } from "../paths.js";
8
+ import { renderPixels } from "../pixels.js";
9
+ import { homedir } from "node:os";
10
+ import { modelLabel, state, subscribe } from "./state.js";
11
+ import { GREETINGS, pick } from "./voice.js";
12
+ const MASCOT_WIDTH = 14;
13
+ const GAP = 2;
14
+ const TICK_MS = 90;
15
+ export function createHeader(tui, theme, cwd, reducedMotion) {
16
+ let height = 0;
17
+ pinToBottom(tui, () => height);
18
+ const greeting = pick(GREETINGS);
19
+ let typed = reducedMotion ? greeting.length : 0;
20
+ let eyes = "open";
21
+ let blinkAt = Date.now() + 1800;
22
+ let glanceAt = Date.now() + 7000 + Math.random() * 6000;
23
+ let eyesUntil = 0;
24
+ let lastKey = "";
25
+ const setEyes = (next, ms) => {
26
+ eyes = next;
27
+ eyesUntil = Date.now() + ms;
28
+ };
29
+ // Lines drawn once the chat has started, per width.
30
+ let still;
31
+ const tick = () => {
32
+ if (state.chatStarted) {
33
+ if (timer)
34
+ clearInterval(timer);
35
+ eyes = "open";
36
+ typed = greeting.length;
37
+ return;
38
+ }
39
+ const now = Date.now();
40
+ if (typed < greeting.length)
41
+ typed++;
42
+ if (state.mood === "working") {
43
+ eyes = "side";
44
+ }
45
+ else if (state.mood === "happy") {
46
+ eyes = "happy";
47
+ }
48
+ else if (state.mood === "oops") {
49
+ eyes = "shut";
50
+ }
51
+ else if (reducedMotion) {
52
+ eyes = "open";
53
+ }
54
+ else if (now >= eyesUntil) {
55
+ eyes = "open";
56
+ if (now >= blinkAt) {
57
+ setEyes(Math.random() < 0.12 ? "wink" : "shut", 130);
58
+ blinkAt = now + 2200 + Math.random() * 3800;
59
+ }
60
+ else if (now >= glanceAt) {
61
+ setEyes("side", 1100);
62
+ glanceAt = now + 9000 + Math.random() * 9000;
63
+ }
64
+ }
65
+ const key = `${eyes}:${typed}:${Math.floor(now / 500) % 2}`;
66
+ if (key !== lastKey) {
67
+ lastKey = key;
68
+ tui.requestRender();
69
+ }
70
+ };
71
+ const timer = reducedMotion ? undefined : setInterval(tick, TICK_MS);
72
+ timer?.unref?.();
73
+ const unsubscribe = subscribe(() => {
74
+ if (state.chatStarted)
75
+ return;
76
+ tick();
77
+ tui.requestRender();
78
+ });
79
+ const textLines = () => {
80
+ const caret = state.chatStarted ? " " : reducedMotion || typed < greeting.length || Math.floor(Date.now() / 500) % 2 === 0 ? theme.fg("accent", "▍") : " ";
81
+ const { connection } = state;
82
+ const info = connection.kind === "ready"
83
+ ? theme.fg("muted", modelLabel())
84
+ : theme.fg(connection.kind === "closed" ? "warning" : "error", `● ${connection.message}`);
85
+ return [
86
+ `${theme.bold(theme.fg("accent", "Klui Code"))} ${theme.fg("dim", `v${VERSION}`)}`,
87
+ info,
88
+ theme.fg("muted", tilde(cwd)),
89
+ "",
90
+ `${theme.fg("dim", "›")} ${theme.bold(theme.fg("text", greeting.slice(0, typed)))}${caret}${theme.fg("dim", ` · / commands · ${keyText("app.tools.expand")} details`)}`,
91
+ ];
92
+ };
93
+ return {
94
+ render(width) {
95
+ const lines = rendered(width);
96
+ height = lines.length;
97
+ return lines;
98
+ },
99
+ invalidate() {
100
+ still = undefined;
101
+ },
102
+ dispose() {
103
+ if (timer)
104
+ clearInterval(timer);
105
+ unsubscribe();
106
+ },
107
+ };
108
+ function rendered(width) {
109
+ if (!state.chatStarted)
110
+ return draw(width);
111
+ if (still?.width !== width) {
112
+ tick();
113
+ still = { width, lines: draw(width) };
114
+ }
115
+ return still.lines;
116
+ }
117
+ function draw(width) {
118
+ const mascot = renderPixels(smallKlui(eyes), theme.getColorMode());
119
+ const text = textLines();
120
+ const fit = (line) => truncateToWidth(line, width);
121
+ if (width < MASCOT_WIDTH + GAP + 20)
122
+ return ["", ...text.map(fit), ""];
123
+ const pad = " ".repeat(GAP);
124
+ // The legs sit beside the blank line above the greeting.
125
+ return ["", ...text.map((line, i) => fit(` ${i < mascot.length ? mascot[i] + pad : ""}${line}`)), ""];
126
+ }
127
+ }
128
+ /** The current header's height, per TUI; a new session brings a new header. */
129
+ const pinned = new WeakMap();
130
+ /**
131
+ * Keep the header at the top of the window and the editor at the bottom: while the chat is shorter
132
+ * than the terminal, blank lines fill the gap under the header (the first `top()` lines). Pi clears
133
+ * the screen and redraws from the top whenever the window is resized, which would otherwise leave
134
+ * the editor halfway up.
135
+ */
136
+ function pinToBottom(tui, top) {
137
+ if (tui.mode !== "regular")
138
+ return;
139
+ const patched = pinned.has(tui);
140
+ pinned.set(tui, top);
141
+ if (patched)
142
+ return;
143
+ const render = tui.render.bind(tui);
144
+ tui.render = (width) => {
145
+ const lines = render(width);
146
+ const room = tui.terminal.rows - lines.length;
147
+ if (room <= 0)
148
+ return lines;
149
+ const at = Math.min(pinned.get(tui)(), lines.length);
150
+ return [...lines.slice(0, at), ...new Array(room).fill(""), ...lines.slice(at)];
151
+ };
152
+ }
153
+ function tilde(path) {
154
+ const home = homedir();
155
+ return path === home || path.startsWith(`${home}/`) ? `~${path.slice(home.length)}` : path;
156
+ }
157
+ /** Pad or trim an ANSI string to exactly `width` visible columns. */
158
+ export function padTo(line, width) {
159
+ const visible = visibleWidth(line);
160
+ return visible >= width ? truncateToWidth(line, width, "") : line + " ".repeat(width - visible);
161
+ }
@@ -0,0 +1,310 @@
1
+ // The Klui extension for Pi: registers the event's AntSeed models as the "klui" provider and
2
+ // dresses the terminal UI in Klui's colors, mascot and voice.
3
+ import { createBashToolDefinition, keyText, } from "@earendil-works/pi-coding-agent";
4
+ import { basename } from "node:path";
5
+ import { toProviderModels } from "../catalog.js";
6
+ import { createFallback } from "../fallback.js";
7
+ import { collectImages } from "../images.js";
8
+ import { ensureKey, fetchCredits, PassError, readDevice } from "../pass.js";
9
+ import { PROVIDER } from "../paths.js";
10
+ import { availableUpdate } from "../update.js";
11
+ import { recordUsage } from "../usage.js";
12
+ import { registerAgents, SUBAGENT_ENV } from "./agents.js";
13
+ import { registerChecks } from "./checks.js";
14
+ import { registerCommands } from "./commands.js";
15
+ import { createFooter } from "./footer.js";
16
+ import { createHeader } from "./header.js";
17
+ import { initialMode, registerPermissions } from "./permissions.js";
18
+ import { initState, modelLabel, state, update } from "./state.js";
19
+ import { registerTodos } from "./todos.js";
20
+ import { registerCompactTools } from "./tools.js";
21
+ import { describeTool } from "./voice.js";
22
+ import { registerWeb } from "./web.js";
23
+ import { createDoneWidget, createWorkingWidget } from "./working.js";
24
+ const WIDGET = "klui-working";
25
+ const TITLE_FRAMES = ["⣾", "⣽", "⣻", "⢿", "⡿", "⣟", "⣯", "⣷"];
26
+ /** Klui Pass refused on purpose (not a network problem), so retrying won't help. */
27
+ const CLOSED_CODES = new Set(["registration_closed", "pool_empty", "paused", "too_many_devices", "pass_revoked"]);
28
+ const REFUSED = "Klui refused your pass · ask an organizer";
29
+ const WRITING = `<writing>
30
+ Users are smart. Give them the answer, not a lesson.
31
+ - Lead with the answer or the result. Then add only what they need to act on it. Stop there.
32
+ - Plain words, short sentences, active voice. Use the real file names, numbers and errors.
33
+ - Sound like a calm, capable colleague: warm and direct. Contractions are fine.
34
+ - No filler openers ("Great question", "Sure!"), no praise, no hype, no emoji, no em dashes.
35
+ - Don't restate the question, recap at the end, or close with offers like "Let me know if...".
36
+ - Give one clear recommendation, not a tour of options.
37
+ - Short paragraphs. Bullets only for three or more parallel items. Code in code blocks.
38
+ - After a task, say what changed and anything left undone in a few lines.
39
+ - If you're unsure, say so briefly and give your best answer.
40
+ </writing>`;
41
+ export const createKluiExtension = ({ config, live }) => async (pi) => {
42
+ const reducedMotion = process.env.KLUI_REDUCED_MOTION === "1";
43
+ initState({ config, live, device: readDevice(), connection: { kind: "ready" }, mood: "idle", chatStarted: false, mode: initialMode() });
44
+ const fallback = createFallback(() => state.config, () => state.device.apiKey);
45
+ const registerProvider = () => {
46
+ pi.registerProvider(PROVIDER, {
47
+ name: "Klui",
48
+ baseUrl: state.config.baseUrl,
49
+ api: "openai-completions",
50
+ // Without a key the models still show up, so the first request explains what's wrong
51
+ // instead of Pi asking the attendee to /login somewhere.
52
+ apiKey: state.device.apiKey ?? "klui-no-key",
53
+ models: toProviderModels(state.config),
54
+ streamSimple: recordUsage(fallback.streamSimple),
55
+ });
56
+ };
57
+ // A key the gateway answered 401 for. If Pass hands the same one back, it's still dead.
58
+ let refusedKey;
59
+ const connect = async (force = false) => {
60
+ try {
61
+ const device = await ensureKey(state.config, { force });
62
+ const refused = refusedKey !== undefined && device.apiKey === refusedKey;
63
+ update({ device, connection: refused ? { kind: "closed", message: REFUSED } : { kind: "ready" } });
64
+ }
65
+ catch (error) {
66
+ // Pass's own messages are written for attendees; anything else is a network problem.
67
+ const pass = error instanceof PassError && !error.code.startsWith("http_") ? error : undefined;
68
+ update({
69
+ connection: pass && CLOSED_CODES.has(pass.code)
70
+ ? { kind: "closed", message: pass.message }
71
+ : { kind: "offline", message: `${pass?.message ?? "Can't reach Klui. Check your wifi"} · /klui retry` },
72
+ });
73
+ }
74
+ registerProvider();
75
+ };
76
+ let creditsCheckedAt = 0;
77
+ const refreshCredits = async (force = false) => {
78
+ const { apiKey } = state.device;
79
+ const { baseUrl } = state.config;
80
+ if (!apiKey || (!force && Date.now() - creditsCheckedAt < 15_000))
81
+ return;
82
+ creditsCheckedAt = Date.now();
83
+ const credits = await fetchCredits(baseUrl, apiKey);
84
+ if (credits)
85
+ update({ credits });
86
+ };
87
+ await connect();
88
+ // ── UI ──────────────────────────────────────────────────────────────────────────────────
89
+ let uiCtx;
90
+ const title = (frame) => {
91
+ if (!uiCtx)
92
+ return;
93
+ const base = `klui · ${basename(uiCtx.cwd)}`;
94
+ uiCtx.ui.setTitle(frame ? `${frame} ${base}` : base);
95
+ };
96
+ // Once per launch, not on every /new or /resume.
97
+ let updateNoticeShown = false;
98
+ pi.on("session_start", async (_event, ctx) => {
99
+ update({
100
+ model: ctx.model ? { provider: ctx.model.provider, id: ctx.model.id, name: ctx.model.name } : undefined,
101
+ chatStarted: ctx.sessionManager.getEntries().some((e) => e.type === "message"),
102
+ });
103
+ if (ctx.mode !== "tui")
104
+ return;
105
+ uiCtx = ctx;
106
+ ctx.ui.setHeader((tui, theme) => createHeader(tui, theme, ctx.cwd, reducedMotion));
107
+ ctx.ui.setFooter((tui, theme, footerData) => createFooter(pi, ctx, tui, theme, footerData));
108
+ // Klui's typing widget replaces Pi's one-line "Working..." loader.
109
+ ctx.ui.setWorkingVisible(false);
110
+ ctx.ui.setHiddenThinkingLabel(`✦ reasoning · ${keyText("app.thinking.toggle")} to show`);
111
+ title();
112
+ void refreshCredits(true);
113
+ if (state.connection.kind !== "ready")
114
+ ctx.ui.notify(state.connection.message, "warning");
115
+ if (!updateNoticeShown) {
116
+ updateNoticeShown = true;
117
+ void availableUpdate().then((latest) => latest && ctx.ui.notify(`Klui Code ${latest} is out · /update to install it`, "info"));
118
+ }
119
+ });
120
+ pi.on("model_select", async (event) => {
121
+ update({ model: { provider: event.model.provider, id: event.model.id, name: event.model.name } });
122
+ });
123
+ // Pasted image chips and dropped image files go along with the message as images.
124
+ pi.on("input", async (event, ctx) => {
125
+ const images = collectImages(event.text);
126
+ if (images.length === 0 && !event.images?.length)
127
+ return { action: "continue" };
128
+ if (ctx.model && !ctx.model.input.includes("image")) {
129
+ if (ctx.hasUI) {
130
+ const seeing = state.config.models.filter((m) => m.input?.includes("image")).map((m) => m.name);
131
+ const hint = seeing.length ? ` Switch to ${seeing.join(" or ")} with /model.` : "";
132
+ ctx.ui.notify(`${modelLabel()} can't see images, so it only gets your text.${hint}`, "warning");
133
+ }
134
+ return { action: "transform", text: event.text, images: [] };
135
+ }
136
+ return { action: "transform", text: event.text, images: [...(event.images ?? []), ...images] };
137
+ });
138
+ registerCompactTools(pi);
139
+ registerWeb(pi);
140
+ registerPermissions(pi, process.env[SUBAGENT_ENV] === "1");
141
+ if (process.env[SUBAGENT_ENV] !== "1")
142
+ registerAgents(pi);
143
+ registerTodos(pi);
144
+ // ── Working animation ───────────────────────────────────────────────────────────────────
145
+ let status = { activity: "thinking", startedAt: Date.now(), tokens: 0 };
146
+ // Tokens from finished replies, plus characters streamed in the current one (about 4 a token).
147
+ let counted = 0;
148
+ let streamed = 0;
149
+ let titleTimer;
150
+ let moodTimer;
151
+ let doneTimer;
152
+ let lastError;
153
+ pi.on("agent_start", async (_event, ctx) => {
154
+ status = { activity: "thinking", startedAt: Date.now(), tokens: 0 };
155
+ counted = 0;
156
+ streamed = 0;
157
+ lastError = undefined;
158
+ clearTimeout(moodTimer);
159
+ clearTimeout(doneTimer);
160
+ update({ mood: "working", chatStarted: true });
161
+ if (ctx.mode !== "tui")
162
+ return;
163
+ ctx.ui.setWorkingVisible(false);
164
+ ctx.ui.setWidget(WIDGET, (tui, theme) => createWorkingWidget(tui, theme, () => status, reducedMotion));
165
+ clearInterval(titleTimer);
166
+ if (reducedMotion) {
167
+ title("…");
168
+ }
169
+ else {
170
+ let frame = 0;
171
+ titleTimer = setInterval(() => title(TITLE_FRAMES[frame++ % TITLE_FRAMES.length]), 100);
172
+ titleTimer.unref?.();
173
+ }
174
+ });
175
+ pi.on("tool_execution_start", async (event) => {
176
+ const { activity, detail } = describeTool(event.toolName, event.args);
177
+ status = { ...status, activity, detail };
178
+ });
179
+ pi.on("message_update", async (event) => {
180
+ const update = event.assistantMessageEvent;
181
+ if (update.type !== "text_delta" && update.type !== "thinking_delta" && update.type !== "toolcall_delta")
182
+ return;
183
+ streamed += update.delta.length;
184
+ status = { ...status, tokens: counted + Math.round(streamed / 4) };
185
+ });
186
+ pi.on("message_end", async (event) => {
187
+ if (event.message.role !== "assistant")
188
+ return;
189
+ counted += event.message.usage?.output || Math.round(streamed / 4);
190
+ streamed = 0;
191
+ status = { ...status, tokens: counted };
192
+ });
193
+ pi.on("tool_execution_end", async () => {
194
+ status = { ...status, activity: "thinking", detail: undefined };
195
+ });
196
+ // After the permission prompt's tool_call handler, so a declined edit never waits on a check.
197
+ registerChecks(pi, (active) => {
198
+ status = { ...status, activity: active ? "running" : "thinking", detail: active ? "checking the changes" : undefined };
199
+ });
200
+ pi.on("agent_end", async (event) => {
201
+ const last = [...event.messages].reverse().find((m) => m.role === "assistant");
202
+ if (last?.stopReason === "error")
203
+ lastError = friendlyError(last.errorMessage);
204
+ });
205
+ pi.on("agent_settled", async (event, ctx) => {
206
+ clearInterval(titleTimer);
207
+ title();
208
+ const happy = !event.aborted && !lastError;
209
+ update({ mood: happy ? "happy" : "oops" });
210
+ moodTimer = setTimeout(() => update({ mood: "idle" }), 2600);
211
+ moodTimer.unref?.();
212
+ void refreshCredits(true);
213
+ if (ctx.mode !== "tui")
214
+ return;
215
+ const outcome = { aborted: event.aborted, error: lastError, startedAt: status.startedAt, tokens: status.tokens };
216
+ ctx.ui.setWidget(WIDGET, (_tui, theme) => createDoneWidget(theme, outcome));
217
+ clearTimeout(doneTimer);
218
+ doneTimer = setTimeout(() => {
219
+ if (ctx.isIdle())
220
+ ctx.ui.setWidget(WIDGET, undefined);
221
+ }, 2600);
222
+ doneTimer.unref?.();
223
+ });
224
+ pi.on("session_shutdown", async () => {
225
+ clearInterval(titleTimer);
226
+ clearTimeout(moodTimer);
227
+ clearTimeout(doneTimer);
228
+ });
229
+ // ── Gateway responses ───────────────────────────────────────────────────────────────────
230
+ let rekeyedAt = 0;
231
+ pi.on("after_provider_response", async (event, ctx) => {
232
+ if (ctx.model?.provider !== PROVIDER)
233
+ return;
234
+ if (event.status === 401) {
235
+ // Ask Klui Pass again. A new key means the old one was stale (say, the gateway moved); the
236
+ // same key back means an organizer revoked it, and retrying won't help. Every refused key is
237
+ // remembered; only the automatic re-ask is throttled.
238
+ refusedKey = state.device.apiKey;
239
+ if (Date.now() - rekeyedAt < 60_000) {
240
+ update({ connection: { kind: "closed", message: REFUSED } });
241
+ return;
242
+ }
243
+ rekeyedAt = Date.now();
244
+ await connect(true);
245
+ if (state.connection.kind === "ready")
246
+ ctx.ui.notify("Refreshed your Klui pass. Send that again!", "info");
247
+ else
248
+ ctx.ui.notify(state.connection.message, "warning");
249
+ }
250
+ else if (event.status === 402) {
251
+ void refreshCredits(true);
252
+ }
253
+ });
254
+ // ── Identity ────────────────────────────────────────────────────────────────────────────
255
+ // The model only ever hears about Klui: Pi's own preamble, its docs section and its PI_* shell
256
+ // variables are swapped out. The writing rules are a short take on the Klui web app's prompt.
257
+ pi.on("before_agent_start", async (event) => ({
258
+ systemPrompt: `${event.systemPrompt
259
+ .replace("You are an expert coding assistant operating inside pi, a coding agent harness.", "You are Klui, an expert coding assistant running in the Klui CLI.")
260
+ .replace(/\n*<docs>[\s\S]*?<\/docs>/, "")}\n\n${WRITING}\n\n${today()}`,
261
+ }));
262
+ registerShell(pi);
263
+ registerCommands(pi, {
264
+ reconnect: async (ctx) => {
265
+ await connect(true);
266
+ if (state.connection.kind === "ready") {
267
+ ctx.ui.notify("Connected to Klui ✦", "info");
268
+ void refreshCredits(true);
269
+ }
270
+ else {
271
+ ctx.ui.notify(state.connection.message, "warning");
272
+ }
273
+ },
274
+ refreshCredits: () => refreshCredits(true),
275
+ });
276
+ };
277
+ /**
278
+ * Pi's bash tool, with KLUI_MODEL and KLUI_REASONING_LEVEL in place of every PI_* variable (Pi's
279
+ * session details, whose model id is the raw provider id, and the settings Klui runs Pi with).
280
+ */
281
+ /** Models only know the year their training ended, so they search for "weather today 2025". */
282
+ export function today(now = new Date()) {
283
+ const date = now.toLocaleDateString("en-US", { weekday: "long", year: "numeric", month: "long", day: "numeric" });
284
+ const zone = Intl.DateTimeFormat().resolvedOptions().timeZone;
285
+ return `Today is ${date} (${zone}). For anything current, like weather, news or prices, search instead of relying on memory, leave past years out of queries, and check that results are from today before calling them current.`;
286
+ }
287
+ function registerShell(pi) {
288
+ const bash = createBashToolDefinition(process.cwd(), {
289
+ exposeSessionEnvironment: false,
290
+ spawnHook: (context) => {
291
+ const env = Object.fromEntries(Object.entries(context.env).filter(([name]) => !name.startsWith("PI_")));
292
+ return { ...context, env: { ...env, KLUI_MODEL: modelLabel(), KLUI_REASONING_LEVEL: pi.getThinkingLevel() ?? "off" } };
293
+ },
294
+ });
295
+ pi.registerTool({ ...bash, promptGuidelines: ["KLUI_MODEL and KLUI_REASONING_LEVEL in the shell name the current model and reasoning level."] });
296
+ }
297
+ function friendlyError(message) {
298
+ if (!message)
299
+ return "something went wrong";
300
+ if (/spend_limit_reached/.test(message))
301
+ return "out of credits for now";
302
+ if (/insufficient_deposits|channel_exhausted/.test(message))
303
+ return "the event wallet needs a top-up";
304
+ if (/401|unauthori[sz]ed/i.test(message))
305
+ return "your Klui pass was refused";
306
+ if (/model_not_found|no.*peer/i.test(message))
307
+ return "no seller has that model right now";
308
+ const firstLine = message.split("\n")[0];
309
+ return firstLine.length > 60 ? `${firstLine.slice(0, 59)}…` : firstLine;
310
+ }