stitchkit-tui 0.1.1

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