codebase-snapshot 0.17.0 → 0.19.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.
package/dist/mcp.cjs CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  var fs2 = require('fs');
4
4
  var path5 = require('path');
5
- var crypto3 = require('crypto');
5
+ var crypto2 = require('crypto');
6
6
  var module$1 = require('module');
7
7
  var url = require('url');
8
8
  var childProcess = require('child_process');
@@ -34,7 +34,7 @@ function _interopNamespace(e) {
34
34
 
35
35
  var fs2__namespace = /*#__PURE__*/_interopNamespace(fs2);
36
36
  var path5__namespace = /*#__PURE__*/_interopNamespace(path5);
37
- var crypto3__namespace = /*#__PURE__*/_interopNamespace(crypto3);
37
+ var crypto2__namespace = /*#__PURE__*/_interopNamespace(crypto2);
38
38
  var childProcess__namespace = /*#__PURE__*/_interopNamespace(childProcess);
39
39
  var ts__default = /*#__PURE__*/_interopDefault(ts);
40
40
  var http__namespace = /*#__PURE__*/_interopNamespace(http);
@@ -363,7 +363,7 @@ function parseOwnerBrief(filePath, text) {
363
363
  return {
364
364
  brief: {
365
365
  path: filePath,
366
- digest: crypto3.createHash("sha256").update(text, "utf8").digest("hex"),
366
+ digest: crypto2.createHash("sha256").update(text, "utf8").digest("hex"),
367
367
  ...recognised["Stakes"] ? { stakes: recognised["Stakes"] } : {},
368
368
  ...recognised["The system"] ? { system: recognised["The system"] } : {},
369
369
  ...recognised["What came before"] ? { history: recognised["What came before"] } : {},
@@ -2230,7 +2230,11 @@ function scanAndRedactSecrets(content, rules, filePath) {
2230
2230
  let finalText = segments.join("");
2231
2231
  finalText = redactStructuredValues(finalText, filePath, recordFinding);
2232
2232
  finalText = redactDockerfileEnv(finalText, filePath, recordFinding);
2233
- const findings = [...findingsByLine.entries()].sort(([left], [right]) => left - right).map(([line, rulesForLine]) => ({
2233
+ const originalLines = content.split(/\r\n|\r|\n/);
2234
+ const findings = [...findingsByLine.entries()].filter(([line]) => {
2235
+ const original = originalLines[line - 1] ?? "";
2236
+ return !original.includes(REDACTION_MARKER) && !original.includes(PEM_REDACTION_MARKER);
2237
+ }).sort(([left], [right]) => left - right).map(([line, rulesForLine]) => ({
2234
2238
  rules: [...rulesForLine],
2235
2239
  line,
2236
2240
  path: filePath
@@ -2298,8 +2302,8 @@ function redactStructuredValues(text, filePath, recordFinding) {
2298
2302
  if (body.trim() !== "") {
2299
2303
  const indent = (/^[ \t]*/.exec(body)?.[0] ?? "").length;
2300
2304
  if (indent <= baseIndent) break;
2305
+ if (!isMarkerLine(body)) masked2 = true;
2301
2306
  segments[cursor2] = maskLineContent(body);
2302
- masked2 = true;
2303
2307
  }
2304
2308
  cursor2 += 2;
2305
2309
  }
@@ -2319,8 +2323,8 @@ function redactStructuredValues(text, filePath, recordFinding) {
2319
2323
  if (body.trim() !== "") {
2320
2324
  const indent = (/^[ \t]*/.exec(body)?.[0] ?? "").length;
2321
2325
  if (indent < valueIndent) break;
2326
+ if (!isMarkerLine(body)) masked = true;
2322
2327
  segments[cursor] = maskValueLine(body);
2323
- masked = true;
2324
2328
  }
2325
2329
  cursor += 2;
2326
2330
  }
@@ -2430,10 +2434,14 @@ var PLACEHOLDER_PATTERNS = [
2430
2434
  /^your[-_ ].*$/i,
2431
2435
  /^(?:example|sample)(?:[-_ ].*)?$/i
2432
2436
  ];
2437
+ function isMarkerLine(value) {
2438
+ return value.includes(REDACTION_MARKER) || value.includes(PEM_REDACTION_MARKER);
2439
+ }
2433
2440
  function isPlaceholderValue(value) {
2434
2441
  const trimmed = value.trim().replace(/^["'`]+/, "").replace(/["'`]+$/, "");
2435
2442
  if (trimmed.length === 0) return false;
2436
2443
  if (PLACEHOLDER_PATTERNS.some((pattern) => pattern.test(trimmed))) return true;
2444
+ if (trimmed.includes(REDACTION_MARKER) || trimmed.includes(PEM_REDACTION_MARKER)) return true;
2437
2445
  return trimmed.includes("...") || /^<[^>]*$/.test(trimmed);
2438
2446
  }
2439
2447
  function quotesAreBalanced(text) {
@@ -2548,7 +2556,7 @@ function applySpansKeepingQuotes(line, spans) {
2548
2556
 
2549
2557
  // src/version.ts
2550
2558
  var GENERATOR_NAME = "codebase-snapshot";
2551
- var GENERATOR_VERSION = "0.17.0";
2559
+ var GENERATOR_VERSION = "0.19.0";
2552
2560
  var SCHEMA_VERSION = "3.0.0";
2553
2561
  var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
2554
2562
  function isOurGeneratorName(name) {
@@ -2599,6 +2607,7 @@ function getGitInfo(cwd, fallbackBranch = "main") {
2599
2607
  let branch = fallbackBranch;
2600
2608
  let commit = "unknown";
2601
2609
  let isDirty = false;
2610
+ let branchFromGit = false;
2602
2611
  const records = output.split("\0").flatMap((record) => record.split("\n"));
2603
2612
  for (const record of records) {
2604
2613
  if (record.length === 0) continue;
@@ -2614,13 +2623,14 @@ function getGitInfo(cwd, fallbackBranch = "main") {
2614
2623
  const head = record.match(/^# branch\.head (.+)$/);
2615
2624
  if (head) {
2616
2625
  branch = head[1] === "(detached)" ? fallbackBranch : head[1];
2626
+ branchFromGit = head[1] !== "(detached)";
2617
2627
  }
2618
2628
  }
2619
- return { branch, commit, isDirty };
2629
+ return { branch, commit, isDirty, branchFromGit };
2620
2630
  } catch (err) {
2621
2631
  const code = err.code;
2622
2632
  const isDirty = code === "ENOBUFS";
2623
- return { branch: fallbackBranch, commit: "unknown", isDirty };
2633
+ return { branch: fallbackBranch, commit: "unknown", isDirty, branchFromGit: false };
2624
2634
  }
2625
2635
  }
2626
2636
  var DEFAULT_IGNORED_DIRS = [
@@ -3666,7 +3676,7 @@ function readConfigExport(exported, file) {
3666
3676
  var lastModuleConfig = null;
3667
3677
  function moduleConfigKey(fullPath) {
3668
3678
  try {
3669
- return crypto3.createHash("sha256").update(fs2__namespace.readFileSync(fullPath)).digest("hex").slice(0, 24);
3679
+ return crypto2.createHash("sha256").update(fs2__namespace.readFileSync(fullPath)).digest("hex").slice(0, 24);
3670
3680
  } catch {
3671
3681
  try {
3672
3682
  const stats = fs2__namespace.statSync(fullPath);
@@ -4514,7 +4524,7 @@ function configDigest(config) {
4514
4524
  (rule) => `${rule.rule}:${rule.pattern.source}/${rule.pattern.flags}:${rule.valueGroup ?? ""}`
4515
4525
  ).sort()
4516
4526
  };
4517
- return crypto3.createHash("sha256").update(JSON.stringify(material)).digest("hex");
4527
+ return crypto2.createHash("sha256").update(JSON.stringify(material)).digest("hex");
4518
4528
  }
4519
4529
 
4520
4530
  // src/ast/profiles/shared.ts
@@ -5335,7 +5345,7 @@ function summarizeTypeScriptSource(relativePath, content) {
5335
5345
  }
5336
5346
  const callee = node.expression;
5337
5347
  if (ts__default.default.isPropertyAccessExpression(callee) && ts__default.default.isIdentifier(callee.expression) && ROUTE_RECEIVERS.has(callee.expression.text) && ROUTE_REGISTRATION_VERBS.has(callee.name.text.toLowerCase()) && firstArgument !== void 0 && ts__default.default.isStringLiteral(firstArgument)) {
5338
- summary.routeHandlers.push(callee.name.text.toUpperCase());
5348
+ summary.routeHandlers.push(callee.name.text.toUpperCase() + " " + firstArgument.text);
5339
5349
  }
5340
5350
  }
5341
5351
  if (ts__default.default.isExportDeclaration(node)) {
@@ -6079,7 +6089,7 @@ function capValue(value, max) {
6079
6089
  var displayPath = (value) => capValue(escapeControls(value), DISPLAY_PATH_MAX);
6080
6090
  function anchorForPath(filePath) {
6081
6091
  const slug = filePath.toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "");
6082
- const digest = crypto3__namespace.createHash("sha256").update(filePath).digest("hex").slice(0, 8);
6092
+ const digest = crypto2__namespace.createHash("sha256").update(filePath).digest("hex").slice(0, 8);
6083
6093
  return `${slug || "file"}-${digest}`;
6084
6094
  }
6085
6095
 
@@ -6269,13 +6279,19 @@ function planForQuestion(manifest, question, options = {}) {
6269
6279
  scored.push({ file, score, why: reasons.slice(0, 3).join(", ") || "centrality " + hub });
6270
6280
  }
6271
6281
  const notes = [];
6282
+ if (manifest.files.length === 0) {
6283
+ notes.push("The snapshot holds no files; there is nothing to plan. Check manifest.skipped for why paths were not emitted.");
6284
+ return { question, budgetTokens: budget, usedTokens: 0, files: [], skipped: [], notes };
6285
+ }
6272
6286
  if (scored.length === 0) {
6273
- notes.push("No file matched the question's terms; the plan falls back to the most-imported files.");
6274
6287
  const hubs = manifest.indexes.imports.centralFiles.slice(0, 12);
6275
6288
  for (const hub of hubs) {
6276
6289
  const file = byPath.get(hub.path);
6277
6290
  if (file !== void 0) scored.push({ file, score: 1, why: "hub, " + hub.importedByCount + " importers" });
6278
6291
  }
6292
+ if (scored.length > 0) {
6293
+ notes.push("No file matched the question's terms; the plan falls back to the most-imported files.");
6294
+ }
6279
6295
  }
6280
6296
  scored.sort((left, right) => right.score - left.score || left.file.relativePath.localeCompare(right.file.relativePath));
6281
6297
  const chosen = /* @__PURE__ */ new Map();
@@ -6339,7 +6355,14 @@ function planForQuestion(manifest, question, options = {}) {
6339
6355
  }
6340
6356
  }
6341
6357
  }
6342
- if (chosen.size === 0) notes.push("The budget is too small for any file in this snapshot.");
6358
+ if (chosen.size === 0) {
6359
+ if (scored.length === 0) {
6360
+ notes.push("No candidate file matched the question, and this snapshot has no centrality data to fall back on.");
6361
+ } else {
6362
+ const cheapest = scored.reduce((minimum, item) => Math.min(minimum, Math.ceil(item.file.includedBytes / 4)), Infinity);
6363
+ notes.push("Nothing fit the budget: the cheapest candidate costs about " + formatNumber(cheapest) + " tokens.");
6364
+ }
6365
+ }
6343
6366
  notes.push(
6344
6367
  formatNumber(chosen.size) + " file(s) chosen of " + formatNumber(manifest.files.length) + " in the snapshot; " + formatNumber(skipped.length) + " skipped for budget."
6345
6368
  );
@@ -6519,6 +6542,48 @@ var RUBY_EXTENSIONS = /* @__PURE__ */ new Set([".rb", ".rake", ".gemspec"]);
6519
6542
  var C_EXTENSIONS = /* @__PURE__ */ new Set([".c", ".h", ".cc", ".cpp", ".cxx", ".hpp", ".hxx", ".m", ".mm"]);
6520
6543
  var PYTHON_SUFFIXES = [".py", ".pyi", "/__init__.py", "/__init__.pyi"];
6521
6544
  var CASE_INSENSITIVE_FILESYSTEM = process.platform === "win32" || process.platform === "darwin";
6545
+ var TSCONFIG_CACHE = /* @__PURE__ */ new Map();
6546
+ function tsconfigPathsFor(cwd) {
6547
+ const configPath = path5__namespace.join(cwd, "tsconfig.json");
6548
+ let stats;
6549
+ try {
6550
+ stats = fs2__namespace.statSync(configPath);
6551
+ } catch (err) {
6552
+ if (err.code === "ENOENT") return null;
6553
+ return null;
6554
+ }
6555
+ const key = `${stats.mtimeMs}:${stats.size}`;
6556
+ const cached = TSCONFIG_CACHE.get(configPath);
6557
+ if (cached !== void 0 && cached.key === key) return cached.value;
6558
+ let value = null;
6559
+ try {
6560
+ const read = ts__default.default.readConfigFile(configPath, ts__default.default.sys.readFile);
6561
+ if (read.error === void 0) {
6562
+ const parsed = ts__default.default.parseJsonConfigFileContent(read.config, ts__default.default.sys, cwd, void 0, configPath);
6563
+ const options = parsed.options;
6564
+ const baseUrl = typeof options.baseUrl === "string" ? repositoryRelative(cwd, options.baseUrl) : null;
6565
+ const rules = [];
6566
+ if (options.paths !== void 0) {
6567
+ for (const [pattern, targets] of Object.entries(options.paths)) {
6568
+ if (!Array.isArray(targets)) continue;
6569
+ rules.push({
6570
+ pattern,
6571
+ targets: targets.map((target) => String(target).replace(/\\/g, "/"))
6572
+ });
6573
+ }
6574
+ }
6575
+ if (baseUrl !== null || rules.length > 0) value = { baseUrl, paths: rules };
6576
+ }
6577
+ } catch (err) {
6578
+ value = null;
6579
+ }
6580
+ TSCONFIG_CACHE.set(configPath, { key, value });
6581
+ return value;
6582
+ }
6583
+ function repositoryRelative(cwd, target) {
6584
+ const relative9 = path5__namespace.relative(cwd, target).replace(/\\/g, "/");
6585
+ return relative9.length === 0 || !relative9.startsWith("..") && !path5__namespace.isAbsolute(relative9) ? relative9 : null;
6586
+ }
6522
6587
  function rememberFirst(map, key, value) {
6523
6588
  if (!map.has(key)) map.set(key, value);
6524
6589
  }
@@ -6710,6 +6775,41 @@ function detectLanguage(filePath) {
6710
6775
  const ext = path5__namespace.posix.extname(base).toLowerCase();
6711
6776
  return LANGUAGE_BY_EXTENSION[ext] ?? "text";
6712
6777
  }
6778
+ var SIGNATURE_FILE = "signature.json";
6779
+ function verifySnapshotSignature(snapshotDir) {
6780
+ const signaturePath = path5__namespace.join(snapshotDir, SIGNATURE_FILE);
6781
+ const manifestPath = path5__namespace.join(snapshotDir, "manifest.json");
6782
+ if (!fs2__namespace.existsSync(signaturePath)) return { ok: false, reason: "no signature.json in this snapshot" };
6783
+ let record;
6784
+ try {
6785
+ record = JSON.parse(fs2__namespace.readFileSync(signaturePath, "utf8"));
6786
+ } catch (error) {
6787
+ return { ok: false, reason: "signature.json is not JSON: " + error.message };
6788
+ }
6789
+ if (record.algorithm !== "ed25519" || typeof record.signature !== "string" || typeof record.publicKey !== "string") {
6790
+ return { ok: false, reason: "signature.json is not an ed25519 record" };
6791
+ }
6792
+ let bytes;
6793
+ try {
6794
+ bytes = fs2__namespace.readFileSync(manifestPath);
6795
+ } catch {
6796
+ return { ok: false, reason: "the signed manifest is missing" };
6797
+ }
6798
+ const sha2562 = crypto2__namespace.createHash("sha256").update(bytes).digest("hex");
6799
+ if (sha2562 !== record.manifestSha256) {
6800
+ return { ok: false, reason: "manifest.json changed after it was signed" };
6801
+ }
6802
+ let verified = false;
6803
+ try {
6804
+ const key = crypto2__namespace.createPublicKey({ key: Buffer.from(record.publicKey, "base64"), format: "der", type: "spki" });
6805
+ verified = crypto2__namespace.verify(null, bytes, key, Buffer.from(record.signature, "base64"));
6806
+ } catch (error) {
6807
+ return { ok: false, reason: "the signature could not be checked: " + error.message };
6808
+ }
6809
+ return verified ? { ok: true, record } : { ok: false, reason: "the signature does not match the manifest" };
6810
+ }
6811
+
6812
+ // src/validator/validate.ts
6713
6813
  function maskedPath(value, secretRules) {
6714
6814
  return findSecretInPath(value, secretRules)?.masked ?? value;
6715
6815
  }
@@ -6773,7 +6873,7 @@ function emptyDrift() {
6773
6873
  };
6774
6874
  }
6775
6875
  function sha256Hex(buffer) {
6776
- return crypto3__namespace.createHash("sha256").update(buffer).digest("hex");
6876
+ return crypto2__namespace.createHash("sha256").update(buffer).digest("hex");
6777
6877
  }
6778
6878
  function wouldNowBeIncluded(cwd, relativePath) {
6779
6879
  const absolutePath = path5__namespace.join(cwd, relativePath);
@@ -7710,6 +7810,11 @@ function validateSnapshot(configInput) {
7710
7810
  `${drift.configMismatches.length} configuration mismatch(es) between the manifest and this run.`
7711
7811
  );
7712
7812
  }
7813
+ const signaturePath = path5__namespace.join(path5__namespace.dirname(manifestPath), "signature.json");
7814
+ if (fs2__namespace.existsSync(signaturePath)) {
7815
+ const outcome = verifySnapshotSignature(path5__namespace.dirname(manifestPath));
7816
+ if (!outcome.ok) errors.push("signature: " + outcome.reason + ".");
7817
+ }
7713
7818
  if (manifest.slice !== void 0 || manifest.budget !== void 0) {
7714
7819
  warnings.push(
7715
7820
  "This snapshot is a selection (" + (manifest.slice !== void 0 ? "--slice" : "--budget-tokens") + "); validate checks what is present and does not re-run the planner, so a file the selection left out is not reported as missing."
@@ -8004,39 +8109,6 @@ var PROMPTS = [
8004
8109
  function buildPrompts() {
8005
8110
  return PROMPTS;
8006
8111
  }
8007
- var SIGNATURE_FILE = "signature.json";
8008
- function verifySnapshotSignature(snapshotDir) {
8009
- const signaturePath = path5__namespace.join(snapshotDir, SIGNATURE_FILE);
8010
- const manifestPath = path5__namespace.join(snapshotDir, "manifest.json");
8011
- if (!fs2__namespace.existsSync(signaturePath)) return { ok: false, reason: "no signature.json in this snapshot" };
8012
- let record;
8013
- try {
8014
- record = JSON.parse(fs2__namespace.readFileSync(signaturePath, "utf8"));
8015
- } catch (error) {
8016
- return { ok: false, reason: "signature.json is not JSON: " + error.message };
8017
- }
8018
- if (record.algorithm !== "ed25519" || typeof record.signature !== "string" || typeof record.publicKey !== "string") {
8019
- return { ok: false, reason: "signature.json is not an ed25519 record" };
8020
- }
8021
- let bytes;
8022
- try {
8023
- bytes = fs2__namespace.readFileSync(manifestPath);
8024
- } catch {
8025
- return { ok: false, reason: "the signed manifest is missing" };
8026
- }
8027
- const sha2562 = crypto3__namespace.createHash("sha256").update(bytes).digest("hex");
8028
- if (sha2562 !== record.manifestSha256) {
8029
- return { ok: false, reason: "manifest.json changed after it was signed" };
8030
- }
8031
- let verified = false;
8032
- try {
8033
- const key = crypto3__namespace.createPublicKey({ key: Buffer.from(record.publicKey, "base64"), format: "der", type: "spki" });
8034
- verified = crypto3__namespace.verify(null, bytes, key, Buffer.from(record.signature, "base64"));
8035
- } catch (error) {
8036
- return { ok: false, reason: "the signature could not be checked: " + error.message };
8037
- }
8038
- return verified ? { ok: true, record } : { ok: false, reason: "the signature does not match the manifest" };
8039
- }
8040
8112
 
8041
8113
  // src/partitioner/part-format.ts
8042
8114
  var FILE_HEADING = "### FILE: ";
@@ -8142,7 +8214,7 @@ var ARTIFACT_FILES = {
8142
8214
  };
8143
8215
  var TEXT_ARTIFACT = /\.(md|json|txt|sarif)$/i;
8144
8216
  function sha256(buffer) {
8145
- return crypto3.createHash("sha256").update(buffer).digest("hex");
8217
+ return crypto2.createHash("sha256").update(buffer).digest("hex");
8146
8218
  }
8147
8219
  function readBytes(file) {
8148
8220
  try {
@@ -8617,8 +8689,9 @@ function auditSnapshot(options) {
8617
8689
  if (typeof member.files === "number" && member.files !== manifest.counts.totalFiles) {
8618
8690
  disagreements.push("file count");
8619
8691
  }
8692
+ const sourceGone = typeof member.path === "string" && !fs2__namespace.existsSync(member.path) ? "Member " + memberName + " source directory is gone (" + member.path + "); the snapshot still describes it. Regenerate the workspace." : null;
8620
8693
  checks.push(
8621
- disagreements.length === 0 ? check(
8694
+ sourceGone !== null ? check("workspace.index", "The workspace index agrees with this member", "warning", "warn", sourceGone) : disagreements.length === 0 ? check(
8622
8695
  "workspace.index",
8623
8696
  "The workspace index agrees with this member",
8624
8697
  "warning",
@@ -8640,12 +8713,45 @@ function auditSnapshot(options) {
8640
8713
  let scannedBytes = 0;
8641
8714
  for (const relative9 of walk(snapshotDir)) {
8642
8715
  if (!TEXT_ARTIFACT.test(relative9) || scannedBytes > scanBudget) continue;
8716
+ if (relative9 === SIGNATURE_FILE) continue;
8643
8717
  const text = readText(path5__namespace.join(snapshotDir, relative9));
8644
8718
  if (text === null) continue;
8645
8719
  scannedBytes += Buffer.byteLength(text, "utf8");
8646
- const found = scanAndRedactSecrets(text, rules, relative9);
8647
- if (found.findings.length > 0) {
8648
- leakHits.push(relative9 + " (" + found.findings.length + " line(s))");
8720
+ let findingCount = 0;
8721
+ if (/^parts[\\/].*\.md$/i.test(relative9)) {
8722
+ let headerText = text;
8723
+ for (const section of parsePartSections(text)) {
8724
+ findingCount += scanAndRedactSecrets(section.body, rules, section.path).findings.length;
8725
+ headerText = headerText.replace(section.body, "");
8726
+ }
8727
+ findingCount += scanAndRedactSecrets(headerText, rules, relative9).findings.length;
8728
+ } else {
8729
+ findingCount = scanAndRedactSecrets(text, rules, relative9).findings.length;
8730
+ }
8731
+ if (findingCount > 0) {
8732
+ leakHits.push(relative9 + " (" + findingCount + " line(s))");
8733
+ }
8734
+ }
8735
+ const signatureRecordPath = path5__namespace.join(snapshotDir, SIGNATURE_FILE);
8736
+ if (fs2__namespace.existsSync(signatureRecordPath)) {
8737
+ const recordText = readText(signatureRecordPath);
8738
+ if (recordText !== null) {
8739
+ scannedBytes += Buffer.byteLength(recordText, "utf8");
8740
+ let scanText = recordText;
8741
+ try {
8742
+ const record = JSON.parse(recordText);
8743
+ const rest = { ...record };
8744
+ delete rest.publicKey;
8745
+ delete rest.signature;
8746
+ delete rest.manifestSha256;
8747
+ delete rest.fingerprint;
8748
+ scanText = JSON.stringify(rest, null, 2);
8749
+ } catch {
8750
+ }
8751
+ const found = scanAndRedactSecrets(scanText, rules, SIGNATURE_FILE);
8752
+ if (found.findings.length > 0) {
8753
+ leakHits.push(SIGNATURE_FILE + " (" + found.findings.length + " line(s))");
8754
+ }
8649
8755
  }
8650
8756
  }
8651
8757
  checks.push(
@@ -9381,6 +9487,10 @@ var WRITES = {
9381
9487
  openWorldHint: false
9382
9488
  };
9383
9489
  var MAX_RESULT_BYTES = 64 * 1024;
9490
+ function capResultText(text) {
9491
+ const clipped = truncateToBytes(text, MAX_RESULT_BYTES);
9492
+ return { text: clipped.isTruncated ? clipped.content : text, clipped: clipped.isTruncated };
9493
+ }
9384
9494
  var ROOT_PROPERTY = {
9385
9495
  type: "string",
9386
9496
  description: "Repository root. Defaults to the directory this server was started in."
@@ -9568,6 +9678,17 @@ var historyTool = {
9568
9678
  isError: true
9569
9679
  };
9570
9680
  }
9681
+ const manifestRead = readManifest3(prepared.workspace);
9682
+ const recordedLog = manifestRead.ok ? manifestRead.manifest.artifacts?.log : void 0;
9683
+ if (recordedLog !== void 0 && recordedLog !== null) {
9684
+ const digest = crypto2.createHash("sha256").update(text, "utf8").digest("hex");
9685
+ if (digest !== recordedLog.sha256) {
9686
+ return {
9687
+ text: "reports/log.md changed after the snapshot was generated (its digest no longer matches the manifest). Regenerate the snapshot rather than trusting this history.",
9688
+ isError: true
9689
+ };
9690
+ }
9691
+ }
9571
9692
  const limit = Math.max(1, typeof args.limit === "number" ? args.limit : 20);
9572
9693
  const commits = parseHistoryReport(text).slice(0, limit);
9573
9694
  return {
@@ -9627,9 +9748,12 @@ var budgetTool = {
9627
9748
  });
9628
9749
  }
9629
9750
  const lines = [question === "" ? "No question: planning for the repository as a whole." : "Question: " + question];
9751
+ if (read.manifest.files.length === 0) {
9752
+ lines.push("The snapshot holds no files, so every budget selects nothing. Check manifest.skipped for why.");
9753
+ }
9630
9754
  for (const row of rows) {
9631
9755
  lines.push(
9632
- row.budget.toLocaleString("en-US") + " tokens: " + row.files + " file(s), " + row.usedTokens.toLocaleString("en-US") + " used" + (row.gained.length === 0 ? "" : ", " + row.gained.length + " gained (" + row.gained.slice(0, 4).join(", ") + (row.gained.length > 4 ? ", \u2026" : "") + ")")
9756
+ row.budget.toLocaleString("en-US") + " tokens: " + row.files + " file(s), " + row.usedTokens.toLocaleString("en-US") + " used" + (row.files === 0 && read.manifest.files.length > 0 ? " - no file fits this budget" : "") + (row.gained.length === 0 ? "" : ", " + row.gained.length + " gained (" + row.gained.slice(0, 4).join(", ") + (row.gained.length > 4 ? ", \u2026" : "") + ")")
9633
9757
  );
9634
9758
  }
9635
9759
  return { text: lines.join("\n"), structured: { budgets: rows } };
@@ -9881,7 +10005,7 @@ var routesTool = {
9881
10005
  routes.sort((left, right) => left.path.localeCompare(right.path) || left.route.localeCompare(right.route));
9882
10006
  const text = routes.length === 0 ? "No route was recorded. Routes come from decorators, framework attributes and route tables." : [
9883
10007
  routes.length + " route(s):",
9884
- ...routes.map((route) => route.route + " (" + route.path + ", " + route.part + ")")
10008
+ ...routes.map((route) => route.route.trim() + " (" + route.path + ", " + route.part + ")")
9885
10009
  ].join("\n");
9886
10010
  return { text, structured: { total: routes.length, routes } };
9887
10011
  }
@@ -10050,8 +10174,9 @@ var searchTool = {
10050
10174
  }
10051
10175
  }
10052
10176
  }
10177
+ const matchedFiles = new Set(matches.map((match) => match.path)).size;
10053
10178
  const lines = [
10054
- matches.length + " match(es) in " + read.manifest.files.length + " file(s)." + (truncated ? " Results are capped; narrow the query." : ""),
10179
+ matches.length === 0 ? "No match in " + read.manifest.files.length + " file(s)." : matches.length + " match(es) in " + matchedFiles + " file(s) of " + read.manifest.files.length + " searched." + (truncated ? " Results are capped, so not every file was searched; narrow the query." : ""),
10055
10180
  ...skippedOversize.length > 0 ? ["Skipped " + skippedOversize.length + " oversized part(s): " + skippedOversize.slice(0, 5).join(", ")] : [],
10056
10181
  ...matches.map((match) => match.path + ":" + match.line + " (" + match.part + "): " + match.text)
10057
10182
  ];
@@ -10074,7 +10199,9 @@ var statsTool = {
10074
10199
  parts: { type: "integer" },
10075
10200
  tokens: { type: "integer" },
10076
10201
  layers: { type: "object" },
10077
- kinds: { type: "object" }
10202
+ kinds: { type: "object" },
10203
+ heaviest: { type: "array", items: { type: "object" } },
10204
+ partSizes: { type: "array", items: { type: "object" } }
10078
10205
  }
10079
10206
  },
10080
10207
  annotations: READ_ONLY,
@@ -10085,7 +10212,11 @@ var statsTool = {
10085
10212
  if (!read.ok) return { text: read.message + " Call snapshot_generate first.", isError: true };
10086
10213
  const manifest = read.manifest;
10087
10214
  const heaviest = [...manifest.files].sort((left, right) => right.includedBytes - left.includedBytes).slice(0, 10).map((file) => ({ path: file.relativePath, tokens: Math.ceil(file.includedBytes / 4), part: file.part }));
10088
- const parts = manifest.parts.map((part) => ({ filename: part.filename, tokens: part.estimatedTokens }));
10215
+ const parts = manifest.parts.map((part) => ({
10216
+ filename: part.filename,
10217
+ bytes: part.byteSize,
10218
+ tokens: part.estimatedTokens
10219
+ }));
10089
10220
  const lines = [
10090
10221
  manifest.counts.totalFiles + " file(s) in " + manifest.counts.partsCount + " part(s), " + (manifest.totals.estimatedTokens ?? 0) + " estimated tokens.",
10091
10222
  "Layers: " + Object.entries(manifest.layers).map(([name, count]) => name + "=" + count).join(", "),
@@ -10141,7 +10272,7 @@ var reviewTool = {
10141
10272
  if (!read.ok) return { text: read.message + " Call snapshot_generate first.", isError: true };
10142
10273
  let validation;
10143
10274
  try {
10144
- validation = validateSnapshot(workspace.config);
10275
+ validation = validateSnapshot(configAsGenerated(workspace, read.manifest));
10145
10276
  } catch (error) {
10146
10277
  return { text: error.message, isError: true };
10147
10278
  }
@@ -10241,24 +10372,17 @@ var diffContextTool = {
10241
10372
  const budget = Math.max(500, typeof args.maxTokens === "number" ? args.maxTokens : 15e3);
10242
10373
  const linesPerFile = Math.max(10, typeof args.linesPerFile === "number" ? args.linesPerFile : 80);
10243
10374
  const byPath = new Map(read.manifest.files.map((file) => [file.relativePath.toLowerCase(), file]));
10375
+ const resolver = buildImportResolver(read.manifest.files, {
10376
+ tsconfig: tsconfigPathsFor(workspace.root)
10377
+ });
10244
10378
  const importers = /* @__PURE__ */ new Map();
10245
10379
  for (const entry of read.manifest.indexes.imports.byFile) {
10246
10380
  for (const specifier of entry.imports) {
10247
- if (!specifier.startsWith(".")) continue;
10248
- const base = entry.path.includes("/") ? entry.path.slice(0, entry.path.lastIndexOf("/")) : "";
10249
- const parts = [];
10250
- for (const segment of (base + "/" + specifier).split("/")) {
10251
- if (segment === "" || segment === ".") continue;
10252
- if (segment === "..") parts.pop();
10253
- else parts.push(segment);
10254
- }
10255
- const joined = parts.join("/").toLowerCase();
10256
- const withoutExtension = joined.replace(/\.[cm]?[jt]sx?$/, "");
10257
- const target = byPath.get(joined) ?? byPath.get(withoutExtension + ".ts") ?? byPath.get(withoutExtension + ".tsx") ?? byPath.get(withoutExtension + ".js") ?? byPath.get(withoutExtension + ".py") ?? byPath.get(withoutExtension + "/index.ts") ?? byPath.get(withoutExtension);
10258
- if (target === void 0) continue;
10259
- const list = importers.get(target.relativePath) ?? [];
10381
+ const target = resolveSpecifier(entry.path, specifier, resolver);
10382
+ if (target === null) continue;
10383
+ const list = importers.get(target) ?? [];
10260
10384
  list.push(entry.path);
10261
- importers.set(target.relativePath, list);
10385
+ importers.set(target, list);
10262
10386
  }
10263
10387
  }
10264
10388
  const missing = [];
@@ -10293,9 +10417,12 @@ var diffContextTool = {
10293
10417
  continue;
10294
10418
  }
10295
10419
  used += tokens;
10420
+ const capped2 = capResultText(window.text);
10296
10421
  changed.push({ path: file.relativePath, part: file.part, tokens });
10297
- text.push("### " + file.relativePath + " (" + file.part + ")");
10298
- text.push(window.text);
10422
+ text.push(
10423
+ "### " + file.relativePath + " (" + file.part + (capped2.clipped ? ", first 64 KiB" : "") + ")"
10424
+ );
10425
+ text.push(capped2.text);
10299
10426
  }
10300
10427
  const dependents = [];
10301
10428
  for (const entry of changed) {
@@ -10377,11 +10504,13 @@ var symbolTool = {
10377
10504
  if (index === -1) continue;
10378
10505
  const from = Math.max(0, index - 3);
10379
10506
  const to = Math.min(lines.length, index + windowSize);
10507
+ const capped2 = capResultText(lines.slice(from, to).join("\n"));
10380
10508
  matches.push({
10381
10509
  path: file.relativePath,
10382
10510
  part: file.part,
10383
10511
  line: index + 1,
10384
- text: lines.slice(from, to).join("\n")
10512
+ text: capped2.text,
10513
+ ...capped2.clipped ? { clippedAtBytes: MAX_RESULT_BYTES } : {}
10385
10514
  });
10386
10515
  }
10387
10516
  if (matches.length === 0) {
@@ -10512,7 +10641,8 @@ var contextTool = {
10512
10641
  continue;
10513
10642
  }
10514
10643
  const window = windowText(section.body, 1, linesPerFile);
10515
- const body = window.text;
10644
+ const capped2 = capResultText(window.text);
10645
+ const body = capped2.text;
10516
10646
  let tokens = Math.max(1, Math.ceil(Buffer.byteLength(body, "utf8") / 4));
10517
10647
  if (used + tokens > budget) {
10518
10648
  const keep = Math.max(4, Math.floor((budget - used) / tokens * linesPerFile));
@@ -10521,14 +10651,19 @@ var contextTool = {
10521
10651
  missing.push(file.relativePath + " (budget)");
10522
10652
  continue;
10523
10653
  }
10524
- const partial = Math.max(1, Math.ceil(Buffer.byteLength(smaller.text, "utf8") / 4));
10525
- text.push("### " + file.relativePath + " (" + file.part + ", first " + Math.max(4, keep) + " lines)");
10526
- text.push(smaller.text);
10654
+ const smallerCapped = capResultText(smaller.text);
10655
+ const partial = Math.max(1, Math.ceil(Buffer.byteLength(smallerCapped.text, "utf8") / 4));
10656
+ text.push(
10657
+ "### " + file.relativePath + " (" + file.part + ", first " + Math.max(4, keep) + " lines" + (smallerCapped.clipped ? ", first 64 KiB" : "") + ")"
10658
+ );
10659
+ text.push(smallerCapped.text);
10527
10660
  blocks.push({ path: file.relativePath, part: file.part, lines: Math.max(4, keep), tokens: partial });
10528
10661
  used += partial;
10529
10662
  continue;
10530
10663
  }
10531
- text.push("### " + file.relativePath + " (" + file.part + ")");
10664
+ text.push(
10665
+ "### " + file.relativePath + " (" + file.part + (capped2.clipped ? ", first 64 KiB" : "") + ")"
10666
+ );
10532
10667
  text.push(body);
10533
10668
  blocks.push({ path: file.relativePath, part: file.part, lines: window.text === "" ? 0 : window.text.split("\n").length, tokens });
10534
10669
  used += tokens;
@@ -10702,8 +10837,17 @@ var answerTool = {
10702
10837
  maxTokens,
10703
10838
  ...args.includeTests === true ? { includeTests: true } : {}
10704
10839
  });
10840
+ if (read.manifest.files.length === 0) {
10841
+ return {
10842
+ text: "The snapshot holds no files, so nothing can be assembled for this question. manifest.skipped records why paths were not emitted (excluded, binary, unchanged).",
10843
+ structured: { question, budgetTokens: maxTokens, usedTokens: 0, files: [], omitted: [] }
10844
+ };
10845
+ }
10705
10846
  const blocks = [];
10706
- const omitted = [];
10847
+ const omitted = plan.skipped.map((entry) => ({
10848
+ path: entry.path,
10849
+ reason: entry.reason
10850
+ }));
10707
10851
  let used = 0;
10708
10852
  const parts = /* @__PURE__ */ new Map();
10709
10853
  for (const planned of plan.files) {
@@ -10732,14 +10876,23 @@ var answerTool = {
10732
10876
  continue;
10733
10877
  }
10734
10878
  const window = windowText(section.body, 1, linesPerFile);
10735
- const text = window.text;
10736
- const tokens = estimateTokens(text);
10879
+ const numbered = window.text.split("\n").map((line, index) => String(index + 1).padStart(5, " ") + " " + line).join("\n");
10880
+ const clipped = truncateToBytes(numbered, MAX_RESULT_BYTES);
10881
+ const bodyText = clipped.isTruncated ? clipped.content : numbered;
10882
+ const tokens = estimateTokens(bodyText);
10737
10883
  if (used + tokens > maxTokens && blocks.length > 0) {
10738
10884
  omitted.push({ path: planned.path, reason: "did not fit the remaining budget" });
10739
10885
  continue;
10740
10886
  }
10741
- const numbered = text.split("\n").map((line, index) => String(index + 1).padStart(5, " ") + " " + line).join("\n");
10742
- blocks.push({ path: planned.path, why: planned.why, tokens, text: numbered, truncated: window.truncated, totalLines: window.totalLines });
10887
+ blocks.push({
10888
+ path: planned.path,
10889
+ why: planned.why,
10890
+ tokens,
10891
+ text: bodyText,
10892
+ truncated: window.truncated || clipped.isTruncated,
10893
+ totalLines: window.totalLines,
10894
+ ...clipped.isTruncated ? { clippedAtBytes: MAX_RESULT_BYTES } : {}
10895
+ });
10743
10896
  used += tokens;
10744
10897
  }
10745
10898
  const lines = [
@@ -10748,7 +10901,9 @@ var answerTool = {
10748
10901
  ];
10749
10902
  for (const block of blocks) {
10750
10903
  lines.push("");
10751
- lines.push("## " + block.path + " (" + block.tokens + " tokens, " + (block.truncated ? "first lines of " + block.totalLines : "whole file") + ")");
10904
+ lines.push(
10905
+ "## " + block.path + " (" + block.tokens + " tokens, " + (block.clippedAtBytes !== void 0 ? "first " + Math.round(block.clippedAtBytes / 1024) + " KiB of the window" : block.truncated ? "first lines of " + block.totalLines : "whole file") + ")"
10906
+ );
10752
10907
  lines.push("Why: " + block.why);
10753
10908
  lines.push("```");
10754
10909
  lines.push(block.text);
@@ -10759,6 +10914,11 @@ var answerTool = {
10759
10914
  lines.push("Not included:");
10760
10915
  for (const entry of omitted) lines.push("- " + entry.path + " - " + entry.reason);
10761
10916
  }
10917
+ if (plan.notes.length > 0) {
10918
+ lines.push("");
10919
+ lines.push("Notes:");
10920
+ for (const note of plan.notes) lines.push("- " + note);
10921
+ }
10762
10922
  return {
10763
10923
  text: lines.join("\n"),
10764
10924
  structured: { question, budgetTokens: maxTokens, usedTokens: used, files: blocks, omitted }
@@ -10873,7 +11033,7 @@ var statusTool = {
10873
11033
  `Files: ${manifest.counts.totalFiles} included, ${manifest.counts.skippedCount} skipped, ${plural(manifest.counts.partsCount, "part")}`,
10874
11034
  `Content: ${formatBytes2(manifest.counts.totalSizeBytes)} of source in ${formatBytes2(manifest.totals.totalContentBytes)} emitted`,
10875
11035
  `Fingerprint: ${manifest.fingerprint}`,
10876
- `Git: ${manifest.git.branch} @ ${manifest.git.commit}${manifest.git.isDirty ? " (dirty)" : " (clean)"}`
11036
+ `Git: ${manifest.git.branch}${manifest.git.branchFromGit === false ? " (fallback; no git branch)" : ""} @ ${manifest.git.commit}${manifest.git.isDirty ? " (dirty)" : " (clean)"}`
10877
11037
  ];
10878
11038
  if (manifest.totals.warningCount > 0) lines.push(`Warnings: ${manifest.totals.warningCount}`);
10879
11039
  if (!versionMatches) {
@@ -11024,6 +11184,16 @@ var generateTool = {
11024
11184
  minimum: 500,
11025
11185
  description: "Fit the snapshot into this token budget, highest value first."
11026
11186
  },
11187
+ only: {
11188
+ type: "array",
11189
+ items: { type: "string" },
11190
+ description: "Globs to include: replaces the config allow-list for this run."
11191
+ },
11192
+ ignore: {
11193
+ type: "array",
11194
+ items: { type: "string" },
11195
+ description: "Globs to exclude, added to the config deny-list for this run."
11196
+ },
11027
11197
  ...SCOPE_PROPERTIES
11028
11198
  },
11029
11199
  additionalProperties: false
@@ -11052,7 +11222,9 @@ var generateTool = {
11052
11222
  ...args.tokenTree === true ? { tokenTree: true } : {},
11053
11223
  ...args.stripComments === true ? { stripComments: true } : {},
11054
11224
  ...args.removeEmptyLines === true ? { removeEmptyLines: true } : {},
11055
- ...typeof args.pack === "string" ? { pack: args.pack } : {}
11225
+ ...typeof args.pack === "string" ? { pack: args.pack } : {},
11226
+ ...Array.isArray(args.only) ? { only: args.only.filter((value) => typeof value === "string") } : {},
11227
+ ...Array.isArray(args.ignore) ? { ignore: args.ignore.filter((value) => typeof value === "string") } : {}
11056
11228
  };
11057
11229
  if (typeof args.slice === "string" && typeof args.budgetTokens === "number") {
11058
11230
  return failure("slice and budgetTokens both narrow the selection; pass one.");
@@ -11096,6 +11268,20 @@ var generateTool = {
11096
11268
  };
11097
11269
  }
11098
11270
  };
11271
+ function configAsGenerated(workspace, manifest) {
11272
+ const recorded = manifest.config;
11273
+ return {
11274
+ ...workspace.config,
11275
+ ...recorded?.artifacts === void 0 ? {} : { artifacts: recorded.artifacts },
11276
+ ...recorded?.stripComments === void 0 ? {} : { stripComments: recorded.stripComments },
11277
+ ...recorded?.removeEmptyLines === void 0 ? {} : { removeEmptyLines: recorded.removeEmptyLines },
11278
+ ...recorded?.pack === void 0 ? {} : { pack: recorded.pack },
11279
+ ...recorded?.logCount === void 0 ? {} : { logCount: recorded.logCount },
11280
+ ...recorded?.skeleton === void 0 ? {} : { skeleton: recorded.skeleton },
11281
+ ...recorded?.sarif === void 0 ? {} : { sarif: recorded.sarif },
11282
+ ...recorded?.maxParts === void 0 ? {} : { maxParts: recorded.maxParts }
11283
+ };
11284
+ }
11099
11285
  var validateTool = {
11100
11286
  name: "snapshot_validate",
11101
11287
  title: "Validate the snapshot",
@@ -11117,9 +11303,11 @@ var validateTool = {
11117
11303
  const prepared = await prepare(args, context, workspaceOverrides(args));
11118
11304
  if (!prepared.ok) return prepared.outcome;
11119
11305
  const workspace = prepared.workspace;
11306
+ const read = readManifest3(workspace);
11307
+ if (!read.ok) return failure(read.message);
11120
11308
  let result;
11121
11309
  try {
11122
- result = validateSnapshot(workspace.config);
11310
+ result = validateSnapshot(configAsGenerated(workspace, read.manifest));
11123
11311
  } catch (error) {
11124
11312
  return failure(error instanceof Error ? error.message : String(error));
11125
11313
  }
@@ -11483,6 +11671,12 @@ var readTool = {
11483
11671
  `${relativePath} is recorded in ${entry.part} but its section could not be located there. Run snapshot_generate to rebuild the snapshot.`
11484
11672
  );
11485
11673
  }
11674
+ if (typeof args.fromLine === "number" && (!Number.isInteger(args.fromLine) || args.fromLine < 1)) {
11675
+ return failure('"fromLine" must be an integer of at least 1 (received ' + String(args.fromLine) + ").");
11676
+ }
11677
+ if (typeof args.lines === "number" && (!Number.isInteger(args.lines) || args.lines < 1)) {
11678
+ return failure('"lines" must be an integer of at least 1 (received ' + String(args.lines) + ").");
11679
+ }
11486
11680
  const fromLine = typeof args.fromLine === "number" ? args.fromLine : 1;
11487
11681
  const lineCount = typeof args.lines === "number" ? args.lines : 200;
11488
11682
  const window = windowText(section.body, fromLine, lineCount);
@@ -11901,6 +12095,8 @@ var COMMAND_OPTION_SCOPE = {
11901
12095
  // — the exact "flag that parses but changes nothing" this table exists to prevent — while
11902
12096
  // `--discovery` was already rejected. Both the parser and `describe`'s `appliesTo` read this
11903
12097
  // list, so removing them narrows the two together.
12098
+ // It asks the registry, not the repository: no cwd, no out-dir, nothing a config could change.
12099
+ update: ["format", "help"],
11904
12100
  report: [
11905
12101
  "cwd",
11906
12102
  "out-dir",
@@ -12193,6 +12389,13 @@ function buildAgentContract() {
12193
12389
  positionals: [],
12194
12390
  exits: [0]
12195
12391
  },
12392
+ {
12393
+ name: "update",
12394
+ aliases: [],
12395
+ summary: "Ask the npm registry whether a newer release exists and print the version it compared against. Exit 0 when current, 1 when an update is available, 2 when the registry could not be reached. The passive notice is suppressed in CI and JSON output; this command always asks and bypasses the cache.",
12396
+ positionals: [],
12397
+ exits: [0, 1, 2]
12398
+ },
12196
12399
  {
12197
12400
  name: "skill",
12198
12401
  aliases: [],
@@ -12488,14 +12691,14 @@ function buildAgentContract() {
12488
12691
  type: "boolean",
12489
12692
  default: false,
12490
12693
  appliesTo: optionAppliesTo("include-diffs"),
12491
- summary: "Also write reports/diff.md: the unstaged and staged diff, with the command that produced each, bounded to 200 KiB and truncated with a note. Absent when there is no change."
12694
+ summary: "Also write reports/diff.md: the unstaged and staged diff, with the command that produced each, bounded to 200 KiB and truncated with a note. Absent when there is no change; outside a git repository the run warns and writes nothing."
12492
12695
  },
12493
12696
  {
12494
12697
  flag: "--include-logs",
12495
12698
  type: "string",
12496
12699
  default: "unset",
12497
12700
  appliesTo: optionAppliesTo("include-logs"),
12498
- summary: "Also write reports/log.md: the last n commits (1-500), one line each, newest first."
12701
+ summary: "Also write reports/log.md: the last n commits (1-500), one line each, newest first. Outside a git repository the run warns and writes nothing."
12499
12702
  },
12500
12703
  {
12501
12704
  flag: "--token-tree",
@@ -13489,6 +13692,18 @@ function createMcpServer(options) {
13489
13692
  if (!isJsonObject(rawArguments)) {
13490
13693
  return errorResponse(id, ERROR_CODES.invalidParams, '"arguments" must be a JSON object.');
13491
13694
  }
13695
+ const missing = (prompt.arguments ?? []).filter((argument) => {
13696
+ if (argument.required !== true) return false;
13697
+ const value = rawArguments[argument.name];
13698
+ return typeof value !== "string" || value.trim() === "";
13699
+ });
13700
+ if (missing.length > 0) {
13701
+ return errorResponse(
13702
+ id,
13703
+ ERROR_CODES.invalidParams,
13704
+ 'Prompt "' + name + '" requires the ' + missing.map((argument) => '"' + argument.name + '"').join(", ") + " argument(s): " + missing.map((argument) => argument.description).join(" ")
13705
+ );
13706
+ }
13492
13707
  const built = prompt.build(rawArguments);
13493
13708
  const messages = built.messages.map((message) => ({
13494
13709
  role: message.role,
@@ -13602,7 +13817,7 @@ var DEFAULT_MAX_BODY = 2 * 1024 * 1024;
13602
13817
  var RATE_LIMIT = 60;
13603
13818
  var RATE_WINDOW_MS = 1e4;
13604
13819
  function generateToken() {
13605
- return crypto3__namespace.randomBytes(24).toString("base64url");
13820
+ return crypto2__namespace.randomBytes(24).toString("base64url");
13606
13821
  }
13607
13822
  function isLoopbackOrigin(origin) {
13608
13823
  try {
@@ -13618,7 +13833,7 @@ function timingSafeEqual2(left, right) {
13618
13833
  const a = Buffer.from(left, "utf8");
13619
13834
  const b = Buffer.from(right, "utf8");
13620
13835
  if (a.length !== b.length) return false;
13621
- return crypto3__namespace.timingSafeEqual(a, b);
13836
+ return crypto2__namespace.timingSafeEqual(a, b);
13622
13837
  }
13623
13838
  async function startHttpTransport(options) {
13624
13839
  const host = options.host ?? "127.0.0.1";
@@ -13663,6 +13878,7 @@ async function startHttpTransport(options) {
13663
13878
  noteRequest(request);
13664
13879
  const send = (status, body, extra = {}) => {
13665
13880
  const text = typeof body === "string" ? body : JSON.stringify(body);
13881
+ if (status >= 400 && status < 500 && status !== 429) metrics.refused += 1;
13666
13882
  response.writeHead(status, {
13667
13883
  "content-type": typeof body === "string" ? "text/plain; charset=utf-8" : "application/json",
13668
13884
  "content-length": Buffer.byteLength(text, "utf8"),
@@ -13674,7 +13890,6 @@ async function startHttpTransport(options) {
13674
13890
  const origin = typeof request.headers.origin === "string" ? request.headers.origin : void 0;
13675
13891
  const allowed = allowedOrigin(origin);
13676
13892
  if (origin !== void 0 && allowed === null) {
13677
- metrics.refused += 1;
13678
13893
  send(403, { error: "origin not allowed" });
13679
13894
  return;
13680
13895
  }
@@ -13712,7 +13927,7 @@ async function startHttpTransport(options) {
13712
13927
  "# HELP snapshot_requests_total HTTP requests received.",
13713
13928
  "# TYPE snapshot_requests_total counter",
13714
13929
  "snapshot_requests_total " + metrics.requests,
13715
- "# HELP snapshot_requests_refused_total Requests refused before dispatch.",
13930
+ "# HELP snapshot_requests_refused_total Requests refused before dispatch (4xx other than 429).",
13716
13931
  "# TYPE snapshot_requests_refused_total counter",
13717
13932
  "snapshot_requests_refused_total " + metrics.refused,
13718
13933
  "# HELP snapshot_requests_rate_limited_total Requests rejected by the rate limit.",
@@ -13737,7 +13952,7 @@ async function startHttpTransport(options) {
13737
13952
  send(401, { error: "unauthorized" }, { ...cors, "www-authenticate": 'Bearer realm="codebase-snapshot"' });
13738
13953
  return;
13739
13954
  }
13740
- const id = crypto3__namespace.randomBytes(12).toString("hex");
13955
+ const id = crypto2__namespace.randomBytes(12).toString("hex");
13741
13956
  response.writeHead(200, {
13742
13957
  ...cors,
13743
13958
  "content-type": "text/event-stream",
@@ -13903,7 +14118,10 @@ exports.LEGACY_PROTOCOL_VERSIONS = LEGACY_PROTOCOL_VERSIONS;
13903
14118
  exports.MAX_LINE_BYTES = MAX_LINE_BYTES;
13904
14119
  exports.METHOD = METHOD;
13905
14120
  exports.MODERN_PROTOCOL_VERSIONS = MODERN_PROTOCOL_VERSIONS;
14121
+ exports.REPORT_RESOURCE_URIS = REPORT_RESOURCE_URIS;
14122
+ exports.RESOURCE_TEMPLATE_URIS = RESOURCE_TEMPLATE_URIS;
13906
14123
  exports.SERVER_INSTRUCTIONS = SERVER_INSTRUCTIONS;
14124
+ exports.STATIC_RESOURCE_URIS = STATIC_RESOURCE_URIS;
13907
14125
  exports.SUPPORTED_PROTOCOL_VERSIONS = SUPPORTED_PROTOCOL_VERSIONS;
13908
14126
  exports.buildPrompts = buildPrompts;
13909
14127
  exports.buildResourceProvider = buildResourceProvider;