agents.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. """
  2. api.v1.agents — Agent CRUD + Execution endpoints.
  3. POST /api/v1/agents Create agent
  4. GET /api/v1/agents List agents
  5. GET /api/v1/agents/{agent_id} Get agent
  6. PUT /api/v1/agents/{agent_id} Update agent (auto version)
  7. DELETE /api/v1/agents/{agent_id} Soft delete
  8. POST /api/v1/agents/{agent_id}/run Synchronous execution
  9. POST /api/v1/agents/{agent_id}/rollback Rollback version
  10. """
  11. from __future__ import annotations
  12. import json
  13. import hashlib
  14. import time
  15. from typing import Any, Dict, Optional
  16. from fastapi import APIRouter, Depends, HTTPException
  17. from pydantic import BaseModel, Field
  18. from agentpaas.api.deps import get_tenant, get_database
  19. from agentpaas.api.middleware.auth import TenantContext
  20. from agentpaas.db.models import Database, gen_id, now_utc
  21. router = APIRouter(prefix="/agents", tags=["agents"])
  22. # ── Request/Response Models ──
  23. class CreateAgentRequest(BaseModel):
  24. name: str = Field(..., max_length=256)
  25. description: str = Field(default="", max_length=4096)
  26. config: Dict[str, Any]
  27. tags: list = Field(default_factory=list)
  28. environment: str = Field(default="production", max_length=64)
  29. class UpdateAgentRequest(BaseModel):
  30. config: Dict[str, Any]
  31. changelog: str = ""
  32. class RunRequest(BaseModel):
  33. input: str = Field(..., max_length=102400) # 100KB max
  34. parameters: Dict[str, Any] = Field(default_factory=dict)
  35. context: Dict[str, Any] = Field(default_factory=dict)
  36. class RollbackRequest(BaseModel):
  37. target_version: int
  38. # ── CRUD Endpoints ──
  39. @router.post("", status_code=201)
  40. async def create_agent(
  41. req: CreateAgentRequest,
  42. tenant: TenantContext = Depends(get_tenant),
  43. db: Database = Depends(get_database),
  44. ):
  45. """Create a new agent. Auto-compiles config via lambdagent."""
  46. agent_id = gen_id("ag_")
  47. config_json = json.dumps(req.config, ensure_ascii=False)
  48. config_hash = hashlib.sha256(config_json.encode()).hexdigest()
  49. # Validate config by compiling (fail fast)
  50. try:
  51. _compile_agent(req.config)
  52. except Exception as e:
  53. raise HTTPException(400, {"error": {"code": "INVALID_CONFIG", "message": str(e)}})
  54. now = now_utc()
  55. db.execute(
  56. "INSERT INTO agents (id, tenant_id, name, description, current_version, tags, environment, status, created_at, updated_at) "
  57. "VALUES (?, ?, ?, ?, 1, ?, ?, 'active', ?, ?)",
  58. (agent_id, tenant.tenant_id, req.name, req.description,
  59. json.dumps(req.tags), req.environment, now, now)
  60. )
  61. db.execute(
  62. "INSERT INTO agent_versions (agent_id, version, config, config_hash, changelog, created_by, created_at) "
  63. "VALUES (?, 1, ?, ?, 'Initial version', ?, ?)",
  64. (agent_id, config_json, config_hash, tenant.user_id, now)
  65. )
  66. db.commit()
  67. return {
  68. "agent_id": agent_id,
  69. "version": 1,
  70. "created_at": now,
  71. "endpoint": f"/api/v1/agents/{agent_id}",
  72. }
  73. @router.get("")
  74. async def list_agents(
  75. tag: Optional[str] = None,
  76. tenant: TenantContext = Depends(get_tenant),
  77. db: Database = Depends(get_database),
  78. ):
  79. """List all agents for this tenant."""
  80. sql = "SELECT * FROM agents WHERE tenant_id = ? AND status = 'active'"
  81. params = [tenant.tenant_id]
  82. if tag:
  83. # SEC-08/SEC-12: Escape SQL LIKE wildcards
  84. safe_tag = tag.replace("%", "\\%").replace("_", "\\_")
  85. sql += " AND tags LIKE ? ESCAPE '\\'"
  86. params.append(f'%"{safe_tag}"%')
  87. sql += " ORDER BY updated_at DESC"
  88. agents = db.fetchall(sql, tuple(params))
  89. for a in agents:
  90. a["tags"] = json.loads(a.get("tags", "[]"))
  91. return {"agents": agents, "count": len(agents)}
  92. @router.get("/{agent_id}")
  93. async def get_agent(
  94. agent_id: str,
  95. tenant: TenantContext = Depends(get_tenant),
  96. db: Database = Depends(get_database),
  97. ):
  98. """Get agent details including current version config."""
  99. agent = db.fetchone(
  100. "SELECT * FROM agents WHERE id = ? AND tenant_id = ? AND status = 'active'",
  101. (agent_id, tenant.tenant_id)
  102. )
  103. if not agent:
  104. raise HTTPException(404, {"error": {"code": "AGENT_NOT_FOUND", "message": f"Agent {agent_id} not found"}})
  105. version = db.fetchone(
  106. "SELECT * FROM agent_versions WHERE agent_id = ? AND version = ?",
  107. (agent_id, agent["current_version"])
  108. )
  109. agent["tags"] = json.loads(agent.get("tags", "[]"))
  110. agent["config"] = json.loads(version["config"]) if version else {}
  111. return agent
  112. @router.put("/{agent_id}")
  113. async def update_agent(
  114. agent_id: str,
  115. req: UpdateAgentRequest,
  116. tenant: TenantContext = Depends(get_tenant),
  117. db: Database = Depends(get_database),
  118. ):
  119. """Update agent config. Auto-increments version."""
  120. agent = db.fetchone(
  121. "SELECT * FROM agents WHERE id = ? AND tenant_id = ? AND status = 'active'",
  122. (agent_id, tenant.tenant_id)
  123. )
  124. if not agent:
  125. raise HTTPException(404, {"error": {"code": "AGENT_NOT_FOUND"}})
  126. config_json = json.dumps(req.config, ensure_ascii=False)
  127. config_hash = hashlib.sha256(config_json.encode()).hexdigest()
  128. # Check if config actually changed
  129. last_version = db.fetchone(
  130. "SELECT config_hash FROM agent_versions WHERE agent_id = ? ORDER BY version DESC LIMIT 1",
  131. (agent_id,)
  132. )
  133. if last_version and last_version["config_hash"] == config_hash:
  134. return {"message": "Config unchanged, no new version created", "version": agent["current_version"]}
  135. # Validate
  136. try:
  137. _compile_agent(req.config)
  138. except Exception as e:
  139. raise HTTPException(400, {"error": {"code": "INVALID_CONFIG", "message": str(e)}})
  140. new_version = agent["current_version"] + 1
  141. now = now_utc()
  142. db.execute(
  143. "INSERT INTO agent_versions (agent_id, version, config, config_hash, changelog, created_by, created_at) "
  144. "VALUES (?, ?, ?, ?, ?, ?, ?)",
  145. (agent_id, new_version, config_json, config_hash, req.changelog, tenant.user_id, now)
  146. )
  147. db.execute(
  148. "UPDATE agents SET current_version = ?, updated_at = ? WHERE id = ?",
  149. (new_version, now, agent_id)
  150. )
  151. db.commit()
  152. return {"agent_id": agent_id, "version": new_version, "updated_at": now}
  153. @router.delete("/{agent_id}")
  154. async def delete_agent(
  155. agent_id: str,
  156. tenant: TenantContext = Depends(get_tenant),
  157. db: Database = Depends(get_database),
  158. ):
  159. """Soft delete agent."""
  160. db.execute(
  161. "UPDATE agents SET status = 'deleted', updated_at = ? WHERE id = ? AND tenant_id = ?",
  162. (now_utc(), agent_id, tenant.tenant_id)
  163. )
  164. db.commit()
  165. return {"message": "Agent deleted", "agent_id": agent_id}
  166. @router.post("/{agent_id}/rollback")
  167. async def rollback_agent(
  168. agent_id: str,
  169. req: RollbackRequest,
  170. tenant: TenantContext = Depends(get_tenant),
  171. db: Database = Depends(get_database),
  172. ):
  173. """Rollback to a previous version."""
  174. version = db.fetchone(
  175. "SELECT * FROM agent_versions WHERE agent_id = ? AND version = ?",
  176. (agent_id, req.target_version)
  177. )
  178. if not version:
  179. raise HTTPException(404, {"error": {"code": "VERSION_NOT_FOUND"}})
  180. db.execute(
  181. "UPDATE agents SET current_version = ?, updated_at = ? WHERE id = ? AND tenant_id = ?",
  182. (req.target_version, now_utc(), agent_id, tenant.tenant_id)
  183. )
  184. db.commit()
  185. return {"agent_id": agent_id, "version": req.target_version, "message": "Rolled back"}
  186. # ── Execution Endpoint ──
  187. @router.post("/{agent_id}/run")
  188. async def run_agent(
  189. agent_id: str,
  190. req: RunRequest,
  191. tenant: TenantContext = Depends(get_tenant),
  192. db: Database = Depends(get_database),
  193. ):
  194. """
  195. Synchronous agent execution.
  196. AgentPaaS.serve(request) =
  197. let yaml = Registry.load(agent_id) in
  198. let term = lambdagent.from_config(yaml) in
  199. let result = Runtime.reduce(term, input) in
  200. (result, trace)
  201. """
  202. # Load agent
  203. agent = db.fetchone(
  204. "SELECT * FROM agents WHERE id = ? AND tenant_id = ? AND status = 'active'",
  205. (agent_id, tenant.tenant_id)
  206. )
  207. if not agent:
  208. raise HTTPException(404, {"error": {"code": "AGENT_NOT_FOUND"}})
  209. version_rec = db.fetchone(
  210. "SELECT * FROM agent_versions WHERE agent_id = ? AND version = ?",
  211. (agent_id, agent["current_version"])
  212. )
  213. config = json.loads(version_rec["config"])
  214. # Apply runtime parameter overrides
  215. for key, val in req.parameters.items():
  216. parts = key.split(".")
  217. target = config
  218. for p in parts[:-1]:
  219. target = target.setdefault(p, {})
  220. target[parts[-1]] = val
  221. # Create run record
  222. run_id = gen_id("run_")
  223. now = now_utc()
  224. db.execute(
  225. "INSERT INTO runs (id, agent_id, agent_version, tenant_id, input, status, created_at) "
  226. "VALUES (?, ?, ?, ?, ?, 'running', ?)",
  227. (run_id, agent_id, agent["current_version"], tenant.tenant_id, req.input, now)
  228. )
  229. db.commit()
  230. # Execute via lambdagent
  231. t0 = time.time()
  232. try:
  233. result, trace_info = _execute_agent(config, req.input)
  234. duration_ms = int((time.time() - t0) * 1000)
  235. db.execute(
  236. "UPDATE runs SET status='completed', output=?, duration_ms=?, "
  237. "input_tokens=?, output_tokens=?, steps=?, completed_at=? WHERE id=?",
  238. (str(result), duration_ms,
  239. trace_info.get("input_tokens", 0), trace_info.get("output_tokens", 0),
  240. trace_info.get("steps", 0), now_utc(), run_id)
  241. )
  242. db.commit()
  243. return {
  244. "run_id": run_id,
  245. "status": "completed",
  246. "output": str(result),
  247. "usage": {
  248. "input_tokens": trace_info.get("input_tokens", 0),
  249. "output_tokens": trace_info.get("output_tokens", 0),
  250. "total_tokens": trace_info.get("total_tokens", 0),
  251. "steps": trace_info.get("steps", 0),
  252. "duration_ms": duration_ms,
  253. },
  254. }
  255. except Exception as e:
  256. duration_ms = int((time.time() - t0) * 1000)
  257. # SEC-04: Log full detail server-side, return sanitized error to client
  258. from agentpaas.observability.logging import logger
  259. logger.error("Agent execution failed: run=%s agent=%s error=%s", run_id, agent_id, str(e), exc_info=True)
  260. db.execute(
  261. "UPDATE runs SET status='failed', error=?, duration_ms=?, completed_at=? WHERE id=?",
  262. (json.dumps({"code": type(e).__name__}), duration_ms, now_utc(), run_id)
  263. )
  264. db.commit()
  265. raise HTTPException(500, {"error": {"code": "EXECUTION_ERROR", "message": "Agent execution failed", "run_id": run_id}})
  266. # ── Agent Versions ──
  267. @router.get("/{agent_id}/versions")
  268. async def list_versions(
  269. agent_id: str,
  270. tenant: TenantContext = Depends(get_tenant),
  271. db: Database = Depends(get_database),
  272. ):
  273. """List all versions of an agent."""
  274. versions = db.fetchall(
  275. "SELECT v.*, a.current_version FROM agent_versions v "
  276. "JOIN agents a ON v.agent_id = a.id "
  277. "WHERE v.agent_id = ? AND a.tenant_id = ? ORDER BY v.version DESC",
  278. (agent_id, tenant.tenant_id)
  279. )
  280. for v in versions:
  281. v["is_current"] = v["version"] == v.pop("current_version", None)
  282. return {"versions": versions}
  283. # ── Record-Only Endpoint (for external execution backends like Claude Code CLI) ──
  284. class RecordRunRequest(BaseModel):
  285. """记录一次外部执行结果(不触发 lambdagent 执行)"""
  286. input: str
  287. output: str
  288. status: str = "completed"
  289. duration_ms: int = 0
  290. steps: int = 0
  291. source: str = "external"
  292. @router.post("/{agent_id}/runs/record", status_code=201)
  293. async def record_run(
  294. agent_id: str,
  295. req: RecordRunRequest,
  296. tenant: TenantContext = Depends(get_tenant),
  297. db: Database = Depends(get_database),
  298. ):
  299. """
  300. Record an externally-executed run (e.g., from Claude Code CLI).
  301. Does NOT trigger lambdagent execution — only writes to the runs table.
  302. """
  303. agent = db.fetchone(
  304. "SELECT * FROM agents WHERE id = ? AND tenant_id = ? AND status = 'active'",
  305. (agent_id, tenant.tenant_id)
  306. )
  307. if not agent:
  308. raise HTTPException(404, {"error": {"code": "AGENT_NOT_FOUND"}})
  309. run_id = gen_id("run_")
  310. now = now_utc()
  311. db.execute(
  312. "INSERT INTO runs (id, agent_id, agent_version, tenant_id, input, output, "
  313. "status, duration_ms, steps, created_at, completed_at) "
  314. "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
  315. (run_id, agent_id, agent["current_version"], tenant.tenant_id,
  316. req.input, req.output, req.status, req.duration_ms, req.steps, now, now)
  317. )
  318. db.commit()
  319. return {
  320. "run_id": run_id,
  321. "status": req.status,
  322. "source": req.source,
  323. "message": "Run recorded (external execution)",
  324. }
  325. # ── Runs History ──
  326. @router.get("/{agent_id}/runs")
  327. async def list_runs(
  328. agent_id: str,
  329. limit: int = 20,
  330. tenant: TenantContext = Depends(get_tenant),
  331. db: Database = Depends(get_database),
  332. ):
  333. """List recent runs for an agent."""
  334. runs = db.fetchall(
  335. "SELECT * FROM runs WHERE agent_id = ? AND tenant_id = ? ORDER BY created_at DESC LIMIT ?",
  336. (agent_id, tenant.tenant_id, limit)
  337. )
  338. return {"runs": runs}
  339. # ── Internal helpers ──
  340. def _compile_agent(config: dict):
  341. """Compile agent config via lambdagent. Raises on invalid config."""
  342. import tempfile, yaml, os
  343. with tempfile.NamedTemporaryFile(mode='w', suffix='.yml', delete=False, encoding='utf-8') as f:
  344. yaml.dump(config, f, allow_unicode=True)
  345. tmp_path = f.name
  346. try:
  347. from lambdagent.fromconfig import from_config
  348. return from_config(tmp_path)
  349. finally:
  350. os.unlink(tmp_path)
  351. def _execute_agent(config: dict, input_text: str):
  352. """Execute agent via lambdagent. Returns (result, trace_info)."""
  353. import tempfile, yaml, os
  354. with tempfile.NamedTemporaryFile(mode='w', suffix='.yml', delete=False, encoding='utf-8') as f:
  355. yaml.dump(config, f, allow_unicode=True)
  356. tmp_path = f.name
  357. try:
  358. from lambdagent.fromconfig import from_config
  359. from lambdagent.core import Context
  360. term = from_config(tmp_path)
  361. ctx = Context()
  362. result = term.apply(input_text, ctx)
  363. # Extract trace info
  364. trace_info = {
  365. "steps": len(ctx.trace),
  366. "input_tokens": sum(getattr(e, 'tokens_used', 0) for e in ctx.trace),
  367. "output_tokens": 0,
  368. "total_tokens": sum(getattr(e, 'tokens_used', 0) for e in ctx.trace),
  369. }
  370. return result, trace_info
  371. finally:
  372. os.unlink(tmp_path)