// `storebound serve --stdio`: the machine interface the desktop app (apps/desktop) drives as a sidecar. // Newline-delimited JSON-RPC 2.0 on stdin / stdout, logs on stderr. Protocol types: lib/desktop-protocol.ts. // // It reuses the MCP core: the same tool list (mcp-tools.ts: schemas, validation, argv building, the forbidden-flag // rules) and the same child-process runner (lib/runner.ts). On top of that, the desktop profile adds: // - a session handshake (`session.hello`) carrying the per-session secret of the host, // - typed methods (one per tool, e.g. `play.listing`, plus project.inspect, portfolio.status, system.*), // - structured results (`data`, the command's --json output), progress notifications and cancellation, // - writes that are dry runs unless the host sends a confirm token (lib/confirm-token.ts) it minted after the owner // confirmed a native dialog showing that dry run. // Nothing here submits for review, releases or publishes: those methods do not exist (tests/serve.test.ts). import { existsSync, statSync } from 'node:fs'; import { isAbsolute, join, resolve } from 'node:path'; import pkg from '../package.json' with { type: 'json' }; import { parseSecret, TokenGuard } from './lib/confirm-token'; import { CONFIG_NAMES } from './lib/config'; import { DESKTOP_PROTOCOL, ERR, type MethodDescriptor, type PortfolioEntry, type PortfolioResult, type ProjectSummary, type ToolResult, } from './lib/desktop-protocol'; import { compiled, pickCallEnv, runCommand, type RunOptions, type Running } from './lib/runner'; import { inputSchema, type ToolDef, TOOLS, toArgv, validateInput } from './mcp-tools'; type Id = string | number; interface Msg { jsonrpc?: string; id?: Id | null; method?: string; params?: unknown } type Json = Record; export type Send = (msg: Json) => void; export type Runner = (argv: string[], o: RunOptions) => Running; const MAX_OUTPUT = 60_000; /** MCP tools the desktop profile leaves out (sending builds to testers on Play, release state changes). */ export const DESKTOP_EXCLUDED = new Set(['play_release_testing', 'apple_phased_release']); /** Words no desktop method name may contain. */ export const FORBIDDEN_METHOD_WORDS = /submit|release|publish|rollout|resume|complete|send|start|stop|cancel|delete|remove|invite/i; /** Read tools whose command prints a structured result with --json. */ export const JSON_TOOLS = new Set(['check', 'check_aso', 'validate', 'health', 'reviews_list', 'prices_diff', 'analytics_compare', 'apple_status', 'apple_next_build', 'play_status', 'play_next_version_code', 'shots_check', 'apple_testflight_status', 'apple_ppo_status']); /** `apple_testflight_status` -> `apple.testflight_status`: first underscore becomes the namespace dot. */ export const methodName = (tool: string): string => tool.replace('_', '.'); export const DESKTOP_TOOLS: ToolDef[] = TOOLS.filter(t => !DESKTOP_EXCLUDED.has(t.name)); const byMethod = new Map(DESKTOP_TOOLS.map(t => [methodName(t.name), t] as const)); function argsSchema(t: ToolDef): MethodDescriptor['args'] { const s = inputSchema(t) as MethodDescriptor['args']; const { dry_run: _d, ...properties } = s.properties; return { ...s, properties }; } const obj = (properties: MethodDescriptor['args']['properties'], required?: string[]): MethodDescriptor['args'] => ({ type: 'object', properties, ...(required ? { required } : {}), additionalProperties: false }); const SYSTEM: MethodDescriptor[] = [ { method: 'session.hello', title: 'Start the session', description: 'Hand over the per-session secret (hex, >= 32 bytes). Must be the first request.', kind: 'session', network: false, destructive: false, json: true, args: obj({ secret: { type: 'string' }, client: { type: 'object' } }, ['secret']) }, { method: 'system.version', title: 'Version', description: 'storebound version, platform and whether this is the compiled sidecar.', kind: 'system', network: false, destructive: false, json: true, args: obj({}) }, { method: 'system.methods', title: 'Methods', description: 'Every method of this profile with its argument schema.', kind: 'system', network: false, destructive: false, json: true, args: obj({}) }, { method: 'system.tools', title: 'Local tools', description: 'Which optional local tools are installed (git, ffmpeg, Google Chrome, Playwright); screenshot and video features need them.', kind: 'system', network: false, destructive: false, json: true, args: obj({}) }, { method: 'project.inspect', title: 'Inspect a project', description: 'Offline summary of a folder\'s storebound.config.ts (name, store ids, languages, products).', kind: 'read', network: false, destructive: false, json: true, args: obj({ project: { type: 'string', description: 'Absolute folder path' } }, ['project']) }, { method: 'portfolio.status', title: 'Portfolio status', description: 'Summary + offline check of many projects; with live, also App Store and Google Play status (read-only).', kind: 'portfolio', network: true, destructive: false, json: true, args: obj({ projects: { type: 'array' }, live: { type: 'boolean', default: false } }, ['projects']) }, ]; export function describeMethods(): MethodDescriptor[] { return [...SYSTEM, ...DESKTOP_TOOLS.map(t => ({ method: methodName(t.name), title: t.title, description: t.description, kind: t.write ? 'write' as const : 'read' as const, network: t.network, destructive: !!t.destructive, json: !t.write && JSON_TOOLS.has(t.name), args: argsSchema(t), }))]; } class RpcError extends Error { constructor(readonly code: number, message: string, readonly data?: unknown) { super(message); } } /** Absolute folder with a storebound config in it, else an error. */ export function checkProject(p: unknown): string { if (typeof p !== 'string' || !p) throw new RpcError(ERR.invalidParams, 'project: absolute folder path required'); if (!isAbsolute(p)) throw new RpcError(ERR.invalidParams, 'project: must be an absolute path'); const dir = resolve(p); let isDir = false; try { isDir = statSync(dir).isDirectory(); } catch { /* missing */ } if (!isDir) throw new RpcError(ERR.invalidParams, `project: not a folder: ${dir}`); if (!CONFIG_NAMES.some(n => existsSync(join(dir, n)))) throw new RpcError(ERR.invalidParams, `project: no storebound.config.ts in ${dir}`); return dir; } const cut = (s: string): string => (s.length > MAX_OUTPUT ? `[... first ${s.length - MAX_OUTPUT} characters cut ...]\n` + s.slice(-MAX_OUTPUT) : s); function credentialsOf(v: unknown): Record { if (v === undefined) return {}; if (typeof v !== 'object' || v === null || Array.isArray(v)) throw new RpcError(ERR.invalidParams, 'credentials: object expected'); return pickCallEnv(v as Record); } /** One sidecar session: state is the secret (after hello), the token guard and the running requests. */ export class Session { private guard: TokenGuard | null = null; private running = new Map>(); private cancelled = new Set(); constructor(private readonly send: Send, private readonly run: Runner = runCommand, private readonly clock: () => number = Date.now) {} get ready(): boolean { return this.guard !== null; } /** Stops every running child (the host went away). */ shutdown(): void { for (const set of this.running.values()) for (const r of set) r.cancel(); } /** Handles one incoming message; resolves with the response (or null for notifications). */ async handle(m: Msg): Promise { if (typeof m !== 'object' || m === null || Array.isArray(m)) return { jsonrpc: '2.0', id: null, error: { code: ERR.invalidRequest, message: 'Invalid request' } }; if (m.id === undefined || m.id === null) { this.notification(m); return null; } const id = m.id; try { const result = await this.dispatch(String(m.method ?? ''), (m.params ?? {}) as Json, id); return { jsonrpc: '2.0', id, result }; } catch (e) { if (this.cancelled.has(id)) return { jsonrpc: '2.0', id, error: { code: ERR.cancelled, message: 'Request cancelled' } }; const err = e instanceof RpcError ? e : new RpcError(ERR.internal, (e as Error).message); return { jsonrpc: '2.0', id, error: { code: err.code, message: err.message, ...(err.data === undefined ? {} : { data: err.data }) } }; } finally { this.running.delete(id); this.cancelled.delete(id); } } private notification(m: Msg): void { const p = (m.params ?? {}) as Json; if (m.method === '$/cancelRequest' || m.method === 'notifications/cancelled') { const id = (p.id ?? p.requestId) as Id | undefined; if (id === undefined) return; this.cancelled.add(id); for (const r of this.running.get(id) ?? []) r.cancel(); } } private track(id: Id, r: Running): Running { if (this.cancelled.has(id)) r.cancel(); let set = this.running.get(id); if (!set) this.running.set(id, (set = new Set())); set.add(r); return r; } private async dispatch(method: string, params: Json, id: Id): Promise { if (typeof params !== 'object' || params === null || Array.isArray(params)) throw new RpcError(ERR.invalidParams, 'params must be an object'); if (method === 'session.hello') { if (this.guard) throw new RpcError(ERR.invalidRequest, 'session already started'); let secret: Buffer; try { secret = parseSecret(params.secret); } catch (e) { throw new RpcError(ERR.invalidParams, (e as Error).message); } this.guard = new TokenGuard(secret, this.clock); return { protocol: DESKTOP_PROTOCOL, server: { name: 'storebound', version: pkg.version, compiled: compiled() }, methods: describeMethods() }; } if (!this.guard) throw new RpcError(ERR.notInitialized, 'session.hello first'); switch (method) { case 'system.version': return { version: pkg.version, compiled: compiled(), platform: process.platform, arch: process.arch, bun: Bun.version }; case 'system.methods': return { methods: describeMethods() }; case 'system.tools': return localTools(); case 'project.inspect': return this.inspect(checkProject(params.project), {}, id); case 'portfolio.status': return this.portfolio(params, id); } const tool = byMethod.get(method); if (!tool) throw new RpcError(ERR.methodNotFound, `Method not found: ${method}`); return this.tool(method, tool, params, id); } private async tool(method: string, t: ToolDef, params: Json, id: Id): Promise { for (const k of Object.keys(params)) if (!['project', 'args', 'dryRun', 'confirmToken', 'credentials'].includes(k)) throw new RpcError(ERR.invalidParams, `unknown param: ${k}`); const project = checkProject(params.project); const args = (params.args ?? {}) as Json; if (typeof args !== 'object' || args === null || Array.isArray(args)) throw new RpcError(ERR.invalidParams, 'args must be an object'); if ('dry_run' in args) throw new RpcError(ERR.invalidParams, 'args.dry_run: use params.dryRun'); const problems = validateInput(t, args); if (problems.length) throw new RpcError(ERR.invalidParams, `Invalid arguments: ${problems.join('; ')}`, { problems }); const env = credentialsOf(params.credentials); let dryRun = true; if (params.dryRun === false) { if (!t.write) dryRun = false; else { if (params.confirmToken === undefined) throw new RpcError(ERR.confirmRequired, `${method} writes: dryRun false needs a confirmToken from the desktop host`); const v = this.guard!.verify(params.confirmToken, method, { project, args }); if (!v.ok) throw new RpcError(ERR.confirmInvalid, `confirm token rejected: ${v.error}`, { reason: v.error }); dryRun = false; } } else if (params.dryRun !== undefined && params.dryRun !== true) throw new RpcError(ERR.invalidParams, 'dryRun must be a boolean'); if (!t.write) dryRun = false; const built = toArgv(t, { ...args, ...(t.write ? { dry_run: dryRun } : {}) }); const json = !t.write && JSON_TOOLS.has(t.name); const argv = json ? [...built.argv, '--json'] : built.argv; const r = this.track(id, this.run(argv, { cwd: project, env, machine: true, onLine: (line, stream) => this.progress(id, { line, stream }) })); const res = await r.result; if (res.cancelled || this.cancelled.has(id)) throw new RpcError(ERR.cancelled, 'Request cancelled'); return { method, ok: res.code === 0, exitCode: res.code, dryRun: t.write ? dryRun : false, command: `storebound ${argv.join(' ')}`, output: cut(res.out), ...(res.data === undefined ? {} : { data: res.data }), }; } private progress(id: Id, p: Json): void { this.send({ jsonrpc: '2.0', method: 'progress', params: { requestId: id, ...p } }); } private async inspect(project: string, env: Record, id: Id): Promise { const r = await this.track(id, this.run(['inspect', '--json'], { cwd: project, env, machine: true })).result; if (r.cancelled) throw new RpcError(ERR.cancelled, 'Request cancelled'); if (r.code !== 0 || !r.data) throw new RpcError(ERR.invalidParams, `project: ${lastLine(r.out) || 'config could not be loaded'}`); return r.data as ProjectSummary; } private async portfolio(params: Json, id: Id): Promise { const list = params.projects; if (!Array.isArray(list) || !list.length || list.length > 200) throw new RpcError(ERR.invalidParams, 'projects: 1-200 absolute folder paths'); const live = params.live === true; const env = credentialsOf(params.credentials); const out: PortfolioEntry[] = new Array(list.length); let done = 0; const one = async (i: number): Promise => { const raw = list[i]; const e: PortfolioEntry = { project: String(raw), ok: false, summary: null, check: null, errors: [] }; out[i] = e; try { const dir = checkProject(raw); e.project = dir; const summary = e.summary = await this.inspect(dir, env, id); const c = await this.track(id, this.run(['check', '--json'], { cwd: dir, env, machine: true })).result; const cd = c.data as { ok?: boolean; problems?: string[]; warnings?: string[] } | undefined; e.check = cd ? { ok: !!cd.ok, problems: cd.problems ?? [], warnings: cd.warnings ?? [] } : { ok: false, problems: [lastLine(c.out) || `check exit ${c.code}`], warnings: [] }; if (live) { const store = async (argv: string[]): Promise<{ data?: unknown; error?: string }> => { const r = await this.track(id, this.run(argv, { cwd: dir, env, machine: true })).result; return r.code === 0 && r.data !== undefined ? { data: r.data } : { error: lastLine(r.out) || `exit ${r.code}` }; }; const [apple, play] = await Promise.all([summary.apple ? store(['apple', 'status', '--json']) : undefined, summary.play ? store(['play', 'status', '--json']) : undefined]); if (apple) e.apple = apple; if (play) e.play = play; } e.ok = e.check.ok && !e.apple?.error && !e.play?.error; } catch (err) { if (this.cancelled.has(id)) throw err; e.errors.push((err as Error).message); } this.progress(id, { n: ++done, total: list.length, project: e.project }); }; // A few projects at a time: each one is a few child processes (and API calls when live). let next = 0; await Promise.all(Array.from({ length: Math.min(3, list.length) }, async () => { while (next < list.length) await one(next++); })); if (this.cancelled.has(id)) throw new RpcError(ERR.cancelled, 'Request cancelled'); return { projects: out, at: new Date(this.clock()).toISOString() }; } } const lastLine = (s: string): string => s.trim().split('\n').filter(Boolean).at(-1)?.replace(/^error:\s*/, '') ?? ''; export function localTools(): Json { const which = (n: string): string | null => Bun.which(n); const chrome = process.platform === 'darwin' ? existsSync('/Applications/Google Chrome.app') : process.platform === 'win32' ? [process.env['PROGRAMFILES'], process.env['PROGRAMFILES(X86)'], process.env.LOCALAPPDATA].some(d => d && existsSync(join(d, 'Google/Chrome/Application/chrome.exe'))) : !!(which('google-chrome') || which('google-chrome-stable') || which('chromium')); const ffmpeg = which('ffmpeg'); return { git: !!which('git'), ffmpeg: !!ffmpeg, chrome, notes: [ ...(ffmpeg ? [] : ['ffmpeg not found: icons, screenshot renders and app preview videos need it (brew install ffmpeg / apt install ffmpeg / winget install ffmpeg)']), ...(chrome ? [] : ['Google Chrome not found: screenshot renders and web captures need Chrome or Playwright\'s Chromium in the project']), ], }; } export async function serveStdio(): Promise { const send: Send = o => { process.stdout.write(JSON.stringify(o) + '\n'); }; const session = new Session(send); console.error(`[storebound serve] ${pkg.version} on stdio (${DESKTOP_PROTOCOL}), waiting for session.hello`); let buf = ''; const decoder = new TextDecoder(); const reader = Bun.stdin.stream().getReader(); for (;;) { const { value, done } = await reader.read(); if (done) break; buf += decoder.decode(value, { stream: true }); let nl: number; while ((nl = buf.indexOf('\n')) >= 0) { const line = buf.slice(0, nl).trim(); buf = buf.slice(nl + 1); if (!line) continue; let msg: Msg; try { msg = JSON.parse(line) as Msg; } catch { send({ jsonrpc: '2.0', id: null, error: { code: ERR.parse, message: 'Parse error' } }); continue; } if (Array.isArray(msg)) { send({ jsonrpc: '2.0', id: null, error: { code: ERR.invalidRequest, message: 'Batches are not supported' } }); continue; } // The handshake must finish before anything else is read, so a request right behind it sees the session. if (!session.ready && msg.method === 'session.hello') { const r = await session.handle(msg); if (r) send(r); continue; } session.handle(msg).then(r => { if (r) send(r); }, e => send({ jsonrpc: '2.0', id: msg.id ?? null, error: { code: ERR.internal, message: String((e as Error).message) } })); } } // stdin closed: the host is gone; stop what still runs. session.shutdown(); process.exit(0); } export async function run(args: { has(n: string): boolean }): Promise { if (!args.has('stdio')) { console.error('usage: storebound serve --stdio (JSON-RPC for the storebound desktop app; for AI tools use `storebound mcp`)'); process.exit(2); } await serveStdio(); }