@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,1919 +0,0 @@
1
- // src/tui/FullscreenTui.ts
2
- import { join, dirname } from "path";
3
- import { homedir } from "os";
4
- import { existsSync, readFileSync, writeFileSync, mkdirSync } from "fs";
5
- import { execSync } from "child_process";
6
- import readline from "readline";
7
- import { Prompt, Renderer } from "@orbit-ai/tui";
8
- function previousCodePointIndex(text, index) {
9
- const safeIndex = Math.max(0, Math.min(index, text.length));
10
- if (safeIndex === 0) return 0;
11
- const previous = text.charCodeAt(safeIndex - 1);
12
- if (previous >= 56320 && previous <= 57343 && safeIndex >= 2) {
13
- const leading = text.charCodeAt(safeIndex - 2);
14
- if (leading >= 55296 && leading <= 56319) {
15
- return safeIndex - 2;
16
- }
17
- }
18
- return safeIndex - 1;
19
- }
20
- function nextCodePointIndex(text, index) {
21
- const safeIndex = Math.max(0, Math.min(index, text.length));
22
- if (safeIndex >= text.length) return text.length;
23
- const leading = text.charCodeAt(safeIndex);
24
- if (leading >= 55296 && leading <= 56319 && safeIndex + 1 < text.length) {
25
- const trailing = text.charCodeAt(safeIndex + 1);
26
- if (trailing >= 56320 && trailing <= 57343) {
27
- return safeIndex + 2;
28
- }
29
- }
30
- return safeIndex + 1;
31
- }
32
- function parseMouseWheelDirection(input) {
33
- const match = input.match(/\x1b\[<(\d+);\d+;\d+[mM]/);
34
- if (!match) return null;
35
- const button = Number(match[1]);
36
- if ((button & 64) === 0) return null;
37
- return (button & 1) === 0 ? "up" : "down";
38
- }
39
- async function pageText(text) {
40
- const lines = text.split("\n");
41
- const rows = process.stdout.rows || 24;
42
- const pageSize = rows - 2;
43
- if (lines.length <= pageSize) {
44
- console.log(text);
45
- return;
46
- }
47
- let cursor = 0;
48
- const wasRaw = !!process.stdin.isRaw;
49
- if (process.stdin.setRawMode) {
50
- process.stdin.setRawMode(true);
51
- }
52
- process.stdin.resume();
53
- readline.emitKeypressEvents(process.stdin);
54
- const keypressPromise = () => {
55
- return new Promise((resolve) => {
56
- const onKeypress = (str, key) => {
57
- process.stdin.removeListener("keypress", onKeypress);
58
- if (key && key.ctrl && key.name === "c") {
59
- if (process.stdin.setRawMode) {
60
- process.stdin.setRawMode(wasRaw);
61
- }
62
- process.exit(0);
63
- }
64
- resolve(key ? key.name || str : str);
65
- };
66
- process.stdin.on("keypress", onKeypress);
67
- });
68
- };
69
- try {
70
- while (cursor < lines.length) {
71
- const chunk = lines.slice(cursor, cursor + pageSize);
72
- console.log(chunk.join("\n"));
73
- cursor += pageSize;
74
- if (cursor >= lines.length) {
75
- break;
76
- }
77
- process.stdout.write(
78
- `\r\x1B[36m-- More (${Math.round(cursor / lines.length * 100)}%) [Space/Enter to continue, q to quit] --\x1B[39m`
79
- );
80
- const key = await keypressPromise();
81
- process.stdout.write("\r\x1B[K");
82
- if (key === "q") {
83
- break;
84
- }
85
- if (key === "return" || key === "enter") {
86
- cursor = cursor - pageSize + 1;
87
- }
88
- }
89
- } finally {
90
- if (process.stdin.setRawMode) {
91
- process.stdin.setRawMode(wasRaw);
92
- }
93
- process.stdin.pause();
94
- }
95
- }
96
- var FullscreenTui = class {
97
- constructor(cwd, modelName, version, config) {
98
- this.cwd = cwd;
99
- this.modelName = modelName;
100
- this.version = version;
101
- this.config = config;
102
- readline.emitKeypressEvents(process.stdin);
103
- process.stdout.write = (chunk, encoding, cb) => {
104
- if (!this.isActive) {
105
- const text = typeof chunk === "string" ? chunk : chunk.toString();
106
- if (text.trim().length > 0) {
107
- this.hasWrittenStdoutSinceStop = true;
108
- }
109
- }
110
- return this.originalWrite(chunk, encoding, cb);
111
- };
112
- this.loadInputHistory();
113
- }
114
- cwd;
115
- modelName;
116
- version;
117
- config;
118
- history = [];
119
- inputBuffer = "";
120
- cursorPosition = 0;
121
- isActive = false;
122
- currentAttempt = 0;
123
- // Command history
124
- inputHistory = [];
125
- historyIndex = -1;
126
- tempBuffer = "";
127
- activeCommandIndex = 0;
128
- ctrlCPressedOnce = false;
129
- ctrlCTimeout = null;
130
- cachedStaticLinesCount = 0;
131
- cachedStaticContent = "";
132
- lastRenderedBottomHeight = 0;
133
- // DeepSeek real-time thinking
134
- currentThinking = "";
135
- // Timers and metrics
136
- attemptStartTime = 0;
137
- firstDeltaTime = 0;
138
- thoughtTimer = null;
139
- thoughtElapsed = 0;
140
- isThinking = false;
141
- sessionCost = 0;
142
- totalInputTokens = 0;
143
- totalCacheReadTokens = 0;
144
- totalOutputTokens = 0;
145
- budgetLimit = 0;
146
- resolveInput = null;
147
- activeRunnable = null;
148
- thinkingKeypressListener = null;
149
- pendingGuidedStatement = null;
150
- // Throttled rendering to prevent terminal flickering during model output
151
- lastRenderTime = 0;
152
- renderPending = false;
153
- renderTimeout = null;
154
- originalWrite = process.stdout.write.bind(process.stdout);
155
- hasWrittenStdoutSinceStop = false;
156
- candidates = null;
157
- modelNameGetter = () => this.modelName;
158
- permissionsMode = "normal";
159
- hideAutocomplete = false;
160
- cachedPlanLines = [];
161
- lastPlanReadTime = 0;
162
- activeContextFiles = [];
163
- cachedGitSummary = null;
164
- lastGitSummaryReadTime = 0;
165
- historyScrollOffset = 0;
166
- maxHistoryScrollOffset = 0;
167
- lastHistoryLineCount = 0;
168
- hasNewOutputWhileScrolled = false;
169
- getPlanLines() {
170
- const now = Date.now();
171
- if (now - this.lastPlanReadTime < 2e3) {
172
- return this.cachedPlanLines;
173
- }
174
- this.lastPlanReadTime = now;
175
- const planPath2 = join(this.cwd, ".orbit", "task.md");
176
- const planPath1 = join(this.cwd, "task.md");
177
- let planPath = "";
178
- if (existsSync(planPath2)) {
179
- planPath = planPath2;
180
- } else if (existsSync(planPath1)) {
181
- planPath = planPath1;
182
- }
183
- if (!planPath) {
184
- this.cachedPlanLines = [];
185
- return [];
186
- }
187
- try {
188
- const content = readFileSync(planPath, "utf8");
189
- const lines = content.split("\n");
190
- const planItems = [];
191
- for (const line of lines) {
192
- const trimmed = line.trim();
193
- if (trimmed.startsWith("- [ ") || trimmed.startsWith("- [x") || trimmed.startsWith("- [/") || trimmed.startsWith("- [x]") || trimmed.startsWith("- [ ]") || trimmed.startsWith("- [/]")) {
194
- planItems.push(trimmed);
195
- }
196
- }
197
- this.cachedPlanLines = planItems;
198
- } catch {
199
- this.cachedPlanLines = [];
200
- }
201
- return this.cachedPlanLines;
202
- }
203
- setPermissionsMode(mode) {
204
- this.permissionsMode = mode;
205
- }
206
- setModelNameGetter(getter) {
207
- this.modelNameGetter = getter;
208
- }
209
- setActiveRunnable(runnable) {
210
- this.activeRunnable = runnable;
211
- }
212
- setCandidates(candidates) {
213
- this.candidates = candidates;
214
- }
215
- getHistoryFilePath() {
216
- return join(homedir(), ".orbit", "input_history.json");
217
- }
218
- loadInputHistory() {
219
- try {
220
- const filePath = this.getHistoryFilePath();
221
- if (existsSync(filePath)) {
222
- const raw = readFileSync(filePath, "utf8");
223
- const parsed = JSON.parse(raw);
224
- if (Array.isArray(parsed)) {
225
- this.inputHistory = parsed.filter((x) => typeof x === "string");
226
- }
227
- }
228
- } catch {
229
- this.inputHistory = [];
230
- }
231
- }
232
- saveInputHistory() {
233
- try {
234
- const filePath = this.getHistoryFilePath();
235
- const dir = dirname(filePath);
236
- if (!existsSync(dir)) {
237
- mkdirSync(dir, { recursive: true });
238
- }
239
- writeFileSync(
240
- filePath,
241
- JSON.stringify(this.inputHistory, null, 2),
242
- "utf8"
243
- );
244
- } catch {
245
- }
246
- }
247
- addSystemMessage(text, raw = false) {
248
- if (!text) return;
249
- this.history.push({
250
- role: "system",
251
- text
252
- });
253
- this.render();
254
- }
255
- onResize = () => {
256
- if (this.isActive) {
257
- this.render(true);
258
- }
259
- };
260
- start(budgetLimit) {
261
- this.budgetLimit = budgetLimit;
262
- this.isActive = true;
263
- this.hasWrittenStdoutSinceStop = false;
264
- const mouseMode = this.config?.tui?.mouse !== false ? "\x1B[?1000h\x1B[?1006h" : "";
265
- process.stdout.write(`\x1B[?1049h${mouseMode}\x1B[?25l`);
266
- process.stdout.on("resize", this.onResize);
267
- this.render();
268
- }
269
- stop() {
270
- if (!this.isActive) return;
271
- this.isActive = false;
272
- process.stdout.off("resize", this.onResize);
273
- process.stdout.write("\x1B[?1006l\x1B[?1000l\x1B[?1049l\x1B[?25h");
274
- this.hasWrittenStdoutSinceStop = false;
275
- if (this.renderTimeout) {
276
- clearTimeout(this.renderTimeout);
277
- this.renderTimeout = null;
278
- }
279
- this.renderPending = false;
280
- }
281
- dispose() {
282
- this.stopThinkingInput();
283
- this.stop();
284
- if (this.thoughtTimer) {
285
- clearInterval(this.thoughtTimer);
286
- this.thoughtTimer = null;
287
- }
288
- if (this.ctrlCTimeout) {
289
- clearTimeout(this.ctrlCTimeout);
290
- this.ctrlCTimeout = null;
291
- }
292
- if (process.stdin.setRawMode && process.stdin.isTTY) {
293
- process.stdin.setRawMode(false);
294
- }
295
- process.stdout.write = this.originalWrite;
296
- }
297
- getGitSummary() {
298
- const now = Date.now();
299
- if (this.cachedGitSummary && now - this.lastGitSummaryReadTime < 1500) {
300
- return this.cachedGitSummary;
301
- }
302
- const summary = {
303
- branch: "no-git",
304
- added: 0,
305
- modified: 0,
306
- deleted: 0
307
- };
308
- try {
309
- summary.branch = execSync("git rev-parse --abbrev-ref HEAD", {
310
- cwd: this.cwd,
311
- stdio: ["ignore", "pipe", "ignore"]
312
- }).toString().trim();
313
- const statusOutput = execSync("git status --porcelain", {
314
- cwd: this.cwd,
315
- stdio: ["ignore", "pipe", "ignore"]
316
- }).toString();
317
- for (const line of statusOutput.split("\n")) {
318
- if (!line) continue;
319
- const code = line.substring(0, 2);
320
- if (code.includes("A") || code.includes("?")) {
321
- summary.added++;
322
- } else if (code.includes("M") || code.includes("R")) {
323
- summary.modified++;
324
- } else if (code.includes("D")) {
325
- summary.deleted++;
326
- }
327
- }
328
- } catch {
329
- }
330
- this.cachedGitSummary = summary;
331
- this.lastGitSummaryReadTime = now;
332
- return summary;
333
- }
334
- getWheelScrollLines() {
335
- const configured = Number(this.config?.tui?.scrollSpeed ?? 50);
336
- return Math.max(1, Math.min(20, Math.ceil(configured / 5)));
337
- }
338
- scrollHistory(delta) {
339
- this.historyScrollOffset = Math.max(
340
- 0,
341
- Math.min(this.maxHistoryScrollOffset, this.historyScrollOffset + delta)
342
- );
343
- if (this.historyScrollOffset === 0) {
344
- this.hasNewOutputWhileScrolled = false;
345
- }
346
- this.render();
347
- }
348
- handleScrollInput(str, key) {
349
- const wheelDirection = parseMouseWheelDirection(str);
350
- if (wheelDirection) {
351
- const lines = this.getWheelScrollLines();
352
- this.scrollHistory(wheelDirection === "up" ? lines : -lines);
353
- return true;
354
- }
355
- const pageSize = Math.max(3, Math.floor((process.stdout.rows || 24) * 0.6));
356
- if (key?.name === "pageup") {
357
- this.scrollHistory(pageSize);
358
- return true;
359
- }
360
- if (key?.name === "pagedown") {
361
- this.scrollHistory(-pageSize);
362
- return true;
363
- }
364
- if (key?.name === "home" && key?.ctrl) {
365
- this.scrollHistory(this.maxHistoryScrollOffset);
366
- return true;
367
- }
368
- if (key?.name === "end" && this.historyScrollOffset > 0) {
369
- this.historyScrollOffset = 0;
370
- this.hasNewOutputWhileScrolled = false;
371
- this.render();
372
- return true;
373
- }
374
- return false;
375
- }
376
- startThinkingInput() {
377
- if (!this.isActive) return;
378
- this.stopThinkingInput();
379
- if (process.stdin.setRawMode) {
380
- process.stdin.setRawMode(true);
381
- }
382
- process.stdin.resume();
383
- this.thinkingKeypressListener = (str, key) => {
384
- if (!this.isActive) {
385
- this.stopThinkingInput();
386
- return;
387
- }
388
- if (this.handleScrollInput(str, key)) {
389
- return;
390
- }
391
- if (key && key.ctrl && key.name === "c") {
392
- if (this.inputBuffer.length > 0) {
393
- this.inputBuffer = "";
394
- this.cursorPosition = 0;
395
- this.render();
396
- } else {
397
- if (this.activeRunnable) {
398
- this.activeRunnable.abort();
399
- }
400
- }
401
- return;
402
- }
403
- if (key && (key.name === "return" || key.name === "enter")) {
404
- const submitted = this.inputBuffer;
405
- if (submitted.trim()) {
406
- this.pendingGuidedStatement = submitted;
407
- if (this.activeRunnable) {
408
- this.activeRunnable.abort();
409
- }
410
- }
411
- this.inputBuffer = "";
412
- this.cursorPosition = 0;
413
- this.render();
414
- return;
415
- }
416
- if (key && key.ctrl) {
417
- return;
418
- }
419
- if (key && key.name === "backspace") {
420
- if (this.cursorPosition > 0) {
421
- const previousIndex = previousCodePointIndex(
422
- this.inputBuffer,
423
- this.cursorPosition
424
- );
425
- this.inputBuffer = this.inputBuffer.slice(0, previousIndex) + this.inputBuffer.slice(this.cursorPosition);
426
- this.cursorPosition = previousIndex;
427
- this.render();
428
- }
429
- return;
430
- }
431
- if (key && key.name === "delete") {
432
- if (this.cursorPosition < this.inputBuffer.length) {
433
- const nextIndex = nextCodePointIndex(
434
- this.inputBuffer,
435
- this.cursorPosition
436
- );
437
- this.inputBuffer = this.inputBuffer.slice(0, this.cursorPosition) + this.inputBuffer.slice(nextIndex);
438
- this.render();
439
- }
440
- return;
441
- }
442
- if (key && key.name === "left") {
443
- if (this.cursorPosition > 0) {
444
- this.cursorPosition = previousCodePointIndex(
445
- this.inputBuffer,
446
- this.cursorPosition
447
- );
448
- this.render();
449
- }
450
- return;
451
- }
452
- if (key && key.name === "right") {
453
- if (this.cursorPosition < this.inputBuffer.length) {
454
- this.cursorPosition = nextCodePointIndex(
455
- this.inputBuffer,
456
- this.cursorPosition
457
- );
458
- this.render();
459
- }
460
- return;
461
- }
462
- if (str && !/[\u0000-\u001f\u007f]/.test(str)) {
463
- this.inputBuffer = this.inputBuffer.slice(0, this.cursorPosition) + str + this.inputBuffer.slice(this.cursorPosition);
464
- this.cursorPosition += str.length;
465
- this.render();
466
- }
467
- };
468
- process.stdin.on("keypress", this.thinkingKeypressListener);
469
- }
470
- stopThinkingInput() {
471
- if (this.thinkingKeypressListener) {
472
- process.stdin.removeListener("keypress", this.thinkingKeypressListener);
473
- this.thinkingKeypressListener = null;
474
- }
475
- }
476
- getActiveMatches() {
477
- if (!this.candidates || !this.inputBuffer.startsWith("/")) return [];
478
- if (this.hideAutocomplete) return [];
479
- const line = this.inputBuffer;
480
- const parts = line.split(/\s+/);
481
- if (parts[0] === "/add" && line.includes(" ")) {
482
- const query = line.slice(5).trim();
483
- const hits = (this.candidates.files || []).filter((f) => f.toLowerCase().includes(query.toLowerCase())).map((f) => `/add ${f}`);
484
- if (hits.length > 0) return hits;
485
- }
486
- if (parts[0] === "/drop" && line.includes(" ")) {
487
- const query = line.slice(6).trim();
488
- const hits = (this.candidates.files || []).filter((f) => f.toLowerCase().includes(query.toLowerCase())).map((f) => `/drop ${f}`);
489
- if (hits.length > 0) return hits;
490
- }
491
- if ((parts[0] === "/read-only" || parts[0] === "/readonly") && line.includes(" ")) {
492
- const prefix = parts[0];
493
- const query = line.slice(prefix.length + 1).trim();
494
- const hits = (this.candidates.files || []).filter((f) => f.toLowerCase().includes(query.toLowerCase())).map((f) => `${prefix} ${f}`);
495
- if (hits.length > 0) return hits;
496
- }
497
- if (parts[0] === "/references" && line.includes(" ")) {
498
- const query = line.slice(12).trim();
499
- const hits = (this.candidates.symbols || []).filter((s) => s.toLowerCase().startsWith(query.toLowerCase())).map((s) => `/references ${s}`);
500
- if (hits.length > 0) return hits;
501
- }
502
- if (parts[0] === "/model" && line.includes(" ")) {
503
- const query = line.slice(7).trim();
504
- const defaultProvider = this.config?.provider?.default;
505
- const providerConfig = this.config?.providers?.[defaultProvider];
506
- const providerType = providerConfig?.type;
507
- let models = [];
508
- if (providerType === "anthropic" || providerType === "anthropic-compatible") {
509
- models = [
510
- "claude-3-5-sonnet-latest",
511
- "claude-3-5-haiku-latest",
512
- "claude-3-opus-latest"
513
- ];
514
- } else if (providerType === "openai") {
515
- models = ["gpt-4o", "gpt-4o-mini", "o1", "o3-mini"];
516
- } else if (providerType === "openai-compatible") {
517
- if (defaultProvider?.includes("deepseek")) {
518
- models = [
519
- "deepseek-v4-flash",
520
- "deepseek-v4-pro",
521
- "deepseek-chat",
522
- "deepseek-reasoner"
523
- ];
524
- } else {
525
- models = [
526
- "gpt-4o",
527
- "gpt-4o-mini",
528
- "deepseek-chat",
529
- "deepseek-reasoner"
530
- ];
531
- }
532
- } else if (providerType === "ollama") {
533
- models = ["qwen2.5-coder:7b", "qwen2.5-coder:1.5b", "llama3"];
534
- } else {
535
- models = [
536
- "deepseek-v4-flash",
537
- "deepseek-v4-pro",
538
- "gpt-4o",
539
- "o3-mini",
540
- "claude-3-5-sonnet-latest"
541
- ];
542
- }
543
- const hits = models.filter((m) => m.toLowerCase().includes(query.toLowerCase())).map((m) => `/model ${m}`);
544
- if (hits.length > 0) return hits;
545
- }
546
- if (parts[0] === "/chat" && line.includes(" ")) {
547
- if (parts.length <= 2) {
548
- const subcommands = ["list", "ls", "new", "delete", "rm", "switch"];
549
- const hits = subcommands.map((sub) => `/chat ${sub}`).filter((c) => c.startsWith(line));
550
- if (hits.length > 0) return hits;
551
- }
552
- if (parts.length >= 3 && ["delete", "rm", "switch"].includes(parts[1])) {
553
- const cmd = parts[0];
554
- const sub = parts[1];
555
- const query = parts.slice(2).join(" ");
556
- const prefix = `${cmd} ${sub} `;
557
- const hits = (this.candidates.sessions || []).filter((s) => {
558
- const lowerS = s.toLowerCase();
559
- const lowerQ = query.toLowerCase();
560
- return lowerS.startsWith(lowerQ) || s.replace(/^sess_/, "").toLowerCase().startsWith(lowerQ);
561
- }).map((s) => `${prefix}${s}`);
562
- if (hits.length > 0) return hits;
563
- }
564
- }
565
- if (parts[0] === "/fork" && line.includes(" ")) {
566
- if (parts.length <= 2) {
567
- const subcommands = ["tree", "switch"];
568
- const hits = subcommands.map((sub) => `/fork ${sub}`).filter((c) => c.startsWith(line));
569
- if (hits.length > 0) return hits;
570
- }
571
- if (parts.length >= 3 && parts[1] === "switch") {
572
- const cmd = parts[0];
573
- const sub = parts[1];
574
- const query = parts.slice(2).join(" ");
575
- const prefix = `${cmd} ${sub} `;
576
- const hits = (this.candidates.sessions || []).filter((s) => {
577
- const lowerS = s.toLowerCase();
578
- const lowerQ = query.toLowerCase();
579
- return lowerS.startsWith(lowerQ) || s.replace(/^sess_/, "").toLowerCase().startsWith(lowerQ);
580
- }).map((s) => `${prefix}${s}`);
581
- if (hits.length > 0) return hits;
582
- }
583
- }
584
- if ((parts[0] === "/delete" || parts[0] === "/rm" || parts[0] === "/del") && line.includes(" ")) {
585
- const prefix = parts[0];
586
- const query = line.slice(prefix.length + 1).trim();
587
- const hits = (this.candidates.sessions || []).filter((s) => {
588
- const lowerS = s.toLowerCase();
589
- const lowerQ = query.toLowerCase();
590
- return lowerS.startsWith(lowerQ) || s.replace(/^sess_/, "").toLowerCase().startsWith(lowerQ);
591
- }).map((s) => `${prefix} ${s}`);
592
- if (hits.length > 0) return hits;
593
- }
594
- const BUILTIN_SLASH_COMMANDS = [
595
- "/help",
596
- "/status",
597
- "/config",
598
- "/model",
599
- "/chat",
600
- "/commit",
601
- "/exit",
602
- "/quit",
603
- "/rollback",
604
- "/timeline",
605
- "/rewind",
606
- "/clear",
607
- "/compact",
608
- "/history",
609
- "/edit",
610
- "/inspect",
611
- "/doc",
612
- "/diagnose",
613
- "/resolve",
614
- "/references",
615
- "/run",
616
- "/grep",
617
- "/api",
618
- "/register",
619
- "/language",
620
- "/fork",
621
- "/mode",
622
- "/ask",
623
- "/code",
624
- "/copy",
625
- "/copy-context",
626
- "/git",
627
- "/tokens",
628
- "/read-only",
629
- "/readonly",
630
- "/new",
631
- "/reset",
632
- "/delete",
633
- "/rm",
634
- "/del",
635
- "/btw",
636
- "/memory",
637
- "/commands"
638
- ];
639
- const cmds = this.candidates.commands.length > 0 ? this.candidates.commands : BUILTIN_SLASH_COMMANDS;
640
- return cmds.filter((c) => c.startsWith(line));
641
- }
642
- getSuggestion() {
643
- const line = this.inputBuffer;
644
- const matches = this.getActiveMatches();
645
- if (matches.length > 0) {
646
- const idx = Math.min(this.activeCommandIndex, matches.length - 1);
647
- const match = matches[idx];
648
- if (match && match !== line) {
649
- return match.substring(line.length);
650
- }
651
- }
652
- return "";
653
- }
654
- getHits() {
655
- const hits = this.getActiveMatches();
656
- return { hits, lastWord: this.inputBuffer };
657
- }
658
- setCost(cost, inputTokens = 0, cacheReadTokens = 0, outputTokens = 0) {
659
- this.sessionCost = cost;
660
- this.totalInputTokens = inputTokens;
661
- this.totalCacheReadTokens = cacheReadTokens;
662
- this.totalOutputTokens = outputTokens;
663
- this.render();
664
- }
665
- handleThinkingDelta(text) {
666
- this.currentThinking += text;
667
- this.throttleRender();
668
- }
669
- addLog(text) {
670
- if (!text || !text.trim()) return;
671
- const trimmed = text.trim();
672
- if (trimmed.includes("Summary:") || trimmed.includes("Modified files:") || trimmed.includes("Verification:") || trimmed.includes("Session Cost:")) {
673
- return;
674
- }
675
- if (text.includes("Orbit:")) {
676
- const cleanText = text.replace(/Orbit:\s*/i, "").trim();
677
- const last = this.history[this.history.length - 1];
678
- if (last && last.role === "assistant") {
679
- if (!last.text.includes(cleanText)) {
680
- last.text = cleanText;
681
- }
682
- this.render();
683
- }
684
- return;
685
- }
686
- if (text.includes("Thought")) {
687
- return;
688
- }
689
- this.history.push({
690
- role: "system",
691
- text: trimmed
692
- });
693
- this.render();
694
- }
695
- syncFromLoop(loop) {
696
- this.activeContextFiles = loop.getRelevantFiles() || [];
697
- const loopHistory = loop.getHistory();
698
- if (loopHistory.length === 0) {
699
- this.render();
700
- return;
701
- }
702
- let localAsstIdx = this.history.map((m, i) => m.role === "assistant" ? i : -1).filter((i) => i !== -1);
703
- let loopAsst = loopHistory.filter((m) => m.role === "assistant");
704
- for (let i = 0; i < loopAsst.length; i++) {
705
- const loopMsg = loopAsst[i];
706
- const textBlock = loopMsg.content.find((b) => b.type === "text");
707
- if (textBlock && textBlock.text) {
708
- const localIdx = localAsstIdx[i];
709
- if (localIdx !== void 0) {
710
- this.history[localIdx].text = textBlock.text;
711
- } else {
712
- this.history.push({
713
- role: "assistant",
714
- text: textBlock.text,
715
- attempt: i + 1
716
- });
717
- }
718
- }
719
- }
720
- this.render();
721
- }
722
- loadHistory(loopHistory) {
723
- this.history = [];
724
- this.historyScrollOffset = 0;
725
- this.hasNewOutputWhileScrolled = false;
726
- let attempt = 0;
727
- for (const msg of loopHistory) {
728
- if (msg.role === "user") {
729
- const text = msg.content.map((c) => c.type === "text" ? c.text : "").join("");
730
- if (text === "REPL Interactive Shell Started") {
731
- continue;
732
- }
733
- this.history.push({
734
- role: "user",
735
- text
736
- });
737
- } else if (msg.role === "assistant") {
738
- attempt++;
739
- const textBlock = msg.content.find((b) => b.type === "text");
740
- this.history.push({
741
- role: "assistant",
742
- text: textBlock?.text || "",
743
- attempt
744
- });
745
- } else if (msg.role === "system") {
746
- const text = msg.content.map((c) => c.type === "text" ? c.text : "").join("");
747
- this.history.push({
748
- role: "system",
749
- text
750
- });
751
- }
752
- }
753
- this.render();
754
- }
755
- async askInput() {
756
- if (!this.isActive) {
757
- if (this.hasWrittenStdoutSinceStop) {
758
- const wasRaw = !!process.stdin.isRaw;
759
- if (process.stdin.setRawMode) {
760
- process.stdin.setRawMode(false);
761
- }
762
- await Prompt.askText("Press Enter to return to Orbit...");
763
- if (process.stdin.setRawMode) {
764
- process.stdin.setRawMode(wasRaw);
765
- }
766
- this.hasWrittenStdoutSinceStop = false;
767
- }
768
- this.start(this.budgetLimit);
769
- }
770
- process.stdout.write("\x1B[?25h");
771
- return new Promise((resolve) => {
772
- this.resolveInput = resolve;
773
- this.inputBuffer = "";
774
- this.cursorPosition = 0;
775
- this.hideAutocomplete = false;
776
- this.render();
777
- const wasRaw = !!process.stdin.isRaw;
778
- if (process.stdin.setRawMode) {
779
- process.stdin.setRawMode(true);
780
- }
781
- process.stdin.resume();
782
- const onKeypress = (str, key) => {
783
- if (!this.isActive) {
784
- cleanup();
785
- return;
786
- }
787
- if (this.handleScrollInput(str, key)) {
788
- return;
789
- }
790
- if (key && key.ctrl && key.name === "c") {
791
- this.activeCommandIndex = 0;
792
- if (this.inputBuffer.length > 0) {
793
- this.inputBuffer = "";
794
- this.cursorPosition = 0;
795
- this.render();
796
- } else {
797
- if (this.ctrlCPressedOnce) {
798
- if (this.ctrlCTimeout) clearTimeout(this.ctrlCTimeout);
799
- cleanup();
800
- this.stop();
801
- process.exit(0);
802
- } else {
803
- this.ctrlCPressedOnce = true;
804
- if (this.ctrlCTimeout) clearTimeout(this.ctrlCTimeout);
805
- this.ctrlCTimeout = setTimeout(() => {
806
- this.ctrlCPressedOnce = false;
807
- this.render();
808
- }, 2e3);
809
- this.render();
810
- }
811
- }
812
- return;
813
- }
814
- if (key && (key.name === "return" || key.name === "enter")) {
815
- cleanup();
816
- process.stdout.write("\x1B[?25l");
817
- const submitted = this.inputBuffer;
818
- this.resolveInput = null;
819
- this.historyScrollOffset = 0;
820
- this.hasNewOutputWhileScrolled = false;
821
- if (submitted.trim()) {
822
- this.history.push({ role: "user", text: submitted });
823
- if (this.inputHistory[this.inputHistory.length - 1] !== submitted) {
824
- this.inputHistory.push(submitted);
825
- this.saveInputHistory();
826
- }
827
- }
828
- this.historyIndex = -1;
829
- this.inputBuffer = "";
830
- this.cursorPosition = 0;
831
- this.render();
832
- resolve(submitted);
833
- return;
834
- }
835
- if (key && key.name === "up") {
836
- if (this.inputBuffer.startsWith("/")) {
837
- const matches = this.getActiveMatches();
838
- if (matches.length > 0) {
839
- this.activeCommandIndex = (this.activeCommandIndex - 1 + matches.length) % matches.length;
840
- this.render();
841
- return;
842
- }
843
- }
844
- if (this.inputHistory.length > 0) {
845
- if (this.historyIndex === -1) {
846
- this.tempBuffer = this.inputBuffer;
847
- this.historyIndex = this.inputHistory.length - 1;
848
- } else if (this.historyIndex > 0) {
849
- this.historyIndex--;
850
- }
851
- this.inputBuffer = this.inputHistory[this.historyIndex];
852
- this.cursorPosition = this.inputBuffer.length;
853
- this.render();
854
- }
855
- return;
856
- }
857
- if (key && key.name === "down") {
858
- if (this.inputBuffer.startsWith("/")) {
859
- const matches = this.getActiveMatches();
860
- if (matches.length > 0) {
861
- this.activeCommandIndex = (this.activeCommandIndex + 1) % matches.length;
862
- this.render();
863
- return;
864
- }
865
- }
866
- if (this.historyIndex !== -1) {
867
- if (this.historyIndex < this.inputHistory.length - 1) {
868
- this.historyIndex++;
869
- this.inputBuffer = this.inputHistory[this.historyIndex];
870
- } else {
871
- this.historyIndex = -1;
872
- this.inputBuffer = this.tempBuffer || "";
873
- }
874
- this.cursorPosition = this.inputBuffer.length;
875
- this.render();
876
- }
877
- return;
878
- }
879
- if (key && key.name === "left") {
880
- if (this.cursorPosition > 0) {
881
- this.cursorPosition = previousCodePointIndex(
882
- this.inputBuffer,
883
- this.cursorPosition
884
- );
885
- this.render();
886
- }
887
- return;
888
- }
889
- if (key && key.name === "right") {
890
- if (this.cursorPosition < this.inputBuffer.length) {
891
- this.cursorPosition = nextCodePointIndex(
892
- this.inputBuffer,
893
- this.cursorPosition
894
- );
895
- this.render();
896
- } else {
897
- const sug = this.getSuggestion();
898
- if (sug) {
899
- this.inputBuffer += sug;
900
- this.cursorPosition = this.inputBuffer.length;
901
- this.render();
902
- }
903
- }
904
- return;
905
- }
906
- if (key && key.name === "tab") {
907
- if (this.inputBuffer.startsWith("/")) {
908
- const matches = this.getActiveMatches();
909
- if (matches.length > 0) {
910
- const idx = Math.min(this.activeCommandIndex, matches.length - 1);
911
- const match = matches[idx];
912
- if (match) {
913
- this.inputBuffer = match;
914
- this.cursorPosition = match.length;
915
- this.activeCommandIndex = 0;
916
- this.render();
917
- }
918
- return;
919
- }
920
- }
921
- const sug = this.getSuggestion();
922
- if (sug) {
923
- this.inputBuffer += sug;
924
- this.cursorPosition = this.inputBuffer.length;
925
- this.render();
926
- }
927
- return;
928
- }
929
- if (key && key.ctrl && key.name === "l") {
930
- this.history = [];
931
- this.render();
932
- return;
933
- }
934
- if (key && key.ctrl && key.name === "u") {
935
- this.activeCommandIndex = 0;
936
- this.inputBuffer = "";
937
- this.cursorPosition = 0;
938
- this.render();
939
- return;
940
- }
941
- if (key && key.ctrl && key.name === "w") {
942
- this.activeCommandIndex = 0;
943
- const beforeCursor = this.inputBuffer.substring(
944
- 0,
945
- this.cursorPosition
946
- );
947
- const afterCursor = this.inputBuffer.substring(this.cursorPosition);
948
- const parts = beforeCursor.trimEnd().split(/\s+/);
949
- parts.pop();
950
- const newBefore = parts.length > 0 ? parts.join(" ") + " " : "";
951
- this.inputBuffer = newBefore + afterCursor;
952
- this.cursorPosition = newBefore.length;
953
- this.render();
954
- return;
955
- }
956
- if (key && key.ctrl && key.name === "p") {
957
- this.activeCommandIndex = 0;
958
- if (!this.inputBuffer.startsWith("/")) {
959
- this.inputBuffer = "/" + this.inputBuffer;
960
- this.cursorPosition = this.inputBuffer.length;
961
- }
962
- this.render();
963
- return;
964
- }
965
- if (key && key.name === "delete") {
966
- this.activeCommandIndex = 0;
967
- this.hideAutocomplete = false;
968
- if (this.cursorPosition < this.inputBuffer.length) {
969
- const nextIndex = nextCodePointIndex(
970
- this.inputBuffer,
971
- this.cursorPosition
972
- );
973
- this.inputBuffer = this.inputBuffer.substring(0, this.cursorPosition) + this.inputBuffer.substring(nextIndex);
974
- this.render();
975
- }
976
- return;
977
- }
978
- if (key && key.name === "backspace") {
979
- this.activeCommandIndex = 0;
980
- this.hideAutocomplete = false;
981
- if (this.cursorPosition > 0) {
982
- const previousIndex = previousCodePointIndex(
983
- this.inputBuffer,
984
- this.cursorPosition
985
- );
986
- this.inputBuffer = this.inputBuffer.substring(0, previousIndex) + this.inputBuffer.substring(this.cursorPosition);
987
- this.cursorPosition = previousIndex;
988
- }
989
- } else if (key && key.name === "escape") {
990
- this.activeCommandIndex = 0;
991
- this.hideAutocomplete = true;
992
- } else if (str && (!key || !key.ctrl && !key.meta && key.name !== "tab")) {
993
- this.activeCommandIndex = 0;
994
- this.hideAutocomplete = false;
995
- this.inputBuffer = this.inputBuffer.substring(0, this.cursorPosition) + str + this.inputBuffer.substring(this.cursorPosition);
996
- this.cursorPosition += str.length;
997
- }
998
- this.render();
999
- };
1000
- const cleanup = () => {
1001
- process.stdin.removeListener("keypress", onKeypress);
1002
- if (process.stdin.setRawMode) {
1003
- process.stdin.setRawMode(wasRaw);
1004
- }
1005
- process.stdin.pause();
1006
- };
1007
- process.stdin.on("keypress", onKeypress);
1008
- });
1009
- }
1010
- startAttempt(attempt) {
1011
- this.currentAttempt = attempt;
1012
- this.attemptStartTime = Date.now();
1013
- this.firstDeltaTime = 0;
1014
- this.isThinking = true;
1015
- this.thoughtElapsed = 0;
1016
- this.currentThinking = "";
1017
- this.history.push({
1018
- role: "assistant",
1019
- text: "",
1020
- attempt
1021
- });
1022
- if (this.thoughtTimer) clearInterval(this.thoughtTimer);
1023
- this.thoughtTimer = setInterval(() => {
1024
- if (this.isThinking) {
1025
- this.thoughtElapsed += 100;
1026
- this.render();
1027
- }
1028
- }, 100);
1029
- this.render();
1030
- }
1031
- handleModelDelta(text) {
1032
- const lastAsst = [...this.history].reverse().find((m) => m.role === "assistant");
1033
- if (lastAsst) {
1034
- if (this.isThinking && text.trim().length > 0) {
1035
- this.isThinking = false;
1036
- if (this.thoughtTimer) {
1037
- clearInterval(this.thoughtTimer);
1038
- this.thoughtTimer = null;
1039
- }
1040
- lastAsst.thoughtTime = Date.now() - this.attemptStartTime;
1041
- }
1042
- lastAsst.text += text;
1043
- this.throttleRender();
1044
- }
1045
- }
1046
- throttleRender() {
1047
- const now = Date.now();
1048
- const minInterval = 60;
1049
- if (now - this.lastRenderTime >= minInterval) {
1050
- if (this.renderTimeout) {
1051
- clearTimeout(this.renderTimeout);
1052
- this.renderTimeout = null;
1053
- }
1054
- this.lastRenderTime = now;
1055
- this.render();
1056
- } else if (!this.renderPending) {
1057
- this.renderPending = true;
1058
- this.renderTimeout = setTimeout(
1059
- () => {
1060
- this.renderPending = false;
1061
- this.lastRenderTime = Date.now();
1062
- this.render();
1063
- },
1064
- minInterval - (now - this.lastRenderTime)
1065
- );
1066
- }
1067
- }
1068
- finishAttempt() {
1069
- const lastAsst = [...this.history].reverse().find((m) => m.role === "assistant");
1070
- if (lastAsst) {
1071
- this.isThinking = false;
1072
- if (this.thoughtTimer) {
1073
- clearInterval(this.thoughtTimer);
1074
- this.thoughtTimer = null;
1075
- }
1076
- lastAsst.totalTime = Date.now() - this.attemptStartTime;
1077
- if (lastAsst.thoughtTime === void 0) {
1078
- lastAsst.thoughtTime = lastAsst.totalTime;
1079
- }
1080
- this.render();
1081
- }
1082
- }
1083
- render(forceFull = false) {
1084
- const columns = Math.max(40, process.stdout.columns || 80);
1085
- const rows = Math.max(10, process.stdout.rows || 24);
1086
- const morandi = {
1087
- user: (s) => `\x1B[38;2;142;163;175m${s}\x1B[0m`,
1088
- userBold: (s) => `\x1B[1;38;2;142;163;175m${s}\x1B[0m`,
1089
- asst: (s) => `\x1B[38;2;143;153;129m${s}\x1B[0m`,
1090
- asstBold: (s) => `\x1B[1;38;2;143;153;129m${s}\x1B[0m`,
1091
- cyan: (s) => `\x1B[38;2;142;163;175m${s}\x1B[0m`,
1092
- accent: (s) => `\x1B[38;2;200;170;120m${s}\x1B[0m`,
1093
- completed: (s) => `\x1B[38;2;135;165;130m${s}\x1B[0m`,
1094
- failed: (s) => `\x1B[38;2;180;120;120m${s}\x1B[0m`,
1095
- warn: (s) => `\x1B[38;2;180;140;130m${s}\x1B[0m`,
1096
- white: (s) => `\x1B[38;2;230;225;215m${s}\x1B[0m`,
1097
- whiteBold: (s) => `\x1B[1;38;2;230;225;215m${s}\x1B[0m`,
1098
- gray: (s) => `\x1B[38;2;150;150;150m${s}\x1B[0m`,
1099
- dim: (s) => `\x1B[2;38;2;110;110;110m${s}\x1B[0m`
1100
- };
1101
- const isWaitingInput = this.resolveInput !== null;
1102
- const isInputActive = isWaitingInput || this.thinkingKeypressListener !== null;
1103
- const hasInput = isInputActive && this.inputBuffer.length > 0;
1104
- const placeholder = isWaitingInput ? "Ask anything..." : "";
1105
- const budgetPct = Math.min(
1106
- 100,
1107
- Math.round(this.sessionCost / (this.budgetLimit || 10) * 100)
1108
- ) + "%";
1109
- const boxWidth = columns - 4;
1110
- const wrapWidth = Math.max(8, boxWidth - 14);
1111
- const fullText = hasInput ? this.inputBuffer : placeholder;
1112
- const wrappedLines = this.wrapText(fullText, wrapWidth);
1113
- const formattedLines = hasInput ? this.formatWrappedLines(wrappedLines, this.inputBuffer.length) : wrappedLines.map((line) => morandi.dim(line));
1114
- const boxContentLines = [];
1115
- const topBorder = morandi.gray(" \u256D" + "\u2500".repeat(boxWidth - 4) + "\u256E");
1116
- const bottomBorder = morandi.gray(" \u2570" + "\u2500".repeat(boxWidth - 4) + "\u256F");
1117
- boxContentLines.push(topBorder);
1118
- for (let i = 0; i < formattedLines.length; i++) {
1119
- const prefix = i === 0 ? "orbit > " : " ";
1120
- const rawLine = wrappedLines[i];
1121
- const visualWidth = this.getStringWidth(rawLine);
1122
- const remainingSpaces = wrapWidth - visualWidth;
1123
- const padding = " ".repeat(remainingSpaces);
1124
- const lineContent = morandi.gray(" \u2502 ") + morandi.userBold(prefix) + formattedLines[i] + padding + morandi.gray(" \u2502");
1125
- boxContentLines.push(lineContent);
1126
- }
1127
- boxContentLines.push(bottomBorder);
1128
- const bottomLines = [];
1129
- if (isWaitingInput) {
1130
- const matches = this.getActiveMatches();
1131
- if (matches.length > 0) {
1132
- const isZh = this.config?.language === "zh";
1133
- const cmdHints = isZh ? {
1134
- "/help": "\u67E5\u770B\u7CFB\u7EDF\u547D\u4EE4\u7684\u8BE6\u7EC6\u5E2E\u52A9\u4E0E\u6307\u5357",
1135
- "/status": "\u5B9E\u65F6\u8BCA\u65AD\u5F53\u524D\u4F1A\u8BDD\u7684\u5065\u5EB7\u4E0E\u8D44\u6E90\u72B6\u6001",
1136
- "/config": "\u67E5\u770B\u4E0E\u4FEE\u6539\u672C\u5730/\u5168\u5C40\u7684\u8FD0\u884C\u914D\u7F6E\u53C2\u6570",
1137
- "/model": "\u52A8\u6001\u5207\u6362\u6B63\u5728\u4F7F\u7528\u7684 AI \u8BED\u8A00\u5927\u6A21\u578B",
1138
- "/chat": "\u4F1A\u8BDD\u7BA1\u7406\u5668 (\u652F\u6301\u5B50\u547D\u4EE4: list, new, delete, switch)",
1139
- "/chat list": "\u5C55\u793A\u6240\u6709\u5DF2\u4FDD\u5B58\u7684\u5386\u53F2\u5BF9\u8BDD\u4F1A\u8BDD",
1140
- "/chat ls": "\u5C55\u793A\u6240\u6709\u5DF2\u4FDD\u5B58\u7684\u5386\u53F2\u5BF9\u8BDD\u4F1A\u8BDD",
1141
- "/chat new": "\u542F\u52A8\u5E76\u521B\u5EFA\u4E00\u4E2A\u5168\u65B0\u7684\u5BF9\u8BDD\u4F1A\u8BDD",
1142
- "/chat delete": "\u79FB\u9664\u4E0D\u9700\u8981\u7684\u5386\u53F2\u5BF9\u8BDD\u4F1A\u8BDD",
1143
- "/chat rm": "\u79FB\u9664\u4E0D\u9700\u8981\u7684\u5386\u53F2\u5BF9\u8BDD\u4F1A\u8BDD",
1144
- "/chat switch": "\u5FEB\u901F\u5207\u6362\u5230\u6307\u5B9A\u7684\u5386\u53F2\u5BF9\u8BDD\u4F1A\u8BDD",
1145
- "/commit": "\u81EA\u52A8\u6682\u5B58\u5DE5\u4F5C\u533A\u4FEE\u6539\u5E76\u751F\u6210 Git \u63D0\u4EA4",
1146
- "/diff": "\u53EF\u89C6\u5316\u6BD4\u5BF9\u5F53\u524D\u5DE5\u4F5C\u533A\u7684\u6240\u6709\u4EE3\u7801\u53D8\u66F4",
1147
- "/test": "\u81EA\u52A8\u5316\u8FD0\u884C\u9879\u76EE\u4E2D\u7684\u5355\u5143\u6D4B\u8BD5\u7EC4\u4EF6",
1148
- "/add": "\u5C06\u9009\u5B9A\u7684\u6587\u4EF6\u6216\u4EE3\u7801\u8D44\u4EA7\u6DFB\u52A0\u5230\u5F53\u524D\u4E0A\u4E0B\u6587",
1149
- "/drop": "\u4ECE\u5F53\u524D\u5BF9\u8BDD\u4E0A\u4E0B\u6587\u4E2D\u79FB\u9664\u9009\u5B9A\u7684\u8D44\u4EA7",
1150
- "/context": "\u67E5\u770B\u5E76\u6DF1\u5EA6\u5206\u6790\u5F53\u524D\u4E0A\u4E0B\u6587\u4E2D\u7684\u6587\u4EF6\u4E0E\u4EE3\u7801\u8D44\u4EA7",
1151
- "/exit": "\u5B89\u5168\u7EC8\u6B62\u5E76\u5173\u95ED\u5F53\u524D\u7684\u7EC8\u7AEF\u4F1A\u8BDD",
1152
- "/quit": "\u5B89\u5168\u7EC8\u6B62\u5E76\u5173\u95ED\u5F53\u524D\u7684\u7EC8\u7AEF\u4F1A\u8BDD",
1153
- "/rollback": "\u4E00\u952E\u64A4\u9500\u5E76\u56DE\u6EDA\u81EA\u4F1A\u8BDD\u542F\u52A8\u4EE5\u6765\u7684\u6240\u6709\u4FEE\u6539",
1154
- "/timeline": "\u67E5\u770B\u5F53\u524D\u4F1A\u8BDD\u53EF\u6062\u590D\u7684\u6587\u4EF6\u68C0\u67E5\u70B9\u65F6\u95F4\u7EBF",
1155
- "/rewind": "\u5C06\u5DE5\u4F5C\u533A\u56DE\u9000\u5230\u6307\u5B9A\u7684\u6301\u4E45\u5316\u68C0\u67E5\u70B9",
1156
- "/clear": "\u6E05\u7A7A\u5F53\u524D\u7EC8\u7AEF\u5C4F\u5E55\u7684\u6240\u6709\u5386\u53F2\u4F1A\u8BDD\u6E32\u67D3",
1157
- "/compact": "\u667A\u80FD\u538B\u7F29\u5F53\u524D\u5BF9\u8BDD\u5386\u53F2\u4EE5\u8282\u7701 Prompt \u8BCD\u91CF",
1158
- "/history": "\u6D4F\u89C8\u5E76\u91CD\u653E\u6267\u884C\u8FC7\u7684\u5386\u53F2\u547D\u4EE4\u5217\u8868",
1159
- "/edit": "\u4EA4\u4E92\u5F0F\u7F16\u8F91\u5DE5\u4F5C\u533A\u4E0E\u4EE3\u7406\u7684\u6838\u5FC3\u914D\u7F6E\u6587\u4EF6",
1160
- "/inspect": "\u6DF1\u5EA6\u5206\u6790\u5E76\u68C0\u67E5\u5F53\u524D\u5DE5\u4F5C\u533A\u7684\u5DE5\u7A0B\u7ED3\u6784",
1161
- "/doc": "\u4E3A\u5DE5\u4F5C\u533A\u4EE3\u7801\u81EA\u52A8\u5206\u6790\u5E76\u751F\u6210 JSDoc \u6587\u6863",
1162
- "/diagnose": "\u667A\u80FD\u626B\u63CF\u5E76\u4E00\u952E\u4FEE\u590D\u5DE5\u4F5C\u533A\u4E2D\u7684\u6784\u5EFA/\u7F16\u8BD1\u9519\u8BEF",
1163
- "/resolve": "\u81EA\u52A8\u68C0\u6D4B\u5E76\u534A\u81EA\u52A8\u89E3\u51B3\u5DE5\u4F5C\u533A\u4E2D\u7684\u4EE3\u7801\u5408\u5E76\u51B2\u7A81",
1164
- "/references": "\u5FEB\u901F\u67E5\u627E\u6307\u5B9A\u7B26\u53F7/\u7C7B/\u51FD\u6570\u5728\u5DE5\u4F5C\u533A\u4E2D\u7684\u5F15\u7528",
1165
- "/run": "\u5728\u5916\u90E8\u7EC8\u7AEF\u6C99\u7BB1\u4E2D\u76F4\u63A5\u6267\u884C Shell \u547D\u4EE4",
1166
- "/grep": "\u5728\u5DE5\u4F5C\u533A\u6587\u4EF6\u5185\u5BB9\u4E2D\u5168\u5C40\u68C0\u7D22\u7279\u5B9A\u5B57\u7B26\u4E32/\u6B63\u5219\u8868\u8FBE\u5F0F",
1167
- "/language": "\u4E00\u952E\u5728\u82F1\u6587\u4E0E\u4E2D\u6587\u4E4B\u95F4\u5207\u6362\u7EC8\u7AEF\u663E\u793A\u8BED\u8A00",
1168
- "/api": "\u4EA4\u4E92\u5F0F\u914D\u7F6E\u4E0E\u6D4B\u8BD5\u6A21\u578B\u63D0\u4F9B\u5546\u7684 API \u5BC6\u94A5\u53CA\u5730\u5740",
1169
- "/register": "\u4E3A\u4EE3\u7406\u8FD0\u884C\u65F6\u52A8\u6001\u6CE8\u518C\u5E76\u6302\u8F7D\u65B0\u7684\u5916\u90E8\u5DE5\u5177",
1170
- "/fork": "\u5206\u652F/\u590D\u523B\u5F53\u524D\u4F1A\u8BDD\u5230\u65B0\u4F1A\u8BDD",
1171
- "/mode": "\u52A8\u6001\u5207\u6362\u7CFB\u7EDF\u5B89\u5168\u786E\u8BA4\u6A21\u5F0F (strict, normal, auto, plan)",
1172
- "/ask": "\u4E00\u952E\u5207\u6362\u81F3 strict \u5B89\u5168\u6A21\u5F0F (\u53EA\u8BFB/\u9AD8\u5B89\u5168\u7EA7)",
1173
- "/code": "\u4E00\u952E\u5207\u6362\u81F3 normal \u5B89\u5168\u6A21\u5F0F (\u9ED8\u8BA4\u53EF\u7F16\u8F91\u6A21\u5F0F)",
1174
- "/copy": "\u62F7\u8D1D AI \u7684\u4E0A\u4E00\u6761\u56DE\u590D\u5230\u7CFB\u7EDF\u526A\u8D34\u677F",
1175
- "/copy-context": "\u62F7\u8D1D\u5F53\u524D\u6D3B\u52A8\u4E0A\u4E0B\u6587\u6587\u4EF6\u5217\u8868\u5230\u7CFB\u7EDF\u526A\u8D34\u677F",
1176
- "/git": "\u5728\u6C99\u7BB1\u7EC8\u7AEF\u4E2D\u76F4\u63A5\u6267\u884C Git \u547D\u4EE4",
1177
- "/tokens": "\u5C55\u793A\u5F53\u524D\u4F1A\u8BDD\u8BE6\u7EC6\u7684 Token \u4F7F\u7528\u91CF\u4E0E\u4F30\u7B97\u6210\u672C",
1178
- "/read-only": "\u6DFB\u52A0\u6587\u4EF6\u5230\u5F53\u524D\u4E0A\u4E0B\u6587\u4E3A\u53EA\u8BFB\u53C2\u8003\u8D44\u6599",
1179
- "/readonly": "\u6DFB\u52A0\u6587\u4EF6\u5230\u5F53\u524D\u4E0A\u4E0B\u6587\u4E3A\u53EA\u8BFB\u53C2\u8003\u8D44\u6599",
1180
- "/btw": "\u95EE\u4E00\u4E2A\u5FEB\u6377\u95EE\u9898\u800C\u4E0D\u6C61\u67D3\u5F53\u524D\u4F1A\u8BDD\u7684\u4E0A\u4E0B\u6587\u5386\u53F2",
1181
- "/memory": "\u67E5\u770B\u9879\u76EE\u672C\u5730\u7684 AGENTS.md \u89C4\u5219\u4E0E\u8BB0\u5FC6\u6587\u4EF6",
1182
- "/commands": "\u5217\u51FA\u9879\u76EE\u7EA7\u4E0E\u7528\u6237\u7EA7\u81EA\u5B9A\u4E49\u63D0\u793A\u547D\u4EE4",
1183
- "/new": "\u521B\u5EFA\u4E00\u4E2A\u5168\u65B0\u7684\u5BF9\u8BDD\u4F1A\u8BDD (\u5FEB\u6377\u952E)",
1184
- "/reset": "\u91CD\u7F6E\u5F53\u524D\u4F1A\u8BDD\u5386\u53F2\u5F00\u59CB\u65B0\u5BF9\u8BDD (\u5FEB\u6377\u952E)",
1185
- "/delete": "\u5220\u9664\u6307\u5B9A\u4F1A\u8BDD\u6216\u5F39\u51FA\u5220\u9664\u83DC\u5355",
1186
- "/rm": "\u5220\u9664\u6307\u5B9A\u4F1A\u8BDD\u6216\u5F39\u51FA\u5220\u9664\u83DC\u5355",
1187
- "/del": "\u5220\u9664\u6307\u5B9A\u4F1A\u8BDD\u6216\u5F39\u51FA\u5220\u9664\u83DC\u5355"
1188
- } : {
1189
- "/help": "Display detailed help and commands reference",
1190
- "/status": "Diagnose session health, token usage, and limits",
1191
- "/config": "View and edit local or global configuration",
1192
- "/model": "Switch the active language model dynamically",
1193
- "/chat": "Manage chat sessions (subcommands: list, new, delete, switch)",
1194
- "/chat list": "List all saved agent chat sessions",
1195
- "/chat ls": "List all saved agent chat sessions",
1196
- "/chat new": "Initialize and start a fresh chat session",
1197
- "/chat delete": "Remove a saved session from the manager",
1198
- "/chat rm": "Remove a saved session from the manager",
1199
- "/chat switch": "Switch focus to a specific saved session",
1200
- "/commit": "Automatically stage changes and create Git commit",
1201
- "/diff": "Interactively view file diffs in the workspace",
1202
- "/test": "Run workspace test suites automatically",
1203
- "/add": "Add files or code symbols to prompt context",
1204
- "/drop": "Remove selected assets from prompt context",
1205
- "/context": "Inspect the assembled active context package and assets",
1206
- "/exit": "Safely terminate and exit the active session",
1207
- "/quit": "Safely terminate and exit the active session",
1208
- "/rollback": "Revert all source edits made during this session",
1209
- "/timeline": "Inspect the persistent checkpoint timeline",
1210
- "/rewind": "Rewind the workspace to a selected checkpoint",
1211
- "/clear": "Clear the terminal screen and scrollback buffer",
1212
- "/compact": "Compress chat history to optimize token usage",
1213
- "/history": "View and replay previously executed commands",
1214
- "/edit": "Configure agent options via interactive editor",
1215
- "/inspect": "Inspect workspace structure and boundary status",
1216
- "/doc": "Generate high-quality documentation for codebase symbols",
1217
- "/diagnose": "Scan workspace and diagnose/fix build issues",
1218
- "/resolve": "Scan and help resolve Git merge conflicts",
1219
- "/references": "Find references and usages of a codebase symbol",
1220
- "/run": "Execute a shell command directly in the terminal sandbox",
1221
- "/grep": "Perform global search for patterns across workspace files",
1222
- "/language": "Switch display language between English & Chinese",
1223
- "/api": "Configure base URL and credentials for APIs",
1224
- "/register": "Register new runtime tools dynamically",
1225
- "/fork": "Fork the current session history into a branch",
1226
- "/mode": "Switch permission mode (strict, normal, auto, plan)",
1227
- "/ask": "Shortcut for strict read-only mode",
1228
- "/code": "Shortcut for normal default editing mode",
1229
- "/copy": "Copy last assistant response to clipboard",
1230
- "/copy-context": "Copy active context files list to clipboard",
1231
- "/git": "Execute a git command in the sandbox",
1232
- "/tokens": "Display session token usage and details",
1233
- "/read-only": "Add files to context as read-only references",
1234
- "/readonly": "Add files to context as read-only references",
1235
- "/btw": "Ask a quick side-question without polluting active history",
1236
- "/memory": "View the workspace memory / AGENTS.md guidelines",
1237
- "/commands": "List project and user custom prompt commands",
1238
- "/new": "Create a brand new chat session (shortcut)",
1239
- "/reset": "Reset history and start a fresh session (shortcut)",
1240
- "/delete": "Delete a session by ID/idx or open deletion menu",
1241
- "/rm": "Delete a session by ID/idx or open deletion menu",
1242
- "/del": "Delete a session by ID/idx or open deletion menu"
1243
- };
1244
- const maxVisible = 5;
1245
- this.activeCommandIndex = Math.min(
1246
- Math.max(0, this.activeCommandIndex),
1247
- matches.length - 1
1248
- );
1249
- let startIdx = 0;
1250
- if (this.activeCommandIndex >= maxVisible) {
1251
- startIdx = this.activeCommandIndex - maxVisible + 1;
1252
- }
1253
- const visibleMatches = matches.slice(startIdx, startIdx + maxVisible);
1254
- const maxPopupWidth = Math.min(86, Math.max(30, columns - 8));
1255
- const formattedMatches = visibleMatches.map((cmd) => {
1256
- const isSelected = visibleMatches.indexOf(cmd) + startIdx === this.activeCommandIndex;
1257
- const prefix = isSelected ? " \u276F " : " ";
1258
- const leftPart = `${prefix}${cmd}`;
1259
- const leftW = this.getStringWidth(leftPart);
1260
- let hint = cmdHints[cmd] || "";
1261
- if (!hint) {
1262
- if (cmd.startsWith("/chat delete ") || cmd.startsWith("/chat rm ")) {
1263
- hint = isZh ? "\u5220\u9664\u8BE5\u4F1A\u8BDD" : "Delete this session";
1264
- } else if (cmd.startsWith("/chat switch ")) {
1265
- hint = isZh ? "\u5207\u6362\u5230\u8BE5\u4F1A\u8BDD" : "Switch to this session";
1266
- } else if (cmd.startsWith("/fork switch ")) {
1267
- hint = isZh ? "\u5207\u6362\u5230\u6307\u5B9A\u7684\u4F1A\u8BDD\u5206\u652F" : "Switch to specified session branch";
1268
- } else if (cmd === "/fork tree") {
1269
- hint = isZh ? "\u5C55\u793A\u6240\u6709\u4F1A\u8BDD\u5206\u652F\u7684\u6811\u72B6\u5173\u7CFB" : "Display session branch lineage tree";
1270
- }
1271
- }
1272
- let rightPart = "";
1273
- let rightW = 0;
1274
- if (hint) {
1275
- const rawRightPart = hint;
1276
- const rawRightW = this.getStringWidth(rawRightPart);
1277
- const maxRightW = maxPopupWidth - leftW - 2;
1278
- if (rawRightW <= maxRightW) {
1279
- rightPart = rawRightPart;
1280
- rightW = rawRightW;
1281
- } else if (maxRightW >= 5) {
1282
- const maxHintW = maxRightW - 3;
1283
- const truncatedHint = this.truncateToWidth(hint, maxHintW);
1284
- rightPart = `${truncatedHint}...`;
1285
- rightW = this.getStringWidth(rightPart);
1286
- }
1287
- }
1288
- return { cmd, isSelected, leftPart, leftW, rightPart, rightW };
1289
- });
1290
- const popupWidth = maxPopupWidth;
1291
- bottomLines.push(morandi.gray(" \u256D" + "\u2500".repeat(popupWidth) + "\u256E"));
1292
- for (const fm of formattedMatches) {
1293
- const spacingWidth = popupWidth - fm.leftW - fm.rightW;
1294
- const spacing2 = " ".repeat(spacingWidth);
1295
- const formattedLine = fm.isSelected ? morandi.accent(fm.leftPart + spacing2) + morandi.dim(fm.rightPart) : morandi.gray(fm.leftPart + spacing2) + morandi.dim(fm.rightPart);
1296
- bottomLines.push(
1297
- morandi.gray(" \u2502") + formattedLine + morandi.gray("\u2502")
1298
- );
1299
- }
1300
- bottomLines.push(morandi.gray(" \u2570" + "\u2500".repeat(popupWidth) + "\u256F"));
1301
- }
1302
- }
1303
- bottomLines.push(...boxContentLines);
1304
- const mode = this.permissionsMode.toUpperCase();
1305
- let statusText = "";
1306
- if (this.historyScrollOffset > 0) {
1307
- const newOutput = this.hasNewOutputWhileScrolled ? this.config?.language === "zh" ? " \xB7 \u6709\u65B0\u8F93\u51FA" : " \xB7 new output" : "";
1308
- statusText = morandi.accent(
1309
- this.config?.language === "zh" ? `\u2191 \u5386\u53F2 ${this.historyScrollOffset} \u884C` : `\u2191 history ${this.historyScrollOffset} lines`
1310
- ) + morandi.warn(newOutput);
1311
- } else if (this.ctrlCPressedOnce) {
1312
- statusText = morandi.warn("Press Ctrl+C again to exit");
1313
- } else {
1314
- const cleanModel2 = this.modelNameGetter().split("/").pop() || this.modelNameGetter();
1315
- statusText = morandi.completed("\u25CF") + " " + morandi.white(`${mode} MODE`) + morandi.gray(" \xB7 ") + morandi.accent(cleanModel2) + morandi.gray(" \xB7 ") + morandi.dim(`attempt: ${this.currentAttempt || 1}`);
1316
- }
1317
- let keybindings = this.historyScrollOffset > 0 ? morandi.gray("[End]") + morandi.dim(this.config?.language === "zh" ? " \u8FD4\u56DE\u5E95\u90E8" : " Bottom") : columns >= 88 ? [
1318
- morandi.gray("[^C]") + morandi.dim(" Cancel"),
1319
- morandi.gray("[^L]") + morandi.dim(" Clear"),
1320
- morandi.gray("[^P]") + morandi.dim(" Cmds")
1321
- ].join(" ") : columns >= 62 ? [
1322
- morandi.gray("[^C]") + morandi.dim(" Cancel"),
1323
- morandi.gray("[^P]") + morandi.dim(" Cmds")
1324
- ].join(" ") : morandi.gray("[^C]") + morandi.dim(" Exit");
1325
- let statusTextLength = this.getStringWidth(statusText);
1326
- let keybindingsLength = this.getStringWidth(keybindings);
1327
- if (statusTextLength + keybindingsLength > columns - 8) {
1328
- const compactMode = `${mode.slice(0, 6)} \xB7 ${this.currentAttempt || 1}`;
1329
- statusText = morandi.completed("\u25CF") + " " + morandi.white(compactMode);
1330
- statusTextLength = this.getStringWidth(statusText);
1331
- }
1332
- if (statusTextLength + keybindingsLength > columns - 8) {
1333
- keybindings = morandi.gray("[^C]");
1334
- keybindingsLength = this.getStringWidth(keybindings);
1335
- }
1336
- const spacing = Math.max(
1337
- 1,
1338
- columns - 6 - statusTextLength - keybindingsLength
1339
- );
1340
- bottomLines.push(" " + statusText + " ".repeat(spacing) + keybindings);
1341
- const bottomHeight = bottomLines.length;
1342
- const cleanModel = this.modelNameGetter().replace(/\[1m\]/g, "");
1343
- const gitSummary = this.getGitSummary();
1344
- const gitBranch = gitSummary.branch;
1345
- const logoLines = [
1346
- `\x1B[38;2;142;163;175m /\\___/\\ \x1B[0m`,
1347
- `\x1B[38;2;142;163;175m ( o.o ) \x1B[0m`,
1348
- `\x1B[38;2;142;163;175m / >\x1B[38;2;230;110;110m\u2665\x1B[38;2;142;163;175m< \\ \x1B[0m`,
1349
- `\x1B[38;2;142;163;175m (__/ \\__) \x1B[0m`
1350
- ];
1351
- const w0 = this.getStringWidth(logoLines[0]);
1352
- const w1 = this.getStringWidth(logoLines[1]);
1353
- const w2 = this.getStringWidth(logoLines[2]);
1354
- const w3 = this.getStringWidth(logoLines[3]);
1355
- const maxLogoW = Math.max(w0, w1, w2, w3);
1356
- const pad0 = " ".repeat(maxLogoW - w0);
1357
- const pad1 = " ".repeat(maxLogoW - w1);
1358
- const pad2 = " ".repeat(maxLogoW - w2);
1359
- const pad3 = " ".repeat(maxLogoW - w3);
1360
- const shortCwd = this.cwd.replace(/\\/g, "/");
1361
- const availableWidth = Math.max(10, columns - 2 - maxLogoW - 2 - 20 - 2);
1362
- let branchText = "";
1363
- if (gitBranch !== "no-git") {
1364
- const stats = [];
1365
- if (gitSummary.added > 0) stats.push(`+${gitSummary.added}`);
1366
- if (gitSummary.modified > 0) stats.push(`~${gitSummary.modified}`);
1367
- if (gitSummary.deleted > 0) stats.push(`-${gitSummary.deleted}`);
1368
- const gitStatusStats = stats.length > 0 ? ` (${stats.join(" ")})` : "";
1369
- const maxBranchLen = 12;
1370
- const displayBranch = gitBranch.length > maxBranchLen ? gitBranch.substring(0, maxBranchLen - 3) + "..." : gitBranch;
1371
- branchText = ` ${morandi.dim("\xB7")} branch:${morandi.asst(displayBranch)}${gitStatusStats ? morandi.accent(gitStatusStats) : ""}`;
1372
- }
1373
- const truncatePath = (p, maxLength) => {
1374
- if (p.length <= maxLength) return p;
1375
- const parts = p.split("/");
1376
- if (parts.length <= 1) {
1377
- return p.substring(p.length - maxLength);
1378
- }
1379
- const lastPart = parts[parts.length - 1];
1380
- if (lastPart.length + 4 > maxLength) {
1381
- return "..." + lastPart.substring(lastPart.length - (maxLength - 3));
1382
- }
1383
- let result = lastPart;
1384
- for (let i = parts.length - 2; i >= 0; i--) {
1385
- const nextResult = parts[i] + "/" + result;
1386
- if (nextResult.length + 4 > maxLength) {
1387
- return ".../" + result;
1388
- }
1389
- result = nextResult;
1390
- }
1391
- return result;
1392
- };
1393
- const pathLabel = "workspace: ";
1394
- const branchWidth = gitBranch !== "no-git" ? 5 + Math.min(12, gitBranch.length) : 0;
1395
- const maxPathWidth = Math.max(
1396
- 6,
1397
- availableWidth - pathLabel.length - branchWidth
1398
- );
1399
- const displayPath = truncatePath(shortCwd, maxPathWidth);
1400
- const hitRate = this.totalInputTokens > 0 ? this.totalCacheReadTokens / this.totalInputTokens * 100 : 0;
1401
- let cacheText = `[cache] hit: ${hitRate.toFixed(0)}% (${(this.totalCacheReadTokens / 1e3).toFixed(0)}k/${(this.totalInputTokens / 1e3).toFixed(0)}k tokens)`;
1402
- if (this.getStringWidth(cacheText) > availableWidth) {
1403
- cacheText = `[cache] hit: ${hitRate.toFixed(0)}% (${(this.totalCacheReadTokens / 1e3).toFixed(0)}k/${(this.totalInputTokens / 1e3).toFixed(0)}k)`;
1404
- }
1405
- if (this.getStringWidth(cacheText) > availableWidth) {
1406
- cacheText = `[cache] hit: ${hitRate.toFixed(0)}%`;
1407
- }
1408
- const cleanHeaderModel = cleanModel.split("/").pop() || cleanModel;
1409
- let headerLines;
1410
- if (columns < 76) {
1411
- const modelWidth = Math.max(8, columns - 16);
1412
- const displayModel = this.getStringWidth(cleanHeaderModel) > modelWidth ? this.truncateToWidth(cleanHeaderModel, modelWidth - 3) + "..." : cleanHeaderModel;
1413
- const compactPath = truncatePath(shortCwd, Math.max(8, columns - 15));
1414
- const compactBranch = gitBranch === "no-git" ? "" : ` \xB7 ${gitBranch.length > 12 ? gitBranch.slice(0, 9) + "..." : gitBranch}`;
1415
- headerLines = [
1416
- ` ${morandi.whiteBold("O R B I T")} ${morandi.dim("\xB7")} ${morandi.accent(displayModel)}`,
1417
- ` ${morandi.dim("workspace:")} ${morandi.gray(compactPath)}`,
1418
- ` ${morandi.dim(cacheText)}${morandi.dim(compactBranch)}`
1419
- ];
1420
- } else {
1421
- const headerLine1 = ` ${logoLines[0]}${pad0} ${morandi.whiteBold("O R B I T")} ${morandi.dim("\xB7")} ${morandi.accent(cleanHeaderModel)}`;
1422
- const headerLine2 = ` ${logoLines[1]}${pad1} ${" ".repeat(20)}${morandi.dim("workspace:")} ${morandi.gray(displayPath)}${branchText}`;
1423
- const headerLine3 = ` ${logoLines[2]}${pad2} ${" ".repeat(20)}${morandi.dim(cacheText)}`;
1424
- const headerLine4 = ` ${logoLines[3]}${pad3}`;
1425
- headerLines = [headerLine1, headerLine2, headerLine3, headerLine4];
1426
- }
1427
- let renderedLines = [];
1428
- const turns = [];
1429
- let currentTurn = null;
1430
- for (const msg of this.history) {
1431
- if (msg.role === "user") {
1432
- if (currentTurn) {
1433
- turns.push(currentTurn);
1434
- }
1435
- currentTurn = { user: msg, system: [] };
1436
- } else if (msg.role === "assistant") {
1437
- if (currentTurn) {
1438
- currentTurn.assistant = msg;
1439
- }
1440
- } else if (msg.role === "system") {
1441
- if (currentTurn) {
1442
- currentTurn.system.push(msg);
1443
- }
1444
- }
1445
- }
1446
- if (currentTurn) {
1447
- turns.push(currentTurn);
1448
- }
1449
- const lastAsst = [...this.history].reverse().find((m) => m.role === "assistant");
1450
- const uBorder = " ";
1451
- const aBorder = " ";
1452
- for (const turn of turns) {
1453
- renderedLines.push(" " + morandi.userBold("\u{1F464} User"));
1454
- renderedLines.push(uBorder);
1455
- const userLines = turn.user.text.split("\n");
1456
- const wrappedUserLines = [];
1457
- for (const line of userLines) {
1458
- wrappedUserLines.push(...this.wrapLine(line, columns - 10));
1459
- }
1460
- for (const line of wrappedUserLines) {
1461
- renderedLines.push(uBorder + morandi.user(line));
1462
- }
1463
- renderedLines.push(uBorder);
1464
- renderedLines.push("");
1465
- if (turn.assistant) {
1466
- const asstLines = [];
1467
- const systemLines = [];
1468
- for (const sys of turn.system) {
1469
- let text = sys.text.trim();
1470
- if (text.startsWith("\u2713 Success") || text.startsWith("\u2716 Failed") || text.startsWith("\u2714 Success")) {
1471
- continue;
1472
- }
1473
- if (text.startsWith("\u2714")) {
1474
- text = morandi.completed("completed") + morandi.gray(text.substring(1));
1475
- } else if (text.startsWith("\u2716")) {
1476
- text = morandi.failed("failed") + morandi.gray(text.substring(1));
1477
- } else if (text.startsWith("\u25CF")) {
1478
- text = morandi.cyan("\u25CF") + morandi.gray(text.substring(1));
1479
- } else if (text.startsWith("\u2726")) {
1480
- text = morandi.cyan("\u2726") + morandi.gray(text.substring(1));
1481
- } else if (text.startsWith("\u26A0")) {
1482
- text = morandi.warn("\u26A0") + morandi.gray(text.substring(1));
1483
- } else {
1484
- text = morandi.cyan("\u2726") + " " + morandi.gray(text);
1485
- }
1486
- systemLines.push(text);
1487
- }
1488
- const isThinkingNow = turn.assistant === lastAsst && this.isThinking;
1489
- const thoughtTimeVal = isThinkingNow ? this.thoughtElapsed : turn.assistant.thoughtTime;
1490
- if (thoughtTimeVal !== void 0) {
1491
- const timeStr = thoughtTimeVal >= 1e3 ? `${(thoughtTimeVal / 1e3).toFixed(1)}s` : `${thoughtTimeVal}ms`;
1492
- const breatheDots = [
1493
- "\x1B[38;2;142;163;175m\xB7\x1B[0m",
1494
- "\x1B[38;2;143;153;129m\u2022\x1B[0m",
1495
- "\x1B[38;2;200;170;120m\u25CF\x1B[0m",
1496
- "\x1B[38;2;135;165;130m\u2022\x1B[0m"
1497
- ];
1498
- const spinIdx = Math.floor(Date.now() / 250) % 4;
1499
- const dotChar = isThinkingNow ? breatheDots[spinIdx] : morandi.gray("\u2022");
1500
- if (isThinkingNow) {
1501
- asstLines.push(
1502
- `${dotChar} ` + morandi.accent(`Thinking... ${timeStr}`)
1503
- );
1504
- if (this.currentThinking) {
1505
- const lines = this.currentThinking.split("\n").filter(Boolean);
1506
- const lastLines = lines.slice(-4);
1507
- const maxL = columns - 14;
1508
- for (const line of lastLines) {
1509
- const trimmed = line.trim();
1510
- let displayText = trimmed;
1511
- const displayW = this.getStringWidth(displayText);
1512
- if (displayW > maxL) {
1513
- displayText = this.truncateToWidth(displayText, maxL - 3) + "...";
1514
- }
1515
- asstLines.push(
1516
- " " + morandi.gray("\xB7 ") + morandi.dim(displayText)
1517
- );
1518
- }
1519
- }
1520
- } else {
1521
- asstLines.push(
1522
- morandi.gray("\u{1F9E0} ") + morandi.dim(`Thought for ${timeStr}`)
1523
- );
1524
- }
1525
- }
1526
- if (systemLines.length > 0) {
1527
- asstLines.push(...systemLines);
1528
- }
1529
- if (turn.assistant.text) {
1530
- if (asstLines.length > 0) {
1531
- asstLines.push("");
1532
- }
1533
- const asstObj = turn.assistant;
1534
- const isStreaming = this.resolveInput === null;
1535
- const nowTime = Date.now();
1536
- const timeSinceLastRender = nowTime - (asstObj._lastMarkdownRenderTime || 0);
1537
- if (!asstObj._formattedCached || asstObj._textCached !== turn.assistant.text) {
1538
- if (!isStreaming || timeSinceLastRender >= 150 || !asstObj._formattedCached) {
1539
- asstObj._formattedCached = Renderer.formatMarkdown(
1540
- turn.assistant.text
1541
- ).split("\n");
1542
- asstObj._textCached = turn.assistant.text;
1543
- asstObj._lastMarkdownRenderTime = nowTime;
1544
- }
1545
- }
1546
- asstLines.push(...asstObj._formattedCached);
1547
- }
1548
- let footerStatusLine = "";
1549
- const lastSys = turn.system[turn.system.length - 1];
1550
- if (lastSys && lastSys.text.includes("Failed")) {
1551
- footerStatusLine = `${morandi.failed("failed")} \xB7 ${morandi.dim(cleanModel)}`;
1552
- } else if (turn.assistant.totalTime !== void 0) {
1553
- const sec = (turn.assistant.totalTime / 1e3).toFixed(1);
1554
- footerStatusLine = `${morandi.completed("completed")} \xB7 ${morandi.dim(cleanModel)} \xB7 ${morandi.dim(sec + "s")}`;
1555
- }
1556
- if (footerStatusLine) {
1557
- asstLines.push("");
1558
- asstLines.push(footerStatusLine);
1559
- }
1560
- const wrappedAsstLines = [];
1561
- for (const line of asstLines) {
1562
- wrappedAsstLines.push(...this.wrapLine(line, columns - 10));
1563
- }
1564
- renderedLines.push(
1565
- " " + morandi.asstBold(`\u{1F916} Orbit (${cleanModel})`)
1566
- );
1567
- renderedLines.push(aBorder);
1568
- for (const line of wrappedAsstLines) {
1569
- renderedLines.push(aBorder + line);
1570
- }
1571
- renderedLines.push(aBorder);
1572
- renderedLines.push("");
1573
- }
1574
- }
1575
- let planText = "";
1576
- const planItems = this.getPlanLines();
1577
- if (planItems.length > 0) {
1578
- const planContent = [];
1579
- let activeIndex = planItems.findIndex((item) => item.startsWith("- [/]"));
1580
- if (activeIndex === -1) {
1581
- activeIndex = planItems.findIndex((item) => item.startsWith("- [ ]"));
1582
- }
1583
- if (activeIndex === -1) {
1584
- activeIndex = planItems.length - 1;
1585
- }
1586
- planContent.push(" " + morandi.accent("\u{1F4CB} Active Plan:"));
1587
- const completedCount = planItems.filter(
1588
- (item, idx) => item.startsWith("- [x]") && idx < activeIndex
1589
- ).length;
1590
- if (completedCount > 0) {
1591
- const cleanCompletedText = `${completedCount} step${completedCount > 1 ? "s" : ""} completed`;
1592
- planContent.push(
1593
- " " + morandi.completed("\u2714") + " " + morandi.gray(cleanCompletedText)
1594
- );
1595
- }
1596
- const activeItem = planItems[activeIndex];
1597
- if (activeItem) {
1598
- const text = activeItem.substring(5).trim();
1599
- const isCurrentRunning = activeItem.startsWith("- [/]");
1600
- const prefixSymbol = isCurrentRunning ? morandi.accent("\u25B8") : morandi.dim("\u25CB");
1601
- let displayText = text;
1602
- const maxTextLen = columns - 10;
1603
- const displayW = this.getStringWidth(displayText);
1604
- if (displayW > maxTextLen) {
1605
- displayText = this.truncateToWidth(displayText, maxTextLen - 3) + "...";
1606
- }
1607
- const coloredText = isCurrentRunning ? morandi.whiteBold(displayText) : morandi.dim(displayText);
1608
- planContent.push(" " + prefixSymbol + " " + coloredText);
1609
- }
1610
- planText = planContent.join("\n") + "\n\n";
1611
- }
1612
- let contextText = "";
1613
- if (this.activeContextFiles && this.activeContextFiles.length > 0) {
1614
- const contextLines = [];
1615
- contextLines.push(" " + morandi.accent("\u{1F4CE} Context Files:"));
1616
- const filesStr = this.activeContextFiles.map((f) => f.path + (f.readOnly ? " (RO)" : "")).join(", ");
1617
- const maxW = columns - 10;
1618
- const wrappedFiles = this.wrapLine(filesStr, maxW);
1619
- for (const line of wrappedFiles) {
1620
- contextLines.push(" " + morandi.white(line));
1621
- }
1622
- contextText = contextLines.join("\n") + "\n\n";
1623
- }
1624
- const headerText = `${headerLines.join("\n")}
1625
-
1626
- ` + planText + contextText;
1627
- const headerHeight = headerText.split("\n").length;
1628
- const maxContentRows = Math.max(1, rows - bottomHeight - headerHeight - 1);
1629
- let flatLines = [];
1630
- for (const item of renderedLines) {
1631
- flatLines.push(...item.split("\n"));
1632
- }
1633
- if (this.historyScrollOffset > 0 && flatLines.length > this.lastHistoryLineCount) {
1634
- this.historyScrollOffset += flatLines.length - this.lastHistoryLineCount;
1635
- this.hasNewOutputWhileScrolled = true;
1636
- }
1637
- this.lastHistoryLineCount = flatLines.length;
1638
- this.maxHistoryScrollOffset = Math.max(
1639
- 0,
1640
- flatLines.length - maxContentRows
1641
- );
1642
- this.historyScrollOffset = Math.min(
1643
- this.historyScrollOffset,
1644
- this.maxHistoryScrollOffset
1645
- );
1646
- let finalLines = [];
1647
- let totalLinesCount = 0;
1648
- const visibleEnd = Math.max(0, flatLines.length - this.historyScrollOffset);
1649
- for (let i = visibleEnd - 1; i >= 0; i--) {
1650
- const line = flatLines[i];
1651
- const visibleLen = this.getStringWidth(line);
1652
- const lineRows = Math.max(
1653
- 1,
1654
- Math.ceil(visibleLen / Math.max(1, columns - 4))
1655
- );
1656
- if (totalLinesCount + lineRows > maxContentRows) {
1657
- break;
1658
- }
1659
- totalLinesCount += lineRows;
1660
- finalLines.unshift(line);
1661
- }
1662
- while (finalLines.length > 0 && finalLines[finalLines.length - 1].replace(/\x1b\[[0-9;]*[a-zA-Z]/g, "").trim() === "") {
1663
- finalLines.pop();
1664
- }
1665
- const gapHeight = finalLines.length > 0 ? 1 : 0;
1666
- const totalHeight = headerHeight + finalLines.length + gapHeight + bottomHeight;
1667
- const extraPad = Math.max(0, rows - totalHeight);
1668
- const allLines = [];
1669
- allLines.push(...headerText.split("\n"));
1670
- if (extraPad > 0) {
1671
- for (let i = 0; i < extraPad; i++) {
1672
- allLines.push("");
1673
- }
1674
- }
1675
- if (finalLines.length > 0) {
1676
- allLines.push(...finalLines);
1677
- allLines.push("");
1678
- }
1679
- allLines.push(...bottomLines);
1680
- const rawLines = allLines;
1681
- const staticText = rawLines.slice(0, rawLines.length - bottomHeight).join("\n");
1682
- const canIncremental = !forceFull && isInputActive && this.cachedStaticLinesCount > 0 && bottomHeight === this.lastRenderedBottomHeight && staticText === this.cachedStaticContent;
1683
- if (canIncremental) {
1684
- let cursorSequence2 = "";
1685
- let tempLen = 0;
1686
- let cursorLineIndex = 0;
1687
- let xOffset = 0;
1688
- for (let i = 0; i < wrappedLines.length; i++) {
1689
- const line = wrappedLines[i];
1690
- if (this.cursorPosition >= tempLen && this.cursorPosition <= tempLen + line.length) {
1691
- cursorLineIndex = i;
1692
- const subStr = line.substring(0, this.cursorPosition - tempLen);
1693
- xOffset = this.getStringWidth(subStr);
1694
- break;
1695
- }
1696
- tempLen += line.length;
1697
- }
1698
- const lineStartX = cursorLineIndex === 0 ? this.getStringWidth(" \u2502 orbit > ") : 12;
1699
- const targetX = lineStartX + xOffset;
1700
- const linesUp = formattedLines.length - cursorLineIndex + 1;
1701
- cursorSequence2 = `\x1B[${linesUp}A\x1B[${targetX + 1}G\x1B[?25h`;
1702
- const bottomOutput = `\x1B[?25l\x1B[${this.cachedStaticLinesCount + 1};1H` + // 移至底部的首行
1703
- bottomLines.map((line) => line + "\x1B[K").join("\n") + "\x1B[J" + // 擦拭并重写 bottomLines
1704
- cursorSequence2;
1705
- process.stdout.write(bottomOutput);
1706
- return;
1707
- }
1708
- this.cachedStaticLinesCount = rawLines.length - bottomHeight;
1709
- this.cachedStaticContent = staticText;
1710
- this.lastRenderedBottomHeight = bottomHeight;
1711
- let finalOutput = "\x1B[?25l\x1B[H" + rawLines.map((line) => line + "\x1B[K").join("\n") + "\x1B[J";
1712
- let cursorSequence = "";
1713
- if (this.resolveInput || this.thinkingKeypressListener !== null) {
1714
- let tempLen = 0;
1715
- let cursorLineIndex = 0;
1716
- let xOffset = 0;
1717
- for (let i = 0; i < wrappedLines.length; i++) {
1718
- const line = wrappedLines[i];
1719
- if (this.cursorPosition >= tempLen && this.cursorPosition <= tempLen + line.length) {
1720
- cursorLineIndex = i;
1721
- const subStr = line.substring(0, this.cursorPosition - tempLen);
1722
- xOffset = this.getStringWidth(subStr);
1723
- break;
1724
- }
1725
- tempLen += line.length;
1726
- }
1727
- const lineStartX = cursorLineIndex === 0 ? this.getStringWidth(" \u2502 orbit > ") : 12;
1728
- const targetX = lineStartX + xOffset;
1729
- const linesUp = formattedLines.length - cursorLineIndex + 1;
1730
- cursorSequence = `\x1B[${linesUp}A\x1B[${targetX + 1}G\x1B[?25h`;
1731
- } else {
1732
- cursorSequence = "\x1B[?25l";
1733
- }
1734
- finalOutput += cursorSequence;
1735
- process.stdout.write(finalOutput);
1736
- }
1737
- isFullWidth(codePoint) {
1738
- if (Number.isNaN(codePoint)) {
1739
- return false;
1740
- }
1741
- if (codePoint === 9698 || // ◢
1742
- codePoint === 9699 || // ◣
1743
- codePoint === 9700 || // ◤
1744
- codePoint === 9701 || // ◥
1745
- codePoint === 9616 || // ▐
1746
- codePoint === 9612 || // ▌
1747
- codePoint === 9679) {
1748
- return true;
1749
- }
1750
- return codePoint >= 4352 && codePoint <= 4447 || // Hangul Jamo
1751
- codePoint === 9001 || // LEFT-POINTING ANGLE BRACKET
1752
- codePoint === 9002 || // RIGHT-POINTING ANGLE BRACKET
1753
- codePoint >= 11904 && codePoint <= 12871 && codePoint !== 12351 || // CJK Radicals Supplement .. Enclosed CJK Letters and Months
1754
- codePoint >= 12880 && codePoint <= 19903 || // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A
1755
- codePoint >= 19968 && codePoint <= 42182 || // CJK Unified Ideographs .. Yi Radicals
1756
- codePoint >= 43360 && codePoint <= 43388 || // Hangul Jamo Extended-A
1757
- codePoint >= 44032 && codePoint <= 55203 || // Hangul Syllables
1758
- codePoint >= 63744 && codePoint <= 64255 || // CJK Compatibility Ideographs
1759
- codePoint >= 65040 && codePoint <= 65049 || // Vertical Forms
1760
- codePoint >= 65072 && codePoint <= 65131 || // CJK Compatibility Forms .. Small Form Variants
1761
- codePoint >= 65281 && codePoint <= 65376 || // Halfwidth and Fullwidth Forms
1762
- codePoint >= 65504 && codePoint <= 65510 || codePoint >= 110592 && codePoint <= 110593 || // Kana Supplement
1763
- codePoint >= 127488 && codePoint <= 127569 || // Enclosed Ideographic Supplement
1764
- codePoint >= 131072 && codePoint <= 262141 || // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane
1765
- codePoint >= 127744 && codePoint <= 129535 || // Emojis
1766
- codePoint >= 128512 && codePoint <= 128591 || // Emoticons
1767
- codePoint >= 128640 && codePoint <= 128767;
1768
- }
1769
- truncateToWidth(str, maxW) {
1770
- let width = 0;
1771
- let result = "";
1772
- for (const char of str) {
1773
- const code = char.codePointAt(0);
1774
- if (code === void 0) continue;
1775
- const charW = this.isFullWidth(code) ? 2 : 1;
1776
- if (width + charW > maxW) {
1777
- break;
1778
- }
1779
- width += charW;
1780
- result += char;
1781
- }
1782
- return result;
1783
- }
1784
- wrapLine(line, maxWidth) {
1785
- const cleanLine = line.replace(
1786
- /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,
1787
- ""
1788
- );
1789
- if (this.getStringWidth(cleanLine) <= maxWidth) {
1790
- return [line];
1791
- }
1792
- const lines = [];
1793
- let currentLine = "";
1794
- let currentWidth = 0;
1795
- const ansiRegex = /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g;
1796
- let activeColor = "";
1797
- let i = 0;
1798
- while (i < line.length) {
1799
- ansiRegex.lastIndex = i;
1800
- const match = ansiRegex.exec(line);
1801
- if (match && match.index === i) {
1802
- const ansiCode = match[0];
1803
- currentLine += ansiCode;
1804
- if (ansiCode.includes("m") && !ansiCode.includes("[0m")) {
1805
- activeColor = ansiCode;
1806
- } else if (ansiCode.includes("[0m")) {
1807
- activeColor = "";
1808
- }
1809
- i += ansiCode.length;
1810
- continue;
1811
- }
1812
- const char = line.charAt(i);
1813
- const code = line.codePointAt(i);
1814
- let charLen = 1;
1815
- if (code && code > 65535) {
1816
- charLen = 2;
1817
- }
1818
- const charStr = line.substring(i, i + charLen);
1819
- const charW = this.isFullWidth(code || 0) ? 2 : 1;
1820
- if (currentWidth + charW > maxWidth) {
1821
- if (activeColor) {
1822
- currentLine += "\x1B[0m";
1823
- }
1824
- lines.push(currentLine);
1825
- currentLine = activeColor + charStr;
1826
- currentWidth = charW;
1827
- } else {
1828
- currentLine += charStr;
1829
- currentWidth += charW;
1830
- }
1831
- i += charLen;
1832
- }
1833
- if (currentLine) {
1834
- lines.push(currentLine);
1835
- }
1836
- return lines;
1837
- }
1838
- getStringWidth(str) {
1839
- const cleanStr = str.replace(
1840
- /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,
1841
- ""
1842
- );
1843
- let width = 0;
1844
- for (let i = 0; i < cleanStr.length; i++) {
1845
- const code = cleanStr.codePointAt(i);
1846
- if (!code) continue;
1847
- if (code > 65535) {
1848
- i++;
1849
- }
1850
- if (this.isFullWidth(code)) {
1851
- width += 2;
1852
- } else {
1853
- width += 1;
1854
- }
1855
- }
1856
- return width;
1857
- }
1858
- wrapText(str, maxWidth) {
1859
- const lines = [];
1860
- let currentLine = "";
1861
- let currentWidth = 0;
1862
- for (let i = 0; i < str.length; i++) {
1863
- const code = str.codePointAt(i);
1864
- if (!code) continue;
1865
- let char = str.charAt(i);
1866
- if (code > 65535) {
1867
- char = str.substring(i, i + 2);
1868
- i++;
1869
- }
1870
- const charWidth = this.isFullWidth(code) ? 2 : 1;
1871
- if (currentWidth + charWidth > maxWidth) {
1872
- lines.push(currentLine);
1873
- currentLine = char;
1874
- currentWidth = charWidth;
1875
- } else {
1876
- currentLine += char;
1877
- currentWidth += charWidth;
1878
- }
1879
- }
1880
- if (currentLine || lines.length === 0) {
1881
- lines.push(currentLine);
1882
- }
1883
- return lines;
1884
- }
1885
- formatWrappedLines(wrappedLines, inputLength) {
1886
- let charIndex = 0;
1887
- const formattedLines = [];
1888
- for (const line of wrappedLines) {
1889
- let formattedLine = "";
1890
- for (let i = 0; i < line.length; i++) {
1891
- const char = line.charAt(i);
1892
- const code = line.codePointAt(i);
1893
- let increment = 1;
1894
- let charStr = char;
1895
- if (code && code > 65535) {
1896
- charStr = line.substring(i, i + 2);
1897
- i++;
1898
- increment = 2;
1899
- }
1900
- if (charIndex < inputLength) {
1901
- formattedLine += `\x1B[1;38;2;230;225;215m${charStr}\x1B[0m`;
1902
- } else {
1903
- formattedLine += `\x1B[2;38;2;110;110;110m${charStr}\x1B[0m`;
1904
- }
1905
- charIndex += increment;
1906
- }
1907
- formattedLines.push(formattedLine);
1908
- }
1909
- return formattedLines;
1910
- }
1911
- };
1912
-
1913
- export {
1914
- previousCodePointIndex,
1915
- nextCodePointIndex,
1916
- parseMouseWheelDirection,
1917
- pageText,
1918
- FullscreenTui
1919
- };