codowave 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.
Files changed (3) hide show
  1. package/README.md +53 -0
  2. package/dist/index.js +1166 -0
  3. package/package.json +37 -0
package/README.md ADDED
@@ -0,0 +1,53 @@
1
+ # Codowave CLI
2
+
3
+ AI-powered coding agent for your GitHub repos.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install -g codowave
9
+ ```
10
+
11
+ ## Development
12
+
13
+ ```bash
14
+ # Install dependencies
15
+ pnpm install
16
+
17
+ # Build the CLI
18
+ pnpm --filter codowave build
19
+
20
+ # Run in development mode
21
+ pnpm --filter codowave dev
22
+ ```
23
+
24
+ ## Publishing to npm
25
+
26
+ This package is published to npm using GitHub Actions. The workflow is defined in `.github/workflows/npm-publish.yml`.
27
+
28
+ ### Publishing a new version
29
+
30
+ **Option 1: Push a tag**
31
+ ```bash
32
+ # Create a tag with the version
33
+ git tag cli/v0.1.0
34
+ git push origin cli/v0.1.0
35
+ ```
36
+
37
+ **Option 2: Manual workflow dispatch**
38
+ 1. Go to [Actions > Publish CLI to npm](https://github.com/CodowaveAI/Codowave/actions/workflows/npm-publish.yml)
39
+ 2. Click "Run workflow"
40
+ 3. Enter the version bump (patch, minor, major) or specific version
41
+ 4. Click "Run workflow"
42
+
43
+ ### Required secrets
44
+
45
+ To publish to npm, you need to set up the following secrets in your repository:
46
+
47
+ 1. **NPM_TOKEN**: An npm access token with publish permissions
48
+ - Create at: https://www.npmjs.com/settings/<your-username>/tokens
49
+ - Add to: https://github.com/CodowaveAI/Codowave/settings/secrets/actions
50
+
51
+ ## License
52
+
53
+ MIT
package/dist/index.js ADDED
@@ -0,0 +1,1166 @@
1
+ #!/usr/bin/env node
2
+ #!/usr/bin/env node
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __esm = (fn, res) => function __init() {
6
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
7
+ };
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+
13
+ // src/utils/error.ts
14
+ import pc from "picocolors";
15
+ function getErrorMessage(err) {
16
+ if (err instanceof CodowaveError) {
17
+ return err.getFormattedMessage();
18
+ }
19
+ if (err instanceof Error) {
20
+ const message = err.message;
21
+ if (message.includes("ECONNREFUSED") || message.includes("ENOTFOUND")) {
22
+ return `Unable to connect to the Codowave API. Please check your internet connection and try again.`;
23
+ }
24
+ if (message.includes("401") || message.includes("unauthorized")) {
25
+ return `Authentication failed. Please run 'codowave init' to re-authenticate.`;
26
+ }
27
+ if (message.includes("403") || message.includes("forbidden")) {
28
+ return `Access denied. You don't have permission to perform this action.`;
29
+ }
30
+ if (message.includes("404") || message.includes("not found")) {
31
+ return `The requested resource was not found. Please check the repository or issue number and try again.`;
32
+ }
33
+ if (message.includes("rate limit")) {
34
+ return `Rate limit exceeded. Please wait a moment and try again.`;
35
+ }
36
+ return message;
37
+ }
38
+ return String(err);
39
+ }
40
+ function handleError(err, context) {
41
+ const message = getErrorMessage(err);
42
+ const prefix = context ? `[${context}] ` : "";
43
+ console.error(`
44
+ ${pc.red("\u2716")} ${prefix}${message}
45
+ `);
46
+ if (err instanceof CodowaveError && err.code) {
47
+ console.error(pc.gray(`Error code: ${err.code}`));
48
+ }
49
+ if (process.env.NODE_ENV === "development" && err instanceof Error && err.stack) {
50
+ console.error(pc.gray(err.stack));
51
+ }
52
+ process.exit(1);
53
+ }
54
+ var CodowaveError, ConfigError, APIError, ErrorCodes;
55
+ var init_error = __esm({
56
+ "src/utils/error.ts"() {
57
+ "use strict";
58
+ CodowaveError = class extends Error {
59
+ constructor(message, code, context) {
60
+ super(message);
61
+ this.code = code;
62
+ this.context = context;
63
+ this.name = "CodowaveError";
64
+ }
65
+ /**
66
+ * Returns a formatted error message with optional context
67
+ */
68
+ getFormattedMessage() {
69
+ let msg = this.message;
70
+ if (this.context && Object.keys(this.context).length > 0) {
71
+ msg += `
72
+
73
+ Context: ${JSON.stringify(this.context, null, 2)}`;
74
+ }
75
+ return msg;
76
+ }
77
+ };
78
+ ConfigError = class extends CodowaveError {
79
+ constructor(message, context) {
80
+ super(message, "CONFIG_ERROR", context);
81
+ this.name = "ConfigError";
82
+ }
83
+ };
84
+ APIError = class extends CodowaveError {
85
+ constructor(message, statusCode, context) {
86
+ super(message, "API_ERROR", context);
87
+ this.statusCode = statusCode;
88
+ this.name = "APIError";
89
+ }
90
+ };
91
+ ErrorCodes = {
92
+ CONFIG_NOT_FOUND: "CONFIG_NOT_FOUND",
93
+ INVALID_CONFIG: "INVALID_CONFIG",
94
+ REPO_NOT_CONFIGURED: "REPO_NOT_CONFIGURED",
95
+ API_ERROR: "API_ERROR",
96
+ NETWORK_ERROR: "NETWORK_ERROR",
97
+ AUTH_ERROR: "AUTH_ERROR",
98
+ INVALID_ISSUE_FORMAT: "INVALID_ISSUE_FORMAT",
99
+ RUN_FAILED: "RUN_FAILED"
100
+ };
101
+ }
102
+ });
103
+
104
+ // src/config.ts
105
+ import { readFileSync, writeFileSync, mkdirSync, existsSync } from "fs";
106
+ import { join } from "path";
107
+ import { homedir } from "os";
108
+ import { z } from "zod";
109
+ function readConfig() {
110
+ if (!existsSync(CONFIG_FILE)) {
111
+ return null;
112
+ }
113
+ try {
114
+ const raw = readFileSync(CONFIG_FILE, "utf-8");
115
+ const json = JSON.parse(raw);
116
+ const parsed = ConfigSchema.safeParse(json);
117
+ if (!parsed.success) {
118
+ const issues = parsed.error.issues.map((i) => ` - ${i.path.join(".")}: ${i.message}`).join("\n");
119
+ console.warn(`[config] Config validation failed:
120
+ ${issues}`);
121
+ return null;
122
+ }
123
+ return parsed.data;
124
+ } catch (err) {
125
+ const message = err instanceof Error ? err.message : String(err);
126
+ console.warn(`[config] Failed to read ${CONFIG_FILE}: ${message}`);
127
+ return null;
128
+ }
129
+ }
130
+ function readConfigOrThrow() {
131
+ const config = readConfig();
132
+ if (!config) {
133
+ throw new ConfigError(
134
+ "No Codowave config found. Run `codowave init` to get started.",
135
+ { suggestion: "Run 'codowave init' to configure your API key and repositories" }
136
+ );
137
+ }
138
+ return config;
139
+ }
140
+ function writeConfig(config) {
141
+ if (!existsSync(CONFIG_DIR)) {
142
+ mkdirSync(CONFIG_DIR, { recursive: true });
143
+ }
144
+ writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2) + "\n", "utf-8");
145
+ }
146
+ function updateConfig(updates) {
147
+ const current = readConfig() ?? {
148
+ apiKey: "",
149
+ apiUrl: "https://api.codowave.com",
150
+ repos: []
151
+ };
152
+ const merged = {
153
+ ...current,
154
+ ...updates
155
+ };
156
+ writeConfig(merged);
157
+ return merged;
158
+ }
159
+ function getConfigPath() {
160
+ return CONFIG_FILE;
161
+ }
162
+ var AIProviderSchema, ConfigSchema, CONFIG_DIR, CONFIG_FILE;
163
+ var init_config = __esm({
164
+ "src/config.ts"() {
165
+ "use strict";
166
+ init_error();
167
+ AIProviderSchema = z.object({
168
+ provider: z.enum(["openai", "anthropic", "minimax", "ollama", "custom"]),
169
+ apiKey: z.string().min(1),
170
+ model: z.string().default(""),
171
+ baseUrl: z.string().url().optional()
172
+ });
173
+ ConfigSchema = z.object({
174
+ apiKey: z.string().min(1),
175
+ apiUrl: z.string().url().default("https://api.codowave.com"),
176
+ repos: z.array(
177
+ z.object({
178
+ owner: z.string(),
179
+ name: z.string(),
180
+ id: z.string().optional()
181
+ })
182
+ ).default([]),
183
+ ai: AIProviderSchema.optional()
184
+ });
185
+ CONFIG_DIR = join(homedir(), ".codowave");
186
+ CONFIG_FILE = join(CONFIG_DIR, "config.json");
187
+ }
188
+ });
189
+
190
+ // src/components/init/GithubAppStep.tsx
191
+ import { useState, useEffect } from "react";
192
+ import {
193
+ Box,
194
+ Text,
195
+ useInput
196
+ } from "ink";
197
+ import Spinner from "ink-spinner";
198
+ import pc3 from "picocolors";
199
+ import { jsx, jsxs } from "react/jsx-runtime";
200
+ var GithubAppStep;
201
+ var init_GithubAppStep = __esm({
202
+ "src/components/init/GithubAppStep.tsx"() {
203
+ "use strict";
204
+ GithubAppStep = ({ apiUrl, onComplete, onCancel }) => {
205
+ const [step, setStep] = useState("api-key");
206
+ const [apiKey, setApiKey] = useState("");
207
+ const [repos, setRepos] = useState([]);
208
+ const [selectedRepos, setSelectedRepos] = useState(/* @__PURE__ */ new Set());
209
+ const [currentSelection, setCurrentSelection] = useState(0);
210
+ const [loading, setLoading] = useState(false);
211
+ const [error, setError] = useState(null);
212
+ useEffect(() => {
213
+ if (step === "repos" && apiKey && repos.length === 0 && !loading) {
214
+ fetchRepos();
215
+ }
216
+ }, [step, apiKey]);
217
+ async function fetchRepos() {
218
+ setLoading(true);
219
+ setError(null);
220
+ try {
221
+ const response = await fetch(`${apiUrl}/api/v1/repos`, {
222
+ headers: {
223
+ Authorization: `Bearer ${apiKey}`,
224
+ "Content-Type": "application/json"
225
+ }
226
+ });
227
+ if (!response.ok) {
228
+ if (response.status === 401) {
229
+ throw new Error("Invalid API key. Please check and try again.");
230
+ }
231
+ throw new Error(`Failed to fetch repositories: ${response.status}`);
232
+ }
233
+ const data = await response.json();
234
+ const fetchedRepos = data.repos || data.repositories || [];
235
+ setRepos(fetchedRepos);
236
+ if (fetchedRepos.length > 0) {
237
+ const allIndices = /* @__PURE__ */ new Set();
238
+ for (let i = 0; i < fetchedRepos.length; i++) {
239
+ allIndices.add(i);
240
+ }
241
+ setSelectedRepos(allIndices);
242
+ }
243
+ } catch (err) {
244
+ setError(err instanceof Error ? err.message : "Failed to fetch repositories");
245
+ } finally {
246
+ setLoading(false);
247
+ }
248
+ }
249
+ function handleApiKeySubmit() {
250
+ if (!apiKey.trim()) {
251
+ setError("API key cannot be empty");
252
+ return;
253
+ }
254
+ setError(null);
255
+ setStep("repos");
256
+ }
257
+ function handleConfirm() {
258
+ const selected = Array.from(selectedRepos).map((i) => repos[i]).filter((repo) => repo !== void 0);
259
+ onComplete(apiKey, selected);
260
+ }
261
+ function handleGoBack() {
262
+ setStep("api-key");
263
+ setError(null);
264
+ }
265
+ useInput((input, key) => {
266
+ if (step === "api-key") {
267
+ if (key.return) {
268
+ handleApiKeySubmit();
269
+ return;
270
+ }
271
+ if (key.escape) {
272
+ onCancel();
273
+ return;
274
+ }
275
+ if (key.backspace || input === "\b") {
276
+ setApiKey((prev) => prev.slice(0, -1));
277
+ setError(null);
278
+ return;
279
+ }
280
+ if (input && !key.ctrl && !key.meta) {
281
+ setApiKey((prev) => prev + input);
282
+ setError(null);
283
+ return;
284
+ }
285
+ } else if (step === "repos") {
286
+ if (key.escape) {
287
+ handleGoBack();
288
+ return;
289
+ }
290
+ if (key.return) {
291
+ handleConfirm();
292
+ return;
293
+ }
294
+ if (input === " ") {
295
+ toggleRepo(currentSelection);
296
+ return;
297
+ }
298
+ if (key.upArrow) {
299
+ setCurrentSelection((prev) => Math.max(0, prev - 1));
300
+ return;
301
+ }
302
+ if (key.downArrow) {
303
+ setCurrentSelection((prev) => Math.min(repos.length - 1, prev + 1));
304
+ return;
305
+ }
306
+ if (input === "a" || input === "A") {
307
+ const allIndices = /* @__PURE__ */ new Set();
308
+ for (let i = 0; i < repos.length; i++) {
309
+ allIndices.add(i);
310
+ }
311
+ setSelectedRepos(allIndices);
312
+ return;
313
+ }
314
+ if (input === "n" || input === "N") {
315
+ setSelectedRepos(/* @__PURE__ */ new Set());
316
+ return;
317
+ }
318
+ }
319
+ });
320
+ function toggleRepo(index) {
321
+ const newSelected = new Set(selectedRepos);
322
+ if (newSelected.has(index)) {
323
+ newSelected.delete(index);
324
+ } else {
325
+ newSelected.add(index);
326
+ }
327
+ setSelectedRepos(newSelected);
328
+ }
329
+ if (step === "api-key") {
330
+ return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", paddingY: 1, children: [
331
+ /* @__PURE__ */ jsx(Box, { marginBottom: 1, children: /* @__PURE__ */ jsx(Text, { bold: true, color: "cyan", children: "\u2550\u2550\u2550 GitHub App Setup \u2550\u2550\u2550" }) }),
332
+ /* @__PURE__ */ jsx(Box, { marginBottom: 1, children: /* @__PURE__ */ jsx(Text, { children: "Enter your Codowave API key:" }) }),
333
+ /* @__PURE__ */ jsxs(Box, { children: [
334
+ /* @__PURE__ */ jsx(Text, { color: "gray", children: "> " }),
335
+ /* @__PURE__ */ jsx(Text, { children: apiKey }),
336
+ /* @__PURE__ */ jsx(Text, { color: "cyan", children: "_" })
337
+ ] }),
338
+ error && /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(Text, { color: "red", children: pc3.red("\u2716 " + error) }) }),
339
+ /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsxs(Text, { color: "gray", children: [
340
+ "Press ",
341
+ /* @__PURE__ */ jsx(Text, { bold: true, children: "Enter" }),
342
+ " to continue, ",
343
+ /* @__PURE__ */ jsx(Text, { bold: true, children: "Esc" }),
344
+ " to cancel"
345
+ ] }) })
346
+ ] });
347
+ }
348
+ if (step === "repos") {
349
+ return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", paddingY: 1, children: [
350
+ /* @__PURE__ */ jsx(Box, { marginBottom: 1, children: /* @__PURE__ */ jsx(Text, { bold: true, color: "cyan", children: "\u2550\u2550\u2550 Select Repositories \u2550\u2550\u2550" }) }),
351
+ loading && /* @__PURE__ */ jsx(Box, { children: /* @__PURE__ */ jsxs(Text, { color: "yellow", children: [
352
+ /* @__PURE__ */ jsx(Spinner, { type: "dots" }),
353
+ " Loading repositories..."
354
+ ] }) }),
355
+ error && /* @__PURE__ */ jsx(Box, { marginBottom: 1, children: /* @__PURE__ */ jsx(Text, { color: "red", children: pc3.red("\u2716 " + error) }) }),
356
+ !loading && !error && repos.length === 0 && /* @__PURE__ */ jsx(Box, { marginBottom: 1, children: /* @__PURE__ */ jsx(Text, { color: "yellow", children: "No repositories found for this API key." }) }),
357
+ !loading && repos.length > 0 && /* @__PURE__ */ jsx(Box, { flexDirection: "column", marginBottom: 1, children: repos.map((repo, index) => /* @__PURE__ */ jsxs(Box, { children: [
358
+ /* @__PURE__ */ jsx(Text, { children: index === currentSelection ? " > " : " " }),
359
+ /* @__PURE__ */ jsxs(Text, { color: selectedRepos.has(index) ? "green" : "gray", children: [
360
+ "[",
361
+ selectedRepos.has(index) ? "\u2713" : " ",
362
+ "]"
363
+ ] }),
364
+ /* @__PURE__ */ jsx(Text, { children: " " }),
365
+ /* @__PURE__ */ jsx(Text, { bold: index === currentSelection, children: /* @__PURE__ */ jsxs(Text, { dimColor: !selectedRepos.has(index), children: [
366
+ repo.owner,
367
+ "/",
368
+ repo.name
369
+ ] }) })
370
+ ] }, index)) }),
371
+ !loading && repos.length > 0 && /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsxs(Text, { color: "gray", children: [
372
+ /* @__PURE__ */ jsx(Text, { bold: true, children: "\u2191/\u2193" }),
373
+ " navigate | ",
374
+ /* @__PURE__ */ jsx(Text, { bold: true, children: "Space" }),
375
+ " toggle | ",
376
+ /* @__PURE__ */ jsx(Text, { bold: true, children: "A" }),
377
+ " all | ",
378
+ /* @__PURE__ */ jsx(Text, { bold: true, children: "N" }),
379
+ " none"
380
+ ] }) }),
381
+ /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsxs(Text, { color: "gray", children: [
382
+ "Selected: ",
383
+ /* @__PURE__ */ jsx(Text, { bold: true, color: "green", children: selectedRepos.size }),
384
+ " / ",
385
+ repos.length,
386
+ " repos | ",
387
+ /* @__PURE__ */ jsx(Text, { bold: true, children: "Enter" }),
388
+ " confirm | ",
389
+ /* @__PURE__ */ jsx(Text, { bold: true, children: "Esc" }),
390
+ " back"
391
+ ] }) })
392
+ ] });
393
+ }
394
+ return null;
395
+ };
396
+ }
397
+ });
398
+
399
+ // src/commands/init.tsx
400
+ var init_exports = {};
401
+ __export(init_exports, {
402
+ initCommand: () => initCommand
403
+ });
404
+ import { Command } from "commander";
405
+ import pc4 from "picocolors";
406
+ import { render } from "ink";
407
+ import { jsx as jsx2 } from "react/jsx-runtime";
408
+ var initCommand;
409
+ var init_init = __esm({
410
+ "src/commands/init.tsx"() {
411
+ "use strict";
412
+ init_config();
413
+ init_GithubAppStep();
414
+ initCommand = new Command("init").description("Initialize Codowave and connect your GitHub repositories").action(async () => {
415
+ const existingConfig = readConfig();
416
+ const defaultApiUrl = "https://api.codowave.com";
417
+ const apiUrl = existingConfig?.apiUrl || defaultApiUrl;
418
+ if (existingConfig?.apiKey) {
419
+ console.log(pc4.yellow("\n\u26A0 Codowave is already initialized.\n"));
420
+ console.log(` API URL: ${pc4.cyan(existingConfig.apiUrl)}`);
421
+ console.log(` Config: ${getConfigPath()}`);
422
+ console.log(pc4.gray("\n Run this command again to reconfigure.\n"));
423
+ return;
424
+ }
425
+ let wizardComplete = false;
426
+ let capturedApiKey = "";
427
+ let capturedRepos = [];
428
+ const { waitUntilExit } = render(
429
+ /* @__PURE__ */ jsx2(
430
+ GithubAppStep,
431
+ {
432
+ apiUrl,
433
+ onComplete: (apiKey, repos) => {
434
+ capturedApiKey = apiKey;
435
+ capturedRepos = repos;
436
+ wizardComplete = true;
437
+ },
438
+ onCancel: () => {
439
+ process.exit(0);
440
+ }
441
+ }
442
+ )
443
+ );
444
+ await waitUntilExit();
445
+ if (!wizardComplete) {
446
+ return;
447
+ }
448
+ writeConfig({
449
+ apiKey: capturedApiKey,
450
+ apiUrl,
451
+ repos: capturedRepos
452
+ });
453
+ console.log(pc4.green("\n\u2713 Initialization complete!"));
454
+ console.log(`
455
+ Config saved to: ${pc4.cyan(getConfigPath())}`);
456
+ console.log(` API URL: ${pc4.cyan(apiUrl)}`);
457
+ console.log(` Repositories: ${pc4.bold(capturedRepos.length)} configured
458
+ `);
459
+ console.log(pc4.gray(" Run ") + pc4.bold("codowave run") + pc4.gray(" to start coding!\n"));
460
+ });
461
+ }
462
+ });
463
+
464
+ // src/commands/run.ts
465
+ var run_exports = {};
466
+ __export(run_exports, {
467
+ runCommand: () => runCommand
468
+ });
469
+ import { Command as Command2 } from "commander";
470
+ import pc5 from "picocolors";
471
+ function parseIssue(input) {
472
+ const urlMatch = input.match(/github\.com\/([^/]+)\/([^/]+)\/issues\/(\d+)/);
473
+ if (urlMatch && urlMatch[1] && urlMatch[2] && urlMatch[3]) {
474
+ return { owner: urlMatch[1], repo: urlMatch[2], number: parseInt(urlMatch[3], 10) };
475
+ }
476
+ const repoMatch = input.match(/([^/]+)\/([^#]+)#(\d+)/);
477
+ if (repoMatch && repoMatch[1] && repoMatch[2] && repoMatch[3]) {
478
+ return { owner: repoMatch[1], repo: repoMatch[2], number: parseInt(repoMatch[3], 10) };
479
+ }
480
+ const numMatch = input.match(/^(\d+)$/);
481
+ if (numMatch && numMatch[1]) {
482
+ return { owner: "", repo: "", number: parseInt(numMatch[1], 10) };
483
+ }
484
+ return null;
485
+ }
486
+ async function triggerRun(config, issue) {
487
+ const apiUrl = config.apiUrl;
488
+ const apiKey = config.apiKey;
489
+ const repoConfig = config.repos.find(
490
+ (r) => r.owner === issue.owner && r.name === issue.repo
491
+ );
492
+ if (!repoConfig) {
493
+ throw new ConfigError(
494
+ `Repository ${issue.owner}/${issue.repo} is not configured.`,
495
+ {
496
+ suggestion: `Run 'codowave config add-repo ${issue.owner}/${issue.repo}' to add this repository`,
497
+ configuredRepos: config.repos.map((r) => `${r.owner}/${r.name}`)
498
+ }
499
+ );
500
+ }
501
+ let response;
502
+ try {
503
+ response = await fetch(`${apiUrl}/api/runs`, {
504
+ method: "POST",
505
+ headers: {
506
+ "Content-Type": "application/json",
507
+ Authorization: `Bearer ${apiKey}`
508
+ },
509
+ body: JSON.stringify({
510
+ repositoryId: repoConfig.id,
511
+ issueNumber: issue.number
512
+ })
513
+ });
514
+ } catch {
515
+ throw new CodowaveError(
516
+ `Failed to connect to Codowave API at ${apiUrl}`,
517
+ ErrorCodes.NETWORK_ERROR,
518
+ { suggestion: "Check your internet connection and verify the API URL in your config." }
519
+ );
520
+ }
521
+ if (!response.ok) {
522
+ let errorMessage = `API returned status ${response.status}`;
523
+ let errorBody = {};
524
+ try {
525
+ errorBody = await response.json();
526
+ errorMessage = errorBody.error || errorBody.message || errorMessage;
527
+ } catch {
528
+ errorMessage = response.statusText || errorMessage;
529
+ }
530
+ if (response.status === 401) {
531
+ throw new CodowaveError(
532
+ `Authentication failed: ${errorMessage}`,
533
+ ErrorCodes.AUTH_ERROR,
534
+ { suggestion: "Run 'codowave init' to re-authenticate." }
535
+ );
536
+ }
537
+ if (response.status === 403) {
538
+ throw new CodowaveError(
539
+ `Access denied: ${errorMessage}`,
540
+ ErrorCodes.AUTH_ERROR,
541
+ { suggestion: "You don't have permission to trigger runs for this repository." }
542
+ );
543
+ }
544
+ if (response.status === 404) {
545
+ throw new CodowaveError(
546
+ `Resource not found: ${errorMessage}`,
547
+ ErrorCodes.API_ERROR,
548
+ { suggestion: "The repository or issue may no longer exist." }
549
+ );
550
+ }
551
+ const errorText = await response.text();
552
+ throw new APIError(
553
+ `Failed to trigger run: ${response.status} ${response.statusText}`,
554
+ response.status,
555
+ { response: errorText, issueNumber: issue.number, repo: `${issue.owner}/${issue.repo}` }
556
+ );
557
+ }
558
+ const data = await response.json();
559
+ return data.runId;
560
+ }
561
+ function createDemoRun(issue) {
562
+ const runId = `run-${Date.now()}`;
563
+ const run = {
564
+ id: runId,
565
+ repo: issue.owner && issue.repo ? `${issue.owner}/${issue.repo}` : "CodowaveAI/Codowave",
566
+ status: "in_progress",
567
+ issue: `#${issue.number}`,
568
+ branchName: `agent/issue-${issue.number}`,
569
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
570
+ stages: [
571
+ { name: "context", status: "pending" },
572
+ { name: "planning", status: "pending" },
573
+ { name: "implementation", status: "pending" },
574
+ { name: "testing", status: "pending" },
575
+ { name: "pr-creation", status: "pending" }
576
+ ]
577
+ };
578
+ demoRuns.set(runId, run);
579
+ return run;
580
+ }
581
+ function streamDemoRun(run) {
582
+ const stages = ["context", "planning", "implementation", "testing", "pr-creation"];
583
+ let currentStage = 0;
584
+ console.log(pc5.bold("\n=== Starting Run ===\n"));
585
+ console.log(pc5.bold("Run ID: ") + run.id);
586
+ console.log(pc5.bold("Repo: ") + run.repo);
587
+ console.log(pc5.bold("Issue: ") + run.issue);
588
+ console.log(pc5.bold("Branch: ") + run.branchName);
589
+ console.log("");
590
+ const interval = setInterval(() => {
591
+ if (currentStage >= stages.length) {
592
+ clearInterval(interval);
593
+ run.status = "completed";
594
+ run.completedAt = (/* @__PURE__ */ new Date()).toISOString();
595
+ run.prNumber = 100 + Math.floor(Math.random() * 50);
596
+ run.prTitle = `feat: Implement issue #${run.issue}`;
597
+ console.log(pc5.green("\n\u2713 Run completed successfully!"));
598
+ console.log(pc5.bold("\n=== Result ===\n"));
599
+ console.log(pc5.bold("PR: ") + `#${run.prNumber} - ${run.prTitle}`);
600
+ console.log(pc5.bold("Branch: ") + run.branchName);
601
+ console.log("");
602
+ process.exit(0);
603
+ return;
604
+ }
605
+ const stageName = stages[currentStage];
606
+ const stage = run.stages.find((s) => s.name === stageName);
607
+ if (stage) {
608
+ stage.status = "running";
609
+ console.log(pc5.blue(`
610
+ --- ${stageName} ---`));
611
+ setTimeout(() => {
612
+ stage.status = "completed";
613
+ stage.logs = `${stageName} completed successfully`;
614
+ currentStage++;
615
+ }, 1e3 + Math.random() * 2e3);
616
+ } else {
617
+ currentStage++;
618
+ }
619
+ }, 500);
620
+ process.on("SIGINT", () => {
621
+ clearInterval(interval);
622
+ run.status = "cancelled";
623
+ console.log(pc5.yellow("\n\n\u26A0 Run cancelled"));
624
+ process.exit(1);
625
+ });
626
+ }
627
+ var demoRuns, runCommand;
628
+ var init_run = __esm({
629
+ "src/commands/run.ts"() {
630
+ "use strict";
631
+ init_config();
632
+ init_error();
633
+ demoRuns = /* @__PURE__ */ new Map();
634
+ runCommand = new Command2("run").description("Trigger Codowave to process a GitHub issue").argument("<issue>", "GitHub issue number, URL (https://github.com/owner/repo/issues/123), or owner/repo#123").option("-r, --repo <owner/repo>", "Target repository (e.g. owner/repo)").option("-s, --stream", "Stream run progress (SSE)", false).action(async (_issueArg, _options) => {
635
+ try {
636
+ const parsed = parseIssue(_issueArg);
637
+ if (!parsed) {
638
+ console.error(pc5.red("\nInvalid issue format. Expected one of:"));
639
+ console.error(pc5.gray(" \u2022 Issue number: 123"));
640
+ console.error(pc5.gray(" \u2022 Full URL: https://github.com/owner/repo/issues/123"));
641
+ console.error(pc5.gray(" \u2022 Short form: owner/repo#123"));
642
+ console.error(pc5.gray(" \u2022 With repo flag: --repo owner/repo 123"));
643
+ process.exit(1);
644
+ }
645
+ if (_options.repo) {
646
+ const parts = _options.repo.split("/");
647
+ parsed.owner = parts[0] || "";
648
+ parsed.repo = parts[1] || "";
649
+ }
650
+ let config = null;
651
+ try {
652
+ config = readConfig();
653
+ } catch {
654
+ }
655
+ if (config && config.apiKey && config.repos.length > 0) {
656
+ console.log(pc5.blue("Connecting to Codowave API..."));
657
+ if (!parsed.owner || !parsed.repo) {
658
+ console.error(pc5.red("Repository required. Use -r option or include in issue URL."));
659
+ process.exit(1);
660
+ }
661
+ const runId = await triggerRun(config, parsed);
662
+ console.log(pc5.green(`\u2713 Run triggered: ${runId}`));
663
+ if (_options.stream) {
664
+ console.log(pc5.blue("\nStreaming run progress..."));
665
+ } else {
666
+ console.log(pc5.gray(`
667
+ Run started. Use \`codowave status ${runId}\` to check progress.`));
668
+ }
669
+ } else {
670
+ console.log(pc5.yellow("\u26A0 No config found. Running in demo mode.\n"));
671
+ const run = createDemoRun(parsed);
672
+ if (_options.stream || !process.stdout.isTTY) {
673
+ streamDemoRun(run);
674
+ } else {
675
+ console.log(pc5.green(`\u2713 Run started: ${run.id}`));
676
+ console.log(pc5.gray(`
677
+ Use \`codowave status ${run.id}\` to check progress.`));
678
+ console.log(pc5.gray(`Use \`codowave logs ${run.id} -f\` to follow logs.`));
679
+ }
680
+ }
681
+ } catch (err) {
682
+ handleError(err, "run");
683
+ }
684
+ });
685
+ }
686
+ });
687
+
688
+ // src/commands/status.ts
689
+ var status_exports = {};
690
+ __export(status_exports, {
691
+ getRun: () => getRun,
692
+ statusCommand: () => statusCommand
693
+ });
694
+ import { Command as Command3 } from "commander";
695
+ import pc6 from "picocolors";
696
+ function initDemoData() {
697
+ if (demoRuns2.size === 0) {
698
+ const demoRun = {
699
+ id: "latest",
700
+ repo: "CodowaveAI/Codowave",
701
+ status: "in_progress",
702
+ issue: "#53: Implement CLI status and logs commands",
703
+ branchName: "agent/issue-53",
704
+ startedAt: new Date(Date.now() - 5 * 60 * 1e3).toISOString(),
705
+ stages: [
706
+ { name: "context", status: "completed", logs: "Loaded 12 files, 3 PRs context" },
707
+ { name: "planning", status: "completed", logs: "Generated implementation plan" },
708
+ { name: "implementation", status: "running", logs: "Implementing status command..." },
709
+ { name: "testing", status: "pending" },
710
+ { name: "pr-creation", status: "pending" }
711
+ ]
712
+ };
713
+ demoRuns2.set(demoRun.id, demoRun);
714
+ const completedRun = {
715
+ id: "abc-123-def",
716
+ repo: "CodowaveAI/Codowave",
717
+ status: "completed",
718
+ issue: "#52: Add authentication flow",
719
+ prNumber: 78,
720
+ prTitle: "feat: Add OAuth authentication flow",
721
+ branchName: "feat/auth-flow",
722
+ startedAt: new Date(Date.now() - 60 * 60 * 1e3).toISOString(),
723
+ completedAt: new Date(Date.now() - 45 * 60 * 1e3).toISOString(),
724
+ stages: [
725
+ { name: "context", status: "completed" },
726
+ { name: "planning", status: "completed" },
727
+ { name: "implementation", status: "completed" },
728
+ { name: "testing", status: "completed" },
729
+ { name: "pr-creation", status: "completed" }
730
+ ]
731
+ };
732
+ demoRuns2.set(completedRun.id, completedRun);
733
+ }
734
+ }
735
+ function getRun(runId) {
736
+ initDemoData();
737
+ if (!runId) {
738
+ return Array.from(demoRuns2.values()).sort(
739
+ (a, b) => new Date(b.startedAt || 0).getTime() - new Date(a.startedAt || 0).getTime()
740
+ )[0];
741
+ }
742
+ return demoRuns2.get(runId);
743
+ }
744
+ function formatStatus(status) {
745
+ switch (status) {
746
+ case "pending":
747
+ return pc6.gray("pending");
748
+ case "in_progress":
749
+ return pc6.blue("in_progress");
750
+ case "completed":
751
+ return pc6.green("completed");
752
+ case "failed":
753
+ return pc6.red("failed");
754
+ case "cancelled":
755
+ return pc6.gray("cancelled");
756
+ default:
757
+ return pc6.gray(status);
758
+ }
759
+ }
760
+ function formatStageStatus(status) {
761
+ switch (status) {
762
+ case "pending":
763
+ return pc6.gray("[ ]");
764
+ case "running":
765
+ return pc6.blue("[~]");
766
+ case "completed":
767
+ return pc6.green("[+]");
768
+ case "failed":
769
+ return pc6.red("[x]");
770
+ case "skipped":
771
+ return pc6.gray("[-]");
772
+ default:
773
+ return pc6.gray("[?]");
774
+ }
775
+ }
776
+ function formatDuration(startedAt, completedAt) {
777
+ if (!startedAt) return "";
778
+ const start = new Date(startedAt).getTime();
779
+ const end = completedAt ? new Date(completedAt).getTime() : Date.now();
780
+ const seconds = Math.floor((end - start) / 1e3);
781
+ if (seconds < 60) return `${seconds}s`;
782
+ const minutes = Math.floor(seconds / 60);
783
+ const remainingSeconds = seconds % 60;
784
+ if (minutes < 60) return `${minutes}m ${remainingSeconds}s`;
785
+ const hours = Math.floor(minutes / 60);
786
+ const remainingMinutes = minutes % 60;
787
+ return `${hours}h ${remainingMinutes}m`;
788
+ }
789
+ var demoRuns2, statusCommand;
790
+ var init_status = __esm({
791
+ "src/commands/status.ts"() {
792
+ "use strict";
793
+ init_error();
794
+ demoRuns2 = /* @__PURE__ */ new Map();
795
+ statusCommand = new Command3("status").description("Show the status of a Codowave run").argument("[run-id]", "Run ID (defaults to latest)").option("-r, --repo <owner/repo>", "Filter by repository").action(async (_runId, _options) => {
796
+ try {
797
+ const run = getRun(_runId);
798
+ if (!run) {
799
+ console.log(pc6.yellow("No runs found. Run `codowave run <issue>` to start a new run."));
800
+ return;
801
+ }
802
+ if (_options?.repo && run.repo !== _options.repo) {
803
+ console.log(pc6.yellow("No run found for repository " + _options.repo));
804
+ return;
805
+ }
806
+ console.log(pc6.bold("\n=== Run Status ===\n"));
807
+ console.log(pc6.bold("ID: ") + run.id);
808
+ console.log(pc6.bold("Repo: ") + run.repo);
809
+ console.log(pc6.bold("Issue: ") + run.issue);
810
+ console.log(pc6.bold("Status: ") + formatStatus(run.status));
811
+ console.log(pc6.bold("Branch: ") + (run.branchName || pc6.gray("(none)")));
812
+ if (run.prNumber) {
813
+ console.log(pc6.bold("PR: ") + "#" + run.prNumber + " - " + (run.prTitle || ""));
814
+ }
815
+ if (run.startedAt) {
816
+ console.log(pc6.bold("Started: ") + new Date(run.startedAt).toLocaleString());
817
+ }
818
+ if (run.completedAt) {
819
+ console.log(pc6.bold("Duration: ") + formatDuration(run.startedAt, run.completedAt));
820
+ } else if (run.startedAt) {
821
+ console.log(pc6.bold("Duration: ") + pc6.blue("running... ") + formatDuration(run.startedAt));
822
+ }
823
+ if (run.errorMessage) {
824
+ console.log(pc6.bold("Error: ") + pc6.red(run.errorMessage));
825
+ }
826
+ console.log(pc6.bold("\n=== Stages ===\n"));
827
+ for (const stage of run.stages) {
828
+ const statusIcon = formatStageStatus(stage.status);
829
+ const statusText = pc6.bold("[" + stage.status + "]");
830
+ console.log(" " + statusIcon + " " + pc6.bold(stage.name.padEnd(20)) + " " + statusText);
831
+ }
832
+ console.log("");
833
+ } catch (err) {
834
+ handleError(err, "status");
835
+ }
836
+ });
837
+ }
838
+ });
839
+
840
+ // src/commands/logs.ts
841
+ var logs_exports = {};
842
+ __export(logs_exports, {
843
+ logsCommand: () => logsCommand
844
+ });
845
+ import { Command as Command4 } from "commander";
846
+ import pc7 from "picocolors";
847
+ var logsCommand;
848
+ var init_logs = __esm({
849
+ "src/commands/logs.ts"() {
850
+ "use strict";
851
+ init_status();
852
+ init_error();
853
+ logsCommand = new Command4("logs").description("Stream logs for a Codowave run").argument("[run-id]", "Run ID (defaults to latest)").option("-f, --follow", "Follow log output (SSE stream)").option("-s, --stage <name>", "Show logs for a specific stage").option("--no-color", "Disable colored output").action(async (_runId, _options) => {
854
+ try {
855
+ const run = getRun(_runId);
856
+ if (!run) {
857
+ console.log(pc7.yellow("No runs found. Run `codowave run <issue>` to start a new run."));
858
+ return;
859
+ }
860
+ if (_options?.stage) {
861
+ const stage = run.stages.find((s) => s.name === _options.stage);
862
+ if (!stage) {
863
+ console.log(pc7.red('Stage "' + _options.stage + '" not found.'));
864
+ console.log(pc7.gray("Available stages: ") + run.stages.map((s) => s.name).join(", "));
865
+ return;
866
+ }
867
+ console.log(pc7.bold("\n=== Logs: " + stage.name + " ===\n"));
868
+ console.log(pc7.bold("Status: ") + stage.status);
869
+ if (stage.logs) {
870
+ console.log(pc7.gray("\n--- Output ---\n"));
871
+ console.log(stage.logs);
872
+ } else {
873
+ console.log(pc7.gray("\n(no logs available yet)"));
874
+ }
875
+ if (_options.follow && stage.status === "running") {
876
+ console.log(pc7.blue("\n--- Following live logs (Ctrl+C to exit) ---\n"));
877
+ console.log(pc7.gray("(Live streaming would connect to API SSE endpoint in production)"));
878
+ }
879
+ console.log("");
880
+ return;
881
+ }
882
+ console.log(pc7.bold("\n=== Logs: " + run.id + " ===\n"));
883
+ console.log(pc7.bold("Issue: ") + run.issue);
884
+ console.log(pc7.bold("Status: ") + run.status);
885
+ console.log("");
886
+ for (const stage of run.stages) {
887
+ const statusIcon = stage.status === "completed" ? "[+]" : stage.status === "failed" ? "[x]" : stage.status === "running" ? "[~]" : "[ ]";
888
+ console.log(pc7.bold("\n" + statusIcon + " " + stage.name + "\n"));
889
+ if (stage.logs) {
890
+ console.log(stage.logs);
891
+ } else if (stage.status === "pending") {
892
+ console.log(pc7.gray("(pending)"));
893
+ } else if (stage.status === "running") {
894
+ console.log(pc7.blue("(running...)"));
895
+ } else if (stage.status === "skipped") {
896
+ console.log(pc7.gray("(skipped)"));
897
+ }
898
+ }
899
+ if (_options?.follow && run.status === "in_progress") {
900
+ console.log(pc7.blue("\n--- Following live logs (Ctrl+C to exit) ---\n"));
901
+ console.log(pc7.gray("(Live streaming would connect to API SSE endpoint in production)"));
902
+ let dots = 0;
903
+ const interval = setInterval(() => {
904
+ dots = (dots + 1) % 4;
905
+ process.stdout.write(pc7.blue("\r" + " ".repeat(dots) + " waiting for updates..."));
906
+ }, 500);
907
+ process.on("SIGINT", () => {
908
+ clearInterval(interval);
909
+ console.log(pc7.gray("\n\n(Stopped following)"));
910
+ process.exit(0);
911
+ });
912
+ }
913
+ console.log("");
914
+ } catch (err) {
915
+ handleError(err, "logs");
916
+ }
917
+ });
918
+ }
919
+ });
920
+
921
+ // src/commands/config-cmd.ts
922
+ var config_cmd_exports = {};
923
+ __export(config_cmd_exports, {
924
+ configCommand: () => configCommand
925
+ });
926
+ import { Command as Command5 } from "commander";
927
+ import pc8 from "picocolors";
928
+ var configCommand;
929
+ var init_config_cmd = __esm({
930
+ "src/commands/config-cmd.ts"() {
931
+ "use strict";
932
+ init_config();
933
+ configCommand = new Command5("config").description("Get or set Codowave configuration values");
934
+ configCommand.command("list").description("List all available config options").action(() => {
935
+ console.log(pc8.bold("\n\u{1F4CB} Available Config Options:\n"));
936
+ console.log(` ${pc8.cyan("apiKey")} ${pc8.gray("\u2014 Your Codowave API key")}`);
937
+ console.log(` ${pc8.cyan("apiUrl")} ${pc8.gray("\u2014 API endpoint URL (default: https://api.codowave.com)")}`);
938
+ console.log(` ${pc8.cyan("repos")} ${pc8.gray("\u2014 List of configured repositories")}`);
939
+ console.log(` ${pc8.cyan("configPath")} ${pc8.gray("\u2014 Path to the config file")}`);
940
+ console.log("");
941
+ });
942
+ configCommand.command("get <key>").description("Get a config value").action((key) => {
943
+ try {
944
+ const config = readConfigOrThrow();
945
+ if (key === "configPath") {
946
+ console.log(pc8.green(getConfigPath()));
947
+ return;
948
+ }
949
+ if (key === "repos") {
950
+ if (config.repos.length === 0) {
951
+ console.log(pc8.yellow("No repos configured."));
952
+ } else {
953
+ console.log(pc8.bold("\n\u{1F4E6} Configured Repositories:\n"));
954
+ config.repos.forEach((repo, index) => {
955
+ console.log(` ${index + 1}. ${pc8.cyan(`${repo.owner}/${repo.name}`)}`);
956
+ if (repo.id) {
957
+ console.log(` ${pc8.gray("ID: " + repo.id)}`);
958
+ }
959
+ });
960
+ console.log("");
961
+ }
962
+ return;
963
+ }
964
+ const value = config[key];
965
+ if (value === void 0) {
966
+ console.error(pc8.red(`\u2716 Unknown config key: ${key}`));
967
+ console.log(pc8.gray(` Run \`codowave config list\` to see available options.`));
968
+ process.exit(1);
969
+ }
970
+ console.log(value);
971
+ } catch (err) {
972
+ console.error(pc8.red(`\u2716 ${err instanceof Error ? err.message : String(err)}`));
973
+ process.exit(1);
974
+ }
975
+ });
976
+ configCommand.command("set <key> <value>").description("Set a config value").action((key, value) => {
977
+ try {
978
+ const validKeys = ["apiKey", "apiUrl"];
979
+ if (!validKeys.includes(key)) {
980
+ console.error(pc8.red(`\u2716 Cannot set '${key}' directly.`));
981
+ console.log(pc8.gray(` For 'repos', use \`codowave init\` to manage repositories.`));
982
+ console.log(pc8.gray(` Run \`codowave config list\` to see available options.`));
983
+ process.exit(1);
984
+ }
985
+ if (key === "apiUrl") {
986
+ try {
987
+ new URL(value);
988
+ } catch {
989
+ console.error(pc8.red(`\u2716 Invalid URL: ${value}`));
990
+ process.exit(1);
991
+ }
992
+ }
993
+ const updates = { [key]: value };
994
+ const newConfig = updateConfig(updates);
995
+ console.log(pc8.green(`\u2713 Updated ${key}`));
996
+ console.log(pc8.gray(` ${key} = ${newConfig[key]}`));
997
+ } catch (err) {
998
+ console.error(pc8.red(`\u2716 ${err instanceof Error ? err.message : String(err)}`));
999
+ process.exit(1);
1000
+ }
1001
+ });
1002
+ configCommand.command("show").description("Show all current config values").action(() => {
1003
+ try {
1004
+ const config = readConfigOrThrow();
1005
+ console.log(pc8.bold("\n\u2699\uFE0F Current Configuration:\n"));
1006
+ console.log(` ${pc8.cyan("apiKey")}: ${config.apiKey ? pc8.green("\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022") + pc8.gray(" (hidden)") : pc8.yellow("not set")}`);
1007
+ console.log(` ${pc8.cyan("apiUrl")}: ${config.apiUrl}`);
1008
+ console.log(` ${pc8.cyan("repos")}: ${config.repos.length} repository(s) configured`);
1009
+ console.log(` ${pc8.cyan("configPath")}: ${pc8.gray(getConfigPath())}`);
1010
+ if (config.repos.length > 0) {
1011
+ console.log(pc8.bold(pc8.gray("\n Repositories:")));
1012
+ config.repos.forEach((repo) => {
1013
+ console.log(` \u2022 ${repo.owner}/${repo.name}${repo.id ? pc8.gray(` (${repo.id})`) : ""}`);
1014
+ });
1015
+ }
1016
+ console.log("");
1017
+ } catch (err) {
1018
+ console.error(pc8.red(`\u2716 ${err instanceof Error ? err.message : String(err)}`));
1019
+ process.exit(1);
1020
+ }
1021
+ });
1022
+ configCommand.action(() => {
1023
+ configCommand.help();
1024
+ });
1025
+ }
1026
+ });
1027
+
1028
+ // src/commands/connect.ts
1029
+ var connect_exports = {};
1030
+ __export(connect_exports, {
1031
+ connectCommand: () => connectCommand,
1032
+ performConnect: () => performConnect
1033
+ });
1034
+ import { Command as Command6 } from "commander";
1035
+ import pc9 from "picocolors";
1036
+ async function performConnect(accessToken) {
1037
+ const config = updateConfig({
1038
+ apiKey: accessToken,
1039
+ apiUrl: PRO_API_URL
1040
+ });
1041
+ console.log(pc9.green("\u2713 Connected to Codowave Pro!"));
1042
+ console.log(pc9.gray(` API URL: ${config.apiUrl}`));
1043
+ }
1044
+ var PRO_API_URL, connectCommand;
1045
+ var init_connect = __esm({
1046
+ "src/commands/connect.ts"() {
1047
+ "use strict";
1048
+ init_config();
1049
+ PRO_API_URL = "https://api.codowave.com";
1050
+ connectCommand = new Command6("connect").description("Connect to Codowave Pro (upgrade from OSS)").action(async () => {
1051
+ try {
1052
+ console.log(pc9.bold("\n\u{1F517} Codowave Connect\n"));
1053
+ console.log(pc9.gray("This command upgrades your OSS installation to Codowave Pro.\n"));
1054
+ const config = readConfig();
1055
+ const isAlreadyPro = config?.apiUrl === PRO_API_URL;
1056
+ if (isAlreadyPro) {
1057
+ console.log(pc9.green("\u2713 You are already connected to Codowave Pro!"));
1058
+ console.log(pc9.gray(` API URL: ${config?.apiUrl}`));
1059
+ console.log("");
1060
+ return;
1061
+ }
1062
+ console.log(pc9.blue("Starting OAuth device flow...\n"));
1063
+ console.log(pc9.gray(" 1. Requesting device code..."));
1064
+ const deviceCode = `CODOWAVE-${Date.now().toString(36).toUpperCase()}`;
1065
+ const verificationUri = "https://codowave.com/activate";
1066
+ console.log(pc9.green("\n \u26A0\uFE0F Device Code: ") + pc9.bold(deviceCode));
1067
+ console.log(pc9.gray("\n 2. Please visit: ") + pc9.cyan(verificationUri));
1068
+ console.log(pc9.gray(" and enter the device code above.\n"));
1069
+ console.log(pc9.yellow(" \u2139\uFE0F This is a stub implementation."));
1070
+ console.log(pc9.gray(" In production, this would poll for OAuth completion.\n"));
1071
+ console.log(pc9.blue(" 3. Would save Pro token and switch API URL...\n"));
1072
+ console.log(pc9.bold("What would happen:\n"));
1073
+ console.log(` \u2022 Save Pro API token to ${getConfigPath()}`);
1074
+ console.log(` \u2022 Set apiUrl to ${PRO_API_URL}`);
1075
+ console.log("");
1076
+ console.log(pc9.gray("Run with ") + pc9.cyan("CODOWAVE_CONNECT=1") + pc9.gray(" to enable (not implemented yet)"));
1077
+ console.log("");
1078
+ } catch (err) {
1079
+ const message = err instanceof Error ? err.message : String(err);
1080
+ console.error(pc9.red(`
1081
+ \u2716 Error: ${message}
1082
+ `));
1083
+ process.exit(1);
1084
+ }
1085
+ });
1086
+ }
1087
+ });
1088
+
1089
+ // src/index.ts
1090
+ init_config();
1091
+ import { Command as Command7 } from "commander";
1092
+ import pc10 from "picocolors";
1093
+
1094
+ // src/utils/global-error.ts
1095
+ init_error();
1096
+ import process2 from "process";
1097
+ import pc2 from "picocolors";
1098
+ function setupGlobalErrorHandlers() {
1099
+ process2.on("uncaughtException", (err) => {
1100
+ console.error(pc2.red("\n\u{1F4A5} Unexpected Error"));
1101
+ console.error(pc2.gray(err.stack || ""));
1102
+ handleError(err, "uncaughtException");
1103
+ });
1104
+ process2.on("unhandledRejection", (reason, _promise) => {
1105
+ const message = reason instanceof Error ? reason.message : String(reason);
1106
+ const stack = reason instanceof Error ? reason.stack : void 0;
1107
+ console.error(pc2.red("\n\u{1F4A5} Unhandled Promise Rejection"));
1108
+ if (stack) {
1109
+ console.error(pc2.gray(stack));
1110
+ } else {
1111
+ console.error(pc2.gray(`Reason: ${message}`));
1112
+ }
1113
+ console.error(pc2.yellow("\nWarning: Unhandled promise rejections can cause instability."));
1114
+ console.error(pc2.gray("Please report this issue: https://github.com/CodowaveAI/Codowave/issues"));
1115
+ process2.exit(1);
1116
+ });
1117
+ }
1118
+
1119
+ // src/index.ts
1120
+ setupGlobalErrorHandlers();
1121
+ var { initCommand: initCommand2 } = await Promise.resolve().then(() => (init_init(), init_exports));
1122
+ var { runCommand: runCommand2 } = await Promise.resolve().then(() => (init_run(), run_exports));
1123
+ var { statusCommand: statusCommand2 } = await Promise.resolve().then(() => (init_status(), status_exports));
1124
+ var { logsCommand: logsCommand2 } = await Promise.resolve().then(() => (init_logs(), logs_exports));
1125
+ var { configCommand: configCommand2 } = await Promise.resolve().then(() => (init_config_cmd(), config_cmd_exports));
1126
+ var { connectCommand: connectCommand2 } = await Promise.resolve().then(() => (init_connect(), connect_exports));
1127
+ var VERSION = "0.1.0";
1128
+ var program = new Command7();
1129
+ program.name("codowave").description(
1130
+ pc10.bold("Codowave") + " \u2014 AI-powered coding agent for your GitHub repositories"
1131
+ ).version(VERSION, "-v, --version", "Output the current version").helpOption("-h, --help", "Display help").addHelpText(
1132
+ "beforeAll",
1133
+ `
1134
+ ${pc10.cyan(" \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557")}
1135
+ ${pc10.cyan(" \u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D")}
1136
+ ${pc10.cyan(" \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2557 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2557 ")}
1137
+ ${pc10.cyan(" \u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u255A\u2588\u2588\u2588\u2554\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2551 \u2588\u2588\u2551\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557")}
1138
+ `
1139
+ ).option("--api-url <url>", "Override the Codowave API URL");
1140
+ program.addCommand(initCommand2);
1141
+ program.addCommand(runCommand2);
1142
+ program.addCommand(statusCommand2);
1143
+ program.addCommand(logsCommand2);
1144
+ program.addCommand(configCommand2);
1145
+ program.addCommand(connectCommand2);
1146
+ program.configureOutput({
1147
+ writeErr: (str) => process.stderr.write(pc10.red(str))
1148
+ });
1149
+ var args = process.argv.slice(2);
1150
+ var isInitOrHelp = args[0] === "init" || args.includes("--help") || args.includes("-h") || args.includes("--version") || args.includes("-v") || args.length === 0;
1151
+ if (!isInitOrHelp) {
1152
+ const config = readConfig();
1153
+ if (!config) {
1154
+ console.warn(
1155
+ pc10.yellow(
1156
+ "\u26A0 No config found. Run " + pc10.bold("codowave init") + " to get started.\n"
1157
+ )
1158
+ );
1159
+ }
1160
+ }
1161
+ program.parseAsync(process.argv).catch((err) => {
1162
+ console.error(pc10.red(`
1163
+ \u2716 Error: ${err instanceof Error ? err.message : String(err)}
1164
+ `));
1165
+ process.exit(1);
1166
+ });
package/package.json ADDED
@@ -0,0 +1,37 @@
1
+ {
2
+ "name": "codowave",
3
+ "version": "0.1.0",
4
+ "description": "Codowave OSS CLI — AI-powered coding agent for your GitHub repos",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "bin": {
8
+ "codowave": "./dist/index.js"
9
+ },
10
+ "files": ["dist"],
11
+ "scripts": {
12
+ "build": "tsup --config tsup.config.ts",
13
+ "dev": "tsup src/index.ts --format esm --watch",
14
+ "typecheck": "tsc --noEmit",
15
+ "lint": "eslint src --ext .ts,.tsx",
16
+ "test": "vitest run",
17
+ "test:watch": "vitest"
18
+ },
19
+ "dependencies": {
20
+ "commander": "^12.1.0",
21
+ "ink": "^5.0.1",
22
+ "ink-spinner": "^5.0.0",
23
+ "picocolors": "^1.1.0",
24
+ "react": "^18.3.1",
25
+ "zod": "^3.23.8"
26
+ },
27
+ "devDependencies": {
28
+ "@types/node": "^22.0.0",
29
+ "@types/react": "^18.3.1",
30
+ "tsup": "^8.3.0",
31
+ "typescript": "^5.6.0",
32
+ "vitest": "^2.1.8"
33
+ },
34
+ "engines": {
35
+ "node": ">=20.0.0"
36
+ }
37
+ }