@winning-sales/nexo 0.4.0 → 0.5.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,279 @@
1
+ import { createReadStream, writeFileSync } from 'node:fs';
2
+ import { clientOf, printJson, printLine, printNotice, sessionOf } from '../context.js';
3
+ import { CliError, usageError } from '../errors.js';
4
+ import { EXIT_CODES } from '../exit-codes.types.js';
5
+ import { confirmed } from '../input/confirm.js';
6
+ import { readAll } from '../input/read-input.js';
7
+ async function call(context, options, method, path, body) {
8
+ const response = await clientOf(context, sessionOf(context, options)).request({
9
+ method,
10
+ path,
11
+ ...(body === undefined ? {} : { body })
12
+ });
13
+ return response.body;
14
+ }
15
+ function templatePath(templateId) {
16
+ return `/v1/message-templates/${encodeURIComponent(templateId)}`;
17
+ }
18
+ async function jsonInput(context, input) {
19
+ const label = input === '-' ? 'stdin' : input;
20
+ let text;
21
+ try {
22
+ text = await readAll(input === '-' ? context.stdin : createReadStream(input));
23
+ }
24
+ catch {
25
+ throw usageError(`Não consegui ler ${label}.`);
26
+ }
27
+ try {
28
+ return JSON.parse(text);
29
+ }
30
+ catch {
31
+ throw usageError(`O conteúdo de ${label} não é JSON válido.`);
32
+ }
33
+ }
34
+ function isRecord(value) {
35
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
36
+ }
37
+ function saveFile(context, path, text, label) {
38
+ try {
39
+ writeFileSync(path, text);
40
+ }
41
+ catch {
42
+ throw new CliError(`Não consegui gravar ${path}.`, EXIT_CODES.failure);
43
+ }
44
+ printNotice(context, `${label} gravado em ${path}.`);
45
+ }
46
+ function formatOf(content) {
47
+ const nodes = content.document?.json.content;
48
+ if (content.document === null) {
49
+ return 'texto simples';
50
+ }
51
+ return nodes !== undefined && nodes.length > 0 && nodes.every((node) => node.type === 'section')
52
+ ? 'estruturado, com a marca'
53
+ : 'blocos, formato antigo';
54
+ }
55
+ function printBrand(context, brand) {
56
+ if (brand === null || brand === undefined) {
57
+ return;
58
+ }
59
+ printLine(context, `Marca: identidade ${brand.identidade}${brand.falta.length === 0 ? '' : `, falta ${brand.falta.join(' e ')}`}`);
60
+ if (brand.aviso !== null && brand.aviso !== undefined) {
61
+ printLine(context, brand.aviso);
62
+ return;
63
+ }
64
+ if (brand.onde !== null) {
65
+ printLine(context, `Cadastre em ${brand.onde}${brand.caminho === null ? '' : ` (${brand.caminho})`}.`);
66
+ }
67
+ }
68
+ const IDENTITY_LABELS = {
69
+ complete: 'completa',
70
+ partial: 'parcial',
71
+ absent: 'ausente'
72
+ };
73
+ function printStructureBrand(context, brand) {
74
+ if (brand === null || brand === undefined) {
75
+ return;
76
+ }
77
+ printLine(context, `Marca: identidade ${IDENTITY_LABELS[brand.identity]}${brand.missing.length === 0 ? '' : `, falta ${brand.missing.join(' e ')}`}`);
78
+ if (brand.text !== null) {
79
+ printLine(context, brand.text);
80
+ }
81
+ }
82
+ function row(template) {
83
+ const kit = template.fromKit ? ' (kit)' : '';
84
+ return `${template.id} ${template.channel.padEnd(8)} ${template.state.padEnd(8)} v${String(template.currentSeq)} ${template.name}${kit}`;
85
+ }
86
+ export async function templatesList(context, options) {
87
+ const query = new URLSearchParams();
88
+ for (const [key, value] of [
89
+ ['channel', options.channel],
90
+ ['state', options.state],
91
+ ['subjectType', options.subjectType]
92
+ ]) {
93
+ if (value !== undefined) {
94
+ query.set(key, value);
95
+ }
96
+ }
97
+ const suffix = query.size === 0 ? '' : `?${query.toString()}`;
98
+ const list = (await call(context, options, 'GET', `/v1/message-templates${suffix}`));
99
+ if (options.json === true) {
100
+ printJson(context, list);
101
+ return;
102
+ }
103
+ if (list.items.length === 0) {
104
+ printLine(context, 'Nenhum modelo de mensagem.');
105
+ return;
106
+ }
107
+ list.items.forEach((template) => {
108
+ printLine(context, row(template));
109
+ });
110
+ }
111
+ export async function templatesGet(context, templateId, options) {
112
+ const template = (await call(context, options, 'GET', templatePath(templateId)));
113
+ if (options.json === true) {
114
+ printJson(context, template);
115
+ return;
116
+ }
117
+ printLine(context, row(template));
118
+ if (template.channel === 'email') {
119
+ printLine(context, `Formato: ${formatOf(template.content)}`);
120
+ printLine(context, `Assunto: ${template.content.subject ?? '—'}`);
121
+ }
122
+ if (template.content.body !== '') {
123
+ printLine(context, template.content.body);
124
+ }
125
+ if (template.rules.length > 0) {
126
+ printLine(context, 'Regras que usam o modelo:');
127
+ template.rules.forEach((rule) => {
128
+ printLine(context, ` ${rule.name} (${rule.status})${rule.sendsAutomatically ? ', envia sozinha' : ''}`);
129
+ });
130
+ }
131
+ printNotice(context, 'Para ler os blocos, use `nexo templates get <id> --json`.');
132
+ }
133
+ export async function templatesPreview(context, templateId, options) {
134
+ const preview = (await call(context, options, 'POST', `${templatePath(templateId)}/preview`, {}));
135
+ if (options.json === true) {
136
+ printJson(context, preview);
137
+ saveHtml(context, options, preview.previews[0]?.email?.html ?? null);
138
+ return;
139
+ }
140
+ preview.previews.forEach((each) => {
141
+ printLine(context, `Assunto: ${each.subject ?? '—'}`);
142
+ printLine(context, each.email === null ? each.body : each.email.text);
143
+ });
144
+ printNotice(context, 'A prévia usa só amostras fixas, nunca registros reais da empresa.');
145
+ saveHtml(context, options, preview.previews[0]?.email?.html ?? null);
146
+ }
147
+ function saveHtml(context, options, html) {
148
+ if (options.html !== undefined && html !== null) {
149
+ saveFile(context, options.html, html, 'O HTML do e-mail');
150
+ }
151
+ }
152
+ export async function templatesStructure(context, options) {
153
+ if ((options.template === undefined) === (options.input === undefined)) {
154
+ throw usageError('Diga o conteúdo a estruturar com --template <id> ou com --input <arquivo>, só um dos dois.');
155
+ }
156
+ const content = options.template === undefined
157
+ ? await jsonInput(context, options.input ?? '-')
158
+ : (await call(context, options, 'GET', templatePath(options.template))).content;
159
+ const structured = (await call(context, options, 'POST', '/v1/message-templates/professional-structure', {
160
+ content
161
+ }));
162
+ if (options.out !== undefined) {
163
+ saveFile(context, options.out, `${JSON.stringify(structured.content, null, 2)}\n`, 'O conteúdo estruturado');
164
+ }
165
+ if (options.json === true) {
166
+ printJson(context, structured);
167
+ return;
168
+ }
169
+ printLine(context, structured.converted ? 'O modelo foi colocado na estrutura nova da marca.' : 'O modelo já estava estruturado, ou vazio: nada mudou.');
170
+ printStructureBrand(context, structured.brand);
171
+ printNotice(context, 'Nada foi gravado. Para gravar, use `nexo templates change`.');
172
+ }
173
+ function listOf(value, label) {
174
+ const list = isRecord(value) ? value['blocos'] : value;
175
+ if (!Array.isArray(list)) {
176
+ throw usageError(`${label} pede a lista de blocos, ou um objeto com "blocos".`);
177
+ }
178
+ return list;
179
+ }
180
+ async function requestOf(context, action, templateId, options) {
181
+ const base = options.input === undefined ? {} : await jsonInput(context, options.input);
182
+ if (!isRecord(base)) {
183
+ throw usageError('O arquivo de --input pede um objeto JSON com os campos do pedido.');
184
+ }
185
+ const request = { ...base, acao: action };
186
+ delete request['confirmationToken'];
187
+ const fields = [
188
+ ['modeloId', templateId],
189
+ ['canal', options.channel],
190
+ ['nome', options.name],
191
+ ['assunto', options.subject],
192
+ ['texto', options.text],
193
+ ['rodape', options.footer],
194
+ ['categoria', options.category],
195
+ ['cabecalho', options.header],
196
+ ['registro', options.record]
197
+ ];
198
+ for (const [key, value] of fields) {
199
+ if (value !== undefined) {
200
+ request[key] = value;
201
+ }
202
+ }
203
+ if (options.blocks !== undefined) {
204
+ request['blocos'] = listOf(await jsonInput(context, options.blocks), '--blocks');
205
+ }
206
+ if (options.structure === false) {
207
+ request['semEstrutura'] = true;
208
+ }
209
+ return request;
210
+ }
211
+ function printProblems(context, problems) {
212
+ problems.forEach((problem) => {
213
+ printLine(context, ` - ${problem.nodeKey === null ? '' : `${problem.nodeKey}: `}${problem.reason}`);
214
+ });
215
+ }
216
+ function printCard(context, card) {
217
+ printLine(context, card.title);
218
+ card.details.forEach((line) => {
219
+ printLine(context, ` ${line}`);
220
+ });
221
+ if (card.change.changes.length > 0) {
222
+ printLine(context, 'O que sai e o que entra:');
223
+ card.change.changes.forEach((line) => {
224
+ printLine(context, ` ${line}`);
225
+ });
226
+ }
227
+ const subject = card.change.previews[0]?.subject;
228
+ if (subject !== undefined && subject !== null) {
229
+ printLine(context, `Assunto da prévia: ${subject}`);
230
+ }
231
+ printBrand(context, card.change.brand);
232
+ }
233
+ function printApplied(context, applied) {
234
+ printLine(context, `${applied.mensagem} (${applied.modelo}: ${applied.situacao}, versão ${String(applied.versao)})`);
235
+ if (applied.avisoFormato !== undefined) {
236
+ printLine(context, applied.avisoFormato);
237
+ }
238
+ printBrand(context, applied.marca);
239
+ applied.meta?.forEach((line) => {
240
+ printLine(context, `Meta: ${line}`);
241
+ });
242
+ }
243
+ async function change(context, action, templateId, options) {
244
+ const request = await requestOf(context, action, templateId, options);
245
+ const card = (await call(context, options, 'POST', '/v1/message-template-changes/preview', request));
246
+ saveHtml(context, options, card.change.previews[0]?.html ?? null);
247
+ if (options.json !== true) {
248
+ printCard(context, card);
249
+ }
250
+ if (card.change.problems.length > 0) {
251
+ printLine(context, 'O Nexo não aceitou o pedido, corrija e rode de novo:');
252
+ printProblems(context, card.change.problems);
253
+ throw new CliError('Nada foi gravado: o pedido tem problemas.', EXIT_CODES.failure);
254
+ }
255
+ if (!(await confirmed(context, options.yes, 'Gravar assim?'))) {
256
+ if (options.json === true) {
257
+ printJson(context, card);
258
+ }
259
+ return;
260
+ }
261
+ const applied = (await call(context, options, 'POST', '/v1/message-template-changes/apply', {
262
+ ...request,
263
+ confirmationToken: card.confirmation.token
264
+ }));
265
+ if (options.json === true) {
266
+ printJson(context, applied);
267
+ return;
268
+ }
269
+ printApplied(context, applied);
270
+ }
271
+ export async function templatesCreate(context, options) {
272
+ await change(context, 'criar_modelo', undefined, options);
273
+ }
274
+ export async function templatesChange(context, templateId, options) {
275
+ await change(context, 'mudar_modelo', templateId, options);
276
+ }
277
+ export async function templatesPublish(context, templateId, options) {
278
+ await change(context, 'publicar_modelo', templateId, options);
279
+ }
@@ -44,6 +44,10 @@ const HINT_BY_STATUS = {
44
44
  const HINT_BY_TYPE = {
45
45
  'agents.writing_budget': null,
46
46
  'core.too_many_attempts': 'Espere alguns minutos: o limite é por pessoa e por empresa, somado ao do app.',
47
+ 'copilot.confirmation_stale': 'O modelo mudou depois da prévia: rode o comando de novo e confirme.',
48
+ 'brain.skill_shrink_needs_confirmation': 'A edição tira item ou encolhe a skill em mais de 30%: mostre à pessoa e, depois do sim, rode de novo com --confirm-shrink.',
49
+ 'brain.layer_skill_refused': 'O texto foi recusado (ordem ao assistente, número da empresa ou skill repetida): reescreva o item como um jeito de fazer.',
50
+ 'brain.skill_without_usage_condition': 'Falta dizer quando usar: ajuste o objetivo e o momento.',
47
51
  'agents.template_required': 'Diga o modelo da versão nova com --template <id>.'
48
52
  };
49
53
  function hintOf(problem) {
@@ -0,0 +1,111 @@
1
+ import { brainAreas, brainBlindTest, brainChoose, brainCreate, brainEdit, brainFromTemplate, brainList, brainMoments, brainRemove, brainTemplates } from './commands/brain.js';
2
+ function collect(value, previous) {
3
+ return [...previous, value];
4
+ }
5
+ const LEVEL = '<nível>';
6
+ const LEVEL_HELP = 'company (empresa), area, team (time) ou person (pessoal)';
7
+ function addReadCommands(brain, context) {
8
+ brain
9
+ .command('areas')
10
+ .description('As áreas da empresa (o id vai em --area)')
11
+ .action(async (_options, command) => {
12
+ await brainAreas(context, command.optsWithGlobals());
13
+ });
14
+ brain
15
+ .command('moments')
16
+ .description('Os momentos que aceitam skill nova (só os que têm o teste "não piora" funcionando)')
17
+ .action(async (_options, command) => {
18
+ await brainMoments(context, command.optsWithGlobals());
19
+ });
20
+ brain
21
+ .command('list')
22
+ .description('Lista as skills de um nível (a pessoal é só sua)')
23
+ .argument(LEVEL, LEVEL_HELP)
24
+ .option('--scope <id>', 'só de uma área ou de um time')
25
+ .action(async (level, _options, command) => {
26
+ await brainList(context, level, command.optsWithGlobals());
27
+ });
28
+ }
29
+ function addWriteCommands(brain, context) {
30
+ brain
31
+ .command('create')
32
+ .description('Cria uma skill pela ideia; o Cérebro escreve o SKILL.md e a skill nasce em teste. Só admin, com calibration:write')
33
+ .argument(LEVEL, LEVEL_HELP)
34
+ .option('--area <id>', 'a área da skill (nível area)')
35
+ .option('--team <id>', 'o time da skill (nível team)')
36
+ .option('--objective <texto>', 'o objetivo, em uma linha')
37
+ .option('--moment <momento>', 'o momento da lista (nexo brain moments)')
38
+ .option('--always <texto>', 'o que fazer sempre (repita para mais de um)', collect, [])
39
+ .option('--never <texto>', 'o que nunca fazer (repita para mais de um)', collect, [])
40
+ .option('--example <texto>', 'um exemplo de como deve sair, em uma linha')
41
+ .action(async (level, _options, command) => {
42
+ await brainCreate(context, level, command.optsWithGlobals());
43
+ });
44
+ }
45
+ function addPersonCommands(brain, context) {
46
+ brain
47
+ .command('templates')
48
+ .description('Os modelos da Winning para skill pessoal, com os campos de cada um')
49
+ .action(async (_options, command) => {
50
+ await brainTemplates(context, command.optsWithGlobals());
51
+ });
52
+ brain
53
+ .command('from-template')
54
+ .description('Cria uma skill pessoal de um modelo: você preenche os campos, nunca o texto')
55
+ .argument('<modelo>', 'id do modelo (nexo brain templates)')
56
+ .option('--answer <campo=texto>', 'a resposta de um campo do modelo (repita; todos são obrigatórios)', collect, [])
57
+ .action(async (templateId, _options, command) => {
58
+ await brainFromTemplate(context, templateId, command.optsWithGlobals());
59
+ });
60
+ brain
61
+ .command('blind-test')
62
+ .description('Compara às cegas, para uma skill pessoal: dois textos A e B, sem dizer qual tem a skill')
63
+ .argument('<skill>', 'id da skill pessoal')
64
+ .action(async (skillId, _options, command) => {
65
+ await brainBlindTest(context, skillId, command.optsWithGlobals());
66
+ });
67
+ brain
68
+ .command('choose')
69
+ .description('Escolhe A ou B na comparação às cegas; só então diz qual tinha a skill')
70
+ .argument('<comparação>', 'id da comparação (nexo brain blind-test)')
71
+ .argument('<escolha>', 'a ou b')
72
+ .action(async (choiceId, chosen, _options, command) => {
73
+ await brainChoose(context, choiceId, chosen, command.optsWithGlobals());
74
+ });
75
+ }
76
+ function addChangeCommands(brain, context) {
77
+ brain
78
+ .command('edit')
79
+ .description('Edita uma skill por item: soma, atualiza ou remove um item; nenhuma outra linha muda')
80
+ .argument(LEVEL, LEVEL_HELP)
81
+ .argument('<skill>', 'id da skill')
82
+ .option('--add-always <texto>', 'soma um item em "sempre" (repita)', collect, [])
83
+ .option('--add-never <texto>', 'soma um item em "nunca" (repita)', collect, [])
84
+ .option('--update-always <troca>', 'troca um item de "sempre": "atual => novo" (repita)', collect, [])
85
+ .option('--update-never <troca>', 'troca um item de "nunca": "atual => novo" (repita)', collect, [])
86
+ .option('--remove-always <texto>', 'tira um item de "sempre" (repita)', collect, [])
87
+ .option('--remove-never <texto>', 'tira um item de "nunca" (repita)', collect, [])
88
+ .option('--confirm-shrink', 'confirma a edição que tira item ou encolhe a skill em mais de 30%')
89
+ .action(async (level, skillId, _options, command) => {
90
+ await brainEdit(context, level, skillId, command.optsWithGlobals());
91
+ });
92
+ brain
93
+ .command('remove')
94
+ .description('Apaga uma skill de qualquer nível (a pessoal dá para restaurar em 30 dias, pelo app)')
95
+ .argument(LEVEL, LEVEL_HELP)
96
+ .argument('<skill>', 'id da skill')
97
+ .option('-y, --yes', 'apaga sem perguntar (só depois do sim da pessoa)')
98
+ .action(async (level, skillId, _options, command) => {
99
+ await brainRemove(context, level, skillId, command.optsWithGlobals());
100
+ });
101
+ }
102
+ export function addBrainCommands(program, context) {
103
+ const brain = program
104
+ .command('brain')
105
+ .alias('cerebro')
106
+ .description('O Cérebro: as skills da empresa, das áreas e dos times, criadas pela ideia e editadas por item (nunca pelo texto)');
107
+ addReadCommands(brain, context);
108
+ addWriteCommands(brain, context);
109
+ addPersonCommands(brain, context);
110
+ addChangeCommands(brain, context);
111
+ }
@@ -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,8 +7,10 @@ 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';
@@ -86,21 +88,28 @@ function addSkillsCommands(program, context) {
86
88
  const skills = program.command('skills').description('As regras do Nexo para a sua IA (Claude Code, Cursor, Codex)');
87
89
  skills
88
90
  .command('install')
89
- .description('Grava as skills do Nexo no projeto; sem opção, detecta o que o projeto usa')
91
+ .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
92
  .option('--claude', 'em .claude/skills')
91
- .option('--cursor', 'em .cursor/rules')
93
+ .option('--cursor', 'em .cursor/skills')
92
94
  .option('--agents', 'em AGENTS.md e .nexo/skills (Codex e outros)')
93
95
  .option('--all', 'nos três')
94
96
  .option('-d, --dir <pasta>', 'pasta do projeto', '.')
95
- .action((_options, command) => {
96
- skillsInstall(context, command.optsWithGlobals());
97
+ .action(async (_options, command) => {
98
+ await skillsInstall(context, command.optsWithGlobals());
97
99
  });
98
100
  skills
99
101
  .command('list')
100
- .description('Lista as skills e onde estão instaladas no projeto')
102
+ .description('Lista as skills, com o nível de cada uma (produto, empresa, área, time) e onde estão instaladas')
101
103
  .option('-d, --dir <pasta>', 'pasta do projeto', '.')
102
- .action((_options, command) => {
103
- skillsList(context, command.optsWithGlobals());
104
+ .action(async (_options, command) => {
105
+ await skillsList(context, command.optsWithGlobals());
106
+ });
107
+ skills
108
+ .command('show')
109
+ .description('Mostra uma skill inteira, sem gravar nada')
110
+ .argument('<nome>', 'nome da skill (de skills list)')
111
+ .action(async (name, _options, command) => {
112
+ await skillsShow(context, name, command.optsWithGlobals());
104
113
  });
105
114
  }
106
115
  function addMcpCommand(program, context) {
@@ -161,5 +170,7 @@ export function buildProgram(context) {
161
170
  addDocumentCommands(program, context);
162
171
  addDealCommands(program, context);
163
172
  addArtifactCommands(program, context);
173
+ addTemplateCommands(program, context);
174
+ addBrainCommands(program, context);
164
175
  return program;
165
176
  }
@@ -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
+ }