kowlun 0.0.0-stage → 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 CHANGED
@@ -1,3 +1,58 @@
1
- # Temporary Holding Version
1
+ # kowlun
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
+ CLI and MCP server for **SuperApp** ([kowlun.com](https://kowlun.com)) — a home for personal apps you build with AI. Your agent deploys an app folder with one command, and it opens on your phone with a ready backend: user, database, files and AI through the SDK.
4
+
5
+ ## Quick start
6
+
7
+ ```
8
+ npx kowlun login # confirm the code in your browser
9
+ npx kowlun deploy ./my-app # → https://my-app.kowlun.app
10
+ ```
11
+
12
+ Or install globally: `npm i -g kowlun` — then use `kowlun …` (alias `superapp …`).
13
+
14
+ ## Commands
15
+
16
+ ```
17
+ kowlun login sign in (device code, confirmed in the browser)
18
+ kowlun whoami who is signed in
19
+ kowlun deploy [dir] deploy a folder with app.json (new version)
20
+ kowlun list my apps
21
+ kowlun info <name> versions of an app
22
+ kowlun rollback <name> [v] roll back to a previous version
23
+ kowlun mcp MCP server for agents (stdio)
24
+ kowlun logout
25
+ ```
26
+
27
+ ## For agents (MCP)
28
+
29
+ Claude Code:
30
+
31
+ ```
32
+ claude mcp add superapp -- npx -y kowlun mcp
33
+ ```
34
+
35
+ On native Windows: `claude mcp add superapp -- cmd /c npx -y kowlun mcp`.
36
+
37
+ Cursor, `.cursor/mcp.json`:
38
+
39
+ ```json
40
+ { "mcpServers": { "superapp": { "command": "npx", "args": ["-y", "kowlun", "mcp"] } } }
41
+ ```
42
+
43
+ Tools: `superapp_deploy`, `superapp_list`, `superapp_info`, `superapp_rollback`, `superapp_whoami`. Sign in once with `npx kowlun login` before using them.
44
+
45
+ ## App format
46
+
47
+ ```
48
+ my-app/
49
+ app.json {"name": "my-app", "title": "My app", "icon": "🏃"}
50
+ web/index.html entry point; everything in web/ is served as static files
51
+ ```
52
+
53
+ ## Environment
54
+
55
+ - `SUPERAPP_API` — platform address (default `https://kowlun.com`). For local development: `kowlun login --api http://localhost:8787`.
56
+ - `SUPERAPP_TOKEN` — session token instead of `login` (CI).
57
+
58
+ Sign-in is stored in `~/.superapp/config.json`.
package/dist/config.js ADDED
@@ -0,0 +1,31 @@
1
+ // Хранение входа CLI: ~/.superapp/config.json (только для текущего пользователя ОС).
2
+ import { mkdir, readFile, rm, writeFile, chmod } from "node:fs/promises";
3
+ import { homedir } from "node:os";
4
+ import { join } from "node:path";
5
+ const DIR = join(homedir(), ".superapp");
6
+ const FILE = join(DIR, "config.json");
7
+ /** Прод. Для локальной разработки: `superapp login --api http://localhost:8787` или SUPERAPP_API. */
8
+ const DEFAULT_API = "https://kowlun.com";
9
+ export async function loadConfig() {
10
+ let saved = {};
11
+ try {
12
+ saved = JSON.parse(await readFile(FILE, "utf8"));
13
+ }
14
+ catch {
15
+ /* ещё не входили */
16
+ }
17
+ return {
18
+ api: (process.env.SUPERAPP_API ?? saved.api ?? DEFAULT_API).replace(/\/$/, ""),
19
+ token: process.env.SUPERAPP_TOKEN ?? saved.token,
20
+ email: saved.email,
21
+ };
22
+ }
23
+ export async function saveConfig(config) {
24
+ await mkdir(DIR, { recursive: true });
25
+ await writeFile(FILE, JSON.stringify(config, null, 2), { mode: 0o600 });
26
+ await chmod(FILE, 0o600).catch(() => { }); // на Windows права не применяются — не страшно
27
+ }
28
+ export async function clearConfig() {
29
+ await rm(FILE, { force: true });
30
+ }
31
+ export const configPath = FILE;
package/dist/core.js ADDED
@@ -0,0 +1,102 @@
1
+ // Действия с платформой, общие для CLI и MCP-сервера. Ничего не печатают и не завершают процесс:
2
+ // возвращают данные или бросают CliError с понятным сообщением.
3
+ import { readFile, readdir, stat } from "node:fs/promises";
4
+ import { join, relative, resolve, sep } from "node:path";
5
+ import { loadConfig } from "./config.js";
6
+ export class CliError extends Error {
7
+ }
8
+ const IGNORE = new Set(["node_modules", ".git", ".DS_Store", "Thumbs.db"]);
9
+ export const kb = (n) => (n < 1024 * 1024 ? `${(n / 1024).toFixed(1)} КБ` : `${(n / 1024 / 1024).toFixed(1)} МБ`);
10
+ export async function http(config, path, init = {}, auth = true) {
11
+ let res;
12
+ try {
13
+ res = await fetch(config.api + path, {
14
+ ...init,
15
+ headers: { ...(auth && config.token ? { authorization: `Bearer ${config.token}` } : {}), ...(init.headers ?? {}) },
16
+ });
17
+ }
18
+ catch {
19
+ throw new CliError(`Не удалось подключиться к ${config.api}. Проверьте интернет (локально — запущен ли pnpm run dev:api).`);
20
+ }
21
+ return { status: res.status, body: await res.json().catch(() => ({})) };
22
+ }
23
+ /** Запрос к API от имени вошедшего пользователя. */
24
+ export async function api(path, init = {}) {
25
+ const config = await loadConfig();
26
+ if (!config.token)
27
+ throw new CliError("Сначала войдите: npx kowlun login");
28
+ const { status, body } = await http(config, path, init);
29
+ if (status === 401)
30
+ throw new CliError("Вход истёк. Войдите снова: npx kowlun login");
31
+ if (status >= 400)
32
+ throw new CliError(body.message ?? body.error ?? `API ответил ${status}`);
33
+ return body;
34
+ }
35
+ async function walk(root, dir, out) {
36
+ let entries;
37
+ try {
38
+ entries = await readdir(dir, { withFileTypes: true });
39
+ }
40
+ catch {
41
+ return; // папки нет — нормально для server/
42
+ }
43
+ for (const e of entries) {
44
+ if (IGNORE.has(e.name) || e.name.startsWith("."))
45
+ continue;
46
+ const full = join(dir, e.name);
47
+ if (e.isDirectory())
48
+ await walk(root, full, out);
49
+ else if (e.isFile())
50
+ out.push(relative(root, full).split(sep).join("/"));
51
+ }
52
+ }
53
+ export async function deploy(dirArg) {
54
+ const dir = resolve(dirArg);
55
+ let manifestRaw;
56
+ try {
57
+ manifestRaw = await readFile(join(dir, "app.json"), "utf8");
58
+ }
59
+ catch {
60
+ throw new CliError(`В ${dir} нет app.json.`);
61
+ }
62
+ let manifest;
63
+ try {
64
+ manifest = JSON.parse(manifestRaw);
65
+ }
66
+ catch {
67
+ throw new CliError("app.json — не валидный JSON.");
68
+ }
69
+ if (!manifest.name)
70
+ throw new CliError("В app.json нет поля name.");
71
+ const paths = [];
72
+ await walk(dir, join(dir, "web"), paths);
73
+ await walk(dir, join(dir, "server"), paths);
74
+ if (!paths.includes("web/index.html"))
75
+ throw new CliError(`Нет ${join(dir, "web", "index.html")}.`);
76
+ const form = new FormData();
77
+ form.set("manifest", manifestRaw);
78
+ let bytes = 0;
79
+ for (const p of paths) {
80
+ const data = await readFile(join(dir, p));
81
+ bytes += (await stat(join(dir, p))).size;
82
+ form.append(`f:${p}`, new Blob([data]), p.split("/").pop());
83
+ }
84
+ const r = await api(`/v1/apps/${encodeURIComponent(manifest.name)}/versions`, { method: "POST", body: form });
85
+ return { app: r.app, version: r.version, files: r.files, bytes: r.bytes, url: r.url, warnings: r.warnings ?? [] };
86
+ }
87
+ export async function listApps() {
88
+ return (await api("/v1/apps")).apps;
89
+ }
90
+ export async function appInfo(name) {
91
+ return api(`/v1/apps/${encodeURIComponent(name)}`);
92
+ }
93
+ export async function rollback(name, version) {
94
+ return api(`/v1/apps/${encodeURIComponent(name)}/rollback`, {
95
+ method: "POST",
96
+ headers: { "content-type": "application/json" },
97
+ body: JSON.stringify({ version }),
98
+ });
99
+ }
100
+ export async function whoami() {
101
+ return (await api("/v1/me")).user;
102
+ }
package/dist/index.js ADDED
@@ -0,0 +1,174 @@
1
+ #!/usr/bin/env node
2
+ // SuperApp CLI.
3
+ //
4
+ // superapp login войти (подтверждение в браузере)
5
+ // superapp logout выйти
6
+ // superapp whoami кто вошёл
7
+ // superapp deploy [dir] залить апку
8
+ // superapp list мои апки
9
+ // superapp info <name> версии апки
10
+ // superapp rollback <name> откатить на прошлую версию
11
+ // superapp mcp MCP-сервер для агентов (stdio)
12
+ //
13
+ // Переменные окружения: SUPERAPP_API (адрес платформы), SUPERAPP_TOKEN (токен вместо входа, для CI).
14
+ import { Command } from "commander";
15
+ import { spawn } from "node:child_process";
16
+ import { clearConfig, configPath, loadConfig, saveConfig } from "./config.js";
17
+ import { appInfo, CliError, deploy, http, kb, listApps, rollback, whoami } from "./core.js";
18
+ const VERSION = "0.1.0";
19
+ const CLIENT_ID = "superapp-cli";
20
+ function fail(message) {
21
+ console.error(`✖ ${message}`);
22
+ process.exit(1);
23
+ }
24
+ /** Выполнить команду: ошибки платформы — понятным текстом, без стектрейса. */
25
+ const run = (fn) => async (...args) => {
26
+ try {
27
+ await fn(...args);
28
+ }
29
+ catch (e) {
30
+ if (e instanceof CliError)
31
+ fail(e.message);
32
+ throw e;
33
+ }
34
+ };
35
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
36
+ function openBrowser(url) {
37
+ const [cmd, args] = process.platform === "win32"
38
+ ? ["rundll32", ["url.dll,FileProtocolHandler", url]]
39
+ : process.platform === "darwin"
40
+ ? ["open", [url]]
41
+ : ["xdg-open", [url]];
42
+ try {
43
+ spawn(cmd, args, { stdio: "ignore", detached: true }).on("error", () => { }).unref();
44
+ }
45
+ catch {
46
+ /* не открылся — ссылка всё равно напечатана */
47
+ }
48
+ }
49
+ const program = new Command().name("kowlun").description("Деплой персональных апок в SuperApp").version(VERSION);
50
+ // --- Вход ------------------------------------------------------------------------------
51
+ program
52
+ .command("login")
53
+ .description("Войти: подтвердите код в браузере")
54
+ .option("--api <url>", "адрес платформы")
55
+ .option("--no-open", "не открывать браузер автоматически")
56
+ .action(run(async (opts) => {
57
+ const config = await loadConfig();
58
+ if (opts.api)
59
+ config.api = opts.api.replace(/\/$/, "");
60
+ const start = await http(config, "/api/auth/device/code", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ client_id: CLIENT_ID }) }, false);
61
+ if (start.status >= 400)
62
+ fail(start.body.message ?? start.body.error_description ?? "Не удалось начать вход.");
63
+ const { device_code, user_code, verification_uri_complete, verification_uri, interval = 5, expires_in = 900 } = start.body;
64
+ const link = new URL(verification_uri_complete ?? verification_uri, config.api).toString();
65
+ console.log(`\nКод: ${user_code}`);
66
+ console.log(`Подтвердите вход в браузере: ${link}\n`);
67
+ if (opts.open)
68
+ openBrowser(link);
69
+ let wait = Number(interval) * 1000;
70
+ const deadline = Date.now() + Number(expires_in) * 1000;
71
+ process.stdout.write("Ждём подтверждения");
72
+ while (Date.now() < deadline) {
73
+ await sleep(wait);
74
+ process.stdout.write(".");
75
+ const poll = await http(config, "/api/auth/device/token", {
76
+ method: "POST",
77
+ headers: { "content-type": "application/json" },
78
+ body: JSON.stringify({ grant_type: "urn:ietf:params:oauth:grant-type:device_code", device_code, client_id: CLIENT_ID }),
79
+ }, false);
80
+ if (poll.body.access_token) {
81
+ config.token = poll.body.access_token;
82
+ const me = await http(config, "/v1/me");
83
+ config.email = me.body.user?.email;
84
+ await saveConfig(config);
85
+ console.log(`\n✔ Вы вошли как ${config.email ?? "пользователь"}`);
86
+ return;
87
+ }
88
+ const error = poll.body.error;
89
+ if (error === "authorization_pending")
90
+ continue;
91
+ if (error === "slow_down") {
92
+ wait += 5000;
93
+ continue;
94
+ }
95
+ if (error === "access_denied")
96
+ fail("\nВход отклонён.");
97
+ if (error === "expired_token")
98
+ fail("\nКод истёк. Запустите npx kowlun login ещё раз.");
99
+ fail(`\n${poll.body.error_description ?? error ?? "Не удалось войти."}`);
100
+ }
101
+ fail("\nКод истёк. Запустите npx kowlun login ещё раз.");
102
+ }));
103
+ program
104
+ .command("logout")
105
+ .description("Выйти")
106
+ .action(run(async () => {
107
+ const config = await loadConfig();
108
+ if (config.token) {
109
+ await http(config, "/api/auth/sign-out", { method: "POST", headers: { "content-type": "application/json" }, body: "{}" }).catch(() => { });
110
+ }
111
+ await clearConfig();
112
+ console.log("✔ Вы вышли");
113
+ }));
114
+ program
115
+ .command("whoami")
116
+ .description("Кто вошёл")
117
+ .action(run(async () => {
118
+ const user = await whoami();
119
+ const config = await loadConfig();
120
+ console.log(`${user.name || user.email} <${user.email}> · ${config.api}`);
121
+ console.log(`Вход сохранён в ${configPath}`);
122
+ }));
123
+ // --- Апки ------------------------------------------------------------------------------
124
+ program
125
+ .command("deploy")
126
+ .description("Залить папку с app.json")
127
+ .argument("[dir]", "папка апки", ".")
128
+ .action(run(async (dir) => {
129
+ const r = await deploy(dir);
130
+ console.log(`✔ ${r.app}: версия ${r.version} опубликована (${r.files} файлов, ${kb(r.bytes)})`);
131
+ for (const w of r.warnings)
132
+ console.log(`! ${w}`);
133
+ console.log(`→ ${r.url}`);
134
+ }));
135
+ program
136
+ .command("list")
137
+ .description("Мои апки")
138
+ .action(run(async () => {
139
+ const apps = await listApps();
140
+ if (!apps.length)
141
+ return console.log("Апок пока нет. Залейте первую: npx kowlun deploy <папка>");
142
+ for (const a of apps)
143
+ console.log(`${a.icon ?? "•"} ${a.name.padEnd(24)} ${a.title.padEnd(28)} ${a.url}`);
144
+ }));
145
+ program
146
+ .command("info")
147
+ .description("Версии апки")
148
+ .argument("<name>")
149
+ .action(run(async (name) => {
150
+ const { app, versions } = await appInfo(name);
151
+ console.log(`${app.icon ?? "•"} ${app.title} → ${app.url}`);
152
+ for (const v of versions) {
153
+ const mark = v.id === app.current_version ? "●" : "○";
154
+ console.log(`${mark} ${v.id} ${new Date(v.created_at).toLocaleString()} ${v.file_count} файлов, ${kb(v.total_bytes)}`);
155
+ }
156
+ }));
157
+ program
158
+ .command("rollback")
159
+ .description("Откатить на прошлую версию (или на указанную)")
160
+ .argument("<name>")
161
+ .argument("[version]")
162
+ .action(run(async (name, version) => {
163
+ const r = await rollback(name, version);
164
+ console.log(`✔ ${name} теперь на версии ${r.version}`);
165
+ }));
166
+ // --- MCP ---------------------------------------------------------------------------------
167
+ program
168
+ .command("mcp")
169
+ .description("MCP-сервер для ИИ-агентов (Claude Code, Cursor): деплой и откат апок")
170
+ .action(async () => {
171
+ const { startMcp } = await import("./mcp.js");
172
+ await startMcp(VERSION);
173
+ });
174
+ await program.parseAsync();
package/dist/mcp.js ADDED
@@ -0,0 +1,75 @@
1
+ // MCP-сервер SuperApp поверх stdio: агент (Claude Code, Cursor) заливает и откатывает апки сам.
2
+ // Вход — тот же, что у CLI (~/.superapp/config.json). Запуск: superapp mcp.
3
+ // Важно: в stdout пишет только протокол MCP, никаких console.log.
4
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
5
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
6
+ import { z } from "zod";
7
+ import { appInfo, CliError, deploy, kb, listApps, rollback, whoami } from "./core.js";
8
+ const ok = (text) => ({ content: [{ type: "text", text }] });
9
+ async function run(fn) {
10
+ try {
11
+ return ok(await fn());
12
+ }
13
+ catch (e) {
14
+ const message = e instanceof CliError ? e.message : `Unexpected error: ${e instanceof Error ? e.message : String(e)}`;
15
+ return { content: [{ type: "text", text: message }], isError: true };
16
+ }
17
+ }
18
+ export async function startMcp(version) {
19
+ const server = new McpServer({ name: "superapp", version });
20
+ server.registerTool("superapp_deploy", {
21
+ title: "Deploy app to SuperApp",
22
+ description: "Publish a SuperApp mini-app folder as a new version. The folder must contain app.json (name, title, icon) and web/index.html. " +
23
+ "Returns the app URL. Every deploy is a new version; use superapp_rollback to go back.",
24
+ inputSchema: { path: z.string().describe("Absolute path to the app folder (the one with app.json)") },
25
+ }, ({ path }) => run(async () => {
26
+ const r = await deploy(path);
27
+ const lines = [`Deployed ${r.app}, version ${r.version} (${r.files} files, ${kb(r.bytes)}).`, `URL: ${r.url}`];
28
+ for (const w of r.warnings)
29
+ lines.push(`Warning: ${w}`);
30
+ lines.push("Open the URL to check it. The user may be asked to sign in and allow the app on first open.");
31
+ return lines.join("\n");
32
+ }));
33
+ server.registerTool("superapp_list", {
34
+ title: "List my SuperApp apps",
35
+ description: "List the signed-in user's SuperApp apps with their URLs.",
36
+ inputSchema: {},
37
+ }, () => run(async () => {
38
+ const apps = await listApps();
39
+ if (!apps.length)
40
+ return "No apps yet.";
41
+ return apps.map((a) => `${a.icon ?? "•"} ${a.name} — ${a.title} — ${a.url}`).join("\n");
42
+ }));
43
+ server.registerTool("superapp_info", {
44
+ title: "SuperApp app versions",
45
+ description: "Show an app's URL and its recent versions; the current one is marked.",
46
+ inputSchema: { name: z.string().describe("App name from app.json") },
47
+ }, ({ name }) => run(async () => {
48
+ const { app, versions } = await appInfo(name);
49
+ const lines = [`${app.icon ?? "•"} ${app.title} — ${app.url}`];
50
+ for (const v of versions) {
51
+ lines.push(`${v.id === app.current_version ? "● current" : "○"} ${v.id} — ${new Date(v.created_at).toISOString()} — ${v.file_count} files`);
52
+ }
53
+ return lines.join("\n");
54
+ }));
55
+ server.registerTool("superapp_rollback", {
56
+ title: "Roll back a SuperApp app",
57
+ description: "Make an earlier version current again. Without version, goes back to the previous one.",
58
+ inputSchema: {
59
+ name: z.string().describe("App name"),
60
+ version: z.string().optional().describe("Version id from superapp_info; omit for the previous version"),
61
+ },
62
+ }, ({ name, version }) => run(async () => {
63
+ const r = await rollback(name, version);
64
+ return `${r.app} is now on version ${r.version}. URL: ${r.url}`;
65
+ }));
66
+ server.registerTool("superapp_whoami", {
67
+ title: "SuperApp account",
68
+ description: "Check which SuperApp account is signed in. If not signed in, ask the user to run `npx -y kowlun login` in a terminal.",
69
+ inputSchema: {},
70
+ }, () => run(async () => {
71
+ const u = await whoami();
72
+ return `Signed in as ${u.name} <${u.email}>.`;
73
+ }));
74
+ await server.connect(new StdioServerTransport());
75
+ }
package/package.json CHANGED
@@ -1,6 +1,43 @@
1
1
  {
2
2
  "name": "kowlun",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Deploy personal AI-made apps to SuperApp (kowlun.com): CLI and MCP server for coding agents",
5
+ "type": "module",
6
+ "bin": {
7
+ "kowlun": "dist/index.js",
8
+ "superapp": "dist/index.js"
9
+ },
10
+ "files": [
11
+ "dist",
12
+ "README.md"
13
+ ],
14
+ "engines": {
15
+ "node": ">=20"
16
+ },
17
+ "license": "UNLICENSED",
18
+ "keywords": [
19
+ "superapp",
20
+ "kowlun",
21
+ "mcp",
22
+ "claude-code",
23
+ "cursor",
24
+ "deploy"
25
+ ],
26
+ "homepage": "https://kowlun.com",
27
+ "scripts": {
28
+ "build": "tsc -p .",
29
+ "typecheck": "tsc -p . --noEmit",
30
+ "prepublishOnly": "tsc -p ."
31
+ },
32
+ "dependencies": {
33
+ "@modelcontextprotocol/sdk": "^1.32.0",
34
+ "commander": "^14.0.0",
35
+ "zod": "^4.0.0"
36
+ },
37
+ "devDependencies": {
38
+ "@types/node": "^22.0.0"
39
+ },
40
+ "publishConfig": {
41
+ "access": "public"
42
+ }
43
+ }