api-cli/bin/aio.js

1225 lines
57 KiB
JavaScript
Executable file

#!/usr/bin/env node
/*
* aio: the All in One AI command line (public API https://api.mozout.com/v1 and /mcp).
* One single file, no dependencies, Node.js 18 or newer (built-in fetch).
* The BUILD block is set by scripts/build.js. Do not edit the copies in dist/ by hand.
*/
'use strict';
/* aio-build:start */
const BUILD = {
"base": "https://api.mozout.com",
"brand": "MozOut",
"docs": "https://docs.mozout.com",
"mcpName": "mozout-ai"
};
/* aio-build:end */
const VERSION = '1.0.1';
const PRODUCT = 'All in One AI';
/* Default models (the same as the MCP server). Change them with --model or with the AIO_MODEL and AIO_<TYPE>_MODEL variables. */
const DEFAULT_MODELS = {
chat: 'moonshotai/kimi-k2.7-code',
image: 'openai/gpt-image-2.5-sunburst/text-to-image',
video: 'ltx-2.3-quality/text-to-video',
audio: 'alibaba/qwen-audio-3.0-tts-flash/text-to-speech'
};
const NODE_MAJOR = parseInt(String(process.versions.node).split('.')[0], 10);
if (!(NODE_MAJOR >= 18)) {
const pt0 = /^pt/i.test(process.env.AIO_LANG || process.env.LC_ALL || process.env.LC_MESSAGES || process.env.LANG || '');
process.stderr.write(pt0
? 'Erro: o aio precisa do Node.js 18 ou mais recente (este é o ' + process.version + ').\n'
: 'Error: aio needs Node.js 18 or later (this is ' + process.version + ').\n');
process.exit(1);
}
const fs = require('fs');
const os = require('os');
const path = require('path');
const readline = require('readline');
const { spawn } = require('child_process');
const { Readable } = require('stream');
const { pipeline } = require('stream/promises');
/* ===================== language ===================== */
function detectLang() {
const v = process.env.AIO_LANG || process.env.LC_ALL || process.env.LC_MESSAGES || process.env.LANG || '';
if (v) { return /^pt/i.test(v) ? 'pt' : 'en'; }
try { return /^pt/i.test(Intl.DateTimeFormat().resolvedOptions().locale) ? 'pt' : 'en'; } catch (e) { return 'en'; }
}
const LANG = detectLang();
const PT = LANG === 'pt';
const M = {
pt: {
error: 'Erro',
request_id: 'id do pedido',
unknown_command: 'comando desconhecido: %s. Veja «aio help».',
unknown_option: 'opção desconhecida: %s',
missing_value: 'falta o valor de %s',
bad_int: '%s tem de ser um número inteiro maior que 0',
bad_type: '--type aceita text, image, video, audio ou agent',
bad_opt: '--opt tem de ser chave=valor (recebido: %s)',
bad_base: 'o endereço da API não é válido: %s',
no_key: 'não há chave de API. Corra «aio auth login» ou defina a variável AIO_API_KEY.',
bad_key_format: 'a chave tem de começar por prod_ ou sandbox_.',
key_invalid: 'chave inválida: a API não a aceita (pode ter sido apagada ou ter expirado). Crie ou copie uma chave no API Center. (%s)',
key_forbidden: 'a chave existe, mas a API recusou o acesso (%s).',
missing_perms: 'Esta chave não tem as permissões de que o aio precisa: %s. Acrescente-as à chave no API Center.',
st_perms: 'Permissões',
perms_none: '(nenhuma)',
ask_key: 'Chave de API (prod_... ou sandbox_...): ',
empty_key: 'não escreveu nenhuma chave.',
logged_in: 'Sessão iniciada com a chave %s (%s).',
saved_in: 'Chave guardada em %s (só o seu utilizador a pode ler).',
from_env: 'A chave veio da variável AIO_API_KEY, que tem prioridade sobre a guardada.',
logged_out: 'Chave apagada de %s.',
nothing_saved: 'Não havia nenhuma chave guardada.',
env_still: 'A variável AIO_API_KEY continua definida neste terminal.',
st_key: 'Chave',
st_source: 'Origem',
st_src_env: 'variável AIO_API_KEY',
st_src_file: 'ficheiro %s',
st_mode: 'Modo',
st_api: 'API',
st_valid: 'Estado',
st_ok: 'válida',
sandbox: 'sandbox (testes sem custos)',
prod: 'produção',
credits: 'Créditos',
plan: 'Plano',
plan_week: 'Restante na semana',
plan_month: 'Restante no mês',
plan_week_reset: 'A semana reinicia',
plan_month_reset: 'O mês reinicia',
plan_fallback: 'Usar créditos quando o plano acabar',
yes: 'sim', no: 'não',
points: 'pontos',
col_id: 'MODELO', col_type: 'TIPO', col_name: 'NOME', col_price: 'PREÇO (créditos)',
per_1m: 'entrada %s / saída %s por 1M tokens',
per_unit: '%s por %s',
units: { image: 'imagem', second: 'segundo', generation: 'geração', '1M tokens': '1M tokens' },
n_models: '%s modelo(s).',
no_models: 'Nenhum modelo encontrado.',
m_name: 'Nome', m_type: 'Tipo', m_category: 'Categoria', m_desc: 'Descrição', m_price: 'Preço', m_context: 'Contexto', m_max_out: 'Saída máxima', m_base: 'Modelo base', m_status: 'Estado', m_tools: 'Ferramentas',
m_inputs: 'Campos de entrada (use --opt nome=valor no aio generate):',
f_required: 'obrigatório', f_default: 'omissão', f_options: 'opções', f_range: 'entre %s e %s',
tokens: 'tokens',
chat_hello: '%s, modelo %s. Escreva e carregue Enter. /reset limpa a conversa, /exit ou Ctrl+C sai.',
chat_reset: 'Conversa limpa.',
chat_usage: '[%s: %s tokens de entrada, %s de saída]',
need_prompt: 'falta o pedido entre aspas. Exemplo: aio %s "%s"',
gen_kind: 'o tipo tem de ser image, video ou audio. Exemplo: aio generate image "um gato"',
gen_wrong_type: 'o modelo %s é de %s, não de %s. Veja «aio models --type %s».',
gen_submitted: 'Pedido enviado: %s (reservados %s créditos).',
gen_waiting: 'A gerar',
gen_check: 'Para consultar: aio status %s --download',
gen_timeout: 'ainda não terminou ao fim de %s s. Consulte mais tarde com: aio status %s --download',
gen_failed: 'a geração falhou: %s',
gen_done: 'Pronto.',
gen_cost: 'Custo: %s créditos.',
gen_saved: 'Guardado: %s',
gen_outputs: 'Ficheiros:',
st_status: 'Estado', st_model: 'Modelo', st_cost: 'Custo',
status_names: { processing: 'a processar', completed: 'concluída', failed: 'falhou' },
dl_failed: 'não foi possível descarregar %s (HTTP %s).',
dl_bad_url: 'endereço de ficheiro recusado: %s',
mcp_target: 'indique claude, codex ou cursor. Exemplo: aio mcp install claude',
mcp_claude_intro: 'Para juntar o servidor MCP ao Claude Code, corra:',
mcp_codex_intro: 'Junte este bloco ao ~/.codex/config.toml:',
mcp_cursor_intro: 'Junte isto ao ~/.cursor/mcp.json (ou ao .cursor/mcp.json do projecto):',
mcp_env_hint: 'Defina a variável com a sua chave antes de abrir a ferramenta:',
mcp_masked_env: 'A chave aparece escondida; use --show-key para a ver por inteiro.',
need_id: 'falta o id. Exemplo: aio %s',
mcp_masked: 'A chave aparece escondida. Use --show-key para a ver por inteiro, ou --yes para o aio correr o comando por si.',
mcp_ask_run: 'Correr este comando agora? [s/N] ',
mcp_ran: 'O Claude Code juntou o servidor %s.',
mcp_run_fail: 'o comando claude terminou com o código %s.',
mcp_no_claude: 'o comando claude não foi encontrado. Instale o Claude Code e volte a tentar.',
mcp_not_run: 'Nada foi alterado.',
network: 'não foi possível contactar %s (%s).',
timeout: 'a API não respondeu a tempo (%s).',
bad_json: 'a API devolveu uma resposta inesperada (HTTP %s).',
rate_wait: 'Limite de pedidos atingido; a esperar %s s.',
needs: 'precisa de %s créditos e tem %s.',
interrupted: 'Interrompido.'
},
en: {
error: 'Error',
request_id: 'request id',
unknown_command: 'unknown command: %s. See "aio help".',
unknown_option: 'unknown option: %s',
missing_value: 'missing value for %s',
bad_int: '%s must be a whole number greater than 0',
bad_type: '--type accepts text, image, video, audio or agent',
bad_opt: '--opt must be key=value (got: %s)',
bad_base: 'the API address is not valid: %s',
no_key: 'no API key. Run "aio auth login" or set the AIO_API_KEY variable.',
bad_key_format: 'the key must start with prod_ or sandbox_.',
key_invalid: 'invalid key: the API does not accept it (it may have been deleted or expired). Create or copy a key in the API Center. (%s)',
key_forbidden: 'the key exists, but the API refused access (%s).',
missing_perms: 'This key is missing permissions aio needs: %s. Add them to the key in the API Center.',
st_perms: 'Permissions',
perms_none: '(none)',
ask_key: 'API key (prod_... or sandbox_...): ',
empty_key: 'no key was entered.',
logged_in: 'Logged in with key %s (%s).',
saved_in: 'Key saved in %s (readable only by your user).',
from_env: 'The key came from the AIO_API_KEY variable, which takes priority over the saved one.',
logged_out: 'Key deleted from %s.',
nothing_saved: 'There was no saved key.',
env_still: 'The AIO_API_KEY variable is still set in this terminal.',
st_key: 'Key',
st_source: 'Source',
st_src_env: 'AIO_API_KEY variable',
st_src_file: 'file %s',
st_mode: 'Mode',
st_api: 'API',
st_valid: 'Status',
st_ok: 'valid',
sandbox: 'sandbox (free tests)',
prod: 'production',
credits: 'Credits',
plan: 'Plan',
plan_week: 'Left this week',
plan_month: 'Left this month',
plan_week_reset: 'Week resets',
plan_month_reset: 'Month resets',
plan_fallback: 'Use credits when the plan runs out',
yes: 'yes', no: 'no',
points: 'points',
col_id: 'MODEL', col_type: 'TYPE', col_name: 'NAME', col_price: 'PRICE (credits)',
per_1m: 'input %s / output %s per 1M tokens',
per_unit: '%s per %s',
units: { image: 'image', second: 'second', generation: 'generation', '1M tokens': '1M tokens' },
n_models: '%s model(s).',
no_models: 'No models found.',
m_name: 'Name', m_type: 'Type', m_category: 'Category', m_desc: 'Description', m_price: 'Price', m_context: 'Context', m_max_out: 'Max output', m_base: 'Base model', m_status: 'Status', m_tools: 'Tools',
m_inputs: 'Input fields (use --opt name=value with aio generate):',
f_required: 'required', f_default: 'default', f_options: 'options', f_range: 'from %s to %s',
tokens: 'tokens',
chat_hello: '%s, model %s. Type and press Enter. /reset clears the chat, /exit or Ctrl+C quits.',
chat_reset: 'Chat cleared.',
chat_usage: '[%s: %s input tokens, %s output]',
need_prompt: 'the prompt is missing. Example: aio %s "%s"',
gen_kind: 'the type must be image, video or audio. Example: aio generate image "a cat"',
gen_wrong_type: 'the model %s is a %s model, not %s. See "aio models --type %s".',
gen_submitted: 'Request sent: %s (%s credits reserved).',
gen_waiting: 'Generating',
gen_check: 'To check it: aio status %s --download',
gen_timeout: 'not finished after %s s. Check later with: aio status %s --download',
gen_failed: 'the generation failed: %s',
gen_done: 'Done.',
gen_cost: 'Cost: %s credits.',
gen_saved: 'Saved: %s',
gen_outputs: 'Files:',
st_status: 'Status', st_model: 'Model', st_cost: 'Cost',
status_names: { processing: 'processing', completed: 'completed', failed: 'failed' },
dl_failed: 'could not download %s (HTTP %s).',
dl_bad_url: 'file address refused: %s',
mcp_target: 'choose claude, codex or cursor. Example: aio mcp install claude',
mcp_claude_intro: 'To add the MCP server to Claude Code, run:',
mcp_codex_intro: 'Add this block to ~/.codex/config.toml:',
mcp_cursor_intro: 'Add this to ~/.cursor/mcp.json (or the project .cursor/mcp.json):',
mcp_env_hint: 'Set the variable with your key before opening the tool:',
mcp_masked_env: 'The key is hidden; use --show-key to see it in full.',
need_id: 'the id is missing. Example: aio %s',
mcp_masked: 'The key is hidden. Use --show-key to see it in full, or --yes and aio runs the command for you.',
mcp_ask_run: 'Run this command now? [y/N] ',
mcp_ran: 'Claude Code added the %s server.',
mcp_run_fail: 'the claude command exited with code %s.',
mcp_no_claude: 'the claude command was not found. Install Claude Code and try again.',
mcp_not_run: 'Nothing was changed.',
network: 'could not connect to %s (%s).',
timeout: 'the API did not answer in time (%s).',
bad_json: 'the API returned an unexpected response (HTTP %s).',
rate_wait: 'Rate limit reached; waiting %s s.',
needs: 'needs %s credits and has %s.',
interrupted: 'Interrupted.'
}
};
function t(k) {
let s = (M[LANG] && M[LANG][k] !== undefined) ? M[LANG][k] : M.en[k];
if (typeof s !== 'string') { return s; }
const args = Array.prototype.slice.call(arguments, 1);
let i = 0;
return s.replace(/%s/g, () => (i < args.length ? String(args[i++]) : ''));
}
/* ===================== errors and output ===================== */
class AioError extends Error {
constructor(message, opts) {
super(message);
opts = opts || {};
this.exitCode = opts.exitCode || 1;
this.status = opts.status || 0;
this.code = opts.code || '';
this.correlation = opts.correlation || '';
this.details = opts.details || null;
}
}
const usageError = (msg) => new AioError(msg, { exitCode: 2 });
const SECRETS = new Set();
function redact(s) {
s = String(s == null ? '' : s);
for (const k of SECRETS) {
if (k && k.length >= 8) { s = s.split(k).join(maskKey(k)); }
}
return s;
}
function maskKey(k) {
k = String(k || '');
const m = /^(prod_|sandbox_)/.exec(k);
const pre = m ? m[1] : '';
return pre + '...' + k.slice(-4);
}
function keyMode(k) { return /^sandbox_/.test(String(k)) ? 'sandbox' : 'prod'; }
const out = (s) => process.stdout.write(redact(s) + '\n');
const err = (s) => process.stderr.write(redact(s) + '\n');
const isTTY = (s) => !!(s && s.isTTY);
const bold = (s) => (isTTY(process.stdout) && !process.env.NO_COLOR ? '\x1b[1m' + s + '\x1b[0m' : s);
const dim = (s, stream) => (isTTY(stream || process.stdout) && !process.env.NO_COLOR ? '\x1b[2m' + s + '\x1b[0m' : s);
/* ===================== settings and key ===================== */
function configDir() {
if (process.env.AIO_CONFIG_DIR) { return process.env.AIO_CONFIG_DIR; }
if (process.platform === 'win32') { return path.join(process.env.APPDATA || path.join(os.homedir(), 'AppData', 'Roaming'), 'aio'); }
return path.join(process.env.XDG_CONFIG_HOME || path.join(os.homedir(), '.config'), 'aio');
}
const configFile = () => path.join(configDir(), 'config.json');
function readConfig() {
try {
const j = JSON.parse(fs.readFileSync(configFile(), 'utf8'));
return j && typeof j === 'object' ? j : {};
} catch (e) { return {}; }
}
function writeConfig(cfg) {
const dir = configDir();
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
try { fs.chmodSync(dir, 0o700); } catch (e) { /* Windows */ }
const file = configFile();
const tmp = file + '.' + process.pid + '.tmp';
fs.writeFileSync(tmp, JSON.stringify(cfg, null, 2) + '\n', { mode: 0o600 });
try { fs.chmodSync(tmp, 0o600); } catch (e) { /* Windows */ }
fs.renameSync(tmp, file);
try { fs.chmodSync(file, 0o600); } catch (e) { /* Windows */ }
return file;
}
function currentKey() {
const env = (process.env.AIO_API_KEY || '').trim();
if (env) { SECRETS.add(env); return { key: env, source: 'env' }; }
const cfg = readConfig();
const k = typeof cfg.api_key === 'string' ? cfg.api_key.trim() : '';
if (k) { SECRETS.add(k); return { key: k, source: 'file' }; }
return { key: '', source: '' };
}
function requireKey() {
const k = currentKey();
if (!k.key) { throw new AioError(t('no_key')); }
return k.key;
}
function baseUrl() {
const b = String(process.env.AIO_BASE_URL || BUILD.base || '').trim().replace(/\/+$/, '');
if (!/^https?:\/\/[^\s/]+/i.test(b)) { throw new AioError(t('bad_base', b || '(vazio)')); }
return b;
}
/* ===================== HTTP ===================== */
const UA = 'aio/' + VERSION + ' (node ' + process.versions.node + '; ' + process.platform + ')';
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
function encodeId(id) { return String(id).split('/').map(encodeURIComponent).join('/'); }
async function request(method, p, opts) {
opts = opts || {};
const key = opts.key || requireKey();
SECRETS.add(key);
const base = baseUrl();
let url = base + p;
if (opts.query) {
const qs = new URLSearchParams();
for (const [k, v] of Object.entries(opts.query)) { if (v !== undefined && v !== null && v !== '') { qs.set(k, String(v)); } }
const s = qs.toString();
if (s) { url += (url.includes('?') ? '&' : '?') + s; }
}
const headers = {
'Authorization': 'Bearer ' + key,
'Accept': opts.stream ? 'text/event-stream' : 'application/json',
'Accept-Language': LANG,
'User-Agent': UA
};
if (opts.body !== undefined) { headers['Content-Type'] = 'application/json'; }
const timeoutMs = opts.timeoutMs || (parseInt(process.env.AIO_TIMEOUT, 10) > 0 ? parseInt(process.env.AIO_TIMEOUT, 10) * 1000 : 120000);
for (let attempt = 0; ; attempt++) {
const ac = new AbortController();
const timer = opts.stream ? null : setTimeout(() => ac.abort(), timeoutMs);
let res;
try {
res = await fetch(url, { method, headers, body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined, signal: opts.signal || ac.signal, redirect: 'error' });
} catch (e) {
if (timer) { clearTimeout(timer); }
if (opts.signal && opts.signal.aborted) { throw e; }
if (e && e.name === 'AbortError') { throw new AioError(t('timeout', method + ' ' + p)); }
const cause = (e && e.cause && (e.cause.code || e.cause.message)) || (e && e.message) || 'fetch';
throw new AioError(t('network', base, cause));
}
/* 429: waits as long as the API asks (at most 3 times, up to 60 s) and tries again */
if (res.status === 429 && attempt < 3 && opts.retry429 !== false) {
const wait = retryAfter(res);
const body429 = await res.text().catch(() => '');
if (timer) { clearTimeout(timer); }
if (wait > 0 && wait <= 60) {
if (!opts.quiet) { err(dim(t('rate_wait', wait), process.stderr)); }
await sleep(wait * 1000);
continue;
}
throw await apiErrorFrom(res, body429);
}
if (!res.ok) {
const text = await res.text().catch(() => '');
if (timer) { clearTimeout(timer); }
throw await apiErrorFrom(res, text);
}
if (opts.stream) { return res; }
const text = await res.text().catch(() => '');
if (timer) { clearTimeout(timer); }
try { return JSON.parse(text); } catch (e) { throw new AioError(t('bad_json', res.status), { status: res.status }); }
}
}
function retryAfter(res) {
const ra = parseInt(res.headers.get('retry-after') || '', 10);
if (ra > 0) { return ra; }
const reset = parseInt(res.headers.get('x-ratelimit-reset') || '', 10);
if (reset > 1e9) { return Math.max(1, Math.ceil(reset - Date.now() / 1000)); }
if (reset > 0) { return reset; }
return 0;
}
async function apiErrorFrom(res, text) {
let j = null;
try { j = JSON.parse(text); } catch (e) { /* not JSON */ }
const e = j && j.error && typeof j.error === 'object' ? j.error : null;
const corr = (e && e.correlation_id) || res.headers.get('x-correlation-id') || '';
if (!e) { return new AioError(t('bad_json', res.status), { status: res.status, correlation: corr }); }
let msg = String(e.message || e.code || ('HTTP ' + res.status));
const d = e.details && typeof e.details === 'object' ? e.details : null;
if (e.code === 'insufficient_credits' && d && d.required !== undefined) { msg += ' (' + t('needs', d.required, d.balance) + ')'; }
return new AioError(msg, { status: res.status, code: String(e.code || e.type || ''), correlation: corr, details: d });
}
/* SSE: returns each JSON object of "data:" until [DONE]. */
async function* sse(res) {
const decoder = new TextDecoder();
let buf = '';
for await (const chunk of res.body) {
buf += decoder.decode(chunk, { stream: true });
let i;
while ((i = buf.search(/\r?\n\r?\n/)) >= 0) {
const block = buf.slice(0, i);
buf = buf.slice(i).replace(/^\r?\n\r?\n/, '');
const data = block.split(/\r?\n/).filter((l) => l.startsWith('data:')).map((l) => l.slice(5).replace(/^ /, '')).join('\n');
if (!data) { continue; }
if (data.trim() === '[DONE]') { return; }
let obj;
try { obj = JSON.parse(data); } catch (e) { continue; }
yield obj;
}
}
}
/* ===================== arguments ===================== */
const VALUE_FLAGS = new Set(['--model', '--system', '--max-tokens', '--type', '--search', '--opt', '--out', '--timeout']);
const BOOL_FLAGS = new Set(['--json', '--no-stream', '--no-wait', '--download', '--yes', '--help', '--version', '--show-key', '--no-color']);
const SHORT = { '-m': '--model', '-s': '--system', '-t': '--type', '-q': '--search', '-o': '--out', '-h': '--help', '-v': '--version', '-y': '--yes' };
function parseArgs(argv) {
const pos = [];
const f = { opt: [] };
for (let i = 0; i < argv.length; i++) {
let a = argv[i];
if (a === '--') { pos.push(...argv.slice(i + 1)); break; }
if (SHORT[a]) { a = SHORT[a]; }
if (a.startsWith('--')) {
let name = a, val;
const eq = a.indexOf('=');
if (eq > 0) { name = a.slice(0, eq); val = a.slice(eq + 1); }
if (name === '--q') { name = '--search'; }
if (VALUE_FLAGS.has(name)) {
if (val === undefined) {
if (i + 1 >= argv.length) { throw usageError(t('missing_value', name)); }
val = argv[++i];
}
const k = name.slice(2);
if (k === 'opt') { f.opt.push(val); } else { f[k] = val; }
} else if (BOOL_FLAGS.has(name) && val === undefined) {
f[name.slice(2)] = true;
} else {
throw usageError(t('unknown_option', a));
}
} else if (a.length > 1 && a.startsWith('-') && !/^-\d/.test(a)) {
throw usageError(t('unknown_option', a));
} else {
pos.push(a);
}
}
return { pos, f };
}
function positiveInt(v, name) {
if (v === undefined) { return undefined; }
if (!/^\d+$/.test(String(v)) || parseInt(v, 10) <= 0) { throw usageError(t('bad_int', name)); }
return parseInt(v, 10);
}
/* ===================== display helpers ===================== */
function fmtNum(n) {
if (n === null || n === undefined || n === '') { return '-'; }
const x = Number(n);
if (!isFinite(x)) { return String(n); }
const s = (Math.round(x * 10000) / 10000).toString();
const parts = s.split('.');
if (Math.abs(x) >= 10000 && !/e/i.test(s)) { parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, PT ? ' ' : ','); }
return parts.join(PT ? ',' : '.');
}
function priceText(p) {
if (!p || typeof p !== 'object') { return '-'; }
if (p.unit === '1M tokens' || p.input !== undefined) { return t('per_1m', fmtNum(p.input), fmtNum(p.output)); }
const units = t('units');
return t('per_unit', fmtNum(p.credits), (units && units[p.unit]) || p.unit || '');
}
function cut(s, w) {
s = String(s == null ? '' : s).replace(/\s+/g, ' ');
if (w <= 1) { return s.slice(0, Math.max(0, w)); }
return s.length > w ? s.slice(0, w - 1) + '…' : s;
}
function table(rows, headers, maxWidths) {
const cols = headers.length;
const widths = headers.map((h, i) => Math.min(maxWidths[i] || 999, Math.max(h.length, ...rows.map((r) => String(r[i] == null ? '' : r[i]).length))));
const termW = (process.stdout.columns && process.stdout.columns > 40) ? process.stdout.columns : 160;
let total = widths.reduce((a, b) => a + b, 0) + 2 * (cols - 1);
/* shrinks the widest columns until it fits the terminal */
while (total > termW) {
let iMax = 0;
for (let i = 1; i < cols; i++) { if (widths[i] > widths[iMax]) { iMax = i; } }
if (widths[iMax] <= 8) { break; }
widths[iMax]--; total--;
}
const line = (r) => r.map((c, i) => (i === cols - 1 ? cut(c, widths[i]) : cut(c, widths[i]).padEnd(widths[i]))).join(' ').replace(/\s+$/, '');
const lines = [bold(line(headers))];
for (const r of rows) { lines.push(line(r)); }
return lines.join('\n');
}
function fmtDate(s) {
if (!s) { return '-'; }
const d = new Date(s);
if (isNaN(d.getTime())) { return String(s); }
try { return d.toLocaleString(PT ? 'pt-PT' : 'en-GB', { dateStyle: 'medium', timeStyle: 'short' }); } catch (e) { return d.toISOString(); }
}
const printJson = (o) => out(JSON.stringify(o, null, 2));
/* ===================== terminal input ===================== */
function readHidden(prompt) {
return new Promise((resolve, reject) => {
const stdin = process.stdin;
process.stderr.write(prompt);
if (!isTTY(stdin)) {
let data = '';
stdin.setEncoding('utf8');
stdin.on('data', (c) => { data += c; });
stdin.on('end', () => resolve(data.split(/\r?\n/)[0].trim()));
stdin.on('error', reject);
return;
}
let value = '';
stdin.setRawMode(true);
stdin.resume();
stdin.setEncoding('utf8');
const onData = (ch) => {
for (const c of ch) {
if (c === '\r' || c === '\n' || c === '\u0004') {
stdin.setRawMode(false); stdin.pause(); stdin.removeListener('data', onData);
process.stderr.write('\n');
resolve(value.trim());
return;
}
if (c === '\u0003') {
stdin.setRawMode(false); stdin.pause(); stdin.removeListener('data', onData);
process.stderr.write('\n');
reject(new AioError(t('interrupted'), { exitCode: 130 }));
return;
}
if (c === '\u007f' || c === '\b') { if (value.length) { value = value.slice(0, -1); process.stderr.write('\b \b'); } continue; }
if (c >= ' ') { value += c; process.stderr.write('*'); }
}
};
stdin.on('data', onData);
});
}
function readAllStdin() {
return new Promise((resolve, reject) => {
let data = '';
process.stdin.setEncoding('utf8');
process.stdin.on('data', (c) => { data += c; });
process.stdin.on('end', () => resolve(data));
process.stdin.on('error', reject);
});
}
function ask(question) {
return new Promise((resolve) => {
const rl = readline.createInterface({ input: process.stdin, output: process.stderr });
rl.question(question, (a) => { rl.close(); resolve(String(a || '').trim()); });
});
}
/* ===================== commands: auth ===================== */
async function cmdAuth(pos, f) {
const sub = pos[0] || 'status';
if (sub === 'login') { return authLogin(f); }
if (sub === 'logout') { return authLogout(); }
if (sub === 'status') { return authStatus(f); }
throw usageError(t('unknown_command', 'auth ' + sub));
}
/* Permissions the aio commands use (models and balance read, chat and media write). */
const NEEDED_PERMS = ['ai:read', 'ai:write'];
/* Checks the key with GET /v1/token, which any valid key may call. */
async function checkKey(key) {
try {
const r = await request('GET', '/v1/token', { key });
const d = (r && r.data) || {};
const perms = Array.isArray(d.permissions) ? d.permissions.map(String) : [];
return { mode: d.mode === 'production' ? 'prod' : (d.mode === 'sandbox' ? 'sandbox' : keyMode(key)), perms, missing: NEEDED_PERMS.filter((p) => !perms.includes(p)), data: d };
} catch (e) {
const why = String(e.message || '').replace(/\.$/, '');
if (e.status === 401) { throw new AioError(t('key_invalid', why), { status: e.status, code: e.code, correlation: e.correlation }); }
if (e.status === 403) { throw new AioError(t('key_forbidden', why), { status: e.status, code: e.code, correlation: e.correlation }); }
throw e;
}
}
async function balanceIf(info, key) {
if (!info.perms.includes('ai:read')) { return null; }
try { return await request('GET', '/v1/ai/balance', { key }); } catch (e) { return null; }
}
function showKey(info, bal) {
out(t('st_perms') + ': ' + (info.perms.length ? info.perms.join(', ') : t('perms_none')));
if (bal && bal.data && bal.data.credits !== undefined) { out(t('credits') + ': ' + fmtNum(bal.data.credits)); }
if (info.missing.length) { err(t('missing_perms', info.missing.join(', '))); }
}
async function authLogin(f) {
let key = (process.env.AIO_API_KEY || '').trim();
const fromEnv = !!key;
if (!key) { key = await readHidden(t('ask_key')); }
if (!key) { throw new AioError(t('empty_key')); }
SECRETS.add(key);
if (!/^(prod|sandbox)_[A-Za-z0-9_-]{8,}$/.test(key)) { throw usageError(t('bad_key_format')); }
const info = await checkKey(key);
const bal = await balanceIf(info, key);
const file = writeConfig(Object.assign(readConfig(), { api_key: key, saved_at: new Date().toISOString() }));
if (f.json) { printJson({ ok: true, key: maskKey(key), mode: info.mode, permissions: info.perms, missing_permissions: info.missing, config: file, balance: bal ? bal.data : null }); return; }
out(t('logged_in', maskKey(key), t(info.mode)));
showKey(info, bal);
out(t('saved_in', file));
if (fromEnv) { out(dim(t('from_env'))); }
}
async function authLogout() {
const file = configFile();
const cfg = readConfig();
if (cfg.api_key) {
delete cfg.api_key; delete cfg.saved_at;
if (Object.keys(cfg).length) { writeConfig(cfg); } else { try { fs.unlinkSync(file); } catch (e) { /* already gone */ } }
out(t('logged_out', file));
} else {
out(t('nothing_saved'));
}
if ((process.env.AIO_API_KEY || '').trim()) { out(t('env_still')); }
}
async function authStatus(f) {
const k = currentKey();
if (!k.key) { throw new AioError(t('no_key')); }
const ki = await checkKey(k.key);
const bal = await balanceIf(ki, k.key);
const info = { key: maskKey(k.key), source: k.source === 'env' ? 'AIO_API_KEY' : configFile(), mode: ki.mode, api: baseUrl(), valid: true, permissions: ki.perms, missing_permissions: ki.missing, credits: bal && bal.data ? bal.data.credits : null };
if (f.json) { printJson(info); return; }
out(t('st_key') + ': ' + info.key);
out(t('st_source') + ': ' + (k.source === 'env' ? t('st_src_env') : t('st_src_file', configFile())));
out(t('st_mode') + ': ' + t(info.mode));
out(t('st_api') + ': ' + info.api);
out(t('st_valid') + ': ' + t('st_ok'));
showKey(ki, bal);
}
/* ===================== balance ===================== */
async function cmdBalance(pos, f) {
const r = await request('GET', '/v1/ai/balance');
if (f.json) { printJson(r); return; }
const d = (r && r.data) || {};
out(t('credits') + ': ' + bold(fmtNum(d.credits)));
const s = d.subscription;
if (s && typeof s === 'object') {
out(t('plan') + ': ' + (s.plan_name || s.plan || '-') + (s.status ? ' (' + s.status + ')' : ''));
if (s.weekly_remaining !== undefined) { out(t('plan_week') + ': ' + fmtNum(s.weekly_remaining) + ' ' + t('points')); }
if (s.monthly_remaining !== undefined) { out(t('plan_month') + ': ' + fmtNum(s.monthly_remaining) + ' ' + t('points')); }
if (s.weekly_resets_at) { out(t('plan_week_reset') + ': ' + fmtDate(s.weekly_resets_at)); }
if (s.monthly_resets_at) { out(t('plan_month_reset') + ': ' + fmtDate(s.monthly_resets_at)); }
if (s.fallback_to_credits !== undefined) { out(t('plan_fallback') + ': ' + (s.fallback_to_credits ? t('yes') : t('no'))); }
}
}
/* ===================== models ===================== */
async function cmdModels(pos, f) {
const type = f.type ? String(f.type).toLowerCase() : '';
if (type && !['text', 'image', 'video', 'audio', 'agent'].includes(type)) { throw usageError(t('bad_type')); }
const q = f.search !== undefined ? f.search : (pos.length ? pos.join(' ') : '');
const r = await request('GET', '/v1/models', { query: { type, q } });
if (f.json) { printJson(r); return; }
const list = Array.isArray(r && r.data) ? r.data : [];
if (!list.length) { out(t('no_models')); return; }
const rows = list.map((m) => [m.id, m.type || '', m.name || '', priceText(m.pricing)]);
out(table(rows, [t('col_id'), t('col_type'), t('col_name'), t('col_price')], [60, 6, 34, 60]));
out(dim(t('n_models', list.length)));
}
async function cmdModel(pos, f) {
const id = pos.join(' ').trim();
if (!id) { throw usageError(t('need_id', 'model ' + DEFAULT_MODELS.image)); }
const m = await request('GET', '/v1/models/' + encodeId(id));
if (f.json) { printJson(m); return; }
out(bold(m.id || id));
const kv = (k, v) => { if (v !== undefined && v !== null && v !== '' && !(Array.isArray(v) && !v.length)) { out(k + ': ' + v); } };
kv(t('m_name'), m.name);
kv(t('m_type'), m.type);
kv(t('m_category'), m.category);
kv(t('m_base'), m.base_model);
kv(t('m_status'), m.status);
kv(t('m_tools'), Array.isArray(m.tools) ? m.tools.join(', ') : undefined);
kv(t('m_price'), priceText(m.pricing));
kv(t('m_context'), m.context_length ? fmtNum(m.context_length) + ' ' + t('tokens') : undefined);
kv(t('m_max_out'), m.max_output_tokens ? fmtNum(m.max_output_tokens) + ' ' + t('tokens') : undefined);
kv(t('m_desc'), m.description);
if (Array.isArray(m.input) && m.input.length) {
out('');
out(t('m_inputs'));
for (const c of m.input) {
const extra = [c.type + (c.items ? '[' + c.items + ']' : '')];
if (c.required) { extra.push(t('f_required')); }
if (c.default !== null && c.default !== undefined && c.default !== '') { extra.push(t('f_default') + ' ' + JSON.stringify(c.default)); }
if (Array.isArray(c.options) && c.options.length) { extra.push(t('f_options') + ' ' + c.options.slice(0, 12).join(', ') + (c.options.length > 12 ? ', …' : '')); }
if (c.min !== null && c.min !== undefined && c.max !== null && c.max !== undefined) { extra.push(t('f_range', c.min, c.max)); }
out(' ' + bold(c.name) + ' (' + extra.join('; ') + ')');
if (c.description) { out(' ' + cut(c.description, 240)); }
}
}
}
/* ===================== chat ===================== */
async function chatOnce(messages, f, opts) {
const model = f.model || process.env.AIO_MODEL || DEFAULT_MODELS.chat;
const body = { model, messages };
if (f['max-tokens'] !== undefined) { body.max_tokens = positiveInt(f['max-tokens'], '--max-tokens'); }
const stream = !f['no-stream'] && !f.json;
if (!stream) {
const r = await request('POST', '/v1/chat/completions', { body, timeoutMs: 330000 });
const text = ((r.choices && r.choices[0] && r.choices[0].message && r.choices[0].message.content) || '');
if (f.json) { printJson(r); } else { out(typeof text === 'string' ? text : JSON.stringify(text)); }
showUsage(model, r.usage);
return typeof text === 'string' ? text : '';
}
body.stream = true;
body.stream_options = { include_usage: true };
const res = await request('POST', '/v1/chat/completions', { body, stream: true, signal: opts && opts.signal });
let text = '';
let usage = null;
let endsWithNewline = true;
for await (const ev of sse(res)) {
if (ev && ev.error) {
const e = ev.error;
throw new AioError(String(e.message || e.code || 'stream error'), { code: e.code || '', correlation: e.correlation_id || res.headers.get('x-correlation-id') || '' });
}
if (ev.usage) { usage = ev.usage; }
const c = ev.choices && ev.choices[0] && ev.choices[0].delta && ev.choices[0].delta.content;
if (typeof c === 'string' && c) {
text += c;
process.stdout.write(c);
endsWithNewline = c.endsWith('\n');
}
}
if (!endsWithNewline || !text) { process.stdout.write('\n'); }
showUsage(model, usage);
return text;
}
function showUsage(model, usage) {
if (!usage || !isTTY(process.stderr)) { return; }
err(dim(t('chat_usage', model, usage.prompt_tokens || 0, usage.completion_tokens || 0), process.stderr));
}
async function cmdChat(pos, f) {
requireKey();
if (f['max-tokens'] !== undefined) { positiveInt(f['max-tokens'], '--max-tokens'); }
let prompt = pos.join(' ').trim();
if (!prompt && !isTTY(process.stdin)) { prompt = (await readAllStdin()).trim(); }
const base = f.system ? [{ role: 'system', content: String(f.system) }] : [];
if (prompt) {
await chatOnce(base.concat([{ role: 'user', content: prompt }]), f);
return;
}
if (f.json) { throw usageError(t('need_prompt', 'chat', PT ? 'olá' : 'hello')); }
return interactiveChat(base, f);
}
async function interactiveChat(base, f) {
const model = f.model || process.env.AIO_MODEL || DEFAULT_MODELS.chat;
err(dim(t('chat_hello', BUILD.brand + ' ' + PRODUCT, model), process.stderr));
let history = base.slice();
const rl = readline.createInterface({ input: process.stdin, output: process.stdout, prompt: '> ', terminal: true });
let current = null;
rl.on('SIGINT', () => {
if (current) { current.abort(); return; }
rl.close();
});
rl.prompt();
for await (const line of rl) {
const s = line.trim();
if (!s) { rl.prompt(); continue; }
if (s === '/exit' || s === '/quit') { break; }
if (s === '/reset') { history = base.slice(); err(dim(t('chat_reset'), process.stderr)); rl.prompt(); continue; }
history.push({ role: 'user', content: s });
current = new AbortController();
try {
const answer = await chatOnce(history, f, { signal: current.signal });
history.push({ role: 'assistant', content: answer });
} catch (e) {
history.pop();
if (e && (e.name === 'AbortError' || /abort/i.test(String(e.message)))) { process.stdout.write('\n'); } else { printError(e); }
}
current = null;
rl.prompt();
}
rl.close();
}
/* ===================== generate and status ===================== */
function parseOptValue(v, field) {
const s = String(v);
const ftype = field && field.type;
if (ftype === 'string' || ftype === 'image' || ftype === 'text') { return s; }
if (ftype === 'array') {
if (s.startsWith('[')) { try { return JSON.parse(s); } catch (e) { /* go on */ } }
return s.split(',').map((x) => x.trim()).filter(Boolean);
}
if (/^(true|false)$/i.test(s)) { return /^true$/i.test(s); }
if (/^-?\d+(\.\d+)?$/.test(s)) { return Number(s); }
if (s.startsWith('{') || s.startsWith('[')) { try { return JSON.parse(s); } catch (e) { /* go on */ } }
return s;
}
function buildInput(kind, prompt, fields, opts) {
const byName = {};
for (const c of fields || []) { byName[c.name] = c; }
const input = {};
for (const o of opts) {
const i = String(o).indexOf('=');
if (i <= 0) { throw usageError(t('bad_opt', o)); }
const k = o.slice(0, i).trim();
input[k] = parseOptValue(o.slice(i + 1), byName[k]);
}
if (prompt) {
let target = 'prompt';
if (kind === 'audio') {
target = byName.text ? 'text' : (byName.prompt ? 'prompt' : (byName.lyrics ? 'lyrics' : 'text'));
} else if (!byName.prompt && byName.text) {
target = 'text';
}
if (input[target] === undefined) { input[target] = prompt; }
}
/* required choice fields: the model default, or the first option (as in the MCP server) */
for (const c of fields || []) {
if (c.required && input[c.name] === undefined && Array.isArray(c.options) && c.options.length) {
input[c.name] = c.options.includes(c.default) ? c.default : c.options[0];
}
}
return input;
}
class Spinner {
constructor(label) {
this.label = label; this.t0 = Date.now(); this.i = 0; this.timer = null;
this.on = isTTY(process.stderr);
}
start() {
if (!this.on) { return this; }
const frames = ['|', '/', '-', '\\'];
this.timer = setInterval(() => {
const s = Math.round((Date.now() - this.t0) / 1000);
process.stderr.write('\r' + frames[this.i++ % 4] + ' ' + this.label + '... ' + s + ' s ');
}, 250);
return this;
}
stop() {
if (this.timer) { clearInterval(this.timer); this.timer = null; process.stderr.write('\r\x1b[K'); }
}
}
async function cmdGenerate(pos, f) {
const kind = String(pos[0] || '').toLowerCase();
if (!['image', 'video', 'audio'].includes(kind)) { throw usageError(t('gen_kind')); }
const prompt = pos.slice(1).join(' ').trim();
if (!prompt && !f.opt.length) { throw usageError(t('need_prompt', 'generate ' + kind, PT ? 'um farol ao pôr do sol' : 'a lighthouse at sunset')); }
for (const o of f.opt) { if (String(o).indexOf('=') <= 0) { throw usageError(t('bad_opt', o)); } }
requireKey();
const envModel = process.env['AIO_' + kind.toUpperCase() + '_MODEL'];
const model = f.model || envModel || DEFAULT_MODELS[kind];
const info = await request('GET', '/v1/models/' + encodeId(model));
if (info && info.type && info.type !== kind) { throw usageError(t('gen_wrong_type', model, info.type, kind, kind)); }
const input = buildInput(kind, prompt, info && info.input, f.opt);
const created = await request('POST', '/v1/media/generations', { body: { model, input }, retry429: true });
const job = (created && created.data) || {};
if (!job.id) { throw new AioError(t('bad_json', 202)); }
if (f['no-wait']) {
if (f.json) { printJson(created); return; }
out(t('gen_submitted', job.id, fmtNum(job.credits_reserved)));
out(t('gen_check', job.id));
return;
}
if (!f.json) { err(t('gen_submitted', job.id, fmtNum(job.credits_reserved))); }
const limit = (f.timeout !== undefined ? positiveInt(f.timeout, '--timeout') : (kind === 'video' ? 900 : 300));
const final = job.status === 'completed' || job.status === 'failed' ? await getGeneration(job.id) : await waitGeneration(job.id, kind, limit);
return finishGeneration(final, f, true);
}
async function getGeneration(id) {
const r = await request('GET', '/v1/media/generations/' + encodeId(id), { quiet: true });
return (r && r.data) || {};
}
async function waitGeneration(id, kind, limitS) {
const sp = new Spinner(t('gen_waiting')).start();
const t0 = Date.now();
const interval = (parseFloat(process.env.AIO_POLL_SECONDS) > 0 ? parseFloat(process.env.AIO_POLL_SECONDS) : (kind === 'video' ? 6 : 3)) * 1000;
try {
for (;;) {
const d = await getGeneration(id);
if (d.status === 'completed' || d.status === 'failed') { return d; }
if ((Date.now() - t0) / 1000 >= limitS) { throw new AioError(t('gen_timeout', limitS, id)); }
await sleep(interval);
}
} finally { sp.stop(); }
}
async function finishGeneration(d, f, download) {
if (d.status === 'failed') { throw new AioError(t('gen_failed', d.error || '-')); }
const files = [];
if (d.status === 'completed' && download) {
const outputs = Array.isArray(d.outputs) ? d.outputs : [];
for (let i = 0; i < outputs.length; i++) {
files.push(await downloadFile(outputs[i], f.out, d.id, i, outputs.length));
}
}
if (f.json) { printJson({ data: d, files }); return; }
if (d.status !== 'completed') {
out(t('st_status') + ': ' + statusName(d.status));
out(t('gen_check', d.id));
return;
}
out(t('gen_done'));
if (files.length) { for (const p of files) { out(t('gen_saved', p)); } } else if (Array.isArray(d.outputs) && d.outputs.length) {
out(t('gen_outputs'));
for (const u of d.outputs) { out(' ' + u); }
}
if (d.credits_charged !== null && d.credits_charged !== undefined) { out(t('gen_cost', fmtNum(d.credits_charged))); }
}
function statusName(s) { const n = t('status_names'); return (n && n[s]) || s || '-'; }
const EXT = { 'image/png': '.png', 'image/jpeg': '.jpg', 'image/webp': '.webp', 'image/gif': '.gif', 'image/svg+xml': '.svg', 'video/mp4': '.mp4', 'video/webm': '.webm', 'audio/mpeg': '.mp3', 'audio/wav': '.wav', 'audio/x-wav': '.wav', 'audio/ogg': '.ogg', 'audio/flac': '.flac', 'audio/aac': '.aac' };
async function downloadFile(url, outOpt, id, i, total) {
let u;
try { u = new URL(String(url)); } catch (e) { throw new AioError(t('dl_bad_url', url)); }
if (u.protocol !== 'https:' && u.protocol !== 'http:') { throw new AioError(t('dl_bad_url', url)); }
/* The files are public: the request goes without the key. */
let res;
try { res = await fetch(u.toString(), { headers: { 'User-Agent': UA }, redirect: 'follow' }); } catch (e) {
throw new AioError(t('network', u.host, (e && e.cause && e.cause.code) || (e && e.message) || 'fetch'));
}
if (!res.ok || !res.body) { throw new AioError(t('dl_failed', u.toString(), res.status)); }
const ctype = String(res.headers.get('content-type') || '').split(';')[0].trim().toLowerCase();
let name = decodeURIComponent(path.posix.basename(u.pathname) || '').replace(/[^A-Za-z0-9._-]+/g, '_').replace(/^\.+/, '');
let ext = path.extname(name);
if (!ext) { ext = EXT[ctype] || ''; }
const stem = String(id || 'aio').replace(/[^A-Za-z0-9-]+/g, '') + (total > 1 ? '-' + (i + 1) : '');
let target;
const o = outOpt ? String(outOpt) : '';
const looksDir = o && (o.endsWith('/') || o.endsWith(path.sep) || (fs.existsSync(o) && fs.statSync(o).isDirectory()));
if (!o || looksDir) {
const dir = o || process.cwd();
fs.mkdirSync(dir, { recursive: true });
target = path.join(dir, stem + ext);
} else {
const oe = path.extname(o);
const baseNoExt = oe ? o.slice(0, -oe.length) : o;
target = (total > 1 ? baseNoExt + '-' + (i + 1) : baseNoExt) + (oe || ext);
fs.mkdirSync(path.dirname(path.resolve(target)), { recursive: true });
}
target = uniquePath(target);
const tmp = target + '.part';
try {
await pipeline(Readable.fromWeb(res.body), fs.createWriteStream(tmp));
fs.renameSync(tmp, target);
} catch (e) {
try { fs.unlinkSync(tmp); } catch (e2) { /* ignore */ }
throw new AioError(t('dl_failed', u.toString(), (e && e.code) || 'write'));
}
return path.resolve(target);
}
function uniquePath(p) {
if (!fs.existsSync(p)) { return p; }
const e = path.extname(p);
const b = e ? p.slice(0, -e.length) : p;
for (let n = 2; n < 10000; n++) { const c = b + '-' + n + e; if (!fs.existsSync(c)) { return c; } }
return b + '-' + Date.now() + e;
}
async function cmdStatus(pos, f) {
const id = String(pos[0] || '').trim();
if (!id) { throw usageError(t('need_id', 'status <id>')); }
const d = await getGeneration(id);
if (d.status === 'failed') { if (f.json) { printJson({ data: d }); process.exitCode = 1; return; } throw new AioError(t('gen_failed', d.error || '-')); }
if (f.download && d.status === 'completed') { return finishGeneration(d, f, true); }
if (f.json) { printJson({ data: d }); return; }
out('ID: ' + (d.id || id));
out(t('st_status') + ': ' + statusName(d.status));
if (d.model) { out(t('st_model') + ': ' + d.model); }
if (Array.isArray(d.outputs) && d.outputs.length) { out(t('gen_outputs')); for (const u of d.outputs) { out(' ' + u); } }
if (d.credits_charged !== null && d.credits_charged !== undefined) { out(t('gen_cost', fmtNum(d.credits_charged))); }
if (d.status === 'processing') { out(dim(t('gen_check', d.id || id))); }
}
/* ===================== mcp install ===================== */
function shQuote(s) { return /^[A-Za-z0-9_\/:.=@%+,-]+$/.test(s) ? s : "'" + String(s).replace(/'/g, "'\\''") + "'"; }
async function cmdMcp(pos, f) {
const sub = pos[0];
const target = String(pos[1] || '').toLowerCase();
if (sub !== 'install') { throw usageError(t('unknown_command', 'mcp ' + (sub || ''))); }
if (!['claude', 'codex', 'cursor'].includes(target)) { throw usageError(t('mcp_target')); }
const url = baseUrl().replace(/\/v1$/, '') + '/mcp';
const name = BUILD.mcpName || 'aio';
const k = currentKey();
const shown = k.key ? (f['show-key'] ? k.key : maskKey(k.key)) : 'prod_...';
if (f['show-key'] && k.key) { SECRETS.delete(k.key); }
if (target === 'claude') {
const args = ['mcp', 'add', '--transport', 'http', '--scope', 'user', name, url, '--header', 'Authorization: Bearer ' + (k.key || 'prod_...')];
const display = 'claude ' + args.slice(0, -2).map(shQuote).join(' ') + ' --header ' + shQuote('Authorization: Bearer ' + shown);
if (f.json) { printJson({ target, name, url, command: display }); return; }
out(t('mcp_claude_intro'));
out('');
out(' ' + display);
out('');
if (k.key && !f['show-key']) { out(dim(t('mcp_masked'))); }
if (!k.key) { return; }
let run = !!f.yes;
if (!run && isTTY(process.stdin) && isTTY(process.stdout)) {
const a = (await ask(t('mcp_ask_run'))).toLowerCase();
run = ['s', 'sim', 'y', 'yes'].includes(a);
}
if (!run) { if (isTTY(process.stdin)) { out(t('mcp_not_run')); } return; }
const code = await new Promise((resolve) => {
const p = spawn(process.platform === 'win32' ? 'claude.cmd' : 'claude', args, { stdio: 'inherit' });
p.on('error', () => resolve(-1));
p.on('exit', (c) => resolve(c === null ? 1 : c));
});
if (code === -1) { throw new AioError(t('mcp_no_claude')); }
if (code !== 0) { throw new AioError(t('mcp_run_fail', code)); }
out(t('mcp_ran', name));
return;
}
const envLine = (process.platform === 'win32' ? '$env:AIO_API_KEY="' + shown + '"' : 'export AIO_API_KEY=' + shQuote(shown));
if (target === 'codex') {
const block = '[mcp_servers.' + (/^[A-Za-z0-9_-]+$/.test(name) ? name : JSON.stringify(name)) + ']\nurl = ' + JSON.stringify(url) + '\nbearer_token_env_var = "AIO_API_KEY"\ntool_timeout_sec = 120';
if (f.json) { printJson({ target, name, url, config: block, env: 'AIO_API_KEY' }); return; }
out(t('mcp_codex_intro'));
out('');
out(block);
out('');
} else {
const obj = { mcpServers: { [name]: { url, headers: { Authorization: 'Bearer ${env:AIO_API_KEY}' } } } };
if (f.json) { printJson({ target, name, url, config: obj, env: 'AIO_API_KEY' }); return; }
out(t('mcp_cursor_intro'));
out('');
out(JSON.stringify(obj, null, 2));
out('');
}
out(t('mcp_env_hint'));
out(' ' + envLine);
if (k.key && !f['show-key']) { out(dim(t('mcp_masked_env'))); }
}
/* ===================== help ===================== */
const HELP = {
pt: {
main: [
'aio %VER%: o comando do %BRAND% %PRODUCT%',
'',
'Uso: aio <comando> [opções]',
'',
'Comandos:',
' auth login | logout | status entrar com a chave de API, sair, ver a chave em uso',
' balance créditos e plano',
' models [--type t] [--search q] listar modelos e preços (t: text, image, video, audio, agent)',
' model <id> detalhe de um modelo e campos de entrada',
' chat ["pedido"] conversar (sem pedido abre o chat interactivo)',
' generate image|video|audio "pedido" gerar e descarregar ficheiros',
' status <id> [--download] ver uma geração e descarregar o resultado',
' mcp install claude|codex|cursor associar o servidor MCP a uma ferramenta',
' help [comando] esta ajuda, ou a de um comando',
'',
'Opções gerais: --json (saída em JSON), --help, --version',
'',
'Variáveis: AIO_API_KEY (chave, tem prioridade), AIO_BASE_URL (endereço da API),',
' AIO_MODEL (modelo do chat), AIO_LANG (pt ou en)',
'',
'API: %BASE% Docs: %DOCS%',
'Códigos de saída: 0 sucesso, 1 erro, 2 uso incorrecto.'
],
auth: ['aio auth login pede a chave (prod_... ou sandbox_...), valida-a e guarda-a em %CFG% (chmod 600).', ' Com a variável AIO_API_KEY, usa-a sem perguntar.', 'aio auth logout apaga a chave guardada.', 'aio auth status mostra a chave em uso (escondida), o modo, as permissões e o saldo.'],
balance: ['aio balance [--json]', 'Mostra os créditos e, se tiver plano, os pontos restantes na semana e no mês.'],
models: ['aio models [--type text|image|video|audio|agent] [--search texto] [--json]', 'Lista os modelos com o preço em créditos.'],
model: ['aio model <id> [--json]', 'Mostra um modelo. Nos de imagem, vídeo e áudio, mostra os campos de entrada para usar com --opt.'],
chat: ['aio chat "pedido" [--model id] [--system "instruções"] [--max-tokens n] [--no-stream] [--json]', 'Sem pedido, abre um chat interactivo (/reset limpa, /exit ou Ctrl+C sai).', 'Também lê o pedido da entrada: echo "olá" | aio chat', 'Modelo por omissão: %CHAT%'],
generate: ['aio generate image|video|audio "pedido" [--model id] [--opt chave=valor ...] [--out caminho] [--no-wait] [--timeout s] [--json]', 'Envia o pedido, espera que termine, descarrega os ficheiros (para --out ou para a pasta actual) e mostra o custo.', 'Exemplo: aio generate image "um farol ao pôr do sol" --opt size=1024x1024 --out imagens/'],
status: ['aio status <id> [--download] [--out caminho] [--json]', 'Mostra o estado de uma geração; com --download, descarrega os ficheiros.'],
mcp: ['aio mcp install claude|codex|cursor [--yes] [--show-key] [--json]', 'Mostra o comando ou o bloco de configuração do servidor MCP (%BASE%/mcp).', 'No Claude Code, o aio só corre o «claude mcp add» se confirmar (ou com --yes).']
},
en: {
main: [
'aio %VER%: the %BRAND% %PRODUCT% command',
'',
'Usage: aio <command> [options]',
'',
'Commands:',
' auth login | logout | status log in with your API key, log out, show the key in use',
' balance credits and plan',
' models [--type t] [--search q] list models and prices (t: text, image, video, audio, agent)',
' model <id> model details and input fields',
' chat ["prompt"] chat (without a prompt it opens an interactive chat)',
' generate image|video|audio "prompt" generate and download files',
' status <id> [--download] check a generation and download the result',
' mcp install claude|codex|cursor connect the MCP server to a tool',
' help [command] this help, or a command\'s help',
'',
'Global options: --json (JSON output), --help, --version',
'',
'Variables: AIO_API_KEY (key, takes priority), AIO_BASE_URL (API address),',
' AIO_MODEL (chat model), AIO_LANG (pt or en)',
'',
'API: %BASE% Docs: %DOCS%',
'Exit codes: 0 success, 1 error, 2 wrong usage.'
],
auth: ['aio auth login asks for the key (prod_... or sandbox_...), checks it and saves it in %CFG% (chmod 600).', ' With the AIO_API_KEY variable set, it uses it without asking.', 'aio auth logout deletes the saved key.', 'aio auth status shows the key in use (hidden), the mode, the permissions and the balance.'],
balance: ['aio balance [--json]', 'Shows your credits and, with a plan, the points left this week and this month.'],
models: ['aio models [--type text|image|video|audio|agent] [--search text] [--json]', 'Lists the models with their price in credits.'],
model: ['aio model <id> [--json]', 'Shows one model. For image, video and audio models it shows the input fields to use with --opt.'],
chat: ['aio chat "prompt" [--model id] [--system "instructions"] [--max-tokens n] [--no-stream] [--json]', 'Without a prompt it opens an interactive chat (/reset clears, /exit or Ctrl+C quits).', 'It also reads the prompt from stdin: echo "hello" | aio chat', 'Default model: %CHAT%'],
generate: ['aio generate image|video|audio "prompt" [--model id] [--opt key=value ...] [--out path] [--no-wait] [--timeout s] [--json]', 'Sends the request, waits until it finishes, downloads the files (to --out or the current folder) and shows the cost.', 'Example: aio generate image "a lighthouse at sunset" --opt size=1024x1024 --out images/'],
status: ['aio status <id> [--download] [--out path] [--json]', 'Shows the status of a generation; with --download it downloads the files.'],
mcp: ['aio mcp install claude|codex|cursor [--yes] [--show-key] [--json]', 'Shows the command or the config block for the MCP server (%BASE%/mcp).', 'For Claude Code, aio only runs "claude mcp add" if you confirm (or with --yes).']
}
};
function help(topic) {
const h = HELP[LANG] || HELP.en;
const lines = h[topic] || h.main;
let base = '';
try { base = baseUrl(); } catch (e) { base = String(process.env.AIO_BASE_URL || BUILD.base); }
out(lines.join('\n')
.replace(/%VER%/g, VERSION).replace(/%BRAND%/g, BUILD.brand).replace(/%PRODUCT%/g, PRODUCT)
.replace(/%BASE%/g, base).replace(/%DOCS%/g, BUILD.docs).replace(/%CFG%/g, configFile())
.replace(/%CHAT%/g, process.env.AIO_MODEL || DEFAULT_MODELS.chat));
}
/* ===================== main ===================== */
const COMMANDS = {
auth: cmdAuth, balance: cmdBalance, models: cmdModels, model: cmdModel, chat: cmdChat,
generate: cmdGenerate, gen: cmdGenerate, status: cmdStatus, mcp: cmdMcp
};
function printError(e) {
if (!(e instanceof AioError)) {
err(t('error') + ': ' + (e && e.message ? e.message : String(e)));
if (process.env.AIO_DEBUG && e && e.stack) { err(e.stack); }
return;
}
const extra = [];
if (e.code) { extra.push(e.code); }
if (e.status) { extra.push('HTTP ' + e.status); }
if (e.correlation) { extra.push(t('request_id') + ' ' + e.correlation); }
err(t('error') + ': ' + e.message + (extra.length ? ' [' + extra.join(', ') + ']' : ''));
}
async function main(argv) {
if (argv.includes('--no-color')) { process.env.NO_COLOR = '1'; }
const { pos, f } = parseArgs(argv);
if (f.version && !pos.length) { out('aio ' + VERSION + ' (' + BUILD.brand + ' ' + PRODUCT + ', ' + (process.env.AIO_BASE_URL || BUILD.base) + ')'); return 0; }
const cmd = pos.shift();
if (!cmd || cmd === 'help') { help(pos[0] === 'gen' ? 'generate' : pos[0]); return 0; }
if (cmd === 'version') { out('aio ' + VERSION + ' (' + BUILD.brand + ' ' + PRODUCT + ', ' + (process.env.AIO_BASE_URL || BUILD.base) + ')'); return 0; }
const fn = COMMANDS[cmd];
if (!fn) { throw usageError(t('unknown_command', cmd)); }
if (f.help) { help(cmd === 'gen' ? 'generate' : cmd); return 0; }
await fn(pos, f);
return process.exitCode || 0;
}
if (require.main === module) {
process.stdout.on('error', (e) => { if (e && e.code === 'EPIPE') { process.exit(0); } });
main(process.argv.slice(2)).then((code) => { process.exitCode = code || 0; }, (e) => {
printError(e);
process.exitCode = (e && e.exitCode) || 1;
});
}
module.exports = { main, parseArgs, buildInput, maskKey, redact, VERSION, BUILD };