import { existsSync, readFileSync, writeFileSync } from 'node:fs'; import { getWorkspaceDir } from './init-command.js'; import type { AuthProfile } from './auth.js'; import { ensureAccountUserDataLayout, ensureUserDataLayout, getUserDataAccountGameplayConfigFile, getUserDataGameplayConfigFile, } from './user-data.js'; import { parseGameplayTriggerConfigs, type GameplayTriggerConfigs, } from './trigger-config.js'; export const CLAWCLAW_ROLE_IDS = [ 'shrimp_generic', 'shrimp_warrior', 'shrimp_pistol', 'crab_generic', 'neutral_paradise_fish', 'neutral_octopus', ] as const; export type ClawclawRoleId = typeof CLAWCLAW_ROLE_IDS[number]; export type GameplayFallbackBehaviors = Record; export const NPM_ROLE_FALLBACK_BEHAVIORS: GameplayFallbackBehaviors = { shrimp_generic: 'task-only', shrimp_warrior: 'task-only', shrimp_pistol: 'task-only', crab_generic: 'kill-lone', neutral_paradise_fish: 'patrol', neutral_octopus: 'kill-lone', }; export const DEFAULT_BEHAVIOR_IDLE_MS = 500; const LEGACY_DEFAULT_FALLBACK_IDLE_MS = 8_000; const LEGACY_RUNTIME_FALLBACK = 'runtime-task-demo'; const GAMEPLAY_CONFIG_FIELDS = new Set([ 'disabled_perception_modules', 'fallback_behaviors', 'disabled_behaviors', 'disabled_triggers', 'idle_ms', 'triggers', ]); const LEGACY_GAMEPLAY_CONFIG_FIELDS = new Set([ ...GAMEPLAY_CONFIG_FIELDS, 'default_strategies', 'disabled_strategies', 'disabled_intents', 'fallback_idle_ms', ]); const LEGACY_FIELDS = [ 'default_strategies', 'disabled_strategies', 'disabled_intents', 'fallback_idle_ms', ] as const; export interface GameplayConfig { disabled_perception_modules: string[]; fallback_behaviors: GameplayFallbackBehaviors; disabled_behaviors: string[]; disabled_triggers: string[]; idle_ms: number; triggers: GameplayTriggerConfigs; } const RESOURCE_ID = /^[a-z0-9][a-z0-9._-]*$/; export function defaultGameplayConfig(): GameplayConfig { return { disabled_perception_modules: [], fallback_behaviors: { ...NPM_ROLE_FALLBACK_BEHAVIORS }, disabled_behaviors: [], disabled_triggers: [], idle_ms: DEFAULT_BEHAVIOR_IDLE_MS, triggers: {}, }; } function record(value: unknown): Record | null { if (!value || typeof value !== 'object' || Array.isArray(value)) return null; const prototype = Object.getPrototypeOf(value); return prototype === Object.prototype || prototype === null ? value as Record : null; } function hasOwn(recordValue: Record, field: string): boolean { return Object.prototype.hasOwnProperty.call(recordValue, field); } function resourceId(value: unknown, field: string): string { if (typeof value !== 'string' || !RESOURCE_ID.test(value)) { throw new Error(`${field} must be a resource id.`); } return value; } function resourceIds(value: unknown, field: string): string[] { if (!Array.isArray(value)) throw new Error(`${field} must be an array.`); return [...new Set(value.map((entry) => resourceId(entry, field)))]; } function behaviorIdleMs(value: unknown): number { if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0 || value > 60_000) { throw new Error('user-data/gameplay.json idle_ms must be an integer from 0 to 60000.'); } return value; } function fallbackBehaviorBindings( value: unknown, field: string, options: { legacy?: boolean } = {}, ): GameplayFallbackBehaviors { const configured = record(value); if (!configured) throw new Error(`${field} must be an object.`); const unknownRoles = Object.keys(configured) .filter((role) => !(CLAWCLAW_ROLE_IDS as readonly string[]).includes(role)); if (unknownRoles.length > 0) { throw new Error(`Unknown role in ${field}: ${unknownRoles.join(', ')}`); } const result = {} as GameplayFallbackBehaviors; for (const role of CLAWCLAW_ROLE_IDS) { const configuredBehavior = hasOwn(configured, role) ? configured[role] : undefined; if (configuredBehavior === null && !options.legacy) { result[role] = null; continue; } const behavior = resourceId(configuredBehavior, `${field}.${role}`); result[role] = options.legacy && behavior === LEGACY_RUNTIME_FALLBACK ? NPM_ROLE_FALLBACK_BEHAVIORS[role] : behavior; } return result; } function assertOnlyFields( root: Record, allowed: ReadonlySet, ): void { const unknownFields = Object.keys(root).filter((field) => !allowed.has(field)); if (unknownFields.length > 0) { throw new Error( `user-data/gameplay.json contains unknown fields: ${unknownFields.sort().join(', ')}.`, ); } } export function parseGameplayConfig(value: unknown): GameplayConfig { const root = record(value); if (!root) throw new Error('user-data/gameplay.json must contain a JSON object.'); assertOnlyFields(root, GAMEPLAY_CONFIG_FIELDS); return { disabled_perception_modules: resourceIds( root.disabled_perception_modules, 'user-data/gameplay.json disabled_perception_modules', ), fallback_behaviors: fallbackBehaviorBindings( root.fallback_behaviors, 'user-data/gameplay.json fallback_behaviors', ), disabled_behaviors: resourceIds( root.disabled_behaviors, 'user-data/gameplay.json disabled_behaviors', ), disabled_triggers: hasOwn(root, 'disabled_triggers') ? resourceIds( root.disabled_triggers, 'user-data/gameplay.json disabled_triggers', ) : [], idle_ms: behaviorIdleMs(root.idle_ms), triggers: parseGameplayTriggerConfigs(root.triggers), }; } function legacyDisabledIds( root: Record, field: 'disabled_strategies' | 'disabled_intents', ): string[] { if (!hasOwn(root, field)) return []; return resourceIds(root[field], `user-data/gameplay.json ${field}`); } function migratedIdleMs(root: Record): number { if (hasOwn(root, 'idle_ms')) return behaviorIdleMs(root.idle_ms); if (!hasOwn(root, 'fallback_idle_ms')) return DEFAULT_BEHAVIOR_IDLE_MS; const legacyValue = root.fallback_idle_ms; if ( typeof legacyValue !== 'number' || !Number.isSafeInteger(legacyValue) || legacyValue < 0 || legacyValue > 60_000 ) { throw new Error( 'user-data/gameplay.json fallback_idle_ms must be an integer from 0 to 60000.', ); } return legacyValue === LEGACY_DEFAULT_FALLBACK_IDLE_MS ? DEFAULT_BEHAVIOR_IDLE_MS : legacyValue; } function migrateLegacyGameplayConfig(root: Record): GameplayConfig { assertOnlyFields(root, LEGACY_GAMEPLAY_CONFIG_FIELDS); const fallbackSource = hasOwn(root, 'fallback_behaviors') ? root.fallback_behaviors : root.default_strategies; const legacyDisabledStrategies = legacyDisabledIds(root, 'disabled_strategies') .filter((id) => id !== LEGACY_RUNTIME_FALLBACK); const legacyDisabledIntents = legacyDisabledIds(root, 'disabled_intents'); const unifiedDisabledBehaviors = hasOwn(root, 'disabled_behaviors') ? resourceIds( root.disabled_behaviors, 'user-data/gameplay.json disabled_behaviors', ) : []; return parseGameplayConfig({ disabled_perception_modules: hasOwn(root, 'disabled_perception_modules') ? root.disabled_perception_modules : [], fallback_behaviors: hasOwn(root, 'fallback_behaviors') ? fallbackBehaviorBindings( fallbackSource, 'user-data/gameplay.json fallback_behaviors', ) : fallbackBehaviorBindings( fallbackSource, 'user-data/gameplay.json default_strategies', { legacy: true }, ), disabled_behaviors: [ ...unifiedDisabledBehaviors, ...legacyDisabledStrategies, ...legacyDisabledIntents, ], disabled_triggers: hasOwn(root, 'disabled_triggers') ? root.disabled_triggers : [], idle_ms: migratedIdleMs(root), triggers: hasOwn(root, 'triggers') ? root.triggers : {}, }); } function hasLegacyFields(root: Record): boolean { return LEGACY_FIELDS.some((field) => hasOwn(root, field)); } export function writeGameplayConfig( config: GameplayConfig, workspaceDir = getWorkspaceDir(), profile?: Pick, ): GameplayConfig { if (profile) ensureAccountUserDataLayout(workspaceDir, profile); else ensureUserDataLayout(workspaceDir); const normalized = parseGameplayConfig(config); writeFileSync( profile ? getUserDataAccountGameplayConfigFile(workspaceDir, profile) : getUserDataGameplayConfigFile(workspaceDir), `${JSON.stringify(normalized, null, 2)}\n`, 'utf8', ); return normalized; } export function readGameplayConfig( workspaceDir = getWorkspaceDir(), profile?: Pick, ): GameplayConfig { if (profile) ensureAccountUserDataLayout(workspaceDir, profile); else ensureUserDataLayout(workspaceDir); const path = profile ? getUserDataAccountGameplayConfigFile(workspaceDir, profile) : getUserDataGameplayConfigFile(workspaceDir); if (!existsSync(path)) return writeGameplayConfig(defaultGameplayConfig(), workspaceDir, profile); try { const raw = JSON.parse(readFileSync(path, 'utf8')); const root = record(raw); if (!root) throw new Error('user-data/gameplay.json must contain a JSON object.'); if (hasLegacyFields(root)) { return writeGameplayConfig(migrateLegacyGameplayConfig(root), workspaceDir, profile); } return parseGameplayConfig(root); } catch (error) { if (error instanceof SyntaxError) { throw new Error(`Invalid JSON in ${path}: ${error.message}`); } throw error; } } export function updateGameplayConfig( update: (config: GameplayConfig) => void, workspaceDir = getWorkspaceDir(), profile?: Pick, ): GameplayConfig { const config = readGameplayConfig(workspaceDir, profile); update(config); return writeGameplayConfig(config, workspaceDir, profile); }