kleos-cli 0.1.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 +113 -0
- package/dist/cli.js +34 -0
- package/dist/cliente.js +134 -0
- package/dist/comandos.js +448 -0
- package/dist/config.js +76 -0
- package/dist/erros.js +40 -0
- package/dist/navegador.js +69 -0
- package/dist/oauth.js +150 -0
- package/dist/ponte.js +51 -0
- package/dist/principal.js +174 -0
- package/dist/saida.js +75 -0
- package/dist/sessao.js +22 -0
- package/dist/skill.js +40 -0
- package/package.json +40 -0
- package/skills/kleos/SKILL.md +122 -0
- package/skills/kleos-cli/SKILL.md +100 -0
package/dist/comandos.js
ADDED
|
@@ -0,0 +1,448 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { chamarFerramenta } from "./cliente.js";
|
|
3
|
+
import { apagarConfig, caminhoDaConfig, gravarConfig, lerConfig, mascarar } from "./config.js";
|
|
4
|
+
import { ErroDaCli, SAIDA, usoErrado } from "./erros.js";
|
|
5
|
+
import { PORTA_PADRAO } from "./navegador.js";
|
|
6
|
+
import { descobrir, gerarPkce, lerRetorno, registrarCliente, trocarCodigo, urlDeAutorizacao } from "./oauth.js";
|
|
7
|
+
import { ponte } from "./ponte.js";
|
|
8
|
+
import { humanoAgentes, humanoGerados, humanoMetricas, humanoPost, humanoPosts, humanoProjetos, humanoSemana, humanoTrabalho, humanoUso, humanoWhoami } from "./saida.js";
|
|
9
|
+
import { destinosEncontrados, instalarSkill, NOME_DA_SKILL } from "./skill.js";
|
|
10
|
+
// ── ajudantes ──────────────────────────────────────────────────────────────
|
|
11
|
+
const texto = (c, nome) => {
|
|
12
|
+
const v = c.valores[nome];
|
|
13
|
+
return typeof v === "string" && v.trim() ? v.trim() : undefined;
|
|
14
|
+
};
|
|
15
|
+
/** Flag repetida ou separada por vírgula: `--status pronto,aprovado` = `--status pronto --status aprovado`. */
|
|
16
|
+
export const lista = (v) => {
|
|
17
|
+
const brutos = Array.isArray(v) ? v : typeof v === "string" ? [v] : [];
|
|
18
|
+
const itens = brutos.flatMap((x) => String(x).split(",")).map((x) => x.trim()).filter(Boolean);
|
|
19
|
+
return itens.length ? itens : undefined;
|
|
20
|
+
};
|
|
21
|
+
export function inteiro(v, nome, min, max) {
|
|
22
|
+
if (v === undefined || v === false)
|
|
23
|
+
return undefined;
|
|
24
|
+
const n = Number(v);
|
|
25
|
+
if (!Number.isInteger(n) || n < min || n > max)
|
|
26
|
+
throw usoErrado(`--${nome} precisa ser um número inteiro de ${min} a ${max}.`);
|
|
27
|
+
return n;
|
|
28
|
+
}
|
|
29
|
+
const inteiros = (v, nome, min, max) => lista(v)?.map((x) => inteiro(x, nome, min, max));
|
|
30
|
+
/** Tira as chaves `undefined`: a ferramenta recebe só o que a pessoa pediu. */
|
|
31
|
+
export const limpar = (o) => Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined && v !== false));
|
|
32
|
+
const PROJETO = { project: { type: "string", short: "p", descricao: "Projeto: id, slug ou nome (dispensável se a chave vê um só)." } };
|
|
33
|
+
/**
|
|
34
|
+
* `--since 7d` (ou `24h`, `2w`) → `from` em data, com `to` amanhã: o
|
|
35
|
+
* intervalo que o `get_metrics` entende (ISO 8601; data sem hora = meia-noite UTC).
|
|
36
|
+
*/
|
|
37
|
+
export function desde(v, agora) {
|
|
38
|
+
const m = /^(\d+)\s*([hdw])$/i.exec(v.trim());
|
|
39
|
+
if (!m)
|
|
40
|
+
throw usoErrado("--since no formato 7d, 24h ou 2w.");
|
|
41
|
+
const n = Number(m[1]);
|
|
42
|
+
const horas = m[2].toLowerCase() === "h" ? n : m[2].toLowerCase() === "d" ? n * 24 : n * 24 * 7;
|
|
43
|
+
const dia = (t) => new Date(t).toISOString().slice(0, 10);
|
|
44
|
+
return { from: dia(agora.getTime() - horas * 3_600_000), to: dia(agora.getTime() + 86_400_000) };
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* `generate_posts` e `plan_week` acima de 10 (ou acima do que sobra no plano)
|
|
48
|
+
* devolvem `confirmation_required` sem gastar. A CLI não confirma sozinha:
|
|
49
|
+
* sai com 4 e diz que `--yes` é o sim.
|
|
50
|
+
*/
|
|
51
|
+
function exigirConfirmacao(dados, comando) {
|
|
52
|
+
if (dados.status !== "confirmation_required")
|
|
53
|
+
return dados;
|
|
54
|
+
const est = dados.estimate ? ` Estimativa: ${JSON.stringify(dados.estimate)}.` : "";
|
|
55
|
+
throw new ErroDaCli(`Gasto grande: precisa do sim de uma pessoa.${est} Mostre a estimativa e rode de novo com --yes (${comando} … --yes).`, SAIDA.aprovacao, dados);
|
|
56
|
+
}
|
|
57
|
+
const escrita = (c) => texto(c, "idempotency-key") ?? randomUUID();
|
|
58
|
+
const IDEMPOTENCIA = { "idempotency-key": { type: "string", descricao: "Repetir com a mesma chave em 24 h devolve o primeiro resultado (padrão: uma nova a cada execução)." } };
|
|
59
|
+
// ── os comandos ────────────────────────────────────────────────────────────
|
|
60
|
+
export const COMANDOS = [
|
|
61
|
+
{
|
|
62
|
+
caminho: ["login"],
|
|
63
|
+
resumo: "Entra pelo navegador (OAuth, sem chave) ou guarda uma chave de API; tudo em ~/.config/kleos/config.json (600).",
|
|
64
|
+
uso: "kleos login [--no-browser] [--port <n>] | kleos login --key <kleos_sk_…|-> [--no-verify]",
|
|
65
|
+
exemplos: ["kleos login", "kleos login --no-browser", "kleos login --key kleos_sk_…", "echo $CHAVE | kleos login --key -", "kleos login --url http://127.0.0.1:3000/mcp --key kleos_sk_…"],
|
|
66
|
+
opcoes: {
|
|
67
|
+
key: { type: "string", descricao: "Entra com uma chave de API em vez do navegador. `-` lê do stdin (ou pergunta no terminal)." },
|
|
68
|
+
"no-browser": { type: "boolean", descricao: "Não abre o navegador: só imprime o endereço do login (SSH, servidor)." },
|
|
69
|
+
port: { type: "string", descricao: `Porta local da volta do login (padrão ${PORTA_PADRAO}; ocupada, qualquer uma livre).` },
|
|
70
|
+
"no-verify": { type: "boolean", descricao: "Guarda sem conferir com whoami." },
|
|
71
|
+
},
|
|
72
|
+
async executar(c) {
|
|
73
|
+
const amb = { env: c.deps.env, home: c.deps.home };
|
|
74
|
+
if (c.valores.key !== undefined)
|
|
75
|
+
return loginComChave(c, amb);
|
|
76
|
+
return loginPeloNavegador(c, amb);
|
|
77
|
+
},
|
|
78
|
+
humano: (d) => `${d.auth === "oauth" ? `Entrou pelo navegador. Token guardado em ${String(d.config)} (renova sozinho).` : `Chave ${String(d.key)} guardada em ${String(d.config)}.`}${d.whoami ? `\n\n${humanoWhoami(d.whoami)}` : ""}`,
|
|
79
|
+
},
|
|
80
|
+
{
|
|
81
|
+
caminho: ["logout"],
|
|
82
|
+
resumo: "Apaga a chave ou o login guardado.",
|
|
83
|
+
uso: "kleos logout",
|
|
84
|
+
exemplos: ["kleos logout"],
|
|
85
|
+
async executar(c) {
|
|
86
|
+
const amb = { env: c.deps.env, home: c.deps.home };
|
|
87
|
+
const tinha = await lerConfig(amb);
|
|
88
|
+
await apagarConfig(amb);
|
|
89
|
+
if (c.deps.env.KLEOS_API_KEY)
|
|
90
|
+
c.avisar("KLEOS_API_KEY ainda está no ambiente: tire de lá também.");
|
|
91
|
+
return { ok: true, config: caminhoDaConfig(amb), auth: tinha.oauth ? "oauth" : tinha.apiKey ? "api_key" : null };
|
|
92
|
+
},
|
|
93
|
+
humano: (d) => d.auth === "oauth"
|
|
94
|
+
? `Login apagado (${String(d.config)}). Para desconectar a CLI de vez, use Configurações › Chaves de API › Apps conectados.`
|
|
95
|
+
: `Chave apagada (${String(d.config)}). Para cortar o acesso de verdade, revogue a chave em Configurações.`,
|
|
96
|
+
},
|
|
97
|
+
{
|
|
98
|
+
caminho: ["whoami"],
|
|
99
|
+
resumo: "A conta, o plano, as camadas e os escopos da chave ou do login.",
|
|
100
|
+
uso: "kleos whoami",
|
|
101
|
+
exemplos: ["kleos whoami", "kleos whoami --json"],
|
|
102
|
+
executar: (c) => chamarFerramenta(c.con, "whoami"),
|
|
103
|
+
humano: humanoWhoami,
|
|
104
|
+
},
|
|
105
|
+
{
|
|
106
|
+
caminho: ["usage"],
|
|
107
|
+
resumo: "O que o plano permite e quanto sobra, por alavanca.",
|
|
108
|
+
uso: "kleos usage",
|
|
109
|
+
exemplos: ["kleos usage", "kleos usage --json | jq '.levers[] | select(.lever==\"posts\")'"],
|
|
110
|
+
executar: (c) => chamarFerramenta(c.con, "get_usage"),
|
|
111
|
+
humano: humanoUso,
|
|
112
|
+
},
|
|
113
|
+
{
|
|
114
|
+
caminho: ["projects", "list"],
|
|
115
|
+
resumo: "Os projetos (apps) que a chave enxerga.",
|
|
116
|
+
uso: "kleos projects list",
|
|
117
|
+
exemplos: ["kleos projects list"],
|
|
118
|
+
executar: (c) => chamarFerramenta(c.con, "list_projects"),
|
|
119
|
+
humano: humanoProjetos,
|
|
120
|
+
},
|
|
121
|
+
{
|
|
122
|
+
caminho: ["agents", "list"],
|
|
123
|
+
resumo: "Os agentes de um projeto, com contas e aprovações pendentes.",
|
|
124
|
+
uso: "kleos agents list [--project <p>]",
|
|
125
|
+
exemplos: ["kleos agents list --project habi"],
|
|
126
|
+
opcoes: PROJETO,
|
|
127
|
+
executar: (c) => chamarFerramenta(c.con, "list_agents", limpar({ project: texto(c, "project") })),
|
|
128
|
+
humano: humanoAgentes,
|
|
129
|
+
},
|
|
130
|
+
{
|
|
131
|
+
caminho: ["posts", "generate"],
|
|
132
|
+
resumo: "Gera N posts para um agente (volta na hora, com os posts em 'gerando').",
|
|
133
|
+
uso: "kleos posts generate --project <p> [--agent <a>] [--count N] [--format carousel|hook-demo|wall-of-text] [--playbook <id>] [--at <iso>]… [--dry-run] [--yes]",
|
|
134
|
+
exemplos: ["kleos posts generate --project habi --agent bia --count 5", "kleos posts generate --project habi --count 30 --dry-run", "kleos posts generate --project habi --count 30 --yes"],
|
|
135
|
+
opcoes: {
|
|
136
|
+
...PROJETO,
|
|
137
|
+
agent: { type: "string", short: "a", descricao: "Agente: id, slug ou nome." },
|
|
138
|
+
count: { type: "string", short: "n", descricao: "Quantos posts (1–50, padrão 1)." },
|
|
139
|
+
format: { type: "string", descricao: "carousel, hook-demo ou wall-of-text (padrão: o Kleos alterna)." },
|
|
140
|
+
playbook: { type: "string", descricao: "Id do playbook (kleos call list_playbooks)." },
|
|
141
|
+
at: { type: "string", multiple: true, descricao: "Data ISO 8601 com fuso, uma por post, na ordem." },
|
|
142
|
+
"dry-run": { type: "boolean", descricao: "Só a estimativa de consumo; não gasta." },
|
|
143
|
+
yes: { type: "boolean", short: "y", descricao: "Confirma gasto grande (acima de 10 ou do que sobra)." },
|
|
144
|
+
...IDEMPOTENCIA,
|
|
145
|
+
},
|
|
146
|
+
async executar(c) {
|
|
147
|
+
const formato = texto(c, "format");
|
|
148
|
+
if (formato && !["carousel", "hook-demo", "wall-of-text"].includes(formato))
|
|
149
|
+
throw usoErrado("--format: carousel, hook-demo ou wall-of-text.");
|
|
150
|
+
const dados = await chamarFerramenta(c.con, "generate_posts", limpar({
|
|
151
|
+
project: texto(c, "project"),
|
|
152
|
+
agent: texto(c, "agent"),
|
|
153
|
+
count: inteiro(c.valores.count, "count", 1, 50),
|
|
154
|
+
piece: formato,
|
|
155
|
+
playbook: texto(c, "playbook"),
|
|
156
|
+
scheduled_for: lista(c.valores.at),
|
|
157
|
+
dry_run: c.valores["dry-run"] === true || undefined,
|
|
158
|
+
confirm: c.valores.yes === true || undefined,
|
|
159
|
+
idempotency_key: escrita(c),
|
|
160
|
+
}));
|
|
161
|
+
return exigirConfirmacao(dados, "kleos posts generate");
|
|
162
|
+
},
|
|
163
|
+
humano: humanoGerados,
|
|
164
|
+
},
|
|
165
|
+
{
|
|
166
|
+
caminho: ["posts", "list"],
|
|
167
|
+
resumo: "Posts por período, estado e agente.",
|
|
168
|
+
uso: "kleos posts list [--project <p>] [--agent <a>] [--status pronto,aprovado] [--from <data>] [--to <data>] [--unscheduled]",
|
|
169
|
+
exemplos: ["kleos posts list --project habi --status pronto", "kleos posts list --status pronto --from 2026-09-29 --unscheduled"],
|
|
170
|
+
opcoes: {
|
|
171
|
+
...PROJETO,
|
|
172
|
+
agent: { type: "string", short: "a", descricao: "Agente: id, slug ou nome." },
|
|
173
|
+
status: { type: "string", multiple: true, descricao: "Estados (gerando, pronto, aprovado, agendado, publicado…), por vírgula." },
|
|
174
|
+
from: { type: "string", descricao: "Início (YYYY-MM-DD ou ISO 8601), inclusivo." },
|
|
175
|
+
to: { type: "string", descricao: "Fim, exclusivo." },
|
|
176
|
+
unscheduled: { type: "boolean", descricao: "Inclui os posts sem data (os de posts generate)." },
|
|
177
|
+
},
|
|
178
|
+
executar: (c) => chamarFerramenta(c.con, "list_posts", limpar({ project: texto(c, "project"), agent: texto(c, "agent"), status: lista(c.valores.status), from: texto(c, "from"), to: texto(c, "to"), include_unscheduled: c.valores.unscheduled === true || undefined })),
|
|
179
|
+
humano: humanoPosts,
|
|
180
|
+
},
|
|
181
|
+
{
|
|
182
|
+
caminho: ["posts", "show"],
|
|
183
|
+
resumo: "Um post: slides, legenda, estado, ações e publicações.",
|
|
184
|
+
uso: "kleos posts show <post_id>",
|
|
185
|
+
exemplos: ["kleos posts show 0f1c…"],
|
|
186
|
+
posicionais: { min: 1, max: 1 },
|
|
187
|
+
executar: (c) => chamarFerramenta(c.con, "get_post", { post: c.posicionais[0] }),
|
|
188
|
+
humano: humanoPost,
|
|
189
|
+
},
|
|
190
|
+
{
|
|
191
|
+
caminho: ["posts", "approve"],
|
|
192
|
+
resumo: "Aprova posts prontos e as publicações que esperam aprovação. Publica em conta real: só com o sim da pessoa.",
|
|
193
|
+
uso: "kleos posts approve <post_id>… [--publication <id>]… [--at <iso>]",
|
|
194
|
+
exemplos: ["kleos posts approve 0f1c… 9a2b…", "kleos posts approve --publication 77aa…"],
|
|
195
|
+
posicionais: { min: 0, max: 50 },
|
|
196
|
+
opcoes: {
|
|
197
|
+
publication: { type: "string", multiple: true, descricao: "Ids de publicação a aprovar (get_post mostra)." },
|
|
198
|
+
at: { type: "string", descricao: "Data ISO 8601 para os aprovados que ainda não têm data." },
|
|
199
|
+
...IDEMPOTENCIA,
|
|
200
|
+
},
|
|
201
|
+
async executar(c) {
|
|
202
|
+
const publicacoes = lista(c.valores.publication);
|
|
203
|
+
if (!c.posicionais.length && !publicacoes)
|
|
204
|
+
throw usoErrado("Diga o que aprovar: kleos posts approve <post_id>… ou --publication <id>.");
|
|
205
|
+
return chamarFerramenta(c.con, "approve_posts", limpar({ post_ids: c.posicionais.length ? c.posicionais : undefined, publication_ids: publicacoes, scheduled_for: texto(c, "at"), idempotency_key: escrita(c) }));
|
|
206
|
+
},
|
|
207
|
+
},
|
|
208
|
+
{
|
|
209
|
+
caminho: ["posts", "schedule"],
|
|
210
|
+
resumo: "Agenda um post em uma ou mais contas.",
|
|
211
|
+
uso: "kleos posts schedule <post_id> --account <conta>… [--at <iso>] [--caption <texto>]",
|
|
212
|
+
exemplos: ['kleos posts schedule 0f1c… --account tiktok:bia --at "2026-09-30T18:00:00-03:00"', "kleos posts schedule 0f1c… --account tiktok --account instagram"],
|
|
213
|
+
posicionais: { min: 1, max: 1 },
|
|
214
|
+
opcoes: {
|
|
215
|
+
account: { type: "string", multiple: true, descricao: "Conta: id, @usuario, rede:usuario, ou só a rede quando o agente tem uma ali." },
|
|
216
|
+
at: { type: "string", descricao: "Quando, ISO 8601 com fuso." },
|
|
217
|
+
caption: { type: "string", descricao: "Legenda própria (conta no teto de posts por conta por dia)." },
|
|
218
|
+
...IDEMPOTENCIA,
|
|
219
|
+
},
|
|
220
|
+
async executar(c) {
|
|
221
|
+
const contas = lista(c.valores.account);
|
|
222
|
+
if (!contas)
|
|
223
|
+
throw usoErrado("Diga em qual conta: --account tiktok (ou @usuario, ou o id).");
|
|
224
|
+
return chamarFerramenta(c.con, "schedule_post", limpar({ post: c.posicionais[0], accounts: contas, at: texto(c, "at"), caption: texto(c, "caption"), idempotency_key: escrita(c) }));
|
|
225
|
+
},
|
|
226
|
+
},
|
|
227
|
+
{
|
|
228
|
+
caminho: ["week", "plan"],
|
|
229
|
+
resumo: "Planeja a produção dos próximos dias (1–14) para os agentes do projeto.",
|
|
230
|
+
uso: "kleos week plan --project <p> [--days 7] [--per-day N] [--times 12:00,19:00] [--weekdays 0,1,2] [--agent <a>]… [--from YYYY-MM-DD] [--activate] [--dry-run] [--yes]",
|
|
231
|
+
exemplos: ["kleos week plan --project habi --days 7 --per-day 2 --dry-run", "kleos week plan --project habi --days 7 --per-day 2 --yes"],
|
|
232
|
+
opcoes: {
|
|
233
|
+
...PROJETO,
|
|
234
|
+
days: { type: "string", descricao: "Dias à frente (1–14, padrão 7)." },
|
|
235
|
+
from: { type: "string", descricao: "Primeiro dia (YYYY-MM-DD); padrão hoje no fuso do projeto." },
|
|
236
|
+
agent: { type: "string", multiple: true, descricao: "Agentes (padrão: todos)." },
|
|
237
|
+
"per-day": { type: "string", descricao: "Posts por dia (1–12); muda a cadência antes." },
|
|
238
|
+
times: { type: "string", descricao: "Horários HH:MM, por vírgula." },
|
|
239
|
+
weekdays: { type: "string", descricao: "Dias da semana, 0 = segunda … 6 = domingo, por vírgula." },
|
|
240
|
+
activate: { type: "boolean", descricao: "Liga a produção contínua para esse horizonte." },
|
|
241
|
+
"dry-run": { type: "boolean", descricao: "Só quantos posts criaria; não gasta." },
|
|
242
|
+
yes: { type: "boolean", short: "y", descricao: "Confirma gasto grande." },
|
|
243
|
+
...IDEMPOTENCIA,
|
|
244
|
+
},
|
|
245
|
+
async executar(c) {
|
|
246
|
+
const dados = await chamarFerramenta(c.con, "plan_week", limpar({
|
|
247
|
+
project: texto(c, "project"),
|
|
248
|
+
days: inteiro(c.valores.days, "days", 1, 14),
|
|
249
|
+
from: texto(c, "from"),
|
|
250
|
+
agents: lista(c.valores.agent),
|
|
251
|
+
posts_per_day: inteiro(c.valores["per-day"], "per-day", 1, 12),
|
|
252
|
+
times: lista(c.valores.times),
|
|
253
|
+
weekdays: inteiros(c.valores.weekdays, "weekdays", 0, 6),
|
|
254
|
+
activate: c.valores.activate === true || undefined,
|
|
255
|
+
dry_run: c.valores["dry-run"] === true || undefined,
|
|
256
|
+
confirm: c.valores.yes === true || undefined,
|
|
257
|
+
idempotency_key: escrita(c),
|
|
258
|
+
}));
|
|
259
|
+
return exigirConfirmacao(dados, "kleos week plan");
|
|
260
|
+
},
|
|
261
|
+
humano: humanoSemana,
|
|
262
|
+
},
|
|
263
|
+
{
|
|
264
|
+
caminho: ["jobs", "wait"],
|
|
265
|
+
resumo: "Espera um trabalho da fila terminar (sai 0 se deu certo, 1 se falhou).",
|
|
266
|
+
uso: "kleos jobs wait <job_id> [--interval 3] [--timeout 600]",
|
|
267
|
+
exemplos: ["kleos jobs wait 5d0e…", "kleos jobs wait 5d0e… --timeout 120 --json"],
|
|
268
|
+
posicionais: { min: 1, max: 1 },
|
|
269
|
+
opcoes: {
|
|
270
|
+
interval: { type: "string", descricao: "Segundos entre consultas (1–60, padrão 3)." },
|
|
271
|
+
timeout: { type: "string", descricao: "Desiste depois de N segundos (padrão 600)." },
|
|
272
|
+
},
|
|
273
|
+
async executar(c) {
|
|
274
|
+
const intervalo = (inteiro(c.valores.interval, "interval", 1, 60) ?? 3) * 1000;
|
|
275
|
+
const limite = (inteiro(c.valores.timeout, "timeout", 1, 86_400) ?? 600) * 1000;
|
|
276
|
+
const inicio = c.deps.agora().getTime();
|
|
277
|
+
let ultimo = "";
|
|
278
|
+
for (;;) {
|
|
279
|
+
const job = await chamarFerramenta(c.con, "get_job", { job_id: c.posicionais[0] });
|
|
280
|
+
const linha = humanoTrabalho(job);
|
|
281
|
+
if (!c.json && linha !== ultimo)
|
|
282
|
+
c.avisar(linha);
|
|
283
|
+
ultimo = linha;
|
|
284
|
+
if (job.status === "done")
|
|
285
|
+
return job;
|
|
286
|
+
if (job.status === "failed")
|
|
287
|
+
throw new ErroDaCli(`O trabalho falhou: ${String(job.error ?? "sem motivo")}`, SAIDA.erro, job);
|
|
288
|
+
if (c.deps.agora().getTime() - inicio + intervalo > limite)
|
|
289
|
+
throw new ErroDaCli(`Ainda ${String(job.status)} depois de ${Math.round(limite / 1000)}s. Rode de novo para continuar esperando.`, SAIDA.erro, job);
|
|
290
|
+
await c.deps.esperar(intervalo);
|
|
291
|
+
}
|
|
292
|
+
},
|
|
293
|
+
humano: humanoTrabalho,
|
|
294
|
+
},
|
|
295
|
+
{
|
|
296
|
+
caminho: ["metrics"],
|
|
297
|
+
resumo: "Resultados de um período: totais, por conta e os melhores posts.",
|
|
298
|
+
uso: "kleos metrics [--project <p>] [--since 7d | --from <data> --to <data>] [--platform tiktok|instagram]",
|
|
299
|
+
exemplos: ["kleos metrics --project habi --since 7d", "kleos metrics --from 2026-09-01 --to 2026-09-15 --platform tiktok"],
|
|
300
|
+
opcoes: {
|
|
301
|
+
...PROJETO,
|
|
302
|
+
since: { type: "string", descricao: "Janela até hoje: 7d, 24h, 2w." },
|
|
303
|
+
from: { type: "string", descricao: "Início (YYYY-MM-DD ou ISO 8601)." },
|
|
304
|
+
to: { type: "string", descricao: "Fim." },
|
|
305
|
+
platform: { type: "string", descricao: "tiktok ou instagram." },
|
|
306
|
+
},
|
|
307
|
+
async executar(c) {
|
|
308
|
+
const plataforma = texto(c, "platform");
|
|
309
|
+
if (plataforma && plataforma !== "tiktok" && plataforma !== "instagram")
|
|
310
|
+
throw usoErrado("--platform: tiktok ou instagram.");
|
|
311
|
+
const janela = texto(c, "since");
|
|
312
|
+
if (janela && (texto(c, "from") || texto(c, "to")))
|
|
313
|
+
throw usoErrado("Use --since ou --from/--to, não os dois.");
|
|
314
|
+
const periodo = janela ? desde(janela, c.deps.agora()) : { from: texto(c, "from"), to: texto(c, "to") };
|
|
315
|
+
return chamarFerramenta(c.con, "get_metrics", limpar({ project: texto(c, "project"), ...periodo, platform: plataforma }));
|
|
316
|
+
},
|
|
317
|
+
humano: humanoMetricas,
|
|
318
|
+
},
|
|
319
|
+
{
|
|
320
|
+
caminho: ["call"],
|
|
321
|
+
resumo: "Chama qualquer ferramenta do MCP pelo nome (a lista está em /llms-full.txt).",
|
|
322
|
+
uso: "kleos call <ferramenta> [--args '<json>']",
|
|
323
|
+
exemplos: ["kleos call list_playbooks --args '{\"project\":\"habi\"}'", "kleos call revise_post --args '{\"post\":\"0f1c…\",\"instruction\":\"gancho em pergunta\"}'"],
|
|
324
|
+
posicionais: { min: 1, max: 1 },
|
|
325
|
+
opcoes: { args: { type: "string", descricao: "Os argumentos da ferramenta, em JSON (objeto)." } },
|
|
326
|
+
async executar(c) {
|
|
327
|
+
const bruto = texto(c, "args") ?? "{}";
|
|
328
|
+
let args;
|
|
329
|
+
try {
|
|
330
|
+
args = JSON.parse(bruto);
|
|
331
|
+
}
|
|
332
|
+
catch {
|
|
333
|
+
throw usoErrado("--args precisa ser JSON válido, ex.: --args '{\"project\":\"habi\"}'.");
|
|
334
|
+
}
|
|
335
|
+
if (!args || typeof args !== "object" || Array.isArray(args))
|
|
336
|
+
throw usoErrado("--args precisa ser um objeto JSON.");
|
|
337
|
+
return chamarFerramenta(c.con, c.posicionais[0], args);
|
|
338
|
+
},
|
|
339
|
+
},
|
|
340
|
+
{
|
|
341
|
+
caminho: ["mcp"],
|
|
342
|
+
resumo: "Ponte stdio → HTTP para o cliente de MCP que só fala stdio.",
|
|
343
|
+
uso: "kleos mcp",
|
|
344
|
+
exemplos: ['{"mcpServers":{"kleos":{"command":"npx","args":["-y","kleos","mcp"],"env":{"KLEOS_API_KEY":"kleos_sk_…"}}}}'],
|
|
345
|
+
async executar(c) {
|
|
346
|
+
if (!c.con.apiKey)
|
|
347
|
+
throw new ErroDaCli("Sem chave de API: defina KLEOS_API_KEY na configuração do cliente ou rode kleos login.", SAIDA.erro);
|
|
348
|
+
await ponte(c.con, { entrada: c.deps.stdin, saida: c.deps.stdout, erros: c.deps.stderr });
|
|
349
|
+
return undefined;
|
|
350
|
+
},
|
|
351
|
+
},
|
|
352
|
+
{
|
|
353
|
+
caminho: ["skill", "install"],
|
|
354
|
+
resumo: "Instala a skill do Kleos no Claude Code, Codex, Hermes e OpenClaw que existirem na máquina.",
|
|
355
|
+
uso: "kleos skill install [--variant cli|mcp] [--target <pasta de skills>]",
|
|
356
|
+
exemplos: ["kleos skill install", "kleos skill install --variant mcp", "kleos skill install --target ./.claude/skills"],
|
|
357
|
+
opcoes: {
|
|
358
|
+
variant: { type: "string", descricao: "cli (padrão: a skill usa esta CLI) ou mcp (a skill usa as ferramentas do MCP)." },
|
|
359
|
+
target: { type: "string", multiple: true, descricao: "Pasta de skills de destino; repete para várias." },
|
|
360
|
+
},
|
|
361
|
+
async executar(c) {
|
|
362
|
+
const variante = (texto(c, "variant") ?? "cli");
|
|
363
|
+
if (!(variante in NOME_DA_SKILL))
|
|
364
|
+
throw usoErrado("--variant: cli ou mcp.");
|
|
365
|
+
const alvos = lista(c.valores.target);
|
|
366
|
+
const destinos = alvos ? alvos.map((pasta) => ({ agente: "--target", pasta })) : await destinosEncontrados(c.deps.home);
|
|
367
|
+
if (!destinos.length)
|
|
368
|
+
throw usoErrado("Não achei ~/.claude, ~/.codex, ~/.hermes nem ~/.openclaw. Diga onde instalar: kleos skill install --target <pasta de skills>.");
|
|
369
|
+
const feitos = await instalarSkill(c.deps.origemDasSkills, variante, destinos);
|
|
370
|
+
return { ok: true, skill: NOME_DA_SKILL[variante], installed: feitos };
|
|
371
|
+
},
|
|
372
|
+
humano: (d) => `Skill ${String(d.skill)} instalada:\n${d.installed.map((f) => ` ${f.agente}: ${f.caminho}`).join("\n")}`,
|
|
373
|
+
},
|
|
374
|
+
];
|
|
375
|
+
// ── login ──────────────────────────────────────────────────────────────────
|
|
376
|
+
/** Quanto o login espera o navegador voltar. */
|
|
377
|
+
const ESPERA_DO_LOGIN_MS = 5 * 60_000;
|
|
378
|
+
async function loginComChave(c, amb) {
|
|
379
|
+
let chave = texto(c, "key");
|
|
380
|
+
if (!chave || chave === "-") {
|
|
381
|
+
if (c.deps.stdinTTY)
|
|
382
|
+
chave = (await c.deps.perguntar("Chave de API do Kleos (kleos_sk_…): ")).trim();
|
|
383
|
+
else
|
|
384
|
+
chave = (await lerTudo(c.deps.stdin)).trim();
|
|
385
|
+
}
|
|
386
|
+
if (!chave)
|
|
387
|
+
throw usoErrado("Informe a chave: kleos login --key kleos_sk_… (crie em Configurações › Chaves de API), ou só kleos login para entrar pelo navegador.");
|
|
388
|
+
if (!chave.startsWith("kleos_sk_"))
|
|
389
|
+
throw usoErrado("Isso não parece uma chave do Kleos: ela começa com kleos_sk_.");
|
|
390
|
+
let quem = null;
|
|
391
|
+
if (!c.valores["no-verify"])
|
|
392
|
+
quem = await chamarFerramenta({ mcpUrl: c.con.mcpUrl, apiKey: chave, fetch: c.con.fetch }, "whoami");
|
|
393
|
+
const url = texto(c, "url");
|
|
394
|
+
const { oauth: _login, ...anterior } = await lerConfig(amb);
|
|
395
|
+
// A chave substitui o login pelo navegador: uma credencial só no arquivo.
|
|
396
|
+
const caminho = await gravarConfig(amb, { ...anterior, apiKey: chave, ...(url ? { mcpUrl: url } : {}) });
|
|
397
|
+
if (c.deps.env.KLEOS_API_KEY)
|
|
398
|
+
c.avisar("Atenção: KLEOS_API_KEY no ambiente continua valendo por cima do arquivo.");
|
|
399
|
+
return { ok: true, auth: "api_key", config: caminho, key: mascarar(chave), mcp_url: url ?? c.con.mcpUrl, ...(quem ? { whoami: quem } : {}) };
|
|
400
|
+
}
|
|
401
|
+
/**
|
|
402
|
+
* OAuth 2.1 com PKCE (`oauth.ts`): descobre o servidor de login, registra a
|
|
403
|
+
* CLI para a porta local (ou reaproveita o registro guardado), abre o
|
|
404
|
+
* navegador na tela de consentimento do Kleos e troca o código pelo token.
|
|
405
|
+
*/
|
|
406
|
+
async function loginPeloNavegador(c, amb) {
|
|
407
|
+
const porta = inteiro(c.valores.port, "port", 1024, 65535) ?? PORTA_PADRAO;
|
|
408
|
+
const { recurso, servidor } = await descobrir(c.con.mcpUrl, c.con.fetch);
|
|
409
|
+
const volta = await c.deps.ouvirCallback(porta);
|
|
410
|
+
try {
|
|
411
|
+
const anterior = await lerConfig(amb);
|
|
412
|
+
const guardado = anterior.oauth;
|
|
413
|
+
const clientId = guardado && guardado.issuer === servidor.issuer && guardado.redirectUri === volta.redirectUri ? guardado.clientId : await registrarCliente(servidor, volta.redirectUri, c.con.fetch);
|
|
414
|
+
const { verifier, challenge, state } = gerarPkce();
|
|
415
|
+
const url = urlDeAutorizacao({ servidor, clientId, redirectUri: volta.redirectUri, challenge, state, recurso });
|
|
416
|
+
c.avisar(`Abra para entrar no Kleos:\n ${url}`);
|
|
417
|
+
if (!c.valores["no-browser"] && !(await c.deps.abrirNavegador(url)))
|
|
418
|
+
c.avisar("Não deu para abrir o navegador: copie o endereço acima.");
|
|
419
|
+
const params = await volta.esperar(ESPERA_DO_LOGIN_MS).catch((e) => {
|
|
420
|
+
throw new ErroDaCli(`Login não concluído: ${e.message}. Rode kleos login de novo.`, SAIDA.erro);
|
|
421
|
+
});
|
|
422
|
+
const code = lerRetorno(params, { state, issuer: servidor.issuer });
|
|
423
|
+
const tokens = await trocarCodigo({ tokenEndpoint: servidor.token_endpoint, clientId, redirectUri: volta.redirectUri, code, verifier, recurso }, c.con.fetch, c.deps.agora);
|
|
424
|
+
let quem = null;
|
|
425
|
+
if (!c.valores["no-verify"])
|
|
426
|
+
quem = await chamarFerramenta({ mcpUrl: c.con.mcpUrl, apiKey: tokens.accessToken, fetch: c.con.fetch }, "whoami");
|
|
427
|
+
const urlDoMcp = texto(c, "url");
|
|
428
|
+
const { apiKey: _chave, ...resto } = anterior;
|
|
429
|
+
// O login substitui a chave guardada: uma credencial só no arquivo.
|
|
430
|
+
const caminho = await gravarConfig(amb, {
|
|
431
|
+
...resto,
|
|
432
|
+
...(urlDoMcp ? { mcpUrl: urlDoMcp } : {}),
|
|
433
|
+
oauth: { issuer: servidor.issuer, tokenEndpoint: servidor.token_endpoint, clientId, redirectUri: volta.redirectUri, resource: recurso, accessToken: tokens.accessToken, refreshToken: tokens.refreshToken, expiresAt: tokens.expiraEm },
|
|
434
|
+
});
|
|
435
|
+
if (c.deps.env.KLEOS_API_KEY)
|
|
436
|
+
c.avisar("Atenção: KLEOS_API_KEY no ambiente continua valendo por cima do login.");
|
|
437
|
+
return { ok: true, auth: "oauth", config: caminho, mcp_url: urlDoMcp ?? c.con.mcpUrl, expires_at: new Date(tokens.expiraEm).toISOString(), ...(quem ? { whoami: quem } : {}) };
|
|
438
|
+
}
|
|
439
|
+
finally {
|
|
440
|
+
volta.fechar();
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
async function lerTudo(entrada) {
|
|
444
|
+
let tudo = "";
|
|
445
|
+
for await (const pedaco of entrada)
|
|
446
|
+
tudo += String(pedaco);
|
|
447
|
+
return tudo;
|
|
448
|
+
}
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { chmod, mkdir, readFile, rm, writeFile } from "node:fs/promises";
|
|
2
|
+
import { dirname, join } from "node:path";
|
|
3
|
+
/**
|
|
4
|
+
* Onde a CLI guarda a credencial: `~/.config/kleos/config.json` (ou
|
|
5
|
+
* `$XDG_CONFIG_HOME/kleos/config.json`), com permissão 600 — só o dono lê.
|
|
6
|
+
*
|
|
7
|
+
* Uma das duas, nunca as duas: a **chave de API** (`kleos login --key`) ou a
|
|
8
|
+
* **sessão OAuth** (`kleos login`, pelo navegador) com o token, o refresh e o
|
|
9
|
+
* registro da CLI no servidor de login. `KLEOS_API_KEY` e `KLEOS_MCP_URL` no
|
|
10
|
+
* ambiente sobrepõem o arquivo: é como o agente em servidor, cron ou CI entra
|
|
11
|
+
* sem `login`.
|
|
12
|
+
*/
|
|
13
|
+
export const MCP_URL_PADRAO = "https://mcp.zurc.app/mcp";
|
|
14
|
+
export function caminhoDaConfig({ env, home }) {
|
|
15
|
+
const base = env.XDG_CONFIG_HOME?.trim() || join(home, ".config");
|
|
16
|
+
return join(base, "kleos", "config.json");
|
|
17
|
+
}
|
|
18
|
+
function lerSessao(v) {
|
|
19
|
+
if (!v || typeof v !== "object")
|
|
20
|
+
return undefined;
|
|
21
|
+
const s = v;
|
|
22
|
+
const textos = ["issuer", "tokenEndpoint", "clientId", "redirectUri", "resource", "accessToken"];
|
|
23
|
+
if (!textos.every((k) => typeof s[k] === "string" && s[k]))
|
|
24
|
+
return undefined;
|
|
25
|
+
if (typeof s.expiresAt !== "number")
|
|
26
|
+
return undefined;
|
|
27
|
+
return {
|
|
28
|
+
issuer: s.issuer,
|
|
29
|
+
tokenEndpoint: s.tokenEndpoint,
|
|
30
|
+
clientId: s.clientId,
|
|
31
|
+
redirectUri: s.redirectUri,
|
|
32
|
+
resource: s.resource,
|
|
33
|
+
accessToken: s.accessToken,
|
|
34
|
+
refreshToken: typeof s.refreshToken === "string" ? s.refreshToken : null,
|
|
35
|
+
expiresAt: s.expiresAt,
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
export async function lerConfig(amb) {
|
|
39
|
+
try {
|
|
40
|
+
const bruto = JSON.parse(await readFile(caminhoDaConfig(amb), "utf8"));
|
|
41
|
+
if (!bruto || typeof bruto !== "object")
|
|
42
|
+
return {};
|
|
43
|
+
const c = bruto;
|
|
44
|
+
const oauth = lerSessao(c.oauth);
|
|
45
|
+
return { ...(typeof c.apiKey === "string" ? { apiKey: c.apiKey } : {}), ...(typeof c.mcpUrl === "string" ? { mcpUrl: c.mcpUrl } : {}), ...(oauth ? { oauth } : {}) };
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
return {};
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
export async function gravarConfig(amb, config) {
|
|
52
|
+
const caminho = caminhoDaConfig(amb);
|
|
53
|
+
await mkdir(dirname(caminho), { recursive: true, mode: 0o700 });
|
|
54
|
+
await writeFile(caminho, `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 });
|
|
55
|
+
// `mode` só vale na criação: um arquivo que já existia mantém a permissão velha.
|
|
56
|
+
await chmod(caminho, 0o600);
|
|
57
|
+
return caminho;
|
|
58
|
+
}
|
|
59
|
+
export async function apagarConfig(amb) {
|
|
60
|
+
await rm(caminhoDaConfig(amb), { force: true });
|
|
61
|
+
}
|
|
62
|
+
/** Ambiente primeiro, depois o arquivo (chave ou sessão); a URL, por fim, o endereço público. */
|
|
63
|
+
export function resolverCredenciais(env, arquivo, flags = {}) {
|
|
64
|
+
const mcpUrl = (flags.url?.trim() || env.KLEOS_MCP_URL?.trim() || arquivo.mcpUrl?.trim() || MCP_URL_PADRAO).replace(/\/+$/, "");
|
|
65
|
+
const doEnv = env.KLEOS_API_KEY?.trim();
|
|
66
|
+
if (doEnv)
|
|
67
|
+
return { apiKey: doEnv, mcpUrl, origem: "env", oauth: null };
|
|
68
|
+
const doArquivo = arquivo.apiKey?.trim();
|
|
69
|
+
if (doArquivo)
|
|
70
|
+
return { apiKey: doArquivo, mcpUrl, origem: "arquivo", oauth: null };
|
|
71
|
+
if (arquivo.oauth)
|
|
72
|
+
return { apiKey: arquivo.oauth.accessToken, mcpUrl, origem: "oauth", oauth: arquivo.oauth };
|
|
73
|
+
return { apiKey: null, mcpUrl, origem: null, oauth: null };
|
|
74
|
+
}
|
|
75
|
+
/** Só o começo da chave, para mostrar qual é sem expor o segredo. */
|
|
76
|
+
export const mascarar = (chave) => (chave.length > 16 ? `${chave.slice(0, 15)}…` : "kleos_sk_…");
|
package/dist/erros.js
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Os códigos de saída da CLI — o contrato com quem a chama por script ou por
|
|
3
|
+
* agente (`docs/AGENTES_MCP_CLI.md`, seção 3):
|
|
4
|
+
*
|
|
5
|
+
* - 0 ok
|
|
6
|
+
* - 1 erro (rede, chave inválida, servidor, trabalho que falhou)
|
|
7
|
+
* - 2 uso errado (comando, flag ou parâmetro inválido)
|
|
8
|
+
* - 3 limite ou cota do plano (não repita em laço: espere renovar ou faça upgrade)
|
|
9
|
+
* - 4 falta aprovação humana, escopo da chave ou camada do plano
|
|
10
|
+
*/
|
|
11
|
+
export const SAIDA = { ok: 0, erro: 1, uso: 2, limite: 3, aprovacao: 4 };
|
|
12
|
+
export class ErroDaCli extends Error {
|
|
13
|
+
saida;
|
|
14
|
+
dados;
|
|
15
|
+
constructor(message, saida = SAIDA.erro,
|
|
16
|
+
/** O objeto do erro como o servidor mandou (`code`, `teto`, `renovaEm`…), para `--json`. */
|
|
17
|
+
dados) {
|
|
18
|
+
super(message);
|
|
19
|
+
this.saida = saida;
|
|
20
|
+
this.dados = dados;
|
|
21
|
+
this.name = "ErroDaCli";
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
export const usoErrado = (mensagem) => new ErroDaCli(mensagem, SAIDA.uso);
|
|
25
|
+
/** O `code` do erro de ferramenta (`src/server/mcp/erros.ts`) → código de saída. */
|
|
26
|
+
export function saidaDoCodigo(code) {
|
|
27
|
+
switch (code) {
|
|
28
|
+
case "limite":
|
|
29
|
+
return SAIDA.limite;
|
|
30
|
+
case "escopo_faltando":
|
|
31
|
+
case "camada_desligada":
|
|
32
|
+
case "proibido":
|
|
33
|
+
return SAIDA.aprovacao;
|
|
34
|
+
case "invalido":
|
|
35
|
+
case "ambiguo":
|
|
36
|
+
return SAIDA.uso;
|
|
37
|
+
default:
|
|
38
|
+
return SAIDA.erro;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { createServer } from "node:http";
|
|
3
|
+
/** Porta preferida: fixa, para o registro da CLI no servidor de login valer entre um login e outro. */
|
|
4
|
+
export const PORTA_PADRAO = 47651;
|
|
5
|
+
const PAGINA = (titulo, texto) => `<!doctype html><html lang="pt-BR"><meta charset="utf-8"><meta name="color-scheme" content="light dark"><title>${titulo}</title><body style="font-family:system-ui,sans-serif;display:grid;place-items:center;min-height:100vh;margin:0"><main style="max-width:28rem;padding:1.5rem;text-align:center"><h1 style="font-size:1.25rem">${titulo}</h1><p>${texto}</p></main></body></html>`;
|
|
6
|
+
function escutar(servidor, porta) {
|
|
7
|
+
return new Promise((resolve, reject) => {
|
|
8
|
+
const erro = (e) => reject(e);
|
|
9
|
+
servidor.once("error", erro);
|
|
10
|
+
servidor.listen(porta, "127.0.0.1", () => {
|
|
11
|
+
servidor.off("error", erro);
|
|
12
|
+
const endereco = servidor.address();
|
|
13
|
+
resolve(typeof endereco === "object" && endereco ? endereco.port : porta);
|
|
14
|
+
});
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
export async function ouvirCallback(porta = PORTA_PADRAO) {
|
|
18
|
+
let entregar = () => undefined;
|
|
19
|
+
const chegou = new Promise((resolve) => (entregar = resolve));
|
|
20
|
+
const servidor = createServer((req, res) => {
|
|
21
|
+
const url = new URL(req.url ?? "/", "http://127.0.0.1");
|
|
22
|
+
if (url.pathname !== "/callback") {
|
|
23
|
+
res.writeHead(404).end();
|
|
24
|
+
return;
|
|
25
|
+
}
|
|
26
|
+
const recusou = url.searchParams.has("error");
|
|
27
|
+
res.writeHead(200, { "content-type": "text/html; charset=utf-8" }).end(recusou ? PAGINA("Conexão recusada", "Nada foi guardado. Pode fechar esta aba.") : PAGINA("Kleos conectado", "Pode fechar esta aba e voltar ao terminal."));
|
|
28
|
+
entregar(url.searchParams);
|
|
29
|
+
});
|
|
30
|
+
let usada;
|
|
31
|
+
try {
|
|
32
|
+
usada = await escutar(servidor, porta);
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
// Porta ocupada: qualquer uma livre. O registro da CLI é refeito para ela.
|
|
36
|
+
usada = await escutar(servidor, 0);
|
|
37
|
+
}
|
|
38
|
+
return {
|
|
39
|
+
redirectUri: `http://127.0.0.1:${usada}/callback`,
|
|
40
|
+
esperar: (ms) => Promise.race([
|
|
41
|
+
chegou,
|
|
42
|
+
new Promise((_, reject) => {
|
|
43
|
+
const t = setTimeout(() => reject(new Error(`o navegador não voltou em ${Math.round(ms / 60_000)} min`)), ms);
|
|
44
|
+
t.unref();
|
|
45
|
+
}),
|
|
46
|
+
]),
|
|
47
|
+
fechar: () => {
|
|
48
|
+
servidor.close();
|
|
49
|
+
servidor.closeAllConnections?.();
|
|
50
|
+
},
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
/** Abre a URL no navegador padrão. `false` se não deu (sem desktop, SSH): a URL já foi impressa. */
|
|
54
|
+
export function abrirNavegador(url) {
|
|
55
|
+
const [comando, args] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["cmd", ["/c", "start", '""', url.replace(/&/g, "^&")]] : ["xdg-open", [url]];
|
|
56
|
+
return new Promise((resolve) => {
|
|
57
|
+
try {
|
|
58
|
+
const filho = spawn(comando, args, { stdio: "ignore", detached: true });
|
|
59
|
+
filho.once("error", () => resolve(false));
|
|
60
|
+
filho.once("spawn", () => {
|
|
61
|
+
filho.unref();
|
|
62
|
+
resolve(true);
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
resolve(false);
|
|
67
|
+
}
|
|
68
|
+
});
|
|
69
|
+
}
|