@vielzeug/codex 1.0.2

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 (50) hide show
  1. package/README.md +142 -0
  2. package/data/.cache.json +33 -0
  3. package/data/llms-full.txt +43590 -0
  4. package/data/llms.txt +117 -0
  5. package/data/vielzeug-data.json +14554 -0
  6. package/dist/__tests__/server.test.js +346 -0
  7. package/dist/__tests__/server.test.js.map +1 -0
  8. package/dist/__tests__/unit.test.js +502 -0
  9. package/dist/__tests__/unit.test.js.map +1 -0
  10. package/dist/_log.js +5 -0
  11. package/dist/_log.js.map +1 -0
  12. package/dist/cli.js +94 -0
  13. package/dist/cli.js.map +1 -0
  14. package/dist/data.js +91 -0
  15. package/dist/data.js.map +1 -0
  16. package/dist/errors.js +26 -0
  17. package/dist/errors.js.map +1 -0
  18. package/dist/frontmatter.js +72 -0
  19. package/dist/frontmatter.js.map +1 -0
  20. package/dist/generator.js +176 -0
  21. package/dist/generator.js.map +1 -0
  22. package/dist/http.js +108 -0
  23. package/dist/http.js.map +1 -0
  24. package/dist/index.js +6 -0
  25. package/dist/index.js.map +1 -0
  26. package/dist/llms.js +162 -0
  27. package/dist/llms.js.map +1 -0
  28. package/dist/port.js +12 -0
  29. package/dist/port.js.map +1 -0
  30. package/dist/resources.js +4 -0
  31. package/dist/resources.js.map +1 -0
  32. package/dist/search.js +125 -0
  33. package/dist/search.js.map +1 -0
  34. package/dist/server.js +13 -0
  35. package/dist/server.js.map +1 -0
  36. package/dist/tools/index.js +62 -0
  37. package/dist/tools/index.js.map +1 -0
  38. package/dist/tools/packages.js +196 -0
  39. package/dist/tools/packages.js.map +1 -0
  40. package/dist/tools/refine.js +329 -0
  41. package/dist/tools/refine.js.map +1 -0
  42. package/dist/tools/schema.js +37 -0
  43. package/dist/tools/schema.js.map +1 -0
  44. package/dist/tools/shared.js +27 -0
  45. package/dist/tools/shared.js.map +1 -0
  46. package/dist/tools.js +1040 -0
  47. package/dist/tools.js.map +1 -0
  48. package/dist/types.js +4 -0
  49. package/dist/types.js.map +1 -0
  50. package/package.json +47 -0
package/dist/data.js ADDED
@@ -0,0 +1,91 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { dirname, resolve } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { CodexError } from './errors.js';
5
+ import { SCHEMA_VERSION } from './types.js';
6
+ const DEFAULT_DATA_FILE = resolve(dirname(fileURLToPath(import.meta.url)), '../data/vielzeug-data.json');
7
+ const REGEN_CMD = 'pnpm --dir packages/codex run prepare:data';
8
+ /** Array-typed BundledPackage fields that every real generated entry always populates. */
9
+ const PACKAGE_ARRAY_FIELDS = ['availableDocPages', 'examples', 'exports', 'keywords', 'related'];
10
+ /** Plain-object-typed BundledPackage fields that every real generated entry always populates. */
11
+ const PACKAGE_OBJECT_FIELDS = ['docs', 'typeSignatures'];
12
+ function isPlainObject(value) {
13
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
14
+ }
15
+ /**
16
+ * `validateBundledData` is public API (see usage.md "load data from a custom snapshot file") and
17
+ * therefore reachable with arbitrary, possibly malformed JSON — not just the package's own
18
+ * generated output. Checking only `slug`/`name` let a structurally-wrong `docs`/`examples`/etc.
19
+ * field pass validation and then throw an unclear `TypeError` deep inside a tool's `run()` instead
20
+ * of a clear `CodexError` here, at load time.
21
+ */
22
+ export function validateBundledData(raw) {
23
+ const r = raw;
24
+ if (typeof raw !== 'object' ||
25
+ raw === null ||
26
+ r['schemaVersion'] !== SCHEMA_VERSION ||
27
+ typeof r['version'] !== 'string' ||
28
+ !Array.isArray(r['packages']) ||
29
+ !Array.isArray(r['refineComponents'])) {
30
+ throw new CodexError(`Bundled data is malformed or uses an outdated schema (expected v${SCHEMA_VERSION}). Regenerate with ${REGEN_CMD}.`);
31
+ }
32
+ for (const entry of r['packages']) {
33
+ const p = entry;
34
+ if (typeof p['slug'] !== 'string' || p['slug'].length === 0 || typeof p['name'] !== 'string') {
35
+ throw new CodexError(`Bundled data has a malformed package entry (missing slug or name). Regenerate with ${REGEN_CMD}.`);
36
+ }
37
+ for (const field of PACKAGE_ARRAY_FIELDS) {
38
+ if (!Array.isArray(p[field])) {
39
+ throw new CodexError(`Bundled data has a malformed package entry ("${p['slug']}"."${field}" must be an array). Regenerate with ${REGEN_CMD}.`);
40
+ }
41
+ }
42
+ for (const field of PACKAGE_OBJECT_FIELDS) {
43
+ if (!isPlainObject(p[field])) {
44
+ throw new CodexError(`Bundled data has a malformed package entry ("${p['slug']}"."${field}" must be an object). Regenerate with ${REGEN_CMD}.`);
45
+ }
46
+ }
47
+ }
48
+ return raw;
49
+ }
50
+ export function loadData(dataFile) {
51
+ const file = dataFile ?? DEFAULT_DATA_FILE;
52
+ let raw;
53
+ try {
54
+ raw = readFileSync(file, 'utf8');
55
+ }
56
+ catch (error) {
57
+ const code = error instanceof Error ? error.code : undefined;
58
+ if (code === 'ENOENT') {
59
+ throw new CodexError(`Bundled MCP data not found at ${file}. In the monorepo run ${REGEN_CMD}; for standalone installs, reinstall @vielzeug/codex to restore packaged data.`, { cause: error });
60
+ }
61
+ const detail = error instanceof Error ? error.message : String(error);
62
+ throw new CodexError(`Failed to read bundled MCP data at ${file}: ${detail}.`, { cause: error });
63
+ }
64
+ let parsed;
65
+ try {
66
+ parsed = JSON.parse(raw);
67
+ }
68
+ catch (error) {
69
+ throw new CodexError(`Bundled MCP data at ${file} is malformed JSON. Regenerate with ${REGEN_CMD}.`, {
70
+ cause: error,
71
+ });
72
+ }
73
+ return validateBundledData(parsed);
74
+ }
75
+ /** Projects a BundledPackage to its lightweight PackageMeta shape (strips heavy content fields). */
76
+ export function packageMeta(pkg) {
77
+ return {
78
+ availableDocPages: pkg.availableDocPages,
79
+ category: pkg.category,
80
+ description: pkg.description,
81
+ exampleIds: pkg.examples.map((e) => e.id),
82
+ exports: pkg.exports,
83
+ hasSource: pkg.apiSource !== null,
84
+ keywords: pkg.keywords,
85
+ name: pkg.name,
86
+ related: pkg.related,
87
+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,EAAE,CAAC;QACzC,OAAO,EAAE,GAAG,CAAC,OAAO;QACpB,SAAS,EAAE,GAAG,CAAC,SAAS,KAAK,IAAI;QACjC,QAAQ,EAAE,GAAG,CAAC,QAAQ;QACtB,IAAI,EAAE,GAAG,CAAC,IAAI;QACd,OAAO,EAAE,GAAG,CAAC,OAAO;QACpB,IAAI,EAAE,GAAG,CAAC,IAAI;QACd,OAAO,EAAE,GAAG,CAAC,OAAO;KACrB,CAAC;AACJ,CAAC"}
package/dist/errors.js ADDED
@@ -0,0 +1,26 @@
1
+ /** Base class for all codex errors. Use `instanceof CodexError` to catch any codex-originated error. */
2
+ export class CodexError extends Error {
3
+ constructor(message, opts) {
4
+ super(message, opts);
5
+ this.name = new.target.name;
6
+ Object.setPrototypeOf(this, new.target.prototype);
7
+ }
8
+ static is(err) {
9
+ return err instanceof CodexError;
10
+ }
11
+ }
12
+ /**
13
+ * Thrown by tool `run()` implementations for any expected failure (bad argument, unknown
14
+ * slug/tag, missing bundled data). `registerTools()` catches this exclusively — via
15
+ * `instanceof CodexError`, not a `ToolError`-specific check — and turns it into a structured
16
+ * `{ code, message }` MCP error result. Anything else that throws is a real bug and is left to
17
+ * propagate as a protocol-level error instead of being silently swallowed.
18
+ */
19
+ export class ToolError extends CodexError {
20
+ code;
21
+ constructor(code, message) {
22
+ super(message);
23
+ this.code = code;
24
+ }
25
+ }
26
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA,wGAAwG;AACxG,MAAM,OAAO,UAAW,SAAQ,KAAK;IACnC,YAAY,OAAe,EAAE,IAAmB;QAC9C,KAAK,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;QACrB,IAAI,CAAC,IAAI,GAAG,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC;QAC5B,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,GAAG,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;IACpD,CAAC;IAED,MAAM,CAAC,EAAE,CAAC,GAAY;QACpB,OAAO,GAAG,YAAY,UAAU,CAAC;IACnC,CAAC;CACF;AASD;;;;;;GAMG;AACH,MAAM,OAAO,SAAU,SAAQ,UAAU;IAC9B,IAAI,CAAgB;IAE7B,YAAY,IAAmB,EAAE,OAAe;QAC9C,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IACnB,CAAC;CACF"}
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Minimal YAML frontmatter parser.
3
+ * Supported formats: inline arrays [a,b,c], block sequences (- item),
4
+ * quoted strings, values containing colons, and CRLF line endings.
5
+ */
6
+ const MAX_FRONTMATTER_INPUT = 102_400; // 100 KB — frontmatter is always tiny; guard against crafted large inputs
7
+ export function parseFrontmatter(markdown) {
8
+ const match = /^---\r?\n([\s\S]*?)\r?\n---/.exec(markdown.slice(0, MAX_FRONTMATTER_INPUT));
9
+ if (!match?.[1])
10
+ return {};
11
+ const lines = match[1].split(/\r?\n/);
12
+ const result = {};
13
+ let i = 0;
14
+ while (i < lines.length) {
15
+ const line = lines[i];
16
+ // Skip empty lines and comments
17
+ if (!line || line.trimStart().startsWith('#')) {
18
+ i++;
19
+ continue;
20
+ }
21
+ const colonIdx = line.indexOf(':');
22
+ if (colonIdx < 1) {
23
+ i++;
24
+ continue;
25
+ }
26
+ const key = line.slice(0, colonIdx).trim();
27
+ if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
28
+ i++;
29
+ continue;
30
+ }
31
+ const rest = line.slice(colonIdx + 1).trim();
32
+ // Inline array: keywords: [mcp, ai-agent, claude]
33
+ if (rest.startsWith('[') && rest.endsWith(']')) {
34
+ result[key] = rest
35
+ .slice(1, -1)
36
+ .split(',')
37
+ .map((s) => s.trim().replace(/^['"`]|['"`]$/g, ''))
38
+ .filter(Boolean);
39
+ i++;
40
+ continue;
41
+ }
42
+ // Empty value → look ahead for block sequence items (- item)
43
+ if (rest === '') {
44
+ i++;
45
+ const items = [];
46
+ while (i < lines.length) {
47
+ const next = lines[i];
48
+ if (!next?.trim())
49
+ break;
50
+ const trimmed = next.trim();
51
+ if (trimmed.startsWith('- ')) {
52
+ items.push(trimmed
53
+ .slice(2)
54
+ .replace(/^['"`]|['"`]$/g, '')
55
+ .trim());
56
+ i++;
57
+ }
58
+ else {
59
+ break;
60
+ }
61
+ }
62
+ if (items.length > 0)
63
+ result[key] = items;
64
+ continue;
65
+ }
66
+ // Regular string — strip surrounding quotes
67
+ result[key] = rest.replace(/^['"`]|['"`]$/g, '');
68
+ i++;
69
+ }
70
+ return result;
71
+ }
72
+ //# sourceMappingURL=frontmatter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"frontmatter.js","sourceRoot":"","sources":["../src/frontmatter.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,MAAM,qBAAqB,GAAG,OAAO,CAAC,CAAC,0EAA0E;AAEjH,MAAM,UAAU,gBAAgB,CAAC,QAAgB;IAC/C,MAAM,KAAK,GAAG,6BAA6B,CAAC,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,EAAE,qBAAqB,CAAC,CAAC,CAAC;IAE3F,IAAI,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC;QAAE,OAAO,EAAE,CAAC;IAE3B,MAAM,KAAK,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IACtC,MAAM,MAAM,GAAsC,EAAE,CAAC;IACrD,IAAI,CAAC,GAAG,CAAC,CAAC;IAEV,OAAO,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC;QACxB,MAAM,IAAI,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;QAEtB,gCAAgC;QAChC,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,SAAS,EAAE,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC;YAC9C,CAAC,EAAE,CAAC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E;oBAAE,MAAM;gBAEzB,MAAM,OAAO,GAAG,IAAI,CAAC,IAAI,EAAE,CAAC;gBAE5B,IAAI,OAAO,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE,CAAC;oBAC7B,KAAK,CAAC,IAAI,CACR,OAAO;yBACJ,KAAK,CAAC,CAAC,CAAC;yBACR,OAAO,CAAC,gBAAgB,EAAE,EAAE,CAAC;yBAC7B,IAAI,EAAE,CACV,CAAC;oBACF,CAAC,EAAE,CAAC;gBACN,CAAC;qBAAM,CAAC;oBACN,MAAM;gBACR,CAAC;YACH,CAAC;YAED,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC;gBAAE,MAAM,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;YAE1C,SAAS;QACX,CAAC;QAED,4CAA4C;QAC5C,MAAM,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,gBAAgB,EAAE,EAAE,CAAC,CAAC;QACjD,CAAC,EAAE,CAAC;IACN,CAAC;IAED,OAAO,MAAM,CAAC;AAChB,CAAC"}
@@ -0,0 +1,176 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { existsSync, readFileSync } from 'node:fs';
3
+ import { dirname, resolve } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ // NOTE: These imports intentionally use .ts extensions (unlike other src/ files).
6
+ // This file is loaded transitively by scripts/generate-bundled-data.ts under Node's
7
+ // --experimental-strip-types, which resolves literal import specifiers — .ts is required
8
+ // to locate the source files at runtime. tsc rewrites these to .js in dist/ via
9
+ // rewriteRelativeImportExtensions in tsconfig.json.
10
+ import { parseFrontmatter } from "./frontmatter.js";
11
+ import { DOC_PAGES, SCHEMA_VERSION, } from "./types.js";
12
+ // Resolves to dist/ in the compiled build, src/ when loaded directly under --experimental-strip-types.
13
+ const __dirname = dirname(fileURLToPath(import.meta.url));
14
+ // ---------------------------------------------------------------------------
15
+ // File helpers
16
+ // ---------------------------------------------------------------------------
17
+ function readJson(filePath) {
18
+ return JSON.parse(readFileSync(filePath, 'utf8'));
19
+ }
20
+ function readTextIfExists(filePath) {
21
+ return filePath && existsSync(filePath) ? readFileSync(filePath, 'utf8') : null;
22
+ }
23
+ function resolveDocsFile(repoRoot, slug, page) {
24
+ const candidates = [
25
+ resolve(repoRoot, `docs/${slug}/${page}.md`),
26
+ ...(page === 'index' ? [resolve(repoRoot, `packages/${slug}/README.md`)] : []),
27
+ ];
28
+ return candidates.find((c) => existsSync(c)) ?? null;
29
+ }
30
+ // ---------------------------------------------------------------------------
31
+ // Sigil CEM declarations
32
+ // ---------------------------------------------------------------------------
33
+ function readSigilDeclarations(repoRoot) {
34
+ const manifestPath = resolve(repoRoot, 'packages/sigil/dist/custom-elements.json');
35
+ if (!existsSync(manifestPath))
36
+ return [];
37
+ const manifest = readJson(manifestPath);
38
+ const modules = Array.isArray(manifest['modules']) ? manifest['modules'] : [];
39
+ return modules.flatMap((mod) => Array.isArray(mod['declarations']) ? mod['declarations'] : []);
40
+ }
41
+ // ---------------------------------------------------------------------------
42
+ // Incremental hashing
43
+ // ---------------------------------------------------------------------------
44
+ function hashPackageFiles(repoRoot, folder, slug) {
45
+ const paths = [
46
+ resolve(repoRoot, folder, 'package.json'),
47
+ resolve(repoRoot, folder, 'src/index.ts'),
48
+ resolve(repoRoot, folder, 'README.md'),
49
+ ...DOC_PAGES.flatMap((page) => {
50
+ const f = resolveDocsFile(repoRoot, slug, page);
51
+ return f ? [f] : [];
52
+ }),
53
+ // Include CEM manifest so a sigil-only component change invalidates the cache
54
+ ...(slug === 'sigil' ? [resolve(repoRoot, 'packages/sigil/dist/custom-elements.json')] : []),
55
+ ];
56
+ const hash = createHash('sha256');
57
+ for (const p of paths) {
58
+ if (existsSync(p)) {
59
+ hash.update(p);
60
+ hash.update(readFileSync(p));
61
+ }
62
+ }
63
+ return hash.digest('hex');
64
+ }
65
+ function toStringArray(value, key) {
66
+ if (Array.isArray(value)) {
67
+ // parseFrontmatter always returns string[], but guard defensively for future callers.
68
+ const nonStrings = value.filter((v) => typeof v !== 'string');
69
+ if (nonStrings.length > 0) {
70
+ process.stderr.write(`codex generator warning: frontmatter field "${key ?? 'unknown'}" contains non-string items (${nonStrings.map(String).join(', ')}) — coercing to string.\n`);
71
+ }
72
+ return value.map(String);
73
+ }
74
+ return value ? [String(value)] : [];
75
+ }
76
+ function processPackage(repoRoot, project, sigilComponents) {
77
+ const slug = project.projectFolder.replace('packages/', '');
78
+ const pkgJson = readJson(resolve(repoRoot, project.projectFolder, 'package.json'));
79
+ const apiSource = readTextIfExists(resolve(repoRoot, project.projectFolder, 'src/index.ts'));
80
+ const indexContent = readTextIfExists(resolveDocsFile(repoRoot, slug, 'index')) ?? '';
81
+ const frontmatter = parseFrontmatter(indexContent);
82
+ const docs = {};
83
+ for (const page of DOC_PAGES) {
84
+ const content = readTextIfExists(resolveDocsFile(repoRoot, slug, page));
85
+ if (typeof content === 'string' && content.length > 0) {
86
+ docs[page] = content;
87
+ }
88
+ }
89
+ const availableDocPages = DOC_PAGES.filter((page) => docs[page] !== undefined);
90
+ return {
91
+ apiSource: typeof apiSource === 'string' && apiSource.length > 0 ? apiSource : null,
92
+ availableDocPages,
93
+ category: typeof frontmatter['category'] === 'string' ? frontmatter['category'] : '',
94
+ components: slug === 'sigil' ? sigilComponents : [],
95
+ description: typeof frontmatter['description'] === 'string' && frontmatter['description'].length > 0
96
+ ? frontmatter['description']
97
+ : typeof pkgJson['description'] === 'string'
98
+ ? pkgJson['description']
99
+ : '',
100
+ docs,
101
+ exports: toStringArray(frontmatter['exports'], 'exports'),
102
+ keywords: toStringArray(frontmatter['keywords'], 'keywords'),
103
+ name: String(project.packageName),
104
+ related: toStringArray(frontmatter['related'], 'related'),
105
+ slug,
106
+ version: typeof pkgJson['version'] === 'string' ? pkgJson['version'] : '0.0.0',
107
+ };
108
+ }
109
+ export function generateBundledData(options = {}) {
110
+ const packageRoot = resolve(__dirname, '..');
111
+ const repoRoot = options.repoRoot ?? resolve(packageRoot, '../..');
112
+ const incremental = options.incremental ?? false;
113
+ const existingDataFile = resolve(packageRoot, 'data/vielzeug-data.json');
114
+ const mcpPackageJson = readJson(resolve(packageRoot, 'package.json'));
115
+ const rushJson = readJson(resolve(repoRoot, 'rush.json'));
116
+ const sigilComponents = readSigilDeclarations(repoRoot);
117
+ // Load incremental cache
118
+ let hashCache = {};
119
+ let existingPackages = new Map();
120
+ if (incremental) {
121
+ const cacheFile = resolve(packageRoot, 'data/.cache.json');
122
+ if (existsSync(existingDataFile) && existsSync(cacheFile)) {
123
+ try {
124
+ hashCache = JSON.parse(readFileSync(cacheFile, 'utf8'));
125
+ const existingRaw = JSON.parse(readFileSync(existingDataFile, 'utf8'));
126
+ if (existingRaw['schemaVersion'] !== SCHEMA_VERSION) {
127
+ process.stderr.write(`codex: schema version mismatch (found ${String(existingRaw['schemaVersion'])}, expected ${SCHEMA_VERSION}) — discarding cache.\n`);
128
+ hashCache = {};
129
+ }
130
+ else {
131
+ const existing = existingRaw;
132
+ existingPackages = new Map(existing.packages.map((p) => [p.slug, p]));
133
+ }
134
+ }
135
+ catch (err) {
136
+ process.stderr.write(`codex: incremental cache read failed, falling back to full regeneration: ${err instanceof Error ? err.message : String(err)}\n`);
137
+ hashCache = {};
138
+ existingPackages = new Map();
139
+ }
140
+ }
141
+ }
142
+ let cacheHits = 0;
143
+ const newHashes = {};
144
+ const packages = rushJson.projects
145
+ .map((project) => {
146
+ const slug = project.projectFolder.replace('packages/', '');
147
+ if (incremental) {
148
+ const currentHash = hashPackageFiles(repoRoot, project.projectFolder, slug);
149
+ newHashes[slug] = currentHash;
150
+ if (hashCache[slug] === currentHash) {
151
+ const cached = existingPackages.get(slug);
152
+ if (cached) {
153
+ cacheHits++;
154
+ // Always refresh sigil components — they come from dist/, not source files
155
+ if (slug === 'sigil')
156
+ return { ...cached, components: sigilComponents };
157
+ return cached;
158
+ }
159
+ }
160
+ }
161
+ return processPackage(repoRoot, project, sigilComponents);
162
+ })
163
+ .sort((a, b) => a.slug.localeCompare(b.slug));
164
+ if (incremental && cacheHits > 0) {
165
+ process.stderr.write(`Incremental: reused ${cacheHits}/${packages.length} packages from cache.\n`);
166
+ }
167
+ return {
168
+ data: {
169
+ packages,
170
+ schemaVersion: SCHEMA_VERSION,
171
+ version: typeof mcpPackageJson['version'] === 'string' ? mcpPackageJson['version'] : '0.0.0',
172
+ },
173
+ ...(incremental && { hashes: newHashes }),
174
+ };
175
+ }
176
+ //# sourceMappingURL=generator.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generator.js","sourceRoot":"","sources":["../src/generator.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACnD,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC7C,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAEzC,kFAAkF;AAClF,oFAAoF;AACpF,yFAAyF;AACzF,gFAAgF;AAChF,oDAAoD;AACpD,OAAO,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AACpD,OAAO,EAIL,SAAS,EAET,cAAc,GACf,MAAM,YAAY,CAAC;AAEpB,uGAAuG;AACvG,MAAM,SAAS,GAAG,OAAO,CAAC,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;AAE1D,8EAA8E;AAC9E,eAAe;AACf,8EAA8E;AAE9E,SAAS,QAAQ,CAAC,QAAgB;IAChC,OAAO,IAAI,CAAC,KAAK,CAAC,YAAY,CAAC,QAAQ,EAAE,MAAM,CAAC,CAA4B,CAAC;AAC/E,CAAC;AAED,SAAS,gBAAgB,CAAC,QAAuB;IAC/C,OAAO,QAAQ,IAAI,UAAU,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,YAAY,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;AAClF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AI,IAAI,KAAK,OAAO;wBAAE,OAAO,EAAE,GAAG,MAAM,EAAE,UAAU,EAAE,eAAe,EAAE,CAAC;oBAExE,OAAO,MAAM,CAAC;gBAChB,CAAC;YACH,CAAC;QACH,CAAC;QAED,OAAO,cAAc,CAAC,QAAQ,EAAE,OAAO,EAAE,eAAe,CAAC,CAAC;IAC5D,CAAC,CAAC;SACD,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC;IAEhD,IAAI,WAAW,IAAI,SAAS,GAAG,CAAC,EAAE,CAAC;QACjC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,uBAAuB,SAAS,IAAI,QAAQ,CAAC,MAAM,yBAAyB,CAAC,CAAC;IACrG,CAAC;IAED,OAAO;QACL,IAAI,EAAE;YACJ,QAAQ;YACR,aAAa,EAAE,cAAc;YAC7B,OAAO,EAAE,OAAO,cAAc,CAAC,SAAS,CAAC,KAAK,QAAQ,CAAC,CAAC,CAAC,cAAc,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,OAAO;SAC7F;QACD,GAAG,CAAC,WAAW,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,CAAC;KAC1C,CAAC;AACJ,CAAC"}
package/dist/http.js ADDED
@@ -0,0 +1,108 @@
1
+ import { SSEServerTransport } from '@modelcontextprotocol/sdk/server/sse.js';
2
+ import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
3
+ import { createServer as createHttpServer } from 'node:http';
4
+ import { log } from './_log.js';
5
+ function setCorsHeaders(res) {
6
+ res.setHeader('access-control-allow-headers', 'content-type, mcp-session-id');
7
+ res.setHeader('access-control-allow-methods', 'GET, POST, DELETE, OPTIONS');
8
+ res.setHeader('access-control-allow-origin', '*');
9
+ }
10
+ function handleError(err, res, req) {
11
+ const message = err instanceof Error ? err.message : String(err);
12
+ if (res.headersSent) {
13
+ const ctx = req ? ` [${req.method} ${req.url}]` : '';
14
+ log(`MCP HTTP error (mid-stream${ctx}): ${message}`);
15
+ if (!res.writableEnded)
16
+ res.end();
17
+ return;
18
+ }
19
+ res.statusCode = 500;
20
+ res.setHeader('content-type', 'application/json; charset=utf-8');
21
+ res.end(JSON.stringify({ error: message }));
22
+ }
23
+ /**
24
+ * Builds the HTTP request handler as a pure function — testable without binding a port.
25
+ * Exported for use in integration tests.
26
+ */
27
+ export function createRequestHandler(streamableTransport, sseSessions, createSseServer, version) {
28
+ return (req, res) => {
29
+ setCorsHeaders(res);
30
+ const url = req.url ?? '/';
31
+ if (req.method === 'OPTIONS') {
32
+ res.statusCode = 204;
33
+ res.end();
34
+ return;
35
+ }
36
+ if (req.method === 'GET' && url === '/health') {
37
+ res.statusCode = 200;
38
+ res.setHeader('content-type', 'application/json; charset=utf-8');
39
+ res.end(JSON.stringify({ status: 'ok', ...(version !== undefined && { version }) }));
40
+ return;
41
+ }
42
+ // Legacy SSE: open a new SSE stream (each connection gets its own Server instance).
43
+ if (req.method === 'GET' && url === '/sse') {
44
+ const transport = new SSEServerTransport('/message', res);
45
+ const sseServer = createSseServer();
46
+ const cleanup = () => {
47
+ sseSessions.delete(transport.sessionId);
48
+ };
49
+ sseSessions.set(transport.sessionId, transport);
50
+ transport.onclose = cleanup;
51
+ void sseServer.connect(transport);
52
+ return;
53
+ }
54
+ // Legacy SSE: receive a client message.
55
+ if (req.method === 'POST' && url.startsWith('/message')) {
56
+ const sessionId = new URL(url, 'http://localhost').searchParams.get('sessionId') ?? '';
57
+ const session = sseSessions.get(sessionId);
58
+ if (!session) {
59
+ res.statusCode = 404;
60
+ res.end(JSON.stringify({ error: 'Session not found' }));
61
+ return;
62
+ }
63
+ void session.handlePostMessage(req, res).catch((err) => handleError(err, res, req));
64
+ return;
65
+ }
66
+ // Streamable HTTP (spec-compliant clients).
67
+ void streamableTransport.handleRequest(req, res).catch((err) => handleError(err, res, req));
68
+ };
69
+ }
70
+ export async function startHttpServer(mcpServer, port, createSseServer, version) {
71
+ // Legacy SSE sessions keyed by sessionId (for older MCP clients like Windsurf).
72
+ const sseSessions = new Map();
73
+ // Streamable HTTP transport (spec-compliant, newer clients).
74
+ const streamableTransport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });
75
+ await mcpServer.connect(streamableTransport);
76
+ const httpServer = createHttpServer(createRequestHandler(streamableTransport, sseSessions, createSseServer, version));
77
+ await new Promise((resolve, reject) => {
78
+ const onError = (err) => reject(err);
79
+ httpServer.once('error', onError);
80
+ httpServer.listen(port, () => {
81
+ httpServer.off('error', onError);
82
+ log(`codex MCP server listening on http://localhost:${port}/`);
83
+ log(` SSE (legacy): GET http://localhost:${port}/sse`);
84
+ log(` Streamable HTTP: POST http://localhost:${port}/`);
85
+ resolve();
86
+ });
87
+ });
88
+ let disposed = false;
89
+ const handle = {
90
+ dispose() {
91
+ if (disposed)
92
+ return Promise.resolve();
93
+ disposed = true;
94
+ return new Promise((resolve) => {
95
+ httpServer.closeAllConnections?.();
96
+ httpServer.close(() => resolve());
97
+ });
98
+ },
99
+ get disposed() {
100
+ return disposed;
101
+ },
102
+ [Symbol.asyncDispose]() {
103
+ return this.dispose();
104
+ },
105
+ };
106
+ return handle;
107
+ }
108
+ //# sourceMappingURL=http.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"http.js","sourceRoot":"","sources":["../src/http.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,kBAAkB,EAAE,MAAM,yCAAyC,CAAC;AAC7E,OAAO,EAAE,6BAA6B,EAAE,MAAM,oDAAoD,CAAC;AACnG,OAAO,EAAE,YAAY,IAAI,gBAAgB,EAAE,MAAM,WAAW,CAAC;AAE7D,OAAO,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AAEhC,SAAS,cAAc,CAAC,GAAmB;IACzC,GAAG,CAAC,SAAS,CAAC,8BAA8B,EAAE,8BAA8B,CAAC,CAAC;IAC9E,GAAG,CAAC,SAA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AO,EAAE,OAAO,CAAC,CAAC;QAClC,UAAU,CAAC,MAAM,CAAC,IAAI,EAAE,GAAG,EAAE;YAC3B,UAAU,CAAC,GAAG,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;YACjC,GAAG,CAAC,kDAAkD,IAAI,GAAG,CAAC,CAAC;YAC/D,GAAG,CAAC,+CAA+C,IAAI,MAAM,CAAC,CAAC;YAC/D,GAAG,CAAC,+CAA+C,IAAI,GAAG,CAAC,CAAC;YAC5D,OAAO,EAAE,CAAC;QACZ,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;IAEH,IAAI,QAAQ,GAAG,KAAK,CAAC;IAErB,MAAM,MAAM,GAAqB;QAC/B,OAAO;YACL,IAAI,QAAQ;gBAAE,OAAO,OAAO,CAAC,OAAO,EAAE,CAAC;YAEvC,QAAQ,GAAG,IAAI,CAAC;YAEhB,OAAO,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,EAAE;gBACnC,UAAU,CAAC,mBAAmB,EAAE,EAAE,CAAC;gBACnC,UAAU,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,OAAO,EAAE,CAAC,CAAC;YACpC,CAAC,CAAC,CAAC;QACL,CAAC;QACD,IAAI,QAAQ;YACV,OAAO,QAAQ,CAAC;QAClB,CAAC;QACD,CAAC,MAAM,CAAC,YAAY,CAAC;YACnB,OAAO,IAAI,CAAC,OAAO,EAAE,CAAC;QACxB,CAAC;KACF,CAAC;IAEF,OAAO,MAAM,CAAC;AAChB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,6 @@
1
+ export { loadData, packageMeta, validateBundledData } from './data.js';
2
+ export { CodexError, ToolError } from './errors.js';
3
+ export { createRequestHandler, startHttpServer } from './http.js';
4
+ export { createServer, createServerFromDisk } from './server.js';
5
+ export { SCHEMA_VERSION, } from './types.js';
6
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAC;AACvE,OAAO,EAAE,UAAU,EAAE,SAAS,EAAsB,MAAM,aAAa,CAAC;AACxE,OAAO,EAAE,oBAAoB,EAAE,eAAe,EAAE,MAAM,WAAW,CAAC;AAGlE,OAAO,EAAE,YAAY,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AACjE,OAAO,EAcL,cAAc,GACf,MAAM,YAAY,CAAC"}