@wheatley-ai/cli 0.1.1 → 0.3.0
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 +37 -3
- package/dist/cli/chat-state.js +95 -0
- package/dist/cli/chat.js +32 -95
- package/dist/cli/io.js +22 -2
- package/dist/cli/main.js +8 -2
- package/dist/cli/personality.js +81 -0
- package/dist/cli/tui/app.js +159 -0
- package/dist/cli/tui/commands.js +98 -0
- package/dist/cli/tui/controller.js +504 -0
- package/dist/cli/tui/editor.js +125 -0
- package/dist/cli/tui/format.js +32 -0
- package/dist/cli/tui/markdown.js +147 -0
- package/dist/cli/tui/prompt.js +275 -0
- package/dist/cli/tui/run.js +63 -0
- package/dist/cli/tui/transcript.js +89 -0
- package/dist/dashboard/assets/{index-DXzGGAxQ.js → index-DThc2x_d.js} +2 -2
- package/dist/dashboard/assets/{sheet-presentation-DMljN0LW.js → sheet-presentation-CkgiDsTg.js} +1 -1
- package/dist/dashboard/index.html +1 -1
- package/dist/node_modules/@wheatley-ai/sdk/package.json +1 -1
- package/dist/ops/cli.js +41 -22
- package/dist/ops/command-runner.js +1 -0
- package/dist/ops/install-method.js +189 -0
- package/dist/ops/registry.js +35 -0
- package/dist/ops/update.js +95 -61
- package/package.json +8 -2
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { BUILTIN_COMMANDS } from "@wheatley-ai/sdk";
|
|
2
|
+
/** The commands that the terminal runs without the Agent. */
|
|
3
|
+
export const LOCAL_COMMANDS = {
|
|
4
|
+
copy: "/copy",
|
|
5
|
+
exit: "/exit",
|
|
6
|
+
help: "/help",
|
|
7
|
+
quit: "/quit",
|
|
8
|
+
};
|
|
9
|
+
export const CHAT_COMMANDS = [
|
|
10
|
+
...BUILTIN_COMMANDS.map((command) => ({
|
|
11
|
+
argument: "argument" in command ? command.argument : undefined,
|
|
12
|
+
description: command.description,
|
|
13
|
+
local: false,
|
|
14
|
+
word: `/${command.name}`,
|
|
15
|
+
})),
|
|
16
|
+
{
|
|
17
|
+
description: "Copy the last reply to the clipboard",
|
|
18
|
+
local: true,
|
|
19
|
+
word: LOCAL_COMMANDS.copy,
|
|
20
|
+
},
|
|
21
|
+
{
|
|
22
|
+
description: "List the commands and keys",
|
|
23
|
+
local: true,
|
|
24
|
+
word: LOCAL_COMMANDS.help,
|
|
25
|
+
},
|
|
26
|
+
{ description: "End the chat", local: true, word: LOCAL_COMMANDS.exit },
|
|
27
|
+
];
|
|
28
|
+
/** The command name and its argument hint, for example `/model <model-id>`. */
|
|
29
|
+
export const commandLabel = (command) => command.argument === undefined
|
|
30
|
+
? command.word
|
|
31
|
+
: `${command.word} ${command.argument}`;
|
|
32
|
+
const COMMAND_NAME = /^\/[a-z-]*$/u;
|
|
33
|
+
const WORD_SPLIT = /\s+/u;
|
|
34
|
+
const RANK = {
|
|
35
|
+
descriptionPrefix: 3,
|
|
36
|
+
descriptionWord: 4,
|
|
37
|
+
namePrefix: 0,
|
|
38
|
+
nameSubstring: 1,
|
|
39
|
+
};
|
|
40
|
+
const rankOf = (command, query) => {
|
|
41
|
+
const name = command.word.slice(1);
|
|
42
|
+
if (name.startsWith(query)) {
|
|
43
|
+
return RANK.namePrefix;
|
|
44
|
+
}
|
|
45
|
+
if (name.includes(query)) {
|
|
46
|
+
return RANK.nameSubstring;
|
|
47
|
+
}
|
|
48
|
+
const words = command.description.toLowerCase().split(WORD_SPLIT);
|
|
49
|
+
if (words.some((word) => word.startsWith(query))) {
|
|
50
|
+
return words[0]?.startsWith(query) === true
|
|
51
|
+
? RANK.descriptionPrefix
|
|
52
|
+
: RANK.descriptionWord;
|
|
53
|
+
}
|
|
54
|
+
return undefined;
|
|
55
|
+
};
|
|
56
|
+
/**
|
|
57
|
+
* The commands for the menu while `line` is a command name without arguments, best first: a name that starts with the
|
|
58
|
+
* query, then a name that contains it, then a description word that starts with it. Returns no commands otherwise.
|
|
59
|
+
*/
|
|
60
|
+
export const matchCommands = (line) => {
|
|
61
|
+
if (!COMMAND_NAME.test(line)) {
|
|
62
|
+
return [];
|
|
63
|
+
}
|
|
64
|
+
const query = line.slice(1);
|
|
65
|
+
return CHAT_COMMANDS.flatMap((command, index) => {
|
|
66
|
+
const rank = rankOf(command, query);
|
|
67
|
+
return rank === undefined ? [] : [{ command, index, rank }];
|
|
68
|
+
})
|
|
69
|
+
.toSorted((a, b) => a.rank - b.rank || a.index - b.index)
|
|
70
|
+
.map(({ command }) => command);
|
|
71
|
+
};
|
|
72
|
+
const editDistance = (a, b) => {
|
|
73
|
+
let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
|
|
74
|
+
// Command words are ASCII, so code units are characters here.
|
|
75
|
+
for (let i = 0; i < a.length; i += 1) {
|
|
76
|
+
const current = [i + 1];
|
|
77
|
+
for (let j = 0; j < b.length; j += 1) {
|
|
78
|
+
current.push(Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (a[i] === b[j] ? 0 : 1)));
|
|
79
|
+
}
|
|
80
|
+
previous = current;
|
|
81
|
+
}
|
|
82
|
+
return previous[b.length] ?? 0;
|
|
83
|
+
};
|
|
84
|
+
const MAX_SUGGESTION_DISTANCE = 2;
|
|
85
|
+
/** The known command closest to an unknown `word`, if one is at most two edits away. */
|
|
86
|
+
export const suggestCommand = (word) => {
|
|
87
|
+
const scored = CHAT_COMMANDS.map((command) => ({
|
|
88
|
+
distance: editDistance(word, command.word),
|
|
89
|
+
word: command.word,
|
|
90
|
+
})).toSorted((a, b) => a.distance - b.distance);
|
|
91
|
+
const [best] = scored;
|
|
92
|
+
return best !== undefined && best.distance <= MAX_SUGGESTION_DISTANCE
|
|
93
|
+
? best.word
|
|
94
|
+
: undefined;
|
|
95
|
+
};
|
|
96
|
+
const COMMAND_LINE = /^\/[a-z][a-z-]*(?:\s|$)/u;
|
|
97
|
+
/** True if `line` looks like a slash command, for example `/stop` or `/model x`, and not like a path such as `/etc/x`. */
|
|
98
|
+
export const isCommandLine = (line) => COMMAND_LINE.test(line);
|
|
@@ -0,0 +1,504 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { parseCommandText } from "@wheatley-ai/sdk";
|
|
3
|
+
import { errorMessage } from "../../core/error-message.js";
|
|
4
|
+
import { ChatState, isCliChatRun, track } from "../chat-state.js";
|
|
5
|
+
import { shuffledThinkingLines } from "../personality.js";
|
|
6
|
+
import { LOCAL_COMMANDS, isCommandLine, matchCommands, suggestCommand, } from "./commands.js";
|
|
7
|
+
import { createMarkdownRenderer, renderMarkdown } from "./markdown.js";
|
|
8
|
+
const MS_PER_SECOND = 1000;
|
|
9
|
+
/** A Run that takes at least this long rings the bell when it ends. */
|
|
10
|
+
const NOTIFY_AFTER_MS = 10_000;
|
|
11
|
+
const SHELL_PREFIX = "!";
|
|
12
|
+
const BELL = "\u0007";
|
|
13
|
+
const OSC = "\u001B]";
|
|
14
|
+
const notification = (text) => `${OSC}9;${text}${BELL}${BELL}`;
|
|
15
|
+
const ofRunEvent = (event, runs) => {
|
|
16
|
+
if (event.name === "run.delta" ||
|
|
17
|
+
event.name === "run.toolStarted" ||
|
|
18
|
+
event.name === "run.toolFinished") {
|
|
19
|
+
return runs.has(event.payload.runId) ? event.payload.runId : undefined;
|
|
20
|
+
}
|
|
21
|
+
return undefined;
|
|
22
|
+
};
|
|
23
|
+
/** Drives one interactive chat: daemon events in, transcript and live view out. */
|
|
24
|
+
export class ChatController {
|
|
25
|
+
#options;
|
|
26
|
+
#state = new ChatState();
|
|
27
|
+
#listeners = new Set();
|
|
28
|
+
#runs = new Set();
|
|
29
|
+
/** IDs of messages that this chat sent, until the daemon echoes them. */
|
|
30
|
+
#sent = new Set();
|
|
31
|
+
/** Texts of `chat.send` requests without a response. Their echo can arrive before the response. */
|
|
32
|
+
#inFlight = [];
|
|
33
|
+
/** IDs of own messages whose echo arrived before the `chat.send` response. */
|
|
34
|
+
#echoedEarly = new Set();
|
|
35
|
+
#toolStarts = new Map();
|
|
36
|
+
/** Runs whose final reply arrived. Their late deltas are already part of the shown reply. */
|
|
37
|
+
#replyDone = new Set();
|
|
38
|
+
#now;
|
|
39
|
+
#view;
|
|
40
|
+
#nextId = 0;
|
|
41
|
+
#buffer = "";
|
|
42
|
+
#streamed = "";
|
|
43
|
+
#renderLine = createMarkdownRenderer();
|
|
44
|
+
#replyStarted = false;
|
|
45
|
+
#runStartedAt;
|
|
46
|
+
#tools = 0;
|
|
47
|
+
#lastReply = "";
|
|
48
|
+
#shell;
|
|
49
|
+
constructor(options) {
|
|
50
|
+
this.#options = options;
|
|
51
|
+
this.#now = options.now ?? Date.now;
|
|
52
|
+
this.#view = {
|
|
53
|
+
activity: undefined,
|
|
54
|
+
agent: options.agent,
|
|
55
|
+
approval: undefined,
|
|
56
|
+
entries: [{ id: this.#id(), kind: "banner" }],
|
|
57
|
+
extensions: undefined,
|
|
58
|
+
live: [],
|
|
59
|
+
model: undefined,
|
|
60
|
+
thinkingLines: shuffledThinkingLines(),
|
|
61
|
+
usage: { costUsd: 0, inputTokens: 0, outputTokens: 0, runs: 0 },
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
/** The current view. React reads it through `useSyncExternalStore`. */
|
|
65
|
+
view = () => this.#view;
|
|
66
|
+
subscribe = (listener) => {
|
|
67
|
+
this.#listeners.add(listener);
|
|
68
|
+
return () => {
|
|
69
|
+
this.#listeners.delete(listener);
|
|
70
|
+
};
|
|
71
|
+
};
|
|
72
|
+
/** True while a Run of this chat or a shell command works. */
|
|
73
|
+
get busy() {
|
|
74
|
+
return this.#state.busy || this.#shell !== undefined;
|
|
75
|
+
}
|
|
76
|
+
/** Resolves when no Run of this chat is active. */
|
|
77
|
+
get idle() {
|
|
78
|
+
return this.#state.idle;
|
|
79
|
+
}
|
|
80
|
+
/** Subscribes to the daemon events and loads the model and extension counts for the banner. */
|
|
81
|
+
start = async () => {
|
|
82
|
+
const { agent, client } = this.#options;
|
|
83
|
+
client.onEvent((event) => {
|
|
84
|
+
this.#onEvent(event);
|
|
85
|
+
});
|
|
86
|
+
await client.request("events.subscribe", {
|
|
87
|
+
agents: [agent],
|
|
88
|
+
topics: ["chat", "run", "approval"],
|
|
89
|
+
});
|
|
90
|
+
try {
|
|
91
|
+
const { config } = await client.request("config.get", {});
|
|
92
|
+
const model = config.agents[agent]?.model;
|
|
93
|
+
if (model !== undefined) {
|
|
94
|
+
this.#update({ model: `${model.provider}/${model.id}` });
|
|
95
|
+
}
|
|
96
|
+
const extensions = await client.request("extensions.list", { agent });
|
|
97
|
+
this.#update({
|
|
98
|
+
extensions: `${extensions.skills.length} skills · ${extensions.plugins.length} plugins · ${extensions.mcpServers.length} MCP servers`,
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
catch {
|
|
102
|
+
// The banner works without these details.
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
/**
|
|
106
|
+
* Handles one submitted line. Returns `"exit"` if the chat must end.
|
|
107
|
+
*
|
|
108
|
+
* Errors: never rejects. A failed request becomes an error entry.
|
|
109
|
+
*/
|
|
110
|
+
submit = async (raw) => {
|
|
111
|
+
const line = raw.trim();
|
|
112
|
+
if (line === "") {
|
|
113
|
+
return undefined;
|
|
114
|
+
}
|
|
115
|
+
if (line === LOCAL_COMMANDS.exit || line === LOCAL_COMMANDS.quit) {
|
|
116
|
+
return "exit";
|
|
117
|
+
}
|
|
118
|
+
this.#append({ kind: "user", text: line });
|
|
119
|
+
try {
|
|
120
|
+
await this.#dispatch(line);
|
|
121
|
+
}
|
|
122
|
+
catch (error) {
|
|
123
|
+
this.#append({
|
|
124
|
+
kind: "notice",
|
|
125
|
+
text: `✗ ${errorMessage(error)}`,
|
|
126
|
+
tone: "error",
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
return undefined;
|
|
130
|
+
};
|
|
131
|
+
/** Answers the open Approval. */
|
|
132
|
+
decide = async (decision, reason) => {
|
|
133
|
+
const { approval } = this.#view;
|
|
134
|
+
if (approval === undefined) {
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
this.#state.removeApproval(approval.approvalId);
|
|
138
|
+
this.#refreshStatus();
|
|
139
|
+
try {
|
|
140
|
+
const { accepted } = await this.#options.client.request("approvals.decide", {
|
|
141
|
+
agent: this.#options.agent,
|
|
142
|
+
approvalId: approval.approvalId,
|
|
143
|
+
resolution: { decision, reason, resolvedBy: "cli" },
|
|
144
|
+
});
|
|
145
|
+
if (!accepted) {
|
|
146
|
+
this.#append({
|
|
147
|
+
kind: "notice",
|
|
148
|
+
text: "The Approval already ended.",
|
|
149
|
+
tone: "dim",
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
catch (error) {
|
|
154
|
+
this.#append({
|
|
155
|
+
kind: "notice",
|
|
156
|
+
text: `✗ Cannot decide the Approval: ${errorMessage(error)}`,
|
|
157
|
+
tone: "error",
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
};
|
|
161
|
+
/** Stops the shell command or the active Run. Returns false if nothing was running. */
|
|
162
|
+
interrupt = () => {
|
|
163
|
+
if (this.#shell !== undefined) {
|
|
164
|
+
this.#shell.kill("SIGINT");
|
|
165
|
+
return true;
|
|
166
|
+
}
|
|
167
|
+
if (!this.#state.busy) {
|
|
168
|
+
return false;
|
|
169
|
+
}
|
|
170
|
+
this.#append({ kind: "notice", text: "Stopping the Run…", tone: "dim" });
|
|
171
|
+
this.#options.client
|
|
172
|
+
.request("chat.command", { agent: this.#options.agent, name: "stop" })
|
|
173
|
+
.catch(() => {
|
|
174
|
+
// The Run can end before the request arrives.
|
|
175
|
+
});
|
|
176
|
+
return true;
|
|
177
|
+
};
|
|
178
|
+
#dispatch = async (line) => {
|
|
179
|
+
if (line.startsWith(SHELL_PREFIX)) {
|
|
180
|
+
this.#runShell(line.slice(SHELL_PREFIX.length).trim());
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
if (line === LOCAL_COMMANDS.help) {
|
|
184
|
+
this.#append({ kind: "help" });
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
if (line === LOCAL_COMMANDS.copy) {
|
|
188
|
+
this.#copyLastReply();
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
const command = parseCommandText(line);
|
|
192
|
+
if (command !== undefined) {
|
|
193
|
+
await this.#options.client.request("chat.command", {
|
|
194
|
+
agent: this.#options.agent,
|
|
195
|
+
args: command.args,
|
|
196
|
+
name: command.name,
|
|
197
|
+
});
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
if (isCommandLine(line)) {
|
|
201
|
+
const [word = line] = line.split(" ");
|
|
202
|
+
const suggestion = suggestCommand(word) ?? matchCommands(word)[0]?.word;
|
|
203
|
+
this.#append({
|
|
204
|
+
kind: "notice",
|
|
205
|
+
text: suggestion === undefined
|
|
206
|
+
? `Unknown command ${word}. Nothing was sent. Type /help for the commands.`
|
|
207
|
+
: `Unknown command ${word}. Nothing was sent. Did you mean ${suggestion}?`,
|
|
208
|
+
tone: "warning",
|
|
209
|
+
});
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
this.#inFlight.push(line);
|
|
213
|
+
const { messageId } = await this.#options.client
|
|
214
|
+
.request("chat.send", { agent: this.#options.agent, text: line })
|
|
215
|
+
.finally(() => {
|
|
216
|
+
const index = this.#inFlight.indexOf(line);
|
|
217
|
+
if (index !== -1) {
|
|
218
|
+
this.#inFlight.splice(index, 1);
|
|
219
|
+
}
|
|
220
|
+
});
|
|
221
|
+
if (!this.#echoedEarly.delete(messageId)) {
|
|
222
|
+
this.#sent.add(messageId);
|
|
223
|
+
}
|
|
224
|
+
this.#state.sent(messageId);
|
|
225
|
+
this.#refreshStatus();
|
|
226
|
+
};
|
|
227
|
+
#runShell = (command) => {
|
|
228
|
+
if (command === "") {
|
|
229
|
+
this.#append({
|
|
230
|
+
kind: "notice",
|
|
231
|
+
text: "Type a command after !, for example !ls.",
|
|
232
|
+
tone: "dim",
|
|
233
|
+
});
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
236
|
+
if (this.#shell !== undefined) {
|
|
237
|
+
this.#append({
|
|
238
|
+
kind: "notice",
|
|
239
|
+
text: "A shell command is already running.",
|
|
240
|
+
tone: "warning",
|
|
241
|
+
});
|
|
242
|
+
return;
|
|
243
|
+
}
|
|
244
|
+
const startedAt = this.#now();
|
|
245
|
+
const child = spawn(process.env.SHELL ?? "/bin/sh", ["-c", command], {
|
|
246
|
+
cwd: process.cwd(),
|
|
247
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
248
|
+
});
|
|
249
|
+
this.#shell = child;
|
|
250
|
+
this.#update({ activity: { command, kind: "shell", startedAt } });
|
|
251
|
+
let pending = "";
|
|
252
|
+
const onData = (chunk) => {
|
|
253
|
+
pending += chunk.toString("utf-8");
|
|
254
|
+
const end = pending.lastIndexOf("\n");
|
|
255
|
+
if (end !== -1) {
|
|
256
|
+
this.#append({ kind: "shell", text: pending.slice(0, end) });
|
|
257
|
+
pending = pending.slice(end + 1);
|
|
258
|
+
}
|
|
259
|
+
};
|
|
260
|
+
child.stdout?.on("data", onData);
|
|
261
|
+
child.stderr?.on("data", onData);
|
|
262
|
+
child.on("error", (error) => {
|
|
263
|
+
this.#append({
|
|
264
|
+
kind: "notice",
|
|
265
|
+
text: `✗ ${error.message}`,
|
|
266
|
+
tone: "error",
|
|
267
|
+
});
|
|
268
|
+
});
|
|
269
|
+
child.on("close", (code, signal) => {
|
|
270
|
+
if (pending !== "") {
|
|
271
|
+
this.#append({ kind: "shell", text: pending });
|
|
272
|
+
}
|
|
273
|
+
this.#shell = undefined;
|
|
274
|
+
const seconds = ((this.#now() - startedAt) / MS_PER_SECOND).toFixed(1);
|
|
275
|
+
const status = signal === null ? `exit ${code ?? 0}` : `stopped by ${signal}`;
|
|
276
|
+
this.#append({
|
|
277
|
+
kind: "notice",
|
|
278
|
+
text: `${status} · ${seconds}s`,
|
|
279
|
+
tone: code === 0 ? "dim" : "warning",
|
|
280
|
+
});
|
|
281
|
+
this.#refreshStatus();
|
|
282
|
+
});
|
|
283
|
+
};
|
|
284
|
+
#copyLastReply = () => {
|
|
285
|
+
if (this.#lastReply === "") {
|
|
286
|
+
this.#append({
|
|
287
|
+
kind: "notice",
|
|
288
|
+
text: "There is no reply to copy yet.",
|
|
289
|
+
tone: "dim",
|
|
290
|
+
});
|
|
291
|
+
return;
|
|
292
|
+
}
|
|
293
|
+
// OSC 52 asks the terminal to set the clipboard. It also works over SSH.
|
|
294
|
+
this.#options.control(`${OSC}52;c;${Buffer.from(this.#lastReply).toString("base64")}${BELL}`);
|
|
295
|
+
this.#append({
|
|
296
|
+
kind: "notice",
|
|
297
|
+
text: "Copied the last reply.",
|
|
298
|
+
tone: "dim",
|
|
299
|
+
});
|
|
300
|
+
};
|
|
301
|
+
#onEvent = (event) => {
|
|
302
|
+
track(this.#state, event);
|
|
303
|
+
if (isCliChatRun(event) && event.name === "run.started") {
|
|
304
|
+
this.#runs.add(event.payload.run.runId);
|
|
305
|
+
this.#runStartedAt = this.#now();
|
|
306
|
+
this.#tools = 0;
|
|
307
|
+
this.#update({ thinkingLines: shuffledThinkingLines() });
|
|
308
|
+
}
|
|
309
|
+
else if (isCliChatRun(event) && event.name === "run.finished") {
|
|
310
|
+
this.#finishRun(event.payload.run);
|
|
311
|
+
}
|
|
312
|
+
else if (ofRunEvent(event, this.#runs) !== undefined) {
|
|
313
|
+
this.#onRunEvent(event);
|
|
314
|
+
}
|
|
315
|
+
else if (event.name === "chat.message") {
|
|
316
|
+
this.#onMessage(event.payload.message);
|
|
317
|
+
}
|
|
318
|
+
else if (event.name === "approval.requested") {
|
|
319
|
+
this.#options.control(notification(`${event.payload.approval.toolName} needs approval`));
|
|
320
|
+
}
|
|
321
|
+
this.#refreshStatus();
|
|
322
|
+
};
|
|
323
|
+
#onRunEvent = (event) => {
|
|
324
|
+
if (event.name === "run.delta") {
|
|
325
|
+
if (!this.#replyDone.has(event.payload.runId)) {
|
|
326
|
+
this.#stream(event.payload.delta);
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
else if (event.name === "run.toolStarted") {
|
|
330
|
+
this.#endSegment();
|
|
331
|
+
this.#toolStarts.set(event.payload.toolCallId, this.#now());
|
|
332
|
+
this.#update({
|
|
333
|
+
activity: {
|
|
334
|
+
input: event.payload.inputPreview,
|
|
335
|
+
kind: "tool",
|
|
336
|
+
name: event.payload.toolName,
|
|
337
|
+
startedAt: this.#now(),
|
|
338
|
+
},
|
|
339
|
+
});
|
|
340
|
+
}
|
|
341
|
+
else if (event.name === "run.toolFinished") {
|
|
342
|
+
const startedAt = this.#toolStarts.get(event.payload.toolCallId) ?? this.#now();
|
|
343
|
+
this.#toolStarts.delete(event.payload.toolCallId);
|
|
344
|
+
this.#tools += 1;
|
|
345
|
+
const { activity } = this.#view;
|
|
346
|
+
this.#append({
|
|
347
|
+
input: activity?.kind === "tool" ? activity.input : "",
|
|
348
|
+
kind: "tool",
|
|
349
|
+
name: event.payload.toolName,
|
|
350
|
+
ok: !event.payload.isError,
|
|
351
|
+
output: event.payload.outputPreview,
|
|
352
|
+
seconds: (this.#now() - startedAt) / MS_PER_SECOND,
|
|
353
|
+
});
|
|
354
|
+
this.#update({
|
|
355
|
+
activity: {
|
|
356
|
+
kind: "thinking",
|
|
357
|
+
startedAt: this.#runStartedAt ?? this.#now(),
|
|
358
|
+
},
|
|
359
|
+
});
|
|
360
|
+
}
|
|
361
|
+
};
|
|
362
|
+
#onMessage = (message) => {
|
|
363
|
+
if (message.role === "user") {
|
|
364
|
+
// Messages that the dashboard sends to the same Chat show up here too.
|
|
365
|
+
if (this.#sent.delete(message.messageId)) {
|
|
366
|
+
return;
|
|
367
|
+
}
|
|
368
|
+
const inFlight = this.#inFlight.indexOf(message.text);
|
|
369
|
+
if (inFlight === -1) {
|
|
370
|
+
this.#append({ kind: "user", text: message.text });
|
|
371
|
+
}
|
|
372
|
+
else {
|
|
373
|
+
this.#inFlight.splice(inFlight, 1);
|
|
374
|
+
this.#echoedEarly.add(message.messageId);
|
|
375
|
+
}
|
|
376
|
+
return;
|
|
377
|
+
}
|
|
378
|
+
this.#lastReply = message.text;
|
|
379
|
+
const ownRun = message.runId !== undefined && this.#runs.has(message.runId)
|
|
380
|
+
? message.runId
|
|
381
|
+
: undefined;
|
|
382
|
+
if (ownRun !== undefined) {
|
|
383
|
+
// The final text can arrive before the last deltas. Print the part that the stream has not shown yet, and
|
|
384
|
+
// ignore the deltas that arrive after it.
|
|
385
|
+
this.#replyDone.add(ownRun);
|
|
386
|
+
if (this.#streamed !== "" && message.text.startsWith(this.#streamed)) {
|
|
387
|
+
this.#stream(message.text.slice(this.#streamed.length));
|
|
388
|
+
this.#endSegment();
|
|
389
|
+
return;
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
this.#endSegment();
|
|
393
|
+
this.#append({
|
|
394
|
+
first: true,
|
|
395
|
+
kind: "reply",
|
|
396
|
+
lines: renderMarkdown(message.text),
|
|
397
|
+
});
|
|
398
|
+
};
|
|
399
|
+
#stream = (delta) => {
|
|
400
|
+
this.#buffer += delta;
|
|
401
|
+
this.#streamed += delta;
|
|
402
|
+
const end = this.#buffer.lastIndexOf("\n");
|
|
403
|
+
if (end !== -1) {
|
|
404
|
+
const lines = this.#buffer.slice(0, end).split("\n");
|
|
405
|
+
this.#buffer = this.#buffer.slice(end + 1);
|
|
406
|
+
this.#appendReply(lines.map((line) => this.#renderLine(line)));
|
|
407
|
+
}
|
|
408
|
+
this.#update({ live: this.#buffer === "" ? [] : [this.#renderPreview()] });
|
|
409
|
+
};
|
|
410
|
+
/** Renders the unfinished line without changing the renderer's code-fence state. */
|
|
411
|
+
#renderPreview = () => {
|
|
412
|
+
const preview = createMarkdownRenderer();
|
|
413
|
+
return preview(this.#buffer);
|
|
414
|
+
};
|
|
415
|
+
#appendReply = (lines) => {
|
|
416
|
+
this.#append({ first: !this.#replyStarted, kind: "reply", lines });
|
|
417
|
+
this.#replyStarted = true;
|
|
418
|
+
};
|
|
419
|
+
/** Ends the current streamed text block, for example before a Tool call or at the end of a reply. */
|
|
420
|
+
#endSegment = () => {
|
|
421
|
+
if (this.#buffer !== "") {
|
|
422
|
+
this.#appendReply([this.#renderLine(this.#buffer)]);
|
|
423
|
+
}
|
|
424
|
+
this.#buffer = "";
|
|
425
|
+
this.#streamed = "";
|
|
426
|
+
this.#renderLine = createMarkdownRenderer();
|
|
427
|
+
this.#replyStarted = false;
|
|
428
|
+
this.#update({ live: [] });
|
|
429
|
+
};
|
|
430
|
+
#finishRun = (run) => {
|
|
431
|
+
this.#endSegment();
|
|
432
|
+
const startedAt = this.#runStartedAt ?? this.#now();
|
|
433
|
+
const elapsed = this.#now() - startedAt;
|
|
434
|
+
const { usage } = this.#view;
|
|
435
|
+
this.#runs.delete(run.runId);
|
|
436
|
+
this.#replyDone.delete(run.runId);
|
|
437
|
+
this.#runStartedAt = undefined;
|
|
438
|
+
if (run.status === "failed") {
|
|
439
|
+
this.#append({
|
|
440
|
+
kind: "notice",
|
|
441
|
+
text: `✗ The Run failed: ${run.error ?? "unknown error"}`,
|
|
442
|
+
tone: "error",
|
|
443
|
+
});
|
|
444
|
+
}
|
|
445
|
+
// One update, so a listener never sees the turn footer with a stale spinner or with the usage before it.
|
|
446
|
+
this.#update({
|
|
447
|
+
activity: this.#shell === undefined && !this.#state.busy
|
|
448
|
+
? undefined
|
|
449
|
+
: this.#view.activity,
|
|
450
|
+
entries: [
|
|
451
|
+
...this.#view.entries,
|
|
452
|
+
{
|
|
453
|
+
id: this.#id(),
|
|
454
|
+
kind: "turn",
|
|
455
|
+
seconds: elapsed / MS_PER_SECOND,
|
|
456
|
+
tools: this.#tools,
|
|
457
|
+
usage: run.usage,
|
|
458
|
+
},
|
|
459
|
+
],
|
|
460
|
+
model: run.model ?? this.#view.model,
|
|
461
|
+
usage: {
|
|
462
|
+
costUsd: usage.costUsd + (run.usage?.costUsd ?? 0),
|
|
463
|
+
inputTokens: usage.inputTokens + (run.usage?.inputTokens ?? 0),
|
|
464
|
+
outputTokens: usage.outputTokens + (run.usage?.outputTokens ?? 0),
|
|
465
|
+
runs: usage.runs + 1,
|
|
466
|
+
},
|
|
467
|
+
});
|
|
468
|
+
if (elapsed >= NOTIFY_AFTER_MS) {
|
|
469
|
+
this.#options.control(notification(`${this.#options.agent} finished`));
|
|
470
|
+
}
|
|
471
|
+
};
|
|
472
|
+
/** Keeps the open Approval and the activity in step with the chat state. */
|
|
473
|
+
#refreshStatus = () => {
|
|
474
|
+
const [approval] = this.#state.approvals;
|
|
475
|
+
let { activity } = this.#view;
|
|
476
|
+
if (this.#shell === undefined && !this.#state.busy) {
|
|
477
|
+
activity = undefined;
|
|
478
|
+
}
|
|
479
|
+
else if (this.#shell === undefined && activity === undefined) {
|
|
480
|
+
activity = {
|
|
481
|
+
kind: "thinking",
|
|
482
|
+
startedAt: this.#runStartedAt ?? this.#now(),
|
|
483
|
+
};
|
|
484
|
+
}
|
|
485
|
+
if (approval !== this.#view.approval || activity !== this.#view.activity) {
|
|
486
|
+
this.#update({ activity, approval });
|
|
487
|
+
}
|
|
488
|
+
};
|
|
489
|
+
#id = () => {
|
|
490
|
+
this.#nextId += 1;
|
|
491
|
+
return this.#nextId;
|
|
492
|
+
};
|
|
493
|
+
#append = (entry) => {
|
|
494
|
+
this.#update({
|
|
495
|
+
entries: [...this.#view.entries, { ...entry, id: this.#id() }],
|
|
496
|
+
});
|
|
497
|
+
};
|
|
498
|
+
#update = (changes) => {
|
|
499
|
+
this.#view = { ...this.#view, ...changes };
|
|
500
|
+
for (const listener of this.#listeners) {
|
|
501
|
+
listener();
|
|
502
|
+
}
|
|
503
|
+
};
|
|
504
|
+
}
|