zyntry 0.0.0-stage → 0.3.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.
Files changed (3) hide show
  1. package/README.md +51 -2
  2. package/index.mjs +870 -0
  3. package/package.json +31 -4
package/README.md CHANGED
@@ -1,3 +1,52 @@
1
- # Temporary Holding Version
1
+ # Zyntry CLI
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Run AI inference, manage runtimes, enforce security, and meter end users — from the terminal. One binary, zero dependencies, and a built-in MCP server for AI coding tools.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm i -g zyntry
9
+ ```
10
+
11
+ ## Get running in under a minute
12
+
13
+ ```bash
14
+ zyntry login # approve the device in your browser — done
15
+ zyntry init # create or link a project in this folder
16
+ zyntry run "hello" -m gpt-4o-mini
17
+ ```
18
+
19
+ The last command prints the model's reply plus the request id, provider, token counts, and exact cost — the platform meters everything for real.
20
+
21
+ ## Commands
22
+
23
+ | Command | What it does |
24
+ | --- | --- |
25
+ | `zyntry run "prompt"` | Inference on your project runtime. `-m <model>`, `-p <project>`, `-r <runtime>`, `--user <id>` (end-user metering), `--approve <call_id>` (approve tool calls), `--json` |
26
+ | `zyntry projects [create <name>]` | List your projects, or create a Free one |
27
+ | `zyntry runtimes` | List the project's runtimes |
28
+ | `zyntry regions` | Deployment regions available to your plan |
29
+ | `zyntry redeploy [id]` | Queue a runtime redeployment |
30
+ | `zyntry security [create\|list]` | Enforced security groups — rate limits, IP/country rules, budgets |
31
+ | `zyntry plans` / `users` / `quota` | End-user metering: rate plans, end users, quota checks |
32
+ | `zyntry updates` | Recent product updates |
33
+ | `zyntry mcp` | Start the MCP server (stdio) |
34
+ | `zyntry whoami` / `logout` | Session management |
35
+
36
+ ## MCP for AI coding tools
37
+
38
+ `zyntry mcp` starts a stdio MCP server that hands your AI agent the same power:
39
+
40
+ ```json
41
+ { "mcpServers": { "zyntry": { "command": "zyntry", "args": ["mcp"] } } }
42
+ ```
43
+
44
+ Tools exposed: `invoke`, `list_projects`, `list_runtimes`, `list_security_groups`, `quota`, `recent_logs`.
45
+
46
+ ## Notes
47
+
48
+ - Authentication uses a device flow: `zyntry login` prints a URL, you approve it in the console, and the token lives in `~/.zyntry/credentials.json`.
49
+ - Project context comes from the `zyntry.yaml` written by `zyntry init`; most commands accept an explicit id if you're outside a project folder.
50
+ - Every command talks to the same enforced API as the console — what the CLI does is what the platform really does.
51
+
52
+ Environment: `ZYNTRY_API_BASE_URL` overrides the API base (default `https://api.zyntry.space`).
package/index.mjs ADDED
@@ -0,0 +1,870 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Zyntry CLI — login and project initialization.
4
+ *
5
+ * The CLI stays minimal: the backend owns authentication (device flow),
6
+ * account state, plan eligibility, project creation, and billing. The
7
+ * developer consents to any paid plan before a subscription is created.
8
+ */
9
+
10
+ import { readFileSync, writeFileSync, existsSync, appendFileSync, unlinkSync, mkdirSync } from "node:fs";
11
+ import { join } from "node:path";
12
+ import { homedir } from "node:os";
13
+ import readline from "node:readline";
14
+ import { spawn } from "node:child_process";
15
+
16
+ const API_BASE = process.env.ZYNTRY_API_BASE_URL || "https://api.zyntry.space";
17
+ const CREDENTIALS_DIR = join(homedir(), ".zyntry");
18
+ const CREDENTIALS_FILE = join(CREDENTIALS_DIR, "credentials.json");
19
+
20
+ const COLORS = {
21
+ dim: (s) => `\x1b[2m${s}\x1b[0m`,
22
+ cyan: (s) => `\x1b[36m${s}\x1b[0m`,
23
+ green: (s) => `\x1b[32m${s}\x1b[0m`,
24
+ yellow: (s) => `\x1b[33m${s}\x1b[0m`,
25
+ red: (s) => `\x1b[31m${s}\x1b[0m`,
26
+ bold: (s) => `\x1b[1m${s}\x1b[0m`,
27
+ };
28
+
29
+ function log(message) { process.stdout.write(`${message}\n`); }
30
+ function dim(message) { log(COLORS.dim(message)); }
31
+ function ok(message) { log(`${COLORS.green("✔")} ${message}`); }
32
+ function warn(message) { log(`${COLORS.yellow("!")} ${message}`); }
33
+ function fail(message) { log(`${COLORS.red("✘")} ${message}`); }
34
+
35
+ async function prompt(question) {
36
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
37
+ return new Promise((resolve) => rl.question(question, (answer) => { rl.close(); resolve(answer.trim()); }));
38
+ }
39
+
40
+ async function confirm(question) {
41
+ const answer = await prompt(`${question} ${COLORS.dim("[y/N]")} `);
42
+ return ["y", "yes"].includes(answer.toLowerCase());
43
+ }
44
+
45
+ function openBrowser(url) {
46
+ const platform = process.platform;
47
+ const command = platform === "win32" ? "start" : platform === "darwin" ? "open" : "xdg-open";
48
+ try { spawn(command, [url], { detached: true, stdio: "ignore", shell: platform === "win32" }).unref(); } catch { /* non-fatal */ }
49
+ }
50
+
51
+ async function api(path, init = {}, token = null) {
52
+ const headers = { "Content-Type": "application/json", Accept: "application/json", ...(init.headers || {}) };
53
+ if (token) headers.Authorization = `Bearer ${token}`;
54
+ const response = await fetch(`${API_BASE}${path}`, { ...init, headers });
55
+ const data = await response.json().catch(() => ({}));
56
+ return { status: response.status, ok: response.ok, data };
57
+ }
58
+
59
+ function loadToken() {
60
+ if (!existsSync(CREDENTIALS_FILE)) return null;
61
+ try { return JSON.parse(readFileSync(CREDENTIALS_FILE, "utf8")).access_token || null; }
62
+ catch { return null; }
63
+ }
64
+
65
+ function saveToken(token, account) {
66
+ mkdirSync(CREDENTIALS_DIR, { recursive: true });
67
+ writeFileSync(CREDENTIALS_FILE, JSON.stringify({ access_token: token, account_email: account?.email, saved_at: new Date().toISOString() }, null, 2));
68
+ }
69
+
70
+ function requireToken() {
71
+ const token = loadToken();
72
+ if (!token) {
73
+ fail("Not logged in. Run " + COLORS.bold("zyntry login") + " first.");
74
+ process.exit(1);
75
+ }
76
+ return token;
77
+ }
78
+
79
+ /* -------------------------------- login -------------------------------- */
80
+
81
+ async function commandLogin() {
82
+ log(COLORS.bold("Zyntry login"));
83
+ dim("Opens your browser to approve this device.\n");
84
+
85
+ const start = await api("/api/v1/cli/device/start", { method: "POST" });
86
+ if (!start.ok) { fail(`Could not start login: ${start.data?.message || start.status}`); process.exit(1); }
87
+
88
+ const { device_code, user_code, verification_url, expires_in, interval } = start.data;
89
+ log(` 1. Open ${COLORS.cyan(verification_url)}`);
90
+ log(` 2. Confirm the code: ${COLORS.bold(user_code)}`);
91
+ dim(` (expires in ${Math.round(expires_in / 60)} minutes)\n`);
92
+ openBrowser(verification_url);
93
+
94
+ const deadline = Date.now() + expires_in * 1000;
95
+ process.stdout.write(COLORS.dim("Waiting for approval"));
96
+ const timer = setInterval(() => process.stdout.write("."), 1500);
97
+
98
+ try {
99
+ while (Date.now() < deadline) {
100
+ await new Promise((resolve) => setTimeout(resolve, interval * 1000));
101
+ const poll = await api("/api/v1/cli/device/token", { method: "POST", body: JSON.stringify({ device_code }) });
102
+ if (poll.ok && poll.data.access_token) {
103
+ clearInterval(timer);
104
+ process.stdout.write("\n\n");
105
+ saveToken(poll.data.access_token, poll.data.account);
106
+ ok(`Logged in as ${COLORS.bold(poll.data.account?.email || "your account")}`);
107
+ dim(`Token saved to ${CREDENTIALS_FILE}`);
108
+ return;
109
+ }
110
+ const error = poll.data?.error || "";
111
+ if (error === "authorization_denied" || error === "authorization_expired") {
112
+ clearInterval(timer);
113
+ process.stdout.write("\n\n");
114
+ fail(error === "authorization_denied" ? "Login was denied." : "The login code expired. Try again.");
115
+ process.exit(1);
116
+ }
117
+ }
118
+ clearInterval(timer);
119
+ process.stdout.write("\n\n");
120
+ fail("Login timed out. Try again.");
121
+ process.exit(1);
122
+ } finally { clearInterval(timer); }
123
+ }
124
+
125
+ /* ------------------------------ whoami ------------------------------ */
126
+
127
+ async function commandWhoami() {
128
+ const token = requireToken();
129
+ const account = await api("/api/v1/cli/account", {}, token);
130
+ if (!account.ok) { fail(account.status === 401 ? "Token revoked or expired. Run zyntry login." : `Account check failed (${account.status}).`); process.exit(1); }
131
+ log(`${COLORS.bold(account.data.account.email)} — ${account.data.projects.length} project${account.data.projects.length === 1 ? "" : "s"}`);
132
+ account.data.projects.forEach((project) => dim(` ${project.name} (${project.plan_code}) — ${project.id}`));
133
+ }
134
+
135
+ /* -------------------------------- init -------------------------------- */
136
+
137
+ function yamlFor(project, credentials) {
138
+ return [
139
+ `# Zyntry project configuration.`,
140
+ `# The Zyntry API receives and applies this file when provisioning or`,
141
+ `# updating infrastructure. It is not executed locally.`,
142
+ ``,
143
+ `project:`,
144
+ ` id: "${project.id}"`,
145
+ ` name: "${project.name}"`,
146
+ ` slug: "${project.slug || ""}"`,
147
+ ` environment: "${project.environment}"`,
148
+ ``,
149
+ `api:`,
150
+ ` base_url: "${credentials.api_base_url}"`,
151
+ ``,
152
+ ].join("\n");
153
+ }
154
+
155
+ function envFor(credentials) {
156
+ return [
157
+ `# Zyntry CLI credentials (added by 'zyntry init')`,
158
+ `ZYNTRY_API_KEY=${credentials.api_key}`,
159
+ `ZYNTRY_API_BASE_URL=${credentials.api_base_url}`,
160
+ ``,
161
+ ].join("\n");
162
+ }
163
+
164
+ function upsertEnv(directory, credentials) {
165
+ const envPath = join(directory, ".env");
166
+ const block = envFor(credentials);
167
+ if (!existsSync(envPath)) { writeFileSync(envPath, block); return; }
168
+ const existing = readFileSync(envPath, "utf8");
169
+ // Replace existing Zyntry variables; leave everything else untouched.
170
+ const cleaned = existing.split("\n").filter((line) => !line.startsWith("ZYNTRY_API_KEY=") && !line.startsWith("ZYNTRY_API_BASE_URL=") && !line.startsWith("# Zyntry CLI credentials"));
171
+ writeFileSync(envPath, `${cleaned.join("\n").replace(/\n+$/, "")}\n\n${block}`);
172
+ }
173
+
174
+ function ensureGitignore(directory) {
175
+ const gitignorePath = join(directory, ".gitignore");
176
+ if (!existsSync(gitignorePath)) { writeFileSync(gitignorePath, ".env\n"); return; }
177
+ const existing = readFileSync(gitignorePath, "utf8");
178
+ if (!existing.split("\n").some((line) => line.trim() === ".env")) appendFileSync(gitignorePath, "\n.env\n");
179
+ }
180
+
181
+ function writeProjectFiles(directory, project, credentials) {
182
+ writeFileSync(join(directory, "zyntry.yaml"), yamlFor(project, credentials));
183
+ upsertEnv(directory, credentials);
184
+ ensureGitignore(directory);
185
+ ok(`Created ${COLORS.bold("zyntry.yaml")} and saved credentials to ${COLORS.bold(".env")}`);
186
+ dim(".env was added to .gitignore");
187
+ }
188
+
189
+ async function commandInit(directory) {
190
+ const token = requireToken();
191
+ const dir = directory || process.cwd();
192
+ const yamlPath = join(dir, "zyntry.yaml");
193
+ const hasExistingYaml = existsSync(yamlPath);
194
+
195
+ const account = await api("/api/v1/cli/account", {}, token);
196
+ if (!account.ok) { fail(account.status === 401 ? "Token revoked or expired. Run zyntry login." : `Account check failed (${account.status}).`); process.exit(1); }
197
+
198
+ log(COLORS.bold(`Zyntry init — ${account.data.account.email}`));
199
+
200
+ // Link an existing project instead of creating a duplicate.
201
+ if (hasExistingYaml) {
202
+ const existing = readFileSync(yamlPath, "utf8");
203
+ const projectId = existing.match(/id:\s*"([^"]+)"/)?.[1];
204
+ warn(`This folder already has a zyntry.yaml${projectId ? ` (project ${projectId})` : ""}.`);
205
+ if (projectId && account.data.projects.some((p) => p.id === projectId)) {
206
+ const link = await confirm("Re-issue credentials for the existing project?");
207
+ if (link) {
208
+ const init = await api("/api/v1/cli/init", { method: "POST", body: JSON.stringify({ action: "link", project_id: projectId }) }, token);
209
+ if (init.ok) { writeProjectFiles(dir, init.data.project, init.data.credentials); ok(`Linked to ${COLORS.bold(init.data.project.name)}`); return; }
210
+ fail(init.data?.message || "Link failed."); process.exit(1);
211
+ }
212
+ dim("No changes made.");
213
+ return;
214
+ }
215
+ }
216
+
217
+ const name = await prompt(`Project name: `) || `cli-${Date.now()}`;
218
+
219
+ if (account.data.free_project_available) {
220
+ // Scenario A: eligible for Free — no choice needed.
221
+ dim("Your account is eligible for a Free project ($0/month).");
222
+ const go = await confirm("Create it now?");
223
+ if (!go) { dim("Nothing was created."); return; }
224
+ const init = await api("/api/v1/cli/init", { method: "POST", body: JSON.stringify({ name, plan_code: "free" }) }, token);
225
+ if (!init.ok) { fail(init.data?.message || `Init failed (${init.status}).`); process.exit(1); }
226
+ writeProjectFiles(dir, init.data.project, init.data.credentials);
227
+ ok(`Created Free project ${COLORS.bold(init.data.project.name)}`);
228
+ return;
229
+ }
230
+
231
+ // Scenario B: Free allowance used — the developer must explicitly consent.
232
+ const plans = (account.data.plans || []).filter((plan) => plan.code !== "free" && plan.price_cents !== null);
233
+ if (!plans.length) { fail("No paid plans are available for your account."); process.exit(1); }
234
+ const recommended = plans.find((plan) => plan.code === account.data.recommended_plan) || plans[0];
235
+ log(`\nYour Free project allowance has been used.`);
236
+ for (const plan of plans) {
237
+ const marker = plan.code === recommended.code ? COLORS.green(` ← recommended`) : "";
238
+ log(` ${COLORS.bold(plan.name)} — $${(plan.price_cents / 100).toFixed(2)}/project/${plan.billing_interval || "month"}${marker}`);
239
+ }
240
+ log(`\nPer-project pricing: each new project needs its own subscription.`);
241
+ const consent = await confirm(`Authorize $${(recommended.price_cents / 100).toFixed(2)}/month for a new ${recommended.name} project?`);
242
+ if (!consent) { dim("\nNothing was charged and no project was created."); return; }
243
+
244
+ const planChoice = plans.length > 1
245
+ ? (await prompt(`Which plan? [${recommended.code}] `) || recommended.code).toLowerCase()
246
+ : recommended.code;
247
+
248
+ const init = await api("/api/v1/cli/init", { method: "POST", body: JSON.stringify({ name, plan_code: planChoice, confirm_paid: true }) }, token);
249
+ if (!init.ok) { fail(init.data?.message || `Init failed (${init.status}).`); process.exit(1); }
250
+
251
+ writeProjectFiles(dir, init.data.project, init.data.credentials);
252
+ ok(`Created project ${COLORS.bold(init.data.project.name)} (activates on payment)`);
253
+
254
+ if (init.data.checkout_url) {
255
+ log(`\n Complete payment: ${COLORS.cyan(init.data.checkout_url)}`);
256
+ openBrowser(init.data.checkout_url);
257
+ dim(" The plan activates once checkout and the billing webhook complete.");
258
+ } else if (init.data.checkout_error) {
259
+ warn(`Checkout is unavailable: ${init.data.checkout_error}`);
260
+ dim("Complete the upgrade later from Settings → Billing in the console.");
261
+ }
262
+ }
263
+
264
+ /* ------------------------------- logout ------------------------------- */
265
+
266
+ async function commandLogout() {
267
+ const token = loadToken();
268
+ if (token) { await api("/api/v1/cli/revoke", { method: "POST" }, token).catch(() => {}); }
269
+ if (existsSync(CREDENTIALS_FILE)) { unlinkSync(CREDENTIALS_FILE); }
270
+ ok("Signed out.");
271
+ }
272
+
273
+ /* -------------------------------- main -------------------------------- */
274
+
275
+ const HELP = `Zyntry CLI
276
+
277
+ Usage:
278
+ zyntry login Authenticate your Zyntry account
279
+ zyntry init [directory] Create or link a project (default: current directory)
280
+ zyntry whoami Show the signed-in account and its projects
281
+ zyntry logout Revoke this device's token and sign out
282
+
283
+ zyntry run "prompt" Run inference on your project runtime
284
+ -m <model> -p <project> -r <runtime> --user <id>
285
+ --approve <call_id> --json
286
+ zyntry projects [create <name>]
287
+ List your projects, or create one
288
+ zyntry runtimes List the project's runtimes
289
+ zyntry regions List deployment regions for the project plan
290
+ zyntry redeploy [id] Queue a redeployment for a runtime
291
+ zyntry security [create|list] Manage enforced security groups
292
+ zyntry plans [create|list] Manage end-user rate plans
293
+ zyntry users [list|add] Manage end users and their usage
294
+ zyntry quota <user_id> Check an end-user's quota
295
+ zyntry updates Show recent product updates
296
+ zyntry mcp Start the Zyntry MCP server (stdio) for
297
+ Claude Code, Cursor, Windsurf, and any MCP client
298
+ zyntry help Show this help
299
+
300
+ Environment:
301
+ ZYNTRY_API_BASE_URL Override the API base URL (default: https://api.zyntry.space)`;
302
+
303
+ /* ------------------------------ end-user metering ------------------------- */
304
+
305
+ async function getProjectIdFromYaml() {
306
+ const yamlPath = join(process.cwd(), "zyntry.yaml");
307
+ if (!existsSync(yamlPath)) { fail("No zyntry.yaml in this directory. Run zyntry init first."); process.exit(1); }
308
+ const yaml = readFileSync(yamlPath, "utf8");
309
+ const projectId = yaml.match(/id:\s*"([^"]+)"/)?.[1];
310
+ if (!projectId) { fail("Could not read project ID from zyntry.yaml."); process.exit(1); }
311
+ return projectId;
312
+ }
313
+
314
+ async function commandPlans(sub) {
315
+ const token = requireToken();
316
+ const projectId = await getProjectIdFromYaml();
317
+ if (sub === "list" || !sub) {
318
+ const result = await api("/api/v1/projects/" + projectId + "/rate-plans", {}, token);
319
+ if (!result.ok) { fail("Unable to list plans: " + (result.data?.message || result.status)); process.exit(1); }
320
+ const plans = result.data.plans || [];
321
+ if (!plans.length) { log("No rate plans yet. Create one with: zyntry plans create"); return; }
322
+ for (const plan of plans) {
323
+ const parts = [];
324
+ if (plan.daily_token_limit) parts.push(plan.daily_token_limit + " tok/day");
325
+ if (plan.daily_request_limit) parts.push(plan.daily_request_limit + " req/day");
326
+ if (plan.requests_per_minute) parts.push(plan.requests_per_minute + "/min");
327
+ if (plan.markup_percentage) parts.push(plan.markup_percentage + "% markup");
328
+ log(" " + COLORS.bold(plan.name) + (plan.is_default ? COLORS.green(" (default)") : "") + " — " + (parts.join(" · ") || "no limits"));
329
+ }
330
+ } else if (sub === "create") {
331
+ const name = await prompt("Plan name: ");
332
+ if (!name) { fail("Name is required."); return; }
333
+ const dailyTokens = (await prompt("Daily token limit (0 = none): ")) || "0";
334
+ const dailyRequests = (await prompt("Daily request limit (0 = none): ")) || "0";
335
+ const rpm = (await prompt("Requests per minute (0 = none): ")) || "0";
336
+ const markup = (await prompt("Markup percentage (0 = none): ")) || "0";
337
+ const body = { name, slug: name.toLowerCase().replace(/\s+/g, "-"), daily_token_limit: Number(dailyTokens) || undefined, daily_request_limit: Number(dailyRequests) || undefined, requests_per_minute: Number(rpm) || undefined, markup_percentage: Number(markup) || undefined };
338
+ const result = await api("/api/v1/projects/" + projectId + "/rate-plans", { method: "POST", body: JSON.stringify(body) }, token);
339
+ if (result.ok) { ok("Rate plan \"" + name + "\" created."); } else { fail("Create failed: " + (result.data?.message || result.status)); }
340
+ }
341
+ }
342
+
343
+ async function commandUsers(sub) {
344
+ const token = requireToken();
345
+ const projectId = await getProjectIdFromYaml();
346
+ if (sub === "list" || !sub) {
347
+ const result = await api("/api/v1/projects/" + projectId + "/end-users?limit=50", {}, token);
348
+ if (!result.ok) { fail("Unable to list users: " + (result.data?.message || result.status)); process.exit(1); }
349
+ const users = result.data.end_users || [];
350
+ if (!users.length) { log("No end users yet. They are created automatically on first request."); return; }
351
+ for (const user of users) {
352
+ const blocked = user.is_blocked ? COLORS.red(" [blocked]") : "";
353
+ log(" " + COLORS.bold(user.external_id) + (user.display_name ? " (" + user.display_name + ")" : "") + blocked);
354
+ }
355
+ } else if (sub === "add") {
356
+ const externalId = await prompt("External user ID: ");
357
+ if (!externalId) { fail("External ID is required."); return; }
358
+ const displayName = await prompt("Display name (optional): ");
359
+ const body = { external_id: external_id, ...(displayName ? { display_name: displayName } : {}) };
360
+ const result = await api("/api/v1/projects/" + projectId + "/end-users", { method: "POST", body: JSON.stringify(body) }, token);
361
+ if (result.ok) { ok("End user \"" + externalId + "\" registered."); } else { fail("Add failed: " + (result.data?.message || result.status)); }
362
+ }
363
+ }
364
+
365
+ async function commandQuota(userId) {
366
+ if (!userId) { fail("Usage: zyntry quota <user_id>"); process.exit(1); }
367
+ const token = requireToken();
368
+ const projectId = await getProjectIdFromYaml();
369
+ const result = await api("/api/v1/billing/check-quota?project_id=" + projectId + "&end_user_id=" + userId, {}, token);
370
+ if (!result.ok) { fail("Quota check failed: " + (result.data?.message || result.status)); process.exit(1); }
371
+ const q = result.data;
372
+ const status = q.allowed ? COLORS.green("allowed") : COLORS.red("blocked (" + q.reason + ")");
373
+ log(" User: " + COLORS.bold(userId));
374
+ log(" Status: " + status);
375
+ if (q.rate_plan) log(" Plan: " + q.rate_plan.name);
376
+ if (q.usage) {
377
+ log(" Today: " + q.usage.daily.tokens + " tokens · " + q.usage.daily.requests + " requests · $" + q.usage.daily.cost);
378
+ log(" Month: " + q.usage.monthly.tokens + " tokens · " + q.usage.monthly.requests + " requests · $" + q.usage.monthly.cost);
379
+ }
380
+ }
381
+
382
+ async function commandRegions() {
383
+ const token = requireToken();
384
+ const projectId = await getProjectIdFromYaml().catch(() => null);
385
+ const result = await api(projectId ? "/api/v1/regions?project_id=" + projectId : "/api/v1/regions", {}, token);
386
+ if (!result.ok) { fail("Unable to list regions: " + (result.data?.message || result.status)); process.exit(1); }
387
+ const regions = result.data.regions || [];
388
+ if (!regions.length) { fail("No regions returned."); return; }
389
+ for (const region of regions) {
390
+ const tag = region.id === "automatic" ? COLORS.green("available")
391
+ : region.status === "limited_capacity" ? COLORS.yellow("limited capacity")
392
+ : region.available ? COLORS.green("available")
393
+ : COLORS.yellow("plan required" + (region.required_plan ? " (" + region.required_plan + ")" : ""));
394
+ log(" " + COLORS.bold(region.name).padEnd(22) + " " + (region.placement_group ? region.placement_group + " " : "") + tag);
395
+ if (region.description) dim(" " + region.description);
396
+ }
397
+ }
398
+
399
+ async function commandRuntimes() {
400
+ const token = requireToken();
401
+ const projectId = await getProjectIdFromYaml();
402
+ const result = await api("/api/v1/runtimes?project_id=" + projectId + "&limit=50", {}, token);
403
+ if (!result.ok) { fail("Unable to list runtimes: " + (result.data?.message || result.status)); process.exit(1); }
404
+ const runtimes = result.data.runtimes || result.data.items || [];
405
+ if (!runtimes.length) { log("No runtimes in this project yet. Create one from the console."); return; }
406
+ for (const runtime of runtimes) {
407
+ const status = String(runtime.health ?? runtime.status ?? "unknown");
408
+ const tone = ["healthy", "active", "running"].includes(status.toLowerCase()) ? COLORS.green : COLORS.yellow;
409
+ log(" " + COLORS.bold(runtime.name) + " " + (runtime.environment ?? "—") + " " + (runtime.region ?? "automatic") + " " + tone(status));
410
+ dim(" " + runtime.id);
411
+ }
412
+ }
413
+
414
+ async function commandRedeploy(runtimeIdArg) {
415
+ const token = requireToken();
416
+ const projectId = await getProjectIdFromYaml();
417
+ let runtimeId = runtimeIdArg;
418
+ if (!runtimeId) {
419
+ const result = await api("/api/v1/runtimes?project_id=" + projectId + "&limit=50", {}, token);
420
+ const runtimes = result.ok ? (result.data.runtimes || result.data.items || []) : [];
421
+ if (!runtimes.length) { fail("No runtimes in this project. Create one from the console first."); return; }
422
+ if (runtimes.length === 1) {
423
+ runtimeId = runtimes[0].id;
424
+ } else {
425
+ log("Which runtime?");
426
+ runtimes.forEach((runtime, index) => log(" " + (index + 1) + ". " + runtime.name + " (" + (runtime.environment ?? "—") + ")"));
427
+ const answer = await prompt("Number: ");
428
+ const picked = runtimes[Number(answer) - 1];
429
+ if (!picked) { fail("Invalid selection."); return; }
430
+ runtimeId = picked.id;
431
+ }
432
+ }
433
+ const result = await api("/api/v1/runtimes/" + runtimeId + "/deployments", { method: "POST" }, token);
434
+ if (result.ok) {
435
+ ok("Redeployment queued — the new version replaces the active deployment when healthy.");
436
+ } else {
437
+ fail("Redeploy failed: " + (result.data?.error || result.data?.message || result.status));
438
+ if (result.status === 402) dim("Custom deployments follow the project plan.");
439
+ }
440
+ }
441
+
442
+ function describeRule(rule) {
443
+ if (rule.type === "rate_limit") return "Rate limit · " + rule.requests_per_minute + "/min per API key";
444
+ if (rule.type === "ip_allowlist") return "IP allowlist · " + (rule.cidrs || []).length + " range" + ((rule.cidrs || []).length === 1 ? "" : "s");
445
+ if (rule.type === "ip_denylist") return "IP denylist · " + (rule.cidrs || []).length + " range" + ((rule.cidrs || []).length === 1 ? "" : "s");
446
+ return String(rule.type || "unknown");
447
+ }
448
+
449
+ async function commandSecurity(sub) {
450
+ const token = requireToken();
451
+ const projectId = await getProjectIdFromYaml();
452
+ if (sub === "create") {
453
+ const name = await prompt("Group name: ");
454
+ if (!name) { fail("Name is required."); return; }
455
+ const rules = [];
456
+ if (await confirm("Add a per-key rate limit?")) {
457
+ const rpm = Number(await prompt("Requests per minute: ") || "0");
458
+ if (rpm > 0) rules.push({ type: "rate_limit", requests_per_minute: Math.floor(rpm) });
459
+ }
460
+ const ruleQuestions = [["ip_allowlist", "Add an IP allowlist?"], ["ip_denylist", "Add an IP denylist?"]];
461
+ for (const [type, question] of ruleQuestions) {
462
+ if (await confirm(question)) {
463
+ const cidrs = (await prompt("CIDR ranges (comma-separated, e.g. 203.0.113.0/24): ") || "")
464
+ .split(/[\s,;]+/).map((value) => value.trim()).filter(Boolean);
465
+ if (cidrs.length) rules.push({ type, cidrs });
466
+ }
467
+ }
468
+ if (!rules.length) { fail("A group with no rules enforces nothing. Add at least one rule."); return; }
469
+ const body = { name: name.trim(), rules, enabled: true };
470
+ const result = await api("/api/v1/projects/" + projectId + "/security-groups", { method: "POST", body: JSON.stringify(body) }, token);
471
+ if (result.ok) {
472
+ ok("Security group \"" + name + "\" created:");
473
+ rules.forEach((rule) => log(" " + describeRule(rule)));
474
+ dim("Rules are enforced on invoke requests once runtimes are assigned (console: Security Groups).");
475
+ } else {
476
+ fail("Create failed: " + (result.data?.message || result.status));
477
+ if (result.status === 402) dim("Custom security groups require the Studio plan.");
478
+ }
479
+ return;
480
+ }
481
+ const result = await api("/api/v1/projects/" + projectId + "/security-groups", {}, token);
482
+ if (!result.ok) { fail("Unable to list security groups: " + (result.data?.message || result.status)); process.exit(1); }
483
+ const groups = result.data.items || [];
484
+ if (!groups.length) { log("No custom security groups. Create one with: zyntry security create"); return; }
485
+ for (const group of groups) {
486
+ const state = group.enabled ? COLORS.green("enforcing") : COLORS.yellow("disabled");
487
+ const attached = (group.runtime_ids || []).length;
488
+ const scope = attached ? attached + " runtime" + (attached === 1 ? "" : "s") : "not attached";
489
+ log(" " + COLORS.bold(group.name) + " " + state + " " + scope);
490
+ (group.rules || []).forEach((rule) => dim(" " + describeRule(rule)));
491
+ }
492
+ }
493
+
494
+ async function commandUpdates() {
495
+ const token = requireToken();
496
+ const result = await api("/api/v1/product-updates", {}, token);
497
+ if (!result.ok) { fail("Unable to list product updates: " + (result.data?.message || result.status)); process.exit(1); }
498
+ const updates = result.data.items || [];
499
+ if (!updates.length) { log("No product updates yet."); return; }
500
+ for (const update of updates) {
501
+ log(" " + COLORS.bold(update.title) + " " + COLORS.dim(String(update.published_at ?? "").slice(0, 10)));
502
+ dim(" " + String(update.body ?? "").split("\n")[0].slice(0, 100));
503
+ }
504
+ }
505
+
506
+ /* ------------------------------ projects --------------------------------- */
507
+
508
+ async function commandProjects(sub, nameArg) {
509
+ const token = requireToken();
510
+ if (sub === "create") {
511
+ const name = nameArg || await prompt("Project name: ");
512
+ if (!name) { fail("A project name is required."); return; }
513
+ const account = await api("/api/v1/cli/account", {}, token);
514
+ if (!account.ok) { fail("Account check failed (" + account.status + ")."); process.exit(1); }
515
+ if (!account.data.free_project_available) {
516
+ fail("Your Free project allowance is used. Run " + COLORS.bold("zyntry init") + " for the paid-plan consent flow.");
517
+ return;
518
+ }
519
+ const init = await api("/api/v1/cli/init", { method: "POST", body: JSON.stringify({ name, plan_code: "free" }) }, token);
520
+ if (!init.ok) { fail(init.data?.message || "Project creation failed (" + init.status + ")."); process.exit(1); }
521
+ ok("Created project " + COLORS.bold(init.data.project.name));
522
+ dim(" " + init.data.project.id + " — run " + COLORS.bold("zyntry init") + " in a folder to link this directory to it.");
523
+ return;
524
+ }
525
+ const result = await api("/api/v1/projects", {}, token);
526
+ if (!result.ok) { fail("Unable to list projects: " + (result.data?.message || result.status)); process.exit(1); }
527
+ const projects = result.data.projects || [];
528
+ if (!projects.length) { log("No projects yet. Run " + COLORS.bold("zyntry init") + " to create one."); return; }
529
+ for (const project of projects) {
530
+ log(" " + COLORS.bold(project.name) + " " + (project.plan_code ?? "free") + " " + (project.environment ?? "—"));
531
+ dim(" " + project.id);
532
+ }
533
+ }
534
+
535
+ /* --------------------------------- run ------------------------------------ */
536
+
537
+ function readProjectIdFromYamlOptional() {
538
+ const yamlPath = join(process.cwd(), "zyntry.yaml");
539
+ if (!existsSync(yamlPath)) return null;
540
+ return readFileSync(yamlPath, "utf8").match(/id:\s*"([^"]+)"/)?.[1] ?? null;
541
+ }
542
+
543
+ async function commandRun(rest) {
544
+ const token = requireToken();
545
+ let prompt = null, model = null, projectId = null, runtimeId = null, endUserId = null, approve = null, asJson = false;
546
+ for (let i = 0; i < rest.length; i++) {
547
+ const arg = rest[i];
548
+ if (arg === "-m" || arg === "--model") model = rest[++i];
549
+ else if (arg === "-p" || arg === "--project") projectId = rest[++i];
550
+ else if (arg === "-r" || arg === "--runtime") runtimeId = rest[++i];
551
+ else if (arg === "--user") endUserId = rest[++i];
552
+ else if (arg === "--approve") approve = rest[++i];
553
+ else if (arg === "--json") asJson = true;
554
+ else if (!prompt) prompt = arg;
555
+ }
556
+ if (!prompt) { fail("A prompt is required: " + COLORS.bold('zyntry run "hello" -m gpt-4o-mini')); return; }
557
+ projectId = projectId || readProjectIdFromYamlOptional();
558
+ if (!projectId) { fail("No project context. Run " + COLORS.bold("zyntry init") + " in this directory, or pass -p <project_id>."); return; }
559
+
560
+ const body = { project_id: projectId, messages: [{ role: "user", content: prompt }] };
561
+ if (model) body.model = model;
562
+ if (runtimeId) body.runtime_id = runtimeId;
563
+ if (endUserId) body.end_user_id = endUserId;
564
+ if (approve) body.approved_tool_calls = [approve];
565
+
566
+ if (!asJson) dim("Running on Zyntry…");
567
+ const result = await api("/api/v1/invoke", { method: "POST", body: JSON.stringify(body) }, token);
568
+ if (asJson) { log(JSON.stringify(result.data, null, 2)); return; }
569
+
570
+ if (result.status === 202 && result.data?.status === "approval_required") {
571
+ const call = result.data.tool_call || {};
572
+ warn("A tool requested your approval before running:");
573
+ log(" " + COLORS.bold(call.tool || "tool") + " " + String(call.arguments || "{}").slice(0, 120));
574
+ dim(" Approve by re-running with: --approve " + (call.id || "<call_id>"));
575
+ return;
576
+ }
577
+ if (!result.ok) {
578
+ fail("Invoke failed: " + (result.data?.message || result.data?.error || result.status));
579
+ if (result.status === 402) dim("The project's plan limits apply. Check quota in the console or upgrade the project.");
580
+ if (result.status === 429) dim(String(result.data?.reason || "Rate limited — retry shortly."));
581
+ process.exit(1);
582
+ }
583
+
584
+ const data = result.data;
585
+ const usage = data.usage || {};
586
+ log("");
587
+ log(String(data.output ?? ""));
588
+ log("");
589
+ dim(
590
+ " " + (data.provider ?? "—") + "/" + (data.model ?? "—")
591
+ + " · " + (usage.input_tokens ?? 0) + "→" + (usage.output_tokens ?? 0) + " tokens"
592
+ + " · $" + Number(usage.cost_usd ?? 0).toFixed(6)
593
+ + " · " + (data.latency_ms ?? "—") + "ms"
594
+ );
595
+ dim(" request " + (data.request_id ?? "—"));
596
+ if (Array.isArray(data.tool_calls) && data.tool_calls.length) {
597
+ for (const call of data.tool_calls) {
598
+ dim(" tool " + call.tool + " → HTTP " + call.http_status + (call.ok === false ? " (failed)" : ""));
599
+ }
600
+ }
601
+ }
602
+
603
+ /* --------------------------------- MCP ------------------------------------ */
604
+
605
+ const MCP_TOOLS = [
606
+ {
607
+ name: "invoke",
608
+ description: "Run an AI inference request on the developer's Zyntry project runtime. Returns the model output plus provider, model, token usage, and cost.",
609
+ inputSchema: {
610
+ type: "object",
611
+ properties: {
612
+ prompt: { type: "string", description: "The user prompt to send." },
613
+ model: { type: "string", description: "Optional model id (e.g. gpt-4o-mini). Defaults to the runtime's routed model." },
614
+ project_id: { type: "string", description: "Optional project id; defaults to the zyntry.yaml project in the working directory." },
615
+ runtime_id: { type: "string", description: "Optional runtime id; defaults to the project's routing." },
616
+ end_user_id: { type: "string", description: "Optional end-user id for metering and quota enforcement." },
617
+ },
618
+ required: ["prompt"],
619
+ },
620
+ },
621
+ { name: "list_projects", description: "List the developer's Zyntry projects with plan and environment.", inputSchema: { type: "object", properties: {} } },
622
+ { name: "create_project", description: "Create a new Zyntry project (Free tier; the paid-plan consent flow requires the interactive CLI).", inputSchema: { type: "object", properties: { name: { type: "string" } }, required: ["name"] } },
623
+ { name: "list_runtimes", description: "List the runtimes of a Zyntry project with environment, region, and health.", inputSchema: { type: "object", properties: { project_id: { type: "string" } } } },
624
+ { name: "list_regions", description: "List the deployment regions available to the project's plan.", inputSchema: { type: "object", properties: { project_id: { type: "string" } } } },
625
+ { name: "list_deployments", description: "List a runtime's deployments with region, status, version, and endpoint.", inputSchema: { type: "object", properties: { runtime_id: { type: "string" }, project_id: { type: "string" } } } },
626
+ { name: "redeploy_runtime", description: "Queue a redeployment for a runtime. The new version replaces the active deployment once healthy.", inputSchema: { type: "object", properties: { runtime_id: { type: "string" }, project_id: { type: "string" } } } },
627
+ { name: "recent_logs", description: "Recent request logs for a Zyntry project: status, model, provider, latency, errors.", inputSchema: { type: "object", properties: { project_id: { type: "string" }, limit: { type: "number" } } } },
628
+ { name: "list_traces", description: "Recent request traces with span counts and outcome.", inputSchema: { type: "object", properties: { project_id: { type: "string" }, limit: { type: "number" } } } },
629
+ { name: "usage_summary", description: "Project usage metrics: request volume, success rate, latency percentiles, and cost.", inputSchema: { type: "object", properties: { project_id: { type: "string" }, days: { type: "number", description: "Window in days (1, 7, 30). Default 7." } } } },
630
+ { name: "list_models", description: "The model catalog available to the project's plan: provider, model ids, context windows, and pricing.", inputSchema: { type: "object", properties: { project_id: { type: "string" } } } },
631
+ { name: "list_security_groups", description: "List the enforced security groups of a Zyntry project, with their rules.", inputSchema: { type: "object", properties: { project_id: { type: "string" } } } },
632
+ { name: "security_activity", description: "Recent security activity: blocked requests, quota hits, and group changes.", inputSchema: { type: "object", properties: { project_id: { type: "string" } } } },
633
+ { name: "quota", description: "The project's rate plans (end-user metering configuration).", inputSchema: { type: "object", properties: { project_id: { type: "string" } } } },
634
+ { name: "list_end_users", description: "List the project's end users with their usage.", inputSchema: { type: "object", properties: { project_id: { type: "string" }, search: { type: "string" } } } },
635
+ { name: "upsert_end_user", description: "Add or update an end user (idempotent by external_id). Optionally attach a rate plan.", inputSchema: { type: "object", properties: { external_id: { type: "string" }, display_name: { type: "string" }, email: { type: "string" }, rate_plan_id: { type: "string" }, project_id: { type: "string" } }, required: ["external_id"] } },
636
+ { name: "list_api_keys", description: "List the project's API keys (prefix, scopes, runtime scope, last use — secrets are never returned).", inputSchema: { type: "object", properties: { project_id: { type: "string" } } } },
637
+ { name: "list_webhooks", description: "List the project's webhook endpoints and their subscribed events.", inputSchema: { type: "object", properties: { project_id: { type: "string" } } } },
638
+ { name: "list_backups", description: "List a runtime's backups with status and size.", inputSchema: { type: "object", properties: { runtime_id: { type: "string" }, project_id: { type: "string" } } } },
639
+ { name: "create_backup", description: "Queue a backup for a runtime.", inputSchema: { type: "object", properties: { runtime_id: { type: "string" }, project_id: { type: "string" } } } },
640
+ { name: "product_updates", description: "Recent Zyntry product updates.", inputSchema: { type: "object", properties: {} } },
641
+ ];
642
+
643
+ const say = (text) => ({ content: [{ type: "text", text: String(text) }] });
644
+ const err = (text) => ({ isError: true, content: [{ type: "text", text: String(text) }] });
645
+
646
+ async function resolveRuntimeId(token, projectId, runtimeIdArg) {
647
+ if (runtimeIdArg) return String(runtimeIdArg);
648
+ const result = await api("/api/v1/runtimes?project_id=" + encodeURIComponent(projectId) + "&limit=50", {}, token);
649
+ const runtimes = result.ok ? (result.data.runtimes || result.data.items || []) : [];
650
+ return runtimes.length ? String(runtimes[0].id) : null;
651
+ }
652
+
653
+ async function mcpInvokeTool(name, args) {
654
+ const token = loadToken();
655
+ if (!token) return err("Not logged in. The developer must run 'zyntry login' first.");
656
+ args = args || {};
657
+ let projectId = args.project_id || readProjectIdFromYamlOptional();
658
+ const needsProject = !["list_projects", "create_project", "product_updates", "invoke"].includes(name);
659
+
660
+ if (name === "invoke") {
661
+ if (!args.prompt) return err("prompt is required");
662
+ if (!projectId) return err("No project context: pass project_id or run zyntry init in the working directory.");
663
+ const body = { project_id: projectId, messages: [{ role: "user", content: String(args.prompt) }] };
664
+ if (args.model) body.model = String(args.model);
665
+ if (args.runtime_id) body.runtime_id = String(args.runtime_id);
666
+ if (args.end_user_id) body.end_user_id = String(args.end_user_id);
667
+ const result = await api("/api/v1/invoke", { method: "POST", body: JSON.stringify(body) }, token);
668
+ if (result.status === 202 && result.data?.status === "approval_required") {
669
+ return say("A tool requested approval before running: " + JSON.stringify(result.data.tool_call) + ". The developer can approve by re-running the CLI with --approve <call_id>.");
670
+ }
671
+ if (!result.ok) return err("Invoke failed (" + result.status + "): " + (result.data?.message || result.data?.error || "unknown"));
672
+ const usage = result.data.usage || {};
673
+ return say(String(result.data.output ?? "") + "\n\n[provider " + (result.data.provider ?? "—") + " · model " + (result.data.model ?? "—") + " · " + (usage.input_tokens ?? 0) + "→" + (usage.output_tokens ?? 0) + " tokens · $" + Number(usage.cost_usd ?? 0).toFixed(6) + " · request " + (result.data.request_id ?? "—") + "]");
674
+ }
675
+
676
+ if (name === "list_projects") {
677
+ const result = await api("/api/v1/projects", {}, token);
678
+ if (!result.ok) return err("Failed (" + result.status + ")");
679
+ const projects = result.data.projects || [];
680
+ return say(projects.length ? projects.map((p) => p.name + " [" + (p.plan_code ?? "free") + "/" + (p.environment ?? "—") + "] id=" + p.id).join("\n") : "No projects yet.");
681
+ }
682
+ if (name === "create_project") {
683
+ if (!args.name) return err("name is required");
684
+ const account = await api("/api/v1/cli/account", {}, token);
685
+ if (!account.ok) return err("Account check failed (" + account.status + ")");
686
+ if (!account.data.free_project_available) return err("Free allowance used; paid plans need the interactive 'zyntry init' consent flow.");
687
+ const init = await api("/api/v1/cli/init", { method: "POST", body: JSON.stringify({ name: String(args.name), plan_code: "free" }) }, token);
688
+ if (!init.ok) return err(init.data?.message || "Creation failed (" + init.status + ")");
689
+ return say("Created project " + init.data.project.name + " (" + init.data.project.id + ")");
690
+ }
691
+ if (name === "product_updates") {
692
+ const result = await api("/api/v1/product-updates", {}, token);
693
+ if (!result.ok) return err("Failed (" + result.status + ")");
694
+ const updates = result.data.items || [];
695
+ return say(updates.length ? updates.map((u) => String(u.published_at ?? "").slice(0, 10) + " — " + u.title).join("\n") : "No product updates yet.");
696
+ }
697
+
698
+ if (needsProject && !projectId) return err("No project context: pass project_id or run zyntry init in the working directory.");
699
+
700
+ if (name === "list_runtimes") {
701
+ const result = await api("/api/v1/runtimes?project_id=" + encodeURIComponent(projectId) + "&limit=50", {}, token);
702
+ if (!result.ok) return err("Failed (" + result.status + ")");
703
+ const runtimes = result.data.runtimes || result.data.items || [];
704
+ return say(runtimes.length ? runtimes.map((r) => r.name + " [" + (r.environment ?? "—") + "/" + (r.region ?? "automatic") + " · " + String(r.health ?? r.status ?? "?") + "] id=" + r.id).join("\n") : "No runtimes.");
705
+ }
706
+ if (name === "list_regions") {
707
+ const result = await api("/api/v1/regions?project_id=" + encodeURIComponent(projectId), {}, token);
708
+ if (!result.ok) return err("Failed (" + result.status + ")");
709
+ const regions = result.data.regions || result.data.items || [];
710
+ return say(regions.length ? regions.map((r) => r.name + " [" + String(r.status ?? (r.available ? "available" : "plan required")) + "] id=" + r.id).join("\n") : "No regions returned.");
711
+ }
712
+ if (name === "list_deployments") {
713
+ const runtimeId = await resolveRuntimeId(token, projectId, args.runtime_id);
714
+ if (!runtimeId) return err("No runtimes in this project.");
715
+ const result = await api("/api/v1/runtimes/" + encodeURIComponent(runtimeId) + "/deployments", {}, token);
716
+ if (!result.ok) return err("Failed (" + result.status + ")");
717
+ const deployments = result.data.deployments || result.data.items || [];
718
+ return say(deployments.length ? deployments.map((d) => (d.region ?? "automatic") + " [" + String(d.health ?? d.status ?? "?") + "] v" + (d.version ?? "—") + (d.endpoint ? " " + d.endpoint : "")).join("\n") : "No deployments recorded.");
719
+ }
720
+ if (name === "redeploy_runtime") {
721
+ const runtimeId = await resolveRuntimeId(token, projectId, args.runtime_id);
722
+ if (!runtimeId) return err("No runtimes in this project.");
723
+ const result = await api("/api/v1/runtimes/" + encodeURIComponent(runtimeId) + "/deployments", { method: "POST" }, token);
724
+ if (!result.ok) return err("Redeploy failed (" + result.status + "): " + (result.data?.message || result.data?.error || ""));
725
+ return say("Redeployment queued for runtime " + runtimeId + " — the new version replaces the active deployment when healthy.");
726
+ }
727
+ if (name === "recent_logs") {
728
+ const limit = Math.min(Math.max(Number(args.limit) || 20, 1), 50);
729
+ const runtimeId = await resolveRuntimeId(token, projectId, args.runtime_id);
730
+ if (!runtimeId) return say("No runtimes — no logs yet.");
731
+ const result = await api("/api/v1/runtimes/" + encodeURIComponent(runtimeId) + "/logs?limit=" + limit, {}, token);
732
+ if (!result.ok) return err("Logs failed (" + result.status + ")");
733
+ const logs = result.data.logs || result.data.items || [];
734
+ return say(logs.length ? logs.map((l) => (l.created_at ?? "") + " [" + (l.status ?? "?") + "] " + (l.model ?? "—") + "/" + (l.provider ?? "—") + " " + (l.latency_ms ?? "—") + "ms" + (l.error_category ? " err=" + l.error_category : "")).join("\n") : "No logs yet.");
735
+ }
736
+ if (name === "list_traces") {
737
+ const limit = Math.min(Math.max(Number(args.limit) || 20, 1), 100);
738
+ const result = await api("/api/v1/insights/projects/" + encodeURIComponent(projectId) + "/traces?limit=" + limit, {}, token);
739
+ if (!result.ok) return err("Failed (" + result.status + ")");
740
+ const traces = result.data.items || [];
741
+ return say(traces.length ? traces.map((t) => (t.started_at ?? "") + " [" + (t.status ?? "?") + " · " + (t.spans?.length ?? t.span_count ?? 0) + " spans] " + (t.id ?? "")).join("\n") : "No traces yet.");
742
+ }
743
+ if (name === "usage_summary") {
744
+ const days = [1, 7, 30].includes(Number(args.days)) ? Number(args.days) : 7;
745
+ const result = await api("/api/v1/insights/projects/" + encodeURIComponent(projectId) + "/metrics?days=" + days, {}, token);
746
+ if (!result.ok) return err("Failed (" + result.status + ")");
747
+ const m = result.data;
748
+ return say("Requests: " + (m.requests ?? 0) + " · success rate: " + (m.success_rate ?? 0) + "% · p50: " + (m.p50_latency_ms ?? "—") + "ms · p95: " + (m.p95_latency_ms ?? "—") + "ms · cost: $" + Number(m.cost ?? 0).toFixed(4) + " (last " + days + " day" + (days === 1 ? "" : "s") + ")");
749
+ }
750
+ if (name === "list_models") {
751
+ const result = await api("/api/v1/models?project_id=" + encodeURIComponent(projectId), {}, token);
752
+ if (!result.ok) return err("Failed (" + result.status + ")");
753
+ const models = result.data.models || result.data.items || result.data || [];
754
+ const list = Array.isArray(models) ? models : [];
755
+ return say(list.length ? list.map((mm) => (mm.provider ?? "—") + "/" + (mm.id ?? mm.model ?? "—") + " [ctx " + (mm.context_window ?? mm.context ?? "?") + "]").join("\n") : "No models returned.");
756
+ }
757
+ if (name === "list_security_groups") {
758
+ const result = await api("/api/v1/projects/" + encodeURIComponent(projectId) + "/security-groups", {}, token);
759
+ if (!result.ok) return err("Failed (" + result.status + "): " + (result.data?.message || result.data?.error || ""));
760
+ const groups = result.data.items || [];
761
+ return say(groups.length ? groups.map((g) => g.name + " [" + (g.enabled ? "enabled" : "disabled") + " · " + (g.rules || []).length + " rules · " + (g.runtime_ids || []).length + " runtimes] id=" + g.id).join("\n") : "No security groups.");
762
+ }
763
+ if (name === "security_activity") {
764
+ const result = await api("/api/v1/projects/" + encodeURIComponent(projectId) + "/security-groups/activity", {}, token);
765
+ if (!result.ok) return err("Failed (" + result.status + "): " + (result.data?.message || result.data?.error || ""));
766
+ const events = result.data.items || [];
767
+ return say(events.length ? events.slice(0, 20).map((e) => (e.created_at ?? "") + " " + (e.event_type ?? "?") + (e.data?.reason ? " · " + e.data.reason : "")).join("\n") : "No security activity yet.");
768
+ }
769
+ if (name === "quota") {
770
+ const result = await api("/api/v1/projects/" + encodeURIComponent(projectId) + "/rate-plans", {}, token);
771
+ if (!result.ok) return err("Failed (" + result.status + ")");
772
+ const plans = result.data.items || result.data.plans || [];
773
+ return say(plans.length ? JSON.stringify(plans, null, 2) : "No rate plans configured; end-user metering is inactive for this project.");
774
+ }
775
+ if (name === "list_end_users") {
776
+ const search = args.search ? "&search=" + encodeURIComponent(String(args.search)) : "";
777
+ const result = await api("/api/v1/projects/" + encodeURIComponent(projectId) + "/end-users?limit=50" + search, {}, token);
778
+ if (!result.ok) return err("Failed (" + result.status + ")");
779
+ const users = result.data.end_users || result.data.items || [];
780
+ return say(users.length ? users.map((u) => (u.external_id ?? u.id) + (u.display_name ? " — " + u.display_name : "") + (u.rate_plan_id ? " [plan " + u.rate_plan_id + "]" : "")).join("\n") : "No end users yet.");
781
+ }
782
+ if (name === "upsert_end_user") {
783
+ if (!args.external_id) return err("external_id is required");
784
+ const body = { external_id: String(args.external_id) };
785
+ if (args.display_name) body.display_name = String(args.display_name);
786
+ if (args.email) body.email = String(args.email);
787
+ if (args.rate_plan_id) body.rate_plan_id = String(args.rate_plan_id);
788
+ const result = await api("/api/v1/projects/" + encodeURIComponent(projectId) + "/end-users", { method: "POST", body: JSON.stringify(body) }, token);
789
+ if (!result.ok) return err("Failed (" + result.status + "): " + (result.data?.message || result.data?.error || ""));
790
+ return say("End user " + (result.data.external_id ?? args.external_id) + " saved.");
791
+ }
792
+ if (name === "list_api_keys") {
793
+ const result = await api("/api/v1/apikeys?project_id=" + encodeURIComponent(projectId), {}, token);
794
+ if (!result.ok) return err("Failed (" + result.status + ")");
795
+ const keys = result.data.api_keys || result.data.items || [];
796
+ return say(keys.length ? keys.map((k) => (k.name ?? "key") + " [" + (k.environment ?? "—") + " · " + (k.status ?? (k.revoked ? "revoked" : "active")) + " · prefix " + (k.prefix ?? k.key_prefix ?? "—") + "]").join("\n") : "No API keys.");
797
+ }
798
+ if (name === "list_webhooks") {
799
+ const result = await api("/api/v1/webhooks?project_id=" + encodeURIComponent(projectId), {}, token);
800
+ if (!result.ok) return err("Failed (" + result.status + ")");
801
+ const webhooks = result.data.items || [];
802
+ return say(webhooks.length ? webhooks.map((w) => (w.url ?? "endpoint") + " [" + (w.events || []).length + " events · " + (w.active ? "active" : "inactive") + "]").join("\n") : "No webhooks.");
803
+ }
804
+ if (name === "list_backups") {
805
+ const runtimeId = await resolveRuntimeId(token, projectId, args.runtime_id);
806
+ if (!runtimeId) return err("No runtimes in this project.");
807
+ const result = await api("/api/v1/insights/runtimes/" + encodeURIComponent(runtimeId) + "/backups", {}, token);
808
+ if (!result.ok) return err("Failed (" + result.status + ")");
809
+ const backups = result.data.items || result.data.backups || [];
810
+ return say(backups.length ? backups.map((b) => (b.created_at ?? "") + " [" + (b.status ?? "?") + (b.size_bytes ? " · " + b.size_bytes + " bytes" : "") + "] " + (b.id ?? "")).join("\n") : "No backups yet.");
811
+ }
812
+ if (name === "create_backup") {
813
+ const runtimeId = await resolveRuntimeId(token, projectId, args.runtime_id);
814
+ if (!runtimeId) return err("No runtimes in this project.");
815
+ const result = await api("/api/v1/insights/runtimes/" + encodeURIComponent(runtimeId) + "/backups", { method: "POST" }, token);
816
+ if (!result.ok) return err("Failed (" + result.status + "): " + (result.data?.message || result.data?.error || ""));
817
+ return say("Backup queued for runtime " + runtimeId + ".");
818
+ }
819
+ return err("Unknown tool: " + name);
820
+ }
821
+
822
+ function commandMcp() {
823
+ const rl = readline.createInterface({ input: process.stdin, terminal: false });
824
+ const write = (message) => process.stdout.write(JSON.stringify(message) + "\n");
825
+ const send = (id, result) => write({ jsonrpc: "2.0", id, result });
826
+ const sendError = (id, code, message) => write({ jsonrpc: "2.0", id, error: { code, message } });
827
+ rl.on("line", (line) => {
828
+ if (!line.trim()) return;
829
+ let message;
830
+ try { message = JSON.parse(line); } catch { return; }
831
+ const method = String(message?.method ?? "");
832
+ if (method === "initialize") {
833
+ send(message.id, { protocolVersion: "2024-11-05", capabilities: { tools: { listChanged: false } }, serverInfo: { name: "zyntry", version: "0.2.0" } });
834
+ } else if (method.startsWith("notifications/")) {
835
+ /* notifications get no response */
836
+ } else if (method === "ping") {
837
+ send(message.id, {});
838
+ } else if (method === "tools/list") {
839
+ send(message.id, { tools: MCP_TOOLS });
840
+ } else if (method === "tools/call") {
841
+ const name = String(message.params?.name ?? "");
842
+ const args = message.params?.arguments || {};
843
+ mcpInvokeTool(name, args).then((result) => send(message.id, result)).catch((error) => sendError(message.id, -32603, String(error?.message ?? error)));
844
+ } else if (message.id !== undefined) {
845
+ sendError(message.id, -32601, "Method not found: " + (method || "(none)"));
846
+ }
847
+ });
848
+ rl.on("close", () => process.exit(0));
849
+ }
850
+
851
+ const [command, ...rest] = process.argv.slice(2);
852
+ switch (command) {
853
+ case "login": await commandLogin(); break;
854
+ case "whoami": case "me": await commandWhoami(); break;
855
+ case "init": await commandInit(rest[0]); break;
856
+ case "logout": await commandLogout(); break;
857
+ case "plans": await commandPlans(rest[0]); break;
858
+ case "users": await commandUsers(rest[0]); break;
859
+ case "quota": await commandQuota(rest[0]); break;
860
+ case "projects": await commandProjects(rest[0], rest[1]); break;
861
+ case "run": case "invoke": await commandRun(rest); break;
862
+ case "mcp": commandMcp(); break;
863
+ case "regions": await commandRegions(); break;
864
+ case "runtimes": await commandRuntimes(); break;
865
+ case "redeploy": await commandRedeploy(rest[0]); break;
866
+ case "security": await commandSecurity(rest[0]); break;
867
+ case "updates": await commandUpdates(); break;
868
+ case "help": case "--help": case undefined: log(HELP); break;
869
+ default: fail("Unknown command: " + command + "\n"); log(HELP); process.exit(1);
870
+ }
package/package.json CHANGED
@@ -1,6 +1,33 @@
1
1
  {
2
2
  "name": "zyntry",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.3.0",
4
+ "description": "The Zyntry CLI — run AI inference, manage runtimes, security groups, and end-user metering from the terminal. Ships with a built-in MCP server for Claude Code, Cursor, and Windsurf.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "bin": {
8
+ "zyntry": "./index.mjs"
9
+ },
10
+ "engines": {
11
+ "node": ">=18"
12
+ },
13
+ "keywords": [
14
+ "zyntry",
15
+ "ai",
16
+ "cli",
17
+ "mcp",
18
+ "llm",
19
+ "inference",
20
+ "model-router",
21
+ "llm-gateway",
22
+ "ai-platform"
23
+ ],
24
+ "repository": {
25
+ "type": "git",
26
+ "url": "git+https://github.com/devspak-s8/zyntry-backend.git"
27
+ },
28
+ "files": [
29
+ "index.mjs",
30
+ "README.md"
31
+ ],
32
+ "preferGlobal": true
33
+ }