@mindbricks/genesis-set 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.
Files changed (41) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/LICENSE +202 -0
  3. package/README.md +147 -2
  4. package/bin/genesis-set.mjs +153 -0
  5. package/corpus/README.md +25 -0
  6. package/corpus/genesis/compile-results.md +246 -0
  7. package/corpus/genesis/compiler-api.md +265 -0
  8. package/corpus/genesis/custom-code.md +519 -0
  9. package/corpus/genesis/deploy.md +190 -0
  10. package/corpus/genesis/pitfalls.md +231 -0
  11. package/corpus/genesis/procedures/README.md +17 -0
  12. package/corpus/genesis/procedures/agent-hub-blueprint.md +13 -0
  13. package/corpus/genesis/procedures/auth-blueprint.md +14 -0
  14. package/corpus/genesis/procedures/bff-blueprint.md +16 -0
  15. package/corpus/genesis/procedures/blueprint-authoring.md +16 -0
  16. package/corpus/genesis/procedures/howto-mail-to-tasks.md +26 -0
  17. package/corpus/genesis/procedures/howto-payment-flow.md +112 -0
  18. package/corpus/genesis/procedures/howto-subscription.md +33 -0
  19. package/corpus/genesis/procedures/notifications-blueprint.md +13 -0
  20. package/corpus/genesis/procedures/patterns-catalog.md +12 -0
  21. package/corpus/genesis/procedures/project-lifecycle.md +27 -0
  22. package/corpus/genesis/run-locally.md +310 -0
  23. package/corpus/genesis/testing.md +532 -0
  24. package/lib/config-cli.mjs +179 -0
  25. package/lib/install.mjs +639 -0
  26. package/lib/mcp-config.mjs +220 -0
  27. package/lib/semver.mjs +94 -0
  28. package/mcp/blueprint.mjs +64 -0
  29. package/mcp/client.mjs +141 -0
  30. package/mcp/config.mjs +166 -0
  31. package/mcp/key-page-html.mjs +275 -0
  32. package/mcp/key-page.mjs +217 -0
  33. package/mcp/key-store.mjs +204 -0
  34. package/mcp/key-tools.mjs +225 -0
  35. package/mcp/server.mjs +164 -0
  36. package/mcp/tools.mjs +270 -0
  37. package/package.json +43 -4
  38. package/skills/genesis-compiler-api/SKILL.md +56 -0
  39. package/skills/genesis-deploy/SKILL.md +36 -0
  40. package/skills/genesis-generated-code/SKILL.md +48 -0
  41. package/skills/genesis-run-and-test/SKILL.md +43 -0
@@ -0,0 +1,220 @@
1
+ // Registers the genesis-set MCP server with the installed agents, at user scope
2
+ // (never in a project folder):
3
+ // Claude Code ~/.claude.json mcpServers.genesis = { type: "stdio", command, args, env }
4
+ // Codex $CODEX_HOME/config.toml a managed [mcp_servers.genesis] block (CODEX_HOME = ~/.codex)
5
+ // The server itself is copied to <data>/mcp/ so the registration survives an
6
+ // npm cache or a moved package. Only an entry genesis-set wrote is replaced or
7
+ // removed; a foreign `genesis` entry blocks the registration (Claude Code: unless
8
+ // --force, the old entry is backed up first).
9
+
10
+ import fs from 'node:fs';
11
+ import path from 'node:path';
12
+
13
+ export const MCP_SERVER_NAME = 'genesis';
14
+ const TOML_BEGIN = '# >>> genesis-set: managed block, written by "genesis-set install"; "genesis-set uninstall" removes it';
15
+ const TOML_END = '# <<< genesis-set';
16
+
17
+ export function mcpServerDir(ctx) {
18
+ return path.join(ctx.dataDir, 'mcp');
19
+ }
20
+
21
+ export function mcpServerFile(ctx) {
22
+ return path.join(mcpServerDir(ctx), 'server.mjs');
23
+ }
24
+
25
+ export function claudeConfigFile(ctx) {
26
+ return path.join(ctx.home, '.claude.json');
27
+ }
28
+
29
+ export function codexConfigFile(ctx) {
30
+ const dir = ctx.env.CODEX_HOME ? path.resolve(ctx.env.CODEX_HOME) : path.join(ctx.home, '.codex');
31
+ return path.join(dir, 'config.toml');
32
+ }
33
+
34
+ /** The command an agent runs: this Node, the copied server, and GENESIS_SET_HOME when it is not the default. */
35
+ export function serverLaunch(ctx) {
36
+ const env = {};
37
+ if (ctx.env.GENESIS_SET_HOME) env.GENESIS_SET_HOME = ctx.dataDir;
38
+ return { command: ctx.nodePath ?? process.execPath, args: [mcpServerFile(ctx)], env };
39
+ }
40
+
41
+ /** Copies the package's mcp/ folder to <data>/mcp/ and stamps the version. */
42
+ export function copyServer(ctx) {
43
+ const src = path.join(ctx.pkgRoot, 'mcp');
44
+ const dest = mcpServerDir(ctx);
45
+ fs.rmSync(dest, { recursive: true, force: true });
46
+ fs.mkdirSync(dest, { recursive: true });
47
+ for (const f of fs.readdirSync(src)) {
48
+ if (f.endsWith('.mjs')) fs.copyFileSync(path.join(src, f), path.join(dest, f));
49
+ }
50
+ fs.writeFileSync(path.join(dest, 'version.json'), `${JSON.stringify({ package: 'genesis-set', version: ctx.version }, null, 2)}\n`);
51
+ // An ES module folder outside any package.json: say so, so `node server.mjs` never guesses.
52
+ fs.writeFileSync(path.join(dest, 'package.json'), '{ "type": "module", "private": true }\n');
53
+ }
54
+
55
+ function writeAtomic(file, text) {
56
+ fs.mkdirSync(path.dirname(file), { recursive: true });
57
+ let mode;
58
+ try {
59
+ mode = fs.statSync(file).mode & 0o777;
60
+ } catch {
61
+ mode = 0o600;
62
+ }
63
+ const tmp = `${file}.genesis-set.${process.pid}.tmp`;
64
+ fs.writeFileSync(tmp, text, { mode });
65
+ fs.renameSync(tmp, file);
66
+ }
67
+
68
+ // ── Claude Code ─────────────────────────────────────────────────────
69
+
70
+ function readClaudeJson(file) {
71
+ let text;
72
+ try {
73
+ text = fs.readFileSync(file, 'utf8');
74
+ } catch (e) {
75
+ if (e.code === 'ENOENT') return { data: {} };
76
+ return { error: `cannot read ${file}: ${e.message}` };
77
+ }
78
+ if (!text.trim()) return { data: {} };
79
+ try {
80
+ const data = JSON.parse(text);
81
+ if (!data || typeof data !== 'object' || Array.isArray(data)) return { error: `${file} is not a JSON object` };
82
+ return { data };
83
+ } catch {
84
+ return { error: `${file} is not valid JSON; fix it or register the server by hand ("claude mcp add")` };
85
+ }
86
+ }
87
+
88
+ function isOurClaudeEntry(entry, ctx) {
89
+ return Boolean(entry && Array.isArray(entry.args) && entry.args[0] === mcpServerFile(ctx));
90
+ }
91
+
92
+ /** { status: written | blocked | failed, message } */
93
+ export function registerClaude(ctx, { force = false } = {}) {
94
+ const file = claudeConfigFile(ctx);
95
+ const { data, error } = readClaudeJson(file);
96
+ if (error) return { status: 'failed', message: error };
97
+ const existing = data.mcpServers?.[MCP_SERVER_NAME];
98
+ if (existing && !isOurClaudeEntry(existing, ctx)) {
99
+ if (!force) {
100
+ return {
101
+ status: 'blocked',
102
+ message: `${file} already has an MCP server "${MCP_SERVER_NAME}" that genesis-set did not write (use --force to replace it; the old entry is backed up)`,
103
+ };
104
+ }
105
+ if (!ctx.dryRun) {
106
+ const backup = path.join(ctx.dataDir, 'backup', `claude-mcp-${MCP_SERVER_NAME}-${Date.now()}.json`);
107
+ fs.mkdirSync(path.dirname(backup), { recursive: true });
108
+ fs.writeFileSync(backup, `${JSON.stringify(existing, null, 2)}\n`);
109
+ }
110
+ }
111
+ const { command, args, env } = serverLaunch(ctx);
112
+ if (!ctx.dryRun) {
113
+ data.mcpServers = { ...(data.mcpServers ?? {}), [MCP_SERVER_NAME]: { type: 'stdio', command, args, env } };
114
+ writeAtomic(file, `${JSON.stringify(data, null, 2)}\n`);
115
+ }
116
+ return { status: 'written', message: `register MCP server "${MCP_SERVER_NAME}" for Claude Code in ${file}` };
117
+ }
118
+
119
+ export function unregisterClaude(ctx) {
120
+ const file = claudeConfigFile(ctx);
121
+ const { data, error } = readClaudeJson(file);
122
+ if (error) return { status: 'failed', message: error };
123
+ const existing = data.mcpServers?.[MCP_SERVER_NAME];
124
+ if (!existing) return { status: 'absent', message: `no MCP server "${MCP_SERVER_NAME}" in ${file}` };
125
+ if (!isOurClaudeEntry(existing, ctx)) return { status: 'kept', message: `keep the MCP server "${MCP_SERVER_NAME}" in ${file}: genesis-set did not write it` };
126
+ if (!ctx.dryRun) {
127
+ delete data.mcpServers[MCP_SERVER_NAME];
128
+ writeAtomic(file, `${JSON.stringify(data, null, 2)}\n`);
129
+ }
130
+ return { status: 'removed', message: `remove MCP server "${MCP_SERVER_NAME}" from ${file}` };
131
+ }
132
+
133
+ export function claudeRegistration(ctx) {
134
+ const { data } = readClaudeJson(claudeConfigFile(ctx));
135
+ const entry = data?.mcpServers?.[MCP_SERVER_NAME];
136
+ if (!entry) return 'not registered';
137
+ return isOurClaudeEntry(entry, ctx) ? 'registered' : 'a foreign "genesis" entry';
138
+ }
139
+
140
+ // ── Codex ───────────────────────────────────────────────────────────
141
+
142
+ const tomlString = (s) => JSON.stringify(String(s));
143
+
144
+ function codexBlock(ctx) {
145
+ const { command, args, env } = serverLaunch(ctx);
146
+ const lines = [TOML_BEGIN, `[mcp_servers.${MCP_SERVER_NAME}]`, `command = ${tomlString(command)}`, `args = [${args.map(tomlString).join(', ')}]`];
147
+ const keys = Object.keys(env);
148
+ if (keys.length) {
149
+ lines.push(`[mcp_servers.${MCP_SERVER_NAME}.env]`);
150
+ for (const k of keys) lines.push(`${k} = ${tomlString(env[k])}`);
151
+ }
152
+ lines.push(TOML_END, '');
153
+ return lines.join('\n');
154
+ }
155
+
156
+ /** The text with our managed block removed, and whether there was one. */
157
+ function withoutManagedBlock(text) {
158
+ const start = text.indexOf(TOML_BEGIN);
159
+ if (start < 0) return { text, had: false };
160
+ const endAt = text.indexOf(TOML_END, start);
161
+ if (endAt < 0) return { text, had: false, broken: true };
162
+ let end = endAt + TOML_END.length;
163
+ const nl = text.indexOf('\n', end);
164
+ end = nl < 0 ? text.length : nl + 1;
165
+ return { text: text.slice(0, start) + text.slice(end), had: true };
166
+ }
167
+
168
+ const FOREIGN_TABLE = new RegExp(`^\\s*\\[\\s*mcp_servers\\.(?:${MCP_SERVER_NAME}|"${MCP_SERVER_NAME}")\\s*\\]`, 'm');
169
+
170
+ export function registerCodex(ctx) {
171
+ const file = codexConfigFile(ctx);
172
+ let text = '';
173
+ try {
174
+ text = fs.readFileSync(file, 'utf8');
175
+ } catch (e) {
176
+ if (e.code !== 'ENOENT') return { status: 'failed', message: `cannot read ${file}: ${e.message}` };
177
+ }
178
+ const stripped = withoutManagedBlock(text);
179
+ if (stripped.broken) return { status: 'failed', message: `${file} has a genesis-set block without its end line; fix it by hand` };
180
+ if (FOREIGN_TABLE.test(stripped.text)) {
181
+ return {
182
+ status: 'blocked',
183
+ message: `${file} already defines [mcp_servers.${MCP_SERVER_NAME}] outside the genesis-set block; remove or rename it, then run "genesis-set install" again`,
184
+ };
185
+ }
186
+ if (!ctx.dryRun) {
187
+ const base = stripped.text.length && !stripped.text.endsWith('\n') ? `${stripped.text}\n` : stripped.text;
188
+ writeAtomic(file, `${base}${base.trim() ? '\n' : ''}${codexBlock(ctx)}`);
189
+ }
190
+ return { status: 'written', message: `register MCP server "${MCP_SERVER_NAME}" for Codex in ${file}` };
191
+ }
192
+
193
+ export function unregisterCodex(ctx) {
194
+ const file = codexConfigFile(ctx);
195
+ let text;
196
+ try {
197
+ text = fs.readFileSync(file, 'utf8');
198
+ } catch {
199
+ return { status: 'absent', message: `no ${file}` };
200
+ }
201
+ const stripped = withoutManagedBlock(text);
202
+ if (!stripped.had) return { status: 'absent', message: `no genesis-set block in ${file}` };
203
+ if (!ctx.dryRun) writeAtomic(file, stripped.text.replace(/\n{3,}$/, '\n\n'));
204
+ return { status: 'removed', message: `remove the genesis-set MCP block from ${file}` };
205
+ }
206
+
207
+ export function codexRegistration(ctx) {
208
+ let text;
209
+ try {
210
+ text = fs.readFileSync(codexConfigFile(ctx), 'utf8');
211
+ } catch {
212
+ return 'not registered';
213
+ }
214
+ if (withoutManagedBlock(text).had) return 'registered';
215
+ return FOREIGN_TABLE.test(text) ? 'a foreign "genesis" entry' : 'not registered';
216
+ }
217
+
218
+ export const REGISTER = { claude: registerClaude, codex: registerCodex };
219
+ export const UNREGISTER = { claude: unregisterClaude, codex: unregisterCodex };
220
+ export const REGISTRATION = { claude: claudeRegistration, codex: codexRegistration };
package/lib/semver.mjs ADDED
@@ -0,0 +1,94 @@
1
+ // The small part of semantic versioning genesis-set needs: parse a version and
2
+ // check it against the range in package.json `dependencies["@mindbricks/mind-set"]`.
3
+ // Ranges: an exact version, `^x.y.z`, `~x.y.z`, comparators (`>=0.1.0 <0.3.0`)
4
+ // and `||` alternatives. A pre-release version only matches a range that names
5
+ // the same major.minor.patch with a pre-release.
6
+
7
+ const VERSION = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;
8
+
9
+ export function parseVersion(v) {
10
+ const m = VERSION.exec(String(v ?? '').trim());
11
+ if (!m) return null;
12
+ return { major: +m[1], minor: +m[2], patch: +m[3], pre: m[4] ? m[4].split('.') : [] };
13
+ }
14
+
15
+ export function compareVersions(a, b) {
16
+ const x = typeof a === 'string' ? parseVersion(a) : a;
17
+ const y = typeof b === 'string' ? parseVersion(b) : b;
18
+ for (const k of ['major', 'minor', 'patch']) if (x[k] !== y[k]) return x[k] < y[k] ? -1 : 1;
19
+ if (!x.pre.length && !y.pre.length) return 0;
20
+ if (!x.pre.length) return 1;
21
+ if (!y.pre.length) return -1;
22
+ for (let i = 0; i < Math.max(x.pre.length, y.pre.length); i++) {
23
+ if (x.pre[i] === undefined) return -1;
24
+ if (y.pre[i] === undefined) return 1;
25
+ if (x.pre[i] === y.pre[i]) continue;
26
+ const nx = /^\d+$/.test(x.pre[i]);
27
+ const ny = /^\d+$/.test(y.pre[i]);
28
+ if (nx && ny) return +x.pre[i] < +y.pre[i] ? -1 : 1;
29
+ if (nx) return -1;
30
+ if (ny) return 1;
31
+ return x.pre[i] < y.pre[i] ? -1 : 1;
32
+ }
33
+ return 0;
34
+ }
35
+
36
+ function comparators(part) {
37
+ const p = part.trim();
38
+ if (!p || p === '*' || p === 'x') return [{ op: '>=', v: parseVersion('0.0.0') }];
39
+ const caret = /^\^(.+)$/.exec(p);
40
+ if (caret) {
41
+ const v = parseVersion(caret[1]);
42
+ if (!v) return null;
43
+ const upper =
44
+ v.major > 0
45
+ ? `${v.major + 1}.0.0`
46
+ : v.minor > 0
47
+ ? `0.${v.minor + 1}.0`
48
+ : `0.0.${v.patch + 1}`;
49
+ return [
50
+ { op: '>=', v },
51
+ { op: '<', v: parseVersion(`${upper}-0`) },
52
+ ];
53
+ }
54
+ const tilde = /^~(.+)$/.exec(p);
55
+ if (tilde) {
56
+ const v = parseVersion(tilde[1]);
57
+ if (!v) return null;
58
+ return [
59
+ { op: '>=', v },
60
+ { op: '<', v: parseVersion(`${v.major}.${v.minor + 1}.0-0`) },
61
+ ];
62
+ }
63
+ const out = [];
64
+ for (const tok of p.split(/\s+/)) {
65
+ const m = /^(>=|<=|>|<|=)?(.+)$/.exec(tok);
66
+ const v = m && parseVersion(m[2]);
67
+ if (!v) return null;
68
+ out.push({ op: m[1] || '=', v });
69
+ }
70
+ return out;
71
+ }
72
+
73
+ /** True when `version` satisfies `range`; null when either cannot be read. */
74
+ export function satisfies(version, range) {
75
+ const v = parseVersion(version);
76
+ if (!v) return null;
77
+ const alternatives = String(range ?? '').split('||');
78
+ let readable = false;
79
+ for (const alt of alternatives) {
80
+ const cs = comparators(alt);
81
+ if (!cs) continue;
82
+ readable = true;
83
+ if (v.pre.length && !cs.some((c) => c.v.pre.length && c.v.major === v.major && c.v.minor === v.minor && c.v.patch === v.patch)) {
84
+ // a pre-release only matches a comparator on the same version with a pre-release
85
+ continue;
86
+ }
87
+ const ok = cs.every(({ op, v: w }) => {
88
+ const c = compareVersions(v, w);
89
+ return op === '>=' ? c >= 0 : op === '>' ? c > 0 : op === '<=' ? c <= 0 : op === '<' ? c < 0 : c === 0;
90
+ });
91
+ if (ok) return true;
92
+ }
93
+ return readable ? false : null;
94
+ }
@@ -0,0 +1,64 @@
1
+ // Reads a blueprint (or one service's fragment) from the user's disk for an
2
+ // inline request. The size is checked here, against the server's limit, before
3
+ // anything is sent: the API measures the compact JSON text of the object, so
4
+ // that is what is measured locally too. Only the parsed object leaves this
5
+ // module; the file path is never sent.
6
+
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+
10
+ import { genesisError } from './client.mjs';
11
+
12
+ /** A file this many times the limit is refused before it is read (pretty-printed JSON is larger than compact). */
13
+ const RAW_FACTOR = 8;
14
+
15
+ export class LocalBlueprintError extends Error {
16
+ constructor(code, message, details) {
17
+ super(message);
18
+ this.body = genesisError(code, message, details);
19
+ }
20
+ }
21
+
22
+ /**
23
+ * The JSON object in `file` (absolute, or relative to the folder the MCP
24
+ * server was started in). `kind` is "blueprint" or "fragment".
25
+ * Throws LocalBlueprintError.
26
+ */
27
+ export function readLocalJson(file, { maxBytes, kind = 'blueprint', cwd = process.cwd() }) {
28
+ if (typeof file !== 'string' || !file.trim()) {
29
+ throw new LocalBlueprintError('GENESIS_BAD_ARGUMENTS', `The ${kind} path must be a non-empty string`);
30
+ }
31
+ const abs = path.resolve(cwd, file.trim());
32
+ let st;
33
+ try {
34
+ st = fs.statSync(abs);
35
+ } catch {
36
+ throw new LocalBlueprintError('GENESIS_BLUEPRINT_FILE_NOT_FOUND', `No ${kind} file at ${abs}`, { path: abs });
37
+ }
38
+ if (!st.isFile()) throw new LocalBlueprintError('GENESIS_BLUEPRINT_FILE_NOT_FOUND', `${abs} is not a file`, { path: abs });
39
+ if (st.size > maxBytes * RAW_FACTOR) {
40
+ throw new LocalBlueprintError(
41
+ 'GENESIS_BLUEPRINT_TOO_LARGE',
42
+ `The ${kind} file ${abs} is ${st.size} bytes; the Genesis limit is ${maxBytes} bytes of compact JSON. Nothing was sent.`,
43
+ { path: abs, fileBytes: st.size, limit: maxBytes, checkedLocally: true },
44
+ );
45
+ }
46
+ let value;
47
+ try {
48
+ value = JSON.parse(fs.readFileSync(abs, 'utf8').replace(/^/, ''));
49
+ } catch (e) {
50
+ throw new LocalBlueprintError('GENESIS_BLUEPRINT_FILE_INVALID', `${abs} is not valid JSON: ${e.message}`, { path: abs });
51
+ }
52
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
53
+ throw new LocalBlueprintError('GENESIS_BLUEPRINT_FILE_INVALID', `${abs} must hold one JSON object (the ${kind})`, { path: abs });
54
+ }
55
+ const bytes = Buffer.byteLength(JSON.stringify(value), 'utf8');
56
+ if (bytes > maxBytes) {
57
+ throw new LocalBlueprintError(
58
+ 'GENESIS_BLUEPRINT_TOO_LARGE',
59
+ `The ${kind} is ${bytes} bytes of compact JSON; the Genesis limit is ${maxBytes}. Nothing was sent.`,
60
+ { path: abs, bytes, limit: maxBytes, checkedLocally: true },
61
+ );
62
+ }
63
+ return value;
64
+ }
package/mcp/client.mjs ADDED
@@ -0,0 +1,141 @@
1
+ // The Genesis Compiler API client of the genesis-set MCP server: one HTTPS call
2
+ // per tool call, the API key as a bearer token, and every answer reduced to
3
+ // `{ ok, httpStatus, body }` where a failure body is always in the Genesis error
4
+ // shape `{ error: { code, message, details? } }`. A Genesis error from the
5
+ // server passes through unchanged; a failure that never reached the API (no
6
+ // key, network, a non-JSON answer) is written in the same shape by this client.
7
+
8
+ import { API_PATH, missingKeyMessage } from './config.mjs';
9
+
10
+ /** A Genesis error body. */
11
+ export function genesisError(code, message, details) {
12
+ return { error: { code, message, ...(details === undefined ? {} : { details }) } };
13
+ }
14
+
15
+ export function localFailure(code, message, details) {
16
+ return { ok: false, httpStatus: null, body: genesisError(code, message, details) };
17
+ }
18
+
19
+ const RETRYABLE_NETWORK = new Set(['ECONNRESET', 'ECONNREFUSED', 'EPIPE', 'ETIMEDOUT', 'EAI_AGAIN', 'UND_ERR_SOCKET']);
20
+
21
+ function networkCode(err) {
22
+ return err?.cause?.code ?? err?.code ?? null;
23
+ }
24
+
25
+ function isGenesisErrorBody(v) {
26
+ return Boolean(v && typeof v === 'object' && v.error && typeof v.error === 'object' && typeof v.error.code === 'string');
27
+ }
28
+
29
+ function authHint(status, configFile) {
30
+ if (status === 401) {
31
+ return (
32
+ 'The Genesis API did not accept the API key. Check the key in the Genesis portal and set the right one ' +
33
+ `(GENESIS_API_KEY, or "genesis-set config set-key", which writes ${configFile}).`
34
+ );
35
+ }
36
+ if (status === 403) return 'This key is not allowed to call the Genesis Compiler API (a user API key is needed).';
37
+ return undefined;
38
+ }
39
+
40
+ /**
41
+ * Calls `{apiBase}/genesis/compiler/v1{path}`. `settings` comes from
42
+ * resolveSettings(); `opts`: { method, query, body, headers, signal, retry }.
43
+ * Never throws.
44
+ */
45
+ export async function callGenesis(settings, path, opts = {}) {
46
+ if (!settings.apiKey) return localFailure('GENESIS_API_KEY_MISSING', missingKeyMessage(settings.configFile, settings.apiBase));
47
+ if (!settings.apiBase) {
48
+ return localFailure('GENESIS_BAD_API_BASE', `The Genesis API base is not usable: ${settings.problems.join('; ')}. Nothing was sent.`);
49
+ }
50
+ const url = new URL(`${settings.apiBase}${API_PATH}${path}`);
51
+ for (const [k, v] of Object.entries(opts.query ?? {})) {
52
+ if (v !== undefined && v !== null && v !== '') url.searchParams.set(k, String(v));
53
+ }
54
+ const method = opts.method ?? 'GET';
55
+ const headers = {
56
+ accept: 'application/json',
57
+ authorization: `Bearer ${settings.apiKey}`,
58
+ 'user-agent': settings.userAgent ?? 'genesis-set-mcp',
59
+ ...(opts.body === undefined ? {} : { 'content-type': 'application/json' }),
60
+ ...(opts.headers ?? {}),
61
+ };
62
+ const payload = opts.body === undefined ? undefined : JSON.stringify(opts.body);
63
+ const attempts = opts.retry === false ? 1 : 2;
64
+ let res;
65
+ for (let attempt = 1; attempt <= attempts; attempt++) {
66
+ const signals = [AbortSignal.timeout(settings.timeoutMs)];
67
+ if (opts.signal) signals.push(opts.signal);
68
+ const signal = signals.length === 1 ? signals[0] : anySignal(signals);
69
+ try {
70
+ res = await fetch(url, { method, headers, body: payload, signal, redirect: 'manual' });
71
+ break;
72
+ } catch (err) {
73
+ if (opts.signal?.aborted) return localFailure('GENESIS_CANCELLED', 'The call was cancelled');
74
+ if (err?.name === 'TimeoutError' || err?.name === 'AbortError') {
75
+ return localFailure('GENESIS_TIMEOUT', `The Genesis API did not answer within ${settings.timeoutMs} ms (${url.origin})`);
76
+ }
77
+ const code = networkCode(err);
78
+ if (attempt < attempts && RETRYABLE_NETWORK.has(code)) {
79
+ await new Promise((r) => setTimeout(r, 500));
80
+ continue;
81
+ }
82
+ return localFailure(
83
+ 'GENESIS_UNREACHABLE',
84
+ `The Genesis API at ${settings.apiBase} could not be reached (${code ?? err?.message ?? 'network error'}). ` +
85
+ 'Check the network and the API base; do not report a validation or build that did not happen.',
86
+ { apiBase: settings.apiBase },
87
+ );
88
+ }
89
+ }
90
+ const text = await res.text().catch(() => '');
91
+ let json;
92
+ try {
93
+ json = text ? JSON.parse(text) : undefined;
94
+ } catch {
95
+ json = undefined;
96
+ }
97
+ if (res.status >= 300 && res.status < 400) {
98
+ return {
99
+ ok: false,
100
+ httpStatus: res.status,
101
+ body: genesisError('GENESIS_BAD_RESPONSE', `The API base ${settings.apiBase} answered a redirect; set the final https address as the API base`, {
102
+ location: res.headers.get('location'),
103
+ }),
104
+ };
105
+ }
106
+ if (res.ok) {
107
+ if (json && typeof json === 'object') return { ok: true, httpStatus: res.status, body: json };
108
+ return {
109
+ ok: false,
110
+ httpStatus: res.status,
111
+ body: genesisError('GENESIS_BAD_RESPONSE', `The Genesis API answered ${res.status} without a JSON body`, { snippet: text.slice(0, 200) }),
112
+ };
113
+ }
114
+ if (isGenesisErrorBody(json)) {
115
+ const hint = authHint(res.status, settings.configFile);
116
+ return { ok: false, httpStatus: res.status, body: hint ? { ...json, hint } : json };
117
+ }
118
+ return {
119
+ ok: false,
120
+ httpStatus: res.status,
121
+ body: genesisError(
122
+ 'GENESIS_BAD_RESPONSE',
123
+ `${url.origin} answered ${res.status} without a Genesis error body; check the API base (${settings.apiBase})`,
124
+ { snippet: text.slice(0, 200) },
125
+ ),
126
+ };
127
+ }
128
+
129
+ /** AbortSignal.any for Node 18 / 20.0-20.2, which lack it. */
130
+ function anySignal(signals) {
131
+ if (typeof AbortSignal.any === 'function') return AbortSignal.any(signals);
132
+ const ctl = new AbortController();
133
+ for (const s of signals) {
134
+ if (s.aborted) {
135
+ ctl.abort(s.reason);
136
+ break;
137
+ }
138
+ s.addEventListener('abort', () => ctl.abort(s.reason), { once: true });
139
+ }
140
+ return ctl.signal;
141
+ }
package/mcp/config.mjs ADDED
@@ -0,0 +1,166 @@
1
+ // Where the genesis-set MCP server finds the Genesis API key and the API base.
2
+ //
3
+ // The key comes from the environment (GENESIS_API_KEY) or from the genesis-set
4
+ // config file in the user's home (<data>/config.json, <data> = GENESIS_SET_HOME
5
+ // or ~/.genesis-set). Nothing is ever read from the current folder or a project
6
+ // folder: a key there would end up in a commit.
7
+
8
+ import fs from 'node:fs';
9
+ import os from 'node:os';
10
+ import path from 'node:path';
11
+
12
+ export const API_KEY_ENV = 'GENESIS_API_KEY';
13
+ export const API_BASE_ENV = 'GENESIS_API_BASE';
14
+ export const DEFAULT_API_BASE = 'https://api.genesiscompiler.com';
15
+ /** Every endpoint lives below this path of the API base. */
16
+ export const API_PATH = '/genesis/compiler/v1';
17
+ /** The Genesis portal page where a user creates an API key (shown once). */
18
+ export const PORTAL_KEYS_URL = 'https://portal.genesiscompiler.com/keys';
19
+ const STAGE_API_HOST = 'sapi.genesiscompiler.com';
20
+ const STAGE_PORTAL_KEYS_URL = 'https://stage.genesiscompiler.com/keys';
21
+
22
+ /** The keys page of the portal that belongs to an API base: the stage API has its own portal. */
23
+ export function portalKeysUrl(apiBase) {
24
+ try {
25
+ if (apiBase && new URL(apiBase).hostname === STAGE_API_HOST) return STAGE_PORTAL_KEYS_URL;
26
+ } catch {
27
+ // not a URL: the prod portal
28
+ }
29
+ return PORTAL_KEYS_URL;
30
+ }
31
+ export const CONFIG_FILE = 'config.json';
32
+ /** The server's default inline-blueprint limit (bytes of the compact JSON text). */
33
+ export const DEFAULT_MAX_BLUEPRINT_BYTES = 10 * 1024 * 1024;
34
+ export const DEFAULT_TIMEOUT_MS = 120_000;
35
+
36
+ /** The genesis-set data folder: GENESIS_SET_HOME, else ~/.genesis-set. */
37
+ export function dataDirOf(env = process.env) {
38
+ if (env.GENESIS_SET_HOME) return path.resolve(env.GENESIS_SET_HOME);
39
+ const home = env.HOME || env.USERPROFILE || os.homedir();
40
+ return path.join(home, '.genesis-set');
41
+ }
42
+
43
+ export function configPathOf(env = process.env) {
44
+ return path.join(dataDirOf(env), CONFIG_FILE);
45
+ }
46
+
47
+ /** The config file as an object; `{}` when it is absent, `{ __error }` when it cannot be read. */
48
+ export function readConfigFile(file) {
49
+ let text;
50
+ try {
51
+ text = fs.readFileSync(file, 'utf8');
52
+ } catch (e) {
53
+ return e && e.code === 'ENOENT' ? {} : { __error: `cannot read ${file}: ${e.message}` };
54
+ }
55
+ try {
56
+ const v = JSON.parse(text);
57
+ return v && typeof v === 'object' && !Array.isArray(v) ? v : { __error: `${file} is not a JSON object` };
58
+ } catch {
59
+ return { __error: `${file} is not valid JSON` };
60
+ }
61
+ }
62
+
63
+ /** Writes the config file with owner-only permissions (0600), creating the folder (0700). */
64
+ export function writeConfigFile(file, config) {
65
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
66
+ const tmp = `${file}.${process.pid}.tmp`;
67
+ fs.writeFileSync(tmp, `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 });
68
+ fs.renameSync(tmp, file);
69
+ try {
70
+ fs.chmodSync(file, 0o600);
71
+ } catch {
72
+ // Windows: no POSIX modes
73
+ }
74
+ }
75
+
76
+ function isLoopback(hostname) {
77
+ const h = hostname.replace(/^\[|\]$/g, '').toLowerCase();
78
+ return h === 'localhost' || h === '::1' || h.endsWith('.localhost') || /^127\.\d+\.\d+\.\d+$/.test(h);
79
+ }
80
+
81
+ /**
82
+ * The API base as a URL string without a trailing slash and without the API
83
+ * path. A plain-http base is allowed only on a loopback address, so the key is
84
+ * never sent in clear text over a network. Throws on a bad value.
85
+ */
86
+ export function normalizeApiBase(raw) {
87
+ let u;
88
+ try {
89
+ u = new URL(String(raw).trim());
90
+ } catch {
91
+ throw new Error(`"${raw}" is not a URL`);
92
+ }
93
+ if (u.protocol !== 'https:' && u.protocol !== 'http:') throw new Error(`"${raw}" is not an http(s) URL`);
94
+ if (u.protocol === 'http:' && !isLoopback(u.hostname)) {
95
+ throw new Error(`"${raw}" uses plain http on a non-local host; use https`);
96
+ }
97
+ if (u.search || u.hash) throw new Error(`"${raw}" must not carry a query or a fragment`);
98
+ let p = u.pathname.replace(/\/+$/, '');
99
+ if (p.endsWith(API_PATH)) p = p.slice(0, -API_PATH.length);
100
+ return `${u.origin}${p}`;
101
+ }
102
+
103
+ function positiveInt(raw, fallback) {
104
+ const n = raw === undefined || raw === null || raw === '' ? Number.NaN : Number(raw);
105
+ return Number.isInteger(n) && n > 0 ? n : fallback;
106
+ }
107
+
108
+ /**
109
+ * Everything a call needs, resolved from the environment and the config file:
110
+ * `{ apiKey, keySource, apiBase, baseSource, configFile, maxBlueprintBytes,
111
+ * timeoutMs, problems }`. `apiKey` is null when no key is set, `apiBase` null
112
+ * when the configured base is not usable; `problems` lists what could not be
113
+ * used (a broken config file, a bad base URL).
114
+ */
115
+ export function resolveSettings(env = process.env) {
116
+ const configFile = configPathOf(env);
117
+ const cfg = readConfigFile(configFile);
118
+ const problems = [];
119
+ if (cfg.__error) problems.push(cfg.__error);
120
+ let apiKey = null;
121
+ let keySource = null;
122
+ const envKey = typeof env[API_KEY_ENV] === 'string' ? env[API_KEY_ENV].trim() : '';
123
+ if (envKey) {
124
+ apiKey = envKey;
125
+ keySource = API_KEY_ENV;
126
+ } else if (typeof cfg.apiKey === 'string' && cfg.apiKey.trim()) {
127
+ apiKey = cfg.apiKey.trim();
128
+ keySource = configFile;
129
+ }
130
+ let apiBase = DEFAULT_API_BASE;
131
+ let baseSource = 'default';
132
+ const rawBase = env[API_BASE_ENV] ? env[API_BASE_ENV] : typeof cfg.apiBase === 'string' && cfg.apiBase ? cfg.apiBase : null;
133
+ if (rawBase) {
134
+ try {
135
+ apiBase = normalizeApiBase(rawBase);
136
+ baseSource = env[API_BASE_ENV] ? API_BASE_ENV : configFile;
137
+ } catch (e) {
138
+ // Never fall back to another host: the key would go somewhere the user did not pick.
139
+ apiBase = null;
140
+ baseSource = env[API_BASE_ENV] ? API_BASE_ENV : configFile;
141
+ problems.push(`API base ${e.message} (set in ${baseSource})`);
142
+ }
143
+ }
144
+ return {
145
+ apiKey,
146
+ keySource,
147
+ apiBase,
148
+ baseSource,
149
+ configFile,
150
+ maxBlueprintBytes: positiveInt(env.GENESIS_MAX_BLUEPRINT_BYTES ?? cfg.maxBlueprintBytes, DEFAULT_MAX_BLUEPRINT_BYTES),
151
+ timeoutMs: positiveInt(env.GENESIS_TIMEOUT_MS ?? cfg.timeoutMs, DEFAULT_TIMEOUT_MS),
152
+ problems,
153
+ };
154
+ }
155
+
156
+ /** The one message for a missing key: where to create it, how to set it, and where never to put it. */
157
+ export function missingKeyMessage(configFile, apiBase) {
158
+ return (
159
+ `No Genesis API key is set. The user creates one on the Genesis portal (${portalKeysUrl(apiBase)}; ` +
160
+ 'it is shown once) and sets it in the environment the agent starts from ' +
161
+ `(export ${API_KEY_ENV}=<your key>), or store it once with "genesis-set config set-key" ` +
162
+ `(it reads the key from stdin and writes ${configFile}, readable only by you). ` +
163
+ 'Never put the key in the project folder, the blueprint, a commit or the chat. ' +
164
+ 'The config file is read on every call; a new environment variable needs an agent restart.'
165
+ );
166
+ }