import { MODES, POLICIES, type PrivacyProfile, type ThinkingLevel, type UltraConfig } from "../types.js"; import { assertRosterModel, MAX_ROSTER_TIERS, type ModelRoster } from "../models/roster.js"; const THINKING = new Set(["off", "minimal", "low", "medium", "high", "xhigh", "max"]); const VERSION = /^\d+\.\d+\.\d+(?:[-+][A-Za-z0-9.-]+)?$/; const MODEL = /^[A-Za-z0-9._-]+\/[A-Za-z0-9._:+-]+$/; function object(value: unknown, label: string): Record { if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`UltraPi config ${label} must be an object`); return value as Record; } function boolean(value: unknown, label: string): boolean { if (typeof value !== "boolean") throw new Error(`UltraPi config ${label} must be boolean`); return value; } function version(value: unknown, label: string): string { if (typeof value !== "string" || value.length > 128 || !VERSION.test(value)) throw new Error(`UltraPi config ${label} must be semver`); return value; } function model(value: unknown, label: string): string { if (typeof value !== "string" || value.length > 256 || !MODEL.test(value)) throw new Error(`UltraPi config ${label} must be provider/model`); return value; } function thinking(value: unknown, label: string): ThinkingLevel { if (typeof value !== "string" || !THINKING.has(value as ThinkingLevel)) throw new Error(`UltraPi config ${label} is invalid`); return value as ThinkingLevel; } function boundedNumber(value: unknown, label: string, { integer = false, min = 0, max = 1_000_000 }: { integer?: boolean; min?: number; max?: number } = {}): number { if (typeof value !== "number" || !Number.isFinite(value) || value < min || value > max || (integer && !Number.isSafeInteger(value))) throw new Error(`UltraPi config ${label} is out of bounds`); return value; } function positiveInteger(value: unknown, label: string): number { return boundedNumber(value, label, { integer: true, min: 1 }); } function ratio(value: unknown, label: string): number { return boundedNumber(value, label, { min: 0, max: 1 }); } function stringArray(value: unknown, label: string): string[] { if (!Array.isArray(value)) throw new Error(`UltraPi config ${label} must be an array`); return value.map((entry, index) => model(entry, `${label}[${index}]`)); } /** * The declared roster is the single source of truth for every later model check, so it is * validated before any role is: a roster that cannot decide anything, or that ranks the same * model twice, would make the ordering meaningless rather than merely wrong. */ function roster(value: unknown, profile: PrivacyProfile): ModelRoster { const declared = object(value, "models"); const tiers = stringArray(declared.tiers, "models.tiers"); if (tiers.length === 0 || tiers.length > MAX_ROSTER_TIERS) throw new Error(`UltraPi config models.tiers must declare 1 to ${MAX_ROSTER_TIERS} models, weakest first`); if (new Set(tiers).size !== tiers.length) throw new Error("UltraPi config models.tiers must not rank the same model twice"); const nonCritical = declared.nonCritical === undefined ? [] : stringArray(declared.nonCritical, "models.nonCritical"); for (const entry of nonCritical) if (!tiers.includes(entry)) throw new Error(`UltraPi config models.nonCritical lists ${entry}, which is not in models.tiers`); if (tiers.every((tier) => nonCritical.includes(tier))) throw new Error("UltraPi config models.nonCritical cannot cover every tier; at least one model must be able to decide"); return { profile, tiers, nonCritical }; } function modelByLens(value: unknown, label: string, declared: ModelRoster, critical: boolean): void { if (value === undefined) return; for (const [lens, entry] of Object.entries(object(value, `${label}.modelByLens`))) { if (!/^[a-z][a-z0-9-]{0,63}$/.test(lens)) throw new Error(`UltraPi config ${label}.modelByLens.${lens} is not a lens name`); assertRosterModel(declared, model(entry, `${label}.modelByLens.${lens}`), critical); } } function role(value: unknown, label: string): Record { const config = object(value, label); model(config.model, `${label}.model`); thinking(config.thinking, `${label}.thinking`); return config; } function rejectDeadField(value: Record, key: string, label: string): void { if (Object.hasOwn(value, key)) throw new Error(`UltraPi config ${label} is no longer supported`); } export function assertConfig(value: unknown): asserts value is UltraConfig { const config = object(value, "root"); if (config.schemaVersion !== 1) throw new Error("Unsupported UltraPi config schemaVersion"); version(config.configVersion, "configVersion"); version(config.policyVersion, "policyVersion"); if (config.profile !== "private" && config.profile !== "free") throw new Error("UltraPi config profile is invalid"); const profile = config.profile; if (typeof config.mode !== "string" || !(MODES as readonly string[]).includes(config.mode)) throw new Error("UltraPi config mode is invalid"); if (typeof config.policy !== "string" || !(POLICIES as readonly string[]).includes(config.policy)) throw new Error("UltraPi config policy is invalid"); const budgets = object(config.budgets, "budgets"); boolean(budgets.acknowledged, "budgets.acknowledged"); for (const key of ["weeklyCreditBudget", "dailyCreditBudget"] as const) if (budgets[key] !== undefined) boundedNumber(budgets[key], `budgets.${key}`, { min: Number.EPSILON, max: 1_000_000_000 }); const declaredRoster = roster(config.models, profile); const root = role(config.root, "root"); assertRosterModel(declaredRoster, root.model as string, true); const scout = role(config.scout, "scout"); assertRosterModel(declaredRoster, scout.model as string); if (scout.allowedSkills !== undefined) { if (!Array.isArray(scout.allowedSkills) || scout.allowedSkills.length > 8 || scout.allowedSkills.some((name) => typeof name !== "string" || !/^[a-z][a-z0-9-]{0,63}$/.test(name))) throw new Error("UltraPi config scout.allowedSkills must be up to eight skill slugs"); } modelByLens(scout.modelByLens, "scout", declaredRoster, false); const scoutInitial = positiveInteger(scout.initial, "scout.initial"); const scoutParallel = positiveInteger(scout.maxParallel, "scout.maxParallel"); const scoutTotal = positiveInteger(scout.maxTotal, "scout.maxTotal"); positiveInteger(scout.maxTurns, "scout.maxTurns"); positiveInteger(scout.maxOutputTokens, "scout.maxOutputTokens"); if (scoutInitial > scoutParallel || scoutParallel > scoutTotal) throw new Error("UltraPi config scout.initial/maxParallel/maxTotal ordering is invalid"); const writer = role(config.boundedWriter, "boundedWriter"); rejectDeadField(writer, "maxParallel", "boundedWriter.maxParallel"); assertRosterModel(declaredRoster, writer.model as string, true); // A writer decides, so a per-lens writer model has to be one the roster lets decide. modelByLens(writer.modelByLens, "boundedWriter", declaredRoster, true); positiveInteger(writer.maxTurns, "boundedWriter.maxTurns"); positiveInteger(writer.maxOutputTokens, "boundedWriter.maxOutputTokens"); const repair = role(config.repair, "repair"); assertRosterModel(declaredRoster, repair.model as string, true); positiveInteger(repair.maxAttempts, "repair.maxAttempts"); boolean(repair.sameFingerprintEscalation, "repair.sameFingerprintEscalation"); const deep = role(config.deep, "deep"); rejectDeadField(deep, "maxParallel", "deep.maxParallel"); assertRosterModel(declaredRoster, deep.model as string, true); positiveInteger(deep.maxTurns, "deep.maxTurns"); const arbitration = role(config.arbitration, "arbitration"); assertRosterModel(declaredRoster, arbitration.model as string, true); positiveInteger(arbitration.maxTurns, "arbitration.maxTurns"); const warRoom = object(config.warRoom, "warRoom"); boolean(warRoom.autoEnabled, "warRoom.autoEnabled"); rejectDeadField(warRoom, "maxMembers", "warRoom.maxMembers"); boundedNumber(warRoom.maxSpecialists, "warRoom.maxSpecialists", { integer: true, min: 0, max: 4 }); boundedNumber(warRoom.maxRounds, "warRoom.maxRounds", { integer: true, min: 1, max: 3 }); boundedNumber(warRoom.maxMessagesPerMember, "warRoom.maxMessagesPerMember", { integer: true, min: 1, max: 4 }); const agents = object(config.piAgentsBudgets, "piAgentsBudgets"); const maxAgents = positiveInteger(agents.maxAgents, "piAgentsBudgets.maxAgents"); const maxParallelism = positiveInteger(agents.maxParallelism, "piAgentsBudgets.maxParallelism"); positiveInteger(agents.maxIterations, "piAgentsBudgets.maxIterations"); if (agents.maxDepth !== 1) throw new Error("UltraPi config piAgentsBudgets.maxDepth must equal 1"); positiveInteger(agents.maxTurns, "piAgentsBudgets.maxTurns"); if (agents.maxCost !== undefined) boundedNumber(agents.maxCost, "piAgentsBudgets.maxCost", { min: Number.EPSILON, max: 1_000_000_000 }); if (maxParallelism > maxAgents) throw new Error("UltraPi config piAgentsBudgets.maxParallelism cannot exceed maxAgents"); const context = object(config.context, "context"); const envelopeTarget = positiveInteger(context.envelopeTargetTokens, "context.envelopeTargetTokens"); const envelopeCap = positiveInteger(context.envelopeHardCapTokens, "context.envelopeHardCapTokens"); const compactAt = ratio(context.compactAtRatio, "context.compactAtRatio"); const blockWideAt = ratio(context.blockWideSwarmAtRatio, "context.blockWideSwarmAtRatio"); if (envelopeTarget > envelopeCap) throw new Error("UltraPi config context.envelopeTargetTokens cannot exceed envelopeHardCapTokens"); if (compactAt >= blockWideAt) throw new Error("UltraPi config context.compactAtRatio must be below blockWideSwarmAtRatio"); const telemetry = object(config.telemetry, "telemetry"); rejectDeadField(telemetry, "enabled", "telemetry.enabled"); boolean(telemetry.rawVaultEnabled, "telemetry.rawVaultEnabled"); positiveInteger(telemetry.rawRetentionDays, "telemetry.rawRetentionDays"); positiveInteger(telemetry.analyticsRetentionDays, "telemetry.analyticsRetentionDays"); rejectDeadField(telemetry, "weeklyExportRequiresApproval", "telemetry.weeklyExportRequiresApproval"); const experiment = object(config.experiment, "experiment"); ratio(experiment.challengerAllocation, "experiment.challengerAllocation"); ratio(experiment.stopLossSuccessDrop, "experiment.stopLossSuccessDrop"); ratio(experiment.stopLossCostIncrease, "experiment.stopLossCostIncrease"); const compatibility = object(config.compatibility, "compatibility"); version(compatibility.piVersion, "compatibility.piVersion"); version(compatibility.piAgentsVersion, "compatibility.piAgentsVersion"); }