Cyber Catalyst Team commited on
Commit
a601181
·
1 Parent(s): 2488be2

Implement MultiProviderRateLimiter, eternity state machines and Forge execution agent endpoints

Browse files
Files changed (1) hide show
  1. backend.py +374 -9
backend.py CHANGED
@@ -95,6 +95,44 @@ nim_client = AsyncOpenAI(
95
  api_key=NIM_API_KEY,
96
  )
97
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98
  # ---------------------------------------------------------------------------
99
  # Tool Definitions (OpenAI function calling format)
100
  # ---------------------------------------------------------------------------
@@ -397,6 +435,16 @@ async def init_db():
397
  );
398
  CREATE INDEX IF NOT EXISTS idx_session_key ON agent_session_entries (project_key, session_id, subpath, id);
399
  CREATE INDEX IF NOT EXISTS idx_project_session ON agent_session_entries (project_key, session_id);
 
 
 
 
 
 
 
 
 
 
400
  """)
401
  except Exception as e:
402
  print(f"[DB] Warning: Could not initialize database: {e}")
@@ -1355,24 +1403,324 @@ async def delete_session(req: SessionDeleteRequest, authorization: str = Header(
1355
  raise HTTPException(status_code=500, detail=str(e))
1356
 
1357
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1358
  # ---------------------------------------------------------------------------
1359
  # Database Retention & Heartbeat loops
1360
  # ---------------------------------------------------------------------------
1361
 
1362
- async def db_cleanup_loop():
1363
- log_activity("Database Retention Cleanup task started")
1364
  while True:
1365
  try:
1366
  if db_pool:
1367
  async with db_pool.acquire() as conn:
1368
- # Purge session entries older than 30 days
1369
- result = await conn.execute(
1370
- "DELETE FROM agent_session_entries WHERE created_at < NOW() - INTERVAL '30 days'"
1371
- )
1372
- log_activity(f"[Cleanup] Nightly retention sweep complete. Status: {result}")
1373
  except Exception as e:
1374
- log_activity(f"[Cleanup Warning] Failed to run retention cleanup: {e}")
1375
- await asyncio.sleep(86400) # Every 24 hours
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1376
 
1377
 
1378
  @app.get("/", response_class=HTMLResponse)
@@ -1596,12 +1944,29 @@ def run_backup_loop():
1596
  log_activity(f"[Backup Error] {e}")
1597
 
1598
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1599
  @app.on_event("startup")
1600
  async def startup_event():
1601
  # Start the watchdog thread on startup
1602
  threading.Thread(target=run_watchdog, daemon=True).start()
1603
  # Start the local backup loop thread
1604
  threading.Thread(target=run_backup_loop, daemon=True).start()
 
 
1605
  # Start the db keep-alive loop on FastAPI event loop
1606
  asyncio.create_task(db_heartbeat_loop())
1607
  # Start the db nightly retention cleanup loop
 
95
  api_key=NIM_API_KEY,
96
  )
97
 
98
+ # ---------------------------------------------------------------------------
99
+ # Rate Limiting & Multi-Provider Setup
100
+ # ---------------------------------------------------------------------------
101
+
102
+ MISTRAL_API_KEY = os.environ.get("MISTRAL_API_KEY", "")
103
+ mistral_client = AsyncOpenAI(
104
+ base_url="https://api.mistral.ai/v1",
105
+ api_key=MISTRAL_API_KEY if MISTRAL_API_KEY else "dummy_key",
106
+ ) if MISTRAL_API_KEY else None
107
+
108
+ class MultiProviderRateLimiter:
109
+ def __init__(self):
110
+ self.nim_limit = 40
111
+ self.nim_window = 60
112
+ self.nim_calls = []
113
+ self.mistral_last_call = 0.0
114
+ self.lock = asyncio.Lock()
115
+
116
+ async def wait_for_mistral(self):
117
+ async with self.lock:
118
+ now = time.time()
119
+ elapsed = now - self.mistral_last_call
120
+ if elapsed < 1.0:
121
+ await asyncio.sleep(1.0 - elapsed)
122
+ self.mistral_last_call = time.time()
123
+
124
+ async def wait_for_nim(self):
125
+ async with self.lock:
126
+ now = time.time()
127
+ self.nim_calls = [t for t in self.nim_calls if now - t < self.nim_window]
128
+ if len(self.nim_calls) >= self.nim_limit - 2:
129
+ sleep_time = self.nim_window - (now - self.nim_calls[0])
130
+ print(f"[RateLimiter] Approaching NIM rate limit (40 RPM). Sleeping {sleep_time:.2f}s...")
131
+ await asyncio.sleep(sleep_time)
132
+ self.nim_calls.append(time.time())
133
+
134
+ rate_limiter = MultiProviderRateLimiter()
135
+
136
  # ---------------------------------------------------------------------------
137
  # Tool Definitions (OpenAI function calling format)
138
  # ---------------------------------------------------------------------------
 
435
  );
436
  CREATE INDEX IF NOT EXISTS idx_session_key ON agent_session_entries (project_key, session_id, subpath, id);
437
  CREATE INDEX IF NOT EXISTS idx_project_session ON agent_session_entries (project_key, session_id);
438
+
439
+ CREATE TABLE IF NOT EXISTS eternity_system_state (
440
+ id SERIAL PRIMARY KEY,
441
+ goal TEXT NOT NULL,
442
+ deadline TIMESTAMPTZ NOT NULL,
443
+ current_mode VARCHAR(20) NOT NULL DEFAULT 'build',
444
+ roadmap JSONB DEFAULT '[]',
445
+ latest_brief TEXT,
446
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()
447
+ );
448
  """)
449
  except Exception as e:
450
  print(f"[DB] Warning: Could not initialize database: {e}")
 
1403
  raise HTTPException(status_code=500, detail=str(e))
1404
 
1405
 
1406
+ from datetime import datetime, timedelta, timezone
1407
+
1408
+ class EternityInitRequest(BaseModel):
1409
+ goal: str
1410
+ deadline_hours: int
1411
+
1412
+ @app.post("/api/eternity/init")
1413
+ async def init_eternity_system(req: EternityInitRequest, authorization: str = Header(None)):
1414
+ auth(authorization)
1415
+ if not db_pool:
1416
+ raise HTTPException(status_code=500, detail="Database not connected")
1417
+ try:
1418
+ deadline = datetime.now(timezone.utc) + timedelta(hours=req.deadline_hours)
1419
+ async with db_pool.acquire() as conn:
1420
+ # Delete any old state
1421
+ await conn.execute("DELETE FROM eternity_system_state")
1422
+ # Insert new state
1423
+ await conn.execute(
1424
+ "INSERT INTO eternity_system_state (goal, deadline, current_mode, roadmap) VALUES ($1, $2, 'build', $3)",
1425
+ req.goal, deadline, "[]"
1426
+ )
1427
+ log_activity(f"[Eternity Loop] System initialized with goal: '{req.goal}' | Deadline: {deadline}")
1428
+ return {"status": "success", "deadline": deadline.isoformat()}
1429
+ except Exception as e:
1430
+ log_activity(f"[Eternity Loop Error] Init failed: {e}")
1431
+ raise HTTPException(status_code=500, detail=str(e))
1432
+
1433
+ @app.get("/api/eternity/status")
1434
+ async def get_eternity_status(authorization: str = Header(None)):
1435
+ auth(authorization)
1436
+ if not db_pool:
1437
+ raise HTTPException(status_code=500, detail="Database not connected")
1438
+ try:
1439
+ async with db_pool.acquire() as conn:
1440
+ row = await conn.fetchrow("SELECT goal, deadline, current_mode, roadmap, latest_brief FROM eternity_system_state ORDER BY id DESC LIMIT 1")
1441
+ if not row:
1442
+ return {"active": False}
1443
+
1444
+ deadline = row["deadline"]
1445
+ now = datetime.now(timezone.utc)
1446
+ remaining = max(0.0, (deadline - now).total_seconds())
1447
+
1448
+ return {
1449
+ "active": True,
1450
+ "goal": row["goal"],
1451
+ "deadline": deadline.isoformat(),
1452
+ "current_mode": row["current_mode"],
1453
+ "roadmap": json.loads(row["roadmap"]) if isinstance(row["roadmap"], str) else row["roadmap"],
1454
+ "latest_brief": row["latest_brief"],
1455
+ "time_remaining_seconds": remaining
1456
+ }
1457
+ except Exception as e:
1458
+ raise HTTPException(status_code=500, detail=str(e))
1459
+
1460
+
1461
+ class ForgeExecuteRequest(BaseModel):
1462
+ task_id: str
1463
+ action: str
1464
+ prompt: str
1465
+ context_rules: Optional[str] = ""
1466
+
1467
+ @app.post("/api/forge/execute")
1468
+ async def forge_execute(req: ForgeExecuteRequest, authorization: str = Header(None)):
1469
+ auth(authorization)
1470
+ log_activity(f"[Forge] Received execution request for task {req.task_id}: '{req.prompt}'")
1471
+ try:
1472
+ messages = [
1473
+ {"role": "system", "content": AGENTIC_SYSTEM_PROMPT + f"\nContext rules: {req.context_rules}"},
1474
+ {"role": "user", "content": req.prompt}
1475
+ ]
1476
+
1477
+ final_messages = list(messages)
1478
+ success = False
1479
+ summary = ""
1480
+ error = None
1481
+
1482
+ for round_num in range(MAX_TOOL_ROUNDS + 1):
1483
+ await rate_limiter.wait_for_nim()
1484
+ response = await nim_client.chat.completions.create(
1485
+ model=RECOMMENDED_MODEL,
1486
+ messages=final_messages,
1487
+ tools=TOOLS,
1488
+ tool_choice="auto"
1489
+ )
1490
+
1491
+ msg = response.choices[0].message
1492
+ tool_calls_payload = None
1493
+ if msg.tool_calls:
1494
+ tool_calls_payload = []
1495
+ for tc in msg.tool_calls:
1496
+ tc_dict = {
1497
+ "id": tc.id,
1498
+ "type": tc.type,
1499
+ "function": {
1500
+ "name": tc.function.name,
1501
+ "arguments": tc.function.arguments
1502
+ }
1503
+ }
1504
+ tool_calls_payload.append(tc_dict)
1505
+
1506
+ final_messages.append({
1507
+ "role": "assistant",
1508
+ "content": msg.content,
1509
+ "tool_calls": tool_calls_payload
1510
+ })
1511
+
1512
+ if not msg.tool_calls:
1513
+ success = True
1514
+ summary = msg.content or "Task completed."
1515
+ break
1516
+
1517
+ for tc in msg.tool_calls:
1518
+ func_name = tc.function.name
1519
+ func_args = json.loads(tc.function.arguments)
1520
+ result = await execute_tool(func_name, func_args)
1521
+
1522
+ final_messages.append({
1523
+ "role": "tool",
1524
+ "tool_call_id": tc.id,
1525
+ "content": result
1526
+ })
1527
+ else:
1528
+ error = "Max tool call rounds exceeded."
1529
+
1530
+ if success:
1531
+ return {
1532
+ "status": "success",
1533
+ "summary": summary,
1534
+ "error": None
1535
+ }
1536
+ else:
1537
+ return {
1538
+ "status": "error",
1539
+ "error": error or "Task execution failed."
1540
+ }
1541
+
1542
+ except Exception as e:
1543
+ log_activity(f"[Forge Error] Task execution failed: {e}")
1544
+ return {
1545
+ "status": "error",
1546
+ "error": str(e)
1547
+ }
1548
+
1549
+
1550
  # ---------------------------------------------------------------------------
1551
  # Database Retention & Heartbeat loops
1552
  # ---------------------------------------------------------------------------
1553
 
1554
+ async def db_heartbeat_loop():
1555
+ log_activity("Database Heartbeat task started")
1556
  while True:
1557
  try:
1558
  if db_pool:
1559
  async with db_pool.acquire() as conn:
1560
+ await conn.execute("SELECT 1")
1561
+ log_activity("[Heartbeat] Pinged Aiven PostgreSQL successfully")
 
 
 
1562
  except Exception as e:
1563
+ log_activity(f"[Heartbeat Warning] Failed to ping database: {e}")
1564
+ await asyncio.sleep(240) # Every 4 minutes
1565
+
1566
+
1567
+ SPACE3_URL = os.environ.get("SPACE3_URL", "https://augment17-claude-code-backend.hf.space")
1568
+ SPACE4_URL = os.environ.get("SPACE4_URL", "https://shyota-mcp-cloud-host.hf.space")
1569
+ SPACE5_URL = os.environ.get("SPACE5_URL", "https://augment17-better-chatbot.hf.space")
1570
+ SPACE6_URL = os.environ.get("SPACE6_URL", "https://augment17-mcp-cloud-host.hf.space")
1571
+
1572
+ async def get_db_state():
1573
+ async with db_pool.acquire() as conn:
1574
+ return await conn.fetchrow("SELECT goal, deadline, current_mode FROM eternity_system_state ORDER BY id DESC LIMIT 1")
1575
+
1576
+ async def update_db_mode(mode: str):
1577
+ async with db_pool.acquire() as conn:
1578
+ await conn.execute("UPDATE eternity_system_state SET current_mode = $1", mode)
1579
+
1580
+ async def update_db_brief(brief: str):
1581
+ async with db_pool.acquire() as conn:
1582
+ await conn.execute("UPDATE eternity_system_state SET latest_brief = $1", brief)
1583
+
1584
+ async def update_db_roadmap(roadmap: list):
1585
+ async with db_pool.acquire() as conn:
1586
+ await conn.execute("UPDATE eternity_system_state SET roadmap = $1", json.dumps(roadmap))
1587
+
1588
+ def post_json(url: str, payload: dict) -> dict:
1589
+ headers = {
1590
+ "Authorization": f"Bearer {BACKEND_API_KEY}",
1591
+ "Content-Type": "application/json"
1592
+ }
1593
+ req = urllib.request.Request(
1594
+ url,
1595
+ data=json.dumps(payload).encode('utf-8'),
1596
+ headers=headers,
1597
+ method="POST"
1598
+ )
1599
+ try:
1600
+ with urllib.request.urlopen(req, timeout=120) as r:
1601
+ return json.loads(r.read().decode('utf-8'))
1602
+ except Exception as e:
1603
+ print(f"[HTTP Error] POST to {url} failed: {e}")
1604
+ return {"status": "error", "error": str(e)}
1605
+
1606
+ async def execute_build_cycle(goal: str):
1607
+ log_activity(f"[Build Mode] Initiating build cycle for goal: '{goal}'")
1608
+ await rate_limiter.wait_for_nim()
1609
+ prompt = f"We are building: '{goal}'. Write a JSON instruction for Space 3 (The Forge) to code the next milestone. Respond ONLY with JSON matching the contract: " + '{"prompt": "task description", "context_rules": "rules"}'
1610
+ try:
1611
+ res = await nim_client.chat.completions.create(
1612
+ model="nvidia/llama-3.1-nemotron-70b-instruct",
1613
+ messages=[{"role": "user", "content": prompt}],
1614
+ max_tokens=300
1615
+ )
1616
+ task = json.loads(res.choices[0].message.content.strip())
1617
+ task_prompt = task.get("prompt")
1618
+ context_rules = task.get("context_rules", "")
1619
+ except Exception as e:
1620
+ log_activity(f"[Build Mode Error] NIM planning failed: {e}")
1621
+ return
1622
+
1623
+ log_activity(f"[Build Mode] Dispatching task to Space 3: '{task_prompt}'")
1624
+ forge_res = post_json(f"{SPACE3_URL}/api/forge/execute", {
1625
+ "task_id": f"build_{int(time.time())}",
1626
+ "action": "execute_code",
1627
+ "prompt": task_prompt,
1628
+ "context_rules": context_rules
1629
+ })
1630
+
1631
+ if forge_res.get("status") == "success":
1632
+ log_activity(f"[Build Mode] Space 3 success: {forge_res.get('summary')}")
1633
+ log_activity("[Build Mode] Triggering Space 6 (The Sandbox) UI verification...")
1634
+ test_res = post_json(f"{SPACE6_URL}/api/sandbox/test", {
1635
+ "test_cmd": "verify_ui",
1636
+ "url": f"{SPACE3_URL}"
1637
+ })
1638
+ log_activity(f"[Build Mode] Space 6 Test Verdict: {test_res.get('verdict')} | Reason: {test_res.get('reason')}")
1639
+
1640
+ log_activity("[Build Mode] Triggering Space 5 (The Vault) backup commit...")
1641
+ post_json(f"{SPACE5_URL}/api/vault/push", {})
1642
+ else:
1643
+ log_activity(f"[Build Mode Warning] Space 3 reported failure: {forge_res.get('error')}")
1644
+
1645
+ async def execute_eternity_cycle(goal: str):
1646
+ log_activity(f"[Eternity Mode] Initiating autonomous R&D cycle for goal: '{goal}'")
1647
+ log_activity("[Eternity Mode] Querying Space 4 (The Library) for new feature research...")
1648
+ research_res = post_json(f"{SPACE4_URL}/api/research", {"query": f"novel scientific or chemical calculation features and algorithms for {goal}"})
1649
+ brief = research_res.get("brief", "No new features found.")
1650
+ await update_db_brief(brief)
1651
+ log_activity(f"[Eternity Mode] Received research brief: {brief[:100]}...")
1652
+
1653
+ await rate_limiter.wait_for_nim()
1654
+ prompt = f"Goal: '{goal}'. Research Brief: '{brief}'. Plan the next feature/optimization code. Respond ONLY with JSON: " + '{"prompt": "task description", "context_rules": "rules"}'
1655
+ try:
1656
+ res = await nim_client.chat.completions.create(
1657
+ model="nvidia/llama-3.1-nemotron-70b-instruct",
1658
+ messages=[{"role": "user", "content": prompt}],
1659
+ max_tokens=300
1660
+ )
1661
+ task = json.loads(res.choices[0].message.content.strip())
1662
+ task_prompt = task.get("prompt")
1663
+ context_rules = task.get("context_rules", "")
1664
+ except Exception as e:
1665
+ log_activity(f"[Eternity Mode Error] NIM planning failed: {e}")
1666
+ return
1667
+
1668
+ log_activity(f"[Eternity Mode] Dispatching task to Space 3: '{task_prompt}'")
1669
+ forge_res = post_json(f"{SPACE3_URL}/api/forge/execute", {
1670
+ "task_id": f"eternity_{int(time.time())}",
1671
+ "action": "execute_code",
1672
+ "prompt": task_prompt,
1673
+ "context_rules": context_rules
1674
+ })
1675
+
1676
+ if forge_res.get("status") == "success":
1677
+ log_activity(f"[Eternity Mode] Space 3 success: {forge_res.get('summary')}")
1678
+ log_activity("[Eternity Mode] Triggering Space 5 (The Vault) backup commit...")
1679
+ post_json(f"{SPACE5_URL}/api/vault/push", {})
1680
+
1681
+
1682
+ def run_eternity_loop():
1683
+ log_activity("[Eternity Loop] Daemon thread started.")
1684
+ while True:
1685
+ try:
1686
+ if not db_pool:
1687
+ time.sleep(10)
1688
+ continue
1689
+
1690
+ loop = asyncio.new_event_loop()
1691
+ state = loop.run_until_complete(get_db_state())
1692
+ loop.close()
1693
+
1694
+ if not state:
1695
+ time.sleep(30)
1696
+ continue
1697
+
1698
+ goal = state["goal"]
1699
+ deadline = state["deadline"]
1700
+ current_mode = state["current_mode"]
1701
+
1702
+ now = datetime.now(timezone.utc)
1703
+ if current_mode == "build" and now >= deadline:
1704
+ loop = asyncio.new_event_loop()
1705
+ loop.run_until_complete(update_db_mode("eternity"))
1706
+ loop.close()
1707
+ current_mode = "eternity"
1708
+ log_activity("[Eternity Loop] Deadline reached. Transitioned to Eternity R&D Mode.")
1709
+
1710
+ if current_mode == "build":
1711
+ loop = asyncio.new_event_loop()
1712
+ loop.run_until_complete(execute_build_cycle(goal))
1713
+ loop.close()
1714
+ time.sleep(300)
1715
+ else:
1716
+ loop = asyncio.new_event_loop()
1717
+ loop.run_until_complete(execute_eternity_cycle(goal))
1718
+ loop.close()
1719
+ time.sleep(43200) # 12 hours
1720
+
1721
+ except Exception as e:
1722
+ log_activity(f"[Eternity Loop Error] Loop crash: {e}")
1723
+ time.sleep(60)
1724
 
1725
 
1726
  @app.get("/", response_class=HTMLResponse)
 
1944
  log_activity(f"[Backup Error] {e}")
1945
 
1946
 
1947
+ async def db_cleanup_loop():
1948
+ log_activity("Database Retention Cleanup task started")
1949
+ while True:
1950
+ try:
1951
+ if db_pool:
1952
+ async with db_pool.acquire() as conn:
1953
+ result = await conn.execute(
1954
+ "DELETE FROM agent_session_entries WHERE created_at < NOW() - INTERVAL '30 days'"
1955
+ )
1956
+ log_activity(f"[Cleanup] Nightly retention sweep complete. Status: {result}")
1957
+ except Exception as e:
1958
+ log_activity(f"[Cleanup Warning] Failed to run retention cleanup: {e}")
1959
+ await asyncio.sleep(86400) # Every 24 hours
1960
+
1961
+
1962
  @app.on_event("startup")
1963
  async def startup_event():
1964
  # Start the watchdog thread on startup
1965
  threading.Thread(target=run_watchdog, daemon=True).start()
1966
  # Start the local backup loop thread
1967
  threading.Thread(target=run_backup_loop, daemon=True).start()
1968
+ # Start the eternity R&D loop thread
1969
+ threading.Thread(target=run_eternity_loop, daemon=True).start()
1970
  # Start the db keep-alive loop on FastAPI event loop
1971
  asyncio.create_task(db_heartbeat_loop())
1972
  # Start the db nightly retention cleanup loop