klui-code 0.1.3 → 0.1.4
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 +21 -7
- package/dist/extension/agents.js +362 -57
- package/dist/extension/checks.js +1 -1
- package/dist/extension/commands.js +3 -3
- package/dist/extension/index.js +97 -15
- package/dist/extension/todos.js +2 -2
- package/dist/extension/tools.js +10 -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 +57 -12
- package/dist/mascot.js +15 -0
- package/dist/pi-patches.js +40 -5
- package/dist/usage.js +46 -20
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -13,9 +13,19 @@ That's it: no account, no API key, no wallet. The installer brings its own Node.
|
|
|
13
13
|
missing or older than 22.19, and puts everything in `~/.klui`. On first launch klui gets your
|
|
14
14
|
device its own event pass and picks the default model.
|
|
15
15
|
|
|
16
|
-
Already on Node 22.19+? `npm install -g klui-code` works too
|
|
17
|
-
|
|
18
|
-
|
|
16
|
+
Already on Node 22.19+? `npm install -g klui-code` works too.
|
|
17
|
+
|
|
18
|
+
On Windows, install [Node.js](https://nodejs.org) (the LTS one) and
|
|
19
|
+
[Git for Windows](https://git-scm.com/download/win) first (Klui runs commands through Git Bash),
|
|
20
|
+
then open a new terminal and run:
|
|
21
|
+
|
|
22
|
+
```
|
|
23
|
+
npm install -g klui-code
|
|
24
|
+
klui
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
"npm is not recognized" means Node.js isn't installed yet, or the terminal was open before it was:
|
|
28
|
+
install it, then open a new terminal.
|
|
19
29
|
|
|
20
30
|
## Using it
|
|
21
31
|
|
|
@@ -35,7 +45,7 @@ Klui warns when the selected model can only read text.
|
|
|
35
45
|
| `/klui retry` | reconnect after a wifi hiccup |
|
|
36
46
|
| `/sessions` or `/resume` | pick up an earlier chat |
|
|
37
47
|
| `/update` | install the latest klui (or `klui update` in your shell); restart to use it |
|
|
38
|
-
| `/usage` | tokens and
|
|
48
|
+
| `/usage` | tokens and model requests in the last 24 hours and overall, including follow-up agent turns, compaction and subagents |
|
|
39
49
|
| `shift+tab` | permission mode: **ask** (asks before edits and commands), **auto** (works freely in the project, asks before risky commands and changes outside it), **yolo** (never asks) |
|
|
40
50
|
| `alt+t` | cycle reasoning level (low, medium, high; picked after each model switch) |
|
|
41
51
|
| `ctrl+l` | model picker |
|
|
@@ -49,8 +59,11 @@ When Klui asks, answer yes, yes and don't ask again this session, no (which stop
|
|
|
49
59
|
with a note for Klui. Reads and searches never ask. Klui starts in auto mode each launch.
|
|
50
60
|
|
|
51
61
|
For a big job, ask Klui to use subagents: each is a fresh Klui with its own context, read-only
|
|
52
|
-
(`explore
|
|
53
|
-
background one reports back when it's done while Klui keeps working.
|
|
62
|
+
(`explore`, files and the web) or able to edit (`general`), on any event model. Several can run
|
|
63
|
+
at once, and a background one reports back when it's done while Klui keeps working. While one
|
|
64
|
+
runs, its row shows its last steps and what it's doing right now (waiting on the model, thinking,
|
|
65
|
+
drafting `styles.css`, running a command, retrying), with a token counter and the time. Expand
|
|
66
|
+
the row to see every step.
|
|
54
67
|
|
|
55
68
|
For multi-step work Klui keeps a todo list above the editor, so you can see what it's on, what's
|
|
56
69
|
done and what's next. The list is saved with the chat, so it survives `/resume` and compaction.
|
|
@@ -84,7 +97,8 @@ klui ──(1) device id──▶ Klui Pass ──▶ key from a pre-made pool
|
|
|
84
97
|
`/sessions`, and three themes (`themes/`).
|
|
85
98
|
- **Web access** (`src/extension/web.ts`): `web_search` and `web_fetch`. They run on the
|
|
86
99
|
attendee's own machine with keyless services (Exa, then DuckDuckGo), never through Klui Pass, so
|
|
87
|
-
every attendee has their own limits.
|
|
100
|
+
every attendee has their own limits. Fetched pages return their full extracted text; downloads
|
|
101
|
+
over 10 MiB are stopped with an error rather than truncated.
|
|
88
102
|
|
|
89
103
|
Running the event? See [server/README.md](server/README.md).
|
|
90
104
|
|
package/dist/extension/agents.js
CHANGED
|
@@ -1,63 +1,86 @@
|
|
|
1
1
|
// Subagents, like OpenCode's task tool and Codex's spawn_agent: the model hands a self-contained job
|
|
2
2
|
// to a fresh Klui with its own context window. Each one is a child `klui --mode json` process, so
|
|
3
3
|
// several can run at once. Each runs on the same model and reasoning level as the main agent
|
|
4
|
-
// unless the task asks for a different model. "explore" agents only read;
|
|
4
|
+
// unless the task asks for a different model. "explore" agents only read (files and the web);
|
|
5
5
|
// "general" agents can also edit files and run commands. A background agent returns right away and
|
|
6
6
|
// reports back as a message when it's done, so the main agent can keep working meanwhile.
|
|
7
|
+
//
|
|
8
|
+
// While one runs, its row says what it's doing from the child's own stream, like Codex's status
|
|
9
|
+
// line and OpenCode's "Preparing write…": waiting on the model, thinking, preparing a write to
|
|
10
|
+
// styles.css, running a command, retrying. Under that sit its last finished steps, a token
|
|
11
|
+
// counter that moves as output streams in, and the time.
|
|
7
12
|
import { spawn } from "node:child_process";
|
|
8
13
|
import { join } from "node:path";
|
|
9
14
|
import { StringEnum } from "@earendil-works/pi-ai";
|
|
10
|
-
import { getMarkdownTheme } from "@earendil-works/pi-coding-agent";
|
|
15
|
+
import { getMarkdownTheme, keyText } from "@earendil-works/pi-coding-agent";
|
|
11
16
|
import { Container, Markdown, Text } from "@earendil-works/pi-tui";
|
|
12
17
|
import { Type } from "typebox";
|
|
13
18
|
import { PACKAGE_DIR, PROVIDER } from "../paths.js";
|
|
14
19
|
import { PERMISSIONS_ENV } from "./permissions.js";
|
|
15
20
|
import { state } from "./state.js";
|
|
21
|
+
import { preparingLabel, shortPath } from "./voice.js";
|
|
16
22
|
/** Set in a subagent's environment: subagents don't start subagents of their own. */
|
|
17
23
|
export const SUBAGENT_ENV = "KLUI_SUBAGENT";
|
|
18
24
|
export const AGENT_MESSAGE = "klui-agent";
|
|
19
25
|
const WIDGET = "klui-agents";
|
|
26
|
+
/** Rows refresh this often while an agent runs, so the clock and counter keep moving between events. */
|
|
27
|
+
const TICK_MS = 500;
|
|
28
|
+
/** Finished steps kept for the expanded view: plenty for any real run, and a bound on a runaway one. */
|
|
29
|
+
const MAX_STEPS = 500;
|
|
30
|
+
const REPORT = "The other agent can't see your work, only that report. If the task needs something your tools can't do, say so at the top of the report instead of guessing.";
|
|
20
31
|
const KINDS = {
|
|
21
32
|
explore: {
|
|
22
|
-
tools: "read,grep,find,ls",
|
|
23
|
-
prompt:
|
|
33
|
+
tools: "read,grep,find,ls,web_search,web_fetch",
|
|
34
|
+
prompt: `You are a Klui subagent researching for another agent. You can read files and search and fetch the web, but never change anything. Search broadly, read what matters, and finish with a compact report: the answer, the exact file paths and line numbers or the URLs you actually read, and short excerpts where they help. ${REPORT}`,
|
|
24
35
|
},
|
|
25
36
|
general: {
|
|
26
|
-
tools: "read,bash,edit,write,grep,find,ls",
|
|
27
|
-
prompt:
|
|
37
|
+
tools: "read,bash,edit,write,grep,find,ls,web_search,web_fetch",
|
|
38
|
+
prompt: `You are a Klui subagent doing one task for another agent. Do the task completely, check your work, and finish with a short report: what you changed (file paths), how you verified it, and anything left undone. ${REPORT}`,
|
|
28
39
|
},
|
|
29
40
|
};
|
|
30
41
|
export function registerAgents(pi) {
|
|
31
42
|
const running = new Map();
|
|
32
43
|
let nextId = 1;
|
|
33
44
|
let ui;
|
|
45
|
+
let widgetTimer;
|
|
46
|
+
/** One line per background agent, with what it's doing; the clock ticks while any runs. */
|
|
34
47
|
const showRunning = () => {
|
|
35
48
|
if (!ui)
|
|
36
49
|
return;
|
|
37
|
-
const list = [...running.values()];
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
50
|
+
const list = [...running.values()].map((r) => r.details);
|
|
51
|
+
if (list.length === 0) {
|
|
52
|
+
clearInterval(widgetTimer);
|
|
53
|
+
widgetTimer = undefined;
|
|
54
|
+
ui.setWidget(WIDGET, undefined);
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
widgetTimer ??= setInterval(showRunning, 1000);
|
|
58
|
+
widgetTimer.unref?.();
|
|
59
|
+
const now = Date.now();
|
|
60
|
+
const shown = list.slice(0, 3).map((d) => ` ◌ ${d.kind} #${d.background} · ${statusLine(d, now)}`);
|
|
61
|
+
if (list.length > 3)
|
|
62
|
+
shown.push(` ◌ +${list.length - 3} more background agents`);
|
|
63
|
+
ui.setWidget(WIDGET, shown);
|
|
41
64
|
};
|
|
42
65
|
pi.registerTool({
|
|
43
66
|
name: "subagent",
|
|
44
67
|
label: "Subagent",
|
|
45
68
|
description: [
|
|
46
69
|
"Hand a self-contained task to a fresh subagent with its own context window, and get its final report back.",
|
|
47
|
-
'kind "explore" (default) can
|
|
70
|
+
'kind "explore" (default) can read and search files and search and fetch the web (web_search, web_fetch), but not change anything: use it for broad codebase questions and web research so your own context stays small.',
|
|
48
71
|
'kind "general" can also edit files and run commands: use it for an independent piece of work.',
|
|
49
72
|
"The subagent can't see this conversation, so put everything it needs in the task.",
|
|
50
73
|
"Call it several times in one turn to run independent tasks in parallel.",
|
|
51
74
|
"Set background to true to keep working while it runs; its report arrives later as a message.",
|
|
52
75
|
`It runs on your model and reasoning level. Set model only when the user asks for a different one: ${state.config.models.map(modelHint).join("; ")}.`,
|
|
53
76
|
].join(" "),
|
|
54
|
-
promptSnippet: "subagent: delegate a self-contained task to a fresh agent (explore = read-only, general = can edit); several can run in parallel",
|
|
77
|
+
promptSnippet: "subagent: delegate a self-contained task to a fresh agent (explore = read-only files and web, general = can edit); several can run in parallel",
|
|
55
78
|
promptGuidelines: [
|
|
56
|
-
"Use subagent for wide searches or independent sub-tasks, not for a single quick lookup you can do yourself.",
|
|
79
|
+
"Use subagent for wide searches, web research or independent sub-tasks, not for a single quick lookup you can do yourself.",
|
|
57
80
|
],
|
|
58
81
|
parameters: Type.Object({
|
|
59
82
|
task: Type.String({ description: "Everything the subagent needs: the goal, relevant paths and what to report back" }),
|
|
60
|
-
kind: Type.Optional(StringEnum(["explore", "general"], { description: "explore (read-only, default) or general (can edit and run commands)" })),
|
|
83
|
+
kind: Type.Optional(StringEnum(["explore", "general"], { description: "explore (read-only files and web, default) or general (can edit and run commands)" })),
|
|
61
84
|
model: Type.Optional(Type.String({ description: "Only when the user asks for a different model: its id or name. Leave it out to use your own model" })),
|
|
62
85
|
background: Type.Optional(Type.Boolean({ description: "Return right away and deliver the report as a message later" })),
|
|
63
86
|
}),
|
|
@@ -68,8 +91,8 @@ export function registerAgents(pi) {
|
|
|
68
91
|
const own = ctx.model?.provider === PROVIDER ? state.config.models.find((m) => m.id === ctx.model.id) : undefined;
|
|
69
92
|
const model = params.model ? resolveModel(params.model) : (own ?? resolveModel(state.config.defaultModel));
|
|
70
93
|
const run = { model: `${PROVIDER}/${model.id}`, thinking: pi.getThinkingLevel() };
|
|
71
|
-
const details = { kind, task: params.task, model: model.name, tools: 0, elapsedMs: 0 };
|
|
72
94
|
const startedAt = Date.now();
|
|
95
|
+
const details = { kind, task: params.task, model: model.name, tools: 0, tokens: 0, steps: [], progress: "starting up", startedAt, elapsedMs: 0 };
|
|
73
96
|
if (params.background) {
|
|
74
97
|
ui = ctx.hasUI ? ctx.ui : undefined;
|
|
75
98
|
const id = nextId++;
|
|
@@ -77,12 +100,18 @@ export function registerAgents(pi) {
|
|
|
77
100
|
details.background = id;
|
|
78
101
|
running.set(id, { controller, details });
|
|
79
102
|
showRunning();
|
|
80
|
-
|
|
103
|
+
let shownAt = 0;
|
|
104
|
+
void runAgent(ctx.cwd, kind, run, params.task, controller.signal, details, () => {
|
|
105
|
+
if (Date.now() - shownAt < 250)
|
|
106
|
+
return;
|
|
107
|
+
shownAt = Date.now();
|
|
108
|
+
showRunning();
|
|
109
|
+
}).then((outcome) => {
|
|
81
110
|
running.delete(id);
|
|
82
111
|
showRunning();
|
|
83
112
|
if (controller.signal.aborted)
|
|
84
113
|
return;
|
|
85
|
-
const done = { ...details,
|
|
114
|
+
const done = { ...details, progress: undefined, error: outcome.error, elapsedMs: Date.now() - startedAt };
|
|
86
115
|
pi.sendMessage({
|
|
87
116
|
customType: AGENT_MESSAGE,
|
|
88
117
|
content: `Background agent #${id} (${kind}) ${outcome.error ? `failed: ${outcome.error}` : "finished"}.\n\n${outcome.output}`,
|
|
@@ -92,46 +121,73 @@ export function registerAgents(pi) {
|
|
|
92
121
|
});
|
|
93
122
|
return {
|
|
94
123
|
content: [{ type: "text", text: `Started background agent #${id}. Its report will arrive as a message when it finishes; carry on meanwhile.` }],
|
|
95
|
-
details,
|
|
124
|
+
details: { ...details, steps: [] },
|
|
96
125
|
};
|
|
97
126
|
}
|
|
127
|
+
// Events come in bursts; between them a steady tick keeps the clock and counter moving.
|
|
98
128
|
let lastUpdate = 0;
|
|
99
|
-
const
|
|
100
|
-
Object.assign(details, p, { elapsedMs: Date.now() - startedAt });
|
|
101
|
-
if (Date.now() - lastUpdate < 200)
|
|
102
|
-
return;
|
|
129
|
+
const emit = () => {
|
|
103
130
|
lastUpdate = Date.now();
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
131
|
+
details.elapsedMs = lastUpdate - startedAt;
|
|
132
|
+
onUpdate?.({ content: [{ type: "text", text: "" }], details: { ...details, steps: [...details.steps] } });
|
|
133
|
+
};
|
|
134
|
+
const tick = setInterval(emit, TICK_MS);
|
|
135
|
+
tick.unref?.();
|
|
136
|
+
emit();
|
|
137
|
+
const outcome = await runAgent(ctx.cwd, kind, run, params.task, signal, details, () => {
|
|
138
|
+
if (Date.now() - lastUpdate >= 150)
|
|
139
|
+
emit();
|
|
140
|
+
}).finally(() => clearInterval(tick));
|
|
141
|
+
// A stopped or failed agent still keeps its steps for the expanded row, and the parent gets
|
|
142
|
+
// whatever it said before it failed, marked as unfinished rather than passed off as its report.
|
|
143
|
+
const failed = signal?.aborted ? "Subagent stopped" : outcome.error;
|
|
144
|
+
if (failed) {
|
|
145
|
+
const said = outcome.output.trim();
|
|
146
|
+
return {
|
|
147
|
+
content: [{ type: "text", text: said ? `${failed}\n\nIt said this before it stopped, so it may be unfinished:\n\n${said}` : failed }],
|
|
148
|
+
details: { ...details, progress: undefined, error: failed, elapsedMs: Date.now() - startedAt },
|
|
149
|
+
isError: true,
|
|
150
|
+
};
|
|
151
|
+
}
|
|
110
152
|
return {
|
|
111
153
|
content: [{ type: "text", text: outcome.output || "(the subagent finished without a report)" }],
|
|
112
|
-
details: { ...details,
|
|
154
|
+
details: { ...details, progress: undefined, elapsedMs: Date.now() - startedAt },
|
|
113
155
|
};
|
|
114
156
|
},
|
|
115
157
|
renderCall(args, theme) {
|
|
116
158
|
const kind = args.kind ?? "explore";
|
|
117
159
|
return new Text(`${theme.bold(theme.fg("toolTitle", "agent"))} ${theme.fg("accent", kind)}\n${theme.fg("muted", args.task ?? "")}`, 0, 0);
|
|
118
160
|
},
|
|
119
|
-
renderResult(result,
|
|
161
|
+
renderResult(result, options, theme) {
|
|
162
|
+
// Expanded: every step, then what it's doing now while it runs, or its report once it's done.
|
|
163
|
+
const d = result.details;
|
|
164
|
+
const steps = (d?.steps ?? []).map((step) => stepLine(step, theme));
|
|
165
|
+
if (options.isPartial && d?.steps) {
|
|
166
|
+
return new Text([...steps, `${theme.fg("accent", spark(Date.now()))} ${theme.fg("accent", statusLine(d, Date.now()))}`].join("\n"), 0, 1);
|
|
167
|
+
}
|
|
120
168
|
const text = result.content.find((c) => c.type === "text")?.text ?? "";
|
|
121
|
-
|
|
169
|
+
const report = text.trim() ? new Markdown(text, 0, 1, getMarkdownTheme()) : new Text(theme.fg("dim", "no report"), 0, 0);
|
|
170
|
+
if (steps.length === 0)
|
|
171
|
+
return report;
|
|
172
|
+
const row = new Container();
|
|
173
|
+
row.addChild(new Text(steps.join("\n"), 0, 1));
|
|
174
|
+
row.addChild(report);
|
|
175
|
+
return row;
|
|
122
176
|
},
|
|
123
177
|
});
|
|
124
178
|
pi.registerMessageRenderer(AGENT_MESSAGE, (message, options, theme) => {
|
|
125
179
|
const d = message.details;
|
|
126
180
|
if (!d)
|
|
127
181
|
return undefined;
|
|
128
|
-
const dot = d.error ? theme.fg("error", "
|
|
129
|
-
const meta = [d.error ??
|
|
182
|
+
const dot = d.error ? theme.fg("error", "●") : theme.fg("success", "●");
|
|
183
|
+
const meta = [d.error ?? plural(d.tools, "tool"), d.tokens > 0 ? `↓ ${formatTokens(d.tokens)} tokens` : undefined, formatElapsed(d.elapsedMs)].filter(Boolean).join(" · ");
|
|
130
184
|
const pad = " ".repeat(options.outputPad);
|
|
131
185
|
const head = `${pad}${dot} ${theme.bold("Agent")}${theme.fg("muted", "(")}${d.kind} #${d.background}: ${clip(firstLine(d.task), 48)}${theme.fg("muted", ")")}`;
|
|
132
186
|
const row = new Container();
|
|
133
187
|
row.addChild(new Text(`${head}\n${pad} ${theme.fg("dim", "⎿")} Reported back ${theme.fg("dim", `· ${meta}`)}`, 0, 0));
|
|
134
188
|
if (options.expanded) {
|
|
189
|
+
if (d.steps?.length)
|
|
190
|
+
row.addChild(new Text(d.steps.map((step) => stepLine(step, theme)).join("\n"), options.outputPad + 2, 1));
|
|
135
191
|
const report = typeof message.content === "string" ? message.content : "";
|
|
136
192
|
row.addChild(new Markdown(report.replace(/^[^\n]*\n\n/, ""), options.outputPad + 2, 1, getMarkdownTheme()));
|
|
137
193
|
}
|
|
@@ -141,8 +197,54 @@ export function registerAgents(pi) {
|
|
|
141
197
|
for (const { controller } of running.values())
|
|
142
198
|
controller.abort();
|
|
143
199
|
running.clear();
|
|
200
|
+
clearInterval(widgetTimer);
|
|
201
|
+
widgetTimer = undefined;
|
|
144
202
|
});
|
|
145
203
|
}
|
|
204
|
+
/**
|
|
205
|
+
* A running agent's row under its call: its last few finished steps, then what it's doing now with
|
|
206
|
+
* the tool count, tokens and time. Older steps are a key press away.
|
|
207
|
+
*/
|
|
208
|
+
export function agentLines(d, theme, now = Date.now(), recent = 2) {
|
|
209
|
+
const fg = theme.fg;
|
|
210
|
+
const steps = d.steps ?? [];
|
|
211
|
+
const lines = [];
|
|
212
|
+
const key = keyText("app.tools.expand");
|
|
213
|
+
if (steps.length > recent)
|
|
214
|
+
lines.push(fg("dim", `… ${plural(steps.length - recent, "earlier step")}${key ? ` (${key} to see them)` : ""}`));
|
|
215
|
+
for (const step of steps.slice(-recent))
|
|
216
|
+
lines.push(stepLine(step, theme));
|
|
217
|
+
lines.push(`${fg("accent", spark(now))} ${fg("accent", agentProgress(d, now))}${fg("dim", ` · ${statusMeta(d, now)}`)}`);
|
|
218
|
+
return lines;
|
|
219
|
+
}
|
|
220
|
+
/** "reading src/app.ts · 3 tools · ↓ 1.2k tokens · 42s". */
|
|
221
|
+
export function statusLine(d, now = Date.now()) {
|
|
222
|
+
return `${agentProgress(d, now)} · ${statusMeta(d, now)}`;
|
|
223
|
+
}
|
|
224
|
+
/** What it's doing, with a retry counting down to its next try. */
|
|
225
|
+
export function agentProgress(d, now = Date.now()) {
|
|
226
|
+
if (d.retry)
|
|
227
|
+
return `retrying ${d.retry.at > now ? `in ${Math.ceil((d.retry.at - now) / 1000)}s ` : "now "}(${d.retry.label})`;
|
|
228
|
+
return d.progress ?? "working";
|
|
229
|
+
}
|
|
230
|
+
function statusMeta(d, now) {
|
|
231
|
+
return [
|
|
232
|
+
plural(d.tools, "tool"),
|
|
233
|
+
d.tokens > 0 ? `↓ ${formatTokens(d.tokens)} tokens` : undefined,
|
|
234
|
+
formatElapsed(now - d.startedAt),
|
|
235
|
+
]
|
|
236
|
+
.filter(Boolean)
|
|
237
|
+
.join(" · ");
|
|
238
|
+
}
|
|
239
|
+
function stepLine(step, theme) {
|
|
240
|
+
const fg = theme.fg;
|
|
241
|
+
return `${step.ok ? fg("success", "✓") : fg("error", "✗")} ${fg("muted", step.text)}`;
|
|
242
|
+
}
|
|
243
|
+
const SPARKS = ["✶", "✷", "✸", "✹", "✺", "✹", "✸", "✷"];
|
|
244
|
+
/** A little star that turns as the row refreshes, so a quiet agent still looks alive. */
|
|
245
|
+
function spark(now) {
|
|
246
|
+
return process.env.KLUI_REDUCED_MOTION === "1" ? "✶" : SPARKS[Math.floor(now / TICK_MS) % SPARKS.length];
|
|
247
|
+
}
|
|
146
248
|
function modelHint(m) {
|
|
147
249
|
return `${m.id} (${m.name}${m.tagline ? `, ${m.tagline}` : ""})`;
|
|
148
250
|
}
|
|
@@ -158,8 +260,157 @@ function resolveModel(requested) {
|
|
|
158
260
|
throw new Error(`Unknown model "${requested}". Pick one of: ${models.map((m) => m.id).join(", ")}`);
|
|
159
261
|
return found;
|
|
160
262
|
}
|
|
161
|
-
/**
|
|
162
|
-
|
|
263
|
+
/** Events that mean a retry's wait is over. */
|
|
264
|
+
const RESUMED = new Set(["auto_retry_end", "turn_start", "message_update", "tool_execution_start", "agent_end"]);
|
|
265
|
+
/** Output tokens from every subagent this process started, background ones included, as they stream. */
|
|
266
|
+
let subagentTokens = 0;
|
|
267
|
+
export function subagentTokensSoFar() {
|
|
268
|
+
return subagentTokens;
|
|
269
|
+
}
|
|
270
|
+
/**
|
|
271
|
+
* Follows a subagent's JSON event stream into `details`: what it's doing now, its finished steps,
|
|
272
|
+
* tokens (estimated at about 4 characters each while a reply streams, then the counted figure),
|
|
273
|
+
* and its time to first token and output speed.
|
|
274
|
+
*/
|
|
275
|
+
export function createTracker(details, now = Date.now) {
|
|
276
|
+
let counted = 0;
|
|
277
|
+
let streamed = 0;
|
|
278
|
+
let requestAt;
|
|
279
|
+
let firstAt;
|
|
280
|
+
let replies = 0;
|
|
281
|
+
let firstTokenTotal = 0;
|
|
282
|
+
let streamMs = 0;
|
|
283
|
+
let streamedOutput = 0;
|
|
284
|
+
/** Tool calls the model is writing out, by content index (they can interleave), with their arguments so far. */
|
|
285
|
+
const preparing = new Map();
|
|
286
|
+
/** Tool calls running now, oldest first. Their end events don't repeat the arguments. */
|
|
287
|
+
const active = new Map();
|
|
288
|
+
const setTokens = (tokens) => {
|
|
289
|
+
subagentTokens += tokens - details.tokens;
|
|
290
|
+
details.tokens = tokens;
|
|
291
|
+
};
|
|
292
|
+
/** Back to the newest call still running, or to thinking when none is. */
|
|
293
|
+
const settle = () => {
|
|
294
|
+
const last = [...active.values()].at(-1);
|
|
295
|
+
details.progress = last ? activity(last.name, last.args) : "thinking";
|
|
296
|
+
};
|
|
297
|
+
let output = "";
|
|
298
|
+
let error;
|
|
299
|
+
const delta = (text) => {
|
|
300
|
+
const t = now();
|
|
301
|
+
if (firstAt === undefined) {
|
|
302
|
+
firstAt = t;
|
|
303
|
+
if (requestAt !== undefined) {
|
|
304
|
+
replies++;
|
|
305
|
+
firstTokenTotal += t - requestAt;
|
|
306
|
+
details.firstTokenMs = Math.round(firstTokenTotal / replies);
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
streamed += text?.length ?? 0;
|
|
310
|
+
setTokens(counted + Math.round(streamed / 4));
|
|
311
|
+
};
|
|
312
|
+
return {
|
|
313
|
+
get output() {
|
|
314
|
+
return output;
|
|
315
|
+
},
|
|
316
|
+
get error() {
|
|
317
|
+
return error;
|
|
318
|
+
},
|
|
319
|
+
onEvent(event) {
|
|
320
|
+
// Pi records the failed try right after announcing the retry; only real work, or the retry ending, clears it.
|
|
321
|
+
if (event.type && RESUMED.has(event.type))
|
|
322
|
+
details.retry = undefined;
|
|
323
|
+
switch (event.type) {
|
|
324
|
+
case "turn_start":
|
|
325
|
+
requestAt = now();
|
|
326
|
+
firstAt = undefined;
|
|
327
|
+
details.progress = "waiting for the model";
|
|
328
|
+
break;
|
|
329
|
+
case "message_update": {
|
|
330
|
+
const update = event.assistantMessageEvent ?? {};
|
|
331
|
+
if (update.type === "thinking_delta") {
|
|
332
|
+
delta(update.delta);
|
|
333
|
+
details.progress = "thinking";
|
|
334
|
+
}
|
|
335
|
+
else if (update.type === "text_delta") {
|
|
336
|
+
delta(update.delta);
|
|
337
|
+
details.progress = "writing";
|
|
338
|
+
}
|
|
339
|
+
else if (update.type === "toolcall_start") {
|
|
340
|
+
delta("");
|
|
341
|
+
const call = { name: update.toolName ?? "tool", args: "" };
|
|
342
|
+
preparing.set(update.contentIndex ?? 0, call);
|
|
343
|
+
details.progress = preparingLabel(call.name, "");
|
|
344
|
+
}
|
|
345
|
+
else if (update.type === "toolcall_delta") {
|
|
346
|
+
delta(update.delta);
|
|
347
|
+
const call = preparing.get(update.contentIndex ?? 0);
|
|
348
|
+
if (call) {
|
|
349
|
+
call.args += update.delta ?? "";
|
|
350
|
+
details.progress = preparingLabel(call.name, call.args);
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
break;
|
|
354
|
+
}
|
|
355
|
+
case "message_end": {
|
|
356
|
+
if (event.message?.role !== "assistant")
|
|
357
|
+
break;
|
|
358
|
+
const t = now();
|
|
359
|
+
const reported = event.message.usage?.output;
|
|
360
|
+
const tokens = reported || Math.round(streamed / 4);
|
|
361
|
+
if (firstAt !== undefined && tokens > 0 && t > firstAt) {
|
|
362
|
+
streamMs += t - firstAt;
|
|
363
|
+
streamedOutput += tokens;
|
|
364
|
+
details.tokensPerSecond = Math.round(streamedOutput / (streamMs / 1000));
|
|
365
|
+
}
|
|
366
|
+
counted += tokens;
|
|
367
|
+
streamed = 0;
|
|
368
|
+
preparing.clear();
|
|
369
|
+
setTokens(counted);
|
|
370
|
+
const text = (event.message.content ?? [])
|
|
371
|
+
.filter((c) => c.type === "text")
|
|
372
|
+
.map((c) => c.text ?? "")
|
|
373
|
+
.join("")
|
|
374
|
+
.trim();
|
|
375
|
+
if (text)
|
|
376
|
+
output = text;
|
|
377
|
+
error = event.message.stopReason === "error" ? (event.message.errorMessage ?? "the model returned an error") : undefined;
|
|
378
|
+
settle();
|
|
379
|
+
break;
|
|
380
|
+
}
|
|
381
|
+
case "tool_execution_start": {
|
|
382
|
+
const call = { name: event.toolName ?? "tool", args: event.args };
|
|
383
|
+
details.tools++;
|
|
384
|
+
active.set(event.toolCallId ?? `call ${details.tools}`, call);
|
|
385
|
+
details.progress = activity(call.name, call.args);
|
|
386
|
+
break;
|
|
387
|
+
}
|
|
388
|
+
case "tool_execution_end": {
|
|
389
|
+
const id = event.toolCallId ?? [...active.keys()][0] ?? "";
|
|
390
|
+
const call = active.get(id) ?? { name: event.toolName ?? "tool" };
|
|
391
|
+
active.delete(id);
|
|
392
|
+
details.steps.push({ text: stepText(call.name, call.args), ok: !event.isError });
|
|
393
|
+
if (details.steps.length > MAX_STEPS)
|
|
394
|
+
details.steps.splice(0, details.steps.length - MAX_STEPS);
|
|
395
|
+
settle();
|
|
396
|
+
break;
|
|
397
|
+
}
|
|
398
|
+
case "auto_retry_start": {
|
|
399
|
+
const why = firstLine(event.errorMessage ?? "").slice(0, 40);
|
|
400
|
+
const attempt = event.attempt ?? 1;
|
|
401
|
+
details.steps.push({ text: `try ${attempt} failed${why ? `: ${why}` : ""}`, ok: false });
|
|
402
|
+
details.retry = { at: now() + (event.delayMs ?? 0), label: `try ${attempt + 1} of ${(event.maxAttempts ?? 1) + 1}` };
|
|
403
|
+
break;
|
|
404
|
+
}
|
|
405
|
+
case "compaction_start":
|
|
406
|
+
details.progress = "tidying its notes";
|
|
407
|
+
break;
|
|
408
|
+
}
|
|
409
|
+
},
|
|
410
|
+
};
|
|
411
|
+
}
|
|
412
|
+
/** Run one subagent to completion, following its progress into `details` as it goes. */
|
|
413
|
+
function runAgent(cwd, kind, run, task, signal, details, onProgress) {
|
|
163
414
|
const args = [
|
|
164
415
|
join(PACKAGE_DIR, "bin", "klui.js"),
|
|
165
416
|
"--mode",
|
|
@@ -178,9 +429,7 @@ function runAgent(cwd, kind, run, task, signal, onProgress) {
|
|
|
178
429
|
];
|
|
179
430
|
return new Promise((resolve) => {
|
|
180
431
|
const child = spawn(process.execPath, args, { cwd, env: { ...process.env, [SUBAGENT_ENV]: "1", [PERMISSIONS_ENV]: state.mode }, stdio: ["ignore", "pipe", "pipe"] });
|
|
181
|
-
|
|
182
|
-
let output = "";
|
|
183
|
-
let error;
|
|
432
|
+
const tracker = createTracker(details);
|
|
184
433
|
let stderr = "";
|
|
185
434
|
let buffer = "";
|
|
186
435
|
const onLine = (line) => {
|
|
@@ -191,21 +440,8 @@ function runAgent(cwd, kind, run, task, signal, onProgress) {
|
|
|
191
440
|
catch {
|
|
192
441
|
return;
|
|
193
442
|
}
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
onProgress({ tools, progress: activity(event.toolName ?? "tool", event.args) });
|
|
197
|
-
}
|
|
198
|
-
else if (event.type === "message_end" && event.message?.role === "assistant") {
|
|
199
|
-
const text = (event.message.content ?? [])
|
|
200
|
-
.filter((c) => c.type === "text")
|
|
201
|
-
.map((c) => c.text ?? "")
|
|
202
|
-
.join("")
|
|
203
|
-
.trim();
|
|
204
|
-
if (text)
|
|
205
|
-
output = text;
|
|
206
|
-
error = event.message.stopReason === "error" ? (event.message.errorMessage ?? "the model returned an error") : undefined;
|
|
207
|
-
onProgress({ tools, progress: "thinking" });
|
|
208
|
-
}
|
|
443
|
+
tracker.onEvent(event);
|
|
444
|
+
onProgress();
|
|
209
445
|
};
|
|
210
446
|
child.stdout.setEncoding("utf8");
|
|
211
447
|
child.stdout.on("data", (chunk) => {
|
|
@@ -225,22 +461,91 @@ function runAgent(cwd, kind, run, task, signal, onProgress) {
|
|
|
225
461
|
signal?.addEventListener("abort", stop, { once: true });
|
|
226
462
|
child.on("error", (e) => {
|
|
227
463
|
signal?.removeEventListener("abort", stop);
|
|
228
|
-
resolve({ output
|
|
464
|
+
resolve({ output: tracker.output, error: e.message });
|
|
229
465
|
});
|
|
230
466
|
child.on("close", (code) => {
|
|
231
467
|
signal?.removeEventListener("abort", stop);
|
|
232
468
|
if (buffer.trim())
|
|
233
469
|
onLine(buffer);
|
|
470
|
+
let error = tracker.error;
|
|
234
471
|
if (code !== 0 && !error && !signal?.aborted)
|
|
235
472
|
error = stderr.trim().split("\n").pop() || `exited with code ${code}`;
|
|
236
|
-
resolve({ output
|
|
473
|
+
resolve({ output: tracker.output, error });
|
|
237
474
|
});
|
|
238
475
|
});
|
|
239
476
|
}
|
|
477
|
+
/** What a tool call is doing, while it runs: "reading src/app.ts", "$ npm test". */
|
|
240
478
|
function activity(toolName, args) {
|
|
241
479
|
const a = args ?? {};
|
|
242
|
-
|
|
243
|
-
|
|
480
|
+
switch (toolName) {
|
|
481
|
+
case "read":
|
|
482
|
+
return `reading ${target(a)}`;
|
|
483
|
+
case "edit":
|
|
484
|
+
return `editing ${target(a)}`;
|
|
485
|
+
case "write":
|
|
486
|
+
return `writing ${target(a)}`;
|
|
487
|
+
case "bash":
|
|
488
|
+
return `$ ${clip(firstLine(String(a.command ?? "")), 40)}`;
|
|
489
|
+
case "grep":
|
|
490
|
+
case "find":
|
|
491
|
+
return `looking for ${clip(String(a.pattern ?? ""), 32)}`;
|
|
492
|
+
case "ls":
|
|
493
|
+
return `listing ${target(a)}`;
|
|
494
|
+
case "web_search":
|
|
495
|
+
return `searching the web for ${clip(String(a.query ?? ""), 36)}`;
|
|
496
|
+
case "web_fetch":
|
|
497
|
+
return `fetching ${clip(String(a.url ?? "").replace(/^https?:\/\//, ""), 40)}`;
|
|
498
|
+
default:
|
|
499
|
+
return `using ${toolName}`;
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
/** A finished tool call, as a step: "Read src/app.ts", "Bash npm test". */
|
|
503
|
+
function stepText(toolName, args) {
|
|
504
|
+
const a = args ?? {};
|
|
505
|
+
const name = STEP_NAMES[toolName] ?? toolName;
|
|
506
|
+
switch (toolName) {
|
|
507
|
+
case "read":
|
|
508
|
+
case "edit":
|
|
509
|
+
case "write":
|
|
510
|
+
case "ls":
|
|
511
|
+
return `${name} ${target(a)}`;
|
|
512
|
+
case "bash":
|
|
513
|
+
return `${name} ${clip(firstLine(String(a.command ?? "")), 48)}`;
|
|
514
|
+
case "grep":
|
|
515
|
+
case "find":
|
|
516
|
+
return `${name} ${clip(String(a.pattern ?? ""), 40)}`;
|
|
517
|
+
case "web_search":
|
|
518
|
+
return `${name} ${clip(String(a.query ?? ""), 44)}`;
|
|
519
|
+
case "web_fetch":
|
|
520
|
+
return `${name} ${clip(String(a.url ?? "").replace(/^https?:\/\//, ""), 48)}`;
|
|
521
|
+
default:
|
|
522
|
+
return name;
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
const STEP_NAMES = {
|
|
526
|
+
read: "Read",
|
|
527
|
+
edit: "Updated",
|
|
528
|
+
write: "Wrote",
|
|
529
|
+
bash: "Ran",
|
|
530
|
+
grep: "Searched",
|
|
531
|
+
find: "Found",
|
|
532
|
+
ls: "Listed",
|
|
533
|
+
web_search: "Searched the web for",
|
|
534
|
+
web_fetch: "Fetched",
|
|
535
|
+
};
|
|
536
|
+
function target(a) {
|
|
537
|
+
const path = [a.path, a.file_path].find((v) => typeof v === "string");
|
|
538
|
+
return path ? clip(shortPath(path), 40) : ".";
|
|
539
|
+
}
|
|
540
|
+
function formatElapsed(ms) {
|
|
541
|
+
const s = Math.max(0, Math.floor(ms / 1000));
|
|
542
|
+
return s < 60 ? `${s}s` : `${Math.floor(s / 60)}m ${String(s % 60).padStart(2, "0")}s`;
|
|
543
|
+
}
|
|
544
|
+
export function formatTokens(n) {
|
|
545
|
+
return n < 1000 ? String(n) : `${(n / 1000).toFixed(1).replace(/\.0$/, "")}k`;
|
|
546
|
+
}
|
|
547
|
+
function plural(n, word) {
|
|
548
|
+
return `${n} ${word}${n === 1 ? "" : "s"}`;
|
|
244
549
|
}
|
|
245
550
|
function clip(text, max) {
|
|
246
551
|
return text.length > max ? `${text.slice(0, max - 1)}…` : text;
|
package/dist/extension/checks.js
CHANGED
|
@@ -86,7 +86,7 @@ export function registerChecks(pi, onChecking = () => { }) {
|
|
|
86
86
|
const shown = options.expanded ? d.lines : d.lines.slice(0, PREVIEW);
|
|
87
87
|
const hidden = total - shown.length;
|
|
88
88
|
const rows = [
|
|
89
|
-
`${pad}${theme.fg("warning", "
|
|
89
|
+
`${pad}${theme.fg("warning", "●")} ${theme.bold("Checks")}`,
|
|
90
90
|
`${pad} ${theme.fg("dim", "⎿")} ${total} problem${total === 1 ? "" : "s"} to fix`,
|
|
91
91
|
...shown.map((l) => `${pad} ${theme.fg("muted", l)}`),
|
|
92
92
|
...(hidden ? [`${pad} ${theme.fg("dim", `… +${hidden} more`)}`] : []),
|
|
@@ -53,7 +53,7 @@ export function registerCommands(pi, actions) {
|
|
|
53
53
|
},
|
|
54
54
|
});
|
|
55
55
|
pi.registerCommand("usage", {
|
|
56
|
-
description: "Tokens
|
|
56
|
+
description: "Tokens and model requests in the last 24 hours and overall, subagents included",
|
|
57
57
|
handler: async (_args, ctx) => {
|
|
58
58
|
ctx.ui.notify(usageReport(readUsage()), "info");
|
|
59
59
|
},
|
|
@@ -164,13 +164,13 @@ function aboutCard(theme, done) {
|
|
|
164
164
|
invalidate() { },
|
|
165
165
|
};
|
|
166
166
|
}
|
|
167
|
-
/** Three rows: the header, total tokens (736.8K) and
|
|
167
|
+
/** Three rows: the header, total tokens (736.8K) and requests, last 24 hours next to lifetime. */
|
|
168
168
|
export function usageReport({ day, lifetime }) {
|
|
169
169
|
const line = (label, a, b) => `${label.padEnd(14)}${a.padStart(10)} ${b.padStart(10)}`;
|
|
170
170
|
return [
|
|
171
171
|
line("Usage", "Last 24h", "Lifetime"),
|
|
172
172
|
line("Total tokens", compact(day.total), compact(lifetime.total)),
|
|
173
|
-
line("
|
|
173
|
+
line("Requests", day.requests.toLocaleString("en-US"), lifetime.requests.toLocaleString("en-US")),
|
|
174
174
|
].join("\n");
|
|
175
175
|
}
|
|
176
176
|
/** 950, 736.8K, 1.2M, 3.4B: one decimal at most. */
|