@sebastientang/llm-council 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/engine.ts","../src/types.ts","../src/providers/anthropic.ts","../src/providers/openrouter.ts","../src/utils/prompt-builder.ts","../src/protocols/adversarial.ts","../src/utils/anonymizer.ts","../src/protocols/peer-review.ts","../src/utils/synthesis-parser.ts","../src/synthesis/chairman.ts","../src/synthesis/dialectical.ts","../src/personas/presets.ts"],"sourcesContent":["// Core engine\nexport { Council, type CouncilOptions } from './engine.js'\n\n// Types\nexport type {\n CompletionRequest,\n CompletionResponse,\n CouncilEvents,\n DeliberationConfig,\n DeliberationMessage,\n DeliberationMetadata,\n DeliberationResult,\n LLMProvider,\n Participant,\n Protocol,\n PromptRequest,\n Synthesis,\n Synthesizer,\n} from './types.js'\n\n// Zod schemas\nexport {\n DeliberationConfigSchema,\n DeliberationMessageSchema,\n DeliberationMetadataSchema,\n ParticipantSchema,\n SynthesisSchema,\n} from './types.js'\n\n// Providers\nexport { AnthropicProvider, OpenRouterProvider } from './providers/index.js'\n\n// Protocols\nexport { AdversarialProtocol, PeerReviewProtocol } from './protocols/index.js'\n\n// Synthesizers\nexport { ChairmanSynthesizer, DialecticalSynthesizer } from './synthesis/index.js'\n\n// Personas\nexport { PERSONAS, type PersonaId } from './personas/index.js'\n\n// Utils\nexport {\n anonymizeMessages,\n createAnonymizationMap,\n deanonymizeLabel,\n type AnonymizationMap,\n} from './utils/anonymizer.js'\nexport { buildInitialUserMessage } from './utils/prompt-builder.js'\nexport {\n buildSynthesisUserMessage,\n parseSynthesisResponse,\n} from './utils/synthesis-parser.js'\n","import mitt from 'mitt'\nimport type {\n CouncilEvents,\n DeliberationConfig,\n DeliberationMessage,\n DeliberationMetadata,\n DeliberationResult,\n LLMProvider,\n Protocol,\n Synthesizer,\n} from './types.js'\nimport { DeliberationConfigSchema } from './types.js'\n\nexport interface CouncilOptions {\n providers: Map<string, LLMProvider>\n protocol: Protocol\n synthesizer: Synthesizer\n synthesisProvider?: { providerId: string; model: string }\n}\n\nexport class Council {\n private providers: Map<string, LLMProvider>\n private protocol: Protocol\n private synthesizer: Synthesizer\n private synthesisProvider: { providerId: string; model: string } | undefined\n private emitter = mitt<CouncilEvents>()\n\n constructor(options: CouncilOptions) {\n this.providers = options.providers\n this.protocol = options.protocol\n this.synthesizer = options.synthesizer\n this.synthesisProvider = options.synthesisProvider\n }\n\n on<K extends keyof CouncilEvents>(\n event: K,\n handler: (payload: CouncilEvents[K]) => void,\n ): void {\n this.emitter.on(event, handler)\n }\n\n off<K extends keyof CouncilEvents>(\n event: K,\n handler: (payload: CouncilEvents[K]) => void,\n ): void {\n this.emitter.off(event, handler)\n }\n\n async deliberate(rawConfig: DeliberationConfig): Promise<DeliberationResult> {\n try {\n const config = DeliberationConfigSchema.parse(rawConfig)\n const startTime = Date.now()\n const allMessages: DeliberationMessage[] = []\n const tokenTracker: Record<\n string,\n { input: number; output: number }\n > = {}\n\n const roundCount = this.protocol.getRoundCount()\n const rounds = Math.min(config.rounds, roundCount)\n\n for (let round = 1; round <= rounds; round++) {\n const prompts = this.protocol.buildPrompts(config, allMessages, round)\n\n this.emitter.emit('round:start', {\n round,\n participantCount: prompts.length,\n })\n\n const roundMessages = await Promise.all(\n prompts.map(async (prompt) => {\n const provider = this.providers.get(prompt.provider)\n if (!provider) {\n throw new Error(\n `Provider '${prompt.provider}' not found. Available: ${[...this.providers.keys()].join(', ')}`,\n )\n }\n\n const response = await provider.complete({\n model: prompt.model,\n systemPrompt: prompt.systemPrompt,\n messages: [{ role: 'user', content: prompt.userMessage }],\n temperature: prompt.temperature,\n maxTokens: prompt.maxTokens,\n })\n\n const participant = config.participants.find(\n (p) => p.id === prompt.participantId,\n )\n\n const message: DeliberationMessage = {\n participantId: prompt.participantId,\n participantName: participant?.name ?? prompt.participantId,\n round,\n content: response.content,\n timestamp: new Date(),\n tokenCount: response.tokenCount,\n }\n\n // Track tokens per model\n const modelKey = `${prompt.provider}/${prompt.model}`\n const existing = tokenTracker[modelKey] ?? { input: 0, output: 0 }\n tokenTracker[modelKey] = {\n input: existing.input + response.tokenCount.input,\n output: existing.output + response.tokenCount.output,\n }\n\n this.emitter.emit('response', message)\n return message\n }),\n )\n\n allMessages.push(...roundMessages)\n }\n\n // Synthesis\n this.emitter.emit('synthesis:start', undefined)\n\n const synthesisProviderConfig = this.synthesisProvider ?? {\n providerId: config.participants[0].provider,\n model: config.participants[0].model,\n }\n\n const provider = this.providers.get(synthesisProviderConfig.providerId)\n if (!provider) {\n throw new Error(\n `Synthesis provider '${synthesisProviderConfig.providerId}' not found`,\n )\n }\n\n const synthesis = await this.synthesizer.synthesize(\n config,\n allMessages,\n provider,\n )\n\n const durationMs = Date.now() - startTime\n const totalTokens = Object.values(tokenTracker).reduce(\n (acc, t) => ({\n input: acc.input + t.input,\n output: acc.output + t.output,\n }),\n { input: 0, output: 0 },\n )\n\n const metadata: DeliberationMetadata = {\n totalTokens,\n durationMs,\n modelBreakdown: tokenTracker,\n }\n\n const result: DeliberationResult = {\n config,\n messages: allMessages,\n synthesis,\n metadata,\n }\n\n this.emitter.emit('complete', result)\n return result\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error))\n this.emitter.emit('error', err)\n throw err\n }\n }\n}\n","import { z } from 'zod'\n\n// --- Provider types ---\n\nexport interface CompletionRequest {\n model: string\n systemPrompt: string\n messages: Array<{ role: 'user' | 'assistant'; content: string }>\n temperature?: number\n maxTokens?: number\n}\n\nexport interface CompletionResponse {\n content: string\n tokenCount: { input: number; output: number }\n model: string\n}\n\nexport interface LLMProvider {\n id: string\n complete(request: CompletionRequest): Promise<CompletionResponse>\n}\n\n// --- Participant types ---\n\nexport const ParticipantSchema = z.object({\n id: z.string(),\n name: z.string(),\n provider: z.string(),\n model: z.string(),\n systemPrompt: z.string(),\n temperature: z.number().min(0).max(2).optional(),\n})\n\nexport type Participant = z.infer<typeof ParticipantSchema>\n\n// --- Protocol types ---\n\nexport interface PromptRequest {\n participantId: string\n provider: string\n model: string\n systemPrompt: string\n userMessage: string\n temperature?: number\n maxTokens?: number\n}\n\nexport interface Protocol {\n buildPrompts(\n config: DeliberationConfig,\n history: DeliberationMessage[],\n round: number,\n ): PromptRequest[]\n getRoundCount(): number\n}\n\n// --- Synthesizer types ---\n\nexport const SynthesisSchema = z.object({\n recommendation: z.string(),\n confidence: z.number().min(0).max(100),\n reasoning: z.string(),\n risks: z.array(z.string()),\n dissent: z.array(z.string()),\n validationGates: z.array(z.string()),\n assumptions: z.array(z.string()),\n raw: z.string(),\n})\n\nexport type Synthesis = z.infer<typeof SynthesisSchema>\n\nexport interface Synthesizer {\n synthesize(\n config: DeliberationConfig,\n messages: DeliberationMessage[],\n provider: LLMProvider,\n ): Promise<Synthesis>\n}\n\n// --- Message types ---\n\nexport const DeliberationMessageSchema = z.object({\n participantId: z.string(),\n participantName: z.string(),\n round: z.number(),\n content: z.string(),\n timestamp: z.date(),\n tokenCount: z.object({ input: z.number(), output: z.number() }),\n})\n\nexport type DeliberationMessage = z.infer<typeof DeliberationMessageSchema>\n\n// --- Config types ---\n\nexport const DeliberationConfigSchema = z.object({\n topic: z.string().min(1),\n options: z.array(z.string()).optional(),\n context: z.string().optional(),\n preferredOption: z.string().optional(),\n participants: z.array(ParticipantSchema).min(2),\n rounds: z.number().min(1).max(5).default(2),\n tokenBudget: z\n .object({\n perResponse: z.number().positive().optional(),\n total: z.number().positive().optional(),\n })\n .optional(),\n})\n\nexport type DeliberationConfig = z.infer<typeof DeliberationConfigSchema>\n\n// --- Result types ---\n\nexport const DeliberationMetadataSchema = z.object({\n totalTokens: z.object({ input: z.number(), output: z.number() }),\n durationMs: z.number(),\n modelBreakdown: z.record(\n z.string(),\n z.object({ input: z.number(), output: z.number() }),\n ),\n})\n\nexport type DeliberationMetadata = z.infer<typeof DeliberationMetadataSchema>\n\nexport interface DeliberationResult {\n config: DeliberationConfig\n messages: DeliberationMessage[]\n synthesis: Synthesis\n metadata: DeliberationMetadata\n}\n\n// --- Event types ---\n\nexport type CouncilEvents = {\n 'round:start': { round: number; participantCount: number }\n response: DeliberationMessage\n 'synthesis:start': undefined\n complete: DeliberationResult\n error: Error\n}\n","import Anthropic from '@anthropic-ai/sdk'\nimport type {\n CompletionRequest,\n CompletionResponse,\n LLMProvider,\n} from '../types.js'\n\ninterface AnthropicProviderConfig {\n apiKey: string\n defaultModel?: string\n defaultMaxTokens?: number\n}\n\nexport class AnthropicProvider implements LLMProvider {\n readonly id = 'anthropic' as const\n private client: Anthropic\n private defaultModel: string\n private defaultMaxTokens: number\n\n constructor(config: AnthropicProviderConfig) {\n this.client = new Anthropic({ apiKey: config.apiKey })\n this.defaultModel = config.defaultModel ?? 'claude-sonnet-4-20250514'\n this.defaultMaxTokens = config.defaultMaxTokens ?? 1024\n }\n\n async complete(request: CompletionRequest): Promise<CompletionResponse> {\n const params: Anthropic.MessageCreateParamsNonStreaming = {\n model: request.model || this.defaultModel,\n max_tokens: request.maxTokens ?? this.defaultMaxTokens,\n system: request.systemPrompt,\n messages: request.messages.map((msg) => ({\n role: msg.role,\n content: msg.content,\n })),\n ...(request.temperature !== undefined && {\n temperature: request.temperature,\n }),\n }\n\n let response: Anthropic.Message\n try {\n response = await this.client.messages.create(params)\n } catch (error: unknown) {\n if (isOverloadedError(error)) {\n await delay(1000)\n response = await this.client.messages.create(params)\n } else {\n throw error\n }\n }\n\n const textBlock = response.content.find(\n (block): block is Anthropic.TextBlock => block.type === 'text',\n )\n\n if (!textBlock) {\n throw new Error(\n `Anthropic response contained no text block. Stop reason: ${response.stop_reason}`,\n )\n }\n\n return {\n content: textBlock.text,\n tokenCount: {\n input: response.usage.input_tokens,\n output: response.usage.output_tokens,\n },\n model: response.model,\n }\n }\n}\n\nfunction isOverloadedError(error: unknown): boolean {\n if (error instanceof Anthropic.APIError) {\n return error.status === 529\n }\n return false\n}\n\nfunction delay(ms: number): Promise<void> {\n return new Promise((resolve) => {\n setTimeout(resolve, ms)\n })\n}\n","import type {\n CompletionRequest,\n CompletionResponse,\n LLMProvider,\n} from '../types.js'\n\ninterface OpenRouterProviderConfig {\n apiKey: string\n appName?: string\n defaultModel?: string\n defaultMaxTokens?: number\n siteUrl?: string\n}\n\ninterface OpenRouterChoice {\n message: { content: string }\n}\n\ninterface OpenRouterUsage {\n prompt_tokens: number\n completion_tokens: number\n}\n\ninterface OpenRouterResponse {\n choices: OpenRouterChoice[]\n usage: OpenRouterUsage\n model: string\n}\n\ninterface OpenRouterError {\n error: { message: string; code?: number }\n}\n\nexport class OpenRouterProvider implements LLMProvider {\n readonly id = 'openrouter' as const\n private readonly apiKey: string\n private readonly appName: string\n private readonly defaultModel: string\n private readonly defaultMaxTokens: number\n private readonly siteUrl: string\n\n constructor(config: OpenRouterProviderConfig) {\n this.apiKey = config.apiKey\n this.appName = config.appName ?? 'llm-council'\n this.defaultModel = config.defaultModel ?? 'openai/gpt-4o'\n this.defaultMaxTokens = config.defaultMaxTokens ?? 1024\n this.siteUrl = config.siteUrl ?? ''\n }\n\n async complete(request: CompletionRequest): Promise<CompletionResponse> {\n const body = {\n model: request.model || this.defaultModel,\n messages: [\n { role: 'system' as const, content: request.systemPrompt },\n ...request.messages.map((msg) => ({\n role: msg.role as 'user' | 'assistant',\n content: msg.content,\n })),\n ],\n max_tokens: request.maxTokens ?? this.defaultMaxTokens,\n ...(request.temperature !== undefined && {\n temperature: request.temperature,\n }),\n }\n\n const headers: Record<string, string> = {\n 'Authorization': `Bearer ${this.apiKey}`,\n 'Content-Type': 'application/json',\n 'X-Title': this.appName,\n }\n\n if (this.siteUrl) {\n headers['HTTP-Referer'] = this.siteUrl\n }\n\n let response = await fetch('https://openrouter.ai/api/v1/chat/completions', {\n method: 'POST',\n headers,\n body: JSON.stringify(body),\n })\n\n if (response.status === 429) {\n const retryAfter = response.headers.get('Retry-After')\n const delayMs = retryAfter ? parseInt(retryAfter, 10) * 1000 : 2000\n await delay(Math.min(delayMs, 10000))\n response = await fetch('https://openrouter.ai/api/v1/chat/completions', {\n method: 'POST',\n headers,\n body: JSON.stringify(body),\n })\n }\n\n if (!response.ok) {\n const errorBody = await response.json().catch(() => null) as OpenRouterError | null\n const message = errorBody?.error?.message ?? `HTTP ${response.status}`\n throw new Error(`OpenRouter API error (${response.status}): ${message}`)\n }\n\n const data = await response.json() as OpenRouterResponse\n\n const content = data.choices?.[0]?.message?.content\n if (!content) {\n throw new Error('OpenRouter response contained no content')\n }\n\n return {\n content,\n tokenCount: {\n input: data.usage?.prompt_tokens ?? 0,\n output: data.usage?.completion_tokens ?? 0,\n },\n model: data.model,\n }\n }\n}\n\nfunction delay(ms: number): Promise<void> {\n return new Promise((resolve) => {\n setTimeout(resolve, ms)\n })\n}\n","import type { DeliberationConfig } from '../types.js'\n\nexport function buildInitialUserMessage(config: DeliberationConfig): string {\n const parts: string[] = []\n\n parts.push(`## Decision Topic\\n${config.topic}`)\n\n if (config.options && config.options.length > 0) {\n const optionsList = config.options\n .map((opt, i) => `${i + 1}. ${opt}`)\n .join('\\n')\n parts.push(`## Options\\n${optionsList}`)\n }\n\n if (config.preferredOption) {\n parts.push(`## Preferred Option\\n${config.preferredOption}`)\n }\n\n if (config.context) {\n parts.push(`## Additional Context\\n${config.context}`)\n }\n\n parts.push(\n 'Provide your initial brief (200-400 words). State your position clearly and support it with reasoning.',\n )\n\n return parts.join('\\n\\n')\n}\n","import type {\n DeliberationConfig,\n DeliberationMessage,\n Protocol,\n PromptRequest,\n} from '../types.js'\nimport { buildInitialUserMessage } from '../utils/prompt-builder.js'\n\nconst DEFAULT_REBUTTAL_GUIDANCE: Record<string, string> = {\n proposer:\n \"Focus your rebuttal on the Challenger's strongest attack.\",\n challenger:\n \"Focus on whether the Proposer's acknowledged weakness is actually fatal.\",\n steelmanner:\n \"Focus on whether the Pre-Mortem's failure story applies equally to the rejected option.\",\n 'pre-mortem':\n \"Focus on which of the Proposer's assumptions appear in your failure cascade.\",\n}\n\ninterface AdversarialProtocolOptions {\n rebuttalGuidance?: Record<string, string>\n}\n\nfunction getRebuttalGuidance(\n participantId: string,\n guidanceMap: Record<string, string>,\n): string {\n for (const [key, guidance] of Object.entries(guidanceMap)) {\n if (participantId.toLowerCase().includes(key.toLowerCase())) {\n return guidance\n }\n }\n return 'Address the most critical point from another member.'\n}\n\nfunction buildRebuttalUserMessage(\n participantId: string,\n otherMessages: DeliberationMessage[],\n guidanceMap: Record<string, string>,\n): string {\n const parts: string[] = []\n\n parts.push(\"Here are the other Council members' briefs:\")\n\n for (const msg of otherMessages) {\n parts.push(`### ${msg.participantName}\\n${msg.content}`)\n }\n\n const guidance = getRebuttalGuidance(participantId, guidanceMap)\n\n parts.push(\n `Write your rebuttal (100-200 words). ${guidance}`,\n )\n\n return parts.join('\\n\\n')\n}\n\nexport class AdversarialProtocol implements Protocol {\n private readonly rebuttalGuidance: Record<string, string>\n\n constructor(options?: AdversarialProtocolOptions) {\n this.rebuttalGuidance = options?.rebuttalGuidance ?? DEFAULT_REBUTTAL_GUIDANCE\n }\n\n getRoundCount(): number {\n return 2\n }\n\n buildPrompts(\n config: DeliberationConfig,\n history: DeliberationMessage[],\n round: number,\n ): PromptRequest[] {\n if (round === 1) {\n return this.buildInitialBriefs(config)\n }\n\n if (round === 2) {\n return this.buildRebuttals(config, history)\n }\n\n return []\n }\n\n private buildInitialBriefs(config: DeliberationConfig): PromptRequest[] {\n const userMessage = buildInitialUserMessage(config)\n\n return config.participants.map((participant) => ({\n participantId: participant.id,\n provider: participant.provider,\n model: participant.model,\n systemPrompt: participant.systemPrompt,\n userMessage,\n temperature: participant.temperature ?? 0.7,\n maxTokens: config.tokenBudget?.perResponse,\n }))\n }\n\n private buildRebuttals(\n config: DeliberationConfig,\n history: DeliberationMessage[],\n ): PromptRequest[] {\n const round1Messages = history.filter((msg) => msg.round === 1)\n\n return config.participants.map((participant) => {\n const otherMessages = round1Messages.filter(\n (msg) => msg.participantId !== participant.id,\n )\n\n return {\n participantId: participant.id,\n provider: participant.provider,\n model: participant.model,\n systemPrompt: participant.systemPrompt,\n userMessage: buildRebuttalUserMessage(\n participant.id,\n otherMessages,\n this.rebuttalGuidance,\n ),\n temperature: participant.temperature ?? 0.7,\n maxTokens: config.tokenBudget?.perResponse,\n }\n })\n }\n}\n","import type { DeliberationMessage } from '../types.js'\n\nconst LABELS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('')\n\nexport interface AnonymizationMap {\n labelToParticipant: Map<string, string>\n participantToLabel: Map<string, string>\n}\n\nexport function createAnonymizationMap(\n participantIds: string[],\n): AnonymizationMap {\n const labelToParticipant = new Map<string, string>()\n const participantToLabel = new Map<string, string>()\n\n for (let i = 0; i < participantIds.length; i++) {\n const label = `Response ${LABELS[i] ?? String(i + 1)}`\n labelToParticipant.set(label, participantIds[i])\n participantToLabel.set(participantIds[i], label)\n }\n\n return { labelToParticipant, participantToLabel }\n}\n\nexport function anonymizeMessages(\n messages: DeliberationMessage[],\n map: AnonymizationMap,\n): Array<{ label: string; content: string }> {\n return messages.map((msg) => ({\n label: map.participantToLabel.get(msg.participantId) ?? 'Unknown',\n content: msg.content,\n }))\n}\n\nexport function deanonymizeLabel(\n label: string,\n map: AnonymizationMap,\n): string | undefined {\n return map.labelToParticipant.get(label)\n}\n","import type {\n DeliberationConfig,\n DeliberationMessage,\n Protocol,\n PromptRequest,\n} from '../types.js'\nimport {\n anonymizeMessages,\n createAnonymizationMap,\n type AnonymizationMap,\n} from '../utils/anonymizer.js'\nimport { buildInitialUserMessage } from '../utils/prompt-builder.js'\n\ninterface PeerReviewProtocolOptions {\n enableRevote?: boolean\n}\n\nexport class PeerReviewProtocol implements Protocol {\n private readonly enableRevote: boolean\n\n constructor(options?: PeerReviewProtocolOptions) {\n this.enableRevote = options?.enableRevote ?? false\n }\n\n getRoundCount(): number {\n return this.enableRevote ? 3 : 2\n }\n\n buildPrompts(\n config: DeliberationConfig,\n history: DeliberationMessage[],\n round: number,\n ): PromptRequest[] {\n if (round === 1) {\n return this.buildInitialBriefs(config)\n }\n\n // Create anonymization map fresh from participant list for rounds 2+\n const anonMap = createAnonymizationMap(config.participants.map((p) => p.id))\n\n if (round === 2) {\n return this.buildRankingRound(config, history, anonMap)\n }\n\n if (round === 3 && this.enableRevote) {\n return this.buildRevoteRound(config, history, anonMap)\n }\n\n return []\n }\n\n private buildInitialBriefs(config: DeliberationConfig): PromptRequest[] {\n const userMessage = buildInitialUserMessage(config)\n\n return config.participants.map((participant) => ({\n participantId: participant.id,\n provider: participant.provider,\n model: participant.model,\n systemPrompt: participant.systemPrompt,\n userMessage,\n temperature: participant.temperature ?? 0.7,\n maxTokens: config.tokenBudget?.perResponse,\n }))\n }\n\n private buildRankingRound(\n config: DeliberationConfig,\n history: DeliberationMessage[],\n anonMap: AnonymizationMap,\n ): PromptRequest[] {\n const round1Messages = history.filter((msg) => msg.round === 1)\n const anonymized = anonymizeMessages(round1Messages, anonMap)\n const briefsText = anonymized\n .map((entry) => `### ${entry.label}\\n${entry.content}`)\n .join('\\n\\n')\n\n const labelList = anonymized.map((e) => e.label).join(', ')\n\n return config.participants.map((participant) => ({\n participantId: participant.id,\n provider: participant.provider,\n model: participant.model,\n systemPrompt: participant.systemPrompt,\n userMessage: buildRankingUserMessage(briefsText, labelList),\n temperature: participant.temperature ?? 0.7,\n maxTokens: config.tokenBudget?.perResponse,\n }))\n }\n\n private buildRevoteRound(\n config: DeliberationConfig,\n history: DeliberationMessage[],\n anonMap: AnonymizationMap,\n ): PromptRequest[] {\n const round2Messages = history.filter((msg) => msg.round === 2)\n const anonymizedRankings = anonymizeMessages(round2Messages, anonMap)\n const rankingsText = anonymizedRankings\n .map((entry) => `### ${entry.label}'s Rankings\\n${entry.content}`)\n .join('\\n\\n')\n\n const round1Messages = history.filter((msg) => msg.round === 1)\n const anonymizedBriefs = anonymizeMessages(round1Messages, anonMap)\n const labelList = anonymizedBriefs.map((e) => e.label).join(', ')\n\n return config.participants.map((participant) => ({\n participantId: participant.id,\n provider: participant.provider,\n model: participant.model,\n systemPrompt: participant.systemPrompt,\n userMessage: buildRevoteUserMessage(rankingsText, labelList),\n temperature: participant.temperature ?? 0.7,\n maxTokens: config.tokenBudget?.perResponse,\n }))\n }\n}\n\nfunction buildRankingUserMessage(briefsText: string, labelList: string): string {\n const parts: string[] = []\n\n parts.push('You are participating in an anonymized peer review. Below are briefs from all council members (including yours, but you do not know which one is yours).')\n parts.push(briefsText)\n parts.push(`Rank ALL responses from best to worst (${labelList}). For each, provide a one-sentence justification.\n\nRespond in EXACTLY this format:\n\nRANKING:\n1. [Label] - [one-sentence justification]\n2. [Label] - [one-sentence justification]\n3. [Label] - [one-sentence justification]\n4. [Label] - [one-sentence justification]`)\n\n return parts.join('\\n\\n')\n}\n\nfunction buildRevoteUserMessage(rankingsText: string, labelList: string): string {\n const parts: string[] = []\n\n parts.push('You have seen the other council members\\' anonymous rankings. Review them and submit your final ranking.')\n parts.push(rankingsText)\n parts.push(`Submit your FINAL ranking of all responses (${labelList}). Consider the other members\\' perspectives.\n\nRespond in EXACTLY this format:\n\nRANKING:\n1. [Label] - [one-sentence justification]\n2. [Label] - [one-sentence justification]\n3. [Label] - [one-sentence justification]\n4. [Label] - [one-sentence justification]`)\n\n return parts.join('\\n\\n')\n}\n","import type {\n DeliberationConfig,\n DeliberationMessage,\n Synthesis,\n} from '../types.js'\n\nexport function groupMessagesByRound(\n messages: DeliberationMessage[],\n): Map<number, DeliberationMessage[]> {\n const grouped = new Map<number, DeliberationMessage[]>()\n for (const msg of messages) {\n const existing = grouped.get(msg.round) ?? []\n existing.push(msg)\n grouped.set(msg.round, existing)\n }\n return grouped\n}\n\nexport function buildSynthesisUserMessage(\n config: DeliberationConfig,\n messages: DeliberationMessage[],\n): string {\n const parts: string[] = []\n\n parts.push(`# Decision Topic\\n${config.topic}`)\n\n if (config.options && config.options.length > 0) {\n parts.push(`# Options\\n${config.options.map((o, i) => `${i + 1}. ${o}`).join('\\n')}`)\n }\n\n if (config.preferredOption) {\n parts.push(`# Preferred Option\\n${config.preferredOption}`)\n }\n\n if (config.context) {\n parts.push(`# Context\\n${config.context}`)\n }\n\n const roundLabels: Record<number, string> = {\n 1: 'Initial Briefs',\n 2: 'Rebuttals',\n 3: 'Final Statements',\n 4: 'Closing Arguments',\n 5: 'Summary',\n }\n\n const grouped = groupMessagesByRound(messages)\n const sortedRounds = [...grouped.keys()].sort((a, b) => a - b)\n\n for (const round of sortedRounds) {\n const label = roundLabels[round] ?? `Round ${round}`\n const roundMessages = grouped.get(round)\n if (!roundMessages) continue\n\n parts.push(`## Round ${round}: ${label}`)\n for (const msg of roundMessages) {\n parts.push(`### ${msg.participantName}\\n${msg.content}`)\n }\n }\n\n return parts.join('\\n\\n')\n}\n\nexport function escapeRegex(str: string): string {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n\nexport function parseListSection(raw: string, header: string): string[] {\n const escaped = escapeRegex(header)\n const pattern = new RegExp(\n `${escaped}:\\\\s*\\\\n((?:- .+(?:\\\\n|$))*)`,\n 'i',\n )\n const match = pattern.exec(raw)\n if (!match?.[1]) return []\n\n return match[1]\n .split('\\n')\n .map((line) => line.replace(/^- /, '').trim())\n .filter((line) => line.length > 0)\n}\n\nexport function parseSynthesisResponse(raw: string): Synthesis {\n const recommendationMatch = /RECOMMENDATION:\\s*(.+)/i.exec(raw)\n const confidenceMatch = /CONFIDENCE:\\s*(\\d+)/i.exec(raw)\n const reasoningMatch = /REASONING:\\s*(.+(?:\\n(?!RISKS:|DISSENT:|VALIDATION_GATES:|ASSUMPTIONS:).+)*)/i.exec(raw)\n\n const recommendation = recommendationMatch?.[1]?.trim() ?? raw.slice(0, 200)\n const confidence = confidenceMatch ? parseInt(confidenceMatch[1], 10) : 50\n const reasoning = reasoningMatch?.[1]?.trim() ?? raw\n\n const risks = parseListSection(raw, 'RISKS')\n const dissent = parseListSection(raw, 'DISSENT')\n const validationGates = parseListSection(raw, 'VALIDATION_GATES')\n const assumptions = parseListSection(raw, 'ASSUMPTIONS')\n\n return {\n recommendation,\n confidence: Math.min(100, Math.max(0, confidence)),\n reasoning,\n risks,\n dissent,\n validationGates,\n assumptions,\n raw,\n }\n}\n","import type {\n DeliberationConfig,\n DeliberationMessage,\n LLMProvider,\n Synthesis,\n Synthesizer,\n} from '../types.js'\nimport {\n buildSynthesisUserMessage,\n parseSynthesisResponse,\n} from '../utils/synthesis-parser.js'\n\ninterface ChairmanSynthesizerOptions {\n model?: string\n temperature?: number\n}\n\nconst SYSTEM_PROMPT = `You are the Chairman of a council deliberation. Your job is to evaluate the arguments presented and SELECT THE BEST ONE. Do not synthesize or merge arguments. Pick the winner.\n\nEvaluation criteria:\n1. Evidence quality - arguments backed by specific data, precedent, or measurable outcomes score highest\n2. Risk awareness - the best argument acknowledges its own weaknesses honestly\n3. Actionability - prefer arguments with clear, concrete next steps over abstract reasoning\n4. Logical coherence - the argument's conclusion must follow from its premises\n\nYour confidence score reflects how clear the winner is:\n- 90%+ = one argument is clearly superior, others have significant flaws\n- 70-89% = a clear winner exists but the runner-up has merit\n- 50-69% = close race between two or more arguments\n- <50% = no clear winner, recommend gathering more data\n\nRespond in EXACTLY this format (no deviations):\n\nRECOMMENDATION: [state which participant's argument wins and why in one sentence]\nCONFIDENCE: [number 0-100]\nREASONING: [2-3 sentences explaining why this argument won over the others]\nRISKS:\n- [risk 1 from the winning argument]\n- [risk 2]\n- [risk 3]\nDISSENT:\n- [the runner-up's strongest point that nearly won]\nVALIDATION_GATES:\n- [gate 1 - measurable, time-bound]\n- [gate 2]\nASSUMPTIONS:\n- [assumption 1 the winning argument depends on]\n- [assumption 2]`\n\nexport class ChairmanSynthesizer implements Synthesizer {\n private readonly model: string\n private readonly temperature: number\n\n constructor(options: ChairmanSynthesizerOptions = {}) {\n this.model = options.model ?? 'claude-sonnet-4-20250514'\n this.temperature = options.temperature ?? 0.3\n }\n\n async synthesize(\n config: DeliberationConfig,\n messages: DeliberationMessage[],\n provider: LLMProvider,\n ): Promise<Synthesis> {\n const userMessage = buildSynthesisUserMessage(config, messages)\n\n const response = await provider.complete({\n model: this.model,\n systemPrompt: SYSTEM_PROMPT,\n messages: [{ role: 'user', content: userMessage }],\n temperature: this.temperature,\n })\n\n return parseSynthesisResponse(response.content)\n }\n}\n","import type {\n DeliberationConfig,\n DeliberationMessage,\n LLMProvider,\n Synthesis,\n Synthesizer,\n} from '../types.js'\nimport {\n buildSynthesisUserMessage,\n parseSynthesisResponse,\n} from '../utils/synthesis-parser.js'\n\ninterface DialecticalSynthesizerOptions {\n model?: string\n temperature?: number\n}\n\nconst SYSTEM_PROMPT = `You are the Synthesis Moderator for a council deliberation. You have received briefs and rebuttals from multiple council members debating a decision. Your job is to:\n1. Weigh evidence over opinion - arguments backed by specific data or precedent outweigh assertions\n2. Favor reversibility when confidence is low - if the council is split, recommend the more reversible option\n3. Synthesize, don't average - your recommendation should reflect the strongest arguments, not a compromise\n4. Calibrate confidence honestly: 90%+ = unanimous agreement with strong evidence; 70-89% = majority with minor dissent; 50-69% = significant split or unknowns; <50% = fundamental disagreement, recommend gathering more data\n\nRespond in EXACTLY this format (no deviations):\n\nRECOMMENDATION: [one sentence]\nCONFIDENCE: [number 0-100]\nREASONING: [2-3 sentences explaining the recommendation]\nRISKS:\n- [risk 1]\n- [risk 2]\n- [risk 3]\nDISSENT:\n- [strongest counter-argument that survived debate]\nVALIDATION_GATES:\n- [gate 1 - measurable, time-bound]\n- [gate 2]\nASSUMPTIONS:\n- [assumption 1 that must hold]\n- [assumption 2]`\n\nexport class DialecticalSynthesizer implements Synthesizer {\n private readonly model: string\n private readonly temperature: number\n\n constructor(options: DialecticalSynthesizerOptions = {}) {\n this.model = options.model ?? 'claude-sonnet-4-20250514'\n this.temperature = options.temperature ?? 0.3\n }\n\n async synthesize(\n config: DeliberationConfig,\n messages: DeliberationMessage[],\n provider: LLMProvider,\n ): Promise<Synthesis> {\n const userMessage = buildSynthesisUserMessage(config, messages)\n\n const response = await provider.complete({\n model: this.model,\n systemPrompt: SYSTEM_PROMPT,\n messages: [{ role: 'user', content: userMessage }],\n temperature: this.temperature,\n })\n\n return parseSynthesisResponse(response.content)\n }\n}\n","import type { Participant } from '../types.js'\n\ntype PersonaPreset = Omit<Participant, 'provider' | 'model'>\n\nconst proposer: PersonaPreset = {\n id: 'proposer',\n name: 'Proposer',\n systemPrompt: `# Proposer — Thesis Builder\n\n## Role\nYou are the Proposer. Your job is to build the strongest possible case FOR the preferred option. You are an advocate, not a neutral analyst.\n\n## Cognitive Stance\nDialectical Inquiry: construct the thesis that will be tested by the other Council members. Your case must be rigorous enough to survive attack.\n\n## What You Must Do\n1. State the recommendation clearly — one sentence, no hedging\n2. List 3-5 supporting arguments — each backed by evidence, logic, or precedent from the decision context\n3. List explicit assumptions — what must be true for this option to succeed. Be honest. Hidden assumptions are the Challenger's ammunition.\n4. Identify the best-case outcome — what does success look like in 3, 6, 12 months?\n5. Acknowledge the weakest point — every thesis has one. Name it.\n\n## Output Format\n## Proposer Brief\n\n**Recommendation:** [one sentence]\n\n**Supporting arguments:**\n1. [argument + evidence]\n2. [argument + evidence]\n3. [argument + evidence]\n\n**Assumptions (what must be true):**\n- [assumption 1]\n- [assumption 2]\n- [assumption 3]\n\n**Best-case outcome:** [description]\n\n**Weakest point:** [honest acknowledgment]\n\n## Rules\n- 200-400 words max\n- No padding, no filler — state assertions directly\n- Every argument must reference specific context (constraints, numbers, precedents)\n- Do NOT address the other agents — write your brief independently`,\n temperature: 0.7,\n}\n\nconst challenger: PersonaPreset = {\n id: 'challenger',\n name: 'Challenger',\n systemPrompt: `# Challenger — Red Team Attacker\n\n## Role\nYou are the Challenger. Your job is to attack the preferred option. Find every vulnerability, hidden cost, second-order effect, and competitive risk. You are the red team.\n\n## Cognitive Stance\nRed Team + Devil's Advocate: assume the preferred option has fatal flaws. Your job is to find them before reality does.\n\n## What You Must Do\n1. Attack the assumptions — take each assumption from the proposal and stress-test it. What if it's wrong?\n2. Find hidden costs — time, money, opportunity cost, relationship cost, reputation risk not in the initial analysis\n3. Identify second-order effects — what happens AFTER the decision? What does it trigger, close off, or commit to?\n4. Surface competitive risks — what can go wrong externally? Market changes, competitor moves, timing risks\n5. Ask the question they're avoiding — every decision has one uncomfortable question nobody wants to ask. Ask it.\n\n## Output Format\n## Challenger Brief\n\n**Verdict:** [one sentence — is this option as strong as it looks?]\n\n**Assumption attacks:**\n- [assumption] -> [why it might be wrong]\n- [assumption] -> [why it might be wrong]\n\n**Hidden costs:**\n- [cost 1]\n- [cost 2]\n\n**Second-order effects:**\n- [effect — what this triggers or closes off]\n\n**The question they're avoiding:**\n[one uncomfortable question]\n\n**Kill condition:** [the single scenario where this option catastrophically fails]\n\n## Rules\n- 200-400 words max\n- Be aggressive but honest — attack the option, not the person\n- Every attack must be specific, not vague\n- Do NOT propose alternatives — that's the Steelmanner's job\n- Do NOT soften your attacks — the whole point is adversarial pressure`,\n temperature: 0.7,\n}\n\nconst steelmanner: PersonaPreset = {\n id: 'steelmanner',\n name: 'Steelmanner',\n systemPrompt: `# Steelmanner — Counter-Proposal Advocate\n\n## Role\nYou are the Steelmanner. Your job is to take the option the decision-maker is leaning AWAY from and build the absolute best case for it. Not criticism of the preferred option — genuine, full-throated advocacy for the alternative.\n\n## Cognitive Stance\nRationalist steelmanning: assume the rejected option has merits being overlooked due to anchoring bias, status quo preference, or emotional attachment to the preferred path.\n\n## What You Must Do\n1. Reframe the rejected option — present it in its most favorable light. What would a brilliant advocate say?\n2. Find unique advantages — what does this option offer that the preferred option cannot? Focus on exclusive benefits.\n3. Address the objections — why is the decision-maker leaning away? Take each objection and counter it with evidence or reframing.\n4. Paint the success scenario — if this option were chosen and executed well, what does the best outcome look like?\n5. Identify the regret scenario — in what future does the decision-maker wish they had chosen this path instead?\n\n## Output Format\n## Steelmanner Brief\n\n**The case for [rejected option]:**\n[2-3 sentence reframe — why this deserves serious consideration]\n\n**Unique advantages:**\n- [advantage 1 — something the preferred option cannot offer]\n- [advantage 2]\n- [advantage 3]\n\n**Objection rebuttals:**\n- \"[objection]\" -> [counter-argument]\n- \"[objection]\" -> [counter-argument]\n\n**Success scenario:** [what the best outcome looks like]\n\n**Regret scenario:** [in what future does choosing the other path feel like a mistake?]\n\n## Rules\n- 200-400 words max\n- Genuine advocacy, not token opposition — actually try to convince\n- Do NOT attack the preferred option (the Challenger does that)\n- Do NOT be balanced — be biased toward the rejected option. That's the point.\n- If there are multiple rejected options, steelman the strongest one`,\n temperature: 0.7,\n}\n\nconst preMortem: PersonaPreset = {\n id: 'pre-mortem',\n name: 'Pre-Mortem',\n systemPrompt: `# Pre-Mortem — Failure Narrator\n\n## Role\nYou are the Pre-Mortem analyst. Your job is to assume the preferred option was chosen, time has passed, and it has failed. Narrate the failure story — how it happened, when it went wrong, and why nobody saw it coming.\n\n## Cognitive Stance\nKlein's Pre-Mortem: by assuming failure has already occurred, you bypass optimism bias and unlock prospective hindsight. Research shows this surfaces 30% more risks than traditional risk analysis.\n\n## What You Must Do\n1. Set the scene — pick a realistic timeframe (3 months? 6 months? 1 year?) and describe the moment of failure\n2. Narrate the failure story in past tense — \"The decision was made on [date]. The first sign of trouble appeared when...\" Write it as a retrospective.\n3. Identify the specific failure modes — not vague \"it didn't work\" but concrete mechanisms\n4. Trace the cascade — how did one failure lead to another? What was the domino chain?\n5. Find the turning point — the single moment where intervention could have prevented the failure. This becomes a validation gate.\n\n## Output Format\n## Pre-Mortem Brief\n\n**Timeframe:** [when the failure becomes apparent]\n\n**The failure story:**\n[3-5 sentences in past tense narrating what went wrong]\n\n**Failure modes:**\n1. [specific mechanism of failure]\n2. [specific mechanism of failure]\n3. [specific mechanism of failure]\n\n**Cascade effect:**\n[how failure mode 1 led to 2 led to 3]\n\n**The turning point:**\n[the moment where intervention would have saved it — this becomes a validation gate]\n\n**Early warning signs:**\n- [signal 1 — what to watch for]\n- [signal 2 — what to watch for]\n\n## Rules\n- 200-400 words max\n- Write in past tense — the failure has already happened\n- Be specific about mechanisms, not vague about outcomes\n- Use real constraints from the decision context\n- The failure must be plausible, not catastrophic fantasy\n- Do NOT suggest solutions — the Synthesizer handles that`,\n temperature: 0.7,\n}\n\nexport const PERSONAS = {\n proposer,\n challenger,\n steelmanner,\n preMortem,\n} as const\n\nexport type PersonaId = keyof typeof PERSONAS\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,kBAAiB;;;ACAjB,iBAAkB;AAyBX,IAAM,oBAAoB,aAAE,OAAO;AAAA,EACxC,IAAI,aAAE,OAAO;AAAA,EACb,MAAM,aAAE,OAAO;AAAA,EACf,UAAU,aAAE,OAAO;AAAA,EACnB,OAAO,aAAE,OAAO;AAAA,EAChB,cAAc,aAAE,OAAO;AAAA,EACvB,aAAa,aAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,CAAC,EAAE,SAAS;AACjD,CAAC;AA2BM,IAAM,kBAAkB,aAAE,OAAO;AAAA,EACtC,gBAAgB,aAAE,OAAO;AAAA,EACzB,YAAY,aAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,GAAG;AAAA,EACrC,WAAW,aAAE,OAAO;AAAA,EACpB,OAAO,aAAE,MAAM,aAAE,OAAO,CAAC;AAAA,EACzB,SAAS,aAAE,MAAM,aAAE,OAAO,CAAC;AAAA,EAC3B,iBAAiB,aAAE,MAAM,aAAE,OAAO,CAAC;AAAA,EACnC,aAAa,aAAE,MAAM,aAAE,OAAO,CAAC;AAAA,EAC/B,KAAK,aAAE,OAAO;AAChB,CAAC;AAcM,IAAM,4BAA4B,aAAE,OAAO;AAAA,EAChD,eAAe,aAAE,OAAO;AAAA,EACxB,iBAAiB,aAAE,OAAO;AAAA,EAC1B,OAAO,aAAE,OAAO;AAAA,EAChB,SAAS,aAAE,OAAO;AAAA,EAClB,WAAW,aA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AAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EA0Cd,aAAa;AACf;AAEA,IAAM,cAA6B;AAAA,EACjC,IAAI;AAAA,EACJ,MAAM;AAAA,EACN,cAAc;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAwCd,aAAa;AACf;AAEA,IAAM,YAA2B;AAAA,EAC/B,IAAI;AAAA,EACJ,MAAM;AAAA,EACN,cAAc;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EA6Cd,aAAa;AACf;AAEO,IAAM,WAAW;AAAA,EACtB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;","names":["mitt","provider","Anthropic","delay","SYSTEM_PROMPT"]}
@@ -0,0 +1,393 @@
1
+ import { z } from 'zod';
2
+
3
+ interface CompletionRequest {
4
+ model: string;
5
+ systemPrompt: string;
6
+ messages: Array<{
7
+ role: 'user' | 'assistant';
8
+ content: string;
9
+ }>;
10
+ temperature?: number;
11
+ maxTokens?: number;
12
+ }
13
+ interface CompletionResponse {
14
+ content: string;
15
+ tokenCount: {
16
+ input: number;
17
+ output: number;
18
+ };
19
+ model: string;
20
+ }
21
+ interface LLMProvider {
22
+ id: string;
23
+ complete(request: CompletionRequest): Promise<CompletionResponse>;
24
+ }
25
+ declare const ParticipantSchema: z.ZodObject<{
26
+ id: z.ZodString;
27
+ name: z.ZodString;
28
+ provider: z.ZodString;
29
+ model: z.ZodString;
30
+ systemPrompt: z.ZodString;
31
+ temperature: z.ZodOptional<z.ZodNumber>;
32
+ }, "strip", z.ZodTypeAny, {
33
+ id: string;
34
+ name: string;
35
+ provider: string;
36
+ model: string;
37
+ systemPrompt: string;
38
+ temperature?: number | undefined;
39
+ }, {
40
+ id: string;
41
+ name: string;
42
+ provider: string;
43
+ model: string;
44
+ systemPrompt: string;
45
+ temperature?: number | undefined;
46
+ }>;
47
+ type Participant = z.infer<typeof ParticipantSchema>;
48
+ interface PromptRequest {
49
+ participantId: string;
50
+ provider: string;
51
+ model: string;
52
+ systemPrompt: string;
53
+ userMessage: string;
54
+ temperature?: number;
55
+ maxTokens?: number;
56
+ }
57
+ interface Protocol {
58
+ buildPrompts(config: DeliberationConfig, history: DeliberationMessage[], round: number): PromptRequest[];
59
+ getRoundCount(): number;
60
+ }
61
+ declare const SynthesisSchema: z.ZodObject<{
62
+ recommendation: z.ZodString;
63
+ confidence: z.ZodNumber;
64
+ reasoning: z.ZodString;
65
+ risks: z.ZodArray<z.ZodString, "many">;
66
+ dissent: z.ZodArray<z.ZodString, "many">;
67
+ validationGates: z.ZodArray<z.ZodString, "many">;
68
+ assumptions: z.ZodArray<z.ZodString, "many">;
69
+ raw: z.ZodString;
70
+ }, "strip", z.ZodTypeAny, {
71
+ recommendation: string;
72
+ confidence: number;
73
+ reasoning: string;
74
+ risks: string[];
75
+ dissent: string[];
76
+ validationGates: string[];
77
+ assumptions: string[];
78
+ raw: string;
79
+ }, {
80
+ recommendation: string;
81
+ confidence: number;
82
+ reasoning: string;
83
+ risks: string[];
84
+ dissent: string[];
85
+ validationGates: string[];
86
+ assumptions: string[];
87
+ raw: string;
88
+ }>;
89
+ type Synthesis = z.infer<typeof SynthesisSchema>;
90
+ interface Synthesizer {
91
+ synthesize(config: DeliberationConfig, messages: DeliberationMessage[], provider: LLMProvider): Promise<Synthesis>;
92
+ }
93
+ declare const DeliberationMessageSchema: z.ZodObject<{
94
+ participantId: z.ZodString;
95
+ participantName: z.ZodString;
96
+ round: z.ZodNumber;
97
+ content: z.ZodString;
98
+ timestamp: z.ZodDate;
99
+ tokenCount: z.ZodObject<{
100
+ input: z.ZodNumber;
101
+ output: z.ZodNumber;
102
+ }, "strip", z.ZodTypeAny, {
103
+ input: number;
104
+ output: number;
105
+ }, {
106
+ input: number;
107
+ output: number;
108
+ }>;
109
+ }, "strip", z.ZodTypeAny, {
110
+ participantId: string;
111
+ participantName: string;
112
+ round: number;
113
+ content: string;
114
+ timestamp: Date;
115
+ tokenCount: {
116
+ input: number;
117
+ output: number;
118
+ };
119
+ }, {
120
+ participantId: string;
121
+ participantName: string;
122
+ round: number;
123
+ content: string;
124
+ timestamp: Date;
125
+ tokenCount: {
126
+ input: number;
127
+ output: number;
128
+ };
129
+ }>;
130
+ type DeliberationMessage = z.infer<typeof DeliberationMessageSchema>;
131
+ declare const DeliberationConfigSchema: z.ZodObject<{
132
+ topic: z.ZodString;
133
+ options: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
134
+ context: z.ZodOptional<z.ZodString>;
135
+ preferredOption: z.ZodOptional<z.ZodString>;
136
+ participants: z.ZodArray<z.ZodObject<{
137
+ id: z.ZodString;
138
+ name: z.ZodString;
139
+ provider: z.ZodString;
140
+ model: z.ZodString;
141
+ systemPrompt: z.ZodString;
142
+ temperature: z.ZodOptional<z.ZodNumber>;
143
+ }, "strip", z.ZodTypeAny, {
144
+ id: string;
145
+ name: string;
146
+ provider: string;
147
+ model: string;
148
+ systemPrompt: string;
149
+ temperature?: number | undefined;
150
+ }, {
151
+ id: string;
152
+ name: string;
153
+ provider: string;
154
+ model: string;
155
+ systemPrompt: string;
156
+ temperature?: number | undefined;
157
+ }>, "many">;
158
+ rounds: z.ZodDefault<z.ZodNumber>;
159
+ tokenBudget: z.ZodOptional<z.ZodObject<{
160
+ perResponse: z.ZodOptional<z.ZodNumber>;
161
+ total: z.ZodOptional<z.ZodNumber>;
162
+ }, "strip", z.ZodTypeAny, {
163
+ perResponse?: number | undefined;
164
+ total?: number | undefined;
165
+ }, {
166
+ perResponse?: number | undefined;
167
+ total?: number | undefined;
168
+ }>>;
169
+ }, "strip", z.ZodTypeAny, {
170
+ topic: string;
171
+ participants: {
172
+ id: string;
173
+ name: string;
174
+ provider: string;
175
+ model: string;
176
+ systemPrompt: string;
177
+ temperature?: number | undefined;
178
+ }[];
179
+ rounds: number;
180
+ options?: string[] | undefined;
181
+ context?: string | undefined;
182
+ preferredOption?: string | undefined;
183
+ tokenBudget?: {
184
+ perResponse?: number | undefined;
185
+ total?: number | undefined;
186
+ } | undefined;
187
+ }, {
188
+ topic: string;
189
+ participants: {
190
+ id: string;
191
+ name: string;
192
+ provider: string;
193
+ model: string;
194
+ systemPrompt: string;
195
+ temperature?: number | undefined;
196
+ }[];
197
+ options?: string[] | undefined;
198
+ context?: string | undefined;
199
+ preferredOption?: string | undefined;
200
+ rounds?: number | undefined;
201
+ tokenBudget?: {
202
+ perResponse?: number | undefined;
203
+ total?: number | undefined;
204
+ } | undefined;
205
+ }>;
206
+ type DeliberationConfig = z.infer<typeof DeliberationConfigSchema>;
207
+ declare const DeliberationMetadataSchema: z.ZodObject<{
208
+ totalTokens: z.ZodObject<{
209
+ input: z.ZodNumber;
210
+ output: z.ZodNumber;
211
+ }, "strip", z.ZodTypeAny, {
212
+ input: number;
213
+ output: number;
214
+ }, {
215
+ input: number;
216
+ output: number;
217
+ }>;
218
+ durationMs: z.ZodNumber;
219
+ modelBreakdown: z.ZodRecord<z.ZodString, z.ZodObject<{
220
+ input: z.ZodNumber;
221
+ output: z.ZodNumber;
222
+ }, "strip", z.ZodTypeAny, {
223
+ input: number;
224
+ output: number;
225
+ }, {
226
+ input: number;
227
+ output: number;
228
+ }>>;
229
+ }, "strip", z.ZodTypeAny, {
230
+ totalTokens: {
231
+ input: number;
232
+ output: number;
233
+ };
234
+ durationMs: number;
235
+ modelBreakdown: Record<string, {
236
+ input: number;
237
+ output: number;
238
+ }>;
239
+ }, {
240
+ totalTokens: {
241
+ input: number;
242
+ output: number;
243
+ };
244
+ durationMs: number;
245
+ modelBreakdown: Record<string, {
246
+ input: number;
247
+ output: number;
248
+ }>;
249
+ }>;
250
+ type DeliberationMetadata = z.infer<typeof DeliberationMetadataSchema>;
251
+ interface DeliberationResult {
252
+ config: DeliberationConfig;
253
+ messages: DeliberationMessage[];
254
+ synthesis: Synthesis;
255
+ metadata: DeliberationMetadata;
256
+ }
257
+ type CouncilEvents = {
258
+ 'round:start': {
259
+ round: number;
260
+ participantCount: number;
261
+ };
262
+ response: DeliberationMessage;
263
+ 'synthesis:start': undefined;
264
+ complete: DeliberationResult;
265
+ error: Error;
266
+ };
267
+
268
+ interface CouncilOptions {
269
+ providers: Map<string, LLMProvider>;
270
+ protocol: Protocol;
271
+ synthesizer: Synthesizer;
272
+ synthesisProvider?: {
273
+ providerId: string;
274
+ model: string;
275
+ };
276
+ }
277
+ declare class Council {
278
+ private providers;
279
+ private protocol;
280
+ private synthesizer;
281
+ private synthesisProvider;
282
+ private emitter;
283
+ constructor(options: CouncilOptions);
284
+ on<K extends keyof CouncilEvents>(event: K, handler: (payload: CouncilEvents[K]) => void): void;
285
+ off<K extends keyof CouncilEvents>(event: K, handler: (payload: CouncilEvents[K]) => void): void;
286
+ deliberate(rawConfig: DeliberationConfig): Promise<DeliberationResult>;
287
+ }
288
+
289
+ interface AnthropicProviderConfig {
290
+ apiKey: string;
291
+ defaultModel?: string;
292
+ defaultMaxTokens?: number;
293
+ }
294
+ declare class AnthropicProvider implements LLMProvider {
295
+ readonly id: "anthropic";
296
+ private client;
297
+ private defaultModel;
298
+ private defaultMaxTokens;
299
+ constructor(config: AnthropicProviderConfig);
300
+ complete(request: CompletionRequest): Promise<CompletionResponse>;
301
+ }
302
+
303
+ interface OpenRouterProviderConfig {
304
+ apiKey: string;
305
+ appName?: string;
306
+ defaultModel?: string;
307
+ defaultMaxTokens?: number;
308
+ siteUrl?: string;
309
+ }
310
+ declare class OpenRouterProvider implements LLMProvider {
311
+ readonly id: "openrouter";
312
+ private readonly apiKey;
313
+ private readonly appName;
314
+ private readonly defaultModel;
315
+ private readonly defaultMaxTokens;
316
+ private readonly siteUrl;
317
+ constructor(config: OpenRouterProviderConfig);
318
+ complete(request: CompletionRequest): Promise<CompletionResponse>;
319
+ }
320
+
321
+ interface AdversarialProtocolOptions {
322
+ rebuttalGuidance?: Record<string, string>;
323
+ }
324
+ declare class AdversarialProtocol implements Protocol {
325
+ private readonly rebuttalGuidance;
326
+ constructor(options?: AdversarialProtocolOptions);
327
+ getRoundCount(): number;
328
+ buildPrompts(config: DeliberationConfig, history: DeliberationMessage[], round: number): PromptRequest[];
329
+ private buildInitialBriefs;
330
+ private buildRebuttals;
331
+ }
332
+
333
+ interface PeerReviewProtocolOptions {
334
+ enableRevote?: boolean;
335
+ }
336
+ declare class PeerReviewProtocol implements Protocol {
337
+ private readonly enableRevote;
338
+ constructor(options?: PeerReviewProtocolOptions);
339
+ getRoundCount(): number;
340
+ buildPrompts(config: DeliberationConfig, history: DeliberationMessage[], round: number): PromptRequest[];
341
+ private buildInitialBriefs;
342
+ private buildRankingRound;
343
+ private buildRevoteRound;
344
+ }
345
+
346
+ interface ChairmanSynthesizerOptions {
347
+ model?: string;
348
+ temperature?: number;
349
+ }
350
+ declare class ChairmanSynthesizer implements Synthesizer {
351
+ private readonly model;
352
+ private readonly temperature;
353
+ constructor(options?: ChairmanSynthesizerOptions);
354
+ synthesize(config: DeliberationConfig, messages: DeliberationMessage[], provider: LLMProvider): Promise<Synthesis>;
355
+ }
356
+
357
+ interface DialecticalSynthesizerOptions {
358
+ model?: string;
359
+ temperature?: number;
360
+ }
361
+ declare class DialecticalSynthesizer implements Synthesizer {
362
+ private readonly model;
363
+ private readonly temperature;
364
+ constructor(options?: DialecticalSynthesizerOptions);
365
+ synthesize(config: DeliberationConfig, messages: DeliberationMessage[], provider: LLMProvider): Promise<Synthesis>;
366
+ }
367
+
368
+ type PersonaPreset = Omit<Participant, 'provider' | 'model'>;
369
+ declare const PERSONAS: {
370
+ readonly proposer: PersonaPreset;
371
+ readonly challenger: PersonaPreset;
372
+ readonly steelmanner: PersonaPreset;
373
+ readonly preMortem: PersonaPreset;
374
+ };
375
+ type PersonaId = keyof typeof PERSONAS;
376
+
377
+ interface AnonymizationMap {
378
+ labelToParticipant: Map<string, string>;
379
+ participantToLabel: Map<string, string>;
380
+ }
381
+ declare function createAnonymizationMap(participantIds: string[]): AnonymizationMap;
382
+ declare function anonymizeMessages(messages: DeliberationMessage[], map: AnonymizationMap): Array<{
383
+ label: string;
384
+ content: string;
385
+ }>;
386
+ declare function deanonymizeLabel(label: string, map: AnonymizationMap): string | undefined;
387
+
388
+ declare function buildInitialUserMessage(config: DeliberationConfig): string;
389
+
390
+ declare function buildSynthesisUserMessage(config: DeliberationConfig, messages: DeliberationMessage[]): string;
391
+ declare function parseSynthesisResponse(raw: string): Synthesis;
392
+
393
+ export { AdversarialProtocol, type AnonymizationMap, AnthropicProvider, ChairmanSynthesizer, type CompletionRequest, type CompletionResponse, Council, type CouncilEvents, type CouncilOptions, type DeliberationConfig, DeliberationConfigSchema, type DeliberationMessage, DeliberationMessageSchema, type DeliberationMetadata, DeliberationMetadataSchema, type DeliberationResult, DialecticalSynthesizer, type LLMProvider, OpenRouterProvider, PERSONAS, type Participant, ParticipantSchema, PeerReviewProtocol, type PersonaId, type PromptRequest, type Protocol, type Synthesis, SynthesisSchema, type Synthesizer, anonymizeMessages, buildInitialUserMessage, buildSynthesisUserMessage, createAnonymizationMap, deanonymizeLabel, parseSynthesisResponse };