BE-CAL-003: Add Agent model with status/heartbeat/exhausted fields

- New app/models/agent.py with Agent model, AgentStatus & ExhaustReason enums
- Agent has 1-to-1 FK to User, unique agent_id (OpenClaw $AGENT_ID),
  claw_identifier (OpenClaw instance, convention-matches MonitoredServer.identifier)
- Status fields: status (idle/on_call/busy/exhausted/offline), last_heartbeat
- Exhausted tracking: exhausted_at, recovery_at, exhaust_reason (rate_limit/billing)
- User model: added 'agent' back-reference (uselist=False)
- Schemas: AgentResponse, AgentStatusUpdate, UserCreate now accepts agent_id+claw_identifier
- UserResponse: includes agent_id when agent is bound
- Users router: create_user creates Agent record when agent_id+claw_identifier provided
- Auto-migration: CREATE TABLE agents in _migrate_schema()
- Startup imports: agent and calendar models registered
This commit is contained in:
zhi
2026-03-30 20:47:44 +00:00
parent a9b4fa14b4
commit 1c062ff4f1
5 changed files with 257 additions and 5 deletions

View File

@@ -261,6 +261,27 @@ def _migrate_schema():
if _has_table(db, "server_states") and not _has_column(db, "server_states", "nginx_sites_json"):
db.execute(text("ALTER TABLE server_states ADD COLUMN nginx_sites_json TEXT NULL"))
# --- agents table (BE-CAL-003) ---
if not _has_table(db, "agents"):
db.execute(text("""
CREATE TABLE agents (
id INTEGER NOT NULL AUTO_INCREMENT,
user_id INTEGER NOT NULL,
agent_id VARCHAR(128) NOT NULL,
claw_identifier VARCHAR(128) NOT NULL,
status ENUM('idle','on_call','busy','exhausted','offline') NOT NULL DEFAULT 'idle',
last_heartbeat DATETIME NULL,
exhausted_at DATETIME NULL,
recovery_at DATETIME NULL,
exhaust_reason ENUM('rate_limit','billing') NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
UNIQUE INDEX idx_agents_user_id (user_id),
UNIQUE INDEX idx_agents_agent_id (agent_id),
CONSTRAINT fk_agents_user_id FOREIGN KEY (user_id) REFERENCES users(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
"""))
# --- essentials table (BE-PR-003) ---
if not _has_table(db, "essentials"):
db.execute(text("""
@@ -316,7 +337,7 @@ def _sync_default_user_roles(db):
@app.on_event("startup")
def startup():
from app.core.config import Base, engine, SessionLocal
from app.models import models, webhook, apikey, activity, milestone, notification, worklog, monitor, role_permission, task, support, meeting, proposal, propose, essential
from app.models import models, webhook, apikey, activity, milestone, notification, worklog, monitor, role_permission, task, support, meeting, proposal, propose, essential, agent, calendar
Base.metadata.create_all(bind=engine)
_migrate_schema()