@awesomate/hosting-mcp
Version:
Awesomate MCP server — lets Claude manage your Awesomate WordPress hosting, plan, limits, n8n automations, and build Node/static apps + databases
1,049 lines • 53.3 kB
JavaScript
#!/usr/bin/env node
/**
* Awesomate Hosting: one-time bootstrap.
*
* Redeems the setup code from the hub's "Connect Claude Code" prompt for a
* durable, scoped access token; stores it as a PROFILE (multi-account safe);
* pins the current folder to that account; and (on Support Plus+) generates an
* SSH keypair and authorizes the PUBLIC key on the client's own cPanel
* account. The private key never leaves this machine; the setup code is the
* only secret that ever crossed the clipboard, and it's short-lived. The
* access token itself is never printed.
*
* Usage (Claude runs this, the user doesn't touch a terminal):
* node bootstrap.mjs --code amt_bs_XXXX [--account <slug>] [--pin-dir <dir>] [--replace] [--client codex|claude|both] [--muse | --no-muse]
* node bootstrap.mjs --pat <token> [--account <slug>] # resume: skip redeem
* node bootstrap.mjs --switch <slug> [--pin-dir <dir>] # use an account already saved here
* node bootstrap.mjs --update [--muse | --no-muse] # refresh the skills, no token
*
* Muse (another agent app) gets a router skill, a connector guide and a rule
* in ~/AGENTS.md (muse.mjs), only where Muse is evidently installed or
* --muse asks for it. Every run ends by printing the account this folder
* uses, and a connect ends by reading the account back from the hub with the
* saved key.
*
* --account asserts WHICH account this connect is for: a mismatch aborts before
* anything is written. --pat resumes a half-finished bootstrap with an
* already-redeemed token. It exists for support on the user's own machine and
* is never suggested in chat: a token on a command line lands in the
* transcript and shell history. Setup codes are replayable for their whole
* 10-minute life, and a fresh Connect command is always the advice.
*
* Proxied environments (cloud agent sandboxes): Node's built-in fetch ignores
* HTTP(S)_PROXY, so this script routes through undici's EnvHttpProxyAgent when
* a proxy is configured (falling back to a one-shot re-exec with
* NODE_USE_ENV_PROXY=1 when undici isn't resolvable).
*
* Node 18+ built-ins only, plus undici when running from the npm package.
*/
import { execFileSync, spawnSync } from 'node:child_process';
import { existsSync, mkdirSync, writeFileSync, chmodSync, readFileSync, cpSync, readdirSync, renameSync, rmSync, rmdirSync, statSync, realpathSync } from 'node:fs';
import { homedir, hostname } from 'node:os';
import { join, dirname, resolve, basename } from 'node:path';
import { fileURLToPath } from 'node:url';
import { format } from 'node:util';
import {
NOT_REWRITTEN, clientLabel, codexEntryToml, codexHome, detectClients, ensureCodexRegistration, rewriteForCodex, skillsDirFor,
} from './agent-clients.mjs';
import { activeAccount, describeActive, readCredentials } from './profiles.mjs';
import { detectMuse, museChecks, refreshMuse } from './muse.mjs';
function arg(name, fallback) {
const i = process.argv.indexOf(`--${name}`);
return i >= 0 && process.argv[i + 1] ? process.argv[i + 1] : fallback;
}
const code = arg('code');
const resumePat = arg('pat');
const expectedAccount = arg('account', null);
const pinDirArg = arg('pin-dir', null);
const switchTo = arg('switch', null);
const apiBase = (arg('api', 'https://hub.awesomate.ai')).replace(/\/$/, '');
// Which coding agent this connect is for: Codex and Claude Code read their MCP
// registration and skills from different places. --client codex|claude|both
// overrides what the environment says.
let CLIENTS;
try {
CLIENTS = detectClients(process.argv, process.env).clients;
} catch (err) {
console.error(err.message);
console.error(process.argv.includes('--update') ? 'Skill refresh failed: no changes made.' : 'AWESOMATE CONNECT: FAILED reason=bad-client');
process.exit(1);
}
const CLIENT_NAMES = CLIENTS.map(clientLabel).join(' and ');
// Written as text, not joined: the hints print the same ~/ path on every platform.
const FIRST_SKILLS_DIR = CLIENTS[0] === 'codex' ? '~/.agents/skills' : '~/.claude/skills';
const UPDATE_ONLY = process.argv.includes('--update');
const SWITCH_ONLY = process.argv.includes('--switch');
if (SWITCH_ONLY && (!switchTo || switchTo.startsWith('--') || UPDATE_ONLY || code || resumePat)) {
console.error('--switch needs the account to use, on its own: --switch <slug> [--pin-dir <dir>].');
console.error('AWESOMATE SWITCH: FAILED reason=bad-switch');
process.exit(1);
}
if (!UPDATE_ONLY && !SWITCH_ONLY && !resumePat && (!code || !code.startsWith('amt_bs_'))) {
console.error('Missing/invalid --code. Copy a fresh Connect command from hub.awesomate.ai/claude and run it again.');
console.error('AWESOMATE CONNECT: FAILED reason=bad-code');
process.exit(1);
}
if (resumePat && !resumePat.startsWith('amt_pat_')) {
console.error('That is not an Awesomate access token. Copy a fresh Connect command from hub.awesomate.ai/claude and run it again.');
console.error('AWESOMATE CONNECT: FAILED reason=bad-pat');
process.exit(1);
}
const dir = join(homedir(), '.awesomate');
const keysDir = join(dir, 'keys');
const credPath = join(dir, 'credentials.json');
const keyPath = join(keysDir, 'id_ed25519');
const PIN_FILENAME = '.awesomate.json';
// ---------------------------------------------------------------------------
// Connect log: every run's output (redacted) lands in ~/.awesomate/
// last-connect.log so a failure is diagnosable AFTER the fact: the
// support-report script attaches it automatically. Tokens and codes never
// reach the log or the screen, not even in part: bootstrap output doesn't
// print them, and the argv line and every printed line are redacted.
// ---------------------------------------------------------------------------
const CONNECT_LOG = [`--- awesomate connect ${new Date().toISOString()} ---`];
function redactSecrets(s) {
return String(s)
.replace(/amt_pat_[A-Za-z0-9_-]+/g, 'amt_pat_[redacted]')
.replace(/amt_bs_[A-Za-z0-9_-]+/g, 'amt_bs_[redacted]');
}
CONNECT_LOG.push(`argv: ${process.argv.slice(2).map(redactSecrets).join(' ')}`);
// The proxy re-exec's parent only waits for its child, which prints the line itself.
let REEXEC_PARENT = false;
// Every run says which account this folder uses (and which others are saved), so a connect that
// moved this folder to another account is never silent. It goes just before the result line, which
// stays the last line; a run with no result line (--update) prints it on the way out.
let ACTIVE_PRINTED = false;
function activeLine() {
ACTIVE_PRINTED = true;
try {
return describeActive(activeAccount({ credPath, cwd: resolve(pinDirArg || process.cwd()), home: homedir(), env: process.env }));
} catch { return null; /* the line must never block the run */ }
}
for (const method of ['log', 'error']) {
const original = console[method].bind(console);
const emit = (line) => { CONNECT_LOG.push(line); original(line); };
console[method] = (...args) => {
// util.format, as console itself does: objects stay readable and an Error keeps its stack.
const line = redactSecrets(format(...args));
if (!ACTIVE_PRINTED && !REEXEC_PARENT && /^AWESOMATE (CONNECT|SWITCH): /.test(line)) {
const active = activeLine();
if (active) emit(redactSecrets(active));
}
emit(line);
};
}
process.on('exit', (code) => {
if (!REEXEC_PARENT && !ACTIVE_PRINTED) {
const active = activeLine();
if (active) console.log(active);
}
// The re-exec parent's child already wrote the full log; the parent's one argv line must not replace it.
if (REEXEC_PARENT) return;
try {
CONNECT_LOG.push(`exit: ${code}`);
mkdirSync(dir, { recursive: true, mode: 0o700 });
// --update and --switch keep their own logs, so they never replace a failed connect's.
const logName = UPDATE_ONLY ? 'last-update.log' : SWITCH_ONLY ? 'last-switch.log' : 'last-connect.log';
writeFileSync(join(dir, logName), `${CONNECT_LOG.join('\n')}\n`, { mode: 0o600 });
} catch { /* logging must never block exit */ }
});
const SUPPORT_HINT =
`Stuck? Generate a support report: node ${FIRST_SKILLS_DIR}/awesomate-hosting/scripts/support-report.mjs --note "<what happened>" (add --submit to send it to Awesomate and get a reference ID).`;
// ---------------------------------------------------------------------------
// Proxy-aware fetch. Node's built-in fetch does NOT honor HTTP(S)_PROXY:
// in sandboxes that force egress through a proxy, requests bypass it and the
// gateway answers 403, which looks exactly like a credential failure. Route
// through undici's EnvHttpProxyAgent when a proxy env var is set.
// ---------------------------------------------------------------------------
const PROXY_URL =
process.env.HTTPS_PROXY || process.env.https_proxy || process.env.HTTP_PROXY || process.env.http_proxy || '';
let doFetch = fetch;
async function initProxySupport() {
if (!PROXY_URL) return;
// undici tags EnvHttpProxyAgent experimental and warns on construction:
// noise in the middle of connect output. Keep every other warning.
process.removeAllListeners('warning');
process.on('warning', (w) => {
if (!/EnvHttpProxyAgent/.test(String(w.message))) console.error(w.stack ?? String(w.message));
});
try {
// Resolves when running from the npm package (undici is a dependency).
const undici = await import('undici');
const dispatcher = new undici.EnvHttpProxyAgent();
doFetch = (url, opts = {}) => undici.fetch(url, { ...opts, dispatcher });
console.log(`• Egress proxy detected: routing hub requests through ${PROXY_URL}.`);
} catch {
// Running from an installed skill copy with no node_modules. Re-exec once
// with NODE_USE_ENV_PROXY=1 (built-in fetch honors proxies on newer Node;
// the env var is ignored where unsupported, so this is at worst a no-op).
if (process.env.AWESOMATE_PROXY_REEXEC !== '1') {
const r = spawnSync(process.execPath, process.argv.slice(1), {
stdio: 'inherit',
env: { ...process.env, NODE_USE_ENV_PROXY: '1', AWESOMATE_PROXY_REEXEC: '1' },
});
REEXEC_PARENT = true;
process.exit(r.status ?? 1);
}
console.log(`• Egress proxy detected (${PROXY_URL}) but proxy support is unavailable in this runtime, so requests may be blocked by the gateway.`);
}
}
const proxyAdvice = () =>
PROXY_URL
? ` An egress proxy is configured (${PROXY_URL}); if this persists, re-run the command prefixed with NODE_USE_ENV_PROXY=1.`
: '';
async function request(method, path, { body, token, base = apiBase } = {}) {
const headers = { 'Content-Type': 'application/json' };
if (token) headers.Authorization = `Bearer ${token}`;
let res;
try {
res = await doFetch(`${base}${path}`, {
method,
headers,
body: method === 'GET' ? undefined : JSON.stringify(body ?? {}),
});
} catch (err) {
const detail = err?.cause?.code ?? err?.code ?? err?.message ?? 'network error';
throw new Error(`Could not reach ${base} (${detail}). This is a NETWORK problem, not a code/token problem.${proxyAdvice()}`);
}
const text = await res.text();
let json;
try { json = text ? JSON.parse(text) : null; } catch { json = text; }
const apiError = json && typeof json === 'object' && typeof json.error === 'string' ? json.error : null;
if (!res.ok) {
if (apiError) {
const e = new Error(`${path} failed: ${apiError}`);
e.isApiError = true;
e.status = res.status;
throw e;
}
// No structured error body → the response almost certainly came from an
// egress gateway / firewall, not from the hub. Say so instead of blaming
// the code: that misdirection is expensive.
throw new Error(
`${path} returned HTTP ${res.status} without an API error body: the request likely never reached hub.awesomate.ai (egress proxy or firewall in the way).${proxyAdvice()}`,
);
}
return json;
}
const post = (path, opts) => request('POST', path, opts);
const get = (path, opts) => request('GET', path, opts);
function readJsonFile(path) {
try {
const parsed = JSON.parse(readFileSync(path, 'utf8'));
return parsed && typeof parsed === 'object' ? parsed : null;
} catch { return null; }
}
/** Atomic JSON write (tmp + rename) so a crash can't leave a torn file. */
function writeJsonFile(path, value, mode) {
const tmp = `${path}.tmp-${process.pid}`;
// A mode is set as the temp file is made, so a file of keys is never readable by others, even for
// the moment between the rename and a later chmod.
writeFileSync(tmp, `${JSON.stringify(value, null, 2)}\n`, mode === undefined ? undefined : { mode });
renameSync(tmp, path);
}
/**
* Merge one account profile into credentials.json (v2 multi-profile shape).
* Existing profiles for OTHER accounts are preserved: connecting a second
* account must never disconnect the first. Top-level v1 fields are kept as a
* mirror of the default profile because already-installed skill scripts
* (ssh-connect.sh / deploy.sh / pull-live.sh copies from older versions) read
* them directly until the skill is refreshed.
*/
function mergeProfile(profile) {
// A file that cannot be read would be written over with only this account in it: every other
// saved account gone without a word. Keep a copy first and say where it is.
if (readCredentials(credPath).unreadable) {
const copy = `${credPath}.unreadable-${Date.now()}`;
try {
cpSync(credPath, copy);
chmodSync(copy, 0o600);
console.log(`! ${credPath} could not be read, so it is being replaced. Its old contents are kept at ${copy}: any account saved in it can be connected again from its own hub page.`);
} catch (err) {
throw new Error(`${credPath} could not be read and could not be copied aside (${err.message}). Nothing was changed: fix or move that file, then run the same command again.`);
}
}
const existing = readJsonFile(credPath) ?? {};
const profiles = { ...(existing.profiles ?? {}) };
// v1 file: lift the old top-level account into the profiles map first so it
// survives this connect.
if (!existing.profiles && typeof existing.pat === 'string' && existing.pat) {
const legacyKey = existing.slug || 'default';
profiles[legacyKey] = {
apiBase: existing.apiBase, pat: existing.pat, contactId: existing.contactId,
slug: existing.slug, email: existing.email, plan: existing.plan,
expiresAt: existing.expiresAt, cpanel: existing.cpanel, ssh: existing.ssh,
};
}
profiles[profile.slug] = { ...(profiles[profile.slug] ?? {}), ...profile };
let defaultProfile = existing.defaultProfile;
if (defaultProfile && !profiles[defaultProfile]) defaultProfile = undefined;
if (!defaultProfile && Object.keys(profiles).length === 1) defaultProfile = profile.slug;
if (existing.defaultProfile && existing.defaultProfile !== profile.slug && profiles[existing.defaultProfile]) {
console.log(`• defaultProfile stays "${existing.defaultProfile}". This folder is pinned to "${profile.slug}" instead.`);
}
// The v1 mirror (read by older helpers that know only one account) follows the default profile
// when one is set, else the account it already named, else the account just connected. It never
// moves to a newly connected account while another one it named is still saved: that move was
// a silent account switch for every legacy reader.
const previousMirror = typeof existing.slug === 'string' && profiles[existing.slug] ? profiles[existing.slug] : null;
const mirrorSource = (defaultProfile && profiles[defaultProfile]) || previousMirror || profile;
const creds = {
version: 2,
...(defaultProfile ? { defaultProfile } : {}),
profiles,
apiBase: mirrorSource.apiBase, pat: mirrorSource.pat, contactId: mirrorSource.contactId,
slug: mirrorSource.slug, email: mirrorSource.email ?? null, plan: mirrorSource.plan,
cpanel: mirrorSource.cpanel ?? null, expiresAt: mirrorSource.expiresAt ?? null,
...(mirrorSource.ssh ? { ssh: mirrorSource.ssh } : {}),
};
mkdirSync(dir, { recursive: true, mode: 0o700 });
chmodSync(dir, 0o700);
writeJsonFile(credPath, creds, 0o600);
chmodSync(credPath, 0o600);
return creds;
}
/**
* Pin a folder to this account. --pin-dir overrides the implicit cwd (useful
* when the bootstrap is run from somewhere other than the project root).
* Never pins $HOME.
*/
function writePin(slug) {
const target = resolve(pinDirArg || process.cwd());
if (pinDirArg && !(existsSync(target) && statSync(target).isDirectory())) {
console.log(`• --pin-dir ${pinDirArg} is not an existing directory, so no pin was written. Create it and add ${PIN_FILENAME} with {"account": "${slug}"}.`);
return null;
}
if (target === resolve(homedir())) {
console.log(`• This is the home directory, so no ${PIN_FILENAME} pin was written. Run it again from the project folder (or pass --pin-dir) to pin that folder.`);
return null;
}
const pinPath = join(target, PIN_FILENAME);
const before = readJsonFile(pinPath);
const old = before && typeof before === 'object' && !Array.isArray(before) ? before : {};
const oldAccount = typeof old.account === 'string' ? old.account : null;
// Anything else the pin carries (a brand, say) is kept for the same account. A brand belongs to
// the account it was set for, so moving the pin to another account drops it, and says so.
const { brand, ...rest } = old;
const keepBrand = brand !== undefined && oldAccount === slug;
writeJsonFile(pinPath, { ...rest, ...(keepBrand ? { brand } : {}), version: 1, account: slug });
if (oldAccount && oldAccount !== slug) {
console.log(`✓ Re-pinned ${target} from account "${oldAccount}" to "${slug}" (${PIN_FILENAME}).`);
if (brand !== undefined) console.log(`• The pin also named the brand "${brand}", which belongs to "${oldAccount}", so it was taken off. If "${slug}" has brands, add its "brand" to ${PIN_FILENAME}.`);
} else {
console.log(`✓ Pinned ${target} to account "${slug}" (${PIN_FILENAME}).`);
}
return pinPath;
}
/** Which account a session started in the pin folder uses right now. */
function activeHere() {
return activeAccount({ credPath, cwd: resolve(pinDirArg || process.cwd()), home: homedir(), env: process.env });
}
/** What makes a session here use another account than the one just written, or null. */
function overriddenBy(active, target) {
if (active.slug === target) return null;
if (active.source === 'env-pat') return 'AWESOMATE_PAT is set';
if (active.source === 'env-account') return `AWESOMATE_ACCOUNT is set to "${process.env.AWESOMATE_ACCOUNT}"`;
if (active.source === 'pin') return `${active.pinPath} names ${active.slug ? `"${active.slug}"` : 'another account'}`;
return active.problem ?? `this folder reads "${active.slug}"`;
}
const SWITCH_CMD = 'npx -y --package=@awesomate/hosting-mcp awesomate-hosting-bootstrap --switch';
/**
* Never move a folder from one account to another without saying so: name the account it used,
* say its key is still saved, and give the one command that switches back.
*/
function warnIfSwitched(before, after) {
if (!before.slug || before.slug === after.slug) return;
const savedNow = readCredentials(credPath).profiles[before.slug];
console.log('');
console.log(`! This folder used the account "${before.slug}" before this run. It now uses "${after.slug ?? 'none'}".`);
if (savedNow) {
console.log(` The "${before.slug}" key is still saved on this computer. To switch this folder back, run:`);
console.log(` ${SWITCH_CMD} ${before.slug}${pinDirArg ? ` --pin-dir ${JSON.stringify(resolve(pinDirArg))}` : ''}`);
} else {
console.log(` No key for "${before.slug}" is saved here any more. To connect it again, copy a fresh Connect command from its own hub page (hub.awesomate.ai/claude, signed in as that account) and run it.`);
}
console.log('');
}
/**
* Copy the skill bundled alongside this script into ~/.claude/skills so Claude
* Code loads it. This runs INSIDE the already-approved bootstrap invocation, so
* there's no separate `cp` step for a permission classifier to block. Idempotent
* (overwrites an older/hand-made copy with the canonical one). Best-effort: a
* failure here never aborts the rest of setup.
*/
/**
* Where this script runs from: inside the npm package (skill/<name>/scripts), or an installed copy.
* names is the bundle's skill list (package layout only), pkgVersion its version.
*/
function bundleInfo() {
// realpathSync: npx runs the bin through a symlink (or a shim on Windows):
// resolve to the file's true location inside the package before walking up,
// or the walk lands in the npx cache's .bin dir. basename() (never
// endsWith('/skill')): Windows paths use '\', which broke the layout check
// and made every Windows bootstrap report "Skill files not found".
let selfPath = fileURLToPath(import.meta.url);
try { selfPath = realpathSync(selfPath); } catch { /* keep unresolved path */ }
const skillRoot = dirname(dirname(dirname(selfPath)));
const isPackageLayout = basename(skillRoot) === 'skill';
if (!isPackageLayout) return { skillRoot, isPackageLayout, names: null, pkgVersion: null };
let pkgVersion = null;
try {
pkgVersion = JSON.parse(readFileSync(join(dirname(skillRoot), 'package.json'), 'utf8')).version ?? null;
} catch { /* non-fatal: the marker just won't be written */ }
let names = [];
try { names = readdirSync(skillRoot).filter((n) => existsSync(join(skillRoot, n, 'SKILL.md'))); } catch { /* none */ }
return { skillRoot, isPackageLayout, names, pkgVersion };
}
/**
* Bring Muse's router, connector guide and AGENTS.md rule up to date, where Muse is on this
* computer (or --muse asks). Muse reads Claude Code's skill folder when this run installed there.
*/
function museSkillsDir() {
return skillsDirFor(CLIENTS.includes('claude') ? 'claude' : CLIENTS[0], homedir());
}
// A missing ~/AGENTS.md rule is never fixed by running the same command again (the file is made
// only with --muse, MUSE-BOOTSTRAP-1), so it warns and the run still succeeds. Every other Muse
// issue fails it.
const MUSE_WARNINGS = new Set(['muse-agents-md']);
function updateMuse() {
const muse = detectMuse({ argv: process.argv, env: process.env, home: homedir() });
if (!muse.on) return { on: false, issues: [], warnings: [] };
const { names, pkgVersion } = bundleInfo();
try {
const r = refreshMuse({ home: homedir(), skillsDir: museSkillsDir(), names, pkgVersion, forced: muse.forced });
return { on: true, issues: r.issues.filter((i) => !MUSE_WARNINGS.has(i)), warnings: r.issues.filter((i) => MUSE_WARNINGS.has(i)) };
} catch (err) {
console.log(`✗ Muse: could not write the Muse files (${err.message}).`);
return { on: true, issues: ['muse-files'], warnings: [] };
}
}
function installSkill() {
// pkgVersion is stamped into each installed skill as .installed-version. The MCP server (always
// latest via unpinned npx) compares it against its own version and reports skill.updateAvailable
// in awesomate_get_context.
const { skillRoot, isPackageLayout, pkgVersion } = bundleInfo();
if (!isPackageLayout) {
// Running from an INSTALLED copy (~/.claude/skills/...): the siblings here
// are the user's other skills, not the bundle, and this skill's src IS its
// dest, so an "update" from here silently refreshed nothing while
// reporting success. Say so honestly and point at the two real paths.
console.log('• This is the installed copy of the skill: it cannot refresh the bundle from here.');
console.log(` Update instead with the awesomate_skill_update tool in ${CLIENT_NAMES}, or re-run the`);
const clientFlag = CLIENTS.length > 1 ? ' --client both' : CLIENTS[0] === 'codex' ? ' --client codex' : '';
console.log(` full bootstrap: npx -y --package=@awesomate/hosting-mcp awesomate-hosting-bootstrap --update${clientFlag}`);
return false;
}
const bundled = readdirSync(skillRoot);
let installed = 0;
for (const client of CLIENTS) for (const name of bundled) {
const src = join(skillRoot, name);
if (!existsSync(join(src, 'SKILL.md'))) continue;
const dest = join(skillsDirFor(client, homedir()), name);
if (src === dest) { installed += 1; continue; } // already running from the installed copy
mkdirSync(dirname(dest), { recursive: true });
cpSync(src, dest, { recursive: true, force: true });
// cpSync never deletes: drop what the bundle no longer ships (awesomate_skill_update does the same).
pruneStale(src, dest);
// Skill text names ~/.claude/skills paths; a Codex copy names its own folder.
if (client === 'codex') rewriteTree(dest);
// Make the shell/mjs helpers executable (npm can publish them non-+x).
const scriptsDir = join(dest, 'scripts');
if (existsSync(scriptsDir)) {
for (const f of readdirSync(scriptsDir)) {
if (/\.(sh|mjs)$/.test(f)) { try { chmodSync(join(scriptsDir, f), 0o755); } catch { /* non-fatal */ } }
}
}
if (pkgVersion) {
try { writeFileSync(join(dest, '.installed-version'), `${pkgVersion}\n`); } catch { /* non-fatal */ }
}
console.log(`✓ Installed the "${name}" skill to ${dest}.`);
installed += 1;
}
if (installed === 0) {
console.log('• Skill files not found next to bootstrap, so no skill was installed (MCP still works).');
return false;
}
return true;
}
function filesUnder(dir, base = '') {
const out = [];
for (const entry of readdirSync(join(dir, base), { withFileTypes: true })) {
const rel = base ? `${base}/${entry.name}` : entry.name;
if (entry.isDirectory()) out.push(...filesUnder(dir, rel));
else out.push(rel);
}
return out;
}
function dirsUnder(dir, base = '') {
const out = [];
for (const entry of readdirSync(join(dir, base), { withFileTypes: true })) {
if (!entry.isDirectory()) continue;
const rel = base ? `${base}/${entry.name}` : entry.name;
out.push(rel, ...dirsUnder(dir, rel));
}
return out;
}
function pruneStale(src, dest) {
try {
const shipped = new Set(filesUnder(src));
for (const rel of filesUnder(dest)) {
if (rel === '.installed-version' || shipped.has(rel)) continue;
rmSync(join(dest, rel), { force: true });
}
// Folders the prune emptied (a dropped references/) go too, deepest first.
for (const dir of dirsUnder(dest).sort((a, b) => b.length - a.length)) {
try { if (readdirSync(join(dest, dir)).length === 0) rmdirSync(join(dest, dir)); } catch { /* not empty or gone */ }
}
} catch { /* pruning is best-effort: an unreadable folder must not fail the install */ }
}
function rewriteTree(dir) {
for (const entry of readdirSync(dir, { withFileTypes: true })) {
const path = join(dir, entry.name);
if (entry.isDirectory()) { rewriteTree(path); continue; }
if (!/\.(md|mjs|js|sh)$/.test(entry.name) || entry.name === NOT_REWRITTEN) continue;
try {
const text = readFileSync(path, 'utf8');
const next = rewriteForCodex(text);
if (next !== text) writeFileSync(path, next);
} catch { /* a file we cannot rewrite keeps the Claude Code path */ }
}
}
// --package= (with the =) instead of -p: the claude CLI pre-scans the FULL
// argv for its own global -p/--print flag, even after the `--` separator,
// so any `claude mcp add … -- npx -y -p pkg bin` flips it into print mode and
// it rejects the scope flag as "unknown option" (marlins bug report,
// 2026-07-28). npx treats both forms identically at runtime; the = form keeps
// the value glued to the token so these args are safe to copy anywhere.
// The explicit package must stay: this package ships two bins.
// Windows: a bare `npx` spawn fails silently (it's npx.cmd there), so the
// server never starts and the tools never appear, even after a restart.
// First observed on the first Windows client, 2026-08-19. cmd /c resolves it.
const CLEAN_ENTRY = process.platform === 'win32'
? {
command: 'cmd',
args: ['/c', 'npx', '-y', '--package=@awesomate/hosting-mcp', 'awesomate-hosting-mcp'],
}
: {
command: 'npx',
args: ['-y', '--package=@awesomate/hosting-mcp', 'awesomate-hosting-mcp'],
};
const MANUAL_ADD_JSON = JSON.stringify({ mcpServers: { 'awesomate-hosting': CLEAN_ENTRY } }, null, 2);
const MANUAL_ADD_TOML = `In ${join(codexHome(process.env, homedir()), 'config.toml')}:\n${codexEntryToml(CLEAN_ENTRY)}`;
/**
* Converge on exactly one env-free, user-scope MCP registration by editing the
* config files DIRECTLY: `claude mcp add` flag syntax has drifted between CLI
* versions (--scope/-s rejected on some), and a registration is too important
* to hang off a moving target.
*
* Legacy bootstraps baked AWESOMATE_PAT into the registration env: env beats
* credentials.json inside the server, so those registrations keep serving a
* STALE account forever after a re-pair. Remove every entry that carries the
* env var (user scope, this project's local scope + .mcp.json); entries in
* OTHER projects are reported for manual cleanup, not touched.
*/
/**
* Each client is registered where IT reads: a Claude Code registration is
* never reported as a Codex one, or the other way round. Each is tried on its
* own, so one failing never leaves the other unregistered; the failures come
* back with the manual form for that client.
*/
function ensureMcpRegistration() {
const failures = [];
if (CLIENTS.includes('codex')) {
try {
ensureCodexRegistration({ env: process.env, home: homedir(), entry: CLEAN_ENTRY });
} catch (err) {
failures.push({ client: 'codex', message: err?.message ?? String(err), manual: MANUAL_ADD_TOML });
}
}
if (CLIENTS.includes('claude')) {
try {
ensureClaudeRegistration();
} catch (err) {
failures.push({ client: 'claude', message: err?.message ?? String(err), manual: MANUAL_ADD_JSON });
}
}
return failures;
}
function ensureClaudeRegistration() {
const cwd = resolve(process.cwd());
const claudeJsonPath = join(homedir(), '.claude.json');
let cfg = {};
if (existsSync(claudeJsonPath)) {
cfg = readJsonFile(claudeJsonPath);
if (!cfg) {
throw new Error(`${claudeJsonPath} exists but is not valid JSON, so it was not rewritten. Fix the file, then add:\n${MANUAL_ADD_JSON}`);
}
}
const entry = cfg.mcpServers?.['awesomate-hosting'];
const entryIsClean =
entry &&
!entry.env?.AWESOMATE_PAT &&
JSON.stringify(entry.args ?? []).includes('awesomate-hosting-mcp') &&
// A bare-npx registration is broken on Windows: rewrite it.
(process.platform !== 'win32' || entry.command === 'cmd');
let changed = false;
if (!entryIsClean) {
cfg.mcpServers = { ...(cfg.mcpServers ?? {}), 'awesomate-hosting': CLEAN_ENTRY };
changed = true;
console.log(
entry?.env?.AWESOMATE_PAT
? '✓ Replaced the legacy user-scope registration (had a token baked into its env) with an env-free one.'
: '✓ Registered the Awesomate Hosting MCP server for Claude Code (user scope, env-free: the folder pin picks the account).',
);
} else {
console.log('✓ MCP server already registered for Claude Code (user scope, env-free): account selection comes from the folder pin.');
}
// This project's local-scope entry (lives under projects[cwd] in ~/.claude.json).
const localEntry = cfg.projects?.[cwd]?.mcpServers?.['awesomate-hosting'];
if (localEntry?.env?.AWESOMATE_PAT) {
delete cfg.projects[cwd].mcpServers['awesomate-hosting'];
changed = true;
console.log("✓ Removed this project's legacy local-scope registration (token baked into env).");
}
// Other projects: report, don't touch.
for (const [projectDir, project] of Object.entries(cfg.projects ?? {})) {
if (resolve(projectDir) === cwd) continue;
if (project?.mcpServers?.['awesomate-hosting']?.env?.AWESOMATE_PAT) {
console.log(`• ${projectDir} still has a legacy registration with a baked-in token. From that folder run the Connect command again, or remove the awesomate-hosting entry from its local MCP config.`);
}
}
if (changed) {
writeJsonFile(claudeJsonPath, cfg);
// Read back and verify: never trust a write (or a CLI exit code) alone.
const verify = readJsonFile(claudeJsonPath);
const written = verify?.mcpServers?.['awesomate-hosting'];
if (!written || written.command !== CLEAN_ENTRY.command || !JSON.stringify(written.args ?? []).includes('awesomate-hosting-mcp')) {
throw new Error(`wrote ${claudeJsonPath} but the awesomate-hosting entry did not verify on read-back`);
}
}
// Project-scope .mcp.json in cwd.
const mcpJsonPath = join(cwd, '.mcp.json');
const mcpJson = readJsonFile(mcpJsonPath);
if (mcpJson?.mcpServers?.['awesomate-hosting']?.env?.AWESOMATE_PAT) {
delete mcpJson.mcpServers['awesomate-hosting'];
writeJsonFile(mcpJsonPath, mcpJson);
console.log('✓ Removed the legacy project-scope (.mcp.json) registration (token baked into env).');
}
}
/**
* The person's other businesses not on this machine yet (multi-entity step 1.12), each with the
* link to connect Claude Code to it in the hub. Read-only and best effort: the hub hands back names
* and links only, never a key, and connecting stays one click per business, under its own rules.
*/
async function printOtherBusinesses(pat) {
try {
// At most 5 s: the result line below must never wait on this extra.
let timer;
const r = await Promise.race([
get('/api/auth/businesses/connectable', { token: pat }),
new Promise((resolve) => { timer = setTimeout(() => resolve(null), 5000); }),
]).finally(() => clearTimeout(timer));
if (!r?.available || !Array.isArray(r.businesses) || r.businesses.length < 2) return;
const have = new Set(Object.keys(readJsonFile(credPath)?.profiles ?? {}).map((k) => k.toLowerCase()));
// The same rule as businessesOnMachine (mcp/src/businesses.ts): any of its web addresses counts.
const missing = r.businesses.filter((b) => !b.current && ![b.slug, ...(b.slugs ?? [])].some((s) => s && have.has(String(s).toLowerCase())));
if (!missing.length) return;
console.log('');
console.log('You can also work on these businesses. Connect each one from its own page in the hub:');
for (const b of missing) console.log(` • ${b.name || b.slug || 'Business ' + b.contactId}: ${b.pairUrl}`);
} catch {
/* an older hub, or the list could not be read: nothing to add */
}
}
const n = (v) => (typeof v === 'number' ? String(v) : 'unknown');
/**
* Read the account back from the hub with the key as SAVED (credentials.json), the same read
* awesomate_whoami and awesomate_get_context make: slug, plan, whose key, features, attention.
* Returns { ok, lines }. Never prints the key.
*/
async function hubCheck(slug, base) {
const p = readCredentials(credPath).profiles[slug];
if (!p?.pat) return { ok: false, lines: [`✗ Hub: the key for "${slug}" could not be read back from ${credPath}.`] };
let ctx;
let timer;
try {
ctx = await Promise.race([
get('/api/hosting-access/context', { token: p.pat, base: (p.apiBase || base || apiBase).replace(/\/$/, '') }),
new Promise((_, reject) => { timer = setTimeout(() => reject(new Error('no answer within 15 seconds')), 15000); }),
]).finally(() => clearTimeout(timer));
} catch (err) {
return { ok: false, lines: [`✗ Hub: could not read the account with the saved key (${err.message}).`] };
}
if (!ctx || typeof ctx !== 'object') return { ok: false, lines: ['✗ Hub: the account read back empty.'] };
if (ctx.slug && ctx.slug !== slug) return { ok: false, lines: [`✗ Hub: the saved key reads as account "${ctx.slug}", not "${slug}".`] };
const k = ctx.key && typeof ctx.key === 'object' ? ctx.key : {};
const keyLine = k.holder === 'person'
? `${k.name || k.email || 'a team member'}'s own key (team member, ${k.level === 'full' ? 'full access' : 'view only'})`
: `the account owner's key${ctx.email ? ` (${ctx.email})` : ''}`;
const lines = [`✓ Hub: account ${ctx.slug ?? slug}, plan ${ctx.plan ?? 'unknown'}, ${keyLine}.`];
if (ctx.features && typeof ctx.features === 'object') {
const entries = Object.entries(ctx.features).filter(([, f]) => f && typeof f === 'object');
const off = entries.filter(([, f]) => f.available === false).map(([key]) => key);
lines.push(` Features: ${entries.length - off.length} on, ${off.length} off${off.length ? ` (${off.slice(0, 8).join(', ')}${off.length > 8 ? ', and more' : ''})` : ''}.`);
} else {
lines.push(' Features: the hub did not say.');
}
const a = ctx.attention && typeof ctx.attention === 'object' ? ctx.attention : {};
lines.push(` Attention: ${n(a.unreadNotifications)} unread notifications, ${n(a.erroringWorkflows7d)} workflows erroring this week (${n(a.failedRuns7d)} failed runs), key expires in ${n(a.patExpiresInDays)} days.`);
return { ok: true, lines };
}
/** The checks that end a connect. Each failure is named, so nothing is left half connected without a word. */
async function finalChecks(slug, muse) {
console.log('');
console.log('Checking the connection:');
const failed = [];
const hub = await hubCheck(slug);
for (const line of hub.lines) console.log(line);
if (!hub.ok) failed.push('verify-hub');
if (muse.on) {
for (const c of museChecks({ home: homedir(), skillsDir: museSkillsDir(), names: bundleInfo().names })) {
// No ~/AGENTS.md at all is a warning (made only with --muse); a file without the rule is not.
const warnOnly = !c.ok && MUSE_WARNINGS.has(c.key) && !existsSync(join(homedir(), 'AGENTS.md'));
console.log(`${c.ok ? '✓' : warnOnly ? '•' : '✗'} ${c.line}`);
if (!c.ok && !warnOnly) failed.push(`verify-${c.key}`);
}
}
return failed;
}
async function main() {
await initProxySupport();
const issues = [];
// Which account this folder used before anything was written, to say so if it changes.
const activeBefore = activeHere();
// ── Identity: redeem a code, or verify a resumed PAT ─────────────────────
let redeemed;
if (resumePat) {
console.log(`Resuming with an existing access token: verifying against ${apiBase} …`);
const ctx = await get('/api/hosting-access/context', { token: resumePat });
redeemed = {
pat: resumePat,
contactId: ctx.contactId,
slug: ctx.slug ?? null,
email: ctx.email ?? null,
plan: ctx.plan,
shellAccess: Boolean(ctx.capabilities?.shell),
cpanel: ctx.cpanel ?? null,
expiresAt: ctx.patExpiresAt ?? null,
...(ctx.key?.holder === 'person' ? { keyKind: 'person_device' } : {}),
};
} else {
console.log(`Redeeming setup code against ${apiBase} …`);
redeemed = await post('/api/hosting-access/redeem', {
body: { code, machineLabel: `${CLIENT_NAMES} on ${hostname()}` },
});
}
const slug = redeemed.slug ?? null;
if (!slug) {
console.error('The hub did not return an account slug, so no profile can be stored safely. Contact Awesomate support.');
console.error('AWESOMATE CONNECT: FAILED reason=no-slug');
process.exit(1);
}
// Wrong-account guard: abort BEFORE writing anything.
if (expectedAccount && expectedAccount !== slug) {
console.error(`This ${resumePat ? 'token' : 'setup code'} belongs to account "${slug}" but this connect was for "${expectedAccount}".`);
console.error(`You are probably logged into the wrong hub account. Log into ${expectedAccount}'s hub account and copy a fresh Connect prompt.`);
console.error(`AWESOMATE CONNECT: FAILED reason=account-mismatch expected=${expectedAccount} got=${slug}`);
process.exit(1);
}
// Server-side identity check with the NEW token before trusting it (the
// resume path already did exactly this to build `redeemed`).
if (!resumePat) {
let context = null;
try {
context = await get('/api/hosting-access/context', { token: redeemed.pat });
} catch (err) {
console.error(`Token verification failed (${err.message}), so it was not stored. Run the same command again (setup codes stay valid for 10 minutes).`);
console.error('AWESOMATE CONNECT: FAILED reason=verify-failed');
process.exit(1);
}
const ctxSlug = context?.slug ?? null;
if (ctxSlug && ctxSlug !== slug) {
console.error(`Identity mismatch: redeem said "${slug}" but the token resolves to "${ctxSlug}". It was not stored. Contact Awesomate support.`);
console.error('AWESOMATE CONNECT: FAILED reason=identity-mismatch');
process.exit(1);
}
redeemed.email = redeemed.email ?? context?.email ?? null;
}
// One computer, two people (per-person keys design §6.1): never silently swap whose key this
// account uses here. An owner and a team member on a shared computer each keep their own.
const saved = readJsonFile(credPath) ?? {};
const before = (saved.profiles ?? {})[slug] ?? (saved.slug === slug ? saved : null);
const beforeEmail = typeof before?.email === 'string' ? before.email.trim().toLowerCase() : null;
const newEmail = typeof redeemed.email === 'string' ? redeemed.email.trim().toLowerCase() : null;
const replacing = Boolean(beforeEmail && newEmail && beforeEmail !== newEmail);
if (replacing && !process.argv.includes('--replace')) {
console.error(`This computer is already connected to "${slug}" as ${beforeEmail}. Connecting as ${newEmail} would replace that key here.`);
console.error('Ask the person at this computer which key should stay. Only on their clear yes, run the same command again with --replace; otherwise connect from your own user account on this computer.');
console.error(`The new key for ${newEmail} was made but not saved here. If it will not be used, remove it in the hub: Settings, Account, Your Claude Code.`);
console.error('AWESOMATE CONNECT: FAILED reason=profile-belongs-to-someone-else');
process.exit(1);
}
const profile = {
apiBase,
pat: redeemed.pat,
contactId: redeemed.contactId,
slug,
email: redeemed.email ?? null,
plan: redeemed.plan,
cpanel: redeemed.cpanel ?? null,
expiresAt: redeemed.expiresAt ?? null,
// Someone else's SSH key never carries over to this person's profile.
...(replacing ? { ssh: undefined } : {}),
};
mergeProfile(profile);
console.log(`✓ Access token stored as profile "${slug}" in ${credPath} (chmod 600). Plan: ${redeemed.plan}.`);
if (replacing) {
console.log(`! The key saved for "${slug}" on this computer was ${beforeEmail}'s. It is now ${newEmail}'s (--replace).`);
console.log(` ${beforeEmail} can connect again from their own user account on this computer: hub.awesomate.ai/claude, signed in as themselves.`);
}
const pinPath = writePin(slug);
warnIfSwitched(activeBefore, activeHere());
// Install the skill + register the MCP server FIRST: these always work and
// don't depend on hosting being fully provisioned. Neither is allowed to
// strand the other or SSH: every step from here is collected, not fatal.
try { installSkill(); } catch (err) {
console.log(`• Could not auto-install the skill (${err.message}). Continuing: you can copy skill/ by hand.`);
}
const failures = ensureMcpRegistration();
if (failures.length) issues.push('mcp-registration');
for (const f of failures) {
console.error(`• ${clientLabel(f.client)} MCP registration failed: ${f.message}`);
console.error(` Add it manually (no token goes in the config: the folder pin picks the account):\n${f.manual}`);
}
// SSH key (Support Plus+): best-effort. If it fails (e.g. hosting not fully
// provisioned yet, or no ssh tooling in this environment), keep the token,
// skill and MCP: deploy and shell just aren't ready until it's registered,
// which the skill can retry later.
if (redeemed.shellAccess) {
try {
if (!existsSync(keyPath)) {
mkdirSync(keysDir, { recursive: true, mode: 0o700 });
execFileSync('ssh-keygen', ['-t', 'ed25519', '-f', keyPath, '-N', '', '-C', `awesomate:${slug}`], { stdio: 'pipe' });
chmodSync(keyPath, 0o600);
}
const publicKey = readFileSync(`${keyPath}.pub`, 'utf8').trim();
const reg = await post('/api/hosting-access/ssh-keys', {
token: redeemed.pat,
body: { publicKey, label: `${CLIENT_NAMES} on ${hostname()}` },
});
profile.ssh = { host: reg.sshHost, user: reg.sshUser, port: reg.sshPort ?? 22, keyPath, fingerprint: reg.fingerprint };
mergeProfile(profile);
console.log(`✓ SSH key authorized on ${reg.sshUser}@${reg.sshHost} (jailed to your account).`);
} catch (err) {
if (err?.code === 'ENOENT') {
console.log('• No ssh-keygen in this environment, so SSH setup was skipped. Deploy and shell need a real workstation. Reads and management calls work fine here.');
} else {
console.log(`• SSH key not registered yet: ${err.message}`);
console.log(' Everything else is set up. Once your hosting is ready, copy a fresh Connect command from hub.awesomate.ai/claude and run it again: that adds the SSH key. Never paste an access token into the chat.');
console.log(' If your hosting never finishes setting up, contact Awesomate support.');
}
}
} else if (redeemed.keyKind === 'person_device') {
console.log('• This is your own key: it does what you can do in the hub. SSH and deploys stay with the account owner.');
} else {
console.log('• Plan has no shell access: read and status mode. Upgrade to Support Plus for SSH and deploys.');
}
const muse = updateMuse();
issues.push(...muse.issues);
for (const f of await finalChecks(slug, muse)) if (!issues.includes(f) && !issues.includes(f.replace(/^verify-/, ''))) issues.push(f);
const who = profile.email ? `${slug} (${profile.email}, plan ${redeemed.plan})` : `${slug} (plan ${redeemed.plan})`;
console.log(`\n${issues.length ? '•' : '✓'} Connected: ${who}${pinPath ? `, pinned ${dirname(pinPath)}` : ''}`);
if (issues.length) {
console.log(`Setup is NOT complete: ${issues.join(', ')}. The lines marked ✗ or • above say what is missing. Fix that and run the same command again.`);
} else {
console.log('Setup complete.');
}
if (muse.on && !existsSync(join(homedir(), 'AGENTS.md'))) {
console.log('Muse can use the Awesomate tools, but there is no ~/AGENTS.md to hold the rule that has it load the awesomate skill first. To create it with that rule, run the same command again with --muse.');
}
console.log('');
console.log(`IMPORTANT: restart ${CLIENT_NAMES} now: the MCP tools load only at startup.`);
if (CLIENTS.includes('codex')) {
console.log('In Codex: type /quit, then run codex again in this folder (in the Codex app or IDE extension, start a new chat after reloading).');
}
console.log('Until the restart, builds still work: the assistant should follow');
console.log(`${FIRST_SKILLS_DIR}/awesomate-n8n/references/rest-fallback.md (n8n) or`);
console.log(`${FIRST_SKILLS_DIR}/awesomate-hosting/references/rest-fallback.md (hosting).`);
console.log('After restarting: run awesomate_whoami to confirm the account, then ask for your first build.');
console.log(`(The skills work in your current session right away via their REST fallback; restart ${CLIENT_NAMES} when convenient to load the MCP tools.)`);
if (muse.on) {
console.log('Muse needs no restart: it calls the tools through ~/workspace/custom-connectors/custom.awesomate (see CONNECTOR.md there), starting with awesomate_whoami, then awesomate_get_context.');
}
// After the restart notice, so a slow hub never delays the one instruction the user must act on.
await printOtherBusinesses(redeemed.pat);
if (issues.length) {
console.log(SUPPORT_HINT);
console.log(`AWESOMATE CONNECT: PARTIAL account=${slug} pin=${pinPath ?? 'none'} issues=${issues.join(',')}`);
process.exit(1);
}
console.log(`AWESOMATE CONNECT: SUCCESS account=${slug} pin=${pinPath ?? 'none'}`);
}
// --update: refresh the installed skills from this package and exit, no
// setup code, no registration, no token. The no-MCP fallback for the
// awesomate_skill_update tool. Muse's router follows the skills it installed.
function runUpdate() {
try {
installSkill();
// Also converge the MCP registration: --update is the no-token repair
// path, and a broken registration (e.g. bare-npx on Windows) is exactly
// what people run it to fix.
for (const f of ensureMcpRegistration()) {
console.error(`Skill files refreshed, but the ${clientLabel(f.client)} MCP registration could not be updated: ${f.message}`);
console.error(`Add it by hand:\n${f.manual}`);
}
const muse = updateMuse();
console.log(`Skills refreshed. New content applies in your next ${CLIENT_NAMES} session.`);
const museAll = [...muse.issues, ...muse.warnings];
if (museAll.length) {
console.log(`Muse is not fully set up: ${museAll.join(', ')}. The lines marked ✗ or • above say what is missing.`);
if (muse.issues.length) process.exit(1);
}
process.exit(0);
} catch (err) {
console.error('Skill refresh failed:', err?.message ?? err);
process.exit(1);
}
}
// --switch <slug>: use an account whose key is already saved here, in this folder (or --pin-dir).
// From the home directory, where no pin is written, it becomes the default account instead.
// No setup code and no new key: the saved key is read back from the hub to prove it still works.
async function runSwitch(target) {
await initProxySupport();
const creds = readCredentials(credPath);
if (creds.unreadable) {
console.error(`${credPath} could not be read, so there is nothing to switch to. Copy a fresh Connect command from hub.awesomate.ai/claude and run it.`);
console.error('AWESOMATE SWITCH: FAILED reason=unreadable-credentials');
process.exit(1);
}
if (!creds.profiles[target]) {
const saved = Object.keys(creds.profiles);
console.error(`No key for "${target}" is saved on this computer.${saved.length ? ` Saved here: ${saved.join(', ')}.` : ''} To add it, copy a fresh Connect command from that account's hub page (hub.awesomate.ai/claude, signed in as it) and run it.`);
console.error('AWESOMATE SWITCH: FAILED reason=no-profile');
process.exit(1);
}
const activeBefore = activeHere();
const home = resolve(pinDirArg || process.cwd()) === resolve(homedir());
let pinPath = null;
if (home) {
const file = readJsonFile(credPath) ?? {};
const p = creds.profiles[target];
writeJsonFile(credPath, {
...file,
defaultProfile: target,
apiBase: p.apiBase, pat: p.pat, contactId: p.contactId, slug: p.slug ?? target, email: p.email ?? null,
plan: p.plan, cpanel: p.cpanel ?? null, expiresAt: p.expiresAt ?? null, ...(p.ssh ? { ssh: p.ssh } : { ssh: undefined }),
}, 0o600);
chmodSync(credPath, 0o600);
console.log(`✓ "${target}" is now the default account on this computer (folders with no pin read it). Changes still need a pinned folder: run --switch from the project folder to pin it.`);
} else {
pinPath = writePin(target);
if (!pinPath) {
console.error('AWESOMATE SWITCH: FAILED reason=no-pin');
process.exit(1);
}
}
const activeAfter = activeHere();
warnIfSwitched(activeBefore, activeAfter);
const issues = [];
// An environment variable, or a pin above this folder, outranks what was just written.
const overridden = overriddenBy(activeAfter, target);
if (overridden) {
issues.push('overridden');
console.log(`! "${target}" is saved as ${home ? 'the default account' : 'this folder\'s account'}, but ${overridden}, so sessions started here still use ${activeAfter.slug ? `"${activeAfter.slug}"` : 'no account'}. Remove that and run --switch again.`);
}
console.log('');
console.log('Checking the account:');
const hub = await hubCheck(target, creds.profiles[target].apiBase);
for (const line of hub.lines) console.log(line);
console.log(`Restart ${CLIENT_NAMES} (or Muse) so it picks up the account.`);
if (!hub.ok) {
issues.push('verify-hub');
console.log(`The switch is written, but the saved key for "${target}" did not check out. Copy a fresh Connect command from that account's hub page and run it.`);
}
if (issues.length) {
console.log(`AWESOMATE SWITCH: PARTIAL account=${target} pin=${pinPath ?? 'none'} issues=${issues.join(',')}`);
process.exit(1);
}
console.log(`AWESOMATE SWITCH: SUCCESS account=${target} pin=${pinPath ?? 'none'}`);
}
if (UPDATE_ONLY) runUpdate();
else if (SWITCH_ONLY) runSwitch(switchTo).catch((err) => {
console.error('Switch failed:', err.message);
console.error('AWESOMATE SWITCH: FAILED reason=error');
process.exit(1);
});
else main().catch((err) => {
console.error('Bootstrap failed:', err.message);
if (err.isApiError && err.status === 401) {
console.error('Grab a fresh code from hub.awesomate.ai/claude: codes last 10 minutes (and stay re-runnable within that window).');
}
console.error(SUPPORT_HINT);
console.error('AWESOMATE CONNECT: FAILED reason=error');
process.exit(1);
});