@bendyline/gezel-cli 0.1.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.
@@ -0,0 +1,3103 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/tui/index.tsx
4
+ import { render } from "ink";
5
+
6
+ // src/tui/App.tsx
7
+ import { Box as Box6, Text as Text6, useApp, useInput as useInput4, useStdout } from "ink";
8
+ import { useCallback, useEffect as useEffect3, useMemo, useRef as useRef2, useState as useState4 } from "react";
9
+
10
+ // src/tui/active-access.ts
11
+ import {
12
+ normalizeCodexPermissionMode,
13
+ projectWorkspaceWritable,
14
+ resolveSandboxCopilot
15
+ } from "@bendyline/gezel";
16
+ function activeAccessMode(opts) {
17
+ const { provider, project, gezel, config } = opts;
18
+ if (provider === "codex-cli") {
19
+ const mode = normalizeCodexPermissionMode(
20
+ project?.codexPermissionMode ?? gezel?.codexPermissionMode ?? gezel?.claudePermissionMode ?? config?.codexCli?.defaultPermissionMode
21
+ );
22
+ switch (mode) {
23
+ case "plan":
24
+ return "read-only";
25
+ case "edit":
26
+ return "editable";
27
+ case "reviewed":
28
+ return "reviewed edits";
29
+ case "full":
30
+ return "full access";
31
+ }
32
+ }
33
+ if (provider === "anthropic-cli") {
34
+ const mode = gezel?.claudePermissionMode ?? config?.anthropicCli?.defaultPermissionMode ?? "acceptEdits";
35
+ if (mode === "plan") return "read-only";
36
+ if (mode === "bypassPermissions") return "full access";
37
+ return "editable";
38
+ }
39
+ if (provider === "copilot" && !resolveSandboxCopilot(config?.sandboxCopilot, gezel?.sandboxCopilot)) {
40
+ return "editable";
41
+ }
42
+ return projectWorkspaceWritable(project) ? "editable" : "read-only";
43
+ }
44
+
45
+ // src/tui/commands.ts
46
+ var SLASH_COMMAND_WORDWHEEL_SIZE = 4;
47
+ var SLASH_COMMANDS = [
48
+ { name: "help", description: "show the command reference" },
49
+ { name: "project", description: "switch active project" },
50
+ { name: "gezel", description: "switch active gezel" },
51
+ { name: "model", description: "switch engine and model" },
52
+ { name: "thread", description: "switch the active chat thread" },
53
+ { name: "task", description: "list and manage project tasks" },
54
+ { name: "start", description: "start a task from a craftbook" },
55
+ { name: "continue", description: "process due and active project tasks" },
56
+ { name: "nightshift", description: "start, stop, or list night-shift work" },
57
+ { name: "focus", description: "send into another active chat" },
58
+ { name: "cli", description: "make bare input run shell commands" },
59
+ { name: "chat", description: "make bare input message your gezel" },
60
+ { name: "clear", description: "clear the visible feed" },
61
+ { name: "quit", description: "exit the TUI" }
62
+ ];
63
+ function suggestSlashCommands(input) {
64
+ if (!input.startsWith("/") || /\s/.test(input)) return [];
65
+ const query = input.slice(1).toLowerCase();
66
+ return SLASH_COMMANDS.filter((command) => command.name.startsWith(query));
67
+ }
68
+ var NIGHT_SHIFT_SUBCOMMANDS = [
69
+ { name: "start", description: "start a manual night shift now" },
70
+ { name: "stop", description: "stop the current night shift" },
71
+ { name: "list", description: "show current and upcoming night-shift work" }
72
+ ];
73
+ function suggestSlashWordwheel(input, craftbooks) {
74
+ const nightShiftMatch = input.match(/^\/nightshift\s+(.*)$/i);
75
+ if (nightShiftMatch) {
76
+ const query = (nightShiftMatch[1] ?? "").trim().toLowerCase();
77
+ return NIGHT_SHIFT_SUBCOMMANDS.filter((command) => command.name.startsWith(query)).map(
78
+ (command) => ({
79
+ key: `nightshift:${command.name}`,
80
+ label: `/nightshift ${command.name}`,
81
+ description: command.description,
82
+ submit: `/nightshift ${command.name}`,
83
+ completion: `/nightshift ${command.name}`
84
+ })
85
+ );
86
+ }
87
+ const startMatch = input.match(/^\/start\s+(.*)$/i);
88
+ if (startMatch) {
89
+ const query = (startMatch[1] ?? "").trim().toLowerCase();
90
+ const terms = query.split(/\s+/).filter(Boolean);
91
+ return craftbooks.filter((book) => {
92
+ const haystack = `${book.id} ${book.name} ${book.description ?? ""}`.toLowerCase();
93
+ return terms.every((term) => haystack.includes(term));
94
+ }).sort((left, right) => {
95
+ const leftRank = craftbookMatchRank(left, query);
96
+ const rightRank = craftbookMatchRank(right, query);
97
+ return leftRank - rightRank || left.name.localeCompare(right.name);
98
+ }).map((book) => ({
99
+ key: `craftbook:${book.id}`,
100
+ label: `/start ${book.id}`,
101
+ description: `${book.name} \xB7 ${book.stepCount} ${book.stepCount === 1 ? "step" : "steps"} \xB7 ${book.source}`,
102
+ submit: `/start ${book.id}`,
103
+ completion: `/start ${book.id}`
104
+ }));
105
+ }
106
+ return suggestSlashCommands(input).map((command) => ({
107
+ key: `command:${command.name}`,
108
+ label: `/${command.name}`,
109
+ description: command.description,
110
+ submit: `/${command.name}`,
111
+ completion: `/${command.name} `
112
+ }));
113
+ }
114
+ function craftbookMatchRank(book, query) {
115
+ if (!query) return 2;
116
+ const id = book.id.toLowerCase();
117
+ const name = book.name.toLowerCase();
118
+ if (id === query || name === query) return 0;
119
+ if (id.startsWith(query) || name.startsWith(query)) return 1;
120
+ return 2;
121
+ }
122
+ function parseInput(raw, cliMode) {
123
+ const text = raw.trim();
124
+ if (!text) return { kind: "empty" };
125
+ if (text.startsWith("/")) {
126
+ const [name, ...rest] = text.slice(1).split(/\s+/);
127
+ return { kind: "command", name: (name ?? "").toLowerCase(), rest: rest.join(" ") };
128
+ }
129
+ if (text.startsWith("!")) return { kind: "shell", text: text.slice(1).trim() };
130
+ if (text === "@tools") return { kind: "tools" };
131
+ if (text.startsWith("@tool ")) {
132
+ const after = text.slice("@tool ".length).trim();
133
+ const sp = after.indexOf(" ");
134
+ const name = sp === -1 ? after : after.slice(0, sp);
135
+ const argsJson = sp === -1 ? "" : after.slice(sp + 1).trim();
136
+ return { kind: "tool", name, argsJson };
137
+ }
138
+ return cliMode ? { kind: "shell", text } : { kind: "prompt", text };
139
+ }
140
+
141
+ // src/tui/components/ChatFeed.tsx
142
+ import { GEZEL_VERSION } from "@bendyline/gezel";
143
+ import { Box, Text } from "ink";
144
+
145
+ // src/tui/feed.ts
146
+ var MAX_ROWS = 200;
147
+ var counter = 0;
148
+ function nextKey() {
149
+ counter += 1;
150
+ return `r${counter}`;
151
+ }
152
+ function reduceFeed(rows, env) {
153
+ const { sessionId, gezelId, event } = env;
154
+ const cap = (next) => next.length > MAX_ROWS ? next.slice(next.length - MAX_ROWS) : next;
155
+ switch (event.type) {
156
+ case "user_message":
157
+ return cap([
158
+ ...rows,
159
+ {
160
+ key: nextKey(),
161
+ sessionId,
162
+ gezelId,
163
+ kind: "user",
164
+ text: event.message.content,
165
+ open: false
166
+ }
167
+ ]);
168
+ case "delta": {
169
+ const idx = findOpenAssistant(rows, sessionId);
170
+ const open = idx === -1 ? void 0 : rows[idx];
171
+ if (!open) {
172
+ return cap([
173
+ ...rows,
174
+ {
175
+ key: nextKey(),
176
+ sessionId,
177
+ gezelId,
178
+ kind: "assistant",
179
+ text: event.content,
180
+ open: true
181
+ }
182
+ ]);
183
+ }
184
+ const next = rows.slice();
185
+ next[idx] = { ...open, text: open.text + event.content };
186
+ return next;
187
+ }
188
+ case "complete": {
189
+ const idx = findOpenAssistant(rows, sessionId);
190
+ const open = idx === -1 ? void 0 : rows[idx];
191
+ const text = event.message.content;
192
+ if (!open) {
193
+ return cap([
194
+ ...rows,
195
+ { key: nextKey(), sessionId, gezelId, kind: "assistant", text, open: false }
196
+ ]);
197
+ }
198
+ const next = rows.slice();
199
+ next[idx] = { ...open, text: text || open.text, open: false };
200
+ return next;
201
+ }
202
+ case "tool":
203
+ return cap([
204
+ ...rows,
205
+ {
206
+ key: nextKey(),
207
+ sessionId,
208
+ gezelId,
209
+ kind: "tool",
210
+ text: toolLabel(event),
211
+ open: false
212
+ }
213
+ ]);
214
+ case "awaiting_gezel":
215
+ return cap([
216
+ ...rows,
217
+ {
218
+ key: nextKey(),
219
+ sessionId,
220
+ gezelId,
221
+ kind: "note",
222
+ text: "\u23F3 awaiting another gezel\u2026",
223
+ open: false
224
+ }
225
+ ]);
226
+ case "task_event":
227
+ return cap([
228
+ ...rows,
229
+ {
230
+ key: nextKey(),
231
+ sessionId: "local",
232
+ gezelId: "",
233
+ kind: "note",
234
+ text: `task \xB7 ${event.summary}`,
235
+ open: false
236
+ }
237
+ ]);
238
+ case "error":
239
+ return cap([
240
+ ...rows,
241
+ { key: nextKey(), sessionId, gezelId, kind: "error", text: event.error, open: false }
242
+ ]);
243
+ case "done":
244
+ return rows.map((r) => r.sessionId === sessionId && r.open ? { ...r, open: false } : r);
245
+ default:
246
+ return rows;
247
+ }
248
+ }
249
+ function sessionToFeedRows(session) {
250
+ const rows = [];
251
+ for (const message of session.messages) {
252
+ if (message.hidden) continue;
253
+ if (message.role === "assistant") {
254
+ for (const tool of message.toolCalls ?? []) {
255
+ rows.push({
256
+ key: nextKey(),
257
+ sessionId: session.id,
258
+ gezelId: session.gezelId,
259
+ kind: "tool",
260
+ text: toolRowText(tool),
261
+ open: false
262
+ });
263
+ }
264
+ }
265
+ if (!message.content.trim()) continue;
266
+ rows.push({
267
+ key: nextKey(),
268
+ sessionId: session.id,
269
+ gezelId: message.from?.gezelId ?? session.gezelId,
270
+ kind: message.role === "user" && !message.from ? "user" : message.from ? "assistant" : message.role,
271
+ text: message.content,
272
+ open: false
273
+ });
274
+ }
275
+ if (session.lastTurnError) {
276
+ rows.push({
277
+ key: nextKey(),
278
+ sessionId: session.id,
279
+ gezelId: session.gezelId,
280
+ kind: "error",
281
+ text: session.lastTurnError,
282
+ open: false
283
+ });
284
+ }
285
+ return rows.length > MAX_ROWS ? rows.slice(rows.length - MAX_ROWS) : rows;
286
+ }
287
+ function reduceTurns(turns, env) {
288
+ const { sessionId, event } = env;
289
+ const set = (label) => new Map(turns).set(sessionId, label);
290
+ const clear = () => {
291
+ if (!turns.has(sessionId)) return turns;
292
+ const m = new Map(turns);
293
+ m.delete(sessionId);
294
+ return m;
295
+ };
296
+ switch (event.type) {
297
+ case "user_message":
298
+ return set("thinking\u2026");
299
+ case "queued":
300
+ return set(event.aheadOf > 0 ? `queued \xB7 ${event.aheadOf} ahead` : "queued");
301
+ case "intent":
302
+ return set(event.label);
303
+ case "engine_phase":
304
+ return set(phaseLabel(event));
305
+ case "delta":
306
+ return set("generating");
307
+ case "tool":
308
+ return set("running tool");
309
+ case "awaiting_gezel":
310
+ return set("awaiting gezel");
311
+ case "error":
312
+ case "done":
313
+ return clear();
314
+ default:
315
+ return turns;
316
+ }
317
+ }
318
+ function phaseLabel(event) {
319
+ const pct = event.progress !== void 0 ? ` ${Math.round(event.progress * 100)}%` : "";
320
+ switch (event.phase) {
321
+ case "starting":
322
+ return "starting engine";
323
+ case "loading_model":
324
+ return `loading model${pct}`;
325
+ case "prefill":
326
+ return `reading prompt${pct}`;
327
+ case "generating":
328
+ return "generating";
329
+ default:
330
+ return "ready";
331
+ }
332
+ }
333
+ function appendNote(rows, text, kind = "note") {
334
+ const next = [
335
+ ...rows,
336
+ { key: nextKey(), sessionId: "local", gezelId: "", kind, text, open: false }
337
+ ];
338
+ return next.length > MAX_ROWS ? next.slice(next.length - MAX_ROWS) : next;
339
+ }
340
+ function finalizeShellRun(rows, runId, message) {
341
+ const key = `term-${runId}`;
342
+ const footer = shellFooter(message);
343
+ const idx = rows.findIndex((r) => r.key === key);
344
+ if (idx === -1) {
345
+ const text = (message.content ?? "").replace(/\s+$/, "");
346
+ const next2 = [
347
+ ...rows,
348
+ {
349
+ key,
350
+ sessionId: `term-${runId}`,
351
+ gezelId: "",
352
+ kind: "shell",
353
+ text: text ? `${text}${footer}` : footer.trimStart(),
354
+ open: false
355
+ }
356
+ ];
357
+ return next2.length > MAX_ROWS ? next2.slice(next2.length - MAX_ROWS) : next2;
358
+ }
359
+ const row = rows[idx];
360
+ if (!row) return rows;
361
+ const next = rows.slice();
362
+ next[idx] = { ...row, open: false, text: `${row.text.replace(/\s+$/, "")}${footer}` };
363
+ return next;
364
+ }
365
+ function shellFooter(message) {
366
+ if (message.errorMessage) return `
367
+ [error: ${message.errorMessage}]`;
368
+ const dur = message.durationMs != null ? ` \xB7 ${(message.durationMs / 1e3).toFixed(1)}s` : "";
369
+ if (message.exitCode == null) return `
370
+ [done${dur}]`;
371
+ return `
372
+ [exit ${message.exitCode}${dur}]`;
373
+ }
374
+ function appendShellChunk(rows, runId, chunk) {
375
+ const key = `term-${runId}`;
376
+ const idx = rows.findIndex((r) => r.key === key);
377
+ if (idx === -1) {
378
+ const next2 = [
379
+ ...rows,
380
+ {
381
+ key,
382
+ sessionId: `term-${runId}`,
383
+ gezelId: "",
384
+ kind: "shell",
385
+ text: chunk,
386
+ open: true
387
+ }
388
+ ];
389
+ return next2.length > MAX_ROWS ? next2.slice(next2.length - MAX_ROWS) : next2;
390
+ }
391
+ const row = rows[idx];
392
+ if (!row) return rows;
393
+ const next = rows.slice();
394
+ next[idx] = { ...row, text: row.text + chunk };
395
+ return next;
396
+ }
397
+ function findOpenAssistant(rows, sessionId) {
398
+ for (let i = rows.length - 1; i >= 0; i--) {
399
+ const r = rows[i];
400
+ if (r && r.sessionId === sessionId && r.kind === "assistant" && r.open) return i;
401
+ }
402
+ return -1;
403
+ }
404
+ function toolLabel(event) {
405
+ return toolRowText(event);
406
+ }
407
+ var MAX_TOOL_DETAIL_CHARS = 160;
408
+ function toolRowText(call) {
409
+ const name = typeof call.name === "string" && call.name.length > 0 ? call.name : "tool";
410
+ const detail = call.argsSummary ?? call.path;
411
+ const flat = detail?.replace(/\s+/g, " ").trim();
412
+ const clipped = flat && flat.length > MAX_TOOL_DETAIL_CHARS ? `${flat.slice(0, MAX_TOOL_DETAIL_CHARS - 1)}\u2026` : flat;
413
+ const failed = call.success === false ? ` \xB7 failed${call.errorMessage ? `: ${call.errorMessage}` : ""}` : "";
414
+ return `\u{1F527} ${name}${clipped ? ` \xB7 ${clipped}` : ""}${failed}`;
415
+ }
416
+ function gezelLabel(gezelId, gezels, boring) {
417
+ const g = gezels.find((x) => x.id === gezelId);
418
+ if (!g) return gezelId;
419
+ if (boring) return g.roleBasedName ?? g.role ?? g.id;
420
+ return g.role ? `${g.name} \xB7 ${g.role}` : g.name;
421
+ }
422
+
423
+ // src/tui/tool-markup.ts
424
+ var BULKY_KEYS = /* @__PURE__ */ new Set([
425
+ "content",
426
+ "body",
427
+ "source",
428
+ "markdown",
429
+ "text",
430
+ "about",
431
+ "missionObjectives"
432
+ ]);
433
+ var MAX_VALUE_CHARS = 60;
434
+ var MAX_PARAMS = 3;
435
+ function renderCall(name, params) {
436
+ const pieces = [];
437
+ for (const [key, value] of params) {
438
+ if (pieces.length >= MAX_PARAMS) break;
439
+ if (BULKY_KEYS.has(key)) continue;
440
+ const flat = value.replace(/\s+/g, " ").trim();
441
+ if (!flat) continue;
442
+ pieces.push(
443
+ `${key}: ${flat.length > MAX_VALUE_CHARS ? `${flat.slice(0, MAX_VALUE_CHARS - 1)}\u2026` : flat}`
444
+ );
445
+ }
446
+ return pieces.length > 0 ? `\u{1F527} ${name} (${pieces.join(", ")})` : `\u{1F527} ${name}`;
447
+ }
448
+ var NAME = "[A-Za-z_][A-Za-z0-9_.-]*";
449
+ var ENVELOPE_RE = /<tool_call>\s*([\s\S]*?)<\/tool_call\s*>/g;
450
+ var HERMES_RE = new RegExp(`<function=(${NAME})>\\s*([\\s\\S]*?)<\\/function\\s*>`, "g");
451
+ var HERMES_PARAM_RE = new RegExp(
452
+ `<parameter=(${NAME})>\\s*([\\s\\S]*?)\\s*<\\/parameter\\s*>`,
453
+ "g"
454
+ );
455
+ var GLM_PAIR_RE = /<arg_key>\s*([\s\S]*?)\s*<\/arg_key>\s*<arg_value>\s*([\s\S]*?)\s*<\/arg_value>/g;
456
+ var GEMMA_ENVELOPE_RE = new RegExp(
457
+ `<\\|tool_call>\\s*call:(${NAME})[\\s\\S]*?<tool_call\\|>`,
458
+ "gi"
459
+ );
460
+ var SHELL_LINE_RE = new RegExp(
461
+ `<tool_call>[ \\t]*(${NAME})((?:[ \\t]+${NAME}[ \\t]*=[ \\t]*(?:"[^"]*"|'[^']*'))*)[ \\t]*(?=$|\\n)`,
462
+ "g"
463
+ );
464
+ function parseHermesParams(body) {
465
+ const params = [];
466
+ for (const m of body.matchAll(HERMES_PARAM_RE)) {
467
+ params.push([m[1] ?? "", m[2] ?? ""]);
468
+ }
469
+ return params;
470
+ }
471
+ function renderJsonValue(v) {
472
+ if (typeof v === "string") return v;
473
+ if (v === null || v === void 0) return String(v);
474
+ try {
475
+ return JSON.stringify(v);
476
+ } catch {
477
+ return String(v);
478
+ }
479
+ }
480
+ function parseEnvelopeBody(body) {
481
+ const inner = body.trim();
482
+ const hermes = new RegExp(`^<function=(${NAME})>\\s*([\\s\\S]*)$`).exec(inner);
483
+ if (hermes) return renderCall(hermes[1] ?? "", parseHermesParams(hermes[2] ?? ""));
484
+ if (inner.startsWith("{")) {
485
+ try {
486
+ const parsed = JSON.parse(inner);
487
+ const name = parsed.name ?? parsed.tool;
488
+ if (typeof name !== "string" || name.length === 0) return null;
489
+ const args = parsed.arguments ?? parsed.args ?? parsed.parameters;
490
+ const params = args && typeof args === "object" && !Array.isArray(args) ? Object.entries(args).map(([k, v]) => [k, renderJsonValue(v)]) : [];
491
+ return renderCall(name, params);
492
+ } catch {
493
+ return null;
494
+ }
495
+ }
496
+ const glm = new RegExp(`^(${NAME})\\s*([\\s\\S]*)$`).exec(inner);
497
+ if (glm) {
498
+ const rest = glm[2] ?? "";
499
+ const params = [];
500
+ for (const m of rest.matchAll(GLM_PAIR_RE)) params.push([m[1] ?? "", m[2] ?? ""]);
501
+ const leftover = rest.replace(GLM_PAIR_RE, "").trim();
502
+ if (leftover.length === 0) return renderCall(glm[1] ?? "", params);
503
+ }
504
+ return null;
505
+ }
506
+ function parseShellArgs(argText) {
507
+ const params = [];
508
+ const re = new RegExp(`(${NAME})[ \\t]*=[ \\t]*("([^"]*)"|'([^']*)')`, "g");
509
+ for (const m of argText.matchAll(re)) {
510
+ params.push([m[1] ?? "", m[3] ?? m[4] ?? ""]);
511
+ }
512
+ return params;
513
+ }
514
+ function humanizePartialTail(text) {
515
+ const idx = Math.max(text.lastIndexOf("<tool_call>"), text.lastIndexOf("<|tool_call>"));
516
+ if (idx === -1) return text;
517
+ const tail = text.slice(idx);
518
+ if (/<\/tool_call\s*>|<tool_call\|>/.test(tail)) return text;
519
+ const name = new RegExp(`^<tool_call>\\s*<function=(${NAME})`).exec(tail)?.[1] ?? new RegExp(`^<tool_call>\\s*\\{\\s*"(?:name|tool)"\\s*:\\s*"(${NAME})"`).exec(tail)?.[1] ?? new RegExp(`^<\\|tool_call>\\s*call:(${NAME})`).exec(tail)?.[1] ?? new RegExp(`^<tool_call>\\s*(${NAME})\\s*$|^<tool_call>\\s*(${NAME})\\s*<arg_key>`).exec(tail)?.slice(1).find(Boolean);
520
+ return `${text.slice(0, idx)}${name ? `\u{1F527} ${name}\u2026` : "\u{1F527} calling a tool\u2026"}`;
521
+ }
522
+ function hasMarkers(text) {
523
+ return text.includes("<tool_call>") || text.includes("<function=") || text.includes("<|tool_call>");
524
+ }
525
+ function humanizeToolMarkup(text) {
526
+ if (!hasMarkers(text)) return text;
527
+ let out = text.replace(ENVELOPE_RE, (raw, body) => parseEnvelopeBody(body) ?? raw);
528
+ out = out.replace(
529
+ HERMES_RE,
530
+ (_raw, name, body) => renderCall(name, parseHermesParams(body))
531
+ );
532
+ out = out.replace(GEMMA_ENVELOPE_RE, (_raw, name) => `\u{1F527} ${name}`);
533
+ out = out.replace(
534
+ SHELL_LINE_RE,
535
+ (_raw, name, argText) => renderCall(name, parseShellArgs(argText))
536
+ );
537
+ return humanizePartialTail(out);
538
+ }
539
+
540
+ // src/tui/components/ChatFeed.tsx
541
+ import { jsx, jsxs } from "react/jsx-runtime";
542
+ var TABLE_LOGO = [
543
+ " o ____________________",
544
+ "o-[O]|____________________|",
545
+ " | /|____________|\\",
546
+ " o /_| |_\\"
547
+ ].join("\n");
548
+ var KIND_COLOR = {
549
+ user: "white",
550
+ assistant: "cyan",
551
+ tool: "yellow",
552
+ note: "magenta",
553
+ error: "red",
554
+ shell: void 0
555
+ };
556
+ function ChatFeed(props) {
557
+ const { rows, gezels, boring, focusedSessionId, visible = 16 } = props;
558
+ const shown = rows.slice(Math.max(0, rows.length - visible));
559
+ return /* @__PURE__ */ jsx(Box, { flexDirection: "column", flexGrow: 1, children: shown.length === 0 ? /* @__PURE__ */ jsxs(Box, { flexDirection: "row", marginBottom: 1, children: [
560
+ /* @__PURE__ */ jsx(Text, { color: "yellow", children: TABLE_LOGO }),
561
+ /* @__PURE__ */ jsxs(Box, { flexDirection: "column", marginLeft: 3, children: [
562
+ /* @__PURE__ */ jsxs(Text, { children: [
563
+ "gezel ",
564
+ GEZEL_VERSION
565
+ ] }),
566
+ /* @__PURE__ */ jsx(Text, { dimColor: true, children: "Type a message to begin" }),
567
+ /* @__PURE__ */ jsx(Text, { dimColor: true, children: "/help for commands" })
568
+ ] })
569
+ ] }) : shown.map((row) => {
570
+ if (row.kind === "shell" && row.sessionId.startsWith("term-")) {
571
+ return /* @__PURE__ */ jsx(Text, { wrap: "wrap", children: clip(row.text) }, row.key);
572
+ }
573
+ const who = row.kind === "user" ? "you" : row.gezelId ? gezelLabel(row.gezelId, gezels, boring) : row.kind === "tool" ? "tool" : row.kind === "shell" ? "shell" : row.kind === "error" ? "error" : "system";
574
+ const isFocused = focusedSessionId && row.sessionId === focusedSessionId;
575
+ return /* @__PURE__ */ jsxs(Box, { flexDirection: "row", children: [
576
+ /* @__PURE__ */ jsx(Text, { dimColor: !isFocused, color: isFocused ? "green" : void 0, children: isFocused ? "\u258E" : " " }),
577
+ /* @__PURE__ */ jsxs(Text, { wrap: "wrap", children: [
578
+ /* @__PURE__ */ jsxs(Text, { bold: true, color: KIND_COLOR[row.kind], children: [
579
+ who,
580
+ ": "
581
+ ] }),
582
+ /* @__PURE__ */ jsx(Text, { color: KIND_COLOR[row.kind], children: clip(row.kind === "assistant" ? humanizeToolMarkup(row.text) : row.text) })
583
+ ] })
584
+ ] }, row.key);
585
+ }) });
586
+ }
587
+ var MAX_CHARS = 8e3;
588
+ function clip(text) {
589
+ const t = text.replace(/\s+$/, "");
590
+ return t.length > MAX_CHARS ? `${t.slice(0, MAX_CHARS)}
591
+ \u2026 (truncated)` : t;
592
+ }
593
+
594
+ // src/tui/components/Picker.tsx
595
+ import { Box as Box2, Text as Text2, useInput } from "ink";
596
+ import { useState } from "react";
597
+ import { Fragment, jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
598
+ function Picker(props) {
599
+ const { title, items, initialValue, windowSize, onSelect, onCancel } = props;
600
+ const [index, setIndex] = useState(() => {
601
+ const initialIndex = initialValue ? items.findIndex((item) => item.value === initialValue) : -1;
602
+ return Math.max(initialIndex, 0);
603
+ });
604
+ const visibleCount = Math.max(1, Math.min(windowSize ?? items.length, items.length || 1));
605
+ const start = Math.min(
606
+ Math.max(0, index - Math.floor(visibleCount / 2)),
607
+ Math.max(0, items.length - visibleCount)
608
+ );
609
+ const visibleItems = items.slice(start, start + visibleCount);
610
+ useInput((_input, key) => {
611
+ if (key.escape) {
612
+ onCancel();
613
+ return;
614
+ }
615
+ if (key.upArrow) {
616
+ setIndex((i) => i <= 0 ? Math.max(items.length - 1, 0) : i - 1);
617
+ return;
618
+ }
619
+ if (key.downArrow) {
620
+ setIndex((i) => i >= items.length - 1 ? 0 : i + 1);
621
+ return;
622
+ }
623
+ if (key.return) {
624
+ const chosen = items[index];
625
+ if (chosen) onSelect(chosen.value);
626
+ }
627
+ });
628
+ return /* @__PURE__ */ jsxs2(Box2, { flexDirection: "column", borderStyle: "round", borderColor: "cyan", paddingX: 1, children: [
629
+ /* @__PURE__ */ jsx2(Text2, { bold: true, color: "cyan", children: title }),
630
+ items.length === 0 ? /* @__PURE__ */ jsx2(Text2, { dimColor: true, children: "(nothing to choose)" }) : /* @__PURE__ */ jsxs2(Fragment, { children: [
631
+ start > 0 ? /* @__PURE__ */ jsxs2(Text2, { dimColor: true, children: [
632
+ " \u2191 ",
633
+ start,
634
+ " more"
635
+ ] }) : null,
636
+ visibleItems.map((item, offset) => {
637
+ const itemIndex = start + offset;
638
+ return /* @__PURE__ */ jsxs2(Text2, { color: itemIndex === index ? "green" : void 0, children: [
639
+ itemIndex === index ? "\u276F " : " ",
640
+ item.label,
641
+ item.hint ? /* @__PURE__ */ jsxs2(Text2, { dimColor: true, children: [
642
+ " \u2014 ",
643
+ item.hint
644
+ ] }) : null
645
+ ] }, item.value);
646
+ }),
647
+ start + visibleItems.length < items.length ? /* @__PURE__ */ jsxs2(Text2, { dimColor: true, children: [
648
+ " \u2193 ",
649
+ items.length - start - visibleItems.length,
650
+ " more"
651
+ ] }) : null
652
+ ] }),
653
+ /* @__PURE__ */ jsx2(Text2, { dimColor: true, children: "\u2191/\u2193 move \xB7 Enter select \xB7 Esc cancel" })
654
+ ] });
655
+ }
656
+
657
+ // src/tui/components/PromptLine.tsx
658
+ import { Box as Box4, Text as Text4, useInput as useInput2 } from "ink";
659
+ import TextInput from "ink-text-input";
660
+ import { useEffect, useState as useState2 } from "react";
661
+
662
+ // src/tui/components/EnginePill.tsx
663
+ import { Box as Box3, Text as Text3 } from "ink";
664
+ import { jsx as jsx3, jsxs as jsxs3 } from "react/jsx-runtime";
665
+ function EnginePill(props) {
666
+ const { provider, model, accessMode, busy, label } = props;
667
+ const text = formatEngineStatus(provider, model, busy, label, accessMode);
668
+ return /* @__PURE__ */ jsx3(Box3, { children: /* @__PURE__ */ jsxs3(Text3, { backgroundColor: busy ? "yellow" : "blackBright", color: busy ? "black" : "white", children: [
669
+ " ",
670
+ text,
671
+ " "
672
+ ] }) });
673
+ }
674
+ function formatEngineStatus(provider, model, busy, label, accessMode) {
675
+ const activity = busy ? `\u25CF ${label ?? "working"}` : "\u25CB idle";
676
+ return [activity, accessMode, formatEngineIdentity(provider, model)].filter(Boolean).join(" \xB7 ");
677
+ }
678
+ function formatEngineIdentity(provider, model) {
679
+ const engine = provider === "llama-cpp" ? "llama" : provider ?? "on-device";
680
+ return model ? `${engine} \xB7 ${model}` : engine;
681
+ }
682
+
683
+ // src/tui/components/PromptLine.tsx
684
+ import { Fragment as Fragment2, jsx as jsx4, jsxs as jsxs4 } from "react/jsx-runtime";
685
+ function PromptLine(props) {
686
+ const {
687
+ projectName,
688
+ gezelLabel: gezelLabel2,
689
+ threadTitle,
690
+ mode,
691
+ provider,
692
+ model,
693
+ accessMode,
694
+ busy,
695
+ statusLabel,
696
+ value,
697
+ active,
698
+ history,
699
+ craftbooks,
700
+ pendingPrompt,
701
+ pendingMode,
702
+ onChange,
703
+ onSubmit
704
+ } = props;
705
+ const [cursor, setCursor] = useState2(history.length);
706
+ const [suggestionIndex, setSuggestionIndex] = useState2(0);
707
+ const suggestions = active && !pendingPrompt ? suggestSlashWordwheel(value, craftbooks) : [];
708
+ const activeSuggestionIndex = Math.min(suggestionIndex, Math.max(0, suggestions.length - 1));
709
+ const suggestionWindowStart = Math.min(
710
+ Math.max(0, activeSuggestionIndex - SLASH_COMMAND_WORDWHEEL_SIZE + 1),
711
+ Math.max(0, suggestions.length - SLASH_COMMAND_WORDWHEEL_SIZE)
712
+ );
713
+ const visibleSuggestions = suggestions.slice(
714
+ suggestionWindowStart,
715
+ suggestionWindowStart + SLASH_COMMAND_WORDWHEEL_SIZE
716
+ );
717
+ const changeValue = (nextValue) => {
718
+ setSuggestionIndex(0);
719
+ onChange(nextValue);
720
+ };
721
+ const submitValue = (submittedValue) => {
722
+ const selected = suggestions[activeSuggestionIndex];
723
+ onSubmit(selected ? selected.submit : submittedValue);
724
+ };
725
+ useEffect(() => {
726
+ setCursor(history.length);
727
+ }, [history.length]);
728
+ useInput2(
729
+ (_input, key) => {
730
+ if (suggestions.length > 0) {
731
+ if (key.upArrow) {
732
+ setSuggestionIndex((i) => i <= 0 ? suggestions.length - 1 : i - 1);
733
+ return;
734
+ }
735
+ if (key.downArrow) {
736
+ setSuggestionIndex((i) => i >= suggestions.length - 1 ? 0 : i + 1);
737
+ return;
738
+ }
739
+ if (key.tab) {
740
+ const selected = suggestions[activeSuggestionIndex];
741
+ if (selected) changeValue(selected.completion);
742
+ return;
743
+ }
744
+ }
745
+ if (pendingPrompt) return;
746
+ if (key.upArrow && history.length > 0) {
747
+ const next = Math.max(0, cursor - 1);
748
+ setCursor(next);
749
+ changeValue(history[next] ?? "");
750
+ } else if (key.downArrow && cursor < history.length) {
751
+ const next = cursor + 1;
752
+ setCursor(next);
753
+ changeValue(next === history.length ? "" : history[next] ?? "");
754
+ }
755
+ },
756
+ { isActive: active }
757
+ );
758
+ const prefix = pendingPrompt ? "\u21B3 " : mode === "cli" ? "$ " : "\u203A ";
759
+ const placeholder = pendingPrompt ? pendingPrompt : mode === "cli" ? "shell / @tool \u2026 (/chat to exit)" : "message, or /command, !shell, @tool";
760
+ return /* @__PURE__ */ jsxs4(Box4, { flexDirection: "column", children: [
761
+ /* @__PURE__ */ jsxs4(Box4, { children: [
762
+ /* @__PURE__ */ jsx4(Text4, { color: "blue", children: projectName }),
763
+ /* @__PURE__ */ jsx4(Text4, { dimColor: true, children: " \xB7 " }),
764
+ /* @__PURE__ */ jsx4(Text4, { color: "magenta", children: gezelLabel2 }),
765
+ threadTitle ? /* @__PURE__ */ jsxs4(Fragment2, { children: [
766
+ /* @__PURE__ */ jsx4(Text4, { dimColor: true, children: " \xB7 " }),
767
+ /* @__PURE__ */ jsxs4(Text4, { color: "cyan", children: [
768
+ "\u21B3 ",
769
+ compactThreadTitle(threadTitle)
770
+ ] })
771
+ ] }) : null,
772
+ /* @__PURE__ */ jsx4(Text4, { children: " " }),
773
+ /* @__PURE__ */ jsx4(
774
+ EnginePill,
775
+ {
776
+ provider,
777
+ model,
778
+ accessMode,
779
+ busy,
780
+ label: statusLabel
781
+ }
782
+ )
783
+ ] }),
784
+ visibleSuggestions.length > 0 ? /* @__PURE__ */ jsxs4(Box4, { flexDirection: "column", marginLeft: 2, children: [
785
+ visibleSuggestions.map((suggestion, windowIndex) => {
786
+ const index = suggestionWindowStart + windowIndex;
787
+ const selected = index === activeSuggestionIndex;
788
+ return /* @__PURE__ */ jsxs4(Text4, { color: selected ? "cyan" : void 0, children: [
789
+ selected ? "\u203A " : " ",
790
+ suggestion.label,
791
+ /* @__PURE__ */ jsxs4(Text4, { dimColor: true, children: [
792
+ " \u2014 ",
793
+ suggestion.description
794
+ ] })
795
+ ] }, suggestion.key);
796
+ }),
797
+ /* @__PURE__ */ jsxs4(Text4, { dimColor: true, children: [
798
+ "\u2191/\u2193 choose \xB7 Enter run \xB7 Tab complete",
799
+ suggestions.length > SLASH_COMMAND_WORDWHEEL_SIZE ? ` \xB7 ${activeSuggestionIndex + 1}/${suggestions.length}` : ""
800
+ ] })
801
+ ] }) : null,
802
+ /* @__PURE__ */ jsxs4(Box4, { children: [
803
+ /* @__PURE__ */ jsx4(Text4, { color: pendingPrompt ? "yellow" : mode === "cli" ? "green" : "cyan", children: prefix }),
804
+ /* @__PURE__ */ jsx4(
805
+ TextInput,
806
+ {
807
+ value,
808
+ onChange: changeValue,
809
+ onSubmit: submitValue,
810
+ focus: active,
811
+ mask: pendingMode === "password" ? "*" : void 0,
812
+ placeholder
813
+ }
814
+ )
815
+ ] })
816
+ ] });
817
+ }
818
+ function compactThreadTitle(title) {
819
+ const display = title === "New session" ? "New thread" : title;
820
+ return display.length > 32 ? `${display.slice(0, 31)}\u2026` : display;
821
+ }
822
+
823
+ // src/tui/components/QuestionPrompt.tsx
824
+ import { Box as Box5, Text as Text5, useInput as useInput3 } from "ink";
825
+ import TextInput2 from "ink-text-input";
826
+ import { useState as useState3 } from "react";
827
+ import { Fragment as Fragment3, jsx as jsx5, jsxs as jsxs5 } from "react/jsx-runtime";
828
+ var QUESTION_OPTION_WINDOW_SIZE = 4;
829
+ function questionOptionCount(question) {
830
+ const choices = question.choices?.length ?? 0;
831
+ const writeIn = question.allowWriteIn ?? true;
832
+ const submit = question.multiSelect === true && choices > 0;
833
+ return choices + (writeIn ? 1 : 0) + (submit ? 1 : 0);
834
+ }
835
+ function QuestionPrompt(props) {
836
+ const { client, question, askerLabel, active, onAnswered } = props;
837
+ const choices = question.choices ?? [];
838
+ const allowWriteIn = question.allowWriteIn ?? true;
839
+ const multiSelect = question.multiSelect === true;
840
+ const options = [
841
+ ...choices.map(
842
+ (label, choiceIndex) => ({ kind: "choice", choiceIndex, label })
843
+ ),
844
+ ...allowWriteIn ? [{ kind: "write-in", label: "Other\u2026" }] : [],
845
+ ...multiSelect && choices.length > 0 ? [{ kind: "submit", label: "Submit selections" }] : []
846
+ ];
847
+ const [optionIndex, setOptionIndex] = useState3(0);
848
+ const [selected, setSelected] = useState3(() => /* @__PURE__ */ new Set());
849
+ const [writing, setWriting] = useState3(choices.length === 0 && allowWriteIn);
850
+ const [writeIn, setWriteIn] = useState3("");
851
+ const [submitting, setSubmitting] = useState3(false);
852
+ const [error, setError] = useState3(null);
853
+ const activeOptionIndex = Math.min(optionIndex, Math.max(0, options.length - 1));
854
+ const windowStart = Math.min(
855
+ Math.max(0, activeOptionIndex - QUESTION_OPTION_WINDOW_SIZE + 1),
856
+ Math.max(0, options.length - QUESTION_OPTION_WINDOW_SIZE)
857
+ );
858
+ const visibleOptions = options.slice(windowStart, windowStart + QUESTION_OPTION_WINDOW_SIZE);
859
+ const submit = async (body) => {
860
+ if (submitting) return;
861
+ if (!body.writeIn && (!body.selectedChoices || body.selectedChoices.length === 0)) {
862
+ setError("Choose an option or supply your own response.");
863
+ return;
864
+ }
865
+ setError(null);
866
+ setSubmitting(true);
867
+ try {
868
+ onAnswered(await client.answerQuestion(question.id, body));
869
+ } catch (err) {
870
+ setError(err instanceof Error ? err.message : String(err));
871
+ setSubmitting(false);
872
+ }
873
+ };
874
+ const submitWriteIn = (value) => {
875
+ const answer = value.trim();
876
+ if (!answer) {
877
+ setError("Type a response before submitting.");
878
+ return;
879
+ }
880
+ void submit({
881
+ ...multiSelect && selected.size > 0 ? { selectedChoices: [...selected].sort((a, b) => a - b) } : {},
882
+ writeIn: answer
883
+ });
884
+ };
885
+ useInput3(
886
+ (input, key) => {
887
+ if (submitting) return;
888
+ if (writing) {
889
+ if (key.escape && choices.length > 0) {
890
+ setWriting(false);
891
+ setError(null);
892
+ }
893
+ return;
894
+ }
895
+ if (key.upArrow) {
896
+ setOptionIndex((index) => index <= 0 ? Math.max(0, options.length - 1) : index - 1);
897
+ return;
898
+ }
899
+ if (key.downArrow) {
900
+ setOptionIndex((index) => index >= options.length - 1 ? 0 : index + 1);
901
+ return;
902
+ }
903
+ const option = options[activeOptionIndex];
904
+ if (!option) return;
905
+ if (input === " " && multiSelect && option.kind === "choice") {
906
+ setSelected((current) => toggleSet(current, option.choiceIndex));
907
+ return;
908
+ }
909
+ if (!key.return) return;
910
+ if (option.kind === "write-in") {
911
+ setWriting(true);
912
+ setError(null);
913
+ } else if (option.kind === "submit") {
914
+ void submit({ selectedChoices: [...selected].sort((a, b) => a - b) });
915
+ } else if (multiSelect) {
916
+ setSelected((current) => toggleSet(current, option.choiceIndex));
917
+ } else {
918
+ void submit({ selectedChoices: [option.choiceIndex] });
919
+ }
920
+ },
921
+ { isActive: active }
922
+ );
923
+ return /* @__PURE__ */ jsxs5(Box5, { flexDirection: "column", borderStyle: "round", borderColor: "yellow", paddingX: 1, children: [
924
+ /* @__PURE__ */ jsxs5(Text5, { bold: true, color: "yellow", children: [
925
+ askerLabel,
926
+ " asks"
927
+ ] }),
928
+ /* @__PURE__ */ jsx5(Text5, { wrap: "wrap", children: question.prompt }),
929
+ writing ? /* @__PURE__ */ jsxs5(Fragment3, { children: [
930
+ /* @__PURE__ */ jsxs5(Box5, { children: [
931
+ /* @__PURE__ */ jsx5(Text5, { color: "cyan", children: "\u203A " }),
932
+ /* @__PURE__ */ jsx5(
933
+ TextInput2,
934
+ {
935
+ value: writeIn,
936
+ onChange: setWriteIn,
937
+ onSubmit: submitWriteIn,
938
+ focus: active && !submitting,
939
+ placeholder: "Type your response"
940
+ }
941
+ )
942
+ ] }),
943
+ /* @__PURE__ */ jsxs5(Text5, { dimColor: true, children: [
944
+ "Enter submit",
945
+ choices.length > 0 ? " \xB7 Esc return to choices" : ""
946
+ ] })
947
+ ] }) : /* @__PURE__ */ jsxs5(Fragment3, { children: [
948
+ visibleOptions.map((option, visibleIndex) => {
949
+ const index = windowStart + visibleIndex;
950
+ const focused = index === activeOptionIndex;
951
+ const checked = option.kind === "choice" && multiSelect && selected.has(option.choiceIndex);
952
+ return /* @__PURE__ */ jsxs5(Text5, { color: focused ? "cyan" : void 0, children: [
953
+ focused ? "\u203A " : " ",
954
+ option.kind === "choice" && multiSelect ? checked ? "[x] " : "[ ] " : "",
955
+ option.label
956
+ ] }, `${option.kind}:${option.label}`);
957
+ }),
958
+ /* @__PURE__ */ jsxs5(Text5, { dimColor: true, children: [
959
+ "\u2191/\u2193 choose \xB7 Enter ",
960
+ multiSelect ? "toggle/submit" : "answer",
961
+ multiSelect ? " \xB7 Space toggle" : "",
962
+ options.length > QUESTION_OPTION_WINDOW_SIZE ? ` \xB7 ${activeOptionIndex + 1}/${options.length}` : ""
963
+ ] })
964
+ ] }),
965
+ submitting ? /* @__PURE__ */ jsx5(Text5, { color: "yellow", children: "Submitting\u2026" }) : null,
966
+ error ? /* @__PURE__ */ jsx5(Text5, { color: "red", children: error }) : null
967
+ ] });
968
+ }
969
+ function toggleSet(current, value) {
970
+ const next = new Set(current);
971
+ if (next.has(value)) next.delete(value);
972
+ else next.add(value);
973
+ return next;
974
+ }
975
+
976
+ // src/tui/craftbook-start.ts
977
+ import {
978
+ CRAFTBOOK_ROLE_META
979
+ } from "@bendyline/gezel";
980
+ function normalizeCraftbooks(items) {
981
+ const byId = /* @__PURE__ */ new Map();
982
+ for (const item of items) {
983
+ if (item.manifest.kind !== "craftbook-template") continue;
984
+ const manifest = item.manifest;
985
+ if (byId.has(manifest.id)) continue;
986
+ byId.set(manifest.id, {
987
+ id: manifest.id,
988
+ name: manifest.name,
989
+ ...manifest.description ? { description: manifest.description } : {},
990
+ version: manifest.version,
991
+ sourceId: item.sourceId,
992
+ source: item.sourceId === "project" ? "project" : item.sourceId === "local" ? "local" : "bundled",
993
+ stepCount: manifest.steps.length,
994
+ tags: manifest.tags ?? [],
995
+ role: manifest.role ?? "general"
996
+ });
997
+ }
998
+ return [...byId.values()].sort((left, right) => left.name.localeCompare(right.name));
999
+ }
1000
+ function craftbookCategories(books, suggestedIds, projectType) {
1001
+ const categories = [];
1002
+ const allIds = new Set(books.map((book) => book.id));
1003
+ const recommended = new Set([...suggestedIds].filter((id) => allIds.has(id)));
1004
+ if (recommended.size > 0) {
1005
+ categories.push({
1006
+ id: "recommended",
1007
+ label: projectType ? `Recommended for ${projectType.label}` : "Recommended",
1008
+ hint: countLabel(recommended.size),
1009
+ bookIds: recommended
1010
+ });
1011
+ }
1012
+ const projectBooks = new Set(
1013
+ books.filter((book) => book.source === "project").map((book) => book.id)
1014
+ );
1015
+ if (projectBooks.size > 0) {
1016
+ categories.push({
1017
+ id: "project",
1018
+ label: "Project craftbooks",
1019
+ hint: countLabel(projectBooks.size),
1020
+ bookIds: projectBooks
1021
+ });
1022
+ }
1023
+ for (const role of CRAFTBOOK_ROLE_META) {
1024
+ const bookIds = new Set(books.filter((book) => book.role === role.id).map((book) => book.id));
1025
+ if (bookIds.size === 0) continue;
1026
+ categories.push({
1027
+ id: `role:${role.id}`,
1028
+ label: role.label,
1029
+ hint: countLabel(bookIds.size),
1030
+ bookIds
1031
+ });
1032
+ }
1033
+ categories.push({
1034
+ id: "all",
1035
+ label: "All craftbooks",
1036
+ hint: countLabel(allIds.size),
1037
+ bookIds: allIds
1038
+ });
1039
+ return categories;
1040
+ }
1041
+ function countLabel(count) {
1042
+ return `${count} ${count === 1 ? "craftbook" : "craftbooks"}`;
1043
+ }
1044
+ function findCraftbook(books, value) {
1045
+ const query = value.trim().toLowerCase();
1046
+ return books.find((book) => book.id.toLowerCase() === query || book.name.toLowerCase() === query);
1047
+ }
1048
+ function craftbookStartRequest(book) {
1049
+ const summary = book.description?.trim();
1050
+ const description = summary ? `Start the "${book.name}" craftbook for this project. ${summary}` : `Start the "${book.name}" craftbook for this project. Follow every step in the recipe and verify its required outcomes before completing the task.`;
1051
+ return {
1052
+ title: book.name,
1053
+ description,
1054
+ craftbookId: book.id,
1055
+ craftbookSourceId: book.sourceId,
1056
+ ...book.version ? { craftbookVersion: book.version } : {},
1057
+ dispatchEntry: true
1058
+ };
1059
+ }
1060
+
1061
+ // src/tui/model-picker.ts
1062
+ var PROVIDER_ORDER = [
1063
+ "mlx",
1064
+ "llama-cpp",
1065
+ "ds4",
1066
+ "ollama",
1067
+ "copilot",
1068
+ "openai",
1069
+ "anthropic",
1070
+ "anthropic-cli",
1071
+ "codex-cli"
1072
+ ];
1073
+ function modelProviderLabel(provider) {
1074
+ switch (provider) {
1075
+ case "copilot":
1076
+ return "GitHub Copilot";
1077
+ case "openai":
1078
+ return "OpenAI";
1079
+ case "anthropic":
1080
+ return "Anthropic";
1081
+ case "anthropic-cli":
1082
+ return "Claude CLI";
1083
+ case "codex-cli":
1084
+ return "Codex CLI";
1085
+ case "ollama":
1086
+ return "Ollama";
1087
+ case "llama-cpp":
1088
+ return "llama.cpp";
1089
+ case "mlx":
1090
+ return "MLX";
1091
+ case "ds4":
1092
+ return "DwarfStar (ds4)";
1093
+ case "remote":
1094
+ return "Remote";
1095
+ }
1096
+ }
1097
+ function configuredModelProviders(config, opts) {
1098
+ const providers = [];
1099
+ if (opts.platform === "darwin" && opts.arch === "arm64") providers.push("mlx");
1100
+ providers.push("llama-cpp");
1101
+ const ds4PlatformAvailable = Boolean(config.ds4BaseUrl) || opts.platform === "linux" || opts.platform === "darwin" && opts.arch === "arm64";
1102
+ const ds4MemoryAvailable = Boolean(config.ds4BaseUrl) || opts.totalRamBytes === null || opts.totalRamBytes >= 45 * 1024 ** 3;
1103
+ if (ds4PlatformAvailable && ds4MemoryAvailable) providers.push("ds4");
1104
+ providers.push("ollama");
1105
+ if (opts.copilotAvailable !== false) providers.push("copilot");
1106
+ if (config.hasOpenaiApiKey) providers.push("openai");
1107
+ if (config.hasAnthropicApiKey) providers.push("anthropic");
1108
+ if (config.anthropicCliStatus?.installed) providers.push("anthropic-cli");
1109
+ if (config.codexCliStatus?.installed) providers.push("codex-cli");
1110
+ return providers.sort((a, b) => PROVIDER_ORDER.indexOf(a) - PROVIDER_ORDER.indexOf(b));
1111
+ }
1112
+ async function loadModelChoices(client, config, platform = process.platform, arch = process.arch) {
1113
+ const [copilot, memory] = await Promise.all([
1114
+ client.getCopilotStatus().catch(() => null),
1115
+ client.getMemoryProfile().catch(() => null)
1116
+ ]);
1117
+ const providers = configuredModelProviders(config, {
1118
+ platform,
1119
+ arch,
1120
+ copilotAvailable: copilot?.available ?? null,
1121
+ totalRamBytes: memory?.totalRamBytes ?? null
1122
+ });
1123
+ const inventories = await Promise.all(
1124
+ providers.map(async (provider) => {
1125
+ try {
1126
+ const result = await client.listProviderModels(provider);
1127
+ return { provider, models: result.models };
1128
+ } catch {
1129
+ return { provider, models: [] };
1130
+ }
1131
+ })
1132
+ );
1133
+ return inventories.flatMap(
1134
+ ({ provider, models }) => models.map((model) => ({
1135
+ provider,
1136
+ model,
1137
+ value: `${provider}:${model.id}`,
1138
+ label: `${modelProviderLabel(provider)} \xB7 ${model.name}`
1139
+ }))
1140
+ );
1141
+ }
1142
+
1143
+ // src/tui/question-queue.ts
1144
+ function plainPendingQuestions(questions) {
1145
+ return questions.filter((question) => !question.answer && !question.intent).slice().sort((a, b) => a.createdAt.localeCompare(b.createdAt));
1146
+ }
1147
+ function updatePendingQuestion(questions, question) {
1148
+ const withoutCurrent = questions.filter((candidate) => candidate.id !== question.id);
1149
+ return plainPendingQuestions(question.answer ? withoutCurrent : [...withoutCurrent, question]);
1150
+ }
1151
+
1152
+ // src/tui/streams.ts
1153
+ import { streamProjectChatEvents, streamTerminalEvents } from "@bendyline/gezel-client";
1154
+ import { useEffect as useEffect2, useRef } from "react";
1155
+ function useProjectEvents(client, projectId, handler) {
1156
+ const handlerRef = useRef(handler);
1157
+ handlerRef.current = handler;
1158
+ useEffect2(() => {
1159
+ const controller = new AbortController();
1160
+ void consumeWithReconnect(
1161
+ async function* () {
1162
+ for await (const env of streamProjectChatEvents({
1163
+ url: client.projectEventsUrl(projectId),
1164
+ headers: client.authHeader(),
1165
+ fetch: client.getFetch(),
1166
+ signal: controller.signal
1167
+ })) {
1168
+ yield env;
1169
+ }
1170
+ },
1171
+ (env) => handlerRef.current(env),
1172
+ controller.signal
1173
+ );
1174
+ return () => controller.abort();
1175
+ }, [client, projectId]);
1176
+ }
1177
+ function useTerminalEvents(client, projectId, handler) {
1178
+ const handlerRef = useRef(handler);
1179
+ handlerRef.current = handler;
1180
+ useEffect2(() => {
1181
+ const controller = new AbortController();
1182
+ void consumeWithReconnect(
1183
+ async function* () {
1184
+ for await (const env of streamTerminalEvents({
1185
+ url: client.terminalEventsUrl(projectId),
1186
+ headers: client.authHeader(),
1187
+ fetch: client.getFetch(),
1188
+ signal: controller.signal
1189
+ })) {
1190
+ yield env;
1191
+ }
1192
+ },
1193
+ (env) => handlerRef.current(env),
1194
+ controller.signal
1195
+ );
1196
+ return () => controller.abort();
1197
+ }, [client, projectId]);
1198
+ }
1199
+ async function consumeWithReconnect(open, handler, signal) {
1200
+ let retryMs = 250;
1201
+ while (!signal.aborted) {
1202
+ try {
1203
+ for await (const event of open()) {
1204
+ handler(event);
1205
+ retryMs = 250;
1206
+ }
1207
+ } catch {
1208
+ }
1209
+ if (signal.aborted) return;
1210
+ await abortableDelay(retryMs, signal);
1211
+ retryMs = Math.min(retryMs * 2, 5e3);
1212
+ }
1213
+ }
1214
+ function abortableDelay(ms, signal) {
1215
+ return new Promise((resolve) => {
1216
+ const timer = setTimeout(done, ms);
1217
+ signal.addEventListener("abort", done, { once: true });
1218
+ function done() {
1219
+ clearTimeout(timer);
1220
+ signal.removeEventListener("abort", done);
1221
+ resolve();
1222
+ }
1223
+ });
1224
+ }
1225
+
1226
+ // src/tui/App.tsx
1227
+ import { jsx as jsx6, jsxs as jsxs6 } from "react/jsx-runtime";
1228
+ function useTerminalSize() {
1229
+ const { stdout } = useStdout();
1230
+ const [size, setSize] = useState4({ rows: stdout?.rows ?? 24, columns: stdout?.columns ?? 80 });
1231
+ useEffect3(() => {
1232
+ if (!stdout) return;
1233
+ const onResize = () => setSize({ rows: stdout.rows ?? 24, columns: stdout.columns ?? 80 });
1234
+ stdout.on("resize", onResize);
1235
+ return () => {
1236
+ stdout.off("resize", onResize);
1237
+ };
1238
+ }, [stdout]);
1239
+ return size;
1240
+ }
1241
+ var HELP = [
1242
+ "/project \u2014 switch project /gezel \u2014 switch gezel /model \u2014 switch engine + model",
1243
+ "/thread \u2014 switch or start a chat thread",
1244
+ "/task \u2014 list, inspect, create, edit, assign, or change task status",
1245
+ "/start \u2014 choose a craftbook and start it as a task",
1246
+ "/continue \u2014 process due schedules and active tasks in this project",
1247
+ "/nightshift start|stop|list \u2014 manage Night Shift",
1248
+ "/focus \u2014 send into another active chat /cli \u2014 CLI mode /chat \u2014 chat mode",
1249
+ "!cmd \u2014 run shell @tools \u2014 list tools @tool <name> {json} \u2014 run a tool",
1250
+ "/clear \u2014 clear feed /quit \u2014 exit",
1251
+ "\u2191/\u2193 \u2014 input history Esc \u2014 interrupt turn Ctrl+C \u2014 interrupt, then again to exit"
1252
+ ];
1253
+ function App(props) {
1254
+ const { client } = props;
1255
+ const { exit } = useApp();
1256
+ const [config, setConfig] = useState4(null);
1257
+ const [gezels, setGezels] = useState4([]);
1258
+ const [projects, setProjects] = useState4([]);
1259
+ const [threads, setThreads] = useState4([]);
1260
+ const [tasks, setTasks] = useState4([]);
1261
+ const [craftbooks, setCraftbooks] = useState4([]);
1262
+ const [craftbookProjectType, setCraftbookProjectType] = useState4(null);
1263
+ const [suggestedCraftbookIds, setSuggestedCraftbookIds] = useState4(() => /* @__PURE__ */ new Set());
1264
+ const [craftbooksNeedingSetup, setCraftbooksNeedingSetup] = useState4(
1265
+ () => /* @__PURE__ */ new Set()
1266
+ );
1267
+ const [startCategoryId, setStartCategoryId] = useState4(null);
1268
+ const [modelChoices, setModelChoices] = useState4([]);
1269
+ const [modelChoicesLoading, setModelChoicesLoading] = useState4(false);
1270
+ const [threadsLoading, setThreadsLoading] = useState4(false);
1271
+ const [pendingQuestions, setPendingQuestions] = useState4([]);
1272
+ const [projectId, setProjectId] = useState4(props.initialProjectId);
1273
+ const [projectName, setProjectName] = useState4(props.initialProjectName);
1274
+ const [activeGezelId, setActiveGezelId] = useState4(null);
1275
+ const [ownSessionId, setOwnSessionId] = useState4(null);
1276
+ const [focusedSessionId, setFocusedSessionId] = useState4(null);
1277
+ const [activeThreadTitle, setActiveThreadTitle] = useState4(null);
1278
+ const [mode, setMode] = useState4("chat");
1279
+ const [overlay, setOverlay] = useState4(null);
1280
+ const [value, setValue] = useState4("");
1281
+ const [rows, setRows] = useState4([]);
1282
+ const [turns, setTurns] = useState4(() => /* @__PURE__ */ new Map());
1283
+ const [status, setStatus] = useState4("Connecting\u2026");
1284
+ const [history, setHistory] = useState4([]);
1285
+ const [activeRuns, setActiveRuns] = useState4(() => /* @__PURE__ */ new Set());
1286
+ const [pendingInput, setPendingInput] = useState4(null);
1287
+ const [managedTaskRef, setManagedTaskRef] = useState4(null);
1288
+ const [taskPrompt, setTaskPrompt] = useState4(null);
1289
+ const [exitArmed, setExitArmed] = useState4(false);
1290
+ const pendingQuestion = pendingQuestions[0];
1291
+ const { rows: termRows, columns: termColumns } = useTerminalSize();
1292
+ const shellColumns = Math.min(500, Math.max(20, termColumns - 2));
1293
+ const wordwheelCount = overlay === null && !pendingInput && !pendingQuestion ? suggestSlashWordwheel(value, craftbooks).length : 0;
1294
+ const wordwheelRows = wordwheelCount > 0 ? Math.min(SLASH_COMMAND_WORDWHEEL_SIZE, wordwheelCount) + 1 : 0;
1295
+ const questionRows = pendingQuestion ? Math.min(QUESTION_OPTION_WINDOW_SIZE, Math.max(1, questionOptionCount(pendingQuestion))) + 4 : 0;
1296
+ const modelPickerWindowSize = Math.max(4, Math.min(10, termRows - 12));
1297
+ const inventoryPickerRows = overlay === "model" || overlay === "start-category" || overlay === "start-craftbook" ? modelPickerWindowSize + 5 : 0;
1298
+ const visibleRows = Math.max(
1299
+ 4,
1300
+ termRows - 7 - wordwheelRows - questionRows - inventoryPickerRows
1301
+ );
1302
+ const boring = props.boring ?? true;
1303
+ const busy = turns.size > 0;
1304
+ const activeGezel = useMemo(
1305
+ () => gezels.find((gezel) => gezel.id === activeGezelId),
1306
+ [gezels, activeGezelId]
1307
+ );
1308
+ const effectiveProvider = activeGezel?.provider ?? config?.provider;
1309
+ const effectiveModel = activeGezel?.model ?? (effectiveProvider ? config?.defaultModel?.[effectiveProvider] : void 0);
1310
+ const statusLabel = useMemo(() => {
1311
+ if (turns.size === 0) return void 0;
1312
+ return focusedSessionId && turns.get(focusedSessionId) || ownSessionId && turns.get(ownSessionId) || turns.values().next().value;
1313
+ }, [turns, focusedSessionId, ownSessionId]);
1314
+ const note = useCallback(
1315
+ (text, kind = "note") => setRows((r) => appendNote(r, text, kind)),
1316
+ []
1317
+ );
1318
+ const taskLoadSequence = useRef2(0);
1319
+ const refreshTasks = useCallback(async () => {
1320
+ const sequence = ++taskLoadSequence.current;
1321
+ try {
1322
+ const res = await client.listProjectTasks(projectId);
1323
+ if (sequence !== taskLoadSequence.current) return;
1324
+ setTasks(sortTasks(res.tasks));
1325
+ } catch {
1326
+ }
1327
+ }, [client, projectId]);
1328
+ const craftbookLoadSequence = useRef2(0);
1329
+ const refreshCraftbooks = useCallback(async () => {
1330
+ const sequence = ++craftbookLoadSequence.current;
1331
+ const result = await client.listProjectCraftbooks(projectId);
1332
+ if (sequence !== craftbookLoadSequence.current) return [];
1333
+ const next = normalizeCraftbooks(result.items);
1334
+ setCraftbooks(next);
1335
+ setCraftbookProjectType(result.projectType ?? null);
1336
+ setSuggestedCraftbookIds(new Set(result.suggestedIds ?? []));
1337
+ setCraftbooksNeedingSetup(new Set(Object.keys(result.missingToolsets)));
1338
+ return next;
1339
+ }, [client, projectId]);
1340
+ useProjectEvents(
1341
+ client,
1342
+ projectId,
1343
+ useCallback(
1344
+ (env) => {
1345
+ setRows((r) => reduceFeed(r, env));
1346
+ setTurns((t) => reduceTurns(t, env));
1347
+ if (env.event.type === "task_event") void refreshTasks();
1348
+ if (env.event.type === "user_message" && env.sessionId === ownSessionId) {
1349
+ const nextTitle = env.event.message.content.slice(0, 60).trim() || "Untitled";
1350
+ setActiveThreadTitle((current) => current === "New thread" ? nextTitle : current);
1351
+ setThreads(
1352
+ (current) => current.map(
1353
+ (thread) => thread.id === env.sessionId && thread.title === "New session" ? { ...thread, title: nextTitle } : thread
1354
+ )
1355
+ );
1356
+ }
1357
+ if (env.event.type === "question_asked" || env.event.type === "question_answered") {
1358
+ const question = env.event.question;
1359
+ setPendingQuestions((questions) => updatePendingQuestion(questions, question));
1360
+ }
1361
+ },
1362
+ [ownSessionId, refreshTasks]
1363
+ )
1364
+ );
1365
+ useTerminalEvents(
1366
+ client,
1367
+ projectId,
1368
+ useCallback((env) => {
1369
+ switch (env.kind) {
1370
+ case "runStarted":
1371
+ setActiveRuns((s) => new Set(s).add(env.runId));
1372
+ return;
1373
+ case "outputChunk":
1374
+ setRows((r) => appendShellChunk(r, env.runId, env.chunk));
1375
+ return;
1376
+ case "inputRequested":
1377
+ setPendingInput({ runId: env.runId, mode: env.mode, promptLine: env.promptLine });
1378
+ setRows((r) => appendNote(r, `\u2328 waiting for input \u2014 ${env.promptLine}`, "note"));
1379
+ return;
1380
+ case "message": {
1381
+ const runId = env.runId;
1382
+ if (!runId) return;
1383
+ setActiveRuns((s) => {
1384
+ if (!s.has(runId)) return s;
1385
+ const n = new Set(s);
1386
+ n.delete(runId);
1387
+ return n;
1388
+ });
1389
+ setPendingInput((p) => p?.runId === runId ? null : p);
1390
+ setRows((r) => finalizeShellRun(r, runId, env.message));
1391
+ return;
1392
+ }
1393
+ default:
1394
+ return;
1395
+ }
1396
+ }, [])
1397
+ );
1398
+ const ensureSession = useCallback(
1399
+ async (gezelId, pid) => {
1400
+ try {
1401
+ const session = await client.createChatSession({ gezelId, projectId: pid });
1402
+ setOwnSessionId(session.id);
1403
+ setFocusedSessionId(session.id);
1404
+ setActiveThreadTitle(displayThreadTitle(session.title));
1405
+ return true;
1406
+ } catch (err) {
1407
+ note(`could not start a session: ${errMsg(err)}`, "error");
1408
+ return false;
1409
+ }
1410
+ },
1411
+ [client, note]
1412
+ );
1413
+ const openThreadPicker = useCallback(async () => {
1414
+ if (!activeGezelId) return note("no active gezel yet.", "error");
1415
+ if (threadsLoading) return;
1416
+ setThreadsLoading(true);
1417
+ try {
1418
+ const result = await client.listChatSessions({ gezelId: activeGezelId, projectId });
1419
+ setThreads(result.sessions.filter((session) => !session.archived && !session.taskRef));
1420
+ setOverlay("thread");
1421
+ } catch (err) {
1422
+ note(`could not load threads: ${errMsg(err)}`, "error");
1423
+ } finally {
1424
+ setThreadsLoading(false);
1425
+ }
1426
+ }, [activeGezelId, client, note, projectId, threadsLoading]);
1427
+ const switchThread = useCallback(
1428
+ async (sessionId) => {
1429
+ setOverlay(null);
1430
+ try {
1431
+ const session = await client.getChatSession(sessionId);
1432
+ if (session.gezelId !== activeGezelId || session.projectId !== projectId) {
1433
+ throw new Error("thread no longer belongs to the active gezel and project");
1434
+ }
1435
+ setOwnSessionId(session.id);
1436
+ setFocusedSessionId(session.id);
1437
+ setActiveThreadTitle(displayThreadTitle(session.title));
1438
+ setRows(sessionToFeedRows(session));
1439
+ } catch (err) {
1440
+ note(`could not switch thread: ${errMsg(err)}`, "error");
1441
+ }
1442
+ },
1443
+ [activeGezelId, client, note, projectId]
1444
+ );
1445
+ const startNewThread = useCallback(async () => {
1446
+ setOverlay(null);
1447
+ if (!activeGezelId) return note("no active gezel yet.", "error");
1448
+ try {
1449
+ const session = await client.createChatSession({ gezelId: activeGezelId, projectId });
1450
+ setOwnSessionId(session.id);
1451
+ setFocusedSessionId(session.id);
1452
+ setActiveThreadTitle(displayThreadTitle(session.title));
1453
+ setRows([]);
1454
+ setThreads((current) => [session, ...current.filter((item) => item.id !== session.id)]);
1455
+ } catch (err) {
1456
+ note(`could not start a thread: ${errMsg(err)}`, "error");
1457
+ }
1458
+ }, [activeGezelId, client, note, projectId]);
1459
+ useEffect3(() => {
1460
+ let cancelled = false;
1461
+ (async () => {
1462
+ try {
1463
+ const [cfg, gz, pj] = await Promise.all([
1464
+ client.getConfig(),
1465
+ client.listGezels(),
1466
+ client.listProjects()
1467
+ ]);
1468
+ if (cancelled) return;
1469
+ setConfig(cfg);
1470
+ setGezels(gz.gezels);
1471
+ setProjects(
1472
+ pj.projects.map((p) => ({
1473
+ id: p.id,
1474
+ name: p.name,
1475
+ workingDir: p.workingDir,
1476
+ allowGezelWrites: p.allowGezelWrites,
1477
+ codexPermissionMode: p.codexPermissionMode
1478
+ }))
1479
+ );
1480
+ const gezelId = cfg.meesterGezelId ?? gz.gezels[0]?.id ?? null;
1481
+ setActiveGezelId(gezelId);
1482
+ setStatus(null);
1483
+ if (gezelId) await ensureSession(gezelId, projectId);
1484
+ else note("no gezels available \u2014 create one with `gezel agent create`.", "error");
1485
+ } catch (err) {
1486
+ if (!cancelled) setStatus(`Failed to connect: ${errMsg(err)}`);
1487
+ }
1488
+ })();
1489
+ return () => {
1490
+ cancelled = true;
1491
+ };
1492
+ }, []);
1493
+ useEffect3(() => {
1494
+ let cancelled = false;
1495
+ setPendingQuestions([]);
1496
+ void client.listQuestions({ projectId, pending: true }).then((result) => {
1497
+ if (!cancelled) setPendingQuestions(plainPendingQuestions(result.questions));
1498
+ }).catch(() => {
1499
+ });
1500
+ return () => {
1501
+ cancelled = true;
1502
+ };
1503
+ }, [client, projectId]);
1504
+ useEffect3(() => {
1505
+ void refreshTasks();
1506
+ const id = setInterval(() => void refreshTasks(), 3e4);
1507
+ return () => {
1508
+ clearInterval(id);
1509
+ };
1510
+ }, [refreshTasks]);
1511
+ useEffect3(() => {
1512
+ void refreshCraftbooks().catch(() => {
1513
+ });
1514
+ }, [refreshCraftbooks]);
1515
+ const managedTask = useMemo(
1516
+ () => tasks.find((task) => task.ref === managedTaskRef),
1517
+ [managedTaskRef, tasks]
1518
+ );
1519
+ const startCategories = useMemo(
1520
+ () => craftbookCategories(craftbooks, suggestedCraftbookIds, craftbookProjectType),
1521
+ [craftbookProjectType, craftbooks, suggestedCraftbookIds]
1522
+ );
1523
+ const startCategory = useMemo(
1524
+ () => startCategories.find((category) => category.id === startCategoryId),
1525
+ [startCategories, startCategoryId]
1526
+ );
1527
+ const startCategoryBooks = useMemo(
1528
+ () => startCategory ? craftbooks.filter((book) => startCategory.bookIds.has(book.id)) : craftbooks,
1529
+ [craftbooks, startCategory]
1530
+ );
1531
+ const gezelLine = useMemo(() => {
1532
+ const g = gezels.find((x) => x.id === activeGezelId);
1533
+ if (!g) return "\u2026";
1534
+ if (boring) return g.roleBasedName ?? g.role ?? g.id;
1535
+ return g.role ? `${g.name} \xB7 ${g.role}` : g.name;
1536
+ }, [gezels, activeGezelId, boring]);
1537
+ const activeProject = useMemo(
1538
+ () => projects.find((project) => project.id === projectId),
1539
+ [projects, projectId]
1540
+ );
1541
+ const accessMode = useMemo(
1542
+ () => activeAccessMode({
1543
+ provider: effectiveProvider,
1544
+ project: activeProject,
1545
+ gezel: activeGezel,
1546
+ config
1547
+ }),
1548
+ [activeGezel, activeProject, config, effectiveProvider]
1549
+ );
1550
+ const focusItems = useMemo(() => {
1551
+ const seen = /* @__PURE__ */ new Map();
1552
+ for (const r of rows) {
1553
+ if (r.sessionId === "local" || r.sessionId.startsWith("term-")) continue;
1554
+ if (!seen.has(r.sessionId)) {
1555
+ const label = gezels.find((g) => g.id === r.gezelId)?.name ?? (r.gezelId || r.sessionId);
1556
+ seen.set(r.sessionId, label);
1557
+ }
1558
+ }
1559
+ const items = [];
1560
+ if (ownSessionId) items.push({ label: "your session", value: ownSessionId, hint: gezelLine });
1561
+ for (const [sid, label] of seen) {
1562
+ if (sid === ownSessionId) continue;
1563
+ items.push({ label, value: sid });
1564
+ }
1565
+ return items;
1566
+ }, [rows, gezels, ownSessionId, gezelLine]);
1567
+ const cancelActive = useCallback(async () => {
1568
+ const sessions = [...turns.keys()];
1569
+ const runs = [...activeRuns];
1570
+ if (sessions.length === 0 && runs.length === 0) return false;
1571
+ await Promise.allSettled([
1572
+ ...sessions.map((s) => client.cancelChatSessionTurn(s)),
1573
+ ...runs.map((r) => client.cancelTerminalRun(projectId, r))
1574
+ ]);
1575
+ return true;
1576
+ }, [turns, activeRuns, client, projectId]);
1577
+ const rememberTask = useCallback((task) => {
1578
+ setTasks((current) => sortTasks([...current.filter((item) => item.ref !== task.ref), task]));
1579
+ }, []);
1580
+ const startCraftbook = useCallback(
1581
+ async (book) => {
1582
+ setOverlay(null);
1583
+ note(`starting ${book.name}\u2026`);
1584
+ try {
1585
+ const created = await client.createTask(projectId, craftbookStartRequest(book));
1586
+ rememberTask(created);
1587
+ setManagedTaskRef(created.ref);
1588
+ note(`started ${created.ref} \u2014 ${created.title}`);
1589
+ } catch (err) {
1590
+ note(`could not start ${book.name}: ${errMsg(err)}`, "error");
1591
+ }
1592
+ },
1593
+ [client, note, projectId, rememberTask]
1594
+ );
1595
+ const submitTaskPrompt = useCallback(
1596
+ async (raw) => {
1597
+ const prompt = taskPrompt;
1598
+ if (!prompt) return;
1599
+ const text = raw.trim();
1600
+ if (!text) {
1601
+ note("task edit canceled.");
1602
+ setTaskPrompt(null);
1603
+ return;
1604
+ }
1605
+ setTaskPrompt(null);
1606
+ try {
1607
+ if (prompt.kind === "create") {
1608
+ const created = await client.createTask(projectId, {
1609
+ title: text,
1610
+ description: `${text} \u2014 complete this task and verify that the result meets the requested outcome.`,
1611
+ assignee: { kind: "user" },
1612
+ steps: [{ name: "Main" }]
1613
+ });
1614
+ rememberTask(created);
1615
+ setManagedTaskRef(created.ref);
1616
+ setOverlay("task-actions");
1617
+ return;
1618
+ }
1619
+ const task = tasks.find((item) => item.ref === prompt.taskRef);
1620
+ if (!task) throw new Error(`task ${prompt.taskRef ?? ""} is no longer available`);
1621
+ const updated = await client.updateTask(task.projectId, task.num, {
1622
+ [prompt.kind]: text
1623
+ });
1624
+ rememberTask(updated);
1625
+ setManagedTaskRef(updated.ref);
1626
+ setOverlay("task-actions");
1627
+ } catch (err) {
1628
+ note(`task update failed: ${errMsg(err)}`, "error");
1629
+ }
1630
+ },
1631
+ [client, note, projectId, rememberTask, taskPrompt, tasks]
1632
+ );
1633
+ const applyTaskStatus = useCallback(
1634
+ async (status2) => {
1635
+ const task = managedTask;
1636
+ if (!task) return setOverlay("task");
1637
+ setOverlay(null);
1638
+ try {
1639
+ const updated = task.status === "draft" && status2 === "active" ? await client.activateTask(task.projectId, task.num) : await client.setTaskStatus(task.projectId, task.num, status2);
1640
+ rememberTask(updated);
1641
+ setManagedTaskRef(updated.ref);
1642
+ setOverlay("task-actions");
1643
+ } catch (err) {
1644
+ note(`could not change ${task.ref}: ${errMsg(err)}`, "error");
1645
+ }
1646
+ },
1647
+ [client, managedTask, note, rememberTask]
1648
+ );
1649
+ const applyTaskAssignee = useCallback(
1650
+ async (value2) => {
1651
+ const task = managedTask;
1652
+ if (!task) return setOverlay("task");
1653
+ setOverlay(null);
1654
+ try {
1655
+ const updated = await client.setTaskAssignee(
1656
+ task.projectId,
1657
+ task.num,
1658
+ value2 === "__user__" ? { kind: "user" } : { kind: "gezel", gezelId: value2 }
1659
+ );
1660
+ rememberTask(updated);
1661
+ setManagedTaskRef(updated.ref);
1662
+ setOverlay("task-actions");
1663
+ } catch (err) {
1664
+ note(`could not reassign ${task.ref}: ${errMsg(err)}`, "error");
1665
+ }
1666
+ },
1667
+ [client, managedTask, note, rememberTask]
1668
+ );
1669
+ const runInput = useCallback(
1670
+ async (raw) => {
1671
+ if (pendingInput) {
1672
+ const target = pendingInput;
1673
+ setPendingInput(null);
1674
+ try {
1675
+ await client.sendTerminalInput(projectId, target.runId, raw);
1676
+ } catch (err) {
1677
+ note(`input failed: ${errMsg(err)}`, "error");
1678
+ }
1679
+ return;
1680
+ }
1681
+ if (taskPrompt) {
1682
+ await submitTaskPrompt(raw);
1683
+ return;
1684
+ }
1685
+ const parsed = parseInput(raw, mode === "cli");
1686
+ switch (parsed.kind) {
1687
+ case "empty":
1688
+ return;
1689
+ case "command":
1690
+ await runCommand(parsed.name, parsed.rest);
1691
+ return;
1692
+ case "prompt": {
1693
+ const target = focusedSessionId ?? ownSessionId;
1694
+ if (!target) return note("no active session yet.", "error");
1695
+ try {
1696
+ await client.sendToChatSession(target, parsed.text);
1697
+ } catch (err) {
1698
+ note(`send failed: ${errMsg(err)}`, "error");
1699
+ }
1700
+ return;
1701
+ }
1702
+ case "shell": {
1703
+ if (!parsed.text) return;
1704
+ note(`$ ${parsed.text}`, "shell");
1705
+ try {
1706
+ await client.runTerminalCommand(projectId, {
1707
+ workingDir: "",
1708
+ input: parsed.text,
1709
+ columns: shellColumns
1710
+ });
1711
+ } catch (err) {
1712
+ note(`shell failed: ${errMsg(err)}`, "error");
1713
+ }
1714
+ return;
1715
+ }
1716
+ case "tools": {
1717
+ const target = focusedSessionId ?? ownSessionId;
1718
+ if (!target) return note("no active session yet.", "error");
1719
+ try {
1720
+ const res = await client.listSessionTools(target);
1721
+ note(`tools (${res.tools.length}): ${res.tools.map((t) => t.name).join(", ")}`, "tool");
1722
+ } catch (err) {
1723
+ note(`list tools failed: ${errMsg(err)}`, "error");
1724
+ }
1725
+ return;
1726
+ }
1727
+ case "tool": {
1728
+ const target = focusedSessionId ?? ownSessionId;
1729
+ if (!target) return note("no active session yet.", "error");
1730
+ let args = {};
1731
+ if (parsed.argsJson) {
1732
+ try {
1733
+ args = JSON.parse(parsed.argsJson);
1734
+ } catch {
1735
+ return note(`invalid JSON args for @tool ${parsed.name}`, "error");
1736
+ }
1737
+ }
1738
+ note(`@tool ${parsed.name} ${parsed.argsJson}`.trim(), "tool");
1739
+ try {
1740
+ const res = await client.invokeSessionTool(target, parsed.name, args);
1741
+ note(res.text || "(no output)", "tool");
1742
+ } catch (err) {
1743
+ note(`tool failed: ${errMsg(err)}`, "error");
1744
+ }
1745
+ return;
1746
+ }
1747
+ }
1748
+ },
1749
+ [
1750
+ client,
1751
+ mode,
1752
+ projectId,
1753
+ shellColumns,
1754
+ focusedSessionId,
1755
+ ownSessionId,
1756
+ note,
1757
+ pendingInput,
1758
+ submitTaskPrompt,
1759
+ taskPrompt
1760
+ ]
1761
+ );
1762
+ const runCommand = useCallback(
1763
+ async (name, rest) => {
1764
+ switch (name) {
1765
+ case "help":
1766
+ case "?":
1767
+ for (const line of HELP) note(line);
1768
+ return;
1769
+ case "project":
1770
+ return setOverlay("project");
1771
+ case "gezel":
1772
+ return setOverlay("gezel");
1773
+ case "model": {
1774
+ if (!activeGezelId || !activeGezel) return note("no active gezel yet.", "error");
1775
+ if (activeGezel.fixedFunction) {
1776
+ return note("this gezel runs a fixed tool and does not use a chat model.", "error");
1777
+ }
1778
+ if (modelChoicesLoading) return note("model choices are already loading.");
1779
+ setModelChoicesLoading(true);
1780
+ note("loading available engines and models\u2026");
1781
+ try {
1782
+ const choices = await loadModelChoices(client, config ?? await client.getConfig());
1783
+ if (choices.length === 0) {
1784
+ return note("no engines with available chat models were found.", "error");
1785
+ }
1786
+ setModelChoices(choices);
1787
+ setOverlay("model");
1788
+ } catch (err) {
1789
+ note(`could not load models: ${errMsg(err)}`, "error");
1790
+ } finally {
1791
+ setModelChoicesLoading(false);
1792
+ }
1793
+ return;
1794
+ }
1795
+ case "thread":
1796
+ await openThreadPicker();
1797
+ return;
1798
+ case "task":
1799
+ setManagedTaskRef(null);
1800
+ return setOverlay("task");
1801
+ case "continue": {
1802
+ try {
1803
+ const result = await client.continueProject(projectId);
1804
+ await refreshTasks();
1805
+ const activeCount = result.activeTaskRefs.length;
1806
+ const scheduledCount = result.scheduledTaskRefs.length;
1807
+ const heldScheduledCount = result.heldScheduledTaskRefs.length;
1808
+ const spawnedCount = result.spawnedTaskRefs.length;
1809
+ const deferredCount = result.deferredNightShiftTaskRefs.length;
1810
+ const parts = [];
1811
+ if (scheduledCount > 0) {
1812
+ parts.push(
1813
+ `processed ${scheduledCount} due schedule${scheduledCount === 1 ? "" : "s"}${spawnedCount > 0 ? ` and spawned ${spawnedCount} task${spawnedCount === 1 ? "" : "s"}` : ""}`
1814
+ );
1815
+ }
1816
+ if (activeCount > 0) {
1817
+ parts.push(`reconciled ${activeCount} active task${activeCount === 1 ? "" : "s"}`);
1818
+ }
1819
+ if (heldScheduledCount > 0) {
1820
+ parts.push(
1821
+ `held ${heldScheduledCount} due schedule${heldScheduledCount === 1 ? "" : "s"}`
1822
+ );
1823
+ }
1824
+ if (deferredCount > 0) {
1825
+ parts.push(
1826
+ `left ${deferredCount} Night Shift task${deferredCount === 1 ? "" : "s"} queued for the shift`
1827
+ );
1828
+ }
1829
+ if (parts.length === 0) {
1830
+ if (result.projectStatus !== "active") {
1831
+ note(`${projectName} is ${result.projectStatus}; no project work was started.`);
1832
+ } else {
1833
+ note(`no due schedules or gezel-owned active tasks found in ${projectName}.`);
1834
+ }
1835
+ } else {
1836
+ note(`continue: ${parts.join("; ")}.`);
1837
+ }
1838
+ if (result.holdReason) note(projectContinueHoldMessage(result.holdReason));
1839
+ } catch (err) {
1840
+ note(`could not continue ${projectName}: ${errMsg(err)}`, "error");
1841
+ }
1842
+ return;
1843
+ }
1844
+ case "start": {
1845
+ let available = craftbooks;
1846
+ if (available.length === 0) {
1847
+ try {
1848
+ available = await refreshCraftbooks();
1849
+ } catch (err) {
1850
+ return note(`could not load craftbooks: ${errMsg(err)}`, "error");
1851
+ }
1852
+ }
1853
+ if (available.length === 0) {
1854
+ return note("no craftbooks are available for this project.", "error");
1855
+ }
1856
+ if (!rest.trim()) {
1857
+ setStartCategoryId(null);
1858
+ return setOverlay("start-category");
1859
+ }
1860
+ const book = findCraftbook(available, rest);
1861
+ if (!book) {
1862
+ return note(`craftbook not found: ${rest.trim()} (try /start)`, "error");
1863
+ }
1864
+ await startCraftbook(book);
1865
+ return;
1866
+ }
1867
+ case "nightshift": {
1868
+ const subcommand = rest.trim().toLowerCase();
1869
+ if (!["start", "stop", "list"].includes(subcommand)) {
1870
+ return note("usage: /nightshift start|stop|list", "error");
1871
+ }
1872
+ try {
1873
+ if (subcommand === "start") {
1874
+ const state2 = await client.setNightShiftManual("start");
1875
+ if (state2.active) {
1876
+ note(`night shift started${state2.source ? ` (${state2.source})` : ""}.`);
1877
+ } else {
1878
+ note(
1879
+ "night shift stayed off \u2014 there is no pending night-shift work, or Night Shift is disabled."
1880
+ );
1881
+ }
1882
+ return;
1883
+ }
1884
+ if (subcommand === "stop") {
1885
+ await client.setNightShiftManual("stop");
1886
+ note("night shift stopped; work already in flight may finish.");
1887
+ return;
1888
+ }
1889
+ const [state, work] = await Promise.all([
1890
+ client.getNightShiftStatus(),
1891
+ client.getNightShiftTasks()
1892
+ ]);
1893
+ note(formatNightShiftList(state, work));
1894
+ } catch (err) {
1895
+ note(`night shift command failed: ${errMsg(err)}`, "error");
1896
+ }
1897
+ return;
1898
+ }
1899
+ case "focus":
1900
+ return setOverlay("focus");
1901
+ case "cli":
1902
+ setMode("cli");
1903
+ return note("CLI mode \u2014 bare input runs as a shell command. /chat to exit.");
1904
+ case "chat":
1905
+ setMode("chat");
1906
+ return note("chat mode \u2014 bare input is a prompt to your gezel.");
1907
+ case "clear":
1908
+ setTurns(/* @__PURE__ */ new Map());
1909
+ setPendingInput(null);
1910
+ return setRows([]);
1911
+ case "quit":
1912
+ case "exit":
1913
+ exit();
1914
+ return;
1915
+ default:
1916
+ return note(`unknown command: /${name} (try /help)`, "error");
1917
+ }
1918
+ },
1919
+ [
1920
+ activeGezel,
1921
+ activeGezelId,
1922
+ client,
1923
+ config,
1924
+ craftbooks,
1925
+ modelChoicesLoading,
1926
+ note,
1927
+ exit,
1928
+ openThreadPicker,
1929
+ projectId,
1930
+ projectName,
1931
+ refreshCraftbooks,
1932
+ refreshTasks,
1933
+ startCraftbook
1934
+ ]
1935
+ );
1936
+ const applyModelChoice = useCallback(
1937
+ async (value2) => {
1938
+ setOverlay(null);
1939
+ if (!activeGezelId || !activeGezel || !config) return;
1940
+ const choice = modelChoices.find((item) => item.value === value2);
1941
+ const nextProvider = choice?.provider ?? null;
1942
+ const nextModel = choice?.model.id;
1943
+ const providerChanged = (activeGezel.provider ?? null) !== nextProvider;
1944
+ try {
1945
+ const updated = await client.updateGezelSettings(activeGezelId, {
1946
+ provider: nextProvider,
1947
+ model: nextModel ?? null,
1948
+ ...providerChanged || !nextModel ? { reasoningEffort: null } : {}
1949
+ });
1950
+ setGezels(
1951
+ (current) => current.map((gezel) => gezel.id === activeGezelId ? updated : gezel)
1952
+ );
1953
+ const started = await ensureSession(activeGezelId, projectId);
1954
+ const sessionNote = started ? "; started a new chat." : ".";
1955
+ if (choice) note(`model \u2192 ${choice.label}${sessionNote}`);
1956
+ else {
1957
+ const defaultModel = config.defaultModel?.[config.provider];
1958
+ const identity = defaultModel ? `${modelProviderLabel(config.provider)} \xB7 ${defaultModel}` : modelProviderLabel(config.provider);
1959
+ note(`model \u2192 default (${identity})${sessionNote}`);
1960
+ }
1961
+ } catch (err) {
1962
+ note(`could not switch model: ${errMsg(err)}`, "error");
1963
+ }
1964
+ },
1965
+ [activeGezel, activeGezelId, client, config, ensureSession, modelChoices, note, projectId]
1966
+ );
1967
+ const onSubmit = useCallback(
1968
+ (raw) => {
1969
+ setValue("");
1970
+ const trimmed = raw.trim();
1971
+ if (trimmed && !pendingInput && !taskPrompt) {
1972
+ setHistory((h) => h[h.length - 1] === trimmed ? h : [...h, trimmed].slice(-100));
1973
+ }
1974
+ void runInput(raw);
1975
+ },
1976
+ [runInput, pendingInput, taskPrompt]
1977
+ );
1978
+ const cancelActiveRef = useRef2(cancelActive);
1979
+ cancelActiveRef.current = cancelActive;
1980
+ useInput4(
1981
+ (input, key) => {
1982
+ if (key.ctrl && input === "c") {
1983
+ if (turns.size > 0 || activeRuns.size > 0) {
1984
+ void cancelActiveRef.current().then((did) => did && note("interrupted."));
1985
+ return;
1986
+ }
1987
+ if (value) return setValue("");
1988
+ if (exitArmed) return exit();
1989
+ setExitArmed(true);
1990
+ note("press Ctrl+C again to exit.");
1991
+ setTimeout(() => setExitArmed(false), 1500);
1992
+ return;
1993
+ }
1994
+ if (key.escape) {
1995
+ if (turns.size > 0 || activeRuns.size > 0) {
1996
+ void cancelActiveRef.current().then((did) => did && note("interrupted."));
1997
+ } else if (pendingInput) {
1998
+ setPendingInput(null);
1999
+ } else if (taskPrompt) {
2000
+ setTaskPrompt(null);
2001
+ note("task edit canceled.");
2002
+ } else if (ownSessionId) {
2003
+ setFocusedSessionId(ownSessionId);
2004
+ }
2005
+ }
2006
+ },
2007
+ {
2008
+ isActive: overlay === null && (!pendingQuestion || pendingInput !== null || taskPrompt !== null)
2009
+ }
2010
+ );
2011
+ if (status) {
2012
+ return /* @__PURE__ */ jsx6(Box6, { flexDirection: "column", padding: 1, children: /* @__PURE__ */ jsx6(Text6, { color: status.startsWith("Failed") ? "red" : "cyan", children: status }) });
2013
+ }
2014
+ return /* @__PURE__ */ jsxs6(Box6, { flexDirection: "column", padding: 1, children: [
2015
+ /* @__PURE__ */ jsx6(
2016
+ ChatFeed,
2017
+ {
2018
+ rows,
2019
+ gezels,
2020
+ boring,
2021
+ focusedSessionId: focusedSessionId ?? void 0,
2022
+ visible: visibleRows
2023
+ }
2024
+ ),
2025
+ overlay === "project" ? /* @__PURE__ */ jsx6(
2026
+ Picker,
2027
+ {
2028
+ title: "Switch project",
2029
+ items: projects.map((p) => ({ label: p.name, value: p.id, hint: p.workingDir })),
2030
+ onCancel: () => setOverlay(null),
2031
+ onSelect: (id) => {
2032
+ setOverlay(null);
2033
+ const p = projects.find((x) => x.id === id);
2034
+ if (!p || id === projectId) return;
2035
+ setProjectId(id);
2036
+ setProjectName(p.name);
2037
+ setRows([]);
2038
+ setTurns(/* @__PURE__ */ new Map());
2039
+ setActiveRuns(/* @__PURE__ */ new Set());
2040
+ setPendingInput(null);
2041
+ setPendingQuestions([]);
2042
+ setThreads([]);
2043
+ setActiveThreadTitle(null);
2044
+ setTasks([]);
2045
+ setCraftbooks([]);
2046
+ setCraftbookProjectType(null);
2047
+ setSuggestedCraftbookIds(/* @__PURE__ */ new Set());
2048
+ setCraftbooksNeedingSetup(/* @__PURE__ */ new Set());
2049
+ setStartCategoryId(null);
2050
+ setManagedTaskRef(null);
2051
+ setTaskPrompt(null);
2052
+ if (activeGezelId) void ensureSession(activeGezelId, id);
2053
+ }
2054
+ }
2055
+ ) : null,
2056
+ overlay === "gezel" ? /* @__PURE__ */ jsx6(
2057
+ Picker,
2058
+ {
2059
+ title: "Switch gezel",
2060
+ items: gezels.map((g) => ({
2061
+ label: boring ? g.roleBasedName ?? g.role ?? g.id : g.name,
2062
+ value: g.id,
2063
+ hint: g.role
2064
+ })),
2065
+ onCancel: () => setOverlay(null),
2066
+ onSelect: (id) => {
2067
+ setOverlay(null);
2068
+ if (id === activeGezelId) return;
2069
+ setActiveGezelId(id);
2070
+ setThreads([]);
2071
+ setActiveThreadTitle(null);
2072
+ void ensureSession(id, projectId);
2073
+ }
2074
+ }
2075
+ ) : null,
2076
+ overlay === "model" ? /* @__PURE__ */ jsx6(
2077
+ Picker,
2078
+ {
2079
+ title: "Choose engine + model",
2080
+ items: [
2081
+ {
2082
+ label: "Use default",
2083
+ value: "__default__",
2084
+ hint: `${modelProviderLabel(config?.provider ?? "llama-cpp")}${config?.defaultModel?.[config.provider] ? ` \xB7 ${config.defaultModel[config.provider]}` : ""}`
2085
+ },
2086
+ ...modelChoices.map((choice) => ({
2087
+ label: choice.label,
2088
+ value: choice.value,
2089
+ hint: activeGezel?.provider === choice.provider && activeGezel.model === choice.model.id ? "current" : choice.model.supportsReasoning ? "reasoning" : void 0
2090
+ }))
2091
+ ],
2092
+ initialValue: activeGezel?.provider && activeGezel.model ? `${activeGezel.provider}:${activeGezel.model}` : "__default__",
2093
+ windowSize: modelPickerWindowSize,
2094
+ onCancel: () => setOverlay(null),
2095
+ onSelect: (value2) => void applyModelChoice(value2)
2096
+ }
2097
+ ) : null,
2098
+ overlay === "start-category" ? /* @__PURE__ */ jsx6(
2099
+ Picker,
2100
+ {
2101
+ title: "Choose a craftbook category",
2102
+ items: startCategories.map((category) => ({
2103
+ label: category.label,
2104
+ value: category.id,
2105
+ hint: category.hint
2106
+ })),
2107
+ windowSize: modelPickerWindowSize,
2108
+ onCancel: () => setOverlay(null),
2109
+ onSelect: (id) => {
2110
+ setStartCategoryId(id);
2111
+ setOverlay("start-craftbook");
2112
+ }
2113
+ }
2114
+ ) : null,
2115
+ overlay === "start-craftbook" ? /* @__PURE__ */ jsx6(
2116
+ Picker,
2117
+ {
2118
+ title: startCategory?.label ?? "Start a craftbook",
2119
+ items: startCategoryBooks.map((book) => ({
2120
+ label: book.name,
2121
+ value: book.id,
2122
+ hint: `${book.stepCount} ${book.stepCount === 1 ? "step" : "steps"} \xB7 ${book.source}${craftbooksNeedingSetup.has(book.id) ? " \xB7 needs setup" : ""}`
2123
+ })),
2124
+ windowSize: modelPickerWindowSize,
2125
+ onCancel: () => setOverlay("start-category"),
2126
+ onSelect: (id) => {
2127
+ const book = startCategoryBooks.find((item) => item.id === id);
2128
+ if (book) void startCraftbook(book);
2129
+ }
2130
+ }
2131
+ ) : null,
2132
+ overlay === "thread" ? /* @__PURE__ */ jsx6(
2133
+ Picker,
2134
+ {
2135
+ title: `Threads with ${gezelLine}`,
2136
+ items: [
2137
+ { label: "Start new thread\u2026", value: "__new__" },
2138
+ ...threads.map((thread) => ({
2139
+ label: displayThreadTitle(thread.title),
2140
+ value: thread.id,
2141
+ hint: threadHint(thread, thread.id === ownSessionId)
2142
+ }))
2143
+ ],
2144
+ initialValue: ownSessionId ?? "__new__",
2145
+ windowSize: Math.max(4, Math.min(10, termRows - 12)),
2146
+ onCancel: () => setOverlay(null),
2147
+ onSelect: (sessionId) => {
2148
+ if (sessionId === "__new__") void startNewThread();
2149
+ else void switchThread(sessionId);
2150
+ }
2151
+ }
2152
+ ) : null,
2153
+ overlay === "task" ? /* @__PURE__ */ jsx6(
2154
+ Picker,
2155
+ {
2156
+ title: `Tasks \xB7 ${tasks.filter((task) => task.status === "active").length} active`,
2157
+ items: [
2158
+ { label: "Create task\u2026", value: "__create__", hint: "new active task" },
2159
+ ...tasks.map((task) => ({
2160
+ label: `${task.ref} ${task.title}`,
2161
+ value: task.ref,
2162
+ hint: `${task.status} \xB7 ${taskAssigneeLabel(task, gezels, boring)}`
2163
+ }))
2164
+ ],
2165
+ windowSize: Math.max(4, Math.min(10, termRows - 12)),
2166
+ onCancel: () => setOverlay(null),
2167
+ onSelect: (ref) => {
2168
+ if (ref === "__create__") {
2169
+ setOverlay(null);
2170
+ setTaskPrompt({ kind: "create", promptLine: "Task title" });
2171
+ return;
2172
+ }
2173
+ setManagedTaskRef(ref);
2174
+ setOverlay("task-actions");
2175
+ }
2176
+ }
2177
+ ) : null,
2178
+ overlay === "task-actions" && managedTask ? /* @__PURE__ */ jsx6(
2179
+ Picker,
2180
+ {
2181
+ title: `${managedTask.ref} \xB7 ${managedTask.status}`,
2182
+ items: [
2183
+ { label: "Show details", value: "show", hint: managedTask.title },
2184
+ { label: "Edit title\u2026", value: "title" },
2185
+ { label: "Edit description\u2026", value: "description" },
2186
+ {
2187
+ label: "Change assignee\u2026",
2188
+ value: "assignee",
2189
+ hint: taskAssigneeLabel(managedTask, gezels, boring)
2190
+ },
2191
+ { label: "Change status\u2026", value: "status", hint: managedTask.status }
2192
+ ],
2193
+ onCancel: () => setOverlay("task"),
2194
+ onSelect: (action) => {
2195
+ if (action === "show") {
2196
+ setOverlay(null);
2197
+ note(formatTaskDetails(managedTask, gezels, boring));
2198
+ } else if (action === "title" || action === "description") {
2199
+ setOverlay(null);
2200
+ setTaskPrompt({
2201
+ kind: action,
2202
+ taskRef: managedTask.ref,
2203
+ promptLine: action === "title" ? "New task title" : "New task description"
2204
+ });
2205
+ } else if (action === "assignee") {
2206
+ setOverlay("task-assignee");
2207
+ } else if (action === "status") {
2208
+ setOverlay("task-status");
2209
+ }
2210
+ }
2211
+ }
2212
+ ) : null,
2213
+ overlay === "task-status" && managedTask ? /* @__PURE__ */ jsx6(
2214
+ Picker,
2215
+ {
2216
+ title: `Set ${managedTask.ref} status`,
2217
+ items: taskStatusChoices(managedTask),
2218
+ onCancel: () => setOverlay("task-actions"),
2219
+ onSelect: (status2) => void applyTaskStatus(status2)
2220
+ }
2221
+ ) : null,
2222
+ overlay === "task-assignee" && managedTask ? /* @__PURE__ */ jsx6(
2223
+ Picker,
2224
+ {
2225
+ title: `Assign ${managedTask.ref}`,
2226
+ items: [
2227
+ {
2228
+ label: "You",
2229
+ value: "__user__",
2230
+ hint: managedTask.assignee.kind === "user" ? "current" : void 0
2231
+ },
2232
+ ...gezels.map((gezel) => ({
2233
+ label: boring ? gezel.roleBasedName ?? gezel.role ?? gezel.id : gezel.name,
2234
+ value: gezel.id,
2235
+ hint: managedTask.assignee.kind === "gezel" && managedTask.assignee.gezelId === gezel.id ? "current" : gezel.role
2236
+ }))
2237
+ ],
2238
+ onCancel: () => setOverlay("task-actions"),
2239
+ onSelect: (assignee) => void applyTaskAssignee(assignee)
2240
+ }
2241
+ ) : null,
2242
+ overlay === "focus" ? /* @__PURE__ */ jsx6(
2243
+ Picker,
2244
+ {
2245
+ title: "Send into which chat?",
2246
+ items: focusItems,
2247
+ onCancel: () => setOverlay(null),
2248
+ onSelect: (sid) => {
2249
+ setOverlay(null);
2250
+ setFocusedSessionId(sid);
2251
+ }
2252
+ }
2253
+ ) : null,
2254
+ overlay === null && pendingQuestion ? /* @__PURE__ */ jsx6(
2255
+ QuestionPrompt,
2256
+ {
2257
+ client,
2258
+ question: pendingQuestion,
2259
+ askerLabel: gezelLabel(pendingQuestion.gezelId, gezels, boring),
2260
+ active: pendingInput === null,
2261
+ onAnswered: (question) => {
2262
+ setPendingQuestions((questions) => updatePendingQuestion(questions, question));
2263
+ setFocusedSessionId(question.sessionId);
2264
+ }
2265
+ },
2266
+ pendingQuestion.id
2267
+ ) : null,
2268
+ /* @__PURE__ */ jsx6(
2269
+ PromptLine,
2270
+ {
2271
+ projectName,
2272
+ gezelLabel: gezelLine,
2273
+ threadTitle: activeThreadTitle ?? void 0,
2274
+ mode,
2275
+ provider: effectiveProvider,
2276
+ model: effectiveModel,
2277
+ accessMode,
2278
+ busy,
2279
+ statusLabel,
2280
+ value,
2281
+ active: overlay === null && (!pendingQuestion || pendingInput !== null || taskPrompt !== null),
2282
+ history,
2283
+ craftbooks,
2284
+ pendingPrompt: pendingInput?.promptLine ?? taskPrompt?.promptLine,
2285
+ pendingMode: pendingInput?.mode ?? (taskPrompt ? "text" : void 0),
2286
+ onChange: setValue,
2287
+ onSubmit
2288
+ }
2289
+ )
2290
+ ] });
2291
+ }
2292
+ function errMsg(err) {
2293
+ return err instanceof Error ? err.message : String(err);
2294
+ }
2295
+ function displayThreadTitle(title) {
2296
+ return title === "New session" ? "New thread" : title;
2297
+ }
2298
+ function threadHint(thread, current) {
2299
+ const engine = thread.model ? `${thread.providerName} \xB7 ${thread.model}` : thread.providerName;
2300
+ return [current ? "current" : null, formatRelativeTime(thread.lastActivityAt), engine].filter(Boolean).join(" \xB7 ");
2301
+ }
2302
+ function formatRelativeTime(iso) {
2303
+ const then = new Date(iso).getTime();
2304
+ if (!Number.isFinite(then)) return iso;
2305
+ const minutes = Math.floor(Math.max(0, Date.now() - then) / 6e4);
2306
+ if (minutes < 1) return "just now";
2307
+ if (minutes < 60) return `${minutes}m ago`;
2308
+ const hours = Math.floor(minutes / 60);
2309
+ if (hours < 24) return `${hours}h ago`;
2310
+ return `${Math.floor(hours / 24)}d ago`;
2311
+ }
2312
+ function projectContinueHoldMessage(reason) {
2313
+ switch (reason) {
2314
+ case "engagement-off":
2315
+ return "project work is held because AI engagement is Off.";
2316
+ case "engagement-paused":
2317
+ return "project work is held because AI engagement is Reactive.";
2318
+ case "provider-busy":
2319
+ return "task work is queued until an engine slot is free.";
2320
+ }
2321
+ }
2322
+ function formatNightShiftList(state, work) {
2323
+ const lines = [
2324
+ `Night Shift: ${state.active ? `active${state.source ? ` (${state.source})` : ""}` : "off"}`
2325
+ ];
2326
+ if (work.background.length > 0) {
2327
+ lines.push("Background:");
2328
+ for (const item of work.background) {
2329
+ lines.push(` - ${item.title}${item.detail ? ` \u2014 ${item.detail}` : ""}`);
2330
+ }
2331
+ }
2332
+ if (work.active.length > 0) {
2333
+ lines.push("Working on:");
2334
+ for (const task of work.active) lines.push(` - ${formatNightShiftTask(task)}`);
2335
+ }
2336
+ if (work.upcoming.length > 0) {
2337
+ lines.push(state.active ? "Up next:" : "Queued for the next shift:");
2338
+ for (const task of work.upcoming) lines.push(` - ${formatNightShiftTask(task)}`);
2339
+ }
2340
+ if (work.background.length + work.active.length + work.upcoming.length === 0) {
2341
+ lines.push("No work is running or queued.");
2342
+ }
2343
+ return lines.join("\n");
2344
+ }
2345
+ function formatNightShiftTask(task) {
2346
+ return `${task.ref} ${task.title} \u2014 ${task.projectName}${task.stepName ? ` \xB7 ${task.stepName}` : ""}`;
2347
+ }
2348
+ var TASK_STATUS_ORDER = {
2349
+ active: 0,
2350
+ draft: 1,
2351
+ paused: 2,
2352
+ complete: 3,
2353
+ canceled: 4
2354
+ };
2355
+ function sortTasks(tasks) {
2356
+ return [...tasks].sort((left, right) => {
2357
+ const byStatus = TASK_STATUS_ORDER[left.status] - TASK_STATUS_ORDER[right.status];
2358
+ if (byStatus !== 0) return byStatus;
2359
+ return right.updatedAt.localeCompare(left.updatedAt);
2360
+ });
2361
+ }
2362
+ function taskAssigneeLabel(task, gezels, boring) {
2363
+ if (task.assignee.kind === "user") return "you";
2364
+ const gezelId = task.assignee.gezelId;
2365
+ const gezel = gezels.find((item) => item.id === gezelId);
2366
+ if (!gezel) return gezelId;
2367
+ return boring ? gezel.roleBasedName ?? gezel.role ?? gezel.id : gezel.name;
2368
+ }
2369
+ function taskStatusChoices(task) {
2370
+ const statuses = task.status === "draft" ? ["active", "canceled"] : task.origin?.kind === "system-job" ? ["active", "paused"] : ["active", "paused", "complete", "canceled"];
2371
+ const labels = {
2372
+ draft: "Move to draft",
2373
+ active: task.status === "draft" ? "Activate" : "Resume / reopen",
2374
+ paused: "Pause",
2375
+ complete: "Mark complete",
2376
+ canceled: "Cancel"
2377
+ };
2378
+ return statuses.filter((status) => status !== task.status).map((status) => ({ label: labels[status], value: status }));
2379
+ }
2380
+ function formatTaskDetails(task, gezels, boring) {
2381
+ const steps = task.craftbook.steps.map((step) => {
2382
+ const marker = step.completedAt ? "\u2713" : step.id === task.activeStepId ? "\u2192" : "\xB7";
2383
+ return ` ${marker} ${step.name}`;
2384
+ });
2385
+ return [
2386
+ `${task.ref} [${task.status}] ${task.title}`,
2387
+ `assignee: ${taskAssigneeLabel(task, gezels, boring)}`,
2388
+ ...task.description ? [`description: ${task.description}`] : [],
2389
+ ...steps.length > 0 ? ["steps:", ...steps] : []
2390
+ ].join("\n");
2391
+ }
2392
+
2393
+ // src/tui/components/BootstrapGate.tsx
2394
+ import { Box as Box7, Text as Text7, useApp as useApp2, useInput as useInput5 } from "ink";
2395
+ import { useCallback as useCallback2, useEffect as useEffect4, useState as useState5 } from "react";
2396
+
2397
+ // src/tui/bootstrap.ts
2398
+ import {
2399
+ computeModelFit,
2400
+ isMoEFromTags,
2401
+ isRecommendedModel,
2402
+ mediaModelFits,
2403
+ pickRecommendedModel
2404
+ } from "@bendyline/gezel";
2405
+ var CHAT_MEMORY_OVERHEAD = {
2406
+ "llama-cpp": 1.2,
2407
+ mlx: 1.3
2408
+ };
2409
+ var NATIVE_TOOLKIT = [
2410
+ "uv",
2411
+ "sd-server",
2412
+ "whisper-server",
2413
+ "llama-server"
2414
+ ];
2415
+ function rankChatModels(items, device, provider) {
2416
+ const candidates = [];
2417
+ for (const item of items) {
2418
+ if (item.manifest.kind !== "chat-model") continue;
2419
+ const manifest = item.manifest;
2420
+ if (manifest.licenseClass !== "open") continue;
2421
+ const source = provider === "mlx" ? manifest.mlx : manifest.llamaCpp;
2422
+ if (!source || provider === "mlx" && manifest.mlx?.disabledReason) continue;
2423
+ const residentBytes = source.residentBytes ?? Math.round(source.approxSizeBytes * CHAT_MEMORY_OVERHEAD[provider]);
2424
+ const fit = computeModelFit({
2425
+ residentBytes,
2426
+ isMoE: isMoEFromTags(manifest.tags),
2427
+ usableBytes: device.usableBytes,
2428
+ totalRamBytes: device.totalRamBytes,
2429
+ gpuVramBytes: device.gpuVramBytes,
2430
+ ...device.budgetBytes !== void 0 ? { admissibleBytes: device.budgetBytes } : {}
2431
+ }).tier;
2432
+ candidates.push({
2433
+ id: manifest.id,
2434
+ name: manifest.name,
2435
+ provider,
2436
+ approxSizeBytes: source.approxSizeBytes,
2437
+ residentBytes,
2438
+ // Effective score: a model the shared gate rejects (restricted license,
2439
+ // no tool support) sorts as unscored rather than leading the list.
2440
+ recoScore: isRecommendedModel(manifest) ? manifest.recoScore ?? 0 : 0,
2441
+ fit
2442
+ });
2443
+ }
2444
+ if (candidates.length === 0) return [];
2445
+ const picked = pickRecommendedModel(
2446
+ candidates.map((model) => ({
2447
+ id: model.id,
2448
+ ...model.recoScore > 0 ? { recoScore: model.recoScore } : {},
2449
+ licenseClass: "open",
2450
+ tags: items.find((item) => item.manifest.kind === "chat-model" && item.manifest.id === model.id)?.manifest?.tags ?? [],
2451
+ residentBytes: model.residentBytes
2452
+ })),
2453
+ device
2454
+ );
2455
+ const comfortable = candidates.filter(
2456
+ (model) => model.fit === "fits" || model.fit === "fits-offload"
2457
+ );
2458
+ const pool = comfortable.length > 0 ? comfortable : candidates;
2459
+ pool.sort(
2460
+ (a, b) => b.recoScore - a.recoScore || fitOrder(a.fit) - fitOrder(b.fit) || b.residentBytes - a.residentBytes || a.name.localeCompare(b.name)
2461
+ );
2462
+ if (!picked) return pool;
2463
+ const bestIndex = pool.findIndex((model) => model.id === picked.id);
2464
+ if (bestIndex < 0) {
2465
+ const best = candidates.find((model) => model.id === picked.id);
2466
+ if (best) pool.unshift(best);
2467
+ return pool;
2468
+ }
2469
+ if (bestIndex > 0) {
2470
+ const [best] = pool.splice(bestIndex, 1);
2471
+ if (best) pool.unshift(best);
2472
+ }
2473
+ return pool;
2474
+ }
2475
+ function pickAccessoryModels(input, device) {
2476
+ const output = [];
2477
+ const image = pickCatalogMedia(input.imageItems, device, "image");
2478
+ if (image && !input.installed.image?.has(image.id)) {
2479
+ output.push({
2480
+ kind: "image",
2481
+ id: image.id,
2482
+ name: image.name,
2483
+ approxSizeBytes: image.approxSizeBytes + (image.auxiliaryFiles ?? []).reduce((sum, file) => sum + (file.sizeBytes ?? 0), 0),
2484
+ requiredEngine: "sd-server"
2485
+ });
2486
+ }
2487
+ const recognition = pickScoredOpen(input.recognition, false);
2488
+ if (recognition && !input.installed.recognition?.has(recognition.id)) {
2489
+ output.push({
2490
+ kind: "recognition",
2491
+ id: recognition.id,
2492
+ name: recognition.name,
2493
+ approxSizeBytes: recognition.approxSizeBytes,
2494
+ requiredEngine: "llama-server"
2495
+ });
2496
+ }
2497
+ const stt = pickScoredOpen(input.audio.stt);
2498
+ if (stt && !input.installed.stt?.has(stt.id)) {
2499
+ output.push({
2500
+ kind: "stt",
2501
+ id: stt.id,
2502
+ name: stt.name,
2503
+ approxSizeBytes: stt.approxSizeBytes,
2504
+ requiredEngine: "whisper-server"
2505
+ });
2506
+ }
2507
+ const tts = pickScoredOpen(input.audio.tts);
2508
+ if (tts && !input.installed.tts?.has(tts.id)) {
2509
+ output.push({
2510
+ kind: "tts",
2511
+ id: tts.id,
2512
+ name: tts.name,
2513
+ approxSizeBytes: tts.approxSizeBytes
2514
+ });
2515
+ }
2516
+ const video = pickCatalogMedia(input.videoItems, device, "video");
2517
+ if (video && !input.installed.video?.has(video.id)) {
2518
+ output.push({
2519
+ kind: "video",
2520
+ id: video.id,
2521
+ name: video.name,
2522
+ approxSizeBytes: video.approxSizeBytes,
2523
+ requiredEngine: "uv"
2524
+ });
2525
+ }
2526
+ return output;
2527
+ }
2528
+ function formatDownloadSize(bytes) {
2529
+ if (bytes >= 1e9) return `${(bytes / 1e9).toFixed(1)} GB`;
2530
+ return `${Math.max(1, Math.round(bytes / 1e6))} MB`;
2531
+ }
2532
+ function fitOrder(fit) {
2533
+ switch (fit) {
2534
+ case "fits":
2535
+ return 0;
2536
+ case "fits-offload":
2537
+ return 1;
2538
+ case "tight":
2539
+ return 2;
2540
+ case "too-big":
2541
+ return 3;
2542
+ }
2543
+ }
2544
+ function pickCatalogMedia(items, device, kind) {
2545
+ const models = items.map((item) => item.manifest).filter((model) => {
2546
+ if (model.licenseClass !== "open" || !model.recoScore) return false;
2547
+ return mediaModelFits(
2548
+ device,
2549
+ kind === "image" ? { minRamGB: model.minRamGB } : { minVramGB: model.minVramGB }
2550
+ );
2551
+ });
2552
+ return pickScoredOpen(models);
2553
+ }
2554
+ function pickScoredOpen(models, requireLicense = true) {
2555
+ return [...models].filter(
2556
+ (model) => typeof model.recoScore === "number" && model.recoScore > 0 && (!requireLicense || model.licenseClass === "open")
2557
+ ).sort((a, b) => (b.recoScore ?? 0) - (a.recoScore ?? 0))[0] ?? null;
2558
+ }
2559
+
2560
+ // src/tui/components/BootstrapGate.tsx
2561
+ import { Fragment as Fragment4, jsx as jsx7, jsxs as jsxs7 } from "react/jsx-runtime";
2562
+ var MAX_ALTERNATIVE_MODELS = 6;
2563
+ function BootstrapGate(props) {
2564
+ const { client, children } = props;
2565
+ const { exit } = useApp2();
2566
+ const [screen, setScreen] = useState5({
2567
+ kind: "loading",
2568
+ message: "Checking this device\u2026"
2569
+ });
2570
+ useInput5(
2571
+ (input, key) => {
2572
+ if (key.ctrl && input.toLowerCase() === "c") exit();
2573
+ },
2574
+ // Once setup hands control to App, App owns Ctrl+C's interrupt/exit
2575
+ // contract. Leaving this handler active made the first Ctrl+C exit the
2576
+ // entire TUI before App could interrupt an in-flight turn or arm its
2577
+ // deliberate second-press exit.
2578
+ { isActive: screen.kind !== "ready" }
2579
+ );
2580
+ const prepareModels = useCallback2(
2581
+ async (context) => {
2582
+ setScreen({ kind: "loading", message: "Finding the best models for this device\u2026" });
2583
+ const installedChat = context.provider === "mlx" ? await client.listMlxModels() : await client.listLlamaCppModels();
2584
+ if (installedChat.models.length > 0) {
2585
+ setScreen({ kind: "ready" });
2586
+ return;
2587
+ }
2588
+ const [
2589
+ imageCatalog,
2590
+ videoCatalog,
2591
+ audioCatalog,
2592
+ recognitionCatalog,
2593
+ installedImage,
2594
+ installedVideo,
2595
+ installedStt,
2596
+ installedTts,
2597
+ installedRecognition
2598
+ ] = await Promise.all([
2599
+ client.listCatalogItems("image-model").catch(() => ({ items: [] })),
2600
+ client.listCatalogItems("video-model").catch(() => ({ items: [] })),
2601
+ client.listAudioCatalog().catch(() => ({ stt: [], tts: [] })),
2602
+ client.listRecognitionCatalog().catch(() => ({ models: [] })),
2603
+ client.listInstalledImageModels().catch(() => ({ models: [] })),
2604
+ client.listInstalledVideoModels().catch(() => ({ models: [] })),
2605
+ client.listInstalledSttModels().catch(() => ({ models: [] })),
2606
+ client.listInstalledTtsModels().catch(() => ({ models: [] })),
2607
+ client.listInstalledRecognitionModels().catch(() => ({ models: [] }))
2608
+ ]);
2609
+ const chatModels = rankChatModels(context.chatCatalog, context.device, context.provider);
2610
+ if (chatModels.length === 0) {
2611
+ setScreen({
2612
+ kind: "error",
2613
+ title: "No compatible local models found",
2614
+ message: "The catalog has no open chat model for this device and local engine. You can continue and configure a cloud or external provider."
2615
+ });
2616
+ return;
2617
+ }
2618
+ const accessories = pickAccessoryModels(
2619
+ {
2620
+ imageItems: imageCatalog.items,
2621
+ videoItems: videoCatalog.items,
2622
+ audio: audioCatalog,
2623
+ recognition: recognitionCatalog.models,
2624
+ installed: {
2625
+ image: idSet(installedImage.models),
2626
+ video: idSet(installedVideo.models),
2627
+ stt: idSet(installedStt.models),
2628
+ tts: idSet(installedTts.models),
2629
+ recognition: idSet(installedRecognition.models)
2630
+ }
2631
+ },
2632
+ context.device
2633
+ );
2634
+ setScreen({ kind: "model-choice", plan: { context, chatModels, accessories } });
2635
+ },
2636
+ [client]
2637
+ );
2638
+ const initialize = useCallback2(async () => {
2639
+ try {
2640
+ setScreen({ kind: "loading", message: "Checking this device\u2026" });
2641
+ const [memory, chatCatalog] = await Promise.all([
2642
+ client.getMemoryProfile(),
2643
+ client.listCatalogItems("chat-model")
2644
+ ]);
2645
+ const config = await settledFirstRunConfig(client);
2646
+ if (config.provider !== "llama-cpp" && config.provider !== "mlx") {
2647
+ setScreen({ kind: "ready" });
2648
+ return;
2649
+ }
2650
+ if (config.provider === "llama-cpp" && (config.llamaCppBaseUrl || config.llamaCppModelPath) || config.provider === "mlx" && (config.mlxBaseUrl || config.mlxModelPath)) {
2651
+ setScreen({ kind: "ready" });
2652
+ return;
2653
+ }
2654
+ const nativeStatus = await client.getNativeEngineStatus();
2655
+ if (!nativeStatus.platformKey) {
2656
+ setScreen({ kind: "ready" });
2657
+ return;
2658
+ }
2659
+ const context = {
2660
+ config,
2661
+ provider: config.provider,
2662
+ device: {
2663
+ platform: memory.platform,
2664
+ gpuVramBytes: memory.gpuVramBytes,
2665
+ ...memory.gpuMemoryKind ? { gpuMemoryKind: memory.gpuMemoryKind } : {},
2666
+ totalRamBytes: memory.totalRamBytes,
2667
+ usableBytes: memory.usableBytes,
2668
+ ...memory.budgetBytes !== void 0 ? { budgetBytes: memory.budgetBytes } : {}
2669
+ },
2670
+ chatCatalog: chatCatalog.items,
2671
+ nativeStatus
2672
+ };
2673
+ const missing = missingToolkit(nativeStatus);
2674
+ if (missing.length > 0) {
2675
+ setScreen({ kind: "native-choice", context, missing });
2676
+ } else {
2677
+ await prepareModels(context);
2678
+ }
2679
+ } catch (error) {
2680
+ setScreen({
2681
+ kind: "error",
2682
+ title: "Setup check failed",
2683
+ message: errorMessage(error),
2684
+ retry: () => void initialize()
2685
+ });
2686
+ }
2687
+ }, [client, prepareModels]);
2688
+ useEffect4(() => {
2689
+ void initialize();
2690
+ }, [initialize]);
2691
+ const installNative = useCallback2(
2692
+ async (context, missing) => {
2693
+ const retry = () => void installNative(context, missing);
2694
+ if (!context.nativeStatus.pinned) {
2695
+ setScreen({
2696
+ kind: "error",
2697
+ title: "Native downloads are unavailable",
2698
+ message: "This CLI build does not carry a verified native release pin. Install a published @bendyline/gezel-cli build or configure external engines."
2699
+ });
2700
+ return;
2701
+ }
2702
+ try {
2703
+ await installNativeToolkit(client, context.nativeStatus, missing, setScreen);
2704
+ const nativeStatus = await client.getNativeEngineStatus();
2705
+ await prepareModels({ ...context, nativeStatus });
2706
+ } catch (error) {
2707
+ setScreen({
2708
+ kind: "error",
2709
+ title: "Native toolkit install failed",
2710
+ message: errorMessage(error),
2711
+ retry
2712
+ });
2713
+ }
2714
+ },
2715
+ [client, prepareModels]
2716
+ );
2717
+ const installModels = useCallback2(
2718
+ async (plan, choice) => {
2719
+ if (choice.kind === "skip") {
2720
+ setScreen({ kind: "ready" });
2721
+ return;
2722
+ }
2723
+ const retry = () => void installModels(plan, choice);
2724
+ try {
2725
+ if (choice.kind === "bundle") {
2726
+ const missing = missingToolkit(await client.getNativeEngineStatus());
2727
+ if (missing.length > 0) {
2728
+ await installNativeToolkit(client, plan.context.nativeStatus, missing, setScreen);
2729
+ }
2730
+ }
2731
+ const jobs = [
2732
+ { label: choice.model.name, sizeBytes: choice.model.approxSizeBytes },
2733
+ ...choice.kind === "bundle" ? plan.accessories.map((model) => ({
2734
+ label: model.name,
2735
+ sizeBytes: model.approxSizeBytes
2736
+ })) : []
2737
+ ];
2738
+ let jobIndex = 0;
2739
+ await installChatModel(client, choice.model, (event) => {
2740
+ updateDownloadProgress(setScreen, jobs[jobIndex], jobIndex, jobs.length, event);
2741
+ });
2742
+ jobIndex += 1;
2743
+ const updated = await client.updateConfig({
2744
+ provider: choice.model.provider,
2745
+ defaultModel: {
2746
+ ...plan.context.config.defaultModel,
2747
+ [choice.model.provider]: choice.model.id
2748
+ },
2749
+ // The successful interactive install supersedes an earlier banner error.
2750
+ firstRunInstallError: null
2751
+ });
2752
+ plan.context.config = updated;
2753
+ if (choice.kind === "bundle") {
2754
+ for (const accessory of plan.accessories) {
2755
+ await installAccessory(client, accessory, (event) => {
2756
+ updateDownloadProgress(setScreen, jobs[jobIndex], jobIndex, jobs.length, event);
2757
+ });
2758
+ jobIndex += 1;
2759
+ }
2760
+ }
2761
+ setScreen({ kind: "ready" });
2762
+ } catch (error) {
2763
+ setScreen({
2764
+ kind: "error",
2765
+ title: "Model install failed",
2766
+ message: errorMessage(error),
2767
+ retry
2768
+ });
2769
+ }
2770
+ },
2771
+ [client]
2772
+ );
2773
+ if (screen.kind === "ready") return /* @__PURE__ */ jsx7(Fragment4, { children });
2774
+ if (screen.kind === "loading") {
2775
+ return /* @__PURE__ */ jsx7(BootstrapFrame, { title: "Preparing the workshop", children: /* @__PURE__ */ jsxs7(Text7, { color: "yellow", children: [
2776
+ "\u25CF ",
2777
+ screen.message
2778
+ ] }) });
2779
+ }
2780
+ if (screen.kind === "installing") {
2781
+ return /* @__PURE__ */ jsxs7(BootstrapFrame, { title: screen.progress.title, children: [
2782
+ /* @__PURE__ */ jsxs7(Text7, { children: [
2783
+ screen.progress.current,
2784
+ "/",
2785
+ screen.progress.total,
2786
+ " ",
2787
+ screen.progress.detail
2788
+ ] }),
2789
+ /* @__PURE__ */ jsx7(ProgressBar, { pct: screen.progress.pct }),
2790
+ /* @__PURE__ */ jsx7(Text7, { dimColor: true, children: screen.progress.pct == null ? "Working\u2026" : `${screen.progress.pct}%` })
2791
+ ] });
2792
+ }
2793
+ if (screen.kind === "native-choice") {
2794
+ const labels = screen.missing.map(nativeLabel).join(", ");
2795
+ return /* @__PURE__ */ jsxs7(BootstrapFrame, { title: "Local tools are not installed yet", children: [
2796
+ /* @__PURE__ */ jsxs7(Text7, { children: [
2797
+ "Gezel can install the verified native-v",
2798
+ screen.context.nativeStatus.release,
2799
+ " toolkit for this device."
2800
+ ] }),
2801
+ /* @__PURE__ */ jsxs7(Text7, { dimColor: true, children: [
2802
+ "Missing: ",
2803
+ labels
2804
+ ] }),
2805
+ /* @__PURE__ */ jsx7(
2806
+ BootstrapChoiceList,
2807
+ {
2808
+ options: [
2809
+ {
2810
+ label: "Install the native toolkit",
2811
+ hint: "recommended \xB7 engines for chat, images, speech, and local model helpers",
2812
+ value: "install"
2813
+ },
2814
+ { label: "Not now", hint: "continue to model choices", value: "skip" }
2815
+ ],
2816
+ onSelect: (value) => {
2817
+ if (value === "install") {
2818
+ void installNative(screen.context, screen.missing);
2819
+ } else {
2820
+ void prepareModels(screen.context);
2821
+ }
2822
+ }
2823
+ }
2824
+ )
2825
+ ] });
2826
+ }
2827
+ if (screen.kind === "model-choice") {
2828
+ const best = screen.plan.chatModels[0];
2829
+ const accessoryBytes = screen.plan.accessories.reduce(
2830
+ (sum, model) => sum + model.approxSizeBytes,
2831
+ 0
2832
+ );
2833
+ const options = [
2834
+ {
2835
+ label: `Recommended workshop set \u2014 ${best.name} + ${screen.plan.accessories.length} helpers`,
2836
+ hint: formatDownloadSize(best.approxSizeBytes + accessoryBytes),
2837
+ value: "bundle"
2838
+ },
2839
+ {
2840
+ label: `${best.name} only`,
2841
+ hint: `best chat model \xB7 ${formatDownloadSize(best.approxSizeBytes)}`,
2842
+ value: `chat:${best.id}`
2843
+ },
2844
+ ...screen.plan.chatModels.slice(1, MAX_ALTERNATIVE_MODELS + 1).map((model) => ({
2845
+ label: `${model.name} only`,
2846
+ hint: `${formatDownloadSize(model.approxSizeBytes)} \xB7 ${fitLabel(model.fit)}`,
2847
+ value: `chat:${model.id}`
2848
+ })),
2849
+ { label: "Not now", hint: "open the TUI without a local model", value: "skip" }
2850
+ ];
2851
+ return /* @__PURE__ */ jsxs7(BootstrapFrame, { title: "No local chat model is installed", children: [
2852
+ /* @__PURE__ */ jsx7(Text7, { children: "Pick a setup for this device. Downloads stay under your Gezel home folder." }),
2853
+ /* @__PURE__ */ jsx7(
2854
+ BootstrapChoiceList,
2855
+ {
2856
+ options,
2857
+ onSelect: (value) => {
2858
+ if (value === "skip") {
2859
+ void installModels(screen.plan, { kind: "skip" });
2860
+ } else if (value === "bundle") {
2861
+ void installModels(screen.plan, { kind: "bundle", model: best });
2862
+ } else {
2863
+ const id = value.slice("chat:".length);
2864
+ const model = screen.plan.chatModels.find((candidate) => candidate.id === id);
2865
+ if (model) void installModels(screen.plan, { kind: "chat", model });
2866
+ }
2867
+ }
2868
+ }
2869
+ )
2870
+ ] });
2871
+ }
2872
+ return /* @__PURE__ */ jsxs7(BootstrapFrame, { title: screen.title, children: [
2873
+ /* @__PURE__ */ jsx7(Text7, { color: "red", children: screen.message }),
2874
+ /* @__PURE__ */ jsx7(
2875
+ BootstrapChoiceList,
2876
+ {
2877
+ options: [
2878
+ ...screen.retry ? [{ label: "Try again", hint: "resume setup", value: "retry" }] : [],
2879
+ { label: "Continue to Gezel", hint: "configure this later", value: "continue" }
2880
+ ],
2881
+ onSelect: (value) => {
2882
+ if (value === "retry") screen.retry?.();
2883
+ else setScreen({ kind: "ready" });
2884
+ }
2885
+ }
2886
+ )
2887
+ ] });
2888
+ }
2889
+ function BootstrapFrame(props) {
2890
+ return /* @__PURE__ */ jsxs7(Box7, { flexDirection: "column", paddingX: 1, paddingY: 1, children: [
2891
+ /* @__PURE__ */ jsx7(Text7, { bold: true, color: "cyan", children: "gezel \xB7 first-time setup" }),
2892
+ /* @__PURE__ */ jsxs7(
2893
+ Box7,
2894
+ {
2895
+ flexDirection: "column",
2896
+ borderStyle: "round",
2897
+ borderColor: "yellow",
2898
+ paddingX: 1,
2899
+ marginTop: 1,
2900
+ children: [
2901
+ /* @__PURE__ */ jsx7(Text7, { bold: true, color: "yellow", children: props.title }),
2902
+ props.children
2903
+ ]
2904
+ }
2905
+ ),
2906
+ /* @__PURE__ */ jsx7(Text7, { dimColor: true, children: "Ctrl+C exit" })
2907
+ ] });
2908
+ }
2909
+ function BootstrapChoiceList(props) {
2910
+ const [index, setIndex] = useState5(0);
2911
+ const options = props.options;
2912
+ useInput5((input, key) => {
2913
+ if (key.upArrow) {
2914
+ setIndex((current) => current <= 0 ? options.length - 1 : current - 1);
2915
+ return;
2916
+ }
2917
+ if (key.downArrow) {
2918
+ setIndex((current) => current >= options.length - 1 ? 0 : current + 1);
2919
+ return;
2920
+ }
2921
+ const numeric = Number.parseInt(input, 10);
2922
+ if (/^[1-9]$/.test(input) && numeric <= options.length) {
2923
+ props.onSelect(options[numeric - 1].value);
2924
+ return;
2925
+ }
2926
+ if (key.return) {
2927
+ const selected = options[index];
2928
+ if (selected) props.onSelect(selected.value);
2929
+ }
2930
+ });
2931
+ return /* @__PURE__ */ jsxs7(Box7, { flexDirection: "column", marginTop: 1, children: [
2932
+ options.map((option, optionIndex) => /* @__PURE__ */ jsxs7(Text7, { color: optionIndex === index ? "green" : void 0, children: [
2933
+ optionIndex === index ? "\u276F " : " ",
2934
+ optionIndex + 1,
2935
+ ". ",
2936
+ option.label,
2937
+ option.hint ? /* @__PURE__ */ jsxs7(Text7, { dimColor: true, children: [
2938
+ " \u2014 ",
2939
+ option.hint
2940
+ ] }) : null
2941
+ ] }, option.value)),
2942
+ /* @__PURE__ */ jsxs7(Text7, { dimColor: true, children: [
2943
+ "\u2191/\u2193 choose \xB7 1\u2013",
2944
+ Math.min(9, options.length),
2945
+ " quick select \xB7 Enter confirm"
2946
+ ] })
2947
+ ] });
2948
+ }
2949
+ function ProgressBar({ pct }) {
2950
+ const width = 36;
2951
+ const filled = pct == null ? 0 : Math.round(Math.max(0, Math.min(100, pct)) / 100 * width);
2952
+ return /* @__PURE__ */ jsxs7(Text7, { color: "yellow", children: [
2953
+ "[",
2954
+ pct == null ? "\xB7".repeat(width) : `${"\u2588".repeat(filled)}${"\u2591".repeat(width - filled)}`,
2955
+ "]"
2956
+ ] });
2957
+ }
2958
+ async function settledFirstRunConfig(client) {
2959
+ let config = await client.getConfig();
2960
+ for (let attempt = 0; attempt < 12; attempt += 1) {
2961
+ if (config.firstRunCompleted || config.provider !== "copilot") return config;
2962
+ await delay(250);
2963
+ config = await client.getConfig();
2964
+ }
2965
+ return config;
2966
+ }
2967
+ async function installNativeToolkit(client, status, missing, setScreen) {
2968
+ for (let index = 0; index < missing.length; index += 1) {
2969
+ const engine = missing[index];
2970
+ let terminalError = null;
2971
+ await client.ensureNativeEngine(
2972
+ engine,
2973
+ (event) => {
2974
+ if (event.type === "error") terminalError = event.error;
2975
+ updateDownloadProgress(
2976
+ setScreen,
2977
+ { label: nativeLabel(engine), sizeBytes: 0 },
2978
+ index,
2979
+ missing.length,
2980
+ event,
2981
+ `Installing native-v${status.release}`
2982
+ );
2983
+ },
2984
+ engine === "llama-server" ? status.llamaBackend : void 0
2985
+ );
2986
+ if (terminalError) throw new Error(terminalError);
2987
+ }
2988
+ }
2989
+ async function installChatModel(client, model, onEvent) {
2990
+ let terminalError = null;
2991
+ const listener = (event) => {
2992
+ if (event.type === "error") terminalError = event.error;
2993
+ onEvent(event);
2994
+ };
2995
+ if (model.provider === "mlx") {
2996
+ await client.installMlxModel(model.id, listener);
2997
+ } else {
2998
+ await client.installLlamaCppModel(model.id, listener);
2999
+ }
3000
+ if (terminalError) throw new Error(terminalError);
3001
+ }
3002
+ async function installAccessory(client, model, onEvent) {
3003
+ let terminalError = null;
3004
+ const listener = (event) => {
3005
+ if (event.type === "error") terminalError = event.error ?? "download failed";
3006
+ onEvent(event);
3007
+ };
3008
+ if (model.kind === "image") {
3009
+ await client.pullImageModel(model.id, listener);
3010
+ } else if (model.kind === "video") {
3011
+ await client.pullVideoModel(model.id, listener);
3012
+ } else if (model.kind === "recognition") {
3013
+ await client.pullRecognitionModel(model.id, listener);
3014
+ } else {
3015
+ await client.pullAudioModel(model.kind, model.id, listener);
3016
+ }
3017
+ if (terminalError) throw new Error(terminalError);
3018
+ }
3019
+ function updateDownloadProgress(setScreen, job, index, total, event, title = "Installing local models") {
3020
+ let pct = null;
3021
+ let detail = job.label;
3022
+ if (event.type === "progress") {
3023
+ const written = "bytesWrittenAll" in event && typeof event.bytesWrittenAll === "number" ? event.bytesWrittenAll : event.bytesWritten;
3024
+ const all = "totalBytesAll" in event && typeof event.totalBytesAll === "number" ? event.totalBytesAll : event.totalBytes;
3025
+ if (typeof written === "number" && typeof all === "number" && all > 0) {
3026
+ pct = Math.min(100, Math.floor(written / all * 100));
3027
+ detail = `${job.label} \xB7 ${formatDownloadSize(written)} of ${formatDownloadSize(all)}`;
3028
+ }
3029
+ } else if (event.type === "retrying" && "attempt" in event) {
3030
+ detail = `${job.label} \xB7 retrying ${event.attempt}/${event.maxAttempts}`;
3031
+ } else if (event.type === "verifying") {
3032
+ detail = `${job.label} \xB7 verifying`;
3033
+ } else if (event.type === "done") {
3034
+ pct = 100;
3035
+ detail = `${job.label} \xB7 ready`;
3036
+ }
3037
+ setScreen({
3038
+ kind: "installing",
3039
+ progress: {
3040
+ title,
3041
+ detail,
3042
+ current: index + 1,
3043
+ total,
3044
+ pct
3045
+ }
3046
+ });
3047
+ }
3048
+ function missingToolkit(status) {
3049
+ const installed = new Set(
3050
+ status.engines.filter((engine) => engine.installed).map((engine) => engine.name)
3051
+ );
3052
+ return NATIVE_TOOLKIT.filter((engine) => !installed.has(engine));
3053
+ }
3054
+ function idSet(models) {
3055
+ return new Set(models.map((model) => model.id));
3056
+ }
3057
+ function nativeLabel(engine) {
3058
+ switch (engine) {
3059
+ case "llama-server":
3060
+ return "llama";
3061
+ case "sd-server":
3062
+ return "image engine";
3063
+ case "whisper-server":
3064
+ return "speech engine";
3065
+ case "uv":
3066
+ return "local runtime helper";
3067
+ case "ds4-server":
3068
+ return "ds4";
3069
+ }
3070
+ }
3071
+ function fitLabel(fit) {
3072
+ if (fit === "fits-offload") return "fits with offload";
3073
+ if (fit === "fits") return "good fit";
3074
+ if (fit === "tight") return "tight fit";
3075
+ return "best available";
3076
+ }
3077
+ function errorMessage(error) {
3078
+ return error instanceof Error ? error.message : String(error);
3079
+ }
3080
+ function delay(ms) {
3081
+ return new Promise((resolve) => setTimeout(resolve, ms));
3082
+ }
3083
+
3084
+ // src/tui/index.tsx
3085
+ import { jsx as jsx8 } from "react/jsx-runtime";
3086
+ async function launchTui(opts) {
3087
+ const instance = render(
3088
+ /* @__PURE__ */ jsx8(BootstrapGate, { client: opts.client, children: /* @__PURE__ */ jsx8(
3089
+ App,
3090
+ {
3091
+ client: opts.client,
3092
+ initialProjectId: opts.projectId,
3093
+ initialProjectName: opts.projectName
3094
+ }
3095
+ ) }),
3096
+ // We own Ctrl+C (interrupt-then-exit); don't let ink exit on the first press.
3097
+ { exitOnCtrlC: false }
3098
+ );
3099
+ await instance.waitUntilExit();
3100
+ }
3101
+ export {
3102
+ launchTui
3103
+ };