stitchkit-tui 0.2.13 → 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 +88 -4
- package/dist/App.d.ts +2 -2
- package/dist/App.d.ts.map +1 -1
- package/dist/app-mqzzrp1t.js +618 -0
- package/dist/cli.js +11 -2195
- package/dist/config.d.ts +8 -16
- package/dist/config.d.ts.map +1 -1
- package/dist/core/chart.d.ts +82 -0
- package/dist/core/chart.d.ts.map +1 -0
- package/dist/core/collection.d.ts.map +1 -1
- package/dist/core/command-palette.d.ts.map +1 -1
- package/dist/core/focus.d.ts +33 -0
- package/dist/core/focus.d.ts.map +1 -0
- package/dist/core/form.d.ts +88 -0
- package/dist/core/form.d.ts.map +1 -0
- package/dist/core/index.d.ts +17 -0
- package/dist/core/index.d.ts.map +1 -1
- package/dist/core/index.js +226 -358
- package/dist/core/json.d.ts +24 -0
- package/dist/core/json.d.ts.map +1 -0
- package/dist/core/key-hints.d.ts +28 -0
- package/dist/core/key-hints.d.ts.map +1 -0
- package/dist/core/keys.d.ts +32 -0
- package/dist/core/keys.d.ts.map +1 -0
- package/dist/core/labels.d.ts +44 -0
- package/dist/core/labels.d.ts.map +1 -0
- package/dist/core/list.d.ts +112 -0
- package/dist/core/list.d.ts.map +1 -0
- package/dist/core/meter.d.ts +61 -0
- package/dist/core/meter.d.ts.map +1 -0
- package/dist/core/navigation.d.ts +33 -0
- package/dist/core/navigation.d.ts.map +1 -0
- package/dist/core/notices.d.ts +39 -0
- package/dist/core/notices.d.ts.map +1 -0
- package/dist/core/progress.d.ts +53 -0
- package/dist/core/progress.d.ts.map +1 -0
- package/dist/core/search.d.ts +36 -0
- package/dist/core/search.d.ts.map +1 -0
- package/dist/core/table.d.ts +126 -0
- package/dist/core/table.d.ts.map +1 -0
- package/dist/core/tabs.d.ts +37 -0
- package/dist/core/tabs.d.ts.map +1 -0
- package/dist/core/text.d.ts +36 -0
- package/dist/core/text.d.ts.map +1 -0
- package/dist/core/theme.d.ts +38 -0
- package/dist/core/theme.d.ts.map +1 -0
- package/dist/gallery/app.d.ts +12 -0
- package/dist/gallery/app.d.ts.map +1 -0
- package/dist/gallery/catalogue.d.ts +11 -0
- package/dist/gallery/catalogue.d.ts.map +1 -0
- package/dist/gallery/main.d.ts +3 -0
- package/dist/gallery/main.d.ts.map +1 -0
- package/dist/gallery/main.js +16 -0
- package/dist/gallery/monitor-page.d.ts +8 -0
- package/dist/gallery/monitor-page.d.ts.map +1 -0
- package/dist/gallery/widgets-page.d.ts +7 -0
- package/dist/gallery/widgets-page.d.ts.map +1 -0
- package/dist/index-251fexwh.js +106 -0
- package/dist/index-54sqbm3r.js +1354 -0
- package/dist/index-ecpc5qkb.js +245 -0
- package/dist/index-fxx9ktw7.js +1603 -0
- package/dist/index-kz62sdr9.js +336 -0
- package/dist/index-z4c2ehg4.js +1705 -0
- package/dist/index.js +77 -2219
- package/dist/run-e1kdpzna.js +15 -0
- package/dist/run.d.ts.map +1 -1
- package/dist/status-line.d.ts +2 -2
- package/dist/status-line.d.ts.map +1 -1
- package/dist/transcript.d.ts +2 -1
- package/dist/transcript.d.ts.map +1 -1
- package/dist/widgets/chart.d.ts +32 -0
- package/dist/widgets/chart.d.ts.map +1 -0
- package/dist/widgets/context.d.ts +29 -0
- package/dist/widgets/context.d.ts.map +1 -0
- package/dist/widgets/feedback.d.ts +65 -0
- package/dist/widgets/feedback.d.ts.map +1 -0
- package/dist/widgets/form.d.ts +23 -0
- package/dist/widgets/form.d.ts.map +1 -0
- package/dist/widgets/index.d.ts +13 -0
- package/dist/widgets/index.d.ts.map +1 -0
- package/dist/widgets/index.js +76 -0
- package/dist/widgets/keyboard.d.ts +28 -0
- package/dist/widgets/keyboard.d.ts.map +1 -0
- package/dist/widgets/layout.d.ts +51 -0
- package/dist/widgets/layout.d.ts.map +1 -0
- package/dist/widgets/list.d.ts +32 -0
- package/dist/widgets/list.d.ts.map +1 -0
- package/dist/widgets/meter.d.ts +26 -0
- package/dist/widgets/meter.d.ts.map +1 -0
- package/dist/widgets/table.d.ts +25 -0
- package/dist/widgets/table.d.ts.map +1 -0
- package/dist/widgets/tabs.d.ts +13 -0
- package/dist/widgets/tabs.d.ts.map +1 -0
- package/dist/widgets/text-view.d.ts +24 -0
- package/dist/widgets/text-view.d.ts.map +1 -0
- package/dist/widgets/theme.d.ts +17 -0
- package/dist/widgets/theme.d.ts.map +1 -0
- package/package.json +25 -12
|
@@ -0,0 +1,1603 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import {
|
|
3
|
+
validateTerminalCommands2,
|
|
4
|
+
createTerminalCommandPalette2,
|
|
5
|
+
setTerminalCommandQuery2,
|
|
6
|
+
terminalCommandMatches2,
|
|
7
|
+
moveTerminalCommandSelection2,
|
|
8
|
+
createTerminalFeedViewport2,
|
|
9
|
+
reduceTerminalFeedViewport2
|
|
10
|
+
} from "./index-kz62sdr9.js";
|
|
11
|
+
import {
|
|
12
|
+
createAgentTuiSessionId2,
|
|
13
|
+
createAgentTuiConversationId2,
|
|
14
|
+
listAgentTuiSessions2,
|
|
15
|
+
startAgentTuiSessionHost2
|
|
16
|
+
} from "./index-ecpc5qkb.js";
|
|
17
|
+
import {
|
|
18
|
+
resolveTerminalPalette2
|
|
19
|
+
} from "./index-z4c2ehg4.js";
|
|
20
|
+
|
|
21
|
+
// src/commands.ts
|
|
22
|
+
import { z } from "zod";
|
|
23
|
+
var AgentTuiCommandOutcomeSchema2 = z.discriminatedUnion("type", [
|
|
24
|
+
z.object({ type: z.literal("submit"), text: z.string().min(1) }).strict(),
|
|
25
|
+
z.object({
|
|
26
|
+
type: z.literal("dialog"),
|
|
27
|
+
dialog: z.string().min(1),
|
|
28
|
+
query: z.string().optional()
|
|
29
|
+
}).strict(),
|
|
30
|
+
z.object({ type: z.literal("notice"), message: z.string() }).strict(),
|
|
31
|
+
z.object({ type: z.literal("action"), action: z.string().min(1) }).strict()
|
|
32
|
+
]);
|
|
33
|
+
function defineTuiCommand2(command) {
|
|
34
|
+
if (!/^[a-z][a-z0-9-]*$/.test(command.name)) {
|
|
35
|
+
throw new Error("TUI command names use lowercase letters, digits and hyphens");
|
|
36
|
+
}
|
|
37
|
+
for (const alias of command.aliases ?? []) {
|
|
38
|
+
if (alias !== "?" && !/^[a-z][a-z0-9-]*$/.test(alias)) {
|
|
39
|
+
throw new Error("TUI command aliases are invalid");
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return command;
|
|
43
|
+
}
|
|
44
|
+
function composeTuiCommands2(...groups) {
|
|
45
|
+
const commands = groups.flat();
|
|
46
|
+
validateTerminalCommands2(commands.map((command) => ({
|
|
47
|
+
id: defineTuiCommand2(command).name,
|
|
48
|
+
aliases: [...command.aliases ?? []],
|
|
49
|
+
label: command.name,
|
|
50
|
+
description: command.description
|
|
51
|
+
})));
|
|
52
|
+
return commands;
|
|
53
|
+
}
|
|
54
|
+
function resolveTuiCommand2(text, commands) {
|
|
55
|
+
if (!text.startsWith("/"))
|
|
56
|
+
return { type: "prompt", text };
|
|
57
|
+
const match = /^\/([^\s]+)(?:\s+([\s\S]*))?$/.exec(text);
|
|
58
|
+
const name = match?.[1];
|
|
59
|
+
if (!name)
|
|
60
|
+
return { type: "prompt", text };
|
|
61
|
+
const command = commands.find((candidate) => candidate.name === name || candidate.aliases?.includes(name));
|
|
62
|
+
return command ? { type: "command", command, argumentsText: match?.[2] ?? "" } : { type: "prompt", text };
|
|
63
|
+
}
|
|
64
|
+
function commandCompletions2(text, commands) {
|
|
65
|
+
if (!text.startsWith("/") || text.slice(1).includes(" "))
|
|
66
|
+
return [];
|
|
67
|
+
const state = setTerminalCommandQuery2(createTerminalCommandPalette2(), text.slice(1));
|
|
68
|
+
const descriptors = terminalCommandMatches2(state, commands.map((command) => ({
|
|
69
|
+
id: command.name,
|
|
70
|
+
aliases: [...command.aliases ?? []],
|
|
71
|
+
label: command.name,
|
|
72
|
+
description: command.description
|
|
73
|
+
})), Math.max(1, commands.length));
|
|
74
|
+
return descriptors.map((descriptor) => commands.find((command) => command.name === descriptor.id)).filter((command) => command !== undefined);
|
|
75
|
+
}
|
|
76
|
+
function selectedCommandCompletion2(text, commands, selectedIndex) {
|
|
77
|
+
const completions = commandCompletions2(text, commands);
|
|
78
|
+
return completions[selectedIndex] ?? completions[0];
|
|
79
|
+
}
|
|
80
|
+
function moveCommandCompletionSelection2(selectedIndex, direction, completionCount) {
|
|
81
|
+
if (completionCount <= 0)
|
|
82
|
+
return 0;
|
|
83
|
+
return moveTerminalCommandSelection2({ query: "", selectedIndex, dismissed: false }, direction === "previous" ? -1 : 1, completionCount).selectedIndex;
|
|
84
|
+
}
|
|
85
|
+
function resolveTuiCommandSubmission2(text, commands, selectedIndex, paletteDismissed = false) {
|
|
86
|
+
const completion = paletteDismissed ? undefined : selectedCommandCompletion2(text, commands, selectedIndex);
|
|
87
|
+
return resolveTuiCommand2(completion ? `/${completion.name}` : text, commands);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// src/composer.ts
|
|
91
|
+
import { z as z2 } from "zod";
|
|
92
|
+
var AgentTuiComposerSchema2 = z2.object({
|
|
93
|
+
draft: z2.string(),
|
|
94
|
+
history: z2.array(z2.string()),
|
|
95
|
+
historyIndex: z2.int().nonnegative().optional(),
|
|
96
|
+
preservedDraft: z2.string()
|
|
97
|
+
}).strict();
|
|
98
|
+
function createAgentTuiComposer2() {
|
|
99
|
+
return { draft: "", history: [], preservedDraft: "" };
|
|
100
|
+
}
|
|
101
|
+
function setAgentTuiDraft2(state, draft) {
|
|
102
|
+
const { historyIndex: _historyIndex, ...rest } = state;
|
|
103
|
+
return { ...rest, draft, preservedDraft: draft };
|
|
104
|
+
}
|
|
105
|
+
function submitAgentTuiComposer2(state) {
|
|
106
|
+
const text = state.draft.trim();
|
|
107
|
+
if (!text)
|
|
108
|
+
return { state };
|
|
109
|
+
const history = state.history.at(-1) === text ? state.history : [...state.history, text];
|
|
110
|
+
return { state: { draft: "", history, preservedDraft: "" }, text };
|
|
111
|
+
}
|
|
112
|
+
function navigateAgentTuiHistory2(state, direction) {
|
|
113
|
+
if (state.history.length === 0)
|
|
114
|
+
return state;
|
|
115
|
+
if (direction === "older") {
|
|
116
|
+
const index = state.historyIndex === undefined ? state.history.length - 1 : Math.max(0, state.historyIndex - 1);
|
|
117
|
+
return { ...state, historyIndex: index, draft: state.history[index] ?? state.draft };
|
|
118
|
+
}
|
|
119
|
+
if (state.historyIndex === undefined)
|
|
120
|
+
return state;
|
|
121
|
+
const index = state.historyIndex + 1;
|
|
122
|
+
if (index >= state.history.length) {
|
|
123
|
+
const { historyIndex: _historyIndex, ...rest } = state;
|
|
124
|
+
return { ...rest, draft: state.preservedDraft };
|
|
125
|
+
}
|
|
126
|
+
return { ...state, historyIndex: index, draft: state.history[index] ?? state.draft };
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// src/config.ts
|
|
130
|
+
import { createHash } from "crypto";
|
|
131
|
+
import { mkdir, readFile, rename, unlink, writeFile } from "fs/promises";
|
|
132
|
+
import path from "path";
|
|
133
|
+
import { AgentModelSelectionSchema } from "stitchkit/agent-runtime";
|
|
134
|
+
import { z as z3 } from "zod";
|
|
135
|
+
var SelectionFileSchema = z3.object({
|
|
136
|
+
conversationId: z3.string().min(1),
|
|
137
|
+
selection: AgentModelSelectionSchema
|
|
138
|
+
}).strict();
|
|
139
|
+
function defineAgentTui2(config) {
|
|
140
|
+
return config;
|
|
141
|
+
}
|
|
142
|
+
function createFileAgentModelSelectionStore2(workspace) {
|
|
143
|
+
const directory = path.join(workspace, ".stitchkit", "tui", "models");
|
|
144
|
+
const filename = (conversationId) => path.join(directory, `${createHash("sha256").update(conversationId).digest("hex")}.json`);
|
|
145
|
+
const load = async (conversationId) => {
|
|
146
|
+
try {
|
|
147
|
+
const record = SelectionFileSchema.parse(JSON.parse(await readFile(filename(conversationId), "utf8")));
|
|
148
|
+
if (record.conversationId !== conversationId) {
|
|
149
|
+
throw new Error("Agent TUI model selection identity does not match its path");
|
|
150
|
+
}
|
|
151
|
+
return record.selection;
|
|
152
|
+
} catch (error) {
|
|
153
|
+
if (!(error instanceof Error && ("code" in error) && error.code === "ENOENT"))
|
|
154
|
+
throw error;
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
};
|
|
158
|
+
return {
|
|
159
|
+
load,
|
|
160
|
+
async save(conversationId, rawSelection) {
|
|
161
|
+
const selection = AgentModelSelectionSchema.parse(rawSelection);
|
|
162
|
+
const target = filename(conversationId);
|
|
163
|
+
const record = SelectionFileSchema.parse({ conversationId, selection });
|
|
164
|
+
await mkdir(directory, { recursive: true, mode: 448 });
|
|
165
|
+
const temporary = `${target}.${crypto.randomUUID()}.tmp`;
|
|
166
|
+
await writeFile(temporary, `${JSON.stringify(record, null, 2)}
|
|
167
|
+
`, {
|
|
168
|
+
encoding: "utf8",
|
|
169
|
+
mode: 384,
|
|
170
|
+
flag: "wx"
|
|
171
|
+
});
|
|
172
|
+
try {
|
|
173
|
+
await rename(temporary, target);
|
|
174
|
+
} catch (error) {
|
|
175
|
+
await unlink(temporary).catch(() => {
|
|
176
|
+
return;
|
|
177
|
+
});
|
|
178
|
+
throw error;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// src/controller.ts
|
|
185
|
+
function activeRun(snapshot) {
|
|
186
|
+
return snapshot.runs.find((run) => run.state === "running" || run.state === "interrupt_requested");
|
|
187
|
+
}
|
|
188
|
+
function pinnedModel(snapshot, runId) {
|
|
189
|
+
const run = snapshot.runs.find(({ id }) => id === runId);
|
|
190
|
+
const inputMessage = snapshot.messages.find(({ id }) => id === run?.inputMessageIds[0]);
|
|
191
|
+
const metadata = inputMessage?.metadata;
|
|
192
|
+
if (typeof metadata !== "object" || metadata === null)
|
|
193
|
+
return;
|
|
194
|
+
const modelId = Reflect.get(metadata, "modelId");
|
|
195
|
+
return typeof modelId === "string" && modelId.length > 0 ? modelId : undefined;
|
|
196
|
+
}
|
|
197
|
+
async function createAgentTuiController2(input) {
|
|
198
|
+
let conversationId = input.conversationId;
|
|
199
|
+
const listeners = new Set;
|
|
200
|
+
let current = {
|
|
201
|
+
conversationId,
|
|
202
|
+
snapshot: await input.harness.snapshot(conversationId),
|
|
203
|
+
streaming: {}
|
|
204
|
+
};
|
|
205
|
+
const emit = () => {
|
|
206
|
+
for (const listener of listeners)
|
|
207
|
+
listener(current);
|
|
208
|
+
};
|
|
209
|
+
let refreshVersion = 0;
|
|
210
|
+
const refresh = async () => {
|
|
211
|
+
const targetConversationId = conversationId;
|
|
212
|
+
const version = ++refreshVersion;
|
|
213
|
+
const [snapshot, approvals, selection] = await Promise.all([
|
|
214
|
+
input.harness.snapshot(targetConversationId),
|
|
215
|
+
input.harness.pendingApprovals(targetConversationId),
|
|
216
|
+
input.selections.load(targetConversationId)
|
|
217
|
+
]);
|
|
218
|
+
if (version !== refreshVersion || targetConversationId !== conversationId)
|
|
219
|
+
return;
|
|
220
|
+
const next = {
|
|
221
|
+
...current,
|
|
222
|
+
conversationId: targetConversationId,
|
|
223
|
+
snapshot,
|
|
224
|
+
...selection && { selectedModelId: selection.modelId },
|
|
225
|
+
...approvals[0] && { pendingApproval: approvals[0] }
|
|
226
|
+
};
|
|
227
|
+
if (!approvals[0])
|
|
228
|
+
delete next.pendingApproval;
|
|
229
|
+
current = next;
|
|
230
|
+
emit();
|
|
231
|
+
};
|
|
232
|
+
let selection = await input.selections.load(conversationId);
|
|
233
|
+
if (!selection) {
|
|
234
|
+
const modelId = input.preferredModelId && input.catalog.models.some(({ id }) => id === input.preferredModelId) && input.preferredModelId || input.catalog.models[0]?.id;
|
|
235
|
+
if (!modelId)
|
|
236
|
+
throw new Error("The Agent TUI model catalog is empty");
|
|
237
|
+
selection = { modelId, selectedAt: new Date().toISOString() };
|
|
238
|
+
await input.selections.save(conversationId, selection);
|
|
239
|
+
}
|
|
240
|
+
current = { ...current, selectedModelId: selection.modelId };
|
|
241
|
+
const unsubscribe = input.harness.subscribe((event) => {
|
|
242
|
+
if (event.conversationId !== conversationId)
|
|
243
|
+
return;
|
|
244
|
+
input.onDiagnostic?.({
|
|
245
|
+
conversationId,
|
|
246
|
+
...event.runId && { runId: event.runId },
|
|
247
|
+
event
|
|
248
|
+
});
|
|
249
|
+
if (event.type === "assistant-delta") {
|
|
250
|
+
current = {
|
|
251
|
+
...current,
|
|
252
|
+
streaming: {
|
|
253
|
+
...current.streaming,
|
|
254
|
+
[event.runId]: (current.streaming[event.runId] ?? "") + event.textDelta
|
|
255
|
+
}
|
|
256
|
+
};
|
|
257
|
+
emit();
|
|
258
|
+
return;
|
|
259
|
+
}
|
|
260
|
+
if (event.type === "terminal") {
|
|
261
|
+
const streaming = Object.fromEntries(Object.entries(current.streaming).filter(([runId]) => runId !== event.runId));
|
|
262
|
+
current = {
|
|
263
|
+
...current,
|
|
264
|
+
streaming,
|
|
265
|
+
...event.reason === "provider_failure" ? {
|
|
266
|
+
notice: {
|
|
267
|
+
tone: "error",
|
|
268
|
+
message: "The model run failed. You can send the next message."
|
|
269
|
+
}
|
|
270
|
+
} : {}
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
if (event.type === "admission" || event.type === "assistant-checkpoint" || event.type === "run-state" || event.type === "terminal") {
|
|
274
|
+
refresh();
|
|
275
|
+
}
|
|
276
|
+
});
|
|
277
|
+
await refresh();
|
|
278
|
+
const selected = async () => {
|
|
279
|
+
const found = await input.selections.load(conversationId);
|
|
280
|
+
if (!found)
|
|
281
|
+
throw new Error("Select a model before submitting");
|
|
282
|
+
return found.modelId;
|
|
283
|
+
};
|
|
284
|
+
return {
|
|
285
|
+
state: () => current,
|
|
286
|
+
subscribe(listener) {
|
|
287
|
+
listeners.add(listener);
|
|
288
|
+
listener(current);
|
|
289
|
+
return () => listeners.delete(listener);
|
|
290
|
+
},
|
|
291
|
+
async submit(rawText, idempotencyKey = crypto.randomUUID()) {
|
|
292
|
+
const text = rawText.trim();
|
|
293
|
+
if (!text)
|
|
294
|
+
throw new Error("Agent message is empty");
|
|
295
|
+
const modelId = await selected();
|
|
296
|
+
const ticket = input.harness.submit({
|
|
297
|
+
conversationId,
|
|
298
|
+
idempotencyKey,
|
|
299
|
+
context: await input.context(),
|
|
300
|
+
parts: [{ type: "text", text }],
|
|
301
|
+
metadata: { modelId }
|
|
302
|
+
});
|
|
303
|
+
const admission = await ticket.admission;
|
|
304
|
+
ticket.result.catch(() => {
|
|
305
|
+
return;
|
|
306
|
+
});
|
|
307
|
+
await refresh();
|
|
308
|
+
return admission.runId;
|
|
309
|
+
},
|
|
310
|
+
async selectModel(modelId) {
|
|
311
|
+
if (!input.catalog.models.some((model) => model.id === modelId)) {
|
|
312
|
+
throw new Error(`Unknown model: ${modelId}`);
|
|
313
|
+
}
|
|
314
|
+
await input.selections.save(conversationId, {
|
|
315
|
+
modelId,
|
|
316
|
+
selectedAt: new Date().toISOString()
|
|
317
|
+
});
|
|
318
|
+
await refresh();
|
|
319
|
+
},
|
|
320
|
+
async switchConversation(nextConversationId) {
|
|
321
|
+
const previousModelId = current.selectedModelId;
|
|
322
|
+
conversationId = nextConversationId;
|
|
323
|
+
const version = ++refreshVersion;
|
|
324
|
+
const snapshot = await input.harness.snapshot(nextConversationId);
|
|
325
|
+
if (version !== refreshVersion || conversationId !== nextConversationId)
|
|
326
|
+
return;
|
|
327
|
+
current = {
|
|
328
|
+
conversationId: nextConversationId,
|
|
329
|
+
snapshot,
|
|
330
|
+
streaming: {}
|
|
331
|
+
};
|
|
332
|
+
let nextSelection = await input.selections.load(nextConversationId);
|
|
333
|
+
if (version !== refreshVersion || conversationId !== nextConversationId)
|
|
334
|
+
return;
|
|
335
|
+
if (!nextSelection) {
|
|
336
|
+
const modelId = previousModelId ?? input.catalog.models[0]?.id;
|
|
337
|
+
if (!modelId)
|
|
338
|
+
throw new Error("The Agent TUI model catalog is empty");
|
|
339
|
+
nextSelection = { modelId, selectedAt: new Date().toISOString() };
|
|
340
|
+
await input.selections.save(nextConversationId, nextSelection);
|
|
341
|
+
if (version !== refreshVersion || conversationId !== nextConversationId)
|
|
342
|
+
return;
|
|
343
|
+
}
|
|
344
|
+
await refresh();
|
|
345
|
+
},
|
|
346
|
+
async respondToApproval(approved, reason) {
|
|
347
|
+
const approval = current.pendingApproval;
|
|
348
|
+
if (!approval)
|
|
349
|
+
throw new Error("No approval is pending");
|
|
350
|
+
const ticket = await input.harness.respondToApproval({
|
|
351
|
+
conversationId,
|
|
352
|
+
approvalId: approval.approvalId,
|
|
353
|
+
approved,
|
|
354
|
+
...reason && { reason },
|
|
355
|
+
context: await input.context(),
|
|
356
|
+
metadata: {
|
|
357
|
+
modelId: pinnedModel(current.snapshot, approval.runId) ?? await selected()
|
|
358
|
+
}
|
|
359
|
+
});
|
|
360
|
+
const admission = await ticket.admission;
|
|
361
|
+
ticket.result.catch(() => {
|
|
362
|
+
return;
|
|
363
|
+
});
|
|
364
|
+
await refresh();
|
|
365
|
+
return admission.runId;
|
|
366
|
+
},
|
|
367
|
+
async interrupt(runId) {
|
|
368
|
+
const target = runId ?? activeRun(current.snapshot)?.id;
|
|
369
|
+
if (!target)
|
|
370
|
+
throw new Error("No active run to interrupt");
|
|
371
|
+
await input.harness.interrupt({ conversationId, runId: target });
|
|
372
|
+
await refresh();
|
|
373
|
+
},
|
|
374
|
+
async close() {
|
|
375
|
+
unsubscribe();
|
|
376
|
+
await input.harness.close({ gracePeriodMs: 1000, forceTimeoutMs: 1000 });
|
|
377
|
+
}
|
|
378
|
+
};
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
// src/diagnostics.ts
|
|
382
|
+
import { lstat, mkdir as mkdir2, readdir, rm } from "fs/promises";
|
|
383
|
+
import path2 from "path";
|
|
384
|
+
import { createDiagnosticJournal } from "stitchkit/application/diagnostic-journal";
|
|
385
|
+
import { z as z4 } from "zod";
|
|
386
|
+
var RUNTIME_EVENT_TYPES = new Set([
|
|
387
|
+
"admission",
|
|
388
|
+
"run-state",
|
|
389
|
+
"terminal",
|
|
390
|
+
"tool-status",
|
|
391
|
+
"run-started",
|
|
392
|
+
"run-terminal",
|
|
393
|
+
"step-finished"
|
|
394
|
+
]);
|
|
395
|
+
var MAX_SESSION_JOURNALS = 8;
|
|
396
|
+
var BaseEventSchema = z4.object({
|
|
397
|
+
schemaVersion: z4.literal(1),
|
|
398
|
+
occurredAt: z4.iso.datetime({ offset: true })
|
|
399
|
+
});
|
|
400
|
+
var AgentTuiDiagnosticEventSchema2 = z4.discriminatedUnion("type", [
|
|
401
|
+
BaseEventSchema.extend({
|
|
402
|
+
type: z4.literal("host-started"),
|
|
403
|
+
sessionId: z4.string().min(8),
|
|
404
|
+
conversationId: z4.string().min(1),
|
|
405
|
+
launchMode: z4.enum(["fresh", "explicit"])
|
|
406
|
+
}).strict(),
|
|
407
|
+
BaseEventSchema.extend({
|
|
408
|
+
type: z4.literal("conversation-changed"),
|
|
409
|
+
sessionId: z4.string().min(8),
|
|
410
|
+
previousConversationId: z4.string().min(1),
|
|
411
|
+
conversationId: z4.string().min(1),
|
|
412
|
+
reason: z4.enum(["new", "clear", "resume"])
|
|
413
|
+
}).strict(),
|
|
414
|
+
BaseEventSchema.extend({
|
|
415
|
+
type: z4.literal("submission-admitted"),
|
|
416
|
+
sessionId: z4.string().min(8),
|
|
417
|
+
conversationId: z4.string().min(1),
|
|
418
|
+
runId: z4.string().min(1),
|
|
419
|
+
source: z4.enum(["terminal", "client"])
|
|
420
|
+
}).strict(),
|
|
421
|
+
BaseEventSchema.extend({
|
|
422
|
+
type: z4.literal("runtime-event"),
|
|
423
|
+
conversationId: z4.string().min(1).optional(),
|
|
424
|
+
runId: z4.string().min(1).optional(),
|
|
425
|
+
eventType: z4.string().min(1),
|
|
426
|
+
state: z4.string().min(1).optional()
|
|
427
|
+
}).strict(),
|
|
428
|
+
BaseEventSchema.extend({
|
|
429
|
+
type: z4.literal("request-failed"),
|
|
430
|
+
sessionId: z4.string().min(8),
|
|
431
|
+
operation: z4.enum(["status", "submit", "interrupt"])
|
|
432
|
+
}).strict(),
|
|
433
|
+
BaseEventSchema.extend({
|
|
434
|
+
type: z4.literal("host-closed"),
|
|
435
|
+
sessionId: z4.string().min(8),
|
|
436
|
+
conversationId: z4.string().min(1)
|
|
437
|
+
}).strict()
|
|
438
|
+
]);
|
|
439
|
+
function stringField(value, name) {
|
|
440
|
+
const field = Reflect.get(value, name);
|
|
441
|
+
return typeof field === "string" && field.length > 0 ? field : undefined;
|
|
442
|
+
}
|
|
443
|
+
function projectAgentTuiRuntimeDiagnostic2(value, occurredAt = new Date().toISOString()) {
|
|
444
|
+
if (typeof value !== "object" || value === null)
|
|
445
|
+
return;
|
|
446
|
+
const nested = Reflect.get(value, "event");
|
|
447
|
+
const event = typeof nested === "object" && nested !== null ? nested : value;
|
|
448
|
+
const eventType = stringField(event, "type");
|
|
449
|
+
if (!eventType || !RUNTIME_EVENT_TYPES.has(eventType))
|
|
450
|
+
return;
|
|
451
|
+
const conversationId = stringField(value, "conversationId") ?? stringField(event, "conversationId");
|
|
452
|
+
const runId = stringField(value, "runId") ?? stringField(event, "runId");
|
|
453
|
+
const state = stringField(event, "state");
|
|
454
|
+
return AgentTuiDiagnosticEventSchema2.parse({
|
|
455
|
+
schemaVersion: 1,
|
|
456
|
+
occurredAt,
|
|
457
|
+
type: "runtime-event",
|
|
458
|
+
...conversationId && { conversationId },
|
|
459
|
+
...runId && { runId },
|
|
460
|
+
eventType,
|
|
461
|
+
...state && { state }
|
|
462
|
+
});
|
|
463
|
+
}
|
|
464
|
+
async function pruneOldSessionJournals(input) {
|
|
465
|
+
const liveSessionIds = new Set((await listAgentTuiSessions2(input.workspace)).map(({ sessionId }) => sessionId));
|
|
466
|
+
liveSessionIds.add(input.currentSessionId);
|
|
467
|
+
const groups = new Map;
|
|
468
|
+
for (const name of await readdir(input.directory)) {
|
|
469
|
+
const match = /^([a-f0-9]{16})\.jsonl(?:\.\d+|\.lock)?$/.exec(name);
|
|
470
|
+
const sessionId = match?.[1];
|
|
471
|
+
if (!sessionId || liveSessionIds.has(sessionId))
|
|
472
|
+
continue;
|
|
473
|
+
const filename = path2.join(input.directory, name);
|
|
474
|
+
const info = await lstat(filename);
|
|
475
|
+
if (!info.isFile())
|
|
476
|
+
continue;
|
|
477
|
+
const group = groups.get(sessionId) ?? { files: [], modifiedAt: 0 };
|
|
478
|
+
group.files.push(filename);
|
|
479
|
+
group.modifiedAt = Math.max(group.modifiedAt, info.mtimeMs);
|
|
480
|
+
groups.set(sessionId, group);
|
|
481
|
+
}
|
|
482
|
+
const inactive = [...groups.values()].sort((left, right) => right.modifiedAt - left.modifiedAt);
|
|
483
|
+
for (const group of inactive.slice(MAX_SESSION_JOURNALS)) {
|
|
484
|
+
for (const filename of group.files)
|
|
485
|
+
await rm(filename);
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
async function createAgentTuiDiagnosticRecorder2(input) {
|
|
489
|
+
const directory = path2.join(input.workspace, ".stitchkit", "logs", "tui");
|
|
490
|
+
await mkdir2(directory, { recursive: true, mode: 448 });
|
|
491
|
+
const basename = `${input.sessionId}.jsonl`;
|
|
492
|
+
await pruneOldSessionJournals({
|
|
493
|
+
directory,
|
|
494
|
+
workspace: input.workspace,
|
|
495
|
+
currentSessionId: input.sessionId
|
|
496
|
+
});
|
|
497
|
+
const journal = await createDiagnosticJournal({
|
|
498
|
+
path: path2.join(directory, basename),
|
|
499
|
+
eventSchema: AgentTuiDiagnosticEventSchema2,
|
|
500
|
+
limits: {
|
|
501
|
+
maxEventBytes: 4096,
|
|
502
|
+
maxPendingItems: 256,
|
|
503
|
+
maxPendingBytes: 256 * 4096,
|
|
504
|
+
maxFileBytes: 512 * 1024,
|
|
505
|
+
maxFiles: 2
|
|
506
|
+
}
|
|
507
|
+
});
|
|
508
|
+
return {
|
|
509
|
+
write(value) {
|
|
510
|
+
const event = projectAgentTuiRuntimeDiagnostic2(value);
|
|
511
|
+
if (event)
|
|
512
|
+
journal.submit(event);
|
|
513
|
+
},
|
|
514
|
+
record(event) {
|
|
515
|
+
journal.submit(event);
|
|
516
|
+
},
|
|
517
|
+
async close() {
|
|
518
|
+
await journal.close({ timeoutMs: 2000 });
|
|
519
|
+
}
|
|
520
|
+
};
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
// src/keyboard.ts
|
|
524
|
+
function isAgentTuiExitKey2(key) {
|
|
525
|
+
return key.ctrl === true && key.name?.toLowerCase() === "c";
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
// src/model-picker.ts
|
|
529
|
+
import { searchAgentModelCatalog } from "stitchkit/agent-runtime";
|
|
530
|
+
var AGENT_TUI_MODEL_RESULT_LIMIT2 = 200;
|
|
531
|
+
function searchAgentTuiModels2(catalog, query) {
|
|
532
|
+
return searchAgentModelCatalog(catalog, {
|
|
533
|
+
query,
|
|
534
|
+
limit: AGENT_TUI_MODEL_RESULT_LIMIT2
|
|
535
|
+
});
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
// src/run.tsx
|
|
539
|
+
import path4 from "path";
|
|
540
|
+
import { createCliRenderer } from "@opentui/core";
|
|
541
|
+
import { createRoot } from "@opentui/react";
|
|
542
|
+
|
|
543
|
+
// src/App.tsx
|
|
544
|
+
import { useKeyboard, useTerminalDimensions } from "@opentui/react";
|
|
545
|
+
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
|
546
|
+
|
|
547
|
+
// src/builtins.ts
|
|
548
|
+
var dialog = (name, query) => ({
|
|
549
|
+
type: "dialog",
|
|
550
|
+
dialog: name,
|
|
551
|
+
...query && { query }
|
|
552
|
+
});
|
|
553
|
+
var action = (name) => ({ type: "action", action: name });
|
|
554
|
+
function createAgentTuiBuiltinCommands() {
|
|
555
|
+
return [
|
|
556
|
+
defineTuiCommand2({
|
|
557
|
+
name: "help",
|
|
558
|
+
aliases: ["?"],
|
|
559
|
+
description: "Show available terminal commands",
|
|
560
|
+
execute: () => dialog("help")
|
|
561
|
+
}),
|
|
562
|
+
defineTuiCommand2({
|
|
563
|
+
name: "model",
|
|
564
|
+
description: "Choose the model for the next run",
|
|
565
|
+
execute: (query) => dialog("model", query.trim())
|
|
566
|
+
}),
|
|
567
|
+
defineTuiCommand2({
|
|
568
|
+
name: "new",
|
|
569
|
+
description: "Start a new durable conversation",
|
|
570
|
+
execute: () => action("new-conversation")
|
|
571
|
+
}),
|
|
572
|
+
defineTuiCommand2({
|
|
573
|
+
name: "sessions",
|
|
574
|
+
description: "Browse durable conversations",
|
|
575
|
+
execute: () => dialog("sessions")
|
|
576
|
+
}),
|
|
577
|
+
defineTuiCommand2({
|
|
578
|
+
name: "resume",
|
|
579
|
+
description: "Resume a durable conversation",
|
|
580
|
+
execute: () => dialog("sessions")
|
|
581
|
+
}),
|
|
582
|
+
defineTuiCommand2({
|
|
583
|
+
name: "status",
|
|
584
|
+
description: "Show session, conversation and run status",
|
|
585
|
+
execute: () => dialog("status")
|
|
586
|
+
}),
|
|
587
|
+
defineTuiCommand2({
|
|
588
|
+
name: "tools",
|
|
589
|
+
description: "Show the direct tool surface",
|
|
590
|
+
execute: () => dialog("tools")
|
|
591
|
+
}),
|
|
592
|
+
defineTuiCommand2({
|
|
593
|
+
name: "skills",
|
|
594
|
+
description: "Show lazily available skills and resources",
|
|
595
|
+
execute: () => dialog("skills")
|
|
596
|
+
}),
|
|
597
|
+
defineTuiCommand2({
|
|
598
|
+
name: "permissions",
|
|
599
|
+
description: "Show approval and sandbox enforcement",
|
|
600
|
+
execute: () => dialog("permissions")
|
|
601
|
+
}),
|
|
602
|
+
defineTuiCommand2({
|
|
603
|
+
name: "interrupt",
|
|
604
|
+
description: "Interrupt the active run",
|
|
605
|
+
available: ({ activeRunId }) => activeRunId !== undefined,
|
|
606
|
+
execute: () => action("interrupt")
|
|
607
|
+
}),
|
|
608
|
+
defineTuiCommand2({
|
|
609
|
+
name: "clear",
|
|
610
|
+
description: "Start clean while keeping this conversation available to resume",
|
|
611
|
+
execute: () => action("clear-conversation")
|
|
612
|
+
}),
|
|
613
|
+
defineTuiCommand2({
|
|
614
|
+
name: "quit",
|
|
615
|
+
aliases: ["exit"],
|
|
616
|
+
description: "Close this terminal host",
|
|
617
|
+
execute: () => action("quit")
|
|
618
|
+
})
|
|
619
|
+
];
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
// src/status-line.ts
|
|
623
|
+
import path3 from "path";
|
|
624
|
+
function formatCount(value) {
|
|
625
|
+
if (value >= 1e6)
|
|
626
|
+
return `${(value / 1e6).toFixed(1)}M`;
|
|
627
|
+
if (value >= 1000)
|
|
628
|
+
return `${(value / 1000).toFixed(1)}k`;
|
|
629
|
+
return String(value);
|
|
630
|
+
}
|
|
631
|
+
function knownTotal(usages, field) {
|
|
632
|
+
if (usages.length === 0)
|
|
633
|
+
return;
|
|
634
|
+
let value = 0;
|
|
635
|
+
let known = 0;
|
|
636
|
+
for (const usage of usages) {
|
|
637
|
+
const item = usage[field];
|
|
638
|
+
if (item.value === undefined)
|
|
639
|
+
continue;
|
|
640
|
+
value += item.value;
|
|
641
|
+
known += 1;
|
|
642
|
+
}
|
|
643
|
+
if (known === 0)
|
|
644
|
+
return;
|
|
645
|
+
return { value, partial: known !== usages.length };
|
|
646
|
+
}
|
|
647
|
+
function formatKnownTotal(total) {
|
|
648
|
+
return `${total.partial ? "\u2265" : ""}${formatCount(total.value)}`;
|
|
649
|
+
}
|
|
650
|
+
function shortIdentity(value) {
|
|
651
|
+
return value.slice(0, 8);
|
|
652
|
+
}
|
|
653
|
+
var defaultAgentTuiStatusLine2 = (context) => {
|
|
654
|
+
const usages = context.snapshot.runs.map(({ usage }) => usage).filter((usage) => usage !== undefined);
|
|
655
|
+
const input = knownTotal(usages, "inputTokens");
|
|
656
|
+
const output = knownTotal(usages, "outputTokens");
|
|
657
|
+
const firstRow = [
|
|
658
|
+
{
|
|
659
|
+
text: context.model?.name ?? context.model?.id ?? "model unavailable",
|
|
660
|
+
tone: "accent"
|
|
661
|
+
}
|
|
662
|
+
];
|
|
663
|
+
if (context.model) {
|
|
664
|
+
firstRow.push({
|
|
665
|
+
text: `${formatCount(context.model.descriptor.contextWindow)} context`,
|
|
666
|
+
tone: "primary"
|
|
667
|
+
});
|
|
668
|
+
}
|
|
669
|
+
if (input || output) {
|
|
670
|
+
firstRow.push({
|
|
671
|
+
text: `session ${input ? `\u2193${formatKnownTotal(input)}` : "\u2193\u2014"} ${output ? `\u2191${formatKnownTotal(output)}` : "\u2191\u2014"}`,
|
|
672
|
+
tone: "muted"
|
|
673
|
+
});
|
|
674
|
+
}
|
|
675
|
+
const activityTone = context.activity === "APPROVAL" ? "warning" : context.activity === "RUNNING" ? "accent" : "success";
|
|
676
|
+
return [
|
|
677
|
+
firstRow,
|
|
678
|
+
[
|
|
679
|
+
{ text: path3.basename(context.workspace) || context.workspace, tone: "primary" },
|
|
680
|
+
{ text: shortIdentity(context.conversationId), tone: "muted" },
|
|
681
|
+
{ text: context.activity.toLowerCase(), tone: activityTone }
|
|
682
|
+
]
|
|
683
|
+
];
|
|
684
|
+
};
|
|
685
|
+
|
|
686
|
+
// src/transcript.ts
|
|
687
|
+
function compactJson(value) {
|
|
688
|
+
const text = JSON.stringify(value);
|
|
689
|
+
return text.length > 360 ? `${text.slice(0, 357)}\u2026` : text;
|
|
690
|
+
}
|
|
691
|
+
function isToolErrorEnvelope(value) {
|
|
692
|
+
return typeof value === "object" && value !== null && "error" in value && typeof Reflect.get(value, "error") === "string";
|
|
693
|
+
}
|
|
694
|
+
function partText(part) {
|
|
695
|
+
if (part.type === "text")
|
|
696
|
+
return { text: part.text };
|
|
697
|
+
if (part.type === "reasoning")
|
|
698
|
+
return { text: part.text };
|
|
699
|
+
if (part.type === "tool-call")
|
|
700
|
+
return { text: `\u2192 ${part.toolName} ${compactJson(part.input)}` };
|
|
701
|
+
if (part.type === "tool-result") {
|
|
702
|
+
const failed = part.outcome !== "success" || isToolErrorEnvelope(part.output);
|
|
703
|
+
return {
|
|
704
|
+
text: `${failed ? "\xD7" : "\u2713"} ${part.toolName}${part.output === undefined ? "" : ` ${compactJson(part.output)}`}`,
|
|
705
|
+
failed
|
|
706
|
+
};
|
|
707
|
+
}
|
|
708
|
+
if (part.type === "tool-approval-request")
|
|
709
|
+
return { text: "Approval required." };
|
|
710
|
+
if (part.type === "tool-approval-response") {
|
|
711
|
+
return {
|
|
712
|
+
text: part.approved ? "Approved." : `Denied${part.reason ? `: ${part.reason}` : "."}`
|
|
713
|
+
};
|
|
714
|
+
}
|
|
715
|
+
if (part.type === "file")
|
|
716
|
+
return { text: `File \xB7 ${part.filename ?? part.reference}` };
|
|
717
|
+
if (part.type === "source")
|
|
718
|
+
return { text: `Source \xB7 ${part.title ?? part.url ?? part.sourceId}` };
|
|
719
|
+
if (part.type === "control")
|
|
720
|
+
return { text: `Run ${part.reason}.` };
|
|
721
|
+
return;
|
|
722
|
+
}
|
|
723
|
+
function role(message) {
|
|
724
|
+
if (message.role === "user")
|
|
725
|
+
return "you";
|
|
726
|
+
if (message.role === "assistant")
|
|
727
|
+
return "agent";
|
|
728
|
+
if (message.role === "tool")
|
|
729
|
+
return "tool";
|
|
730
|
+
return "system";
|
|
731
|
+
}
|
|
732
|
+
function projectAgentTuiTranscript2(snapshot) {
|
|
733
|
+
return snapshot.messages.flatMap((message) => message.parts.flatMap((part, index) => {
|
|
734
|
+
const projected = partText(part);
|
|
735
|
+
if (!projected?.text.trim())
|
|
736
|
+
return [];
|
|
737
|
+
const messageRole = role(message);
|
|
738
|
+
return [
|
|
739
|
+
{
|
|
740
|
+
id: `${message.id}:${index}`,
|
|
741
|
+
role: messageRole,
|
|
742
|
+
text: projected.text,
|
|
743
|
+
tone: projected.failed ? "danger" : part.type === "tool-result" ? "success" : messageRole === "you" ? "accent" : messageRole === "tool" || messageRole === "system" ? "muted" : "primary"
|
|
744
|
+
}
|
|
745
|
+
];
|
|
746
|
+
}));
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
// src/App.tsx
|
|
750
|
+
import { jsx, jsxs } from "@opentui/react/jsx-runtime";
|
|
751
|
+
function isDialog(value) {
|
|
752
|
+
return ["help", "model", "sessions", "status", "tools", "skills", "permissions"].includes(value);
|
|
753
|
+
}
|
|
754
|
+
function isString(value) {
|
|
755
|
+
return value !== undefined;
|
|
756
|
+
}
|
|
757
|
+
function errorMessage(error) {
|
|
758
|
+
return error instanceof Error ? error.message : String(error);
|
|
759
|
+
}
|
|
760
|
+
function roleLabel(role) {
|
|
761
|
+
if (role === "you")
|
|
762
|
+
return "YOU";
|
|
763
|
+
if (role === "agent")
|
|
764
|
+
return "AGENT";
|
|
765
|
+
if (role === "tool")
|
|
766
|
+
return "TOOL";
|
|
767
|
+
return "SYSTEM";
|
|
768
|
+
}
|
|
769
|
+
function formatContext(tokens) {
|
|
770
|
+
return tokens >= 1e6 ? `${(tokens / 1e6).toFixed(1)}M` : `${Math.round(tokens / 1000)}K`;
|
|
771
|
+
}
|
|
772
|
+
function activeRunId(state) {
|
|
773
|
+
return state.snapshot.runs.find(({ state: runState }) => runState === "running" || runState === "interrupt_requested")?.id;
|
|
774
|
+
}
|
|
775
|
+
function AgentTuiApp({
|
|
776
|
+
controller,
|
|
777
|
+
catalog,
|
|
778
|
+
conversations,
|
|
779
|
+
commands: customCommands = [],
|
|
780
|
+
theme,
|
|
781
|
+
workspace,
|
|
782
|
+
statusLine,
|
|
783
|
+
sessionId,
|
|
784
|
+
title,
|
|
785
|
+
onConversationChange,
|
|
786
|
+
onExit
|
|
787
|
+
}) {
|
|
788
|
+
const dimensions = useTerminalDimensions();
|
|
789
|
+
const [state, setState] = useState(controller.state());
|
|
790
|
+
const [dialog, setDialog] = useState();
|
|
791
|
+
const [modelQuery, setModelQuery] = useState("");
|
|
792
|
+
const [modelSearchFocused, setModelSearchFocused] = useState(true);
|
|
793
|
+
const [composer, setComposer] = useState(createAgentTuiComposer2);
|
|
794
|
+
const [completionIndex, setCompletionIndex] = useState(0);
|
|
795
|
+
const [dismissedCompletionDraft, setDismissedCompletionDraft] = useState();
|
|
796
|
+
const draft = composer.draft;
|
|
797
|
+
const [localNotice, setLocalNotice] = useState();
|
|
798
|
+
const [hiddenBefore, setHiddenBefore] = useState(0);
|
|
799
|
+
const [sessions, setSessions] = useState([]);
|
|
800
|
+
const [sessionCursor, setSessionCursor] = useState();
|
|
801
|
+
const [viewport, setViewport] = useState(() => createTerminalFeedViewport2(0, 1));
|
|
802
|
+
const previousTranscriptSize = useRef(0);
|
|
803
|
+
const previousConversationId = useRef(state.conversationId);
|
|
804
|
+
const composerRef = useRef(null);
|
|
805
|
+
const transcriptRef = useRef(null);
|
|
806
|
+
const compact = dimensions.width < 90;
|
|
807
|
+
const commands = useMemo(() => composeTuiCommands2(createAgentTuiBuiltinCommands(), customCommands), [customCommands]);
|
|
808
|
+
const entries = useMemo(() => projectAgentTuiTranscript2(state.snapshot).slice(hiddenBefore), [hiddenBefore, state.snapshot]);
|
|
809
|
+
const streamingRows = useMemo(() => Object.values(state.streaming).reduce((total, text) => total + Math.max(1, text.split(`
|
|
810
|
+
`).length), 0), [state.streaming]);
|
|
811
|
+
const transcriptUnits = entries.length + streamingRows;
|
|
812
|
+
const completions = useMemo(() => dismissedCompletionDraft === draft ? [] : commandCompletions2(draft, commands).slice(0, 5), [commands, dismissedCompletionDraft, draft]);
|
|
813
|
+
const runId = activeRunId(state);
|
|
814
|
+
const activity = state.pendingApproval ? "APPROVAL" : runId ? "RUNNING" : "READY";
|
|
815
|
+
const selectedModel = catalog.models.find(({ id }) => id === state.selectedModelId);
|
|
816
|
+
const statusRows = useMemo(() => {
|
|
817
|
+
if (statusLine === false)
|
|
818
|
+
return [];
|
|
819
|
+
return (statusLine ?? defaultAgentTuiStatusLine2)({
|
|
820
|
+
title,
|
|
821
|
+
workspace,
|
|
822
|
+
activity,
|
|
823
|
+
sessionId,
|
|
824
|
+
conversationId: state.conversationId,
|
|
825
|
+
...selectedModel && { model: selectedModel },
|
|
826
|
+
snapshot: state.snapshot
|
|
827
|
+
});
|
|
828
|
+
}, [
|
|
829
|
+
activity,
|
|
830
|
+
selectedModel,
|
|
831
|
+
sessionId,
|
|
832
|
+
state.conversationId,
|
|
833
|
+
state.snapshot,
|
|
834
|
+
statusLine,
|
|
835
|
+
title,
|
|
836
|
+
workspace
|
|
837
|
+
]);
|
|
838
|
+
useEffect(() => controller.subscribe(setState), [controller]);
|
|
839
|
+
useEffect(() => {
|
|
840
|
+
const capacity = Math.max(1, dimensions.height - 12);
|
|
841
|
+
const previous = previousTranscriptSize.current;
|
|
842
|
+
const conversationChanged = previousConversationId.current !== state.conversationId;
|
|
843
|
+
previousTranscriptSize.current = transcriptUnits;
|
|
844
|
+
previousConversationId.current = state.conversationId;
|
|
845
|
+
setViewport((current) => {
|
|
846
|
+
if (conversationChanged || transcriptUnits < previous) {
|
|
847
|
+
return createTerminalFeedViewport2(transcriptUnits, capacity);
|
|
848
|
+
}
|
|
849
|
+
const appended = reduceTerminalFeedViewport2(current, {
|
|
850
|
+
type: "append",
|
|
851
|
+
count: transcriptUnits - previous
|
|
852
|
+
});
|
|
853
|
+
return reduceTerminalFeedViewport2(appended, { type: "resize", capacity });
|
|
854
|
+
});
|
|
855
|
+
}, [dimensions.height, state.conversationId, transcriptUnits]);
|
|
856
|
+
useEffect(() => {
|
|
857
|
+
if (dialog !== "sessions" || !conversations)
|
|
858
|
+
return;
|
|
859
|
+
conversations.list({ limit: 50 }).then((page) => {
|
|
860
|
+
setSessions(page.items);
|
|
861
|
+
setSessionCursor(page.nextCursor);
|
|
862
|
+
}).catch((error) => setLocalNotice(errorMessage(error)));
|
|
863
|
+
}, [conversations, dialog]);
|
|
864
|
+
const applyOutcome = useCallback(async (outcome) => {
|
|
865
|
+
if (outcome.type === "dialog") {
|
|
866
|
+
setDialog(isDialog(outcome.dialog) ? outcome.dialog : "help");
|
|
867
|
+
if (outcome.dialog === "model") {
|
|
868
|
+
setModelQuery(outcome.query ?? "");
|
|
869
|
+
setModelSearchFocused((outcome.query ?? "").length === 0);
|
|
870
|
+
}
|
|
871
|
+
return;
|
|
872
|
+
}
|
|
873
|
+
if (outcome.type === "notice") {
|
|
874
|
+
setLocalNotice(outcome.message);
|
|
875
|
+
return;
|
|
876
|
+
}
|
|
877
|
+
if (outcome.type === "submit") {
|
|
878
|
+
await controller.submit(outcome.text);
|
|
879
|
+
return;
|
|
880
|
+
}
|
|
881
|
+
if (outcome.action === "interrupt") {
|
|
882
|
+
await controller.interrupt();
|
|
883
|
+
} else if (outcome.action === "new-conversation") {
|
|
884
|
+
const conversationId = createAgentTuiConversationId2();
|
|
885
|
+
await controller.switchConversation(conversationId);
|
|
886
|
+
await onConversationChange(conversationId, "new");
|
|
887
|
+
setHiddenBefore(0);
|
|
888
|
+
} else if (outcome.action === "clear-conversation") {
|
|
889
|
+
const conversationId = createAgentTuiConversationId2();
|
|
890
|
+
await controller.switchConversation(conversationId);
|
|
891
|
+
await onConversationChange(conversationId, "clear");
|
|
892
|
+
setHiddenBefore(0);
|
|
893
|
+
} else if (outcome.action === "quit") {
|
|
894
|
+
await onExit();
|
|
895
|
+
}
|
|
896
|
+
}, [controller, onConversationChange, onExit]);
|
|
897
|
+
const submit = useCallback(async () => {
|
|
898
|
+
const withCurrentText = setAgentTuiDraft2(composer, composerRef.current?.plainText ?? composer.draft);
|
|
899
|
+
const submitted = submitAgentTuiComposer2(withCurrentText);
|
|
900
|
+
if (!submitted.text)
|
|
901
|
+
return;
|
|
902
|
+
const text = submitted.text;
|
|
903
|
+
const resolution = resolveTuiCommandSubmission2(text, commands, completionIndex, dismissedCompletionDraft === text);
|
|
904
|
+
try {
|
|
905
|
+
if (resolution.type === "prompt") {
|
|
906
|
+
await controller.submit(resolution.text);
|
|
907
|
+
} else {
|
|
908
|
+
const context = {
|
|
909
|
+
conversationId: state.conversationId,
|
|
910
|
+
...runId && { activeRunId: runId }
|
|
911
|
+
};
|
|
912
|
+
if (resolution.command.available && !resolution.command.available(context)) {
|
|
913
|
+
setLocalNotice(`/${resolution.command.name} is not available in the current state.`);
|
|
914
|
+
return;
|
|
915
|
+
}
|
|
916
|
+
await applyOutcome(await resolution.command.execute(resolution.argumentsText, context));
|
|
917
|
+
}
|
|
918
|
+
composerRef.current?.setText("");
|
|
919
|
+
setComposer(submitted.state);
|
|
920
|
+
setDismissedCompletionDraft(undefined);
|
|
921
|
+
} catch (error) {
|
|
922
|
+
setLocalNotice(error instanceof Error ? error.message : String(error));
|
|
923
|
+
}
|
|
924
|
+
}, [
|
|
925
|
+
applyOutcome,
|
|
926
|
+
commands,
|
|
927
|
+
completionIndex,
|
|
928
|
+
composer,
|
|
929
|
+
controller,
|
|
930
|
+
dismissedCompletionDraft,
|
|
931
|
+
runId,
|
|
932
|
+
state.conversationId
|
|
933
|
+
]);
|
|
934
|
+
useKeyboard((key) => {
|
|
935
|
+
if (isAgentTuiExitKey2(key)) {
|
|
936
|
+
Promise.resolve(onExit()).catch((error) => setLocalNotice(errorMessage(error)));
|
|
937
|
+
return;
|
|
938
|
+
}
|
|
939
|
+
if (state.pendingApproval && key.name === "y") {
|
|
940
|
+
controller.respondToApproval(true).catch((error) => setLocalNotice(errorMessage(error)));
|
|
941
|
+
return;
|
|
942
|
+
}
|
|
943
|
+
if (state.pendingApproval && (key.name === "n" || key.name === "escape")) {
|
|
944
|
+
controller.respondToApproval(false, "Denied from the terminal host").catch((error) => setLocalNotice(errorMessage(error)));
|
|
945
|
+
return;
|
|
946
|
+
}
|
|
947
|
+
if (dialog && key.name === "escape") {
|
|
948
|
+
setDialog(undefined);
|
|
949
|
+
return;
|
|
950
|
+
}
|
|
951
|
+
if (dialog === "model" && key.name === "tab") {
|
|
952
|
+
key.preventDefault();
|
|
953
|
+
key.stopPropagation();
|
|
954
|
+
setModelSearchFocused((focused) => !focused);
|
|
955
|
+
return;
|
|
956
|
+
}
|
|
957
|
+
if (!dialog && completions.length > 0 && key.name === "escape") {
|
|
958
|
+
key.preventDefault();
|
|
959
|
+
key.stopPropagation();
|
|
960
|
+
setDismissedCompletionDraft(draft);
|
|
961
|
+
return;
|
|
962
|
+
}
|
|
963
|
+
if (!dialog && completions.length > 0 && (key.name === "up" || key.name === "down")) {
|
|
964
|
+
key.preventDefault();
|
|
965
|
+
key.stopPropagation();
|
|
966
|
+
const direction = key.name === "up" ? -1 : 1;
|
|
967
|
+
setCompletionIndex((current) => moveCommandCompletionSelection2(current, direction === -1 ? "previous" : "next", completions.length));
|
|
968
|
+
return;
|
|
969
|
+
}
|
|
970
|
+
if (!dialog && key.name === "tab" && completions[0]) {
|
|
971
|
+
key.preventDefault();
|
|
972
|
+
key.stopPropagation();
|
|
973
|
+
const selected = completions[completionIndex] ?? completions[0];
|
|
974
|
+
const next = setAgentTuiDraft2(composer, `/${selected.name} `);
|
|
975
|
+
composerRef.current?.setText(next.draft);
|
|
976
|
+
setComposer(next);
|
|
977
|
+
setCompletionIndex(0);
|
|
978
|
+
setDismissedCompletionDraft(undefined);
|
|
979
|
+
return;
|
|
980
|
+
}
|
|
981
|
+
if (!dialog && key.name === "pageup") {
|
|
982
|
+
transcriptRef.current?.scrollBy(-0.8, "viewport");
|
|
983
|
+
setViewport((current) => reduceTerminalFeedViewport2(current, { type: "page", pages: -1 }));
|
|
984
|
+
}
|
|
985
|
+
if (!dialog && key.name === "pagedown") {
|
|
986
|
+
transcriptRef.current?.scrollBy(0.8, "viewport");
|
|
987
|
+
setViewport((current) => reduceTerminalFeedViewport2(current, { type: "page", pages: 1 }));
|
|
988
|
+
}
|
|
989
|
+
if (!dialog && key.option && (key.name === "up" || key.name === "down")) {
|
|
990
|
+
const lines = key.name === "up" ? -1 : 1;
|
|
991
|
+
transcriptRef.current?.scrollBy(lines, "step");
|
|
992
|
+
setViewport((current) => reduceTerminalFeedViewport2(current, { type: "scroll", lines }));
|
|
993
|
+
}
|
|
994
|
+
if (!dialog && key.name === "home" && key.ctrl) {
|
|
995
|
+
transcriptRef.current?.scrollTo(0);
|
|
996
|
+
setViewport((current) => reduceTerminalFeedViewport2(current, { type: "home" }));
|
|
997
|
+
}
|
|
998
|
+
if (!dialog && key.name === "end" && key.ctrl) {
|
|
999
|
+
transcriptRef.current?.scrollTo(Number.MAX_SAFE_INTEGER);
|
|
1000
|
+
setViewport((current) => reduceTerminalFeedViewport2(current, { type: "end" }));
|
|
1001
|
+
}
|
|
1002
|
+
if (!dialog && key.ctrl && (key.name === "up" || key.name === "down")) {
|
|
1003
|
+
const next = navigateAgentTuiHistory2(composer, key.name === "up" ? "older" : "newer");
|
|
1004
|
+
composerRef.current?.setText(next.draft);
|
|
1005
|
+
setComposer(next);
|
|
1006
|
+
}
|
|
1007
|
+
});
|
|
1008
|
+
const visibleModels = searchAgentTuiModels2(catalog, modelQuery);
|
|
1009
|
+
const modelOptions = visibleModels.models.map((model) => {
|
|
1010
|
+
const coding = model.metrics.find(({ metric }) => metric === "coding");
|
|
1011
|
+
const evidence = coding ?? model.popularity;
|
|
1012
|
+
return {
|
|
1013
|
+
name: model.name,
|
|
1014
|
+
description: `${model.id} \xB7 ${formatContext(model.descriptor.contextWindow)} \xB7 #${model.popularity?.rank ?? "\u2014"} weekly${coding ? ` \xB7 coding ${coding.value}` : ""}${evidence ? ` \xB7 ${evidence.source} @ ${evidence.observedAt.slice(0, 10)}` : ""}`
|
|
1015
|
+
};
|
|
1016
|
+
});
|
|
1017
|
+
const selectedModelIndex = Math.max(0, visibleModels.models.findIndex(({ id }) => id === state.selectedModelId));
|
|
1018
|
+
return /* @__PURE__ */ jsxs("box", {
|
|
1019
|
+
style: {
|
|
1020
|
+
width: "100%",
|
|
1021
|
+
height: "100%",
|
|
1022
|
+
flexDirection: "column"
|
|
1023
|
+
},
|
|
1024
|
+
children: [
|
|
1025
|
+
/* @__PURE__ */ jsxs("box", {
|
|
1026
|
+
style: {
|
|
1027
|
+
height: 1,
|
|
1028
|
+
paddingLeft: compact ? 1 : 2,
|
|
1029
|
+
paddingRight: compact ? 1 : 2,
|
|
1030
|
+
alignItems: "center",
|
|
1031
|
+
flexDirection: "row"
|
|
1032
|
+
},
|
|
1033
|
+
children: [
|
|
1034
|
+
/* @__PURE__ */ jsx("text", {
|
|
1035
|
+
fg: theme.accent,
|
|
1036
|
+
children: /* @__PURE__ */ jsxs("strong", {
|
|
1037
|
+
children: [
|
|
1038
|
+
"\u25C6 ",
|
|
1039
|
+
title
|
|
1040
|
+
]
|
|
1041
|
+
})
|
|
1042
|
+
}),
|
|
1043
|
+
!compact ? /* @__PURE__ */ jsxs("text", {
|
|
1044
|
+
fg: theme.muted,
|
|
1045
|
+
children: [
|
|
1046
|
+
" \xB7 ",
|
|
1047
|
+
selectedModel?.name ?? state.selectedModelId
|
|
1048
|
+
]
|
|
1049
|
+
}) : null
|
|
1050
|
+
]
|
|
1051
|
+
}),
|
|
1052
|
+
/* @__PURE__ */ jsxs("scrollbox", {
|
|
1053
|
+
ref: transcriptRef,
|
|
1054
|
+
focused: !dialog && !state.pendingApproval,
|
|
1055
|
+
stickyScroll: viewport.followTail,
|
|
1056
|
+
stickyStart: "bottom",
|
|
1057
|
+
style: {
|
|
1058
|
+
flexGrow: 1,
|
|
1059
|
+
paddingLeft: compact ? 1 : 2,
|
|
1060
|
+
paddingRight: compact ? 1 : 2,
|
|
1061
|
+
paddingTop: 1,
|
|
1062
|
+
contentOptions: { flexDirection: "column" },
|
|
1063
|
+
scrollbarOptions: { visible: !compact }
|
|
1064
|
+
},
|
|
1065
|
+
children: [
|
|
1066
|
+
entries.length === 0 ? /* @__PURE__ */ jsxs("box", {
|
|
1067
|
+
style: { flexDirection: "column", paddingTop: 1 },
|
|
1068
|
+
children: [
|
|
1069
|
+
/* @__PURE__ */ jsx("text", {
|
|
1070
|
+
fg: theme.primary,
|
|
1071
|
+
children: /* @__PURE__ */ jsx("strong", {
|
|
1072
|
+
children: "What do you want to build?"
|
|
1073
|
+
})
|
|
1074
|
+
}),
|
|
1075
|
+
/* @__PURE__ */ jsx("text", {
|
|
1076
|
+
fg: theme.muted,
|
|
1077
|
+
children: "Type / for commands"
|
|
1078
|
+
})
|
|
1079
|
+
]
|
|
1080
|
+
}) : entries.map((entry) => /* @__PURE__ */ jsxs("box", {
|
|
1081
|
+
style: { flexDirection: "column", marginBottom: 1 },
|
|
1082
|
+
children: [
|
|
1083
|
+
/* @__PURE__ */ jsx("text", {
|
|
1084
|
+
fg: entry.role === "you" ? theme.accent : theme.muted,
|
|
1085
|
+
children: /* @__PURE__ */ jsx("strong", {
|
|
1086
|
+
children: roleLabel(entry.role)
|
|
1087
|
+
})
|
|
1088
|
+
}),
|
|
1089
|
+
/* @__PURE__ */ jsx("text", {
|
|
1090
|
+
fg: theme[entry.tone],
|
|
1091
|
+
children: entry.text
|
|
1092
|
+
})
|
|
1093
|
+
]
|
|
1094
|
+
}, entry.id)),
|
|
1095
|
+
Object.entries(state.streaming).map(([streamRunId, text]) => /* @__PURE__ */ jsxs("box", {
|
|
1096
|
+
style: { flexDirection: "column", marginBottom: 1 },
|
|
1097
|
+
children: [
|
|
1098
|
+
/* @__PURE__ */ jsx("text", {
|
|
1099
|
+
fg: theme.muted,
|
|
1100
|
+
children: /* @__PURE__ */ jsx("strong", {
|
|
1101
|
+
children: "AGENT \xB7 STREAMING"
|
|
1102
|
+
})
|
|
1103
|
+
}),
|
|
1104
|
+
/* @__PURE__ */ jsx("text", {
|
|
1105
|
+
fg: theme.primary,
|
|
1106
|
+
children: text
|
|
1107
|
+
})
|
|
1108
|
+
]
|
|
1109
|
+
}, streamRunId))
|
|
1110
|
+
]
|
|
1111
|
+
}),
|
|
1112
|
+
state.pendingApproval ? /* @__PURE__ */ jsxs("box", {
|
|
1113
|
+
title: " APPROVAL ",
|
|
1114
|
+
titleColor: theme.warning,
|
|
1115
|
+
style: {
|
|
1116
|
+
height: 7,
|
|
1117
|
+
marginLeft: compact ? 0 : 2,
|
|
1118
|
+
marginRight: compact ? 0 : 2,
|
|
1119
|
+
border: true,
|
|
1120
|
+
borderColor: theme.warning,
|
|
1121
|
+
backgroundColor: theme.panelRaised,
|
|
1122
|
+
padding: 1,
|
|
1123
|
+
flexDirection: "column"
|
|
1124
|
+
},
|
|
1125
|
+
children: [
|
|
1126
|
+
/* @__PURE__ */ jsx("text", {
|
|
1127
|
+
fg: theme.primary,
|
|
1128
|
+
children: /* @__PURE__ */ jsx("strong", {
|
|
1129
|
+
children: state.pendingApproval.toolName
|
|
1130
|
+
})
|
|
1131
|
+
}),
|
|
1132
|
+
/* @__PURE__ */ jsx("text", {
|
|
1133
|
+
fg: theme.muted,
|
|
1134
|
+
children: JSON.stringify(state.pendingApproval.input).slice(0, 240)
|
|
1135
|
+
}),
|
|
1136
|
+
/* @__PURE__ */ jsx("text", {
|
|
1137
|
+
fg: theme.warning,
|
|
1138
|
+
children: "Y approve once \xB7 N / Esc deny"
|
|
1139
|
+
})
|
|
1140
|
+
]
|
|
1141
|
+
}) : /* @__PURE__ */ jsxs("box", {
|
|
1142
|
+
style: { flexDirection: "column" },
|
|
1143
|
+
children: [
|
|
1144
|
+
completions.length > 0 ? /* @__PURE__ */ jsx("box", {
|
|
1145
|
+
style: {
|
|
1146
|
+
maxHeight: 7,
|
|
1147
|
+
marginLeft: compact ? 1 : 2,
|
|
1148
|
+
marginRight: compact ? 1 : 2,
|
|
1149
|
+
border: ["bottom"],
|
|
1150
|
+
borderColor: theme.border,
|
|
1151
|
+
flexDirection: "column"
|
|
1152
|
+
},
|
|
1153
|
+
children: completions.map((command, index) => /* @__PURE__ */ jsx("box", {
|
|
1154
|
+
style: {
|
|
1155
|
+
paddingLeft: 1,
|
|
1156
|
+
...index === completionIndex && {
|
|
1157
|
+
backgroundColor: theme.panelRaised
|
|
1158
|
+
}
|
|
1159
|
+
},
|
|
1160
|
+
children: /* @__PURE__ */ jsxs("text", {
|
|
1161
|
+
fg: index === completionIndex ? theme.primary : theme.muted,
|
|
1162
|
+
children: [
|
|
1163
|
+
/* @__PURE__ */ jsxs("span", {
|
|
1164
|
+
fg: theme.accent,
|
|
1165
|
+
children: [
|
|
1166
|
+
index === completionIndex ? "\u203A" : " ",
|
|
1167
|
+
" /",
|
|
1168
|
+
command.name
|
|
1169
|
+
]
|
|
1170
|
+
}),
|
|
1171
|
+
" ",
|
|
1172
|
+
command.description
|
|
1173
|
+
]
|
|
1174
|
+
})
|
|
1175
|
+
}, command.name))
|
|
1176
|
+
}) : null,
|
|
1177
|
+
/* @__PURE__ */ jsxs("box", {
|
|
1178
|
+
style: {
|
|
1179
|
+
height: 3,
|
|
1180
|
+
marginLeft: compact ? 1 : 2,
|
|
1181
|
+
marginRight: compact ? 1 : 2,
|
|
1182
|
+
border: ["top", "bottom"],
|
|
1183
|
+
borderColor: dialog ? theme.border : theme.borderActive,
|
|
1184
|
+
paddingLeft: 1,
|
|
1185
|
+
paddingRight: 1,
|
|
1186
|
+
flexDirection: "row"
|
|
1187
|
+
},
|
|
1188
|
+
children: [
|
|
1189
|
+
/* @__PURE__ */ jsx("text", {
|
|
1190
|
+
fg: dialog ? theme.muted : theme.accent,
|
|
1191
|
+
children: "\u203A "
|
|
1192
|
+
}),
|
|
1193
|
+
/* @__PURE__ */ jsx("textarea", {
|
|
1194
|
+
ref: composerRef,
|
|
1195
|
+
focused: !dialog,
|
|
1196
|
+
placeholder: "Message the agent or type / for commands\u2026",
|
|
1197
|
+
initialValue: draft,
|
|
1198
|
+
wrapMode: "word",
|
|
1199
|
+
keyBindings: [
|
|
1200
|
+
{ name: "return", action: "submit" },
|
|
1201
|
+
{ name: "return", shift: true, action: "newline" }
|
|
1202
|
+
],
|
|
1203
|
+
onContentChange: () => {
|
|
1204
|
+
const text = composerRef.current?.plainText ?? "";
|
|
1205
|
+
setComposer((current) => setAgentTuiDraft2(current, text));
|
|
1206
|
+
setCompletionIndex(0);
|
|
1207
|
+
setDismissedCompletionDraft(undefined);
|
|
1208
|
+
},
|
|
1209
|
+
onSubmit: () => void submit(),
|
|
1210
|
+
style: { width: "100%", height: "100%" }
|
|
1211
|
+
})
|
|
1212
|
+
]
|
|
1213
|
+
})
|
|
1214
|
+
]
|
|
1215
|
+
}),
|
|
1216
|
+
localNotice || state.notice || viewport.unseen > 0 ? /* @__PURE__ */ jsx("box", {
|
|
1217
|
+
style: { height: 1, paddingLeft: compact ? 1 : 2, paddingRight: 1 },
|
|
1218
|
+
children: /* @__PURE__ */ jsx("text", {
|
|
1219
|
+
fg: localNotice || state.notice ? theme.danger : theme.accent,
|
|
1220
|
+
children: localNotice ?? state.notice?.message ?? `${viewport.unseen} new messages`
|
|
1221
|
+
})
|
|
1222
|
+
}) : null,
|
|
1223
|
+
statusRows.length > 0 ? /* @__PURE__ */ jsx("box", {
|
|
1224
|
+
style: {
|
|
1225
|
+
height: statusRows.length,
|
|
1226
|
+
paddingLeft: compact ? 1 : 2,
|
|
1227
|
+
paddingRight: 1,
|
|
1228
|
+
flexDirection: "column"
|
|
1229
|
+
},
|
|
1230
|
+
children: statusRows.map((row, rowIndex) => /* @__PURE__ */ jsx("text", {
|
|
1231
|
+
children: row.map((segment, segmentIndex) => /* @__PURE__ */ jsxs("span", {
|
|
1232
|
+
fg: theme[segment.tone ?? "primary"],
|
|
1233
|
+
bg: segmentIndex % 2 === 0 ? theme.panel : theme.panelRaised,
|
|
1234
|
+
children: [
|
|
1235
|
+
" ",
|
|
1236
|
+
segment.text,
|
|
1237
|
+
" "
|
|
1238
|
+
]
|
|
1239
|
+
}, `${segment.text}-${segmentIndex}`))
|
|
1240
|
+
}, `status-${rowIndex}`))
|
|
1241
|
+
}) : null,
|
|
1242
|
+
dialog ? /* @__PURE__ */ jsxs("box", {
|
|
1243
|
+
title: ` ${dialog.toUpperCase()} `,
|
|
1244
|
+
titleColor: theme.accent,
|
|
1245
|
+
style: {
|
|
1246
|
+
position: "absolute",
|
|
1247
|
+
left: compact ? 1 : Math.max(4, Math.floor(dimensions.width * 0.12)),
|
|
1248
|
+
right: compact ? 1 : Math.max(4, Math.floor(dimensions.width * 0.12)),
|
|
1249
|
+
top: compact ? 2 : 4,
|
|
1250
|
+
bottom: compact ? 2 : 4,
|
|
1251
|
+
border: true,
|
|
1252
|
+
borderColor: theme.borderActive,
|
|
1253
|
+
backgroundColor: theme.panelRaised,
|
|
1254
|
+
padding: 1,
|
|
1255
|
+
flexDirection: "column"
|
|
1256
|
+
},
|
|
1257
|
+
children: [
|
|
1258
|
+
dialog === "model" ? /* @__PURE__ */ jsxs("box", {
|
|
1259
|
+
style: { flexDirection: "column", width: "100%", height: "100%" },
|
|
1260
|
+
children: [
|
|
1261
|
+
/* @__PURE__ */ jsxs("text", {
|
|
1262
|
+
fg: theme.muted,
|
|
1263
|
+
children: [
|
|
1264
|
+
"Search the full catalog \xB7 showing ",
|
|
1265
|
+
visibleModels.models.length,
|
|
1266
|
+
" of",
|
|
1267
|
+
" ",
|
|
1268
|
+
visibleModels.total,
|
|
1269
|
+
" matches \xB7 Tab switches search/list"
|
|
1270
|
+
]
|
|
1271
|
+
}),
|
|
1272
|
+
/* @__PURE__ */ jsx("box", {
|
|
1273
|
+
style: {
|
|
1274
|
+
height: 3,
|
|
1275
|
+
border: true,
|
|
1276
|
+
borderColor: modelSearchFocused ? theme.borderActive : theme.border,
|
|
1277
|
+
paddingLeft: 1,
|
|
1278
|
+
paddingRight: 1
|
|
1279
|
+
},
|
|
1280
|
+
children: /* @__PURE__ */ jsx("input", {
|
|
1281
|
+
focused: modelSearchFocused,
|
|
1282
|
+
value: modelQuery,
|
|
1283
|
+
placeholder: "Filter by model, provider or capability\u2026",
|
|
1284
|
+
onInput: setModelQuery,
|
|
1285
|
+
onSubmit: () => setModelSearchFocused(false),
|
|
1286
|
+
style: { width: "100%" }
|
|
1287
|
+
})
|
|
1288
|
+
}),
|
|
1289
|
+
/* @__PURE__ */ jsx("select", {
|
|
1290
|
+
focused: !modelSearchFocused,
|
|
1291
|
+
options: modelOptions,
|
|
1292
|
+
selectedIndex: selectedModelIndex,
|
|
1293
|
+
showDescription: true,
|
|
1294
|
+
showScrollIndicator: true,
|
|
1295
|
+
wrapSelection: true,
|
|
1296
|
+
backgroundColor: theme.panelRaised,
|
|
1297
|
+
textColor: theme.primary,
|
|
1298
|
+
descriptionColor: theme.muted,
|
|
1299
|
+
selectedBackgroundColor: theme.accent,
|
|
1300
|
+
selectedTextColor: theme.canvas,
|
|
1301
|
+
selectedDescriptionColor: theme.canvas,
|
|
1302
|
+
style: { width: "100%", flexGrow: 1 },
|
|
1303
|
+
onSelect: (index) => {
|
|
1304
|
+
const model = visibleModels.models[index];
|
|
1305
|
+
if (!model)
|
|
1306
|
+
return;
|
|
1307
|
+
controller.selectModel(model.id).then(() => setDialog(undefined)).catch((error) => setLocalNotice(errorMessage(error)));
|
|
1308
|
+
}
|
|
1309
|
+
})
|
|
1310
|
+
]
|
|
1311
|
+
}) : dialog === "sessions" ? conversations ? /* @__PURE__ */ jsx("select", {
|
|
1312
|
+
focused: true,
|
|
1313
|
+
options: sessions.map((session) => ({
|
|
1314
|
+
name: session.conversationId,
|
|
1315
|
+
description: `${session.activeRuns > 0 ? `${session.activeRuns} active \xB7 ` : ""}${session.preview}`
|
|
1316
|
+
})),
|
|
1317
|
+
showDescription: true,
|
|
1318
|
+
showScrollIndicator: true,
|
|
1319
|
+
backgroundColor: theme.panelRaised,
|
|
1320
|
+
textColor: theme.primary,
|
|
1321
|
+
descriptionColor: theme.muted,
|
|
1322
|
+
selectedBackgroundColor: theme.accent,
|
|
1323
|
+
selectedTextColor: theme.canvas,
|
|
1324
|
+
selectedDescriptionColor: theme.canvas,
|
|
1325
|
+
style: { width: "100%", height: "100%" },
|
|
1326
|
+
onSelect: (index) => {
|
|
1327
|
+
const selected = sessions[index];
|
|
1328
|
+
if (!selected)
|
|
1329
|
+
return;
|
|
1330
|
+
controller.switchConversation(selected.conversationId).then(async () => {
|
|
1331
|
+
await onConversationChange(selected.conversationId, "resume");
|
|
1332
|
+
setDialog(undefined);
|
|
1333
|
+
setHiddenBefore(0);
|
|
1334
|
+
}).catch((error) => setLocalNotice(errorMessage(error)));
|
|
1335
|
+
}
|
|
1336
|
+
}) : /* @__PURE__ */ jsx("text", {
|
|
1337
|
+
fg: theme.muted,
|
|
1338
|
+
children: "This host does not provide a conversation catalog."
|
|
1339
|
+
}) : dialog === "help" ? /* @__PURE__ */ jsx("scrollbox", {
|
|
1340
|
+
focused: true,
|
|
1341
|
+
style: { flexGrow: 1, contentOptions: { flexDirection: "column" } },
|
|
1342
|
+
children: commands.map((command) => /* @__PURE__ */ jsxs("text", {
|
|
1343
|
+
fg: theme.primary,
|
|
1344
|
+
children: [
|
|
1345
|
+
/* @__PURE__ */ jsxs("span", {
|
|
1346
|
+
fg: theme.accent,
|
|
1347
|
+
children: [
|
|
1348
|
+
"/",
|
|
1349
|
+
command.name
|
|
1350
|
+
]
|
|
1351
|
+
}),
|
|
1352
|
+
" ",
|
|
1353
|
+
command.description
|
|
1354
|
+
]
|
|
1355
|
+
}, command.name))
|
|
1356
|
+
}) : dialog === "status" ? /* @__PURE__ */ jsxs("box", {
|
|
1357
|
+
style: { flexDirection: "column" },
|
|
1358
|
+
children: [
|
|
1359
|
+
/* @__PURE__ */ jsxs("text", {
|
|
1360
|
+
fg: theme.primary,
|
|
1361
|
+
children: [
|
|
1362
|
+
"Session ",
|
|
1363
|
+
sessionId
|
|
1364
|
+
]
|
|
1365
|
+
}),
|
|
1366
|
+
/* @__PURE__ */ jsxs("text", {
|
|
1367
|
+
fg: theme.primary,
|
|
1368
|
+
children: [
|
|
1369
|
+
"Conversation ",
|
|
1370
|
+
state.conversationId
|
|
1371
|
+
]
|
|
1372
|
+
}),
|
|
1373
|
+
/* @__PURE__ */ jsxs("text", {
|
|
1374
|
+
fg: theme.primary,
|
|
1375
|
+
children: [
|
|
1376
|
+
"Model ",
|
|
1377
|
+
state.selectedModelId
|
|
1378
|
+
]
|
|
1379
|
+
}),
|
|
1380
|
+
/* @__PURE__ */ jsxs("text", {
|
|
1381
|
+
fg: theme.primary,
|
|
1382
|
+
children: [
|
|
1383
|
+
"Run ",
|
|
1384
|
+
runId ?? "idle"
|
|
1385
|
+
]
|
|
1386
|
+
}),
|
|
1387
|
+
/* @__PURE__ */ jsx("text", {
|
|
1388
|
+
fg: theme.muted,
|
|
1389
|
+
children: "External clients submit through this host's controller."
|
|
1390
|
+
})
|
|
1391
|
+
]
|
|
1392
|
+
}) : dialog === "tools" ? /* @__PURE__ */ jsxs("box", {
|
|
1393
|
+
style: { flexDirection: "column" },
|
|
1394
|
+
children: [
|
|
1395
|
+
[
|
|
1396
|
+
...new Set(entries.filter(({ role }) => role === "tool").map(({ text }) => text.split(" ")[1]).filter(isString))
|
|
1397
|
+
].map((name) => /* @__PURE__ */ jsx("text", {
|
|
1398
|
+
fg: theme.primary,
|
|
1399
|
+
children: name
|
|
1400
|
+
}, name)),
|
|
1401
|
+
/* @__PURE__ */ jsx("text", {
|
|
1402
|
+
fg: theme.muted,
|
|
1403
|
+
children: "Direct tools retain their own durable identity."
|
|
1404
|
+
})
|
|
1405
|
+
]
|
|
1406
|
+
}) : dialog === "permissions" ? /* @__PURE__ */ jsxs("box", {
|
|
1407
|
+
style: { flexDirection: "column" },
|
|
1408
|
+
children: [
|
|
1409
|
+
/* @__PURE__ */ jsx("text", {
|
|
1410
|
+
fg: theme.primary,
|
|
1411
|
+
children: "Approval decisions are per exact tool call."
|
|
1412
|
+
}),
|
|
1413
|
+
/* @__PURE__ */ jsx("text", {
|
|
1414
|
+
fg: theme.muted,
|
|
1415
|
+
children: "Sandbox enforcement is supplied and reported by the embedding host."
|
|
1416
|
+
})
|
|
1417
|
+
]
|
|
1418
|
+
}) : /* @__PURE__ */ jsxs("box", {
|
|
1419
|
+
style: { flexDirection: "column" },
|
|
1420
|
+
children: [
|
|
1421
|
+
/* @__PURE__ */ jsx("text", {
|
|
1422
|
+
fg: theme.primary,
|
|
1423
|
+
children: "Skills and resources are discovered lazily by the harness."
|
|
1424
|
+
}),
|
|
1425
|
+
/* @__PURE__ */ jsx("text", {
|
|
1426
|
+
fg: theme.muted,
|
|
1427
|
+
children: "The model reads exact content through the direct read_resource tool."
|
|
1428
|
+
})
|
|
1429
|
+
]
|
|
1430
|
+
}),
|
|
1431
|
+
dialog === "sessions" && sessionCursor ? /* @__PURE__ */ jsx("text", {
|
|
1432
|
+
fg: theme.muted,
|
|
1433
|
+
children: "More conversations are available."
|
|
1434
|
+
}) : null,
|
|
1435
|
+
/* @__PURE__ */ jsx("text", {
|
|
1436
|
+
fg: theme.muted,
|
|
1437
|
+
children: "Esc close"
|
|
1438
|
+
})
|
|
1439
|
+
]
|
|
1440
|
+
}) : null
|
|
1441
|
+
]
|
|
1442
|
+
});
|
|
1443
|
+
}
|
|
1444
|
+
|
|
1445
|
+
// src/run.tsx
|
|
1446
|
+
import { jsx as jsx2 } from "@opentui/react/jsx-runtime";
|
|
1447
|
+
function runtimeContext(config) {
|
|
1448
|
+
return Promise.resolve(config.context());
|
|
1449
|
+
}
|
|
1450
|
+
function defaultAgentTuiRecoveryDecision2({
|
|
1451
|
+
run
|
|
1452
|
+
}) {
|
|
1453
|
+
return run.state === "queued" ? { action: "resume" } : { action: "skip" };
|
|
1454
|
+
}
|
|
1455
|
+
function resolveAgentTuiInitialConversationId2(initialConversationId) {
|
|
1456
|
+
return initialConversationId ?? createAgentTuiConversationId2();
|
|
1457
|
+
}
|
|
1458
|
+
async function runAgentTui2(config) {
|
|
1459
|
+
const workspace = path4.resolve(config.workspace ?? process.cwd());
|
|
1460
|
+
const sessionId = createAgentTuiSessionId2();
|
|
1461
|
+
const initialConversationId = resolveAgentTuiInitialConversationId2(config.initialConversationId);
|
|
1462
|
+
const diagnostics = await createAgentTuiDiagnosticRecorder2({ workspace, sessionId });
|
|
1463
|
+
const catalog = await config.modelCatalog.load();
|
|
1464
|
+
const selections = createFileAgentModelSelectionStore2(workspace);
|
|
1465
|
+
const bundle = await config.createRuntime({ catalog, selections, diagnostics });
|
|
1466
|
+
await bundle.harness.recover({
|
|
1467
|
+
resolveContext: () => runtimeContext(config),
|
|
1468
|
+
decide: config.recover ?? defaultAgentTuiRecoveryDecision2
|
|
1469
|
+
});
|
|
1470
|
+
const controller = await createAgentTuiController2({
|
|
1471
|
+
harness: bundle.harness,
|
|
1472
|
+
catalog,
|
|
1473
|
+
selections,
|
|
1474
|
+
conversationId: initialConversationId,
|
|
1475
|
+
context: () => runtimeContext(config),
|
|
1476
|
+
...config.preferredModelId && { preferredModelId: config.preferredModelId },
|
|
1477
|
+
onDiagnostic: ({ conversationId, runId, event }) => diagnostics.write({ conversationId, ...runId && { runId }, event })
|
|
1478
|
+
});
|
|
1479
|
+
const handle = async (request) => {
|
|
1480
|
+
try {
|
|
1481
|
+
if (request.operation === "submit") {
|
|
1482
|
+
const runId = await controller.submit(request.text, request.idempotencyKey);
|
|
1483
|
+
diagnostics.record({
|
|
1484
|
+
schemaVersion: 1,
|
|
1485
|
+
occurredAt: new Date().toISOString(),
|
|
1486
|
+
type: "submission-admitted",
|
|
1487
|
+
sessionId,
|
|
1488
|
+
conversationId: controller.state().conversationId,
|
|
1489
|
+
runId,
|
|
1490
|
+
source: "client"
|
|
1491
|
+
});
|
|
1492
|
+
return {
|
|
1493
|
+
requestId: request.requestId,
|
|
1494
|
+
outcome: "ok",
|
|
1495
|
+
sessionId,
|
|
1496
|
+
conversationId: controller.state().conversationId,
|
|
1497
|
+
runId
|
|
1498
|
+
};
|
|
1499
|
+
}
|
|
1500
|
+
if (request.operation === "interrupt")
|
|
1501
|
+
await controller.interrupt(request.runId);
|
|
1502
|
+
const activeRunId = controller.state().snapshot.runs.find(({ state }) => state === "running" || state === "interrupt_requested")?.id;
|
|
1503
|
+
return {
|
|
1504
|
+
requestId: request.requestId,
|
|
1505
|
+
outcome: "ok",
|
|
1506
|
+
sessionId,
|
|
1507
|
+
conversationId: controller.state().conversationId,
|
|
1508
|
+
...activeRunId && { runId: activeRunId }
|
|
1509
|
+
};
|
|
1510
|
+
} catch {
|
|
1511
|
+
diagnostics.record({
|
|
1512
|
+
schemaVersion: 1,
|
|
1513
|
+
occurredAt: new Date().toISOString(),
|
|
1514
|
+
type: "request-failed",
|
|
1515
|
+
sessionId,
|
|
1516
|
+
operation: request.operation
|
|
1517
|
+
});
|
|
1518
|
+
return {
|
|
1519
|
+
requestId: request.requestId,
|
|
1520
|
+
outcome: "error",
|
|
1521
|
+
error: {
|
|
1522
|
+
code: "REQUEST_FAILED",
|
|
1523
|
+
message: "The terminal host could not complete the request"
|
|
1524
|
+
}
|
|
1525
|
+
};
|
|
1526
|
+
}
|
|
1527
|
+
};
|
|
1528
|
+
const host = await startAgentTuiSessionHost2({
|
|
1529
|
+
rootDirectory: workspace,
|
|
1530
|
+
conversationId: initialConversationId,
|
|
1531
|
+
sessionId,
|
|
1532
|
+
handle
|
|
1533
|
+
});
|
|
1534
|
+
let hostConversationId = initialConversationId;
|
|
1535
|
+
diagnostics.record({
|
|
1536
|
+
schemaVersion: 1,
|
|
1537
|
+
occurredAt: new Date().toISOString(),
|
|
1538
|
+
type: "host-started",
|
|
1539
|
+
sessionId,
|
|
1540
|
+
conversationId: initialConversationId,
|
|
1541
|
+
launchMode: config.initialConversationId === undefined ? "fresh" : "explicit"
|
|
1542
|
+
});
|
|
1543
|
+
const renderer = await createCliRenderer({ exitOnCtrlC: false });
|
|
1544
|
+
const themeMode = config.themeMode === undefined || config.themeMode === "auto" ? await renderer.waitForThemeMode(250) ?? "dark" : config.themeMode;
|
|
1545
|
+
const root = createRoot(renderer);
|
|
1546
|
+
let closing;
|
|
1547
|
+
const onSignal = () => void close();
|
|
1548
|
+
const close = () => {
|
|
1549
|
+
if (closing)
|
|
1550
|
+
return closing;
|
|
1551
|
+
process.off("SIGINT", onSignal);
|
|
1552
|
+
process.off("SIGTERM", onSignal);
|
|
1553
|
+
renderer.destroy();
|
|
1554
|
+
closing = (async () => {
|
|
1555
|
+
try {
|
|
1556
|
+
diagnostics.record({
|
|
1557
|
+
schemaVersion: 1,
|
|
1558
|
+
occurredAt: new Date().toISOString(),
|
|
1559
|
+
type: "host-closed",
|
|
1560
|
+
sessionId,
|
|
1561
|
+
conversationId: controller.state().conversationId
|
|
1562
|
+
});
|
|
1563
|
+
await host.close();
|
|
1564
|
+
await controller.close();
|
|
1565
|
+
} finally {
|
|
1566
|
+
await diagnostics.close();
|
|
1567
|
+
renderer.destroy();
|
|
1568
|
+
}
|
|
1569
|
+
})();
|
|
1570
|
+
return closing;
|
|
1571
|
+
};
|
|
1572
|
+
root.render(/* @__PURE__ */ jsx2(AgentTuiApp, {
|
|
1573
|
+
controller,
|
|
1574
|
+
catalog,
|
|
1575
|
+
...bundle.conversations && { conversations: bundle.conversations },
|
|
1576
|
+
...config.commands && { commands: config.commands },
|
|
1577
|
+
theme: resolveTerminalPalette2(themeMode, config.theme),
|
|
1578
|
+
workspace,
|
|
1579
|
+
...config.statusLine !== undefined && { statusLine: config.statusLine },
|
|
1580
|
+
sessionId: host.sessionId,
|
|
1581
|
+
title: config.title ?? "Stitchkit agent",
|
|
1582
|
+
onConversationChange: async (conversationId, reason) => {
|
|
1583
|
+
const previousConversationId = hostConversationId;
|
|
1584
|
+
await host.setConversationId(conversationId);
|
|
1585
|
+
hostConversationId = conversationId;
|
|
1586
|
+
diagnostics.record({
|
|
1587
|
+
schemaVersion: 1,
|
|
1588
|
+
occurredAt: new Date().toISOString(),
|
|
1589
|
+
type: "conversation-changed",
|
|
1590
|
+
sessionId,
|
|
1591
|
+
previousConversationId,
|
|
1592
|
+
conversationId,
|
|
1593
|
+
reason
|
|
1594
|
+
});
|
|
1595
|
+
},
|
|
1596
|
+
onExit: close
|
|
1597
|
+
}));
|
|
1598
|
+
process.once("SIGINT", onSignal);
|
|
1599
|
+
process.once("SIGTERM", onSignal);
|
|
1600
|
+
return { sessionId: host.sessionId, close };
|
|
1601
|
+
}
|
|
1602
|
+
|
|
1603
|
+
export { AgentTuiCommandOutcomeSchema2, defineTuiCommand2, composeTuiCommands2, resolveTuiCommand2, commandCompletions2, selectedCommandCompletion2, moveCommandCompletionSelection2, resolveTuiCommandSubmission2, AgentTuiComposerSchema2, createAgentTuiComposer2, setAgentTuiDraft2, submitAgentTuiComposer2, navigateAgentTuiHistory2, defineAgentTui2, createFileAgentModelSelectionStore2, createAgentTuiController2, AgentTuiDiagnosticEventSchema2, projectAgentTuiRuntimeDiagnostic2, createAgentTuiDiagnosticRecorder2, isAgentTuiExitKey2, AGENT_TUI_MODEL_RESULT_LIMIT2, searchAgentTuiModels2, defaultAgentTuiStatusLine2, projectAgentTuiTranscript2, defaultAgentTuiRecoveryDecision2, resolveAgentTuiInitialConversationId2, runAgentTui2 };
|