import { accountRequiredMessage } from '../lib/desktop-mode.js'; import { runOwnerCommand } from './module-runtime-control.js'; import { Command, InvalidArgumentError, Option } from 'commander'; import { AuthStore, type AuthProfile } from '../lib/auth.js'; import { CLAWCLAW_ROLE_IDS, NPM_ROLE_FALLBACK_BEHAVIORS, readGameplayConfig, updateGameplayConfig, type ClawclawRoleId, } from '../lib/gameplay-config.js'; import { getWorkspaceDir } from '../lib/init-command.js'; import { ensureAccountUserDataLayout, getUserDataAccountBehaviorsDir, getUserDataAccountGameplayConfigFile, } from '../lib/user-data.js'; import { BEHAVIOR_PLUGIN_API_VERSION, type BehaviorActivationLayer } from '../sdk/behavior-plugin/index.js'; import { behaviorSourceCompatibilityError, } from '../runtime/clawclaw/plugins/behavior/behavior-source.js'; import { readLocalAgentWorkspaceSnapshot } from '../lib/agent-workspace-sync.js'; import { filterInactiveAgentWorkspaceSnapshot } from '../lib/capability-cloud-presence.js'; import { listAgentWorkspaceBehaviorSources, mergeAgentWorkspaceBehaviorSources, type ManagedClawclawBehaviorSource, } from '../lib/agent-workspace-runtime.js'; import { sendProfileOwnerControlRequest, type OwnerControlResponse, type OwnerControlType, } from '../runtime/owner-control.js'; import { ShortCommandRunner, type CommandIo, type ShortCommandOperationResult, } from '../short-command/runner.js'; import { discoverLocalCapabilities } from '../lib/capability-discovery.js'; import { capabilityEntryForPath, classifyStrategyLifecycle, readCapabilityWorkspaceRegistry, } from '../lib/capability-workspace.js'; import { strategyActivationError, strategyActivationMode } from '../runtime/clawclaw/behavior-trigger.js'; import { readFileSync } from 'node:fs'; import { selectCapability } from '../lib/capability-selection.js'; import { renameCapabilityOperationWhenIdle } from '../lib/capability-operation-rename.js'; const OWNER_CONTROL_TIMEOUT_MS = 30_000; const MAX_BEHAVIOR_RUNTIME_MS = 120_000; const OWNER_RUNTIME_GUIDANCE = 'Run `ccl prepare` first. If participation exists, attach its foreground runtime with `ccl join`; only when participation.status is `idle` and the user wants a new match, run `ccl start match`.'; export interface BehaviorCommandDependencies { activeProfile?: () => AuthProfile | null; sendOwnerControlRequest?: typeof sendProfileOwnerControlRequest; io?: CommandIo; } const processIo: CommandIo = { writeStdout: (text) => { process.stdout.write(text); }, setExitCode: (code) => { process.exitCode = code; }, }; function parseJsonObject(value: string, field = 'input'): 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 parseRuntimeMs(value: string): number { const parsed = Number(value); if (!Number.isSafeInteger(parsed) || parsed < 1 || parsed > MAX_BEHAVIOR_RUNTIME_MS) { throw new InvalidArgumentError( `must be an integer from 1 to ${MAX_BEHAVIOR_RUNTIME_MS} milliseconds`, ); } return parsed; } function parseIdleMs(value: string): number { const parsed = Number(value); if (!Number.isSafeInteger(parsed) || parsed < 0 || parsed > 60_000) { throw new InvalidArgumentError('must be an integer from 0 to 60000 milliseconds'); } return parsed; } function parseRole(value: string): ClawclawRoleId { if (!(CLAWCLAW_ROLE_IDS as readonly string[]).includes(value)) { throw new InvalidArgumentError(`must be one of: ${CLAWCLAW_ROLE_IDS.join(', ')}`); } return value as ClawclawRoleId; } function sourceEntry( source: ManagedClawclawBehaviorSource, disabled: ReadonlySet, ): Record { const compatibilityError = behaviorSourceCompatibilityError(source); const versionCompatible = source.apiVersion === BEHAVIOR_PLUGIN_API_VERSION; const loadable = versionCompatible && compatibilityError === undefined; return { id: source.id, declared_id: source.declaredId ?? source.id, working_copy_path: source.workingCopyPath ?? source.sourcePath, runtime_source_path: source.sourcePath, name: source.name, description: source.description, api_version: source.apiVersion ?? null, expected_api_version: BEHAVIOR_PLUGIN_API_VERSION, loadable, ...(loadable ? {} : { compatibility_error: versionCompatible ? compatibilityError : `behavior_api_version_unsupported:expected=${BEHAVIOR_PLUGIN_API_VERSION}:received=${source.apiVersion ?? 'missing'}`, }), execution: source.execution, every_ticks: source.everyTicks, state_mode: source.stateMode ?? 'isolated', inputs: source.inputs, produces: source.produces ?? [], ...(source.runtime === undefined ? {} : { runtime: source.runtime }), activation_mode: strategyActivationMode(source), ...(source.triggerError ? { reflex: { available: false, reason: source.triggerError } } : {}), strategy_type: classifyStrategyLifecycle(readFileSync(source.sourcePath, 'utf8')), source: source.management.source, managed_by: source.management.managedBy, ...(source.management.publisher ? { publisher: source.management.publisher } : {}), ...(source.management.resourceId ? { resource_id: source.management.resourceId } : {}), ...(source.management.forkedFromResourceId ? { forked_from_resource_id: source.management.forkedFromResourceId } : {}), ...(source.management.versionId ? { version_id: source.management.versionId } : {}), ...(source.management.versionNumber ? { version_number: source.management.versionNumber, version_description: source.management.versionDescription ?? '' } : {}), ...(source.management.resolution ? { resolution: source.management.resolution } : {}), ...(source.management.ownerId ? { owner: { id: source.management.ownerId, name: source.management.ownerName ?? null, }, } : {}), disabled: source.management.source === 'local' && disabled.has(source.id), }; } async function tryApplyRuntimeConfig( type: 'behavior_fallback' | 'behavior_idle', payload: Readonly>, dependencies: BehaviorCommandDependencies, ): 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, type, { expected_scope: snapshot.scope, ...payload, }, 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), }; } } function activeProfile(dependencies: BehaviorCommandDependencies): AuthProfile { const profile = (dependencies.activeProfile ?? (() => new AuthStore().getActive()))(); if (!profile) throw new Error(accountRequiredMessage('No active account. Run `ccl account register` or switch accounts first.')); return profile; } function discoveredSources(profile: Pick) { const workspaceDir = getWorkspaceDir(); ensureAccountUserDataLayout(workspaceDir, profile); const localCapabilities = discoverLocalCapabilities(workspaceDir, profile).behaviors; const local = localCapabilities.map(({ source }) => source); const snapshot = filterInactiveAgentWorkspaceSnapshot( workspaceDir, profile, readLocalAgentWorkspaceSnapshot(workspaceDir, profile), ); const hub = snapshot ? listAgentWorkspaceBehaviorSources(workspaceDir, profile, snapshot) : []; const selectedLocal = localCapabilities.filter(({ entry }) => entry.selection === 'equipped' && !snapshot?.items.strategy.some(item => item.resourceId === entry.hub?.resourceId)).map(({ source }) => source); return { local, selectedLocal, hub }; } function sources( profile: Pick, disabledLocalIds: ReadonlySet = new Set(), ): readonly ManagedClawclawBehaviorSource[] { const { selectedLocal: local, hub } = discoveredSources(profile); return mergeAgentWorkspaceBehaviorSources( local.filter(({ id }) => !disabledLocalIds.has(id)), hub, ); } function inventorySources( profile: Pick, disabledLocalIds: ReadonlySet, ): readonly ManagedClawclawBehaviorSource[] { const { local, selectedLocal, hub } = discoveredSources(profile); const effective = mergeAgentWorkspaceBehaviorSources( selectedLocal.filter(({ id }) => !disabledLocalIds.has(id)), hub, ); const effectiveIds = new Set(effective.map(({ id }) => id)); const disabledOnly = mergeAgentWorkspaceBehaviorSources( local.filter((source) => ( !effectiveIds.has(source.id) && ( disabledLocalIds.has(source.id) || capabilityEntryForPath( getWorkspaceDir(), profile, 'behavior', source.sourcePath, )?.selection !== 'equipped' ) )), [], ); return [...effective, ...disabledOnly]; } export function createBehaviorCommand(dependencies: BehaviorCommandDependencies = {}): Command { return createStrategyControlCommand('behavior', dependencies); } export function createStrategyCommand(dependencies: BehaviorCommandDependencies = {}): Command { return createStrategyControlCommand('strategy', dependencies); } function createStrategyControlCommand(commandName: 'behavior' | 'strategy', dependencies: BehaviorCommandDependencies): Command { const behavior = new Command(commandName) .description('Discover, configure, and run long or short Behaviors') .addHelpText('after', () => { const workspaceDir = getWorkspaceDir(); const profile = (dependencies.activeProfile ?? (() => new AuthStore().getActive()))(); const directory = profile ? getUserDataAccountBehaviorsDir(workspaceDir, profile) : '/capabilities/behaviors'; return `\n${commandName === 'strategy' ? 'Strategy' : 'Behavior'} modules:\n Place .ts or .js files in ${directory}\n Discovery reads static manifests without executing module code.\n`; }); behavior.addCommand(new Command('rename') .description('Rename one equipped Behavior operation for the active account') .argument('', 'Current CCL operation name') .argument('', 'New account-local operation name') .allowExcessArguments(false) .action(async (currentId: string, newId: string) => { console.log(JSON.stringify(await renameCapabilityOperationWhenIdle( getWorkspaceDir(), activeProfile(dependencies), 'behavior', currentId, newId, ), null, 2)); })); behavior.addCommand(new Command('list') .description('List statically discovered Behavior modules') .action(async () => { const workspaceDir = getWorkspaceDir(); const profile = activeProfile(dependencies); const gameplay = readGameplayConfig(workspaceDir, profile); const disabled = new Set(gameplay.disabled_behaviors); for (const source of discoveredSources(profile).local) { if (capabilityEntryForPath( workspaceDir, profile, 'behavior', source.sourcePath, )?.selection !== 'equipped') disabled.add(source.id); } const discovered = inventorySources(profile, disabled); const entries = discovered.map((source) => sourceEntry(source, disabled)); console.log(JSON.stringify({ behaviors: entries, ignored_disabled_ids: gameplay.disabled_behaviors .filter((id) => !discovered.some((source) => source.id === id)), }, null, 2)); })); behavior.addCommand(new Command('info') .description('Show one statically discovered Behavior manifest') .argument('', 'Behavior id') .allowExcessArguments(false) .action(async (id: string) => { const workspaceDir = getWorkspaceDir(); const profile = activeProfile(dependencies); const gameplay = readGameplayConfig(workspaceDir, profile); const disabled = new Set(gameplay.disabled_behaviors); for (const source of discoveredSources(profile).local) { if (capabilityEntryForPath( workspaceDir, profile, 'behavior', source.sourcePath, )?.selection !== 'equipped') disabled.add(source.id); } const source = inventorySources(profile, disabled).find((candidate) => candidate.id === id); if (!source) throw new Error(`Unknown behavior module '${id}'.`); console.log(JSON.stringify({ ...sourceEntry(source, disabled), fallback_for_roles: CLAWCLAW_ROLE_IDS .filter((role) => gameplay.fallback_behaviors[role] === id), }, null, 2)); })); for (const disabled of [true, false] as const) { const verb = disabled ? 'disable' : 'enable'; behavior.addCommand(new Command(verb) .description(`${disabled ? 'Disable' : 'Enable'} a Behavior on the next Runtime`) .argument('', 'Behavior id') .allowExcessArguments(false) .action(async (id: string) => { const workspaceDir = getWorkspaceDir(); const profile = activeProfile(dependencies); const gameplay = readGameplayConfig(workspaceDir, profile); const local = discoveredSources(profile).local.find((source) => source.id === id); const effective = sources(profile, new Set(gameplay.disabled_behaviors)) .find((source) => source.id === id); const registered = Object.values(readCapabilityWorkspaceRegistry(workspaceDir, profile).entries) .some(entry => entry.type === 'behavior' && entry.runtimeId === id); if (!disabled && !local && !effective && !registered) { throw new Error(`Unknown behavior module '${id}'.`); } if (disabled) { const fallbackRoles = CLAWCLAW_ROLE_IDS .filter((role) => gameplay.fallback_behaviors[role] === id); const selectedHubReplacement = discoveredSources(profile).hub.some((source) => source.id === id); if (fallbackRoles.length > 0 && !selectedHubReplacement) { throw new Error( `Cannot disable fallback Behavior '${id}' for role(s): ${fallbackRoles.join(', ')}.`, ); } } await selectCapability(workspaceDir, profile, 'behavior', id, !disabled); const updated = readGameplayConfig(workspaceDir, profile); console.log(JSON.stringify({ behavior: id, disabled, effective: 'next_runtime', config_file: getUserDataAccountGameplayConfigFile(workspaceDir, profile), disabled_behaviors: updated.disabled_behaviors, }, null, 2)); })); } behavior.addCommand(new Command('start') .description('Start one Behavior as long-running or bounded foreground work') .argument('', 'Behavior id') .addOption(new Option('--layer ', 'Activation layer').choices(['long', 'short']).makeOptionMandatory()) .option('--input ', 'Behavior input JSON object', (value) => parseJsonObject(value), {}) .option('--max-runtime-ms ', 'Maximum runtime for this activation', parseRuntimeMs) .allowExcessArguments(false) .action(async (id: string, opts: { layer: Exclude; input: Record; maxRuntimeMs?: number; }) => { const workspaceDir = getWorkspaceDir(); const profile = activeProfile(dependencies); const gameplay = readGameplayConfig(workspaceDir, profile); const source = sources(profile, new Set(gameplay.disabled_behaviors)) .find((candidate) => candidate.id === id); if (!source) throw new Error(`Unknown behavior module '${id}'.`); const hub = source.management.source === 'hub'; const entry = sourceEntry(source, new Set(hub ? [] : gameplay.disabled_behaviors)); if (entry.loadable !== true) { throw new Error(`Behavior '${id}' is not loadable: ${String(entry.compatibility_error)}`); } if (!hub && gameplay.disabled_behaviors.includes(id)) { throw new Error(`Behavior '${id}' is disabled in user-data/gameplay.json.`); } const error = strategyActivationError(source); if (error) throw new Error(`${id}: ${error}. 该策略仅自动触发,由同文件的感知请求启动。`); await runOwnerCommand(`ccl ${commandName} start`, 'behavior_start', { behavior: id, layer: opts.layer, input: opts.input, ...(opts.maxRuntimeMs === undefined ? {} : { max_runtime_ms: opts.maxRuntimeMs }), }, true, dependencies); })); behavior.addCommand(new Command('status') .description('Show execution stack and background watches, optionally for one Behavior') .argument('[id]', 'Optional Behavior operation name') .allowExcessArguments(false) .action(async (id?: string) => { await runOwnerCommand(`ccl ${commandName} status`, 'behavior_status', id ? { behavior: id } : {}, false, dependencies); })); behavior.addCommand(new Command('cancel') .description('Cancel one activation, or the current activation when omitted') .argument('[activation-id]', 'Activation id') .allowExcessArguments(false) .action(async (activationId?: string) => { await runOwnerCommand(`ccl ${commandName} cancel`, 'behavior_cancel', { ...(activationId === undefined ? {} : { activation_id: activationId }), }, true, dependencies); })); behavior.addCommand(new Command('idle') .description('Persist the shared delay before long/fallback Behavior control') .argument('', 'Idle/resume delay in milliseconds', parseIdleMs) .allowExcessArguments(false) .action(async (idleMs: number) => { const workspaceDir = getWorkspaceDir(); const profile = activeProfile(dependencies); const updated = updateGameplayConfig((current) => { current.idle_ms = idleMs; }, workspaceDir, profile); const runtime = await tryApplyRuntimeConfig('behavior_idle', { idle_ms: idleMs }, dependencies); console.log(JSON.stringify({ idle_ms: updated.idle_ms, config_file: getUserDataAccountGameplayConfigFile(workspaceDir, profile), runtime, }, null, 2)); })); const fallback = new Command('fallback') .description('Configure the role-specific idle fallback Behavior'); const setFallback = async ( id: string, role: ClawclawRoleId, mode: 'custom' | 'default', ) => { const workspaceDir = getWorkspaceDir(); const profile = activeProfile(dependencies); const gameplay = readGameplayConfig(workspaceDir, profile); const discovered = sources(profile, new Set(gameplay.disabled_behaviors)); const source = discovered.find((candidate) => candidate.id === id); if (!source) throw new Error(`Unknown behavior module '${id}'.`); const hub = source.management.source === 'hub'; const entry = sourceEntry(source, new Set(hub ? [] : gameplay.disabled_behaviors)); if (entry.loadable !== true || (!hub && gameplay.disabled_behaviors.includes(id))) { throw new Error(`Behavior '${id}' is not enabled and loadable.`); } const error = strategyActivationError(source); if (error) throw new Error(`${id}: ${error}. 该策略仅自动触发,请选择普通策略作为角色默认策略。`); const updated = updateGameplayConfig((current) => { current.fallback_behaviors[role] = id; }, workspaceDir, profile); const runtime = await tryApplyRuntimeConfig('behavior_fallback', { action: 'set', behavior: id, input: {}, role, }, dependencies); console.log(JSON.stringify({ role, fallback_mode: mode, fallback_behavior: updated.fallback_behaviors[role], config_file: getUserDataAccountGameplayConfigFile(workspaceDir, profile), runtime, }, null, 2)); }; const removeFallback = async ( role: ClawclawRoleId, mode: 'none' | 'default', ) => { const workspaceDir = getWorkspaceDir(); const profile = activeProfile(dependencies); const updated = updateGameplayConfig((current) => { current.fallback_behaviors[role] = null; }, workspaceDir, profile); const runtime = await tryApplyRuntimeConfig('behavior_fallback', { action: 'clear', role, }, dependencies); console.log(JSON.stringify({ role, fallback_mode: mode, fallback_behavior: updated.fallback_behaviors[role], config_file: getUserDataAccountGameplayConfigFile(workspaceDir, profile), runtime, }, null, 2)); }; fallback.addCommand(new Command('set') .description('Set a role fallback Behavior') .argument('', 'Behavior id') .requiredOption('--role ', 'Role binding', parseRole) .allowExcessArguments(false) .action((id: string, opts: { role: ClawclawRoleId }) => ( setFallback(id, opts.role, 'custom') ))); fallback.addCommand(new Command('default') .description('Restore the current default fallback Behavior for a role') .requiredOption('--role ', 'Role binding', parseRole) .allowExcessArguments(false) .action((opts: { role: ClawclawRoleId }) => { const defaultBehavior = NPM_ROLE_FALLBACK_BEHAVIORS[opts.role]; return defaultBehavior === null ? removeFallback(opts.role, 'default') : setFallback(defaultBehavior, opts.role, 'default'); })); fallback.addCommand(new Command('none') .description('Use no fallback Behavior for a role') .requiredOption('--role ', 'Role binding', parseRole) .allowExcessArguments(false) .action((opts: { role: ClawclawRoleId }) => removeFallback(opts.role, 'none'))); behavior.addCommand(fallback); behavior.addCommand(new Command('watch') .description('Enable automatic reflection for this strategy in the current game') .argument('', 'Equipped Behavior operation name') .option('--input ', 'Optional match-local strategy parameter patch', value => parseJsonObject(value), {}) .allowExcessArguments(false).action(async (id: string, opts: { input: Record }) => { await runOwnerCommand(`ccl ${commandName} watch`, 'behavior_watch', { behavior: id, input: opts.input }, true, dependencies); })); behavior.addCommand(new Command('unwatch') .description('Block automatic activation and cancel the associated Reflex') .argument('', 'Equipped Behavior operation name') .allowExcessArguments(false).action(async (id: string) => { await runOwnerCommand(`ccl ${commandName} unwatch`, 'behavior_unwatch', { behavior: id }, true, dependencies); })); behavior.addCommand(new Command('update') .description('Patch this Behavior\'s match-local parameters and current executions; keep its watch switch') .argument('', 'Behavior operation name; with --activation, one activation ID') .option('--activation', 'Update only the specified execution, without changing shared parameters') .requiredOption('--input ', 'Parameter patch JSON object', value => parseJsonObject(value)) .allowExcessArguments(false).action(async (id: string, opts: { activation?: boolean; input: Record }) => { await runOwnerCommand(`ccl ${commandName} update`, 'behavior_update', opts.activation ? { activation_id: id, input: opts.input } : { behavior: id, input: opts.input }, true, dependencies); })); if (commandName === 'behavior') behavior.alias('beh'); if (commandName === 'strategy') { const present = (value: string) => value.replace(/Behaviors/g, 'Strategies').replace(/Behavior/g, 'Strategy'); const visit = (command: Command): void => { command.description(present(command.description())); for (const argument of command.registeredArguments) argument.description = present(argument.description); for (const option of command.options) option.description = present(option.description); for (const child of command.commands) visit(child); }; visit(behavior); } return behavior; }