@ctxthuta/cxops 1.0.3 → 1.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # CortexOps Multi-Agent Framework
2
2
 
3
- An autonomous, multi-agent engineering and scientific research operating system built for high-throughput software delivery and academic research, operating both as **Native Google Antigravity Subagents** and as a **Standalone Python Multi-Agent Framework** (`google-antigravity` SDK).
3
+ An autonomous, multi-agent engineering and scientific research operating system built for high-throughput software delivery and academic research, operating as **Native Google Antigravity Subagents**.
4
4
 
5
5
  Integrated with the [ThutaCortex](file:///home/lenovo/Documents/ThutaCortex) second brain for institutional memory, architectural pattern retrieval, and automated knowledge ingestion.
6
6
 
@@ -82,16 +82,29 @@ When working inside Google Antigravity (IDE or CLI):
82
82
  - Subagents execute directly through Antigravity's authenticated session.
83
83
  - Mention individual specialists directly (`@backend_engineer`, `@system_architect`, `@code_reviewer`), or mention `@cxagents` to mobilize the entire relevant team concurrently.
84
84
 
85
- ### Mode B: Standalone Python Framework (Terminal / CI / Headless)
85
+ <!--
86
+ ### Mode B: Standalone Multi-Engine Framework (Terminal / CI / Headless)
86
87
  When running outside Antigravity as an automated background process:
87
- - Configure your Gemini API key:
88
- ```bash
88
+ - Configure your preferred engine (default: antigravity):
89
+ # Antigravity (Google DeepMind SDK, default)
89
90
  export GEMINI_API_KEY="your-gemini-api-key"
90
- ```
91
- - Run tasks via the Python driver:
92
- ```bash
93
- ./cx run "Research streaming anomaly detection on arXiv, produce an architecture design, and implement an in-memory streaming detector in Python with passing unit tests."
94
- ```
91
+
92
+ # Claude (Anthropic)
93
+ export ANTHROPIC_API_KEY="your-anthropic-api-key"
94
+
95
+ # Codex (OpenAI)
96
+ export OPENAI_API_KEY="your-openai-api-key"
97
+
98
+ - Run tasks with your preferred execution harness:
99
+ # Default Antigravity engine (Gemini 3.8 models)
100
+ cxops run "Research streaming anomaly detection and implement an in-memory detector with unit tests."
101
+
102
+ # Anthropic Claude engine (Claude 3.7 / 3.5 Sonnet)
103
+ cxops run -e claude "Design high-throughput event sourcing microservice."
104
+
105
+ # OpenAI Codex engine (GPT-4o / o3-mini)
106
+ cxops run -e codex "Generate relational PostgreSQL DDL with composite indexes."
107
+ -->
95
108
 
96
109
  ---
97
110
 
package/bin/cxops.js CHANGED
@@ -49,6 +49,53 @@ function loadEnvFile() {
49
49
 
50
50
  loadEnvFile();
51
51
 
52
+ function saveEnvKey(key, value) {
53
+ const cleanKey = key.trim();
54
+ const cleanVal = (value || '').trim().replace(/[\r\n]/g, '');
55
+ const savePaths = [
56
+ path.join(ROOT_DIR, '.env'),
57
+ path.join(os.homedir(), '.cortexops', '.env'),
58
+ ];
59
+
60
+ for (const envPath of savePaths) {
61
+ try {
62
+ const envDir = path.dirname(envPath);
63
+ if (!fs.existsSync(envDir)) {
64
+ fs.mkdirSync(envDir, { recursive: true });
65
+ }
66
+ let content = '';
67
+ if (fs.existsSync(envPath)) {
68
+ content = fs.readFileSync(envPath, 'utf-8');
69
+ const regex = new RegExp(`^${cleanKey}=.*$`, 'm');
70
+ if (regex.test(content)) {
71
+ content = content.replace(regex, `${cleanKey}=${cleanVal}`);
72
+ } else {
73
+ content += (content.endsWith('\n') ? '' : '\n') + `${cleanKey}=${cleanVal}\n`;
74
+ }
75
+ } else {
76
+ content = `${cleanKey}=${cleanVal}\n`;
77
+ }
78
+ fs.writeFileSync(envPath, content, { mode: 0o600 });
79
+ } catch (_) {}
80
+ }
81
+ process.env[cleanKey] = cleanVal;
82
+ }
83
+
84
+ function normalizeEngine(input) {
85
+ if (!input) return null;
86
+ const clean = input.trim().toLowerCase();
87
+ if (['antigravity', 'gemini', 'ag'].includes(clean)) {
88
+ return 'antigravity';
89
+ }
90
+ if (['claude', 'anthropic'].includes(clean)) {
91
+ return 'claude';
92
+ }
93
+ if (['codex', 'openai', 'chatgpt'].includes(clean)) {
94
+ return 'codex';
95
+ }
96
+ return null;
97
+ }
98
+
52
99
  function getVenvPython() {
53
100
  const isWin = process.platform === 'win32';
54
101
  const venvPython = isWin
@@ -218,53 +265,78 @@ async function runSetup() {
218
265
  console.log(' Warning: Python 3.10+ is required for subagents and telemetry.');
219
266
  }
220
267
 
221
- console.log('\n[2] Authentication & API Keys:');
222
- const existingKey = process.env.GEMINI_API_KEY;
223
- if (existingKey) {
224
- console.log(' * GEMINI_API_KEY is already set in your environment.');
225
- } else {
226
- const hasKey = await rl.question(' Do you have a Gemini API key for standalone execution? (y/n) [y]: ');
227
- if (hasKey.trim().toLowerCase() !== 'n') {
228
- const keyInput = await rl.question(' Enter your GEMINI_API_KEY: ');
229
- const cleanKey = keyInput.trim().replace(/[\r\n]/g, '');
230
- if (cleanKey) {
231
- const savePaths = [
232
- path.join(ROOT_DIR, '.env'),
233
- path.join(os.homedir(), '.cortexops', '.env'),
234
- ];
235
- for (const envPath of savePaths) {
236
- const envDir = path.dirname(envPath);
237
- if (!fs.existsSync(envDir)) {
238
- fs.mkdirSync(envDir, { recursive: true });
239
- }
240
- let content = '';
241
- if (fs.existsSync(envPath)) {
242
- content = fs.readFileSync(envPath, 'utf-8');
243
- if (content.includes('GEMINI_API_KEY=')) {
244
- content = content.replace(/GEMINI_API_KEY=.*(\r?\n|$)/g, `GEMINI_API_KEY=${cleanKey}\n`);
245
- } else {
246
- content += (content.endsWith('\n') ? '' : '\n') + `GEMINI_API_KEY=${cleanKey}\n`;
247
- }
248
- } else {
249
- content = `GEMINI_API_KEY=${cleanKey}\n`;
250
- }
251
- fs.writeFileSync(envPath, content, { mode: 0o600 });
252
- console.log(` * Saved GEMINI_API_KEY to ${envPath} (mode 0600)`);
268
+ /*
269
+ // Standalone execution engine and authentication setup (temporarily inactive)
270
+ console.log('\n[2] Execution Engine & Platform Selection:');
271
+ const defaultEngine = (process.env.CORTEXOPS_ENGINE || 'antigravity').toLowerCase();
272
+ console.log(' Available Execution Harnesses:');
273
+ console.log(' - antigravity: Google Antigravity SDK with Gemini 3.8 models (Default)');
274
+ console.log(' - claude: Anthropic Claude models (Claude 3.7 / 3.5 Sonnet)');
275
+ console.log(' - codex: OpenAI Codex / GPT-4o / o3-mini models');
276
+
277
+ const enginePrompt = await rl.question(` Select default engine [antigravity | claude | codex] (default: ${defaultEngine}): `);
278
+ const resolvedEngine = normalizeEngine(enginePrompt) || defaultEngine || 'antigravity';
279
+ saveEnvKey('CORTEXOPS_ENGINE', resolvedEngine);
280
+ console.log(` * Configured execution engine: ${resolvedEngine}`);
281
+
282
+ console.log('\n[3] Authentication & API Keys:');
283
+ if (resolvedEngine === 'antigravity') {
284
+ const existingKey = process.env.GEMINI_API_KEY;
285
+ if (existingKey) {
286
+ console.log(' * GEMINI_API_KEY is already configured.');
287
+ } else {
288
+ const hasKey = await rl.question(' Configure GEMINI_API_KEY for Antigravity engine? (y/n) [y]: ');
289
+ if (hasKey.trim().toLowerCase() !== 'n') {
290
+ const keyInput = await rl.question(' Enter your GEMINI_API_KEY: ');
291
+ const cleanKey = keyInput.trim().replace(/[\r\n]/g, '');
292
+ if (cleanKey) {
293
+ saveEnvKey('GEMINI_API_KEY', cleanKey);
294
+ console.log(' * Saved GEMINI_API_KEY to configuration files (mode 0600)');
295
+ }
296
+ } else {
297
+ console.log(' * Skipping API key. Antigravity IDE sessions will authenticate automatically.');
298
+ }
299
+ }
300
+ } else if (resolvedEngine === 'claude') {
301
+ const existingKey = process.env.ANTHROPIC_API_KEY;
302
+ if (existingKey) {
303
+ console.log(' * ANTHROPIC_API_KEY is already configured.');
304
+ } else {
305
+ const hasKey = await rl.question(' Configure ANTHROPIC_API_KEY for Claude engine? (y/n) [y]: ');
306
+ if (hasKey.trim().toLowerCase() !== 'n') {
307
+ const keyInput = await rl.question(' Enter your ANTHROPIC_API_KEY: ');
308
+ const cleanKey = keyInput.trim().replace(/[\r\n]/g, '');
309
+ if (cleanKey) {
310
+ saveEnvKey('ANTHROPIC_API_KEY', cleanKey);
311
+ console.log(' * Saved ANTHROPIC_API_KEY to configuration files (mode 0600)');
253
312
  }
254
- process.env.GEMINI_API_KEY = cleanKey;
255
313
  }
314
+ }
315
+ } else if (resolvedEngine === 'codex') {
316
+ const existingKey = process.env.OPENAI_API_KEY;
317
+ if (existingKey) {
318
+ console.log(' * OPENAI_API_KEY is already configured.');
256
319
  } else {
257
- console.log(' * Skipping API key. Antigravity IDE sessions will use existing authenticated session.');
320
+ const hasKey = await rl.question(' Configure OPENAI_API_KEY for Codex engine? (y/n) [y]: ');
321
+ if (hasKey.trim().toLowerCase() !== 'n') {
322
+ const keyInput = await rl.question(' Enter your OPENAI_API_KEY: ');
323
+ const cleanKey = keyInput.trim().replace(/[\r\n]/g, '');
324
+ if (cleanKey) {
325
+ saveEnvKey('OPENAI_API_KEY', cleanKey);
326
+ console.log(' * Saved OPENAI_API_KEY to configuration files (mode 0600)');
327
+ }
328
+ }
258
329
  }
259
330
  }
331
+ */
260
332
 
261
- console.log('\n[3] Antigravity Global Plugin Registration:');
333
+ console.log('\n[2] Antigravity Global Plugin Registration:');
262
334
  const linkChoice = await rl.question(' Register CortexOps global plugin for Antigravity sessions? (y/n) [y]: ');
263
335
  if (linkChoice.trim().toLowerCase() !== 'n') {
264
336
  linkPlugin();
265
337
  }
266
338
 
267
- console.log('\n[4] Second Brain Integration (ThutaCortex):');
339
+ console.log('\n[3] Second Brain Integration (ThutaCortex):');
268
340
  const defaultVault = path.join(os.homedir(), 'Documents', 'ThutaCortex');
269
341
  const vaultChoice = await rl.question(` ThutaCortex vault path [${defaultVault}]: `);
270
342
  const resolvedVault = vaultChoice.trim() || defaultVault;
@@ -276,7 +348,7 @@ async function runSetup() {
276
348
  console.log(' The framework will operate in local-only mode until the vault is initialized.');
277
349
  }
278
350
 
279
- console.log('\n[5] Python Virtual Environment & Dependencies:');
351
+ console.log('\n[4] Python Virtual Environment & Dependencies:');
280
352
  const venvDir = path.join(ROOT_DIR, '.venv');
281
353
  if (fs.existsSync(venvDir)) {
282
354
  console.log(' * Virtual environment already exists at .venv/');
@@ -303,18 +375,26 @@ async function runSetup() {
303
375
  }
304
376
  }
305
377
 
306
- console.log('\n[6] Subagent Definition Verification:');
378
+ console.log('\n[5] Subagent Definition Verification:');
307
379
  const py = getVenvPython();
308
380
  if (py && fs.existsSync(VERIFY_SCRIPT)) {
309
381
  spawnSync(py, [VERIFY_SCRIPT], { stdio: 'inherit', env: { ...process.env, PYTHONPATH: ROOT_DIR } });
310
382
  }
311
383
 
312
384
  console.log('\n' + '='.repeat(70));
313
- console.log('Setup complete. You can now use:');
314
- console.log(' cxops status Display the operational & token telemetry dashboard');
315
- console.log(' cxops watch Continuously monitor the live dashboard');
316
- console.log(' cxops verify Verify all 12 subagent definitions');
317
- console.log(' cxops run "<goal>" Dispatch autonomous tasks via Python SDK');
385
+ console.log('Setup complete. CortexOps subagents are active in Antigravity.');
386
+ console.log('You can now:');
387
+ console.log(' - Type @<agent> or @cxagents in Antigravity chat');
388
+ console.log(' - cxops status Display operational & token telemetry dashboard');
389
+ console.log(' - cxops watch Continuously monitor the live dashboard');
390
+ console.log(' - cxops verify Verify all 12 subagent definitions');
391
+ console.log(' - cxops doctor Run diagnostic health check');
392
+ /*
393
+ // Standalone task runner commands (temporarily inactive)
394
+ console.log(' cxops run "<goal>" Dispatch autonomous tasks (Default: antigravity)');
395
+ console.log(' cxops run -e claude "<goal>" Dispatch tasks using Claude');
396
+ console.log(' cxops run -e codex "<goal>" Dispatch tasks using Codex');
397
+ */
318
398
  console.log('='.repeat(70));
319
399
  } finally {
320
400
  rl.close();
@@ -349,6 +429,45 @@ function runDoctor() {
349
429
  console.log('[WARN] Virtual Environment: .venv not found. Run "cxops setup" to create.');
350
430
  }
351
431
 
432
+ /*
433
+ // Standalone execution engine and API key diagnostics (temporarily inactive)
434
+ const activeEngine = (process.env.CORTEXOPS_ENGINE || 'antigravity').toLowerCase();
435
+ const isDefaultEngine = !process.env.CORTEXOPS_ENGINE || activeEngine === 'antigravity';
436
+ console.log(`[PASS] Execution Engine: ${activeEngine} ${isDefaultEngine ? '(Default)' : ''}`);
437
+
438
+ const geminiKey = process.env.GEMINI_API_KEY;
439
+ const anthropicKey = process.env.ANTHROPIC_API_KEY;
440
+ const openaiKey = process.env.OPENAI_API_KEY;
441
+
442
+ if (activeEngine === 'antigravity') {
443
+ if (geminiKey) {
444
+ console.log('[PASS] Antigravity Auth: GEMINI_API_KEY is configured.');
445
+ } else {
446
+ console.log('[INFO] Antigravity Auth: GEMINI_API_KEY not in environment. Antigravity IDE sessions will authenticate automatically.');
447
+ }
448
+ } else if (activeEngine === 'claude') {
449
+ if (anthropicKey) {
450
+ console.log('[PASS] Claude Auth: ANTHROPIC_API_KEY is configured.');
451
+ } else {
452
+ console.log('[WARN] Claude Auth: ANTHROPIC_API_KEY not configured. Run "cxops setup" to set.');
453
+ }
454
+ } else if (activeEngine === 'codex') {
455
+ if (openaiKey) {
456
+ console.log('[PASS] Codex Auth: OPENAI_API_KEY is configured.');
457
+ } else {
458
+ console.log('[WARN] Codex Auth: OPENAI_API_KEY not configured. Run "cxops setup" to set.');
459
+ }
460
+ }
461
+
462
+ const secondaryKeys = [];
463
+ if (activeEngine !== 'antigravity' && geminiKey) secondaryKeys.push('GEMINI_API_KEY');
464
+ if (activeEngine !== 'claude' && anthropicKey) secondaryKeys.push('ANTHROPIC_API_KEY');
465
+ if (activeEngine !== 'codex' && openaiKey) secondaryKeys.push('OPENAI_API_KEY');
466
+ if (secondaryKeys.length > 0) {
467
+ console.log(`[PASS] Additional Keys Configured: ${secondaryKeys.join(', ')}`);
468
+ }
469
+ */
470
+
352
471
  // Antigravity global plugin link status
353
472
  const { targets } = getPluginTargets();
354
473
  let linkFound = false;
@@ -382,14 +501,6 @@ function runDoctor() {
382
501
  console.log(`[INFO] ThutaCortex Second Brain: Not present at ${vaultPath} (Local fallback mode)`);
383
502
  }
384
503
 
385
- // Gemini API key authentication
386
- const apiKey = process.env.GEMINI_API_KEY;
387
- if (apiKey) {
388
- console.log('[PASS] Authentication: GEMINI_API_KEY is configured.');
389
- } else {
390
- console.log('[INFO] Authentication: GEMINI_API_KEY not in environment. Antigravity IDE sessions will authenticate automatically.');
391
- }
392
-
393
504
  // Subagent declarative definitions check
394
505
  const pluginAgentsDir = path.join(PLUGIN_SOURCE, 'agents');
395
506
  if (fs.existsSync(pluginAgentsDir)) {
@@ -405,10 +516,10 @@ function getPackageVersion() {
405
516
  const pkgPath = path.join(ROOT_DIR, 'package.json');
406
517
  if (fs.existsSync(pkgPath)) {
407
518
  const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
408
- return pkg.version || '1.0.3';
519
+ return pkg.version || '1.0.4';
409
520
  }
410
521
  } catch (_) {}
411
- return '1.0.3';
522
+ return '1.0.4';
412
523
  }
413
524
 
414
525
  function fetchLatestNpmVersion() {
@@ -447,11 +558,19 @@ async function runVersion(detailed = false) {
447
558
  return;
448
559
  }
449
560
 
561
+ /*
562
+ const activeEngine = (process.env.CORTEXOPS_ENGINE || 'antigravity').toLowerCase();
563
+ const isDefaultEngine = !process.env.CORTEXOPS_ENGINE || activeEngine === 'antigravity';
564
+ */
565
+
450
566
  console.log('='.repeat(70));
451
567
  console.log(`CORTEXOPS FRAMEWORK VERSION: v${currentVer}`);
452
568
  console.log('='.repeat(70));
453
569
  console.log(`Package Name: @ctxthuta/cxops`);
454
570
  console.log(`Current Version: v${currentVer}`);
571
+ /*
572
+ console.log(`Active Engine: ${activeEngine} ${isDefaultEngine ? '(Default)' : ''}`);
573
+ */
455
574
  console.log(`Node.js Runtime: ${process.version}`);
456
575
  console.log(`Platform: ${process.platform} (${process.arch})`);
457
576
 
@@ -483,17 +602,21 @@ Usage:
483
602
  cxops [command]
484
603
 
485
604
  Commands:
486
- setup, init Run interactive cross-platform setup wizard
487
- doctor Run system diagnostics and prerequisite health check
488
- status, dashboard Display operational & token telemetry dashboard
489
- watch Continuously monitor the dashboard (auto-refresh)
490
- verify Verify all 12 declarative subagent definitions
491
- run "<prompt>" Dispatch an autonomous multi-agent task via Python SDK
492
- version, -v, --version Display framework version and check for updates
493
- link Link Antigravity global plugin symlink/junction
494
- unlink Remove Antigravity global plugin symlink/junction
495
- help, --help, -h Display this command reference
496
- `);
605
+ setup, init Run interactive cross-platform setup wizard
606
+ doctor Run system diagnostics and prerequisite health check
607
+ status, dashboard Display operational & token telemetry dashboard
608
+ watch Continuously monitor the dashboard (auto-refresh)
609
+ verify Verify all 12 declarative subagent definitions
610
+ version, -v, --version Display framework version and check for updates
611
+ link Link Antigravity global plugin symlink/junction
612
+ unlink Remove Antigravity global plugin symlink/junction
613
+ help, --help, -h Display this command reference
614
+ ` + /*
615
+ ` run [options] "<prompt>" Dispatch an autonomous multi-agent task via Python SDK
616
+ Options:
617
+ -e, --engine <engine> Select execution harness: antigravity (default), claude, codex
618
+ -m, --model <model> Override model identifier for the selected engine
619
+ ` + */ '');
497
620
  }
498
621
 
499
622
  async function main() {
@@ -531,13 +654,16 @@ async function main() {
531
654
  const isDetailed = command === 'version' || args.includes('--check') || args.includes('-c');
532
655
  await runVersion(isDetailed);
533
656
  break;
657
+ /*
534
658
  case 'run':
535
659
  if (args.length < 2) {
536
- console.error('[ERROR] Task prompt required. Usage: cxops run "<prompt>"');
660
+ console.error('[ERROR] Task prompt required.');
661
+ console.error('Usage: cxops run [--engine antigravity|claude|codex] "<prompt>"');
537
662
  process.exit(1);
538
663
  }
539
664
  executePythonScript(MAIN_SCRIPT, args.slice(1));
540
665
  break;
666
+ */
541
667
  case 'help':
542
668
  case '--help':
543
669
  case '-h':
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@ctxthuta/cxops",
3
- "version": "1.0.3",
4
- "description": "CortexOps Multi-Agent Framework: Autonomous engineering and research operating system for Google Antigravity and Python SDK.",
3
+ "version": "1.0.5",
4
+ "description": "CortexOps Multi-Agent Framework: Autonomous engineering and research operating system for Google Antigravity.",
5
5
  "main": "bin/cxops.js",
6
6
  "bin": {
7
7
  "cxops": "bin/cxops.js",
@@ -21,6 +21,10 @@
21
21
  "cortexops",
22
22
  "multi-agent",
23
23
  "antigravity",
24
+ "claude",
25
+ "codex",
26
+ "openai",
27
+ "anthropic",
24
28
  "subagents",
25
29
  "aiops",
26
30
  "orchestrator",
package/src/engines.py ADDED
@@ -0,0 +1,178 @@
1
+ """CortexOps Multi-Engine Execution Dispatcher.
2
+
3
+ Provides polymorphic engine runners for Antigravity (default), Claude, and Codex.
4
+ """
5
+
6
+ import json
7
+ import os
8
+ import sys
9
+ from abc import ABC, abstractmethod
10
+ from typing import Optional
11
+ import httpx
12
+
13
+ from src.team import LEAD_PM_DIRECTOR_INSTRUCTIONS, create_cortexops_team
14
+
15
+ DEFAULT_GEMINI_MODEL = os.environ.get("GEMINI_MODEL", "gemini-3.8-flash")
16
+ DEFAULT_CLAUDE_MODEL = os.environ.get("ANTHROPIC_MODEL", "claude-3-7-sonnet-20250219")
17
+ DEFAULT_CODEX_MODEL = os.environ.get("OPENAI_MODEL", "gpt-4o")
18
+
19
+
20
+ class BaseEngine(ABC):
21
+ """Abstract execution harness interface for CortexOps tasks."""
22
+
23
+ @abstractmethod
24
+ async def run(self, prompt: str, model: Optional[str] = None) -> None:
25
+ """Executes the task prompt and streams the engineering outcome to stdout."""
26
+ pass
27
+
28
+
29
+ class AntigravityEngine(BaseEngine):
30
+ """Native Google Antigravity SDK engine harness utilizing Gemini models."""
31
+
32
+ async def run(self, prompt: str, model: Optional[str] = None) -> None:
33
+ from google.antigravity import Agent
34
+
35
+ target_model = model or DEFAULT_GEMINI_MODEL
36
+ config = create_cortexops_team(model=target_model)
37
+
38
+ async with Agent(config) as team:
39
+ response = await team.chat(prompt)
40
+ async for chunk in response:
41
+ print(chunk, end="", flush=True)
42
+
43
+
44
+ class ClaudeEngine(BaseEngine):
45
+ """Anthropic Claude execution harness with real-time SSE streaming."""
46
+
47
+ async def run(self, prompt: str, model: Optional[str] = None) -> None:
48
+ api_key = os.environ.get("ANTHROPIC_API_KEY", "").strip()
49
+ if not api_key:
50
+ raise ValueError(
51
+ "ANTHROPIC_API_KEY is not configured.\n"
52
+ "Please set ANTHROPIC_API_KEY in your environment, .env file, or run 'cxops setup'."
53
+ )
54
+
55
+ target_model = model or DEFAULT_CLAUDE_MODEL
56
+ headers = {
57
+ "x-api-key": api_key,
58
+ "anthropic-version": "2023-06-01",
59
+ "content-type": "application/json",
60
+ }
61
+ payload = {
62
+ "model": target_model,
63
+ "max_tokens": 4096,
64
+ "system": LEAD_PM_DIRECTOR_INSTRUCTIONS,
65
+ "messages": [
66
+ {"role": "user", "content": prompt}
67
+ ],
68
+ "stream": True,
69
+ }
70
+
71
+ async with httpx.AsyncClient(timeout=120.0) as client:
72
+ async with client.stream(
73
+ "POST",
74
+ "https://api.anthropic.com/v1/messages",
75
+ headers=headers,
76
+ json=payload
77
+ ) as response:
78
+ if response.status_code != 200:
79
+ err_body = await response.aread()
80
+ sys.stderr.write(
81
+ f"[ERROR] Anthropic API returned HTTP {response.status_code}: "
82
+ f"{err_body.decode('utf-8', errors='replace')}\n"
83
+ )
84
+ sys.exit(1)
85
+
86
+ async for line in response.aiter_lines():
87
+ if line.startswith("data: "):
88
+ data_str = line[6:].strip()
89
+ if not data_str or data_str == "[DONE]":
90
+ continue
91
+ try:
92
+ event = json.loads(data_str)
93
+ if event.get("type") == "content_block_delta":
94
+ text = event.get("delta", {}).get("text", "")
95
+ print(text, end="", flush=True)
96
+ except json.JSONDecodeError:
97
+ pass
98
+
99
+
100
+ class CodexEngine(BaseEngine):
101
+ """OpenAI Codex / ChatGPT execution harness with real-time SSE streaming."""
102
+
103
+ async def run(self, prompt: str, model: Optional[str] = None) -> None:
104
+ api_key = os.environ.get("OPENAI_API_KEY", "").strip()
105
+ if not api_key:
106
+ raise ValueError(
107
+ "OPENAI_API_KEY is not configured.\n"
108
+ "Please set OPENAI_API_KEY in your environment, .env file, or run 'cxops setup'."
109
+ )
110
+
111
+ target_model = model or DEFAULT_CODEX_MODEL
112
+ headers = {
113
+ "Authorization": f"Bearer {api_key}",
114
+ "Content-Type": "application/json",
115
+ }
116
+ payload = {
117
+ "model": target_model,
118
+ "messages": [
119
+ {"role": "system", "content": LEAD_PM_DIRECTOR_INSTRUCTIONS},
120
+ {"role": "user", "content": prompt},
121
+ ],
122
+ "stream": True,
123
+ }
124
+
125
+ async with httpx.AsyncClient(timeout=120.0) as client:
126
+ async with client.stream(
127
+ "POST",
128
+ "https://api.openai.com/v1/chat/completions",
129
+ headers=headers,
130
+ json=payload
131
+ ) as response:
132
+ if response.status_code != 200:
133
+ err_body = await response.aread()
134
+ sys.stderr.write(
135
+ f"[ERROR] OpenAI API returned HTTP {response.status_code}: "
136
+ f"{err_body.decode('utf-8', errors='replace')}\n"
137
+ )
138
+ sys.exit(1)
139
+
140
+ async for line in response.aiter_lines():
141
+ if line.startswith("data: "):
142
+ data_str = line[6:].strip()
143
+ if not data_str or data_str == "[DONE]":
144
+ continue
145
+ try:
146
+ event = json.loads(data_str)
147
+ choices = event.get("choices", [])
148
+ if choices:
149
+ delta = choices[0].get("delta", {})
150
+ content = delta.get("content", "")
151
+ if content:
152
+ print(content, end="", flush=True)
153
+ except json.JSONDecodeError:
154
+ pass
155
+
156
+
157
+ def resolve_engine(engine_name: Optional[str]) -> BaseEngine:
158
+ """Normalizes and instantiates the target execution engine harness."""
159
+ normalized = (engine_name or "").strip().lower()
160
+
161
+ if normalized in ("claude", "anthropic"):
162
+ return ClaudeEngine()
163
+ if normalized in ("codex", "openai", "chatgpt"):
164
+ return CodexEngine()
165
+
166
+ return AntigravityEngine()
167
+
168
+
169
+ def get_default_model(engine_name: str) -> str:
170
+ """Returns the default model identifier for the selected engine harness."""
171
+ normalized = (engine_name or "").strip().lower()
172
+
173
+ if normalized in ("claude", "anthropic"):
174
+ return DEFAULT_CLAUDE_MODEL
175
+ if normalized in ("codex", "openai", "chatgpt"):
176
+ return DEFAULT_CODEX_MODEL
177
+
178
+ return DEFAULT_GEMINI_MODEL
package/src/main.py CHANGED
@@ -1,14 +1,17 @@
1
1
  """CLI Entrypoint for CortexOps Multi-Agent Framework."""
2
2
 
3
+ import argparse
3
4
  import asyncio
4
5
  import os
5
6
  import sys
6
7
  from pathlib import Path
8
+ from typing import Optional
7
9
 
8
10
  REPO_ROOT = Path(__file__).resolve().parent.parent
9
11
  if str(REPO_ROOT) not in sys.path:
10
12
  sys.path.insert(0, str(REPO_ROOT))
11
13
 
14
+
12
15
  def load_environment() -> None:
13
16
  """Discovers and loads environment variables from candidate .env files."""
14
17
  candidate_paths = [
@@ -30,45 +33,104 @@ def load_environment() -> None:
30
33
  except Exception:
31
34
  pass
32
35
 
36
+
33
37
  load_environment()
34
38
 
35
- from google.antigravity import Agent
36
- from src.team import create_cortexops_team
39
+ from src.engines import resolve_engine, get_default_model
40
+
41
+
42
+ def parse_arguments():
43
+ """Parses command-line arguments for engine, model, and task prompt."""
44
+ parser = argparse.ArgumentParser(
45
+ description="CortexOps Multi-Agent Framework Task Runner",
46
+ add_help=False,
47
+ )
48
+ parser.add_argument(
49
+ "-e",
50
+ "--engine",
51
+ dest="engine",
52
+ default=os.environ.get("CORTEXOPS_ENGINE", "antigravity"),
53
+ help="Target execution harness: antigravity (default), claude, codex",
54
+ )
55
+ parser.add_argument(
56
+ "-m",
57
+ "--model",
58
+ dest="model",
59
+ default=None,
60
+ help="Model identifier override for selected execution engine",
61
+ )
62
+ parser.add_argument(
63
+ "-h",
64
+ "--help",
65
+ action="help",
66
+ help="Display this task runner help reference and exit",
67
+ )
68
+ parser.add_argument(
69
+ "prompt",
70
+ nargs="*",
71
+ help="Engineering task prompt or project goal",
72
+ )
73
+ return parser.parse_args()
74
+
37
75
 
38
- DEFAULT_MODEL = os.environ.get("GEMINI_MODEL", "gemini-3.8-flash")
76
+ async def run_task(prompt: str, engine_name: str, model_override: Optional[str] = None):
77
+ """Executes a complete engineering or research lifecycle task via the selected engine."""
78
+ engine = resolve_engine(engine_name)
79
+ resolved_model = model_override or get_default_model(engine_name)
80
+ normalized_engine = "antigravity"
81
+ if engine_name.lower() in ("claude", "anthropic"):
82
+ normalized_engine = "claude"
83
+ elif engine_name.lower() in ("codex", "openai", "chatgpt"):
84
+ normalized_engine = "codex"
85
+
86
+ engine_tag = normalized_engine.upper()
87
+ is_default = normalized_engine == "antigravity"
39
88
 
40
- async def run_task(prompt: str, model: str = DEFAULT_MODEL):
41
- """Runs a complete software engineering or research lifecycle task with the CortexOps team."""
42
- config = create_cortexops_team(model=model)
43
-
44
89
  print("=" * 70)
45
- print("CORTEXOPS MULTI-AGENT FRAMEWORK - ACTIVE")
90
+ print(f"CORTEXOPS MULTI-AGENT FRAMEWORK - ACTIVE [{engine_tag} ENGINE]")
46
91
  print("Roles: TPM Director | Staff R&D | Principal Architect | UI/UX | Frontend | Backend | DevOps | ML | QA | Reviewer | Academic Researcher | Software Engineer | cxagents")
47
- print(f"Model: {model}")
48
- print(f"Goal: {prompt}")
92
+ print(f"Engine: {normalized_engine} {'(Default)' if is_default else ''}")
93
+ print(f"Model: {resolved_model}")
94
+ print(f"Goal: {prompt}")
49
95
  print("=" * 70 + "\n")
50
-
51
- async with Agent(config) as team:
52
- response = await team.chat(prompt)
53
- print("\n" + "=" * 70)
54
- print("ENGINEERING OUTCOME:")
55
- print("=" * 70)
56
- async for chunk in response:
57
- print(chunk, end="", flush=True)
58
- print("\n")
96
+
97
+ print("=" * 70)
98
+ print("ENGINEERING OUTCOME:")
99
+ print("=" * 70)
100
+
101
+ await engine.run(prompt=prompt, model=resolved_model)
102
+ print("\n")
103
+
59
104
 
60
105
  def main():
61
- if len(sys.argv) > 1:
62
- prompt = " ".join(sys.argv[1:])
63
- else:
106
+ args = parse_arguments()
107
+ prompt = " ".join(args.prompt).strip() if args.prompt else ""
108
+
109
+ if not prompt:
64
110
  print("Enter the engineering project or feature request:")
65
- prompt = input("> ").strip()
66
-
111
+ try:
112
+ prompt = input("> ").strip()
113
+ except (KeyboardInterrupt, EOFError):
114
+ print("\nAborted.")
115
+ sys.exit(0)
116
+
67
117
  if not prompt:
68
- print("No task provided. Exiting.")
118
+ print("No task prompt provided. Exiting.")
119
+ sys.exit(1)
120
+
121
+ try:
122
+ asyncio.run(run_task(
123
+ prompt=prompt,
124
+ engine_name=args.engine,
125
+ model_override=args.model,
126
+ ))
127
+ except (ValueError, RuntimeError) as err:
128
+ sys.stderr.write(f"\n[ERROR] {err}\n")
69
129
  sys.exit(1)
70
-
71
- asyncio.run(run_task(prompt))
130
+ except KeyboardInterrupt:
131
+ print("\nOperation cancelled by user.")
132
+ sys.exit(0)
133
+
72
134
 
73
135
  if __name__ == "__main__":
74
136
  main()