@winning-sales/nexo 0.4.0 → 0.6.0

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,97 @@
1
+ import { Option } from 'commander';
2
+ import { templatesChange, templatesCreate, templatesGet, templatesList, templatesPreview, templatesPublish, templatesStructure } from './commands/templates.js';
3
+ function writeOptions(command) {
4
+ return command
5
+ .option('--input <arquivo>', 'o pedido em JSON, de um arquivo ou - para o stdin; as opções abaixo valem mais')
6
+ .option('--name <nome>', 'o nome do modelo, único no canal')
7
+ .option('--subject <texto>', 'o assunto do e-mail')
8
+ .option('--text <texto>', 'o texto do WhatsApp, ou do e-mail sem blocos')
9
+ .option('--footer <texto>', 'o rodapé do WhatsApp; texto vazio tira')
10
+ .option('--header <texto>', 'o cabeçalho de texto do WhatsApp; texto vazio tira')
11
+ .addOption(new Option('--category <categoria>', 'a categoria do WhatsApp na Meta').choices(['marketing', 'utilidade']))
12
+ .addOption(new Option('--record <registro>', 'o registro da regra que vai usar o modelo').choices([
13
+ 'negocio',
14
+ 'lead',
15
+ 'contato',
16
+ 'empresa',
17
+ 'reuniao'
18
+ ]))
19
+ .option('--blocks <arquivo>', 'os blocos do e-mail em JSON (a lista completa), de um arquivo ou - para o stdin')
20
+ .option('--no-structure', 'e-mail sem logo, faixas nem cabeçalho da marca (só quando a pessoa pede)')
21
+ .option('--html <arquivo>', 'grava o HTML da prévia do e-mail')
22
+ .option('-y, --yes', 'grava depois de mostrar, sem perguntar (só depois do sim da pessoa)');
23
+ }
24
+ function addReadCommands(templates, context) {
25
+ templates
26
+ .command('list')
27
+ .description('Os modelos da empresa, com o canal, o estado e a versão')
28
+ .addOption(new Option('--channel <canal>', 'só deste canal').choices(['email', 'whatsapp']))
29
+ .addOption(new Option('--state <estado>', 'só neste estado').choices(['draft', 'ready', 'archived']))
30
+ .addOption(new Option('--subject-type <tipo>', 'o registro da regra, para ver quais modelos servem').choices([
31
+ 'deal',
32
+ 'lead',
33
+ 'contact',
34
+ 'company',
35
+ 'meeting'
36
+ ]))
37
+ .action(async (_options, command) => {
38
+ await templatesList(context, command.optsWithGlobals());
39
+ });
40
+ templates
41
+ .command('get')
42
+ .description('Um modelo: o conteúdo, o formato (com a marca ou antigo) e as regras que o usam; --json traz os blocos')
43
+ .argument('<modelo>', 'id do modelo')
44
+ .action(async (templateId, _options, command) => {
45
+ await templatesGet(context, templateId, command.optsWithGlobals());
46
+ });
47
+ }
48
+ function addPreviewCommands(templates, context) {
49
+ templates
50
+ .command('preview')
51
+ .description('A prévia do modelo com amostras fixas, a mesma do editor; nada é gravado')
52
+ .argument('<modelo>', 'id do modelo')
53
+ .option('--html <arquivo>', 'grava o HTML do e-mail, para abrir no navegador')
54
+ .action(async (templateId, _options, command) => {
55
+ await templatesPreview(context, templateId, command.optsWithGlobals());
56
+ });
57
+ templates
58
+ .command('structure')
59
+ .description('Mostra um modelo de e-mail antigo na estrutura nova da marca; nada é gravado')
60
+ .option('--template <id>', 'o modelo a estruturar')
61
+ .option('--input <arquivo>', 'ou o conteúdo em JSON, de um arquivo ou - para o stdin')
62
+ .option('--out <arquivo>', 'grava o conteúdo estruturado em JSON')
63
+ .action(async (_options, command) => {
64
+ await templatesStructure(context, command.optsWithGlobals());
65
+ });
66
+ }
67
+ function addWriteCommands(templates, context) {
68
+ writeOptions(templates
69
+ .command('create')
70
+ .description('Cria o rascunho de um modelo: mostra a prévia e o que falta da marca, e grava depois do sim')
71
+ .addOption(new Option('--channel <canal>', 'o canal do modelo').choices(['email', 'whatsapp']))).action(async (_options, command) => {
72
+ await templatesCreate(context, command.optsWithGlobals());
73
+ });
74
+ writeOptions(templates
75
+ .command('change')
76
+ .description('Muda o rascunho de um modelo (uma versão nova); o que não vem fica como está')
77
+ .argument('<modelo>', 'id do modelo')).action(async (templateId, _options, command) => {
78
+ await templatesChange(context, templateId, command.optsWithGlobals());
79
+ });
80
+ templates
81
+ .command('publish')
82
+ .description('Deixa o modelo pronto para usar (no WhatsApp, envia à Meta); mostra o cartão e grava depois do sim')
83
+ .argument('<modelo>', 'id do modelo')
84
+ .option('-y, --yes', 'publica depois de mostrar, sem perguntar (só depois do sim da pessoa)')
85
+ .action(async (templateId, _options, command) => {
86
+ await templatesPublish(context, templateId, command.optsWithGlobals());
87
+ });
88
+ }
89
+ export function addTemplateCommands(program, context) {
90
+ const templates = program
91
+ .command('templates')
92
+ .alias('modelos')
93
+ .description('Os modelos de mensagem (e-mail e WhatsApp), o e-mail com a marca da empresa');
94
+ addReadCommands(templates, context);
95
+ addPreviewCommands(templates, context);
96
+ addWriteCommands(templates, context);
97
+ }
package/dist/program.js CHANGED
@@ -7,11 +7,14 @@ import { addConnectCommands } from './program-connect.js';
7
7
  import { addAutomationCommands } from './program-automations.js';
8
8
  import { addDocumentCommands } from './program-documents.js';
9
9
  import { addArtifactCommands, addDealCommands } from './program-artifacts.js';
10
+ import { addTemplateCommands } from './program-templates.js';
11
+ import { addBrainCommands } from './program-brain.js';
10
12
  import { addDashboardCommands } from './program-dashboards.js';
11
- import { skillsInstall, skillsList } from './commands/skills.js';
13
+ import { skillsInstall, skillsList, skillsShow } from './commands/skills.js';
12
14
  import { login } from './commands/login.js';
13
15
  import { logout } from './commands/logout.js';
14
16
  import { whoami } from './commands/whoami.js';
17
+ import { companies, useCompany } from './commands/platform.js';
15
18
  import { CLI_VERSION } from './version.js';
16
19
  function collect(value, previous) {
17
20
  return [...previous, value];
@@ -45,6 +48,23 @@ function addAuthCommands(program, context) {
45
48
  await whoami(context, globalsOf(command));
46
49
  });
47
50
  }
51
+ function addPlatformCommands(program, context) {
52
+ program
53
+ .command('companies')
54
+ .description('Lista as empresas em que o usuário da plataforma pode agir (só com login de plataforma)')
55
+ .argument('[busca]', 'parte do nome da empresa')
56
+ .action(async (search, _options, command) => {
57
+ await companies(context, search, globalsOf(command));
58
+ });
59
+ program
60
+ .command('use')
61
+ .description('Escolhe a empresa em que a conexão de plataforma age, por id ou por um nome que case com uma só; fica valendo até a troca')
62
+ .argument('[empresa]', 'id da empresa, ou parte do nome')
63
+ .option('--none', 'sai da empresa escolhida')
64
+ .action(async (target, _options, command) => {
65
+ await useCompany(context, target, command.optsWithGlobals());
66
+ });
67
+ }
48
68
  function addApiCommand(program, context) {
49
69
  program
50
70
  .command('api')
@@ -86,21 +106,28 @@ function addSkillsCommands(program, context) {
86
106
  const skills = program.command('skills').description('As regras do Nexo para a sua IA (Claude Code, Cursor, Codex)');
87
107
  skills
88
108
  .command('install')
89
- .description('Grava as skills do Nexo no projeto; sem opção, detecta o que o projeto usa')
109
+ .description('Grava as skills de produto no projeto; com login, as da sua empresa, área e time vão para a sua pasta (~/.claude, ~/.cursor ou ~/.codex), nunca para o projeto')
90
110
  .option('--claude', 'em .claude/skills')
91
- .option('--cursor', 'em .cursor/rules')
111
+ .option('--cursor', 'em .cursor/skills')
92
112
  .option('--agents', 'em AGENTS.md e .nexo/skills (Codex e outros)')
93
113
  .option('--all', 'nos três')
94
114
  .option('-d, --dir <pasta>', 'pasta do projeto', '.')
95
- .action((_options, command) => {
96
- skillsInstall(context, command.optsWithGlobals());
115
+ .action(async (_options, command) => {
116
+ await skillsInstall(context, command.optsWithGlobals());
97
117
  });
98
118
  skills
99
119
  .command('list')
100
- .description('Lista as skills e onde estão instaladas no projeto')
120
+ .description('Lista as skills, com o nível de cada uma (produto, empresa, área, time) e onde estão instaladas')
101
121
  .option('-d, --dir <pasta>', 'pasta do projeto', '.')
102
- .action((_options, command) => {
103
- skillsList(context, command.optsWithGlobals());
122
+ .action(async (_options, command) => {
123
+ await skillsList(context, command.optsWithGlobals());
124
+ });
125
+ skills
126
+ .command('show')
127
+ .description('Mostra uma skill inteira, sem gravar nada')
128
+ .argument('<nome>', 'nome da skill (de skills list)')
129
+ .action(async (name, _options, command) => {
130
+ await skillsShow(context, name, command.optsWithGlobals());
104
131
  });
105
132
  }
106
133
  function addMcpCommand(program, context) {
@@ -108,7 +135,7 @@ function addMcpCommand(program, context) {
108
135
  .command('mcp')
109
136
  .description('Configura os servidores MCP do Nexo no cliente de IA do projeto')
110
137
  .command('setup')
111
- .description('Escreve a configuração do MCP do Nexo e do Nexo Connect, com o token lido de NEXO_TOKEN')
138
+ .description('Escreve a configuração do MCP do Nexo, do Nexo Admin e do Nexo Connect, com o token lido de NEXO_TOKEN')
112
139
  .option('--claude', 'em .mcp.json (Claude Code)')
113
140
  .option('--cursor', 'em .cursor/mcp.json')
114
141
  .option('--codex', 'em .codex/config.toml')
@@ -150,6 +177,7 @@ export function buildProgram(context) {
150
177
  writeErr: (text) => context.stderr.write(text)
151
178
  });
152
179
  addAuthCommands(program, context);
180
+ addPlatformCommands(program, context);
153
181
  addApiCommand(program, context);
154
182
  addDocsCommands(program, context);
155
183
  addSkillsCommands(program, context);
@@ -161,5 +189,7 @@ export function buildProgram(context) {
161
189
  addDocumentCommands(program, context);
162
190
  addDealCommands(program, context);
163
191
  addArtifactCommands(program, context);
192
+ addTemplateCommands(program, context);
193
+ addBrainCommands(program, context);
164
194
  return program;
165
195
  }
@@ -0,0 +1,39 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { DEFAULT_ENVIRONMENT } from '../config/environments.js';
3
+ import { bundledSkills } from './skill-files.js';
4
+ const INDEX_PATH = '/docs/skills/index.json';
5
+ const TIMEOUT_MS = 3000;
6
+ export function sha256Of(content) {
7
+ return createHash('sha256').update(content).digest('hex');
8
+ }
9
+ function isRecord(value) {
10
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
11
+ }
12
+ function isHashedEntry(value) {
13
+ return isRecord(value) && typeof value.name === 'string' && typeof value.sha256 === 'string';
14
+ }
15
+ async function hashedIndex(fetchFn) {
16
+ const response = await fetchFn(`${DEFAULT_ENVIRONMENT.apiUrl}${INDEX_PATH}`, { signal: AbortSignal.timeout(TIMEOUT_MS) });
17
+ const body = response.ok ? await response.json() : null;
18
+ const skills = isRecord(body) ? body.skills : null;
19
+ return Array.isArray(skills) && skills.length > 0 && skills.every(isHashedEntry) ? skills : null;
20
+ }
21
+ /**
22
+ * The product skills that came with this CLI and no longer match the ones the Nexo serves, by the SHA-256 of each file in
23
+ * `/docs/skills/index.json`. Null when it cannot tell (no network, answer in another format): the check never fails a command.
24
+ */
25
+ export async function staleBundledSkills(fetchFn, bundled = bundledSkills()) {
26
+ try {
27
+ const index = await hashedIndex(fetchFn);
28
+ const local = new Map(bundled.map((skill) => [skill.name, sha256Of(skill.content)]));
29
+ return index === null
30
+ ? null
31
+ : index.filter((entry) => local.get(entry.name) !== entry.sha256).map((entry) => entry.name);
32
+ }
33
+ catch {
34
+ return null;
35
+ }
36
+ }
37
+ export function staleNotice(stale) {
38
+ return `As skills de produto que vêm com esta CLI estão velhas (${stale.join(', ')}). Atualize a CLI (npm install -g @winning-sales/nexo@latest) e rode \`nexo skills install\` de novo.`;
39
+ }
@@ -0,0 +1,45 @@
1
+ export const REMOTE_LEVELS = ['product', 'company', 'area', 'team', 'person'];
2
+ export const LEVEL_LABELS = {
3
+ product: 'produto',
4
+ company: 'empresa',
5
+ area: 'área',
6
+ team: 'time',
7
+ person: 'pessoa'
8
+ };
9
+ function isRecord(value) {
10
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
11
+ }
12
+ function isLevel(value) {
13
+ return REMOTE_LEVELS.some((level) => level === value);
14
+ }
15
+ function isEntry(value) {
16
+ return (isRecord(value) &&
17
+ typeof value.name === 'string' &&
18
+ isLevel(value.level) &&
19
+ typeof value.status === 'string' &&
20
+ typeof value.description === 'string' &&
21
+ typeof value.version === 'string');
22
+ }
23
+ function isSkill(value) {
24
+ return isEntry(value) && typeof value.body === 'string';
25
+ }
26
+ /** The skills of the four levels the token reaches, as `GET /v1/skills` lists them: the same `skillsFor` of the copilot. */
27
+ export async function remoteIndex(client) {
28
+ const response = await client.request({ method: 'GET', path: '/v1/skills' });
29
+ const skills = isRecord(response.body) ? response.body.skills : null;
30
+ if (!Array.isArray(skills) || !skills.every(isEntry)) {
31
+ throw new Error('Resposta inesperada de /v1/skills.');
32
+ }
33
+ return skills;
34
+ }
35
+ export async function remoteSkill(client, name) {
36
+ const response = await client.request({ method: 'GET', path: `/v1/skills/${encodeURIComponent(name)}` });
37
+ if (!isSkill(response.body)) {
38
+ throw new Error(`Resposta inesperada de /v1/skills/${name}.`);
39
+ }
40
+ return response.body;
41
+ }
42
+ /** The skills of the company, of an area, of a team: what never goes into the project folder, where it would be committed. */
43
+ export function clientLevelOnly(skills) {
44
+ return skills.filter((skill) => skill.level !== 'product');
45
+ }
@@ -0,0 +1,50 @@
1
+ import { existsSync, mkdirSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { parseSkill } from './skill-files.js';
4
+ const SKILL_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
5
+ const MINIMUM_SKILLS = 1;
6
+ function isEntry(value) {
7
+ if (typeof value !== 'object' || value === null || !('name' in value) || !('file' in value)) {
8
+ return false;
9
+ }
10
+ return typeof value.name === 'string' && SKILL_NAME.test(value.name) && value.file === `${value.name}.md`;
11
+ }
12
+ function skillsListOf(parsed) {
13
+ return typeof parsed === 'object' && parsed !== null && 'skills' in parsed ? parsed.skills : undefined;
14
+ }
15
+ export function skillEntriesOf(json) {
16
+ const skills = skillsListOf(JSON.parse(json));
17
+ if (!Array.isArray(skills) || skills.length < MINIMUM_SKILLS || !skills.every(isEntry)) {
18
+ throw new Error('the skills index is not { skills: [{ name, file }] } with a file named after each skill; the format probably changed');
19
+ }
20
+ return skills;
21
+ }
22
+ async function checkedSkill(base, entry, download) {
23
+ const content = await download(`${base}/${entry.file}`);
24
+ const skill = parseSkill(content);
25
+ if (skill.name !== entry.name || skill.description === '' || skill.body === '') {
26
+ throw new Error(`${entry.file} is not the SKILL.md of ${entry.name}`);
27
+ }
28
+ return content;
29
+ }
30
+ export async function syncSkills(directory, base, download) {
31
+ const entries = skillEntriesOf(await download(`${base}/index.json`));
32
+ const contents = await Promise.all(entries.map((entry) => checkedSkill(base, entry, download)));
33
+ const wanted = new Set(entries.map((entry) => entry.name));
34
+ const present = existsSync(directory)
35
+ ? readdirSync(directory, { withFileTypes: true })
36
+ .filter((entry) => entry.isDirectory())
37
+ .map((entry) => entry.name)
38
+ : [];
39
+ const removed = present.filter((name) => !wanted.has(name));
40
+ for (const name of removed) {
41
+ rmSync(join(directory, name), { recursive: true });
42
+ }
43
+ const written = entries.map((entry, position) => {
44
+ const target = join(directory, entry.name, 'SKILL.md');
45
+ mkdirSync(join(directory, entry.name), { recursive: true });
46
+ writeFileSync(target, contents[position] ?? '');
47
+ return entry.name;
48
+ });
49
+ return { written, removed };
50
+ }
@@ -7,9 +7,6 @@ function writeFile(path, content) {
7
7
  writeFileSync(path, content);
8
8
  return path;
9
9
  }
10
- function cursorRule(skill) {
11
- return `---\ndescription: ${skill.description}\nglobs:\nalwaysApply: false\n---\n\n${skill.body}\n`;
12
- }
13
10
  function agentsBlock(skills) {
14
11
  const lines = skills.map((skill) => `- \`.nexo/skills/${skill.name}.md\`: ${skill.description}`);
15
12
  return [
@@ -44,7 +41,7 @@ export function installSkills(directory, target, skills) {
44
41
  return skills.map((skill) => writeFile(join(directory, '.claude', 'skills', skill.name, 'SKILL.md'), skill.content));
45
42
  }
46
43
  if (target === 'cursor') {
47
- return skills.map((skill) => writeFile(join(directory, '.cursor', 'rules', `${skill.name}.mdc`), cursorRule(skill)));
44
+ return skills.map((skill) => writeFile(join(directory, '.cursor', 'skills', skill.name, 'SKILL.md'), skill.content));
48
45
  }
49
46
  return installAgents(directory, skills);
50
47
  }
@@ -0,0 +1,145 @@
1
+ import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
2
+ import { homedir } from 'node:os';
3
+ import { dirname, join } from 'node:path';
4
+ import { LEVEL_LABELS } from './remote-skills.js';
5
+ export const USER_TOOLS = ['claude', 'cursor', 'codex'];
6
+ const USER_DIRECTORIES = {
7
+ claude: ['.claude', 'skills'],
8
+ cursor: ['.cursor', 'skills'],
9
+ codex: ['.codex', 'skills']
10
+ };
11
+ const CURSOR_READS = ['claude', 'codex'];
12
+ const MARKER = '.nexo-profile';
13
+ const TOOL_OF_TARGET = { claude: 'claude', cursor: 'cursor', agents: 'codex' };
14
+ export function homeOf(env) {
15
+ return env.HOME ?? homedir();
16
+ }
17
+ export function userSkillsDirectory(home, tool) {
18
+ return join(home, ...USER_DIRECTORIES[tool]);
19
+ }
20
+ /**
21
+ * The tools that receive the skills of the client. Cursor also reads the folders of Claude Code and of Codex, so whoever uses Cursor with
22
+ * one of them gets each skill in a single folder (the one of Claude Code, when it is there), or Cursor would load it twice.
23
+ */
24
+ export function userToolsFor(home, targets) {
25
+ const chosen = new Set(targets.map((target) => TOOL_OF_TARGET[target]));
26
+ if (!chosen.has('cursor')) {
27
+ return USER_TOOLS.filter((tool) => chosen.has(tool));
28
+ }
29
+ const reader = CURSOR_READS.find((tool) => chosen.has(tool) || existsSync(dirname(userSkillsDirectory(home, tool))));
30
+ return [reader ?? 'cursor'];
31
+ }
32
+ function slugOf(text) {
33
+ return text
34
+ .toLowerCase()
35
+ .replace(/[^a-z0-9]+/g, '-')
36
+ .replace(/^-+|-+$/g, '');
37
+ }
38
+ export function folderNameOf(profile, skill) {
39
+ const test = skill.status === 'tentative' ? 'em-teste-' : '';
40
+ return `nexo-${slugOf(profile)}-${test}${slugOf(skill.name)}`;
41
+ }
42
+ function oneLine(text) {
43
+ return text.replace(/\s+/g, ' ').trim();
44
+ }
45
+ export function userSkillFileOf(profile, skill, now) {
46
+ const test = skill.status === 'tentative' ? '[em teste, só nesta máquina] ' : '';
47
+ return [
48
+ '---',
49
+ `name: ${folderNameOf(profile, skill)}`,
50
+ `description: ${JSON.stringify(`${test}${oneLine(skill.description)}`)}`,
51
+ 'metadata:',
52
+ ` nexo-profile: ${JSON.stringify(profile)}`,
53
+ ` nexo-level: ${skill.level}`,
54
+ ` nexo-level-label: ${LEVEL_LABELS[skill.level]}`,
55
+ ` nexo-version: ${JSON.stringify(skill.version)}`,
56
+ ` nexo-installed-at: ${now.toISOString()}`,
57
+ '---',
58
+ '',
59
+ skill.body.trim(),
60
+ ''
61
+ ].join('\n');
62
+ }
63
+ function foldersOf(directory, profile) {
64
+ if (!existsSync(directory)) {
65
+ return [];
66
+ }
67
+ return readdirSync(directory, { withFileTypes: true })
68
+ .filter((entry) => entry.isDirectory() && entry.name.startsWith('nexo-'))
69
+ .map((entry) => join(directory, entry.name))
70
+ .filter((folder) => {
71
+ const marker = join(folder, MARKER);
72
+ return existsSync(marker) && readFileSync(marker, 'utf8').trim() === profile;
73
+ });
74
+ }
75
+ /** Removes what this profile left in the three folders of the user; the product skills of the project and other profiles stay. */
76
+ export function removeUserSkills(home, profile) {
77
+ const removed = USER_TOOLS.flatMap((tool) => foldersOf(userSkillsDirectory(home, tool), profile));
78
+ for (const folder of removed) {
79
+ rmSync(folder, { recursive: true, force: true });
80
+ }
81
+ return removed;
82
+ }
83
+ const VERSION_LINE = /^ {2}nexo-version: (.*)$/m;
84
+ const LEVEL_LINE = /^ {2}nexo-level: (.*)$/m;
85
+ const INSTALLED_AT_LINE = /^( {2}nexo-installed-at: ).*$/m;
86
+ function isCurrent(folder, profile, entry) {
87
+ const marker = join(folder, MARKER);
88
+ const file = join(folder, 'SKILL.md');
89
+ if (!existsSync(marker) || !existsSync(file) || readFileSync(marker, 'utf8').trim() !== profile) {
90
+ return false;
91
+ }
92
+ const content = readFileSync(file, 'utf8');
93
+ const version = VERSION_LINE.exec(content)?.[1];
94
+ const level = LEVEL_LINE.exec(content)?.[1];
95
+ return version === JSON.stringify(entry.version) && level === entry.level;
96
+ }
97
+ function folderOf(home, tool, profile, entry) {
98
+ return join(userSkillsDirectory(home, tool), folderNameOf(profile, entry));
99
+ }
100
+ function writeSkill(folder, profile, fresh, now) {
101
+ mkdirSync(folder, { recursive: true });
102
+ writeFileSync(join(folder, MARKER), `${profile}\n`);
103
+ const file = join(folder, 'SKILL.md');
104
+ writeFileSync(file, userSkillFileOf(profile, fresh, now));
105
+ return file;
106
+ }
107
+ function refreshDate(folder, now) {
108
+ const file = join(folder, 'SKILL.md');
109
+ writeFileSync(file, readFileSync(file, 'utf8').replace(INSTALLED_AT_LINE, `$1${now.toISOString()}`));
110
+ }
111
+ /**
112
+ * Brings the folders of the user to what the API lists for the profile, comparing versions instead of wiping and rewriting: a skill whose
113
+ * version did not change is neither downloaded nor rewritten (only its date is refreshed, which is what the "older than a day" rule reads),
114
+ * a new or changed one is written, and what left the reach is removed. Every body is downloaded before anything is touched, so a network
115
+ * failure in the middle leaves the folders as they were.
116
+ */
117
+ export async function syncUserSkills(home, tools, profile, entries, load, now = new Date()) {
118
+ const slots = tools.flatMap((tool) => entries.map((entry) => {
119
+ const folder = folderOf(home, tool, profile, entry);
120
+ return { folder, entry, current: isCurrent(folder, profile, entry) };
121
+ }));
122
+ const stale = new Set(slots.filter((slot) => !slot.current).map((slot) => slot.entry));
123
+ const loaded = await Promise.all([...stale].map(load));
124
+ const bodies = new Map(loaded.map((skill) => [skill.name, skill]));
125
+ const wanted = new Set(slots.map((slot) => slot.folder));
126
+ const removed = USER_TOOLS.flatMap((tool) => foldersOf(userSkillsDirectory(home, tool), profile)).filter((folder) => !wanted.has(folder));
127
+ for (const folder of removed) {
128
+ rmSync(folder, { recursive: true, force: true });
129
+ }
130
+ const written = slots.flatMap((slot) => {
131
+ const fresh = bodies.get(slot.entry.name);
132
+ if (slot.current || fresh === undefined) {
133
+ refreshDate(slot.folder, now);
134
+ return [];
135
+ }
136
+ return [writeSkill(slot.folder, profile, fresh, now)];
137
+ });
138
+ const upToDate = entries
139
+ .filter((entry) => !stale.has(entry))
140
+ .map((entry) => entry.name);
141
+ return { written, upToDate, removed };
142
+ }
143
+ export function installedUserTools(home, profile, skill) {
144
+ return USER_TOOLS.filter((tool) => existsSync(join(userSkillsDirectory(home, tool), folderNameOf(profile, skill), 'SKILL.md')));
145
+ }