codebase-snapshot 0.12.15 → 0.14.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 (44) hide show
  1. package/CHANGELOG.md +1063 -3
  2. package/README.md +14 -3
  3. package/SECURITY.md +2 -2
  4. package/dist/bin.js +10092 -5998
  5. package/dist/{chunk-FZB2FTHF.js → chunk-2YNQ42B3.js} +7971 -865
  6. package/dist/chunk-7WSZUMT6.js +306 -0
  7. package/dist/cli.cjs +9763 -5718
  8. package/dist/cli.d.cts +115 -2
  9. package/dist/cli.d.ts +115 -2
  10. package/dist/cli.js +389 -8
  11. package/dist/{generate-worker-BK4uJx7Z.d.cts → generate-worker-B79yGkQO.d.cts} +16 -0
  12. package/dist/{generate-worker-BK4uJx7Z.d.ts → generate-worker-B79yGkQO.d.ts} +16 -0
  13. package/dist/index.cjs +7655 -744
  14. package/dist/index.d.cts +145 -6
  15. package/dist/index.d.ts +145 -6
  16. package/dist/index.js +1 -1
  17. package/dist/mcp.cjs +3595 -1093
  18. package/dist/mcp.d.cts +92 -19
  19. package/dist/mcp.d.ts +92 -19
  20. package/dist/mcp.js +2 -2
  21. package/dist/{types-c0tLF2WC.d.cts → types-CbD8yQRZ.d.cts} +145 -1
  22. package/dist/{types-c0tLF2WC.d.ts → types-CbD8yQRZ.d.ts} +145 -1
  23. package/docs/agent.md +1 -1
  24. package/docs/benchmarks.md +80 -0
  25. package/docs/budget.md +59 -0
  26. package/docs/cli.md +41 -4
  27. package/docs/configuration.md +27 -0
  28. package/docs/delta.md +50 -0
  29. package/docs/deploy.md +75 -0
  30. package/docs/health.md +44 -0
  31. package/docs/mcp.md +116 -11
  32. package/docs/migration.md +68 -0
  33. package/docs/output.md +9 -3
  34. package/docs/remote.md +60 -0
  35. package/docs/security-review.md +117 -0
  36. package/docs/serve.md +66 -0
  37. package/docs/signing.md +61 -0
  38. package/docs/slice.md +57 -0
  39. package/docs/tools.md +161 -0
  40. package/docs/troubleshooting.md +63 -0
  41. package/docs/vs-repomix.md +1 -1
  42. package/docs/workspace.md +93 -0
  43. package/package.json +1 -1
  44. package/dist/chunk-EPAXW6QJ.js +0 -3749
@@ -0,0 +1,306 @@
1
+ import { createServer, buildTools, GENERATOR_VERSION } from './chunk-2YNQ42B3.js';
2
+ import * as http from 'http';
3
+ import * as crypto from 'crypto';
4
+
5
+ var DEFAULT_PORT = 4789;
6
+ var DEFAULT_MAX_BODY = 2 * 1024 * 1024;
7
+ var RATE_LIMIT = 60;
8
+ var RATE_WINDOW_MS = 1e4;
9
+ function generateToken() {
10
+ return crypto.randomBytes(24).toString("base64url");
11
+ }
12
+ function isLoopbackOrigin(origin) {
13
+ try {
14
+ const url = new URL(origin);
15
+ if (url.protocol !== "http:" && url.protocol !== "https:") return false;
16
+ const host = url.hostname;
17
+ return host === "localhost" || host === "127.0.0.1" || host === "[::1]" || host === "::1";
18
+ } catch {
19
+ return false;
20
+ }
21
+ }
22
+ function timingSafeEqual2(left, right) {
23
+ const a = Buffer.from(left, "utf8");
24
+ const b = Buffer.from(right, "utf8");
25
+ if (a.length !== b.length) return false;
26
+ return crypto.timingSafeEqual(a, b);
27
+ }
28
+ async function startHttpTransport(options) {
29
+ const host = options.host ?? "127.0.0.1";
30
+ const port = options.port ?? DEFAULT_PORT;
31
+ const log = options.log ?? ((line) => process.stderr.write(line + "\n"));
32
+ const token = options.token === void 0 ? generateToken() : options.token;
33
+ const maxBody = options.maxBodyBytes ?? DEFAULT_MAX_BODY;
34
+ const extraOrigins = options.allowedOrigins ?? [];
35
+ if (token === null && host !== "127.0.0.1" && host !== "localhost" && host !== "::1") {
36
+ throw new Error(
37
+ "Refusing to serve " + host + " without a token: a repository reachable from the network must require Authorization. Drop --no-auth, or bind the loopback address."
38
+ );
39
+ }
40
+ const server = createServer({ cwd: options.cwd, log });
41
+ const toolCount = buildTools().length;
42
+ const sseSessions = /* @__PURE__ */ new Map();
43
+ const tokenAccepted = (request, url) => {
44
+ if (token === null) return true;
45
+ const header = request.headers.authorization ?? "";
46
+ const match = /^Bearer\s+(.+)$/i.exec(header);
47
+ if (match !== null && timingSafeEqual2(match[1].trim(), token)) return true;
48
+ const fromQuery = url.searchParams.get("token");
49
+ return fromQuery !== null && timingSafeEqual2(fromQuery, token);
50
+ };
51
+ const sessions = /* @__PURE__ */ new Map();
52
+ const metrics = {
53
+ requests: 0,
54
+ byMethod: /* @__PURE__ */ new Map(),
55
+ refused: 0,
56
+ rateLimited: 0};
57
+ const noteRequest = (request) => {
58
+ metrics.requests += 1;
59
+ const method = request.method ?? "UNKNOWN";
60
+ metrics.byMethod.set(method, (metrics.byMethod.get(method) ?? 0) + 1);
61
+ };
62
+ const allowedOrigin = (origin) => {
63
+ if (origin === void 0) return null;
64
+ if (isLoopbackOrigin(origin)) return origin;
65
+ return extraOrigins.includes(origin) ? origin : null;
66
+ };
67
+ const httpServer = http.createServer((request, response) => {
68
+ noteRequest(request);
69
+ const send = (status, body, extra = {}) => {
70
+ const text = typeof body === "string" ? body : JSON.stringify(body);
71
+ response.writeHead(status, {
72
+ "content-type": typeof body === "string" ? "text/plain; charset=utf-8" : "application/json",
73
+ "content-length": Buffer.byteLength(text, "utf8"),
74
+ "x-content-type-options": "nosniff",
75
+ ...extra
76
+ });
77
+ response.end(text);
78
+ };
79
+ const origin = typeof request.headers.origin === "string" ? request.headers.origin : void 0;
80
+ const allowed = allowedOrigin(origin);
81
+ if (origin !== void 0 && allowed === null) {
82
+ metrics.refused += 1;
83
+ send(403, { error: "origin not allowed" });
84
+ return;
85
+ }
86
+ const cors = {};
87
+ if (allowed !== null) {
88
+ cors["access-control-allow-origin"] = allowed;
89
+ cors["vary"] = "origin";
90
+ cors["access-control-allow-headers"] = "authorization, content-type, mcp-protocol-version, mcp-session-id";
91
+ cors["access-control-allow-methods"] = "POST, GET, OPTIONS";
92
+ cors["access-control-max-age"] = "600";
93
+ }
94
+ if (request.method === "OPTIONS") {
95
+ send(204, "", cors);
96
+ return;
97
+ }
98
+ if (request.method === "GET" && request.url === "/healthz") {
99
+ send(
100
+ 200,
101
+ {
102
+ ok: true,
103
+ name: "codebase-snapshot",
104
+ version: GENERATOR_VERSION,
105
+ tools: toolCount,
106
+ uptimeSeconds: Math.round(process.uptime())
107
+ },
108
+ cors
109
+ );
110
+ return;
111
+ }
112
+ if (request.method === "GET" && request.url === "/metrics") {
113
+ const lines = [
114
+ "# HELP snapshot_uptime_seconds Seconds since the process started.",
115
+ "# TYPE snapshot_uptime_seconds gauge",
116
+ "snapshot_uptime_seconds " + Math.round(process.uptime()),
117
+ "# HELP snapshot_requests_total HTTP requests received.",
118
+ "# TYPE snapshot_requests_total counter",
119
+ "snapshot_requests_total " + metrics.requests,
120
+ "# HELP snapshot_requests_refused_total Requests refused before dispatch.",
121
+ "# TYPE snapshot_requests_refused_total counter",
122
+ "snapshot_requests_refused_total " + metrics.refused,
123
+ "# HELP snapshot_requests_rate_limited_total Requests rejected by the rate limit.",
124
+ "# TYPE snapshot_requests_rate_limited_total counter",
125
+ "snapshot_requests_rate_limited_total " + metrics.rateLimited,
126
+ "# HELP snapshot_tools Number of tools this server serves.",
127
+ "# TYPE snapshot_tools gauge",
128
+ "snapshot_tools " + toolCount
129
+ ];
130
+ for (const [method, count] of metrics.byMethod) {
131
+ lines.push('snapshot_requests_by_method_total{method="' + method + '"} ' + count);
132
+ }
133
+ send(200, lines.join("\n") + "\n", {
134
+ ...cors,
135
+ "content-type": "text/plain; version=0.0.4; charset=utf-8"
136
+ });
137
+ return;
138
+ }
139
+ const url = new URL(request.url ?? "/", "http://localhost");
140
+ if (request.method === "GET" && url.pathname === "/sse") {
141
+ if (!tokenAccepted(request, url)) {
142
+ send(401, { error: "unauthorized" }, { ...cors, "www-authenticate": 'Bearer realm="codebase-snapshot"' });
143
+ return;
144
+ }
145
+ const id = crypto.randomBytes(12).toString("hex");
146
+ response.writeHead(200, {
147
+ ...cors,
148
+ "content-type": "text/event-stream",
149
+ "cache-control": "no-cache, no-transform",
150
+ connection: "keep-alive",
151
+ "x-accel-buffering": "no"
152
+ });
153
+ const write = (payload) => {
154
+ response.write(payload);
155
+ };
156
+ sseSessions.set(id, { write, end: () => response.end() });
157
+ const heartbeat = setInterval(() => write(": ping\n\n"), 15e3);
158
+ const cleanup = () => {
159
+ clearInterval(heartbeat);
160
+ sseSessions.delete(id);
161
+ };
162
+ request.on("close", cleanup);
163
+ response.on("close", cleanup);
164
+ write("event: endpoint\ndata: /messages?sessionId=" + id + "\n\n");
165
+ return;
166
+ }
167
+ if (request.method === "POST" && url.pathname === "/messages") {
168
+ if (!tokenAccepted(request, url)) {
169
+ send(401, { error: "unauthorized" }, { ...cors, "www-authenticate": 'Bearer realm="codebase-snapshot"' });
170
+ return;
171
+ }
172
+ const id = url.searchParams.get("sessionId") ?? "";
173
+ const stream = sseSessions.get(id);
174
+ if (stream === void 0) {
175
+ send(404, { error: "unknown sessionId; open GET /sse first" });
176
+ return;
177
+ }
178
+ const chunks2 = [];
179
+ let received2 = 0;
180
+ request.on("data", (chunk) => {
181
+ received2 += chunk.length;
182
+ if (received2 > maxBody) {
183
+ request.destroy();
184
+ send(413, { error: "request body too large", limit: maxBody });
185
+ return;
186
+ }
187
+ chunks2.push(chunk);
188
+ });
189
+ request.on("end", () => {
190
+ void (async () => {
191
+ let message;
192
+ try {
193
+ message = JSON.parse(Buffer.concat(chunks2).toString("utf8"));
194
+ } catch (error) {
195
+ send(400, { jsonrpc: "2.0", id: null, error: { code: -32700, message: String(error) } });
196
+ return;
197
+ }
198
+ const answer = await server.handle(message);
199
+ if (answer !== null) stream.write("event: message\ndata: " + JSON.stringify(answer) + "\n\n");
200
+ send(202, "", cors);
201
+ })();
202
+ });
203
+ return;
204
+ }
205
+ if (request.url === "/") {
206
+ send(
207
+ 200,
208
+ "codebase-snapshot MCP server\n\nPOST JSON-RPC 2.0 to /mcp. Health: GET /healthz.\n",
209
+ cors
210
+ );
211
+ return;
212
+ }
213
+ if (request.method !== "POST" || request.url !== "/mcp") {
214
+ send(405, { error: "method not allowed" }, { ...cors, allow: "POST, OPTIONS" });
215
+ return;
216
+ }
217
+ if (token !== null) {
218
+ const header = request.headers.authorization ?? "";
219
+ const match = /^Bearer\s+(.+)$/i.exec(header);
220
+ if (match === null || !timingSafeEqual2(match[1].trim(), token)) {
221
+ send(401, { error: "unauthorized" }, { ...cors, "www-authenticate": 'Bearer realm="codebase-snapshot"' });
222
+ return;
223
+ }
224
+ }
225
+ const remote = request.socket.remoteAddress ?? "unknown";
226
+ const now = Date.now();
227
+ const window = sessions.get(remote);
228
+ if (window === void 0 || window.resetAt <= now) sessions.set(remote, { count: 1, resetAt: now + RATE_WINDOW_MS });
229
+ else if (window.count >= RATE_LIMIT) {
230
+ metrics.rateLimited += 1;
231
+ send(429, { error: "too many requests" }, { ...cors, "retry-after": "10" });
232
+ return;
233
+ } else window.count += 1;
234
+ let received = 0;
235
+ const chunks = [];
236
+ request.on("data", (chunk) => {
237
+ received += chunk.length;
238
+ if (received > maxBody) {
239
+ request.destroy();
240
+ send(413, { error: "request body too large", limit: maxBody }, cors);
241
+ return;
242
+ }
243
+ chunks.push(chunk);
244
+ });
245
+ request.on("end", () => {
246
+ void (async () => {
247
+ let message;
248
+ try {
249
+ message = JSON.parse(Buffer.concat(chunks).toString("utf8"));
250
+ } catch (error) {
251
+ send(400, { jsonrpc: "2.0", id: null, error: { code: -32700, message: "Parse error: " + error.message } }, cors);
252
+ return;
253
+ }
254
+ const answers = [];
255
+ const batch = Array.isArray(message) ? message : [message];
256
+ for (const item of batch) {
257
+ const answer = await server.handle(item);
258
+ if (answer !== null) answers.push(answer);
259
+ }
260
+ if (answers.length === 0) {
261
+ send(202, "", cors);
262
+ return;
263
+ }
264
+ send(200, Array.isArray(message) ? answers : answers[0], cors);
265
+ })().catch((error) => {
266
+ log("mcp/http: " + error.message);
267
+ send(500, { jsonrpc: "2.0", id: null, error: { code: -32603, message: "Internal error" } }, cors);
268
+ });
269
+ });
270
+ request.on("error", () => {
271
+ try {
272
+ response.destroy();
273
+ } catch {
274
+ }
275
+ });
276
+ });
277
+ await new Promise((resolve, reject) => {
278
+ httpServer.once("error", reject);
279
+ httpServer.listen(port, host, () => {
280
+ httpServer.removeListener("error", reject);
281
+ resolve();
282
+ });
283
+ });
284
+ const address = httpServer.address();
285
+ const actualPort = typeof address === "object" && address !== null ? address.port : port;
286
+ const displayHost = host === "0.0.0.0" || host === "::" ? "127.0.0.1" : host;
287
+ return {
288
+ url: "http://" + displayHost + ":" + actualPort + "/mcp",
289
+ port: actualPort,
290
+ host,
291
+ token,
292
+ close: () => new Promise((resolve) => {
293
+ for (const [, session] of sseSessions) {
294
+ try {
295
+ session.end();
296
+ } catch {
297
+ }
298
+ }
299
+ sseSessions.clear();
300
+ httpServer.close(() => resolve());
301
+ httpServer.closeAllConnections();
302
+ })
303
+ };
304
+ }
305
+
306
+ export { generateToken, startHttpTransport };