@winning-sales/nexo 0.6.0 → 0.7.1
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 +113 -0
- package/assets/skills/nexo-api/SKILL.md +1 -0
- package/assets/skills/nexo-connect/SKILL.md +20 -5
- package/dist/auth/callback-page.js +51 -0
- package/dist/auth/loopback-server.js +17 -7
- 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/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 +20 -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 +2 -0
- package/dist/tools/tool-manifest.js +61 -0
- package/package.json +1 -1
- package/reference.json +1349 -51
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { AGENT_PAIRING_PAGE, 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 { requestLocalChange } from '../connect/changes.js';
|
|
5
|
+
import { describeAgent, describeAgentRow, isAgent, isAgentList, isPairingCode, newlyPaired, revokePreview } from '../connect/agents.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
|
+
export const PAIR_WAIT = DEFAULT_PATIENCE;
|
|
10
|
+
async function fetchAgents(context, session) {
|
|
11
|
+
const response = await clientOf(context, session).request({ method: 'GET', path: '/v1/connect/agents' });
|
|
12
|
+
if (!isAgentList(response.body)) {
|
|
13
|
+
throw new Error('Lista de agentes em formato inesperado.');
|
|
14
|
+
}
|
|
15
|
+
return response.body;
|
|
16
|
+
}
|
|
17
|
+
async function fetchAgent(context, session, agentId) {
|
|
18
|
+
const response = await clientOf(context, session).request({
|
|
19
|
+
method: 'GET',
|
|
20
|
+
path: `/v1/connect/agents/${encodeURIComponent(agentId)}`
|
|
21
|
+
});
|
|
22
|
+
if (!isAgent(response.body)) {
|
|
23
|
+
throw new Error('Agente em formato inesperado.');
|
|
24
|
+
}
|
|
25
|
+
return response.body;
|
|
26
|
+
}
|
|
27
|
+
export async function agentsList(context, options) {
|
|
28
|
+
const agents = await fetchAgents(context, sessionOf(context, options));
|
|
29
|
+
if (options.json === true) {
|
|
30
|
+
printJson(context, agents);
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
if (agents.length === 0) {
|
|
34
|
+
printLine(context, 'Nenhum agente local nesta empresa. Instale o primeiro com `nexo connect agents pair`.');
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
for (const agent of agents) {
|
|
38
|
+
printLine(context, describeAgentRow(agent));
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
export async function agentShow(context, agentId, options) {
|
|
42
|
+
const agent = await fetchAgent(context, sessionOf(context, options), agentId);
|
|
43
|
+
if (options.json === true) {
|
|
44
|
+
printJson(context, agent);
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
for (const line of describeAgent(agent)) {
|
|
48
|
+
printLine(context, line);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
async function createCode(context, session, options) {
|
|
52
|
+
try {
|
|
53
|
+
const response = await clientOf(context, session).request({
|
|
54
|
+
method: 'POST',
|
|
55
|
+
path: '/v1/connect/agents/pairing-codes',
|
|
56
|
+
body: options.name === undefined ? {} : { name: options.name }
|
|
57
|
+
});
|
|
58
|
+
if (!isPairingCode(response.body)) {
|
|
59
|
+
throw new Error('Código de pareamento em formato inesperado.');
|
|
60
|
+
}
|
|
61
|
+
return response.body;
|
|
62
|
+
}
|
|
63
|
+
catch (error) {
|
|
64
|
+
if (error instanceof CliError && error.exitCode === EXIT_CODES.forbidden) {
|
|
65
|
+
throw new CliError(error.message, EXIT_CODES.forbidden, 'Só uma chave pessoal com o escopo connectors:hosts gera o código; com o login da CLI, rode `nexo connect agents pair` sem --code e gere o código na tela.');
|
|
66
|
+
}
|
|
67
|
+
throw error;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
async function waitForPaired(context, session, known, wait) {
|
|
71
|
+
return pollUntil(async () => newlyPaired(await fetchAgents(context, session), known), (ms) => pause(context, ms), wait, timedOut('Nenhum agente novo foi pareado a tempo.', 'Gere o código na tela, instale o agente com ele e confira com `nexo connect agents`.'));
|
|
72
|
+
}
|
|
73
|
+
const PAIRING_HINT = 'Gere o código lá, com a sua sessão, e use-o na instalação do agente na máquina da empresa. O código não passa pela CLI.';
|
|
74
|
+
async function announcePairing(context, session, options) {
|
|
75
|
+
if (options.code === true) {
|
|
76
|
+
const code = await createCode(context, session, options);
|
|
77
|
+
printLine(context, `Código de pareamento: ${code.code} (vale uma vez, até ${code.expiresAt})`);
|
|
78
|
+
printLine(context, 'Use-o na instalação do agente, na máquina da empresa.');
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
const app = knownAppUrl(session.apiUrl);
|
|
82
|
+
if (app === null) {
|
|
83
|
+
printNotice(context, `Não conheço o app do ambiente ${session.apiUrl}, então não abri o navegador.`);
|
|
84
|
+
printNotice(context, `Abra no app desse ambiente o caminho ${AGENT_PAIRING_PAGE}`);
|
|
85
|
+
printNotice(context, PAIRING_HINT);
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
const url = `${app}${AGENT_PAIRING_PAGE}`;
|
|
89
|
+
const opened = await context.openUrl(url);
|
|
90
|
+
printNotice(context, opened ? 'Abri a aba Agente local no navegador.' : 'Abra a aba Agente local no navegador:');
|
|
91
|
+
printNotice(context, opened ? `Se não abriu, use: ${url}` : url);
|
|
92
|
+
printNotice(context, PAIRING_HINT);
|
|
93
|
+
}
|
|
94
|
+
export async function agentPair(context, options, wait = PAIR_WAIT) {
|
|
95
|
+
if (options.code === true && options.json === true) {
|
|
96
|
+
throw usageError('--code não vai com --json: o código sairia no meio do JSON e iria parar no log de quem chama.', 'Rode `pair --code` sem --json.');
|
|
97
|
+
}
|
|
98
|
+
const session = sessionOf(context, options);
|
|
99
|
+
const known = options.wait === false ? null : new Set((await fetchAgents(context, session)).map((agent) => agent.id));
|
|
100
|
+
await announcePairing(context, session, options);
|
|
101
|
+
if (known === null) {
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
printNotice(context, 'Esperando um agente novo ser pareado (até 10 minutos)…');
|
|
105
|
+
const agent = await waitForPaired(context, session, known, wait);
|
|
106
|
+
if (options.json === true) {
|
|
107
|
+
printJson(context, agent);
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
printLine(context, 'Agente pareado:');
|
|
111
|
+
for (const line of describeAgent(agent)) {
|
|
112
|
+
printLine(context, line);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
export async function agentRevoke(context, agentId, options) {
|
|
116
|
+
const session = sessionOf(context, options);
|
|
117
|
+
const agent = await fetchAgent(context, session, agentId);
|
|
118
|
+
if (agent.status === 'revoked') {
|
|
119
|
+
throw usageError(`O agente ${agent.name} já está revogado.`, 'Para ter um agente de novo, rode `nexo connect agents pair`.');
|
|
120
|
+
}
|
|
121
|
+
await requestLocalChange(context, {
|
|
122
|
+
preview: revokePreview(agent),
|
|
123
|
+
command: `nexo connect agents revoke ${agentId}`,
|
|
124
|
+
confirmed: options.confirm === true,
|
|
125
|
+
yes: options.yes === true,
|
|
126
|
+
json: options.json === true,
|
|
127
|
+
apply: () => clientOf(context, session).request({ method: 'POST', path: `/v1/connect/agents/${encodeURIComponent(agentId)}/revoke` }),
|
|
128
|
+
report: () => {
|
|
129
|
+
printLine(context, `Agente ${agent.name} revogado. O túnel foi cortado.`);
|
|
130
|
+
}
|
|
131
|
+
});
|
|
132
|
+
}
|
|
@@ -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
|
+
}
|