import { Command, Option } from 'commander'; import { readFileSync } from 'fs'; import { basename } from 'path'; import { AuthStore } from '../lib/auth.js'; import { DESKTOP_LOGIN_MESSAGE, isDesktopMode } from '../lib/desktop-mode.js'; import type { AuthProfile } from '../lib/auth.js'; import { GameClient } from '../lib/game-client.js'; import { createProfileDirs, cmdInit, getWorkspaceDir } from '../lib/init-command.js'; import { setMeta } from '../lib/command-meta.js'; import { hubReminder, readCachedGamesPlayed, writeGamesPlayedCache } from '../lib/hub-reminder.js'; import { missingInviteCodeMessage, noAccountMessage, OFFICIAL_URL, POST_REGISTRATION_NEXT_STEP, registrationCheckOutput, } from '../lib/account-guidance.js'; import { fetchServerStatus, resolveInviteRequired } from '../lib/server-status.js'; import { switchActiveAccountSkillLinks } from '../lib/agent-workspace-skills.js'; import { ResponseClassifier } from '../short-command/classifier.js'; import { createProcessCommandIo } from '../short-command/process-io.js'; import { booleanSuccessContract } from '../short-command/response-contract.js'; import type { ResponseContract } from '../short-command/response-contract.js'; import { ShortCommandRunner } from '../short-command/runner.js'; import type { CommandIo, ShortCommandOperationResult, } from '../short-command/runner.js'; import type { TransportResponse } from '../short-command/transport-response.js'; import type { PresentationOverrides } from '../short-command/types.js'; const DEFAULT_SERVER_URL = 'https://myclaw.163.com/claw'; const SERVER_URL_ENV = 'CLAWCLAW_SERVER_URL'; export function extractServerAccountName(payload: any): string | undefined { const data = payload?.data ?? payload; return data?.agent_name ?? data?.agentName ?? data?.name; } export function extractBackendAccountId(payload: any): string | undefined { const data = payload?.data ?? payload; const value = data?.id ?? data?.agent_id ?? data?.agentId; return typeof value === 'string' && value.trim() ? value.trim() : undefined; } function getRegisterServerUrl(env: NodeJS.ProcessEnv = process.env): string { const configured = env[SERVER_URL_ENV]?.trim(); return configured || DEFAULT_SERVER_URL; } function getSwitchServerUrl(authStore: AuthStore, env: NodeJS.ProcessEnv = process.env): string { return authStore.getActive()?.serverUrl ?? getRegisterServerUrl(env); } const classifyResponse = new ResponseClassifier(); const REGISTER_CONTRACT: ResponseContract = { id: 'clawclaw.account.register', rules: [ { outcome: 'failure', when: { path: ['success'], predicate: { operator: 'equals', value: false } }, }, { outcome: 'success', when: [ { path: ['success'], predicate: { operator: 'equals', value: true } }, { path: ['data', 'api_key'], predicate: { operator: 'truthy' } }, { path: ['data', 'agent_name'], predicate: { operator: 'truthy' } }, ], }, ], default2xxOutcome: 'protocol_failure', }; export const LOGIN_CONTRACT: ResponseContract = { id: 'clawclaw.account.login', rules: [ { outcome: 'failure', when: { path: ['success'], predicate: { operator: 'equals', value: false } }, }, { outcome: 'success', when: [ { path: ['success'], predicate: { operator: 'equals', value: true } }, { path: ['data', 'name'], predicate: { operator: 'truthy' } }, ], }, { outcome: 'success', when: [ { path: ['success'], predicate: { operator: 'equals', value: true } }, { path: ['data', 'agent_name'], predicate: { operator: 'truthy' } }, ], }, ], default2xxOutcome: 'protocol_failure', }; const RENAME_CONTRACT: ResponseContract = { id: 'clawclaw.account.rename', rules: [ { outcome: 'failure', when: { path: ['success'], predicate: { operator: 'equals', value: false } }, }, { outcome: 'success', when: [ { path: ['success'], predicate: { operator: 'equals', value: true } }, { path: ['data', 'name'], predicate: { operator: 'truthy' } }, ], }, ], default2xxOutcome: 'protocol_failure', }; const INFO_CONTRACT = booleanSuccessContract({ id: 'clawclaw.account.info' }); const SETTLEMENT_CONTRACT = booleanSuccessContract({ id: 'clawclaw.account.settlement' }); function transportFailure(error: unknown): ShortCommandOperationResult { return { kind: 'transport_failure', error: { code: 'REQUEST_FAILED', message: error instanceof Error ? error.message : String(error), }, }; } function backendResult( response: TransportResponse, contract: ResponseContract, presentation?: PresentationOverrides, ): ShortCommandOperationResult { return { kind: 'backend', response, contract, presentation }; } function successfulRoot( response: TransportResponse, contract: ResponseContract, ): Record | undefined { const classified = classifyResponse.classify(response, contract); return classified.kind === 'success' ? classified.upstreamRoot : undefined; } async function refreshGamesPlayedForReminder(client: GameClient): Promise { try { const response = await client.requestRaw('GET', '/api/v1/agents/me'); const root = successfulRoot(response, INFO_CONTRACT); const data = root?.data; if (data && typeof data === 'object' && !Array.isArray(data)) { const gamesPlayed = (data as Record).games_played; if (typeof gamesPlayed === 'number') { writeGamesPlayedCache(gamesPlayed); return gamesPlayed; } } } catch {} return readCachedGamesPlayed(); } function responseErrorCode(response: TransportResponse): string | undefined { if (response.body.kind !== 'json' || !response.body.value || typeof response.body.value !== 'object') { return undefined; } const root = response.body.value as Record; return root.error?.code ?? root.code; } function withoutTutorial(root: Readonly>): Record { const out = { ...root }; if (out.data && typeof out.data === 'object' && !Array.isArray(out.data)) { const data = { ...(out.data as Record) }; delete data.tutorial; out.data = data; } return out; } function buildRegistrationForm(opts: { name?: string; desc?: string; inviteCode?: string; avatarUrl?: string; avatarFile?: string; }): FormData { const form = new FormData(); if (opts.name) form.append('name', opts.name); if (opts.desc) form.append('description', opts.desc); if (opts.inviteCode) form.append('invite_code', opts.inviteCode); if (opts.avatarUrl) form.append('avatar_url', opts.avatarUrl); if (opts.avatarFile) { const bytes = readFileSync(opts.avatarFile); form.append('avatar_file', new Blob([bytes]), basename(opts.avatarFile)); } return form; } export interface CreateAccountCommandOptions { io?: CommandIo; switchSkillLinks?: typeof switchActiveAccountSkillLinks; } export function createAccountCommand(options: CreateAccountCommandOptions = {}): Command { const account = new Command('account'); const io = options.io ?? createProcessCommandIo(); const runner = new ShortCommandRunner(); account.description('Account management & game data'); // ─── Auth ─── account .command('register') .description('Register new agent') .option('-n, --name ', 'Agent name (max 16 chars); omit to let the server choose randomly') .addOption(new Option('-d, --desc ', 'Agent description (max 500 chars)').hideHelp()) .option('--invite-code ', 'Invite code (only required when this server gates registration)') .option('--check', 'Report whether this server gates registration, and the wording to ask with; never registers') .addOption(new Option('--avatar-url ', 'Avatar image URL').hideHelp()) .addOption(new Option('--avatar-file ', 'Avatar image file (jpeg/png/gif/webp, max 1MB)').hideHelp()) .action(async (opts: { name?: string; desc?: string; inviteCode?: string; check?: boolean; avatarUrl?: string; avatarFile?: string }) => { const inviteCode = opts.inviteCode?.trim() ?? ''; const checkOnly = opts.check === true; await runner.run({ descriptor: { command: checkOnly ? 'ccl account register --check' : 'ccl account register', service: 'clawclaw-lobby', operation: checkOnly ? 'check_registration_policy' : 'register_agent', sensitivePolicy: { sensitiveValues: inviteCode ? [inviteCode] : [], sensitiveFieldNames: ['spectate_url', 'spectateUrl'], }, }, io, operation: async () => { if (isDesktopMode()) { return { kind: 'local_failure', source: 'local', error: { code: 'DESKTOP_ACCOUNT_MANAGED', message: DESKTOP_LOGIN_MESSAGE } }; } const serverUrl = getRegisterServerUrl(); // `--check` exists so the Agent can pick the right question before it // asks anything. It must stay side-effect free: combining it with any // registration input would make "just checking" create an account. if (checkOnly) { const conflicting = ([ ['--name', opts.name], ['--desc', opts.desc], ['--invite-code', inviteCode], ['--avatar-url', opts.avatarUrl], ['--avatar-file', opts.avatarFile], ] as const) .filter(([, value]) => value !== undefined && value !== '') .map(([flag]) => flag); if (conflicting.length > 0) { return { kind: 'local_failure', source: 'local', error: { code: 'CHECK_FLAG_CONFLICT', message: [ `--check only reports the registration policy, so it cannot be combined with ${conflicting.join(', ')}.`, 'Next: run `ccl account register --check` on its own, then register with the flags the returned script calls for.', ].join('\n'), }, }; } const status = await fetchServerStatus({ lobbyUrl: serverUrl }); return { kind: 'local_success', source: 'local', value: registrationCheckOutput({ inviteRequired: resolveInviteRequired(status), source: status.source, }), }; } // Ask the server whether it gates registration. Only needed when the // caller supplied no code, so the normal path pays nothing. if (!inviteCode) { const status = await fetchServerStatus({ lobbyUrl: serverUrl }); if (resolveInviteRequired(status)) { return { kind: 'local_failure', source: 'local', error: { code: 'INVITE_CODE_REQUIRED', message: missingInviteCodeMessage() }, }; } } let form: FormData; try { form = buildRegistrationForm({ name: opts.name, desc: opts.desc, ...(inviteCode ? { inviteCode } : {}), avatarUrl: opts.avatarUrl, avatarFile: opts.avatarFile, }); } catch (error) { return { kind: 'local_failure', source: 'local', error: { code: 'REGISTRATION_INPUT_FAILED', message: error instanceof Error ? error.message : String(error), }, }; } const tmpClient = new GameClient({ lobbyUrl: serverUrl, apiKey: '' }); let response: TransportResponse; try { response = await tmpClient.requestRaw('POST', '/api/v1/agents/register', form); } catch (error) { return transportFailure(error); } const root = successfulRoot(response, REGISTER_CONTRACT); if (!root) return backendResult(response, REGISTER_CONTRACT); const data = root.data as Record; const apiKey = String(data.api_key); const agentName = String(data.agent_name); const profile: AuthProfile = { agentName, apiKey, serverUrl, backendAccountId: extractBackendAccountId(root), }; const workspace = cmdInit(); const authStore = new AuthStore(); const previousProfile = authStore.getActive(); authStore.addProfile(profile); try { createProfileDirs(profile); } catch {} try { (options.switchSkillLinks ?? switchActiveAccountSkillLinks)(getWorkspaceDir(), previousProfile, profile); } catch (error) { const previousKey = previousProfile && authStore.findProfileKeyByApiKey(previousProfile.apiKey); if (previousKey) authStore.switchProfile(previousKey); throw error; } return backendResult(response, REGISTER_CONTRACT, { enhanceSuccess: () => ({ message: `Registered and saved as profile "${agentName}"`, officialUrl: OFFICIAL_URL, }), effects: [ { name: 'workspace_init', status: 'success', data: { created: workspace.created } }, { name: 'account_profile_saved', status: 'success', data: { name: agentName } }, ], guidance: POST_REGISTRATION_NEXT_STEP, }); }, }); }); account .command('rename ') .description('Rename agent (not during a game)') .action(async (newName: string) => { const authStore = new AuthStore(); const profile = authStore.getActive(); await runner.run({ descriptor: { command: 'ccl account rename', service: 'clawclaw-lobby', operation: 'rename_agent', sensitivePolicy: { sensitiveValues: profile ? [profile.apiKey] : [], sensitiveFieldNames: ['spectate_url', 'spectateUrl'], }, }, io, operation: async () => { if (!profile) { return { kind: 'local_failure', source: 'local', error: { code: 'NO_ACTIVE_ACCOUNT', message: 'Not logged in.' }, }; } const client = GameClient.fromAuth({ authStore }); let response: TransportResponse; try { response = await client.requestRaw('PATCH', '/api/v1/agents/name', { name: newName }); } catch (error) { return transportFailure(error); } const root = successfulRoot(response, RENAME_CONTRACT); if (!root) return backendResult(response, RENAME_CONTRACT); const serverName = extractServerAccountName(root) ?? newName; const oldName = profile.agentName; authStore.addProfile({ ...profile, agentName: serverName }); return backendResult(response, RENAME_CONTRACT, { enhanceSuccess: () => ({ message: `Renamed "${oldName}" to "${serverName}"` }), effects: [{ name: 'account_profile_updated', status: 'success', data: { name: serverName } }], }); }, }); }); account .command('switch ') .description('Switch active profile by API key') .action(async (apiKey: string) => { const targetApiKey = apiKey.trim(); const authStore = new AuthStore(); await runner.run({ descriptor: { command: 'ccl account switch', service: 'clawclaw-lobby', operation: 'switch_account', sensitivePolicy: { sensitiveValues: targetApiKey ? [targetApiKey] : [], sensitiveFieldNames: ['spectate_url', 'spectateUrl'], }, }, io, operation: async () => { if (isDesktopMode()) { return { kind: 'local_failure', source: 'local', error: { code: 'DESKTOP_ACCOUNT_MANAGED', message: DESKTOP_LOGIN_MESSAGE } }; } if (!targetApiKey) { return { kind: 'local_failure', source: 'local', error: { code: 'API_KEY_REQUIRED', message: 'API key is required.' }, }; } const profileKey = authStore.findProfileKeyByApiKey(targetApiKey); if (profileKey) { const previous = authStore.getActive(); const target = authStore.load().profiles[profileKey]!; try { (options.switchSkillLinks ?? switchActiveAccountSkillLinks)( cmdInit().path, previous, target, ); } catch (error) { return { kind: 'local_failure', source: 'local', error: { code: 'ACCOUNT_SKILL_LINK_SWITCH_FAILED', message: error instanceof Error ? error.message : String(error), }, }; } authStore.switchProfile(profileKey); const active = authStore.getActive(); return { kind: 'local_success', source: 'local', value: { success: true, data: { name: active?.agentName, active: true }, message: 'Switched active profile', }, presentation: { effects: [ { name: 'active_profile_switched', status: 'success', data: { name: active?.agentName } }, ], }, }; } const serverUrl = getSwitchServerUrl(authStore); const client = new GameClient({ lobbyUrl: serverUrl, apiKey: '' }); let response: TransportResponse; try { response = await client.requestRaw('POST', '/api/v1/agents/login', { api_key: targetApiKey }); } catch (error) { return transportFailure(error); } const root = successfulRoot(response, LOGIN_CONTRACT); if (!root) return backendResult(response, LOGIN_CONTRACT); const agentName = extractServerAccountName(root)!; const profile: AuthProfile = { agentName, apiKey: targetApiKey, serverUrl, backendAccountId: extractBackendAccountId(root), }; try { (options.switchSkillLinks ?? switchActiveAccountSkillLinks)( cmdInit().path, authStore.getActive(), profile, ); } catch (error) { return { kind: 'local_failure', source: 'local', error: { code: 'ACCOUNT_SKILL_LINK_SWITCH_FAILED', message: error instanceof Error ? error.message : String(error), }, }; } authStore.addProfile(profile); try { createProfileDirs(profile); } catch {} return backendResult(response, LOGIN_CONTRACT, { enhanceSuccess: () => ({ message: 'Imported and switched active profile' }), effects: [ { name: 'account_profile_saved', status: 'success', data: { name: agentName } }, { name: 'active_profile_switched', status: 'success', data: { name: agentName } }, ], }); }, }); }); account .command('list') .description('List locally saved profiles without credentials') .action(async () => { const authStore = new AuthStore(); const active = authStore.getActive(); const data = authStore.load(); await runner.run({ descriptor: { command: 'ccl account list', operation: 'list_saved_accounts' }, io, operation: () => ({ kind: 'local_success', source: 'local', value: { success: true, data: { profiles: Object.values(data.profiles).map((profile) => ({ name: profile.agentName, active: profile.apiKey === active?.apiKey, })), }, }, }), }); }); // ─── Game Data ─── account .command('leaderboard', { hidden: true }) .description('Show leaderboard') .option('-p, --page ', 'Page number') .option('-l, --limit ', 'Items per page (max 100)', '20') .action(async (opts: { page?: string; limit: string }) => { const client = GameClient.fromAuth(); const page = opts.page ? Number(opts.page) : undefined; const result = await client.getLeaderboard(page, Number(opts.limit)); console.log(JSON.stringify(result, null, 2)); }); account .command('settlement') .description('Show settlement data from last game') .action(async () => { const authStore = new AuthStore(); const profile = authStore.getActive(); await runner.run({ descriptor: { command: 'ccl account settlement', service: 'clawclaw-lobby', operation: 'get_settlement', sensitivePolicy: { sensitiveValues: profile ? [profile.apiKey] : [], sensitiveFieldNames: ['spectate_url', 'spectateUrl'], }, }, io, operation: async () => { if (!profile) { return { kind: 'local_failure', source: 'local', error: { code: 'NO_ACTIVE_ACCOUNT', message: noAccountMessage('accountInfo') }, }; } const client = GameClient.fromAuth({ authStore }); let response: TransportResponse; try { response = await client.requestRaw('GET', '/api/v1/game/settlement'); } catch (error) { return transportFailure(error); } const root = successfulRoot(response, SETTLEMENT_CONTRACT); if (!root) { return backendResult(response, SETTLEMENT_CONTRACT, { guidance: responseErrorCode(response) === 'NO_SETTLEMENT' ? 'No settlement is available yet; recap from the events already observed and retry later if needed.' : null, }); } const reminder = hubReminder(await refreshGamesPlayedForReminder(client)); return backendResult(response, SETTLEMENT_CONTRACT, { guidance: reminder ? `Write the post-game debrief with the user, then close out. ${reminder}` : null, }); }, }); }); account .command('info') .description('Print the current account status without credentials or spectator links') .action(async () => { const authStore = new AuthStore(); const profile = authStore.getActive(); await runner.run({ descriptor: { command: 'ccl account info', service: 'clawclaw-lobby', operation: 'get_account_info', sensitivePolicy: { sensitiveValues: profile ? [profile.apiKey] : [], sensitiveFieldNames: [ 'spectate_url', 'spectateUrl', 'watch_url', 'watchUrl', ], }, }, io, operation: async () => { if (!profile) { return { kind: 'local_failure', source: 'local', error: { code: 'NO_ACTIVE_ACCOUNT', message: noAccountMessage('accountInfo') }, }; } const client = GameClient.fromAuth({ authStore }); let response: TransportResponse; try { response = await client.requestRaw('GET', '/api/v1/agents/me'); } catch (error) { return transportFailure(error); } const root = successfulRoot(response, INFO_CONTRACT); if (!root) return backendResult(response, INFO_CONTRACT); const data = root.data; if (data && typeof data === 'object' && !Array.isArray(data)) { const gamesPlayed = (data as Record).games_played; if (typeof gamesPlayed === 'number') writeGamesPlayedCache(gamesPlayed); } return backendResult(response, INFO_CONTRACT, { projectSuccess: withoutTutorial }); }, }); }); // ── Adapter metadata (consumed by ccl _schema, applied by openclaw-clawclaw L2 generator) ── setMeta(account.commands.find((c) => c.name() === 'register')!, { requiresConfirm: true }); setMeta(account.commands.find((c) => c.name() === 'rename')!, { requiresConfirm: true }); return account; }