klui-code 0.1.5 → 0.1.7

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
  ```
@@ -40,7 +41,6 @@ Klui warns when the selected model can only read text.
40
41
  |---|---|
41
42
  | `/klui` | about card: model, credits left, links |
42
43
  | `/klui model` | pick one of the event models |
43
- | `/klui theme` | `klui-dark`, `klui-light` or `klui-arcade` (default follows your terminal) |
44
44
  | `/klui credits` | credits left on your pass |
45
45
  | `/klui retry` | reconnect after a wifi hiccup |
46
46
  | `/sessions` or `/resume` | pick up an earlier chat |
@@ -82,19 +82,25 @@ in `~/.klui` and never touches an existing pi setup.
82
82
  ```
83
83
  klui ──(1) device id──▶ Klui Pass ──▶ key from a pre-made pool
84
84
  │
85
- └──(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
86
88
  ```
87
89
 
88
- - **One funded account.** Klui runs a single AntSeed buyer holding the event wallet, behind
89
- AntSeed's own API-key gateway. Every attendee key is paid by that one wallet, and the gateway
90
- 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.
91
97
  - **Klui Pass** (`server/`) hands each device a key from a pool and serves the event's model list,
92
98
  so models can change mid-event without a new release. It never sees prompts or code: klui talks to
93
- the gateway directly.
99
+ the router directly.
94
100
  - **The CLI** is pi with one extension (`src/extension/`): the `klui` provider, the pixel header,
95
- the working line (a shimmering phrase, the time and tokens in one small box), the footer, one-line tool
101
+ the working line (a shimmering phrase, the time and tokens in one small box), the footer, labeled tool
96
102
  rows, the `subagent` tool (each subagent is a child `klui --mode json` process), `/klui`,
97
- `/sessions`, and three themes (`themes/`).
103
+ `/sessions`, and one look in dark and light (`themes/`), picked to match the terminal.
98
104
  - **Web access** (`src/extension/web.ts`): `web_search` and `web_fetch`. They run on the
99
105
  attendee's own machine with keyless services (Exa, then DuckDuckGo), never through Klui Pass, so
100
106
  every attendee has their own limits. Fetched pages return their full extracted text; downloads
@@ -120,7 +126,7 @@ it for global installs, so transitive packages can still move within their own s
120
126
  |---|---|
121
127
  | `KLUI_PASS_URL` | Klui Pass to use (default `https://klui.ai/code/pass`) |
122
128
  | `KLUI_HOME` | where klui keeps its state (default `~/.klui`) |
123
- | `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 |
124
130
  | `KLUI_REDUCED_MOTION=1` | no animations |
125
131
 
126
132
  To try the whole flow locally against free AntSeed sellers, run an AntSeed buyer and gateway, make
package/dist/cli.js CHANGED
@@ -25,7 +25,8 @@ function seedSettings(config, piVersion) {
25
25
  // First run, or unreadable: start fresh.
26
26
  }
27
27
  const ids = new Set(config.models.map((m) => m.id));
28
- settings.theme ??= "klui-light/klui-dark";
28
+ // Klui has one look: dark, or light on a light terminal. Earlier versions let people pick others.
29
+ settings.theme = "klui-light/klui-dark";
29
30
  // Klui draws its own header, so Pi's logo and key hints would only flash up first.
30
31
  settings.quietStartup = true;
31
32
  settings.enabledModels ??= [`${PROVIDER}/*`];
@@ -112,7 +113,9 @@ async function run() {
112
113
  const loaded = loadConfig();
113
114
  seedSettings(loaded.config, pi.VERSION);
114
115
  seedKeybindings();
115
- 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");
116
119
  const { createKluiExtension } = await import("./extension/index.js");
117
120
  await pi.main([...args, "--theme", THEMES_DIR], {
118
121
  extensionFactories: [{ name: "klui", factory: createKluiExtension(loaded), hidden: true }],
@@ -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();
@@ -1,4 +1,4 @@
1
- // /klui: an about card, plus quick pickers for the event models and Klui themes. /sessions: the
1
+ // /klui: an about card, plus a quick picker for the event models. /sessions: the
2
2
  // earlier chats, to pick one up again. /usage: tokens used in the last 24 hours and overall.
3
3
  import { SessionManager, SessionSelectorComponent } from "@earendil-works/pi-coding-agent";
4
4
  import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
@@ -9,27 +9,19 @@ import { renderPixels } from "../pixels.js";
9
9
  import { update } from "../update.js";
10
10
  import { readUsage } from "../usage.js";
11
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
12
  const SUBCOMMANDS = [
18
13
  { value: "model", label: "model", description: "pick one of the event models" },
19
- { value: "theme", label: "theme", description: "switch Klui themes" },
20
14
  { value: "credits", label: "credits", description: "check the credits left on your key" },
21
15
  { value: "retry", label: "retry", description: "reconnect to Klui after a network hiccup" },
22
16
  ];
23
17
  export function registerCommands(pi, actions) {
24
18
  pi.registerCommand("klui", {
25
- description: "About Klui, models, themes and credits",
19
+ description: "About Klui, models and credits",
26
20
  getArgumentCompletions: (prefix) => SUBCOMMANDS.filter((s) => s.value.startsWith(prefix.trim())),
27
21
  handler: async (args, ctx) => {
28
22
  const sub = args.trim().toLowerCase();
29
23
  if (sub === "model" || sub === "models")
30
24
  return pickModel(pi, ctx);
31
- if (sub === "theme" || sub === "themes")
32
- return pickTheme(ctx);
33
25
  if (sub === "retry")
34
26
  return actions.reconnect(ctx);
35
27
  if (sub === "credits") {
@@ -112,16 +104,6 @@ async function pickModel(pi, ctx) {
112
104
  ctx.ui.notify(`Switched to ${picked.name}`, "info");
113
105
  showThinkingMenu();
114
106
  }
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
107
  function aboutCard(theme, done) {
126
108
  const border = (s) => theme.fg("borderAccent", s);
127
109
  return {
@@ -151,7 +133,7 @@ function aboutCard(theme, done) {
151
133
  "",
152
134
  ];
153
135
  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"));
136
+ body.push("", theme.fg("dim", "/klui model · /klui credits · /usage any key to close"));
155
137
  const pad = (line) => {
156
138
  const fitted = truncateToWidth(line, inner, "");
157
139
  return `${border("│")} ${fitted}${" ".repeat(Math.max(0, inner - visibleWidth(fitted)))} ${border("│")}`;
@@ -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
+ }
@@ -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
  });
@@ -1,8 +1,9 @@
1
- // Tool calls drawn the way Claude Code draws them: "● Update(src/app.ts)" with the outcome under
2
- // it, "⎿ Updated src/app.ts with 4 additions and 1 removal", and edits shown as a short diff. Click
3
- // a row, or press the expand key, to see the call and its output drawn the way Pi normally draws them.
1
+ // Tool calls drawn as a labeled row: the tool's name in a label colored by how it's going, then
2
+ // what it works on, "[ Update ] src/app.ts", with the outcome under it, "⎿ Updated src/app.ts with 4
3
+ // additions and 1 removal", and edits shown as a short diff. Click a row, or press the expand key,
4
+ // to see the call and its output drawn the way Pi normally draws them.
4
5
  import { keyText, renderDiff } from "@earendil-works/pi-coding-agent";
5
- import { Box, Container, Text, truncateToWidth } from "@earendil-works/pi-tui";
6
+ import { Box, Container, indexedColor, parseColor, styleText, Text, truncateToWidth } from "@earendil-works/pi-tui";
6
7
  import { isAbsolute, relative } from "node:path";
7
8
  import { agentLines, formatTokens } from "./agents.js";
8
9
  import { DECLINED } from "./permissions.js";
@@ -36,28 +37,41 @@ class Lines {
36
37
  invalidate() { }
37
38
  }
38
39
  const NOTHING = new Container();
40
+ /**
41
+ * Label colors, text then background: lavender while the tool runs, Klui blue when done, red when it
42
+ * failed. Terminals without 24-bit color (Apple's Terminal) get the 256-color numbers picked to
43
+ * match; rounding the deep backgrounds there would turn the blue label teal.
44
+ */
45
+ const LABELS = {
46
+ dark: { running: ["#b9a8ff", "#2a2350", 147, 60], done: ["#8fd3fb", "#1f3358", 117, 24], failed: ["#ff7a85", "#3d1d26", 210, 52] },
47
+ light: { running: ["#5b3fc4", "#ece6ff", 61, 189], done: ["#1585c9", "#dbe7fb", 25, 153], failed: ["#d43c4c", "#fde8ea", 160, 224] },
48
+ };
49
+ function label(name, status, theme) {
50
+ const [fg, bg, fg256, bg256] = LABELS[theme.appearance === "light" ? "light" : "dark"][status];
51
+ const mode = theme.getColorMode();
52
+ const colors = mode === "truecolor" ? { fg: parseColor(fg), bg: parseColor(bg) } : { fg: indexedColor(fg256), bg: indexedColor(bg256) };
53
+ return styleText(` ${name} `, { ...colors, bold: true }, mode);
54
+ }
39
55
  function compactCall(toolName, args, theme, context) {
40
56
  const state = context.state;
41
57
  state.kluiHead ??= new Lines();
42
- // The dot stays dim until the result colors it.
58
+ // Lavender until the result colors it.
43
59
  if (!state.kluiBody)
44
- state.kluiHead.set([`${theme.fg("dim", "●")} ${title(toolName, args, theme, context.cwd)}`], context.outputPad);
60
+ state.kluiHead.set([title(toolName, args, "running", theme, context.cwd)], context.outputPad);
45
61
  return state.kluiHead;
46
62
  }
47
63
  function compactResult(toolName, result, theme, context) {
48
64
  const state = context.state;
49
65
  state.kluiBody ??= new Lines();
50
- const head = title(toolName, context.args, theme, context.cwd);
51
66
  if (context.isPartial) {
52
67
  // Long-running tools (subagents) say what they're up to under the call.
53
68
  const d = result.details;
54
- state.kluiHead?.set([`${theme.fg("dim", "●")} ${head}`], context.outputPad);
69
+ state.kluiHead?.set([title(toolName, context.args, "running", theme, context.cwd)], context.outputPad);
55
70
  const live = toolName === "subagent" && d?.startedAt !== undefined ? agentLines(d, theme) : d?.progress ? [theme.fg("dim", d.progress)] : [];
56
71
  state.kluiBody.set(under(theme, live), context.outputPad);
57
72
  return state.kluiBody;
58
73
  }
59
- const dot = context.isError ? theme.fg("error", "●") : theme.fg("success", "●");
60
- state.kluiHead?.set([`${dot} ${head}`], context.outputPad);
74
+ state.kluiHead?.set([title(toolName, context.args, context.isError ? "failed" : "done", theme, context.cwd)], context.outputPad);
61
75
  const lines = context.isError ? errorLines(result, theme) : outcome(toolName, context.args, result, theme, context.cwd);
62
76
  const time = context.durationMs !== undefined && context.durationMs >= 1000 ? theme.fg("dim", ` · ${(context.durationMs / 1000).toFixed(1)}s`) : "";
63
77
  if (lines[0] !== undefined)
@@ -65,9 +79,9 @@ function compactResult(toolName, result, theme, context) {
65
79
  state.kluiBody.set(under(theme, lines), context.outputPad);
66
80
  return state.kluiBody;
67
81
  }
68
- /** Hang lines under the call: the first after "⎿", the rest lined up with it. */
82
+ /** Hang lines under the call: the first after "⎿", under the label's first letter, the rest lined up with it. */
69
83
  function under(theme, lines) {
70
- return lines.map((line, i) => `${i === 0 ? ` ${theme.fg("dim", "⎿")} ` : " "}${line}`);
84
+ return lines.map((line, i) => `${i === 0 ? ` ${theme.fg("dim", "⎿")} ` : " "}${line}`);
71
85
  }
72
86
  const NAMES = {
73
87
  read: "Read",
@@ -84,10 +98,10 @@ const NAMES = {
84
98
  screenshot: "Screenshot",
85
99
  todo: "Todos",
86
100
  };
87
- function title(toolName, args, theme, cwd) {
101
+ function title(toolName, args, status, theme, cwd) {
88
102
  const a = (args ?? {});
89
- const name = theme.bold(NAMES[toolName] ?? toolName);
90
- const arg = (text) => (text ? `${theme.fg("muted", "(")}${text}${theme.fg("muted", ")")}` : "");
103
+ const name = label(NAMES[toolName] ?? toolName, status, theme);
104
+ const arg = (text) => (text ? ` ${text}` : "");
91
105
  const path = (value) => shortPath(typeof value === "string" ? value : ".", cwd);
92
106
  switch (toolName) {
93
107
  case "read":
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);
@@ -7,11 +7,13 @@ import { chipFor, isClipboardImageFile } from "./images.js";
7
7
  import { PROVIDER } from "./paths.js";
8
8
  import { scrollFrame } from "./scroll.js";
9
9
  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();
10
+ /** `machineOutput`: `--mode json` or `rpc`, where every stdout line is JSON for another program to parse. */
11
+ export async function patchPi(config, machineOutput = false) {
12
+ if (!machineOutput)
13
+ brandOutput();
12
14
  scrollWithTerminal();
13
15
  clearAfterCopy();
14
- for (const patch of [() => sellerModelIds(config), retryProviderIssues, removeLlama, hidePiFooter, hoverJumpToLatest, queuedMessages, trimSlashMenu, slashAliases, simpleThinkingMenu, thinkingAfterModel, () => tidyModelPicker(), () => quietPiHints(config), pasteImageChips])
16
+ for (const patch of [() => sellerModelIds(config), retryProviderIssues, removeLlama, hidePiFooter, hoverJumpToLatest, queuedMessages, trimSlashMenu, slashAliases, simpleThinkingMenu, thinkingAfterModel, () => tidyModelPicker(), () => quietPiHints(config), pasteImageChips, quietImageNotes])
15
17
  await patch().catch(() => { });
16
18
  }
17
19
  /**
@@ -48,6 +50,18 @@ async function retryProviderIssues() {
48
50
  proto._isRetryableError = function (message) {
49
51
  return message.errorMessage === PROVIDER_ISSUE || isRetryable.call(this, message);
50
52
  };
53
+ const { InteractiveMode } = await piModule("./modes/interactive/interactive-mode.js");
54
+ const handle = InteractiveMode.prototype.handleEvent;
55
+ if (typeof handle !== "function")
56
+ return;
57
+ InteractiveMode.prototype.handleEvent = function (event) {
58
+ const retry = this.settingsManager.getRetrySettings();
59
+ if (event.type === "message_end" && event.message?.role === "assistant" && event.message.errorMessage === PROVIDER_ISSUE && retry.enabled && this.session.retryAttempt < retry.maxRetries) {
60
+ // Change only the display copy: Pi still recognises the original error for retries.
61
+ event = { ...event, message: { ...event.message, errorMessage: "Klui had a model provider issue. Retrying…" } };
62
+ }
63
+ return handle.call(this, event);
64
+ };
51
65
  }
52
66
  /** Klui uses event models, so don't load Pi's local llama.cpp manager or its /llama command. */
53
67
  async function removeLlama() {
@@ -180,11 +194,12 @@ function rebrand(text) {
180
194
  /**
181
195
  * Klui's slash menu: /resume and /exit (see slashAliases) open /sessions and quit. Pi's /session,
182
196
  * its bug reporter (it files issues with the Pi developers), its changelog and /scoped-models stay
183
- * out of the list; they still work when typed. Provider login/logout are removed as well.
197
+ * out of the list; they still work when typed. Provider login/logout and /settings (its themes and
198
+ * options aren't Klui's to change) are removed as well.
184
199
  */
185
200
  async function trimSlashMenu() {
186
201
  const { BUILTIN_SLASH_COMMANDS: commands } = await piModule("./core/slash-commands.js");
187
- const hidden = new Set(["session", "bug", "changelog", "scoped-models", "login", "logout"]);
202
+ const hidden = new Set(["session", "bug", "changelog", "scoped-models", "login", "logout", "settings"]);
188
203
  for (let i = commands.length - 1; i >= 0; i--)
189
204
  if (hidden.has(commands[i].name))
190
205
  commands.splice(i, 1);
@@ -201,7 +216,7 @@ export function showThinkingMenu() {
201
216
  if (interactive?.session.supportsThinking())
202
217
  interactive.showThinkingSelector();
203
218
  }
204
- /** Session aliases and event-pass guidance in place of provider login/logout. */
219
+ /** Session aliases, and a word in place of provider login/logout and /settings. */
205
220
  async function slashAliases() {
206
221
  const { InteractiveMode } = await piModule("./modes/interactive/interactive-mode.js");
207
222
  const proto = InteractiveMode.prototype;
@@ -220,6 +235,10 @@ async function slashAliases() {
220
235
  this.showError("Klui connects with your event pass automatically. Use /klui retry to reconnect.");
221
236
  return;
222
237
  }
238
+ if (/^\/settings(\s|$)/.test(text.trim())) {
239
+ this.showError("Klui has no settings menu. Use /model to switch models and /thinking for reasoning.");
240
+ return;
241
+ }
223
242
  await submit(aliases[text.trim()] ?? text);
224
243
  };
225
244
  };
@@ -324,6 +343,23 @@ async function quietPiHints(config) {
324
343
  showStatus.call(this, name ? `${match[1] === "Model" ? "Using" : "Default is now"} ${name}` : message);
325
344
  };
326
345
  }
346
+ /**
347
+ * Pi shrinks a large pasted image and adds a note to the prompt's text ("[Image: original 2086x1416,
348
+ * displayed at 2000x1358. Multiply coordinates by…]", or "[Image converted from…]"), which is then
349
+ * saved and shown as part of what the person typed. Klui never maps pixel coordinates, so drop
350
+ * those notes. Keep "[Image omitted…]": the model should know an image didn't reach it.
351
+ */
352
+ async function quietImageNotes() {
353
+ const { AgentSession } = await piModule("./core/agent-session.js");
354
+ const proto = AgentSession.prototype;
355
+ const normalize = proto._normalizePromptImages;
356
+ if (typeof normalize !== "function")
357
+ return;
358
+ proto._normalizePromptImages = async function (images) {
359
+ const normalized = await normalize.call(this, images);
360
+ return { ...normalized, hints: normalized.hints.filter((hint) => hint.startsWith("[Image omitted")) };
361
+ };
362
+ }
327
363
  /** ctrl+v with an image on the clipboard puts an "[Image #1]" chip in the composer, not a temp path. */
328
364
  async function pasteImageChips() {
329
365
  const { InteractiveMode } = await piModule("./modes/interactive/interactive-mode.js");
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.5",
3
+ "version": "0.1.7",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "klui-code",
9
- "version": "0.1.5",
9
+ "version": "0.1.7",
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.5",
4
- "description": "Klui Code: a pixel-cute coding agent for your terminal, built on Pi and running on AntSeed.",
3
+ "version": "0.1.7",
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",
@@ -1,81 +0,0 @@
1
- {
2
- "$schema": "https://raw.githubusercontent.com/earendil-works/pi/main/packages/coding-agent/src/modes/interactive/theme/theme-schema.json",
3
- "name": "klui-arcade",
4
- "appearance": "dark",
5
- "vars": {
6
- "text": "#f2ecff",
7
- "muted": "#b0a3d4",
8
- "dim": "#7d6fa6",
9
- "line": "#43356b",
10
- "sky": "#5fe3ff",
11
- "blue": "#8f7bff",
12
- "soft": "#c3b6ff",
13
- "pink": "#ff5fd2",
14
- "mint": "#a6ff4d",
15
- "coral": "#ff5f6d",
16
- "sun": "#ffe14d"
17
- },
18
- "colors": {
19
- "accent": "sky",
20
- "border": "blue",
21
- "borderAccent": "sky",
22
- "borderMuted": "line",
23
- "success": "mint",
24
- "error": "coral",
25
- "warning": "sun",
26
- "muted": "muted",
27
- "dim": "dim",
28
- "text": "text",
29
- "thinkingText": "muted",
30
- "selectedBg": "#35206b",
31
- "scrollbarTrack": "line",
32
- "scrollbarThumb": "muted",
33
- "searchMatchBg": "#5a4a00",
34
- "searchMatchText": "text",
35
- "userMessageBg": "#24164a",
36
- "userMessageText": "text",
37
- "customMessageBg": "#2e1240",
38
- "customMessageText": "muted",
39
- "customMessageLabel": "pink",
40
- "toolPendingBg": "#1c1433",
41
- "toolSuccessBg": "#18301a",
42
- "toolErrorBg": "#3a1424",
43
- "toolTitle": "text",
44
- "toolOutput": "muted",
45
- "mdHeading": "sky",
46
- "mdLink": "blue",
47
- "mdLinkUrl": "dim",
48
- "mdCode": "pink",
49
- "mdCodeBlock": "text",
50
- "mdCodeBlockBorder": "line",
51
- "mdQuote": "muted",
52
- "mdQuoteBorder": "blue",
53
- "mdHr": "line",
54
- "mdListBullet": "sky",
55
- "toolDiffAdded": "mint",
56
- "toolDiffRemoved": "coral",
57
- "toolDiffContext": "dim",
58
- "syntaxComment": "dim",
59
- "syntaxKeyword": "blue",
60
- "syntaxFunction": "sky",
61
- "syntaxVariable": "text",
62
- "syntaxString": "mint",
63
- "syntaxNumber": "sun",
64
- "syntaxType": "pink",
65
- "syntaxOperator": "muted",
66
- "syntaxPunctuation": "muted",
67
- "thinkingOff": "line",
68
- "thinkingMinimal": "dim",
69
- "thinkingLow": "soft",
70
- "thinkingMedium": "sky",
71
- "thinkingHigh": "blue",
72
- "thinkingXhigh": "pink",
73
- "thinkingMax": "coral",
74
- "bashMode": "mint"
75
- },
76
- "export": {
77
- "pageBg": "#120b24",
78
- "cardBg": "#1a1132",
79
- "infoBg": "#24164a"
80
- }
81
- }