@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,231 +0,0 @@
1
- import { ConfigLoader } from "@orbit-build/config";
2
- import { AutocompleteEngine } from "@orbit-build/core";
3
-
4
- class JSONRPCReader {
5
- private buffer = "";
6
-
7
- constructor(private onMessage: (msg: any) => void) {}
8
-
9
- public feed(chunk: string) {
10
- this.buffer += chunk;
11
- while (true) {
12
- const headerIndex = this.buffer.indexOf("\r\n\r\n");
13
- if (headerIndex === -1) {
14
- break;
15
- }
16
-
17
- const headerPart = this.buffer.substring(0, headerIndex);
18
- const contentLengthMatch = headerPart.match(/Content-Length:\s*(\d+)/i);
19
- if (!contentLengthMatch) {
20
- // Invalid header, clear header and continue
21
- this.buffer = this.buffer.substring(headerIndex + 4);
22
- continue;
23
- }
24
-
25
- const contentLength = parseInt(contentLengthMatch[1], 10);
26
- const bodyStartIndex = headerIndex + 4;
27
-
28
- if (this.buffer.length < bodyStartIndex + contentLength) {
29
- // Message body is still incomplete, wait for more data
30
- break;
31
- }
32
-
33
- const bodyPart = this.buffer.substring(
34
- bodyStartIndex,
35
- bodyStartIndex + contentLength,
36
- );
37
- this.buffer = this.buffer.substring(bodyStartIndex + contentLength);
38
-
39
- try {
40
- const parsed = JSON.parse(bodyPart);
41
- this.onMessage(parsed);
42
- } catch (err: any) {
43
- console.error(`[LSP Error] Failed to parse JSON body: ${err.message}`);
44
- }
45
- }
46
- }
47
- }
48
-
49
- function sendRPC(msg: any) {
50
- const body = JSON.stringify(msg);
51
- process.stdout.write(
52
- `Content-Length: ${Buffer.byteLength(body, "utf8")}\r\n\r\n${body}`,
53
- );
54
- }
55
-
56
- function getPrefixSuffix(
57
- text: string,
58
- line: number,
59
- character: number,
60
- ): { prefix: string; suffix: string } {
61
- const lines = text.split(/\r?\n/);
62
- if (line < 0 || line >= lines.length) {
63
- return { prefix: text, suffix: "" };
64
- }
65
-
66
- const beforeLines = lines.slice(0, line);
67
- const currentLine = lines[line];
68
- const charIdx = Math.min(character, currentLine.length);
69
-
70
- const beforeInLine = currentLine.substring(0, charIdx);
71
- const afterInLine = currentLine.substring(charIdx);
72
-
73
- const afterLines = lines.slice(line + 1);
74
-
75
- const prefix = [...beforeLines, beforeInLine].join("\n");
76
- const suffix = [afterInLine, ...afterLines].join("\n");
77
-
78
- return { prefix, suffix };
79
- }
80
-
81
- export async function runLSPServer(cwd: string): Promise<void> {
82
- console.error("[LSP] Starting Orbit LSP Server...");
83
-
84
- const config = ConfigLoader.loadSync(cwd);
85
- const autocompleteEngine = new AutocompleteEngine();
86
- const documentCache = new Map<string, string>();
87
-
88
- const reader = new JSONRPCReader(async (msg) => {
89
- if (!msg.method) return;
90
-
91
- switch (msg.method) {
92
- case "initialize":
93
- sendRPC({
94
- jsonrpc: "2.0",
95
- id: msg.id,
96
- result: {
97
- capabilities: {
98
- textDocumentSync: 1, // Full document sync
99
- completionProvider: {
100
- resolveProvider: false,
101
- triggerCharacters: [".", "(", "{", " ", ":", ","],
102
- },
103
- },
104
- },
105
- });
106
- break;
107
-
108
- case "initialized":
109
- console.error("[LSP] Orbit Autocomplete Server fully initialized.");
110
- break;
111
-
112
- case "textDocument/didOpen": {
113
- const { uri, text } = msg.params.textDocument;
114
- documentCache.set(uri, text);
115
- break;
116
- }
117
-
118
- case "textDocument/didChange": {
119
- const { uri } = msg.params.textDocument;
120
- const change = msg.params.contentChanges?.[0];
121
- if (change) {
122
- documentCache.set(uri, change.text);
123
- }
124
- break;
125
- }
126
-
127
- case "textDocument/didClose": {
128
- const { uri } = msg.params.textDocument;
129
- documentCache.delete(uri);
130
- break;
131
- }
132
-
133
- case "textDocument/completion": {
134
- const { uri } = msg.params.textDocument;
135
- const { line, character } = msg.params.position;
136
-
137
- const docText = documentCache.get(uri);
138
- if (!docText) {
139
- sendRPC({
140
- jsonrpc: "2.0",
141
- id: msg.id,
142
- result: [],
143
- });
144
- break;
145
- }
146
-
147
- const { prefix, suffix } = getPrefixSuffix(docText, line, character);
148
-
149
- try {
150
- const completion = await autocompleteEngine.autocomplete(
151
- prefix,
152
- suffix,
153
- config,
154
- uri,
155
- );
156
-
157
- if (completion) {
158
- sendRPC({
159
- jsonrpc: "2.0",
160
- id: msg.id,
161
- result: [
162
- {
163
- label:
164
- completion.trim().substring(0, 40) +
165
- (completion.trim().length > 40 ? "..." : ""),
166
- kind: 15, // Snippet / Text
167
- insertText: completion,
168
- detail: "Orbit Autocomplete",
169
- documentation: {
170
- kind: "markdown",
171
- value: `\`\`\`typescript\n${completion}\n\`\`\``,
172
- },
173
- },
174
- ],
175
- });
176
- } else {
177
- sendRPC({
178
- jsonrpc: "2.0",
179
- id: msg.id,
180
- result: [],
181
- });
182
- }
183
- } catch (err: any) {
184
- console.error(`[LSP Autocomplete Error] ${err.message}`);
185
- sendRPC({
186
- jsonrpc: "2.0",
187
- id: msg.id,
188
- result: [],
189
- });
190
- }
191
- break;
192
- }
193
-
194
- case "shutdown":
195
- sendRPC({
196
- jsonrpc: "2.0",
197
- id: msg.id,
198
- result: null,
199
- });
200
- break;
201
-
202
- case "exit":
203
- process.exit(0);
204
- break;
205
-
206
- default:
207
- // Respond with method not found for standard requests
208
- if (msg.id !== undefined) {
209
- sendRPC({
210
- jsonrpc: "2.0",
211
- id: msg.id,
212
- error: {
213
- code: -32601,
214
- message: `Method not found: ${msg.method}`,
215
- },
216
- });
217
- }
218
- break;
219
- }
220
- });
221
-
222
- process.stdin.setEncoding("utf8");
223
- process.stdin.on("data", (chunk) => {
224
- reader.feed(chunk.toString());
225
- });
226
-
227
- process.stdin.on("end", () => {
228
- console.error("[LSP] Connection ended.");
229
- process.exit(0);
230
- });
231
- }
@@ -1,8 +0,0 @@
1
- import { ConfigLoader } from "@orbit-build/config";
2
- import picocolors from "picocolors";
3
-
4
- export function runConfig(cwd: string): void {
5
- const config = ConfigLoader.loadSync(cwd);
6
- console.log(picocolors.bold("\nResolved Orbit Configuration:\n"));
7
- console.log(JSON.stringify(config, null, 2));
8
- }
@@ -1,62 +0,0 @@
1
- import { existsSync, mkdirSync, rmSync, writeFileSync } from "fs";
2
- import { join } from "path";
3
- import { tmpdir } from "os";
4
- import { afterEach, beforeEach, describe, expect, it } from "vitest";
5
- import { expandCustomCommand, loadCustomCommands } from "./customCommands.js";
6
-
7
- describe("custom slash commands", () => {
8
- let cwd: string;
9
-
10
- beforeEach(() => {
11
- cwd = join(tmpdir(), `orbit-custom-command-${Date.now()}`);
12
- mkdirSync(join(cwd, ".orbit", "commands"), { recursive: true });
13
- });
14
-
15
- afterEach(() => {
16
- if (existsSync(cwd)) rmSync(cwd, { recursive: true, force: true });
17
- });
18
-
19
- it("loads project commands with validated frontmatter", () => {
20
- writeFileSync(
21
- join(cwd, ".orbit", "commands", "review.md"),
22
- [
23
- "---",
24
- "description: Review a target for correctness",
25
- "argumentHint: <path>",
26
- "---",
27
- "Review $ARGUMENTS and report actionable findings.",
28
- ].join("\n"),
29
- "utf8",
30
- );
31
-
32
- const commands = loadCustomCommands(cwd);
33
- expect(commands).toHaveLength(1);
34
- expect(commands[0]).toMatchObject({
35
- name: "review",
36
- description: "Review a target for correctness",
37
- source: "project",
38
- });
39
- });
40
-
41
- it("does not allow custom commands to shadow reserved built-ins", () => {
42
- writeFileSync(
43
- join(cwd, ".orbit", "commands", "help.md"),
44
- "Ignore the built-in help.",
45
- "utf8",
46
- );
47
- expect(loadCustomCommands(cwd, ["help"])).toHaveLength(0);
48
- });
49
-
50
- it("expands aggregate and positional arguments", () => {
51
- const command = {
52
- name: "migrate",
53
- description: "Migrate code",
54
- template: "Move $1 to $2.\nScope: $ARGUMENTS",
55
- source: "project" as const,
56
- filePath: "migrate.md",
57
- };
58
- expect(expandCustomCommand(command, "old-api new-api")).toBe(
59
- "Move old-api to new-api.\nScope: old-api new-api",
60
- );
61
- });
62
- });
@@ -1,127 +0,0 @@
1
- import { existsSync, readFileSync, readdirSync } from "fs";
2
- import { basename, extname, join } from "path";
3
- import { homedir } from "os";
4
- import { parse } from "yaml";
5
- import { z } from "zod";
6
-
7
- const CommandMetadataSchema = z.object({
8
- description: z.string().max(240).optional(),
9
- argumentHint: z.string().max(120).optional(),
10
- });
11
-
12
- export interface CustomCommand {
13
- name: string;
14
- description: string;
15
- argumentHint?: string;
16
- template: string;
17
- source: "user" | "project";
18
- filePath: string;
19
- }
20
-
21
- const VALID_COMMAND_NAME = /^[a-z0-9][a-z0-9-_]{0,47}$/i;
22
- const MAX_COMMAND_FILE_BYTES = 256 * 1024;
23
-
24
- function parseCommandFile(
25
- filePath: string,
26
- source: CustomCommand["source"],
27
- ): CustomCommand | null {
28
- const commandName = basename(filePath, extname(filePath));
29
- if (!VALID_COMMAND_NAME.test(commandName)) return null;
30
-
31
- const raw = readFileSync(filePath, "utf8");
32
- if (Buffer.byteLength(raw, "utf8") > MAX_COMMAND_FILE_BYTES) return null;
33
-
34
- let metadata: z.infer<typeof CommandMetadataSchema> = {};
35
- let template = raw.trim();
36
- const frontmatter = raw.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);
37
- if (frontmatter) {
38
- const parsed = CommandMetadataSchema.safeParse(parse(frontmatter[1]) || {});
39
- if (!parsed.success) return null;
40
- metadata = parsed.data;
41
- template = frontmatter[2].trim();
42
- }
43
- if (!template) return null;
44
-
45
- return {
46
- name: commandName.toLowerCase(),
47
- description:
48
- metadata.description || `Run the ${commandName} prompt workflow`,
49
- argumentHint: metadata.argumentHint,
50
- template,
51
- source,
52
- filePath,
53
- };
54
- }
55
-
56
- function loadDirectory(
57
- directory: string,
58
- source: CustomCommand["source"],
59
- ): CustomCommand[] {
60
- if (!existsSync(directory)) return [];
61
- const commands: CustomCommand[] = [];
62
- for (const entry of readdirSync(directory, { withFileTypes: true })) {
63
- if (!entry.isFile() || extname(entry.name).toLowerCase() !== ".md") {
64
- continue;
65
- }
66
- try {
67
- const command = parseCommandFile(join(directory, entry.name), source);
68
- if (command) commands.push(command);
69
- } catch {
70
- // A malformed optional command should not prevent Orbit from starting.
71
- }
72
- }
73
- return commands;
74
- }
75
-
76
- export function loadCustomCommands(
77
- cwd: string,
78
- reservedNames: Iterable<string> = [],
79
- ): CustomCommand[] {
80
- const reserved = new Set(
81
- Array.from(reservedNames, (name) => name.replace(/^\//, "").toLowerCase()),
82
- );
83
- const merged = new Map<string, CustomCommand>();
84
-
85
- for (const command of loadDirectory(
86
- join(homedir(), ".orbit", "commands"),
87
- "user",
88
- )) {
89
- if (!reserved.has(command.name)) merged.set(command.name, command);
90
- }
91
- for (const command of loadDirectory(
92
- join(cwd, ".orbit", "commands"),
93
- "project",
94
- )) {
95
- if (!reserved.has(command.name)) merged.set(command.name, command);
96
- }
97
-
98
- return Array.from(merged.values()).sort((a, b) =>
99
- a.name.localeCompare(b.name),
100
- );
101
- }
102
-
103
- export function expandCustomCommand(
104
- command: CustomCommand,
105
- rawArguments: string,
106
- ): string {
107
- const args = rawArguments.trim();
108
- const positional = args ? args.split(/\s+/) : [];
109
- let expanded = command.template
110
- .replace(/\$ARGUMENTS\b/g, args)
111
- .replace(/\{\{\s*args\s*\}\}/gi, args);
112
-
113
- for (let index = 1; index <= 9; index++) {
114
- expanded = expanded.replace(
115
- new RegExp(`\\$${index}\\b`, "g"),
116
- positional[index - 1] || "",
117
- );
118
- }
119
-
120
- if (
121
- args &&
122
- !/\$ARGUMENTS\b|\{\{\s*args\s*\}\}|\$[1-9]\b/i.test(command.template)
123
- ) {
124
- expanded += `\n\nAdditional user arguments:\n${args}`;
125
- }
126
- return expanded.trim();
127
- }
@@ -1,63 +0,0 @@
1
- import { execSync } from "child_process";
2
- import picocolors from "picocolors";
3
- import { ConfigLoader } from "@orbit-build/config";
4
-
5
- export function runDoctor(cwd: string): void {
6
- console.log(picocolors.bold("\nOrbit Environment Diagnostics:\n"));
7
-
8
- const nodeVersion = process.version;
9
- const major = parseInt(nodeVersion.replace("v", "").split(".")[0], 10);
10
- if (major >= 20) {
11
- console.log(
12
- picocolors.green(`✔ Node.js version: ${nodeVersion} (Supported)`),
13
- );
14
- } else {
15
- console.log(
16
- picocolors.red(
17
- `✖ Node.js version: ${nodeVersion} (Requires Node.js 20+)`,
18
- ),
19
- );
20
- }
21
-
22
- try {
23
- const gitVersion = execSync("git --version", { encoding: "utf8" }).trim();
24
- console.log(picocolors.green(`✔ Git: ${gitVersion}`));
25
- } catch {
26
- console.log(
27
- picocolors.yellow(
28
- `⚠ Git: Not detected in environment path. Sandbox rollbacks will use filesystem backups.`,
29
- ),
30
- );
31
- }
32
-
33
- try {
34
- const rgVersion = execSync("rg --version", { encoding: "utf8" })
35
- .trim()
36
- .split("\n")[0];
37
- console.log(picocolors.green(`✔ Ripgrep (rg): ${rgVersion}`));
38
- } catch {
39
- console.log(
40
- picocolors.yellow(
41
- `⚠ Ripgrep (rg): Not detected. Code searches will use Node-based stream scanning.`,
42
- ),
43
- );
44
- }
45
-
46
- const config = ConfigLoader.loadSync(cwd);
47
- const defaultProvider = config.provider.default;
48
- const providerDetails = config.providers[defaultProvider];
49
-
50
- if (providerDetails?.apiKey) {
51
- console.log(
52
- picocolors.green(
53
- `✔ API Key: Loaded for default provider "${defaultProvider}"`,
54
- ),
55
- );
56
- } else {
57
- console.log(
58
- picocolors.red(
59
- `✖ API Key: Missing for default provider "${defaultProvider}". Configure ${providerDetails?.apiKeyEnv || "API keyenv"}`,
60
- ),
61
- );
62
- }
63
- }
@@ -1,112 +0,0 @@
1
- import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
2
- import { runAgent } from "./run.js";
3
- import { eventBus } from "@orbit-build/core";
4
- import { ConfigLoader } from "@orbit-build/config";
5
- import fs from "fs";
6
- import path from "path";
7
- import { tmpdir } from "os";
8
-
9
- // Mock AgentLoop to avoid actual provider calls
10
- vi.mock("@orbit-build/core", async () => {
11
- const actual = await vi.importActual<typeof import("@orbit-build/core")>("@orbit-build/core");
12
-
13
- class MockAgentLoop {
14
- constructor(
15
- private cwd: string,
16
- private config: any,
17
- private provider: any,
18
- private task: string,
19
- private interaction: any
20
- ) {}
21
-
22
- async run() {
23
- // Simulate calling interaction.askApproval to test non-interactive auto-deny
24
- const approved = await this.interaction.askApproval("Should write file?", "some-args");
25
- this.interaction.showText(`Approved: ${approved}`);
26
-
27
- // Simulate emitting an event
28
- eventBus.emitEvent("info", { message: "Test info message" });
29
- }
30
- }
31
-
32
- return {
33
- ...actual,
34
- AgentLoop: MockAgentLoop,
35
- };
36
- });
37
-
38
- describe("non-interactive orbit exec tests", () => {
39
- let cwd: string;
40
-
41
- beforeEach(() => {
42
- cwd = path.join(tmpdir(), `orbit-exec-test-${Date.now()}`);
43
- fs.mkdirSync(cwd, { recursive: true });
44
-
45
- vi.spyOn(ConfigLoader, "loadSync").mockReturnValue({
46
- name: "test",
47
- provider: { default: "test-provider" },
48
- models: { default: "test-model" },
49
- providers: { "test-provider": { type: "openai", apiKey: "test-key" } },
50
- permissions: { mode: "interactive" },
51
- tools: { bash: { enabled: false }, webSearch: { enabled: false }, mcp: { enabled: false } },
52
- mcpServers: {},
53
- hooks: {},
54
- session: { store: "jsonl" },
55
- } as any);
56
- });
57
-
58
- afterEach(() => {
59
- vi.restoreAllMocks();
60
- if (fs.existsSync(cwd)) {
61
- fs.rmSync(cwd, { recursive: true, force: true });
62
- }
63
- });
64
-
65
- it("should auto-deny approvals and write to stderr in non-interactive mode", async () => {
66
- const consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
67
-
68
- await runAgent(cwd, "test task", {}, false, { nonInteractive: true });
69
-
70
- // Expect showText and askApproval logs to go to stderr
71
- expect(consoleErrorSpy).toHaveBeenCalled();
72
- const calls = consoleErrorSpy.mock.calls.map(c => c.join(" "));
73
- expect(calls.some(c => c.includes("Automatically denying action"))).toBe(true);
74
- expect(calls.some(c => c.includes("Approved: false"))).toBe(true);
75
- });
76
-
77
- it("should stream events as JSONL to stdout in jsonl mode", async () => {
78
- const logOutput: string[] = [];
79
- const origLog = console.log;
80
- const origError = console.error;
81
-
82
- // We capture stdout log calls
83
- console.log = (msg: string) => {
84
- logOutput.push(msg);
85
- };
86
- console.error = () => {};
87
-
88
- try {
89
- await runAgent(cwd, "test task", {}, false, {
90
- nonInteractive: true,
91
- jsonl: true,
92
- });
93
- } finally {
94
- console.log = origLog;
95
- console.error = origError;
96
- }
97
-
98
- // Check if the JSONL event was printed to stdout
99
- expect(logOutput.length).toBeGreaterThan(0);
100
- const parsedEvents = logOutput.map(line => {
101
- try {
102
- return JSON.parse(line);
103
- } catch {
104
- return null;
105
- }
106
- });
107
-
108
- const infoEvent = parsedEvents.find(e => e && e.type === "info");
109
- expect(infoEvent).toBeDefined();
110
- expect(infoEvent.payload.message).toBe("Test info message");
111
- });
112
- });
@@ -1,26 +0,0 @@
1
- import { writeFileSync, existsSync } from "fs";
2
- import { join } from "path";
3
- import picocolors from "picocolors";
4
-
5
- export function runInit(cwd: string): void {
6
- const target = join(cwd, "ORBIT.md");
7
- if (existsSync(target)) {
8
- console.log(picocolors.yellow(`ORBIT.md already exists in ${cwd}.`));
9
- return;
10
- }
11
-
12
- const content = `# Orbit Project Guidelines
13
-
14
- This file contains custom developer instructions and rules for the Orbit AI Coding Agent.
15
-
16
- ## Code Standards
17
- - Keep modifications minimal and precise.
18
- - Preserves existing formatting conventions and docstrings.
19
- - Always verify changes by running appropriate test suites.
20
- `;
21
-
22
- writeFileSync(target, content, "utf8");
23
- console.log(
24
- picocolors.green(`Successfully initialized ORBIT.md at ${target}`),
25
- );
26
- }