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,31 @@
1
+ // Shared, observable state for the Klui UI pieces (header, footer, working widget, commands).
2
+ const listeners = new Set();
3
+ export let state;
4
+ export function initState(initial) {
5
+ state = initial;
6
+ }
7
+ export function update(patch) {
8
+ Object.assign(state, patch);
9
+ for (const listener of listeners)
10
+ listener();
11
+ }
12
+ export function subscribe(listener) {
13
+ listeners.add(listener);
14
+ return () => listeners.delete(listener);
15
+ }
16
+ export function modelLabel() {
17
+ const model = state.model;
18
+ if (!model)
19
+ return "no model";
20
+ return state.config.models.find((m) => m.id === model.id)?.name ?? model.name ?? model.id;
21
+ }
22
+ /** "$1.00 left today", or just "$1.00" where space is short. */
23
+ export function creditsLabel(short = false) {
24
+ const credits = state.credits;
25
+ if (credits?.remainingUsd == null)
26
+ return undefined;
27
+ const left = `$${credits.remainingUsd.toFixed(2)}`;
28
+ if (short)
29
+ return left;
30
+ return credits.period === "daily" ? `${left} left today` : `${left} left`;
31
+ }
@@ -0,0 +1,124 @@
1
+ // A task list the model keeps for multi-step work, shown above the editor so you can see what
2
+ // it's doing, what's done and what's next. Each `todo` call sends the whole list, and each list
3
+ // is saved in the session, so it comes back after /reload, /resume and compaction. A finished
4
+ // list stays up until the next message, then gets out of the way.
5
+ import { StringEnum } from "@earendil-works/pi-ai";
6
+ import { truncateToWidth } from "@earendil-works/pi-tui";
7
+ import { Type } from "typebox";
8
+ const ENTRY = "klui-todos";
9
+ const WIDGET = "klui-todos";
10
+ /** Task rows the panel shows before "+N more". */
11
+ const MAX_ROWS = 6;
12
+ export function registerTodos(pi) {
13
+ let todos = [];
14
+ let changedThisRun = false;
15
+ let ui;
16
+ const show = () => {
17
+ if (!ui)
18
+ return;
19
+ const visible = todos.length > 0 && (changedThisRun || todos.some((t) => t.status !== "completed"));
20
+ ui.setWidget(WIDGET, visible ? (_tui, theme) => ({ render: (width) => todoPanel(todos, theme, width), invalidate() { } }) : undefined);
21
+ };
22
+ const restore = (ctx) => {
23
+ todos = lastTodos(ctx.sessionManager.getBranch());
24
+ show();
25
+ };
26
+ pi.registerTool({
27
+ name: "todo",
28
+ label: "Todos",
29
+ description: "Write the task list for multi-step work. Each call replaces the whole list; send an empty list to clear it.",
30
+ promptSnippet: "Track multi-step work in a task list the user can see",
31
+ promptGuidelines: [
32
+ "Use `todo` for work with three or more steps, or when the user gives you several things to do. Skip it for quick, single-step requests.",
33
+ "Send the full list on every `todo` call. Keep exactly one task in_progress: mark it completed as soon as it's done and set the next one in_progress in the same call.",
34
+ "Don't mark a task completed while its tests fail or the work is partial; add a task for the blocker instead.",
35
+ "Write each task's content as a short command (\"Add tests\") and its activeForm as what shows while it runs (\"Adding tests\").",
36
+ ],
37
+ parameters: Type.Object({
38
+ todos: Type.Array(Type.Object({
39
+ content: Type.String({ description: "The task, as a short command" }),
40
+ status: StringEnum(["pending", "in_progress", "completed"]),
41
+ activeForm: Type.Optional(Type.String({ description: "Shown while the task is in progress, e.g. \"Adding tests\"" })),
42
+ })),
43
+ }),
44
+ async execute(_id, params) {
45
+ todos = params.todos.map((t) => ({ ...t, content: t.content.trim() })).filter((t) => t.content);
46
+ changedThisRun = true;
47
+ // Saved as its own entry too: a call made from a codemode script never lands in the
48
+ // session as a tool result.
49
+ pi.appendEntry(ENTRY, { todos });
50
+ show();
51
+ return { content: [{ type: "text", text: summary(todos) }], details: { todos } };
52
+ },
53
+ });
54
+ pi.on("session_start", async (_event, ctx) => {
55
+ ui = ctx.mode === "tui" ? ctx.ui : undefined;
56
+ changedThisRun = false;
57
+ restore(ctx);
58
+ });
59
+ pi.on("session_compact", async (_event, ctx) => restore(ctx));
60
+ pi.on("session_tree", async (_event, ctx) => restore(ctx));
61
+ // On each new message, not each agent loop: a continuation (say, after a check) is the same run.
62
+ pi.on("before_agent_start", async () => {
63
+ changedThisRun = false;
64
+ show();
65
+ });
66
+ // Saved entries never reach the model. When the latest `todo` result it can see isn't the
67
+ // current list (compaction dropped it, or a script made the change), it hears what's still open.
68
+ pi.on("context", async (event) => {
69
+ if (!todos.some((t) => t.status !== "completed"))
70
+ return;
71
+ const seen = event.messages.findLast((m) => m.role === "toolResult" && m.toolName === "todo");
72
+ if (seen && JSON.stringify(seen.details?.todos) === JSON.stringify(todos))
73
+ return;
74
+ const list = todos.map((t) => `- [${t.status}] ${t.content}`).join("\n");
75
+ const note = { role: "custom", customType: ENTRY, content: `Your task list so far (update it with \`todo\`):\n${list}`, display: false, timestamp: Date.now() };
76
+ return { messages: [...event.messages, note] };
77
+ });
78
+ }
79
+ /** The list from the latest `todo` call on this branch. */
80
+ export function lastTodos(branch) {
81
+ let todos = [];
82
+ for (const entry of branch) {
83
+ const e = entry;
84
+ if (e.type === "custom" && e.customType === ENTRY && Array.isArray(e.data?.todos))
85
+ todos = e.data.todos;
86
+ }
87
+ return todos;
88
+ }
89
+ /** "2/5 done · Adding tests", for the model and the transcript. */
90
+ export function summary(todos) {
91
+ if (todos.length === 0)
92
+ return "Cleared the task list.";
93
+ const done = todos.filter((t) => t.status === "completed").length;
94
+ const current = todos.find((t) => t.status === "in_progress");
95
+ return `${done}/${todos.length} done${current ? ` · ${current.activeForm || current.content}` : ""}`;
96
+ }
97
+ /**
98
+ * The panel: a heading, then the tasks. When they don't fit, finished ones go first (oldest
99
+ * first), then pending ones from the end, so what's in progress and next always shows.
100
+ */
101
+ export function todoPanel(todos, theme, width) {
102
+ const done = todos.filter((t) => t.status === "completed").length;
103
+ const keep = new Set(todos.keys());
104
+ const drop = [...todos.keys()].filter((i) => todos[i].status === "completed");
105
+ for (let i = todos.length - 1; i >= 0; i--)
106
+ if (todos[i].status === "pending")
107
+ drop.push(i);
108
+ while (keep.size > MAX_ROWS && drop.length)
109
+ keep.delete(drop.shift());
110
+ const rows = todos.flatMap((t, i) => {
111
+ if (!keep.has(i))
112
+ return [];
113
+ if (t.status === "completed")
114
+ return [` ${theme.fg("success", "✓")} ${theme.fg("dim", theme.strikethrough(t.content))}`];
115
+ if (t.status === "in_progress")
116
+ return [` ${theme.fg("accent", "◼")} ${theme.bold(t.activeForm || t.content)}`];
117
+ return [` ${theme.fg("dim", "◻")} ${t.content}`];
118
+ });
119
+ const hidden = todos.length - keep.size;
120
+ if (hidden)
121
+ rows.push(theme.fg("dim", ` +${hidden} more`));
122
+ const heading = `${theme.fg("accent", "Todos")} ${theme.fg("dim", `${done}/${todos.length}`)}`;
123
+ return [heading, ...rows, ""].map((line) => truncateToWidth(line, width));
124
+ }
@@ -0,0 +1,251 @@
1
+ // Tool calls drawn the way Claude Code draws them: "⏺ Update(src/app.ts)" with the outcome under
2
+ // it, "⎿ Updated src/app.ts with 4 additions and 1 removal", and edits shown as a short diff. Click
3
+ // a row, or press the expand key, to see the call and its output drawn the way Pi normally draws them.
4
+ import { keyText, renderDiff } from "@earendil-works/pi-coding-agent";
5
+ import { Box, Container, Text, truncateToWidth } from "@earendil-works/pi-tui";
6
+ import { isAbsolute, relative } from "node:path";
7
+ import { DECLINED } from "./permissions.js";
8
+ /** How many diff or output lines a row shows before "… +N lines". */
9
+ const PREVIEW_DIFF = 12;
10
+ const PREVIEW_OUTPUT = 3;
11
+ export function registerCompactTools(pi) {
12
+ pi.registerToolRenderer((toolName, next) => {
13
+ const base = next();
14
+ if (!base)
15
+ return undefined;
16
+ return {
17
+ renderShell: "self",
18
+ renderCall: (args, theme, context) => context.expanded ? expandedCall(toolName, base, args, theme, context) : compactCall(toolName, args, theme, context),
19
+ renderResult: (result, options, theme, context) => context.expanded ? expandedResult(base, result, options, theme, context) : compactResult(toolName, result, theme, context),
20
+ };
21
+ });
22
+ }
23
+ // ── Compact ───────────────────────────────────────────────────────────────────────────────────
24
+ /** Lines cut to the terminal width instead of wrapping. */
25
+ class Lines {
26
+ lines = [];
27
+ pad = 0;
28
+ set(lines, pad) {
29
+ this.lines = lines;
30
+ this.pad = pad;
31
+ }
32
+ render(width) {
33
+ return this.lines.map((line) => truncateToWidth(" ".repeat(this.pad) + line, width));
34
+ }
35
+ invalidate() { }
36
+ }
37
+ const NOTHING = new Container();
38
+ function compactCall(toolName, args, theme, context) {
39
+ const state = context.state;
40
+ state.kluiHead ??= new Lines();
41
+ // The dot stays dim until the result colors it.
42
+ if (!state.kluiBody)
43
+ state.kluiHead.set([`${theme.fg("dim", "⏺")} ${title(toolName, args, theme, context.cwd)}`], context.outputPad);
44
+ return state.kluiHead;
45
+ }
46
+ function compactResult(toolName, result, theme, context) {
47
+ const state = context.state;
48
+ state.kluiBody ??= new Lines();
49
+ const head = title(toolName, context.args, theme, context.cwd);
50
+ if (context.isPartial) {
51
+ // Long-running tools (subagents) say what they're up to under the call.
52
+ const d = result.details;
53
+ state.kluiHead?.set([`${theme.fg("dim", "⏺")} ${head}`], context.outputPad);
54
+ state.kluiBody.set(d?.progress ? under(theme, [theme.fg("dim", `${d.progress}${d.tools ? ` · ${plural(d.tools, "tool")}` : ""}`)]) : [], context.outputPad);
55
+ return state.kluiBody;
56
+ }
57
+ const dot = context.isError ? theme.fg("error", "⏺") : theme.fg("success", "⏺");
58
+ state.kluiHead?.set([`${dot} ${head}`], context.outputPad);
59
+ const lines = context.isError ? errorLines(result, theme) : outcome(toolName, context.args, result, theme, context.cwd);
60
+ const time = context.durationMs !== undefined && context.durationMs >= 1000 ? theme.fg("dim", ` · ${(context.durationMs / 1000).toFixed(1)}s`) : "";
61
+ if (lines[0] !== undefined)
62
+ lines[0] += time;
63
+ state.kluiBody.set(under(theme, lines), context.outputPad);
64
+ return state.kluiBody;
65
+ }
66
+ /** Hang lines under the call: the first after "⎿", the rest lined up with it. */
67
+ function under(theme, lines) {
68
+ return lines.map((line, i) => `${i === 0 ? ` ${theme.fg("dim", "⎿")} ` : " "}${line}`);
69
+ }
70
+ const NAMES = {
71
+ read: "Read",
72
+ edit: "Update",
73
+ write: "Write",
74
+ bash: "Bash",
75
+ ls: "List",
76
+ grep: "Search",
77
+ find: "Find",
78
+ subagent: "Agent",
79
+ codemode: "Script",
80
+ web_search: "Web Search",
81
+ web_fetch: "Fetch",
82
+ todo: "Todos",
83
+ };
84
+ function title(toolName, args, theme, cwd) {
85
+ const a = (args ?? {});
86
+ const name = theme.bold(NAMES[toolName] ?? toolName);
87
+ const arg = (text) => (text ? `${theme.fg("muted", "(")}${text}${theme.fg("muted", ")")}` : "");
88
+ const path = (value) => shortPath(typeof value === "string" ? value : ".", cwd);
89
+ switch (toolName) {
90
+ case "read":
91
+ case "edit":
92
+ case "write":
93
+ return name + arg(path(a.path ?? a.file_path));
94
+ case "ls":
95
+ return name + arg(path(a.path));
96
+ case "bash":
97
+ return name + arg(firstLine(String(a.command ?? "")));
98
+ case "subagent":
99
+ // Clipped, so a long task doesn't push the kind off screen.
100
+ return `${name}${arg(`${String(a.kind ?? "explore")}: ${clip(firstLine(String(a.task ?? "")), 56)}`)}`;
101
+ case "codemode":
102
+ case "todo":
103
+ // A script's first line, or a task list, says nothing useful here.
104
+ return name;
105
+ case "web_search":
106
+ return name + arg(clip(String(a.query ?? ""), 64));
107
+ case "web_fetch":
108
+ return name + arg(clip(String(a.url ?? "").replace(/^https?:\/\//, ""), 64));
109
+ case "grep":
110
+ case "find":
111
+ return name + arg(`${String(a.pattern ?? "")}${a.path ? theme.fg("muted", ` in ${shortPath(String(a.path), cwd)}`) : ""}`);
112
+ default: {
113
+ const first = Object.values(a).find((v) => typeof v === "string");
114
+ return name + arg(first ? clip(firstLine(first), 64) : "");
115
+ }
116
+ }
117
+ }
118
+ /** What the tool did, as lines under the call. */
119
+ function outcome(toolName, args, result, theme, cwd) {
120
+ const text = outputText(result).trimEnd();
121
+ const lineCount = text ? text.split("\n").length : 0;
122
+ const a = (args ?? {});
123
+ switch (toolName) {
124
+ case "edit": {
125
+ const diff = result.details?.diff ?? "";
126
+ const lines = diff.split("\n");
127
+ const added = lines.filter((l) => /^\+\s*\d/.test(l)).length;
128
+ const removed = lines.filter((l) => /^-\s*\d/.test(l)).length;
129
+ const file = theme.bold(shortPath(String(a.path ?? a.file_path ?? ""), cwd));
130
+ const counts = [added && plural(added, "addition"), removed && plural(removed, "removal")].filter(Boolean).join(" and ");
131
+ return [`Updated ${file}${counts ? ` with ${counts}` : ""}`, ...preview(renderDiff(diff).split("\n"), PREVIEW_DIFF, theme)];
132
+ }
133
+ case "write": {
134
+ const content = typeof a.content === "string" ? a.content : "";
135
+ const lines = content.replace(/\n$/, "").split("\n");
136
+ const width = String(lines.length).length;
137
+ const numbered = lines.map((l, i) => `${theme.fg("dim", String(i + 1).padStart(width))} ${l.replace(/\t/g, " ")}`);
138
+ return [`Wrote ${plural(lines.length, "line")} to ${theme.bold(shortPath(String(a.path ?? a.file_path ?? ""), cwd))}`, ...preview(numbered, PREVIEW_OUTPUT * 2, theme)];
139
+ }
140
+ case "read":
141
+ return [`Read ${theme.bold(String(lineCount))} ${lineCount === 1 ? "line" : "lines"}`];
142
+ case "bash":
143
+ case "codemode":
144
+ // Like Claude Code: the first few lines of output, so most results need no expanding.
145
+ return text ? preview(text.split("\n").map((l) => theme.fg("toolOutput", l)), PREVIEW_OUTPUT, theme) : [theme.fg("dim", "(no output)")];
146
+ case "grep":
147
+ case "find":
148
+ case "ls":
149
+ return /^No (matches|files) found/.test(text) || !text
150
+ ? [theme.fg("dim", "Nothing found")]
151
+ : [`Found ${theme.bold(String(lineCount))} ${lineCount === 1 ? "result" : "results"}`];
152
+ case "web_search": {
153
+ const d = result.details;
154
+ return d?.results === undefined ? [] : [`${plural(d.results, "result")} ${theme.fg("dim", `from ${d.provider === "exa" ? "Exa" : "DuckDuckGo"}`)}`];
155
+ }
156
+ case "web_fetch": {
157
+ const chars = result.details?.chars;
158
+ return chars === undefined ? [] : [`Received ${theme.bold(chars.toLocaleString("en-US"))} characters`];
159
+ }
160
+ case "todo":
161
+ return text ? [theme.fg("muted", text)] : [];
162
+ case "subagent": {
163
+ const d = result.details;
164
+ if (!d)
165
+ return [];
166
+ if (d.background)
167
+ return [theme.fg("dim", `Working in the background as #${d.background}`)];
168
+ return [`Done ${theme.fg("dim", `· ${[plural(d.tools ?? 0, "tool"), d.model].filter(Boolean).join(" · ")}`)}`];
169
+ }
170
+ default:
171
+ return lineCount ? [theme.fg("dim", plural(lineCount, "line"))] : [];
172
+ }
173
+ }
174
+ function errorLines(result, theme) {
175
+ const text = outputText(result).trim();
176
+ if (text.startsWith(DECLINED)) {
177
+ const note = /and said: ([\s\S]*)$/.exec(text)?.[1];
178
+ return [`${theme.fg("warning", "Declined")}${note ? theme.fg("muted", ` · ${firstLine(note)}`) : ""}`];
179
+ }
180
+ const lines = text.split("\n").filter((l) => l.trim());
181
+ if (lines.length === 0)
182
+ return [theme.fg("error", "Failed")];
183
+ return preview(lines.map((l) => theme.fg("error", l)), PREVIEW_OUTPUT, theme);
184
+ }
185
+ /** The first `max` lines, then how many more there are and how to see them. */
186
+ function preview(lines, max, theme) {
187
+ if (lines.length <= max)
188
+ return lines;
189
+ return [...lines.slice(0, max), theme.fg("dim", `… +${lines.length - max} lines (${keyText("app.tools.expand")} to expand)`)];
190
+ }
191
+ // ── Expanded: Pi's own drawing ────────────────────────────────────────────────────────────────
192
+ /**
193
+ * Pi draws most tools as one tinted box holding the call and then the result. Klui's shell is
194
+ * "self", so it rebuilds that box: the call renderer refills it, and the result renderer, which
195
+ * runs right after, adds the output to it.
196
+ */
197
+ function expandedCall(toolName, base, args, theme, context) {
198
+ const state = context.state;
199
+ const call = base.renderCall
200
+ ? base.renderCall(args, theme, { ...context, lastComponent: state.kluiCall })
201
+ : new Text(`${theme.bold(theme.fg("toolTitle", toolName))}\n${theme.fg("muted", JSON.stringify(args, null, 2) ?? "")}`, 0, 0);
202
+ state.kluiCall = call;
203
+ if (base.renderShell === "self")
204
+ return call;
205
+ const bg = context.isPartial ? "toolPendingBg" : context.isError ? "toolErrorBg" : "toolSuccessBg";
206
+ state.kluiBox ??= new Box(context.outputPad, 1);
207
+ state.kluiBox.setPaddingX(context.outputPad);
208
+ state.kluiBox.setBgFn((text) => theme.bg(bg, text));
209
+ state.kluiBox.clear();
210
+ state.kluiBox.addChild(call);
211
+ return state.kluiBox;
212
+ }
213
+ function expandedResult(base, result, options, theme, context) {
214
+ const state = context.state;
215
+ const output = base.renderResult
216
+ ? base.renderResult(result, options, theme, { ...context, lastComponent: state.kluiResult })
217
+ : fallbackResult(result, theme);
218
+ state.kluiResult = output;
219
+ if (base.renderShell === "self")
220
+ return output ?? NOTHING;
221
+ if (output)
222
+ state.kluiBox?.addChild(output);
223
+ return NOTHING;
224
+ }
225
+ function fallbackResult(result, theme) {
226
+ const text = outputText(result).trimEnd();
227
+ return text ? new Text(theme.fg("toolOutput", text), 0, 0) : undefined;
228
+ }
229
+ // ── Helpers ───────────────────────────────────────────────────────────────────────────────────
230
+ function outputText(result) {
231
+ return result.content
232
+ .filter((c) => c.type === "text")
233
+ .map((c) => c.text)
234
+ .join("\n");
235
+ }
236
+ function shortPath(path, cwd) {
237
+ if (!isAbsolute(path))
238
+ return path;
239
+ const rel = relative(cwd, path);
240
+ return rel && !rel.startsWith("..") && !isAbsolute(rel) ? rel : path;
241
+ }
242
+ function firstLine(text) {
243
+ const [first = "", ...rest] = text.trim().split("\n");
244
+ return rest.length > 0 ? `${first} …` : first;
245
+ }
246
+ function clip(text, max) {
247
+ return text.length > max ? `${text.slice(0, max - 1)}…` : text;
248
+ }
249
+ function plural(n, word) {
250
+ return `${n} ${word}${n === 1 ? "" : "s"}`;
251
+ }
@@ -0,0 +1,61 @@
1
+ // Klui's voice, shared with the web app's thinking bar and home greeting (public/js/klui.js).
2
+ export const PHRASES = {
3
+ thinking: ["locking in", "connecting the dots", "big brain time", "cooking something up", "thinking it through"],
4
+ reading: ["taking notes", "highlighting the good bits", "skimming the code", "reading the room"],
5
+ searching: ["hunting it down", "digging around", "following the trail", "sifting results"],
6
+ running: ["running it", "pressing buttons", "watching the logs", "crossing fingers"],
7
+ writing: ["making edits", "writing the code", "finding the words", "polishing pixels"],
8
+ };
9
+ export const GREETINGS = [
10
+ "what are we building?",
11
+ "what's cooking?",
12
+ "say less, i'm ready",
13
+ "what we working on?",
14
+ "drop it here",
15
+ "let's cook",
16
+ "got an idea? let's ship it",
17
+ "hackathon mode: on",
18
+ ];
19
+ export const DONE_LINES = ["done!", "shipped it", "all yours", "ta-da", "nailed it", "that's a wrap"];
20
+ export function pick(items, avoid) {
21
+ if (items.length < 2)
22
+ return items[0];
23
+ let next;
24
+ do
25
+ next = items[Math.floor(Math.random() * items.length)];
26
+ while (next === avoid);
27
+ return next;
28
+ }
29
+ /** What Klui says it's doing while a tool runs. */
30
+ export function describeTool(toolName, args) {
31
+ const path = typeof args?.path === "string" ? shortPath(args.path) : undefined;
32
+ switch (toolName) {
33
+ case "read":
34
+ return { activity: "reading", detail: path ? `reading ${path}` : undefined };
35
+ case "edit":
36
+ return { activity: "writing", detail: path ? `editing ${path}` : undefined };
37
+ case "write":
38
+ return { activity: "writing", detail: path ? `writing ${path}` : undefined };
39
+ case "grep":
40
+ case "find":
41
+ case "ls":
42
+ return { activity: "searching", detail: typeof args?.pattern === "string" ? `looking for ${clip(args.pattern, 28)}` : undefined };
43
+ case "bash": {
44
+ const command = typeof args?.command === "string" ? args.command.split("\n")[0].trim() : "";
45
+ return { activity: "running", detail: command ? `$ ${clip(command, 40)}` : undefined };
46
+ }
47
+ case "todo":
48
+ return { activity: "thinking", detail: "updating the plan" };
49
+ case "subagent":
50
+ return { activity: "searching", detail: `a subagent is ${args?.kind === "general" ? "on it" : "exploring"}` };
51
+ default:
52
+ return { activity: "thinking", detail: `using ${toolName}` };
53
+ }
54
+ }
55
+ function shortPath(path) {
56
+ const parts = path.split("/").filter(Boolean);
57
+ return parts.length > 2 ? `…/${parts.slice(-2).join("/")}` : path;
58
+ }
59
+ function clip(text, max) {
60
+ return text.length > max ? `${text.slice(0, max - 1)}…` : text;
61
+ }
@@ -0,0 +1,119 @@
1
+ // Web search and page fetching. Both run on the attendee's own machine and use keyless services,
2
+ // so nothing goes through the event server and every attendee has their own limits. Search asks
3
+ // Exa's public MCP endpoint and falls back to DuckDuckGo's HTML page.
4
+ import { Type } from "typebox";
5
+ const TIMEOUT_MS = 20_000;
6
+ const MAX_PAGE_CHARS = 30_000;
7
+ /** When these tools can't get through, the model can still reach the web from the shell. */
8
+ const USE_CURL = "Fall back to curl in bash (for search: https://html.duckduckgo.com/html/?q=...).";
9
+ export function registerWeb(pi) {
10
+ pi.registerTool({
11
+ name: "web_search",
12
+ label: "Web search",
13
+ description: "Search the web. Returns titles, URLs and snippets. Use web_fetch to read a result in full.",
14
+ promptSnippet: "web_search: search the web for current or external information",
15
+ parameters: Type.Object({
16
+ query: Type.String({ description: "What to search for" }),
17
+ }),
18
+ executionMode: "parallel",
19
+ async execute(_toolCallId, params, signal) {
20
+ const results = await searchExa(params.query, signal)
21
+ .catch(() => searchDuckDuckGo(params.query, signal))
22
+ .catch(() => {
23
+ throw new Error(`Exa and DuckDuckGo are both unavailable right now. ${USE_CURL}`);
24
+ });
25
+ return { content: [{ type: "text", text: results.text }], details: { results: results.count, provider: results.provider } };
26
+ },
27
+ });
28
+ pi.registerTool({
29
+ name: "web_fetch",
30
+ label: "Web fetch",
31
+ description: `Fetch a URL and return its text (pages are reduced to plain text, cut at ${MAX_PAGE_CHARS} characters).`,
32
+ promptSnippet: "web_fetch: read a web page or other URL as text",
33
+ parameters: Type.Object({
34
+ url: Type.String({ description: "The http(s) URL to fetch" }),
35
+ }),
36
+ executionMode: "parallel",
37
+ async execute(_toolCallId, params, signal) {
38
+ if (!/^https?:\/\//i.test(params.url))
39
+ throw new Error("Only http(s) URLs can be fetched.");
40
+ const response = await fetch(params.url, { headers: { "user-agent": "Mozilla/5.0 (compatible; klui)" }, signal: timeout(signal) }).catch((error) => {
41
+ throw new Error(`Couldn't fetch ${params.url} (${error.message}). ${USE_CURL}`);
42
+ });
43
+ if (!response.ok)
44
+ throw new Error(`${params.url} answered ${response.status}. ${USE_CURL}`);
45
+ const body = await response.text();
46
+ const html = /html/i.test(response.headers.get("content-type") ?? "");
47
+ const text = (html ? htmlToText(body) : body).trim();
48
+ const cut = text.length > MAX_PAGE_CHARS ? `${text.slice(0, MAX_PAGE_CHARS)}\n\n[cut at ${MAX_PAGE_CHARS} characters]` : text;
49
+ return { content: [{ type: "text", text: cut || "(empty page)" }], details: { chars: text.length } };
50
+ },
51
+ });
52
+ }
53
+ async function searchExa(query, signal) {
54
+ const response = await fetch("https://mcp.exa.ai/mcp?tools=web_search_exa", {
55
+ method: "POST",
56
+ headers: { "content-type": "application/json", accept: "application/json, text/event-stream" },
57
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "web_search_exa", arguments: { query, numResults: 5 } } }),
58
+ signal: timeout(signal),
59
+ });
60
+ if (!response.ok)
61
+ throw new Error(`Exa answered ${response.status}`);
62
+ // The answer comes as JSON or as a server-sent event holding the JSON.
63
+ const body = await response.text();
64
+ const json = body.split("\n").find((l) => l.startsWith("data:"))?.slice(5) ?? body;
65
+ const result = JSON.parse(json).result;
66
+ const text = result?.content?.[0]?.text?.trim();
67
+ const count = (text?.match(/^URL: /gm) ?? []).length;
68
+ if (!text || result?.isError || count === 0)
69
+ throw new Error("Exa returned no results");
70
+ return { text, count, provider: "exa" };
71
+ }
72
+ async function searchDuckDuckGo(query, signal) {
73
+ const response = await fetch(`https://html.duckduckgo.com/html/?q=${encodeURIComponent(query)}`, {
74
+ headers: { "user-agent": "Mozilla/5.0 (compatible; klui)" },
75
+ signal: timeout(signal),
76
+ });
77
+ // 202 is DuckDuckGo's bot check.
78
+ if (response.status !== 200)
79
+ throw new Error(`DuckDuckGo answered ${response.status}`);
80
+ const html = await response.text();
81
+ const results = [];
82
+ for (const block of html.split('class="result__a"').slice(1, 6)) {
83
+ const link = /href="([^"]+)"[^>]*>([\s\S]*?)<\/a>/.exec(block);
84
+ if (!link)
85
+ continue;
86
+ const href = decode(link[1]);
87
+ const url = new URL(href, "https://duckduckgo.com").searchParams.get("uddg") ?? href;
88
+ const snippet = /class="result__snippet"[^>]*>([\s\S]*?)<\/a>/.exec(block)?.[1] ?? "";
89
+ results.push(`Title: ${htmlToText(link[2])}\nURL: ${url}\n${htmlToText(snippet)}`);
90
+ }
91
+ // No results at all usually means the page changed shape, not that the web knows nothing.
92
+ if (results.length === 0)
93
+ throw new Error("DuckDuckGo returned no results");
94
+ return { text: results.join("\n\n"), count: results.length, provider: "duckduckgo" };
95
+ }
96
+ /** Rough but dependable: drop scripts, styles and tags, keep line breaks at block ends. */
97
+ export function htmlToText(html) {
98
+ return decode(html
99
+ .replace(/<(script|style|noscript|svg|head)[\s\S]*?<\/\1>/gi, "")
100
+ .replace(/<\/(p|div|li|h[1-6]|tr|section|article|header|footer)>|<br\s*\/?>/gi, "\n")
101
+ .replace(/<[^>]+>/g, ""))
102
+ .replace(/[ \t]+/g, " ")
103
+ .replace(/\n\s*\n\s*/g, "\n\n")
104
+ .trim();
105
+ }
106
+ function decode(text) {
107
+ return text
108
+ .replace(/&#(\d+);/g, (_, n) => String.fromCodePoint(Number(n)))
109
+ .replace(/&#x([0-9a-f]+);/gi, (_, n) => String.fromCodePoint(parseInt(n, 16)))
110
+ .replace(/&nbsp;/g, " ")
111
+ .replace(/&quot;/g, '"')
112
+ .replace(/&#39;|&apos;/g, "'")
113
+ .replace(/&lt;/g, "<")
114
+ .replace(/&gt;/g, ">")
115
+ .replace(/&amp;/g, "&");
116
+ }
117
+ function timeout(signal) {
118
+ return signal ? AbortSignal.any([signal, AbortSignal.timeout(TIMEOUT_MS)]) : AbortSignal.timeout(TIMEOUT_MS);
119
+ }