storebound/cli/install.ts
CRT 36a8bf9625 CLI runs on Node 20+: npx storebound (bunx keeps working)
- cli/lib/rt.ts: the runtime layer on node: modules (spawn / spawnSync with Bun's defaults, exit codes and
  "Executable not found", which with PATHEXT, sleep, serve, Glob, hasher, gunzip, stdin, SQLite, packageRoot,
  config imports with a type-stripping fallback for Node 20); every Bun.* use in cli/ goes through it
- tools/gen-embedded.ts -> cli/lib/embedded.ts: templates/, cli/shots/*.html and Play's Data safety form embedded
  (replaces Bun text imports; the bundle and the compiled sidecar carry them), checked fresh by bun run ci
- package.json: bin dist/storebound.mjs (Node ESM bundle, tools/build-node.ts, prepack), engines node >=20
- bun run ci: node bundle + node smoke (real node: --version, help, check same as Bun, scan, release plan --help,
  init, MCP handshake + tool call); Forgejo CI sets up Node 20; tests/node-compat.test.ts guards cli/
- install writes npx MCP commands when run with Node; bin/storebound falls back to Node
- docs: npx storebound init (Node 20+) or bunx storebound init
2026-10-13 04:03:28 +08:00

83 lines
4.9 KiB
TypeScript

// Put the storebound skills and MCP server into an app or game project for one or more AI coding tools.
// storebound install --agent claude|codex|cursor|copilot|windsurf|gemini|opencode[,...] [--dir .] [--dry]
// [--no-skills] [--no-mcp] [--command "bunx storebound"]
// Skills are copied to the tool's skills folder (our own skill folders are updated, nothing else is touched). The MCP
// entry "storebound" is added to the tool's config file; every other entry stays as it is. Re-running is safe.
// MCP command: `bunx storebound mcp` (`npx storebound mcp` when run with Node) when the project has storebound in
// node_modules; else, under Bun, this toolchain's bin/storebound by absolute path, under Node (`npx storebound
// install`: the toolchain sits in npx's cache, which can be cleared) `npx -y storebound@<this version> mcp`
// (override with --command).
import { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
import { homedir } from 'node:os';
import { dirname, join, resolve } from 'node:path';
import type { Args } from './lib/args';
import { AGENTS, type AgentId, isAgent, type McpCommand, mergeCodexToml, mergeJsonServer } from './lib/agents';
import { log, warn } from './lib/log';
import * as rt from './lib/rt';
import pkg from '../package.json' with { type: 'json' };
const TOOLCHAIN = rt.packageRoot();
/** Every file of a folder, relative path -> content, for comparing skill folders. */
function snapshot(dir: string, base = dir, out = new Map<string, string>()): Map<string, string> {
if (!existsSync(dir)) return out;
for (const n of readdirSync(dir, { withFileTypes: true })) {
const p = join(dir, n.name);
if (n.isDirectory()) snapshot(p, base, out); else out.set(p.slice(base.length), readFileSync(p, 'utf8'));
}
return out;
}
const same = (a: Map<string, string>, b: Map<string, string>) => a.size === b.size && [...a].every(([k, v]) => b.get(k) === v);
export function mcpCommand(project: string, override?: string, runtime: 'bun' | 'node' = rt.runtime.name, version = pkg.version): McpCommand {
if (override) { const [command, ...args] = override.split(/\s+/).filter(Boolean); return { command: command!, args: [...args, 'mcp'] }; }
if (existsSync(join(project, 'node_modules', 'storebound', 'package.json'))) return { command: runtime === 'bun' ? 'bunx' : 'npx', args: ['storebound', 'mcp'] };
if (runtime === 'node') return { command: 'npx', args: ['-y', `storebound@${version}`, 'mcp'] };
return { command: join(TOOLCHAIN, 'bin', 'storebound'), args: ['mcp'] };
}
export async function run(args: Args): Promise<void> {
const agents = args.list('agent');
if (!agents.length || !agents.every(isAgent)) throw new Error(`usage: install --agent ${Object.keys(AGENTS).join('|')}[,...] [--dir .] [--dry] [--no-skills] [--no-mcp]`);
const project = resolve(args.str('dir', '.'));
const dry = args.has('dry');
const home = args.get('home') ?? homedir();
const cmd = mcpCommand(project, args.get('command'));
const skillsSrc = join(TOOLCHAIN, 'skills');
const skills = readdirSync(skillsSrc).filter(n => existsSync(join(skillsSrc, n, 'SKILL.md'))).sort();
const say = (m: string) => log('install', dry ? `${m} (dry)` : m);
const doneDirs = new Set<string>();
for (const id of agents as AgentId[]) {
const a = AGENTS[id];
log('install', `${a.label}`);
if (!args.has('no-skills') && !doneDirs.has(a.skillsDir)) {
doneDirs.add(a.skillsDir);
let created = 0, updated = 0, kept = 0;
for (const s of skills) {
const from = join(skillsSrc, s);
const to = join(project, a.skillsDir, s);
const had = existsSync(to);
if (had && same(snapshot(from), snapshot(to))) { kept++; continue; }
if (!dry) { mkdirSync(dirname(to), { recursive: true }); cpSync(from, to, { recursive: true, force: true }); }
if (had) updated++; else created++;
}
say(`skills -> ${a.skillsDir}: ${created} new, ${updated} updated, ${kept} up to date`);
}
if (!args.has('no-mcp')) {
const rel = a.mcpFile({ home, xdg: process.env.XDG_CONFIG_HOME, exists: existsSync });
const file = rel.startsWith('~/') ? join(home, rel.slice(2)) : rel.startsWith('/') ? rel : join(project, rel);
const cur = existsSync(file) ? readFileSync(file, 'utf8') : null;
try {
const r = a.format === 'codex-toml' ? mergeCodexToml(cur, cmd) : mergeJsonServer(cur, a.format, cmd);
if (!r.changed) log('install', `mcp ${rel}: up to date`);
else {
if (!dry) { mkdirSync(dirname(file), { recursive: true }); writeFileSync(file, r.text); }
say(`mcp ${rel}: storebound -> ${cmd.command} ${cmd.args.join(' ')}`);
}
} catch (e) { warn('install', `mcp ${rel}: ${(e as Error).message}`); }
}
if (a.note) log('install', ` note: ${a.note}`);
}
log('install', 'restart the AI tool so it picks up the skills and the MCP server; credentials stay in env / .storebound/');
}