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.
@@ -0,0 +1,105 @@
1
+ import { api } from '../api.js';
2
+ import { output, green } from '../output.js';
3
+ // koigrid experiments — experimentos A/B sobre flags multivariantes (ficha cdb42b0e, docs/products/FLAGS.md §Experimentos).
4
+ // Todo se fija ANTES de arrancar: hipótesis, métrica principal, métricas de seguridad y muestra por variante.
5
+ export async function experiments(a) {
6
+ const json = !!a.flags.json;
7
+ const sub = a.sub || 'ls';
8
+ const key = a.positionals[0];
9
+ const exigir = (uso) => { if (!key)
10
+ throw new Error(`usage: koigrid experiments ${uso}`); };
11
+ if (sub === 'ls' || sub === 'list') {
12
+ const r = await api('/experiments');
13
+ const l = r.experiments || [];
14
+ return output(l, json, {
15
+ rows: l.map((x) => ({ key: x.key, flag: x.flagKey, status: x.status, metric: x.primaryMetric, sample: x.minSamplePerVariant, winner: x.winner ?? '' })),
16
+ columns: ['key', 'flag', 'status', 'metric', 'sample', 'winner'],
17
+ });
18
+ }
19
+ if (sub === 'create') {
20
+ exigir('create <key> --flag <flagKey> --hypothesis "…" --metric <primary> [--guardrails a,b] (--sample N | --baseline 0.024 --mde 0.5)');
21
+ const body = { key, flagKey: a.flags.flag, hypothesis: a.flags.hypothesis, primaryMetric: a.flags.metric };
22
+ if (a.flags.guardrails)
23
+ body.guardrailMetrics = String(a.flags.guardrails).split(',').map((s) => s.trim()).filter(Boolean);
24
+ if (a.flags.sample !== undefined)
25
+ body.minSamplePerVariant = Number(a.flags.sample);
26
+ if (a.flags.baseline !== undefined)
27
+ body.baselineRate = Number(a.flags.baseline);
28
+ if (a.flags.mde !== undefined)
29
+ body.minDetectableEffect = Number(a.flags.mde);
30
+ const r = await api('/experiments', { method: 'POST', body });
31
+ return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ Experiment "${key}" created (draft) · ${r.experiment?.minSamplePerVariant} units per variant`));
32
+ }
33
+ if (sub === 'show' || sub === 'get') {
34
+ exigir('show <key>');
35
+ const r = await api(`/experiments/${encodeURIComponent(key)}`);
36
+ return console.log(JSON.stringify(r.experiment, null, 2));
37
+ }
38
+ if (sub === 'edit') {
39
+ exigir('edit <key> [--hypothesis "…"] [--guardrails a,b] [--sample N] (only while draft)');
40
+ const body = {};
41
+ if (a.flags.hypothesis)
42
+ body.hypothesis = String(a.flags.hypothesis);
43
+ if (a.flags.guardrails)
44
+ body.guardrailMetrics = String(a.flags.guardrails).split(',').map((s) => s.trim()).filter(Boolean);
45
+ if (a.flags.sample !== undefined)
46
+ body.minSamplePerVariant = Number(a.flags.sample);
47
+ await api(`/experiments/${encodeURIComponent(key)}`, { method: 'PATCH', body });
48
+ return console.log(green(`✓ ${key} updated`));
49
+ }
50
+ if (sub === 'start' || sub === 'stop') {
51
+ exigir(`${sub} <key>`);
52
+ const r = await api(`/experiments/${encodeURIComponent(key)}/${sub}`, { method: 'POST' });
53
+ return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ ${key}: ${r.experiment?.status}`));
54
+ }
55
+ if (sub === 'decide') {
56
+ exigir('decide <key> --winner <variant|none> --note "why"');
57
+ const w = a.flags.winner === undefined || String(a.flags.winner) === 'none' ? null : String(a.flags.winner);
58
+ const r = await api(`/experiments/${encodeURIComponent(key)}/decide`, { method: 'POST', body: { winner: w, note: a.flags.note } });
59
+ return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ ${key} decided: ${w ?? 'no difference'}`));
60
+ }
61
+ if (sub === 'expose') {
62
+ exigir('expose <key> <unit>');
63
+ const r = await api(`/experiments/${encodeURIComponent(key)}/exposures`, { method: 'POST', body: { unit: a.positionals[1] } });
64
+ return console.log(json ? JSON.stringify(r, null, 2) : `${a.positionals[1]} → ${r.variant ?? 'not in the test'}${r.recorded ? '' : ' (already recorded)'}`);
65
+ }
66
+ if (sub === 'convert') {
67
+ exigir('convert <key> <unit> <metric>');
68
+ const r = await api(`/experiments/${encodeURIComponent(key)}/conversions`, { method: 'POST', body: { unit: a.positionals[1], metric: a.positionals[2] } });
69
+ return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ ${a.positionals[2]} ${r.recorded ? 'recorded' : 'already recorded'}`));
70
+ }
71
+ if (sub === 'results') {
72
+ exigir('results <key>');
73
+ const r = await api(`/experiments/${encodeURIComponent(key)}/results`);
74
+ if (json)
75
+ return console.log(JSON.stringify(r, null, 2));
76
+ const m = r.experiment?.primaryMetric;
77
+ const rows = (r.variants || []).map((v) => ({ variant: v.variant, exposed: v.exposed, [m]: v.conversions?.[m] ?? 0, rate: v.exposed ? `${(((v.conversions?.[m] ?? 0) / v.exposed) * 100).toFixed(2)}%` : '—' }));
78
+ console.log(`${key} · ${r.experiment?.status} · target ${r.experiment?.minSamplePerVariant} per variant`);
79
+ output(rows, false, { rows, columns: ['variant', 'exposed', m, 'rate'] });
80
+ const an = r.analysis;
81
+ if (!an)
82
+ return;
83
+ const pc = (x) => `${(x * 100).toFixed(1)}%`;
84
+ const cmp = (an.primary || []).map((c) => ({
85
+ variant: c.variant,
86
+ 'vs control': c.relativeLift == null ? '—' : `${c.relativeLift >= 0 ? '+' : ''}${pc(c.relativeLift)}`,
87
+ interval: c.relativeInterval ? `${pc(c.relativeInterval[0])} … ${pc(c.relativeInterval[1])}` : '—',
88
+ p: c.alwaysValidPValue == null ? '—' : c.alwaysValidPValue.toFixed(3),
89
+ verdict: c.verdict,
90
+ }));
91
+ if (cmp.length) {
92
+ console.log('');
93
+ output(cmp, false, { rows: cmp, columns: ['variant', 'vs control', 'interval', 'p', 'verdict'] });
94
+ }
95
+ if (an.srm?.measured)
96
+ console.log(`\nsample ratio: p=${an.srm.pValue < 0.001 ? an.srm.pValue.toExponential(1) : an.srm.pValue.toFixed(3)}${an.srm.mismatch ? ' ⚠️ MISMATCH' : ' ok'}`);
97
+ return console.log(`\n${an.verdict}: ${an.summary}`);
98
+ }
99
+ if (sub === 'rm' || sub === 'delete') {
100
+ exigir('rm <key> (only while draft)');
101
+ await api(`/experiments/${encodeURIComponent(key)}`, { method: 'DELETE' });
102
+ return console.log(green(`✓ Deleted ${key}`));
103
+ }
104
+ throw new Error(`unknown: experiments ${sub}`);
105
+ }
@@ -62,6 +62,24 @@ export async function flags(a) {
62
62
  await api(`/flags/${encodeURIComponent(key)}`, { method: 'PATCH', body: { rules: [{ attribute, op, values }] } });
63
63
  return console.log(green(`✓ ${key}: ${attribute} ${op} [${values.join(', ')}]`));
64
64
  }
65
+ if (sub === 'variants') {
66
+ // Flag multivariante para un experimento A/B: koigrid flags variants <key> control=50,home=50 (o --clear)
67
+ const key = a.positionals[0];
68
+ if (!key)
69
+ throw new Error('usage: koigrid flags variants <key> <variant=weight,…> (o --clear)');
70
+ if (a.flags.clear) {
71
+ await api(`/flags/${encodeURIComponent(key)}`, { method: 'PATCH', body: { variants: null } });
72
+ return console.log(green(`✓ ${key}: variants cleared (on/off flag again)`));
73
+ }
74
+ const variants = String(a.positionals[1] || '').split(',').map((p) => p.trim()).filter(Boolean).map((p) => {
75
+ const [k, w] = p.split('=');
76
+ return { key: (k || '').trim(), weight: Number(w) };
77
+ });
78
+ if (variants.length < 2 || variants.some((v) => !v.key || !Number.isFinite(v.weight)))
79
+ throw new Error('usage: koigrid flags variants <key> control=50,home=50');
80
+ await api(`/flags/${encodeURIComponent(key)}`, { method: 'PATCH', body: { variants } });
81
+ return console.log(green(`✓ ${key}: ${variants.map((v) => `${v.key} ${v.weight}`).join(' · ')}`));
82
+ }
65
83
  if (sub === 'eval' || sub === 'evaluate') {
66
84
  const context = a.flags.context ? String(a.flags.context) : '';
67
85
  const attributes = {};
@@ -78,8 +96,9 @@ export async function flags(a) {
78
96
  if (json)
79
97
  return console.log(JSON.stringify(r, null, 2));
80
98
  const f = r.flags || {};
81
- const rows = Object.keys(f).map((k) => ({ key: k, value: f[k] ? 'true' : 'false' }));
82
- return output(rows, false, { rows, columns: ['key', 'value'] });
99
+ const v = r.variants || {};
100
+ const rows = Object.keys(f).map((k) => ({ key: k, value: f[k] ? 'true' : 'false', variant: k in v ? (v[k] ?? '—') : '' }));
101
+ return output(rows, false, { rows, columns: ['key', 'value', 'variant'] });
83
102
  }
84
103
  throw new Error(`unknown: flags ${sub}`);
85
104
  }
@@ -0,0 +1,28 @@
1
+ import { api } from '../api.js';
2
+ import { green } from '../output.js';
3
+ /**
4
+ * Quién puede conectarse a una base o caché (ficha 5120dcde): `<cmd> network <id>` muestra · `--allow ip,cidr,…` la
5
+ * restringe a esas IPs (más la flota de koigrid) · `--only-koigrid` sólo desde koigrid · `--public` la abre a todos.
6
+ */
7
+ export async function network(base, cmd, id, a, json) {
8
+ const ruta = `/${base}/${encodeURIComponent(id)}/network`;
9
+ let body = null;
10
+ if (a.flags.public)
11
+ body = { allowedIps: null };
12
+ else if (a.flags['only-koigrid'])
13
+ body = { allowedIps: [] };
14
+ else if (a.flags.allow)
15
+ body = { allowedIps: String(a.flags.allow).split(',').map((s) => s.trim()).filter(Boolean) };
16
+ const r = body ? await api(ruta, { method: 'PUT', body }) : await api(ruta);
17
+ if (json)
18
+ return console.log(JSON.stringify(r, null, 2));
19
+ const n = r.network ?? {};
20
+ const linea = n.access === 'public' ? 'public: any IP (password + TLS)' : `restricted: ${n.allowedIps?.length ? n.allowedIps.join(', ') : '(none)'} + the koigrid fleet`;
21
+ if (!body)
22
+ return console.log(`${linea}\n change: koigrid ${cmd} network ${id} --allow 1.2.3.4,10.0.0.0/24 | --only-koigrid | --public`);
23
+ console.log(green(`✓ ${linea}`));
24
+ if (n.applied === false)
25
+ console.log(' ⚠️ not applied on every machine yet: retried automatically within 10 minutes');
26
+ for (const w of n.warnings ?? [])
27
+ console.log(` ⚠️ ${w}`);
28
+ }
@@ -1,6 +1,6 @@
1
1
  import { api } from '../api.js';
2
2
  import { output, green } from '../output.js';
3
- // koigrid notifications — preferencias de aviso por email (por categoría: alarms/anomalies/spend/jobs/heartbeats/checks).
3
+ // koigrid notifications — preferencias de aviso por email (por categoría: alarms/anomalies/spend/jobs/heartbeats/checks/deploys/maintenance).
4
4
  // koigrid notifications ls
5
5
  // koigrid notifications set spend off (o on)
6
6
  export async function notifications(a) {
@@ -13,7 +13,7 @@ export async function notifications(a) {
13
13
  if (sub === 'set') {
14
14
  const category = a.positionals[0], state = a.positionals[1];
15
15
  if (!category || (state !== 'on' && state !== 'off'))
16
- throw new Error('usage: koigrid notifications set <alarms|anomalies|spend|jobs|heartbeats|checks> <on|off>');
16
+ throw new Error('usage: koigrid notifications set <alarms|anomalies|spend|jobs|heartbeats|checks|deploys|maintenance> <on|off>');
17
17
  const r = await api('/notifications/preferences', { method: 'PUT', body: { category, emailEnabled: state === 'on' } });
18
18
  return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ ${category} email notifications ${state}`));
19
19
  }
@@ -0,0 +1,37 @@
1
+ import { api } from '../api.js';
2
+ import { output } from '../output.js';
3
+ // koigrid pricing — la tarifa (precio por recurso reservado) y el presupuesto de lo que costaría algo ANTES de
4
+ // crearlo. Sin credenciales: el precio es público (lib/billing/tarifa.ts).
5
+ // koigrid pricing → la tarifa
6
+ // koigrid pricing quote --memory 1024 --cpus 1 [--disk 10] [--copies 2] [--storage 50]
7
+ // koigrid pricing quote --json '{"resources":[…]}'
8
+ export async function pricing(a) {
9
+ const json = !!a.flags.json && a.flags.json === true;
10
+ const sub = a.positionals[0];
11
+ if (sub === 'quote') {
12
+ let body;
13
+ if (typeof a.flags.json === 'string')
14
+ body = JSON.parse(a.flags.json);
15
+ else {
16
+ const n = (k) => (a.flags[k] !== undefined ? Number(a.flags[k]) : undefined);
17
+ body = {
18
+ resources: [{ memoryMb: n('memory') ?? 0, cpus: n('cpus') ?? 0, diskGb: n('disk'), copies: n('copies') }],
19
+ objectStorageGb: n('storage'),
20
+ };
21
+ }
22
+ const r = await api('/pricing/quote', { method: 'POST', body, anon: true });
23
+ if (json)
24
+ return console.log(JSON.stringify(r, null, 2));
25
+ output(r.lines ?? [], false, {
26
+ rows: (r.lines ?? []).map((l) => ({ name: l.name ?? '—', copies: l.desglose?.copias, ram: l.desglose?.ramUsd, vcpu: l.desglose?.vcpuUsd, disk: l.desglose?.discoUsd, monthly: l.mensualUsd })),
27
+ columns: ['name', 'copies', 'ram', 'vcpu', 'disk', 'monthly'],
28
+ });
29
+ return console.log(`\nTotal: $${r.monthlyUsd}/month ($${r.hourlyUsd}/hour)${r.objectStorageUsd ? ` · object storage $${r.objectStorageUsd}` : ''}`);
30
+ }
31
+ const r = await api('/pricing', { anon: true });
32
+ if (json)
33
+ return console.log(JSON.stringify(r, null, 2));
34
+ const p = r.prices ?? {};
35
+ console.log(`RAM $${p.ramGbMonth}/GB·month${p.vcpuMonth ? ` · vCPU $${p.vcpuMonth}/month` : ' (shared vCPU included)'} · disk $${p.diskGbMonth}/GB·month · object storage $${p.objectStorageGbMonth}/GB·month · egress included`);
36
+ console.log(`Billed per hour (${r.hoursPerMonth} h/month), only while a resource exists.`);
37
+ }
@@ -1,6 +1,7 @@
1
1
  import { api } from '../api.js';
2
2
  import { output, green } from '../output.js';
3
3
  import { proyectoDeFlags } from '../proyecto.js';
4
+ import { network } from './network.js';
4
5
  export async function redis(a) {
5
6
  const json = !!a.flags.json, sub = a.sub || 'ls', id = a.positionals[0];
6
7
  const need = () => { if (!id)
@@ -79,6 +80,58 @@ export async function redis(a) {
79
80
  const r = await api(`/redis/${encodeURIComponent(id)}/restore`, { method: 'POST', body });
80
81
  return console.log(json ? JSON.stringify(r, null, 2) : green('✓ Restoring to a new cache…'));
81
82
  }
83
+ case 'network': {
84
+ need();
85
+ return network('redis', 'redis', id, a, json);
86
+ }
87
+ case 'password': {
88
+ // Rotar la contraseña sin corte (ficha dd6ffe39): `rotate` añade una nueva (valen las dos), `retire` quita la
89
+ // anterior cuando las apps ya la usan (se niega si alguien se quedaría fuera, salvo --force). Sin paso, el estado.
90
+ need();
91
+ const step = a.positionals[1];
92
+ const usos = (l = []) => {
93
+ for (const u of l)
94
+ console.log(` · ${u.type} ${u.name}: ${u.via === 'reference' ? 'por referencia' : u.pastedIsPrevious ? 'PEGADA (la anterior: edítala)' : 'pegada (ya la nueva)'}${u.redeployedSinceRotation === true ? ' · redesplegada' : u.redeployedSinceRotation === false ? ' · SIN redesplegar' : ''}`);
95
+ };
96
+ if (!step) {
97
+ const r = await api(`/redis/${encodeURIComponent(id)}/password`);
98
+ if (json)
99
+ return console.log(JSON.stringify(r, null, 2));
100
+ console.log(r.rotation?.inProgress ? `Rotación en curso desde ${r.rotation.rotatedAt}: valen la nueva y la anterior` : 'Sin rotación en curso');
101
+ return usos(r.usedBy);
102
+ }
103
+ if (step !== 'rotate' && step !== 'retire')
104
+ throw new Error('usage: koigrid redis password <id> [rotate|retire [--force]]');
105
+ const r = await api(`/redis/${encodeURIComponent(id)}/password`, { method: 'POST', body: { step, ...(a.flags.force ? { force: true } : {}) } });
106
+ if (json)
107
+ return console.log(JSON.stringify(r, null, 2));
108
+ for (const p of r.steps || [])
109
+ console.log(` ${p.ok ? '✓' : '✗'} ${p.step}: ${p.detail}`);
110
+ usos(r.usedBy);
111
+ if (r.next)
112
+ console.log(` ${r.next}`);
113
+ return console.log(r.ok ? green(step === 'rotate' ? '✓ Contraseña rotada' : '✓ Contraseña anterior retirada') : '✗ No se completó');
114
+ }
115
+ case 'dr-copy': {
116
+ // Copia de desastre (ficha c21ac56a): `redis dr-copy <id>` muestra · `add` la pide · `rm` la retira.
117
+ need();
118
+ const act = a.positionals[1];
119
+ if (!act) {
120
+ const r = await api(`/redis/${encodeURIComponent(id)}/dr-copy`);
121
+ if (json)
122
+ return console.log(JSON.stringify(r, null, 2));
123
+ return console.log(r.drCopy ? `${r.drCopy.member} · ${r.drCopy.provider} · ${r.drCopy.state} · promotion: ${r.drCopy.promotion}` : 'no disaster-recovery copy');
124
+ }
125
+ if (act === 'add') {
126
+ const r = await api(`/redis/${encodeURIComponent(id)}/dr-copy`, { method: 'POST' });
127
+ return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ Adding disaster-recovery copy ${r.drCopy?.member} in ${r.drCopy?.provider} (no downtime; follow with: koigrid redis dr-copy ${id})`));
128
+ }
129
+ if (act === 'rm' || act === 'remove') {
130
+ const r = await api(`/redis/${encodeURIComponent(id)}/dr-copy`, { method: 'DELETE' });
131
+ return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ Removed disaster-recovery copy ${r.drCopy?.member}`));
132
+ }
133
+ throw new Error('usage: koigrid redis dr-copy <id> [add|rm]');
134
+ }
82
135
  case 'rename': {
83
136
  need();
84
137
  const name = a.positionals[1];
@@ -87,6 +140,15 @@ export async function redis(a) {
87
140
  const r = await api(`/redis/${encodeURIComponent(id)}`, { method: 'PATCH', body: { name } });
88
141
  return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ Cache renamed to "${name}"`));
89
142
  }
143
+ case 'resize': {
144
+ // Memoria de una caché viva, en caliente (sin reinicio ni failover). Múltiplo de 256 MB.
145
+ need();
146
+ const mb = Number(a.positionals[1]);
147
+ if (!Number.isInteger(mb))
148
+ throw new Error('usage: koigrid redis resize <id> <memoryMb> (multiple of 256, e.g. 1024)');
149
+ const r = await api(`/redis/${encodeURIComponent(id)}`, { method: 'PATCH', body: { memoryMb: mb } });
150
+ return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ Cache memory set to ${mb} MB (in place, no downtime)`));
151
+ }
90
152
  default: throw new Error(`unknown: redis ${sub}`);
91
153
  }
92
154
  }
@@ -67,5 +67,20 @@ export async function registry(a) {
67
67
  // ayuda: imprime el comando docker login (el push/pull es por docker, no por este CLI)
68
68
  return console.log('docker login registry.koigrid.com -u token -p <koi-token-with-registry:read/write>\n# luego: docker tag <img> registry.koigrid.com/<name>:<tag> && docker push registry.koigrid.com/<name>:<tag>');
69
69
  }
70
+ if (sub === 'policy') {
71
+ // Retención por repositorio (como una lifecycle policy de ECR): `policy <name>` la enseña, `policy <name> 20`
72
+ // la fija y `policy <name> plan` vuelve a la del plan. Lo que sirve un despliegue vivo se conserva siempre.
73
+ const repo = a.positionals[0];
74
+ const v = a.positionals[1];
75
+ if (!repo)
76
+ throw new Error('usage: koigrid registry policy <name> [<keep-last>|plan]');
77
+ const path = `/registry/repositories/${Buffer.from(repo).toString('base64url')}/policy`;
78
+ const r = v === undefined
79
+ ? await api(path)
80
+ : await api(path, { method: 'PUT', body: { keepLast: v === 'plan' ? null : Number(v) } });
81
+ if (json)
82
+ return console.log(JSON.stringify(r, null, 2));
83
+ return console.log(`${r.name}: keeps the last ${r.keepLast} versions (${r.source === 'plan' ? 'plan default' : 'repository policy'}); images that a live deployment uses are always kept`);
84
+ }
70
85
  throw new Error(`unknown: registry ${sub}`);
71
86
  }
@@ -1,15 +1,16 @@
1
- import { api } from '../api.js';
1
+ import { api, ApiError } from '../api.js';
2
2
  import { output, green } from '../output.js';
3
- // koigrid rewards — Programa de recompensas (feedback pagado + activación). Ganas saldo por acciones y lo redimes
4
- // como crédito de infra o gift card. AI-first: un agente que despliega+prueba reclama la recompensa por API.
3
+ // koigrid rewards — Programa de recompensas (feedback + activación). Ganas crédito de koigrid por acciones y se aplica
4
+ // solo a tu factura (sólo crédito: ni dinero ni tarjetas regalo). AI-first: un agente que despliega+prueba reclama la recompensa por API.
5
5
  // koigrid rewards (mi saldo + mis submissions) (alias: rewards ls)
6
6
  // koigrid rewards lines (qué acciones se pagan y cuánto)
7
- // koigrid rewards submit <reason> [--json '{"...":"..."}'] (reclamar una recompensa)
8
- // koigrid rewards redeem credit|giftcard [--amount <cents>] (redimir el saldo)
7
+ // koigrid rewards submit <reason> --json '{"...":"..."}' (reclamar: report {message} · deploy_feedback {appId,timeToWorking,pros,cons,recommend} · ugc {url})
8
+ // koigrid rewards redeem (aplicar ya el saldo a la factura)
9
9
  // koigrid rewards beta (programa beta: estado, tareas, saldo, pagos)
10
10
  // koigrid rewards beta apply --json '{"appUrl":…}' (solicitar la entrada; se aprueba a mano)
11
- // koigrid rewards beta feedback --json '{"appId":…}' (tu opinión de UX/UI)
12
- // koigrid rewards beta agent-log --json '{"entries":[…]}' (el registro de fallos y mejoras de TU agente)
11
+ // koigrid rewards beta feedback --json '{"appId":…}' (tu opinión al desplegar, con pros y contras: 5 $)
12
+ // koigrid rewards beta feedback-month --json '{"appId":…}' (tu opinión tras un mes de uso: 5 $)
13
+ // koigrid rewards beta agent-log --json '{"entries":[…]}' (el registro de fallos y mejoras de TU agente; sin recompensa)
13
14
  // koigrid rewards beta wallet <network> <address> (usdt-trc20|usdc-trc20|usdt-polygon|usdc-polygon|btc)
14
15
  // koigrid rewards beta payout (pedir el pago en cripto)
15
16
  export async function rewards(a) {
@@ -38,26 +39,35 @@ export async function rewards(a) {
38
39
  if (sub === 'submit') {
39
40
  const reason = a.positionals[0];
40
41
  if (!reason)
41
- throw new Error('usage: koigrid rewards submit <reason> [--json \'{"...":"..."}\'] (reasons: koigrid rewards lines)');
42
+ throw new Error('usage: koigrid rewards submit <reason> --json \'{"...":"..."}\' (report {"message"} · deploy_feedback {"appId","timeToWorking","pros","cons","recommend"} · ugc {"url"} · register)');
42
43
  const body = { reason };
43
44
  if (a.flags.json && typeof a.flags.json === 'string')
44
45
  body.details = JSON.parse(String(a.flags.json));
45
- const r = await api('/rewards', { method: 'POST', body });
46
+ let r;
47
+ try {
48
+ r = await api('/rewards', { method: 'POST', body });
49
+ }
50
+ catch (e) {
51
+ // invalid_details trae problems[] por campo: se enseñan TODOS, no sólo el primero que va en `detail`.
52
+ const problemas = e instanceof ApiError && Array.isArray(e.body?.problems) ? e.body.problems : [];
53
+ if (problemas.length && !json)
54
+ for (const p of problemas)
55
+ console.error(` ✗ ${p.field}: ${p.code}${p.min ? ` (min ${p.min})` : ''} — ${p.message}`);
56
+ throw e;
57
+ }
46
58
  if (json)
47
59
  return console.log(JSON.stringify(r, null, 2));
48
60
  return console.log(green(`✓ Recompensa enviada (${r.submission?.status}) — $${((r.submission?.amountCents ?? 0) / 100).toFixed(2)}`));
49
61
  }
50
62
  if (sub === 'redeem') {
63
+ // Sólo crédito de koigrid. `credit` se sigue aceptando como argumento por compatibilidad con guiones viejos.
51
64
  const type = a.positionals[0];
52
- if (type !== 'credit' && type !== 'giftcard')
53
- throw new Error('usage: koigrid rewards redeem credit|giftcard [--amount <cents>]');
54
- const body = { type };
55
- if (a.flags.amount !== undefined)
56
- body.amountCents = Number(a.flags.amount);
57
- const r = await api('/rewards/redeem', { method: 'POST', body });
65
+ if (type !== undefined && type !== 'credit')
66
+ throw new Error('usage: koigrid rewards redeem (rewards are koigrid credit only: no cash or gift cards)');
67
+ const r = await api('/rewards/redeem', { method: 'POST', body: { type: 'credit' } });
58
68
  if (json)
59
69
  return console.log(JSON.stringify(r, null, 2));
60
- return console.log(green(`✓ Redimido $${((r.redeemed ?? 0) / 100).toFixed(2)} como ${r.type} — saldo restante $${((r.newBalance ?? 0) / 100).toFixed(2)}`));
70
+ return console.log(green(`✓ Aplicado $${((r.redeemed ?? 0) / 100).toFixed(2)} de crédito a tu factura — saldo restante $${((r.newBalance ?? 0) / 100).toFixed(2)}`));
61
71
  }
62
72
  if (sub === 'beta')
63
73
  return beta(a);
@@ -91,19 +101,24 @@ async function beta(a) {
91
101
  console.log(`Cartera: ${r.wallet.networkName} ${r.wallet.address}`);
92
102
  for (const p of r.payouts || [])
93
103
  console.log(` pago ${usd(p.amountCents)} · ${p.status}${p.txHash ? ` · tx ${p.txHash}` : ''}`);
94
- return console.log(`Descuento ${r.discount.percentOff}% × ${r.discount.months} meses: ${r.discount.used ? 'usado' : r.discount.earned ? 'GANADO (se aplica solo al pagar un plan)' : 'se gana al aprobarse tu opinión'}`);
104
+ const m = r.feedbackMonth;
105
+ return console.log(`Opinión del mes: ${m?.status}${m && !m.available ? (m.opensAt ? ` · se abre el ${String(m.opensAt).slice(0, 10)}` : ' · se abre un mes después de aprobar tu primera opinión') : ''}`);
95
106
  }
96
107
  if (accion === 'apply') {
97
108
  const r = await api('/rewards/beta/apply', { method: 'POST', body: cuerpo(a, "koigrid rewards beta apply --json '{\"appUrl\":…,\"appType\":…,\"monthlySpend\":…,\"motivation\":…}'") });
98
109
  return console.log(green(`✓ Solicitud enviada (${r.application?.status}). Te avisaremos por correo y en tu hilo de soporte.`));
99
110
  }
100
111
  if (accion === 'feedback') {
101
- const r = await api('/rewards/beta/feedback', { method: 'POST', body: cuerpo(a, "koigrid rewards beta feedback --json '{\"appId\":…,\"timeToWorking\":…,\"ux\":…,\"ui\":…,\"missing\":…,\"recommend\":8}'") });
112
+ const r = await api('/rewards/beta/feedback', { method: 'POST', body: cuerpo(a, "koigrid rewards beta feedback --json '{\"appId\":…,\"timeToWorking\":…,\"pros\":…,\"cons\":…,\"recommend\":8}'") });
102
113
  return console.log(green(`✓ Opinión enviada (${r.submission?.status}) — ${usd(r.submission?.amountCents)} al aprobarse`));
103
114
  }
115
+ if (accion === 'feedback-month') {
116
+ const r = await api('/rewards/beta/feedback-month', { method: 'POST', body: cuerpo(a, "koigrid rewards beta feedback-month --json '{\"appId\":…,\"pros\":…,\"cons\":…,\"stay\":\"yes|if_fixed|no\",\"recommend\":8}'") });
117
+ return console.log(green(`✓ Opinión del mes enviada (${r.submission?.status}) — ${usd(r.submission?.amountCents)} al aprobarse`));
118
+ }
104
119
  if (accion === 'agent-log') {
105
120
  const r = await api('/rewards/beta/agent-log', { method: 'POST', body: cuerpo(a, "koigrid rewards beta agent-log --json '{\"entries\":[{\"type\":\"bug\",\"action\":…,\"happened\":…}]}'") });
106
- return console.log(green(`✓ Registro guardado (${r.entries} entradas) · recompensa: ${r.reward === 'opened' ? 'pendiente de revisión' : 'ya reclamada antes'}`));
121
+ return console.log(green(`✓ Registro guardado (${r.entries} entradas) · gracias: nos ayuda a hacer koigrid más fácil para las IAs (sin recompensa)`));
107
122
  }
108
123
  if (accion === 'wallet') {
109
124
  const [, network, address] = a.positionals;