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/oauth.js
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
2
|
+
import { ErroDaCli, SAIDA } from "./erros.js";
|
|
3
|
+
const falha = (mensagem) => new ErroDaCli(mensagem, SAIDA.erro);
|
|
4
|
+
async function lerJson(f, url, init) {
|
|
5
|
+
let resposta;
|
|
6
|
+
try {
|
|
7
|
+
resposta = await f(url, { ...init, headers: { accept: "application/json", ...init?.headers } });
|
|
8
|
+
}
|
|
9
|
+
catch (e) {
|
|
10
|
+
throw falha(`Não deu para falar com ${new URL(url).host}: ${e.message}`);
|
|
11
|
+
}
|
|
12
|
+
const texto = await resposta.text();
|
|
13
|
+
try {
|
|
14
|
+
const json = JSON.parse(texto);
|
|
15
|
+
return { status: resposta.status, corpo: json && typeof json === "object" && !Array.isArray(json) ? json : null };
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
return { status: resposta.status, corpo: null };
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
/** `https://h/mcp` → `https://h/.well-known/oauth-protected-resource/mcp`, e a raiz como reserva. */
|
|
22
|
+
export function urlsDosMetadadosDoRecurso(mcpUrl) {
|
|
23
|
+
const url = new URL(mcpUrl);
|
|
24
|
+
const caminho = url.pathname.replace(/\/+$/, "");
|
|
25
|
+
const raiz = `${url.origin}/.well-known/oauth-protected-resource`;
|
|
26
|
+
return caminho ? [`${raiz}${caminho}`, raiz] : [raiz];
|
|
27
|
+
}
|
|
28
|
+
/** A ordem da spec do MCP para emissor com caminho: OAuth com inserção, OIDC com inserção, OIDC anexado. */
|
|
29
|
+
export function urlsDosMetadadosDoServidor(issuer) {
|
|
30
|
+
const url = new URL(issuer);
|
|
31
|
+
const caminho = url.pathname.replace(/\/+$/, "");
|
|
32
|
+
if (!caminho)
|
|
33
|
+
return [`${url.origin}/.well-known/oauth-authorization-server`, `${url.origin}/.well-known/openid-configuration`];
|
|
34
|
+
return [`${url.origin}/.well-known/oauth-authorization-server${caminho}`, `${url.origin}/.well-known/openid-configuration${caminho}`, `${url.origin}${caminho}/.well-known/openid-configuration`];
|
|
35
|
+
}
|
|
36
|
+
export async function descobrir(mcpUrl, f) {
|
|
37
|
+
let recurso = null;
|
|
38
|
+
let emissor = null;
|
|
39
|
+
for (const url of urlsDosMetadadosDoRecurso(mcpUrl)) {
|
|
40
|
+
const { status, corpo } = await lerJson(f, url);
|
|
41
|
+
const servidores = corpo?.authorization_servers;
|
|
42
|
+
if (status === 200 && Array.isArray(servidores) && typeof servidores[0] === "string") {
|
|
43
|
+
emissor = servidores[0];
|
|
44
|
+
recurso = typeof corpo?.resource === "string" ? corpo.resource : mcpUrl;
|
|
45
|
+
break;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
if (!emissor || !recurso)
|
|
49
|
+
throw falha(`${new URL(mcpUrl).host} não anuncia login OAuth. Use uma chave: kleos login --key kleos_sk_… (Configurações › Chaves de API).`);
|
|
50
|
+
for (const url of urlsDosMetadadosDoServidor(emissor)) {
|
|
51
|
+
const { status, corpo } = await lerJson(f, url);
|
|
52
|
+
if (status !== 200 || !corpo)
|
|
53
|
+
continue;
|
|
54
|
+
// RFC 8414 §3.3: o emissor do documento tem que ser o mesmo que montou o endereço.
|
|
55
|
+
if (corpo.issuer !== emissor)
|
|
56
|
+
throw falha(`O servidor de login respondeu com outro emissor (${String(corpo.issuer)}); não é seguro seguir.`);
|
|
57
|
+
if (typeof corpo.authorization_endpoint !== "string" || typeof corpo.token_endpoint !== "string")
|
|
58
|
+
continue;
|
|
59
|
+
const metodos = Array.isArray(corpo.code_challenge_methods_supported) ? corpo.code_challenge_methods_supported : ["S256"];
|
|
60
|
+
if (!metodos.includes("S256"))
|
|
61
|
+
throw falha("O servidor de login não aceita PKCE S256.");
|
|
62
|
+
return { recurso, servidor: corpo };
|
|
63
|
+
}
|
|
64
|
+
throw falha(`Não achei os metadados do servidor de login (${emissor}).`);
|
|
65
|
+
}
|
|
66
|
+
const b64url = (b) => b.toString("base64url");
|
|
67
|
+
/** PKCE (RFC 7636): o `code_verifier` fica na CLI; só o desafio S256 vai para o navegador. */
|
|
68
|
+
export function gerarPkce(aleatorio = randomBytes) {
|
|
69
|
+
const verifier = b64url(aleatorio(32));
|
|
70
|
+
return { verifier, challenge: desafioS256(verifier), state: b64url(aleatorio(16)) };
|
|
71
|
+
}
|
|
72
|
+
export const desafioS256 = (verifier) => b64url(createHash("sha256").update(verifier).digest());
|
|
73
|
+
/** DCR: a CLI como cliente público nativo, sem segredo, com o endereço de volta exato. */
|
|
74
|
+
export async function registrarCliente(servidor, redirectUri, f) {
|
|
75
|
+
if (!servidor.registration_endpoint)
|
|
76
|
+
throw falha("O servidor de login não aceita registro de app. Use uma chave: kleos login --key kleos_sk_…");
|
|
77
|
+
const { status, corpo } = await lerJson(f, servidor.registration_endpoint, {
|
|
78
|
+
method: "POST",
|
|
79
|
+
headers: { "content-type": "application/json" },
|
|
80
|
+
body: JSON.stringify({
|
|
81
|
+
client_name: "Kleos CLI",
|
|
82
|
+
client_uri: "https://ugc.zurc.app/docs/agentes",
|
|
83
|
+
redirect_uris: [redirectUri],
|
|
84
|
+
grant_types: ["authorization_code", "refresh_token"],
|
|
85
|
+
response_types: ["code"],
|
|
86
|
+
token_endpoint_auth_method: "none",
|
|
87
|
+
application_type: "native",
|
|
88
|
+
}),
|
|
89
|
+
});
|
|
90
|
+
if (status < 200 || status >= 300 || typeof corpo?.client_id !== "string") {
|
|
91
|
+
const motivo = typeof corpo?.error_description === "string" ? corpo.error_description : typeof corpo?.error === "string" ? corpo.error : `HTTP ${status}`;
|
|
92
|
+
throw falha(`O servidor de login recusou o registro da CLI (${motivo}).`);
|
|
93
|
+
}
|
|
94
|
+
return corpo.client_id;
|
|
95
|
+
}
|
|
96
|
+
export function urlDeAutorizacao(p) {
|
|
97
|
+
const url = new URL(p.servidor.authorization_endpoint);
|
|
98
|
+
url.searchParams.set("response_type", "code");
|
|
99
|
+
url.searchParams.set("client_id", p.clientId);
|
|
100
|
+
url.searchParams.set("redirect_uri", p.redirectUri);
|
|
101
|
+
url.searchParams.set("code_challenge", p.challenge);
|
|
102
|
+
url.searchParams.set("code_challenge_method", "S256");
|
|
103
|
+
url.searchParams.set("state", p.state);
|
|
104
|
+
// RFC 8707: a spec do MCP manda enviar sempre, mesmo que o servidor ignore.
|
|
105
|
+
url.searchParams.set("resource", p.recurso);
|
|
106
|
+
return url.toString();
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* O que voltou no `redirect_uri`: o código, conferido. `state` diferente é
|
|
110
|
+
* outro login (ou alguém tentando injetar um código); `iss` diferente é a
|
|
111
|
+
* mistura de servidores da RFC 9207 — nos dois, nada segue.
|
|
112
|
+
*/
|
|
113
|
+
export function lerRetorno(params, esperado) {
|
|
114
|
+
const iss = params.get("iss");
|
|
115
|
+
if (iss !== null && iss !== esperado.issuer)
|
|
116
|
+
throw falha("O retorno do login veio de outro servidor. Rode kleos login de novo.");
|
|
117
|
+
if (params.get("state") !== esperado.state)
|
|
118
|
+
throw falha("O retorno do login não é deste pedido (state diferente). Rode kleos login de novo.");
|
|
119
|
+
const erro = params.get("error");
|
|
120
|
+
if (erro === "access_denied")
|
|
121
|
+
throw new ErroDaCli("Você recusou a conexão no navegador. Nada foi guardado.", SAIDA.aprovacao);
|
|
122
|
+
if (erro)
|
|
123
|
+
throw falha(`O login não terminou: ${params.get("error_description") ?? erro}.`);
|
|
124
|
+
const code = params.get("code");
|
|
125
|
+
if (!code)
|
|
126
|
+
throw falha("O retorno do login veio sem código.");
|
|
127
|
+
return code;
|
|
128
|
+
}
|
|
129
|
+
async function pedirToken(tokenEndpoint, campos, f, agora) {
|
|
130
|
+
const { status, corpo } = await lerJson(f, tokenEndpoint, {
|
|
131
|
+
method: "POST",
|
|
132
|
+
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
133
|
+
body: new URLSearchParams(campos).toString(),
|
|
134
|
+
});
|
|
135
|
+
if (status !== 200 || typeof corpo?.access_token !== "string") {
|
|
136
|
+
const motivo = typeof corpo?.error_description === "string" ? corpo.error_description : typeof corpo?.error === "string" ? corpo.error : `HTTP ${status}`;
|
|
137
|
+
throw new ErroDaCli(`O servidor de login não entregou o token (${motivo}).`, SAIDA.erro, { code: typeof corpo?.error === "string" ? corpo.error : "token", status });
|
|
138
|
+
}
|
|
139
|
+
const segundos = typeof corpo.expires_in === "number" ? corpo.expires_in : 3600;
|
|
140
|
+
return { accessToken: corpo.access_token, refreshToken: typeof corpo.refresh_token === "string" ? corpo.refresh_token : null, expiraEm: agora().getTime() + segundos * 1000 };
|
|
141
|
+
}
|
|
142
|
+
export function trocarCodigo(p, f, agora) {
|
|
143
|
+
return pedirToken(p.tokenEndpoint, { grant_type: "authorization_code", code: p.code, redirect_uri: p.redirectUri, client_id: p.clientId, code_verifier: p.verifier, resource: p.recurso }, f, agora);
|
|
144
|
+
}
|
|
145
|
+
export function renovarToken(p, f, agora) {
|
|
146
|
+
return pedirToken(p.tokenEndpoint, { grant_type: "refresh_token", refresh_token: p.refreshToken, client_id: p.clientId, resource: p.recurso }, f, agora);
|
|
147
|
+
}
|
|
148
|
+
/** Folga antes de vencer: renovar um minuto antes evita o 401 no meio de um comando. */
|
|
149
|
+
export const FOLGA_MS = 60_000;
|
|
150
|
+
export const venceLogo = (expiraEm, agora) => expiraEm - FOLGA_MS <= agora.getTime();
|
package/dist/ponte.js
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { createInterface } from "node:readline";
|
|
2
|
+
import { postar } from "./cliente.js";
|
|
3
|
+
import { ErroDaCli } from "./erros.js";
|
|
4
|
+
const ehPedido = (m) => typeof m.method === "string" && m.id !== undefined && m.id !== null;
|
|
5
|
+
export function erroRpc(id, mensagem, code = -32000) {
|
|
6
|
+
return { jsonrpc: "2.0", id: id ?? null, error: { code, message: mensagem } };
|
|
7
|
+
}
|
|
8
|
+
export async function ponte(con, { entrada, saida, erros }) {
|
|
9
|
+
const cabecalhos = {};
|
|
10
|
+
const escrever = (m) => saida.write(`${JSON.stringify(m)}\n`);
|
|
11
|
+
const pendentes = new Set();
|
|
12
|
+
const encaminhar = async (linha) => {
|
|
13
|
+
let mensagem;
|
|
14
|
+
try {
|
|
15
|
+
mensagem = JSON.parse(linha);
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
escrever(erroRpc(null, "JSON inválido na entrada.", -32700));
|
|
19
|
+
return;
|
|
20
|
+
}
|
|
21
|
+
const lista = Array.isArray(mensagem) ? mensagem : [mensagem];
|
|
22
|
+
try {
|
|
23
|
+
const resposta = await postar(con, mensagem, cabecalhos);
|
|
24
|
+
const sessao = resposta.cabecalhos.get("mcp-session-id");
|
|
25
|
+
if (sessao)
|
|
26
|
+
cabecalhos["mcp-session-id"] = sessao;
|
|
27
|
+
for (const m of resposta.mensagens) {
|
|
28
|
+
const versao = m.result?.protocolVersion;
|
|
29
|
+
if (typeof versao === "string")
|
|
30
|
+
cabecalhos["mcp-protocol-version"] = versao;
|
|
31
|
+
escrever(m);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
catch (e) {
|
|
35
|
+
const texto = e instanceof ErroDaCli ? e.message : e.message;
|
|
36
|
+
erros.write(`kleos mcp: ${texto}\n`);
|
|
37
|
+
// Todo pedido precisa de resposta, ou o cliente fica esperando para sempre.
|
|
38
|
+
for (const m of lista.filter(ehPedido))
|
|
39
|
+
escrever(erroRpc(m.id, texto));
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
const linhas = createInterface({ input: entrada, crlfDelay: Infinity });
|
|
43
|
+
for await (const bruta of linhas) {
|
|
44
|
+
const linha = bruta.trim();
|
|
45
|
+
if (!linha)
|
|
46
|
+
continue;
|
|
47
|
+
const p = encaminhar(linha).finally(() => pendentes.delete(p));
|
|
48
|
+
pendentes.add(p);
|
|
49
|
+
}
|
|
50
|
+
await Promise.all(pendentes);
|
|
51
|
+
}
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
import { parseArgs } from "node:util";
|
|
2
|
+
import { VERSAO } from "./cliente.js";
|
|
3
|
+
import { COMANDOS } from "./comandos.js";
|
|
4
|
+
import { lerConfig, resolverCredenciais } from "./config.js";
|
|
5
|
+
import { ErroDaCli, SAIDA, usoErrado } from "./erros.js";
|
|
6
|
+
import { conexaoDe } from "./sessao.js";
|
|
7
|
+
/**
|
|
8
|
+
* A entrada da CLI, sem `process`: recebe os argumentos e as dependências e
|
|
9
|
+
* devolve o código de saída. O `cli.ts` só liga isto ao processo; os testes
|
|
10
|
+
* chamam direto, com `fetch` falso.
|
|
11
|
+
*/
|
|
12
|
+
const GLOBAIS = {
|
|
13
|
+
json: { type: "boolean", descricao: "Saída em JSON (padrão quando o stdout não é terminal)." },
|
|
14
|
+
url: { type: "string", descricao: "Endereço do MCP (padrão: KLEOS_MCP_URL, o arquivo, ou https://mcp.zurc.app/mcp)." },
|
|
15
|
+
help: { type: "boolean", short: "h", descricao: "Esta ajuda." },
|
|
16
|
+
version: { type: "boolean", short: "v", descricao: "A versão da CLI." },
|
|
17
|
+
};
|
|
18
|
+
const paraParse = (o) => Object.fromEntries(Object.entries(o).map(([k, v]) => [k, { type: v.type, ...(v.multiple ? { multiple: true } : {}), ...(v.short ? { short: v.short } : {}) }]));
|
|
19
|
+
/** A união de todas as opções: para o primeiro passe saber quais flags levam valor. */
|
|
20
|
+
function todasAsOpcoes() {
|
|
21
|
+
const uniao = paraParse(GLOBAIS);
|
|
22
|
+
for (const c of COMANDOS) {
|
|
23
|
+
for (const [k, v] of Object.entries(paraParse(c.opcoes ?? {}))) {
|
|
24
|
+
const atual = uniao[k];
|
|
25
|
+
if (!atual) {
|
|
26
|
+
uniao[k] = { ...v };
|
|
27
|
+
continue;
|
|
28
|
+
}
|
|
29
|
+
// Mesmo nome em dois comandos: string ganha (engole o valor), e repetir vale se algum repete.
|
|
30
|
+
const junto = { type: atual.type === "string" || v.type === "string" ? "string" : "boolean" };
|
|
31
|
+
if (atual.multiple || v.multiple)
|
|
32
|
+
junto.multiple = true;
|
|
33
|
+
const atalho = atual.short ?? v.short;
|
|
34
|
+
if (atalho && (!atual.short || !v.short || atual.short === v.short))
|
|
35
|
+
junto.short = atalho;
|
|
36
|
+
uniao[k] = junto;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
// Atalhos repetidos entre opções diferentes confundiriam o primeiro passe.
|
|
40
|
+
const vistos = new Map();
|
|
41
|
+
for (const [k, v] of Object.entries(uniao)) {
|
|
42
|
+
if (!v.short)
|
|
43
|
+
continue;
|
|
44
|
+
if (vistos.has(v.short) && vistos.get(v.short) !== k)
|
|
45
|
+
delete uniao[k].short;
|
|
46
|
+
else
|
|
47
|
+
vistos.set(v.short, k);
|
|
48
|
+
}
|
|
49
|
+
return uniao;
|
|
50
|
+
}
|
|
51
|
+
/** O comando é o prefixo mais longo dos posicionais que casa com um caminho. */
|
|
52
|
+
export function acharComando(posicionais) {
|
|
53
|
+
let melhor = null;
|
|
54
|
+
for (const c of COMANDOS) {
|
|
55
|
+
if (c.caminho.every((p, i) => posicionais[i] === p) && (!melhor || c.caminho.length > melhor.caminho.length))
|
|
56
|
+
melhor = c;
|
|
57
|
+
}
|
|
58
|
+
return { comando: melhor, resto: melhor ? posicionais.slice(melhor.caminho.length) : posicionais };
|
|
59
|
+
}
|
|
60
|
+
const opcaoNaAjuda = (nome, o) => ` ${o.short ? `-${o.short}, ` : " "}--${nome}${o.type === "string" ? " <valor>" : ""}${o.multiple ? " (repete)" : ""}\n ${o.descricao}`;
|
|
61
|
+
export function ajudaGeral() {
|
|
62
|
+
const largura = Math.max(...COMANDOS.map((c) => c.caminho.join(" ").length));
|
|
63
|
+
return [
|
|
64
|
+
`kleos ${VERSAO} — o Kleos pelo terminal e por qualquer agente de IA (cliente do MCP).`,
|
|
65
|
+
"",
|
|
66
|
+
"Uso: kleos <comando> [opções]",
|
|
67
|
+
"",
|
|
68
|
+
"Comandos:",
|
|
69
|
+
...COMANDOS.map((c) => ` ${c.caminho.join(" ").padEnd(largura)} ${c.resumo}`),
|
|
70
|
+
"",
|
|
71
|
+
"Opções de todo comando:",
|
|
72
|
+
...Object.entries(GLOBAIS).map(([k, o]) => opcaoNaAjuda(k, o)),
|
|
73
|
+
"",
|
|
74
|
+
"Entrar: `kleos login` (navegador, sem chave), ou KLEOS_API_KEY / `kleos login --key` para rodar sem gente. Endereço: KLEOS_MCP_URL.",
|
|
75
|
+
"Saída: 0 ok · 1 erro · 2 uso errado · 3 limite/cota · 4 falta aprovação, escopo ou camada.",
|
|
76
|
+
"",
|
|
77
|
+
"Exemplos:",
|
|
78
|
+
" kleos login",
|
|
79
|
+
" kleos login --key kleos_sk_…",
|
|
80
|
+
" kleos projects list",
|
|
81
|
+
" kleos posts generate --project habi --agent bia --count 10 --dry-run",
|
|
82
|
+
" kleos posts list --project habi --status pronto --unscheduled",
|
|
83
|
+
" kleos week plan --project habi --days 7 --per-day 2 --yes",
|
|
84
|
+
"",
|
|
85
|
+
"Ajuda de um comando: kleos <comando> --help. Docs: https://ugc.zurc.app/docs/agentes",
|
|
86
|
+
].join("\n");
|
|
87
|
+
}
|
|
88
|
+
export function ajudaDoComando(c) {
|
|
89
|
+
const opcoes = Object.entries(c.opcoes ?? {});
|
|
90
|
+
return [
|
|
91
|
+
`kleos ${c.caminho.join(" ")} — ${c.resumo}`,
|
|
92
|
+
"",
|
|
93
|
+
`Uso: ${c.uso}`,
|
|
94
|
+
...(opcoes.length ? ["", "Opções:", ...opcoes.map(([k, o]) => opcaoNaAjuda(k, o))] : []),
|
|
95
|
+
"",
|
|
96
|
+
"Opções de todo comando: --json, --url <mcp>, --help",
|
|
97
|
+
"",
|
|
98
|
+
"Exemplos:",
|
|
99
|
+
...c.exemplos.map((e) => ` ${e}`),
|
|
100
|
+
].join("\n");
|
|
101
|
+
}
|
|
102
|
+
const escrever = (deps, fluxo, texto) => deps[fluxo].write(texto.endsWith("\n") ? texto : `${texto}\n`);
|
|
103
|
+
export async function principal(argv, deps, stdoutTTY) {
|
|
104
|
+
let json = !stdoutTTY || argv.includes("--json");
|
|
105
|
+
try {
|
|
106
|
+
// 1º passe: só para separar o comando das flags.
|
|
107
|
+
let solto;
|
|
108
|
+
try {
|
|
109
|
+
solto = parseArgs({ args: argv, options: todasAsOpcoes(), allowPositionals: true, strict: false });
|
|
110
|
+
}
|
|
111
|
+
catch (e) {
|
|
112
|
+
throw usoErrado(e.message);
|
|
113
|
+
}
|
|
114
|
+
const { comando, resto } = acharComando(solto.positionals);
|
|
115
|
+
if (solto.values.version) {
|
|
116
|
+
escrever(deps, "stdout", json ? JSON.stringify({ version: VERSAO }) : VERSAO);
|
|
117
|
+
return SAIDA.ok;
|
|
118
|
+
}
|
|
119
|
+
if (!comando) {
|
|
120
|
+
if (solto.positionals.length === 0 || solto.positionals[0] === "help") {
|
|
121
|
+
const alvo = solto.positionals[0] === "help" ? acharComando(solto.positionals.slice(1)).comando : null;
|
|
122
|
+
escrever(deps, "stdout", alvo ? ajudaDoComando(alvo) : ajudaGeral());
|
|
123
|
+
return solto.positionals.length === 0 && !solto.values.help ? SAIDA.uso : SAIDA.ok;
|
|
124
|
+
}
|
|
125
|
+
throw usoErrado(`Comando desconhecido: ${solto.positionals.join(" ")}. Veja kleos --help.`);
|
|
126
|
+
}
|
|
127
|
+
if (solto.values.help) {
|
|
128
|
+
escrever(deps, "stdout", ajudaDoComando(comando));
|
|
129
|
+
return SAIDA.ok;
|
|
130
|
+
}
|
|
131
|
+
// 2º passe, estrito: flag que o comando não conhece é uso errado.
|
|
132
|
+
let valores;
|
|
133
|
+
try {
|
|
134
|
+
const estrito = parseArgs({
|
|
135
|
+
args: argv,
|
|
136
|
+
options: { ...paraParse(GLOBAIS), ...paraParse(comando.opcoes ?? {}) },
|
|
137
|
+
allowPositionals: true,
|
|
138
|
+
strict: true,
|
|
139
|
+
});
|
|
140
|
+
valores = estrito.values;
|
|
141
|
+
}
|
|
142
|
+
catch (e) {
|
|
143
|
+
throw usoErrado(`${e.message.split("\n")[0]} Veja kleos ${comando.caminho.join(" ")} --help.`);
|
|
144
|
+
}
|
|
145
|
+
json = !stdoutTTY || valores.json === true;
|
|
146
|
+
const faixa = comando.posicionais ?? { min: 0, max: 0 };
|
|
147
|
+
if (resto.length < faixa.min || resto.length > faixa.max)
|
|
148
|
+
throw usoErrado(`Uso: ${comando.uso}`);
|
|
149
|
+
const arquivo = await lerConfig({ env: deps.env, home: deps.home });
|
|
150
|
+
const cred = resolverCredenciais(deps.env, arquivo, { url: typeof valores.url === "string" ? valores.url : undefined });
|
|
151
|
+
const dados = await comando.executar({
|
|
152
|
+
valores,
|
|
153
|
+
posicionais: resto,
|
|
154
|
+
// O login não precisa de credencial (é ele que cria); os outros renovam o token OAuth antes, se preciso.
|
|
155
|
+
con: comando.caminho[0] === "login" ? { mcpUrl: cred.mcpUrl, apiKey: cred.apiKey, fetch: deps.fetch } : await conexaoDe(cred, deps),
|
|
156
|
+
deps,
|
|
157
|
+
json,
|
|
158
|
+
avisar: (t) => escrever(deps, "stderr", t),
|
|
159
|
+
});
|
|
160
|
+
if (dados === undefined)
|
|
161
|
+
return SAIDA.ok;
|
|
162
|
+
const obj = (dados ?? {});
|
|
163
|
+
escrever(deps, "stdout", json || !comando.humano ? JSON.stringify(obj, null, 2) : comando.humano(obj));
|
|
164
|
+
return SAIDA.ok;
|
|
165
|
+
}
|
|
166
|
+
catch (e) {
|
|
167
|
+
const erro = e instanceof ErroDaCli ? e : new ErroDaCli(e?.message ?? String(e), SAIDA.erro);
|
|
168
|
+
if (json)
|
|
169
|
+
escrever(deps, "stderr", JSON.stringify({ error: erro.message, exit_code: erro.saida, ...(erro.dados ? { details: erro.dados } : {}) }));
|
|
170
|
+
else
|
|
171
|
+
escrever(deps, "stderr", `kleos: ${erro.message}`);
|
|
172
|
+
return erro.saida;
|
|
173
|
+
}
|
|
174
|
+
}
|
package/dist/saida.js
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A saída para gente (TTY sem `--json`). Para máquina, a CLI imprime o JSON
|
|
3
|
+
* da ferramenta como veio; aqui só o resumo legível. Número que não existe é
|
|
4
|
+
* "—", nunca zero.
|
|
5
|
+
*/
|
|
6
|
+
export const traco = (v) => (v === null || v === undefined || v === "" ? "—" : String(v));
|
|
7
|
+
export function tabela(cabecalho, linhas) {
|
|
8
|
+
const todas = [cabecalho, ...linhas.map((l) => l.map(traco))];
|
|
9
|
+
const larguras = cabecalho.map((_, i) => Math.max(...todas.map((l) => (l[i] ?? "").length)));
|
|
10
|
+
return todas.map((l) => l.map((c, i) => (i === l.length - 1 ? c : c.padEnd(larguras[i] ?? 0))).join(" ").trimEnd()).join("\n");
|
|
11
|
+
}
|
|
12
|
+
const arr = (v) => (Array.isArray(v) ? v : []);
|
|
13
|
+
const obj = (v) => (v && typeof v === "object" ? v : {});
|
|
14
|
+
export function humanoWhoami(d) {
|
|
15
|
+
const org = obj(d.organization);
|
|
16
|
+
const plano = obj(d.plan);
|
|
17
|
+
const chave = obj(d.api_key);
|
|
18
|
+
const camadas = Object.entries(obj(d.layers))
|
|
19
|
+
.filter(([, v]) => v === true)
|
|
20
|
+
.map(([k]) => k);
|
|
21
|
+
return [
|
|
22
|
+
`Organização: ${traco(org.name)} (${traco(org.id)})`,
|
|
23
|
+
`Plano: ${traco(plano.label)} · ${traco(plano.status)}${plano.note ? ` — ${String(plano.note)}` : ""}`,
|
|
24
|
+
`${d.auth === "oauth" ? "Login: " : "Chave: "} ${traco(chave.name)} · escopos ${arr(chave.scopes).join(", ") || "—"}${chave.project_id ? ` · projeto ${String(chave.project_id)}` : " · organização inteira"}`,
|
|
25
|
+
`Camadas: ${camadas.join(", ") || "—"}`,
|
|
26
|
+
`App: ${traco(d.url)}`,
|
|
27
|
+
].join("\n");
|
|
28
|
+
}
|
|
29
|
+
export function humanoUso(d) {
|
|
30
|
+
const linhas = arr(d.levers).map((l) => [l.label ?? l.lever, l.period, `${traco(l.used)} / ${traco(l.limit)}`, l.remaining, l.renews_at ? String(l.renews_at).slice(0, 16).replace("T", " ") : null]);
|
|
31
|
+
return `${tabela(["alavanca", "período", "usado / teto", "sobra", "renova"], linhas)}\n\nPlano: ${traco(d.plan)} · ${traco(d.status)} · ${traco(d.url)}`;
|
|
32
|
+
}
|
|
33
|
+
export const humanoProjetos = (d) => arr(d.projects).length ? tabela(["slug", "nome", "estado", "id"], arr(d.projects).map((p) => [p.slug, p.name, p.status, p.id])) : "Nenhum projeto que esta chave enxergue.";
|
|
34
|
+
export const humanoAgentes = (d) => arr(d.agents).length
|
|
35
|
+
? tabela(["slug", "nome", "estado", "aprovações", "contas"], arr(d.agents).map((a) => [a.slug, a.name, a.status, a.pending_approvals, arr(a.accounts).map((c) => `${String(c.network)}:${traco(c.username)}`).join(", ")]))
|
|
36
|
+
: "Nenhum agente neste projeto.";
|
|
37
|
+
export const humanoPosts = (d) => arr(d.posts).length
|
|
38
|
+
? `${tabela(["id", "estado", "quando", "agente", "título"], arr(d.posts).map((p) => [p.id, p.status, p.scheduled_for, obj(p.agent).slug, p.title]))}${d.truncated ? "\n(lista cortada: estreite o período)" : ""}`
|
|
39
|
+
: "Nenhum post neste recorte.";
|
|
40
|
+
export function humanoPost(d) {
|
|
41
|
+
const slides = arr(d.slides).map((s, i) => ` ${i + 1}. ${traco(s.text)}`);
|
|
42
|
+
const pubs = arr(d.publications).map((p) => ` ${String(p.id)} · ${String(p.state)} · ${traco(p.scheduled_for)}`);
|
|
43
|
+
return [
|
|
44
|
+
`${traco(d.title)} [${traco(d.status)}] · ${traco(d.format)}`,
|
|
45
|
+
`Quando: ${traco(d.scheduled_for)} · Agente: ${traco(obj(d.agent).slug)}`,
|
|
46
|
+
slides.length ? `Slides:\n${slides.join("\n")}` : null,
|
|
47
|
+
d.caption ? `Legenda: ${String(d.caption)}` : null,
|
|
48
|
+
`Ações: ${arr(d.actions).join(", ") || "—"}`,
|
|
49
|
+
pubs.length ? `Publicações:\n${pubs.join("\n")}` : null,
|
|
50
|
+
`Abrir: ${traco(d.url)}`,
|
|
51
|
+
]
|
|
52
|
+
.filter(Boolean)
|
|
53
|
+
.join("\n");
|
|
54
|
+
}
|
|
55
|
+
export function humanoGerados(d) {
|
|
56
|
+
const posts = arr(d.posts);
|
|
57
|
+
const est = obj(d.estimate);
|
|
58
|
+
const cabeca = d.status === "dry_run" ? "Estimativa (nada foi gasto):" : `${posts.length} post(s) ${d.status === "partial" ? "(parcial)" : "na fila"}:`;
|
|
59
|
+
const estimativa = Object.keys(est).length ? `\n${JSON.stringify(est, null, 2)}` : "";
|
|
60
|
+
const lista = posts.map((p) => ` ${String(p.id)} · ${String(p.status)} · ${traco(p.scheduled_for)}`).join("\n");
|
|
61
|
+
return `${cabeca}${estimativa}${lista ? `\n${lista}` : ""}${d.error ? `\nAviso: ${String(d.error)}` : ""}\nAcompanhe: ${traco(d.url)}`;
|
|
62
|
+
}
|
|
63
|
+
export function humanoSemana(d) {
|
|
64
|
+
if (d.status === "dry_run")
|
|
65
|
+
return `Estimativa (nada foi gasto): ${traco(obj(d.estimate).posts)} posts; sobram ${traco(obj(d.estimate).posts_remaining)} no plano.\n${traco(d.url)}`;
|
|
66
|
+
return `Planejados ${traco(d.planned)} · já existiam ${traco(d.existing)} · faltaram ${traco(d.left)} · falharam ${traco(d.failed)}${d.message ? `\n${String(d.message)}` : ""}\nAcompanhe: ${traco(d.url)}`;
|
|
67
|
+
}
|
|
68
|
+
export function humanoMetricas(d) {
|
|
69
|
+
const totais = Object.entries(obj(d.totals)).map(([k, v]) => ` ${k}: ${traco(v)}`);
|
|
70
|
+
const top = arr(d.top_posts).map((p, i) => ` ${i + 1}. ${traco(p.network)} ${traco(p.username)} · ${traco(p.platform_url)}`);
|
|
71
|
+
return [`${String(d.from).slice(0, 10)} → ${String(d.to).slice(0, 10)} (sincronizado ${traco(d.last_synced_at)})`, "Totais:", ...(totais.length ? totais : [" —"]), top.length ? `Top posts:\n${top.join("\n")}` : null, traco(d.url)]
|
|
72
|
+
.filter(Boolean)
|
|
73
|
+
.join("\n");
|
|
74
|
+
}
|
|
75
|
+
export const humanoTrabalho = (d) => `${traco(d.kind)} ${traco(d.id)}: ${traco(d.status)}${d.progress ? ` (${traco(obj(d.progress).step)}/${traco(obj(d.progress).of)} ${traco(obj(d.progress).label)})` : ""}${d.error ? `\nErro: ${String(d.error)}` : ""}`;
|
package/dist/sessao.js
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { gravarConfig, lerConfig } from "./config.js";
|
|
2
|
+
import { renovarToken, venceLogo } from "./oauth.js";
|
|
3
|
+
export async function conexaoDe(cred, deps) {
|
|
4
|
+
if (!cred.oauth)
|
|
5
|
+
return { mcpUrl: cred.mcpUrl, apiKey: cred.apiKey, fetch: deps.fetch };
|
|
6
|
+
const amb = { env: deps.env, home: deps.home };
|
|
7
|
+
let sessao = cred.oauth;
|
|
8
|
+
const renovar = async () => {
|
|
9
|
+
if (!sessao.refreshToken)
|
|
10
|
+
return null;
|
|
11
|
+
const t = await renovarToken({ tokenEndpoint: sessao.tokenEndpoint, clientId: sessao.clientId, refreshToken: sessao.refreshToken, recurso: sessao.resource }, deps.fetch, deps.agora);
|
|
12
|
+
sessao = { ...sessao, accessToken: t.accessToken, refreshToken: t.refreshToken ?? sessao.refreshToken, expiresAt: t.expiraEm };
|
|
13
|
+
const arquivo = await lerConfig(amb);
|
|
14
|
+
await gravarConfig(amb, { ...arquivo, oauth: sessao });
|
|
15
|
+
return sessao.accessToken;
|
|
16
|
+
};
|
|
17
|
+
if (venceLogo(sessao.expiresAt, deps.agora())) {
|
|
18
|
+
// Falhar aqui não é o fim: o servidor dá o 401 com a frase certa ("rode kleos login").
|
|
19
|
+
await renovar().catch(() => null);
|
|
20
|
+
}
|
|
21
|
+
return { mcpUrl: cred.mcpUrl, apiKey: sessao.accessToken, fetch: deps.fetch, renovar };
|
|
22
|
+
}
|
package/dist/skill.js
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { cp, stat } from "node:fs/promises";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
/** O nome da pasta da skill em `packages/skills`. */
|
|
4
|
+
export const NOME_DA_SKILL = { cli: "kleos-cli", mcp: "kleos" };
|
|
5
|
+
export const AGENTES = [
|
|
6
|
+
{ nome: "Claude Code", pasta: ".claude" },
|
|
7
|
+
{ nome: "Codex", pasta: ".codex" },
|
|
8
|
+
{ nome: "Hermes", pasta: ".hermes" },
|
|
9
|
+
{ nome: "OpenClaw", pasta: ".openclaw" },
|
|
10
|
+
];
|
|
11
|
+
const existe = async (caminho) => {
|
|
12
|
+
try {
|
|
13
|
+
return (await stat(caminho)).isDirectory();
|
|
14
|
+
}
|
|
15
|
+
catch {
|
|
16
|
+
return false;
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
/** As pastas `skills` dos agentes instalados (a pasta do agente existe na home). */
|
|
20
|
+
export async function destinosEncontrados(home) {
|
|
21
|
+
const achados = [];
|
|
22
|
+
for (const a of AGENTES) {
|
|
23
|
+
if (await existe(join(home, a.pasta)))
|
|
24
|
+
achados.push({ agente: a.nome, pasta: join(home, a.pasta, "skills") });
|
|
25
|
+
}
|
|
26
|
+
return achados;
|
|
27
|
+
}
|
|
28
|
+
export async function instalarSkill(origemDasSkills, variante, destinos) {
|
|
29
|
+
const nome = NOME_DA_SKILL[variante];
|
|
30
|
+
const origem = join(origemDasSkills, nome);
|
|
31
|
+
if (!(await existe(origem)))
|
|
32
|
+
throw new Error(`A skill ${nome} não veio no pacote (${origem}).`);
|
|
33
|
+
const feitos = [];
|
|
34
|
+
for (const d of destinos) {
|
|
35
|
+
const caminho = join(d.pasta, nome);
|
|
36
|
+
await cp(origem, caminho, { recursive: true, force: true });
|
|
37
|
+
feitos.push({ agente: d.agente, caminho });
|
|
38
|
+
}
|
|
39
|
+
return feitos;
|
|
40
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "kleos-cli",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"mcpName": "app.zurc/kleos",
|
|
5
|
+
"description": "CLI do Kleos: gere, agende e meça posts UGC do seu app pelo terminal ou por qualquer agente de IA. Cliente do MCP em https://mcp.zurc.app/mcp.",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"bin": {
|
|
8
|
+
"kleos": "dist/cli.js"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"dist",
|
|
12
|
+
"skills",
|
|
13
|
+
"README.md"
|
|
14
|
+
],
|
|
15
|
+
"engines": {
|
|
16
|
+
"node": ">=22"
|
|
17
|
+
},
|
|
18
|
+
"scripts": {
|
|
19
|
+
"build": "tsc -p tsconfig.json && node scripts/copiar-skills.mjs",
|
|
20
|
+
"test": "vitest run",
|
|
21
|
+
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
22
|
+
"prepack": "npm run build"
|
|
23
|
+
},
|
|
24
|
+
"keywords": [
|
|
25
|
+
"kleos",
|
|
26
|
+
"mcp",
|
|
27
|
+
"ugc",
|
|
28
|
+
"tiktok",
|
|
29
|
+
"instagram",
|
|
30
|
+
"cli",
|
|
31
|
+
"agent"
|
|
32
|
+
],
|
|
33
|
+
"homepage": "https://ugc.zurc.app/docs/agentes",
|
|
34
|
+
"license": "UNLICENSED",
|
|
35
|
+
"devDependencies": {
|
|
36
|
+
"@types/node": "^22.0.0",
|
|
37
|
+
"typescript": "^5.9.0",
|
|
38
|
+
"vitest": "^5.0.0"
|
|
39
|
+
}
|
|
40
|
+
}
|