klui-code 0.1.6 → 0.1.8

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.
package/README.md CHANGED
@@ -1,7 +1,8 @@
1
1
  # Klui Code
2
2
 
3
3
  Klui in your terminal: a pixel-cute coding agent for the Klui hackathon. It reads, edits and runs
4
- code in your project, and it's free for attendees: inference runs on [AntSeed](https://antseed.com)
4
+ code in your project, and it's free for attendees: inference runs on
5
+ [Surplus](https://www.surplusintelligence.ai), with [AntSeed](https://antseed.com) as the backup,
5
6
  and Klui covers the bill.
6
7
 
7
8
  ```
@@ -81,15 +82,21 @@ in `~/.klui` and never touches an existing pi setup.
81
82
  ```
82
83
  klui ──(1) device id──▶ Klui Pass ──▶ key from a pre-made pool
83
84
  │
84
- └──(2) chat + tools, Bearer <key>──▶ AntSeed gateway ──▶ AntSeed buyer (event wallet) ──▶ sellers
85
+ └──(2) chat + tools, Bearer <key>──▶ Klui router ──▶ Surplus (Klui's key)
86
+ │ after two failures
87
+ └──▶ AntSeed gateway ──▶ AntSeed buyer (event wallet) ──▶ sellers
85
88
  ```
86
89
 
87
- - **One funded account.** Klui runs a single AntSeed buyer holding the event wallet, behind
88
- AntSeed's own API-key gateway. Every attendee key is paid by that one wallet, and the gateway
89
- enforces each key's spend cap.
90
+ - **Klui's router** (`server/router.mjs`) is the only way in. It serves just the event's models, from
91
+ Surplus with Klui's one key (which never leaves the server), and moves a request to AntSeed when
92
+ Surplus fails it twice. A conversation AntSeed took over stays there while its prompt is cached
93
+ on that seller.
94
+ - **One funded account per provider.** Klui runs a single AntSeed buyer holding the event wallet,
95
+ behind AntSeed's own API-key gateway. Every attendee key is paid by that one wallet, and each
96
+ key's spend cap covers what it spends on Surplus and AntSeed together.
90
97
  - **Klui Pass** (`server/`) hands each device a key from a pool and serves the event's model list,
91
98
  so models can change mid-event without a new release. It never sees prompts or code: klui talks to
92
- the gateway directly.
99
+ the router directly.
93
100
  - **The CLI** is pi with one extension (`src/extension/`): the `klui` provider, the pixel header,
94
101
  the working line (a shimmering phrase, the time and tokens in one small box), the footer, labeled tool
95
102
  rows, the `subagent` tool (each subagent is a child `klui --mode json` process), `/klui`,
@@ -119,7 +126,7 @@ it for global installs, so transitive packages can still move within their own s
119
126
  |---|---|
120
127
  | `KLUI_PASS_URL` | Klui Pass to use (default `https://klui.ai/code/pass`) |
121
128
  | `KLUI_HOME` | where klui keeps its state (default `~/.klui`) |
122
- | `KLUI_API_KEY`, `KLUI_BASE_URL` | skip Pass and use this AntSeed gateway key directly |
129
+ | `KLUI_API_KEY`, `KLUI_BASE_URL` | skip Pass and use this key and router (or AntSeed gateway) directly |
123
130
  | `KLUI_REDUCED_MOTION=1` | no animations |
124
131
 
125
132
  To try the whole flow locally against free AntSeed sellers, run an AntSeed buyer and gateway, make
package/dist/cli.js CHANGED
@@ -113,7 +113,9 @@ async function run() {
113
113
  const loaded = loadConfig();
114
114
  seedSettings(loaded.config, pi.VERSION);
115
115
  seedKeybindings();
116
- await patchPi(loaded.config);
116
+ // Pi's own parser, so a repeated --mode counts the way Pi counts it (the last one wins).
117
+ const { mode } = pi.parseArgs(args);
118
+ await patchPi(loaded.config, mode === "json" || mode === "rpc");
117
119
  const { createKluiExtension } = await import("./extension/index.js");
118
120
  await pi.main([...args, "--theme", THEMES_DIR], {
119
121
  extensionFactories: [{ name: "klui", factory: createKluiExtension(loaded), hidden: true }],
@@ -0,0 +1,193 @@
1
+ // When something new lands on the clipboard, a line above the composer says which keys paste it.
2
+ // Text and images paste differently: the terminal pastes text itself (cmd+v on macOS, ctrl+v in
3
+ // Windows Terminal and VS Code), but it can't send an image, so Klui reads images straight from the
4
+ // clipboard on Pi's paste key (ctrl+v on macOS, alt+v on Windows, where the terminal keeps ctrl+v).
5
+ // Pi's key pastes text too, so it's the advice wherever Klui doesn't know the terminal's own key.
6
+ //
7
+ // Klui looks at the clipboard when the terminal window gets focus back (fullscreen mode turns on
8
+ // the terminal's focus reports) and right after Klui copies something itself. A terminal that never
9
+ // reports focus gets a light check every couple of seconds instead.
10
+ import { createHash } from "node:crypto";
11
+ const hash = (data) => createHash("sha1").update(data).digest("hex");
12
+ /** A read that failed (Windows: another app has the clipboard open) makes the whole clipboard unknown. */
13
+ const FAILED = Symbol("failed");
14
+ const settle = (read) => read ? read().catch(() => FAILED) : Promise.resolve(undefined);
15
+ /**
16
+ * What's on the clipboard, in the order Pi's paste key takes it: files, then an image, then text.
17
+ * Undefined when the clipboard can't be read; null when it's empty.
18
+ */
19
+ export async function readClip(reader) {
20
+ // One after another: on Windows each read opens the clipboard, which locks it for other apps.
21
+ const files = await settle(reader.getFilePaths?.bind(reader));
22
+ const image = await settle(() => reader.getImage());
23
+ const text = await settle(() => reader.getText());
24
+ if (files === FAILED || image === FAILED || text === FAILED)
25
+ return undefined;
26
+ if (files === undefined && image === undefined && text === undefined)
27
+ return undefined;
28
+ if (files?.length)
29
+ return { kind: "files", files: files.length, signature: `files:${hash(files.join("\0"))}` };
30
+ // The text is part of it: the hint names its key too.
31
+ if (image?.length)
32
+ return { kind: "image", alsoText: !!text, signature: `image:${hash(image)}:${text ? hash(text) : ""}` };
33
+ if (text)
34
+ return { kind: "text", signature: `text:${hash(text)}` };
35
+ return null;
36
+ }
37
+ /**
38
+ * The key the terminal itself pastes text with, or Pi's paste key (`piKey`) where that's unknown.
39
+ * The old Windows console (conhost) hands ctrl+v to Klui instead of pasting, and Pi's key is alt+v.
40
+ */
41
+ export function textPasteKey(piKey, platform = process.platform, env = process.env) {
42
+ if (platform === "darwin")
43
+ return "cmd+v";
44
+ if (platform === "win32") {
45
+ if (env.WT_SESSION || env.TERM_PROGRAM === "vscode")
46
+ return "ctrl+v";
47
+ if (env.TERM_PROGRAM === "WezTerm")
48
+ return "ctrl+shift+v";
49
+ return piKey;
50
+ }
51
+ return "ctrl+shift+v";
52
+ }
53
+ /** The hint's words: what was copied, and which keys paste it. `imageKey` is Pi's paste key. */
54
+ export function hintParts(clip, imageKey, platform = process.platform, env = process.env) {
55
+ const textKey = textPasteKey(imageKey, platform, env);
56
+ if (clip.kind === "text")
57
+ return { what: "Text copied", keys: [{ key: textKey, does: "to paste" }] };
58
+ if (clip.kind === "files") {
59
+ return { what: clip.files === 1 ? "File copied" : `${clip.files} files copied`, keys: [{ key: imageKey, does: "to paste" }] };
60
+ }
61
+ if (!clip.alsoText || textKey === imageKey)
62
+ return { what: "Image copied", keys: [{ key: imageKey, does: "to paste" }] };
63
+ return { what: "Image copied", keys: [{ key: imageKey, does: "pastes the image" }, { key: textKey, does: "the text" }] };
64
+ }
65
+ const listeners = new Set();
66
+ export function clipboardEvent(event) {
67
+ for (const listener of listeners)
68
+ listener(event);
69
+ }
70
+ export function onClipboardEvent(listener) {
71
+ listeners.add(listener);
72
+ return () => listeners.delete(listener);
73
+ }
74
+ const RETRIES = 3;
75
+ /**
76
+ * Remembers what was on the clipboard and shows the hint when that changes. Whatever is on the
77
+ * clipboard when Klui starts is taken as already known, so no hint shows for it, and so is
78
+ * whatever is on it when something gets pasted.
79
+ */
80
+ export function createClipboardWatcher({ read, show, hide, pollMs = 2_000, showMs = 10_000, retryMs = 500 }) {
81
+ let last;
82
+ let known = false;
83
+ let stopped = false;
84
+ // Goes up on every paste, copy and focus. A read that started before the latest one is stale:
85
+ // it changes nothing, and the check that event started reads again.
86
+ let epoch = 0;
87
+ // After a paste, the first read that works records what was pasted without showing it, unless
88
+ // Klui copies something first.
89
+ let quiet = false;
90
+ let hideTimer;
91
+ let pollTimer;
92
+ let retryTimer;
93
+ let retries = 0;
94
+ // One read at a time. Checks asked for during a read share the one read after it.
95
+ let reading;
96
+ let next;
97
+ const clearHint = () => {
98
+ clearTimeout(hideTimer);
99
+ hideTimer = undefined;
100
+ hide();
101
+ };
102
+ /** False when the clipboard couldn't be read. */
103
+ const look = async () => {
104
+ const started = epoch;
105
+ const clip = await read().catch(() => undefined);
106
+ if (stopped || epoch !== started)
107
+ return true;
108
+ if (clip === undefined)
109
+ return false;
110
+ const silent = quiet;
111
+ quiet = false;
112
+ const signature = clip?.signature ?? null;
113
+ if (known && signature === last)
114
+ return true;
115
+ const first = !known;
116
+ known = true;
117
+ last = signature;
118
+ if (first || silent)
119
+ return true;
120
+ if (!clip) {
121
+ clearHint();
122
+ return true;
123
+ }
124
+ clearTimeout(hideTimer);
125
+ show(clip);
126
+ hideTimer = setTimeout(clearHint, showMs);
127
+ hideTimer.unref?.();
128
+ return true;
129
+ };
130
+ const check = () => {
131
+ if (stopped)
132
+ return Promise.resolve(true);
133
+ if (!reading) {
134
+ reading = look().finally(() => {
135
+ reading = undefined;
136
+ });
137
+ return reading;
138
+ }
139
+ next ??= reading.then(() => {
140
+ next = undefined;
141
+ return check();
142
+ });
143
+ return next;
144
+ };
145
+ /** Checks focus, a copy or a paste ask for get a few more tries when the clipboard is busy. */
146
+ const checkHard = () => {
147
+ retries = 0;
148
+ clearTimeout(retryTimer);
149
+ retryTimer = undefined;
150
+ const attempt = () => void check().then((ok) => {
151
+ if (ok || stopped || retries >= RETRIES)
152
+ return;
153
+ retries++;
154
+ retryTimer = setTimeout(() => {
155
+ retryTimer = undefined;
156
+ attempt();
157
+ }, retryMs);
158
+ retryTimer.unref?.();
159
+ });
160
+ attempt();
161
+ };
162
+ pollTimer = setInterval(() => void check(), pollMs);
163
+ pollTimer.unref?.();
164
+ void check();
165
+ return {
166
+ check,
167
+ handle(event) {
168
+ if (stopped)
169
+ return;
170
+ epoch++;
171
+ // Klui's own copy after a paste is something new. Focus keeps a paste's quiet read due: what
172
+ // was pasted can still be all that's there.
173
+ if (event === "pasted")
174
+ quiet = true;
175
+ else if (event === "copied")
176
+ quiet = false;
177
+ if (event === "pasted")
178
+ clearHint();
179
+ if (event === "focus" && pollTimer) {
180
+ // The terminal reports focus, so polling can stop.
181
+ clearInterval(pollTimer);
182
+ pollTimer = undefined;
183
+ }
184
+ checkHard();
185
+ },
186
+ stop() {
187
+ stopped = true;
188
+ clearInterval(pollTimer);
189
+ clearTimeout(hideTimer);
190
+ clearTimeout(retryTimer);
191
+ },
192
+ };
193
+ }
@@ -14,6 +14,7 @@
14
14
  // an IPC channel, and the dialog shows here. Its chat is saved in KLUI_HOME/subagents (only the
15
15
  // newest few, for a week), and the result names the file, so `klui --session <file>` opens it.
16
16
  import { spawn } from "node:child_process";
17
+ import { randomUUID } from "node:crypto";
17
18
  import { mkdirSync, readdirSync, rmSync, statSync } from "node:fs";
18
19
  import { join } from "node:path";
19
20
  import { StringEnum } from "@earendil-works/pi-ai";
@@ -23,6 +24,7 @@ import { Type } from "typebox";
23
24
  import { KLUI_HOME, PACKAGE_DIR, PROVIDER } from "../paths.js";
24
25
  import { PARENT_SESSION_ENV } from "../usage.js";
25
26
  import { ASK_PARENT, decide, PERMISSIONS_ENV } from "./permissions.js";
27
+ import { emitEvent, eventsWanted } from "./events.js";
26
28
  import { state } from "./state.js";
27
29
  import { preparingLabel, shortPath } from "./voice.js";
28
30
  /** Set in a subagent's environment: subagents don't start subagents of their own. */
@@ -90,6 +92,7 @@ export function registerAgents(pi) {
90
92
  ],
91
93
  parameters: Type.Object({
92
94
  task: Type.String({ description: "Everything the subagent needs: the goal, relevant paths and what to report back" }),
95
+ title: Type.Optional(Type.String({ description: "3 to 6 words naming the task for the user, like \"Find ModelManifest usages\"" })),
93
96
  kind: Type.Optional(StringEnum(["explore", "general"], { description: "explore (read-only files and web, default) or general (can edit and run commands)" })),
94
97
  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" })),
95
98
  background: Type.Optional(Type.Boolean({ description: "Return right away and deliver the report as a message later" })),
@@ -102,16 +105,30 @@ export function registerAgents(pi) {
102
105
  const model = params.model ? resolveModel(params.model) : (own ?? resolveModel(state.config.defaultModel));
103
106
  const run = { model: `${PROVIDER}/${model.id}`, thinking: pi.getThinkingLevel() };
104
107
  const startedAt = Date.now();
105
- const details = { kind, task: params.task, model: model.name, tools: 0, tokens: 0, steps: [], progress: "starting up", startedAt, elapsedMs: 0 };
108
+ const title = params.title?.trim() || undefined;
109
+ const details = { kind, task: params.task, ...(title ? { title } : {}), model: model.name, tools: 0, tokens: 0, steps: [], progress: "starting up", startedAt, elapsedMs: 0 };
106
110
  if (params.background) {
107
111
  ui = ctx.hasUI ? ctx.ui : undefined;
112
+ // An app running Klui over RPC can't see background agents otherwise: no tool call follows them.
113
+ const app = eventsWanted(ctx) ? ctx.ui : undefined;
108
114
  const id = nextId++;
109
115
  const controller = new AbortController();
110
116
  details.background = id;
117
+ details.run = randomUUID();
111
118
  running.set(id, { controller, details });
112
119
  showRunning();
120
+ let reportedAt = 0;
121
+ const report = (status, error) => {
122
+ reportedAt = Date.now();
123
+ if (app)
124
+ emitEvent(app, { type: "agent", id, run: details.run, kind, task: params.task, status, progress: status === "running" ? details.progress : undefined, error, transcript: details.transcript });
125
+ };
113
126
  let shownAt = 0;
127
+ // After runAgent has named the transcript, so the app can follow it from the start.
128
+ queueMicrotask(() => report("running"));
114
129
  void runAgent(ctx, kind, run, params.task, controller.signal, details, () => {
130
+ if (Date.now() - reportedAt >= 1000)
131
+ report("running");
115
132
  if (Date.now() - shownAt < 250)
116
133
  return;
117
134
  shownAt = Date.now();
@@ -119,6 +136,7 @@ export function registerAgents(pi) {
119
136
  }).then((outcome) => {
120
137
  running.delete(id);
121
138
  showRunning();
139
+ report(controller.signal.aborted ? "canceled" : outcome.error ? "failed" : "completed", outcome.error);
122
140
  if (controller.signal.aborted)
123
141
  return;
124
142
  const done = { ...details, progress: undefined, error: outcome.error, elapsedMs: Date.now() - startedAt };
@@ -203,6 +221,22 @@ export function registerAgents(pi) {
203
221
  }
204
222
  return row;
205
223
  });
224
+ pi.registerCommand("stop-agents", {
225
+ description: "Stop the background agents, or just the one numbered (/stop-agents 2)",
226
+ handler: async (args, ctx) => {
227
+ const wanted = args.trim();
228
+ const stopping = [...running].filter(([id]) => wanted === "" || String(id) === wanted.replace(/^#/, ""));
229
+ for (const [, { controller }] of stopping)
230
+ controller.abort();
231
+ // The app follows them through their events, which report each one as canceled.
232
+ if (eventsWanted(ctx))
233
+ return;
234
+ if (stopping.length === 0)
235
+ ctx.ui.notify(wanted === "" ? "No background agents are running." : `No background agent #${wanted.replace(/^#/, "")} is running.`, "info");
236
+ else
237
+ ctx.ui.notify(`Stopped ${stopping.length === 1 ? `background agent #${stopping[0][0]}` : `${stopping.length} background agents`}.`, "info");
238
+ },
239
+ });
206
240
  pi.on("session_shutdown", async () => {
207
241
  for (const { controller } of running.values())
208
242
  controller.abort();
@@ -0,0 +1,51 @@
1
+ // The clipboard hint above the composer (see ../clipboard-hint.ts): "Image copied · ctrl+v to paste".
2
+ import { keyText } from "@earendil-works/pi-coding-agent";
3
+ import { getNativeClipboard, truncateToWidth } from "@earendil-works/pi-tui";
4
+ import { createClipboardWatcher, hintParts, onClipboardEvent, readClip } from "../clipboard-hint.js";
5
+ const WIDGET = "klui-clipboard";
6
+ const BRACKETED_PASTE = "\x1b[200~";
7
+ export function hintLine(clip, theme, width, platform = process.platform) {
8
+ const { what, keys } = hintParts(clip, keyText("app.clipboard.pasteImage") || "ctrl+v", platform);
9
+ const dot = theme.fg("dim", " · ");
10
+ const pasting = keys.map(({ key, does }) => `${theme.bold(theme.fg("accent", key))} ${theme.fg("muted", does)}`).join(dot);
11
+ return truncateToWidth(` ${theme.fg("muted", what)}${dot}${pasting}`, width);
12
+ }
13
+ export function registerClipboardHint(pi) {
14
+ let watcher;
15
+ let unsubscribe;
16
+ let unlisten;
17
+ const stop = () => {
18
+ watcher?.stop();
19
+ unsubscribe?.();
20
+ unlisten?.();
21
+ watcher = unsubscribe = unlisten = undefined;
22
+ };
23
+ pi.on("session_start", async (_event, ctx) => {
24
+ stop();
25
+ if (ctx.mode !== "tui")
26
+ return;
27
+ const clipboard = getNativeClipboard();
28
+ if (!clipboard)
29
+ return;
30
+ const { ui } = ctx;
31
+ watcher = createClipboardWatcher({
32
+ read: () => readClip(clipboard),
33
+ show: (clip) => ui.setWidget(WIDGET, (_tui, theme) => ({ render: (width) => [hintLine(clip, theme, width)], invalidate() { } })),
34
+ hide: () => ui.setWidget(WIDGET, undefined),
35
+ });
36
+ const current = watcher;
37
+ unsubscribe = onClipboardEvent((event) => current.handle(event));
38
+ // The terminal's own paste arrives as a bracketed paste.
39
+ unlisten = ui.onTerminalInput((data) => {
40
+ if (data.includes(BRACKETED_PASTE))
41
+ current.handle("pasted");
42
+ return undefined;
43
+ });
44
+ });
45
+ // Sending the message, or queueing it while Klui works, is using what was pasted.
46
+ pi.on("input", async () => {
47
+ watcher?.handle("pasted");
48
+ return { action: "continue" };
49
+ });
50
+ pi.on("session_shutdown", async () => stop());
51
+ }
@@ -0,0 +1,13 @@
1
+ // Klui's state for a desktop or mobile app that runs Klui over RPC (`klui --mode rpc`). Pi's RPC
2
+ // stream carries chat, tools and dialogs, but not what Klui draws in the terminal (the task list,
3
+ // background agents), so those go out as notify messages: one line, `klui:v1 ` then JSON.
4
+ // Only when the host asks with KLUI_EVENTS=1, so other RPC hosts never see them as notices.
5
+ export const EVENTS_ENV = "KLUI_EVENTS";
6
+ export const EVENT_PREFIX = "klui:v1 ";
7
+ /** Whether this session reports its state to an app. */
8
+ export function eventsWanted(ctx) {
9
+ return process.env[EVENTS_ENV] === "1" && ctx.mode === "rpc" && ctx.hasUI;
10
+ }
11
+ export function emitEvent(ui, event) {
12
+ ui.notify(`${EVENT_PREFIX}${JSON.stringify(event)}`, "info");
13
+ }
@@ -1,9 +1,9 @@
1
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.
2
+ // model, context used and connection status on the right.
3
3
  import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
4
4
  import { PROVIDER } from "../paths.js";
5
5
  import { modeLabel } from "./permissions.js";
6
- import { creditsLabel, modelLabel, state, subscribe } from "./state.js";
6
+ import { modelLabel, state, subscribe } from "./state.js";
7
7
  export function createFooter(pi, ctx, tui, theme, footerData) {
8
8
  const unsubscribe = subscribe(() => tui.requestRender());
9
9
  return {
@@ -12,18 +12,15 @@ export function createFooter(pi, ctx, tui, theme, footerData) {
12
12
  const think = ctx.model?.reasoning && level && level !== "off" ? ` · ${level}` : "";
13
13
  const usage = ctx.getContextUsage();
14
14
  const statuses = [...footerData.getExtensionStatuses().values()].filter(Boolean);
15
- // Event credits only pay for the event's models.
15
+ // Connection status only applies to the event's models.
16
16
  const eventModel = state.model?.provider === PROVIDER;
17
- const credits = eventModel ? creditsLabel(true) : undefined;
18
17
  const status = !eventModel
19
18
  ? undefined
20
19
  : state.connection.kind === "connecting"
21
20
  ? theme.fg("dim", "connecting…")
22
21
  : state.connection.kind !== "ready"
23
22
  ? theme.fg(state.connection.kind === "closed" ? "warning" : "error", `● ${state.connection.message}`)
24
- : credits
25
- ? theme.fg("success", credits)
26
- : undefined;
23
+ : undefined;
27
24
  const tail = (full) => {
28
25
  const right = [modelLabel() + (full ? think : "")];
29
26
  if (full && usage?.percent != null)
@@ -12,6 +12,7 @@ import { recordUsage } from "../usage.js";
12
12
  import { agentProgress, registerAgents, SUBAGENT_ENV, subagentTokensSoFar } from "./agents.js";
13
13
  import { registerBrowser } from "./browser.js";
14
14
  import { registerChecks } from "./checks.js";
15
+ import { registerClipboardHint } from "./clipboard.js";
15
16
  import { registerCommands } from "./commands.js";
16
17
  import { createFooter } from "./footer.js";
17
18
  import { createHeader } from "./header.js";
@@ -221,6 +222,8 @@ export const createKluiExtension = ({ config, live, fresh }) => async (pi) => {
221
222
  pi.on("model_select", async (event) => {
222
223
  update({ model: { provider: event.model.provider, id: event.model.id, name: event.model.name } });
223
224
  });
225
+ // Before Klui's own input handler, which decides what the message carries.
226
+ registerClipboardHint(pi);
224
227
  // Pasted image chips and dropped image files go along with the message as images.
225
228
  pi.on("input", async (event, ctx) => {
226
229
  const images = collectImages(event.text);
@@ -5,6 +5,7 @@
5
5
  import { StringEnum } from "@earendil-works/pi-ai";
6
6
  import { truncateToWidth } from "@earendil-works/pi-tui";
7
7
  import { Type } from "typebox";
8
+ import { emitEvent, eventsWanted } from "./events.js";
8
9
  const ENTRY = "klui-todos";
9
10
  const WIDGET = "klui-todos";
10
11
  /** Task rows the panel shows before "+N more". */
@@ -13,15 +14,23 @@ export function registerTodos(pi) {
13
14
  let todos = [];
14
15
  let changedThisRun = false;
15
16
  let ui;
17
+ /** An app running Klui over RPC (see events.ts), which draws the list itself. */
18
+ let app;
16
19
  const show = () => {
17
20
  if (!ui)
18
21
  return;
19
22
  const visible = todos.length > 0 && (changedThisRun || todos.some((t) => t.status !== "completed"));
20
23
  ui.setWidget(WIDGET, visible ? (_tui, theme) => ({ render: (width) => todoPanel(todos, theme, width), invalidate() { } }) : undefined);
21
24
  };
25
+ /** Tell the app the list changed: a call from a codemode script has no `todo` result to read. */
26
+ const report = () => {
27
+ if (app)
28
+ emitEvent(app, { type: "todos", todos });
29
+ };
22
30
  const restore = (ctx) => {
23
31
  todos = lastTodos(ctx.sessionManager.getBranch());
24
32
  show();
33
+ report();
25
34
  };
26
35
  pi.registerTool({
27
36
  name: "todo",
@@ -48,11 +57,13 @@ export function registerTodos(pi) {
48
57
  // session as a tool result.
49
58
  pi.appendEntry(ENTRY, { todos });
50
59
  show();
60
+ report();
51
61
  return { content: [{ type: "text", text: summary(todos) }], details: { todos } };
52
62
  },
53
63
  });
54
64
  pi.on("session_start", async (_event, ctx) => {
55
65
  ui = ctx.mode === "tui" ? ctx.ui : undefined;
66
+ app = eventsWanted(ctx) ? ctx.ui : undefined;
56
67
  changedThisRun = false;
57
68
  restore(ctx);
58
69
  });
package/dist/fallback.js CHANGED
@@ -39,12 +39,13 @@ export const PROVIDER_ISSUE = "Klui had a model provider issue. Please retry.";
39
39
  /**
40
40
  * A peer that hasn't started answering by now is treated as gone (some hang without a word, others
41
41
  * send headers and then nothing). Long prompts get longer: reading an uncached 900K-token
42
- * conversation alone takes a peer 20-30 s.
42
+ * conversation alone takes a peer 20-30 s. Klui's router spends the first part of this on Surplus
43
+ * before it moves the request to AntSeed (see server/router.mjs), which gets the rest.
43
44
  */
44
45
  export function answerTimeoutMs(context) {
45
46
  // About 4 characters a token; image data is left out, since a picture costs far fewer tokens than its base64.
46
47
  const tokens = JSON.stringify(context, (key, value) => (key === "data" ? undefined : value)).length / 4;
47
- return 25_000 + Math.round((tokens / 100_000) * 5_000);
48
+ return 45_000 + Math.round((tokens / 100_000) * 10_000);
48
49
  }
49
50
  /** The service name in a gateway model id: "<peerId>@deepseek-v4.1-flash" → "deepseek-v4.1-flash". */
50
51
  export function serviceOf(id) {
@@ -52,13 +53,20 @@ export function serviceOf(id) {
52
53
  return at === -1 ? id : id.slice(at + 1);
53
54
  }
54
55
  /**
55
- * The reply keeps the event model's id, so a resumed chat finds its model again, and names the peer
56
- * that answered (`<peer>@<service>`) as the response model, for the usage log.
56
+ * Klui's router names a reply Surplus wrote `surplus@<service>` (see server/router.mjs). Pi keeps
57
+ * that as the reply's response model, since it isn't the id klui asked for.
58
+ */
59
+ const SURPLUS = "surplus@";
60
+ /**
61
+ * The reply keeps the event model's id, so a resumed chat finds its model again, and names who
62
+ * answered as the response model, for the usage log: Surplus, or the peer klui picked
63
+ * (`<peer>@<service>`).
57
64
  */
58
65
  function sellerAside(event, id) {
59
66
  const reply = event.type === "done" ? event.message : event.type === "error" ? event.error : "partial" in event ? event.partial : undefined;
60
67
  if (reply && reply.model !== id) {
61
- reply.responseModel = reply.model;
68
+ if (!reply.responseModel?.startsWith(SURPLUS))
69
+ reply.responseModel = reply.model;
62
70
  reply.model = id;
63
71
  }
64
72
  return event;
@@ -66,12 +74,15 @@ function sellerAside(event, id) {
66
74
  /**
67
75
  * Pi replays a reply's reasoning only to the model that wrote it, by id. Replies keep the event
68
76
  * model's id (see sellerAside), so a copy of the chat names the seller again on the replies that
69
- * seller wrote, as it did when replies kept the seller's id.
77
+ * seller wrote, as it did when replies kept the seller's id. Surplus's replies count as this
78
+ * seller's too: the router sends klui's requests to Surplus whichever seller klui picked, and it's
79
+ * the same model either way.
70
80
  */
71
81
  function asSeller(context, attempt) {
72
- if (!context.messages.some((m) => m.role === "assistant" && m.responseModel === attempt))
82
+ const mine = (m) => m.role === "assistant" && (m.responseModel === attempt || (!!m.responseModel?.startsWith(SURPLUS) && serviceOf(m.responseModel) === serviceOf(attempt)));
83
+ if (!context.messages.some(mine))
73
84
  return context;
74
- return { ...context, messages: context.messages.map((m) => (m.role === "assistant" && m.responseModel === attempt ? { ...m, model: attempt } : m)) };
85
+ return { ...context, messages: context.messages.map((m) => (mine(m) ? { ...m, model: attempt } : m)) };
75
86
  }
76
87
  /** A failure whose own message is for the user (Klui can't connect, say), not a provider's. */
77
88
  class ForTheUser extends Error {
@@ -149,6 +160,9 @@ function rank(all) {
149
160
  export function worthAnotherPeer(message) {
150
161
  if (!message)
151
162
  return false;
163
+ // AntSeed preserves a seller's 403 even when the gateway key is valid.
164
+ if (/^\s*403\b/.test(message) && /"antseed_fault"\s*:\s*"peer"/.test(message) && /"code"\s*:\s*"upstream_unavailable"/.test(message))
165
+ return true;
152
166
  if (/^\s*(400|401|403)\b/.test(message) || /invalid_api_key|abort/i.test(message))
153
167
  return false;
154
168
  return /^\s*(402|404|408|409|429|5\d\d)\b/.test(message) || /insufficient_deposits|not reachable|does not support|no peer|timed? ?out|ECONN|fetch failed/i.test(message);
@@ -3,15 +3,18 @@
3
3
  // if a Pi update moves things around.
4
4
  import { Spacer, TruncatedText, TuiAltScreen } from "@earendil-works/pi-tui";
5
5
  import { PROVIDER_ISSUE, serviceOf } from "./fallback.js";
6
+ import { clipboardEvent } from "./clipboard-hint.js";
6
7
  import { chipFor, isClipboardImageFile } from "./images.js";
7
8
  import { PROVIDER } from "./paths.js";
8
9
  import { scrollFrame } from "./scroll.js";
9
10
  export const piModule = async (path) => (await import(new URL(path, import.meta.resolve("@earendil-works/pi-coding-agent")).href));
10
- export async function patchPi(config) {
11
- brandOutput();
11
+ /** `machineOutput`: `--mode json` or `rpc`, where every stdout line is JSON for another program to parse. */
12
+ export async function patchPi(config, machineOutput = false) {
13
+ if (!machineOutput)
14
+ brandOutput();
12
15
  scrollWithTerminal();
13
16
  clearAfterCopy();
14
- for (const patch of [() => sellerModelIds(config), retryProviderIssues, removeLlama, hidePiFooter, hoverJumpToLatest, queuedMessages, trimSlashMenu, slashAliases, simpleThinkingMenu, thinkingAfterModel, () => tidyModelPicker(), () => quietPiHints(config), pasteImageChips])
17
+ for (const patch of [() => sellerModelIds(config), retryProviderIssues, removeLlama, hidePiFooter, hoverJumpToLatest, queuedMessages, trimSlashMenu, slashAliases, simpleThinkingMenu, thinkingAfterModel, () => tidyModelPicker(), () => quietPiHints(config), pasteImageChips, quietImageNotes, clipboardEvents])
15
18
  await patch().catch(() => { });
16
19
  }
17
20
  /**
@@ -48,6 +51,18 @@ async function retryProviderIssues() {
48
51
  proto._isRetryableError = function (message) {
49
52
  return message.errorMessage === PROVIDER_ISSUE || isRetryable.call(this, message);
50
53
  };
54
+ const { InteractiveMode } = await piModule("./modes/interactive/interactive-mode.js");
55
+ const handle = InteractiveMode.prototype.handleEvent;
56
+ if (typeof handle !== "function")
57
+ return;
58
+ InteractiveMode.prototype.handleEvent = function (event) {
59
+ const retry = this.settingsManager.getRetrySettings();
60
+ if (event.type === "message_end" && event.message?.role === "assistant" && event.message.errorMessage === PROVIDER_ISSUE && retry.enabled && this.session.retryAttempt < retry.maxRetries) {
61
+ // Change only the display copy: Pi still recognises the original error for retries.
62
+ event = { ...event, message: { ...event.message, errorMessage: "Klui had a model provider issue. Retrying…" } };
63
+ }
64
+ return handle.call(this, event);
65
+ };
51
66
  }
52
67
  /** Klui uses event models, so don't load Pi's local llama.cpp manager or its /llama command. */
53
68
  async function removeLlama() {
@@ -329,6 +344,23 @@ async function quietPiHints(config) {
329
344
  showStatus.call(this, name ? `${match[1] === "Model" ? "Using" : "Default is now"} ${name}` : message);
330
345
  };
331
346
  }
347
+ /**
348
+ * Pi shrinks a large pasted image and adds a note to the prompt's text ("[Image: original 2086x1416,
349
+ * displayed at 2000x1358. Multiply coordinates by…]", or "[Image converted from…]"), which is then
350
+ * saved and shown as part of what the person typed. Klui never maps pixel coordinates, so drop
351
+ * those notes. Keep "[Image omitted…]": the model should know an image didn't reach it.
352
+ */
353
+ async function quietImageNotes() {
354
+ const { AgentSession } = await piModule("./core/agent-session.js");
355
+ const proto = AgentSession.prototype;
356
+ const normalize = proto._normalizePromptImages;
357
+ if (typeof normalize !== "function")
358
+ return;
359
+ proto._normalizePromptImages = async function (images) {
360
+ const normalized = await normalize.call(this, images);
361
+ return { ...normalized, hints: normalized.hints.filter((hint) => hint.startsWith("[Image omitted")) };
362
+ };
363
+ }
332
364
  /** ctrl+v with an image on the clipboard puts an "[Image #1]" chip in the composer, not a temp path. */
333
365
  async function pasteImageChips() {
334
366
  const { InteractiveMode } = await piModule("./modes/interactive/interactive-mode.js");
@@ -351,6 +383,51 @@ async function pasteImageChips() {
351
383
  editor.insertTextAtCursor = insert;
352
384
  else
353
385
  delete editor.insertTextAtCursor;
386
+ clipboardEvent("pasted");
354
387
  }
355
388
  };
356
389
  }
390
+ /**
391
+ * Tells the clipboard hint (clipboard-hint.ts) when the terminal window gets focus back and when
392
+ * Klui copies something itself. Pi's fullscreen mode turns on focus reports and swallows them.
393
+ */
394
+ async function clipboardEvents() {
395
+ const alt = TuiAltScreen.prototype;
396
+ const viewportInput = alt.handleViewportInput;
397
+ if (typeof viewportInput === "function") {
398
+ alt.handleViewportInput = function (data) {
399
+ if (data === "\x1b[I")
400
+ clipboardEvent("focus");
401
+ return viewportInput.call(this, data);
402
+ };
403
+ }
404
+ // Every Pi copy confirms with "Copied!" or "Copied … to clipboard", and only once it's copied.
405
+ const copied = (message) => typeof message === "string" && message.startsWith("Copied") && clipboardEvent("copied");
406
+ const flash = alt.flash;
407
+ if (typeof flash === "function") {
408
+ alt.flash = function (message, durationMs) {
409
+ flash.call(this, message, durationMs);
410
+ copied(message);
411
+ };
412
+ }
413
+ const { InteractiveMode } = await piModule("./modes/interactive/interactive-mode.js");
414
+ // Right-click pastes text straight into the composer, past the terminal input listeners.
415
+ const rightClick = InteractiveMode.prototype.handleRightClickPaste;
416
+ if (typeof rightClick === "function") {
417
+ InteractiveMode.prototype.handleRightClickPaste = async function () {
418
+ try {
419
+ await rightClick.call(this);
420
+ }
421
+ finally {
422
+ clipboardEvent("pasted");
423
+ }
424
+ };
425
+ }
426
+ const status = InteractiveMode.prototype.showStatus;
427
+ if (typeof status !== "function")
428
+ return;
429
+ InteractiveMode.prototype.showStatus = function (message) {
430
+ status.call(this, message);
431
+ copied(message);
432
+ };
433
+ }
package/dist/update.js CHANGED
@@ -16,6 +16,9 @@ export function installKind(dir = PACKAGE_DIR) {
16
16
  // npm folder has none.
17
17
  try {
18
18
  const pkg = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
19
+ // The copy bundled inside Klui Code desktop, which updates with the app.
20
+ if (pkg?.kluiDesktop === true)
21
+ return { kind: "desktop" };
19
22
  if (pkg?.dependencies?.[PACKAGE])
20
23
  return { kind: "prefix", root };
21
24
  }
@@ -56,6 +59,8 @@ export async function update(onStart = () => { }) {
56
59
  const install = installKind();
57
60
  if (install.kind === "source")
58
61
  return { status: "failed", message: "This klui runs from a source checkout. Update it with git pull && npm install." };
62
+ if (install.kind === "desktop")
63
+ return { status: "failed", message: "This klui comes with the Klui Code desktop app. Update it with the update button in the app's sidebar." };
59
64
  const latest = await latestVersion(10_000);
60
65
  if (!latest)
61
66
  return { status: "failed", message: "Couldn't reach the npm registry. Check your connection and try again." };
@@ -77,7 +82,8 @@ export async function update(onStart = () => { }) {
77
82
  * ~/.klui). Undefined when up to date, offline, or running from source.
78
83
  */
79
84
  export async function availableUpdate() {
80
- if (installKind().kind === "source")
85
+ const kind = installKind().kind;
86
+ if (kind === "source" || kind === "desktop")
81
87
  return undefined;
82
88
  let latest;
83
89
  try {
package/dist/usage.js CHANGED
@@ -20,6 +20,7 @@ export const PARENT_SESSION_ENV = "KLUI_PARENT_SESSION";
20
20
  export function recordUsage(streamSimple, agent = "main", paths = PATHS) {
21
21
  return ((...args) => {
22
22
  const start = Date.now();
23
+ const requested = args[0];
23
24
  const options = args[2];
24
25
  const session = process.env[PARENT_SESSION_ENV] || options?.sessionId;
25
26
  const stream = streamSimple(...args);
@@ -39,7 +40,7 @@ export function recordUsage(streamSimple, agent = "main", paths = PATHS) {
39
40
  const end = Date.now();
40
41
  const error = reply?.providerError || reply?.errorMessage;
41
42
  const timing = { start, ttft: firstAt === undefined ? undefined : firstAt - start, ms: end - start };
42
- appendEntry({ t: end, ...tokens(reply?.usage), model: reply?.responseModel ?? reply?.model, agent, ...timing, session, error: error?.slice(0, 1000) }, paths);
43
+ appendEntry({ t: end, ...tokens(reply?.usage), model: reply?.responseModel ?? reply?.model ?? requested?.id, requestedModel: requested?.id ?? reply?.model ?? reply?.responseModel, agent, ...timing, session, error: error?.slice(0, 1000) }, paths);
43
44
  };
44
45
  stream.result().then(log, () => log(undefined));
45
46
  return stream;
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "klui-code",
3
- "version": "0.1.6",
3
+ "version": "0.1.8",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "klui-code",
9
- "version": "0.1.6",
9
+ "version": "0.1.8",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@earendil-works/chord": "1.1.0",
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "klui-code",
3
- "version": "0.1.6",
4
- "description": "Klui Code: a pixel-cute coding agent for your terminal, built on Pi and running on AntSeed.",
3
+ "version": "0.1.8",
4
+ "description": "Klui Code: a pixel-cute coding agent for your terminal, built on Pi and running on Surplus and AntSeed.",
5
5
  "keywords": [
6
6
  "klui",
7
7
  "coding-agent",