import { Command, InvalidArgumentError, Option } from 'commander'; import { AuthStore, type AuthProfile } from '../lib/auth.js'; import { readGameplayConfig, updateGameplayConfig } from '../lib/gameplay-config.js'; import { getWorkspaceDir } from '../lib/init-command.js'; import { toTriggerRegistrationOverrides, type GameplayTriggerConfig, type GameplayTriggerRearm, } from '../lib/trigger-config.js'; import { ensureAccountUserDataLayout, getUserDataAccountGameplayConfigFile, getUserDataAccountTriggersDir, } from '../lib/user-data.js'; import { TRIGGER_PLUGIN_API_VERSION, MAX_TRIGGER_RUNTIME_MS } from '../sdk/trigger-plugin/index.js'; import { BEHAVIOR_PLUGIN_API_VERSION } from '../sdk/behavior-plugin/index.js'; import { behaviorSourceCompatibilityError, } from '../runtime/clawclaw/plugins/behavior/behavior-source.js'; import { discoverLocalCapabilities } from '../lib/capability-discovery.js'; import { listClawclawTriggerSources } from '../runtime/clawclaw/plugins/trigger/trigger-source.js'; import { readLocalAgentWorkspaceSnapshot } from '../lib/agent-workspace-sync.js'; import { listAgentWorkspaceBehaviorSources, mergeAgentWorkspaceBehaviorSources, } from '../lib/agent-workspace-runtime.js'; import { normalizeBehaviorInput } from '../runtime/clawclaw/behavior-input-fields.js'; import { sendProfileOwnerControlRequest } from '../runtime/owner-control.js'; const OWNER_CONTROL_TIMEOUT_MS = 30_000; export interface TriggerCommandDependencies { activeProfile?: () => AuthProfile | null; sendOwnerControlRequest?: typeof sendProfileOwnerControlRequest; } function parseJsonObject(value: string, field: string): Record { let parsed: unknown; try { parsed = JSON.parse(value); } catch (error) { throw new InvalidArgumentError( `${field} must be a JSON object: ${error instanceof Error ? error.message : String(error)}`, ); } if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { throw new InvalidArgumentError(`${field} must be a JSON object`); } return parsed as Record; } function parseSafeInteger(value: string, field: string, minimum: number, maximum?: number): number { const parsed = Number(value); if ( !Number.isSafeInteger(parsed) || parsed < minimum || (maximum !== undefined && parsed > maximum) ) { throw new InvalidArgumentError( `${field} must be a safe integer from ${minimum}${maximum === undefined ? '' : ` to ${maximum}`}`, ); } return parsed; } function activeProfile(dependencies: TriggerCommandDependencies): AuthProfile { const profile = (dependencies.activeProfile ?? (() => new AuthStore().getActive()))(); if (!profile) throw new Error('No active account. Run `ccl account register` or switch accounts first.'); return profile; } function triggerSources(workspaceDir: string, profile: Pick) { ensureAccountUserDataLayout(workspaceDir, profile); return listClawclawTriggerSources(getUserDataAccountTriggersDir(workspaceDir, profile)); } function persistedOverride(id: string, config: GameplayTriggerConfig | undefined) { if (config === undefined) return undefined; return toTriggerRegistrationOverrides({ [id]: config })[0]; } function triggerEntry( source: ReturnType[number], config: GameplayTriggerConfig | undefined, disabled = false, ): Record { const override = persistedOverride(source.id, config); const versionCompatible = source.apiVersion === TRIGGER_PLUGIN_API_VERSION; const input = normalizeBehaviorInput(override?.input ?? {}, source.manifest.inputs); const behaviorInput = { ...structuredClone(source.manifest.defaultBehaviorInput), ...structuredClone(override?.behaviorInput ?? {}), }; return { id: source.id, name: source.name, description: source.description, api_version: source.apiVersion, expected_api_version: TRIGGER_PLUGIN_API_VERSION, loadable: versionCompatible, ...(versionCompatible ? {} : { compatibility_error: `trigger_api_version_unsupported:expected=${TRIGGER_PLUGIN_API_VERSION}:received=${source.apiVersion}`, }), inputs: source.manifest.inputs, consumes: source.manifest.consumes, defaults: { behavior: source.manifest.defaultBehavior, behavior_input: source.manifest.defaultBehaviorInput, reflex_priority: source.manifest.defaultReflexPriority, cooldown_ms: source.manifest.defaultCooldownMs, rearm: source.manifest.defaultRearm, max_runtime_ms: source.manifest.defaultMaxRuntimeMs, }, configured: config ?? {}, effective: { enabled: !disabled, input, behavior: override?.behavior ?? source.manifest.defaultBehavior, behavior_input: behaviorInput, reflex_priority: override?.reflexPriority ?? source.manifest.defaultReflexPriority, cooldown_ms: override?.cooldownMs ?? source.manifest.defaultCooldownMs, rearm: override?.rearm ?? source.manifest.defaultRearm, max_runtime_ms: override?.maxRuntimeMs ?? source.manifest.defaultMaxRuntimeMs, }, source: 'local', }; } function assertBehaviorBinding( id: string, workspaceDir: string, profile: Pick, ): void { const gameplay = readGameplayConfig(workspaceDir, profile); const discovered = discoverLocalCapabilities(workspaceDir, profile).behaviors; const local = discovered.map(({ source }) => source); const selectedLocal = discovered .filter(({ entry }) => entry.selection === 'equipped') .map(({ source }) => source); const snapshot = readLocalAgentWorkspaceSnapshot(workspaceDir, profile); const hub = snapshot ? listAgentWorkspaceBehaviorSources(workspaceDir, profile, snapshot) : []; const source = mergeAgentWorkspaceBehaviorSources( selectedLocal.filter((candidate) => !gameplay.disabled_behaviors.includes(candidate.id)), hub, ) .find((candidate) => candidate.id === id); if (!source) { if (local.some((candidate) => candidate.id === id) && gameplay.disabled_behaviors.includes(id)) { throw new Error(`Behavior '${id}' is disabled in user-data/gameplay.json.`); } throw new Error(`Unknown behavior module '${id}'.`); } if ( source.apiVersion !== BEHAVIOR_PLUGIN_API_VERSION || behaviorSourceCompatibilityError(source) !== undefined ) { throw new Error(`Behavior '${id}' is not loadable.`); } } async function tryApplyRuntimeConfig( id: string, config: GameplayTriggerConfig, dependencies: TriggerCommandDependencies, ): Promise> { const profile = (dependencies.activeProfile ?? (() => new AuthStore().getActive()))(); if (!profile) return { applied: false, reason: 'no_active_account' }; const send = dependencies.sendOwnerControlRequest ?? sendProfileOwnerControlRequest; try { const snapshot = await send(profile, 'snapshot'); if (!snapshot?.ok || snapshot.scope === undefined) { return { applied: false, reason: 'no_game_start_owner' }; } const response = await send(profile, 'trigger_configure', { expected_scope: snapshot.scope, trigger: id, config, }, OWNER_CONTROL_TIMEOUT_MS); return response?.ok ? { applied: true } : { applied: false, reason: response?.error ?? 'owner_rejected' }; } catch (error) { return { applied: false, reason: 'owner_unavailable', message: error instanceof Error ? error.message : String(error), }; } } async function updateTrigger( id: string, update: (config: GameplayTriggerConfig, disabled: Set) => void, dependencies: TriggerCommandDependencies, ): Promise { const workspaceDir = getWorkspaceDir(); const profile = activeProfile(dependencies); const source = triggerSources(workspaceDir, profile).find((candidate) => candidate.id === id); if (!source) throw new Error(`Unknown or ambiguous trigger module '${id}'.`); const before = readGameplayConfig(workspaceDir, profile); const nextConfig = { ...(before.triggers[id] ?? {}) }; const nextDisabled = new Set(before.disabled_triggers); update(nextConfig, nextDisabled); const effectiveBehavior = nextConfig.behavior ?? source.manifest.defaultBehavior; if (!nextDisabled.has(id)) assertBehaviorBinding(effectiveBehavior, workspaceDir, profile); const updated = updateGameplayConfig((gameplay) => { gameplay.triggers[id] = nextConfig; gameplay.disabled_triggers = [...nextDisabled].sort(); }, workspaceDir, profile); const config = updated.triggers[id]!; const runtime = await tryApplyRuntimeConfig(id, config, dependencies); console.log(JSON.stringify({ trigger: id, config, effective: triggerEntry(source, config, updated.disabled_triggers.includes(id)).effective, config_file: getUserDataAccountGameplayConfigFile(workspaceDir, profile), runtime, }, null, 2)); } export function createTriggerCommand(dependencies: TriggerCommandDependencies = {}): Command { const trigger = new Command('trigger') .alias('trg') .description('Configure legacy standalone Reflex triggers; new automatic reflexes use paired Perception and Behavior resources.') .addHelpText('after', () => { const workspaceDir = getWorkspaceDir(); const profile = (dependencies.activeProfile ?? (() => new AuthStore().getActive()))(); const directory = profile ? getUserDataAccountTriggersDir(workspaceDir, profile) : '/capabilities/triggers'; return `\nTrigger modules:\n Place .ts or .js files in ${directory}\n Local Triggers are available by default unless listed in disabled_triggers; discovery never executes module code.\n`; }); trigger.addCommand(new Command('list') .description('List statically discovered Trigger modules') .action(async () => { const workspaceDir = getWorkspaceDir(); const profile = activeProfile(dependencies); const gameplay = readGameplayConfig(workspaceDir, profile); const sources = triggerSources(workspaceDir, profile); console.log(JSON.stringify({ triggers: sources.map((source) => triggerEntry( source, gameplay.triggers[source.id], gameplay.disabled_triggers.includes(source.id), )), ignored_config_ids: Object.keys(gameplay.triggers) .filter((id) => !sources.some((source) => source.id === id)), }, null, 2)); })); trigger.addCommand(new Command('info') .description('Show one statically discovered Trigger manifest and effective configuration') .argument('', 'Trigger id') .allowExcessArguments(false) .action(async (id: string) => { const workspaceDir = getWorkspaceDir(); const profile = activeProfile(dependencies); const gameplay = readGameplayConfig(workspaceDir, profile); const source = triggerSources(workspaceDir, profile).find((candidate) => candidate.id === id); if (!source) throw new Error(`Unknown or ambiguous trigger module '${id}'.`); console.log(JSON.stringify(triggerEntry( source, gameplay.triggers[id], gameplay.disabled_triggers.includes(id), ), null, 2)); })); trigger.addCommand(new Command('enable') .description('Enable one Trigger and apply it to an attached Runtime') .argument('', 'Trigger id') .allowExcessArguments(false) .action(async (id: string) => { const workspaceDir = getWorkspaceDir(); const profile = activeProfile(dependencies); const source = triggerSources(workspaceDir, profile).find((candidate) => candidate.id === id); if (!source) throw new Error(`Unknown or ambiguous trigger module '${id}'.`); const gameplay = readGameplayConfig(workspaceDir, profile); assertBehaviorBinding( gameplay.triggers[id]?.behavior ?? source.manifest.defaultBehavior, workspaceDir, profile, ); await updateTrigger(id, (_config, disabled) => { disabled.delete(id); }, dependencies); })); trigger.addCommand(new Command('disable') .description('Disable one Trigger and apply it to an attached Runtime') .argument('', 'Trigger id') .allowExcessArguments(false) .action(async (id: string) => { await updateTrigger(id, (_config, disabled) => { disabled.add(id); }, dependencies); })); trigger.addCommand(new Command('configure') .description('Persist Trigger rule, binding, priority, cooldown, rearm, or runtime settings') .argument('', 'Trigger id') .option('--input ', 'Trigger rule input JSON object', (value) => parseJsonObject(value, 'input')) .option('--behavior ', 'Fixed Reflex Behavior id') .option('--behavior-input ', 'Fixed Behavior input JSON object', (value) => parseJsonObject(value, 'behavior-input')) .option('--reflex-priority ', 'Priority relative to other Reflexes', (value) => ( parseSafeInteger(value, 'reflex-priority', Number.MIN_SAFE_INTEGER) )) .option('--cooldown-ms ', 'Cooldown in milliseconds', (value) => ( parseSafeInteger(value, 'cooldown-ms', 0) )) .addOption(new Option('--rearm ', 'Rearm policy').choices(['after_clear', 'after_cooldown'])) .option('--max-runtime-ms ', 'Maximum Reflex runtime', (value) => ( parseSafeInteger(value, 'max-runtime-ms', 1, MAX_TRIGGER_RUNTIME_MS) )) .option('--reset', 'Clear all Trigger overrides without changing disabled_triggers') .allowExcessArguments(false) .action(async (id: string, opts: { input?: Record; behavior?: string; behaviorInput?: Record; reflexPriority?: number; cooldownMs?: number; rearm?: GameplayTriggerRearm; maxRuntimeMs?: number; reset?: boolean; }) => { const values = [ opts.input, opts.behavior, opts.behaviorInput, opts.reflexPriority, opts.cooldownMs, opts.rearm, opts.maxRuntimeMs, ]; if (!opts.reset && values.every((value) => value === undefined)) { throw new Error('Provide at least one Trigger override or --reset.'); } if (opts.reset && values.some((value) => value !== undefined)) { throw new Error('--reset cannot be combined with Trigger overrides.'); } if (opts.behavior !== undefined) { assertBehaviorBinding(opts.behavior, getWorkspaceDir(), activeProfile(dependencies)); } await updateTrigger(id, (config) => { if (opts.reset) { for (const key of Object.keys(config) as (keyof GameplayTriggerConfig)[]) { delete config[key]; } return; } if (opts.input !== undefined) config.input = opts.input; if (opts.behavior !== undefined) config.behavior = opts.behavior; if (opts.behaviorInput !== undefined) config.behavior_input = opts.behaviorInput; if (opts.reflexPriority !== undefined) config.reflex_priority = opts.reflexPriority; if (opts.cooldownMs !== undefined) config.cooldown_ms = opts.cooldownMs; if (opts.rearm !== undefined) config.rearm = opts.rearm; if (opts.maxRuntimeMs !== undefined) config.max_runtime_ms = opts.maxRuntimeMs; }, dependencies); })); return trigger; }