klui-code 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,92 @@
1
+ // While the agent works, one small box sits above the editor, like Claude Code's: a shimmering
2
+ // phrase, then the time and tokens so far. When the run ends it says so for a moment.
3
+ import { keyText } from "@earendil-works/pi-coding-agent";
4
+ import { backgroundAnsi, foregroundAnsi, parseColor, truncateToWidth } from "@earendil-works/pi-tui";
5
+ import { KLUI } from "../mascot.js";
6
+ import { mixHex } from "../pixels.js";
7
+ import { DONE_LINES, PHRASES, pick } from "./voice.js";
8
+ const FRAME_MS = 50;
9
+ const PHRASE_MS = 3600;
10
+ /** The animated working line. `status()` is read on every frame. */
11
+ export function createWorkingWidget(tui, theme, status, reducedMotion) {
12
+ let frame = 0;
13
+ let activity = status().activity;
14
+ let phrase = pick(PHRASES[activity]);
15
+ let phraseAt = Date.now();
16
+ const timer = setInterval(() => {
17
+ frame++;
18
+ const current = status();
19
+ const now = Date.now();
20
+ if (current.activity !== activity || now - phraseAt > PHRASE_MS) {
21
+ activity = current.activity;
22
+ phrase = pick(PHRASES[activity], phrase);
23
+ phraseAt = now;
24
+ }
25
+ tui.requestRender();
26
+ }, reducedMotion ? 1000 : FRAME_MS);
27
+ timer.unref?.();
28
+ return {
29
+ render(width) {
30
+ const current = status();
31
+ const title = reducedMotion ? theme.fg("accent", `${phrase}…`) : shimmer(`${phrase}…`, frame, theme);
32
+ const meta = [
33
+ current.detail,
34
+ formatElapsed(Date.now() - current.startedAt),
35
+ current.tokens > 0 ? `↓ ${formatTokens(current.tokens)} tokens` : undefined,
36
+ `${keyText("app.interrupt")} to stop`,
37
+ ].filter(Boolean);
38
+ return line(title, meta.join(" · "), theme, width);
39
+ },
40
+ invalidate() { },
41
+ dispose() {
42
+ clearInterval(timer);
43
+ },
44
+ };
45
+ }
46
+ /** A short "done" line, or "stopped" / "hit a snag". */
47
+ export function createDoneWidget(theme, outcome) {
48
+ const happy = !outcome.aborted && !outcome.error;
49
+ const said = happy ? pick(DONE_LINES) : outcome.aborted ? "stopped" : "hit a snag";
50
+ const title = happy ? theme.bold(theme.fg("accent", said)) : theme.fg(outcome.aborted ? "muted" : "error", said);
51
+ const meta = [
52
+ formatElapsed(Date.now() - outcome.startedAt),
53
+ outcome.tokens > 0 ? `↓ ${formatTokens(outcome.tokens)} tokens` : undefined,
54
+ outcome.error,
55
+ ].filter(Boolean);
56
+ return {
57
+ render: (width) => line(title, meta.join(" · "), theme, width),
58
+ invalidate() { },
59
+ };
60
+ }
61
+ function line(title, meta, theme, width) {
62
+ return [truncateToWidth(` ${box(title, meta, theme)}`, width)];
63
+ }
64
+ /** The phrase and the numbers on a soft blue background. Every color inside resets only the foreground. */
65
+ function box(title, meta, theme) {
66
+ const light = theme.appearance === "light";
67
+ const bg = backgroundAnsi(parseColor(light ? "#d6e9fb" : "#1b2b45"), theme.getColorMode());
68
+ const dim = foregroundAnsi(parseColor(light ? "#56637f" : "#7f93b2"), theme.getColorMode());
69
+ return `${bg} ${title} ${dim}${meta} \x1b[39m\x1b[49m`;
70
+ }
71
+ /** A bright band sweeping across the text, sky blue to white. Plain accent on 256-color terminals. */
72
+ function shimmer(text, frame, theme) {
73
+ if (theme.getColorMode() !== "truecolor")
74
+ return theme.fg("accent", text);
75
+ const chars = [...text];
76
+ const band = ((frame * 1.6) % (chars.length + 12)) - 6;
77
+ const base = theme.appearance === "light" ? KLUI.blue : KLUI.body;
78
+ const peak = theme.appearance === "light" ? KLUI.body : "#ffffff";
79
+ return chars
80
+ .map((ch, i) => {
81
+ const t = Math.max(0, 1 - Math.abs(i - band) / 4);
82
+ return `${foregroundAnsi(parseColor(mixHex(base, peak, t * 0.85)), "truecolor")}${ch}`;
83
+ })
84
+ .join("") + "\x1b[39m";
85
+ }
86
+ function formatElapsed(ms) {
87
+ const s = Math.floor(ms / 1000);
88
+ return s < 60 ? `${s}s` : `${Math.floor(s / 60)}m ${String(s % 60).padStart(2, "0")}s`;
89
+ }
90
+ function formatTokens(n) {
91
+ return n < 1000 ? String(n) : `${(n / 1000).toFixed(1).replace(/\.0$/, "")}k`;
92
+ }
@@ -0,0 +1,217 @@
1
+ // Models live on whichever peers serve them today, and those come and go (a seller goes offline,
2
+ // changes its price, or starts charging). Klui ranks the peers from the gateway's live model list:
3
+ // a `paid` model tries free peers first, then the best mix of price and reputation; a `free` one
4
+ // stays on peers serving it for free. A request a peer can't serve moves to the next one, and only
5
+ // when none of them answers does the error reach the chat.
6
+ import { createAssistantMessageEventStream } from "@earendil-works/pi-ai";
7
+ import { getApiProvider } from "@earendil-works/pi-ai/compat";
8
+ /** A coding turn re-sends the conversation, so most of its input is already cached on the peer. */
9
+ const TURN_MIX = { cached: 24, input: 6, output: 1 };
10
+ /** How a peer is picked: mostly by price, the rest by reputation. */
11
+ const COST_WEIGHT = 0.75;
12
+ /** Klui's minimum reputation for paid peers, shared by every AntSeed model. */
13
+ const MIN_REPUTATION = 51;
14
+ /** A peer that failed sits out this long before it's tried again. */
15
+ const COOLDOWN_MS = 10 * 60_000;
16
+ /** A peer that hasn't started answering by now is treated as gone (some hang without a word). */
17
+ const ANSWER_TIMEOUT_MS = 25_000;
18
+ /** Paid peers tried per request: each failure can cost a timeout, and paid peers rarely all fail. */
19
+ const MAX_PAID_TRIES = 4;
20
+ /** The service name in a gateway model id: "<peerId>@mimo-v2.6-flash" → "mimo-v2.6-flash". */
21
+ export function serviceOf(id) {
22
+ const at = id.indexOf("@");
23
+ return at === -1 ? id : id.slice(at + 1);
24
+ }
25
+ /** What a typical turn costs on this offer, in USD per million tokens. */
26
+ export function turnPrice(offer) {
27
+ const { inputUsdPerMillion: input, outputUsdPerMillion: output } = offer;
28
+ if (typeof input !== "number" || typeof output !== "number")
29
+ return undefined;
30
+ const cached = offer.cachedInputUsdPerMillion ?? input;
31
+ const { cached: c, input: i, output: o } = TURN_MIX;
32
+ return (c * cached + i * input + o * output) / (c + i + o);
33
+ }
34
+ /**
35
+ * Peers serving the model under any of `names` over chat completions, as pinned gateway ids, best
36
+ * first. A peer's score is 75% price (cheapest 1, dearest 0, on a log scale since prices span
37
+ * 1000x) and 25% reputation. Free peers always come first. `freeOnly` keeps just those peers;
38
+ * paid peers below Klui's reputation cutoff are left out.
39
+ */
40
+ export function rankOffers(models, names, freeOnly = false, needsImages = false) {
41
+ const wanted = new Set(names.map((n) => n.toLowerCase()));
42
+ const offers = new Map();
43
+ for (const model of models) {
44
+ const listed = [model.id, ...(model.aliases ?? [])].some((n) => wanted.has(n.toLowerCase()));
45
+ for (const offer of model.peers ?? []) {
46
+ if (!listed && !wanted.has(offer.serviceId.toLowerCase()))
47
+ continue;
48
+ if (needsImages && !offer.capabilities?.inputs?.includes("image"))
49
+ continue;
50
+ const price = turnPrice(offer);
51
+ const chat = !offer.protocols || offer.protocols.includes("openai-chat-completions");
52
+ if (price === undefined || !chat || (freeOnly && price !== 0))
53
+ continue;
54
+ const reputation = offer.effectiveReputationScore ?? offer.reputationScore ?? 0;
55
+ if (price !== 0 && reputation < MIN_REPUTATION)
56
+ continue;
57
+ const existing = offers.get(offer.peerId);
58
+ if (existing && existing.price <= price)
59
+ continue;
60
+ offers.set(offer.peerId, { id: `${offer.peerId}@${offer.serviceId}`, price, reputation: Math.min(Math.max(reputation / 100, 0), 1) });
61
+ }
62
+ }
63
+ const all = [...offers.values()];
64
+ // Price/reputation orders each group; a free offer always wins over a paid one.
65
+ const logs = all.map((o) => Math.log(o.price + 1e-4));
66
+ const lo = Math.min(...logs);
67
+ const hi = Math.max(...logs);
68
+ const score = (i) => COST_WEIGHT * (hi > lo ? (hi - logs[i]) / (hi - lo) : 1) + (1 - COST_WEIGHT) * all[i].reputation;
69
+ return all
70
+ .map((o, i) => ({ id: o.id, free: o.price === 0, score: score(i) }))
71
+ .sort((a, b) => Number(b.free) - Number(a.free) || b.score - a.score)
72
+ .map((o) => o.id);
73
+ }
74
+ /**
75
+ * A failure another peer might not have: the peer is gone, refuses the service, or charges (the
76
+ * gateway answers 402 when the wallet has nothing deposited with it). Bad keys, bad requests and
77
+ * the user pressing stop are the same on every peer.
78
+ */
79
+ export function worthAnotherPeer(message) {
80
+ if (!message)
81
+ return false;
82
+ if (/^\s*(400|401|403)\b/.test(message) || /invalid_api_key|abort/i.test(message))
83
+ return false;
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
+ }
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) {
91
+ /** The peer that last answered for each free model, so later turns go straight to it. */
92
+ const working = new Map();
93
+ /** Peers that failed recently, until when they sit out. */
94
+ const cooling = new Map();
95
+ let catalog;
96
+ const gatewayModels = async (signal) => {
97
+ if (catalog && Date.now() - catalog.at < 60_000)
98
+ return catalog.models;
99
+ const { baseUrl } = getConfig();
100
+ const response = await fetch(`${baseUrl}/models`, {
101
+ headers: { authorization: `Bearer ${getApiKey() ?? ""}` },
102
+ signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(8000)]) : AbortSignal.timeout(8000),
103
+ });
104
+ if (!response.ok)
105
+ throw new Error(`model list answered ${response.status}`);
106
+ const models = (await response.json()).data ?? [];
107
+ catalog = { at: Date.now(), models };
108
+ return models;
109
+ };
110
+ const base = () => {
111
+ const api = getApiProvider("openai-completions");
112
+ if (!api)
113
+ throw new Error("No API provider registered for api: openai-completions");
114
+ return api;
115
+ };
116
+ return {
117
+ streamSimple(model, context, options) {
118
+ const entry = getConfig().models.find((m) => m.id === model.id);
119
+ const paid = !!entry?.paid;
120
+ const names = [serviceOf(model.id), ...(entry?.aliases ?? [])];
121
+ const needsImages = context.messages.some((message) => Array.isArray(message.content) && message.content.some((part) => part.type === "image"));
122
+ const out = createAssistantMessageEventStream();
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
+ }
140
+ const tried = new Set();
141
+ /** The best-ranked peer not tried yet and not sitting out, from the live list. */
142
+ const nextPeer = async () => {
143
+ const offers = await gatewayModels(options?.signal).catch(() => []);
144
+ return rankOffers(offers, names, !paid, needsImages).find((id) => !tried.has(id) && (cooling.get(id) ?? 0) < Date.now());
145
+ };
146
+ // Images must stay on peers advertising vision, even if the last text turn used another peer.
147
+ let next = needsImages ? await nextPeer() : paid ? ((await nextPeer()) ?? model.id) : (working.get(model.id) ?? model.id);
148
+ if (needsImages && !next)
149
+ throw new Error(`No vision provider is available for ${model.name} right now. Try again or pick another vision model with /model.`);
150
+ let firstError;
151
+ let outOfCredits = false;
152
+ while (next) {
153
+ tried.add(next);
154
+ const attempt = next;
155
+ next = undefined;
156
+ const silent = new AbortController();
157
+ const timer = setTimeout(() => silent.abort(), ANSWER_TIMEOUT_MS);
158
+ const signal = options?.signal ? AbortSignal.any([options.signal, silent.signal]) : silent.signal;
159
+ const events = base().streamSimple({ ...model, id: attempt }, context, { ...options, signal });
160
+ let started = false;
161
+ try {
162
+ for await (const event of events) {
163
+ // Nothing has reached the chat yet, so a refusal here can still go to another peer.
164
+ const refused = event.type === "error" && (silent.signal.aborted || worthAnotherPeer(event.error.errorMessage));
165
+ if (!started && refused && !options?.signal?.aborted) {
166
+ firstError ??= event;
167
+ cooling.set(attempt, Date.now() + COOLDOWN_MS);
168
+ if (working.get(model.id) === attempt)
169
+ working.delete(model.id);
170
+ // A paid 402 means the wallet itself is empty, so every peer would say the same.
171
+ outOfCredits = paid && /^\s*402\b/.test(event.error.errorMessage ?? "");
172
+ if (!outOfCredits && !(paid && tried.size >= MAX_PAID_TRIES))
173
+ next = await nextPeer();
174
+ break;
175
+ }
176
+ if (!started) {
177
+ started = true;
178
+ clearTimeout(timer);
179
+ if (!paid && attempt !== model.id)
180
+ working.set(model.id, attempt);
181
+ }
182
+ out.push(event);
183
+ }
184
+ }
185
+ finally {
186
+ clearTimeout(timer);
187
+ }
188
+ if (started)
189
+ return out.end();
190
+ }
191
+ // Every peer refused. The gateway's own message (a 402 asking to deposit funds, or a
192
+ // peer hash) means nothing to an attendee, so say what happened instead.
193
+ if (firstError?.type === "error") {
194
+ const errorMessage = outOfCredits
195
+ ? `Klui is out of credits for ${model.name}. Pick a free model with /model.`
196
+ : paid
197
+ ? `No provider is answering for ${model.name} right now. Try again, or pick another model with /model.`
198
+ : `No free provider is serving ${model.name} right now. Pick another model with /model.`;
199
+ out.push({ ...firstError, error: { ...firstError.error, errorMessage } });
200
+ }
201
+ out.end();
202
+ })().catch((error) => {
203
+ const reason = options?.signal?.aborted ? "aborted" : "error";
204
+ out.push({
205
+ type: "error",
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() },
208
+ });
209
+ out.end();
210
+ });
211
+ return out;
212
+ },
213
+ };
214
+ }
215
+ function emptyUsage() {
216
+ return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } };
217
+ }
package/dist/images.js ADDED
@@ -0,0 +1,70 @@
1
+ // Images in the composer. ctrl+v with an image on the clipboard drops an "[Image #1]" chip where
2
+ // the cursor is (Pi itself pastes the path of a temp file, which a model can only reach through
3
+ // its read tool, and not at all when the model is text only). Image files dragged into the
4
+ // terminal arrive as paths; those stay in the text so the model knows where the file is. On
5
+ // send, both go along with the message as real image attachments.
6
+ import { existsSync, readFileSync, realpathSync } from "node:fs";
7
+ import { homedir } from "node:os";
8
+ import { extname } from "node:path";
9
+ const MIME = { ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".gif": "image/gif", ".webp": "image/webp" };
10
+ /** Where Pi saves a pasted clipboard image. */
11
+ const CLIPBOARD_FILE = /(?:^|[\\/])pi-clipboard-[0-9a-f-]+\.(?:png|jpe?g|gif|webp)$/i;
12
+ const CHIP = /\[Image #(\d+)\]/g;
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;
18
+ const pasted = new Map();
19
+ let nextNumber = 1;
20
+ export function isClipboardImageFile(text) {
21
+ return CLIPBOARD_FILE.test(text.trim());
22
+ }
23
+ /** Remember a pasted image file and return the chip that stands for it in the composer. */
24
+ export function chipFor(file) {
25
+ const number = nextNumber++;
26
+ pasted.set(number, file.trim());
27
+ return `[Image #${number}]`;
28
+ }
29
+ function load(file) {
30
+ const mimeType = MIME[extname(file).toLowerCase()];
31
+ if (!mimeType || !existsSync(file))
32
+ return undefined;
33
+ try {
34
+ return { type: "image", data: readFileSync(file).toString("base64"), mimeType };
35
+ }
36
+ catch {
37
+ return undefined;
38
+ }
39
+ }
40
+ /** The images a message refers to, in the order they appear: pasted chips and dropped files. */
41
+ export function collectImages(text) {
42
+ const found = [];
43
+ for (const match of text.matchAll(CHIP)) {
44
+ const file = pasted.get(Number(match[1]));
45
+ if (file)
46
+ found.push({ at: match.index, file });
47
+ }
48
+ for (const match of text.matchAll(IMAGE_PATH)) {
49
+ const raw = match[1] ?? match[2] ?? match[3].replaceAll("\\ ", " ");
50
+ found.push({ at: match.index, file: raw.startsWith("~/") ? `${homedir()}${raw.slice(1)}` : raw });
51
+ }
52
+ const seen = new Set();
53
+ const images = [];
54
+ for (const entry of found.sort((a, b) => a.at - b.at)) {
55
+ try {
56
+ // A chip and a dropped path can name the same file through different symlinks.
57
+ const file = realpathSync(entry.file);
58
+ if (seen.has(file))
59
+ continue;
60
+ seen.add(file);
61
+ const image = load(entry.file);
62
+ if (image)
63
+ images.push(image);
64
+ }
65
+ catch {
66
+ // A missing or unreadable file stays in the text, without an attachment.
67
+ }
68
+ }
69
+ return images;
70
+ }
package/dist/mascot.js ADDED
@@ -0,0 +1,73 @@
1
+ // The pixel Klui from the web app's composer (public/js/composerKlui.js), drawn with half blocks.
2
+ // Same flat style and colors: a plain body, block arms, two block legs and dark eyes.
3
+ import { canvas, fillRect, fromArt } from "./pixels.js";
4
+ export const KLUI = {
5
+ body: "#8fd3fb",
6
+ eye: "#16202e",
7
+ lid: "#56637f",
8
+ base: "#434e66",
9
+ screen: "#bfe6ff",
10
+ blush: "#ff9ecb",
11
+ blue: "#2f6bff",
12
+ spark: "#ffd479",
13
+ };
14
+ /**
15
+ * The full-size Klui for the header: 28 columns by 9 rows. The face sits on whole cells (even
16
+ * rows, two pixels tall) so no half block meets a different color, which fonts draw with a seam.
17
+ */
18
+ export function bigKlui(eyes = "open") {
19
+ const c = KLUI;
20
+ const px = canvas(28, 18);
21
+ fillRect(px, 4, 0, 20, 12, c.body); // body
22
+ fillRect(px, 0, 4, 4, 4, c.body); // arms
23
+ fillRect(px, 24, 4, 4, 4, c.body);
24
+ fillRect(px, 8, 12, 2, 5, c.body); // legs
25
+ fillRect(px, 18, 12, 2, 5, c.body);
26
+ const eye = (x, kind) => {
27
+ switch (kind) {
28
+ case "open":
29
+ fillRect(px, x, 2, 2, 4, c.eye);
30
+ break;
31
+ case "shut":
32
+ case "wink":
33
+ fillRect(px, x - 1, 4, 4, 2, c.eye);
34
+ break;
35
+ case "happy":
36
+ fillRect(px, x - 1, 4, 1, 2, c.eye);
37
+ fillRect(px, x, 2, 2, 2, c.eye);
38
+ fillRect(px, x + 2, 4, 1, 2, c.eye);
39
+ break;
40
+ }
41
+ };
42
+ if (eyes === "side") {
43
+ // Looking sideways the eyes move left and sit closer together, like the web sprite.
44
+ eye(6, "open");
45
+ eye(12, "open");
46
+ }
47
+ else {
48
+ eye(8, eyes === "wink" ? "open" : eyes);
49
+ eye(18, eyes);
50
+ }
51
+ if (eyes === "happy" || eyes === "wink") {
52
+ fillRect(px, 5, 6, 2, 2, c.blush);
53
+ fillRect(px, 21, 6, 2, 2, c.blush);
54
+ }
55
+ return px;
56
+ }
57
+ const MINI_PALETTE = { B: KLUI.body, E: KLUI.eye, P: KLUI.blush };
58
+ /**
59
+ * The header Klui, drawn like the web sprite: a 10 x 6 body with block arms at its middle, tall
60
+ * dark eyes and two legs, blushing when happy. 14 columns by 4 rows. The eyes fill exactly one cell each, since a cell
61
+ * split between eye and body shows a seam (an "eyebrow") in most fonts. A blink hides them.
62
+ */
63
+ export function smallKlui(eyes = "open") {
64
+ const face = {
65
+ open: "BBBBEBBBBEBBBB",
66
+ side: "BBBEBBBBEBBBBB",
67
+ shut: "BBBBBBBBBBBBBB",
68
+ wink: "BBBBEBBBBBBBBB",
69
+ happy: "BBBBEBBBBEBBBB",
70
+ }[eyes];
71
+ const cheeks = eyes === "happy" || eyes === "wink" ? "..BPBBBBBBPB.." : "..BBBBBBBBBB..";
72
+ return fromArt(["..BBBBBBBBBB..", "..BBBBBBBBBB..", face, face, cheeks, cheeks, "....B....B....", "....B....B...."], MINI_PALETTE);
73
+ }
package/dist/pass.js ADDED
@@ -0,0 +1,124 @@
1
+ // Talks to Klui Pass: fetches the event config and gets this device its own AntSeed gateway key.
2
+ // Every key draws from the one wallet Klui funds for the event, with a spend cap per key.
3
+ import { randomBytes } from "node:crypto";
4
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
5
+ import { dirname } from "node:path";
6
+ import { BUNDLED_CONFIG, sanitizeConfig } from "./catalog.js";
7
+ import { CONFIG_CACHE_FILE, DEVICE_FILE, PASS_URL, VERSION } from "./paths.js";
8
+ export class PassError extends Error {
9
+ code;
10
+ constructor(message, code) {
11
+ super(message);
12
+ this.code = code;
13
+ }
14
+ }
15
+ function readJson(file) {
16
+ try {
17
+ return JSON.parse(readFileSync(file, "utf8"));
18
+ }
19
+ catch {
20
+ return undefined;
21
+ }
22
+ }
23
+ function writeJson(file, value) {
24
+ mkdirSync(dirname(file), { recursive: true });
25
+ const tmp = `${file}.${process.pid}.tmp`;
26
+ writeFileSync(tmp, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
27
+ renameSync(tmp, file);
28
+ }
29
+ export function readDevice() {
30
+ const saved = readJson(DEVICE_FILE);
31
+ if (saved?.deviceId)
32
+ return saved;
33
+ const fresh = { deviceId: randomBytes(16).toString("hex") };
34
+ writeJson(DEVICE_FILE, fresh);
35
+ return fresh;
36
+ }
37
+ export function saveDevice(state) {
38
+ writeJson(DEVICE_FILE, state);
39
+ }
40
+ export function readCachedConfig() {
41
+ return sanitizeConfig(readJson(CONFIG_CACHE_FILE));
42
+ }
43
+ async function request(path, init) {
44
+ const response = await fetch(`${PASS_URL}${path}`, {
45
+ ...init,
46
+ headers: { "content-type": "application/json", "user-agent": `klui-code/${VERSION}`, ...init.headers },
47
+ signal: AbortSignal.timeout(init.timeoutMs),
48
+ });
49
+ const body = (await response.json().catch(() => undefined));
50
+ if (!response.ok) {
51
+ throw new PassError(body?.error?.message ?? `Klui Pass answered ${response.status}`, body?.error?.code ?? `http_${response.status}`);
52
+ }
53
+ return body;
54
+ }
55
+ /** The event config from Klui Pass, saved for next launch, or undefined when Pass doesn't answer. */
56
+ async function fetchConfig() {
57
+ try {
58
+ const config = sanitizeConfig(await request("/v1/config", { method: "GET", timeoutMs: 4000 }));
59
+ if (config)
60
+ writeJson(CONFIG_CACHE_FILE, config);
61
+ return config;
62
+ }
63
+ catch {
64
+ return undefined; // Offline or Pass is down.
65
+ }
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
+ const override = process.env.KLUI_BASE_URL?.replace(/\/+$/, "");
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 };
77
+ }
78
+ /** Make sure this device holds a key for the gateway in `config`, registering when needed. */
79
+ export async function ensureKey(config, opts = {}) {
80
+ const device = readDevice();
81
+ if (process.env.KLUI_API_KEY)
82
+ return { ...device, apiKey: process.env.KLUI_API_KEY, baseUrl: config.baseUrl };
83
+ if (!opts.force && device.apiKey && device.baseUrl === config.baseUrl)
84
+ return device;
85
+ const result = (await request("/v1/register", {
86
+ method: "POST",
87
+ body: JSON.stringify({ deviceId: device.deviceId, version: VERSION }),
88
+ timeoutMs: 10_000,
89
+ }));
90
+ if (typeof result?.apiKey !== "string")
91
+ throw new PassError("Klui Pass sent no key", "bad_response");
92
+ const next = { deviceId: device.deviceId, apiKey: result.apiKey, baseUrl: config.baseUrl };
93
+ saveDevice(next);
94
+ return next;
95
+ }
96
+ /** Remaining event credits for this key, from the AntSeed gateway's `/key` endpoint. */
97
+ export async function fetchCredits(baseUrl, apiKey) {
98
+ try {
99
+ const root = baseUrl.replace(/\/v1$/, "");
100
+ const response = await fetch(`${root}/key`, {
101
+ headers: { authorization: `Bearer ${apiKey}` },
102
+ signal: AbortSignal.timeout(5000),
103
+ });
104
+ if (!response.ok)
105
+ return undefined;
106
+ const body = (await response.json());
107
+ const limits = body.data?.limits ?? {};
108
+ // Report whichever cap runs out first.
109
+ let best = { remainingUsd: null, limitUsd: null, period: null };
110
+ for (const period of ["daily", "total"]) {
111
+ const entry = limits[period];
112
+ if (!entry || entry.remaining_usd == null)
113
+ continue;
114
+ const remaining = Number(entry.remaining_usd);
115
+ if (best.remainingUsd === null || remaining < best.remainingUsd) {
116
+ best = { remainingUsd: remaining, limitUsd: entry.limit_usd == null ? null : Number(entry.limit_usd), period };
117
+ }
118
+ }
119
+ return best;
120
+ }
121
+ catch {
122
+ return undefined;
123
+ }
124
+ }
package/dist/paths.js ADDED
@@ -0,0 +1,23 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { dirname, join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ /** Root of the installed klui package (one level above dist/). */
6
+ export const PACKAGE_DIR = join(dirname(fileURLToPath(import.meta.url)), "..");
7
+ export const THEMES_DIR = join(PACKAGE_DIR, "themes");
8
+ export const VERSION = (() => {
9
+ try {
10
+ return JSON.parse(readFileSync(join(PACKAGE_DIR, "package.json"), "utf8")).version ?? "0.0.0";
11
+ }
12
+ catch {
13
+ return "0.0.0";
14
+ }
15
+ })();
16
+ /** Everything klui stores lives here, apart from Pi's own agent directory inside it. */
17
+ export const KLUI_HOME = process.env.KLUI_HOME || join(homedir(), ".klui");
18
+ export const AGENT_DIR = join(KLUI_HOME, "agent");
19
+ export const DEVICE_FILE = join(KLUI_HOME, "device.json");
20
+ export const CONFIG_CACHE_FILE = join(KLUI_HOME, "config-cache.json");
21
+ /** The Klui Pass service hands out event keys and the model list. */
22
+ export const PASS_URL = (process.env.KLUI_PASS_URL || "https://klui.ai/code/pass").replace(/\/+$/, "");
23
+ export const PROVIDER = "klui";