CREATE TABLE agent_settings ( id smallint PRIMARY KEY DEFAULT 1 CHECK (id = 1), enabled boolean NOT NULL DEFAULT false, provider_name text NOT NULL DEFAULT '', provider_type text NOT NULL DEFAULT 'openai_compatible' CHECK (provider_type IN ('openai_compatible','openai','custom_http')), base_url text NOT NULL DEFAULT '', model text NOT NULL DEFAULT '', encrypted_api_key bytea, timeout_ms integer NOT NULL DEFAULT 30000 CHECK (timeout_ms BETWEEN 1000 AND 120000), max_tokens integer NOT NULL DEFAULT 2048 CHECK (max_tokens BETWEEN 1 AND 32768), temperature double precision NOT NULL DEFAULT 0.2 CHECK (temperature BETWEEN 0 AND 2), system_prompt text NOT NULL DEFAULT '', max_history integer NOT NULL DEFAULT 20 CHECK (max_history BETWEEN 1 AND 100), rate_limit integer NOT NULL DEFAULT 30 CHECK (rate_limit BETWEEN 1 AND 600), request_logging boolean NOT NULL DEFAULT false, tool_enabled boolean NOT NULL DEFAULT true, confirmation_required boolean NOT NULL DEFAULT true, created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(), updated_by uuid REFERENCES users(id) ); CREATE TABLE agent_sessions ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), admin_user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, title text NOT NULL DEFAULT 'OverCooked Admin Agent', created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(), expires_at timestamptz NOT NULL DEFAULT (now() + interval '24 hours') ); CREATE INDEX agent_sessions_admin_idx ON agent_sessions(admin_user_id, updated_at DESC); CREATE TABLE agent_messages ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), session_id uuid NOT NULL REFERENCES agent_sessions(id) ON DELETE CASCADE, role text NOT NULL CHECK (role IN ('system','user','assistant','tool')), content text NOT NULL, tool_name text, tool_call_id text, confirmation_state text NOT NULL DEFAULT 'none' CHECK (confirmation_state IN ('none','pending','confirmed','cancelled','expired')), created_at timestamptz NOT NULL DEFAULT now() ); CREATE INDEX agent_messages_session_idx ON agent_messages(session_id, created_at); CREATE TABLE agent_audit ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), session_id uuid REFERENCES agent_sessions(id) ON DELETE SET NULL, admin_user_id uuid NOT NULL REFERENCES users(id) ON DELETE RESTRICT, capability text NOT NULL, action text NOT NULL, target text NOT NULL DEFAULT '', request_summary text NOT NULL DEFAULT '', result jsonb NOT NULL DEFAULT '{}'::jsonb, status text NOT NULL CHECK (status IN ('planned','pending_confirmation','success','cancelled','failed')), error_code text NOT NULL DEFAULT '', trace_id text NOT NULL DEFAULT '', latency_ms bigint NOT NULL DEFAULT 0, created_at timestamptz NOT NULL DEFAULT now() ); CREATE INDEX agent_audit_admin_idx ON agent_audit(admin_user_id, created_at DESC);