import "server-only"; import { desc, eq } from "drizzle-orm"; import type { TokenIdentity } from "@/lib/api-tokens"; import { db } from "@/lib/db/client"; import { agentActivity } from "@/lib/db/schema"; export type ActivityOutcome = "ok" | "pending_approval" | "refused"; /** Record what a token did (or was refused); never fails the request it belongs to. */ export async function logActivity( token: TokenIdentity, action: string, x: { targetType?: string; targetId?: string | null; outcome: ActivityOutcome; code?: string | null; message?: string | null }, ): Promise { try { await db() .insert(agentActivity) .values({ tokenId: token.id, tokenName: token.name, action, targetType: x.targetType ?? null, targetId: x.targetId ?? null, outcome: x.outcome, code: x.code ?? null, message: x.message?.slice(0, 500) ?? null, }); } catch (err) { console.error("[agent-activity]", err); } } export type ActivityRow = typeof agentActivity.$inferSelect; export async function listActivity(tokenId: string, limit = 100): Promise { return db().select().from(agentActivity).where(eq(agentActivity.tokenId, tokenId)).orderBy(desc(agentActivity.createdAt)).limit(limit); } /** An error with a code and an HTTP status below 500: a refusal the agent caused, worth logging. */ function refusal(err: unknown): { code: string; message: string } | null { const e = err as { code?: unknown; status?: unknown; message?: unknown }; if (typeof e?.code === "string" && typeof e.status === "number" && e.status < 500) return { code: e.code, message: String(e.message ?? "") }; if (err instanceof Error && err.name === "ZodError") return { code: "invalid_request", message: err.message.slice(0, 300) }; return null; } /** * Run an agent action and record it: ok, pending approval (when the result's state says so) or * refused with the error code. The error is rethrown for the route to answer. */ export async function act(token: TokenIdentity, action: string, target: { type: string; id?: string | null }, fn: () => Promise): Promise { try { const r = await fn(); const { id, state } = r as { id?: unknown; state?: unknown }; await logActivity(token, action, { targetType: target.type, targetId: target.id ?? (typeof id === "string" ? id : null), outcome: state === "pending_approval" ? "pending_approval" : "ok", }); return r; } catch (err) { const why = refusal(err); if (why) await logActivity(token, action, { targetType: target.type, targetId: target.id ?? null, outcome: "refused", code: why.code, message: why.message }); throw err; } }