-- 000046_agent_tasks.sql — 智能体节点任务下发/认领/上报 + 个人智能体安全策略。

-- 任务表:管理员下发,节点经令牌认证后按池认领(SKIP LOCKED),执行后上报结果;
-- 失败按 attempts/max_attempts 退避重入队。
CREATE TABLE IF NOT EXISTS gateway.agent_tasks (
    id uuid PRIMARY KEY,
    task_type varchar(32) NOT NULL CHECK (task_type IN ('prompt', 'http', 'mcp_invoke', 'skill_run', 'digital_employee', 'custom')),
    payload jsonb NOT NULL DEFAULT '{}'::jsonb,
    pool_type varchar(16) NOT NULL DEFAULT 'private' CHECK (pool_type IN ('public', 'private')),
    pool_code varchar(64) NOT NULL DEFAULT 'default',
    node_id uuid REFERENCES gateway.agent_nodes(id) ON DELETE SET NULL,
    status varchar(16) NOT NULL DEFAULT 'queued' CHECK (status IN ('queued', 'claimed', 'running', 'succeeded', 'failed', 'cancelled')),
    claim_token varchar(64),
    attempts integer NOT NULL DEFAULT 0 CHECK (attempts >= 0),
    max_attempts integer NOT NULL DEFAULT 3 CHECK (max_attempts BETWEEN 1 AND 10),
    result jsonb,
    error text NOT NULL DEFAULT '' CHECK (length(error) <= 4000),
    created_by uuid REFERENCES gateway.admin_accounts(id) ON DELETE SET NULL,
    available_at timestamptz NOT NULL DEFAULT clock_timestamp(),
    created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
    claimed_at timestamptz,
    finished_at timestamptz
);

CREATE INDEX IF NOT EXISTS agent_tasks_queue_idx
    ON gateway.agent_tasks (status, available_at, created_at)
    WHERE status IN ('queued', 'claimed');
CREATE INDEX IF NOT EXISTS agent_tasks_time_idx
    ON gateway.agent_tasks (created_at DESC);

-- 工具限流窗口支持按用户拆分:portal_user_id 为全零哨兵表示非个人调用(全局窗口),
-- 个人调用按 (tool_id, portal_user_id) 独立计数,便于个人限流倍数。
ALTER TABLE gateway.tool_rate_usage
    DROP CONSTRAINT IF EXISTS tool_rate_usage_pkey;

ALTER TABLE gateway.tool_rate_usage
    ADD COLUMN IF NOT EXISTS portal_user_id uuid NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000',
    ADD PRIMARY KEY (tool_id, portal_user_id, window_start);

-- 个人智能体安全策略:个人调用跳过工具审批标记、按倍数放宽个人限流。
CREATE TABLE IF NOT EXISTS gateway.portal_agent_policies (
    portal_user_id uuid PRIMARY KEY REFERENCES gateway.portal_users(id) ON DELETE CASCADE,
    auto_approve_tools boolean NOT NULL DEFAULT false,
    rate_limit_multiplier integer NOT NULL DEFAULT 1 CHECK (rate_limit_multiplier BETWEEN 1 AND 100),
    updated_at timestamptz NOT NULL DEFAULT clock_timestamp()
);
