import { createBackendClient, resolveSyncContext, timeoutFetch, type BackendClient } from '@henkaku-center/chi-sync'; import { identityFromOwnerId, type HumanIdentity } from './protocol.js'; export type ParticipantDirectory = { actor: HumanIdentity; participants: HumanIdentity[] }; export async function discoverParticipants(cwd: string, options: { home?: string; clientFactory?: (headers: Record) => Pick; } = {}): Promise { const context = resolveSyncContext(cwd, options.home); if (!context.ok) return null; const headers = { authorization: `Bearer ${context.sessionToken}`, 'x-chi-repo': context.repoSlug }; const client = (options.clientFactory ?? ((requestHeaders) => createBackendClient({ headers: requestHeaders, fetchImpl: timeoutFetch() })))(headers); const response = await client.listParticipants(); const actorRecord = response.participants.find((participant) => participant.ownerId.toLowerCase() === response.self.toLowerCase()); const actor = identityFromOwnerId(actorRecord ? `github:${actorRecord.handle}` : response.self); if (!actor) throw new Error('authenticated Chi identity is not a GitHub handle'); const byId = new Map(); for (const record of response.participants) { const participant = identityFromOwnerId(`github:${record.handle}`); if (participant && participant.id === record.ownerId.toLowerCase() && participant.id !== actor.id && !byId.has(participant.id)) byId.set(participant.id, participant); } return { actor, participants: [...byId.values()].sort((left, right) => left.handle.localeCompare(right.handle)) }; }