@awesomate/hosting-mcp 0.172.46 → 0.172.66

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * Awesomate Hosting — one-time bootstrap.
3
+ * Awesomate Hosting: one-time bootstrap.
4
4
  *
5
5
  * Redeems the setup code from the hub's "Connect Claude Code" prompt for a
6
6
  * durable, scoped access token; stores it as a PROFILE (multi-account safe);
@@ -10,11 +10,19 @@
10
10
  * only secret that ever crossed the clipboard, and it's short-lived. The
11
11
  * access token itself is never printed.
12
12
  *
13
- * Usage (Claude runs this — the user doesn't touch a terminal):
14
- * node bootstrap.mjs --code amt_bs_XXXX [--account <slug>] [--pin-dir <dir>] [--replace] [--client codex|claude|both]
13
+ * Usage (Claude runs this, the user doesn't touch a terminal):
14
+ * node bootstrap.mjs --code amt_bs_XXXX [--account <slug>] [--pin-dir <dir>] [--replace] [--client codex|claude|both] [--muse | --no-muse]
15
15
  * node bootstrap.mjs --pat <token> [--account <slug>] # resume: skip redeem
16
+ * node bootstrap.mjs --switch <slug> [--pin-dir <dir>] # use an account already saved here
17
+ * node bootstrap.mjs --update [--muse | --no-muse] # refresh the skills, no token
16
18
  *
17
- * --account asserts WHICH account this connect is for — mismatch aborts before
19
+ * Muse (another agent app) gets a router skill, a connector guide and a rule
20
+ * in ~/AGENTS.md (muse.mjs), only where Muse is evidently installed or
21
+ * --muse asks for it. Every run ends by printing the account this folder
22
+ * uses, and a connect ends by reading the account back from the hub with the
23
+ * saved key.
24
+ *
25
+ * --account asserts WHICH account this connect is for: a mismatch aborts before
18
26
  * anything is written. --pat resumes a half-finished bootstrap with an
19
27
  * already-redeemed token. It exists for support on the user's own machine and
20
28
  * is never suggested in chat: a token on a command line lands in the
@@ -34,9 +42,12 @@ import { existsSync, mkdirSync, writeFileSync, chmodSync, readFileSync, cpSync,
34
42
  import { homedir, hostname } from 'node:os';
35
43
  import { join, dirname, resolve, basename } from 'node:path';
36
44
  import { fileURLToPath } from 'node:url';
45
+ import { format } from 'node:util';
37
46
  import {
38
47
  NOT_REWRITTEN, clientLabel, codexEntryToml, codexHome, detectClients, ensureCodexRegistration, rewriteForCodex, skillsDirFor,
39
48
  } from './agent-clients.mjs';
49
+ import { activeAccount, describeActive, readCredentials } from './profiles.mjs';
50
+ import { detectMuse, museChecks, refreshMuse } from './muse.mjs';
40
51
 
41
52
  function arg(name, fallback) {
42
53
  const i = process.argv.indexOf(`--${name}`);
@@ -47,6 +58,7 @@ const code = arg('code');
47
58
  const resumePat = arg('pat');
48
59
  const expectedAccount = arg('account', null);
49
60
  const pinDirArg = arg('pin-dir', null);
61
+ const switchTo = arg('switch', null);
50
62
  const apiBase = (arg('api', 'https://hub.awesomate.ai')).replace(/\/$/, '');
51
63
 
52
64
  // Which coding agent this connect is for: Codex and Claude Code read their MCP
@@ -65,8 +77,15 @@ const CLIENT_NAMES = CLIENTS.map(clientLabel).join(' and ');
65
77
  const FIRST_SKILLS_DIR = CLIENTS[0] === 'codex' ? '~/.agents/skills' : '~/.claude/skills';
66
78
 
67
79
  const UPDATE_ONLY = process.argv.includes('--update');
80
+ const SWITCH_ONLY = process.argv.includes('--switch');
81
+
82
+ if (SWITCH_ONLY && (!switchTo || switchTo.startsWith('--') || UPDATE_ONLY || code || resumePat)) {
83
+ console.error('--switch needs the account to use, on its own: --switch <slug> [--pin-dir <dir>].');
84
+ console.error('AWESOMATE SWITCH: FAILED reason=bad-switch');
85
+ process.exit(1);
86
+ }
68
87
 
69
- if (!UPDATE_ONLY && !resumePat && (!code || !code.startsWith('amt_bs_'))) {
88
+ if (!UPDATE_ONLY && !SWITCH_ONLY && !resumePat && (!code || !code.startsWith('amt_bs_'))) {
70
89
  console.error('Missing/invalid --code. Copy a fresh Connect command from hub.awesomate.ai/claude and run it again.');
71
90
  console.error('AWESOMATE CONNECT: FAILED reason=bad-code');
72
91
  process.exit(1);
@@ -85,30 +104,56 @@ const PIN_FILENAME = '.awesomate.json';
85
104
 
86
105
  // ---------------------------------------------------------------------------
87
106
  // Connect log: every run's output (redacted) lands in ~/.awesomate/
88
- // last-connect.log so a failure is diagnosable AFTER the fact — the
89
- // support-report script attaches it automatically. Tokens/codes never reach
90
- // the log: bootstrap output doesn't print them and the argv line is redacted.
107
+ // last-connect.log so a failure is diagnosable AFTER the fact: the
108
+ // support-report script attaches it automatically. Tokens and codes never
109
+ // reach the log or the screen, not even in part: bootstrap output doesn't
110
+ // print them, and the argv line and every printed line are redacted.
91
111
  // ---------------------------------------------------------------------------
92
112
  const CONNECT_LOG = [`--- awesomate connect ${new Date().toISOString()} ---`];
93
113
  function redactSecrets(s) {
94
114
  return String(s)
95
- .replace(/amt_pat_[A-Za-z0-9_-]{8,}/g, (t) => `${t.slice(0, 12)}…${t.slice(-4)}`)
96
- .replace(/amt_bs_[A-Za-z0-9_-]{4,}/g, 'amt_bs_[redacted]');
115
+ .replace(/amt_pat_[A-Za-z0-9_-]+/g, 'amt_pat_[redacted]')
116
+ .replace(/amt_bs_[A-Za-z0-9_-]+/g, 'amt_bs_[redacted]');
97
117
  }
98
118
  CONNECT_LOG.push(`argv: ${process.argv.slice(2).map(redactSecrets).join(' ')}`);
119
+ // The proxy re-exec's parent only waits for its child, which prints the line itself.
120
+ let REEXEC_PARENT = false;
121
+ // Every run says which account this folder uses (and which others are saved), so a connect that
122
+ // moved this folder to another account is never silent. It goes just before the result line, which
123
+ // stays the last line; a run with no result line (--update) prints it on the way out.
124
+ let ACTIVE_PRINTED = false;
125
+ function activeLine() {
126
+ ACTIVE_PRINTED = true;
127
+ try {
128
+ return describeActive(activeAccount({ credPath, cwd: resolve(pinDirArg || process.cwd()), home: homedir(), env: process.env }));
129
+ } catch { return null; /* the line must never block the run */ }
130
+ }
99
131
  for (const method of ['log', 'error']) {
100
132
  const original = console[method].bind(console);
133
+ const emit = (line) => { CONNECT_LOG.push(line); original(line); };
101
134
  console[method] = (...args) => {
102
- CONNECT_LOG.push(redactSecrets(args.join(' ')));
103
- original(...args);
135
+ // util.format, as console itself does: objects stay readable and an Error keeps its stack.
136
+ const line = redactSecrets(format(...args));
137
+ if (!ACTIVE_PRINTED && !REEXEC_PARENT && /^AWESOMATE (CONNECT|SWITCH): /.test(line)) {
138
+ const active = activeLine();
139
+ if (active) emit(redactSecrets(active));
140
+ }
141
+ emit(line);
104
142
  };
105
143
  }
106
144
  process.on('exit', (code) => {
145
+ if (!REEXEC_PARENT && !ACTIVE_PRINTED) {
146
+ const active = activeLine();
147
+ if (active) console.log(active);
148
+ }
149
+ // The re-exec parent's child already wrote the full log; the parent's one argv line must not replace it.
150
+ if (REEXEC_PARENT) return;
107
151
  try {
108
152
  CONNECT_LOG.push(`exit: ${code}`);
109
153
  mkdirSync(dir, { recursive: true, mode: 0o700 });
110
- // --update keeps its own log, so it never replaces a failed connect's.
111
- writeFileSync(join(dir, UPDATE_ONLY ? 'last-update.log' : 'last-connect.log'), `${CONNECT_LOG.join('\n')}\n`, { mode: 0o600 });
154
+ // --update and --switch keep their own logs, so they never replace a failed connect's.
155
+ const logName = UPDATE_ONLY ? 'last-update.log' : SWITCH_ONLY ? 'last-switch.log' : 'last-connect.log';
156
+ writeFileSync(join(dir, logName), `${CONNECT_LOG.join('\n')}\n`, { mode: 0o600 });
112
157
  } catch { /* logging must never block exit */ }
113
158
  });
114
159
 
@@ -116,7 +161,7 @@ const SUPPORT_HINT =
116
161
  `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).`;
117
162
 
118
163
  // ---------------------------------------------------------------------------
119
- // Proxy-aware fetch. Node's built-in fetch does NOT honor HTTP(S)_PROXY —
164
+ // Proxy-aware fetch. Node's built-in fetch does NOT honor HTTP(S)_PROXY:
120
165
  // in sandboxes that force egress through a proxy, requests bypass it and the
121
166
  // gateway answers 403, which looks exactly like a credential failure. Route
122
167
  // through undici's EnvHttpProxyAgent when a proxy env var is set.
@@ -127,7 +172,7 @@ let doFetch = fetch;
127
172
 
128
173
  async function initProxySupport() {
129
174
  if (!PROXY_URL) return;
130
- // undici tags EnvHttpProxyAgent experimental and warns on construction —
175
+ // undici tags EnvHttpProxyAgent experimental and warns on construction:
131
176
  // noise in the middle of connect output. Keep every other warning.
132
177
  process.removeAllListeners('warning');
133
178
  process.on('warning', (w) => {
@@ -138,7 +183,7 @@ async function initProxySupport() {
138
183
  const undici = await import('undici');
139
184
  const dispatcher = new undici.EnvHttpProxyAgent();
140
185
  doFetch = (url, opts = {}) => undici.fetch(url, { ...opts, dispatcher });
141
- console.log(`• Egress proxy detected — routing hub requests through ${PROXY_URL}.`);
186
+ console.log(`• Egress proxy detected: routing hub requests through ${PROXY_URL}.`);
142
187
  } catch {
143
188
  // Running from an installed skill copy with no node_modules. Re-exec once
144
189
  // with NODE_USE_ENV_PROXY=1 (built-in fetch honors proxies on newer Node;
@@ -148,9 +193,10 @@ async function initProxySupport() {
148
193
  stdio: 'inherit',
149
194
  env: { ...process.env, NODE_USE_ENV_PROXY: '1', AWESOMATE_PROXY_REEXEC: '1' },
150
195
  });
196
+ REEXEC_PARENT = true;
151
197
  process.exit(r.status ?? 1);
152
198
  }
153
- console.log(`• Egress proxy detected (${PROXY_URL}) but proxy support is unavailable in this runtime — requests may be blocked by the gateway.`);
199
+ console.log(`• Egress proxy detected (${PROXY_URL}) but proxy support is unavailable in this runtime, so requests may be blocked by the gateway.`);
154
200
  }
155
201
  }
156
202
 
@@ -159,19 +205,19 @@ const proxyAdvice = () =>
159
205
  ? ` An egress proxy is configured (${PROXY_URL}); if this persists, re-run the command prefixed with NODE_USE_ENV_PROXY=1.`
160
206
  : '';
161
207
 
162
- async function request(method, path, { body, token } = {}) {
208
+ async function request(method, path, { body, token, base = apiBase } = {}) {
163
209
  const headers = { 'Content-Type': 'application/json' };
164
210
  if (token) headers.Authorization = `Bearer ${token}`;
165
211
  let res;
166
212
  try {
167
- res = await doFetch(`${apiBase}${path}`, {
213
+ res = await doFetch(`${base}${path}`, {
168
214
  method,
169
215
  headers,
170
216
  body: method === 'GET' ? undefined : JSON.stringify(body ?? {}),
171
217
  });
172
218
  } catch (err) {
173
219
  const detail = err?.cause?.code ?? err?.code ?? err?.message ?? 'network error';
174
- throw new Error(`Could not reach ${apiBase} (${detail}). This is a NETWORK problem, not a code/token problem.${proxyAdvice()}`);
220
+ throw new Error(`Could not reach ${base} (${detail}). This is a NETWORK problem, not a code/token problem.${proxyAdvice()}`);
175
221
  }
176
222
  const text = await res.text();
177
223
  let json;
@@ -186,9 +232,9 @@ async function request(method, path, { body, token } = {}) {
186
232
  }
187
233
  // No structured error body → the response almost certainly came from an
188
234
  // egress gateway / firewall, not from the hub. Say so instead of blaming
189
- // the code — that misdirection is expensive.
235
+ // the code: that misdirection is expensive.
190
236
  throw new Error(
191
- `${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()}`,
237
+ `${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()}`,
192
238
  );
193
239
  }
194
240
  return json;
@@ -204,21 +250,35 @@ function readJsonFile(path) {
204
250
  }
205
251
 
206
252
  /** Atomic JSON write (tmp + rename) so a crash can't leave a torn file. */
207
- function writeJsonFile(path, value) {
253
+ function writeJsonFile(path, value, mode) {
208
254
  const tmp = `${path}.tmp-${process.pid}`;
209
- writeFileSync(tmp, `${JSON.stringify(value, null, 2)}\n`);
255
+ // A mode is set as the temp file is made, so a file of keys is never readable by others, even for
256
+ // the moment between the rename and a later chmod.
257
+ writeFileSync(tmp, `${JSON.stringify(value, null, 2)}\n`, mode === undefined ? undefined : { mode });
210
258
  renameSync(tmp, path);
211
259
  }
212
260
 
213
261
  /**
214
262
  * Merge one account profile into credentials.json (v2 multi-profile shape).
215
- * Existing profiles for OTHER accounts are preserved — connecting a second
263
+ * Existing profiles for OTHER accounts are preserved: connecting a second
216
264
  * account must never disconnect the first. Top-level v1 fields are kept as a
217
265
  * mirror of the default profile because already-installed skill scripts
218
266
  * (ssh-connect.sh / deploy.sh / pull-live.sh copies from older versions) read
219
267
  * them directly until the skill is refreshed.
220
268
  */
221
269
  function mergeProfile(profile) {
270
+ // A file that cannot be read would be written over with only this account in it: every other
271
+ // saved account gone without a word. Keep a copy first and say where it is.
272
+ if (readCredentials(credPath).unreadable) {
273
+ const copy = `${credPath}.unreadable-${Date.now()}`;
274
+ try {
275
+ cpSync(credPath, copy);
276
+ chmodSync(copy, 0o600);
277
+ 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.`);
278
+ } catch (err) {
279
+ 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.`);
280
+ }
281
+ }
222
282
  const existing = readJsonFile(credPath) ?? {};
223
283
  const profiles = { ...(existing.profiles ?? {}) };
224
284
 
@@ -239,13 +299,15 @@ function mergeProfile(profile) {
239
299
  if (defaultProfile && !profiles[defaultProfile]) defaultProfile = undefined;
240
300
  if (!defaultProfile && Object.keys(profiles).length === 1) defaultProfile = profile.slug;
241
301
  if (existing.defaultProfile && existing.defaultProfile !== profile.slug && profiles[existing.defaultProfile]) {
242
- console.log(`• defaultProfile stays "${existing.defaultProfile}" — this folder is pinned to "${profile.slug}" instead.`);
302
+ console.log(`• defaultProfile stays "${existing.defaultProfile}". This folder is pinned to "${profile.slug}" instead.`);
243
303
  }
244
304
 
245
- // The v1 mirror follows the default profile when one is set; otherwise the
246
- // account just connected (matching the old last-connect-wins behavior for
247
- // legacy readers, without losing the other profiles).
248
- const mirrorSource = (defaultProfile && profiles[defaultProfile]) || profile;
305
+ // The v1 mirror (read by older helpers that know only one account) follows the default profile
306
+ // when one is set, else the account it already named, else the account just connected. It never
307
+ // moves to a newly connected account while another one it named is still saved: that move was
308
+ // a silent account switch for every legacy reader.
309
+ const previousMirror = typeof existing.slug === 'string' && profiles[existing.slug] ? profiles[existing.slug] : null;
310
+ const mirrorSource = (defaultProfile && profiles[defaultProfile]) || previousMirror || profile;
249
311
  const creds = {
250
312
  version: 2,
251
313
  ...(defaultProfile ? { defaultProfile } : {}),
@@ -258,7 +320,7 @@ function mergeProfile(profile) {
258
320
 
259
321
  mkdirSync(dir, { recursive: true, mode: 0o700 });
260
322
  chmodSync(dir, 0o700);
261
- writeJsonFile(credPath, creds);
323
+ writeJsonFile(credPath, creds, 0o600);
262
324
  chmodSync(credPath, 0o600);
263
325
  return creds;
264
326
  }
@@ -271,23 +333,65 @@ function mergeProfile(profile) {
271
333
  function writePin(slug) {
272
334
  const target = resolve(pinDirArg || process.cwd());
273
335
  if (pinDirArg && !(existsSync(target) && statSync(target).isDirectory())) {
274
- console.log(`• --pin-dir ${pinDirArg} is not an existing directory — skipping the pin. Create it and add ${PIN_FILENAME} with {"account": "${slug}"}.`);
336
+ console.log(`• --pin-dir ${pinDirArg} is not an existing directory, so no pin was written. Create it and add ${PIN_FILENAME} with {"account": "${slug}"}.`);
275
337
  return null;
276
338
  }
277
339
  if (target === resolve(homedir())) {
278
- console.log(`• Target is the home directory — not writing a ${PIN_FILENAME} pin. Re-run from the project folder (or pass --pin-dir) to pin it.`);
340
+ 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.`);
279
341
  return null;
280
342
  }
281
343
  const pinPath = join(target, PIN_FILENAME);
282
- const existing = readJsonFile(pinPath);
283
- if (existing?.account && existing.account !== slug) {
284
- console.log(`• Re-pinning ${target}: ${existing.account} → ${slug}.`);
344
+ const before = readJsonFile(pinPath);
345
+ const old = before && typeof before === 'object' && !Array.isArray(before) ? before : {};
346
+ const oldAccount = typeof old.account === 'string' ? old.account : null;
347
+ // Anything else the pin carries (a brand, say) is kept for the same account. A brand belongs to
348
+ // the account it was set for, so moving the pin to another account drops it, and says so.
349
+ const { brand, ...rest } = old;
350
+ const keepBrand = brand !== undefined && oldAccount === slug;
351
+ writeJsonFile(pinPath, { ...rest, ...(keepBrand ? { brand } : {}), version: 1, account: slug });
352
+ if (oldAccount && oldAccount !== slug) {
353
+ console.log(`✓ Re-pinned ${target} from account "${oldAccount}" to "${slug}" (${PIN_FILENAME}).`);
354
+ 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}.`);
355
+ } else {
356
+ console.log(`✓ Pinned ${target} to account "${slug}" (${PIN_FILENAME}).`);
285
357
  }
286
- writeJsonFile(pinPath, { version: 1, account: slug });
287
- console.log(`✓ Pinned ${target} to account "${slug}" (${PIN_FILENAME}).`);
288
358
  return pinPath;
289
359
  }
290
360
 
361
+ /** Which account a session started in the pin folder uses right now. */
362
+ function activeHere() {
363
+ return activeAccount({ credPath, cwd: resolve(pinDirArg || process.cwd()), home: homedir(), env: process.env });
364
+ }
365
+
366
+ /** What makes a session here use another account than the one just written, or null. */
367
+ function overriddenBy(active, target) {
368
+ if (active.slug === target) return null;
369
+ if (active.source === 'env-pat') return 'AWESOMATE_PAT is set';
370
+ if (active.source === 'env-account') return `AWESOMATE_ACCOUNT is set to "${process.env.AWESOMATE_ACCOUNT}"`;
371
+ if (active.source === 'pin') return `${active.pinPath} names ${active.slug ? `"${active.slug}"` : 'another account'}`;
372
+ return active.problem ?? `this folder reads "${active.slug}"`;
373
+ }
374
+
375
+ const SWITCH_CMD = 'npx -y --package=@awesomate/hosting-mcp awesomate-hosting-bootstrap --switch';
376
+
377
+ /**
378
+ * Never move a folder from one account to another without saying so: name the account it used,
379
+ * say its key is still saved, and give the one command that switches back.
380
+ */
381
+ function warnIfSwitched(before, after) {
382
+ if (!before.slug || before.slug === after.slug) return;
383
+ const savedNow = readCredentials(credPath).profiles[before.slug];
384
+ console.log('');
385
+ console.log(`! This folder used the account "${before.slug}" before this run. It now uses "${after.slug ?? 'none'}".`);
386
+ if (savedNow) {
387
+ console.log(` The "${before.slug}" key is still saved on this computer. To switch this folder back, run:`);
388
+ console.log(` ${SWITCH_CMD} ${before.slug}${pinDirArg ? ` --pin-dir ${JSON.stringify(resolve(pinDirArg))}` : ''}`);
389
+ } else {
390
+ 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.`);
391
+ }
392
+ console.log('');
393
+ }
394
+
291
395
  /**
292
396
  * Copy the skill bundled alongside this script into ~/.claude/skills so Claude
293
397
  * Code loads it. This runs INSIDE the already-approved bootstrap invocation, so
@@ -295,38 +399,73 @@ function writePin(slug) {
295
399
  * (overwrites an older/hand-made copy with the canonical one). Best-effort: a
296
400
  * failure here never aborts the rest of setup.
297
401
  */
298
- function installSkill() {
299
- // realpathSync: npx runs the bin through a symlink (or a shim on Windows) —
402
+ /**
403
+ * Where this script runs from: inside the npm package (skill/<name>/scripts), or an installed copy.
404
+ * names is the bundle's skill list (package layout only), pkgVersion its version.
405
+ */
406
+ function bundleInfo() {
407
+ // realpathSync: npx runs the bin through a symlink (or a shim on Windows):
300
408
  // resolve to the file's true location inside the package before walking up,
301
409
  // or the walk lands in the npx cache's .bin dir. basename() (never
302
410
  // endsWith('/skill')): Windows paths use '\', which broke the layout check
303
411
  // and made every Windows bootstrap report "Skill files not found".
304
412
  let selfPath = fileURLToPath(import.meta.url);
305
413
  try { selfPath = realpathSync(selfPath); } catch { /* keep unresolved path */ }
306
- const hostingSkill = dirname(dirname(selfPath));
307
- const skillRoot = dirname(hostingSkill);
414
+ const skillRoot = dirname(dirname(dirname(selfPath)));
308
415
  const isPackageLayout = basename(skillRoot) === 'skill';
416
+ if (!isPackageLayout) return { skillRoot, isPackageLayout, names: null, pkgVersion: null };
417
+ let pkgVersion = null;
418
+ try {
419
+ pkgVersion = JSON.parse(readFileSync(join(dirname(skillRoot), 'package.json'), 'utf8')).version ?? null;
420
+ } catch { /* non-fatal: the marker just won't be written */ }
421
+ let names = [];
422
+ try { names = readdirSync(skillRoot).filter((n) => existsSync(join(skillRoot, n, 'SKILL.md'))); } catch { /* none */ }
423
+ return { skillRoot, isPackageLayout, names, pkgVersion };
424
+ }
425
+
426
+ /**
427
+ * Bring Muse's router, connector guide and AGENTS.md rule up to date, where Muse is on this
428
+ * computer (or --muse asks). Muse reads Claude Code's skill folder when this run installed there.
429
+ */
430
+ function museSkillsDir() {
431
+ return skillsDirFor(CLIENTS.includes('claude') ? 'claude' : CLIENTS[0], homedir());
432
+ }
433
+
434
+ // A missing ~/AGENTS.md rule is never fixed by running the same command again (the file is made
435
+ // only with --muse, MUSE-BOOTSTRAP-1), so it warns and the run still succeeds. Every other Muse
436
+ // issue fails it.
437
+ const MUSE_WARNINGS = new Set(['muse-agents-md']);
438
+
439
+ function updateMuse() {
440
+ const muse = detectMuse({ argv: process.argv, env: process.env, home: homedir() });
441
+ if (!muse.on) return { on: false, issues: [], warnings: [] };
442
+ const { names, pkgVersion } = bundleInfo();
443
+ try {
444
+ const r = refreshMuse({ home: homedir(), skillsDir: museSkillsDir(), names, pkgVersion, forced: muse.forced });
445
+ return { on: true, issues: r.issues.filter((i) => !MUSE_WARNINGS.has(i)), warnings: r.issues.filter((i) => MUSE_WARNINGS.has(i)) };
446
+ } catch (err) {
447
+ console.log(`✗ Muse: could not write the Muse files (${err.message}).`);
448
+ return { on: true, issues: ['muse-files'], warnings: [] };
449
+ }
450
+ }
451
+
452
+ function installSkill() {
453
+ // pkgVersion is stamped into each installed skill as .installed-version. The MCP server (always
454
+ // latest via unpinned npx) compares it against its own version and reports skill.updateAvailable
455
+ // in awesomate_get_context.
456
+ const { skillRoot, isPackageLayout, pkgVersion } = bundleInfo();
309
457
  if (!isPackageLayout) {
310
458
  // Running from an INSTALLED copy (~/.claude/skills/...): the siblings here
311
459
  // are the user's other skills, not the bundle, and this skill's src IS its
312
- // dest — so an "update" from here silently refreshed nothing while
460
+ // dest, so an "update" from here silently refreshed nothing while
313
461
  // reporting success. Say so honestly and point at the two real paths.
314
- console.log('• This is the installed copy of the skill — it cannot refresh the bundle from here.');
462
+ console.log('• This is the installed copy of the skill: it cannot refresh the bundle from here.');
315
463
  console.log(` Update instead with the awesomate_skill_update tool in ${CLIENT_NAMES}, or re-run the`);
316
464
  const clientFlag = CLIENTS.length > 1 ? ' --client both' : CLIENTS[0] === 'codex' ? ' --client codex' : '';
317
465
  console.log(` full bootstrap: npx -y --package=@awesomate/hosting-mcp awesomate-hosting-bootstrap --update${clientFlag}`);
318
466
  return false;
319
467
  }
320
468
  const bundled = readdirSync(skillRoot);
321
- // Package version, stamped into each installed skill as .installed-version.
322
- // The MCP server (always latest via unpinned npx) compares it against its own
323
- // version and reports skill.updateAvailable in awesomate_get_context.
324
- let pkgVersion = null;
325
- if (isPackageLayout) {
326
- try {
327
- pkgVersion = JSON.parse(readFileSync(join(dirname(skillRoot), 'package.json'), 'utf8')).version ?? null;
328
- } catch { /* non-fatal — marker just won't be written */ }
329
- }
330
469
  let installed = 0;
331
470
  for (const client of CLIENTS) for (const name of bundled) {
332
471
  const src = join(skillRoot, name);
@@ -353,7 +492,7 @@ function installSkill() {
353
492
  installed += 1;
354
493
  }
355
494
  if (installed === 0) {
356
- console.log('• Skill files not found next to bootstrap — skipping skill install (MCP still works).');
495
+ console.log('• Skill files not found next to bootstrap, so no skill was installed (MCP still works).');
357
496
  return false;
358
497
  }
359
498
  return true;
@@ -407,14 +546,14 @@ function rewriteTree(dir) {
407
546
  }
408
547
 
409
548
  // --package= (with the =) instead of -p: the claude CLI pre-scans the FULL
410
- // argv for its own global -p/--print flag — even after the `--` separator —
549
+ // argv for its own global -p/--print flag, even after the `--` separator,
411
550
  // so any `claude mcp add … -- npx -y -p pkg bin` flips it into print mode and
412
551
  // it rejects the scope flag as "unknown option" (marlins bug report,
413
552
  // 2026-07-28). npx treats both forms identically at runtime; the = form keeps
414
553
  // the value glued to the token so these args are safe to copy anywhere.
415
554
  // The explicit package must stay: this package ships two bins.
416
555
  // Windows: a bare `npx` spawn fails silently (it's npx.cmd there), so the
417
- // server never starts and the tools never appear — even after a restart.
556
+ // server never starts and the tools never appear, even after a restart.
418
557
  // First observed on the first Windows client, 2026-08-19. cmd /c resolves it.
419
558
  const CLEAN_ENTRY = process.platform === 'win32'
420
559
  ? {
@@ -430,11 +569,11 @@ const MANUAL_ADD_TOML = `In ${join(codexHome(process.env, homedir()), 'config.to
430
569
 
431
570
  /**
432
571
  * Converge on exactly one env-free, user-scope MCP registration by editing the
433
- * config files DIRECTLY — `claude mcp add` flag syntax has drifted between CLI
572
+ * config files DIRECTLY: `claude mcp add` flag syntax has drifted between CLI
434
573
  * versions (--scope/-s rejected on some), and a registration is too important
435
574
  * to hang off a moving target.
436
575
  *
437
- * Legacy bootstraps baked AWESOMATE_PAT into the registration env — env beats
576
+ * Legacy bootstraps baked AWESOMATE_PAT into the registration env: env beats
438
577
  * credentials.json inside the server, so those registrations keep serving a
439
578
  * STALE account forever after a re-pair. Remove every entry that carries the
440
579
  * env var (user scope, this project's local scope + .mcp.json); entries in
@@ -473,7 +612,7 @@ function ensureClaudeRegistration() {
473
612
  if (existsSync(claudeJsonPath)) {
474
613
  cfg = readJsonFile(claudeJsonPath);
475
614
  if (!cfg) {
476
- throw new Error(`${claudeJsonPath} exists but is not valid JSON — refusing to rewrite it. Fix the file, then add:\n${MANUAL_ADD_JSON}`);
615
+ throw new Error(`${claudeJsonPath} exists but is not valid JSON, so it was not rewritten. Fix the file, then add:\n${MANUAL_ADD_JSON}`);
477
616
  }
478
617
  }
479
618
 
@@ -482,7 +621,7 @@ function ensureClaudeRegistration() {
482
621
  entry &&
483
622
  !entry.env?.AWESOMATE_PAT &&
484
623
  JSON.stringify(entry.args ?? []).includes('awesomate-hosting-mcp') &&
485
- // A bare-npx registration is broken on Windows — rewrite it.
624
+ // A bare-npx registration is broken on Windows: rewrite it.
486
625
  (process.platform !== 'win32' || entry.command === 'cmd');
487
626
 
488
627
  let changed = false;
@@ -509,13 +648,13 @@ function ensureClaudeRegistration() {
509
648
  for (const [projectDir, project] of Object.entries(cfg.projects ?? {})) {
510
649
  if (resolve(projectDir) === cwd) continue;
511
650
  if (project?.mcpServers?.['awesomate-hosting']?.env?.AWESOMATE_PAT) {
512
- 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.`);
651
+ 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.`);
513
652
  }
514
653
  }
515
654
 
516
655
  if (changed) {
517
656
  writeJsonFile(claudeJsonPath, cfg);
518
- // Read back and verify — never trust a write (or a CLI exit code) alone.
657
+ // Read back and verify: never trust a write (or a CLI exit code) alone.
519
658
  const verify = readJsonFile(claudeJsonPath);
520
659
  const written = verify?.mcpServers?.['awesomate-hosting'];
521
660
  if (!written || written.command !== CLEAN_ENTRY.command || !JSON.stringify(written.args ?? []).includes('awesomate-hosting-mcp')) {
@@ -559,14 +698,74 @@ async function printOtherBusinesses(pat) {
559
698
  }
560
699
  }
561
700
 
701
+ const n = (v) => (typeof v === 'number' ? String(v) : 'unknown');
702
+
703
+ /**
704
+ * Read the account back from the hub with the key as SAVED (credentials.json), the same read
705
+ * awesomate_whoami and awesomate_get_context make: slug, plan, whose key, features, attention.
706
+ * Returns { ok, lines }. Never prints the key.
707
+ */
708
+ async function hubCheck(slug, base) {
709
+ const p = readCredentials(credPath).profiles[slug];
710
+ if (!p?.pat) return { ok: false, lines: [`✗ Hub: the key for "${slug}" could not be read back from ${credPath}.`] };
711
+ let ctx;
712
+ let timer;
713
+ try {
714
+ ctx = await Promise.race([
715
+ get('/api/hosting-access/context', { token: p.pat, base: (p.apiBase || base || apiBase).replace(/\/$/, '') }),
716
+ new Promise((_, reject) => { timer = setTimeout(() => reject(new Error('no answer within 15 seconds')), 15000); }),
717
+ ]).finally(() => clearTimeout(timer));
718
+ } catch (err) {
719
+ return { ok: false, lines: [`✗ Hub: could not read the account with the saved key (${err.message}).`] };
720
+ }
721
+ if (!ctx || typeof ctx !== 'object') return { ok: false, lines: ['✗ Hub: the account read back empty.'] };
722
+ if (ctx.slug && ctx.slug !== slug) return { ok: false, lines: [`✗ Hub: the saved key reads as account "${ctx.slug}", not "${slug}".`] };
723
+ const k = ctx.key && typeof ctx.key === 'object' ? ctx.key : {};
724
+ const keyLine = k.holder === 'person'
725
+ ? `${k.name || k.email || 'a team member'}'s own key (team member, ${k.level === 'full' ? 'full access' : 'view only'})`
726
+ : `the account owner's key${ctx.email ? ` (${ctx.email})` : ''}`;
727
+ const lines = [`✓ Hub: account ${ctx.slug ?? slug}, plan ${ctx.plan ?? 'unknown'}, ${keyLine}.`];
728
+ if (ctx.features && typeof ctx.features === 'object') {
729
+ const entries = Object.entries(ctx.features).filter(([, f]) => f && typeof f === 'object');
730
+ const off = entries.filter(([, f]) => f.available === false).map(([key]) => key);
731
+ lines.push(` Features: ${entries.length - off.length} on, ${off.length} off${off.length ? ` (${off.slice(0, 8).join(', ')}${off.length > 8 ? ', and more' : ''})` : ''}.`);
732
+ } else {
733
+ lines.push(' Features: the hub did not say.');
734
+ }
735
+ const a = ctx.attention && typeof ctx.attention === 'object' ? ctx.attention : {};
736
+ 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.`);
737
+ return { ok: true, lines };
738
+ }
739
+
740
+ /** The checks that end a connect. Each failure is named, so nothing is left half connected without a word. */
741
+ async function finalChecks(slug, muse) {
742
+ console.log('');
743
+ console.log('Checking the connection:');
744
+ const failed = [];
745
+ const hub = await hubCheck(slug);
746
+ for (const line of hub.lines) console.log(line);
747
+ if (!hub.ok) failed.push('verify-hub');
748
+ if (muse.on) {
749
+ for (const c of museChecks({ home: homedir(), skillsDir: museSkillsDir(), names: bundleInfo().names })) {
750
+ // No ~/AGENTS.md at all is a warning (made only with --muse); a file without the rule is not.
751
+ const warnOnly = !c.ok && MUSE_WARNINGS.has(c.key) && !existsSync(join(homedir(), 'AGENTS.md'));
752
+ console.log(`${c.ok ? '✓' : warnOnly ? '•' : '✗'} ${c.line}`);
753
+ if (!c.ok && !warnOnly) failed.push(`verify-${c.key}`);
754
+ }
755
+ }
756
+ return failed;
757
+ }
758
+
562
759
  async function main() {
563
760
  await initProxySupport();
564
761
  const issues = [];
762
+ // Which account this folder used before anything was written, to say so if it changes.
763
+ const activeBefore = activeHere();
565
764
 
566
765
  // ── Identity: redeem a code, or verify a resumed PAT ─────────────────────
567
766
  let redeemed;
568
767
  if (resumePat) {
569
- console.log(`Resuming with an existing access token — verifying against ${apiBase} …`);
768
+ console.log(`Resuming with an existing access token: verifying against ${apiBase} …`);
570
769
  const ctx = await get('/api/hosting-access/context', { token: resumePat });
571
770
  redeemed = {
572
771
  pat: resumePat,
@@ -588,14 +787,14 @@ async function main() {
588
787
 
589
788
  const slug = redeemed.slug ?? null;
590
789
  if (!slug) {
591
- console.error('The hub did not return an account slug — cannot safely store a profile. Contact Awesomate support.');
790
+ console.error('The hub did not return an account slug, so no profile can be stored safely. Contact Awesomate support.');
592
791
  console.error('AWESOMATE CONNECT: FAILED reason=no-slug');
593
792
  process.exit(1);
594
793
  }
595
794
  // Wrong-account guard: abort BEFORE writing anything.
596
795
  if (expectedAccount && expectedAccount !== slug) {
597
796
  console.error(`This ${resumePat ? 'token' : 'setup code'} belongs to account "${slug}" but this connect was for "${expectedAccount}".`);
598
- console.error(`You are probably logged into the wrong hub account — log into ${expectedAccount}'s hub account and copy a fresh Connect prompt.`);
797
+ console.error(`You are probably logged into the wrong hub account. Log into ${expectedAccount}'s hub account and copy a fresh Connect prompt.`);
599
798
  console.error(`AWESOMATE CONNECT: FAILED reason=account-mismatch expected=${expectedAccount} got=${slug}`);
600
799
  process.exit(1);
601
800
  }
@@ -607,13 +806,13 @@ async function main() {
607
806
  try {
608
807
  context = await get('/api/hosting-access/context', { token: redeemed.pat });
609
808
  } catch (err) {
610
- console.error(`Token verification failed (${err.message}) — not storing it. Re-run the same command (setup codes stay valid for 10 minutes).`);
809
+ console.error(`Token verification failed (${err.message}), so it was not stored. Run the same command again (setup codes stay valid for 10 minutes).`);
611
810
  console.error('AWESOMATE CONNECT: FAILED reason=verify-failed');
612
811
  process.exit(1);
613
812
  }
614
813
  const ctxSlug = context?.slug ?? null;
615
814
  if (ctxSlug && ctxSlug !== slug) {
616
- console.error(`Identity mismatch: redeem said "${slug}" but the token resolves to "${ctxSlug}". Not storing it — contact Awesomate support.`);
815
+ console.error(`Identity mismatch: redeem said "${slug}" but the token resolves to "${ctxSlug}". It was not stored. Contact Awesomate support.`);
617
816
  console.error('AWESOMATE CONNECT: FAILED reason=identity-mismatch');
618
817
  process.exit(1);
619
818
  }
@@ -649,14 +848,19 @@ async function main() {
649
848
  };
650
849
  mergeProfile(profile);
651
850
  console.log(`✓ Access token stored as profile "${slug}" in ${credPath} (chmod 600). Plan: ${redeemed.plan}.`);
851
+ if (replacing) {
852
+ console.log(`! The key saved for "${slug}" on this computer was ${beforeEmail}'s. It is now ${newEmail}'s (--replace).`);
853
+ console.log(` ${beforeEmail} can connect again from their own user account on this computer: hub.awesomate.ai/claude, signed in as themselves.`);
854
+ }
652
855
 
653
856
  const pinPath = writePin(slug);
857
+ warnIfSwitched(activeBefore, activeHere());
654
858
 
655
- // Install the skill + register the MCP server FIRST — these always work and
859
+ // Install the skill + register the MCP server FIRST: these always work and
656
860
  // don't depend on hosting being fully provisioned. Neither is allowed to
657
861
  // strand the other or SSH: every step from here is collected, not fatal.
658
862
  try { installSkill(); } catch (err) {
659
- console.log(`• Could not auto-install the skill (${err.message}) — continuing; you can copy skill/ manually.`);
863
+ console.log(`• Could not auto-install the skill (${err.message}). Continuing: you can copy skill/ by hand.`);
660
864
  }
661
865
 
662
866
  const failures = ensureMcpRegistration();
@@ -667,9 +871,9 @@ async function main() {
667
871
  }
668
872
 
669
873
  // SSH key (Support Plus+): best-effort. If it fails (e.g. hosting not fully
670
- // provisioned yet, or no ssh tooling in this environment), keep the token +
671
- // skill + MCP — deploy/shell just aren't ready until it's registered, which
672
- // the skill can retry later.
874
+ // provisioned yet, or no ssh tooling in this environment), keep the token,
875
+ // skill and MCP: deploy and shell just aren't ready until it's registered,
876
+ // which the skill can retry later.
673
877
  if (redeemed.shellAccess) {
674
878
  try {
675
879
  if (!existsSync(keyPath)) {
@@ -687,7 +891,7 @@ async function main() {
687
891
  console.log(`✓ SSH key authorized on ${reg.sshUser}@${reg.sshHost} (jailed to your account).`);
688
892
  } catch (err) {
689
893
  if (err?.code === 'ENOENT') {
690
- console.log('• No ssh-keygen in this environment — skipping SSH setup. Deploy and shell need a real workstation; reads and management calls work fine here.');
894
+ 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.');
691
895
  } else {
692
896
  console.log(`• SSH key not registered yet: ${err.message}`);
693
897
  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.');
@@ -697,12 +901,23 @@ async function main() {
697
901
  } else if (redeemed.keyKind === 'person_device') {
698
902
  console.log('• This is your own key: it does what you can do in the hub. SSH and deploys stay with the account owner.');
699
903
  } else {
700
- console.log('• Plan has no shell access — read/status mode. Upgrade to Support Plus for SSH + deploy.');
904
+ console.log('• Plan has no shell access: read and status mode. Upgrade to Support Plus for SSH and deploys.');
701
905
  }
702
906
 
907
+ const muse = updateMuse();
908
+ issues.push(...muse.issues);
909
+ for (const f of await finalChecks(slug, muse)) if (!issues.includes(f) && !issues.includes(f.replace(/^verify-/, ''))) issues.push(f);
910
+
703
911
  const who = profile.email ? `${slug} (${profile.email}, plan ${redeemed.plan})` : `${slug} (plan ${redeemed.plan})`;
704
- console.log(`\n✓ Connected: ${who}${pinPath ? ` — pinned ${dirname(pinPath)}` : ''}`);
705
- console.log('Setup complete.');
912
+ console.log(`\n${issues.length ? '•' : '✓'} Connected: ${who}${pinPath ? `, pinned ${dirname(pinPath)}` : ''}`);
913
+ if (issues.length) {
914
+ 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.`);
915
+ } else {
916
+ console.log('Setup complete.');
917
+ }
918
+ if (muse.on && !existsSync(join(homedir(), 'AGENTS.md'))) {
919
+ 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.');
920
+ }
706
921
  console.log('');
707
922
  console.log(`IMPORTANT: restart ${CLIENT_NAMES} now: the MCP tools load only at startup.`);
708
923
  if (CLIENTS.includes('codex')) {
@@ -713,6 +928,9 @@ async function main() {
713
928
  console.log(`${FIRST_SKILLS_DIR}/awesomate-hosting/references/rest-fallback.md (hosting).`);
714
929
  console.log('After restarting: run awesomate_whoami to confirm the account, then ask for your first build.');
715
930
  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.)`);
931
+ if (muse.on) {
932
+ 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.');
933
+ }
716
934
  // After the restart notice, so a slow hub never delays the one instruction the user must act on.
717
935
  await printOtherBusinesses(redeemed.pat);
718
936
  if (issues.length) {
@@ -725,7 +943,7 @@ async function main() {
725
943
 
726
944
  // --update: refresh the installed skills from this package and exit, no
727
945
  // setup code, no registration, no token. The no-MCP fallback for the
728
- // awesomate_skill_update tool.
946
+ // awesomate_skill_update tool. Muse's router follows the skills it installed.
729
947
  function runUpdate() {
730
948
  try {
731
949
  installSkill();
@@ -736,7 +954,13 @@ function runUpdate() {
736
954
  console.error(`Skill files refreshed, but the ${clientLabel(f.client)} MCP registration could not be updated: ${f.message}`);
737
955
  console.error(`Add it by hand:\n${f.manual}`);
738
956
  }
957
+ const muse = updateMuse();
739
958
  console.log(`Skills refreshed. New content applies in your next ${CLIENT_NAMES} session.`);
959
+ const museAll = [...muse.issues, ...muse.warnings];
960
+ if (museAll.length) {
961
+ console.log(`Muse is not fully set up: ${museAll.join(', ')}. The lines marked ✗ or • above say what is missing.`);
962
+ if (muse.issues.length) process.exit(1);
963
+ }
740
964
  process.exit(0);
741
965
  } catch (err) {
742
966
  console.error('Skill refresh failed:', err?.message ?? err);
@@ -744,11 +968,79 @@ function runUpdate() {
744
968
  }
745
969
  }
746
970
 
971
+ // --switch <slug>: use an account whose key is already saved here, in this folder (or --pin-dir).
972
+ // From the home directory, where no pin is written, it becomes the default account instead.
973
+ // No setup code and no new key: the saved key is read back from the hub to prove it still works.
974
+ async function runSwitch(target) {
975
+ await initProxySupport();
976
+ const creds = readCredentials(credPath);
977
+ if (creds.unreadable) {
978
+ 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.`);
979
+ console.error('AWESOMATE SWITCH: FAILED reason=unreadable-credentials');
980
+ process.exit(1);
981
+ }
982
+ if (!creds.profiles[target]) {
983
+ const saved = Object.keys(creds.profiles);
984
+ 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.`);
985
+ console.error('AWESOMATE SWITCH: FAILED reason=no-profile');
986
+ process.exit(1);
987
+ }
988
+ const activeBefore = activeHere();
989
+ const home = resolve(pinDirArg || process.cwd()) === resolve(homedir());
990
+ let pinPath = null;
991
+ if (home) {
992
+ const file = readJsonFile(credPath) ?? {};
993
+ const p = creds.profiles[target];
994
+ writeJsonFile(credPath, {
995
+ ...file,
996
+ defaultProfile: target,
997
+ apiBase: p.apiBase, pat: p.pat, contactId: p.contactId, slug: p.slug ?? target, email: p.email ?? null,
998
+ plan: p.plan, cpanel: p.cpanel ?? null, expiresAt: p.expiresAt ?? null, ...(p.ssh ? { ssh: p.ssh } : { ssh: undefined }),
999
+ }, 0o600);
1000
+ chmodSync(credPath, 0o600);
1001
+ 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.`);
1002
+ } else {
1003
+ pinPath = writePin(target);
1004
+ if (!pinPath) {
1005
+ console.error('AWESOMATE SWITCH: FAILED reason=no-pin');
1006
+ process.exit(1);
1007
+ }
1008
+ }
1009
+ const activeAfter = activeHere();
1010
+ warnIfSwitched(activeBefore, activeAfter);
1011
+ const issues = [];
1012
+ // An environment variable, or a pin above this folder, outranks what was just written.
1013
+ const overridden = overriddenBy(activeAfter, target);
1014
+ if (overridden) {
1015
+ issues.push('overridden');
1016
+ 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.`);
1017
+ }
1018
+ console.log('');
1019
+ console.log('Checking the account:');
1020
+ const hub = await hubCheck(target, creds.profiles[target].apiBase);
1021
+ for (const line of hub.lines) console.log(line);
1022
+ console.log(`Restart ${CLIENT_NAMES} (or Muse) so it picks up the account.`);
1023
+ if (!hub.ok) {
1024
+ issues.push('verify-hub');
1025
+ 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.`);
1026
+ }
1027
+ if (issues.length) {
1028
+ console.log(`AWESOMATE SWITCH: PARTIAL account=${target} pin=${pinPath ?? 'none'} issues=${issues.join(',')}`);
1029
+ process.exit(1);
1030
+ }
1031
+ console.log(`AWESOMATE SWITCH: SUCCESS account=${target} pin=${pinPath ?? 'none'}`);
1032
+ }
1033
+
747
1034
  if (UPDATE_ONLY) runUpdate();
1035
+ else if (SWITCH_ONLY) runSwitch(switchTo).catch((err) => {
1036
+ console.error('Switch failed:', err.message);
1037
+ console.error('AWESOMATE SWITCH: FAILED reason=error');
1038
+ process.exit(1);
1039
+ });
748
1040
  else main().catch((err) => {
749
1041
  console.error('Bootstrap failed:', err.message);
750
1042
  if (err.isApiError && err.status === 401) {
751
- console.error('Grab a fresh code from hub.awesomate.ai/claude — codes last 10 minutes (and stay re-runnable within that window).');
1043
+ console.error('Grab a fresh code from hub.awesomate.ai/claude: codes last 10 minutes (and stay re-runnable within that window).');
752
1044
  }
753
1045
  console.error(SUPPORT_HINT);
754
1046
  console.error('AWESOMATE CONNECT: FAILED reason=error');