@orbit-build/cli 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,36 +0,0 @@
1
- import { describe, it, expect, vi } from "vitest";
2
- import { ReplController } from "./ReplController.js";
3
-
4
- describe("ReplController Instantiation and Completer Tests", () => {
5
- const mockConfig = {
6
- language: "en",
7
- permissions: { mode: "strict" },
8
- models: { default: "gpt-4", planner: "planner-model", coder: "coder-model", reviewer: "reviewer-model", fast: "fast-model" },
9
- autocomplete: { enabled: false },
10
- session: { store: "jsonl", path: ".orbit/test-sessions" },
11
- };
12
-
13
- const mockProvider = {
14
- id: "openai",
15
- chat: vi.fn(),
16
- };
17
-
18
- const mockInteraction = {
19
- askApproval: vi.fn(),
20
- showText: vi.fn(),
21
- showDiff: vi.fn(),
22
- };
23
-
24
- it("should instantiate ReplController successfully", () => {
25
- const controller = new ReplController(
26
- process.cwd(),
27
- mockConfig,
28
- mockProvider,
29
- mockInteraction as any,
30
- false,
31
- true
32
- );
33
- expect(controller).toBeDefined();
34
- expect(controller.start).toBeDefined();
35
- });
36
- });
@@ -1,539 +0,0 @@
1
- import {
2
- AgentLoop,
3
- UserInteraction,
4
- Orchestrator,
5
- eventBus,
6
- AutocompleteEngine,
7
- } from "@orbit-build/core";
8
- import { Prompt, Renderer } from "@orbit-build/tui";
9
- import picocolors from "picocolors";
10
- import { existsSync, readFileSync, writeFileSync, mkdirSync, watch } from "fs";
11
- import { join, dirname, resolve } from "path";
12
- import { homedir } from "os";
13
- import http from "http";
14
- import { SymbolIndexer } from "@orbit-build/context-engine";
15
- import { FullscreenTui, pageText } from "../tui/FullscreenTui.js";
16
- import { CommandRouter, getAutocompleteCandidates } from "./CommandRouter.js";
17
-
18
- interface LocalState {
19
- lastSessionId?: string;
20
- lastModel?: string;
21
- }
22
-
23
- export class ReplController {
24
- private currentTui: FullscreenTui | null = null;
25
- private watchTimeout: NodeJS.Timeout | null = null;
26
- private watcher: any = null;
27
- private candidates: any = null;
28
- private autocompleteServer: http.Server | null = null;
29
-
30
- constructor(
31
- private cwd: string,
32
- private config: any,
33
- private providerInstance: any,
34
- private interaction: UserInteraction,
35
- private multi?: boolean,
36
- private direct?: boolean
37
- ) {}
38
-
39
- private getLocalState(): LocalState {
40
- const statePath = join(this.cwd, ".orbit", "state.json");
41
- if (!existsSync(statePath)) return {};
42
- try {
43
- return JSON.parse(readFileSync(statePath, "utf8"));
44
- } catch {
45
- return {};
46
- }
47
- }
48
-
49
- private saveLocalState(state: LocalState): void {
50
- const statePath = join(this.cwd, ".orbit", "state.json");
51
- try {
52
- const dir = dirname(statePath);
53
- if (!existsSync(dir)) {
54
- mkdirSync(dir, { recursive: true });
55
- }
56
- const current = this.getLocalState();
57
- const updated = { ...current, ...state };
58
- writeFileSync(statePath, JSON.stringify(updated, null, 2), "utf8");
59
- } catch {}
60
- }
61
-
62
- private startAutocompleteServer() {
63
- const engine = new AutocompleteEngine();
64
- const server = http.createServer(async (req, res) => {
65
- res.setHeader("Access-Control-Allow-Origin", "*");
66
- res.setHeader("Access-Control-Allow-Methods", "POST, OPTIONS");
67
- res.setHeader("Access-Control-Allow-Headers", "Content-Type");
68
-
69
- if (req.method === "OPTIONS") {
70
- res.writeHead(200);
71
- res.end();
72
- return;
73
- }
74
-
75
- if (req.method === "POST" && req.url === "/autocomplete") {
76
- let body = "";
77
- req.on("data", (chunk) => {
78
- body += chunk;
79
- });
80
- req.on("end", async () => {
81
- try {
82
- const parsed = JSON.parse(body);
83
- const prefix = parsed.prefix || "";
84
- const suffix = parsed.suffix || "";
85
- const completion = await engine.autocomplete(prefix, suffix, this.config);
86
- res.writeHead(200, { "Content-Type": "application/json" });
87
- res.end(JSON.stringify({ completion }));
88
- } catch (e: any) {
89
- res.writeHead(400, { "Content-Type": "application/json" });
90
- res.end(JSON.stringify({ error: e.message }));
91
- }
92
- });
93
- } else {
94
- res.writeHead(404);
95
- res.end();
96
- }
97
- });
98
-
99
- let currentPort = 6018;
100
- server.once("listening", () => {
101
- eventBus.emitEvent("info", {
102
- message: `Autocomplete bridge server running on http://127.0.0.1:${currentPort}`,
103
- });
104
- });
105
- server.on("error", (err: any) => {
106
- if (err.code === "EADDRINUSE") {
107
- currentPort++;
108
- server.listen(currentPort, "127.0.0.1");
109
- }
110
- });
111
- server.listen(currentPort, "127.0.0.1");
112
- return server;
113
- }
114
-
115
- public async start(): Promise<void> {
116
- const version = "v0.1.0";
117
- const sigintHandler = () => {
118
- // Prevent process exit on Ctrl+C during agent execution or REPL waiting.
119
- };
120
- process.on("SIGINT", sigintHandler);
121
-
122
- const isTTY =
123
- process.stdin.isTTY && typeof process.stdin.setRawMode === "function";
124
- const useFullscreenTui = isTTY && !this.direct;
125
- this.autocompleteServer = this.config.autocomplete?.enabled
126
- ? this.startAutocompleteServer()
127
- : null;
128
-
129
- const tui = new FullscreenTui(this.cwd, this.config.models.default, version, this.config);
130
- this.currentTui = tui;
131
- tui.setPermissionsMode(this.config.permissions.mode);
132
-
133
- const tuiInteraction: UserInteraction = {
134
- askApproval: async (reason: string, preview?: string): Promise<boolean> => {
135
- const wasActive = useFullscreenTui && tui.isActive;
136
- if (wasActive) tui.stop();
137
-
138
- console.log(`\nRisk Warning: ${reason}`);
139
- if (preview) {
140
- console.log(picocolors.gray(`Parameters: ${preview}`));
141
- }
142
- const approved = await Prompt.askApproval("Confirm action?");
143
-
144
- if (wasActive) tui.start(this.config.budgetLimit);
145
- return approved;
146
- },
147
- showText(text: string): void {
148
- if (useFullscreenTui && tui.isActive) {
149
- tui.addLog(text);
150
- } else {
151
- console.log(text);
152
- }
153
- },
154
- showDiff: async (
155
- filePath: string,
156
- before: string | null,
157
- after: string,
158
- ): Promise<void> => {
159
- const wasActive = useFullscreenTui && tui.isActive;
160
- if (wasActive) tui.stop();
161
-
162
- await pageText(DiffView.render(filePath, before, after));
163
-
164
- if (wasActive) tui.start(this.config.budgetLimit);
165
- },
166
- };
167
-
168
- const localState = this.getLocalState();
169
- let resumeSessionId: string | undefined;
170
- if (localState.lastSessionId) {
171
- const resume = await Prompt.askApproval(
172
- `Found previous session (${localState.lastSessionId}). Resume last session?`,
173
- );
174
- if (resume) {
175
- resumeSessionId = localState.lastSessionId;
176
- }
177
- }
178
-
179
- const loop = new AgentLoop(
180
- this.cwd,
181
- this.config,
182
- this.providerInstance,
183
- "REPL Interactive Shell Started",
184
- tuiInteraction,
185
- {
186
- disableStatusBar: useFullscreenTui,
187
- sessionId: resumeSessionId,
188
- },
189
- );
190
-
191
- this.saveLocalState({
192
- lastSessionId: loop.getSessionId(),
193
- lastModel: loop.getModelOverride() || this.config.models.default,
194
- });
195
-
196
- if (resumeSessionId && useFullscreenTui) {
197
- tui.loadHistory(loop.getHistory());
198
- }
199
-
200
- tui.setModelNameGetter(
201
- () => loop.getModelOverride() || this.config.models.default,
202
- );
203
-
204
- // Load autocomplete candidates
205
- this.candidates = await getAutocompleteCandidates(this.cwd, this.config);
206
- tui.setCandidates(this.candidates);
207
-
208
- const onModelDelta = (payload: any) => {
209
- if (useFullscreenTui) {
210
- tui.handleModelDelta(payload.text);
211
- } else {
212
- process.stdout.write(payload.text);
213
- }
214
- };
215
- const onLoopStart = (payload: any) => {
216
- if (useFullscreenTui) {
217
- tui.startAttempt(payload.attempt);
218
- }
219
- };
220
- const onCostUpdate = (payload: any) => {
221
- if (useFullscreenTui) {
222
- tui.setCost(
223
- payload.sessionCost,
224
- payload.totalInputTokens,
225
- payload.totalCacheReadTokens,
226
- payload.totalOutputTokens,
227
- );
228
- }
229
- };
230
- const onThinkingDelta = (payload: any) => {
231
- if (useFullscreenTui) {
232
- tui.handleThinkingDelta(payload.text);
233
- } else {
234
- process.stdout.write(picocolors.gray(payload.text));
235
- }
236
- };
237
-
238
- eventBus.on("model_delta", onModelDelta);
239
- eventBus.on("loop_start", onLoopStart);
240
- eventBus.on("cost_update", onCostUpdate);
241
- eventBus.on("thinking_delta", onThinkingDelta);
242
-
243
- // Start background file watcher (Dynamic Incremental Watcher with Config Ignores)
244
- const ignorePatterns = this.config.context?.ignore || [];
245
- const ignoreRegexes = ignorePatterns.map((pattern: string) => {
246
- const escaped = pattern
247
- .replace(/[.+^${}()|[\]\\]/g, "\\$&")
248
- .replace(/\*\*/g, ".*")
249
- .replace(/\*/g, "[^/]*");
250
- const finalPattern = escaped.endsWith(".*")
251
- ? "^" + escaped + "$"
252
- : "(^" + escaped + "$|^" + escaped + "\/.*)";
253
- return new RegExp(finalPattern);
254
- });
255
-
256
- const normCwd = resolve(this.cwd).toLowerCase().replace(/\\/g, "/");
257
- const normHome = resolve(homedir()).toLowerCase().replace(/\\/g, "/");
258
- const isHomeOrRoot =
259
- normCwd === normHome ||
260
- normCwd === "/" ||
261
- /^[a-zA-Z]:\/$/.test(normCwd) ||
262
- dirname(normCwd) === normCwd;
263
-
264
- if (!isHomeOrRoot) {
265
- const indexer = new SymbolIndexer(this.cwd);
266
- this.watcher = watch(this.cwd, { recursive: true }, (eventType, filename) => {
267
- if (
268
- filename &&
269
- /\.(ts|tsx|js|jsx)$/.test(filename) &&
270
- !filename.includes(".orbit")
271
- ) {
272
- const normalized = filename.replace(/\\/g, "/");
273
- const isIgnored = ignoreRegexes.some((rx: RegExp) =>
274
- rx.test(normalized),
275
- );
276
- if (isIgnored) return;
277
-
278
- if (this.watchTimeout) clearTimeout(this.watchTimeout);
279
- this.watchTimeout = setTimeout(() => {
280
- indexer.index().catch(() => {});
281
- }, 500); // debounce 500ms
282
- }
283
- });
284
- }
285
-
286
- if (useFullscreenTui) {
287
- tui.start(this.config.budgetLimit);
288
- } else {
289
- Renderer.printHeader(loop.getSessionId(), this.config.models.default, this.cwd);
290
- }
291
-
292
- const commandRouter = new CommandRouter(
293
- this.cwd,
294
- this.config,
295
- this.providerInstance,
296
- (newProvider: any) => {
297
- this.providerInstance = newProvider;
298
- },
299
- loop,
300
- tui,
301
- useFullscreenTui,
302
- () => this.candidates,
303
- (c: any) => {
304
- this.candidates = c;
305
- tui.setCandidates(c);
306
- },
307
- this.getLocalState.bind(this),
308
- this.saveLocalState.bind(this),
309
- tuiInteraction,
310
- this.multi
311
- );
312
-
313
- try {
314
- while (true) {
315
- let input: string | null;
316
- if (useFullscreenTui) {
317
- input = await tui.askInput();
318
- } else {
319
- input = await Prompt.askTextWithAutocomplete(
320
- "Type your task or command...",
321
- this.makeCompleter(),
322
- `${picocolors.bold(picocolors.magenta("orbit"))}${picocolors.gray(" ❯ ")}`,
323
- );
324
- }
325
-
326
- if (input === null) {
327
- if (useFullscreenTui) {
328
- tui.stop();
329
- }
330
- console.log(
331
- picocolors.yellow("Exiting Orbit Interactive Shell. Goodbye!"),
332
- );
333
- break;
334
- }
335
- if (!input) continue;
336
-
337
- const trimmed = input.trim();
338
- if (!trimmed) continue;
339
-
340
- const routeResult = await commandRouter.route(trimmed);
341
- if (routeResult.shouldExit) {
342
- break;
343
- }
344
- if (routeResult.processed) {
345
- continue;
346
- }
347
-
348
- const state = (loop as any).state;
349
- state.task = trimmed;
350
- state.done = false;
351
- state.attemptCount = 0;
352
-
353
- state.history.push({
354
- id: `msg_user_${Date.now()}`,
355
- role: "user",
356
- createdAt: new Date().toISOString(),
357
- content: [{ type: "text", text: trimmed }],
358
- });
359
-
360
- // Auto-generate session title if it's the default title
361
- const activeSession = loop.sessionManager.getActiveSession();
362
- if (
363
- activeSession &&
364
- (activeSession.title === "New Orbit Session" || !activeSession.title)
365
- ) {
366
- const fastModel = this.config.models.fast || this.config.models.default;
367
- const firstPrompt = trimmed;
368
- Promise.resolve().then(async () => {
369
- try {
370
- const stream = this.providerInstance.chat({
371
- model: fastModel,
372
- messages: [
373
- {
374
- id: `msg_title_gen_${Date.now()}`,
375
- role: "user",
376
- createdAt: new Date().toISOString(),
377
- content: [
378
- {
379
- type: "text",
380
- 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:\n\n${firstPrompt.substring(0, 1000)}`,
381
- },
382
- ],
383
- },
384
- ],
385
- tools: [],
386
- });
387
- let title = "";
388
- for await (const event of stream) {
389
- if (event.type === "text_delta") {
390
- title += event.text;
391
- }
392
- }
393
- const finalTitle = title.trim().replace(/^["']|["']$/g, "");
394
- if (
395
- finalTitle &&
396
- activeSession.id === loop.sessionManager.getActiveSession()?.id
397
- ) {
398
- activeSession.title = finalTitle;
399
- loop.sessionManager
400
- .getSessionStore()
401
- .updateSession(activeSession);
402
- }
403
- } catch {
404
- // Ignore background title generation errors
405
- }
406
- });
407
- }
408
-
409
- let orchestratorInstance: Orchestrator | null = null;
410
- if (this.multi) {
411
- orchestratorInstance = new Orchestrator(
412
- this.cwd,
413
- this.config,
414
- this.providerInstance,
415
- trimmed,
416
- tuiInteraction,
417
- );
418
- tui.setActiveRunnable(orchestratorInstance);
419
- } else {
420
- tui.setActiveRunnable(loop);
421
- }
422
-
423
- tui.startThinkingInput();
424
-
425
- try {
426
- if (orchestratorInstance) {
427
- await orchestratorInstance.run();
428
- } else {
429
- await loop.run();
430
- }
431
- } catch {
432
- // Fallback
433
- } finally {
434
- tui.stopThinkingInput();
435
- tui.setActiveRunnable(null);
436
- }
437
-
438
- // If a guided correction was entered during execution, loop to append and rerun
439
- while (tui.pendingGuidedStatement) {
440
- const guidedTask = tui.pendingGuidedStatement;
441
- tui.pendingGuidedStatement = null;
442
-
443
- const isZh = this.config.language === "zh";
444
- tuiInteraction.showText(
445
- isZh
446
- ? `\n● 收到引导指令。正在重新规划思考...`
447
- : `\n● Guided instruction received. Replanning execution...`,
448
- );
449
-
450
- state.task = guidedTask;
451
- state.done = false;
452
- state.attemptCount = 0;
453
- state.history.push({
454
- id: `msg_user_${Date.now()}`,
455
- role: "user",
456
- createdAt: new Date().toISOString(),
457
- content: [{ type: "text", text: guidedTask }],
458
- });
459
-
460
- tui.syncFromLoop(loop);
461
-
462
- let subOrchestrator: Orchestrator | null = null;
463
- if (this.multi) {
464
- subOrchestrator = new Orchestrator(
465
- this.cwd,
466
- this.config,
467
- this.providerInstance,
468
- guidedTask,
469
- tuiInteraction,
470
- );
471
- tui.setActiveRunnable(subOrchestrator);
472
- } else {
473
- tui.setActiveRunnable(loop);
474
- }
475
-
476
- tui.startThinkingInput();
477
-
478
- try {
479
- if (subOrchestrator) {
480
- await subOrchestrator.run();
481
- } else {
482
- await loop.run();
483
- }
484
- } catch {
485
- // Fallback
486
- } finally {
487
- tui.stopThinkingInput();
488
- tui.setActiveRunnable(null);
489
- }
490
- }
491
- tui.syncFromLoop(loop);
492
- tui.finishAttempt();
493
-
494
- // Refresh candidates in the background asynchronously
495
- getAutocompleteCandidates(this.cwd, this.config)
496
- .then((c) => {
497
- this.candidates = c;
498
- tui.setCandidates(c);
499
- })
500
- .catch(() => {});
501
- }
502
- } finally {
503
- process.off("SIGINT", sigintHandler);
504
- this.watcher?.close();
505
- if (this.watchTimeout) clearTimeout(this.watchTimeout);
506
- eventBus.off("model_delta", onModelDelta);
507
- eventBus.off("loop_start", onLoopStart);
508
- eventBus.off("cost_update", onCostUpdate);
509
- eventBus.off("thinking_delta", onThinkingDelta);
510
- tui.dispose();
511
- this.autocompleteServer?.close();
512
- }
513
- }
514
-
515
- private makeCompleter() {
516
- return (line: string): [string[], string] => {
517
- const candidates = this.candidates;
518
- if (!candidates) return [[], ""];
519
-
520
- if (line.startsWith("/")) {
521
- const hits = candidates.commands.filter((c: string) => c.startsWith(line));
522
- return [hits.length ? hits : candidates.commands, line];
523
- }
524
-
525
- const words = line.split(/\s+/);
526
- const lastWord = words[words.length - 1] || "";
527
-
528
- if (!lastWord) {
529
- return [[], lastWord];
530
- }
531
-
532
- const fileHits = candidates.files.filter((f: string) => f.startsWith(lastWord));
533
- const symbolHits = candidates.symbols.filter((s: string) => s.startsWith(lastWord));
534
- const allHits = [...fileHits, ...symbolHits];
535
-
536
- return [allHits, lastWord];
537
- };
538
- }
539
- }