| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436 |
- """
- api.v1.agents — Agent CRUD + Execution endpoints.
- POST /api/v1/agents Create agent
- GET /api/v1/agents List agents
- GET /api/v1/agents/{agent_id} Get agent
- PUT /api/v1/agents/{agent_id} Update agent (auto version)
- DELETE /api/v1/agents/{agent_id} Soft delete
- POST /api/v1/agents/{agent_id}/run Synchronous execution
- POST /api/v1/agents/{agent_id}/rollback Rollback version
- """
- from __future__ import annotations
- import json
- import hashlib
- import time
- from typing import Any, Dict, Optional
- from fastapi import APIRouter, Depends, HTTPException
- from pydantic import BaseModel, Field
- from agentpaas.api.deps import get_tenant, get_database
- from agentpaas.api.middleware.auth import TenantContext
- from agentpaas.db.models import Database, gen_id, now_utc
- router = APIRouter(prefix="/agents", tags=["agents"])
- # ── Request/Response Models ──
- class CreateAgentRequest(BaseModel):
- name: str = Field(..., max_length=256)
- description: str = Field(default="", max_length=4096)
- config: Dict[str, Any]
- tags: list = Field(default_factory=list)
- environment: str = Field(default="production", max_length=64)
- class UpdateAgentRequest(BaseModel):
- config: Dict[str, Any]
- changelog: str = ""
- class RunRequest(BaseModel):
- input: str = Field(..., max_length=102400) # 100KB max
- parameters: Dict[str, Any] = Field(default_factory=dict)
- context: Dict[str, Any] = Field(default_factory=dict)
- class RollbackRequest(BaseModel):
- target_version: int
- # ── CRUD Endpoints ──
- @router.post("", status_code=201)
- async def create_agent(
- req: CreateAgentRequest,
- tenant: TenantContext = Depends(get_tenant),
- db: Database = Depends(get_database),
- ):
- """Create a new agent. Auto-compiles config via lambdagent."""
- agent_id = gen_id("ag_")
- config_json = json.dumps(req.config, ensure_ascii=False)
- config_hash = hashlib.sha256(config_json.encode()).hexdigest()
- # Validate config by compiling (fail fast)
- try:
- _compile_agent(req.config)
- except Exception as e:
- raise HTTPException(400, {"error": {"code": "INVALID_CONFIG", "message": str(e)}})
- now = now_utc()
- db.execute(
- "INSERT INTO agents (id, tenant_id, name, description, current_version, tags, environment, status, created_at, updated_at) "
- "VALUES (?, ?, ?, ?, 1, ?, ?, 'active', ?, ?)",
- (agent_id, tenant.tenant_id, req.name, req.description,
- json.dumps(req.tags), req.environment, now, now)
- )
- db.execute(
- "INSERT INTO agent_versions (agent_id, version, config, config_hash, changelog, created_by, created_at) "
- "VALUES (?, 1, ?, ?, 'Initial version', ?, ?)",
- (agent_id, config_json, config_hash, tenant.user_id, now)
- )
- db.commit()
- return {
- "agent_id": agent_id,
- "version": 1,
- "created_at": now,
- "endpoint": f"/api/v1/agents/{agent_id}",
- }
- @router.get("")
- async def list_agents(
- tag: Optional[str] = None,
- tenant: TenantContext = Depends(get_tenant),
- db: Database = Depends(get_database),
- ):
- """List all agents for this tenant."""
- sql = "SELECT * FROM agents WHERE tenant_id = ? AND status = 'active'"
- params = [tenant.tenant_id]
- if tag:
- # SEC-08/SEC-12: Escape SQL LIKE wildcards
- safe_tag = tag.replace("%", "\\%").replace("_", "\\_")
- sql += " AND tags LIKE ? ESCAPE '\\'"
- params.append(f'%"{safe_tag}"%')
- sql += " ORDER BY updated_at DESC"
- agents = db.fetchall(sql, tuple(params))
- for a in agents:
- a["tags"] = json.loads(a.get("tags", "[]"))
- return {"agents": agents, "count": len(agents)}
- @router.get("/{agent_id}")
- async def get_agent(
- agent_id: str,
- tenant: TenantContext = Depends(get_tenant),
- db: Database = Depends(get_database),
- ):
- """Get agent details including current version config."""
- agent = db.fetchone(
- "SELECT * FROM agents WHERE id = ? AND tenant_id = ? AND status = 'active'",
- (agent_id, tenant.tenant_id)
- )
- if not agent:
- raise HTTPException(404, {"error": {"code": "AGENT_NOT_FOUND", "message": f"Agent {agent_id} not found"}})
- version = db.fetchone(
- "SELECT * FROM agent_versions WHERE agent_id = ? AND version = ?",
- (agent_id, agent["current_version"])
- )
- agent["tags"] = json.loads(agent.get("tags", "[]"))
- agent["config"] = json.loads(version["config"]) if version else {}
- return agent
- @router.put("/{agent_id}")
- async def update_agent(
- agent_id: str,
- req: UpdateAgentRequest,
- tenant: TenantContext = Depends(get_tenant),
- db: Database = Depends(get_database),
- ):
- """Update agent config. Auto-increments version."""
- agent = db.fetchone(
- "SELECT * FROM agents WHERE id = ? AND tenant_id = ? AND status = 'active'",
- (agent_id, tenant.tenant_id)
- )
- if not agent:
- raise HTTPException(404, {"error": {"code": "AGENT_NOT_FOUND"}})
- config_json = json.dumps(req.config, ensure_ascii=False)
- config_hash = hashlib.sha256(config_json.encode()).hexdigest()
- # Check if config actually changed
- last_version = db.fetchone(
- "SELECT config_hash FROM agent_versions WHERE agent_id = ? ORDER BY version DESC LIMIT 1",
- (agent_id,)
- )
- if last_version and last_version["config_hash"] == config_hash:
- return {"message": "Config unchanged, no new version created", "version": agent["current_version"]}
- # Validate
- try:
- _compile_agent(req.config)
- except Exception as e:
- raise HTTPException(400, {"error": {"code": "INVALID_CONFIG", "message": str(e)}})
- new_version = agent["current_version"] + 1
- now = now_utc()
- db.execute(
- "INSERT INTO agent_versions (agent_id, version, config, config_hash, changelog, created_by, created_at) "
- "VALUES (?, ?, ?, ?, ?, ?, ?)",
- (agent_id, new_version, config_json, config_hash, req.changelog, tenant.user_id, now)
- )
- db.execute(
- "UPDATE agents SET current_version = ?, updated_at = ? WHERE id = ?",
- (new_version, now, agent_id)
- )
- db.commit()
- return {"agent_id": agent_id, "version": new_version, "updated_at": now}
- @router.delete("/{agent_id}")
- async def delete_agent(
- agent_id: str,
- tenant: TenantContext = Depends(get_tenant),
- db: Database = Depends(get_database),
- ):
- """Soft delete agent."""
- db.execute(
- "UPDATE agents SET status = 'deleted', updated_at = ? WHERE id = ? AND tenant_id = ?",
- (now_utc(), agent_id, tenant.tenant_id)
- )
- db.commit()
- return {"message": "Agent deleted", "agent_id": agent_id}
- @router.post("/{agent_id}/rollback")
- async def rollback_agent(
- agent_id: str,
- req: RollbackRequest,
- tenant: TenantContext = Depends(get_tenant),
- db: Database = Depends(get_database),
- ):
- """Rollback to a previous version."""
- version = db.fetchone(
- "SELECT * FROM agent_versions WHERE agent_id = ? AND version = ?",
- (agent_id, req.target_version)
- )
- if not version:
- raise HTTPException(404, {"error": {"code": "VERSION_NOT_FOUND"}})
- db.execute(
- "UPDATE agents SET current_version = ?, updated_at = ? WHERE id = ? AND tenant_id = ?",
- (req.target_version, now_utc(), agent_id, tenant.tenant_id)
- )
- db.commit()
- return {"agent_id": agent_id, "version": req.target_version, "message": "Rolled back"}
- # ── Execution Endpoint ──
- @router.post("/{agent_id}/run")
- async def run_agent(
- agent_id: str,
- req: RunRequest,
- tenant: TenantContext = Depends(get_tenant),
- db: Database = Depends(get_database),
- ):
- """
- Synchronous agent execution.
- AgentPaaS.serve(request) =
- let yaml = Registry.load(agent_id) in
- let term = lambdagent.from_config(yaml) in
- let result = Runtime.reduce(term, input) in
- (result, trace)
- """
- # Load agent
- agent = db.fetchone(
- "SELECT * FROM agents WHERE id = ? AND tenant_id = ? AND status = 'active'",
- (agent_id, tenant.tenant_id)
- )
- if not agent:
- raise HTTPException(404, {"error": {"code": "AGENT_NOT_FOUND"}})
- version_rec = db.fetchone(
- "SELECT * FROM agent_versions WHERE agent_id = ? AND version = ?",
- (agent_id, agent["current_version"])
- )
- config = json.loads(version_rec["config"])
- # Apply runtime parameter overrides
- for key, val in req.parameters.items():
- parts = key.split(".")
- target = config
- for p in parts[:-1]:
- target = target.setdefault(p, {})
- target[parts[-1]] = val
- # Create run record
- run_id = gen_id("run_")
- now = now_utc()
- db.execute(
- "INSERT INTO runs (id, agent_id, agent_version, tenant_id, input, status, created_at) "
- "VALUES (?, ?, ?, ?, ?, 'running', ?)",
- (run_id, agent_id, agent["current_version"], tenant.tenant_id, req.input, now)
- )
- db.commit()
- # Execute via lambdagent
- t0 = time.time()
- try:
- result, trace_info = _execute_agent(config, req.input)
- duration_ms = int((time.time() - t0) * 1000)
- db.execute(
- "UPDATE runs SET status='completed', output=?, duration_ms=?, "
- "input_tokens=?, output_tokens=?, steps=?, completed_at=? WHERE id=?",
- (str(result), duration_ms,
- trace_info.get("input_tokens", 0), trace_info.get("output_tokens", 0),
- trace_info.get("steps", 0), now_utc(), run_id)
- )
- db.commit()
- return {
- "run_id": run_id,
- "status": "completed",
- "output": str(result),
- "usage": {
- "input_tokens": trace_info.get("input_tokens", 0),
- "output_tokens": trace_info.get("output_tokens", 0),
- "total_tokens": trace_info.get("total_tokens", 0),
- "steps": trace_info.get("steps", 0),
- "duration_ms": duration_ms,
- },
- }
- except Exception as e:
- duration_ms = int((time.time() - t0) * 1000)
- # SEC-04: Log full detail server-side, return sanitized error to client
- from agentpaas.observability.logging import logger
- logger.error("Agent execution failed: run=%s agent=%s error=%s", run_id, agent_id, str(e), exc_info=True)
- db.execute(
- "UPDATE runs SET status='failed', error=?, duration_ms=?, completed_at=? WHERE id=?",
- (json.dumps({"code": type(e).__name__}), duration_ms, now_utc(), run_id)
- )
- db.commit()
- raise HTTPException(500, {"error": {"code": "EXECUTION_ERROR", "message": "Agent execution failed", "run_id": run_id}})
- # ── Agent Versions ──
- @router.get("/{agent_id}/versions")
- async def list_versions(
- agent_id: str,
- tenant: TenantContext = Depends(get_tenant),
- db: Database = Depends(get_database),
- ):
- """List all versions of an agent."""
- versions = db.fetchall(
- "SELECT v.*, a.current_version FROM agent_versions v "
- "JOIN agents a ON v.agent_id = a.id "
- "WHERE v.agent_id = ? AND a.tenant_id = ? ORDER BY v.version DESC",
- (agent_id, tenant.tenant_id)
- )
- for v in versions:
- v["is_current"] = v["version"] == v.pop("current_version", None)
- return {"versions": versions}
- # ── Record-Only Endpoint (for external execution backends like Claude Code CLI) ──
- class RecordRunRequest(BaseModel):
- """记录一次外部执行结果(不触发 lambdagent 执行)"""
- input: str
- output: str
- status: str = "completed"
- duration_ms: int = 0
- steps: int = 0
- source: str = "external"
- @router.post("/{agent_id}/runs/record", status_code=201)
- async def record_run(
- agent_id: str,
- req: RecordRunRequest,
- tenant: TenantContext = Depends(get_tenant),
- db: Database = Depends(get_database),
- ):
- """
- Record an externally-executed run (e.g., from Claude Code CLI).
- Does NOT trigger lambdagent execution — only writes to the runs table.
- """
- agent = db.fetchone(
- "SELECT * FROM agents WHERE id = ? AND tenant_id = ? AND status = 'active'",
- (agent_id, tenant.tenant_id)
- )
- if not agent:
- raise HTTPException(404, {"error": {"code": "AGENT_NOT_FOUND"}})
- run_id = gen_id("run_")
- now = now_utc()
- db.execute(
- "INSERT INTO runs (id, agent_id, agent_version, tenant_id, input, output, "
- "status, duration_ms, steps, created_at, completed_at) "
- "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
- (run_id, agent_id, agent["current_version"], tenant.tenant_id,
- req.input, req.output, req.status, req.duration_ms, req.steps, now, now)
- )
- db.commit()
- return {
- "run_id": run_id,
- "status": req.status,
- "source": req.source,
- "message": "Run recorded (external execution)",
- }
- # ── Runs History ──
- @router.get("/{agent_id}/runs")
- async def list_runs(
- agent_id: str,
- limit: int = 20,
- tenant: TenantContext = Depends(get_tenant),
- db: Database = Depends(get_database),
- ):
- """List recent runs for an agent."""
- runs = db.fetchall(
- "SELECT * FROM runs WHERE agent_id = ? AND tenant_id = ? ORDER BY created_at DESC LIMIT ?",
- (agent_id, tenant.tenant_id, limit)
- )
- return {"runs": runs}
- # ── Internal helpers ──
- def _compile_agent(config: dict):
- """Compile agent config via lambdagent. Raises on invalid config."""
- import tempfile, yaml, os
- with tempfile.NamedTemporaryFile(mode='w', suffix='.yml', delete=False, encoding='utf-8') as f:
- yaml.dump(config, f, allow_unicode=True)
- tmp_path = f.name
- try:
- from lambdagent.fromconfig import from_config
- return from_config(tmp_path)
- finally:
- os.unlink(tmp_path)
- def _execute_agent(config: dict, input_text: str):
- """Execute agent via lambdagent. Returns (result, trace_info)."""
- import tempfile, yaml, os
- with tempfile.NamedTemporaryFile(mode='w', suffix='.yml', delete=False, encoding='utf-8') as f:
- yaml.dump(config, f, allow_unicode=True)
- tmp_path = f.name
- try:
- from lambdagent.fromconfig import from_config
- from lambdagent.core import Context
- term = from_config(tmp_path)
- ctx = Context()
- result = term.apply(input_text, ctx)
- # Extract trace info
- trace_info = {
- "steps": len(ctx.trace),
- "input_tokens": sum(getattr(e, 'tokens_used', 0) for e in ctx.trace),
- "output_tokens": 0,
- "total_tokens": sum(getattr(e, 'tokens_used', 0) for e in ctx.trace),
- }
- return result, trace_info
- finally:
- os.unlink(tmp_path)
|