/** * Call the hosted package's ./audio-store export through the Kody CLI (signed in with `kody login` as Noah). * Set KODY_CLI to override. */ import { spawn } from 'node:child_process' const cli = (process.env.KODY_CLI ?? 'npx -y @kodycodes/cli@latest').split(' ') function run(args: string[]): Promise<{ stdout: string; stderr: string }> { return new Promise((resolve, reject) => { const child = spawn(cli[0], [...cli.slice(1), ...args]) let stdout = '' let stderr = '' child.stdout.on('data', (d) => (stdout += d)) child.stderr.on('data', (d) => (stderr += d)) child.on('error', reject) child.on('close', () => resolve({ stdout, stderr })) }) } /** * Run one audio-store action, retrying up to three times. * * @param params - the action and its fields * @returns the export's JSON result */ export async function callStore(params: Record): Promise { for (let attempt = 1; ; attempt++) { const { stdout, stderr } = await run(['execute', '--invoke', 'kody:@noah/mega-radio/audio-store', '--params', JSON.stringify(params), '--json']) const out = stdout.trim() try { const parsed = JSON.parse(out) const result = parsed?.structuredContent?.result if (parsed?.isError || result === undefined) throw new Error(JSON.stringify(parsed?.structuredContent?.error ?? parsed?.content ?? parsed).slice(0, 500)) return result } catch (error) { if (attempt >= 3) throw new Error(`${params.action} ${params.code ?? ''} failed: ${String(error)}\n${out.slice(0, 1000)}\n${stderr.slice(0, 1000)}`) console.error(`${params.action} ${params.code ?? ''} attempt ${attempt} failed, retrying`) } } }