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/agents.js
CHANGED
|
@@ -1,63 +1,96 @@
|
|
|
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.
|
|
12
|
+
//
|
|
13
|
+
// A subagent can't show a dialog, so when a call of its needs the user's OK it asks this Klui over
|
|
14
|
+
// an IPC channel, and the dialog shows here. Its chat is saved in KLUI_HOME/subagents (only the
|
|
15
|
+
// newest few, for a week), and the result names the file, so `klui --session <file>` opens it.
|
|
7
16
|
import { spawn } from "node:child_process";
|
|
17
|
+
import { mkdirSync, readdirSync, rmSync, statSync } from "node:fs";
|
|
8
18
|
import { join } from "node:path";
|
|
9
19
|
import { StringEnum } from "@earendil-works/pi-ai";
|
|
10
|
-
import { getMarkdownTheme } from "@earendil-works/pi-coding-agent";
|
|
20
|
+
import { getMarkdownTheme, keyText } from "@earendil-works/pi-coding-agent";
|
|
11
21
|
import { Container, Markdown, Text } from "@earendil-works/pi-tui";
|
|
12
22
|
import { Type } from "typebox";
|
|
13
|
-
import { PACKAGE_DIR, PROVIDER } from "../paths.js";
|
|
14
|
-
import {
|
|
23
|
+
import { KLUI_HOME, PACKAGE_DIR, PROVIDER } from "../paths.js";
|
|
24
|
+
import { PARENT_SESSION_ENV } from "../usage.js";
|
|
25
|
+
import { ASK_PARENT, decide, PERMISSIONS_ENV } from "./permissions.js";
|
|
15
26
|
import { state } from "./state.js";
|
|
27
|
+
import { preparingLabel, shortPath } from "./voice.js";
|
|
16
28
|
/** Set in a subagent's environment: subagents don't start subagents of their own. */
|
|
17
29
|
export const SUBAGENT_ENV = "KLUI_SUBAGENT";
|
|
18
30
|
export const AGENT_MESSAGE = "klui-agent";
|
|
19
31
|
const WIDGET = "klui-agents";
|
|
32
|
+
/** Rows refresh this often while an agent runs, so the clock and counter keep moving between events. */
|
|
33
|
+
const TICK_MS = 500;
|
|
34
|
+
/** Finished steps kept for the expanded view: plenty for any real run, and a bound on a runaway one. */
|
|
35
|
+
const MAX_STEPS = 500;
|
|
36
|
+
/** Subagent chats kept: the newest this many, none older than a week. */
|
|
37
|
+
const TRANSCRIPTS = join(KLUI_HOME, "subagents");
|
|
38
|
+
const MAX_TRANSCRIPTS = 30;
|
|
39
|
+
const TRANSCRIPT_DAYS = 7;
|
|
40
|
+
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
41
|
const KINDS = {
|
|
21
42
|
explore: {
|
|
22
|
-
tools: "read,grep,find,ls",
|
|
23
|
-
prompt:
|
|
43
|
+
tools: "read,grep,find,ls,web_search,web_fetch",
|
|
44
|
+
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
45
|
},
|
|
25
46
|
general: {
|
|
26
|
-
tools: "read,bash,edit,write,grep,find,ls",
|
|
27
|
-
prompt:
|
|
47
|
+
tools: "read,bash,edit,write,grep,find,ls,web_search,web_fetch,screenshot",
|
|
48
|
+
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
49
|
},
|
|
29
50
|
};
|
|
30
51
|
export function registerAgents(pi) {
|
|
31
52
|
const running = new Map();
|
|
32
53
|
let nextId = 1;
|
|
33
54
|
let ui;
|
|
55
|
+
let widgetTimer;
|
|
56
|
+
/** One line per background agent, with what it's doing; the clock ticks while any runs. */
|
|
34
57
|
const showRunning = () => {
|
|
35
58
|
if (!ui)
|
|
36
59
|
return;
|
|
37
|
-
const list = [...running.values()];
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
60
|
+
const list = [...running.values()].map((r) => r.details);
|
|
61
|
+
if (list.length === 0) {
|
|
62
|
+
clearInterval(widgetTimer);
|
|
63
|
+
widgetTimer = undefined;
|
|
64
|
+
ui.setWidget(WIDGET, undefined);
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
widgetTimer ??= setInterval(showRunning, 1000);
|
|
68
|
+
widgetTimer.unref?.();
|
|
69
|
+
const now = Date.now();
|
|
70
|
+
const shown = list.slice(0, 3).map((d) => ` ◌ ${d.kind} #${d.background} · ${statusLine(d, now)}`);
|
|
71
|
+
if (list.length > 3)
|
|
72
|
+
shown.push(` ◌ +${list.length - 3} more background agents`);
|
|
73
|
+
ui.setWidget(WIDGET, shown);
|
|
41
74
|
};
|
|
42
75
|
pi.registerTool({
|
|
43
76
|
name: "subagent",
|
|
44
77
|
label: "Subagent",
|
|
45
78
|
description: [
|
|
46
79
|
"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
|
|
80
|
+
'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
81
|
'kind "general" can also edit files and run commands: use it for an independent piece of work.',
|
|
49
82
|
"The subagent can't see this conversation, so put everything it needs in the task.",
|
|
50
83
|
"Call it several times in one turn to run independent tasks in parallel.",
|
|
51
84
|
"Set background to true to keep working while it runs; its report arrives later as a message.",
|
|
52
85
|
`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
86
|
].join(" "),
|
|
54
|
-
promptSnippet: "subagent: delegate a self-contained task to a fresh agent (explore = read-only, general = can edit); several can run in parallel",
|
|
87
|
+
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
88
|
promptGuidelines: [
|
|
56
|
-
"Use subagent for wide searches or independent sub-tasks, not for a single quick lookup you can do yourself.",
|
|
89
|
+
"Use subagent for wide searches, web research or independent sub-tasks, not for a single quick lookup you can do yourself.",
|
|
57
90
|
],
|
|
58
91
|
parameters: Type.Object({
|
|
59
92
|
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)" })),
|
|
93
|
+
kind: Type.Optional(StringEnum(["explore", "general"], { description: "explore (read-only files and web, default) or general (can edit and run commands)" })),
|
|
61
94
|
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
95
|
background: Type.Optional(Type.Boolean({ description: "Return right away and deliver the report as a message later" })),
|
|
63
96
|
}),
|
|
@@ -68,8 +101,8 @@ export function registerAgents(pi) {
|
|
|
68
101
|
const own = ctx.model?.provider === PROVIDER ? state.config.models.find((m) => m.id === ctx.model.id) : undefined;
|
|
69
102
|
const model = params.model ? resolveModel(params.model) : (own ?? resolveModel(state.config.defaultModel));
|
|
70
103
|
const run = { model: `${PROVIDER}/${model.id}`, thinking: pi.getThinkingLevel() };
|
|
71
|
-
const details = { kind, task: params.task, model: model.name, tools: 0, elapsedMs: 0 };
|
|
72
104
|
const startedAt = Date.now();
|
|
105
|
+
const details = { kind, task: params.task, model: model.name, tools: 0, tokens: 0, steps: [], progress: "starting up", startedAt, elapsedMs: 0 };
|
|
73
106
|
if (params.background) {
|
|
74
107
|
ui = ctx.hasUI ? ctx.ui : undefined;
|
|
75
108
|
const id = nextId++;
|
|
@@ -77,12 +110,18 @@ export function registerAgents(pi) {
|
|
|
77
110
|
details.background = id;
|
|
78
111
|
running.set(id, { controller, details });
|
|
79
112
|
showRunning();
|
|
80
|
-
|
|
113
|
+
let shownAt = 0;
|
|
114
|
+
void runAgent(ctx, kind, run, params.task, controller.signal, details, () => {
|
|
115
|
+
if (Date.now() - shownAt < 250)
|
|
116
|
+
return;
|
|
117
|
+
shownAt = Date.now();
|
|
118
|
+
showRunning();
|
|
119
|
+
}).then((outcome) => {
|
|
81
120
|
running.delete(id);
|
|
82
121
|
showRunning();
|
|
83
122
|
if (controller.signal.aborted)
|
|
84
123
|
return;
|
|
85
|
-
const done = { ...details,
|
|
124
|
+
const done = { ...details, progress: undefined, error: outcome.error, elapsedMs: Date.now() - startedAt };
|
|
86
125
|
pi.sendMessage({
|
|
87
126
|
customType: AGENT_MESSAGE,
|
|
88
127
|
content: `Background agent #${id} (${kind}) ${outcome.error ? `failed: ${outcome.error}` : "finished"}.\n\n${outcome.output}`,
|
|
@@ -92,46 +131,73 @@ export function registerAgents(pi) {
|
|
|
92
131
|
});
|
|
93
132
|
return {
|
|
94
133
|
content: [{ type: "text", text: `Started background agent #${id}. Its report will arrive as a message when it finishes; carry on meanwhile.` }],
|
|
95
|
-
details,
|
|
134
|
+
details: { ...details, steps: [] },
|
|
96
135
|
};
|
|
97
136
|
}
|
|
137
|
+
// Events come in bursts; between them a steady tick keeps the clock and counter moving.
|
|
98
138
|
let lastUpdate = 0;
|
|
99
|
-
const
|
|
100
|
-
Object.assign(details, p, { elapsedMs: Date.now() - startedAt });
|
|
101
|
-
if (Date.now() - lastUpdate < 200)
|
|
102
|
-
return;
|
|
139
|
+
const emit = () => {
|
|
103
140
|
lastUpdate = Date.now();
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
141
|
+
details.elapsedMs = lastUpdate - startedAt;
|
|
142
|
+
onUpdate?.({ content: [{ type: "text", text: "" }], details: { ...details, steps: [...details.steps] } });
|
|
143
|
+
};
|
|
144
|
+
const tick = setInterval(emit, TICK_MS);
|
|
145
|
+
tick.unref?.();
|
|
146
|
+
emit();
|
|
147
|
+
const outcome = await runAgent(ctx, kind, run, params.task, signal, details, () => {
|
|
148
|
+
if (Date.now() - lastUpdate >= 150)
|
|
149
|
+
emit();
|
|
150
|
+
}).finally(() => clearInterval(tick));
|
|
151
|
+
// A stopped or failed agent still keeps its steps for the expanded row, and the parent gets
|
|
152
|
+
// whatever it said before it failed, marked as unfinished rather than passed off as its report.
|
|
153
|
+
const failed = signal?.aborted ? "Subagent stopped" : outcome.error;
|
|
154
|
+
if (failed) {
|
|
155
|
+
const said = outcome.output.trim();
|
|
156
|
+
return {
|
|
157
|
+
content: [{ type: "text", text: said ? `${failed}\n\nIt said this before it stopped, so it may be unfinished:\n\n${said}` : failed }],
|
|
158
|
+
details: { ...details, progress: undefined, error: failed, elapsedMs: Date.now() - startedAt },
|
|
159
|
+
isError: true,
|
|
160
|
+
};
|
|
161
|
+
}
|
|
110
162
|
return {
|
|
111
163
|
content: [{ type: "text", text: outcome.output || "(the subagent finished without a report)" }],
|
|
112
|
-
details: { ...details,
|
|
164
|
+
details: { ...details, progress: undefined, elapsedMs: Date.now() - startedAt },
|
|
113
165
|
};
|
|
114
166
|
},
|
|
115
167
|
renderCall(args, theme) {
|
|
116
168
|
const kind = args.kind ?? "explore";
|
|
117
169
|
return new Text(`${theme.bold(theme.fg("toolTitle", "agent"))} ${theme.fg("accent", kind)}\n${theme.fg("muted", args.task ?? "")}`, 0, 0);
|
|
118
170
|
},
|
|
119
|
-
renderResult(result,
|
|
171
|
+
renderResult(result, options, theme) {
|
|
172
|
+
// Expanded: every step, then what it's doing now while it runs, or its report once it's done.
|
|
173
|
+
const d = result.details;
|
|
174
|
+
const steps = (d?.steps ?? []).map((step) => stepLine(step, theme));
|
|
175
|
+
if (options.isPartial && d?.steps) {
|
|
176
|
+
return new Text([...steps, `${theme.fg("accent", spark(Date.now()))} ${theme.fg("accent", statusLine(d, Date.now()))}`].join("\n"), 0, 1);
|
|
177
|
+
}
|
|
120
178
|
const text = result.content.find((c) => c.type === "text")?.text ?? "";
|
|
121
|
-
|
|
179
|
+
const report = text.trim() ? new Markdown(text, 0, 1, getMarkdownTheme()) : new Text(theme.fg("dim", "no report"), 0, 0);
|
|
180
|
+
if (steps.length === 0)
|
|
181
|
+
return report;
|
|
182
|
+
const row = new Container();
|
|
183
|
+
row.addChild(new Text(steps.join("\n"), 0, 1));
|
|
184
|
+
row.addChild(report);
|
|
185
|
+
return row;
|
|
122
186
|
},
|
|
123
187
|
});
|
|
124
188
|
pi.registerMessageRenderer(AGENT_MESSAGE, (message, options, theme) => {
|
|
125
189
|
const d = message.details;
|
|
126
190
|
if (!d)
|
|
127
191
|
return undefined;
|
|
128
|
-
const dot = d.error ? theme.fg("error", "
|
|
129
|
-
const meta = [d.error ??
|
|
192
|
+
const dot = d.error ? theme.fg("error", "●") : theme.fg("success", "●");
|
|
193
|
+
const meta = [d.error ?? plural(d.tools, "tool"), d.tokens > 0 ? `↓ ${formatTokens(d.tokens)} tokens` : undefined, formatElapsed(d.elapsedMs)].filter(Boolean).join(" · ");
|
|
130
194
|
const pad = " ".repeat(options.outputPad);
|
|
131
195
|
const head = `${pad}${dot} ${theme.bold("Agent")}${theme.fg("muted", "(")}${d.kind} #${d.background}: ${clip(firstLine(d.task), 48)}${theme.fg("muted", ")")}`;
|
|
132
196
|
const row = new Container();
|
|
133
197
|
row.addChild(new Text(`${head}\n${pad} ${theme.fg("dim", "⎿")} Reported back ${theme.fg("dim", `· ${meta}`)}`, 0, 0));
|
|
134
198
|
if (options.expanded) {
|
|
199
|
+
if (d.steps?.length)
|
|
200
|
+
row.addChild(new Text(d.steps.map((step) => stepLine(step, theme)).join("\n"), options.outputPad + 2, 1));
|
|
135
201
|
const report = typeof message.content === "string" ? message.content : "";
|
|
136
202
|
row.addChild(new Markdown(report.replace(/^[^\n]*\n\n/, ""), options.outputPad + 2, 1, getMarkdownTheme()));
|
|
137
203
|
}
|
|
@@ -141,8 +207,54 @@ export function registerAgents(pi) {
|
|
|
141
207
|
for (const { controller } of running.values())
|
|
142
208
|
controller.abort();
|
|
143
209
|
running.clear();
|
|
210
|
+
clearInterval(widgetTimer);
|
|
211
|
+
widgetTimer = undefined;
|
|
144
212
|
});
|
|
145
213
|
}
|
|
214
|
+
/**
|
|
215
|
+
* A running agent's row under its call: its last few finished steps, then what it's doing now with
|
|
216
|
+
* the tool count, tokens and time. Older steps are a key press away.
|
|
217
|
+
*/
|
|
218
|
+
export function agentLines(d, theme, now = Date.now(), recent = 2) {
|
|
219
|
+
const fg = theme.fg;
|
|
220
|
+
const steps = d.steps ?? [];
|
|
221
|
+
const lines = [];
|
|
222
|
+
const key = keyText("app.tools.expand");
|
|
223
|
+
if (steps.length > recent)
|
|
224
|
+
lines.push(fg("dim", `… ${plural(steps.length - recent, "earlier step")}${key ? ` (${key} to see them)` : ""}`));
|
|
225
|
+
for (const step of steps.slice(-recent))
|
|
226
|
+
lines.push(stepLine(step, theme));
|
|
227
|
+
lines.push(`${fg("accent", spark(now))} ${fg("accent", agentProgress(d, now))}${fg("dim", ` · ${statusMeta(d, now)}`)}`);
|
|
228
|
+
return lines;
|
|
229
|
+
}
|
|
230
|
+
/** "reading src/app.ts · 3 tools · ↓ 1.2k tokens · 42s". */
|
|
231
|
+
export function statusLine(d, now = Date.now()) {
|
|
232
|
+
return `${agentProgress(d, now)} · ${statusMeta(d, now)}`;
|
|
233
|
+
}
|
|
234
|
+
/** What it's doing, with a retry counting down to its next try. */
|
|
235
|
+
export function agentProgress(d, now = Date.now()) {
|
|
236
|
+
if (d.retry)
|
|
237
|
+
return `retrying ${d.retry.at > now ? `in ${Math.ceil((d.retry.at - now) / 1000)}s ` : "now "}(${d.retry.label})`;
|
|
238
|
+
return d.progress ?? "working";
|
|
239
|
+
}
|
|
240
|
+
function statusMeta(d, now) {
|
|
241
|
+
return [
|
|
242
|
+
plural(d.tools, "tool"),
|
|
243
|
+
d.tokens > 0 ? `↓ ${formatTokens(d.tokens)} tokens` : undefined,
|
|
244
|
+
formatElapsed(now - d.startedAt),
|
|
245
|
+
]
|
|
246
|
+
.filter(Boolean)
|
|
247
|
+
.join(" · ");
|
|
248
|
+
}
|
|
249
|
+
function stepLine(step, theme) {
|
|
250
|
+
const fg = theme.fg;
|
|
251
|
+
return `${step.ok ? fg("success", "✓") : fg("error", "✗")} ${fg("muted", step.text)}`;
|
|
252
|
+
}
|
|
253
|
+
const SPARKS = ["✶", "✷", "✸", "✹", "✺", "✹", "✸", "✷"];
|
|
254
|
+
/** A little star that turns as the row refreshes, so a quiet agent still looks alive. */
|
|
255
|
+
function spark(now) {
|
|
256
|
+
return process.env.KLUI_REDUCED_MOTION === "1" ? "✶" : SPARKS[Math.floor(now / TICK_MS) % SPARKS.length];
|
|
257
|
+
}
|
|
146
258
|
function modelHint(m) {
|
|
147
259
|
return `${m.id} (${m.name}${m.tagline ? `, ${m.tagline}` : ""})`;
|
|
148
260
|
}
|
|
@@ -158,14 +270,164 @@ function resolveModel(requested) {
|
|
|
158
270
|
throw new Error(`Unknown model "${requested}". Pick one of: ${models.map((m) => m.id).join(", ")}`);
|
|
159
271
|
return found;
|
|
160
272
|
}
|
|
161
|
-
/**
|
|
162
|
-
|
|
273
|
+
/** Events that mean a retry's wait is over. */
|
|
274
|
+
const RESUMED = new Set(["auto_retry_end", "turn_start", "message_update", "tool_execution_start", "agent_end"]);
|
|
275
|
+
/** Output tokens from every subagent this process started, background ones included, as they stream. */
|
|
276
|
+
let subagentTokens = 0;
|
|
277
|
+
export function subagentTokensSoFar() {
|
|
278
|
+
return subagentTokens;
|
|
279
|
+
}
|
|
280
|
+
/**
|
|
281
|
+
* Follows a subagent's JSON event stream into `details`: what it's doing now, its finished steps,
|
|
282
|
+
* tokens (estimated at about 4 characters each while a reply streams, then the counted figure),
|
|
283
|
+
* and its time to first token and output speed.
|
|
284
|
+
*/
|
|
285
|
+
export function createTracker(details, now = Date.now) {
|
|
286
|
+
let counted = 0;
|
|
287
|
+
let streamed = 0;
|
|
288
|
+
let requestAt;
|
|
289
|
+
let firstAt;
|
|
290
|
+
let replies = 0;
|
|
291
|
+
let firstTokenTotal = 0;
|
|
292
|
+
let streamMs = 0;
|
|
293
|
+
let streamedOutput = 0;
|
|
294
|
+
/** Tool calls the model is writing out, by content index (they can interleave), with their arguments so far. */
|
|
295
|
+
const preparing = new Map();
|
|
296
|
+
/** Tool calls running now, oldest first. Their end events don't repeat the arguments. */
|
|
297
|
+
const active = new Map();
|
|
298
|
+
const setTokens = (tokens) => {
|
|
299
|
+
subagentTokens += tokens - details.tokens;
|
|
300
|
+
details.tokens = tokens;
|
|
301
|
+
};
|
|
302
|
+
/** Back to the newest call still running, or to thinking when none is. */
|
|
303
|
+
const settle = () => {
|
|
304
|
+
const last = [...active.values()].at(-1);
|
|
305
|
+
details.progress = last ? activity(last.name, last.args) : "thinking";
|
|
306
|
+
};
|
|
307
|
+
let output = "";
|
|
308
|
+
let error;
|
|
309
|
+
const delta = (text) => {
|
|
310
|
+
const t = now();
|
|
311
|
+
if (firstAt === undefined) {
|
|
312
|
+
firstAt = t;
|
|
313
|
+
if (requestAt !== undefined) {
|
|
314
|
+
replies++;
|
|
315
|
+
firstTokenTotal += t - requestAt;
|
|
316
|
+
details.firstTokenMs = Math.round(firstTokenTotal / replies);
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
streamed += text?.length ?? 0;
|
|
320
|
+
setTokens(counted + Math.round(streamed / 4));
|
|
321
|
+
};
|
|
322
|
+
return {
|
|
323
|
+
get output() {
|
|
324
|
+
return output;
|
|
325
|
+
},
|
|
326
|
+
get error() {
|
|
327
|
+
return error;
|
|
328
|
+
},
|
|
329
|
+
onEvent(event) {
|
|
330
|
+
// Pi records the failed try right after announcing the retry; only real work, or the retry ending, clears it.
|
|
331
|
+
if (event.type && RESUMED.has(event.type))
|
|
332
|
+
details.retry = undefined;
|
|
333
|
+
switch (event.type) {
|
|
334
|
+
case "turn_start":
|
|
335
|
+
requestAt = now();
|
|
336
|
+
firstAt = undefined;
|
|
337
|
+
details.progress = "waiting for the model";
|
|
338
|
+
break;
|
|
339
|
+
case "message_update": {
|
|
340
|
+
const update = event.assistantMessageEvent ?? {};
|
|
341
|
+
if (update.type === "thinking_delta") {
|
|
342
|
+
delta(update.delta);
|
|
343
|
+
details.progress = "thinking";
|
|
344
|
+
}
|
|
345
|
+
else if (update.type === "text_delta") {
|
|
346
|
+
delta(update.delta);
|
|
347
|
+
details.progress = "writing";
|
|
348
|
+
}
|
|
349
|
+
else if (update.type === "toolcall_start") {
|
|
350
|
+
delta("");
|
|
351
|
+
const call = { name: update.toolName ?? "tool", args: "" };
|
|
352
|
+
preparing.set(update.contentIndex ?? 0, call);
|
|
353
|
+
details.progress = preparingLabel(call.name, "");
|
|
354
|
+
}
|
|
355
|
+
else if (update.type === "toolcall_delta") {
|
|
356
|
+
delta(update.delta);
|
|
357
|
+
const call = preparing.get(update.contentIndex ?? 0);
|
|
358
|
+
if (call) {
|
|
359
|
+
call.args += update.delta ?? "";
|
|
360
|
+
details.progress = preparingLabel(call.name, call.args);
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
break;
|
|
364
|
+
}
|
|
365
|
+
case "message_end": {
|
|
366
|
+
if (event.message?.role !== "assistant")
|
|
367
|
+
break;
|
|
368
|
+
const t = now();
|
|
369
|
+
const reported = event.message.usage?.output;
|
|
370
|
+
const tokens = reported || Math.round(streamed / 4);
|
|
371
|
+
if (firstAt !== undefined && tokens > 0 && t > firstAt) {
|
|
372
|
+
streamMs += t - firstAt;
|
|
373
|
+
streamedOutput += tokens;
|
|
374
|
+
details.tokensPerSecond = Math.round(streamedOutput / (streamMs / 1000));
|
|
375
|
+
}
|
|
376
|
+
counted += tokens;
|
|
377
|
+
streamed = 0;
|
|
378
|
+
preparing.clear();
|
|
379
|
+
setTokens(counted);
|
|
380
|
+
const text = (event.message.content ?? [])
|
|
381
|
+
.filter((c) => c.type === "text")
|
|
382
|
+
.map((c) => c.text ?? "")
|
|
383
|
+
.join("")
|
|
384
|
+
.trim();
|
|
385
|
+
if (text)
|
|
386
|
+
output = text;
|
|
387
|
+
error = event.message.stopReason === "error" ? (event.message.errorMessage ?? "the model returned an error") : undefined;
|
|
388
|
+
settle();
|
|
389
|
+
break;
|
|
390
|
+
}
|
|
391
|
+
case "tool_execution_start": {
|
|
392
|
+
const call = { name: event.toolName ?? "tool", args: event.args };
|
|
393
|
+
details.tools++;
|
|
394
|
+
active.set(event.toolCallId ?? `call ${details.tools}`, call);
|
|
395
|
+
details.progress = activity(call.name, call.args);
|
|
396
|
+
break;
|
|
397
|
+
}
|
|
398
|
+
case "tool_execution_end": {
|
|
399
|
+
const id = event.toolCallId ?? [...active.keys()][0] ?? "";
|
|
400
|
+
const call = active.get(id) ?? { name: event.toolName ?? "tool" };
|
|
401
|
+
active.delete(id);
|
|
402
|
+
details.steps.push({ text: stepText(call.name, call.args), ok: !event.isError });
|
|
403
|
+
if (details.steps.length > MAX_STEPS)
|
|
404
|
+
details.steps.splice(0, details.steps.length - MAX_STEPS);
|
|
405
|
+
settle();
|
|
406
|
+
break;
|
|
407
|
+
}
|
|
408
|
+
case "auto_retry_start": {
|
|
409
|
+
const why = firstLine(event.errorMessage ?? "").slice(0, 40);
|
|
410
|
+
const attempt = event.attempt ?? 1;
|
|
411
|
+
details.steps.push({ text: `try ${attempt} failed${why ? `: ${why}` : ""}`, ok: false });
|
|
412
|
+
details.retry = { at: now() + (event.delayMs ?? 0), label: `try ${attempt + 1} of ${(event.maxAttempts ?? 1) + 1}` };
|
|
413
|
+
break;
|
|
414
|
+
}
|
|
415
|
+
case "compaction_start":
|
|
416
|
+
details.progress = "tidying its notes";
|
|
417
|
+
break;
|
|
418
|
+
}
|
|
419
|
+
},
|
|
420
|
+
};
|
|
421
|
+
}
|
|
422
|
+
/** Run one subagent to completion, following its progress into `details` as it goes. */
|
|
423
|
+
function runAgent(ctx, kind, run, task, signal, details, onProgress) {
|
|
163
424
|
const args = [
|
|
164
425
|
join(PACKAGE_DIR, "bin", "klui.js"),
|
|
165
426
|
"--mode",
|
|
166
427
|
"json",
|
|
167
428
|
"-p",
|
|
168
|
-
"--
|
|
429
|
+
"--session",
|
|
430
|
+
(details.transcript = newTranscript(kind)),
|
|
169
431
|
"--model",
|
|
170
432
|
run.model,
|
|
171
433
|
"--thinking",
|
|
@@ -177,10 +439,9 @@ function runAgent(cwd, kind, run, task, signal, onProgress) {
|
|
|
177
439
|
`Task: ${task}`,
|
|
178
440
|
];
|
|
179
441
|
return new Promise((resolve) => {
|
|
180
|
-
const
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
let error;
|
|
442
|
+
const env = { ...process.env, [SUBAGENT_ENV]: "1", [PERMISSIONS_ENV]: state.mode, [PARENT_SESSION_ENV]: ctx.sessionManager.getSessionId() };
|
|
443
|
+
const child = spawn(process.execPath, args, { cwd: ctx.cwd, env, stdio: ["ignore", "pipe", "pipe", "ipc"] });
|
|
444
|
+
const tracker = createTracker(details);
|
|
184
445
|
let stderr = "";
|
|
185
446
|
let buffer = "";
|
|
186
447
|
const onLine = (line) => {
|
|
@@ -191,21 +452,8 @@ function runAgent(cwd, kind, run, task, signal, onProgress) {
|
|
|
191
452
|
catch {
|
|
192
453
|
return;
|
|
193
454
|
}
|
|
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
|
-
}
|
|
455
|
+
tracker.onEvent(event);
|
|
456
|
+
onProgress();
|
|
209
457
|
};
|
|
210
458
|
child.stdout.setEncoding("utf8");
|
|
211
459
|
child.stdout.on("data", (chunk) => {
|
|
@@ -217,6 +465,23 @@ function runAgent(cwd, kind, run, task, signal, onProgress) {
|
|
|
217
465
|
newline = buffer.indexOf("\n");
|
|
218
466
|
}
|
|
219
467
|
});
|
|
468
|
+
// A call that needs the user's OK: ask here, and answer the subagent.
|
|
469
|
+
child.on("message", async (message) => {
|
|
470
|
+
if (message?.type !== ASK_PARENT)
|
|
471
|
+
return;
|
|
472
|
+
const was = details.progress;
|
|
473
|
+
details.progress = "waiting for your OK";
|
|
474
|
+
onProgress();
|
|
475
|
+
const decision = await decide(ctx, message.toolName, message.input, message.cwd, `${kind} agent`).catch(() => ({
|
|
476
|
+
block: true,
|
|
477
|
+
reason: "Nobody could be asked for the user's OK. Don't work around it: say what you wanted to do in your report.",
|
|
478
|
+
}));
|
|
479
|
+
if (details.progress === "waiting for your OK")
|
|
480
|
+
details.progress = was;
|
|
481
|
+
onProgress();
|
|
482
|
+
if (child.connected)
|
|
483
|
+
child.send({ type: ASK_PARENT, id: message.id, decision });
|
|
484
|
+
});
|
|
220
485
|
child.stderr.setEncoding("utf8");
|
|
221
486
|
child.stderr.on("data", (chunk) => {
|
|
222
487
|
stderr = (stderr + chunk).slice(-2000);
|
|
@@ -225,22 +490,108 @@ function runAgent(cwd, kind, run, task, signal, onProgress) {
|
|
|
225
490
|
signal?.addEventListener("abort", stop, { once: true });
|
|
226
491
|
child.on("error", (e) => {
|
|
227
492
|
signal?.removeEventListener("abort", stop);
|
|
228
|
-
resolve({ output
|
|
493
|
+
resolve({ output: tracker.output, error: e.message });
|
|
229
494
|
});
|
|
230
495
|
child.on("close", (code) => {
|
|
231
496
|
signal?.removeEventListener("abort", stop);
|
|
232
497
|
if (buffer.trim())
|
|
233
498
|
onLine(buffer);
|
|
499
|
+
let error = tracker.error;
|
|
234
500
|
if (code !== 0 && !error && !signal?.aborted)
|
|
235
501
|
error = stderr.trim().split("\n").pop() || `exited with code ${code}`;
|
|
236
|
-
resolve({ output
|
|
502
|
+
resolve({ output: tracker.output, error });
|
|
237
503
|
});
|
|
238
504
|
});
|
|
239
505
|
}
|
|
506
|
+
let transcripts = 0;
|
|
507
|
+
/** A path for a new subagent's chat, after clearing out old ones. */
|
|
508
|
+
function newTranscript(kind) {
|
|
509
|
+
try {
|
|
510
|
+
mkdirSync(TRANSCRIPTS, { recursive: true });
|
|
511
|
+
const files = readdirSync(TRANSCRIPTS)
|
|
512
|
+
.filter((f) => f.endsWith(".jsonl"))
|
|
513
|
+
.map((f) => ({ path: join(TRANSCRIPTS, f), at: statSync(join(TRANSCRIPTS, f)).mtimeMs }))
|
|
514
|
+
.sort((a, b) => b.at - a.at);
|
|
515
|
+
const old = Date.now() - TRANSCRIPT_DAYS * 24 * 60 * 60 * 1000;
|
|
516
|
+
for (const [i, file] of files.entries())
|
|
517
|
+
if (i >= MAX_TRANSCRIPTS - 1 || file.at < old)
|
|
518
|
+
rmSync(file.path, { force: true });
|
|
519
|
+
}
|
|
520
|
+
catch { }
|
|
521
|
+
return join(TRANSCRIPTS, `${new Date().toISOString().replace(/[:.]/g, "-")}-${kind}-${process.pid}-${++transcripts}.jsonl`);
|
|
522
|
+
}
|
|
523
|
+
/** What a tool call is doing, while it runs: "reading src/app.ts", "$ npm test". */
|
|
240
524
|
function activity(toolName, args) {
|
|
241
525
|
const a = args ?? {};
|
|
242
|
-
|
|
243
|
-
|
|
526
|
+
switch (toolName) {
|
|
527
|
+
case "read":
|
|
528
|
+
return `reading ${target(a)}`;
|
|
529
|
+
case "edit":
|
|
530
|
+
return `editing ${target(a)}`;
|
|
531
|
+
case "write":
|
|
532
|
+
return `writing ${target(a)}`;
|
|
533
|
+
case "bash":
|
|
534
|
+
return `$ ${clip(firstLine(String(a.command ?? "")), 40)}`;
|
|
535
|
+
case "grep":
|
|
536
|
+
case "find":
|
|
537
|
+
return `looking for ${clip(String(a.pattern ?? ""), 32)}`;
|
|
538
|
+
case "ls":
|
|
539
|
+
return `listing ${target(a)}`;
|
|
540
|
+
case "web_search":
|
|
541
|
+
return `searching the web for ${clip(String(a.query ?? ""), 36)}`;
|
|
542
|
+
case "web_fetch":
|
|
543
|
+
return `fetching ${clip(String(a.url ?? "").replace(/^https?:\/\//, ""), 40)}`;
|
|
544
|
+
default:
|
|
545
|
+
return `using ${toolName}`;
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
/** A finished tool call, as a step: "Read src/app.ts", "Bash npm test". */
|
|
549
|
+
function stepText(toolName, args) {
|
|
550
|
+
const a = args ?? {};
|
|
551
|
+
const name = STEP_NAMES[toolName] ?? toolName;
|
|
552
|
+
switch (toolName) {
|
|
553
|
+
case "read":
|
|
554
|
+
case "edit":
|
|
555
|
+
case "write":
|
|
556
|
+
case "ls":
|
|
557
|
+
return `${name} ${target(a)}`;
|
|
558
|
+
case "bash":
|
|
559
|
+
return `${name} ${clip(firstLine(String(a.command ?? "")), 48)}`;
|
|
560
|
+
case "grep":
|
|
561
|
+
case "find":
|
|
562
|
+
return `${name} ${clip(String(a.pattern ?? ""), 40)}`;
|
|
563
|
+
case "web_search":
|
|
564
|
+
return `${name} ${clip(String(a.query ?? ""), 44)}`;
|
|
565
|
+
case "web_fetch":
|
|
566
|
+
return `${name} ${clip(String(a.url ?? "").replace(/^https?:\/\//, ""), 48)}`;
|
|
567
|
+
default:
|
|
568
|
+
return name;
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
const STEP_NAMES = {
|
|
572
|
+
read: "Read",
|
|
573
|
+
edit: "Updated",
|
|
574
|
+
write: "Wrote",
|
|
575
|
+
bash: "Ran",
|
|
576
|
+
grep: "Searched",
|
|
577
|
+
find: "Found",
|
|
578
|
+
ls: "Listed",
|
|
579
|
+
web_search: "Searched the web for",
|
|
580
|
+
web_fetch: "Fetched",
|
|
581
|
+
};
|
|
582
|
+
function target(a) {
|
|
583
|
+
const path = [a.path, a.file_path].find((v) => typeof v === "string");
|
|
584
|
+
return path ? clip(shortPath(path), 40) : ".";
|
|
585
|
+
}
|
|
586
|
+
function formatElapsed(ms) {
|
|
587
|
+
const s = Math.max(0, Math.floor(ms / 1000));
|
|
588
|
+
return s < 60 ? `${s}s` : `${Math.floor(s / 60)}m ${String(s % 60).padStart(2, "0")}s`;
|
|
589
|
+
}
|
|
590
|
+
export function formatTokens(n) {
|
|
591
|
+
return n < 1000 ? String(n) : `${(n / 1000).toFixed(1).replace(/\.0$/, "")}k`;
|
|
592
|
+
}
|
|
593
|
+
function plural(n, word) {
|
|
594
|
+
return `${n} ${word}${n === 1 ? "" : "s"}`;
|
|
244
595
|
}
|
|
245
596
|
function clip(text, max) {
|
|
246
597
|
return text.length > max ? `${text.slice(0, max - 1)}…` : text;
|