@glasstrace/sdk 1.1.1 → 1.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +78 -1
  2. package/dist/{chunk-DIM4JRXM.js → chunk-2M57EO6U.js} +2 -2
  3. package/dist/{chunk-P22UQ2OJ.js → chunk-3LILTM3T.js} +1 -1
  4. package/dist/chunk-3LILTM3T.js.map +1 -0
  5. package/dist/{chunk-MXDZHFJQ.js → chunk-C567H5EQ.js} +2 -2
  6. package/dist/{chunk-7SZQN6IU.js → chunk-NB7GJE4S.js} +2 -2
  7. package/dist/chunk-NB7GJE4S.js.map +1 -0
  8. package/dist/{chunk-ZRDQ6ZKI.js → chunk-UJ2JC7PZ.js} +92 -473
  9. package/dist/chunk-UJ2JC7PZ.js.map +1 -0
  10. package/dist/{chunk-Y26HJUPD.js → chunk-Z35HKVSO.js} +135 -8
  11. package/dist/chunk-Z35HKVSO.js.map +1 -0
  12. package/dist/cli/init.cjs +463 -440
  13. package/dist/cli/init.cjs.map +1 -1
  14. package/dist/cli/init.js +434 -63
  15. package/dist/cli/init.js.map +1 -1
  16. package/dist/cli/mcp-add.cjs +14 -2
  17. package/dist/cli/mcp-add.cjs.map +1 -1
  18. package/dist/cli/mcp-add.js +17 -5
  19. package/dist/cli/mcp-add.js.map +1 -1
  20. package/dist/cli/status.cjs.map +1 -1
  21. package/dist/cli/status.js +1 -3
  22. package/dist/cli/status.js.map +1 -1
  23. package/dist/cli/uninit.cjs +3 -3
  24. package/dist/cli/uninit.cjs.map +1 -1
  25. package/dist/cli/uninit.js +3 -3
  26. package/dist/cli/validate.cjs +14162 -2
  27. package/dist/cli/validate.cjs.map +1 -1
  28. package/dist/cli/validate.d.cts +7 -3
  29. package/dist/cli/validate.d.ts +7 -3
  30. package/dist/cli/validate.js +25 -2
  31. package/dist/cli/validate.js.map +1 -1
  32. package/dist/index.cjs +134 -5
  33. package/dist/index.cjs.map +1 -1
  34. package/dist/index.js +3 -3
  35. package/dist/{monorepo-GSL6JD3G.js → monorepo-PFVNPQ6X.js} +3 -5
  36. package/dist/node-entry.cjs +134 -5
  37. package/dist/node-entry.cjs.map +1 -1
  38. package/dist/node-entry.js +3 -3
  39. package/package.json +1 -1
  40. package/dist/chunk-7SZQN6IU.js.map +0 -1
  41. package/dist/chunk-P22UQ2OJ.js.map +0 -1
  42. package/dist/chunk-Y26HJUPD.js.map +0 -1
  43. package/dist/chunk-ZRDQ6ZKI.js.map +0 -1
  44. /package/dist/{chunk-DIM4JRXM.js.map → chunk-2M57EO6U.js.map} +0 -0
  45. /package/dist/{chunk-MXDZHFJQ.js.map → chunk-C567H5EQ.js.map} +0 -0
  46. /package/dist/{monorepo-GSL6JD3G.js.map → monorepo-PFVNPQ6X.js.map} +0 -0
@@ -3,7 +3,7 @@
3
3
  */
4
4
  interface ValidationIssue {
5
5
  /** Stable machine-readable identifier for the issue class. */
6
- code: "glasstrace-dir-without-register-import" | "sdk-import-without-glasstrace-dir" | "mcp-marker-without-configs" | "mcp-configs-without-marker";
6
+ code: "glasstrace-dir-without-register-import" | "sdk-import-without-glasstrace-dir" | "mcp-marker-without-configs" | "mcp-configs-without-marker" | "mcp-helper-stale-credential";
7
7
  /** Human-readable message describing the inconsistency. */
8
8
  message: string;
9
9
  /** Suggested command or manual action to resolve the issue. */
@@ -39,7 +39,7 @@ declare function hasGlasstraceImport(content: string): boolean;
39
39
  declare function hasRegisterGlasstraceImport(content: string): boolean;
40
40
  /**
41
41
  * Validates consistency between the filesystem artifacts that `sdk init`
42
- * produces (DISC-1247 Scenario 4). Detects four classes of inconsistency:
42
+ * produces (DISC-1247 Scenario 4). Detects five classes of inconsistency:
43
43
  *
44
44
  * 1. `.glasstrace/` exists but `instrumentation.ts` does not import
45
45
  * `registerGlasstrace` from `@glasstrace/sdk`.
@@ -47,6 +47,10 @@ declare function hasRegisterGlasstraceImport(content: string): boolean;
47
47
  * from `@glasstrace/sdk`.
48
48
  * 3. `.glasstrace/mcp-connected` marker exists but no MCP config files.
49
49
  * 4. MCP config files exist but no `.glasstrace/mcp-connected` marker.
50
+ * 5. `.glasstrace/mcp-connected` marker records a credential identity
51
+ * that no longer matches the project's effective MCP credential
52
+ * (e.g. project moved from anon to account/dev-key but the managed
53
+ * helper config still embeds the anon bearer — DISC-1512).
50
54
  *
51
55
  * Each issue includes a stable `code`, a message, and a suggested fix.
52
56
  * Exit code is non-zero whenever any issue is detected so CI pipelines
@@ -55,6 +59,6 @@ declare function hasRegisterGlasstraceImport(content: string): boolean;
55
59
  * @param options - Configuration for the validator.
56
60
  * @returns A structured result describing detected inconsistencies.
57
61
  */
58
- declare function runValidate(options: ValidateOptions): ValidateResult;
62
+ declare function runValidate(options: ValidateOptions): Promise<ValidateResult>;
59
63
 
60
64
  export { type ValidateOptions, type ValidateResult, type ValidationIssue, hasGlasstraceImport, hasRegisterGlasstraceImport, runValidate };
@@ -3,7 +3,7 @@
3
3
  */
4
4
  interface ValidationIssue {
5
5
  /** Stable machine-readable identifier for the issue class. */
6
- code: "glasstrace-dir-without-register-import" | "sdk-import-without-glasstrace-dir" | "mcp-marker-without-configs" | "mcp-configs-without-marker";
6
+ code: "glasstrace-dir-without-register-import" | "sdk-import-without-glasstrace-dir" | "mcp-marker-without-configs" | "mcp-configs-without-marker" | "mcp-helper-stale-credential";
7
7
  /** Human-readable message describing the inconsistency. */
8
8
  message: string;
9
9
  /** Suggested command or manual action to resolve the issue. */
@@ -39,7 +39,7 @@ declare function hasGlasstraceImport(content: string): boolean;
39
39
  declare function hasRegisterGlasstraceImport(content: string): boolean;
40
40
  /**
41
41
  * Validates consistency between the filesystem artifacts that `sdk init`
42
- * produces (DISC-1247 Scenario 4). Detects four classes of inconsistency:
42
+ * produces (DISC-1247 Scenario 4). Detects five classes of inconsistency:
43
43
  *
44
44
  * 1. `.glasstrace/` exists but `instrumentation.ts` does not import
45
45
  * `registerGlasstrace` from `@glasstrace/sdk`.
@@ -47,6 +47,10 @@ declare function hasRegisterGlasstraceImport(content: string): boolean;
47
47
  * from `@glasstrace/sdk`.
48
48
  * 3. `.glasstrace/mcp-connected` marker exists but no MCP config files.
49
49
  * 4. MCP config files exist but no `.glasstrace/mcp-connected` marker.
50
+ * 5. `.glasstrace/mcp-connected` marker records a credential identity
51
+ * that no longer matches the project's effective MCP credential
52
+ * (e.g. project moved from anon to account/dev-key but the managed
53
+ * helper config still embeds the anon bearer — DISC-1512).
50
54
  *
51
55
  * Each issue includes a stable `code`, a message, and a suggested fix.
52
56
  * Exit code is non-zero whenever any issue is detected so CI pipelines
@@ -55,6 +59,6 @@ declare function hasRegisterGlasstraceImport(content: string): boolean;
55
59
  * @param options - Configuration for the validator.
56
60
  * @returns A structured result describing detected inconsistencies.
57
61
  */
58
- declare function runValidate(options: ValidateOptions): ValidateResult;
62
+ declare function runValidate(options: ValidateOptions): Promise<ValidateResult>;
59
63
 
60
64
  export { type ValidateOptions, type ValidateResult, type ValidationIssue, hasGlasstraceImport, hasRegisterGlasstraceImport, runValidate };
@@ -1,3 +1,9 @@
1
+ import {
2
+ identityFingerprint,
3
+ readMcpMarker,
4
+ resolveEffectiveMcpCredential
5
+ } from "../chunk-3LILTM3T.js";
6
+ import "../chunk-X5MAXP5T.js";
1
7
  import "../chunk-NSBPE2FW.js";
2
8
 
3
9
  // src/cli/validate.ts
@@ -7,7 +13,8 @@ var MCP_CONFIG_CANDIDATES = [
7
13
  ".mcp.json",
8
14
  ".cursor/mcp.json",
9
15
  ".gemini/settings.json",
10
- ".codex/config.toml"
16
+ ".codex/config.toml",
17
+ ".glasstrace/mcp.json"
11
18
  ];
12
19
  function hasGlasstraceImport(content) {
13
20
  return /@glasstrace\/sdk/.test(content);
@@ -18,7 +25,7 @@ function hasRegisterGlasstraceImport(content) {
18
25
  if (!importMatch) return false;
19
26
  return importMatch[1].split(",").map((s) => s.trim()).includes("registerGlasstrace");
20
27
  }
21
- function runValidate(options) {
28
+ async function runValidate(options) {
22
29
  const { projectRoot } = options;
23
30
  const issues = [];
24
31
  const glasstraceDir = path.join(projectRoot, ".glasstrace");
@@ -63,6 +70,22 @@ function runValidate(options) {
63
70
  fix: "Run `npx glasstrace init` to re-register the marker, or `npx glasstrace uninit` to fully remove MCP configuration."
64
71
  });
65
72
  }
73
+ if (markerExists) {
74
+ try {
75
+ const [markerState, resolved] = await Promise.all([
76
+ readMcpMarker(projectRoot),
77
+ resolveEffectiveMcpCredential(projectRoot)
78
+ ]);
79
+ if (markerState.status === "valid" && resolved.effective !== null && markerState.credentialHash !== identityFingerprint(resolved.effective.key)) {
80
+ issues.push({
81
+ code: "mcp-helper-stale-credential",
82
+ message: "Managed MCP configs were last refreshed with a different credential than the project is now using. MCP queries may return no traces while the dashboard sees them.",
83
+ fix: "Run `npx glasstrace mcp add --force` to refresh managed MCP configs with the current credential."
84
+ });
85
+ }
86
+ } catch {
87
+ }
88
+ }
66
89
  const summary = [];
67
90
  if (issues.length === 0) {
68
91
  summary.push("Glasstrace install state is consistent.");
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/cli/validate.ts"],"sourcesContent":["import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\n/**\n * A single artifact-state inconsistency detected by `sdk init --validate`.\n */\nexport interface ValidationIssue {\n /** Stable machine-readable identifier for the issue class. */\n code:\n | \"glasstrace-dir-without-register-import\"\n | \"sdk-import-without-glasstrace-dir\"\n | \"mcp-marker-without-configs\"\n | \"mcp-configs-without-marker\";\n /** Human-readable message describing the inconsistency. */\n message: string;\n /** Suggested command or manual action to resolve the issue. */\n fix: string;\n}\n\n/** Options for `runValidate`. */\nexport interface ValidateOptions {\n projectRoot: string;\n}\n\n/** Structured result of running the validator. */\nexport interface ValidateResult {\n /** Zero when no issues; non-zero when any issue is detected. */\n exitCode: number;\n /** Ordered lines of human-friendly summary output. */\n summary: string[];\n /** Detailed per-issue findings. */\n issues: ValidationIssue[];\n}\n\n/** MCP config files init may create. Used to detect stale state. */\nconst MCP_CONFIG_CANDIDATES = [\n \".mcp.json\",\n \".cursor/mcp.json\",\n \".gemini/settings.json\",\n \".codex/config.toml\",\n] as const;\n\n/**\n * Returns true when the given instrumentation file imports\n * `@glasstrace/sdk` (which includes the `registerGlasstrace` import\n * emitted by `sdk init`).\n *\n * @internal Exported for unit testing only.\n */\nexport function hasGlasstraceImport(content: string): boolean {\n return /@glasstrace\\/sdk/.test(content);\n}\n\n/**\n * Returns true when the file imports `registerGlasstrace` specifically\n * (as opposed to other named exports such as `withGlasstraceConfig`).\n *\n * @internal Exported for unit testing only.\n */\nexport function hasRegisterGlasstraceImport(content: string): boolean {\n // Single- or multi-specifier imports from @glasstrace/sdk that include\n // `registerGlasstrace` as a named export.\n const match = /import\\s*\\{([^}]+)\\}\\s*from\\s*[\"']@glasstrace\\/sdk[\"']/;\n const importMatch = match.exec(content);\n if (!importMatch) return false;\n return importMatch[1]\n .split(\",\")\n .map((s) => s.trim())\n .includes(\"registerGlasstrace\");\n}\n\n/**\n * Validates consistency between the filesystem artifacts that `sdk init`\n * produces (DISC-1247 Scenario 4). Detects four classes of inconsistency:\n *\n * 1. `.glasstrace/` exists but `instrumentation.ts` does not import\n * `registerGlasstrace` from `@glasstrace/sdk`.\n * 2. `.glasstrace/` is missing but `instrumentation.ts` still imports\n * from `@glasstrace/sdk`.\n * 3. `.glasstrace/mcp-connected` marker exists but no MCP config files.\n * 4. MCP config files exist but no `.glasstrace/mcp-connected` marker.\n *\n * Each issue includes a stable `code`, a message, and a suggested fix.\n * Exit code is non-zero whenever any issue is detected so CI pipelines\n * can gate on `sdk init --validate`.\n *\n * @param options - Configuration for the validator.\n * @returns A structured result describing detected inconsistencies.\n */\nexport function runValidate(options: ValidateOptions): ValidateResult {\n const { projectRoot } = options;\n const issues: ValidationIssue[] = [];\n\n const glasstraceDir = path.join(projectRoot, \".glasstrace\");\n const instrumentationPath = path.join(projectRoot, \"instrumentation.ts\");\n const markerPath = path.join(glasstraceDir, \"mcp-connected\");\n\n const glasstraceDirExists = isDirectorySafe(glasstraceDir);\n const instrumentationExists = fs.existsSync(instrumentationPath);\n const instrumentationContent = instrumentationExists\n ? safeReadFile(instrumentationPath)\n : null;\n const markerExists = fs.existsSync(markerPath);\n\n const mcpConfigsPresent = MCP_CONFIG_CANDIDATES.filter((rel) =>\n fs.existsSync(path.join(projectRoot, rel)),\n );\n\n // 1. .glasstrace/ present but instrumentation missing the SDK import\n if (glasstraceDirExists) {\n if (\n instrumentationContent === null ||\n !hasRegisterGlasstraceImport(instrumentationContent)\n ) {\n issues.push({\n code: \"glasstrace-dir-without-register-import\",\n message:\n \".glasstrace/ exists but instrumentation.ts is missing the registerGlasstrace import.\",\n fix: \"Run `npx glasstrace init` to re-scaffold instrumentation.ts, or remove .glasstrace/ if the SDK is no longer in use.\",\n });\n }\n }\n\n // 2. .glasstrace/ missing but instrumentation still imports the SDK\n if (!glasstraceDirExists && instrumentationContent !== null) {\n if (hasGlasstraceImport(instrumentationContent)) {\n issues.push({\n code: \"sdk-import-without-glasstrace-dir\",\n message:\n \"instrumentation.ts imports from @glasstrace/sdk but .glasstrace/ is missing.\",\n fix: \"Run `npx glasstrace init` to recreate .glasstrace/, or `npx glasstrace uninit` to fully remove the SDK.\",\n });\n }\n }\n\n // 3. MCP marker present but no MCP config files exist\n if (markerExists && mcpConfigsPresent.length === 0) {\n issues.push({\n code: \"mcp-marker-without-configs\",\n message:\n \".glasstrace/mcp-connected marker is present but no MCP config files were found.\",\n fix: \"Run `npx glasstrace mcp add --force` to regenerate MCP configs, or delete .glasstrace/mcp-connected.\",\n });\n }\n\n // 4. MCP config files exist but no marker\n if (!markerExists && mcpConfigsPresent.length > 0) {\n issues.push({\n code: \"mcp-configs-without-marker\",\n message: `MCP config files exist (${mcpConfigsPresent.join(\", \")}) but .glasstrace/mcp-connected marker is missing.`,\n fix: \"Run `npx glasstrace init` to re-register the marker, or `npx glasstrace uninit` to fully remove MCP configuration.\",\n });\n }\n\n const summary: string[] = [];\n if (issues.length === 0) {\n summary.push(\"Glasstrace install state is consistent.\");\n } else {\n summary.push(\n `Detected ${issues.length} inconsistenc${issues.length === 1 ? \"y\" : \"ies\"} in Glasstrace install state:`,\n );\n }\n\n return {\n exitCode: issues.length > 0 ? 1 : 0,\n summary,\n issues,\n };\n}\n\n/**\n * Reads a file as UTF-8, returning `null` if the file cannot be read.\n */\nfunction safeReadFile(filePath: string): string | null {\n try {\n return fs.readFileSync(filePath, \"utf-8\");\n } catch {\n return null;\n }\n}\n\n/**\n * Returns true when the path exists and is a directory. Returns false\n * when the path is missing, is not a directory, or when `statSync`\n * throws (permission denied, TOCTOU race between existsSync and\n * statSync, etc). Validation is best-effort and must not throw — a\n * crash here would turn a reporting tool into a hard failure.\n */\nfunction isDirectorySafe(dirPath: string): boolean {\n try {\n if (!fs.existsSync(dirPath)) return false;\n return fs.statSync(dirPath).isDirectory();\n } catch {\n return false;\n }\n}\n"],"mappings":";;;AAAA,YAAY,QAAQ;AACpB,YAAY,UAAU;AAkCtB,IAAM,wBAAwB;AAAA,EAC5B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AASO,SAAS,oBAAoB,SAA0B;AAC5D,SAAO,mBAAmB,KAAK,OAAO;AACxC;AAQO,SAAS,4BAA4B,SAA0B;AAGpE,QAAM,QAAQ;AACd,QAAM,cAAc,MAAM,KAAK,OAAO;AACtC,MAAI,CAAC,YAAa,QAAO;AACzB,SAAO,YAAY,CAAC,EACjB,MAAM,GAAG,EACT,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC,EACnB,SAAS,oBAAoB;AAClC;AAoBO,SAAS,YAAY,SAA0C;AACpE,QAAM,EAAE,YAAY,IAAI;AACxB,QAAM,SAA4B,CAAC;AAEnC,QAAM,gBAAqB,UAAK,aAAa,aAAa;AAC1D,QAAM,sBAA2B,UAAK,aAAa,oBAAoB;AACvE,QAAM,aAAkB,UAAK,eAAe,eAAe;AAE3D,QAAM,sBAAsB,gBAAgB,aAAa;AACzD,QAAM,wBAA2B,cAAW,mBAAmB;AAC/D,Q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AQ;AACN,WAAO;AAAA,EACT;AACF;AASA,SAAS,gBAAgB,SAA0B;AACjD,MAAI;AACF,QAAI,CAAI,cAAW,OAAO,EAAG,QAAO;AACpC,WAAU,YAAS,OAAO,EAAE,YAAY;AAAA,EAC1C,QAAQ;AACN,WAAO;AAAA,EACT;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/cli/validate.ts"],"sourcesContent":["import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport {\n identityFingerprint,\n readMcpMarker,\n resolveEffectiveMcpCredential,\n} from \"../mcp-runtime.js\";\n\n/**\n * A single artifact-state inconsistency detected by `sdk init --validate`.\n */\nexport interface ValidationIssue {\n /** Stable machine-readable identifier for the issue class. */\n code:\n | \"glasstrace-dir-without-register-import\"\n | \"sdk-import-without-glasstrace-dir\"\n | \"mcp-marker-without-configs\"\n | \"mcp-configs-without-marker\"\n | \"mcp-helper-stale-credential\";\n /** Human-readable message describing the inconsistency. */\n message: string;\n /** Suggested command or manual action to resolve the issue. */\n fix: string;\n}\n\n/** Options for `runValidate`. */\nexport interface ValidateOptions {\n projectRoot: string;\n}\n\n/** Structured result of running the validator. */\nexport interface ValidateResult {\n /** Zero when no issues; non-zero when any issue is detected. */\n exitCode: number;\n /** Ordered lines of human-friendly summary output. */\n summary: string[];\n /** Detailed per-issue findings. */\n issues: ValidationIssue[];\n}\n\n/**\n * MCP config files init or `mcp add` may create. Used by issue classes\n * 3 and 4 to detect marker/config drift. The SDK-managed generic\n * helper at `.glasstrace/mcp.json` is included so generic-only\n * installs (e.g. CI-mode init, or workspaces whose only consumer is\n * the validation/debug query helper) validate cleanly instead of\n * being incorrectly reported as `mcp-marker-without-configs`.\n */\nconst MCP_CONFIG_CANDIDATES = [\n \".mcp.json\",\n \".cursor/mcp.json\",\n \".gemini/settings.json\",\n \".codex/config.toml\",\n \".glasstrace/mcp.json\",\n] as const;\n\n/**\n * Returns true when the given instrumentation file imports\n * `@glasstrace/sdk` (which includes the `registerGlasstrace` import\n * emitted by `sdk init`).\n *\n * @internal Exported for unit testing only.\n */\nexport function hasGlasstraceImport(content: string): boolean {\n return /@glasstrace\\/sdk/.test(content);\n}\n\n/**\n * Returns true when the file imports `registerGlasstrace` specifically\n * (as opposed to other named exports such as `withGlasstraceConfig`).\n *\n * @internal Exported for unit testing only.\n */\nexport function hasRegisterGlasstraceImport(content: string): boolean {\n // Single- or multi-specifier imports from @glasstrace/sdk that include\n // `registerGlasstrace` as a named export.\n const match = /import\\s*\\{([^}]+)\\}\\s*from\\s*[\"']@glasstrace\\/sdk[\"']/;\n const importMatch = match.exec(content);\n if (!importMatch) return false;\n return importMatch[1]\n .split(\",\")\n .map((s) => s.trim())\n .includes(\"registerGlasstrace\");\n}\n\n/**\n * Validates consistency between the filesystem artifacts that `sdk init`\n * produces (DISC-1247 Scenario 4). Detects five classes of inconsistency:\n *\n * 1. `.glasstrace/` exists but `instrumentation.ts` does not import\n * `registerGlasstrace` from `@glasstrace/sdk`.\n * 2. `.glasstrace/` is missing but `instrumentation.ts` still imports\n * from `@glasstrace/sdk`.\n * 3. `.glasstrace/mcp-connected` marker exists but no MCP config files.\n * 4. MCP config files exist but no `.glasstrace/mcp-connected` marker.\n * 5. `.glasstrace/mcp-connected` marker records a credential identity\n * that no longer matches the project's effective MCP credential\n * (e.g. project moved from anon to account/dev-key but the managed\n * helper config still embeds the anon bearer — DISC-1512).\n *\n * Each issue includes a stable `code`, a message, and a suggested fix.\n * Exit code is non-zero whenever any issue is detected so CI pipelines\n * can gate on `sdk init --validate`.\n *\n * @param options - Configuration for the validator.\n * @returns A structured result describing detected inconsistencies.\n */\nexport async function runValidate(options: ValidateOptions): Promise<ValidateResult> {\n const { projectRoot } = options;\n const issues: ValidationIssue[] = [];\n\n const glasstraceDir = path.join(projectRoot, \".glasstrace\");\n const instrumentationPath = path.join(projectRoot, \"instrumentation.ts\");\n const markerPath = path.join(glasstraceDir, \"mcp-connected\");\n\n const glasstraceDirExists = isDirectorySafe(glasstraceDir);\n const instrumentationExists = fs.existsSync(instrumentationPath);\n const instrumentationContent = instrumentationExists\n ? safeReadFile(instrumentationPath)\n : null;\n const markerExists = fs.existsSync(markerPath);\n\n const mcpConfigsPresent = MCP_CONFIG_CANDIDATES.filter((rel) =>\n fs.existsSync(path.join(projectRoot, rel)),\n );\n\n // 1. .glasstrace/ present but instrumentation missing the SDK import\n if (glasstraceDirExists) {\n if (\n instrumentationContent === null ||\n !hasRegisterGlasstraceImport(instrumentationContent)\n ) {\n issues.push({\n code: \"glasstrace-dir-without-register-import\",\n message:\n \".glasstrace/ exists but instrumentation.ts is missing the registerGlasstrace import.\",\n fix: \"Run `npx glasstrace init` to re-scaffold instrumentation.ts, or remove .glasstrace/ if the SDK is no longer in use.\",\n });\n }\n }\n\n // 2. .glasstrace/ missing but instrumentation still imports the SDK\n if (!glasstraceDirExists && instrumentationContent !== null) {\n if (hasGlasstraceImport(instrumentationContent)) {\n issues.push({\n code: \"sdk-import-without-glasstrace-dir\",\n message:\n \"instrumentation.ts imports from @glasstrace/sdk but .glasstrace/ is missing.\",\n fix: \"Run `npx glasstrace init` to recreate .glasstrace/, or `npx glasstrace uninit` to fully remove the SDK.\",\n });\n }\n }\n\n // 3. MCP marker present but no MCP config files exist\n if (markerExists && mcpConfigsPresent.length === 0) {\n issues.push({\n code: \"mcp-marker-without-configs\",\n message:\n \".glasstrace/mcp-connected marker is present but no MCP config files were found.\",\n fix: \"Run `npx glasstrace mcp add --force` to regenerate MCP configs, or delete .glasstrace/mcp-connected.\",\n });\n }\n\n // 4. MCP config files exist but no marker\n if (!markerExists && mcpConfigsPresent.length > 0) {\n issues.push({\n code: \"mcp-configs-without-marker\",\n message: `MCP config files exist (${mcpConfigsPresent.join(\", \")}) but .glasstrace/mcp-connected marker is missing.`,\n fix: \"Run `npx glasstrace init` to re-register the marker, or `npx glasstrace uninit` to fully remove MCP configuration.\",\n });\n }\n\n // 5. Marker records a credential identity that no longer matches\n // the project's effective MCP credential. Catches the DISC-1512\n // case where `.glasstrace/config` is linked to an account and\n // `.env.local` carries a dev key, but managed MCP configs still\n // embed an anon bearer (so MCP queries are scoped to anon rows\n // while ingestion writes account-scoped traces).\n if (markerExists) {\n try {\n const [markerState, resolved] = await Promise.all([\n readMcpMarker(projectRoot),\n resolveEffectiveMcpCredential(projectRoot),\n ]);\n if (\n markerState.status === \"valid\" &&\n resolved.effective !== null &&\n markerState.credentialHash !== identityFingerprint(resolved.effective.key)\n ) {\n issues.push({\n code: \"mcp-helper-stale-credential\",\n message:\n \"Managed MCP configs were last refreshed with a different credential than the project is now using. MCP queries may return no traces while the dashboard sees them.\",\n fix: \"Run `npx glasstrace mcp add --force` to refresh managed MCP configs with the current credential.\",\n });\n }\n } catch {\n // Validation is best-effort and must not throw — credential\n // resolution failures here are silent and leave the issue\n // unflagged. Other classes still apply.\n }\n }\n\n const summary: string[] = [];\n if (issues.length === 0) {\n summary.push(\"Glasstrace install state is consistent.\");\n } else {\n summary.push(\n `Detected ${issues.length} inconsistenc${issues.length === 1 ? \"y\" : \"ies\"} in Glasstrace install state:`,\n );\n }\n\n return {\n exitCode: issues.length > 0 ? 1 : 0,\n summary,\n issues,\n };\n}\n\n/**\n * Reads a file as UTF-8, returning `null` if the file cannot be read.\n */\nfunction safeReadFile(filePath: string): string | null {\n try {\n return fs.readFileSync(filePath, \"utf-8\");\n } catch {\n return null;\n }\n}\n\n/**\n * Returns true when the path exists and is a directory. Returns false\n * when the path is missing, is not a directory, or when `statSync`\n * throws (permission denied, TOCTOU race between existsSync and\n * statSync, etc). Validation is best-effort and must not throw — a\n * crash here would turn a reporting tool into a hard failure.\n */\nfunction isDirectorySafe(dirPath: string): boolean {\n try {\n if (!fs.existsSync(dirPath)) return false;\n return fs.statSync(dirPath).isDirectory();\n } catch {\n return false;\n }\n}\n"],"mappings":";;;;;;;;;AAAA,YAAY,QAAQ;AACpB,YAAY,UAAU;AA+CtB,IAAM,wBAAwB;AAAA,EAC5B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAA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034
18034
  init_console_capture();
18035
18035
  init_error_nudge();
18036
+
18037
+ // src/error-response-body.ts
18038
+ var ERROR_RESPONSE_BODY_MAX_BYTES = 4096;
18039
+ var ERROR_RESPONSE_BODY_TRUNCATION_MARKER = "...[truncated]";
18040
+ var REDACTED = "[REDACTED]";
18041
+ var ERROR_STATUS_MIN = 400;
18042
+ var ERROR_STATUS_MAX = 599;
18043
+ function isHttpErrorStatus(status) {
18044
+ let numeric;
18045
+ if (typeof status === "number") {
18046
+ numeric = status;
18047
+ } else if (typeof status === "string" && status.length > 0) {
18048
+ numeric = Number(status);
18049
+ } else {
18050
+ return false;
18051
+ }
18052
+ if (!Number.isFinite(numeric)) return false;
18053
+ return numeric >= ERROR_STATUS_MIN && numeric <= ERROR_STATUS_MAX;
18054
+ }
18055
+ var REDACTION_PATTERNS = [
18056
+ // Order matters: redact specific token shapes BEFORE the generic
18057
+ // key=value catcher so a literal `Bearer eyJ…` collapses into a single
18058
+ // [REDACTED] and the JWT regex does not separately match the suffix.
18059
+ {
18060
+ name: "bearer",
18061
+ // Case-insensitive on the scheme: HTTP frameworks and proxies
18062
+ // round-trip the auth scheme with inconsistent casing
18063
+ // (`Bearer`, `bearer`, `BEARER`), and a real token leaks just as
18064
+ // badly under any of them.
18065
+ pattern: /\bBearer\s+[A-Za-z0-9._\-+/=]+/gi
18066
+ },
18067
+ {
18068
+ name: "jwt",
18069
+ // Three base64url segments separated by dots. Real JWTs encode at
18070
+ // minimum a small JSON header in the first segment, which alone is
18071
+ // typically ≥10 chars after base64url; a 16-char floor avoids false
18072
+ // positives on dotted text like a stack-trace frame
18073
+ // (`react.dom.server`) while still catching every real JWT we have
18074
+ // seen in the wild. Anchored with word boundaries on both sides so
18075
+ // a 3-dot semantic version like "next@15.4.1.2" does not match.
18076
+ pattern: /\b[A-Za-z0-9_-]{16,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/g
18077
+ },
18078
+ {
18079
+ name: "glasstrace-api-key",
18080
+ // gt_dev_* and gt_anon_* keys are >=24 chars of [A-Za-z0-9].
18081
+ pattern: /\bgt_(?:dev|anon)_[A-Za-z0-9]{16,}\b/g
18082
+ },
18083
+ {
18084
+ name: "aws-access-key",
18085
+ // 20-char prefix-fixed identifier.
18086
+ pattern: /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g
18087
+ },
18088
+ {
18089
+ name: "key-value-secret-quoted",
18090
+ // Quoted-string variant: (key) [:=] "<value>". The value runs to
18091
+ // the next unescaped closing quote so a multi-word secret like
18092
+ // `password="my secret phrase"` is fully consumed instead of
18093
+ // splitting at the first space and leaving the tail visible.
18094
+ // The leading `(?<![A-Za-z0-9_])` prevents matching inside
18095
+ // identifiers like `passwordless`. The trailing `"?` after the
18096
+ // keyword absorbs the closing quote in JSON-style `"apikey":
18097
+ // "value"` so the colon is still seen as the separator.
18098
+ pattern: /(?<![A-Za-z0-9_])(?:api[_-]?key|apikey|secret|password|token)"?\s*[:=]\s*"(?:[^"\\]|\\.)*"/gi
18099
+ },
18100
+ {
18101
+ name: "key-value-secret-bare",
18102
+ // Unquoted variant: (key) [:=] <bare-value>. The bare value
18103
+ // capture stops at common JSON/text delimiters so we redact only
18104
+ // the value, not surrounding structure. Listed AFTER the quoted
18105
+ // variant so a quoted value's surrounding `"` are consumed by
18106
+ // the first pattern and we never fall through here for a quoted
18107
+ // secret.
18108
+ pattern: /(?<![A-Za-z0-9_])(?:api[_-]?key|apikey|secret|password|token)"?\s*[:=]\s*[^\s,;}\]"]+/gi
18109
+ }
18110
+ ];
18111
+ function sanitizeErrorResponseBody(body) {
18112
+ let out = body;
18113
+ for (const { pattern } of REDACTION_PATTERNS) {
18114
+ out = out.replace(pattern, REDACTED);
18115
+ }
18116
+ return out;
18117
+ }
18118
+ function truncateErrorResponseBody(body) {
18119
+ const encoder = new TextEncoder();
18120
+ const encoded = encoder.encode(body);
18121
+ if (encoded.byteLength <= ERROR_RESPONSE_BODY_MAX_BYTES) {
18122
+ return body;
18123
+ }
18124
+ let cut = ERROR_RESPONSE_BODY_MAX_BYTES;
18125
+ let scan = cut - 1;
18126
+ while (scan >= 0 && (encoded[scan] & 192) === 128) {
18127
+ scan -= 1;
18128
+ }
18129
+ if (scan >= 0) {
18130
+ const leading = encoded[scan];
18131
+ let expected = 1;
18132
+ if ((leading & 128) === 0) {
18133
+ expected = 1;
18134
+ } else if ((leading & 224) === 192) {
18135
+ expected = 2;
18136
+ } else if ((leading & 240) === 224) {
18137
+ expected = 3;
18138
+ } else if ((leading & 248) === 240) {
18139
+ expected = 4;
18140
+ }
18141
+ if (scan + expected > cut) {
18142
+ cut = scan;
18143
+ }
18144
+ }
18145
+ const decoder = new TextDecoder("utf-8", { fatal: false });
18146
+ const sliced = encoded.subarray(0, cut);
18147
+ const decoded = decoder.decode(sliced);
18148
+ return decoded + ERROR_RESPONSE_BODY_TRUNCATION_MARKER;
18149
+ }
18150
+ function prepareErrorResponseBody(body) {
18151
+ if (body.length === 0) return null;
18152
+ if (body.trim().length === 0) return null;
18153
+ const sanitized = sanitizeErrorResponseBody(body);
18154
+ return truncateErrorResponseBody(sanitized);
18155
+ }
18156
+
18157
+ // src/enriching-exporter.ts
18036
18158
  var ATTR = GLASSTRACE_ATTRIBUTE_NAMES;
18037
18159
  var API_KEY_PENDING = "pending";
18038
18160
  var MAX_PENDING_SPANS = 1024;
@@ -18260,7 +18382,14 @@ var GlasstraceExporter = class {
18260
18382
  if (this.getConfig().errorResponseBodies) {
18261
18383
  const responseBody = attrs["glasstrace.internal.response_body"];
18262
18384
  if (typeof responseBody === "string") {
18263
- extra[ATTR.ERROR_RESPONSE_BODY] = responseBody.slice(0, 500);
18385
+ const enrichedStatus = extra[ATTR.HTTP_STATUS_CODE];
18386
+ const effectiveStatus = typeof enrichedStatus === "number" ? enrichedStatus : statusCode;
18387
+ if (isHttpErrorStatus(effectiveStatus)) {
18388
+ const prepared = prepareErrorResponseBody(responseBody);
18389
+ if (prepared !== null) {
18390
+ extra[ATTR.ERROR_RESPONSE_BODY] = prepared;
18391
+ }
18392
+ }
18264
18393
  }
18265
18394
  }
18266
18395
  const spanAny = span;
@@ -22126,7 +22255,7 @@ function registerGlasstrace(options) {
22126
22255
  setCoreState(CoreState.REGISTERING);
22127
22256
  startRuntimeStateWriter({
22128
22257
  projectRoot: process.cwd(),
22129
- sdkVersion: "1.1.1"
22258
+ sdkVersion: "1.1.2"
22130
22259
  });
22131
22260
  const config2 = resolveConfig(options);
22132
22261
  if (config2.verbose) {
@@ -22292,8 +22421,8 @@ async function backgroundInit(config2, anonKeyForInit, generation) {
22292
22421
  if (config2.verbose) {
22293
22422
  console.info("[glasstrace] Background init firing.");
22294
22423
  }
22295
- const healthReport = collectHealthReport("1.1.1");
22296
- const initResult = await performInit(config2, anonKeyForInit, "1.1.1", healthReport);
22424
+ const healthReport = collectHealthReport("1.1.2");
22425
+ const initResult = await performInit(config2, anonKeyForInit, "1.1.2", healthReport);
22297
22426
  if (generation !== registrationGeneration) return;
22298
22427
  const currentState = getCoreState();
22299
22428
  if (currentState === CoreState.SHUTTING_DOWN || currentState === CoreState.SHUTDOWN) {
@@ -22316,7 +22445,7 @@ async function backgroundInit(config2, anonKeyForInit, generation) {
22316
22445
  }
22317
22446
  maybeInstallConsoleCapture();
22318
22447
  if (didLastInitSucceed()) {
22319
- startHeartbeat(config2, anonKeyForInit, "1.1.1", generation, (newApiKey, accountId) => {
22448
+ startHeartbeat(config2, anonKeyForInit, "1.1.2", generation, (newApiKey, accountId) => {
22320
22449
  setAuthState(AuthState.CLAIMING);
22321
22450
  emitLifecycleEvent("auth:claim_started", { accountId });
22322
22451
  setResolvedApiKey(newApiKey);