import { accountRequiredMessage } from '../lib/desktop-mode.js'; import { Command } from 'commander'; import { extname, resolve } from 'path'; import { Action } from '../sdk/action.js'; import { AuthStore, type AuthProfile } from '../lib/auth.js'; import { sendProfileOwnerControlRequest } from '../runtime/owner-control.js'; import { ShortCommandRunner, type CommandIo, type ShortCommandOperationResult, } from '../short-command/runner.js'; import type { CommandEffect, LocalCommandError } from '../short-command/types.js'; export type CommunicationActionKind = 'speak' | 'vote' | 'aside'; export interface CommunicationCommandDependencies { activeProfile?: () => AuthProfile | null; sendOwnerControlRequest?: typeof sendProfileOwnerControlRequest; io?: CommandIo; cwd?: () => string; } const processCommunicationIo: CommandIo = { writeStdout: (text) => { process.stdout.write(text); }, setExitCode: (code) => { process.exitCode = code; }, }; 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`.'; /** The runtime may have another cwd, so IPC must carry an absolute path. */ export function ownerAudioFilePath(filePath: string, cwd = process.cwd()): string { return resolve(cwd, filePath); } export function audioContentTypeFor(filePath: string): string { const ext = extname(filePath).toLowerCase(); switch (ext) { case '': case '.mp3': return 'audio/mpeg'; case '.wav': return 'audio/wav'; case '.ogg': case '.oga': return 'audio/ogg'; case '.m4a': case '.mp4': return 'audio/mp4'; case '.webm': return 'audio/webm'; default: throw new Error(`Unsupported audio file type "${ext || '(none)'}". Supported: mp3, wav, m4a, ogg, webm.`); } } export function communicationAction(kind: CommunicationActionKind, value: string): Action { switch (kind) { case 'speak': return Action.speech(value); case 'vote': { // `skip` → target_seat 0 (弃票);数字 → 座位号。 const trimmed = value.trim(); if (trimmed === 'skip') return Action.vote(0); const seat = Number(trimmed); if (!/^\d+$/.test(trimmed) || !Number.isInteger(seat)) { throw new Error(`invalid_vote_target: "${value}" — use a seat number or skip`); } return Action.vote(seat); } case 'aside': return Action.think().withThinking(value); } } /** Local control deferral must never be presented as a backend rejection. */ export function localControlDeferral(ownerResult: unknown): LocalCommandError | null { const result = ownerResult && typeof ownerResult === 'object' ? ownerResult as Record : {}; if (result.status !== 'deferred') return null; const raw = result.error && typeof result.error === 'object' ? result.error as Record : {}; const nested = raw.error && typeof raw.error === 'object' ? raw.error as Record : raw; return { code: String(nested.code ?? 'CONTROL_DEFERRED'), message: String(nested.message ?? 'The local control scheduler deferred this action.'), ...(nested.details === undefined ? {} : { details: nested.details }), }; } /** Preserve confirmed backend roots while keeping uncertain submissions non-retryable-by-default. */ export function failedOwnerActionOperation( ownerResult: Record, index: number, effects: CommandEffect[], ): ShortCommandOperationResult { const root = ownerResult.error && typeof ownerResult.error === 'object' && !Array.isArray(ownerResult.error) ? ownerResult.error as Record : { error: { code: 'ACTION_FAILED', message: String(ownerResult.error ?? 'Action failed.') } }; const errorCode = root.error && typeof root.error === 'object' ? String((root.error as Record).code ?? '') : ''; const actionOutcome = (ownerResult.actionOutcome ?? (errorCode === 'ACTION_REQUEST_FAILED' || errorCode === 'ACTION_PROTOCOL_ERROR' ? 'unknown' : undefined)) as 'confirmed' | 'not_submitted' | 'unknown' | undefined; const source = (ownerResult.source ?? (errorCode === 'ACTION_PROTOCOL_ERROR' ? 'protocol' : errorCode === 'ACTION_REQUEST_FAILED' ? 'transport' : undefined)) as 'backend' | 'transport' | 'protocol' | 'local' | undefined; effects.push({ name: `action_${index + 1}`, status: 'failure' }); const status = index > 0 || ownerResult.status === 'partial' ? 'partial' as const : 'failure' as const; if (actionOutcome === 'unknown') { return { kind: 'local_outcome', status, source: source === 'protocol' ? 'protocol' : source === 'transport' ? 'transport' : 'owner', value: { ...root, action_outcome: 'unknown' }, reason: 'gameplay_action_outcome_unknown', presentation: { effects, failedEffect: `action_${index + 1}`, guidance: 'The gameplay action may have reached the server, but no valid acknowledgement was received. ' + 'Do not blindly repeat it; read current game State before deciding what to do next.', }, }; } if (actionOutcome === 'not_submitted') { const value = { ...root, action_outcome: 'not_submitted' }; const presentation = { effects, failedEffect: `action_${index + 1}`, guidance: 'Preparation failed before the gameplay Action endpoint was called. ' + 'Use the returned error and current game State before retrying.', }; return source === 'backend' ? { kind: 'backend_outcome', status, value, presentation } : { kind: 'local_outcome', status, source: source === 'protocol' ? 'protocol' : source === 'transport' ? 'transport' : 'owner', value, reason: 'gameplay_action_not_submitted', presentation, }; } return { kind: 'backend_outcome', status, value: root, presentation: { effects, failedEffect: `action_${index + 1}`, guidance: 'The backend rejected the action. Use its error fields and current game State before retrying.', }, }; } interface SubmitCommunicationActionOptions { command: `ccl ${CommunicationActionKind}`; action: Action; audioFile?: string; } async function submitCommunicationAction( options: SubmitCommunicationActionOptions, dependencies: CommunicationCommandDependencies = {}, ): Promise { const runner = new ShortCommandRunner(); const profile = (dependencies.activeProfile ?? (() => new AuthStore().getActive()))(); const sendOwnerControl = dependencies.sendOwnerControlRequest ?? sendProfileOwnerControlRequest; const io = dependencies.io ?? processCommunicationIo; await runner.run({ descriptor: { command: options.command, service: 'clawclaw-game-owner', operation: 'submit_action', sensitivePolicy: { sensitiveValues: profile ? [profile.apiKey] : [], sensitiveFieldNames: ['api_key', 'apiKey', 'token', 'authorization', 'audio_url'], }, }, io, operation: async (): Promise => { if (!profile) { return { kind: 'local_failure', source: 'local', error: { code: 'NO_ACTIVE_ACCOUNT', message: accountRequiredMessage('No active account. Run `ccl account register` or switch accounts first.') }, }; } const effects: CommandEffect[] = []; let audioFile: { path: string; contentType: string } | undefined; if (options.audioFile) { try { audioFile = { path: ownerAudioFilePath(options.audioFile, (dependencies.cwd ?? (() => process.cwd()))()), contentType: audioContentTypeFor(options.audioFile), }; } catch (error) { effects.push({ name: 'action_1', status: 'failure', reason: 'invalid_audio_file' }); return { kind: 'local_failure', source: 'local', error: { code: 'INVALID_AUDIO_FILE', message: error instanceof Error ? error.message : String(error), details: { action_outcome: 'not_submitted' }, }, reason: 'gameplay_action_not_submitted', presentation: { effects, failedEffect: 'action_1', guidance: 'The audio file was rejected locally. No gameplay action was submitted.', }, }; } } let snapshot: any; try { snapshot = await sendOwnerControl(profile, 'snapshot'); } catch (error) { return { kind: 'transport_failure', error: { code: 'OWNER_UNAVAILABLE', message: error instanceof Error ? error.message : String(error), }, presentation: { guidance: OWNER_RUNTIME_GUIDANCE }, }; } if (!snapshot?.ok || !snapshot.scope) { return { kind: 'local_failure', source: 'owner', error: { code: 'NO_GAME_START_OWNER', message: snapshot?.error ?? OWNER_RUNTIME_GUIDANCE, }, presentation: { guidance: OWNER_RUNTIME_GUIDANCE }, }; } let response: any; try { response = await sendOwnerControl(profile, 'action', { capability: 'clawclaw.action', expected_scope: snapshot.scope, action: { route: 'auto', action: options.action.toJSON(), ...(audioFile ? { audioFile } : {}), }, }, 60_000); } catch (error) { const errorRoot = { success: false, error: { code: 'OWNER_ACTION_UNAVAILABLE', message: error instanceof Error ? error.message : String(error), details: { action_outcome: 'unknown' }, }, action_outcome: 'unknown', }; effects.push({ name: 'action_1', status: 'failure', reason: 'owner_transport_failed_outcome_unknown', }); return { kind: 'transport_failure', error: errorRoot.error, reason: 'owner_action_outcome_unknown', presentation: { effects, failedEffect: 'action_1', guidance: 'The owner action channel failed before an acknowledgement. Check current State before deciding whether the action itself needs retrying.', }, }; } if (response == null) { effects.push({ name: 'action_1', status: 'failure', reason: 'owner_no_response_outcome_unknown', }); return { kind: 'transport_failure', error: { code: 'OWNER_ACTION_NO_RESPONSE', message: 'The runtime action channel closed without an acknowledgement.', details: { action_outcome: 'unknown' }, }, reason: 'owner_action_outcome_unknown', presentation: { effects, failedEffect: 'action_1', guidance: 'The runtime returned no acknowledgement. The gameplay action outcome is unknown; ' + 'read current game State before deciding whether to retry.', }, }; } if (!response?.ok) { effects.push({ name: 'action_1', status: 'failure', reason: response?.error ?? 'owner_action_unavailable' }); return { kind: 'local_failure', source: 'owner', error: { code: 'OWNER_ACTION_REJECTED', message: response?.error ?? 'The owner rejected the action request.', }, presentation: { effects, failedEffect: 'action_1' }, }; } const ownerResult = response.result; const controlDeferred = localControlDeferral(ownerResult); if (controlDeferred) { effects.push({ name: 'action_1', status: 'failure', reason: controlDeferred.code, }); return { kind: 'local_failure', source: 'owner', error: controlDeferred, reason: 'action_control_deferred', presentation: { effects, failedEffect: 'action_1', guidance: 'The action stayed local because control is temporarily unavailable. ' + 'Read current game information before retrying; no gameplay action was sent.', }, }; } if (ownerResult?.status !== 'success') { return failedOwnerActionOperation(ownerResult ?? {}, 0, effects); } effects.push({ name: 'action_1', status: 'success' }); const value = ownerResult.value; if (value && typeof value === 'object' && !Array.isArray(value)) { return { kind: 'backend_outcome', status: 'success', value: value as Record, presentation: { effects }, }; } return { kind: 'local_success', source: 'owner', value: { results: [value ?? 'ok'] }, presentation: { effects }, }; }, }); } export function createSpeakCommand(dependencies: CommunicationCommandDependencies = {}): Command { return new Command('speak') .description('Send in-game speech') .argument('', 'Speech text') .option('--file ', 'Upload a local audio file and attach it to speech') .action(async (text: string, opts: { file?: string }) => { await submitCommunicationAction({ command: 'ccl speak', action: communicationAction('speak', text), audioFile: opts.file, }, dependencies); }); } export function createVoteCommand(dependencies: CommunicationCommandDependencies = {}): Command { return new Command('vote') .description('Vote for a player (by seat number) during a meeting, or skip') .argument('', 'Seat number (1-10) of the player to vote out, or skip') .action(async (target: string) => { await submitCommunicationAction({ command: 'ccl vote', action: communicationAction('vote', target), }, dependencies); }); } export function createAsideCommand(dependencies: CommunicationCommandDependencies = {}): Command { return new Command('aside') .description('Send a private aside to the user/spectators; not visible to other in-game players') .argument('', 'Private aside text') .action(async (text: string) => { await submitCommunicationAction({ command: 'ccl aside', action: communicationAction('aside', text), }, dependencies); }); }