koigrid 0.22.0 → 0.24.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
@@ -4,6 +4,19 @@ All notable changes to the koigrid CLI are documented here. Format: [Keep a Chan
4
4
 
5
5
  ## [Unreleased]
6
6
 
7
+ ## [0.24.0] — 2026-11-30
8
+
9
+ ### Added
10
+
11
+ - `koigrid db metrics <id>` and `koigrid redis metrics <id>` accept `--since <ISO> [--until <ISO>]` for any window of up to 168 h (like CloudWatch GetMetricData StartTime/EndTime), instead of only the last `--hours`. A week at `--bucket 5m` now fits (2016 points).
12
+
13
+ ## [0.23.0] — 2026-11-30
14
+
15
+ ### Added
16
+
17
+ - `koigrid help search <what you want to do> [--with-help] [--json]`: finds the commands for a task described in plain words (e.g. `koigrid help search add a custom domain`), like `apropos` / `man -k`; `--with-help` also prints how to use the best match. Offline and deterministic: it searches the commands' own names, summaries and usage, no model involved. `koigrid apps domains --help` now has its own usage.
18
+ - `koigrid apps min-ready <id> <seconds|off>`: on a batched deploy (maxSurge), each batch must stay running with no restarts for that many seconds (up to 300) before more old replicas stop; if a new replica stops or restarts, the deploy rolls back with `deploy_unstable` and the previous version keeps serving — like Kubernetes `minReadySeconds`. Backed by `PATCH /apps/:id {minReadySeconds}`.
19
+
7
20
  ## [0.22.0] — 2026-11-29
8
21
 
9
22
  ### Added
@@ -801,6 +801,21 @@ export async function apps(a) {
801
801
  console.log(yellow(` ⚠ ${b.note}`));
802
802
  return;
803
803
  }
804
+ case 'min-ready': {
805
+ // Tiempo mínimo sano por tanda (minReadySeconds de Kubernetes): cada tanda sigue en marcha y sin reiniciarse N s
806
+ // antes de parar más viejas; si no, se deshace. `off` = apagado.
807
+ const v = a.positionals[1];
808
+ if (!id || !v)
809
+ throw new Error('usage: koigrid apps min-ready <appId> <seconds 1-300|off>');
810
+ const minReadySeconds = v === 'off' ? 0 : Number(v);
811
+ if (!Number.isInteger(minReadySeconds) || minReadySeconds < 0 || minReadySeconds > 300)
812
+ throw new Error('seconds must be an integer up to 300, or off');
813
+ const r = await api(`/apps/${encodeURIComponent(id)}`, { method: 'PATCH', body: { minReadySeconds } });
814
+ if (json)
815
+ return console.log(JSON.stringify(r, null, 2));
816
+ console.log(green(minReadySeconds ? `✓ Each batch must stay healthy ${minReadySeconds} s before more old replicas stop` : '✓ Min ready time off'));
817
+ return;
818
+ }
804
819
  case 'deploy-analysis': {
805
820
  // Análisis entre tandas: tras cada tanda se observan N s y se deshace si las réplicas nuevas dan claramente más 5xx
806
821
  // que las viejas a la vez (Kayenta/Flagger). `off` = apagado.
@@ -126,10 +126,10 @@ export async function db(a) {
126
126
  return output(l, false, { rows: l.map((x) => ({ member: x.member, role: x.role + (x.papel === 'dr' ? ' (dr)' : ''), allocated: x.measured ? `${x.allocatedGb} GB` : 'not measured', used: x.measured ? `${x.usedGb} GB` : '', pct: x.measured ? `${x.usedPct}%` : '', ago: x.measured ? `${x.measuredAgoSec}s` : '' })), columns: ['member', 'role', 'allocated', 'used', 'pct', 'ago'] });
127
127
  }
128
128
  case 'metrics': {
129
- // ?metric=a,b · ?bucket=5m&stat=max · ?hours (ficha c6f869c8, como CloudWatch GetMetricData)
129
+ // ?metric=a,b · ?bucket=5m&stat=max · ?hours o ?since=&until= (ficha c6f869c8, como CloudWatch GetMetricData)
130
130
  need();
131
131
  const q = new URLSearchParams();
132
- for (const k of ['hours', 'metric', 'bucket', 'stat'])
132
+ for (const k of ['hours', 'metric', 'bucket', 'stat', 'since', 'until'])
133
133
  if (a.flags[k] != null)
134
134
  q.set(k, String(a.flags[k]));
135
135
  return console.log(JSON.stringify(await api(`/databases/${encodeURIComponent(id)}/metrics${q.size ? `?${q}` : ''}`), null, 2));
@@ -49,10 +49,10 @@ export async function redis(a) {
49
49
  return process.exit(res.status ?? 0);
50
50
  }
51
51
  case 'metrics': {
52
- // ?metric=a,b · ?bucket=5m&stat=max · ?hours (ficha c6f869c8, como CloudWatch GetMetricData)
52
+ // ?metric=a,b · ?bucket=5m&stat=max · ?hours o ?since=&until= (ficha c6f869c8, como CloudWatch GetMetricData)
53
53
  need();
54
54
  const q = new URLSearchParams();
55
- for (const k of ['hours', 'metric', 'bucket', 'stat'])
55
+ for (const k of ['hours', 'metric', 'bucket', 'stat', 'since', 'until'])
56
56
  if (a.flags[k] != null)
57
57
  q.set(k, String(a.flags[k]));
58
58
  return console.log(JSON.stringify(await api(`/redis/${encodeURIComponent(id)}/metrics${q.size ? `?${q}` : ''}`), null, 2));
package/dist/help.js CHANGED
@@ -18,6 +18,7 @@ GLOBAL FLAGS
18
18
  --token <t> API token for this call (overrides stored; or KOIGRID_TOKEN)
19
19
  --api <url> API base URL (default https://koigrid.com/api/v1)
20
20
  -h, --help Show help
21
+ help search <task> [--with-help] Find the command for what you want to do (e.g. help search restore a database backup)
21
22
  -v, --version Show version
22
23
 
23
24
  Everything the CLI does is the koigrid API — an AI agent can run these commands directly.`;
@@ -35,3 +36,83 @@ export function buildCommandHelp(cmd, sub) {
35
36
  const subs = c.subs.length ? `\n\nSUBCOMMANDS\n ${c.subs.join(' · ')}\n\nRun \`koigrid ${c.name} <subcommand>\` (usage errors list each one's flags).` : '';
36
37
  return `koigrid ${c.name} — ${c.summary}${subs}`;
37
38
  }
39
+ const VACIAS = new Set(['a', 'an', 'the', 'to', 'of', 'for', 'in', 'on', 'my', 'and', 'or', 'with', 'how', 'do', 'i', 'can', 'is', 'it', 'me', 'from', 'by', 'el', 'la', 'los', 'las', 'un', 'una', 'de', 'del', 'en', 'mi', 'y', 'o', 'con', 'como', 'para', 'por', 'que', 'se', 'al', 'quiero']);
40
+ // Palabras de la tarea que el manifest dice de otra forma. Pocas y obvias: el resto lo resuelve el resumen.
41
+ const SINONIMOS = {
42
+ postgres: ['db'], postgresql: ['db'], database: ['db'], sql: ['db', 'query'], base: ['db'], datos: ['db'],
43
+ cache: ['redis'], valkey: ['redis'], bucket: ['storage'], s3: ['storage'], object: ['storage'], cron: ['jobs'],
44
+ schedule: ['jobs'], secret: ['config'], env: ['env', 'config'], variable: ['env'], domain: ['domains'],
45
+ dominio: ['domains'], desplegar: ['deploy'], ship: ['deploy'], publish: ['deploy'], log: ['logs'], copia: ['backups'],
46
+ backup: ['backups'], restaurar: ['restore'], uptime: ['checks'], monitor: ['checks'], key: ['tokens'], token: ['tokens'],
47
+ borrar: ['rm'], delete: ['rm'], remove: ['rm'], list: ['ls'], listar: ['ls'], create: ['create'], crear: ['create'],
48
+ };
49
+ function palabras(texto) {
50
+ return texto.toLowerCase().normalize('NFD').replace(/[̀-ͯ]/g, '').split(/[^a-z0-9]+/).filter(Boolean);
51
+ }
52
+ /** Raíz burda (rotate/rotation/rotating → rotat, deploys → deploy), como el stemmer de un buscador, sin diccionario. */
53
+ function raiz(w) {
54
+ for (const suf of ['ations', 'ation', 'ions', 'ing', 'ion', 'ed', 'es', 'e', 's'])
55
+ if (w.length - suf.length >= 4 && w.endsWith(suf))
56
+ return w.slice(0, -suf.length);
57
+ return w;
58
+ }
59
+ /** ¿La palabra de la tarea casa con la del manifest? Igual, o la misma raíz. */
60
+ function casa(q, w) {
61
+ return q === w || raiz(q) === raiz(w);
62
+ }
63
+ function terminos(consulta) {
64
+ return palabras(consulta).filter((p) => !VACIAS.has(p)).map((p) => [p, ...(SINONIMOS[p] ?? [])]);
65
+ }
66
+ function entradas() {
67
+ const out = [];
68
+ for (const c of CLI_COMMANDS) {
69
+ const nombre = [c.name, ...(c.aliases ?? [])].flatMap(palabras);
70
+ const resumen = palabras(c.summary);
71
+ const rutas = c.endpoints.flatMap(palabras);
72
+ out.push({ command: `koigrid ${c.name}`, summary: c.summary, help: buildCommandHelp(c.name) ?? '', campos: [[nombre, 5], [resumen, 2], [rutas, 1]], propios: null });
73
+ for (const s of c.subs) {
74
+ const uso = c.usage?.[s] ? palabras(c.usage[s]) : [];
75
+ out.push({
76
+ command: `koigrid ${c.name} ${s}`, summary: c.summary, help: buildCommandHelp(c.name, s) ?? '',
77
+ campos: [[palabras(s), 5], [nombre, 3], [uso, 2], [resumen, 1], [rutas, 1]],
78
+ // Un subcomando sólo sale si casa algo SUYO (su nombre o su usage); si no, ya lo representa el comando.
79
+ propios: [...palabras(s), ...uso],
80
+ });
81
+ }
82
+ }
83
+ return out;
84
+ }
85
+ /** Los comandos (y subcomandos) que mejor encajan con la tarea, de más a menos. [] si nada casa. */
86
+ export function buscarComandos(consulta, max = 5) {
87
+ const qs = terminos(consulta);
88
+ if (!qs.length)
89
+ return [];
90
+ const todas = entradas();
91
+ const casaAlguna = (alt, ws) => ws.some((w) => alt.some((q) => casa(q, w)));
92
+ // Una palabra que sale en casi todo («add», «ls») distingue poco; una rara («domain») mucho: IDF, como un buscador.
93
+ const idf = qs.map((alt) => {
94
+ const df = todas.filter((e) => e.campos.some(([ws]) => casaAlguna(alt, ws))).length;
95
+ return df ? Math.log(1 + todas.length / df) : 0;
96
+ });
97
+ const out = [];
98
+ for (const e of todas) {
99
+ if (e.propios && !qs.some((alt) => casaAlguna(alt, e.propios)))
100
+ continue;
101
+ let total = 0;
102
+ let casadas = 0;
103
+ qs.forEach((alt, i) => {
104
+ let mejor = 0;
105
+ for (const [ws, peso] of e.campos)
106
+ if (casaAlguna(alt, ws))
107
+ mejor = Math.max(mejor, peso);
108
+ if (mejor) {
109
+ total += mejor * idf[i];
110
+ casadas++;
111
+ }
112
+ });
113
+ // Que case la mayoría de la tarea pesa más que muchas veces una sola palabra.
114
+ if (casadas)
115
+ out.push({ command: e.command, summary: e.summary, score: Math.round(total * (casadas / qs.length) * 100) / 100, help: e.help });
116
+ }
117
+ return out.sort((a, b) => b.score - a.score || a.command.length - b.command.length).slice(0, max);
118
+ }
package/dist/index.js CHANGED
@@ -2,7 +2,7 @@
2
2
  // Entry del CLI. Dispatch data-driven desde el manifest (resolveCommand) + registro de handlers.
3
3
  // Añadir un comando = fichero en commands/ + entrada en registry.ts + manifest.ts (los guards lo obligan).
4
4
  import { parseArgs, vigilarFlags } from './args.js';
5
- import { buildHelp, buildCommandHelp } from './help.js';
5
+ import { buildHelp, buildCommandHelp, buscarComandos } from './help.js';
6
6
  import { ApiError } from './api.js';
7
7
  import { resolveCommand, CLI_COMMANDS } from './manifest.js';
8
8
  import { HANDLERS } from './registry.js';
@@ -24,6 +24,30 @@ async function main() {
24
24
  return;
25
25
  }
26
26
  // Ayuda humana, o `help --json` → manifest completo para que un AGENTE IA introspeccione TODO el CLI.
27
+ // `koigrid help search <tarea> [--with-help]`: los comandos que encajan con lo que quieres hacer (ficha 9facae2c).
28
+ if (a.cmd === 'help' && a.sub === 'search') {
29
+ const consulta = a.positionals.join(' ');
30
+ if (!consulta) {
31
+ console.error(red('Usage: koigrid help search <what you want to do> [--with-help] [--json]'));
32
+ process.exit(1);
33
+ }
34
+ const hallados = buscarComandos(consulta);
35
+ if (a.flags.json) {
36
+ console.log(JSON.stringify(hallados.map(({ help, ...h }) => (a.flags['with-help'] ? { ...h, help } : h)), null, 2));
37
+ return;
38
+ }
39
+ if (!hallados.length) {
40
+ console.log(`No command matches "${consulta}". Run \`koigrid --help\` for the full list.`);
41
+ return;
42
+ }
43
+ for (const h of hallados)
44
+ console.log(` ${h.command.padEnd(34)} ${h.summary}`);
45
+ if (a.flags['with-help'])
46
+ console.log(`\n${hallados[0].help}`);
47
+ else
48
+ console.log(`\nAdd --with-help to see how to use the first one.`);
49
+ return;
50
+ }
27
51
  if (!a.cmd || a.cmd === 'help' || a.flags.help || a.flags.h) {
28
52
  // `koigrid <cmd> [sub] --help`: la ayuda de ese comando o subcomando (ficha f76082de); sin comando, la global.
29
53
  const propia = a.cmd && a.cmd !== 'help' && !a.flags.json ? buildCommandHelp(a.cmd, a.sub) : null;
package/dist/manifest.js CHANGED
@@ -19,8 +19,11 @@ export const CLI_COMMANDS = [
19
19
  Waiting waits until live or failed and prints the URL or the error with the end of the log (default)
20
20
  --no-wait (or --detach) returns at once · --timeout <min> (default 20) · with --json it returns at once unless --wait
21
21
  Other --project <id> · --json`,
22
+ domains: `koigrid apps domains <app-id> add <domain> | move <domain> | rm <domain> | ls | verify
23
+ Custom domain on your app: add it, create the DNS record it prints (CNAME to <slug>.apps…), and koigrid issues the
24
+ TLS certificate. move <domain> takes it from another of your apps, keeping its certificate. verify re-checks the DNS.`,
22
25
  },
23
- subs: ['ls', 'deploy', 'logs', 'http', 'requests', 'rm', 'rename', 'health-path', 'port', 'release', 'build-settings', 'traffic-ramp', 'max-surge', 'deploy-analysis', 'scale', 'resize', 'autoscale', 'scale-out', 'env', 'domains', 'volumes', 'cdn', 'cache', 'protection', 'retention', 'github', 'github-repos', 'hooks', 'rollback', 'pause', 'resume', 'restore', 'migrate', 'deployments', 'previews', 'preview', 'rules', 'rule', 'rule-rm', 'rule-toggle', 'registry', 'loadtest'],
26
+ subs: ['ls', 'deploy', 'logs', 'http', 'requests', 'rm', 'rename', 'health-path', 'port', 'release', 'build-settings', 'traffic-ramp', 'max-surge', 'min-ready', 'deploy-analysis', 'scale', 'resize', 'autoscale', 'scale-out', 'env', 'domains', 'volumes', 'cdn', 'cache', 'protection', 'retention', 'github', 'github-repos', 'hooks', 'rollback', 'pause', 'resume', 'restore', 'migrate', 'deployments', 'previews', 'preview', 'rules', 'rule', 'rule-rm', 'rule-toggle', 'registry', 'loadtest'],
24
27
  endpoints: ['apps', 'apps/[id]', 'apps/[id]/deployments', 'apps/[id]/source-upload', 'apps/[id]/logs', 'apps/[id]/http', 'apps/[id]/requests', 'apps/[id]/scale', 'apps/[id]/resources', 'apps/[id]/autoscale', 'apps/[id]/scale-out', 'apps/[id]/env', 'apps/[id]/env/verify', 'apps/[id]/domains', 'apps/[id]/domains/verify', 'apps/[id]/volumes', 'apps/[id]/volumes/[volId]', 'apps/[id]/volumes/[volId]/backups', 'apps/[id]/volumes/[volId]/backups/[backupId]/restore', 'apps/[id]/cdn', 'apps/[id]/cache', 'apps/[id]/cache/purge', 'apps/[id]/protection', 'apps/[id]/protection/evaluate', 'apps/[id]/retention', 'apps/[id]/github', 'github/repos', 'apps/[id]/deploy-hooks', 'apps/[id]/deploy-hooks/[hookId]', 'apps/[id]/rollback', 'apps/[id]/pause', 'apps/[id]/resume', 'apps/[id]/restore', 'apps/[id]/migrate', 'apps/[id]/previews', 'apps/[id]/rules', 'apps/[id]/rules/[ruleId]', 'apps/[id]/registry', 'apps/[id]/loadtest'],
25
28
  },
26
29
  { name: 'db', aliases: ['databases', 'database'], product: 'databases', summary: 'Managed Postgres (HA) — incl. SQL console (db query/tables) + branching (db branch) + managed restore (db restore-dump)', subs: ['ls', 'info', 'create', 'rm', 'rename', 'pause', 'resume', 'retention', 'weekly', 'monthly', 'url', 'connect', 'metrics', 'events', 'top-queries', 'slots', 'logs', 'backups', 'restore', 'restore-dump', 'fix-ownership', 'analyze', 'import', 'restore-status', 'ext', 'replicas', 'dr-copy', 'network', 'recovery-cert', 'backup-key', 'backup-access', 'pub', 'query', 'tables', 'branch', 'roles', 'params', 'pooler', 'rotation', 'patching', 'sync', 'slot-cap', 'resize', 'apply-config', 'maintenance', 'subs', 'data', 'rpc'], endpoints: ['databases', 'databases/[id]', 'databases/[id]/pause', 'databases/[id]/resume', 'databases/[id]/connection', 'databases/[id]/backups', 'databases/[id]/restore', 'databases/[id]/restore-dump', 'databases/[id]/restore-dump/upload-url', 'databases/[id]/restore-dump/[jobId]', 'databases/[id]/fix-ownership', 'databases/[id]/analyze', 'databases/[id]/metrics', 'databases/[id]/events', 'databases/[id]/queries', 'databases/[id]/replication-slots', 'databases/[id]/logs', 'databases/[id]/extensions', 'databases/[id]/replicas', 'databases/[id]/dr-copy', 'databases/[id]/network', 'databases/recovery-certificate', 'databases/[id]/backups/encryption-key', 'databases/[id]/backups/access', 'databases/[id]/publications', 'databases/[id]/subscriptions', 'databases/[id]/subscriptions/preflight', 'databases/[id]/subscriptions/verify', 'databases/[id]/subscriptions/verify/[verificationId]', 'databases/[id]/subscriptions/sync-sequences', 'databases/[id]/apply-config', 'databases/[id]/maintenance/apply', 'databases/[id]/maintenance/defer', 'databases/[id]/query', 'databases/[id]/branches', 'databases/[id]/branches/[branchId]', 'databases/[id]/branches/[branchId]/reset', 'databases/[id]/roles', 'databases/[id]/roles/[roleName]', 'databases/[id]/parameters', 'databases/[id]/pooler', 'databases/[id]/rotation', 'databases/[id]/rotation/rotate', 'databases/[id]/rotation/migrate', 'databases/[id]/data/[table]', 'databases/[id]/rpc/[fn]'] },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "koigrid",
3
- "version": "0.22.0",
3
+ "version": "0.24.0",
4
4
  "description": "koigrid CLI — deploy apps, databases, redis, storage and more from your terminal (or your AI agent).",
5
5
  "bin": {
6
6
  "koigrid": "dist/index.js"