import { PERMISSION_KEYS } from "@paperclipai/shared"; import type { HumanCompanyMembershipRole } from "@paperclipai/shared"; import { NEW_STANDARD_AGENT_DEFAULT_GRANT_KEYS, newStandardAgentGrantScope } from "../lib/agent-permissions.js"; import { grantsForHumanRole } from "./company-member-roles.js"; export function grantsFromDefaults( defaultsPayload: Record | null | undefined, key: "human" | "agent" ): Array<{ permissionKey: (typeof PERMISSION_KEYS)[number]; scope: Record | null; }> { if (!defaultsPayload || typeof defaultsPayload !== "object") return []; const scoped = defaultsPayload[key]; if (!scoped || typeof scoped !== "object") return []; const grants = (scoped as Record).grants; if (!Array.isArray(grants)) return []; const validPermissionKeys = new Set(PERMISSION_KEYS); const result: Array<{ permissionKey: (typeof PERMISSION_KEYS)[number]; scope: Record | null; }> = []; for (const item of grants) { if (!item || typeof item !== "object") continue; const record = item as Record; if (typeof record.permissionKey !== "string") continue; if (!validPermissionKeys.has(record.permissionKey)) continue; result.push({ permissionKey: record.permissionKey as (typeof PERMISSION_KEYS)[number], scope: record.scope && typeof record.scope === "object" && !Array.isArray(record.scope) ? (record.scope as Record) : null, }); } return result; } export function agentJoinGrantsFromDefaults( defaultsPayload: Record | null | undefined, agentId: string, ): Array<{ permissionKey: (typeof PERMISSION_KEYS)[number]; scope: Record | null; }> { const grants = grantsFromDefaults(defaultsPayload, "agent"); // Invitation approval replaces the whole grant set after agent creation. // Retain new-agent defaults, but never widen an explicitly scoped grant. for (const permissionKey of NEW_STANDARD_AGENT_DEFAULT_GRANT_KEYS) { if (!grants.some((grant) => grant.permissionKey === permissionKey)) { grants.push({ permissionKey, scope: newStandardAgentGrantScope(permissionKey, agentId) }); } } return grants; } export function humanJoinGrantsFromDefaults( defaultsPayload: Record | null | undefined, membershipRole: HumanCompanyMembershipRole ): Array<{ permissionKey: (typeof PERMISSION_KEYS)[number]; scope: Record | null; }> { const grants = grantsFromDefaults(defaultsPayload, "human"); return grants.length > 0 ? grants : grantsForHumanRole(membershipRole); }