@ctxthuta/cxops 1.0.3 → 1.0.4

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
@@ -82,15 +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
+ ### Mode B: Standalone Multi-Engine Framework (Terminal / CI / Headless)
86
86
  When running outside Antigravity as an automated background process:
87
- - Configure your Gemini API key:
87
+ - Configure your preferred engine (default: `antigravity`):
88
88
  ```bash
89
+ # Antigravity (Google DeepMind SDK, default)
89
90
  export GEMINI_API_KEY="your-gemini-api-key"
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"
90
97
  ```
91
- - Run tasks via the Python driver:
98
+ - Run tasks with your preferred execution harness:
92
99
  ```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."
100
+ # Default Antigravity engine (Gemini 3.8 models)
101
+ cxops run "Research streaming anomaly detection and implement an in-memory detector with unit tests."
102
+
103
+ # Anthropic Claude engine (Claude 3.7 / 3.5 Sonnet)
104
+ cxops run -e claude "Design high-throughput event sourcing microservice."
105
+
106
+ # OpenAI Codex engine (GPT-4o / o3-mini)
107
+ cxops run -e codex "Generate relational PostgreSQL DDL with composite indexes."
94
108
  ```
95
109
 
96
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,75 @@ 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
+ console.log('\n[2] Execution Engine & Platform Selection:');
269
+ const defaultEngine = (process.env.CORTEXOPS_ENGINE || 'antigravity').toLowerCase();
270
+ console.log(' Available Execution Harnesses:');
271
+ console.log(' - antigravity: Google Antigravity SDK with Gemini 3.8 models (Default)');
272
+ console.log(' - claude: Anthropic Claude models (Claude 3.7 / 3.5 Sonnet)');
273
+ console.log(' - codex: OpenAI Codex / GPT-4o / o3-mini models');
274
+
275
+ const enginePrompt = await rl.question(` Select default engine [antigravity | claude | codex] (default: ${defaultEngine}): `);
276
+ const resolvedEngine = normalizeEngine(enginePrompt) || defaultEngine || 'antigravity';
277
+ saveEnvKey('CORTEXOPS_ENGINE', resolvedEngine);
278
+ console.log(` * Configured execution engine: ${resolvedEngine}`);
279
+
280
+ console.log('\n[3] Authentication & API Keys:');
281
+ if (resolvedEngine === 'antigravity') {
282
+ const existingKey = process.env.GEMINI_API_KEY;
283
+ if (existingKey) {
284
+ console.log(' * GEMINI_API_KEY is already configured.');
285
+ } else {
286
+ const hasKey = await rl.question(' Configure GEMINI_API_KEY for Antigravity engine? (y/n) [y]: ');
287
+ if (hasKey.trim().toLowerCase() !== 'n') {
288
+ const keyInput = await rl.question(' Enter your GEMINI_API_KEY: ');
289
+ const cleanKey = keyInput.trim().replace(/[\r\n]/g, '');
290
+ if (cleanKey) {
291
+ saveEnvKey('GEMINI_API_KEY', cleanKey);
292
+ console.log(' * Saved GEMINI_API_KEY to configuration files (mode 0600)');
293
+ }
294
+ } else {
295
+ console.log(' * Skipping API key. Antigravity IDE sessions will authenticate automatically.');
296
+ }
297
+ }
298
+ } else if (resolvedEngine === 'claude') {
299
+ const existingKey = process.env.ANTHROPIC_API_KEY;
300
+ if (existingKey) {
301
+ console.log(' * ANTHROPIC_API_KEY is already configured.');
302
+ } else {
303
+ const hasKey = await rl.question(' Configure ANTHROPIC_API_KEY for Claude engine? (y/n) [y]: ');
304
+ if (hasKey.trim().toLowerCase() !== 'n') {
305
+ const keyInput = await rl.question(' Enter your ANTHROPIC_API_KEY: ');
306
+ const cleanKey = keyInput.trim().replace(/[\r\n]/g, '');
307
+ if (cleanKey) {
308
+ saveEnvKey('ANTHROPIC_API_KEY', cleanKey);
309
+ console.log(' * Saved ANTHROPIC_API_KEY to configuration files (mode 0600)');
253
310
  }
254
- process.env.GEMINI_API_KEY = cleanKey;
255
311
  }
312
+ }
313
+ } else if (resolvedEngine === 'codex') {
314
+ const existingKey = process.env.OPENAI_API_KEY;
315
+ if (existingKey) {
316
+ console.log(' * OPENAI_API_KEY is already configured.');
256
317
  } else {
257
- console.log(' * Skipping API key. Antigravity IDE sessions will use existing authenticated session.');
318
+ const hasKey = await rl.question(' Configure OPENAI_API_KEY for Codex engine? (y/n) [y]: ');
319
+ if (hasKey.trim().toLowerCase() !== 'n') {
320
+ const keyInput = await rl.question(' Enter your OPENAI_API_KEY: ');
321
+ const cleanKey = keyInput.trim().replace(/[\r\n]/g, '');
322
+ if (cleanKey) {
323
+ saveEnvKey('OPENAI_API_KEY', cleanKey);
324
+ console.log(' * Saved OPENAI_API_KEY to configuration files (mode 0600)');
325
+ }
326
+ }
258
327
  }
259
328
  }
260
329
 
261
- console.log('\n[3] Antigravity Global Plugin Registration:');
330
+ console.log('\n[4] Antigravity Global Plugin Registration:');
262
331
  const linkChoice = await rl.question(' Register CortexOps global plugin for Antigravity sessions? (y/n) [y]: ');
263
332
  if (linkChoice.trim().toLowerCase() !== 'n') {
264
333
  linkPlugin();
265
334
  }
266
335
 
267
- console.log('\n[4] Second Brain Integration (ThutaCortex):');
336
+ console.log('\n[5] Second Brain Integration (ThutaCortex):');
268
337
  const defaultVault = path.join(os.homedir(), 'Documents', 'ThutaCortex');
269
338
  const vaultChoice = await rl.question(` ThutaCortex vault path [${defaultVault}]: `);
270
339
  const resolvedVault = vaultChoice.trim() || defaultVault;
@@ -276,7 +345,7 @@ async function runSetup() {
276
345
  console.log(' The framework will operate in local-only mode until the vault is initialized.');
277
346
  }
278
347
 
279
- console.log('\n[5] Python Virtual Environment & Dependencies:');
348
+ console.log('\n[6] Python Virtual Environment & Dependencies:');
280
349
  const venvDir = path.join(ROOT_DIR, '.venv');
281
350
  if (fs.existsSync(venvDir)) {
282
351
  console.log(' * Virtual environment already exists at .venv/');
@@ -303,7 +372,7 @@ async function runSetup() {
303
372
  }
304
373
  }
305
374
 
306
- console.log('\n[6] Subagent Definition Verification:');
375
+ console.log('\n[7] Subagent Definition Verification:');
307
376
  const py = getVenvPython();
308
377
  if (py && fs.existsSync(VERIFY_SCRIPT)) {
309
378
  spawnSync(py, [VERIFY_SCRIPT], { stdio: 'inherit', env: { ...process.env, PYTHONPATH: ROOT_DIR } });
@@ -311,10 +380,12 @@ async function runSetup() {
311
380
 
312
381
  console.log('\n' + '='.repeat(70));
313
382
  console.log('Setup complete. You can now use:');
314
- console.log(' cxops status Display the operational & token telemetry dashboard');
383
+ console.log(' cxops status Display operational & token telemetry dashboard');
315
384
  console.log(' cxops watch Continuously monitor the live dashboard');
316
385
  console.log(' cxops verify Verify all 12 subagent definitions');
317
- console.log(' cxops run "<goal>" Dispatch autonomous tasks via Python SDK');
386
+ console.log(' cxops run "<goal>" Dispatch autonomous tasks (Default: antigravity)');
387
+ console.log(' cxops run -e claude "<goal>" Dispatch tasks using Claude');
388
+ console.log(' cxops run -e codex "<goal>" Dispatch tasks using Codex');
318
389
  console.log('='.repeat(70));
319
390
  } finally {
320
391
  rl.close();
@@ -349,6 +420,44 @@ function runDoctor() {
349
420
  console.log('[WARN] Virtual Environment: .venv not found. Run "cxops setup" to create.');
350
421
  }
351
422
 
423
+ // Execution engine configuration
424
+ const activeEngine = (process.env.CORTEXOPS_ENGINE || 'antigravity').toLowerCase();
425
+ const isDefaultEngine = !process.env.CORTEXOPS_ENGINE || activeEngine === 'antigravity';
426
+ console.log(`[PASS] Execution Engine: ${activeEngine} ${isDefaultEngine ? '(Default)' : ''}`);
427
+
428
+ // Engine-specific authentication diagnostics
429
+ const geminiKey = process.env.GEMINI_API_KEY;
430
+ const anthropicKey = process.env.ANTHROPIC_API_KEY;
431
+ const openaiKey = process.env.OPENAI_API_KEY;
432
+
433
+ if (activeEngine === 'antigravity') {
434
+ if (geminiKey) {
435
+ console.log('[PASS] Antigravity Auth: GEMINI_API_KEY is configured.');
436
+ } else {
437
+ console.log('[INFO] Antigravity Auth: GEMINI_API_KEY not in environment. Antigravity IDE sessions will authenticate automatically.');
438
+ }
439
+ } else if (activeEngine === 'claude') {
440
+ if (anthropicKey) {
441
+ console.log('[PASS] Claude Auth: ANTHROPIC_API_KEY is configured.');
442
+ } else {
443
+ console.log('[WARN] Claude Auth: ANTHROPIC_API_KEY not configured. Run "cxops setup" to set.');
444
+ }
445
+ } else if (activeEngine === 'codex') {
446
+ if (openaiKey) {
447
+ console.log('[PASS] Codex Auth: OPENAI_API_KEY is configured.');
448
+ } else {
449
+ console.log('[WARN] Codex Auth: OPENAI_API_KEY not configured. Run "cxops setup" to set.');
450
+ }
451
+ }
452
+
453
+ const secondaryKeys = [];
454
+ if (activeEngine !== 'antigravity' && geminiKey) secondaryKeys.push('GEMINI_API_KEY');
455
+ if (activeEngine !== 'claude' && anthropicKey) secondaryKeys.push('ANTHROPIC_API_KEY');
456
+ if (activeEngine !== 'codex' && openaiKey) secondaryKeys.push('OPENAI_API_KEY');
457
+ if (secondaryKeys.length > 0) {
458
+ console.log(`[PASS] Additional Keys Configured: ${secondaryKeys.join(', ')}`);
459
+ }
460
+
352
461
  // Antigravity global plugin link status
353
462
  const { targets } = getPluginTargets();
354
463
  let linkFound = false;
@@ -382,14 +491,6 @@ function runDoctor() {
382
491
  console.log(`[INFO] ThutaCortex Second Brain: Not present at ${vaultPath} (Local fallback mode)`);
383
492
  }
384
493
 
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
494
  // Subagent declarative definitions check
394
495
  const pluginAgentsDir = path.join(PLUGIN_SOURCE, 'agents');
395
496
  if (fs.existsSync(pluginAgentsDir)) {
@@ -405,10 +506,10 @@ function getPackageVersion() {
405
506
  const pkgPath = path.join(ROOT_DIR, 'package.json');
406
507
  if (fs.existsSync(pkgPath)) {
407
508
  const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
408
- return pkg.version || '1.0.3';
509
+ return pkg.version || '1.0.4';
409
510
  }
410
511
  } catch (_) {}
411
- return '1.0.3';
512
+ return '1.0.4';
412
513
  }
413
514
 
414
515
  function fetchLatestNpmVersion() {
@@ -447,11 +548,15 @@ async function runVersion(detailed = false) {
447
548
  return;
448
549
  }
449
550
 
551
+ const activeEngine = (process.env.CORTEXOPS_ENGINE || 'antigravity').toLowerCase();
552
+ const isDefaultEngine = !process.env.CORTEXOPS_ENGINE || activeEngine === 'antigravity';
553
+
450
554
  console.log('='.repeat(70));
451
555
  console.log(`CORTEXOPS FRAMEWORK VERSION: v${currentVer}`);
452
556
  console.log('='.repeat(70));
453
557
  console.log(`Package Name: @ctxthuta/cxops`);
454
558
  console.log(`Current Version: v${currentVer}`);
559
+ console.log(`Active Engine: ${activeEngine} ${isDefaultEngine ? '(Default)' : ''}`);
455
560
  console.log(`Node.js Runtime: ${process.version}`);
456
561
  console.log(`Platform: ${process.platform} (${process.arch})`);
457
562
 
@@ -483,16 +588,25 @@ Usage:
483
588
  cxops [command]
484
589
 
485
590
  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
591
+ setup, init Run interactive cross-platform setup wizard
592
+ doctor Run system diagnostics and prerequisite health check
593
+ status, dashboard Display operational & token telemetry dashboard
594
+ watch Continuously monitor the dashboard (auto-refresh)
595
+ verify Verify all 12 declarative subagent definitions
596
+ run [options] "<prompt>" Dispatch an autonomous multi-agent task via Python SDK
597
+ version, -v, --version Display framework version and check for updates
598
+ link Link Antigravity global plugin symlink/junction
599
+ unlink Remove Antigravity global plugin symlink/junction
600
+ help, --help, -h Display this command reference
601
+
602
+ Run Options:
603
+ -e, --engine <engine> Select execution harness: antigravity (default), claude, codex
604
+ -m, --model <model> Override model identifier for the selected engine
605
+
606
+ Supported Engines:
607
+ antigravity Google Antigravity SDK with Gemini 3.8 models (Default)
608
+ claude Anthropic Claude models (Claude 3.7 / 3.5 Sonnet)
609
+ codex OpenAI Codex / GPT-4o / o3-mini models
496
610
  `);
497
611
  }
498
612
 
@@ -533,7 +647,8 @@ async function main() {
533
647
  break;
534
648
  case 'run':
535
649
  if (args.length < 2) {
536
- console.error('[ERROR] Task prompt required. Usage: cxops run "<prompt>"');
650
+ console.error('[ERROR] Task prompt required.');
651
+ console.error('Usage: cxops run [--engine antigravity|claude|codex] "<prompt>"');
537
652
  process.exit(1);
538
653
  }
539
654
  executePythonScript(MAIN_SCRIPT, args.slice(1));
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.4",
4
+ "description": "CortexOps Multi-Agent Framework: Autonomous engineering and research operating system for Google Antigravity, Claude, and Codex with Python SDK.",
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()