koigrid 0.8.0 → 0.10.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/CHANGELOG.md CHANGED
@@ -2,6 +2,32 @@
2
2
 
3
3
  All notable changes to the koigrid CLI are documented here. Format: [Keep a Changelog](https://keepachangelog.com). Versions follow [SemVer](https://semver.org).
4
4
 
5
+ ## [Unreleased]
6
+
7
+ ## [0.10.0] — 2026-11-26
8
+
9
+ ### Added
10
+ - **Update notice**: once a day the CLI checks npm and, if a newer version exists, says so on stderr with the command
11
+ to update. Never in CI or with `--json`; turn it off with `KOIGRID_NO_UPDATE_CHECK=1`.
12
+
13
+ ## [0.9.0] — 2026-11-25
14
+
15
+ ### Changed
16
+ - **Default port comes from the image** (ficha 4d8b02da): without `--port`, the app listens on the image's single
17
+ `EXPOSE` port (an nginx `--dir` app goes live on 80), else 3000. A warning is shown if it clashes with one you chose.
18
+ - **A missing image is reported as such** (ficha 51987655): the deploy fails with `image_pull_failed` ("could not pull
19
+ the image") instead of a timeout, and internal timestamps no longer leak into your log.
20
+ - **`koigrid apps deploy` waits for the outcome** (ficha f76082de): shows each state change and ends with the URL, or with
21
+ the error and the last lines of the build/deploy log (exit code 1). `--no-wait` / `--detach` return at once,
22
+ `--timeout <min>` (default 20). With `--json` it still returns at once unless you pass `--wait` (scripts don't change).
23
+
24
+ ### Added
25
+ - **`koigrid apps port <id> <n>`** — change an app's port after creating it (redeploys).
26
+ - **Help per command and subcommand**: `koigrid apps deploy --help` lists its flags (it used to print the global help).
27
+ - **`koigrid login --email <you>`** — no key to paste: agent registration (auth.md, like `fly` / `vercel login`). The CLI
28
+ shows a link and a 6-digit code, the person approves it in the browser with that account, and the CLI keeps a 24-hour
29
+ token that **renews by itself** for up to 30 days (and once more after a 401). `--name` names the agent in Tokens.
30
+
5
31
  ## [0.7.0] — 2026-07-24
6
32
 
7
33
  ### Added
@@ -0,0 +1,49 @@
1
+ // ¿Hay una versión más nueva del CLI? (ficha dd72ac6f). Como update-notifier, gh o flyctl: pregunta a npm como mucho una
2
+ // vez al día, guarda la respuesta en ~/.koigrid/update-check.json y avisa por stderr (no ensucia una salida --json). La
3
+ // consulta va al FINAL del comando, con plazo de 1,5 s, y un fallo de red se calla: avisar de una versión nueva nunca puede
4
+ // romper ni frenar el comando que se pidió.
5
+ import { homedir } from 'node:os';
6
+ import { join } from 'node:path';
7
+ import { readFileSync, writeFileSync, mkdirSync } from 'node:fs';
8
+ const FICHERO = join(homedir(), '.koigrid', 'update-check.json');
9
+ const UN_DIA_MS = 24 * 3600_000;
10
+ const REGISTRO = 'https://registry.npmjs.org/koigrid/latest';
11
+ /** ¿`a` es más nueva que `b`? Sólo x.y.z (una versión con sufijo no se anuncia). PURA. */
12
+ export function esMasNueva(a, b) {
13
+ const pa = a.match(/^(\d+)\.(\d+)\.(\d+)$/);
14
+ const pb = b.match(/^(\d+)\.(\d+)\.(\d+)$/);
15
+ if (!pa || !pb)
16
+ return false;
17
+ for (let i = 1; i <= 3; i++)
18
+ if (Number(pa[i]) !== Number(pb[i]))
19
+ return Number(pa[i]) > Number(pb[i]);
20
+ return false;
21
+ }
22
+ /** ¿Se comprueba en esta ejecución? No en CI, ni con --json, ni si se pidió no hacerlo. PURA. */
23
+ export function debeComprobar(entorno, json) {
24
+ return !json && !entorno.CI && entorno.KOIGRID_NO_UPDATE_CHECK !== '1' && entorno.NO_UPDATE_NOTIFIER === undefined;
25
+ }
26
+ /** El aviso, si lo hay. PURA. */
27
+ export function avisoDeVersion(actual, ultima) {
28
+ return ultima && esMasNueva(ultima, actual) ? `A new koigrid CLI is available: ${actual} → ${ultima}. Update: npm i -g koigrid@latest` : null;
29
+ }
30
+ /** Lee la última versión conocida y, si la consulta tiene más de un día, pregunta a npm. Nunca lanza. */
31
+ export async function ultimaVersionConocida(ahora = Date.now()) {
32
+ let cache = {};
33
+ try {
34
+ cache = JSON.parse(readFileSync(FICHERO, 'utf8'));
35
+ }
36
+ catch { /* primera vez */ }
37
+ if (cache.comprobado && ahora - cache.comprobado < UN_DIA_MS)
38
+ return cache.ultima ?? null;
39
+ try {
40
+ const r = await fetch(REGISTRO, { signal: AbortSignal.timeout(1500) });
41
+ const ultima = r.ok ? String((await r.json()).version ?? '') || null : null;
42
+ mkdirSync(join(homedir(), '.koigrid'), { recursive: true, mode: 0o700 });
43
+ writeFileSync(FICHERO, JSON.stringify({ comprobado: ahora, ultima }));
44
+ return ultima;
45
+ }
46
+ catch {
47
+ return cache.ultima ?? null;
48
+ }
49
+ }
package/dist/agente.js ADDED
@@ -0,0 +1,103 @@
1
+ // cli/src/agente.ts — `koigrid login --email`: el registro de agente de auth.md (ficha d6d481e3), como el `vercel login`
2
+ // por código de dispositivo. La CLI pide acceso para ese email, enseña el enlace y el código de 6 cifras, espera a que
3
+ // la persona lo apruebe en el navegador y guarda el token y su aserción; después `renovarSiHaceFalta` renueva el token
4
+ // antes de que caduque. El protocolo, en https://koigrid.com/auth.md.
5
+ import { saveConfig, loadConfig, DEFAULT_API } from './config.js';
6
+ const GRANT_CLAIM = 'urn:workos:agent-auth:grant-type:claim';
7
+ const GRANT_JWT_BEARER = 'urn:ietf:params:oauth:grant-type:jwt-bearer';
8
+ /** Se renueva cuando quedan menos de 10 min de token. */
9
+ const MARGEN_RENOVACION_MS = 10 * 60_000;
10
+ function origenDe(api) {
11
+ return new URL(api).origin;
12
+ }
13
+ async function json(res) {
14
+ const t = await res.text();
15
+ try {
16
+ return t ? JSON.parse(t) : null;
17
+ }
18
+ catch {
19
+ return null;
20
+ }
21
+ }
22
+ async function descubrir(origen) {
23
+ const m = await json(await fetch(`${origen}/.well-known/oauth-authorization-server`, { signal: AbortSignal.timeout(15_000) }));
24
+ if (!m?.token_endpoint || !m?.agent_auth?.identity_endpoint)
25
+ throw new Error('This koigrid server does not offer agent registration (no agent_auth in its OAuth metadata).');
26
+ return { tokenEndpoint: m.token_endpoint, identityEndpoint: m.agent_auth.identity_endpoint, claimEndpoint: m.agent_auth.claim_endpoint };
27
+ }
28
+ async function tokenEndpoint(url, form) {
29
+ const res = await fetch(url, { method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams(form).toString(), signal: AbortSignal.timeout(30_000) });
30
+ return { status: res.status, body: await json(res) };
31
+ }
32
+ function guardar(api, b) {
33
+ saveConfig({ token: b.access_token, api, assertion: b.identity_assertion, tokenExpiresAt: new Date(Date.now() + Number(b.expires_in) * 1000).toISOString() });
34
+ }
35
+ const dormir = (ms) => new Promise((r) => setTimeout(r, ms));
36
+ /** La ceremonia entera. `avisar` imprime para la persona (el enlace y el código). Devuelve cuando hay token guardado. */
37
+ export async function loginComoAgente(email, opts) {
38
+ const api = opts.api || loadConfig().api || DEFAULT_API;
39
+ const ep = await descubrir(origenDe(api));
40
+ const alta = await fetch(ep.identityEndpoint, {
41
+ method: 'POST',
42
+ headers: { 'content-type': 'application/json' },
43
+ body: JSON.stringify({ type: 'service_auth', login_hint: email, client_name: opts.clientName ?? 'koigrid CLI' }),
44
+ signal: AbortSignal.timeout(30_000),
45
+ });
46
+ const a = await json(alta);
47
+ if (!alta.ok)
48
+ throw new Error(`${a?.error ?? `HTTP ${alta.status}`}: ${a?.error_description ?? ''}`.trim());
49
+ let claim = a.claim;
50
+ const mostrar = () => opts.avisar(`Open ${claim.verification_uri_complete ?? claim.verification_uri}\nsign in as ${email} and enter the code: ${claim.user_code}`);
51
+ mostrar();
52
+ let intervalo = Number(claim.interval) || 5;
53
+ for (;;) {
54
+ await dormir(intervalo * 1000);
55
+ const r = await tokenEndpoint(ep.tokenEndpoint, { grant_type: GRANT_CLAIM, claim_token: a.claim_token });
56
+ if (r.status === 200 && r.body?.access_token)
57
+ return guardar(api, r.body);
58
+ const e = r.body?.error;
59
+ if (e === 'authorization_pending')
60
+ continue;
61
+ if (e === 'slow_down') {
62
+ intervalo += 5;
63
+ continue;
64
+ }
65
+ if (e === 'expired_token') {
66
+ const n = await fetch(ep.claimEndpoint, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ claim_token: a.claim_token, email }), signal: AbortSignal.timeout(30_000) });
67
+ const nb = await json(n);
68
+ if (!n.ok)
69
+ throw new Error(`${nb?.error ?? `HTTP ${n.status}`}: the registration ended. Run the login again.`);
70
+ claim = nb.claim;
71
+ opts.avisar('The code expired. New code:');
72
+ mostrar();
73
+ continue;
74
+ }
75
+ throw new Error(`${e ?? `HTTP ${r.status}`}: ${r.body?.error_description ?? 'the registration ended. Run the login again.'}`);
76
+ }
77
+ }
78
+ /** ¿Hay que renovar? Sólo con aserción guardada y quedando menos del margen. PURA. */
79
+ export function tocaRenovar(c, ahora = Date.now()) {
80
+ if (!c.assertion || !c.tokenExpiresAt)
81
+ return false;
82
+ const exp = Date.parse(c.tokenExpiresAt);
83
+ return Number.isFinite(exp) && exp - ahora < MARGEN_RENOVACION_MS;
84
+ }
85
+ /**
86
+ * Renueva el token si va a caducar (o si `forzar`, tras un 401). Devuelve el token vigente. Si la renovación falla con
87
+ * `invalid_grant` (aserción caducada o la persona revocó al agente), lo dice: hay que volver a entrar.
88
+ */
89
+ export async function renovarSiHaceFalta(forzar = false) {
90
+ const c = loadConfig();
91
+ if (!c.assertion || (!forzar && !tocaRenovar(c)))
92
+ return c.token;
93
+ const api = c.api || DEFAULT_API;
94
+ const ep = await descubrir(origenDe(api));
95
+ const r = await tokenEndpoint(ep.tokenEndpoint, { grant_type: GRANT_JWT_BEARER, assertion: c.assertion });
96
+ if (r.status === 200 && r.body?.access_token) {
97
+ guardar(api, r.body);
98
+ return r.body.access_token;
99
+ }
100
+ if (r.body?.error === 'invalid_grant')
101
+ throw new Error('Your agent access ended (expired, or revoked in Tokens). Run `koigrid login --email <your email>` again.');
102
+ return c.token; // rate_limited u otro fallo pasajero: se sigue con el token actual mientras valga
103
+ }
package/dist/api.js CHANGED
@@ -1,5 +1,6 @@
1
1
  // Cliente HTTP de la API de koigrid. Añade el Bearer token + maneja errores JSON de forma uniforme.
2
2
  import { loadConfig, DEFAULT_API } from './config.js';
3
+ import { renovarSiHaceFalta } from './agente.js';
3
4
  import { createRequire } from 'node:module';
4
5
  // El CLI se IDENTIFICA con su versión: sin esto la API no puede distinguir un CLI viejo (que descartaba flags en
5
6
  // silencio) de una petición a mano, ni avisar a quien siga en una versión con fallos conocidos.
@@ -13,10 +14,13 @@ export const USER_AGENT = `koigrid-cli/${VERSION}`;
13
14
  export class ApiError extends Error {
14
15
  status;
15
16
  detail;
16
- constructor(status, message, detail) {
17
+ body;
18
+ /** `body`: el JSON de error entero, para los campos que no son `error`/`detail` (p. ej. `checkoutUrl`). */
19
+ constructor(status, message, detail, body) {
17
20
  super(message);
18
21
  this.status = status;
19
22
  this.detail = detail;
23
+ this.body = body;
20
24
  this.name = 'ApiError';
21
25
  }
22
26
  }
@@ -26,7 +30,8 @@ export class ApiError extends Error {
26
30
  */
27
31
  export async function api(path, opts = {}) {
28
32
  const cfg = loadConfig();
29
- const token = opts.token || cfg.token;
33
+ // Entraste con `koigrid login --email` (registro de agente): el token se renueva solo antes de caducar.
34
+ const token = opts.token || (cfg.assertion ? await renovarSiHaceFalta() : cfg.token);
30
35
  const base = opts.api || cfg.api || DEFAULT_API;
31
36
  // `anon`: endpoints PÚBLICOS a propósito. Exigir credenciales para consultarlos sería una contradicción — el
32
37
  // historial de cambios existe para que puedas averiguar si tu problema está arreglado, y quien todavía no ha
@@ -50,7 +55,7 @@ export async function api(path, opts = {}) {
50
55
  }
51
56
  catch { }
52
57
  ;
53
- throw new ApiError(res.status, j?.error || `HTTP ${res.status}`, j?.detail);
58
+ throw new ApiError(res.status, j?.error || `HTTP ${res.status}`, j?.detail, j ?? { requestId: res.headers.get('x-request-id') ?? undefined });
54
59
  }
55
60
  return text;
56
61
  }
@@ -59,7 +64,82 @@ export async function api(path, opts = {}) {
59
64
  json = text ? JSON.parse(text) : null;
60
65
  }
61
66
  catch { /* non-json */ }
67
+ // Un 401 con aserción guardada (el token se revocó o caducó antes de tiempo): se renueva UNA vez y se repite.
68
+ if (res.status === 401 && !opts.token && cfg.assertion && !opts.raw && !opts._renovado) {
69
+ const nuevo = await renovarSiHaceFalta(true);
70
+ if (nuevo && nuevo !== token)
71
+ return api(path, { ...opts, _renovado: true });
72
+ }
62
73
  if (!res.ok)
63
- throw new ApiError(res.status, json?.error || `HTTP ${res.status}`, json?.detail);
74
+ throw new ApiError(res.status, json?.error || `HTTP ${res.status}`, json?.detail, json);
75
+ // ⛔ UN 2xx QUE NO ES JSON NO ES LA API (ficha 550d3360). Con KOIGRID_API=https://koigrid.com (sin /api/v1) la web
76
+ // responde 200 con su HTML; esto devolvía null y el comando reventaba con «Cannot read properties of null (reading
77
+ // 'app')», sin decir que la URL estaba mal. Como gh o el CLI de Stripe: qué URL se usó y cuál es la buena.
78
+ if (text && json === null)
79
+ throw new ApiError(res.status, noEsLaApi(base, path, res.headers.get('content-type')), pistaDeUrl(base));
64
80
  return json;
65
81
  }
82
+ /** El mensaje de una respuesta 2xx que no es JSON: la URL pedida y lo que llegó en su lugar. */
83
+ export function noEsLaApi(base, path, contentType) {
84
+ return `${base}${path} did not answer like the koigrid API (got ${contentType || 'a non-JSON body'} instead of JSON)`;
85
+ }
86
+ /** La pista para arreglarlo: casi siempre es la base sin /api/v1. */
87
+ export function pistaDeUrl(base) {
88
+ const limpia = base.replace(/\/+$/, '');
89
+ return limpia.endsWith('/api/v1')
90
+ ? `Check KOIGRID_API (or "api" in your config): it is ${base}.`
91
+ : `Check KOIGRID_API (or "api" in your config): did you mean ${limpia}/api/v1 ? The default is ${DEFAULT_API}.`;
92
+ }
93
+ /**
94
+ * Una respuesta NDJSON (application/x-ndjson) de la API, evento a evento según llega: la salida en directo de una orden
95
+ * de una VM. Sin el plazo de 30 s de `api` (un enganche dura hasta 10 min por diseño): el servidor manda un latido
96
+ * cada 15 s, así que 60 s sin nada es una conexión muerta. Un error HTTP antes del primer evento se lanza como en `api`.
97
+ */
98
+ export async function apiNdjson(path, opts, alEvento) {
99
+ const cfg = loadConfig();
100
+ if (cfg.assertion)
101
+ cfg.token = await renovarSiHaceFalta();
102
+ if (!cfg.token)
103
+ throw new ApiError(401, 'Not logged in. Run `koigrid login` (or set KOIGRID_TOKEN).');
104
+ const ctrl = new AbortController();
105
+ let vigia = setTimeout(() => ctrl.abort(), 60_000);
106
+ const res = await fetch(`${cfg.api || DEFAULT_API}${path}`, {
107
+ method: opts.method || 'GET',
108
+ headers: { 'user-agent': USER_AGENT, Authorization: `Bearer ${cfg.token}`, accept: 'application/x-ndjson', ...(opts.body ? { 'content-type': 'application/json' } : {}) },
109
+ body: opts.body ? JSON.stringify(opts.body) : undefined,
110
+ signal: ctrl.signal,
111
+ }).catch((e) => { throw new ApiError(0, `network error: ${e?.message || e}`); });
112
+ if (!res.ok || !res.body) {
113
+ clearTimeout(vigia);
114
+ const text = await res.text();
115
+ let j = null;
116
+ try {
117
+ j = JSON.parse(text);
118
+ }
119
+ catch { }
120
+ throw new ApiError(res.status, j?.error || `HTTP ${res.status}`, j?.detail, j);
121
+ }
122
+ const dec = new TextDecoder();
123
+ let resto = '';
124
+ try {
125
+ for await (const trozo of res.body) {
126
+ clearTimeout(vigia);
127
+ vigia = setTimeout(() => ctrl.abort(), 60_000);
128
+ const partes = (resto + dec.decode(trozo, { stream: true })).split('\n');
129
+ resto = partes.pop() ?? '';
130
+ for (const l of partes)
131
+ if (l.trim())
132
+ alEvento(JSON.parse(l));
133
+ }
134
+ if (resto.trim())
135
+ alEvento(JSON.parse(resto));
136
+ }
137
+ catch (e) {
138
+ if (ctrl.signal.aborted)
139
+ throw new ApiError(0, 'the live output stopped arriving (no heartbeat in 60 s)');
140
+ throw e;
141
+ }
142
+ finally {
143
+ clearTimeout(vigia);
144
+ }
145
+ }
@@ -1,9 +1,46 @@
1
1
  import { execFileSync } from 'node:child_process';
2
2
  import { createHash } from 'node:crypto';
3
3
  import { api } from '../api.js';
4
- import { output, green } from '../output.js';
4
+ import { output, green, yellow, red, dim } from '../output.js';
5
+ import { esperarDesenlace, finalDelRegistro, debeEsperar } from '../esperar.js';
5
6
  import { credencialRegistryDeFlags } from '../registry-flags.js';
6
7
  import { proyectoDeFlags } from '../proyecto.js';
8
+ /**
9
+ * Espera al desenlace de un despliegue y lo cuenta (ficha f76082de): el progreso, y al final la URL o el error con el
10
+ * final del registro. Un fallo deja exit code 1; agotar la espera no es un fallo (el despliegue sigue) y lo dice.
11
+ */
12
+ async function esperarYContar(appId, depId, plazoMin, json) {
13
+ const leer = async () => {
14
+ const l = ((await api(`/apps/${encodeURIComponent(appId)}/deployments`)).deployments ?? []);
15
+ return depId ? l.find((x) => x.id === depId) : l[0];
16
+ };
17
+ const r = await esperarDesenlace({
18
+ leer, dormir: (ms) => new Promise((ok) => setTimeout(ok, ms)), ahora: () => Date.now(), plazoMs: plazoMin * 60_000,
19
+ alCambiar: json ? undefined : (e) => console.log(dim(` · ${e}`)),
20
+ });
21
+ const final = r.final?.status === 'live' ? (await api(`/apps/${encodeURIComponent(appId)}`)).app : null;
22
+ const url = final?.url ?? null;
23
+ const worker = final?.kind === 'worker';
24
+ if (json) {
25
+ console.log(JSON.stringify({ deploymentId: r.final?.id ?? depId ?? null, appId, status: r.final?.status ?? 'unknown', url, error: r.final?.error ?? null, timedOut: r.agotado }, null, 2));
26
+ }
27
+ else if (r.agotado) {
28
+ console.log(yellow(`… still ${r.final?.status ?? 'starting'} after ${plazoMin} min — it keeps going. Follow it: koigrid apps deployments ${appId}`));
29
+ }
30
+ else if (r.final?.status === 'live') {
31
+ // Un worker no tiene URL a propósito (ficha 73b2fa7c): decirlo, no «todavía no».
32
+ console.log(green(worker ? `✓ Running as a background worker (no URL). Logs: koigrid apps logs ${appId}` : `✓ Live: ${url ?? '(no URL yet)'}`));
33
+ }
34
+ else {
35
+ console.log(red(`✗ Deployment ${r.final?.status}${r.final?.error ? `: ${r.final.error}` : ''}`));
36
+ const fin = finalDelRegistro(r.final?.logs);
37
+ if (fin)
38
+ console.log(dim(`--- last lines of the build/deploy log ---\n${fin}`));
39
+ console.log(dim(`Full logs: koigrid apps logs ${appId} --type build`));
40
+ }
41
+ if (!r.agotado && r.final?.status !== 'live')
42
+ process.exitCode = 1;
43
+ }
7
44
  export async function apps(a) {
8
45
  const json = !!a.flags.json, sub = a.sub || 'ls';
9
46
  const id = a.positionals[0];
@@ -40,6 +77,8 @@ export async function apps(a) {
40
77
  bs.branch = a.flags.branch; // rama a clonar (repo); sin ella, main
41
78
  if (a.flags.dockerfile)
42
79
  bs.dockerfilePath = a.flags.dockerfile; // otro Dockerfile que el de la raíz de build
80
+ if (a.flags['release-cmd'])
81
+ bs.releaseCommand = a.flags['release-cmd']; // fase de release (migraciones), antes de arrancar la versión nueva
43
82
  // Tamaño AL CREAR (POST /apps ya lo admitía): sin esto había que crear y luego `apps resize`, o sea dos
44
83
  // despliegues, y el primero arrancaba con la memoria por defecto (un Chromium no cabe en ella).
45
84
  const tam = {};
@@ -52,9 +91,18 @@ export async function apps(a) {
52
91
  const ing = a.flags.ingress === 'runner' ? { ingress: 'runner' } : {};
53
92
  if (a.flags.ingress !== undefined && a.flags.ingress !== 'runner' && a.flags.ingress !== 'edge')
54
93
  throw new Error("--ingress must be 'edge' (default) or 'runner'");
94
+ // --worker: proceso de fondo SIN puerto (consumidor de cola, bot), como un worker de Heroku o un Background Worker
95
+ // de Render (ficha 73b2fa7c). Sin URL ni dominio; vivo = el proceso se sostiene. --port no aplica.
96
+ if (a.flags.worker && a.flags.port)
97
+ throw new Error('--worker has no port: drop --port (a background worker receives no traffic)');
98
+ if (a.flags.worker)
99
+ ing.kind = 'worker';
55
100
  if (!name || (!image && !repo && !dir))
56
- throw new Error('usage: koigrid apps deploy <name> --dir <path>|--image <img>|--repo <git-url> [--branch B] [--repo-token <t>] [--port N] [--ingress edge|runner] [--build-cmd C] [--install-cmd C] [--start-cmd C] [--root-dir D] [--node-version V] [--dockerfile PATH] [--memory <mb>] [--cpus <n>] [--project <id>] [--env KEY=VALUE ...] [--env-target all|production|preview]');
101
+ throw new Error('usage: koigrid apps deploy <name> --dir <path>|--image <img>|--repo <git-url> [--branch B] [--repo-token <t>] [--port N | --worker] [--ingress edge|runner] [--build-cmd C] [--install-cmd C] [--start-cmd C] [--root-dir D] [--node-version V] [--dockerfile PATH] [--release-cmd C] [--memory <mb>] [--cpus <n>] [--project <id>] [--env KEY=VALUE ...] [--env-target all|production|preview]');
57
102
  const port = a.flags.port ? Number(a.flags.port) : 3000;
103
+ // Esperar al desenlace (ficha f76082de): por defecto sí (personas y agentes), --json sólo con --wait, --no-wait nunca.
104
+ const esperar = debeEsperar(a.flags, json);
105
+ const plazoMin = a.flags.timeout ? Math.max(1, Number(a.flags.timeout)) : 20;
58
106
  // --env KEY=VAL (repetible): el entorno viaja CON la creación, así que el primer despliegue ya sale con él
59
107
  // (ficha d62bcde4). Antes había que crear, fijar variables y redesplegar: el primer despliegue fallaba siempre.
60
108
  const envPares = [].concat(a.flags.env ?? []);
@@ -69,7 +117,8 @@ export async function apps(a) {
69
117
  // deploy --dir: empaqueta el directorio (excluye lo pesado/irrelevante) → subida presignada a koigrid →
70
118
  // el runner lo construye igual que un repo. No requiere git ni Docker local.
71
119
  if (dir) {
72
- const app = await api('/apps', { method: 'POST', body: { name, port, ...hc, ...bs, ...tam, ...ing, ...en, ...proyectoDeFlags(a) } });
120
+ // `sourceType: 'archive'` (ficha 828d84dd): la app nace esperando su código, y así lo dice desde el primer momento.
121
+ const app = await api('/apps', { method: 'POST', body: { name, sourceType: 'archive', port, ...hc, ...bs, ...tam, ...ing, ...en, ...proyectoDeFlags(a) } });
73
122
  const aid = app.app?.id || app.id;
74
123
  const up = await api(`/apps/${encodeURIComponent(aid)}/source-upload`, { method: 'POST', body: {} });
75
124
  const { uploadUrl, archiveKey } = up.upload;
@@ -81,7 +130,11 @@ export async function apps(a) {
81
130
  const d = await api(`/apps/${encodeURIComponent(aid)}/deployments`, { method: 'POST', body: { sourceType: 'archive', archiveKey } });
82
131
  // Devuelve el ID del DEPLOYMENT (el que aparece en GET /apps/:id/deployments), NO el del app — evita la
83
132
  // confusión "ids CLI≠API" del journey. appId aparte, etiquetado.
84
- return json ? console.log(JSON.stringify({ deploymentId: d.deployment?.id, appId: aid, status: d.deployment?.status || 'queued', source: 'dir' }, null, 2)) : console.log(green(`✓ Deploying "${name}" from ${dir}… (deployment ${String(d.deployment?.id || '').slice(0, 8)})`));
133
+ if (!json)
134
+ console.log(green(`✓ Deploying "${name}" from ${dir}… (deployment ${String(d.deployment?.id || '').slice(0, 8)})`));
135
+ if (esperar)
136
+ return esperarYContar(aid, d.deployment?.id, plazoMin, json);
137
+ return json ? console.log(JSON.stringify({ deploymentId: d.deployment?.id, appId: aid, status: d.deployment?.status || 'queued', source: 'dir' }, null, 2)) : undefined;
85
138
  }
86
139
  const app = await api('/apps', { method: 'POST', body: { ...proyectoDeFlags(a), ...(repo ? { name, sourceType: 'git', repo, port, ...(repoToken ? { repoToken } : {}), ...hc, ...bs, ...tam, ...ing, ...en } : { name, sourceType: 'image', image, port, ...hc, ...tam, ...reg, ...ing, ...en }) } });
87
140
  const aid = app.app?.id || app.id;
@@ -95,12 +148,18 @@ export async function apps(a) {
95
148
  await new Promise((r) => setTimeout(r, 1000));
96
149
  auto = ((await api(`/apps/${encodeURIComponent(aid)}/deployments`)).deployments ?? [])[0];
97
150
  }
98
- return json
99
- ? console.log(JSON.stringify({ deploymentId: auto?.id ?? null, appId: aid, status: auto?.status || 'queued', automatic: true }, null, 2))
100
- : console.log(green(`✓ Deploying "${name}"… (deployment ${String(auto?.id || '').slice(0, 8) || 'starting'}, automatic on create)`));
151
+ if (!json)
152
+ console.log(green(`✓ Deploying "${name}"… (deployment ${String(auto?.id || '').slice(0, 8) || 'starting'}, automatic on create)`));
153
+ if (esperar)
154
+ return esperarYContar(aid, auto?.id, plazoMin, json);
155
+ return json ? console.log(JSON.stringify({ deploymentId: auto?.id ?? null, appId: aid, status: auto?.status || 'queued', automatic: true }, null, 2)) : undefined;
101
156
  }
102
157
  const d = await api(`/apps/${encodeURIComponent(aid)}/deployments`, { method: 'POST', body: {} });
103
- return json ? console.log(JSON.stringify({ deploymentId: d.deployment?.id, appId: aid, status: d.deployment?.status || 'queued' }, null, 2)) : console.log(green(`✓ Deploying "${name}"… (deployment ${String(d.deployment?.id || '').slice(0, 8)})`));
158
+ if (!json)
159
+ console.log(green(`✓ Deploying "${name}"… (deployment ${String(d.deployment?.id || '').slice(0, 8)})`));
160
+ if (esperar)
161
+ return esperarYContar(aid, d.deployment?.id, plazoMin, json);
162
+ return json ? console.log(JSON.stringify({ deploymentId: d.deployment?.id, appId: aid, status: d.deployment?.status || 'queued' }, null, 2)) : undefined;
104
163
  }
105
164
  case 'deployments':
106
165
  need('');
@@ -109,9 +168,38 @@ export async function apps(a) {
109
168
  const l = r.deployments || r || [];
110
169
  return output(l, json, { rows: l.map((x) => ({ id: x.id.slice(0, 8), status: x.status, source: x.source || '—' })), columns: ['id', 'status', 'source'] });
111
170
  }
112
- case 'logs':
171
+ case 'logs': {
113
172
  need('');
114
- return console.log((await api(`/apps/${encodeURIComponent(id)}/logs?tail=${a.flags.tail || 200}`)).logs || '');
173
+ // Los mismos filtros que la API (ficha d53876c6): --since/--until (ISO UTC), --replica, --runner, --q y --type build.
174
+ const qs = new URLSearchParams({ tail: String(a.flags.tail || 200) });
175
+ for (const k of ['type', 'since', 'until', 'replica', 'runner', 'q'])
176
+ if (typeof a.flags[k] === 'string' && a.flags[k])
177
+ qs.set(k, String(a.flags[k]));
178
+ const r = await api(`/apps/${encodeURIComponent(id)}/logs?${qs}`);
179
+ return console.log(json ? JSON.stringify(r, null, 2) : r.logs || '');
180
+ }
181
+ // Lo que vio el PROXY (ficha 7d10e8b8): peticiones, 5xx por código y las rutas que fallaron — también los 502/504
182
+ // que la app nunca registra. --hours (1-840, def. 24; más de 168 pide --bucket 1h|6h|1d) · --bucket 1m|5m|15m|1h|6h|1d (def. 5m).
183
+ case 'http': {
184
+ need(' [--hours 24] [--bucket 5m]');
185
+ const q = new URLSearchParams();
186
+ if (a.flags.hours)
187
+ q.set('hours', String(a.flags.hours));
188
+ if (a.flags.bucket)
189
+ q.set('bucket', String(a.flags.bucket));
190
+ const r = await api(`/apps/${encodeURIComponent(id)}/http${q.size ? `?${q}` : ''}`);
191
+ if (json)
192
+ return console.log(JSON.stringify(r, null, 2));
193
+ const t = r.totals || {};
194
+ const codigos = Object.entries(t.byStatus || {}).map(([c, n]) => `${c}×${n}`).join(' ');
195
+ console.log(`${r.hours} h · ${t.requests ?? 0} requests · ${t.errors5xx ?? 0} 5xx${codigos ? ` (${codigos})` : ''} · availability ${t.availabilityPct ?? '—'}%`);
196
+ output(r.series || [], false, { rows: (r.series || []).filter((p) => p.errors5xx > 0).map((p) => ({ at: String(p.at), requests: String(p.requests), '5xx': String(p.errors5xx), 'err%': String(p.errorPct ?? '—'), p99max: String(p.p99MaxMs ?? '—') })), columns: ['at', 'requests', '5xx', 'err%', 'p99max'] });
197
+ if ((r.errors || []).length) {
198
+ console.log(`\nlatest 5xx${r.errorsOmitted ? ` (+${r.errorsOmitted} not kept individually)` : ''}:`);
199
+ output(r.errors, false, { rows: r.errors.slice(0, 50).map((e) => ({ at: String(e.at), status: String(e.status), method: String(e.method || '—'), path: String(e.path || '—'), ms: String(e.durationMs ?? '—') })), columns: ['at', 'status', 'method', 'path', 'ms'] });
200
+ }
201
+ return;
202
+ }
115
203
  case 'rm':
116
204
  case 'delete':
117
205
  need('');
@@ -137,7 +225,7 @@ export async function apps(a) {
137
225
  return json ? console.log(JSON.stringify(r, null, 2)) : console.log(green(r.wasPaused ? (r.redeployed ? `✓ Resuming ${id}… (relanzando la última imagen)` : `✓ ${id} reanudada (nunca tuvo un deploy vivo: despliega con: koigrid apps deploy)`) : `✓ ${id} no estaba pausada`));
138
226
  }
139
227
  case 'loadtest': { // reporte de capacidad: rps + p50/p95/p99 + rodilla + señales del servidor (docs/platform/CAPACITY.md)
140
- need(' [--duration <s≤600>] [--concurrency <n≤100>] [--path /] [--ramp] [--stages 3] [--warmup 3] [--paths \'[{"path":"/","weight":3}]\']');
228
+ need(' [--duration <s≤600>] [--concurrency <n≤100>] [--path /] [--ramp] [--stages 3] [--warmup 3] [--paths \'[{"path":"/","weight":3}]\'] [--header "X-Origin-Verify: <secreto>"]…');
141
229
  const body = {};
142
230
  if (a.flags.duration !== undefined)
143
231
  body.durationSec = Number(a.flags.duration);
@@ -153,10 +241,24 @@ export async function apps(a) {
153
241
  body.warmupSec = Number(a.flags.warmup);
154
242
  if (a.flags.paths !== undefined)
155
243
  body.paths = JSON.parse(String(a.flags.paths));
244
+ // --header "Nombre: valor", repetible: p. ej. el secreto de origen que exige tu CDN (si no, sólo se mide un 403).
245
+ if (a.flags.header !== undefined) {
246
+ const headers = {};
247
+ for (const h of [].concat(a.flags.header)) {
248
+ const linea = String(h);
249
+ const i = linea.indexOf(':');
250
+ if (i <= 0)
251
+ throw new Error(`--header necesita "Nombre: valor" (recibido sin «:»)`);
252
+ headers[linea.slice(0, i).trim()] = linea.slice(i + 1).trim();
253
+ }
254
+ body.headers = headers;
255
+ }
156
256
  const r = await api(`/apps/${encodeURIComponent(id)}/loadtest`, { method: 'POST', body });
157
257
  if (a.flags.json)
158
258
  return console.log(JSON.stringify(r, null, 2));
159
259
  console.log(green(`✓ load-test ${r.app} (${r.target})`));
260
+ if (r.headersSent?.length)
261
+ console.log(` cabeceras enviadas: ${r.headersSent.join(', ')}`);
160
262
  console.log(` ${r.requests} reqs · ~${Math.round(r.rps)} req/s · p50 ${Math.round(r.p50)}ms · p95 ${Math.round(r.p95)}ms · p99 ${Math.round(r.p99)}ms · errores ${(r.errorRate * 100).toFixed(1)}%`);
161
263
  if (r.coldStartP95 != null)
162
264
  console.log(` arranque en frío (excluido del p95): ${r.coldStartP95}ms`);
@@ -407,7 +509,7 @@ export async function apps(a) {
407
509
  const act = a.positionals[1];
408
510
  if (!act) {
409
511
  const r = await api(`/apps/${encodeURIComponent(id)}/cdn`);
410
- return console.log(json ? JSON.stringify(r, null, 2) : `cdn: ${r.cdn?.enabled ? 'on' : 'off'}`);
512
+ return console.log(json ? JSON.stringify(r, null, 2) : `cdn: ${r.cdn?.enabled ? 'on' : 'off'}${r.cdn?.reason ? ` (${r.cdn.reason}: ${r.cdn.detail ?? ''})` : ''}`);
411
513
  }
412
514
  const r = await api(`/apps/${encodeURIComponent(id)}/cdn`, { method: 'PUT', body: { enabled: act === 'on' } });
413
515
  return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ CDN ${act}`));
@@ -586,6 +688,95 @@ export async function apps(a) {
586
688
  const r = await api(`/apps/${encodeURIComponent(id)}`, { method: 'PATCH', body: { name } });
587
689
  return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ App renamed to "${name}"`));
588
690
  }
691
+ case 'health-path': {
692
+ // Ruta de «lista» (readiness) de la app: la puerta del despliegue y el sondeo activo del edge. `off` la quita.
693
+ const ruta = a.positionals[1];
694
+ if (!id || !ruta)
695
+ throw new Error('usage: koigrid apps health-path <appId> </path|off>');
696
+ const healthCheckPath = ruta === 'off' ? null : ruta;
697
+ const r = await api(`/apps/${encodeURIComponent(id)}`, { method: 'PATCH', body: { healthCheckPath } });
698
+ return console.log(json ? JSON.stringify(r, null, 2) : green(healthCheckPath ? `✓ Health path set to ${healthCheckPath}` : '✓ Health path removed'));
699
+ }
700
+ case 'port': {
701
+ // Puerto del contenedor (PORT=<n>, ficha 4d8b02da): se aplica en el siguiente despliegue.
702
+ const n = Number(a.positionals[1]);
703
+ if (!id || !Number.isInteger(n) || n < 1 || n > 65535)
704
+ throw new Error('usage: koigrid apps port <appId> <1-65535>');
705
+ const r = await api(`/apps/${encodeURIComponent(id)}`, { method: 'PATCH', body: { port: n } });
706
+ return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ Port set to ${n} (applies on the next deploy)`));
707
+ }
708
+ case 'release': {
709
+ // FASE DE RELEASE (como Heroku release / Fly release_command): corre una vez por despliegue, con la imagen y el
710
+ // entorno de la app, ANTES de arrancar la versión nueva. Se aplica en el siguiente despliegue. `off` la quita.
711
+ const orden = a.positionals.slice(1).join(' ');
712
+ if (!id || !orden)
713
+ throw new Error('usage: koigrid apps release <appId> <command|off> (e.g. "npx prisma migrate deploy")');
714
+ const releaseCommand = orden === 'off' ? null : orden;
715
+ const r = await api(`/apps/${encodeURIComponent(id)}`, { method: 'PATCH', body: { releaseCommand } });
716
+ return console.log(json ? JSON.stringify(r, null, 2) : green(releaseCommand ? `✓ Release command set; it runs on the next deploy, before the new version starts` : '✓ Release command removed'));
717
+ }
718
+ case 'build-settings': {
719
+ // Ajustes de build de una app EXISTENTE (antes sólo al crearla). Se aplican en el siguiente despliegue; `off` quita uno.
720
+ const mapa = { 'build-cmd': 'buildCommand', 'install-cmd': 'installCommand', 'start-cmd': 'startCommand', 'root-dir': 'rootDirectory', 'node-version': 'nodeVersion', dockerfile: 'dockerfilePath', 'release-cmd': 'releaseCommand' };
721
+ const body = {};
722
+ for (const [flag, campo] of Object.entries(mapa))
723
+ if (typeof a.flags[flag] === 'string')
724
+ body[campo] = a.flags[flag] === 'off' ? null : a.flags[flag];
725
+ if (!id || !Object.keys(body).length)
726
+ throw new Error('usage: koigrid apps build-settings <appId> [--build-cmd C] [--install-cmd C] [--start-cmd C] [--root-dir D] [--node-version V] [--dockerfile PATH] [--release-cmd C] (value "off" removes it; applies on the next deploy)');
727
+ const r = await api(`/apps/${encodeURIComponent(id)}`, { method: 'PATCH', body });
728
+ return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ Build settings saved (${Object.keys(body).join(', ')}); they apply on the next deploy`));
729
+ }
730
+ case 'traffic-ramp': {
731
+ // Traspaso gradual al desplegar: N segundos para pasar los clientes de la versión anterior a la nueva. `off` = de golpe.
732
+ const v = a.positionals[1];
733
+ if (!id || !v)
734
+ throw new Error('usage: koigrid apps traffic-ramp <appId> <seconds 30-600|off>');
735
+ const trafficRampSeconds = v === 'off' ? 0 : Number(v);
736
+ if (!Number.isInteger(trafficRampSeconds))
737
+ throw new Error('seconds must be an integer between 30 and 600, or off');
738
+ const r = await api(`/apps/${encodeURIComponent(id)}`, { method: 'PATCH', body: { trafficRampSeconds } });
739
+ return console.log(json ? JSON.stringify(r, null, 2) : green(trafficRampSeconds ? `✓ Deploys will shift traffic gradually over ${trafficRampSeconds} s` : '✓ Deploys will switch traffic at once'));
740
+ }
741
+ case 'max-surge': {
742
+ // Despliegue por tandas: como mucho N réplicas nuevas a la vez junto a las viejas (maxSurge de Kubernetes). `off` = sin límite.
743
+ const v = a.positionals[1];
744
+ if (!id || !v)
745
+ throw new Error('usage: koigrid apps max-surge <appId> <replicas 1-100|off>');
746
+ const maxSurge = v === 'off' ? 0 : Number(v);
747
+ if (!Number.isInteger(maxSurge) || maxSurge < 0 || maxSurge > 100)
748
+ throw new Error('replicas must be an integer between 1 and 100, or off');
749
+ const r = await api(`/apps/${encodeURIComponent(id)}`, { method: 'PATCH', body: { maxSurge } });
750
+ if (json)
751
+ return console.log(JSON.stringify(r, null, 2));
752
+ // Lo que dice el SERVIDOR que hará (deployBatches), no lo que se pidió: se sube para no pasar del tope de tandas
753
+ // y fuera del reparto del edge no hay tandas.
754
+ const b = r.app?.deployBatches;
755
+ console.log(green(maxSurge ? `✓ maxSurge ${maxSurge} saved` : '✓ Deploys will start all new replicas at once when they fit'));
756
+ if (b && maxSurge && b.applies && b.effectiveMaxSurge)
757
+ console.log(` Redeploys: ${b.batches} batch(es) of up to ${b.effectiveMaxSurge} replica(s)`);
758
+ if (b?.note)
759
+ console.log(yellow(` ⚠ ${b.note}`));
760
+ return;
761
+ }
762
+ case 'deploy-analysis': {
763
+ // Análisis entre tandas: tras cada tanda se observan N s y se deshace si las réplicas nuevas dan claramente más 5xx
764
+ // que las viejas a la vez (Kayenta/Flagger). `off` = apagado.
765
+ const v = a.positionals[1];
766
+ if (!id || !v)
767
+ throw new Error('usage: koigrid apps deploy-analysis <appId> <seconds 30-600|off>');
768
+ const deployAnalysisSeconds = v === 'off' ? 0 : Number(v);
769
+ if (!Number.isInteger(deployAnalysisSeconds))
770
+ throw new Error('seconds must be an integer between 30 and 600, or off');
771
+ const r = await api(`/apps/${encodeURIComponent(id)}`, { method: 'PATCH', body: { deployAnalysisSeconds } });
772
+ if (json)
773
+ return console.log(JSON.stringify(r, null, 2));
774
+ const b = r.app?.deployBatches;
775
+ console.log(green(deployAnalysisSeconds ? `✓ Batched deploys will watch ${deployAnalysisSeconds} s of traffic after each batch` : '✓ Deploy analysis off'));
776
+ if (b?.analysisNote)
777
+ console.log(` ${b.analysisNote}`);
778
+ return;
779
+ }
589
780
  default: throw new Error(`unknown: apps ${sub}`);
590
781
  }
591
782
  }
@@ -2,10 +2,19 @@ import { createInterface } from 'node:readline/promises';
2
2
  import { api } from '../api.js';
3
3
  import { saveConfig, clearConfig, loadConfig } from '../config.js';
4
4
  import { green, dim } from '../output.js';
5
+ import { loginComoAgente } from '../agente.js';
5
6
  export async function login(flags) {
7
+ // `--email <email>`: sin token que pegar. Registro de agente (auth.md): enlace + código de 6 cifras que la persona
8
+ // aprueba en el navegador; el token se renueva solo hasta 30 días. Ideal para un agente que trabaja para alguien.
9
+ if (typeof flags.email === 'string') {
10
+ await loginComoAgente(flags.email, { api: typeof flags.api === 'string' ? flags.api : undefined, clientName: typeof flags.name === 'string' ? flags.name : undefined, avisar: (s) => console.log(s) });
11
+ const me = await api('/me');
12
+ console.log(green(`✓ Logged in as ${me?.user?.email || me?.email || flags.email} (agent access, renews automatically)`));
13
+ return;
14
+ }
6
15
  let token = typeof flags.token === 'string' ? flags.token : '';
7
16
  if (!token) {
8
- console.log(dim('Create an API key at https://koigrid.com/dashboard/keys and paste it here.'));
17
+ console.log(dim('Create an API key at https://koigrid.com/dashboard/keys and paste it here (or run `koigrid login --email <your email>`).'));
9
18
  const rl = createInterface({ input: process.stdin, output: process.stdout });
10
19
  token = (await rl.question('Token (koi_…): ')).trim();
11
20
  rl.close();