@winning-sales/nexo 0.7.1 → 0.9.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.
- package/README.md +53 -3
- package/assets/connect/connect-sdk.d.ts +294 -11
- package/assets/connect/manifest.schema.json +598 -9
- package/assets/docs/pages.json +1 -1
- package/assets/skills/nexo-api/SKILL.md +8 -0
- package/assets/skills/nexo-automations/SKILL.md +10 -0
- package/assets/skills/nexo-connect/SKILL.md +15 -4
- package/assets/skills/nexo-dashboards/SKILL.md +2 -0
- package/dist/commands/agents.js +241 -0
- package/dist/commands/automations.js +32 -17
- package/dist/commands/brain.js +16 -1
- package/dist/commands/connect-access.js +64 -23
- package/dist/commands/context-company.js +137 -0
- package/dist/commands/knowledge.js +261 -0
- package/dist/connect/access.js +81 -7
- package/dist/connect/changes.js +12 -1
- package/dist/connect/runs.js +1 -1
- package/dist/program-agents.js +65 -0
- package/dist/program-brain.js +1 -0
- package/dist/program-connect-access.js +16 -9
- package/dist/program-context.js +61 -0
- package/dist/program-knowledge.js +130 -0
- package/dist/program.js +10 -1
- package/dist/tools/tool-manifest.js +30 -1
- package/package.json +1 -1
- package/reference.json +945 -132
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import { clientOf, printJson, printLine, sessionOf } from '../context.js';
|
|
2
|
+
import { usageError } from '../errors.js';
|
|
3
|
+
import { confirmed } from '../input/confirm.js';
|
|
4
|
+
/** O bloco da rota de escrita (português) e o canvas que GET /v1/company/context devolve. */
|
|
5
|
+
const BLOCKS = {
|
|
6
|
+
empresa: 'company',
|
|
7
|
+
icp: 'icp',
|
|
8
|
+
persona: 'persona',
|
|
9
|
+
proposta_de_valor: 'value-prop',
|
|
10
|
+
posicionamento: 'positioning',
|
|
11
|
+
oferta: 'offer',
|
|
12
|
+
prova: 'proof'
|
|
13
|
+
};
|
|
14
|
+
const STATES = { confirmed: 'confirmado', draft: 'rascunho', empty: 'vazio' };
|
|
15
|
+
async function call(context, options, method, path, body) {
|
|
16
|
+
const response = await clientOf(context, sessionOf(context, options)).request({
|
|
17
|
+
method,
|
|
18
|
+
path,
|
|
19
|
+
...(body === undefined ? {} : { body })
|
|
20
|
+
});
|
|
21
|
+
return response.body;
|
|
22
|
+
}
|
|
23
|
+
function blockOf(raw) {
|
|
24
|
+
const name = raw.trim().toLowerCase().replaceAll('-', '_');
|
|
25
|
+
if (BLOCKS[name] === undefined) {
|
|
26
|
+
throw usageError(`Bloco "${raw}" não existe: use ${Object.keys(BLOCKS).join(', ')}.`);
|
|
27
|
+
}
|
|
28
|
+
return name;
|
|
29
|
+
}
|
|
30
|
+
function valueOf(raw, options) {
|
|
31
|
+
if (options.valueJson !== true) {
|
|
32
|
+
return raw;
|
|
33
|
+
}
|
|
34
|
+
try {
|
|
35
|
+
return JSON.parse(raw);
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
throw usageError('Com --value-json, o valor precisa ser JSON válido (texto vai entre aspas).');
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
function itemOf(raw, index) {
|
|
42
|
+
if ((raw === undefined) === (index === undefined)) {
|
|
43
|
+
throw usageError('Diga o item (o texto exato) ou --index <posição>, um dos dois.');
|
|
44
|
+
}
|
|
45
|
+
if (index === undefined) {
|
|
46
|
+
return raw;
|
|
47
|
+
}
|
|
48
|
+
if (!/^\d+$/.test(index)) {
|
|
49
|
+
throw usageError(`--index precisa de um número a partir de 0 (recebi "${index}").`);
|
|
50
|
+
}
|
|
51
|
+
return Number(index);
|
|
52
|
+
}
|
|
53
|
+
function isRecord(value) {
|
|
54
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
55
|
+
}
|
|
56
|
+
function isField(value) {
|
|
57
|
+
return 'value' in value && 'origin' in value;
|
|
58
|
+
}
|
|
59
|
+
function leaves(node, path) {
|
|
60
|
+
if (Array.isArray(node)) {
|
|
61
|
+
return node.flatMap((child, index) => leaves(child, path === '' ? String(index) : `${path}.${String(index)}`));
|
|
62
|
+
}
|
|
63
|
+
if (!isRecord(node)) {
|
|
64
|
+
return [];
|
|
65
|
+
}
|
|
66
|
+
if (isField(node)) {
|
|
67
|
+
const value = node['value'];
|
|
68
|
+
const text = typeof value === 'string' ? value : JSON.stringify(value);
|
|
69
|
+
return [` ${path} = ${text === '' ? '(vazio)' : text} [${String(node['origin'])}]`];
|
|
70
|
+
}
|
|
71
|
+
return Object.entries(node).flatMap(([key, child]) => leaves(child, path === '' ? key : `${path}.${key}`));
|
|
72
|
+
}
|
|
73
|
+
function printBlock(context, name, canvas) {
|
|
74
|
+
const state = STATES[canvas.state] ?? canvas.state;
|
|
75
|
+
printLine(context, `${name}: ${state}${canvas.version === null ? '' : `, versão ${String(canvas.version)}`}`);
|
|
76
|
+
leaves(canvas.canvas, '').forEach((line) => {
|
|
77
|
+
printLine(context, line);
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
export async function contextShow(context, rawBlock, options) {
|
|
81
|
+
const only = rawBlock === undefined ? undefined : blockOf(rawBlock);
|
|
82
|
+
const body = (await call(context, options, 'GET', '/v1/company/context'));
|
|
83
|
+
const names = only === undefined ? Object.keys(BLOCKS) : [only];
|
|
84
|
+
if (options.json === true) {
|
|
85
|
+
printJson(context, only === undefined ? body : { [only]: body.canvases[BLOCKS[only]] });
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
for (const name of names) {
|
|
89
|
+
const canvas = body.canvases[BLOCKS[name]];
|
|
90
|
+
if (canvas !== undefined) {
|
|
91
|
+
printBlock(context, name, canvas);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
async function change(context, request, options) {
|
|
96
|
+
const body = options.changeConfirmed === true ? { ...request, confirmaBlocoConfirmado: true } : request;
|
|
97
|
+
const card = (await call(context, options, 'POST', '/v1/company/context/changes/preview', body));
|
|
98
|
+
if (options.json !== true) {
|
|
99
|
+
printLine(context, card.title);
|
|
100
|
+
card.details.forEach((line) => {
|
|
101
|
+
printLine(context, ` ${line}`);
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
if (!(await confirmed(context, options.yes, 'Gravar assim?'))) {
|
|
105
|
+
if (options.json === true) {
|
|
106
|
+
printJson(context, card);
|
|
107
|
+
}
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
const applied = (await call(context, options, 'POST', '/v1/company/context/changes/apply', {
|
|
111
|
+
...body,
|
|
112
|
+
confirmationToken: card.confirmation.token
|
|
113
|
+
}));
|
|
114
|
+
if (options.json === true) {
|
|
115
|
+
printJson(context, applied);
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
printLine(context, applied.message);
|
|
119
|
+
}
|
|
120
|
+
function fieldOf(raw) {
|
|
121
|
+
if (raw.trim() === '') {
|
|
122
|
+
throw usageError('Diga o campo, com pontos e posições a partir de 0 (como `nexo context show` mostra).');
|
|
123
|
+
}
|
|
124
|
+
return raw.trim();
|
|
125
|
+
}
|
|
126
|
+
export async function contextSet(context, rawBlock, field, value, options) {
|
|
127
|
+
await change(context, { bloco: blockOf(rawBlock), acao: 'campo_mudar', campo: fieldOf(field), valor: valueOf(value, options) }, options);
|
|
128
|
+
}
|
|
129
|
+
export async function contextAdd(context, rawBlock, field, value, options) {
|
|
130
|
+
await change(context, { bloco: blockOf(rawBlock), acao: 'item_somar', campo: fieldOf(field), valor: valueOf(value, options) }, options);
|
|
131
|
+
}
|
|
132
|
+
export async function contextRemove(context, rawBlock, field, item, options) {
|
|
133
|
+
await change(context, { bloco: blockOf(rawBlock), acao: 'item_tirar', campo: fieldOf(field), item: itemOf(item, options.index) }, options);
|
|
134
|
+
}
|
|
135
|
+
export async function contextConfirm(context, rawBlock, options) {
|
|
136
|
+
await change(context, { bloco: blockOf(rawBlock), acao: 'bloco_confirmar' }, options);
|
|
137
|
+
}
|
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
import { clientOf, printJson, printLine, printNotice, sessionOf } from '../context.js';
|
|
2
|
+
import { usageError } from '../errors.js';
|
|
3
|
+
import { confirmed } from '../input/confirm.js';
|
|
4
|
+
export const RULE_SUBJECTS = [
|
|
5
|
+
'discount',
|
|
6
|
+
'minimum_price',
|
|
7
|
+
'deadline',
|
|
8
|
+
'payment_terms',
|
|
9
|
+
'integration',
|
|
10
|
+
'scope',
|
|
11
|
+
'implementation'
|
|
12
|
+
];
|
|
13
|
+
export const RESOLVE_ACTIONS = ['choose', 'approve', 'use', 'rewrite', 'discard'];
|
|
14
|
+
export const ITEM_TYPES = ['rule', 'practice', 'product_fact', 'price', 'proof', 'standard'];
|
|
15
|
+
const MAX_MOVE = 100;
|
|
16
|
+
async function call(context, options, method, path, extra = {}) {
|
|
17
|
+
const response = await clientOf(context, sessionOf(context, options)).request({ method, path, ...extra });
|
|
18
|
+
return response.body;
|
|
19
|
+
}
|
|
20
|
+
function typeOf(raw) {
|
|
21
|
+
if (raw === undefined) {
|
|
22
|
+
return undefined;
|
|
23
|
+
}
|
|
24
|
+
if (!ITEM_TYPES.includes(raw)) {
|
|
25
|
+
throw usageError(`Tipo "${raw}" não existe: use ${ITEM_TYPES.join(', ')}.`);
|
|
26
|
+
}
|
|
27
|
+
return raw;
|
|
28
|
+
}
|
|
29
|
+
/** The structured fields of a rule, as the server wants them: the subject plus four nullable strings. */
|
|
30
|
+
function ruleOf(options) {
|
|
31
|
+
const given = [options.subject, options.condition, options.limit, options.exception, options.approver];
|
|
32
|
+
if (given.every((value) => value === undefined)) {
|
|
33
|
+
return undefined;
|
|
34
|
+
}
|
|
35
|
+
if (options.subject === undefined || !RULE_SUBJECTS.includes(options.subject)) {
|
|
36
|
+
throw usageError(`Os campos da regra pedem --subject: ${RULE_SUBJECTS.join(', ')}.`, '--condition, --limit, --exception e --approver são opcionais; numa edição, o que não vier fica vazio.');
|
|
37
|
+
}
|
|
38
|
+
return {
|
|
39
|
+
subject: options.subject,
|
|
40
|
+
condition: options.condition ?? null,
|
|
41
|
+
limit: options.limit ?? null,
|
|
42
|
+
exception: options.exception ?? null,
|
|
43
|
+
approver: options.approver ?? null
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
function themeName(item) {
|
|
47
|
+
return item.theme?.name ?? item.themeId ?? '-';
|
|
48
|
+
}
|
|
49
|
+
function printItem(context, item) {
|
|
50
|
+
printLine(context, `${item.id} ${item.type.padEnd(12)} [${item.status}] tema: ${themeName(item)}`);
|
|
51
|
+
printLine(context, ` ${item.text}`);
|
|
52
|
+
}
|
|
53
|
+
const MAX_LIST_PAGES = 200;
|
|
54
|
+
async function listPage(context, options, query) {
|
|
55
|
+
return (await call(context, options, 'GET', '/v1/knowledge/items', { query }));
|
|
56
|
+
}
|
|
57
|
+
function inTheme(items, themeId) {
|
|
58
|
+
return items.filter((item) => (item.themeId ?? item.theme?.id) === themeId);
|
|
59
|
+
}
|
|
60
|
+
/** Walks every page and keeps the items of one theme: the API has no theme filter on the list. */
|
|
61
|
+
async function itemsOfTheme(context, options, base, themeId) {
|
|
62
|
+
const kept = [];
|
|
63
|
+
let page = 1;
|
|
64
|
+
let totalPages = 1;
|
|
65
|
+
while (page <= totalPages && page <= MAX_LIST_PAGES) {
|
|
66
|
+
const result = await listPage(context, options, { ...base, page: String(page), pageSize: '100' });
|
|
67
|
+
kept.push(...inTheme(result.data, themeId));
|
|
68
|
+
totalPages = result.pagination.totalPages;
|
|
69
|
+
page += 1;
|
|
70
|
+
}
|
|
71
|
+
return { data: kept, pagination: { page: 1, totalPages: 1, totalRecords: kept.length } };
|
|
72
|
+
}
|
|
73
|
+
function listQueryOf(options) {
|
|
74
|
+
const query = {};
|
|
75
|
+
const type = typeOf(options.type);
|
|
76
|
+
if (type !== undefined) {
|
|
77
|
+
query.type = type;
|
|
78
|
+
}
|
|
79
|
+
if (options.needsYou === true) {
|
|
80
|
+
query.needsYou = 'true';
|
|
81
|
+
}
|
|
82
|
+
if (options.theme === undefined) {
|
|
83
|
+
if (options.page !== undefined) {
|
|
84
|
+
query.page = options.page;
|
|
85
|
+
}
|
|
86
|
+
if (options.pageSize !== undefined) {
|
|
87
|
+
query.pageSize = options.pageSize;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
return query;
|
|
91
|
+
}
|
|
92
|
+
export async function itemsList(context, options) {
|
|
93
|
+
const query = listQueryOf(options);
|
|
94
|
+
const page = options.theme === undefined ? await listPage(context, options, query) : await itemsOfTheme(context, options, query, options.theme);
|
|
95
|
+
if (options.json === true) {
|
|
96
|
+
printJson(context, page);
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
if (page.data.length === 0) {
|
|
100
|
+
printLine(context, 'Nenhum item.');
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
page.data.forEach((item) => {
|
|
104
|
+
printItem(context, item);
|
|
105
|
+
});
|
|
106
|
+
if (page.pagination.page < page.pagination.totalPages) {
|
|
107
|
+
printNotice(context, `Página ${String(page.pagination.page)} de ${String(page.pagination.totalPages)}: veja a próxima com --page.`);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
export async function itemsCreate(context, options) {
|
|
111
|
+
const type = typeOf(options.type);
|
|
112
|
+
if (type === undefined || options.text === undefined || options.text.trim() === '') {
|
|
113
|
+
throw usageError('Diga o tipo (--type) e o texto (--text) do item.', `Tipos: ${ITEM_TYPES.join(', ')}.`);
|
|
114
|
+
}
|
|
115
|
+
const rule = ruleOf(options);
|
|
116
|
+
if (type === 'rule' && rule === undefined) {
|
|
117
|
+
throw usageError('Item do tipo rule pede --subject (e, se quiser, --condition, --limit, --exception, --approver).');
|
|
118
|
+
}
|
|
119
|
+
const body = { type, text: options.text };
|
|
120
|
+
if (rule !== undefined) {
|
|
121
|
+
body.rule = rule;
|
|
122
|
+
}
|
|
123
|
+
if (options.theme !== undefined) {
|
|
124
|
+
body.themeId = options.theme;
|
|
125
|
+
}
|
|
126
|
+
const item = (await call(context, options, 'POST', '/v1/knowledge/items', { body }));
|
|
127
|
+
if (options.json === true) {
|
|
128
|
+
printJson(context, item);
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
printLine(context, 'Item criado; já está em uso.');
|
|
132
|
+
printItem(context, item);
|
|
133
|
+
}
|
|
134
|
+
export async function itemsEdit(context, itemId, options) {
|
|
135
|
+
const body = {};
|
|
136
|
+
const type = typeOf(options.type);
|
|
137
|
+
if (type !== undefined) {
|
|
138
|
+
body.type = type;
|
|
139
|
+
}
|
|
140
|
+
if (options.theme !== undefined) {
|
|
141
|
+
body.themeId = options.theme;
|
|
142
|
+
}
|
|
143
|
+
if (options.text !== undefined) {
|
|
144
|
+
body.text = options.text;
|
|
145
|
+
}
|
|
146
|
+
const rule = ruleOf(options);
|
|
147
|
+
if (rule !== undefined) {
|
|
148
|
+
body.rule = rule;
|
|
149
|
+
}
|
|
150
|
+
if (Object.keys(body).length === 0) {
|
|
151
|
+
throw usageError('Nenhuma mudança: use --text, --type, --theme ou os campos da regra (--subject ...).');
|
|
152
|
+
}
|
|
153
|
+
const item = (await call(context, options, 'PATCH', `/v1/knowledge/items/${encodeURIComponent(itemId)}`, { body }));
|
|
154
|
+
if (options.json === true) {
|
|
155
|
+
printJson(context, item);
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
printLine(context, 'Item editado.');
|
|
159
|
+
printItem(context, item);
|
|
160
|
+
}
|
|
161
|
+
export async function itemsMove(context, itemIds, options) {
|
|
162
|
+
if (options.theme === undefined) {
|
|
163
|
+
throw usageError('Diga o tema de destino com --theme <id> (`nexo knowledge themes list`).');
|
|
164
|
+
}
|
|
165
|
+
if (itemIds.length === 0 || itemIds.length > MAX_MOVE) {
|
|
166
|
+
throw usageError(`Passe de 1 a ${String(MAX_MOVE)} ids de item.`);
|
|
167
|
+
}
|
|
168
|
+
const result = (await call(context, options, 'POST', '/v1/knowledge/items/move', {
|
|
169
|
+
body: { itemIds, themeId: options.theme }
|
|
170
|
+
}));
|
|
171
|
+
if (options.json === true) {
|
|
172
|
+
printJson(context, result);
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
175
|
+
printLine(context, `${String(result.moved)} item(ns) no tema ${result.themeId}.`);
|
|
176
|
+
}
|
|
177
|
+
export async function themesList(context, options) {
|
|
178
|
+
const list = (await call(context, options, 'GET', '/v1/knowledge/themes'));
|
|
179
|
+
if (options.json === true) {
|
|
180
|
+
printJson(context, list);
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
if (list.data.length === 0) {
|
|
184
|
+
printLine(context, 'Nenhum tema.');
|
|
185
|
+
}
|
|
186
|
+
for (const theme of list.data) {
|
|
187
|
+
printLine(context, `${theme.id} ${theme.name} (${String(theme.itemCount)} itens, ${String(theme.materialCount)} arquivos, ${String(theme.webSourceCount)} fontes web)`);
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
function nameOf(name) {
|
|
191
|
+
if (name.trim() === '') {
|
|
192
|
+
throw usageError('O nome do tema não pode ser vazio.');
|
|
193
|
+
}
|
|
194
|
+
return name;
|
|
195
|
+
}
|
|
196
|
+
export async function themesCreate(context, name, options) {
|
|
197
|
+
const theme = (await call(context, options, 'POST', '/v1/knowledge/themes', { body: { name: nameOf(name) } }));
|
|
198
|
+
if (options.json === true) {
|
|
199
|
+
printJson(context, theme);
|
|
200
|
+
return;
|
|
201
|
+
}
|
|
202
|
+
printLine(context, `Tema criado: ${theme.id} ${theme.name}`);
|
|
203
|
+
}
|
|
204
|
+
export async function themesRename(context, themeId, name, options) {
|
|
205
|
+
const theme = (await call(context, options, 'PATCH', `/v1/knowledge/themes/${encodeURIComponent(themeId)}`, {
|
|
206
|
+
body: { name: nameOf(name) }
|
|
207
|
+
}));
|
|
208
|
+
if (options.json === true) {
|
|
209
|
+
printJson(context, theme);
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
printLine(context, `Tema renomeado: ${theme.id} ${theme.name}`);
|
|
213
|
+
}
|
|
214
|
+
export async function themesRemove(context, themeId, options) {
|
|
215
|
+
if (!(await confirmed(context, options.yes, `Apagar o tema ${themeId}? Só passa se ele estiver vazio.`))) {
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
await call(context, options, 'DELETE', `/v1/knowledge/themes/${encodeURIComponent(themeId)}`);
|
|
219
|
+
printLine(context, 'Tema apagado.');
|
|
220
|
+
}
|
|
221
|
+
function itemPath(itemId, suffix = '') {
|
|
222
|
+
return `/v1/knowledge/items/${encodeURIComponent(itemId)}${suffix}`;
|
|
223
|
+
}
|
|
224
|
+
export async function itemsSwitch(context, itemId, on, options) {
|
|
225
|
+
const item = (await call(context, options, 'POST', itemPath(itemId, on ? '/enable' : '/disable')));
|
|
226
|
+
if (options.json === true) {
|
|
227
|
+
printJson(context, item);
|
|
228
|
+
return;
|
|
229
|
+
}
|
|
230
|
+
printLine(context, on ? 'Item ligado: de volta em uso.' : 'Item desligado: fora de uso, sem apagar.');
|
|
231
|
+
printItem(context, item);
|
|
232
|
+
}
|
|
233
|
+
export async function itemsResolve(context, itemId, options) {
|
|
234
|
+
const action = options.action;
|
|
235
|
+
if (action === undefined || !RESOLVE_ACTIONS.includes(action)) {
|
|
236
|
+
throw usageError(`Diga a ação com --action: ${RESOLVE_ACTIONS.join(', ')}.`);
|
|
237
|
+
}
|
|
238
|
+
if (action === 'rewrite' && (options.text === undefined || options.text.trim() === '')) {
|
|
239
|
+
throw usageError('A ação rewrite pede o texto novo com --text.');
|
|
240
|
+
}
|
|
241
|
+
if (action === 'discard' && !(await confirmed(context, options.yes, `Descartar o item ${itemId}? Ele sai da Base de vez.`))) {
|
|
242
|
+
return;
|
|
243
|
+
}
|
|
244
|
+
const body = { action };
|
|
245
|
+
if (action === 'rewrite') {
|
|
246
|
+
body.text = options.text;
|
|
247
|
+
}
|
|
248
|
+
const result = await call(context, options, 'POST', itemPath(itemId, '/resolve'), { body });
|
|
249
|
+
if (options.json === true) {
|
|
250
|
+
printJson(context, result);
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
printLine(context, `Pendência resolvida (${action}).`);
|
|
254
|
+
}
|
|
255
|
+
export async function itemsRemove(context, itemId, options) {
|
|
256
|
+
if (!(await confirmed(context, options.yes, `Remover o item ${itemId}? Ele não volta com o mesmo material (para tirar de uso, use off).`))) {
|
|
257
|
+
return;
|
|
258
|
+
}
|
|
259
|
+
await call(context, options, 'DELETE', itemPath(itemId));
|
|
260
|
+
printLine(context, 'Item removido.');
|
|
261
|
+
}
|
package/dist/connect/access.js
CHANGED
|
@@ -37,7 +37,25 @@ export function isSecretList(value) {
|
|
|
37
37
|
}
|
|
38
38
|
export function isWebhook(value) {
|
|
39
39
|
const fields = fieldsOf(value);
|
|
40
|
-
return fields !== null && typeof fields.url === 'string' &&
|
|
40
|
+
return fields !== null && typeof fields.url === 'string' && isAuthOrNull(fields.auth) && isAuthOrNull(fields.authInEdit);
|
|
41
|
+
}
|
|
42
|
+
function isAuthOrNull(value) {
|
|
43
|
+
if (value === null) {
|
|
44
|
+
return true;
|
|
45
|
+
}
|
|
46
|
+
const fields = fieldsOf(value);
|
|
47
|
+
return fields !== null && typeof fields.type === 'string' && typeof fields.secret === 'string';
|
|
48
|
+
}
|
|
49
|
+
export function isWebhookDeliveryList(value) {
|
|
50
|
+
const fields = fieldsOf(value);
|
|
51
|
+
return (fields !== null &&
|
|
52
|
+
Array.isArray(fields.deliveries) &&
|
|
53
|
+
fields.deliveries.every((item) => isDelivery(item)) &&
|
|
54
|
+
(fields.next === null || typeof fields.next === 'string'));
|
|
55
|
+
}
|
|
56
|
+
function isDelivery(item) {
|
|
57
|
+
const delivery = fieldsOf(item);
|
|
58
|
+
return delivery !== null && typeof delivery.receivedAt === 'string' && typeof delivery.outcome === 'string';
|
|
41
59
|
}
|
|
42
60
|
export function isOAuthStatus(value) {
|
|
43
61
|
const fields = fieldsOf(value);
|
|
@@ -68,12 +86,68 @@ export function isMailFileList(value) {
|
|
|
68
86
|
export function describeSecret(slot) {
|
|
69
87
|
return `${slot.name.padEnd(28)} ${slot.filled ? `preenchido${slot.setAt === null ? '' : ` desde ${slot.setAt}`}` : 'faltando'}`;
|
|
70
88
|
}
|
|
71
|
-
export
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
89
|
+
export const WEBHOOK_URL_WARNING = 'O endereço é a credencial do webhook: quem o tem pode chamá-lo. Não o cole em lugar público nem em chat; só no outro sistema.';
|
|
90
|
+
const OUTCOME_NAMES = {
|
|
91
|
+
ran: 'rodou',
|
|
92
|
+
waiting: 'esperando a vez',
|
|
93
|
+
refused: 'recusada',
|
|
94
|
+
discarded: 'descartada'
|
|
95
|
+
};
|
|
96
|
+
const REASON_NAMES = {
|
|
97
|
+
missing: 'a chamada veio sem a autenticação declarada',
|
|
98
|
+
mismatch: 'a autenticação não confere com o segredo',
|
|
99
|
+
stale: 'a hora da chamada está fora da tolerância',
|
|
100
|
+
secret_missing: 'o segredo da autenticação não está preenchido no Nexo',
|
|
101
|
+
not_published: 'o conector não tem versão publicada',
|
|
102
|
+
no_webhook_trigger: 'a versão publicada não tem gatilho de webhook',
|
|
103
|
+
disabled: 'o conector está desligado',
|
|
104
|
+
paused: 'o conector está pausado',
|
|
105
|
+
unstorable: 'o corpo não pôde ser guardado'
|
|
106
|
+
};
|
|
107
|
+
/** Os nomes dos segredos que a autenticação usa, sem repetir. */
|
|
108
|
+
export function authSecretNames(auth) {
|
|
109
|
+
return auth === null
|
|
110
|
+
? []
|
|
111
|
+
: [...new Set([auth.user, auth.secret].filter((name) => name !== undefined))];
|
|
112
|
+
}
|
|
113
|
+
function describeHmac(auth) {
|
|
114
|
+
const timed = auth.signed === 'timestamp.body';
|
|
115
|
+
const prefix = auth.prefix === undefined || auth.prefix === '' ? '' : ` (com o prefixo ${auth.prefix})`;
|
|
116
|
+
const time = timed
|
|
117
|
+
? `; o cabeçalho ${auth.timestampHeader ?? '?'} leva a hora, em segundos (${String(auth.toleranceSeconds ?? 300)} s de tolerância)`
|
|
118
|
+
: '';
|
|
119
|
+
const algorithm = (auth.algorithm ?? 'sha256').toUpperCase();
|
|
120
|
+
return `assinatura HMAC-${algorithm} (${auth.encoding ?? 'hex'}) ${timed ? 'de "<hora>.<corpo>"' : 'do corpo'} com o segredo ${auth.secret}, no cabeçalho ${auth.header ?? '?'}${prefix}${time}`;
|
|
121
|
+
}
|
|
122
|
+
export function describeAuth(auth) {
|
|
123
|
+
if (auth.type === 'header') {
|
|
124
|
+
return `o cabeçalho ${auth.header ?? '?'} leva o valor do segredo ${auth.secret}`;
|
|
125
|
+
}
|
|
126
|
+
if (auth.type === 'basic') {
|
|
127
|
+
return `HTTP Basic, com o usuário do segredo ${auth.user ?? '?'} e a senha do segredo ${auth.secret}`;
|
|
128
|
+
}
|
|
129
|
+
return describeHmac(auth);
|
|
130
|
+
}
|
|
131
|
+
/** `missing`: os nomes de segredo da autenticação que o Nexo ainda não tem preenchidos. */
|
|
132
|
+
export function describeWebhook(webhook, missing) {
|
|
133
|
+
const lines = [`URL: ${webhook.url} (POST)`, WEBHOOK_URL_WARNING];
|
|
134
|
+
lines.push(webhook.auth === null
|
|
135
|
+
? 'Autenticação publicada: nenhuma `auth` declarada. Com versão publicada e gatilho de webhook, a autenticação é o token do endereço (/webhooks/connect/<token>): o Nexo não exige assinatura, e quem tem o endereço pode chamar. Sem versão publicada ou sem gatilho de webhook, a chamada é descartada e nada roda. Para exigir também um cabeçalho, HTTP Basic ou HMAC, declare `auth` no manifesto e publique.'
|
|
136
|
+
: `Autenticação publicada (a que confere as chamadas agora, além do token do endereço): ${describeAuth(webhook.auth)}.`);
|
|
137
|
+
if (JSON.stringify(webhook.authInEdit) !== JSON.stringify(webhook.auth)) {
|
|
138
|
+
lines.push(webhook.authInEdit === null
|
|
139
|
+
? 'Na versão em edição: nenhuma `auth` declarada; só o token do endereço (vale depois de publicar).'
|
|
140
|
+
: `Na versão em edição (vale depois de publicar): ${describeAuth(webhook.authInEdit)}.`);
|
|
141
|
+
}
|
|
142
|
+
if (missing.length > 0) {
|
|
143
|
+
lines.push(`Falta preencher: ${missing.join(', ')}. Preencha com \`nexo connect secrets set <NOME>\`.`);
|
|
144
|
+
}
|
|
145
|
+
return lines;
|
|
146
|
+
}
|
|
147
|
+
export function describeDelivery(delivery) {
|
|
148
|
+
const reason = delivery.reason === null ? null : (REASON_NAMES[delivery.reason] ?? delivery.reason);
|
|
149
|
+
const run = delivery.runId === null ? '' : ` execução ${delivery.runId}${delivery.runStatus === null ? '' : ` (${delivery.runStatus})`}`;
|
|
150
|
+
return `${delivery.receivedAt} ${(OUTCOME_NAMES[delivery.outcome] ?? delivery.outcome).padEnd(15)} ${delivery.contentType ?? 'sem tipo'}, ${String(delivery.sizeBytes)} bytes${reason === null ? '' : `; motivo: ${reason}`}${run === '' ? '' : `;${run}`}`;
|
|
77
151
|
}
|
|
78
152
|
const APP_NAMES = {
|
|
79
153
|
nexo: 'o app do Nexo',
|
package/dist/connect/changes.js
CHANGED
|
@@ -34,6 +34,17 @@ async function apply(context, session, request, token) {
|
|
|
34
34
|
printLine(context, line);
|
|
35
35
|
}
|
|
36
36
|
}
|
|
37
|
+
/** Com `--json` o stdout é um JSON só em todo caminho: a prévia vai para o stderr. */
|
|
38
|
+
function showPreviewFor(context, preview, json) {
|
|
39
|
+
if (!json) {
|
|
40
|
+
showPreview(context, preview);
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
printNotice(context, preview.title);
|
|
44
|
+
for (const change of preview.changes) {
|
|
45
|
+
printNotice(context, ` - ${change}`);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
37
48
|
export function showPreview(context, preview) {
|
|
38
49
|
printLine(context, preview.title);
|
|
39
50
|
for (const change of preview.changes) {
|
|
@@ -94,7 +105,7 @@ export async function requestChange(context, session, request) {
|
|
|
94
105
|
printJson(context, response.body);
|
|
95
106
|
return;
|
|
96
107
|
}
|
|
97
|
-
|
|
108
|
+
showPreviewFor(context, response.body, request.json);
|
|
98
109
|
await decide(context, session, request, response.body);
|
|
99
110
|
}
|
|
100
111
|
function reportApplied(context, change, response) {
|
package/dist/connect/runs.js
CHANGED
|
@@ -43,7 +43,7 @@ function plannedLines(title, calls) {
|
|
|
43
43
|
];
|
|
44
44
|
}
|
|
45
45
|
function failedSteps(steps) {
|
|
46
|
-
const failed = (steps ?? []).filter((step) => step.errorCode !== null || (step.status ?? 0) >= 400);
|
|
46
|
+
const failed = (steps ?? []).filter((step) => (step.errorCode ?? null) !== null || (step.status ?? 0) >= 400);
|
|
47
47
|
return failed
|
|
48
48
|
.slice(0, 10)
|
|
49
49
|
.map((step) => ` ${step.kind} ${step.target ?? ''} → ${step.errorCode ?? String(step.status)}: ${step.message ?? ''}`.trimEnd());
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { agentsHours, agentsList, agentsSet, agentsShow } from './commands/agents.js';
|
|
2
|
+
import { usageError } from './errors.js';
|
|
3
|
+
function collect(value, previous) {
|
|
4
|
+
return [...(previous ?? []), value];
|
|
5
|
+
}
|
|
6
|
+
function addShowAndSet(agents, context) {
|
|
7
|
+
agents
|
|
8
|
+
.command('show')
|
|
9
|
+
.description('Mostra a configuração de um agente')
|
|
10
|
+
.argument('<agente>', 'sdr ou cs')
|
|
11
|
+
.action(async (role, _options, command) => {
|
|
12
|
+
await agentsShow(context, role, command.optsWithGlobals());
|
|
13
|
+
});
|
|
14
|
+
agents
|
|
15
|
+
.command('set')
|
|
16
|
+
.description('Muda um agente: mostra o que muda e só salva depois do sim (só administrador)')
|
|
17
|
+
.argument('<agente>', 'sdr ou cs')
|
|
18
|
+
.option('--on', 'liga o agente')
|
|
19
|
+
.option('--off', 'desliga o agente')
|
|
20
|
+
.option('--cases <casos>', 'after_hours, stalled_queue e covered_by_knowledge, separados por vírgula; none para nenhum')
|
|
21
|
+
.option('--book-meeting', 'o Agente SDR marca reunião na agenda do vendedor')
|
|
22
|
+
.option('--no-book-meeting', 'o Agente SDR deixa de marcar reunião')
|
|
23
|
+
.option('--meeting-minutes <min>', 'duração da reunião: 30, 45 ou 60')
|
|
24
|
+
.option('--meeting-lead <min>', 'antecedência mínima da reunião: 120, 240 ou 1440')
|
|
25
|
+
.option('--name <nome>', 'nome do agente nas conversas (até 30 caracteres)')
|
|
26
|
+
.option('-y, --yes', 'salva logo depois de mostrar o que muda')
|
|
27
|
+
.action(async (role, _options, command) => {
|
|
28
|
+
refuseBothBookFlags(command);
|
|
29
|
+
await agentsSet(context, role, command.optsWithGlobals());
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
function addHours(agents, context) {
|
|
33
|
+
agents
|
|
34
|
+
.command('hours')
|
|
35
|
+
.description('O horário de reunião: sem vendedor, lê e muda o seu; com o id de um vendedor, só lê (cada um muda o próprio). Mudar mostra o que muda e pede o sim')
|
|
36
|
+
.argument('[vendedor]', 'id do vendedor, só para ler')
|
|
37
|
+
.option('--day <dias=faixas>', 'o horário próprio inteiro, como seg-sex=09:00-12:00,14:00-18:00 (repita por dia ou grupo de dias)', collect)
|
|
38
|
+
.option('--company', 'apaga o horário próprio e volta ao da empresa')
|
|
39
|
+
.option('-y, --yes', 'salva logo depois de mostrar o que muda')
|
|
40
|
+
.action(async (seller, _options, command) => {
|
|
41
|
+
await agentsHours(context, seller, command.optsWithGlobals());
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
/** Commander keeps only the last of --book-meeting and --no-book-meeting, so the contradiction is read from the arguments. */
|
|
45
|
+
function refuseBothBookFlags(command) {
|
|
46
|
+
let root = command;
|
|
47
|
+
while (root.parent !== null) {
|
|
48
|
+
root = root.parent;
|
|
49
|
+
}
|
|
50
|
+
const args = root.rawArgs;
|
|
51
|
+
if (args.includes('--book-meeting') && args.includes('--no-book-meeting')) {
|
|
52
|
+
throw usageError('Escolha --book-meeting ou --no-book-meeting, não os dois.');
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
export function addAgentCommands(program, context) {
|
|
56
|
+
const agents = program
|
|
57
|
+
.command('agents')
|
|
58
|
+
.alias('agentes')
|
|
59
|
+
.description('Os Agentes de atendimento (SDR e CS): o estado, a configuração e o horário de reunião')
|
|
60
|
+
.action(async (_options, command) => {
|
|
61
|
+
await agentsList(context, command.optsWithGlobals());
|
|
62
|
+
});
|
|
63
|
+
addShowAndSet(agents, context);
|
|
64
|
+
addHours(agents, context);
|
|
65
|
+
}
|
package/dist/program-brain.js
CHANGED
|
@@ -35,6 +35,7 @@ function addWriteCommands(brain, context) {
|
|
|
35
35
|
.option('--team <id>', 'o time da skill (nível team)')
|
|
36
36
|
.option('--objective <texto>', 'o objetivo, em uma linha')
|
|
37
37
|
.option('--moment <momento>', 'o momento da lista (nexo brain moments)')
|
|
38
|
+
.option('--agent-role <papel>', 'só com o momento attendance_agent_turn: sdr (o padrão) ou cs')
|
|
38
39
|
.option('--always <texto>', 'o que fazer sempre (repita para mais de um)', collect, [])
|
|
39
40
|
.option('--never <texto>', 'o que nunca fazer (repita para mais de um)', collect, [])
|
|
40
41
|
.option('--example <texto>', 'um exemplo de como deve sair, em uma linha')
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { emailFiles, emailRenew, emailShow, oauthAuthorize, oauthClientRemove, oauthClientSet, oauthShow, sftpAccept, sftpKeys,
|
|
1
|
+
import { emailFiles, emailRenew, emailShow, oauthAuthorize, oauthClientRemove, oauthClientSet, oauthShow, sftpAccept, sftpKeys, webhookDeliveries, webhookRotate, webhookShow } from './commands/connect-access.js';
|
|
2
2
|
import { hostsApprove, hostsList } from './commands/connect-hosts.js';
|
|
3
3
|
const FOLDER_HELP = 'pasta do conector';
|
|
4
4
|
const CONFIRM_HELP = 'aplica, depois do sim da pessoa';
|
|
@@ -23,21 +23,28 @@ function addHostsCommands(connect, context) {
|
|
|
23
23
|
function addWebhookCommands(connect, context) {
|
|
24
24
|
const webhook = connect
|
|
25
25
|
.command('webhook')
|
|
26
|
-
.description('O webhook do conector: a
|
|
26
|
+
.description('O webhook do conector: o endereço (que é a credencial), a autenticação declarada e os segredos que faltam')
|
|
27
27
|
.argument('[pasta]', FOLDER_HELP, '.')
|
|
28
28
|
.action(async (dir, _options, command) => {
|
|
29
29
|
await webhookShow(context, dir, command.optsWithGlobals());
|
|
30
30
|
});
|
|
31
31
|
webhook
|
|
32
|
-
.command('
|
|
33
|
-
.description('
|
|
34
|
-
.
|
|
35
|
-
.
|
|
32
|
+
.command('deliveries')
|
|
33
|
+
.description('As últimas chamadas que o outro sistema fez ao webhook, da mais nova à mais antiga, com o desfecho e o motivo')
|
|
34
|
+
.argument('[pasta]', FOLDER_HELP, '.')
|
|
35
|
+
.option('--limit <n>', 'quantas entregas por página (1 a 100; padrão 25)')
|
|
36
|
+
.option('--before <id>', 'a próxima página: o id que a página anterior mostrou em "Há mais"')
|
|
37
|
+
.action(async (dir, _options, command) => {
|
|
38
|
+
await webhookDeliveries(context, dir, command.optsWithGlobals());
|
|
39
|
+
});
|
|
40
|
+
webhook
|
|
41
|
+
.command('rotate')
|
|
42
|
+
.description('Troca o token do endereço: mostra o que muda e pede o sim; o endereço antigo para de valer na hora')
|
|
36
43
|
.argument('[pasta]', FOLDER_HELP, '.')
|
|
37
|
-
.option('--
|
|
38
|
-
.option('--
|
|
44
|
+
.option('--confirm <token>', 'aplica com o token da prévia, depois do sim da pessoa')
|
|
45
|
+
.option('-y, --yes', YES_HELP)
|
|
39
46
|
.action(async (dir, _options, command) => {
|
|
40
|
-
await
|
|
47
|
+
await webhookRotate(context, dir, command.optsWithGlobals());
|
|
41
48
|
});
|
|
42
49
|
}
|
|
43
50
|
function addOAuthClientCommands(oauth, context) {
|