/** * Factory runtime settings (non-secret). Credentials stay in Connect mappings. */ import { defaultCardRoutes, normalizeCardRoutes, type CardRoute } from '../cards/routes.ts' import { loadJson, saveJson, storageKeys } from './storage.ts' import { defaultPolicyConfig, type FactoryPolicyConfig } from '../core/policy.ts' import { defaultColumnTimeLimits, type ColumnTimeLimits } from '../core/board.ts' import { defaultRunnerSettings, normalizeRunnerSettings, type RunnerSettings } from '../adapters/agent/runners.ts' export type FactorySettings = FactoryPolicyConfig & { /** Cloudflare account id for model triage (Workers AI / AI Gateway). */ cloudflareAccountId: string | null /** AI Gateway id (default kody). */ cloudflareAiGatewayId: string /** Max agent starts per sweep tick. */ sweepStartLimit: number /** Default dryRun for live agent starts when true (extra safety). */ agentDryRunDefault: boolean /** * Which projects/repos sweep, backfill, and webhook intake act on. * Default `allowlist` with nothing listed: nothing is in scope until the owner names the pilot. */ pilotScope: PilotScope /** Minutes the implementer has to get main green after a red merge before a fallback agent is queued. */ postMergeFixTimeoutMinutes: number /** Minutes to wait for the merge commit's checks to report before the watch gives up. */ postMergePendingTimeoutMinutes: number /** Per-column time limits (ms) for stall detection on work and plan boards. */ columnTimeLimits: ColumnTimeLimits /** Whether to surface stalled cards as a health signal. */ stallHealthEnabled: boolean /** Global kill switch: when true, the sweep will not start new agent runs or merges. Default false. */ killSwitch: boolean /** When true, the factory writes status comments and labels back to source GitHub issues. Default false. */ issueWritebackEnabled: boolean /** GitHub login linked to the Cursor account for Bugbot triggers (e.g. 'kentcdodds'). Empty skips the Bugbot step. */ bugbotCursorLogin: string /** Discord channel id for ship-pr summaries. Empty skips posting. */ shipPrSummaryChannelId: string /** Whether Discord notification output is enabled. Default false. */ discordNotificationsEnabled: boolean /** Discord channel id for factory notifications. Empty skips posting. */ discordNotificationsChannelId: string /** * Every bot wake goes through `@kody/wake-relay`. Minutes to wait for its * `wake.delivered` answer before the sweep raises a wake alert (Factory * health page, card label, Discord when on). Default 5, clamped 2 to 60. * Reads the older `eventWakeFallbackMinutes` value when this one is unset. */ wakeAlertMinutes: number /** Emit `@kody/factory.health.*` and `@kody/factory.card.created` events. Default false. */ emitHealthEvents: boolean /** * Cards from source events (DR problems, status outages). `shadow` (default) * records what would be filed; `live` files through create() with the same key. */ eventCardsMode: 'shadow' | 'live' /** * Which role a new or re-triaged card wakes (first match wins). Emits * `@kody/factory.wake.requested` through `@kody/wake-relay`, once per card. * Empty list turns card wakes off. Default: see `defaultCardRoutes()`. */ cardRoutes: CardRoute[] /** * Friction filing (`./friction/file`) makes cards for repos in a factory * project, and for Kody package targets under `packageProjectId`. * Off keeps the older GitHub issue and Patch wake paths. */ frictionCards: { enabled: boolean; packageProjectId: string } /** * Web push VAPID public key (base64url, uncompressed P-256 point). Not a * secret. The private key lives only in the `webPush` signing credential. * Empty turns web push off. */ webPushVapidPublicKey: string /** VAPID `sub` claim: a mailto: or https: contact for push services. */ webPushSubject: string /** Factory project that Sentry issue cards land in when `sentryProjectMap` has no match. Empty drops unmapped issues. */ sentryIntakeProjectId: string /** Sentry project slug to factory project id. */ sentryProjectMap: Record /** Kody id of the package that publishes Sentry issue events (`@kody/.issue.alerted`). Default `sentry-events`. */ sentryEventsSource: string /** * GitHub as package events (`@kody/github.*`). `shadow` (default) records * what each event would do next to the factory's own webhook result; * `live` lets the events do the work and turns the factory's own GitHub * webhooks into forwarders; `off` ignores the events. */ githubEventsMode: 'off' | 'shadow' | 'live' /** Forward deliveries that reach the factory's own GitHub webhooks to `@kody/github/events/ingest`. Default true. */ githubEventsBridge: boolean /** Kody id of the package that publishes `@kody/github.*` events. Default `github`. */ githubEventsSource: string /** * Agent runners by id (`devin` by default): the runner `package` that * answers `@kody/factory.agent.*.requested` and whose `session.*` events * count, its `exports`, and `sessionUrlTemplate` for card links. */ runners: RunnerSettings /** * Base URL for every link the factory hands out (card links, report links, * health links, agent briefs). Empty means the app's hosted kody.run URL. * Set it to a custom domain (for example `https://factory.kody.build`) once * that domain serves the app. */ publicBaseUrl: string /** * Who may open the app. `platform` (default) trusts Kody's own gate, which * admits only people who can run the app while it is not internet-visible. * `members` also checks inside the app: signed-in members of the owning org * only, everyone else is sent to Sign in with Kody. Turn `members` on before * the app becomes internet-visible (custom domain at the host root). */ appAccess: 'platform' | 'members' } export type PilotScope = { mode: 'all' | 'allowlist'; projectIds: string[]; repoRefs: string[] } export function defaultPilotScope(): PilotScope { return { mode: 'allowlist', projectIds: [], repoRefs: [] } } export function normalizePilotScope(raw: unknown): PilotScope { const r = (raw && typeof raw === 'object' ? raw : {}) as Partial const ids = Array.isArray(r.projectIds) ? r.projectIds.map(String).filter((x) => /^[a-z][a-z0-9_-]{0,63}$/.test(x)) : [] const repos = Array.isArray(r.repoRefs) ? r.repoRefs.map(String).filter((x) => /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(x)) : [] return { mode: r.mode === 'all' ? 'all' : 'allowlist', projectIds: ids, repoRefs: repos } } export function defaultFactorySettings(): FactorySettings { return { ...defaultPolicyConfig(), cloudflareAccountId: null, cloudflareAiGatewayId: 'kody', sweepStartLimit: 3, agentDryRunDefault: false, pilotScope: defaultPilotScope(), postMergeFixTimeoutMinutes: 60, postMergePendingTimeoutMinutes: 180, columnTimeLimits: defaultColumnTimeLimits(), stallHealthEnabled: false, killSwitch: false, issueWritebackEnabled: false, bugbotCursorLogin: '', shipPrSummaryChannelId: '', discordNotificationsEnabled: false, discordNotificationsChannelId: '', wakeAlertMinutes: 5, emitHealthEvents: false, eventCardsMode: 'shadow', cardRoutes: defaultCardRoutes(), frictionCards: { enabled: true, packageProjectId: 'kody' }, webPushVapidPublicKey: '', webPushSubject: 'https://kody-factory--kody.kody.run/', sentryIntakeProjectId: 'kody', sentryProjectMap: {}, sentryEventsSource: 'sentry-events', githubEventsMode: 'shadow', githubEventsBridge: true, githubEventsSource: 'github', runners: defaultRunnerSettings(), publicBaseUrl: '', appAccess: 'platform', // Keep shadowMode true until owner flips via settings / setup. shadowMode: true, maxConcurrentRuns: 3, agentMayMerge: 'none', } } export async function loadSettings(): Promise { const raw = await loadJson>( storageKeys.SETTINGS_KEY, defaultFactorySettings(), ) const merged = { ...defaultFactorySettings(), ...raw } return { ...merged, pilotScope: normalizePilotScope(merged.pilotScope), wakeAlertMinutes: Math.min(Math.max(Math.floor(Number((raw as { wakeAlertMinutes?: unknown }).wakeAlertMinutes ?? (raw as { eventWakeFallbackMinutes?: unknown }).eventWakeFallbackMinutes) || 5), 2), 60), emitHealthEvents: merged.emitHealthEvents === true, eventCardsMode: merged.eventCardsMode === 'live' ? 'live' : 'shadow', cardRoutes: normalizeCardRoutes(merged.cardRoutes), frictionCards: normalizeFrictionCards(merged.frictionCards), webPushVapidPublicKey: typeof merged.webPushVapidPublicKey === 'string' && /^[A-Za-z0-9_-]{80,100}$/.test(merged.webPushVapidPublicKey) ? merged.webPushVapidPublicKey : '', webPushSubject: typeof merged.webPushSubject === 'string' && /^(mailto:[^\s]{3,200}|https:\/\/[^\s]{3,200})$/.test(merged.webPushSubject) ? merged.webPushSubject : 'https://kody-factory--kody.kody.run/', sentryIntakeProjectId: typeof merged.sentryIntakeProjectId === 'string' && /^([a-z][a-z0-9_-]{0,63})?$/.test(merged.sentryIntakeProjectId) ? merged.sentryIntakeProjectId : 'kody', sentryProjectMap: normalizeProjectMap(merged.sentryProjectMap), sentryEventsSource: typeof merged.sentryEventsSource === 'string' && /^[a-z0-9][a-z0-9_-]{0,63}$/.test(merged.sentryEventsSource) ? merged.sentryEventsSource : 'sentry-events', githubEventsMode: merged.githubEventsMode === 'live' || merged.githubEventsMode === 'off' ? merged.githubEventsMode : 'shadow', githubEventsBridge: merged.githubEventsBridge !== false, runners: normalizeRunnerSettings(merged.runners), githubEventsSource: typeof merged.githubEventsSource === 'string' && /^[a-z0-9][a-z0-9_-]{0,63}$/.test(merged.githubEventsSource) ? merged.githubEventsSource : 'github', publicBaseUrl: normalizeBaseUrl(merged.publicBaseUrl), appAccess: merged.appAccess === 'members' ? 'members' : 'platform', } } /** `https://host[/path]` with no trailing slash, query, or hash; anything else is ''. */ function normalizeFrictionCards(raw: unknown): FactorySettings['frictionCards'] { const r = (raw && typeof raw === 'object' ? raw : {}) as Partial return { enabled: r.enabled !== false, packageProjectId: typeof r.packageProjectId === 'string' && /^[a-z][a-z0-9_-]{0,63}$/.test(r.packageProjectId) ? r.packageProjectId : 'kody', } } export function normalizeBaseUrl(raw: unknown): string { if (typeof raw !== 'string' || !raw.trim()) return '' try { const u = new URL(raw.trim()) if (u.protocol !== 'https:' || u.username || u.password || u.search || u.hash) return '' return `${u.origin}${u.pathname}`.replace(/\/+$/, '') } catch { return '' } } function normalizeProjectMap(raw: unknown): Record { if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return {} const out: Record = {} for (const [k, v] of Object.entries(raw as Record).slice(0, 50)) { if (/^[A-Za-z0-9_.-]{1,100}$/.test(k) && typeof v === 'string' && /^[a-z][a-z0-9_-]{0,63}$/.test(v)) out[k] = v } return out } export async function saveSettings(next: FactorySettings): Promise { await saveJson(storageKeys.SETTINGS_KEY, next) } export async function patchSettings( patch: Partial, ): Promise { const current = await loadSettings() const next = { ...current, ...patch } await saveSettings(next) return next }