codebase-snapshot 0.12.14 → 0.13.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 +950 -3
  2. package/README.md +15 -3
  3. package/SECURITY.md +2 -2
  4. package/dist/bin.js +9848 -5460
  5. package/dist/{chunk-UQHIG2KN.js → chunk-BOJYZQFB.js} +7651 -747
  6. package/dist/chunk-NESEHOPU.js +266 -0
  7. package/dist/cli.cjs +9954 -5619
  8. package/dist/cli.d.cts +120 -2
  9. package/dist/cli.d.ts +120 -2
  10. package/dist/cli.js +422 -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 +7389 -680
  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 +3830 -1057
  18. package/dist/mcp.d.cts +86 -4
  19. package/dist/mcp.d.ts +86 -4
  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 +56 -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 +75 -0
  31. package/docs/mcp.md +112 -10
  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-6EGIFYWK.js +0 -3248
@@ -1,3248 +0,0 @@
1
- import { GENERATOR_VERSION, anchorForPath, displayPath, MIN_MAX_PART_BYTES, SCHEMA_VERSION, GENERATOR_NAME, ARTIFACT_NAMES, PRESETS, generateInWorker, validateSnapshot, buildImportResolver, resolveSpecifier, truncateToBytes, explainPath, renderExplainText, describeManifestShapeProblem, loadConfigFileDetailed, parseByteSize, resolveConfig } from './chunk-UQHIG2KN.js';
2
- import * as fs from 'fs';
3
- import * as path from 'path';
4
-
5
- // src/mcp/protocol.ts
6
- var LEGACY_PROTOCOL_VERSIONS = ["2025-11-25", "2025-06-18"];
7
- var MODERN_PROTOCOL_VERSIONS = ["2026-07-28"];
8
- var SUPPORTED_PROTOCOL_VERSIONS = [
9
- ...MODERN_PROTOCOL_VERSIONS,
10
- ...LEGACY_PROTOCOL_VERSIONS
11
- ];
12
- var DEFAULT_LEGACY_PROTOCOL_VERSION = LEGACY_PROTOCOL_VERSIONS[0];
13
- var ERROR_CODES = {
14
- parseError: -32700,
15
- invalidRequest: -32600,
16
- methodNotFound: -32601,
17
- invalidParams: -32602,
18
- internalError: -32603,
19
- /**
20
- * A resource whose complete text is larger than one read may return.
21
- *
22
- * `-32000` is JSON-RPC's range for implementation-defined server errors, which is what this is:
23
- * there is no standard code for "the document is too large", and answering with -32602 would tell
24
- * a client its request was malformed when it was not. The message names the size, the limit and
25
- * the tool to use instead, because a resource read that cannot return the whole resource must not
26
- * invent a partial one.
27
- */
28
- resourceTooLarge: -32e3,
29
- /**
30
- * A known resource that this snapshot does not contain.
31
- *
32
- * `-32002` is the MCP code for "resource not found". Answering `-32602` ("Unknown resource")
33
- * for `snapshot://prompt` in a snapshot generated with `--skip-artifacts prompt` told the
34
- * client its URI was wrong when the artifact had simply been left out.
35
- */
36
- resourceNotFound: -32002,
37
- /**
38
- * The server is at its concurrency limit.
39
- *
40
- * Implementation-defined range, like `resourceTooLarge`. A typed error rather than silent
41
- * queueing or a dropped request: the caller can retry, and knows why.
42
- */
43
- overloaded: -32001,
44
- unsupportedProtocolVersion: -32022
45
- };
46
- var METHOD = {
47
- initialize: "initialize",
48
- initialized: "notifications/initialized",
49
- discover: "server/discover",
50
- ping: "ping",
51
- toolsList: "tools/list",
52
- toolsCall: "tools/call",
53
- resourcesList: "resources/list",
54
- resourcesRead: "resources/read",
55
- resourceTemplatesList: "resources/templates/list",
56
- promptsList: "prompts/list",
57
- promptsGet: "prompts/get",
58
- cancelled: "notifications/cancelled"
59
- };
60
- var META_KEYS = {
61
- protocolVersion: "io.modelcontextprotocol/protocolVersion",
62
- clientCapabilities: "io.modelcontextprotocol/clientCapabilities",
63
- clientInfo: "io.modelcontextprotocol/clientInfo",
64
- serverInfo: "io.modelcontextprotocol/serverInfo"};
65
- function isJsonObject(value) {
66
- return typeof value === "object" && value !== null && !Array.isArray(value);
67
- }
68
- function serverInfoMeta(info) {
69
- const value = { name: info.name, version: info.version };
70
- if (info.title) value.title = info.title;
71
- return { [META_KEYS.serverInfo]: value };
72
- }
73
- function successResponse(id, result, modern, info) {
74
- if (!modern) return { jsonrpc: "2.0", id, result };
75
- const withMeta = {
76
- ...result,
77
- resultType: "complete",
78
- _meta: { ...isJsonObject(result._meta) ? result._meta : {}, ...serverInfoMeta(info) }
79
- };
80
- return { jsonrpc: "2.0", id, result: withMeta };
81
- }
82
- function errorResponse(id, code, message, data) {
83
- const error = { code, message };
84
- if (data !== void 0) error.data = data;
85
- return { jsonrpc: "2.0", id, error };
86
- }
87
-
88
- // src/mcp/era.ts
89
- function createSession() {
90
- return { era: null, protocolVersion: null, ready: false };
91
- }
92
- function isLegacyVersion(version) {
93
- return LEGACY_PROTOCOL_VERSIONS.includes(version);
94
- }
95
- function isModernVersion(version) {
96
- return MODERN_PROTOCOL_VERSIONS.includes(version);
97
- }
98
- function inspectModernMeta(params) {
99
- const raw = params?._meta;
100
- if (!isJsonObject(raw)) return { kind: "absent" };
101
- const version = raw[META_KEYS.protocolVersion];
102
- if (typeof version !== "string" || version.length === 0) {
103
- return { kind: "incomplete", missing: META_KEYS.protocolVersion };
104
- }
105
- const capabilities2 = raw[META_KEYS.clientCapabilities];
106
- if (!isJsonObject(capabilities2)) {
107
- return { kind: "incomplete", missing: META_KEYS.clientCapabilities };
108
- }
109
- const info = raw[META_KEYS.clientInfo];
110
- return {
111
- kind: "present",
112
- meta: {
113
- version,
114
- clientCapabilities: capabilities2,
115
- clientInfo: isJsonObject(info) ? info : null
116
- }
117
- };
118
- }
119
- function unsupportedVersionData(requested) {
120
- return { requested, supported: [...SUPPORTED_PROTOCOL_VERSIONS] };
121
- }
122
- function classifyRequest(method, params, session) {
123
- const inspection = inspectModernMeta(params);
124
- if (session.era === "modern") {
125
- if (inspection.kind === "absent") {
126
- return {
127
- kind: "error",
128
- code: ERROR_CODES.invalidRequest,
129
- message: `This request has no _meta. The modern era requires "${META_KEYS.protocolVersion}" and "${META_KEYS.clientCapabilities}" on every request.`
130
- };
131
- }
132
- if (inspection.kind === "incomplete") {
133
- return {
134
- kind: "error",
135
- code: ERROR_CODES.invalidParams,
136
- message: `The request _meta is missing the required key "${inspection.missing}".`
137
- };
138
- }
139
- if (!isModernVersion(inspection.meta.version)) {
140
- return {
141
- kind: "error",
142
- code: ERROR_CODES.unsupportedProtocolVersion,
143
- message: `Unsupported protocol version "${inspection.meta.version}".`,
144
- data: unsupportedVersionData(inspection.meta.version)
145
- };
146
- }
147
- return { kind: "era", era: "modern", version: inspection.meta.version };
148
- }
149
- if (session.era === "legacy") {
150
- return { kind: "era", era: "legacy", version: session.protocolVersion };
151
- }
152
- if (method === METHOD.initialize) {
153
- return { kind: "era", era: "legacy", version: null };
154
- }
155
- if (inspection.kind === "present") {
156
- if (!isModernVersion(inspection.meta.version)) {
157
- return {
158
- kind: "error",
159
- code: ERROR_CODES.unsupportedProtocolVersion,
160
- message: `Unsupported protocol version "${inspection.meta.version}".`,
161
- data: unsupportedVersionData(inspection.meta.version)
162
- };
163
- }
164
- return { kind: "era", era: "modern", version: inspection.meta.version };
165
- }
166
- if (inspection.kind === "incomplete") {
167
- return {
168
- kind: "error",
169
- code: ERROR_CODES.invalidParams,
170
- message: `The request _meta is missing the required key "${inspection.missing}".`
171
- };
172
- }
173
- if (method === METHOD.discover) {
174
- return { kind: "era", era: "modern", version: MODERN_PROTOCOL_VERSIONS[0] };
175
- }
176
- return { kind: "era", era: "legacy", version: null };
177
- }
178
- function negotiateLegacyVersion(requested) {
179
- if (typeof requested === "string" && isLegacyVersion(requested)) {
180
- return { version: requested, matched: true };
181
- }
182
- return { version: DEFAULT_LEGACY_PROTOCOL_VERSION, matched: false };
183
- }
184
-
185
- // src/mcp/part.ts
186
- var FILE_HEADING = "### FILE: ";
187
- var CONTENT_MARKERS = /* @__PURE__ */ new Set(["#### Content", "#### Bounded Preview"]);
188
- var ANCHOR_LINE = /^<a id="([^"]+)"><\/a>$/;
189
- var META_PREFIX = "- Meta: ";
190
- var LEGACY_INCLUSION_PREFIX = "- Inclusion: ";
191
- var LEGACY_INCLUDED_LINES_PREFIX = "- Included Lines: ";
192
- var INCLUSION_MODES = /* @__PURE__ */ new Set(["full", "preview", "signatures"]);
193
- var COMPACT_COUNTS = /^(\d+)\s+lines?(?:\s+of\s+\d+\s+lines?)?/;
194
- function readIncludedLines(fields) {
195
- const last = fields[fields.length - 1];
196
- if (last === void 0) return null;
197
- const counts = COMPACT_COUNTS.exec(last.trim());
198
- return counts === null ? null : Number(counts[1]);
199
- }
200
- function parsePartSections(partText) {
201
- const lines = partText.split("\n");
202
- const sections = [];
203
- let index = 0;
204
- while (index < lines.length) {
205
- if (!lines[index].startsWith(FILE_HEADING)) {
206
- index += 1;
207
- continue;
208
- }
209
- const heading = lines[index].slice(FILE_HEADING.length);
210
- const anchorMatch = index > 0 ? ANCHOR_LINE.exec(lines[index - 1]) : null;
211
- let cursor = index + 1;
212
- let inclusion = null;
213
- let includedLines = null;
214
- while (cursor < lines.length && !CONTENT_MARKERS.has(lines[cursor])) {
215
- const line = lines[cursor];
216
- if (line.startsWith(FILE_HEADING)) break;
217
- if (line.startsWith(META_PREFIX)) {
218
- const fields = line.slice(META_PREFIX.length).split("|");
219
- for (const field of fields) {
220
- const value = field.trim();
221
- if (INCLUSION_MODES.has(value)) inclusion = value;
222
- }
223
- includedLines = readIncludedLines(fields);
224
- } else if (line.startsWith(LEGACY_INCLUSION_PREFIX)) {
225
- inclusion = line.slice(LEGACY_INCLUSION_PREFIX.length).trim();
226
- } else if (line.startsWith(LEGACY_INCLUDED_LINES_PREFIX)) {
227
- const value = Number(line.slice(LEGACY_INCLUDED_LINES_PREFIX.length).trim());
228
- includedLines = Number.isFinite(value) ? value : null;
229
- }
230
- cursor += 1;
231
- }
232
- if (cursor >= lines.length || !CONTENT_MARKERS.has(lines[cursor])) {
233
- index = cursor + 1;
234
- continue;
235
- }
236
- let fenceLine = cursor + 1;
237
- while (fenceLine < lines.length && lines[fenceLine].trim().length === 0) fenceLine += 1;
238
- const fenceMatch = /^(`{4,})/.exec(lines[fenceLine] ?? "");
239
- if (!fenceMatch) {
240
- index = cursor + 1;
241
- continue;
242
- }
243
- const fence = fenceMatch[1];
244
- const body = [];
245
- let bodyLine = fenceLine + 1;
246
- while (bodyLine < lines.length && lines[bodyLine] !== fence) {
247
- body.push(lines[bodyLine]);
248
- bodyLine += 1;
249
- }
250
- sections.push({ path: heading, anchor: anchorMatch?.[1] ?? null, body: body.join("\n"), inclusion, includedLines });
251
- index = bodyLine + 1;
252
- }
253
- return sections;
254
- }
255
- function findSection(sections, relativePath) {
256
- const anchor = anchorForPath(relativePath);
257
- const byAnchor = sections.find((section) => section.anchor === anchor);
258
- if (byAnchor) return byAnchor;
259
- const rendered = displayPath(relativePath);
260
- const samePath = (section) => section.path === relativePath || section.path === rendered;
261
- const exact = sections.find(samePath);
262
- if (exact) return exact;
263
- const foldedPath = rendered.toLowerCase();
264
- const folded = sections.filter((section) => {
265
- const path4 = section.path.toLowerCase();
266
- return path4 === relativePath.toLowerCase() || path4 === foldedPath;
267
- });
268
- return folded.length === 1 ? folded[0] : null;
269
- }
270
- function windowText(body, fromLine, lineCount) {
271
- const lines = body.split("\n");
272
- const total = body.length === 0 ? 0 : lines.length;
273
- const requested = Math.max(1, Math.trunc(fromLine));
274
- const pastEnd = total > 0 && requested > total;
275
- const start = pastEnd ? requested : Math.min(requested, Math.max(1, total));
276
- const end = Math.min(total, start + Math.max(1, Math.trunc(lineCount)) - 1);
277
- const slice = pastEnd ? [] : lines.slice(start - 1, Math.max(start - 1, end));
278
- return {
279
- text: slice.join("\n"),
280
- fromLine: start,
281
- returnedLines: slice.length,
282
- totalLines: total,
283
- truncated: !pastEnd && end < total,
284
- nextFromLine: !pastEnd && end < total ? end + 1 : null,
285
- pastEnd
286
- };
287
- }
288
- function foldForComparison(value) {
289
- return process.platform === "win32" || process.platform === "darwin" ? value.toLowerCase() : value;
290
- }
291
- function canonicalPath(value) {
292
- const absolute = path.resolve(value);
293
- try {
294
- return fs.realpathSync(absolute);
295
- } catch {
296
- return absolute;
297
- }
298
- }
299
- function isInside(parent, child) {
300
- const foldedParent = foldForComparison(parent);
301
- const foldedChild = foldForComparison(child);
302
- return foldedChild === foldedParent || foldedChild.startsWith(`${foldedParent}${path.sep}`);
303
- }
304
- function resolveThroughExistingAncestor(target) {
305
- let existing = target;
306
- const missing = [];
307
- while (!fs.existsSync(existing)) {
308
- missing.unshift(path.basename(existing));
309
- const parent = path.dirname(existing);
310
- if (parent === existing) break;
311
- existing = parent;
312
- }
313
- const resolved = canonicalPath(existing);
314
- return missing.length === 0 ? resolved : path.join(resolved, ...missing);
315
- }
316
- function resolveRoot(requested, context) {
317
- if (requested !== void 0 && (typeof requested !== "string" || requested.trim().length === 0)) {
318
- return { ok: false, message: '"root" must be a non-empty string when provided.' };
319
- }
320
- const wanted = typeof requested === "string" ? requested.trim() : context.cwd;
321
- const absolute = path.resolve(context.cwd, wanted);
322
- let stats;
323
- try {
324
- stats = fs.statSync(absolute);
325
- } catch {
326
- return { ok: false, message: `"${wanted}" does not exist, so it cannot be a repository root.` };
327
- }
328
- if (!stats.isDirectory()) {
329
- return { ok: false, message: `"${wanted}" is not a directory.` };
330
- }
331
- const resolved = canonicalPath(absolute);
332
- for (const allowed of context.roots) {
333
- if (isInside(canonicalPath(allowed), resolved)) return { ok: true, root: resolved };
334
- }
335
- const shown = context.roots.join(", ");
336
- return {
337
- ok: false,
338
- message: `"${wanted}" resolves outside the directories this server may read (${shown}). The server reads the directory it was started for; restart it with --cwd <directory> to serve a different repository.`
339
- };
340
- }
341
- async function openWorkspace(root, overrides = {}, allowedRoots, options = {}) {
342
- const loaded = await loadConfigFileDetailed(root, options);
343
- if (loaded.errors.length > 0) {
344
- return {
345
- ok: false,
346
- message: `The config file could not be read: ${loaded.errors.join("; ")} Fix it, or delete it to use the defaults \u2014 this server will not silently ignore it.`
347
- };
348
- }
349
- const cliOptions = { cwd: root };
350
- if (overrides.maxPartBytes !== void 0) {
351
- const parsed = parseByteSize(overrides.maxPartBytes);
352
- if (parsed === void 0) {
353
- return {
354
- ok: false,
355
- message: '"maxPartBytes" must be a byte count, for example 307200 or "300k".'
356
- };
357
- }
358
- cliOptions.maxPartBytes = parsed;
359
- }
360
- if (overrides.maxPartTokens !== void 0) {
361
- const parsed = parseByteSize(overrides.maxPartTokens);
362
- if (parsed === void 0) {
363
- return {
364
- ok: false,
365
- message: '"maxPartTokens" must be a token count, for example 32000 or "32k".'
366
- };
367
- }
368
- cliOptions.maxPartTokens = parsed;
369
- }
370
- if (overrides.outDir !== void 0) {
371
- if (typeof overrides.outDir !== "string" || overrides.outDir.trim().length === 0) {
372
- return { ok: false, message: '"outDir" must be a non-empty string.' };
373
- }
374
- const requested = overrides.outDir.trim();
375
- const permitted = allowedRoots !== void 0 && allowedRoots.length > 0 ? allowedRoots : [root];
376
- const resolved = resolveThroughExistingAncestor(path.resolve(root, requested));
377
- if (!permitted.some((allowed) => isInside(canonicalPath(allowed), resolved))) {
378
- const shown = permitted.map((allowed) => canonicalPath(allowed)).join(", ");
379
- return {
380
- ok: false,
381
- message: `"outDir" must resolve inside the repository this server serves (${shown}). A tool argument may not place the snapshot outside it; pass a directory inside the root, or restart the server with --cwd pointing at the repository you want to write.`
382
- };
383
- }
384
- cliOptions.outDir = requested;
385
- }
386
- if (overrides.changedSince !== void 0) {
387
- if (typeof overrides.changedSince !== "string" || overrides.changedSince.trim().length === 0) {
388
- return {
389
- ok: false,
390
- message: '"changedSince" must be a git ref such as "main" or "HEAD~3".'
391
- };
392
- }
393
- cliOptions.changedSince = overrides.changedSince.trim();
394
- }
395
- if (overrides.skeleton === true) cliOptions.skeleton = true;
396
- if (overrides.sarif === true) cliOptions.sarif = true;
397
- if (overrides.staged === true) cliOptions.staged = true;
398
- if (overrides.withDependents === true) cliOptions.withDependents = true;
399
- try {
400
- const config = resolveConfig(loaded.config, cliOptions, root);
401
- return { ok: true, workspace: { root, config, configFile: loaded.file, cliOptions } };
402
- } catch (error) {
403
- return { ok: false, message: error instanceof Error ? error.message : String(error) };
404
- }
405
- }
406
- var MANIFEST_CACHE_LIMIT = 8;
407
- var manifestCache = /* @__PURE__ */ new Map();
408
- function manifestPathFor(workspace) {
409
- return path.resolve(workspace.root, workspace.config.outDir, "manifest.json");
410
- }
411
- function partPathFor(workspace, filename) {
412
- if (filename.length === 0 || filename.includes("\0")) return null;
413
- const partsDir = path.resolve(workspace.root, workspace.config.outDir, "parts");
414
- const resolved = path.resolve(partsDir, filename);
415
- const relative3 = path.relative(partsDir, resolved);
416
- if (relative3.length === 0 || relative3.includes(path.sep) || relative3.includes("/") || relative3.includes("\\") || path.isAbsolute(relative3)) {
417
- return null;
418
- }
419
- let stats;
420
- try {
421
- stats = fs.lstatSync(resolved);
422
- } catch {
423
- return null;
424
- }
425
- if (!stats.isFile()) return null;
426
- try {
427
- if (path.dirname(fs.realpathSync(resolved)) !== fs.realpathSync(partsDir)) return null;
428
- } catch {
429
- return null;
430
- }
431
- return resolved;
432
- }
433
- function readManifest(workspace) {
434
- const file = manifestPathFor(workspace);
435
- const shown = path.relative(workspace.root, file).split(path.sep).join("/") || file;
436
- let stats;
437
- try {
438
- stats = fs.statSync(file);
439
- } catch {
440
- return {
441
- ok: false,
442
- missing: true,
443
- message: `There is no snapshot manifest at ${shown}. Call snapshot_plan to preview what would be included, or snapshot_generate to write it.`
444
- };
445
- }
446
- const cached = manifestCache.get(file);
447
- if (cached && cached.mtimeMs === stats.mtimeMs && cached.ctimeMs === stats.ctimeMs && cached.size === stats.size) {
448
- return { ok: true, manifest: cached.manifest, file };
449
- }
450
- let raw;
451
- try {
452
- raw = fs.readFileSync(file, "utf8");
453
- } catch (error) {
454
- return {
455
- ok: false,
456
- missing: false,
457
- message: `${shown} exists but could not be read: ${error instanceof Error ? error.message : String(error)}`
458
- };
459
- }
460
- let parsed;
461
- try {
462
- parsed = JSON.parse(raw);
463
- } catch {
464
- return { ok: false, missing: false, message: `${shown} is not valid JSON.` };
465
- }
466
- const problem = describeManifestShapeProblem(parsed);
467
- if (problem) {
468
- return { ok: false, missing: false, message: `${shown} is not a snapshot manifest: ${problem}` };
469
- }
470
- const manifest = parsed;
471
- manifestCache.delete(file);
472
- manifestCache.set(file, {
473
- mtimeMs: stats.mtimeMs,
474
- ctimeMs: stats.ctimeMs,
475
- size: stats.size,
476
- manifest
477
- });
478
- while (manifestCache.size > MANIFEST_CACHE_LIMIT) {
479
- const oldest = manifestCache.keys().next().value;
480
- if (oldest === void 0) break;
481
- manifestCache.delete(oldest);
482
- }
483
- return { ok: true, manifest, file };
484
- }
485
- function forgetManifest(file) {
486
- manifestCache.delete(file);
487
- }
488
-
489
- // src/mcp/tools.ts
490
- var READ_ONLY = {
491
- readOnlyHint: true,
492
- destructiveHint: false,
493
- idempotentHint: true,
494
- openWorldHint: false
495
- };
496
- var WRITES = {
497
- readOnlyHint: false,
498
- // It replaces the snapshot directory but never anything it did not write, so it is additive with
499
- // respect to the user's files.
500
- destructiveHint: false,
501
- idempotentHint: true,
502
- openWorldHint: false
503
- };
504
- var MAX_RESULT_BYTES = 64 * 1024;
505
- var ROOT_PROPERTY = {
506
- type: "string",
507
- description: "Repository root. Defaults to the directory this server was started in."
508
- };
509
- var OUT_DIR_PROPERTY = {
510
- type: "string",
511
- description: "Snapshot directory, relative to the root, and it must resolve inside the served repository. Defaults to the project configuration's outDir."
512
- };
513
- var outDirOverride = (args) => ({ outDir: args.outDir });
514
- var SCOPE_PROPERTIES = {
515
- maxPartTokens: {
516
- type: "string",
517
- description: 'Token ceiling per part, for example 32000 or "32k". Narrower than maxPartBytes; it converts at four bytes per token.'
518
- },
519
- skeleton: {
520
- type: "boolean",
521
- description: "Replace every function body with `{ /* ... */ }`, keeping signatures, imports and exports. Applies to TypeScript, JavaScript and JSX."
522
- },
523
- sarif: {
524
- type: "boolean",
525
- description: "Also write reports/audit.sarif beside reports/audit.md, for CI code scanning."
526
- },
527
- changedSince: {
528
- type: "string",
529
- description: 'Only files changed since this git ref, for example "main" or "HEAD~3".'
530
- },
531
- staged: {
532
- type: "boolean",
533
- description: "Only files staged in the git index."
534
- },
535
- withDependents: {
536
- type: "boolean",
537
- description: "With staged or changedSince, also include the files that import the changed ones (one hop)."
538
- }
539
- };
540
- function workspaceOverrides(args) {
541
- return {
542
- outDir: args.outDir,
543
- maxPartBytes: args.maxPartBytes,
544
- maxPartTokens: args.maxPartTokens,
545
- skeleton: args.skeleton,
546
- sarif: args.sarif,
547
- changedSince: args.changedSince,
548
- staged: args.staged,
549
- withDependents: args.withDependents
550
- };
551
- }
552
- function failure(message) {
553
- return { text: message, isError: true };
554
- }
555
- function plural(count, word) {
556
- return `${count} ${word}${count === 1 ? "" : "s"}`;
557
- }
558
- function formatBytes(bytes) {
559
- if (bytes < 1024) return `${bytes} B`;
560
- if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} kB`;
561
- return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
562
- }
563
- function relativeFor(workspace, absolute) {
564
- return path.relative(workspace.root, absolute).split(path.sep).join("/");
565
- }
566
- function capped(values, limit = 20) {
567
- return { count: values.length, sample: values.slice(0, limit) };
568
- }
569
- function summarizeDrift(drift) {
570
- return {
571
- missingInSnapshot: capped(drift.missingInSnapshot),
572
- missingOnDisk: capped(drift.missingOnDisk),
573
- unreadable: capped(drift.unreadable),
574
- hashMismatches: capped(drift.hashMismatches),
575
- partIssues: capped(drift.partIssues),
576
- totalsMismatches: capped(drift.totalsMismatches),
577
- configMismatches: capped(drift.configMismatches)
578
- };
579
- }
580
- function toRelativePath(root, value) {
581
- const cleaned = value.trim();
582
- if (cleaned.length === 0 || cleaned.includes("\0")) return null;
583
- const resolvedRoot = path.resolve(root);
584
- const absolute = path.resolve(resolvedRoot, cleaned);
585
- const relative3 = path.relative(resolvedRoot, absolute);
586
- if (relative3 === "" || relative3 === ".." || relative3.startsWith(`..${path.sep}`) || path.isAbsolute(relative3)) {
587
- return null;
588
- }
589
- return relative3.split(path.sep).join("/");
590
- }
591
- function symbolsOf(entry) {
592
- const summary = entry.summary;
593
- if (!summary || typeof summary !== "object") return [];
594
- const names = [];
595
- const collect = (value) => {
596
- if (!Array.isArray(value)) return;
597
- for (const item of value) {
598
- if (typeof item === "string") names.push(item);
599
- }
600
- };
601
- const record = summary;
602
- for (const field of [
603
- "exports",
604
- "reactComponents",
605
- "routeHandlers",
606
- "functions",
607
- "classes",
608
- "interfaces",
609
- "types",
610
- "enums",
611
- "hooks",
612
- "headings",
613
- // The rest of the same records. `variables` is where a `const`, a Python constant, a Go
614
- // `var`, a Rust `mod`, a C `#define` and a Terraform `variable` block all land, so leaving it
615
- // out made `snapshot_locate` miss most of what a non-JavaScript file declares; `directives`
616
- // carries `"use client"`-style markers, and `frontmatterKeys`/`keys` are the headings and
617
- // top-level names of a Markdown or JSON file.
618
- "variables",
619
- "directives",
620
- "frontmatterKeys",
621
- "keys"
622
- ]) {
623
- collect(record[field]);
624
- }
625
- return names;
626
- }
627
- async function prepare(args, context, overrides = {}) {
628
- const rootOutcome = resolveRoot(args.root, context);
629
- if (!rootOutcome.ok) return { ok: false, outcome: failure(rootOutcome.message) };
630
- const opened = await openWorkspace(rootOutcome.root, overrides, context.roots, {
631
- allowExecutableConfig: false
632
- });
633
- if (!opened.ok) return { ok: false, outcome: failure(opened.message) };
634
- return { ok: true, workspace: opened.workspace };
635
- }
636
- var statusTool = {
637
- name: "snapshot_status",
638
- title: "Snapshot status",
639
- description: "Report whether a snapshot exists for this repository, when it was built, and what it covers. Reads the manifest rather than the repository, so it is cheap. Call it before deciding whether a snapshot needs to be generated.",
640
- inputSchema: {
641
- type: "object",
642
- properties: { root: ROOT_PROPERTY, outDir: OUT_DIR_PROPERTY },
643
- additionalProperties: false
644
- },
645
- outputSchema: {
646
- type: "object",
647
- properties: {
648
- present: { type: "boolean" },
649
- root: { type: "string" },
650
- outDir: { type: "string" },
651
- fingerprint: { type: "string" },
652
- generatedAt: { type: "string" },
653
- generatorVersion: { type: "string" },
654
- generatorVersionMatches: { type: "boolean" },
655
- includedFiles: { type: "integer" },
656
- skippedFiles: { type: "integer" },
657
- partCount: { type: "integer" },
658
- warningCount: { type: "integer" }
659
- }
660
- },
661
- annotations: READ_ONLY,
662
- async handler(args, context) {
663
- const prepared = await prepare(args, context, outDirOverride(args));
664
- if (!prepared.ok) return prepared.outcome;
665
- const workspace = prepared.workspace;
666
- const read = readManifest(workspace);
667
- if (!read.ok) {
668
- return {
669
- text: read.message,
670
- structured: {
671
- present: false,
672
- root: workspace.root,
673
- outDir: workspace.config.outDir,
674
- message: read.message
675
- }
676
- };
677
- }
678
- const manifest = read.manifest;
679
- const versionMatches = manifest.generator.version === GENERATOR_VERSION;
680
- const lines = [
681
- `Snapshot: ${workspace.config.outDir}/`,
682
- `Generated: ${manifest.generatedAt} by ${manifest.generator.name} ${manifest.generator.version}`,
683
- `Files: ${manifest.counts.totalFiles} included, ${manifest.counts.skippedCount} skipped, ${plural(manifest.counts.partsCount, "part")}`,
684
- `Content: ${formatBytes(manifest.counts.totalSizeBytes)} of source in ${formatBytes(manifest.totals.totalContentBytes)} emitted`,
685
- `Fingerprint: ${manifest.fingerprint}`,
686
- `Git: ${manifest.git.branch} @ ${manifest.git.commit}${manifest.git.isDirty ? " (dirty)" : " (clean)"}`
687
- ];
688
- if (manifest.totals.warningCount > 0) lines.push(`Warnings: ${manifest.totals.warningCount}`);
689
- if (!versionMatches) {
690
- lines.push(
691
- `Note: written by ${manifest.generator.version}, this server is ${GENERATOR_VERSION}. Re-run snapshot_generate if the difference matters.`
692
- );
693
- }
694
- return {
695
- text: lines.join("\n"),
696
- structured: {
697
- present: true,
698
- root: workspace.root,
699
- outDir: workspace.config.outDir,
700
- fingerprint: manifest.fingerprint,
701
- generatedAt: manifest.generatedAt,
702
- generatorVersion: manifest.generator.version,
703
- generatorVersionMatches: versionMatches,
704
- includedFiles: manifest.counts.totalFiles,
705
- skippedFiles: manifest.counts.skippedCount,
706
- partCount: manifest.counts.partsCount,
707
- warningCount: manifest.totals.warningCount,
708
- preset: manifest.config.preset,
709
- maxPartBytes: manifest.budgets.maxPartBytes
710
- }
711
- };
712
- }
713
- };
714
- var planTool = {
715
- name: "snapshot_plan",
716
- title: "Preview a snapshot",
717
- description: "Preview a snapshot without writing anything: how many files and parts it would contain, and why every excluded file was excluded. Use it to choose a part budget before generating.",
718
- inputSchema: {
719
- type: "object",
720
- properties: {
721
- root: ROOT_PROPERTY,
722
- outDir: OUT_DIR_PROPERTY,
723
- maxPartBytes: {
724
- type: "string",
725
- description: 'Byte budget per part, for example 307200 or "300k". Defaults to the project configuration.'
726
- },
727
- ...SCOPE_PROPERTIES
728
- },
729
- additionalProperties: false
730
- },
731
- outputSchema: {
732
- type: "object",
733
- properties: {
734
- files: { type: "integer" },
735
- skipped: { type: "integer" },
736
- parts: { type: "integer" },
737
- sourceBytes: { type: "integer" },
738
- emittedBytes: { type: "integer" },
739
- preset: { type: "string" }
740
- }
741
- },
742
- annotations: READ_ONLY,
743
- async handler(args, context) {
744
- const prepared = await prepare(args, context, workspaceOverrides(args));
745
- if (!prepared.ok) return prepared.outcome;
746
- const workspace = prepared.workspace;
747
- const result = await generateInWorker(workspace.root, workspace.cliOptions, { dryRun: true });
748
- if (!result.ok) return failure(result.message);
749
- const summary = result.summary;
750
- const topReasons = summary.skipReasons;
751
- const lines = [
752
- "Dry run \u2014 nothing was written.",
753
- `Preset: ${summary.preset}`,
754
- `Would include ${plural(summary.totalFiles, "file")} in ${plural(summary.partsCount, "part")} (${formatBytes(summary.totalSizeBytes)} of source, ${formatBytes(summary.totalContentBytes)} emitted).`,
755
- `Would skip ${plural(summary.skippedCount, "file")}.`
756
- ];
757
- if (topReasons.length > 0) {
758
- lines.push("Top skip reasons:");
759
- for (const entry of topReasons) lines.push(` - ${entry.reason} (${entry.count})`);
760
- }
761
- if (summary.warnings.length > 0) {
762
- lines.push(`Warnings (${summary.warnings.length}):`);
763
- for (const warning of summary.warnings.slice(0, 5)) lines.push(` - ${warning}`);
764
- }
765
- return {
766
- text: lines.join("\n"),
767
- structured: {
768
- files: summary.totalFiles,
769
- skipped: summary.skippedCount,
770
- parts: summary.partsCount,
771
- sourceBytes: summary.totalSizeBytes,
772
- emittedBytes: summary.totalContentBytes,
773
- preset: summary.preset,
774
- maxPartBytes: workspace.config.maxPartBytes,
775
- layers: summary.layers,
776
- skipReasons: topReasons,
777
- warnings: summary.warnings.slice(0, 5),
778
- warningCount: summary.warnings.length
779
- }
780
- };
781
- }
782
- };
783
- var generateTool = {
784
- name: "snapshot_generate",
785
- title: "Generate the snapshot",
786
- description: "Write the snapshot to its output directory and return its fingerprint, parts and counts. Replaces the previous snapshot in that directory. A large repository can take several seconds.",
787
- inputSchema: {
788
- type: "object",
789
- properties: {
790
- root: ROOT_PROPERTY,
791
- outDir: OUT_DIR_PROPERTY,
792
- maxPartBytes: {
793
- type: "string",
794
- description: 'Byte budget per part, for example 307200 or "300k". Defaults to the project configuration.'
795
- },
796
- ...SCOPE_PROPERTIES
797
- },
798
- additionalProperties: false
799
- },
800
- outputSchema: {
801
- type: "object",
802
- properties: {
803
- fingerprint: { type: "string" },
804
- files: { type: "integer" },
805
- skipped: { type: "integer" },
806
- parts: { type: "integer" },
807
- emittedBytes: { type: "integer" }
808
- }
809
- },
810
- annotations: WRITES,
811
- async handler(args, context) {
812
- const prepared = await prepare(args, context, workspaceOverrides(args));
813
- if (!prepared.ok) return prepared.outcome;
814
- const workspace = prepared.workspace;
815
- const result = await generateInWorker(workspace.root, workspace.cliOptions);
816
- if (!result.ok) return failure(result.message);
817
- const summary = result.summary;
818
- forgetManifest(manifestPathFor(workspace));
819
- const written = relativeFor(workspace, path.resolve(workspace.root, workspace.config.outDir));
820
- const lines = [
821
- `Wrote ${written}/`,
822
- `Files: ${summary.totalFiles} included, ${summary.skippedCount} skipped, ${plural(summary.partsCount, "part")}`,
823
- `Parts: ${summary.parts.map((part) => `${part.filename} (${formatBytes(part.byteSize)})`).join(", ")}`,
824
- `Fingerprint: ${summary.fingerprint}`
825
- ];
826
- if (summary.warnings.length > 0) {
827
- lines.push(`Warnings (${summary.warnings.length}):`);
828
- for (const warning of summary.warnings.slice(0, 5)) lines.push(` - ${warning}`);
829
- }
830
- return {
831
- text: lines.join("\n"),
832
- structured: {
833
- fingerprint: summary.fingerprint,
834
- files: summary.totalFiles,
835
- skipped: summary.skippedCount,
836
- parts: summary.partsCount,
837
- emittedBytes: summary.totalContentBytes,
838
- outDir: written,
839
- partFiles: summary.parts.map((part) => part.filename),
840
- warningCount: summary.warnings.length
841
- }
842
- };
843
- }
844
- };
845
- var validateTool = {
846
- name: "snapshot_validate",
847
- title: "Validate the snapshot",
848
- description: "Re-read the repository and report whether the snapshot on disk still matches it. Use it before trusting context that came from an earlier session, or after changing the config.",
849
- inputSchema: {
850
- type: "object",
851
- properties: { root: ROOT_PROPERTY, outDir: OUT_DIR_PROPERTY, ...SCOPE_PROPERTIES },
852
- additionalProperties: false
853
- },
854
- outputSchema: {
855
- type: "object",
856
- properties: {
857
- current: { type: "boolean" },
858
- manifestPresent: { type: "boolean" }
859
- }
860
- },
861
- annotations: READ_ONLY,
862
- async handler(args, context) {
863
- const prepared = await prepare(args, context, workspaceOverrides(args));
864
- if (!prepared.ok) return prepared.outcome;
865
- const workspace = prepared.workspace;
866
- let result;
867
- try {
868
- result = validateSnapshot(workspace.config);
869
- } catch (error) {
870
- return failure(error instanceof Error ? error.message : String(error));
871
- }
872
- const lines = [];
873
- if (result.valid) {
874
- lines.push("The snapshot matches the repository.");
875
- } else {
876
- lines.push("The snapshot is out of date.");
877
- const drift = result.drift;
878
- const observations = [
879
- ["file(s) changed on disk", drift.hashMismatches.length],
880
- ["file(s) added since the snapshot", drift.missingInSnapshot.length],
881
- ["file(s) gone since the snapshot", drift.missingOnDisk.length],
882
- ["part file(s) damaged or missing", drift.partIssues.length],
883
- ["setting(s) changed since the snapshot", drift.configMismatches.length],
884
- ["internal count(s) disagreeing", drift.totalsMismatches.length]
885
- ];
886
- for (const [label, count] of observations) {
887
- if (count > 0) lines.push(` - ${count} ${label}`);
888
- }
889
- for (const error of result.errors.slice(0, 5)) lines.push(` - ${error}`);
890
- lines.push("Run snapshot_generate to refresh it.");
891
- }
892
- for (const warning of result.warnings.slice(0, 5)) lines.push(`Note: ${warning}`);
893
- return {
894
- text: lines.join("\n"),
895
- structured: {
896
- current: result.valid,
897
- manifestPresent: result.manifestPresent,
898
- drift: summarizeDrift(result.drift),
899
- errors: result.errors.slice(0, 10),
900
- warnings: result.warnings.slice(0, 10)
901
- }
902
- // A stale snapshot is an answer, not a tool failure: the caller asked whether it is current.
903
- };
904
- }
905
- };
906
- var locateTool = {
907
- name: "snapshot_locate",
908
- title: "Locate code in the snapshot",
909
- description: "Find which part holds the code you need. Matches file paths, exported symbols, component names and routes from the snapshot's index, so one part can be read instead of all of them.",
910
- inputSchema: {
911
- type: "object",
912
- properties: {
913
- query: {
914
- type: "string",
915
- description: "Text to match, case-insensitively, against paths and exported symbols."
916
- },
917
- by: {
918
- type: "string",
919
- enum: ["auto", "path", "symbol", "route", "layer", "kind"],
920
- default: "auto",
921
- description: "Restrict what is matched. Defaults to every category."
922
- },
923
- limit: {
924
- type: "integer",
925
- minimum: 1,
926
- maximum: 100,
927
- default: 20,
928
- description: "Maximum matches to return."
929
- },
930
- root: ROOT_PROPERTY,
931
- outDir: OUT_DIR_PROPERTY
932
- },
933
- required: ["query"],
934
- additionalProperties: false
935
- },
936
- outputSchema: {
937
- type: "object",
938
- properties: { total: { type: "integer" } }
939
- },
940
- annotations: READ_ONLY,
941
- async handler(args, context) {
942
- const prepared = await prepare(args, context, outDirOverride(args));
943
- if (!prepared.ok) return prepared.outcome;
944
- const workspace = prepared.workspace;
945
- const read = readManifest(workspace);
946
- if (!read.ok) return failure(read.message);
947
- const query = String(args.query ?? "").trim();
948
- if (query.length === 0) return failure('"query" must not be empty.');
949
- const needle = query.toLowerCase();
950
- const by = typeof args.by === "string" ? args.by : "auto";
951
- const limit = typeof args.limit === "number" ? args.limit : 20;
952
- const manifest = read.manifest;
953
- const matches = [];
954
- const add = (entry, matchedBy, detail) => {
955
- matches.push({
956
- path: entry.relativePath,
957
- part: entry.part,
958
- layer: entry.layer,
959
- kind: entry.kind,
960
- matchedBy,
961
- ...detail ? { detail } : {}
962
- });
963
- };
964
- const wants = (category) => by === "auto" || by === category;
965
- for (const entry of manifest.files) {
966
- if (wants("path") && entry.relativePath.toLowerCase().includes(needle)) {
967
- add(entry, "path");
968
- continue;
969
- }
970
- if (wants("symbol")) {
971
- const symbol = symbolsOf(entry).find((name) => name.toLowerCase().includes(needle));
972
- if (symbol) {
973
- add(entry, "symbol", symbol);
974
- continue;
975
- }
976
- }
977
- if (wants("layer") && entry.layer.toLowerCase().includes(needle)) add(entry, "layer");
978
- else if (wants("kind") && entry.kind.toLowerCase().includes(needle)) add(entry, "kind");
979
- }
980
- if (wants("route")) {
981
- const matchedPaths = new Set(matches.map((match) => match.path));
982
- for (const route of manifest.indexes.routes) {
983
- const method = route.methods.find((name) => name.toLowerCase().includes(needle));
984
- if (!route.path.toLowerCase().includes(needle) && method === void 0) continue;
985
- if (matchedPaths.has(route.path)) continue;
986
- matchedPaths.add(route.path);
987
- matches.push({
988
- path: route.path,
989
- part: route.part,
990
- layer: "route",
991
- kind: "route",
992
- matchedBy: "route",
993
- detail: route.methods.join(", ")
994
- });
995
- }
996
- }
997
- if (matches.length === 0) {
998
- return {
999
- text: `Nothing in the snapshot matches "${query}". Try a shorter fragment, or snapshot_explain a path to see whether it is included at all.`,
1000
- structured: { total: 0, matches: [] }
1001
- };
1002
- }
1003
- const shown = matches.slice(0, limit);
1004
- const lines = [
1005
- `${matches.length} match${matches.length === 1 ? "" : "es"} for "${query}"` + (matches.length > shown.length ? ` (showing ${shown.length})` : "") + ":"
1006
- ];
1007
- for (const match of shown) {
1008
- const detail = match.detail ? ` \u2014 ${match.detail}` : "";
1009
- lines.push(` ${match.path}${detail} [${match.part}, ${match.layer}/${match.kind}]`);
1010
- }
1011
- if (matches.length > shown.length) {
1012
- lines.push("Raise `limit` to see more.");
1013
- }
1014
- return {
1015
- text: lines.join("\n"),
1016
- structured: { total: matches.length, returned: shown.length, matches: shown }
1017
- };
1018
- }
1019
- };
1020
- var dependentsTool = {
1021
- name: "snapshot_dependents",
1022
- title: "Follow the import graph",
1023
- description: 'For one file in the snapshot: what it imports, and which files import it. Answers "what breaks if I change this?" without reading the parts.',
1024
- inputSchema: {
1025
- type: "object",
1026
- properties: {
1027
- path: {
1028
- type: "string",
1029
- description: "Snapshot-relative path, exactly as snapshot_locate or manifest.files[] reports it."
1030
- },
1031
- direction: {
1032
- type: "string",
1033
- enum: ["both", "imports", "imported-by"],
1034
- default: "both",
1035
- description: "Which edges to return."
1036
- },
1037
- limit: {
1038
- type: "integer",
1039
- minimum: 1,
1040
- maximum: 200,
1041
- default: 50,
1042
- description: "Maximum entries per direction."
1043
- },
1044
- root: ROOT_PROPERTY,
1045
- outDir: OUT_DIR_PROPERTY
1046
- },
1047
- required: ["path"],
1048
- additionalProperties: false
1049
- },
1050
- outputSchema: {
1051
- type: "object",
1052
- properties: {
1053
- path: { type: "string" },
1054
- imports: { type: "array" },
1055
- importedBy: { type: "array" },
1056
- unresolved: { type: "array" }
1057
- }
1058
- },
1059
- annotations: READ_ONLY,
1060
- async handler(args, context) {
1061
- const prepared = await prepare(args, context, outDirOverride(args));
1062
- if (!prepared.ok) return prepared.outcome;
1063
- const read = readManifest(prepared.workspace);
1064
- if (!read.ok) return failure(read.message);
1065
- const manifest = read.manifest;
1066
- const requested = String(args.path ?? "").trim().replace(/\\/g, "/");
1067
- if (requested.length === 0) return failure('"path" must not be empty.');
1068
- const filesByPath = new Map(manifest.files.map((file) => [file.relativePath, file]));
1069
- const entry = filesByPath.get(requested) ?? manifest.files.find((file) => file.relativePath.toLowerCase() === requested.toLowerCase());
1070
- if (!entry) {
1071
- return failure(
1072
- `${requested} is not in the snapshot. Use snapshot_locate to find its path, or snapshot_explain to see whether it was excluded.`
1073
- );
1074
- }
1075
- const direction = args.direction === "imports" || args.direction === "imported-by" ? String(args.direction) : "both";
1076
- const limit = typeof args.limit === "number" && args.limit > 0 ? Math.floor(args.limit) : 50;
1077
- const resolver = buildImportResolver(manifest.files);
1078
- const imports = [];
1079
- const unresolved = [];
1080
- if (direction !== "imported-by") {
1081
- const own = manifest.indexes.imports.byFile.find((file) => file.path === entry.relativePath);
1082
- for (const specifier of own?.imports ?? []) {
1083
- const resolved = resolveSpecifier(entry.relativePath, specifier, resolver);
1084
- if (resolved === null) {
1085
- unresolved.push(specifier);
1086
- continue;
1087
- }
1088
- const target = filesByPath.get(resolved);
1089
- if (target) imports.push({ path: resolved, specifier, part: target.part });
1090
- }
1091
- }
1092
- const importedBy = [];
1093
- if (direction !== "imports") {
1094
- for (const candidate of manifest.indexes.imports.byFile) {
1095
- if (candidate.path === entry.relativePath) continue;
1096
- const edge = candidate.imports.some(
1097
- (specifier) => resolveSpecifier(candidate.path, specifier, resolver) === entry.relativePath
1098
- );
1099
- if (!edge) continue;
1100
- const source = filesByPath.get(candidate.path);
1101
- importedBy.push({ path: candidate.path, part: source?.part ?? "" });
1102
- }
1103
- }
1104
- const shownImports = imports.slice(0, limit);
1105
- const shownImportedBy = importedBy.slice(0, limit);
1106
- const lines = [
1107
- `${entry.relativePath} \u2014 ${importedBy.length} importer(s), ${imports.length} import(s), ${unresolved.length} outside the snapshot.`
1108
- ];
1109
- if (direction !== "imports") {
1110
- lines.push("", "Imported by:");
1111
- if (shownImportedBy.length === 0) lines.push(" (nothing in the snapshot imports it)");
1112
- for (const item of shownImportedBy) lines.push(` ${item.path} [${item.part}]`);
1113
- if (importedBy.length > shownImportedBy.length) {
1114
- lines.push(` \u2026 ${importedBy.length - shownImportedBy.length} more; raise \`limit\`.`);
1115
- }
1116
- }
1117
- if (direction !== "imported-by") {
1118
- lines.push("", "Imports:");
1119
- if (shownImports.length === 0) lines.push(" (none recorded for this file)");
1120
- for (const item of shownImports) {
1121
- lines.push(` ${item.path} (from "${item.specifier}") [${item.part}]`);
1122
- }
1123
- if (imports.length > shownImports.length) {
1124
- lines.push(` \u2026 ${imports.length - shownImports.length} more; raise \`limit\`.`);
1125
- }
1126
- if (unresolved.length > 0) {
1127
- lines.push("", `Outside the snapshot (${unresolved.length}): ${unresolved.join(", ")}`);
1128
- }
1129
- }
1130
- return {
1131
- text: lines.join("\n"),
1132
- structured: {
1133
- path: entry.relativePath,
1134
- imports: shownImports,
1135
- importedBy: shownImportedBy,
1136
- unresolved
1137
- }
1138
- };
1139
- }
1140
- };
1141
- var readTool = {
1142
- name: "snapshot_read",
1143
- title: "Read a file from the snapshot",
1144
- description: "Return a line window of one file as the snapshot contains it: redacted, and bounded to a preview when the source is large. Reports the next `fromLine` when more remains.",
1145
- inputSchema: {
1146
- type: "object",
1147
- properties: {
1148
- path: {
1149
- type: "string",
1150
- description: "File path relative to the repository root, as snapshot_locate reports it."
1151
- },
1152
- fromLine: {
1153
- type: "integer",
1154
- minimum: 1,
1155
- default: 1,
1156
- description: "First line to return, 1-based."
1157
- },
1158
- lines: {
1159
- type: "integer",
1160
- minimum: 1,
1161
- maximum: 2e3,
1162
- default: 200,
1163
- description: "How many lines to return."
1164
- },
1165
- root: ROOT_PROPERTY,
1166
- outDir: OUT_DIR_PROPERTY
1167
- },
1168
- required: ["path"],
1169
- additionalProperties: false
1170
- },
1171
- outputSchema: {
1172
- type: "object",
1173
- properties: {
1174
- path: { type: "string" },
1175
- part: { type: "string" },
1176
- fromLine: { type: "integer" },
1177
- returnedLines: { type: "integer" },
1178
- totalLines: { type: "integer" },
1179
- nextFromLine: { type: "integer" },
1180
- pageable: { type: "boolean" },
1181
- reason: { type: "string" }
1182
- }
1183
- },
1184
- annotations: READ_ONLY,
1185
- async handler(args, context) {
1186
- const prepared = await prepare(args, context, outDirOverride(args));
1187
- if (!prepared.ok) return prepared.outcome;
1188
- const workspace = prepared.workspace;
1189
- if (typeof args.path !== "string") return failure('"path" must be a string.');
1190
- const relativePath = toRelativePath(workspace.root, args.path);
1191
- if (!relativePath) {
1192
- return failure(
1193
- `"${args.path}" is outside ${workspace.root}. Paths are read relative to the repository root.`
1194
- );
1195
- }
1196
- const read = readManifest(workspace);
1197
- if (!read.ok) return failure(read.message);
1198
- const manifest = read.manifest;
1199
- const entry = manifest.files.find((file) => file.relativePath === relativePath) ?? manifest.files.find((file) => file.relativePath.toLowerCase() === relativePath.toLowerCase());
1200
- if (!entry) {
1201
- const skipped = manifest.skipped.find((record) => record.path === relativePath);
1202
- if (skipped) {
1203
- const detail = skipped.detail ? ` (${skipped.detail})` : "";
1204
- return failure(
1205
- `${relativePath} is not in the snapshot: ${skipped.reason}${detail}. Sensitive and ignored files stay out unless they are included explicitly.`
1206
- );
1207
- }
1208
- return failure(
1209
- `${relativePath} is not in the snapshot. Call snapshot_locate to find the path, or snapshot_explain to learn why it was excluded.`
1210
- );
1211
- }
1212
- const partPath = partPathFor(workspace, entry.part);
1213
- if (partPath === null) {
1214
- return failure(
1215
- `${entry.part} is not a part of this snapshot: its name leaves ${workspace.config.outDir}/parts. Run snapshot_generate to rebuild it.`
1216
- );
1217
- }
1218
- let partText;
1219
- try {
1220
- partText = fs.readFileSync(partPath, "utf8");
1221
- } catch {
1222
- return failure(
1223
- `${entry.part} could not be read, so the snapshot is damaged. Run snapshot_generate to rebuild it.`
1224
- );
1225
- }
1226
- const section = findSection(parsePartSections(partText), entry.relativePath);
1227
- if (!section) {
1228
- return failure(
1229
- `${relativePath} is recorded in ${entry.part} but its section could not be located there. Run snapshot_generate to rebuild the snapshot.`
1230
- );
1231
- }
1232
- const fromLine = typeof args.fromLine === "number" ? args.fromLine : 1;
1233
- const lineCount = typeof args.lines === "number" ? args.lines : 200;
1234
- const window = windowText(section.body, fromLine, lineCount);
1235
- let body = window.text;
1236
- let truncatedByBytes = false;
1237
- let clippedInsideLine = false;
1238
- if (Buffer.byteLength(body, "utf8") > MAX_RESULT_BYTES) {
1239
- const clipped = truncateToBytes(body, MAX_RESULT_BYTES);
1240
- const lastBreak = clipped.content.lastIndexOf("\n");
1241
- if (lastBreak > 0) {
1242
- body = clipped.content.slice(0, lastBreak);
1243
- } else {
1244
- body = clipped.content;
1245
- clippedInsideLine = true;
1246
- }
1247
- truncatedByBytes = true;
1248
- }
1249
- const returnedLines = body.length === 0 ? 0 : body.split("\n").length;
1250
- const moreRemain = !clippedInsideLine && !window.pastEnd && (window.truncated || truncatedByBytes);
1251
- const header = [
1252
- `${entry.relativePath} \u2014 ${entry.part}, ${entry.layer}/${entry.kind}, ${entry.language}`,
1253
- // The line range is the answer to "where am I in this file", and it is computed from the
1254
- // body the window was taken from, so it is just as meaningful for a preview as for a full
1255
- // file. It used to be replaced — not augmented — by the preview note, so a 40-line window
1256
- // into a 300-line preview came back with no range at all and the caller could not tell
1257
- // where the window ended. Both facts are stated now, and `signatures` is no longer
1258
- // silently treated as a full file.
1259
- ...section.inclusion === "preview" ? [
1260
- "Bounded preview: the snapshot holds this file's head and tail only, so these line numbers count the preview, not the source."
1261
- ] : section.inclusion === "signatures" ? [
1262
- "Signatures: function and method bodies were replaced with `{ /* ... */ }` when the snapshot was generated."
1263
- ] : [],
1264
- window.totalLines === 0 ? "This file is empty." : window.pastEnd ? `This file has ${window.totalLines} line(s); fromLine=${window.fromLine} is past its end.` : clippedInsideLine ? `Line ${window.fromLine} of ${window.totalLines}: this line is longer than one result can carry, so this page ends mid-line.` : `Lines ${window.fromLine}\u2013${window.fromLine + returnedLines - 1} of ${window.totalLines}.`
1265
- ];
1266
- const lines = [...header, "", body];
1267
- if (moreRemain) {
1268
- const next = window.fromLine + returnedLines;
1269
- lines.push("", `Truncated. Call snapshot_read with fromLine=${next} for the rest.`);
1270
- } else if (clippedInsideLine) {
1271
- lines.push(
1272
- "",
1273
- "Truncated. The remainder of this line is not reachable through snapshot_read; read the file from disk to see it."
1274
- );
1275
- }
1276
- return {
1277
- text: lines.join("\n"),
1278
- structured: {
1279
- path: entry.relativePath,
1280
- part: entry.part,
1281
- // The window itself: a caller that wants to measure or re-send what it received should
1282
- // not have to strip the header and the paging note back off `text`.
1283
- body,
1284
- layer: entry.layer,
1285
- kind: entry.kind,
1286
- language: entry.language,
1287
- inclusion: section.inclusion ?? entry.inclusionMode,
1288
- fromLine: window.fromLine,
1289
- returnedLines,
1290
- totalLines: window.totalLines,
1291
- truncated: moreRemain || clippedInsideLine,
1292
- pageable: !clippedInsideLine,
1293
- ...clippedInsideLine ? { reason: "line exceeds the result limit; its remainder is not reachable by fromLine" } : {},
1294
- nextFromLine: moreRemain ? window.fromLine + returnedLines : null,
1295
- sha256: entry.hashSha256
1296
- }
1297
- };
1298
- }
1299
- };
1300
- var explainTool = {
1301
- name: "snapshot_explain",
1302
- title: "Explain one path",
1303
- description: 'Explain how the next snapshot would treat one path: its layer, kind, language and part, or the exact reason it is excluded. Answers "why is this file missing".',
1304
- inputSchema: {
1305
- type: "object",
1306
- properties: {
1307
- path: {
1308
- type: "string",
1309
- description: "Path relative to the repository root. Directories are explained as a whole."
1310
- },
1311
- root: ROOT_PROPERTY,
1312
- outDir: OUT_DIR_PROPERTY,
1313
- ...SCOPE_PROPERTIES
1314
- },
1315
- required: ["path"],
1316
- additionalProperties: false
1317
- },
1318
- outputSchema: {
1319
- type: "object",
1320
- properties: {
1321
- path: { type: "string" },
1322
- included: { type: "boolean" },
1323
- reason: { type: "string" }
1324
- }
1325
- },
1326
- annotations: READ_ONLY,
1327
- async handler(args, context) {
1328
- const prepared = await prepare(args, context, workspaceOverrides(args));
1329
- if (!prepared.ok) return prepared.outcome;
1330
- const workspace = prepared.workspace;
1331
- if (typeof args.path !== "string") return failure('"path" must be a string.');
1332
- const relativePath = toRelativePath(workspace.root, args.path);
1333
- if (!relativePath) {
1334
- return failure(`"${args.path}" is outside ${workspace.root}.`);
1335
- }
1336
- let result;
1337
- try {
1338
- result = explainPath(workspace.config, relativePath);
1339
- } catch (error) {
1340
- return failure(error instanceof Error ? error.message : String(error));
1341
- }
1342
- return {
1343
- text: renderExplainText(result),
1344
- structured: {
1345
- path: result.path,
1346
- included: result.included,
1347
- ...result.reason ? { reason: result.reason } : {},
1348
- ...result.detail ? { detail: result.detail } : {},
1349
- ...result.layer ? { layer: result.layer } : {},
1350
- ...result.kind ? { kind: result.kind } : {},
1351
- ...result.language ? { language: result.language } : {},
1352
- ...result.part ? { part: result.part } : {},
1353
- ...result.inclusionMode ? { inclusion: result.inclusionMode } : {},
1354
- ...typeof result.lines === "number" ? { lines: result.lines } : {},
1355
- ...typeof result.bytes === "number" ? { bytes: result.bytes } : {},
1356
- ...typeof result.secretCount === "number" ? { secretCount: result.secretCount } : {}
1357
- }
1358
- };
1359
- }
1360
- };
1361
- function buildTools() {
1362
- return [
1363
- statusTool,
1364
- planTool,
1365
- generateTool,
1366
- validateTool,
1367
- locateTool,
1368
- dependentsTool,
1369
- readTool,
1370
- explainTool
1371
- ];
1372
- }
1373
-
1374
- // src/mcp/prompts.ts
1375
- var ORIENT = `You have a codebase-snapshot server for this repository. Build a map of it before reading any code.
1376
-
1377
- 1. Call snapshot_status. If no snapshot exists, call snapshot_plan to preview it, then snapshot_generate.
1378
- 2. Call snapshot_locate for the areas that matter. Search by exported symbol, route or path fragment rather than guessing filenames.
1379
- 3. Report back: the layers present, the entry points, and the files that matter here \u2014 cited as paths with their part.
1380
- 4. Read one file at a time with snapshot_read, one window at a time. Do not read a part end to end.`;
1381
- var KEEP_CURRENT = `Keep the context you were given provably current while you work.
1382
-
1383
- 1. Before relying on a snapshot from an earlier session, call snapshot_validate.
1384
- 2. If it reports drift, call snapshot_generate once, then snapshot_validate again.
1385
- 3. After changes you make, call snapshot_validate and report what it said.
1386
- 4. Never call a snapshot current unless snapshot_validate said so in this session.`;
1387
- function withFocus(base, focus) {
1388
- return typeof focus === "string" && focus.trim().length > 0 ? `${base}
1389
-
1390
- Focus for this pass: ${focus.trim()}` : base;
1391
- }
1392
- function buildPrompts() {
1393
- return [
1394
- {
1395
- name: "orient",
1396
- title: "Orient in this repository",
1397
- description: "Map the repository from the snapshot before reading any of it.",
1398
- arguments: [
1399
- {
1400
- name: "focus",
1401
- description: 'Optional area to concentrate on, for example "authentication".',
1402
- required: false
1403
- }
1404
- ],
1405
- build(args) {
1406
- return {
1407
- description: "Map the repository before reading it.",
1408
- messages: [{ role: "user", content: { type: "text", text: withFocus(ORIENT, args.focus) } }]
1409
- };
1410
- }
1411
- },
1412
- {
1413
- name: "keep-current",
1414
- title: "Keep the snapshot current",
1415
- description: "Validate before trusting earlier context, and again after making changes.",
1416
- arguments: [],
1417
- build() {
1418
- return {
1419
- description: "Keep the context current.",
1420
- messages: [{ role: "user", content: { type: "text", text: KEEP_CURRENT } }]
1421
- };
1422
- }
1423
- }
1424
- ];
1425
- }
1426
-
1427
- // src/mcp/uris.ts
1428
- var STATIC_RESOURCE_URIS = [
1429
- "snapshot://manifest",
1430
- "snapshot://contract",
1431
- "snapshot://skill",
1432
- "snapshot://prompt",
1433
- "snapshot://reports/audit",
1434
- "snapshot://reports/tree",
1435
- "snapshot://reports/navigation"
1436
- ];
1437
- var RESOURCE_TEMPLATE_URIS = ["snapshot://parts/{index}"];
1438
-
1439
- // src/agent/option-scope.ts
1440
- var VALIDATE_OPTIONS = [
1441
- "sarif",
1442
- "skeleton",
1443
- "changed-since",
1444
- "staged",
1445
- "with-dependents",
1446
- "cwd",
1447
- "out-dir",
1448
- "max-part-bytes",
1449
- "max-part-tokens",
1450
- "large-file-bytes",
1451
- "max-monolith-bytes",
1452
- "max-parts",
1453
- "brief",
1454
- "prompt-task",
1455
- "include-monolith",
1456
- "include-sensitive-files",
1457
- "skip-artifacts",
1458
- "only-artifacts",
1459
- "no-config",
1460
- "discovery",
1461
- "format",
1462
- "no-update-check",
1463
- "mode",
1464
- "help",
1465
- "version"
1466
- ];
1467
- var COMMAND_OPTION_SCOPE = {
1468
- generate: [
1469
- "sarif",
1470
- "skeleton",
1471
- "changed-since",
1472
- "staged",
1473
- "with-dependents",
1474
- "cwd",
1475
- "out-dir",
1476
- "max-part-bytes",
1477
- "max-part-tokens",
1478
- "large-file-bytes",
1479
- "max-monolith-bytes",
1480
- "attachment-slots",
1481
- "max-parts",
1482
- "brief",
1483
- "prompt-task",
1484
- "include-monolith",
1485
- "include-sensitive-files",
1486
- "skip-artifacts",
1487
- "only-artifacts",
1488
- "no-config",
1489
- "discovery",
1490
- "format",
1491
- "mode",
1492
- "dry-run",
1493
- "watch",
1494
- "autopilot",
1495
- "no-install",
1496
- "no-update-check",
1497
- "help",
1498
- "version"
1499
- ],
1500
- validate: VALIDATE_OPTIONS,
1501
- // `report` reads `manifest.json` and prints what is there; a generation setting would change
1502
- // nothing. The seven generation flags used to be listed here and were accepted as silent no-ops
1503
- // — the exact "flag that parses but changes nothing" this table exists to prevent — while
1504
- // `--discovery` was already rejected. Both the parser and `describe`'s `appliesTo` read this
1505
- // list, so removing them narrows the two together.
1506
- report: [
1507
- "cwd",
1508
- "out-dir",
1509
- "no-config",
1510
- "no-update-check",
1511
- "format",
1512
- "mode",
1513
- "help",
1514
- "version"
1515
- ],
1516
- explain: [
1517
- // The scope decides what `explain` says about a file, dependents included: without these,
1518
- // a file that is in the snapshot only because it imports a changed one was explained as
1519
- // `included: false, reason: "unchanged"`.
1520
- "changed-since",
1521
- "staged",
1522
- "with-dependents",
1523
- "cwd",
1524
- "out-dir",
1525
- // `--large-file-bytes` changes the inclusion mode `explain` reports, so it belongs here.
1526
- // `--max-part-bytes`, `--max-monolith-bytes`, `--include-monolith`, `--skip-artifacts` and
1527
- // `--only-artifacts` were accepted and never read: a per-file answer cannot depend on how the
1528
- // whole snapshot is partitioned, and none of them changes whether this file is included.
1529
- // Removed rather than implemented, because a flag that parses and does nothing is the defect
1530
- // this table exists to prevent.
1531
- "large-file-bytes",
1532
- "include-sensitive-files",
1533
- "no-config",
1534
- "discovery",
1535
- "no-update-check",
1536
- "format",
1537
- "mode",
1538
- "help",
1539
- "version"
1540
- ],
1541
- diff: ["format", "mode", "no-config", "no-update-check", "help", "version"],
1542
- describe: ["format", "mode", "help", "version"],
1543
- init: [
1544
- "install-hook",
1545
- "cwd",
1546
- "out-dir",
1547
- "max-part-bytes",
1548
- "include-sensitive-files",
1549
- "skip-artifacts",
1550
- "only-artifacts",
1551
- "preset",
1552
- "include",
1553
- "exclude",
1554
- "yes",
1555
- "force",
1556
- "dry-run",
1557
- "no-update-check",
1558
- "format",
1559
- "mode",
1560
- "help",
1561
- "version"
1562
- ],
1563
- skill: ["cwd", "format", "mode", "install", "target", "help", "version"],
1564
- // `mcp` reads the repository, so it takes --cwd. It has no --format: stdout carries JSON-RPC
1565
- // messages, and there is no second shape to choose, so offering the flag would be a lie.
1566
- mcp: ["cwd", "mode", "help", "version"],
1567
- // `setup` generates through the `generate` command, so every generation setting it can
1568
- // honour is in scope. Rejecting them made the one-command path unable to express a walk
1569
- // scan, a monolith or a different large-file threshold; the alternative was to run
1570
- // `setup` and then edit the config it had just written.
1571
- setup: [
1572
- "install-hook",
1573
- "cwd",
1574
- "out-dir",
1575
- "max-part-bytes",
1576
- // Persisted into the config `setup` writes, then forwarded to the generation it runs — so
1577
- // the snapshot it produces validates against the config beside it. Accepting a setting here
1578
- // without writing it down made `setup --large-file-bytes 100k` finish with a snapshot its
1579
- // own `validate` called drifted, on the first run of a brand-new project.
1580
- "max-part-tokens",
1581
- "skeleton",
1582
- "sarif",
1583
- "large-file-bytes",
1584
- "max-monolith-bytes",
1585
- "include-monolith",
1586
- "include-sensitive-files",
1587
- "skip-artifacts",
1588
- "only-artifacts",
1589
- "discovery",
1590
- "preset",
1591
- "include",
1592
- "exclude",
1593
- "yes",
1594
- "force",
1595
- "no-install",
1596
- "dry-run",
1597
- "no-update-check",
1598
- "format",
1599
- "mode",
1600
- "help",
1601
- "version"
1602
- ]
1603
- };
1604
- var COMMAND_ORDER = [
1605
- "generate",
1606
- "validate",
1607
- "report",
1608
- "explain",
1609
- "init",
1610
- "setup",
1611
- "diff",
1612
- "describe",
1613
- "skill",
1614
- "mcp"
1615
- ];
1616
- function commandsForOption(option) {
1617
- return COMMAND_ORDER.filter((command) => COMMAND_OPTION_SCOPE[command].includes(option));
1618
- }
1619
- function optionAppliesTo(option) {
1620
- return commandsForOption(option).join("/");
1621
- }
1622
-
1623
- // src/agent/contract.ts
1624
- var CONTRACT_VERSION = "1.0.0";
1625
- var PACKAGE_NAME = "codebase-snapshot";
1626
- var MAJOR_VERSION = GENERATOR_VERSION.split(".")[0];
1627
- var ARTIFACT_SUMMARY = {
1628
- readme: "README.md describing the snapshot at the output root.",
1629
- prompt: "PROMPT.md: the instruction sheet to paste with the snapshot, rendered from its manifest.",
1630
- manifest: "manifest.json: machine-readable index of every file, part, hash and config.",
1631
- parts: "parts/*.md: the packed, budget-limited markdown parts that carry the code.",
1632
- navigation: "reports/navigation.md: links between parts and layers.",
1633
- projectTree: "reports/project-tree.md: the directory tree of included files.",
1634
- audit: "reports/audit.md: secret findings, large files, parse diagnostics, git state.",
1635
- monolith: "full-codebase.json and full-codebase.md: the whole repository in one file (off by default)."
1636
- };
1637
- var ARTIFACT_DEFAULTS = {
1638
- readme: true,
1639
- prompt: true,
1640
- manifest: true,
1641
- parts: true,
1642
- navigation: true,
1643
- projectTree: true,
1644
- audit: true,
1645
- monolith: false
1646
- };
1647
- function renderContractText(contract) {
1648
- const lines = [];
1649
- lines.push(`${contract.package} v${contract.version}`);
1650
- lines.push(contract.summary);
1651
- lines.push("");
1652
- lines.push(`Node : ${contract.requires.node}`);
1653
- lines.push(`Schema : ${contract.schemaVersion} (contract ${contract.contractVersion})`);
1654
- lines.push(`One-shot : ${contract.invocation.oneShot} <command>`);
1655
- lines.push(`Installed : ${contract.invocation.installed} <command>`);
1656
- lines.push("");
1657
- lines.push("Workflow:");
1658
- for (const step of contract.workflow) {
1659
- lines.push(` ${step.step}. ${step.id}`);
1660
- lines.push(` run : ${step.run}`);
1661
- lines.push(` expect : ${step.expect}`);
1662
- if (step.notes) lines.push(` note : ${step.notes}`);
1663
- }
1664
- lines.push("");
1665
- lines.push("Commands:");
1666
- for (const command of contract.commands) {
1667
- const args = command.positionals.length > 0 ? ` ${command.positionals.join(" ")}` : "";
1668
- lines.push(` ${(command.name + args).padEnd(26)} ${command.summary}`);
1669
- }
1670
- lines.push("");
1671
- lines.push("Exit codes:");
1672
- for (const [code, meaning] of Object.entries(contract.exitCodes)) {
1673
- lines.push(` ${code} ${meaning}`);
1674
- }
1675
- lines.push("");
1676
- lines.push(`Presets (${contract.presets.length}): ${contract.presets.map((p) => p.name).join(", ")}`);
1677
- lines.push("");
1678
- lines.push("Artifacts:");
1679
- for (const artifact of contract.artifacts) {
1680
- lines.push(` ${artifact.name.padEnd(12)} ${artifact.default ? "on " : "off"} ${artifact.summary}`);
1681
- }
1682
- lines.push("");
1683
- lines.push("Options:");
1684
- for (const option of contract.options) {
1685
- const fallback = option.default === void 0 ? "" : ` [${JSON.stringify(option.default)}]`;
1686
- lines.push(` ${option.flag.padEnd(24)} ${option.appliesTo.padEnd(32)}${fallback}`);
1687
- lines.push(` ${"".padEnd(24)} ${option.summary}`);
1688
- }
1689
- lines.push("");
1690
- lines.push("MCP:");
1691
- lines.push(` command ${contract.mcp.command}`);
1692
- lines.push(` transport ${contract.mcp.transport}`);
1693
- lines.push(
1694
- ` versions modern ${contract.mcp.protocolVersions.modern.join(", ")} / legacy ${contract.mcp.protocolVersions.legacy.join(", ")}`
1695
- );
1696
- lines.push(
1697
- ` tools ${contract.mcp.tools.map((tool) => tool.readOnly ? tool.name : `${tool.name} (writes)`).join(", ")}`
1698
- );
1699
- lines.push(` prompts ${contract.mcp.prompts.map((prompt) => prompt.name).join(", ")}`);
1700
- lines.push(` resources ${contract.mcp.resources.join(", ")}`);
1701
- lines.push(` templates ${contract.mcp.resourceTemplates.join(", ")}`);
1702
- lines.push("");
1703
- lines.push("Safety:");
1704
- for (const note of contract.safety) lines.push(` - ${note}`);
1705
- lines.push("");
1706
- lines.push("Troubleshooting:");
1707
- for (const item of contract.troubleshooting) {
1708
- lines.push(` ${item.symptom}`);
1709
- lines.push(` cause: ${item.cause}`);
1710
- lines.push(` fix : ${item.fix}`);
1711
- }
1712
- lines.push("");
1713
- lines.push("This is the human rendering. Agents should use: describe --format json");
1714
- return lines.join("\n");
1715
- }
1716
- function buildAgentContract() {
1717
- return {
1718
- generator: GENERATOR_NAME,
1719
- package: PACKAGE_NAME,
1720
- version: GENERATOR_VERSION,
1721
- schemaVersion: SCHEMA_VERSION,
1722
- contractVersion: CONTRACT_VERSION,
1723
- summary: "Turns a repository into an LLM-ready snapshot: code packed into size-budgeted markdown parts, plus a manifest, a project tree, navigation and a secret audit. Auto-detects the project shape (framework, language, monorepo, docs, infra).",
1724
- requires: { node: ">=18.0.0", dependencies: ["typescript"] },
1725
- invocation: {
1726
- oneShot: `npx ${PACKAGE_NAME}@latest`,
1727
- installed: "npx codebase-snapshot",
1728
- bins: ["codebase-snapshot", "snapshot"],
1729
- notes: [
1730
- `The bare package name also works: npx ${PACKAGE_NAME} <command>.`,
1731
- "`codebase-snapshot` is the canonical name and the one to script against. `snapshot` is the short alias a global install provides; in a project that has the package installed, `npx snapshot` resolves the local bin first.",
1732
- `Pin an exact version \u2014 for example \`npx ${PACKAGE_NAME}@${GENERATOR_VERSION} --version\` \u2014 when you need the same build on every machine. A major range is not enough before 1.0: npm's caret on a 0.x version pins the minor, and 0.x minors are breaking by convention.`,
1733
- "Both bin names point at the same file. npm resolves a package by its bin entries, so they must stay aliases of one executable.",
1734
- "A bare run in a project with no configuration asks once, sets the project up and generates \u2014 but only at a terminal. With no TTY it exits 2 and names the alternatives, so an unattended caller must say what it wants: `generate` after `init --yes`, or `--autopilot`.",
1735
- "Human progress goes to stderr. With --format json the payload on stdout is pure JSON.",
1736
- "A failing run also writes pure JSON to stdout: { error: { message, exitCode } }. The exit code and the stderr line are unchanged."
1737
- ]
1738
- },
1739
- workflow: [
1740
- {
1741
- step: 1,
1742
- id: "verify",
1743
- run: `npx ${PACKAGE_NAME}@latest --version`,
1744
- // The requirement is the major version; the exact build is context. A
1745
- // floating tag may print a different patch today than next week, and an agent
1746
- // must not conclude that a working tool is broken because of a patch.
1747
- expect: `prints v${MAJOR_VERSION} or newer on stdout and exits 0 (this build is v${GENERATOR_VERSION}: compare the major version, not the patch)`,
1748
- notes: `If it prints an older major than this contract's, the @latest tag is behind the release: pin the exact version with \`npx ${PACKAGE_NAME}@${GENERATOR_VERSION} --version\` instead of retrying @latest. If it prints nothing, clear the npm cache and retry, or use \`npx -p <pkg> codebase-snapshot\`.`
1749
- },
1750
- {
1751
- step: 2,
1752
- id: "understand",
1753
- run: `npx ${PACKAGE_NAME}@latest describe --format json`,
1754
- expect: "the full contract as JSON: commands, options, presets, exit codes",
1755
- notes: "Read this before acting if you have no prior knowledge of the tool."
1756
- },
1757
- {
1758
- step: 3,
1759
- id: "configure",
1760
- run: `npx ${PACKAGE_NAME}@latest init --yes`,
1761
- expect: 'writes a commented config file listing every setting at its current value: snapshot.config.ts only when the running Node can strip types (>= 22.6) and the project is an ES module (`"type": "module"` in package.json); snapshot.config.mjs otherwise',
1762
- notes: "Non-interactive. The detected preset is chosen automatically; override with --preset <name>. Skip this step to run on built-in defaults."
1763
- },
1764
- {
1765
- step: 4,
1766
- id: "generate",
1767
- run: `npx ${PACKAGE_NAME}@latest generate`,
1768
- expect: "exit 0, and ./snapshot/ written with parts, reports and manifest.json"
1769
- },
1770
- {
1771
- step: 5,
1772
- id: "verify-output",
1773
- run: `npx ${PACKAGE_NAME}@latest validate`,
1774
- expect: "exit 0 means the snapshot matches the files on disk",
1775
- notes: "Exit 1 means drift or a damaged snapshot; re-run generate."
1776
- },
1777
- {
1778
- step: 6,
1779
- id: "consume",
1780
- run: "read ./snapshot/PROMPT.md first, then ./snapshot/parts/*.md, ./snapshot/manifest.json and ./snapshot/reports/audit.md",
1781
- expect: "the code, the index of what was included, and the risk findings",
1782
- notes: "manifest.json.files[] lists every included file with layer, kind, language, part and summary. manifest.skipped[] explains every file that was left out and why; manifest.incomplete[] lists every included file that is not present in full, with its missing line ranges. PROMPT.md is the instruction sheet for whoever reads the snapshot; it is rendered from the manifest, so it names this run's omissions rather than describing snapshots in general."
1783
- }
1784
- ],
1785
- commands: [
1786
- {
1787
- name: "generate",
1788
- aliases: ["default"],
1789
- summary: "Write the snapshot. This is the command you normally want. In a project with no configuration, a terminal asks once and sets the project up first; without a terminal it exits 2 and names `--autopilot` and `init --yes`.",
1790
- positionals: [],
1791
- exits: [0, 1, 2]
1792
- },
1793
- {
1794
- name: "validate",
1795
- aliases: ["check"],
1796
- summary: "Compare the snapshot on disk with the repository; exit 1 on drift. `check` is an alias of `validate`.",
1797
- positionals: [],
1798
- exits: [0, 1]
1799
- },
1800
- {
1801
- name: "report",
1802
- aliases: [],
1803
- summary: "Print snapshot health, layer metrics and the secret audit.",
1804
- positionals: [],
1805
- exits: [0, 1]
1806
- },
1807
- {
1808
- name: "setup",
1809
- aliases: [],
1810
- summary: "Everything a repository needs in one command, with defaults: write the config when there is none (an existing one is kept), add the npm scripts, devDependency and .gitignore entries, install dependencies with the project's package manager, then generate the snapshot. --no-install skips the install; --dry-run writes nothing.",
1811
- positionals: [],
1812
- exits: [0, 1, 2]
1813
- },
1814
- {
1815
- name: "init",
1816
- aliases: [],
1817
- summary: "Write a commented config file (snapshot.config.ts only when Node can strip types and the project is an ES module; snapshot.config.mjs otherwise), add the snapshot scripts and the devDependency, ignore the snapshot directories, and write a BRIEF.md scaffold for the owner half of PROMPT.md. No agent file is written. Interactive, or --yes for CI.",
1818
- positionals: [],
1819
- exits: [0, 1, 2]
1820
- },
1821
- {
1822
- name: "explain",
1823
- aliases: [],
1824
- summary: "Explain how one path would be treated: layer, kind, part, skip reason. Always exits 0 when it can report; read `included` and `reason` instead of the exit code.",
1825
- positionals: ["<path>"],
1826
- exits: [0]
1827
- },
1828
- {
1829
- name: "diff",
1830
- aliases: [],
1831
- summary: "Compare two snapshots (directories or manifest.json files).",
1832
- positionals: ["<before>", "<after>"],
1833
- exits: [0, 1]
1834
- },
1835
- {
1836
- name: "describe",
1837
- aliases: [],
1838
- summary: "Print this contract. --format json for machines, text for humans.",
1839
- positionals: [],
1840
- exits: [0]
1841
- },
1842
- {
1843
- name: "skill",
1844
- aliases: [],
1845
- summary: "Print the agent skill, or --install it into the tool registries this repository's agent reads (.claude/skills, .cursor/rules). Files it creates are added to .gitignore. It never writes AGENTS.md: that file belongs to the repository.",
1846
- positionals: [],
1847
- exits: [0, 1, 2]
1848
- },
1849
- {
1850
- name: "mcp",
1851
- aliases: [],
1852
- summary: "Serve this repository to an MCP client over stdio. The tools, resources and protocol versions it offers are listed in this contract's `mcp` block.",
1853
- positionals: [],
1854
- exits: [0, 2]
1855
- }
1856
- ],
1857
- exitCodes: {
1858
- "0": "success (and validate: no drift)",
1859
- "1": "drift detected, or generation refused/failed (nothing was written)",
1860
- "2": "usage error: unknown flag/command, bad value, wrong argument count"
1861
- },
1862
- options: [
1863
- {
1864
- flag: "--out-dir",
1865
- type: "string",
1866
- default: "snapshot",
1867
- appliesTo: optionAppliesTo("out-dir"),
1868
- summary: "Where the snapshot is written. Must not be the repo root or a directory the tool did not create."
1869
- },
1870
- {
1871
- flag: "--max-part-bytes",
1872
- type: "string",
1873
- default: 307200,
1874
- appliesTo: optionAppliesTo("max-part-bytes"),
1875
- summary: 'Byte budget per markdown part. Accepts "120k" / "1.5mb". Minimum 4096.'
1876
- },
1877
- {
1878
- flag: "--max-part-tokens",
1879
- type: "string",
1880
- default: "unset",
1881
- appliesTo: optionAppliesTo("max-part-tokens"),
1882
- summary: "Ceiling on a part expressed in tokens. Converted to bytes at 4 bytes/token and enforced as that byte ceiling \u2014 the estimate in manifest.parts[].estimatedTokens is not a hard bound, and a warning names any part whose estimate exceeds it. Minimum 1024."
1883
- },
1884
- {
1885
- flag: "--large-file-bytes",
1886
- type: "string",
1887
- default: 307200,
1888
- appliesTo: optionAppliesTo("large-file-bytes"),
1889
- summary: "Above this size a file gets a head/tail preview instead of the full body. It defaults to maxPartBytes and may not exceed it: a file between the two could not fit a part."
1890
- },
1891
- {
1892
- flag: "--max-monolith-bytes",
1893
- type: "string",
1894
- default: "unset",
1895
- appliesTo: optionAppliesTo("max-monolith-bytes"),
1896
- summary: "Skip the monolith artifacts when they would exceed this size."
1897
- },
1898
- {
1899
- flag: "--include-monolith",
1900
- type: "boolean",
1901
- default: false,
1902
- appliesTo: optionAppliesTo("include-monolith"),
1903
- summary: "Also write full-codebase.json and full-codebase.md."
1904
- },
1905
- {
1906
- flag: "--include-sensitive-files",
1907
- type: "boolean",
1908
- default: false,
1909
- appliesTo: optionAppliesTo("include-sensitive-files"),
1910
- summary: "Also emit .env / *.pem / .npmrc style files. Off by default; they are recorded as skipped."
1911
- },
1912
- {
1913
- flag: "--discovery",
1914
- type: "string",
1915
- default: "auto",
1916
- appliesTo: optionAppliesTo("discovery"),
1917
- summary: "How files are discovered: auto (git when usable), git (require git), walk (read .gitignore files directly, including nested ones; the escape hatch for a .git that cannot be listed)."
1918
- },
1919
- {
1920
- flag: "--attachment-slots",
1921
- type: "number",
1922
- default: "10",
1923
- appliesTo: optionAppliesTo("attachment-slots"),
1924
- summary: "Files the destination accepts in one message (0 = no limit). PROMPT.md plans the delivery against it: which parts to attach, what to leave behind, and the part budget that would merge them. It does not change the payload."
1925
- },
1926
- {
1927
- flag: "--brief",
1928
- type: "string",
1929
- default: "unset",
1930
- appliesTo: optionAppliesTo("brief"),
1931
- summary: "Path to the owner-written half of PROMPT.md: Stakes, The system, What came before, The bar and Calibration replace or extend the generated prose; any other heading is kept as Owner notes. The measured headings cannot be redefined; fenced code is content, not headings. The file is capped at 64 KiB. A missing file is an error and an edited file is config drift."
1932
- },
1933
- {
1934
- flag: "--prompt-task",
1935
- type: "string",
1936
- default: "audit",
1937
- appliesTo: optionAppliesTo("prompt-task"),
1938
- summary: "Which job the brief is written for: audit (default), review or explain. It changes the opening section, not the standard."
1939
- },
1940
- {
1941
- flag: "--max-parts",
1942
- type: "number",
1943
- default: "unset",
1944
- appliesTo: optionAppliesTo("max-parts"),
1945
- summary: "Experimental: grow the per-part budget until the snapshot has at most this many parts. The budget it settles on is recorded in manifest.budgets.maxPartBytes and may exceed maxPartBytes; a warning says so."
1946
- },
1947
- {
1948
- flag: "--skip-artifacts",
1949
- type: "string",
1950
- default: "unset",
1951
- appliesTo: optionAppliesTo("skip-artifacts"),
1952
- summary: "Comma-separated artifacts to omit (readme, manifest, parts, navigation, projectTree, audit, monolith)."
1953
- },
1954
- {
1955
- flag: "--only-artifacts",
1956
- type: "string",
1957
- default: "unset",
1958
- appliesTo: optionAppliesTo("only-artifacts"),
1959
- summary: "Write only these artifacts. Cannot be combined with --skip-artifacts."
1960
- },
1961
- {
1962
- flag: "--skeleton",
1963
- type: "boolean",
1964
- default: false,
1965
- appliesTo: optionAppliesTo("skeleton"),
1966
- summary: 'Replace function and method bodies with `{ /* ... */ }` in JS, JSX, TS and TSX files (including .mjs/.cjs; .d.ts files have nothing to collapse), keeping signatures and comments. The part records inclusionMode "signatures" for each file it touched.'
1967
- },
1968
- {
1969
- flag: "--sarif",
1970
- type: "boolean",
1971
- default: false,
1972
- appliesTo: optionAppliesTo("sarif"),
1973
- summary: "Also write reports/audit.sarif (SARIF 2.1.0) so a CI security gate can read the redaction findings. The matched value is never included."
1974
- },
1975
- {
1976
- flag: "--changed-since",
1977
- type: "string",
1978
- default: "unset",
1979
- appliesTo: optionAppliesTo("changed-since"),
1980
- summary: 'Snapshot only the files that differ from this git ref, plus untracked ones. Everything else is recorded in skipped[] with reason "unchanged". Requires a git checkout.'
1981
- },
1982
- {
1983
- flag: "--staged",
1984
- type: "boolean",
1985
- default: false,
1986
- appliesTo: optionAppliesTo("staged"),
1987
- summary: "Snapshot only the files staged in the index. The pre-commit counterpart of --changed-since."
1988
- },
1989
- {
1990
- flag: "--with-dependents",
1991
- type: "boolean",
1992
- default: false,
1993
- appliesTo: optionAppliesTo("with-dependents"),
1994
- summary: "Widen a changed-files scope by one hop: files that import a changed file are included too. Only meaningful with --changed-since or --staged."
1995
- },
1996
- {
1997
- flag: "--format",
1998
- type: "string",
1999
- default: "text",
2000
- // `optionAppliesTo` always returns the explicit slash list, so this is the same scoped form
2001
- // as every other option — no prose sentinel a machine consumer could misread.
2002
- appliesTo: optionAppliesTo("format"),
2003
- summary: 'Output format: "text" or "json". JSON goes to stdout, progress to stderr.'
2004
- },
2005
- {
2006
- flag: "--mode",
2007
- type: "string",
2008
- default: "generate",
2009
- appliesTo: optionAppliesTo("mode"),
2010
- summary: "Select the command when no command word is given. Values: generate, validate, check, report, init, setup, explain, diff, describe, skill, mcp. A command word and --mode must name the same command; a contradiction is a usage error (exit 2)."
2011
- },
2012
- {
2013
- flag: "--cwd",
2014
- type: "string",
2015
- default: "process.cwd()",
2016
- appliesTo: optionAppliesTo("cwd"),
2017
- summary: "Repository to operate on. Must be an existing directory."
2018
- },
2019
- {
2020
- flag: "--dry-run",
2021
- type: "boolean",
2022
- default: false,
2023
- appliesTo: optionAppliesTo("dry-run"),
2024
- summary: "Compute everything and print the result without writing."
2025
- },
2026
- {
2027
- flag: "--watch",
2028
- type: "boolean",
2029
- default: false,
2030
- appliesTo: optionAppliesTo("watch"),
2031
- summary: "Regenerate on every change until interrupted."
2032
- },
2033
- {
2034
- flag: "--no-config",
2035
- type: "boolean",
2036
- default: false,
2037
- appliesTo: optionAppliesTo("no-config"),
2038
- summary: "Ignore the config file and run on the built-in defaults."
2039
- },
2040
- {
2041
- flag: "--preset",
2042
- type: "string",
2043
- default: "detected",
2044
- appliesTo: optionAppliesTo("preset"),
2045
- summary: "Force a project preset instead of detecting one. Unknown names are a usage error."
2046
- },
2047
- {
2048
- flag: "--include",
2049
- type: "string",
2050
- default: "unset",
2051
- appliesTo: optionAppliesTo("include"),
2052
- summary: "Comma-separated allow-list of globs to record in the generated config."
2053
- },
2054
- {
2055
- flag: "--exclude",
2056
- type: "string",
2057
- default: "unset",
2058
- appliesTo: optionAppliesTo("exclude"),
2059
- summary: "Comma-separated globs to record in the generated config."
2060
- },
2061
- {
2062
- flag: "--yes",
2063
- type: "boolean",
2064
- default: false,
2065
- appliesTo: optionAppliesTo("yes"),
2066
- summary: "Accept every default without prompting. Required in a non-TTY."
2067
- },
2068
- {
2069
- flag: "--force",
2070
- type: "boolean",
2071
- default: false,
2072
- appliesTo: optionAppliesTo("force"),
2073
- summary: "Overwrite an existing config file."
2074
- },
2075
- {
2076
- flag: "--autopilot",
2077
- type: "boolean",
2078
- default: false,
2079
- appliesTo: optionAppliesTo("autopilot"),
2080
- summary: "Set the project up without asking, then generate: detect the preset, write the config and .gitignore, add the npm scripts and devDependency, install with the project's own package manager, generate. Autopilot chooses the preset and takes no --preset/--include/--exclude/--install-hook: those belong to `setup` or `init`. Never overwrites an existing config, and never prompts. Refuses an empty directory (exit 1); contradicts --no-config (exit 2)."
2081
- },
2082
- {
2083
- flag: "--install",
2084
- type: "boolean",
2085
- default: false,
2086
- appliesTo: optionAppliesTo("install"),
2087
- summary: "Write the skill into the repository instead of printing it."
2088
- },
2089
- {
2090
- flag: "--target",
2091
- type: "string",
2092
- default: "all",
2093
- appliesTo: optionAppliesTo("target"),
2094
- summary: 'Where to install: "claude", "cursor" or "all".'
2095
- },
2096
- {
2097
- flag: "--no-install",
2098
- type: "boolean",
2099
- default: false,
2100
- appliesTo: optionAppliesTo("no-install"),
2101
- summary: "Skip installing the dependency before generating: `setup`, or `generate --autopilot` (CI, offline, or a lockfile you do not want a package manager to touch)."
2102
- },
2103
- {
2104
- flag: "--install-hook",
2105
- type: "boolean",
2106
- default: false,
2107
- appliesTo: optionAppliesTo("install-hook"),
2108
- summary: "After writing the config, install a pre-commit hook that runs `validate`. An existing hook this tool did not write is left alone."
2109
- },
2110
- {
2111
- flag: "--no-update-check",
2112
- type: "boolean",
2113
- default: false,
2114
- appliesTo: optionAppliesTo("no-update-check"),
2115
- summary: "Skip the check for a newer published version. The check is already skipped when stdout is not a terminal, in CI, in a JSON invocation, and in `mcp`, which makes no network requests."
2116
- }
2117
- ],
2118
- presets: PRESETS.map((preset) => ({
2119
- name: preset.name,
2120
- priority: preset.priority,
2121
- recommendedBudget: preset.recommendedBudget ?? "300k",
2122
- excludes: preset.exclude ? [...preset.exclude] : []
2123
- })),
2124
- artifacts: ARTIFACT_NAMES.map((name) => ({
2125
- name,
2126
- default: ARTIFACT_DEFAULTS[name] ?? true,
2127
- summary: ARTIFACT_SUMMARY[name] ?? name
2128
- })),
2129
- config: {
2130
- fileNames: [
2131
- "snapshot.config.ts",
2132
- "snapshot.config.js",
2133
- "snapshot.config.mjs",
2134
- "snapshot.config.cjs",
2135
- "snapshot.config.json",
2136
- ".snapshotrc.json",
2137
- ".snapshotrc",
2138
- 'package.json \u2192 "snapshot" key'
2139
- ],
2140
- settings: [
2141
- { key: "outDir", type: "string", default: "snapshot", summary: "Snapshot output directory." },
2142
- { key: "tmpDir", type: "string", default: "snapshot.tmp", summary: "Scratch directory used for the atomic swap." },
2143
- { key: "branch", type: "string", default: "main", summary: "Branch recorded when git cannot report one." },
2144
- { key: "preset", type: "string", default: "detected", summary: "Force a preset. Unknown names are an error." },
2145
- { key: "maxPartBytes", type: "number | string", default: 307200, summary: "Per-part byte budget." },
2146
- { key: "maxPartTokens", type: "number | string | null", default: null, summary: "Per-part token ceiling; narrows maxPartBytes. Minimum 1024." },
2147
- { key: "skeleton", type: "boolean", default: false, summary: "Collapse function bodies to `{ /* ... */ }` in TS, JS, TSX and JSX files." },
2148
- { key: "sarif", type: "boolean", default: false, summary: "Also write reports/audit.sarif." },
2149
- { key: "changedSince", type: "string | null", default: null, summary: "Snapshot only files that differ from this git ref." },
2150
- { key: "staged", type: "boolean", default: false, summary: "Snapshot only files staged in the index." },
2151
- { key: "withDependents", type: "boolean", default: false, summary: "With a changed-files scope, also include one hop of importers." },
2152
- { key: "largeFileBytes", type: "number | string", default: 307200, summary: "Preview threshold for large files; defaults to maxPartBytes and may not exceed it." },
2153
- { key: "previewHeadLines", type: "number", default: 80, summary: "Lines kept from the head of a large file." },
2154
- { key: "previewTailLines", type: "number", default: 40, summary: "Lines kept from the tail of a large file." },
2155
- { key: "includeMonolith", type: "boolean", default: false, summary: "Also write the single-file monolith." },
2156
- { key: "maxMonolithBytes", type: "number | string | null", default: null, summary: "Skip the monolith above this size." },
2157
- { key: "includeSensitiveFiles", type: "boolean", default: false, summary: "Emit .env / *.pem / credential files." },
2158
- { key: "include", type: "string[]", default: "[]", summary: "Allow-list of globs; empty means everything." },
2159
- { key: "excludePatterns", type: "string[]", default: "[]", summary: "Extra exclude globs." },
2160
- { key: "brief", type: "string", default: "unset", summary: "Path to the owner-written half of PROMPT.md. Recognised headings: Stakes, The system, What came before, The bar, Calibration; unknown headings are kept as Owner notes; measured headings are refused. The file is digested, so editing it is drift." },
2161
- { key: "promptTask", type: "string", default: "audit", summary: "Which job the brief is written for: audit, review or explain. The standard and the coverage duty are the same in all three." },
2162
- { key: "maxParts", type: "number | null", default: null, summary: "Experimental: the most parts a snapshot may have. The per-part budget grows to fit, up to the run's own needs; the effective ceiling is recorded in manifest.budgets.maxPartBytes and may exceed maxPartBytes." },
2163
- { key: "attachmentSlots", type: "number", default: 10, summary: "Files the destination accepts in one message (0 = no limit); PROMPT.md plans the delivery to fit. It does not change the payload, and it is not part of the config digest." },
2164
- { key: "discovery", type: '"auto" | "git" | "walk"', default: "auto", summary: "How files are discovered; `walk` scans the tree and reads .gitignore directly when a .git directory cannot be listed." },
2165
- { key: "artifacts", type: "object", default: "all on except monolith", summary: "Per-artifact opt-out." },
2166
- { key: "budgets", type: "object", default: "{ default, byLayer }", summary: "Per-layer byte budgets." },
2167
- { key: "layersMode", type: '"merge" | "replace"', default: "merge", summary: "Whether custom layers extend or replace the preset's." },
2168
- { key: "layers", type: "array", default: "preset layers", summary: "Custom layer rules (glob or RegExp)." },
2169
- { key: "kinds", type: "array", default: "preset kinds", summary: "Custom kind rules." },
2170
- { key: "secrets", type: "object", default: "{}", summary: "Custom secret patterns, or disable the defaults." },
2171
- { key: "secretRules", type: "array", default: "[]", summary: "Full secret-rule list: the library spelling of secrets.customPatterns. The built-ins are prepended unless secrets.disableDefaultPatterns is set." },
2172
- { key: "hooks", type: "object", default: "{}", summary: "afterGenerate(manifest) runs after a successful generate." }
2173
- ]
2174
- },
2175
- output: {
2176
- layout: [
2177
- "<outDir>/README.md",
2178
- "<outDir>/PROMPT.md",
2179
- "<outDir>/manifest.json",
2180
- "<outDir>/parts/part-NNN.md",
2181
- "<outDir>/reports/project-tree.md",
2182
- "<outDir>/reports/navigation.md",
2183
- "<outDir>/reports/audit.md",
2184
- "<outDir>/.codebase-snapshot (ownership marker, always written)"
2185
- ],
2186
- notes: [
2187
- "Parts are ordered and budget-limited; a file that cannot fit one part is emitted as a head/tail preview, and every file not present in full is listed in manifest.json incomplete[] with the missing line ranges.",
2188
- "manifest.json.files[] carries relativePath, layer, kind, language, part, inclusionMode, truncationReason, omittedRanges and hash; manifest.json.incomplete[] lists every file not present in full; `summary` is conditional \u2014 it is absent for languages with no structural summary, and `summaryOmitted: true` marks a summary dropped to fit the part budget; encoding appears when the file was not plain UTF-8.",
2189
- "indexes.imports.byFile includes previewed files (their import specifiers are still extracted); such an entry carries `exportsOmitted: true` instead of pretending it exports nothing.",
2190
- "validate re-checks manifest.incomplete[] against files[] and refuses a manifest whose two statements of what is missing disagree.",
2191
- "manifest.skipped[] carries the path and the exact reason it was excluded.",
2192
- "PROMPT.md is rendered from the manifest of the run that wrote it \u2014 its parts, partial files, skip tallies and fingerprint are that run's \u2014 and manifest.artifacts.prompt records its digest, so an edited prompt fails validate.",
2193
- `The output directory is replaced atomically; ${MIN_MAX_PART_BYTES} bytes is the smallest legal budget.`
2194
- ]
2195
- },
2196
- safety: [
2197
- "Sensitive files (.env, *.pem, .npmrc, .ssh/, .tfstate) are excluded by default and listed in manifest.skipped[].",
2198
- "Secret-shaped strings in ordinary source files are redacted in the emitted parts.",
2199
- "The tool refuses to replace an outDir that it did not create, so a mistyped outDir cannot delete source code.",
2200
- "Nothing is ever written above the repository root; --out-dir may not be the root or an ancestor."
2201
- ],
2202
- mcp: {
2203
- command: `npx ${PACKAGE_NAME} mcp`,
2204
- transport: "stdio",
2205
- protocolVersions: {
2206
- modern: [...MODERN_PROTOCOL_VERSIONS],
2207
- legacy: [...LEGACY_PROTOCOL_VERSIONS],
2208
- default: DEFAULT_LEGACY_PROTOCOL_VERSION
2209
- },
2210
- tools: buildTools().map((tool) => ({
2211
- name: tool.name,
2212
- title: tool.title,
2213
- summary: tool.description,
2214
- readOnly: tool.annotations.readOnlyHint,
2215
- parameters: Object.keys(tool.inputSchema.properties),
2216
- required: tool.inputSchema.required ?? []
2217
- })),
2218
- prompts: buildPrompts().map((prompt) => ({
2219
- name: prompt.name,
2220
- summary: prompt.description,
2221
- arguments: prompt.arguments.map((argument) => argument.name)
2222
- })),
2223
- resources: [...STATIC_RESOURCE_URIS],
2224
- resourceTemplates: [...RESOURCE_TEMPLATE_URIS],
2225
- notes: [
2226
- "stdout carries JSON-RPC messages only; every note and log line goes to stderr.",
2227
- "The server speaks both protocol eras: the legacy `initialize` handshake and the stateless revision, which is detected from `server/discover` or from per-request `_meta`.",
2228
- "Everything it can do is a subset of the CLI. It never installs packages and never writes a config file.",
2229
- "A `root` argument may name a sub-directory of the server's --cwd, and nothing outside it is readable."
2230
- ]
2231
- },
2232
- troubleshooting: [
2233
- {
2234
- symptom: "Command prints nothing and exits 0",
2235
- cause: "A stale global install of this package (often a leftover `npm link`) is shadowing npx: npm runs the global binary instead of installing the published one.",
2236
- fix: "Check `npm ls -g --depth=0` for codebase-snapshot and remove it with `npm rm -g codebase-snapshot`. If it is not installed globally, clear the npx cache with `npm cache clean --force` and retry."
2237
- },
2238
- {
2239
- symptom: "Exit 1 with 'Refusing to replace outDir'",
2240
- cause: "The outDir exists and contains files this tool did not write.",
2241
- fix: "Choose a new/empty --out-dir, or delete the existing directory yourself."
2242
- },
2243
- {
2244
- symptom: "Exit 1 with 'The config file could not be read'",
2245
- cause: "snapshot.config.* exists but does not parse.",
2246
- fix: "Fix the syntax, or delete the config to use the defaults."
2247
- },
2248
- {
2249
- symptom: "Exit 1 from validate",
2250
- cause: "The snapshot no longer matches the files on disk.",
2251
- fix: "Re-run generate."
2252
- },
2253
- {
2254
- symptom: "A directory you expected is missing from the snapshot",
2255
- cause: "It is excluded by the preset, by default ignores, or by your own globs.",
2256
- fix: "Run `explain <path>`; manifest.skipped[] also records the reason for every file."
2257
- }
2258
- ]
2259
- };
2260
- }
2261
-
2262
- // src/agent/skill.ts
2263
- var PACKAGE_NAME2 = "codebase-snapshot";
2264
- var MAJOR_VERSION2 = GENERATOR_VERSION.split(".")[0];
2265
- var SKILL_NAME = "codebase-snapshot";
2266
- function renderSkill() {
2267
- return `---
2268
- name: ${SKILL_NAME}
2269
- description: Create an LLM-ready snapshot of a repository (size-budgeted markdown parts, a JSON manifest, project tree, navigation and a secret audit) when a whole codebase has to be read, summarized or handed to a model that cannot clone it. Use when asked to snapshot a codebase, prepare repository context, or analyze a project's structure.
2270
- version: ${GENERATOR_VERSION}
2271
- ---
2272
-
2273
- # codebase-snapshot
2274
-
2275
- Turns a repository into an LLM-ready snapshot under \`./snapshot/\`: code packed into
2276
- size-budgeted markdown parts, plus a manifest that indexes every file, a project tree, a
2277
- navigation index and a secret audit.
2278
-
2279
- Use it when you need to understand a whole repository, or produce repository context for
2280
- another model, and reading files one by one would not fit in context.
2281
-
2282
- ## Before you start
2283
-
2284
- This tool is a Node CLI. It needs **Node.js 18 or newer**. You do not need to install it
2285
- globally, and you do not need to clone anything.
2286
-
2287
- **Pin a version** \u2014 \`npx ${PACKAGE_NAME2}@${GENERATOR_VERSION} <command>\` \u2014 when you
2288
- need the same version on every machine. The bare package name works too: this package ships
2289
- one executable file, published under two names (\`codebase-snapshot\` and \`snapshot\`), which is
2290
- what lets npm pick it. A global install gives the short command \`snapshot\`; inside a project
2291
- that has this package installed, \`npx snapshot\` resolves the local copy first. If a command
2292
- exits 0 printing nothing, the executable was not resolved \u2014 clear the npm cache and retry;
2293
- do not assume the repository is broken.
2294
-
2295
- ## Step by step
2296
-
2297
- 1. **Verify the tool.** Run \`npx ${PACKAGE_NAME2}@latest --version\`. Expect \`v${MAJOR_VERSION2}\` or
2298
- newer on stdout \u2014 compare the major version, not the patch, because the
2299
- \`@latest\` tag can lag this release. If what it prints is older, pin the exact
2300
- release (\`@${GENERATOR_VERSION}\`) instead of retrying. Empty output means you hit the
2301
- bare-spec problem above.
2302
-
2303
- 2. **Read the contract, not the prose.** Run
2304
- \`npx ${PACKAGE_NAME2}@latest describe --format json\`. It returns the full machine
2305
- contract: every command, every option with its default, the exit-code meanings, the
2306
- 25 project presets, the artifact list, the config settings and a troubleshooting
2307
- table. Read it before you make decisions; do not guess option names.
2308
-
2309
- 3. **Look before you leap (optional but cheap).** To see how a specific file or directory
2310
- would be treated, run \`npx ${PACKAGE_NAME2}@latest explain <path>\`. It reports the
2311
- layer, kind, language, target part, and the exact reason a path would be skipped.
2312
- \`--format json\` if you want to parse it.
2313
-
2314
- 3b. **One command, if the user just wants it working.** \`npx ${PACKAGE_NAME2}@latest setup\`
2315
- does steps 4\u20136 in one go with defaults: it writes the config (an existing one is kept),
2316
- adds the npm scripts and the devDependency, installs with the project's package manager,
2317
- and generates. Use \`--no-install\` when the machine is offline or the user does not want
2318
- their lockfile touched. \`--autopilot\` does exactly the same thing from the default
2319
- command (\`npx ${PACKAGE_NAME2}@latest --autopilot\`) and is the form to reach for when a
2320
- single invocation must both set the project up and produce the snapshot. Prefer the
2321
- explicit steps below when you need to control any of those, or when something fails and
2322
- you want to see which part.
2323
-
2324
- 4. **Configure (recommended).** Run \`npx ${PACKAGE_NAME2}@latest init --yes\`. It detects
2325
- the project shape, then writes a commented config file listing **every** setting at its
2326
- current value. The filename depends on the project: \`snapshot.config.ts\` only when
2327
- the running Node can strip types (Node >= 22.6) **and** the project is an ES module
2328
- (\`"type": "module"\` in package.json); otherwise \`snapshot.config.mjs\`. Pass
2329
- \`--preset <name>\` only if detection is wrong; the preset names are in the contract.
2330
- Skipping this step is safe **at a terminal**: the first \`generate\` asks once, can write
2331
- the config for you and then generates. Unattended, a \`generate\` with no config exits 2 \u2014
2332
- run this step, or \`--autopilot\`, or pass \`--no-config\` to run deliberately on the
2333
- built-in defaults.
2334
-
2335
- 5. **Generate.** Run \`npx ${PACKAGE_NAME2}@latest generate\`. Expect exit 0 and a
2336
- \`./snapshot/\` directory. If you need a different location use \`--out-dir <path>\`; if
2337
- you need smaller or larger parts use \`--max-part-bytes 120k\`.
2338
-
2339
- 6. **Verify.** Run \`npx ${PACKAGE_NAME2}@latest validate\`. Exit 0 means the snapshot
2340
- matches the files on disk. Exit 1 means drift \u2014 re-run step 5.
2341
-
2342
- 7. **Read the output in this order:**
2343
- - \`snapshot/parts/part-*.md\` \u2014 the code itself. Each file carries one \`- Meta:\` line
2344
- (layer/kind, language, inclusion, size) and, only when the body is **not** the whole
2345
- file, a structural summary (imports, exports, classes, functions). A full file has no
2346
- summary line, because the summary would repeat the code three lines below it \u2014 read
2347
- \`manifest.json\` for it. A summary dropped to fit the budget appears as a
2348
- \`Summary: (omitted \u2026)\` line.
2349
- - \`snapshot/manifest.json\` \u2014 the index. \`files[]\` has \`relativePath\`, \`layer\`,
2350
- \`kind\`, \`language\`, \`part\`, \`inclusionMode\`, \`hashSha256\` and the structural
2351
- \`summary\`, plus \`encoding\` when the file was not plain UTF-8. \`summary\` is
2352
- **optional**: it is absent for languages with no structural summary, and
2353
- \`summaryOmitted: true\` marks one dropped for size, and the reason in \`summaryOmittedReason\` says which rule \u2014 never assume it
2354
- exists. The per-file \`hashSha256\` is only here and in the manifest; it is not printed
2355
- into the parts.
2356
- \`skipped[]\` records every excluded file **and why**. The top-level \`incomplete[]\` records every included
2357
- file whose body is not the whole file, with its reason and omittedRanges: ask that list,
2358
- not the footer of a part, when the question is whether anything was lost. Prefer querying this over
2359
- re-reading the parts.
2360
- - \`snapshot/reports/audit.md\` \u2014 secrets found, large files, parse diagnostics, git
2361
- state. Read this before you quote code back to a user.
2362
- - \`snapshot/reports/project-tree.md\` and \`navigation.md\` \u2014 structure and cross-links.
2363
- - \`snapshot/PROMPT.md\` \u2014 the instruction sheet to hand to the model that receives the
2364
- snapshot: paste it with the parts. It is rendered from this run's manifest and names the
2365
- parts, the partial files and the fingerprint, so do not rewrite it by hand \u2014 \`validate\`
2366
- fails when it was edited.
2367
-
2368
- ## Project types
2369
-
2370
- Detection is automatic and covers Next.js, Nuxt, SvelteKit, Remix, Astro, Angular, Solid,
2371
- Vue+React with Vite, Nest, Express/Fastify/Koa, any Node library, monorepos, Django,
2372
- FastAPI/Flask, plain Python, Go, Rust, Java/Spring, .NET, PHP/Laravel, Ruby/Rails,
2373
- Terraform/Docker infra, docs-only repositories, and a generic fallback. It sets sensible
2374
- layers, kinds, ecosystem ignore patterns and a recommended part budget. For non-TypeScript
2375
- languages it extracts imports, exports, classes and functions structurally; Vue, Svelte and
2376
- Astro script blocks go through the real TypeScript compiler. You do not need to configure
2377
- any of this to get a good first snapshot.
2378
-
2379
- ## Things that will surprise you
2380
-
2381
- - **Sensitive files are excluded by default** (\`.env\`, \`*.pem\`, \`.npmrc\`, \`.ssh/\`,
2382
- \`.tfstate\`) and are listed in \`manifest.skipped[]\`. Add \`--include-sensitive-files\` only
2383
- if the user asks for them explicitly.
2384
- - **Secret-shaped strings inside normal source files are redacted** in the emitted parts.
2385
- If the user needs the raw value, say so rather than working around it.
2386
- - **The output directory is owned by the tool.** It is replaced atomically, and the tool
2387
- refuses to replace a directory it did not create. Never point \`--out-dir\` at source
2388
- code; if you see \`Refusing to replace outDir\`, choose a new directory rather than
2389
- deleting anything.
2390
- - **Exit 2 is a usage error**, not a failure of the repository. Re-read the contract
2391
- before retrying.
2392
- - **A first run refuses rather than guessing.** In a project with no config and no previous
2393
- snapshot, \`generate\` without a terminal exits 2 instead of silently using defaults. That
2394
- is deliberate: say which set-up you want (\`--autopilot\`, \`init --yes\`, or \`--no-config\`)
2395
- rather than retrying the same command.
2396
- - **\`--format json\` keeps stdout pure.** Progress goes to stderr, so \`stdout\` is safe to
2397
- pipe into a JSON parser.
2398
-
2399
- ## Making this available to other agents
2400
-
2401
- Run \`npx ${PACKAGE_NAME2}@latest skill --install\`. It writes this skill into the two
2402
- registries agent tools read by name \u2014 \`.claude/skills/${SKILL_NAME}/SKILL.md\` and
2403
- \`.cursor/rules/${SKILL_NAME}.mdc\` \u2014 and appends exactly those files to \`.gitignore\`, so the
2404
- install leaves nothing untracked. It is idempotent, and it refuses a target that resolves
2405
- outside the repository, so a linked \`.claude/\` cannot be used to write elsewhere.
2406
-
2407
- It never writes \`AGENTS.md\`. That file is the repository's own agent contract \u2014 build
2408
- commands, conventions, house rules \u2014 and this tool has no business editing it. If you want
2409
- this skill in there, run \`npx ${PACKAGE_NAME2}@latest skill\` and paste the text yourself: the
2410
- diff, and the commit, are then yours.
2411
-
2412
- ## When the client speaks MCP
2413
-
2414
- If the agent runs inside an MCP client, \`npx ${PACKAGE_NAME2}@latest mcp\` serves this repository
2415
- as eight tools over stdio instead of shelling out. Its reads come from the snapshot rather than
2416
- the working tree, so excluded files and redacted values never reach the context. Use
2417
- \`snapshot_locate\` before \`snapshot_read\`, and \`snapshot_validate\` before trusting a snapshot
2418
- from an earlier session.
2419
- `;
2420
- }
2421
-
2422
- // src/mcp/resources.ts
2423
- var MAX_RESOURCE_BYTES = 512 * 1024;
2424
- var ResourceTooLargeError = class extends Error {
2425
- constructor(uri, bytes, limit, message) {
2426
- super(message);
2427
- this.uri = uri;
2428
- this.bytes = bytes;
2429
- this.limit = limit;
2430
- this.name = "ResourceTooLargeError";
2431
- }
2432
- uri;
2433
- bytes;
2434
- limit;
2435
- };
2436
- var ResourceNotFoundError = class extends Error {
2437
- constructor(uri, message) {
2438
- super(message);
2439
- this.uri = uri;
2440
- this.name = "ResourceNotFoundError";
2441
- }
2442
- uri;
2443
- };
2444
- function refuseTooLarge(uri, bytes, advice) {
2445
- throw new ResourceTooLargeError(
2446
- uri,
2447
- bytes,
2448
- MAX_RESOURCE_BYTES,
2449
- `${uri} is ${formatBytes2(bytes)}, above the ${formatBytes2(MAX_RESOURCE_BYTES)} single-read limit, so it was not returned. ${advice}`
2450
- );
2451
- }
2452
- function ensureSingleRead(uri, text, advice) {
2453
- const bytes = Buffer.byteLength(text, "utf8");
2454
- if (bytes > MAX_RESOURCE_BYTES) refuseTooLarge(uri, bytes, advice);
2455
- return text;
2456
- }
2457
- var MANIFEST_ADVICE = "Cutting a JSON document at the limit leaves invalid JSON, so this resource is never truncated. Use the snapshot_locate, snapshot_read and snapshot_status tools instead \u2014 they read the manifest directly \u2014 or read manifest.json from the snapshot directory.";
2458
- var PART_ADVICE = "A part cut at the limit is a fragment of a file, not the file. Use snapshot_locate to find the file inside this part that you need, then snapshot_read for a bounded window of it.";
2459
- var PROMPT_URI = "snapshot://prompt";
2460
- var PROMPT_ADVICE = "PROMPT.md is written whole and never truncated; regenerate it with snapshot_generate, then read it from the snapshot directory.";
2461
- var REPORT_ADVICE = "A report cut at the limit would look complete and would not be. Read it from the snapshot directory instead: the file on disk is complete.";
2462
- var PART_URI = /^snapshot:\/\/parts\/(\d+)$/;
2463
- var REPORT_URIS = /* @__PURE__ */ new Map([
2464
- ["snapshot://reports/audit", { file: "audit.md", title: "Secret audit and risk findings" }],
2465
- ["snapshot://reports/tree", { file: "project-tree.md", title: "Project tree" }],
2466
- ["snapshot://reports/navigation", { file: "navigation.md", title: "Navigation index" }]
2467
- ]);
2468
- function formatBytes2(bytes) {
2469
- if (bytes < 1024) return `${bytes} B`;
2470
- if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} kB`;
2471
- return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
2472
- }
2473
- async function workspaceFor(context) {
2474
- const root = resolveRoot(void 0, context);
2475
- if (!root.ok) return { error: root.message };
2476
- const opened = await openWorkspace(root.root, {}, void 0, { allowExecutableConfig: false });
2477
- if (!opened.ok) return { error: opened.message };
2478
- return opened.workspace;
2479
- }
2480
- function readFileIfPresent(file) {
2481
- try {
2482
- return fs.readFileSync(file, "utf8");
2483
- } catch {
2484
- return null;
2485
- }
2486
- }
2487
- function buildResourceProvider() {
2488
- return {
2489
- async list(context) {
2490
- const resources = [
2491
- {
2492
- uri: "snapshot://manifest",
2493
- name: "manifest",
2494
- title: "Snapshot manifest",
2495
- description: "Every file in the snapshot with its layer, kind, language, part and hash, plus the reason each excluded file was excluded. A manifest larger than 512 kB is refused with its size instead of truncated: cut JSON does not parse. Use snapshot_locate, snapshot_read and snapshot_status for a large repository.",
2496
- mimeType: "application/json"
2497
- },
2498
- {
2499
- uri: "snapshot://contract",
2500
- name: "contract",
2501
- title: "Tool contract",
2502
- description: "The machine-readable description of the codebase-snapshot command line.",
2503
- mimeType: "application/json"
2504
- },
2505
- {
2506
- uri: "snapshot://skill",
2507
- name: "skill",
2508
- title: "Agent skill",
2509
- description: "Usage guidance for an agent working with this tool.",
2510
- mimeType: "text/markdown"
2511
- },
2512
- {
2513
- uri: PROMPT_URI,
2514
- name: "prompt",
2515
- title: "Snapshot brief",
2516
- description: "The brief for this snapshot: the job, what the snapshot contains, what it omits, the history it was built from and the standard the answer is held to. Read this before the parts; it names which part holds which file.",
2517
- mimeType: "text/markdown"
2518
- }
2519
- ];
2520
- for (const [uri, report] of REPORT_URIS) {
2521
- resources.push({
2522
- uri,
2523
- name: report.file.replace(/\.md$/, ""),
2524
- title: report.title,
2525
- description: `${report.title} from the most recent snapshot. A report larger than 512 kB is refused rather than truncated; read the file from the snapshot directory.`,
2526
- mimeType: "text/markdown"
2527
- });
2528
- }
2529
- const workspace = await workspaceFor(context);
2530
- if ("error" in workspace) return resources;
2531
- const read = readManifest(workspace);
2532
- if (!read.ok) return resources;
2533
- for (const part of read.manifest.parts) {
2534
- const readable = part.byteSize <= MAX_RESOURCE_BYTES;
2535
- resources.push({
2536
- uri: `snapshot://parts/${part.index}`,
2537
- name: `part-${String(part.index).padStart(3, "0")}`,
2538
- title: `Part ${part.index} (${part.fileCount} files, ${formatBytes2(part.byteSize)})`,
2539
- description: `Part ${part.index} of ${read.manifest.parts.length}: ${part.fileCount} file(s), ${part.lines} line(s), ${formatBytes2(part.byteSize)}.` + (readable ? "" : ` Above the ${formatBytes2(MAX_RESOURCE_BYTES)} single-read limit, so this resource is refused rather than truncated; use snapshot_locate and snapshot_read.`),
2540
- mimeType: "text/markdown"
2541
- });
2542
- }
2543
- return resources;
2544
- },
2545
- templates() {
2546
- return [
2547
- {
2548
- uriTemplate: "snapshot://parts/{index}",
2549
- name: "part",
2550
- title: "Snapshot part",
2551
- description: "One budgeted part of the snapshot, by its 1-based index.",
2552
- mimeType: "text/markdown"
2553
- }
2554
- ];
2555
- },
2556
- async read(uri, context) {
2557
- if (uri === "snapshot://contract") {
2558
- const contract = buildAgentContract();
2559
- return {
2560
- uri,
2561
- mimeType: "application/json",
2562
- text: ensureSingleRead(
2563
- uri,
2564
- JSON.stringify(contract, null, 2),
2565
- "Run 'codebase-snapshot describe --format json' for the complete contract."
2566
- )
2567
- };
2568
- }
2569
- if (uri === "snapshot://skill") {
2570
- return {
2571
- uri,
2572
- mimeType: "text/markdown",
2573
- text: ensureSingleRead(
2574
- uri,
2575
- renderSkill(),
2576
- "Print it with 'codebase-snapshot skill'."
2577
- )
2578
- };
2579
- }
2580
- const workspace = await workspaceFor(context);
2581
- if ("error" in workspace) return null;
2582
- if (uri === PROMPT_URI) {
2583
- const text = readFileIfPresent(
2584
- path.resolve(workspace.root, workspace.config.outDir, "PROMPT.md")
2585
- );
2586
- if (text === null) {
2587
- throw new ResourceNotFoundError(
2588
- uri,
2589
- "This snapshot contains no PROMPT.md: the prompt artifact was disabled (artifacts.prompt = false or --skip-artifacts prompt), or nothing has been generated yet. Run snapshot_generate first."
2590
- );
2591
- }
2592
- return { uri, mimeType: "text/markdown", text: ensureSingleRead(uri, text, PROMPT_ADVICE) };
2593
- }
2594
- const report = REPORT_URIS.get(uri);
2595
- if (report) {
2596
- const text = readFileIfPresent(
2597
- path.resolve(workspace.root, workspace.config.outDir, "reports", report.file)
2598
- );
2599
- if (text === null) {
2600
- throw new ResourceNotFoundError(
2601
- uri,
2602
- "This snapshot contains no " + report.file + ": that report was disabled, or nothing has been generated yet. Run snapshot_generate first."
2603
- );
2604
- }
2605
- return { uri, mimeType: "text/markdown", text: ensureSingleRead(uri, text, REPORT_ADVICE) };
2606
- }
2607
- if (uri === "snapshot://manifest") {
2608
- const read = readManifest(workspace);
2609
- if (!read.ok) return null;
2610
- const text = readFileIfPresent(read.file) ?? JSON.stringify(read.manifest, null, 2);
2611
- return { uri, mimeType: "application/json", text: ensureSingleRead(uri, text, MANIFEST_ADVICE) };
2612
- }
2613
- const partMatch = PART_URI.exec(uri);
2614
- if (partMatch) {
2615
- const read = readManifest(workspace);
2616
- if (!read.ok) return null;
2617
- const index = Number(partMatch[1]);
2618
- const part = read.manifest.parts.find((candidate) => candidate.index === index);
2619
- if (!part) return null;
2620
- const partPath = partPathFor(workspace, part.filename);
2621
- if (partPath === null) return null;
2622
- let partBytes;
2623
- try {
2624
- partBytes = fs.statSync(partPath).size;
2625
- } catch {
2626
- return null;
2627
- }
2628
- if (partBytes > MAX_RESOURCE_BYTES) refuseTooLarge(uri, partBytes, PART_ADVICE);
2629
- const text = readFileIfPresent(partPath);
2630
- if (text === null) return null;
2631
- return { uri, mimeType: "text/markdown", text: ensureSingleRead(uri, text, PART_ADVICE) };
2632
- }
2633
- return null;
2634
- }
2635
- };
2636
- }
2637
-
2638
- // src/mcp/schema.ts
2639
- function validateArguments(schema, value) {
2640
- if (value === void 0) value = {};
2641
- if (!isJsonObject(value)) return ["arguments must be a JSON object"];
2642
- const problems = [];
2643
- const known = new Set(Object.keys(schema.properties));
2644
- for (const key of Object.keys(value)) {
2645
- if (!known.has(key) && schema.additionalProperties !== true) {
2646
- const allowed = [...known].sort().join(", ");
2647
- problems.push(`unknown argument "${key}" (accepted: ${allowed || "none"})`);
2648
- }
2649
- }
2650
- for (const required of schema.required ?? []) {
2651
- if (value[required] === void 0) problems.push(`missing required argument "${required}"`);
2652
- }
2653
- for (const [key, propertySchema] of Object.entries(schema.properties)) {
2654
- const argument = value[key];
2655
- if (argument === void 0) continue;
2656
- problems.push(...checkValue(key, propertySchema, argument));
2657
- }
2658
- return problems;
2659
- }
2660
- function checkValue(path4, schema, value) {
2661
- if (schema.enum && !schema.enum.includes(value)) {
2662
- return [`"${path4}" must be one of: ${schema.enum.join(", ")}`];
2663
- }
2664
- switch (schema.type) {
2665
- case "string": {
2666
- if (typeof value !== "string") return [`"${path4}" must be a string`];
2667
- const problems = [];
2668
- if (schema.minLength !== void 0 && value.length < schema.minLength) {
2669
- problems.push(`"${path4}" must be at least ${schema.minLength} character(s)`);
2670
- }
2671
- if (schema.maxLength !== void 0 && value.length > schema.maxLength) {
2672
- problems.push(`"${path4}" must be at most ${schema.maxLength} character(s)`);
2673
- }
2674
- return problems;
2675
- }
2676
- case "number":
2677
- case "integer": {
2678
- if (typeof value !== "number" || Number.isNaN(value)) {
2679
- return [`"${path4}" must be a number`];
2680
- }
2681
- if (schema.type === "integer" && !Number.isInteger(value)) {
2682
- return [`"${path4}" must be an integer`];
2683
- }
2684
- const problems = [];
2685
- if (schema.minimum !== void 0 && value < schema.minimum) {
2686
- problems.push(`"${path4}" must be >= ${schema.minimum}`);
2687
- }
2688
- if (schema.maximum !== void 0 && value > schema.maximum) {
2689
- problems.push(`"${path4}" must be <= ${schema.maximum}`);
2690
- }
2691
- return problems;
2692
- }
2693
- case "boolean":
2694
- return typeof value === "boolean" ? [] : [`"${path4}" must be a boolean`];
2695
- case "array": {
2696
- if (!Array.isArray(value)) return [`"${path4}" must be an array`];
2697
- if (!schema.items) return [];
2698
- const problems = [];
2699
- value.forEach((item, index) => {
2700
- problems.push(...checkValue(`${path4}[${index}]`, schema.items, item));
2701
- });
2702
- return problems;
2703
- }
2704
- case "object":
2705
- return isJsonObject(value) ? [] : [`"${path4}" must be an object`];
2706
- default:
2707
- return [];
2708
- }
2709
- }
2710
- function applyDefaults(schema, value) {
2711
- const out = { ...value };
2712
- for (const [key, propertySchema] of Object.entries(schema.properties)) {
2713
- if (out[key] === void 0 && propertySchema.default !== void 0) {
2714
- out[key] = propertySchema.default;
2715
- }
2716
- }
2717
- return out;
2718
- }
2719
- function coerceNumericStrings(schema, value) {
2720
- const out = { ...value };
2721
- for (const [key, propertySchema] of Object.entries(schema.properties)) {
2722
- const raw = out[key];
2723
- if (typeof raw !== "string") continue;
2724
- if (propertySchema.type !== "number" && propertySchema.type !== "integer") continue;
2725
- if (raw.trim().length === 0) continue;
2726
- const parsed = Number(raw);
2727
- if (Number.isFinite(parsed)) out[key] = parsed;
2728
- }
2729
- return out;
2730
- }
2731
-
2732
- // src/mcp/server.ts
2733
- function capabilities() {
2734
- return {
2735
- tools: { listChanged: false },
2736
- resources: { subscribe: false, listChanged: false },
2737
- prompts: { listChanged: false }
2738
- };
2739
- }
2740
- function requestIdOf(message) {
2741
- const raw = message.id;
2742
- return typeof raw === "string" || typeof raw === "number" ? raw : null;
2743
- }
2744
- function createMcpServer(options) {
2745
- const session = createSession();
2746
- const toolsByName = new Map(options.tools.map((tool) => [tool.name, tool]));
2747
- const promptsByName = new Map(options.prompts.map((prompt) => [prompt.name, prompt]));
2748
- const identity = () => ({
2749
- name: options.info.name,
2750
- title: options.info.title,
2751
- version: options.info.version,
2752
- websiteUrl: options.info.websiteUrl
2753
- });
2754
- const ok = (id, result, modern) => successResponse(id, result, modern, options.info);
2755
- function handleNotification(method) {
2756
- if (method === METHOD.initialized && session.era === "legacy") session.ready = true;
2757
- }
2758
- function initialize(id, params) {
2759
- const negotiation = negotiateLegacyVersion(params?.protocolVersion);
2760
- session.era = "legacy";
2761
- session.protocolVersion = negotiation.version;
2762
- session.ready = true;
2763
- options.context.log(
2764
- negotiation.matched ? `mcp: client initialized with protocol ${negotiation.version}` : `mcp: client asked for an unsupported version and was offered ${negotiation.version}`
2765
- );
2766
- return {
2767
- jsonrpc: "2.0",
2768
- id,
2769
- result: {
2770
- protocolVersion: negotiation.version,
2771
- capabilities: capabilities(),
2772
- serverInfo: identity(),
2773
- instructions: options.instructions
2774
- }
2775
- };
2776
- }
2777
- function discover(id) {
2778
- session.era = "modern";
2779
- session.ready = true;
2780
- return ok(
2781
- id,
2782
- {
2783
- supportedVersions: [...SUPPORTED_PROTOCOL_VERSIONS],
2784
- capabilities: capabilities(),
2785
- instructions: options.instructions,
2786
- // The capability set depends on which repository the server was started for, so the answer
2787
- // may be cached only by the client that asked, and not at all after this response.
2788
- cacheScope: "private",
2789
- ttlMs: 0
2790
- },
2791
- true
2792
- );
2793
- }
2794
- function listTools(id, modern) {
2795
- const tools = options.tools.map((tool) => ({
2796
- name: tool.name,
2797
- title: tool.title,
2798
- description: tool.description,
2799
- inputSchema: tool.inputSchema,
2800
- ...tool.outputSchema ? { outputSchema: tool.outputSchema } : {},
2801
- annotations: tool.annotations
2802
- }));
2803
- return ok(id, { tools }, modern);
2804
- }
2805
- async function callTool(id, modern, params) {
2806
- const name = params?.name;
2807
- if (typeof name !== "string") {
2808
- return errorResponse(id, ERROR_CODES.invalidParams, 'tools/call requires a "name" string.');
2809
- }
2810
- const tool = toolsByName.get(name);
2811
- if (!tool) {
2812
- const known = [...toolsByName.keys()].sort().join(", ");
2813
- return errorResponse(id, ERROR_CODES.invalidParams, `Unknown tool "${name}". Available: ${known}.`);
2814
- }
2815
- const rawArguments = params?.arguments ?? {};
2816
- if (!isJsonObject(rawArguments)) {
2817
- return errorResponse(id, ERROR_CODES.invalidParams, '"arguments" must be a JSON object.');
2818
- }
2819
- const supplied = coerceNumericStrings(tool.inputSchema, rawArguments);
2820
- const problems = validateArguments(tool.inputSchema, supplied);
2821
- if (problems.length > 0) {
2822
- return ok(
2823
- id,
2824
- {
2825
- content: [{ type: "text", text: `Invalid arguments for ${tool.name}:
2826
- - ${problems.join("\n- ")}` }],
2827
- isError: true
2828
- },
2829
- modern
2830
- );
2831
- }
2832
- const args = applyDefaults(tool.inputSchema, supplied);
2833
- let outcome;
2834
- try {
2835
- outcome = await tool.handler(args, options.context);
2836
- } catch (error) {
2837
- const detail = error instanceof Error ? error.message : String(error);
2838
- options.context.log(`mcp: tool ${tool.name} failed: ${detail}`);
2839
- return ok(
2840
- id,
2841
- { content: [{ type: "text", text: `${tool.name} failed: ${detail}` }], isError: true },
2842
- modern
2843
- );
2844
- }
2845
- return ok(
2846
- id,
2847
- {
2848
- content: [{ type: "text", text: outcome.text }],
2849
- ...outcome.structured ? { structuredContent: outcome.structured } : {},
2850
- ...outcome.isError ? { isError: true } : {}
2851
- },
2852
- modern
2853
- );
2854
- }
2855
- async function listResources(id, modern) {
2856
- const resources = await options.resources.list(options.context);
2857
- return ok(id, { resources }, modern);
2858
- }
2859
- async function readResource(id, modern, params) {
2860
- const uri = params?.uri;
2861
- if (typeof uri !== "string") {
2862
- return errorResponse(id, ERROR_CODES.invalidParams, 'resources/read requires a "uri" string.');
2863
- }
2864
- let contents;
2865
- try {
2866
- contents = await options.resources.read(uri, options.context);
2867
- } catch (error) {
2868
- if (error instanceof ResourceNotFoundError) {
2869
- return errorResponse(id, ERROR_CODES.resourceNotFound, error.message, { uri: error.uri });
2870
- }
2871
- if (error instanceof ResourceTooLargeError) {
2872
- options.context.log(
2873
- `mcp: refused ${error.uri} (${error.bytes} bytes, limit ${error.limit}); returning it would truncate it`
2874
- );
2875
- return errorResponse(id, ERROR_CODES.resourceTooLarge, error.message, {
2876
- uri: error.uri,
2877
- bytes: error.bytes,
2878
- limit: error.limit
2879
- });
2880
- }
2881
- throw error;
2882
- }
2883
- if (!contents) {
2884
- return errorResponse(id, ERROR_CODES.invalidParams, `Unknown resource "${uri}".`);
2885
- }
2886
- return ok(id, { contents: [contents] }, modern);
2887
- }
2888
- function listPrompts(id, modern) {
2889
- const prompts = options.prompts.map((prompt) => ({
2890
- name: prompt.name,
2891
- ...prompt.title ? { title: prompt.title } : {},
2892
- description: prompt.description,
2893
- arguments: prompt.arguments
2894
- }));
2895
- return ok(id, { prompts }, modern);
2896
- }
2897
- function getPrompt(id, modern, params) {
2898
- const name = params?.name;
2899
- if (typeof name !== "string") {
2900
- return errorResponse(id, ERROR_CODES.invalidParams, 'prompts/get requires a "name" string.');
2901
- }
2902
- const prompt = promptsByName.get(name);
2903
- if (!prompt) {
2904
- const known = [...promptsByName.keys()].sort().join(", ");
2905
- return errorResponse(id, ERROR_CODES.invalidParams, `Unknown prompt "${name}". Available: ${known}.`);
2906
- }
2907
- const rawArguments = params?.arguments ?? {};
2908
- if (!isJsonObject(rawArguments)) {
2909
- return errorResponse(id, ERROR_CODES.invalidParams, '"arguments" must be a JSON object.');
2910
- }
2911
- const built = prompt.build(rawArguments);
2912
- const messages = built.messages.map((message) => ({
2913
- role: message.role,
2914
- content: { type: "text", text: message.content.text }
2915
- }));
2916
- return ok(id, { description: built.description, messages }, modern);
2917
- }
2918
- async function route(name, id, modern, params) {
2919
- switch (name) {
2920
- case METHOD.initialize:
2921
- return modern ? errorResponse(
2922
- id,
2923
- ERROR_CODES.methodNotFound,
2924
- '"initialize" does not exist in this protocol revision; call "server/discover".'
2925
- ) : initialize(id, params);
2926
- case METHOD.discover:
2927
- return discover(id);
2928
- case METHOD.ping:
2929
- return modern ? errorResponse(
2930
- id,
2931
- ERROR_CODES.methodNotFound,
2932
- '"ping" was removed in this protocol revision; call "server/discover".'
2933
- ) : ok(id, {}, modern);
2934
- }
2935
- if (!session.ready) {
2936
- return errorResponse(
2937
- id,
2938
- ERROR_CODES.invalidRequest,
2939
- 'This connection has not been initialized. Send "initialize" first.'
2940
- );
2941
- }
2942
- switch (name) {
2943
- case METHOD.toolsList:
2944
- return listTools(id, modern);
2945
- case METHOD.toolsCall:
2946
- return callTool(id, modern, params);
2947
- case METHOD.resourcesList:
2948
- return listResources(id, modern);
2949
- case METHOD.resourcesRead:
2950
- return readResource(id, modern, params);
2951
- case METHOD.resourceTemplatesList:
2952
- return ok(id, { resourceTemplates: options.resources.templates() }, modern);
2953
- case METHOD.promptsList:
2954
- return listPrompts(id, modern);
2955
- case METHOD.promptsGet:
2956
- return getPrompt(id, modern, params);
2957
- default:
2958
- return errorResponse(id, ERROR_CODES.methodNotFound, `Unknown method "${name}".`);
2959
- }
2960
- }
2961
- async function dispatch(message) {
2962
- if (!isJsonObject(message)) {
2963
- return errorResponse(
2964
- null,
2965
- ERROR_CODES.invalidRequest,
2966
- Array.isArray(message) ? "Batch requests are not supported: send one JSON-RPC message per line." : "Message is not a JSON object."
2967
- );
2968
- }
2969
- const isRequest = Object.prototype.hasOwnProperty.call(message, "id");
2970
- const method = message.method;
2971
- const params = message.params;
2972
- if (message.jsonrpc !== "2.0" && isRequest) {
2973
- return errorResponse(requestIdOf(message), ERROR_CODES.invalidRequest, 'Message must carry "jsonrpc": "2.0".');
2974
- }
2975
- if (typeof method !== "string" || method.length === 0) {
2976
- return isRequest ? errorResponse(requestIdOf(message), ERROR_CODES.invalidRequest, 'Message must carry a "method" string.') : null;
2977
- }
2978
- if (params !== void 0 && !isJsonObject(params)) {
2979
- return isRequest ? errorResponse(requestIdOf(message), ERROR_CODES.invalidRequest, '"params" must be a JSON object when present.') : null;
2980
- }
2981
- const named = params;
2982
- const decision = classifyRequest(method, named, session);
2983
- const modern = decision.kind === "era" ? decision.era === "modern" : session.era === "modern";
2984
- if (!isRequest) {
2985
- if (decision.kind === "era" && session.era === null) {
2986
- session.era = decision.era;
2987
- session.protocolVersion = decision.version;
2988
- }
2989
- handleNotification(method);
2990
- return null;
2991
- }
2992
- const id = requestIdOf(message);
2993
- if (id === null) {
2994
- return errorResponse(null, ERROR_CODES.invalidRequest, 'A request "id" must be a string or a number.');
2995
- }
2996
- if (decision.kind === "error") {
2997
- return errorResponse(id, decision.code, decision.message, decision.data);
2998
- }
2999
- if (session.era === null) {
3000
- session.era = decision.era;
3001
- session.protocolVersion = decision.version;
3002
- }
3003
- return route(method, id, modern, named);
3004
- }
3005
- return {
3006
- session,
3007
- async handle(message) {
3008
- try {
3009
- return await dispatch(message);
3010
- } catch (error) {
3011
- const detail = error instanceof Error ? error.message : String(error);
3012
- options.context.log(`mcp: internal error: ${detail}`);
3013
- const id = isJsonObject(message) ? requestIdOf(message) : null;
3014
- return errorResponse(id, ERROR_CODES.internalError, "Internal server error.");
3015
- }
3016
- }
3017
- };
3018
- }
3019
-
3020
- // src/mcp/instructions.ts
3021
- var SERVER_INSTRUCTIONS = [
3022
- "codebase-snapshot serves this repository as a size-budgeted snapshot, not as a directory walk.",
3023
- "",
3024
- "Work in this order:",
3025
- "1. snapshot_status \u2014 is there a snapshot here, and has the tree moved since it was built?",
3026
- "2. snapshot_locate \u2014 find which part holds the code you need.",
3027
- "3. snapshot_read \u2014 read a window of one file. Never read a part end to end.",
3028
- "4. snapshot_dependents \u2014 before changing a file, see what imports it.",
3029
- "5. snapshot_validate \u2014 before trusting context that came from an earlier conversation.",
3030
- "",
3031
- "Rules that matter:",
3032
- "- Parts are budgeted, not small: a 12-part snapshot is hundreds of kilobytes. Use snapshot_locate first.",
3033
- "- A file absent from the snapshot has a recorded reason. Ask snapshot_explain, do not assume.",
3034
- "- snapshot_generate is the only tool that writes. It never installs packages and never writes config.",
3035
- "- Paths are relative to the repository root the server was started for, and nothing outside it is readable."
3036
- ].join("\n");
3037
-
3038
- // src/mcp/stdio.ts
3039
- var MAX_LINE_BYTES = 32 * 1024 * 1024;
3040
- function createWriter(output) {
3041
- return {
3042
- write(value) {
3043
- return new Promise((resolve4, reject) => {
3044
- output.write(`${JSON.stringify(value)}
3045
- `, (error) => {
3046
- if (error) reject(error);
3047
- else resolve4();
3048
- });
3049
- });
3050
- }
3051
- };
3052
- }
3053
- function createLineReader(input, options) {
3054
- let buffer = "";
3055
- let bufferBytes = 0;
3056
- let discarding = false;
3057
- let discardedBytes = 0;
3058
- const deliver = (line) => {
3059
- if (discarding) {
3060
- discarding = false;
3061
- discardedBytes = 0;
3062
- return;
3063
- }
3064
- const trimmed = line.endsWith("\r") ? line.slice(0, -1) : line;
3065
- if (trimmed.trim().length === 0) return;
3066
- options.onLine(trimmed);
3067
- };
3068
- const discardBuffered = () => {
3069
- discarding = true;
3070
- discardedBytes += bufferBytes;
3071
- buffer = "";
3072
- bufferBytes = 0;
3073
- options.onOverflow?.(discardedBytes);
3074
- };
3075
- const drain = () => {
3076
- let index = buffer.indexOf("\n");
3077
- while (index >= 0) {
3078
- const line = buffer.slice(0, index);
3079
- buffer = buffer.slice(index + 1);
3080
- if (discarding) {
3081
- deliver(line);
3082
- } else {
3083
- const lineBytes = Buffer.byteLength(line, "utf8");
3084
- if (lineBytes > MAX_LINE_BYTES) options.onOverflow?.(lineBytes);
3085
- else deliver(line);
3086
- }
3087
- index = buffer.indexOf("\n");
3088
- }
3089
- bufferBytes = Buffer.byteLength(buffer, "utf8");
3090
- if (!discarding && bufferBytes > MAX_LINE_BYTES) discardBuffered();
3091
- };
3092
- const onData = (chunk) => {
3093
- const chunkBytes = Buffer.byteLength(chunk, "utf8");
3094
- if (discarding) {
3095
- const index = chunk.indexOf("\n");
3096
- if (index < 0) {
3097
- discardedBytes += chunkBytes;
3098
- return;
3099
- }
3100
- buffer = chunk.slice(index + 1);
3101
- bufferBytes = Buffer.byteLength(buffer, "utf8");
3102
- deliver("");
3103
- drain();
3104
- return;
3105
- }
3106
- if (chunk.indexOf("\n") < 0 && bufferBytes + chunkBytes > MAX_LINE_BYTES) {
3107
- discarding = true;
3108
- discardedBytes = bufferBytes + chunkBytes;
3109
- buffer = "";
3110
- bufferBytes = 0;
3111
- options.onOverflow?.(discardedBytes);
3112
- return;
3113
- }
3114
- buffer += chunk;
3115
- drain();
3116
- };
3117
- const onEnd = () => {
3118
- const rest = buffer;
3119
- const restBytes = bufferBytes || Buffer.byteLength(rest, "utf8");
3120
- buffer = "";
3121
- bufferBytes = 0;
3122
- if (rest.length === 0) return;
3123
- if (discarding) {
3124
- discarding = false;
3125
- discardedBytes = 0;
3126
- return;
3127
- }
3128
- if (restBytes > MAX_LINE_BYTES) {
3129
- options.onOverflow?.(restBytes);
3130
- return;
3131
- }
3132
- deliver(rest);
3133
- };
3134
- input.setEncoding("utf8");
3135
- input.on("data", onData);
3136
- input.on("end", onEnd);
3137
- return () => {
3138
- input.off("data", onData);
3139
- input.off("end", onEnd);
3140
- };
3141
- }
3142
-
3143
- // src/mcp/run.ts
3144
- var PROJECT_URL = "https://ankurhalder.github.io/codebase-snapshot/";
3145
- function createServer(options) {
3146
- const cwd = options.cwd;
3147
- const roots = options.roots && options.roots.length > 0 ? options.roots : [cwd];
3148
- const context = {
3149
- cwd,
3150
- roots,
3151
- log: options.log ?? ((line) => process.stderr.write(`${line}
3152
- `))
3153
- };
3154
- return createMcpServer({
3155
- info: {
3156
- name: GENERATOR_NAME,
3157
- title: "codebase-snapshot",
3158
- version: GENERATOR_VERSION,
3159
- websiteUrl: PROJECT_URL
3160
- },
3161
- instructions: SERVER_INSTRUCTIONS,
3162
- tools: buildTools(),
3163
- resources: buildResourceProvider(),
3164
- prompts: buildPrompts(),
3165
- context
3166
- });
3167
- }
3168
- async function runStdioServer(options) {
3169
- const log = options.log ?? ((line) => process.stderr.write(`${line}
3170
- `));
3171
- const server = createServer(options);
3172
- const writer = createWriter(process.stdout);
3173
- let writeChain = Promise.resolve();
3174
- const send = (message) => {
3175
- writeChain = writeChain.then(() => writer.write(message)).catch((error) => {
3176
- log(`mcp: could not write a response: ${error instanceof Error ? error.message : String(error)}`);
3177
- });
3178
- return writeChain;
3179
- };
3180
- const MAX_IN_FLIGHT = 4;
3181
- let inFlight = 0;
3182
- let inputEnded = false;
3183
- let resolveDone = () => void 0;
3184
- const finished = new Promise((resolve4) => {
3185
- resolveDone = resolve4;
3186
- });
3187
- const finishIfIdle = () => {
3188
- if (inputEnded && inFlight === 0) resolveDone(0);
3189
- };
3190
- const handleLine = async (line) => {
3191
- let message;
3192
- try {
3193
- message = JSON.parse(line);
3194
- } catch {
3195
- await send(errorResponse(null, ERROR_CODES.parseError, "Message is not valid JSON."));
3196
- return;
3197
- }
3198
- const response = await server.handle(message);
3199
- if (response) await send(response);
3200
- };
3201
- const rejectOverloaded = (line) => {
3202
- let id = null;
3203
- try {
3204
- const parsed = JSON.parse(line);
3205
- if (!isJsonObject(parsed)) return;
3206
- if (typeof parsed.id === "string" || typeof parsed.id === "number") id = parsed.id;
3207
- else return;
3208
- } catch {
3209
- return;
3210
- }
3211
- void send(
3212
- errorResponse(
3213
- id,
3214
- ERROR_CODES.overloaded,
3215
- `The server is already handling ${MAX_IN_FLIGHT} requests; retry this one when it is free.`
3216
- )
3217
- );
3218
- };
3219
- const stopReading = createLineReader(process.stdin, {
3220
- onOverflow: (bytes) => log(`mcp: discarded an oversized message (${bytes} bytes)`),
3221
- onLine: (line) => {
3222
- if (inFlight >= MAX_IN_FLIGHT) {
3223
- rejectOverloaded(line);
3224
- return;
3225
- }
3226
- inFlight += 1;
3227
- void handleLine(line).finally(() => {
3228
- inFlight -= 1;
3229
- finishIfIdle();
3230
- });
3231
- }
3232
- });
3233
- const onEnd = () => {
3234
- inputEnded = true;
3235
- finishIfIdle();
3236
- };
3237
- process.stdin.on("end", onEnd);
3238
- process.stdin.on("close", onEnd);
3239
- log(`mcp: serving ${options.cwd} over stdio`);
3240
- const code = await finished;
3241
- stopReading();
3242
- process.stdin.off("end", onEnd);
3243
- process.stdin.off("close", onEnd);
3244
- await writeChain;
3245
- return code;
3246
- }
3247
-
3248
- export { COMMAND_OPTION_SCOPE, ERROR_CODES, LEGACY_PROTOCOL_VERSIONS, MAX_LINE_BYTES, METHOD, MODERN_PROTOCOL_VERSIONS, SERVER_INSTRUCTIONS, SKILL_NAME, SUPPORTED_PROTOCOL_VERSIONS, buildAgentContract, buildPrompts, buildResourceProvider, buildTools, classifyRequest, coerceNumericStrings, commandsForOption, createLineReader, createMcpServer, createServer, createSession, createWriter, findSection, inspectModernMeta, negotiateLegacyVersion, parsePartSections, renderContractText, renderSkill, runStdioServer, validateArguments, windowText };