@awesomate/hosting-mcp 0.172.61 → 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.
@@ -0,0 +1,537 @@
1
+ /**
2
+ * Muse support for the Awesomate connect. Node 18 built-ins only: this file
3
+ * is copied into the user's skills folder beside bootstrap.mjs.
4
+ *
5
+ * Muse is another agent app. It finds skills in /opt/muse/skills and
6
+ * ~/workspace/custom-skills, calls tools through a connector helper in
7
+ * ~/workspace/custom-connectors/<name>/bin/client.py, and reads ~/AGENTS.md
8
+ * every turn. Claude Code's area skills (~/.claude/skills/awesomate-*) are
9
+ * invisible to it until something points at them. This writes:
10
+ *
11
+ * - a ROUTER skill, ~/workspace/custom-skills/awesomate (SKILL.md and
12
+ * skill.yaml), that lists each area skill and says to read it fresh each
13
+ * session. It never copies an area skill's content.
14
+ * - skills-manifest.json beside it: what the router was built from, so the
15
+ * next run can say which areas were added, renamed or removed.
16
+ * - CONNECTOR.md (a marked block, anything else in the file is kept) and,
17
+ * when none is there, bin/client.py under custom-connectors/custom.awesomate.
18
+ * - one marked rule in ~/AGENTS.md, only when that file already exists or the
19
+ * person asked with --muse: other tools read that file too.
20
+ *
21
+ * Nothing here ever holds a token, a setup code or a key.
22
+ */
23
+
24
+ import { createHash } from 'node:crypto';
25
+ import { chmodSync, copyFileSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, statSync, writeFileSync } from 'node:fs';
26
+ import { dirname, join, relative, sep } from 'node:path';
27
+ import { fileURLToPath } from 'node:url';
28
+
29
+ export const ROUTER_MARK = '<!-- awesomate-router: written by the Awesomate connect. Run the connect again to refresh it, edits here are replaced. -->';
30
+ export const YAML_MARK = '# Written by the Awesomate connect. Run the connect again to refresh it.';
31
+ export const CONNECTOR_START = '<!-- awesomate-connector: start (written by the Awesomate connect, kept up to date by it) -->';
32
+ export const CONNECTOR_END = '<!-- awesomate-connector: end -->';
33
+ export const AGENTS_START = '<!-- awesomate: start (added by the Awesomate connect) -->';
34
+ export const AGENTS_END = '<!-- awesomate: end -->';
35
+ /** A rule someone added by hand starts this way. It is never added a second time. */
36
+ export const AGENTS_RULE_LEAD = 'Before any Awesomate work, load the Muse skill `awesomate`';
37
+ export const CLIENT_MARK = '# awesomate-muse-client';
38
+ export const MCP_COMMAND = 'npx -y --package=@awesomate/hosting-mcp awesomate-hosting-mcp';
39
+
40
+ export function musePaths(home) {
41
+ const routerDir = join(home, 'workspace', 'custom-skills', 'awesomate');
42
+ const connectorDir = join(home, 'workspace', 'custom-connectors', 'custom.awesomate');
43
+ return {
44
+ routerDir,
45
+ routerPath: join(routerDir, 'SKILL.md'),
46
+ yamlPath: join(routerDir, 'skill.yaml'),
47
+ manifestPath: join(routerDir, 'skills-manifest.json'),
48
+ connectorDir,
49
+ connectorDoc: join(connectorDir, 'CONNECTOR.md'),
50
+ clientPath: join(connectorDir, 'bin', 'client.py'),
51
+ agentsMd: join(home, 'AGENTS.md'),
52
+ };
53
+ }
54
+
55
+ /** A path under home, written as ~/... on every platform. */
56
+ export function tilde(home, path) {
57
+ const rel = relative(home, path);
58
+ if (!rel || rel.startsWith('..')) return path;
59
+ return `~/${rel.split(sep).join('/')}`;
60
+ }
61
+
62
+ /**
63
+ * Muse is set up only where it is evidently present, or when asked. --no-muse
64
+ * always wins. AWESOMATE_MUSE_SYSTEM_DIR stands in for /opt/muse in tests.
65
+ */
66
+ export function detectMuse({ argv, env, home, exists = existsSync }) {
67
+ if (argv.includes('--no-muse')) return { on: false, forced: false, why: 'the --no-muse flag' };
68
+ if (argv.includes('--muse')) return { on: true, forced: true, why: 'the --muse flag' };
69
+ const system = env.AWESOMATE_MUSE_SYSTEM_DIR || '/opt/muse';
70
+ if (exists(system)) return { on: true, forced: false, why: `${system} is there` };
71
+ if (exists(join(home, 'workspace', 'custom-skills'))) return { on: true, forced: false, why: '~/workspace/custom-skills is there' };
72
+ return { on: false, forced: false, why: null };
73
+ }
74
+
75
+ /** The front matter of a SKILL.md: plain, quoted and folded (>) values. */
76
+ export function frontMatter(text) {
77
+ const m = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text);
78
+ if (!m) return {};
79
+ const out = {};
80
+ const lines = m[1].split(/\r?\n/);
81
+ for (let i = 0; i < lines.length; i += 1) {
82
+ const kv = /^([A-Za-z_][\w-]*):\s*(.*)$/.exec(lines[i]);
83
+ if (!kv) continue;
84
+ let value = kv[2].trim();
85
+ if (/^[>|][-+]?$/.test(value)) {
86
+ const parts = [];
87
+ while (i + 1 < lines.length && (/^\s+\S/.test(lines[i + 1]) || lines[i + 1].trim() === '')) parts.push(lines[(i += 1)].trim());
88
+ value = value.startsWith('>') ? parts.join(' ').replace(/\s+/g, ' ').trim() : parts.join('\n').trim();
89
+ } else if (/^(["']).*\1$/.test(value)) {
90
+ value = value.slice(1, -1);
91
+ }
92
+ out[kv[1]] = value;
93
+ }
94
+ return out;
95
+ }
96
+
97
+ /** Muse skill text: no semicolons, no em or en dashes, no table pipes. */
98
+ export function museText(s) {
99
+ return String(s)
100
+ .replace(/\s*[\u2014\u2013]\s*/g, ': ')
101
+ .replace(/;/g, ',')
102
+ .replace(/\|/g, '/')
103
+ .replace(/,\s*,/g, ',')
104
+ .replace(/\s+/g, ' ')
105
+ .trim();
106
+ }
107
+
108
+ /** What an area covers: the first sentence of its description. */
109
+ export function summaryOf(description, max = 180) {
110
+ const text = museText(description ?? '');
111
+ const m = /^(.+?[.!?])(\s|$)/.exec(text);
112
+ let first = (m ? m[1] : text) || 'An Awesomate area skill.';
113
+ if (first.length > max) {
114
+ // A long first sentence is cut at the last clause that fits: the router is read every turn.
115
+ const cut = Math.max(first.lastIndexOf(', ', max), first.lastIndexOf(': ', max));
116
+ first = `${(cut > 40 ? first.slice(0, cut) : first.slice(0, max).replace(/\s+\S*$/, '')).replace(/[,:]$/, '')}.`;
117
+ }
118
+ return first;
119
+ }
120
+
121
+ /** Short names for the skill.yaml description, in the order a business meets them. */
122
+ const LABELS = {
123
+ 'awesomate-hosting': 'website hosting and WordPress',
124
+ 'awesomate-seo': 'SEO',
125
+ 'awesomate-app-builder': 'apps and websites',
126
+ 'awesomate-portals': 'customer portals',
127
+ 'awesomate-database': 'databases',
128
+ 'awesomate-github': 'GitHub',
129
+ 'awesomate-credentials': 'secrets',
130
+ 'awesomate-n8n': 'n8n automations',
131
+ 'awesomate-knowledge': 'Knowledge',
132
+ 'awesomate-email': 'Contacts and email',
133
+ 'awesomate-funnels': 'funnels and webinars',
134
+ 'awesomate-bookings': 'bookings',
135
+ 'awesomate-payments': 'payments',
136
+ 'awesomate-design': 'design',
137
+ 'awesomate-business-map': 'the business map',
138
+ 'awesomate-onebrain': '1Brain',
139
+ 'awesomate-support': 'support',
140
+ };
141
+ const ORDER = Object.keys(LABELS);
142
+
143
+ export function labelOf(name) {
144
+ return LABELS[name] ?? name.replace(/^awesomate-/, '').replace(/-/g, ' ');
145
+ }
146
+
147
+ const sha256 = (s) => createHash('sha256').update(s).digest('hex');
148
+
149
+ /**
150
+ * The installed area skills Muse should know about. `names`, when given, is
151
+ * the bundle's own list (a skill the bundle stopped shipping stays on disk but
152
+ * is no longer an area); otherwise every awesomate-* folder with a SKILL.md.
153
+ */
154
+ export function areaSkills({ skillsDir, names = null }) {
155
+ let candidates = names;
156
+ if (!candidates) {
157
+ try {
158
+ candidates = readdirSync(skillsDir, { withFileTypes: true }).filter((e) => e.isDirectory() && /^awesomate-[a-z0-9-]+$/.test(e.name)).map((e) => e.name);
159
+ } catch { candidates = []; }
160
+ }
161
+ const areas = [];
162
+ for (const name of [...candidates].sort()) {
163
+ const skillPath = join(skillsDir, name, 'SKILL.md');
164
+ let text;
165
+ try { text = readFileSync(skillPath, 'utf8'); } catch { continue; }
166
+ let version = null;
167
+ try { version = readFileSync(join(skillsDir, name, '.installed-version'), 'utf8').trim() || null; } catch { /* unversioned */ }
168
+ const fm = frontMatter(text);
169
+ areas.push({
170
+ name,
171
+ version,
172
+ sha256: sha256(text),
173
+ updated: statSync(skillPath).mtime.toISOString(),
174
+ // The same skill under a new name: the text with its own name taken out.
175
+ renameKey: sha256(text.replace(/^name:.*$/m, '').split(name).join('<self>')),
176
+ summary: summaryOf(fm.description),
177
+ label: labelOf(name),
178
+ });
179
+ }
180
+ return areas;
181
+ }
182
+
183
+ export function buildManifest({ areas, skillsTilde, pkgVersion, now }) {
184
+ return {
185
+ version: 1,
186
+ writtenBy: 'awesomate-hosting-bootstrap',
187
+ package: pkgVersion ?? null,
188
+ updatedAt: now,
189
+ skillsDir: skillsTilde,
190
+ areas: areas.map((a) => ({
191
+ area: a.name,
192
+ path: `${skillsTilde}/${a.name}/SKILL.md`,
193
+ version: a.version,
194
+ sha256: a.sha256,
195
+ updated: a.updated,
196
+ renameKey: a.renameKey,
197
+ })),
198
+ };
199
+ }
200
+
201
+ export function readManifest(path) {
202
+ try {
203
+ const m = JSON.parse(readFileSync(path, 'utf8'));
204
+ return m && Array.isArray(m.areas) ? m : null;
205
+ } catch { return null; }
206
+ }
207
+
208
+ /** What changed since the last manifest. A rename is a removed and an added area with the same text. */
209
+ export function diffManifests(prev, next) {
210
+ const now = new Map(next.areas.map((a) => [a.area, a]));
211
+ if (!prev) return { first: true, added: [...now.keys()], removed: [], renamed: [], updated: [], count: now.size, before: 0 };
212
+ const was = new Map(prev.areas.filter((a) => a && typeof a.area === 'string').map((a) => [a.area, a]));
213
+ let added = [...now.keys()].filter((n) => !was.has(n));
214
+ let removed = [...was.keys()].filter((n) => !now.has(n));
215
+ const renamed = [];
216
+ for (const from of [...removed]) {
217
+ const key = was.get(from).renameKey;
218
+ const to = key && added.find((n) => now.get(n).renameKey === key);
219
+ if (to) {
220
+ renamed.push({ from, to });
221
+ added = added.filter((n) => n !== to);
222
+ removed = removed.filter((n) => n !== from);
223
+ }
224
+ }
225
+ const updated = [...now.keys()].filter((n) => was.has(n) && was.get(n).sha256 !== now.get(n).sha256);
226
+ return { first: false, added, removed, renamed, updated, count: now.size, before: was.size };
227
+ }
228
+
229
+ export function describeDiff(d) {
230
+ if (d.first) return `Muse router written with ${d.count} area skills.`;
231
+ const parts = [];
232
+ if (d.renamed.length) parts.push(`renamed ${d.renamed.map((r) => `${r.from} to ${r.to}`).join(', ')}`);
233
+ if (d.added.length) parts.push(`added ${d.added.join(', ')}`);
234
+ if (d.removed.length) parts.push(`removed ${d.removed.join(', ')}`);
235
+ const updated = d.updated.length ? ` ${d.updated.length} updated.` : '';
236
+ if (!parts.length) return `Muse router: ${d.count} area skills, none added, renamed or removed.${updated}`;
237
+ return `Muse router updated: ${parts.join(', ')}. Now ${d.count} area skills (was ${d.before}).${updated}`;
238
+ }
239
+
240
+ /** The router skill. Muse format: no semicolons, no em dashes, no tables, closing Available connectors list. */
241
+ export function routerSkillMd({ areas, skillsTilde, connectorTilde }) {
242
+ const list = areas.map((a) => `- ${a.name} (${skillsTilde}/${a.name}/SKILL.md): ${a.summary}`);
243
+ const text = [
244
+ '# Awesomate',
245
+ '',
246
+ 'Load this skill first before any Awesomate tool or advice. It does not hold the instructions for any area. It sends you to the area skill that does.',
247
+ '',
248
+ '## First calls in a session',
249
+ '',
250
+ '1. Call `awesomate_whoami`. Note the account slug it names.',
251
+ '2. Call `awesomate_get_context`. Read the plan, `features` and `attention`.',
252
+ '3. Stop if the account slug is not the one the user means. Say which account is connected, ask which one they mean, and do nothing else until it is right.',
253
+ '',
254
+ '## Area skills',
255
+ '',
256
+ `Each area has its own skill in ${skillsTilde}. Before you work in an area, read its SKILL.md fresh, once each session. Do not use a saved or remembered copy. These files change whenever Awesomate updates them.`,
257
+ '',
258
+ ...list,
259
+ '',
260
+ 'When no area fits, read awesomate-support. When two fit, read both.',
261
+ '',
262
+ '## How to call the tools',
263
+ '',
264
+ `Call the Awesomate tools through the custom.awesomate connector. ${connectorTilde}/CONNECTOR.md says how, in what order, and the rules for live sites, drafts, credits and refusals. Read it before the first call in a session.`,
265
+ '',
266
+ '## Rules that always apply',
267
+ '',
268
+ '- Snapshot a live site before changing it.',
269
+ '- Drafts first. Publish only when the owner says yes.',
270
+ '- Confirm before anything destructive or that spends a credit.',
271
+ '- Never offer work in a feature whose `available` is false. Say its message instead.',
272
+ '- Never retry a 403. Say what it said.',
273
+ '- Never print a setup code, access token or key, in chat or in any file.',
274
+ '',
275
+ '## Available connectors',
276
+ '',
277
+ `- custom.awesomate: the Awesomate account tools, from \`awesomate_whoami\` and \`awesomate_get_context\` to every area's tools. How to call them: ${connectorTilde}/CONNECTOR.md.`,
278
+ '',
279
+ ROUTER_MARK,
280
+ '',
281
+ ];
282
+ return text.map((l) => (l.startsWith('<!--') ? l : l.replace(/;/g, ',').replace(/[\u2014\u2013]/g, ','))).join('\n');
283
+ }
284
+
285
+ export function routerSkillYaml({ areas }) {
286
+ const rank = (name) => (ORDER.includes(name) ? ORDER.indexOf(name) : ORDER.length);
287
+ const labels = [...areas].sort((a, b) => rank(a.name) - rank(b.name) || a.name.localeCompare(b.name)).map((a) => a.label);
288
+ const covered = labels.length > 1 ? `${labels.slice(0, -1).join(', ')} and ${labels[labels.length - 1]}` : labels[0] ?? 'every area';
289
+ const description = museText(`Sends Awesomate account work to the right Awesomate area skill: ${covered}. Load this skill first before any Awesomate tool or advice.`);
290
+ return [
291
+ YAML_MARK,
292
+ 'name: awesomate',
293
+ 'title: Awesomate',
294
+ 'category: Work and knowledge',
295
+ 'include_in_prompt: true',
296
+ `description: ${JSON.stringify(description)}`,
297
+ '',
298
+ ].join('\n');
299
+ }
300
+
301
+ /** The connector guide's own block. clientState: written, updated, unchanged or kept (someone else's client.py). */
302
+ export function connectorBlock({ skillsTilde, connectorTilde, clientState }) {
303
+ const ours = clientState !== 'kept';
304
+ const call = ours
305
+ ? [
306
+ `The helper is ${connectorTilde}/bin/client.py (Python 3, standard library only). It starts the Awesomate MCP server (\`${MCP_COMMAND}\`), makes one call and prints the answer.`,
307
+ '',
308
+ '```bash',
309
+ `python3 ${connectorTilde}/bin/client.py call awesomate_whoami`,
310
+ `python3 ${connectorTilde}/bin/client.py call awesomate_get_context`,
311
+ `python3 ${connectorTilde}/bin/client.py call awesomate_list_sites '{}'`,
312
+ `python3 ${connectorTilde}/bin/client.py tools`,
313
+ '```',
314
+ '',
315
+ '- `call <tool> [json]` runs one tool. The arguments are one JSON object, in single quotes. Leave it out for a tool that takes none.',
316
+ '- `tools` lists every tool with its first line.',
317
+ '- `--account <slug>` before `call` picks the account for that call. Without it, the account comes from the folder you run it in (a `.awesomate.json` pin), else the only account saved, else the default.',
318
+ '- It exits 1 when the tool answered with an error, and prints that error.',
319
+ '- The first call can take a minute while npx downloads the server. Later calls are quick.',
320
+ ]
321
+ : [
322
+ 'This machine already had a bin/client.py that the Awesomate connect did not write, so it was left as it is. Call it the way it was set up. Whatever it does, it must reach the same tools through the Awesomate MCP server:',
323
+ '',
324
+ '```bash',
325
+ MCP_COMMAND,
326
+ '```',
327
+ ];
328
+ return [
329
+ CONNECTOR_START,
330
+ '## Awesomate tools from Muse',
331
+ '',
332
+ ...call,
333
+ '',
334
+ 'The key lives in ~/.awesomate/credentials.json and never needs to be read, copied or passed. The server reads it itself.',
335
+ '',
336
+ '## First calls in a session',
337
+ '',
338
+ '1. `awesomate_whoami`: the account slug, plan and whose key it is.',
339
+ '2. `awesomate_get_context`: the plan, `features` (what this account has) and `attention` (what needs a look).',
340
+ '3. Stop if the slug is not the account the user means. Ask, and do nothing else until it is right.',
341
+ '',
342
+ `Then read the matching area skill in ${skillsTilde}/awesomate-*/SKILL.md, fresh each session, before working in that area.`,
343
+ '',
344
+ '## Safety rules',
345
+ '',
346
+ '- Snapshot a live site before changing it (`awesomate_snapshot_site`).',
347
+ '- Drafts first. Publish only when the owner says yes.',
348
+ '- Confirm with the user before anything destructive or that spends a credit.',
349
+ '- Never offer or start work in a feature whose `available` is false in `awesomate_get_context`. Say its message.',
350
+ '- Never retry a 403. Relay what it said in one line.',
351
+ '- Never print a setup code, access token or key, in chat, in output or in any file.',
352
+ '',
353
+ 'To connect another account, or this one again, copy a fresh Connect command from hub.awesomate.ai/claude and run it.',
354
+ CONNECTOR_END,
355
+ ].join('\n');
356
+ }
357
+
358
+ /** Write only when the text changed. Returns created, updated or unchanged. */
359
+ export function writeIfChanged(path, text, mode) {
360
+ // A symlink (~/AGENTS.md into a dotfiles repo) is written through: renaming over it would replace the
361
+ // link with a plain file and leave the real one unchanged. A dangling link is written as a new file.
362
+ try {
363
+ if (lstatSync(path).isSymbolicLink()) path = realpathSync(path);
364
+ } catch { /* no file yet, or a dangling link */ }
365
+ let before = null;
366
+ try { before = readFileSync(path, 'utf8'); } catch { /* new file */ }
367
+ if (before === text) return 'unchanged';
368
+ mkdirSync(dirname(path), { recursive: true });
369
+ const tmp = `${path}.tmp-${process.pid}`;
370
+ writeFileSync(tmp, text, mode ? { mode } : undefined);
371
+ if (mode) chmodSync(tmp, mode);
372
+ renameSync(tmp, path);
373
+ return before === null ? 'created' : 'updated';
374
+ }
375
+
376
+ /** A file someone else wrote is kept as a copy before ours replaces it. */
377
+ function keepCopy(path) {
378
+ let copy = `${path}.before-awesomate`;
379
+ if (existsSync(copy)) copy = `${path}.before-awesomate-${Date.now()}`;
380
+ copyFileSync(path, copy);
381
+ return copy;
382
+ }
383
+
384
+ function writeOwned(path, text, mark, log, home) {
385
+ let kept = null;
386
+ if (existsSync(path)) {
387
+ let before = '';
388
+ try { before = readFileSync(path, 'utf8'); } catch { /* treated as someone else's */ }
389
+ if (!before.includes(mark)) kept = keepCopy(path);
390
+ }
391
+ const state = writeIfChanged(path, text);
392
+ if (kept) log(`• ${tilde(home, path)} was not written by the Awesomate connect. A copy is kept at ${tilde(home, kept)}.`);
393
+ return state;
394
+ }
395
+
396
+ export function upsertBlock(text, start, end, block) {
397
+ const s = text.indexOf(start);
398
+ const e = s >= 0 ? text.indexOf(end, s) : -1;
399
+ if (s >= 0 && e > s) return `${text.slice(0, s)}${block}${text.slice(e + end.length)}`;
400
+ // A start with no end after it (someone deleted the end line): take out only the stray marker lines,
401
+ // keep every other line, and add a fresh block. Replacing from the stray start would drop their text.
402
+ if (s >= 0 || text.includes(end)) {
403
+ text = text.split('\n').filter((line) => line.trim() !== start && line.trim() !== end).join('\n');
404
+ }
405
+ const sep = text.trim() ? (text.endsWith('\n') ? '\n' : '\n\n') : '';
406
+ return `${text.trim() ? text : ''}${sep}${block}\n`;
407
+ }
408
+
409
+ export function agentsRule({ skillsTilde }) {
410
+ return `${AGENTS_RULE_LEAD} (\`~/workspace/custom-skills/awesomate/SKILL.md\`) and the matching area skill in \`${skillsTilde}/awesomate-*/SKILL.md\`. Read the area skill fresh each session, do not use a saved copy. First call in a session: \`awesomate_whoami\`, then \`awesomate_get_context\`. Stop if the account slug is not the one the user means.`;
411
+ }
412
+
413
+ /**
414
+ * Add the rule to ~/AGENTS.md once. Never creates the file unless forced, and
415
+ * never adds a second copy of a rule someone already added by hand.
416
+ */
417
+ export function ensureAgentsRule({ path, rule, forced }) {
418
+ const exists = existsSync(path);
419
+ if (!exists && !forced) return 'no-file';
420
+ const before = exists ? readFileSync(path, 'utf8') : '';
421
+ const block = `${AGENTS_START}\n${rule}\n${AGENTS_END}`;
422
+ const hasBlock = before.includes(AGENTS_START) && before.includes(AGENTS_END);
423
+ if (!hasBlock && before.includes(AGENTS_RULE_LEAD)) return 'by-hand';
424
+ const crlf = /\r\n/.test(before);
425
+ let next = upsertBlock(before.replace(/\r\n/g, '\n'), AGENTS_START, AGENTS_END, block);
426
+ if (crlf) next = next.replace(/\n/g, '\r\n');
427
+ if (next === before) return 'present';
428
+ const mode = exists ? statSync(path).mode & 0o777 : 0o644;
429
+ writeIfChanged(path, next, mode);
430
+ return hasBlock ? 'updated' : 'added';
431
+ }
432
+
433
+ export function agentsRulePresent(path) {
434
+ try {
435
+ const text = readFileSync(path, 'utf8');
436
+ return (text.includes(AGENTS_START) && text.includes(AGENTS_END)) || text.includes(AGENTS_RULE_LEAD);
437
+ } catch { return false; }
438
+ }
439
+
440
+ const CLIENT_SOURCE = join(dirname(fileURLToPath(import.meta.url)), 'muse-client.py');
441
+
442
+ /** Ours when absent or already ours. Someone else's helper is never replaced. */
443
+ export function ensureClient(path, source = CLIENT_SOURCE) {
444
+ const text = readFileSync(source, 'utf8');
445
+ if (existsSync(path)) {
446
+ let before = '';
447
+ try { before = readFileSync(path, 'utf8'); } catch { return 'kept'; }
448
+ if (!before.includes(CLIENT_MARK)) return 'kept';
449
+ }
450
+ const state = writeIfChanged(path, text, 0o755);
451
+ return state === 'created' ? 'written' : state;
452
+ }
453
+
454
+ /**
455
+ * Bring Muse up to date with the installed area skills. The rule in AGENTS.md
456
+ * is added only after the router and the connector guide are on disk and check
457
+ * out: a rule pointing at a skill that is not there is worse than none.
458
+ */
459
+ export function refreshMuse({ home, skillsDir, names = null, pkgVersion = null, forced = false, now = new Date().toISOString(), log = console.log }) {
460
+ const paths = musePaths(home);
461
+ const skillsTilde = tilde(home, skillsDir);
462
+ const connectorTilde = tilde(home, paths.connectorDir);
463
+ const issues = [];
464
+ const areas = areaSkills({ skillsDir, names });
465
+ if (!areas.length) {
466
+ log(`• Muse: no Awesomate area skills are installed in ${skillsTilde}, so the Muse router was not written.`);
467
+ return { issues: ['muse-no-skills'], diff: null };
468
+ }
469
+ const next = buildManifest({ areas, skillsTilde, pkgVersion, now });
470
+ const diff = diffManifests(readManifest(paths.manifestPath), next);
471
+
472
+ writeOwned(paths.routerPath, routerSkillMd({ areas, skillsTilde, connectorTilde }), ROUTER_MARK, log, home);
473
+ writeOwned(paths.yamlPath, routerSkillYaml({ areas }), YAML_MARK, log, home);
474
+ const clientState = ensureClient(paths.clientPath);
475
+ if (clientState === 'kept') log(`• Muse: kept the existing ${tilde(home, paths.clientPath)} (not written by the Awesomate connect).`);
476
+ // Only a guide that is not there starts from the default header. One that is there but cannot be
477
+ // read is never written over: what it holds may be someone's own text.
478
+ let doc = null;
479
+ try { doc = readFileSync(paths.connectorDoc, 'utf8'); } catch (err) {
480
+ if (err?.code === 'ENOENT') doc = '# custom.awesomate\n';
481
+ else {
482
+ log(`✗ Muse: could not read ${tilde(home, paths.connectorDoc)} (${err.message}), so the connector guide was left as it is.`);
483
+ issues.push('muse-files');
484
+ }
485
+ }
486
+ if (doc !== null) writeIfChanged(paths.connectorDoc, upsertBlock(doc, CONNECTOR_START, CONNECTOR_END, connectorBlock({ skillsTilde, connectorTilde, clientState })));
487
+
488
+ const router = (() => { try { return readFileSync(paths.routerPath, 'utf8'); } catch { return ''; } })();
489
+ const missing = areas.filter((a) => !router.includes(`${skillsTilde}/${a.name}/SKILL.md`)).map((a) => a.name);
490
+ if (!router.includes(ROUTER_MARK) || missing.length || !existsSync(paths.yamlPath)) {
491
+ log(`✗ Muse: the router at ${tilde(home, paths.routerPath)} did not check out${missing.length ? ` (missing ${missing.join(', ')})` : ''}. The AGENTS.md rule was not added.`);
492
+ return { issues: [...issues, 'muse-router'], diff };
493
+ }
494
+ log(`✓ ${describeDiff(diff)} Router: ${tilde(home, paths.routerPath)}.`);
495
+ log(`✓ Muse: connector guide at ${tilde(home, paths.connectorDoc)}${clientState === 'kept' ? '' : `, helper at ${tilde(home, paths.clientPath)}`}.`);
496
+
497
+ const agents = ensureAgentsRule({ path: paths.agentsMd, rule: agentsRule({ skillsTilde }), forced });
498
+ if (agents === 'no-file') {
499
+ log('• Muse: there is no ~/AGENTS.md, so the "load the awesomate skill first" rule was not added. Run the connect again with --muse to create it.');
500
+ issues.push('muse-agents-md');
501
+ } else if (agents === 'by-hand') {
502
+ log('✓ Muse: ~/AGENTS.md already has the Awesomate rule (added by hand), so it was left as it is.');
503
+ } else {
504
+ log(`✓ Muse: ${agents === 'present' ? 'the Awesomate rule is already in' : agents === 'updated' ? 'updated the Awesomate rule in' : 'added the Awesomate rule to'} ~/AGENTS.md.`);
505
+ }
506
+
507
+ writeIfChanged(paths.manifestPath, `${JSON.stringify(next, null, 2)}\n`);
508
+ return { issues, diff };
509
+ }
510
+
511
+ /** Checks read back from disk, for the end of a run. */
512
+ export function museChecks({ home, skillsDir, names = null }) {
513
+ const paths = musePaths(home);
514
+ const skillsTilde = tilde(home, skillsDir);
515
+ const areas = areaSkills({ skillsDir, names });
516
+ let router = '';
517
+ try { router = readFileSync(paths.routerPath, 'utf8'); } catch { /* missing */ }
518
+ const listed = areas.filter((a) => router.includes(`${skillsTilde}/${a.name}/SKILL.md`)).length;
519
+ const doc = (() => { try { return readFileSync(paths.connectorDoc, 'utf8'); } catch { return ''; } })();
520
+ return [
521
+ {
522
+ key: 'muse-router',
523
+ ok: Boolean(router) && areas.length > 0 && listed === areas.length,
524
+ line: router ? `Muse router at ${tilde(home, paths.routerPath)} lists ${listed} of ${areas.length} area skills.` : `Muse router missing at ${tilde(home, paths.routerPath)}.`,
525
+ },
526
+ {
527
+ key: 'muse-agents-md',
528
+ ok: agentsRulePresent(paths.agentsMd),
529
+ line: agentsRulePresent(paths.agentsMd) ? 'Muse rule in ~/AGENTS.md is there.' : 'Muse rule is not in ~/AGENTS.md.',
530
+ },
531
+ {
532
+ key: 'muse-connector',
533
+ ok: doc.includes(CONNECTOR_START),
534
+ line: doc.includes(CONNECTOR_START) ? `Muse connector guide at ${tilde(home, paths.connectorDoc)}.` : `Muse connector guide missing at ${tilde(home, paths.connectorDoc)}.`,
535
+ },
536
+ ];
537
+ }
@@ -0,0 +1,115 @@
1
+ /**
2
+ * The saved Awesomate accounts on this computer, and which one a folder uses.
3
+ * Node 18 built-ins only: this file is copied into the user's skills folder
4
+ * beside bootstrap.mjs.
5
+ *
6
+ * activeAccount() follows the MCP server's order exactly (mcp/src/config.ts):
7
+ * AWESOMATE_PAT env, AWESOMATE_ACCOUNT env, the nearest .awesomate.json pin
8
+ * (AWESOMATE_PIN_FILE, else walked up from the folder, stopping at home), the
9
+ * only profile, then defaultProfile. It never prints or returns a token.
10
+ */
11
+
12
+ import { existsSync, readFileSync } from 'node:fs';
13
+ import { dirname, isAbsolute, join, resolve } from 'node:path';
14
+
15
+ export const PIN_FILENAME = '.awesomate.json';
16
+
17
+ /**
18
+ * Read credentials.json. `unreadable` is true when the file exists but is not
19
+ * a JSON object: a caller about to write it must keep a copy first, or every
20
+ * profile in it is lost without a word.
21
+ */
22
+ export function readCredentials(credPath) {
23
+ let raw;
24
+ try {
25
+ raw = readFileSync(credPath, 'utf8');
26
+ } catch (err) {
27
+ return { exists: err?.code !== 'ENOENT', unreadable: err?.code !== 'ENOENT', file: {}, profiles: {}, defaultProfile: null };
28
+ }
29
+ let file = null;
30
+ try {
31
+ const parsed = JSON.parse(raw);
32
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) file = parsed;
33
+ } catch { /* unreadable below */ }
34
+ if (!file) return { exists: true, unreadable: raw.trim() !== '', file: {}, profiles: {}, defaultProfile: null };
35
+ const profiles = {};
36
+ if (file.profiles && typeof file.profiles === 'object') {
37
+ for (const [key, p] of Object.entries(file.profiles)) {
38
+ if (p && typeof p === 'object' && typeof p.pat === 'string') profiles[key] = p;
39
+ }
40
+ } else if (typeof file.pat === 'string' && file.pat) {
41
+ profiles[file.slug || 'default'] = file;
42
+ }
43
+ const defaultProfile = typeof file.defaultProfile === 'string' && profiles[file.defaultProfile] ? file.defaultProfile : null;
44
+ return { exists: true, unreadable: false, file, profiles, defaultProfile };
45
+ }
46
+
47
+ export function findPin({ cwd, home, env }) {
48
+ const explicit = env.AWESOMATE_PIN_FILE;
49
+ if (explicit) {
50
+ const path = isAbsolute(explicit) ? explicit : resolve(cwd, explicit);
51
+ return existsSync(path) ? path : null;
52
+ }
53
+ const top = resolve(home);
54
+ let dir = resolve(cwd);
55
+ for (;;) {
56
+ const candidate = join(dir, PIN_FILENAME);
57
+ if (existsSync(candidate)) return candidate;
58
+ if (dir === top) return null;
59
+ const parent = dirname(dir);
60
+ if (parent === dir) return null;
61
+ dir = parent;
62
+ }
63
+ }
64
+
65
+ function pinAccount(pinPath) {
66
+ try {
67
+ const pin = JSON.parse(readFileSync(pinPath, 'utf8'));
68
+ return pin && typeof pin.account === 'string' ? pin.account : null;
69
+ } catch { return null; }
70
+ }
71
+
72
+ /**
73
+ * Which account a session started in `cwd` uses. slug is null when none can
74
+ * be chosen; `problem` then says why in a sentence.
75
+ */
76
+ export function activeAccount({ credPath, cwd, home, env }) {
77
+ const { profiles, defaultProfile, unreadable } = readCredentials(credPath);
78
+ const saved = Object.keys(profiles);
79
+ const base = { saved, pinPath: null };
80
+ if (unreadable) return { ...base, slug: null, source: 'none', problem: `${credPath} could not be read` };
81
+ if (env.AWESOMATE_PAT) {
82
+ const match = Object.entries(profiles).find(([, p]) => p.pat === env.AWESOMATE_PAT);
83
+ return { ...base, slug: match ? match[1].slug ?? match[0] : null, source: 'env-pat', problem: match ? null : 'AWESOMATE_PAT is set to a key that is not saved here' };
84
+ }
85
+ if (env.AWESOMATE_ACCOUNT) {
86
+ const slug = env.AWESOMATE_ACCOUNT;
87
+ return { ...base, slug: profiles[slug] ? slug : null, source: 'env-account', problem: profiles[slug] ? null : `AWESOMATE_ACCOUNT names "${slug}", which has no key saved here` };
88
+ }
89
+ const pinPath = findPin({ cwd, home, env });
90
+ if (pinPath) {
91
+ const slug = pinAccount(pinPath);
92
+ if (slug && profiles[slug]) return { ...base, slug, source: 'pin', pinPath, problem: null };
93
+ return { ...base, slug: null, source: 'pin', pinPath, problem: slug ? `the folder pin names "${slug}", which has no key saved here` : `${pinPath} names no account` };
94
+ }
95
+ if (saved.length === 1) return { ...base, slug: saved[0], source: 'sole-profile', problem: null };
96
+ if (defaultProfile) return { ...base, slug: defaultProfile, source: 'default-profile', problem: null };
97
+ if (saved.length === 0) return { ...base, slug: null, source: 'none', problem: 'no account is connected on this computer' };
98
+ return { ...base, slug: null, source: 'none', problem: 'several accounts are saved and this folder is not pinned to one' };
99
+ }
100
+
101
+ const WHY = {
102
+ 'env-pat': 'AWESOMATE_PAT is set',
103
+ 'env-account': 'AWESOMATE_ACCOUNT is set',
104
+ 'sole-profile': 'the only account saved here',
105
+ 'default-profile': 'the default account, so reads only: pin this folder before any change',
106
+ };
107
+
108
+ /** One line for the end of every run. */
109
+ export function describeActive(active) {
110
+ const others = active.saved.filter((s) => s !== active.slug);
111
+ const also = others.length ? ` Also saved on this computer: ${others.join(', ')}.` : '';
112
+ if (!active.slug) return `Active Awesomate account here: none (${active.problem}).${also}`;
113
+ const why = active.source === 'pin' ? `pinned by ${active.pinPath}` : WHY[active.source] ?? active.source;
114
+ return `Active Awesomate account here: ${active.slug} (${why}).${also}`;
115
+ }
@@ -87,6 +87,9 @@ answered 401 on every run.
87
87
  an existing person, a list, consent or a series. An erased address is refused.
88
88
  - **A tag can start an email series** that starts on that tag, for people already subscribed (CA9). Say
89
89
  so before adding a tag, and use one no series starts on when testing.
90
+ - **A tag can put someone on a customers list** where an Owner set that list to fill from the tag (lists
91
+ that fill from a tag). That is the point of the rule: the automation just tags, and the list fills. The
92
+ node never sets or suggests a rule; Claude suggests one with `awesomate_crm_lists_change`.
90
93
  - **Record Event** tells Contacts what happened, so a series can start for a person already subscribed.
91
94
  It never subscribes anyone: the series' own rules decide who starts. Someone not in Contacts yet is
92
95
  **added** (as Create or Update would), and an event that happened more than two days ago is kept as a