klui-code 0.1.3 → 0.1.5
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 +22 -8
- package/dist/cli.js +2 -0
- package/dist/extension/agents.js +412 -61
- package/dist/extension/browser.js +179 -0
- package/dist/extension/checks.js +1 -1
- package/dist/extension/commands.js +3 -3
- package/dist/extension/index.js +99 -15
- package/dist/extension/permissions.js +77 -36
- package/dist/extension/todos.js +2 -2
- package/dist/extension/tools.js +11 -6
- package/dist/extension/voice.js +53 -8
- package/dist/extension/web.js +12 -5
- package/dist/extension/working.js +47 -15
- package/dist/fallback.js +130 -37
- package/dist/mascot.js +15 -0
- package/dist/pi-patches.js +55 -5
- package/dist/usage.js +56 -21
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
package/dist/extension/voice.js
CHANGED
|
@@ -1,10 +1,30 @@
|
|
|
1
1
|
// Klui's voice, shared with the web app's thinking bar and home greeting (public/js/klui.js).
|
|
2
2
|
export const PHRASES = {
|
|
3
|
-
thinking: [
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
3
|
+
thinking: [
|
|
4
|
+
"locking in",
|
|
5
|
+
"connecting the dots",
|
|
6
|
+
"big brain time",
|
|
7
|
+
"cooking something up",
|
|
8
|
+
"thinking it through",
|
|
9
|
+
"flabbergasting",
|
|
10
|
+
"percolating",
|
|
11
|
+
"noodling on it",
|
|
12
|
+
"galaxy-braining",
|
|
13
|
+
"scheming",
|
|
14
|
+
"simmering",
|
|
15
|
+
"marinating",
|
|
16
|
+
"vibing it out",
|
|
17
|
+
"conjuring",
|
|
18
|
+
"cogitating",
|
|
19
|
+
"brewing ideas",
|
|
20
|
+
"pondering the orb",
|
|
21
|
+
"doing the math",
|
|
22
|
+
],
|
|
23
|
+
reading: ["taking notes", "highlighting the good bits", "skimming the code", "reading the room", "speed reading", "absorbing the lore", "peeking inside", "nose in the docs"],
|
|
24
|
+
searching: ["hunting it down", "digging around", "following the trail", "sifting results", "rummaging", "spelunking", "on the case", "sniffing it out", "treasure hunting"],
|
|
25
|
+
running: ["running it", "pressing buttons", "watching the logs", "crossing fingers", "taking it for a spin", "kicking the tires", "hold onto your hat", "letting it rip"],
|
|
26
|
+
writing: ["making edits", "writing the code", "finding the words", "polishing pixels", "finagling", "tinkering", "sprinkling magic", "bamboozling the bugs", "shipping bits"],
|
|
27
|
+
delegating: ["rallying the crew", "teamwork mode", "the helpers are on it", "divide and conquer", "assembling the squad", "minions deployed", "calling in backup"],
|
|
8
28
|
};
|
|
9
29
|
export const GREETINGS = [
|
|
10
30
|
"what are we building?",
|
|
@@ -16,7 +36,7 @@ export const GREETINGS = [
|
|
|
16
36
|
"got an idea? let's ship it",
|
|
17
37
|
"hackathon mode: on",
|
|
18
38
|
];
|
|
19
|
-
export const DONE_LINES = ["done!", "shipped it", "all yours", "ta-da", "nailed it", "that's a wrap"];
|
|
39
|
+
export const DONE_LINES = ["done!", "shipped it", "all yours", "ta-da", "nailed it", "that's a wrap", "voilà", "chef's kiss", "easy peasy", "and scene", "bam!", "mission accomplished"];
|
|
20
40
|
export function pick(items, avoid) {
|
|
21
41
|
if (items.length < 2)
|
|
22
42
|
return items[0];
|
|
@@ -47,12 +67,37 @@ export function describeTool(toolName, args) {
|
|
|
47
67
|
case "todo":
|
|
48
68
|
return { activity: "thinking", detail: "updating the plan" };
|
|
49
69
|
case "subagent":
|
|
50
|
-
return { activity: "
|
|
70
|
+
return { activity: "delegating", detail: `a subagent is ${args?.kind === "general" ? "on it" : "exploring"}` };
|
|
51
71
|
default:
|
|
52
72
|
return { activity: "thinking", detail: `using ${toolName}` };
|
|
53
73
|
}
|
|
54
74
|
}
|
|
55
|
-
|
|
75
|
+
/**
|
|
76
|
+
* What Klui says while the model is still writing out a tool call, before it runs: a big write can
|
|
77
|
+
* stream for minutes. `args` is the JSON so far; the path or command shows up as soon as it's in.
|
|
78
|
+
*/
|
|
79
|
+
export function preparingLabel(toolName, args) {
|
|
80
|
+
const field = (name) => {
|
|
81
|
+
const raw = new RegExp(`"${name}"\\s*:\\s*"((?:[^"\\\\]|\\\\.)*)`).exec(args)?.[1];
|
|
82
|
+
return raw?.replace(/\\n/g, "\n").replace(/\\(.)/g, "$1");
|
|
83
|
+
};
|
|
84
|
+
const path = field("path") ?? field("file_path");
|
|
85
|
+
switch (toolName) {
|
|
86
|
+
case "write":
|
|
87
|
+
return path ? `drafting ${shortPath(path)}` : "drafting a file";
|
|
88
|
+
case "edit":
|
|
89
|
+
return path ? `drafting an edit to ${shortPath(path)}` : "drafting an edit";
|
|
90
|
+
case "bash": {
|
|
91
|
+
const command = field("command")?.split("\n")[0]?.trim();
|
|
92
|
+
return command ? `drafting $ ${clip(command, 36)}` : "drafting a command";
|
|
93
|
+
}
|
|
94
|
+
case "subagent":
|
|
95
|
+
return "briefing a subagent";
|
|
96
|
+
default:
|
|
97
|
+
return `getting ${toolName} ready`;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
export function shortPath(path) {
|
|
56
101
|
const parts = path.split("/").filter(Boolean);
|
|
57
102
|
return parts.length > 2 ? `…/${parts.slice(-2).join("/")}` : path;
|
|
58
103
|
}
|
package/dist/extension/web.js
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
// Exa's public MCP endpoint and falls back to DuckDuckGo's HTML page.
|
|
4
4
|
import { Type } from "typebox";
|
|
5
5
|
const TIMEOUT_MS = 20_000;
|
|
6
|
-
const
|
|
6
|
+
const MAX_PAGE_BYTES = 10 * 1024 * 1024;
|
|
7
7
|
/** When these tools can't get through, the model can still reach the web from the shell. */
|
|
8
8
|
const USE_CURL = "Fall back to curl in bash (for search: https://html.duckduckgo.com/html/?q=...).";
|
|
9
9
|
export function registerWeb(pi) {
|
|
@@ -28,7 +28,7 @@ export function registerWeb(pi) {
|
|
|
28
28
|
pi.registerTool({
|
|
29
29
|
name: "web_fetch",
|
|
30
30
|
label: "Web fetch",
|
|
31
|
-
description:
|
|
31
|
+
description: "Fetch a URL and return its full text (HTML is reduced to plain text; downloads over 10 MiB are rejected).",
|
|
32
32
|
promptSnippet: "web_fetch: read a web page or other URL as text",
|
|
33
33
|
parameters: Type.Object({
|
|
34
34
|
url: Type.String({ description: "The http(s) URL to fetch" }),
|
|
@@ -42,11 +42,18 @@ export function registerWeb(pi) {
|
|
|
42
42
|
});
|
|
43
43
|
if (!response.ok)
|
|
44
44
|
throw new Error(`${params.url} answered ${response.status}. ${USE_CURL}`);
|
|
45
|
-
const
|
|
45
|
+
const chunks = [];
|
|
46
|
+
let size = 0;
|
|
47
|
+
for await (const chunk of response.body ?? []) {
|
|
48
|
+
size += chunk.byteLength;
|
|
49
|
+
if (size > MAX_PAGE_BYTES)
|
|
50
|
+
throw new Error(`${params.url} exceeds the 10 MiB download limit. Fetch a smaller page or section.`);
|
|
51
|
+
chunks.push(chunk);
|
|
52
|
+
}
|
|
53
|
+
const body = new TextDecoder().decode(Buffer.concat(chunks));
|
|
46
54
|
const html = /html/i.test(response.headers.get("content-type") ?? "");
|
|
47
55
|
const text = (html ? htmlToText(body) : body).trim();
|
|
48
|
-
|
|
49
|
-
return { content: [{ type: "text", text: cut || "(empty page)" }], details: { chars: text.length } };
|
|
56
|
+
return { content: [{ type: "text", text: text || "(empty page)" }], details: { chars: text.length } };
|
|
50
57
|
},
|
|
51
58
|
});
|
|
52
59
|
}
|
|
@@ -1,8 +1,10 @@
|
|
|
1
|
-
// While the agent works, one
|
|
2
|
-
//
|
|
1
|
+
// While the agent works, a tiny one-row Klui sits above the editor and acts out what it's doing
|
|
2
|
+
// (looking around while it reads, typing while it writes, hopping while a command runs, waving
|
|
3
|
+
// while subagents work), next to a shimmering phrase and the time and tokens so far. When the run
|
|
4
|
+
// ends it cheers for a moment, with how fast the replies streamed.
|
|
3
5
|
import { keyText } from "@earendil-works/pi-coding-agent";
|
|
4
|
-
import {
|
|
5
|
-
import { KLUI } from "../mascot.js";
|
|
6
|
+
import { foregroundAnsi, parseColor, truncateToWidth } from "@earendil-works/pi-tui";
|
|
7
|
+
import { KLUI, tinyKlui } from "../mascot.js";
|
|
6
8
|
import { mixHex } from "../pixels.js";
|
|
7
9
|
import { DONE_LINES, PHRASES, pick } from "./voice.js";
|
|
8
10
|
const FRAME_MS = 50;
|
|
@@ -10,6 +12,7 @@ const PHRASE_MS = 3600;
|
|
|
10
12
|
/** The animated working line. `status()` is read on every frame. */
|
|
11
13
|
export function createWorkingWidget(tui, theme, status, reducedMotion) {
|
|
12
14
|
let frame = 0;
|
|
15
|
+
const bornAt = Date.now();
|
|
13
16
|
let activity = status().activity;
|
|
14
17
|
let phrase = pick(PHRASES[activity]);
|
|
15
18
|
let phraseAt = Date.now();
|
|
@@ -28,14 +31,16 @@ export function createWorkingWidget(tui, theme, status, reducedMotion) {
|
|
|
28
31
|
return {
|
|
29
32
|
render(width) {
|
|
30
33
|
const current = status();
|
|
34
|
+
const now = Date.now();
|
|
35
|
+
const t = reducedMotion ? 0 : now - bornAt;
|
|
31
36
|
const title = reducedMotion ? theme.fg("accent", `${phrase}…`) : shimmer(`${phrase}…`, frame, theme);
|
|
32
37
|
const meta = [
|
|
33
38
|
current.detail,
|
|
34
|
-
formatElapsed(
|
|
39
|
+
formatElapsed(now - current.startedAt),
|
|
35
40
|
current.tokens > 0 ? `↓ ${formatTokens(current.tokens)} tokens` : undefined,
|
|
36
41
|
`${keyText("app.interrupt")} to stop`,
|
|
37
42
|
].filter(Boolean);
|
|
38
|
-
return
|
|
43
|
+
return rows(workingPose(current.activity, t), title, meta.join(" · "), theme, width);
|
|
39
44
|
},
|
|
40
45
|
invalidate() { },
|
|
41
46
|
dispose() {
|
|
@@ -48,25 +53,52 @@ export function createDoneWidget(theme, outcome) {
|
|
|
48
53
|
const happy = !outcome.aborted && !outcome.error;
|
|
49
54
|
const said = happy ? pick(DONE_LINES) : outcome.aborted ? "stopped" : "hit a snag";
|
|
50
55
|
const title = happy ? theme.bold(theme.fg("accent", said)) : theme.fg(outcome.aborted ? "muted" : "error", said);
|
|
56
|
+
const pose = happy
|
|
57
|
+
? { eyes: "happy", arms: "up", step: false }
|
|
58
|
+
: { eyes: "left", arms: "down", step: false }; // a sheepish glance away
|
|
51
59
|
const meta = [
|
|
52
60
|
formatElapsed(Date.now() - outcome.startedAt),
|
|
53
61
|
outcome.tokens > 0 ? `↓ ${formatTokens(outcome.tokens)} tokens` : undefined,
|
|
62
|
+
outcome.tokensPerSecond ? `${outcome.tokensPerSecond} tok/s` : undefined,
|
|
54
63
|
outcome.error,
|
|
55
64
|
].filter(Boolean);
|
|
56
65
|
return {
|
|
57
|
-
render: (width) =>
|
|
66
|
+
render: (width) => rows(pose, title, meta.join(" · "), theme, width),
|
|
58
67
|
invalidate() { },
|
|
59
68
|
};
|
|
60
69
|
}
|
|
61
|
-
|
|
62
|
-
|
|
70
|
+
/** One row: Klui, the phrase, then the numbers dimmed. */
|
|
71
|
+
function rows(pose, title, meta, theme, width) {
|
|
72
|
+
const dim = foregroundAnsi(parseColor(theme.appearance === "light" ? "#56637f" : "#7f93b2"), theme.getColorMode());
|
|
73
|
+
return [truncateToWidth(` ${tinyKlui(pose, theme.getColorMode())} ${title} ${dim}${meta}\x1b[39m`, width)];
|
|
63
74
|
}
|
|
64
|
-
/**
|
|
65
|
-
function
|
|
66
|
-
const
|
|
67
|
-
const
|
|
68
|
-
const
|
|
69
|
-
|
|
75
|
+
/** What Klui does while it works: it blinks now and then, and acts out the activity. */
|
|
76
|
+
export function workingPose(activity, t) {
|
|
77
|
+
const blink = t % 3400 > 3240;
|
|
78
|
+
const pose = { eyes: blink ? "shut" : "open", arms: "down", step: false };
|
|
79
|
+
const beat = (ms) => Math.floor(t / ms) % 2 === 1;
|
|
80
|
+
switch (activity) {
|
|
81
|
+
case "reading":
|
|
82
|
+
case "searching":
|
|
83
|
+
if (!blink)
|
|
84
|
+
pose.eyes = beat(900) ? "left" : "right";
|
|
85
|
+
break;
|
|
86
|
+
case "writing":
|
|
87
|
+
pose.arms = beat(180) ? "left" : "right";
|
|
88
|
+
break;
|
|
89
|
+
case "running":
|
|
90
|
+
pose.step = beat(220);
|
|
91
|
+
break;
|
|
92
|
+
case "delegating":
|
|
93
|
+
pose.arms = beat(350) ? "right" : "down";
|
|
94
|
+
break;
|
|
95
|
+
case "thinking":
|
|
96
|
+
// Every so often it glances aside, mulling it over.
|
|
97
|
+
if (!blink && t % 5200 > 4200)
|
|
98
|
+
pose.eyes = "left";
|
|
99
|
+
break;
|
|
100
|
+
}
|
|
101
|
+
return pose;
|
|
70
102
|
}
|
|
71
103
|
/** A bright band sweeping across the text, sky blue to white. Plain accent on 256-color terminals. */
|
|
72
104
|
function shimmer(text, frame, theme) {
|
package/dist/fallback.js
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
// a `paid` model tries free peers first, then the best mix of price and reputation; a `free` one
|
|
4
4
|
// stays on peers serving it for free. A request a peer can't serve moves to the next one, and only
|
|
5
5
|
// when none of them answers does the error reach the chat.
|
|
6
|
-
import { createAssistantMessageEventStream } from "@earendil-works/pi-ai";
|
|
6
|
+
import { createAssistantMessageEventStream, isContextOverflow, } from "@earendil-works/pi-ai";
|
|
7
7
|
import { getApiProvider } from "@earendil-works/pi-ai/compat";
|
|
8
8
|
/** A coding turn re-sends the conversation, so most of its input is already cached on the peer. */
|
|
9
9
|
const TURN_MIX = { cached: 24, input: 6, output: 1 };
|
|
@@ -11,13 +11,35 @@ const TURN_MIX = { cached: 24, input: 6, output: 1 };
|
|
|
11
11
|
const COST_WEIGHT = 0.75;
|
|
12
12
|
/** Klui's minimum reputation for paid peers, shared by every AntSeed model. */
|
|
13
13
|
const MIN_REPUTATION = 51;
|
|
14
|
+
/**
|
|
15
|
+
* Sellers we've checked read images on these models (Oct 2026: each named both colors of a
|
|
16
|
+
* two-color picture, and its token counts matched the model's own tokenizer), by peer id. Many
|
|
17
|
+
* don't say so in the gateway list, so an image goes to these first, by the usual price and
|
|
18
|
+
* reputation pick but past the reputation cutoff, since we know they work. Sellers that only advertise
|
|
19
|
+
* images come after.
|
|
20
|
+
*/
|
|
21
|
+
const VISION_TESTED = {
|
|
22
|
+
"666e688780b9fdee5d2fe8ccafa666bb084c4666": ["deepseek-v4.1-flash"], // bartly.eth64.de
|
|
23
|
+
"0b0b9574d5b038f6fd906325e699020423adf446": ["deepseek-v4.1-flash"], // ZLKPro-Api
|
|
24
|
+
"9e402b4d2b20f723ea8b7ae32bd46fec6d2a8ec3": ["deepseek-v4.1-flash"], // engy
|
|
25
|
+
"0ee134b462785a6407860278ced89d193e1d6c41": ["deepseek-v4.1-flash"], // klinn
|
|
26
|
+
"c3cf17082a164c4cf3504d50962668649d327662": ["deepseek-v4.1-flash"], // Apiport
|
|
27
|
+
};
|
|
14
28
|
/** A peer that failed sits out this long before it's tried again. */
|
|
15
29
|
const COOLDOWN_MS = 10 * 60_000;
|
|
16
30
|
/** Paid peers tried per request: each failure can cost a timeout, and paid peers rarely all fail. */
|
|
17
31
|
const MAX_PAID_TRIES = 4;
|
|
32
|
+
/** Once a reply streams, a peer that sends nothing (no text, reasoning or tool call) this long has stalled. */
|
|
33
|
+
const STALL_MS = 45_000;
|
|
18
34
|
/**
|
|
19
|
-
*
|
|
20
|
-
*
|
|
35
|
+
* All the chat ever says about a failed provider: what went wrong is for troubleshooting, so it goes
|
|
36
|
+
* in the usage log (see usage.ts). Pi retries a reply that failed with it (see pi-patches.ts).
|
|
37
|
+
*/
|
|
38
|
+
export const PROVIDER_ISSUE = "Klui had a model provider issue. Please retry.";
|
|
39
|
+
/**
|
|
40
|
+
* A peer that hasn't started answering by now is treated as gone (some hang without a word, others
|
|
41
|
+
* send headers and then nothing). Long prompts get longer: reading an uncached 900K-token
|
|
42
|
+
* conversation alone takes a peer 20-30 s.
|
|
21
43
|
*/
|
|
22
44
|
export function answerTimeoutMs(context) {
|
|
23
45
|
// About 4 characters a token; image data is left out, since a picture costs far fewer tokens than its base64.
|
|
@@ -29,6 +51,42 @@ export function serviceOf(id) {
|
|
|
29
51
|
const at = id.indexOf("@");
|
|
30
52
|
return at === -1 ? id : id.slice(at + 1);
|
|
31
53
|
}
|
|
54
|
+
/**
|
|
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.
|
|
57
|
+
*/
|
|
58
|
+
function sellerAside(event, id) {
|
|
59
|
+
const reply = event.type === "done" ? event.message : event.type === "error" ? event.error : "partial" in event ? event.partial : undefined;
|
|
60
|
+
if (reply && reply.model !== id) {
|
|
61
|
+
reply.responseModel = reply.model;
|
|
62
|
+
reply.model = id;
|
|
63
|
+
}
|
|
64
|
+
return event;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Pi replays a reply's reasoning only to the model that wrote it, by id. Replies keep the event
|
|
68
|
+
* 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.
|
|
70
|
+
*/
|
|
71
|
+
function asSeller(context, attempt) {
|
|
72
|
+
if (!context.messages.some((m) => m.role === "assistant" && m.responseModel === attempt))
|
|
73
|
+
return context;
|
|
74
|
+
return { ...context, messages: context.messages.map((m) => (m.role === "assistant" && m.responseModel === attempt ? { ...m, model: attempt } : m)) };
|
|
75
|
+
}
|
|
76
|
+
/** A failure whose own message is for the user (Klui can't connect, say), not a provider's. */
|
|
77
|
+
class ForTheUser extends Error {
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* A failure as the chat shows it: PROVIDER_ISSUE, with what the peers said kept in `providerError`
|
|
81
|
+
* for the usage log. A context overflow keeps its own message, so Pi compacts the chat and goes on.
|
|
82
|
+
*/
|
|
83
|
+
function providerIssue(event, id, failures) {
|
|
84
|
+
if (event.type !== "error")
|
|
85
|
+
return event;
|
|
86
|
+
const failed = { ...event.error, stopReason: "error" };
|
|
87
|
+
const errorMessage = isContextOverflow(failed, 0) ? failed.errorMessage : PROVIDER_ISSUE;
|
|
88
|
+
return sellerAside({ type: "error", reason: "error", error: { ...failed, errorMessage, providerError: failures.join(" | ").slice(0, 1000) } }, id);
|
|
89
|
+
}
|
|
32
90
|
/** What a typical turn costs on this offer, in USD per million tokens. */
|
|
33
91
|
export function turnPrice(offer) {
|
|
34
92
|
const { inputUsdPerMillion: input, outputUsdPerMillion: output } = offer;
|
|
@@ -42,7 +100,8 @@ export function turnPrice(offer) {
|
|
|
42
100
|
* Peers serving the model under any of `names` over chat completions, as pinned gateway ids, best
|
|
43
101
|
* first. A peer's score is 75% price (cheapest 1, dearest 0, on a log scale since prices span
|
|
44
102
|
* 1000x) and 25% reputation. Free peers always come first. `freeOnly` keeps just those peers;
|
|
45
|
-
* paid peers below Klui's reputation cutoff are left out.
|
|
103
|
+
* paid peers below Klui's reputation cutoff are left out. With `needsImages`, sellers in
|
|
104
|
+
* VISION_TESTED come first (cutoff or not), then those advertising images.
|
|
46
105
|
*/
|
|
47
106
|
export function rankOffers(models, names, freeOnly = false, needsImages = false) {
|
|
48
107
|
const wanted = new Set(names.map((n) => n.toLowerCase()));
|
|
@@ -52,23 +111,27 @@ export function rankOffers(models, names, freeOnly = false, needsImages = false)
|
|
|
52
111
|
for (const offer of model.peers ?? []) {
|
|
53
112
|
if (!listed && !wanted.has(offer.serviceId.toLowerCase()))
|
|
54
113
|
continue;
|
|
55
|
-
|
|
114
|
+
const tested = needsImages && !!VISION_TESTED[offer.peerId]?.some((n) => wanted.has(n));
|
|
115
|
+
if (needsImages && !tested && !offer.capabilities?.inputs?.includes("image"))
|
|
56
116
|
continue;
|
|
57
117
|
const price = turnPrice(offer);
|
|
58
118
|
const chat = !offer.protocols || offer.protocols.includes("openai-chat-completions");
|
|
59
119
|
if (price === undefined || !chat || (freeOnly && price !== 0))
|
|
60
120
|
continue;
|
|
61
121
|
const reputation = offer.effectiveReputationScore ?? offer.reputationScore ?? 0;
|
|
62
|
-
if (price !== 0 && reputation < MIN_REPUTATION)
|
|
122
|
+
if (price !== 0 && reputation < MIN_REPUTATION && !tested)
|
|
63
123
|
continue;
|
|
64
124
|
const existing = offers.get(offer.peerId);
|
|
65
125
|
if (existing && existing.price <= price)
|
|
66
126
|
continue;
|
|
67
|
-
offers.set(offer.peerId, { id: `${offer.peerId}@${offer.serviceId}`, price, reputation: Math.min(Math.max(reputation / 100, 0), 1) });
|
|
127
|
+
offers.set(offer.peerId, { id: `${offer.peerId}@${offer.serviceId}`, price, reputation: Math.min(Math.max(reputation / 100, 0), 1), tested });
|
|
68
128
|
}
|
|
69
129
|
}
|
|
70
130
|
const all = [...offers.values()];
|
|
71
|
-
|
|
131
|
+
return [...rank(all.filter((o) => o.tested)), ...rank(all.filter((o) => !o.tested))];
|
|
132
|
+
}
|
|
133
|
+
/** Price/reputation orders the peers; a free offer always wins over a paid one. */
|
|
134
|
+
function rank(all) {
|
|
72
135
|
const logs = all.map((o) => Math.log(o.price + 1e-4));
|
|
73
136
|
const lo = Math.min(...logs);
|
|
74
137
|
const hi = Math.max(...logs);
|
|
@@ -133,15 +196,17 @@ export function createFallback(getConfig, getApiKey, connect = async () => undef
|
|
|
133
196
|
if (options?.signal?.aborted)
|
|
134
197
|
throw new Error("Request was aborted");
|
|
135
198
|
if (!getApiKey())
|
|
136
|
-
throw new
|
|
199
|
+
throw new ForTheUser(problem ?? "Can't reach Klui. Check your wifi and try again.");
|
|
137
200
|
// The gateway may have changed while this message waited for its key.
|
|
138
201
|
model = { ...model, baseUrl: getConfig().baseUrl };
|
|
139
202
|
}
|
|
140
203
|
// The key Pi started this request with may be the placeholder from before Klui connected.
|
|
141
204
|
options = { ...options, apiKey: getApiKey() };
|
|
142
205
|
if (!entry?.free && !entry?.paid) {
|
|
143
|
-
for await (const event of base().streamSimple(model, context, options))
|
|
144
|
-
|
|
206
|
+
for await (const event of base().streamSimple(model, context, options)) {
|
|
207
|
+
const failed = event.type === "error" && !options?.signal?.aborted;
|
|
208
|
+
out.push(failed ? providerIssue(event, model.id, [`${model.id}: ${event.error.errorMessage}`]) : event);
|
|
209
|
+
}
|
|
145
210
|
return out.end();
|
|
146
211
|
}
|
|
147
212
|
const tried = new Set();
|
|
@@ -155,39 +220,67 @@ export function createFallback(getConfig, getApiKey, connect = async () => undef
|
|
|
155
220
|
if (needsImages && !next)
|
|
156
221
|
throw new Error(`No vision provider is available for ${model.name} right now. Try again or pick another vision model with /model.`);
|
|
157
222
|
let firstError;
|
|
158
|
-
|
|
223
|
+
const broke = [];
|
|
224
|
+
/** What each peer that failed said, for the usage log. */
|
|
225
|
+
const failures = [];
|
|
159
226
|
const answerTimeout = answerTimeoutMs(context);
|
|
160
227
|
while (next) {
|
|
161
228
|
tried.add(next);
|
|
162
229
|
const attempt = next;
|
|
163
230
|
next = undefined;
|
|
164
231
|
const silent = new AbortController();
|
|
165
|
-
|
|
232
|
+
// Until the model says something, the peer has the whole answer timeout; after that,
|
|
233
|
+
// every text, reasoning or tool-call event restarts a shorter stall timer.
|
|
234
|
+
let timer = setTimeout(() => silent.abort(), answerTimeout);
|
|
166
235
|
const signal = options?.signal ? AbortSignal.any([options.signal, silent.signal]) : silent.signal;
|
|
167
|
-
const events = base().streamSimple({ ...model, id: attempt }, context, { ...options, signal });
|
|
236
|
+
const events = base().streamSimple({ ...model, id: attempt }, asSeller(context, attempt), { ...options, signal });
|
|
237
|
+
/** The start event comes with the response headers, before any token: held until the model says something. */
|
|
238
|
+
const held = [];
|
|
168
239
|
let started = false;
|
|
169
240
|
try {
|
|
170
241
|
for await (const event of events) {
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
242
|
+
if (event.type === "error") {
|
|
243
|
+
const stopped = !!options?.signal?.aborted;
|
|
244
|
+
const why = silent.signal.aborted ? `silent for ${(started ? STALL_MS : answerTimeout) / 1000}s` : (event.error.errorMessage ?? "error");
|
|
245
|
+
// Nothing has reached the chat yet, so a refusal here can still go to another peer.
|
|
246
|
+
if (!started && !stopped && (silent.signal.aborted || worthAnotherPeer(event.error.errorMessage))) {
|
|
247
|
+
firstError ??= event;
|
|
248
|
+
failures.push(`${attempt}: ${why}`);
|
|
249
|
+
cooling.set(attempt, Date.now() + COOLDOWN_MS);
|
|
250
|
+
if (working.get(model.id) === attempt)
|
|
251
|
+
working.delete(model.id);
|
|
252
|
+
// A paid 402 from one seller doesn't mean the wallet is empty: a seller Klui hasn't paid
|
|
253
|
+
// yet must first reserve part of it for a payment channel, which a small balance can't
|
|
254
|
+
// cover while sellers that already have one keep answering. So try the next seller, and
|
|
255
|
+
// only call it out of credits when every seller tried said 402.
|
|
256
|
+
broke.push(paid && /^\s*402\b/.test(event.error.errorMessage ?? ""));
|
|
257
|
+
if (!(paid && tried.size >= MAX_PAID_TRIES))
|
|
258
|
+
next = await nextPeer();
|
|
259
|
+
break;
|
|
260
|
+
}
|
|
261
|
+
// Stopped by the user, or failed (a stall included) after tokens reached the chat.
|
|
262
|
+
if (started && !stopped) {
|
|
263
|
+
cooling.set(attempt, Date.now() + COOLDOWN_MS);
|
|
264
|
+
if (working.get(model.id) === attempt)
|
|
265
|
+
working.delete(model.id);
|
|
266
|
+
}
|
|
267
|
+
out.push(stopped ? sellerAside(event, model.id) : providerIssue(event, model.id, [...failures, `${attempt}: ${why}`]));
|
|
268
|
+
return out.end();
|
|
183
269
|
}
|
|
270
|
+
if (!started && event.type === "start") {
|
|
271
|
+
held.push(event);
|
|
272
|
+
continue;
|
|
273
|
+
}
|
|
274
|
+
clearTimeout(timer);
|
|
275
|
+
timer = setTimeout(() => silent.abort(), STALL_MS);
|
|
184
276
|
if (!started) {
|
|
185
277
|
started = true;
|
|
186
|
-
clearTimeout(timer);
|
|
187
278
|
if (!paid && attempt !== model.id)
|
|
188
279
|
working.set(model.id, attempt);
|
|
280
|
+
for (const h of held)
|
|
281
|
+
out.push(sellerAside(h, model.id));
|
|
189
282
|
}
|
|
190
|
-
out.push(event);
|
|
283
|
+
out.push(sellerAside(event, model.id));
|
|
191
284
|
}
|
|
192
285
|
}
|
|
193
286
|
finally {
|
|
@@ -199,21 +292,21 @@ export function createFallback(getConfig, getApiKey, connect = async () => undef
|
|
|
199
292
|
// Every peer refused. The gateway's own message (a 402 asking to deposit funds, or a
|
|
200
293
|
// peer hash) means nothing to an attendee, so say what happened instead.
|
|
201
294
|
if (firstError?.type === "error") {
|
|
202
|
-
const
|
|
203
|
-
|
|
204
|
-
:
|
|
205
|
-
|
|
206
|
-
: `No free provider is serving ${model.name} right now. Pick another model with /model.`;
|
|
207
|
-
out.push({ ...firstError, error: { ...firstError.error, errorMessage } });
|
|
295
|
+
const outOfCredits = broke.length > 0 && broke.every(Boolean);
|
|
296
|
+
out.push(outOfCredits
|
|
297
|
+
? sellerAside({ ...firstError, error: { ...firstError.error, errorMessage: `Klui is out of credits for ${model.name}. Pick a free model with /model.` } }, model.id)
|
|
298
|
+
: providerIssue(firstError, model.id, failures));
|
|
208
299
|
}
|
|
209
300
|
out.end();
|
|
210
301
|
})().catch((error) => {
|
|
211
302
|
const reason = options?.signal?.aborted ? "aborted" : "error";
|
|
212
|
-
|
|
303
|
+
const said = error instanceof Error ? error.message : String(error);
|
|
304
|
+
const event = {
|
|
213
305
|
type: "error",
|
|
214
306
|
reason,
|
|
215
|
-
error: { role: "assistant", content: [], api: model.api, provider: model.provider, model: model.id, stopReason: reason, errorMessage:
|
|
216
|
-
}
|
|
307
|
+
error: { role: "assistant", content: [], api: model.api, provider: model.provider, model: model.id, stopReason: reason, errorMessage: said, usage: emptyUsage(), timestamp: Date.now() },
|
|
308
|
+
};
|
|
309
|
+
out.push(reason === "aborted" || error instanceof ForTheUser ? event : providerIssue(event, model.id, [said]));
|
|
217
310
|
out.end();
|
|
218
311
|
});
|
|
219
312
|
return out;
|
package/dist/mascot.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// The pixel Klui from the web app's composer (public/js/composerKlui.js), drawn with half blocks.
|
|
2
2
|
// Same flat style and colors: a plain body, block arms, two block legs and dark eyes.
|
|
3
|
+
import { backgroundAnsi, foregroundAnsi, parseColor } from "@earendil-works/pi-tui";
|
|
3
4
|
import { canvas, fillRect, fromArt } from "./pixels.js";
|
|
4
5
|
export const KLUI = {
|
|
5
6
|
body: "#8fd3fb",
|
|
@@ -71,3 +72,17 @@ export function smallKlui(eyes = "open") {
|
|
|
71
72
|
const cheeks = eyes === "happy" || eyes === "wink" ? "..BPBBBBBBPB.." : "..BBBBBBBBBB..";
|
|
72
73
|
return fromArt(["..BBBBBBBBBB..", "..BBBBBBBBBB..", face, face, cheeks, cheeks, "....B....B....", "....B....B...."], MINI_PALETTE);
|
|
73
74
|
}
|
|
75
|
+
const TINY_EYES = { open: " ▪ ▪ ", left: "▪ ▪ ", right: " ▪ ▪", shut: " - - ", happy: " ^ ^ " };
|
|
76
|
+
/**
|
|
77
|
+
* The working line's Klui, one row tall: a blue body with dark eyes and an arm nub on each side,
|
|
78
|
+
* 8 columns wide. At this size the eyes are glyphs on the body color rather than pixels, since a
|
|
79
|
+
* whole dark cell reads as a hole on a dark terminal.
|
|
80
|
+
*/
|
|
81
|
+
export function tinyKlui(pose, mode) {
|
|
82
|
+
const body = foregroundAnsi(parseColor(KLUI.body), mode);
|
|
83
|
+
const eye = foregroundAnsi(parseColor(KLUI.eye), mode);
|
|
84
|
+
const fill = backgroundAnsi(parseColor(KLUI.body), mode);
|
|
85
|
+
const up = (side) => (pose.arms === "up" || pose.arms === side ? "▀" : "▄");
|
|
86
|
+
const sprite = `${body}${up("left")}${fill}${eye}${TINY_EYES[pose.eyes]}\x1b[49m${body}${up("right")}\x1b[39m`;
|
|
87
|
+
return pose.step ? ` ${sprite}` : `${sprite} `;
|
|
88
|
+
}
|
package/dist/pi-patches.js
CHANGED
|
@@ -2,16 +2,60 @@
|
|
|
2
2
|
// Pi's own modules (the same instance Pi runs, resolved from its package) and is skipped quietly
|
|
3
3
|
// if a Pi update moves things around.
|
|
4
4
|
import { Spacer, TruncatedText, TuiAltScreen } from "@earendil-works/pi-tui";
|
|
5
|
+
import { PROVIDER_ISSUE, serviceOf } from "./fallback.js";
|
|
5
6
|
import { chipFor, isClipboardImageFile } from "./images.js";
|
|
7
|
+
import { PROVIDER } from "./paths.js";
|
|
6
8
|
import { scrollFrame } from "./scroll.js";
|
|
7
9
|
export const piModule = async (path) => (await import(new URL(path, import.meta.resolve("@earendil-works/pi-coding-agent")).href));
|
|
8
10
|
export async function patchPi(config) {
|
|
9
11
|
brandOutput();
|
|
10
12
|
scrollWithTerminal();
|
|
11
13
|
clearAfterCopy();
|
|
12
|
-
for (const patch of [hidePiFooter, hoverJumpToLatest, queuedMessages, trimSlashMenu, slashAliases, simpleThinkingMenu, thinkingAfterModel, () => tidyModelPicker(), () => quietPiHints(config), pasteImageChips])
|
|
14
|
+
for (const patch of [() => sellerModelIds(config), retryProviderIssues, removeLlama, hidePiFooter, hoverJumpToLatest, queuedMessages, trimSlashMenu, slashAliases, simpleThinkingMenu, thinkingAfterModel, () => tidyModelPicker(), () => quietPiHints(config), pasteImageChips])
|
|
13
15
|
await patch().catch(() => { });
|
|
14
16
|
}
|
|
17
|
+
/**
|
|
18
|
+
* Chats saved before 0.1.4 name the peer that answered (`<peer>@deepseek-v4-1-flash`) as the model,
|
|
19
|
+
* so resuming one looked for a model that doesn't exist and warned before falling back. Resolve
|
|
20
|
+
* such an id to the event model it serves.
|
|
21
|
+
*/
|
|
22
|
+
async function sellerModelIds(config) {
|
|
23
|
+
const { ModelRuntime } = await piModule("./core/model-runtime.js");
|
|
24
|
+
const proto = ModelRuntime.prototype;
|
|
25
|
+
const getModel = proto.getModel;
|
|
26
|
+
if (typeof getModel !== "function")
|
|
27
|
+
return;
|
|
28
|
+
proto.getModel = function (provider, id) {
|
|
29
|
+
const found = getModel.call(this, provider, id);
|
|
30
|
+
if (found || provider !== PROVIDER || !id.includes("@"))
|
|
31
|
+
return found;
|
|
32
|
+
const service = serviceOf(id);
|
|
33
|
+
const model = config.models.find((m) => m.id === service || m.aliases?.includes(service));
|
|
34
|
+
return model ? getModel.call(this, provider, model.id) : undefined;
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Klui shows a failed provider as PROVIDER_ISSUE rather than what it said (see fallback.ts), which
|
|
39
|
+
* Pi's retry wouldn't recognise as worth another try. It is: Pi waits and asks again (every 5s,
|
|
40
|
+
* three times; see seedSettings in cli.ts), a reply that stalled halfway included.
|
|
41
|
+
*/
|
|
42
|
+
async function retryProviderIssues() {
|
|
43
|
+
const { AgentSession } = await piModule("./core/agent-session.js");
|
|
44
|
+
const proto = AgentSession.prototype;
|
|
45
|
+
const isRetryable = proto._isRetryableError;
|
|
46
|
+
if (typeof isRetryable !== "function")
|
|
47
|
+
return;
|
|
48
|
+
proto._isRetryableError = function (message) {
|
|
49
|
+
return message.errorMessage === PROVIDER_ISSUE || isRetryable.call(this, message);
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
/** Klui uses event models, so don't load Pi's local llama.cpp manager or its /llama command. */
|
|
53
|
+
async function removeLlama() {
|
|
54
|
+
const { builtInExtensions } = await piModule("./extensions/index.js");
|
|
55
|
+
const index = builtInExtensions.findIndex((extension) => extension.name === "llama.cpp");
|
|
56
|
+
if (index !== -1)
|
|
57
|
+
builtInExtensions.splice(index, 1);
|
|
58
|
+
}
|
|
15
59
|
/** Klui puts its own footer in place once it loads; Pi's would show until then, and again on /new. */
|
|
16
60
|
async function hidePiFooter() {
|
|
17
61
|
const { FooterComponent } = await piModule("./modes/interactive/components/footer.js");
|
|
@@ -136,11 +180,11 @@ function rebrand(text) {
|
|
|
136
180
|
/**
|
|
137
181
|
* Klui's slash menu: /resume and /exit (see slashAliases) open /sessions and quit. Pi's /session,
|
|
138
182
|
* its bug reporter (it files issues with the Pi developers), its changelog and /scoped-models stay
|
|
139
|
-
* out of the list; they still work when typed.
|
|
183
|
+
* out of the list; they still work when typed. Provider login/logout are removed as well.
|
|
140
184
|
*/
|
|
141
185
|
async function trimSlashMenu() {
|
|
142
186
|
const { BUILTIN_SLASH_COMMANDS: commands } = await piModule("./core/slash-commands.js");
|
|
143
|
-
const hidden = new Set(["session", "bug", "changelog", "scoped-models"]);
|
|
187
|
+
const hidden = new Set(["session", "bug", "changelog", "scoped-models", "login", "logout"]);
|
|
144
188
|
for (let i = commands.length - 1; i >= 0; i--)
|
|
145
189
|
if (hidden.has(commands[i].name))
|
|
146
190
|
commands.splice(i, 1);
|
|
@@ -157,7 +201,7 @@ export function showThinkingMenu() {
|
|
|
157
201
|
if (interactive?.session.supportsThinking())
|
|
158
202
|
interactive.showThinkingSelector();
|
|
159
203
|
}
|
|
160
|
-
/**
|
|
204
|
+
/** Session aliases and event-pass guidance in place of provider login/logout. */
|
|
161
205
|
async function slashAliases() {
|
|
162
206
|
const { InteractiveMode } = await piModule("./modes/interactive/interactive-mode.js");
|
|
163
207
|
const proto = InteractiveMode.prototype;
|
|
@@ -171,7 +215,13 @@ async function slashAliases() {
|
|
|
171
215
|
if (!submit)
|
|
172
216
|
return;
|
|
173
217
|
const aliases = { "/resume": "/sessions", "/exit": "/quit" };
|
|
174
|
-
this.defaultEditor.onSubmit = (text) =>
|
|
218
|
+
this.defaultEditor.onSubmit = async (text) => {
|
|
219
|
+
if (/^\/(login|logout)(\s|$)/.test(text.trim())) {
|
|
220
|
+
this.showError("Klui connects with your event pass automatically. Use /klui retry to reconnect.");
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
await submit(aliases[text.trim()] ?? text);
|
|
224
|
+
};
|
|
175
225
|
};
|
|
176
226
|
}
|
|
177
227
|
/**
|