@robota-sdk/agent-cli 3.0.0-beta.4 → 3.0.0-beta.40

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,3163 @@
1
+ // src/cli.ts
2
+ import { readFileSync as readFileSync4, existsSync as existsSync3, mkdirSync as mkdirSync2, writeFileSync as writeFileSync2 } from "fs";
3
+ import { join as join5, dirname as dirname3 } from "path";
4
+ import { fileURLToPath } from "url";
5
+ import {
6
+ loadConfig,
7
+ loadContext,
8
+ detectProject,
9
+ createSession as createSession2,
10
+ SessionStore,
11
+ FileSessionLogger as FileSessionLogger2,
12
+ projectPaths as projectPaths2
13
+ } from "@robota-sdk/agent-sdk";
14
+ import { promptForApproval } from "@robota-sdk/agent-sdk";
15
+
16
+ // src/utils/cli-args.ts
17
+ import { parseArgs } from "util";
18
+ var VALID_MODES = ["plan", "default", "acceptEdits", "bypassPermissions"];
19
+ function parsePermissionMode(raw) {
20
+ if (raw === void 0) return void 0;
21
+ if (!VALID_MODES.includes(raw)) {
22
+ process.stderr.write(`Invalid --permission-mode "${raw}". Valid: ${VALID_MODES.join(" | ")}
23
+ `);
24
+ process.exit(1);
25
+ }
26
+ return raw;
27
+ }
28
+ function parseMaxTurns(raw) {
29
+ if (raw === void 0) return void 0;
30
+ const n = parseInt(raw, 10);
31
+ if (isNaN(n) || n <= 0) {
32
+ process.stderr.write(`Invalid --max-turns "${raw}". Must be a positive integer.
33
+ `);
34
+ process.exit(1);
35
+ }
36
+ return n;
37
+ }
38
+ function parseCliArgs() {
39
+ const { values, positionals } = parseArgs({
40
+ allowPositionals: true,
41
+ options: {
42
+ p: { type: "boolean", short: "p", default: false },
43
+ c: { type: "boolean", short: "c", default: false },
44
+ r: { type: "string", short: "r" },
45
+ model: { type: "string" },
46
+ language: { type: "string" },
47
+ "permission-mode": { type: "string" },
48
+ "max-turns": { type: "string" },
49
+ version: { type: "boolean", default: false },
50
+ reset: { type: "boolean", default: false }
51
+ }
52
+ });
53
+ return {
54
+ positional: positionals,
55
+ printMode: values["p"] ?? false,
56
+ continueMode: values["c"] ?? false,
57
+ resumeId: values["r"],
58
+ model: values["model"],
59
+ language: values["language"],
60
+ permissionMode: parsePermissionMode(values["permission-mode"]),
61
+ maxTurns: parseMaxTurns(values["max-turns"]),
62
+ version: values["version"] ?? false,
63
+ reset: values["reset"] ?? false
64
+ };
65
+ }
66
+
67
+ // src/utils/settings-io.ts
68
+ import { existsSync, readFileSync, writeFileSync, mkdirSync, unlinkSync } from "fs";
69
+ import { join, dirname } from "path";
70
+ function getUserSettingsPath() {
71
+ const home = process.env.HOME ?? process.env.USERPROFILE ?? "/";
72
+ return join(home, ".robota", "settings.json");
73
+ }
74
+ function readSettings(path) {
75
+ if (!existsSync(path)) return {};
76
+ return JSON.parse(readFileSync(path, "utf8"));
77
+ }
78
+ function writeSettings(path, settings) {
79
+ mkdirSync(dirname(path), { recursive: true });
80
+ writeFileSync(path, JSON.stringify(settings, null, 2) + "\n", "utf8");
81
+ }
82
+ function updateModelInSettings(settingsPath, modelId) {
83
+ const settings = readSettings(settingsPath);
84
+ const provider = settings.provider ?? {};
85
+ provider.model = modelId;
86
+ settings.provider = provider;
87
+ writeSettings(settingsPath, settings);
88
+ }
89
+ function deleteSettings(path) {
90
+ if (existsSync(path)) {
91
+ unlinkSync(path);
92
+ return true;
93
+ }
94
+ return false;
95
+ }
96
+
97
+ // src/print-terminal.ts
98
+ import * as readline from "readline";
99
+ var PrintTerminal = class {
100
+ write(text) {
101
+ process.stdout.write(text);
102
+ }
103
+ writeLine(text) {
104
+ process.stdout.write(text + "\n");
105
+ }
106
+ writeMarkdown(md) {
107
+ process.stdout.write(md);
108
+ }
109
+ writeError(text) {
110
+ process.stderr.write(text + "\n");
111
+ }
112
+ prompt(question) {
113
+ return new Promise((resolve) => {
114
+ const rl = readline.createInterface({
115
+ input: process.stdin,
116
+ output: process.stdout,
117
+ terminal: false,
118
+ historySize: 0
119
+ });
120
+ rl.question(question, (answer) => {
121
+ rl.close();
122
+ resolve(answer);
123
+ });
124
+ });
125
+ }
126
+ async select(options, initialIndex = 0) {
127
+ for (let i = 0; i < options.length; i++) {
128
+ const marker = i === initialIndex ? ">" : " ";
129
+ process.stdout.write(` ${marker} ${i + 1}) ${options[i]}
130
+ `);
131
+ }
132
+ const answer = await this.prompt(
133
+ ` Choose [1-${options.length}] (default: ${options[initialIndex]}): `
134
+ );
135
+ const trimmed = answer.trim().toLowerCase();
136
+ if (trimmed === "") return initialIndex;
137
+ const num = parseInt(trimmed, 10);
138
+ if (!isNaN(num) && num >= 1 && num <= options.length) return num - 1;
139
+ return initialIndex;
140
+ }
141
+ spinner(_message) {
142
+ return { stop() {
143
+ }, update() {
144
+ } };
145
+ }
146
+ };
147
+
148
+ // src/ui/render.tsx
149
+ import { render } from "ink";
150
+
151
+ // src/ui/App.tsx
152
+ import { useState as useState10, useRef as useRef8, useEffect as useEffect3, useCallback as useCallback10 } from "react";
153
+ import { Box as Box11, Text as Text13, useApp, useInput as useInput7 } from "ink";
154
+ import { getModelName } from "@robota-sdk/agent-core";
155
+ import { createSystemMessage as createSystemMessage3 } from "@robota-sdk/agent-core";
156
+
157
+ // src/ui/hooks/useSession.ts
158
+ import { useState, useCallback, useRef } from "react";
159
+ import { createSession, FileSessionLogger, projectPaths } from "@robota-sdk/agent-sdk";
160
+
161
+ // src/utils/edit-diff.ts
162
+ import { readFileSync as readFileSync2 } from "fs";
163
+ var CONTEXT_LINES = 2;
164
+ function generateDiffLines(oldStr, newStr, startLine = 1) {
165
+ if (oldStr === newStr) return [];
166
+ const lines = [];
167
+ const oldLines = oldStr.split("\n");
168
+ const newLines = newStr.split("\n");
169
+ for (let i = 0; i < oldLines.length; i++) {
170
+ lines.push({ type: "remove", text: oldLines[i], lineNumber: startLine + i });
171
+ }
172
+ for (let i = 0; i < newLines.length; i++) {
173
+ lines.push({ type: "add", text: newLines[i], lineNumber: startLine + i });
174
+ }
175
+ return lines;
176
+ }
177
+ function generateDiffLinesWithContext(oldStr, newStr, startLine, filePath) {
178
+ if (oldStr === newStr) return [];
179
+ const diffLines = generateDiffLines(oldStr, newStr, startLine);
180
+ let fileLines;
181
+ try {
182
+ fileLines = readFileSync2(filePath, "utf-8").split("\n");
183
+ } catch {
184
+ return diffLines;
185
+ }
186
+ const result = [];
187
+ const contextStart = Math.max(0, startLine - 1 - CONTEXT_LINES);
188
+ for (let i = contextStart; i < startLine - 1; i++) {
189
+ if (i < fileLines.length) {
190
+ result.push({ type: "context", text: fileLines[i], lineNumber: i + 1 });
191
+ }
192
+ }
193
+ result.push(...diffLines);
194
+ const newLineCount = newStr.split("\n").length;
195
+ const afterStart = startLine - 1 + newLineCount;
196
+ for (let i = afterStart; i < afterStart + CONTEXT_LINES; i++) {
197
+ if (i < fileLines.length) {
198
+ result.push({ type: "context", text: fileLines[i], lineNumber: i + 1 });
199
+ }
200
+ }
201
+ return result;
202
+ }
203
+ function extractEditDiff(toolName, toolArgs, startLine) {
204
+ if (toolName !== "Edit" || !toolArgs) return null;
205
+ const filePath = toolArgs.file_path ?? toolArgs.filePath;
206
+ const oldStr = toolArgs.old_string ?? toolArgs.oldString;
207
+ const newStr = toolArgs.new_string ?? toolArgs.newString;
208
+ if (typeof filePath !== "string") return null;
209
+ if (typeof oldStr !== "string" || typeof newStr !== "string") return null;
210
+ let sl = startLine ?? 0;
211
+ if (!sl) {
212
+ try {
213
+ const fileContent = readFileSync2(filePath, "utf-8");
214
+ const idx = fileContent.indexOf(newStr);
215
+ if (idx >= 0) {
216
+ sl = fileContent.substring(0, idx).split("\n").length;
217
+ } else {
218
+ sl = 1;
219
+ }
220
+ } catch {
221
+ sl = 1;
222
+ }
223
+ }
224
+ const lines = generateDiffLinesWithContext(oldStr, newStr, sl, filePath);
225
+ if (lines.length === 0) return null;
226
+ return { file: filePath, lines };
227
+ }
228
+
229
+ // src/ui/hooks/useSession.ts
230
+ var TOOL_ARG_DISPLAY_MAX = 80;
231
+ var TAIL_KEEP = 30;
232
+ var MAX_COMPLETED_TOOLS = 50;
233
+ var NOOP_TERMINAL = {
234
+ write: () => {
235
+ },
236
+ writeLine: () => {
237
+ },
238
+ writeMarkdown: () => {
239
+ },
240
+ writeError: () => {
241
+ },
242
+ prompt: () => Promise.resolve(""),
243
+ select: () => Promise.resolve(0),
244
+ spinner: () => ({ stop: () => {
245
+ }, update: () => {
246
+ } })
247
+ };
248
+ function useSession(props) {
249
+ const [permissionRequest, setPermissionRequest] = useState(null);
250
+ const [streamingText, setStreamingText] = useState("");
251
+ const streamingTextRef = useRef("");
252
+ const [activeTools, setActiveTools] = useState([]);
253
+ const permissionQueueRef = useRef([]);
254
+ const processingRef = useRef(false);
255
+ const processNextPermission = useCallback(() => {
256
+ if (processingRef.current) return;
257
+ const next = permissionQueueRef.current[0];
258
+ if (!next) {
259
+ setPermissionRequest(null);
260
+ return;
261
+ }
262
+ processingRef.current = true;
263
+ setPermissionRequest({
264
+ toolName: next.toolName,
265
+ toolArgs: next.toolArgs,
266
+ resolve: (result) => {
267
+ permissionQueueRef.current.shift();
268
+ processingRef.current = false;
269
+ setPermissionRequest(null);
270
+ next.resolve(result);
271
+ setTimeout(() => processNextPermission(), 0);
272
+ }
273
+ });
274
+ }, []);
275
+ const sessionRef = useRef(null);
276
+ if (sessionRef.current === null) {
277
+ const permissionHandler = (toolName, toolArgs) => {
278
+ return new Promise((resolve) => {
279
+ permissionQueueRef.current.push({ toolName, toolArgs, resolve });
280
+ processNextPermission();
281
+ });
282
+ };
283
+ let flushTimer = null;
284
+ const onTextDelta = (delta) => {
285
+ streamingTextRef.current += delta;
286
+ if (!flushTimer) {
287
+ flushTimer = setTimeout(() => {
288
+ setStreamingText(streamingTextRef.current);
289
+ flushTimer = null;
290
+ }, 16);
291
+ }
292
+ };
293
+ const onToolExecution = (event) => {
294
+ if (event.type === "start") {
295
+ let firstArg = "";
296
+ if (event.toolArgs) {
297
+ const firstVal = Object.values(event.toolArgs)[0];
298
+ const raw = typeof firstVal === "string" ? firstVal : JSON.stringify(firstVal ?? "");
299
+ firstArg = raw.length > TOOL_ARG_DISPLAY_MAX ? raw.slice(0, TOOL_ARG_DISPLAY_MAX - TAIL_KEEP - 3) + "..." + raw.slice(-TAIL_KEEP) : raw;
300
+ }
301
+ setActiveTools((prev) => [
302
+ ...prev,
303
+ { toolName: event.toolName, firstArg, isRunning: true, _toolArgs: event.toolArgs }
304
+ ]);
305
+ } else {
306
+ const toolResult = event.denied ? "denied" : event.success === false ? "error" : "success";
307
+ setActiveTools((prev) => {
308
+ const updated = prev.map((t) => {
309
+ if (!(t.toolName === event.toolName && t.isRunning)) return t;
310
+ let startLine;
311
+ if (event.toolResultData && event.toolName === "Edit") {
312
+ try {
313
+ const parsed = JSON.parse(event.toolResultData);
314
+ if (typeof parsed.startLine === "number") {
315
+ startLine = parsed.startLine;
316
+ }
317
+ } catch {
318
+ }
319
+ }
320
+ const editDiff = extractEditDiff(
321
+ event.toolName,
322
+ t._toolArgs,
323
+ startLine
324
+ );
325
+ const finished = {
326
+ ...t,
327
+ isRunning: false,
328
+ result: toolResult
329
+ };
330
+ if (editDiff) {
331
+ finished.diffLines = editDiff.lines;
332
+ finished.diffFile = editDiff.file;
333
+ }
334
+ delete finished._toolArgs;
335
+ return finished;
336
+ });
337
+ const completed = updated.filter((t) => !t.isRunning);
338
+ if (completed.length > MAX_COMPLETED_TOOLS) {
339
+ const excess = completed.length - MAX_COMPLETED_TOOLS;
340
+ let removed = 0;
341
+ return updated.filter((t) => {
342
+ if (!t.isRunning && removed < excess) {
343
+ removed++;
344
+ return false;
345
+ }
346
+ return true;
347
+ });
348
+ }
349
+ return updated;
350
+ });
351
+ }
352
+ };
353
+ const paths = projectPaths(props.cwd ?? process.cwd());
354
+ sessionRef.current = createSession({
355
+ config: props.config,
356
+ context: props.context,
357
+ terminal: NOOP_TERMINAL,
358
+ sessionLogger: new FileSessionLogger(paths.logs),
359
+ projectInfo: props.projectInfo,
360
+ sessionStore: props.sessionStore,
361
+ permissionMode: props.permissionMode,
362
+ maxTurns: props.maxTurns,
363
+ permissionHandler,
364
+ onTextDelta,
365
+ onToolExecution
366
+ });
367
+ }
368
+ const clearStreamingText = useCallback(() => {
369
+ setStreamingText("");
370
+ streamingTextRef.current = "";
371
+ setActiveTools([]);
372
+ }, []);
373
+ return {
374
+ session: sessionRef.current,
375
+ permissionRequest,
376
+ streamingText,
377
+ clearStreamingText,
378
+ activeTools
379
+ };
380
+ }
381
+
382
+ // src/ui/hooks/useMessages.ts
383
+ import { useState as useState2, useCallback as useCallback2 } from "react";
384
+ var MAX_RENDERED_MESSAGES = 100;
385
+ function useMessages() {
386
+ const [messages, setMessages] = useState2([]);
387
+ const addMessage = useCallback2((msg) => {
388
+ setMessages((prev) => {
389
+ const updated = [...prev, msg];
390
+ if (updated.length > MAX_RENDERED_MESSAGES) {
391
+ return updated.slice(-MAX_RENDERED_MESSAGES);
392
+ }
393
+ return updated;
394
+ });
395
+ }, []);
396
+ return { messages, setMessages, addMessage };
397
+ }
398
+
399
+ // src/ui/hooks/useSlashCommands.ts
400
+ import { useCallback as useCallback3 } from "react";
401
+ import { createSystemMessage } from "@robota-sdk/agent-core";
402
+
403
+ // src/commands/slash-executor.ts
404
+ var VALID_MODES2 = ["plan", "default", "acceptEdits", "bypassPermissions"];
405
+ var HELP_TEXT = [
406
+ "Available commands:",
407
+ " /help \u2014 Show this help",
408
+ " /clear \u2014 Clear conversation",
409
+ " /compact [instr] \u2014 Compact context (optional focus instructions)",
410
+ " /mode [m] \u2014 Show/change permission mode",
411
+ " /language [lang] \u2014 Set response language (ko, en, ja, zh)",
412
+ " /cost \u2014 Show session info",
413
+ " /reset \u2014 Delete settings and exit",
414
+ " /exit \u2014 Exit CLI"
415
+ ].join("\n");
416
+ function handleHelp(addMessage) {
417
+ addMessage({ role: "system", content: HELP_TEXT });
418
+ return { handled: true };
419
+ }
420
+ function handleClear(addMessage, clearMessages, session) {
421
+ clearMessages();
422
+ session.clearHistory();
423
+ addMessage({ role: "system", content: "Conversation cleared." });
424
+ return { handled: true };
425
+ }
426
+ async function handleCompact(args, session, addMessage) {
427
+ const instructions = args.trim() || void 0;
428
+ const before = session.getContextState().usedPercentage;
429
+ addMessage({ role: "system", content: "Compacting context..." });
430
+ await session.compact(instructions);
431
+ const after = session.getContextState().usedPercentage;
432
+ addMessage({
433
+ role: "system",
434
+ content: `Context compacted: ${Math.round(before)}% -> ${Math.round(after)}%`
435
+ });
436
+ return { handled: true };
437
+ }
438
+ function handleMode(arg, session, addMessage) {
439
+ if (!arg) {
440
+ addMessage({ role: "system", content: `Current mode: ${session.getPermissionMode()}` });
441
+ } else if (VALID_MODES2.includes(arg)) {
442
+ session.setPermissionMode(arg);
443
+ addMessage({ role: "system", content: `Permission mode set to: ${arg}` });
444
+ } else {
445
+ addMessage({ role: "system", content: `Invalid mode. Valid: ${VALID_MODES2.join(" | ")}` });
446
+ }
447
+ return { handled: true };
448
+ }
449
+ function handleModel(modelId, addMessage) {
450
+ if (!modelId) {
451
+ addMessage({ role: "system", content: "Select a model from the /model submenu." });
452
+ return { handled: true };
453
+ }
454
+ return { handled: true, pendingModelId: modelId };
455
+ }
456
+ function handleCost(session, addMessage) {
457
+ addMessage({
458
+ role: "system",
459
+ content: `Session: ${session.getSessionId()}
460
+ Messages: ${session.getMessageCount()}`
461
+ });
462
+ return { handled: true };
463
+ }
464
+ function handlePermissions(session, addMessage) {
465
+ const mode = session.getPermissionMode();
466
+ const sessionAllowed = session.getSessionAllowedTools();
467
+ const lines = [`Permission mode: ${mode}`];
468
+ if (sessionAllowed.length > 0) {
469
+ lines.push(`Session-approved tools: ${sessionAllowed.join(", ")}`);
470
+ } else {
471
+ lines.push("No session-approved tools.");
472
+ }
473
+ addMessage({ role: "system", content: lines.join("\n") });
474
+ return { handled: true };
475
+ }
476
+ function handleContext(session, addMessage) {
477
+ const ctx = session.getContextState();
478
+ addMessage({
479
+ role: "system",
480
+ content: `Context: ${ctx.usedTokens.toLocaleString()} / ${ctx.maxTokens.toLocaleString()} tokens (${Math.round(ctx.usedPercentage)}%)`
481
+ });
482
+ return { handled: true };
483
+ }
484
+ function handleLanguage(lang, addMessage) {
485
+ if (!lang) {
486
+ addMessage({ role: "system", content: "Usage: /language <code> (e.g., ko, en, ja, zh)" });
487
+ return { handled: true };
488
+ }
489
+ const settingsPath = getUserSettingsPath();
490
+ const settings = readSettings(settingsPath);
491
+ settings.language = lang;
492
+ writeSettings(settingsPath, settings);
493
+ addMessage({ role: "system", content: `Language set to "${lang}". Restarting...` });
494
+ return { handled: true, exitRequested: true };
495
+ }
496
+ function handleReset(addMessage) {
497
+ const settingsPath = getUserSettingsPath();
498
+ if (deleteSettings(settingsPath)) {
499
+ addMessage({ role: "system", content: `Deleted ${settingsPath}. Exiting...` });
500
+ } else {
501
+ addMessage({ role: "system", content: "No user settings found." });
502
+ }
503
+ return { handled: true, exitRequested: true };
504
+ }
505
+ async function handlePluginCommand(args, addMessage, callbacks) {
506
+ const parts = args.trim().split(/\s+/);
507
+ const subcommand = parts[0] ?? "";
508
+ const subArgs = parts.slice(1).join(" ").trim();
509
+ try {
510
+ switch (subcommand) {
511
+ case "":
512
+ case void 0:
513
+ case "manage": {
514
+ return { handled: true, triggerPluginTUI: true };
515
+ }
516
+ case "install": {
517
+ if (!subArgs) {
518
+ addMessage({ role: "system", content: "Usage: /plugin install <name>@<marketplace>" });
519
+ return { handled: true };
520
+ }
521
+ await callbacks.install(subArgs);
522
+ addMessage({ role: "system", content: `Installed plugin: ${subArgs}` });
523
+ return { handled: true };
524
+ }
525
+ case "uninstall": {
526
+ if (!subArgs) {
527
+ addMessage({ role: "system", content: "Usage: /plugin uninstall <name>@<marketplace>" });
528
+ return { handled: true };
529
+ }
530
+ await callbacks.uninstall(subArgs);
531
+ addMessage({ role: "system", content: `Uninstalled plugin: ${subArgs}` });
532
+ return { handled: true };
533
+ }
534
+ case "enable": {
535
+ if (!subArgs) {
536
+ addMessage({ role: "system", content: "Usage: /plugin enable <name>@<marketplace>" });
537
+ return { handled: true };
538
+ }
539
+ await callbacks.enable(subArgs);
540
+ addMessage({ role: "system", content: `Enabled plugin: ${subArgs}` });
541
+ return { handled: true };
542
+ }
543
+ case "disable": {
544
+ if (!subArgs) {
545
+ addMessage({ role: "system", content: "Usage: /plugin disable <name>@<marketplace>" });
546
+ return { handled: true };
547
+ }
548
+ await callbacks.disable(subArgs);
549
+ addMessage({ role: "system", content: `Disabled plugin: ${subArgs}` });
550
+ return { handled: true };
551
+ }
552
+ case "marketplace": {
553
+ const mpParts = subArgs.split(/\s+/);
554
+ const mpSubcommand = mpParts[0] ?? "";
555
+ const mpArgs = mpParts.slice(1).join(" ").trim();
556
+ if (mpSubcommand === "add" && mpArgs) {
557
+ const registeredName = await callbacks.marketplaceAdd(mpArgs);
558
+ addMessage({
559
+ role: "system",
560
+ content: `Added marketplace: "${registeredName}" (from ${mpArgs})
561
+ Install plugins with: /plugin install <name>@${registeredName}`
562
+ });
563
+ return { handled: true };
564
+ } else if (mpSubcommand === "remove" && mpArgs) {
565
+ await callbacks.marketplaceRemove(mpArgs);
566
+ addMessage({
567
+ role: "system",
568
+ content: `Removed marketplace "${mpArgs}" and uninstalled its plugins.`
569
+ });
570
+ return { handled: true };
571
+ } else if (mpSubcommand === "update" && mpArgs) {
572
+ await callbacks.marketplaceUpdate(mpArgs);
573
+ addMessage({
574
+ role: "system",
575
+ content: `Updated marketplace "${mpArgs}".`
576
+ });
577
+ return { handled: true };
578
+ } else if (mpSubcommand === "list") {
579
+ const sources = await callbacks.marketplaceList();
580
+ if (sources.length === 0) {
581
+ addMessage({ role: "system", content: "No marketplace sources configured." });
582
+ } else {
583
+ const lines = sources.map((s) => ` ${s.name} (${s.type})`);
584
+ addMessage({ role: "system", content: `Marketplace sources:
585
+ ${lines.join("\n")}` });
586
+ }
587
+ return { handled: true };
588
+ } else {
589
+ addMessage({
590
+ role: "system",
591
+ content: "Usage: /plugin marketplace add <source> | remove <name> | update <name> | list"
592
+ });
593
+ return { handled: true };
594
+ }
595
+ }
596
+ default:
597
+ addMessage({ role: "system", content: `Unknown plugin subcommand: ${subcommand}` });
598
+ return { handled: true };
599
+ }
600
+ } catch (error) {
601
+ const message = error instanceof Error ? error.message : String(error);
602
+ addMessage({ role: "system", content: `Plugin error: ${message}` });
603
+ return { handled: true };
604
+ }
605
+ }
606
+ async function handleReloadPlugins(addMessage, callbacks) {
607
+ await callbacks.reloadPlugins();
608
+ addMessage({ role: "system", content: "Plugins reload complete." });
609
+ return { handled: true };
610
+ }
611
+ async function executeSlashCommand(cmd, args, session, addMessage, clearMessages, registry, pluginCallbacks) {
612
+ switch (cmd) {
613
+ case "help":
614
+ return handleHelp(addMessage);
615
+ case "clear":
616
+ return handleClear(addMessage, clearMessages, session);
617
+ case "compact":
618
+ return handleCompact(args, session, addMessage);
619
+ case "mode":
620
+ return handleMode(args.split(/\s+/)[0] || void 0, session, addMessage);
621
+ case "model":
622
+ return handleModel(args.split(/\s+/)[0] || void 0, addMessage);
623
+ case "language":
624
+ return handleLanguage(args.split(/\s+/)[0] || void 0, addMessage);
625
+ case "cost":
626
+ return handleCost(session, addMessage);
627
+ case "permissions":
628
+ return handlePermissions(session, addMessage);
629
+ case "context":
630
+ return handleContext(session, addMessage);
631
+ case "reset":
632
+ return handleReset(addMessage);
633
+ case "exit":
634
+ return { handled: true, exitRequested: true };
635
+ case "plugin":
636
+ if (pluginCallbacks) {
637
+ return handlePluginCommand(args, addMessage, pluginCallbacks);
638
+ }
639
+ addMessage({ role: "system", content: "Plugin management is not available." });
640
+ return { handled: true };
641
+ case "reload-plugins":
642
+ if (pluginCallbacks) {
643
+ return handleReloadPlugins(addMessage, pluginCallbacks);
644
+ }
645
+ addMessage({ role: "system", content: "Plugin management is not available." });
646
+ return { handled: true };
647
+ default: {
648
+ const dynamicCmd = registry.getCommands().find((c) => c.name === cmd && (c.source === "skill" || c.source === "plugin"));
649
+ if (dynamicCmd) {
650
+ addMessage({ role: "system", content: `Invoking ${dynamicCmd.source}: ${cmd}` });
651
+ return { handled: false };
652
+ }
653
+ addMessage({ role: "system", content: `Unknown command "/${cmd}". Type /help for help.` });
654
+ return { handled: true };
655
+ }
656
+ }
657
+ }
658
+
659
+ // src/ui/hooks/useSlashCommands.ts
660
+ var EXIT_DELAY_MS = 500;
661
+ function useSlashCommands(session, addMessage, setMessages, exit, registry, pendingModelChangeRef, setPendingModelId, pluginCallbacks, setShowPluginTUI) {
662
+ return useCallback3(
663
+ async (input) => {
664
+ const parts = input.slice(1).split(/\s+/);
665
+ const cmd = parts[0]?.toLowerCase() ?? "";
666
+ const args = parts.slice(1).join(" ");
667
+ const clearMessages = () => setMessages([]);
668
+ const slashAddMessage = (msg) => {
669
+ addMessage(createSystemMessage(msg.content));
670
+ };
671
+ const result = await executeSlashCommand(
672
+ cmd,
673
+ args,
674
+ session,
675
+ slashAddMessage,
676
+ clearMessages,
677
+ registry,
678
+ pluginCallbacks
679
+ );
680
+ if (result.pendingModelId) {
681
+ pendingModelChangeRef.current = result.pendingModelId;
682
+ setPendingModelId(result.pendingModelId);
683
+ }
684
+ if (result.triggerPluginTUI) {
685
+ setShowPluginTUI?.(true);
686
+ }
687
+ if (result.exitRequested) {
688
+ setTimeout(() => exit(), EXIT_DELAY_MS);
689
+ }
690
+ return result.handled;
691
+ },
692
+ [
693
+ session,
694
+ addMessage,
695
+ setMessages,
696
+ exit,
697
+ registry,
698
+ pendingModelChangeRef,
699
+ setPendingModelId,
700
+ pluginCallbacks,
701
+ setShowPluginTUI
702
+ ]
703
+ );
704
+ }
705
+
706
+ // src/ui/hooks/useSubmitHandler.ts
707
+ import { useCallback as useCallback4 } from "react";
708
+ import { randomUUID } from "crypto";
709
+ import {
710
+ createSubagentSession,
711
+ getBuiltInAgent,
712
+ retrieveAgentToolDeps
713
+ } from "@robota-sdk/agent-sdk";
714
+ import {
715
+ createUserMessage,
716
+ createAssistantMessage,
717
+ createSystemMessage as createSystemMessage2,
718
+ createToolMessage
719
+ } from "@robota-sdk/agent-core";
720
+
721
+ // src/utils/tool-call-extractor.ts
722
+ var TOOL_ARG_MAX_LENGTH = 80;
723
+ var TAIL_KEEP2 = 30;
724
+ function extractToolCallsWithDiff(history, startIndex) {
725
+ const summaries = [];
726
+ for (let i = startIndex; i < history.length; i++) {
727
+ const msg = history[i];
728
+ if (msg.role === "assistant" && msg.toolCalls) {
729
+ for (const tc of msg.toolCalls) {
730
+ const value = parseFirstArgValue(tc.function.arguments);
731
+ const truncated = value.length > TOOL_ARG_MAX_LENGTH ? value.slice(0, TOOL_ARG_MAX_LENGTH - TAIL_KEEP2 - 3) + "..." + value.slice(-TAIL_KEEP2) : value;
732
+ const summary = {
733
+ line: `${tc.function.name}(${truncated})`
734
+ };
735
+ if (tc.function.name === "Edit") {
736
+ try {
737
+ const args = JSON.parse(tc.function.arguments);
738
+ const diff = extractEditDiff("Edit", args);
739
+ if (diff) {
740
+ summary.diffLines = diff.lines;
741
+ summary.diffFile = diff.file;
742
+ }
743
+ } catch {
744
+ }
745
+ }
746
+ summaries.push(summary);
747
+ }
748
+ }
749
+ }
750
+ return summaries;
751
+ }
752
+ function parseFirstArgValue(argsJson) {
753
+ try {
754
+ const parsed = JSON.parse(argsJson);
755
+ const firstVal = Object.values(parsed)[0];
756
+ return typeof firstVal === "string" ? firstVal : JSON.stringify(firstVal);
757
+ } catch {
758
+ return argsJson;
759
+ }
760
+ }
761
+
762
+ // src/utils/skill-prompt.ts
763
+ import { execSync } from "child_process";
764
+ function substituteVariables(content, args, context) {
765
+ const argParts = args ? args.split(/\s+/) : [];
766
+ let result = content;
767
+ result = result.replace(/\$ARGUMENTS\[(\d+)]/g, (_match, index) => {
768
+ return argParts[Number(index)] ?? "";
769
+ });
770
+ result = result.replace(/\$ARGUMENTS/g, args);
771
+ result = result.replace(/\$(\d)(?!\d|\w|\[)/g, (_match, digit) => {
772
+ return argParts[Number(digit)] ?? "";
773
+ });
774
+ result = result.replace(/\$\{CLAUDE_SESSION_ID}/g, context?.sessionId ?? "");
775
+ result = result.replace(/\$\{CLAUDE_SKILL_DIR}/g, context?.skillDir ?? "");
776
+ return result;
777
+ }
778
+ async function preprocessShellCommands(content) {
779
+ const shellPattern = /!`([^`]+)`/g;
780
+ if (!shellPattern.test(content)) {
781
+ return content;
782
+ }
783
+ shellPattern.lastIndex = 0;
784
+ let result = content;
785
+ let match;
786
+ const matches = [];
787
+ while ((match = shellPattern.exec(content)) !== null) {
788
+ matches.push({ full: match[0], command: match[1] });
789
+ }
790
+ for (const { full, command } of matches) {
791
+ let output = "";
792
+ try {
793
+ output = execSync(command, {
794
+ timeout: 5e3,
795
+ encoding: "utf-8",
796
+ stdio: ["pipe", "pipe", "pipe"]
797
+ }).trimEnd();
798
+ } catch {
799
+ output = "";
800
+ }
801
+ result = result.replace(full, output);
802
+ }
803
+ return result;
804
+ }
805
+ async function buildSkillPrompt(input, registry, context) {
806
+ const parts = input.slice(1).split(/\s+/);
807
+ const cmd = parts[0]?.toLowerCase() ?? "";
808
+ const skillCmd = registry.getCommands().find((c) => c.name === cmd && (c.source === "skill" || c.source === "plugin"));
809
+ if (!skillCmd) return null;
810
+ const args = parts.slice(1).join(" ").trim();
811
+ const userInstruction = args || skillCmd.description;
812
+ if (skillCmd.skillContent) {
813
+ let processed = await preprocessShellCommands(skillCmd.skillContent);
814
+ processed = substituteVariables(processed, args, context);
815
+ return `<skill name="${cmd}">
816
+ ${processed}
817
+ </skill>
818
+
819
+ Execute the "${cmd}" skill: ${userInstruction}`;
820
+ }
821
+ return `Use the "${cmd}" skill: ${userInstruction}`;
822
+ }
823
+
824
+ // src/commands/skill-executor.ts
825
+ function buildProcessedContent(skill, args, context) {
826
+ if (!skill.skillContent) return null;
827
+ return substituteVariables(skill.skillContent, args, context);
828
+ }
829
+ function buildInjectPrompt(skill, args, context) {
830
+ const processed = buildProcessedContent(skill, args, context);
831
+ if (processed) {
832
+ const userInstruction = args || skill.description;
833
+ return `<skill name="${skill.name}">
834
+ ${processed}
835
+ </skill>
836
+
837
+ Execute the "${skill.name}" skill: ${userInstruction}`;
838
+ }
839
+ return `Use the "${skill.name}" skill: ${args || skill.description}`;
840
+ }
841
+ async function executeSkill(skill, args, callbacks, context) {
842
+ if (skill.context === "fork") {
843
+ if (!callbacks.runInFork) {
844
+ throw new Error("Fork execution is not available. Agent tool deps may not be initialized.");
845
+ }
846
+ const content = buildProcessedContent(skill, args, context);
847
+ const prompt2 = content ?? `Use the "${skill.name}" skill: ${args || skill.description}`;
848
+ const options = {};
849
+ if (skill.agent) options.agent = skill.agent;
850
+ if (skill.allowedTools) options.allowedTools = skill.allowedTools;
851
+ const result = await callbacks.runInFork(prompt2, options);
852
+ return { mode: "fork", result };
853
+ }
854
+ const prompt = buildInjectPrompt(skill, args, context);
855
+ return { mode: "inject", prompt };
856
+ }
857
+
858
+ // src/ui/hooks/useSubmitHandler.ts
859
+ function syncContextState(session, setter) {
860
+ const ctx = session.getContextState();
861
+ setter({ percentage: ctx.usedPercentage, usedTokens: ctx.usedTokens, maxTokens: ctx.maxTokens });
862
+ }
863
+ async function runSessionPrompt(prompt, session, addMessage, clearStreamingText, setIsThinking, setContextState, rawInput) {
864
+ setIsThinking(true);
865
+ clearStreamingText();
866
+ const historyBefore = session.getHistory().length;
867
+ try {
868
+ const response = await session.run(prompt, rawInput);
869
+ clearStreamingText();
870
+ const history = session.getHistory();
871
+ const toolSummaries = extractToolCallsWithDiff(
872
+ history,
873
+ historyBefore
874
+ );
875
+ if (toolSummaries.length > 0) {
876
+ addMessage(
877
+ createToolMessage(JSON.stringify(toolSummaries), {
878
+ toolCallId: randomUUID(),
879
+ name: `${toolSummaries.length} tools`
880
+ })
881
+ );
882
+ }
883
+ addMessage(createAssistantMessage(response || "(empty response)"));
884
+ syncContextState(session, setContextState);
885
+ } catch (err) {
886
+ clearStreamingText();
887
+ const isAbortError = err instanceof DOMException && err.name === "AbortError" || err instanceof Error && (err.message.includes("aborted") || err.message.includes("abort"));
888
+ if (isAbortError) {
889
+ const history = session.getHistory();
890
+ const toolSummaries = extractToolCallsWithDiff(
891
+ history,
892
+ historyBefore
893
+ );
894
+ if (toolSummaries.length > 0) {
895
+ addMessage(
896
+ createToolMessage(JSON.stringify(toolSummaries), {
897
+ toolCallId: randomUUID(),
898
+ name: `${toolSummaries.length} tools`
899
+ })
900
+ );
901
+ }
902
+ const assistantParts = [];
903
+ let lastAssistantState = "complete";
904
+ for (let i = historyBefore; i < history.length; i++) {
905
+ const msg = history[i];
906
+ if (msg && msg.role === "assistant" && msg.content) {
907
+ assistantParts.push(msg.content);
908
+ if (msg.state === "interrupted") lastAssistantState = "interrupted";
909
+ }
910
+ }
911
+ if (assistantParts.length > 0) {
912
+ addMessage(
913
+ createAssistantMessage(assistantParts.join("\n\n"), { state: lastAssistantState })
914
+ );
915
+ }
916
+ addMessage(createSystemMessage2("Interrupted by user."));
917
+ } else {
918
+ const errMsg = err instanceof Error ? err.message : String(err);
919
+ addMessage(createSystemMessage2(`Error: ${errMsg}`));
920
+ }
921
+ } finally {
922
+ setIsThinking(false);
923
+ }
924
+ }
925
+ function createForkRunner(sessionKey) {
926
+ const deps = retrieveAgentToolDeps(sessionKey);
927
+ if (!deps) return void 0;
928
+ return async (content, options) => {
929
+ const agentType = options.agent ?? "general-purpose";
930
+ const agentDef = getBuiltInAgent(agentType) ?? deps.customAgentRegistry?.(agentType);
931
+ if (!agentDef) {
932
+ throw new Error(`Unknown agent type for fork execution: ${agentType}`);
933
+ }
934
+ const effectiveDef = options.allowedTools ? { ...agentDef, tools: options.allowedTools } : agentDef;
935
+ const subSession = createSubagentSession({
936
+ agentDefinition: effectiveDef,
937
+ parentConfig: deps.config,
938
+ parentContext: deps.context,
939
+ parentTools: deps.tools,
940
+ terminal: deps.terminal,
941
+ isForkWorker: true,
942
+ permissionHandler: deps.permissionHandler,
943
+ onTextDelta: deps.onTextDelta,
944
+ onToolExecution: deps.onToolExecution
945
+ });
946
+ return await subSession.run(content);
947
+ };
948
+ }
949
+ function findSkillCommand(input, registry) {
950
+ const parts = input.slice(1).split(/\s+/);
951
+ const cmd = parts[0]?.toLowerCase() ?? "";
952
+ const skillCmd = registry.getCommands().find((c) => c.name === cmd && (c.source === "skill" || c.source === "plugin"));
953
+ if (!skillCmd) return null;
954
+ return { skill: skillCmd, args: parts.slice(1).join(" ").trim() };
955
+ }
956
+ function useSubmitHandler(session, addMessage, handleSlashCommand, clearStreamingText, setIsThinking, setContextState, registry) {
957
+ return useCallback4(
958
+ async (input) => {
959
+ if (input.startsWith("/")) {
960
+ const handled = await handleSlashCommand(input);
961
+ if (handled) {
962
+ syncContextState(session, setContextState);
963
+ return;
964
+ }
965
+ const found = findSkillCommand(input, registry);
966
+ if (!found) return;
967
+ const { skill, args } = found;
968
+ if (skill.context === "fork") {
969
+ const runInFork = createForkRunner(session);
970
+ const result = await executeSkill(skill, args, { runInFork });
971
+ if (result.mode === "fork") {
972
+ addMessage(createAssistantMessage(result.result ?? "(empty response)"));
973
+ syncContextState(session, setContextState);
974
+ return;
975
+ }
976
+ if (result.prompt) {
977
+ const cmdName2 = input.slice(1).split(/\s+/)[0]?.toLowerCase() ?? "";
978
+ const qualifiedName2 = registry.resolveQualifiedName(cmdName2);
979
+ const hookInput2 = qualifiedName2 ? `/${qualifiedName2}${input.slice(1 + cmdName2.length)}` : input;
980
+ return runSessionPrompt(
981
+ result.prompt,
982
+ session,
983
+ addMessage,
984
+ clearStreamingText,
985
+ setIsThinking,
986
+ setContextState,
987
+ hookInput2
988
+ );
989
+ }
990
+ return;
991
+ }
992
+ const prompt = await buildSkillPrompt(input, registry);
993
+ if (!prompt) return;
994
+ const cmdName = input.slice(1).split(/\s+/)[0]?.toLowerCase() ?? "";
995
+ const qualifiedName = registry.resolveQualifiedName(cmdName);
996
+ const hookInput = qualifiedName ? `/${qualifiedName}${input.slice(1 + cmdName.length)}` : input;
997
+ return runSessionPrompt(
998
+ prompt,
999
+ session,
1000
+ addMessage,
1001
+ clearStreamingText,
1002
+ setIsThinking,
1003
+ setContextState,
1004
+ hookInput
1005
+ );
1006
+ }
1007
+ addMessage(createUserMessage(input));
1008
+ return runSessionPrompt(
1009
+ input,
1010
+ session,
1011
+ addMessage,
1012
+ clearStreamingText,
1013
+ setIsThinking,
1014
+ setContextState
1015
+ );
1016
+ },
1017
+ [
1018
+ session,
1019
+ addMessage,
1020
+ handleSlashCommand,
1021
+ clearStreamingText,
1022
+ setIsThinking,
1023
+ setContextState,
1024
+ registry
1025
+ ]
1026
+ );
1027
+ }
1028
+
1029
+ // src/ui/hooks/useCommandRegistry.ts
1030
+ import { useRef as useRef2 } from "react";
1031
+ import { homedir as homedir2 } from "os";
1032
+ import { join as join3, dirname as dirname2 } from "path";
1033
+ import { BundlePluginLoader } from "@robota-sdk/agent-sdk";
1034
+
1035
+ // src/commands/command-registry.ts
1036
+ var CommandRegistry = class {
1037
+ sources = [];
1038
+ addSource(source) {
1039
+ this.sources.push(source);
1040
+ }
1041
+ /** Get all commands, optionally filtered by prefix */
1042
+ getCommands(filter) {
1043
+ const all = [];
1044
+ for (const source of this.sources) {
1045
+ all.push(...source.getCommands());
1046
+ }
1047
+ if (!filter) return all;
1048
+ const lower = filter.toLowerCase();
1049
+ return all.filter((cmd) => cmd.name.toLowerCase().startsWith(lower));
1050
+ }
1051
+ /** Resolve a short name to its fully qualified plugin:name form */
1052
+ resolveQualifiedName(shortName) {
1053
+ const matches = this.getCommands().filter(
1054
+ (c) => c.source === "plugin" && c.name.includes(":") && c.name.endsWith(`:${shortName}`)
1055
+ );
1056
+ if (matches.length !== 1) return null;
1057
+ return matches[0].name;
1058
+ }
1059
+ /** Get subcommands for a specific command */
1060
+ getSubcommands(commandName) {
1061
+ const lower = commandName.toLowerCase();
1062
+ for (const source of this.sources) {
1063
+ for (const cmd of source.getCommands()) {
1064
+ if (cmd.name.toLowerCase() === lower && cmd.subcommands) {
1065
+ return cmd.subcommands;
1066
+ }
1067
+ }
1068
+ }
1069
+ return [];
1070
+ }
1071
+ };
1072
+
1073
+ // src/commands/builtin-source.ts
1074
+ import { CLAUDE_MODELS, formatTokenCount } from "@robota-sdk/agent-core";
1075
+ function buildModelSubcommands() {
1076
+ const seen = /* @__PURE__ */ new Set();
1077
+ const commands = [];
1078
+ for (const model of Object.values(CLAUDE_MODELS)) {
1079
+ if (seen.has(model.name)) continue;
1080
+ seen.add(model.name);
1081
+ commands.push({
1082
+ name: model.id,
1083
+ description: `${model.name} (${formatTokenCount(model.contextWindow).toUpperCase()})`,
1084
+ source: "builtin"
1085
+ });
1086
+ }
1087
+ return commands;
1088
+ }
1089
+ function createBuiltinCommands() {
1090
+ return [
1091
+ { name: "help", description: "Show available commands", source: "builtin" },
1092
+ { name: "clear", description: "Clear conversation history", source: "builtin" },
1093
+ {
1094
+ name: "mode",
1095
+ description: "Permission mode",
1096
+ source: "builtin",
1097
+ subcommands: [
1098
+ { name: "plan", description: "Plan only, no execution", source: "builtin" },
1099
+ { name: "default", description: "Ask before risky actions", source: "builtin" },
1100
+ { name: "acceptEdits", description: "Auto-approve file edits", source: "builtin" },
1101
+ { name: "bypassPermissions", description: "Skip all permission checks", source: "builtin" }
1102
+ ]
1103
+ },
1104
+ {
1105
+ name: "model",
1106
+ description: "Select AI model",
1107
+ source: "builtin",
1108
+ subcommands: buildModelSubcommands()
1109
+ },
1110
+ {
1111
+ name: "language",
1112
+ description: "Set response language",
1113
+ source: "builtin",
1114
+ subcommands: [
1115
+ { name: "ko", description: "Korean", source: "builtin" },
1116
+ { name: "en", description: "English", source: "builtin" },
1117
+ { name: "ja", description: "Japanese", source: "builtin" },
1118
+ { name: "zh", description: "Chinese", source: "builtin" }
1119
+ ]
1120
+ },
1121
+ { name: "compact", description: "Compress context window", source: "builtin" },
1122
+ { name: "cost", description: "Show session info", source: "builtin" },
1123
+ { name: "context", description: "Context window info", source: "builtin" },
1124
+ { name: "permissions", description: "Permission rules", source: "builtin" },
1125
+ { name: "plugin", description: "Manage plugins", source: "builtin" },
1126
+ { name: "reload-plugins", description: "Reload all plugin resources", source: "builtin" },
1127
+ { name: "reset", description: "Delete settings and exit", source: "builtin" },
1128
+ { name: "exit", description: "Exit CLI", source: "builtin" }
1129
+ ];
1130
+ }
1131
+ var BuiltinCommandSource = class {
1132
+ name = "builtin";
1133
+ commands;
1134
+ constructor() {
1135
+ this.commands = createBuiltinCommands();
1136
+ }
1137
+ getCommands() {
1138
+ return this.commands;
1139
+ }
1140
+ };
1141
+
1142
+ // src/commands/skill-source.ts
1143
+ import { readdirSync, readFileSync as readFileSync3, existsSync as existsSync2 } from "fs";
1144
+ import { join as join2, basename } from "path";
1145
+ import { homedir } from "os";
1146
+ var BOOLEAN_KEYS = /* @__PURE__ */ new Set(["disable-model-invocation", "user-invocable"]);
1147
+ var LIST_KEYS = /* @__PURE__ */ new Set(["allowed-tools"]);
1148
+ function kebabToCamel(key) {
1149
+ return key.replace(/-([a-z])/g, (_match, letter) => letter.toUpperCase());
1150
+ }
1151
+ function parseFrontmatter(content) {
1152
+ const lines = content.split("\n");
1153
+ if (lines[0]?.trim() !== "---") return null;
1154
+ const result = {};
1155
+ for (let i = 1; i < lines.length; i++) {
1156
+ const line = lines[i];
1157
+ if (line.trim() === "---") break;
1158
+ const match = line.match(/^([a-z][a-z0-9-]*):\s*(.+)/);
1159
+ if (!match) continue;
1160
+ const key = match[1];
1161
+ const rawValue = match[2].trim();
1162
+ const camelKey = kebabToCamel(key);
1163
+ if (BOOLEAN_KEYS.has(key)) {
1164
+ result[camelKey] = rawValue === "true";
1165
+ } else if (LIST_KEYS.has(key)) {
1166
+ result[camelKey] = rawValue.split(",").map((s) => s.trim());
1167
+ } else {
1168
+ result[camelKey] = rawValue;
1169
+ }
1170
+ }
1171
+ return Object.keys(result).length > 0 ? result : null;
1172
+ }
1173
+ function buildCommand(frontmatter, content, fallbackName) {
1174
+ const cmd = {
1175
+ name: frontmatter?.name ?? fallbackName,
1176
+ description: frontmatter?.description ?? `Skill: ${fallbackName}`,
1177
+ source: "skill",
1178
+ skillContent: content
1179
+ };
1180
+ if (frontmatter?.argumentHint !== void 0) cmd.argumentHint = frontmatter.argumentHint;
1181
+ if (frontmatter?.disableModelInvocation !== void 0)
1182
+ cmd.disableModelInvocation = frontmatter.disableModelInvocation;
1183
+ if (frontmatter?.userInvocable !== void 0) cmd.userInvocable = frontmatter.userInvocable;
1184
+ if (frontmatter?.allowedTools !== void 0) cmd.allowedTools = frontmatter.allowedTools;
1185
+ if (frontmatter?.model !== void 0) cmd.model = frontmatter.model;
1186
+ if (frontmatter?.effort !== void 0) cmd.effort = frontmatter.effort;
1187
+ if (frontmatter?.context !== void 0) cmd.context = frontmatter.context;
1188
+ if (frontmatter?.agent !== void 0) cmd.agent = frontmatter.agent;
1189
+ return cmd;
1190
+ }
1191
+ function scanSkillsDir(skillsDir) {
1192
+ if (!existsSync2(skillsDir)) return [];
1193
+ const commands = [];
1194
+ const entries = readdirSync(skillsDir, { withFileTypes: true });
1195
+ for (const entry of entries) {
1196
+ if (!entry.isDirectory()) continue;
1197
+ const skillFile = join2(skillsDir, entry.name, "SKILL.md");
1198
+ if (!existsSync2(skillFile)) continue;
1199
+ const content = readFileSync3(skillFile, "utf-8");
1200
+ const frontmatter = parseFrontmatter(content);
1201
+ commands.push(buildCommand(frontmatter, content, entry.name));
1202
+ }
1203
+ return commands;
1204
+ }
1205
+ function scanCommandsDir(commandsDir) {
1206
+ if (!existsSync2(commandsDir)) return [];
1207
+ const commands = [];
1208
+ const entries = readdirSync(commandsDir, { withFileTypes: true });
1209
+ for (const entry of entries) {
1210
+ if (!entry.isFile() || !entry.name.endsWith(".md")) continue;
1211
+ const filePath = join2(commandsDir, entry.name);
1212
+ const content = readFileSync3(filePath, "utf-8");
1213
+ const frontmatter = parseFrontmatter(content);
1214
+ const fallbackName = basename(entry.name, ".md");
1215
+ commands.push(buildCommand(frontmatter, content, fallbackName));
1216
+ }
1217
+ return commands;
1218
+ }
1219
+ var SkillCommandSource = class {
1220
+ name = "skill";
1221
+ cwd;
1222
+ home;
1223
+ cachedCommands = null;
1224
+ constructor(cwd, home) {
1225
+ this.cwd = cwd;
1226
+ this.home = home ?? homedir();
1227
+ }
1228
+ getCommands() {
1229
+ if (this.cachedCommands) return this.cachedCommands;
1230
+ const sources = [
1231
+ scanSkillsDir(join2(this.cwd, ".claude", "skills")),
1232
+ // 1. project .claude/skills
1233
+ scanCommandsDir(join2(this.cwd, ".claude", "commands")),
1234
+ // 2. project .claude/commands (legacy)
1235
+ scanSkillsDir(join2(this.home, ".robota", "skills")),
1236
+ // 3. user ~/.robota/skills
1237
+ scanSkillsDir(join2(this.cwd, ".agents", "skills"))
1238
+ // 4. project .agents/skills
1239
+ ];
1240
+ const seen = /* @__PURE__ */ new Set();
1241
+ const merged = [];
1242
+ for (const commands of sources) {
1243
+ for (const cmd of commands) {
1244
+ if (!seen.has(cmd.name)) {
1245
+ seen.add(cmd.name);
1246
+ merged.push(cmd);
1247
+ }
1248
+ }
1249
+ }
1250
+ this.cachedCommands = merged;
1251
+ return this.cachedCommands;
1252
+ }
1253
+ /** Get skills that models can invoke (excludes disableModelInvocation: true) */
1254
+ getModelInvocableSkills() {
1255
+ return this.getCommands().filter((cmd) => cmd.disableModelInvocation !== true);
1256
+ }
1257
+ /** Get skills that users can invoke (excludes userInvocable: false) */
1258
+ getUserInvocableSkills() {
1259
+ return this.getCommands().filter((cmd) => cmd.userInvocable !== false);
1260
+ }
1261
+ };
1262
+
1263
+ // src/commands/plugin-source.ts
1264
+ var PluginCommandSource = class {
1265
+ name = "plugin";
1266
+ plugins;
1267
+ constructor(plugins) {
1268
+ this.plugins = plugins;
1269
+ }
1270
+ getCommands() {
1271
+ const commands = [];
1272
+ for (const plugin of this.plugins) {
1273
+ for (const skill of plugin.skills) {
1274
+ const baseName = skill.name.includes("@") ? skill.name.split("@")[0] : skill.name;
1275
+ commands.push({
1276
+ name: baseName,
1277
+ description: `(${plugin.manifest.name}) ${skill.description}`,
1278
+ source: "plugin",
1279
+ skillContent: skill.skillContent,
1280
+ pluginDir: plugin.pluginDir
1281
+ });
1282
+ }
1283
+ for (const cmd of plugin.commands) {
1284
+ commands.push({
1285
+ name: cmd.name,
1286
+ description: cmd.description,
1287
+ source: "plugin",
1288
+ skillContent: cmd.skillContent,
1289
+ pluginDir: plugin.pluginDir
1290
+ });
1291
+ }
1292
+ }
1293
+ return commands;
1294
+ }
1295
+ };
1296
+
1297
+ // src/ui/hooks/useCommandRegistry.ts
1298
+ function buildPluginEnv(plugin) {
1299
+ const dataDir = join3(dirname2(dirname2(plugin.pluginDir)), "data", plugin.manifest.name);
1300
+ return {
1301
+ CLAUDE_PLUGIN_ROOT: plugin.pluginDir,
1302
+ CLAUDE_PLUGIN_PATH: plugin.pluginDir,
1303
+ CLAUDE_PLUGIN_DATA: dataDir
1304
+ };
1305
+ }
1306
+ function mergePluginHooks(plugins) {
1307
+ const merged = {};
1308
+ for (const plugin of plugins) {
1309
+ const hooksObj = plugin.hooks;
1310
+ if (!hooksObj) continue;
1311
+ const pluginEnv = buildPluginEnv(plugin);
1312
+ const innerHooks = hooksObj.hooks ?? hooksObj;
1313
+ for (const [event, groups] of Object.entries(innerHooks)) {
1314
+ if (!Array.isArray(groups)) continue;
1315
+ if (!merged[event]) merged[event] = [];
1316
+ const resolved = groups.map((group) => {
1317
+ const resolved2 = resolvePluginRoot(group, plugin.pluginDir);
1318
+ if (typeof resolved2 === "object" && resolved2 !== null) {
1319
+ resolved2.env = pluginEnv;
1320
+ }
1321
+ return resolved2;
1322
+ });
1323
+ merged[event].push(...resolved);
1324
+ }
1325
+ }
1326
+ return merged;
1327
+ }
1328
+ function resolvePluginRoot(group, pluginDir) {
1329
+ if (typeof group !== "object" || group === null) return group;
1330
+ const obj = group;
1331
+ if (Array.isArray(obj.hooks)) {
1332
+ return {
1333
+ ...obj,
1334
+ hooks: obj.hooks.map((h) => {
1335
+ if (typeof h !== "object" || h === null) return h;
1336
+ const hook = h;
1337
+ if (typeof hook.command === "string") {
1338
+ return {
1339
+ ...hook,
1340
+ command: hook.command.replace(/\$\{CLAUDE_PLUGIN_ROOT\}/g, pluginDir)
1341
+ };
1342
+ }
1343
+ return hook;
1344
+ })
1345
+ };
1346
+ }
1347
+ return group;
1348
+ }
1349
+ function useCommandRegistry(cwd) {
1350
+ const resultRef = useRef2(null);
1351
+ if (resultRef.current === null) {
1352
+ const registry = new CommandRegistry();
1353
+ registry.addSource(new BuiltinCommandSource());
1354
+ registry.addSource(new SkillCommandSource(cwd));
1355
+ let pluginHooks = {};
1356
+ const pluginsDir = join3(homedir2(), ".robota", "plugins");
1357
+ const loader = new BundlePluginLoader(pluginsDir);
1358
+ try {
1359
+ const plugins = loader.loadPluginsSync();
1360
+ if (plugins.length > 0) {
1361
+ registry.addSource(new PluginCommandSource(plugins));
1362
+ pluginHooks = mergePluginHooks(plugins);
1363
+ }
1364
+ } catch {
1365
+ }
1366
+ resultRef.current = { registry, pluginHooks };
1367
+ }
1368
+ return resultRef.current;
1369
+ }
1370
+
1371
+ // src/ui/hooks/usePluginCallbacks.ts
1372
+ import { useMemo } from "react";
1373
+ import { homedir as homedir3 } from "os";
1374
+ import { join as join4 } from "path";
1375
+ import {
1376
+ PluginSettingsStore,
1377
+ BundlePluginLoader as BundlePluginLoader2,
1378
+ BundlePluginInstaller,
1379
+ MarketplaceClient
1380
+ } from "@robota-sdk/agent-sdk";
1381
+ function usePluginCallbacks(cwd) {
1382
+ return useMemo(() => {
1383
+ const home = homedir3();
1384
+ const pluginsDir = join4(home, ".robota", "plugins");
1385
+ const userSettingsPath = join4(home, ".robota", "settings.json");
1386
+ const settingsStore = new PluginSettingsStore(userSettingsPath);
1387
+ const marketplace = new MarketplaceClient({ pluginsDir });
1388
+ const installer = new BundlePluginInstaller({
1389
+ pluginsDir,
1390
+ settingsStore,
1391
+ marketplaceClient: marketplace
1392
+ });
1393
+ const loader = new BundlePluginLoader2(pluginsDir);
1394
+ return {
1395
+ listInstalled: async () => {
1396
+ const plugins = await loader.loadAll();
1397
+ const enabledMap = settingsStore.getEnabledPlugins();
1398
+ return plugins.map((p) => {
1399
+ const parts = p.pluginDir.split("/");
1400
+ const cacheIdx = parts.indexOf("cache");
1401
+ const marketplaceName = cacheIdx >= 0 ? parts[cacheIdx + 1] : "";
1402
+ const fullId = marketplaceName ? `${p.manifest.name}@${marketplaceName}` : p.manifest.name;
1403
+ return {
1404
+ name: fullId,
1405
+ description: p.manifest.description,
1406
+ enabled: enabledMap[fullId] !== false && enabledMap[p.manifest.name] !== false
1407
+ };
1408
+ });
1409
+ },
1410
+ listAvailablePlugins: async (marketplaceName) => {
1411
+ let manifest;
1412
+ try {
1413
+ manifest = marketplace.fetchManifest(marketplaceName);
1414
+ } catch {
1415
+ return [];
1416
+ }
1417
+ const installed = installer.getInstalledPlugins();
1418
+ const installedNames = new Set(Object.values(installed).map((r) => r.pluginName));
1419
+ return manifest.plugins.map((p) => ({
1420
+ name: p.name,
1421
+ description: p.description,
1422
+ installed: installedNames.has(p.name)
1423
+ }));
1424
+ },
1425
+ install: async (pluginId, scope) => {
1426
+ const [name, marketplaceName] = pluginId.split("@");
1427
+ if (!name || !marketplaceName) {
1428
+ throw new Error("Plugin ID must be in format: name@marketplace");
1429
+ }
1430
+ if (scope === "project") {
1431
+ const projectPluginsDir = join4(cwd, ".robota", "plugins");
1432
+ const projectInstaller = new BundlePluginInstaller({
1433
+ pluginsDir: projectPluginsDir,
1434
+ settingsStore,
1435
+ marketplaceClient: marketplace
1436
+ });
1437
+ await projectInstaller.install(name, marketplaceName);
1438
+ } else {
1439
+ await installer.install(name, marketplaceName);
1440
+ }
1441
+ },
1442
+ uninstall: async (pluginId) => {
1443
+ await installer.uninstall(pluginId);
1444
+ },
1445
+ enable: async (pluginId) => {
1446
+ await installer.enable(pluginId);
1447
+ },
1448
+ disable: async (pluginId) => {
1449
+ await installer.disable(pluginId);
1450
+ },
1451
+ marketplaceAdd: async (source) => {
1452
+ if (source.includes("/") && !source.includes(":")) {
1453
+ return marketplace.addMarketplace({ type: "github", repo: source });
1454
+ } else {
1455
+ return marketplace.addMarketplace({ type: "git", url: source });
1456
+ }
1457
+ },
1458
+ marketplaceRemove: async (name) => {
1459
+ const installedFromMarketplace = installer.getPluginsByMarketplace(name);
1460
+ for (const record of installedFromMarketplace) {
1461
+ await installer.uninstall(`${record.pluginName}@${record.marketplace}`);
1462
+ }
1463
+ marketplace.removeMarketplace(name);
1464
+ },
1465
+ marketplaceUpdate: async (name) => {
1466
+ marketplace.updateMarketplace(name);
1467
+ },
1468
+ marketplaceList: async () => {
1469
+ return marketplace.listMarketplaces().map((m) => ({
1470
+ name: m.name,
1471
+ type: m.source.type
1472
+ }));
1473
+ },
1474
+ reloadPlugins: async () => {
1475
+ }
1476
+ };
1477
+ }, [cwd]);
1478
+ }
1479
+
1480
+ // src/ui/MessageList.tsx
1481
+ import React2 from "react";
1482
+ import { Box as Box2, Text as Text2 } from "ink";
1483
+ import { isToolMessage, isAssistantMessage } from "@robota-sdk/agent-core";
1484
+
1485
+ // src/ui/render-markdown.ts
1486
+ import { marked } from "marked";
1487
+ import TerminalRenderer from "marked-terminal";
1488
+ marked.setOptions({
1489
+ renderer: new TerminalRenderer()
1490
+ });
1491
+ function renderMarkdown(md) {
1492
+ const result = marked.parse(md);
1493
+ return typeof result === "string" ? result.trimEnd() : md;
1494
+ }
1495
+
1496
+ // src/ui/DiffBlock.tsx
1497
+ import { Box, Text } from "ink";
1498
+ import { jsxs } from "react/jsx-runtime";
1499
+ var MAX_DIFF_LINES = 12;
1500
+ var TRUNCATED_SHOW = 10;
1501
+ function DiffBlock({ file, lines }) {
1502
+ const truncated = lines.length > MAX_DIFF_LINES;
1503
+ const visible = truncated ? lines.slice(0, TRUNCATED_SHOW) : lines;
1504
+ const remaining = lines.length - TRUNCATED_SHOW;
1505
+ const maxLineNum = Math.max(...visible.map((l) => l.lineNumber), 0);
1506
+ const numWidth = String(maxLineNum).length;
1507
+ return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", marginLeft: 4, children: [
1508
+ file && /* @__PURE__ */ jsxs(Text, { color: "white", dimColor: true, children: [
1509
+ "\u2502 ",
1510
+ file
1511
+ ] }),
1512
+ visible.map((line, i) => {
1513
+ const lineNum = String(line.lineNumber).padStart(numWidth, " ");
1514
+ if (line.type === "context") {
1515
+ return /* @__PURE__ */ jsxs(Text, { color: "white", dimColor: true, children: [
1516
+ "\u2502 ",
1517
+ lineNum,
1518
+ " ",
1519
+ line.text
1520
+ ] }, i);
1521
+ }
1522
+ const prefix = line.type === "remove" ? "-" : "+";
1523
+ const bgColor = line.type === "remove" ? "#5c1a1a" : "#1a3d1a";
1524
+ const fgColor = line.type === "remove" ? "#ff9999" : "#99ff99";
1525
+ return /* @__PURE__ */ jsxs(Text, { color: fgColor, backgroundColor: bgColor, children: [
1526
+ "\u2502 ",
1527
+ lineNum,
1528
+ " ",
1529
+ prefix,
1530
+ " ",
1531
+ line.text
1532
+ ] }, i);
1533
+ }),
1534
+ truncated && /* @__PURE__ */ jsxs(Text, { color: "white", dimColor: true, children: [
1535
+ "\u2502 ... and ",
1536
+ remaining,
1537
+ " more lines"
1538
+ ] })
1539
+ ] });
1540
+ }
1541
+
1542
+ // src/ui/MessageList.tsx
1543
+ import { Fragment, jsx, jsxs as jsxs2 } from "react/jsx-runtime";
1544
+ function RoleLabel({ role }) {
1545
+ switch (role) {
1546
+ case "user":
1547
+ return /* @__PURE__ */ jsxs2(Text2, { color: "green", bold: true, children: [
1548
+ "You:",
1549
+ " "
1550
+ ] });
1551
+ case "assistant":
1552
+ return /* @__PURE__ */ jsxs2(Text2, { color: "cyan", bold: true, children: [
1553
+ "Robota:",
1554
+ " "
1555
+ ] });
1556
+ case "system":
1557
+ return /* @__PURE__ */ jsxs2(Text2, { color: "yellow", bold: true, children: [
1558
+ "System:",
1559
+ " "
1560
+ ] });
1561
+ case "tool":
1562
+ return /* @__PURE__ */ jsxs2(Text2, { color: "white", bold: true, children: [
1563
+ "Tool:",
1564
+ " "
1565
+ ] });
1566
+ }
1567
+ }
1568
+ function ToolMessage({ message }) {
1569
+ if (!isToolMessage(message)) {
1570
+ return /* @__PURE__ */ jsx(Fragment, {});
1571
+ }
1572
+ const toolName = message.name;
1573
+ const content = message.content;
1574
+ let summaries = null;
1575
+ try {
1576
+ const parsed = JSON.parse(content);
1577
+ if (Array.isArray(parsed) && parsed.length > 0 && typeof parsed[0].line === "string") {
1578
+ summaries = parsed;
1579
+ }
1580
+ } catch {
1581
+ }
1582
+ if (summaries) {
1583
+ return /* @__PURE__ */ jsxs2(Box2, { flexDirection: "column", marginBottom: 1, children: [
1584
+ /* @__PURE__ */ jsxs2(Box2, { children: [
1585
+ /* @__PURE__ */ jsxs2(Text2, { color: "white", bold: true, children: [
1586
+ "Tool:",
1587
+ " "
1588
+ ] }),
1589
+ toolName && /* @__PURE__ */ jsxs2(Text2, { color: "white", dimColor: true, children: [
1590
+ "[",
1591
+ toolName,
1592
+ "]"
1593
+ ] })
1594
+ ] }),
1595
+ /* @__PURE__ */ jsx(Text2, { children: " " }),
1596
+ summaries.map((s, i) => /* @__PURE__ */ jsxs2(Box2, { flexDirection: "column", children: [
1597
+ /* @__PURE__ */ jsxs2(Text2, { color: "green", children: [
1598
+ " ",
1599
+ "\u2713",
1600
+ " ",
1601
+ s.line
1602
+ ] }),
1603
+ s.diffLines && s.diffLines.length > 0 && /* @__PURE__ */ jsx(DiffBlock, { file: s.diffFile, lines: s.diffLines })
1604
+ ] }, i))
1605
+ ] });
1606
+ }
1607
+ const lines = content.split("\n").filter((l) => l.trim());
1608
+ return /* @__PURE__ */ jsxs2(Box2, { flexDirection: "column", marginBottom: 1, children: [
1609
+ /* @__PURE__ */ jsxs2(Box2, { children: [
1610
+ /* @__PURE__ */ jsxs2(Text2, { color: "white", bold: true, children: [
1611
+ "Tool:",
1612
+ " "
1613
+ ] }),
1614
+ toolName && /* @__PURE__ */ jsxs2(Text2, { color: "white", dimColor: true, children: [
1615
+ "[",
1616
+ toolName,
1617
+ "]"
1618
+ ] })
1619
+ ] }),
1620
+ /* @__PURE__ */ jsx(Text2, { children: " " }),
1621
+ lines.map((line, i) => /* @__PURE__ */ jsxs2(Text2, { color: "green", children: [
1622
+ " ",
1623
+ "\u2713",
1624
+ " ",
1625
+ line
1626
+ ] }, i))
1627
+ ] });
1628
+ }
1629
+ var MessageItem = React2.memo(function MessageItem2({
1630
+ message
1631
+ }) {
1632
+ if (isToolMessage(message)) {
1633
+ return /* @__PURE__ */ jsx(ToolMessage, { message });
1634
+ }
1635
+ const content = message.content ?? "";
1636
+ const isInterrupted = message.state === "interrupted";
1637
+ return /* @__PURE__ */ jsxs2(Box2, { flexDirection: "column", marginBottom: 1, children: [
1638
+ /* @__PURE__ */ jsx(Box2, { children: /* @__PURE__ */ jsx(RoleLabel, { role: message.role }) }),
1639
+ /* @__PURE__ */ jsx(Text2, { children: " " }),
1640
+ /* @__PURE__ */ jsx(Box2, { marginLeft: 2, children: /* @__PURE__ */ jsx(Text2, { wrap: "wrap", children: isAssistantMessage(message) ? renderMarkdown(content + (isInterrupted ? "\n\n_(interrupted)_" : "")) : content }) })
1641
+ ] });
1642
+ });
1643
+ function MessageList({ messages }) {
1644
+ return /* @__PURE__ */ jsx(Box2, { flexDirection: "column", children: messages.map((msg) => /* @__PURE__ */ jsx(MessageItem, { message: msg }, msg.id)) });
1645
+ }
1646
+
1647
+ // src/ui/StatusBar.tsx
1648
+ import { Box as Box3, Text as Text3 } from "ink";
1649
+ import { formatTokenCount as formatTokenCount2 } from "@robota-sdk/agent-core";
1650
+ import { jsx as jsx2, jsxs as jsxs3 } from "react/jsx-runtime";
1651
+ var CONTEXT_YELLOW_THRESHOLD = 70;
1652
+ var CONTEXT_RED_THRESHOLD = 90;
1653
+ function getContextColor(percentage) {
1654
+ if (percentage >= CONTEXT_RED_THRESHOLD) return "red";
1655
+ if (percentage >= CONTEXT_YELLOW_THRESHOLD) return "yellow";
1656
+ return "green";
1657
+ }
1658
+ function StatusBar({
1659
+ permissionMode,
1660
+ modelName,
1661
+ sessionId: _sessionId,
1662
+ messageCount,
1663
+ isThinking,
1664
+ contextPercentage,
1665
+ contextUsedTokens,
1666
+ contextMaxTokens
1667
+ }) {
1668
+ const contextColor = getContextColor(contextPercentage);
1669
+ return /* @__PURE__ */ jsxs3(
1670
+ Box3,
1671
+ {
1672
+ borderStyle: "single",
1673
+ borderColor: "gray",
1674
+ paddingLeft: 1,
1675
+ paddingRight: 1,
1676
+ justifyContent: "space-between",
1677
+ children: [
1678
+ /* @__PURE__ */ jsxs3(Text3, { children: [
1679
+ /* @__PURE__ */ jsx2(Text3, { color: "cyan", bold: true, children: "Mode:" }),
1680
+ " ",
1681
+ /* @__PURE__ */ jsx2(Text3, { children: permissionMode }),
1682
+ " | ",
1683
+ /* @__PURE__ */ jsx2(Text3, { dimColor: true, children: modelName }),
1684
+ " | ",
1685
+ /* @__PURE__ */ jsxs3(Text3, { color: contextColor, children: [
1686
+ "Context: ",
1687
+ Math.round(contextPercentage),
1688
+ "% (",
1689
+ formatTokenCount2(contextUsedTokens),
1690
+ "/",
1691
+ formatTokenCount2(contextMaxTokens),
1692
+ ")"
1693
+ ] })
1694
+ ] }),
1695
+ /* @__PURE__ */ jsxs3(Text3, { children: [
1696
+ isThinking && /* @__PURE__ */ jsx2(Text3, { color: "yellow", children: "Thinking... " }),
1697
+ /* @__PURE__ */ jsxs3(Text3, { dimColor: true, children: [
1698
+ "msgs: ",
1699
+ messageCount
1700
+ ] })
1701
+ ] })
1702
+ ]
1703
+ }
1704
+ );
1705
+ }
1706
+
1707
+ // src/ui/InputArea.tsx
1708
+ import React5, { useState as useState5, useCallback as useCallback5, useMemo as useMemo2, useRef as useRef4 } from "react";
1709
+ import { Box as Box5, Text as Text7, useInput as useInput2, useStdout } from "ink";
1710
+
1711
+ // src/ui/CjkTextInput.tsx
1712
+ import { useRef as useRef3, useState as useState3 } from "react";
1713
+ import { Text as Text4, useInput } from "ink";
1714
+ import chalk from "chalk";
1715
+ import stringWidth from "string-width";
1716
+ import { jsx as jsx3 } from "react/jsx-runtime";
1717
+ var PASTE_START = "[200~";
1718
+ var PASTE_END = "[201~";
1719
+ function filterPrintable(input) {
1720
+ if (!input || input.length === 0) return "";
1721
+ return input.replace(/[\x00-\x1f\x7f]/g, "");
1722
+ }
1723
+ function insertAtCursor(value, cursor, input) {
1724
+ const next = value.slice(0, cursor) + input + value.slice(cursor);
1725
+ return { value: next, cursor: cursor + input.length };
1726
+ }
1727
+ function displayOffset(chars, charIndex, width) {
1728
+ let offset = 0;
1729
+ for (let i = 0; i < charIndex && i < chars.length; i++) {
1730
+ const w = stringWidth(chars[i]);
1731
+ const col = offset % width;
1732
+ if (col + w > width) offset += width - col;
1733
+ offset += w;
1734
+ }
1735
+ return offset;
1736
+ }
1737
+ function charIndexAtDisplayOffset(chars, target, width) {
1738
+ let offset = 0;
1739
+ for (let i = 0; i < chars.length; i++) {
1740
+ if (offset >= target) return i;
1741
+ const w = stringWidth(chars[i]);
1742
+ const col = offset % width;
1743
+ if (col + w > width) offset += width - col;
1744
+ offset += w;
1745
+ }
1746
+ return chars.length;
1747
+ }
1748
+ function CjkTextInput({
1749
+ value,
1750
+ onChange,
1751
+ onSubmit,
1752
+ onPaste,
1753
+ placeholder = "",
1754
+ focus = true,
1755
+ showCursor = true,
1756
+ availableWidth
1757
+ }) {
1758
+ const valueRef = useRef3(value);
1759
+ const cursorRef = useRef3(value.length);
1760
+ const [, forceRender] = useState3(0);
1761
+ const isPastingRef = useRef3(false);
1762
+ const pasteBufferRef = useRef3("");
1763
+ if (value !== valueRef.current) {
1764
+ valueRef.current = value;
1765
+ if (cursorRef.current > value.length) {
1766
+ cursorRef.current = value.length;
1767
+ }
1768
+ }
1769
+ useInput(
1770
+ (input, key) => {
1771
+ try {
1772
+ if (input === PASTE_START || input.startsWith(PASTE_START)) {
1773
+ isPastingRef.current = true;
1774
+ const afterMarker = input.slice(PASTE_START.length);
1775
+ if (afterMarker.length > 0) {
1776
+ pasteBufferRef.current += afterMarker;
1777
+ }
1778
+ return;
1779
+ }
1780
+ if (isPastingRef.current) {
1781
+ if (input === PASTE_END || input.includes(PASTE_END)) {
1782
+ const beforeMarker = input.split(PASTE_END)[0] ?? "";
1783
+ pasteBufferRef.current += beforeMarker;
1784
+ const text = pasteBufferRef.current.replace(/\r\n?/g, "\n");
1785
+ pasteBufferRef.current = "";
1786
+ isPastingRef.current = false;
1787
+ if (text.length > 0) {
1788
+ if (text.includes("\n") && onPaste) {
1789
+ onPaste(text);
1790
+ } else {
1791
+ const printable2 = filterPrintable(text);
1792
+ if (printable2.length > 0) {
1793
+ const result2 = insertAtCursor(valueRef.current, cursorRef.current, printable2);
1794
+ cursorRef.current = result2.cursor;
1795
+ valueRef.current = result2.value;
1796
+ onChange(result2.value);
1797
+ }
1798
+ }
1799
+ }
1800
+ } else {
1801
+ pasteBufferRef.current += input;
1802
+ }
1803
+ return;
1804
+ }
1805
+ if (key.ctrl && input === "c" || key.tab || key.shift && key.tab) {
1806
+ return;
1807
+ }
1808
+ if (key.upArrow || key.downArrow) {
1809
+ if (availableWidth && availableWidth > 0) {
1810
+ const chars = [...valueRef.current];
1811
+ const offset = displayOffset(chars, cursorRef.current, availableWidth);
1812
+ const target = key.upArrow ? offset - availableWidth : offset + availableWidth;
1813
+ if (target >= 0) {
1814
+ const newCursor = charIndexAtDisplayOffset(chars, target, availableWidth);
1815
+ if (newCursor !== cursorRef.current) {
1816
+ cursorRef.current = newCursor;
1817
+ forceRender((n) => n + 1);
1818
+ }
1819
+ }
1820
+ }
1821
+ return;
1822
+ }
1823
+ if (key.return) {
1824
+ onSubmit?.(valueRef.current);
1825
+ return;
1826
+ }
1827
+ if (input.length > 1 && (input.includes("\n") || input.includes("\r")) && onPaste) {
1828
+ onPaste(input.replace(/\r\n?/g, "\n"));
1829
+ return;
1830
+ }
1831
+ if (key.leftArrow) {
1832
+ if (cursorRef.current > 0) {
1833
+ cursorRef.current -= 1;
1834
+ forceRender((n) => n + 1);
1835
+ }
1836
+ return;
1837
+ }
1838
+ if (key.rightArrow) {
1839
+ if (cursorRef.current < valueRef.current.length) {
1840
+ cursorRef.current += 1;
1841
+ forceRender((n) => n + 1);
1842
+ }
1843
+ return;
1844
+ }
1845
+ if (key.backspace || key.delete) {
1846
+ if (cursorRef.current > 0) {
1847
+ const v = valueRef.current;
1848
+ const next = v.slice(0, cursorRef.current - 1) + v.slice(cursorRef.current);
1849
+ cursorRef.current -= 1;
1850
+ valueRef.current = next;
1851
+ onChange(next);
1852
+ }
1853
+ return;
1854
+ }
1855
+ const printable = filterPrintable(input);
1856
+ if (printable.length === 0) return;
1857
+ const result = insertAtCursor(valueRef.current, cursorRef.current, printable);
1858
+ cursorRef.current = result.cursor;
1859
+ valueRef.current = result.value;
1860
+ onChange(result.value);
1861
+ } catch {
1862
+ }
1863
+ },
1864
+ { isActive: focus }
1865
+ );
1866
+ return /* @__PURE__ */ jsx3(Text4, { children: renderWithCursor(valueRef.current, cursorRef.current, placeholder, showCursor && focus) });
1867
+ }
1868
+ function renderWithCursor(value, cursorOffset, placeholder, showCursor) {
1869
+ if (!showCursor) {
1870
+ return value.length > 0 ? value : placeholder ? chalk.gray(placeholder) : "";
1871
+ }
1872
+ if (value.length === 0) {
1873
+ if (placeholder.length > 0) {
1874
+ return chalk.inverse(placeholder[0]) + chalk.gray(placeholder.slice(1));
1875
+ }
1876
+ return chalk.inverse(" ");
1877
+ }
1878
+ const chars = [...value];
1879
+ let rendered = "";
1880
+ for (let i = 0; i < chars.length; i++) {
1881
+ const char = chars[i] ?? "";
1882
+ rendered += i === cursorOffset ? chalk.inverse(char) : char;
1883
+ }
1884
+ if (cursorOffset >= chars.length) {
1885
+ rendered += chalk.inverse(" ");
1886
+ }
1887
+ return rendered;
1888
+ }
1889
+
1890
+ // src/ui/WaveText.tsx
1891
+ import { useState as useState4, useEffect } from "react";
1892
+ import { Text as Text5 } from "ink";
1893
+ import { jsx as jsx4 } from "react/jsx-runtime";
1894
+ var WAVE_COLORS = ["#666666", "#888888", "#aaaaaa", "#888888"];
1895
+ var INTERVAL_MS = 400;
1896
+ var CHARS_PER_GROUP = 4;
1897
+ function WaveText({ text }) {
1898
+ const [tick, setTick] = useState4(0);
1899
+ useEffect(() => {
1900
+ const timer = setInterval(() => {
1901
+ setTick((prev) => prev + 1);
1902
+ }, INTERVAL_MS);
1903
+ return () => clearInterval(timer);
1904
+ }, []);
1905
+ const chars = [...text];
1906
+ return /* @__PURE__ */ jsx4(Text5, { children: chars.map((char, i) => {
1907
+ const group = Math.floor(i / CHARS_PER_GROUP);
1908
+ const colorIndex = (tick + group) % WAVE_COLORS.length;
1909
+ return /* @__PURE__ */ jsx4(Text5, { color: WAVE_COLORS[colorIndex], children: char }, i);
1910
+ }) });
1911
+ }
1912
+
1913
+ // src/ui/SlashAutocomplete.tsx
1914
+ import { Box as Box4, Text as Text6 } from "ink";
1915
+ import { jsx as jsx5, jsxs as jsxs4 } from "react/jsx-runtime";
1916
+ var MAX_VISIBLE = 8;
1917
+ function CommandRow(props) {
1918
+ const { cmd, isSelected, showSlash } = props;
1919
+ const indicator = isSelected ? "\u25B8 " : " ";
1920
+ const nameColor = isSelected ? "cyan" : void 0;
1921
+ const dimmed = !isSelected;
1922
+ return /* @__PURE__ */ jsx5(Box4, { children: /* @__PURE__ */ jsxs4(Text6, { color: nameColor, dimColor: dimmed, children: [
1923
+ indicator,
1924
+ showSlash ? `/${cmd.name} ${cmd.description}` : cmd.description
1925
+ ] }) });
1926
+ }
1927
+ function SlashAutocomplete({
1928
+ commands,
1929
+ selectedIndex,
1930
+ visible,
1931
+ isSubcommandMode
1932
+ }) {
1933
+ if (!visible || commands.length === 0) return null;
1934
+ const scrollOffset = computeScrollOffset(selectedIndex, commands.length);
1935
+ const visibleCommands = commands.slice(scrollOffset, scrollOffset + MAX_VISIBLE);
1936
+ return /* @__PURE__ */ jsx5(Box4, { flexDirection: "column", borderStyle: "round", borderColor: "gray", paddingX: 1, children: visibleCommands.map((cmd, i) => /* @__PURE__ */ jsx5(
1937
+ CommandRow,
1938
+ {
1939
+ cmd,
1940
+ isSelected: scrollOffset + i === selectedIndex,
1941
+ showSlash: !isSubcommandMode
1942
+ },
1943
+ cmd.name
1944
+ )) });
1945
+ }
1946
+ function computeScrollOffset(selectedIndex, total) {
1947
+ if (total <= MAX_VISIBLE) return 0;
1948
+ if (selectedIndex < MAX_VISIBLE) return 0;
1949
+ const maxOffset = total - MAX_VISIBLE;
1950
+ return Math.min(selectedIndex - MAX_VISIBLE + 1, maxOffset);
1951
+ }
1952
+
1953
+ // src/utils/paste-labels.ts
1954
+ var PASTE_LABEL_RE = /\[Pasted text #(\d+)(?: \+\d+ lines)?\]/g;
1955
+ function expandPasteLabels(text, store) {
1956
+ return text.replace(PASTE_LABEL_RE, (_, id) => store.get(Number(id)) ?? "");
1957
+ }
1958
+
1959
+ // src/ui/InputArea.tsx
1960
+ import { jsx as jsx6, jsxs as jsxs5 } from "react/jsx-runtime";
1961
+ function parseSlashInput(value) {
1962
+ if (!value.startsWith("/")) return { isSlash: false, parentCommand: "", filter: "" };
1963
+ const afterSlash = value.slice(1);
1964
+ const spaceIndex = afterSlash.indexOf(" ");
1965
+ if (spaceIndex === -1) return { isSlash: true, parentCommand: "", filter: afterSlash };
1966
+ const parent = afterSlash.slice(0, spaceIndex);
1967
+ const rest = afterSlash.slice(spaceIndex + 1);
1968
+ return { isSlash: true, parentCommand: parent, filter: rest };
1969
+ }
1970
+ function useAutocomplete(value, registry) {
1971
+ const [selectedIndex, setSelectedIndex] = useState5(0);
1972
+ const [dismissed, setDismissed] = useState5(false);
1973
+ const prevValueRef = React5.useRef(value);
1974
+ if (prevValueRef.current !== value) {
1975
+ prevValueRef.current = value;
1976
+ if (dismissed) setDismissed(false);
1977
+ }
1978
+ const parsed = parseSlashInput(value);
1979
+ const isSubcommandMode = parsed.isSlash && parsed.parentCommand.length > 0;
1980
+ const filteredCommands = useMemo2(() => {
1981
+ if (!registry || !parsed.isSlash || dismissed) return [];
1982
+ if (isSubcommandMode) {
1983
+ const subs = registry.getSubcommands(parsed.parentCommand);
1984
+ if (subs.length === 0) return [];
1985
+ if (!parsed.filter) return subs;
1986
+ const lower = parsed.filter.toLowerCase();
1987
+ return subs.filter((c) => c.name.toLowerCase().startsWith(lower));
1988
+ }
1989
+ return registry.getCommands(parsed.filter);
1990
+ }, [registry, parsed.isSlash, parsed.parentCommand, parsed.filter, dismissed, isSubcommandMode]);
1991
+ const showPopup = parsed.isSlash && filteredCommands.length > 0 && !dismissed;
1992
+ if (selectedIndex >= filteredCommands.length && filteredCommands.length > 0) {
1993
+ setSelectedIndex(filteredCommands.length - 1);
1994
+ }
1995
+ return {
1996
+ showPopup,
1997
+ filteredCommands,
1998
+ selectedIndex,
1999
+ setSelectedIndex,
2000
+ isSubcommandMode,
2001
+ setShowPopup: (val) => {
2002
+ if (typeof val === "function") {
2003
+ setDismissed((prev) => {
2004
+ const nextVal = val(!prev);
2005
+ return !nextVal;
2006
+ });
2007
+ } else {
2008
+ setDismissed(!val);
2009
+ }
2010
+ }
2011
+ };
2012
+ }
2013
+ var BORDER_HORIZONTAL = 2;
2014
+ var PADDING_LEFT = 1;
2015
+ var PROMPT_WIDTH = 2;
2016
+ var INPUT_AREA_OVERHEAD = BORDER_HORIZONTAL + PADDING_LEFT + PROMPT_WIDTH;
2017
+ function InputArea({
2018
+ onSubmit,
2019
+ onCancelQueue,
2020
+ isDisabled,
2021
+ isAborting,
2022
+ pendingPrompt,
2023
+ registry
2024
+ }) {
2025
+ const [value, setValue] = useState5("");
2026
+ const pasteStore = useRef4(/* @__PURE__ */ new Map());
2027
+ const { stdout } = useStdout();
2028
+ const terminalColumns = stdout?.columns ?? 80;
2029
+ const availableWidth = Math.max(1, terminalColumns - INPUT_AREA_OVERHEAD);
2030
+ const pasteIdRef = useRef4(0);
2031
+ const {
2032
+ showPopup,
2033
+ filteredCommands,
2034
+ selectedIndex,
2035
+ setSelectedIndex,
2036
+ isSubcommandMode,
2037
+ setShowPopup
2038
+ } = useAutocomplete(value, registry);
2039
+ const handlePaste = useCallback5((text) => {
2040
+ pasteIdRef.current += 1;
2041
+ const id = pasteIdRef.current;
2042
+ pasteStore.current.set(id, text);
2043
+ const lineCount = text.split("\n").length;
2044
+ const label = `[Pasted text #${id} +${lineCount} lines]`;
2045
+ setValue((prev) => prev ? `${prev} ${label}` : label);
2046
+ }, []);
2047
+ const handleSubmit = useCallback5(
2048
+ (text) => {
2049
+ const trimmed = text.trim();
2050
+ if (trimmed.length === 0) return;
2051
+ if (showPopup && filteredCommands[selectedIndex]) {
2052
+ selectCommand(filteredCommands[selectedIndex]);
2053
+ return;
2054
+ }
2055
+ const expanded = expandPasteLabels(trimmed, pasteStore.current);
2056
+ setValue("");
2057
+ pasteStore.current.clear();
2058
+ pasteIdRef.current = 0;
2059
+ onSubmit(expanded);
2060
+ },
2061
+ [showPopup, filteredCommands, selectedIndex, onSubmit]
2062
+ );
2063
+ const selectCommand = useCallback5(
2064
+ (cmd) => {
2065
+ const parsed = parseSlashInput(value);
2066
+ if (parsed.parentCommand) {
2067
+ const fullCommand = `/${parsed.parentCommand} ${cmd.name}`;
2068
+ setValue("");
2069
+ onSubmit(fullCommand);
2070
+ return;
2071
+ }
2072
+ if (cmd.subcommands && cmd.subcommands.length > 0) {
2073
+ setValue(`/${cmd.name} `);
2074
+ setSelectedIndex(0);
2075
+ return;
2076
+ }
2077
+ setValue("");
2078
+ onSubmit(`/${cmd.name}`);
2079
+ },
2080
+ [value, onSubmit, setSelectedIndex]
2081
+ );
2082
+ useInput2(
2083
+ (_input, key) => {
2084
+ if (!showPopup) return;
2085
+ if (key.upArrow) {
2086
+ setSelectedIndex((prev) => prev > 0 ? prev - 1 : filteredCommands.length - 1);
2087
+ } else if (key.downArrow) {
2088
+ setSelectedIndex((prev) => prev < filteredCommands.length - 1 ? prev + 1 : 0);
2089
+ } else if (key.escape) {
2090
+ setShowPopup(false);
2091
+ } else if (key.tab) {
2092
+ const cmd = filteredCommands[selectedIndex];
2093
+ if (cmd) selectCommand(cmd);
2094
+ }
2095
+ },
2096
+ { isActive: showPopup && !isDisabled }
2097
+ );
2098
+ useInput2(
2099
+ (_input, key) => {
2100
+ if ((key.backspace || key.delete) && pendingPrompt) {
2101
+ onCancelQueue?.();
2102
+ }
2103
+ },
2104
+ { isActive: !!pendingPrompt }
2105
+ );
2106
+ return /* @__PURE__ */ jsxs5(Box5, { flexDirection: "column", children: [
2107
+ showPopup && /* @__PURE__ */ jsx6(
2108
+ SlashAutocomplete,
2109
+ {
2110
+ commands: filteredCommands,
2111
+ selectedIndex,
2112
+ visible: showPopup,
2113
+ isSubcommandMode
2114
+ }
2115
+ ),
2116
+ /* @__PURE__ */ jsx6(
2117
+ Box5,
2118
+ {
2119
+ borderStyle: "single",
2120
+ borderColor: isAborting ? "yellow" : pendingPrompt ? "cyan" : isDisabled ? "gray" : "green",
2121
+ paddingLeft: 1,
2122
+ children: isAborting ? /* @__PURE__ */ jsx6(Text7, { color: "yellow", children: " Interrupting..." }) : pendingPrompt ? /* @__PURE__ */ jsxs5(Text7, { color: "cyan", children: [
2123
+ " ",
2124
+ "Queued: ",
2125
+ pendingPrompt.length > 50 ? pendingPrompt.slice(0, 47) + "..." : pendingPrompt,
2126
+ " ",
2127
+ /* @__PURE__ */ jsx6(Text7, { dimColor: true, children: "(Backspace to cancel)" })
2128
+ ] }) : isDisabled ? /* @__PURE__ */ jsx6(WaveText, { text: " Waiting for response... (ESC to interrupt)" }) : /* @__PURE__ */ jsxs5(Box5, { children: [
2129
+ /* @__PURE__ */ jsx6(Text7, { color: "green", bold: true, children: "> " }),
2130
+ /* @__PURE__ */ jsx6(
2131
+ CjkTextInput,
2132
+ {
2133
+ value,
2134
+ onChange: setValue,
2135
+ onSubmit: handleSubmit,
2136
+ onPaste: handlePaste,
2137
+ placeholder: "Type a message or /help",
2138
+ availableWidth
2139
+ }
2140
+ )
2141
+ ] })
2142
+ }
2143
+ )
2144
+ ] });
2145
+ }
2146
+
2147
+ // src/ui/ConfirmPrompt.tsx
2148
+ import { useState as useState6, useCallback as useCallback6, useRef as useRef5 } from "react";
2149
+ import { Box as Box6, Text as Text8, useInput as useInput3 } from "ink";
2150
+ import { jsx as jsx7, jsxs as jsxs6 } from "react/jsx-runtime";
2151
+ function ConfirmPrompt({
2152
+ message,
2153
+ options = ["Yes", "No"],
2154
+ onSelect
2155
+ }) {
2156
+ const [selected, setSelected] = useState6(0);
2157
+ const resolvedRef = useRef5(false);
2158
+ const doSelect = useCallback6(
2159
+ (index) => {
2160
+ if (resolvedRef.current) return;
2161
+ resolvedRef.current = true;
2162
+ onSelect(index);
2163
+ },
2164
+ [onSelect]
2165
+ );
2166
+ useInput3((input, key) => {
2167
+ if (resolvedRef.current) return;
2168
+ if (key.leftArrow || key.upArrow) {
2169
+ setSelected((prev) => prev > 0 ? prev - 1 : prev);
2170
+ } else if (key.rightArrow || key.downArrow) {
2171
+ setSelected((prev) => prev < options.length - 1 ? prev + 1 : prev);
2172
+ } else if (key.return) {
2173
+ doSelect(selected);
2174
+ } else if (input === "y" && options.length === 2) {
2175
+ doSelect(0);
2176
+ } else if (input === "n" && options.length === 2) {
2177
+ doSelect(1);
2178
+ }
2179
+ });
2180
+ return /* @__PURE__ */ jsxs6(Box6, { flexDirection: "column", borderStyle: "round", borderColor: "yellow", paddingX: 1, children: [
2181
+ /* @__PURE__ */ jsx7(Text8, { color: "yellow", children: message }),
2182
+ /* @__PURE__ */ jsx7(Box6, { marginTop: 1, children: options.map((opt, i) => /* @__PURE__ */ jsx7(Box6, { marginRight: 2, children: /* @__PURE__ */ jsxs6(Text8, { color: i === selected ? "cyan" : void 0, bold: i === selected, children: [
2183
+ i === selected ? "> " : " ",
2184
+ opt
2185
+ ] }) }, opt)) }),
2186
+ /* @__PURE__ */ jsx7(Text8, { dimColor: true, children: " arrow keys to select, Enter to confirm" })
2187
+ ] });
2188
+ }
2189
+
2190
+ // src/ui/PermissionPrompt.tsx
2191
+ import React7 from "react";
2192
+ import { Box as Box7, Text as Text9, useInput as useInput4 } from "ink";
2193
+ import { jsx as jsx8, jsxs as jsxs7 } from "react/jsx-runtime";
2194
+ var OPTIONS = ["Allow", "Allow always (this session)", "Deny"];
2195
+ function formatArgs(args) {
2196
+ const entries = Object.entries(args);
2197
+ if (entries.length === 0) return "(no arguments)";
2198
+ return entries.map(([k, v]) => `${k}: ${typeof v === "string" ? v : JSON.stringify(v)}`).join(", ");
2199
+ }
2200
+ function PermissionPrompt({ request }) {
2201
+ const [selected, setSelected] = React7.useState(0);
2202
+ const resolvedRef = React7.useRef(false);
2203
+ const prevRequestRef = React7.useRef(request);
2204
+ if (prevRequestRef.current !== request) {
2205
+ prevRequestRef.current = request;
2206
+ resolvedRef.current = false;
2207
+ setSelected(0);
2208
+ }
2209
+ const doResolve = React7.useCallback(
2210
+ (index) => {
2211
+ if (resolvedRef.current) return;
2212
+ resolvedRef.current = true;
2213
+ if (index === 0) request.resolve(true);
2214
+ else if (index === 1) request.resolve("allow-session");
2215
+ else request.resolve(false);
2216
+ },
2217
+ [request]
2218
+ );
2219
+ useInput4((input, key) => {
2220
+ if (resolvedRef.current) return;
2221
+ if (key.upArrow || key.leftArrow) {
2222
+ setSelected((prev) => prev > 0 ? prev - 1 : prev);
2223
+ } else if (key.downArrow || key.rightArrow) {
2224
+ setSelected((prev) => prev < OPTIONS.length - 1 ? prev + 1 : prev);
2225
+ } else if (key.return) {
2226
+ doResolve(selected);
2227
+ } else if (input === "y" || input === "1") {
2228
+ doResolve(0);
2229
+ } else if (input === "a" || input === "2") {
2230
+ doResolve(1);
2231
+ } else if (input === "n" || input === "d" || input === "3") {
2232
+ doResolve(2);
2233
+ }
2234
+ });
2235
+ return /* @__PURE__ */ jsxs7(Box7, { flexDirection: "column", borderStyle: "round", borderColor: "yellow", paddingX: 1, children: [
2236
+ /* @__PURE__ */ jsx8(Text9, { color: "yellow", bold: true, children: "[Permission Required]" }),
2237
+ /* @__PURE__ */ jsxs7(Text9, { children: [
2238
+ "Tool:",
2239
+ " ",
2240
+ /* @__PURE__ */ jsx8(Text9, { color: "cyan", bold: true, children: request.toolName })
2241
+ ] }),
2242
+ /* @__PURE__ */ jsxs7(Text9, { dimColor: true, children: [
2243
+ " ",
2244
+ formatArgs(request.toolArgs)
2245
+ ] }),
2246
+ /* @__PURE__ */ jsx8(Box7, { marginTop: 1, children: OPTIONS.map((opt, i) => /* @__PURE__ */ jsx8(Box7, { marginRight: 2, children: /* @__PURE__ */ jsxs7(Text9, { color: i === selected ? "cyan" : void 0, bold: i === selected, children: [
2247
+ i === selected ? "> " : " ",
2248
+ opt
2249
+ ] }) }, opt)) }),
2250
+ /* @__PURE__ */ jsx8(Text9, { dimColor: true, children: " left/right to select, Enter to confirm" })
2251
+ ] });
2252
+ }
2253
+
2254
+ // src/ui/StreamingIndicator.tsx
2255
+ import { Box as Box8, Text as Text10 } from "ink";
2256
+ import { Fragment as Fragment2, jsx as jsx9, jsxs as jsxs8 } from "react/jsx-runtime";
2257
+ function getToolStyle(t) {
2258
+ if (t.isRunning) return { color: "yellow", icon: "\u27F3", strikethrough: false };
2259
+ if (t.result === "error") return { color: "red", icon: "\u2717", strikethrough: true };
2260
+ if (t.result === "denied") return { color: "yellowBright", icon: "\u2298", strikethrough: true };
2261
+ return { color: "green", icon: "\u2713", strikethrough: false };
2262
+ }
2263
+ function StreamingIndicator({ text, activeTools }) {
2264
+ const hasTools = activeTools.length > 0;
2265
+ const hasText = text.length > 0;
2266
+ if (!hasTools && !hasText) {
2267
+ return /* @__PURE__ */ jsx9(Fragment2, {});
2268
+ }
2269
+ return /* @__PURE__ */ jsxs8(Box8, { flexDirection: "column", children: [
2270
+ hasTools && /* @__PURE__ */ jsxs8(Box8, { flexDirection: "column", marginBottom: 1, children: [
2271
+ /* @__PURE__ */ jsx9(Text10, { color: "white", bold: true, children: "Tools:" }),
2272
+ /* @__PURE__ */ jsx9(Text10, { children: " " }),
2273
+ activeTools.map((t, i) => {
2274
+ const { color, icon, strikethrough } = getToolStyle(t);
2275
+ return /* @__PURE__ */ jsxs8(Box8, { flexDirection: "column", children: [
2276
+ /* @__PURE__ */ jsxs8(Text10, { color, strikethrough, children: [
2277
+ " ",
2278
+ icon,
2279
+ " ",
2280
+ t.toolName,
2281
+ "(",
2282
+ t.firstArg,
2283
+ ")"
2284
+ ] }),
2285
+ t.diffLines && t.diffLines.length > 0 && /* @__PURE__ */ jsx9(DiffBlock, { file: t.diffFile, lines: t.diffLines })
2286
+ ] }, `${t.toolName}-${i}`);
2287
+ })
2288
+ ] }),
2289
+ hasText && /* @__PURE__ */ jsxs8(Box8, { flexDirection: "column", marginBottom: 1, children: [
2290
+ /* @__PURE__ */ jsx9(Text10, { color: "cyan", bold: true, children: "Robota:" }),
2291
+ /* @__PURE__ */ jsx9(Text10, { children: " " }),
2292
+ /* @__PURE__ */ jsx9(Box8, { marginLeft: 2, children: /* @__PURE__ */ jsx9(Text10, { wrap: "wrap", children: renderMarkdown(text) }) })
2293
+ ] })
2294
+ ] });
2295
+ }
2296
+
2297
+ // src/ui/PluginTUI.tsx
2298
+ import { useState as useState9, useEffect as useEffect2, useCallback as useCallback9 } from "react";
2299
+
2300
+ // src/ui/MenuSelect.tsx
2301
+ import { useState as useState7, useCallback as useCallback7, useRef as useRef6 } from "react";
2302
+ import { Box as Box9, Text as Text11, useInput as useInput5 } from "ink";
2303
+ import { jsx as jsx10, jsxs as jsxs9 } from "react/jsx-runtime";
2304
+ function MenuSelect({
2305
+ title,
2306
+ items,
2307
+ onSelect,
2308
+ onBack,
2309
+ loading,
2310
+ error
2311
+ }) {
2312
+ const [selected, setSelected] = useState7(0);
2313
+ const selectedRef = useRef6(0);
2314
+ const resolvedRef = useRef6(false);
2315
+ const doSelect = useCallback7(
2316
+ (index) => {
2317
+ if (resolvedRef.current || items.length === 0) return;
2318
+ resolvedRef.current = true;
2319
+ onSelect(items[index].value);
2320
+ },
2321
+ [items, onSelect]
2322
+ );
2323
+ useInput5((input, key) => {
2324
+ if (resolvedRef.current) return;
2325
+ if (key.escape) {
2326
+ resolvedRef.current = true;
2327
+ onBack();
2328
+ return;
2329
+ }
2330
+ if (loading || error || items.length === 0) return;
2331
+ if (key.upArrow) {
2332
+ const next = selectedRef.current > 0 ? selectedRef.current - 1 : selectedRef.current;
2333
+ selectedRef.current = next;
2334
+ setSelected(next);
2335
+ } else if (key.downArrow) {
2336
+ const next = selectedRef.current < items.length - 1 ? selectedRef.current + 1 : selectedRef.current;
2337
+ selectedRef.current = next;
2338
+ setSelected(next);
2339
+ } else if (key.return) {
2340
+ doSelect(selectedRef.current);
2341
+ }
2342
+ });
2343
+ return /* @__PURE__ */ jsxs9(Box9, { flexDirection: "column", borderStyle: "round", borderColor: "yellow", paddingX: 1, children: [
2344
+ /* @__PURE__ */ jsx10(Text11, { color: "yellow", bold: true, children: title }),
2345
+ loading && /* @__PURE__ */ jsx10(Box9, { marginTop: 1, children: /* @__PURE__ */ jsx10(Text11, { dimColor: true, children: "Loading..." }) }),
2346
+ error && /* @__PURE__ */ jsxs9(Box9, { marginTop: 1, flexDirection: "column", children: [
2347
+ /* @__PURE__ */ jsx10(Text11, { color: "red", children: error }),
2348
+ /* @__PURE__ */ jsx10(Text11, { dimColor: true, children: "Press Esc to go back" })
2349
+ ] }),
2350
+ !loading && !error && /* @__PURE__ */ jsx10(Box9, { flexDirection: "column", marginTop: 1, children: items.map((item, i) => /* @__PURE__ */ jsxs9(Box9, { children: [
2351
+ /* @__PURE__ */ jsxs9(Text11, { color: i === selected ? "cyan" : void 0, bold: i === selected, children: [
2352
+ i === selected ? "> " : " ",
2353
+ item.label
2354
+ ] }),
2355
+ item.hint && /* @__PURE__ */ jsxs9(Text11, { dimColor: true, children: [
2356
+ " ",
2357
+ item.hint
2358
+ ] })
2359
+ ] }, item.value)) }),
2360
+ /* @__PURE__ */ jsx10(Text11, { dimColor: true, children: loading || error ? "" : " \u2191\u2193 Navigate Enter Select Esc Back" })
2361
+ ] });
2362
+ }
2363
+
2364
+ // src/ui/TextPrompt.tsx
2365
+ import { useState as useState8, useRef as useRef7, useCallback as useCallback8 } from "react";
2366
+ import { Box as Box10, Text as Text12, useInput as useInput6 } from "ink";
2367
+ import { jsx as jsx11, jsxs as jsxs10 } from "react/jsx-runtime";
2368
+ function TextPrompt({
2369
+ title,
2370
+ placeholder,
2371
+ onSubmit,
2372
+ onCancel,
2373
+ validate
2374
+ }) {
2375
+ const [value, setValue] = useState8("");
2376
+ const [error, setError] = useState8();
2377
+ const resolvedRef = useRef7(false);
2378
+ const valueRef = useRef7("");
2379
+ const handleSubmit = useCallback8(() => {
2380
+ if (resolvedRef.current) return;
2381
+ const trimmed = valueRef.current.trim();
2382
+ if (!trimmed) return;
2383
+ if (validate) {
2384
+ const err = validate(trimmed);
2385
+ if (err) {
2386
+ setError(err);
2387
+ return;
2388
+ }
2389
+ }
2390
+ resolvedRef.current = true;
2391
+ onSubmit(trimmed);
2392
+ }, [validate, onSubmit]);
2393
+ useInput6((input, key) => {
2394
+ if (resolvedRef.current) return;
2395
+ if (key.escape) {
2396
+ resolvedRef.current = true;
2397
+ onCancel();
2398
+ return;
2399
+ }
2400
+ if (key.return) {
2401
+ handleSubmit();
2402
+ return;
2403
+ }
2404
+ if (key.backspace || key.delete) {
2405
+ valueRef.current = valueRef.current.slice(0, -1);
2406
+ setValue(valueRef.current);
2407
+ setError(void 0);
2408
+ return;
2409
+ }
2410
+ if (input && !key.ctrl && !key.meta) {
2411
+ valueRef.current = valueRef.current + input;
2412
+ setValue(valueRef.current);
2413
+ setError(void 0);
2414
+ }
2415
+ });
2416
+ return /* @__PURE__ */ jsxs10(Box10, { flexDirection: "column", borderStyle: "round", borderColor: "yellow", paddingX: 1, children: [
2417
+ /* @__PURE__ */ jsx11(Text12, { color: "yellow", bold: true, children: title }),
2418
+ /* @__PURE__ */ jsxs10(Box10, { marginTop: 1, children: [
2419
+ /* @__PURE__ */ jsx11(Text12, { color: "cyan", children: "> " }),
2420
+ value ? /* @__PURE__ */ jsx11(Text12, { children: value }) : placeholder ? /* @__PURE__ */ jsx11(Text12, { dimColor: true, children: placeholder }) : null,
2421
+ /* @__PURE__ */ jsx11(Text12, { color: "cyan", children: "\u2588" })
2422
+ ] }),
2423
+ error && /* @__PURE__ */ jsx11(Text12, { color: "red", children: error }),
2424
+ /* @__PURE__ */ jsx11(Text12, { dimColor: true, children: " Enter Submit Esc Cancel" })
2425
+ ] });
2426
+ }
2427
+
2428
+ // src/ui/plugin-tui-handlers.ts
2429
+ function handleMainSelect(value, nav) {
2430
+ if (value === "marketplace") {
2431
+ nav.push({ screen: "marketplace-list" });
2432
+ } else if (value === "installed") {
2433
+ nav.push({ screen: "installed-list" });
2434
+ }
2435
+ }
2436
+ function handleMarketplaceListSelect(value, nav) {
2437
+ if (value === "__add__") {
2438
+ nav.push({ screen: "marketplace-add" });
2439
+ } else {
2440
+ nav.push({ screen: "marketplace-action", context: { marketplace: value } });
2441
+ }
2442
+ }
2443
+ function handleMarketplaceActionSelect(value, marketplace, callbacks, nav) {
2444
+ if (value === "browse") {
2445
+ nav.push({ screen: "marketplace-browse", context: { marketplace } });
2446
+ } else if (value === "update") {
2447
+ callbacks.marketplaceUpdate(marketplace).then(() => {
2448
+ nav.notify(`Updated marketplace "${marketplace}".`);
2449
+ nav.pop();
2450
+ }).catch((err) => {
2451
+ nav.notify(`Error: ${err instanceof Error ? err.message : String(err)}`);
2452
+ });
2453
+ } else if (value === "remove") {
2454
+ nav.setConfirm({
2455
+ message: `Remove marketplace "${marketplace}" and all its plugins?`,
2456
+ onConfirm: () => {
2457
+ nav.setConfirm(void 0);
2458
+ callbacks.marketplaceRemove(marketplace).then(() => {
2459
+ nav.notify(`Removed marketplace "${marketplace}".`);
2460
+ nav.popN(2);
2461
+ }).catch((err) => {
2462
+ nav.notify(`Error: ${err instanceof Error ? err.message : String(err)}`);
2463
+ });
2464
+ },
2465
+ onCancel: () => nav.setConfirm(void 0)
2466
+ });
2467
+ }
2468
+ }
2469
+ function handleMarketplaceBrowseSelect(value, marketplace, items, nav) {
2470
+ const fullId = `${value}@${marketplace}`;
2471
+ const item = items.find((i) => i.value === value);
2472
+ if (item?.hint === "installed") {
2473
+ nav.push({ screen: "installed-action", context: { pluginId: fullId } });
2474
+ } else {
2475
+ nav.push({ screen: "marketplace-install-scope", context: { marketplace, pluginId: fullId } });
2476
+ }
2477
+ }
2478
+ function handleInstallScopeSelect(value, pluginId, callbacks, nav) {
2479
+ const scope = value;
2480
+ callbacks.install(pluginId, scope).then(() => {
2481
+ nav.notify(`Installed plugin "${pluginId}" (${scope} scope).`);
2482
+ nav.popN(2);
2483
+ }).catch((err) => {
2484
+ nav.notify(`Error: ${err instanceof Error ? err.message : String(err)}`);
2485
+ });
2486
+ }
2487
+ function handleInstalledListSelect(value, callbacks, nav) {
2488
+ nav.setConfirm({
2489
+ message: `Uninstall plugin "${value}"?`,
2490
+ onConfirm: () => {
2491
+ nav.setConfirm(void 0);
2492
+ callbacks.uninstall(value).then(() => {
2493
+ nav.notify(`Uninstalled plugin "${value}".`);
2494
+ nav.refresh();
2495
+ }).catch((err) => {
2496
+ nav.notify(`Error: ${err instanceof Error ? err.message : String(err)}`);
2497
+ });
2498
+ },
2499
+ onCancel: () => nav.setConfirm(void 0)
2500
+ });
2501
+ }
2502
+ function handleInstalledActionSelect(value, pluginId, callbacks, nav) {
2503
+ if (value === "uninstall") {
2504
+ nav.setConfirm({
2505
+ message: `Uninstall plugin "${pluginId}"?`,
2506
+ onConfirm: () => {
2507
+ nav.setConfirm(void 0);
2508
+ callbacks.uninstall(pluginId).then(() => {
2509
+ nav.notify(`Uninstalled plugin "${pluginId}".`);
2510
+ nav.popN(2);
2511
+ }).catch((err) => {
2512
+ nav.notify(`Error: ${err instanceof Error ? err.message : String(err)}`);
2513
+ });
2514
+ },
2515
+ onCancel: () => nav.setConfirm(void 0)
2516
+ });
2517
+ }
2518
+ }
2519
+
2520
+ // src/ui/PluginTUI.tsx
2521
+ import { jsx as jsx12 } from "react/jsx-runtime";
2522
+ function PluginTUI({ callbacks, onClose, addMessage }) {
2523
+ const [stack, setStack] = useState9([{ screen: "main" }]);
2524
+ const [items, setItems] = useState9([]);
2525
+ const [loading, setLoading] = useState9(false);
2526
+ const [error, setError] = useState9();
2527
+ const [confirm, setConfirm] = useState9();
2528
+ const [refreshCounter, setRefreshCounter] = useState9(0);
2529
+ const current = stack[stack.length - 1] ?? { screen: "main" };
2530
+ const push = useCallback9((state) => {
2531
+ setStack((prev) => [...prev, state]);
2532
+ setItems([]);
2533
+ setError(void 0);
2534
+ }, []);
2535
+ const pop = useCallback9(() => {
2536
+ setStack((prev) => {
2537
+ if (prev.length <= 1) {
2538
+ onClose();
2539
+ return prev;
2540
+ }
2541
+ return prev.slice(0, -1);
2542
+ });
2543
+ setItems([]);
2544
+ setError(void 0);
2545
+ }, [onClose]);
2546
+ const popN = useCallback9(
2547
+ (n) => {
2548
+ setStack((prev) => {
2549
+ const next = prev.slice(0, Math.max(1, prev.length - n));
2550
+ if (next.length === 0) {
2551
+ onClose();
2552
+ return prev;
2553
+ }
2554
+ return next;
2555
+ });
2556
+ setItems([]);
2557
+ setError(void 0);
2558
+ },
2559
+ [onClose]
2560
+ );
2561
+ const notify = useCallback9(
2562
+ (content) => {
2563
+ addMessage?.({ role: "system", content });
2564
+ },
2565
+ [addMessage]
2566
+ );
2567
+ const refresh = useCallback9(() => {
2568
+ setItems([]);
2569
+ setRefreshCounter((c) => c + 1);
2570
+ }, []);
2571
+ const nav = { push, pop, popN, notify, setConfirm, refresh };
2572
+ useEffect2(() => {
2573
+ const screen2 = current.screen;
2574
+ if (screen2 === "marketplace-list") {
2575
+ setLoading(true);
2576
+ callbacks.marketplaceList().then((sources) => {
2577
+ const baseItems = [{ label: "Add Marketplace", value: "__add__" }];
2578
+ const sourceItems = sources.map((s) => ({
2579
+ label: s.name,
2580
+ value: s.name,
2581
+ hint: s.type
2582
+ }));
2583
+ setItems([...baseItems, ...sourceItems]);
2584
+ setLoading(false);
2585
+ }).catch((err) => {
2586
+ setError(err instanceof Error ? err.message : String(err));
2587
+ setLoading(false);
2588
+ });
2589
+ } else if (screen2 === "marketplace-browse") {
2590
+ const marketplace = current.context?.marketplace ?? "";
2591
+ setLoading(true);
2592
+ callbacks.listAvailablePlugins(marketplace).then((plugins) => {
2593
+ setItems(
2594
+ plugins.map((p) => ({
2595
+ label: p.name,
2596
+ value: p.name,
2597
+ hint: p.installed ? "installed" : p.description
2598
+ }))
2599
+ );
2600
+ setLoading(false);
2601
+ }).catch((err) => {
2602
+ setError(err instanceof Error ? err.message : String(err));
2603
+ setLoading(false);
2604
+ });
2605
+ } else if (screen2 === "installed-list") {
2606
+ setLoading(true);
2607
+ callbacks.listInstalled().then((plugins) => {
2608
+ setItems(
2609
+ plugins.map((p) => ({
2610
+ label: p.name,
2611
+ value: p.name,
2612
+ hint: p.description
2613
+ }))
2614
+ );
2615
+ setLoading(false);
2616
+ }).catch((err) => {
2617
+ setError(err instanceof Error ? err.message : String(err));
2618
+ setLoading(false);
2619
+ });
2620
+ }
2621
+ }, [stack.length, current.screen, current.context?.marketplace, callbacks, refreshCounter]);
2622
+ const handleSelect = useCallback9(
2623
+ (value) => {
2624
+ const screen2 = current.screen;
2625
+ const ctx = current.context;
2626
+ if (screen2 === "main") handleMainSelect(value, nav);
2627
+ else if (screen2 === "marketplace-list") handleMarketplaceListSelect(value, nav);
2628
+ else if (screen2 === "marketplace-action")
2629
+ handleMarketplaceActionSelect(value, ctx?.marketplace ?? "", callbacks, nav);
2630
+ else if (screen2 === "marketplace-browse")
2631
+ handleMarketplaceBrowseSelect(value, ctx?.marketplace ?? "", items, nav);
2632
+ else if (screen2 === "marketplace-install-scope")
2633
+ handleInstallScopeSelect(value, ctx?.pluginId ?? "", callbacks, nav);
2634
+ else if (screen2 === "installed-list") handleInstalledListSelect(value, callbacks, nav);
2635
+ else if (screen2 === "installed-action")
2636
+ handleInstalledActionSelect(value, ctx?.pluginId ?? "", callbacks, nav);
2637
+ },
2638
+ [current, items, callbacks, push, pop, popN, notify, setConfirm, refresh]
2639
+ );
2640
+ const handleTextSubmit = useCallback9(
2641
+ (value) => {
2642
+ if (current.screen === "marketplace-add") {
2643
+ callbacks.marketplaceAdd(value).then((name) => {
2644
+ notify(`Added marketplace "${name}" from ${value}.`);
2645
+ pop();
2646
+ }).catch((err) => {
2647
+ notify(`Error: ${err instanceof Error ? err.message : String(err)}`);
2648
+ pop();
2649
+ });
2650
+ }
2651
+ },
2652
+ [current.screen, callbacks, notify, pop]
2653
+ );
2654
+ if (confirm) {
2655
+ return /* @__PURE__ */ jsx12(
2656
+ ConfirmPrompt,
2657
+ {
2658
+ message: confirm.message,
2659
+ onSelect: (index) => {
2660
+ if (index === 0) confirm.onConfirm();
2661
+ else confirm.onCancel();
2662
+ }
2663
+ }
2664
+ );
2665
+ }
2666
+ const screen = current.screen;
2667
+ if (screen === "marketplace-add") {
2668
+ return /* @__PURE__ */ jsx12(
2669
+ TextPrompt,
2670
+ {
2671
+ title: "Add Marketplace Source",
2672
+ placeholder: "owner/repo or git URL",
2673
+ onSubmit: handleTextSubmit,
2674
+ onCancel: pop,
2675
+ validate: (v) => !v.includes("/") ? "Must be owner/repo or a git URL" : void 0
2676
+ }
2677
+ );
2678
+ }
2679
+ if (screen === "marketplace-action") {
2680
+ return /* @__PURE__ */ jsx12(
2681
+ MenuSelect,
2682
+ {
2683
+ title: `Marketplace: ${current.context?.marketplace ?? ""}`,
2684
+ items: [
2685
+ { label: "Browse plugins", value: "browse" },
2686
+ { label: "Update", value: "update" },
2687
+ { label: "Remove", value: "remove" }
2688
+ ],
2689
+ onSelect: handleSelect,
2690
+ onBack: pop
2691
+ },
2692
+ stack.length
2693
+ );
2694
+ }
2695
+ if (screen === "marketplace-install-scope") {
2696
+ return /* @__PURE__ */ jsx12(
2697
+ MenuSelect,
2698
+ {
2699
+ title: `Install scope for "${current.context?.pluginId ?? ""}"`,
2700
+ items: [
2701
+ { label: "User scope", value: "user" },
2702
+ { label: "Project scope", value: "project" }
2703
+ ],
2704
+ onSelect: handleSelect,
2705
+ onBack: pop
2706
+ },
2707
+ stack.length
2708
+ );
2709
+ }
2710
+ if (screen === "installed-action") {
2711
+ return /* @__PURE__ */ jsx12(
2712
+ MenuSelect,
2713
+ {
2714
+ title: `Plugin: ${current.context?.pluginId ?? ""}`,
2715
+ items: [{ label: "Uninstall", value: "uninstall" }],
2716
+ onSelect: handleSelect,
2717
+ onBack: pop
2718
+ },
2719
+ stack.length
2720
+ );
2721
+ }
2722
+ const titleMap = {
2723
+ main: "Plugin Management",
2724
+ "marketplace-list": "Marketplace",
2725
+ "marketplace-browse": `Browse: ${current.context?.marketplace ?? ""}`,
2726
+ "installed-list": "Installed Plugins"
2727
+ };
2728
+ const staticItemsMap = {
2729
+ main: [
2730
+ { label: "Marketplace", value: "marketplace" },
2731
+ { label: "Installed Plugins", value: "installed" }
2732
+ ]
2733
+ };
2734
+ return /* @__PURE__ */ jsx12(
2735
+ MenuSelect,
2736
+ {
2737
+ title: titleMap[screen] ?? "Plugin Management",
2738
+ items: staticItemsMap[screen] ?? items,
2739
+ onSelect: handleSelect,
2740
+ onBack: pop,
2741
+ loading,
2742
+ error
2743
+ },
2744
+ `${screen}-${stack.length}-${refreshCounter}`
2745
+ );
2746
+ }
2747
+
2748
+ // src/ui/App.tsx
2749
+ import { jsx as jsx13, jsxs as jsxs11 } from "react/jsx-runtime";
2750
+ var EXIT_DELAY_MS2 = 500;
2751
+ function mergeHooksIntoConfig(configHooks, pluginHooks) {
2752
+ const pluginKeys = Object.keys(pluginHooks);
2753
+ if (pluginKeys.length === 0) return configHooks;
2754
+ const merged = {};
2755
+ for (const [event, groups] of Object.entries(pluginHooks)) {
2756
+ merged[event] = [...groups];
2757
+ }
2758
+ if (configHooks) {
2759
+ for (const [event, groups] of Object.entries(configHooks)) {
2760
+ if (!Array.isArray(groups)) continue;
2761
+ if (!merged[event]) merged[event] = [];
2762
+ merged[event].push(...groups);
2763
+ }
2764
+ }
2765
+ return merged;
2766
+ }
2767
+ function App(props) {
2768
+ const { exit } = useApp();
2769
+ const { registry, pluginHooks } = useCommandRegistry(props.cwd ?? process.cwd());
2770
+ const configWithPluginHooks = {
2771
+ ...props.config,
2772
+ hooks: mergeHooksIntoConfig(
2773
+ props.config.hooks,
2774
+ pluginHooks
2775
+ )
2776
+ };
2777
+ const { session, permissionRequest, streamingText, clearStreamingText, activeTools } = useSession(
2778
+ { ...props, config: configWithPluginHooks }
2779
+ );
2780
+ const { messages, setMessages, addMessage } = useMessages();
2781
+ const [isThinking, setIsThinking] = useState10(false);
2782
+ const initialCtx = session.getContextState();
2783
+ const [contextState, setContextState] = useState10({
2784
+ percentage: initialCtx.usedPercentage,
2785
+ usedTokens: initialCtx.usedTokens,
2786
+ maxTokens: initialCtx.maxTokens
2787
+ });
2788
+ const pendingModelChangeRef = useRef8(null);
2789
+ const [pendingModelId, setPendingModelId] = useState10(null);
2790
+ const [showPluginTUI, setShowPluginTUI] = useState10(false);
2791
+ const [isAborting, setIsAborting] = useState10(false);
2792
+ const [pendingPrompt, setPendingPrompt] = useState10(null);
2793
+ const pendingPromptRef = useRef8(null);
2794
+ const pluginCallbacks = usePluginCallbacks(props.cwd ?? process.cwd());
2795
+ const handleSlashCommand = useSlashCommands(
2796
+ session,
2797
+ addMessage,
2798
+ setMessages,
2799
+ exit,
2800
+ registry,
2801
+ pendingModelChangeRef,
2802
+ setPendingModelId,
2803
+ pluginCallbacks,
2804
+ setShowPluginTUI
2805
+ );
2806
+ const executePrompt = useSubmitHandler(
2807
+ session,
2808
+ addMessage,
2809
+ handleSlashCommand,
2810
+ clearStreamingText,
2811
+ setIsThinking,
2812
+ setContextState,
2813
+ registry
2814
+ );
2815
+ const handleSubmit = useCallback10(
2816
+ async (input) => {
2817
+ if (isThinking) {
2818
+ setPendingPrompt(input);
2819
+ pendingPromptRef.current = input;
2820
+ return;
2821
+ }
2822
+ await executePrompt(input);
2823
+ },
2824
+ [isThinking, executePrompt]
2825
+ );
2826
+ useInput7(
2827
+ (_input, key) => {
2828
+ if (key.escape && isThinking) {
2829
+ setIsAborting(true);
2830
+ setPendingPrompt(null);
2831
+ pendingPromptRef.current = null;
2832
+ session.abort();
2833
+ }
2834
+ },
2835
+ { isActive: !permissionRequest && !showPluginTUI }
2836
+ );
2837
+ useEffect3(() => {
2838
+ if (!isThinking) {
2839
+ setIsAborting(false);
2840
+ if (pendingPromptRef.current) {
2841
+ const prompt = pendingPromptRef.current;
2842
+ setPendingPrompt(null);
2843
+ pendingPromptRef.current = null;
2844
+ setTimeout(() => executePrompt(prompt), 0);
2845
+ }
2846
+ }
2847
+ }, [isThinking, pendingPrompt, executePrompt]);
2848
+ return /* @__PURE__ */ jsxs11(Box11, { flexDirection: "column", children: [
2849
+ /* @__PURE__ */ jsxs11(Box11, { flexDirection: "column", paddingX: 1, marginBottom: 1, children: [
2850
+ /* @__PURE__ */ jsx13(Text13, { color: "cyan", bold: true, children: `
2851
+ ____ ___ ____ ___ _____ _
2852
+ | _ \\ / _ \\| __ ) / _ \\_ _|/ \\
2853
+ | |_) | | | | _ \\| | | || | / _ \\
2854
+ | _ <| |_| | |_) | |_| || |/ ___ \\
2855
+ |_| \\_\\\\___/|____/ \\___/ |_/_/ \\_\\
2856
+ ` }),
2857
+ /* @__PURE__ */ jsxs11(Text13, { dimColor: true, children: [
2858
+ " v",
2859
+ props.version ?? "0.0.0"
2860
+ ] })
2861
+ ] }),
2862
+ /* @__PURE__ */ jsxs11(Box11, { flexDirection: "column", paddingX: 1, flexGrow: 1, children: [
2863
+ /* @__PURE__ */ jsx13(MessageList, { messages }),
2864
+ isThinking && /* @__PURE__ */ jsx13(Box11, { flexDirection: "column", marginBottom: 1, children: /* @__PURE__ */ jsx13(StreamingIndicator, { text: streamingText, activeTools }) })
2865
+ ] }),
2866
+ permissionRequest && /* @__PURE__ */ jsx13(PermissionPrompt, { request: permissionRequest }),
2867
+ pendingModelId && /* @__PURE__ */ jsx13(
2868
+ ConfirmPrompt,
2869
+ {
2870
+ message: `Change model to ${getModelName(pendingModelId)}? This will restart the session.`,
2871
+ onSelect: (index) => {
2872
+ setPendingModelId(null);
2873
+ pendingModelChangeRef.current = null;
2874
+ if (index === 0) {
2875
+ try {
2876
+ const settingsPath = getUserSettingsPath();
2877
+ updateModelInSettings(settingsPath, pendingModelId);
2878
+ addMessage(
2879
+ createSystemMessage3(
2880
+ `Model changed to ${getModelName(pendingModelId)}. Restarting...`
2881
+ )
2882
+ );
2883
+ setTimeout(() => exit(), EXIT_DELAY_MS2);
2884
+ } catch (err) {
2885
+ addMessage(
2886
+ createSystemMessage3(
2887
+ `Failed: ${err instanceof Error ? err.message : String(err)}`
2888
+ )
2889
+ );
2890
+ }
2891
+ } else {
2892
+ addMessage(createSystemMessage3("Model change cancelled."));
2893
+ }
2894
+ }
2895
+ }
2896
+ ),
2897
+ showPluginTUI && /* @__PURE__ */ jsx13(
2898
+ PluginTUI,
2899
+ {
2900
+ callbacks: pluginCallbacks,
2901
+ onClose: () => setShowPluginTUI(false),
2902
+ addMessage: (msg) => addMessage(createSystemMessage3(msg.content))
2903
+ }
2904
+ ),
2905
+ /* @__PURE__ */ jsx13(
2906
+ StatusBar,
2907
+ {
2908
+ permissionMode: session.getPermissionMode(),
2909
+ modelName: getModelName(props.config.provider.model),
2910
+ sessionId: session.getSessionId(),
2911
+ messageCount: messages.length,
2912
+ isThinking,
2913
+ contextPercentage: contextState.percentage,
2914
+ contextUsedTokens: contextState.usedTokens,
2915
+ contextMaxTokens: contextState.maxTokens
2916
+ }
2917
+ ),
2918
+ /* @__PURE__ */ jsx13(
2919
+ InputArea,
2920
+ {
2921
+ onSubmit: handleSubmit,
2922
+ onCancelQueue: () => {
2923
+ setPendingPrompt(null);
2924
+ pendingPromptRef.current = null;
2925
+ },
2926
+ isDisabled: !!permissionRequest || showPluginTUI || isThinking && !!pendingPrompt,
2927
+ isAborting,
2928
+ pendingPrompt,
2929
+ registry
2930
+ }
2931
+ ),
2932
+ /* @__PURE__ */ jsx13(Text13, { children: " " })
2933
+ ] });
2934
+ }
2935
+
2936
+ // src/ui/render.tsx
2937
+ import { jsx as jsx14 } from "react/jsx-runtime";
2938
+ function renderApp(options) {
2939
+ process.on("unhandledRejection", (reason) => {
2940
+ process.stderr.write(`
2941
+ [UNHANDLED REJECTION] ${reason}
2942
+ `);
2943
+ if (reason instanceof Error) {
2944
+ process.stderr.write(`${reason.stack}
2945
+ `);
2946
+ }
2947
+ });
2948
+ if (process.stdin.isTTY && process.stdout.isTTY) {
2949
+ process.stdout.write("\x1B[?2004h");
2950
+ }
2951
+ const instance = render(/* @__PURE__ */ jsx14(App, { ...options }), {
2952
+ exitOnCtrlC: true
2953
+ });
2954
+ instance.waitUntilExit().then(() => {
2955
+ if (process.stdout.isTTY) {
2956
+ process.stdout.write("\x1B[?2004l");
2957
+ }
2958
+ process.exit(0);
2959
+ }).catch((err) => {
2960
+ if (err) {
2961
+ process.stderr.write(`
2962
+ [EXIT ERROR] ${err}
2963
+ `);
2964
+ }
2965
+ process.exit(1);
2966
+ });
2967
+ }
2968
+
2969
+ // src/cli.ts
2970
+ function checkSettingsFile(filePath) {
2971
+ if (!existsSync3(filePath)) return "missing";
2972
+ try {
2973
+ const raw = readFileSync4(filePath, "utf8").trim();
2974
+ if (raw.length === 0) return "incomplete";
2975
+ const parsed = JSON.parse(raw);
2976
+ const provider = parsed.provider;
2977
+ if (!provider?.apiKey) return "incomplete";
2978
+ return "valid";
2979
+ } catch {
2980
+ return "corrupt";
2981
+ }
2982
+ }
2983
+ function readVersion() {
2984
+ try {
2985
+ const thisFile = fileURLToPath(import.meta.url);
2986
+ const dir = dirname3(thisFile);
2987
+ const candidates = [join5(dir, "..", "..", "package.json"), join5(dir, "..", "package.json")];
2988
+ for (const pkgPath of candidates) {
2989
+ try {
2990
+ const raw = readFileSync4(pkgPath, "utf-8");
2991
+ const pkg = JSON.parse(raw);
2992
+ if (pkg.version !== void 0 && pkg.name !== void 0) {
2993
+ return pkg.version;
2994
+ }
2995
+ } catch {
2996
+ }
2997
+ }
2998
+ return "0.0.0";
2999
+ } catch {
3000
+ return "0.0.0";
3001
+ }
3002
+ }
3003
+ function promptInput(label, masked = false) {
3004
+ return new Promise((resolve) => {
3005
+ process.stdout.write(label);
3006
+ let input = "";
3007
+ const stdin = process.stdin;
3008
+ const wasRaw = stdin.isRaw;
3009
+ stdin.setRawMode(true);
3010
+ stdin.resume();
3011
+ stdin.setEncoding("utf8");
3012
+ const onData = (data) => {
3013
+ for (const ch of data) {
3014
+ if (ch === "\r" || ch === "\n") {
3015
+ stdin.removeListener("data", onData);
3016
+ stdin.setRawMode(wasRaw ?? false);
3017
+ stdin.pause();
3018
+ process.stdout.write("\n");
3019
+ resolve(input.trim());
3020
+ return;
3021
+ } else if (ch === "\x7F" || ch === "\b") {
3022
+ if (input.length > 0) {
3023
+ input = input.slice(0, -1);
3024
+ process.stdout.write("\b \b");
3025
+ }
3026
+ } else if (ch === "") {
3027
+ process.stdout.write("\n");
3028
+ process.exit(0);
3029
+ } else if (ch.charCodeAt(0) >= 32) {
3030
+ input += ch;
3031
+ process.stdout.write(masked ? "*" : ch);
3032
+ }
3033
+ }
3034
+ };
3035
+ stdin.on("data", onData);
3036
+ });
3037
+ }
3038
+ async function ensureConfig(cwd) {
3039
+ const userPath = getUserSettingsPath();
3040
+ const projectPath = join5(cwd, ".robota", "settings.json");
3041
+ const localPath = join5(cwd, ".robota", "settings.local.json");
3042
+ const paths = [userPath, projectPath, localPath];
3043
+ const checks = paths.map((p) => ({ path: p, status: checkSettingsFile(p) }));
3044
+ if (checks.some((c) => c.status === "valid")) {
3045
+ return;
3046
+ }
3047
+ const corrupt = checks.filter((c) => c.status === "corrupt");
3048
+ const incomplete = checks.filter((c) => c.status === "incomplete");
3049
+ process.stdout.write("\n");
3050
+ if (corrupt.length > 0) {
3051
+ for (const c of corrupt) {
3052
+ process.stderr.write(` ERROR: Settings file is corrupt (invalid JSON): ${c.path}
3053
+ `);
3054
+ }
3055
+ process.stdout.write("\n");
3056
+ }
3057
+ if (incomplete.length > 0) {
3058
+ for (const c of incomplete) {
3059
+ process.stderr.write(` WARNING: Settings file is missing provider.apiKey: ${c.path}
3060
+ `);
3061
+ }
3062
+ process.stdout.write("\n");
3063
+ }
3064
+ if (corrupt.length === 0 && incomplete.length === 0) {
3065
+ process.stdout.write(" Welcome to Robota CLI!\n");
3066
+ process.stdout.write(" No configuration found. Let's set up.\n");
3067
+ } else {
3068
+ process.stdout.write(" Reconfiguring...\n");
3069
+ }
3070
+ process.stdout.write("\n");
3071
+ const apiKey = await promptInput(" Anthropic API key: ", true);
3072
+ if (!apiKey) {
3073
+ process.stderr.write("\n No API key provided. Exiting.\n");
3074
+ process.exit(1);
3075
+ }
3076
+ const language = await promptInput(" Response language (ko/en/ja/zh, default: en): ");
3077
+ const settingsDir = dirname3(userPath);
3078
+ mkdirSync2(settingsDir, { recursive: true });
3079
+ const settings = {
3080
+ provider: {
3081
+ name: "anthropic",
3082
+ model: "claude-sonnet-4-6",
3083
+ apiKey
3084
+ }
3085
+ };
3086
+ if (language) {
3087
+ settings.language = language;
3088
+ }
3089
+ writeFileSync2(userPath, JSON.stringify(settings, null, 2) + "\n", "utf8");
3090
+ process.stdout.write(`
3091
+ Config saved to ${userPath}
3092
+
3093
+ `);
3094
+ }
3095
+ function resetConfig() {
3096
+ const userPath = getUserSettingsPath();
3097
+ if (deleteSettings(userPath)) {
3098
+ process.stdout.write(`Deleted ${userPath}
3099
+ `);
3100
+ } else {
3101
+ process.stdout.write("No user settings found.\n");
3102
+ }
3103
+ }
3104
+ async function startCli() {
3105
+ const args = parseCliArgs();
3106
+ if (args.version) {
3107
+ process.stdout.write(`robota ${readVersion()}
3108
+ `);
3109
+ return;
3110
+ }
3111
+ if (args.reset) {
3112
+ resetConfig();
3113
+ return;
3114
+ }
3115
+ const cwd = process.cwd();
3116
+ await ensureConfig(cwd);
3117
+ const [config, context, projectInfo] = await Promise.all([
3118
+ loadConfig(cwd),
3119
+ loadContext(cwd),
3120
+ detectProject(cwd)
3121
+ ]);
3122
+ if (args.model !== void 0) {
3123
+ config.provider.model = args.model;
3124
+ }
3125
+ if (args.language !== void 0) {
3126
+ config.language = args.language;
3127
+ }
3128
+ const sessionStore = new SessionStore();
3129
+ if (args.printMode) {
3130
+ const prompt = args.positional.join(" ").trim();
3131
+ if (prompt.length === 0) {
3132
+ process.stderr.write("Print mode (-p) requires a prompt argument.\n");
3133
+ process.exit(1);
3134
+ }
3135
+ const terminal = new PrintTerminal();
3136
+ const paths = projectPaths2(cwd);
3137
+ const session = createSession2({
3138
+ config,
3139
+ context,
3140
+ terminal,
3141
+ sessionLogger: new FileSessionLogger2(paths.logs),
3142
+ projectInfo,
3143
+ permissionMode: args.permissionMode,
3144
+ promptForApproval
3145
+ });
3146
+ const response = await session.run(prompt);
3147
+ process.stdout.write(response + "\n");
3148
+ return;
3149
+ }
3150
+ renderApp({
3151
+ config,
3152
+ context,
3153
+ projectInfo,
3154
+ sessionStore,
3155
+ permissionMode: args.permissionMode,
3156
+ maxTurns: args.maxTurns,
3157
+ version: readVersion()
3158
+ });
3159
+ }
3160
+
3161
+ export {
3162
+ startCli
3163
+ };