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.
@@ -1,4 +1,8 @@
1
- import { api } from '../api.js';
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
7
  // koigrid sandboxes — compute efímero (docker run --rm una vez). Ver docs/products/SANDBOXES.md.
4
8
  export async function sandboxes(a) {
@@ -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
+ }
@@ -92,6 +92,29 @@ export async function storage(a) {
92
92
  console.log(valor === 'on' ? green('✓ réplica externa ACTIVADA') : '⚠️ réplica externa DESACTIVADA');
93
93
  return console.log(` ${r.meaning}`);
94
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
+ // Lo servido por el nombre público en 24 h (ficha 2b384027): sólo lo trae el GET de estado.
114
+ if (r.traffic)
115
+ console.log(` últimas ${r.traffic.horas} h: ${r.traffic.requests} peticiones · ${(r.traffic.bytes / 1e6).toFixed(1)} MB · ${r.traffic.errors5xx} 5xx`);
116
+ return;
117
+ }
95
118
  // Explorador de objetos: ls por prefijo, url de subida/descarga, borrar
96
119
  if (sub === 'objects' || sub === 'ls-objects') {
97
120
  const id = a.positionals[0];
@@ -29,7 +29,11 @@ export async function tokens(a) {
29
29
  if (json)
30
30
  return console.log(JSON.stringify(r, null, 2));
31
31
  console.log(green(`✓ Token "${name}" created — copy it now, it won't be shown again:`));
32
- return console.log(r.token?.token || '');
32
+ console.log(r.token?.token || '');
33
+ // A stderr: el token sigue saliendo solo en stdout (`TOKEN=$(koigrid tokens create …)` no se rompe).
34
+ for (const w of r.warnings || [])
35
+ console.error(`⚠ ${w}`);
36
+ return;
33
37
  }
34
38
  if (sub === 'rm' || sub === 'delete' || sub === 'revoke') {
35
39
  const id = a.positionals[0];
package/dist/config.js CHANGED
@@ -12,7 +12,10 @@ export function loadConfig() {
12
12
  file = JSON.parse(readFileSync(FILE, 'utf8'));
13
13
  }
14
14
  catch { /* ignore */ }
15
- return { token: process.env.KOIGRID_TOKEN || file.token, api: process.env.KOIGRID_API || file.api || DEFAULT_API };
15
+ // Con KOIGRID_TOKEN manda el entorno: no se renueva lo que la CLI no guardó.
16
+ if (process.env.KOIGRID_TOKEN)
17
+ return { token: process.env.KOIGRID_TOKEN, api: process.env.KOIGRID_API || file.api || DEFAULT_API };
18
+ return { token: file.token, api: process.env.KOIGRID_API || file.api || DEFAULT_API, assertion: file.assertion, tokenExpiresAt: file.tokenExpiresAt };
16
19
  }
17
20
  export function saveConfig(c) {
18
21
  // El token es un secreto: crea el dir 0700 y ESCRIBE el fichero ya con modo 0600 (mode en writeFileSync) para
@@ -0,0 +1,41 @@
1
+ // cli/src/esperar.ts — `koigrid apps deploy` ESPERA al desenlace del despliegue (ficha f76082de).
2
+ // Antes volvía en cuanto el despliegue empezaba, sin URL ni resultado: un agente LLM que mudaba una app de Heroku (24-nov)
3
+ // tuvo que sondear GET /apps/:id/deployments a mano para saber si había terminado. Como `vercel deploy`, `railway up` o
4
+ // `fly deploy`: se espera, se enseña cada cambio de estado y se termina con la URL, o con el error y el final del registro.
5
+ // `--no-wait` vuelve al momento. La salida `--json` (guiones) sigue volviendo al momento salvo con `--wait`.
6
+ // La lectura (red), el reloj y la espera se inyectan: la decisión se prueba sin red (esperar.test.ts).
7
+ /** Estados en curso de un despliegue: cualquier otro es su desenlace (live, failed, superseded…). */
8
+ export const EN_CURSO = ['queued', 'building', 'deploying'];
9
+ export async function esperarDesenlace(o) {
10
+ const hasta = o.ahora() + o.plazoMs;
11
+ let ultimo;
12
+ let estado = '';
13
+ for (;;) {
14
+ // Un fallo de red al leer no es el desenlace: se reintenta hasta el plazo.
15
+ const d = await o.leer().catch(() => undefined);
16
+ if (d) {
17
+ ultimo = d;
18
+ if (d.status !== estado) {
19
+ estado = d.status;
20
+ o.alCambiar?.(estado);
21
+ }
22
+ if (!EN_CURSO.includes(d.status))
23
+ return { final: d, agotado: false };
24
+ }
25
+ if (o.ahora() >= hasta)
26
+ return { final: ultimo, agotado: true };
27
+ await o.dormir(o.cadaMs ?? 3000);
28
+ }
29
+ }
30
+ /** Las últimas `n` líneas no vacías de un registro (lo que se enseña cuando falla). */
31
+ export function finalDelRegistro(logs, n = 25) {
32
+ return String(logs ?? '').split('\n').filter((l) => l.trim()).slice(-n).join('\n');
33
+ }
34
+ /** ¿Se espera? Personas y agentes, sí por defecto; `--json` (guiones), sólo con `--wait`; `--no-wait` nunca. */
35
+ export function debeEsperar(flags, json) {
36
+ if (flags['no-wait'] || flags.detach)
37
+ return false;
38
+ if (flags.wait)
39
+ return true;
40
+ return !json;
41
+ }
package/dist/help.js CHANGED
@@ -5,7 +5,7 @@ export function buildHelp() {
5
5
  const label = c.name + (c.subs.length ? ` <${c.subs.join('|')}>` : '');
6
6
  return ` ${label.padEnd(30)} ${c.summary}`;
7
7
  });
8
- return `koigrid — flat-rate managed cloud, from your terminal (or your AI agent).
8
+ return `koigrid — managed cloud, pay only for what you reserve, from your terminal (or your AI agent).
9
9
 
10
10
  USAGE
11
11
  koigrid <command> [subcommand] [args] [--flags]
@@ -22,3 +22,16 @@ GLOBAL FLAGS
22
22
 
23
23
  Everything the CLI does is the koigrid API — an AI agent can run these commands directly.`;
24
24
  }
25
+ /**
26
+ * Ayuda de UN comando, o de uno de sus subcomandos si declara su `usage` (ficha f76082de). Sin esto, `koigrid apps deploy
27
+ * --help` enseñaba la ayuda global. null si el comando no existe (entonces vale la global).
28
+ */
29
+ export function buildCommandHelp(cmd, sub) {
30
+ const c = CLI_COMMANDS.find((x) => x.name === cmd || x.aliases?.includes(cmd));
31
+ if (!c)
32
+ return null;
33
+ if (sub && c.usage?.[sub])
34
+ return c.usage[sub];
35
+ 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
+ return `koigrid ${c.name} — ${c.summary}${subs}`;
37
+ }