@winning-sales/nexo 0.5.0 → 0.7.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 +119 -1
- package/assets/skills/nexo-api/SKILL.md +2 -1
- package/assets/skills/nexo-connect/SKILL.md +20 -5
- package/dist/commands/connect-access.js +279 -0
- package/dist/commands/connect-agents.js +132 -0
- package/dist/commands/connect-build.js +172 -0
- package/dist/commands/connect-execute.js +85 -0
- package/dist/commands/connect-files.js +23 -7
- package/dist/commands/connect-hosts.js +177 -0
- package/dist/commands/connect-retained.js +134 -0
- package/dist/commands/connect-runs.js +70 -14
- package/dist/commands/connect-versions.js +143 -0
- package/dist/commands/erp.js +225 -0
- package/dist/commands/login.js +1 -5
- package/dist/commands/mcp.js +2 -1
- package/dist/commands/platform.js +98 -0
- package/dist/commands/whoami.js +9 -1
- package/dist/config/environments.js +10 -0
- package/dist/connect/access.js +117 -0
- package/dist/connect/agents.js +71 -0
- package/dist/connect/changes.js +68 -7
- package/dist/connect/operation-args.js +30 -0
- package/dist/connect/retained.js +106 -0
- package/dist/connect/runs.js +65 -10
- package/dist/connect/schedule.js +38 -0
- package/dist/connect/template.js +23 -0
- package/dist/connect/versions.js +60 -0
- package/dist/erp/operations.js +87 -0
- package/dist/http/problem.js +22 -1
- package/dist/program-connect-access.js +134 -0
- package/dist/program-connect.js +256 -4
- package/dist/program-erp.js +44 -0
- package/dist/program.js +22 -1
- package/dist/tools/tool-manifest.js +65 -0
- package/package.json +1 -1
- package/reference.json +1394 -54
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { clientOf, printJson, printLine, printNotice, sessionOf } from '../context.js';
|
|
4
|
+
import { CliError } from '../errors.js';
|
|
5
|
+
import { EXIT_CODES } from '../exit-codes.types.js';
|
|
6
|
+
import { STATE_FILE, projectDirectory, readState, writeState } from '../connect/project.js';
|
|
7
|
+
import { connectorIdOf } from './connect-runs.js';
|
|
8
|
+
export const BUILD_WAIT = { intervalMs: 3000, timeoutMs: 10 * 60_000 };
|
|
9
|
+
const ALLOWANCE_NOTICE = 'Atenção: a conversa com a IA do Connect gasta a franquia de IA da empresa.';
|
|
10
|
+
const KIND_LABELS = {
|
|
11
|
+
access_request: 'pediu acesso',
|
|
12
|
+
authorization_request: 'pediu a autorização do Nexo no sistema',
|
|
13
|
+
host_request: 'pediu a aprovação de um host',
|
|
14
|
+
rehearsal: 'ensaiou o conector',
|
|
15
|
+
source: 'leu uma fonte'
|
|
16
|
+
};
|
|
17
|
+
function startedOf(body) {
|
|
18
|
+
const fields = typeof body === 'object' && body !== null ? body : {};
|
|
19
|
+
if (typeof fields.connectorId !== 'string' || typeof fields.turnId !== 'string') {
|
|
20
|
+
throw new Error('Resposta da conversa em formato inesperado.');
|
|
21
|
+
}
|
|
22
|
+
return { connectorId: fields.connectorId, turnId: fields.turnId };
|
|
23
|
+
}
|
|
24
|
+
function conversationOf(body) {
|
|
25
|
+
const fields = typeof body === 'object' && body !== null ? body : {};
|
|
26
|
+
if (!Array.isArray(fields.messages) || typeof fields.answering !== 'boolean') {
|
|
27
|
+
throw new Error('Conversa em formato inesperado.');
|
|
28
|
+
}
|
|
29
|
+
return { messages: fields.messages, answering: fields.answering };
|
|
30
|
+
}
|
|
31
|
+
async function fetchConversation(context, session, connectorId) {
|
|
32
|
+
const response = await clientOf(context, session).request({
|
|
33
|
+
method: 'GET',
|
|
34
|
+
path: `/v1/connect/connectors/${connectorId}/build`
|
|
35
|
+
});
|
|
36
|
+
return conversationOf(response.body);
|
|
37
|
+
}
|
|
38
|
+
function pause(milliseconds) {
|
|
39
|
+
return new Promise((resolve) => setTimeout(resolve, milliseconds));
|
|
40
|
+
}
|
|
41
|
+
async function waitForAnswer(context, session, connectorId, wait) {
|
|
42
|
+
const deadline = Date.now() + wait.timeoutMs;
|
|
43
|
+
let conversation = await fetchConversation(context, session, connectorId);
|
|
44
|
+
while (conversation.answering) {
|
|
45
|
+
if (Date.now() > deadline) {
|
|
46
|
+
throw new CliError('A IA ainda está respondendo.', EXIT_CODES.failure, `Acompanhe com \`nexo connect --connector ${connectorId} build show\`.`);
|
|
47
|
+
}
|
|
48
|
+
await pause(wait.intervalMs);
|
|
49
|
+
conversation = await fetchConversation(context, session, connectorId);
|
|
50
|
+
}
|
|
51
|
+
return conversation;
|
|
52
|
+
}
|
|
53
|
+
function describeMessage(message) {
|
|
54
|
+
const who = message.author === 'person' ? 'Você' : 'IA';
|
|
55
|
+
if (message.kind === 'text') {
|
|
56
|
+
const text = message.content['text'];
|
|
57
|
+
return [`${who}: ${typeof text === 'string' ? text : ''}`];
|
|
58
|
+
}
|
|
59
|
+
if (message.kind === 'version') {
|
|
60
|
+
const summary = message.content['summary'];
|
|
61
|
+
const seq = message.content['seq'];
|
|
62
|
+
const head = `IA: escreveu a versão ${typeof seq === 'number' ? String(seq) : '?'}`;
|
|
63
|
+
return [typeof summary === 'string' && summary !== '' ? `${head}: ${summary}` : head];
|
|
64
|
+
}
|
|
65
|
+
return [`${who}: ${KIND_LABELS[message.kind] ?? message.kind}`];
|
|
66
|
+
}
|
|
67
|
+
/** O que a IA fez na última vez: tudo depois da última fala da pessoa. */
|
|
68
|
+
function lastTurn(messages) {
|
|
69
|
+
let from = 0;
|
|
70
|
+
messages.forEach((message, index) => {
|
|
71
|
+
if (message.author === 'person' && message.kind === 'text') {
|
|
72
|
+
from = index;
|
|
73
|
+
}
|
|
74
|
+
});
|
|
75
|
+
return messages.slice(from);
|
|
76
|
+
}
|
|
77
|
+
function writtenVersions(messages) {
|
|
78
|
+
return messages.filter((message) => message.kind === 'version').length;
|
|
79
|
+
}
|
|
80
|
+
function printMessages(context, messages) {
|
|
81
|
+
for (const line of messages.flatMap(describeMessage)) {
|
|
82
|
+
printLine(context, line);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
function printTurn(context, connectorId, dir, messages) {
|
|
86
|
+
const turn = lastTurn(messages);
|
|
87
|
+
printMessages(context, turn);
|
|
88
|
+
if (writtenVersions(turn) > 0) {
|
|
89
|
+
printLine(context, `Para ver o código: nexo connect pull ${connectorId} ${dir ?? '<pasta>'}`);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
async function openTurn(context, session, request) {
|
|
93
|
+
printNotice(context, ALLOWANCE_NOTICE);
|
|
94
|
+
const response = await clientOf(context, session).request({ method: 'POST', path: request.path, body: request.body });
|
|
95
|
+
return startedOf(response.body);
|
|
96
|
+
}
|
|
97
|
+
async function followTurn(context, session, started, dir, options, wait) {
|
|
98
|
+
if (options.wait === false) {
|
|
99
|
+
if (options.json === true) {
|
|
100
|
+
printJson(context, started);
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
printLine(context, `Conector ${started.connectorId}, vez ${started.turnId}. Acompanhe com \`nexo connect --connector ${started.connectorId} build show\`.`);
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
if (options.json !== true) {
|
|
107
|
+
printLine(context, `Conector ${started.connectorId}, vez ${started.turnId}. Esperando a IA responder...`);
|
|
108
|
+
}
|
|
109
|
+
const conversation = await waitForAnswer(context, session, started.connectorId, wait);
|
|
110
|
+
if (options.json === true) {
|
|
111
|
+
printJson(context, { ...started, ...conversation });
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
printTurn(context, started.connectorId, dir, conversation.messages);
|
|
115
|
+
}
|
|
116
|
+
function existingConnector(options, dir) {
|
|
117
|
+
if (options.connector !== undefined) {
|
|
118
|
+
return options.connector;
|
|
119
|
+
}
|
|
120
|
+
const folder = projectDirectory(dir);
|
|
121
|
+
if (!existsSync(join(folder, STATE_FILE))) {
|
|
122
|
+
return null;
|
|
123
|
+
}
|
|
124
|
+
return readState(folder).connectorId;
|
|
125
|
+
}
|
|
126
|
+
function startBody(message, dir) {
|
|
127
|
+
const folder = projectDirectory(dir);
|
|
128
|
+
if (!existsSync(join(folder, STATE_FILE))) {
|
|
129
|
+
return { message };
|
|
130
|
+
}
|
|
131
|
+
const state = readState(folder);
|
|
132
|
+
return { message, name: state.name, ...(state.systemId === null ? {} : { systemId: state.systemId }) };
|
|
133
|
+
}
|
|
134
|
+
/** A pasta já inicializada guarda o id do conector que a conversa abriu: a próxima mensagem cai na mesma conversa. */
|
|
135
|
+
function rememberConnector(dir, connectorId) {
|
|
136
|
+
const folder = projectDirectory(dir);
|
|
137
|
+
if (existsSync(join(folder, STATE_FILE))) {
|
|
138
|
+
writeState(folder, { ...readState(folder), connectorId });
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
export async function connectBuild(context, message, dir, options, wait = BUILD_WAIT) {
|
|
142
|
+
const session = sessionOf(context, options);
|
|
143
|
+
const connectorId = existingConnector(options, dir);
|
|
144
|
+
const started = connectorId === null
|
|
145
|
+
? await openTurn(context, session, { path: '/v1/connect/build', body: startBody(message, dir) })
|
|
146
|
+
: await openTurn(context, session, { path: `/v1/connect/connectors/${connectorId}/build`, body: { message } });
|
|
147
|
+
if (connectorId === null) {
|
|
148
|
+
rememberConnector(dir, started.connectorId);
|
|
149
|
+
}
|
|
150
|
+
await followTurn(context, session, started, dir, options, wait);
|
|
151
|
+
}
|
|
152
|
+
export async function connectBuildFix(context, runId, dir, options, wait = BUILD_WAIT) {
|
|
153
|
+
const session = sessionOf(context, options);
|
|
154
|
+
const connectorId = connectorIdOf(options, dir);
|
|
155
|
+
const started = await openTurn(context, session, {
|
|
156
|
+
path: `/v1/connect/connectors/${connectorId}/runs/${encodeURIComponent(runId)}/fix`,
|
|
157
|
+
body: options.message === undefined ? {} : { message: options.message }
|
|
158
|
+
});
|
|
159
|
+
await followTurn(context, session, started, dir, options, wait);
|
|
160
|
+
}
|
|
161
|
+
export async function connectBuildShow(context, dir, options) {
|
|
162
|
+
const session = sessionOf(context, options);
|
|
163
|
+
const conversation = await fetchConversation(context, session, connectorIdOf(options, dir));
|
|
164
|
+
if (options.json === true) {
|
|
165
|
+
printJson(context, conversation);
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
printMessages(context, conversation.messages);
|
|
169
|
+
if (conversation.answering) {
|
|
170
|
+
printLine(context, 'A IA ainda está respondendo: rode `nexo connect build show` de novo daqui a pouco.');
|
|
171
|
+
}
|
|
172
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { clientOf, printLine, sessionOf } from '../context.js';
|
|
2
|
+
import { CliError } from '../errors.js';
|
|
3
|
+
import { EXIT_CODES } from '../exit-codes.types.js';
|
|
4
|
+
import { requestChange, requestLocalChange } from '../connect/changes.js';
|
|
5
|
+
import { DEFAULT_WAIT, printRun, runIsClean, waitForRun } from '../connect/runs.js';
|
|
6
|
+
import { fetchConnector } from './connect-files.js';
|
|
7
|
+
import { connectorIdOf } from './connect-runs.js';
|
|
8
|
+
const EXECUTIONS = {
|
|
9
|
+
'run-now': { path: 'runs', what: 'roda agora, como o gatilho rodaria' },
|
|
10
|
+
'initial-load': { path: 'initial-load', what: 'faz a carga inicial, lendo a origem inteira' }
|
|
11
|
+
};
|
|
12
|
+
function opened(body) {
|
|
13
|
+
const fields = typeof body === 'object' && body !== null ? body : {};
|
|
14
|
+
if (typeof fields.runId !== 'string') {
|
|
15
|
+
throw new Error('Execução aberta em formato inesperado.');
|
|
16
|
+
}
|
|
17
|
+
return { runId: fields.runId, link: fields.link ?? '' };
|
|
18
|
+
}
|
|
19
|
+
function executionPreview(kind, published) {
|
|
20
|
+
const version = published === null ? 'publicada' : `${String(published)} (a publicada)`;
|
|
21
|
+
return {
|
|
22
|
+
title: `A versão ${version} ${EXECUTIONS[kind].what}`,
|
|
23
|
+
changes: [
|
|
24
|
+
'Grava no Nexo de verdade: não é ensaio.',
|
|
25
|
+
'Tudo o que ela gravar no Nexo vai num conjunto que o desfazer leva de volta (`nexo connect undo <execução>`).',
|
|
26
|
+
'O que ela mandar ao outro sistema não se desfaz.'
|
|
27
|
+
]
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
async function openAndWait(context, session, request, outcome) {
|
|
31
|
+
const response = await clientOf(context, session).request({
|
|
32
|
+
method: 'POST',
|
|
33
|
+
path: `/v1/connect/connectors/${request.connectorId}/${request.path}`
|
|
34
|
+
});
|
|
35
|
+
const started = opened(response.body);
|
|
36
|
+
outcome.link = started.link;
|
|
37
|
+
if (request.noWait) {
|
|
38
|
+
return response;
|
|
39
|
+
}
|
|
40
|
+
outcome.run = await waitForRun(context, session, { connectorId: request.connectorId, runId: started.runId }, request.wait);
|
|
41
|
+
return { status: response.status, body: outcome.run };
|
|
42
|
+
}
|
|
43
|
+
function reportOutcome(context, outcome, quiet, body) {
|
|
44
|
+
if (outcome.run === null) {
|
|
45
|
+
printLine(context, `Execução ${opened(body).runId} começou: ${outcome.link}`);
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
printRun(context, outcome.run, { quiet });
|
|
49
|
+
printLine(context, `Tela: ${outcome.link}`);
|
|
50
|
+
}
|
|
51
|
+
export async function connectExecute(context, kind, dir, options, wait = DEFAULT_WAIT) {
|
|
52
|
+
const connectorId = connectorIdOf(options, dir);
|
|
53
|
+
const session = sessionOf(context, options);
|
|
54
|
+
const published = (await fetchConnector(context, session, connectorId)).connector.publishedSeq;
|
|
55
|
+
const outcome = { run: null, link: '' };
|
|
56
|
+
await requestLocalChange(context, {
|
|
57
|
+
preview: executionPreview(kind, published),
|
|
58
|
+
command: `nexo connect ${kind}`,
|
|
59
|
+
confirmed: options.confirm === true,
|
|
60
|
+
yes: options.yes === true,
|
|
61
|
+
json: options.json === true,
|
|
62
|
+
apply: () => openAndWait(context, session, { connectorId, path: EXECUTIONS[kind].path, wait, noWait: options.wait === false }, outcome),
|
|
63
|
+
report: (body) => {
|
|
64
|
+
reportOutcome(context, outcome, options.quiet === true, body);
|
|
65
|
+
}
|
|
66
|
+
});
|
|
67
|
+
if (outcome.run !== null && !runIsClean(outcome.run)) {
|
|
68
|
+
throw new CliError('A execução não terminou limpa.', EXIT_CODES.failure, 'Leia o erro acima; `nexo connect undo` leva de volta o que ela gravou.');
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
function undoSummary(body) {
|
|
72
|
+
const result = typeof body === 'object' && body !== null ? body : {};
|
|
73
|
+
return [`Registros desfeitos: ${String(result.records ?? 0)}.`, ...(typeof result.notice === 'string' ? [result.notice] : [])];
|
|
74
|
+
}
|
|
75
|
+
export async function connectUndo(context, runId, dir, options) {
|
|
76
|
+
await requestChange(context, sessionOf(context, options), {
|
|
77
|
+
connectorId: connectorIdOf(options, dir),
|
|
78
|
+
path: `runs/${encodeURIComponent(runId)}/undo`,
|
|
79
|
+
command: `nexo connect undo ${runId}`,
|
|
80
|
+
summarize: undoSummary,
|
|
81
|
+
confirm: typeof options.confirm === 'string' ? options.confirm : undefined,
|
|
82
|
+
yes: options.yes === true,
|
|
83
|
+
json: options.json === true
|
|
84
|
+
});
|
|
85
|
+
}
|
|
@@ -6,7 +6,9 @@ import { CliError } from '../errors.js';
|
|
|
6
6
|
import { EXIT_CODES } from '../exit-codes.types.js';
|
|
7
7
|
import { NexoApiError } from '../http/problem.js';
|
|
8
8
|
import { SDK_FILE, ensureEmpty, projectDirectory, readFiles, readState, writeFiles, writeState } from '../connect/project.js';
|
|
9
|
-
import {
|
|
9
|
+
import { filesDigest } from '../connect/versions.js';
|
|
10
|
+
import { companyTimeZone, scheduleLine } from '../connect/schedule.js';
|
|
11
|
+
import { TEMPLATE_CODE, TEMPLATE_README, TEMPLATE_TSCONFIG, templateManifest } from '../connect/template.js';
|
|
10
12
|
function isSaved(value) {
|
|
11
13
|
return typeof value === 'object' && value !== null && typeof value.connectorId === 'string';
|
|
12
14
|
}
|
|
@@ -32,6 +34,7 @@ export async function connectInit(context, dir, options) {
|
|
|
32
34
|
const system = options.system === undefined ? null : await systemNamed(context, options, options.system);
|
|
33
35
|
mkdirSync(directory, { recursive: true });
|
|
34
36
|
writeFiles(directory, { code: TEMPLATE_CODE, manifest: templateManifest() });
|
|
37
|
+
writeFileSync(join(directory, 'README.md'), TEMPLATE_README);
|
|
35
38
|
copySdk(directory);
|
|
36
39
|
const name = options.name ?? system?.name ?? 'Novo conector';
|
|
37
40
|
writeState(directory, { connectorId: null, name, systemId: system?.id ?? null, baseSeq: null });
|
|
@@ -65,7 +68,7 @@ async function saveVersion(context, session, state, body) {
|
|
|
65
68
|
function reportSaved(context, saved) {
|
|
66
69
|
printLine(context, `Versão ${String(saved.version.seq)} salva. Ela está em edição: ensaie com \`nexo connect rehearse\`.`);
|
|
67
70
|
if (saved.pendingHosts.length > 0) {
|
|
68
|
-
printLine(context, `Hosts esperando o sim de uma pessoa: ${saved.pendingHosts.join(', ')}
|
|
71
|
+
printLine(context, `Hosts esperando o sim de uma pessoa: ${saved.pendingHosts.join(', ')}. Aprove com \`nexo connect hosts approve\`.`);
|
|
69
72
|
}
|
|
70
73
|
if (saved.missingSecrets.length > 0) {
|
|
71
74
|
printLine(context, `Segredos a preencher (pela pessoa): ${saved.missingSecrets.join(', ')}. Use \`nexo connect secrets set <NOME>\`.`);
|
|
@@ -79,8 +82,9 @@ export async function connectPush(context, dir, options) {
|
|
|
79
82
|
if (summary === '') {
|
|
80
83
|
throw new CliError('Diga o que mudou nesta versão.', EXIT_CODES.usage, 'Use -m "o que mudou".');
|
|
81
84
|
}
|
|
82
|
-
const
|
|
83
|
-
|
|
85
|
+
const files = readFiles(directory);
|
|
86
|
+
const saved = await saveVersion(context, sessionOf(context, options), state, { ...files, summary });
|
|
87
|
+
writeState(directory, { ...state, connectorId: saved.connectorId, baseSeq: saved.version.seq, baseDigest: filesDigest(files) });
|
|
84
88
|
if (options.json === true) {
|
|
85
89
|
printJson(context, saved);
|
|
86
90
|
return;
|
|
@@ -111,7 +115,13 @@ export async function connectPull(context, connectorId, dir, options) {
|
|
|
111
115
|
const files = version.body;
|
|
112
116
|
writeFiles(directory, { code: files.code, manifest: files.manifest });
|
|
113
117
|
copySdk(directory);
|
|
114
|
-
writeState(directory, {
|
|
118
|
+
writeState(directory, {
|
|
119
|
+
connectorId,
|
|
120
|
+
name: view.connector.name,
|
|
121
|
+
systemId: view.connector.systemId,
|
|
122
|
+
baseSeq: view.connector.headSeq,
|
|
123
|
+
baseDigest: filesDigest(files)
|
|
124
|
+
});
|
|
115
125
|
printLine(context, `Versão ${String(seq)} de "${view.connector.name}" em ${directory}.`);
|
|
116
126
|
}
|
|
117
127
|
export async function connectStatus(context, dir, options) {
|
|
@@ -121,7 +131,8 @@ export async function connectStatus(context, dir, options) {
|
|
|
121
131
|
printLine(context, `"${state.name}" ainda não foi enviado ao Nexo. Suba com \`nexo connect push -m "primeira versão"\`.`);
|
|
122
132
|
return;
|
|
123
133
|
}
|
|
124
|
-
const
|
|
134
|
+
const session = sessionOf(context, options);
|
|
135
|
+
const view = await fetchConnector(context, session, state.connectorId);
|
|
125
136
|
if (options.json === true) {
|
|
126
137
|
printJson(context, { local: state, remote: view });
|
|
127
138
|
return;
|
|
@@ -131,6 +142,11 @@ export async function connectStatus(context, dir, options) {
|
|
|
131
142
|
if (state.baseSeq !== view.connector.headSeq) {
|
|
132
143
|
printLine(context, 'Há uma versão mais nova no Nexo do que a desta pasta.');
|
|
133
144
|
}
|
|
134
|
-
printLine(context, `Segredos faltando: ${view.missingSecrets.join(', ') || 'nenhum'}. Hosts esperando: ${view.pendingHosts.join(', ') || 'nenhum'}.`);
|
|
145
|
+
printLine(context, `Segredos faltando: ${view.missingSecrets.join(', ') || 'nenhum'}. Hosts esperando: ${view.pendingHosts.join(', ') || 'nenhum'}${view.pendingHosts.length > 0 ? ' (aprove com `nexo connect hosts approve`)' : ''}.`);
|
|
146
|
+
const zone = typeof view.connector.nextRunAt === 'string' ? await companyTimeZone(context, session) : null;
|
|
147
|
+
const agenda = scheduleLine(view.connector, zone);
|
|
148
|
+
if (agenda !== null) {
|
|
149
|
+
printLine(context, agenda);
|
|
150
|
+
}
|
|
135
151
|
printLine(context, `Tela: ${view.link}`);
|
|
136
152
|
}
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import { knownAppUrl } from '../config/environments.js';
|
|
2
|
+
import { clientOf, printJson, printLine, printNotice, sessionOf } from '../context.js';
|
|
3
|
+
import { DEFAULT_PATIENCE, pollUntil, timedOut } from '../connect/access.js';
|
|
4
|
+
import { showPreview } from '../connect/changes.js';
|
|
5
|
+
import { STATE_FILE } from '../connect/project.js';
|
|
6
|
+
import { CliError, usageError } from '../errors.js';
|
|
7
|
+
import { EXIT_CODES } from '../exit-codes.types.js';
|
|
8
|
+
import { pause } from '../documents/journey-api.js';
|
|
9
|
+
import { existsSync } from 'node:fs';
|
|
10
|
+
import { createInterface } from 'node:readline';
|
|
11
|
+
import { join } from 'node:path';
|
|
12
|
+
import { fetchConnector } from './connect-files.js';
|
|
13
|
+
import { connectorIdOf } from './connect-runs.js';
|
|
14
|
+
export function hostsOf(view) {
|
|
15
|
+
const approved = view.connector.approvedHosts;
|
|
16
|
+
return {
|
|
17
|
+
approved: Array.isArray(approved) ? approved : [],
|
|
18
|
+
pending: Array.isArray(view.pendingHosts) ? view.pendingHosts : []
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
/** A tela do conector aberta no ponto certo (`foco`, nexu-fe#1520), a partir do `link` que o Nexo devolve. */
|
|
22
|
+
export function screenLink(view, focus) {
|
|
23
|
+
const url = new URL(view.link);
|
|
24
|
+
url.searchParams.set('foco', focus);
|
|
25
|
+
return url.toString();
|
|
26
|
+
}
|
|
27
|
+
/** Abre a página no navegador; com a API de um ambiente que não conheço, só mostra o link. */
|
|
28
|
+
export async function openOrShow(context, session, url, what) {
|
|
29
|
+
if (knownAppUrl(session.apiUrl) === null) {
|
|
30
|
+
printNotice(context, `Não conheço o app do ambiente ${session.apiUrl}, então não abri o navegador.`);
|
|
31
|
+
printNotice(context, `Abra ${what}: ${url}`);
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
const opened = await context.openUrl(url);
|
|
35
|
+
printNotice(context, opened ? `Abri ${what} no navegador.` : `Abra ${what} no navegador:`);
|
|
36
|
+
printNotice(context, opened ? `Se não abriu, use: ${url}` : url);
|
|
37
|
+
}
|
|
38
|
+
export async function hostsList(context, dir, options) {
|
|
39
|
+
const view = await fetchConnector(context, sessionOf(context, options), connectorIdOf(options, dir));
|
|
40
|
+
const hosts = hostsOf(view);
|
|
41
|
+
if (options.json === true) {
|
|
42
|
+
printJson(context, { approvedHosts: hosts.approved, pendingHosts: hosts.pending });
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
printLine(context, `Aprovados: ${hosts.approved.join(', ') || 'nenhum'}.`);
|
|
46
|
+
printLine(context, `Esperando o sim de uma pessoa: ${hosts.pending.join(', ') || 'nenhum'}.`);
|
|
47
|
+
if (hosts.pending.length > 0) {
|
|
48
|
+
printLine(context, 'Aprove com `nexo connect hosts approve`.');
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
/** Os argumentos são hosts; o último vira a pasta se for uma pasta de conector. */
|
|
52
|
+
function splitArguments(args) {
|
|
53
|
+
const last = args.at(-1);
|
|
54
|
+
if (last !== undefined && existsSync(join(last, STATE_FILE))) {
|
|
55
|
+
return { hosts: args.slice(0, -1), dir: last };
|
|
56
|
+
}
|
|
57
|
+
return { hosts: args, dir: undefined };
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Só uma chave pessoal (`nexo_pat_`), com uma pessoa no terminal, pede a aprovação ao `/v1`; qualquer outro token segue
|
|
61
|
+
* como o do `nexo login` (nenhum recebe `connectors:hosts`) e vai pela tela. Sem terminal, também vai pela tela:
|
|
62
|
+
* nenhum comando que um agente rode aprova host.
|
|
63
|
+
*/
|
|
64
|
+
function approvesWithKey(context, session) {
|
|
65
|
+
return session.token.startsWith('nexo_pat_') && context.stdin.isTTY === true;
|
|
66
|
+
}
|
|
67
|
+
function hostsToApprove(wanted, state) {
|
|
68
|
+
const approved = new Set(state.approved);
|
|
69
|
+
const pending = new Set(state.pending);
|
|
70
|
+
for (const host of wanted) {
|
|
71
|
+
if (!pending.has(host) && !approved.has(host)) {
|
|
72
|
+
throw usageError(`O host ${host} não está entre os que a versão em edição pede.`, `Os que esperam o sim: ${state.pending.join(', ') || 'nenhum'}. Suba a versão com \`nexo connect push\` se o host é novo.`);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return (wanted.length === 0 ? state.pending : wanted).filter((host) => !approved.has(host));
|
|
76
|
+
}
|
|
77
|
+
async function typedApproval(context, hosts) {
|
|
78
|
+
const reader = createInterface({ input: context.stdin, output: context.stderr, terminal: true });
|
|
79
|
+
try {
|
|
80
|
+
const answer = await new Promise((resolve) => {
|
|
81
|
+
reader.question(`Para aprovar, digite "aprovar"${hosts.length === 1 ? ` ou o host (${hosts[0] ?? ''})` : ''}: `, resolve);
|
|
82
|
+
});
|
|
83
|
+
const typed = answer.trim().toLowerCase();
|
|
84
|
+
return typed === 'aprovar' || (hosts.length === 1 && typed === hosts[0]?.toLowerCase());
|
|
85
|
+
}
|
|
86
|
+
finally {
|
|
87
|
+
reader.close();
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
async function previewApproval(context, session, base, hosts) {
|
|
91
|
+
try {
|
|
92
|
+
const response = await clientOf(context, session).request({
|
|
93
|
+
method: 'POST',
|
|
94
|
+
path: `${base}/hosts/approve/preview`,
|
|
95
|
+
body: { hosts }
|
|
96
|
+
});
|
|
97
|
+
if (!isApprovalPreview(response.body)) {
|
|
98
|
+
throw new Error('Prévia em formato inesperado.');
|
|
99
|
+
}
|
|
100
|
+
return response.body;
|
|
101
|
+
}
|
|
102
|
+
catch (error) {
|
|
103
|
+
if (error instanceof CliError && error.exitCode === EXIT_CODES.forbidden) {
|
|
104
|
+
printNotice(context, 'Esta chave não tem o escopo connectors:hosts; a aprovação vai pela tela.');
|
|
105
|
+
return null;
|
|
106
|
+
}
|
|
107
|
+
throw error;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
function isApprovalPreview(value) {
|
|
111
|
+
const fields = typeof value === 'object' ? value : null;
|
|
112
|
+
return fields !== null && typeof fields.title === 'string' && Array.isArray(fields.changes) && typeof fields.confirmation === 'object';
|
|
113
|
+
}
|
|
114
|
+
/** Chave pessoal com o escopo, numa pessoa no terminal: prévia do `/v1` e a pessoa digita para aplicar. `false`: sem o escopo, vai pela tela. */
|
|
115
|
+
async function approveWithKey(context, session, connectorId, hosts, options) {
|
|
116
|
+
const base = `/v1/connect/connectors/${connectorId}`;
|
|
117
|
+
const preview = await previewApproval(context, session, base, hosts);
|
|
118
|
+
if (preview === null) {
|
|
119
|
+
return false;
|
|
120
|
+
}
|
|
121
|
+
showPreview(context, preview);
|
|
122
|
+
if (!(await typedApproval(context, hosts))) {
|
|
123
|
+
printNotice(context, 'Nada mudou.');
|
|
124
|
+
return true;
|
|
125
|
+
}
|
|
126
|
+
const response = await clientOf(context, session).request({
|
|
127
|
+
method: 'POST',
|
|
128
|
+
path: `${base}/hosts/approve`,
|
|
129
|
+
body: { hosts, confirmationToken: preview.confirmation.token }
|
|
130
|
+
});
|
|
131
|
+
if (options.json === true) {
|
|
132
|
+
printJson(context, response.body);
|
|
133
|
+
return true;
|
|
134
|
+
}
|
|
135
|
+
printLine(context, `Aprovados: ${hosts.join(', ')}.`);
|
|
136
|
+
return true;
|
|
137
|
+
}
|
|
138
|
+
function announce(context, targets) {
|
|
139
|
+
printNotice(context, 'Cada host aprovado passa a receber as chamadas do conector com os segredos dele:');
|
|
140
|
+
for (const host of targets) {
|
|
141
|
+
printNotice(context, ` - ${host}`);
|
|
142
|
+
}
|
|
143
|
+
printNotice(context, 'Confira que cada um é do sistema que o conector integra. A aprovação é sua, na tela, com a sua sessão.');
|
|
144
|
+
}
|
|
145
|
+
/** Espera todos os hosts estarem entre os aprovados; o que vale é o estado lido, não o relógio. */
|
|
146
|
+
async function waitForApproval(context, session, connectorId, targets, patience) {
|
|
147
|
+
return pollUntil(async () => {
|
|
148
|
+
const approved = new Set(hostsOf(await fetchConnector(context, session, connectorId)).approved);
|
|
149
|
+
return targets.every((host) => approved.has(host)) ? [...approved] : null;
|
|
150
|
+
}, (ms) => pause(context, ms), patience, timedOut(`Os hosts ${targets.join(', ')} não foram aprovados a tempo.`, 'Aprove na tela do conector e confira com `nexo connect hosts`.'));
|
|
151
|
+
}
|
|
152
|
+
export async function hostsApprove(context, args, options, patience = DEFAULT_PATIENCE) {
|
|
153
|
+
const { hosts: wanted, dir } = splitArguments(args);
|
|
154
|
+
const session = sessionOf(context, options);
|
|
155
|
+
const connectorId = connectorIdOf(options, dir);
|
|
156
|
+
const view = await fetchConnector(context, session, connectorId);
|
|
157
|
+
const targets = hostsToApprove(wanted, hostsOf(view));
|
|
158
|
+
if (targets.length === 0) {
|
|
159
|
+
printLine(context, 'Nenhum host esperando o sim.');
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
announce(context, targets);
|
|
163
|
+
if (approvesWithKey(context, session) && (await approveWithKey(context, session, connectorId, targets, options))) {
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
await openOrShow(context, session, screenLink(view, 'hosts'), 'a tela do conector, nos hosts');
|
|
167
|
+
if (options.wait === false) {
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
printNotice(context, 'Esperando a aprovação na tela (até 10 minutos)…');
|
|
171
|
+
const approved = await waitForApproval(context, session, connectorId, targets, patience);
|
|
172
|
+
if (options.json === true) {
|
|
173
|
+
printJson(context, { approvedHosts: approved });
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
printLine(context, `Aprovados: ${targets.join(', ')}.`);
|
|
177
|
+
}
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import { clientOf, printJson, printLine, sessionOf } from '../context.js';
|
|
2
|
+
import { requestChange, requestLocalChange } from '../connect/changes.js';
|
|
3
|
+
import { usageError } from '../errors.js';
|
|
4
|
+
import { readFixFile, describeItem, describeWrites, fixFrom, fixPreview, isExternalWrites, isQuarantineList } from '../connect/retained.js';
|
|
5
|
+
import { connectorIdOf } from './connect-runs.js';
|
|
6
|
+
function base(connectorId) {
|
|
7
|
+
return `/v1/connect/connectors/${connectorId}`;
|
|
8
|
+
}
|
|
9
|
+
function tokenOf(options) {
|
|
10
|
+
return typeof options.confirm === 'string' ? options.confirm : undefined;
|
|
11
|
+
}
|
|
12
|
+
async function openItems(context, options, dir) {
|
|
13
|
+
const response = await clientOf(context, sessionOf(context, options)).request({
|
|
14
|
+
method: 'GET',
|
|
15
|
+
path: `${base(connectorIdOf(options, dir))}/quarantine`
|
|
16
|
+
});
|
|
17
|
+
if (!isQuarantineList(response.body)) {
|
|
18
|
+
throw new Error('Quarentena em formato inesperado.');
|
|
19
|
+
}
|
|
20
|
+
return response.body;
|
|
21
|
+
}
|
|
22
|
+
export async function quarantineList(context, dir, options) {
|
|
23
|
+
const items = await openItems(context, options, dir);
|
|
24
|
+
if (options.json === true) {
|
|
25
|
+
printJson(context, items);
|
|
26
|
+
return;
|
|
27
|
+
}
|
|
28
|
+
if (items.length === 0) {
|
|
29
|
+
printLine(context, 'Nenhum registro aberto na quarentena.');
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
for (const line of items.flatMap(describeItem)) {
|
|
33
|
+
printLine(context, line);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
async function itemOf(context, itemId, dir, options) {
|
|
37
|
+
const item = (await openItems(context, options, dir)).find((found) => found.id === itemId);
|
|
38
|
+
if (item === undefined) {
|
|
39
|
+
throw usageError(`O registro ${itemId} não está aberto na quarentena.`, 'Veja os abertos com `nexo connect quarantine`.');
|
|
40
|
+
}
|
|
41
|
+
return item;
|
|
42
|
+
}
|
|
43
|
+
export async function quarantineFix(context, itemId, dir, options) {
|
|
44
|
+
const fix = fixFrom(options.set ?? [], options.file === undefined ? null : readFixFile(options.file));
|
|
45
|
+
const item = await itemOf(context, itemId, dir, options);
|
|
46
|
+
const connectorId = connectorIdOf(options, dir);
|
|
47
|
+
await requestLocalChange(context, {
|
|
48
|
+
preview: fixPreview(item, fix),
|
|
49
|
+
command: `nexo connect quarantine fix ${itemId}`,
|
|
50
|
+
confirmed: options.confirm === true,
|
|
51
|
+
yes: options.yes === true,
|
|
52
|
+
json: options.json === true,
|
|
53
|
+
apply: () => clientOf(context, sessionOf(context, options)).request({
|
|
54
|
+
method: 'PATCH',
|
|
55
|
+
path: `${base(connectorId)}/quarantine/${encodeURIComponent(itemId)}`,
|
|
56
|
+
body: fix
|
|
57
|
+
})
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
export async function quarantineDiscard(context, itemId, dir, options) {
|
|
61
|
+
const item = await itemOf(context, itemId, dir, options);
|
|
62
|
+
const connectorId = connectorIdOf(options, dir);
|
|
63
|
+
await requestLocalChange(context, {
|
|
64
|
+
preview: {
|
|
65
|
+
title: `Descartar o registro ${item.id} (${item.objectType}) da quarentena`,
|
|
66
|
+
changes: [...describeItem(item).slice(1), 'Ele sai da quarentena sem ir para o Nexo.']
|
|
67
|
+
},
|
|
68
|
+
command: `nexo connect quarantine discard ${itemId}`,
|
|
69
|
+
confirmed: options.confirm === true,
|
|
70
|
+
yes: options.yes === true,
|
|
71
|
+
json: options.json === true,
|
|
72
|
+
apply: () => clientOf(context, sessionOf(context, options)).request({
|
|
73
|
+
method: 'POST',
|
|
74
|
+
path: `${base(connectorId)}/quarantine/${encodeURIComponent(itemId)}/discard`
|
|
75
|
+
})
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
function reprocessSummary(body) {
|
|
79
|
+
const result = body;
|
|
80
|
+
return [
|
|
81
|
+
`Resolvidos: ${String(result.resolved ?? 0)}, recusados de novo: ${String(result.refused ?? 0)}, para o próximo: ${String(result.left ?? 0)}.`,
|
|
82
|
+
...(result.status === 'running' ? ['A execução continua; veja `nexo connect runs`.'] : [])
|
|
83
|
+
];
|
|
84
|
+
}
|
|
85
|
+
export async function quarantineReprocess(context, dir, options) {
|
|
86
|
+
await requestChange(context, sessionOf(context, options), {
|
|
87
|
+
connectorId: connectorIdOf(options, dir),
|
|
88
|
+
path: 'quarantine/reprocess',
|
|
89
|
+
body: {},
|
|
90
|
+
command: 'nexo connect quarantine reprocess',
|
|
91
|
+
summarize: reprocessSummary,
|
|
92
|
+
confirm: tokenOf(options),
|
|
93
|
+
yes: options.yes === true,
|
|
94
|
+
json: options.json === true
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
export async function writesList(context, dir, options) {
|
|
98
|
+
const response = await clientOf(context, sessionOf(context, options)).request({
|
|
99
|
+
method: 'GET',
|
|
100
|
+
path: `${base(connectorIdOf(options, dir))}/external-writes`
|
|
101
|
+
});
|
|
102
|
+
if (!isExternalWrites(response.body)) {
|
|
103
|
+
throw new Error('Escritas retidas em formato inesperado.');
|
|
104
|
+
}
|
|
105
|
+
if (options.json === true) {
|
|
106
|
+
printJson(context, response.body);
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
const writes = response.body;
|
|
110
|
+
for (const line of describeWrites(writes)) {
|
|
111
|
+
printLine(context, line);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
export async function writesConfirm(context, id, dir, options) {
|
|
115
|
+
await requestChange(context, sessionOf(context, options), {
|
|
116
|
+
connectorId: connectorIdOf(options, dir),
|
|
117
|
+
path: `external-writes/${encodeURIComponent(id)}/confirm`,
|
|
118
|
+
command: `nexo connect writes confirm ${id}`,
|
|
119
|
+
confirm: tokenOf(options),
|
|
120
|
+
yes: options.yes === true,
|
|
121
|
+
json: options.json === true
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
export async function writeHost(context, action, host, dir, options) {
|
|
125
|
+
await requestChange(context, sessionOf(context, options), {
|
|
126
|
+
connectorId: connectorIdOf(options, dir),
|
|
127
|
+
path: `write-hosts/${action}`,
|
|
128
|
+
body: { host },
|
|
129
|
+
command: `nexo connect write-hosts ${action} ${host}`,
|
|
130
|
+
confirm: tokenOf(options),
|
|
131
|
+
yes: options.yes === true,
|
|
132
|
+
json: options.json === true
|
|
133
|
+
});
|
|
134
|
+
}
|