import { z } from "zod"; import type { KyInstance } from "ky"; import { getGlobalCache } from "../../core/cache/index.js"; import { listRoleGroups, listRoleMembers, listRoles } from "./api.js"; import type { Role, RoleGroup, RoleMemberReport, RoleQuery } from "./types.js"; const CACHE_TTL_MS = 10 * 60 * 1000; async function getCatalog( client: KyInstance, corpId: string ): Promise<{ roles: Role[]; groups: RoleGroup[] }> { const cache = getGlobalCache(); return cache.withCache( `roles:catalog:${corpId}`, async () => { const [roles, groups] = await Promise.all([ listRoles(client, corpId), listRoleGroups(client, corpId), ]); return { roles, groups }; }, { namespace: "roles", ttlMs: CACHE_TTL_MS } ); } export async function searchRoles( client: KyInstance, corpId: string, query: RoleQuery = {} ): Promise { const { roles } = await getCatalog(client, corpId); const keyword = (query.keyword || query.id || query.code || query.name || "").trim().toLowerCase(); if (!keyword) return roles; return roles.filter((role) => [role.id, role.name, role.code, role.purposeName, role.scope.name].some((value) => value.toLowerCase().includes(keyword) ) ); } export async function getRoleGroups(client: KyInstance, corpId: string): Promise { return (await getCatalog(client, corpId)).groups; } export async function resolveRole( client: KyInstance, corpId: string, target: string ): Promise { const matches = await searchRoles(client, corpId, { keyword: target }); return ( matches.find((role) => role.id === target || role.code === target || role.name === target) || matches[0] ); } export async function getRoleMembers( client: KyInstance, corpId: string, target: string ): Promise { const role = await resolveRole(client, corpId, target); if (!role) return undefined; return { role, members: await listRoleMembers(client, corpId, role.id) }; } export const roleTools = [ { name: "role_list", description: "列出当前企业角色定义与角色组", parameters: z.object({ keyword: z.string().optional(), count: z.number().optional() }), handler: async ({ corpContext }: any, params: { keyword?: string; count?: number }) => { const corp = corpContext.getCurrent(); if (!corp) throw new Error("未配置活跃企业上下文"); const client = await import("../../core/http/session-client.js").then((m) => m.createSessionClient(corp)); const roles = await searchRoles(client, corp.corpId || corp.id, { keyword: params.keyword }); return { count: roles.length, roles: roles.slice(0, params.count ?? 100) }; }, }, ];