klui-code 0.1.0 → 0.1.2

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
@@ -14,6 +14,8 @@ missing or older than 22.19, and puts everything in `~/.klui`. On first launch k
14
14
  device its own event pass and picks the default model.
15
15
 
16
16
  Already on Node 22.19+? `npm install -g klui-code` works too (and is the way on Windows).
17
+ On Windows, Klui runs commands through Git Bash, so install [Git for Windows](https://git-scm.com/download/win)
18
+ first if you don't have it.
17
19
 
18
20
  ## Using it
19
21
 
package/dist/checks.js CHANGED
@@ -36,12 +36,13 @@ export function tsProjects(file) {
36
36
  /** Type errors in a project, from its own `tsc`. Undefined when it has no compiler installed. */
37
37
  export async function typecheck(config) {
38
38
  const dir = dirname(config);
39
- const tsc = findUp(dir, join("node_modules", ".bin", process.platform === "win32" ? "tsc.cmd" : "tsc"));
39
+ // Its JavaScript entry point, run with this Node: Windows can't start the .cmd shim without a shell.
40
+ const tsc = findUp(dir, join("node_modules", "typescript", "bin", "tsc"));
40
41
  if (!tsc)
41
42
  return undefined;
42
- const { stdout } = await run(tsc, ["--noEmit", "--pretty", "false", "-p", config], dir);
43
+ const { stdout } = await run(process.execPath, [tsc, "--noEmit", "--pretty", "false", "-p", config], dir);
43
44
  const problems = [];
44
- for (const line of stdout.split("\n")) {
45
+ for (const line of stdout.split(/\r?\n/)) {
45
46
  const m = /^(.+?)\((\d+),(\d+)\): error (TS\d+: .*)$/.exec(line);
46
47
  const bare = /^error (TS\d+: .*)$/.exec(line); // no location, like a missing "types" package
47
48
  if (m)
package/dist/cli.js CHANGED
@@ -1,9 +1,9 @@
1
1
  // `klui`: Pi with the Klui extension and themes preloaded, in its own config directory so it never
2
2
  // touches an existing Pi setup.
3
- import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
3
+ import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
4
4
  import { join } from "node:path";
5
- import { loadConfig } from "./pass.js";
6
- import { patchPi } from "./pi-patches.js";
5
+ import { ensureKey, loadConfig } from "./pass.js";
6
+ import { patchPi, piModule } from "./pi-patches.js";
7
7
  import { AGENT_DIR, PROVIDER, THEMES_DIR, VERSION } from "./paths.js";
8
8
  import { update } from "./update.js";
9
9
  const MIN_NODE = [22, 19];
@@ -26,7 +26,8 @@ function seedSettings(config, piVersion) {
26
26
  }
27
27
  const ids = new Set(config.models.map((m) => m.id));
28
28
  settings.theme ??= "klui-light/klui-dark";
29
- settings.quietStartup ??= "header";
29
+ // Klui draws its own header, so Pi's logo and key hints would only flash up first.
30
+ settings.quietStartup = true;
30
31
  settings.enabledModels ??= [`${PROVIDER}/*`];
31
32
  // Earlier versions also listed GPU Router's models, which Klui no longer has.
32
33
  if (Array.isArray(settings.enabledModels)) {
@@ -36,6 +37,8 @@ function seedSettings(config, piVersion) {
36
37
  // Reasoning shows as one line until asked for, and the model can batch tool calls in one
37
38
  // codemode script: fewer round trips, so runs are faster and use fewer requests.
38
39
  settings.hideThinkingBlock ??= true;
40
+ // Reason hard by default; a level the user picks (alt+t) is saved here and kept.
41
+ settings.defaultThinkingLevel ??= "high";
39
42
  settings.defaultTools ??= ["+codemode"];
40
43
  // Fullscreen, so selecting text copies it (the terminal can't tell Klui about its own
41
44
  // selection). Klui makes its scrolling as smooth as the terminal's (see scroll.ts). Earlier
@@ -57,7 +60,13 @@ function seedSettings(config, piVersion) {
57
60
  mkdirSync(AGENT_DIR, { recursive: true });
58
61
  const tmp = `${file}.${process.pid}.tmp`;
59
62
  writeFileSync(tmp, `${JSON.stringify(settings, null, 2)}\n`);
60
- renameSync(tmp, file);
63
+ try {
64
+ renameSync(tmp, file);
65
+ }
66
+ catch {
67
+ // Windows refuses while another program holds the file open; the saved settings still work.
68
+ rmSync(tmp, { force: true });
69
+ }
61
70
  }
62
71
  /** shift+tab cycles Klui's permission modes, like Claude Code, so Pi's thinking cycle moves to alt+t. */
63
72
  function seedKeybindings() {
@@ -89,14 +98,16 @@ async function run() {
89
98
  process.env.PI_CODING_AGENT_DIR = AGENT_DIR;
90
99
  process.env.PI_SKIP_VERSION_CHECK = "1";
91
100
  process.env.PI_TELEMETRY = "0";
101
+ if (args[0] === "setup" && args.length === 1)
102
+ return runSetup();
92
103
  // Imported after the environment is set: Pi reads its config directory at import time.
93
104
  const pi = await import("@earendil-works/pi-coding-agent");
94
105
  if (args[0] === "--version" || args[0] === "-v") {
95
106
  console.log(`Klui Code ${VERSION} (pi ${pi.VERSION})`);
96
107
  return;
97
108
  }
98
- // Fetched before Pi starts so a first launch already defaults to a live event model.
99
- const loaded = await loadConfig();
109
+ // Never waits on the network: the saved or bundled config now, the live one when Pass answers.
110
+ const loaded = loadConfig();
100
111
  seedSettings(loaded.config, pi.VERSION);
101
112
  seedKeybindings();
102
113
  await patchPi(loaded.config);
@@ -105,6 +116,26 @@ async function run() {
105
116
  extensionFactories: [{ name: "klui", factory: createKluiExtension(loaded), hidden: true }],
106
117
  });
107
118
  }
119
+ /**
120
+ * `klui setup`, run by the installer: everything a first launch would otherwise fetch (the event
121
+ * config, this device's key, and Pi's fd and rg), so the first `klui` opens ready. Best effort:
122
+ * whatever fails here, klui fetches when it starts.
123
+ */
124
+ async function runSetup() {
125
+ const loaded = loadConfig();
126
+ const config = (await loaded.fresh) ?? loaded.config;
127
+ for (let tries = 0; tries < 3; tries++) {
128
+ try {
129
+ await ensureKey(config);
130
+ break;
131
+ }
132
+ catch {
133
+ await new Promise((resolve) => setTimeout(resolve, 2_000));
134
+ }
135
+ }
136
+ const { ensureTool } = await piModule("./utils/tools-manager.js");
137
+ await Promise.all([ensureTool("fd"), ensureTool("rg")]).catch(() => { });
138
+ }
108
139
  /** `klui update`: installs the latest release; the next `klui` runs it. */
109
140
  async function runUpdate() {
110
141
  const blue = (text) => `\x1b[38;2;143;211;251m${text}\x1b[0m`;
@@ -9,7 +9,7 @@ export function createFooter(pi, ctx, tui, theme, footerData) {
9
9
  return {
10
10
  render(width) {
11
11
  const level = pi.getThinkingLevel();
12
- const think = ctx.model?.reasoning && level && level !== "off" ? ` · think ${level}` : "";
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
15
  // Event credits only pay for the event's models.
@@ -17,11 +17,13 @@ export function createFooter(pi, ctx, tui, theme, footerData) {
17
17
  const credits = eventModel ? creditsLabel(true) : undefined;
18
18
  const status = !eventModel
19
19
  ? undefined
20
- : state.connection.kind !== "ready"
21
- ? theme.fg(state.connection.kind === "closed" ? "warning" : "error", `● ${state.connection.message}`)
22
- : credits
23
- ? theme.fg("success", credits)
24
- : undefined;
20
+ : state.connection.kind === "connecting"
21
+ ? theme.fg("dim", "connecting…")
22
+ : state.connection.kind !== "ready"
23
+ ? theme.fg(state.connection.kind === "closed" ? "warning" : "error", `● ${state.connection.message}`)
24
+ : credits
25
+ ? theme.fg("success", credits)
26
+ : undefined;
25
27
  const tail = (full) => {
26
28
  const right = [modelLabel() + (full ? think : "")];
27
29
  if (full && usage?.percent != null)
@@ -79,7 +79,7 @@ export function createHeader(tui, theme, cwd, reducedMotion) {
79
79
  const textLines = () => {
80
80
  const caret = state.chatStarted ? " " : reducedMotion || typed < greeting.length || Math.floor(Date.now() / 500) % 2 === 0 ? theme.fg("accent", "▍") : " ";
81
81
  const { connection } = state;
82
- const info = connection.kind === "ready"
82
+ const info = connection.kind === "ready" || connection.kind === "connecting"
83
83
  ? theme.fg("muted", modelLabel())
84
84
  : theme.fg(connection.kind === "closed" ? "warning" : "error", `● ${connection.message}`);
85
85
  return [
@@ -26,6 +26,7 @@ const TITLE_FRAMES = ["⣾", "⣽", "⣻", "⢿", "⡿", "⣟", "⣯", "⣷"];
26
26
  /** Klui Pass refused on purpose (not a network problem), so retrying won't help. */
27
27
  const CLOSED_CODES = new Set(["registration_closed", "pool_empty", "paused", "too_many_devices", "pass_revoked"]);
28
28
  const REFUSED = "Klui refused your pass · ask an organizer";
29
+ const STILL_CONNECTING = "Klui is still connecting. Check your wifi and send again.";
29
30
  const WRITING = `<writing>
30
31
  Users are smart. Give them the answer, not a lesson.
31
32
  - Lead with the answer or the result. Then add only what they need to act on it. Stop there.
@@ -38,10 +39,40 @@ Users are smart. Give them the answer, not a lesson.
38
39
  - After a task, say what changed and anything left undone in a few lines.
39
40
  - If you're unsure, say so briefly and give your best answer.
40
41
  </writing>`;
41
- export const createKluiExtension = ({ config, live }) => async (pi) => {
42
+ export const createKluiExtension = ({ config, live, fresh }) => async (pi) => {
42
43
  const reducedMotion = process.env.KLUI_REDUCED_MOTION === "1";
43
- initState({ config, live, device: readDevice(), connection: { kind: "ready" }, mood: "idle", chatStarted: false, mode: initialMode() });
44
- const fallback = createFallback(() => state.config, () => state.device.apiKey);
44
+ let uiCtx;
45
+ const device = readDevice();
46
+ const keyed = !!process.env.KLUI_API_KEY || (!!device.apiKey && device.baseUrl === config.baseUrl);
47
+ // A key the gateway answered 401 for. If Pass hands the same one back, it's still dead.
48
+ let refusedKey;
49
+ /** The device's key, if it was issued for the gateway Klui uses now and hasn't been refused. */
50
+ const usableKey = () => {
51
+ if (process.env.KLUI_API_KEY)
52
+ return process.env.KLUI_API_KEY;
53
+ const { apiKey, baseUrl } = state.device;
54
+ return apiKey && apiKey !== refusedKey && baseUrl === state.config.baseUrl ? apiKey : undefined;
55
+ };
56
+ initState({ config, live, device, connection: { kind: keyed ? "ready" : "connecting" }, mood: "idle", chatStarted: false, mode: initialMode() });
57
+ const fallback = createFallback(() => state.config, usableKey,
58
+ // A message sent before Klui has its key starts the quick retries over and waits up to 15
59
+ // seconds for them before saying it's still connecting.
60
+ async (signal) => {
61
+ const stopped = new Promise((resolve) => signal?.addEventListener("abort", () => resolve(), { once: true }));
62
+ const waiting = () => !usableKey() && state.connection.kind !== "closed" && !signal?.aborted && !shutDown;
63
+ const until = Date.now() + 15_000;
64
+ const timeUp = new Promise((resolve) => setTimeout(resolve, 15_000).unref?.());
65
+ if (waiting()) {
66
+ retryDelay = 1_000;
67
+ await Promise.race([connect(), stopped, timeUp]);
68
+ }
69
+ while (waiting() && Date.now() < until) {
70
+ await Promise.race([new Promise((resolve) => setTimeout(resolve, 500)), stopped]);
71
+ }
72
+ if (usableKey())
73
+ return undefined;
74
+ return state.connection.kind === "closed" ? state.connection.message : STILL_CONNECTING;
75
+ });
45
76
  const registerProvider = () => {
46
77
  pi.registerProvider(PROVIDER, {
47
78
  name: "Klui",
@@ -49,33 +80,71 @@ export const createKluiExtension = ({ config, live }) => async (pi) => {
49
80
  api: "openai-completions",
50
81
  // Without a key the models still show up, so the first request explains what's wrong
51
82
  // instead of Pi asking the attendee to /login somewhere.
52
- apiKey: state.device.apiKey ?? "klui-no-key",
83
+ apiKey: usableKey() ?? "klui-no-key",
53
84
  models: toProviderModels(state.config),
54
85
  streamSimple: recordUsage(fallback.streamSimple),
55
86
  });
56
87
  };
57
- // A key the gateway answered 401 for. If Pass hands the same one back, it's still dead.
58
- let refusedKey;
59
- const connect = async (force = false) => {
88
+ // Without a key, Klui keeps asking Klui Pass in the background, soon at first and then about
89
+ // once a minute. Each wait is randomized so a room of laptops doesn't ask all at once.
90
+ let retryTimer;
91
+ let retryDelay = 1_000;
92
+ /** Pass said this network is registering too fast; nothing asks again before this. */
93
+ let holdUntil = 0;
94
+ let connecting;
95
+ /** One attempt at a time; a forced one (a refused key, a new gateway) runs after the current one. */
96
+ const connect = (force = false) => {
97
+ if (connecting && !force)
98
+ return connecting;
99
+ const run = (connecting ?? Promise.resolve()).then(() => attempt(force));
100
+ connecting = run;
101
+ void run.finally(() => {
102
+ if (connecting === run)
103
+ connecting = undefined;
104
+ });
105
+ return run;
106
+ };
107
+ let shutDown = false;
108
+ const attempt = async (force) => {
109
+ // Pass can answer after /reload or exit, when this extension is gone and Pi refuses its calls.
110
+ // Not even a forced one asks during a rate-limit hold; the retry timer goes when it's over.
111
+ if (shutDown || Date.now() < holdUntil)
112
+ return;
113
+ clearTimeout(retryTimer);
114
+ // A refused key is only worth replacing, never reusing from the device file.
115
+ force ||= refusedKey !== undefined && state.device.apiKey === refusedKey;
60
116
  try {
61
117
  const device = await ensureKey(state.config, { force });
118
+ if (shutDown)
119
+ return;
62
120
  const refused = refusedKey !== undefined && device.apiKey === refusedKey;
63
121
  update({ device, connection: refused ? { kind: "closed", message: REFUSED } : { kind: "ready" } });
122
+ retryDelay = 1_000;
123
+ if (!refused)
124
+ void refreshCredits(true);
64
125
  }
65
126
  catch (error) {
66
- // Pass's own messages are written for attendees; anything else is a network problem.
67
- const pass = error instanceof PassError && !error.code.startsWith("http_") ? error : undefined;
68
- update({
69
- connection: pass && CLOSED_CODES.has(pass.code)
70
- ? { kind: "closed", message: pass.message }
71
- : { kind: "offline", message: `${pass?.message ?? "Can't reach Klui. Check your wifi"} · /klui retry` },
72
- });
127
+ if (shutDown)
128
+ return;
129
+ // Pass refusing on purpose (event over, pool empty) won't change by asking again.
130
+ if (error instanceof PassError && CLOSED_CODES.has(error.code)) {
131
+ update({ connection: { kind: "closed", message: error.message } });
132
+ }
133
+ else {
134
+ if (error instanceof PassError && error.code === "rate_limited")
135
+ holdUntil = Date.now() + 60_000;
136
+ update({ connection: { kind: "connecting" } });
137
+ const wait = Math.max(retryDelay, holdUntil - Date.now());
138
+ retryTimer = setTimeout(() => void connect(), wait * (1 + Math.random() / 2));
139
+ retryTimer.unref?.();
140
+ retryDelay = Math.min(retryDelay * 2, 60_000);
141
+ }
73
142
  }
74
143
  registerProvider();
75
144
  };
76
145
  let creditsCheckedAt = 0;
77
146
  const refreshCredits = async (force = false) => {
78
- const { apiKey } = state.device;
147
+ const apiKey = usableKey();
79
148
  const { baseUrl } = state.config;
80
149
  if (!apiKey || (!force && Date.now() - creditsCheckedAt < 15_000))
81
150
  return;
@@ -84,9 +153,38 @@ export const createKluiExtension = ({ config, live }) => async (pi) => {
84
153
  if (credits)
85
154
  update({ credits });
86
155
  };
87
- await connect();
156
+ // A live config can drop the model the saved one had selected; Pi would keep sending its old id.
157
+ let sessionCtx;
158
+ const keepModelAvailable = async (ctx) => {
159
+ const current = ctx.model;
160
+ if (shutDown || current?.provider !== PROVIDER || state.config.models.some((m) => m.id === current.id))
161
+ return;
162
+ const model = ctx.modelRegistry.find(PROVIDER, state.config.defaultModel);
163
+ if (model)
164
+ await pi.setModel(model);
165
+ };
166
+ // The models are there from the start. With a saved key that's all; without one (a first
167
+ // launch), Klui gets one in the background while the attendee starts typing.
168
+ registerProvider();
169
+ if (keyed)
170
+ await connect();
171
+ else
172
+ void connect().catch(() => { });
173
+ // Started from the saved config: take the live one when Pass sends it (a new model list, or a
174
+ // new gateway, which needs its own key).
175
+ void fresh?.then(async (live) => {
176
+ if (shutDown || !live || JSON.stringify(live) === JSON.stringify(state.config))
177
+ return;
178
+ const moved = live.baseUrl !== state.config.baseUrl;
179
+ update({ config: live, live: true });
180
+ if (moved)
181
+ await connect(true);
182
+ else
183
+ registerProvider();
184
+ if (sessionCtx)
185
+ await keepModelAvailable(sessionCtx);
186
+ }).catch(() => { });
88
187
  // ── UI ──────────────────────────────────────────────────────────────────────────────────
89
- let uiCtx;
90
188
  const title = (frame) => {
91
189
  if (!uiCtx)
92
190
  return;
@@ -100,6 +198,8 @@ export const createKluiExtension = ({ config, live }) => async (pi) => {
100
198
  model: ctx.model ? { provider: ctx.model.provider, id: ctx.model.id, name: ctx.model.name } : undefined,
101
199
  chatStarted: ctx.sessionManager.getEntries().some((e) => e.type === "message"),
102
200
  });
201
+ sessionCtx = ctx;
202
+ await keepModelAvailable(ctx);
103
203
  if (ctx.mode !== "tui")
104
204
  return;
105
205
  uiCtx = ctx;
@@ -110,7 +210,7 @@ export const createKluiExtension = ({ config, live }) => async (pi) => {
110
210
  ctx.ui.setHiddenThinkingLabel(`✦ reasoning · ${keyText("app.thinking.toggle")} to show`);
111
211
  title();
112
212
  void refreshCredits(true);
113
- if (state.connection.kind !== "ready")
213
+ if (state.connection.kind === "closed")
114
214
  ctx.ui.notify(state.connection.message, "warning");
115
215
  if (!updateNoticeShown) {
116
216
  updateNoticeShown = true;
@@ -222,6 +322,8 @@ export const createKluiExtension = ({ config, live }) => async (pi) => {
222
322
  doneTimer.unref?.();
223
323
  });
224
324
  pi.on("session_shutdown", async () => {
325
+ shutDown = true;
326
+ clearTimeout(retryTimer);
225
327
  clearInterval(titleTimer);
226
328
  clearTimeout(moodTimer);
227
329
  clearTimeout(doneTimer);
@@ -245,7 +347,7 @@ export const createKluiExtension = ({ config, live }) => async (pi) => {
245
347
  if (state.connection.kind === "ready")
246
348
  ctx.ui.notify("Refreshed your Klui pass. Send that again!", "info");
247
349
  else
248
- ctx.ui.notify(state.connection.message, "warning");
350
+ ctx.ui.notify(state.connection.kind === "closed" ? state.connection.message : STILL_CONNECTING, "warning");
249
351
  }
250
352
  else if (event.status === 402) {
251
353
  void refreshCredits(true);
@@ -268,7 +370,7 @@ export const createKluiExtension = ({ config, live }) => async (pi) => {
268
370
  void refreshCredits(true);
269
371
  }
270
372
  else {
271
- ctx.ui.notify(state.connection.message, "warning");
373
+ ctx.ui.notify(state.connection.kind === "closed" ? state.connection.message : STILL_CONNECTING, "warning");
272
374
  }
273
375
  },
274
376
  refreshCredits: () => refreshCredits(true),
package/dist/fallback.js CHANGED
@@ -83,7 +83,11 @@ export function worthAnotherPeer(message) {
83
83
  return false;
84
84
  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);
85
85
  }
86
- export function createFallback(getConfig, getApiKey) {
86
+ /**
87
+ * `connect` asks Klui Pass for a key when there's none yet (say Pass was unreachable at launch),
88
+ * and says why when it still can't get one.
89
+ */
90
+ export function createFallback(getConfig, getApiKey, connect = async () => undefined) {
87
91
  /** The peer that last answered for each free model, so later turns go straight to it. */
88
92
  const working = new Map();
89
93
  /** Peers that failed recently, until when they sit out. */
@@ -112,13 +116,27 @@ export function createFallback(getConfig, getApiKey) {
112
116
  return {
113
117
  streamSimple(model, context, options) {
114
118
  const entry = getConfig().models.find((m) => m.id === model.id);
115
- if (!entry?.free && !entry?.paid)
116
- return base().streamSimple(model, context, options);
117
- const paid = !!entry.paid;
118
- const names = [serviceOf(model.id), ...(entry.aliases ?? [])];
119
+ const paid = !!entry?.paid;
120
+ const names = [serviceOf(model.id), ...(entry?.aliases ?? [])];
119
121
  const needsImages = context.messages.some((message) => Array.isArray(message.content) && message.content.some((part) => part.type === "image"));
120
122
  const out = createAssistantMessageEventStream();
121
123
  void (async () => {
124
+ if (!getApiKey()) {
125
+ const problem = await connect(options?.signal);
126
+ if (options?.signal?.aborted)
127
+ throw new Error("Request was aborted");
128
+ if (!getApiKey())
129
+ throw new Error(problem ?? "Can't reach Klui. Check your wifi and try again.");
130
+ // The gateway may have changed while this message waited for its key.
131
+ model = { ...model, baseUrl: getConfig().baseUrl };
132
+ }
133
+ // The key Pi started this request with may be the placeholder from before Klui connected.
134
+ options = { ...options, apiKey: getApiKey() };
135
+ if (!entry?.free && !entry?.paid) {
136
+ for await (const event of base().streamSimple(model, context, options))
137
+ out.push(event);
138
+ return out.end();
139
+ }
122
140
  const tried = new Set();
123
141
  /** The best-ranked peer not tried yet and not sitting out, from the live list. */
124
142
  const nextPeer = async () => {
@@ -182,10 +200,11 @@ export function createFallback(getConfig, getApiKey) {
182
200
  }
183
201
  out.end();
184
202
  })().catch((error) => {
203
+ const reason = options?.signal?.aborted ? "aborted" : "error";
185
204
  out.push({
186
205
  type: "error",
187
- reason: "error",
188
- error: { role: "assistant", content: [], api: model.api, provider: model.provider, model: model.id, stopReason: "error", errorMessage: String(error), usage: emptyUsage(), timestamp: Date.now() },
206
+ reason,
207
+ error: { role: "assistant", content: [], api: model.api, provider: model.provider, model: model.id, stopReason: reason, errorMessage: error instanceof Error ? error.message : String(error), usage: emptyUsage(), timestamp: Date.now() },
189
208
  });
190
209
  out.end();
191
210
  });
package/dist/images.js CHANGED
@@ -10,8 +10,11 @@ const MIME = { ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg",
10
10
  /** Where Pi saves a pasted clipboard image. */
11
11
  const CLIPBOARD_FILE = /(?:^|[\\/])pi-clipboard-[0-9a-f-]+\.(?:png|jpe?g|gif|webp)$/i;
12
12
  const CHIP = /\[Image #(\d+)\]/g;
13
- /** An absolute or home-relative image path: plain, with backslash-escaped spaces, or quoted. */
14
- const IMAGE_PATH = /'((?:\/|~\/)[^']+?\.(?:png|jpe?g|gif|webp))'|"((?:\/|~\/)[^"]+?\.(?:png|jpe?g|gif|webp))"|((?:\/|~\/)(?:\\ |[^\s'"])+?\.(?:png|jpe?g|gif|webp))(?=$|[\s,.;:!?)])/gi;
13
+ /**
14
+ * An absolute (C:\ on Windows) or home-relative image path: plain, with backslash-escaped spaces, or
15
+ * quoted. A plain one starts a word, so a long run of path-like text is scanned once, not from every slash.
16
+ */
17
+ const IMAGE_PATH = /'((?:\/|~\/|[a-z]:[\\/])[^']+?\.(?:png|jpe?g|gif|webp))'|"((?:\/|~\/|[a-z]:[\\/])[^"]+?\.(?:png|jpe?g|gif|webp))"|(?<![^\s(,])((?:\/|~\/|[a-z]:[\\/])(?:\\ |[^\s'"])+?\.(?:png|jpe?g|gif|webp))(?=$|[\s,.;:!?)])/gi;
15
18
  const pasted = new Map();
16
19
  let nextNumber = 1;
17
20
  export function isClipboardImageFile(text) {
package/dist/pass.js CHANGED
@@ -52,26 +52,28 @@ async function request(path, init) {
52
52
  }
53
53
  return body;
54
54
  }
55
- /**
56
- * The live config when Klui Pass answers, otherwise the last one we saw, otherwise the bundled one.
57
- * `KLUI_BASE_URL` overrides the gateway, for organizers testing a gateway directly.
58
- */
59
- export async function loadConfig() {
60
- let config;
61
- let live = false;
55
+ /** The event config from Klui Pass, saved for next launch, or undefined when Pass doesn't answer. */
56
+ async function fetchConfig() {
62
57
  try {
63
- config = sanitizeConfig(await request("/v1/config", { method: "GET", timeoutMs: 4000 }));
64
- if (config) {
58
+ const config = sanitizeConfig(await request("/v1/config", { method: "GET", timeoutMs: 4000 }));
59
+ if (config)
65
60
  writeJson(CONFIG_CACHE_FILE, config);
66
- live = true;
67
- }
61
+ return config;
68
62
  }
69
63
  catch {
70
- // Offline or Pass is down: fall through to the cache.
64
+ return undefined; // Offline or Pass is down.
71
65
  }
72
- config ??= readCachedConfig() ?? BUNDLED_CONFIG;
66
+ }
67
+ /**
68
+ * The config to start with: the saved one, or the bundled one on a first launch, so klui never
69
+ * waits on the network to open. `fresh` brings the live one in when Pass answers.
70
+ * `KLUI_BASE_URL` overrides the gateway, for organizers testing a gateway directly.
71
+ */
72
+ export function loadConfig() {
73
73
  const override = process.env.KLUI_BASE_URL?.replace(/\/+$/, "");
74
- return { config: override ? { ...config, baseUrl: override } : config, live };
74
+ const withOverride = (config) => (override ? { ...config, baseUrl: override } : config);
75
+ const fresh = fetchConfig().then((config) => config && withOverride(config));
76
+ return { config: withOverride(readCachedConfig() ?? BUNDLED_CONFIG), live: false, fresh };
75
77
  }
76
78
  /** Make sure this device holds a key for the gateway in `config`, registering when needed. */
77
79
  export async function ensureKey(config, opts = {}) {
@@ -9,9 +9,15 @@ export async function patchPi(config) {
9
9
  brandOutput();
10
10
  scrollWithTerminal();
11
11
  clearAfterCopy();
12
- for (const patch of [hoverJumpToLatest, queuedMessages, trimSlashMenu, slashAliases, simpleThinkingMenu, thinkingAfterModel, () => tidyModelPicker(), () => quietPiHints(config), pasteImageChips])
12
+ for (const patch of [hidePiFooter, hoverJumpToLatest, queuedMessages, trimSlashMenu, slashAliases, simpleThinkingMenu, thinkingAfterModel, () => tidyModelPicker(), () => quietPiHints(config), pasteImageChips])
13
13
  await patch().catch(() => { });
14
14
  }
15
+ /** Klui puts its own footer in place once it loads; Pi's would show until then, and again on /new. */
16
+ async function hidePiFooter() {
17
+ const { FooterComponent } = await piModule("./modes/interactive/components/footer.js");
18
+ if (typeof FooterComponent.prototype.render === "function")
19
+ FooterComponent.prototype.render = () => [];
20
+ }
15
21
  /**
16
22
  * The terminal title ("π - project"), the line printed on exit ("To resume this session:
17
23
  * pi --session …") and a few of Pi's warnings are written straight to stdout.
package/dist/update.js CHANGED
@@ -111,13 +111,14 @@ function installedVersion() {
111
111
  /** npm next to the Node running klui (the installer's own copy), else the one on PATH. */
112
112
  function npm(args) {
113
113
  const win = process.platform === "win32";
114
- const bundled = join(dirname(process.execPath), win ? "npm.cmd" : "npm");
115
- const command = existsSync(bundled) ? bundled : win ? "npm.cmd" : "npm";
114
+ // npm's own script, run by this Node, so no shell has to parse a path like C:\Program Files.
115
+ const node = dirname(process.execPath);
116
+ const cli = [join(node, "node_modules", "npm", "bin", "npm-cli.js"), join(node, "..", "lib", "node_modules", "npm", "bin", "npm-cli.js")].find((path) => existsSync(path));
116
117
  return new Promise((done) => {
117
- const child = spawn(command, args, {
118
- env: { ...process.env, NPM_CONFIG_UPDATE_NOTIFIER: "false", PATH: `${dirname(process.execPath)}${win ? ";" : ":"}${process.env.PATH ?? ""}` },
118
+ const child = spawn(cli ? process.execPath : win ? "npm.cmd" : "npm", cli ? [cli, ...args] : args, {
119
+ env: { ...process.env, NPM_CONFIG_UPDATE_NOTIFIER: "false", PATH: `${node}${win ? ";" : ":"}${process.env.PATH ?? ""}` },
119
120
  stdio: ["ignore", "pipe", "pipe"],
120
- shell: win,
121
+ shell: win && !cli,
121
122
  windowsHide: true,
122
123
  });
123
124
  let output = "";
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "klui-code",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "klui-code",
9
- "version": "0.1.0",
9
+ "version": "0.1.2",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@earendil-works/chord": "1.1.0",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "klui-code",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "Klui Code: a pixel-cute coding agent for your terminal, built on Pi and running on AntSeed.",
5
5
  "keywords": [
6
6
  "klui",