@robota-sdk/agent-cli 3.0.0-beta.5 → 3.0.0-beta.50

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,2523 @@
1
+ // src/cli.ts
2
+ import { readFileSync as readFileSync3, existsSync as existsSync3, mkdirSync as mkdirSync2, writeFileSync as writeFileSync2 } from "fs";
3
+ import { join as join5, dirname as dirname2 } from "path";
4
+ import { fileURLToPath } from "url";
5
+ import { InteractiveSession as InteractiveSession2 } from "@robota-sdk/agent-sdk";
6
+ import { SessionStore } from "@robota-sdk/agent-sessions";
7
+
8
+ // src/utils/cli-args.ts
9
+ import { parseArgs } from "util";
10
+ var VALID_MODES = ["plan", "default", "acceptEdits", "bypassPermissions"];
11
+ function parsePermissionMode(raw) {
12
+ if (raw === void 0) return void 0;
13
+ if (!VALID_MODES.includes(raw)) {
14
+ process.stderr.write(`Invalid --permission-mode "${raw}". Valid: ${VALID_MODES.join(" | ")}
15
+ `);
16
+ process.exit(1);
17
+ }
18
+ return raw;
19
+ }
20
+ function parseMaxTurns(raw) {
21
+ if (raw === void 0) return void 0;
22
+ const n = parseInt(raw, 10);
23
+ if (isNaN(n) || n <= 0) {
24
+ process.stderr.write(`Invalid --max-turns "${raw}". Must be a positive integer.
25
+ `);
26
+ process.exit(1);
27
+ }
28
+ return n;
29
+ }
30
+ function parseCliArgs() {
31
+ const { values, positionals } = parseArgs({
32
+ allowPositionals: true,
33
+ options: {
34
+ p: { type: "boolean", short: "p", default: false },
35
+ continue: { type: "boolean", short: "c", default: false },
36
+ resume: { type: "string", short: "r" },
37
+ model: { type: "string" },
38
+ language: { type: "string" },
39
+ "permission-mode": { type: "string" },
40
+ "max-turns": { type: "string" },
41
+ "fork-session": { type: "boolean", default: false },
42
+ name: { type: "string", short: "n" },
43
+ "output-format": { type: "string" },
44
+ "system-prompt": { type: "string" },
45
+ "append-system-prompt": { type: "string" },
46
+ version: { type: "boolean", default: false },
47
+ reset: { type: "boolean", default: false }
48
+ }
49
+ });
50
+ return {
51
+ positional: positionals,
52
+ printMode: values["p"] ?? false,
53
+ continueMode: values["continue"] ?? false,
54
+ resumeId: values["resume"],
55
+ model: values["model"],
56
+ language: values["language"],
57
+ permissionMode: parsePermissionMode(values["permission-mode"]),
58
+ maxTurns: parseMaxTurns(values["max-turns"]),
59
+ forkSession: values["fork-session"] ?? false,
60
+ sessionName: values["name"],
61
+ outputFormat: values["output-format"],
62
+ systemPrompt: values["system-prompt"],
63
+ appendSystemPrompt: values["append-system-prompt"],
64
+ version: values["version"] ?? false,
65
+ reset: values["reset"] ?? false
66
+ };
67
+ }
68
+
69
+ // src/utils/settings-io.ts
70
+ import { existsSync, readFileSync, writeFileSync, mkdirSync, unlinkSync } from "fs";
71
+ import { join, dirname } from "path";
72
+ function getUserSettingsPath() {
73
+ const home = process.env.HOME ?? process.env.USERPROFILE ?? "/";
74
+ return join(home, ".robota", "settings.json");
75
+ }
76
+ function readSettings(path) {
77
+ if (!existsSync(path)) return {};
78
+ return JSON.parse(readFileSync(path, "utf8"));
79
+ }
80
+ function writeSettings(path, settings) {
81
+ mkdirSync(dirname(path), { recursive: true });
82
+ writeFileSync(path, JSON.stringify(settings, null, 2) + "\n", "utf8");
83
+ }
84
+ function updateModelInSettings(settingsPath, modelId) {
85
+ const settings = readSettings(settingsPath);
86
+ const provider = settings.provider ?? {};
87
+ provider.model = modelId;
88
+ settings.provider = provider;
89
+ writeSettings(settingsPath, settings);
90
+ }
91
+ function deleteSettings(path) {
92
+ if (existsSync(path)) {
93
+ unlinkSync(path);
94
+ return true;
95
+ }
96
+ return false;
97
+ }
98
+
99
+ // src/utils/provider-factory.ts
100
+ import { readFileSync as readFileSync2, existsSync as existsSync2 } from "fs";
101
+ import { join as join2 } from "path";
102
+ import { homedir } from "os";
103
+ import { AnthropicProvider } from "@robota-sdk/agent-provider-anthropic";
104
+ function readProviderSettings(cwd) {
105
+ const paths = [
106
+ join2(cwd, ".robota", "settings.local.json"),
107
+ join2(cwd, ".robota", "settings.json"),
108
+ join2(cwd, ".claude", "settings.local.json"),
109
+ join2(cwd, ".claude", "settings.json"),
110
+ join2(homedir(), ".robota", "settings.json"),
111
+ join2(homedir(), ".claude", "settings.json")
112
+ ];
113
+ for (const filePath of paths) {
114
+ if (!existsSync2(filePath)) continue;
115
+ try {
116
+ const raw = readFileSync2(filePath, "utf8");
117
+ const parsed = JSON.parse(raw);
118
+ const provider = parsed.provider;
119
+ if (provider?.apiKey && provider?.name) {
120
+ return {
121
+ name: provider.name,
122
+ model: provider.model ?? "claude-sonnet-4-6",
123
+ apiKey: provider.apiKey
124
+ };
125
+ }
126
+ } catch {
127
+ continue;
128
+ }
129
+ }
130
+ throw new Error("No provider configuration found. Run `robota` to set up.");
131
+ }
132
+ function createProviderFromSettings(cwd, modelOverride) {
133
+ const settings = readProviderSettings(cwd);
134
+ const model = modelOverride ?? settings.model;
135
+ switch (settings.name) {
136
+ case "anthropic":
137
+ return new AnthropicProvider({ apiKey: settings.apiKey, defaultModel: model });
138
+ default:
139
+ throw new Error(`Unknown provider: ${settings.name}. Currently supported: anthropic`);
140
+ }
141
+ }
142
+
143
+ // src/cli.ts
144
+ import { createHeadlessTransport } from "@robota-sdk/agent-transport-headless";
145
+
146
+ // src/ui/render.tsx
147
+ import { render } from "ink";
148
+
149
+ // src/ui/App.tsx
150
+ import { useState as useState10, useRef as useRef8, useEffect as useEffect4 } from "react";
151
+ import { Box as Box12, Text as Text14, useApp, useInput as useInput8 } from "ink";
152
+ import { getModelName, createSystemMessage as createSystemMessage2, messageToHistoryEntry as messageToHistoryEntry2 } from "@robota-sdk/agent-core";
153
+
154
+ // src/ui/hooks/useInteractiveSession.ts
155
+ import { useState, useRef, useCallback, useEffect } from "react";
156
+ import { homedir as homedir2 } from "os";
157
+ import { join as join3 } from "path";
158
+ import {
159
+ InteractiveSession,
160
+ CommandRegistry,
161
+ BuiltinCommandSource,
162
+ SkillCommandSource,
163
+ PluginCommandSource,
164
+ BundlePluginLoader,
165
+ buildSkillPrompt
166
+ } from "@robota-sdk/agent-sdk";
167
+ import { createSystemMessage, messageToHistoryEntry } from "@robota-sdk/agent-core";
168
+ import { randomUUID } from "crypto";
169
+
170
+ // src/ui/tui-state-manager.ts
171
+ var MAX_RENDERED_MESSAGES = 100;
172
+ var TuiStateManager = class {
173
+ // ── Rendering state ───────────────────────────────────────────
174
+ history = [];
175
+ streamingText = "";
176
+ activeTools = [];
177
+ isThinking = false;
178
+ isAborting = false;
179
+ pendingPrompt = null;
180
+ contextState = { percentage: 0, usedTokens: 0, maxTokens: 0 };
181
+ /** Called after any state change. React hook sets this to trigger re-render. */
182
+ onChange = null;
183
+ // ── Internal ──────────────────────────────────────────────────
184
+ streamBuf = "";
185
+ notify() {
186
+ this.onChange?.();
187
+ }
188
+ // ── Event handlers (InteractiveSession → state) ───────────────
189
+ onTextDelta = (delta) => {
190
+ this.streamBuf += delta;
191
+ this.streamingText = this.streamBuf;
192
+ this.notify();
193
+ };
194
+ onToolStart = (state) => {
195
+ this.activeTools = [...this.activeTools, state];
196
+ this.notify();
197
+ };
198
+ onToolEnd = (state) => {
199
+ const idx = this.activeTools.findIndex((t) => t.toolName === state.toolName && t.isRunning);
200
+ if (idx !== -1) {
201
+ const updated = [...this.activeTools];
202
+ updated[idx] = state;
203
+ this.activeTools = updated;
204
+ }
205
+ this.notify();
206
+ };
207
+ onThinking = (thinking) => {
208
+ this.isThinking = thinking;
209
+ if (thinking) {
210
+ this.streamBuf = "";
211
+ this.streamingText = "";
212
+ this.activeTools = [];
213
+ } else {
214
+ this.isAborting = false;
215
+ }
216
+ this.notify();
217
+ };
218
+ onComplete = (result) => {
219
+ this.streamBuf = "";
220
+ this.streamingText = "";
221
+ this.activeTools = [];
222
+ this.contextState = {
223
+ percentage: result.contextState.usedPercentage,
224
+ usedTokens: result.contextState.usedTokens,
225
+ maxTokens: result.contextState.maxTokens
226
+ };
227
+ this.notify();
228
+ };
229
+ onInterrupted = () => {
230
+ this.streamBuf = "";
231
+ this.streamingText = "";
232
+ this.activeTools = [];
233
+ this.notify();
234
+ };
235
+ onError = () => {
236
+ this.streamBuf = "";
237
+ this.streamingText = "";
238
+ this.activeTools = [];
239
+ this.notify();
240
+ };
241
+ // ── State updates from external sources ───────────────────────
242
+ /** Sync history from InteractiveSession */
243
+ syncHistory(entries) {
244
+ if (entries.length === 0) return;
245
+ this.history = entries.length > MAX_RENDERED_MESSAGES ? entries.slice(-MAX_RENDERED_MESSAGES) : [...entries];
246
+ this.notify();
247
+ }
248
+ /** Add a single history entry */
249
+ addEntry(entry) {
250
+ const updated = [...this.history, entry];
251
+ this.history = updated.length > MAX_RENDERED_MESSAGES ? updated.slice(-MAX_RENDERED_MESSAGES) : updated;
252
+ this.notify();
253
+ }
254
+ /** Update pending prompt state */
255
+ setPendingPrompt(prompt) {
256
+ this.pendingPrompt = prompt;
257
+ this.notify();
258
+ }
259
+ /** Set aborting flag */
260
+ setAborting(aborting) {
261
+ this.isAborting = aborting;
262
+ this.notify();
263
+ }
264
+ /** Update context state */
265
+ setContextState(state) {
266
+ this.contextState = state;
267
+ this.notify();
268
+ }
269
+ };
270
+
271
+ // src/ui/hooks/useInteractiveSession.ts
272
+ function initializeSession(props, permissionHandler) {
273
+ const interactiveSession = new InteractiveSession({
274
+ cwd: props.cwd,
275
+ provider: props.provider,
276
+ permissionMode: props.permissionMode,
277
+ maxTurns: props.maxTurns,
278
+ permissionHandler,
279
+ sessionStore: props.sessionStore,
280
+ resumeSessionId: props.resumeSessionId,
281
+ forkSession: props.forkSession,
282
+ sessionName: props.sessionName
283
+ });
284
+ const registry = new CommandRegistry();
285
+ registry.addSource(new BuiltinCommandSource());
286
+ registry.addSource(new SkillCommandSource(props.cwd));
287
+ const pluginsDir = join3(homedir2(), ".robota", "plugins");
288
+ const loader = new BundlePluginLoader(pluginsDir);
289
+ try {
290
+ const plugins = loader.loadPluginsSync();
291
+ if (plugins.length > 0) {
292
+ registry.addSource(new PluginCommandSource(plugins));
293
+ }
294
+ } catch {
295
+ }
296
+ const manager = new TuiStateManager();
297
+ return { interactiveSession, registry, manager };
298
+ }
299
+ function useInteractiveSession(props) {
300
+ const [, forceRender] = useState(0);
301
+ const [permissionRequest, setPermissionRequest] = useState(null);
302
+ const permissionQueueRef = useRef([]);
303
+ const processingRef = useRef(false);
304
+ const processNextPermission = useCallback(() => {
305
+ if (processingRef.current) return;
306
+ const next = permissionQueueRef.current[0];
307
+ if (!next) {
308
+ setPermissionRequest(null);
309
+ return;
310
+ }
311
+ processingRef.current = true;
312
+ setPermissionRequest({
313
+ toolName: next.toolName,
314
+ toolArgs: next.toolArgs,
315
+ resolve: (result) => {
316
+ permissionQueueRef.current.shift();
317
+ processingRef.current = false;
318
+ setPermissionRequest(null);
319
+ next.resolve(result);
320
+ setTimeout(() => processNextPermission(), 0);
321
+ }
322
+ });
323
+ }, []);
324
+ const permissionHandler = useCallback(
325
+ (toolName, toolArgs) => new Promise((resolve) => {
326
+ permissionQueueRef.current.push({ toolName, toolArgs, resolve });
327
+ processNextPermission();
328
+ }),
329
+ [processNextPermission]
330
+ );
331
+ const stateRef = useRef(null);
332
+ if (stateRef.current === null) {
333
+ stateRef.current = initializeSession(props, permissionHandler);
334
+ }
335
+ const { interactiveSession, registry, manager } = stateRef.current;
336
+ manager.onChange = () => forceRender((n) => n + 1);
337
+ if (manager.history.length === 0) {
338
+ const restored = interactiveSession.getFullHistory();
339
+ if (restored.length > 0) {
340
+ manager.syncHistory(restored);
341
+ }
342
+ }
343
+ useEffect(() => {
344
+ interactiveSession.on("text_delta", manager.onTextDelta);
345
+ interactiveSession.on("tool_start", manager.onToolStart);
346
+ interactiveSession.on("tool_end", manager.onToolEnd);
347
+ interactiveSession.on("thinking", manager.onThinking);
348
+ interactiveSession.on("complete", manager.onComplete);
349
+ interactiveSession.on("interrupted", manager.onInterrupted);
350
+ interactiveSession.on("error", manager.onError);
351
+ const initCheck = setInterval(() => {
352
+ try {
353
+ const ctx = interactiveSession.getContextState();
354
+ manager.setContextState({
355
+ percentage: ctx.usedPercentage,
356
+ usedTokens: ctx.usedTokens,
357
+ maxTokens: ctx.maxTokens
358
+ });
359
+ const restored = interactiveSession.getFullHistory();
360
+ if (restored.length > 0) {
361
+ manager.syncHistory(restored);
362
+ }
363
+ clearInterval(initCheck);
364
+ } catch {
365
+ }
366
+ }, 200);
367
+ return () => {
368
+ clearInterval(initCheck);
369
+ interactiveSession.off("text_delta", manager.onTextDelta);
370
+ interactiveSession.off("tool_start", manager.onToolStart);
371
+ interactiveSession.off("tool_end", manager.onToolEnd);
372
+ interactiveSession.off("thinking", manager.onThinking);
373
+ interactiveSession.off("complete", manager.onComplete);
374
+ interactiveSession.off("interrupted", manager.onInterrupted);
375
+ interactiveSession.off("error", manager.onError);
376
+ };
377
+ }, [interactiveSession, manager]);
378
+ useEffect(() => {
379
+ manager.syncHistory(interactiveSession.getFullHistory());
380
+ if (!manager.isThinking) {
381
+ manager.setPendingPrompt(interactiveSession.getPendingPrompt());
382
+ }
383
+ }, [manager.isThinking, interactiveSession, manager]);
384
+ const handleSubmit = useCallback(
385
+ async (input) => {
386
+ if (input.startsWith("/")) {
387
+ const parts = input.slice(1).split(/\s+/);
388
+ const cmd = parts[0]?.toLowerCase() ?? "";
389
+ const args = parts.slice(1).join(" ");
390
+ const result = await interactiveSession.executeCommand(cmd, args);
391
+ if (result) {
392
+ manager.addEntry(messageToHistoryEntry(createSystemMessage(result.message)));
393
+ const effects = interactiveSession;
394
+ if (result.data?.modelId) {
395
+ effects._pendingModelId = result.data.modelId;
396
+ return;
397
+ }
398
+ if (result.data?.language) {
399
+ effects._pendingLanguage = result.data.language;
400
+ return;
401
+ }
402
+ if (result.data?.resetRequested) {
403
+ effects._resetRequested = true;
404
+ return;
405
+ }
406
+ if (result.data?.triggerResumePicker) {
407
+ effects._triggerResumePicker = true;
408
+ return;
409
+ }
410
+ if (result.data?.name) {
411
+ effects._sessionName = result.data.name;
412
+ return;
413
+ }
414
+ const ctx = interactiveSession.getContextState();
415
+ manager.setContextState({
416
+ percentage: ctx.usedPercentage,
417
+ usedTokens: ctx.usedTokens,
418
+ maxTokens: ctx.maxTokens
419
+ });
420
+ return;
421
+ }
422
+ const skillCmd = registry.getCommands().find((c) => c.name === cmd && (c.source === "skill" || c.source === "plugin"));
423
+ if (skillCmd) {
424
+ manager.addEntry({
425
+ id: randomUUID(),
426
+ timestamp: /* @__PURE__ */ new Date(),
427
+ category: "event",
428
+ type: "skill-invocation",
429
+ data: {
430
+ skillName: cmd,
431
+ source: skillCmd.source,
432
+ message: `Invoking ${skillCmd.source}: ${cmd}`
433
+ }
434
+ });
435
+ const prompt = await buildSkillPrompt(input, registry);
436
+ if (prompt) {
437
+ const qualifiedName = registry.resolveQualifiedName(cmd);
438
+ const hookInput = qualifiedName ? `/${qualifiedName}${input.slice(1 + cmd.length)}` : input;
439
+ await interactiveSession.submit(prompt, input, hookInput);
440
+ manager.setPendingPrompt(interactiveSession.getPendingPrompt());
441
+ return;
442
+ }
443
+ }
444
+ if (cmd === "exit") {
445
+ interactiveSession._exitRequested = true;
446
+ return;
447
+ }
448
+ if (cmd === "plugin") {
449
+ interactiveSession._triggerPluginTUI = true;
450
+ return;
451
+ }
452
+ manager.addEntry(
453
+ messageToHistoryEntry(
454
+ createSystemMessage(`Unknown command "/${cmd}". Type /help for help.`)
455
+ )
456
+ );
457
+ return;
458
+ }
459
+ await interactiveSession.submit(input);
460
+ manager.setPendingPrompt(interactiveSession.getPendingPrompt());
461
+ },
462
+ [interactiveSession, registry, manager]
463
+ );
464
+ const handleAbort = useCallback(() => {
465
+ manager.setAborting(true);
466
+ interactiveSession.abort();
467
+ }, [interactiveSession, manager]);
468
+ const handleCancelQueue = useCallback(() => {
469
+ interactiveSession.cancelQueue();
470
+ manager.setPendingPrompt(null);
471
+ }, [interactiveSession, manager]);
472
+ return {
473
+ interactiveSession,
474
+ registry,
475
+ history: manager.history,
476
+ addEntry: (entry) => manager.addEntry(entry),
477
+ streamingText: manager.streamingText,
478
+ activeTools: manager.activeTools,
479
+ isThinking: manager.isThinking,
480
+ isAborting: manager.isAborting,
481
+ pendingPrompt: manager.pendingPrompt,
482
+ permissionRequest,
483
+ contextState: manager.contextState,
484
+ handleSubmit,
485
+ handleAbort,
486
+ handleCancelQueue
487
+ };
488
+ }
489
+
490
+ // src/ui/hooks/usePluginCallbacks.ts
491
+ import { useMemo } from "react";
492
+ import { homedir as homedir3 } from "os";
493
+ import { join as join4 } from "path";
494
+ import {
495
+ PluginSettingsStore,
496
+ BundlePluginLoader as BundlePluginLoader2,
497
+ BundlePluginInstaller,
498
+ MarketplaceClient
499
+ } from "@robota-sdk/agent-sdk";
500
+ function usePluginCallbacks(cwd) {
501
+ return useMemo(() => {
502
+ const home = homedir3();
503
+ const pluginsDir = join4(home, ".robota", "plugins");
504
+ const userSettingsPath = join4(home, ".robota", "settings.json");
505
+ const settingsStore = new PluginSettingsStore(userSettingsPath);
506
+ const marketplace = new MarketplaceClient({ pluginsDir });
507
+ const installer = new BundlePluginInstaller({
508
+ pluginsDir,
509
+ settingsStore,
510
+ marketplaceClient: marketplace
511
+ });
512
+ const loader = new BundlePluginLoader2(pluginsDir);
513
+ return {
514
+ listInstalled: async () => {
515
+ const plugins = await loader.loadAll();
516
+ const enabledMap = settingsStore.getEnabledPlugins();
517
+ return plugins.map((p) => {
518
+ const parts = p.pluginDir.split("/");
519
+ const cacheIdx = parts.indexOf("cache");
520
+ const marketplaceName = cacheIdx >= 0 ? parts[cacheIdx + 1] : "";
521
+ const fullId = marketplaceName ? `${p.manifest.name}@${marketplaceName}` : p.manifest.name;
522
+ return {
523
+ name: fullId,
524
+ description: p.manifest.description,
525
+ enabled: enabledMap[fullId] !== false && enabledMap[p.manifest.name] !== false
526
+ };
527
+ });
528
+ },
529
+ listAvailablePlugins: async (marketplaceName) => {
530
+ let manifest;
531
+ try {
532
+ manifest = marketplace.fetchManifest(marketplaceName);
533
+ } catch {
534
+ return [];
535
+ }
536
+ const installed = installer.getInstalledPlugins();
537
+ const installedNames = new Set(Object.values(installed).map((r) => r.pluginName));
538
+ return manifest.plugins.map((p) => ({
539
+ name: p.name,
540
+ description: p.description,
541
+ installed: installedNames.has(p.name)
542
+ }));
543
+ },
544
+ install: async (pluginId, scope) => {
545
+ const [name, marketplaceName] = pluginId.split("@");
546
+ if (!name || !marketplaceName) {
547
+ throw new Error("Plugin ID must be in format: name@marketplace");
548
+ }
549
+ if (scope === "project") {
550
+ const projectPluginsDir = join4(cwd, ".robota", "plugins");
551
+ const projectInstaller = new BundlePluginInstaller({
552
+ pluginsDir: projectPluginsDir,
553
+ settingsStore,
554
+ marketplaceClient: marketplace
555
+ });
556
+ await projectInstaller.install(name, marketplaceName);
557
+ } else {
558
+ await installer.install(name, marketplaceName);
559
+ }
560
+ },
561
+ uninstall: async (pluginId) => {
562
+ await installer.uninstall(pluginId);
563
+ },
564
+ enable: async (pluginId) => {
565
+ await installer.enable(pluginId);
566
+ },
567
+ disable: async (pluginId) => {
568
+ await installer.disable(pluginId);
569
+ },
570
+ marketplaceAdd: async (source) => {
571
+ if (source.includes("/") && !source.includes(":")) {
572
+ return marketplace.addMarketplace({ type: "github", repo: source });
573
+ } else {
574
+ return marketplace.addMarketplace({ type: "git", url: source });
575
+ }
576
+ },
577
+ marketplaceRemove: async (name) => {
578
+ const installedFromMarketplace = installer.getPluginsByMarketplace(name);
579
+ for (const record of installedFromMarketplace) {
580
+ await installer.uninstall(`${record.pluginName}@${record.marketplace}`);
581
+ }
582
+ marketplace.removeMarketplace(name);
583
+ },
584
+ marketplaceUpdate: async (name) => {
585
+ marketplace.updateMarketplace(name);
586
+ },
587
+ marketplaceList: async () => {
588
+ return marketplace.listMarketplaces().map((m) => ({
589
+ name: m.name,
590
+ type: m.source.type
591
+ }));
592
+ },
593
+ reloadPlugins: async () => {
594
+ }
595
+ };
596
+ }, [cwd]);
597
+ }
598
+
599
+ // src/ui/MessageList.tsx
600
+ import React2 from "react";
601
+ import { Box as Box2, Text as Text2 } from "ink";
602
+ import { isToolMessage, isAssistantMessage } from "@robota-sdk/agent-core";
603
+
604
+ // src/ui/render-markdown.ts
605
+ import { marked } from "marked";
606
+ import TerminalRenderer from "marked-terminal";
607
+ marked.setOptions({
608
+ renderer: new TerminalRenderer()
609
+ });
610
+ function renderMarkdown(md) {
611
+ const result = marked.parse(md);
612
+ return typeof result === "string" ? result.trimEnd() : md;
613
+ }
614
+
615
+ // src/ui/DiffBlock.tsx
616
+ import { Box, Text } from "ink";
617
+ import { jsxs } from "react/jsx-runtime";
618
+ var MAX_DIFF_LINES = 12;
619
+ var TRUNCATED_SHOW = 10;
620
+ function DiffBlock({ file, lines }) {
621
+ const truncated = lines.length > MAX_DIFF_LINES;
622
+ const visible = truncated ? lines.slice(0, TRUNCATED_SHOW) : lines;
623
+ const remaining = lines.length - TRUNCATED_SHOW;
624
+ const maxLineNum = Math.max(...visible.map((l) => l.lineNumber), 0);
625
+ const numWidth = String(maxLineNum).length;
626
+ return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", marginLeft: 4, children: [
627
+ file && /* @__PURE__ */ jsxs(Text, { color: "white", dimColor: true, children: [
628
+ "\u2502 ",
629
+ file
630
+ ] }),
631
+ visible.map((line, i) => {
632
+ const lineNum = String(line.lineNumber).padStart(numWidth, " ");
633
+ if (line.type === "context") {
634
+ return /* @__PURE__ */ jsxs(Text, { color: "white", dimColor: true, children: [
635
+ "\u2502 ",
636
+ lineNum,
637
+ " ",
638
+ line.text
639
+ ] }, i);
640
+ }
641
+ const prefix = line.type === "remove" ? "-" : "+";
642
+ const bgColor = line.type === "remove" ? "#5c1a1a" : "#1a3d1a";
643
+ const fgColor = line.type === "remove" ? "#ff9999" : "#99ff99";
644
+ return /* @__PURE__ */ jsxs(Text, { color: fgColor, backgroundColor: bgColor, children: [
645
+ "\u2502 ",
646
+ lineNum,
647
+ " ",
648
+ prefix,
649
+ " ",
650
+ line.text
651
+ ] }, i);
652
+ }),
653
+ truncated && /* @__PURE__ */ jsxs(Text, { color: "white", dimColor: true, children: [
654
+ "\u2502 ... and ",
655
+ remaining,
656
+ " more lines"
657
+ ] })
658
+ ] });
659
+ }
660
+
661
+ // src/ui/MessageList.tsx
662
+ import { Fragment, jsx, jsxs as jsxs2 } from "react/jsx-runtime";
663
+ function RoleLabel({ role }) {
664
+ switch (role) {
665
+ case "user":
666
+ return /* @__PURE__ */ jsxs2(Text2, { color: "green", bold: true, children: [
667
+ "You:",
668
+ " "
669
+ ] });
670
+ case "assistant":
671
+ return /* @__PURE__ */ jsxs2(Text2, { color: "cyan", bold: true, children: [
672
+ "Robota:",
673
+ " "
674
+ ] });
675
+ case "system":
676
+ return /* @__PURE__ */ jsxs2(Text2, { color: "yellow", bold: true, children: [
677
+ "System:",
678
+ " "
679
+ ] });
680
+ case "tool":
681
+ return /* @__PURE__ */ jsxs2(Text2, { color: "white", bold: true, children: [
682
+ "Tool:",
683
+ " "
684
+ ] });
685
+ }
686
+ }
687
+ function ToolMessage({ message }) {
688
+ if (!isToolMessage(message)) {
689
+ return /* @__PURE__ */ jsx(Fragment, {});
690
+ }
691
+ const toolName = message.name;
692
+ const content = message.content;
693
+ let summaries = null;
694
+ try {
695
+ const parsed = JSON.parse(content);
696
+ if (Array.isArray(parsed) && parsed.length > 0 && typeof parsed[0].line === "string") {
697
+ summaries = parsed;
698
+ }
699
+ } catch {
700
+ }
701
+ if (summaries) {
702
+ return /* @__PURE__ */ jsxs2(Box2, { flexDirection: "column", marginBottom: 1, children: [
703
+ /* @__PURE__ */ jsxs2(Box2, { children: [
704
+ /* @__PURE__ */ jsxs2(Text2, { color: "white", bold: true, children: [
705
+ "Tool:",
706
+ " "
707
+ ] }),
708
+ toolName && /* @__PURE__ */ jsxs2(Text2, { color: "white", dimColor: true, children: [
709
+ "[",
710
+ toolName,
711
+ "]"
712
+ ] })
713
+ ] }),
714
+ /* @__PURE__ */ jsx(Text2, { children: " " }),
715
+ summaries.map((s, i) => /* @__PURE__ */ jsxs2(Box2, { flexDirection: "column", children: [
716
+ /* @__PURE__ */ jsxs2(Text2, { color: "green", children: [
717
+ " ",
718
+ "\u2713",
719
+ " ",
720
+ s.line
721
+ ] }),
722
+ s.diffLines && s.diffLines.length > 0 && /* @__PURE__ */ jsx(DiffBlock, { file: s.diffFile, lines: s.diffLines })
723
+ ] }, i))
724
+ ] });
725
+ }
726
+ const lines = content.split("\n").filter((l) => l.trim());
727
+ return /* @__PURE__ */ jsxs2(Box2, { flexDirection: "column", marginBottom: 1, children: [
728
+ /* @__PURE__ */ jsxs2(Box2, { children: [
729
+ /* @__PURE__ */ jsxs2(Text2, { color: "white", bold: true, children: [
730
+ "Tool:",
731
+ " "
732
+ ] }),
733
+ toolName && /* @__PURE__ */ jsxs2(Text2, { color: "white", dimColor: true, children: [
734
+ "[",
735
+ toolName,
736
+ "]"
737
+ ] })
738
+ ] }),
739
+ /* @__PURE__ */ jsx(Text2, { children: " " }),
740
+ lines.map((line, i) => /* @__PURE__ */ jsxs2(Text2, { color: "green", children: [
741
+ " ",
742
+ "\u2713",
743
+ " ",
744
+ line
745
+ ] }, i))
746
+ ] });
747
+ }
748
+ var MessageItem = React2.memo(function MessageItem2({
749
+ message
750
+ }) {
751
+ if (isToolMessage(message)) {
752
+ return /* @__PURE__ */ jsx(ToolMessage, { message });
753
+ }
754
+ const content = message.content ?? "";
755
+ const isInterrupted = message.state === "interrupted";
756
+ return /* @__PURE__ */ jsxs2(Box2, { flexDirection: "column", marginBottom: 1, children: [
757
+ /* @__PURE__ */ jsx(Box2, { children: /* @__PURE__ */ jsx(RoleLabel, { role: message.role }) }),
758
+ /* @__PURE__ */ jsx(Text2, { children: " " }),
759
+ /* @__PURE__ */ jsx(Box2, { marginLeft: 2, children: /* @__PURE__ */ jsx(Text2, { wrap: "wrap", children: isAssistantMessage(message) ? renderMarkdown(content + (isInterrupted ? "\n\n_(interrupted)_" : "")) : content }) })
760
+ ] });
761
+ });
762
+ function ToolSummaryEntry({ entry }) {
763
+ const data = entry.data;
764
+ const lines = data?.summary?.split("\n") ?? [];
765
+ return /* @__PURE__ */ jsxs2(Box2, { flexDirection: "column", marginBottom: 1, children: [
766
+ /* @__PURE__ */ jsx(Box2, { children: /* @__PURE__ */ jsxs2(Text2, { color: "white", bold: true, children: [
767
+ "Tool:",
768
+ " "
769
+ ] }) }),
770
+ /* @__PURE__ */ jsx(Text2, { children: " " }),
771
+ lines.map((line, i) => /* @__PURE__ */ jsxs2(Text2, { color: "green", children: [
772
+ " ",
773
+ line
774
+ ] }, i))
775
+ ] });
776
+ }
777
+ function EventEntry({ entry }) {
778
+ const eventData = entry.data;
779
+ const eventMessage = typeof eventData?.message === "string" ? eventData.message : typeof eventData?.content === "string" ? eventData.content : entry.type;
780
+ return /* @__PURE__ */ jsxs2(Box2, { flexDirection: "column", marginBottom: 1, children: [
781
+ /* @__PURE__ */ jsx(Box2, { children: /* @__PURE__ */ jsxs2(Text2, { color: "yellow", bold: true, children: [
782
+ "System:",
783
+ " "
784
+ ] }) }),
785
+ /* @__PURE__ */ jsx(Text2, { children: " " }),
786
+ /* @__PURE__ */ jsx(Box2, { marginLeft: 2, children: /* @__PURE__ */ jsx(Text2, { wrap: "wrap", children: eventMessage }) })
787
+ ] });
788
+ }
789
+ function EntryItem({ entry }) {
790
+ if (entry.category === "chat") {
791
+ const message = entry.data;
792
+ return /* @__PURE__ */ jsx(MessageItem, { message });
793
+ }
794
+ if (entry.type === "tool-summary") {
795
+ return /* @__PURE__ */ jsx(ToolSummaryEntry, { entry });
796
+ }
797
+ if (entry.type === "tool-start" || entry.type === "tool-end") {
798
+ return /* @__PURE__ */ jsx(Fragment, {});
799
+ }
800
+ return /* @__PURE__ */ jsx(EventEntry, { entry });
801
+ }
802
+ function MessageList({ history }) {
803
+ return /* @__PURE__ */ jsx(Box2, { flexDirection: "column", children: history.map((entry) => /* @__PURE__ */ jsx(EntryItem, { entry }, entry.id)) });
804
+ }
805
+
806
+ // src/ui/StatusBar.tsx
807
+ import { Box as Box3, Text as Text3 } from "ink";
808
+ import { formatTokenCount } from "@robota-sdk/agent-core";
809
+ import { Fragment as Fragment2, jsx as jsx2, jsxs as jsxs3 } from "react/jsx-runtime";
810
+ var CONTEXT_YELLOW_THRESHOLD = 70;
811
+ var CONTEXT_RED_THRESHOLD = 90;
812
+ function getContextColor(percentage) {
813
+ if (percentage >= CONTEXT_RED_THRESHOLD) return "red";
814
+ if (percentage >= CONTEXT_YELLOW_THRESHOLD) return "yellow";
815
+ return "green";
816
+ }
817
+ function StatusBar({
818
+ permissionMode,
819
+ modelName,
820
+ sessionId: _sessionId,
821
+ messageCount,
822
+ isThinking,
823
+ contextPercentage,
824
+ contextUsedTokens,
825
+ contextMaxTokens,
826
+ sessionName
827
+ }) {
828
+ const contextColor = getContextColor(contextPercentage);
829
+ return /* @__PURE__ */ jsxs3(
830
+ Box3,
831
+ {
832
+ borderStyle: "single",
833
+ borderColor: "gray",
834
+ paddingLeft: 1,
835
+ paddingRight: 1,
836
+ justifyContent: "space-between",
837
+ children: [
838
+ /* @__PURE__ */ jsxs3(Text3, { children: [
839
+ /* @__PURE__ */ jsx2(Text3, { color: "cyan", bold: true, children: "Mode:" }),
840
+ " ",
841
+ /* @__PURE__ */ jsx2(Text3, { children: permissionMode }),
842
+ sessionName && /* @__PURE__ */ jsxs3(Fragment2, { children: [
843
+ " | ",
844
+ /* @__PURE__ */ jsx2(Text3, { color: "magenta", children: sessionName })
845
+ ] }),
846
+ " | ",
847
+ /* @__PURE__ */ jsx2(Text3, { dimColor: true, children: modelName }),
848
+ " | ",
849
+ /* @__PURE__ */ jsxs3(Text3, { color: contextColor, children: [
850
+ "Context: ",
851
+ Math.round(contextPercentage),
852
+ "% (",
853
+ formatTokenCount(contextUsedTokens),
854
+ "/",
855
+ formatTokenCount(contextMaxTokens),
856
+ ")"
857
+ ] })
858
+ ] }),
859
+ /* @__PURE__ */ jsxs3(Text3, { children: [
860
+ isThinking && /* @__PURE__ */ jsx2(Text3, { color: "yellow", children: "Thinking... " }),
861
+ /* @__PURE__ */ jsxs3(Text3, { dimColor: true, children: [
862
+ "msgs: ",
863
+ messageCount
864
+ ] })
865
+ ] })
866
+ ]
867
+ }
868
+ );
869
+ }
870
+
871
+ // src/ui/InputArea.tsx
872
+ import React5, { useState as useState4, useCallback as useCallback2, useMemo as useMemo2, useRef as useRef3 } from "react";
873
+ import { Box as Box5, Text as Text7, useInput as useInput2, useStdout } from "ink";
874
+
875
+ // src/ui/CjkTextInput.tsx
876
+ import { useRef as useRef2, useState as useState2 } from "react";
877
+ import { Text as Text4, useInput } from "ink";
878
+ import chalk from "chalk";
879
+ import stringWidth from "string-width";
880
+ import { jsx as jsx3 } from "react/jsx-runtime";
881
+ var PASTE_START = "[200~";
882
+ var PASTE_END = "[201~";
883
+ function filterPrintable(input) {
884
+ if (!input || input.length === 0) return "";
885
+ return input.replace(/[\x00-\x1f\x7f]/g, "");
886
+ }
887
+ function insertAtCursor(value, cursor, input) {
888
+ const next = value.slice(0, cursor) + input + value.slice(cursor);
889
+ return { value: next, cursor: cursor + input.length };
890
+ }
891
+ function displayOffset(chars, charIndex, width) {
892
+ let offset = 0;
893
+ for (let i = 0; i < charIndex && i < chars.length; i++) {
894
+ const w = stringWidth(chars[i]);
895
+ const col = offset % width;
896
+ if (col + w > width) offset += width - col;
897
+ offset += w;
898
+ }
899
+ return offset;
900
+ }
901
+ function charIndexAtDisplayOffset(chars, target, width) {
902
+ let offset = 0;
903
+ for (let i = 0; i < chars.length; i++) {
904
+ if (offset >= target) return i;
905
+ const w = stringWidth(chars[i]);
906
+ const col = offset % width;
907
+ if (col + w > width) offset += width - col;
908
+ offset += w;
909
+ }
910
+ return chars.length;
911
+ }
912
+ function CjkTextInput({
913
+ value,
914
+ onChange,
915
+ onSubmit,
916
+ onPaste,
917
+ placeholder = "",
918
+ focus = true,
919
+ showCursor = true,
920
+ availableWidth
921
+ }) {
922
+ const valueRef = useRef2(value);
923
+ const cursorRef = useRef2(value.length);
924
+ const [, forceRender] = useState2(0);
925
+ const isPastingRef = useRef2(false);
926
+ const pasteBufferRef = useRef2("");
927
+ if (value !== valueRef.current) {
928
+ valueRef.current = value;
929
+ cursorRef.current = value.length;
930
+ }
931
+ useInput(
932
+ (input, key) => {
933
+ try {
934
+ if (input === PASTE_START || input.startsWith(PASTE_START)) {
935
+ isPastingRef.current = true;
936
+ const afterMarker = input.slice(PASTE_START.length);
937
+ if (afterMarker.length > 0) {
938
+ pasteBufferRef.current += afterMarker;
939
+ }
940
+ return;
941
+ }
942
+ if (isPastingRef.current) {
943
+ if (input === PASTE_END || input.includes(PASTE_END)) {
944
+ const beforeMarker = input.split(PASTE_END)[0] ?? "";
945
+ pasteBufferRef.current += beforeMarker;
946
+ const text = pasteBufferRef.current.replace(/\r\n?/g, "\n");
947
+ pasteBufferRef.current = "";
948
+ isPastingRef.current = false;
949
+ if (text.length > 0) {
950
+ if (text.includes("\n") && onPaste) {
951
+ onPaste(text);
952
+ } else {
953
+ const printable2 = filterPrintable(text);
954
+ if (printable2.length > 0) {
955
+ const result2 = insertAtCursor(valueRef.current, cursorRef.current, printable2);
956
+ cursorRef.current = result2.cursor;
957
+ valueRef.current = result2.value;
958
+ onChange(result2.value);
959
+ }
960
+ }
961
+ }
962
+ } else {
963
+ pasteBufferRef.current += input;
964
+ }
965
+ return;
966
+ }
967
+ if (key.ctrl && input === "c" || key.tab || key.shift && key.tab) {
968
+ return;
969
+ }
970
+ if (key.upArrow || key.downArrow) {
971
+ if (availableWidth && availableWidth > 0) {
972
+ const chars = [...valueRef.current];
973
+ const offset = displayOffset(chars, cursorRef.current, availableWidth);
974
+ const target = key.upArrow ? offset - availableWidth : offset + availableWidth;
975
+ if (target >= 0) {
976
+ const newCursor = charIndexAtDisplayOffset(chars, target, availableWidth);
977
+ if (newCursor !== cursorRef.current) {
978
+ cursorRef.current = newCursor;
979
+ forceRender((n) => n + 1);
980
+ }
981
+ }
982
+ }
983
+ return;
984
+ }
985
+ if (key.return) {
986
+ onSubmit?.(valueRef.current);
987
+ return;
988
+ }
989
+ if (input.length > 1 && (input.includes("\n") || input.includes("\r")) && onPaste) {
990
+ onPaste(input.replace(/\r\n?/g, "\n"));
991
+ return;
992
+ }
993
+ if (key.leftArrow) {
994
+ if (cursorRef.current > 0) {
995
+ cursorRef.current -= 1;
996
+ forceRender((n) => n + 1);
997
+ }
998
+ return;
999
+ }
1000
+ if (key.rightArrow) {
1001
+ if (cursorRef.current < valueRef.current.length) {
1002
+ cursorRef.current += 1;
1003
+ forceRender((n) => n + 1);
1004
+ }
1005
+ return;
1006
+ }
1007
+ if (key.backspace || key.delete) {
1008
+ if (cursorRef.current > 0) {
1009
+ const v = valueRef.current;
1010
+ const next = v.slice(0, cursorRef.current - 1) + v.slice(cursorRef.current);
1011
+ cursorRef.current -= 1;
1012
+ valueRef.current = next;
1013
+ onChange(next);
1014
+ }
1015
+ return;
1016
+ }
1017
+ const printable = filterPrintable(input);
1018
+ if (printable.length === 0) return;
1019
+ const result = insertAtCursor(valueRef.current, cursorRef.current, printable);
1020
+ cursorRef.current = result.cursor;
1021
+ valueRef.current = result.value;
1022
+ onChange(result.value);
1023
+ } catch {
1024
+ }
1025
+ },
1026
+ { isActive: focus }
1027
+ );
1028
+ return /* @__PURE__ */ jsx3(Text4, { children: renderWithCursor(valueRef.current, cursorRef.current, placeholder, showCursor && focus) });
1029
+ }
1030
+ function renderWithCursor(value, cursorOffset, placeholder, showCursor) {
1031
+ if (!showCursor) {
1032
+ return value.length > 0 ? value : placeholder ? chalk.gray(placeholder) : "";
1033
+ }
1034
+ if (value.length === 0) {
1035
+ if (placeholder.length > 0) {
1036
+ return chalk.inverse(placeholder[0]) + chalk.gray(placeholder.slice(1));
1037
+ }
1038
+ return chalk.inverse(" ");
1039
+ }
1040
+ const chars = [...value];
1041
+ let rendered = "";
1042
+ for (let i = 0; i < chars.length; i++) {
1043
+ const char = chars[i] ?? "";
1044
+ rendered += i === cursorOffset ? chalk.inverse(char) : char;
1045
+ }
1046
+ if (cursorOffset >= chars.length) {
1047
+ rendered += chalk.inverse(" ");
1048
+ }
1049
+ return rendered;
1050
+ }
1051
+
1052
+ // src/ui/WaveText.tsx
1053
+ import { useState as useState3, useEffect as useEffect2 } from "react";
1054
+ import { Text as Text5 } from "ink";
1055
+ import { jsx as jsx4 } from "react/jsx-runtime";
1056
+ var WAVE_COLORS = ["#666666", "#888888", "#aaaaaa", "#888888"];
1057
+ var INTERVAL_MS = 400;
1058
+ var CHARS_PER_GROUP = 4;
1059
+ function WaveText({ text }) {
1060
+ const [tick, setTick] = useState3(0);
1061
+ useEffect2(() => {
1062
+ const timer = setInterval(() => {
1063
+ setTick((prev) => prev + 1);
1064
+ }, INTERVAL_MS);
1065
+ return () => clearInterval(timer);
1066
+ }, []);
1067
+ const chars = [...text];
1068
+ return /* @__PURE__ */ jsx4(Text5, { children: chars.map((char, i) => {
1069
+ const group = Math.floor(i / CHARS_PER_GROUP);
1070
+ const colorIndex = (tick + group) % WAVE_COLORS.length;
1071
+ return /* @__PURE__ */ jsx4(Text5, { color: WAVE_COLORS[colorIndex], children: char }, i);
1072
+ }) });
1073
+ }
1074
+
1075
+ // src/ui/SlashAutocomplete.tsx
1076
+ import { Box as Box4, Text as Text6 } from "ink";
1077
+ import { jsx as jsx5, jsxs as jsxs4 } from "react/jsx-runtime";
1078
+ var MAX_VISIBLE = 8;
1079
+ function CommandRow(props) {
1080
+ const { cmd, isSelected, showSlash } = props;
1081
+ const indicator = isSelected ? "\u25B8 " : " ";
1082
+ const nameColor = isSelected ? "cyan" : void 0;
1083
+ const dimmed = !isSelected;
1084
+ return /* @__PURE__ */ jsx5(Box4, { children: /* @__PURE__ */ jsxs4(Text6, { color: nameColor, dimColor: dimmed, children: [
1085
+ indicator,
1086
+ showSlash ? `/${cmd.name} ${cmd.description}` : cmd.description
1087
+ ] }) });
1088
+ }
1089
+ function SlashAutocomplete({
1090
+ commands,
1091
+ selectedIndex,
1092
+ visible,
1093
+ isSubcommandMode
1094
+ }) {
1095
+ if (!visible || commands.length === 0) return null;
1096
+ const scrollOffset = computeScrollOffset(selectedIndex, commands.length);
1097
+ const visibleCommands = commands.slice(scrollOffset, scrollOffset + MAX_VISIBLE);
1098
+ return /* @__PURE__ */ jsx5(Box4, { flexDirection: "column", borderStyle: "round", borderColor: "gray", paddingX: 1, children: visibleCommands.map((cmd, i) => /* @__PURE__ */ jsx5(
1099
+ CommandRow,
1100
+ {
1101
+ cmd,
1102
+ isSelected: scrollOffset + i === selectedIndex,
1103
+ showSlash: !isSubcommandMode
1104
+ },
1105
+ cmd.name
1106
+ )) });
1107
+ }
1108
+ function computeScrollOffset(selectedIndex, total) {
1109
+ if (total <= MAX_VISIBLE) return 0;
1110
+ if (selectedIndex < MAX_VISIBLE) return 0;
1111
+ const maxOffset = total - MAX_VISIBLE;
1112
+ return Math.min(selectedIndex - MAX_VISIBLE + 1, maxOffset);
1113
+ }
1114
+
1115
+ // src/utils/paste-labels.ts
1116
+ var PASTE_LABEL_RE = /\[Pasted text #(\d+)(?: \+\d+ lines)?\]/g;
1117
+ function expandPasteLabels(text, store) {
1118
+ return text.replace(PASTE_LABEL_RE, (_, id) => store.get(Number(id)) ?? "");
1119
+ }
1120
+
1121
+ // src/ui/InputArea.tsx
1122
+ import { jsx as jsx6, jsxs as jsxs5 } from "react/jsx-runtime";
1123
+ function parseSlashInput(value) {
1124
+ if (!value.startsWith("/")) return { isSlash: false, parentCommand: "", filter: "" };
1125
+ const afterSlash = value.slice(1);
1126
+ const spaceIndex = afterSlash.indexOf(" ");
1127
+ if (spaceIndex === -1) return { isSlash: true, parentCommand: "", filter: afterSlash };
1128
+ const parent = afterSlash.slice(0, spaceIndex);
1129
+ const rest = afterSlash.slice(spaceIndex + 1);
1130
+ return { isSlash: true, parentCommand: parent, filter: rest };
1131
+ }
1132
+ function useAutocomplete(value, registry) {
1133
+ const [selectedIndex, setSelectedIndex] = useState4(0);
1134
+ const [dismissed, setDismissed] = useState4(false);
1135
+ const prevValueRef = React5.useRef(value);
1136
+ if (prevValueRef.current !== value) {
1137
+ prevValueRef.current = value;
1138
+ if (dismissed) setDismissed(false);
1139
+ }
1140
+ const parsed = parseSlashInput(value);
1141
+ const isSubcommandMode = parsed.isSlash && parsed.parentCommand.length > 0;
1142
+ const filteredCommands = useMemo2(() => {
1143
+ if (!registry || !parsed.isSlash || dismissed) return [];
1144
+ if (isSubcommandMode) {
1145
+ const subs = registry.getSubcommands(parsed.parentCommand);
1146
+ if (subs.length === 0) return [];
1147
+ if (!parsed.filter) return subs;
1148
+ const lower = parsed.filter.toLowerCase();
1149
+ return subs.filter((c) => c.name.toLowerCase().startsWith(lower));
1150
+ }
1151
+ return registry.getCommands(parsed.filter);
1152
+ }, [registry, parsed.isSlash, parsed.parentCommand, parsed.filter, dismissed, isSubcommandMode]);
1153
+ const showPopup = parsed.isSlash && filteredCommands.length > 0 && !dismissed;
1154
+ if (selectedIndex >= filteredCommands.length && filteredCommands.length > 0) {
1155
+ setSelectedIndex(filteredCommands.length - 1);
1156
+ }
1157
+ return {
1158
+ showPopup,
1159
+ filteredCommands,
1160
+ selectedIndex,
1161
+ setSelectedIndex,
1162
+ isSubcommandMode,
1163
+ setShowPopup: (val) => {
1164
+ if (typeof val === "function") {
1165
+ setDismissed((prev) => {
1166
+ const nextVal = val(!prev);
1167
+ return !nextVal;
1168
+ });
1169
+ } else {
1170
+ setDismissed(!val);
1171
+ }
1172
+ }
1173
+ };
1174
+ }
1175
+ var BORDER_HORIZONTAL = 2;
1176
+ var PADDING_LEFT = 1;
1177
+ var PROMPT_WIDTH = 2;
1178
+ var INPUT_AREA_OVERHEAD = BORDER_HORIZONTAL + PADDING_LEFT + PROMPT_WIDTH;
1179
+ function InputArea({
1180
+ onSubmit,
1181
+ onCancelQueue,
1182
+ isDisabled,
1183
+ isAborting,
1184
+ pendingPrompt,
1185
+ registry,
1186
+ sessionName
1187
+ }) {
1188
+ const [value, setValue] = useState4("");
1189
+ const pasteStore = useRef3(/* @__PURE__ */ new Map());
1190
+ const { stdout } = useStdout();
1191
+ const terminalColumns = stdout?.columns ?? 80;
1192
+ const availableWidth = Math.max(1, terminalColumns - INPUT_AREA_OVERHEAD);
1193
+ const pasteIdRef = useRef3(0);
1194
+ const {
1195
+ showPopup,
1196
+ filteredCommands,
1197
+ selectedIndex,
1198
+ setSelectedIndex,
1199
+ isSubcommandMode,
1200
+ setShowPopup
1201
+ } = useAutocomplete(value, registry);
1202
+ const handlePaste = useCallback2((text) => {
1203
+ pasteIdRef.current += 1;
1204
+ const id = pasteIdRef.current;
1205
+ pasteStore.current.set(id, text);
1206
+ const lineCount = text.split("\n").length;
1207
+ const label = `[Pasted text #${id} +${lineCount} lines]`;
1208
+ setValue((prev) => prev ? `${prev} ${label}` : label);
1209
+ }, []);
1210
+ const tabCompleteCommand = useCallback2(
1211
+ (cmd) => {
1212
+ const parsed = parseSlashInput(value);
1213
+ if (parsed.parentCommand) {
1214
+ setValue(`/${parsed.parentCommand} ${cmd.name} `);
1215
+ return;
1216
+ }
1217
+ if (cmd.subcommands && cmd.subcommands.length > 0) {
1218
+ setValue(`/${cmd.name} `);
1219
+ setSelectedIndex(0);
1220
+ return;
1221
+ }
1222
+ setValue(`/${cmd.name} `);
1223
+ },
1224
+ [value, setSelectedIndex]
1225
+ );
1226
+ const enterSelectCommand = useCallback2(
1227
+ (cmd) => {
1228
+ const parsed = parseSlashInput(value);
1229
+ if (parsed.parentCommand) {
1230
+ const fullCommand = `/${parsed.parentCommand} ${cmd.name}`;
1231
+ setValue("");
1232
+ onSubmit(fullCommand);
1233
+ return;
1234
+ }
1235
+ if (cmd.subcommands && cmd.subcommands.length > 0) {
1236
+ setValue(`/${cmd.name} `);
1237
+ setSelectedIndex(0);
1238
+ return;
1239
+ }
1240
+ setValue("");
1241
+ onSubmit(`/${cmd.name}`);
1242
+ },
1243
+ [value, onSubmit, setSelectedIndex]
1244
+ );
1245
+ const handleSubmit = useCallback2(
1246
+ (text) => {
1247
+ const trimmed = text.trim();
1248
+ if (trimmed.length === 0) return;
1249
+ if (showPopup && filteredCommands[selectedIndex]) {
1250
+ enterSelectCommand(filteredCommands[selectedIndex]);
1251
+ return;
1252
+ }
1253
+ const expanded = expandPasteLabels(trimmed, pasteStore.current);
1254
+ setValue("");
1255
+ pasteStore.current.clear();
1256
+ pasteIdRef.current = 0;
1257
+ onSubmit(expanded);
1258
+ },
1259
+ [showPopup, filteredCommands, selectedIndex, onSubmit, enterSelectCommand]
1260
+ );
1261
+ useInput2(
1262
+ (_input, key) => {
1263
+ if (!showPopup) return;
1264
+ if (key.upArrow) {
1265
+ setSelectedIndex((prev) => prev > 0 ? prev - 1 : filteredCommands.length - 1);
1266
+ } else if (key.downArrow) {
1267
+ setSelectedIndex((prev) => prev < filteredCommands.length - 1 ? prev + 1 : 0);
1268
+ } else if (key.escape) {
1269
+ setShowPopup(false);
1270
+ } else if (key.tab) {
1271
+ const cmd = filteredCommands[selectedIndex];
1272
+ if (cmd) tabCompleteCommand(cmd);
1273
+ }
1274
+ },
1275
+ { isActive: showPopup && !isDisabled }
1276
+ );
1277
+ useInput2(
1278
+ (_input, key) => {
1279
+ if ((key.backspace || key.delete) && pendingPrompt) {
1280
+ onCancelQueue?.();
1281
+ }
1282
+ },
1283
+ { isActive: !!pendingPrompt }
1284
+ );
1285
+ const borderColor = isAborting ? "yellow" : pendingPrompt ? "cyan" : isDisabled ? "gray" : "green";
1286
+ const innerWidth = Math.max(1, terminalColumns - BORDER_HORIZONTAL);
1287
+ const topBorder = (() => {
1288
+ if (sessionName) {
1289
+ const label = ` "${sessionName}" `;
1290
+ const rightPad = 2;
1291
+ const leftLen = Math.max(0, innerWidth - label.length - rightPad);
1292
+ return { left: "\u250C" + "\u2500".repeat(leftLen), label, right: "\u2500".repeat(rightPad) + "\u2510" };
1293
+ }
1294
+ return { left: "\u250C" + "\u2500".repeat(innerWidth), label: "", right: "\u2510" };
1295
+ })();
1296
+ return /* @__PURE__ */ jsxs5(Box5, { flexDirection: "column", children: [
1297
+ showPopup && /* @__PURE__ */ jsx6(
1298
+ SlashAutocomplete,
1299
+ {
1300
+ commands: filteredCommands,
1301
+ selectedIndex,
1302
+ visible: showPopup,
1303
+ isSubcommandMode
1304
+ }
1305
+ ),
1306
+ /* @__PURE__ */ jsxs5(Text7, { color: borderColor, children: [
1307
+ topBorder.left,
1308
+ topBorder.label ? /* @__PURE__ */ jsx6(Text7, { backgroundColor: borderColor, color: "black", bold: true, children: topBorder.label }) : null,
1309
+ topBorder.right
1310
+ ] }),
1311
+ /* @__PURE__ */ jsx6(Box5, { borderStyle: "single", borderTop: false, borderColor, paddingLeft: 1, children: isAborting ? /* @__PURE__ */ jsx6(Text7, { color: "yellow", children: " Interrupting..." }) : pendingPrompt ? /* @__PURE__ */ jsxs5(Text7, { color: "cyan", children: [
1312
+ " ",
1313
+ "Queued: ",
1314
+ pendingPrompt.length > 50 ? pendingPrompt.slice(0, 47) + "..." : pendingPrompt,
1315
+ " ",
1316
+ /* @__PURE__ */ jsx6(Text7, { dimColor: true, children: "(Backspace to cancel)" })
1317
+ ] }) : isDisabled ? /* @__PURE__ */ jsx6(WaveText, { text: " Waiting for response... (ESC to interrupt)" }) : /* @__PURE__ */ jsxs5(Box5, { children: [
1318
+ /* @__PURE__ */ jsx6(Text7, { color: "green", bold: true, children: "> " }),
1319
+ /* @__PURE__ */ jsx6(
1320
+ CjkTextInput,
1321
+ {
1322
+ value,
1323
+ onChange: setValue,
1324
+ onSubmit: handleSubmit,
1325
+ onPaste: handlePaste,
1326
+ placeholder: "Type a message or /help",
1327
+ availableWidth
1328
+ }
1329
+ )
1330
+ ] }) })
1331
+ ] });
1332
+ }
1333
+
1334
+ // src/ui/ConfirmPrompt.tsx
1335
+ import { useState as useState5, useCallback as useCallback3, useRef as useRef4 } from "react";
1336
+ import { Box as Box6, Text as Text8, useInput as useInput3 } from "ink";
1337
+ import { jsx as jsx7, jsxs as jsxs6 } from "react/jsx-runtime";
1338
+ function ConfirmPrompt({
1339
+ message,
1340
+ options = ["Yes", "No"],
1341
+ onSelect
1342
+ }) {
1343
+ const [selected, setSelected] = useState5(0);
1344
+ const resolvedRef = useRef4(false);
1345
+ const doSelect = useCallback3(
1346
+ (index) => {
1347
+ if (resolvedRef.current) return;
1348
+ resolvedRef.current = true;
1349
+ onSelect(index);
1350
+ },
1351
+ [onSelect]
1352
+ );
1353
+ useInput3((input, key) => {
1354
+ if (resolvedRef.current) return;
1355
+ if (key.leftArrow || key.upArrow) {
1356
+ setSelected((prev) => prev > 0 ? prev - 1 : prev);
1357
+ } else if (key.rightArrow || key.downArrow) {
1358
+ setSelected((prev) => prev < options.length - 1 ? prev + 1 : prev);
1359
+ } else if (key.return) {
1360
+ doSelect(selected);
1361
+ } else if (input === "y" && options.length === 2) {
1362
+ doSelect(0);
1363
+ } else if (input === "n" && options.length === 2) {
1364
+ doSelect(1);
1365
+ }
1366
+ });
1367
+ return /* @__PURE__ */ jsxs6(Box6, { flexDirection: "column", borderStyle: "round", borderColor: "yellow", paddingX: 1, children: [
1368
+ /* @__PURE__ */ jsx7(Text8, { color: "yellow", children: message }),
1369
+ /* @__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: [
1370
+ i === selected ? "> " : " ",
1371
+ opt
1372
+ ] }) }, opt)) }),
1373
+ /* @__PURE__ */ jsx7(Text8, { dimColor: true, children: " arrow keys to select, Enter to confirm" })
1374
+ ] });
1375
+ }
1376
+
1377
+ // src/ui/PermissionPrompt.tsx
1378
+ import React7 from "react";
1379
+ import { Box as Box7, Text as Text9, useInput as useInput4 } from "ink";
1380
+ import { jsx as jsx8, jsxs as jsxs7 } from "react/jsx-runtime";
1381
+ var OPTIONS = ["Allow", "Allow always (this session)", "Deny"];
1382
+ function formatArgs(args) {
1383
+ const entries = Object.entries(args);
1384
+ if (entries.length === 0) return "(no arguments)";
1385
+ return entries.map(([k, v]) => `${k}: ${typeof v === "string" ? v : JSON.stringify(v)}`).join(", ");
1386
+ }
1387
+ function PermissionPrompt({ request }) {
1388
+ const [selected, setSelected] = React7.useState(0);
1389
+ const resolvedRef = React7.useRef(false);
1390
+ const prevRequestRef = React7.useRef(request);
1391
+ if (prevRequestRef.current !== request) {
1392
+ prevRequestRef.current = request;
1393
+ resolvedRef.current = false;
1394
+ setSelected(0);
1395
+ }
1396
+ const doResolve = React7.useCallback(
1397
+ (index) => {
1398
+ if (resolvedRef.current) return;
1399
+ resolvedRef.current = true;
1400
+ if (index === 0) request.resolve(true);
1401
+ else if (index === 1) request.resolve("allow-session");
1402
+ else request.resolve(false);
1403
+ },
1404
+ [request]
1405
+ );
1406
+ useInput4((input, key) => {
1407
+ if (resolvedRef.current) return;
1408
+ if (key.upArrow || key.leftArrow) {
1409
+ setSelected((prev) => prev > 0 ? prev - 1 : prev);
1410
+ } else if (key.downArrow || key.rightArrow) {
1411
+ setSelected((prev) => prev < OPTIONS.length - 1 ? prev + 1 : prev);
1412
+ } else if (key.return) {
1413
+ doResolve(selected);
1414
+ } else if (input === "y" || input === "1") {
1415
+ doResolve(0);
1416
+ } else if (input === "a" || input === "2") {
1417
+ doResolve(1);
1418
+ } else if (input === "n" || input === "d" || input === "3") {
1419
+ doResolve(2);
1420
+ }
1421
+ });
1422
+ return /* @__PURE__ */ jsxs7(Box7, { flexDirection: "column", borderStyle: "round", borderColor: "yellow", paddingX: 1, children: [
1423
+ /* @__PURE__ */ jsx8(Text9, { color: "yellow", bold: true, children: "[Permission Required]" }),
1424
+ /* @__PURE__ */ jsxs7(Text9, { children: [
1425
+ "Tool:",
1426
+ " ",
1427
+ /* @__PURE__ */ jsx8(Text9, { color: "cyan", bold: true, children: request.toolName })
1428
+ ] }),
1429
+ /* @__PURE__ */ jsxs7(Text9, { dimColor: true, children: [
1430
+ " ",
1431
+ formatArgs(request.toolArgs)
1432
+ ] }),
1433
+ /* @__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: [
1434
+ i === selected ? "> " : " ",
1435
+ opt
1436
+ ] }) }, opt)) }),
1437
+ /* @__PURE__ */ jsx8(Text9, { dimColor: true, children: " left/right to select, Enter to confirm" })
1438
+ ] });
1439
+ }
1440
+
1441
+ // src/ui/StreamingIndicator.tsx
1442
+ import { Box as Box8, Text as Text10 } from "ink";
1443
+ import { Fragment as Fragment3, jsx as jsx9, jsxs as jsxs8 } from "react/jsx-runtime";
1444
+ function getToolStyle(t) {
1445
+ if (t.isRunning) return { color: "yellow", icon: "\u27F3", strikethrough: false };
1446
+ if (t.result === "error") return { color: "red", icon: "\u2717", strikethrough: true };
1447
+ if (t.result === "denied") return { color: "yellowBright", icon: "\u2298", strikethrough: true };
1448
+ return { color: "green", icon: "\u2713", strikethrough: false };
1449
+ }
1450
+ function StreamingIndicator({ text, activeTools }) {
1451
+ const hasTools = activeTools.length > 0;
1452
+ const hasText = text.length > 0;
1453
+ if (!hasTools && !hasText) {
1454
+ return /* @__PURE__ */ jsx9(Fragment3, {});
1455
+ }
1456
+ return /* @__PURE__ */ jsxs8(Box8, { flexDirection: "column", children: [
1457
+ hasTools && /* @__PURE__ */ jsxs8(Box8, { flexDirection: "column", marginBottom: 1, children: [
1458
+ /* @__PURE__ */ jsx9(Text10, { color: "white", bold: true, children: "Tools:" }),
1459
+ /* @__PURE__ */ jsx9(Text10, { children: " " }),
1460
+ activeTools.map((t, i) => {
1461
+ const { color, icon, strikethrough } = getToolStyle(t);
1462
+ return /* @__PURE__ */ jsxs8(Box8, { flexDirection: "column", children: [
1463
+ /* @__PURE__ */ jsxs8(Text10, { color, strikethrough, children: [
1464
+ " ",
1465
+ icon,
1466
+ " ",
1467
+ t.toolName,
1468
+ "(",
1469
+ t.firstArg,
1470
+ ")"
1471
+ ] }),
1472
+ t.diffLines && t.diffLines.length > 0 && /* @__PURE__ */ jsx9(DiffBlock, { file: t.diffFile, lines: t.diffLines })
1473
+ ] }, `${t.toolName}-${i}`);
1474
+ })
1475
+ ] }),
1476
+ hasText && /* @__PURE__ */ jsxs8(Box8, { flexDirection: "column", marginBottom: 1, children: [
1477
+ /* @__PURE__ */ jsx9(Text10, { color: "cyan", bold: true, children: "Robota:" }),
1478
+ /* @__PURE__ */ jsx9(Text10, { children: " " }),
1479
+ /* @__PURE__ */ jsx9(Box8, { marginLeft: 2, children: /* @__PURE__ */ jsx9(Text10, { wrap: "wrap", children: renderMarkdown(text) }) })
1480
+ ] })
1481
+ ] });
1482
+ }
1483
+
1484
+ // src/ui/PluginTUI.tsx
1485
+ import { useState as useState8, useEffect as useEffect3, useCallback as useCallback6 } from "react";
1486
+
1487
+ // src/ui/MenuSelect.tsx
1488
+ import { useState as useState6, useCallback as useCallback4, useRef as useRef5 } from "react";
1489
+ import { Box as Box9, Text as Text11, useInput as useInput5 } from "ink";
1490
+ import { jsx as jsx10, jsxs as jsxs9 } from "react/jsx-runtime";
1491
+ function MenuSelect({
1492
+ title,
1493
+ items,
1494
+ onSelect,
1495
+ onBack,
1496
+ loading,
1497
+ error
1498
+ }) {
1499
+ const [selected, setSelected] = useState6(0);
1500
+ const selectedRef = useRef5(0);
1501
+ const resolvedRef = useRef5(false);
1502
+ const doSelect = useCallback4(
1503
+ (index) => {
1504
+ if (resolvedRef.current || items.length === 0) return;
1505
+ resolvedRef.current = true;
1506
+ onSelect(items[index].value);
1507
+ },
1508
+ [items, onSelect]
1509
+ );
1510
+ useInput5((input, key) => {
1511
+ if (resolvedRef.current) return;
1512
+ if (key.escape) {
1513
+ resolvedRef.current = true;
1514
+ onBack();
1515
+ return;
1516
+ }
1517
+ if (loading || error || items.length === 0) return;
1518
+ if (key.upArrow) {
1519
+ const next = selectedRef.current > 0 ? selectedRef.current - 1 : selectedRef.current;
1520
+ selectedRef.current = next;
1521
+ setSelected(next);
1522
+ } else if (key.downArrow) {
1523
+ const next = selectedRef.current < items.length - 1 ? selectedRef.current + 1 : selectedRef.current;
1524
+ selectedRef.current = next;
1525
+ setSelected(next);
1526
+ } else if (key.return) {
1527
+ doSelect(selectedRef.current);
1528
+ }
1529
+ });
1530
+ return /* @__PURE__ */ jsxs9(Box9, { flexDirection: "column", borderStyle: "round", borderColor: "yellow", paddingX: 1, children: [
1531
+ /* @__PURE__ */ jsx10(Text11, { color: "yellow", bold: true, children: title }),
1532
+ loading && /* @__PURE__ */ jsx10(Box9, { marginTop: 1, children: /* @__PURE__ */ jsx10(Text11, { dimColor: true, children: "Loading..." }) }),
1533
+ error && /* @__PURE__ */ jsxs9(Box9, { marginTop: 1, flexDirection: "column", children: [
1534
+ /* @__PURE__ */ jsx10(Text11, { color: "red", children: error }),
1535
+ /* @__PURE__ */ jsx10(Text11, { dimColor: true, children: "Press Esc to go back" })
1536
+ ] }),
1537
+ !loading && !error && /* @__PURE__ */ jsx10(Box9, { flexDirection: "column", marginTop: 1, children: items.map((item, i) => /* @__PURE__ */ jsxs9(Box9, { children: [
1538
+ /* @__PURE__ */ jsxs9(Text11, { color: i === selected ? "cyan" : void 0, bold: i === selected, children: [
1539
+ i === selected ? "> " : " ",
1540
+ item.label
1541
+ ] }),
1542
+ item.hint && /* @__PURE__ */ jsxs9(Text11, { dimColor: true, children: [
1543
+ " ",
1544
+ item.hint
1545
+ ] })
1546
+ ] }, item.value)) }),
1547
+ /* @__PURE__ */ jsx10(Text11, { dimColor: true, children: loading || error ? "" : " \u2191\u2193 Navigate Enter Select Esc Back" })
1548
+ ] });
1549
+ }
1550
+
1551
+ // src/ui/TextPrompt.tsx
1552
+ import { useState as useState7, useRef as useRef6, useCallback as useCallback5 } from "react";
1553
+ import { Box as Box10, Text as Text12, useInput as useInput6 } from "ink";
1554
+ import { jsx as jsx11, jsxs as jsxs10 } from "react/jsx-runtime";
1555
+ function TextPrompt({
1556
+ title,
1557
+ placeholder,
1558
+ onSubmit,
1559
+ onCancel,
1560
+ validate
1561
+ }) {
1562
+ const [value, setValue] = useState7("");
1563
+ const [error, setError] = useState7();
1564
+ const resolvedRef = useRef6(false);
1565
+ const valueRef = useRef6("");
1566
+ const handleSubmit = useCallback5(() => {
1567
+ if (resolvedRef.current) return;
1568
+ const trimmed = valueRef.current.trim();
1569
+ if (!trimmed) return;
1570
+ if (validate) {
1571
+ const err = validate(trimmed);
1572
+ if (err) {
1573
+ setError(err);
1574
+ return;
1575
+ }
1576
+ }
1577
+ resolvedRef.current = true;
1578
+ onSubmit(trimmed);
1579
+ }, [validate, onSubmit]);
1580
+ useInput6((input, key) => {
1581
+ if (resolvedRef.current) return;
1582
+ if (key.escape) {
1583
+ resolvedRef.current = true;
1584
+ onCancel();
1585
+ return;
1586
+ }
1587
+ if (key.return) {
1588
+ handleSubmit();
1589
+ return;
1590
+ }
1591
+ if (key.backspace || key.delete) {
1592
+ valueRef.current = valueRef.current.slice(0, -1);
1593
+ setValue(valueRef.current);
1594
+ setError(void 0);
1595
+ return;
1596
+ }
1597
+ if (input && !key.ctrl && !key.meta) {
1598
+ valueRef.current = valueRef.current + input;
1599
+ setValue(valueRef.current);
1600
+ setError(void 0);
1601
+ }
1602
+ });
1603
+ return /* @__PURE__ */ jsxs10(Box10, { flexDirection: "column", borderStyle: "round", borderColor: "yellow", paddingX: 1, children: [
1604
+ /* @__PURE__ */ jsx11(Text12, { color: "yellow", bold: true, children: title }),
1605
+ /* @__PURE__ */ jsxs10(Box10, { marginTop: 1, children: [
1606
+ /* @__PURE__ */ jsx11(Text12, { color: "cyan", children: "> " }),
1607
+ value ? /* @__PURE__ */ jsx11(Text12, { children: value }) : placeholder ? /* @__PURE__ */ jsx11(Text12, { dimColor: true, children: placeholder }) : null,
1608
+ /* @__PURE__ */ jsx11(Text12, { color: "cyan", children: "\u2588" })
1609
+ ] }),
1610
+ error && /* @__PURE__ */ jsx11(Text12, { color: "red", children: error }),
1611
+ /* @__PURE__ */ jsx11(Text12, { dimColor: true, children: " Enter Submit Esc Cancel" })
1612
+ ] });
1613
+ }
1614
+
1615
+ // src/ui/plugin-tui-handlers.ts
1616
+ function handleMainSelect(value, nav) {
1617
+ if (value === "marketplace") {
1618
+ nav.push({ screen: "marketplace-list" });
1619
+ } else if (value === "installed") {
1620
+ nav.push({ screen: "installed-list" });
1621
+ }
1622
+ }
1623
+ function handleMarketplaceListSelect(value, nav) {
1624
+ if (value === "__add__") {
1625
+ nav.push({ screen: "marketplace-add" });
1626
+ } else {
1627
+ nav.push({ screen: "marketplace-action", context: { marketplace: value } });
1628
+ }
1629
+ }
1630
+ function handleMarketplaceActionSelect(value, marketplace, callbacks, nav) {
1631
+ if (value === "browse") {
1632
+ nav.push({ screen: "marketplace-browse", context: { marketplace } });
1633
+ } else if (value === "update") {
1634
+ callbacks.marketplaceUpdate(marketplace).then(() => {
1635
+ nav.notify(`Updated marketplace "${marketplace}".`);
1636
+ nav.pop();
1637
+ }).catch((err) => {
1638
+ nav.notify(`Error: ${err instanceof Error ? err.message : String(err)}`);
1639
+ });
1640
+ } else if (value === "remove") {
1641
+ nav.setConfirm({
1642
+ message: `Remove marketplace "${marketplace}" and all its plugins?`,
1643
+ onConfirm: () => {
1644
+ nav.setConfirm(void 0);
1645
+ callbacks.marketplaceRemove(marketplace).then(() => {
1646
+ nav.notify(`Removed marketplace "${marketplace}".`);
1647
+ nav.popN(2);
1648
+ }).catch((err) => {
1649
+ nav.notify(`Error: ${err instanceof Error ? err.message : String(err)}`);
1650
+ });
1651
+ },
1652
+ onCancel: () => nav.setConfirm(void 0)
1653
+ });
1654
+ }
1655
+ }
1656
+ function handleMarketplaceBrowseSelect(value, marketplace, items, nav) {
1657
+ const fullId = `${value}@${marketplace}`;
1658
+ const item = items.find((i) => i.value === value);
1659
+ if (item?.hint === "installed") {
1660
+ nav.push({ screen: "installed-action", context: { pluginId: fullId } });
1661
+ } else {
1662
+ nav.push({ screen: "marketplace-install-scope", context: { marketplace, pluginId: fullId } });
1663
+ }
1664
+ }
1665
+ function handleInstallScopeSelect(value, pluginId, callbacks, nav) {
1666
+ const scope = value;
1667
+ callbacks.install(pluginId, scope).then(() => {
1668
+ nav.notify(`Installed plugin "${pluginId}" (${scope} scope).`);
1669
+ nav.popN(2);
1670
+ }).catch((err) => {
1671
+ nav.notify(`Error: ${err instanceof Error ? err.message : String(err)}`);
1672
+ });
1673
+ }
1674
+ function handleInstalledListSelect(value, callbacks, nav) {
1675
+ nav.setConfirm({
1676
+ message: `Uninstall plugin "${value}"?`,
1677
+ onConfirm: () => {
1678
+ nav.setConfirm(void 0);
1679
+ callbacks.uninstall(value).then(() => {
1680
+ nav.notify(`Uninstalled plugin "${value}".`);
1681
+ nav.refresh();
1682
+ }).catch((err) => {
1683
+ nav.notify(`Error: ${err instanceof Error ? err.message : String(err)}`);
1684
+ });
1685
+ },
1686
+ onCancel: () => nav.setConfirm(void 0)
1687
+ });
1688
+ }
1689
+ function handleInstalledActionSelect(value, pluginId, callbacks, nav) {
1690
+ if (value === "uninstall") {
1691
+ nav.setConfirm({
1692
+ message: `Uninstall plugin "${pluginId}"?`,
1693
+ onConfirm: () => {
1694
+ nav.setConfirm(void 0);
1695
+ callbacks.uninstall(pluginId).then(() => {
1696
+ nav.notify(`Uninstalled plugin "${pluginId}".`);
1697
+ nav.popN(2);
1698
+ }).catch((err) => {
1699
+ nav.notify(`Error: ${err instanceof Error ? err.message : String(err)}`);
1700
+ });
1701
+ },
1702
+ onCancel: () => nav.setConfirm(void 0)
1703
+ });
1704
+ }
1705
+ }
1706
+
1707
+ // src/ui/PluginTUI.tsx
1708
+ import { jsx as jsx12 } from "react/jsx-runtime";
1709
+ function PluginTUI({ callbacks, onClose, addMessage }) {
1710
+ const [stack, setStack] = useState8([{ screen: "main" }]);
1711
+ const [items, setItems] = useState8([]);
1712
+ const [loading, setLoading] = useState8(false);
1713
+ const [error, setError] = useState8();
1714
+ const [confirm, setConfirm] = useState8();
1715
+ const [refreshCounter, setRefreshCounter] = useState8(0);
1716
+ const current = stack[stack.length - 1] ?? { screen: "main" };
1717
+ const push = useCallback6((state) => {
1718
+ setStack((prev) => [...prev, state]);
1719
+ setItems([]);
1720
+ setError(void 0);
1721
+ }, []);
1722
+ const pop = useCallback6(() => {
1723
+ setStack((prev) => {
1724
+ if (prev.length <= 1) {
1725
+ onClose();
1726
+ return prev;
1727
+ }
1728
+ return prev.slice(0, -1);
1729
+ });
1730
+ setItems([]);
1731
+ setError(void 0);
1732
+ }, [onClose]);
1733
+ const popN = useCallback6(
1734
+ (n) => {
1735
+ setStack((prev) => {
1736
+ const next = prev.slice(0, Math.max(1, prev.length - n));
1737
+ if (next.length === 0) {
1738
+ onClose();
1739
+ return prev;
1740
+ }
1741
+ return next;
1742
+ });
1743
+ setItems([]);
1744
+ setError(void 0);
1745
+ },
1746
+ [onClose]
1747
+ );
1748
+ const notify = useCallback6(
1749
+ (content) => {
1750
+ addMessage?.({ role: "system", content });
1751
+ },
1752
+ [addMessage]
1753
+ );
1754
+ const refresh = useCallback6(() => {
1755
+ setItems([]);
1756
+ setRefreshCounter((c) => c + 1);
1757
+ }, []);
1758
+ const nav = { push, pop, popN, notify, setConfirm, refresh };
1759
+ useEffect3(() => {
1760
+ const screen2 = current.screen;
1761
+ if (screen2 === "marketplace-list") {
1762
+ setLoading(true);
1763
+ callbacks.marketplaceList().then((sources) => {
1764
+ const baseItems = [{ label: "Add Marketplace", value: "__add__" }];
1765
+ const sourceItems = sources.map((s) => ({
1766
+ label: s.name,
1767
+ value: s.name,
1768
+ hint: s.type
1769
+ }));
1770
+ setItems([...baseItems, ...sourceItems]);
1771
+ setLoading(false);
1772
+ }).catch((err) => {
1773
+ setError(err instanceof Error ? err.message : String(err));
1774
+ setLoading(false);
1775
+ });
1776
+ } else if (screen2 === "marketplace-browse") {
1777
+ const marketplace = current.context?.marketplace ?? "";
1778
+ setLoading(true);
1779
+ callbacks.listAvailablePlugins(marketplace).then((plugins) => {
1780
+ setItems(
1781
+ plugins.map((p) => ({
1782
+ label: p.name,
1783
+ value: p.name,
1784
+ hint: p.installed ? "installed" : p.description
1785
+ }))
1786
+ );
1787
+ setLoading(false);
1788
+ }).catch((err) => {
1789
+ setError(err instanceof Error ? err.message : String(err));
1790
+ setLoading(false);
1791
+ });
1792
+ } else if (screen2 === "installed-list") {
1793
+ setLoading(true);
1794
+ callbacks.listInstalled().then((plugins) => {
1795
+ setItems(
1796
+ plugins.map((p) => ({
1797
+ label: p.name,
1798
+ value: p.name,
1799
+ hint: p.description
1800
+ }))
1801
+ );
1802
+ setLoading(false);
1803
+ }).catch((err) => {
1804
+ setError(err instanceof Error ? err.message : String(err));
1805
+ setLoading(false);
1806
+ });
1807
+ }
1808
+ }, [stack.length, current.screen, current.context?.marketplace, callbacks, refreshCounter]);
1809
+ const handleSelect = useCallback6(
1810
+ (value) => {
1811
+ const screen2 = current.screen;
1812
+ const ctx = current.context;
1813
+ if (screen2 === "main") handleMainSelect(value, nav);
1814
+ else if (screen2 === "marketplace-list") handleMarketplaceListSelect(value, nav);
1815
+ else if (screen2 === "marketplace-action")
1816
+ handleMarketplaceActionSelect(value, ctx?.marketplace ?? "", callbacks, nav);
1817
+ else if (screen2 === "marketplace-browse")
1818
+ handleMarketplaceBrowseSelect(value, ctx?.marketplace ?? "", items, nav);
1819
+ else if (screen2 === "marketplace-install-scope")
1820
+ handleInstallScopeSelect(value, ctx?.pluginId ?? "", callbacks, nav);
1821
+ else if (screen2 === "installed-list") handleInstalledListSelect(value, callbacks, nav);
1822
+ else if (screen2 === "installed-action")
1823
+ handleInstalledActionSelect(value, ctx?.pluginId ?? "", callbacks, nav);
1824
+ },
1825
+ [current, items, callbacks, push, pop, popN, notify, setConfirm, refresh]
1826
+ );
1827
+ const handleTextSubmit = useCallback6(
1828
+ (value) => {
1829
+ if (current.screen === "marketplace-add") {
1830
+ callbacks.marketplaceAdd(value).then((name) => {
1831
+ notify(`Added marketplace "${name}" from ${value}.`);
1832
+ pop();
1833
+ }).catch((err) => {
1834
+ notify(`Error: ${err instanceof Error ? err.message : String(err)}`);
1835
+ pop();
1836
+ });
1837
+ }
1838
+ },
1839
+ [current.screen, callbacks, notify, pop]
1840
+ );
1841
+ if (confirm) {
1842
+ return /* @__PURE__ */ jsx12(
1843
+ ConfirmPrompt,
1844
+ {
1845
+ message: confirm.message,
1846
+ onSelect: (index) => {
1847
+ if (index === 0) confirm.onConfirm();
1848
+ else confirm.onCancel();
1849
+ }
1850
+ }
1851
+ );
1852
+ }
1853
+ const screen = current.screen;
1854
+ if (screen === "marketplace-add") {
1855
+ return /* @__PURE__ */ jsx12(
1856
+ TextPrompt,
1857
+ {
1858
+ title: "Add Marketplace Source",
1859
+ placeholder: "owner/repo or git URL",
1860
+ onSubmit: handleTextSubmit,
1861
+ onCancel: pop,
1862
+ validate: (v) => !v.includes("/") ? "Must be owner/repo or a git URL" : void 0
1863
+ }
1864
+ );
1865
+ }
1866
+ if (screen === "marketplace-action") {
1867
+ return /* @__PURE__ */ jsx12(
1868
+ MenuSelect,
1869
+ {
1870
+ title: `Marketplace: ${current.context?.marketplace ?? ""}`,
1871
+ items: [
1872
+ { label: "Browse plugins", value: "browse" },
1873
+ { label: "Update", value: "update" },
1874
+ { label: "Remove", value: "remove" }
1875
+ ],
1876
+ onSelect: handleSelect,
1877
+ onBack: pop
1878
+ },
1879
+ stack.length
1880
+ );
1881
+ }
1882
+ if (screen === "marketplace-install-scope") {
1883
+ return /* @__PURE__ */ jsx12(
1884
+ MenuSelect,
1885
+ {
1886
+ title: `Install scope for "${current.context?.pluginId ?? ""}"`,
1887
+ items: [
1888
+ { label: "User scope", value: "user" },
1889
+ { label: "Project scope", value: "project" }
1890
+ ],
1891
+ onSelect: handleSelect,
1892
+ onBack: pop
1893
+ },
1894
+ stack.length
1895
+ );
1896
+ }
1897
+ if (screen === "installed-action") {
1898
+ return /* @__PURE__ */ jsx12(
1899
+ MenuSelect,
1900
+ {
1901
+ title: `Plugin: ${current.context?.pluginId ?? ""}`,
1902
+ items: [{ label: "Uninstall", value: "uninstall" }],
1903
+ onSelect: handleSelect,
1904
+ onBack: pop
1905
+ },
1906
+ stack.length
1907
+ );
1908
+ }
1909
+ const titleMap = {
1910
+ main: "Plugin Management",
1911
+ "marketplace-list": "Marketplace",
1912
+ "marketplace-browse": `Browse: ${current.context?.marketplace ?? ""}`,
1913
+ "installed-list": "Installed Plugins"
1914
+ };
1915
+ const staticItemsMap = {
1916
+ main: [
1917
+ { label: "Marketplace", value: "marketplace" },
1918
+ { label: "Installed Plugins", value: "installed" }
1919
+ ]
1920
+ };
1921
+ return /* @__PURE__ */ jsx12(
1922
+ MenuSelect,
1923
+ {
1924
+ title: titleMap[screen] ?? "Plugin Management",
1925
+ items: staticItemsMap[screen] ?? items,
1926
+ onSelect: handleSelect,
1927
+ onBack: pop,
1928
+ loading,
1929
+ error
1930
+ },
1931
+ `${screen}-${stack.length}-${refreshCounter}`
1932
+ );
1933
+ }
1934
+
1935
+ // src/ui/ListPicker.tsx
1936
+ import { useState as useState9, useRef as useRef7 } from "react";
1937
+ import { Box as Box11, Text as Text13, useInput as useInput7 } from "ink";
1938
+ import { jsx as jsx13, jsxs as jsxs11 } from "react/jsx-runtime";
1939
+ var DEFAULT_MAX_VISIBLE = 3;
1940
+ function ListPicker({
1941
+ items,
1942
+ renderItem,
1943
+ onSelect,
1944
+ onCancel,
1945
+ maxVisible = DEFAULT_MAX_VISIBLE
1946
+ }) {
1947
+ const [selectedIndex, setSelectedIndex] = useState9(0);
1948
+ const [scrollOffset, setScrollOffset] = useState9(0);
1949
+ const selectedRef = useRef7(0);
1950
+ const resolvedRef = useRef7(false);
1951
+ useInput7((_input, key) => {
1952
+ if (resolvedRef.current) return;
1953
+ if (key.escape) {
1954
+ resolvedRef.current = true;
1955
+ onCancel();
1956
+ return;
1957
+ }
1958
+ if (items.length === 0) return;
1959
+ if (key.upArrow) {
1960
+ const next = selectedRef.current > 0 ? selectedRef.current - 1 : selectedRef.current;
1961
+ selectedRef.current = next;
1962
+ setSelectedIndex(next);
1963
+ if (next < scrollOffset) {
1964
+ setScrollOffset(next);
1965
+ }
1966
+ } else if (key.downArrow) {
1967
+ const next = selectedRef.current < items.length - 1 ? selectedRef.current + 1 : selectedRef.current;
1968
+ selectedRef.current = next;
1969
+ setSelectedIndex(next);
1970
+ if (next >= scrollOffset + maxVisible) {
1971
+ setScrollOffset(next - maxVisible + 1);
1972
+ }
1973
+ } else if (key.return) {
1974
+ const item = items[selectedRef.current];
1975
+ if (item !== void 0) {
1976
+ resolvedRef.current = true;
1977
+ onSelect(item);
1978
+ }
1979
+ }
1980
+ });
1981
+ if (items.length === 0) {
1982
+ return /* @__PURE__ */ jsx13(Box11, {});
1983
+ }
1984
+ const visibleItems = items.slice(scrollOffset, scrollOffset + maxVisible);
1985
+ const hasMore = scrollOffset + maxVisible < items.length;
1986
+ const hasLess = scrollOffset > 0;
1987
+ return /* @__PURE__ */ jsxs11(Box11, { flexDirection: "column", children: [
1988
+ hasLess && /* @__PURE__ */ jsxs11(Text13, { dimColor: true, children: [
1989
+ " \u2191 ",
1990
+ scrollOffset,
1991
+ " more above"
1992
+ ] }),
1993
+ visibleItems.map((item, index) => /* @__PURE__ */ jsx13(Box11, { marginBottom: 1, children: renderItem(item, scrollOffset + index === selectedIndex) }, scrollOffset + index)),
1994
+ hasMore && /* @__PURE__ */ jsxs11(Text13, { dimColor: true, children: [
1995
+ " \u2193 ",
1996
+ items.length - scrollOffset - maxVisible,
1997
+ " more below"
1998
+ ] })
1999
+ ] });
2000
+ }
2001
+
2002
+ // src/ui/App.tsx
2003
+ import { Fragment as Fragment4, jsx as jsx14, jsxs as jsxs12 } from "react/jsx-runtime";
2004
+ var EXIT_DELAY_MS = 500;
2005
+ var SESSION_ID_DISPLAY_LENGTH = 8;
2006
+ function App(props) {
2007
+ const [activeSessionId, setActiveSessionId] = useState10(props.resumeSessionId);
2008
+ return /* @__PURE__ */ jsx14(
2009
+ AppInner,
2010
+ {
2011
+ ...props,
2012
+ resumeSessionId: activeSessionId,
2013
+ onSessionSwitch: (sessionId) => setActiveSessionId(sessionId)
2014
+ },
2015
+ activeSessionId ?? "__new__"
2016
+ );
2017
+ }
2018
+ function AppInner(props) {
2019
+ const { exit } = useApp();
2020
+ const cwd = props.cwd;
2021
+ const {
2022
+ interactiveSession,
2023
+ registry,
2024
+ history,
2025
+ addEntry,
2026
+ streamingText,
2027
+ activeTools,
2028
+ isThinking,
2029
+ isAborting,
2030
+ pendingPrompt,
2031
+ permissionRequest,
2032
+ contextState,
2033
+ handleSubmit: baseHandleSubmit,
2034
+ handleAbort,
2035
+ handleCancelQueue
2036
+ } = useInteractiveSession({
2037
+ cwd,
2038
+ provider: props.provider,
2039
+ permissionMode: props.permissionMode,
2040
+ maxTurns: props.maxTurns,
2041
+ sessionStore: props.sessionStore,
2042
+ resumeSessionId: props.resumeSessionId,
2043
+ forkSession: props.forkSession,
2044
+ sessionName: props.sessionName
2045
+ });
2046
+ const pluginCallbacks = usePluginCallbacks(cwd);
2047
+ const [pendingModelId, setPendingModelId] = useState10(null);
2048
+ const pendingModelChangeRef = useRef8(null);
2049
+ const [showPluginTUI, setShowPluginTUI] = useState10(false);
2050
+ const [showSessionPicker, setShowSessionPicker] = useState10(
2051
+ props.resumeSessionId === "__picker__"
2052
+ );
2053
+ const [sessionName, setSessionName] = useState10(props.sessionName);
2054
+ useEffect4(() => {
2055
+ const name = interactiveSession?.getName?.();
2056
+ if (name && !sessionName) setSessionName(name);
2057
+ }, [interactiveSession, sessionName]);
2058
+ useEffect4(() => {
2059
+ const title = sessionName ? `Robota \u2014 ${sessionName}` : "Robota";
2060
+ process.stdout.write(`\x1B]0;${title}\x07`);
2061
+ }, [sessionName]);
2062
+ const handleSubmit = async (input) => {
2063
+ await baseHandleSubmit(input);
2064
+ const sideEffects = interactiveSession;
2065
+ if (sideEffects._pendingModelId) {
2066
+ const modelId = sideEffects._pendingModelId;
2067
+ delete sideEffects._pendingModelId;
2068
+ pendingModelChangeRef.current = modelId;
2069
+ setPendingModelId(modelId);
2070
+ return;
2071
+ }
2072
+ if (sideEffects._pendingLanguage) {
2073
+ const lang = sideEffects._pendingLanguage;
2074
+ delete sideEffects._pendingLanguage;
2075
+ const settingsPath = getUserSettingsPath();
2076
+ const settings = readSettings(settingsPath);
2077
+ settings.language = lang;
2078
+ writeSettings(settingsPath, settings);
2079
+ addEntry(
2080
+ messageToHistoryEntry2(createSystemMessage2(`Language set to "${lang}". Restarting...`))
2081
+ );
2082
+ setTimeout(() => exit(), EXIT_DELAY_MS);
2083
+ return;
2084
+ }
2085
+ if (sideEffects._resetRequested) {
2086
+ delete sideEffects._resetRequested;
2087
+ const settingsPath = getUserSettingsPath();
2088
+ if (deleteSettings(settingsPath)) {
2089
+ addEntry(messageToHistoryEntry2(createSystemMessage2(`Deleted ${settingsPath}. Exiting...`)));
2090
+ } else {
2091
+ addEntry(messageToHistoryEntry2(createSystemMessage2("No user settings found.")));
2092
+ }
2093
+ setTimeout(() => exit(), EXIT_DELAY_MS);
2094
+ return;
2095
+ }
2096
+ if (sideEffects._exitRequested) {
2097
+ delete sideEffects._exitRequested;
2098
+ setTimeout(() => exit(), EXIT_DELAY_MS);
2099
+ return;
2100
+ }
2101
+ if (sideEffects._triggerPluginTUI) {
2102
+ delete sideEffects._triggerPluginTUI;
2103
+ setShowPluginTUI(true);
2104
+ return;
2105
+ }
2106
+ if (sideEffects._triggerResumePicker) {
2107
+ delete sideEffects._triggerResumePicker;
2108
+ setShowSessionPicker(true);
2109
+ return;
2110
+ }
2111
+ if (sideEffects._sessionName) {
2112
+ const name = sideEffects._sessionName;
2113
+ delete sideEffects._sessionName;
2114
+ interactiveSession.setName(name);
2115
+ setSessionName(name);
2116
+ return;
2117
+ }
2118
+ };
2119
+ useInput8(
2120
+ (_input, key) => {
2121
+ if (key.escape && isThinking) {
2122
+ handleAbort();
2123
+ }
2124
+ },
2125
+ { isActive: !permissionRequest && !showPluginTUI && !showSessionPicker }
2126
+ );
2127
+ let permissionMode = props.permissionMode ?? "default";
2128
+ let sessionId = "";
2129
+ try {
2130
+ const session = interactiveSession.getSession();
2131
+ permissionMode = session.getPermissionMode();
2132
+ sessionId = session.getSessionId();
2133
+ } catch {
2134
+ }
2135
+ return /* @__PURE__ */ jsxs12(Box12, { flexDirection: "column", children: [
2136
+ /* @__PURE__ */ jsxs12(Box12, { flexDirection: "column", paddingX: 1, marginBottom: 1, children: [
2137
+ /* @__PURE__ */ jsx14(Text14, { color: "cyan", bold: true, children: `
2138
+ ____ ___ ____ ___ _____ _
2139
+ | _ \\ / _ \\| __ ) / _ \\_ _|/ \\
2140
+ | |_) | | | | _ \\| | | || | / _ \\
2141
+ | _ <| |_| | |_) | |_| || |/ ___ \\
2142
+ |_| \\_\\\\___/|____/ \\___/ |_/_/ \\_\\
2143
+ ` }),
2144
+ /* @__PURE__ */ jsxs12(Text14, { dimColor: true, children: [
2145
+ " v",
2146
+ props.version ?? "0.0.0"
2147
+ ] })
2148
+ ] }),
2149
+ /* @__PURE__ */ jsxs12(Box12, { flexDirection: "column", paddingX: 1, flexGrow: 1, children: [
2150
+ /* @__PURE__ */ jsx14(MessageList, { history }),
2151
+ (isThinking || activeTools.length > 0) && /* @__PURE__ */ jsx14(Box12, { flexDirection: "column", marginBottom: 1, children: /* @__PURE__ */ jsx14(StreamingIndicator, { text: streamingText, activeTools }) })
2152
+ ] }),
2153
+ permissionRequest && /* @__PURE__ */ jsx14(PermissionPrompt, { request: permissionRequest }),
2154
+ pendingModelId && /* @__PURE__ */ jsx14(
2155
+ ConfirmPrompt,
2156
+ {
2157
+ message: `Change model to ${getModelName(pendingModelId)}? This will restart the session.`,
2158
+ onSelect: (index) => {
2159
+ setPendingModelId(null);
2160
+ pendingModelChangeRef.current = null;
2161
+ if (index === 0) {
2162
+ try {
2163
+ const settingsPath = getUserSettingsPath();
2164
+ updateModelInSettings(settingsPath, pendingModelId);
2165
+ addEntry(
2166
+ messageToHistoryEntry2(
2167
+ createSystemMessage2(
2168
+ `Model changed to ${getModelName(pendingModelId)}. Restarting...`
2169
+ )
2170
+ )
2171
+ );
2172
+ setTimeout(() => exit(), EXIT_DELAY_MS);
2173
+ } catch (err) {
2174
+ addEntry(
2175
+ messageToHistoryEntry2(
2176
+ createSystemMessage2(
2177
+ `Failed: ${err instanceof Error ? err.message : String(err)}`
2178
+ )
2179
+ )
2180
+ );
2181
+ }
2182
+ } else {
2183
+ addEntry(messageToHistoryEntry2(createSystemMessage2("Model change cancelled.")));
2184
+ }
2185
+ }
2186
+ }
2187
+ ),
2188
+ showPluginTUI && /* @__PURE__ */ jsx14(
2189
+ PluginTUI,
2190
+ {
2191
+ callbacks: pluginCallbacks,
2192
+ onClose: () => setShowPluginTUI(false),
2193
+ addMessage: (msg) => addEntry(messageToHistoryEntry2(createSystemMessage2(msg.content)))
2194
+ }
2195
+ ),
2196
+ showSessionPicker && /* @__PURE__ */ jsxs12(Box12, { flexDirection: "column", paddingX: 1, marginBottom: 1, children: [
2197
+ /* @__PURE__ */ jsx14(Text14, { bold: true, color: "cyan", children: "Select a session to resume (ESC to cancel):" }),
2198
+ /* @__PURE__ */ jsx14(
2199
+ ListPicker,
2200
+ {
2201
+ items: (props.sessionStore?.list() ?? []).filter((s) => s.cwd === props.cwd),
2202
+ renderItem: (session, isSelected) => {
2203
+ const lastMsg = session.messages.slice().reverse().find((m) => {
2204
+ const msg = m;
2205
+ return msg.role === "assistant" && msg.content;
2206
+ });
2207
+ const rawPreview = lastMsg?.content?.replace(/[\n\r]+/g, " ").trim() ?? "";
2208
+ const preview = rawPreview ? rawPreview.slice(0, 60) + (rawPreview.length > 60 ? "..." : "") : "";
2209
+ return /* @__PURE__ */ jsxs12(Text14, { children: [
2210
+ isSelected ? "> " : " ",
2211
+ /* @__PURE__ */ jsx14(Text14, { bold: true, children: session.name ?? session.id.slice(0, SESSION_ID_DISPLAY_LENGTH) }),
2212
+ " ",
2213
+ /* @__PURE__ */ jsx14(Text14, { dimColor: true, children: new Date(session.updatedAt).toLocaleString(void 0, {
2214
+ month: "short",
2215
+ day: "numeric",
2216
+ hour: "2-digit",
2217
+ minute: "2-digit"
2218
+ }) }),
2219
+ " ",
2220
+ /* @__PURE__ */ jsxs12(Text14, { dimColor: true, children: [
2221
+ "msgs: ",
2222
+ session.messages.length
2223
+ ] }),
2224
+ preview ? /* @__PURE__ */ jsxs12(Fragment4, { children: [
2225
+ "\n ",
2226
+ /* @__PURE__ */ jsx14(Text14, { color: "gray", children: preview })
2227
+ ] }) : null
2228
+ ] });
2229
+ },
2230
+ onSelect: (session) => {
2231
+ setShowSessionPicker(false);
2232
+ props.onSessionSwitch(session.id);
2233
+ },
2234
+ onCancel: () => {
2235
+ setShowSessionPicker(false);
2236
+ addEntry(messageToHistoryEntry2(createSystemMessage2("Session resume cancelled.")));
2237
+ }
2238
+ }
2239
+ )
2240
+ ] }),
2241
+ /* @__PURE__ */ jsx14(
2242
+ StatusBar,
2243
+ {
2244
+ permissionMode,
2245
+ modelName: props.modelId ? getModelName(props.modelId) : "",
2246
+ sessionId,
2247
+ messageCount: history.length,
2248
+ isThinking,
2249
+ contextPercentage: contextState.percentage,
2250
+ contextUsedTokens: contextState.usedTokens,
2251
+ contextMaxTokens: contextState.maxTokens,
2252
+ sessionName
2253
+ }
2254
+ ),
2255
+ /* @__PURE__ */ jsx14(
2256
+ InputArea,
2257
+ {
2258
+ onSubmit: handleSubmit,
2259
+ onCancelQueue: handleCancelQueue,
2260
+ isDisabled: !!permissionRequest || showPluginTUI || showSessionPicker || isThinking && !!pendingPrompt,
2261
+ isAborting,
2262
+ pendingPrompt,
2263
+ registry,
2264
+ sessionName
2265
+ }
2266
+ ),
2267
+ /* @__PURE__ */ jsx14(Text14, { children: " " })
2268
+ ] });
2269
+ }
2270
+
2271
+ // src/ui/render.tsx
2272
+ import { jsx as jsx15 } from "react/jsx-runtime";
2273
+ function renderApp(options) {
2274
+ process.on("unhandledRejection", (reason) => {
2275
+ process.stderr.write(`
2276
+ [UNHANDLED REJECTION] ${reason}
2277
+ `);
2278
+ if (reason instanceof Error) {
2279
+ process.stderr.write(`${reason.stack}
2280
+ `);
2281
+ }
2282
+ });
2283
+ if (process.stdin.isTTY && process.stdout.isTTY) {
2284
+ process.stdout.write("\x1B[?2004h");
2285
+ }
2286
+ const instance = render(/* @__PURE__ */ jsx15(App, { ...options }), {
2287
+ exitOnCtrlC: true
2288
+ });
2289
+ instance.waitUntilExit().then(() => {
2290
+ if (process.stdout.isTTY) {
2291
+ process.stdout.write("\x1B[?2004l");
2292
+ }
2293
+ process.exit(0);
2294
+ }).catch((err) => {
2295
+ if (err) {
2296
+ process.stderr.write(`
2297
+ [EXIT ERROR] ${err}
2298
+ `);
2299
+ }
2300
+ process.exit(1);
2301
+ });
2302
+ }
2303
+
2304
+ // src/cli.ts
2305
+ function checkSettingsFile(filePath) {
2306
+ if (!existsSync3(filePath)) return "missing";
2307
+ try {
2308
+ const raw = readFileSync3(filePath, "utf8").trim();
2309
+ if (raw.length === 0) return "incomplete";
2310
+ const parsed = JSON.parse(raw);
2311
+ const provider = parsed.provider;
2312
+ if (!provider?.apiKey) return "incomplete";
2313
+ return "valid";
2314
+ } catch {
2315
+ return "corrupt";
2316
+ }
2317
+ }
2318
+ function readVersion() {
2319
+ try {
2320
+ const thisFile = fileURLToPath(import.meta.url);
2321
+ const dir = dirname2(thisFile);
2322
+ const candidates = [join5(dir, "..", "..", "package.json"), join5(dir, "..", "package.json")];
2323
+ for (const pkgPath of candidates) {
2324
+ try {
2325
+ const raw = readFileSync3(pkgPath, "utf-8");
2326
+ const pkg = JSON.parse(raw);
2327
+ if (pkg.version !== void 0 && pkg.name !== void 0) {
2328
+ return pkg.version;
2329
+ }
2330
+ } catch {
2331
+ }
2332
+ }
2333
+ return "0.0.0";
2334
+ } catch {
2335
+ return "0.0.0";
2336
+ }
2337
+ }
2338
+ function promptInput(label, masked = false) {
2339
+ return new Promise((resolve) => {
2340
+ process.stdout.write(label);
2341
+ let input = "";
2342
+ const stdin = process.stdin;
2343
+ const wasRaw = stdin.isRaw;
2344
+ stdin.setRawMode(true);
2345
+ stdin.resume();
2346
+ stdin.setEncoding("utf8");
2347
+ const onData = (data) => {
2348
+ for (const ch of data) {
2349
+ if (ch === "\r" || ch === "\n") {
2350
+ stdin.removeListener("data", onData);
2351
+ stdin.setRawMode(wasRaw ?? false);
2352
+ stdin.pause();
2353
+ process.stdout.write("\n");
2354
+ resolve(input.trim());
2355
+ return;
2356
+ } else if (ch === "\x7F" || ch === "\b") {
2357
+ if (input.length > 0) {
2358
+ input = input.slice(0, -1);
2359
+ process.stdout.write("\b \b");
2360
+ }
2361
+ } else if (ch === "") {
2362
+ process.stdout.write("\n");
2363
+ process.exit(0);
2364
+ } else if (ch.charCodeAt(0) >= 32) {
2365
+ input += ch;
2366
+ process.stdout.write(masked ? "*" : ch);
2367
+ }
2368
+ }
2369
+ };
2370
+ stdin.on("data", onData);
2371
+ });
2372
+ }
2373
+ async function ensureConfig(cwd) {
2374
+ const userPath = getUserSettingsPath();
2375
+ const projectPath = join5(cwd, ".robota", "settings.json");
2376
+ const localPath = join5(cwd, ".robota", "settings.local.json");
2377
+ const paths = [userPath, projectPath, localPath];
2378
+ const checks = paths.map((p) => ({ path: p, status: checkSettingsFile(p) }));
2379
+ if (checks.some((c) => c.status === "valid")) {
2380
+ return;
2381
+ }
2382
+ const corrupt = checks.filter((c) => c.status === "corrupt");
2383
+ const incomplete = checks.filter((c) => c.status === "incomplete");
2384
+ process.stdout.write("\n");
2385
+ if (corrupt.length > 0) {
2386
+ for (const c of corrupt) {
2387
+ process.stderr.write(` ERROR: Settings file is corrupt (invalid JSON): ${c.path}
2388
+ `);
2389
+ }
2390
+ process.stdout.write("\n");
2391
+ }
2392
+ if (incomplete.length > 0) {
2393
+ for (const c of incomplete) {
2394
+ process.stderr.write(` WARNING: Settings file is missing provider.apiKey: ${c.path}
2395
+ `);
2396
+ }
2397
+ process.stdout.write("\n");
2398
+ }
2399
+ if (corrupt.length === 0 && incomplete.length === 0) {
2400
+ process.stdout.write(" Welcome to Robota CLI!\n");
2401
+ process.stdout.write(" No configuration found. Let's set up.\n");
2402
+ } else {
2403
+ process.stdout.write(" Reconfiguring...\n");
2404
+ }
2405
+ process.stdout.write("\n");
2406
+ const apiKey = await promptInput(" Anthropic API key: ", true);
2407
+ if (!apiKey) {
2408
+ process.stderr.write("\n No API key provided. Exiting.\n");
2409
+ process.exit(1);
2410
+ }
2411
+ const language = await promptInput(" Response language (ko/en/ja/zh, default: en): ");
2412
+ const settingsDir = dirname2(userPath);
2413
+ mkdirSync2(settingsDir, { recursive: true });
2414
+ const settings = {
2415
+ provider: {
2416
+ name: "anthropic",
2417
+ model: "claude-sonnet-4-6",
2418
+ apiKey
2419
+ }
2420
+ };
2421
+ if (language) {
2422
+ settings.language = language;
2423
+ }
2424
+ writeFileSync2(userPath, JSON.stringify(settings, null, 2) + "\n", "utf8");
2425
+ process.stdout.write(`
2426
+ Config saved to ${userPath}
2427
+
2428
+ `);
2429
+ }
2430
+ function resetConfig() {
2431
+ const userPath = getUserSettingsPath();
2432
+ if (deleteSettings(userPath)) {
2433
+ process.stdout.write(`Deleted ${userPath}
2434
+ `);
2435
+ } else {
2436
+ process.stdout.write("No user settings found.\n");
2437
+ }
2438
+ }
2439
+ async function startCli() {
2440
+ const args = parseCliArgs();
2441
+ if (args.version) {
2442
+ process.stdout.write(`robota ${readVersion()}
2443
+ `);
2444
+ return;
2445
+ }
2446
+ if (args.reset) {
2447
+ resetConfig();
2448
+ return;
2449
+ }
2450
+ const cwd = process.cwd();
2451
+ await ensureConfig(cwd);
2452
+ const providerSettings = readProviderSettings(cwd);
2453
+ const modelId = args.model ?? providerSettings.model;
2454
+ const provider = createProviderFromSettings(cwd, args.model);
2455
+ const sessionStore = new SessionStore();
2456
+ let resumeSessionId;
2457
+ if (args.continueMode) {
2458
+ const sessions = sessionStore.list().filter((s) => s.cwd === cwd);
2459
+ if (sessions.length > 0) {
2460
+ resumeSessionId = sessions[0].id;
2461
+ }
2462
+ } else if (args.resumeId !== void 0) {
2463
+ if (args.resumeId === "") {
2464
+ resumeSessionId = "__picker__";
2465
+ } else {
2466
+ const sessions = sessionStore.list();
2467
+ const match = sessions.find((s) => s.id === args.resumeId || s.name === args.resumeId);
2468
+ if (match) {
2469
+ resumeSessionId = match.id;
2470
+ } else {
2471
+ process.stderr.write(`Session not found: ${args.resumeId}
2472
+ `);
2473
+ process.exit(1);
2474
+ }
2475
+ }
2476
+ }
2477
+ if (args.printMode) {
2478
+ let prompt = args.positional.join(" ").trim();
2479
+ if (!prompt && !process.stdin.isTTY) {
2480
+ const chunks = [];
2481
+ for await (const chunk of process.stdin) {
2482
+ chunks.push(chunk);
2483
+ }
2484
+ prompt = Buffer.concat(chunks).toString("utf-8").trim();
2485
+ }
2486
+ if (!prompt) {
2487
+ process.stderr.write("Print mode (-p) requires a prompt argument.\n");
2488
+ process.exit(1);
2489
+ }
2490
+ const session = new InteractiveSession2({
2491
+ cwd,
2492
+ provider,
2493
+ permissionMode: args.permissionMode ?? "bypassPermissions",
2494
+ maxTurns: args.maxTurns,
2495
+ sessionStore,
2496
+ sessionName: args.sessionName
2497
+ });
2498
+ const transport = createHeadlessTransport({
2499
+ outputFormat: args.outputFormat ?? "text",
2500
+ prompt
2501
+ });
2502
+ session.attachTransport(transport);
2503
+ await transport.start();
2504
+ process.exit(transport.getExitCode());
2505
+ }
2506
+ renderApp({
2507
+ cwd,
2508
+ provider,
2509
+ modelId,
2510
+ language: args.language,
2511
+ permissionMode: args.permissionMode,
2512
+ maxTurns: args.maxTurns,
2513
+ version: readVersion(),
2514
+ sessionStore,
2515
+ resumeSessionId,
2516
+ forkSession: args.forkSession,
2517
+ sessionName: args.sessionName
2518
+ });
2519
+ }
2520
+
2521
+ export {
2522
+ startCli
2523
+ };