embarko 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.
@@ -0,0 +1,162 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { createInterface } from "node:readline/promises";
3
+ import { MCP_URL, SITE_URL } from "../lib/api.js";
4
+ import { installMcp, onPath } from "../lib/agents.js";
5
+ import { resolveToken, saveToken } from "../lib/credentials.js";
6
+ import { bold, dim, green, line, red, step } from "../lib/out.js";
7
+ import { browserLogin } from "./login.js";
8
+
9
+ export const options = {
10
+ "dry-run": { type: "boolean" },
11
+ yes: { type: "boolean", short: "y" },
12
+ "no-login": { type: "boolean" },
13
+ "skip-install": { type: "boolean" },
14
+ "skip-skill": { type: "boolean" },
15
+ "skip-mcp": { type: "boolean" },
16
+ };
17
+
18
+ export const usage = `Usage: embarko setup [options]
19
+
20
+ One command to get Embarko into every AI tool on this machine:
21
+ 1. installs the embarko CLI (npm install -g), when run through npx
22
+ 2. adds the Embarko deploy skill to your AI agents (Claude Code, Cursor,
23
+ Codex, ... — the ones installed here)
24
+ 3. adds the Embarko MCP server to Claude Code, Cursor, Codex, OpenCode,
25
+ GitHub Copilot CLI and Factory Droid, where installed
26
+ 4. signs you in through the browser (skip with --no-login)
27
+
28
+ Options:
29
+ --dry-run Show what would change, change nothing
30
+ -y, --yes Sign in without asking first
31
+ --no-login Don't sign in
32
+ --skip-install Don't install the CLI globally
33
+ --skip-skill Don't add the skill
34
+ --skip-mcp Don't add the MCP server`;
35
+
36
+ const SKILL_REPO = process.env.EMBARKO_SKILL_REPO || "embarko-ai/skill";
37
+ const SKILL_NAME = "embarko-deploy";
38
+ const NPM_PACKAGE = process.env.EMBARKO_NPM_PACKAGE || "embarko@latest";
39
+
40
+ export async function run(values) {
41
+ const dry = values["dry-run"];
42
+ const shell = process.platform === "win32"; // npm/npx are .cmd files there
43
+ let failed = 0;
44
+ const say = (ok, msg) => line(` ${ok === true ? green("✓") : ok === false ? red("✗") : dim("·")} ${msg}`);
45
+
46
+ line(bold(`Embarko setup${dry ? " (dry run: nothing will change)" : ""}`));
47
+ line();
48
+
49
+ // 1. CLI
50
+ step("CLI");
51
+ if (values["skip-install"]) say(null, "skipped (--skip-install)");
52
+ else if (!runningFromNpx()) say(true, "embarko is installed");
53
+ else if (dry) say(null, `would run: npm install -g ${NPM_PACKAGE}`);
54
+ else {
55
+ const res = spawnSync("npm", ["install", "-g", NPM_PACKAGE], { stdio: ["ignore", "ignore", "pipe"], encoding: "utf8", shell });
56
+ if (res.status === 0) say(true, "installed: the `embarko` command is ready");
57
+ else {
58
+ failed++;
59
+ say(false, `npm install -g ${NPM_PACKAGE} failed. Keep using \`npx embarko\`, or install it yourself.`);
60
+ if (res.stderr) line(dim(indent(lastLines(res.stderr, 4))));
61
+ }
62
+ }
63
+
64
+ // 2. Skill
65
+ step("Skill");
66
+ const skillArgs = ["-y", "skills", "add", SKILL_REPO, "--skill", SKILL_NAME, "-g", "-y", "--copy"];
67
+ if (values["skip-skill"]) say(null, "skipped (--skip-skill)");
68
+ else if (dry) say(null, `would run: npx ${skillArgs.join(" ")}`);
69
+ else {
70
+ const res = spawnSync("npx", skillArgs, {
71
+ stdio: ["ignore", "pipe", "pipe"],
72
+ encoding: "utf8",
73
+ shell,
74
+ env: { ...process.env, AI_AGENT: process.env.AI_AGENT || "embarko-setup" },
75
+ });
76
+ if (res.status === 0) say(true, `added "${SKILL_NAME}" to the AI agents found on this machine`);
77
+ else {
78
+ failed++;
79
+ say(false, `could not add the skill. Run it yourself: npx ${skillArgs.join(" ")}`);
80
+ line(dim(indent(lastLines(res.stderr || res.stdout || "", 4))));
81
+ }
82
+ }
83
+
84
+ // 3. MCP
85
+ step("MCP server");
86
+ if (values["skip-mcp"]) say(null, "skipped (--skip-mcp)");
87
+ else {
88
+ const results = installMcp(MCP_URL, { dryRun: dry });
89
+ if (!results.length) say(null, "no MCP-capable AI tool found (looked for Claude Code, Cursor, Codex, OpenCode, Copilot CLI, Factory Droid)");
90
+ for (const r of results) {
91
+ if (r.status === "added") say(true, `${r.tool}: added`);
92
+ else if (r.status === "already") say(true, `${r.tool}: already set up`);
93
+ else if (r.status === "would-add") say(null, `${r.tool}: would add (${r.detail})`);
94
+ else {
95
+ failed++;
96
+ say(false, `${r.tool}: ${r.detail}`);
97
+ }
98
+ }
99
+ say(null, `Claude, ChatGPT and other chat apps: add the connector from ${SITE_URL}/docs/connectors`);
100
+ if (results.some((r) => r.status === "added")) say(null, "Each AI tool asks you to sign in to Embarko the first time it uses it.");
101
+ }
102
+
103
+ // 4. Sign in
104
+ step("Sign in");
105
+ const { token, source } = resolveToken();
106
+ if (token) say(true, `already signed in (token from ${source}). Check with: embarko whoami`);
107
+ else if (values["no-login"]) say(null, "skipped. Sign in any time with: embarko login");
108
+ else if (dry) say(null, "would open the browser to sign in");
109
+ else if (!(values.yes || (await confirm("Sign in to Embarko in your browser now?")))) {
110
+ say(null, "skipped. You can still deploy without an account (a temporary app); sign in any time with: embarko login");
111
+ } else {
112
+ try {
113
+ const result = await browserLogin();
114
+ saveToken(result.accessToken, {
115
+ companyId: result.companyId,
116
+ companyName: result.companyName,
117
+ kind: result.kind,
118
+ tokenId: result.tokenId,
119
+ });
120
+ say(true, `signed in${result.companyName ? ` to ${result.companyName}` : ""}`);
121
+ } catch (err) {
122
+ failed++;
123
+ say(false, `${err.message}`);
124
+ }
125
+ }
126
+
127
+ line();
128
+ if (dry) line("Dry run done. Run without --dry-run to apply.");
129
+ else line(failed ? `Done, with ${failed} problem(s) above.` : `${green("Done.")} Ask your AI agent to "deploy this app to Embarko", or run: embarko deploy`);
130
+ return failed ? 1 : 0;
131
+ }
132
+
133
+ // npx runs packages from its cache (…/_npx/…); a global or linked install
134
+ // lives anywhere else.
135
+ function runningFromNpx() {
136
+ const script = process.argv[1] ?? "";
137
+ if (/[\\/]_npx[\\/]/.test(script)) return true;
138
+ return !onPath("embarko");
139
+ }
140
+
141
+ // Asks on a terminal; an agent or a pipe gets "no", so setup never hangs.
142
+ async function confirm(question) {
143
+ if (!process.stdin.isTTY || !process.stdout.isTTY) return false;
144
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
145
+ try {
146
+ const answer = (await rl.question(` ${question} (Y/n) `)).trim().toLowerCase();
147
+ return answer === "" || answer === "y" || answer === "yes";
148
+ } finally {
149
+ rl.close();
150
+ }
151
+ }
152
+
153
+ function lastLines(text, n) {
154
+ return text.trim().split("\n").slice(-n).join("\n");
155
+ }
156
+
157
+ function indent(text) {
158
+ return text
159
+ .split("\n")
160
+ .map((l) => ` ${l}`)
161
+ .join("\n");
162
+ }
@@ -0,0 +1,36 @@
1
+ import { errorText, request } from "../lib/api.js";
2
+ import { resolveToken } from "../lib/credentials.js";
3
+ import { resolveAppName } from "../lib/pack.js";
4
+ import { kv, line, step } from "../lib/out.js";
5
+
6
+ export const options = {
7
+ json: { type: "boolean" },
8
+ };
9
+
10
+ export const usage = `Usage: embarko status [app] [--json]
11
+
12
+ Where the app stands: building, starting, live, failed, crashed or
13
+ not_deployed. The app defaults to the one in the current folder
14
+ (package.json "name" or the folder name).`;
15
+
16
+ export async function run(values, positionals) {
17
+ const name = positionals[0] ?? resolveAppName(".").name;
18
+ const { token } = resolveToken();
19
+ const { status, data } = await request(`/apps/${encodeURIComponent(name)}/status`, { token });
20
+ if (values.json) {
21
+ console.log(JSON.stringify(data, null, 2));
22
+ return status === 200 ? 0 : 1;
23
+ }
24
+ if (status !== 200) {
25
+ const hint = status === 404 && !token ? "\nIf the app has been kept (claimed), sign in first: embarko login" : "";
26
+ throw new Error(`${errorText(data, `HTTP ${status}`)}${hint}`);
27
+ }
28
+ step(`${name}: ${data.status}`);
29
+ if (data.error) line(` ${data.error}`);
30
+ if (data.links?.app) kv("URL", data.links.app);
31
+ if (data.app && data.app.claimed === false && data.app.expiresAt) {
32
+ line(` Temporary: deleted at ${data.app.expiresAt} unless kept.`);
33
+ }
34
+ if (data.next) kv("Next", data.next);
35
+ return data.status === "failed" || data.status === "crashed" ? 1 : 0;
36
+ }
@@ -0,0 +1,35 @@
1
+ import { readAccount, resolveToken } from "../lib/credentials.js";
2
+ import { step } from "../lib/out.js";
3
+ import { validateToken } from "./login.js";
4
+
5
+ export const options = {
6
+ json: { type: "boolean" },
7
+ };
8
+
9
+ export const usage = `Usage: embarko whoami [--json]
10
+
11
+ Checks the saved token with Embarko and shows which workspace new apps go to.`;
12
+
13
+ export async function run(values) {
14
+ const { token, source } = resolveToken();
15
+ if (!token) {
16
+ if (values.json) console.log(JSON.stringify({ signedIn: false }));
17
+ else step("Not signed in. Run: embarko login");
18
+ return 1;
19
+ }
20
+ const data = await validateToken(token);
21
+ // The workspace name is only known from a browser sign-in.
22
+ const account = source.startsWith("EMBARKO_") || source === "DEPLOY_TOKEN" ? null : readAccount();
23
+ const companyName = account?.companyId === data?.companyId ? account?.companyName : undefined;
24
+ if (values.json) {
25
+ console.log(JSON.stringify({ signedIn: Boolean(data), source, ...data, companyName }, null, 2));
26
+ return data ? 0 : 1;
27
+ }
28
+ if (!data) {
29
+ step(`The token from ${source} isn't valid any more. Run: embarko login`);
30
+ return 1;
31
+ }
32
+ step(`Signed in${companyName ? ` to ${companyName}` : ""} (workspace ${data.companyId}, ${data.kind} token).`);
33
+ step(`Token from ${source}.`);
34
+ return 0;
35
+ }
@@ -0,0 +1,84 @@
1
+ // Registers the Embarko MCP server with the AI tools on this machine. Each one
2
+ // is only touched when its config folder already exists (the tool is
3
+ // installed), and an existing "embarko" entry is left as it is.
4
+ import { spawnSync } from "node:child_process";
5
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
6
+ import os from "node:os";
7
+ import path from "node:path";
8
+
9
+ export const SERVER_NAME = "embarko";
10
+
11
+ const FILE_TARGETS = {
12
+ cursor: { label: "Cursor", file: (h) => path.join(h, ".cursor", "mcp.json") },
13
+ codex: { label: "OpenAI Codex", file: (h) => path.join(h, ".codex", "config.toml") },
14
+ opencode: { label: "OpenCode", file: (h) => path.join(h, ".config", "opencode", "opencode.json") },
15
+ copilot: { label: "GitHub Copilot CLI", file: (h) => path.join(h, ".copilot", "mcp-config.json") },
16
+ "factory-droid": { label: "Factory Droid", file: (h) => path.join(h, ".factory", "mcp.json") },
17
+ };
18
+
19
+ export function onPath(cmd) {
20
+ const res = spawnSync(process.platform === "win32" ? "where" : "which", [cmd], { stdio: "ignore" });
21
+ return res.status === 0;
22
+ }
23
+
24
+ // Same shapes InstaCloud's setup writes, per each tool's docs.
25
+ export function renderJson(slug, existing, url) {
26
+ const root = existing.trim() ? JSON.parse(existing) : {};
27
+ if (typeof root !== "object" || root === null || Array.isArray(root)) throw new Error("the file isn't a JSON object");
28
+ if (slug === "opencode") {
29
+ if (root.mcp?.[SERVER_NAME]) return null;
30
+ root.$schema ??= "https://opencode.ai/config.json";
31
+ root.mcp = { ...(root.mcp ?? {}), [SERVER_NAME]: { type: "remote", url, enabled: true } };
32
+ } else {
33
+ if (root.mcpServers?.[SERVER_NAME]) return null;
34
+ const entry =
35
+ slug === "cursor" ? { url } : slug === "copilot" ? { type: "http", url, tools: ["*"] } : { type: "http", url, disabled: false };
36
+ root.mcpServers = { ...(root.mcpServers ?? {}), [SERVER_NAME]: entry };
37
+ }
38
+ return JSON.stringify(root, null, 2) + "\n";
39
+ }
40
+
41
+ // Appending a whole [mcp_servers.<name>] table is always valid TOML.
42
+ export function renderCodex(existing, url) {
43
+ if (existing.includes(`[mcp_servers.${SERVER_NAME}]`)) return null;
44
+ const base = existing.replace(/\s*$/, "");
45
+ return `${base}${base ? "\n\n" : ""}[mcp_servers.${SERVER_NAME}]\nurl = ${JSON.stringify(url)}\n`;
46
+ }
47
+
48
+ // Returns one { tool, status, detail } per AI tool found.
49
+ export function installMcp(url, { dryRun = false, home = os.homedir(), claudeCode = true } = {}) {
50
+ const results = [];
51
+
52
+ if (claudeCode && onPath("claude")) {
53
+ const has = spawnSync("claude", ["mcp", "get", SERVER_NAME], { stdio: "ignore" }).status === 0;
54
+ if (has) results.push({ tool: "Claude Code", status: "already" });
55
+ else if (dryRun) results.push({ tool: "Claude Code", status: "would-add", detail: `claude mcp add --transport http --scope user ${SERVER_NAME} ${url}` });
56
+ else {
57
+ const res = spawnSync("claude", ["mcp", "add", "--transport", "http", "--scope", "user", SERVER_NAME, url], { encoding: "utf8" });
58
+ results.push(
59
+ res.status === 0
60
+ ? { tool: "Claude Code", status: "added" }
61
+ : { tool: "Claude Code", status: "failed", detail: (res.stderr || res.stdout || "").trim() },
62
+ );
63
+ }
64
+ }
65
+
66
+ for (const [slug, target] of Object.entries(FILE_TARGETS)) {
67
+ const file = target.file(home);
68
+ if (!existsSync(path.dirname(file))) continue;
69
+ try {
70
+ const existing = existsSync(file) ? readFileSync(file, "utf8") : "";
71
+ const next = slug === "codex" ? renderCodex(existing, url) : renderJson(slug, existing, url);
72
+ if (next === null) results.push({ tool: target.label, status: "already", detail: file });
73
+ else if (dryRun) results.push({ tool: target.label, status: "would-add", detail: file });
74
+ else {
75
+ mkdirSync(path.dirname(file), { recursive: true });
76
+ writeFileSync(file, next);
77
+ results.push({ tool: target.label, status: "added", detail: file });
78
+ }
79
+ } catch (err) {
80
+ results.push({ tool: target.label, status: "failed", detail: `${file}: ${err.message} (left unchanged)` });
81
+ }
82
+ }
83
+ return results;
84
+ }
package/src/lib/api.js ADDED
@@ -0,0 +1,66 @@
1
+ // Everything goes to the deploy service; it proxies /api/* to hostnsoft-api.
2
+ export const SHIP_URL = (process.env.EMBARKO_API_URL || "https://ship.embarko.ai").replace(/\/+$/, "");
3
+ export const SITE_URL = (process.env.EMBARKO_SITE_URL || "https://embarko.ai").replace(/\/+$/, "");
4
+ export const MCP_URL = process.env.EMBARKO_MCP_URL || "https://mcp.embarko.ai/mcp";
5
+
6
+ export class ApiError extends Error {
7
+ constructor(message, { status, body } = {}) {
8
+ super(message);
9
+ this.status = status;
10
+ this.body = body;
11
+ this.code = body?.code ?? body?.error;
12
+ }
13
+ }
14
+
15
+ // Claude Code marks its own shells with CLAUDECODE=1; others can set
16
+ // EMBARKO_AGENT_NAME. Shown in the app's deploy history.
17
+ export function agentName(flag) {
18
+ if (flag) return flag;
19
+ if (process.env.EMBARKO_AGENT_NAME) return process.env.EMBARKO_AGENT_NAME;
20
+ if (process.env.CLAUDECODE === "1") return "claude-code";
21
+ return null;
22
+ }
23
+
24
+ export async function request(pathOrUrl, { method = "GET", token, headers = {}, json, body } = {}) {
25
+ const url = /^https?:\/\//.test(pathOrUrl) ? pathOrUrl : `${SHIP_URL}${pathOrUrl}`;
26
+ const h = { Accept: "application/json", ...headers };
27
+ if (token) h.Authorization = `Bearer ${token}`;
28
+ if (json !== undefined) {
29
+ h["Content-Type"] = "application/json";
30
+ body = JSON.stringify(json);
31
+ }
32
+ let res;
33
+ try {
34
+ res = await fetch(url, { method, headers: h, body });
35
+ } catch (err) {
36
+ throw new ApiError(unreachable(url, err));
37
+ }
38
+ const text = await res.text();
39
+ let data;
40
+ try {
41
+ data = text ? JSON.parse(text) : {};
42
+ } catch {
43
+ data = { raw: text };
44
+ }
45
+ return { status: res.status, ok: res.ok, data };
46
+ }
47
+
48
+ // Same advice deploy.sh gives: almost always a sandbox with a domain allowlist.
49
+ function unreachable(url, err) {
50
+ const host = new URL(url).host;
51
+ return [
52
+ `cannot reach ${host} at all (${err?.cause?.code ?? err?.message ?? "connection failed"}).`,
53
+ "This is almost always a network-sandboxed agent environment, not an Embarko problem.",
54
+ "Allow these domains in your agent's network settings: embarko.ai, ship.embarko.ai, *.embarko.app,",
55
+ "or run this from a machine with normal network access.",
56
+ ].join("\n ");
57
+ }
58
+
59
+ export function errorText(data, fallback) {
60
+ const parts = [];
61
+ if (data?.message || data?.error) parts.push(String(data.message ?? data.error));
62
+ if (data?.code && data.code !== data.error) parts.push(`(code: ${data.code})`);
63
+ let text = parts.length ? parts.join(" ") : fallback;
64
+ if (data?.next) text += `\nNext: ${data.next}`;
65
+ return text;
66
+ }
@@ -0,0 +1,66 @@
1
+ import { mkdirSync, readFileSync, rmSync, writeFileSync, chmodSync } from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+
5
+ // The same file the skill's deploy.sh reads (first non-comment line is the
6
+ // token), so signing in here also makes the skill's script deploy as you.
7
+ export function credentialsPath() {
8
+ return process.env.EMBARKO_CREDENTIALS_FILE || path.join(os.homedir(), ".embarko", "credentials");
9
+ }
10
+
11
+ // Workspace name etc. for `whoami`; kept apart so the credentials file stays
12
+ // in the one-token format deploy.sh expects.
13
+ function accountPath() {
14
+ return path.join(path.dirname(credentialsPath()), "account.json");
15
+ }
16
+
17
+ export function readSavedToken() {
18
+ try {
19
+ const line = readFileSync(credentialsPath(), "utf8")
20
+ .split("\n")
21
+ .map((l) => l.trim())
22
+ .find((l) => l && !l.startsWith("#"));
23
+ return line || null;
24
+ } catch {
25
+ return null;
26
+ }
27
+ }
28
+
29
+ // An env token wins over the saved one, as in deploy.sh.
30
+ export function resolveToken() {
31
+ const fromEnv = process.env.EMBARKO_TOKEN || process.env.DEPLOY_TOKEN;
32
+ if (fromEnv) return { token: fromEnv.trim(), source: process.env.EMBARKO_TOKEN ? "EMBARKO_TOKEN" : "DEPLOY_TOKEN" };
33
+ const saved = readSavedToken();
34
+ return saved ? { token: saved, source: credentialsPath() } : { token: null, source: null };
35
+ }
36
+
37
+ export function saveToken(token, account = {}) {
38
+ const file = credentialsPath();
39
+ const dir = path.dirname(file);
40
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
41
+ const label = account.companyName ? ` (workspace: ${account.companyName})` : "";
42
+ writeFileSync(file, `# Embarko deploy token, saved by \`embarko login\`${label}. Keep it secret.\n${token}\n`, { mode: 0o600 });
43
+ chmodSync(file, 0o600);
44
+ writeFileSync(accountPath(), JSON.stringify({ ...account, savedAt: new Date().toISOString() }, null, 2) + "\n", { mode: 0o600 });
45
+ chmodSync(accountPath(), 0o600);
46
+ return file;
47
+ }
48
+
49
+ export function readAccount() {
50
+ try {
51
+ return JSON.parse(readFileSync(accountPath(), "utf8"));
52
+ } catch {
53
+ return null;
54
+ }
55
+ }
56
+
57
+ export function clearToken() {
58
+ let removed = false;
59
+ for (const file of [credentialsPath(), accountPath()]) {
60
+ try {
61
+ rmSync(file);
62
+ removed = true;
63
+ } catch {}
64
+ }
65
+ return removed;
66
+ }
@@ -0,0 +1,21 @@
1
+ import { spawn } from "node:child_process";
2
+
3
+ // Opens a URL in the default browser. Returns false when there is no way to
4
+ // (a headless box, an agent sandbox); the caller prints the URL either way.
5
+ export function openBrowser(url) {
6
+ if (process.env.EMBARKO_NO_BROWSER) return false;
7
+ const [cmd, args] =
8
+ process.platform === "darwin"
9
+ ? ["open", [url]]
10
+ : process.platform === "win32"
11
+ ? ["cmd", ["/c", "start", "", url.replace(/&/g, "^&")]]
12
+ : ["xdg-open", [url]];
13
+ try {
14
+ const child = spawn(cmd, args, { stdio: "ignore", detached: true });
15
+ child.on("error", () => {});
16
+ child.unref();
17
+ return true;
18
+ } catch {
19
+ return false;
20
+ }
21
+ }
package/src/lib/out.js ADDED
@@ -0,0 +1,19 @@
1
+ const color = process.stdout.isTTY && !process.env.NO_COLOR;
2
+ const wrap = (code) => (s) => (color ? `\x1b[${code}m${s}\x1b[0m` : s);
3
+
4
+ export const bold = wrap(1);
5
+ export const dim = wrap(2);
6
+ export const green = wrap(32);
7
+ export const red = wrap(31);
8
+
9
+ export function step(msg) {
10
+ console.log(`${bold("==>")} ${msg}`);
11
+ }
12
+
13
+ export function line(msg = "") {
14
+ console.log(msg);
15
+ }
16
+
17
+ export function kv(label, value) {
18
+ console.log(`${bold(`==> ${label}:`)}\n${value}`);
19
+ }