koigrid 0.1.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/README.md ADDED
@@ -0,0 +1,57 @@
1
+ # koigrid CLI
2
+
3
+ Deploy apps, databases, Redis, storage and more on [koigrid](https://koigrid.com) — from your
4
+ terminal, your CI/CD, or your **AI agent** (Claude Code / Cursor can run these commands directly).
5
+
6
+ ## Install
7
+ ```bash
8
+ npm i -g koigrid # or: npx koigrid <command>
9
+ ```
10
+
11
+ ## Quickstart
12
+ ```bash
13
+ koigrid login # paste an API key (koigrid.com/dashboard/keys)
14
+ koigrid apps deploy web --image nginx:alpine --port 80
15
+ koigrid apps ls
16
+ koigrid db create prod --replicas 1
17
+ koigrid db url <id> # connection string
18
+ ```
19
+
20
+ ## Commands
21
+ ```
22
+ login / logout / whoami
23
+ apps ls | deploy <name> --image <img>|--repo <git-url> [--port N] | logs <id> | rm <id>
24
+ db ls | create <name> [--replicas N] | url <id>
25
+ redis ls | create <name> [--replicas N] | url <id>
26
+ storage ls | create <name> | rm <id> | keys | key
27
+ jobs ls | create <name> --schedule "<cron>" --image <img> [--command "..."] | rm <id> | trigger <id> | runs <id>
28
+ events ls | metrics
29
+ email send --to <addr> --subject <s> --text|--html <body> | messages | config
30
+ ```
31
+ Every koigrid product with an API has a command. A build-time guard (`lib/cli-coverage.test.ts`)
32
+ fails CI if a new product is added without its CLI command — so the CLI never falls behind.
33
+
34
+ ## For scripts, CI and AI agents
35
+ Every command accepts `--json` for machine-readable output, and `--token <t>` / `KOIGRID_TOKEN`
36
+ for non-interactive auth. Everything the CLI does is the koigrid REST API — so an AI agent can run
37
+ `koigrid` commands directly (more robust than a flaky MCP server).
38
+
39
+ ```bash
40
+ KOIGRID_TOKEN=koi_… koigrid apps ls --json | jq '.[].url'
41
+ ```
42
+
43
+ ## Auth
44
+ `koigrid login` stores a token in `~/.koigrid/config.json` (chmod 600). Override per-call with
45
+ `--token`, or globally with `KOIGRID_TOKEN`. Point at another API with `--api` / `KOIGRID_API`.
46
+
47
+ ## Security
48
+ - **No shell execution, zero dependencies** — the CLI only makes HTTPS calls to the koigrid API,
49
+ so there is no command-injection or supply-chain surface.
50
+ - **Token at rest**: stored in `~/.koigrid/config.json` with `chmod 600` (owner-only), like the
51
+ gh/vercel/aws CLIs. Your machine is the trust boundary.
52
+ - **Prefer `koigrid login` or `KOIGRID_TOKEN`** over `--token` in scripts: a token passed as a
53
+ CLI flag can show up in your shell history and process list (`ps`).
54
+ - **The server is the security boundary**: every call is authorized server-side by your token's
55
+ scopes, expiry, cost cap and organization — the CLI can never do more than the token allows.
56
+ - `--api` / `KOIGRID_API` only override the base URL (default `https://koigrid.com`); the token is
57
+ only ever sent there over TLS.
package/dist/api.js ADDED
@@ -0,0 +1,34 @@
1
+ // Cliente HTTP de la API de koigrid. Añade el Bearer token + maneja errores JSON de forma uniforme.
2
+ import { loadConfig, DEFAULT_API } from './config.js';
3
+ export class ApiError extends Error {
4
+ status;
5
+ detail;
6
+ constructor(status, message, detail) {
7
+ super(message);
8
+ this.status = status;
9
+ this.detail = detail;
10
+ this.name = 'ApiError';
11
+ }
12
+ }
13
+ export async function api(path, opts = {}) {
14
+ const cfg = loadConfig();
15
+ const token = opts.token || cfg.token;
16
+ const base = opts.api || cfg.api || DEFAULT_API;
17
+ if (!token)
18
+ throw new ApiError(401, 'Not logged in. Run `koigrid login` (or set KOIGRID_TOKEN).');
19
+ const res = await fetch(`${base}${path}`, {
20
+ method: opts.method || 'GET',
21
+ headers: { Authorization: `Bearer ${token}`, ...(opts.body ? { 'content-type': 'application/json' } : {}) },
22
+ body: opts.body ? JSON.stringify(opts.body) : undefined,
23
+ signal: AbortSignal.timeout(30_000),
24
+ }).catch((e) => { throw new ApiError(0, `network error: ${e?.message || e}`); });
25
+ const text = await res.text();
26
+ let json = null;
27
+ try {
28
+ json = text ? JSON.parse(text) : null;
29
+ }
30
+ catch { /* non-json */ }
31
+ if (!res.ok)
32
+ throw new ApiError(res.status, json?.error || `HTTP ${res.status}`, json?.detail);
33
+ return json;
34
+ }
package/dist/args.js ADDED
@@ -0,0 +1,28 @@
1
+ /** `apps deploy web --image nginx --port 80 --json` → {cmd:apps, sub:deploy, positionals:[web], flags:{image,port,json}} */
2
+ export function parseArgs(argv) {
3
+ const positionals = [];
4
+ const flags = {};
5
+ for (let i = 0; i < argv.length; i++) {
6
+ const a = argv[i];
7
+ if (a.startsWith('--')) {
8
+ const key = a.slice(2);
9
+ const next = argv[i + 1];
10
+ if (next !== undefined && !next.startsWith('-')) {
11
+ flags[key] = next;
12
+ i++;
13
+ }
14
+ else {
15
+ flags[key] = true;
16
+ }
17
+ }
18
+ else if (a.startsWith('-') && a.length === 2) {
19
+ flags[a.slice(1)] = true;
20
+ }
21
+ else {
22
+ positionals.push(a);
23
+ }
24
+ }
25
+ const cmd = positionals.shift();
26
+ const sub = positionals.shift();
27
+ return { cmd, sub, positionals, flags };
28
+ }
@@ -0,0 +1,28 @@
1
+ import { api } from '../api.js';
2
+ import { output, green } from '../output.js';
3
+ export async function alarms(a) {
4
+ const json = !!a.flags.json, sub = a.sub || 'ls';
5
+ if (sub === 'ls' || sub === 'list') {
6
+ const r = await api('/alarms');
7
+ const l = r.alarms || r || [];
8
+ return output(l, json, { rows: l.map((x) => ({ id: String(x.id).slice(0, 8), name: x.name, metric: x.metric, threshold: String(x.threshold ?? '') })), columns: ['id', 'name', 'metric', 'threshold'] });
9
+ }
10
+ if (sub === 'create') {
11
+ const name = a.positionals[0];
12
+ if (!name || !a.flags.metric || a.flags.threshold === undefined)
13
+ throw new Error('usage: koigrid alarms create <name> --metric <m> --threshold N [--comparison gt|lt]');
14
+ const body = { name, metric: a.flags.metric, threshold: Number(a.flags.threshold) };
15
+ if (a.flags.comparison)
16
+ body.comparison = a.flags.comparison;
17
+ const r = await api('/alarms', { method: 'POST', body });
18
+ return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ Alarm "${name}" created`));
19
+ }
20
+ if (sub === 'rm' || sub === 'delete') {
21
+ const id = a.positionals[0];
22
+ if (!id)
23
+ throw new Error('usage: koigrid alarms rm <id>');
24
+ await api(`/alarms/${encodeURIComponent(id)}`, { method: 'DELETE' });
25
+ return console.log(green(`✓ Deleted ${id}`));
26
+ }
27
+ throw new Error(`unknown: alarms ${sub}`);
28
+ }
@@ -0,0 +1,172 @@
1
+ import { api } from '../api.js';
2
+ import { output, green } from '../output.js';
3
+ export async function apps(a) {
4
+ const json = !!a.flags.json, sub = a.sub || 'ls';
5
+ const id = a.positionals[0];
6
+ const need = (m) => { if (!id)
7
+ throw new Error(`usage: koigrid apps ${sub} <id>${m}`); };
8
+ switch (sub) {
9
+ case 'ls':
10
+ case 'list': {
11
+ const r = await api('/apps');
12
+ const l = r.apps || r || [];
13
+ return output(l, json, { rows: l.map((x) => ({ id: x.id.slice(0, 8), name: x.name, status: x.status, url: x.url || '—' })), columns: ['id', 'name', 'status', 'url'] });
14
+ }
15
+ case 'deploy': {
16
+ const name = a.positionals[0], image = a.flags.image, repo = a.flags.repo;
17
+ if (!name || (!image && !repo))
18
+ throw new Error('usage: koigrid apps deploy <name> --image <img>|--repo <git-url> [--port N]');
19
+ const port = a.flags.port ? Number(a.flags.port) : 3000;
20
+ const app = await api('/apps', { method: 'POST', body: repo ? { name, sourceType: 'git', repo, port } : { name, sourceType: 'image', image, port } });
21
+ const aid = app.app?.id || app.id;
22
+ await api(`/apps/${encodeURIComponent(aid)}/deployments`, { method: 'POST', body: {} });
23
+ return json ? console.log(JSON.stringify({ id: aid, status: 'queued' }, null, 2)) : console.log(green(`✓ Deploying "${name}"…`));
24
+ }
25
+ case 'deployments':
26
+ need('');
27
+ {
28
+ const r = await api(`/apps/${encodeURIComponent(id)}/deployments`);
29
+ const l = r.deployments || r || [];
30
+ return output(l, json, { rows: l.map((x) => ({ id: x.id.slice(0, 8), status: x.status, source: x.source || '—' })), columns: ['id', 'status', 'source'] });
31
+ }
32
+ case 'logs':
33
+ need('');
34
+ return console.log((await api(`/apps/${encodeURIComponent(id)}/logs?tail=${a.flags.tail || 200}`)).logs || '');
35
+ case 'rm':
36
+ case 'delete':
37
+ need('');
38
+ await api(`/apps/${encodeURIComponent(id)}`, { method: 'DELETE' });
39
+ return console.log(green(`✓ Deleted ${id}`));
40
+ case 'rollback': {
41
+ need(' --deployment <depId>');
42
+ const d = a.flags.deployment;
43
+ if (!d)
44
+ throw new Error('need --deployment <depId>');
45
+ await api(`/apps/${encodeURIComponent(id)}/rollback`, { method: 'POST', body: { deploymentId: d } });
46
+ return console.log(green('✓ Rolling back…'));
47
+ }
48
+ case 'scale': {
49
+ need(' [--replicas N]');
50
+ if (a.flags.replicas === undefined) {
51
+ const r = await api(`/apps/${encodeURIComponent(id)}/scale`);
52
+ return console.log(json ? JSON.stringify(r, null, 2) : `replicas: ${r.scale?.replicas}`);
53
+ }
54
+ const r = await api(`/apps/${encodeURIComponent(id)}/scale`, { method: 'PUT', body: { replicas: Number(a.flags.replicas) } });
55
+ return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ Scaled to ${a.flags.replicas}`));
56
+ }
57
+ case 'autoscale': {
58
+ need(' --enabled true|false [--min N --max N --target-cpu N]');
59
+ if (a.flags.enabled === undefined) {
60
+ const r = await api(`/apps/${encodeURIComponent(id)}/autoscale`);
61
+ return console.log(json ? JSON.stringify(r, null, 2) : JSON.stringify(r.autoscale));
62
+ }
63
+ const body = { enabled: a.flags.enabled === 'true' || a.flags.enabled === true };
64
+ if (a.flags.min)
65
+ body.min = Number(a.flags.min);
66
+ if (a.flags.max)
67
+ body.max = Number(a.flags.max);
68
+ if (a.flags['target-cpu'])
69
+ body.targetCpuPct = Number(a.flags['target-cpu']);
70
+ const r = await api(`/apps/${encodeURIComponent(id)}/autoscale`, { method: 'PUT', body });
71
+ return console.log(json ? JSON.stringify(r, null, 2) : green('✓ Autoscale updated'));
72
+ }
73
+ case 'env': {
74
+ need(' set KEY=VAL | rm KEY | ls');
75
+ const act = a.positionals[1];
76
+ if (!act || act === 'ls') {
77
+ const r = await api(`/apps/${encodeURIComponent(id)}/env`);
78
+ return console.log(json ? JSON.stringify(r, null, 2) : (r.env || r.keys || []).join('\n'));
79
+ }
80
+ if (act === 'rm') {
81
+ const k = a.positionals[2];
82
+ if (!k)
83
+ throw new Error('need KEY');
84
+ await api(`/apps/${encodeURIComponent(id)}/env?key=${encodeURIComponent(k)}`, { method: 'DELETE' });
85
+ return console.log(green(`✓ Removed ${k}`));
86
+ }
87
+ if (act === 'set') {
88
+ const kv = a.positionals[2];
89
+ if (!kv?.includes('='))
90
+ throw new Error('need KEY=VALUE');
91
+ const [k, ...v] = kv.split('=');
92
+ await api(`/apps/${encodeURIComponent(id)}/env`, { method: 'POST', body: { env: { [k]: v.join('=') } } });
93
+ return console.log(green(`✓ Set ${k} (redeploying)`));
94
+ }
95
+ throw new Error('usage: koigrid apps env <id> set KEY=VAL | rm KEY | ls');
96
+ }
97
+ case 'domains': {
98
+ need(' add <domain> | rm <domain> | ls');
99
+ const act = a.positionals[1];
100
+ if (!act || act === 'ls') {
101
+ const r = await api(`/apps/${encodeURIComponent(id)}/domains`);
102
+ const l = r.domains || r || [];
103
+ return output(l, json, { rows: l.map((x) => ({ domain: x.domain || x })), columns: ['domain'] });
104
+ }
105
+ if (act === 'add') {
106
+ const d = a.positionals[2];
107
+ if (!d)
108
+ throw new Error('need <domain>');
109
+ const r = await api(`/apps/${encodeURIComponent(id)}/domains`, { method: 'POST', body: { domain: d } });
110
+ return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ Added ${d} — set the CNAME shown`));
111
+ }
112
+ if (act === 'rm') {
113
+ const d = a.positionals[2];
114
+ if (!d)
115
+ throw new Error('need <domain>');
116
+ await api(`/apps/${encodeURIComponent(id)}/domains?domain=${encodeURIComponent(d)}`, { method: 'DELETE' });
117
+ return console.log(green(`✓ Removed ${d}`));
118
+ }
119
+ throw new Error('usage: koigrid apps domains <id> add <domain> | rm <domain> | ls');
120
+ }
121
+ case 'volumes': {
122
+ need(' add <name> --size N --mount /path | rm <volId> | ls');
123
+ const act = a.positionals[1];
124
+ if (!act || act === 'ls') {
125
+ const r = await api(`/apps/${encodeURIComponent(id)}/volumes`);
126
+ const l = r.volumes || r || [];
127
+ return output(l, json, { rows: l.map((x) => ({ id: String(x.id).slice(0, 8), name: x.name, gb: String(x.sizeGb || ''), mount: x.mountPath || '' })), columns: ['id', 'name', 'gb', 'mount'] });
128
+ }
129
+ if (act === 'add') {
130
+ const name = a.positionals[2];
131
+ if (!name || !a.flags.size || !a.flags.mount)
132
+ throw new Error('need <name> --size N --mount /path');
133
+ const r = await api(`/apps/${encodeURIComponent(id)}/volumes`, { method: 'POST', body: { name, sizeGb: Number(a.flags.size), mountPath: a.flags.mount } });
134
+ return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ Volume "${name}" attached`));
135
+ }
136
+ if (act === 'rm') {
137
+ const v = a.positionals[2];
138
+ if (!v)
139
+ throw new Error('need <volId>');
140
+ await api(`/apps/${encodeURIComponent(id)}/volumes/${encodeURIComponent(v)}`, { method: 'DELETE' });
141
+ return console.log(green(`✓ Removed ${v}`));
142
+ }
143
+ throw new Error('usage: koigrid apps volumes <id> add <name> --size N --mount /path | rm <volId> | ls');
144
+ }
145
+ case 'cdn': {
146
+ need(' on|off');
147
+ const act = a.positionals[1];
148
+ if (!act) {
149
+ const r = await api(`/apps/${encodeURIComponent(id)}/cdn`);
150
+ return console.log(json ? JSON.stringify(r, null, 2) : `cdn: ${r.cdn?.enabled ? 'on' : 'off'}`);
151
+ }
152
+ const r = await api(`/apps/${encodeURIComponent(id)}/cdn`, { method: 'PUT', body: { enabled: act === 'on' } });
153
+ return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ CDN ${act}`));
154
+ }
155
+ case 'github': {
156
+ need(' <owner/repo> [--branch b] [--auto-deploy]');
157
+ const repo = a.positionals[1];
158
+ if (!repo) {
159
+ const r = await api(`/apps/${encodeURIComponent(id)}/github`);
160
+ return console.log(JSON.stringify(r, null, 2));
161
+ }
162
+ const body = { githubRepo: repo, autoDeploy: !!a.flags['auto-deploy'] };
163
+ if (a.flags.branch)
164
+ body.branch = a.flags.branch;
165
+ if (a.flags.installation)
166
+ body.installationId = a.flags.installation;
167
+ const r = await api(`/apps/${encodeURIComponent(id)}/github`, { method: 'PUT', body });
168
+ return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ Connected ${repo}`));
169
+ }
170
+ default: throw new Error(`unknown: apps ${sub}`);
171
+ }
172
+ }
@@ -0,0 +1,25 @@
1
+ import { createInterface } from 'node:readline/promises';
2
+ import { api } from '../api.js';
3
+ import { saveConfig, clearConfig, loadConfig } from '../config.js';
4
+ import { green, dim } from '../output.js';
5
+ export async function login(flags) {
6
+ let token = typeof flags.token === 'string' ? flags.token : '';
7
+ if (!token) {
8
+ console.log(dim('Create an API key at https://koigrid.com/dashboard/keys and paste it here.'));
9
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
10
+ token = (await rl.question('Token (koi_…): ')).trim();
11
+ rl.close();
12
+ }
13
+ const me = await api('/me', { token });
14
+ const api_ = typeof flags.api === 'string' ? flags.api : loadConfig().api;
15
+ saveConfig({ token, api: api_ });
16
+ console.log(green(`✓ Logged in as ${me?.user?.email || me?.email || 'user'}`));
17
+ }
18
+ export async function logout() { clearConfig(); console.log('✓ Logged out'); }
19
+ export async function whoami(json) {
20
+ const me = await api('/me');
21
+ if (json)
22
+ console.log(JSON.stringify(me, null, 2));
23
+ else
24
+ console.log(me?.user?.email || me?.email || JSON.stringify(me));
25
+ }
@@ -0,0 +1,65 @@
1
+ import { api } from '../api.js';
2
+ import { output, green } from '../output.js';
3
+ export async function db(a) {
4
+ const json = !!a.flags.json, sub = a.sub || 'ls', id = a.positionals[0];
5
+ const need = () => { if (!id)
6
+ throw new Error(`usage: koigrid db ${sub} <id>`); };
7
+ switch (sub) {
8
+ case 'ls':
9
+ case 'list': {
10
+ const r = await api('/databases');
11
+ const l = r.databases || r || [];
12
+ return output(l, json, { rows: l.map((x) => ({ id: x.id.slice(0, 8), name: x.name, status: x.status, replicas: String(x.desiredReplicas ?? 0) })), columns: ['id', 'name', 'status', 'replicas'] });
13
+ }
14
+ case 'create': {
15
+ const name = a.positionals[0];
16
+ if (!name)
17
+ throw new Error('usage: koigrid db create <name> [--replicas N]');
18
+ const body = { name };
19
+ if (a.flags.replicas)
20
+ body.replicas = Number(a.flags.replicas);
21
+ const r = await api('/databases', { method: 'POST', body });
22
+ return console.log(json ? JSON.stringify(r.database || r, null, 2) : green(`✓ Creating "${name}"…`));
23
+ }
24
+ case 'rm':
25
+ case 'delete':
26
+ need();
27
+ await api(`/databases/${encodeURIComponent(id)}`, { method: 'DELETE' });
28
+ return console.log(green(`✓ Deleted ${id}`));
29
+ case 'url':
30
+ case 'connection': {
31
+ need();
32
+ const r = await api(`/databases/${encodeURIComponent(id)}/connection`);
33
+ if (json)
34
+ return console.log(JSON.stringify(r.connection, null, 2));
35
+ console.log(r.connection?.uri);
36
+ if (r.connection?.readUri)
37
+ console.log('# read-only:', r.connection.readUri);
38
+ return;
39
+ }
40
+ case 'metrics':
41
+ need();
42
+ return console.log(JSON.stringify(await api(`/databases/${encodeURIComponent(id)}/metrics`), null, 2));
43
+ case 'backups': {
44
+ need();
45
+ if (a.positionals[1] === 'create') {
46
+ await api(`/databases/${encodeURIComponent(id)}/backups`, { method: 'POST' });
47
+ return console.log(green('✓ Backup started'));
48
+ }
49
+ const r = await api(`/databases/${encodeURIComponent(id)}/backups`);
50
+ const l = r.backups || r || [];
51
+ return output(l, json, { rows: l.map((x) => ({ id: String(x.id).slice(0, 8), status: x.status, at: String(x.createdAt || '').slice(0, 16) })), columns: ['id', 'status', 'at'] });
52
+ }
53
+ case 'restore': {
54
+ need();
55
+ const body = {};
56
+ if (a.flags.name)
57
+ body.name = a.flags.name;
58
+ if (a.flags.time)
59
+ body.targetTime = a.flags.time;
60
+ const r = await api(`/databases/${encodeURIComponent(id)}/restore`, { method: 'POST', body });
61
+ return console.log(json ? JSON.stringify(r, null, 2) : green('✓ Restoring to a new cluster…'));
62
+ }
63
+ default: throw new Error(`unknown: db ${sub}`);
64
+ }
65
+ }
@@ -0,0 +1,32 @@
1
+ import { api } from '../api.js';
2
+ import { output, green } from '../output.js';
3
+ export async function email(a) {
4
+ const json = !!a.flags.json, sub = a.sub || 'messages';
5
+ if (sub === 'send') {
6
+ const to = a.flags.to, subject = a.flags.subject;
7
+ if (!to || !subject)
8
+ throw new Error('usage: koigrid email send --to <addr> --subject <s> --text <body>|--html <body>');
9
+ const body = { to, subject };
10
+ if (a.flags.text)
11
+ body.text = a.flags.text;
12
+ if (a.flags.html)
13
+ body.html = a.flags.html;
14
+ if (a.flags.from)
15
+ body.from = a.flags.from;
16
+ const r = await api('/email/send', { method: 'POST', body });
17
+ console.log(json ? JSON.stringify(r, null, 2) : green(`✓ Sent to ${to}`));
18
+ return;
19
+ }
20
+ if (sub === 'messages') {
21
+ const r = await api('/email/messages');
22
+ const list = r.messages || r || [];
23
+ output(list, json, { rows: list.map((x) => ({ to: x.to, subject: (x.subject || '').slice(0, 30), status: x.status })), columns: ['to', 'subject', 'status'] });
24
+ return;
25
+ }
26
+ if (sub === 'config') {
27
+ const r = await api('/email/config');
28
+ console.log(JSON.stringify(r, null, 2));
29
+ return;
30
+ }
31
+ throw new Error(`unknown: email ${sub}`);
32
+ }
@@ -0,0 +1,17 @@
1
+ import { api } from '../api.js';
2
+ import { output } from '../output.js';
3
+ export async function events(a) {
4
+ const json = !!a.flags.json, sub = a.sub || 'ls';
5
+ if (sub === 'ls' || sub === 'list') {
6
+ const r = await api('/events');
7
+ const list = r.events || r || [];
8
+ output(list, json, { rows: list.map((x) => ({ time: String(x.createdAt || '').slice(0, 16), type: x.type, message: (x.message || '').slice(0, 50) })), columns: ['time', 'type', 'message'] });
9
+ return;
10
+ }
11
+ if (sub === 'metrics') {
12
+ const r = await api('/metrics');
13
+ console.log(JSON.stringify(r, null, 2));
14
+ return;
15
+ }
16
+ throw new Error(`unknown: events ${sub}`);
17
+ }
@@ -0,0 +1,70 @@
1
+ import { api } from '../api.js';
2
+ import { output, green } from '../output.js';
3
+ export async function jobs(a) {
4
+ const json = !!a.flags.json, sub = a.sub || 'ls';
5
+ if (sub === 'ls' || sub === 'list') {
6
+ const r = await api('/jobs');
7
+ const list = r.jobs || r || [];
8
+ output(list, json, { rows: list.map((x) => ({ id: x.id.slice(0, 8), name: x.name, schedule: x.schedule, last: x.lastStatus || '—' })), columns: ['id', 'name', 'schedule', 'last'] });
9
+ return;
10
+ }
11
+ if (sub === 'create') {
12
+ const name = a.positionals[0];
13
+ const schedule = a.flags.schedule;
14
+ const image = a.flags.image;
15
+ if (!name || !schedule || !image)
16
+ throw new Error('usage: koigrid jobs create <name> --schedule "<cron>" --image <img> [--command "..."]');
17
+ const body = { name, schedule, image };
18
+ if (a.flags.command)
19
+ body.command = a.flags.command;
20
+ const r = await api('/jobs', { method: 'POST', body });
21
+ if (json)
22
+ console.log(JSON.stringify(r, null, 2));
23
+ else
24
+ console.log(green(`✓ Job "${name}" created (${schedule})`));
25
+ return;
26
+ }
27
+ if (sub === 'rm' || sub === 'delete') {
28
+ const id = a.positionals[0];
29
+ if (!id)
30
+ throw new Error('usage: koigrid jobs rm <id>');
31
+ await api(`/jobs/${encodeURIComponent(id)}`, { method: 'DELETE' });
32
+ console.log(green(`✓ Deleted ${id}`));
33
+ return;
34
+ }
35
+ if (sub === 'trigger') {
36
+ const id = a.positionals[0];
37
+ if (!id)
38
+ throw new Error('usage: koigrid jobs trigger <id>');
39
+ const r = await api(`/jobs/${encodeURIComponent(id)}/trigger`, { method: 'POST' });
40
+ console.log(json ? JSON.stringify(r, null, 2) : green(`✓ Triggered`));
41
+ return;
42
+ }
43
+ if (sub === 'runs') {
44
+ const id = a.positionals[0];
45
+ if (!id)
46
+ throw new Error('usage: koigrid jobs runs <id>');
47
+ const r = await api(`/jobs/${encodeURIComponent(id)}/runs`);
48
+ const list = r.runs || r || [];
49
+ output(list, json, { rows: list.map((x) => ({ id: x.id.slice(0, 8), status: x.status, exit: String(x.exitCode ?? '—') })), columns: ['id', 'status', 'exit'] });
50
+ return;
51
+ }
52
+ if (sub === 'update') {
53
+ const id = a.positionals[0];
54
+ if (!id)
55
+ throw new Error('usage: koigrid jobs update <id> [--schedule ..] [--image ..] [--enabled true|false]');
56
+ const body = {};
57
+ if (a.flags.schedule)
58
+ body.schedule = a.flags.schedule;
59
+ if (a.flags.image)
60
+ body.image = a.flags.image;
61
+ if (a.flags.command)
62
+ body.command = a.flags.command;
63
+ if (a.flags.enabled !== undefined)
64
+ body.enabled = a.flags.enabled === 'true' || a.flags.enabled === true;
65
+ const r = await api(`/jobs/${encodeURIComponent(id)}`, { method: 'PATCH', body });
66
+ console.log(json ? JSON.stringify(r, null, 2) : green('✓ Job updated'));
67
+ return;
68
+ }
69
+ throw new Error(`unknown: jobs ${sub}`);
70
+ }
@@ -0,0 +1,58 @@
1
+ import { api } from '../api.js';
2
+ import { output, green } from '../output.js';
3
+ export async function redis(a) {
4
+ const json = !!a.flags.json, sub = a.sub || 'ls', id = a.positionals[0];
5
+ const need = () => { if (!id)
6
+ throw new Error(`usage: koigrid redis ${sub} <id>`); };
7
+ switch (sub) {
8
+ case 'ls':
9
+ case 'list': {
10
+ const r = await api('/redis');
11
+ const l = r.caches || r.redis || r || [];
12
+ return output(l, json, { rows: l.map((x) => ({ id: x.id.slice(0, 8), name: x.name, status: x.status, replicas: String(x.desiredReplicas ?? 0) })), columns: ['id', 'name', 'status', 'replicas'] });
13
+ }
14
+ case 'create': {
15
+ const name = a.positionals[0];
16
+ if (!name)
17
+ throw new Error('usage: koigrid redis create <name> [--replicas N]');
18
+ const body = { name };
19
+ if (a.flags.replicas)
20
+ body.replicas = Number(a.flags.replicas);
21
+ const r = await api('/redis', { method: 'POST', body });
22
+ return console.log(json ? JSON.stringify(r.cache || r, null, 2) : green(`✓ Creating "${name}"…`));
23
+ }
24
+ case 'rm':
25
+ case 'delete':
26
+ need();
27
+ await api(`/redis/${encodeURIComponent(id)}`, { method: 'DELETE' });
28
+ return console.log(green(`✓ Deleted ${id}`));
29
+ case 'url':
30
+ case 'connection': {
31
+ need();
32
+ const r = await api(`/redis/${encodeURIComponent(id)}/connection`);
33
+ return console.log(json ? JSON.stringify(r.connection, null, 2) : r.connection?.uri);
34
+ }
35
+ case 'metrics':
36
+ need();
37
+ return console.log(JSON.stringify(await api(`/redis/${encodeURIComponent(id)}/metrics`), null, 2));
38
+ case 'backups': {
39
+ need();
40
+ if (a.positionals[1] === 'create') {
41
+ await api(`/redis/${encodeURIComponent(id)}/backups`, { method: 'POST' });
42
+ return console.log(green('✓ Snapshot started'));
43
+ }
44
+ const r = await api(`/redis/${encodeURIComponent(id)}/backups`);
45
+ const l = r.backups || r || [];
46
+ return output(l, json, { rows: l.map((x) => ({ id: String(x.id).slice(0, 8), status: x.status })), columns: ['id', 'status'] });
47
+ }
48
+ case 'restore': {
49
+ need();
50
+ const body = {};
51
+ if (a.flags.name)
52
+ body.name = a.flags.name;
53
+ const r = await api(`/redis/${encodeURIComponent(id)}/restore`, { method: 'POST', body });
54
+ return console.log(json ? JSON.stringify(r, null, 2) : green('✓ Restoring to a new cache…'));
55
+ }
56
+ default: throw new Error(`unknown: redis ${sub}`);
57
+ }
58
+ }
@@ -0,0 +1,50 @@
1
+ import { api } from '../api.js';
2
+ import { output, green } from '../output.js';
3
+ export async function storage(a) {
4
+ const json = !!a.flags.json, sub = a.sub || 'ls';
5
+ if (sub === 'ls' || sub === 'list') {
6
+ const r = await api('/buckets');
7
+ const list = r.buckets || r || [];
8
+ output(list, json, { rows: list.map((x) => ({ id: x.id.slice(0, 8), name: x.name, bucket: x.bucketName || '' })), columns: ['id', 'name', 'bucket'] });
9
+ return;
10
+ }
11
+ if (sub === 'create') {
12
+ const name = a.positionals[0];
13
+ if (!name)
14
+ throw new Error('usage: koigrid storage create <name>');
15
+ const r = await api('/buckets', { method: 'POST', body: { name } });
16
+ if (json)
17
+ console.log(JSON.stringify(r, null, 2));
18
+ else
19
+ console.log(green(`✓ Bucket "${name}" created`));
20
+ return;
21
+ }
22
+ if (sub === 'rm' || sub === 'delete') {
23
+ const id = a.positionals[0];
24
+ if (!id)
25
+ throw new Error('usage: koigrid storage rm <id>');
26
+ await api(`/buckets/${encodeURIComponent(id)}`, { method: 'DELETE' });
27
+ console.log(green(`✓ Deleted ${id}`));
28
+ return;
29
+ }
30
+ if (sub === 'keys') {
31
+ const r = await api('/storage/keys');
32
+ 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'] });
34
+ return;
35
+ }
36
+ if (sub === 'key') {
37
+ const r = await api('/storage/keys', { method: 'POST' });
38
+ console.log(json ? JSON.stringify(r, null, 2) : green('✓ Key created (secret shown once):\n') + JSON.stringify(r, null, 2));
39
+ return;
40
+ }
41
+ if (sub === 'key' && a.positionals[0] === 'rm') {
42
+ const kid = a.positionals[1];
43
+ if (!kid)
44
+ throw new Error('usage: koigrid storage key rm <id>');
45
+ await api(`/storage/keys/${encodeURIComponent(kid)}`, { method: 'DELETE' });
46
+ console.log(green(`✓ Revoked ${kid}`));
47
+ return;
48
+ }
49
+ throw new Error(`unknown: storage ${sub}`);
50
+ }
@@ -0,0 +1,5 @@
1
+ import { api } from '../api.js';
2
+ export async function usage(a) {
3
+ const r = await api('/usage');
4
+ console.log(JSON.stringify(r, null, 2));
5
+ }
package/dist/config.js ADDED
@@ -0,0 +1,28 @@
1
+ // Config del CLI: token + api base en ~/.koigrid/config.json (perms 600). Env override: KOIGRID_TOKEN/KOIGRID_API.
2
+ import { homedir } from 'node:os';
3
+ import { join } from 'node:path';
4
+ import { readFileSync, writeFileSync, mkdirSync, rmSync, existsSync, chmodSync } from 'node:fs';
5
+ const DIR = join(homedir(), '.koigrid');
6
+ const FILE = join(DIR, 'config.json');
7
+ export const DEFAULT_API = 'https://koigrid.com/api/v1';
8
+ export function loadConfig() {
9
+ let file = {};
10
+ try {
11
+ if (existsSync(FILE))
12
+ file = JSON.parse(readFileSync(FILE, 'utf8'));
13
+ }
14
+ catch { /* ignore */ }
15
+ return { token: process.env.KOIGRID_TOKEN || file.token, api: process.env.KOIGRID_API || file.api || DEFAULT_API };
16
+ }
17
+ export function saveConfig(c) {
18
+ mkdirSync(DIR, { recursive: true });
19
+ writeFileSync(FILE, JSON.stringify(c, null, 2));
20
+ try {
21
+ chmodSync(FILE, 0o600);
22
+ }
23
+ catch { /* windows */ }
24
+ }
25
+ export function clearConfig() { try {
26
+ rmSync(FILE);
27
+ }
28
+ catch { /* ignore */ } }
package/dist/help.js ADDED
@@ -0,0 +1,24 @@
1
+ // Ayuda GENERADA del manifest (nunca se queda obsoleta al añadir comandos).
2
+ import { CLI_COMMANDS } from './manifest.js';
3
+ export function buildHelp() {
4
+ const rows = CLI_COMMANDS.map((c) => {
5
+ const label = c.name + (c.subs.length ? ` <${c.subs.join('|')}>` : '');
6
+ return ` ${label.padEnd(30)} ${c.summary}`;
7
+ });
8
+ return `koigrid — flat-rate managed cloud, from your terminal (or your AI agent).
9
+
10
+ USAGE
11
+ koigrid <command> [subcommand] [args] [--flags]
12
+
13
+ COMMANDS
14
+ ${rows.join('\n')}
15
+
16
+ GLOBAL FLAGS
17
+ --json Machine-readable output (scripts / AI agents / CI)
18
+ --token <t> API token for this call (overrides stored; or KOIGRID_TOKEN)
19
+ --api <url> API base URL (default https://koigrid.com/api/v1)
20
+ -h, --help Show help
21
+ -v, --version Show version
22
+
23
+ Everything the CLI does is the koigrid API — an AI agent can run these commands directly.`;
24
+ }
package/dist/index.js ADDED
@@ -0,0 +1,46 @@
1
+ #!/usr/bin/env node
2
+ // Entry del CLI. Dispatch data-driven desde el manifest (resolveCommand) + registro de handlers.
3
+ // Añadir un comando = fichero en commands/ + entrada en registry.ts + manifest.ts (los guards lo obligan).
4
+ import { parseArgs } from './args.js';
5
+ import { buildHelp } from './help.js';
6
+ import { ApiError } from './api.js';
7
+ import { resolveCommand, CLI_COMMANDS } from './manifest.js';
8
+ import { HANDLERS } from './registry.js';
9
+ import { red } from './output.js';
10
+ import { createRequire } from 'node:module';
11
+ const version = (() => { try {
12
+ return createRequire(import.meta.url)('../package.json').version;
13
+ }
14
+ catch {
15
+ return '0.1.0';
16
+ } })();
17
+ async function main() {
18
+ const a = parseArgs(process.argv.slice(2));
19
+ if (a.flags.version || a.flags.v) {
20
+ console.log(version);
21
+ return;
22
+ }
23
+ // Ayuda humana, o `help --json` → manifest completo para que un AGENTE IA introspeccione TODO el CLI.
24
+ if (!a.cmd || a.cmd === 'help' || a.flags.help || a.flags.h) {
25
+ console.log(a.flags.json ? JSON.stringify(CLI_COMMANDS, null, 2) : buildHelp());
26
+ return;
27
+ }
28
+ if (typeof a.flags.token === 'string')
29
+ process.env.KOIGRID_TOKEN = a.flags.token;
30
+ if (typeof a.flags.api === 'string')
31
+ process.env.KOIGRID_API = a.flags.api;
32
+ const name = resolveCommand(a.cmd);
33
+ if (!name || !HANDLERS[name]) {
34
+ console.error(red(`Unknown command: ${a.cmd}`) + `\nRun \`koigrid --help\`.`);
35
+ process.exit(1);
36
+ }
37
+ await HANDLERS[name](a);
38
+ }
39
+ main().catch((e) => {
40
+ if (e instanceof ApiError) {
41
+ console.error(red(`✗ ${e.message}`) + (e.detail ? `\n ${e.detail}` : ''));
42
+ process.exit(e.status === 401 ? 2 : 1);
43
+ }
44
+ console.error(red(`✗ ${e?.message || e}`));
45
+ process.exit(1);
46
+ });
@@ -0,0 +1,24 @@
1
+ export const CLI_COMMANDS = [
2
+ { name: 'login', summary: 'Authenticate (paste an API key, or --token / KOIGRID_TOKEN)', subs: [], endpoints: [] },
3
+ { name: 'logout', summary: 'Remove the stored credentials', subs: [], endpoints: [] },
4
+ { name: 'whoami', summary: 'Show the authenticated account', subs: [], endpoints: ['me'] },
5
+ { name: 'usage', summary: 'Show usage & cost', subs: [], endpoints: ['usage'] },
6
+ {
7
+ name: 'apps', aliases: ['app'], product: 'apps', summary: 'Deploy and manage apps',
8
+ subs: ['ls', 'deploy', 'logs', 'rm', 'scale', 'autoscale', 'env', 'domains', 'volumes', 'cdn', 'github', 'rollback', 'deployments'],
9
+ endpoints: ['apps', 'apps/[id]', 'apps/[id]/deployments', 'apps/[id]/logs', 'apps/[id]/scale', 'apps/[id]/autoscale', 'apps/[id]/env', 'apps/[id]/domains', 'apps/[id]/volumes', 'apps/[id]/volumes/[volId]', 'apps/[id]/cdn', 'apps/[id]/github', 'apps/[id]/rollback'],
10
+ },
11
+ { name: 'db', aliases: ['databases', 'database'], product: 'databases', summary: 'Managed Postgres (HA)', subs: ['ls', 'create', 'rm', 'url', 'metrics', 'backups', 'restore'], endpoints: ['databases', 'databases/[id]', 'databases/[id]/connection', 'databases/[id]/backups', 'databases/[id]/restore', 'databases/[id]/metrics'] },
12
+ { name: 'redis', aliases: ['cache'], product: 'cache', summary: 'Managed Redis (HA)', subs: ['ls', 'create', 'rm', 'url', 'metrics', 'backups', 'restore'], endpoints: ['redis', 'redis/[id]', 'redis/[id]/connection', 'redis/[id]/backups', 'redis/[id]/restore', 'redis/[id]/metrics'] },
13
+ { name: 'storage', aliases: ['buckets'], product: 'storage', summary: 'Object storage (S3)', subs: ['ls', 'create', 'rm', 'keys', 'key'], endpoints: ['buckets', 'buckets/[id]', 'storage/keys', 'storage/keys/[id]'] },
14
+ { name: 'jobs', aliases: ['cron'], product: 'jobs', summary: 'Cron / scheduled jobs', subs: ['ls', 'create', 'update', 'rm', 'trigger', 'runs'], endpoints: ['jobs', 'jobs/[id]', 'jobs/[id]/runs', 'jobs/[id]/trigger'] },
15
+ { name: 'events', aliases: ['activity'], product: 'observability', summary: 'Events and metrics', subs: ['ls', 'metrics'], endpoints: ['events', 'metrics'] },
16
+ { name: 'alarms', product: 'observability', summary: 'Metric alarms', subs: ['ls', 'create', 'rm'], endpoints: ['alarms', 'alarms/[id]'] },
17
+ { name: 'email', product: 'email', summary: 'Transactional email', subs: ['send', 'messages', 'config'], endpoints: ['email/send', 'email/messages', 'email/config'] },
18
+ ];
19
+ export function resolveCommand(input) {
20
+ for (const c of CLI_COMMANDS)
21
+ if (c.name === input || c.aliases?.includes(input))
22
+ return c.name;
23
+ return undefined;
24
+ }
package/dist/output.js ADDED
@@ -0,0 +1,26 @@
1
+ // Salida: modo humano (tabla alineada) y modo --json (máquina/agentes/CI). formatTable es puro (testeable).
2
+ const c = (n, s) => (process.stdout.isTTY ? `\x1b[${n}m${s}\x1b[0m` : s);
3
+ export const dim = (s) => c(2, s);
4
+ export const green = (s) => c(32, s);
5
+ export const red = (s) => c(31, s);
6
+ export const bold = (s) => c(1, s);
7
+ /** Tabla alineada de filas (objetos con las mismas claves). PURA. */
8
+ export function formatTable(rows, columns) {
9
+ if (rows.length === 0)
10
+ return '(none)';
11
+ const cols = columns || Object.keys(rows[0]);
12
+ const widths = cols.map((col) => Math.max(col.length, ...rows.map((r) => String(r[col] ?? '').length)));
13
+ const line = (cells) => cells.map((cell, i) => cell.padEnd(widths[i])).join(' ').trimEnd();
14
+ return [line(cols.map((x) => x.toUpperCase())), ...rows.map((r) => line(cols.map((col) => String(r[col] ?? ''))))].join('\n');
15
+ }
16
+ export function output(data, json, table) {
17
+ if (json) {
18
+ console.log(JSON.stringify(data, null, 2));
19
+ return;
20
+ }
21
+ if (table) {
22
+ console.log(formatTable(table.rows, table.columns));
23
+ return;
24
+ }
25
+ console.log(typeof data === 'string' ? data : JSON.stringify(data, null, 2));
26
+ }
@@ -0,0 +1,16 @@
1
+ import * as auth from './commands/auth.js';
2
+ import { apps } from './commands/apps.js';
3
+ import { db } from './commands/db.js';
4
+ import { redis } from './commands/redis.js';
5
+ import { storage } from './commands/storage.js';
6
+ import { jobs } from './commands/jobs.js';
7
+ import { events } from './commands/events.js';
8
+ import { email } from './commands/email.js';
9
+ import { alarms } from './commands/alarms.js';
10
+ import { usage } from './commands/usage.js';
11
+ export const HANDLERS = {
12
+ login: (a) => auth.login(a.flags),
13
+ logout: () => auth.logout(),
14
+ whoami: (a) => auth.whoami(!!a.flags.json),
15
+ usage, apps, db, redis, storage, jobs, events, alarms, email,
16
+ };
package/package.json ADDED
@@ -0,0 +1,36 @@
1
+ {
2
+ "name": "koigrid",
3
+ "version": "0.1.0",
4
+ "description": "koigrid CLI \u2014 deploy apps, databases, redis, storage and more from your terminal (or your AI agent).",
5
+ "bin": {
6
+ "koigrid": "dist/index.js"
7
+ },
8
+ "type": "module",
9
+ "files": [
10
+ "dist"
11
+ ],
12
+ "engines": {
13
+ "node": ">=18"
14
+ },
15
+ "scripts": {
16
+ "build": "tsc -p tsconfig.json",
17
+ "dev": "tsx src/index.ts",
18
+ "prepublishOnly": "npm run build"
19
+ },
20
+ "keywords": [
21
+ "koigrid",
22
+ "cloud",
23
+ "paas",
24
+ "deploy",
25
+ "cli"
26
+ ],
27
+ "license": "MIT",
28
+ "repository": {
29
+ "type": "git",
30
+ "url": "https://github.com/rikseotools/koigrid",
31
+ "directory": "cli"
32
+ },
33
+ "homepage": "https://koigrid.com",
34
+ "bugs": "https://koigrid.com",
35
+ "author": "koigrid"
36
+ }