shortcutxl 0.2.11 → 0.2.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/README.md +26 -26
  2. package/agent-docs/README.md +397 -397
  3. package/agent-docs/docs/compaction.md +390 -390
  4. package/agent-docs/docs/custom-provider.md +580 -580
  5. package/agent-docs/docs/extensions.md +1971 -1971
  6. package/agent-docs/docs/packages.md +209 -209
  7. package/agent-docs/docs/rpc.md +1317 -1317
  8. package/agent-docs/docs/sdk.md +962 -962
  9. package/agent-docs/docs/session.md +412 -412
  10. package/agent-docs/docs/termux.md +127 -127
  11. package/agent-docs/docs/tui.md +887 -887
  12. package/agent-docs/examples/README.md +25 -25
  13. package/agent-docs/examples/extensions/README.md +205 -205
  14. package/agent-docs/examples/extensions/antigravity-image-gen.ts +447 -447
  15. package/agent-docs/examples/extensions/auto-commit-on-exit.ts +49 -49
  16. package/agent-docs/examples/extensions/bash-spawn-hook.ts +30 -30
  17. package/agent-docs/examples/extensions/bookmark.ts +50 -50
  18. package/agent-docs/examples/extensions/built-in-tool-renderer.ts +256 -256
  19. package/agent-docs/examples/extensions/claude-rules.ts +86 -86
  20. package/agent-docs/examples/extensions/commands.ts +75 -75
  21. package/agent-docs/examples/extensions/confirm-destructive.ts +59 -59
  22. package/agent-docs/examples/extensions/custom-compaction.ts +126 -126
  23. package/agent-docs/examples/extensions/custom-footer.ts +63 -63
  24. package/agent-docs/examples/extensions/custom-header.ts +73 -73
  25. package/agent-docs/examples/extensions/custom-provider-anthropic/index.ts +660 -660
  26. package/agent-docs/examples/extensions/custom-provider-gitlab-duo/index.ts +362 -362
  27. package/agent-docs/examples/extensions/custom-provider-gitlab-duo/test.ts +88 -88
  28. package/agent-docs/examples/extensions/custom-provider-qwen-cli/index.ts +349 -349
  29. package/agent-docs/examples/extensions/dirty-repo-guard.ts +56 -56
  30. package/agent-docs/examples/extensions/doom-overlay/doom-component.ts +133 -133
  31. package/agent-docs/examples/extensions/doom-overlay/doom-keys.ts +108 -108
  32. package/agent-docs/examples/extensions/doom-overlay/index.ts +74 -74
  33. package/agent-docs/examples/extensions/dynamic-resources/index.ts +15 -15
  34. package/agent-docs/examples/extensions/dynamic-tools.ts +77 -77
  35. package/agent-docs/examples/extensions/event-bus.ts +43 -43
  36. package/agent-docs/examples/extensions/file-trigger.ts +41 -41
  37. package/agent-docs/examples/extensions/git-checkpoint.ts +53 -53
  38. package/agent-docs/examples/extensions/handoff.ts +155 -155
  39. package/agent-docs/examples/extensions/hello.ts +25 -25
  40. package/agent-docs/examples/extensions/inline-bash.ts +94 -94
  41. package/agent-docs/examples/extensions/input-transform.ts +43 -43
  42. package/agent-docs/examples/extensions/interactive-shell.ts +209 -209
  43. package/agent-docs/examples/extensions/mac-system-theme.ts +47 -47
  44. package/agent-docs/examples/extensions/message-renderer.ts +59 -59
  45. package/agent-docs/examples/extensions/minimal-mode.ts +430 -430
  46. package/agent-docs/examples/extensions/modal-editor.ts +90 -90
  47. package/agent-docs/examples/extensions/model-status.ts +31 -31
  48. package/agent-docs/examples/extensions/notify.ts +55 -55
  49. package/agent-docs/examples/extensions/overlay-qa-tests.ts +936 -936
  50. package/agent-docs/examples/extensions/overlay-test.ts +159 -159
  51. package/agent-docs/examples/extensions/permission-gate.ts +37 -37
  52. package/agent-docs/examples/extensions/pirate.ts +47 -47
  53. package/agent-docs/examples/extensions/plan-mode/index.ts +363 -363
  54. package/agent-docs/examples/extensions/preset.ts +418 -418
  55. package/agent-docs/examples/extensions/protected-paths.ts +30 -30
  56. package/agent-docs/examples/extensions/qna.ts +122 -122
  57. package/agent-docs/examples/extensions/question.ts +278 -278
  58. package/agent-docs/examples/extensions/questionnaire.ts +440 -440
  59. package/agent-docs/examples/extensions/rainbow-editor.ts +90 -90
  60. package/agent-docs/examples/extensions/reload-runtime.ts +37 -37
  61. package/agent-docs/examples/extensions/rpc-demo.ts +124 -124
  62. package/agent-docs/examples/extensions/sandbox/index.ts +324 -324
  63. package/agent-docs/examples/extensions/send-user-message.ts +97 -97
  64. package/agent-docs/examples/extensions/session-name.ts +27 -27
  65. package/agent-docs/examples/extensions/shutdown-command.ts +69 -69
  66. package/agent-docs/examples/extensions/snake.ts +343 -343
  67. package/agent-docs/examples/extensions/space-invaders.ts +566 -566
  68. package/agent-docs/examples/extensions/ssh.ts +233 -233
  69. package/agent-docs/examples/extensions/status-line.ts +40 -40
  70. package/agent-docs/examples/extensions/subagent/agents.ts +130 -130
  71. package/agent-docs/examples/extensions/subagent/index.ts +1068 -1068
  72. package/agent-docs/examples/extensions/summarize.ts +206 -206
  73. package/agent-docs/examples/extensions/system-prompt-header.ts +17 -17
  74. package/agent-docs/examples/extensions/timed-confirm.ts +72 -72
  75. package/agent-docs/examples/extensions/titlebar-spinner.ts +58 -58
  76. package/agent-docs/examples/extensions/todo.ts +314 -314
  77. package/agent-docs/examples/extensions/tool-override.ts +146 -146
  78. package/agent-docs/examples/extensions/tools.ts +145 -145
  79. package/agent-docs/examples/extensions/trigger-compact.ts +40 -40
  80. package/agent-docs/examples/extensions/truncated-tool.ts +194 -194
  81. package/agent-docs/examples/extensions/widget-placement.ts +17 -17
  82. package/agent-docs/examples/extensions/with-deps/index.ts +37 -37
  83. package/agent-docs/examples/rpc-extension-ui.ts +654 -654
  84. package/agent-docs/examples/sdk/01-minimal.ts +22 -22
  85. package/agent-docs/examples/sdk/02-custom-model.ts +48 -48
  86. package/agent-docs/examples/sdk/03-custom-prompt.ts +55 -55
  87. package/agent-docs/examples/sdk/04-skills.ts +53 -53
  88. package/agent-docs/examples/sdk/05-tools.ts +56 -56
  89. package/agent-docs/examples/sdk/06-extensions.ts +88 -88
  90. package/agent-docs/examples/sdk/07-context-files.ts +40 -40
  91. package/agent-docs/examples/sdk/08-prompt-templates.ts +47 -47
  92. package/agent-docs/examples/sdk/09-api-keys-and-oauth.ts +48 -48
  93. package/agent-docs/examples/sdk/10-settings.ts +54 -54
  94. package/agent-docs/examples/sdk/11-sessions.ts +48 -48
  95. package/agent-docs/examples/sdk/12-full-control.ts +82 -82
  96. package/agent-docs/examples/sdk/README.md +144 -144
  97. package/agent-docs/xll-spec.md +110 -110
  98. package/dist/core/auth-storage.js +21 -2
  99. package/dist/main.js +2 -1
  100. package/package.json +1 -1
  101. package/xll/ShortcutXL.xll +0 -0
  102. package/xll/modules/debug_render.py +272 -272
  103. package/xll/modules/gameboy.py +241 -241
  104. package/xll/modules/pong.py +188 -188
  105. package/xll/modules/shortcut_xl/_diff_highlight.py +176 -0
  106. package/xll/modules/shortcut_xl/_log.py +12 -12
  107. package/xll/modules/shortcut_xl/_registry.py +44 -44
  108. package/xll/modules/stocks.py +100 -100
  109. /package/skills/{com-advanced-api → COM-advanced-api}/SKILL.md +0 -0
  110. /package/skills/{com-advanced-api → COM-advanced-api}/excel-type-library.py +0 -0
  111. /package/skills/{com-advanced-api → COM-advanced-api}/office-type-library.py +0 -0
@@ -1,654 +1,654 @@
1
- /**
2
- * RPC Extension UI Example (TUI)
3
- *
4
- * A lightweight TUI chat client that spawns the agent in RPC mode.
5
- * Demonstrates how to build a custom UI on top of the RPC protocol,
6
- * including handling extension UI requests (select, confirm, input, editor).
7
- *
8
- * Usage: npx tsx examples/rpc-extension-ui.ts
9
- *
10
- * Slash commands:
11
- * /select - demo select dialog
12
- * /confirm - demo confirm dialog
13
- * /input - demo input dialog
14
- * /editor - demo editor dialog
15
- */
16
-
17
- import { spawn } from 'node:child_process';
18
- import { dirname, join } from 'node:path';
19
- import * as readline from 'node:readline';
20
- import { fileURLToPath } from 'node:url';
21
- import {
22
- type Component,
23
- Container,
24
- Input,
25
- matchesKey,
26
- ProcessTerminal,
27
- SelectList,
28
- TUI
29
- } from 'shortcutxl';
30
-
31
- const __dirname = dirname(fileURLToPath(import.meta.url));
32
-
33
- // ============================================================================
34
- // ANSI helpers
35
- // ============================================================================
36
-
37
- const GREEN = '\x1b[32m';
38
- const YELLOW = '\x1b[33m';
39
- const BLUE = '\x1b[34m';
40
- const MAGENTA = '\x1b[35m';
41
- const RED = '\x1b[31m';
42
- const DIM = '\x1b[2m';
43
- const BOLD = '\x1b[1m';
44
- const RESET = '\x1b[0m';
45
-
46
- // ============================================================================
47
- // Extension UI request type (subset of rpc-types.ts)
48
- // ============================================================================
49
-
50
- interface ExtensionUIRequest {
51
- type: 'extension_ui_request';
52
- id: string;
53
- method: string;
54
- title?: string;
55
- options?: string[];
56
- message?: string;
57
- placeholder?: string;
58
- prefill?: string;
59
- notifyType?: 'info' | 'warning' | 'error';
60
- statusKey?: string;
61
- statusText?: string;
62
- widgetKey?: string;
63
- widgetLines?: string[];
64
- text?: string;
65
- }
66
-
67
- // ============================================================================
68
- // Output log: accumulates styled lines, renders the tail that fits
69
- // ============================================================================
70
-
71
- class OutputLog implements Component {
72
- private lines: string[] = [];
73
- private maxLines = 1000;
74
- private visibleLines = 0;
75
-
76
- setVisibleLines(n: number): void {
77
- this.visibleLines = n;
78
- }
79
-
80
- append(line: string): void {
81
- this.lines.push(line);
82
- if (this.lines.length > this.maxLines) {
83
- this.lines = this.lines.slice(-this.maxLines);
84
- }
85
- }
86
-
87
- appendRaw(text: string): void {
88
- if (this.lines.length === 0) {
89
- this.lines.push(text);
90
- } else {
91
- this.lines[this.lines.length - 1] += text;
92
- }
93
- }
94
-
95
- invalidate(): void {}
96
-
97
- render(width: number): string[] {
98
- if (this.lines.length === 0) return [''];
99
- const n = this.visibleLines > 0 ? this.visibleLines : this.lines.length;
100
- return this.lines.slice(-n).map((l) => l.slice(0, width));
101
- }
102
- }
103
-
104
- // ============================================================================
105
- // Loading indicator: "Agent: Working." -> ".." -> "..." -> "."
106
- // ============================================================================
107
-
108
- class LoadingIndicator implements Component {
109
- private dots = 1;
110
- private intervalId: NodeJS.Timeout | null = null;
111
- private tui: TUI | null = null;
112
-
113
- start(tui: TUI): void {
114
- this.tui = tui;
115
- this.dots = 1;
116
- this.intervalId = setInterval(() => {
117
- this.dots = (this.dots % 3) + 1;
118
- this.tui?.requestRender();
119
- }, 400);
120
- }
121
-
122
- stop(): void {
123
- if (this.intervalId) {
124
- clearInterval(this.intervalId);
125
- this.intervalId = null;
126
- }
127
- }
128
-
129
- invalidate(): void {}
130
-
131
- render(_width: number): string[] {
132
- return [`${BLUE}${BOLD}Agent:${RESET} ${DIM}Working${'.'.repeat(this.dots)}${RESET}`];
133
- }
134
- }
135
-
136
- // ============================================================================
137
- // Prompt input: label + single-line input
138
- // ============================================================================
139
-
140
- class PromptInput implements Component {
141
- readonly input: Input;
142
- onCtrlD?: () => void;
143
-
144
- constructor() {
145
- this.input = new Input();
146
- }
147
-
148
- handleInput(data: string): void {
149
- if (matchesKey(data, 'ctrl+d')) {
150
- this.onCtrlD?.();
151
- return;
152
- }
153
- this.input.handleInput(data);
154
- }
155
-
156
- invalidate(): void {
157
- this.input.invalidate();
158
- }
159
-
160
- render(width: number): string[] {
161
- return [`${GREEN}${BOLD}You:${RESET}`, ...this.input.render(width)];
162
- }
163
- }
164
-
165
- // ============================================================================
166
- // Dialog components: replace the prompt input during interactive requests
167
- // ============================================================================
168
-
169
- class SelectDialog implements Component {
170
- private list: SelectList;
171
- private title: string;
172
- onSelect?: (value: string) => void;
173
- onCancel?: () => void;
174
-
175
- constructor(title: string, options: string[]) {
176
- this.title = title;
177
- const items = options.map((o) => ({ value: o, label: o }));
178
- this.list = new SelectList(items, Math.min(items.length, 8), {
179
- selectedPrefix: (t) => `${MAGENTA}${t}${RESET}`,
180
- selectedText: (t) => `${MAGENTA}${t}${RESET}`,
181
- description: (t) => `${DIM}${t}${RESET}`,
182
- scrollInfo: (t) => `${DIM}${t}${RESET}`,
183
- noMatch: (t) => `${YELLOW}${t}${RESET}`
184
- });
185
- this.list.onSelect = (item) => this.onSelect?.(item.value);
186
- this.list.onCancel = () => this.onCancel?.();
187
- }
188
-
189
- handleInput(data: string): void {
190
- this.list.handleInput(data);
191
- }
192
-
193
- invalidate(): void {
194
- this.list.invalidate();
195
- }
196
-
197
- render(width: number): string[] {
198
- return [
199
- `${MAGENTA}${BOLD}${this.title}${RESET}`,
200
- ...this.list.render(width),
201
- `${DIM}Up/Down, Enter to select, Esc to cancel${RESET}`
202
- ];
203
- }
204
- }
205
-
206
- class InputDialog implements Component {
207
- private dialogInput: Input;
208
- private title: string;
209
- onCtrlD?: () => void;
210
-
211
- constructor(title: string, prefill?: string) {
212
- this.title = title;
213
- this.dialogInput = new Input();
214
- if (prefill) this.dialogInput.setValue(prefill);
215
- }
216
-
217
- set onSubmit(fn: ((value: string) => void) | undefined) {
218
- this.dialogInput.onSubmit = fn;
219
- }
220
-
221
- set onEscape(fn: (() => void) | undefined) {
222
- this.dialogInput.onEscape = fn;
223
- }
224
-
225
- get inputComponent(): Input {
226
- return this.dialogInput;
227
- }
228
-
229
- handleInput(data: string): void {
230
- if (matchesKey(data, 'ctrl+d')) {
231
- this.onCtrlD?.();
232
- return;
233
- }
234
- this.dialogInput.handleInput(data);
235
- }
236
-
237
- invalidate(): void {
238
- this.dialogInput.invalidate();
239
- }
240
-
241
- render(width: number): string[] {
242
- return [
243
- `${MAGENTA}${BOLD}${this.title}${RESET}`,
244
- ...this.dialogInput.render(width),
245
- `${DIM}Enter to submit, Esc to cancel${RESET}`
246
- ];
247
- }
248
- }
249
-
250
- // ============================================================================
251
- // Main
252
- // ============================================================================
253
-
254
- async function main() {
255
- const extensionPath = join(__dirname, 'extensions/rpc-demo.ts');
256
- const cliPath = join(__dirname, '../dist/cli.js');
257
-
258
- const agent = spawn(
259
- 'node',
260
- [cliPath, '--mode', 'rpc', '--no-session', '--no-extension', '--extension', extensionPath],
261
- { stdio: ['pipe', 'pipe', 'pipe'] }
262
- );
263
-
264
- let stderr = '';
265
- agent.stderr?.on('data', (data: Buffer) => {
266
- stderr += data.toString();
267
- });
268
-
269
- await new Promise((resolve) => setTimeout(resolve, 500));
270
- if (agent.exitCode !== null) {
271
- console.error(`Agent exited immediately. Stderr:\n${stderr}`);
272
- process.exit(1);
273
- }
274
-
275
- // -- TUI setup --
276
-
277
- const terminal = new ProcessTerminal();
278
- const tui = new TUI(terminal);
279
-
280
- const outputLog = new OutputLog();
281
- const loadingIndicator = new LoadingIndicator();
282
- const promptInput = new PromptInput();
283
-
284
- const root = new Container();
285
- root.addChild(outputLog);
286
- root.addChild(promptInput);
287
-
288
- tui.addChild(root);
289
- tui.setFocus(promptInput.input);
290
-
291
- // -- Agent communication --
292
-
293
- function send(obj: Record<string, unknown>): void {
294
- agent.stdin!.write(`${JSON.stringify(obj)}\n`);
295
- }
296
-
297
- let isStreaming = false;
298
- let hasTextOutput = false;
299
-
300
- function exit(): void {
301
- tui.stop();
302
- agent.kill('SIGTERM');
303
- process.exit(0);
304
- }
305
-
306
- // -- Bottom area management --
307
- // The bottom of the screen is either the prompt input or a dialog.
308
- // These helpers swap between them.
309
-
310
- let activeDialog: Component | null = null;
311
-
312
- function setBottomComponent(component: Component): void {
313
- root.clear();
314
- root.addChild(outputLog);
315
- if (isStreaming) root.addChild(loadingIndicator);
316
- root.addChild(component);
317
- tui.setFocus(component);
318
- tui.requestRender();
319
- }
320
-
321
- function showPrompt(): void {
322
- activeDialog = null;
323
- setBottomComponent(promptInput);
324
- tui.setFocus(promptInput.input);
325
- }
326
-
327
- function showDialog(dialog: Component): void {
328
- activeDialog = dialog;
329
- setBottomComponent(dialog);
330
- }
331
-
332
- function showLoading(): void {
333
- if (!isStreaming) {
334
- isStreaming = true;
335
- hasTextOutput = false;
336
- root.clear();
337
- root.addChild(outputLog);
338
- root.addChild(loadingIndicator);
339
- root.addChild(activeDialog ?? promptInput);
340
- if (!activeDialog) tui.setFocus(promptInput.input);
341
- loadingIndicator.start(tui);
342
- tui.requestRender();
343
- }
344
- }
345
-
346
- function hideLoading(): void {
347
- loadingIndicator.stop();
348
- root.clear();
349
- root.addChild(outputLog);
350
- root.addChild(activeDialog ?? promptInput);
351
- if (!activeDialog) tui.setFocus(promptInput.input);
352
- tui.requestRender();
353
- }
354
-
355
- // -- Extension UI dialog handling --
356
-
357
- function showSelectDialog(
358
- title: string,
359
- options: string[],
360
- onDone: (value: string | undefined) => void
361
- ): void {
362
- const dialog = new SelectDialog(title, options);
363
- dialog.onSelect = (value) => {
364
- showPrompt();
365
- onDone(value);
366
- };
367
- dialog.onCancel = () => {
368
- showPrompt();
369
- onDone(undefined);
370
- };
371
- showDialog(dialog);
372
- }
373
-
374
- function showInputDialog(
375
- title: string,
376
- prefill?: string,
377
- onDone?: (value: string | undefined) => void
378
- ): void {
379
- const dialog = new InputDialog(title, prefill);
380
- dialog.onSubmit = (value) => {
381
- showPrompt();
382
- onDone?.(value.trim() || undefined);
383
- };
384
- dialog.onEscape = () => {
385
- showPrompt();
386
- onDone?.(undefined);
387
- };
388
- dialog.onCtrlD = exit;
389
- showDialog(dialog);
390
- tui.setFocus(dialog.inputComponent);
391
- }
392
-
393
- function handleExtensionUI(req: ExtensionUIRequest): void {
394
- const { id, method } = req;
395
-
396
- switch (method) {
397
- // Dialog methods: replace prompt with interactive component
398
- case 'select': {
399
- showSelectDialog(req.title ?? 'Select', req.options ?? [], (value) => {
400
- if (value !== undefined) {
401
- send({ type: 'extension_ui_response', id, value });
402
- } else {
403
- send({ type: 'extension_ui_response', id, cancelled: true });
404
- }
405
- });
406
- break;
407
- }
408
-
409
- case 'confirm': {
410
- const title = req.message ? `${req.title}: ${req.message}` : (req.title ?? 'Confirm');
411
- showSelectDialog(title, ['Yes', 'No'], (value) => {
412
- send({ type: 'extension_ui_response', id, confirmed: value === 'Yes' });
413
- });
414
- break;
415
- }
416
-
417
- case 'input': {
418
- const title = req.placeholder
419
- ? `${req.title} (${req.placeholder})`
420
- : (req.title ?? 'Input');
421
- showInputDialog(title, undefined, (value) => {
422
- if (value !== undefined) {
423
- send({ type: 'extension_ui_response', id, value });
424
- } else {
425
- send({ type: 'extension_ui_response', id, cancelled: true });
426
- }
427
- });
428
- break;
429
- }
430
-
431
- case 'editor': {
432
- const prefill = req.prefill?.replace(/\n/g, ' ');
433
- showInputDialog(req.title ?? 'Editor', prefill, (value) => {
434
- if (value !== undefined) {
435
- send({ type: 'extension_ui_response', id, value });
436
- } else {
437
- send({ type: 'extension_ui_response', id, cancelled: true });
438
- }
439
- });
440
- break;
441
- }
442
-
443
- // Fire-and-forget methods: display as notification
444
- case 'notify': {
445
- const notifyType = (req.notifyType as string) ?? 'info';
446
- const color = notifyType === 'error' ? RED : notifyType === 'warning' ? YELLOW : MAGENTA;
447
- outputLog.append(`${color}${BOLD}Notification:${RESET} ${req.message}`);
448
- tui.requestRender();
449
- break;
450
- }
451
-
452
- case 'setStatus':
453
- outputLog.append(
454
- `${MAGENTA}${BOLD}Notification:${RESET} ${DIM}[status: ${req.statusKey}]${RESET} ${req.statusText ?? '(cleared)'}`
455
- );
456
- tui.requestRender();
457
- break;
458
-
459
- case 'setWidget': {
460
- const lines = req.widgetLines;
461
- if (lines && lines.length > 0) {
462
- outputLog.append(
463
- `${MAGENTA}${BOLD}Notification:${RESET} ${DIM}[widget: ${req.widgetKey}]${RESET}`
464
- );
465
- for (const wl of lines) {
466
- outputLog.append(` ${DIM}${wl}${RESET}`);
467
- }
468
- tui.requestRender();
469
- }
470
- break;
471
- }
472
-
473
- case 'set_editor_text':
474
- promptInput.input.setValue((req.text as string) ?? '');
475
- tui.requestRender();
476
- break;
477
- }
478
- }
479
-
480
- // -- Slash commands (local, not sent to agent) --
481
-
482
- function handleSlashCommand(cmd: string): boolean {
483
- switch (cmd) {
484
- case '/select':
485
- showSelectDialog('Pick a color', ['Red', 'Green', 'Blue', 'Yellow'], (value) => {
486
- if (value) {
487
- outputLog.append(`${MAGENTA}${BOLD}Notification:${RESET} You picked: ${value}`);
488
- } else {
489
- outputLog.append(`${MAGENTA}${BOLD}Notification:${RESET} Selection cancelled`);
490
- }
491
- tui.requestRender();
492
- });
493
- return true;
494
-
495
- case '/confirm':
496
- showSelectDialog('Are you sure?', ['Yes', 'No'], (value) => {
497
- const confirmed = value === 'Yes';
498
- outputLog.append(`${MAGENTA}${BOLD}Notification:${RESET} Confirmed: ${confirmed}`);
499
- tui.requestRender();
500
- });
501
- return true;
502
-
503
- case '/input':
504
- showInputDialog('Enter your name', undefined, (value) => {
505
- if (value) {
506
- outputLog.append(`${MAGENTA}${BOLD}Notification:${RESET} You entered: ${value}`);
507
- } else {
508
- outputLog.append(`${MAGENTA}${BOLD}Notification:${RESET} Input cancelled`);
509
- }
510
- tui.requestRender();
511
- });
512
- return true;
513
-
514
- case '/editor':
515
- showInputDialog('Edit text', 'Hello, world!', (value) => {
516
- if (value) {
517
- outputLog.append(`${MAGENTA}${BOLD}Notification:${RESET} Submitted: ${value}`);
518
- } else {
519
- outputLog.append(`${MAGENTA}${BOLD}Notification:${RESET} Editor cancelled`);
520
- }
521
- tui.requestRender();
522
- });
523
- return true;
524
-
525
- default:
526
- return false;
527
- }
528
- }
529
-
530
- // -- Process agent stdout --
531
-
532
- const stdoutRl = readline.createInterface({ input: agent.stdout!, terminal: false });
533
-
534
- stdoutRl.on('line', (line) => {
535
- let data: Record<string, unknown>;
536
- try {
537
- data = JSON.parse(line);
538
- } catch {
539
- return;
540
- }
541
-
542
- if (data.type === 'response' && !data.success) {
543
- outputLog.append(`${RED}[error]${RESET} ${data.command}: ${data.error}`);
544
- tui.requestRender();
545
- return;
546
- }
547
-
548
- if (data.type === 'agent_start') {
549
- showLoading();
550
- return;
551
- }
552
-
553
- if (data.type === 'extension_ui_request') {
554
- handleExtensionUI(data as unknown as ExtensionUIRequest);
555
- return;
556
- }
557
-
558
- if (data.type === 'message_update') {
559
- const evt = data.assistantMessageEvent as Record<string, unknown> | undefined;
560
- if (evt?.type === 'text_delta') {
561
- if (!hasTextOutput) {
562
- hasTextOutput = true;
563
- outputLog.append('');
564
- outputLog.append(`${BLUE}${BOLD}Agent:${RESET}`);
565
- }
566
- const delta = evt.delta as string;
567
- const parts = delta.split('\n');
568
- for (let i = 0; i < parts.length; i++) {
569
- if (i > 0) outputLog.append('');
570
- if (parts[i]) outputLog.appendRaw(parts[i]);
571
- }
572
- tui.requestRender();
573
- }
574
- return;
575
- }
576
-
577
- if (data.type === 'tool_execution_start') {
578
- outputLog.append(`${DIM}[tool: ${data.toolName}]${RESET}`);
579
- tui.requestRender();
580
- return;
581
- }
582
-
583
- if (data.type === 'tool_execution_end') {
584
- const result = JSON.stringify(data.result).slice(0, 120);
585
- outputLog.append(`${DIM}[result: ${result}...]${RESET}`);
586
- tui.requestRender();
587
- return;
588
- }
589
-
590
- if (data.type === 'agent_end') {
591
- isStreaming = false;
592
- hideLoading();
593
- outputLog.append('');
594
- tui.requestRender();
595
- return;
596
- }
597
- });
598
-
599
- // -- User input --
600
-
601
- promptInput.input.onSubmit = (value) => {
602
- const trimmed = value.trim();
603
- if (!trimmed) return;
604
-
605
- promptInput.input.setValue('');
606
-
607
- if (handleSlashCommand(trimmed)) {
608
- outputLog.append(`${GREEN}${BOLD}You:${RESET} ${trimmed}`);
609
- tui.requestRender();
610
- return;
611
- }
612
-
613
- outputLog.append(`${GREEN}${BOLD}You:${RESET} ${trimmed}`);
614
- send({ type: 'prompt', message: trimmed });
615
- tui.requestRender();
616
- };
617
-
618
- promptInput.onCtrlD = exit;
619
-
620
- promptInput.input.onEscape = () => {
621
- if (isStreaming) {
622
- send({ type: 'abort' });
623
- outputLog.append(`${YELLOW}[aborted]${RESET}`);
624
- tui.requestRender();
625
- } else {
626
- exit();
627
- }
628
- };
629
-
630
- // -- Agent exit --
631
-
632
- agent.on('exit', (code) => {
633
- tui.stop();
634
- if (stderr) console.error(stderr);
635
- console.log(`Agent exited with code ${code}`);
636
- process.exit(code ?? 0);
637
- });
638
-
639
- // -- Start --
640
-
641
- outputLog.append(`${BOLD}RPC Chat${RESET}`);
642
- outputLog.append(
643
- `${DIM}Type a message and press Enter. Esc to abort or exit. Ctrl+D to quit.${RESET}`
644
- );
645
- outputLog.append(`${DIM}Slash commands: /select /confirm /input /editor${RESET}`);
646
- outputLog.append('');
647
-
648
- tui.start();
649
- }
650
-
651
- main().catch((err) => {
652
- console.error(err);
653
- process.exit(1);
654
- });
1
+ /**
2
+ * RPC Extension UI Example (TUI)
3
+ *
4
+ * A lightweight TUI chat client that spawns the agent in RPC mode.
5
+ * Demonstrates how to build a custom UI on top of the RPC protocol,
6
+ * including handling extension UI requests (select, confirm, input, editor).
7
+ *
8
+ * Usage: npx tsx examples/rpc-extension-ui.ts
9
+ *
10
+ * Slash commands:
11
+ * /select - demo select dialog
12
+ * /confirm - demo confirm dialog
13
+ * /input - demo input dialog
14
+ * /editor - demo editor dialog
15
+ */
16
+
17
+ import { spawn } from 'node:child_process';
18
+ import { dirname, join } from 'node:path';
19
+ import * as readline from 'node:readline';
20
+ import { fileURLToPath } from 'node:url';
21
+ import {
22
+ type Component,
23
+ Container,
24
+ Input,
25
+ matchesKey,
26
+ ProcessTerminal,
27
+ SelectList,
28
+ TUI
29
+ } from 'shortcutxl';
30
+
31
+ const __dirname = dirname(fileURLToPath(import.meta.url));
32
+
33
+ // ============================================================================
34
+ // ANSI helpers
35
+ // ============================================================================
36
+
37
+ const GREEN = '\x1b[32m';
38
+ const YELLOW = '\x1b[33m';
39
+ const BLUE = '\x1b[34m';
40
+ const MAGENTA = '\x1b[35m';
41
+ const RED = '\x1b[31m';
42
+ const DIM = '\x1b[2m';
43
+ const BOLD = '\x1b[1m';
44
+ const RESET = '\x1b[0m';
45
+
46
+ // ============================================================================
47
+ // Extension UI request type (subset of rpc-types.ts)
48
+ // ============================================================================
49
+
50
+ interface ExtensionUIRequest {
51
+ type: 'extension_ui_request';
52
+ id: string;
53
+ method: string;
54
+ title?: string;
55
+ options?: string[];
56
+ message?: string;
57
+ placeholder?: string;
58
+ prefill?: string;
59
+ notifyType?: 'info' | 'warning' | 'error';
60
+ statusKey?: string;
61
+ statusText?: string;
62
+ widgetKey?: string;
63
+ widgetLines?: string[];
64
+ text?: string;
65
+ }
66
+
67
+ // ============================================================================
68
+ // Output log: accumulates styled lines, renders the tail that fits
69
+ // ============================================================================
70
+
71
+ class OutputLog implements Component {
72
+ private lines: string[] = [];
73
+ private maxLines = 1000;
74
+ private visibleLines = 0;
75
+
76
+ setVisibleLines(n: number): void {
77
+ this.visibleLines = n;
78
+ }
79
+
80
+ append(line: string): void {
81
+ this.lines.push(line);
82
+ if (this.lines.length > this.maxLines) {
83
+ this.lines = this.lines.slice(-this.maxLines);
84
+ }
85
+ }
86
+
87
+ appendRaw(text: string): void {
88
+ if (this.lines.length === 0) {
89
+ this.lines.push(text);
90
+ } else {
91
+ this.lines[this.lines.length - 1] += text;
92
+ }
93
+ }
94
+
95
+ invalidate(): void {}
96
+
97
+ render(width: number): string[] {
98
+ if (this.lines.length === 0) return [''];
99
+ const n = this.visibleLines > 0 ? this.visibleLines : this.lines.length;
100
+ return this.lines.slice(-n).map((l) => l.slice(0, width));
101
+ }
102
+ }
103
+
104
+ // ============================================================================
105
+ // Loading indicator: "Agent: Working." -> ".." -> "..." -> "."
106
+ // ============================================================================
107
+
108
+ class LoadingIndicator implements Component {
109
+ private dots = 1;
110
+ private intervalId: NodeJS.Timeout | null = null;
111
+ private tui: TUI | null = null;
112
+
113
+ start(tui: TUI): void {
114
+ this.tui = tui;
115
+ this.dots = 1;
116
+ this.intervalId = setInterval(() => {
117
+ this.dots = (this.dots % 3) + 1;
118
+ this.tui?.requestRender();
119
+ }, 400);
120
+ }
121
+
122
+ stop(): void {
123
+ if (this.intervalId) {
124
+ clearInterval(this.intervalId);
125
+ this.intervalId = null;
126
+ }
127
+ }
128
+
129
+ invalidate(): void {}
130
+
131
+ render(_width: number): string[] {
132
+ return [`${BLUE}${BOLD}Agent:${RESET} ${DIM}Working${'.'.repeat(this.dots)}${RESET}`];
133
+ }
134
+ }
135
+
136
+ // ============================================================================
137
+ // Prompt input: label + single-line input
138
+ // ============================================================================
139
+
140
+ class PromptInput implements Component {
141
+ readonly input: Input;
142
+ onCtrlD?: () => void;
143
+
144
+ constructor() {
145
+ this.input = new Input();
146
+ }
147
+
148
+ handleInput(data: string): void {
149
+ if (matchesKey(data, 'ctrl+d')) {
150
+ this.onCtrlD?.();
151
+ return;
152
+ }
153
+ this.input.handleInput(data);
154
+ }
155
+
156
+ invalidate(): void {
157
+ this.input.invalidate();
158
+ }
159
+
160
+ render(width: number): string[] {
161
+ return [`${GREEN}${BOLD}You:${RESET}`, ...this.input.render(width)];
162
+ }
163
+ }
164
+
165
+ // ============================================================================
166
+ // Dialog components: replace the prompt input during interactive requests
167
+ // ============================================================================
168
+
169
+ class SelectDialog implements Component {
170
+ private list: SelectList;
171
+ private title: string;
172
+ onSelect?: (value: string) => void;
173
+ onCancel?: () => void;
174
+
175
+ constructor(title: string, options: string[]) {
176
+ this.title = title;
177
+ const items = options.map((o) => ({ value: o, label: o }));
178
+ this.list = new SelectList(items, Math.min(items.length, 8), {
179
+ selectedPrefix: (t) => `${MAGENTA}${t}${RESET}`,
180
+ selectedText: (t) => `${MAGENTA}${t}${RESET}`,
181
+ description: (t) => `${DIM}${t}${RESET}`,
182
+ scrollInfo: (t) => `${DIM}${t}${RESET}`,
183
+ noMatch: (t) => `${YELLOW}${t}${RESET}`
184
+ });
185
+ this.list.onSelect = (item) => this.onSelect?.(item.value);
186
+ this.list.onCancel = () => this.onCancel?.();
187
+ }
188
+
189
+ handleInput(data: string): void {
190
+ this.list.handleInput(data);
191
+ }
192
+
193
+ invalidate(): void {
194
+ this.list.invalidate();
195
+ }
196
+
197
+ render(width: number): string[] {
198
+ return [
199
+ `${MAGENTA}${BOLD}${this.title}${RESET}`,
200
+ ...this.list.render(width),
201
+ `${DIM}Up/Down, Enter to select, Esc to cancel${RESET}`
202
+ ];
203
+ }
204
+ }
205
+
206
+ class InputDialog implements Component {
207
+ private dialogInput: Input;
208
+ private title: string;
209
+ onCtrlD?: () => void;
210
+
211
+ constructor(title: string, prefill?: string) {
212
+ this.title = title;
213
+ this.dialogInput = new Input();
214
+ if (prefill) this.dialogInput.setValue(prefill);
215
+ }
216
+
217
+ set onSubmit(fn: ((value: string) => void) | undefined) {
218
+ this.dialogInput.onSubmit = fn;
219
+ }
220
+
221
+ set onEscape(fn: (() => void) | undefined) {
222
+ this.dialogInput.onEscape = fn;
223
+ }
224
+
225
+ get inputComponent(): Input {
226
+ return this.dialogInput;
227
+ }
228
+
229
+ handleInput(data: string): void {
230
+ if (matchesKey(data, 'ctrl+d')) {
231
+ this.onCtrlD?.();
232
+ return;
233
+ }
234
+ this.dialogInput.handleInput(data);
235
+ }
236
+
237
+ invalidate(): void {
238
+ this.dialogInput.invalidate();
239
+ }
240
+
241
+ render(width: number): string[] {
242
+ return [
243
+ `${MAGENTA}${BOLD}${this.title}${RESET}`,
244
+ ...this.dialogInput.render(width),
245
+ `${DIM}Enter to submit, Esc to cancel${RESET}`
246
+ ];
247
+ }
248
+ }
249
+
250
+ // ============================================================================
251
+ // Main
252
+ // ============================================================================
253
+
254
+ async function main() {
255
+ const extensionPath = join(__dirname, 'extensions/rpc-demo.ts');
256
+ const cliPath = join(__dirname, '../dist/cli.js');
257
+
258
+ const agent = spawn(
259
+ 'node',
260
+ [cliPath, '--mode', 'rpc', '--no-session', '--no-extension', '--extension', extensionPath],
261
+ { stdio: ['pipe', 'pipe', 'pipe'] }
262
+ );
263
+
264
+ let stderr = '';
265
+ agent.stderr?.on('data', (data: Buffer) => {
266
+ stderr += data.toString();
267
+ });
268
+
269
+ await new Promise((resolve) => setTimeout(resolve, 500));
270
+ if (agent.exitCode !== null) {
271
+ console.error(`Agent exited immediately. Stderr:\n${stderr}`);
272
+ process.exit(1);
273
+ }
274
+
275
+ // -- TUI setup --
276
+
277
+ const terminal = new ProcessTerminal();
278
+ const tui = new TUI(terminal);
279
+
280
+ const outputLog = new OutputLog();
281
+ const loadingIndicator = new LoadingIndicator();
282
+ const promptInput = new PromptInput();
283
+
284
+ const root = new Container();
285
+ root.addChild(outputLog);
286
+ root.addChild(promptInput);
287
+
288
+ tui.addChild(root);
289
+ tui.setFocus(promptInput.input);
290
+
291
+ // -- Agent communication --
292
+
293
+ function send(obj: Record<string, unknown>): void {
294
+ agent.stdin!.write(`${JSON.stringify(obj)}\n`);
295
+ }
296
+
297
+ let isStreaming = false;
298
+ let hasTextOutput = false;
299
+
300
+ function exit(): void {
301
+ tui.stop();
302
+ agent.kill('SIGTERM');
303
+ process.exit(0);
304
+ }
305
+
306
+ // -- Bottom area management --
307
+ // The bottom of the screen is either the prompt input or a dialog.
308
+ // These helpers swap between them.
309
+
310
+ let activeDialog: Component | null = null;
311
+
312
+ function setBottomComponent(component: Component): void {
313
+ root.clear();
314
+ root.addChild(outputLog);
315
+ if (isStreaming) root.addChild(loadingIndicator);
316
+ root.addChild(component);
317
+ tui.setFocus(component);
318
+ tui.requestRender();
319
+ }
320
+
321
+ function showPrompt(): void {
322
+ activeDialog = null;
323
+ setBottomComponent(promptInput);
324
+ tui.setFocus(promptInput.input);
325
+ }
326
+
327
+ function showDialog(dialog: Component): void {
328
+ activeDialog = dialog;
329
+ setBottomComponent(dialog);
330
+ }
331
+
332
+ function showLoading(): void {
333
+ if (!isStreaming) {
334
+ isStreaming = true;
335
+ hasTextOutput = false;
336
+ root.clear();
337
+ root.addChild(outputLog);
338
+ root.addChild(loadingIndicator);
339
+ root.addChild(activeDialog ?? promptInput);
340
+ if (!activeDialog) tui.setFocus(promptInput.input);
341
+ loadingIndicator.start(tui);
342
+ tui.requestRender();
343
+ }
344
+ }
345
+
346
+ function hideLoading(): void {
347
+ loadingIndicator.stop();
348
+ root.clear();
349
+ root.addChild(outputLog);
350
+ root.addChild(activeDialog ?? promptInput);
351
+ if (!activeDialog) tui.setFocus(promptInput.input);
352
+ tui.requestRender();
353
+ }
354
+
355
+ // -- Extension UI dialog handling --
356
+
357
+ function showSelectDialog(
358
+ title: string,
359
+ options: string[],
360
+ onDone: (value: string | undefined) => void
361
+ ): void {
362
+ const dialog = new SelectDialog(title, options);
363
+ dialog.onSelect = (value) => {
364
+ showPrompt();
365
+ onDone(value);
366
+ };
367
+ dialog.onCancel = () => {
368
+ showPrompt();
369
+ onDone(undefined);
370
+ };
371
+ showDialog(dialog);
372
+ }
373
+
374
+ function showInputDialog(
375
+ title: string,
376
+ prefill?: string,
377
+ onDone?: (value: string | undefined) => void
378
+ ): void {
379
+ const dialog = new InputDialog(title, prefill);
380
+ dialog.onSubmit = (value) => {
381
+ showPrompt();
382
+ onDone?.(value.trim() || undefined);
383
+ };
384
+ dialog.onEscape = () => {
385
+ showPrompt();
386
+ onDone?.(undefined);
387
+ };
388
+ dialog.onCtrlD = exit;
389
+ showDialog(dialog);
390
+ tui.setFocus(dialog.inputComponent);
391
+ }
392
+
393
+ function handleExtensionUI(req: ExtensionUIRequest): void {
394
+ const { id, method } = req;
395
+
396
+ switch (method) {
397
+ // Dialog methods: replace prompt with interactive component
398
+ case 'select': {
399
+ showSelectDialog(req.title ?? 'Select', req.options ?? [], (value) => {
400
+ if (value !== undefined) {
401
+ send({ type: 'extension_ui_response', id, value });
402
+ } else {
403
+ send({ type: 'extension_ui_response', id, cancelled: true });
404
+ }
405
+ });
406
+ break;
407
+ }
408
+
409
+ case 'confirm': {
410
+ const title = req.message ? `${req.title}: ${req.message}` : (req.title ?? 'Confirm');
411
+ showSelectDialog(title, ['Yes', 'No'], (value) => {
412
+ send({ type: 'extension_ui_response', id, confirmed: value === 'Yes' });
413
+ });
414
+ break;
415
+ }
416
+
417
+ case 'input': {
418
+ const title = req.placeholder
419
+ ? `${req.title} (${req.placeholder})`
420
+ : (req.title ?? 'Input');
421
+ showInputDialog(title, undefined, (value) => {
422
+ if (value !== undefined) {
423
+ send({ type: 'extension_ui_response', id, value });
424
+ } else {
425
+ send({ type: 'extension_ui_response', id, cancelled: true });
426
+ }
427
+ });
428
+ break;
429
+ }
430
+
431
+ case 'editor': {
432
+ const prefill = req.prefill?.replace(/\n/g, ' ');
433
+ showInputDialog(req.title ?? 'Editor', prefill, (value) => {
434
+ if (value !== undefined) {
435
+ send({ type: 'extension_ui_response', id, value });
436
+ } else {
437
+ send({ type: 'extension_ui_response', id, cancelled: true });
438
+ }
439
+ });
440
+ break;
441
+ }
442
+
443
+ // Fire-and-forget methods: display as notification
444
+ case 'notify': {
445
+ const notifyType = (req.notifyType as string) ?? 'info';
446
+ const color = notifyType === 'error' ? RED : notifyType === 'warning' ? YELLOW : MAGENTA;
447
+ outputLog.append(`${color}${BOLD}Notification:${RESET} ${req.message}`);
448
+ tui.requestRender();
449
+ break;
450
+ }
451
+
452
+ case 'setStatus':
453
+ outputLog.append(
454
+ `${MAGENTA}${BOLD}Notification:${RESET} ${DIM}[status: ${req.statusKey}]${RESET} ${req.statusText ?? '(cleared)'}`
455
+ );
456
+ tui.requestRender();
457
+ break;
458
+
459
+ case 'setWidget': {
460
+ const lines = req.widgetLines;
461
+ if (lines && lines.length > 0) {
462
+ outputLog.append(
463
+ `${MAGENTA}${BOLD}Notification:${RESET} ${DIM}[widget: ${req.widgetKey}]${RESET}`
464
+ );
465
+ for (const wl of lines) {
466
+ outputLog.append(` ${DIM}${wl}${RESET}`);
467
+ }
468
+ tui.requestRender();
469
+ }
470
+ break;
471
+ }
472
+
473
+ case 'set_editor_text':
474
+ promptInput.input.setValue((req.text as string) ?? '');
475
+ tui.requestRender();
476
+ break;
477
+ }
478
+ }
479
+
480
+ // -- Slash commands (local, not sent to agent) --
481
+
482
+ function handleSlashCommand(cmd: string): boolean {
483
+ switch (cmd) {
484
+ case '/select':
485
+ showSelectDialog('Pick a color', ['Red', 'Green', 'Blue', 'Yellow'], (value) => {
486
+ if (value) {
487
+ outputLog.append(`${MAGENTA}${BOLD}Notification:${RESET} You picked: ${value}`);
488
+ } else {
489
+ outputLog.append(`${MAGENTA}${BOLD}Notification:${RESET} Selection cancelled`);
490
+ }
491
+ tui.requestRender();
492
+ });
493
+ return true;
494
+
495
+ case '/confirm':
496
+ showSelectDialog('Are you sure?', ['Yes', 'No'], (value) => {
497
+ const confirmed = value === 'Yes';
498
+ outputLog.append(`${MAGENTA}${BOLD}Notification:${RESET} Confirmed: ${confirmed}`);
499
+ tui.requestRender();
500
+ });
501
+ return true;
502
+
503
+ case '/input':
504
+ showInputDialog('Enter your name', undefined, (value) => {
505
+ if (value) {
506
+ outputLog.append(`${MAGENTA}${BOLD}Notification:${RESET} You entered: ${value}`);
507
+ } else {
508
+ outputLog.append(`${MAGENTA}${BOLD}Notification:${RESET} Input cancelled`);
509
+ }
510
+ tui.requestRender();
511
+ });
512
+ return true;
513
+
514
+ case '/editor':
515
+ showInputDialog('Edit text', 'Hello, world!', (value) => {
516
+ if (value) {
517
+ outputLog.append(`${MAGENTA}${BOLD}Notification:${RESET} Submitted: ${value}`);
518
+ } else {
519
+ outputLog.append(`${MAGENTA}${BOLD}Notification:${RESET} Editor cancelled`);
520
+ }
521
+ tui.requestRender();
522
+ });
523
+ return true;
524
+
525
+ default:
526
+ return false;
527
+ }
528
+ }
529
+
530
+ // -- Process agent stdout --
531
+
532
+ const stdoutRl = readline.createInterface({ input: agent.stdout!, terminal: false });
533
+
534
+ stdoutRl.on('line', (line) => {
535
+ let data: Record<string, unknown>;
536
+ try {
537
+ data = JSON.parse(line);
538
+ } catch {
539
+ return;
540
+ }
541
+
542
+ if (data.type === 'response' && !data.success) {
543
+ outputLog.append(`${RED}[error]${RESET} ${data.command}: ${data.error}`);
544
+ tui.requestRender();
545
+ return;
546
+ }
547
+
548
+ if (data.type === 'agent_start') {
549
+ showLoading();
550
+ return;
551
+ }
552
+
553
+ if (data.type === 'extension_ui_request') {
554
+ handleExtensionUI(data as unknown as ExtensionUIRequest);
555
+ return;
556
+ }
557
+
558
+ if (data.type === 'message_update') {
559
+ const evt = data.assistantMessageEvent as Record<string, unknown> | undefined;
560
+ if (evt?.type === 'text_delta') {
561
+ if (!hasTextOutput) {
562
+ hasTextOutput = true;
563
+ outputLog.append('');
564
+ outputLog.append(`${BLUE}${BOLD}Agent:${RESET}`);
565
+ }
566
+ const delta = evt.delta as string;
567
+ const parts = delta.split('\n');
568
+ for (let i = 0; i < parts.length; i++) {
569
+ if (i > 0) outputLog.append('');
570
+ if (parts[i]) outputLog.appendRaw(parts[i]);
571
+ }
572
+ tui.requestRender();
573
+ }
574
+ return;
575
+ }
576
+
577
+ if (data.type === 'tool_execution_start') {
578
+ outputLog.append(`${DIM}[tool: ${data.toolName}]${RESET}`);
579
+ tui.requestRender();
580
+ return;
581
+ }
582
+
583
+ if (data.type === 'tool_execution_end') {
584
+ const result = JSON.stringify(data.result).slice(0, 120);
585
+ outputLog.append(`${DIM}[result: ${result}...]${RESET}`);
586
+ tui.requestRender();
587
+ return;
588
+ }
589
+
590
+ if (data.type === 'agent_end') {
591
+ isStreaming = false;
592
+ hideLoading();
593
+ outputLog.append('');
594
+ tui.requestRender();
595
+ return;
596
+ }
597
+ });
598
+
599
+ // -- User input --
600
+
601
+ promptInput.input.onSubmit = (value) => {
602
+ const trimmed = value.trim();
603
+ if (!trimmed) return;
604
+
605
+ promptInput.input.setValue('');
606
+
607
+ if (handleSlashCommand(trimmed)) {
608
+ outputLog.append(`${GREEN}${BOLD}You:${RESET} ${trimmed}`);
609
+ tui.requestRender();
610
+ return;
611
+ }
612
+
613
+ outputLog.append(`${GREEN}${BOLD}You:${RESET} ${trimmed}`);
614
+ send({ type: 'prompt', message: trimmed });
615
+ tui.requestRender();
616
+ };
617
+
618
+ promptInput.onCtrlD = exit;
619
+
620
+ promptInput.input.onEscape = () => {
621
+ if (isStreaming) {
622
+ send({ type: 'abort' });
623
+ outputLog.append(`${YELLOW}[aborted]${RESET}`);
624
+ tui.requestRender();
625
+ } else {
626
+ exit();
627
+ }
628
+ };
629
+
630
+ // -- Agent exit --
631
+
632
+ agent.on('exit', (code) => {
633
+ tui.stop();
634
+ if (stderr) console.error(stderr);
635
+ console.log(`Agent exited with code ${code}`);
636
+ process.exit(code ?? 0);
637
+ });
638
+
639
+ // -- Start --
640
+
641
+ outputLog.append(`${BOLD}RPC Chat${RESET}`);
642
+ outputLog.append(
643
+ `${DIM}Type a message and press Enter. Esc to abort or exit. Ctrl+D to quit.${RESET}`
644
+ );
645
+ outputLog.append(`${DIM}Slash commands: /select /confirm /input /editor${RESET}`);
646
+ outputLog.append('');
647
+
648
+ tui.start();
649
+ }
650
+
651
+ main().catch((err) => {
652
+ console.error(err);
653
+ process.exit(1);
654
+ });