@jojonax/codex-copilot 1.5.5 → 1.6.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,769 +1,773 @@
1
- /**
2
- * AI Provider Registry — supports multiple AI coding tools
3
- *
4
- * Each provider has its own invocation pattern:
5
- * - Codex CLI: piped stdin → codex exec --full-auto
6
- * - Claude Code: -p flag + --allowedTools for safe auto-execution
7
- * - Cursor Agent: cursor-agent CLI with -p headless mode
8
- * - Gemini CLI: gemini -p for non-interactive prompt
9
- * - Codex Desktop / Cursor IDE / Antigravity IDE: clipboard + manual
10
- */
11
-
12
- import { execSync, spawn } from 'child_process';
13
- import { readFileSync, writeFileSync, existsSync } from 'fs';
14
- import { resolve } from 'path';
15
- import { log } from './logger.js';
16
- import { ask } from './prompt.js';
17
- import { automator } from './automator.js';
18
-
19
- const HOME = process.env.HOME || process.env.USERPROFILE || '~';
20
-
21
- // ──────────────────────────────────────────────
22
- // Provider Registry — each provider is unique
23
- // ──────────────────────────────────────────────
24
-
25
- const PROVIDERS = {
26
- // ─── CLI Providers (auto-execute) ───
27
-
28
- 'codex-cli': {
29
- name: 'Codex CLI',
30
- type: 'cli',
31
- detect: 'codex',
32
- // Codex uses piped stdin: cat file | codex exec --full-auto -
33
- buildCommand: (promptPath, cwd) =>
34
- `cat ${shellEscape(promptPath)} | codex exec --full-auto -`,
35
- description: 'OpenAI Codex CLI — pipes prompt via stdin',
36
- version: {
37
- command: 'codex --version',
38
- parse: (output) => output.match(/[\d.]+/)?.[0],
39
- latest: { type: 'brew-cask', name: 'codex' },
40
- update: 'brew upgrade --cask codex',
41
- },
42
- },
43
-
44
- 'claude-code': {
45
- name: 'Claude Code',
46
- type: 'cli',
47
- detect: 'claude',
48
- // Claude Code uses -p (print/non-interactive) + --allowedTools for permissions
49
- // Reads the file content and passes as argument (not piped)
50
- buildCommand: (promptPath, cwd) => {
51
- const escaped = shellEscape(promptPath);
52
- // Use subshell to read file content into -p argument
53
- return `claude -p "$(cat ${escaped})" --allowedTools "Bash(git*),Read,Write,Edit"`;
54
- },
55
- description: 'Anthropic Claude Code CLI — -p mode with tool permissions',
56
- version: {
57
- command: 'claude --version',
58
- parse: (output) => output.match(/[\d.]+/)?.[0],
59
- latest: { type: 'npm', name: '@anthropic-ai/claude-code' },
60
- update: 'npm update -g @anthropic-ai/claude-code',
61
- },
62
- },
63
-
64
- 'cursor-agent': {
65
- name: 'Cursor Agent',
66
- type: 'cli',
67
- detect: 'cursor-agent',
68
- // Cursor Agent uses -p flag for headless/non-interactive mode
69
- buildCommand: (promptPath, cwd) => {
70
- const escaped = shellEscape(promptPath);
71
- return `cursor-agent -p "$(cat ${escaped})"`;
72
- },
73
- description: 'Cursor Agent CLI — headless -p mode',
74
- // No standard package manager — skip version check
75
- },
76
-
77
- 'gemini-cli': {
78
- name: 'Gemini CLI',
79
- type: 'cli',
80
- detect: 'gemini',
81
- // Gemini CLI uses -p for non-interactive prompt execution
82
- buildCommand: (promptPath, cwd) => {
83
- const escaped = shellEscape(promptPath);
84
- return `gemini -p "$(cat ${escaped})"`;
85
- },
86
- description: 'Google Gemini CLI — non-interactive -p mode',
87
- version: {
88
- command: 'gemini --version',
89
- parse: (output) => output.match(/[\d.]+/)?.[0],
90
- latest: { type: 'brew', name: 'gemini-cli' },
91
- update: 'brew upgrade gemini-cli',
92
- },
93
- },
94
-
95
- // ─── IDE Providers (clipboard + manual) ───
96
-
97
- 'codex-desktop': {
98
- name: 'Codex Desktop',
99
- type: 'ide',
100
- instructions: 'Open Codex Desktop → paste the prompt → execute',
101
- displayPrompt: true, // Show the prompt content in terminal box
102
- },
103
-
104
- 'cursor': {
105
- name: 'Cursor IDE',
106
- type: 'ide',
107
- instructions: 'Open Cursor → Ctrl/Cmd+I (Composer) → paste the prompt → run as Agent',
108
- displayPrompt: false, // Too long to display, just copy to clipboard
109
- },
110
-
111
- 'antigravity': {
112
- name: 'Antigravity (Gemini)',
113
- type: 'ide',
114
- instructions: 'Open Antigravity → paste the prompt into chat → execute',
115
- displayPrompt: false,
116
- },
117
- };
118
-
119
- /**
120
- * Get a provider by ID
121
- */
122
- export function getProvider(id) {
123
- return PROVIDERS[id] || null;
124
- }
125
-
126
- /**
127
- * Get all provider IDs
128
- */
129
- export function getAllProviderIds() {
130
- return Object.keys(PROVIDERS);
131
- }
132
-
133
- /**
134
- * Detect which CLI providers are installed on the system
135
- * @returns {string[]} list of available provider IDs
136
- */
137
- export function detectAvailable() {
138
- const available = [];
139
- for (const [id, prov] of Object.entries(PROVIDERS)) {
140
- if (prov.type === 'cli' && prov.detect) {
141
- try {
142
- const cmd = process.platform === 'win32'
143
- ? `where ${prov.detect}`
144
- : `which ${prov.detect}`;
145
- execSync(cmd, { stdio: 'pipe' });
146
- available.push(id);
147
- } catch {
148
- // Not installed
149
- }
150
- }
151
- }
152
- return available;
153
- }
154
-
155
- /**
156
- * Build the selection menu for init
157
- * Groups CLIs first (with detection status), then IDEs
158
- * @returns {{ label: string, value: string }[]}
159
- */
160
- export function buildProviderChoices(versionCache = {}) {
161
- const detected = detectAvailable();
162
- const choices = [];
163
-
164
- // CLI providers first with detection indicator + version info
165
- for (const [id, prov] of Object.entries(PROVIDERS)) {
166
- if (prov.type === 'cli') {
167
- const installed = detected.includes(id);
168
- let tag = installed ? ' ✓ detected' : '';
169
-
170
- // Append version info if available in cache
171
- const vi = versionCache[id];
172
- if (vi && vi.current) {
173
- if (vi.updateAvailable) {
174
- tag += ` (v${vi.current} → v${vi.latest} available)`;
175
- } else if (vi.latest) {
176
- tag += ` (v${vi.current} ✓ latest)`;
177
- } else {
178
- tag += ` (v${vi.current})`;
179
- }
180
- }
181
-
182
- choices.push({
183
- label: `${prov.name}${tag} — ${prov.description}`,
184
- value: id,
185
- available: installed,
186
- });
187
- }
188
- }
189
-
190
- // IDE providers — show auto-paste capability if recipe exists
191
- for (const [id, prov] of Object.entries(PROVIDERS)) {
192
- if (prov.type === 'ide') {
193
- const hasAutoPaste = automator.hasRecipe(id);
194
- const tag = hasAutoPaste ? 'auto-paste' : 'clipboard + manual';
195
- choices.push({
196
- label: `${prov.name} — ${tag}`,
197
- value: id,
198
- available: true,
199
- });
200
- }
201
- }
202
-
203
- return choices;
204
- }
205
-
206
- /**
207
- * Execute a prompt using the configured provider
208
- *
209
- * CLI providers: auto-execute via their specific command
210
- * IDE providers: copy to clipboard + display instructions + wait
211
- *
212
- * @param {string} providerId - Provider ID from config
213
- * @param {string} promptPath - Absolute path to prompt file
214
- * @param {string} cwd - Working directory
215
- * @returns {Promise<{ ok: boolean, rateLimited?: boolean, retryAt?: Date }>}
216
- */
217
- export async function executePrompt(providerId, promptPath, cwd) {
218
- const prov = PROVIDERS[providerId];
219
-
220
- if (!prov) {
221
- log.warn(`Unknown provider '${providerId}', falling back to clipboard mode`);
222
- const ok = await clipboardFallback(promptPath);
223
- return { ok };
224
- }
225
-
226
- if (prov.type === 'cli') {
227
- return await executeCLI(prov, providerId, promptPath, cwd);
228
- } else {
229
- const ok = await executeIDE(prov, providerId, promptPath);
230
- return { ok };
231
- }
232
- }
233
-
234
- /**
235
- * Execute via CLI provider — each tool has its own command pattern.
236
- * Output is captured and filtered to show only file-level progress,
237
- * keeping the terminal clean (like Claude Code's compact display).
238
- */
239
- async function executeCLI(prov, providerId, promptPath, cwd) {
240
- // Verify the CLI is still available
241
- if (prov.detect) {
242
- try {
243
- const cmd = process.platform === 'win32'
244
- ? `where ${prov.detect}`
245
- : `which ${prov.detect}`;
246
- execSync(cmd, { stdio: 'pipe' });
247
- } catch {
248
- log.warn(`${prov.name} not found in PATH, falling back to clipboard mode`);
249
- const ok = await clipboardFallback(promptPath);
250
- return { ok };
251
- }
252
- }
253
-
254
- const command = prov.buildCommand(promptPath, cwd);
255
- log.info(`Executing via ${prov.name}...`);
256
- log.dim(` \u2192 ${command.substring(0, 80)}${command.length > 80 ? '...' : ''}`);
257
-
258
- return new Promise((resolvePromise) => {
259
- const child = spawn('sh', ['-c', command], {
260
- cwd,
261
- stdio: ['pipe', 'pipe', 'pipe'],
262
- });
263
-
264
- let lastFile = '';
265
- let statusText = command.substring(0, 80);
266
- let lineBuffer = '';
267
- let stderrBuffer = ''; // Capture stderr for rate limit detection
268
- const FILE_EXT = /(?:^|\s|['"|(/])([a-zA-Z0-9_.\/-]+\.(?:rs|ts|js|jsx|tsx|py|go|toml|yaml|yml|json|md|css|html|sh|sql|prisma|vue|svelte))\b/;
269
-
270
- // Spinner animation — gives a dynamic, alive feel
271
- const SPINNER = ['\u280B', '\u2819', '\u2839', '\u2838', '\u283C', '\u2834', '\u2826', '\u2827', '\u2807', '\u280F'];
272
- let spinIdx = 0;
273
- const spinTimer = setInterval(() => {
274
- const frame = SPINNER[spinIdx % SPINNER.length];
275
- process.stdout.write(`\r\x1b[K \x1b[36m${frame}\x1b[0m ${statusText}`);
276
- spinIdx++;
277
- }, 80);
278
-
279
- function processLine(line) {
280
- const fileMatch = line.match(FILE_EXT);
281
- if (fileMatch && fileMatch[1] !== lastFile) {
282
- lastFile = fileMatch[1];
283
- statusText = lastFile;
284
- }
285
- }
286
-
287
- child.stdout.on('data', (data) => {
288
- const text = data.toString();
289
- lineBuffer += text;
290
- stderrBuffer += text; // Also check stdout for rate limit messages
291
- const lines = lineBuffer.split('\n');
292
- lineBuffer = lines.pop();
293
- for (const line of lines) processLine(line);
294
- });
295
-
296
- child.stderr.on('data', (data) => {
297
- const text = data.toString();
298
- stderrBuffer += text;
299
- const trimmed = text.trim();
300
- if (trimmed && !trimmed.includes('\u2588') && !trimmed.includes('progress')) {
301
- for (const line of trimmed.split('\n').slice(0, 3)) {
302
- if (line.trim()) log.dim(` ${line.substring(0, 120)}`);
303
- }
304
- }
305
- });
306
-
307
- child.on('close', (code) => {
308
- clearInterval(spinTimer);
309
- process.stdout.write('\r\x1b[K');
310
- if (code === 0) {
311
- log.info(`${prov.name} execution complete`);
312
- resolvePromise({ ok: true });
313
- } else {
314
- // Check for rate limit error in captured output
315
- const rateLimitInfo = parseRateLimitError(stderrBuffer);
316
- if (rateLimitInfo) {
317
- log.warn(`${prov.name} hit rate limit — retry at ${rateLimitInfo.retryAtStr}`);
318
- resolvePromise({ ok: false, rateLimited: true, retryAt: rateLimitInfo.retryAt, retryAtStr: rateLimitInfo.retryAtStr });
319
- } else {
320
- log.warn(`${prov.name} exited with code ${code}`);
321
- resolvePromise({ ok: false });
322
- }
323
- }
324
- });
325
-
326
- child.on('error', (err) => {
327
- clearInterval(spinTimer);
328
- process.stdout.write('\r\x1b[K');
329
- log.warn(`${prov.name} execution failed: ${err.message}`);
330
- resolvePromise({ ok: false });
331
- });
332
- });
333
- }
334
-
335
- /**
336
- * Execute via IDE provider
337
- *
338
- * Priority: auto-paste (if IDE running) → manual clipboard fallback
339
- */
340
- async function executeIDE(prov, providerId, promptPath) {
341
- const prompt = readFileSync(promptPath, 'utf-8');
342
-
343
- // ── Try auto-paste first ──
344
- if (automator.hasRecipe(providerId)) {
345
- if (automator.isIDERunning(providerId)) {
346
- log.info(`${prov.name} detected — attempting auto-paste...`);
347
- const ok = automator.activateAndPaste(providerId, prompt);
348
- if (ok) {
349
- log.info(`✅ Prompt auto-pasted into ${prov.name}`);
350
- log.blank();
351
- await ask(`Press Enter after ${prov.name} development is complete...`);
352
- return true;
353
- }
354
- log.warn('Auto-paste failed, falling back to manual mode');
355
- } else {
356
- log.warn(`${prov.name} is not running — using clipboard mode`);
357
- }
358
- }
359
-
360
- // ── Manual fallback ──
361
- log.blank();
362
- log.info(`📋 ${prov.instructions}`);
363
- log.dim(` Prompt file: ${promptPath}`);
364
- log.blank();
365
-
366
- // Some providers benefit from seeing the prompt in terminal
367
- if (prov.displayPrompt) {
368
- const lines = prompt.split('\n');
369
- const maxLines = 30;
370
- const show = lines.slice(0, maxLines);
371
- console.log(' ┌─── Prompt Preview ─────────────────────────────────────┐');
372
- for (const line of show) {
373
- console.log(` │ ${line}`);
374
- }
375
- if (lines.length > maxLines) {
376
- console.log(` │ ... (${lines.length - maxLines} more lines — see full file)`);
377
- }
378
- console.log(' └────────────────────────────────────────────────────────┘');
379
- log.blank();
380
- }
381
-
382
- copyToClipboard(prompt);
383
-
384
- await ask(`Press Enter after ${prov.name} development is complete...`);
385
- return true;
386
- }
387
-
388
- /**
389
- * Fallback: copy to clipboard and wait for any provider
390
- */
391
- async function clipboardFallback(promptPath) {
392
- const prompt = readFileSync(promptPath, 'utf-8');
393
-
394
- log.blank();
395
- log.info('📋 Paste the prompt into your AI coding tool and execute');
396
- log.dim(` Prompt file: ${promptPath}`);
397
- log.blank();
398
-
399
- copyToClipboard(prompt);
400
-
401
- await ask('Press Enter after development is complete...');
402
- return true;
403
- }
404
-
405
- function copyToClipboard(text) {
406
- try {
407
- if (process.platform === 'darwin') {
408
- execSync('pbcopy', { input: text, stdio: ['pipe', 'pipe', 'pipe'] });
409
- } else if (process.platform === 'linux') {
410
- // Try xclip first, then xsel
411
- try {
412
- execSync('xclip -selection clipboard', { input: text, stdio: ['pipe', 'pipe', 'pipe'] });
413
- } catch {
414
- execSync('xsel --clipboard --input', { input: text, stdio: ['pipe', 'pipe', 'pipe'] });
415
- }
416
- }
417
- // Windows: skip no good CLI clipboard tool
418
- log.info('📋 Copied to clipboard');
419
- } catch {
420
- log.dim('(Could not copy to clipboard — copy the file manually)');
421
- }
422
- }
423
-
424
- function shellEscape(str) {
425
- return `'${str.replace(/'/g, "'\\''")}'`;
426
- }
427
-
428
- /**
429
- * Lightweight AI query — capture output rather than inherit stdio.
430
- * Only works for CLI providers. Returns null for IDE providers.
431
- *
432
- * @param {string} providerId - Provider ID
433
- * @param {string} question - The question/prompt text
434
- * @param {string} cwd - Working directory
435
- * @returns {Promise<string|null>} AI response text, or null if unsupported/failed
436
- */
437
- export async function queryAI(providerId, question, cwd) {
438
- const prov = PROVIDERS[providerId];
439
- if (!prov || prov.type !== 'cli') return null;
440
-
441
- // Verify CLI is available
442
- if (prov.detect) {
443
- try {
444
- const cmd = process.platform === 'win32'
445
- ? `where ${prov.detect}`
446
- : `which ${prov.detect}`;
447
- execSync(cmd, { stdio: 'pipe' });
448
- } catch {
449
- return null;
450
- }
451
- }
452
-
453
- // Write question to temp file
454
- const tmpPath = resolve(cwd, '.codex-copilot/_query_prompt.md');
455
- writeFileSync(tmpPath, question);
456
-
457
- const command = prov.buildCommand(tmpPath, cwd);
458
-
459
- try {
460
- const output = execSync(command, {
461
- cwd,
462
- encoding: 'utf-8',
463
- stdio: ['pipe', 'pipe', 'pipe'],
464
- timeout: 60000, // 60s timeout for classification
465
- });
466
- return output.trim();
467
- } catch (err) {
468
- log.dim(`AI query failed: ${(err.message || '').substring(0, 80)}`);
469
- return null;
470
- }
471
- }
472
-
473
- /**
474
- * Use AI to classify code review feedback.
475
- *
476
- * Returns 'pass' if AI determines no actionable issues,
477
- * 'fix' if there are issues to address, or null if classification failed.
478
- *
479
- * @param {string} providerId - Provider ID
480
- * @param {string} feedbackText - The collected review feedback
481
- * @param {string} cwd - Working directory
482
- * @returns {Promise<'pass'|'fix'|null>}
483
- */
484
- export async function classifyReview(providerId, feedbackText, cwd) {
485
- const classificationPrompt = `You are a code review classifier. Your ONLY job is to determine if the following code review feedback contains actionable issues that require code changes.
486
-
487
- ## Code Review Feedback
488
- ${feedbackText}
489
-
490
- ## Instructions
491
- - If the review says the code looks good, has no issues, is purely informational, or explicitly states no changes are needed: output exactly PASS
492
- - If the review requests specific code changes, points out bugs, security issues, or improvements that need action: output exactly FIX
493
-
494
- IMPORTANT: Output ONLY a single word on the first line: either PASS or FIX. No other text.`;
495
-
496
- const response = await queryAI(providerId, classificationPrompt, cwd);
497
- if (!response) return null;
498
-
499
- // Parse the first meaningful line
500
- const firstLine = response.split('\n').map(l => l.trim()).find(l => l.length > 0);
501
- if (!firstLine) return null;
502
-
503
- const upper = firstLine.toUpperCase();
504
- if (upper.includes('PASS')) return 'pass';
505
- if (upper.includes('FIX')) return 'fix';
506
-
507
- return null; // Ambiguous — caller decides fallback
508
- }
509
-
510
- // ──────────────────────────────────────────────
511
- // Version Check & Auto-Update
512
- // ──────────────────────────────────────────────
513
-
514
- /**
515
- * Compare two semver-like version strings.
516
- * Returns true if latest > current.
517
- */
518
- function isNewerVersion(current, latest) {
519
- if (!current || !latest) return false;
520
- const a = current.split('.').map(Number);
521
- const b = latest.split('.').map(Number);
522
- const len = Math.max(a.length, b.length);
523
- for (let i = 0; i < len; i++) {
524
- const av = a[i] || 0;
525
- const bv = b[i] || 0;
526
- if (bv > av) return true;
527
- if (bv < av) return false;
528
- }
529
- return false;
530
- }
531
-
532
- /**
533
- * Get the locally installed version of a provider.
534
- * @returns {string|null} version string or null
535
- */
536
- function getLocalVersion(providerId) {
537
- const prov = PROVIDERS[providerId];
538
- if (!prov?.version) return null;
539
- try {
540
- const output = execSync(prov.version.command, {
541
- encoding: 'utf-8',
542
- stdio: ['pipe', 'pipe', 'pipe'],
543
- timeout: 5000,
544
- }).trim();
545
- return prov.version.parse(output);
546
- } catch {
547
- return null;
548
- }
549
- }
550
-
551
- /**
552
- * Fetch the latest available version from the package registry.
553
- * @returns {string|null} latest version string or null
554
- */
555
- function fetchLatestVersion(providerId) {
556
- const prov = PROVIDERS[providerId];
557
- if (!prov?.version?.latest) return null;
558
-
559
- const { type, name } = prov.version.latest;
560
- try {
561
- if (type === 'npm') {
562
- return execSync(`npm view ${name} version`, {
563
- encoding: 'utf-8',
564
- stdio: ['pipe', 'pipe', 'pipe'],
565
- timeout: 10000,
566
- }).trim();
567
- }
568
- if (type === 'brew') {
569
- const json = execSync(`brew info ${name} --json=v2`, {
570
- encoding: 'utf-8',
571
- stdio: ['pipe', 'pipe', 'pipe'],
572
- timeout: 10000,
573
- });
574
- const data = JSON.parse(json);
575
- return data.formulae?.[0]?.versions?.stable || null;
576
- }
577
- if (type === 'brew-cask') {
578
- const json = execSync(`brew info --cask ${name} --json=v2`, {
579
- encoding: 'utf-8',
580
- stdio: ['pipe', 'pipe', 'pipe'],
581
- timeout: 10000,
582
- });
583
- const data = JSON.parse(json);
584
- return data.casks?.[0]?.version || null;
585
- }
586
- } catch {
587
- return null;
588
- }
589
- return null;
590
- }
591
-
592
- /**
593
- * Check version status for a single provider.
594
- * @param {string} providerId
595
- * @returns {{ current: string|null, latest: string|null, updateAvailable: boolean, updateCommand: string|null }}
596
- */
597
- export function checkProviderVersion(providerId) {
598
- const prov = PROVIDERS[providerId];
599
- if (!prov?.version) {
600
- return { current: null, latest: null, updateAvailable: false, updateCommand: null };
601
- }
602
-
603
- const current = getLocalVersion(providerId);
604
- const latest = fetchLatestVersion(providerId);
605
- const updateAvailable = isNewerVersion(current, latest);
606
-
607
- return {
608
- current,
609
- latest,
610
- updateAvailable,
611
- updateCommand: updateAvailable ? prov.version.update : null,
612
- };
613
- }
614
-
615
- /**
616
- * Check versions for all installed CLI providers in parallel.
617
- * Returns a map of providerId → version info.
618
- * Non-blocking: failures are silently ignored.
619
- */
620
- export function checkAllVersions() {
621
- const detected = detectAvailable();
622
- const results = {};
623
-
624
- for (const id of detected) {
625
- const prov = PROVIDERS[id];
626
- if (!prov?.version) continue;
627
- try {
628
- results[id] = checkProviderVersion(id);
629
- } catch {
630
- // Skip on failure — non-blocking
631
- }
632
- }
633
-
634
- return results;
635
- }
636
-
637
- /**
638
- * Execute the update command for a provider.
639
- * @param {string} providerId
640
- * @returns {boolean} true if update succeeded
641
- */
642
- export function updateProvider(providerId) {
643
- const prov = PROVIDERS[providerId];
644
- if (!prov?.version?.update) return false;
645
-
646
- try {
647
- log.info(`Updating ${prov.name}...`);
648
- execSync(prov.version.update, {
649
- encoding: 'utf-8',
650
- stdio: 'inherit',
651
- timeout: 120000, // 2 minute timeout for updates
652
- });
653
- log.info(`✅ ${prov.name} updated successfully`);
654
- return true;
655
- } catch (err) {
656
- log.warn(`Failed to update ${prov.name}: ${(err.message || '').substring(0, 100)}`);
657
- return false;
658
- }
659
- }
660
-
661
- // ──────────────────────────────────────────────
662
- // Rate Limit Detection
663
- // ──────────────────────────────────────────────
664
-
665
- /**
666
- * Parse rate limit error from CLI output.
667
- * Looks for: "try again at X:XX PM" or "try again at X:XX AM"
668
- * @param {string} output - Combined stdout+stderr text
669
- * @returns {{ retryAt: Date, retryAtStr: string } | null}
670
- */
671
- function parseRateLimitError(output) {
672
- if (!output) return null;
673
-
674
- // Match "usage limit" or "rate limit" patterns
675
- const isRateLimited = /usage limit|rate limit|too many requests/i.test(output);
676
- if (!isRateLimited) return null;
677
-
678
- // Extract time: "try again at 6:06 PM" or "try again at 18:06"
679
- const timeMatch = output.match(/try again at\s+(\d{1,2}:\d{2}(?::\d{2})?\s*(?:AM|PM)?)/i);
680
- if (!timeMatch) {
681
- // Rate limited but no specific time — estimate 30 minutes from now
682
- const retryAt = new Date(Date.now() + 30 * 60 * 1000);
683
- return { retryAt, retryAtStr: retryAt.toLocaleTimeString() };
684
- }
685
-
686
- const timeStr = timeMatch[1].trim();
687
- const now = new Date();
688
- const today = now.toISOString().split('T')[0]; // YYYY-MM-DD
689
-
690
- // Parse the time string
691
- let retryAt;
692
- if (/AM|PM/i.test(timeStr)) {
693
- // 12-hour format: "6:06 PM"
694
- retryAt = new Date(`${today} ${timeStr}`);
695
- } else {
696
- // 24-hour format: "18:06"
697
- retryAt = new Date(`${today}T${timeStr}`);
698
- }
699
-
700
- // If parsed time is in the past, it's tomorrow
701
- if (retryAt <= now) {
702
- retryAt.setDate(retryAt.getDate() + 1);
703
- }
704
-
705
- // Sanity check: if retry is more than 6 hours away, something's wrong
706
- if (retryAt - now > 6 * 60 * 60 * 1000) {
707
- retryAt = new Date(Date.now() + 30 * 60 * 1000);
708
- }
709
-
710
- return { retryAt, retryAtStr: timeStr };
711
- }
712
-
713
- // ──────────────────────────────────────────────
714
- // Quota Pre-Check
715
- // ──────────────────────────────────────────────
716
-
717
- /**
718
- * Check current Codex 7d quota usage before execution.
719
- * Reads the latest rollout file for quota data.
720
- *
721
- * @param {number} threshold - Percentage at which to block (default 97)
722
- * @returns {{ ok: boolean, quota5h: number|null, quota7d: number|null, warning: boolean }}
723
- */
724
- export function checkQuotaBeforeExecution(threshold = 97) {
725
- try {
726
- const sessionsDir = resolve(HOME, '.codex/sessions');
727
- if (!existsSync(sessionsDir)) return { ok: true, quota5h: null, quota7d: null, warning: false };
728
-
729
- // Find the most recent rollout file
730
- const raw = execSync(
731
- `find "${sessionsDir}" -name "rollout-*.jsonl" -type f | sort -r | head -1`,
732
- { encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'], timeout: 5000 }
733
- ).trim();
734
- if (!raw || !existsSync(raw)) return { ok: true, quota5h: null, quota7d: null, warning: false };
735
-
736
- // Get the last token_count event with rate_limits
737
- const line = execSync(
738
- `grep '"rate_limits"' "${raw}" | tail -1`,
739
- { encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'], timeout: 5000 }
740
- ).trim();
741
- if (!line) return { ok: true, quota5h: null, quota7d: null, warning: false };
742
-
743
- const data = JSON.parse(line);
744
- const limits = data?.payload?.rate_limits;
745
- if (!limits) return { ok: true, quota5h: null, quota7d: null, warning: false };
746
-
747
- const quota5h = limits.primary?.used_percent ?? null;
748
- const quota7d = limits.secondary?.used_percent ?? null;
749
-
750
- // Block if 7d quota exceeds threshold
751
- if (quota7d !== null && quota7d >= threshold) {
752
- return { ok: false, quota5h, quota7d, warning: false };
753
- }
754
-
755
- // Warn if 7d quota is high (>= 95%)
756
- const warning = quota7d !== null && quota7d >= 95;
757
- return { ok: true, quota5h, quota7d, warning };
758
- } catch {
759
- // Quota check failed don't block execution
760
- return { ok: true, quota5h: null, quota7d: null, warning: false };
761
- }
762
- }
763
-
764
- export const provider = {
765
- getProvider, getAllProviderIds, detectAvailable,
766
- buildProviderChoices, executePrompt, queryAI, classifyReview,
767
- checkProviderVersion, checkAllVersions, updateProvider,
768
- checkQuotaBeforeExecution,
769
- };
1
+ /**
2
+ * AI Provider Registry — supports multiple AI coding tools
3
+ *
4
+ * Each provider has its own invocation pattern:
5
+ * - Codex CLI: piped stdin → codex exec --full-auto
6
+ * - Claude Code: -p flag + --allowedTools for safe auto-execution
7
+ * - Cursor Agent: cursor-agent CLI with -p headless mode
8
+ * - Gemini CLI: gemini -p for non-interactive prompt
9
+ * - Codex Desktop / Cursor IDE / Antigravity IDE: clipboard + manual
10
+ */
11
+
12
+ import { execSync, spawn } from 'child_process';
13
+ import { readFileSync, writeFileSync, existsSync } from 'fs';
14
+ import { resolve } from 'path';
15
+ import { log } from './logger.js';
16
+ import { ask } from './prompt.js';
17
+ import { automator } from './automator.js';
18
+
19
+ const HOME = process.env.HOME || process.env.USERPROFILE || '~';
20
+
21
+ // ──────────────────────────────────────────────
22
+ // Provider Registry — each provider is unique
23
+ // ──────────────────────────────────────────────
24
+
25
+ const PROVIDERS = {
26
+ // ─── CLI Providers (auto-execute) ───
27
+
28
+ 'codex-cli': {
29
+ name: 'Codex CLI',
30
+ type: 'cli',
31
+ detect: 'codex',
32
+ // Codex uses piped stdin: cat file | codex exec --full-auto -
33
+ buildCommand: (promptPath, cwd) =>
34
+ `cat ${shellEscape(promptPath)} | codex exec --full-auto -`,
35
+ description: 'OpenAI Codex CLI — pipes prompt via stdin',
36
+ version: {
37
+ command: 'codex --version',
38
+ parse: (output) => output.match(/[\d.]+/)?.[0],
39
+ latest: { type: 'brew-cask', name: 'codex' },
40
+ update: 'brew upgrade --cask codex',
41
+ },
42
+ },
43
+
44
+ 'claude-code': {
45
+ name: 'Claude Code',
46
+ type: 'cli',
47
+ detect: 'claude',
48
+ // Claude Code uses -p (print/non-interactive) + --allowedTools for permissions
49
+ // Reads the file content and passes as argument (not piped)
50
+ buildCommand: (promptPath, cwd) => {
51
+ const escaped = shellEscape(promptPath);
52
+ // Use subshell to read file content into -p argument
53
+ return `claude -p "$(cat ${escaped})" --allowedTools "Bash(git*),Read,Write,Edit"`;
54
+ },
55
+ description: 'Anthropic Claude Code CLI — -p mode with tool permissions',
56
+ version: {
57
+ command: 'claude --version',
58
+ parse: (output) => output.match(/[\d.]+/)?.[0],
59
+ latest: { type: 'npm', name: '@anthropic-ai/claude-code' },
60
+ update: 'npm update -g @anthropic-ai/claude-code',
61
+ },
62
+ },
63
+
64
+ 'cursor-agent': {
65
+ name: 'Cursor Agent',
66
+ type: 'cli',
67
+ detect: 'cursor-agent',
68
+ // Cursor Agent uses -p flag for headless/non-interactive mode
69
+ buildCommand: (promptPath, cwd) => {
70
+ const escaped = shellEscape(promptPath);
71
+ return `cursor-agent -p "$(cat ${escaped})"`;
72
+ },
73
+ description: 'Cursor Agent CLI — headless -p mode',
74
+ // No standard package manager — skip version check
75
+ },
76
+
77
+ 'gemini-cli': {
78
+ name: 'Gemini CLI',
79
+ type: 'cli',
80
+ detect: 'gemini',
81
+ // Gemini CLI uses -p for non-interactive prompt execution
82
+ buildCommand: (promptPath, cwd) => {
83
+ const escaped = shellEscape(promptPath);
84
+ return `gemini -p "$(cat ${escaped})"`;
85
+ },
86
+ description: 'Google Gemini CLI — non-interactive -p mode',
87
+ version: {
88
+ command: 'gemini --version',
89
+ parse: (output) => output.match(/[\d.]+/)?.[0],
90
+ latest: { type: 'brew', name: 'gemini-cli' },
91
+ update: 'brew upgrade gemini-cli',
92
+ },
93
+ },
94
+
95
+ // ─── IDE Providers (clipboard + manual) ───
96
+
97
+ 'codex-desktop': {
98
+ name: 'Codex Desktop',
99
+ type: 'ide',
100
+ instructions: 'Open Codex Desktop → paste the prompt → execute',
101
+ displayPrompt: true, // Show the prompt content in terminal box
102
+ },
103
+
104
+ 'cursor': {
105
+ name: 'Cursor IDE',
106
+ type: 'ide',
107
+ instructions: 'Open Cursor → Ctrl/Cmd+I (Composer) → paste the prompt → run as Agent',
108
+ displayPrompt: false, // Too long to display, just copy to clipboard
109
+ },
110
+
111
+ 'antigravity': {
112
+ name: 'Antigravity (Gemini)',
113
+ type: 'ide',
114
+ instructions: 'Open Antigravity → paste the prompt into chat → execute',
115
+ displayPrompt: false,
116
+ },
117
+ };
118
+
119
+ /**
120
+ * Get a provider by ID
121
+ */
122
+ export function getProvider(id) {
123
+ return PROVIDERS[id] || null;
124
+ }
125
+
126
+ /**
127
+ * Get all provider IDs
128
+ */
129
+ export function getAllProviderIds() {
130
+ return Object.keys(PROVIDERS);
131
+ }
132
+
133
+ /**
134
+ * Detect which CLI providers are installed on the system
135
+ * @returns {string[]} list of available provider IDs
136
+ */
137
+ export function detectAvailable() {
138
+ const available = [];
139
+ for (const [id, prov] of Object.entries(PROVIDERS)) {
140
+ if (prov.type === 'cli' && prov.detect) {
141
+ try {
142
+ const cmd = process.platform === 'win32'
143
+ ? `where ${prov.detect}`
144
+ : `which ${prov.detect}`;
145
+ execSync(cmd, { stdio: 'pipe' });
146
+ available.push(id);
147
+ } catch {
148
+ // Not installed
149
+ }
150
+ }
151
+ }
152
+ return available;
153
+ }
154
+
155
+ /**
156
+ * Build the selection menu for init
157
+ * Groups CLIs first (with detection status), then IDEs
158
+ * @returns {{ label: string, value: string }[]}
159
+ */
160
+ export function buildProviderChoices(versionCache = {}) {
161
+ const detected = detectAvailable();
162
+ const choices = [];
163
+
164
+ // CLI providers first with detection indicator + version info
165
+ for (const [id, prov] of Object.entries(PROVIDERS)) {
166
+ if (prov.type === 'cli') {
167
+ const installed = detected.includes(id);
168
+ let tag = installed ? ' ✓ detected' : '';
169
+
170
+ // Append version info if available in cache
171
+ const vi = versionCache[id];
172
+ if (vi && vi.current) {
173
+ if (vi.updateAvailable) {
174
+ tag += ` (v${vi.current} → v${vi.latest} available)`;
175
+ } else if (vi.latest) {
176
+ tag += ` (v${vi.current} ✓ latest)`;
177
+ } else {
178
+ tag += ` (v${vi.current})`;
179
+ }
180
+ }
181
+
182
+ choices.push({
183
+ label: `${prov.name}${tag} — ${prov.description}`,
184
+ value: id,
185
+ available: installed,
186
+ });
187
+ }
188
+ }
189
+
190
+ // IDE providers — show auto-paste capability if recipe exists
191
+ for (const [id, prov] of Object.entries(PROVIDERS)) {
192
+ if (prov.type === 'ide') {
193
+ const hasAutoPaste = automator.hasRecipe(id);
194
+ const tag = hasAutoPaste ? 'auto-paste' : 'clipboard + manual';
195
+ choices.push({
196
+ label: `${prov.name} — ${tag}`,
197
+ value: id,
198
+ available: true,
199
+ });
200
+ }
201
+ }
202
+
203
+ return choices;
204
+ }
205
+
206
+ /**
207
+ * Execute a prompt using the configured provider
208
+ *
209
+ * CLI providers: auto-execute via their specific command
210
+ * IDE providers: copy to clipboard + display instructions + wait
211
+ *
212
+ * @param {string} providerId - Provider ID from config
213
+ * @param {string} promptPath - Absolute path to prompt file
214
+ * @param {string} cwd - Working directory
215
+ * @returns {Promise<{ ok: boolean, rateLimited?: boolean, retryAt?: Date }>}
216
+ */
217
+ export async function executePrompt(providerId, promptPath, cwd) {
218
+ const prov = PROVIDERS[providerId];
219
+
220
+ if (!prov) {
221
+ log.warn(`Unknown provider '${providerId}', falling back to clipboard mode`);
222
+ const ok = await clipboardFallback(promptPath);
223
+ return { ok };
224
+ }
225
+
226
+ if (prov.type === 'cli') {
227
+ return await executeCLI(prov, providerId, promptPath, cwd);
228
+ } else {
229
+ const ok = await executeIDE(prov, providerId, promptPath);
230
+ return { ok };
231
+ }
232
+ }
233
+
234
+ /**
235
+ * Execute via CLI provider — each tool has its own command pattern.
236
+ * Output is captured and filtered to show only file-level progress,
237
+ * keeping the terminal clean (like Claude Code's compact display).
238
+ */
239
+ async function executeCLI(prov, providerId, promptPath, cwd) {
240
+ // Verify the CLI is still available
241
+ if (prov.detect) {
242
+ try {
243
+ const cmd = process.platform === 'win32'
244
+ ? `where ${prov.detect}`
245
+ : `which ${prov.detect}`;
246
+ execSync(cmd, { stdio: 'pipe' });
247
+ } catch {
248
+ log.warn(`${prov.name} not found in PATH, falling back to clipboard mode`);
249
+ const ok = await clipboardFallback(promptPath);
250
+ return { ok };
251
+ }
252
+ }
253
+
254
+ const command = prov.buildCommand(promptPath, cwd);
255
+ log.info(`Executing via ${prov.name}...`);
256
+ log.dim(` \u2192 ${command.substring(0, 80)}${command.length > 80 ? '...' : ''}`);
257
+
258
+ return new Promise((resolvePromise) => {
259
+ const child = spawn('sh', ['-c', command], {
260
+ cwd,
261
+ stdio: ['pipe', 'pipe', 'pipe'],
262
+ });
263
+
264
+ let lastFile = '';
265
+ let statusText = command.substring(0, 80);
266
+ let lineBuffer = '';
267
+ let stderrBuffer = ''; // Capture stderr for rate limit detection
268
+ const FILE_EXT = /(?:^|\s|['"|(/])([a-zA-Z0-9_.\/-]+\.(?:rs|ts|js|jsx|tsx|py|go|toml|yaml|yml|json|md|css|html|sh|sql|prisma|vue|svelte))\b/;
269
+
270
+ // Spinner animation — gives a dynamic, alive feel
271
+ const SPINNER = ['\u280B', '\u2819', '\u2839', '\u2838', '\u283C', '\u2834', '\u2826', '\u2827', '\u2807', '\u280F'];
272
+ let spinIdx = 0;
273
+ const spinTimer = setInterval(() => {
274
+ const frame = SPINNER[spinIdx % SPINNER.length];
275
+ process.stdout.write(`\r\x1b[K \x1b[36m${frame}\x1b[0m ${statusText}`);
276
+ spinIdx++;
277
+ }, 80);
278
+
279
+ function processLine(line) {
280
+ const fileMatch = line.match(FILE_EXT);
281
+ if (fileMatch && fileMatch[1] !== lastFile) {
282
+ lastFile = fileMatch[1];
283
+ statusText = lastFile;
284
+ }
285
+ }
286
+
287
+ child.stdout.on('data', (data) => {
288
+ const text = data.toString();
289
+ lineBuffer += text;
290
+ stderrBuffer += text; // Also check stdout for rate limit messages
291
+ const lines = lineBuffer.split('\n');
292
+ lineBuffer = lines.pop();
293
+ for (const line of lines) processLine(line);
294
+ });
295
+
296
+ child.stderr.on('data', (data) => {
297
+ const text = data.toString();
298
+ stderrBuffer += text;
299
+ const trimmed = text.trim();
300
+ if (trimmed && !trimmed.includes('\u2588') && !trimmed.includes('progress')) {
301
+ for (const line of trimmed.split('\n').slice(0, 3)) {
302
+ if (line.trim()) log.dim(` ${line.substring(0, 120)}`);
303
+ }
304
+ }
305
+ });
306
+
307
+ child.on('close', (code) => {
308
+ clearInterval(spinTimer);
309
+ process.stdout.write('\r\x1b[K');
310
+ if (code === 0) {
311
+ log.info(`${prov.name} execution complete`);
312
+ resolvePromise({ ok: true });
313
+ } else {
314
+ // Check for rate limit error in captured output
315
+ const rateLimitInfo = parseRateLimitError(stderrBuffer);
316
+ if (rateLimitInfo) {
317
+ log.warn(`${prov.name} hit rate limit — retry at ${rateLimitInfo.retryAtStr}`);
318
+ resolvePromise({ ok: false, rateLimited: true, retryAt: rateLimitInfo.retryAt, retryAtStr: rateLimitInfo.retryAtStr });
319
+ } else {
320
+ log.warn(`${prov.name} exited with code ${code}`);
321
+ resolvePromise({ ok: false });
322
+ }
323
+ }
324
+ });
325
+
326
+ child.on('error', (err) => {
327
+ clearInterval(spinTimer);
328
+ process.stdout.write('\r\x1b[K');
329
+ log.warn(`${prov.name} execution failed: ${err.message}`);
330
+ resolvePromise({ ok: false });
331
+ });
332
+ });
333
+ }
334
+
335
+ /**
336
+ * Execute via IDE provider
337
+ *
338
+ * Priority: auto-paste (if IDE running) → manual clipboard fallback
339
+ */
340
+ async function executeIDE(prov, providerId, promptPath) {
341
+ const prompt = readFileSync(promptPath, 'utf-8');
342
+
343
+ // ── Try auto-paste first ──
344
+ if (automator.hasRecipe(providerId)) {
345
+ if (automator.isIDERunning(providerId)) {
346
+ log.info(`${prov.name} detected — attempting auto-paste...`);
347
+ const ok = automator.activateAndPaste(providerId, prompt);
348
+ if (ok) {
349
+ log.info(`✅ Prompt auto-pasted into ${prov.name}`);
350
+ log.blank();
351
+ await ask(`Press Enter after ${prov.name} development is complete...`);
352
+ return true;
353
+ }
354
+ log.warn('Auto-paste failed, falling back to manual mode');
355
+ } else {
356
+ log.warn(`${prov.name} is not running — using clipboard mode`);
357
+ }
358
+ }
359
+
360
+ // ── Manual fallback ──
361
+ log.blank();
362
+ log.info(`📋 ${prov.instructions}`);
363
+ log.dim(` Prompt file: ${promptPath}`);
364
+ log.blank();
365
+
366
+ // Some providers benefit from seeing the prompt in terminal
367
+ if (prov.displayPrompt) {
368
+ const lines = prompt.split('\n');
369
+ const maxLines = 30;
370
+ const show = lines.slice(0, maxLines);
371
+ console.log(' ┌─── Prompt Preview ─────────────────────────────────────┐');
372
+ for (const line of show) {
373
+ console.log(` │ ${line}`);
374
+ }
375
+ if (lines.length > maxLines) {
376
+ console.log(` │ ... (${lines.length - maxLines} more lines — see full file)`);
377
+ }
378
+ console.log(' └────────────────────────────────────────────────────────┘');
379
+ log.blank();
380
+ }
381
+
382
+ copyToClipboard(prompt);
383
+
384
+ await ask(`Press Enter after ${prov.name} development is complete...`);
385
+ return true;
386
+ }
387
+
388
+ /**
389
+ * Fallback: copy to clipboard and wait for any provider
390
+ */
391
+ async function clipboardFallback(promptPath) {
392
+ const prompt = readFileSync(promptPath, 'utf-8');
393
+
394
+ log.blank();
395
+ log.info('📋 Paste the prompt into your AI coding tool and execute');
396
+ log.dim(` Prompt file: ${promptPath}`);
397
+ log.blank();
398
+
399
+ copyToClipboard(prompt);
400
+
401
+ await ask('Press Enter after development is complete...');
402
+ return true;
403
+ }
404
+
405
+ function copyToClipboard(text) {
406
+ try {
407
+ if (process.platform === 'darwin') {
408
+ execSync('pbcopy', { input: text, stdio: ['pipe', 'pipe', 'pipe'] });
409
+ } else if (process.platform === 'linux') {
410
+ // Try xclip first, then xsel
411
+ try {
412
+ execSync('xclip -selection clipboard', { input: text, stdio: ['pipe', 'pipe', 'pipe'] });
413
+ } catch {
414
+ execSync('xsel --clipboard --input', { input: text, stdio: ['pipe', 'pipe', 'pipe'] });
415
+ }
416
+ } else if (process.platform === 'win32') {
417
+ execSync('clip', { input: text, stdio: ['pipe', 'pipe', 'pipe'] });
418
+ }
419
+ log.info('📋 Copied to clipboard');
420
+ } catch {
421
+ log.dim('(Could not copy to clipboard — copy the file manually)');
422
+ }
423
+ }
424
+
425
+ function shellEscape(str) {
426
+ if (process.platform === 'win32') {
427
+ return `"${str.replace(/"/g, '\\"')}"`;
428
+ }
429
+ return `'${str.replace(/'/g, "'\\''")}'`;
430
+ }
431
+
432
+ /**
433
+ * Lightweight AI query capture output rather than inherit stdio.
434
+ * Only works for CLI providers. Returns null for IDE providers.
435
+ *
436
+ * @param {string} providerId - Provider ID
437
+ * @param {string} question - The question/prompt text
438
+ * @param {string} cwd - Working directory
439
+ * @returns {Promise<string|null>} AI response text, or null if unsupported/failed
440
+ */
441
+ export async function queryAI(providerId, question, cwd) {
442
+ const prov = PROVIDERS[providerId];
443
+ if (!prov || prov.type !== 'cli') return null;
444
+
445
+ // Verify CLI is available
446
+ if (prov.detect) {
447
+ try {
448
+ const cmd = process.platform === 'win32'
449
+ ? `where ${prov.detect}`
450
+ : `which ${prov.detect}`;
451
+ execSync(cmd, { stdio: 'pipe' });
452
+ } catch {
453
+ return null;
454
+ }
455
+ }
456
+
457
+ // Write question to temp file
458
+ const tmpPath = resolve(cwd, '.codex-copilot/_query_prompt.md');
459
+ writeFileSync(tmpPath, question);
460
+
461
+ const command = prov.buildCommand(tmpPath, cwd);
462
+
463
+ try {
464
+ const output = execSync(command, {
465
+ cwd,
466
+ encoding: 'utf-8',
467
+ stdio: ['pipe', 'pipe', 'pipe'],
468
+ timeout: 60000, // 60s timeout for classification
469
+ });
470
+ return output.trim();
471
+ } catch (err) {
472
+ log.dim(`AI query failed: ${(err.message || '').substring(0, 80)}`);
473
+ return null;
474
+ }
475
+ }
476
+
477
+ /**
478
+ * Use AI to classify code review feedback.
479
+ *
480
+ * Returns 'pass' if AI determines no actionable issues,
481
+ * 'fix' if there are issues to address, or null if classification failed.
482
+ *
483
+ * @param {string} providerId - Provider ID
484
+ * @param {string} feedbackText - The collected review feedback
485
+ * @param {string} cwd - Working directory
486
+ * @returns {Promise<'pass'|'fix'|null>}
487
+ */
488
+ export async function classifyReview(providerId, feedbackText, cwd) {
489
+ const classificationPrompt = `You are a code review classifier. Your ONLY job is to determine if the following code review feedback contains actionable issues that require code changes.
490
+
491
+ ## Code Review Feedback
492
+ ${feedbackText}
493
+
494
+ ## Instructions
495
+ - If the review says the code looks good, has no issues, is purely informational, or explicitly states no changes are needed: output exactly PASS
496
+ - If the review requests specific code changes, points out bugs, security issues, or improvements that need action: output exactly FIX
497
+
498
+ IMPORTANT: Output ONLY a single word on the first line: either PASS or FIX. No other text.`;
499
+
500
+ const response = await queryAI(providerId, classificationPrompt, cwd);
501
+ if (!response) return null;
502
+
503
+ // Parse the first meaningful line
504
+ const firstLine = response.split('\n').map(l => l.trim()).find(l => l.length > 0);
505
+ if (!firstLine) return null;
506
+
507
+ const upper = firstLine.toUpperCase();
508
+ if (upper.includes('PASS')) return 'pass';
509
+ if (upper.includes('FIX')) return 'fix';
510
+
511
+ return null; // Ambiguous caller decides fallback
512
+ }
513
+
514
+ // ──────────────────────────────────────────────
515
+ // Version Check & Auto-Update
516
+ // ──────────────────────────────────────────────
517
+
518
+ /**
519
+ * Compare two semver-like version strings.
520
+ * Returns true if latest > current.
521
+ */
522
+ function isNewerVersion(current, latest) {
523
+ if (!current || !latest) return false;
524
+ const a = current.split('.').map(Number);
525
+ const b = latest.split('.').map(Number);
526
+ const len = Math.max(a.length, b.length);
527
+ for (let i = 0; i < len; i++) {
528
+ const av = a[i] || 0;
529
+ const bv = b[i] || 0;
530
+ if (bv > av) return true;
531
+ if (bv < av) return false;
532
+ }
533
+ return false;
534
+ }
535
+
536
+ /**
537
+ * Get the locally installed version of a provider.
538
+ * @returns {string|null} version string or null
539
+ */
540
+ function getLocalVersion(providerId) {
541
+ const prov = PROVIDERS[providerId];
542
+ if (!prov?.version) return null;
543
+ try {
544
+ const output = execSync(prov.version.command, {
545
+ encoding: 'utf-8',
546
+ stdio: ['pipe', 'pipe', 'pipe'],
547
+ timeout: 5000,
548
+ }).trim();
549
+ return prov.version.parse(output);
550
+ } catch {
551
+ return null;
552
+ }
553
+ }
554
+
555
+ /**
556
+ * Fetch the latest available version from the package registry.
557
+ * @returns {string|null} latest version string or null
558
+ */
559
+ function fetchLatestVersion(providerId) {
560
+ const prov = PROVIDERS[providerId];
561
+ if (!prov?.version?.latest) return null;
562
+
563
+ const { type, name } = prov.version.latest;
564
+ try {
565
+ if (type === 'npm') {
566
+ return execSync(`npm view ${name} version`, {
567
+ encoding: 'utf-8',
568
+ stdio: ['pipe', 'pipe', 'pipe'],
569
+ timeout: 10000,
570
+ }).trim();
571
+ }
572
+ if (type === 'brew') {
573
+ const json = execSync(`brew info ${name} --json=v2`, {
574
+ encoding: 'utf-8',
575
+ stdio: ['pipe', 'pipe', 'pipe'],
576
+ timeout: 10000,
577
+ });
578
+ const data = JSON.parse(json);
579
+ return data.formulae?.[0]?.versions?.stable || null;
580
+ }
581
+ if (type === 'brew-cask') {
582
+ const json = execSync(`brew info --cask ${name} --json=v2`, {
583
+ encoding: 'utf-8',
584
+ stdio: ['pipe', 'pipe', 'pipe'],
585
+ timeout: 10000,
586
+ });
587
+ const data = JSON.parse(json);
588
+ return data.casks?.[0]?.version || null;
589
+ }
590
+ } catch {
591
+ return null;
592
+ }
593
+ return null;
594
+ }
595
+
596
+ /**
597
+ * Check version status for a single provider.
598
+ * @param {string} providerId
599
+ * @returns {{ current: string|null, latest: string|null, updateAvailable: boolean, updateCommand: string|null }}
600
+ */
601
+ export function checkProviderVersion(providerId) {
602
+ const prov = PROVIDERS[providerId];
603
+ if (!prov?.version) {
604
+ return { current: null, latest: null, updateAvailable: false, updateCommand: null };
605
+ }
606
+
607
+ const current = getLocalVersion(providerId);
608
+ const latest = fetchLatestVersion(providerId);
609
+ const updateAvailable = isNewerVersion(current, latest);
610
+
611
+ return {
612
+ current,
613
+ latest,
614
+ updateAvailable,
615
+ updateCommand: updateAvailable ? prov.version.update : null,
616
+ };
617
+ }
618
+
619
+ /**
620
+ * Check versions for all installed CLI providers in parallel.
621
+ * Returns a map of providerId → version info.
622
+ * Non-blocking: failures are silently ignored.
623
+ */
624
+ export function checkAllVersions() {
625
+ const detected = detectAvailable();
626
+ const results = {};
627
+
628
+ for (const id of detected) {
629
+ const prov = PROVIDERS[id];
630
+ if (!prov?.version) continue;
631
+ try {
632
+ results[id] = checkProviderVersion(id);
633
+ } catch {
634
+ // Skip on failure — non-blocking
635
+ }
636
+ }
637
+
638
+ return results;
639
+ }
640
+
641
+ /**
642
+ * Execute the update command for a provider.
643
+ * @param {string} providerId
644
+ * @returns {boolean} true if update succeeded
645
+ */
646
+ export function updateProvider(providerId) {
647
+ const prov = PROVIDERS[providerId];
648
+ if (!prov?.version?.update) return false;
649
+
650
+ try {
651
+ log.info(`Updating ${prov.name}...`);
652
+ execSync(prov.version.update, {
653
+ encoding: 'utf-8',
654
+ stdio: 'inherit',
655
+ timeout: 120000, // 2 minute timeout for updates
656
+ });
657
+ log.info(`✅ ${prov.name} updated successfully`);
658
+ return true;
659
+ } catch (err) {
660
+ log.warn(`Failed to update ${prov.name}: ${(err.message || '').substring(0, 100)}`);
661
+ return false;
662
+ }
663
+ }
664
+
665
+ // ──────────────────────────────────────────────
666
+ // Rate Limit Detection
667
+ // ──────────────────────────────────────────────
668
+
669
+ /**
670
+ * Parse rate limit error from CLI output.
671
+ * Looks for: "try again at X:XX PM" or "try again at X:XX AM"
672
+ * @param {string} output - Combined stdout+stderr text
673
+ * @returns {{ retryAt: Date, retryAtStr: string } | null}
674
+ */
675
+ function parseRateLimitError(output) {
676
+ if (!output) return null;
677
+
678
+ // Match "usage limit" or "rate limit" patterns
679
+ const isRateLimited = /usage limit|rate limit|too many requests/i.test(output);
680
+ if (!isRateLimited) return null;
681
+
682
+ // Extract time: "try again at 6:06 PM" or "try again at 18:06"
683
+ const timeMatch = output.match(/try again at\s+(\d{1,2}:\d{2}(?::\d{2})?\s*(?:AM|PM)?)/i);
684
+ if (!timeMatch) {
685
+ // Rate limited but no specific time — estimate 30 minutes from now
686
+ const retryAt = new Date(Date.now() + 30 * 60 * 1000);
687
+ return { retryAt, retryAtStr: retryAt.toLocaleTimeString() };
688
+ }
689
+
690
+ const timeStr = timeMatch[1].trim();
691
+ const now = new Date();
692
+ const today = now.toISOString().split('T')[0]; // YYYY-MM-DD
693
+
694
+ // Parse the time string
695
+ let retryAt;
696
+ if (/AM|PM/i.test(timeStr)) {
697
+ // 12-hour format: "6:06 PM"
698
+ retryAt = new Date(`${today} ${timeStr}`);
699
+ } else {
700
+ // 24-hour format: "18:06"
701
+ retryAt = new Date(`${today}T${timeStr}`);
702
+ }
703
+
704
+ // If parsed time is in the past, it's tomorrow
705
+ if (retryAt <= now) {
706
+ retryAt.setDate(retryAt.getDate() + 1);
707
+ }
708
+
709
+ // Sanity check: if retry is more than 6 hours away, something's wrong
710
+ if (retryAt - now > 6 * 60 * 60 * 1000) {
711
+ retryAt = new Date(Date.now() + 30 * 60 * 1000);
712
+ }
713
+
714
+ return { retryAt, retryAtStr: timeStr };
715
+ }
716
+
717
+ // ──────────────────────────────────────────────
718
+ // Quota Pre-Check
719
+ // ──────────────────────────────────────────────
720
+
721
+ /**
722
+ * Check current Codex 7d quota usage before execution.
723
+ * Reads the latest rollout file for quota data.
724
+ *
725
+ * @param {number} threshold - Percentage at which to block (default 97)
726
+ * @returns {{ ok: boolean, quota5h: number|null, quota7d: number|null, warning: boolean }}
727
+ */
728
+ export function checkQuotaBeforeExecution(threshold = 97) {
729
+ try {
730
+ const sessionsDir = resolve(HOME, '.codex/sessions');
731
+ if (!existsSync(sessionsDir)) return { ok: true, quota5h: null, quota7d: null, warning: false };
732
+
733
+ // Find the most recent rollout file
734
+ const raw = execSync(
735
+ `find "${sessionsDir}" -name "rollout-*.jsonl" -type f | sort -r | head -1`,
736
+ { encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'], timeout: 5000 }
737
+ ).trim();
738
+ if (!raw || !existsSync(raw)) return { ok: true, quota5h: null, quota7d: null, warning: false };
739
+
740
+ // Get the last token_count event with rate_limits
741
+ const line = execSync(
742
+ `grep '"rate_limits"' "${raw}" | tail -1`,
743
+ { encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'], timeout: 5000 }
744
+ ).trim();
745
+ if (!line) return { ok: true, quota5h: null, quota7d: null, warning: false };
746
+
747
+ const data = JSON.parse(line);
748
+ const limits = data?.payload?.rate_limits;
749
+ if (!limits) return { ok: true, quota5h: null, quota7d: null, warning: false };
750
+
751
+ const quota5h = limits.primary?.used_percent ?? null;
752
+ const quota7d = limits.secondary?.used_percent ?? null;
753
+
754
+ // Block if 7d quota exceeds threshold
755
+ if (quota7d !== null && quota7d >= threshold) {
756
+ return { ok: false, quota5h, quota7d, warning: false };
757
+ }
758
+
759
+ // Warn if 7d quota is high (>= 95%)
760
+ const warning = quota7d !== null && quota7d >= 95;
761
+ return { ok: true, quota5h, quota7d, warning };
762
+ } catch {
763
+ // Quota check failed — don't block execution
764
+ return { ok: true, quota5h: null, quota7d: null, warning: false };
765
+ }
766
+ }
767
+
768
+ export const provider = {
769
+ getProvider, getAllProviderIds, detectAvailable,
770
+ buildProviderChoices, executePrompt, queryAI, classifyReview,
771
+ checkProviderVersion, checkAllVersions, updateProvider,
772
+ checkQuotaBeforeExecution,
773
+ };