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
package/dist/cli.js
CHANGED
|
@@ -1,2206 +1,20 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
+
import {
|
|
4
|
+
listAgentTuiSessions2,
|
|
5
|
+
createAgentTuiClient2
|
|
6
|
+
} from "./index-ecpc5qkb.js";
|
|
3
7
|
|
|
4
8
|
// src/cli.ts
|
|
5
|
-
import path6 from "path";
|
|
6
|
-
import { pathToFileURL } from "url";
|
|
7
|
-
|
|
8
|
-
// src/run.tsx
|
|
9
|
-
import path5 from "path";
|
|
10
|
-
import { createCliRenderer } from "@opentui/core";
|
|
11
|
-
import { createRoot } from "@opentui/react";
|
|
12
|
-
|
|
13
|
-
// src/App.tsx
|
|
14
|
-
import { useKeyboard, useTerminalDimensions } from "@opentui/react";
|
|
15
|
-
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
|
16
|
-
|
|
17
|
-
// src/commands.ts
|
|
18
|
-
import { z as z2 } from "zod";
|
|
19
|
-
|
|
20
|
-
// src/core/command-palette.ts
|
|
21
|
-
import { z } from "zod";
|
|
22
|
-
var TerminalCommandDescriptorSchema = z.object({
|
|
23
|
-
id: z.string().regex(/^[a-z][a-z0-9-]*$/),
|
|
24
|
-
aliases: z.array(z.string().min(1)).default([]),
|
|
25
|
-
label: z.string().min(1),
|
|
26
|
-
description: z.string().default("")
|
|
27
|
-
}).strict();
|
|
28
|
-
var TerminalCommandPaletteStateSchema = z.object({
|
|
29
|
-
query: z.string(),
|
|
30
|
-
selectedIndex: z.int().nonnegative(),
|
|
31
|
-
dismissed: z.boolean()
|
|
32
|
-
}).strict();
|
|
33
|
-
function validateTerminalCommands(commands) {
|
|
34
|
-
const parsed = commands.map((command) => TerminalCommandDescriptorSchema.parse(command));
|
|
35
|
-
const owners = new Map;
|
|
36
|
-
for (const command of parsed) {
|
|
37
|
-
for (const name of [command.id, ...command.aliases]) {
|
|
38
|
-
const owner = owners.get(name);
|
|
39
|
-
if (owner)
|
|
40
|
-
throw new Error(`Terminal command ${name} collides with ${owner}`);
|
|
41
|
-
owners.set(name, command.id);
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
return parsed;
|
|
45
|
-
}
|
|
46
|
-
function createTerminalCommandPalette() {
|
|
47
|
-
return { query: "", selectedIndex: 0, dismissed: false };
|
|
48
|
-
}
|
|
49
|
-
function setTerminalCommandQuery(state, query) {
|
|
50
|
-
TerminalCommandPaletteStateSchema.parse(state);
|
|
51
|
-
return { query, selectedIndex: 0, dismissed: false };
|
|
52
|
-
}
|
|
53
|
-
function dismissTerminalCommandPalette(state) {
|
|
54
|
-
return { ...TerminalCommandPaletteStateSchema.parse(state), dismissed: true };
|
|
55
|
-
}
|
|
56
|
-
function terminalCommandMatches(state, commands, limit = 20) {
|
|
57
|
-
const current = TerminalCommandPaletteStateSchema.parse(state);
|
|
58
|
-
if (current.dismissed)
|
|
59
|
-
return [];
|
|
60
|
-
const parsed = validateTerminalCommands(commands);
|
|
61
|
-
const query = current.query.toLowerCase();
|
|
62
|
-
return parsed.filter((command) => command.id.includes(query) || command.label.toLowerCase().includes(query) || command.aliases.some((alias) => alias.includes(query))).slice(0, z.int().positive().parse(limit));
|
|
63
|
-
}
|
|
64
|
-
function moveTerminalCommandSelection(state, delta, matchCount) {
|
|
65
|
-
const current = TerminalCommandPaletteStateSchema.parse(state);
|
|
66
|
-
if (matchCount <= 0)
|
|
67
|
-
return { ...current, selectedIndex: 0 };
|
|
68
|
-
return {
|
|
69
|
-
...current,
|
|
70
|
-
selectedIndex: ((current.selectedIndex + delta) % matchCount + matchCount) % matchCount
|
|
71
|
-
};
|
|
72
|
-
}
|
|
73
|
-
function selectedTerminalCommand(state, commands, limit = 20) {
|
|
74
|
-
const matches = terminalCommandMatches(state, commands, limit);
|
|
75
|
-
return matches[state.selectedIndex] ?? matches[0];
|
|
76
|
-
}
|
|
77
|
-
function resolveExactTerminalCommand(name, commands) {
|
|
78
|
-
return validateTerminalCommands(commands).find((command) => command.id === name || command.aliases.includes(name));
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
// src/commands.ts
|
|
82
|
-
var AgentTuiCommandOutcomeSchema = z2.discriminatedUnion("type", [
|
|
83
|
-
z2.object({ type: z2.literal("submit"), text: z2.string().min(1) }).strict(),
|
|
84
|
-
z2.object({
|
|
85
|
-
type: z2.literal("dialog"),
|
|
86
|
-
dialog: z2.string().min(1),
|
|
87
|
-
query: z2.string().optional()
|
|
88
|
-
}).strict(),
|
|
89
|
-
z2.object({ type: z2.literal("notice"), message: z2.string() }).strict(),
|
|
90
|
-
z2.object({ type: z2.literal("action"), action: z2.string().min(1) }).strict()
|
|
91
|
-
]);
|
|
92
|
-
function defineTuiCommand(command) {
|
|
93
|
-
if (!/^[a-z][a-z0-9-]*$/.test(command.name)) {
|
|
94
|
-
throw new Error("TUI command names use lowercase letters, digits and hyphens");
|
|
95
|
-
}
|
|
96
|
-
for (const alias of command.aliases ?? []) {
|
|
97
|
-
if (alias !== "?" && !/^[a-z][a-z0-9-]*$/.test(alias)) {
|
|
98
|
-
throw new Error("TUI command aliases are invalid");
|
|
99
|
-
}
|
|
100
|
-
}
|
|
101
|
-
return command;
|
|
102
|
-
}
|
|
103
|
-
function composeTuiCommands(...groups) {
|
|
104
|
-
const commands = groups.flat();
|
|
105
|
-
validateTerminalCommands(commands.map((command) => ({
|
|
106
|
-
id: defineTuiCommand(command).name,
|
|
107
|
-
aliases: [...command.aliases ?? []],
|
|
108
|
-
label: command.name,
|
|
109
|
-
description: command.description
|
|
110
|
-
})));
|
|
111
|
-
return commands;
|
|
112
|
-
}
|
|
113
|
-
function resolveTuiCommand(text, commands) {
|
|
114
|
-
if (!text.startsWith("/"))
|
|
115
|
-
return { type: "prompt", text };
|
|
116
|
-
const match = /^\/([^\s]+)(?:\s+([\s\S]*))?$/.exec(text);
|
|
117
|
-
const name = match?.[1];
|
|
118
|
-
if (!name)
|
|
119
|
-
return { type: "prompt", text };
|
|
120
|
-
const command = commands.find((candidate) => candidate.name === name || candidate.aliases?.includes(name));
|
|
121
|
-
return command ? { type: "command", command, argumentsText: match?.[2] ?? "" } : { type: "prompt", text };
|
|
122
|
-
}
|
|
123
|
-
function commandCompletions(text, commands) {
|
|
124
|
-
if (!text.startsWith("/") || text.slice(1).includes(" "))
|
|
125
|
-
return [];
|
|
126
|
-
const state = setTerminalCommandQuery(createTerminalCommandPalette(), text.slice(1));
|
|
127
|
-
const descriptors = terminalCommandMatches(state, commands.map((command) => ({
|
|
128
|
-
id: command.name,
|
|
129
|
-
aliases: [...command.aliases ?? []],
|
|
130
|
-
label: command.name,
|
|
131
|
-
description: command.description
|
|
132
|
-
})), Math.max(1, commands.length));
|
|
133
|
-
return descriptors.map((descriptor) => commands.find((command) => command.name === descriptor.id)).filter((command) => command !== undefined);
|
|
134
|
-
}
|
|
135
|
-
function selectedCommandCompletion(text, commands, selectedIndex) {
|
|
136
|
-
const completions = commandCompletions(text, commands);
|
|
137
|
-
return completions[selectedIndex] ?? completions[0];
|
|
138
|
-
}
|
|
139
|
-
function moveCommandCompletionSelection(selectedIndex, direction, completionCount) {
|
|
140
|
-
if (completionCount <= 0)
|
|
141
|
-
return 0;
|
|
142
|
-
return moveTerminalCommandSelection({ query: "", selectedIndex, dismissed: false }, direction === "previous" ? -1 : 1, completionCount).selectedIndex;
|
|
143
|
-
}
|
|
144
|
-
function resolveTuiCommandSubmission(text, commands, selectedIndex, paletteDismissed = false) {
|
|
145
|
-
const completion = paletteDismissed ? undefined : selectedCommandCompletion(text, commands, selectedIndex);
|
|
146
|
-
return resolveTuiCommand(completion ? `/${completion.name}` : text, commands);
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
// src/builtins.ts
|
|
150
|
-
var dialog = (name, query) => ({
|
|
151
|
-
type: "dialog",
|
|
152
|
-
dialog: name,
|
|
153
|
-
...query && { query }
|
|
154
|
-
});
|
|
155
|
-
var action = (name) => ({ type: "action", action: name });
|
|
156
|
-
function createAgentTuiBuiltinCommands() {
|
|
157
|
-
return [
|
|
158
|
-
defineTuiCommand({
|
|
159
|
-
name: "help",
|
|
160
|
-
aliases: ["?"],
|
|
161
|
-
description: "Show available terminal commands",
|
|
162
|
-
execute: () => dialog("help")
|
|
163
|
-
}),
|
|
164
|
-
defineTuiCommand({
|
|
165
|
-
name: "model",
|
|
166
|
-
description: "Choose the model for the next run",
|
|
167
|
-
execute: (query) => dialog("model", query.trim())
|
|
168
|
-
}),
|
|
169
|
-
defineTuiCommand({
|
|
170
|
-
name: "new",
|
|
171
|
-
description: "Start a new durable conversation",
|
|
172
|
-
execute: () => action("new-conversation")
|
|
173
|
-
}),
|
|
174
|
-
defineTuiCommand({
|
|
175
|
-
name: "sessions",
|
|
176
|
-
description: "Browse durable conversations",
|
|
177
|
-
execute: () => dialog("sessions")
|
|
178
|
-
}),
|
|
179
|
-
defineTuiCommand({
|
|
180
|
-
name: "resume",
|
|
181
|
-
description: "Resume a durable conversation",
|
|
182
|
-
execute: () => dialog("sessions")
|
|
183
|
-
}),
|
|
184
|
-
defineTuiCommand({
|
|
185
|
-
name: "status",
|
|
186
|
-
description: "Show session, conversation and run status",
|
|
187
|
-
execute: () => dialog("status")
|
|
188
|
-
}),
|
|
189
|
-
defineTuiCommand({
|
|
190
|
-
name: "tools",
|
|
191
|
-
description: "Show the direct tool surface",
|
|
192
|
-
execute: () => dialog("tools")
|
|
193
|
-
}),
|
|
194
|
-
defineTuiCommand({
|
|
195
|
-
name: "skills",
|
|
196
|
-
description: "Show lazily available skills and resources",
|
|
197
|
-
execute: () => dialog("skills")
|
|
198
|
-
}),
|
|
199
|
-
defineTuiCommand({
|
|
200
|
-
name: "permissions",
|
|
201
|
-
description: "Show approval and sandbox enforcement",
|
|
202
|
-
execute: () => dialog("permissions")
|
|
203
|
-
}),
|
|
204
|
-
defineTuiCommand({
|
|
205
|
-
name: "interrupt",
|
|
206
|
-
description: "Interrupt the active run",
|
|
207
|
-
available: ({ activeRunId }) => activeRunId !== undefined,
|
|
208
|
-
execute: () => action("interrupt")
|
|
209
|
-
}),
|
|
210
|
-
defineTuiCommand({
|
|
211
|
-
name: "clear",
|
|
212
|
-
description: "Start clean while keeping this conversation available to resume",
|
|
213
|
-
execute: () => action("clear-conversation")
|
|
214
|
-
}),
|
|
215
|
-
defineTuiCommand({
|
|
216
|
-
name: "quit",
|
|
217
|
-
aliases: ["exit"],
|
|
218
|
-
description: "Close this terminal host",
|
|
219
|
-
execute: () => action("quit")
|
|
220
|
-
})
|
|
221
|
-
];
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
// src/composer.ts
|
|
225
|
-
import { z as z3 } from "zod";
|
|
226
|
-
var AgentTuiComposerSchema = z3.object({
|
|
227
|
-
draft: z3.string(),
|
|
228
|
-
history: z3.array(z3.string()),
|
|
229
|
-
historyIndex: z3.int().nonnegative().optional(),
|
|
230
|
-
preservedDraft: z3.string()
|
|
231
|
-
}).strict();
|
|
232
|
-
function createAgentTuiComposer() {
|
|
233
|
-
return { draft: "", history: [], preservedDraft: "" };
|
|
234
|
-
}
|
|
235
|
-
function setAgentTuiDraft(state, draft) {
|
|
236
|
-
const { historyIndex: _historyIndex, ...rest } = state;
|
|
237
|
-
return { ...rest, draft, preservedDraft: draft };
|
|
238
|
-
}
|
|
239
|
-
function submitAgentTuiComposer(state) {
|
|
240
|
-
const text = state.draft.trim();
|
|
241
|
-
if (!text)
|
|
242
|
-
return { state };
|
|
243
|
-
const history = state.history.at(-1) === text ? state.history : [...state.history, text];
|
|
244
|
-
return { state: { draft: "", history, preservedDraft: "" }, text };
|
|
245
|
-
}
|
|
246
|
-
function navigateAgentTuiHistory(state, direction) {
|
|
247
|
-
if (state.history.length === 0)
|
|
248
|
-
return state;
|
|
249
|
-
if (direction === "older") {
|
|
250
|
-
const index = state.historyIndex === undefined ? state.history.length - 1 : Math.max(0, state.historyIndex - 1);
|
|
251
|
-
return { ...state, historyIndex: index, draft: state.history[index] ?? state.draft };
|
|
252
|
-
}
|
|
253
|
-
if (state.historyIndex === undefined)
|
|
254
|
-
return state;
|
|
255
|
-
const index = state.historyIndex + 1;
|
|
256
|
-
if (index >= state.history.length) {
|
|
257
|
-
const { historyIndex: _historyIndex, ...rest } = state;
|
|
258
|
-
return { ...rest, draft: state.preservedDraft };
|
|
259
|
-
}
|
|
260
|
-
return { ...state, historyIndex: index, draft: state.history[index] ?? state.draft };
|
|
261
|
-
}
|
|
262
|
-
|
|
263
|
-
// src/core/collection.ts
|
|
264
|
-
import { z as z4 } from "zod";
|
|
265
|
-
var TerminalCollectionStateSchema = z4.object({
|
|
266
|
-
keys: z4.array(z4.string().min(1)),
|
|
267
|
-
selectedKey: z4.string().min(1).nullable(),
|
|
268
|
-
start: z4.int().nonnegative(),
|
|
269
|
-
capacity: z4.int().positive()
|
|
270
|
-
}).strict();
|
|
271
|
-
function maximumStart(total, capacity) {
|
|
272
|
-
return Math.max(0, total - capacity);
|
|
273
|
-
}
|
|
274
|
-
function reveal(start, capacity, index, total) {
|
|
275
|
-
const bounded = Math.min(Math.max(0, start), maximumStart(total, capacity));
|
|
276
|
-
if (index < bounded)
|
|
277
|
-
return index;
|
|
278
|
-
if (index >= bounded + capacity)
|
|
279
|
-
return index - capacity + 1;
|
|
280
|
-
return bounded;
|
|
281
|
-
}
|
|
282
|
-
function uniqueKeys(keys) {
|
|
283
|
-
const result = z4.array(z4.string().min(1)).parse(keys);
|
|
284
|
-
if (new Set(result).size !== result.length) {
|
|
285
|
-
throw new Error("Terminal collection keys must be unique");
|
|
286
|
-
}
|
|
287
|
-
return result;
|
|
288
|
-
}
|
|
289
|
-
function createTerminalCollection(keys, capacity, selectedKey) {
|
|
290
|
-
const parsedKeys = uniqueKeys(keys);
|
|
291
|
-
const parsedCapacity = z4.int().positive().parse(capacity);
|
|
292
|
-
const selected = selectedKey !== undefined && parsedKeys.includes(selectedKey) ? selectedKey : parsedKeys[0] ?? null;
|
|
293
|
-
const index = selected === null ? -1 : parsedKeys.indexOf(selected);
|
|
294
|
-
return TerminalCollectionStateSchema.parse({
|
|
295
|
-
keys: parsedKeys,
|
|
296
|
-
selectedKey: selected,
|
|
297
|
-
start: index < 0 ? 0 : reveal(0, parsedCapacity, index, parsedKeys.length),
|
|
298
|
-
capacity: parsedCapacity
|
|
299
|
-
});
|
|
300
|
-
}
|
|
301
|
-
function reduceTerminalCollection(state, action) {
|
|
302
|
-
const current = TerminalCollectionStateSchema.parse(state);
|
|
303
|
-
if (action.type === "reconcile") {
|
|
304
|
-
const keys = uniqueKeys(action.keys);
|
|
305
|
-
if (keys.length === 0)
|
|
306
|
-
return { keys, selectedKey: null, start: 0, capacity: current.capacity };
|
|
307
|
-
const previousIndex = current.selectedKey === null ? 0 : Math.max(0, current.keys.indexOf(current.selectedKey));
|
|
308
|
-
const selectedKey = current.selectedKey !== null && keys.includes(current.selectedKey) ? current.selectedKey : keys[Math.min(previousIndex, keys.length - 1)];
|
|
309
|
-
if (!selectedKey)
|
|
310
|
-
throw new Error("Terminal collection survivor is unavailable");
|
|
311
|
-
const index = keys.indexOf(selectedKey);
|
|
312
|
-
return TerminalCollectionStateSchema.parse({
|
|
313
|
-
...current,
|
|
314
|
-
keys,
|
|
315
|
-
selectedKey,
|
|
316
|
-
start: reveal(current.start, current.capacity, index, keys.length)
|
|
317
|
-
});
|
|
318
|
-
}
|
|
319
|
-
if (action.type === "resize") {
|
|
320
|
-
const capacity = z4.int().positive().parse(action.capacity);
|
|
321
|
-
const index = current.selectedKey === null ? -1 : current.keys.indexOf(current.selectedKey);
|
|
322
|
-
return TerminalCollectionStateSchema.parse({
|
|
323
|
-
...current,
|
|
324
|
-
capacity,
|
|
325
|
-
start: index < 0 ? 0 : reveal(current.start, capacity, index, current.keys.length)
|
|
326
|
-
});
|
|
327
|
-
}
|
|
328
|
-
if (action.type === "scroll") {
|
|
329
|
-
return TerminalCollectionStateSchema.parse({
|
|
330
|
-
...current,
|
|
331
|
-
start: Math.min(Math.max(0, current.start + action.lines), maximumStart(current.keys.length, current.capacity))
|
|
332
|
-
});
|
|
333
|
-
}
|
|
334
|
-
if (current.keys.length === 0)
|
|
335
|
-
return current;
|
|
336
|
-
const currentIndex = current.selectedKey === null ? 0 : Math.max(0, current.keys.indexOf(current.selectedKey));
|
|
337
|
-
const nextIndex = action.type === "select" ? current.keys.indexOf(action.key) : action.wrap ? ((currentIndex + action.delta) % current.keys.length + current.keys.length) % current.keys.length : Math.min(Math.max(0, currentIndex + action.delta), current.keys.length - 1);
|
|
338
|
-
if (nextIndex < 0) {
|
|
339
|
-
throw new Error(action.type === "select" ? `Unknown terminal collection key: ${action.key}` : "Terminal collection movement could not resolve a selection");
|
|
340
|
-
}
|
|
341
|
-
const selectedKey = current.keys[nextIndex];
|
|
342
|
-
if (!selectedKey)
|
|
343
|
-
throw new Error("Terminal collection selection is unavailable");
|
|
344
|
-
return TerminalCollectionStateSchema.parse({
|
|
345
|
-
...current,
|
|
346
|
-
selectedKey,
|
|
347
|
-
start: reveal(current.start, current.capacity, nextIndex, current.keys.length)
|
|
348
|
-
});
|
|
349
|
-
}
|
|
350
|
-
function visibleTerminalCollectionRange(state) {
|
|
351
|
-
const parsed = TerminalCollectionStateSchema.parse(state);
|
|
352
|
-
return {
|
|
353
|
-
start: parsed.start,
|
|
354
|
-
end: Math.min(parsed.keys.length, parsed.start + parsed.capacity)
|
|
355
|
-
};
|
|
356
|
-
}
|
|
357
|
-
// src/core/operation.ts
|
|
358
|
-
import { z as z5 } from "zod";
|
|
359
|
-
var TerminalOperationStateSchema = z5.object({
|
|
360
|
-
status: z5.enum(["idle", "confirming", "pending", "succeeded", "failed"]),
|
|
361
|
-
operationId: z5.string().min(1).nullable(),
|
|
362
|
-
message: z5.string().optional()
|
|
363
|
-
}).strict();
|
|
364
|
-
function createTerminalOperationState() {
|
|
365
|
-
return { status: "idle", operationId: null };
|
|
366
|
-
}
|
|
367
|
-
function reduceTerminalOperationState(state, action) {
|
|
368
|
-
const current = TerminalOperationStateSchema.parse(state);
|
|
369
|
-
if (action.type === "request") {
|
|
370
|
-
if (current.status === "pending")
|
|
371
|
-
throw new Error("A terminal operation is already pending");
|
|
372
|
-
return TerminalOperationStateSchema.parse({
|
|
373
|
-
status: "confirming",
|
|
374
|
-
operationId: action.operationId,
|
|
375
|
-
...action.message !== undefined && { message: action.message }
|
|
376
|
-
});
|
|
377
|
-
}
|
|
378
|
-
if (action.type === "reset" || action.type === "cancel") {
|
|
379
|
-
if (action.type === "cancel" && current.status !== "confirming") {
|
|
380
|
-
throw new Error("Only a confirming terminal operation can be cancelled");
|
|
381
|
-
}
|
|
382
|
-
return createTerminalOperationState();
|
|
383
|
-
}
|
|
384
|
-
if (action.type === "confirm") {
|
|
385
|
-
if (current.status !== "confirming") {
|
|
386
|
-
throw new Error("Only a confirming terminal operation can become pending");
|
|
387
|
-
}
|
|
388
|
-
return { ...current, status: "pending" };
|
|
389
|
-
}
|
|
390
|
-
if (current.status !== "pending") {
|
|
391
|
-
throw new Error("Only a pending terminal operation can settle");
|
|
392
|
-
}
|
|
393
|
-
return TerminalOperationStateSchema.parse({
|
|
394
|
-
status: action.type === "succeed" ? "succeeded" : "failed",
|
|
395
|
-
operationId: current.operationId,
|
|
396
|
-
...action.message !== undefined && { message: action.message }
|
|
397
|
-
});
|
|
398
|
-
}
|
|
399
|
-
// src/core/panes.ts
|
|
400
|
-
import { z as z6 } from "zod";
|
|
401
|
-
var TerminalPaneIdSchema = z6.enum(["primary", "secondary"]);
|
|
402
|
-
var TerminalPaneModeSchema = z6.enum(["split", "single"]);
|
|
403
|
-
var TerminalPaneStateSchema = z6.object({
|
|
404
|
-
mode: TerminalPaneModeSchema,
|
|
405
|
-
focus: TerminalPaneIdSchema,
|
|
406
|
-
primarySize: z6.int().positive(),
|
|
407
|
-
totalSize: z6.int().positive(),
|
|
408
|
-
minPrimary: z6.int().positive(),
|
|
409
|
-
minSecondary: z6.int().positive()
|
|
410
|
-
}).strict();
|
|
411
|
-
function clampPrimary(input) {
|
|
412
|
-
const maximum = Math.max(input.minPrimary, input.totalSize - input.minSecondary);
|
|
413
|
-
return Math.min(Math.max(input.minPrimary, input.primarySize), maximum);
|
|
414
|
-
}
|
|
415
|
-
function createTerminalPaneState(input) {
|
|
416
|
-
const values = z6.object({
|
|
417
|
-
totalSize: z6.int().positive(),
|
|
418
|
-
primarySize: z6.int().positive(),
|
|
419
|
-
minPrimary: z6.int().positive(),
|
|
420
|
-
minSecondary: z6.int().positive(),
|
|
421
|
-
mode: TerminalPaneModeSchema.default("split"),
|
|
422
|
-
focus: TerminalPaneIdSchema.default("primary")
|
|
423
|
-
}).strict().parse(input);
|
|
424
|
-
if (values.mode === "split" && values.totalSize < values.minPrimary + values.minSecondary) {
|
|
425
|
-
throw new Error("Split terminal panes do not fit within the total size");
|
|
426
|
-
}
|
|
427
|
-
return TerminalPaneStateSchema.parse({
|
|
428
|
-
...values,
|
|
429
|
-
primarySize: clampPrimary(values)
|
|
430
|
-
});
|
|
431
|
-
}
|
|
432
|
-
function reduceTerminalPaneState(state, action) {
|
|
433
|
-
const current = TerminalPaneStateSchema.parse(state);
|
|
434
|
-
if (action.type === "focus")
|
|
435
|
-
return { ...current, focus: action.pane };
|
|
436
|
-
if (action.type === "toggle-focus") {
|
|
437
|
-
return { ...current, focus: current.focus === "primary" ? "secondary" : "primary" };
|
|
438
|
-
}
|
|
439
|
-
if (action.type === "mode") {
|
|
440
|
-
if (action.mode === "split" && current.totalSize < current.minPrimary + current.minSecondary) {
|
|
441
|
-
throw new Error("Split terminal panes do not fit within the total size");
|
|
442
|
-
}
|
|
443
|
-
return { ...current, mode: action.mode };
|
|
444
|
-
}
|
|
445
|
-
const totalSize = action.type === "terminal-resize" ? action.totalSize : current.totalSize;
|
|
446
|
-
const mode = current.mode === "split" && totalSize < current.minPrimary + current.minSecondary ? "single" : current.mode;
|
|
447
|
-
const primarySize = action.type === "resize" ? action.primarySize : current.primarySize;
|
|
448
|
-
return TerminalPaneStateSchema.parse({
|
|
449
|
-
...current,
|
|
450
|
-
totalSize,
|
|
451
|
-
mode,
|
|
452
|
-
primarySize: clampPrimary({
|
|
453
|
-
primarySize,
|
|
454
|
-
totalSize,
|
|
455
|
-
minPrimary: current.minPrimary,
|
|
456
|
-
minSecondary: current.minSecondary
|
|
457
|
-
})
|
|
458
|
-
});
|
|
459
|
-
}
|
|
460
|
-
function visibleTerminalPanes(state) {
|
|
461
|
-
const parsed = TerminalPaneStateSchema.parse(state);
|
|
462
|
-
return parsed.mode === "split" ? ["primary", "secondary"] : [parsed.focus];
|
|
463
|
-
}
|
|
464
|
-
// src/core/viewport.ts
|
|
465
|
-
import { z as z7 } from "zod";
|
|
466
|
-
var TerminalFeedViewportSchema = z7.object({
|
|
467
|
-
total: z7.int().nonnegative(),
|
|
468
|
-
capacity: z7.int().positive(),
|
|
469
|
-
start: z7.int().nonnegative(),
|
|
470
|
-
followTail: z7.boolean(),
|
|
471
|
-
unseen: z7.int().nonnegative()
|
|
472
|
-
}).strict();
|
|
473
|
-
function maximumStart2(total, capacity) {
|
|
474
|
-
return Math.max(0, total - capacity);
|
|
475
|
-
}
|
|
476
|
-
function createTerminalFeedViewport(total, capacity) {
|
|
477
|
-
const parsedTotal = z7.int().nonnegative().parse(total);
|
|
478
|
-
const parsedCapacity = z7.int().positive().parse(capacity);
|
|
479
|
-
return TerminalFeedViewportSchema.parse({
|
|
480
|
-
total: parsedTotal,
|
|
481
|
-
capacity: parsedCapacity,
|
|
482
|
-
start: maximumStart2(parsedTotal, parsedCapacity),
|
|
483
|
-
followTail: true,
|
|
484
|
-
unseen: 0
|
|
485
|
-
});
|
|
486
|
-
}
|
|
487
|
-
function reduceTerminalFeedViewport(state, action) {
|
|
488
|
-
const current = TerminalFeedViewportSchema.parse(state);
|
|
489
|
-
if (action.type === "append") {
|
|
490
|
-
const count = Math.max(0, action.count);
|
|
491
|
-
const total = current.total + count;
|
|
492
|
-
return TerminalFeedViewportSchema.parse({
|
|
493
|
-
...current,
|
|
494
|
-
total,
|
|
495
|
-
start: current.followTail ? maximumStart2(total, current.capacity) : current.start,
|
|
496
|
-
unseen: current.followTail ? 0 : current.unseen + count
|
|
497
|
-
});
|
|
498
|
-
}
|
|
499
|
-
if (action.type === "prepend") {
|
|
500
|
-
const count = Math.max(0, action.count);
|
|
501
|
-
return TerminalFeedViewportSchema.parse({
|
|
502
|
-
...current,
|
|
503
|
-
total: current.total + count,
|
|
504
|
-
start: current.start + count
|
|
505
|
-
});
|
|
506
|
-
}
|
|
507
|
-
if (action.type === "resize") {
|
|
508
|
-
const capacity = z7.int().positive().parse(action.capacity);
|
|
509
|
-
return TerminalFeedViewportSchema.parse({
|
|
510
|
-
...current,
|
|
511
|
-
capacity,
|
|
512
|
-
start: current.followTail ? maximumStart2(current.total, capacity) : Math.min(current.start, maximumStart2(current.total, capacity))
|
|
513
|
-
});
|
|
514
|
-
}
|
|
515
|
-
if (action.type === "home")
|
|
516
|
-
return { ...current, start: 0, followTail: false };
|
|
517
|
-
if (action.type === "end") {
|
|
518
|
-
return {
|
|
519
|
-
...current,
|
|
520
|
-
start: maximumStart2(current.total, current.capacity),
|
|
521
|
-
followTail: true,
|
|
522
|
-
unseen: 0
|
|
523
|
-
};
|
|
524
|
-
}
|
|
525
|
-
const delta = action.type === "page" ? action.pages * current.capacity : action.lines;
|
|
526
|
-
const start = Math.max(0, Math.min(maximumStart2(current.total, current.capacity), current.start + delta));
|
|
527
|
-
const atTail = start === maximumStart2(current.total, current.capacity) && delta > 0;
|
|
528
|
-
return { ...current, start, followTail: atTail, unseen: atTail ? 0 : current.unseen };
|
|
529
|
-
}
|
|
530
|
-
function visibleTerminalFeedRange(state) {
|
|
531
|
-
const parsed = TerminalFeedViewportSchema.parse(state);
|
|
532
|
-
return { start: parsed.start, end: Math.min(parsed.total, parsed.start + parsed.capacity) };
|
|
533
|
-
}
|
|
534
|
-
// src/keyboard.ts
|
|
535
|
-
function isAgentTuiExitKey(key) {
|
|
536
|
-
return key.ctrl === true && key.name?.toLowerCase() === "c";
|
|
537
|
-
}
|
|
538
|
-
|
|
539
|
-
// src/model-picker.ts
|
|
540
|
-
import { searchAgentModelCatalog } from "stitchkit/agent-runtime";
|
|
541
|
-
var AGENT_TUI_MODEL_RESULT_LIMIT = 200;
|
|
542
|
-
function searchAgentTuiModels(catalog, query) {
|
|
543
|
-
return searchAgentModelCatalog(catalog, {
|
|
544
|
-
query,
|
|
545
|
-
limit: AGENT_TUI_MODEL_RESULT_LIMIT
|
|
546
|
-
});
|
|
547
|
-
}
|
|
548
|
-
|
|
549
|
-
// src/session.ts
|
|
550
|
-
import { chmod, mkdir, readdir, readFile, rename, unlink, writeFile } from "fs/promises";
|
|
551
9
|
import path from "path";
|
|
552
|
-
import {
|
|
553
|
-
var MAX_REQUEST_BYTES = 65536;
|
|
554
|
-
var AgentTuiSessionDescriptorSchema = z8.object({
|
|
555
|
-
schemaVersion: z8.literal(1),
|
|
556
|
-
sessionId: z8.string().min(8),
|
|
557
|
-
conversationId: z8.string().min(1),
|
|
558
|
-
socketPath: z8.string().min(1),
|
|
559
|
-
token: z8.string().min(32),
|
|
560
|
-
pid: z8.int().positive(),
|
|
561
|
-
startedAt: z8.iso.datetime({ offset: true })
|
|
562
|
-
}).strict();
|
|
563
|
-
var AgentTuiSessionRequestSchema = z8.discriminatedUnion("operation", [
|
|
564
|
-
z8.object({ requestId: z8.string().min(1), operation: z8.literal("status") }).strict(),
|
|
565
|
-
z8.object({
|
|
566
|
-
requestId: z8.string().min(1),
|
|
567
|
-
operation: z8.literal("submit"),
|
|
568
|
-
text: z8.string().min(1),
|
|
569
|
-
idempotencyKey: z8.string().min(1)
|
|
570
|
-
}).strict(),
|
|
571
|
-
z8.object({
|
|
572
|
-
requestId: z8.string().min(1),
|
|
573
|
-
operation: z8.literal("interrupt"),
|
|
574
|
-
runId: z8.string().min(1).optional()
|
|
575
|
-
}).strict()
|
|
576
|
-
]);
|
|
577
|
-
var AgentTuiSessionResponseSchema = z8.discriminatedUnion("outcome", [
|
|
578
|
-
z8.object({
|
|
579
|
-
requestId: z8.string().min(1),
|
|
580
|
-
outcome: z8.literal("ok"),
|
|
581
|
-
sessionId: z8.string().min(1),
|
|
582
|
-
conversationId: z8.string().min(1),
|
|
583
|
-
runId: z8.string().min(1).optional()
|
|
584
|
-
}).strict(),
|
|
585
|
-
z8.object({
|
|
586
|
-
requestId: z8.string().min(1),
|
|
587
|
-
outcome: z8.literal("error"),
|
|
588
|
-
error: z8.object({ code: z8.string().min(1), message: z8.string().min(1) }).strict()
|
|
589
|
-
}).strict()
|
|
590
|
-
]);
|
|
591
|
-
function createAgentTuiSessionId() {
|
|
592
|
-
return crypto.randomUUID().replaceAll("-", "").slice(0, 16);
|
|
593
|
-
}
|
|
594
|
-
function createAgentTuiConversationId() {
|
|
595
|
-
return `conversation-${crypto.randomUUID()}`;
|
|
596
|
-
}
|
|
597
|
-
function sessionsDirectory(rootDirectory) {
|
|
598
|
-
return path.join(rootDirectory, ".stitchkit", "tui", "sessions");
|
|
599
|
-
}
|
|
600
|
-
function descriptorPath(rootDirectory, sessionId) {
|
|
601
|
-
return path.join(sessionsDirectory(rootDirectory), `${sessionId}.json`);
|
|
602
|
-
}
|
|
603
|
-
function processAlive(pid) {
|
|
604
|
-
try {
|
|
605
|
-
process.kill(pid, 0);
|
|
606
|
-
return true;
|
|
607
|
-
} catch (error) {
|
|
608
|
-
return error instanceof Error && "code" in error && error.code === "EPERM";
|
|
609
|
-
}
|
|
610
|
-
}
|
|
611
|
-
async function readDescriptor(rootDirectory, sessionId) {
|
|
612
|
-
const descriptor = AgentTuiSessionDescriptorSchema.parse(JSON.parse(await readFile(descriptorPath(rootDirectory, sessionId), "utf8")));
|
|
613
|
-
const expectedSocket = path.join(sessionsDirectory(rootDirectory), `${sessionId}.sock`);
|
|
614
|
-
if (descriptor.sessionId !== sessionId || descriptor.socketPath !== expectedSocket) {
|
|
615
|
-
throw new Error("Agent TUI session descriptor identity does not match its path");
|
|
616
|
-
}
|
|
617
|
-
return descriptor;
|
|
618
|
-
}
|
|
619
|
-
async function probeDescriptor(descriptor, timeoutMs = 500) {
|
|
620
|
-
try {
|
|
621
|
-
const requestId = crypto.randomUUID();
|
|
622
|
-
const response = await fetch("http://localhost/request", {
|
|
623
|
-
method: "POST",
|
|
624
|
-
unix: descriptor.socketPath,
|
|
625
|
-
headers: {
|
|
626
|
-
Authorization: `Bearer ${descriptor.token}`,
|
|
627
|
-
"Content-Type": "application/json"
|
|
628
|
-
},
|
|
629
|
-
body: JSON.stringify({ requestId, operation: "status" }),
|
|
630
|
-
signal: AbortSignal.timeout(timeoutMs)
|
|
631
|
-
});
|
|
632
|
-
if (!response.ok)
|
|
633
|
-
return false;
|
|
634
|
-
const parsed = AgentTuiSessionResponseSchema.safeParse(await response.json());
|
|
635
|
-
return parsed.success && parsed.data.outcome === "ok" && parsed.data.requestId === requestId && parsed.data.sessionId === descriptor.sessionId;
|
|
636
|
-
} catch {
|
|
637
|
-
return false;
|
|
638
|
-
}
|
|
639
|
-
}
|
|
640
|
-
async function writeDescriptor(rootDirectory, descriptor) {
|
|
641
|
-
const directory = sessionsDirectory(rootDirectory);
|
|
642
|
-
await mkdir(directory, { recursive: true, mode: 448 });
|
|
643
|
-
await chmod(directory, 448);
|
|
644
|
-
const filename = descriptorPath(rootDirectory, descriptor.sessionId);
|
|
645
|
-
const temporary = `${filename}.${crypto.randomUUID()}.tmp`;
|
|
646
|
-
await writeFile(temporary, `${JSON.stringify(descriptor)}
|
|
647
|
-
`, {
|
|
648
|
-
encoding: "utf8",
|
|
649
|
-
mode: 384,
|
|
650
|
-
flag: "wx"
|
|
651
|
-
});
|
|
652
|
-
await rename(temporary, filename);
|
|
653
|
-
await chmod(filename, 384);
|
|
654
|
-
}
|
|
655
|
-
async function removeDescriptor(rootDirectory, descriptor) {
|
|
656
|
-
const expectedSocket = path.join(sessionsDirectory(rootDirectory), `${descriptor.sessionId}.sock`);
|
|
657
|
-
if (descriptor.socketPath === expectedSocket) {
|
|
658
|
-
await unlink(expectedSocket).catch(() => {
|
|
659
|
-
return;
|
|
660
|
-
});
|
|
661
|
-
}
|
|
662
|
-
await unlink(descriptorPath(rootDirectory, descriptor.sessionId)).catch(() => {
|
|
663
|
-
return;
|
|
664
|
-
});
|
|
665
|
-
}
|
|
666
|
-
async function listAgentTuiSessions(rootDirectory) {
|
|
667
|
-
const directory = sessionsDirectory(rootDirectory);
|
|
668
|
-
const names = await readdir(directory).catch((error) => {
|
|
669
|
-
if (error.code === "ENOENT")
|
|
670
|
-
return [];
|
|
671
|
-
throw error;
|
|
672
|
-
});
|
|
673
|
-
const descriptors = [];
|
|
674
|
-
for (const name of names.sort()) {
|
|
675
|
-
if (!name.endsWith(".json"))
|
|
676
|
-
continue;
|
|
677
|
-
try {
|
|
678
|
-
const sessionId = name.slice(0, -".json".length);
|
|
679
|
-
const descriptor = await readDescriptor(rootDirectory, sessionId);
|
|
680
|
-
if (!processAlive(descriptor.pid) || !await probeDescriptor(descriptor)) {
|
|
681
|
-
await removeDescriptor(rootDirectory, descriptor);
|
|
682
|
-
continue;
|
|
683
|
-
}
|
|
684
|
-
descriptors.push(descriptor);
|
|
685
|
-
} catch {
|
|
686
|
-
await unlink(path.join(directory, name)).catch(() => {
|
|
687
|
-
return;
|
|
688
|
-
});
|
|
689
|
-
}
|
|
690
|
-
}
|
|
691
|
-
return descriptors;
|
|
692
|
-
}
|
|
693
|
-
async function startAgentTuiSessionHost(input) {
|
|
694
|
-
for (const descriptor of await listAgentTuiSessions(input.rootDirectory)) {
|
|
695
|
-
if (!processAlive(descriptor.pid))
|
|
696
|
-
await removeDescriptor(input.rootDirectory, descriptor);
|
|
697
|
-
}
|
|
698
|
-
const sessionId = input.sessionId ?? createAgentTuiSessionId();
|
|
699
|
-
const socketPath = path.join(sessionsDirectory(input.rootDirectory), `${sessionId}.sock`);
|
|
700
|
-
const token = `${crypto.randomUUID()}${crypto.randomUUID()}`;
|
|
701
|
-
let conversationId = input.conversationId;
|
|
702
|
-
let descriptor = AgentTuiSessionDescriptorSchema.parse({
|
|
703
|
-
schemaVersion: 1,
|
|
704
|
-
sessionId,
|
|
705
|
-
conversationId,
|
|
706
|
-
socketPath,
|
|
707
|
-
token,
|
|
708
|
-
pid: process.pid,
|
|
709
|
-
startedAt: new Date().toISOString()
|
|
710
|
-
});
|
|
711
|
-
await mkdir(path.dirname(socketPath), { recursive: true, mode: 448 });
|
|
712
|
-
let server;
|
|
713
|
-
try {
|
|
714
|
-
server = Bun.serve({
|
|
715
|
-
unix: socketPath,
|
|
716
|
-
async fetch(request) {
|
|
717
|
-
if (request.headers.get("authorization") !== `Bearer ${token}`) {
|
|
718
|
-
return Response.json({ error: "UNAUTHORIZED" }, { status: 401 });
|
|
719
|
-
}
|
|
720
|
-
const declaredLength = Number(request.headers.get("content-length") ?? "0");
|
|
721
|
-
if (declaredLength > MAX_REQUEST_BYTES) {
|
|
722
|
-
return Response.json({ error: "REQUEST_TOO_LARGE" }, { status: 413 });
|
|
723
|
-
}
|
|
724
|
-
const body = await request.text();
|
|
725
|
-
if (Buffer.byteLength(body) > MAX_REQUEST_BYTES) {
|
|
726
|
-
return Response.json({ error: "REQUEST_TOO_LARGE" }, { status: 413 });
|
|
727
|
-
}
|
|
728
|
-
try {
|
|
729
|
-
const parsed = AgentTuiSessionRequestSchema.parse(JSON.parse(body));
|
|
730
|
-
return Response.json(await input.handle(parsed));
|
|
731
|
-
} catch {
|
|
732
|
-
return Response.json({ error: "INVALID_REQUEST" }, { status: 400 });
|
|
733
|
-
}
|
|
734
|
-
}
|
|
735
|
-
});
|
|
736
|
-
await chmod(socketPath, 384);
|
|
737
|
-
await writeDescriptor(input.rootDirectory, descriptor);
|
|
738
|
-
} catch (error) {
|
|
739
|
-
server?.stop(true);
|
|
740
|
-
await unlink(socketPath).catch(() => {
|
|
741
|
-
return;
|
|
742
|
-
});
|
|
743
|
-
await unlink(descriptorPath(input.rootDirectory, sessionId)).catch(() => {
|
|
744
|
-
return;
|
|
745
|
-
});
|
|
746
|
-
throw error;
|
|
747
|
-
}
|
|
748
|
-
return {
|
|
749
|
-
sessionId,
|
|
750
|
-
socketPath,
|
|
751
|
-
async setConversationId(nextConversationId) {
|
|
752
|
-
conversationId = nextConversationId;
|
|
753
|
-
descriptor = AgentTuiSessionDescriptorSchema.parse({
|
|
754
|
-
...descriptor,
|
|
755
|
-
conversationId
|
|
756
|
-
});
|
|
757
|
-
await writeDescriptor(input.rootDirectory, descriptor);
|
|
758
|
-
},
|
|
759
|
-
async close() {
|
|
760
|
-
server.stop(true);
|
|
761
|
-
await unlink(socketPath).catch(() => {
|
|
762
|
-
return;
|
|
763
|
-
});
|
|
764
|
-
await unlink(descriptorPath(input.rootDirectory, sessionId)).catch(() => {
|
|
765
|
-
return;
|
|
766
|
-
});
|
|
767
|
-
}
|
|
768
|
-
};
|
|
769
|
-
}
|
|
770
|
-
async function createAgentTuiClient(input) {
|
|
771
|
-
const descriptor = await readDescriptor(input.rootDirectory, input.sessionId);
|
|
772
|
-
const timeoutMs = input.timeoutMs ?? 5000;
|
|
773
|
-
return {
|
|
774
|
-
async request(request) {
|
|
775
|
-
const response = await fetch("http://localhost/request", {
|
|
776
|
-
method: "POST",
|
|
777
|
-
unix: descriptor.socketPath,
|
|
778
|
-
headers: {
|
|
779
|
-
Authorization: `Bearer ${descriptor.token}`,
|
|
780
|
-
"Content-Type": "application/json"
|
|
781
|
-
},
|
|
782
|
-
body: JSON.stringify(AgentTuiSessionRequestSchema.parse(request)),
|
|
783
|
-
signal: AbortSignal.timeout(timeoutMs)
|
|
784
|
-
});
|
|
785
|
-
if (!response.ok)
|
|
786
|
-
throw new Error(`TUI session request failed with HTTP ${response.status}`);
|
|
787
|
-
return AgentTuiSessionResponseSchema.parse(await response.json());
|
|
788
|
-
}
|
|
789
|
-
};
|
|
790
|
-
}
|
|
791
|
-
|
|
792
|
-
// src/status-line.ts
|
|
793
|
-
import path2 from "path";
|
|
794
|
-
function formatCount(value) {
|
|
795
|
-
if (value >= 1e6)
|
|
796
|
-
return `${(value / 1e6).toFixed(1)}M`;
|
|
797
|
-
if (value >= 1000)
|
|
798
|
-
return `${(value / 1000).toFixed(1)}k`;
|
|
799
|
-
return String(value);
|
|
800
|
-
}
|
|
801
|
-
function knownTotal(usages, field) {
|
|
802
|
-
if (usages.length === 0)
|
|
803
|
-
return;
|
|
804
|
-
let value = 0;
|
|
805
|
-
let known = 0;
|
|
806
|
-
for (const usage of usages) {
|
|
807
|
-
const item = usage[field];
|
|
808
|
-
if (item.value === undefined)
|
|
809
|
-
continue;
|
|
810
|
-
value += item.value;
|
|
811
|
-
known += 1;
|
|
812
|
-
}
|
|
813
|
-
if (known === 0)
|
|
814
|
-
return;
|
|
815
|
-
return { value, partial: known !== usages.length };
|
|
816
|
-
}
|
|
817
|
-
function formatKnownTotal(total) {
|
|
818
|
-
return `${total.partial ? "\u2265" : ""}${formatCount(total.value)}`;
|
|
819
|
-
}
|
|
820
|
-
function shortIdentity(value) {
|
|
821
|
-
return value.slice(0, 8);
|
|
822
|
-
}
|
|
823
|
-
var defaultAgentTuiStatusLine = (context) => {
|
|
824
|
-
const usages = context.snapshot.runs.map(({ usage }) => usage).filter((usage) => usage !== undefined);
|
|
825
|
-
const input = knownTotal(usages, "inputTokens");
|
|
826
|
-
const output = knownTotal(usages, "outputTokens");
|
|
827
|
-
const firstRow = [
|
|
828
|
-
{
|
|
829
|
-
text: context.model?.name ?? context.model?.id ?? "model unavailable",
|
|
830
|
-
tone: "accent"
|
|
831
|
-
}
|
|
832
|
-
];
|
|
833
|
-
if (context.model) {
|
|
834
|
-
firstRow.push({
|
|
835
|
-
text: `${formatCount(context.model.descriptor.contextWindow)} context`,
|
|
836
|
-
tone: "primary"
|
|
837
|
-
});
|
|
838
|
-
}
|
|
839
|
-
if (input || output) {
|
|
840
|
-
firstRow.push({
|
|
841
|
-
text: `session ${input ? `\u2193${formatKnownTotal(input)}` : "\u2193\u2014"} ${output ? `\u2191${formatKnownTotal(output)}` : "\u2191\u2014"}`,
|
|
842
|
-
tone: "muted"
|
|
843
|
-
});
|
|
844
|
-
}
|
|
845
|
-
const activityTone = context.activity === "APPROVAL" ? "warning" : context.activity === "RUNNING" ? "accent" : "success";
|
|
846
|
-
return [
|
|
847
|
-
firstRow,
|
|
848
|
-
[
|
|
849
|
-
{ text: path2.basename(context.workspace) || context.workspace, tone: "primary" },
|
|
850
|
-
{ text: shortIdentity(context.conversationId), tone: "muted" },
|
|
851
|
-
{ text: context.activity.toLowerCase(), tone: activityTone }
|
|
852
|
-
]
|
|
853
|
-
];
|
|
854
|
-
};
|
|
855
|
-
|
|
856
|
-
// src/transcript.ts
|
|
857
|
-
function compactJson(value) {
|
|
858
|
-
const text = JSON.stringify(value);
|
|
859
|
-
return text.length > 360 ? `${text.slice(0, 357)}\u2026` : text;
|
|
860
|
-
}
|
|
861
|
-
function isToolErrorEnvelope(value) {
|
|
862
|
-
return typeof value === "object" && value !== null && "error" in value && typeof Reflect.get(value, "error") === "string";
|
|
863
|
-
}
|
|
864
|
-
function partText(part) {
|
|
865
|
-
if (part.type === "text")
|
|
866
|
-
return { text: part.text };
|
|
867
|
-
if (part.type === "reasoning")
|
|
868
|
-
return { text: part.text };
|
|
869
|
-
if (part.type === "tool-call")
|
|
870
|
-
return { text: `\u2192 ${part.toolName} ${compactJson(part.input)}` };
|
|
871
|
-
if (part.type === "tool-result") {
|
|
872
|
-
const failed = part.outcome !== "success" || isToolErrorEnvelope(part.output);
|
|
873
|
-
return {
|
|
874
|
-
text: `${failed ? "\xD7" : "\u2713"} ${part.toolName}${part.output === undefined ? "" : ` ${compactJson(part.output)}`}`,
|
|
875
|
-
failed
|
|
876
|
-
};
|
|
877
|
-
}
|
|
878
|
-
if (part.type === "tool-approval-request")
|
|
879
|
-
return { text: "Approval required." };
|
|
880
|
-
if (part.type === "tool-approval-response") {
|
|
881
|
-
return {
|
|
882
|
-
text: part.approved ? "Approved." : `Denied${part.reason ? `: ${part.reason}` : "."}`
|
|
883
|
-
};
|
|
884
|
-
}
|
|
885
|
-
if (part.type === "file")
|
|
886
|
-
return { text: `File \xB7 ${part.filename ?? part.reference}` };
|
|
887
|
-
if (part.type === "source")
|
|
888
|
-
return { text: `Source \xB7 ${part.title ?? part.url ?? part.sourceId}` };
|
|
889
|
-
if (part.type === "control")
|
|
890
|
-
return { text: `Run ${part.reason}.` };
|
|
891
|
-
return;
|
|
892
|
-
}
|
|
893
|
-
function role(message) {
|
|
894
|
-
if (message.role === "user")
|
|
895
|
-
return "you";
|
|
896
|
-
if (message.role === "assistant")
|
|
897
|
-
return "agent";
|
|
898
|
-
if (message.role === "tool")
|
|
899
|
-
return "tool";
|
|
900
|
-
return "system";
|
|
901
|
-
}
|
|
902
|
-
function projectAgentTuiTranscript(snapshot) {
|
|
903
|
-
return snapshot.messages.flatMap((message) => message.parts.flatMap((part, index) => {
|
|
904
|
-
const projected = partText(part);
|
|
905
|
-
if (!projected?.text.trim())
|
|
906
|
-
return [];
|
|
907
|
-
const messageRole = role(message);
|
|
908
|
-
return [
|
|
909
|
-
{
|
|
910
|
-
id: `${message.id}:${index}`,
|
|
911
|
-
role: messageRole,
|
|
912
|
-
text: projected.text,
|
|
913
|
-
tone: projected.failed ? "danger" : part.type === "tool-result" ? "success" : messageRole === "you" ? "accent" : messageRole === "tool" || messageRole === "system" ? "muted" : "primary"
|
|
914
|
-
}
|
|
915
|
-
];
|
|
916
|
-
}));
|
|
917
|
-
}
|
|
918
|
-
|
|
919
|
-
// src/App.tsx
|
|
920
|
-
import { jsx, jsxs } from "@opentui/react/jsx-runtime";
|
|
921
|
-
function isDialog(value) {
|
|
922
|
-
return ["help", "model", "sessions", "status", "tools", "skills", "permissions"].includes(value);
|
|
923
|
-
}
|
|
924
|
-
function isString(value) {
|
|
925
|
-
return value !== undefined;
|
|
926
|
-
}
|
|
927
|
-
function errorMessage(error) {
|
|
928
|
-
return error instanceof Error ? error.message : String(error);
|
|
929
|
-
}
|
|
930
|
-
function roleLabel(role) {
|
|
931
|
-
if (role === "you")
|
|
932
|
-
return "YOU";
|
|
933
|
-
if (role === "agent")
|
|
934
|
-
return "AGENT";
|
|
935
|
-
if (role === "tool")
|
|
936
|
-
return "TOOL";
|
|
937
|
-
return "SYSTEM";
|
|
938
|
-
}
|
|
939
|
-
function toneColor(tone, theme) {
|
|
940
|
-
if (tone === "muted")
|
|
941
|
-
return theme.muted;
|
|
942
|
-
if (tone === "success")
|
|
943
|
-
return theme.success;
|
|
944
|
-
if (tone === "danger")
|
|
945
|
-
return theme.danger;
|
|
946
|
-
if (tone === "accent")
|
|
947
|
-
return theme.accent;
|
|
948
|
-
return theme.primary;
|
|
949
|
-
}
|
|
950
|
-
function statusToneColor(tone, theme) {
|
|
951
|
-
return theme[tone ?? "primary"];
|
|
952
|
-
}
|
|
953
|
-
function formatContext(tokens) {
|
|
954
|
-
return tokens >= 1e6 ? `${(tokens / 1e6).toFixed(1)}M` : `${Math.round(tokens / 1000)}K`;
|
|
955
|
-
}
|
|
956
|
-
function activeRunId(state) {
|
|
957
|
-
return state.snapshot.runs.find(({ state: runState }) => runState === "running" || runState === "interrupt_requested")?.id;
|
|
958
|
-
}
|
|
959
|
-
function AgentTuiApp({
|
|
960
|
-
controller,
|
|
961
|
-
catalog,
|
|
962
|
-
conversations,
|
|
963
|
-
commands: customCommands = [],
|
|
964
|
-
theme,
|
|
965
|
-
workspace,
|
|
966
|
-
statusLine,
|
|
967
|
-
sessionId,
|
|
968
|
-
title,
|
|
969
|
-
onConversationChange,
|
|
970
|
-
onExit
|
|
971
|
-
}) {
|
|
972
|
-
const dimensions = useTerminalDimensions();
|
|
973
|
-
const [state, setState] = useState(controller.state());
|
|
974
|
-
const [dialog, setDialog] = useState();
|
|
975
|
-
const [modelQuery, setModelQuery] = useState("");
|
|
976
|
-
const [modelSearchFocused, setModelSearchFocused] = useState(true);
|
|
977
|
-
const [composer, setComposer] = useState(createAgentTuiComposer);
|
|
978
|
-
const [completionIndex, setCompletionIndex] = useState(0);
|
|
979
|
-
const [dismissedCompletionDraft, setDismissedCompletionDraft] = useState();
|
|
980
|
-
const draft = composer.draft;
|
|
981
|
-
const [localNotice, setLocalNotice] = useState();
|
|
982
|
-
const [hiddenBefore, setHiddenBefore] = useState(0);
|
|
983
|
-
const [sessions, setSessions] = useState([]);
|
|
984
|
-
const [sessionCursor, setSessionCursor] = useState();
|
|
985
|
-
const [viewport, setViewport] = useState(() => createTerminalFeedViewport(0, 1));
|
|
986
|
-
const previousTranscriptSize = useRef(0);
|
|
987
|
-
const previousConversationId = useRef(state.conversationId);
|
|
988
|
-
const composerRef = useRef(null);
|
|
989
|
-
const transcriptRef = useRef(null);
|
|
990
|
-
const compact = dimensions.width < 90;
|
|
991
|
-
const commands = useMemo(() => composeTuiCommands(createAgentTuiBuiltinCommands(), customCommands), [customCommands]);
|
|
992
|
-
const entries = useMemo(() => projectAgentTuiTranscript(state.snapshot).slice(hiddenBefore), [hiddenBefore, state.snapshot]);
|
|
993
|
-
const streamingRows = useMemo(() => Object.values(state.streaming).reduce((total, text) => total + Math.max(1, text.split(`
|
|
994
|
-
`).length), 0), [state.streaming]);
|
|
995
|
-
const transcriptUnits = entries.length + streamingRows;
|
|
996
|
-
const completions = useMemo(() => dismissedCompletionDraft === draft ? [] : commandCompletions(draft, commands).slice(0, 5), [commands, dismissedCompletionDraft, draft]);
|
|
997
|
-
const runId = activeRunId(state);
|
|
998
|
-
const activity = state.pendingApproval ? "APPROVAL" : runId ? "RUNNING" : "READY";
|
|
999
|
-
const selectedModel = catalog.models.find(({ id }) => id === state.selectedModelId);
|
|
1000
|
-
const statusRows = useMemo(() => {
|
|
1001
|
-
if (statusLine === false)
|
|
1002
|
-
return [];
|
|
1003
|
-
return (statusLine ?? defaultAgentTuiStatusLine)({
|
|
1004
|
-
title,
|
|
1005
|
-
workspace,
|
|
1006
|
-
activity,
|
|
1007
|
-
sessionId,
|
|
1008
|
-
conversationId: state.conversationId,
|
|
1009
|
-
...selectedModel && { model: selectedModel },
|
|
1010
|
-
snapshot: state.snapshot
|
|
1011
|
-
});
|
|
1012
|
-
}, [
|
|
1013
|
-
activity,
|
|
1014
|
-
selectedModel,
|
|
1015
|
-
sessionId,
|
|
1016
|
-
state.conversationId,
|
|
1017
|
-
state.snapshot,
|
|
1018
|
-
statusLine,
|
|
1019
|
-
title,
|
|
1020
|
-
workspace
|
|
1021
|
-
]);
|
|
1022
|
-
useEffect(() => controller.subscribe(setState), [controller]);
|
|
1023
|
-
useEffect(() => {
|
|
1024
|
-
const capacity = Math.max(1, dimensions.height - 12);
|
|
1025
|
-
const previous = previousTranscriptSize.current;
|
|
1026
|
-
const conversationChanged = previousConversationId.current !== state.conversationId;
|
|
1027
|
-
previousTranscriptSize.current = transcriptUnits;
|
|
1028
|
-
previousConversationId.current = state.conversationId;
|
|
1029
|
-
setViewport((current) => {
|
|
1030
|
-
if (conversationChanged || transcriptUnits < previous) {
|
|
1031
|
-
return createTerminalFeedViewport(transcriptUnits, capacity);
|
|
1032
|
-
}
|
|
1033
|
-
const appended = reduceTerminalFeedViewport(current, {
|
|
1034
|
-
type: "append",
|
|
1035
|
-
count: transcriptUnits - previous
|
|
1036
|
-
});
|
|
1037
|
-
return reduceTerminalFeedViewport(appended, { type: "resize", capacity });
|
|
1038
|
-
});
|
|
1039
|
-
}, [dimensions.height, state.conversationId, transcriptUnits]);
|
|
1040
|
-
useEffect(() => {
|
|
1041
|
-
if (dialog !== "sessions" || !conversations)
|
|
1042
|
-
return;
|
|
1043
|
-
conversations.list({ limit: 50 }).then((page) => {
|
|
1044
|
-
setSessions(page.items);
|
|
1045
|
-
setSessionCursor(page.nextCursor);
|
|
1046
|
-
}).catch((error) => setLocalNotice(errorMessage(error)));
|
|
1047
|
-
}, [conversations, dialog]);
|
|
1048
|
-
const applyOutcome = useCallback(async (outcome) => {
|
|
1049
|
-
if (outcome.type === "dialog") {
|
|
1050
|
-
setDialog(isDialog(outcome.dialog) ? outcome.dialog : "help");
|
|
1051
|
-
if (outcome.dialog === "model") {
|
|
1052
|
-
setModelQuery(outcome.query ?? "");
|
|
1053
|
-
setModelSearchFocused((outcome.query ?? "").length === 0);
|
|
1054
|
-
}
|
|
1055
|
-
return;
|
|
1056
|
-
}
|
|
1057
|
-
if (outcome.type === "notice") {
|
|
1058
|
-
setLocalNotice(outcome.message);
|
|
1059
|
-
return;
|
|
1060
|
-
}
|
|
1061
|
-
if (outcome.type === "submit") {
|
|
1062
|
-
await controller.submit(outcome.text);
|
|
1063
|
-
return;
|
|
1064
|
-
}
|
|
1065
|
-
if (outcome.action === "interrupt") {
|
|
1066
|
-
await controller.interrupt();
|
|
1067
|
-
} else if (outcome.action === "new-conversation") {
|
|
1068
|
-
const conversationId = createAgentTuiConversationId();
|
|
1069
|
-
await controller.switchConversation(conversationId);
|
|
1070
|
-
await onConversationChange(conversationId, "new");
|
|
1071
|
-
setHiddenBefore(0);
|
|
1072
|
-
} else if (outcome.action === "clear-conversation") {
|
|
1073
|
-
const conversationId = createAgentTuiConversationId();
|
|
1074
|
-
await controller.switchConversation(conversationId);
|
|
1075
|
-
await onConversationChange(conversationId, "clear");
|
|
1076
|
-
setHiddenBefore(0);
|
|
1077
|
-
} else if (outcome.action === "quit") {
|
|
1078
|
-
await onExit();
|
|
1079
|
-
}
|
|
1080
|
-
}, [controller, onConversationChange, onExit]);
|
|
1081
|
-
const submit = useCallback(async () => {
|
|
1082
|
-
const withCurrentText = setAgentTuiDraft(composer, composerRef.current?.plainText ?? composer.draft);
|
|
1083
|
-
const submitted = submitAgentTuiComposer(withCurrentText);
|
|
1084
|
-
if (!submitted.text)
|
|
1085
|
-
return;
|
|
1086
|
-
const text = submitted.text;
|
|
1087
|
-
const resolution = resolveTuiCommandSubmission(text, commands, completionIndex, dismissedCompletionDraft === text);
|
|
1088
|
-
try {
|
|
1089
|
-
if (resolution.type === "prompt") {
|
|
1090
|
-
await controller.submit(resolution.text);
|
|
1091
|
-
} else {
|
|
1092
|
-
const context = {
|
|
1093
|
-
conversationId: state.conversationId,
|
|
1094
|
-
...runId && { activeRunId: runId }
|
|
1095
|
-
};
|
|
1096
|
-
if (resolution.command.available && !resolution.command.available(context)) {
|
|
1097
|
-
setLocalNotice(`/${resolution.command.name} is not available in the current state.`);
|
|
1098
|
-
return;
|
|
1099
|
-
}
|
|
1100
|
-
await applyOutcome(await resolution.command.execute(resolution.argumentsText, context));
|
|
1101
|
-
}
|
|
1102
|
-
composerRef.current?.setText("");
|
|
1103
|
-
setComposer(submitted.state);
|
|
1104
|
-
setDismissedCompletionDraft(undefined);
|
|
1105
|
-
} catch (error) {
|
|
1106
|
-
setLocalNotice(error instanceof Error ? error.message : String(error));
|
|
1107
|
-
}
|
|
1108
|
-
}, [
|
|
1109
|
-
applyOutcome,
|
|
1110
|
-
commands,
|
|
1111
|
-
completionIndex,
|
|
1112
|
-
composer,
|
|
1113
|
-
controller,
|
|
1114
|
-
dismissedCompletionDraft,
|
|
1115
|
-
runId,
|
|
1116
|
-
state.conversationId
|
|
1117
|
-
]);
|
|
1118
|
-
useKeyboard((key) => {
|
|
1119
|
-
if (isAgentTuiExitKey(key)) {
|
|
1120
|
-
Promise.resolve(onExit()).catch((error) => setLocalNotice(errorMessage(error)));
|
|
1121
|
-
return;
|
|
1122
|
-
}
|
|
1123
|
-
if (state.pendingApproval && key.name === "y") {
|
|
1124
|
-
controller.respondToApproval(true).catch((error) => setLocalNotice(errorMessage(error)));
|
|
1125
|
-
return;
|
|
1126
|
-
}
|
|
1127
|
-
if (state.pendingApproval && (key.name === "n" || key.name === "escape")) {
|
|
1128
|
-
controller.respondToApproval(false, "Denied from the terminal host").catch((error) => setLocalNotice(errorMessage(error)));
|
|
1129
|
-
return;
|
|
1130
|
-
}
|
|
1131
|
-
if (dialog && key.name === "escape") {
|
|
1132
|
-
setDialog(undefined);
|
|
1133
|
-
return;
|
|
1134
|
-
}
|
|
1135
|
-
if (dialog === "model" && key.name === "tab") {
|
|
1136
|
-
key.preventDefault();
|
|
1137
|
-
key.stopPropagation();
|
|
1138
|
-
setModelSearchFocused((focused) => !focused);
|
|
1139
|
-
return;
|
|
1140
|
-
}
|
|
1141
|
-
if (!dialog && completions.length > 0 && key.name === "escape") {
|
|
1142
|
-
key.preventDefault();
|
|
1143
|
-
key.stopPropagation();
|
|
1144
|
-
setDismissedCompletionDraft(draft);
|
|
1145
|
-
return;
|
|
1146
|
-
}
|
|
1147
|
-
if (!dialog && completions.length > 0 && (key.name === "up" || key.name === "down")) {
|
|
1148
|
-
key.preventDefault();
|
|
1149
|
-
key.stopPropagation();
|
|
1150
|
-
const direction = key.name === "up" ? -1 : 1;
|
|
1151
|
-
setCompletionIndex((current) => moveCommandCompletionSelection(current, direction === -1 ? "previous" : "next", completions.length));
|
|
1152
|
-
return;
|
|
1153
|
-
}
|
|
1154
|
-
if (!dialog && key.name === "tab" && completions[0]) {
|
|
1155
|
-
key.preventDefault();
|
|
1156
|
-
key.stopPropagation();
|
|
1157
|
-
const selected = completions[completionIndex] ?? completions[0];
|
|
1158
|
-
const next = setAgentTuiDraft(composer, `/${selected.name} `);
|
|
1159
|
-
composerRef.current?.setText(next.draft);
|
|
1160
|
-
setComposer(next);
|
|
1161
|
-
setCompletionIndex(0);
|
|
1162
|
-
setDismissedCompletionDraft(undefined);
|
|
1163
|
-
return;
|
|
1164
|
-
}
|
|
1165
|
-
if (!dialog && key.name === "pageup") {
|
|
1166
|
-
transcriptRef.current?.scrollBy(-0.8, "viewport");
|
|
1167
|
-
setViewport((current) => reduceTerminalFeedViewport(current, { type: "page", pages: -1 }));
|
|
1168
|
-
}
|
|
1169
|
-
if (!dialog && key.name === "pagedown") {
|
|
1170
|
-
transcriptRef.current?.scrollBy(0.8, "viewport");
|
|
1171
|
-
setViewport((current) => reduceTerminalFeedViewport(current, { type: "page", pages: 1 }));
|
|
1172
|
-
}
|
|
1173
|
-
if (!dialog && key.option && (key.name === "up" || key.name === "down")) {
|
|
1174
|
-
const lines = key.name === "up" ? -1 : 1;
|
|
1175
|
-
transcriptRef.current?.scrollBy(lines, "step");
|
|
1176
|
-
setViewport((current) => reduceTerminalFeedViewport(current, { type: "scroll", lines }));
|
|
1177
|
-
}
|
|
1178
|
-
if (!dialog && key.name === "home" && key.ctrl) {
|
|
1179
|
-
transcriptRef.current?.scrollTo(0);
|
|
1180
|
-
setViewport((current) => reduceTerminalFeedViewport(current, { type: "home" }));
|
|
1181
|
-
}
|
|
1182
|
-
if (!dialog && key.name === "end" && key.ctrl) {
|
|
1183
|
-
transcriptRef.current?.scrollTo(Number.MAX_SAFE_INTEGER);
|
|
1184
|
-
setViewport((current) => reduceTerminalFeedViewport(current, { type: "end" }));
|
|
1185
|
-
}
|
|
1186
|
-
if (!dialog && key.ctrl && (key.name === "up" || key.name === "down")) {
|
|
1187
|
-
const next = navigateAgentTuiHistory(composer, key.name === "up" ? "older" : "newer");
|
|
1188
|
-
composerRef.current?.setText(next.draft);
|
|
1189
|
-
setComposer(next);
|
|
1190
|
-
}
|
|
1191
|
-
});
|
|
1192
|
-
const visibleModels = searchAgentTuiModels(catalog, modelQuery);
|
|
1193
|
-
const modelOptions = visibleModels.models.map((model) => {
|
|
1194
|
-
const coding = model.metrics.find(({ metric }) => metric === "coding");
|
|
1195
|
-
const evidence = coding ?? model.popularity;
|
|
1196
|
-
return {
|
|
1197
|
-
name: model.name,
|
|
1198
|
-
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)}` : ""}`
|
|
1199
|
-
};
|
|
1200
|
-
});
|
|
1201
|
-
const selectedModelIndex = Math.max(0, visibleModels.models.findIndex(({ id }) => id === state.selectedModelId));
|
|
1202
|
-
return /* @__PURE__ */ jsxs("box", {
|
|
1203
|
-
style: {
|
|
1204
|
-
width: "100%",
|
|
1205
|
-
height: "100%",
|
|
1206
|
-
flexDirection: "column"
|
|
1207
|
-
},
|
|
1208
|
-
children: [
|
|
1209
|
-
/* @__PURE__ */ jsxs("box", {
|
|
1210
|
-
style: {
|
|
1211
|
-
height: 1,
|
|
1212
|
-
paddingLeft: compact ? 1 : 2,
|
|
1213
|
-
paddingRight: compact ? 1 : 2,
|
|
1214
|
-
alignItems: "center",
|
|
1215
|
-
flexDirection: "row"
|
|
1216
|
-
},
|
|
1217
|
-
children: [
|
|
1218
|
-
/* @__PURE__ */ jsx("text", {
|
|
1219
|
-
fg: theme.accent,
|
|
1220
|
-
children: /* @__PURE__ */ jsxs("strong", {
|
|
1221
|
-
children: [
|
|
1222
|
-
"\u25C6 ",
|
|
1223
|
-
title
|
|
1224
|
-
]
|
|
1225
|
-
})
|
|
1226
|
-
}),
|
|
1227
|
-
!compact ? /* @__PURE__ */ jsxs("text", {
|
|
1228
|
-
fg: theme.muted,
|
|
1229
|
-
children: [
|
|
1230
|
-
" \xB7 ",
|
|
1231
|
-
selectedModel?.name ?? state.selectedModelId
|
|
1232
|
-
]
|
|
1233
|
-
}) : null
|
|
1234
|
-
]
|
|
1235
|
-
}),
|
|
1236
|
-
/* @__PURE__ */ jsxs("scrollbox", {
|
|
1237
|
-
ref: transcriptRef,
|
|
1238
|
-
focused: !dialog && !state.pendingApproval,
|
|
1239
|
-
stickyScroll: viewport.followTail,
|
|
1240
|
-
stickyStart: "bottom",
|
|
1241
|
-
style: {
|
|
1242
|
-
flexGrow: 1,
|
|
1243
|
-
paddingLeft: compact ? 1 : 2,
|
|
1244
|
-
paddingRight: compact ? 1 : 2,
|
|
1245
|
-
paddingTop: 1,
|
|
1246
|
-
contentOptions: { flexDirection: "column" },
|
|
1247
|
-
scrollbarOptions: { visible: !compact }
|
|
1248
|
-
},
|
|
1249
|
-
children: [
|
|
1250
|
-
entries.length === 0 ? /* @__PURE__ */ jsxs("box", {
|
|
1251
|
-
style: { flexDirection: "column", paddingTop: 1 },
|
|
1252
|
-
children: [
|
|
1253
|
-
/* @__PURE__ */ jsx("text", {
|
|
1254
|
-
fg: theme.primary,
|
|
1255
|
-
children: /* @__PURE__ */ jsx("strong", {
|
|
1256
|
-
children: "What do you want to build?"
|
|
1257
|
-
})
|
|
1258
|
-
}),
|
|
1259
|
-
/* @__PURE__ */ jsx("text", {
|
|
1260
|
-
fg: theme.muted,
|
|
1261
|
-
children: "Type / for commands"
|
|
1262
|
-
})
|
|
1263
|
-
]
|
|
1264
|
-
}) : entries.map((entry) => /* @__PURE__ */ jsxs("box", {
|
|
1265
|
-
style: { flexDirection: "column", marginBottom: 1 },
|
|
1266
|
-
children: [
|
|
1267
|
-
/* @__PURE__ */ jsx("text", {
|
|
1268
|
-
fg: entry.role === "you" ? theme.accent : theme.muted,
|
|
1269
|
-
children: /* @__PURE__ */ jsx("strong", {
|
|
1270
|
-
children: roleLabel(entry.role)
|
|
1271
|
-
})
|
|
1272
|
-
}),
|
|
1273
|
-
/* @__PURE__ */ jsx("text", {
|
|
1274
|
-
fg: toneColor(entry.tone, theme),
|
|
1275
|
-
children: entry.text
|
|
1276
|
-
})
|
|
1277
|
-
]
|
|
1278
|
-
}, entry.id)),
|
|
1279
|
-
Object.entries(state.streaming).map(([streamRunId, text]) => /* @__PURE__ */ jsxs("box", {
|
|
1280
|
-
style: { flexDirection: "column", marginBottom: 1 },
|
|
1281
|
-
children: [
|
|
1282
|
-
/* @__PURE__ */ jsx("text", {
|
|
1283
|
-
fg: theme.muted,
|
|
1284
|
-
children: /* @__PURE__ */ jsx("strong", {
|
|
1285
|
-
children: "AGENT \xB7 STREAMING"
|
|
1286
|
-
})
|
|
1287
|
-
}),
|
|
1288
|
-
/* @__PURE__ */ jsx("text", {
|
|
1289
|
-
fg: theme.primary,
|
|
1290
|
-
children: text
|
|
1291
|
-
})
|
|
1292
|
-
]
|
|
1293
|
-
}, streamRunId))
|
|
1294
|
-
]
|
|
1295
|
-
}),
|
|
1296
|
-
state.pendingApproval ? /* @__PURE__ */ jsxs("box", {
|
|
1297
|
-
title: " APPROVAL ",
|
|
1298
|
-
titleColor: theme.warning,
|
|
1299
|
-
style: {
|
|
1300
|
-
height: 7,
|
|
1301
|
-
marginLeft: compact ? 0 : 2,
|
|
1302
|
-
marginRight: compact ? 0 : 2,
|
|
1303
|
-
border: true,
|
|
1304
|
-
borderColor: theme.warning,
|
|
1305
|
-
backgroundColor: theme.panelRaised,
|
|
1306
|
-
padding: 1,
|
|
1307
|
-
flexDirection: "column"
|
|
1308
|
-
},
|
|
1309
|
-
children: [
|
|
1310
|
-
/* @__PURE__ */ jsx("text", {
|
|
1311
|
-
fg: theme.primary,
|
|
1312
|
-
children: /* @__PURE__ */ jsx("strong", {
|
|
1313
|
-
children: state.pendingApproval.toolName
|
|
1314
|
-
})
|
|
1315
|
-
}),
|
|
1316
|
-
/* @__PURE__ */ jsx("text", {
|
|
1317
|
-
fg: theme.muted,
|
|
1318
|
-
children: JSON.stringify(state.pendingApproval.input).slice(0, 240)
|
|
1319
|
-
}),
|
|
1320
|
-
/* @__PURE__ */ jsx("text", {
|
|
1321
|
-
fg: theme.warning,
|
|
1322
|
-
children: "Y approve once \xB7 N / Esc deny"
|
|
1323
|
-
})
|
|
1324
|
-
]
|
|
1325
|
-
}) : /* @__PURE__ */ jsxs("box", {
|
|
1326
|
-
style: { flexDirection: "column" },
|
|
1327
|
-
children: [
|
|
1328
|
-
completions.length > 0 ? /* @__PURE__ */ jsx("box", {
|
|
1329
|
-
style: {
|
|
1330
|
-
maxHeight: 7,
|
|
1331
|
-
marginLeft: compact ? 1 : 2,
|
|
1332
|
-
marginRight: compact ? 1 : 2,
|
|
1333
|
-
border: ["bottom"],
|
|
1334
|
-
borderColor: theme.border,
|
|
1335
|
-
flexDirection: "column"
|
|
1336
|
-
},
|
|
1337
|
-
children: completions.map((command, index) => /* @__PURE__ */ jsx("box", {
|
|
1338
|
-
style: {
|
|
1339
|
-
paddingLeft: 1,
|
|
1340
|
-
...index === completionIndex && {
|
|
1341
|
-
backgroundColor: theme.panelRaised
|
|
1342
|
-
}
|
|
1343
|
-
},
|
|
1344
|
-
children: /* @__PURE__ */ jsxs("text", {
|
|
1345
|
-
fg: index === completionIndex ? theme.primary : theme.muted,
|
|
1346
|
-
children: [
|
|
1347
|
-
/* @__PURE__ */ jsxs("span", {
|
|
1348
|
-
fg: theme.accent,
|
|
1349
|
-
children: [
|
|
1350
|
-
index === completionIndex ? "\u203A" : " ",
|
|
1351
|
-
" /",
|
|
1352
|
-
command.name
|
|
1353
|
-
]
|
|
1354
|
-
}),
|
|
1355
|
-
" ",
|
|
1356
|
-
command.description
|
|
1357
|
-
]
|
|
1358
|
-
})
|
|
1359
|
-
}, command.name))
|
|
1360
|
-
}) : null,
|
|
1361
|
-
/* @__PURE__ */ jsxs("box", {
|
|
1362
|
-
style: {
|
|
1363
|
-
height: 3,
|
|
1364
|
-
marginLeft: compact ? 1 : 2,
|
|
1365
|
-
marginRight: compact ? 1 : 2,
|
|
1366
|
-
border: ["top", "bottom"],
|
|
1367
|
-
borderColor: dialog ? theme.border : theme.borderActive,
|
|
1368
|
-
paddingLeft: 1,
|
|
1369
|
-
paddingRight: 1,
|
|
1370
|
-
flexDirection: "row"
|
|
1371
|
-
},
|
|
1372
|
-
children: [
|
|
1373
|
-
/* @__PURE__ */ jsx("text", {
|
|
1374
|
-
fg: dialog ? theme.muted : theme.accent,
|
|
1375
|
-
children: "\u203A "
|
|
1376
|
-
}),
|
|
1377
|
-
/* @__PURE__ */ jsx("textarea", {
|
|
1378
|
-
ref: composerRef,
|
|
1379
|
-
focused: !dialog,
|
|
1380
|
-
placeholder: "Message the agent or type / for commands\u2026",
|
|
1381
|
-
initialValue: draft,
|
|
1382
|
-
wrapMode: "word",
|
|
1383
|
-
keyBindings: [
|
|
1384
|
-
{ name: "return", action: "submit" },
|
|
1385
|
-
{ name: "return", shift: true, action: "newline" }
|
|
1386
|
-
],
|
|
1387
|
-
onContentChange: () => {
|
|
1388
|
-
const text = composerRef.current?.plainText ?? "";
|
|
1389
|
-
setComposer((current) => setAgentTuiDraft(current, text));
|
|
1390
|
-
setCompletionIndex(0);
|
|
1391
|
-
setDismissedCompletionDraft(undefined);
|
|
1392
|
-
},
|
|
1393
|
-
onSubmit: () => void submit(),
|
|
1394
|
-
style: { width: "100%", height: "100%" }
|
|
1395
|
-
})
|
|
1396
|
-
]
|
|
1397
|
-
})
|
|
1398
|
-
]
|
|
1399
|
-
}),
|
|
1400
|
-
localNotice || state.notice || viewport.unseen > 0 ? /* @__PURE__ */ jsx("box", {
|
|
1401
|
-
style: { height: 1, paddingLeft: compact ? 1 : 2, paddingRight: 1 },
|
|
1402
|
-
children: /* @__PURE__ */ jsx("text", {
|
|
1403
|
-
fg: localNotice || state.notice ? theme.danger : theme.accent,
|
|
1404
|
-
children: localNotice ?? state.notice?.message ?? `${viewport.unseen} new messages`
|
|
1405
|
-
})
|
|
1406
|
-
}) : null,
|
|
1407
|
-
statusRows.length > 0 ? /* @__PURE__ */ jsx("box", {
|
|
1408
|
-
style: {
|
|
1409
|
-
height: statusRows.length,
|
|
1410
|
-
paddingLeft: compact ? 1 : 2,
|
|
1411
|
-
paddingRight: 1,
|
|
1412
|
-
flexDirection: "column"
|
|
1413
|
-
},
|
|
1414
|
-
children: statusRows.map((row, rowIndex) => /* @__PURE__ */ jsx("text", {
|
|
1415
|
-
children: row.map((segment, segmentIndex) => /* @__PURE__ */ jsxs("span", {
|
|
1416
|
-
fg: statusToneColor(segment.tone, theme),
|
|
1417
|
-
bg: segmentIndex % 2 === 0 ? theme.panel : theme.panelRaised,
|
|
1418
|
-
children: [
|
|
1419
|
-
" ",
|
|
1420
|
-
segment.text,
|
|
1421
|
-
" "
|
|
1422
|
-
]
|
|
1423
|
-
}, `${segment.text}-${segmentIndex}`))
|
|
1424
|
-
}, `status-${rowIndex}`))
|
|
1425
|
-
}) : null,
|
|
1426
|
-
dialog ? /* @__PURE__ */ jsxs("box", {
|
|
1427
|
-
title: ` ${dialog.toUpperCase()} `,
|
|
1428
|
-
titleColor: theme.accent,
|
|
1429
|
-
style: {
|
|
1430
|
-
position: "absolute",
|
|
1431
|
-
left: compact ? 1 : Math.max(4, Math.floor(dimensions.width * 0.12)),
|
|
1432
|
-
right: compact ? 1 : Math.max(4, Math.floor(dimensions.width * 0.12)),
|
|
1433
|
-
top: compact ? 2 : 4,
|
|
1434
|
-
bottom: compact ? 2 : 4,
|
|
1435
|
-
border: true,
|
|
1436
|
-
borderColor: theme.borderActive,
|
|
1437
|
-
backgroundColor: theme.panelRaised,
|
|
1438
|
-
padding: 1,
|
|
1439
|
-
flexDirection: "column"
|
|
1440
|
-
},
|
|
1441
|
-
children: [
|
|
1442
|
-
dialog === "model" ? /* @__PURE__ */ jsxs("box", {
|
|
1443
|
-
style: { flexDirection: "column", width: "100%", height: "100%" },
|
|
1444
|
-
children: [
|
|
1445
|
-
/* @__PURE__ */ jsxs("text", {
|
|
1446
|
-
fg: theme.muted,
|
|
1447
|
-
children: [
|
|
1448
|
-
"Search the full catalog \xB7 showing ",
|
|
1449
|
-
visibleModels.models.length,
|
|
1450
|
-
" of",
|
|
1451
|
-
" ",
|
|
1452
|
-
visibleModels.total,
|
|
1453
|
-
" matches \xB7 Tab switches search/list"
|
|
1454
|
-
]
|
|
1455
|
-
}),
|
|
1456
|
-
/* @__PURE__ */ jsx("box", {
|
|
1457
|
-
style: {
|
|
1458
|
-
height: 3,
|
|
1459
|
-
border: true,
|
|
1460
|
-
borderColor: modelSearchFocused ? theme.borderActive : theme.border,
|
|
1461
|
-
paddingLeft: 1,
|
|
1462
|
-
paddingRight: 1
|
|
1463
|
-
},
|
|
1464
|
-
children: /* @__PURE__ */ jsx("input", {
|
|
1465
|
-
focused: modelSearchFocused,
|
|
1466
|
-
value: modelQuery,
|
|
1467
|
-
placeholder: "Filter by model, provider or capability\u2026",
|
|
1468
|
-
onInput: setModelQuery,
|
|
1469
|
-
onSubmit: () => setModelSearchFocused(false),
|
|
1470
|
-
style: { width: "100%" }
|
|
1471
|
-
})
|
|
1472
|
-
}),
|
|
1473
|
-
/* @__PURE__ */ jsx("select", {
|
|
1474
|
-
focused: !modelSearchFocused,
|
|
1475
|
-
options: modelOptions,
|
|
1476
|
-
selectedIndex: selectedModelIndex,
|
|
1477
|
-
showDescription: true,
|
|
1478
|
-
showScrollIndicator: true,
|
|
1479
|
-
wrapSelection: true,
|
|
1480
|
-
backgroundColor: theme.panelRaised,
|
|
1481
|
-
textColor: theme.primary,
|
|
1482
|
-
descriptionColor: theme.muted,
|
|
1483
|
-
selectedBackgroundColor: theme.accent,
|
|
1484
|
-
selectedTextColor: theme.canvas,
|
|
1485
|
-
selectedDescriptionColor: theme.canvas,
|
|
1486
|
-
style: { width: "100%", flexGrow: 1 },
|
|
1487
|
-
onSelect: (index) => {
|
|
1488
|
-
const model = visibleModels.models[index];
|
|
1489
|
-
if (!model)
|
|
1490
|
-
return;
|
|
1491
|
-
controller.selectModel(model.id).then(() => setDialog(undefined)).catch((error) => setLocalNotice(errorMessage(error)));
|
|
1492
|
-
}
|
|
1493
|
-
})
|
|
1494
|
-
]
|
|
1495
|
-
}) : dialog === "sessions" ? conversations ? /* @__PURE__ */ jsx("select", {
|
|
1496
|
-
focused: true,
|
|
1497
|
-
options: sessions.map((session) => ({
|
|
1498
|
-
name: session.conversationId,
|
|
1499
|
-
description: `${session.activeRuns > 0 ? `${session.activeRuns} active \xB7 ` : ""}${session.preview}`
|
|
1500
|
-
})),
|
|
1501
|
-
showDescription: true,
|
|
1502
|
-
showScrollIndicator: true,
|
|
1503
|
-
backgroundColor: theme.panelRaised,
|
|
1504
|
-
textColor: theme.primary,
|
|
1505
|
-
descriptionColor: theme.muted,
|
|
1506
|
-
selectedBackgroundColor: theme.accent,
|
|
1507
|
-
selectedTextColor: theme.canvas,
|
|
1508
|
-
selectedDescriptionColor: theme.canvas,
|
|
1509
|
-
style: { width: "100%", height: "100%" },
|
|
1510
|
-
onSelect: (index) => {
|
|
1511
|
-
const selected = sessions[index];
|
|
1512
|
-
if (!selected)
|
|
1513
|
-
return;
|
|
1514
|
-
controller.switchConversation(selected.conversationId).then(async () => {
|
|
1515
|
-
await onConversationChange(selected.conversationId, "resume");
|
|
1516
|
-
setDialog(undefined);
|
|
1517
|
-
setHiddenBefore(0);
|
|
1518
|
-
}).catch((error) => setLocalNotice(errorMessage(error)));
|
|
1519
|
-
}
|
|
1520
|
-
}) : /* @__PURE__ */ jsx("text", {
|
|
1521
|
-
fg: theme.muted,
|
|
1522
|
-
children: "This host does not provide a conversation catalog."
|
|
1523
|
-
}) : dialog === "help" ? /* @__PURE__ */ jsx("scrollbox", {
|
|
1524
|
-
focused: true,
|
|
1525
|
-
style: { flexGrow: 1, contentOptions: { flexDirection: "column" } },
|
|
1526
|
-
children: commands.map((command) => /* @__PURE__ */ jsxs("text", {
|
|
1527
|
-
fg: theme.primary,
|
|
1528
|
-
children: [
|
|
1529
|
-
/* @__PURE__ */ jsxs("span", {
|
|
1530
|
-
fg: theme.accent,
|
|
1531
|
-
children: [
|
|
1532
|
-
"/",
|
|
1533
|
-
command.name
|
|
1534
|
-
]
|
|
1535
|
-
}),
|
|
1536
|
-
" ",
|
|
1537
|
-
command.description
|
|
1538
|
-
]
|
|
1539
|
-
}, command.name))
|
|
1540
|
-
}) : dialog === "status" ? /* @__PURE__ */ jsxs("box", {
|
|
1541
|
-
style: { flexDirection: "column" },
|
|
1542
|
-
children: [
|
|
1543
|
-
/* @__PURE__ */ jsxs("text", {
|
|
1544
|
-
fg: theme.primary,
|
|
1545
|
-
children: [
|
|
1546
|
-
"Session ",
|
|
1547
|
-
sessionId
|
|
1548
|
-
]
|
|
1549
|
-
}),
|
|
1550
|
-
/* @__PURE__ */ jsxs("text", {
|
|
1551
|
-
fg: theme.primary,
|
|
1552
|
-
children: [
|
|
1553
|
-
"Conversation ",
|
|
1554
|
-
state.conversationId
|
|
1555
|
-
]
|
|
1556
|
-
}),
|
|
1557
|
-
/* @__PURE__ */ jsxs("text", {
|
|
1558
|
-
fg: theme.primary,
|
|
1559
|
-
children: [
|
|
1560
|
-
"Model ",
|
|
1561
|
-
state.selectedModelId
|
|
1562
|
-
]
|
|
1563
|
-
}),
|
|
1564
|
-
/* @__PURE__ */ jsxs("text", {
|
|
1565
|
-
fg: theme.primary,
|
|
1566
|
-
children: [
|
|
1567
|
-
"Run ",
|
|
1568
|
-
runId ?? "idle"
|
|
1569
|
-
]
|
|
1570
|
-
}),
|
|
1571
|
-
/* @__PURE__ */ jsx("text", {
|
|
1572
|
-
fg: theme.muted,
|
|
1573
|
-
children: "External clients submit through this host's controller."
|
|
1574
|
-
})
|
|
1575
|
-
]
|
|
1576
|
-
}) : dialog === "tools" ? /* @__PURE__ */ jsxs("box", {
|
|
1577
|
-
style: { flexDirection: "column" },
|
|
1578
|
-
children: [
|
|
1579
|
-
[
|
|
1580
|
-
...new Set(entries.filter(({ role }) => role === "tool").map(({ text }) => text.split(" ")[1]).filter(isString))
|
|
1581
|
-
].map((name) => /* @__PURE__ */ jsx("text", {
|
|
1582
|
-
fg: theme.primary,
|
|
1583
|
-
children: name
|
|
1584
|
-
}, name)),
|
|
1585
|
-
/* @__PURE__ */ jsx("text", {
|
|
1586
|
-
fg: theme.muted,
|
|
1587
|
-
children: "Direct tools retain their own durable identity."
|
|
1588
|
-
})
|
|
1589
|
-
]
|
|
1590
|
-
}) : dialog === "permissions" ? /* @__PURE__ */ jsxs("box", {
|
|
1591
|
-
style: { flexDirection: "column" },
|
|
1592
|
-
children: [
|
|
1593
|
-
/* @__PURE__ */ jsx("text", {
|
|
1594
|
-
fg: theme.primary,
|
|
1595
|
-
children: "Approval decisions are per exact tool call."
|
|
1596
|
-
}),
|
|
1597
|
-
/* @__PURE__ */ jsx("text", {
|
|
1598
|
-
fg: theme.muted,
|
|
1599
|
-
children: "Sandbox enforcement is supplied and reported by the embedding host."
|
|
1600
|
-
})
|
|
1601
|
-
]
|
|
1602
|
-
}) : /* @__PURE__ */ jsxs("box", {
|
|
1603
|
-
style: { flexDirection: "column" },
|
|
1604
|
-
children: [
|
|
1605
|
-
/* @__PURE__ */ jsx("text", {
|
|
1606
|
-
fg: theme.primary,
|
|
1607
|
-
children: "Skills and resources are discovered lazily by the harness."
|
|
1608
|
-
}),
|
|
1609
|
-
/* @__PURE__ */ jsx("text", {
|
|
1610
|
-
fg: theme.muted,
|
|
1611
|
-
children: "The model reads exact content through the direct read_resource tool."
|
|
1612
|
-
})
|
|
1613
|
-
]
|
|
1614
|
-
}),
|
|
1615
|
-
dialog === "sessions" && sessionCursor ? /* @__PURE__ */ jsx("text", {
|
|
1616
|
-
fg: theme.muted,
|
|
1617
|
-
children: "More conversations are available."
|
|
1618
|
-
}) : null,
|
|
1619
|
-
/* @__PURE__ */ jsx("text", {
|
|
1620
|
-
fg: theme.muted,
|
|
1621
|
-
children: "Esc close"
|
|
1622
|
-
})
|
|
1623
|
-
]
|
|
1624
|
-
}) : null
|
|
1625
|
-
]
|
|
1626
|
-
});
|
|
1627
|
-
}
|
|
1628
|
-
|
|
1629
|
-
// src/config.ts
|
|
1630
|
-
import { createHash } from "crypto";
|
|
1631
|
-
import { mkdir as mkdir2, readFile as readFile2, rename as rename2, unlink as unlink2, writeFile as writeFile2 } from "fs/promises";
|
|
1632
|
-
import path3 from "path";
|
|
1633
|
-
import { AgentModelSelectionSchema } from "stitchkit/agent-runtime";
|
|
1634
|
-
import { z as z9 } from "zod";
|
|
1635
|
-
var SelectionFileSchema = z9.object({
|
|
1636
|
-
conversationId: z9.string().min(1),
|
|
1637
|
-
selection: AgentModelSelectionSchema
|
|
1638
|
-
}).strict();
|
|
1639
|
-
var defaultAgentTuiTheme = {
|
|
1640
|
-
canvas: "#111111",
|
|
1641
|
-
panel: "#1e2129",
|
|
1642
|
-
panelRaised: "#303441",
|
|
1643
|
-
border: "#454a57",
|
|
1644
|
-
borderActive: "#d9dde7",
|
|
1645
|
-
primary: "#e6ebf5",
|
|
1646
|
-
muted: "#828aa0",
|
|
1647
|
-
accent: "#e58a66",
|
|
1648
|
-
success: "#64df98",
|
|
1649
|
-
danger: "#ff6b78",
|
|
1650
|
-
warning: "#ffd04f"
|
|
1651
|
-
};
|
|
1652
|
-
function defineAgentTui(config) {
|
|
1653
|
-
return config;
|
|
1654
|
-
}
|
|
1655
|
-
function resolveAgentTuiTheme(theme) {
|
|
1656
|
-
return { ...defaultAgentTuiTheme, ...theme };
|
|
1657
|
-
}
|
|
1658
|
-
function createFileAgentModelSelectionStore(workspace) {
|
|
1659
|
-
const directory = path3.join(workspace, ".stitchkit", "tui", "models");
|
|
1660
|
-
const filename = (conversationId) => path3.join(directory, `${createHash("sha256").update(conversationId).digest("hex")}.json`);
|
|
1661
|
-
const load = async (conversationId) => {
|
|
1662
|
-
try {
|
|
1663
|
-
const record = SelectionFileSchema.parse(JSON.parse(await readFile2(filename(conversationId), "utf8")));
|
|
1664
|
-
if (record.conversationId !== conversationId) {
|
|
1665
|
-
throw new Error("Agent TUI model selection identity does not match its path");
|
|
1666
|
-
}
|
|
1667
|
-
return record.selection;
|
|
1668
|
-
} catch (error) {
|
|
1669
|
-
if (!(error instanceof Error && ("code" in error) && error.code === "ENOENT"))
|
|
1670
|
-
throw error;
|
|
1671
|
-
return;
|
|
1672
|
-
}
|
|
1673
|
-
};
|
|
1674
|
-
return {
|
|
1675
|
-
load,
|
|
1676
|
-
async save(conversationId, rawSelection) {
|
|
1677
|
-
const selection = AgentModelSelectionSchema.parse(rawSelection);
|
|
1678
|
-
const target = filename(conversationId);
|
|
1679
|
-
const record = SelectionFileSchema.parse({ conversationId, selection });
|
|
1680
|
-
await mkdir2(directory, { recursive: true, mode: 448 });
|
|
1681
|
-
const temporary = `${target}.${crypto.randomUUID()}.tmp`;
|
|
1682
|
-
await writeFile2(temporary, `${JSON.stringify(record, null, 2)}
|
|
1683
|
-
`, {
|
|
1684
|
-
encoding: "utf8",
|
|
1685
|
-
mode: 384,
|
|
1686
|
-
flag: "wx"
|
|
1687
|
-
});
|
|
1688
|
-
try {
|
|
1689
|
-
await rename2(temporary, target);
|
|
1690
|
-
} catch (error) {
|
|
1691
|
-
await unlink2(temporary).catch(() => {
|
|
1692
|
-
return;
|
|
1693
|
-
});
|
|
1694
|
-
throw error;
|
|
1695
|
-
}
|
|
1696
|
-
}
|
|
1697
|
-
};
|
|
1698
|
-
}
|
|
1699
|
-
|
|
1700
|
-
// src/controller.ts
|
|
1701
|
-
function activeRun(snapshot) {
|
|
1702
|
-
return snapshot.runs.find((run) => run.state === "running" || run.state === "interrupt_requested");
|
|
1703
|
-
}
|
|
1704
|
-
function pinnedModel(snapshot, runId) {
|
|
1705
|
-
const run = snapshot.runs.find(({ id }) => id === runId);
|
|
1706
|
-
const inputMessage = snapshot.messages.find(({ id }) => id === run?.inputMessageIds[0]);
|
|
1707
|
-
const metadata = inputMessage?.metadata;
|
|
1708
|
-
if (typeof metadata !== "object" || metadata === null)
|
|
1709
|
-
return;
|
|
1710
|
-
const modelId = Reflect.get(metadata, "modelId");
|
|
1711
|
-
return typeof modelId === "string" && modelId.length > 0 ? modelId : undefined;
|
|
1712
|
-
}
|
|
1713
|
-
async function createAgentTuiController(input) {
|
|
1714
|
-
let conversationId = input.conversationId;
|
|
1715
|
-
const listeners = new Set;
|
|
1716
|
-
let current = {
|
|
1717
|
-
conversationId,
|
|
1718
|
-
snapshot: await input.harness.snapshot(conversationId),
|
|
1719
|
-
streaming: {}
|
|
1720
|
-
};
|
|
1721
|
-
const emit = () => {
|
|
1722
|
-
for (const listener of listeners)
|
|
1723
|
-
listener(current);
|
|
1724
|
-
};
|
|
1725
|
-
let refreshVersion = 0;
|
|
1726
|
-
const refresh = async () => {
|
|
1727
|
-
const targetConversationId = conversationId;
|
|
1728
|
-
const version = ++refreshVersion;
|
|
1729
|
-
const [snapshot, approvals, selection] = await Promise.all([
|
|
1730
|
-
input.harness.snapshot(targetConversationId),
|
|
1731
|
-
input.harness.pendingApprovals(targetConversationId),
|
|
1732
|
-
input.selections.load(targetConversationId)
|
|
1733
|
-
]);
|
|
1734
|
-
if (version !== refreshVersion || targetConversationId !== conversationId)
|
|
1735
|
-
return;
|
|
1736
|
-
const next = {
|
|
1737
|
-
...current,
|
|
1738
|
-
conversationId: targetConversationId,
|
|
1739
|
-
snapshot,
|
|
1740
|
-
...selection && { selectedModelId: selection.modelId },
|
|
1741
|
-
...approvals[0] && { pendingApproval: approvals[0] }
|
|
1742
|
-
};
|
|
1743
|
-
if (!approvals[0])
|
|
1744
|
-
delete next.pendingApproval;
|
|
1745
|
-
current = next;
|
|
1746
|
-
emit();
|
|
1747
|
-
};
|
|
1748
|
-
let selection = await input.selections.load(conversationId);
|
|
1749
|
-
if (!selection) {
|
|
1750
|
-
const modelId = input.preferredModelId && input.catalog.models.some(({ id }) => id === input.preferredModelId) && input.preferredModelId || input.catalog.models[0]?.id;
|
|
1751
|
-
if (!modelId)
|
|
1752
|
-
throw new Error("The Agent TUI model catalog is empty");
|
|
1753
|
-
selection = { modelId, selectedAt: new Date().toISOString() };
|
|
1754
|
-
await input.selections.save(conversationId, selection);
|
|
1755
|
-
}
|
|
1756
|
-
current = { ...current, selectedModelId: selection.modelId };
|
|
1757
|
-
const unsubscribe = input.harness.subscribe((event) => {
|
|
1758
|
-
if (event.conversationId !== conversationId)
|
|
1759
|
-
return;
|
|
1760
|
-
input.onDiagnostic?.({
|
|
1761
|
-
conversationId,
|
|
1762
|
-
...event.runId && { runId: event.runId },
|
|
1763
|
-
event
|
|
1764
|
-
});
|
|
1765
|
-
if (event.type === "assistant-delta") {
|
|
1766
|
-
current = {
|
|
1767
|
-
...current,
|
|
1768
|
-
streaming: {
|
|
1769
|
-
...current.streaming,
|
|
1770
|
-
[event.runId]: (current.streaming[event.runId] ?? "") + event.textDelta
|
|
1771
|
-
}
|
|
1772
|
-
};
|
|
1773
|
-
emit();
|
|
1774
|
-
return;
|
|
1775
|
-
}
|
|
1776
|
-
if (event.type === "terminal") {
|
|
1777
|
-
const streaming = Object.fromEntries(Object.entries(current.streaming).filter(([runId]) => runId !== event.runId));
|
|
1778
|
-
current = {
|
|
1779
|
-
...current,
|
|
1780
|
-
streaming,
|
|
1781
|
-
...event.reason === "provider_failure" ? {
|
|
1782
|
-
notice: {
|
|
1783
|
-
tone: "error",
|
|
1784
|
-
message: "The model run failed. You can send the next message."
|
|
1785
|
-
}
|
|
1786
|
-
} : {}
|
|
1787
|
-
};
|
|
1788
|
-
}
|
|
1789
|
-
if (event.type === "admission" || event.type === "assistant-checkpoint" || event.type === "run-state" || event.type === "terminal") {
|
|
1790
|
-
refresh();
|
|
1791
|
-
}
|
|
1792
|
-
});
|
|
1793
|
-
await refresh();
|
|
1794
|
-
const selected = async () => {
|
|
1795
|
-
const found = await input.selections.load(conversationId);
|
|
1796
|
-
if (!found)
|
|
1797
|
-
throw new Error("Select a model before submitting");
|
|
1798
|
-
return found.modelId;
|
|
1799
|
-
};
|
|
1800
|
-
return {
|
|
1801
|
-
state: () => current,
|
|
1802
|
-
subscribe(listener) {
|
|
1803
|
-
listeners.add(listener);
|
|
1804
|
-
listener(current);
|
|
1805
|
-
return () => listeners.delete(listener);
|
|
1806
|
-
},
|
|
1807
|
-
async submit(rawText, idempotencyKey = crypto.randomUUID()) {
|
|
1808
|
-
const text = rawText.trim();
|
|
1809
|
-
if (!text)
|
|
1810
|
-
throw new Error("Agent message is empty");
|
|
1811
|
-
const modelId = await selected();
|
|
1812
|
-
const ticket = input.harness.submit({
|
|
1813
|
-
conversationId,
|
|
1814
|
-
idempotencyKey,
|
|
1815
|
-
context: await input.context(),
|
|
1816
|
-
parts: [{ type: "text", text }],
|
|
1817
|
-
metadata: { modelId }
|
|
1818
|
-
});
|
|
1819
|
-
const admission = await ticket.admission;
|
|
1820
|
-
ticket.result.catch(() => {
|
|
1821
|
-
return;
|
|
1822
|
-
});
|
|
1823
|
-
await refresh();
|
|
1824
|
-
return admission.runId;
|
|
1825
|
-
},
|
|
1826
|
-
async selectModel(modelId) {
|
|
1827
|
-
if (!input.catalog.models.some((model) => model.id === modelId)) {
|
|
1828
|
-
throw new Error(`Unknown model: ${modelId}`);
|
|
1829
|
-
}
|
|
1830
|
-
await input.selections.save(conversationId, {
|
|
1831
|
-
modelId,
|
|
1832
|
-
selectedAt: new Date().toISOString()
|
|
1833
|
-
});
|
|
1834
|
-
await refresh();
|
|
1835
|
-
},
|
|
1836
|
-
async switchConversation(nextConversationId) {
|
|
1837
|
-
const previousModelId = current.selectedModelId;
|
|
1838
|
-
conversationId = nextConversationId;
|
|
1839
|
-
const version = ++refreshVersion;
|
|
1840
|
-
const snapshot = await input.harness.snapshot(nextConversationId);
|
|
1841
|
-
if (version !== refreshVersion || conversationId !== nextConversationId)
|
|
1842
|
-
return;
|
|
1843
|
-
current = {
|
|
1844
|
-
conversationId: nextConversationId,
|
|
1845
|
-
snapshot,
|
|
1846
|
-
streaming: {}
|
|
1847
|
-
};
|
|
1848
|
-
let nextSelection = await input.selections.load(nextConversationId);
|
|
1849
|
-
if (version !== refreshVersion || conversationId !== nextConversationId)
|
|
1850
|
-
return;
|
|
1851
|
-
if (!nextSelection) {
|
|
1852
|
-
const modelId = previousModelId ?? input.catalog.models[0]?.id;
|
|
1853
|
-
if (!modelId)
|
|
1854
|
-
throw new Error("The Agent TUI model catalog is empty");
|
|
1855
|
-
nextSelection = { modelId, selectedAt: new Date().toISOString() };
|
|
1856
|
-
await input.selections.save(nextConversationId, nextSelection);
|
|
1857
|
-
if (version !== refreshVersion || conversationId !== nextConversationId)
|
|
1858
|
-
return;
|
|
1859
|
-
}
|
|
1860
|
-
await refresh();
|
|
1861
|
-
},
|
|
1862
|
-
async respondToApproval(approved, reason) {
|
|
1863
|
-
const approval = current.pendingApproval;
|
|
1864
|
-
if (!approval)
|
|
1865
|
-
throw new Error("No approval is pending");
|
|
1866
|
-
const ticket = await input.harness.respondToApproval({
|
|
1867
|
-
conversationId,
|
|
1868
|
-
approvalId: approval.approvalId,
|
|
1869
|
-
approved,
|
|
1870
|
-
...reason && { reason },
|
|
1871
|
-
context: await input.context(),
|
|
1872
|
-
metadata: {
|
|
1873
|
-
modelId: pinnedModel(current.snapshot, approval.runId) ?? await selected()
|
|
1874
|
-
}
|
|
1875
|
-
});
|
|
1876
|
-
const admission = await ticket.admission;
|
|
1877
|
-
ticket.result.catch(() => {
|
|
1878
|
-
return;
|
|
1879
|
-
});
|
|
1880
|
-
await refresh();
|
|
1881
|
-
return admission.runId;
|
|
1882
|
-
},
|
|
1883
|
-
async interrupt(runId) {
|
|
1884
|
-
const target = runId ?? activeRun(current.snapshot)?.id;
|
|
1885
|
-
if (!target)
|
|
1886
|
-
throw new Error("No active run to interrupt");
|
|
1887
|
-
await input.harness.interrupt({ conversationId, runId: target });
|
|
1888
|
-
await refresh();
|
|
1889
|
-
},
|
|
1890
|
-
async close() {
|
|
1891
|
-
unsubscribe();
|
|
1892
|
-
await input.harness.close({ gracePeriodMs: 1000, forceTimeoutMs: 1000 });
|
|
1893
|
-
}
|
|
1894
|
-
};
|
|
1895
|
-
}
|
|
1896
|
-
|
|
1897
|
-
// src/diagnostics.ts
|
|
1898
|
-
import { lstat, mkdir as mkdir3, readdir as readdir2, rm } from "fs/promises";
|
|
1899
|
-
import path4 from "path";
|
|
1900
|
-
import { createDiagnosticJournal } from "stitchkit/application/diagnostic-journal";
|
|
1901
|
-
import { z as z10 } from "zod";
|
|
1902
|
-
var RUNTIME_EVENT_TYPES = new Set([
|
|
1903
|
-
"admission",
|
|
1904
|
-
"run-state",
|
|
1905
|
-
"terminal",
|
|
1906
|
-
"tool-status",
|
|
1907
|
-
"run-started",
|
|
1908
|
-
"run-terminal",
|
|
1909
|
-
"step-finished"
|
|
1910
|
-
]);
|
|
1911
|
-
var MAX_SESSION_JOURNALS = 8;
|
|
1912
|
-
var BaseEventSchema = z10.object({
|
|
1913
|
-
schemaVersion: z10.literal(1),
|
|
1914
|
-
occurredAt: z10.iso.datetime({ offset: true })
|
|
1915
|
-
});
|
|
1916
|
-
var AgentTuiDiagnosticEventSchema = z10.discriminatedUnion("type", [
|
|
1917
|
-
BaseEventSchema.extend({
|
|
1918
|
-
type: z10.literal("host-started"),
|
|
1919
|
-
sessionId: z10.string().min(8),
|
|
1920
|
-
conversationId: z10.string().min(1),
|
|
1921
|
-
launchMode: z10.enum(["fresh", "explicit"])
|
|
1922
|
-
}).strict(),
|
|
1923
|
-
BaseEventSchema.extend({
|
|
1924
|
-
type: z10.literal("conversation-changed"),
|
|
1925
|
-
sessionId: z10.string().min(8),
|
|
1926
|
-
previousConversationId: z10.string().min(1),
|
|
1927
|
-
conversationId: z10.string().min(1),
|
|
1928
|
-
reason: z10.enum(["new", "clear", "resume"])
|
|
1929
|
-
}).strict(),
|
|
1930
|
-
BaseEventSchema.extend({
|
|
1931
|
-
type: z10.literal("submission-admitted"),
|
|
1932
|
-
sessionId: z10.string().min(8),
|
|
1933
|
-
conversationId: z10.string().min(1),
|
|
1934
|
-
runId: z10.string().min(1),
|
|
1935
|
-
source: z10.enum(["terminal", "client"])
|
|
1936
|
-
}).strict(),
|
|
1937
|
-
BaseEventSchema.extend({
|
|
1938
|
-
type: z10.literal("runtime-event"),
|
|
1939
|
-
conversationId: z10.string().min(1).optional(),
|
|
1940
|
-
runId: z10.string().min(1).optional(),
|
|
1941
|
-
eventType: z10.string().min(1),
|
|
1942
|
-
state: z10.string().min(1).optional()
|
|
1943
|
-
}).strict(),
|
|
1944
|
-
BaseEventSchema.extend({
|
|
1945
|
-
type: z10.literal("request-failed"),
|
|
1946
|
-
sessionId: z10.string().min(8),
|
|
1947
|
-
operation: z10.enum(["status", "submit", "interrupt"])
|
|
1948
|
-
}).strict(),
|
|
1949
|
-
BaseEventSchema.extend({
|
|
1950
|
-
type: z10.literal("host-closed"),
|
|
1951
|
-
sessionId: z10.string().min(8),
|
|
1952
|
-
conversationId: z10.string().min(1)
|
|
1953
|
-
}).strict()
|
|
1954
|
-
]);
|
|
1955
|
-
function stringField(value, name) {
|
|
1956
|
-
const field = Reflect.get(value, name);
|
|
1957
|
-
return typeof field === "string" && field.length > 0 ? field : undefined;
|
|
1958
|
-
}
|
|
1959
|
-
function projectAgentTuiRuntimeDiagnostic(value, occurredAt = new Date().toISOString()) {
|
|
1960
|
-
if (typeof value !== "object" || value === null)
|
|
1961
|
-
return;
|
|
1962
|
-
const nested = Reflect.get(value, "event");
|
|
1963
|
-
const event = typeof nested === "object" && nested !== null ? nested : value;
|
|
1964
|
-
const eventType = stringField(event, "type");
|
|
1965
|
-
if (!eventType || !RUNTIME_EVENT_TYPES.has(eventType))
|
|
1966
|
-
return;
|
|
1967
|
-
const conversationId = stringField(value, "conversationId") ?? stringField(event, "conversationId");
|
|
1968
|
-
const runId = stringField(value, "runId") ?? stringField(event, "runId");
|
|
1969
|
-
const state = stringField(event, "state");
|
|
1970
|
-
return AgentTuiDiagnosticEventSchema.parse({
|
|
1971
|
-
schemaVersion: 1,
|
|
1972
|
-
occurredAt,
|
|
1973
|
-
type: "runtime-event",
|
|
1974
|
-
...conversationId && { conversationId },
|
|
1975
|
-
...runId && { runId },
|
|
1976
|
-
eventType,
|
|
1977
|
-
...state && { state }
|
|
1978
|
-
});
|
|
1979
|
-
}
|
|
1980
|
-
async function pruneOldSessionJournals(input) {
|
|
1981
|
-
const liveSessionIds = new Set((await listAgentTuiSessions(input.workspace)).map(({ sessionId }) => sessionId));
|
|
1982
|
-
liveSessionIds.add(input.currentSessionId);
|
|
1983
|
-
const groups = new Map;
|
|
1984
|
-
for (const name of await readdir2(input.directory)) {
|
|
1985
|
-
const match = /^([a-f0-9]{16})\.jsonl(?:\.\d+|\.lock)?$/.exec(name);
|
|
1986
|
-
const sessionId = match?.[1];
|
|
1987
|
-
if (!sessionId || liveSessionIds.has(sessionId))
|
|
1988
|
-
continue;
|
|
1989
|
-
const filename = path4.join(input.directory, name);
|
|
1990
|
-
const info = await lstat(filename);
|
|
1991
|
-
if (!info.isFile())
|
|
1992
|
-
continue;
|
|
1993
|
-
const group = groups.get(sessionId) ?? { files: [], modifiedAt: 0 };
|
|
1994
|
-
group.files.push(filename);
|
|
1995
|
-
group.modifiedAt = Math.max(group.modifiedAt, info.mtimeMs);
|
|
1996
|
-
groups.set(sessionId, group);
|
|
1997
|
-
}
|
|
1998
|
-
const inactive = [...groups.values()].sort((left, right) => right.modifiedAt - left.modifiedAt);
|
|
1999
|
-
for (const group of inactive.slice(MAX_SESSION_JOURNALS)) {
|
|
2000
|
-
for (const filename of group.files)
|
|
2001
|
-
await rm(filename);
|
|
2002
|
-
}
|
|
2003
|
-
}
|
|
2004
|
-
async function createAgentTuiDiagnosticRecorder(input) {
|
|
2005
|
-
const directory = path4.join(input.workspace, ".stitchkit", "logs", "tui");
|
|
2006
|
-
await mkdir3(directory, { recursive: true, mode: 448 });
|
|
2007
|
-
const basename = `${input.sessionId}.jsonl`;
|
|
2008
|
-
await pruneOldSessionJournals({
|
|
2009
|
-
directory,
|
|
2010
|
-
workspace: input.workspace,
|
|
2011
|
-
currentSessionId: input.sessionId
|
|
2012
|
-
});
|
|
2013
|
-
const journal = await createDiagnosticJournal({
|
|
2014
|
-
path: path4.join(directory, basename),
|
|
2015
|
-
eventSchema: AgentTuiDiagnosticEventSchema,
|
|
2016
|
-
limits: {
|
|
2017
|
-
maxEventBytes: 4096,
|
|
2018
|
-
maxPendingItems: 256,
|
|
2019
|
-
maxPendingBytes: 256 * 4096,
|
|
2020
|
-
maxFileBytes: 512 * 1024,
|
|
2021
|
-
maxFiles: 2
|
|
2022
|
-
}
|
|
2023
|
-
});
|
|
2024
|
-
return {
|
|
2025
|
-
write(value) {
|
|
2026
|
-
const event = projectAgentTuiRuntimeDiagnostic(value);
|
|
2027
|
-
if (event)
|
|
2028
|
-
journal.submit(event);
|
|
2029
|
-
},
|
|
2030
|
-
record(event) {
|
|
2031
|
-
journal.submit(event);
|
|
2032
|
-
},
|
|
2033
|
-
async close() {
|
|
2034
|
-
await journal.close({ timeoutMs: 2000 });
|
|
2035
|
-
}
|
|
2036
|
-
};
|
|
2037
|
-
}
|
|
2038
|
-
|
|
2039
|
-
// src/run.tsx
|
|
2040
|
-
import { jsx as jsx2 } from "@opentui/react/jsx-runtime";
|
|
2041
|
-
function runtimeContext(config) {
|
|
2042
|
-
return Promise.resolve(config.context());
|
|
2043
|
-
}
|
|
2044
|
-
function defaultAgentTuiRecoveryDecision({
|
|
2045
|
-
run
|
|
2046
|
-
}) {
|
|
2047
|
-
return run.state === "queued" ? { action: "resume" } : { action: "skip" };
|
|
2048
|
-
}
|
|
2049
|
-
function resolveAgentTuiInitialConversationId(initialConversationId) {
|
|
2050
|
-
return initialConversationId ?? createAgentTuiConversationId();
|
|
2051
|
-
}
|
|
2052
|
-
async function runAgentTui(config) {
|
|
2053
|
-
const workspace = path5.resolve(config.workspace ?? process.cwd());
|
|
2054
|
-
const sessionId = createAgentTuiSessionId();
|
|
2055
|
-
const initialConversationId = resolveAgentTuiInitialConversationId(config.initialConversationId);
|
|
2056
|
-
const diagnostics = await createAgentTuiDiagnosticRecorder({ workspace, sessionId });
|
|
2057
|
-
const catalog = await config.modelCatalog.load();
|
|
2058
|
-
const selections = createFileAgentModelSelectionStore(workspace);
|
|
2059
|
-
const bundle = await config.createRuntime({ catalog, selections, diagnostics });
|
|
2060
|
-
await bundle.harness.recover({
|
|
2061
|
-
resolveContext: () => runtimeContext(config),
|
|
2062
|
-
decide: config.recover ?? defaultAgentTuiRecoveryDecision
|
|
2063
|
-
});
|
|
2064
|
-
const controller = await createAgentTuiController({
|
|
2065
|
-
harness: bundle.harness,
|
|
2066
|
-
catalog,
|
|
2067
|
-
selections,
|
|
2068
|
-
conversationId: initialConversationId,
|
|
2069
|
-
context: () => runtimeContext(config),
|
|
2070
|
-
...config.preferredModelId && { preferredModelId: config.preferredModelId },
|
|
2071
|
-
onDiagnostic: ({ conversationId, runId, event }) => diagnostics.write({ conversationId, ...runId && { runId }, event })
|
|
2072
|
-
});
|
|
2073
|
-
const handle = async (request) => {
|
|
2074
|
-
try {
|
|
2075
|
-
if (request.operation === "submit") {
|
|
2076
|
-
const runId = await controller.submit(request.text, request.idempotencyKey);
|
|
2077
|
-
diagnostics.record({
|
|
2078
|
-
schemaVersion: 1,
|
|
2079
|
-
occurredAt: new Date().toISOString(),
|
|
2080
|
-
type: "submission-admitted",
|
|
2081
|
-
sessionId,
|
|
2082
|
-
conversationId: controller.state().conversationId,
|
|
2083
|
-
runId,
|
|
2084
|
-
source: "client"
|
|
2085
|
-
});
|
|
2086
|
-
return {
|
|
2087
|
-
requestId: request.requestId,
|
|
2088
|
-
outcome: "ok",
|
|
2089
|
-
sessionId,
|
|
2090
|
-
conversationId: controller.state().conversationId,
|
|
2091
|
-
runId
|
|
2092
|
-
};
|
|
2093
|
-
}
|
|
2094
|
-
if (request.operation === "interrupt")
|
|
2095
|
-
await controller.interrupt(request.runId);
|
|
2096
|
-
const activeRunId = controller.state().snapshot.runs.find(({ state }) => state === "running" || state === "interrupt_requested")?.id;
|
|
2097
|
-
return {
|
|
2098
|
-
requestId: request.requestId,
|
|
2099
|
-
outcome: "ok",
|
|
2100
|
-
sessionId,
|
|
2101
|
-
conversationId: controller.state().conversationId,
|
|
2102
|
-
...activeRunId && { runId: activeRunId }
|
|
2103
|
-
};
|
|
2104
|
-
} catch {
|
|
2105
|
-
diagnostics.record({
|
|
2106
|
-
schemaVersion: 1,
|
|
2107
|
-
occurredAt: new Date().toISOString(),
|
|
2108
|
-
type: "request-failed",
|
|
2109
|
-
sessionId,
|
|
2110
|
-
operation: request.operation
|
|
2111
|
-
});
|
|
2112
|
-
return {
|
|
2113
|
-
requestId: request.requestId,
|
|
2114
|
-
outcome: "error",
|
|
2115
|
-
error: {
|
|
2116
|
-
code: "REQUEST_FAILED",
|
|
2117
|
-
message: "The terminal host could not complete the request"
|
|
2118
|
-
}
|
|
2119
|
-
};
|
|
2120
|
-
}
|
|
2121
|
-
};
|
|
2122
|
-
const host = await startAgentTuiSessionHost({
|
|
2123
|
-
rootDirectory: workspace,
|
|
2124
|
-
conversationId: initialConversationId,
|
|
2125
|
-
sessionId,
|
|
2126
|
-
handle
|
|
2127
|
-
});
|
|
2128
|
-
let hostConversationId = initialConversationId;
|
|
2129
|
-
diagnostics.record({
|
|
2130
|
-
schemaVersion: 1,
|
|
2131
|
-
occurredAt: new Date().toISOString(),
|
|
2132
|
-
type: "host-started",
|
|
2133
|
-
sessionId,
|
|
2134
|
-
conversationId: initialConversationId,
|
|
2135
|
-
launchMode: config.initialConversationId === undefined ? "fresh" : "explicit"
|
|
2136
|
-
});
|
|
2137
|
-
const renderer = await createCliRenderer({ exitOnCtrlC: false });
|
|
2138
|
-
const root = createRoot(renderer);
|
|
2139
|
-
let closing;
|
|
2140
|
-
const onSignal = () => void close();
|
|
2141
|
-
const close = () => {
|
|
2142
|
-
if (closing)
|
|
2143
|
-
return closing;
|
|
2144
|
-
process.off("SIGINT", onSignal);
|
|
2145
|
-
process.off("SIGTERM", onSignal);
|
|
2146
|
-
renderer.destroy();
|
|
2147
|
-
closing = (async () => {
|
|
2148
|
-
try {
|
|
2149
|
-
diagnostics.record({
|
|
2150
|
-
schemaVersion: 1,
|
|
2151
|
-
occurredAt: new Date().toISOString(),
|
|
2152
|
-
type: "host-closed",
|
|
2153
|
-
sessionId,
|
|
2154
|
-
conversationId: controller.state().conversationId
|
|
2155
|
-
});
|
|
2156
|
-
await host.close();
|
|
2157
|
-
await controller.close();
|
|
2158
|
-
} finally {
|
|
2159
|
-
await diagnostics.close();
|
|
2160
|
-
renderer.destroy();
|
|
2161
|
-
}
|
|
2162
|
-
})();
|
|
2163
|
-
return closing;
|
|
2164
|
-
};
|
|
2165
|
-
root.render(/* @__PURE__ */ jsx2(AgentTuiApp, {
|
|
2166
|
-
controller,
|
|
2167
|
-
catalog,
|
|
2168
|
-
...bundle.conversations && { conversations: bundle.conversations },
|
|
2169
|
-
...config.commands && { commands: config.commands },
|
|
2170
|
-
theme: resolveAgentTuiTheme(config.theme),
|
|
2171
|
-
workspace,
|
|
2172
|
-
...config.statusLine !== undefined && { statusLine: config.statusLine },
|
|
2173
|
-
sessionId: host.sessionId,
|
|
2174
|
-
title: config.title ?? "Stitchkit agent",
|
|
2175
|
-
onConversationChange: async (conversationId, reason) => {
|
|
2176
|
-
const previousConversationId = hostConversationId;
|
|
2177
|
-
await host.setConversationId(conversationId);
|
|
2178
|
-
hostConversationId = conversationId;
|
|
2179
|
-
diagnostics.record({
|
|
2180
|
-
schemaVersion: 1,
|
|
2181
|
-
occurredAt: new Date().toISOString(),
|
|
2182
|
-
type: "conversation-changed",
|
|
2183
|
-
sessionId,
|
|
2184
|
-
previousConversationId,
|
|
2185
|
-
conversationId,
|
|
2186
|
-
reason
|
|
2187
|
-
});
|
|
2188
|
-
},
|
|
2189
|
-
onExit: close
|
|
2190
|
-
}));
|
|
2191
|
-
process.once("SIGINT", onSignal);
|
|
2192
|
-
process.once("SIGTERM", onSignal);
|
|
2193
|
-
return { sessionId: host.sessionId, close };
|
|
2194
|
-
}
|
|
2195
|
-
|
|
2196
|
-
// src/cli.ts
|
|
10
|
+
import { pathToFileURL } from "url";
|
|
2197
11
|
function argument(name) {
|
|
2198
12
|
const index = Bun.argv.indexOf(name);
|
|
2199
13
|
return index < 0 ? undefined : Bun.argv[index + 1];
|
|
2200
14
|
}
|
|
2201
15
|
async function request(sessionId, payload) {
|
|
2202
|
-
const client = await
|
|
2203
|
-
rootDirectory:
|
|
16
|
+
const client = await createAgentTuiClient2({
|
|
17
|
+
rootDirectory: path.resolve(argument("--workspace") ?? process.cwd()),
|
|
2204
18
|
sessionId
|
|
2205
19
|
});
|
|
2206
20
|
const response = await client.request(payload);
|
|
@@ -2210,15 +24,16 @@ async function request(sessionId, payload) {
|
|
|
2210
24
|
process.exitCode = 1;
|
|
2211
25
|
}
|
|
2212
26
|
async function loadConfig(filename) {
|
|
2213
|
-
const module = await import(pathToFileURL(
|
|
27
|
+
const module = await import(pathToFileURL(path.resolve(filename)).href);
|
|
2214
28
|
return Reflect.get(module, "default");
|
|
2215
29
|
}
|
|
2216
30
|
function isAgentTuiConfig(value) {
|
|
2217
31
|
return typeof value === "object" && value !== null && typeof Reflect.get(value, "createRuntime") === "function" && typeof Reflect.get(value, "context") === "function" && typeof Reflect.get(value, "modelCatalog") === "object";
|
|
2218
32
|
}
|
|
33
|
+
process.env.NODE_ENV ??= "production";
|
|
2219
34
|
var command = Bun.argv[2] ?? "run";
|
|
2220
35
|
if (command === "sessions") {
|
|
2221
|
-
for (const session of await
|
|
36
|
+
for (const session of await listAgentTuiSessions2(path.resolve(argument("--workspace") ?? process.cwd()))) {
|
|
2222
37
|
process.stdout.write(`${session.sessionId} ${session.conversationId} pid=${session.pid}
|
|
2223
38
|
`);
|
|
2224
39
|
}
|
|
@@ -2254,6 +69,7 @@ if (command === "sessions") {
|
|
|
2254
69
|
if (!isAgentTuiConfig(config)) {
|
|
2255
70
|
throw new Error("The config default export must be created with defineAgentTui()");
|
|
2256
71
|
}
|
|
72
|
+
const { runAgentTui } = await import("./run-e1kdpzna.js");
|
|
2257
73
|
await runAgentTui(config);
|
|
2258
74
|
} else {
|
|
2259
75
|
throw new Error(`Unknown command: ${command}`);
|