@wheatley-ai/cli 0.1.1 → 0.2.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/dist/cli/chat-state.js +95 -0
- package/dist/cli/chat.js +32 -95
- package/dist/cli/io.js +22 -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/node_modules/@wheatley-ai/sdk/package.json +1 -1
- package/package.json +8 -2
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
export const EMPTY_DRAFT = { cursor: 0, text: "" };
|
|
2
|
+
export const draftOf = (text) => ({ cursor: text.length, text });
|
|
3
|
+
export const insert = (draft, value) => ({
|
|
4
|
+
cursor: draft.cursor + value.length,
|
|
5
|
+
text: `${draft.text.slice(0, draft.cursor)}${value}${draft.text.slice(draft.cursor)}`,
|
|
6
|
+
});
|
|
7
|
+
export const deleteBackward = (draft) => draft.cursor === 0
|
|
8
|
+
? draft
|
|
9
|
+
: {
|
|
10
|
+
cursor: draft.cursor - 1,
|
|
11
|
+
text: `${draft.text.slice(0, draft.cursor - 1)}${draft.text.slice(draft.cursor)}`,
|
|
12
|
+
};
|
|
13
|
+
export const deleteForward = (draft) => ({
|
|
14
|
+
cursor: draft.cursor,
|
|
15
|
+
text: `${draft.text.slice(0, draft.cursor)}${draft.text.slice(draft.cursor + 1)}`,
|
|
16
|
+
});
|
|
17
|
+
export const moveLeft = (draft) => ({
|
|
18
|
+
...draft,
|
|
19
|
+
cursor: Math.max(0, draft.cursor - 1),
|
|
20
|
+
});
|
|
21
|
+
export const moveRight = (draft) => ({
|
|
22
|
+
...draft,
|
|
23
|
+
cursor: Math.min(draft.text.length, draft.cursor + 1),
|
|
24
|
+
});
|
|
25
|
+
const lineStart = (draft) => draft.text.lastIndexOf("\n", draft.cursor - 1) + 1;
|
|
26
|
+
const lineEnd = (draft) => {
|
|
27
|
+
const end = draft.text.indexOf("\n", draft.cursor);
|
|
28
|
+
return end === -1 ? draft.text.length : end;
|
|
29
|
+
};
|
|
30
|
+
export const moveHome = (draft) => ({
|
|
31
|
+
...draft,
|
|
32
|
+
cursor: lineStart(draft),
|
|
33
|
+
});
|
|
34
|
+
export const moveEnd = (draft) => ({
|
|
35
|
+
...draft,
|
|
36
|
+
cursor: lineEnd(draft),
|
|
37
|
+
});
|
|
38
|
+
const WORD_CHARACTER = /\w/u;
|
|
39
|
+
const isWordCharacter = (character) => character !== undefined && WORD_CHARACTER.test(character);
|
|
40
|
+
/** The index of the start of the word before the cursor. Skips spaces and punctuation before the word first. */
|
|
41
|
+
const previousWordStart = (draft) => {
|
|
42
|
+
let index = draft.cursor;
|
|
43
|
+
while (index > 0 && !isWordCharacter(draft.text[index - 1])) {
|
|
44
|
+
index -= 1;
|
|
45
|
+
}
|
|
46
|
+
while (index > 0 && isWordCharacter(draft.text[index - 1])) {
|
|
47
|
+
index -= 1;
|
|
48
|
+
}
|
|
49
|
+
return index;
|
|
50
|
+
};
|
|
51
|
+
const nextWordEnd = (draft) => {
|
|
52
|
+
let index = draft.cursor;
|
|
53
|
+
while (index < draft.text.length && !isWordCharacter(draft.text[index])) {
|
|
54
|
+
index += 1;
|
|
55
|
+
}
|
|
56
|
+
while (index < draft.text.length && isWordCharacter(draft.text[index])) {
|
|
57
|
+
index += 1;
|
|
58
|
+
}
|
|
59
|
+
return index;
|
|
60
|
+
};
|
|
61
|
+
export const moveWordLeft = (draft) => ({
|
|
62
|
+
...draft,
|
|
63
|
+
cursor: previousWordStart(draft),
|
|
64
|
+
});
|
|
65
|
+
export const moveWordRight = (draft) => ({
|
|
66
|
+
...draft,
|
|
67
|
+
cursor: nextWordEnd(draft),
|
|
68
|
+
});
|
|
69
|
+
/** Ctrl+W: deletes the word before the cursor. */
|
|
70
|
+
export const deleteWordBackward = (draft) => {
|
|
71
|
+
const start = previousWordStart(draft);
|
|
72
|
+
return {
|
|
73
|
+
cursor: start,
|
|
74
|
+
text: `${draft.text.slice(0, start)}${draft.text.slice(draft.cursor)}`,
|
|
75
|
+
};
|
|
76
|
+
};
|
|
77
|
+
/** Ctrl+U: deletes from the start of the current line to the cursor. */
|
|
78
|
+
export const deleteToLineStart = (draft) => {
|
|
79
|
+
const start = lineStart(draft);
|
|
80
|
+
return {
|
|
81
|
+
cursor: start,
|
|
82
|
+
text: `${draft.text.slice(0, start)}${draft.text.slice(draft.cursor)}`,
|
|
83
|
+
};
|
|
84
|
+
};
|
|
85
|
+
/** Ctrl+K: deletes from the cursor to the end of the current line. */
|
|
86
|
+
export const deleteToLineEnd = (draft) => ({
|
|
87
|
+
cursor: draft.cursor,
|
|
88
|
+
text: `${draft.text.slice(0, draft.cursor)}${draft.text.slice(lineEnd(draft))}`,
|
|
89
|
+
});
|
|
90
|
+
/** True if the cursor is on the first line of the draft. Up then recalls history instead of moving between lines. */
|
|
91
|
+
export const onFirstLine = (draft) => !draft.text.slice(0, draft.cursor).includes("\n");
|
|
92
|
+
/** True if the cursor is on the last line of the draft. */
|
|
93
|
+
export const onLastLine = (draft) => !draft.text.slice(draft.cursor).includes("\n");
|
|
94
|
+
/** Moves the cursor one line up or down, and keeps its column where the line is long enough. */
|
|
95
|
+
export const moveVertical = (draft, step) => {
|
|
96
|
+
const start = lineStart(draft);
|
|
97
|
+
const column = draft.cursor - start;
|
|
98
|
+
if (step === -1) {
|
|
99
|
+
const previousEnd = start - 1;
|
|
100
|
+
const previousStart = draft.text.lastIndexOf("\n", previousEnd - 1) + 1;
|
|
101
|
+
return {
|
|
102
|
+
...draft,
|
|
103
|
+
cursor: Math.min(previousStart + column, previousEnd),
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
const end = lineEnd(draft);
|
|
107
|
+
const nextStart = end + 1;
|
|
108
|
+
const nextEnd = lineEnd({ ...draft, cursor: nextStart });
|
|
109
|
+
return { ...draft, cursor: Math.min(nextStart + column, nextEnd) };
|
|
110
|
+
};
|
|
111
|
+
export const HISTORY_START = { index: -1, saved: EMPTY_DRAFT };
|
|
112
|
+
/** Moves one step back (older) or forward (newer) in `history`. Returns `undefined` at either end. */
|
|
113
|
+
export const stepHistory = (history, cursor, current, step) => {
|
|
114
|
+
// Step 1 is older. The newest entry is at index 0.
|
|
115
|
+
const index = cursor.index + step;
|
|
116
|
+
if (index < -1 || index >= history.length) {
|
|
117
|
+
return undefined;
|
|
118
|
+
}
|
|
119
|
+
const saved = cursor.index === -1 ? current : cursor.saved;
|
|
120
|
+
const entry = history[index];
|
|
121
|
+
return {
|
|
122
|
+
cursor: { index, saved },
|
|
123
|
+
draft: index === -1 || entry === undefined ? saved : draftOf(entry),
|
|
124
|
+
};
|
|
125
|
+
};
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
const THOUSAND = 1000;
|
|
2
|
+
const MILLION = 1_000_000;
|
|
3
|
+
const SECONDS_PER_MINUTE = 60;
|
|
4
|
+
const SECONDS_PER_HOUR = 3600;
|
|
5
|
+
const SHORT_SECONDS = 10;
|
|
6
|
+
const CENT = 0.01;
|
|
7
|
+
/** A token count for the status bar, for example `842`, `12.3k`, or `1.2M`. */
|
|
8
|
+
export const formatCount = (count) => {
|
|
9
|
+
if (count >= MILLION) {
|
|
10
|
+
return `${(count / MILLION).toFixed(1)}M`;
|
|
11
|
+
}
|
|
12
|
+
return count >= THOUSAND ? `${(count / THOUSAND).toFixed(1)}k` : `${count}`;
|
|
13
|
+
};
|
|
14
|
+
/** A cost in US dollars, with more digits below one cent. */
|
|
15
|
+
export const formatCost = (usd) => usd > 0 && usd < CENT ? `$${usd.toFixed(4)}` : `$${usd.toFixed(2)}`;
|
|
16
|
+
/** A duration, for example `0.4s`, `12s`, `3m 05s`, or `1h 02m`. */
|
|
17
|
+
export const formatSeconds = (seconds) => {
|
|
18
|
+
if (seconds < SHORT_SECONDS) {
|
|
19
|
+
return `${seconds.toFixed(1)}s`;
|
|
20
|
+
}
|
|
21
|
+
const whole = Math.round(seconds);
|
|
22
|
+
if (whole < SECONDS_PER_MINUTE) {
|
|
23
|
+
return `${whole}s`;
|
|
24
|
+
}
|
|
25
|
+
if (whole < SECONDS_PER_HOUR) {
|
|
26
|
+
const minutes = Math.floor(whole / SECONDS_PER_MINUTE);
|
|
27
|
+
return `${minutes}m ${String(whole % SECONDS_PER_MINUTE).padStart(2, "0")}s`;
|
|
28
|
+
}
|
|
29
|
+
const hours = Math.floor(whole / SECONDS_PER_HOUR);
|
|
30
|
+
const minutes = Math.floor((whole % SECONDS_PER_HOUR) / SECONDS_PER_MINUTE);
|
|
31
|
+
return `${hours}h ${String(minutes).padStart(2, "0")}m`;
|
|
32
|
+
};
|