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

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