@orbit-build/cli 0.1.0

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.
package/dist/index.js ADDED
@@ -0,0 +1,4895 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/index.ts
4
+ import { Command } from "commander";
5
+
6
+ // src/commands/init.ts
7
+ import { writeFileSync, existsSync } from "fs";
8
+ import { join } from "path";
9
+ import picocolors from "picocolors";
10
+ function runInit(cwd) {
11
+ const target = join(cwd, "ORBIT.md");
12
+ if (existsSync(target)) {
13
+ console.log(picocolors.yellow(`ORBIT.md already exists in ${cwd}.`));
14
+ return;
15
+ }
16
+ const content = `# Orbit Project Guidelines
17
+
18
+ This file contains custom developer instructions and rules for the Orbit AI Coding Agent.
19
+
20
+ ## Code Standards
21
+ - Keep modifications minimal and precise.
22
+ - Preserves existing formatting conventions and docstrings.
23
+ - Always verify changes by running appropriate test suites.
24
+ `;
25
+ writeFileSync(target, content, "utf8");
26
+ console.log(
27
+ picocolors.green(`Successfully initialized ORBIT.md at ${target}`)
28
+ );
29
+ }
30
+
31
+ // src/commands/config.ts
32
+ import { ConfigLoader } from "@orbit-build/config";
33
+ import picocolors2 from "picocolors";
34
+ function runConfig(cwd) {
35
+ const config = ConfigLoader.loadSync(cwd);
36
+ console.log(picocolors2.bold("\nResolved Orbit Configuration:\n"));
37
+ console.log(JSON.stringify(config, null, 2));
38
+ }
39
+
40
+ // src/commands/doctor.ts
41
+ import { execSync } from "child_process";
42
+ import picocolors3 from "picocolors";
43
+ import { ConfigLoader as ConfigLoader2 } from "@orbit-build/config";
44
+ function runDoctor(cwd) {
45
+ console.log(picocolors3.bold("\nOrbit Environment Diagnostics:\n"));
46
+ const nodeVersion = process.version;
47
+ const major = parseInt(nodeVersion.replace("v", "").split(".")[0], 10);
48
+ if (major >= 20) {
49
+ console.log(
50
+ picocolors3.green(`\u2714 Node.js version: ${nodeVersion} (Supported)`)
51
+ );
52
+ } else {
53
+ console.log(
54
+ picocolors3.red(
55
+ `\u2716 Node.js version: ${nodeVersion} (Requires Node.js 20+)`
56
+ )
57
+ );
58
+ }
59
+ try {
60
+ const gitVersion = execSync("git --version", { encoding: "utf8" }).trim();
61
+ console.log(picocolors3.green(`\u2714 Git: ${gitVersion}`));
62
+ } catch {
63
+ console.log(
64
+ picocolors3.yellow(
65
+ `\u26A0 Git: Not detected in environment path. Sandbox rollbacks will use filesystem backups.`
66
+ )
67
+ );
68
+ }
69
+ try {
70
+ const rgVersion = execSync("rg --version", { encoding: "utf8" }).trim().split("\n")[0];
71
+ console.log(picocolors3.green(`\u2714 Ripgrep (rg): ${rgVersion}`));
72
+ } catch {
73
+ console.log(
74
+ picocolors3.yellow(
75
+ `\u26A0 Ripgrep (rg): Not detected. Code searches will use Node-based stream scanning.`
76
+ )
77
+ );
78
+ }
79
+ const config = ConfigLoader2.loadSync(cwd);
80
+ const defaultProvider = config.provider.default;
81
+ const providerDetails = config.providers[defaultProvider];
82
+ if (providerDetails?.apiKey) {
83
+ console.log(
84
+ picocolors3.green(
85
+ `\u2714 API Key: Loaded for default provider "${defaultProvider}"`
86
+ )
87
+ );
88
+ } else {
89
+ console.log(
90
+ picocolors3.red(
91
+ `\u2716 API Key: Missing for default provider "${defaultProvider}". Configure ${providerDetails?.apiKeyEnv || "API keyenv"}`
92
+ )
93
+ );
94
+ }
95
+ }
96
+
97
+ // src/commands/run.ts
98
+ import {
99
+ ConfigLoader as ConfigLoader3
100
+ } from "@orbit-build/config";
101
+ import {
102
+ AgentLoop as AgentLoop2,
103
+ Orchestrator as Orchestrator2,
104
+ eventBus as eventBus2
105
+ } from "@orbit-build/core";
106
+ import {
107
+ DeepSeekAnthropicProvider,
108
+ DeepSeekOpenAIProvider,
109
+ OpenAIProvider,
110
+ AnthropicProvider,
111
+ OllamaProvider
112
+ } from "@orbit-build/model-providers";
113
+ import { Prompt as Prompt4, DiffView as DiffView2 } from "@orbit-build/tui";
114
+ import picocolors6 from "picocolors";
115
+ import { existsSync as existsSync6, readFileSync as readFileSync5 } from "fs";
116
+ import { join as join6 } from "path";
117
+
118
+ // src/tui/FullscreenTui.ts
119
+ import { join as join4, dirname as dirname2 } from "path";
120
+ import { homedir as homedir3 } from "os";
121
+ import { existsSync as existsSync4, readFileSync as readFileSync3, writeFileSync as writeFileSync2, mkdirSync } from "fs";
122
+ import { exec } from "child_process";
123
+ import readline from "readline";
124
+ import { Prompt as Prompt2, Renderer } from "@orbit-build/tui";
125
+
126
+ // src/runtime/CommandRouter.ts
127
+ import { ConfigSchema } from "@orbit-build/config";
128
+ import { Prompt } from "@orbit-build/tui";
129
+ import picocolors4 from "picocolors";
130
+ import glob from "fast-glob";
131
+ import { existsSync as existsSync3, readFileSync as readFileSync2, readdirSync as readdirSync2 } from "fs";
132
+ import { join as join3, dirname, resolve } from "path";
133
+ import { homedir as homedir2 } from "os";
134
+ import { PermissionEngine } from "@orbit-build/permissions";
135
+
136
+ // src/commands/customCommands.ts
137
+ import { existsSync as existsSync2, readFileSync, readdirSync } from "fs";
138
+ import { basename, extname, join as join2 } from "path";
139
+ import { homedir } from "os";
140
+ import { parse } from "yaml";
141
+ import { z } from "zod";
142
+ var CommandMetadataSchema = z.object({
143
+ description: z.string().max(240).optional(),
144
+ argumentHint: z.string().max(120).optional()
145
+ });
146
+ var VALID_COMMAND_NAME = /^[a-z0-9][a-z0-9-_]{0,47}$/i;
147
+ var MAX_COMMAND_FILE_BYTES = 256 * 1024;
148
+ function parseCommandFile(filePath, source) {
149
+ const commandName = basename(filePath, extname(filePath));
150
+ if (!VALID_COMMAND_NAME.test(commandName)) return null;
151
+ const raw = readFileSync(filePath, "utf8");
152
+ if (Buffer.byteLength(raw, "utf8") > MAX_COMMAND_FILE_BYTES) return null;
153
+ let metadata = {};
154
+ let template = raw.trim();
155
+ const frontmatter = raw.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);
156
+ if (frontmatter) {
157
+ const parsed = CommandMetadataSchema.safeParse(parse(frontmatter[1]) || {});
158
+ if (!parsed.success) return null;
159
+ metadata = parsed.data;
160
+ template = frontmatter[2].trim();
161
+ }
162
+ if (!template) return null;
163
+ return {
164
+ name: commandName.toLowerCase(),
165
+ description: metadata.description || `Run the ${commandName} prompt workflow`,
166
+ argumentHint: metadata.argumentHint,
167
+ template,
168
+ source,
169
+ filePath
170
+ };
171
+ }
172
+ function loadDirectory(directory, source) {
173
+ if (!existsSync2(directory)) return [];
174
+ const commands = [];
175
+ for (const entry of readdirSync(directory, { withFileTypes: true })) {
176
+ if (!entry.isFile() || extname(entry.name).toLowerCase() !== ".md") {
177
+ continue;
178
+ }
179
+ try {
180
+ const command = parseCommandFile(join2(directory, entry.name), source);
181
+ if (command) commands.push(command);
182
+ } catch {
183
+ }
184
+ }
185
+ return commands;
186
+ }
187
+ function loadCustomCommands(cwd, reservedNames = []) {
188
+ const reserved = new Set(
189
+ Array.from(reservedNames, (name) => name.replace(/^\//, "").toLowerCase())
190
+ );
191
+ const merged = /* @__PURE__ */ new Map();
192
+ for (const command of loadDirectory(
193
+ join2(homedir(), ".orbit", "commands"),
194
+ "user"
195
+ )) {
196
+ if (!reserved.has(command.name)) merged.set(command.name, command);
197
+ }
198
+ for (const command of loadDirectory(
199
+ join2(cwd, ".orbit", "commands"),
200
+ "project"
201
+ )) {
202
+ if (!reserved.has(command.name)) merged.set(command.name, command);
203
+ }
204
+ return Array.from(merged.values()).sort(
205
+ (a, b) => a.name.localeCompare(b.name)
206
+ );
207
+ }
208
+ function expandCustomCommand(command, rawArguments) {
209
+ const args = rawArguments.trim();
210
+ const positional = args ? args.split(/\s+/) : [];
211
+ let expanded = command.template.replace(/\$ARGUMENTS\b/g, args).replace(/\{\{\s*args\s*\}\}/gi, args);
212
+ for (let index = 1; index <= 9; index++) {
213
+ expanded = expanded.replace(
214
+ new RegExp(`\\$${index}\\b`, "g"),
215
+ positional[index - 1] || ""
216
+ );
217
+ }
218
+ if (args && !/\$ARGUMENTS\b|\{\{\s*args\s*\}\}|\$[1-9]\b/i.test(command.template)) {
219
+ expanded += `
220
+
221
+ Additional user arguments:
222
+ ${args}`;
223
+ }
224
+ return expanded.trim();
225
+ }
226
+
227
+ // src/runtime/CommandRouter.ts
228
+ import { createRequire } from "module";
229
+ var require2 = createRequire(import.meta.url);
230
+ var BUILTIN_SLASH_COMMANDS = [
231
+ "/help",
232
+ "/status",
233
+ "/config",
234
+ "/model",
235
+ "/chat",
236
+ "/commit",
237
+ "/exit",
238
+ "/quit",
239
+ "/rollback",
240
+ "/clear",
241
+ "/add",
242
+ "/drop",
243
+ "/mode",
244
+ "/copy"
245
+ ];
246
+ var CommandRouter = class {
247
+ constructor(cwd, config, providerInstance, setProviderInstance, loop, tui, useFullscreenTui, getCandidates, setCandidates, getLocalState2, saveLocalState, tuiInteraction, multi) {
248
+ this.cwd = cwd;
249
+ this.config = config;
250
+ this.providerInstance = providerInstance;
251
+ this.setProviderInstance = setProviderInstance;
252
+ this.loop = loop;
253
+ this.tui = tui;
254
+ this.useFullscreenTui = useFullscreenTui;
255
+ this.getCandidates = getCandidates;
256
+ this.setCandidates = setCandidates;
257
+ this.getLocalState = getLocalState2;
258
+ this.saveLocalState = saveLocalState;
259
+ this.tuiInteraction = tuiInteraction;
260
+ this.multi = multi;
261
+ }
262
+ cwd;
263
+ config;
264
+ providerInstance;
265
+ setProviderInstance;
266
+ loop;
267
+ tui;
268
+ useFullscreenTui;
269
+ getCandidates;
270
+ setCandidates;
271
+ getLocalState;
272
+ saveLocalState;
273
+ tuiInteraction;
274
+ multi;
275
+ printOutput(text, raw = false) {
276
+ if (this.tui && this.tui.isActive) {
277
+ this.tui.addSystemMessage(text, raw);
278
+ } else {
279
+ console.log(text);
280
+ }
281
+ }
282
+ async route(input) {
283
+ let trimmed = input.trim();
284
+ if (!trimmed) return { shouldExit: false, processed: false };
285
+ const useFullscreenTui = this.useFullscreenTui;
286
+ const tui = this.tui;
287
+ const config = this.config;
288
+ const loop = this.loop;
289
+ const cwd = this.cwd;
290
+ if (trimmed.startsWith("/")) {
291
+ const commandName = trimmed.slice(1).split(/\s+/, 1)[0].toLowerCase();
292
+ const customCommand = loadCustomCommands(
293
+ cwd,
294
+ BUILTIN_SLASH_COMMANDS
295
+ ).find((candidate) => candidate.name === commandName);
296
+ if (customCommand) {
297
+ const rawArguments = trimmed.slice(commandName.length + 1).trim();
298
+ trimmed = expandCustomCommand(customCommand, rawArguments);
299
+ tui.addLog(
300
+ `${config.language === "zh" ? "\u5DF2\u5C55\u5F00\u81EA\u5B9A\u4E49\u547D\u4EE4" : "Expanded custom command"} /${customCommand.name}`
301
+ );
302
+ }
303
+ }
304
+ if (trimmed.startsWith("!") || trimmed.startsWith("/run")) {
305
+ const wasActive = useFullscreenTui && tui.isActive;
306
+ if (wasActive) tui.stop();
307
+ let shellCmd = "";
308
+ if (trimmed.startsWith("!")) {
309
+ shellCmd = trimmed.substring(1).trim();
310
+ } else {
311
+ shellCmd = trimmed.substring(4).trim();
312
+ }
313
+ const isZh = config.language === "zh";
314
+ if (!shellCmd) {
315
+ console.log(
316
+ isZh ? picocolors4.yellow(
317
+ "\u7528\u6CD5: !<shell_command> \u6216 /run <shell_command>"
318
+ ) : picocolors4.yellow(
319
+ "Usage: !<shell_command> or /run <shell_command>"
320
+ )
321
+ );
322
+ if (wasActive) tui.start(config.budgetLimit);
323
+ return { shouldExit: false, processed: true };
324
+ }
325
+ const permissionEngine = new PermissionEngine(config);
326
+ const decision = permissionEngine.evaluate(
327
+ "bash",
328
+ { command: shellCmd },
329
+ "execute"
330
+ );
331
+ if (decision.action === "deny") {
332
+ console.log(
333
+ picocolors4.red(
334
+ isZh ? `\u2716 \u547D\u4EE4\u5DF2\u88AB\u5B89\u5168\u7B56\u7565\u963B\u6B62: ${decision.reason}` : `\u2716 Command blocked by safety policy: ${decision.reason}`
335
+ )
336
+ );
337
+ if (wasActive) tui.start(config.budgetLimit);
338
+ return { shouldExit: false, processed: true };
339
+ }
340
+ if (decision.action === "ask") {
341
+ const approved = await Prompt.askApproval(
342
+ isZh ? `\u547D\u4EE4\u9700\u8981 ${decision.risk} \u6743\u9650\uFF1A${shellCmd}` : `Command requires ${decision.risk} permission: ${shellCmd}`
343
+ );
344
+ if (!approved) {
345
+ console.log(
346
+ isZh ? "\u5DF2\u53D6\u6D88\u547D\u4EE4\u6267\u884C\u3002" : "Command execution cancelled."
347
+ );
348
+ if (wasActive) tui.start(config.budgetLimit);
349
+ return { shouldExit: false, processed: true };
350
+ }
351
+ }
352
+ console.log(
353
+ isZh ? picocolors4.cyan(`
354
+ \u6B63\u5728\u6267\u884C Shell \u547D\u4EE4: ${shellCmd}...`) : picocolors4.cyan(`
355
+ Running shell command: ${shellCmd}...`)
356
+ );
357
+ try {
358
+ const { spawnSync } = await import("child_process");
359
+ const result = spawnSync(shellCmd, {
360
+ cwd,
361
+ stdio: "inherit",
362
+ shell: true
363
+ });
364
+ if (result.status === 0) {
365
+ console.log(
366
+ isZh ? picocolors4.green(`
367
+ \u2714 \u547D\u4EE4\u6267\u884C\u6210\u529F\u3002`) : picocolors4.green(`
368
+ \u2714 Command completed successfully.`)
369
+ );
370
+ } else {
371
+ console.log(
372
+ isZh ? picocolors4.red(`
373
+ \u2716 \u547D\u4EE4\u6267\u884C\u5931\u8D25\uFF0C\u9000\u51FA\u4EE3\u7801: ${result.status}`) : picocolors4.red(
374
+ `
375
+ \u2716 Command failed with exit code ${result.status}`
376
+ )
377
+ );
378
+ }
379
+ await Prompt.askText(
380
+ isZh ? "\u6309 Enter \u952E\u8FD4\u56DE Orbit..." : "Press Enter to return to Orbit..."
381
+ );
382
+ } catch (err) {
383
+ console.log(
384
+ isZh ? picocolors4.red(`\u65E0\u6CD5\u6267\u884C\u547D\u4EE4: ${err.message}`) : picocolors4.red(`Failed to execute command: ${err.message}`)
385
+ );
386
+ } finally {
387
+ tui.syncFromLoop(loop);
388
+ if (wasActive) tui.start(config.budgetLimit);
389
+ }
390
+ return { shouldExit: false, processed: true };
391
+ }
392
+ if (trimmed.startsWith("/")) {
393
+ const parts = trimmed.split(" ");
394
+ const command = parts[0].toLowerCase();
395
+ if (command === "/exit" || command === "/quit") {
396
+ console.log(
397
+ picocolors4.yellow("Exiting Orbit Interactive Shell. Goodbye!")
398
+ );
399
+ return { shouldExit: true, processed: true };
400
+ }
401
+ if (command === "/help") {
402
+ const isZh = config.language === "zh";
403
+ let helpText = "";
404
+ if (isZh) {
405
+ helpText = [
406
+ "",
407
+ picocolors4.bold(picocolors4.cyan("\u25CF Orbit \u4EA4\u4E92\u5F0F\u7EC8\u7AEF\u6307\u4EE4\u6307\u5357")),
408
+ "",
409
+ picocolors4.bold(picocolors4.yellow(" [ \u4E0A\u4E0B\u6587\u7BA1\u7406 (Context) ]")),
410
+ ` ${picocolors4.green("/add")} ${picocolors4.cyan("<file>")} - \u6DFB\u52A0\u6587\u4EF6/\u76EE\u5F55\u81F3\u5F53\u524D\u4E0A\u4E0B\u6587 (\u4F7F\u7528 -r \u8BBE\u4E3A\u53EA\u8BFB)`,
411
+ ` ${picocolors4.green("/drop")} ${picocolors4.cyan("<file>")} - \u4ECE\u6D3B\u52A8\u4E0A\u4E0B\u6587\u4E2D\u79FB\u9664\u6307\u5B9A\u6587\u4EF6\u6216\u901A\u914D\u7B26\u6A21\u5F0F`,
412
+ ` ${picocolors4.green("/clear")} - \u6E05\u7A7A\u7EC8\u7AEF\u5C4F\u5E55\u548C\u6EDA\u52A8\u7F13\u51B2`,
413
+ "",
414
+ picocolors4.bold(picocolors4.yellow(" [ \u4F1A\u8BDD\u4E0E\u5386\u53F2 (Session) ]")),
415
+ ` ${picocolors4.green("/chat")} ${picocolors4.cyan("[action]")} - \u7BA1\u7406\u5BF9\u8BDD\u4F1A\u8BDD (\u5B50\u547D\u4EE4: list/ls, new, delete/rm, switch)`,
416
+ ` ${picocolors4.green("/rollback")} - \u56DE\u6EDA\u6700\u8FD1\u7684\u6587\u4EF6\u4FEE\u6539\u68C0\u67E5\u70B9`,
417
+ ` ${picocolors4.green("/copy")} - \u62F7\u8D1D AI \u7684\u6700\u65B0\u56DE\u590D\u81F3\u7CFB\u7EDF\u526A\u8D34\u677F`,
418
+ "",
419
+ picocolors4.bold(picocolors4.yellow(" [ \u914D\u7F6E\u4E0E\u72B6\u6001 (Settings) ]")),
420
+ ` ${picocolors4.green("/status")} - \u8BCA\u65AD\u5E76\u5C55\u793A\u5F53\u524D\u4F1A\u8BDD\u3001\u6A21\u578B\u3001Token \u6D88\u8017\u548C\u9650\u989D`,
421
+ ` ${picocolors4.green("/config")} ${picocolors4.cyan("[k=v]")} - \u67E5\u770B\u6216\u4EA4\u4E92\u5F0F/\u76F4\u63A5\u4FEE\u6539\u914D\u7F6E\u53C2\u6570`,
422
+ ` ${picocolors4.green("/model")} ${picocolors4.cyan("[name]")} - \u52A8\u6001\u67E5\u8BE2\u6216\u5207\u6362\u6B63\u5728\u4F7F\u7528\u7684 AI \u8BED\u8A00\u5927\u6A21\u578B`,
423
+ ` ${picocolors4.green("/mode")} ${picocolors4.cyan("[mode]")} - \u5207\u6362\u5B89\u5168\u786E\u8BA4\u6A21\u5F0F (strict, normal, auto, plan)`,
424
+ "",
425
+ picocolors4.bold(picocolors4.yellow(" [ Git \u63D0\u4EA4 (Git) ]")),
426
+ ` ${picocolors4.green("/commit")} ${picocolors4.cyan("[msg]")} - \u6682\u5B58\u5DE5\u4F5C\u533A\u4FEE\u6539\u5E76\u751F\u6210\u63D0\u4EA4 (\u7A7A\u6D88\u606F\u65F6\u4F7F\u7528 LLM \u81EA\u52A8\u751F\u6210)`,
427
+ "",
428
+ picocolors4.bold(picocolors4.yellow(" [ \u7CFB\u7EDF\u63A7\u5236 (System) ]")),
429
+ ` ${picocolors4.green("/help")} - \u663E\u793A\u6B64\u5E2E\u52A9\u4FE1\u606F`,
430
+ ` ${picocolors4.green("/exit")} / ${picocolors4.green("/quit")} - \u5B89\u5168\u9000\u51FA\u4EA4\u4E92\u5F0F\u7EC8\u7AEF`,
431
+ "",
432
+ picocolors4.bold(picocolors4.cyan(" [ Shell \u547D\u4EE4\u76F4\u63A5\u8FD0\u884C ]")),
433
+ ` ${picocolors4.green("!<cmd>")} - \u76F4\u63A5\u6267\u884C\u7CFB\u7EDF\u539F\u751F Shell \u547D\u4EE4 (\u4F8B\u5982: !git diff)`,
434
+ ""
435
+ ].join("\n");
436
+ } else {
437
+ helpText = [
438
+ "",
439
+ picocolors4.bold(picocolors4.cyan("\u25CF Orbit Interactive Shell Commands Guide")),
440
+ "",
441
+ picocolors4.bold(picocolors4.yellow(" [ Context Management ]")),
442
+ ` ${picocolors4.green("/add")} ${picocolors4.cyan("<file>")} - Add files/dirs to prompt context (use -r for read-only)`,
443
+ ` ${picocolors4.green("/drop")} ${picocolors4.cyan("<file>")} - Remove files/patterns from active prompt context`,
444
+ ` ${picocolors4.green("/clear")} - Clear the terminal screen and scrollback buffer`,
445
+ "",
446
+ picocolors4.bold(picocolors4.yellow(" [ Session & History ]")),
447
+ ` ${picocolors4.green("/chat")} ${picocolors4.cyan("[action]")} - Manage sessions (subcommands: list/ls, new, delete/rm, switch)`,
448
+ ` ${picocolors4.green("/rollback")} - Revert the last file edits checkpoint`,
449
+ ` ${picocolors4.green("/copy")} - Copy last assistant response to system clipboard`,
450
+ "",
451
+ picocolors4.bold(picocolors4.yellow(" [ Configuration & Status ]")),
452
+ ` ${picocolors4.green("/status")} - Display active session info, token usage, and budget limits`,
453
+ ` ${picocolors4.green("/config")} ${picocolors4.cyan("[k=v]")} - View or modify configurations interactively or via key=value`,
454
+ ` ${picocolors4.green("/model")} ${picocolors4.cyan("[name]")} - Query or dynamically swap the active AI model`,
455
+ ` ${picocolors4.green("/mode")} ${picocolors4.cyan("[mode]")} - Switch permission safety mode (strict, normal, auto, plan)`,
456
+ "",
457
+ picocolors4.bold(picocolors4.yellow(" [ Git Operations ]")),
458
+ ` ${picocolors4.green("/commit")} ${picocolors4.cyan("[msg]")} - Stage all changes and commit (generates message via LLM if empty)`,
459
+ "",
460
+ picocolors4.bold(picocolors4.yellow(" [ System Commands ]")),
461
+ ` ${picocolors4.green("/help")} - Show this commands guide`,
462
+ ` ${picocolors4.green("/exit")} / ${picocolors4.green("/quit")} - Terminate the interactive session`,
463
+ "",
464
+ picocolors4.bold(picocolors4.cyan(" [ Direct Shell Execution ]")),
465
+ ` ${picocolors4.green("!<cmd>")} - Run a raw shell command directly on the host machine (e.g. !git status)`,
466
+ ""
467
+ ].join("\n");
468
+ }
469
+ this.printOutput(helpText);
470
+ return { shouldExit: false, processed: true };
471
+ }
472
+ if (command === "/rollback") {
473
+ const isZh = config.language === "zh";
474
+ const args = parts.slice(1).join(" ").trim();
475
+ if (args === "all" || args === "--all") {
476
+ await loop.rollbackLastCheckpoint();
477
+ return { shouldExit: false, processed: true };
478
+ }
479
+ const { execSync: execSync2 } = await import("child_process");
480
+ let statusOut = "";
481
+ try {
482
+ statusOut = execSync2("git status --porcelain", {
483
+ cwd,
484
+ stdio: ["ignore", "pipe", "ignore"]
485
+ }).toString();
486
+ } catch {
487
+ await loop.rollbackLastCheckpoint();
488
+ return { shouldExit: false, processed: true };
489
+ }
490
+ const lines = statusOut.split("\n").map((l) => l.trim()).filter(Boolean);
491
+ if (lines.length === 0) {
492
+ console.log(
493
+ isZh ? picocolors4.yellow(
494
+ "\u5F53\u524D\u5DE5\u4F5C\u533A\u6CA1\u6709\u68C0\u6D4B\u5230\u4EFB\u4F55\u672A\u63D0\u4EA4\u7684\u4EE3\u7801\u53D8\u66F4\u3002"
495
+ ) : picocolors4.yellow(
496
+ "No uncommitted changes detected in the workspace."
497
+ )
498
+ );
499
+ return { shouldExit: false, processed: true };
500
+ }
501
+ const modifiedFiles = lines.map((line) => {
502
+ const filepath = line.substring(3).trim().replace(/^["']|["']$/g, "");
503
+ if (filepath.includes(" -> ")) {
504
+ const parts2 = filepath.split(" -> ");
505
+ return parts2[parts2.length - 1].trim().replace(/^["']|["']$/g, "");
506
+ }
507
+ return filepath;
508
+ });
509
+ const wasActive = useFullscreenTui && tui.isActive;
510
+ if (wasActive) tui.stop();
511
+ try {
512
+ const options = [
513
+ {
514
+ value: "all",
515
+ label: isZh ? "\u3010\u5168\u90E8\u56DE\u6EDA\u3011 \u64A4\u9500\u6240\u6709\u53D8\u66F4" : "[Rollback All] Discard all changes"
516
+ },
517
+ ...modifiedFiles.map((f) => ({ value: f, label: f }))
518
+ ];
519
+ const selected = await Prompt.askMultiSelect(
520
+ isZh ? "\u9009\u62E9\u8981\u56DE\u6EDA\uFF08\u64A4\u9500\u53D8\u66F4\uFF09\u7684\u6587\u4EF6\uFF1A" : "Select files to rollback (discard changes):",
521
+ options
522
+ );
523
+ if (selected && selected.length > 0) {
524
+ if (selected.includes("all")) {
525
+ await loop.rollbackLastCheckpoint();
526
+ } else {
527
+ for (const file of selected) {
528
+ const rolledBack = loop.rollbackFileToCheckpoint(
529
+ file
530
+ );
531
+ if (!rolledBack) {
532
+ try {
533
+ execSync2(`git checkout -- "${file}"`, {
534
+ cwd,
535
+ stdio: "ignore"
536
+ });
537
+ } catch {
538
+ try {
539
+ const fullP = resolve(cwd, file);
540
+ if (existsSync3(fullP)) {
541
+ import("fs").then((fs) => fs.unlinkSync(fullP));
542
+ }
543
+ } catch {
544
+ }
545
+ }
546
+ }
547
+ }
548
+ console.log(
549
+ isZh ? picocolors4.green(
550
+ `\u2714 \u6210\u529F\u56DE\u6EDA\u4EE5\u4E0B\u6587\u4EF6\u7684\u53D8\u66F4: ${selected.join(", ")}`
551
+ ) : picocolors4.green(
552
+ `\u2714 Successfully rolled back changes for: ${selected.join(", ")}`
553
+ )
554
+ );
555
+ }
556
+ } else {
557
+ console.log(
558
+ isZh ? picocolors4.yellow("\u672A\u9009\u62E9\u4EFB\u4F55\u6587\u4EF6\u3002") : picocolors4.yellow("No files selected.")
559
+ );
560
+ }
561
+ } catch (err) {
562
+ console.log(
563
+ isZh ? picocolors4.red(`\u56DE\u6EDA\u64CD\u4F5C\u5931\u8D25: ${err.message}`) : picocolors4.red(`Rollback operation failed: ${err.message}`)
564
+ );
565
+ } finally {
566
+ tui.syncFromLoop(loop);
567
+ if (wasActive) tui.start(config.budgetLimit);
568
+ }
569
+ return { shouldExit: false, processed: true };
570
+ }
571
+ if (command === "/status") {
572
+ const activeConfig = loop.getConfig();
573
+ const activeModel = loop.getModelOverride() || activeConfig.models.default;
574
+ const budgetLimit = activeConfig.budgetLimit;
575
+ const currentCost = loop.getSessionCost();
576
+ const mode = activeConfig.permissions.mode;
577
+ const statusText = [
578
+ picocolors4.bold(picocolors4.cyan("\n=== Orbit Session Status ===")),
579
+ ` \u{1F194} Session ID: ${picocolors4.green(loop.getSessionId())}`,
580
+ ` \u{1F50C} Provider: ${picocolors4.green(this.providerInstance.id)} (${this.providerInstance.baseUrl || "Default URL"})`,
581
+ ` \u{1F916} Active Model: ${picocolors4.green(activeModel)}`,
582
+ ` \u{1F4B0} Session Cost: $${currentCost.toFixed(4)} / $${budgetLimit.toFixed(2)} (Limit)`,
583
+ ` \u{1F6E1}\uFE0F Security Mode: ${picocolors4.green(mode.toUpperCase())}`,
584
+ picocolors4.cyan("============================\n")
585
+ ].join("\n");
586
+ this.printOutput(statusText);
587
+ return { shouldExit: false, processed: true };
588
+ }
589
+ if (command === "/config") {
590
+ const configArg = parts.slice(1).join(" ").trim();
591
+ const activeConfig = loop.getConfig();
592
+ if (configArg) {
593
+ const eqIndex = configArg.indexOf("=");
594
+ if (eqIndex === -1) {
595
+ this.printOutput(
596
+ picocolors4.yellow(
597
+ "Usage: /config <key>=<value> or just /config for interactive menu."
598
+ )
599
+ );
600
+ return { shouldExit: false, processed: true };
601
+ }
602
+ const key = configArg.slice(0, eqIndex).trim();
603
+ const rawVal = configArg.slice(eqIndex + 1).trim();
604
+ const currentVal = this.getNestedProperty(activeConfig, key);
605
+ if (currentVal === void 0) {
606
+ this.printOutput(
607
+ picocolors4.red(`Error: Unknown configuration key "${key}".`)
608
+ );
609
+ return { shouldExit: false, processed: true };
610
+ }
611
+ let parsedVal = rawVal;
612
+ if (typeof currentVal === "boolean") {
613
+ const lowerVal = rawVal.toLowerCase();
614
+ if (lowerVal === "true" || lowerVal === "1") parsedVal = true;
615
+ else if (lowerVal === "false" || lowerVal === "0")
616
+ parsedVal = false;
617
+ else {
618
+ this.printOutput(
619
+ picocolors4.red(
620
+ `Error: Key "${key}" expects a boolean value (true/false).`
621
+ )
622
+ );
623
+ return { shouldExit: false, processed: true };
624
+ }
625
+ } else if (typeof currentVal === "number") {
626
+ const num = Number(rawVal);
627
+ if (isNaN(num)) {
628
+ this.printOutput(
629
+ picocolors4.red(
630
+ `Error: Key "${key}" expects a numeric value.`
631
+ )
632
+ );
633
+ return { shouldExit: false, processed: true };
634
+ }
635
+ parsedVal = num;
636
+ } else if (Array.isArray(currentVal)) {
637
+ parsedVal = rawVal.split(",").map((s) => s.trim()).filter(Boolean);
638
+ }
639
+ const testConfig = JSON.parse(JSON.stringify(activeConfig));
640
+ this.setNestedProperty(testConfig, key, parsedVal);
641
+ const parseResult = ConfigSchema.safeParse(testConfig);
642
+ if (!parseResult.success) {
643
+ this.printOutput(
644
+ picocolors4.red(
645
+ `Configuration validation failed: ${parseResult.error.message}`
646
+ )
647
+ );
648
+ return { shouldExit: false, processed: true };
649
+ }
650
+ this.setNestedProperty(activeConfig, key, parsedVal);
651
+ this.printOutput(
652
+ picocolors4.green(`\u2714 Updated "${key}" to: ${parsedVal}`)
653
+ );
654
+ return { shouldExit: false, processed: true };
655
+ }
656
+ const wasActive = useFullscreenTui && tui.isActive;
657
+ if (wasActive) tui.stop();
658
+ try {
659
+ while (true) {
660
+ const currentMode = activeConfig.permissions.mode;
661
+ const currentBudget = activeConfig.budgetLimit;
662
+ const currentAllowRead = activeConfig.permissions.allowRead;
663
+ const currentApprovalWrite = activeConfig.permissions.requireApprovalForWrite;
664
+ const currentApprovalBash = activeConfig.permissions.requireApprovalForBash;
665
+ const currentBlockDangerous = activeConfig.permissions.blockDangerousCommands;
666
+ const currentProtectSecrets = activeConfig.permissions.protectSecrets;
667
+ const currentBashEnabled = activeConfig.tools.bash.enabled;
668
+ const currentSearchEnabled = activeConfig.tools.webSearch.enabled;
669
+ const currentMcpEnabled = activeConfig.tools.mcp.enabled;
670
+ const currentEditor = activeConfig.editor;
671
+ const currentAutoCommit = activeConfig.autoCommit;
672
+ const currentProtectedPaths = activeConfig.permissions.protectedPaths;
673
+ const currentIgnore = activeConfig.context.ignore;
674
+ const choice = await Prompt.askSelect(
675
+ "Select a configuration key to modify:",
676
+ [
677
+ {
678
+ value: "permissions.mode",
679
+ label: `\u{1F6E1}\uFE0F permissions.mode (current: ${currentMode})`
680
+ },
681
+ {
682
+ value: "budgetLimit",
683
+ label: `\u{1F4B0} budgetLimit (current: $${currentBudget})`
684
+ },
685
+ {
686
+ value: "permissions.allowRead",
687
+ label: `\u{1F4C4} permissions.allowRead (current: ${currentAllowRead})`
688
+ },
689
+ {
690
+ value: "permissions.requireApprovalForWrite",
691
+ label: `\u270F\uFE0F permissions.requireApprovalForWrite (current: ${currentApprovalWrite})`
692
+ },
693
+ {
694
+ value: "permissions.requireApprovalForBash",
695
+ label: `\u{1F41A} permissions.requireApprovalForBash (current: ${currentApprovalBash})`
696
+ },
697
+ {
698
+ value: "permissions.blockDangerousCommands",
699
+ label: `\u{1F6AB} permissions.blockDangerousCommands (current: ${currentBlockDangerous})`
700
+ },
701
+ {
702
+ value: "permissions.protectSecrets",
703
+ label: `\u{1F511} permissions.protectSecrets (current: ${currentProtectSecrets})`
704
+ },
705
+ {
706
+ value: "tools.bash.enabled",
707
+ label: `\u{1F4BB} tools.bash.enabled (current: ${currentBashEnabled})`
708
+ },
709
+ {
710
+ value: "tools.webSearch.enabled",
711
+ label: `\u{1F310} tools.webSearch.enabled (current: ${currentSearchEnabled})`
712
+ },
713
+ {
714
+ value: "tools.mcp.enabled",
715
+ label: `\u{1F50C} tools.mcp.enabled (current: ${currentMcpEnabled})`
716
+ },
717
+ {
718
+ value: "permissions.protectedPaths",
719
+ label: `\u{1F512} permissions.protectedPaths (current: ${currentProtectedPaths.join(", ")})`
720
+ },
721
+ {
722
+ value: "context.ignore",
723
+ label: `\u{1F5C2}\uFE0F context.ignore (current: ${currentIgnore.join(", ")})`
724
+ },
725
+ {
726
+ value: "editor",
727
+ label: `\u{1F4DD} editor (current: ${currentEditor})`
728
+ },
729
+ {
730
+ value: "autoCommit",
731
+ label: `\u{1F680} autoCommit (current: ${currentAutoCommit})`
732
+ },
733
+ { value: "exit", label: "\u274C Exit Menu" }
734
+ ]
735
+ );
736
+ if (choice === null || choice === "exit" || choice === "") {
737
+ break;
738
+ }
739
+ const currentVal = this.getNestedProperty(activeConfig, choice);
740
+ if (typeof currentVal === "boolean") {
741
+ const nextVal = await Prompt.askSelect(`Set ${choice} to:`, [
742
+ { value: "true", label: "true" },
743
+ { value: "false", label: "false" }
744
+ ]);
745
+ if (nextVal !== null && nextVal !== "") {
746
+ const boolVal = nextVal === "true";
747
+ const testConfig = JSON.parse(JSON.stringify(activeConfig));
748
+ this.setNestedProperty(testConfig, choice, boolVal);
749
+ const parseResult = ConfigSchema.safeParse(testConfig);
750
+ if (parseResult.success) {
751
+ this.setNestedProperty(activeConfig, choice, boolVal);
752
+ console.log(
753
+ picocolors4.green(`\u2714 Updated "${choice}" to: ${boolVal}`)
754
+ );
755
+ } else {
756
+ console.log(
757
+ picocolors4.red(
758
+ `Validation error: ${parseResult.error.message}`
759
+ )
760
+ );
761
+ }
762
+ }
763
+ } else if (choice === "permissions.mode") {
764
+ const nextVal = await Prompt.askSelect(
765
+ "Set permissions.mode to:",
766
+ [
767
+ {
768
+ value: "strict",
769
+ label: "strict (High security, ask for write/exec, block dangerous)"
770
+ },
771
+ {
772
+ value: "normal",
773
+ label: "normal (Standard safety, ask for all write/exec)"
774
+ },
775
+ {
776
+ value: "auto",
777
+ label: "auto (Allow write/exec automatically, block dangerous)"
778
+ },
779
+ {
780
+ value: "plan",
781
+ label: "plan (Interactive planning mode - read-only)"
782
+ }
783
+ ]
784
+ );
785
+ if (nextVal !== null && nextVal !== "") {
786
+ const testConfig = JSON.parse(JSON.stringify(activeConfig));
787
+ this.setNestedProperty(testConfig, choice, nextVal);
788
+ const parseResult = ConfigSchema.safeParse(testConfig);
789
+ if (parseResult.success) {
790
+ this.setNestedProperty(activeConfig, choice, nextVal);
791
+ console.log(
792
+ picocolors4.green(`\u2714 Updated "${choice}" to: ${nextVal}`)
793
+ );
794
+ } else {
795
+ console.log(
796
+ picocolors4.red(
797
+ `Validation error: ${parseResult.error.message}`
798
+ )
799
+ );
800
+ }
801
+ }
802
+ } else if (choice === "budgetLimit") {
803
+ const nextValStr = await Prompt.askText(
804
+ `Enter new budget limit (number):`,
805
+ String(currentVal)
806
+ );
807
+ if (nextValStr !== null && nextValStr !== "") {
808
+ const numVal = Number(nextValStr);
809
+ if (isNaN(numVal)) {
810
+ console.log(
811
+ picocolors4.red(
812
+ "Error: budgetLimit must be a valid number."
813
+ )
814
+ );
815
+ } else {
816
+ const testConfig = JSON.parse(JSON.stringify(activeConfig));
817
+ this.setNestedProperty(testConfig, choice, numVal);
818
+ const parseResult = ConfigSchema.safeParse(testConfig);
819
+ if (parseResult.success) {
820
+ this.setNestedProperty(activeConfig, choice, numVal);
821
+ console.log(
822
+ picocolors4.green(`\u2714 Updated "${choice}" to: ${numVal}`)
823
+ );
824
+ } else {
825
+ console.log(
826
+ picocolors4.red(
827
+ `Validation error: ${parseResult.error.message}`
828
+ )
829
+ );
830
+ }
831
+ }
832
+ }
833
+ } else if (Array.isArray(currentVal)) {
834
+ const nextValStr = await Prompt.askText(
835
+ `Enter comma-separated values for ${choice}:`,
836
+ currentVal.join(", ")
837
+ );
838
+ if (nextValStr !== null && nextValStr !== "") {
839
+ const arrVal = nextValStr.split(",").map((s) => s.trim()).filter(Boolean);
840
+ const testConfig = JSON.parse(JSON.stringify(activeConfig));
841
+ this.setNestedProperty(testConfig, choice, arrVal);
842
+ const parseResult = ConfigSchema.safeParse(testConfig);
843
+ if (parseResult.success) {
844
+ this.setNestedProperty(activeConfig, choice, arrVal);
845
+ console.log(
846
+ picocolors4.green(
847
+ `\u2714 Updated "${choice}" to: [${arrVal.join(", ")}]`
848
+ )
849
+ );
850
+ } else {
851
+ console.log(
852
+ picocolors4.red(
853
+ `Validation error: ${parseResult.error.message}`
854
+ )
855
+ );
856
+ }
857
+ }
858
+ } else if (typeof currentVal === "string" && choice !== "permissions.mode") {
859
+ const nextValStr = await Prompt.askText(
860
+ `Enter value for ${choice}:`,
861
+ String(currentVal)
862
+ );
863
+ if (nextValStr !== null && nextValStr !== "") {
864
+ const testConfig = JSON.parse(JSON.stringify(activeConfig));
865
+ this.setNestedProperty(testConfig, choice, nextValStr);
866
+ const parseResult = ConfigSchema.safeParse(testConfig);
867
+ if (parseResult.success) {
868
+ this.setNestedProperty(activeConfig, choice, nextValStr);
869
+ console.log(
870
+ picocolors4.green(
871
+ `\u2714 Updated "${choice}" to: ${nextValStr}`
872
+ )
873
+ );
874
+ } else {
875
+ console.log(
876
+ picocolors4.red(
877
+ `Validation error: ${parseResult.error.message}`
878
+ )
879
+ );
880
+ }
881
+ }
882
+ }
883
+ }
884
+ } finally {
885
+ if (wasActive && !tui.isActive) {
886
+ tui.start(config.budgetLimit);
887
+ }
888
+ }
889
+ return { shouldExit: false, processed: true };
890
+ }
891
+ if (command === "/model") {
892
+ const modelArg = parts.slice(1).join(" ").trim();
893
+ const activeConfig = loop.getConfig();
894
+ if (!modelArg) {
895
+ const wasActive = useFullscreenTui && tui.isActive;
896
+ if (wasActive) tui.stop();
897
+ try {
898
+ const activeModel = loop.getModelOverride() || activeConfig.models.default;
899
+ let modelOptions = [];
900
+ const providerId = this.providerInstance.id;
901
+ if (providerId === "anthropic") {
902
+ modelOptions = [
903
+ {
904
+ value: "claude-3-5-sonnet-latest",
905
+ label: "claude-3-5-sonnet-latest (Claude 3.5 Sonnet - Recommended)"
906
+ },
907
+ {
908
+ value: "claude-3-5-haiku-latest",
909
+ label: "claude-3-5-haiku-latest (Claude 3.5 Haiku)"
910
+ },
911
+ {
912
+ value: "claude-3-opus-latest",
913
+ label: "claude-3-opus-latest (Claude 3 Opus)"
914
+ }
915
+ ];
916
+ } else if (providerId === "openai") {
917
+ modelOptions = [
918
+ { value: "gpt-4o", label: "gpt-4o (GPT-4o - Recommended)" },
919
+ { value: "gpt-4o-mini", label: "gpt-4o-mini (GPT-4o mini)" },
920
+ { value: "o1", label: "o1 (o1 Reasoner)" },
921
+ {
922
+ value: "o3-mini",
923
+ label: "o3-mini (o3-mini Fast Reasoner)"
924
+ }
925
+ ];
926
+ } else if (providerId === "deepseek-openai" || providerId === "deepseek-anthropic") {
927
+ modelOptions = [
928
+ {
929
+ value: "deepseek-v4-flash",
930
+ label: "deepseek-v4-flash (DeepSeek-V4 / Fast & Flash - Recommended)"
931
+ },
932
+ {
933
+ value: "deepseek-v4-pro",
934
+ label: "deepseek-v4-pro (DeepSeek-V4 / Advanced & Pro)"
935
+ },
936
+ {
937
+ value: "deepseek-chat",
938
+ label: "deepseek-chat (DeepSeek-V3 / Chat)"
939
+ },
940
+ {
941
+ value: "deepseek-reasoner",
942
+ label: "deepseek-reasoner (DeepSeek-R1 / Reasoner)"
943
+ }
944
+ ];
945
+ } else if (providerId === "ollama") {
946
+ modelOptions = [
947
+ { value: "qwen2.5-coder:7b", label: "qwen2.5-coder:7b" },
948
+ { value: "qwen2.5-coder:1.5b", label: "qwen2.5-coder:1.5b" },
949
+ { value: "llama3", label: "llama3" }
950
+ ];
951
+ } else {
952
+ modelOptions = [
953
+ {
954
+ value: "deepseek-v4-flash",
955
+ label: "deepseek-v4-flash (DeepSeek-V4 / Fast & Flash)"
956
+ },
957
+ {
958
+ value: "deepseek-v4-pro",
959
+ label: "deepseek-v4-pro (DeepSeek-V4 / Advanced & Pro)"
960
+ },
961
+ { value: "gpt-4o", label: "gpt-4o (GPT-4o)" },
962
+ {
963
+ value: "claude-3-5-sonnet-latest",
964
+ label: "claude-3-5-sonnet-latest (Claude 3.5 Sonnet)"
965
+ }
966
+ ];
967
+ }
968
+ modelOptions.push({
969
+ value: "custom",
970
+ label: "Custom model name..."
971
+ });
972
+ modelOptions.push({ value: "cancel", label: "Cancel" });
973
+ const selectedModel = await Prompt.askSelect(
974
+ `Current model: ${activeModel}. Select a model to switch:`,
975
+ modelOptions
976
+ );
977
+ if (!selectedModel || selectedModel === "cancel") {
978
+ return { shouldExit: false, processed: true };
979
+ }
980
+ let finalModel = selectedModel;
981
+ if (selectedModel === "custom") {
982
+ const customModel = await Prompt.askText(
983
+ "Enter custom model name:"
984
+ );
985
+ if (customModel) {
986
+ finalModel = customModel;
987
+ loop.setModelOverride(customModel);
988
+ if (wasActive && !tui.isActive) {
989
+ tui.start(config.budgetLimit);
990
+ }
991
+ this.printOutput(
992
+ `Switched active model to: ${picocolors4.green(customModel)}`
993
+ );
994
+ } else {
995
+ return { shouldExit: false, processed: true };
996
+ }
997
+ } else {
998
+ loop.setModelOverride(selectedModel);
999
+ if (wasActive && !tui.isActive) {
1000
+ tui.start(config.budgetLimit);
1001
+ }
1002
+ this.printOutput(
1003
+ `Switched active model to: ${picocolors4.green(selectedModel)}`
1004
+ );
1005
+ }
1006
+ this.saveLocalState({ lastModel: finalModel });
1007
+ } finally {
1008
+ if (wasActive && !tui.isActive) {
1009
+ tui.start(config.budgetLimit);
1010
+ }
1011
+ }
1012
+ return { shouldExit: false, processed: true };
1013
+ }
1014
+ loop.setModelOverride(modelArg);
1015
+ this.printOutput(
1016
+ `Switched active model to: ${picocolors4.green(modelArg)}`
1017
+ );
1018
+ this.saveLocalState({ lastModel: modelArg });
1019
+ return { shouldExit: false, processed: true };
1020
+ }
1021
+ if (command === "/commit") {
1022
+ const commitMsg = parts.slice(1).join(" ").trim();
1023
+ const isZh = config.language === "zh";
1024
+ const { execSync: execSync2 } = await import("child_process");
1025
+ try {
1026
+ let diff = execSync2("git diff --cached", { cwd }).toString().trim();
1027
+ if (!diff) {
1028
+ const unstaged = execSync2("git status --porcelain", { cwd }).toString().trim();
1029
+ if (!unstaged) {
1030
+ console.log(
1031
+ picocolors4.yellow(
1032
+ isZh ? "\u5DE5\u4F5C\u533A\u5E72\u51C0\uFF0C\u6CA1\u6709\u68C0\u6D4B\u5230\u4EFB\u4F55\u5DF2\u6682\u5B58\u6216\u672A\u6682\u5B58\u7684\u66F4\u6539\u3002" : "Workspace clean. No staged or unstaged changes found to commit."
1033
+ )
1034
+ );
1035
+ return { shouldExit: false, processed: true };
1036
+ }
1037
+ const wasActive = useFullscreenTui && tui.isActive;
1038
+ if (wasActive) tui.stop();
1039
+ const autoStage = await Prompt.askApproval(
1040
+ isZh ? "\u672A\u68C0\u6D4B\u5230\u5DF2\u6682\u5B58\u7684\u4FEE\u6539\uFF0C\u662F\u5426\u81EA\u52A8\u6682\u5B58\u5DE5\u4F5C\u533A\u4E2D\u7684\u6240\u6709\u53D8\u66F4\u5E76\u751F\u6210\u63D0\u4EA4\uFF1F" : "No staged changes found. Automatically stage all local changes and create a commit?"
1041
+ );
1042
+ if (wasActive) tui.start(config.budgetLimit);
1043
+ if (!autoStage) {
1044
+ console.log(
1045
+ picocolors4.yellow(
1046
+ isZh ? "\u64CD\u4F5C\u5DF2\u53D6\u6D88\u3002\u8BF7\u5148\u8FD0\u884C 'git add' \u6682\u5B58\u4F60\u7684\u4FEE\u6539\u3002" : "Operation cancelled. Please run 'git add' to stage your changes first."
1047
+ )
1048
+ );
1049
+ return { shouldExit: false, processed: true };
1050
+ }
1051
+ console.log(
1052
+ isZh ? "\u6B63\u5728\u6682\u5B58\u6240\u6709\u53D8\u66F4..." : "Staging all changes..."
1053
+ );
1054
+ execSync2("git add -A", { cwd });
1055
+ diff = execSync2("git diff --cached", { cwd }).toString().trim();
1056
+ if (!diff) {
1057
+ console.log(
1058
+ picocolors4.red(
1059
+ isZh ? "\u2716 \u6682\u5B58\u5931\u8D25\u6216\u6682\u5B58\u540E\u4ECD\u65E0\u53D8\u66F4\u3002" : "\u2716 Staging failed or resulted in no diff."
1060
+ )
1061
+ );
1062
+ return { shouldExit: false, processed: true };
1063
+ }
1064
+ }
1065
+ let finalMsg = commitMsg;
1066
+ if (!finalMsg) {
1067
+ console.log("Generating commit message via LLM...");
1068
+ const fastModel = config.models.fast || config.models.default;
1069
+ const stream = this.providerInstance.chat({
1070
+ model: fastModel,
1071
+ messages: [
1072
+ {
1073
+ id: `msg_commit_cmd_${Date.now()}`,
1074
+ role: "user",
1075
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1076
+ content: [
1077
+ {
1078
+ type: "text",
1079
+ text: `Generate a concise, high-quality conventional git commit message (e.g. feat(cli): add autocomplete) for the following git diff. Output ONLY the commit message, no formatting, no markdown, no quotes, just the text:
1080
+
1081
+ ${diff.substring(0, 2e4)}`
1082
+ }
1083
+ ]
1084
+ }
1085
+ ],
1086
+ tools: []
1087
+ });
1088
+ let generatedMessage = "";
1089
+ for await (const event of stream) {
1090
+ if (event.type === "text_delta") {
1091
+ generatedMessage += event.text;
1092
+ }
1093
+ }
1094
+ finalMsg = generatedMessage.trim().replace(/^["']|["']$/g, "");
1095
+ if (!finalMsg) {
1096
+ finalMsg = "chore: auto-commit";
1097
+ }
1098
+ }
1099
+ console.log(
1100
+ `Committing changes with message: "${picocolors4.green(finalMsg)}"`
1101
+ );
1102
+ const commitCmd = `git commit -m ${JSON.stringify(finalMsg)}`;
1103
+ execSync2(commitCmd, { cwd });
1104
+ console.log(picocolors4.green("\u2714 Git commit created successfully."));
1105
+ } catch (err) {
1106
+ console.log(picocolors4.red(`\u2716 Commit failed: ${err.message}`));
1107
+ }
1108
+ return { shouldExit: false, processed: true };
1109
+ }
1110
+ if (command === "/add") {
1111
+ let fileArg = parts.slice(1).join(" ").trim();
1112
+ const isZh = config.language === "zh";
1113
+ const candidates = this.getCandidates();
1114
+ let readOnly = false;
1115
+ if (fileArg.startsWith("--read-only ") || fileArg.startsWith("--readonly ") || fileArg.startsWith("-r ")) {
1116
+ readOnly = true;
1117
+ fileArg = fileArg.replace(/^(--read-only|--readonly|-r)\s+/, "").trim();
1118
+ } else if (fileArg === "--read-only" || fileArg === "--readonly" || fileArg === "-r") {
1119
+ readOnly = true;
1120
+ fileArg = "";
1121
+ }
1122
+ if (!fileArg) {
1123
+ const wasActive = useFullscreenTui && tui.isActive;
1124
+ if (wasActive) tui.stop();
1125
+ try {
1126
+ if (!candidates || !candidates.files || candidates.files.length === 0) {
1127
+ console.log(
1128
+ isZh ? picocolors4.yellow("\u5DE5\u4F5C\u533A\u672A\u627E\u5230\u53EF\u6DFB\u52A0\u7684\u6587\u4EF6\u3002") : picocolors4.yellow(
1129
+ "No files found in the workspace to add."
1130
+ )
1131
+ );
1132
+ } else {
1133
+ const filterQuery = await Prompt.askText(
1134
+ isZh ? "\u8F93\u5165\u6587\u4EF6\u540D\u8FC7\u6EE4\u8BCD\uFF08\u652F\u6301\u6A21\u7CCA\u5339\u914D\uFF0C\u76F4\u63A5\u56DE\u8F66\u5217\u51FA\u6240\u6709\uFF09\uFF1A" : "Enter filename filter query (fuzzy, press Enter for all):"
1135
+ );
1136
+ if (filterQuery === null) {
1137
+ console.log(
1138
+ isZh ? picocolors4.yellow("\u64CD\u4F5C\u5DF2\u53D6\u6D88\u3002") : picocolors4.yellow("Operation cancelled.")
1139
+ );
1140
+ return { shouldExit: false, processed: true };
1141
+ }
1142
+ let filtered = candidates.files;
1143
+ if (filterQuery.trim()) {
1144
+ const q = filterQuery.trim().toLowerCase();
1145
+ filtered = candidates.files.filter(
1146
+ (f) => f.toLowerCase().includes(q)
1147
+ );
1148
+ }
1149
+ if (filtered.length === 0) {
1150
+ console.log(
1151
+ isZh ? picocolors4.yellow("\u672A\u627E\u5230\u5339\u914D\u8FC7\u6EE4\u8BCD\u7684\u6587\u4EF6\u3002") : picocolors4.yellow("No matching files found.")
1152
+ );
1153
+ } else {
1154
+ const options = filtered.map((f) => ({ value: f, label: f }));
1155
+ const selected = await Prompt.askMultiSelect(
1156
+ isZh ? readOnly ? "\u9009\u62E9\u8981\u6DFB\u52A0\u5230\u4E0A\u4E0B\u6587\u7684\u53EA\u8BFB\u53C2\u8003\u6587\u4EF6\uFF1A" : "\u9009\u62E9\u8981\u6DFB\u52A0\u5230\u4E0A\u4E0B\u6587\u7684\u6587\u4EF6\uFF1A" : readOnly ? "Select files to add as read-only reference context:" : "Select files to add to the context:",
1157
+ options
1158
+ );
1159
+ if (selected && selected.length > 0) {
1160
+ for (const f of selected) {
1161
+ if (readOnly) {
1162
+ loop.addReadOnlyFilePublic(
1163
+ f,
1164
+ "Manually added via interactive /add --read-only"
1165
+ );
1166
+ } else {
1167
+ loop.addRelevantFilePublic(
1168
+ f,
1169
+ "Manually added via interactive /add"
1170
+ );
1171
+ }
1172
+ }
1173
+ console.log(
1174
+ isZh ? readOnly ? picocolors4.green(
1175
+ `\u2714 \u6210\u529F\u6DFB\u52A0 ${selected.length} \u4E2A\u53EA\u8BFB\u6587\u4EF6\u5230\u4E0A\u4E0B\u6587\u3002`
1176
+ ) : picocolors4.green(
1177
+ `\u2714 \u6210\u529F\u6DFB\u52A0 ${selected.length} \u4E2A\u6587\u4EF6\u5230\u4E0A\u4E0B\u6587\u3002`
1178
+ ) : readOnly ? picocolors4.green(
1179
+ `\u2714 Added ${selected.length} read-only file(s) to active context.`
1180
+ ) : picocolors4.green(
1181
+ `\u2714 Added ${selected.length} file(s) to active context.`
1182
+ )
1183
+ );
1184
+ } else {
1185
+ console.log(
1186
+ isZh ? picocolors4.yellow("\u672A\u9009\u62E9\u4EFB\u4F55\u6587\u4EF6\u3002") : picocolors4.yellow("No files selected.")
1187
+ );
1188
+ }
1189
+ }
1190
+ }
1191
+ } catch (err) {
1192
+ console.log(
1193
+ isZh ? picocolors4.red(`\u9009\u62E9\u6587\u4EF6\u5931\u8D25: ${err.message}`) : picocolors4.red(`Failed to select files: ${err.message}`)
1194
+ );
1195
+ } finally {
1196
+ tui.syncFromLoop(loop);
1197
+ if (wasActive) tui.start(config.budgetLimit);
1198
+ }
1199
+ return { shouldExit: false, processed: true };
1200
+ }
1201
+ const { isAbsolute, relative, resolve: pathResolve } = await import("path");
1202
+ const { statSync } = await import("fs");
1203
+ const absPath = isAbsolute(fileArg) ? fileArg : pathResolve(cwd, fileArg);
1204
+ const relPath = relative(cwd, absPath).replace(/\\/g, "/");
1205
+ if (!existsSync3(absPath)) {
1206
+ const matched = (candidates?.files || []).filter(
1207
+ (f) => f.toLowerCase().includes(fileArg.toLowerCase()) || f.toLowerCase().endsWith("/" + fileArg.toLowerCase())
1208
+ );
1209
+ if (matched.length === 1) {
1210
+ if (readOnly) {
1211
+ loop.addReadOnlyFilePublic(
1212
+ matched[0],
1213
+ "Fuzzy matched via /add --read-only"
1214
+ );
1215
+ console.log(
1216
+ isZh ? picocolors4.green(`\u2714 \u81EA\u52A8\u5339\u914D\u5E76\u6DFB\u52A0\u53EA\u8BFB\u6587\u4EF6: ${matched[0]}`) : picocolors4.green(
1217
+ `\u2714 Auto-matched and added read-only file: ${matched[0]}`
1218
+ )
1219
+ );
1220
+ } else {
1221
+ loop.addRelevantFilePublic(matched[0], "Fuzzy matched via /add");
1222
+ console.log(
1223
+ isZh ? picocolors4.green(`\u2714 \u81EA\u52A8\u5339\u914D\u5E76\u6DFB\u52A0\u6587\u4EF6: ${matched[0]}`) : picocolors4.green(
1224
+ `\u2714 Auto-matched and added file: ${matched[0]}`
1225
+ )
1226
+ );
1227
+ }
1228
+ tui.syncFromLoop(loop);
1229
+ return { shouldExit: false, processed: true };
1230
+ } else if (matched.length > 1) {
1231
+ console.log(
1232
+ isZh ? picocolors4.yellow(
1233
+ `\u627E\u5230\u591A\u4E2A\u5339\u914D\u6587\u4EF6\uFF0C\u8BF7\u7CBE\u786E\u8F93\u5165\u8DEF\u5F84\u6216\u4F7F\u7528\u65E0\u53C2\u4EA4\u4E92\u9009\u62E9:
1234
+ ${matched.map((m) => ` \u2022 ${m}`).join("\n")}`
1235
+ ) : picocolors4.yellow(
1236
+ `Multiple matches found, please specify or use interactive select:
1237
+ ${matched.map((m) => ` \u2022 ${m}`).join("\n")}`
1238
+ )
1239
+ );
1240
+ return { shouldExit: false, processed: true };
1241
+ }
1242
+ console.log(
1243
+ isZh ? picocolors4.red(`\u6587\u4EF6\u4E0D\u5B58\u5728: ${fileArg}`) : picocolors4.red(`File does not exist: ${fileArg}`)
1244
+ );
1245
+ return { shouldExit: false, processed: true };
1246
+ }
1247
+ try {
1248
+ const stat = statSync(absPath);
1249
+ if (stat.isDirectory()) {
1250
+ const files = await glob("**/*", {
1251
+ cwd: absPath,
1252
+ onlyFiles: true,
1253
+ suppressErrors: true
1254
+ });
1255
+ for (const f of files) {
1256
+ const subRelPath = join3(relPath, f).replace(/\\/g, "/");
1257
+ if (readOnly) {
1258
+ loop.addReadOnlyFilePublic(
1259
+ subRelPath,
1260
+ "Manually added directory via /add --read-only"
1261
+ );
1262
+ } else {
1263
+ loop.addRelevantFilePublic(
1264
+ subRelPath,
1265
+ "Manually added directory via /add"
1266
+ );
1267
+ }
1268
+ }
1269
+ console.log(
1270
+ isZh ? readOnly ? picocolors4.green(
1271
+ `\u2714 \u6210\u529F\u6DFB\u52A0\u76EE\u5F55 ${relPath} \u4E0B\u7684\u6240\u6709\u53EA\u8BFB\u6587\u4EF6\u5230\u4E0A\u4E0B\u6587\u3002`
1272
+ ) : picocolors4.green(
1273
+ `\u2714 \u6210\u529F\u6DFB\u52A0\u76EE\u5F55 ${relPath} \u4E0B\u7684\u6240\u6709\u6587\u4EF6\u5230\u4E0A\u4E0B\u6587\u3002`
1274
+ ) : readOnly ? picocolors4.green(
1275
+ `\u2714 Added all files in directory ${relPath} as read-only to active context.`
1276
+ ) : picocolors4.green(
1277
+ `\u2714 Added all files in directory ${relPath} to active context.`
1278
+ )
1279
+ );
1280
+ } else {
1281
+ if (readOnly) {
1282
+ loop.addReadOnlyFilePublic(
1283
+ relPath,
1284
+ "Manually added file via /add --read-only"
1285
+ );
1286
+ console.log(
1287
+ isZh ? picocolors4.green(`\u2714 \u5DF2\u5C06\u53EA\u8BFB\u6587\u4EF6 ${relPath} \u6DFB\u52A0\u5230\u4E0A\u4E0B\u6587\u3002`) : picocolors4.green(
1288
+ `\u2714 Added read-only file ${relPath} to active context.`
1289
+ )
1290
+ );
1291
+ } else {
1292
+ loop.addRelevantFilePublic(
1293
+ relPath,
1294
+ "Manually added file via /add"
1295
+ );
1296
+ console.log(
1297
+ isZh ? picocolors4.green(`\u2714 \u5DF2\u5C06 ${relPath} \u6DFB\u52A0\u5230\u4E0A\u4E0B\u6587\u3002`) : picocolors4.green(`\u2714 Added ${relPath} to active context.`)
1298
+ );
1299
+ }
1300
+ }
1301
+ tui.syncFromLoop(loop);
1302
+ } catch (err) {
1303
+ console.log(
1304
+ isZh ? picocolors4.red(`\u6DFB\u52A0\u5931\u8D25: ${err.message}`) : picocolors4.red(`Failed to add: ${err.message}`)
1305
+ );
1306
+ }
1307
+ return { shouldExit: false, processed: true };
1308
+ }
1309
+ if (command === "/drop") {
1310
+ const fileArg = parts.slice(1).join(" ").trim();
1311
+ const isZh = config.language === "zh";
1312
+ if (!fileArg) {
1313
+ const wasActive = useFullscreenTui && tui.isActive;
1314
+ if (wasActive) tui.stop();
1315
+ try {
1316
+ const activeFiles2 = loop.getRelevantFiles();
1317
+ if (activeFiles2.length === 0) {
1318
+ console.log(
1319
+ isZh ? picocolors4.yellow("\u5F53\u524D\u6D3B\u52A8\u4E0A\u4E0B\u6587\u4E3A\u7A7A\uFF0C\u65E0\u53EF\u79FB\u9664\u7684\u6587\u4EF6\u3002") : picocolors4.yellow(
1320
+ "Active context is empty, no files to remove."
1321
+ )
1322
+ );
1323
+ } else {
1324
+ const options = activeFiles2.map((f) => ({
1325
+ value: f.path,
1326
+ label: f.path
1327
+ }));
1328
+ const selected = await Prompt.askMultiSelect(
1329
+ isZh ? "\u9009\u62E9\u8981\u4ECE\u4E0A\u4E0B\u6587\u4E2D\u79FB\u9664\u7684\u6587\u4EF6\uFF1A" : "Select files to remove from the context:",
1330
+ options
1331
+ );
1332
+ if (selected && selected.length > 0) {
1333
+ for (const f of selected) {
1334
+ loop.removeRelevantFilePublic(f);
1335
+ }
1336
+ console.log(
1337
+ isZh ? picocolors4.green(
1338
+ `\u2714 \u6210\u529F\u4ECE\u4E0A\u4E0B\u6587\u4E2D\u79FB\u9664 ${selected.length} \u4E2A\u6587\u4EF6\u3002`
1339
+ ) : picocolors4.green(
1340
+ `\u2714 Removed ${selected.length} file(s) from active context.`
1341
+ )
1342
+ );
1343
+ } else {
1344
+ console.log(
1345
+ isZh ? picocolors4.yellow("\u672A\u9009\u62E9\u4EFB\u4F55\u6587\u4EF6\u3002") : picocolors4.yellow("No files selected.")
1346
+ );
1347
+ }
1348
+ }
1349
+ } catch (err) {
1350
+ console.log(
1351
+ isZh ? picocolors4.red(`\u79FB\u9664\u6587\u4EF6\u5931\u8D25: ${err.message}`) : picocolors4.red(`Failed to remove files: ${err.message}`)
1352
+ );
1353
+ } finally {
1354
+ tui.syncFromLoop(loop);
1355
+ if (wasActive) tui.start(config.budgetLimit);
1356
+ }
1357
+ return { shouldExit: false, processed: true };
1358
+ }
1359
+ if (fileArg === "all" || fileArg === "*") {
1360
+ loop.clearRelevantFilesPublic();
1361
+ tui.syncFromLoop(loop);
1362
+ console.log(
1363
+ isZh ? picocolors4.green(`\u2714 \u5DF2\u4ECE\u4E0A\u4E0B\u6587\u4E2D\u6E05\u7A7A\u6240\u6709\u6587\u4EF6\u3002`) : picocolors4.green(`\u2714 Cleared all files from active context.`)
1364
+ );
1365
+ return { shouldExit: false, processed: true };
1366
+ }
1367
+ const { isAbsolute, relative, resolve: pathResolve } = await import("path");
1368
+ const absPath = isAbsolute(fileArg) ? fileArg : pathResolve(cwd, fileArg);
1369
+ const relPath = relative(cwd, absPath).replace(/\\/g, "/");
1370
+ const beforeCount = loop.getRelevantFiles().length;
1371
+ loop.removeRelevantFilePublic(relPath);
1372
+ const activeFiles = loop.getRelevantFiles().map((f) => f.path);
1373
+ const escaped = fileArg.replace(/[.+^${}()|[\]\\]/g, "\\$&");
1374
+ const globRegexStr = escaped.replace(/\*/g, ".*").replace(/\?/g, ".");
1375
+ const rx = new RegExp("^" + globRegexStr + "$", "i");
1376
+ for (const f of activeFiles) {
1377
+ if (rx.test(f) || f.startsWith(relPath)) {
1378
+ loop.removeRelevantFilePublic(f);
1379
+ }
1380
+ }
1381
+ tui.syncFromLoop(loop);
1382
+ const afterCount = loop.getRelevantFiles().length;
1383
+ const droppedCount = beforeCount - afterCount;
1384
+ if (droppedCount > 0) {
1385
+ console.log(
1386
+ isZh ? picocolors4.green(
1387
+ `\u2714 \u4ECE\u4E0A\u4E0B\u6587\u4E2D\u6210\u529F\u79FB\u9664 ${droppedCount} \u4E2A\u6587\u4EF6\u3002`
1388
+ ) : picocolors4.green(
1389
+ `\u2714 Removed ${droppedCount} file(s) from active context.`
1390
+ )
1391
+ );
1392
+ } else {
1393
+ console.log(
1394
+ isZh ? picocolors4.yellow(`\u4E0A\u4E0B\u6587\u4E2D\u672A\u627E\u5230\u5339\u914D "${fileArg}" \u7684\u6587\u4EF6\u3002`) : picocolors4.yellow(
1395
+ `No files matching "${fileArg}" were found in active context.`
1396
+ )
1397
+ );
1398
+ }
1399
+ return { shouldExit: false, processed: true };
1400
+ }
1401
+ if (command === "/clear") {
1402
+ console.clear();
1403
+ return { shouldExit: false, processed: true };
1404
+ }
1405
+ if (command === "/chat") {
1406
+ const wasActive = useFullscreenTui && tui.isActive;
1407
+ let stoppedTui = false;
1408
+ const stopTuiIfNeeded = () => {
1409
+ if (wasActive && !stoppedTui) {
1410
+ tui.stop();
1411
+ stoppedTui = true;
1412
+ }
1413
+ };
1414
+ const restoreTuiAndPrint = (msg) => {
1415
+ if (wasActive && stoppedTui && !tui.isActive) {
1416
+ tui.start(config.budgetLimit);
1417
+ stoppedTui = false;
1418
+ }
1419
+ this.printOutput(msg);
1420
+ };
1421
+ try {
1422
+ const subCommand = parts[1]?.toLowerCase();
1423
+ const arg = parts.slice(2).join(" ").trim();
1424
+ const sessions = loop.getSessions();
1425
+ const handleDelete = (idToDelete) => {
1426
+ loop.deleteSession(idToDelete);
1427
+ restoreTuiAndPrint(
1428
+ picocolors4.green(
1429
+ `\u2714 Session ${idToDelete} deleted successfully.`
1430
+ )
1431
+ );
1432
+ const activeSession = loop.state?.sessionId || loop.sessionManager.getActiveSession()?.id;
1433
+ if (activeSession === idToDelete) {
1434
+ const remaining = loop.getSessions();
1435
+ if (remaining.length > 0) {
1436
+ const targetSession = remaining[0];
1437
+ const success = loop.resumeSession(targetSession.id);
1438
+ if (success) {
1439
+ tui.loadHistory(loop.getHistory());
1440
+ restoreTuiAndPrint(
1441
+ picocolors4.green(
1442
+ `\u2714 Automatically switched to session: ${targetSession.id}`
1443
+ )
1444
+ );
1445
+ this.saveLocalState({
1446
+ lastSessionId: targetSession.id,
1447
+ lastModel: loop.getModelOverride() || config.models.default
1448
+ });
1449
+ }
1450
+ } else {
1451
+ const activeModel = loop.getModelOverride() || config.models.default;
1452
+ const newSessionId = loop.startNewSession(
1453
+ this.providerInstance.id,
1454
+ activeModel
1455
+ );
1456
+ tui.loadHistory([]);
1457
+ restoreTuiAndPrint(
1458
+ picocolors4.green(
1459
+ `\u2714 Automatically started new session: ${newSessionId}`
1460
+ )
1461
+ );
1462
+ this.saveLocalState({
1463
+ lastSessionId: newSessionId,
1464
+ lastModel: activeModel
1465
+ });
1466
+ }
1467
+ }
1468
+ };
1469
+ if (subCommand === "list" || subCommand === "ls") {
1470
+ if (sessions.length === 0) {
1471
+ restoreTuiAndPrint(
1472
+ picocolors4.yellow("No active or saved sessions found.")
1473
+ );
1474
+ } else {
1475
+ let listMsg = picocolors4.bold(
1476
+ picocolors4.cyan("\n=== Orbit Saved Sessions ===\n\n")
1477
+ );
1478
+ const activeSessionId = loop.state?.sessionId || loop.sessionManager.getActiveSession()?.id;
1479
+ sessions.forEach((s, idx) => {
1480
+ const formattedDate = new Date(s.createdAt).toLocaleString();
1481
+ const isActive = s.id === activeSessionId;
1482
+ const prefixStr = isActive ? picocolors4.green("\u25CF (active)") : " ";
1483
+ listMsg += ` ${prefixStr} [${idx + 1}] ${picocolors4.blue(s.id)} - ${s.title || "Untitled"} (${formattedDate}) [${s.model}]
1484
+ `;
1485
+ });
1486
+ listMsg += picocolors4.cyan("============================\n");
1487
+ restoreTuiAndPrint(listMsg);
1488
+ }
1489
+ return { shouldExit: false, processed: true };
1490
+ }
1491
+ if (subCommand === "delete" || subCommand === "rm" || subCommand === "del") {
1492
+ let idToDelete = arg;
1493
+ if (!idToDelete) {
1494
+ if (sessions.length === 0) {
1495
+ restoreTuiAndPrint(
1496
+ picocolors4.yellow(
1497
+ "No active or saved sessions found to delete."
1498
+ )
1499
+ );
1500
+ return { shouldExit: false, processed: true };
1501
+ }
1502
+ const deleteOptions = sessions.map((s) => {
1503
+ const formattedDate = new Date(s.createdAt).toLocaleString();
1504
+ return {
1505
+ value: s.id,
1506
+ label: `${s.id} - ${s.title || "Untitled"} (${formattedDate}) [${s.model}]`
1507
+ };
1508
+ });
1509
+ deleteOptions.push({
1510
+ value: "cancel",
1511
+ label: "Cancel"
1512
+ });
1513
+ stopTuiIfNeeded();
1514
+ idToDelete = await Prompt.askSelect(
1515
+ "Choose a session to delete:",
1516
+ deleteOptions
1517
+ );
1518
+ } else {
1519
+ const idx = parseInt(idToDelete, 10);
1520
+ if (!isNaN(idx) && idx >= 1 && idx <= sessions.length) {
1521
+ idToDelete = sessions[idx - 1].id;
1522
+ } else {
1523
+ const found = sessions.find((s) => s.id === idToDelete);
1524
+ if (!found) {
1525
+ restoreTuiAndPrint(
1526
+ picocolors4.red(`\u2716 Session not found: ${idToDelete}`)
1527
+ );
1528
+ return { shouldExit: false, processed: true };
1529
+ }
1530
+ }
1531
+ }
1532
+ if (!idToDelete || idToDelete === "cancel") {
1533
+ return { shouldExit: false, processed: true };
1534
+ }
1535
+ let confirm = "yes";
1536
+ if (!arg) {
1537
+ stopTuiIfNeeded();
1538
+ confirm = await Prompt.askSelect(
1539
+ `Are you sure you want to delete session ${idToDelete}?`,
1540
+ [
1541
+ { value: "yes", label: "Yes, delete it" },
1542
+ { value: "no", label: "No, cancel" }
1543
+ ]
1544
+ );
1545
+ }
1546
+ if (confirm === "yes") {
1547
+ handleDelete(idToDelete);
1548
+ }
1549
+ return { shouldExit: false, processed: true };
1550
+ }
1551
+ if (subCommand === "new" || subCommand === "create") {
1552
+ const activeModel = loop.getModelOverride() || config.models.default;
1553
+ const newSessionId = loop.startNewSession(
1554
+ this.providerInstance.id,
1555
+ activeModel
1556
+ );
1557
+ tui.loadHistory([]);
1558
+ restoreTuiAndPrint(
1559
+ picocolors4.green(`\u2714 Started new session: ${newSessionId}`)
1560
+ );
1561
+ this.saveLocalState({
1562
+ lastSessionId: newSessionId,
1563
+ lastModel: activeModel
1564
+ });
1565
+ return { shouldExit: false, processed: true };
1566
+ }
1567
+ if (subCommand === "switch" || subCommand === "load" || subCommand && (sessions.some((s) => s.id === subCommand) || !isNaN(parseInt(subCommand, 10)))) {
1568
+ let targetId = subCommand === "switch" || subCommand === "load" ? arg : subCommand;
1569
+ if (!targetId) {
1570
+ restoreTuiAndPrint(
1571
+ picocolors4.yellow("Usage: /chat switch <session_id | index>")
1572
+ );
1573
+ return { shouldExit: false, processed: true };
1574
+ }
1575
+ const idx = parseInt(targetId, 10);
1576
+ if (!isNaN(idx) && idx >= 1 && idx <= sessions.length) {
1577
+ targetId = sessions[idx - 1].id;
1578
+ }
1579
+ const found = sessions.find((s) => s.id === targetId);
1580
+ if (!found) {
1581
+ restoreTuiAndPrint(
1582
+ picocolors4.red(`\u2716 Session not found: ${targetId}`)
1583
+ );
1584
+ return { shouldExit: false, processed: true };
1585
+ }
1586
+ const success = loop.resumeSession(targetId);
1587
+ if (success) {
1588
+ tui.loadHistory(loop.getHistory());
1589
+ restoreTuiAndPrint(
1590
+ picocolors4.green(`\u2714 Switched to session: ${targetId}`)
1591
+ );
1592
+ this.saveLocalState({
1593
+ lastSessionId: targetId,
1594
+ lastModel: loop.getModelOverride() || config.models.default
1595
+ });
1596
+ } else {
1597
+ restoreTuiAndPrint(
1598
+ picocolors4.red(`\u2716 Failed to resume session: ${targetId}`)
1599
+ );
1600
+ }
1601
+ return { shouldExit: false, processed: true };
1602
+ }
1603
+ if (sessions.length === 0) {
1604
+ const activeModel = loop.getModelOverride() || config.models.default;
1605
+ const newSessionId = loop.startNewSession(
1606
+ this.providerInstance.id,
1607
+ activeModel
1608
+ );
1609
+ tui.loadHistory([]);
1610
+ restoreTuiAndPrint(
1611
+ picocolors4.green(`\u2714 Started new session: ${newSessionId}`)
1612
+ );
1613
+ this.saveLocalState({
1614
+ lastSessionId: newSessionId,
1615
+ lastModel: activeModel
1616
+ });
1617
+ return { shouldExit: false, processed: true };
1618
+ }
1619
+ const sessionOptions = sessions.map((s) => {
1620
+ const formattedDate = new Date(s.createdAt).toLocaleString();
1621
+ return {
1622
+ value: s.id,
1623
+ label: `${s.id} - ${s.title || "Untitled"} (${formattedDate}) [${s.model}]`
1624
+ };
1625
+ });
1626
+ sessionOptions.unshift({
1627
+ value: "new",
1628
+ label: picocolors4.green("+ Start a new session")
1629
+ });
1630
+ sessionOptions.unshift({
1631
+ value: "delete_menu",
1632
+ label: picocolors4.red("- Delete a session...")
1633
+ });
1634
+ sessionOptions.push({
1635
+ value: "cancel",
1636
+ label: "Cancel"
1637
+ });
1638
+ const selectedSessionId = await Prompt.askSelect(
1639
+ "Choose a session to load:",
1640
+ sessionOptions
1641
+ );
1642
+ if (!selectedSessionId || selectedSessionId === "cancel") {
1643
+ return { shouldExit: false, processed: true };
1644
+ }
1645
+ if (selectedSessionId === "delete_menu") {
1646
+ const deleteOptions = sessions.map((s) => {
1647
+ const formattedDate = new Date(s.createdAt).toLocaleString();
1648
+ return {
1649
+ value: s.id,
1650
+ label: `${s.id} - ${s.title || "Untitled"} (${formattedDate}) [${s.model}]`
1651
+ };
1652
+ });
1653
+ deleteOptions.push({
1654
+ value: "cancel",
1655
+ label: "Cancel"
1656
+ });
1657
+ const idToDelete = await Prompt.askSelect(
1658
+ "Choose a session to delete:",
1659
+ deleteOptions
1660
+ );
1661
+ if (idToDelete && idToDelete !== "cancel") {
1662
+ const confirm = await Prompt.askSelect(
1663
+ `Are you sure you want to delete session ${idToDelete}?`,
1664
+ [
1665
+ { value: "yes", label: "Yes, delete it" },
1666
+ { value: "no", label: "No, cancel" }
1667
+ ]
1668
+ );
1669
+ if (confirm === "yes") {
1670
+ handleDelete(idToDelete);
1671
+ }
1672
+ }
1673
+ } else if (selectedSessionId === "new") {
1674
+ const activeModel = loop.getModelOverride() || config.models.default;
1675
+ const newSessionId = loop.startNewSession(
1676
+ this.providerInstance.id,
1677
+ activeModel
1678
+ );
1679
+ tui.loadHistory([]);
1680
+ console.log(
1681
+ picocolors4.green(`\u2714 Started new session: ${newSessionId}`)
1682
+ );
1683
+ this.saveLocalState({
1684
+ lastSessionId: newSessionId,
1685
+ lastModel: activeModel
1686
+ });
1687
+ } else {
1688
+ const success = loop.resumeSession(selectedSessionId);
1689
+ if (success) {
1690
+ tui.loadHistory(loop.getHistory());
1691
+ console.log(
1692
+ picocolors4.green(
1693
+ `\u2714 Switched to session: ${selectedSessionId}`
1694
+ )
1695
+ );
1696
+ this.saveLocalState({
1697
+ lastSessionId: selectedSessionId,
1698
+ lastModel: loop.getModelOverride() || config.models.default
1699
+ });
1700
+ } else {
1701
+ console.log(
1702
+ picocolors4.red(
1703
+ `Failed to resume session: ${selectedSessionId}`
1704
+ )
1705
+ );
1706
+ }
1707
+ }
1708
+ } finally {
1709
+ try {
1710
+ tui.setCandidates(await getAutocompleteCandidates(cwd, config));
1711
+ } catch {
1712
+ }
1713
+ if (wasActive) tui.start(config.budgetLimit);
1714
+ }
1715
+ return { shouldExit: false, processed: true };
1716
+ }
1717
+ if (command === "/mode") {
1718
+ const isZh = config.language === "zh";
1719
+ const targetMode = parts.slice(1).join(" ").trim().toLowerCase();
1720
+ if (!targetMode) {
1721
+ console.log(
1722
+ isZh ? picocolors4.yellow("\u7528\u6CD5: /mode <strict|normal|auto|plan>") : picocolors4.yellow("Usage: /mode <strict|normal|auto|plan>")
1723
+ );
1724
+ return { shouldExit: false, processed: true };
1725
+ }
1726
+ const validModes = ["strict", "normal", "auto", "plan"];
1727
+ if (!validModes.includes(targetMode)) {
1728
+ console.log(
1729
+ isZh ? picocolors4.red(
1730
+ `\u2716 \u65E0\u6548\u7684\u5B89\u5168\u6A21\u5F0F: ${targetMode}\u3002\u53EF\u9009\u6A21\u5F0F: ${validModes.join(", ")}`
1731
+ ) : picocolors4.red(
1732
+ `\u2716 Invalid security mode: ${targetMode}. Valid modes: ${validModes.join(", ")}`
1733
+ )
1734
+ );
1735
+ return { shouldExit: false, processed: true };
1736
+ }
1737
+ loop.getConfig().permissions.mode = targetMode;
1738
+ console.log(
1739
+ isZh ? picocolors4.green(
1740
+ `\u2714 \u5DF2\u5207\u6362\u5B89\u5168\u6A21\u5F0F\u81F3: ${targetMode.toUpperCase()}`
1741
+ ) : picocolors4.green(
1742
+ `\u2714 Switched security mode to: ${targetMode.toUpperCase()}`
1743
+ )
1744
+ );
1745
+ tui.syncFromLoop(loop);
1746
+ return { shouldExit: false, processed: true };
1747
+ }
1748
+ if (command === "/copy") {
1749
+ const isZh = config.language === "zh";
1750
+ const history = loop.getHistory();
1751
+ const lastAssistantMsg = [...history].reverse().find((msg) => msg.role === "assistant");
1752
+ if (!lastAssistantMsg) {
1753
+ console.log(
1754
+ isZh ? picocolors4.yellow("\u6CA1\u6709\u627E\u5230 AI \u7684\u6700\u8FD1\u56DE\u590D\u3002") : picocolors4.yellow(
1755
+ "No recent assistant response found to copy."
1756
+ )
1757
+ );
1758
+ return { shouldExit: false, processed: true };
1759
+ }
1760
+ let textToCopy = "";
1761
+ if (typeof lastAssistantMsg.content === "string") {
1762
+ textToCopy = lastAssistantMsg.content;
1763
+ } else if (Array.isArray(lastAssistantMsg.content)) {
1764
+ textToCopy = lastAssistantMsg.content.map((c) => c.type === "text" ? c.text : "").join("");
1765
+ }
1766
+ if (!textToCopy) {
1767
+ console.log(
1768
+ isZh ? picocolors4.yellow("AI \u7684\u6700\u8FD1\u56DE\u590D\u5185\u5BB9\u4E3A\u7A7A\u3002") : picocolors4.yellow("Recent assistant response is empty.")
1769
+ );
1770
+ return { shouldExit: false, processed: true };
1771
+ }
1772
+ const copied = this.copyToClipboard(textToCopy);
1773
+ if (copied) {
1774
+ console.log(
1775
+ isZh ? picocolors4.green("\u2714 \u5DF2\u6210\u529F\u590D\u5236 AI \u6700\u8FD1\u56DE\u590D\u5230\u526A\u8D34\u677F\uFF01") : picocolors4.green(
1776
+ "\u2714 Successfully copied recent AI response to clipboard!"
1777
+ )
1778
+ );
1779
+ } else {
1780
+ console.log(
1781
+ isZh ? picocolors4.red(
1782
+ "\u2716 \u590D\u5236\u5230\u526A\u8D34\u677F\u5931\u8D25\uFF0C\u7CFB\u7EDF\u672A\u914D\u7F6E\u526A\u8D34\u677F\u5DE5\u5177\uFF08\u5982 pbcopy/clip/xclip\uFF09\u3002"
1783
+ ) : picocolors4.red(
1784
+ "\u2716 Failed to copy to clipboard. Ensure pbcopy/clip/xclip is installed."
1785
+ )
1786
+ );
1787
+ }
1788
+ return { shouldExit: false, processed: true };
1789
+ }
1790
+ this.printOutput(
1791
+ picocolors4.red(
1792
+ `Unknown command: ${trimmed}. Type /help for available commands.`
1793
+ )
1794
+ );
1795
+ return { shouldExit: false, processed: true };
1796
+ }
1797
+ return { shouldExit: false, processed: false };
1798
+ }
1799
+ getNestedProperty(obj, path) {
1800
+ const parts = path.split(".");
1801
+ let current = obj;
1802
+ for (const part of parts) {
1803
+ if (current == null || typeof current !== "object") {
1804
+ return void 0;
1805
+ }
1806
+ current = current[part];
1807
+ }
1808
+ return current;
1809
+ }
1810
+ setNestedProperty(obj, path, value) {
1811
+ const parts = path.split(".");
1812
+ let current = obj;
1813
+ for (let i = 0; i < parts.length - 1; i++) {
1814
+ const part = parts[i];
1815
+ if (!(part in current) || current[part] == null || typeof current[part] !== "object") {
1816
+ current[part] = {};
1817
+ }
1818
+ current = current[part];
1819
+ }
1820
+ current[parts[parts.length - 1]] = value;
1821
+ }
1822
+ copyToClipboard(text) {
1823
+ const { execSync: execSync2 } = require2("child_process");
1824
+ try {
1825
+ if (process.platform === "win32") {
1826
+ execSync2("clip", { input: text });
1827
+ return true;
1828
+ } else if (process.platform === "darwin") {
1829
+ execSync2("pbcopy", { input: text });
1830
+ return true;
1831
+ } else {
1832
+ try {
1833
+ execSync2("xclip -selection clipboard", { input: text });
1834
+ return true;
1835
+ } catch {
1836
+ try {
1837
+ execSync2("xsel -ib", { input: text });
1838
+ return true;
1839
+ } catch {
1840
+ try {
1841
+ execSync2("wl-copy", { input: text });
1842
+ return true;
1843
+ } catch {
1844
+ return false;
1845
+ }
1846
+ }
1847
+ }
1848
+ }
1849
+ } catch {
1850
+ return false;
1851
+ }
1852
+ }
1853
+ };
1854
+ async function getAutocompleteCandidates(cwd, config) {
1855
+ const customCommands = loadCustomCommands(cwd, BUILTIN_SLASH_COMMANDS);
1856
+ const commands = [
1857
+ ...BUILTIN_SLASH_COMMANDS,
1858
+ ...customCommands.map((command) => `/${command.name}`)
1859
+ ];
1860
+ const files = [];
1861
+ const symbols = [];
1862
+ const sessions = [];
1863
+ const normCwd = resolve(cwd).toLowerCase().replace(/\\/g, "/");
1864
+ const normHome = resolve(homedir2()).toLowerCase().replace(/\\/g, "/");
1865
+ const isHomeOrRoot = normCwd === normHome || normCwd === "/" || /^[a-zA-Z]:\/$/.test(normCwd) || dirname(normCwd) === normCwd;
1866
+ if (isHomeOrRoot) {
1867
+ return {
1868
+ commands,
1869
+ files,
1870
+ symbols,
1871
+ sessions
1872
+ };
1873
+ }
1874
+ try {
1875
+ const ignorePatterns = config.context?.ignore || [];
1876
+ const globbedFiles = await glob("**/*", {
1877
+ cwd,
1878
+ ignore: ignorePatterns,
1879
+ onlyFiles: true,
1880
+ dot: true,
1881
+ suppressErrors: true
1882
+ });
1883
+ files.push(...globbedFiles);
1884
+ } catch {
1885
+ }
1886
+ try {
1887
+ const indexPath = join3(cwd, ".orbit", "symbols.json");
1888
+ if (existsSync3(indexPath)) {
1889
+ const raw = readFileSync2(indexPath, "utf8");
1890
+ const index = JSON.parse(raw);
1891
+ if (index.files && typeof index.files === "object") {
1892
+ for (const fileData of Object.values(index.files)) {
1893
+ const data = fileData;
1894
+ if (data && Array.isArray(data.symbols)) {
1895
+ for (const sym of data.symbols) {
1896
+ if (sym.name) {
1897
+ symbols.push(sym.name);
1898
+ }
1899
+ }
1900
+ }
1901
+ }
1902
+ }
1903
+ }
1904
+ } catch {
1905
+ }
1906
+ try {
1907
+ const sessionDir = join3(cwd, ".orbit", "sessions");
1908
+ if (existsSync3(sessionDir)) {
1909
+ const dirs = readdirSync2(sessionDir);
1910
+ for (const dir of dirs) {
1911
+ const sessionFile = join3(sessionDir, dir, "session.json");
1912
+ if (existsSync3(sessionFile)) {
1913
+ sessions.push(dir);
1914
+ }
1915
+ }
1916
+ }
1917
+ } catch {
1918
+ }
1919
+ return {
1920
+ commands,
1921
+ files,
1922
+ symbols: Array.from(new Set(symbols)),
1923
+ sessions
1924
+ };
1925
+ }
1926
+
1927
+ // src/tui/FullscreenTui.ts
1928
+ function previousCodePointIndex(text, index) {
1929
+ const safeIndex = Math.max(0, Math.min(index, text.length));
1930
+ if (safeIndex === 0) return 0;
1931
+ const previous = text.charCodeAt(safeIndex - 1);
1932
+ if (previous >= 56320 && previous <= 57343 && safeIndex >= 2) {
1933
+ const leading = text.charCodeAt(safeIndex - 2);
1934
+ if (leading >= 55296 && leading <= 56319) {
1935
+ return safeIndex - 2;
1936
+ }
1937
+ }
1938
+ return safeIndex - 1;
1939
+ }
1940
+ function nextCodePointIndex(text, index) {
1941
+ const safeIndex = Math.max(0, Math.min(index, text.length));
1942
+ if (safeIndex >= text.length) return text.length;
1943
+ const leading = text.charCodeAt(safeIndex);
1944
+ if (leading >= 55296 && leading <= 56319 && safeIndex + 1 < text.length) {
1945
+ const trailing = text.charCodeAt(safeIndex + 1);
1946
+ if (trailing >= 56320 && trailing <= 57343) {
1947
+ return safeIndex + 2;
1948
+ }
1949
+ }
1950
+ return safeIndex + 1;
1951
+ }
1952
+ function previousWordIndex(text, index) {
1953
+ let pos = index;
1954
+ while (pos > 0 && /\s/.test(text.charAt(pos - 1))) {
1955
+ pos--;
1956
+ }
1957
+ while (pos > 0 && !/\s/.test(text.charAt(pos - 1))) {
1958
+ pos--;
1959
+ }
1960
+ return pos;
1961
+ }
1962
+ function nextWordIndex(text, index) {
1963
+ let pos = index;
1964
+ while (pos < text.length && /\s/.test(text.charAt(pos))) {
1965
+ pos++;
1966
+ }
1967
+ while (pos < text.length && !/\s/.test(text.charAt(pos))) {
1968
+ pos++;
1969
+ }
1970
+ return pos;
1971
+ }
1972
+ function parseMouseWheelDirection(input) {
1973
+ if (typeof input !== "string") return null;
1974
+ const match = input.match(/\x1b\[<(\d+);\d+;\d+[mM]/);
1975
+ if (!match) return null;
1976
+ const button = Number(match[1]);
1977
+ if ((button & 64) === 0) return null;
1978
+ return (button & 1) === 0 ? "up" : "down";
1979
+ }
1980
+ async function pageText(text) {
1981
+ const lines = text.split("\n");
1982
+ const rows = process.stdout.rows || 24;
1983
+ const pageSize = rows - 2;
1984
+ if (lines.length <= pageSize) {
1985
+ console.log(text);
1986
+ return;
1987
+ }
1988
+ let cursor = 0;
1989
+ const wasRaw = !!process.stdin.isRaw;
1990
+ if (process.stdin.setRawMode) {
1991
+ process.stdin.setRawMode(true);
1992
+ }
1993
+ process.stdin.resume();
1994
+ readline.emitKeypressEvents(process.stdin);
1995
+ const keypressPromise = () => {
1996
+ return new Promise((resolve3) => {
1997
+ const onKeypress = (str, key) => {
1998
+ process.stdin.removeListener("keypress", onKeypress);
1999
+ if (key && key.ctrl && key.name === "c") {
2000
+ if (process.stdin.setRawMode) {
2001
+ process.stdin.setRawMode(wasRaw);
2002
+ }
2003
+ process.exit(0);
2004
+ }
2005
+ resolve3(key ? key.name || str : str);
2006
+ };
2007
+ process.stdin.on("keypress", onKeypress);
2008
+ });
2009
+ };
2010
+ try {
2011
+ while (cursor < lines.length) {
2012
+ const chunk = lines.slice(cursor, cursor + pageSize);
2013
+ console.log(chunk.join("\n"));
2014
+ cursor += pageSize;
2015
+ if (cursor >= lines.length) {
2016
+ break;
2017
+ }
2018
+ process.stdout.write(
2019
+ `\r\x1B[36m-- More (${Math.round(cursor / lines.length * 100)}%) [Space/Enter to continue, q to quit] --\x1B[39m`
2020
+ );
2021
+ const key = await keypressPromise();
2022
+ process.stdout.write("\r\x1B[K");
2023
+ if (key === "q") {
2024
+ break;
2025
+ }
2026
+ if (key === "return" || key === "enter") {
2027
+ cursor = cursor - pageSize + 1;
2028
+ }
2029
+ }
2030
+ } finally {
2031
+ if (process.stdin.setRawMode) {
2032
+ process.stdin.setRawMode(wasRaw);
2033
+ }
2034
+ process.stdin.pause();
2035
+ }
2036
+ }
2037
+ var FullscreenTui = class {
2038
+ constructor(cwd, modelName, version, config) {
2039
+ this.cwd = cwd;
2040
+ this.modelName = modelName;
2041
+ this.version = version;
2042
+ this.config = config;
2043
+ readline.emitKeypressEvents(process.stdin);
2044
+ process.stdout.write = (chunk, encoding, cb) => {
2045
+ if (!this.isActive) {
2046
+ const text = typeof chunk === "string" ? chunk : chunk.toString();
2047
+ if (text.trim().length > 0) {
2048
+ this.hasWrittenStdoutSinceStop = true;
2049
+ }
2050
+ }
2051
+ return this.originalWrite(chunk, encoding, cb);
2052
+ };
2053
+ this.loadInputHistory();
2054
+ }
2055
+ cwd;
2056
+ modelName;
2057
+ version;
2058
+ config;
2059
+ history = [];
2060
+ inputBuffer = "";
2061
+ cursorPosition = 0;
2062
+ isActive = false;
2063
+ currentAttempt = 0;
2064
+ // Command history
2065
+ inputHistory = [];
2066
+ historyIndex = -1;
2067
+ tempBuffer = "";
2068
+ activeCommandIndex = 0;
2069
+ ctrlCPressedOnce = false;
2070
+ ctrlCTimeout = null;
2071
+ cachedStaticLinesCount = 0;
2072
+ cachedStaticContent = "";
2073
+ lastRenderedBottomHeight = 0;
2074
+ // DeepSeek real-time thinking
2075
+ currentThinking = "";
2076
+ // Timers and metrics
2077
+ attemptStartTime = 0;
2078
+ firstDeltaTime = 0;
2079
+ thoughtTimer = null;
2080
+ thoughtElapsed = 0;
2081
+ isThinking = false;
2082
+ sessionCost = 0;
2083
+ totalInputTokens = 0;
2084
+ totalCacheReadTokens = 0;
2085
+ totalOutputTokens = 0;
2086
+ budgetLimit = 0;
2087
+ resolveInput = null;
2088
+ activeRunnable = null;
2089
+ thinkingKeypressListener = null;
2090
+ pendingGuidedStatement = null;
2091
+ // Throttled rendering to prevent terminal flickering during model output
2092
+ lastRenderTime = 0;
2093
+ renderPending = false;
2094
+ renderTimeout = null;
2095
+ originalWrite = process.stdout.write.bind(process.stdout);
2096
+ hasWrittenStdoutSinceStop = false;
2097
+ originalStdinEmit = null;
2098
+ candidates = null;
2099
+ modelNameGetter = () => this.modelName;
2100
+ permissionsMode = "normal";
2101
+ hideAutocomplete = false;
2102
+ cachedPlanLines = [];
2103
+ lastPlanReadTime = 0;
2104
+ activeContextFiles = [];
2105
+ cachedGitSummary = null;
2106
+ lastGitSummaryReadTime = 0;
2107
+ isRefreshingGit = false;
2108
+ historyScrollOffset = 0;
2109
+ maxHistoryScrollOffset = 0;
2110
+ lastHistoryLineCount = 0;
2111
+ hasNewOutputWhileScrolled = false;
2112
+ getPlanLines() {
2113
+ const now = Date.now();
2114
+ if (now - this.lastPlanReadTime < 2e3) {
2115
+ return this.cachedPlanLines;
2116
+ }
2117
+ this.lastPlanReadTime = now;
2118
+ const planPath2 = join4(this.cwd, ".orbit", "task.md");
2119
+ const planPath1 = join4(this.cwd, "task.md");
2120
+ let planPath = "";
2121
+ if (existsSync4(planPath2)) {
2122
+ planPath = planPath2;
2123
+ } else if (existsSync4(planPath1)) {
2124
+ planPath = planPath1;
2125
+ }
2126
+ if (!planPath) {
2127
+ this.cachedPlanLines = [];
2128
+ return [];
2129
+ }
2130
+ try {
2131
+ const content = readFileSync3(planPath, "utf8");
2132
+ const lines = content.split("\n");
2133
+ const planItems = [];
2134
+ for (const line of lines) {
2135
+ const trimmed = line.trim();
2136
+ if (trimmed.startsWith("- [ ") || trimmed.startsWith("- [x") || trimmed.startsWith("- [/") || trimmed.startsWith("- [x]") || trimmed.startsWith("- [ ]") || trimmed.startsWith("- [/]")) {
2137
+ planItems.push(trimmed);
2138
+ }
2139
+ }
2140
+ this.cachedPlanLines = planItems;
2141
+ } catch {
2142
+ this.cachedPlanLines = [];
2143
+ }
2144
+ return this.cachedPlanLines;
2145
+ }
2146
+ setPermissionsMode(mode) {
2147
+ this.permissionsMode = mode;
2148
+ }
2149
+ setModelNameGetter(getter) {
2150
+ this.modelNameGetter = getter;
2151
+ }
2152
+ setActiveRunnable(runnable) {
2153
+ this.activeRunnable = runnable;
2154
+ }
2155
+ setCandidates(candidates) {
2156
+ if (!candidates) {
2157
+ this.candidates = null;
2158
+ return;
2159
+ }
2160
+ this.candidates = {
2161
+ commands: Array.isArray(candidates.commands) ? candidates.commands.filter((c) => typeof c === "string") : [],
2162
+ files: Array.isArray(candidates.files) ? candidates.files.filter((f) => typeof f === "string") : [],
2163
+ symbols: Array.isArray(candidates.symbols) ? candidates.symbols.filter((s) => typeof s === "string") : [],
2164
+ sessions: Array.isArray(candidates.sessions) ? candidates.sessions.filter((s) => typeof s === "string") : []
2165
+ };
2166
+ }
2167
+ getHistoryFilePath() {
2168
+ return join4(homedir3(), ".orbit", "input_history.json");
2169
+ }
2170
+ loadInputHistory() {
2171
+ try {
2172
+ const filePath = this.getHistoryFilePath();
2173
+ if (existsSync4(filePath)) {
2174
+ const raw = readFileSync3(filePath, "utf8");
2175
+ const parsed = JSON.parse(raw);
2176
+ if (Array.isArray(parsed)) {
2177
+ this.inputHistory = parsed.filter((x) => typeof x === "string");
2178
+ }
2179
+ }
2180
+ } catch {
2181
+ this.inputHistory = [];
2182
+ }
2183
+ }
2184
+ saveInputHistory() {
2185
+ try {
2186
+ const filePath = this.getHistoryFilePath();
2187
+ const dir = dirname2(filePath);
2188
+ if (!existsSync4(dir)) {
2189
+ mkdirSync(dir, { recursive: true });
2190
+ }
2191
+ writeFileSync2(
2192
+ filePath,
2193
+ JSON.stringify(this.inputHistory, null, 2),
2194
+ "utf8"
2195
+ );
2196
+ } catch {
2197
+ }
2198
+ }
2199
+ addSystemMessage(text, _raw = false) {
2200
+ if (!text) return;
2201
+ this.history.push({
2202
+ role: "system",
2203
+ text
2204
+ });
2205
+ this.render();
2206
+ }
2207
+ onResize = () => {
2208
+ if (this.isActive) {
2209
+ this.render(true);
2210
+ }
2211
+ };
2212
+ start(budgetLimit) {
2213
+ this.budgetLimit = budgetLimit;
2214
+ this.isActive = true;
2215
+ this.hasWrittenStdoutSinceStop = false;
2216
+ if (this.originalStdinEmit) {
2217
+ process.stdin.emit = this.originalStdinEmit;
2218
+ this.originalStdinEmit = null;
2219
+ }
2220
+ const mouseMode = this.config?.tui?.mouse !== false ? "\x1B[?1000h\x1B[?1006h" : "";
2221
+ process.stdout.write(`\x1B[?1049h${mouseMode}\x1B[?25l`);
2222
+ process.stdout.on("resize", this.onResize);
2223
+ if (this.config?.tui?.mouse !== false) {
2224
+ this.originalStdinEmit = process.stdin.emit;
2225
+ process.stdin.emit = (event, ...args) => {
2226
+ if (event === "data" && args[0]) {
2227
+ const chunk = args[0];
2228
+ const isBuffer = Buffer.isBuffer(chunk);
2229
+ let str = isBuffer ? chunk.toString("utf8") : chunk;
2230
+ const sgrRegex = /\x1b\[<(\d+);(\d+);(\d+)([mM])/g;
2231
+ let match;
2232
+ let hasMouse = false;
2233
+ while ((match = sgrRegex.exec(str)) !== null) {
2234
+ hasMouse = true;
2235
+ const button = Number(match[1]);
2236
+ if ((button & 64) !== 0) {
2237
+ const direction = (button & 1) === 0 ? "up" : "down";
2238
+ const lines = this.getWheelScrollLines();
2239
+ this.scrollHistory(direction === "up" ? lines : -lines);
2240
+ }
2241
+ }
2242
+ if (hasMouse) {
2243
+ str = str.replace(sgrRegex, "");
2244
+ }
2245
+ const normalRegex = /\x1b\[M([\s\S]{3})/g;
2246
+ if (normalRegex.test(str)) {
2247
+ str = str.replace(normalRegex, "");
2248
+ hasMouse = true;
2249
+ }
2250
+ if (hasMouse) {
2251
+ if (str.length === 0) {
2252
+ return true;
2253
+ }
2254
+ args[0] = isBuffer ? Buffer.from(str, "utf8") : str;
2255
+ }
2256
+ }
2257
+ return this.originalStdinEmit.apply(process.stdin, [event, ...args]);
2258
+ };
2259
+ }
2260
+ this.render();
2261
+ }
2262
+ stop() {
2263
+ if (!this.isActive) return;
2264
+ this.isActive = false;
2265
+ process.stdout.off("resize", this.onResize);
2266
+ process.stdout.write("\x1B[?1006l\x1B[?1000l\x1B[?1049l\x1B[?25h");
2267
+ this.hasWrittenStdoutSinceStop = false;
2268
+ if (this.renderTimeout) {
2269
+ clearTimeout(this.renderTimeout);
2270
+ this.renderTimeout = null;
2271
+ }
2272
+ this.renderPending = false;
2273
+ if (this.originalStdinEmit) {
2274
+ process.stdin.emit = this.originalStdinEmit;
2275
+ this.originalStdinEmit = null;
2276
+ }
2277
+ }
2278
+ dispose() {
2279
+ this.stopThinkingInput();
2280
+ this.stop();
2281
+ if (this.thoughtTimer) {
2282
+ clearInterval(this.thoughtTimer);
2283
+ this.thoughtTimer = null;
2284
+ }
2285
+ if (this.ctrlCTimeout) {
2286
+ clearTimeout(this.ctrlCTimeout);
2287
+ this.ctrlCTimeout = null;
2288
+ }
2289
+ if (process.stdin.setRawMode && process.stdin.isTTY) {
2290
+ process.stdin.setRawMode(false);
2291
+ }
2292
+ process.stdout.write = this.originalWrite;
2293
+ }
2294
+ getGitSummary() {
2295
+ const now = Date.now();
2296
+ if (!this.cachedGitSummary) {
2297
+ this.cachedGitSummary = {
2298
+ branch: "no-git",
2299
+ added: 0,
2300
+ modified: 0,
2301
+ deleted: 0
2302
+ };
2303
+ this.refreshGitSummaryAsync().catch(() => {
2304
+ });
2305
+ } else if (now - this.lastGitSummaryReadTime > 8e3) {
2306
+ this.refreshGitSummaryAsync().catch(() => {
2307
+ });
2308
+ }
2309
+ return this.cachedGitSummary;
2310
+ }
2311
+ async refreshGitSummaryAsync() {
2312
+ if (this.isRefreshingGit) return;
2313
+ this.isRefreshingGit = true;
2314
+ this.lastGitSummaryReadTime = Date.now();
2315
+ try {
2316
+ const summary = {
2317
+ branch: "no-git",
2318
+ added: 0,
2319
+ modified: 0,
2320
+ deleted: 0
2321
+ };
2322
+ const branchPromise = new Promise((resolve3) => {
2323
+ exec(
2324
+ "git rev-parse --abbrev-ref HEAD",
2325
+ { cwd: this.cwd },
2326
+ (err, stdout) => {
2327
+ if (err) resolve3("no-git");
2328
+ else resolve3(stdout.trim());
2329
+ }
2330
+ );
2331
+ });
2332
+ const statusPromise = new Promise((resolve3) => {
2333
+ exec("git status --porcelain", { cwd: this.cwd }, (err, stdout) => {
2334
+ if (err) resolve3("");
2335
+ else resolve3(stdout);
2336
+ });
2337
+ });
2338
+ const [branch, statusOutput] = await Promise.all([
2339
+ branchPromise,
2340
+ statusPromise
2341
+ ]);
2342
+ summary.branch = branch;
2343
+ for (const line of statusOutput.split("\n")) {
2344
+ if (!line) continue;
2345
+ const code = line.substring(0, 2);
2346
+ if (code.includes("A") || code.includes("?")) {
2347
+ summary.added++;
2348
+ } else if (code.includes("M") || code.includes("R")) {
2349
+ summary.modified++;
2350
+ } else if (code.includes("D")) {
2351
+ summary.deleted++;
2352
+ }
2353
+ }
2354
+ this.cachedGitSummary = summary;
2355
+ this.render();
2356
+ } catch {
2357
+ } finally {
2358
+ this.isRefreshingGit = false;
2359
+ }
2360
+ }
2361
+ getWheelScrollLines() {
2362
+ const configured = Number(this.config?.tui?.scrollSpeed ?? 50);
2363
+ return Math.max(1, Math.min(20, Math.ceil(configured / 5)));
2364
+ }
2365
+ scrollHistory(delta) {
2366
+ this.historyScrollOffset = Math.max(
2367
+ 0,
2368
+ Math.min(this.maxHistoryScrollOffset, this.historyScrollOffset + delta)
2369
+ );
2370
+ if (this.historyScrollOffset === 0) {
2371
+ this.hasNewOutputWhileScrolled = false;
2372
+ }
2373
+ this.render();
2374
+ }
2375
+ handleScrollInput(str, key) {
2376
+ const wheelDirection = parseMouseWheelDirection(str);
2377
+ if (wheelDirection) {
2378
+ const lines = this.getWheelScrollLines();
2379
+ this.scrollHistory(wheelDirection === "up" ? lines : -lines);
2380
+ return true;
2381
+ }
2382
+ const pageSize = Math.max(3, Math.floor((process.stdout.rows || 24) * 0.6));
2383
+ if (key?.name === "pageup") {
2384
+ this.scrollHistory(pageSize);
2385
+ return true;
2386
+ }
2387
+ if (key?.name === "pagedown") {
2388
+ this.scrollHistory(-pageSize);
2389
+ return true;
2390
+ }
2391
+ if (key?.name === "home" && key?.ctrl) {
2392
+ this.scrollHistory(this.maxHistoryScrollOffset);
2393
+ return true;
2394
+ }
2395
+ if (key?.name === "end" && this.historyScrollOffset > 0) {
2396
+ this.historyScrollOffset = 0;
2397
+ this.hasNewOutputWhileScrolled = false;
2398
+ this.render();
2399
+ return true;
2400
+ }
2401
+ return false;
2402
+ }
2403
+ startThinkingInput() {
2404
+ if (!this.isActive) return;
2405
+ this.stopThinkingInput();
2406
+ if (process.stdin.setRawMode) {
2407
+ process.stdin.setRawMode(true);
2408
+ }
2409
+ process.stdin.resume();
2410
+ this.thinkingKeypressListener = (str, key) => {
2411
+ try {
2412
+ if (!this.isActive) {
2413
+ this.stopThinkingInput();
2414
+ return;
2415
+ }
2416
+ if (this.handleScrollInput(str, key)) {
2417
+ return;
2418
+ }
2419
+ if (key && key.ctrl && key.name === "c") {
2420
+ if (this.inputBuffer.length > 0) {
2421
+ this.inputBuffer = "";
2422
+ this.cursorPosition = 0;
2423
+ this.render();
2424
+ } else {
2425
+ if (this.activeRunnable) {
2426
+ this.activeRunnable.abort();
2427
+ }
2428
+ }
2429
+ return;
2430
+ }
2431
+ if (key && (key.name === "return" || key.name === "enter")) {
2432
+ const submitted = this.inputBuffer;
2433
+ if (submitted.trim()) {
2434
+ this.pendingGuidedStatement = submitted;
2435
+ if (this.activeRunnable) {
2436
+ this.activeRunnable.abort();
2437
+ }
2438
+ }
2439
+ this.inputBuffer = "";
2440
+ this.cursorPosition = 0;
2441
+ this.render();
2442
+ return;
2443
+ }
2444
+ if (key && (key.name === "home" || key.ctrl && key.name === "a")) {
2445
+ this.cursorPosition = 0;
2446
+ this.render();
2447
+ return;
2448
+ }
2449
+ if (key && (key.name === "end" || key.ctrl && key.name === "e")) {
2450
+ this.cursorPosition = this.inputBuffer.length;
2451
+ this.render();
2452
+ return;
2453
+ }
2454
+ if (key && (key.ctrl || key.meta) && key.name === "left") {
2455
+ this.cursorPosition = previousWordIndex(this.inputBuffer, this.cursorPosition);
2456
+ this.render();
2457
+ return;
2458
+ }
2459
+ if (key && (key.ctrl || key.meta) && key.name === "right") {
2460
+ this.cursorPosition = nextWordIndex(this.inputBuffer, this.cursorPosition);
2461
+ this.render();
2462
+ return;
2463
+ }
2464
+ if (key && key.ctrl && (key.name === "backspace" || key.name === "w")) {
2465
+ if (this.cursorPosition > 0) {
2466
+ const targetPos = previousWordIndex(this.inputBuffer, this.cursorPosition);
2467
+ this.inputBuffer = this.inputBuffer.slice(0, targetPos) + this.inputBuffer.slice(this.cursorPosition);
2468
+ this.cursorPosition = targetPos;
2469
+ this.render();
2470
+ }
2471
+ return;
2472
+ }
2473
+ if (key && key.ctrl && key.name === "delete") {
2474
+ if (this.cursorPosition < this.inputBuffer.length) {
2475
+ const targetPos = nextWordIndex(this.inputBuffer, this.cursorPosition);
2476
+ this.inputBuffer = this.inputBuffer.slice(0, this.cursorPosition) + this.inputBuffer.slice(targetPos);
2477
+ this.render();
2478
+ }
2479
+ return;
2480
+ }
2481
+ if (key && key.ctrl && key.name === "u") {
2482
+ this.inputBuffer = "";
2483
+ this.cursorPosition = 0;
2484
+ this.render();
2485
+ return;
2486
+ }
2487
+ if (key && key.ctrl) {
2488
+ return;
2489
+ }
2490
+ if (key && key.name === "backspace") {
2491
+ if (this.cursorPosition > 0) {
2492
+ const previousIndex = previousCodePointIndex(
2493
+ this.inputBuffer,
2494
+ this.cursorPosition
2495
+ );
2496
+ this.inputBuffer = this.inputBuffer.slice(0, previousIndex) + this.inputBuffer.slice(this.cursorPosition);
2497
+ this.cursorPosition = previousIndex;
2498
+ this.render();
2499
+ }
2500
+ return;
2501
+ }
2502
+ if (key && key.name === "delete") {
2503
+ if (this.cursorPosition < this.inputBuffer.length) {
2504
+ const nextIndex = nextCodePointIndex(
2505
+ this.inputBuffer,
2506
+ this.cursorPosition
2507
+ );
2508
+ this.inputBuffer = this.inputBuffer.slice(0, this.cursorPosition) + this.inputBuffer.slice(nextIndex);
2509
+ this.render();
2510
+ }
2511
+ return;
2512
+ }
2513
+ if (key && key.name === "left") {
2514
+ if (this.cursorPosition > 0) {
2515
+ this.cursorPosition = previousCodePointIndex(
2516
+ this.inputBuffer,
2517
+ this.cursorPosition
2518
+ );
2519
+ this.render();
2520
+ }
2521
+ return;
2522
+ }
2523
+ if (key && key.name === "right") {
2524
+ if (this.cursorPosition < this.inputBuffer.length) {
2525
+ this.cursorPosition = nextCodePointIndex(
2526
+ this.inputBuffer,
2527
+ this.cursorPosition
2528
+ );
2529
+ this.render();
2530
+ }
2531
+ return;
2532
+ }
2533
+ if (str && !/[\u0000-\u001f\u007f]/.test(str)) {
2534
+ this.inputBuffer = this.inputBuffer.slice(0, this.cursorPosition) + str + this.inputBuffer.slice(this.cursorPosition);
2535
+ this.cursorPosition += str.length;
2536
+ this.render();
2537
+ }
2538
+ } catch (error) {
2539
+ const logDir = join4(homedir3(), ".orbit");
2540
+ try {
2541
+ if (!existsSync4(logDir)) {
2542
+ mkdirSync(logDir, { recursive: true });
2543
+ }
2544
+ writeFileSync2(
2545
+ join4(logDir, "tui_error.log"),
2546
+ `[${(/* @__PURE__ */ new Date()).toISOString()}] Error in thinkingKeypressListener: ${error instanceof Error ? error.stack : error}
2547
+ `,
2548
+ { flag: "a" }
2549
+ );
2550
+ } catch {
2551
+ }
2552
+ try {
2553
+ this.render();
2554
+ } catch {
2555
+ }
2556
+ }
2557
+ };
2558
+ process.stdin.on("keypress", this.thinkingKeypressListener);
2559
+ }
2560
+ stopThinkingInput() {
2561
+ if (this.thinkingKeypressListener) {
2562
+ process.stdin.removeListener("keypress", this.thinkingKeypressListener);
2563
+ this.thinkingKeypressListener = null;
2564
+ }
2565
+ }
2566
+ getActiveMatches() {
2567
+ if (!this.candidates || !this.inputBuffer.startsWith("/")) return [];
2568
+ if (this.hideAutocomplete) return [];
2569
+ const line = this.inputBuffer;
2570
+ const parts = line.split(/\s+/);
2571
+ if (parts[0] === "/add" && line.includes(" ")) {
2572
+ let query = line.slice(5).trim();
2573
+ let prefix = "/add ";
2574
+ if (query.startsWith("-r ")) {
2575
+ prefix = "/add -r ";
2576
+ query = query.slice(3).trim();
2577
+ } else if (query.startsWith("--read-only ")) {
2578
+ prefix = "/add --read-only ";
2579
+ query = query.slice(12).trim();
2580
+ } else if (query.startsWith("--readonly ")) {
2581
+ prefix = "/add --readonly ";
2582
+ query = query.slice(11).trim();
2583
+ } else if (query === "-r" || query === "--read-only" || query === "--readonly") {
2584
+ query = "";
2585
+ prefix = `/add ${parts[1]} `;
2586
+ }
2587
+ const hits = (this.candidates.files || []).filter((f) => f.toLowerCase().includes(query.toLowerCase())).map((f) => `${prefix}${f}`);
2588
+ if (hits.length > 0) return hits;
2589
+ }
2590
+ if (parts[0] === "/drop" && line.includes(" ")) {
2591
+ const query = line.slice(6).trim();
2592
+ const hits = (this.candidates.files || []).filter((f) => f.toLowerCase().includes(query.toLowerCase())).map((f) => `/drop ${f}`);
2593
+ if (hits.length > 0) return hits;
2594
+ }
2595
+ if (parts[0] === "/model" && line.includes(" ")) {
2596
+ const query = line.slice(7).trim();
2597
+ const defaultProvider = this.config?.provider?.default;
2598
+ const providerConfig = this.config?.providers?.[defaultProvider];
2599
+ const providerType = providerConfig?.type;
2600
+ let models = [];
2601
+ if (providerType === "anthropic" || providerType === "anthropic-compatible") {
2602
+ models = [
2603
+ "claude-3-5-sonnet-latest",
2604
+ "claude-3-5-haiku-latest",
2605
+ "claude-3-opus-latest"
2606
+ ];
2607
+ } else if (providerType === "openai") {
2608
+ models = ["gpt-4o", "gpt-4o-mini", "o1", "o3-mini"];
2609
+ } else if (providerType === "openai-compatible") {
2610
+ if (defaultProvider?.includes("deepseek")) {
2611
+ models = [
2612
+ "deepseek-v4-flash",
2613
+ "deepseek-v4-pro",
2614
+ "deepseek-chat",
2615
+ "deepseek-reasoner"
2616
+ ];
2617
+ } else {
2618
+ models = [
2619
+ "gpt-4o",
2620
+ "gpt-4o-mini",
2621
+ "deepseek-chat",
2622
+ "deepseek-reasoner"
2623
+ ];
2624
+ }
2625
+ } else if (providerType === "ollama") {
2626
+ models = ["qwen2.5-coder:7b", "qwen2.5-coder:1.5b", "llama3"];
2627
+ } else {
2628
+ models = [
2629
+ "deepseek-v4-flash",
2630
+ "deepseek-v4-pro",
2631
+ "gpt-4o",
2632
+ "o3-mini",
2633
+ "claude-3-5-sonnet-latest"
2634
+ ];
2635
+ }
2636
+ const hits = models.filter((m) => m.toLowerCase().includes(query.toLowerCase())).map((m) => `/model ${m}`);
2637
+ if (hits.length > 0) return hits;
2638
+ }
2639
+ if (parts[0] === "/chat" && line.includes(" ")) {
2640
+ if (parts.length <= 2) {
2641
+ const subcommands = ["list", "ls", "new", "delete", "rm", "switch"];
2642
+ const hits = subcommands.map((sub) => `/chat ${sub}`).filter((c) => c.startsWith(line));
2643
+ if (hits.length > 0) return hits;
2644
+ }
2645
+ if (parts.length >= 3 && ["delete", "rm", "switch"].includes(parts[1])) {
2646
+ const cmd = parts[0];
2647
+ const sub = parts[1];
2648
+ const query = parts.slice(2).join(" ");
2649
+ const prefix = `${cmd} ${sub} `;
2650
+ const hits = (this.candidates.sessions || []).filter((s) => {
2651
+ const lowerS = s.toLowerCase();
2652
+ const lowerQ = query.toLowerCase();
2653
+ return lowerS.startsWith(lowerQ) || s.replace(/^sess_/, "").toLowerCase().startsWith(lowerQ);
2654
+ }).map((s) => `${prefix}${s}`);
2655
+ if (hits.length > 0) return hits;
2656
+ }
2657
+ }
2658
+ const cmds = this.candidates && Array.isArray(this.candidates.commands) && this.candidates.commands.length > 0 ? this.candidates.commands : BUILTIN_SLASH_COMMANDS;
2659
+ return cmds.filter((c) => c.startsWith(line));
2660
+ }
2661
+ getSuggestion() {
2662
+ const line = this.inputBuffer;
2663
+ const matches = this.getActiveMatches();
2664
+ if (matches.length > 0) {
2665
+ const idx = Math.min(this.activeCommandIndex, matches.length - 1);
2666
+ const match = matches[idx];
2667
+ if (match && match !== line) {
2668
+ return match.substring(line.length);
2669
+ }
2670
+ }
2671
+ return "";
2672
+ }
2673
+ getHits() {
2674
+ const hits = this.getActiveMatches();
2675
+ return { hits, lastWord: this.inputBuffer };
2676
+ }
2677
+ setCost(cost, inputTokens = 0, cacheReadTokens = 0, outputTokens = 0) {
2678
+ this.sessionCost = cost;
2679
+ this.totalInputTokens = inputTokens;
2680
+ this.totalCacheReadTokens = cacheReadTokens;
2681
+ this.totalOutputTokens = outputTokens;
2682
+ this.render();
2683
+ }
2684
+ handleThinkingDelta(text) {
2685
+ this.currentThinking += text;
2686
+ this.throttleRender();
2687
+ }
2688
+ addLog(text) {
2689
+ if (!text || !text.trim()) return;
2690
+ const trimmed = text.trim();
2691
+ if (trimmed.includes("Summary:") || trimmed.includes("Modified files:") || trimmed.includes("Verification:") || trimmed.includes("Session Cost:")) {
2692
+ return;
2693
+ }
2694
+ if (text.includes("Orbit:")) {
2695
+ const cleanText = text.replace(/Orbit:\s*/i, "").trim();
2696
+ const last = this.history[this.history.length - 1];
2697
+ if (last && last.role === "assistant") {
2698
+ if (!last.text.includes(cleanText)) {
2699
+ last.text = cleanText;
2700
+ }
2701
+ this.render();
2702
+ }
2703
+ return;
2704
+ }
2705
+ if (text.includes("Thought")) {
2706
+ return;
2707
+ }
2708
+ this.history.push({
2709
+ role: "system",
2710
+ text: trimmed
2711
+ });
2712
+ this.render();
2713
+ }
2714
+ syncFromLoop(loop) {
2715
+ this.activeContextFiles = loop.getRelevantFiles() || [];
2716
+ const loopHistory = loop.getHistory();
2717
+ if (loopHistory.length === 0) {
2718
+ this.render();
2719
+ return;
2720
+ }
2721
+ const localAsstIdx = this.history.map((m, i) => m.role === "assistant" ? i : -1).filter((i) => i !== -1);
2722
+ const loopAsst = loopHistory.filter((m) => m.role === "assistant");
2723
+ for (let i = 0; i < loopAsst.length; i++) {
2724
+ const loopMsg = loopAsst[i];
2725
+ const textBlock = loopMsg.content.find((b) => b.type === "text");
2726
+ if (textBlock && textBlock.text) {
2727
+ const localIdx = localAsstIdx[i];
2728
+ if (localIdx !== void 0) {
2729
+ this.history[localIdx].text = textBlock.text;
2730
+ } else {
2731
+ this.history.push({
2732
+ role: "assistant",
2733
+ text: textBlock.text,
2734
+ attempt: i + 1
2735
+ });
2736
+ }
2737
+ }
2738
+ }
2739
+ this.render();
2740
+ }
2741
+ loadHistory(loopHistory) {
2742
+ this.history = [];
2743
+ this.historyScrollOffset = 0;
2744
+ this.hasNewOutputWhileScrolled = false;
2745
+ let attempt = 0;
2746
+ for (const msg of loopHistory) {
2747
+ if (msg.role === "user") {
2748
+ const text = msg.content.map((c) => c.type === "text" ? c.text : "").join("");
2749
+ if (text === "REPL Interactive Shell Started") {
2750
+ continue;
2751
+ }
2752
+ this.history.push({
2753
+ role: "user",
2754
+ text
2755
+ });
2756
+ } else if (msg.role === "assistant") {
2757
+ attempt++;
2758
+ const textBlock = msg.content.find((b) => b.type === "text");
2759
+ this.history.push({
2760
+ role: "assistant",
2761
+ text: textBlock?.text || "",
2762
+ attempt
2763
+ });
2764
+ } else if (msg.role === "system") {
2765
+ const text = msg.content.map((c) => c.type === "text" ? c.text : "").join("");
2766
+ this.history.push({
2767
+ role: "system",
2768
+ text
2769
+ });
2770
+ }
2771
+ }
2772
+ this.render();
2773
+ }
2774
+ async askInput() {
2775
+ if (!this.isActive) {
2776
+ if (this.hasWrittenStdoutSinceStop) {
2777
+ const wasRaw = !!process.stdin.isRaw;
2778
+ if (process.stdin.setRawMode) {
2779
+ process.stdin.setRawMode(false);
2780
+ }
2781
+ await Prompt2.askText("Press Enter to return to Orbit...");
2782
+ if (process.stdin.setRawMode) {
2783
+ process.stdin.setRawMode(wasRaw);
2784
+ }
2785
+ this.hasWrittenStdoutSinceStop = false;
2786
+ }
2787
+ this.start(this.budgetLimit);
2788
+ }
2789
+ process.stdout.write("\x1B[?25h");
2790
+ return new Promise((resolve3) => {
2791
+ this.resolveInput = resolve3;
2792
+ this.inputBuffer = "";
2793
+ this.cursorPosition = 0;
2794
+ this.hideAutocomplete = false;
2795
+ this.render();
2796
+ const wasRaw = !!process.stdin.isRaw;
2797
+ if (process.stdin.setRawMode) {
2798
+ process.stdin.setRawMode(true);
2799
+ }
2800
+ process.stdin.resume();
2801
+ const onKeypress = (str, key) => {
2802
+ try {
2803
+ if (!this.isActive) {
2804
+ cleanup();
2805
+ return;
2806
+ }
2807
+ if (this.handleScrollInput(str, key)) {
2808
+ return;
2809
+ }
2810
+ if (key && key.ctrl && key.name === "c") {
2811
+ this.activeCommandIndex = 0;
2812
+ if (this.inputBuffer.length > 0) {
2813
+ this.inputBuffer = "";
2814
+ this.cursorPosition = 0;
2815
+ this.render();
2816
+ } else {
2817
+ if (this.ctrlCPressedOnce) {
2818
+ if (this.ctrlCTimeout) clearTimeout(this.ctrlCTimeout);
2819
+ cleanup();
2820
+ this.stop();
2821
+ process.exit(0);
2822
+ } else {
2823
+ this.ctrlCPressedOnce = true;
2824
+ if (this.ctrlCTimeout) clearTimeout(this.ctrlCTimeout);
2825
+ this.ctrlCTimeout = setTimeout(() => {
2826
+ this.ctrlCPressedOnce = false;
2827
+ this.render();
2828
+ }, 2e3);
2829
+ this.render();
2830
+ }
2831
+ }
2832
+ return;
2833
+ }
2834
+ if (key && (key.name === "return" || key.name === "enter")) {
2835
+ cleanup();
2836
+ process.stdout.write("\x1B[?25l");
2837
+ let submitted = this.inputBuffer;
2838
+ if (this.inputBuffer.startsWith("/")) {
2839
+ const matches = this.getActiveMatches();
2840
+ if (matches.length > 0) {
2841
+ const idx = Math.min(
2842
+ this.activeCommandIndex,
2843
+ matches.length - 1
2844
+ );
2845
+ const match = matches[idx];
2846
+ if (match) {
2847
+ submitted = match;
2848
+ }
2849
+ }
2850
+ }
2851
+ this.resolveInput = null;
2852
+ this.historyScrollOffset = 0;
2853
+ this.hasNewOutputWhileScrolled = false;
2854
+ if (submitted.trim()) {
2855
+ this.history.push({ role: "user", text: submitted });
2856
+ if (this.inputHistory[this.inputHistory.length - 1] !== submitted) {
2857
+ this.inputHistory.push(submitted);
2858
+ this.saveInputHistory();
2859
+ }
2860
+ }
2861
+ this.historyIndex = -1;
2862
+ this.inputBuffer = "";
2863
+ this.cursorPosition = 0;
2864
+ this.render();
2865
+ resolve3(submitted);
2866
+ return;
2867
+ }
2868
+ if (key && (key.name === "home" || key.ctrl && key.name === "a")) {
2869
+ this.activeCommandIndex = 0;
2870
+ this.cursorPosition = 0;
2871
+ this.render();
2872
+ return;
2873
+ }
2874
+ if (key && (key.name === "end" || key.ctrl && key.name === "e")) {
2875
+ this.activeCommandIndex = 0;
2876
+ this.cursorPosition = this.inputBuffer.length;
2877
+ this.render();
2878
+ return;
2879
+ }
2880
+ if (key && (key.ctrl || key.meta) && key.name === "left") {
2881
+ this.activeCommandIndex = 0;
2882
+ this.cursorPosition = previousWordIndex(
2883
+ this.inputBuffer,
2884
+ this.cursorPosition
2885
+ );
2886
+ this.render();
2887
+ return;
2888
+ }
2889
+ if (key && (key.ctrl || key.meta) && key.name === "right") {
2890
+ this.activeCommandIndex = 0;
2891
+ this.cursorPosition = nextWordIndex(
2892
+ this.inputBuffer,
2893
+ this.cursorPosition
2894
+ );
2895
+ this.render();
2896
+ return;
2897
+ }
2898
+ if (key && key.ctrl && (key.name === "backspace" || key.name === "w")) {
2899
+ this.activeCommandIndex = 0;
2900
+ this.hideAutocomplete = false;
2901
+ if (this.cursorPosition > 0) {
2902
+ const targetPos = previousWordIndex(
2903
+ this.inputBuffer,
2904
+ this.cursorPosition
2905
+ );
2906
+ this.inputBuffer = this.inputBuffer.slice(0, targetPos) + this.inputBuffer.slice(this.cursorPosition);
2907
+ this.cursorPosition = targetPos;
2908
+ this.render();
2909
+ }
2910
+ return;
2911
+ }
2912
+ if (key && key.ctrl && key.name === "delete") {
2913
+ this.activeCommandIndex = 0;
2914
+ this.hideAutocomplete = false;
2915
+ if (this.cursorPosition < this.inputBuffer.length) {
2916
+ const targetPos = nextWordIndex(
2917
+ this.inputBuffer,
2918
+ this.cursorPosition
2919
+ );
2920
+ this.inputBuffer = this.inputBuffer.slice(0, this.cursorPosition) + this.inputBuffer.slice(targetPos);
2921
+ this.render();
2922
+ }
2923
+ return;
2924
+ }
2925
+ if (key && key.ctrl && key.name === "u") {
2926
+ this.activeCommandIndex = 0;
2927
+ this.inputBuffer = "";
2928
+ this.cursorPosition = 0;
2929
+ this.render();
2930
+ return;
2931
+ }
2932
+ if (key && key.name === "up") {
2933
+ if (this.inputBuffer.startsWith("/")) {
2934
+ const matches = this.getActiveMatches();
2935
+ if (matches.length > 0) {
2936
+ this.activeCommandIndex = (this.activeCommandIndex - 1 + matches.length) % matches.length;
2937
+ this.render();
2938
+ return;
2939
+ }
2940
+ }
2941
+ if (this.inputHistory.length > 0) {
2942
+ if (this.historyIndex === -1) {
2943
+ this.tempBuffer = this.inputBuffer;
2944
+ this.historyIndex = this.inputHistory.length - 1;
2945
+ } else if (this.historyIndex > 0) {
2946
+ this.historyIndex--;
2947
+ }
2948
+ this.inputBuffer = this.inputHistory[this.historyIndex];
2949
+ this.cursorPosition = this.inputBuffer.length;
2950
+ this.render();
2951
+ }
2952
+ return;
2953
+ }
2954
+ if (key && key.name === "down") {
2955
+ if (this.inputBuffer.startsWith("/")) {
2956
+ const matches = this.getActiveMatches();
2957
+ if (matches.length > 0) {
2958
+ this.activeCommandIndex = (this.activeCommandIndex + 1) % matches.length;
2959
+ this.render();
2960
+ return;
2961
+ }
2962
+ }
2963
+ if (this.historyIndex !== -1) {
2964
+ if (this.historyIndex < this.inputHistory.length - 1) {
2965
+ this.historyIndex++;
2966
+ this.inputBuffer = this.inputHistory[this.historyIndex];
2967
+ } else {
2968
+ this.historyIndex = -1;
2969
+ this.inputBuffer = this.tempBuffer || "";
2970
+ }
2971
+ this.cursorPosition = this.inputBuffer.length;
2972
+ this.render();
2973
+ }
2974
+ return;
2975
+ }
2976
+ if (key && key.name === "left") {
2977
+ if (this.cursorPosition > 0) {
2978
+ this.cursorPosition = previousCodePointIndex(
2979
+ this.inputBuffer,
2980
+ this.cursorPosition
2981
+ );
2982
+ this.render();
2983
+ }
2984
+ return;
2985
+ }
2986
+ if (key && key.name === "right") {
2987
+ if (this.cursorPosition < this.inputBuffer.length) {
2988
+ this.cursorPosition = nextCodePointIndex(
2989
+ this.inputBuffer,
2990
+ this.cursorPosition
2991
+ );
2992
+ this.render();
2993
+ } else {
2994
+ const sug = this.getSuggestion();
2995
+ if (sug) {
2996
+ this.inputBuffer += sug;
2997
+ this.cursorPosition = this.inputBuffer.length;
2998
+ this.render();
2999
+ }
3000
+ }
3001
+ return;
3002
+ }
3003
+ if (key && key.name === "tab") {
3004
+ if (this.inputBuffer.startsWith("/")) {
3005
+ const matches = this.getActiveMatches();
3006
+ if (matches.length > 0) {
3007
+ const idx = Math.min(
3008
+ this.activeCommandIndex,
3009
+ matches.length - 1
3010
+ );
3011
+ const match = matches[idx];
3012
+ if (match) {
3013
+ this.inputBuffer = match;
3014
+ this.cursorPosition = match.length;
3015
+ this.activeCommandIndex = 0;
3016
+ this.render();
3017
+ }
3018
+ return;
3019
+ }
3020
+ }
3021
+ const sug = this.getSuggestion();
3022
+ if (sug) {
3023
+ this.inputBuffer += sug;
3024
+ this.cursorPosition = this.inputBuffer.length;
3025
+ this.render();
3026
+ }
3027
+ return;
3028
+ }
3029
+ if (key && key.ctrl && key.name === "l") {
3030
+ this.history = [];
3031
+ this.render();
3032
+ return;
3033
+ }
3034
+ if (key && key.ctrl && key.name === "p") {
3035
+ this.activeCommandIndex = 0;
3036
+ if (!this.inputBuffer.startsWith("/")) {
3037
+ this.inputBuffer = "/" + this.inputBuffer;
3038
+ this.cursorPosition = this.inputBuffer.length;
3039
+ }
3040
+ this.render();
3041
+ return;
3042
+ }
3043
+ if (key && key.name === "delete") {
3044
+ this.activeCommandIndex = 0;
3045
+ this.hideAutocomplete = false;
3046
+ if (this.cursorPosition < this.inputBuffer.length) {
3047
+ const nextIndex = nextCodePointIndex(
3048
+ this.inputBuffer,
3049
+ this.cursorPosition
3050
+ );
3051
+ this.inputBuffer = this.inputBuffer.substring(0, this.cursorPosition) + this.inputBuffer.substring(nextIndex);
3052
+ this.render();
3053
+ }
3054
+ return;
3055
+ }
3056
+ if (key && key.name === "backspace") {
3057
+ this.activeCommandIndex = 0;
3058
+ this.hideAutocomplete = false;
3059
+ if (this.cursorPosition > 0) {
3060
+ const previousIndex = previousCodePointIndex(
3061
+ this.inputBuffer,
3062
+ this.cursorPosition
3063
+ );
3064
+ this.inputBuffer = this.inputBuffer.substring(0, previousIndex) + this.inputBuffer.substring(this.cursorPosition);
3065
+ this.cursorPosition = previousIndex;
3066
+ }
3067
+ } else if (key && key.name === "escape") {
3068
+ this.activeCommandIndex = 0;
3069
+ this.hideAutocomplete = true;
3070
+ } else if (str && !/[\u0000-\u001f\u007f]/.test(str) && (!key || !key.ctrl && !key.meta && key.name !== "tab")) {
3071
+ this.activeCommandIndex = 0;
3072
+ this.hideAutocomplete = false;
3073
+ this.inputBuffer = this.inputBuffer.substring(0, this.cursorPosition) + str + this.inputBuffer.substring(this.cursorPosition);
3074
+ this.cursorPosition += str.length;
3075
+ }
3076
+ this.render();
3077
+ } catch (error) {
3078
+ const logDir = join4(homedir3(), ".orbit");
3079
+ try {
3080
+ if (!existsSync4(logDir)) {
3081
+ mkdirSync(logDir, { recursive: true });
3082
+ }
3083
+ writeFileSync2(
3084
+ join4(logDir, "tui_error.log"),
3085
+ `[${(/* @__PURE__ */ new Date()).toISOString()}] Error in onKeypress: ${error instanceof Error ? error.stack : error}
3086
+ `,
3087
+ { flag: "a" }
3088
+ );
3089
+ } catch {
3090
+ }
3091
+ try {
3092
+ this.render();
3093
+ } catch {
3094
+ }
3095
+ }
3096
+ };
3097
+ const cleanup = () => {
3098
+ process.stdin.removeListener("keypress", onKeypress);
3099
+ if (process.stdin.setRawMode) {
3100
+ process.stdin.setRawMode(wasRaw);
3101
+ }
3102
+ process.stdin.pause();
3103
+ };
3104
+ process.stdin.on("keypress", onKeypress);
3105
+ });
3106
+ }
3107
+ startAttempt(attempt) {
3108
+ this.currentAttempt = attempt;
3109
+ this.attemptStartTime = Date.now();
3110
+ this.firstDeltaTime = 0;
3111
+ this.isThinking = true;
3112
+ this.thoughtElapsed = 0;
3113
+ this.currentThinking = "";
3114
+ this.history.push({
3115
+ role: "assistant",
3116
+ text: "",
3117
+ attempt
3118
+ });
3119
+ if (this.thoughtTimer) clearInterval(this.thoughtTimer);
3120
+ this.thoughtTimer = setInterval(() => {
3121
+ if (this.isThinking) {
3122
+ this.thoughtElapsed += 100;
3123
+ this.render();
3124
+ }
3125
+ }, 100);
3126
+ this.render();
3127
+ }
3128
+ handleModelDelta(text) {
3129
+ const lastAsst = [...this.history].reverse().find((m) => m.role === "assistant");
3130
+ if (lastAsst) {
3131
+ if (this.isThinking && text.trim().length > 0) {
3132
+ this.isThinking = false;
3133
+ if (this.thoughtTimer) {
3134
+ clearInterval(this.thoughtTimer);
3135
+ this.thoughtTimer = null;
3136
+ }
3137
+ lastAsst.thoughtTime = Date.now() - this.attemptStartTime;
3138
+ }
3139
+ lastAsst.text += text;
3140
+ this.throttleRender();
3141
+ }
3142
+ }
3143
+ throttleRender() {
3144
+ const now = Date.now();
3145
+ const minInterval = 60;
3146
+ if (now - this.lastRenderTime >= minInterval) {
3147
+ if (this.renderTimeout) {
3148
+ clearTimeout(this.renderTimeout);
3149
+ this.renderTimeout = null;
3150
+ }
3151
+ this.lastRenderTime = now;
3152
+ this.render();
3153
+ } else if (!this.renderPending) {
3154
+ this.renderPending = true;
3155
+ this.renderTimeout = setTimeout(
3156
+ () => {
3157
+ this.renderPending = false;
3158
+ this.lastRenderTime = Date.now();
3159
+ this.render();
3160
+ },
3161
+ minInterval - (now - this.lastRenderTime)
3162
+ );
3163
+ }
3164
+ }
3165
+ finishAttempt() {
3166
+ const lastAsst = [...this.history].reverse().find((m) => m.role === "assistant");
3167
+ if (lastAsst) {
3168
+ this.isThinking = false;
3169
+ if (this.thoughtTimer) {
3170
+ clearInterval(this.thoughtTimer);
3171
+ this.thoughtTimer = null;
3172
+ }
3173
+ lastAsst.totalTime = Date.now() - this.attemptStartTime;
3174
+ if (lastAsst.thoughtTime === void 0) {
3175
+ lastAsst.thoughtTime = lastAsst.totalTime;
3176
+ }
3177
+ this.render();
3178
+ }
3179
+ }
3180
+ render(forceFull = false) {
3181
+ const columns = Math.max(40, process.stdout.columns || 80);
3182
+ const rows = Math.max(10, process.stdout.rows || 24);
3183
+ const morandi = {
3184
+ user: (s) => `\x1B[38;2;142;163;175m${s}\x1B[0m`,
3185
+ userBold: (s) => `\x1B[1;38;2;142;163;175m${s}\x1B[0m`,
3186
+ asst: (s) => `\x1B[38;2;143;153;129m${s}\x1B[0m`,
3187
+ asstBold: (s) => `\x1B[1;38;2;143;153;129m${s}\x1B[0m`,
3188
+ cyan: (s) => `\x1B[38;2;142;163;175m${s}\x1B[0m`,
3189
+ accent: (s) => `\x1B[38;2;200;170;120m${s}\x1B[0m`,
3190
+ completed: (s) => `\x1B[38;2;135;165;130m${s}\x1B[0m`,
3191
+ failed: (s) => `\x1B[38;2;180;120;120m${s}\x1B[0m`,
3192
+ warn: (s) => `\x1B[38;2;180;140;130m${s}\x1B[0m`,
3193
+ white: (s) => `\x1B[38;2;230;225;215m${s}\x1B[0m`,
3194
+ whiteBold: (s) => `\x1B[1;38;2;230;225;215m${s}\x1B[0m`,
3195
+ gray: (s) => `\x1B[38;2;150;150;150m${s}\x1B[0m`,
3196
+ dim: (s) => `\x1B[2;38;2;110;110;110m${s}\x1B[0m`
3197
+ };
3198
+ const isWaitingInput = this.resolveInput !== null;
3199
+ const isInputActive = isWaitingInput || this.thinkingKeypressListener !== null;
3200
+ const hasInput = isInputActive && this.inputBuffer.length > 0;
3201
+ const placeholder = isWaitingInput ? "Ask anything..." : "";
3202
+ const boxWidth = columns - 4;
3203
+ const wrapWidth = Math.max(8, boxWidth - 14);
3204
+ const fullText = hasInput ? this.inputBuffer : placeholder;
3205
+ const wrappedLines = this.wrapText(fullText, wrapWidth);
3206
+ const formattedLines = hasInput ? this.formatWrappedLines(wrappedLines, this.inputBuffer.length) : wrappedLines.map((line) => morandi.dim(line));
3207
+ const boxContentLines = [];
3208
+ const topBorder = morandi.gray(" \u256D" + "\u2500".repeat(boxWidth - 4) + "\u256E");
3209
+ const bottomBorder = morandi.gray(" \u2570" + "\u2500".repeat(boxWidth - 4) + "\u256F");
3210
+ boxContentLines.push(topBorder);
3211
+ for (let i = 0; i < formattedLines.length; i++) {
3212
+ const prefix = i === 0 ? "orbit > " : " ";
3213
+ const rawLine = wrappedLines[i];
3214
+ const visualWidth = this.getStringWidth(rawLine);
3215
+ const remainingSpaces = wrapWidth - visualWidth;
3216
+ const padding = " ".repeat(Math.max(0, remainingSpaces));
3217
+ const lineContent = morandi.gray(" \u2502 ") + morandi.userBold(prefix) + formattedLines[i] + padding + morandi.gray(" \u2502");
3218
+ boxContentLines.push(lineContent);
3219
+ }
3220
+ boxContentLines.push(bottomBorder);
3221
+ const bottomLines = [];
3222
+ if (isWaitingInput) {
3223
+ const matches = this.getActiveMatches();
3224
+ if (matches.length > 0) {
3225
+ const isZh = this.config?.language === "zh";
3226
+ const cmdHints = isZh ? {
3227
+ "/help": "\u67E5\u770B\u7CFB\u7EDF\u547D\u4EE4\u7684\u8BE6\u7EC6\u5E2E\u52A9\u4E0E\u6307\u5357",
3228
+ "/status": "\u5B9E\u65F6\u8BCA\u65AD\u5F53\u524D\u4F1A\u8BDD\u7684\u5065\u5EB7\u4E0E\u8D44\u6E90\u72B6\u6001",
3229
+ "/config": "\u67E5\u770B\u4E0E\u4FEE\u6539\u672C\u5730/\u5168\u5C40\u7684\u8FD0\u884C\u914D\u7F6E\u53C2\u6570",
3230
+ "/model": "\u52A8\u6001\u5207\u6362\u6B63\u5728\u4F7F\u7528\u7684 AI \u8BED\u8A00\u5927\u6A21\u578B",
3231
+ "/chat": "\u4F1A\u8BDD\u7BA1\u7406\u5668 (\u652F\u6301\u5B50\u547D\u4EE4: list, new, delete, switch)",
3232
+ "/chat list": "\u5C55\u793A\u6240\u6709\u5DF2\u4FDD\u5B58\u7684\u5386\u53F2\u5BF9\u8BDD\u4F1A\u8BDD",
3233
+ "/chat ls": "\u5C55\u793A\u6240\u6709\u5DF2\u4FDD\u5B58\u7684\u5386\u53F2\u5BF9\u8BDD\u4F1A\u8BDD",
3234
+ "/chat new": "\u542F\u52A8\u5E76\u521B\u5EFA\u4E00\u4E2A\u5168\u65B0\u7684\u5BF9\u8BDD\u4F1A\u8BDD",
3235
+ "/chat delete": "\u79FB\u9664\u4E0D\u9700\u8981\u7684\u5386\u53F2\u5BF9\u8BDD\u4F1A\u8BDD",
3236
+ "/chat rm": "\u79FB\u9664\u4E0D\u9700\u8981\u7684\u5386\u53F2\u5BF9\u8BDD\u4F1A\u8BDD",
3237
+ "/chat switch": "\u5FEB\u901F\u5207\u6362\u5230\u6307\u5B9A\u7684\u5386\u53F2\u5BF9\u8BDD\u4F1A\u8BDD",
3238
+ "/commit": "\u81EA\u52A8\u6682\u5B58\u5DE5\u4F5C\u533A\u4FEE\u6539\u5E76\u751F\u6210 Git \u63D0\u4EA4",
3239
+ "/exit": "\u5B89\u5168\u7EC8\u6B62\u5E76\u5173\u95ED\u5F53\u524D\u7684\u7EC8\u7AEF\u4F1A\u8BDD",
3240
+ "/quit": "\u5B89\u5168\u7EC8\u6B62\u5E76\u5173\u95ED\u5F53\u524D\u7684\u7EC8\u7AEF\u4F1A\u8BDD",
3241
+ "/rollback": "\u4E00\u952E\u64A4\u9500\u5E76\u56DE\u6EDA\u81EA\u4F1A\u8BDD\u542F\u52A8\u4EE5\u6765\u7684\u6240\u6709\u4FEE\u6539",
3242
+ "/clear": "\u6E05\u7A7A\u5F53\u524D\u7EC8\u7AEF\u5C4F\u5E55\u7684\u6240\u6709\u5386\u53F2\u4F1A\u8BDD\u6E32\u67D3",
3243
+ "/add": "\u5C06\u9009\u5B9A\u7684\u6587\u4EF6\u6216\u4EE3\u7801\u8D44\u4EA7\u6DFB\u52A0\u5230\u5F53\u524D\u4E0A\u4E0B\u6587",
3244
+ "/drop": "\u4ECE\u5F53\u524D\u5BF9\u8BDD\u4E0A\u4E0B\u6587\u4E2D\u79FB\u9664\u9009\u5B9A\u7684\u8D44\u4EA7",
3245
+ "/mode": "\u52A8\u6001\u5207\u6362\u7CFB\u7EDF\u5B89\u5168\u786E\u8BA4\u6A21\u5F0F (strict, normal, auto, plan)",
3246
+ "/copy": "\u62F7\u8D1D AI \u7684\u4E0A\u4E00\u6761\u56DE\u590D\u5230\u7CFB\u7EDF\u526A\u8D34\u677F"
3247
+ } : {
3248
+ "/help": "Display detailed help and commands reference",
3249
+ "/status": "Diagnose session health, token usage, and limits",
3250
+ "/config": "View and edit local or global configuration",
3251
+ "/model": "Switch the active language model dynamically",
3252
+ "/chat": "Manage chat sessions (subcommands: list, new, delete, switch)",
3253
+ "/chat list": "List all saved agent chat sessions",
3254
+ "/chat ls": "List all saved agent chat sessions",
3255
+ "/chat new": "Initialize and start a fresh chat session",
3256
+ "/chat delete": "Remove a saved session from the manager",
3257
+ "/chat rm": "Remove a saved session from the manager",
3258
+ "/chat switch": "Switch focus to a specific saved session",
3259
+ "/commit": "Automatically stage changes and create Git commit",
3260
+ "/exit": "Safely terminate and exit the active session",
3261
+ "/quit": "Safely terminate and exit the active session",
3262
+ "/rollback": "Revert all source edits made during this session",
3263
+ "/clear": "Clear the terminal screen and scrollback buffer",
3264
+ "/add": "Add files or code symbols to prompt context",
3265
+ "/drop": "Remove selected assets from prompt context",
3266
+ "/mode": "Switch permission mode (strict, normal, auto, plan)",
3267
+ "/copy": "Copy last assistant response to clipboard"
3268
+ };
3269
+ const maxVisible = 5;
3270
+ this.activeCommandIndex = Math.min(
3271
+ Math.max(0, this.activeCommandIndex),
3272
+ matches.length - 1
3273
+ );
3274
+ let startIdx = 0;
3275
+ if (this.activeCommandIndex >= maxVisible) {
3276
+ startIdx = this.activeCommandIndex - maxVisible + 1;
3277
+ }
3278
+ const visibleMatches = matches.slice(startIdx, startIdx + maxVisible);
3279
+ const maxPopupWidth = Math.min(86, Math.max(30, columns - 8));
3280
+ const formattedMatches = visibleMatches.map((cmd) => {
3281
+ const isSelected = visibleMatches.indexOf(cmd) + startIdx === this.activeCommandIndex;
3282
+ const prefix = isSelected ? " \u276F " : " ";
3283
+ let hint = cmdHints[cmd] || "";
3284
+ if (!hint) {
3285
+ if (cmd.startsWith("/chat delete ") || cmd.startsWith("/chat rm ")) {
3286
+ hint = isZh ? "\u5220\u9664\u8BE5\u4F1A\u8BDD" : "Delete this session";
3287
+ } else if (cmd.startsWith("/chat switch ")) {
3288
+ hint = isZh ? "\u5207\u6362\u5230\u8BE5\u4F1A\u8BDD" : "Switch to this session";
3289
+ } else if (cmd.startsWith("/fork switch ")) {
3290
+ hint = isZh ? "\u5207\u6362\u5230\u6307\u5B9A\u7684\u4F1A\u8BDD\u5206\u652F" : "Switch to specified session branch";
3291
+ } else if (cmd === "/fork tree") {
3292
+ hint = isZh ? "\u5C55\u793A\u6240\u6709\u4F1A\u8BDD\u5206\u652F\u7684\u6811\u72B6\u5173\u7CFB" : "Display session branch lineage tree";
3293
+ }
3294
+ }
3295
+ const maxLeftW = Math.max(15, Math.floor(maxPopupWidth * 0.6));
3296
+ let leftPart = `${prefix}${cmd}`;
3297
+ let leftW = this.getStringWidth(leftPart);
3298
+ if (leftW > maxLeftW) {
3299
+ leftPart = this.truncateToWidth(leftPart, maxLeftW - 3) + "...";
3300
+ leftW = this.getStringWidth(leftPart);
3301
+ }
3302
+ let rightPart = "";
3303
+ let rightW = 0;
3304
+ if (hint) {
3305
+ const availableRightW = maxPopupWidth - leftW - 2 - 4;
3306
+ if (availableRightW >= 5) {
3307
+ const rawRightW = this.getStringWidth(hint);
3308
+ if (rawRightW <= availableRightW) {
3309
+ rightPart = hint;
3310
+ rightW = rawRightW;
3311
+ } else {
3312
+ rightPart = this.truncateToWidth(hint, availableRightW - 3) + "...";
3313
+ rightW = this.getStringWidth(rightPart);
3314
+ }
3315
+ }
3316
+ }
3317
+ return { cmd, isSelected, leftPart, leftW, rightPart, rightW };
3318
+ });
3319
+ const popupWidth = maxPopupWidth;
3320
+ bottomLines.push(morandi.gray(" \u256D" + "\u2500".repeat(popupWidth) + "\u256E"));
3321
+ for (const fm of formattedMatches) {
3322
+ const spacingWidth = popupWidth - fm.leftW - fm.rightW - 4;
3323
+ const spacing2 = " ".repeat(Math.max(1, spacingWidth));
3324
+ const rightPadding = " ";
3325
+ const formattedLine = fm.isSelected ? morandi.accent(fm.leftPart + spacing2) + morandi.dim(fm.rightPart) + rightPadding : morandi.gray(fm.leftPart + spacing2) + morandi.dim(fm.rightPart) + rightPadding;
3326
+ bottomLines.push(
3327
+ morandi.gray(" \u2502") + formattedLine + morandi.gray("\u2502")
3328
+ );
3329
+ }
3330
+ bottomLines.push(morandi.gray(" \u2570" + "\u2500".repeat(popupWidth) + "\u256F"));
3331
+ }
3332
+ }
3333
+ bottomLines.push(...boxContentLines);
3334
+ const mode = this.permissionsMode.toUpperCase();
3335
+ let statusText = "";
3336
+ if (this.historyScrollOffset > 0) {
3337
+ const newOutput = this.hasNewOutputWhileScrolled ? this.config?.language === "zh" ? " \xB7 \u6709\u65B0\u8F93\u51FA" : " \xB7 new output" : "";
3338
+ statusText = morandi.accent(
3339
+ this.config?.language === "zh" ? `\u2191 \u5386\u53F2 ${this.historyScrollOffset} \u884C` : `\u2191 history ${this.historyScrollOffset} lines`
3340
+ ) + morandi.warn(newOutput);
3341
+ } else if (this.ctrlCPressedOnce) {
3342
+ statusText = morandi.warn("Press Ctrl+C again to exit");
3343
+ } else {
3344
+ const cleanModel2 = this.modelNameGetter().split("/").pop() || this.modelNameGetter();
3345
+ const costStr = `$` + this.sessionCost.toFixed(4);
3346
+ statusText = morandi.completed("\u25CF") + " " + morandi.white(`${mode} MODE`) + morandi.gray(" \xB7 ") + morandi.accent(cleanModel2) + morandi.gray(" \xB7 ") + morandi.accent(costStr) + morandi.gray(" \xB7 ") + morandi.dim(`attempt: ${this.currentAttempt || 1}`);
3347
+ }
3348
+ let keybindings = this.historyScrollOffset > 0 ? morandi.gray("[End]") + morandi.dim(this.config?.language === "zh" ? " \u8FD4\u56DE\u5E95\u90E8" : " Bottom") : columns >= 88 ? [
3349
+ morandi.gray("[^C]") + morandi.dim(" Cancel"),
3350
+ morandi.gray("[^L]") + morandi.dim(" Clear"),
3351
+ morandi.gray("[^P]") + morandi.dim(" Cmds")
3352
+ ].join(" ") : columns >= 62 ? [
3353
+ morandi.gray("[^C]") + morandi.dim(" Cancel"),
3354
+ morandi.gray("[^P]") + morandi.dim(" Cmds")
3355
+ ].join(" ") : morandi.gray("[^C]") + morandi.dim(" Exit");
3356
+ let statusTextLength = this.getStringWidth(statusText);
3357
+ let keybindingsLength = this.getStringWidth(keybindings);
3358
+ if (statusTextLength + keybindingsLength > columns - 8) {
3359
+ const compactMode = `${mode.slice(0, 6)} \xB7 ${this.currentAttempt || 1}`;
3360
+ statusText = morandi.completed("\u25CF") + " " + morandi.white(compactMode);
3361
+ statusTextLength = this.getStringWidth(statusText);
3362
+ }
3363
+ if (statusTextLength + keybindingsLength > columns - 8) {
3364
+ keybindings = morandi.gray("[^C]");
3365
+ keybindingsLength = this.getStringWidth(keybindings);
3366
+ }
3367
+ const spacing = Math.max(
3368
+ 1,
3369
+ columns - 6 - statusTextLength - keybindingsLength
3370
+ );
3371
+ bottomLines.push(" " + statusText + " ".repeat(spacing) + keybindings);
3372
+ const bottomHeight = bottomLines.length;
3373
+ const cleanModel = this.modelNameGetter().replace(/\[1m\]/g, "");
3374
+ const gitSummary = this.getGitSummary();
3375
+ const gitBranch = gitSummary.branch;
3376
+ const logoLines = [
3377
+ `\x1B[38;2;142;163;175m /\\___/\\ \x1B[0m`,
3378
+ `\x1B[38;2;142;163;175m ( o.o ) \x1B[0m`,
3379
+ `\x1B[38;2;142;163;175m / >\x1B[38;2;230;110;110m\u2665\x1B[38;2;142;163;175m< \\ \x1B[0m`,
3380
+ `\x1B[38;2;142;163;175m (__/ \\__) \x1B[0m`
3381
+ ];
3382
+ const w0 = this.getStringWidth(logoLines[0]);
3383
+ const w1 = this.getStringWidth(logoLines[1]);
3384
+ const w2 = this.getStringWidth(logoLines[2]);
3385
+ const w3 = this.getStringWidth(logoLines[3]);
3386
+ const maxLogoW = Math.max(w0, w1, w2, w3);
3387
+ const pad0 = " ".repeat(maxLogoW - w0);
3388
+ const pad1 = " ".repeat(maxLogoW - w1);
3389
+ const pad2 = " ".repeat(maxLogoW - w2);
3390
+ const pad3 = " ".repeat(maxLogoW - w3);
3391
+ const shortCwd = this.cwd.replace(/\\/g, "/");
3392
+ const availableWidth = Math.max(10, columns - 2 - maxLogoW - 2 - 20 - 2);
3393
+ let branchText = "";
3394
+ if (gitBranch !== "no-git") {
3395
+ const stats = [];
3396
+ if (gitSummary.added > 0) stats.push(`+${gitSummary.added}`);
3397
+ if (gitSummary.modified > 0) stats.push(`~${gitSummary.modified}`);
3398
+ if (gitSummary.deleted > 0) stats.push(`-${gitSummary.deleted}`);
3399
+ const gitStatusStats = stats.length > 0 ? ` (${stats.join(" ")})` : "";
3400
+ const maxBranchLen = 12;
3401
+ const displayBranch = gitBranch.length > maxBranchLen ? gitBranch.substring(0, maxBranchLen - 3) + "..." : gitBranch;
3402
+ branchText = ` ${morandi.dim("\xB7")} ${morandi.dim("\u2387")} ${morandi.asst(displayBranch)}${gitStatusStats ? " " + morandi.accent(gitStatusStats) : ""}`;
3403
+ }
3404
+ const truncatePath = (p, maxLength) => {
3405
+ if (p.length <= maxLength) return p;
3406
+ const parts = p.split("/");
3407
+ if (parts.length <= 1) {
3408
+ return p.substring(p.length - maxLength);
3409
+ }
3410
+ const lastPart = parts[parts.length - 1];
3411
+ if (lastPart.length + 4 > maxLength) {
3412
+ return "..." + lastPart.substring(lastPart.length - (maxLength - 3));
3413
+ }
3414
+ let result = lastPart;
3415
+ for (let i = parts.length - 2; i >= 0; i--) {
3416
+ const nextResult = parts[i] + "/" + result;
3417
+ if (nextResult.length + 4 > maxLength) {
3418
+ return ".../" + result;
3419
+ }
3420
+ result = nextResult;
3421
+ }
3422
+ return result;
3423
+ };
3424
+ const pathLabel = "workspace: ";
3425
+ const branchWidth = gitBranch !== "no-git" ? 5 + Math.min(12, gitBranch.length) : 0;
3426
+ const maxPathWidth = Math.max(
3427
+ 6,
3428
+ availableWidth - pathLabel.length - branchWidth
3429
+ );
3430
+ const displayPath = truncatePath(shortCwd, maxPathWidth);
3431
+ const hitRate = this.totalInputTokens > 0 ? this.totalCacheReadTokens / this.totalInputTokens * 100 : 0;
3432
+ let cacheText = `[cache] hit: ${hitRate.toFixed(0)}% (${(this.totalCacheReadTokens / 1e3).toFixed(0)}k/${(this.totalInputTokens / 1e3).toFixed(0)}k tokens)`;
3433
+ if (this.getStringWidth(cacheText) > availableWidth) {
3434
+ cacheText = `[cache] hit: ${hitRate.toFixed(0)}% (${(this.totalCacheReadTokens / 1e3).toFixed(0)}k/${(this.totalInputTokens / 1e3).toFixed(0)}k)`;
3435
+ }
3436
+ if (this.getStringWidth(cacheText) > availableWidth) {
3437
+ cacheText = `[cache] hit: ${hitRate.toFixed(0)}%`;
3438
+ }
3439
+ const cleanHeaderModel = cleanModel.split("/").pop() || cleanModel;
3440
+ let headerLines;
3441
+ if (columns < 76) {
3442
+ const modelWidth = Math.max(8, columns - 16);
3443
+ const displayModel = this.getStringWidth(cleanHeaderModel) > modelWidth ? this.truncateToWidth(cleanHeaderModel, modelWidth - 3) + "..." : cleanHeaderModel;
3444
+ const compactPath = truncatePath(shortCwd, Math.max(8, columns - 15));
3445
+ const compactBranch = gitBranch === "no-git" ? "" : ` \xB7 ${gitBranch.length > 12 ? gitBranch.slice(0, 9) + "..." : gitBranch}`;
3446
+ headerLines = [
3447
+ ` ${morandi.whiteBold("O R B I T")} ${morandi.dim("\xB7")} ${morandi.accent(displayModel)}`,
3448
+ ` ${morandi.dim("workspace:")} ${morandi.gray(compactPath)}`,
3449
+ ` ${morandi.dim(cacheText)}${morandi.dim(compactBranch)}`
3450
+ ];
3451
+ } else {
3452
+ const headerLine1 = ` ${logoLines[0]}${pad0} ${morandi.whiteBold("O R B I T")} ${morandi.dim("\xB7")} ${morandi.accent(cleanHeaderModel)}`;
3453
+ const headerLine2 = ` ${logoLines[1]}${pad1} ${" ".repeat(20)}${morandi.dim("workspace:")} ${morandi.gray(displayPath)}${branchText}`;
3454
+ const headerLine3 = ` ${logoLines[2]}${pad2} ${" ".repeat(20)}${morandi.dim(cacheText)}`;
3455
+ const headerLine4 = ` ${logoLines[3]}${pad3}`;
3456
+ headerLines = [headerLine1, headerLine2, headerLine3, headerLine4];
3457
+ }
3458
+ const renderedLines = [];
3459
+ const turns = [];
3460
+ let currentTurn = null;
3461
+ for (const msg of this.history) {
3462
+ if (msg.role === "user") {
3463
+ if (currentTurn) {
3464
+ turns.push(currentTurn);
3465
+ }
3466
+ currentTurn = { user: msg, system: [] };
3467
+ } else if (msg.role === "assistant") {
3468
+ if (currentTurn) {
3469
+ currentTurn.assistant = msg;
3470
+ }
3471
+ } else if (msg.role === "system") {
3472
+ if (currentTurn) {
3473
+ currentTurn.system.push(msg);
3474
+ }
3475
+ }
3476
+ }
3477
+ if (currentTurn) {
3478
+ turns.push(currentTurn);
3479
+ }
3480
+ const lastAsst = [...this.history].reverse().find((m) => m.role === "assistant");
3481
+ const uBorder = " ";
3482
+ const aBorder = " ";
3483
+ for (const turn of turns) {
3484
+ renderedLines.push(" " + morandi.userBold("\u{1F464} User"));
3485
+ renderedLines.push(uBorder);
3486
+ const userLines = turn.user.text.split("\n");
3487
+ const wrappedUserLines = [];
3488
+ for (const line of userLines) {
3489
+ wrappedUserLines.push(...this.wrapLine(line, columns - 10));
3490
+ }
3491
+ for (const line of wrappedUserLines) {
3492
+ renderedLines.push(uBorder + morandi.user(line));
3493
+ }
3494
+ renderedLines.push(uBorder);
3495
+ renderedLines.push("");
3496
+ if (turn.assistant) {
3497
+ const asstLines = [];
3498
+ const systemLines = [];
3499
+ for (const sys of turn.system) {
3500
+ let text = sys.text.trim();
3501
+ if (text.startsWith("\u2713 Success") || text.startsWith("\u2716 Failed") || text.startsWith("\u2714 Success")) {
3502
+ continue;
3503
+ }
3504
+ if (text.startsWith("\u2714")) {
3505
+ text = morandi.completed("completed") + morandi.gray(text.substring(1));
3506
+ } else if (text.startsWith("\u2716")) {
3507
+ text = morandi.failed("failed") + morandi.gray(text.substring(1));
3508
+ } else if (text.startsWith("\u25CF")) {
3509
+ text = morandi.cyan("\u25CF") + morandi.gray(text.substring(1));
3510
+ } else if (text.startsWith("\u2726")) {
3511
+ text = morandi.cyan("\u2726") + morandi.gray(text.substring(1));
3512
+ } else if (text.startsWith("\u26A0")) {
3513
+ text = morandi.warn("\u26A0") + morandi.gray(text.substring(1));
3514
+ } else {
3515
+ text = morandi.cyan("\u2726") + " " + morandi.gray(text);
3516
+ }
3517
+ systemLines.push(text);
3518
+ }
3519
+ const isThinkingNow = turn.assistant === lastAsst && this.isThinking;
3520
+ const thoughtTimeVal = isThinkingNow ? this.thoughtElapsed : turn.assistant.thoughtTime;
3521
+ if (thoughtTimeVal !== void 0) {
3522
+ const timeStr = thoughtTimeVal >= 1e3 ? `${(thoughtTimeVal / 1e3).toFixed(1)}s` : `${thoughtTimeVal}ms`;
3523
+ const breatheDots = [
3524
+ "\x1B[38;2;142;163;175m\xB7\x1B[0m",
3525
+ "\x1B[38;2;143;153;129m\u2022\x1B[0m",
3526
+ "\x1B[38;2;200;170;120m\u25CF\x1B[0m",
3527
+ "\x1B[38;2;135;165;130m\u2022\x1B[0m"
3528
+ ];
3529
+ const spinIdx = Math.floor(Date.now() / 250) % 4;
3530
+ const dotChar = isThinkingNow ? breatheDots[spinIdx] : morandi.gray("\u2022");
3531
+ if (isThinkingNow) {
3532
+ asstLines.push(
3533
+ `${dotChar} ` + morandi.accent(`Thinking... ${timeStr}`)
3534
+ );
3535
+ if (this.currentThinking) {
3536
+ const lines = this.currentThinking.split("\n").filter(Boolean);
3537
+ const lastLines = lines.slice(-4);
3538
+ const maxL = columns - 14;
3539
+ for (const line of lastLines) {
3540
+ const trimmed = line.trim();
3541
+ let displayText = trimmed;
3542
+ const displayW = this.getStringWidth(displayText);
3543
+ if (displayW > maxL) {
3544
+ displayText = this.truncateToWidth(displayText, maxL - 3) + "...";
3545
+ }
3546
+ asstLines.push(
3547
+ " " + morandi.gray("\xB7 ") + morandi.dim(displayText)
3548
+ );
3549
+ }
3550
+ }
3551
+ } else {
3552
+ asstLines.push(
3553
+ morandi.gray("\u{1F9E0} ") + morandi.dim(`Thought for ${timeStr}`)
3554
+ );
3555
+ }
3556
+ }
3557
+ if (systemLines.length > 0) {
3558
+ asstLines.push(...systemLines);
3559
+ }
3560
+ if (turn.assistant.text) {
3561
+ if (asstLines.length > 0) {
3562
+ asstLines.push("");
3563
+ }
3564
+ const asstObj = turn.assistant;
3565
+ const isStreaming = this.resolveInput === null;
3566
+ const nowTime = Date.now();
3567
+ const timeSinceLastRender = nowTime - (asstObj._lastMarkdownRenderTime || 0);
3568
+ if (!asstObj._formattedCached || asstObj._textCached !== turn.assistant.text) {
3569
+ if (!isStreaming || timeSinceLastRender >= 150 || !asstObj._formattedCached) {
3570
+ asstObj._formattedCached = Renderer.formatMarkdown(
3571
+ turn.assistant.text
3572
+ ).split("\n");
3573
+ asstObj._textCached = turn.assistant.text;
3574
+ asstObj._lastMarkdownRenderTime = nowTime;
3575
+ }
3576
+ }
3577
+ asstLines.push(...asstObj._formattedCached);
3578
+ }
3579
+ let footerStatusLine = "";
3580
+ const lastSys = turn.system[turn.system.length - 1];
3581
+ if (lastSys && lastSys.text.includes("Failed")) {
3582
+ footerStatusLine = `${morandi.failed("failed")} \xB7 ${morandi.dim(cleanModel)}`;
3583
+ } else if (turn.assistant.totalTime !== void 0) {
3584
+ const sec = (turn.assistant.totalTime / 1e3).toFixed(1);
3585
+ footerStatusLine = `${morandi.completed("completed")} \xB7 ${morandi.dim(cleanModel)} \xB7 ${morandi.dim(sec + "s")}`;
3586
+ }
3587
+ if (footerStatusLine) {
3588
+ asstLines.push("");
3589
+ asstLines.push(footerStatusLine);
3590
+ }
3591
+ const wrappedAsstLines = [];
3592
+ for (const line of asstLines) {
3593
+ wrappedAsstLines.push(...this.wrapLine(line, columns - 10));
3594
+ }
3595
+ renderedLines.push(
3596
+ " " + morandi.asstBold(`\u{1F916} Orbit (${cleanModel})`)
3597
+ );
3598
+ renderedLines.push(aBorder);
3599
+ for (const line of wrappedAsstLines) {
3600
+ renderedLines.push(aBorder + line);
3601
+ }
3602
+ renderedLines.push(aBorder);
3603
+ renderedLines.push("");
3604
+ }
3605
+ }
3606
+ let planText = "";
3607
+ const planItems = this.getPlanLines();
3608
+ if (planItems.length > 0) {
3609
+ const planContent = [];
3610
+ let activeIndex = planItems.findIndex((item) => item.startsWith("- [/]"));
3611
+ if (activeIndex === -1) {
3612
+ activeIndex = planItems.findIndex((item) => item.startsWith("- [ ]"));
3613
+ }
3614
+ if (activeIndex === -1) {
3615
+ activeIndex = planItems.length - 1;
3616
+ }
3617
+ planContent.push(" " + morandi.accent("\u{1F4CB} Active Plan:"));
3618
+ const startPlanIdx = Math.max(0, activeIndex - 1);
3619
+ const endPlanIdx = Math.min(planItems.length - 1, activeIndex + 1);
3620
+ if (startPlanIdx > 0) {
3621
+ planContent.push(
3622
+ " " + morandi.dim(`... ${startPlanIdx} step(s) completed`)
3623
+ );
3624
+ }
3625
+ for (let i = startPlanIdx; i <= endPlanIdx; i++) {
3626
+ const item = planItems[i];
3627
+ const text = item.substring(5).trim();
3628
+ const isCurrentRunning = item.startsWith("- [/]") || item.startsWith("- [/");
3629
+ const isCompleted = item.startsWith("- [x]") || item.startsWith("- [x");
3630
+ let prefixSymbol = "";
3631
+ if (isCurrentRunning) {
3632
+ prefixSymbol = morandi.accent("\u25CF");
3633
+ } else if (isCompleted) {
3634
+ prefixSymbol = morandi.completed("\u2714");
3635
+ } else {
3636
+ prefixSymbol = morandi.gray("\u25CB");
3637
+ }
3638
+ let displayText = text;
3639
+ const maxTextLen = columns - 12;
3640
+ const displayW = this.getStringWidth(displayText);
3641
+ if (displayW > maxTextLen) {
3642
+ displayText = this.truncateToWidth(displayText, maxTextLen - 3) + "...";
3643
+ }
3644
+ const coloredText = isCurrentRunning ? morandi.whiteBold(displayText) : isCompleted ? morandi.dim(displayText) : morandi.gray(displayText);
3645
+ planContent.push(" " + prefixSymbol + " " + coloredText);
3646
+ }
3647
+ if (endPlanIdx < planItems.length - 1) {
3648
+ const remaining = planItems.length - 1 - endPlanIdx;
3649
+ planContent.push(
3650
+ " " + morandi.dim(`... ${remaining} step(s) pending`)
3651
+ );
3652
+ }
3653
+ planText = planContent.join("\n") + "\n\n";
3654
+ }
3655
+ let contextText = "";
3656
+ if (this.activeContextFiles && this.activeContextFiles.length > 0) {
3657
+ const contextLines = [];
3658
+ contextLines.push(" " + morandi.accent("\u{1F4CE} Context Files:"));
3659
+ const filesStr = this.activeContextFiles.map((f) => `[${f.path}${f.readOnly ? " \u{1F512}" : ""}]`).join(" ");
3660
+ const maxW = columns - 10;
3661
+ const wrappedFiles = this.wrapLine(filesStr, maxW);
3662
+ for (const line of wrappedFiles) {
3663
+ contextLines.push(" " + morandi.white(line));
3664
+ }
3665
+ contextText = contextLines.join("\n") + "\n\n";
3666
+ }
3667
+ const headerText = `${headerLines.join("\n")}
3668
+
3669
+ ` + planText + contextText;
3670
+ const headerHeight = headerText.split("\n").length;
3671
+ const maxContentRows = Math.max(1, rows - bottomHeight - headerHeight - 1);
3672
+ const flatLines = [];
3673
+ for (const item of renderedLines) {
3674
+ flatLines.push(...item.split("\n"));
3675
+ }
3676
+ if (this.historyScrollOffset > 0 && flatLines.length > this.lastHistoryLineCount) {
3677
+ this.historyScrollOffset += flatLines.length - this.lastHistoryLineCount;
3678
+ this.hasNewOutputWhileScrolled = true;
3679
+ }
3680
+ this.lastHistoryLineCount = flatLines.length;
3681
+ this.maxHistoryScrollOffset = Math.max(
3682
+ 0,
3683
+ flatLines.length - maxContentRows
3684
+ );
3685
+ this.historyScrollOffset = Math.min(
3686
+ this.historyScrollOffset,
3687
+ this.maxHistoryScrollOffset
3688
+ );
3689
+ const finalLines = [];
3690
+ let totalLinesCount = 0;
3691
+ const visibleEnd = Math.max(0, flatLines.length - this.historyScrollOffset);
3692
+ for (let i = visibleEnd - 1; i >= 0; i--) {
3693
+ const line = flatLines[i];
3694
+ const visibleLen = this.getStringWidth(line);
3695
+ const lineRows = Math.max(
3696
+ 1,
3697
+ Math.ceil(visibleLen / Math.max(1, columns - 4))
3698
+ );
3699
+ if (totalLinesCount + lineRows > maxContentRows) {
3700
+ break;
3701
+ }
3702
+ totalLinesCount += lineRows;
3703
+ finalLines.unshift(line);
3704
+ }
3705
+ while (finalLines.length > 0 && finalLines[finalLines.length - 1].replace(/\x1b\[[0-9;]*[a-zA-Z]/g, "").trim() === "") {
3706
+ finalLines.pop();
3707
+ }
3708
+ const gapHeight = finalLines.length > 0 ? 1 : 0;
3709
+ const totalHeight = headerHeight + finalLines.length + gapHeight + bottomHeight;
3710
+ const extraPad = Math.max(0, rows - totalHeight);
3711
+ const allLines = [];
3712
+ allLines.push(...headerText.split("\n"));
3713
+ if (extraPad > 0) {
3714
+ for (let i = 0; i < extraPad; i++) {
3715
+ allLines.push("");
3716
+ }
3717
+ }
3718
+ if (finalLines.length > 0) {
3719
+ allLines.push(...finalLines);
3720
+ allLines.push("");
3721
+ }
3722
+ allLines.push(...bottomLines);
3723
+ const rawLines = allLines;
3724
+ const staticText = rawLines.slice(0, rawLines.length - bottomHeight).join("\n");
3725
+ const canIncremental = !forceFull && isInputActive && this.cachedStaticLinesCount > 0 && bottomHeight === this.lastRenderedBottomHeight && staticText === this.cachedStaticContent;
3726
+ if (canIncremental) {
3727
+ let cursorSequence2 = "";
3728
+ let tempLen = 0;
3729
+ let cursorLineIndex = 0;
3730
+ let xOffset = 0;
3731
+ for (let i = 0; i < wrappedLines.length; i++) {
3732
+ const line = wrappedLines[i];
3733
+ if (this.cursorPosition >= tempLen && this.cursorPosition <= tempLen + line.length) {
3734
+ cursorLineIndex = i;
3735
+ const subStr = line.substring(0, this.cursorPosition - tempLen);
3736
+ xOffset = this.getStringWidth(subStr);
3737
+ break;
3738
+ }
3739
+ tempLen += line.length;
3740
+ }
3741
+ const lineStartX = cursorLineIndex === 0 ? this.getStringWidth(" \u2502 orbit > ") : 12;
3742
+ const targetX = lineStartX + xOffset;
3743
+ const linesUp = formattedLines.length - cursorLineIndex + 1;
3744
+ cursorSequence2 = `\x1B[${linesUp}A\x1B[${targetX + 1}G\x1B[?25h`;
3745
+ const bottomOutput = `\x1B[?25l\x1B[${this.cachedStaticLinesCount + 1};1H` + // 移至底部的首行
3746
+ bottomLines.map((line) => line + "\x1B[K").join("\n") + "\x1B[J" + // 擦拭并重写 bottomLines
3747
+ cursorSequence2;
3748
+ process.stdout.write(bottomOutput);
3749
+ return;
3750
+ }
3751
+ this.cachedStaticLinesCount = rawLines.length - bottomHeight;
3752
+ this.cachedStaticContent = staticText;
3753
+ this.lastRenderedBottomHeight = bottomHeight;
3754
+ let finalOutput = "\x1B[?25l\x1B[H" + rawLines.map((line) => line + "\x1B[K").join("\n") + "\x1B[J";
3755
+ let cursorSequence = "";
3756
+ if (this.resolveInput || this.thinkingKeypressListener !== null) {
3757
+ let tempLen = 0;
3758
+ let cursorLineIndex = 0;
3759
+ let xOffset = 0;
3760
+ for (let i = 0; i < wrappedLines.length; i++) {
3761
+ const line = wrappedLines[i];
3762
+ if (this.cursorPosition >= tempLen && this.cursorPosition <= tempLen + line.length) {
3763
+ cursorLineIndex = i;
3764
+ const subStr = line.substring(0, this.cursorPosition - tempLen);
3765
+ xOffset = this.getStringWidth(subStr);
3766
+ break;
3767
+ }
3768
+ tempLen += line.length;
3769
+ }
3770
+ const lineStartX = cursorLineIndex === 0 ? this.getStringWidth(" \u2502 orbit > ") : 12;
3771
+ const targetX = lineStartX + xOffset;
3772
+ const linesUp = formattedLines.length - cursorLineIndex + 1;
3773
+ cursorSequence = `\x1B[${linesUp}A\x1B[${targetX + 1}G\x1B[?25h`;
3774
+ } else {
3775
+ cursorSequence = "\x1B[?25l";
3776
+ }
3777
+ finalOutput += cursorSequence;
3778
+ process.stdout.write(finalOutput);
3779
+ }
3780
+ isFullWidth(codePoint) {
3781
+ if (Number.isNaN(codePoint)) {
3782
+ return false;
3783
+ }
3784
+ if (codePoint === 9698 || // ◢
3785
+ codePoint === 9699 || // ◣
3786
+ codePoint === 9700 || // ◤
3787
+ codePoint === 9701 || // ◥
3788
+ codePoint === 9616 || // ▐
3789
+ codePoint === 9612 || // ▌
3790
+ codePoint === 9679) {
3791
+ return true;
3792
+ }
3793
+ return codePoint >= 4352 && codePoint <= 4447 || // Hangul Jamo
3794
+ codePoint === 9001 || // LEFT-POINTING ANGLE BRACKET
3795
+ codePoint === 9002 || // RIGHT-POINTING ANGLE BRACKET
3796
+ codePoint >= 11904 && codePoint <= 12871 && codePoint !== 12351 || // CJK Radicals Supplement .. Enclosed CJK Letters and Months
3797
+ codePoint >= 12880 && codePoint <= 19903 || // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A
3798
+ codePoint >= 19968 && codePoint <= 42182 || // CJK Unified Ideographs .. Yi Radicals
3799
+ codePoint >= 43360 && codePoint <= 43388 || // Hangul Jamo Extended-A
3800
+ codePoint >= 44032 && codePoint <= 55203 || // Hangul Syllables
3801
+ codePoint >= 63744 && codePoint <= 64255 || // CJK Compatibility Ideographs
3802
+ codePoint >= 65040 && codePoint <= 65049 || // Vertical Forms
3803
+ codePoint >= 65072 && codePoint <= 65131 || // CJK Compatibility Forms .. Small Form Variants
3804
+ codePoint >= 65281 && codePoint <= 65376 || // Halfwidth and Fullwidth Forms
3805
+ codePoint >= 65504 && codePoint <= 65510 || codePoint >= 110592 && codePoint <= 110593 || // Kana Supplement
3806
+ codePoint >= 127488 && codePoint <= 127569 || // Enclosed Ideographic Supplement
3807
+ codePoint >= 131072 && codePoint <= 262141 || // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane
3808
+ codePoint >= 127744 && codePoint <= 129535 || // Emojis
3809
+ codePoint >= 128512 && codePoint <= 128591 || // Emoticons
3810
+ codePoint >= 128640 && codePoint <= 128767;
3811
+ }
3812
+ truncateToWidth(str, maxW) {
3813
+ let width = 0;
3814
+ let result = "";
3815
+ for (const char of str) {
3816
+ const code = char.codePointAt(0);
3817
+ if (code === void 0) continue;
3818
+ const charW = this.isFullWidth(code) ? 2 : 1;
3819
+ if (width + charW > maxW) {
3820
+ break;
3821
+ }
3822
+ width += charW;
3823
+ result += char;
3824
+ }
3825
+ return result;
3826
+ }
3827
+ wrapLine(line, maxWidth) {
3828
+ const cleanLine = line.replace(
3829
+ /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,
3830
+ ""
3831
+ );
3832
+ if (this.getStringWidth(cleanLine) <= maxWidth) {
3833
+ return [line];
3834
+ }
3835
+ const lines = [];
3836
+ let currentLine = "";
3837
+ let currentWidth = 0;
3838
+ const ansiRegex = /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g;
3839
+ let activeColor = "";
3840
+ let i = 0;
3841
+ while (i < line.length) {
3842
+ ansiRegex.lastIndex = i;
3843
+ const match = ansiRegex.exec(line);
3844
+ if (match && match.index === i) {
3845
+ const ansiCode = match[0];
3846
+ currentLine += ansiCode;
3847
+ if (ansiCode.includes("m") && !ansiCode.includes("[0m")) {
3848
+ activeColor = ansiCode;
3849
+ } else if (ansiCode.includes("[0m")) {
3850
+ activeColor = "";
3851
+ }
3852
+ i += ansiCode.length;
3853
+ continue;
3854
+ }
3855
+ const code = line.codePointAt(i);
3856
+ let charLen = 1;
3857
+ if (code && code > 65535) {
3858
+ charLen = 2;
3859
+ }
3860
+ const charStr = line.substring(i, i + charLen);
3861
+ const charW = this.isFullWidth(code || 0) ? 2 : 1;
3862
+ if (currentWidth + charW > maxWidth) {
3863
+ if (activeColor) {
3864
+ currentLine += "\x1B[0m";
3865
+ }
3866
+ lines.push(currentLine);
3867
+ currentLine = activeColor + charStr;
3868
+ currentWidth = charW;
3869
+ } else {
3870
+ currentLine += charStr;
3871
+ currentWidth += charW;
3872
+ }
3873
+ i += charLen;
3874
+ }
3875
+ if (currentLine) {
3876
+ lines.push(currentLine);
3877
+ }
3878
+ return lines;
3879
+ }
3880
+ getStringWidth(str) {
3881
+ const cleanStr = str.replace(
3882
+ /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,
3883
+ ""
3884
+ );
3885
+ let width = 0;
3886
+ for (let i = 0; i < cleanStr.length; i++) {
3887
+ const code = cleanStr.codePointAt(i);
3888
+ if (!code) continue;
3889
+ if (code > 65535) {
3890
+ i++;
3891
+ }
3892
+ if (this.isFullWidth(code)) {
3893
+ width += 2;
3894
+ } else {
3895
+ width += 1;
3896
+ }
3897
+ }
3898
+ return width;
3899
+ }
3900
+ wrapText(str, maxWidth) {
3901
+ const lines = [];
3902
+ let currentLine = "";
3903
+ let currentWidth = 0;
3904
+ for (let i = 0; i < str.length; i++) {
3905
+ const code = str.codePointAt(i);
3906
+ if (!code) continue;
3907
+ let char = str.charAt(i);
3908
+ if (code > 65535) {
3909
+ char = str.substring(i, i + 2);
3910
+ i++;
3911
+ }
3912
+ const charWidth = this.isFullWidth(code) ? 2 : 1;
3913
+ if (currentWidth + charWidth > maxWidth) {
3914
+ lines.push(currentLine);
3915
+ currentLine = char;
3916
+ currentWidth = charWidth;
3917
+ } else {
3918
+ currentLine += char;
3919
+ currentWidth += charWidth;
3920
+ }
3921
+ }
3922
+ if (currentLine || lines.length === 0) {
3923
+ lines.push(currentLine);
3924
+ }
3925
+ return lines;
3926
+ }
3927
+ formatWrappedLines(wrappedLines, inputLength) {
3928
+ let charIndex = 0;
3929
+ const formattedLines = [];
3930
+ for (const line of wrappedLines) {
3931
+ let formattedLine = "";
3932
+ for (let i = 0; i < line.length; i++) {
3933
+ const char = line.charAt(i);
3934
+ const code = line.codePointAt(i);
3935
+ let increment = 1;
3936
+ let charStr = char;
3937
+ if (code && code > 65535) {
3938
+ charStr = line.substring(i, i + 2);
3939
+ i++;
3940
+ increment = 2;
3941
+ }
3942
+ if (charIndex < inputLength) {
3943
+ formattedLine += `\x1B[1;38;2;230;225;215m${charStr}\x1B[0m`;
3944
+ } else {
3945
+ formattedLine += `\x1B[2;38;2;110;110;110m${charStr}\x1B[0m`;
3946
+ }
3947
+ charIndex += increment;
3948
+ }
3949
+ formattedLines.push(formattedLine);
3950
+ }
3951
+ return formattedLines;
3952
+ }
3953
+ };
3954
+
3955
+ // src/runtime/ReplController.ts
3956
+ import {
3957
+ AgentLoop,
3958
+ Orchestrator,
3959
+ eventBus,
3960
+ AutocompleteEngine
3961
+ } from "@orbit-build/core";
3962
+ import { Prompt as Prompt3, Renderer as Renderer2 } from "@orbit-build/tui";
3963
+ import picocolors5 from "picocolors";
3964
+ import { existsSync as existsSync5, readFileSync as readFileSync4, writeFileSync as writeFileSync3, mkdirSync as mkdirSync2, watch } from "fs";
3965
+ import { join as join5, dirname as dirname3, resolve as resolve2 } from "path";
3966
+ import { homedir as homedir4 } from "os";
3967
+ import http from "http";
3968
+ import { SymbolIndexer } from "@orbit-build/context-engine";
3969
+ var ReplController = class {
3970
+ constructor(cwd, config, providerInstance, interaction, multi, direct) {
3971
+ this.cwd = cwd;
3972
+ this.config = config;
3973
+ this.providerInstance = providerInstance;
3974
+ this.interaction = interaction;
3975
+ this.multi = multi;
3976
+ this.direct = direct;
3977
+ }
3978
+ cwd;
3979
+ config;
3980
+ providerInstance;
3981
+ interaction;
3982
+ multi;
3983
+ direct;
3984
+ currentTui = null;
3985
+ watchTimeout = null;
3986
+ watcher = null;
3987
+ candidates = null;
3988
+ autocompleteServer = null;
3989
+ getLocalState() {
3990
+ const statePath = join5(this.cwd, ".orbit", "state.json");
3991
+ if (!existsSync5(statePath)) return {};
3992
+ try {
3993
+ return JSON.parse(readFileSync4(statePath, "utf8"));
3994
+ } catch {
3995
+ return {};
3996
+ }
3997
+ }
3998
+ saveLocalState(state) {
3999
+ const statePath = join5(this.cwd, ".orbit", "state.json");
4000
+ try {
4001
+ const dir = dirname3(statePath);
4002
+ if (!existsSync5(dir)) {
4003
+ mkdirSync2(dir, { recursive: true });
4004
+ }
4005
+ const current = this.getLocalState();
4006
+ const updated = { ...current, ...state };
4007
+ writeFileSync3(statePath, JSON.stringify(updated, null, 2), "utf8");
4008
+ } catch {
4009
+ }
4010
+ }
4011
+ startAutocompleteServer() {
4012
+ const engine = new AutocompleteEngine();
4013
+ const server = http.createServer(async (req, res) => {
4014
+ res.setHeader("Access-Control-Allow-Origin", "*");
4015
+ res.setHeader("Access-Control-Allow-Methods", "POST, OPTIONS");
4016
+ res.setHeader("Access-Control-Allow-Headers", "Content-Type");
4017
+ if (req.method === "OPTIONS") {
4018
+ res.writeHead(200);
4019
+ res.end();
4020
+ return;
4021
+ }
4022
+ if (req.method === "POST" && req.url === "/autocomplete") {
4023
+ let body = "";
4024
+ req.on("data", (chunk) => {
4025
+ body += chunk;
4026
+ });
4027
+ req.on("end", async () => {
4028
+ try {
4029
+ const parsed = JSON.parse(body);
4030
+ const prefix = parsed.prefix || "";
4031
+ const suffix = parsed.suffix || "";
4032
+ const completion = await engine.autocomplete(prefix, suffix, this.config);
4033
+ res.writeHead(200, { "Content-Type": "application/json" });
4034
+ res.end(JSON.stringify({ completion }));
4035
+ } catch (e) {
4036
+ res.writeHead(400, { "Content-Type": "application/json" });
4037
+ res.end(JSON.stringify({ error: e.message }));
4038
+ }
4039
+ });
4040
+ } else {
4041
+ res.writeHead(404);
4042
+ res.end();
4043
+ }
4044
+ });
4045
+ let currentPort = 6018;
4046
+ server.once("listening", () => {
4047
+ eventBus.emitEvent("info", {
4048
+ message: `Autocomplete bridge server running on http://127.0.0.1:${currentPort}`
4049
+ });
4050
+ });
4051
+ server.on("error", (err) => {
4052
+ if (err.code === "EADDRINUSE") {
4053
+ currentPort++;
4054
+ server.listen(currentPort, "127.0.0.1");
4055
+ }
4056
+ });
4057
+ server.listen(currentPort, "127.0.0.1");
4058
+ return server;
4059
+ }
4060
+ async start() {
4061
+ const version = "v0.1.0";
4062
+ const sigintHandler = () => {
4063
+ };
4064
+ process.on("SIGINT", sigintHandler);
4065
+ const isTTY = process.stdin.isTTY && typeof process.stdin.setRawMode === "function";
4066
+ const useFullscreenTui = isTTY && !this.direct;
4067
+ this.autocompleteServer = this.config.autocomplete?.enabled ? this.startAutocompleteServer() : null;
4068
+ const tui = new FullscreenTui(this.cwd, this.config.models.default, version, this.config);
4069
+ this.currentTui = tui;
4070
+ tui.setPermissionsMode(this.config.permissions.mode);
4071
+ const tuiInteraction = {
4072
+ askApproval: async (reason, preview) => {
4073
+ const wasActive = useFullscreenTui && tui.isActive;
4074
+ if (wasActive) tui.stop();
4075
+ console.log(`
4076
+ Risk Warning: ${reason}`);
4077
+ if (preview) {
4078
+ console.log(picocolors5.gray(`Parameters: ${preview}`));
4079
+ }
4080
+ const approved = await Prompt3.askApproval("Confirm action?");
4081
+ if (wasActive) tui.start(this.config.budgetLimit);
4082
+ return approved;
4083
+ },
4084
+ showText(text) {
4085
+ if (useFullscreenTui && tui.isActive) {
4086
+ tui.addLog(text);
4087
+ } else {
4088
+ console.log(text);
4089
+ }
4090
+ },
4091
+ showDiff: async (filePath, before, after) => {
4092
+ const wasActive = useFullscreenTui && tui.isActive;
4093
+ if (wasActive) tui.stop();
4094
+ await pageText(DiffView.render(filePath, before, after));
4095
+ if (wasActive) tui.start(this.config.budgetLimit);
4096
+ }
4097
+ };
4098
+ const localState = this.getLocalState();
4099
+ let resumeSessionId;
4100
+ if (localState.lastSessionId) {
4101
+ const resume = await Prompt3.askApproval(
4102
+ `Found previous session (${localState.lastSessionId}). Resume last session?`
4103
+ );
4104
+ if (resume) {
4105
+ resumeSessionId = localState.lastSessionId;
4106
+ }
4107
+ }
4108
+ const loop = new AgentLoop(
4109
+ this.cwd,
4110
+ this.config,
4111
+ this.providerInstance,
4112
+ "REPL Interactive Shell Started",
4113
+ tuiInteraction,
4114
+ {
4115
+ disableStatusBar: useFullscreenTui,
4116
+ sessionId: resumeSessionId
4117
+ }
4118
+ );
4119
+ this.saveLocalState({
4120
+ lastSessionId: loop.getSessionId(),
4121
+ lastModel: loop.getModelOverride() || this.config.models.default
4122
+ });
4123
+ if (resumeSessionId && useFullscreenTui) {
4124
+ tui.loadHistory(loop.getHistory());
4125
+ }
4126
+ tui.setModelNameGetter(
4127
+ () => loop.getModelOverride() || this.config.models.default
4128
+ );
4129
+ this.candidates = await getAutocompleteCandidates(this.cwd, this.config);
4130
+ tui.setCandidates(this.candidates);
4131
+ const onModelDelta = (payload) => {
4132
+ if (useFullscreenTui) {
4133
+ tui.handleModelDelta(payload.text);
4134
+ } else {
4135
+ process.stdout.write(payload.text);
4136
+ }
4137
+ };
4138
+ const onLoopStart = (payload) => {
4139
+ if (useFullscreenTui) {
4140
+ tui.startAttempt(payload.attempt);
4141
+ }
4142
+ };
4143
+ const onCostUpdate = (payload) => {
4144
+ if (useFullscreenTui) {
4145
+ tui.setCost(
4146
+ payload.sessionCost,
4147
+ payload.totalInputTokens,
4148
+ payload.totalCacheReadTokens,
4149
+ payload.totalOutputTokens
4150
+ );
4151
+ }
4152
+ };
4153
+ const onThinkingDelta = (payload) => {
4154
+ if (useFullscreenTui) {
4155
+ tui.handleThinkingDelta(payload.text);
4156
+ } else {
4157
+ process.stdout.write(picocolors5.gray(payload.text));
4158
+ }
4159
+ };
4160
+ eventBus.on("model_delta", onModelDelta);
4161
+ eventBus.on("loop_start", onLoopStart);
4162
+ eventBus.on("cost_update", onCostUpdate);
4163
+ eventBus.on("thinking_delta", onThinkingDelta);
4164
+ const ignorePatterns = this.config.context?.ignore || [];
4165
+ const ignoreRegexes = ignorePatterns.map((pattern) => {
4166
+ const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*\*/g, ".*").replace(/\*/g, "[^/]*");
4167
+ const finalPattern = escaped.endsWith(".*") ? "^" + escaped + "$" : "(^" + escaped + "$|^" + escaped + "/.*)";
4168
+ return new RegExp(finalPattern);
4169
+ });
4170
+ const normCwd = resolve2(this.cwd).toLowerCase().replace(/\\/g, "/");
4171
+ const normHome = resolve2(homedir4()).toLowerCase().replace(/\\/g, "/");
4172
+ const isHomeOrRoot = normCwd === normHome || normCwd === "/" || /^[a-zA-Z]:\/$/.test(normCwd) || dirname3(normCwd) === normCwd;
4173
+ if (!isHomeOrRoot) {
4174
+ const indexer = new SymbolIndexer(this.cwd);
4175
+ this.watcher = watch(this.cwd, { recursive: true }, (eventType, filename) => {
4176
+ if (filename && /\.(ts|tsx|js|jsx)$/.test(filename) && !filename.includes(".orbit")) {
4177
+ const normalized = filename.replace(/\\/g, "/");
4178
+ const isIgnored = ignoreRegexes.some(
4179
+ (rx) => rx.test(normalized)
4180
+ );
4181
+ if (isIgnored) return;
4182
+ if (this.watchTimeout) clearTimeout(this.watchTimeout);
4183
+ this.watchTimeout = setTimeout(() => {
4184
+ indexer.index().catch(() => {
4185
+ });
4186
+ }, 500);
4187
+ }
4188
+ });
4189
+ }
4190
+ if (useFullscreenTui) {
4191
+ tui.start(this.config.budgetLimit);
4192
+ } else {
4193
+ Renderer2.printHeader(loop.getSessionId(), this.config.models.default, this.cwd);
4194
+ }
4195
+ const commandRouter = new CommandRouter(
4196
+ this.cwd,
4197
+ this.config,
4198
+ this.providerInstance,
4199
+ (newProvider) => {
4200
+ this.providerInstance = newProvider;
4201
+ },
4202
+ loop,
4203
+ tui,
4204
+ useFullscreenTui,
4205
+ () => this.candidates,
4206
+ (c) => {
4207
+ this.candidates = c;
4208
+ tui.setCandidates(c);
4209
+ },
4210
+ this.getLocalState.bind(this),
4211
+ this.saveLocalState.bind(this),
4212
+ tuiInteraction,
4213
+ this.multi
4214
+ );
4215
+ try {
4216
+ while (true) {
4217
+ let input;
4218
+ if (useFullscreenTui) {
4219
+ input = await tui.askInput();
4220
+ } else {
4221
+ input = await Prompt3.askTextWithAutocomplete(
4222
+ "Type your task or command...",
4223
+ this.makeCompleter(),
4224
+ `${picocolors5.bold(picocolors5.magenta("orbit"))}${picocolors5.gray(" \u276F ")}`
4225
+ );
4226
+ }
4227
+ if (input === null) {
4228
+ if (useFullscreenTui) {
4229
+ tui.stop();
4230
+ }
4231
+ console.log(
4232
+ picocolors5.yellow("Exiting Orbit Interactive Shell. Goodbye!")
4233
+ );
4234
+ break;
4235
+ }
4236
+ if (!input) continue;
4237
+ const trimmed = input.trim();
4238
+ if (!trimmed) continue;
4239
+ const routeResult = await commandRouter.route(trimmed);
4240
+ if (routeResult.shouldExit) {
4241
+ break;
4242
+ }
4243
+ if (routeResult.processed) {
4244
+ continue;
4245
+ }
4246
+ const state = loop.state;
4247
+ state.task = trimmed;
4248
+ state.done = false;
4249
+ state.attemptCount = 0;
4250
+ state.history.push({
4251
+ id: `msg_user_${Date.now()}`,
4252
+ role: "user",
4253
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
4254
+ content: [{ type: "text", text: trimmed }]
4255
+ });
4256
+ const activeSession = loop.sessionManager.getActiveSession();
4257
+ if (activeSession && (activeSession.title === "New Orbit Session" || !activeSession.title)) {
4258
+ const fastModel = this.config.models.fast || this.config.models.default;
4259
+ const firstPrompt = trimmed;
4260
+ Promise.resolve().then(async () => {
4261
+ try {
4262
+ const stream = this.providerInstance.chat({
4263
+ model: fastModel,
4264
+ messages: [
4265
+ {
4266
+ id: `msg_title_gen_${Date.now()}`,
4267
+ role: "user",
4268
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
4269
+ content: [
4270
+ {
4271
+ type: "text",
4272
+ text: `Summarize the following user task into a very concise title (max 5 words, e.g. "Fix button layout" or "Add login unit tests"). Output ONLY the title, no markdown, no punctuation, no quotes:
4273
+
4274
+ ${firstPrompt.substring(0, 1e3)}`
4275
+ }
4276
+ ]
4277
+ }
4278
+ ],
4279
+ tools: []
4280
+ });
4281
+ let title = "";
4282
+ for await (const event of stream) {
4283
+ if (event.type === "text_delta") {
4284
+ title += event.text;
4285
+ }
4286
+ }
4287
+ const finalTitle = title.trim().replace(/^["']|["']$/g, "");
4288
+ if (finalTitle && activeSession.id === loop.sessionManager.getActiveSession()?.id) {
4289
+ activeSession.title = finalTitle;
4290
+ loop.sessionManager.getSessionStore().updateSession(activeSession);
4291
+ }
4292
+ } catch {
4293
+ }
4294
+ });
4295
+ }
4296
+ let orchestratorInstance = null;
4297
+ if (this.multi) {
4298
+ orchestratorInstance = new Orchestrator(
4299
+ this.cwd,
4300
+ this.config,
4301
+ this.providerInstance,
4302
+ trimmed,
4303
+ tuiInteraction
4304
+ );
4305
+ tui.setActiveRunnable(orchestratorInstance);
4306
+ } else {
4307
+ tui.setActiveRunnable(loop);
4308
+ }
4309
+ tui.startThinkingInput();
4310
+ try {
4311
+ if (orchestratorInstance) {
4312
+ await orchestratorInstance.run();
4313
+ } else {
4314
+ await loop.run();
4315
+ }
4316
+ } catch {
4317
+ } finally {
4318
+ tui.stopThinkingInput();
4319
+ tui.setActiveRunnable(null);
4320
+ }
4321
+ while (tui.pendingGuidedStatement) {
4322
+ const guidedTask = tui.pendingGuidedStatement;
4323
+ tui.pendingGuidedStatement = null;
4324
+ const isZh = this.config.language === "zh";
4325
+ tuiInteraction.showText(
4326
+ isZh ? `
4327
+ \u25CF \u6536\u5230\u5F15\u5BFC\u6307\u4EE4\u3002\u6B63\u5728\u91CD\u65B0\u89C4\u5212\u601D\u8003...` : `
4328
+ \u25CF Guided instruction received. Replanning execution...`
4329
+ );
4330
+ state.task = guidedTask;
4331
+ state.done = false;
4332
+ state.attemptCount = 0;
4333
+ state.history.push({
4334
+ id: `msg_user_${Date.now()}`,
4335
+ role: "user",
4336
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
4337
+ content: [{ type: "text", text: guidedTask }]
4338
+ });
4339
+ tui.syncFromLoop(loop);
4340
+ let subOrchestrator = null;
4341
+ if (this.multi) {
4342
+ subOrchestrator = new Orchestrator(
4343
+ this.cwd,
4344
+ this.config,
4345
+ this.providerInstance,
4346
+ guidedTask,
4347
+ tuiInteraction
4348
+ );
4349
+ tui.setActiveRunnable(subOrchestrator);
4350
+ } else {
4351
+ tui.setActiveRunnable(loop);
4352
+ }
4353
+ tui.startThinkingInput();
4354
+ try {
4355
+ if (subOrchestrator) {
4356
+ await subOrchestrator.run();
4357
+ } else {
4358
+ await loop.run();
4359
+ }
4360
+ } catch {
4361
+ } finally {
4362
+ tui.stopThinkingInput();
4363
+ tui.setActiveRunnable(null);
4364
+ }
4365
+ }
4366
+ tui.syncFromLoop(loop);
4367
+ tui.finishAttempt();
4368
+ getAutocompleteCandidates(this.cwd, this.config).then((c) => {
4369
+ this.candidates = c;
4370
+ tui.setCandidates(c);
4371
+ }).catch(() => {
4372
+ });
4373
+ }
4374
+ } finally {
4375
+ process.off("SIGINT", sigintHandler);
4376
+ this.watcher?.close();
4377
+ if (this.watchTimeout) clearTimeout(this.watchTimeout);
4378
+ eventBus.off("model_delta", onModelDelta);
4379
+ eventBus.off("loop_start", onLoopStart);
4380
+ eventBus.off("cost_update", onCostUpdate);
4381
+ eventBus.off("thinking_delta", onThinkingDelta);
4382
+ tui.dispose();
4383
+ this.autocompleteServer?.close();
4384
+ }
4385
+ }
4386
+ makeCompleter() {
4387
+ return (line) => {
4388
+ const candidates = this.candidates;
4389
+ if (!candidates) return [[], ""];
4390
+ if (line.startsWith("/")) {
4391
+ const hits = candidates.commands.filter((c) => c.startsWith(line));
4392
+ return [hits.length ? hits : candidates.commands, line];
4393
+ }
4394
+ const words = line.split(/\s+/);
4395
+ const lastWord = words[words.length - 1] || "";
4396
+ if (!lastWord) {
4397
+ return [[], lastWord];
4398
+ }
4399
+ const fileHits = candidates.files.filter((f) => f.startsWith(lastWord));
4400
+ const symbolHits = candidates.symbols.filter((s) => s.startsWith(lastWord));
4401
+ const allHits = [...fileHits, ...symbolHits];
4402
+ return [allHits, lastWord];
4403
+ };
4404
+ }
4405
+ };
4406
+
4407
+ // src/commands/run.ts
4408
+ function getLocalState(cwd) {
4409
+ const statePath = join6(cwd, ".orbit", "state.json");
4410
+ if (!existsSync6(statePath)) return {};
4411
+ try {
4412
+ return JSON.parse(readFileSync5(statePath, "utf8"));
4413
+ } catch {
4414
+ return {};
4415
+ }
4416
+ }
4417
+ async function runAgent(cwd, task, cliOverrides, multi, options) {
4418
+ if (options?.jsonl) {
4419
+ const originalLog = console.log;
4420
+ console.log = (...args) => {
4421
+ console.error(...args);
4422
+ };
4423
+ eventBus2.on("*", (event) => {
4424
+ originalLog(JSON.stringify(event));
4425
+ });
4426
+ }
4427
+ const config = ConfigLoader3.loadSync(cwd, cliOverrides);
4428
+ if (!cliOverrides || !cliOverrides.model) {
4429
+ const localState = getLocalState(cwd);
4430
+ if (localState.lastModel) {
4431
+ config.models.default = localState.lastModel;
4432
+ }
4433
+ }
4434
+ if (config.models) {
4435
+ if (config.models.default) {
4436
+ config.models.default = config.models.default.replace(/\[1m\]/g, "");
4437
+ }
4438
+ if (config.models.fast) {
4439
+ config.models.fast = config.models.fast.replace(/\[1m\]/g, "");
4440
+ }
4441
+ }
4442
+ const providerName = config.provider.default;
4443
+ const pConfig = config.providers[providerName];
4444
+ if (!pConfig) {
4445
+ console.error(
4446
+ picocolors6.red(
4447
+ `Provider "${providerName}" is not defined in configuration.`
4448
+ )
4449
+ );
4450
+ return;
4451
+ }
4452
+ let providerInstance;
4453
+ if (pConfig.type === "anthropic-compatible") {
4454
+ providerInstance = new DeepSeekAnthropicProvider(
4455
+ pConfig.apiKey,
4456
+ pConfig.baseUrl
4457
+ );
4458
+ } else if (pConfig.type === "openai-compatible") {
4459
+ providerInstance = new DeepSeekOpenAIProvider(
4460
+ pConfig.apiKey,
4461
+ pConfig.baseUrl
4462
+ );
4463
+ } else if (pConfig.type === "openai") {
4464
+ providerInstance = new OpenAIProvider(pConfig.apiKey, pConfig.baseUrl);
4465
+ } else if (pConfig.type === "anthropic") {
4466
+ providerInstance = new AnthropicProvider(pConfig.apiKey, pConfig.baseUrl);
4467
+ } else if (pConfig.type === "ollama") {
4468
+ providerInstance = new OllamaProvider(pConfig.baseUrl);
4469
+ }
4470
+ if (!providerInstance) {
4471
+ console.error(
4472
+ picocolors6.red(`Unsupported provider type "${pConfig.type}".`)
4473
+ );
4474
+ return;
4475
+ }
4476
+ const interaction = options?.nonInteractive ? {
4477
+ async askApproval(reason, preview) {
4478
+ console.error(`
4479
+ Risk Warning [Non-Interactive Mode]: ${reason}`);
4480
+ if (preview) {
4481
+ console.error(picocolors6.gray(`Parameters: ${preview}`));
4482
+ }
4483
+ console.error("Automatically denying action in non-interactive mode.");
4484
+ return false;
4485
+ },
4486
+ showText(text) {
4487
+ console.error(text);
4488
+ },
4489
+ async showDiff(filePath, _before, _after) {
4490
+ console.error(`[Diff for ${filePath} shown in non-interactive mode]`);
4491
+ }
4492
+ } : {
4493
+ async askApproval(reason, preview) {
4494
+ console.log(`
4495
+ Risk Warning: ${reason}`);
4496
+ if (preview) {
4497
+ console.log(picocolors6.gray(`Parameters: ${preview}`));
4498
+ }
4499
+ return await Prompt4.askApproval("Confirm action?");
4500
+ },
4501
+ showText(text) {
4502
+ console.log(text);
4503
+ },
4504
+ async showDiff(filePath, before, after) {
4505
+ await pageText(DiffView2.render(filePath, before, after));
4506
+ }
4507
+ };
4508
+ const activeTask = task;
4509
+ if (!activeTask) {
4510
+ const controller = new ReplController(
4511
+ cwd,
4512
+ config,
4513
+ providerInstance,
4514
+ interaction,
4515
+ multi,
4516
+ !!cliOverrides?.direct
4517
+ );
4518
+ await controller.start();
4519
+ return;
4520
+ }
4521
+ if (multi) {
4522
+ const orchestrator = new Orchestrator2(
4523
+ cwd,
4524
+ config,
4525
+ providerInstance,
4526
+ activeTask,
4527
+ interaction
4528
+ );
4529
+ await orchestrator.run();
4530
+ } else {
4531
+ const loop = new AgentLoop2(
4532
+ cwd,
4533
+ config,
4534
+ providerInstance,
4535
+ activeTask,
4536
+ interaction
4537
+ );
4538
+ await loop.run();
4539
+ }
4540
+ }
4541
+
4542
+ // src/commands/LSPServer.ts
4543
+ import { ConfigLoader as ConfigLoader4 } from "@orbit-build/config";
4544
+ import { AutocompleteEngine as AutocompleteEngine2 } from "@orbit-build/core";
4545
+ var JSONRPCReader = class {
4546
+ constructor(onMessage) {
4547
+ this.onMessage = onMessage;
4548
+ }
4549
+ onMessage;
4550
+ buffer = "";
4551
+ feed(chunk) {
4552
+ this.buffer += chunk;
4553
+ while (true) {
4554
+ const headerIndex = this.buffer.indexOf("\r\n\r\n");
4555
+ if (headerIndex === -1) {
4556
+ break;
4557
+ }
4558
+ const headerPart = this.buffer.substring(0, headerIndex);
4559
+ const contentLengthMatch = headerPart.match(/Content-Length:\s*(\d+)/i);
4560
+ if (!contentLengthMatch) {
4561
+ this.buffer = this.buffer.substring(headerIndex + 4);
4562
+ continue;
4563
+ }
4564
+ const contentLength = parseInt(contentLengthMatch[1], 10);
4565
+ const bodyStartIndex = headerIndex + 4;
4566
+ if (this.buffer.length < bodyStartIndex + contentLength) {
4567
+ break;
4568
+ }
4569
+ const bodyPart = this.buffer.substring(
4570
+ bodyStartIndex,
4571
+ bodyStartIndex + contentLength
4572
+ );
4573
+ this.buffer = this.buffer.substring(bodyStartIndex + contentLength);
4574
+ try {
4575
+ const parsed = JSON.parse(bodyPart);
4576
+ this.onMessage(parsed);
4577
+ } catch (err) {
4578
+ console.error(`[LSP Error] Failed to parse JSON body: ${err.message}`);
4579
+ }
4580
+ }
4581
+ }
4582
+ };
4583
+ function sendRPC(msg) {
4584
+ const body = JSON.stringify(msg);
4585
+ process.stdout.write(
4586
+ `Content-Length: ${Buffer.byteLength(body, "utf8")}\r
4587
+ \r
4588
+ ${body}`
4589
+ );
4590
+ }
4591
+ function getPrefixSuffix(text, line, character) {
4592
+ const lines = text.split(/\r?\n/);
4593
+ if (line < 0 || line >= lines.length) {
4594
+ return { prefix: text, suffix: "" };
4595
+ }
4596
+ const beforeLines = lines.slice(0, line);
4597
+ const currentLine = lines[line];
4598
+ const charIdx = Math.min(character, currentLine.length);
4599
+ const beforeInLine = currentLine.substring(0, charIdx);
4600
+ const afterInLine = currentLine.substring(charIdx);
4601
+ const afterLines = lines.slice(line + 1);
4602
+ const prefix = [...beforeLines, beforeInLine].join("\n");
4603
+ const suffix = [afterInLine, ...afterLines].join("\n");
4604
+ return { prefix, suffix };
4605
+ }
4606
+ async function runLSPServer(cwd) {
4607
+ console.error("[LSP] Starting Orbit LSP Server...");
4608
+ const config = ConfigLoader4.loadSync(cwd);
4609
+ const autocompleteEngine = new AutocompleteEngine2();
4610
+ const documentCache = /* @__PURE__ */ new Map();
4611
+ const reader = new JSONRPCReader(async (msg) => {
4612
+ if (!msg.method) return;
4613
+ switch (msg.method) {
4614
+ case "initialize":
4615
+ sendRPC({
4616
+ jsonrpc: "2.0",
4617
+ id: msg.id,
4618
+ result: {
4619
+ capabilities: {
4620
+ textDocumentSync: 1,
4621
+ // Full document sync
4622
+ completionProvider: {
4623
+ resolveProvider: false,
4624
+ triggerCharacters: [".", "(", "{", " ", ":", ","]
4625
+ }
4626
+ }
4627
+ }
4628
+ });
4629
+ break;
4630
+ case "initialized":
4631
+ console.error("[LSP] Orbit Autocomplete Server fully initialized.");
4632
+ break;
4633
+ case "textDocument/didOpen": {
4634
+ const { uri, text } = msg.params.textDocument;
4635
+ documentCache.set(uri, text);
4636
+ break;
4637
+ }
4638
+ case "textDocument/didChange": {
4639
+ const { uri } = msg.params.textDocument;
4640
+ const change = msg.params.contentChanges?.[0];
4641
+ if (change) {
4642
+ documentCache.set(uri, change.text);
4643
+ }
4644
+ break;
4645
+ }
4646
+ case "textDocument/didClose": {
4647
+ const { uri } = msg.params.textDocument;
4648
+ documentCache.delete(uri);
4649
+ break;
4650
+ }
4651
+ case "textDocument/completion": {
4652
+ const { uri } = msg.params.textDocument;
4653
+ const { line, character } = msg.params.position;
4654
+ const docText = documentCache.get(uri);
4655
+ if (!docText) {
4656
+ sendRPC({
4657
+ jsonrpc: "2.0",
4658
+ id: msg.id,
4659
+ result: []
4660
+ });
4661
+ break;
4662
+ }
4663
+ const { prefix, suffix } = getPrefixSuffix(docText, line, character);
4664
+ try {
4665
+ const completion = await autocompleteEngine.autocomplete(
4666
+ prefix,
4667
+ suffix,
4668
+ config,
4669
+ uri
4670
+ );
4671
+ if (completion) {
4672
+ sendRPC({
4673
+ jsonrpc: "2.0",
4674
+ id: msg.id,
4675
+ result: [
4676
+ {
4677
+ label: completion.trim().substring(0, 40) + (completion.trim().length > 40 ? "..." : ""),
4678
+ kind: 15,
4679
+ // Snippet / Text
4680
+ insertText: completion,
4681
+ detail: "Orbit Autocomplete",
4682
+ documentation: {
4683
+ kind: "markdown",
4684
+ value: `\`\`\`typescript
4685
+ ${completion}
4686
+ \`\`\``
4687
+ }
4688
+ }
4689
+ ]
4690
+ });
4691
+ } else {
4692
+ sendRPC({
4693
+ jsonrpc: "2.0",
4694
+ id: msg.id,
4695
+ result: []
4696
+ });
4697
+ }
4698
+ } catch (err) {
4699
+ console.error(`[LSP Autocomplete Error] ${err.message}`);
4700
+ sendRPC({
4701
+ jsonrpc: "2.0",
4702
+ id: msg.id,
4703
+ result: []
4704
+ });
4705
+ }
4706
+ break;
4707
+ }
4708
+ case "shutdown":
4709
+ sendRPC({
4710
+ jsonrpc: "2.0",
4711
+ id: msg.id,
4712
+ result: null
4713
+ });
4714
+ break;
4715
+ case "exit":
4716
+ process.exit(0);
4717
+ break;
4718
+ default:
4719
+ if (msg.id !== void 0) {
4720
+ sendRPC({
4721
+ jsonrpc: "2.0",
4722
+ id: msg.id,
4723
+ error: {
4724
+ code: -32601,
4725
+ message: `Method not found: ${msg.method}`
4726
+ }
4727
+ });
4728
+ }
4729
+ break;
4730
+ }
4731
+ });
4732
+ process.stdin.setEncoding("utf8");
4733
+ process.stdin.on("data", (chunk) => {
4734
+ reader.feed(chunk.toString());
4735
+ });
4736
+ process.stdin.on("end", () => {
4737
+ console.error("[LSP] Connection ended.");
4738
+ process.exit(0);
4739
+ });
4740
+ }
4741
+
4742
+ // src/commands/login.ts
4743
+ import readline2 from "readline";
4744
+ import picocolors7 from "picocolors";
4745
+ import { CredentialsManager } from "@orbit-build/config";
4746
+ var PROVIDERS = {
4747
+ "1": { name: "deepseek-openai", envVar: "DEEPSEEK_API_KEY" },
4748
+ "2": { name: "openai", envVar: "OPENAI_API_KEY" },
4749
+ "3": { name: "anthropic", envVar: "ANTHROPIC_API_KEY" },
4750
+ "4": { name: "deepseek-anthropic", envVar: "ANTHROPIC_AUTH_TOKEN" }
4751
+ };
4752
+ function askQuestion(query) {
4753
+ const rl = readline2.createInterface({
4754
+ input: process.stdin,
4755
+ output: process.stdout
4756
+ });
4757
+ return new Promise((resolve3) => {
4758
+ rl.question(query, (answer) => {
4759
+ rl.close();
4760
+ resolve3(answer.trim());
4761
+ });
4762
+ });
4763
+ }
4764
+ function askSecret(query) {
4765
+ return new Promise((resolve3) => {
4766
+ const rl = readline2.createInterface({
4767
+ input: process.stdin,
4768
+ output: process.stdout
4769
+ });
4770
+ const stdin = process.stdin;
4771
+ const stdout = process.stdout;
4772
+ stdout.write(query);
4773
+ stdin.setRawMode(true);
4774
+ stdin.resume();
4775
+ let input = "";
4776
+ const onData = (char) => {
4777
+ const charStr = char.toString("utf8");
4778
+ switch (charStr) {
4779
+ case "\n":
4780
+ case "\r":
4781
+ case "":
4782
+ stdin.setRawMode(false);
4783
+ stdin.pause();
4784
+ stdin.removeListener("data", onData);
4785
+ stdout.write("\n");
4786
+ rl.close();
4787
+ resolve3(input.trim());
4788
+ break;
4789
+ case "":
4790
+ stdin.setRawMode(false);
4791
+ stdin.pause();
4792
+ stdin.removeListener("data", onData);
4793
+ stdout.write("\n");
4794
+ rl.close();
4795
+ process.exit(130);
4796
+ break;
4797
+ case "\b":
4798
+ case "\x7F":
4799
+ if (input.length > 0) {
4800
+ input = input.slice(0, -1);
4801
+ stdout.write("\r" + query + "*".repeat(input.length) + " ");
4802
+ stdout.write("\r" + query + "*".repeat(input.length));
4803
+ }
4804
+ break;
4805
+ default:
4806
+ if (charStr.charCodeAt(0) >= 32) {
4807
+ input += charStr;
4808
+ stdout.write("*");
4809
+ }
4810
+ break;
4811
+ }
4812
+ };
4813
+ stdin.on("data", onData);
4814
+ });
4815
+ }
4816
+ async function runLogin() {
4817
+ console.log(picocolors7.bold("\n--- Configure Orbit API Keys ---"));
4818
+ console.log("Select an API provider to configure:\n");
4819
+ for (const [key, provider2] of Object.entries(PROVIDERS)) {
4820
+ console.log(` ${picocolors7.cyan(key)}) ${picocolors7.bold(provider2.name)} (saves to ${provider2.envVar})`);
4821
+ }
4822
+ console.log("");
4823
+ const choice = await askQuestion("Enter your choice (1-4): ");
4824
+ const provider = PROVIDERS[choice];
4825
+ if (!provider) {
4826
+ console.log(picocolors7.red("\n\u2716 Invalid choice. Exiting."));
4827
+ return;
4828
+ }
4829
+ console.log(picocolors7.cyan(`
4830
+ Configuring API Key for provider "${picocolors7.bold(provider.name)}"...`));
4831
+ const apiKey = await askSecret("Enter API Key (input will be hidden): ");
4832
+ if (!apiKey) {
4833
+ console.log(picocolors7.red("\n\u2716 API Key cannot be empty. Exiting."));
4834
+ return;
4835
+ }
4836
+ try {
4837
+ const credsManager = new CredentialsManager();
4838
+ credsManager.storeSecret(provider.envVar, apiKey);
4839
+ console.log(picocolors7.green(`
4840
+ \u2714 API Key for "${provider.name}" stored securely!`));
4841
+ } catch (error) {
4842
+ console.log(picocolors7.red(`
4843
+ \u2716 Failed to store API Key securely: ${error.message}`));
4844
+ }
4845
+ }
4846
+
4847
+ // src/index.ts
4848
+ var program = new Command();
4849
+ program.name("orbit").description("Orbit - Local AI Coding Agent Runtime").version("0.1.0").argument("[task]", "task description for Orbit to execute").option("--provider <provider>", "specify model provider").option("--model <model>", "specify model name").option("--yes", "bypass low-risk approvals").option("--multi", "run in multi-agent planning/coding/review mode").option("--direct", "run interactive REPL in direct console streaming mode").action(async (task, options) => {
4850
+ const cwd = process.cwd();
4851
+ const overrides = {};
4852
+ if (options.provider) {
4853
+ overrides.provider = { default: options.provider };
4854
+ }
4855
+ if (options.model) {
4856
+ overrides.models = { default: options.model };
4857
+ }
4858
+ if (options.direct) {
4859
+ overrides.direct = true;
4860
+ }
4861
+ if (options.yes) {
4862
+ overrides.permissions = { mode: "auto" };
4863
+ }
4864
+ await runAgent(cwd, task, overrides, !!options.multi);
4865
+ });
4866
+ program.command("init").description("initialize ORBIT.md guidelines file").action(() => {
4867
+ runInit(process.cwd());
4868
+ });
4869
+ program.command("config").description("show resolved configurations").action(() => {
4870
+ runConfig(process.cwd());
4871
+ });
4872
+ program.command("login").description("interactively configure API keys for models").action(async () => {
4873
+ await runLogin();
4874
+ });
4875
+ program.command("doctor").description("diagnose local environment and API configs").action(() => {
4876
+ runDoctor(process.cwd());
4877
+ });
4878
+ program.command("lsp").description("start the local LSP autocomplete server").action(async () => {
4879
+ await runLSPServer(process.cwd());
4880
+ });
4881
+ program.command("exec").description("run a task in non-interactive mode and stream events as JSONL").argument("<prompt>", "the task prompt to execute").option("--provider <provider>", "specify model provider").option("--model <model>", "specify model name").option("--jsonl", "output event logs in JSONL format").action(async (prompt, options) => {
4882
+ const cwd = process.cwd();
4883
+ const overrides = {};
4884
+ if (options.provider) {
4885
+ overrides.provider = { default: options.provider };
4886
+ }
4887
+ if (options.model) {
4888
+ overrides.models = { default: options.model };
4889
+ }
4890
+ await runAgent(cwd, prompt, overrides, false, {
4891
+ nonInteractive: true,
4892
+ jsonl: !!options.jsonl
4893
+ });
4894
+ });
4895
+ program.parse(process.argv);