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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Arya Sankhe
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,123 @@
1
- # Temporary Holding Version
1
+ # Klui Code
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
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)
5
+ and Klui covers the bill.
6
+
7
+ ```
8
+ curl -fsSL https://klui.ai/code/install.sh | sh
9
+ klui
10
+ ```
11
+
12
+ That's it: no account, no API key, no wallet. The installer brings its own Node.js if yours is
13
+ missing or older than 22.19, and puts everything in `~/.klui`. On first launch klui gets your
14
+ device its own event pass and picks the default model.
15
+
16
+ Already on Node 22.19+? `npm install -g klui-code` works too (and is the way on Windows).
17
+
18
+ ## Using it
19
+
20
+ Type what you want built and press enter. Klui reads files, edits code and runs commands in the
21
+ folder you started it from.
22
+
23
+ Paste a clipboard image with `ctrl+v`: it appears as an `[Image #1]` chip and is sent with your
24
+ message. You can also drag an image file into the terminal. Pick a model that supports images;
25
+ Klui warns when the selected model can only read text.
26
+
27
+ | | |
28
+ |---|---|
29
+ | `/klui` | about card: model, credits left, links |
30
+ | `/klui model` | pick one of the event models |
31
+ | `/klui theme` | `klui-dark`, `klui-light` or `klui-arcade` (default follows your terminal) |
32
+ | `/klui credits` | credits left on your pass |
33
+ | `/klui retry` | reconnect after a wifi hiccup |
34
+ | `/sessions` or `/resume` | pick up an earlier chat |
35
+ | `/update` | install the latest klui (or `klui update` in your shell); restart to use it |
36
+ | `/usage` | tokens and messages in the last 24 hours and overall, subagents included |
37
+ | `shift+tab` | permission mode: **ask** (asks before edits and commands), **auto** (works freely in the project, asks before risky commands and changes outside it), **yolo** (never asks) |
38
+ | `alt+t` | cycle reasoning level (low, medium, high; picked after each model switch) |
39
+ | `ctrl+l` | model picker |
40
+ | `ctrl+o` / `ctrl+t` | expand tool calls / reasoning (collapsed to a short summary, like Claude Code) |
41
+ | `!cmd` | run a shell command yourself |
42
+ | `enter` while Klui works | queue a message; it goes in after the current step (`alt+↑` to edit queued messages) |
43
+ | `esc` | stop Klui mid-run |
44
+ | `/` | every other command |
45
+
46
+ When Klui asks, answer yes, yes and don't ask again this session, no (which stops the turn), or no
47
+ with a note for Klui. Reads and searches never ask. Klui starts in auto mode each launch.
48
+
49
+ For a big job, ask Klui to use subagents: each is a fresh Klui with its own context, read-only
50
+ (`explore`) or able to edit (`general`), on any event model. Several can run at once, and a
51
+ background one reports back when it's done while Klui keeps working.
52
+
53
+ For multi-step work Klui keeps a todo list above the editor, so you can see what it's on, what's
54
+ done and what's next. The list is saved with the chat, so it survives `/resume` and compaction.
55
+
56
+ When Klui has changed files and is about to finish, it checks them with the project's own tools:
57
+ its TypeScript compiler, ruff or Python's parser, Node's syntax check and a JSON parse. If its
58
+ changes broke something, it gets the errors back and fixes them first. Only errors its own changes
59
+ caused count, and it never installs, formats or rewrites anything on its own.
60
+
61
+ klui is built on [pi](https://github.com/earendil-works/pi), so pi's commands, sessions
62
+ (`klui -c` continues the last one), skills and `AGENTS.md` files all work. It keeps its own config
63
+ in `~/.klui` and never touches an existing pi setup.
64
+
65
+ ## How it works
66
+
67
+ ```
68
+ klui ──(1) device id──▶ Klui Pass ──▶ key from a pre-made pool
69
+ │
70
+ └──(2) chat + tools, Bearer <key>──▶ AntSeed gateway ──▶ AntSeed buyer (event wallet) ──▶ sellers
71
+ ```
72
+
73
+ - **One funded account.** Klui runs a single AntSeed buyer holding the event wallet, behind
74
+ AntSeed's own API-key gateway. Every attendee key is paid by that one wallet, and the gateway
75
+ enforces each key's spend cap.
76
+ - **Klui Pass** (`server/`) hands each device a key from a pool and serves the event's model list,
77
+ so models can change mid-event without a new release. It never sees prompts or code: klui talks to
78
+ the gateway directly.
79
+ - **The CLI** is pi with one extension (`src/extension/`): the `klui` provider, the pixel header,
80
+ the working line (a shimmering phrase, the time and tokens in one small box), the footer, one-line tool
81
+ rows, the `subagent` tool (each subagent is a child `klui --mode json` process), `/klui`,
82
+ `/sessions`, and three themes (`themes/`).
83
+ - **Web access** (`src/extension/web.ts`): `web_search` and `web_fetch`. They run on the
84
+ attendee's own machine with keyless services (Exa, then DuckDuckGo), never through Klui Pass, so
85
+ every attendee has their own limits.
86
+
87
+ Running the event? See [server/README.md](server/README.md).
88
+
89
+ ## Developing
90
+
91
+ ```
92
+ npm install # builds dist/ too
93
+ npm run dev # rebuild on change
94
+ npm test
95
+ node bin/klui.js # run without installing
96
+ ```
97
+
98
+ Pi is pinned: every `@earendil-works/*` package is an exact direct dependency, so a new Pi release
99
+ never reaches users until you upgrade it here, run the tests, and publish. `npm-shrinkwrap.json`
100
+ (shipped with the package) locks the rest for `npm ci`, but recent npm versions don't always honour
101
+ it for global installs, so transitive packages can still move within their own semver ranges.
102
+
103
+ | Env var | Purpose |
104
+ |---|---|
105
+ | `KLUI_PASS_URL` | Klui Pass to use (default `https://klui.ai/code/pass`) |
106
+ | `KLUI_HOME` | where klui keeps its state (default `~/.klui`) |
107
+ | `KLUI_API_KEY`, `KLUI_BASE_URL` | skip Pass and use this AntSeed gateway key directly |
108
+ | `KLUI_REDUCED_MOTION=1` | no animations |
109
+
110
+ To try the whole flow locally against free AntSeed sellers, run an AntSeed buyer and gateway, make
111
+ a small pool and start Pass (see [server/README.md](server/README.md#local-dry-run)), then
112
+ `KLUI_PASS_URL=http://127.0.0.1:8790 KLUI_HOME=/tmp/klui-home node bin/klui.js`.
113
+
114
+ ## Releasing
115
+
116
+ ```
117
+ npm version patch # or minor; commits and tags vX.Y.Z
118
+ git push --follow-tags # CI publishes the tag to npm (needs the NPM_TOKEN secret)
119
+ scp install.sh root@klui.ai:/srv/klui-code/install.sh # only when the installer changed
120
+ ```
121
+
122
+ `npm publish` runs the tests first and rebuilds `dist/` from scratch. Installed copies see the new
123
+ version within a day (or right away with `/update` or `klui update`).
package/bin/klui.js ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import "../dist/cli.js";
@@ -0,0 +1,99 @@
1
+ // The event's model list. Klui Pass serves the live version (so organizers can swap models during
2
+ // the event without a new release); this bundled copy is the fallback when it can't be reached.
3
+ export const BUNDLED_CONFIG = {
4
+ event: { name: "Klui Hackathon", tagline: "hackathon edition", url: "https://klui.ai" },
5
+ baseUrl: "https://klui.ai/code/v1",
6
+ defaultModel: "deepseek-v4.1-flash",
7
+ models: [
8
+ {
9
+ id: "deepseek-v4.1-flash",
10
+ name: "DeepSeek V4.1 Flash",
11
+ input: ["text", "image"],
12
+ tagline: "fast & snappy",
13
+ paid: true,
14
+ aliases: ["deepseek-v4-1-flash", "deepseek/deepseek-v4-1-flash", "deepseek/deepseek-v4.1-flash"],
15
+ reasoning: true,
16
+ compat: {
17
+ supportsStore: false,
18
+ supportsDeveloperRole: false,
19
+ maxTokensField: "max_tokens",
20
+ requiresReasoningContentOnAssistantMessages: true,
21
+ thinkingFormat: "deepseek",
22
+ },
23
+ thinkingLevelMap: { max: "max" },
24
+ },
25
+ {
26
+ id: "mimo-v2.6-flash",
27
+ name: "MiMo V2.6 Flash",
28
+ tagline: "fast & efficient",
29
+ paid: true,
30
+ aliases: ["xiaomi/mimo-v2.6-flash", "xiaomi/mimo-v2-6-flash", "xiaomi-mimo-v2-6-flash"],
31
+ reasoning: true,
32
+ compat: {
33
+ supportsStore: false,
34
+ supportsDeveloperRole: false,
35
+ maxTokensField: "max_tokens",
36
+ requiresReasoningContentOnAssistantMessages: true,
37
+ thinkingFormat: "openai",
38
+ },
39
+ },
40
+ {
41
+ id: "glm-5.3-flash",
42
+ name: "GLM 5.3 Flash",
43
+ input: ["text", "image"],
44
+ tagline: "steady all-rounder",
45
+ paid: true,
46
+ aliases: ["glm-5-3-flash", "z-ai-glm-5-3-flash", "z-ai/glm-5.3-flash"],
47
+ reasoning: true,
48
+ compat: {
49
+ supportsStore: false,
50
+ supportsDeveloperRole: false,
51
+ supportsReasoningEffort: true,
52
+ maxTokensField: "max_tokens",
53
+ thinkingFormat: "openai",
54
+ },
55
+ thinkingLevelMap: { max: "max" },
56
+ },
57
+ ],
58
+ };
59
+ /** Keep only well-formed entries so a bad server response can't break startup. */
60
+ export function sanitizeConfig(raw) {
61
+ if (!raw || typeof raw !== "object")
62
+ return undefined;
63
+ const value = raw;
64
+ const models = Array.isArray(value.models)
65
+ ? value.models
66
+ .filter((m) => !!m && typeof m.id === "string" && typeof m.name === "string")
67
+ .map((m) => (m.aliases === undefined || Array.isArray(m.aliases) ? m : { ...m, aliases: undefined }))
68
+ : [];
69
+ if (models.length === 0 || typeof value.baseUrl !== "string")
70
+ return undefined;
71
+ const defaultModel = typeof value.defaultModel === "string" && models.some((m) => m.id === value.defaultModel)
72
+ ? value.defaultModel
73
+ : models[0].id;
74
+ const event = value.event && typeof value.event.name === "string" ? value.event : BUNDLED_CONFIG.event;
75
+ return { event, baseUrl: value.baseUrl.replace(/\/+$/, ""), defaultModel, models };
76
+ }
77
+ export function toProviderModels({ models }) {
78
+ return models.map((m) => ({
79
+ id: m.id,
80
+ name: m.name,
81
+ reasoning: m.reasoning ?? false,
82
+ input: m.input ?? ["text"],
83
+ // Attendees don't pay per token, so Pi shows no cost; remaining credits come from the key instead.
84
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
85
+ // Sellers on the network advertise different limits; stay inside what all of them accept.
86
+ contextWindow: m.contextWindow ?? 200_000,
87
+ maxTokens: m.maxTokens ?? 32_768,
88
+ ...(m.compat ? { compat: m.compat } : {}),
89
+ ...(m.reasoning ? { thinkingLevelMap: thinkingLevels(m.thinkingLevelMap) } : {}),
90
+ }));
91
+ }
92
+ /**
93
+ * The reasoning levels Klui offers: low, medium and high on every reasoning model, plus whatever
94
+ * higher ones the model supports. Reasoning is never switched off. Applied here rather than in
95
+ * each config so the live config from Klui Pass gets the same menu.
96
+ */
97
+ function thinkingLevels(map = {}) {
98
+ return { ...map, off: null, minimal: null, low: map.low ?? "low", medium: map.medium ?? "medium", high: map.high ?? "high" };
99
+ }
package/dist/checks.js ADDED
@@ -0,0 +1,146 @@
1
+ // Fast checks on the files Klui changed, with the tools the project already has: its own
2
+ // TypeScript compiler, ruff or Python's parser, Node's syntax check and JSON.parse. Nothing is
3
+ // installed, formatted or fixed; the problems go back to the model to deal with.
4
+ import { execFile } from "node:child_process";
5
+ import { existsSync, readFileSync } from "node:fs";
6
+ import { basename, delimiter, dirname, extname, join, resolve } from "node:path";
7
+ const TS = new Set([".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs"]);
8
+ const NODE = new Set([".js", ".mjs", ".cjs"]);
9
+ const TIMEOUT_MS = 60_000;
10
+ /**
11
+ * The TypeScript projects a file (or a tsconfig) belongs to: the nearest tsconfig.json and the
12
+ * projects it references. One that only points at others (Vite's, with `"files": []`) has nothing
13
+ * of its own to check.
14
+ */
15
+ export function tsProjects(file) {
16
+ const isConfig = /^tsconfig.*\.json$/.test(basename(file));
17
+ if (!TS.has(extname(file)) && !isConfig)
18
+ return [];
19
+ for (let dir = dirname(file);; dir = dirname(dir)) {
20
+ const config = join(dir, "tsconfig.json");
21
+ if (existsSync(config)) {
22
+ const json = readJsonc(config);
23
+ const refs = (Array.isArray(json?.references) ? json.references : [])
24
+ .map((r) => (typeof r?.path === "string" ? resolve(dir, r.path) : ""))
25
+ .map((p) => (p.endsWith(".json") ? p : join(p, "tsconfig.json")))
26
+ .filter((p) => existsSync(p));
27
+ const solutionOnly = refs.length > 0 && Array.isArray(json?.files) && json.files.length === 0 && !json.include;
28
+ const projects = solutionOnly ? refs : [config, ...refs];
29
+ // An edited config is checked itself, even one nothing references.
30
+ return isConfig && !projects.includes(file) ? [...projects, file] : projects;
31
+ }
32
+ if (dirname(dir) === dir)
33
+ return isConfig ? [file] : [];
34
+ }
35
+ }
36
+ /** Type errors in a project, from its own `tsc`. Undefined when it has no compiler installed. */
37
+ export async function typecheck(config) {
38
+ const dir = dirname(config);
39
+ const tsc = findUp(dir, join("node_modules", ".bin", process.platform === "win32" ? "tsc.cmd" : "tsc"));
40
+ if (!tsc)
41
+ return undefined;
42
+ const { stdout } = await run(tsc, ["--noEmit", "--pretty", "false", "-p", config], dir);
43
+ const problems = [];
44
+ for (const line of stdout.split("\n")) {
45
+ const m = /^(.+?)\((\d+),(\d+)\): error (TS\d+: .*)$/.exec(line);
46
+ const bare = /^error (TS\d+: .*)$/.exec(line); // no location, like a missing "types" package
47
+ if (m)
48
+ problems.push({ file: resolve(dir, m[1]), line: Number(m[2]), column: Number(m[3]), message: m[4] });
49
+ else if (bare)
50
+ problems.push({ file: config, message: bare[1] });
51
+ else if (/^\s+\S/.test(line) && problems.length)
52
+ problems.at(-1).message += ` ${line.trim()}`;
53
+ }
54
+ return problems;
55
+ }
56
+ /** Syntax and undefined-name errors in one file, for the languages that don't need a project. */
57
+ export async function checkFile(file) {
58
+ const ext = extname(file);
59
+ if (ext === ".json" && !/(^|[\\/])(ts|js)config[^\\/]*\.json$|[\\/]\.vscode[\\/]/.test(file)) {
60
+ try {
61
+ JSON.parse(readFileSync(file, "utf8"));
62
+ return [];
63
+ }
64
+ catch (error) {
65
+ return [{ file, message: error.message }];
66
+ }
67
+ }
68
+ if (NODE.has(ext)) {
69
+ const { stderr, failed } = await run(process.execPath, ["--check", file], dirname(file));
70
+ if (!failed)
71
+ return [];
72
+ const at = new RegExp(`${escape(file)}:(\\d+)`).exec(stderr);
73
+ const message = stderr.split("\n").find((l) => /^\w*Error\b/.test(l)) ?? "syntax error";
74
+ return [{ file, line: at ? Number(at[1]) : undefined, message }];
75
+ }
76
+ if (ext === ".py") {
77
+ const ruff = findUp(dirname(file), join(".venv", "bin", "ruff")) ?? onPath("ruff");
78
+ if (ruff) {
79
+ // Real errors only: syntax, undefined names, broken comparisons. No style rules.
80
+ const { stdout } = await run(ruff, ["check", "--select", "E9,F63,F7,F82", "--output-format", "concise", "--no-cache", file], dirname(file));
81
+ return stdout
82
+ .split("\n")
83
+ .map((l) => /^(.+?):(\d+):(\d+): (.+)$/.exec(l))
84
+ .filter((m) => m !== null)
85
+ .map((m) => ({ file, line: Number(m[2]), column: Number(m[3]), message: m[4] }));
86
+ }
87
+ const parse = "import ast,sys\ntry: ast.parse(open(sys.argv[1],'rb').read(), sys.argv[1])\nexcept SyntaxError as e: print(f'{e.lineno}\\t{e.msg}')";
88
+ const { stdout } = await run(onPath("python3") ?? "python3", ["-c", parse, file], dirname(file));
89
+ const [line, message] = stdout.trim().split("\t");
90
+ return message ? [{ file, line: Number(line), message: `SyntaxError: ${message}` }] : [];
91
+ }
92
+ return [];
93
+ }
94
+ /** Problems in `after` that weren't in `before`. Lines move as code is edited, so they're ignored. */
95
+ export function newProblems(before, after) {
96
+ const seen = new Map();
97
+ for (const p of before)
98
+ seen.set(key(p), (seen.get(key(p)) ?? 0) + 1);
99
+ return after.filter((p) => {
100
+ const left = seen.get(key(p)) ?? 0;
101
+ if (left > 0)
102
+ seen.set(key(p), left - 1);
103
+ return left === 0;
104
+ });
105
+ }
106
+ /** `src/app.ts:12:5 TS2322: Type 'string' is not assignable to type 'number'.` */
107
+ export function formatProblem(p, shortPath) {
108
+ const at = [shortPath(p.file), p.line, p.column].filter((part) => part !== undefined).join(":");
109
+ return `${at} ${p.message}`;
110
+ }
111
+ function key(p) {
112
+ return `${p.file}\0${p.message}`;
113
+ }
114
+ function run(command, args, cwd) {
115
+ return new Promise((done) => {
116
+ execFile(command, args, { cwd, timeout: TIMEOUT_MS, maxBuffer: 16 * 1024 * 1024, windowsHide: true }, (error, stdout, stderr) => done({ stdout: String(stdout), stderr: String(stderr), failed: error !== null }));
117
+ });
118
+ }
119
+ function findUp(dir, name) {
120
+ for (;; dir = dirname(dir)) {
121
+ if (existsSync(join(dir, name)))
122
+ return join(dir, name);
123
+ if (dirname(dir) === dir)
124
+ return undefined;
125
+ }
126
+ }
127
+ function onPath(name) {
128
+ for (const dir of (process.env.PATH ?? "").split(delimiter)) {
129
+ if (dir && existsSync(join(dir, name)))
130
+ return join(dir, name);
131
+ }
132
+ return undefined;
133
+ }
134
+ /** tsconfig files allow comments and trailing commas. */
135
+ function readJsonc(file) {
136
+ try {
137
+ const text = readFileSync(file, "utf8").replace(/("(?:\\.|[^"\\])*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (_, str) => str ?? "");
138
+ return JSON.parse(text.replace(/,(\s*[}\]])/g, "$1"));
139
+ }
140
+ catch {
141
+ return undefined;
142
+ }
143
+ }
144
+ function escape(text) {
145
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
146
+ }
package/dist/cli.js ADDED
@@ -0,0 +1,126 @@
1
+ // `klui`: Pi with the Klui extension and themes preloaded, in its own config directory so it never
2
+ // touches an existing Pi setup.
3
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
4
+ import { join } from "node:path";
5
+ import { loadConfig } from "./pass.js";
6
+ import { patchPi } from "./pi-patches.js";
7
+ import { AGENT_DIR, PROVIDER, THEMES_DIR, VERSION } from "./paths.js";
8
+ import { update } from "./update.js";
9
+ const MIN_NODE = [22, 19];
10
+ function nodeIsRecentEnough() {
11
+ const [major = 0, minor = 0] = process.versions.node.split(".").map(Number);
12
+ return major > MIN_NODE[0] || (major === MIN_NODE[0] && minor >= MIN_NODE[1]);
13
+ }
14
+ /**
15
+ * First-run defaults, plus a few values kept in line on every launch: the Klui model when the
16
+ * saved one isn't an event model, and no Pi changelog or install telemetry.
17
+ */
18
+ function seedSettings(config, piVersion) {
19
+ const file = join(AGENT_DIR, "settings.json");
20
+ let settings = {};
21
+ try {
22
+ settings = JSON.parse(readFileSync(file, "utf8"));
23
+ }
24
+ catch {
25
+ // First run, or unreadable: start fresh.
26
+ }
27
+ const ids = new Set(config.models.map((m) => m.id));
28
+ settings.theme ??= "klui-light/klui-dark";
29
+ settings.quietStartup ??= "header";
30
+ settings.enabledModels ??= [`${PROVIDER}/*`];
31
+ // Earlier versions also listed GPU Router's models, which Klui no longer has.
32
+ if (Array.isArray(settings.enabledModels)) {
33
+ const patterns = settings.enabledModels.filter((p) => !String(p).startsWith("gpurouter/"));
34
+ settings.enabledModels = patterns.length ? patterns : [`${PROVIDER}/*`];
35
+ }
36
+ // Reasoning shows as one line until asked for, and the model can batch tool calls in one
37
+ // codemode script: fewer round trips, so runs are faster and use fewer requests.
38
+ settings.hideThinkingBlock ??= true;
39
+ settings.defaultTools ??= ["+codemode"];
40
+ // Fullscreen, so selecting text copies it (the terminal can't tell Klui about its own
41
+ // selection). Klui makes its scrolling as smooth as the terminal's (see scroll.ts). Earlier
42
+ // versions saved "regular"; move those over once.
43
+ if (!settings.kluiFullscreen) {
44
+ if (settings.tuiMode === "regular")
45
+ delete settings.tuiMode;
46
+ settings.kluiFullscreen = true;
47
+ }
48
+ // No scrollbar. Pi's default one also appeared when scrolling started and hid a second after it
49
+ // stopped, touching every row each time, so every scroll began and ended with a full repaint.
50
+ settings.fullscreenScrollbar ??= "hidden";
51
+ if (settings.defaultProvider !== PROVIDER || !ids.has(String(settings.defaultModel))) {
52
+ settings.defaultProvider = PROVIDER;
53
+ settings.defaultModel = config.defaultModel;
54
+ }
55
+ settings.lastChangelogVersion = piVersion;
56
+ settings.enableInstallTelemetry = false;
57
+ mkdirSync(AGENT_DIR, { recursive: true });
58
+ const tmp = `${file}.${process.pid}.tmp`;
59
+ writeFileSync(tmp, `${JSON.stringify(settings, null, 2)}\n`);
60
+ renameSync(tmp, file);
61
+ }
62
+ /** shift+tab cycles Klui's permission modes, like Claude Code, so Pi's thinking cycle moves to alt+t. */
63
+ function seedKeybindings() {
64
+ const file = join(AGENT_DIR, "keybindings.json");
65
+ let bindings = {};
66
+ try {
67
+ bindings = JSON.parse(readFileSync(file, "utf8"));
68
+ }
69
+ catch (error) {
70
+ // A file we can't read is the attendee's to fix; only a missing one gets created.
71
+ if (error.code !== "ENOENT")
72
+ return;
73
+ }
74
+ if ("app.thinking.cycle" in bindings)
75
+ return;
76
+ bindings["app.thinking.cycle"] = "alt+t";
77
+ writeFileSync(file, `${JSON.stringify(bindings, null, 2)}\n`);
78
+ }
79
+ async function run() {
80
+ const args = process.argv.slice(2);
81
+ if (!nodeIsRecentEnough()) {
82
+ console.error(`klui needs Node.js ${MIN_NODE.join(".")} or newer (you have ${process.versions.node}).`);
83
+ console.error("Grab the latest LTS from https://nodejs.org and run klui again.");
84
+ process.exit(1);
85
+ }
86
+ process.title = "klui";
87
+ if (args[0] === "update" && args.length === 1)
88
+ return runUpdate();
89
+ process.env.PI_CODING_AGENT_DIR = AGENT_DIR;
90
+ process.env.PI_SKIP_VERSION_CHECK = "1";
91
+ process.env.PI_TELEMETRY = "0";
92
+ // Imported after the environment is set: Pi reads its config directory at import time.
93
+ const pi = await import("@earendil-works/pi-coding-agent");
94
+ if (args[0] === "--version" || args[0] === "-v") {
95
+ console.log(`Klui Code ${VERSION} (pi ${pi.VERSION})`);
96
+ return;
97
+ }
98
+ // Fetched before Pi starts so a first launch already defaults to a live event model.
99
+ const loaded = await loadConfig();
100
+ seedSettings(loaded.config, pi.VERSION);
101
+ seedKeybindings();
102
+ await patchPi(loaded.config);
103
+ const { createKluiExtension } = await import("./extension/index.js");
104
+ await pi.main([...args, "--theme", THEMES_DIR], {
105
+ extensionFactories: [{ name: "klui", factory: createKluiExtension(loaded), hidden: true }],
106
+ });
107
+ }
108
+ /** `klui update`: installs the latest release; the next `klui` runs it. */
109
+ async function runUpdate() {
110
+ const blue = (text) => `\x1b[38;2;143;211;251m${text}\x1b[0m`;
111
+ const dim = (text) => `\x1b[2m${text}\x1b[0m`;
112
+ console.log(dim("checking for updates…"));
113
+ const result = await update((to) => console.log(dim(`updating Klui Code ${VERSION} → ${to}…`)));
114
+ if (result.status === "current")
115
+ console.log(`${blue("✦")} Klui Code ${result.version} is the latest version`);
116
+ else if (result.status === "updated")
117
+ console.log(`${blue("✦")} Klui Code ${result.to} is installed · run klui to use it`);
118
+ else {
119
+ console.error(result.message);
120
+ process.exitCode = 1;
121
+ }
122
+ }
123
+ run().catch((error) => {
124
+ console.error(error instanceof Error ? (error.stack ?? error.message) : error);
125
+ process.exit(1);
126
+ });