koigrid 0.7.0 → 0.9.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 +19 -2
- package/dist/api.js +78 -6
- package/dist/args.js +19 -0
- package/dist/commands/analytics.js +1 -1
- package/dist/commands/apps.js +369 -27
- package/dist/commands/audit.js +1 -1
- package/dist/commands/billing.js +87 -0
- package/dist/commands/bots.js +1 -1
- package/dist/commands/changelog.js +19 -0
- package/dist/commands/checks.js +4 -3
- package/dist/commands/config.js +9 -6
- package/dist/commands/connect.js +2 -2
- package/dist/commands/db.js +761 -17
- package/dist/commands/dns.js +1 -1
- package/dist/commands/errors.js +1 -1
- package/dist/commands/events.js +15 -3
- package/dist/commands/experiments.js +105 -0
- package/dist/commands/flags.js +22 -3
- package/dist/commands/heartbeats.js +3 -3
- package/dist/commands/images.js +1 -1
- package/dist/commands/jobs.js +39 -4
- package/dist/commands/links.js +59 -0
- package/dist/commands/logs.js +1 -1
- package/dist/commands/members.js +26 -1
- package/dist/commands/network.js +28 -0
- package/dist/commands/notices.js +24 -0
- package/dist/commands/notifications.js +2 -2
- package/dist/commands/otel.js +1 -1
- package/dist/commands/pricing.js +37 -0
- package/dist/commands/projects.js +1 -1
- package/dist/commands/queues.js +4 -3
- package/dist/commands/redis.js +80 -2
- package/dist/commands/registry.js +58 -3
- package/dist/commands/rewards.js +92 -14
- package/dist/commands/sandboxes.js +507 -2
- package/dist/commands/speed.js +1 -1
- package/dist/commands/spend.js +1 -1
- package/dist/commands/status.js +1 -1
- package/dist/commands/storage.js +51 -3
- package/dist/commands/support.js +47 -0
- package/dist/commands/tokens.js +7 -3
- package/dist/commands/up.js +6 -2
- package/dist/commands/waf.js +1 -1
- package/dist/commands/webhooks.js +1 -1
- package/dist/commands/wordpress.js +4 -3
- package/dist/commands/workflows.js +4 -3
- package/dist/esperar.js +41 -0
- package/dist/help.js +14 -1
- package/dist/index.js +26 -6
- package/dist/manifest.js +29 -12
- package/dist/output.js +1 -0
- package/dist/proyecto.js +6 -0
- package/dist/registry-flags.js +17 -0
- package/dist/registry.js +8 -2
- package/package.json +1 -1
- package/dist/commands/ai.js +0 -56
|
@@ -1,6 +1,10 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { spawnSync } from 'node:child_process';
|
|
2
|
+
import { existsSync, readFileSync, appendFileSync, mkdirSync } from 'node:fs';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { api, apiNdjson } from '../api.js';
|
|
2
6
|
import { output, green } from '../output.js';
|
|
3
|
-
// koigrid sandboxes — compute efímero (docker run --rm una vez). Ver docs/SANDBOXES.md.
|
|
7
|
+
// koigrid sandboxes — compute efímero (docker run --rm una vez). Ver docs/products/SANDBOXES.md.
|
|
4
8
|
export async function sandboxes(a) {
|
|
5
9
|
const json = !!a.flags.json;
|
|
6
10
|
const sub = a.sub || 'ls';
|
|
@@ -32,6 +36,8 @@ export async function sandboxes(a) {
|
|
|
32
36
|
console.log(s.logs);
|
|
33
37
|
return;
|
|
34
38
|
}
|
|
39
|
+
if (sub === 'vm' || sub === 'vms')
|
|
40
|
+
return vm(a, json);
|
|
35
41
|
// get <id>
|
|
36
42
|
const id = sub === 'get' ? a.positionals[0] : sub;
|
|
37
43
|
if (!id)
|
|
@@ -44,3 +50,502 @@ export async function sandboxes(a) {
|
|
|
44
50
|
if (s.logs)
|
|
45
51
|
console.log(s.logs);
|
|
46
52
|
}
|
|
53
|
+
const USO_VM = `usage: koigrid sandboxes vm <action> …
|
|
54
|
+
ls list VMs
|
|
55
|
+
create <name> [--size small|medium|large|xlarge] [--auto-pause MIN] [--label k=v] [--ssh-key FILE.pub]
|
|
56
|
+
[--env KEY=VALUE]… [--repo owner/repo]… [--environment FILE.json] [--safe-for-third-parties]
|
|
57
|
+
env <vm> its environment: variable names, files, repositories, last apply (never values)
|
|
58
|
+
env set <vm> [--env KEY=VALUE]… [--repo owner/repo]… [--environment FILE.json] [--safe-for-third-parties]
|
|
59
|
+
replace it (values may use \${{ shared.KEY }}, \${{ db.<name>.DATABASE_URL }}…)
|
|
60
|
+
token <vm> [--expires SECONDS] [--read-only] an API token that only works on this VM, to hand to someone else
|
|
61
|
+
usage <vm> [--days N] what it has used: seconds running, GB·h and cost, per day (≤90 days)
|
|
62
|
+
limits fair-use ceilings of your VMs and how much of each is used
|
|
63
|
+
ssh <vm> [-- command] SSH into the VM (wakes it if paused); needs your key on it (ssh-key set)
|
|
64
|
+
ssh-key set <vm> [--key FILE.pub]… replace the keys allowed in (default ~/.ssh/id_ed25519.pub) · ssh-key ls <vm>
|
|
65
|
+
ssh-config <vm> [--write] the ~/.ssh/config block for ssh, VS Code and Cursor (--write adds it, and the VM host key)
|
|
66
|
+
get <vm> detail (id or name)
|
|
67
|
+
exec <vm> --cmd "…" [--timeout S] [--cwd DIR] [--detach | --stream]
|
|
68
|
+
--detach: in the background, no time limit (prints its command id)
|
|
69
|
+
--stream: in the background, showing its output live until it ends
|
|
70
|
+
commands ls <vm> background commands
|
|
71
|
+
commands show <vm> <cmd> [--stdout-offset N] [--stderr-offset N]
|
|
72
|
+
commands attach <vm> <cmd> follow its output live (reconnects by itself)
|
|
73
|
+
commands stop <vm> <cmd> SIGTERM to its process group, SIGKILL after 5 s
|
|
74
|
+
pause|resume|stop|start <vm>
|
|
75
|
+
fork <vm> --name <new>
|
|
76
|
+
snapshot <vm> --name <label> · snapshots <vm>
|
|
77
|
+
update <vm> [--auto-pause MIN] [--size …] [--label k=v]
|
|
78
|
+
rm <vm>
|
|
79
|
+
files ls <vm> [path] [--depth N] · files find <vm> <path> --name '*.ts'
|
|
80
|
+
files cat <vm> <path> · files put <vm> <path> (--file LOCAL | --text "…") [--mode 644]
|
|
81
|
+
files mv <vm> <from> <to> [--overwrite] · files rm <vm> <path> [--recursive]
|
|
82
|
+
files mkdir <vm> <path> · files chmod <vm> <path> <mode>
|
|
83
|
+
files replace <vm> <path> --search "…" --replace "…" [--dry-run] (literal text, not a regex)
|
|
84
|
+
files upload <vm> <local-file> <path> · files download <vm> <path> [--out LOCAL] (large files, up to 5 GiB)
|
|
85
|
+
files push <vm> <local-dir> <path> upload a whole folder (packed as .tar.gz, unpacked in the VM)`;
|
|
86
|
+
/**
|
|
87
|
+
* El entorno de una VM desde las opciones (ficha 75dd5b43): --environment FILE.json (el objeto entero, como la API),
|
|
88
|
+
* y encima --env KEY=VALUE, --repo owner/repo y --safe-for-third-parties. undefined si no se pidió nada.
|
|
89
|
+
*/
|
|
90
|
+
function entorno(a) {
|
|
91
|
+
const lista = (f) => (f === undefined ? [] : (Array.isArray(f) ? f : [f]).map(String));
|
|
92
|
+
const base = a.flags.environment ? JSON.parse(readFileSync(String(a.flags.environment).replace(/^~(?=\/)/, homedir()), 'utf8')) : {};
|
|
93
|
+
for (const kv of lista(a.flags.env)) {
|
|
94
|
+
const i = kv.indexOf('=');
|
|
95
|
+
if (i < 1)
|
|
96
|
+
throw new Error(`--env needs KEY=VALUE (got ${kv})`);
|
|
97
|
+
base.variables = { ...(base.variables || {}), [kv.slice(0, i)]: kv.slice(i + 1) };
|
|
98
|
+
}
|
|
99
|
+
for (const url of lista(a.flags.repo))
|
|
100
|
+
base.repositories = [...(base.repositories || []), { url }];
|
|
101
|
+
if (a.flags['safe-for-third-parties'])
|
|
102
|
+
base.safeForThirdParties = true;
|
|
103
|
+
return Object.keys(base).length || a.flags.environment ? base : undefined;
|
|
104
|
+
}
|
|
105
|
+
function muestraEntorno(e) {
|
|
106
|
+
console.log(`variables: ${(e.variables || []).join(', ') || '—'}`);
|
|
107
|
+
for (const f of e.files || [])
|
|
108
|
+
console.log(`file: ${f.path} (${f.mode}, ${f.bytes} B)`);
|
|
109
|
+
for (const r of e.repositories || [])
|
|
110
|
+
console.log(`repo: ${r.url} → ${r.path}${r.setup ? (r.setupBlocking ? ' · setup (blocking)' : ' · setup') : ''}`);
|
|
111
|
+
if (e.safeForThirdParties)
|
|
112
|
+
console.log('safe for third parties: nothing of yours goes into the VM');
|
|
113
|
+
const st = e.status;
|
|
114
|
+
if (st) {
|
|
115
|
+
console.log(st.ok ? green(`✓ applied (${st.reason}) ${st.appliedAt}`) : `✗ last apply (${st.reason}) failed: ${st.error}`);
|
|
116
|
+
for (const r of st.repositories || [])
|
|
117
|
+
if (r.setupCommandId)
|
|
118
|
+
console.log(` setup ${r.path}: koigrid sandboxes vm commands attach <vm> ${r.setupCommandId}`);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
function etiquetas(a) {
|
|
122
|
+
const raw = a.flags.label;
|
|
123
|
+
if (!raw)
|
|
124
|
+
return undefined;
|
|
125
|
+
const lista = Array.isArray(raw) ? raw : [raw];
|
|
126
|
+
return Object.fromEntries(lista.map((x) => String(x).split('=')).map(([k, ...v]) => [k, v.join('=')]));
|
|
127
|
+
}
|
|
128
|
+
/** Las claves públicas locales: los ficheros que se pasen, o la primera que haya entre las habituales de ~/.ssh. */
|
|
129
|
+
function clavesLocales(flag) {
|
|
130
|
+
const ficheros = flag ? (Array.isArray(flag) ? flag : [flag]).map(String).filter((f) => f !== 'true') : [];
|
|
131
|
+
const candidatos = ficheros.length ? ficheros : ['id_ed25519.pub', 'id_ecdsa.pub', 'id_rsa.pub'].map((f) => join(homedir(), '.ssh', f)).filter(existsSync).slice(0, 1);
|
|
132
|
+
if (!candidatos.length)
|
|
133
|
+
throw new Error('no public key found in ~/.ssh: create one with ssh-keygen -t ed25519, or pass --key FILE.pub');
|
|
134
|
+
return candidatos.map((f) => readFileSync(f.replace(/^~(?=\/)/, homedir()), 'utf8').trim());
|
|
135
|
+
}
|
|
136
|
+
function filaVm(x) {
|
|
137
|
+
return { name: x.name, size: x.size, status: x.status, ssh: x.ssh?.enabled ? `koi-${x.name}` : '', autoPause: x.autoPauseMin ? `${x.autoPauseMin}m` : 'off', id: String(x.id).slice(0, 8) };
|
|
138
|
+
}
|
|
139
|
+
// koigrid sandboxes vm — VMs persistentes para agentes (Sandboxes v2, docs/design/VMS.md).
|
|
140
|
+
async function vm(a, json) {
|
|
141
|
+
const accion = a.positionals[0] || 'ls';
|
|
142
|
+
const objetivo = a.positionals[1];
|
|
143
|
+
const necesita = () => {
|
|
144
|
+
if (!objetivo)
|
|
145
|
+
throw new Error(USO_VM);
|
|
146
|
+
return objetivo;
|
|
147
|
+
};
|
|
148
|
+
const muestra = (r) => {
|
|
149
|
+
if (json)
|
|
150
|
+
return console.log(JSON.stringify(r, null, 2));
|
|
151
|
+
const v = r.vm || {};
|
|
152
|
+
console.log(green(`✓ ${v.name} — ${v.status}`) + (v.ssh?.enabled ? ` · koigrid sandboxes vm ssh ${v.name}` : ''));
|
|
153
|
+
if (v.statusReason)
|
|
154
|
+
console.log(v.statusReason);
|
|
155
|
+
};
|
|
156
|
+
if (accion === 'ls' || accion === 'list') {
|
|
157
|
+
const r = await api('/sandboxes/vms');
|
|
158
|
+
const l = r.vms || [];
|
|
159
|
+
return output(l, json, { rows: l.map(filaVm), columns: ['name', 'size', 'status', 'ssh', 'autoPause', 'id'] });
|
|
160
|
+
}
|
|
161
|
+
if (accion === 'create') {
|
|
162
|
+
const body = { name: necesita() };
|
|
163
|
+
if (a.flags.size)
|
|
164
|
+
body.size = String(a.flags.size);
|
|
165
|
+
if (a.flags['auto-pause'] !== undefined)
|
|
166
|
+
body.autoPauseMin = Number(a.flags['auto-pause']);
|
|
167
|
+
const labels = etiquetas(a);
|
|
168
|
+
if (labels)
|
|
169
|
+
body.labels = labels;
|
|
170
|
+
if (a.flags['ssh-key'])
|
|
171
|
+
body.sshPublicKeys = clavesLocales(a.flags['ssh-key']);
|
|
172
|
+
const env = entorno(a);
|
|
173
|
+
if (env)
|
|
174
|
+
body.environment = env;
|
|
175
|
+
return muestra(await api('/sandboxes/vms', { method: 'POST', body }));
|
|
176
|
+
}
|
|
177
|
+
// ── Entorno y token acotado a la VM (ficha 75dd5b43) ──
|
|
178
|
+
if (accion === 'env') {
|
|
179
|
+
const set = objetivo === 'set';
|
|
180
|
+
const vmNombre = set ? a.positionals[2] : objetivo;
|
|
181
|
+
if (!vmNombre)
|
|
182
|
+
throw new Error(USO_VM);
|
|
183
|
+
const rutaEnv = `/sandboxes/vms/${encodeURIComponent(vmNombre)}/environment`;
|
|
184
|
+
const r = set ? await api(rutaEnv, { method: 'PUT', body: entorno(a) ?? {} }) : await api(rutaEnv);
|
|
185
|
+
if (json)
|
|
186
|
+
return console.log(JSON.stringify(r, null, 2));
|
|
187
|
+
return muestraEntorno(r.environment || {});
|
|
188
|
+
}
|
|
189
|
+
if (accion === 'usage') {
|
|
190
|
+
const dias = a.flags.days ? `?days=${Number(a.flags.days)}` : '';
|
|
191
|
+
const r = await api(`/sandboxes/vms/${encodeURIComponent(necesita())}/usage${dias}`);
|
|
192
|
+
if (json)
|
|
193
|
+
return console.log(JSON.stringify(r, null, 2));
|
|
194
|
+
const u = r.usage;
|
|
195
|
+
const filas = (u.days || []).map((d) => ({ day: d.day, hours: (d.seconds / 3600).toFixed(2), gbHours: d.gbHours, costUsd: d.costUsd }));
|
|
196
|
+
output(filas, false, { rows: filas, columns: ['day', 'hours', 'gbHours', 'costUsd'] });
|
|
197
|
+
console.log(`total ${(u.total.seconds / 3600).toFixed(2)} h · ${u.total.gbHours} GB·h · $${u.total.costUsd}${u.billed ? '' : ' (measured, not charged)'} · $${u.pricePerHourUsd}/h${u.cpu ? ` · CPU ${u.cpu.percent}%` : ''}`);
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
if (accion === 'limits') {
|
|
201
|
+
const r = await api('/sandboxes/vms/limits');
|
|
202
|
+
if (json)
|
|
203
|
+
return console.log(JSON.stringify(r, null, 2));
|
|
204
|
+
const l = r.limits;
|
|
205
|
+
console.log(`VMs ${l.vms.used}/${l.vms.max} · vCPU running ${l.vcpuRunning.used}/${l.vcpuRunning.max} (${l.raise})`);
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
if (accion === 'token') {
|
|
209
|
+
const body = {};
|
|
210
|
+
if (a.flags.expires)
|
|
211
|
+
body.expiresInSeconds = Number(a.flags.expires);
|
|
212
|
+
if (a.flags['read-only'])
|
|
213
|
+
body.scopes = ['sandboxes:read'];
|
|
214
|
+
const r = await api(`/sandboxes/vms/${encodeURIComponent(necesita())}/tokens`, { method: 'POST', body });
|
|
215
|
+
if (json)
|
|
216
|
+
return console.log(JSON.stringify(r, null, 2));
|
|
217
|
+
console.log(r.token.token);
|
|
218
|
+
console.error(`only valid on ${r.base}/… until ${r.token.expiresAt} · revoke: koigrid tokens revoke ${r.token.id}`);
|
|
219
|
+
return;
|
|
220
|
+
}
|
|
221
|
+
// ── SSH (ficha daa6b24a): por la puerta de koigrid, cifrado de punta a punta con la VM ──
|
|
222
|
+
if (accion === 'ssh-key') {
|
|
223
|
+
const sub = objetivo;
|
|
224
|
+
const vmNombre = a.positionals[2];
|
|
225
|
+
if (!vmNombre || (sub !== 'set' && sub !== 'ls'))
|
|
226
|
+
throw new Error(USO_VM);
|
|
227
|
+
const ruta = `/sandboxes/vms/${encodeURIComponent(vmNombre)}/ssh-keys`;
|
|
228
|
+
const r = sub === 'ls' ? await api(ruta) : await api(ruta, { method: 'PUT', body: { keys: clavesLocales(a.flags.key) } });
|
|
229
|
+
if (json)
|
|
230
|
+
return console.log(JSON.stringify(r, null, 2));
|
|
231
|
+
for (const k of r.keys || [])
|
|
232
|
+
console.log(String(k).slice(0, 60) + '…');
|
|
233
|
+
if (sub === 'set')
|
|
234
|
+
console.log(green(`✓ ${(r.keys || []).length} key(s) on ${vmNombre}`) + ` · koigrid sandboxes vm ssh ${vmNombre}`);
|
|
235
|
+
return;
|
|
236
|
+
}
|
|
237
|
+
if (accion === 'ssh-config' || accion === 'ssh') {
|
|
238
|
+
const r = await api(`/sandboxes/vms/${encodeURIComponent(necesita())}/ssh-keys`);
|
|
239
|
+
const s = r.ssh || {};
|
|
240
|
+
if (!s.enabled)
|
|
241
|
+
throw new Error(`${necesita()} has no SSH keys yet: koigrid sandboxes vm ssh-key set ${necesita()}`);
|
|
242
|
+
if (accion === 'ssh-config') {
|
|
243
|
+
if (json)
|
|
244
|
+
return console.log(JSON.stringify(s, null, 2));
|
|
245
|
+
if (!a.flags.write) {
|
|
246
|
+
console.log(s.config);
|
|
247
|
+
if (s.knownHosts)
|
|
248
|
+
console.log(`\n# and in ~/.ssh/known_hosts:\n${s.knownHosts}`);
|
|
249
|
+
return;
|
|
250
|
+
}
|
|
251
|
+
const dir = join(homedir(), '.ssh');
|
|
252
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
253
|
+
const config = join(dir, 'config');
|
|
254
|
+
const yaConfig = existsSync(config) && readFileSync(config, 'utf8').includes(String(s.config).split('\n')[0]);
|
|
255
|
+
if (!yaConfig)
|
|
256
|
+
appendFileSync(config, `\n${s.config}\n`, { mode: 0o600 });
|
|
257
|
+
const known = join(dir, 'known_hosts');
|
|
258
|
+
if (s.knownHosts && !(existsSync(known) && readFileSync(known, 'utf8').includes(s.knownHosts)))
|
|
259
|
+
appendFileSync(known, `${s.knownHosts}\n`, { mode: 0o600 });
|
|
260
|
+
return console.log(green(`✓ ${yaConfig ? 'already in' : 'added to'} ~/.ssh/config`) + `: ssh ${String(s.config).split('\n')[0].slice(5)} (VS Code / Cursor: Remote-SSH → that host)`);
|
|
261
|
+
}
|
|
262
|
+
// ssh: el mismo ProxyCommand que el bloque de config, con la clave de host de la VM fijada si ya la tiene.
|
|
263
|
+
const sep = process.argv.indexOf('--');
|
|
264
|
+
const orden = sep >= 0 ? process.argv.slice(sep + 1) : [];
|
|
265
|
+
const proxy = `ssh -p ${s.gate.port} -o StrictHostKeyChecking=accept-new ${s.gate.user}@${s.gate.host} %h`;
|
|
266
|
+
const args = ['-o', `ProxyCommand=${proxy}`, '-o', `HostKeyAlias=koi-${s.target}`, `${s.user}@${s.target}`, ...orden];
|
|
267
|
+
const r2 = spawnSync('ssh', args, { stdio: 'inherit' });
|
|
268
|
+
if (r2.error)
|
|
269
|
+
throw new Error(`could not run ssh: ${r2.error.message}`);
|
|
270
|
+
process.exitCode = r2.status ?? 1;
|
|
271
|
+
return;
|
|
272
|
+
}
|
|
273
|
+
if (accion === 'get')
|
|
274
|
+
return muestra(await api(`/sandboxes/vms/${encodeURIComponent(necesita())}`));
|
|
275
|
+
if (accion === 'exec') {
|
|
276
|
+
if (!a.flags.cmd)
|
|
277
|
+
throw new Error(USO_VM);
|
|
278
|
+
const body = { command: String(a.flags.cmd) };
|
|
279
|
+
if (a.flags.timeout)
|
|
280
|
+
body.timeoutSec = Number(a.flags.timeout);
|
|
281
|
+
if (a.flags.cwd)
|
|
282
|
+
body.cwd = String(a.flags.cwd);
|
|
283
|
+
if (a.flags.stream) {
|
|
284
|
+
body.stream = true;
|
|
285
|
+
return seguirOrden(necesita(), `/sandboxes/vms/${encodeURIComponent(necesita())}/exec`, body, json);
|
|
286
|
+
}
|
|
287
|
+
if (a.flags.detach) {
|
|
288
|
+
body.detached = true;
|
|
289
|
+
const r = await api(`/sandboxes/vms/${encodeURIComponent(necesita())}/exec`, { method: 'POST', body });
|
|
290
|
+
if (json)
|
|
291
|
+
return console.log(JSON.stringify(r, null, 2));
|
|
292
|
+
return console.log(green(`✓ running in the background: ${r.command?.id}`) + `\n koigrid sandboxes vm commands attach ${necesita()} ${r.command?.id}`);
|
|
293
|
+
}
|
|
294
|
+
const r = await api(`/sandboxes/vms/${encodeURIComponent(necesita())}/exec`, { method: 'POST', body });
|
|
295
|
+
if (json)
|
|
296
|
+
return console.log(JSON.stringify(r, null, 2));
|
|
297
|
+
const x = r.result || {};
|
|
298
|
+
if (x.stdout)
|
|
299
|
+
process.stdout.write(x.stdout);
|
|
300
|
+
if (x.stderr)
|
|
301
|
+
process.stderr.write(x.stderr);
|
|
302
|
+
if (x.exitCode !== 0)
|
|
303
|
+
process.exitCode = typeof x.exitCode === 'number' ? x.exitCode : 1;
|
|
304
|
+
return;
|
|
305
|
+
}
|
|
306
|
+
if (accion === 'pause')
|
|
307
|
+
return muestra(await api(`/sandboxes/vms/${encodeURIComponent(necesita())}/pause`, { method: 'POST' }));
|
|
308
|
+
if (accion === 'resume')
|
|
309
|
+
return muestra(await api(`/sandboxes/vms/${encodeURIComponent(necesita())}/resume`, { method: 'POST' }));
|
|
310
|
+
if (accion === 'stop')
|
|
311
|
+
return muestra(await api(`/sandboxes/vms/${encodeURIComponent(necesita())}/stop`, { method: 'POST' }));
|
|
312
|
+
if (accion === 'start')
|
|
313
|
+
return muestra(await api(`/sandboxes/vms/${encodeURIComponent(necesita())}/start`, { method: 'POST' }));
|
|
314
|
+
if (accion === 'fork') {
|
|
315
|
+
if (!a.flags.name)
|
|
316
|
+
throw new Error(USO_VM);
|
|
317
|
+
return muestra(await api(`/sandboxes/vms/${encodeURIComponent(necesita())}/fork`, { method: 'POST', body: { name: String(a.flags.name) } }));
|
|
318
|
+
}
|
|
319
|
+
if (accion === 'snapshot') {
|
|
320
|
+
if (!a.flags.name)
|
|
321
|
+
throw new Error(USO_VM);
|
|
322
|
+
const r = await api(`/sandboxes/vms/${encodeURIComponent(necesita())}/snapshots`, { method: 'POST', body: { name: String(a.flags.name) } });
|
|
323
|
+
if (json)
|
|
324
|
+
return console.log(JSON.stringify(r, null, 2));
|
|
325
|
+
return console.log(green(`✓ snapshot ${r.snapshot?.name} (${r.snapshot?.id})`));
|
|
326
|
+
}
|
|
327
|
+
if (accion === 'snapshots') {
|
|
328
|
+
const r = await api(`/sandboxes/vms/${encodeURIComponent(necesita())}/snapshots`);
|
|
329
|
+
const l = r.snapshots || [];
|
|
330
|
+
return output(l, json, { rows: l.map((x) => ({ name: x.name ?? '(pause)', kind: x.kind, memory: x.withMemory ? 'yes' : 'no', created: x.createdAt, id: String(x.id).slice(0, 8) })), columns: ['name', 'kind', 'memory', 'created', 'id'] });
|
|
331
|
+
}
|
|
332
|
+
if (accion === 'update') {
|
|
333
|
+
const body = {};
|
|
334
|
+
if (a.flags['auto-pause'] !== undefined)
|
|
335
|
+
body.autoPauseMin = Number(a.flags['auto-pause']);
|
|
336
|
+
if (a.flags.size)
|
|
337
|
+
body.size = String(a.flags.size);
|
|
338
|
+
const labels = etiquetas(a);
|
|
339
|
+
if (labels)
|
|
340
|
+
body.labels = labels;
|
|
341
|
+
return muestra(await api(`/sandboxes/vms/${encodeURIComponent(necesita())}`, { method: 'PATCH', body }));
|
|
342
|
+
}
|
|
343
|
+
if (accion === 'commands' || accion === 'command')
|
|
344
|
+
return ordenes(a, json);
|
|
345
|
+
if (accion === 'files' || accion === 'file')
|
|
346
|
+
return ficheros(a, json);
|
|
347
|
+
if (accion === 'rm' || accion === 'delete') {
|
|
348
|
+
await api(`/sandboxes/vms/${encodeURIComponent(necesita())}`, { method: 'DELETE' });
|
|
349
|
+
return json ? console.log(JSON.stringify({ deleted: true })) : console.log(green('✓ deleted'));
|
|
350
|
+
}
|
|
351
|
+
throw new Error(USO_VM);
|
|
352
|
+
}
|
|
353
|
+
// koigrid sandboxes vm commands — órdenes en segundo plano de una VM (ficha c20bdf5f).
|
|
354
|
+
async function ordenes(a, json) {
|
|
355
|
+
const sub = a.positionals[1] || 'ls';
|
|
356
|
+
const vmId = a.positionals[2];
|
|
357
|
+
const cmd = a.positionals[3];
|
|
358
|
+
if (!vmId)
|
|
359
|
+
throw new Error(USO_VM);
|
|
360
|
+
const base = `/sandboxes/vms/${encodeURIComponent(vmId)}/commands`;
|
|
361
|
+
if (sub === 'ls' || sub === 'list') {
|
|
362
|
+
const r = await api(base);
|
|
363
|
+
const l = r.commands || [];
|
|
364
|
+
return output(l, json, { rows: l.map((x) => ({ id: x.id, status: x.status, exit: x.exitCode ?? '', started: x.startedAt, command: String(x.command).slice(0, 60) })), columns: ['id', 'status', 'exit', 'started', 'command'] });
|
|
365
|
+
}
|
|
366
|
+
if (!cmd)
|
|
367
|
+
throw new Error(USO_VM);
|
|
368
|
+
const ruta = `${base}/${encodeURIComponent(cmd)}`;
|
|
369
|
+
if (sub === 'show' || sub === 'get') {
|
|
370
|
+
const q = new URLSearchParams();
|
|
371
|
+
if (a.flags['stdout-offset'] !== undefined)
|
|
372
|
+
q.set('stdoutOffset', String(a.flags['stdout-offset']));
|
|
373
|
+
if (a.flags['stderr-offset'] !== undefined)
|
|
374
|
+
q.set('stderrOffset', String(a.flags['stderr-offset']));
|
|
375
|
+
const r = await api(`${ruta}${q.size ? `?${q}` : ''}`);
|
|
376
|
+
if (json)
|
|
377
|
+
return console.log(JSON.stringify(r, null, 2));
|
|
378
|
+
const c = r.command || {};
|
|
379
|
+
if (c.stdout)
|
|
380
|
+
process.stdout.write(c.stdout);
|
|
381
|
+
if (c.stderr)
|
|
382
|
+
process.stderr.write(c.stderr);
|
|
383
|
+
const fin = c.running ? 'running' : `${c.status}${c.exitCode !== null && c.exitCode !== undefined ? ` (exit ${c.exitCode})` : ''}`;
|
|
384
|
+
console.error(green(`— ${fin}`) + (c.more ? ` · more: --stdout-offset ${c.stdoutNextOffset} --stderr-offset ${c.stderrNextOffset}` : '') + (c.outputAvailable === false ? ` · ${c.detail}` : ''));
|
|
385
|
+
return;
|
|
386
|
+
}
|
|
387
|
+
if (sub === 'attach' || sub === 'follow')
|
|
388
|
+
return seguirOrden(vmId, `${ruta}/stream`, undefined, json, cmd);
|
|
389
|
+
if (sub === 'stop' || sub === 'kill') {
|
|
390
|
+
const r = await api(`/sandboxes/vms/${encodeURIComponent(vmId)}/commands/${encodeURIComponent(cmd)}`, { method: 'DELETE' });
|
|
391
|
+
if (json)
|
|
392
|
+
return console.log(JSON.stringify(r, null, 2));
|
|
393
|
+
return console.log(green(`✓ ${r.command?.status}${r.command?.exitCode != null ? ` (exit ${r.command.exitCode})` : ''}`));
|
|
394
|
+
}
|
|
395
|
+
throw new Error(USO_VM);
|
|
396
|
+
}
|
|
397
|
+
/**
|
|
398
|
+
* Sigue la salida en directo de una orden (NDJSON) y, si el servidor pide reconectar (cada 10 min), se vuelve a
|
|
399
|
+
* enganchar desde esos offsets: ni hueco ni repetición. Sale con el código de la orden. `--json` imprime los eventos.
|
|
400
|
+
*/
|
|
401
|
+
async function seguirOrden(vmId, ruta, cuerpo, json, cmd) {
|
|
402
|
+
let id = cmd;
|
|
403
|
+
for (;;) {
|
|
404
|
+
let reconectar = null;
|
|
405
|
+
await apiNdjson(ruta, cuerpo ? { method: 'POST', body: cuerpo } : {}, (e) => {
|
|
406
|
+
if (json)
|
|
407
|
+
console.log(JSON.stringify(e));
|
|
408
|
+
if (e.type === 'started')
|
|
409
|
+
id = e.id;
|
|
410
|
+
else if (e.type === 'stdout' && !json)
|
|
411
|
+
process.stdout.write(e.data);
|
|
412
|
+
else if (e.type === 'stderr' && !json)
|
|
413
|
+
process.stderr.write(e.data);
|
|
414
|
+
else if (e.type === 'reconnect')
|
|
415
|
+
reconectar = { stdoutOffset: e.stdoutOffset, stderrOffset: e.stderrOffset };
|
|
416
|
+
else if (e.type === 'exit')
|
|
417
|
+
process.exitCode = typeof e.exitCode === 'number' ? e.exitCode : 1;
|
|
418
|
+
else if (e.type === 'error')
|
|
419
|
+
throw new Error(`${e.error}: ${e.detail}`);
|
|
420
|
+
});
|
|
421
|
+
const r = reconectar;
|
|
422
|
+
if (!r || !id)
|
|
423
|
+
return;
|
|
424
|
+
ruta = `/sandboxes/vms/${encodeURIComponent(vmId)}/commands/${encodeURIComponent(id)}/stream?stdoutOffset=${r.stdoutOffset}&stderrOffset=${r.stderrOffset}`;
|
|
425
|
+
cuerpo = undefined;
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
// koigrid sandboxes vm files — ficheros de una VM (ficha VM-FICHEROS, lib/api/vm-ficheros.ts).
|
|
429
|
+
async function ficheros(a, json) {
|
|
430
|
+
const sub = a.positionals[1] || 'ls';
|
|
431
|
+
const vmId = a.positionals[2];
|
|
432
|
+
const p1 = a.positionals[3];
|
|
433
|
+
const p2 = a.positionals[4];
|
|
434
|
+
if (!vmId)
|
|
435
|
+
throw new Error(USO_VM);
|
|
436
|
+
const base = `/sandboxes/vms/${encodeURIComponent(vmId)}/files`;
|
|
437
|
+
const listar = (l) => output(l, json, { rows: l.map((e) => ({ type: e.type, mode: e.mode, size: e.size, modified: e.modifiedAt, path: e.path })), columns: ['type', 'mode', 'size', 'modified', 'path'] });
|
|
438
|
+
const hecho = (r, texto) => (json ? console.log(JSON.stringify(r, null, 2)) : console.log(green(`✓ ${texto}`)));
|
|
439
|
+
if (sub === 'ls' || sub === 'list') {
|
|
440
|
+
const q = new URLSearchParams({ path: p1 || '/root' });
|
|
441
|
+
if (a.flags.depth)
|
|
442
|
+
q.set('depth', String(a.flags.depth));
|
|
443
|
+
const r = await api(`${base}?${q}`);
|
|
444
|
+
return listar(r.entries || []);
|
|
445
|
+
}
|
|
446
|
+
if (sub === 'find') {
|
|
447
|
+
if (!p1 || !a.flags.name)
|
|
448
|
+
throw new Error(USO_VM);
|
|
449
|
+
const r = await api(`${base}?${new URLSearchParams({ path: p1, name: String(a.flags.name) })}`);
|
|
450
|
+
return listar(r.entries || []);
|
|
451
|
+
}
|
|
452
|
+
if (!p1)
|
|
453
|
+
throw new Error(USO_VM);
|
|
454
|
+
if (sub === 'cat' || sub === 'get') {
|
|
455
|
+
const r = await api(`${base}/content?${new URLSearchParams({ path: p1 })}`);
|
|
456
|
+
if (json)
|
|
457
|
+
return console.log(JSON.stringify(r, null, 2));
|
|
458
|
+
process.stdout.write(Buffer.from(r.contentBase64 || '', 'base64'));
|
|
459
|
+
if (r.truncated)
|
|
460
|
+
console.error(`— truncated: showing ${r.maxBytes} of ${r.size} bytes (use exec or SSH for the whole file)`);
|
|
461
|
+
return;
|
|
462
|
+
}
|
|
463
|
+
if (sub === 'put' || sub === 'write') {
|
|
464
|
+
const body = { path: p1 };
|
|
465
|
+
if (a.flags.file) {
|
|
466
|
+
const { readFileSync, statSync } = await import('node:fs');
|
|
467
|
+
// Más de 3 MB: por URL firmada (la escritura directa admite 4 MB y el base64 los infla un tercio).
|
|
468
|
+
if (statSync(String(a.flags.file)).size > 3 * 1024 * 1024)
|
|
469
|
+
return hecho(await subirGrande(vmId, readFileSync(String(a.flags.file)), p1, false), `${p1} (uploaded)`);
|
|
470
|
+
body.contentBase64 = readFileSync(String(a.flags.file)).toString('base64');
|
|
471
|
+
}
|
|
472
|
+
else if (a.flags.text !== undefined)
|
|
473
|
+
body.content = String(a.flags.text);
|
|
474
|
+
else
|
|
475
|
+
throw new Error(USO_VM);
|
|
476
|
+
if (a.flags.mode)
|
|
477
|
+
body.mode = String(a.flags.mode);
|
|
478
|
+
const r = await api(`/sandboxes/vms/${encodeURIComponent(vmId)}/files/content`, { method: 'PUT', body });
|
|
479
|
+
return hecho(r, `${r.path} (${r.size} bytes)`);
|
|
480
|
+
}
|
|
481
|
+
if (sub === 'mv' || sub === 'move') {
|
|
482
|
+
if (!p2)
|
|
483
|
+
throw new Error(USO_VM);
|
|
484
|
+
const r = await api(`/sandboxes/vms/${encodeURIComponent(vmId)}/files/move`, { method: 'POST', body: { from: p1, to: p2, overwrite: !!a.flags.overwrite } });
|
|
485
|
+
return hecho(r, `${r.from} → ${r.to}`);
|
|
486
|
+
}
|
|
487
|
+
if (sub === 'rm' || sub === 'delete') {
|
|
488
|
+
const q = new URLSearchParams({ path: p1 });
|
|
489
|
+
if (a.flags.recursive)
|
|
490
|
+
q.set('recursive', 'true');
|
|
491
|
+
const r = await api(`/sandboxes/vms/${encodeURIComponent(vmId)}/files?${q}`, { method: 'DELETE' });
|
|
492
|
+
return hecho(r, `deleted ${r.deleted}`);
|
|
493
|
+
}
|
|
494
|
+
if (sub === 'mkdir')
|
|
495
|
+
return hecho(await api(`/sandboxes/vms/${encodeURIComponent(vmId)}/files/mkdir`, { method: 'POST', body: { path: p1 } }), `created ${p1}`);
|
|
496
|
+
if (sub === 'chmod') {
|
|
497
|
+
if (!p2)
|
|
498
|
+
throw new Error(USO_VM);
|
|
499
|
+
const r = await api(`/sandboxes/vms/${encodeURIComponent(vmId)}/files/chmod`, { method: 'POST', body: { path: p1, mode: p2 } });
|
|
500
|
+
return hecho(r, `${r.path} → ${r.mode}`);
|
|
501
|
+
}
|
|
502
|
+
if (sub === 'upload') {
|
|
503
|
+
if (!p2)
|
|
504
|
+
throw new Error(USO_VM);
|
|
505
|
+
const { readFileSync } = await import('node:fs');
|
|
506
|
+
const r = await subirGrande(vmId, readFileSync(p1), p2, false);
|
|
507
|
+
return hecho(r, `${r.path} (${r.size} bytes)`);
|
|
508
|
+
}
|
|
509
|
+
if (sub === 'push') {
|
|
510
|
+
if (!p2)
|
|
511
|
+
throw new Error(USO_VM);
|
|
512
|
+
const { execFileSync } = await import('node:child_process');
|
|
513
|
+
const tgz = execFileSync('tar', ['-czf', '-', '-C', p1, '.'], { maxBuffer: 6 * 1024 ** 3 });
|
|
514
|
+
const r = await subirGrande(vmId, tgz, p2, true);
|
|
515
|
+
return hecho(r, `${p1} → ${r.path} (${r.uploadedBytes} bytes packed)`);
|
|
516
|
+
}
|
|
517
|
+
if (sub === 'download') {
|
|
518
|
+
const r = await api(`/sandboxes/vms/${encodeURIComponent(vmId)}/files/download-url`, { method: 'POST', body: { path: p1 } });
|
|
519
|
+
if (json && !a.flags.out)
|
|
520
|
+
return console.log(JSON.stringify(r, null, 2));
|
|
521
|
+
const res = await fetch(r.downloadUrl);
|
|
522
|
+
if (!res.ok)
|
|
523
|
+
throw new Error(`download failed: HTTP ${res.status}`);
|
|
524
|
+
const datos = Buffer.from(await res.arrayBuffer());
|
|
525
|
+
const destino = String(a.flags.out || p1.split('/').pop() || 'file');
|
|
526
|
+
const { writeFileSync } = await import('node:fs');
|
|
527
|
+
writeFileSync(destino, datos);
|
|
528
|
+
return hecho({ ...r, savedTo: destino }, `${p1} → ${destino} (${datos.length} bytes)`);
|
|
529
|
+
}
|
|
530
|
+
if (sub === 'replace') {
|
|
531
|
+
if (a.flags.search === undefined || a.flags.replace === undefined)
|
|
532
|
+
throw new Error(USO_VM);
|
|
533
|
+
const r = await api(`/sandboxes/vms/${encodeURIComponent(vmId)}/files/replace`, { method: 'POST', body: { path: p1, search: String(a.flags.search), replace: String(a.flags.replace), dryRun: !!a.flags['dry-run'] } });
|
|
534
|
+
if (json)
|
|
535
|
+
return console.log(JSON.stringify(r, null, 2));
|
|
536
|
+
for (const f of r.files || [])
|
|
537
|
+
console.log(`${f.skipped ? `skipped (${f.skipped})` : `${f.replacements}×`} ${f.path}`);
|
|
538
|
+
return console.log(green(`✓ ${r.replacements} replacement(s)${r.dryRun ? ' (dry run: nothing written)' : ''}`));
|
|
539
|
+
}
|
|
540
|
+
throw new Error(USO_VM);
|
|
541
|
+
}
|
|
542
|
+
// Subida grande en dos pasos (ficha VM-FICHEROS-URL): URL firmada → PUT directo al almacén → la VM se lo trae.
|
|
543
|
+
async function subirGrande(vmId, datos, ruta, extraer) {
|
|
544
|
+
const u = await api(`/sandboxes/vms/${encodeURIComponent(vmId)}/files/upload-url`, { method: 'POST', body: {} });
|
|
545
|
+
if (datos.length > u.maxBytes)
|
|
546
|
+
throw new Error(`the file is ${datos.length} bytes; the limit is ${u.maxBytes}`);
|
|
547
|
+
const put = await fetch(u.uploadUrl, { method: 'PUT', body: new Uint8Array(datos) });
|
|
548
|
+
if (!put.ok)
|
|
549
|
+
throw new Error(`upload to the signed URL failed: HTTP ${put.status}`);
|
|
550
|
+
return api(`/sandboxes/vms/${encodeURIComponent(vmId)}/files/upload-complete`, { method: 'POST', body: { uploadId: u.uploadId, path: ruta, extract: extraer } });
|
|
551
|
+
}
|
package/dist/commands/speed.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { api } from '../api.js';
|
|
2
2
|
import { output } from '../output.js';
|
|
3
|
-
// koigrid speed — Speed Insights (Core Web Vitals). Reutiliza el site de Web Analytics. Ver docs/SPEED-INSIGHTS.md.
|
|
3
|
+
// koigrid speed — Speed Insights (Core Web Vitals). Reutiliza el site de Web Analytics. Ver docs/products/SPEED-INSIGHTS.md.
|
|
4
4
|
export async function speed(a) {
|
|
5
5
|
const json = !!a.flags.json;
|
|
6
6
|
const sub = a.sub || 'ls';
|
package/dist/commands/spend.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { api } from '../api.js';
|
|
2
2
|
import { green } from '../output.js';
|
|
3
|
-
// koigrid spend — Spend Management (tope de gasto mensual + avisos + parada dura). Ver docs/SPEND.md.
|
|
3
|
+
// koigrid spend — Spend Management (tope de gasto mensual + avisos + parada dura). Ver docs/products/SPEND.md.
|
|
4
4
|
export async function spend(a) {
|
|
5
5
|
const json = !!a.flags.json;
|
|
6
6
|
const sub = a.sub || 'show';
|
package/dist/commands/status.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { api } from '../api.js';
|
|
2
2
|
import { output, green } from '../output.js';
|
|
3
|
-
// koigrid status — status pages públicas generadas de tus Checks. Ver docs/STATUS-PAGES.md.
|
|
3
|
+
// koigrid status — status pages públicas generadas de tus Checks. Ver docs/products/STATUS-PAGES.md.
|
|
4
4
|
export async function status(a) {
|
|
5
5
|
const json = !!a.flags.json;
|
|
6
6
|
const sub = a.sub || 'ls';
|
package/dist/commands/storage.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { api } from '../api.js';
|
|
2
2
|
import { output, green } from '../output.js';
|
|
3
|
+
import { proyectoDeFlags } from '../proyecto.js';
|
|
3
4
|
export async function storage(a) {
|
|
4
5
|
const json = !!a.flags.json, sub = a.sub || 'ls';
|
|
5
6
|
if (sub === 'ls' || sub === 'list') {
|
|
@@ -11,8 +12,8 @@ export async function storage(a) {
|
|
|
11
12
|
if (sub === 'create') {
|
|
12
13
|
const name = a.positionals[0];
|
|
13
14
|
if (!name)
|
|
14
|
-
throw new Error('usage: koigrid storage create <name>');
|
|
15
|
-
const r = await api('/buckets', { method: 'POST', body: { name } });
|
|
15
|
+
throw new Error('usage: koigrid storage create <name> [--project <id>]');
|
|
16
|
+
const r = await api('/buckets', { method: 'POST', body: { name, ...proyectoDeFlags(a) } });
|
|
16
17
|
if (json)
|
|
17
18
|
console.log(JSON.stringify(r, null, 2));
|
|
18
19
|
else
|
|
@@ -27,10 +28,24 @@ export async function storage(a) {
|
|
|
27
28
|
console.log(green(`✓ Deleted ${id}`));
|
|
28
29
|
return;
|
|
29
30
|
}
|
|
31
|
+
// La ORGANIZACIÓN va en la tabla, no sólo en el --json (ficha f06dba3d): una clave emitida desde la cuenta
|
|
32
|
+
// equivocada sólo se ve si se enseña de quién es, y el error de julio tardó tres semanas en aparecer porque
|
|
33
|
+
// ni el panel ni esto lo decían.
|
|
30
34
|
if (sub === 'keys') {
|
|
31
35
|
const r = await api('/storage/keys');
|
|
32
36
|
const list = r.keys || r || [];
|
|
33
|
-
output(list, json, { rows: list.map((x) => ({ id: x.id.slice(0, 8), accessKey: x.accessKey || x.prefix || '' })), columns: ['id', 'accessKey'] });
|
|
37
|
+
output(list, json, { rows: list.map((x) => ({ id: x.id.slice(0, 8), accessKey: x.accessKey || x.prefix || '', account: x.organization?.name || x.organization?.id || '' })), columns: ['id', 'accessKey', 'account'] });
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
// QUÉ ALCANZA una clave, leído del almacén (no lo que creíamos al emitirla). `alcance: null` = no se pudo leer.
|
|
41
|
+
if (sub === 'key-scope') {
|
|
42
|
+
const kid = a.positionals[0];
|
|
43
|
+
if (!kid)
|
|
44
|
+
throw new Error('usage: koigrid storage key-scope <id>');
|
|
45
|
+
const r = await api(`/storage/keys/${encodeURIComponent(kid)}/scope`);
|
|
46
|
+
output(r, json, { rows: (r.alcance ?? []).map((b) => ({ bucket: b })), columns: ['bucket'] });
|
|
47
|
+
if (!json && r.alcance === null)
|
|
48
|
+
console.log('⚠️ no se pudo leer el alcance en el almacén — eso NO significa que no alcance nada');
|
|
34
49
|
return;
|
|
35
50
|
}
|
|
36
51
|
if (sub === 'key') {
|
|
@@ -64,6 +79,39 @@ export async function storage(a) {
|
|
|
64
79
|
console.log(json ? JSON.stringify(r, null, 2) : (r.restored ? green(`✓ Restored ${key}`) : `— ${key} no estaba borrado (nada que restaurar)`));
|
|
65
80
|
return;
|
|
66
81
|
}
|
|
82
|
+
// ⭐ Política de RÉPLICA EXTERNA. Existe por el pilar AI-first (lo que decide un humano lo decide un agente) y
|
|
83
|
+
// porque la decisión debe ser DECLARABLE: antes se replicaba todo porque nadie había decidido lo contrario.
|
|
84
|
+
if (sub === 'replication') {
|
|
85
|
+
const id = a.positionals[0], valor = a.positionals[1];
|
|
86
|
+
if (!id || !['on', 'off'].includes(String(valor)))
|
|
87
|
+
throw new Error('usage: koigrid storage replication <bucketId> on|off');
|
|
88
|
+
const r = await api(`/buckets/${encodeURIComponent(id)}`, { method: 'PUT', body: { mirrorOffsite: valor === 'on' } });
|
|
89
|
+
if (json)
|
|
90
|
+
return console.log(JSON.stringify(r, null, 2));
|
|
91
|
+
// Se enseña la CONSECUENCIA, no un «ok»: apagar la copia externa de un bucket merece leerse antes de seguir.
|
|
92
|
+
console.log(valor === 'on' ? green('✓ réplica externa ACTIVADA') : '⚠️ réplica externa DESACTIVADA');
|
|
93
|
+
return console.log(` ${r.meaning}`);
|
|
94
|
+
}
|
|
95
|
+
// ⭐ LECTURA PÚBLICA (ficha 7427948b): `public <id>` estado · `public <id> on [--prefix p/]` abre · `public <id> off` cierra.
|
|
96
|
+
// Abrir el bucket entero exige escribirlo (`on` sin --prefix): no sale de un flag olvidado sin que se diga.
|
|
97
|
+
if (sub === 'public') {
|
|
98
|
+
const id = a.positionals[0], accion = a.positionals[1];
|
|
99
|
+
if (!id || (accion && !['on', 'off'].includes(accion)))
|
|
100
|
+
throw new Error('usage: koigrid storage public <bucketId> [on [--prefix assets/] | off]');
|
|
101
|
+
const ruta = `/buckets/${encodeURIComponent(id)}/public`;
|
|
102
|
+
const r = !accion ? await api(ruta) : accion === 'off' ? await api(ruta, { method: 'DELETE' }) : await api(ruta, { method: 'PUT', body: { prefix: typeof a.flags.prefix === 'string' ? a.flags.prefix : '' } });
|
|
103
|
+
if (json)
|
|
104
|
+
return console.log(JSON.stringify(r, null, 2));
|
|
105
|
+
const b = r.bucket || {};
|
|
106
|
+
if (b.publicPrefix === null || b.publicPrefix === undefined)
|
|
107
|
+
return console.log(accion === 'off' ? green('✓ bucket privado otra vez') : 'privado (sólo con credencial o URL firmada)');
|
|
108
|
+
console.log(green(`✓ público${b.publicPrefix ? ` (sólo «${b.publicPrefix}»)` : ' (todo el bucket)'}`));
|
|
109
|
+
if (b.publicUrl)
|
|
110
|
+
console.log(` ${b.publicUrl}`);
|
|
111
|
+
if (r.warning)
|
|
112
|
+
console.log(`⚠️ ${r.warning}`);
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
67
115
|
// Explorador de objetos: ls por prefijo, url de subida/descarga, borrar
|
|
68
116
|
if (sub === 'objects' || sub === 'ls-objects') {
|
|
69
117
|
const id = a.positionals[0];
|