@orbit-build/cli 0.1.0 → 0.1.2

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.
@@ -1,2548 +0,0 @@
1
- import { join, dirname } from "path";
2
- import { homedir } from "os";
3
- import { existsSync, readFileSync, writeFileSync, mkdirSync } from "fs";
4
- import { exec } from "child_process";
5
- import readline from "readline";
6
- import { Prompt, Renderer } from "@orbit-build/tui";
7
- import { BUILTIN_SLASH_COMMANDS } from "../runtime/CommandRouter.js";
8
-
9
- export function previousCodePointIndex(text: string, index: number): number {
10
- const safeIndex = Math.max(0, Math.min(index, text.length));
11
- if (safeIndex === 0) return 0;
12
- const previous = text.charCodeAt(safeIndex - 1);
13
- if (previous >= 0xdc00 && previous <= 0xdfff && safeIndex >= 2) {
14
- const leading = text.charCodeAt(safeIndex - 2);
15
- if (leading >= 0xd800 && leading <= 0xdbff) {
16
- return safeIndex - 2;
17
- }
18
- }
19
- return safeIndex - 1;
20
- }
21
-
22
- export function nextCodePointIndex(text: string, index: number): number {
23
- const safeIndex = Math.max(0, Math.min(index, text.length));
24
- if (safeIndex >= text.length) return text.length;
25
- const leading = text.charCodeAt(safeIndex);
26
- if (leading >= 0xd800 && leading <= 0xdbff && safeIndex + 1 < text.length) {
27
- const trailing = text.charCodeAt(safeIndex + 1);
28
- if (trailing >= 0xdc00 && trailing <= 0xdfff) {
29
- return safeIndex + 2;
30
- }
31
- }
32
- return safeIndex + 1;
33
- }
34
-
35
- export function previousWordIndex(text: string, index: number): number {
36
- let pos = index;
37
- while (pos > 0 && /\s/.test(text.charAt(pos - 1))) {
38
- pos--;
39
- }
40
- while (pos > 0 && !/\s/.test(text.charAt(pos - 1))) {
41
- pos--;
42
- }
43
- return pos;
44
- }
45
-
46
- export function nextWordIndex(text: string, index: number): number {
47
- let pos = index;
48
- while (pos < text.length && /\s/.test(text.charAt(pos))) {
49
- pos++;
50
- }
51
- while (pos < text.length && !/\s/.test(text.charAt(pos))) {
52
- pos++;
53
- }
54
- return pos;
55
- }
56
-
57
- export function parseMouseWheelDirection(
58
- input: string | undefined | null,
59
- ): "up" | "down" | null {
60
- if (typeof input !== "string") return null;
61
- const match = input.match(/\x1b\[<(\d+);\d+;\d+[mM]/);
62
- if (!match) return null;
63
- const button = Number(match[1]);
64
- if ((button & 64) === 0) return null;
65
- return (button & 1) === 0 ? "up" : "down";
66
- }
67
-
68
- export async function pageText(text: string): Promise<void> {
69
- const lines = text.split("\n");
70
- const rows = process.stdout.rows || 24;
71
- const pageSize = rows - 2;
72
-
73
- if (lines.length <= pageSize) {
74
- console.log(text);
75
- return;
76
- }
77
-
78
- let cursor = 0;
79
- const wasRaw = !!process.stdin.isRaw;
80
- if (process.stdin.setRawMode) {
81
- process.stdin.setRawMode(true);
82
- }
83
- process.stdin.resume();
84
-
85
- readline.emitKeypressEvents(process.stdin);
86
-
87
- const keypressPromise = (): Promise<string> => {
88
- return new Promise((resolve) => {
89
- const onKeypress = (str: string, key: any) => {
90
- process.stdin.removeListener("keypress", onKeypress);
91
- if (key && key.ctrl && key.name === "c") {
92
- if (process.stdin.setRawMode) {
93
- process.stdin.setRawMode(wasRaw);
94
- }
95
- process.exit(0);
96
- }
97
- resolve(key ? key.name || str : str);
98
- };
99
- process.stdin.on("keypress", onKeypress);
100
- });
101
- };
102
-
103
- try {
104
- while (cursor < lines.length) {
105
- const chunk = lines.slice(cursor, cursor + pageSize);
106
- console.log(chunk.join("\n"));
107
- cursor += pageSize;
108
-
109
- if (cursor >= lines.length) {
110
- break;
111
- }
112
-
113
- process.stdout.write(
114
- `\r\x1b[36m-- More (${Math.round((cursor / lines.length) * 100)}%) [Space/Enter to continue, q to quit] --\x1b[39m`,
115
- );
116
-
117
- const key = await keypressPromise();
118
- process.stdout.write("\r\x1b[K");
119
-
120
- if (key === "q") {
121
- break;
122
- }
123
- if (key === "return" || key === "enter") {
124
- cursor = cursor - pageSize + 1;
125
- }
126
- }
127
- } finally {
128
- if (process.stdin.setRawMode) {
129
- process.stdin.setRawMode(wasRaw);
130
- }
131
- process.stdin.pause();
132
- }
133
- }
134
-
135
- export class FullscreenTui {
136
- private history: Array<{
137
- role: "user" | "assistant" | "system";
138
- text: string;
139
- thoughtTime?: number; // ms
140
- totalTime?: number; // ms
141
- attempt?: number;
142
- }> = [];
143
-
144
- private inputBuffer = "";
145
- private cursorPosition = 0;
146
- public isActive = false;
147
- private currentAttempt = 0;
148
-
149
- // Command history
150
- private inputHistory: string[] = [];
151
- private historyIndex = -1;
152
- private tempBuffer = "";
153
- private activeCommandIndex = 0;
154
- private ctrlCPressedOnce = false;
155
- private ctrlCTimeout: NodeJS.Timeout | null = null;
156
- private cachedStaticLinesCount = 0;
157
- private cachedStaticContent = "";
158
- private lastRenderedBottomHeight = 0;
159
-
160
- // DeepSeek real-time thinking
161
- private currentThinking = "";
162
-
163
- // Timers and metrics
164
- private attemptStartTime = 0;
165
- private firstDeltaTime = 0;
166
- private thoughtTimer: NodeJS.Timeout | null = null;
167
- private thoughtElapsed = 0;
168
- private isThinking = false;
169
-
170
- private sessionCost = 0;
171
- private totalInputTokens = 0;
172
- private totalCacheReadTokens = 0;
173
- private totalOutputTokens = 0;
174
- private budgetLimit = 0;
175
-
176
- private resolveInput: ((val: string | null) => void) | null = null;
177
- private activeRunnable: { abort: () => void } | null = null;
178
- private thinkingKeypressListener: ((str: string, key: any) => void) | null =
179
- null;
180
- public pendingGuidedStatement: string | null = null;
181
-
182
- // Throttled rendering to prevent terminal flickering during model output
183
- private lastRenderTime = 0;
184
- private renderPending = false;
185
- private renderTimeout: NodeJS.Timeout | null = null;
186
-
187
- private originalWrite = process.stdout.write.bind(process.stdout);
188
- private hasWrittenStdoutSinceStop = false;
189
- private originalStdinEmit: any = null;
190
-
191
-
192
- private candidates: {
193
- commands: string[];
194
- files: string[];
195
- symbols: string[];
196
- sessions: string[];
197
- } | null = null;
198
- private modelNameGetter: () => string = () => this.modelName;
199
- private permissionsMode = "normal";
200
- private hideAutocomplete = false;
201
-
202
- private cachedPlanLines: string[] = [];
203
- private lastPlanReadTime = 0;
204
- private activeContextFiles: Array<{
205
- path: string;
206
- reason: string;
207
- readOnly?: boolean;
208
- }> = [];
209
- private cachedGitSummary: {
210
- branch: string;
211
- added: number;
212
- modified: number;
213
- deleted: number;
214
- } | null = null;
215
- private lastGitSummaryReadTime = 0;
216
- private isRefreshingGit = false;
217
- private historyScrollOffset = 0;
218
- private maxHistoryScrollOffset = 0;
219
- private lastHistoryLineCount = 0;
220
- private hasNewOutputWhileScrolled = false;
221
-
222
- private getPlanLines(): string[] {
223
- const now = Date.now();
224
- if (now - this.lastPlanReadTime < 2000) {
225
- return this.cachedPlanLines;
226
- }
227
- this.lastPlanReadTime = now;
228
- const planPath2 = join(this.cwd, ".orbit", "task.md");
229
- const planPath1 = join(this.cwd, "task.md");
230
- let planPath = "";
231
- if (existsSync(planPath2)) {
232
- planPath = planPath2;
233
- } else if (existsSync(planPath1)) {
234
- planPath = planPath1;
235
- }
236
- if (!planPath) {
237
- this.cachedPlanLines = [];
238
- return [];
239
- }
240
- try {
241
- const content = readFileSync(planPath, "utf8");
242
- const lines = content.split("\n");
243
- const planItems: string[] = [];
244
- for (const line of lines) {
245
- const trimmed = line.trim();
246
- if (
247
- trimmed.startsWith("- [ ") ||
248
- trimmed.startsWith("- [x") ||
249
- trimmed.startsWith("- [/") ||
250
- trimmed.startsWith("- [x]") ||
251
- trimmed.startsWith("- [ ]") ||
252
- trimmed.startsWith("- [/]")
253
- ) {
254
- planItems.push(trimmed);
255
- }
256
- }
257
- this.cachedPlanLines = planItems;
258
- } catch {
259
- this.cachedPlanLines = [];
260
- }
261
- return this.cachedPlanLines;
262
- }
263
-
264
- public setPermissionsMode(mode: string) {
265
- this.permissionsMode = mode;
266
- }
267
-
268
- public setModelNameGetter(getter: () => string) {
269
- this.modelNameGetter = getter;
270
- }
271
-
272
- public setActiveRunnable(runnable: { abort: () => void } | null) {
273
- this.activeRunnable = runnable;
274
- }
275
-
276
- constructor(
277
- private cwd: string,
278
- private modelName: string,
279
- private version: string,
280
- private config?: any,
281
- ) {
282
- readline.emitKeypressEvents(process.stdin);
283
- process.stdout.write = (chunk: any, encoding?: any, cb?: any) => {
284
- if (!this.isActive) {
285
- const text = typeof chunk === "string" ? chunk : chunk.toString();
286
- if (text.trim().length > 0) {
287
- this.hasWrittenStdoutSinceStop = true;
288
- }
289
- }
290
- return this.originalWrite(chunk, encoding, cb);
291
- };
292
- this.loadInputHistory();
293
- }
294
-
295
- public setCandidates(candidates: any) {
296
- if (!candidates) {
297
- this.candidates = null;
298
- return;
299
- }
300
- this.candidates = {
301
- commands: Array.isArray(candidates.commands)
302
- ? candidates.commands.filter((c: any) => typeof c === "string")
303
- : [],
304
- files: Array.isArray(candidates.files)
305
- ? candidates.files.filter((f: any) => typeof f === "string")
306
- : [],
307
- symbols: Array.isArray(candidates.symbols)
308
- ? candidates.symbols.filter((s: any) => typeof s === "string")
309
- : [],
310
- sessions: Array.isArray(candidates.sessions)
311
- ? candidates.sessions.filter((s: any) => typeof s === "string")
312
- : [],
313
- };
314
- }
315
-
316
- private getHistoryFilePath(): string {
317
- return join(homedir(), ".orbit", "input_history.json");
318
- }
319
-
320
- private loadInputHistory() {
321
- try {
322
- const filePath = this.getHistoryFilePath();
323
- if (existsSync(filePath)) {
324
- const raw = readFileSync(filePath, "utf8");
325
- const parsed = JSON.parse(raw);
326
- if (Array.isArray(parsed)) {
327
- this.inputHistory = parsed.filter((x) => typeof x === "string");
328
- }
329
- }
330
- } catch {
331
- this.inputHistory = [];
332
- }
333
- }
334
-
335
- private saveInputHistory() {
336
- try {
337
- const filePath = this.getHistoryFilePath();
338
- const dir = dirname(filePath);
339
- if (!existsSync(dir)) {
340
- mkdirSync(dir, { recursive: true });
341
- }
342
- writeFileSync(
343
- filePath,
344
- JSON.stringify(this.inputHistory, null, 2),
345
- "utf8",
346
- );
347
- } catch {
348
- // Ignore
349
- }
350
- }
351
-
352
- public addSystemMessage(text: string, _raw = false) {
353
- if (!text) return;
354
- this.history.push({
355
- role: "system",
356
- text: text,
357
- });
358
- this.render();
359
- }
360
-
361
- private onResize = () => {
362
- if (this.isActive) {
363
- this.render(true);
364
- }
365
- };
366
-
367
- public start(budgetLimit: number) {
368
- this.budgetLimit = budgetLimit;
369
- this.isActive = true;
370
- this.hasWrittenStdoutSinceStop = false;
371
-
372
- if (this.originalStdinEmit) {
373
- process.stdin.emit = this.originalStdinEmit;
374
- this.originalStdinEmit = null;
375
- }
376
-
377
- const mouseMode =
378
- this.config?.tui?.mouse !== false ? "\x1b[?1000h\x1b[?1006h" : "";
379
- process.stdout.write(`\x1b[?1049h${mouseMode}\x1b[?25l`);
380
- process.stdout.on("resize", this.onResize);
381
-
382
- if (this.config?.tui?.mouse !== false) {
383
- this.originalStdinEmit = process.stdin.emit;
384
- process.stdin.emit = (event: string, ...args: any[]) => {
385
- if (event === "data" && args[0]) {
386
- const chunk = args[0];
387
- const isBuffer = Buffer.isBuffer(chunk);
388
- let str = isBuffer ? chunk.toString("utf8") : chunk;
389
-
390
- const sgrRegex = /\x1b\[<(\d+);(\d+);(\d+)([mM])/g;
391
- let match;
392
- let hasMouse = false;
393
- while ((match = sgrRegex.exec(str)) !== null) {
394
- hasMouse = true;
395
- const button = Number(match[1]);
396
- if ((button & 64) !== 0) {
397
- const direction = (button & 1) === 0 ? "up" : "down";
398
- const lines = this.getWheelScrollLines();
399
- this.scrollHistory(direction === "up" ? lines : -lines);
400
- }
401
- }
402
-
403
- if (hasMouse) {
404
- str = str.replace(sgrRegex, "");
405
- }
406
-
407
- const normalRegex = /\x1b\[M([\s\S]{3})/g;
408
- if (normalRegex.test(str)) {
409
- str = str.replace(normalRegex, "");
410
- hasMouse = true;
411
- }
412
-
413
- if (hasMouse) {
414
- if (str.length === 0) {
415
- return true;
416
- }
417
- args[0] = isBuffer ? Buffer.from(str, "utf8") : str;
418
- }
419
- }
420
- return this.originalStdinEmit.apply(process.stdin, [event, ...args]);
421
- };
422
- }
423
-
424
- this.render();
425
- }
426
-
427
- public stop() {
428
- if (!this.isActive) return;
429
- this.isActive = false;
430
- process.stdout.off("resize", this.onResize);
431
- process.stdout.write("\x1b[?1006l\x1b[?1000l\x1b[?1049l\x1b[?25h");
432
- this.hasWrittenStdoutSinceStop = false;
433
- if (this.renderTimeout) {
434
- clearTimeout(this.renderTimeout);
435
- this.renderTimeout = null;
436
- }
437
- this.renderPending = false;
438
-
439
- if (this.originalStdinEmit) {
440
- process.stdin.emit = this.originalStdinEmit;
441
- this.originalStdinEmit = null;
442
- }
443
- }
444
-
445
-
446
- public dispose() {
447
- this.stopThinkingInput();
448
- this.stop();
449
- if (this.thoughtTimer) {
450
- clearInterval(this.thoughtTimer);
451
- this.thoughtTimer = null;
452
- }
453
- if (this.ctrlCTimeout) {
454
- clearTimeout(this.ctrlCTimeout);
455
- this.ctrlCTimeout = null;
456
- }
457
- if (process.stdin.setRawMode && process.stdin.isTTY) {
458
- process.stdin.setRawMode(false);
459
- }
460
- process.stdout.write = this.originalWrite as typeof process.stdout.write;
461
- }
462
-
463
- private getGitSummary() {
464
- const now = Date.now();
465
- if (!this.cachedGitSummary) {
466
- this.cachedGitSummary = {
467
- branch: "no-git",
468
- added: 0,
469
- modified: 0,
470
- deleted: 0,
471
- };
472
- this.refreshGitSummaryAsync().catch(() => {});
473
- } else if (now - this.lastGitSummaryReadTime > 8000) {
474
- this.refreshGitSummaryAsync().catch(() => {});
475
- }
476
- return this.cachedGitSummary;
477
- }
478
-
479
- private async refreshGitSummaryAsync() {
480
- if (this.isRefreshingGit) return;
481
- this.isRefreshingGit = true;
482
- this.lastGitSummaryReadTime = Date.now();
483
-
484
- try {
485
- const summary = {
486
- branch: "no-git",
487
- added: 0,
488
- modified: 0,
489
- deleted: 0,
490
- };
491
-
492
- const branchPromise = new Promise<string>((resolve) => {
493
- exec(
494
- "git rev-parse --abbrev-ref HEAD",
495
- { cwd: this.cwd },
496
- (err, stdout) => {
497
- if (err) resolve("no-git");
498
- else resolve(stdout.trim());
499
- },
500
- );
501
- });
502
-
503
- const statusPromise = new Promise<string>((resolve) => {
504
- exec("git status --porcelain", { cwd: this.cwd }, (err, stdout) => {
505
- if (err) resolve("");
506
- else resolve(stdout);
507
- });
508
- });
509
-
510
- const [branch, statusOutput] = await Promise.all([
511
- branchPromise,
512
- statusPromise,
513
- ]);
514
- summary.branch = branch;
515
-
516
- for (const line of statusOutput.split("\n")) {
517
- if (!line) continue;
518
- const code = line.substring(0, 2);
519
- if (code.includes("A") || code.includes("?")) {
520
- summary.added++;
521
- } else if (code.includes("M") || code.includes("R")) {
522
- summary.modified++;
523
- } else if (code.includes("D")) {
524
- summary.deleted++;
525
- }
526
- }
527
-
528
- this.cachedGitSummary = summary;
529
- this.render();
530
- } catch {
531
- // Ignored
532
- } finally {
533
- this.isRefreshingGit = false;
534
- }
535
- }
536
-
537
- private getWheelScrollLines(): number {
538
- const configured = Number(this.config?.tui?.scrollSpeed ?? 50);
539
- return Math.max(1, Math.min(20, Math.ceil(configured / 5)));
540
- }
541
-
542
- private scrollHistory(delta: number): void {
543
- this.historyScrollOffset = Math.max(
544
- 0,
545
- Math.min(this.maxHistoryScrollOffset, this.historyScrollOffset + delta),
546
- );
547
- if (this.historyScrollOffset === 0) {
548
- this.hasNewOutputWhileScrolled = false;
549
- }
550
- this.render();
551
- }
552
-
553
- private handleScrollInput(str: string, key: any): boolean {
554
- const wheelDirection = parseMouseWheelDirection(str);
555
- if (wheelDirection) {
556
- const lines = this.getWheelScrollLines();
557
- this.scrollHistory(wheelDirection === "up" ? lines : -lines);
558
- return true;
559
- }
560
-
561
- const pageSize = Math.max(3, Math.floor((process.stdout.rows || 24) * 0.6));
562
- if (key?.name === "pageup") {
563
- this.scrollHistory(pageSize);
564
- return true;
565
- }
566
- if (key?.name === "pagedown") {
567
- this.scrollHistory(-pageSize);
568
- return true;
569
- }
570
- if (key?.name === "home" && key?.ctrl) {
571
- this.scrollHistory(this.maxHistoryScrollOffset);
572
- return true;
573
- }
574
- if (key?.name === "end" && this.historyScrollOffset > 0) {
575
- this.historyScrollOffset = 0;
576
- this.hasNewOutputWhileScrolled = false;
577
- this.render();
578
- return true;
579
- }
580
- return false;
581
- }
582
-
583
- public startThinkingInput() {
584
- if (!this.isActive) return;
585
- this.stopThinkingInput();
586
-
587
- if (process.stdin.setRawMode) {
588
- process.stdin.setRawMode(true);
589
- }
590
- process.stdin.resume();
591
-
592
- this.thinkingKeypressListener = (str: string, key: any) => {
593
- try {
594
- if (!this.isActive) {
595
- this.stopThinkingInput();
596
- return;
597
- }
598
-
599
- if (this.handleScrollInput(str, key)) {
600
- return;
601
- }
602
-
603
- if (key && key.ctrl && key.name === "c") {
604
- if (this.inputBuffer.length > 0) {
605
- this.inputBuffer = "";
606
- this.cursorPosition = 0;
607
- this.render();
608
- } else {
609
- if (this.activeRunnable) {
610
- this.activeRunnable.abort();
611
- }
612
- }
613
- return;
614
- }
615
-
616
- if (key && (key.name === "return" || key.name === "enter")) {
617
- const submitted = this.inputBuffer;
618
- if (submitted.trim()) {
619
- this.pendingGuidedStatement = submitted;
620
- if (this.activeRunnable) {
621
- this.activeRunnable.abort();
622
- }
623
- }
624
- this.inputBuffer = "";
625
- this.cursorPosition = 0;
626
- this.render();
627
- return;
628
- }
629
-
630
- if (key && (key.name === "home" || (key.ctrl && key.name === "a"))) {
631
- this.cursorPosition = 0;
632
- this.render();
633
- return;
634
- }
635
-
636
- if (key && (key.name === "end" || (key.ctrl && key.name === "e"))) {
637
- this.cursorPosition = this.inputBuffer.length;
638
- this.render();
639
- return;
640
- }
641
-
642
- if (key && (key.ctrl || key.meta) && key.name === "left") {
643
- this.cursorPosition = previousWordIndex(this.inputBuffer, this.cursorPosition);
644
- this.render();
645
- return;
646
- }
647
-
648
- if (key && (key.ctrl || key.meta) && key.name === "right") {
649
- this.cursorPosition = nextWordIndex(this.inputBuffer, this.cursorPosition);
650
- this.render();
651
- return;
652
- }
653
-
654
- if (key && key.ctrl && (key.name === "backspace" || key.name === "w")) {
655
- if (this.cursorPosition > 0) {
656
- const targetPos = previousWordIndex(this.inputBuffer, this.cursorPosition);
657
- this.inputBuffer =
658
- this.inputBuffer.slice(0, targetPos) +
659
- this.inputBuffer.slice(this.cursorPosition);
660
- this.cursorPosition = targetPos;
661
- this.render();
662
- }
663
- return;
664
- }
665
-
666
- if (key && key.ctrl && key.name === "delete") {
667
- if (this.cursorPosition < this.inputBuffer.length) {
668
- const targetPos = nextWordIndex(this.inputBuffer, this.cursorPosition);
669
- this.inputBuffer =
670
- this.inputBuffer.slice(0, this.cursorPosition) +
671
- this.inputBuffer.slice(targetPos);
672
- this.render();
673
- }
674
- return;
675
- }
676
-
677
- if (key && key.ctrl && key.name === "u") {
678
- this.inputBuffer = "";
679
- this.cursorPosition = 0;
680
- this.render();
681
- return;
682
- }
683
-
684
- if (key && key.ctrl) {
685
- return;
686
- }
687
-
688
- if (key && key.name === "backspace") {
689
- if (this.cursorPosition > 0) {
690
- const previousIndex = previousCodePointIndex(
691
- this.inputBuffer,
692
- this.cursorPosition,
693
- );
694
- this.inputBuffer =
695
- this.inputBuffer.slice(0, previousIndex) +
696
- this.inputBuffer.slice(this.cursorPosition);
697
- this.cursorPosition = previousIndex;
698
- this.render();
699
- }
700
- return;
701
- }
702
-
703
- if (key && key.name === "delete") {
704
- if (this.cursorPosition < this.inputBuffer.length) {
705
- const nextIndex = nextCodePointIndex(
706
- this.inputBuffer,
707
- this.cursorPosition,
708
- );
709
- this.inputBuffer =
710
- this.inputBuffer.slice(0, this.cursorPosition) +
711
- this.inputBuffer.slice(nextIndex);
712
- this.render();
713
- }
714
- return;
715
- }
716
-
717
- if (key && key.name === "left") {
718
- if (this.cursorPosition > 0) {
719
- this.cursorPosition = previousCodePointIndex(
720
- this.inputBuffer,
721
- this.cursorPosition,
722
- );
723
- this.render();
724
- }
725
- return;
726
- }
727
-
728
- if (key && key.name === "right") {
729
- if (this.cursorPosition < this.inputBuffer.length) {
730
- this.cursorPosition = nextCodePointIndex(
731
- this.inputBuffer,
732
- this.cursorPosition,
733
- );
734
- this.render();
735
- }
736
- return;
737
- }
738
-
739
- if (str && !/[\u0000-\u001f\u007f]/.test(str)) {
740
- this.inputBuffer =
741
- this.inputBuffer.slice(0, this.cursorPosition) +
742
- str +
743
- this.inputBuffer.slice(this.cursorPosition);
744
- this.cursorPosition += str.length;
745
- this.render();
746
- }
747
- } catch (error) {
748
- const logDir = join(homedir(), ".orbit");
749
- try {
750
- if (!existsSync(logDir)) {
751
- mkdirSync(logDir, { recursive: true });
752
- }
753
- writeFileSync(
754
- join(logDir, "tui_error.log"),
755
- `[${new Date().toISOString()}] Error in thinkingKeypressListener: ${error instanceof Error ? error.stack : error}\n`,
756
- { flag: "a" },
757
- );
758
- } catch {}
759
- try {
760
- this.render();
761
- } catch {}
762
- }
763
- };
764
-
765
- process.stdin.on("keypress", this.thinkingKeypressListener);
766
- }
767
-
768
- public stopThinkingInput() {
769
- if (this.thinkingKeypressListener) {
770
- process.stdin.removeListener("keypress", this.thinkingKeypressListener);
771
- this.thinkingKeypressListener = null;
772
- }
773
- }
774
-
775
- private getActiveMatches(): string[] {
776
- if (!this.candidates || !this.inputBuffer.startsWith("/")) return [];
777
- if (this.hideAutocomplete) return [];
778
-
779
- const line = this.inputBuffer;
780
- const parts = line.split(/\s+/);
781
-
782
- if (parts[0] === "/add" && line.includes(" ")) {
783
- let query = line.slice(5).trim();
784
- let prefix = "/add ";
785
- if (query.startsWith("-r ")) {
786
- prefix = "/add -r ";
787
- query = query.slice(3).trim();
788
- } else if (query.startsWith("--read-only ")) {
789
- prefix = "/add --read-only ";
790
- query = query.slice(12).trim();
791
- } else if (query.startsWith("--readonly ")) {
792
- prefix = "/add --readonly ";
793
- query = query.slice(11).trim();
794
- } else if (query === "-r" || query === "--read-only" || query === "--readonly") {
795
- query = "";
796
- prefix = `/add ${parts[1]} `;
797
- }
798
- const hits = (this.candidates.files || [])
799
- .filter((f) => f.toLowerCase().includes(query.toLowerCase()))
800
- .map((f) => `${prefix}${f}`);
801
- if (hits.length > 0) return hits;
802
- }
803
-
804
- if (parts[0] === "/drop" && line.includes(" ")) {
805
- const query = line.slice(6).trim();
806
- const hits = (this.candidates.files || [])
807
- .filter((f) => f.toLowerCase().includes(query.toLowerCase()))
808
- .map((f) => `/drop ${f}`);
809
- if (hits.length > 0) return hits;
810
- }
811
-
812
- if (parts[0] === "/model" && line.includes(" ")) {
813
- const query = line.slice(7).trim();
814
- const defaultProvider = this.config?.provider?.default;
815
- const providerConfig = this.config?.providers?.[defaultProvider];
816
- const providerType = providerConfig?.type;
817
-
818
- let models: string[] = [];
819
- if (
820
- providerType === "anthropic" ||
821
- providerType === "anthropic-compatible"
822
- ) {
823
- models = [
824
- "claude-3-5-sonnet-latest",
825
- "claude-3-5-haiku-latest",
826
- "claude-3-opus-latest",
827
- ];
828
- } else if (providerType === "openai") {
829
- models = ["gpt-4o", "gpt-4o-mini", "o1", "o3-mini"];
830
- } else if (providerType === "openai-compatible") {
831
- if (defaultProvider?.includes("deepseek")) {
832
- models = [
833
- "deepseek-v4-flash",
834
- "deepseek-v4-pro",
835
- "deepseek-chat",
836
- "deepseek-reasoner",
837
- ];
838
- } else {
839
- models = [
840
- "gpt-4o",
841
- "gpt-4o-mini",
842
- "deepseek-chat",
843
- "deepseek-reasoner",
844
- ];
845
- }
846
- } else if (providerType === "ollama") {
847
- models = ["qwen2.5-coder:7b", "qwen2.5-coder:1.5b", "llama3"];
848
- } else {
849
- models = [
850
- "deepseek-v4-flash",
851
- "deepseek-v4-pro",
852
- "gpt-4o",
853
- "o3-mini",
854
- "claude-3-5-sonnet-latest",
855
- ];
856
- }
857
-
858
- const hits = models
859
- .filter((m) => m.toLowerCase().includes(query.toLowerCase()))
860
- .map((m) => `/model ${m}`);
861
- if (hits.length > 0) return hits;
862
- }
863
-
864
- if (parts[0] === "/chat" && line.includes(" ")) {
865
- // 1. If it's just "/chat " completing the subcommand
866
- if (parts.length <= 2) {
867
- const subcommands = ["list", "ls", "new", "delete", "rm", "switch"];
868
- const hits = subcommands
869
- .map((sub) => `/chat ${sub}`)
870
- .filter((c) => c.startsWith(line));
871
- if (hits.length > 0) return hits;
872
- }
873
-
874
- // 2. If it's "/chat delete <query>", "/chat switch <query>", "/chat rm <query>"
875
- if (parts.length >= 3 && ["delete", "rm", "switch"].includes(parts[1])) {
876
- const cmd = parts[0];
877
- const sub = parts[1];
878
- const query = parts.slice(2).join(" ");
879
- const prefix = `${cmd} ${sub} `;
880
- const hits = (this.candidates.sessions || [])
881
- .filter((s) => {
882
- const lowerS = s.toLowerCase();
883
- const lowerQ = query.toLowerCase();
884
- return (
885
- lowerS.startsWith(lowerQ) ||
886
- s
887
- .replace(/^sess_/, "")
888
- .toLowerCase()
889
- .startsWith(lowerQ)
890
- );
891
- })
892
- .map((s) => `${prefix}${s}`);
893
- if (hits.length > 0) return hits;
894
- }
895
- }
896
-
897
-
898
- const cmds =
899
- this.candidates &&
900
- Array.isArray(this.candidates.commands) &&
901
- this.candidates.commands.length > 0
902
- ? this.candidates.commands
903
- : BUILTIN_SLASH_COMMANDS;
904
- return cmds.filter((c) => c.startsWith(line));
905
- }
906
-
907
- private getSuggestion(): string {
908
- const line = this.inputBuffer;
909
- const matches = this.getActiveMatches();
910
- if (matches.length > 0) {
911
- const idx = Math.min(this.activeCommandIndex, matches.length - 1);
912
- const match = matches[idx];
913
- if (match && match !== line) {
914
- return match.substring(line.length);
915
- }
916
- }
917
- return "";
918
- }
919
-
920
- private getHits(): { hits: string[]; lastWord: string } {
921
- const hits = this.getActiveMatches();
922
- return { hits, lastWord: this.inputBuffer };
923
- }
924
-
925
- public setCost(
926
- cost: number,
927
- inputTokens = 0,
928
- cacheReadTokens = 0,
929
- outputTokens = 0,
930
- ) {
931
- this.sessionCost = cost;
932
- this.totalInputTokens = inputTokens;
933
- this.totalCacheReadTokens = cacheReadTokens;
934
- this.totalOutputTokens = outputTokens;
935
- this.render();
936
- }
937
-
938
- public handleThinkingDelta(text: string) {
939
- this.currentThinking += text;
940
- this.throttleRender();
941
- }
942
-
943
- public addLog(text: string) {
944
- if (!text || !text.trim()) return;
945
- const trimmed = text.trim();
946
- if (
947
- trimmed.includes("Summary:") ||
948
- trimmed.includes("Modified files:") ||
949
- trimmed.includes("Verification:") ||
950
- trimmed.includes("Session Cost:")
951
- ) {
952
- return;
953
- }
954
- if (text.includes("Orbit:")) {
955
- const cleanText = text.replace(/Orbit:\s*/i, "").trim();
956
- const last = this.history[this.history.length - 1];
957
- if (last && last.role === "assistant") {
958
- if (!last.text.includes(cleanText)) {
959
- last.text = cleanText;
960
- }
961
- this.render();
962
- }
963
- return;
964
- }
965
- if (text.includes("Thought")) {
966
- return;
967
- }
968
-
969
- this.history.push({
970
- role: "system",
971
- text: trimmed,
972
- });
973
- this.render();
974
- }
975
-
976
- public syncFromLoop(loop: any) {
977
- this.activeContextFiles = loop.getRelevantFiles() || [];
978
- const loopHistory = loop.getHistory();
979
- if (loopHistory.length === 0) {
980
- this.render();
981
- return;
982
- }
983
-
984
- const localAsstIdx = this.history
985
- .map((m, i) => (m.role === "assistant" ? i : -1))
986
- .filter((i) => i !== -1);
987
- const loopAsst = loopHistory.filter((m: any) => m.role === "assistant");
988
-
989
- for (let i = 0; i < loopAsst.length; i++) {
990
- const loopMsg = loopAsst[i];
991
- const textBlock = loopMsg.content.find((b: any) => b.type === "text");
992
- if (textBlock && textBlock.text) {
993
- const localIdx = localAsstIdx[i];
994
- if (localIdx !== undefined) {
995
- this.history[localIdx].text = textBlock.text;
996
- } else {
997
- this.history.push({
998
- role: "assistant",
999
- text: textBlock.text,
1000
- attempt: i + 1,
1001
- });
1002
- }
1003
- }
1004
- }
1005
- this.render();
1006
- }
1007
-
1008
- public loadHistory(loopHistory: any[]) {
1009
- this.history = [];
1010
- this.historyScrollOffset = 0;
1011
- this.hasNewOutputWhileScrolled = false;
1012
- let attempt = 0;
1013
- for (const msg of loopHistory) {
1014
- if (msg.role === "user") {
1015
- const text = msg.content
1016
- .map((c: any) => (c.type === "text" ? c.text : ""))
1017
- .join("");
1018
- if (text === "REPL Interactive Shell Started") {
1019
- continue;
1020
- }
1021
- this.history.push({
1022
- role: "user",
1023
- text,
1024
- });
1025
- } else if (msg.role === "assistant") {
1026
- attempt++;
1027
- const textBlock = msg.content.find((b: any) => b.type === "text");
1028
- this.history.push({
1029
- role: "assistant",
1030
- text: textBlock?.text || "",
1031
- attempt,
1032
- });
1033
- } else if (msg.role === "system") {
1034
- const text = msg.content
1035
- .map((c: any) => (c.type === "text" ? c.text : ""))
1036
- .join("");
1037
- this.history.push({
1038
- role: "system",
1039
- text,
1040
- });
1041
- }
1042
- }
1043
- this.render();
1044
- }
1045
-
1046
- public async askInput(): Promise<string | null> {
1047
- if (!this.isActive) {
1048
- if (this.hasWrittenStdoutSinceStop) {
1049
- const wasRaw = !!process.stdin.isRaw;
1050
- if (process.stdin.setRawMode) {
1051
- process.stdin.setRawMode(false);
1052
- }
1053
- await Prompt.askText("Press Enter to return to Orbit...");
1054
- if (process.stdin.setRawMode) {
1055
- process.stdin.setRawMode(wasRaw);
1056
- }
1057
- this.hasWrittenStdoutSinceStop = false;
1058
- }
1059
- this.start(this.budgetLimit);
1060
- }
1061
- process.stdout.write("\x1b[?25h");
1062
-
1063
- return new Promise((resolve) => {
1064
- this.resolveInput = resolve;
1065
- this.inputBuffer = "";
1066
- this.cursorPosition = 0;
1067
- this.hideAutocomplete = false;
1068
- this.render();
1069
-
1070
- const wasRaw = !!process.stdin.isRaw;
1071
- if (process.stdin.setRawMode) {
1072
- process.stdin.setRawMode(true);
1073
- }
1074
- process.stdin.resume();
1075
-
1076
- const onKeypress = (str: string, key: any) => {
1077
- try {
1078
- if (!this.isActive) {
1079
- cleanup();
1080
- return;
1081
- }
1082
-
1083
- if (this.handleScrollInput(str, key)) {
1084
- return;
1085
- }
1086
-
1087
- if (key && key.ctrl && key.name === "c") {
1088
- this.activeCommandIndex = 0;
1089
- if (this.inputBuffer.length > 0) {
1090
- this.inputBuffer = "";
1091
- this.cursorPosition = 0;
1092
- this.render();
1093
- } else {
1094
- if (this.ctrlCPressedOnce) {
1095
- if (this.ctrlCTimeout) clearTimeout(this.ctrlCTimeout);
1096
- cleanup();
1097
- this.stop();
1098
- process.exit(0);
1099
- } else {
1100
- this.ctrlCPressedOnce = true;
1101
- if (this.ctrlCTimeout) clearTimeout(this.ctrlCTimeout);
1102
- this.ctrlCTimeout = setTimeout(() => {
1103
- this.ctrlCPressedOnce = false;
1104
- this.render();
1105
- }, 2000);
1106
- this.render();
1107
- }
1108
- }
1109
- return;
1110
- }
1111
-
1112
- if (key && (key.name === "return" || key.name === "enter")) {
1113
- cleanup();
1114
- process.stdout.write("\x1b[?25l");
1115
- let submitted = this.inputBuffer;
1116
- if (this.inputBuffer.startsWith("/")) {
1117
- const matches = this.getActiveMatches();
1118
- if (matches.length > 0) {
1119
- const idx = Math.min(
1120
- this.activeCommandIndex,
1121
- matches.length - 1,
1122
- );
1123
- const match = matches[idx];
1124
- if (match) {
1125
- submitted = match;
1126
- }
1127
- }
1128
- }
1129
- this.resolveInput = null;
1130
- this.historyScrollOffset = 0;
1131
- this.hasNewOutputWhileScrolled = false;
1132
-
1133
- if (submitted.trim()) {
1134
- this.history.push({ role: "user", text: submitted });
1135
- if (
1136
- this.inputHistory[this.inputHistory.length - 1] !== submitted
1137
- ) {
1138
- this.inputHistory.push(submitted);
1139
- this.saveInputHistory();
1140
- }
1141
- }
1142
- this.historyIndex = -1;
1143
- this.inputBuffer = "";
1144
- this.cursorPosition = 0;
1145
- this.render();
1146
- resolve(submitted);
1147
- return;
1148
- }
1149
-
1150
- if (key && (key.name === "home" || (key.ctrl && key.name === "a"))) {
1151
- this.activeCommandIndex = 0;
1152
- this.cursorPosition = 0;
1153
- this.render();
1154
- return;
1155
- }
1156
-
1157
- if (key && (key.name === "end" || (key.ctrl && key.name === "e"))) {
1158
- this.activeCommandIndex = 0;
1159
- this.cursorPosition = this.inputBuffer.length;
1160
- this.render();
1161
- return;
1162
- }
1163
-
1164
- if (key && (key.ctrl || key.meta) && key.name === "left") {
1165
- this.activeCommandIndex = 0;
1166
- this.cursorPosition = previousWordIndex(
1167
- this.inputBuffer,
1168
- this.cursorPosition,
1169
- );
1170
- this.render();
1171
- return;
1172
- }
1173
-
1174
- if (key && (key.ctrl || key.meta) && key.name === "right") {
1175
- this.activeCommandIndex = 0;
1176
- this.cursorPosition = nextWordIndex(
1177
- this.inputBuffer,
1178
- this.cursorPosition,
1179
- );
1180
- this.render();
1181
- return;
1182
- }
1183
-
1184
- if (key && key.ctrl && (key.name === "backspace" || key.name === "w")) {
1185
- this.activeCommandIndex = 0;
1186
- this.hideAutocomplete = false;
1187
- if (this.cursorPosition > 0) {
1188
- const targetPos = previousWordIndex(
1189
- this.inputBuffer,
1190
- this.cursorPosition,
1191
- );
1192
- this.inputBuffer =
1193
- this.inputBuffer.slice(0, targetPos) +
1194
- this.inputBuffer.slice(this.cursorPosition);
1195
- this.cursorPosition = targetPos;
1196
- this.render();
1197
- }
1198
- return;
1199
- }
1200
-
1201
- if (key && key.ctrl && key.name === "delete") {
1202
- this.activeCommandIndex = 0;
1203
- this.hideAutocomplete = false;
1204
- if (this.cursorPosition < this.inputBuffer.length) {
1205
- const targetPos = nextWordIndex(
1206
- this.inputBuffer,
1207
- this.cursorPosition,
1208
- );
1209
- this.inputBuffer =
1210
- this.inputBuffer.slice(0, this.cursorPosition) +
1211
- this.inputBuffer.slice(targetPos);
1212
- this.render();
1213
- }
1214
- return;
1215
- }
1216
-
1217
- if (key && key.ctrl && key.name === "u") {
1218
- this.activeCommandIndex = 0;
1219
- this.inputBuffer = "";
1220
- this.cursorPosition = 0;
1221
- this.render();
1222
- return;
1223
- }
1224
-
1225
- if (key && key.name === "up") {
1226
- if (this.inputBuffer.startsWith("/")) {
1227
- const matches = this.getActiveMatches();
1228
- if (matches.length > 0) {
1229
- this.activeCommandIndex =
1230
- (this.activeCommandIndex - 1 + matches.length) %
1231
- matches.length;
1232
- this.render();
1233
- return;
1234
- }
1235
- }
1236
- if (this.inputHistory.length > 0) {
1237
- if (this.historyIndex === -1) {
1238
- this.tempBuffer = this.inputBuffer;
1239
- this.historyIndex = this.inputHistory.length - 1;
1240
- } else if (this.historyIndex > 0) {
1241
- this.historyIndex--;
1242
- }
1243
- this.inputBuffer = this.inputHistory[this.historyIndex];
1244
- this.cursorPosition = this.inputBuffer.length;
1245
- this.render();
1246
- }
1247
- return;
1248
- }
1249
-
1250
- if (key && key.name === "down") {
1251
- if (this.inputBuffer.startsWith("/")) {
1252
- const matches = this.getActiveMatches();
1253
- if (matches.length > 0) {
1254
- this.activeCommandIndex =
1255
- (this.activeCommandIndex + 1) % matches.length;
1256
- this.render();
1257
- return;
1258
- }
1259
- }
1260
- if (this.historyIndex !== -1) {
1261
- if (this.historyIndex < this.inputHistory.length - 1) {
1262
- this.historyIndex++;
1263
- this.inputBuffer = this.inputHistory[this.historyIndex];
1264
- } else {
1265
- this.historyIndex = -1;
1266
- this.inputBuffer = this.tempBuffer || "";
1267
- }
1268
- this.cursorPosition = this.inputBuffer.length;
1269
- this.render();
1270
- }
1271
- return;
1272
- }
1273
-
1274
- if (key && key.name === "left") {
1275
- if (this.cursorPosition > 0) {
1276
- this.cursorPosition = previousCodePointIndex(
1277
- this.inputBuffer,
1278
- this.cursorPosition,
1279
- );
1280
- this.render();
1281
- }
1282
- return;
1283
- }
1284
-
1285
- if (key && key.name === "right") {
1286
- if (this.cursorPosition < this.inputBuffer.length) {
1287
- this.cursorPosition = nextCodePointIndex(
1288
- this.inputBuffer,
1289
- this.cursorPosition,
1290
- );
1291
- this.render();
1292
- } else {
1293
- const sug = this.getSuggestion();
1294
- if (sug) {
1295
- this.inputBuffer += sug;
1296
- this.cursorPosition = this.inputBuffer.length;
1297
- this.render();
1298
- }
1299
- }
1300
- return;
1301
- }
1302
-
1303
- if (key && key.name === "tab") {
1304
- if (this.inputBuffer.startsWith("/")) {
1305
- const matches = this.getActiveMatches();
1306
- if (matches.length > 0) {
1307
- const idx = Math.min(
1308
- this.activeCommandIndex,
1309
- matches.length - 1,
1310
- );
1311
- const match = matches[idx];
1312
- if (match) {
1313
- this.inputBuffer = match;
1314
- this.cursorPosition = match.length;
1315
- this.activeCommandIndex = 0;
1316
- this.render();
1317
- }
1318
- return;
1319
- }
1320
- }
1321
- const sug = this.getSuggestion();
1322
- if (sug) {
1323
- this.inputBuffer += sug;
1324
- this.cursorPosition = this.inputBuffer.length;
1325
- this.render();
1326
- }
1327
- return;
1328
- }
1329
-
1330
- if (key && key.ctrl && key.name === "l") {
1331
- this.history = [];
1332
- this.render();
1333
- return;
1334
- }
1335
-
1336
- if (key && key.ctrl && key.name === "p") {
1337
- this.activeCommandIndex = 0;
1338
- if (!this.inputBuffer.startsWith("/")) {
1339
- this.inputBuffer = "/" + this.inputBuffer;
1340
- this.cursorPosition = this.inputBuffer.length;
1341
- }
1342
- this.render();
1343
- return;
1344
- }
1345
-
1346
- if (key && key.name === "delete") {
1347
- this.activeCommandIndex = 0;
1348
- this.hideAutocomplete = false;
1349
- if (this.cursorPosition < this.inputBuffer.length) {
1350
- const nextIndex = nextCodePointIndex(
1351
- this.inputBuffer,
1352
- this.cursorPosition,
1353
- );
1354
- this.inputBuffer =
1355
- this.inputBuffer.substring(0, this.cursorPosition) +
1356
- this.inputBuffer.substring(nextIndex);
1357
- this.render();
1358
- }
1359
- return;
1360
- }
1361
-
1362
- if (key && key.name === "backspace") {
1363
- this.activeCommandIndex = 0;
1364
- this.hideAutocomplete = false;
1365
- if (this.cursorPosition > 0) {
1366
- const previousIndex = previousCodePointIndex(
1367
- this.inputBuffer,
1368
- this.cursorPosition,
1369
- );
1370
- this.inputBuffer =
1371
- this.inputBuffer.substring(0, previousIndex) +
1372
- this.inputBuffer.substring(this.cursorPosition);
1373
- this.cursorPosition = previousIndex;
1374
- }
1375
- } else if (key && key.name === "escape") {
1376
- this.activeCommandIndex = 0;
1377
- this.hideAutocomplete = true;
1378
- } else if (
1379
- str &&
1380
- !/[\u0000-\u001f\u007f]/.test(str) &&
1381
- (!key || (!key.ctrl && !key.meta && key.name !== "tab"))
1382
- ) {
1383
- this.activeCommandIndex = 0;
1384
- this.hideAutocomplete = false;
1385
- this.inputBuffer =
1386
- this.inputBuffer.substring(0, this.cursorPosition) +
1387
- str +
1388
- this.inputBuffer.substring(this.cursorPosition);
1389
- this.cursorPosition += str.length;
1390
- }
1391
-
1392
- this.render();
1393
- } catch (error) {
1394
- const logDir = join(homedir(), ".orbit");
1395
- try {
1396
- if (!existsSync(logDir)) {
1397
- mkdirSync(logDir, { recursive: true });
1398
- }
1399
- writeFileSync(
1400
- join(logDir, "tui_error.log"),
1401
- `[${new Date().toISOString()}] Error in onKeypress: ${error instanceof Error ? error.stack : error}\n`,
1402
- { flag: "a" },
1403
- );
1404
- } catch {}
1405
- try {
1406
- this.render();
1407
- } catch {}
1408
- }
1409
- };
1410
-
1411
- const cleanup = () => {
1412
- process.stdin.removeListener("keypress", onKeypress);
1413
- if (process.stdin.setRawMode) {
1414
- process.stdin.setRawMode(wasRaw);
1415
- }
1416
- process.stdin.pause();
1417
- };
1418
-
1419
- process.stdin.on("keypress", onKeypress);
1420
- });
1421
- }
1422
-
1423
- public startAttempt(attempt: number) {
1424
- this.currentAttempt = attempt;
1425
- this.attemptStartTime = Date.now();
1426
- this.firstDeltaTime = 0;
1427
- this.isThinking = true;
1428
- this.thoughtElapsed = 0;
1429
- this.currentThinking = "";
1430
-
1431
- this.history.push({
1432
- role: "assistant",
1433
- text: "",
1434
- attempt: attempt,
1435
- });
1436
-
1437
- if (this.thoughtTimer) clearInterval(this.thoughtTimer);
1438
- this.thoughtTimer = setInterval(() => {
1439
- if (this.isThinking) {
1440
- this.thoughtElapsed += 100;
1441
- this.render();
1442
- }
1443
- }, 100);
1444
-
1445
- this.render();
1446
- }
1447
-
1448
- public handleModelDelta(text: string) {
1449
- const lastAsst = [...this.history]
1450
- .reverse()
1451
- .find((m) => m.role === "assistant");
1452
- if (lastAsst) {
1453
- if (this.isThinking && text.trim().length > 0) {
1454
- this.isThinking = false;
1455
- if (this.thoughtTimer) {
1456
- clearInterval(this.thoughtTimer);
1457
- this.thoughtTimer = null;
1458
- }
1459
- lastAsst.thoughtTime = Date.now() - this.attemptStartTime;
1460
- }
1461
- lastAsst.text += text;
1462
- this.throttleRender();
1463
- }
1464
- }
1465
-
1466
- private throttleRender() {
1467
- const now = Date.now();
1468
- const minInterval = 60;
1469
- if (now - this.lastRenderTime >= minInterval) {
1470
- if (this.renderTimeout) {
1471
- clearTimeout(this.renderTimeout);
1472
- this.renderTimeout = null;
1473
- }
1474
- this.lastRenderTime = now;
1475
- this.render();
1476
- } else if (!this.renderPending) {
1477
- this.renderPending = true;
1478
- this.renderTimeout = setTimeout(
1479
- () => {
1480
- this.renderPending = false;
1481
- this.lastRenderTime = Date.now();
1482
- this.render();
1483
- },
1484
- minInterval - (now - this.lastRenderTime),
1485
- );
1486
- }
1487
- }
1488
-
1489
- public finishAttempt() {
1490
- const lastAsst = [...this.history]
1491
- .reverse()
1492
- .find((m) => m.role === "assistant");
1493
- if (lastAsst) {
1494
- this.isThinking = false;
1495
- if (this.thoughtTimer) {
1496
- clearInterval(this.thoughtTimer);
1497
- this.thoughtTimer = null;
1498
- }
1499
- lastAsst.totalTime = Date.now() - this.attemptStartTime;
1500
- if (lastAsst.thoughtTime === undefined) {
1501
- lastAsst.thoughtTime = lastAsst.totalTime;
1502
- }
1503
- this.render();
1504
- }
1505
- }
1506
-
1507
- public render(forceFull = false) {
1508
- const columns = Math.max(40, process.stdout.columns || 80);
1509
- const rows = Math.max(10, process.stdout.rows || 24);
1510
-
1511
- const morandi = {
1512
- user: (s: string) => `\x1b[38;2;142;163;175m${s}\x1b[0m`,
1513
- userBold: (s: string) => `\x1b[1;38;2;142;163;175m${s}\x1b[0m`,
1514
- asst: (s: string) => `\x1b[38;2;143;153;129m${s}\x1b[0m`,
1515
- asstBold: (s: string) => `\x1b[1;38;2;143;153;129m${s}\x1b[0m`,
1516
- cyan: (s: string) => `\x1b[38;2;142;163;175m${s}\x1b[0m`,
1517
- accent: (s: string) => `\x1b[38;2;200;170;120m${s}\x1b[0m`,
1518
- completed: (s: string) => `\x1b[38;2;135;165;130m${s}\x1b[0m`,
1519
- failed: (s: string) => `\x1b[38;2;180;120;120m${s}\x1b[0m`,
1520
- warn: (s: string) => `\x1b[38;2;180;140;130m${s}\x1b[0m`,
1521
- white: (s: string) => `\x1b[38;2;230;225;215m${s}\x1b[0m`,
1522
- whiteBold: (s: string) => `\x1b[1;38;2;230;225;215m${s}\x1b[0m`,
1523
- gray: (s: string) => `\x1b[38;2;150;150;150m${s}\x1b[0m`,
1524
- dim: (s: string) => `\x1b[2;38;2;110;110;110m${s}\x1b[0m`,
1525
- };
1526
-
1527
- const isWaitingInput = this.resolveInput !== null;
1528
- const isInputActive =
1529
- isWaitingInput || this.thinkingKeypressListener !== null;
1530
- const hasInput = isInputActive && this.inputBuffer.length > 0;
1531
- const placeholder = isWaitingInput ? "Ask anything..." : "";
1532
-
1533
-
1534
- // A.1 构建底部的圆角输入框与状态行以及指令匹配浮窗
1535
- const boxWidth = columns - 4;
1536
- const wrapWidth = Math.max(8, boxWidth - 14);
1537
- const fullText = hasInput ? this.inputBuffer : placeholder;
1538
-
1539
- const wrappedLines = this.wrapText(fullText, wrapWidth);
1540
- const formattedLines = hasInput
1541
- ? this.formatWrappedLines(wrappedLines, this.inputBuffer.length)
1542
- : wrappedLines.map((line) => morandi.dim(line));
1543
-
1544
- const boxContentLines: string[] = [];
1545
- const topBorder = morandi.gray(" ╭" + "─".repeat(boxWidth - 4) + "╮");
1546
- const bottomBorder = morandi.gray(" ╰" + "─".repeat(boxWidth - 4) + "╯");
1547
-
1548
- boxContentLines.push(topBorder);
1549
- for (let i = 0; i < formattedLines.length; i++) {
1550
- const prefix = i === 0 ? "orbit > " : " ";
1551
- const rawLine = wrappedLines[i];
1552
- const visualWidth = this.getStringWidth(rawLine);
1553
- const remainingSpaces = wrapWidth - visualWidth;
1554
- const padding = " ".repeat(Math.max(0, remainingSpaces));
1555
-
1556
- const lineContent =
1557
- morandi.gray(" │ ") +
1558
- morandi.userBold(prefix) +
1559
- formattedLines[i] +
1560
- padding +
1561
- morandi.gray(" │");
1562
- boxContentLines.push(lineContent);
1563
- }
1564
- boxContentLines.push(bottomBorder);
1565
-
1566
- const bottomLines: string[] = [];
1567
-
1568
- // A.2 只有以 / 开头且正在等待输入时,渲染指令下拉浮窗
1569
- if (isWaitingInput) {
1570
- const matches = this.getActiveMatches();
1571
-
1572
- if (matches.length > 0) {
1573
- const isZh = this.config?.language === "zh";
1574
- const cmdHints: Record<string, string> = isZh
1575
- ? {
1576
- "/help": "查看系统命令的详细帮助与指南",
1577
- "/status": "实时诊断当前会话的健康与资源状态",
1578
- "/config": "查看与修改本地/全局的运行配置参数",
1579
- "/model": "动态切换正在使用的 AI 语言大模型",
1580
- "/chat": "会话管理器 (支持子命令: list, new, delete, switch)",
1581
- "/chat list": "展示所有已保存的历史对话会话",
1582
- "/chat ls": "展示所有已保存的历史对话会话",
1583
- "/chat new": "启动并创建一个全新的对话会话",
1584
- "/chat delete": "移除不需要的历史对话会话",
1585
- "/chat rm": "移除不需要的历史对话会话",
1586
- "/chat switch": "快速切换到指定的历史对话会话",
1587
- "/commit": "自动暂存工作区修改并生成 Git 提交",
1588
- "/exit": "安全终止并关闭当前的终端会话",
1589
- "/quit": "安全终止并关闭当前的终端会话",
1590
- "/rollback": "一键撤销并回滚自会话启动以来的所有修改",
1591
- "/clear": "清空当前终端屏幕的所有历史会话渲染",
1592
- "/add": "将选定的文件或代码资产添加到当前上下文",
1593
- "/drop": "从当前对话上下文中移除选定的资产",
1594
- "/mode": "动态切换系统安全确认模式 (strict, normal, auto, plan)",
1595
- "/copy": "拷贝 AI 的上一条回复到系统剪贴板",
1596
- }
1597
- : {
1598
- "/help": "Display detailed help and commands reference",
1599
- "/status": "Diagnose session health, token usage, and limits",
1600
- "/config": "View and edit local or global configuration",
1601
- "/model": "Switch the active language model dynamically",
1602
- "/chat":
1603
- "Manage chat sessions (subcommands: list, new, delete, switch)",
1604
- "/chat list": "List all saved agent chat sessions",
1605
- "/chat ls": "List all saved agent chat sessions",
1606
- "/chat new": "Initialize and start a fresh chat session",
1607
- "/chat delete": "Remove a saved session from the manager",
1608
- "/chat rm": "Remove a saved session from the manager",
1609
- "/chat switch": "Switch focus to a specific saved session",
1610
- "/commit": "Automatically stage changes and create Git commit",
1611
- "/exit": "Safely terminate and exit the active session",
1612
- "/quit": "Safely terminate and exit the active session",
1613
- "/rollback": "Revert all source edits made during this session",
1614
- "/clear": "Clear the terminal screen and scrollback buffer",
1615
- "/add": "Add files or code symbols to prompt context",
1616
- "/drop": "Remove selected assets from prompt context",
1617
- "/mode": "Switch permission mode (strict, normal, auto, plan)",
1618
- "/copy": "Copy last assistant response to clipboard",
1619
- };
1620
-
1621
- const maxVisible = 5;
1622
- this.activeCommandIndex = Math.min(
1623
- Math.max(0, this.activeCommandIndex),
1624
- matches.length - 1,
1625
- );
1626
-
1627
- let startIdx = 0;
1628
- if (this.activeCommandIndex >= maxVisible) {
1629
- startIdx = this.activeCommandIndex - maxVisible + 1;
1630
- }
1631
- const visibleMatches = matches.slice(startIdx, startIdx + maxVisible);
1632
-
1633
- const maxPopupWidth = Math.min(86, Math.max(30, columns - 8));
1634
- const formattedMatches = visibleMatches.map((cmd) => {
1635
- const isSelected =
1636
- visibleMatches.indexOf(cmd) + startIdx === this.activeCommandIndex;
1637
- const prefix = isSelected ? " ❯ " : " ";
1638
-
1639
- let hint = cmdHints[cmd] || "";
1640
- if (!hint) {
1641
- if (
1642
- cmd.startsWith("/chat delete ") ||
1643
- cmd.startsWith("/chat rm ")
1644
- ) {
1645
- hint = isZh ? "删除该会话" : "Delete this session";
1646
- } else if (cmd.startsWith("/chat switch ")) {
1647
- hint = isZh ? "切换到该会话" : "Switch to this session";
1648
- } else if (cmd.startsWith("/fork switch ")) {
1649
- hint = isZh
1650
- ? "切换到指定的会话分支"
1651
- : "Switch to specified session branch";
1652
- } else if (cmd === "/fork tree") {
1653
- hint = isZh
1654
- ? "展示所有会话分支的树状关系"
1655
- : "Display session branch lineage tree";
1656
- }
1657
- }
1658
-
1659
- // Ensure prefix + cmd + hint fits within maxPopupWidth.
1660
- // maxPopupWidth is at least 30. We keep at least 15 columns for leftPart.
1661
- const maxLeftW = Math.max(15, Math.floor(maxPopupWidth * 0.6));
1662
-
1663
- let leftPart = `${prefix}${cmd}`;
1664
- let leftW = this.getStringWidth(leftPart);
1665
- if (leftW > maxLeftW) {
1666
- leftPart = this.truncateToWidth(leftPart, maxLeftW - 3) + "...";
1667
- leftW = this.getStringWidth(leftPart);
1668
- }
1669
-
1670
- let rightPart = "";
1671
- let rightW = 0;
1672
- if (hint) {
1673
- const availableRightW = maxPopupWidth - leftW - 2 - 4;
1674
- if (availableRightW >= 5) {
1675
- const rawRightW = this.getStringWidth(hint);
1676
- if (rawRightW <= availableRightW) {
1677
- rightPart = hint;
1678
- rightW = rawRightW;
1679
- } else {
1680
- rightPart =
1681
- this.truncateToWidth(hint, availableRightW - 3) + "...";
1682
- rightW = this.getStringWidth(rightPart);
1683
- }
1684
- }
1685
- }
1686
-
1687
- return { cmd, isSelected, leftPart, leftW, rightPart, rightW };
1688
- });
1689
-
1690
- const popupWidth = maxPopupWidth;
1691
-
1692
- bottomLines.push(morandi.gray(" ╭" + "─".repeat(popupWidth) + "╮"));
1693
- for (const fm of formattedMatches) {
1694
- const spacingWidth = popupWidth - fm.leftW - fm.rightW - 4;
1695
- const spacing = " ".repeat(Math.max(1, spacingWidth));
1696
- const rightPadding = " ";
1697
-
1698
- const formattedLine = fm.isSelected
1699
- ? morandi.accent(fm.leftPart + spacing) + morandi.dim(fm.rightPart) + rightPadding
1700
- : morandi.gray(fm.leftPart + spacing) + morandi.dim(fm.rightPart) + rightPadding;
1701
-
1702
- bottomLines.push(
1703
- morandi.gray(" │") + formattedLine + morandi.gray("│"),
1704
- );
1705
- }
1706
- bottomLines.push(morandi.gray(" ╰" + "─".repeat(popupWidth) + "╯"));
1707
-
1708
- }
1709
- }
1710
-
1711
- // A.3 压入输入框
1712
- bottomLines.push(...boxContentLines);
1713
-
1714
- // A.4 构建底部状态行
1715
- const mode = this.permissionsMode.toUpperCase();
1716
-
1717
- let statusText = "";
1718
- if (this.historyScrollOffset > 0) {
1719
- const newOutput = this.hasNewOutputWhileScrolled
1720
- ? this.config?.language === "zh"
1721
- ? " · 有新输出"
1722
- : " · new output"
1723
- : "";
1724
- statusText =
1725
- morandi.accent(
1726
- this.config?.language === "zh"
1727
- ? `↑ 历史 ${this.historyScrollOffset} 行`
1728
- : `↑ history ${this.historyScrollOffset} lines`,
1729
- ) + morandi.warn(newOutput);
1730
- } else if (this.ctrlCPressedOnce) {
1731
- statusText = morandi.warn("Press Ctrl+C again to exit");
1732
- } else {
1733
- const cleanModel =
1734
- this.modelNameGetter().split("/").pop() || this.modelNameGetter();
1735
- const costStr = `$` + this.sessionCost.toFixed(4);
1736
- statusText =
1737
- morandi.completed("●") +
1738
- " " +
1739
- morandi.white(`${mode} MODE`) +
1740
- morandi.gray(" · ") +
1741
- morandi.accent(cleanModel) +
1742
- morandi.gray(" · ") +
1743
- morandi.accent(costStr) +
1744
- morandi.gray(" · ") +
1745
- morandi.dim(`attempt: ${this.currentAttempt || 1}`);
1746
- }
1747
-
1748
- let keybindings =
1749
- this.historyScrollOffset > 0
1750
- ? morandi.gray("[End]") +
1751
- morandi.dim(this.config?.language === "zh" ? " 返回底部" : " Bottom")
1752
- : columns >= 88
1753
- ? [
1754
- morandi.gray("[^C]") + morandi.dim(" Cancel"),
1755
- morandi.gray("[^L]") + morandi.dim(" Clear"),
1756
- morandi.gray("[^P]") + morandi.dim(" Cmds"),
1757
- ].join(" ")
1758
- : columns >= 62
1759
- ? [
1760
- morandi.gray("[^C]") + morandi.dim(" Cancel"),
1761
- morandi.gray("[^P]") + morandi.dim(" Cmds"),
1762
- ].join(" ")
1763
- : morandi.gray("[^C]") + morandi.dim(" Exit");
1764
-
1765
- let statusTextLength = this.getStringWidth(statusText);
1766
- let keybindingsLength = this.getStringWidth(keybindings);
1767
- if (statusTextLength + keybindingsLength > columns - 8) {
1768
- const compactMode = `${mode.slice(0, 6)} · ${this.currentAttempt || 1}`;
1769
- statusText = morandi.completed("●") + " " + morandi.white(compactMode);
1770
- statusTextLength = this.getStringWidth(statusText);
1771
- }
1772
- if (statusTextLength + keybindingsLength > columns - 8) {
1773
- keybindings = morandi.gray("[^C]");
1774
- keybindingsLength = this.getStringWidth(keybindings);
1775
- }
1776
- const spacing = Math.max(
1777
- 1,
1778
- columns - 6 - statusTextLength - keybindingsLength,
1779
- );
1780
-
1781
- bottomLines.push(" " + statusText + " ".repeat(spacing) + keybindings);
1782
-
1783
- const bottomHeight = bottomLines.length;
1784
-
1785
- // 全屏渲染逻辑(当无法增量时)
1786
- const cleanModel = this.modelNameGetter().replace(/\[1m\]/g, "");
1787
-
1788
- // 1. 获取 Git 当前分支与状态(短时缓存,避免流式输出期间阻塞重绘)
1789
- const gitSummary = this.getGitSummary();
1790
- const gitBranch = gitSummary.branch;
1791
-
1792
- // 2. 渲染左上角像素行星 Logo 及其右侧信息
1793
- const logoLines = [
1794
- `\x1b[38;2;142;163;175m /\\___/\\ \x1b[0m`,
1795
- `\x1b[38;2;142;163;175m ( o.o ) \x1b[0m`,
1796
- `\x1b[38;2;142;163;175m / >\x1b[38;2;230;110;110m♥\x1b[38;2;142;163;175m< \\ \x1b[0m`,
1797
- `\x1b[38;2;142;163;175m (__/ \\__) \x1b[0m`,
1798
- ];
1799
-
1800
- const w0 = this.getStringWidth(logoLines[0]);
1801
- const w1 = this.getStringWidth(logoLines[1]);
1802
- const w2 = this.getStringWidth(logoLines[2]);
1803
- const w3 = this.getStringWidth(logoLines[3]);
1804
- const maxLogoW = Math.max(w0, w1, w2, w3);
1805
-
1806
- const pad0 = " ".repeat(maxLogoW - w0);
1807
- const pad1 = " ".repeat(maxLogoW - w1);
1808
- const pad2 = " ".repeat(maxLogoW - w2);
1809
- const pad3 = " ".repeat(maxLogoW - w3);
1810
-
1811
- const shortCwd = this.cwd.replace(/\\/g, "/");
1812
-
1813
- // Safety check to prevent left/right overflow of the header
1814
- const availableWidth = Math.max(10, columns - 2 - maxLogoW - 2 - 20 - 2);
1815
-
1816
- let branchText = "";
1817
- if (gitBranch !== "no-git") {
1818
- const stats: string[] = [];
1819
- if (gitSummary.added > 0) stats.push(`+${gitSummary.added}`);
1820
- if (gitSummary.modified > 0) stats.push(`~${gitSummary.modified}`);
1821
- if (gitSummary.deleted > 0) stats.push(`-${gitSummary.deleted}`);
1822
- const gitStatusStats = stats.length > 0 ? ` (${stats.join(" ")})` : "";
1823
- const maxBranchLen = 12;
1824
- const displayBranch =
1825
- gitBranch.length > maxBranchLen
1826
- ? gitBranch.substring(0, maxBranchLen - 3) + "..."
1827
- : gitBranch;
1828
- branchText = ` ${morandi.dim("·")} ${morandi.dim("⎇")} ${morandi.asst(displayBranch)}${gitStatusStats ? " " + morandi.accent(gitStatusStats) : ""}`;
1829
- }
1830
-
1831
- // Helper to truncate path from middle/beginning to make it fit maxPathWidth
1832
- const truncatePath = (p: string, maxLength: number): string => {
1833
- if (p.length <= maxLength) return p;
1834
- const parts = p.split("/");
1835
- if (parts.length <= 1) {
1836
- return p.substring(p.length - maxLength);
1837
- }
1838
- const lastPart = parts[parts.length - 1];
1839
- if (lastPart.length + 4 > maxLength) {
1840
- return "..." + lastPart.substring(lastPart.length - (maxLength - 3));
1841
- }
1842
- let result = lastPart;
1843
- for (let i = parts.length - 2; i >= 0; i--) {
1844
- const nextResult = parts[i] + "/" + result;
1845
- if (nextResult.length + 4 > maxLength) {
1846
- return ".../" + result;
1847
- }
1848
- result = nextResult;
1849
- }
1850
- return result;
1851
- };
1852
-
1853
- const pathLabel = "workspace: ";
1854
- const branchWidth =
1855
- gitBranch !== "no-git" ? 5 + Math.min(12, gitBranch.length) : 0;
1856
- const maxPathWidth = Math.max(
1857
- 6,
1858
- availableWidth - pathLabel.length - branchWidth,
1859
- );
1860
- const displayPath = truncatePath(shortCwd, maxPathWidth);
1861
-
1862
- const hitRate =
1863
- this.totalInputTokens > 0
1864
- ? (this.totalCacheReadTokens / this.totalInputTokens) * 100
1865
- : 0;
1866
- let cacheText = `[cache] hit: ${hitRate.toFixed(0)}% (${(this.totalCacheReadTokens / 1000).toFixed(0)}k/${(this.totalInputTokens / 1000).toFixed(0)}k tokens)`;
1867
- if (this.getStringWidth(cacheText) > availableWidth) {
1868
- cacheText = `[cache] hit: ${hitRate.toFixed(0)}% (${(this.totalCacheReadTokens / 1000).toFixed(0)}k/${(this.totalInputTokens / 1000).toFixed(0)}k)`;
1869
- }
1870
- if (this.getStringWidth(cacheText) > availableWidth) {
1871
- cacheText = `[cache] hit: ${hitRate.toFixed(0)}%`;
1872
- }
1873
-
1874
- const cleanHeaderModel = cleanModel.split("/").pop() || cleanModel;
1875
- let headerLines: string[];
1876
- if (columns < 76) {
1877
- const modelWidth = Math.max(8, columns - 16);
1878
- const displayModel =
1879
- this.getStringWidth(cleanHeaderModel) > modelWidth
1880
- ? this.truncateToWidth(cleanHeaderModel, modelWidth - 3) + "..."
1881
- : cleanHeaderModel;
1882
- const compactPath = truncatePath(shortCwd, Math.max(8, columns - 15));
1883
- const compactBranch =
1884
- gitBranch === "no-git"
1885
- ? ""
1886
- : ` · ${gitBranch.length > 12 ? gitBranch.slice(0, 9) + "..." : gitBranch}`;
1887
- headerLines = [
1888
- ` ${morandi.whiteBold("O R B I T")} ${morandi.dim("·")} ${morandi.accent(displayModel)}`,
1889
- ` ${morandi.dim("workspace:")} ${morandi.gray(compactPath)}`,
1890
- ` ${morandi.dim(cacheText)}${morandi.dim(compactBranch)}`,
1891
- ];
1892
- } else {
1893
- const headerLine1 = ` ${logoLines[0]}${pad0} ${morandi.whiteBold("O R B I T")} ${morandi.dim("·")} ${morandi.accent(cleanHeaderModel)}`;
1894
- const headerLine2 = ` ${logoLines[1]}${pad1} ${" ".repeat(20)}${morandi.dim("workspace:")} ${morandi.gray(displayPath)}${branchText}`;
1895
- const headerLine3 = ` ${logoLines[2]}${pad2} ${" ".repeat(20)}${morandi.dim(cacheText)}`;
1896
- const headerLine4 = ` ${logoLines[3]}${pad3}`;
1897
- headerLines = [headerLine1, headerLine2, headerLine3, headerLine4];
1898
- }
1899
-
1900
- // 3. 构建历史对话内容
1901
- const renderedLines: string[] = [];
1902
-
1903
- interface TuiTurn {
1904
- user: any;
1905
- assistant?: any;
1906
- system: any[];
1907
- }
1908
-
1909
- const turns: TuiTurn[] = [];
1910
- let currentTurn: TuiTurn | null = null;
1911
-
1912
- for (const msg of this.history) {
1913
- if (msg.role === "user") {
1914
- if (currentTurn) {
1915
- turns.push(currentTurn);
1916
- }
1917
- currentTurn = { user: msg, system: [] };
1918
- } else if (msg.role === "assistant") {
1919
- if (currentTurn) {
1920
- currentTurn.assistant = msg;
1921
- }
1922
- } else if (msg.role === "system") {
1923
- if (currentTurn) {
1924
- currentTurn.system.push(msg);
1925
- }
1926
- }
1927
- }
1928
- if (currentTurn) {
1929
- turns.push(currentTurn);
1930
- }
1931
-
1932
- const lastAsst = [...this.history]
1933
- .reverse()
1934
- .find((m) => m.role === "assistant");
1935
- const uBorder = " ";
1936
- const aBorder = " ";
1937
-
1938
- for (const turn of turns) {
1939
- // Render User Turn
1940
- renderedLines.push(" " + morandi.userBold("👤 User"));
1941
- renderedLines.push(uBorder);
1942
-
1943
- const userLines = turn.user.text.split("\n");
1944
- const wrappedUserLines: string[] = [];
1945
- for (const line of userLines) {
1946
- wrappedUserLines.push(...this.wrapLine(line, columns - 10));
1947
- }
1948
- for (const line of wrappedUserLines) {
1949
- renderedLines.push(uBorder + morandi.user(line));
1950
- }
1951
- renderedLines.push(uBorder);
1952
- renderedLines.push(""); // spacing
1953
-
1954
- // Render Assistant Turn
1955
- if (turn.assistant) {
1956
- const asstLines: string[] = [];
1957
- const systemLines: string[] = [];
1958
-
1959
- for (const sys of turn.system) {
1960
- let text = sys.text.trim();
1961
- if (
1962
- text.startsWith("✓ Success") ||
1963
- text.startsWith("✖ Failed") ||
1964
- text.startsWith("✔ Success")
1965
- ) {
1966
- continue;
1967
- }
1968
- if (text.startsWith("✔")) {
1969
- text =
1970
- morandi.completed("completed") + morandi.gray(text.substring(1));
1971
- } else if (text.startsWith("✖")) {
1972
- text = morandi.failed("failed") + morandi.gray(text.substring(1));
1973
- } else if (text.startsWith("●")) {
1974
- text = morandi.cyan("●") + morandi.gray(text.substring(1));
1975
- } else if (text.startsWith("✦")) {
1976
- text = morandi.cyan("✦") + morandi.gray(text.substring(1));
1977
- } else if (text.startsWith("⚠")) {
1978
- text = morandi.warn("⚠") + morandi.gray(text.substring(1));
1979
- } else {
1980
- text = morandi.cyan("✦") + " " + morandi.gray(text);
1981
- }
1982
- systemLines.push(text);
1983
- }
1984
-
1985
- const isThinkingNow = turn.assistant === lastAsst && this.isThinking;
1986
- const thoughtTimeVal = isThinkingNow
1987
- ? this.thoughtElapsed
1988
- : turn.assistant.thoughtTime;
1989
-
1990
- if (thoughtTimeVal !== undefined) {
1991
- const timeStr =
1992
- thoughtTimeVal >= 1000
1993
- ? `${(thoughtTimeVal / 1000).toFixed(1)}s`
1994
- : `${thoughtTimeVal}ms`;
1995
-
1996
- const breatheDots = [
1997
- "\x1b[38;2;142;163;175m·\x1b[0m",
1998
- "\x1b[38;2;143;153;129m•\x1b[0m",
1999
- "\x1b[38;2;200;170;120m●\x1b[0m",
2000
- "\x1b[38;2;135;165;130m•\x1b[0m",
2001
- ];
2002
- const spinIdx = Math.floor(Date.now() / 250) % 4;
2003
- const dotChar = isThinkingNow
2004
- ? breatheDots[spinIdx]
2005
- : morandi.gray("•");
2006
-
2007
- if (isThinkingNow) {
2008
- asstLines.push(
2009
- `${dotChar} ` + morandi.accent(`Thinking... ${timeStr}`),
2010
- );
2011
- if (this.currentThinking) {
2012
- const lines = this.currentThinking.split("\n").filter(Boolean);
2013
- const lastLines = lines.slice(-4);
2014
- const maxL = columns - 14;
2015
- for (const line of lastLines) {
2016
- const trimmed = line.trim();
2017
- let displayText = trimmed;
2018
- const displayW = this.getStringWidth(displayText);
2019
- if (displayW > maxL) {
2020
- displayText =
2021
- this.truncateToWidth(displayText, maxL - 3) + "...";
2022
- }
2023
- asstLines.push(
2024
- " " + morandi.gray("· ") + morandi.dim(displayText),
2025
- );
2026
- }
2027
- }
2028
- } else {
2029
- asstLines.push(
2030
- morandi.gray("🧠 ") + morandi.dim(`Thought for ${timeStr}`),
2031
- );
2032
- }
2033
- }
2034
-
2035
- if (systemLines.length > 0) {
2036
- asstLines.push(...systemLines);
2037
- }
2038
-
2039
- if (turn.assistant.text) {
2040
- if (asstLines.length > 0) {
2041
- asstLines.push("");
2042
- }
2043
-
2044
- const asstObj = turn.assistant as any;
2045
- const isStreaming = this.resolveInput === null;
2046
- const nowTime = Date.now();
2047
- const timeSinceLastRender =
2048
- nowTime - (asstObj._lastMarkdownRenderTime || 0);
2049
-
2050
- if (
2051
- !asstObj._formattedCached ||
2052
- asstObj._textCached !== turn.assistant.text
2053
- ) {
2054
- if (
2055
- !isStreaming ||
2056
- timeSinceLastRender >= 150 ||
2057
- !asstObj._formattedCached
2058
- ) {
2059
- asstObj._formattedCached = Renderer.formatMarkdown(
2060
- turn.assistant.text,
2061
- ).split("\n");
2062
- asstObj._textCached = turn.assistant.text;
2063
- asstObj._lastMarkdownRenderTime = nowTime;
2064
- }
2065
- }
2066
- asstLines.push(...asstObj._formattedCached);
2067
- }
2068
-
2069
- let footerStatusLine = "";
2070
- const lastSys = turn.system[turn.system.length - 1];
2071
- if (lastSys && lastSys.text.includes("Failed")) {
2072
- footerStatusLine = `${morandi.failed("failed")} · ${morandi.dim(cleanModel)}`;
2073
- } else if (turn.assistant.totalTime !== undefined) {
2074
- const sec = (turn.assistant.totalTime / 1000).toFixed(1);
2075
- footerStatusLine = `${morandi.completed("completed")} · ${morandi.dim(cleanModel)} · ${morandi.dim(sec + "s")}`;
2076
- }
2077
-
2078
- if (footerStatusLine) {
2079
- asstLines.push("");
2080
- asstLines.push(footerStatusLine);
2081
- }
2082
-
2083
- const wrappedAsstLines: string[] = [];
2084
- for (const line of asstLines) {
2085
- wrappedAsstLines.push(...this.wrapLine(line, columns - 10));
2086
- }
2087
-
2088
- renderedLines.push(
2089
- " " + morandi.asstBold(`🤖 Orbit (${cleanModel})`),
2090
- );
2091
- renderedLines.push(aBorder);
2092
- for (const line of wrappedAsstLines) {
2093
- renderedLines.push(aBorder + line);
2094
- }
2095
- renderedLines.push(aBorder);
2096
- renderedLines.push("");
2097
- }
2098
- }
2099
-
2100
- // A.6 Read Plan Items
2101
- let planText = "";
2102
- const planItems = this.getPlanLines();
2103
- if (planItems.length > 0) {
2104
- const planContent: string[] = [];
2105
- let activeIndex = planItems.findIndex((item) => item.startsWith("- [/]"));
2106
- if (activeIndex === -1) {
2107
- activeIndex = planItems.findIndex((item) => item.startsWith("- [ ]"));
2108
- }
2109
- if (activeIndex === -1) {
2110
- activeIndex = planItems.length - 1;
2111
- }
2112
-
2113
- planContent.push(" " + morandi.accent("📋 Active Plan:"));
2114
-
2115
- const startPlanIdx = Math.max(0, activeIndex - 1);
2116
- const endPlanIdx = Math.min(planItems.length - 1, activeIndex + 1);
2117
-
2118
- if (startPlanIdx > 0) {
2119
- planContent.push(
2120
- " " + morandi.dim(`... ${startPlanIdx} step(s) completed`),
2121
- );
2122
- }
2123
-
2124
- for (let i = startPlanIdx; i <= endPlanIdx; i++) {
2125
- const item = planItems[i];
2126
- const text = item.substring(5).trim();
2127
- const isCurrentRunning =
2128
- item.startsWith("- [/]") || item.startsWith("- [/");
2129
- const isCompleted = item.startsWith("- [x]") || item.startsWith("- [x");
2130
-
2131
- let prefixSymbol = "";
2132
- if (isCurrentRunning) {
2133
- prefixSymbol = morandi.accent("●");
2134
- } else if (isCompleted) {
2135
- prefixSymbol = morandi.completed("✔");
2136
- } else {
2137
- prefixSymbol = morandi.gray("○");
2138
- }
2139
-
2140
- let displayText = text;
2141
- const maxTextLen = columns - 12;
2142
- const displayW = this.getStringWidth(displayText);
2143
- if (displayW > maxTextLen) {
2144
- displayText =
2145
- this.truncateToWidth(displayText, maxTextLen - 3) + "...";
2146
- }
2147
-
2148
- const coloredText = isCurrentRunning
2149
- ? morandi.whiteBold(displayText)
2150
- : isCompleted
2151
- ? morandi.dim(displayText)
2152
- : morandi.gray(displayText);
2153
-
2154
- planContent.push(" " + prefixSymbol + " " + coloredText);
2155
- }
2156
-
2157
- if (endPlanIdx < planItems.length - 1) {
2158
- const remaining = planItems.length - 1 - endPlanIdx;
2159
- planContent.push(
2160
- " " + morandi.dim(`... ${remaining} step(s) pending`),
2161
- );
2162
- }
2163
- planText = planContent.join("\n") + "\n\n";
2164
- }
2165
-
2166
- // A.5 Context files panel
2167
- let contextText = "";
2168
- if (this.activeContextFiles && this.activeContextFiles.length > 0) {
2169
- const contextLines: string[] = [];
2170
- contextLines.push(" " + morandi.accent("📎 Context Files:"));
2171
-
2172
- const filesStr = this.activeContextFiles
2173
- .map((f) => `[${f.path}${f.readOnly ? " 🔒" : ""}]`)
2174
- .join(" ");
2175
- const maxW = columns - 10;
2176
- const wrappedFiles = this.wrapLine(filesStr, maxW);
2177
- for (const line of wrappedFiles) {
2178
- contextLines.push(" " + morandi.white(line));
2179
- }
2180
- contextText = contextLines.join("\n") + "\n\n";
2181
- }
2182
-
2183
- const headerText = `${headerLines.join("\n")}\n\n` + planText + contextText;
2184
- const headerHeight = headerText.split("\n").length;
2185
-
2186
- // 6. 排版与渲染到终端 (带垂直裁剪逻辑,自底向上排布)
2187
- // 留出 1 行用于历史记录与输入框之间的空行间隔
2188
- const maxContentRows = Math.max(1, rows - bottomHeight - headerHeight - 1);
2189
-
2190
- const flatLines: string[] = [];
2191
- for (const item of renderedLines) {
2192
- flatLines.push(...item.split("\n"));
2193
- }
2194
-
2195
- if (
2196
- this.historyScrollOffset > 0 &&
2197
- flatLines.length > this.lastHistoryLineCount
2198
- ) {
2199
- this.historyScrollOffset += flatLines.length - this.lastHistoryLineCount;
2200
- this.hasNewOutputWhileScrolled = true;
2201
- }
2202
- this.lastHistoryLineCount = flatLines.length;
2203
- this.maxHistoryScrollOffset = Math.max(
2204
- 0,
2205
- flatLines.length - maxContentRows,
2206
- );
2207
- this.historyScrollOffset = Math.min(
2208
- this.historyScrollOffset,
2209
- this.maxHistoryScrollOffset,
2210
- );
2211
-
2212
- const finalLines: string[] = [];
2213
- let totalLinesCount = 0;
2214
-
2215
- const visibleEnd = Math.max(0, flatLines.length - this.historyScrollOffset);
2216
- for (let i = visibleEnd - 1; i >= 0; i--) {
2217
- const line = flatLines[i];
2218
- const visibleLen = this.getStringWidth(line);
2219
- const lineRows = Math.max(
2220
- 1,
2221
- Math.ceil(visibleLen / Math.max(1, columns - 4)),
2222
- );
2223
- if (totalLinesCount + lineRows > maxContentRows) {
2224
- break;
2225
- }
2226
- totalLinesCount += lineRows;
2227
- finalLines.unshift(line);
2228
- }
2229
-
2230
- // Trim trailing empty lines from finalLines to prevent extra blank space at the bottom
2231
- while (
2232
- finalLines.length > 0 &&
2233
- finalLines[finalLines.length - 1]
2234
- .replace(/\x1b\[[0-9;]*[a-zA-Z]/g, "")
2235
- .trim() === ""
2236
- ) {
2237
- finalLines.pop();
2238
- }
2239
-
2240
- const gapHeight = finalLines.length > 0 ? 1 : 0;
2241
- const totalHeight =
2242
- headerHeight + finalLines.length + gapHeight + bottomHeight;
2243
- const extraPad = Math.max(0, rows - totalHeight);
2244
-
2245
- const allLines: string[] = [];
2246
- allLines.push(...headerText.split("\n"));
2247
-
2248
- if (extraPad > 0) {
2249
- for (let i = 0; i < extraPad; i++) {
2250
- allLines.push("");
2251
- }
2252
- }
2253
-
2254
- if (finalLines.length > 0) {
2255
- allLines.push(...finalLines);
2256
- // 聊天记录的下限和输入框的长方形边框隔开一行空行
2257
- allLines.push("");
2258
- }
2259
-
2260
- allLines.push(...bottomLines);
2261
- const rawLines = allLines;
2262
-
2263
- const staticText = rawLines
2264
- .slice(0, rawLines.length - bottomHeight)
2265
- .join("\n");
2266
- const canIncremental =
2267
- !forceFull &&
2268
- isInputActive &&
2269
- this.cachedStaticLinesCount > 0 &&
2270
- bottomHeight === this.lastRenderedBottomHeight &&
2271
- staticText === this.cachedStaticContent;
2272
-
2273
- if (canIncremental) {
2274
- // 局部增量重绘
2275
- let cursorSequence = "";
2276
- let tempLen = 0;
2277
- let cursorLineIndex = 0;
2278
- let xOffset = 0;
2279
- for (let i = 0; i < wrappedLines.length; i++) {
2280
- const line = wrappedLines[i];
2281
- if (
2282
- this.cursorPosition >= tempLen &&
2283
- this.cursorPosition <= tempLen + line.length
2284
- ) {
2285
- cursorLineIndex = i;
2286
- const subStr = line.substring(0, this.cursorPosition - tempLen);
2287
- xOffset = this.getStringWidth(subStr);
2288
- break;
2289
- }
2290
- tempLen += line.length;
2291
- }
2292
- const lineStartX =
2293
- cursorLineIndex === 0 ? this.getStringWidth(" │ orbit > ") : 12;
2294
- const targetX = lineStartX + xOffset;
2295
- const linesUp = formattedLines.length - cursorLineIndex + 1; // 距离状态行向上数 linesUp 行
2296
- cursorSequence = `\x1b[${linesUp}A\x1b[${targetX + 1}G\x1b[?25h`;
2297
-
2298
- const bottomOutput =
2299
- "\x1b[?25l" + // 隐藏光标
2300
- `\x1b[${this.cachedStaticLinesCount + 1};1H` + // 移至底部的首行
2301
- bottomLines.map((line) => line + "\x1b[K").join("\n") +
2302
- "\x1b[J" + // 擦拭并重写 bottomLines
2303
- cursorSequence;
2304
-
2305
- process.stdout.write(bottomOutput);
2306
- return;
2307
- }
2308
-
2309
- // 缓存静态渲染信息
2310
- this.cachedStaticLinesCount = rawLines.length - bottomHeight;
2311
- this.cachedStaticContent = staticText;
2312
- this.lastRenderedBottomHeight = bottomHeight;
2313
-
2314
- let finalOutput =
2315
- "\x1b[?25l\x1b[H" +
2316
- rawLines.map((line) => line + "\x1b[K").join("\n") +
2317
- "\x1b[J";
2318
-
2319
- // 7. 相对光标精确定位与原子打包输出
2320
- let cursorSequence = "";
2321
- if (this.resolveInput || this.thinkingKeypressListener !== null) {
2322
- let tempLen = 0;
2323
- let cursorLineIndex = 0;
2324
- let xOffset = 0;
2325
- for (let i = 0; i < wrappedLines.length; i++) {
2326
- const line = wrappedLines[i];
2327
- if (
2328
- this.cursorPosition >= tempLen &&
2329
- this.cursorPosition <= tempLen + line.length
2330
- ) {
2331
- cursorLineIndex = i;
2332
- const subStr = line.substring(0, this.cursorPosition - tempLen);
2333
- xOffset = this.getStringWidth(subStr);
2334
- break;
2335
- }
2336
- tempLen += line.length;
2337
- }
2338
- const lineStartX =
2339
- cursorLineIndex === 0 ? this.getStringWidth(" │ orbit > ") : 12;
2340
- const targetX = lineStartX + xOffset;
2341
- const linesUp = formattedLines.length - cursorLineIndex + 1; // 距离状态行向上数 linesUp 行
2342
- cursorSequence = `\x1b[${linesUp}A\x1b[${targetX + 1}G\x1b[?25h`;
2343
- } else {
2344
- cursorSequence = "\x1b[?25l";
2345
- }
2346
-
2347
- finalOutput += cursorSequence;
2348
- process.stdout.write(finalOutput);
2349
- }
2350
-
2351
- private isFullWidth(codePoint: number): boolean {
2352
- if (Number.isNaN(codePoint)) {
2353
- return false;
2354
- }
2355
- if (
2356
- codePoint === 0x25e2 || // ◢
2357
- codePoint === 0x25e3 || // ◣
2358
- codePoint === 0x25e4 || // ◤
2359
- codePoint === 0x25e5 || // ◥
2360
- codePoint === 0x2590 || // ▐
2361
- codePoint === 0x258c || // ▌
2362
- codePoint === 0x25cf // ●
2363
- ) {
2364
- return true;
2365
- }
2366
- return (
2367
- (codePoint >= 0x1100 && codePoint <= 0x115f) || // Hangul Jamo
2368
- codePoint === 0x2329 || // LEFT-POINTING ANGLE BRACKET
2369
- codePoint === 0x232a || // RIGHT-POINTING ANGLE BRACKET
2370
- (codePoint >= 0x2e80 && codePoint <= 0x3247 && codePoint !== 0x303f) || // CJK Radicals Supplement .. Enclosed CJK Letters and Months
2371
- (codePoint >= 0x3250 && codePoint <= 0x4dbf) || // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A
2372
- (codePoint >= 0x4e00 && codePoint <= 0xa4c6) || // CJK Unified Ideographs .. Yi Radicals
2373
- (codePoint >= 0xa960 && codePoint <= 0xa97c) || // Hangul Jamo Extended-A
2374
- (codePoint >= 0xac00 && codePoint <= 0xd7a3) || // Hangul Syllables
2375
- (codePoint >= 0xf900 && codePoint <= 0xfaff) || // CJK Compatibility Ideographs
2376
- (codePoint >= 0xfe10 && codePoint <= 0xfe19) || // Vertical Forms
2377
- (codePoint >= 0xfe30 && codePoint <= 0xfe6b) || // CJK Compatibility Forms .. Small Form Variants
2378
- (codePoint >= 0xff01 && codePoint <= 0xff60) || // Halfwidth and Fullwidth Forms
2379
- (codePoint >= 0xffe0 && codePoint <= 0xffe6) ||
2380
- (codePoint >= 0x1b000 && codePoint <= 0x1b001) || // Kana Supplement
2381
- (codePoint >= 0x1f200 && codePoint <= 0x1f251) || // Enclosed Ideographic Supplement
2382
- (codePoint >= 0x20000 && codePoint <= 0x3fffd) || // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane
2383
- (codePoint >= 0x1f300 && codePoint <= 0x1f9ff) || // Emojis
2384
- (codePoint >= 0x1f600 && codePoint <= 0x1f64f) || // Emoticons
2385
- (codePoint >= 0x1f680 && codePoint <= 0x1f6ff) // Transport & Map
2386
- );
2387
- }
2388
-
2389
- private truncateToWidth(str: string, maxW: number): string {
2390
- let width = 0;
2391
- let result = "";
2392
- for (const char of str) {
2393
- const code = char.codePointAt(0);
2394
- if (code === undefined) continue;
2395
- const charW = this.isFullWidth(code) ? 2 : 1;
2396
- if (width + charW > maxW) {
2397
- break;
2398
- }
2399
- width += charW;
2400
- result += char;
2401
- }
2402
- return result;
2403
- }
2404
-
2405
- private wrapLine(line: string, maxWidth: number): string[] {
2406
- const cleanLine = line.replace(
2407
- /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,
2408
- "",
2409
- );
2410
- if (this.getStringWidth(cleanLine) <= maxWidth) {
2411
- return [line];
2412
- }
2413
-
2414
- const lines: string[] = [];
2415
- let currentLine = "";
2416
- let currentWidth = 0;
2417
-
2418
- const ansiRegex =
2419
- /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g;
2420
- let activeColor = "";
2421
-
2422
- let i = 0;
2423
- while (i < line.length) {
2424
- ansiRegex.lastIndex = i;
2425
- const match = ansiRegex.exec(line);
2426
- if (match && match.index === i) {
2427
- const ansiCode = match[0];
2428
- currentLine += ansiCode;
2429
- if (ansiCode.includes("m") && !ansiCode.includes("[0m")) {
2430
- activeColor = ansiCode;
2431
- } else if (ansiCode.includes("[0m")) {
2432
- activeColor = "";
2433
- }
2434
- i += ansiCode.length;
2435
- continue;
2436
- }
2437
-
2438
-
2439
- const code = line.codePointAt(i);
2440
- let charLen = 1;
2441
- if (code && code > 0xffff) {
2442
- charLen = 2;
2443
- }
2444
- const charStr = line.substring(i, i + charLen);
2445
- const charW = this.isFullWidth(code || 0) ? 2 : 1;
2446
-
2447
- if (currentWidth + charW > maxWidth) {
2448
- if (activeColor) {
2449
- currentLine += "\x1b[0m";
2450
- }
2451
- lines.push(currentLine);
2452
- currentLine = activeColor + charStr;
2453
- currentWidth = charW;
2454
- } else {
2455
- currentLine += charStr;
2456
- currentWidth += charW;
2457
- }
2458
- i += charLen;
2459
- }
2460
-
2461
- if (currentLine) {
2462
- lines.push(currentLine);
2463
- }
2464
- return lines;
2465
- }
2466
-
2467
- private getStringWidth(str: string): number {
2468
- const cleanStr = str.replace(
2469
- /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,
2470
- "",
2471
- );
2472
- let width = 0;
2473
- for (let i = 0; i < cleanStr.length; i++) {
2474
- const code = cleanStr.codePointAt(i);
2475
- if (!code) continue;
2476
- if (code > 0xffff) {
2477
- i++;
2478
- }
2479
- if (this.isFullWidth(code)) {
2480
- width += 2;
2481
- } else {
2482
- width += 1;
2483
- }
2484
- }
2485
- return width;
2486
- }
2487
-
2488
- private wrapText(str: string, maxWidth: number): string[] {
2489
- const lines: string[] = [];
2490
- let currentLine = "";
2491
- let currentWidth = 0;
2492
-
2493
- for (let i = 0; i < str.length; i++) {
2494
- const code = str.codePointAt(i);
2495
- if (!code) continue;
2496
- let char = str.charAt(i);
2497
- if (code > 0xffff) {
2498
- char = str.substring(i, i + 2);
2499
- i++;
2500
- }
2501
- const charWidth = this.isFullWidth(code) ? 2 : 1;
2502
- if (currentWidth + charWidth > maxWidth) {
2503
- lines.push(currentLine);
2504
- currentLine = char;
2505
- currentWidth = charWidth;
2506
- } else {
2507
- currentLine += char;
2508
- currentWidth += charWidth;
2509
- }
2510
- }
2511
- if (currentLine || lines.length === 0) {
2512
- lines.push(currentLine);
2513
- }
2514
- return lines;
2515
- }
2516
-
2517
- private formatWrappedLines(
2518
- wrappedLines: string[],
2519
- inputLength: number,
2520
- ): string[] {
2521
- let charIndex = 0;
2522
- const formattedLines: string[] = [];
2523
-
2524
- for (const line of wrappedLines) {
2525
- let formattedLine = "";
2526
- for (let i = 0; i < line.length; i++) {
2527
- const char = line.charAt(i);
2528
- const code = line.codePointAt(i);
2529
- let increment = 1;
2530
- let charStr = char;
2531
- if (code && code > 0xffff) {
2532
- charStr = line.substring(i, i + 2);
2533
- i++;
2534
- increment = 2;
2535
- }
2536
-
2537
- if (charIndex < inputLength) {
2538
- formattedLine += `\x1b[1;38;2;230;225;215m${charStr}\x1b[0m`; // morandi.whiteBold
2539
- } else {
2540
- formattedLine += `\x1b[2;38;2;110;110;110m${charStr}\x1b[0m`; // morandi.dim
2541
- }
2542
- charIndex += increment;
2543
- }
2544
- formattedLines.push(formattedLine);
2545
- }
2546
- return formattedLines;
2547
- }
2548
- }