@glasstrace/sdk 1.3.2 → 1.3.3
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/README.md +38 -0
- package/dist/{chunk-REEU6CNO.js → chunk-3HWBR7XM.js} +3 -3
- package/dist/chunk-3HWBR7XM.js.map +1 -0
- package/dist/{chunk-XS3BO7RY.js → chunk-BQKPRFLF.js} +3 -3
- package/dist/{chunk-GCFOY7T2.js → chunk-E62DL2H4.js} +3 -3
- package/dist/{chunk-UFZEISZB.js → chunk-LQKJ27LO.js} +2 -2
- package/dist/chunk-LQKJ27LO.js.map +1 -0
- package/dist/{chunk-MQHLWSIX.js → chunk-M4ZI7J3N.js} +100 -62
- package/dist/{chunk-MQHLWSIX.js.map → chunk-M4ZI7J3N.js.map} +1 -1
- package/dist/{chunk-JFR42QG5.js → chunk-QJVAKVQJ.js} +2 -2
- package/dist/{chunk-CRM3EYOL.js → chunk-WKOQJCFN.js} +2 -2
- package/dist/{chunk-DQGNUENK.js → chunk-XNKG4WNQ.js} +30 -14
- package/dist/chunk-XNKG4WNQ.js.map +1 -0
- package/dist/{chunk-3TU62WD6.js → chunk-YG3X7TUI.js} +1 -1
- package/dist/chunk-YG3X7TUI.js.map +1 -0
- package/dist/cli/init.cjs +51 -13
- package/dist/cli/init.cjs.map +1 -1
- package/dist/cli/init.js +6 -6
- package/dist/cli/mcp-add.cjs +49 -11
- package/dist/cli/mcp-add.cjs.map +1 -1
- package/dist/cli/mcp-add.js +2 -2
- package/dist/cli/uninit.cjs.map +1 -1
- package/dist/cli/uninit.js +3 -3
- package/dist/cli/validate.cjs +49 -11
- package/dist/cli/validate.cjs.map +1 -1
- package/dist/cli/validate.js +2 -2
- package/dist/edge-entry.cjs +88 -50
- package/dist/edge-entry.cjs.map +1 -1
- package/dist/edge-entry.js +2 -2
- package/dist/index.cjs +123 -68
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +6 -6
- package/dist/node-entry.cjs +123 -68
- package/dist/node-entry.cjs.map +1 -1
- package/dist/node-entry.js +8 -8
- package/dist/node-subpath.cjs +49 -11
- package/dist/node-subpath.cjs.map +1 -1
- package/dist/node-subpath.js +4 -4
- package/dist/{source-map-uploader-LACAGKIW.js → source-map-uploader-JAD3XM4F.js} +4 -4
- package/package.json +1 -1
- package/dist/chunk-3TU62WD6.js.map +0 -1
- package/dist/chunk-DQGNUENK.js.map +0 -1
- package/dist/chunk-REEU6CNO.js.map +0 -1
- package/dist/chunk-UFZEISZB.js.map +0 -1
- /package/dist/{chunk-XS3BO7RY.js.map → chunk-BQKPRFLF.js.map} +0 -0
- /package/dist/{chunk-GCFOY7T2.js.map → chunk-E62DL2H4.js.map} +0 -0
- /package/dist/{chunk-JFR42QG5.js.map → chunk-QJVAKVQJ.js.map} +0 -0
- /package/dist/{chunk-CRM3EYOL.js.map → chunk-WKOQJCFN.js.map} +0 -0
- /package/dist/{source-map-uploader-LACAGKIW.js.map → source-map-uploader-JAD3XM4F.js.map} +0 -0
package/README.md
CHANGED
|
@@ -229,6 +229,18 @@ projects that have not adopted the convention behave exactly as
|
|
|
229
229
|
before; their stored traces simply do not render mapped frames in
|
|
230
230
|
the dashboard.
|
|
231
231
|
|
|
232
|
+
When `GLASSTRACE_BUILD_HASH` is set but does not match the typical
|
|
233
|
+
git SHA shape (7-64 hexadecimal characters, covering abbreviated
|
|
234
|
+
SHA-1, full SHA-1, and full SHA-256), the SDK logs a one-shot warning
|
|
235
|
+
at startup and still ships the value — the build hash is
|
|
236
|
+
informational metadata, so a misconfiguration must never prevent the
|
|
237
|
+
SDK from starting. The warning surfaces common failure modes
|
|
238
|
+
(path-traversal-shaped values, wrong env-var name copied from
|
|
239
|
+
another tool, internal whitespace from a CI variable with a stray
|
|
240
|
+
newline) earlier than waiting to notice the dashboard rendering no
|
|
241
|
+
mapped frames. The captured value is redacted in the warning text in
|
|
242
|
+
case a secret was accidentally substituted.
|
|
243
|
+
|
|
232
244
|
The error-source attributes are stamped only by the manual
|
|
233
245
|
`captureError()` API, on the `glasstrace.error` span event. They
|
|
234
246
|
report the compiled-output `file:line` from the top user-attributable
|
|
@@ -246,6 +258,32 @@ These attributes are additive: any consumer that does not understand
|
|
|
246
258
|
them ignores them. Existing trace pipelines and dashboards continue
|
|
247
259
|
to work unchanged.
|
|
248
260
|
|
|
261
|
+
### Path information in `glasstrace.source.file`
|
|
262
|
+
|
|
263
|
+
`glasstrace.source.file` carries the path string V8 reported for the
|
|
264
|
+
top user-attributable frame, exactly as the JavaScript runtime emitted
|
|
265
|
+
it. On a developer machine this is typically an absolute filesystem
|
|
266
|
+
path including your home directory and repository root; in a built or
|
|
267
|
+
served runtime (Vercel, AWS Lambda, a container image) it is the
|
|
268
|
+
deployment-controlled directory the runtime evaluated the file from;
|
|
269
|
+
in bundler-instrumented runtimes (Next.js webpack, Turbopack) it can be
|
|
270
|
+
a pseudo-path such as `webpack-internal:///(rsc)/./app/page.tsx`. The
|
|
271
|
+
SDK preserves whichever form V8 reported.
|
|
272
|
+
|
|
273
|
+
The same path already appears in the `error.stack` event attribute on
|
|
274
|
+
captured `glasstrace.error` events whose underlying value is an `Error`
|
|
275
|
+
instance with a `stack` property (every frame's path lands in the
|
|
276
|
+
serialized stack string). The `glasstrace.source.file` attribute is a
|
|
277
|
+
strict subset of what `error.stack` exposes for those events, so
|
|
278
|
+
adopting source-map enrichment introduces no incremental path
|
|
279
|
+
disclosure beyond what existing error traces already carry.
|
|
280
|
+
|
|
281
|
+
The SDK forwards the path verbatim — without stripping the working
|
|
282
|
+
directory or bundler prefix — because ingestion's source-map resolver
|
|
283
|
+
matches against the path the compiler emitted into the source map.
|
|
284
|
+
Stripping at the writer would prevent the dashboard from rendering
|
|
285
|
+
mapped frames.
|
|
286
|
+
|
|
249
287
|
## Browser-extension discovery
|
|
250
288
|
|
|
251
289
|
`glasstrace init` writes a small static file at
|
|
@@ -2,12 +2,12 @@ import {
|
|
|
2
2
|
atomicWriteFile,
|
|
3
3
|
refreshGenericMcpConfigAtRuntime,
|
|
4
4
|
resolveEffectiveMcpCredential
|
|
5
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-LQKJ27LO.js";
|
|
6
6
|
import {
|
|
7
7
|
DEFAULT_CAPTURE_CONFIG,
|
|
8
8
|
SdkCachedConfigSchema,
|
|
9
9
|
SdkInitResponseSchema
|
|
10
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-M4ZI7J3N.js";
|
|
11
11
|
import {
|
|
12
12
|
__require
|
|
13
13
|
} from "./chunk-NSBPE2FW.js";
|
|
@@ -692,4 +692,4 @@ export {
|
|
|
692
692
|
didLastInitSucceed,
|
|
693
693
|
verifyInitReachable
|
|
694
694
|
};
|
|
695
|
-
//# sourceMappingURL=chunk-
|
|
695
|
+
//# sourceMappingURL=chunk-3HWBR7XM.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/health-collector.ts","../src/https-transport.ts","../src/init-client.ts"],"sourcesContent":["import type { SdkHealthReport } from \"@glasstrace/protocol\";\n\n// --- Module-level state (singleton pattern matching init-client.ts) ---\n\n/** Spans successfully forwarded to the delegate exporter since last collect. */\nlet tracesExported = 0;\n\n/** Spans dropped: buffer overflow evictions + spans lost on shutdown. */\nlet tracesDropped = 0;\n\n/** Failed performInit attempts since last collect. */\nlet initFailures = 0;\n\n/** Timestamp (ms) of the last successful config sync (performInit success or cached config load). */\nlet lastConfigSyncAt: number | null = null;\n\n// --- Recording functions (called by other modules) ---\n\n/**\n * Records that spans were submitted to the delegate exporter.\n * Counts submission, not confirmed delivery (DISC-1118).\n * Called by GlasstraceExporter after delegate.export() is invoked.\n */\nexport function recordSpansExported(count: number): void {\n if (!Number.isFinite(count) || count < 0 || !Number.isInteger(count)) return;\n tracesExported += count;\n}\n\n/**\n * Records that spans were dropped (buffer overflow eviction or shutdown loss).\n * Called by GlasstraceExporter on buffer eviction and unresolved-key shutdown.\n */\nexport function recordSpansDropped(count: number): void {\n if (!Number.isFinite(count) || count < 0 || !Number.isInteger(count)) return;\n tracesDropped += count;\n}\n\n/**\n * Records a failed performInit attempt.\n * Called by performInit when the init request fails for any reason.\n */\nexport function recordInitFailure(): void {\n try { initFailures += 1; } catch { /* best-effort */ }\n}\n\n/**\n * Records the timestamp of a successful config sync.\n * Called by performInit on success and by loadCachedConfig when loading a valid cache.\n */\nexport function recordConfigSync(timestamp: number): void {\n try { lastConfigSyncAt = timestamp; } catch { /* best-effort */ }\n}\n\n// --- Collection ---\n\n/**\n * Snapshots the current health metrics into an SdkHealthReport without\n * resetting counters. Counters are only reset when {@link acknowledgeHealthReport}\n * is called after the init request succeeds. This two-phase approach prevents\n * metric loss when `performInit` fails — the counters persist for the next\n * init attempt.\n *\n * On the first init call, all counters will be zero, which is correct.\n *\n * @param sdkVersion - The SDK version string to include in the report.\n * @returns The health report, or null if collection fails unexpectedly.\n */\nexport function collectHealthReport(sdkVersion: string): SdkHealthReport | null {\n try {\n const now = Date.now();\n const configAge = lastConfigSyncAt !== null ? Math.max(0, now - lastConfigSyncAt) : 0;\n\n return {\n tracesExportedSinceLastInit: tracesExported,\n tracesDropped,\n initFailures,\n configAge: Math.round(configAge),\n sdkVersion,\n };\n } catch {\n return null;\n }\n}\n\n/**\n * Subtracts the reported values from the running counters after a health\n * report has been successfully delivered to the backend. Called by\n * `performInit` on the success path. If init fails, counters persist\n * for the next attempt.\n *\n * Uses subtraction instead of zeroing to preserve any increments that\n * occurred between the snapshot (`collectHealthReport`) and delivery\n * (e.g., spans exported during the init HTTP call). Values are clamped\n * to 0 to guard against edge cases.\n *\n * Core invariant (DISC-1123): for any finite counter C and finite reported\n * value, after acknowledge:\n * C_new = max(0, C_before_ack - reported_value)\n * This guarantees:\n * 1. Reported finite, non-negative values are removed exactly once\n * (no double-counting).\n * 2. Activity between snapshot and acknowledge is preserved (not lost).\n * 3. The counter never goes negative (clamp prevents underflow).\n * Corruption vectors guarded: non-finite report fields (NaN/±Infinity)\n * preserve the counter; negative finite report fields are clamped to 0\n * before subtraction.\n *\n * `lastConfigSyncAt` is NOT affected — config age measures time since\n * the last successful sync, not the last acknowledgment.\n */\nexport function acknowledgeHealthReport(report: SdkHealthReport): void {\n const exp = Math.max(0, report.tracesExportedSinceLastInit);\n const expVal = tracesExported - exp;\n tracesExported = Number.isFinite(expVal) ? Math.max(0, expVal) : tracesExported;\n\n const drop = Math.max(0, report.tracesDropped);\n const dropVal = tracesDropped - drop;\n tracesDropped = Number.isFinite(dropVal) ? Math.max(0, dropVal) : tracesDropped;\n\n const fail = Math.max(0, report.initFailures);\n const failVal = initFailures - fail;\n initFailures = Number.isFinite(failVal) ? Math.max(0, failVal) : initFailures;\n}\n\n// --- Test support ---\n\n/**\n * Resets all health metrics to initial state. For testing only.\n */\nexport function _resetHealthForTesting(): void {\n tracesExported = 0;\n tracesDropped = 0;\n initFailures = 0;\n lastConfigSyncAt = null;\n}\n","/**\n * Minimal Node-native HTTPS transport used by the SDK init call.\n *\n * ## Why this exists\n *\n * Next.js 16 patches the global `fetch` to add caching, revalidation,\n * and request deduplication. When the SDK is bundled into a Next.js\n * process (instrumentation.ts path), outbound calls to\n * `api.glasstrace.dev` get intercepted by the patched fetch and can\n * silently hang — the fetch promise never resolves (DISC-493 Issue 3).\n *\n * A silent init hang is catastrophic: the SDK stays in \"pending key\"\n * state forever, enriched spans are buffered without ever being\n * exported, and anonymous keys are never registered server-side\n * (DISC-494).\n *\n * ## Why `node:https`\n *\n * `node:https` is a Node.js core module. It has zero bundle weight\n * (important because the SDK is tsup-inlined into every consumer's\n * bundle) and is always available on Node.js >= 20. Using it directly\n * bypasses the global `fetch` patching entirely — Next.js never sees\n * the request.\n *\n * Alternatives considered and rejected:\n *\n * - **`undici` as a runtime dep** — adds ~400KB inlined into every\n * consumer bundle.\n * - **`fetch(..., { cache: \"no-store\", next: { revalidate: 0 } })`** —\n * bandaid. Couples the SDK to Next.js's fetch-extension API and still\n * relies on Next's patched fetch behaving correctly. Explicitly\n * forbidden by the task brief for this reason.\n * - **Monkey-patch `globalThis.fetch`** — forbidden in the public SDK\n * (`glasstrace-sdk/CLAUDE.md`). Bypassing the patched fetch by\n * calling a different API is avoidance, not patching.\n *\n * ## Structure\n *\n * `httpsPostJson` is the only exported function. It:\n * - Sends a POST to a URL with a JSON body\n * - Applies a per-request timeout (default 10s)\n * - Retries transport-level failures (DNS, TCP, TLS) with backoff\n * - Never retries HTTP status errors — those are surfaced immediately\n * - Distinguishes transport failure, server error, and body-parse error\n * so callers can render actionable messages\n */\nimport {\n request as httpsRequest,\n type RequestOptions as HttpsRequestOptions,\n} from \"node:https\";\nimport {\n request as httpRequest,\n type IncomingMessage,\n} from \"node:http\";\nimport { URL } from \"node:url\";\n\n/** Error thrown when the HTTP request never completed (DNS/TCP/TLS/timeout). */\nexport class HttpsTransportError extends Error {\n readonly kind = \"transport\" as const;\n readonly cause?: unknown;\n constructor(message: string, cause?: unknown) {\n super(message);\n this.name = \"HttpsTransportError\";\n this.cause = cause;\n }\n}\n\n/** Error thrown when the server returned a non-2xx HTTP status. */\nexport class HttpsStatusError extends Error {\n readonly kind = \"status\" as const;\n readonly status: number;\n /** Raw response body text (may be truncated by caller if large). */\n readonly body: string;\n constructor(status: number, body: string) {\n super(`Server returned HTTP ${status}`);\n this.name = \"HttpsStatusError\";\n this.status = status;\n this.body = body;\n }\n}\n\n/** Error thrown when the response body was not parseable JSON. */\nexport class HttpsBodyParseError extends Error {\n readonly kind = \"parse\" as const;\n readonly status: number;\n readonly cause?: unknown;\n constructor(status: number, cause?: unknown) {\n super(`Server returned malformed response (HTTP ${status})`);\n this.name = \"HttpsBodyParseError\";\n this.status = status;\n this.cause = cause;\n }\n}\n\n/** Options controlling timeout and retry behavior. */\nexport interface HttpsPostJsonOptions {\n /** Parsed headers (including Content-Type, Authorization, etc). */\n headers: Record<string, string>;\n /** Per-attempt timeout, ms. Defaults to 10000. */\n timeoutMs?: number;\n /**\n * Total number of attempts INCLUDING the first. Defaults to 3\n * (initial + 2 retries). Only transport errors are retried.\n */\n maxAttempts?: number;\n /**\n * Backoff delays between retries, ms. The array length should be\n * `maxAttempts - 1`. Defaults to [500, 1500].\n */\n retryDelaysMs?: readonly number[];\n /**\n * Total deadline across all attempts, ms. Defaults to 20000.\n * If exceeded, no further retries are attempted and the last error\n * is surfaced. Guards against CLI hang on flaky networks.\n */\n totalDeadlineMs?: number;\n /**\n * Abort signal. When aborted, the in-flight request is terminated and\n * no further retries are attempted.\n */\n signal?: AbortSignal;\n /**\n * Scheduler injection point for tests. Defaults to `setTimeout`.\n * Using fake timers in tests requires the injected scheduler to honor\n * `vi.advanceTimersByTime()` — Node's real setTimeout is fine when no\n * fake timers are installed.\n */\n scheduler?: (fn: () => void, ms: number) => { unref?: () => void };\n /**\n * Alternate HTTPS request function. Injected by tests to simulate\n * Next.js-style fetch patching (assert call count stays zero) or to\n * mock transport behavior without opening real sockets.\n */\n requestImpl?: typeof httpsRequest;\n /**\n * Alternate HTTP request function, used when the URL is `http://`.\n * Splitting http/https lets tests use a local non-TLS mock server.\n */\n httpRequestImpl?: typeof httpRequest;\n}\n\n/** Shape of a successful response. */\nexport interface HttpsPostJsonResult {\n /** HTTP status code. Always in [200, 299] for success. */\n status: number;\n /** Parsed JSON body. May be `undefined` for 204 No Content. */\n body: unknown;\n /** Raw body text for diagnostics. */\n raw: string;\n}\n\n/** Delays so a failing test still completes before the suite's timeout. */\nconst DEFAULT_TIMEOUT_MS = 10_000;\nconst DEFAULT_RETRY_DELAYS_MS = [500, 1500] as const;\nconst DEFAULT_TOTAL_DEADLINE_MS = 20_000;\n\n/**\n * Sends a POST request with a JSON body using `node:https`. Bypasses\n * any `globalThis.fetch` patching (Next.js 16, MSW, etc).\n *\n * @throws {HttpsTransportError} DNS failure, TCP reset, TLS handshake\n * failure, request timeout, or abort.\n * @throws {HttpsStatusError} HTTP response with status >= 400.\n * @throws {HttpsBodyParseError} HTTP 2xx with non-JSON body (status not\n * equal to 204).\n */\nexport async function httpsPostJson(\n url: string,\n jsonBody: unknown,\n options: HttpsPostJsonOptions,\n): Promise<HttpsPostJsonResult> {\n const parsed = new URL(url);\n const isHttps = parsed.protocol === \"https:\";\n const isHttp = parsed.protocol === \"http:\";\n if (!isHttps && !isHttp) {\n throw new HttpsTransportError(\n `Unsupported protocol: ${parsed.protocol} (expected http: or https:)`,\n );\n }\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const maxAttempts = options.maxAttempts ?? 3;\n const retryDelaysMs = options.retryDelaysMs ?? DEFAULT_RETRY_DELAYS_MS;\n const totalDeadlineMs = options.totalDeadlineMs ?? DEFAULT_TOTAL_DEADLINE_MS;\n const scheduler = options.scheduler ?? ((fn, ms) => setTimeout(fn, ms));\n const requestImpl = isHttps\n ? (options.requestImpl ?? httpsRequest)\n : (options.httpRequestImpl ?? httpRequest);\n\n // Serialize once so retries use the exact same bytes.\n let payload: string;\n try {\n payload = JSON.stringify(jsonBody);\n } catch (err) {\n throw new HttpsTransportError(\n `Failed to serialize request body: ${err instanceof Error ? err.message : String(err)}`,\n err,\n );\n }\n const payloadBuffer = Buffer.from(payload, \"utf-8\");\n\n const startedAt = Date.now();\n let lastError: unknown;\n\n for (let attempt = 0; attempt < maxAttempts; attempt += 1) {\n if (options.signal?.aborted) {\n throw new HttpsTransportError(\"Request aborted\");\n }\n // Respect the total deadline — don't start another attempt if we'd\n // blow past it even before issuing the request.\n const elapsed = Date.now() - startedAt;\n if (elapsed >= totalDeadlineMs) {\n break;\n }\n const remainingBudget = totalDeadlineMs - elapsed;\n const attemptTimeoutMs = Math.min(timeoutMs, remainingBudget);\n\n try {\n return await sendSingleRequest(\n parsed,\n payloadBuffer,\n options.headers,\n attemptTimeoutMs,\n options.signal,\n requestImpl,\n );\n } catch (err) {\n lastError = err;\n // Never retry status/parse errors — they're server responses, not\n // transient network failures.\n if (err instanceof HttpsStatusError || err instanceof HttpsBodyParseError) {\n throw err;\n }\n const isLast = attempt === maxAttempts - 1;\n if (isLast) break;\n\n const delayMs = retryDelaysMs[attempt] ?? retryDelaysMs[retryDelaysMs.length - 1] ?? 0;\n const elapsedBeforeSleep = Date.now() - startedAt;\n const remaining = totalDeadlineMs - elapsedBeforeSleep;\n if (remaining <= 0) break;\n const actualDelayMs = Math.min(delayMs, remaining);\n await sleep(actualDelayMs, scheduler, options.signal);\n }\n }\n\n if (lastError instanceof HttpsTransportError) throw lastError;\n throw new HttpsTransportError(\n lastError instanceof Error ? lastError.message : \"Request failed\",\n lastError,\n );\n}\n\n/**\n * Fires a single HTTPS request. Resolves with the parsed result on 2xx,\n * throws the appropriate typed error otherwise. Caller handles retries.\n */\nfunction sendSingleRequest(\n url: URL,\n payload: Buffer,\n headers: Record<string, string>,\n timeoutMs: number,\n signal: AbortSignal | undefined,\n requestImpl: typeof httpsRequest,\n): Promise<HttpsPostJsonResult> {\n return new Promise<HttpsPostJsonResult>((resolve, reject) => {\n // Merge caller headers with Content-Length so Node doesn't chunk\n // the body. Explicit content-length also prevents confusion from\n // servers that reject chunked POSTs.\n const finalHeaders: Record<string, string | number> = {\n ...headers,\n \"Content-Length\": payload.byteLength,\n };\n\n const reqOptions: HttpsRequestOptions = {\n method: \"POST\",\n hostname: url.hostname,\n port: url.port === \"\" ? undefined : Number(url.port),\n path: `${url.pathname}${url.search}`,\n headers: finalHeaders,\n // Explicit timeout at the socket level. Still complemented by a\n // manual timer below because `timeout` only fires when the socket\n // is idle — it does not cover \"TLS handshake hangs forever\".\n timeout: timeoutMs,\n };\n\n let settled = false;\n // Hoisted so every settle path can clear the manual timer and drop\n // the optional abort listener. Assigned below once `req`, `timer`,\n // and `onAbort` exist.\n let cleanup = (): void => {};\n const settle = (fn: () => void): void => {\n if (settled) return;\n settled = true;\n cleanup();\n fn();\n };\n\n const req = requestImpl(reqOptions, (res: IncomingMessage) => {\n const chunks: Buffer[] = [];\n res.on(\"data\", (chunk: Buffer | string) => {\n chunks.push(typeof chunk === \"string\" ? Buffer.from(chunk, \"utf-8\") : chunk);\n });\n res.on(\"end\", () => {\n const raw = Buffer.concat(chunks).toString(\"utf-8\");\n const status = res.statusCode ?? 0;\n if (status < 200 || status >= 300) {\n settle(() => reject(new HttpsStatusError(status, raw)));\n return;\n }\n // HTTP 204: no body is expected; resolve with undefined.\n if (status === 204 || raw.length === 0) {\n settle(() => resolve({ status, body: undefined, raw }));\n return;\n }\n try {\n const parsed = JSON.parse(raw);\n settle(() => resolve({ status, body: parsed, raw }));\n } catch (err) {\n settle(() => reject(new HttpsBodyParseError(status, err)));\n }\n });\n res.on(\"error\", (err) => {\n settle(() => reject(new HttpsTransportError(`Response stream error: ${err.message}`, err)));\n });\n });\n\n // A single manual timeout guards against handshake/DNS hangs that\n // the `timeout` option in `request()` does not cover. We destroy the\n // socket on timeout so the node:https layer doesn't keep it alive.\n const timer = setTimeout(() => {\n settle(() => {\n req.destroy(new Error(\"Request timed out\"));\n reject(new HttpsTransportError(`Request timed out after ${timeoutMs}ms`));\n });\n }, timeoutMs);\n // Don't block process exit while the timer is running.\n if (typeof timer.unref === \"function\") timer.unref();\n\n // Hoisted so `cleanup` can remove it on settle. Only registered\n // on the signal below when `signal !== undefined`.\n const onAbort = (): void => {\n settle(() => {\n req.destroy(new Error(\"Aborted\"));\n reject(new HttpsTransportError(\"Request aborted\"));\n });\n };\n\n // Install cleanup now that `timer` and `onAbort` exist. Invoked by\n // every settle path (success, status-error, parse-error, transport\n // error, timeout, abort) to clear the manual timer and drop the\n // abort listener so long-lived signals don't accumulate listeners.\n cleanup = (): void => {\n clearTimeout(timer);\n if (signal !== undefined) {\n signal.removeEventListener(\"abort\", onAbort);\n }\n };\n\n req.on(\"error\", (err) => {\n settle(() => reject(new HttpsTransportError(`fetch failed: ${err.message}`, err)));\n });\n\n req.on(\"timeout\", () => {\n settle(() => {\n req.destroy(new Error(\"Request timed out\"));\n reject(new HttpsTransportError(`Request timed out after ${timeoutMs}ms`));\n });\n });\n\n if (signal !== undefined) {\n if (signal.aborted) {\n req.destroy(new Error(\"Aborted\"));\n settle(() => reject(new HttpsTransportError(\"Request aborted\")));\n return;\n }\n signal.addEventListener(\"abort\", onAbort, { once: true });\n }\n\n req.end(payload);\n });\n}\n\n/**\n * Delay helper that honors an AbortSignal. We cannot use `setTimeout`'s\n * built-in `signal` option because it is not available in older Node 20\n * patch releases (added in 20.6).\n *\n * Both settle paths (timer fires, signal aborts) clear the pending\n * timer and remove the abort listener so this helper remains leak-free\n * under heavy retry/abort usage.\n */\nfunction sleep(\n ms: number,\n scheduler: (fn: () => void, ms: number) => { unref?: () => void },\n signal: AbortSignal | undefined,\n): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n let settled = false;\n // Forward-declared so `settle` below can reference it. Assigned\n // once `timer` exists.\n let cleanup = (): void => {};\n const settle = (fn: () => void): void => {\n if (settled) return;\n settled = true;\n cleanup();\n fn();\n };\n const onAbort = (): void => {\n settle(() => reject(new HttpsTransportError(\"Request aborted\")));\n };\n const timer = scheduler(() => {\n settle(resolve);\n }, ms);\n if (typeof timer.unref === \"function\") timer.unref();\n cleanup = (): void => {\n // `scheduler` returns whatever `setTimeout` returns (NodeJS.Timeout\n // in Node, number in jsdom). Both are accepted by `clearTimeout`.\n clearTimeout(timer as unknown as NodeJS.Timeout);\n if (signal !== undefined) {\n signal.removeEventListener(\"abort\", onAbort);\n }\n };\n if (signal !== undefined) {\n if (signal.aborted) {\n onAbort();\n return;\n }\n signal.addEventListener(\"abort\", onAbort, { once: true });\n }\n });\n}\n","import {\n SdkInitResponseSchema,\n SdkCachedConfigSchema,\n DEFAULT_CAPTURE_CONFIG,\n} from \"@glasstrace/protocol\";\nimport type {\n SdkInitResponse,\n CaptureConfig,\n AnonApiKey,\n ImportGraphPayload,\n SdkHealthReport,\n SdkDiagnosticCode,\n} from \"@glasstrace/protocol\";\nimport type { ResolvedConfig } from \"./env-detection.js\";\nimport { recordInitFailure, recordConfigSync, acknowledgeHealthReport } from \"./health-collector.js\";\nimport {\n httpsPostJson,\n HttpsStatusError,\n HttpsTransportError,\n HttpsBodyParseError,\n} from \"./https-transport.js\";\nimport {\n resolveEffectiveMcpCredential,\n refreshGenericMcpConfigAtRuntime,\n} from \"./mcp-runtime.js\";\nimport { atomicWriteFile } from \"./atomic-write.js\";\n\nconst GLASSTRACE_DIR = \".glasstrace\";\nconst CONFIG_FILE = \"config\";\nconst TWENTY_FOUR_HOURS_MS = 24 * 60 * 60 * 1000;\nconst INIT_TIMEOUT_MS = 10_000;\n\n/**\n * Lazily imports `node:fs/promises` and `node:path`. Returns `null` if\n * the modules are unavailable (non-Node environments). Cached after first call.\n */\nlet fsPathAsyncCache: { fs: typeof import(\"node:fs/promises\"); path: typeof import(\"node:path\") } | null | undefined;\n\nasync function loadFsPathAsync(): Promise<{ fs: typeof import(\"node:fs/promises\"); path: typeof import(\"node:path\") } | null> {\n if (fsPathAsyncCache !== undefined) return fsPathAsyncCache;\n try {\n const [fs, path] = await Promise.all([\n import(\"node:fs/promises\"),\n import(\"node:path\"),\n ]);\n fsPathAsyncCache = { fs, path };\n return fsPathAsyncCache;\n } catch {\n fsPathAsyncCache = null;\n return null;\n }\n}\n\n/**\n * Lazily imports synchronous `node:fs` and `node:path` via `require()`.\n * Returns `null` when unavailable. Used by `loadCachedConfig` which is\n * synchronous for startup performance.\n */\nfunction loadFsSyncOrNull(): { readFileSync: typeof import(\"node:fs\").readFileSync; join: typeof import(\"node:path\").join } | null {\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports, glasstrace/no-unguarded-node-require -- guarded by the surrounding try/catch in `loadFsSyncOrNull`; throw returns `null`, callers (e.g. `loadCachedConfig`) treat it as no cached config (DISC-1555).\n const fs = require(\"node:fs\") as typeof import(\"node:fs\");\n // eslint-disable-next-line @typescript-eslint/no-require-imports, glasstrace/no-unguarded-node-require -- guarded by the same try/catch as the preceding `node:fs` require (DISC-1555).\n const path = require(\"node:path\") as typeof import(\"node:path\");\n return { readFileSync: fs.readFileSync, join: path.join };\n } catch {\n return null;\n }\n}\n\n/**\n * Test-only transport hook. When set, `sendInitRequest` calls this\n * instead of `httpsPostJson`. Enables unit tests to assert that the\n * SDK never routes through `globalThis.fetch` (Next.js patching) by\n * injecting a pure-function transport that never touches the network.\n *\n * Production code never sets this. Reset via `_resetConfigForTesting()`.\n */\ntype HttpsPostJsonFn = typeof httpsPostJson;\nlet transportOverride: HttpsPostJsonFn | null = null;\n\n/** In-memory config from the latest successful init response. */\nlet currentConfig: SdkInitResponse | null = null;\n\n/** Whether the disk cache has already been checked by getActiveConfig(). */\nlet configCacheChecked = false;\n\n/** Whether the next init call should be skipped (rate-limit backoff). */\nlet rateLimitBackoff = false;\n\n/** Whether the most recent performInit call completed the success path. */\nlet lastInitSucceeded = false;\n\n/**\n * Reads and validates a cached config file from `.glasstrace/config`.\n * Returns the parsed `SdkInitResponse` or `null` on any failure,\n * including when `node:fs` is unavailable (non-Node environments).\n */\nexport function loadCachedConfig(projectRoot?: string): SdkInitResponse | null {\n const modules = loadFsSyncOrNull();\n if (!modules) return null;\n\n const root = projectRoot ?? process.cwd();\n const configPath = modules.join(root, GLASSTRACE_DIR, CONFIG_FILE);\n\n try {\n // Use synchronous read for startup performance (this is called during init)\n const content = modules.readFileSync(configPath, \"utf-8\");\n const parsed = JSON.parse(content);\n const cached = SdkCachedConfigSchema.parse(parsed);\n\n // Warn if cache is stale\n const age = Date.now() - cached.cachedAt;\n if (age > TWENTY_FOUR_HOURS_MS) {\n console.warn(\n `[glasstrace] Cached config is ${Math.round(age / 3600000)}h old. Will refresh on next init.`,\n );\n }\n\n // Parse the response through the schema\n const result = SdkInitResponseSchema.safeParse(cached.response);\n if (result.success) {\n recordConfigSync(cached.cachedAt);\n return result.data;\n }\n\n console.warn(\"[glasstrace] Cached config failed validation. Using defaults.\");\n return null;\n } catch {\n return null;\n }\n}\n\n/**\n * Persists the init response to `.glasstrace/config` using the SDK 2.0\n * atomic-write protocol (`tmp + fsync(tmp) + rename + fsync(parent)`).\n * Silently skipped when `node:fs` is unavailable (non-Node environments).\n * On I/O failure, logs a warning.\n *\n * Atomicity: the payload is written to `.glasstrace/config.tmp`, fsynced\n * to durable storage, then renamed into place; the parent directory is\n * fsynced last so the rename survives an immediate crash. `rename` is\n * atomic on POSIX filesystems, so readers either see the previous valid\n * config or the new valid config — never a truncated or partially-written\n * file (DISC-1247 Scenario 5). If any step fails, the temp file is\n * cleaned up on a best-effort basis.\n */\nexport async function saveCachedConfig(\n response: SdkInitResponse,\n projectRoot?: string,\n): Promise<void> {\n const modules = await loadFsPathAsync();\n if (!modules) return;\n\n const root = projectRoot ?? process.cwd();\n const dirPath = modules.path.join(root, GLASSTRACE_DIR);\n const configPath = modules.path.join(dirPath, CONFIG_FILE);\n\n try {\n await modules.fs.mkdir(dirPath, { recursive: true, mode: 0o700 });\n await modules.fs.chmod(dirPath, 0o700);\n const cached = {\n response,\n cachedAt: Date.now(),\n };\n // Atomic write per SDK 2.0 §4.3: tmp + fsync(tmp) + rename +\n // fsync(parent). Sibling temp guarantees same-filesystem rename\n // (atomic per POSIX). The helper best-effort cleans up the tmp\n // file on failure (DISC-1247 Scenario 5).\n await atomicWriteFile(configPath, JSON.stringify(cached), {\n encoding: \"utf-8\",\n mode: 0o600,\n });\n // chmod the final path to defend against platforms that don't honor\n // the mode passed to writeFile/rename on first creation.\n await modules.fs.chmod(configPath, 0o600);\n } catch (err) {\n console.warn(\n `[glasstrace] Failed to cache config to ${configPath}: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n}\n\n/**\n * Sends a POST request to `/v1/sdk/init`.\n * Validates the response against `SdkInitResponseSchema`.\n *\n * Uses `node:https` via {@link httpsPostJson} rather than the global\n * `fetch` because Next.js 16 patches `fetch` for caching/revalidation\n * and can cause the init request to silently hang (DISC-493 Issue 3).\n * Retries transport-level failures (DNS, TCP, TLS) twice with 500ms +\n * 1500ms backoff, capped at a 20-second total deadline. Server responses\n * (HTTP 4xx/5xx) are never retried and are surfaced immediately.\n */\nexport async function sendInitRequest(\n config: ResolvedConfig,\n anonKey: AnonApiKey | null,\n sdkVersion: string,\n importGraph?: ImportGraphPayload,\n healthReport?: SdkHealthReport,\n diagnostics?: Array<{ code: SdkDiagnosticCode; message: string; timestamp: number }>,\n signal?: AbortSignal,\n): Promise<SdkInitResponse> {\n // Determine the API key for auth. Use || (not ??) so empty strings\n // fall through to the anonymous key — defense in depth for DISC-467.\n const effectiveKey = config.apiKey || anonKey;\n if (!effectiveKey) {\n throw new Error(\"No API key available for init request\");\n }\n\n // Build the request payload\n const payload: Record<string, unknown> = {\n sdkVersion,\n };\n\n // Straggler linking: if dev key is set AND anonKey is provided\n if (config.apiKey && anonKey) {\n payload.anonKey = anonKey;\n }\n\n if (config.environment) {\n payload.environment = config.environment;\n }\n if (importGraph) {\n payload.importGraph = importGraph;\n }\n if (healthReport) {\n payload.healthReport = healthReport;\n }\n if (diagnostics) {\n payload.diagnostics = diagnostics;\n }\n\n const url = `${config.endpoint}/v1/sdk/init`;\n\n const transport = transportOverride ?? httpsPostJson;\n let result;\n try {\n result = await transport(url, payload, {\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${effectiveKey}`,\n },\n timeoutMs: INIT_TIMEOUT_MS,\n signal,\n });\n } catch (err) {\n if (err instanceof HttpsStatusError) {\n const error = new Error(`Init request failed with status ${err.status}`);\n (error as unknown as Record<string, unknown>).status = err.status;\n throw error;\n }\n if (err instanceof HttpsBodyParseError) {\n // Preserve SyntaxError name so callers can distinguish parse failures\n // (existing test contract uses `name === \"SyntaxError\"`).\n const cause = err.cause;\n if (cause instanceof SyntaxError) throw cause;\n throw err;\n }\n if (err instanceof HttpsTransportError) {\n // Transport error — surface as-is; callers classify via message/name.\n throw err;\n }\n throw err;\n }\n\n return SdkInitResponseSchema.parse(result.body);\n}\n\n/**\n * Result returned by {@link performInit} when the backend reports an\n * account claim transition. `null` means no claim was present.\n */\nexport interface InitClaimResult {\n claimResult: NonNullable<SdkInitResponse[\"claimResult\"]>;\n}\n\n/**\n * Result of {@link writeClaimedKey}. The discriminator tells the\n * caller which on-disk source the key now lives at — and, if both\n * file writes failed, that no refresh of dependent state should be\n * attempted because there is no on-disk credential to back it.\n */\nexport interface WriteClaimedKeyResult {\n persisted: \"env-local\" | \"claimed-key\" | \"none\";\n}\n\n/**\n * Writes a claimed API key to disk using a fallback chain:\n * 1. `.env.local` — update or create with the new key\n * 2. `.glasstrace/claimed-key` — fallback if `.env.local` is not writable\n * 3. Dashboard message — if all file writes fail (key is never logged)\n *\n * The key value MUST NOT appear in any log output or stderr message.\n * In non-Node environments where `node:fs` is unavailable, falls through\n * directly to the dashboard message (step 3).\n *\n * Returns a {@link WriteClaimedKeyResult} so the caller can gate\n * downstream actions (specifically: managed MCP config refresh) on\n * the key actually having reached disk. Returning `persisted: \"none\"`\n * means the SDK could not write the key anywhere; refreshing\n * `.glasstrace/mcp.json` from the new key would put it out of sync\n * with the credential the runtime can actually read on the next\n * cold start.\n */\nexport async function writeClaimedKey(\n newApiKey: string,\n projectRoot?: string,\n): Promise<WriteClaimedKeyResult> {\n const modules = await loadFsPathAsync();\n\n if (modules) {\n const root = projectRoot ?? process.cwd();\n const envLocalPath = modules.path.join(root, \".env.local\");\n\n // Step 1: Try writing to .env.local\n let envLocalWritten = false;\n try {\n let content: string;\n try {\n content = await modules.fs.readFile(envLocalPath, \"utf-8\");\n // Replace all existing GLASSTRACE_API_KEY lines or append\n if (/^GLASSTRACE_API_KEY=.*/m.test(content)) {\n content = content.replace(\n /^GLASSTRACE_API_KEY=.*$/gm,\n `GLASSTRACE_API_KEY=${newApiKey}`,\n );\n } else {\n // Ensure trailing newline before appending\n if (content.length > 0 && !content.endsWith(\"\\n\")) {\n content += \"\\n\";\n }\n content += `GLASSTRACE_API_KEY=${newApiKey}\\n`;\n }\n } catch (readErr: unknown) {\n // Only create a new file when the file genuinely does not exist.\n // Other read errors (e.g., permission denied) should not silently\n // overwrite an existing .env.local that we cannot read.\n const code = readErr instanceof Error ? (readErr as NodeJS.ErrnoException).code : undefined;\n if (code !== \"ENOENT\") {\n throw readErr;\n }\n content = `GLASSTRACE_API_KEY=${newApiKey}\\n`;\n }\n\n await modules.fs.writeFile(envLocalPath, content, { encoding: \"utf-8\", mode: 0o600 });\n await modules.fs.chmod(envLocalPath, 0o600);\n envLocalWritten = true;\n } catch {\n // .env.local write failed — fall through to step 2\n }\n\n if (envLocalWritten) {\n try {\n process.stderr.write(\n \"[glasstrace] Account claimed! API key written to .env.local. Restart your dev server to use it.\\n\",\n );\n } catch { /* stderr is best-effort */ }\n return { persisted: \"env-local\" };\n }\n\n // Step 2: Try writing to .glasstrace/claimed-key\n let claimedKeyWritten = false;\n try {\n const dirPath = modules.path.join(root, GLASSTRACE_DIR);\n await modules.fs.mkdir(dirPath, { recursive: true, mode: 0o700 });\n await modules.fs.chmod(dirPath, 0o700);\n const claimedKeyPath = modules.path.join(dirPath, \"claimed-key\");\n await modules.fs.writeFile(claimedKeyPath, newApiKey, {\n encoding: \"utf-8\",\n mode: 0o600,\n });\n await modules.fs.chmod(claimedKeyPath, 0o600);\n claimedKeyWritten = true;\n } catch {\n // .glasstrace write also failed — fall through to step 3\n }\n\n if (claimedKeyWritten) {\n try {\n process.stderr.write(\n \"[glasstrace] Account claimed! API key written to .glasstrace/claimed-key. Copy it to your .env.local file.\\n\",\n );\n } catch { /* stderr is best-effort */ }\n return { persisted: \"claimed-key\" };\n }\n }\n\n // Step 3: All file writes failed (or node:fs unavailable) — log a message WITHOUT the key\n try {\n process.stderr.write(\n \"[glasstrace] Account claimed but could not write key to disk. Visit your dashboard settings to rotate and retrieve a new API key.\\n\",\n );\n } catch { /* stderr is best-effort */ }\n return { persisted: \"none\" };\n}\n\n/**\n * Orchestrates the full init flow: send request, update config, cache result.\n * This function MUST NOT throw.\n *\n * Returns the claim result when the backend reports an account claim\n * transition, or `null` when no claim result is available (including\n * when init is skipped due to rate-limit backoff, missing API key,\n * or request failure). Callers that do not need claim information\n * can safely ignore the return value.\n */\nexport async function performInit(\n config: ResolvedConfig,\n anonKey: AnonApiKey | null,\n sdkVersion: string,\n healthReport?: SdkHealthReport | null,\n): Promise<InitClaimResult | null> {\n lastInitSucceeded = false;\n\n // Skip if in rate-limit backoff\n if (rateLimitBackoff) {\n rateLimitBackoff = false; // Reset for next call\n return null;\n }\n\n // Guard flag: prevents recordInitFailure() from being called twice if the\n // inner catch body itself throws (e.g., an unexpected error in console.warn\n // or the instanceof checks). Without this flag, the outer safety-net catch\n // would call recordInitFailure() a second time, inflating initFailures in\n // the health report. Fix for DISC-1121.\n let failureRecorded = false;\n\n try {\n const effectiveKey = config.apiKey || anonKey;\n if (!effectiveKey) {\n console.warn(\"[glasstrace] No API key available for init request.\");\n return null;\n }\n\n // No outer AbortController timeout: `httpsPostJson` enforces a\n // per-attempt timeout (INIT_TIMEOUT_MS = 10s) AND a 20s total\n // deadline across retries. An outer 10s abort would race the first\n // attempt's own timeout and prevent the backoff-retry window from\n // ever running, defeating the transport's retry behavior.\n try {\n // Delegate to sendInitRequest to avoid duplicating fetch logic\n const result = await sendInitRequest(\n config,\n anonKey,\n sdkVersion,\n undefined,\n healthReport ?? undefined,\n undefined,\n );\n\n // Update in-memory config\n currentConfig = result;\n recordConfigSync(Date.now());\n if (healthReport) {\n acknowledgeHealthReport(healthReport);\n }\n lastInitSucceeded = true;\n\n // Persist to disk\n await saveCachedConfig(result);\n\n // Handle account claim transition — write key to disk, never to stderr\n if (result.claimResult) {\n let persisted: WriteClaimedKeyResult[\"persisted\"] = \"none\";\n try {\n const w = await writeClaimedKey(result.claimResult.newApiKey);\n persisted = w.persisted;\n } catch {\n // writeClaimedKey handles its own errors internally, but guard\n // against unexpected failures to ensure claimResult is never lost\n }\n\n // When the claimed key actually reached disk, refresh the\n // managed `.glasstrace/mcp.json` (if SDK-shaped) so MCP queries\n // start using the same credential ingestion now writes traces\n // with. Refresh failure must not lose claimResult — wrap the\n // whole thing in its own try/catch.\n if (persisted !== \"none\") {\n try {\n const resolved = await resolveEffectiveMcpCredential();\n await refreshGenericMcpConfigAtRuntime(\n process.cwd(),\n resolved.effective,\n resolved.anonKey,\n );\n } catch {\n // Refresh failure leaves the existing managed config in\n // place. The next CLI-driven `glasstrace mcp add` run will\n // detect the marker mismatch and prompt a re-run.\n }\n }\n\n return { claimResult: result.claimResult };\n }\n\n return null;\n } catch (err) {\n recordInitFailure();\n failureRecorded = true;\n\n // HttpsTransportError covers DNS/TCP/TLS/timeout from the\n // node:https transport itself — `httpsPostJson` raises timeouts\n // via this error class when its internal deadlines expire.\n if (err instanceof HttpsTransportError) {\n if (/timed out|aborted/i.test(err.message)) {\n console.warn(\"[glasstrace] ingestion_unreachable: Init request timed out.\");\n } else {\n console.warn(`[glasstrace] ingestion_unreachable: ${err.message}`);\n }\n return null;\n }\n\n // Check for HTTP status errors attached by sendInitRequest\n const status = (err as Record<string, unknown>).status;\n if (status === 401) {\n console.warn(\n \"[glasstrace] ingestion_auth_failed: Check your GLASSTRACE_API_KEY.\",\n );\n return null;\n }\n\n if (status === 429) {\n console.warn(\"[glasstrace] ingestion_rate_limited: Backing off.\");\n rateLimitBackoff = true;\n return null;\n }\n\n if (typeof status === \"number\" && status >= 400) {\n console.warn(\n `[glasstrace] Init request failed with status ${status}. Using cached config.`,\n );\n return null;\n }\n\n // Schema validation failure from sendInitRequest.parse\n // NOTE: Health report was already sent to the backend (HTTP 200).\n // Not acknowledging here means the next report will double-count\n // these values. This is intentional — over-reporting is preferable\n // to data loss when the response is unparseable (DISC-1120).\n if (err instanceof Error && err.name === \"ZodError\") {\n console.warn(\n \"[glasstrace] Init response failed validation (schema version mismatch?). Using cached config.\",\n );\n return null;\n }\n\n // Network error or other fetch failure\n console.warn(\n `[glasstrace] ingestion_unreachable: ${err instanceof Error ? err.message : String(err)}`,\n );\n return null;\n }\n } catch (err) {\n // Outermost catch — safety net for unexpected throws from the inner catch\n // body itself (e.g., an error in console.warn or instanceof checks).\n // Only record the failure if the inner catch did not already do so (DISC-1121).\n if (!failureRecorded) {\n recordInitFailure();\n }\n // Guard console.warn itself: performInit MUST NOT throw. If console.warn\n // throws here (the same failure mode this catch was added to handle), swallow\n // silently rather than violating the \"never throws\" contract.\n try {\n console.warn(\n `[glasstrace] Unexpected init error: ${err instanceof Error ? err.message : String(err)}`,\n );\n } catch { /* best-effort logging; never propagate */ }\n }\n\n return null;\n}\n\n/**\n * Returns the current capture config from the three-tier fallback chain:\n * 1. In-memory config from latest init response\n * 2. File cache (read at most once per process lifetime)\n * 3. DEFAULT_CAPTURE_CONFIG\n *\n * The disk read is cached via `configCacheChecked` to avoid repeated\n * synchronous I/O on the hot path (called by GlasstraceExporter on\n * every span export batch).\n */\nexport function getActiveConfig(): CaptureConfig {\n // Tier 1: in-memory\n if (currentConfig) {\n return currentConfig.config;\n }\n\n // Tier 2: file cache (only attempt once)\n if (!configCacheChecked) {\n configCacheChecked = true;\n const cached = loadCachedConfig();\n if (cached) {\n currentConfig = cached;\n return cached.config;\n }\n }\n\n // Tier 3: defaults\n return { ...DEFAULT_CAPTURE_CONFIG };\n}\n\n/**\n * Returns the `linkedAccountId` from the current in-memory init response,\n * or `undefined` if no init response is available or no account is linked.\n *\n * Used by the discovery endpoint to determine whether `claimed: true`\n * should be included in the response.\n */\nexport function getLinkedAccountId(): string | undefined {\n return currentConfig?.linkedAccountId;\n}\n\n/**\n * Returns the `claimResult` from the current in-memory init response,\n * or `undefined` if no init response is available or no claim occurred.\n *\n * Used by the discovery endpoint to detect in-flight claims: a valid\n * init response can include `claimResult` (claim happening NOW) without\n * `linkedAccountId` being set yet.\n */\nexport function getClaimResult(): SdkInitResponse[\"claimResult\"] {\n return currentConfig?.claimResult;\n}\n\n/**\n * Resets the in-memory config store. For testing only.\n */\nexport function _resetConfigForTesting(): void {\n currentConfig = null;\n configCacheChecked = false;\n rateLimitBackoff = false;\n lastInitSucceeded = false;\n transportOverride = null;\n}\n\n/**\n * Installs a test-only transport that replaces the `node:https` path\n * used by `sendInitRequest` and `performInit`. Tests use this to avoid\n * opening real sockets and to assert the SDK never routes through\n * `globalThis.fetch`. Pass `null` to restore the default transport.\n *\n * @internal Test-only. Never called from production code paths.\n */\nexport function _setTransportForTesting(fn: HttpsPostJsonFn | null): void {\n transportOverride = fn;\n}\n\n/**\n * Sets the in-memory config directly. Used by performInit and the orchestrator.\n */\nexport function _setCurrentConfig(config: SdkInitResponse): void {\n currentConfig = config;\n}\n\n/**\n * Returns whether rate-limit backoff is active. For testing only.\n */\nexport function _isRateLimitBackoff(): boolean {\n return rateLimitBackoff;\n}\n\n/**\n * Reads and clears the rate-limit backoff flag.\n * Called by the heartbeat after performInit returns null to detect 429 responses.\n * Returns true if a 429 occurred, false otherwise.\n */\nexport function consumeRateLimitFlag(): boolean {\n if (rateLimitBackoff) {\n rateLimitBackoff = false;\n return true;\n }\n return false;\n}\n\n/**\n * Returns true if the most recent performInit call completed the success path\n * (recordConfigSync + acknowledgeHealthReport were called).\n * Used by backgroundInit to decide whether to start the heartbeat.\n */\nexport function didLastInitSucceed(): boolean {\n return lastInitSucceeded;\n}\n\n/**\n * Result of {@link verifyInitReachable}.\n *\n * - `ok: true` — server acknowledged the init call with a valid, schema-\n * compliant payload. The anon key (if any) is registered server-side.\n * - `ok: false` with `reason: \"transport\"` — DNS/TCP/TLS/timeout failure.\n * No response reached the server (or couldn't be parsed off the wire).\n * `detail` is the raw cause (e.g. \"ECONNREFUSED\") with any leading\n * `fetch failed: ` prefix stripped; callers that render to the user\n * should add the prefix themselves to avoid doubling it.\n * - `ok: false` with `reason: \"rejected\"` — HTTP 4xx/5xx status. The\n * server received the call but declined it. `status` is set.\n * - `ok: false` with `reason: \"malformed\"` — HTTP 2xx but the body was\n * not valid JSON or did not match the protocol schema.\n */\nexport type VerifyInitResult =\n | { ok: true; response: SdkInitResponse }\n | { ok: false; reason: \"transport\"; detail: string }\n | { ok: false; reason: \"rejected\"; status: number; detail: string }\n | { ok: false; reason: \"malformed\"; detail: string };\n\n/**\n * Synchronously verifies that `/v1/sdk/init` is reachable and that the\n * provided anon key (if any) is registered server-side. Unlike\n * {@link performInit}, this function does NOT swallow errors — it\n * classifies them into the three user-actionable categories and\n * returns them.\n *\n * Used by the CLI `init` command to fail loudly when the init request\n * fails (DISC-493 Issue 3, DISC-494), rather than relying on the\n * runtime fire-and-forget call which can silently fail inside a\n * Next.js 16 process.\n *\n * The anon key is NEVER logged by this function. Error `detail`\n * strings are sanitized to the failure class only — the key does not\n * appear in transport, rejection, or malformed messages.\n */\nexport async function verifyInitReachable(\n config: ResolvedConfig,\n anonKey: AnonApiKey | null,\n sdkVersion: string,\n): Promise<VerifyInitResult> {\n try {\n const response = await sendInitRequest(config, anonKey, sdkVersion);\n return { ok: true, response };\n } catch (err) {\n // HTTP status error — server rejected the key.\n const status = (err as Record<string, unknown>).status;\n if (typeof status === \"number\") {\n return {\n ok: false,\n reason: \"rejected\",\n status,\n detail: `server returned HTTP ${status}`,\n };\n }\n\n // Schema validation failure (ZodError) or JSON parse error\n // (SyntaxError). Both mean the server responded but the body is\n // not a shape we can use.\n if (err instanceof Error && (err.name === \"ZodError\" || err.name === \"SyntaxError\")) {\n return {\n ok: false,\n reason: \"malformed\",\n detail: \"server returned malformed response\",\n };\n }\n\n // Everything else (transport errors, timeouts, abort, unknown) is\n // classified as transport. `detail` is the raw cause without a\n // `fetch failed:` prefix so the CLI (the only caller that renders\n // this) can format it as `fetch failed: <detail>` without risking\n // the double-prefix that would occur when the underlying error\n // already starts with `fetch failed:` (e.g., `HttpsTransportError`\n // from `sendSingleRequest`).\n const rawMessage = err instanceof Error ? err.message : String(err);\n const detail = rawMessage.startsWith(\"fetch failed: \")\n ? rawMessage.slice(\"fetch failed: \".length)\n : rawMessage;\n return { ok: false, reason: \"transport\", detail };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAKA,IAAI,iBAAiB;AAGrB,IAAI,gBAAgB;AAGpB,IAAI,eAAe;AAGnB,IAAI,mBAAkC;AAS/B,SAAS,oBAAoB,OAAqB;AACvD,MAAI,CAAC,OAAO,SAAS,KAAK,KAAK,QAAQ,KAAK,CAAC,OAAO,UAAU,KAAK,EAAG;A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;AAAA,QACR,QAAQ;AAAA,MACV;AAAA,IACF;AASA,UAAM,aAAa,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAClE,UAAM,SAAS,WAAW,WAAW,gBAAgB,IACjD,WAAW,MAAM,iBAAiB,MAAM,IACxC;AACJ,WAAO,EAAE,IAAI,OAAO,QAAQ,aAAa,OAAO;AAAA,EAClD;AACF;","names":[]}
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import {
|
|
2
2
|
sdkLog
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-YG3X7TUI.js";
|
|
4
4
|
import {
|
|
5
5
|
PresignedUploadResponseSchema,
|
|
6
6
|
SourceMapManifestResponseSchema,
|
|
7
7
|
SourceMapUploadResponseSchema
|
|
8
|
-
} from "./chunk-
|
|
8
|
+
} from "./chunk-M4ZI7J3N.js";
|
|
9
9
|
|
|
10
10
|
// src/source-map-uploader.ts
|
|
11
11
|
import * as fs from "node:fs/promises";
|
|
@@ -331,4 +331,4 @@ export {
|
|
|
331
331
|
uploadSourceMapsPresigned,
|
|
332
332
|
uploadSourceMapsAuto
|
|
333
333
|
};
|
|
334
|
-
//# sourceMappingURL=chunk-
|
|
334
|
+
//# sourceMappingURL=chunk-BQKPRFLF.js.map
|
|
@@ -5,10 +5,10 @@ import {
|
|
|
5
5
|
isDevApiKey,
|
|
6
6
|
readEnvLocalApiKey,
|
|
7
7
|
writeAndFsyncTempSync
|
|
8
|
-
} from "./chunk-
|
|
8
|
+
} from "./chunk-LQKJ27LO.js";
|
|
9
9
|
import {
|
|
10
10
|
AnonApiKeySchema
|
|
11
|
-
} from "./chunk-
|
|
11
|
+
} from "./chunk-M4ZI7J3N.js";
|
|
12
12
|
import {
|
|
13
13
|
NEXT_CONFIG_NAMES
|
|
14
14
|
} from "./chunk-NB7GJE4S.js";
|
|
@@ -914,4 +914,4 @@ export {
|
|
|
914
914
|
writeShutdownMarker,
|
|
915
915
|
runUninit
|
|
916
916
|
};
|
|
917
|
-
//# sourceMappingURL=chunk-
|
|
917
|
+
//# sourceMappingURL=chunk-E62DL2H4.js.map
|
|
@@ -2,7 +2,7 @@ import {
|
|
|
2
2
|
AnonApiKeySchema,
|
|
3
3
|
DevApiKeySchema,
|
|
4
4
|
createAnonApiKey
|
|
5
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-M4ZI7J3N.js";
|
|
6
6
|
import {
|
|
7
7
|
__require
|
|
8
8
|
} from "./chunk-NSBPE2FW.js";
|
|
@@ -614,4 +614,4 @@ export {
|
|
|
614
614
|
writeMcpMarker,
|
|
615
615
|
refreshGenericMcpConfigAtRuntime
|
|
616
616
|
};
|
|
617
|
-
//# sourceMappingURL=chunk-
|
|
617
|
+
//# sourceMappingURL=chunk-LQKJ27LO.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/anon-key.ts","../src/atomic-write.ts","../src/mcp-runtime.ts"],"sourcesContent":["import { AnonApiKeySchema, DevApiKeySchema, createAnonApiKey } from \"@glasstrace/protocol\";\nimport type { AnonApiKey, DevApiKey } from \"@glasstrace/protocol\";\n\nconst GLASSTRACE_DIR = \".glasstrace\";\nconst ANON_KEY_FILE = \"anon_key\";\nconst CLAIMED_KEY_FILE = \"claimed-key\";\n\n/**\n * Lazily imports `node:fs/promises` and `node:path`. Returns `null` if\n * the modules are unavailable (non-Node environments). The result is\n * cached after first resolution.\n */\nlet fsPathCache: { fs: typeof import(\"node:fs/promises\"); path: typeof import(\"node:path\") } | null | undefined;\n\nasync function loadFsPath(): Promise<{ fs: typeof import(\"node:fs/promises\"); path: typeof import(\"node:path\") } | null> {\n if (fsPathCache !== undefined) return fsPathCache;\n try {\n const [fs, path] = await Promise.all([\n import(\"node:fs/promises\"),\n import(\"node:path\"),\n ]);\n fsPathCache = { fs, path };\n return fsPathCache;\n } catch {\n fsPathCache = null;\n return null;\n }\n}\n\n/**\n * In-memory cache for ephemeral keys when filesystem persistence fails.\n * Keyed by resolved project root to support multiple roots in tests.\n */\nconst ephemeralKeyCache = new Map<string, AnonApiKey>();\n\n/**\n * Reads an existing anonymous key from the filesystem.\n * Returns the key if valid, or null if:\n * - The file does not exist\n * - The file content is invalid\n * - An I/O error occurs\n * - `node:fs` is unavailable (non-Node environment)\n */\nexport async function readAnonKey(projectRoot?: string): Promise<AnonApiKey | null> {\n const root = projectRoot ?? process.cwd();\n\n const modules = await loadFsPath();\n if (modules) {\n const keyPath = modules.path.join(root, GLASSTRACE_DIR, ANON_KEY_FILE);\n try {\n const content = await modules.fs.readFile(keyPath, \"utf-8\");\n const result = AnonApiKeySchema.safeParse(content);\n if (result.success) {\n return result.data;\n }\n } catch {\n // Fall through to check ephemeral cache\n }\n }\n\n // Check in-memory cache (used when filesystem persistence failed\n // or when node:fs is unavailable)\n const cached = ephemeralKeyCache.get(root);\n if (cached !== undefined) {\n return cached;\n }\n\n return null;\n}\n\n/**\n * Reads a claimed developer API key persisted at\n * `.glasstrace/claimed-key`. The file is the runtime fallback used by\n * {@link import(\"./init-client.js\").writeClaimedKey} when `.env.local`\n * is not writable.\n *\n * Returns the key when the file exists and its contents pass\n * `DevApiKeySchema` validation. Returns `null` when:\n * - The file does not exist.\n * - The file content fails strict schema validation (a malformed or\n * stale value cannot be distinguished from a valid one without a\n * server roundtrip — callers should treat this as \"no key\").\n * - An I/O error occurs.\n * - `node:fs` is unavailable (non-Node environment).\n */\nexport async function readClaimedKey(projectRoot?: string): Promise<DevApiKey | null> {\n const root = projectRoot ?? process.cwd();\n\n const modules = await loadFsPath();\n if (!modules) return null;\n\n const keyPath = modules.path.join(root, GLASSTRACE_DIR, CLAIMED_KEY_FILE);\n try {\n const content = await modules.fs.readFile(keyPath, \"utf-8\");\n const trimmed = content.trim();\n const parsed = DevApiKeySchema.safeParse(trimmed);\n if (parsed.success) {\n return parsed.data;\n }\n } catch {\n // Fall through — file missing, unreadable, or invalid; treat as absent.\n }\n\n return null;\n}\n\n/**\n * Gets an existing anonymous key from the filesystem, or creates a new one.\n *\n * - If file exists and contains a valid key, returns it\n * - If file does not exist or content is invalid, generates a new key via createAnonApiKey()\n * - Writes the new key to `.glasstrace/anon_key`, creating the directory if needed\n * - On file write failure: logs a warning, caches an ephemeral in-memory key so\n * repeated calls in the same process return the same key\n * - In non-Node environments: returns an ephemeral in-memory key\n */\nexport async function getOrCreateAnonKey(projectRoot?: string): Promise<AnonApiKey> {\n const root = projectRoot ?? process.cwd();\n\n // Try reading existing key from filesystem\n const existingKey = await readAnonKey(root);\n if (existingKey !== null) {\n return existingKey;\n }\n\n // Check in-memory cache (used when filesystem is unavailable)\n const cached = ephemeralKeyCache.get(root);\n if (cached !== undefined) {\n return cached;\n }\n\n // Generate a new key\n const newKey = createAnonApiKey();\n\n // Attempt filesystem persistence (only in Node.js environments)\n const modules = await loadFsPath();\n if (!modules) {\n // No filesystem access — cache in memory\n ephemeralKeyCache.set(root, newKey);\n return newKey;\n }\n\n const dirPath = modules.path.join(root, GLASSTRACE_DIR);\n const keyPath = modules.path.join(dirPath, ANON_KEY_FILE);\n\n // Persist to filesystem using atomic create-or-fail (O_CREAT | O_EXCL)\n // to prevent TOCTOU races where concurrent cold starts both generate keys.\n try {\n await modules.fs.mkdir(dirPath, { recursive: true, mode: 0o700 });\n await modules.fs.writeFile(keyPath, newKey, { flag: \"wx\", mode: 0o600 });\n return newKey;\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code === \"EEXIST\") {\n // Another process won the race. Retry reading their key with\n // short delays — the winner's writeFile is atomic for small\n // payloads but the filesystem may not have flushed yet.\n for (let attempt = 0; attempt < 3; attempt++) {\n const winnerKey = await readAnonKey(root);\n if (winnerKey !== null) {\n return winnerKey;\n }\n // Short delay before next retry (50ms), skip after final attempt\n if (attempt < 2) {\n await new Promise((resolve) => setTimeout(resolve, 50));\n }\n }\n // All retries exhausted — overwrite as last resort.\n // Use explicit chmod after overwrite since writeFile mode only\n // applies on creation on some platforms.\n try {\n await modules.fs.writeFile(keyPath, newKey, { mode: 0o600 });\n await modules.fs.chmod(keyPath, 0o600);\n return newKey;\n } catch {\n // Overwrite failed — fall through to ephemeral cache\n }\n }\n\n // Non-EEXIST error (EACCES, ENOTDIR, etc.) — cache in memory so\n // repeated calls get the same ephemeral key within this process.\n ephemeralKeyCache.set(root, newKey);\n console.warn(\n `[glasstrace] Failed to persist anonymous key to ${keyPath}: ${err instanceof Error ? err.message : String(err)}. Using ephemeral key.`,\n );\n return newKey;\n }\n}\n","/**\n * Atomic file-write helper.\n *\n * Implements the durability half of the atomic-write protocol\n * (`docs/component-designs/sdk-architecture.md` §4.3 — Atomic file\n * writes; durability protocol steps 6–9):\n *\n * 1. Write the payload to a sibling temp file in the **same**\n * directory as the final target. The shared directory guarantees\n * `rename(2)` stays on the same filesystem and therefore atomic\n * per POSIX semantics.\n * 2. **fsync the temp file.** Forces data and metadata to durable\n * storage before the rename is observable.\n * 3. **rename atomically into place.** Readers see either the old\n * file contents or the new ones, never a partial write.\n * 4. **fsync the parent directory.** On POSIX, `rename(2)` durability\n * is not guaranteed until the containing directory's own metadata\n * is synced. Without this step, a power loss between rename and\n * parent-dir sync can leave the rename invisible after reboot\n * (the kernel acknowledges the syscall but the metadata never\n * reached durable storage).\n *\n * Closes the durability gap that allowed DISC-494 (anon-key unlinked\n * silently on re-init under crash interleavings).\n *\n * Out-of-scope by design:\n * - The `lstat → tmp → rename → re-lstat` TOCTOU re-check (spec\n * §4.3 steps 1–2 and 7's re-verification) is next-major scope per\n * `sdk-architecture.md` §4.3 — TOCTOU protection.\n * - The `GLASSTRACE_TEST_CRASH_AFTER` crash-injection harness is\n * next-major scope per `sdk-architecture.md` §4.3 — Crash-injection\n * harness.\n * - Structured error-with-step-number reporting is next-major scope\n * per `sdk-architecture.md` §4.3 — durability protocol step 9.\n *\n * Cross-platform behavior:\n * - On POSIX (Linux, macOS), the parent-directory fsync uses an\n * `open(O_RDONLY) → fsync → close` sequence. This is the canonical\n * way to flush directory metadata.\n * - On Windows, opening a directory for read returns `EISDIR` (and\n * `fsync` on the resulting handle would fail with `EINVAL` even\n * if the open succeeded). NTFS's rename semantics also do not\n * require an explicit directory fsync to commit the rename\n * metadata. The helper therefore swallows `EISDIR`, `EINVAL`,\n * `EPERM`, and `ENOTSUP` from the parent-dir fsync step. Any\n * other error from the open/fsync/close sequence still propagates\n * so genuine I/O failures are not silently ignored.\n *\n * Concurrency:\n * - Two processes writing the same target concurrently follow\n * last-rename-wins semantics. The helper does not lock; the\n * caller is responsible for any external mutual-exclusion. This\n * matches the existing 0.19.x behavior of every migrated call\n * site — the helper does not change concurrency guarantees, only\n * durability.\n *\n * Performance:\n * - `fsync` is intrinsically expensive on rotational media (one\n * full disk-cache flush). The sync variant is exposed for the\n * `runtime-state.ts` writer, which runs in a signal handler with\n * a strict time budget; existing callers were already issuing a\n * blocking `writeFileSync + renameSync`, so the additional cost\n * is the two `fsync` calls. On modern SSDs this remains in the\n * low-millisecond range.\n *\n * Module-load safety: `node:fs` and `node:fs/promises` are loaded\n * lazily so the module can be imported in non-Node environments\n * (Edge Runtime, browser bundles) without crashing at import time.\n * Calling any helper export in such an environment throws a clear\n * error; callers that may run on the edge must therefore probe\n * their own Node-availability before reaching this module (see\n * `init-client.ts`'s `loadFsPathAsync`).\n *\n * @internal Not re-exported from `index.ts`/`node-entry.ts`/\n * `edge-entry.ts`. Importable only from sibling SDK modules.\n */\n\nimport type { FileHandle } from \"node:fs/promises\";\n\n/**\n * Resolves the parent directory of a path without importing `node:path`,\n * so this module remains importable in non-Node environments where\n * `node:path` is unavailable. Handles both POSIX (`/`) and Windows\n * (`\\\\`) separators because Windows paths can use either form.\n *\n * Behavior matches `path.dirname` for the inputs this module receives\n * (always absolute paths produced by SDK callers): finds the last\n * separator and returns the prefix; returns `\".\"` if no separator is\n * present (a relative leaf name); preserves the root for `/foo` →\n * `/`. Edge cases like trailing-separator inputs are not exercised by\n * SDK callers so are not modeled here.\n */\nfunction parentDir(filePath: string): string {\n const lastSlash = filePath.lastIndexOf(\"/\");\n const lastBackslash = filePath.lastIndexOf(\"\\\\\");\n const lastSep = Math.max(lastSlash, lastBackslash);\n if (lastSep < 0) return \".\";\n if (lastSep === 0) return filePath.slice(0, 1); // root: \"/x\" → \"/\"\n return filePath.slice(0, lastSep);\n}\n\n/**\n * Options accepted by both `atomicWriteFile` and `atomicWriteFileSync`.\n *\n * The shape mirrors the relevant subset of `fs.writeFile`'s options\n * object. `mode` defaults to `0o600` (state files); callers writing\n * static or discoverable files (e.g., `.well-known/glasstrace.json`)\n * may pass `0o644`. `encoding` defaults to `\"utf-8\"` when the payload\n * is a string and is ignored when the payload is a `Uint8Array`.\n */\nexport interface AtomicWriteOptions {\n /**\n * POSIX file mode applied to the temp file before the rename.\n * Defaults to `0o600`. The mode applies to the temp file and is\n * carried through the rename; callers that need a different\n * post-rename mode should call `chmod` themselves after this\n * helper resolves.\n *\n * The helper re-applies this mode unconditionally via `chmod`/`chmodSync`\n * after writing, so a pre-existing temp file (e.g., residue from a\n * crashed prior run) cannot carry stale permissive bits into the\n * caller's renamed target. The fsync handle is opened read-only so\n * callers passing a read-only mode (e.g. `0o444`) are still supported.\n */\n mode?: number;\n /**\n * Encoding for string payloads. Defaults to `\"utf-8\"`. Ignored when\n * the payload is a `Uint8Array`.\n */\n encoding?: BufferEncoding;\n}\n\n/** Errno codes that the parent-dir fsync step is permitted to swallow. */\nconst PARENT_FSYNC_SWALLOWED_CODES: ReadonlySet<string> = new Set([\n \"EISDIR\",\n \"EINVAL\",\n \"EPERM\",\n \"ENOTSUP\",\n]);\n\n/**\n * Reads the `code` property off an `unknown` thrown value if present.\n * Helper avoids `as` casts on `err` and works with both plain objects\n * and `NodeJS.ErrnoException` instances.\n */\nfunction errnoCodeOf(err: unknown): string | undefined {\n if (err === null || typeof err !== \"object\") return undefined;\n const code = (err as { code?: unknown }).code;\n return typeof code === \"string\" ? code : undefined;\n}\n\n/**\n * Builds the path of the sibling temp file. The temp lives in the\n * same directory as the target so the eventual `rename(2)` stays on\n * the same filesystem.\n *\n * Callers may pre-compute their own temp paths (e.g., `<path>.tmp-\n * <pid>` for the discovery-file write to keep multi-process collisions\n * disambiguated). When they do, they call the helper's `*WithTmp`\n * variants. The default temp suffix is `.tmp` for parity with the\n * existing 0.19.x call sites.\n */\nfunction defaultTmpPath(targetPath: string): string {\n return `${targetPath}.tmp`;\n}\n\n// ---------------------------------------------------------------------------\n// Lazy module loaders\n// ---------------------------------------------------------------------------\n\nlet fsPromisesCache: typeof import(\"node:fs/promises\") | null | undefined;\nlet fsSyncCache: typeof import(\"node:fs\") | null | undefined;\n\nasync function loadFsPromises(): Promise<typeof import(\"node:fs/promises\")> {\n if (fsPromisesCache !== undefined) {\n if (fsPromisesCache === null) {\n throw new Error(\n \"node:fs/promises is unavailable in this environment; atomicWriteFile cannot be used here.\",\n );\n }\n return fsPromisesCache;\n }\n try {\n fsPromisesCache = await import(\"node:fs/promises\");\n return fsPromisesCache;\n } catch {\n fsPromisesCache = null;\n throw new Error(\n \"node:fs/promises is unavailable in this environment; atomicWriteFile cannot be used here.\",\n );\n }\n}\n\nfunction loadFsSync(): typeof import(\"node:fs\") {\n if (fsSyncCache !== undefined) {\n if (fsSyncCache === null) {\n throw new Error(\n \"node:fs is unavailable in this environment; atomicWriteFileSync cannot be used here.\",\n );\n }\n return fsSyncCache;\n }\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports, glasstrace/no-unguarded-node-require -- guarded by the surrounding try/catch which caches `null` and surfaces a clean Error on subsequent calls; consumers gate with `isSyncFsAvailable()` (DISC-1555).\n fsSyncCache = require(\"node:fs\") as typeof import(\"node:fs\");\n return fsSyncCache;\n } catch {\n fsSyncCache = null;\n throw new Error(\n \"node:fs is unavailable in this environment; atomicWriteFileSync cannot be used here.\",\n );\n }\n}\n\n// ---------------------------------------------------------------------------\n// Async variant\n// ---------------------------------------------------------------------------\n\n/**\n * Atomically writes `payload` to `targetPath` using\n * `tmp + fsync(tmp) + rename + fsync(parent)` semantics.\n *\n * On any error from the write/fsync/rename steps, the helper makes a\n * best-effort attempt to remove the temp file and rethrows the\n * original error. The parent-dir fsync step swallows\n * `EISDIR`/`EINVAL`/`EPERM`/`ENOTSUP` to support platforms where\n * directory fsync is not supported (notably Windows on NTFS).\n *\n * @param targetPath Absolute path to the final destination.\n * @param payload `string` or `Uint8Array` payload.\n * @param options See {@link AtomicWriteOptions}.\n */\nexport async function atomicWriteFile(\n targetPath: string,\n payload: string | Uint8Array,\n options: AtomicWriteOptions = {},\n): Promise<void> {\n return atomicWriteFileWithTmp(targetPath, defaultTmpPath(targetPath), payload, options);\n}\n\n/**\n * Async variant accepting an explicit `tmpPath`. The temp path MUST\n * live in the same directory as `targetPath` to preserve rename\n * atomicity. Used by `cli/discovery-file.ts` to disambiguate\n * concurrent writers via a `.tmp-<pid>` suffix.\n */\nexport async function atomicWriteFileWithTmp(\n targetPath: string,\n tmpPath: string,\n payload: string | Uint8Array,\n options: AtomicWriteOptions = {},\n): Promise<void> {\n const mode = options.mode ?? 0o600;\n const encoding = options.encoding ?? \"utf-8\";\n const fsp = await loadFsPromises();\n\n let handle: FileHandle | null = null;\n try {\n // Step 1: write payload to the temp file.\n if (typeof payload === \"string\") {\n await fsp.writeFile(tmpPath, payload, { encoding, mode });\n } else {\n await fsp.writeFile(tmpPath, payload, { mode });\n }\n\n // Step 1a: re-apply the requested mode unconditionally. `writeFile`\n // only honors `mode` when it CREATES the file; if `tmpPath` is a\n // pre-existing residue from a prior crash (or a hostile actor) the\n // existing permissions are preserved, which would silently rename a\n // world-readable temp into place. Path-based `chmod` lets the fsync\n // handle below remain read-only, so callers that pass a read-only\n // mode (e.g. 0o444) are still supported.\n await fsp.chmod(tmpPath, mode);\n\n // Step 2: fsync the temp file. Open then fsync via the\n // `FileHandle.sync()` method — `writeFile` closes its internal\n // handle immediately, so we re-open here. Read-only is sufficient\n // for `fsync` and works for callers that supply a read-only `mode`.\n handle = await fsp.open(tmpPath, \"r\");\n await handle.sync();\n await handle.close();\n handle = null;\n\n // Step 3: rename into place. POSIX-atomic on same-filesystem.\n await fsp.rename(tmpPath, targetPath);\n } catch (err) {\n if (handle !== null) {\n try {\n await handle.close();\n } catch {\n // Best-effort: the original error takes precedence.\n }\n }\n await removeTmpResidueAsync(fsp, tmpPath);\n throw err;\n }\n\n // Step 4: fsync the parent directory. Failures on platforms that\n // do not support directory fsync are swallowed; genuine I/O errors\n // still propagate.\n await fsyncParentDirAsync(targetPath, fsp);\n}\n\n/**\n * Best-effort removal of the temp file after a failed atomic-write\n * step. Tries `unlink` first (the common case where the temp is a\n * regular file). If `unlink` fails with `EISDIR`/`EPERM` — meaning the\n * temp path resolves to a directory left behind by a prior crash or\n * misconfiguration — falls back to a non-recursive `rmdir`. Any error\n * from either operation is swallowed so the caller can rethrow the\n * original I/O failure.\n */\nasync function removeTmpResidueAsync(\n fsp: typeof import(\"node:fs/promises\"),\n tmpPath: string,\n): Promise<void> {\n try {\n await fsp.unlink(tmpPath);\n return;\n } catch (err) {\n const code = errnoCodeOf(err);\n if (code !== \"EISDIR\" && code !== \"EPERM\") {\n // Tmp may not exist (ENOENT), or unlink may have failed for an\n // unrelated reason. Either way, nothing more to do — the\n // original error takes precedence in the caller.\n return;\n }\n }\n try {\n await fsp.rmdir(tmpPath);\n } catch {\n // Directory may be non-empty or otherwise unremovable; the original\n // I/O failure remains the actionable error for the caller.\n }\n}\n\nasync function fsyncParentDirAsync(\n targetPath: string,\n fsp: typeof import(\"node:fs/promises\"),\n): Promise<void> {\n const parent = parentDir(targetPath);\n let handle: FileHandle | null = null;\n try {\n handle = await fsp.open(parent, \"r\");\n await handle.sync();\n } catch (err) {\n const code = errnoCodeOf(err);\n if (code !== undefined && PARENT_FSYNC_SWALLOWED_CODES.has(code)) {\n // Platform does not support directory fsync (Windows / NTFS).\n // The rename has already returned successfully; durability\n // semantics on those filesystems do not require an explicit\n // directory sync.\n return;\n }\n throw err;\n } finally {\n if (handle !== null) {\n try {\n await handle.close();\n } catch {\n // Close errors after a successful fsync are not actionable.\n }\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Sync variant\n// ---------------------------------------------------------------------------\n\n/**\n * Synchronous counterpart to {@link atomicWriteFile}. Exists for\n * `runtime-state.ts`, which writes from a signal handler that\n * cannot await. Otherwise prefer the async variant.\n */\nexport function atomicWriteFileSync(\n targetPath: string,\n payload: string | Uint8Array,\n options: AtomicWriteOptions = {},\n): void {\n atomicWriteFileSyncWithTmp(targetPath, defaultTmpPath(targetPath), payload, options);\n}\n\n/**\n * Sync variant accepting an explicit `tmpPath`. Mirrors\n * {@link atomicWriteFileWithTmp}.\n */\nexport function atomicWriteFileSyncWithTmp(\n targetPath: string,\n tmpPath: string,\n payload: string | Uint8Array,\n options: AtomicWriteOptions = {},\n): void {\n const mode = options.mode ?? 0o600;\n const encoding = options.encoding ?? \"utf-8\";\n const fs = loadFsSync();\n\n let fd: number | null = null;\n try {\n if (typeof payload === \"string\") {\n fs.writeFileSync(tmpPath, payload, { encoding, mode });\n } else {\n fs.writeFileSync(tmpPath, payload, { mode });\n }\n\n // Re-apply the requested mode unconditionally — see the matching\n // comment in `atomicWriteFileWithTmp` for the credential-leak\n // rationale when `tmpPath` is pre-existing residue.\n fs.chmodSync(tmpPath, mode);\n\n // Read-only is sufficient for `fsync` and works for callers that\n // supply a read-only `mode`.\n fd = fs.openSync(tmpPath, \"r\");\n fs.fsyncSync(fd);\n fs.closeSync(fd);\n fd = null;\n\n fs.renameSync(tmpPath, targetPath);\n } catch (err) {\n if (fd !== null) {\n try {\n fs.closeSync(fd);\n } catch {\n // Best-effort.\n }\n }\n removeTmpResidueSync(fs, tmpPath);\n throw err;\n }\n\n fsyncParentDirSyncWithFs(targetPath, fs);\n}\n\n/**\n * Synchronous counterpart to {@link removeTmpResidueAsync}. See the\n * async variant's JSDoc for the `EISDIR`/`EPERM` rationale.\n */\nfunction removeTmpResidueSync(\n fs: typeof import(\"node:fs\"),\n tmpPath: string,\n): void {\n try {\n fs.unlinkSync(tmpPath);\n return;\n } catch (err) {\n const code = errnoCodeOf(err);\n if (code !== \"EISDIR\" && code !== \"EPERM\") {\n return;\n }\n }\n try {\n fs.rmdirSync(tmpPath);\n } catch {\n // Directory may be non-empty; original error takes precedence.\n }\n}\n\n/**\n * Synchronously fsyncs the parent directory of `targetPath`. Errors\n * matching {@link PARENT_FSYNC_SWALLOWED_CODES} (Windows / NTFS does\n * not support directory fsync) are silently ignored; other errors\n * propagate. Exposed for callers like `cli/discovery-file.ts` that\n * need to compose the steps manually around a backup-rollback flow.\n *\n * @internal Sibling-module use only.\n */\nexport function fsyncParentDirSync(targetPath: string): void {\n fsyncParentDirSyncWithFs(targetPath, loadFsSync());\n}\n\nfunction fsyncParentDirSyncWithFs(\n targetPath: string,\n fs: typeof import(\"node:fs\"),\n): void {\n const parent = parentDir(targetPath);\n let fd: number | null = null;\n try {\n fd = fs.openSync(parent, \"r\");\n fs.fsyncSync(fd);\n } catch (err) {\n const code = errnoCodeOf(err);\n if (code !== undefined && PARENT_FSYNC_SWALLOWED_CODES.has(code)) {\n return;\n }\n throw err;\n } finally {\n if (fd !== null) {\n try {\n fs.closeSync(fd);\n } catch {\n // Close errors after a successful fsync are not actionable.\n }\n }\n }\n}\n\n/**\n * Synchronously writes `payload` to `tmpPath` and fsyncs the\n * resulting file so its data and metadata are durable on disk\n * before any rename is observable. Throws on any I/O error from\n * either step; on throw, the partially-written tmp file is left\n * in place (callers handle cleanup so they can decide between\n * `unlink` and a backup-rollback strategy).\n *\n * Steps 1 and 2 of the SDK 2.0 §4.3 protocol. Pair with a `rename`\n * (step 3) and {@link fsyncParentDirSync} (step 4) — or use\n * {@link atomicWriteFileSync}/{@link atomicWriteFileSyncWithTmp}\n * which compose all four steps internally.\n *\n * @internal Sibling-module use only.\n */\nexport function writeAndFsyncTempSync(\n tmpPath: string,\n payload: string | Uint8Array,\n options: AtomicWriteOptions = {},\n): void {\n const mode = options.mode ?? 0o600;\n const encoding = options.encoding ?? \"utf-8\";\n const fs = loadFsSync();\n if (typeof payload === \"string\") {\n fs.writeFileSync(tmpPath, payload, { encoding, mode });\n } else {\n fs.writeFileSync(tmpPath, payload, { mode });\n }\n // Re-apply the requested mode in case `tmpPath` already existed —\n // `writeFileSync` only honors `mode` when creating the file, so a\n // stale residue could otherwise carry permissive bits into the\n // caller's eventual rename. Path-based `chmodSync` keeps the fsync\n // handle below read-only.\n fs.chmodSync(tmpPath, mode);\n // Read-only is sufficient for `fsync` and works for callers that\n // pass a read-only `mode`.\n const fd = fs.openSync(tmpPath, \"r\");\n try {\n fs.fsyncSync(fd);\n } finally {\n try {\n fs.closeSync(fd);\n } catch {\n // Close errors after fsync are not actionable.\n }\n }\n}\n\n/**\n * Returns `true` when synchronous `node:fs` is reachable in the current\n * runtime, `false` otherwise. Callers that prefer a silent-skip path\n * over a thrown `node:fs is unavailable` error use this probe before\n * dispatching to {@link atomicWriteFileSync}.\n *\n * The probe shares the lazy-loader cache with the sync helpers, so a\n * `true` result also primes the cache for the subsequent write. This\n * keeps the probe overhead to one `require(\"node:fs\")` per process.\n *\n * Background: tsup's bundled `__require` shim throws \"Dynamic require\n * of \\\"node:fs\\\" is not supported\" when the SDK is loaded as an ESM\n * module from a host like Next.js (DISC-1555). The runtime is a real\n * Node process — it just lacks a working synchronous `require()`\n * binding in the ESM scope. Async helpers are unaffected because\n * `await import(\"node:fs/promises\")` is ESM-native.\n *\n * @internal Sibling-module use only.\n */\nexport function isSyncFsAvailable(): boolean {\n try {\n loadFsSync();\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Test-only: clear the cached lazy-loaded modules. Allows test suites\n * that mock `node:fs`/`node:fs/promises` to ensure the helper re-runs\n * its module probe.\n *\n * @internal Tests only.\n */\nexport function _resetModuleCacheForTesting(): void {\n fsPromisesCache = undefined;\n fsSyncCache = undefined;\n}\n","import { createHash } from \"node:crypto\";\nimport {\n AnonApiKeySchema,\n DevApiKeySchema,\n type AnonApiKey,\n type DevApiKey,\n} from \"@glasstrace/protocol\";\nimport { readAnonKey, readClaimedKey } from \"./anon-key.js\";\nimport { atomicWriteFile } from \"./atomic-write.js\";\n\n/**\n * Glasstrace MCP endpoint embedded in managed MCP configs and used by\n * the runtime claim-refresh path. Lives here (not in `cli/constants.ts`)\n * so the runtime helper can reach it without crossing the runtime/CLI\n * boundary; CLI callers import it directly from this module.\n */\nexport const MCP_ENDPOINT = \"https://api.glasstrace.dev/mcp\";\n\n/**\n * Runtime-safe MCP credential and config utilities.\n *\n * This module is loaded into user processes at SDK boot. It must not\n * import from `cli/*` or `agent-detection/*` so the runtime bundle does\n * not pull in CLI scaffolding or filesystem scanners. The boundary is\n * enforced by an import-graph guard test.\n *\n * Internal: not re-exported via `node-entry.ts` or `index.ts`.\n *\n * @module\n */\n\nlet fsPathCache:\n | { fs: typeof import(\"node:fs/promises\"); path: typeof import(\"node:path\") }\n | null\n | undefined;\n\nasync function loadFsPath(): Promise<\n | { fs: typeof import(\"node:fs/promises\"); path: typeof import(\"node:path\") }\n | null\n> {\n if (fsPathCache !== undefined) return fsPathCache;\n try {\n const [fs, path] = await Promise.all([\n import(\"node:fs/promises\"),\n import(\"node:path\"),\n ]);\n fsPathCache = { fs, path };\n return fsPathCache;\n } catch {\n fsPathCache = null;\n return null;\n }\n}\n\n/**\n * Computes a stable identity fingerprint for deduplication purposes.\n * This is NOT password hashing — the input is an opaque token used as\n * a marker identity, not a credential stored for authentication.\n *\n * @internal Exported for unit testing and for `cli/scaffolder.ts`'s\n * marker writer.\n */\nexport function identityFingerprint(token: string): string {\n return `sha256:${createHash(\"sha256\").update(token).digest(\"hex\")}`;\n}\n\n/**\n * Compares two MCP config strings for canonical-JSON equality. Returns\n * `true` when both inputs parse as JSON and produce structurally equal\n * objects after recursive key sorting; falls back to trimmed text\n * comparison for TOML and other non-JSON formats. Returns `false` on\n * parse errors that don't fall through to text comparison.\n *\n * Used to detect manually-edited MCP configs before overwriting them\n * (DISC-1247 Scenario 2c) and as the staleness signal for SDK-managed\n * configs that must be refreshed when the project's effective\n * credential changes.\n *\n * @internal Exported for unit testing only.\n */\nexport function mcpConfigMatches(\n existingContent: string,\n expectedContent: string,\n): boolean {\n const trimmedExpected = expectedContent.trim();\n\n try {\n const existingParsed: unknown = JSON.parse(existingContent);\n const expectedParsed: unknown = JSON.parse(trimmedExpected);\n return (\n JSON.stringify(canonicalize(existingParsed)) ===\n JSON.stringify(canonicalize(expectedParsed))\n );\n } catch {\n // Fall through to text comparison for TOML and other non-JSON formats.\n }\n\n return existingContent.trim() === trimmedExpected;\n}\n\nfunction canonicalize(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map(canonicalize);\n }\n if (value !== null && typeof value === \"object\") {\n const obj = value as Record<string, unknown>;\n const sorted: Record<string, unknown> = {};\n for (const key of Object.keys(obj).sort()) {\n sorted[key] = canonicalize(obj[key]);\n }\n return sorted;\n }\n return value;\n}\n\n/**\n * Parses a `.env.local` file's text content for `GLASSTRACE_API_KEY`,\n * returning the last assignment's value. Empty values\n * (`GLASSTRACE_API_KEY=`) and the `your_key_here` placeholder are\n * filtered out. Surrounding single or double quotes are stripped.\n *\n * The resolver validates the returned value against `DevApiKeySchema`\n * before accepting it; this parser is permissive on purpose so that\n * malformed values can be flagged with a `malformed-env-local`\n * warning rather than silently dropped.\n *\n * @internal Exported for unit testing only.\n */\nexport function readEnvLocalApiKey(content: string): string | null {\n let last: string | null = null;\n const regex = /^\\s*GLASSTRACE_API_KEY\\s*=\\s*(.*)$/gm;\n let match: RegExpExecArray | null;\n while ((match = regex.exec(content)) !== null) {\n const raw = match[1].trim();\n if (raw === \"\") continue;\n const unquoted = raw.replace(/^(['\"])(.*)\\1$/, \"$2\");\n if (unquoted === \"\" || unquoted === \"your_key_here\") continue;\n last = unquoted;\n }\n return last;\n}\n\n/**\n * Returns true when the given API key value looks like a claimed\n * developer key (prefix `gt_dev_`). Defensive against leading or\n * trailing whitespace.\n *\n * **This is a prefix-only check, not strict validation.** Use it as a\n * fast path for \"looks like a claimed key, do not overwrite\". The\n * effective-credential resolver validates with\n * `DevApiKeySchema.safeParse` because a `gt_dev_` prefix alone is not\n * sufficient to authenticate against the backend.\n *\n * @internal Exported for unit testing only.\n */\nexport function isDevApiKey(value: string | null | undefined): boolean {\n if (value === null || value === undefined) return false;\n return value.trim().startsWith(\"gt_dev_\");\n}\n\n/**\n * Returns true when the given API key value is a fully-valid anonymous\n * API key (matches `AnonApiKeySchema`). Used by `registerViaCli` as a\n * runtime guard so that a `DevApiKey` cannot be passed via process\n * arguments to vendor MCP CLIs (which would expose it via `ps` on\n * multi-user hosts).\n *\n * @internal Exported for unit testing only.\n */\nexport function isAnonApiKey(value: string | null | undefined): boolean {\n if (value === null || value === undefined) return false;\n return AnonApiKeySchema.safeParse(value).success;\n}\n\n/**\n * The MCP-effective credential, tagged by which on-disk source produced\n * it. `env-local` and `claimed-key` carry a branded `DevApiKey`;\n * `anon` carries a branded `AnonApiKey`. Internal — not re-exported.\n */\nexport type EffectiveMcpCredential =\n | { source: \"env-local\"; key: DevApiKey }\n | { source: \"claimed-key\"; key: DevApiKey }\n | { source: \"anon\"; key: AnonApiKey };\n\n/**\n * Surfaced when the resolver detected a recoverable anomaly the caller\n * should inform the user about without printing key material.\n *\n * - `malformed-env-local`: `.env.local` set `GLASSTRACE_API_KEY` to a\n * value that fails `DevApiKeySchema`. The resolver fell through.\n * - `claimed-key-only`: the effective credential came from\n * `.glasstrace/claimed-key` because `.env.local` had no usable dev\n * key. Suggest the user copy the key into `.env.local`.\n */\nexport type ResolveWarning = \"malformed-env-local\" | \"claimed-key-only\";\n\n/**\n * The resolved credential plus the on-disk anon key (returned\n * separately so the staleness check does not have to re-read the\n * file) and any warnings the caller should surface to the user.\n */\nexport interface ResolveResult {\n effective: EffectiveMcpCredential | null;\n anonKey: AnonApiKey | null;\n warnings: ReadonlyArray<ResolveWarning>;\n}\n\n/**\n * Resolves the MCP-effective credential for a project, in priority\n * order: `.env.local` `GLASSTRACE_API_KEY` (validated as\n * `DevApiKeySchema`) → `.glasstrace/claimed-key` (validated as\n * `DevApiKeySchema`) → `.glasstrace/anon_key` (`AnonApiKey`). Returns\n * `null` for `effective` only when no source produced a usable key.\n *\n * The function is async because it touches the filesystem. It is\n * called only on the post-claim runtime branch and from the CLI\n * commands `glasstrace init` and `glasstrace mcp add`. It is **not**\n * on the steady-state init path.\n */\nexport async function resolveEffectiveMcpCredential(\n projectRoot?: string,\n): Promise<ResolveResult> {\n const root = projectRoot ?? process.cwd();\n const warnings: ResolveWarning[] = [];\n\n const envLocalKey = await readEnvLocalDevKey(root, warnings);\n const claimedKey = envLocalKey === null ? await readClaimedKey(root) : null;\n const anonKey = await readAnonKey(root);\n\n let effective: EffectiveMcpCredential | null = null;\n if (envLocalKey !== null) {\n effective = { source: \"env-local\", key: envLocalKey };\n } else if (claimedKey !== null) {\n effective = { source: \"claimed-key\", key: claimedKey };\n warnings.push(\"claimed-key-only\");\n } else if (anonKey !== null) {\n effective = { source: \"anon\", key: anonKey };\n }\n\n return { effective, anonKey, warnings };\n}\n\nasync function readEnvLocalDevKey(\n root: string,\n warnings: ResolveWarning[],\n): Promise<DevApiKey | null> {\n const modules = await loadFsPath();\n if (!modules) return null;\n\n const envPath = modules.path.join(root, \".env.local\");\n let content: string;\n try {\n content = await modules.fs.readFile(envPath, \"utf-8\");\n } catch {\n return null;\n }\n\n const raw = readEnvLocalApiKey(content);\n if (raw === null) return null;\n\n const parsed = DevApiKeySchema.safeParse(raw);\n if (!parsed.success) {\n warnings.push(\"malformed-env-local\");\n return null;\n }\n return parsed.data;\n}\n\n/**\n * Source label for the credential a marker file describes.\n *\n * @internal\n */\nexport type MarkerCredentialSource = \"env-local\" | \"claimed-key\" | \"anon\";\n\n/**\n * Descriptor passed to {@link writeMcpMarker} and matched by\n * {@link readMcpMarker}. `credentialHash` is the\n * `identityFingerprint` of the credential actually written into the\n * managed MCP config — never the credential itself.\n *\n * @internal\n */\nexport interface MarkerTarget {\n credentialSource: MarkerCredentialSource;\n credentialHash: string;\n}\n\n/**\n * Normalized state of a `.glasstrace/mcp-connected` marker on disk.\n *\n * - `absent`: no marker file present.\n * - `valid`: a v1 or v2 marker that parsed cleanly. v1 markers are\n * reported as `credentialSource = \"anon\"` with `credentialHash`\n * taken from the legacy `keyHash` field (the v1 schema can only\n * describe an anon credential).\n * - `unknown-version`: the marker has `version > 2`. Treat as\n * not-configured so a future SDK that wrote the marker doesn't\n * block this SDK from refreshing.\n * - `corrupted`: parse failure or schema mismatch. Treat as\n * not-configured.\n *\n * @internal\n */\nexport type MarkerState =\n | { status: \"absent\" }\n | { status: \"valid\"; credentialSource: MarkerCredentialSource; credentialHash: string }\n | { status: \"unknown-version\" }\n | { status: \"corrupted\" };\n\nconst MCP_MARKER_FILE = \"mcp-connected\";\nconst GLASSTRACE_DIR = \".glasstrace\";\n\n/**\n * Reads `.glasstrace/mcp-connected` and returns its normalized state.\n * Used by `mcp add` (marker-mismatch detection) and by\n * {@link writeMcpMarker} (skip-if-match optimization).\n *\n * Reader rules per the design (`SDK-034 D3`):\n * - `version === undefined` → v1: `{ keyHash, configuredAt }`. Mapped\n * to `credentialSource: \"anon\"`, `credentialHash: keyHash`. v1's\n * `keyHash` is itself produced by `identityFingerprint`, so the\n * format matches v2 without conversion.\n * - `version === 2` → v2 reader.\n * - `version > 2` → `unknown-version` (conservative-fail).\n * - Parse failure → `corrupted` (conservative-fail).\n *\n * @internal Exported for unit testing only.\n */\nexport async function readMcpMarker(projectRoot?: string): Promise<MarkerState> {\n const root = projectRoot ?? process.cwd();\n const modules = await loadFsPath();\n if (!modules) return { status: \"absent\" };\n\n const markerPath = modules.path.join(root, GLASSTRACE_DIR, MCP_MARKER_FILE);\n let content: string;\n try {\n content = await modules.fs.readFile(markerPath, \"utf-8\");\n } catch {\n return { status: \"absent\" };\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(content);\n } catch {\n return { status: \"corrupted\" };\n }\n\n if (parsed === null || typeof parsed !== \"object\") {\n return { status: \"corrupted\" };\n }\n\n const obj = parsed as Record<string, unknown>;\n const version = obj[\"version\"];\n\n if (version === undefined) {\n // v1: { keyHash, configuredAt }\n const keyHash = obj[\"keyHash\"];\n if (typeof keyHash !== \"string\" || keyHash === \"\") {\n return { status: \"corrupted\" };\n }\n return {\n status: \"valid\",\n credentialSource: \"anon\",\n credentialHash: keyHash,\n };\n }\n\n if (version === 2) {\n const source = obj[\"credentialSource\"];\n const hash = obj[\"credentialHash\"];\n if (\n (source !== \"env-local\" && source !== \"claimed-key\" && source !== \"anon\") ||\n typeof hash !== \"string\" ||\n hash === \"\"\n ) {\n return { status: \"corrupted\" };\n }\n return {\n status: \"valid\",\n credentialSource: source,\n credentialHash: hash,\n };\n }\n\n if (typeof version === \"number\" && version > 2) {\n return { status: \"unknown-version\" };\n }\n\n return { status: \"corrupted\" };\n}\n\n/**\n * Writes a v2 `.glasstrace/mcp-connected` marker. Returns `true` when\n * the marker was created or updated, `false` when an existing marker\n * already records the same `(credentialSource, credentialHash)` pair\n * and was left untouched.\n *\n * Writer always emits v2 with `version: 2`. The legacy `keyHash`\n * field is intentionally omitted from new writes — v1 readers ignore\n * unknown fields and the duplicate would diverge over time. v3+ and\n * corrupted markers are unconditionally overwritten.\n *\n * The directory is created with `0o700` and the file with `0o600`,\n * matching existing scaffolder behavior.\n *\n * @internal Exported for unit testing only.\n */\nexport async function writeMcpMarker(\n projectRoot: string,\n target: MarkerTarget,\n): Promise<boolean> {\n const modules = await loadFsPath();\n if (!modules) return false;\n\n const dirPath = modules.path.join(projectRoot, GLASSTRACE_DIR);\n const markerPath = modules.path.join(dirPath, MCP_MARKER_FILE);\n\n const state = await readMcpMarker(projectRoot);\n if (\n state.status === \"valid\" &&\n state.credentialSource === target.credentialSource &&\n state.credentialHash === target.credentialHash\n ) {\n return false;\n }\n\n await modules.fs.mkdir(dirPath, { recursive: true, mode: 0o700 });\n\n const body = JSON.stringify(\n {\n version: 2,\n credentialSource: target.credentialSource,\n credentialHash: target.credentialHash,\n configuredAt: new Date().toISOString(),\n },\n null,\n 2,\n );\n\n await modules.fs.writeFile(markerPath, body, { mode: 0o600 });\n // writeFile mode only applies on creation on some platforms.\n await modules.fs.chmod(markerPath, 0o600);\n return true;\n}\n\nconst MCP_CONFIG_FILE = \"mcp.json\";\n\n/**\n * The set of outcomes the runtime claim-refresh helper can produce.\n *\n * - `rewrote`: `.glasstrace/mcp.json` matched the SDK-shaped output\n * for the on-disk anon key, was rewritten with the effective\n * credential, and the marker was updated.\n * - `preserved`: `.glasstrace/mcp.json` exists but does not match the\n * SDK-shaped output for the on-disk anon key. The file is left\n * untouched (the user may have hand-edited it). The marker is not\n * touched.\n * - `absent`: `.glasstrace/mcp.json` does not exist (`ENOENT`), or\n * no anon key is on disk so there is nothing to compare against. A\n * project without an anon key never had an SDK-shaped `mcp.json`\n * written by the runtime path, so this branch is a true no-op.\n * - `skipped-anon-source`: the effective credential is `null` or its\n * source is `\"anon\"`. Either way, there is no claim transition to\n * refresh for. Caller should generally gate on\n * `effective.source !== \"anon\"` before invoking the helper; this\n * branch is the runtime-side belt-and-suspenders.\n * - `skipped-not-persisted`: never reached in practice — the caller\n * in `init-client.ts` gates on `writeClaimedKey`'s `persisted` not\n * being `\"none\"`. The variant exists so an exhaustive switch in\n * the caller stays exhaustive if the gate is removed.\n *\n * @internal\n */\nexport type RuntimeRefreshAction =\n | \"rewrote\"\n | \"preserved\"\n | \"absent\"\n | \"skipped-anon-source\"\n | \"skipped-not-persisted\";\n\nlet refreshNudgeEmitted = false;\n\n/**\n * @internal Exported for unit testing only — resets the per-process\n * \"refresh nudge already emitted\" flag.\n */\nexport function __resetRefreshNudgeForTest(): void {\n refreshNudgeEmitted = false;\n}\n\n/**\n * Emits a single redacted stderr line announcing the MCP config\n * refresh. Deduplicated per process via a module-level flag — a\n * second call within the same process is a no-op. Cross-process\n * dedup (the same user running `mcp add` in another terminal moments\n * later) is explicitly out of scope.\n */\nfunction emitRefreshNudge(persistedSource: \"env-local\" | \"claimed-key\"): void {\n if (refreshNudgeEmitted) return;\n refreshNudgeEmitted = true;\n try {\n if (persistedSource === \"claimed-key\") {\n process.stderr.write(\n \"[glasstrace] MCP config refreshed for the new credential. \" +\n \"Copy .glasstrace/claimed-key into .env.local so Codex can pick it up on next restart.\\n\",\n );\n } else {\n process.stderr.write(\n \"[glasstrace] MCP config refreshed for the new credential.\\n\",\n );\n }\n } catch {\n // stderr is best-effort; refresh outcome must not depend on it.\n }\n}\n\n/**\n * Returns the SDK-shaped JSON for `.glasstrace/mcp.json` (the generic\n * MCP config used at runtime). Inlined here — and intentionally not\n * imported from `agent-detection/configs.ts` — because the runtime\n * path must not pull `agent-detection` into the runtime bundle. The\n * shape matches what `generateMcpConfig({ name: \"generic\", ... },\n * endpoint, bearer)` would produce. If the agent-detection version\n * diverges, the staleness check stops detecting SDK-managed configs;\n * a regression test against `generateMcpConfig`'s \"generic\" branch\n * lives in `tests/unit/sdk/mcp-runtime.test.ts`.\n */\nfunction genericMcpConfigContent(endpoint: string, bearer: string): string {\n return JSON.stringify(\n {\n mcpServers: {\n glasstrace: {\n url: endpoint,\n headers: {\n Authorization: `Bearer ${bearer}`,\n },\n },\n },\n },\n null,\n 2,\n );\n}\n\n/**\n * Refreshes `.glasstrace/mcp.json` after a successful account claim\n * transition has persisted a dev/account credential to disk (via\n * `writeClaimedKey`). The file is rewritten only when its content\n * matches the SDK-shaped output for the project's on-disk anon key\n * (canonical-JSON equivalence via `mcpConfigMatches` — whitespace and\n * key order are normalised before comparison). User-edited or\n * third-party `mcp.json` content is preserved.\n *\n * Atomic write protocol: write the replacement to a sibling temp\n * path, set `0o600`, then `rename` into place. This matches the\n * existing pattern at `init-client.ts` for `.glasstrace/config`,\n * `anon-key.ts` for `.glasstrace/anon_key`, and `runtime-state.ts`.\n * The temp must be on the same filesystem as the destination for the\n * `rename` to be atomic.\n *\n * The helper is invoked only on the post-claim runtime branch (see\n * `init-client.ts` `performInit`) and never on the steady-state init\n * path. It must not throw — failures during write/chmod/rename or\n * marker update surface as `\"preserved\"` so the caller's\n * `claimResult` return is preserved. The temp file is best-effort\n * cleaned up on failure to avoid leaving stale `.tmp` siblings on\n * disk.\n *\n * @internal Exported for unit testing only; not re-exported from\n * `node-entry.ts` or `index.ts`.\n */\nexport async function refreshGenericMcpConfigAtRuntime(\n projectRoot: string,\n effective: EffectiveMcpCredential | null,\n anonKeyOnDisk: AnonApiKey | null,\n): Promise<{ action: RuntimeRefreshAction }> {\n if (effective === null || effective.source === \"anon\") {\n return { action: \"skipped-anon-source\" };\n }\n\n // Dev-key-only project (no .glasstrace/anon_key on disk): the\n // staleness check has nothing to compare against. The SDK never\n // wrote mcp.json without an anon key, so there is nothing to\n // refresh.\n if (anonKeyOnDisk === null) {\n return { action: \"absent\" };\n }\n\n const modules = await loadFsPath();\n if (!modules) return { action: \"absent\" };\n\n const dirPath = modules.path.join(projectRoot, GLASSTRACE_DIR);\n const configPath = modules.path.join(dirPath, MCP_CONFIG_FILE);\n\n let existing: string;\n try {\n existing = await modules.fs.readFile(configPath, \"utf-8\");\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code === \"ENOENT\") {\n return { action: \"absent\" };\n }\n return { action: \"preserved\" };\n }\n\n const expectedAnon = genericMcpConfigContent(MCP_ENDPOINT, anonKeyOnDisk);\n if (!mcpConfigMatches(existing, expectedAnon)) {\n return { action: \"preserved\" };\n }\n\n // SDK-managed and stale. Replace atomically per SDK 2.0 §4.3:\n // tmp + fsync(tmp) + rename + fsync(parent). Any failure in the\n // helper or marker update path must produce a non-throw outcome\n // so the caller's claimResult return is preserved; the helper\n // best-effort cleans up the .tmp sibling on failure.\n const replacement = genericMcpConfigContent(MCP_ENDPOINT, effective.key);\n try {\n await atomicWriteFile(configPath, replacement, { mode: 0o600 });\n\n await writeMcpMarker(projectRoot, {\n credentialSource: effective.source,\n credentialHash: identityFingerprint(effective.key),\n });\n } catch {\n return { action: \"preserved\" };\n }\n\n emitRefreshNudge(effective.source);\n\n return { action: \"rewrote\" };\n}\n"],"mappings":";;;;;;;;;;AAGA,IAAM,iBAA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