@dxos/observability 0.16.0 → 0.17.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/lib/chunk-ObservabilityExtension.mjs +33 -2
- package/dist/lib/chunk-ObservabilityExtension.mjs.map +1 -1
- package/dist/lib/chunk-OtelProxy.mjs +102 -0
- package/dist/lib/chunk-OtelProxy.mjs.map +1 -0
- package/dist/lib/chunk-OtelSpanSink.mjs +1 -1
- package/dist/lib/chunk-OtelSpanSink.mjs.map +1 -1
- package/dist/lib/extensions/otel/OtelProxy.mjs +1 -0
- package/dist/lib/index.mjs +2 -1
- package/dist/types/src/extensions/otel/OtelProxy.d.ts +18 -0
- package/dist/types/src/extensions/otel/OtelProxy.d.ts.map +1 -0
- package/dist/types/src/extensions/otel/OtelProxy.js +90 -0
- package/dist/types/src/extensions/otel/OtelProxy.js.map +1 -0
- package/dist/types/src/extensions/otel/OtelProxy.test.d.ts +2 -0
- package/dist/types/src/extensions/otel/OtelProxy.test.d.ts.map +1 -0
- package/dist/types/src/extensions/otel/OtelProxy.test.js +62 -0
- package/dist/types/src/extensions/otel/OtelProxy.test.js.map +1 -0
- package/dist/types/src/extensions/otel/tail-sampling.d.ts +1 -1
- package/dist/types/src/extensions/otel/tail-sampling.js +1 -1
- package/{src/extensions/otel/sinks.ts → dist/types/src/extensions/otel/worker-entrypoints.d.ts} +2 -5
- package/dist/types/src/extensions/otel/worker-entrypoints.d.ts.map +1 -0
- package/dist/types/src/extensions/otel/{sinks.js → worker-entrypoints.js} +2 -2
- package/dist/types/src/extensions/otel/worker-entrypoints.js.map +1 -0
- package/dist/types/src/extensions/posthog/before-send.d.ts +1 -0
- package/dist/types/src/extensions/posthog/before-send.d.ts.map +1 -1
- package/dist/types/src/extensions/posthog/before-send.js +38 -0
- package/dist/types/src/extensions/posthog/before-send.js.map +1 -1
- package/dist/types/src/extensions/posthog/before-send.test.js +52 -1
- package/dist/types/src/extensions/posthog/before-send.test.js.map +1 -1
- package/dist/types/src/extensions/posthog/extension.js +2 -2
- package/dist/types/src/extensions/posthog/extension.js.map +1 -1
- package/dist/types/src/index.d.ts +1 -1
- package/dist/types/src/index.d.ts.map +1 -1
- package/dist/types/src/index.js +1 -1
- package/dist/types/src/index.js.map +1 -1
- package/dist/types/src/version.d.ts +1 -1
- package/dist/types/src/version.js +1 -1
- package/dist/types/tsconfig.tsbuildinfo +1 -1
- package/package.json +25 -21
- package/src/extensions/otel/OtelProxy.test.ts +74 -0
- package/src/extensions/otel/OtelProxy.ts +119 -0
- package/src/extensions/otel/tail-sampling.ts +1 -1
- package/{dist/types/src/extensions/otel/sinks.d.ts → src/extensions/otel/worker-entrypoints.ts} +5 -1
- package/src/extensions/posthog/before-send.test.ts +69 -1
- package/src/extensions/posthog/before-send.ts +45 -1
- package/src/extensions/posthog/extension.ts +2 -2
- package/src/index.ts +1 -1
- package/src/version.ts +1 -1
- package/dist/types/src/extensions/otel/sinks.d.ts.map +0 -1
- package/dist/types/src/extensions/otel/sinks.js.map +0 -1
|
@@ -63,7 +63,7 @@ var toAiGenerationProperties = (inference) => stripUndefined({
|
|
|
63
63
|
var stripUndefined = (properties) => Object.fromEntries(Object.entries(properties).filter(([, value]) => value !== void 0));
|
|
64
64
|
//#endregion
|
|
65
65
|
//#region src/version.ts
|
|
66
|
-
var DXOS_VERSION = "0.
|
|
66
|
+
var DXOS_VERSION = "0.17.0";
|
|
67
67
|
//#endregion
|
|
68
68
|
//#region src/extensions/posthog/before-send.ts
|
|
69
69
|
/**
|
|
@@ -77,6 +77,33 @@ var dropBenignExceptions = (capture) => {
|
|
|
77
77
|
const exceptions = capture.properties.$exception_list ?? [];
|
|
78
78
|
return exceptions.length > 0 && exceptions.every(({ value }) => typeof value === "string" && BENIGN_EXCEPTIONS.some((pattern) => pattern.test(value))) ? null : capture;
|
|
79
79
|
};
|
|
80
|
+
var INVITATION_PARAM = "spaceInvitationCode";
|
|
81
|
+
var redactUrl = (value) => {
|
|
82
|
+
if (!value.includes("?")) return value;
|
|
83
|
+
let url;
|
|
84
|
+
try {
|
|
85
|
+
url = new URL(value);
|
|
86
|
+
} catch {
|
|
87
|
+
return value;
|
|
88
|
+
}
|
|
89
|
+
if (!url.searchParams.has(INVITATION_PARAM)) return value;
|
|
90
|
+
url.searchParams.delete(INVITATION_PARAM);
|
|
91
|
+
return url.toString();
|
|
92
|
+
};
|
|
93
|
+
/** Redacts every string in a property value, including person properties nested as `properties.$set`. */
|
|
94
|
+
var redactValue = (value) => {
|
|
95
|
+
if (typeof value === "string") return redactUrl(value);
|
|
96
|
+
if (Array.isArray(value)) return value.map(redactValue);
|
|
97
|
+
if (value !== null && typeof value === "object") return redactProperties(value);
|
|
98
|
+
return value;
|
|
99
|
+
};
|
|
100
|
+
var redactProperties = (properties) => Object.fromEntries(Object.entries(properties).map(([key, value]) => [key, redactValue(value)]));
|
|
101
|
+
var redactInvitationCodes = (capture) => capture && {
|
|
102
|
+
...capture,
|
|
103
|
+
properties: redactProperties(capture.properties),
|
|
104
|
+
...capture.$set && { $set: redactProperties(capture.$set) },
|
|
105
|
+
...capture.$set_once && { $set_once: redactProperties(capture.$set_once) }
|
|
106
|
+
};
|
|
80
107
|
//#endregion
|
|
81
108
|
//#region src/extensions/posthog/otel-destination.ts
|
|
82
109
|
var __dxlog_file$1 = "/__w/dxos/dxos/packages/sdk/observability/src/extensions/posthog/otel-destination.ts";
|
|
@@ -209,7 +236,11 @@ var extensions = Effect.fn(function* ({ config, release, environment, serviceNam
|
|
|
209
236
|
blockSelector: `:not(body):has(> iframe:not(.${REPLAY_IFRAME_CLASS}))`,
|
|
210
237
|
...posthogConfig?.session_recording
|
|
211
238
|
},
|
|
212
|
-
before_send: [
|
|
239
|
+
before_send: [
|
|
240
|
+
dropBenignExceptions,
|
|
241
|
+
redactInvitationCodes,
|
|
242
|
+
...[posthogConfig?.before_send ?? []].flat()
|
|
243
|
+
],
|
|
213
244
|
...recordingStart ? { disable_session_recording: true } : {}
|
|
214
245
|
});
|
|
215
246
|
if (recordingStart) yield* Effect.forkDetach(recordingStart.pipe(Effect.andThen(Effect.sync(() => posthog.startSessionRecording()))));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"chunk-ObservabilityExtension.mjs","names":["__dxlog_file"],"sources":["../../src/extensions/posthog/llm-analytics.ts","../../src/version.ts","../../src/extensions/posthog/before-send.ts","../../src/extensions/posthog/otel-destination.ts","../../src/extensions/posthog/extension.ts","../../src/extensions/posthog/index.ts","../../src/ObservabilityExtension.ts"],"sourcesContent":["//\n// Copyright 2026 DXOS.org\n//\n\nimport type * as ObservabilityExtension from '../../ObservabilityExtension.ts';\n\n/**\n * PostHog's LLM analytics schema. Three events with `$ai_*` properties are what the product reads:\n * `$ai_trace` is the top-level unit (a conversation turn here), `$ai_span` a step inside it (a tool\n * call), `$ai_generation` a model call. They are linked by `$ai_trace_id`, and a span or generation\n * names its parent with `$ai_parent_id`.\n *\n * `$ai_input_tokens` is the uncached count, which is what PostHog expects alongside the two cache\n * figures — together they price the call, and their ratio is the prompt-cache hit rate.\n */\nexport const AI_GENERATION_EVENT = '$ai_generation';\nexport const AI_TRACE_EVENT = '$ai_trace';\nexport const AI_SPAN_EVENT = '$ai_span';\n\n/** `$ai_trace`: the turn, carrying the prompt and the messages it produced as its states. */\nexport const toAiTraceProperties = (turn: ObservabilityExtension.Turn): Record<string, unknown> =>\n stripUndefined({\n ...spanProperties(turn),\n });\n\n/** `$ai_span` of type `tool`: one tool call, carrying its arguments and result as its states. */\nexport const toAiSpanProperties = (toolCall: ObservabilityExtension.ToolCall): Record<string, unknown> =>\n stripUndefined({\n ...spanProperties(toolCall),\n $ai_span_type: 'tool',\n });\n\nconst spanProperties = (span: ObservabilityExtension.AiSpanBase): Record<string, unknown> => ({\n $ai_trace_id: span.traceId,\n $ai_span_id: span.spanId,\n $ai_parent_id: span.parentSpanId,\n $ai_span_name: span.spanName,\n $ai_session_id: span.sessionId,\n $ai_latency: span.latency,\n $ai_input_state: span.content?.input,\n $ai_output_state: span.content?.output,\n $ai_content_truncated: span.content?.truncated,\n $ai_is_error: span.errorClass ? true : undefined,\n $ai_error: span.errorClass,\n});\n\nexport const toAiGenerationProperties = (inference: ObservabilityExtension.Inference): Record<string, unknown> =>\n stripUndefined({\n $ai_trace_id: inference.traceId,\n $ai_span_id: inference.spanId,\n $ai_parent_id: inference.parentSpanId,\n $ai_span_name: inference.spanName,\n $ai_provider: inference.provider,\n $ai_model: inference.model,\n $ai_session_id: inference.sessionId,\n $ai_model_parameters: inference.parameters,\n $ai_input_tokens: inference.inputTokens,\n $ai_output_tokens: inference.outputTokens,\n $ai_cache_read_input_tokens: inference.cacheReadTokens,\n $ai_cache_creation_input_tokens: inference.cacheWriteTokens,\n $ai_latency: inference.latency,\n $ai_stream: inference.streaming,\n $ai_input: inference.content?.input,\n $ai_output_choices: inference.content?.output,\n $ai_tools: inference.content?.tools,\n $ai_content_truncated: inference.content?.truncated,\n $ai_is_error: inference.errorClass ? true : undefined,\n $ai_error: inference.errorClass,\n });\n\nconst stripUndefined = (properties: Record<string, unknown>): Record<string, unknown> =>\n Object.fromEntries(Object.entries(properties).filter(([, value]) => value !== undefined));\n","//\n// Copyright 2026 DXOS.org\n//\n\nexport const DXOS_VERSION = '0.16.0';\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport { type BeforeSendFn } from 'posthog-js';\n\n/**\n * Browser-raised errors with no stack and no effect on the user: a ResizeObserver callback that resized an element\n * mid-delivery is reported this way, and the browser delivers the skipped notifications on the next frame.\n */\nconst BENIGN_EXCEPTIONS = [/^ResizeObserver loop/];\n\n/** Drops `$exception` events whose every exception is benign. */\nexport const dropBenignExceptions: BeforeSendFn = (capture) => {\n if (capture?.event !== '$exception') {\n return capture;\n }\n\n const exceptions: { value?: unknown }[] = capture.properties.$exception_list ?? [];\n const benign =\n exceptions.length > 0 &&\n exceptions.every(\n ({ value }) => typeof value === 'string' && BENIGN_EXCEPTIONS.some((pattern) => pattern.test(value)),\n );\n return benign ? null : capture;\n};\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport { type Config, getEnvString } from '@dxos/config';\nimport { log } from '@dxos/log';\n\nimport { type OtelDestination } from '../otel/otel.ts';\n\n/** PostHog serves OTLP under `/i` of the same host it ingests product analytics on, not at the root. */\nconst OTLP_PATH_PREFIX = '/i';\n\n/**\n * PostHog as an OTLP backend, authenticated with the public `phc_` project token rather than a\n * secret, so the browser can post to it directly.\n */\nexport const otelDestination = (config: Config): OtelDestination | undefined => {\n const host = getEnvString(config, 'DX_POSTHOG_API_HOST');\n const apiKey = getEnvString(config, 'DX_POSTHOG_API_KEY');\n if (!host) {\n return undefined;\n }\n if (!apiKey) {\n log.info('DX_POSTHOG_API_HOST is set without DX_POSTHOG_API_KEY; skipping PostHog OTLP export');\n return undefined;\n }\n\n return {\n endpoint: `${host.replace(/\\/$/, '')}${OTLP_PATH_PREFIX}`,\n headers: { Authorization: `Bearer ${apiKey}` },\n };\n};\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Effect from 'effect/Effect';\nimport { type PostHogConfig } from 'posthog-js';\n\nimport { type Config, getEnvString } from '@dxos/config';\nimport { log } from '@dxos/log';\nimport { type IdbLogStore } from '@dxos/log-store-idb';\nimport { gzip, isNode } from '@dxos/util';\n\nimport * as ObservabilityExtension from '../../ObservabilityExtension.ts';\nimport { DXOS_VERSION } from '../../version.ts';\nimport { stubExtension } from '../stub.ts';\nimport { dropBenignExceptions } from './before-send.ts';\nimport {\n AI_GENERATION_EVENT,\n AI_SPAN_EVENT,\n AI_TRACE_EVENT,\n toAiGenerationProperties,\n toAiSpanProperties,\n toAiTraceProperties,\n} from './llm-analytics.ts';\nimport { otelDestination } from './otel-destination.ts';\n\nconst WIDGET_SESSION_STORAGE_KEY = 'dxos.support.widgetSessionId';\n\nconst widgetSessionId = (): string => {\n try {\n const existing = localStorage.getItem(WIDGET_SESSION_STORAGE_KEY);\n if (existing) {\n return existing;\n }\n const minted = crypto.randomUUID();\n localStorage.setItem(WIDGET_SESSION_STORAGE_KEY, minted);\n return minted;\n } catch {\n return crypto.randomUUID();\n }\n};\n\nexport type ExtensionsOptions = {\n config: Config;\n /** Release identifier, e.g. `composer@0.8.3`. */\n release?: string;\n /** Deployment environment, e.g. `production` or `staging`. */\n environment?: string;\n serviceName?: string;\n posthog?: Partial<PostHogConfig>;\n /**\n * Shared persistent log store for debug log dumps.\n * The owning app is expected to register `logStore.processor` with `log` itself —\n * this extension only consumes the buffered logs (via `export()`).\n */\n logStore?: IdbLogStore;\n /**\n * Maximum byte size passed to `logStore.export()` when uploading feedback logs.\n * Should match the upload limit enforced by the server receiving the logs.\n * When omitted the full store is exported without trimming.\n */\n feedbackLogMaxSize?: number;\n /**\n * Where to POST feedback logs, defaulting to {@link DEFAULT_FEEDBACK_LOGS_ENDPOINT}.\n * A native build serves its frontend from its own origin and has no such route there, so it must\n * pass the absolute URL of a deployment that does.\n */\n feedbackLogsEndpoint?: string;\n /**\n * Holds session recording back until this settles, so the recorder's DOM snapshot and compression\n * stay off the main thread during app startup. Ignored when `posthog.disable_session_recording` is set.\n */\n sessionRecordingStart?: Effect.Effect<void>;\n /** What the `posthog-node` transport needs; a browser host has posthog-js and reads none of it. */\n node?: NodeOptions;\n};\n\nexport type NodeOptions = {\n /** Pins the project instead of reading `DX_POSTHOG_API_KEY`. */\n apiKey?: string;\n /** Ingestion host — a region, or a proxy on your own domain. */\n host?: string;\n /** Attribution for events captured before `identify`, since there is no ambient person. */\n distinctId?: string;\n /** Which MCP server this host is, stamped on every `$mcp_*` event. */\n mcpServer?: { name: string; version: string };\n};\n\n/** Same-origin route of the web deployment, which proxies the upload to object storage. */\nconst DEFAULT_FEEDBACK_LOGS_ENDPOINT = '/api/feedback-logs';\n\n/** Upload serialized logs, gzipped, to the feedback-logs endpoint. Returns the R2 key on success. */\nconst uploadLogs = async (\n endpoint: string,\n ndjson: string,\n kind: ObservabilityExtension.SupportUploadKind = 'logs',\n): Promise<string | undefined> => {\n try {\n // The endpoint may be relative (same-origin) or absolute (native builds), so append rather than parse.\n const url = kind === 'logs' ? endpoint : `${endpoint}${endpoint.includes('?') ? '&' : '?'}kind=${kind}`;\n const response = await fetch(url, {\n method: 'POST',\n headers: { 'Content-Type': 'application/gzip' },\n body: await gzip(ndjson),\n });\n if (!response.ok) {\n log.warn('feedback log upload failed', { endpoint, status: response.status });\n return undefined;\n }\n const { key } = await response.json();\n return key;\n } catch (err) {\n log.warn('feedback log upload error', { endpoint, error: err });\n return undefined;\n }\n};\n\n/**\n * Class on an iframe that session replay records with its content. Only for a same-origin iframe the\n * recorder can read: it never releases an opaque one removed with an ancestor, which replays empty anyway.\n */\nexport const REPLAY_IFRAME_CLASS = 'dx-replay-iframe';\n\n/** Create a PostHog-backed observability extension for events, errors, and support tickets. */\nexport const extensions: (options: ExtensionsOptions) => Effect.Effect<ObservabilityExtension.Extension> = Effect.fn(\n function* ({\n config,\n release,\n environment,\n serviceName = 'app',\n posthog: posthogConfig,\n logStore,\n feedbackLogMaxSize,\n feedbackLogsEndpoint = DEFAULT_FEEDBACK_LOGS_ENDPOINT,\n sessionRecordingStart,\n node,\n }) {\n if (isNode()) {\n const { extensions: nodeExtensions } = yield* Effect.promise(() => import('#posthog-transport'));\n return yield* nodeExtensions({ config, release, environment, node });\n }\n if (typeof window === 'undefined') {\n log('PostHog is being stubbed because it is running in a worker.');\n return stubExtension;\n }\n\n const apiKey = getEnvString(config, 'DX_POSTHOG_API_KEY');\n const api_host = getEnvString(config, 'DX_POSTHOG_API_HOST');\n if (!apiKey || !api_host) {\n log.info('Missing POSTHOG_API_KEY or POSTHOG_API_HOST');\n return stubExtension;\n }\n\n const { default: posthog } = yield* Effect.promise(() => import('posthog-js'));\n const { logProcessor } = yield* Effect.promise(() => import('./log-processor.ts'));\n let unregisterPosthogProcessors: (() => void) | undefined;\n const recordingStart = posthogConfig?.disable_session_recording ? undefined : sessionRecordingStart;\n\n return {\n initialize: (context) =>\n Effect.gen(function* () {\n // https://posthog.com/docs/libraries/js/config\n posthog.init(apiKey, {\n api_host,\n mask_all_text: true,\n capture_exceptions: true,\n // Cookies stay scoped to the exact host; the cross-subdomain dmn_chk_* probe fails on public-suffix hosts (e.g. *.pages.dev) and spams the console.\n cross_subdomain_cookie: false,\n ...posthogConfig,\n session_recording: {\n // The recorder never releases a cross-origin iframe removed with an ancestor, and that\n // iframe pins the whole detached tree; children of a blocked element are never recorded.\n // `<body>` is exempt, or a hidden iframe appended to it would blank the whole replay.\n blockSelector: `:not(body):has(> iframe:not(.${REPLAY_IFRAME_CLASS}))`,\n ...posthogConfig?.session_recording,\n },\n before_send: [dropBenignExceptions, ...[posthogConfig?.before_send ?? []].flat()],\n ...(recordingStart ? { disable_session_recording: true } : {}),\n });\n if (recordingStart) {\n // Without an override this only lifts the local block; remote replay settings and sampling still apply.\n yield* Effect.forkDetach(\n recordingStart.pipe(Effect.andThen(Effect.sync(() => posthog.startSessionRecording()))),\n );\n }\n posthog.register({\n sdkVersion: DXOS_VERSION,\n ...(release ? { release } : {}),\n ...(environment ? { environment } : {}),\n });\n unregisterPosthogProcessors?.();\n const removePosthogLog = log.addProcessor(logProcessor);\n // PostHog joins a log record to its session replay on a log attribute literally named\n // `sessionId` — not the OTel `session.id` resource attribute — and rotates that id.\n const tagSession = () => context.setTags({ sessionId: posthog.get_session_id() }, 'logs');\n const removeSessionListener = posthog.onSessionId(tagSession);\n tagSession();\n unregisterPosthogProcessors = () => {\n removePosthogLog();\n removeSessionListener();\n };\n }),\n close: () =>\n Effect.sync(() => {\n unregisterPosthogProcessors?.();\n unregisterPosthogProcessors = undefined;\n }),\n enable: () => Effect.sync(() => posthog.opt_in_capturing()),\n disable: () => Effect.sync(() => posthog.opt_out_capturing()),\n identify: (distinctId, attributes, setOnceAttributes) => {\n posthog.identify(distinctId, attributes, setOnceAttributes);\n },\n alias: (distinctId, previousId) => {\n posthog.alias(distinctId, previousId);\n },\n setTags: (tags) => {\n posthog.register_for_session(tags);\n },\n get enabled(): boolean {\n return posthog.is_capturing();\n },\n apis: [\n {\n kind: 'events',\n isAvailable: () => Effect.succeed(true),\n captureEvent: (event, attributes) => {\n posthog.capture(event, attributes);\n },\n },\n {\n kind: 'errors',\n isAvailable: () => Effect.succeed(true),\n captureException: (error, attributes) => {\n posthog.captureException(error, attributes);\n },\n },\n {\n kind: 'ai',\n isAvailable: () => Effect.succeed(true),\n captureInference: (inference) => {\n posthog.capture(AI_GENERATION_EVENT, toAiGenerationProperties(inference));\n },\n captureTurn: (turn) => {\n posthog.capture(AI_TRACE_EVENT, toAiTraceProperties(turn));\n },\n captureToolCall: (toolCall) => {\n posthog.capture(AI_SPAN_EVENT, toAiSpanProperties(toolCall));\n },\n },\n {\n kind: 'support',\n isAvailable: () => Effect.succeed(logStore !== undefined),\n uploadLogs: async () => {\n if (logStore === undefined) {\n return undefined;\n }\n const ndjson = await logStore.export({ maxSize: feedbackLogMaxSize });\n if (ndjson.length === 0) {\n return undefined;\n }\n return await uploadLogs(feedbackLogsEndpoint, ndjson);\n },\n uploadNdjson: async (ndjson, kind) =>\n ndjson.length === 0 ? undefined : await uploadLogs(feedbackLogsEndpoint, ndjson, kind),\n sessionContext: () => {\n if (!posthog.__loaded) {\n return undefined;\n }\n try {\n return {\n distinctId: posthog.get_distinct_id(),\n widgetSessionId: widgetSessionId(),\n sessionId: posthog.get_session_id(),\n replayUrl: posthog.get_session_replay_url({ withTimestamp: true, timestampLookBack: 30 }),\n currentUrl: `${window.location.origin}${window.location.pathname}`,\n };\n } catch (err) {\n log.warn('PostHog session context unavailable', { err });\n return undefined;\n }\n },\n flushLogs: async (attributes) => {\n const destination = otelDestination(config);\n if (!destination) {\n return;\n }\n const ndjson = await logStore?.export({ maxSize: feedbackLogMaxSize });\n if (!ndjson || ndjson.length === 0) {\n return;\n }\n const { flushSupportLogs } = await import('./support-logs.ts');\n const count = await flushSupportLogs(ndjson, {\n destination,\n resourceAttributes: {\n 'service.name': serviceName,\n ...(release ? { 'service.version': release } : {}),\n ...(environment ? { 'deployment.environment': environment } : {}),\n },\n attributes,\n });\n log.info('support logs flushed to PostHog', { ...attributes, count });\n },\n },\n ],\n };\n },\n);\n","//\n// Copyright 2025 DXOS.org\n//\n\nexport * from './llm-analytics.ts';\nexport * from './extension.ts';\nexport * from './otel-destination.ts';\n","//\n// Copyright 2025 DXOS.org\n//\n\n// @import-as-namespace\n\nimport type * as Effect from 'effect/Effect';\n\nimport { type CleanupFn } from '@dxos/async';\nimport { type MetricObserver } from '@dxos/tracing';\n\nexport * from './extensions/index.ts';\n\n/**\n * Kind of observability extension.\n *\n * - errors: Error tracking (e.g., PostHog)\n * - events: Product usage event tracking (e.g., PostHog)\n * - support: Support tickets anchoring user reports and telemetry (e.g., PostHog)\n * - ai: Model inferences, tool calls, and turns (e.g., PostHog LLM analytics, OTel gen_ai)\n * - logs: Structured logging (e.g., OTEL)\n * - mcp: MCP server sessions and tool calls (e.g., PostHog)\n * - metrics: Metric data (e.g., OTEL)\n * - traces: Distributed tracing (e.g., OTEL)\n */\nexport type Kind = 'ai' | 'errors' | 'events' | 'support' | 'logs' | 'mcp' | 'metrics' | 'traces';\n\n/**\n * Base for every extension API variant. All kinds implement availability the same way.\n */\nexport type ExtensionApiBase<K extends Kind = Kind> = {\n kind: K;\n isAvailable(): Effect.Effect<boolean>;\n};\n\n/**\n * Instrument-level metadata, declared once by the first caller for a given metric name.\n * Units must be UCUM as OTel requires — `s`, `By`, `{thing}`.\n */\nexport type MetricMeta = { unit?: string; description?: string };\n\n/**\n * Metrics extension API (kind-specific methods only).\n */\nexport type Metrics = {\n gauge(name: string, value: number, tags?: Attributes, meta?: MetricMeta): void;\n increment(name: string, value?: number, tags?: Attributes, meta?: MetricMeta): void;\n distribution(name: string, value: number, tags?: Attributes, meta?: MetricMeta): void;\n /**\n * Registers a callback read once per export interval.\n * Prefer this over {@link Metrics.gauge} for any \"current value\" metric, since a pushed gauge\n * only lands in the export windows its producer happens to tick in.\n */\n observe(name: string, callback: MetricObserver, tags?: Attributes, meta?: MetricMeta): CleanupFn;\n};\n\n/**\n * Errors extension API (kind-specific methods only).\n */\nexport type Errors = {\n captureException(error: Error, attributes?: Attributes): void;\n};\n\n/**\n * Wider than {@link Attributes}: event properties carry structured values (message arrays,\n * nested objects), not just scalars.\n */\nexport type EventAttributes = Record<string, unknown>;\n\n/**\n * Events extension API (kind-specific methods only).\n */\nexport type Events = {\n captureEvent(event: string, attributes?: EventAttributes): void;\n};\n\n/**\n * One model call, already filtered by the capture policy and scrubbed (see `AiObservability`). Shaped\n * after the OTel GenAI conventions rather than any vendor's schema — an extension maps it onto\n * whatever its backend calls these things.\n */\nexport type Inference = {\n traceId: string;\n spanId: string;\n parentSpanId?: string;\n /** Provider span name, e.g. `LanguageModel.streamText`. */\n spanName: string;\n /** `gen_ai.provider.name` — the serving product, not the wire dialect. */\n provider?: string;\n model?: string;\n /** Conversation the call belongs to, when the call site named one. */\n sessionId?: string;\n /** Request parameters the provider reported (temperature, max_tokens, …). */\n parameters?: Record<string, unknown>;\n /** Excludes tokens served from the prompt cache; add {@link cacheReadTokens} for the total. */\n inputTokens?: number;\n outputTokens?: number;\n /** Absent rather than zero when the provider does not report prompt caching. */\n cacheReadTokens?: number;\n cacheWriteTokens?: number;\n /** Wall-clock duration, in seconds. */\n latency: number;\n streaming: boolean;\n /** Absent entirely when the capture policy denied it. */\n content?: GenerationContent;\n /** Exception class name only — a provider's message can embed request or response fragments. */\n errorClass?: string;\n};\n\nexport type GenerationContent = {\n /** Parsed prompt messages, or the raw string when {@link truncated} left it unparseable. */\n input?: unknown;\n output?: unknown;\n tools?: unknown;\n /** Some field above was cut to fit, so it is a fragment rather than the whole. */\n truncated?: boolean;\n};\n\n/** Fields a turn and a tool call share with an inference: identity, timing, and gated content. */\nexport type AiSpanBase = {\n traceId: string;\n spanId: string;\n parentSpanId?: string;\n /** For a tool call, the tool's name rather than the span's. */\n spanName: string;\n /** Conversation the span belongs to, when the call site named one. */\n sessionId?: string;\n /** Wall-clock duration, in seconds. */\n latency: number;\n /** Absent entirely when the capture policy denied it. */\n content?: AiSpanContent;\n /** Exception class name only, as on {@link Inference}. */\n errorClass?: string;\n};\n\nexport type AiSpanContent = {\n input?: unknown;\n output?: unknown;\n /** Some field above was cut to fit, so it is a fragment rather than the whole. */\n truncated?: boolean;\n};\n\n/**\n * One conversation turn: the unit a backend groups a turn's model calls and tool calls under (what\n * PostHog calls a trace). Its input is the user prompt and its output the messages the turn produced.\n */\nexport type Turn = AiSpanBase;\n\n/** One tool call inside a turn (what PostHog calls a span), with the arguments and the result. */\nexport type ToolCall = AiSpanBase;\n\n/**\n * AI extension API (kind-specific methods only).\n */\nexport type Ai = {\n captureInference(inference: Inference): void;\n captureTurn(turn: Turn): void;\n captureToolCall(toolCall: ToolCall): void;\n};\n\n/** The client name an MCP event carries when no request named its client; `@posthog/mcp` drops a falsy one. */\nexport const UNKNOWN_MCP_CLIENT = 'unknown';\n\n/** What every MCP event carries: the session it groups under and the client it came from. */\nexport type McpSession = {\n /** Groups the session's events; one server process is one session over a stdio transport. */\n sessionId: string;\n clientName?: string;\n clientVersion?: string;\n protocolVersion?: string;\n};\n\n/** MCP extension API (kind-specific methods only). */\nexport type Mcp = {\n /** A client connected successfully. */\n captureInitialize(session: McpSession): void;\n captureToolCall(\n call: McpSession & { toolName: string; parameters?: unknown; durationMs: number; isError: boolean },\n ): void;\n};\n\n/**\n * Support extension API (kind-specific methods only).\n */\nexport type SupportLogTags = { ticketId: string } | { reportId: string };\n\n/** What an uploaded NDJSON bundle is, which decides where it is filed in storage. */\nexport type SupportUploadKind = 'logs' | 'trajectory';\n\nexport type Support = {\n uploadLogs(): Promise<string | undefined>;\n /** Uploads an NDJSON bundle the caller built (e.g. an agent trajectory), returning its storage key. */\n uploadNdjson(ndjson: string, kind: SupportUploadKind): Promise<string | undefined>;\n sessionContext(): SupportSessionContext | undefined;\n flushLogs(attributes: SupportLogTags): Promise<void>;\n};\n\nexport type ExtensionApi =\n | (ExtensionApiBase<'errors'> & Errors)\n | (ExtensionApiBase<'events'> & Events)\n | (ExtensionApiBase<'support'> & Support)\n | (ExtensionApiBase<'ai'> & Ai)\n // TODO(wittjosiah): Direct logs api?\n | (ExtensionApiBase<'mcp'> & Mcp)\n | ExtensionApiBase<'logs'>\n | (ExtensionApiBase<'metrics'> & Metrics)\n // TODO(wittjosiah): Direct traces api?\n | ExtensionApiBase<'traces'>;\n\n/**\n * What a browser knows about its own telemetry session. Shaped after what posthog-js's own widget\n * sends.\n */\nexport type SupportSessionContext = {\n distinctId: string;\n /** Browser-minted id the widget API uses for access control on anonymous tickets. */\n widgetSessionId: string;\n sessionId?: string;\n replayUrl?: string;\n currentUrl?: string;\n};\n\n/**\n * Attributes to be attached to observability events.\n */\nexport type Attributes = Record<string, string | number | boolean | undefined>;\n\nexport type ExtensionContext = {\n setTags(tags: Attributes, kind?: Kind): void;\n};\n\n/**\n * Implementation of an observability extension API.\n */\nexport type Extension = {\n initialize?(context: ExtensionContext): Effect.Effect<void, Error>;\n close?(): Effect.Effect<void>;\n enable?(): Effect.Effect<void>;\n disable?(): Effect.Effect<void>;\n flush?(): Effect.Effect<void>;\n identify?(distinctId: string, attributes?: Attributes, setOnceAttributes?: Attributes): void;\n alias?(distinctId: string, previousId?: string): void;\n setTags?(tags: Record<string, string>, kind?: Kind): void;\n enabled: boolean;\n apis: ExtensionApi[];\n};\n"],"mappings":";;;;;;;;;;;;;;;;;AAeA,IAAa,sBAAsB;AACnC,IAAa,iBAAiB;AAC9B,IAAa,gBAAgB;;AAG7B,IAAa,uBAAuB,SAClC,eAAe,EACb,GAAG,eAAe,IAAI,EACxB,CAAC;;AAGH,IAAa,sBAAsB,aACjC,eAAe;CACb,GAAG,eAAe,QAAQ;CAC1B,eAAe;AACjB,CAAC;AAEH,IAAM,kBAAkB,UAAsE;CAC5F,cAAc,KAAK;CACnB,aAAa,KAAK;CAClB,eAAe,KAAK;CACpB,eAAe,KAAK;CACpB,gBAAgB,KAAK;CACrB,aAAa,KAAK;CAClB,iB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;OAChD,GAAI,cAAc,EAAE,0BAA0B,YAAY,IAAI,CAAC;MACjE;MACA;KACF,CAAC;KACD,IAAI,KAAK,mCAAmC;MAAE,GAAG;MAAY;KAAM,GAAA;MAAA,YAAA;MAAA,GAAA;MAAA,GAAA;MAAA,GAAA;KAAA,CAAC;IACtE;GACF;EACF;CACF;AACF,CACF;;;;;;;;;;;;;;;;;;;;;;AEjJA,IAAa,qBAAqB"}
|
|
1
|
+
{"version":3,"file":"chunk-ObservabilityExtension.mjs","names":["__dxlog_file"],"sources":["../../src/extensions/posthog/llm-analytics.ts","../../src/version.ts","../../src/extensions/posthog/before-send.ts","../../src/extensions/posthog/otel-destination.ts","../../src/extensions/posthog/extension.ts","../../src/extensions/posthog/index.ts","../../src/ObservabilityExtension.ts"],"sourcesContent":["//\n// Copyright 2026 DXOS.org\n//\n\nimport type * as ObservabilityExtension from '../../ObservabilityExtension.ts';\n\n/**\n * PostHog's LLM analytics schema. Three events with `$ai_*` properties are what the product reads:\n * `$ai_trace` is the top-level unit (a conversation turn here), `$ai_span` a step inside it (a tool\n * call), `$ai_generation` a model call. They are linked by `$ai_trace_id`, and a span or generation\n * names its parent with `$ai_parent_id`.\n *\n * `$ai_input_tokens` is the uncached count, which is what PostHog expects alongside the two cache\n * figures — together they price the call, and their ratio is the prompt-cache hit rate.\n */\nexport const AI_GENERATION_EVENT = '$ai_generation';\nexport const AI_TRACE_EVENT = '$ai_trace';\nexport const AI_SPAN_EVENT = '$ai_span';\n\n/** `$ai_trace`: the turn, carrying the prompt and the messages it produced as its states. */\nexport const toAiTraceProperties = (turn: ObservabilityExtension.Turn): Record<string, unknown> =>\n stripUndefined({\n ...spanProperties(turn),\n });\n\n/** `$ai_span` of type `tool`: one tool call, carrying its arguments and result as its states. */\nexport const toAiSpanProperties = (toolCall: ObservabilityExtension.ToolCall): Record<string, unknown> =>\n stripUndefined({\n ...spanProperties(toolCall),\n $ai_span_type: 'tool',\n });\n\nconst spanProperties = (span: ObservabilityExtension.AiSpanBase): Record<string, unknown> => ({\n $ai_trace_id: span.traceId,\n $ai_span_id: span.spanId,\n $ai_parent_id: span.parentSpanId,\n $ai_span_name: span.spanName,\n $ai_session_id: span.sessionId,\n $ai_latency: span.latency,\n $ai_input_state: span.content?.input,\n $ai_output_state: span.content?.output,\n $ai_content_truncated: span.content?.truncated,\n $ai_is_error: span.errorClass ? true : undefined,\n $ai_error: span.errorClass,\n});\n\nexport const toAiGenerationProperties = (inference: ObservabilityExtension.Inference): Record<string, unknown> =>\n stripUndefined({\n $ai_trace_id: inference.traceId,\n $ai_span_id: inference.spanId,\n $ai_parent_id: inference.parentSpanId,\n $ai_span_name: inference.spanName,\n $ai_provider: inference.provider,\n $ai_model: inference.model,\n $ai_session_id: inference.sessionId,\n $ai_model_parameters: inference.parameters,\n $ai_input_tokens: inference.inputTokens,\n $ai_output_tokens: inference.outputTokens,\n $ai_cache_read_input_tokens: inference.cacheReadTokens,\n $ai_cache_creation_input_tokens: inference.cacheWriteTokens,\n $ai_latency: inference.latency,\n $ai_stream: inference.streaming,\n $ai_input: inference.content?.input,\n $ai_output_choices: inference.content?.output,\n $ai_tools: inference.content?.tools,\n $ai_content_truncated: inference.content?.truncated,\n $ai_is_error: inference.errorClass ? true : undefined,\n $ai_error: inference.errorClass,\n });\n\nconst stripUndefined = (properties: Record<string, unknown>): Record<string, unknown> =>\n Object.fromEntries(Object.entries(properties).filter(([, value]) => value !== undefined));\n","//\n// Copyright 2026 DXOS.org\n//\n\nexport const DXOS_VERSION = '0.17.0';\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport { type BeforeSendFn, type Properties } from 'posthog-js';\n\n/**\n * Browser-raised errors with no stack and no effect on the user: a ResizeObserver callback that resized an element\n * mid-delivery is reported this way, and the browser delivers the skipped notifications on the next frame.\n */\nconst BENIGN_EXCEPTIONS = [/^ResizeObserver loop/];\n\n/** Drops `$exception` events whose every exception is benign. */\nexport const dropBenignExceptions: BeforeSendFn = (capture) => {\n if (capture?.event !== '$exception') {\n return capture;\n }\n\n const exceptions: { value?: unknown }[] = capture.properties.$exception_list ?? [];\n const benign =\n exceptions.length > 0 &&\n exceptions.every(\n ({ value }) => typeof value === 'string' && BENIGN_EXCEPTIONS.some((pattern) => pattern.test(value)),\n );\n return benign ? null : capture;\n};\n\nconst INVITATION_PARAM = 'spaceInvitationCode';\n\nconst redactUrl = (value: string): string => {\n if (!value.includes('?')) {\n return value;\n }\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n return value;\n }\n if (!url.searchParams.has(INVITATION_PARAM)) {\n return value;\n }\n url.searchParams.delete(INVITATION_PARAM);\n return url.toString();\n};\n\n/** Redacts every string in a property value, including person properties nested as `properties.$set`. */\nconst redactValue = (value: unknown): unknown => {\n if (typeof value === 'string') {\n return redactUrl(value);\n }\n if (Array.isArray(value)) {\n return value.map(redactValue);\n }\n if (value !== null && typeof value === 'object') {\n return redactProperties(value);\n }\n return value;\n};\n\nconst redactProperties = (properties: object): Properties =>\n Object.fromEntries(Object.entries(properties).map(([key, value]) => [key, redactValue(value)]));\n\nexport const redactInvitationCodes: BeforeSendFn = (capture) =>\n capture && {\n ...capture,\n properties: redactProperties(capture.properties),\n ...(capture.$set && { $set: redactProperties(capture.$set) }),\n ...(capture.$set_once && { $set_once: redactProperties(capture.$set_once) }),\n };\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport { type Config, getEnvString } from '@dxos/config';\nimport { log } from '@dxos/log';\n\nimport { type OtelDestination } from '../otel/otel.ts';\n\n/** PostHog serves OTLP under `/i` of the same host it ingests product analytics on, not at the root. */\nconst OTLP_PATH_PREFIX = '/i';\n\n/**\n * PostHog as an OTLP backend, authenticated with the public `phc_` project token rather than a\n * secret, so the browser can post to it directly.\n */\nexport const otelDestination = (config: Config): OtelDestination | undefined => {\n const host = getEnvString(config, 'DX_POSTHOG_API_HOST');\n const apiKey = getEnvString(config, 'DX_POSTHOG_API_KEY');\n if (!host) {\n return undefined;\n }\n if (!apiKey) {\n log.info('DX_POSTHOG_API_HOST is set without DX_POSTHOG_API_KEY; skipping PostHog OTLP export');\n return undefined;\n }\n\n return {\n endpoint: `${host.replace(/\\/$/, '')}${OTLP_PATH_PREFIX}`,\n headers: { Authorization: `Bearer ${apiKey}` },\n };\n};\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Effect from 'effect/Effect';\nimport { type PostHogConfig } from 'posthog-js';\n\nimport { type Config, getEnvString } from '@dxos/config';\nimport { log } from '@dxos/log';\nimport { type IdbLogStore } from '@dxos/log-store-idb';\nimport { gzip, isNode } from '@dxos/util';\n\nimport * as ObservabilityExtension from '../../ObservabilityExtension.ts';\nimport { DXOS_VERSION } from '../../version.ts';\nimport { stubExtension } from '../stub.ts';\nimport { dropBenignExceptions, redactInvitationCodes } from './before-send.ts';\nimport {\n AI_GENERATION_EVENT,\n AI_SPAN_EVENT,\n AI_TRACE_EVENT,\n toAiGenerationProperties,\n toAiSpanProperties,\n toAiTraceProperties,\n} from './llm-analytics.ts';\nimport { otelDestination } from './otel-destination.ts';\n\nconst WIDGET_SESSION_STORAGE_KEY = 'dxos.support.widgetSessionId';\n\nconst widgetSessionId = (): string => {\n try {\n const existing = localStorage.getItem(WIDGET_SESSION_STORAGE_KEY);\n if (existing) {\n return existing;\n }\n const minted = crypto.randomUUID();\n localStorage.setItem(WIDGET_SESSION_STORAGE_KEY, minted);\n return minted;\n } catch {\n return crypto.randomUUID();\n }\n};\n\nexport type ExtensionsOptions = {\n config: Config;\n /** Release identifier, e.g. `composer@0.8.3`. */\n release?: string;\n /** Deployment environment, e.g. `production` or `staging`. */\n environment?: string;\n serviceName?: string;\n posthog?: Partial<PostHogConfig>;\n /**\n * Shared persistent log store for debug log dumps.\n * The owning app is expected to register `logStore.processor` with `log` itself —\n * this extension only consumes the buffered logs (via `export()`).\n */\n logStore?: IdbLogStore;\n /**\n * Maximum byte size passed to `logStore.export()` when uploading feedback logs.\n * Should match the upload limit enforced by the server receiving the logs.\n * When omitted the full store is exported without trimming.\n */\n feedbackLogMaxSize?: number;\n /**\n * Where to POST feedback logs, defaulting to {@link DEFAULT_FEEDBACK_LOGS_ENDPOINT}.\n * A native build serves its frontend from its own origin and has no such route there, so it must\n * pass the absolute URL of a deployment that does.\n */\n feedbackLogsEndpoint?: string;\n /**\n * Holds session recording back until this settles, so the recorder's DOM snapshot and compression\n * stay off the main thread during app startup. Ignored when `posthog.disable_session_recording` is set.\n */\n sessionRecordingStart?: Effect.Effect<void>;\n /** What the `posthog-node` transport needs; a browser host has posthog-js and reads none of it. */\n node?: NodeOptions;\n};\n\nexport type NodeOptions = {\n /** Pins the project instead of reading `DX_POSTHOG_API_KEY`. */\n apiKey?: string;\n /** Ingestion host — a region, or a proxy on your own domain. */\n host?: string;\n /** Attribution for events captured before `identify`, since there is no ambient person. */\n distinctId?: string;\n /** Which MCP server this host is, stamped on every `$mcp_*` event. */\n mcpServer?: { name: string; version: string };\n};\n\n/** Same-origin route of the web deployment, which proxies the upload to object storage. */\nconst DEFAULT_FEEDBACK_LOGS_ENDPOINT = '/api/feedback-logs';\n\n/** Upload serialized logs, gzipped, to the feedback-logs endpoint. Returns the R2 key on success. */\nconst uploadLogs = async (\n endpoint: string,\n ndjson: string,\n kind: ObservabilityExtension.SupportUploadKind = 'logs',\n): Promise<string | undefined> => {\n try {\n // The endpoint may be relative (same-origin) or absolute (native builds), so append rather than parse.\n const url = kind === 'logs' ? endpoint : `${endpoint}${endpoint.includes('?') ? '&' : '?'}kind=${kind}`;\n const response = await fetch(url, {\n method: 'POST',\n headers: { 'Content-Type': 'application/gzip' },\n body: await gzip(ndjson),\n });\n if (!response.ok) {\n log.warn('feedback log upload failed', { endpoint, status: response.status });\n return undefined;\n }\n const { key } = await response.json();\n return key;\n } catch (err) {\n log.warn('feedback log upload error', { endpoint, error: err });\n return undefined;\n }\n};\n\n/**\n * Class on an iframe that session replay records with its content. Only for a same-origin iframe the\n * recorder can read: it never releases an opaque one removed with an ancestor, which replays empty anyway.\n */\nexport const REPLAY_IFRAME_CLASS = 'dx-replay-iframe';\n\n/** Create a PostHog-backed observability extension for events, errors, and support tickets. */\nexport const extensions: (options: ExtensionsOptions) => Effect.Effect<ObservabilityExtension.Extension> = Effect.fn(\n function* ({\n config,\n release,\n environment,\n serviceName = 'app',\n posthog: posthogConfig,\n logStore,\n feedbackLogMaxSize,\n feedbackLogsEndpoint = DEFAULT_FEEDBACK_LOGS_ENDPOINT,\n sessionRecordingStart,\n node,\n }) {\n if (isNode()) {\n const { extensions: nodeExtensions } = yield* Effect.promise(() => import('#posthog-transport'));\n return yield* nodeExtensions({ config, release, environment, node });\n }\n if (typeof window === 'undefined') {\n log('PostHog is being stubbed because it is running in a worker.');\n return stubExtension;\n }\n\n const apiKey = getEnvString(config, 'DX_POSTHOG_API_KEY');\n const api_host = getEnvString(config, 'DX_POSTHOG_API_HOST');\n if (!apiKey || !api_host) {\n log.info('Missing POSTHOG_API_KEY or POSTHOG_API_HOST');\n return stubExtension;\n }\n\n const { default: posthog } = yield* Effect.promise(() => import('posthog-js'));\n const { logProcessor } = yield* Effect.promise(() => import('./log-processor.ts'));\n let unregisterPosthogProcessors: (() => void) | undefined;\n const recordingStart = posthogConfig?.disable_session_recording ? undefined : sessionRecordingStart;\n\n return {\n initialize: (context) =>\n Effect.gen(function* () {\n // https://posthog.com/docs/libraries/js/config\n posthog.init(apiKey, {\n api_host,\n mask_all_text: true,\n capture_exceptions: true,\n // Cookies stay scoped to the exact host; the cross-subdomain dmn_chk_* probe fails on public-suffix hosts (e.g. *.pages.dev) and spams the console.\n cross_subdomain_cookie: false,\n ...posthogConfig,\n session_recording: {\n // The recorder never releases a cross-origin iframe removed with an ancestor, and that\n // iframe pins the whole detached tree; children of a blocked element are never recorded.\n // `<body>` is exempt, or a hidden iframe appended to it would blank the whole replay.\n blockSelector: `:not(body):has(> iframe:not(.${REPLAY_IFRAME_CLASS}))`,\n ...posthogConfig?.session_recording,\n },\n before_send: [dropBenignExceptions, redactInvitationCodes, ...[posthogConfig?.before_send ?? []].flat()],\n ...(recordingStart ? { disable_session_recording: true } : {}),\n });\n if (recordingStart) {\n // Without an override this only lifts the local block; remote replay settings and sampling still apply.\n yield* Effect.forkDetach(\n recordingStart.pipe(Effect.andThen(Effect.sync(() => posthog.startSessionRecording()))),\n );\n }\n posthog.register({\n sdkVersion: DXOS_VERSION,\n ...(release ? { release } : {}),\n ...(environment ? { environment } : {}),\n });\n unregisterPosthogProcessors?.();\n const removePosthogLog = log.addProcessor(logProcessor);\n // PostHog joins a log record to its session replay on a log attribute literally named\n // `sessionId` — not the OTel `session.id` resource attribute — and rotates that id.\n const tagSession = () => context.setTags({ sessionId: posthog.get_session_id() }, 'logs');\n const removeSessionListener = posthog.onSessionId(tagSession);\n tagSession();\n unregisterPosthogProcessors = () => {\n removePosthogLog();\n removeSessionListener();\n };\n }),\n close: () =>\n Effect.sync(() => {\n unregisterPosthogProcessors?.();\n unregisterPosthogProcessors = undefined;\n }),\n enable: () => Effect.sync(() => posthog.opt_in_capturing()),\n disable: () => Effect.sync(() => posthog.opt_out_capturing()),\n identify: (distinctId, attributes, setOnceAttributes) => {\n posthog.identify(distinctId, attributes, setOnceAttributes);\n },\n alias: (distinctId, previousId) => {\n posthog.alias(distinctId, previousId);\n },\n setTags: (tags) => {\n posthog.register_for_session(tags);\n },\n get enabled(): boolean {\n return posthog.is_capturing();\n },\n apis: [\n {\n kind: 'events',\n isAvailable: () => Effect.succeed(true),\n captureEvent: (event, attributes) => {\n posthog.capture(event, attributes);\n },\n },\n {\n kind: 'errors',\n isAvailable: () => Effect.succeed(true),\n captureException: (error, attributes) => {\n posthog.captureException(error, attributes);\n },\n },\n {\n kind: 'ai',\n isAvailable: () => Effect.succeed(true),\n captureInference: (inference) => {\n posthog.capture(AI_GENERATION_EVENT, toAiGenerationProperties(inference));\n },\n captureTurn: (turn) => {\n posthog.capture(AI_TRACE_EVENT, toAiTraceProperties(turn));\n },\n captureToolCall: (toolCall) => {\n posthog.capture(AI_SPAN_EVENT, toAiSpanProperties(toolCall));\n },\n },\n {\n kind: 'support',\n isAvailable: () => Effect.succeed(logStore !== undefined),\n uploadLogs: async () => {\n if (logStore === undefined) {\n return undefined;\n }\n const ndjson = await logStore.export({ maxSize: feedbackLogMaxSize });\n if (ndjson.length === 0) {\n return undefined;\n }\n return await uploadLogs(feedbackLogsEndpoint, ndjson);\n },\n uploadNdjson: async (ndjson, kind) =>\n ndjson.length === 0 ? undefined : await uploadLogs(feedbackLogsEndpoint, ndjson, kind),\n sessionContext: () => {\n if (!posthog.__loaded) {\n return undefined;\n }\n try {\n return {\n distinctId: posthog.get_distinct_id(),\n widgetSessionId: widgetSessionId(),\n sessionId: posthog.get_session_id(),\n replayUrl: posthog.get_session_replay_url({ withTimestamp: true, timestampLookBack: 30 }),\n currentUrl: `${window.location.origin}${window.location.pathname}`,\n };\n } catch (err) {\n log.warn('PostHog session context unavailable', { err });\n return undefined;\n }\n },\n flushLogs: async (attributes) => {\n const destination = otelDestination(config);\n if (!destination) {\n return;\n }\n const ndjson = await logStore?.export({ maxSize: feedbackLogMaxSize });\n if (!ndjson || ndjson.length === 0) {\n return;\n }\n const { flushSupportLogs } = await import('./support-logs.ts');\n const count = await flushSupportLogs(ndjson, {\n destination,\n resourceAttributes: {\n 'service.name': serviceName,\n ...(release ? { 'service.version': release } : {}),\n ...(environment ? { 'deployment.environment': environment } : {}),\n },\n attributes,\n });\n log.info('support logs flushed to PostHog', { ...attributes, count });\n },\n },\n ],\n };\n },\n);\n","//\n// Copyright 2025 DXOS.org\n//\n\nexport * from './llm-analytics.ts';\nexport * from './extension.ts';\nexport * from './otel-destination.ts';\n","//\n// Copyright 2025 DXOS.org\n//\n\n// @import-as-namespace\n\nimport type * as Effect from 'effect/Effect';\n\nimport { type CleanupFn } from '@dxos/async';\nimport { type MetricObserver } from '@dxos/tracing';\n\nexport * from './extensions/index.ts';\n\n/**\n * Kind of observability extension.\n *\n * - errors: Error tracking (e.g., PostHog)\n * - events: Product usage event tracking (e.g., PostHog)\n * - support: Support tickets anchoring user reports and telemetry (e.g., PostHog)\n * - ai: Model inferences, tool calls, and turns (e.g., PostHog LLM analytics, OTel gen_ai)\n * - logs: Structured logging (e.g., OTEL)\n * - mcp: MCP server sessions and tool calls (e.g., PostHog)\n * - metrics: Metric data (e.g., OTEL)\n * - traces: Distributed tracing (e.g., OTEL)\n */\nexport type Kind = 'ai' | 'errors' | 'events' | 'support' | 'logs' | 'mcp' | 'metrics' | 'traces';\n\n/**\n * Base for every extension API variant. All kinds implement availability the same way.\n */\nexport type ExtensionApiBase<K extends Kind = Kind> = {\n kind: K;\n isAvailable(): Effect.Effect<boolean>;\n};\n\n/**\n * Instrument-level metadata, declared once by the first caller for a given metric name.\n * Units must be UCUM as OTel requires — `s`, `By`, `{thing}`.\n */\nexport type MetricMeta = { unit?: string; description?: string };\n\n/**\n * Metrics extension API (kind-specific methods only).\n */\nexport type Metrics = {\n gauge(name: string, value: number, tags?: Attributes, meta?: MetricMeta): void;\n increment(name: string, value?: number, tags?: Attributes, meta?: MetricMeta): void;\n distribution(name: string, value: number, tags?: Attributes, meta?: MetricMeta): void;\n /**\n * Registers a callback read once per export interval.\n * Prefer this over {@link Metrics.gauge} for any \"current value\" metric, since a pushed gauge\n * only lands in the export windows its producer happens to tick in.\n */\n observe(name: string, callback: MetricObserver, tags?: Attributes, meta?: MetricMeta): CleanupFn;\n};\n\n/**\n * Errors extension API (kind-specific methods only).\n */\nexport type Errors = {\n captureException(error: Error, attributes?: Attributes): void;\n};\n\n/**\n * Wider than {@link Attributes}: event properties carry structured values (message arrays,\n * nested objects), not just scalars.\n */\nexport type EventAttributes = Record<string, unknown>;\n\n/**\n * Events extension API (kind-specific methods only).\n */\nexport type Events = {\n captureEvent(event: string, attributes?: EventAttributes): void;\n};\n\n/**\n * One model call, already filtered by the capture policy and scrubbed (see `AiObservability`). Shaped\n * after the OTel GenAI conventions rather than any vendor's schema — an extension maps it onto\n * whatever its backend calls these things.\n */\nexport type Inference = {\n traceId: string;\n spanId: string;\n parentSpanId?: string;\n /** Provider span name, e.g. `LanguageModel.streamText`. */\n spanName: string;\n /** `gen_ai.provider.name` — the serving product, not the wire dialect. */\n provider?: string;\n model?: string;\n /** Conversation the call belongs to, when the call site named one. */\n sessionId?: string;\n /** Request parameters the provider reported (temperature, max_tokens, …). */\n parameters?: Record<string, unknown>;\n /** Excludes tokens served from the prompt cache; add {@link cacheReadTokens} for the total. */\n inputTokens?: number;\n outputTokens?: number;\n /** Absent rather than zero when the provider does not report prompt caching. */\n cacheReadTokens?: number;\n cacheWriteTokens?: number;\n /** Wall-clock duration, in seconds. */\n latency: number;\n streaming: boolean;\n /** Absent entirely when the capture policy denied it. */\n content?: GenerationContent;\n /** Exception class name only — a provider's message can embed request or response fragments. */\n errorClass?: string;\n};\n\nexport type GenerationContent = {\n /** Parsed prompt messages, or the raw string when {@link truncated} left it unparseable. */\n input?: unknown;\n output?: unknown;\n tools?: unknown;\n /** Some field above was cut to fit, so it is a fragment rather than the whole. */\n truncated?: boolean;\n};\n\n/** Fields a turn and a tool call share with an inference: identity, timing, and gated content. */\nexport type AiSpanBase = {\n traceId: string;\n spanId: string;\n parentSpanId?: string;\n /** For a tool call, the tool's name rather than the span's. */\n spanName: string;\n /** Conversation the span belongs to, when the call site named one. */\n sessionId?: string;\n /** Wall-clock duration, in seconds. */\n latency: number;\n /** Absent entirely when the capture policy denied it. */\n content?: AiSpanContent;\n /** Exception class name only, as on {@link Inference}. */\n errorClass?: string;\n};\n\nexport type AiSpanContent = {\n input?: unknown;\n output?: unknown;\n /** Some field above was cut to fit, so it is a fragment rather than the whole. */\n truncated?: boolean;\n};\n\n/**\n * One conversation turn: the unit a backend groups a turn's model calls and tool calls under (what\n * PostHog calls a trace). Its input is the user prompt and its output the messages the turn produced.\n */\nexport type Turn = AiSpanBase;\n\n/** One tool call inside a turn (what PostHog calls a span), with the arguments and the result. */\nexport type ToolCall = AiSpanBase;\n\n/**\n * AI extension API (kind-specific methods only).\n */\nexport type Ai = {\n captureInference(inference: Inference): void;\n captureTurn(turn: Turn): void;\n captureToolCall(toolCall: ToolCall): void;\n};\n\n/** The client name an MCP event carries when no request named its client; `@posthog/mcp` drops a falsy one. */\nexport const UNKNOWN_MCP_CLIENT = 'unknown';\n\n/** What every MCP event carries: the session it groups under and the client it came from. */\nexport type McpSession = {\n /** Groups the session's events; one server process is one session over a stdio transport. */\n sessionId: string;\n clientName?: string;\n clientVersion?: string;\n protocolVersion?: string;\n};\n\n/** MCP extension API (kind-specific methods only). */\nexport type Mcp = {\n /** A client connected successfully. */\n captureInitialize(session: McpSession): void;\n captureToolCall(\n call: McpSession & { toolName: string; parameters?: unknown; durationMs: number; isError: boolean },\n ): void;\n};\n\n/**\n * Support extension API (kind-specific methods only).\n */\nexport type SupportLogTags = { ticketId: string } | { reportId: string };\n\n/** What an uploaded NDJSON bundle is, which decides where it is filed in storage. */\nexport type SupportUploadKind = 'logs' | 'trajectory';\n\nexport type Support = {\n uploadLogs(): Promise<string | undefined>;\n /** Uploads an NDJSON bundle the caller built (e.g. an agent trajectory), returning its storage key. */\n uploadNdjson(ndjson: string, kind: SupportUploadKind): Promise<string | undefined>;\n sessionContext(): SupportSessionContext | undefined;\n flushLogs(attributes: SupportLogTags): Promise<void>;\n};\n\nexport type ExtensionApi =\n | (ExtensionApiBase<'errors'> & Errors)\n | (ExtensionApiBase<'events'> & Events)\n | (ExtensionApiBase<'support'> & Support)\n | (ExtensionApiBase<'ai'> & Ai)\n // TODO(wittjosiah): Direct logs api?\n | (ExtensionApiBase<'mcp'> & Mcp)\n | ExtensionApiBase<'logs'>\n | (ExtensionApiBase<'metrics'> & Metrics)\n // TODO(wittjosiah): Direct traces api?\n | ExtensionApiBase<'traces'>;\n\n/**\n * What a browser knows about its own telemetry session. Shaped after what posthog-js's own widget\n * sends.\n */\nexport type SupportSessionContext = {\n distinctId: string;\n /** Browser-minted id the widget API uses for access control on anonymous tickets. */\n widgetSessionId: string;\n sessionId?: string;\n replayUrl?: string;\n currentUrl?: string;\n};\n\n/**\n * Attributes to be attached to observability events.\n */\nexport type Attributes = Record<string, string | number | boolean | undefined>;\n\nexport type ExtensionContext = {\n setTags(tags: Attributes, kind?: Kind): void;\n};\n\n/**\n * Implementation of an observability extension API.\n */\nexport type Extension = {\n initialize?(context: ExtensionContext): Effect.Effect<void, Error>;\n close?(): Effect.Effect<void>;\n enable?(): Effect.Effect<void>;\n disable?(): Effect.Effect<void>;\n flush?(): Effect.Effect<void>;\n identify?(distinctId: string, attributes?: Attributes, setOnceAttributes?: Attributes): void;\n alias?(distinctId: string, previousId?: string): void;\n setTags?(tags: Record<string, string>, kind?: Kind): void;\n enabled: boolean;\n apis: ExtensionApi[];\n};\n"],"mappings":";;;;;;;;;;;;;;;;;AAeA,IAAa,sBAAsB;AACnC,IAAa,iBAAiB;AAC9B,IAAa,gBAAgB;;AAG7B,IAAa,uBAAuB,SAClC,eAAe,EACb,GAAG,eAAe,IAAI,EACxB,CAAC;;AAGH,IAAa,sBAAsB,aACjC,eAAe;CACb,GAAG,eAAe,QAAQ;CAC1B,eAAe;AACjB,CAAC;AAEH,IAAM,kBAAkB,UAAsE;CAC5F,cAAc,KAAK;CACnB,aAAa,KAAK;CAClB,eAAe,KAAK;CACpB,eAAe,KAAK;CACpB,gBAAgB,KAAK;CACrB,aAAa,KAAK;CAClB,iBAAiB,KAAK,SAAS;CAC/B,kBAAkB,KAAK,SAAS;CAChC,uBAAuB,KAAK,SAAS;CACrC,cAAc,KAAK,aAAa,OAAO,KAAA;CACvC,WAAW,KAAK;AAClB;AAEA,IAAa,4BAA4B,cACvC,eAAe;CACb,cAAc,UAAU;CACxB,aAAa,UAAU;CACvB,eAAe,UAAU;CACzB,eAAe,UAAU;CACzB,cAAc,UAAU;CACxB,WAAW,UAAU;CACrB,gBAAgB,UAAU;CAC1B,sBAAsB,UAAU;CAChC,kBAAkB,UAAU;CAC5B,mBAAmB,UAAU;CAC7B,6BAA6B,UAAU;CACvC,iCAAiC,UAAU;CAC3C,aAAa,UAAU;CACvB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AAuC,EAAE,IAAI,GAAA;OAAA,YAAA;OAAA,GAAA;OAAA,GAAA;OAAA,GAAA;MAAA,CAAC;MACvD;KACF;IACF;IACA,WAAW,OAAO,eAAe;KAC/B,MAAM,cAAc,gBAAgB,MAAM;KAC1C,IAAI,CAAC,aACH;KAEF,MAAM,SAAS,MAAM,UAAU,OAAO,EAAE,SAAS,mBAAmB,CAAC;KACrE,IAAI,CAAC,UAAU,OAAO,WAAW,GAC/B;KAEF,MAAM,EAAE,qBAAqB,MAAM,OAAO;KAC1C,MAAM,QAAQ,MAAM,iBAAiB,QAAQ;MAC3C;MACA,oBAAoB;OAClB,gBAAgB;OAChB,GAAI,UAAU,EAAE,mBAAmB,QAAQ,IAAI,CAAC;OAChD,GAAI,cAAc,EAAE,0BAA0B,YAAY,IAAI,CAAC;MACjE;MACA;KACF,CAAC;KACD,IAAI,KAAK,mCAAmC;MAAE,GAAG;MAAY;KAAM,GAAA;MAAA,YAAA;MAAA,GAAA;MAAA,GAAA;MAAA,GAAA;KAAA,CAAC;IACtE;GACF;EACF;CACF;AACF,CACF;;;;;;;;;;;;;;;;;;;;;;AEjJA,IAAa,qBAAqB"}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { t as __exportAll } from "./chunk-rolldown-runtime.mjs";
|
|
2
|
+
//#region src/extensions/otel/OtelProxy.ts
|
|
3
|
+
var OtelProxy_exports = /* @__PURE__ */ __exportAll({
|
|
4
|
+
PREFIX: () => PREFIX,
|
|
5
|
+
handle: () => handle
|
|
6
|
+
});
|
|
7
|
+
/** The route a client's OTel exporter posts to on the deployment that serves it. */
|
|
8
|
+
var PREFIX = "/api/otel";
|
|
9
|
+
var SIGNALS = /* @__PURE__ */ new Set([
|
|
10
|
+
"/v1/traces",
|
|
11
|
+
"/v1/logs",
|
|
12
|
+
"/v1/metrics"
|
|
13
|
+
]);
|
|
14
|
+
/** A POST always carries `Origin`, so a missing one is refused. */
|
|
15
|
+
var isAllowedOrigin = (request, origin, extraOrigins) => origin !== null && (origin === new URL(request.url).origin || extraOrigins?.has(origin) === true);
|
|
16
|
+
var corsHeaders = (request, origin, extraOrigins) => ({
|
|
17
|
+
"Access-Control-Allow-Origin": isAllowedOrigin(request, origin, extraOrigins) ? origin ?? "" : "",
|
|
18
|
+
"Access-Control-Allow-Methods": "POST, OPTIONS",
|
|
19
|
+
"Access-Control-Allow-Headers": "Content-Type, Content-Encoding",
|
|
20
|
+
"Vary": "Origin"
|
|
21
|
+
});
|
|
22
|
+
/**
|
|
23
|
+
* Forwards an OTLP request on `/api/otel/v1/{traces,logs,metrics}` to PostHog with the project token.
|
|
24
|
+
* Returns `undefined` for any other path, so the caller can route it elsewhere.
|
|
25
|
+
*/
|
|
26
|
+
var handle = (request, options) => {
|
|
27
|
+
const { pathname } = new URL(request.url);
|
|
28
|
+
const signal = pathname.startsWith(`/api/otel/`) ? pathname.slice(9) : void 0;
|
|
29
|
+
return signal && SIGNALS.has(signal) ? forward(request, options, signal) : void 0;
|
|
30
|
+
};
|
|
31
|
+
var forward = async (request, { url, token, extraOrigins, maxBodySize }, signal) => {
|
|
32
|
+
const origin = request.headers.get("Origin");
|
|
33
|
+
const cors = corsHeaders(request, origin, extraOrigins);
|
|
34
|
+
if (request.method === "OPTIONS") return new Response(null, {
|
|
35
|
+
status: 204,
|
|
36
|
+
headers: cors
|
|
37
|
+
});
|
|
38
|
+
if (request.method !== "POST") return new Response("Method not allowed", {
|
|
39
|
+
status: 405,
|
|
40
|
+
headers: cors
|
|
41
|
+
});
|
|
42
|
+
if (!isAllowedOrigin(request, origin, extraOrigins)) return new Response("Forbidden", {
|
|
43
|
+
status: 403,
|
|
44
|
+
headers: cors
|
|
45
|
+
});
|
|
46
|
+
if (!url || !token) return new Response("OTel proxy not configured", {
|
|
47
|
+
status: 503,
|
|
48
|
+
headers: cors
|
|
49
|
+
});
|
|
50
|
+
if (!request.body) return new Response("Empty body", {
|
|
51
|
+
status: 400,
|
|
52
|
+
headers: cors
|
|
53
|
+
});
|
|
54
|
+
const headers = {
|
|
55
|
+
"Content-Type": request.headers.get("Content-Type") ?? "application/json",
|
|
56
|
+
"Authorization": `Bearer ${token}`
|
|
57
|
+
};
|
|
58
|
+
for (const name of ["Content-Encoding", "Content-Length"]) {
|
|
59
|
+
const value = request.headers.get(name);
|
|
60
|
+
if (value) headers[name] = value;
|
|
61
|
+
}
|
|
62
|
+
let size = 0;
|
|
63
|
+
let tooLarge = false;
|
|
64
|
+
const { readable, writable } = new TransformStream({ transform: (chunk, controller) => {
|
|
65
|
+
size += chunk.byteLength;
|
|
66
|
+
if (size > maxBodySize) {
|
|
67
|
+
tooLarge = true;
|
|
68
|
+
controller.error(/* @__PURE__ */ new Error("Payload too large"));
|
|
69
|
+
} else controller.enqueue(chunk);
|
|
70
|
+
} });
|
|
71
|
+
const piped = request.body.pipeTo(writable).catch(() => {});
|
|
72
|
+
let upstream;
|
|
73
|
+
try {
|
|
74
|
+
upstream = await fetch(`${url.replace(/\/$/, "")}${signal}`, {
|
|
75
|
+
method: "POST",
|
|
76
|
+
headers,
|
|
77
|
+
body: readable
|
|
78
|
+
});
|
|
79
|
+
} catch {
|
|
80
|
+
await readable.cancel().catch(() => {});
|
|
81
|
+
}
|
|
82
|
+
await piped;
|
|
83
|
+
if (tooLarge) return new Response("Payload too large", {
|
|
84
|
+
status: 413,
|
|
85
|
+
headers: cors
|
|
86
|
+
});
|
|
87
|
+
if (!upstream) return new Response("Bad gateway", {
|
|
88
|
+
status: 502,
|
|
89
|
+
headers: cors
|
|
90
|
+
});
|
|
91
|
+
return new Response(upstream.body, {
|
|
92
|
+
status: upstream.status,
|
|
93
|
+
headers: {
|
|
94
|
+
"Content-Type": upstream.headers.get("Content-Type") ?? "application/json",
|
|
95
|
+
...cors
|
|
96
|
+
}
|
|
97
|
+
});
|
|
98
|
+
};
|
|
99
|
+
//#endregion
|
|
100
|
+
export { PREFIX as n, handle as r, OtelProxy_exports as t };
|
|
101
|
+
|
|
102
|
+
//# sourceMappingURL=chunk-OtelProxy.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"chunk-OtelProxy.mjs","names":[],"sources":["../../src/extensions/otel/OtelProxy.ts"],"sourcesContent":["//\n// Copyright 2026 DXOS.org\n//\n\n// @import-as-namespace\n\n// Cloudflare Workers import this through its own subpath, so it uses only the Fetch API.\n\n/** The route a client's OTel exporter posts to on the deployment that serves it. */\nexport const PREFIX = '/api/otel';\n\nconst SIGNALS = new Set(['/v1/traces', '/v1/logs', '/v1/metrics']);\n\nexport type Options = {\n /** PostHog's OTLP base URL, e.g. `https://eu.i.posthog.com/i`. */\n url?: string;\n /** The project token, sent upstream as the bearer token so it never reaches the client. */\n token?: string;\n /** Origins admitted besides the deployment's own, such as a native build's. */\n extraOrigins?: ReadonlySet<string>;\n /** Largest body forwarded, in bytes. */\n maxBodySize: number;\n};\n\n/** A POST always carries `Origin`, so a missing one is refused. */\nconst isAllowedOrigin = (request: Request, origin: string | null, extraOrigins?: ReadonlySet<string>): boolean =>\n origin !== null && (origin === new URL(request.url).origin || extraOrigins?.has(origin) === true);\n\nconst corsHeaders = (\n request: Request,\n origin: string | null,\n extraOrigins?: ReadonlySet<string>,\n): Record<string, string> => ({\n 'Access-Control-Allow-Origin': isAllowedOrigin(request, origin, extraOrigins) ? (origin ?? '') : '',\n 'Access-Control-Allow-Methods': 'POST, OPTIONS',\n 'Access-Control-Allow-Headers': 'Content-Type, Content-Encoding',\n 'Vary': 'Origin',\n});\n\n/**\n * Forwards an OTLP request on `/api/otel/v1/{traces,logs,metrics}` to PostHog with the project token.\n * Returns `undefined` for any other path, so the caller can route it elsewhere.\n */\nexport const handle = (request: Request, options: Options): Promise<Response> | undefined => {\n const { pathname } = new URL(request.url);\n const signal = pathname.startsWith(`${PREFIX}/`) ? pathname.slice(PREFIX.length) : undefined;\n return signal && SIGNALS.has(signal) ? forward(request, options, signal) : undefined;\n};\n\nconst forward = async (\n request: Request,\n { url, token, extraOrigins, maxBodySize }: Options,\n signal: string,\n): Promise<Response> => {\n const origin = request.headers.get('Origin');\n const cors = corsHeaders(request, origin, extraOrigins);\n if (request.method === 'OPTIONS') {\n return new Response(null, { status: 204, headers: cors });\n }\n if (request.method !== 'POST') {\n return new Response('Method not allowed', { status: 405, headers: cors });\n }\n if (!isAllowedOrigin(request, origin, extraOrigins)) {\n return new Response('Forbidden', { status: 403, headers: cors });\n }\n if (!url || !token) {\n return new Response('OTel proxy not configured', { status: 503, headers: cors });\n }\n if (!request.body) {\n return new Response('Empty body', { status: 400, headers: cors });\n }\n\n const headers: Record<string, string> = {\n 'Content-Type': request.headers.get('Content-Type') ?? 'application/json',\n 'Authorization': `Bearer ${token}`,\n };\n for (const name of ['Content-Encoding', 'Content-Length']) {\n const value = request.headers.get(name);\n if (value) {\n headers[name] = value;\n }\n }\n\n let size = 0;\n let tooLarge = false;\n const { readable, writable } = new TransformStream<Uint8Array, Uint8Array>({\n transform: (chunk, controller) => {\n size += chunk.byteLength;\n if (size > maxBodySize) {\n tooLarge = true;\n controller.error(new Error('Payload too large'));\n } else {\n controller.enqueue(chunk);\n }\n },\n });\n const piped = request.body.pipeTo(writable).catch(() => {});\n\n let upstream: Response | undefined;\n try {\n upstream = await fetch(`${url.replace(/\\/$/, '')}${signal}`, { method: 'POST', headers, body: readable });\n } catch {\n // An aborted body stream rejects the fetch, as does an unreachable upstream. A fetch that failed before reading\n // leaves the pipe blocked on backpressure, so the body is cancelled to end it.\n await readable.cancel().catch(() => {});\n }\n await piped;\n\n if (tooLarge) {\n return new Response('Payload too large', { status: 413, headers: cors });\n }\n if (!upstream) {\n return new Response('Bad gateway', { status: 502, headers: cors });\n }\n return new Response(upstream.body, {\n status: upstream.status,\n headers: { 'Content-Type': upstream.headers.get('Content-Type') ?? 'application/json', ...cors },\n });\n};\n"],"mappings":";;;;;;;AASA,IAAa,SAAS;AAEtB,IAAM,0BAAU,IAAI,IAAI;CAAC;CAAc;CAAY;AAAa,CAAC;;AAcjE,IAAM,mBAAmB,SA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AAU;CAC7B;CACA,KAAK,MAAM,QAAQ,CAAC,oBAAoB,gBAAgB,GAAG;EACzD,MAAM,QAAQ,QAAQ,QAAQ,IAAI,IAAI;EACtC,IAAI,OACF,QAAQ,QAAQ;CAEpB;CAEA,IAAI,OAAO;CACX,IAAI,WAAW;CACf,MAAM,EAAE,UAAU,aAAa,IAAI,gBAAwC,EACzE,YAAY,OAAO,eAAe;EAChC,QAAQ,MAAM;EACd,IAAI,OAAO,aAAa;GACtB,WAAW;GACX,WAAW,sBAAM,IAAI,MAAM,mBAAmB,CAAC;EACjD,OACE,WAAW,QAAQ,KAAK;CAE5B,EACF,CAAC;CACD,MAAM,QAAQ,QAAQ,KAAK,OAAO,QAAQ,CAAC,CAAC,YAAY,CAAC,CAAC;CAE1D,IAAI;CACJ,IAAI;EACF,WAAW,MAAM,MAAM,GAAG,IAAI,QAAQ,OAAO,EAAE,IAAI,UAAU;GAAE,QAAQ;GAAQ;GAAS,MAAM;EAAS,CAAC;CAC1G,QAAQ;EAGN,MAAM,SAAS,OAAO,CAAC,CAAC,YAAY,CAAC,CAAC;CACxC;CACA,MAAM;CAEN,IAAI,UACF,OAAO,IAAI,SAAS,qBAAqB;EAAE,QAAQ;EAAK,SAAS;CAAK,CAAC;CAEzE,IAAI,CAAC,UACH,OAAO,IAAI,SAAS,eAAe;EAAE,QAAQ;EAAK,SAAS;CAAK,CAAC;CAEnE,OAAO,IAAI,SAAS,SAAS,MAAM;EACjC,QAAQ,SAAS;EACjB,SAAS;GAAE,gBAAgB,SAAS,QAAQ,IAAI,cAAc,KAAK;GAAoB,GAAG;EAAK;CACjG,CAAC;AACH"}
|
|
@@ -51,7 +51,7 @@ var AiContentStrippingSpanProcessor = class {
|
|
|
51
51
|
* cannot know that the span will fail, and it sees the span name before the provider has annotated
|
|
52
52
|
* it. Both decisions are only available once the span has ended — which is what "tail" means. The
|
|
53
53
|
* canonical implementation of this is the OpenTelemetry Collector's tail-sampling processor, which
|
|
54
|
-
* buffers whole traces server-side; there is no collector between Composer and
|
|
54
|
+
* buffers whole traces server-side; there is no collector between Composer and PostHog, so the same
|
|
55
55
|
* decisions are made here instead, on the spans this realm produced.
|
|
56
56
|
*
|
|
57
57
|
* The rules are the canonical tail-sampling set — keep what errored, keep what was slow, sample the
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"chunk-OtelSpanSink.mjs","names":["TailSampling.TailSampler","TailSampling.hrTimeToMs","AiContent.withoutAiContent"],"sources":["../../src/extensions/otel/ai-content.ts","../../src/extensions/otel/tail-sampling.ts","../../src/extensions/otel/OtelSpanSink.ts"],"sourcesContent":["//\n// Copyright 2026 DXOS.org\n//\n\nimport { type Attributes, type Context } from '@opentelemetry/api';\nimport { type ReadableSpan, type Span, type SpanProcessor } from '@opentelemetry/sdk-trace-base';\n\nimport * as SpanAttributes from '@dxos/effect/SpanAttributes';\n\n/**\n * The prompt, the response, and the tool names. They stay on the span for the AI analytics sink,\n * which applies the content policy, and never leave the process with it: a trace backend gets the\n * model call's metadata.\n */\nexport const AI_CONTENT_ATTRIBUTES: ReadonlySet<string> = new Set([\n SpanAttributes.AI.input,\n SpanAttributes.AI.output,\n SpanAttributes.AI.tools,\n]);\n\nexport const withoutAiContent = (attributes: Attributes): Attributes =>\n Object.fromEntries(Object.entries(attributes).filter(([key]) => !AI_CONTENT_ATTRIBUTES.has(key)));\n\n/** A view of the span without its content attributes; the span itself is what other processors read. */\nexport const stripAiContent = (span: ReadableSpan): ReadableSpan =>\n Object.create(span, { attributes: { value: withoutAiContent(span.attributes), enumerable: true } });\n\n/** Strips AI content from every span it forwards. Sits directly in front of an exporter. */\nexport class AiContentStrippingSpanProcessor implements SpanProcessor {\n constructor(private readonly _delegate: SpanProcessor) {}\n\n onStart(span: Span, parentContext: Context): void {\n this._delegate.onStart(span, parentContext);\n }\n\n onEnd(span: ReadableSpan): void {\n this._delegate.onEnd(stripAiContent(span));\n }\n\n forceFlush(): Promise<void> {\n return this._delegate.forceFlush();\n }\n\n shutdown(): Promise<void> {\n return this._delegate.shutdown();\n }\n}\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport { type Attributes, type Context, SpanStatusCode } from '@opentelemetry/api';\nimport type { ReadableSpan, Span, SpanProcessor } from '@opentelemetry/sdk-trace-base';\n\nimport * as SpanAttributes from '@dxos/effect/SpanAttributes';\n\n/**\n * Tail sampling for spans arriving at the observability worker.\n *\n * Head sampling cannot express either rule we want. A sampler runs when a span is *created*, so it\n * cannot know that the span will fail, and it sees the span name before the provider has annotated\n * it. Both decisions are only available once the span has ended — which is what \"tail\" means. The\n * canonical implementation of this is the OpenTelemetry Collector's tail-sampling processor, which\n * buffers whole traces server-side; there is no collector between Composer and SigNoz, so the same\n * decisions are made here instead, on the spans this realm produced.\n *\n * The rules are the canonical tail-sampling set — keep what errored, keep what was slow, sample the\n * rest — as described in OpenTelemetry's own writeup and implemented by the Collector's\n * `tailsamplingprocessor` policies (`status_code`, `latency`, `probabilistic`):\n *\n * - https://opentelemetry.io/blog/2022/tail-sampling/\n * - https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/processor/tailsamplingprocessor\n *\n * Expressing them as a processor that filters in `onEnd` is the documented way to drop spans from a\n * JS SDK, since a `Sampler` cannot: https://github.com/open-telemetry/opentelemetry-js/discussions/2817\n *\n * In order:\n * - a span that **errored** is kept, and its trace is promoted;\n * - a span slower than {@link DEFAULT_SLOW_MS} is kept, and its trace is promoted;\n * - a span marked `dxos.sampling.keep` — a rare flow such as an invitation, which a dashboard counts\n * one by one and a 30% sample would mostly hide — is kept, and its trace is promoted;\n * - a span carrying `gen_ai.*` or `dxos.ai.kind` — a model call, or the turn and tool calls\n * around it that the AI analytics sink reports — is kept, and its trace is promoted, so a model call is never a\n * fraction of the calls that happened. This one is ours rather than canonical: the AI events are\n * what price the product, and a sampled fraction of them reports a fraction of the spend;\n * - any other span of a **promoted** trace is kept;\n * - everything else is kept at {@link DEFAULT_RATIO}, keyed on the trace id so the decision is the\n * same for every span of a trace.\n *\n * Promotion is remembered rather than buffered: holding span payloads until a trace settles would\n * mean an unbounded buffer and a decision delay, and a conversation's trace can stay open for\n * minutes. Remembering only the trace id costs nothing and recovers the case that matters, since a\n * parent ends *after* its children — so promoting on the first error keeps the ancestors that\n * explain it. Siblings that already ended and were dropped are not recovered; that is the price of\n * not buffering, and it is why an errored trace can arrive with gaps rather than whole.\n */\n\n/** Kept fraction for a trace that nothing promoted. Matches the head ratio this replaced. */\nexport const DEFAULT_RATIO = 0.3;\n\n/**\n * Above this, a span is kept as slow.\n *\n * Far above the 5s the Collector's examples use, because this app's slowest spans are model calls\n * and a conversation turn legitimately runs for tens of seconds — a 5s threshold would promote\n * nearly every AI trace and quietly turn the ratio off for exactly the traffic there is most of.\n * At 30s what is left is a hang rather than a slow answer.\n */\nexport const DEFAULT_SLOW_MS = 30_000;\n\n/**\n * Bound on remembered trace ids. Reached only under a burst far above normal span rates, and a trace\n * evicted early degrades to the ratio rather than to a dropped span.\n */\nconst DEFAULT_MAX_TRACKED_TRACES = 10_000;\n\nexport type Options = {\n ratio?: number;\n slowMs?: number;\n maxTrackedTraces?: number;\n};\n\n/** The parts of an ended span the rules read, whether it arrived over a port or ended in-process. */\nexport type Decidable = {\n readonly traceId: string;\n readonly status: { readonly code: SpanStatusCode };\n readonly attributes: Attributes;\n readonly durationMs: number;\n};\n\nexport class TailSampler {\n private readonly _ratio: number;\n private readonly _slowMs: number;\n private readonly _maxTrackedTraces: number;\n /** Insertion-ordered, so the oldest entry is the first key — an LRU without the bookkeeping. */\n private readonly _promoted = new Set<string>();\n\n constructor({\n ratio = DEFAULT_RATIO,\n slowMs = DEFAULT_SLOW_MS,\n maxTrackedTraces = DEFAULT_MAX_TRACKED_TRACES,\n }: Options = {}) {\n this._ratio = ratio;\n this._slowMs = slowMs;\n this._maxTrackedTraces = maxTrackedTraces;\n }\n\n /** Whether the span should be forwarded to the exporter. */\n keep(span: Decidable): boolean {\n if (this._isPromotable(span)) {\n this.promote(span.traceId);\n return true;\n }\n return this._promoted.has(span.traceId) || sampledByTraceId(span.traceId, this._ratio);\n }\n\n private _isPromotable(span: Decidable): boolean {\n return (\n span.status.code === SpanStatusCode.ERROR ||\n span.durationMs > this._slowMs ||\n isKeepMarked(span.attributes) ||\n Object.keys(span.attributes).some(isAiAttribute)\n );\n }\n\n /**\n * Keeps every later span of the trace. Called for what the sampler cannot see itself: a log at\n * warning or above names a trace worth keeping the same way an errored span does.\n */\n promote(traceId: string): void {\n // Re-inserting moves the id to the end, so an active trace is not evicted ahead of a stale one.\n this._promoted.delete(traceId);\n this._promoted.add(traceId);\n while (this._promoted.size > this._maxTrackedTraces) {\n const oldest = this._promoted.values().next();\n if (oldest.done) {\n break;\n }\n this._promoted.delete(oldest.value);\n }\n }\n}\n\nconst GEN_AI_PREFIX = 'gen_ai.';\n\n/** `gen_ai.*` marks a model call; `dxos.ai.kind` the turn around it and the tool calls inside it. */\nconst isAiAttribute = (key: string): boolean => key.startsWith(GEN_AI_PREFIX) || key === SpanAttributes.AI.kind;\n\n/** Manual `@dxos/tracing` spans namespace their attributes under `ctx.`, so the marker arrives either way. */\nconst isKeepMarked = (attributes: Attributes): boolean =>\n attributes[SpanAttributes.SAMPLING.keep] === true || attributes[`ctx.${SpanAttributes.SAMPLING.keep}`] === true;\n\n/**\n * Deterministic per trace, so every span of a trace decides the same way. Reads the low 8 hex digits\n * of the 32-hex-digit trace id — the id is random, so any window is uniform, and 32 bits is well\n * inside the exact range of a double.\n */\nconst sampledByTraceId = (traceId: string, ratio: number): boolean => {\n if (ratio >= 1) {\n return true;\n }\n if (ratio <= 0 || traceId.length < 8) {\n return false;\n }\n const value = Number.parseInt(traceId.slice(-8), 16);\n return Number.isNaN(value) ? false : value / 0x1_0000_0000 < ratio;\n};\n\n/** OTel reports durations as `[seconds, nanoseconds]`. */\nexport const hrTimeToMs = ([seconds, nanos]: [number, number]): number => seconds * 1_000 + nanos / 1e6;\n\n/**\n * Applies the same rules in-process, for the path that exports without a worker (node, and a browser\n * with no observability worker). Without it that path would export everything, since head sampling\n * no longer thins anything.\n */\nexport class TailSamplingSpanProcessor implements SpanProcessor {\n private readonly _sampler: TailSampler;\n\n constructor(\n private readonly _delegate: SpanProcessor,\n options?: Options,\n ) {\n this._sampler = new TailSampler(options);\n }\n\n onStart(span: Span, parentContext: Context): void {\n this._delegate.onStart(span, parentContext);\n }\n\n /** See {@link TailSampler.promote}. */\n promote(traceId: string): void {\n this._sampler.promote(traceId);\n }\n\n onEnd(span: ReadableSpan): void {\n const { traceId } = span.spanContext();\n const decidable = {\n traceId,\n status: span.status,\n attributes: span.attributes,\n durationMs: hrTimeToMs(span.duration),\n };\n if (this._sampler.keep(decidable)) {\n this._delegate.onEnd(span);\n }\n }\n\n forceFlush(): Promise<void> {\n return this._delegate.forceFlush();\n }\n\n shutdown(): Promise<void> {\n return this._delegate.shutdown();\n }\n}\n","//\n// Copyright 2026 DXOS.org\n//\n\n// @import-as-namespace\n\n// The log-writer worker imports this through its own subpath, so nothing else loads the\n// OpenTelemetry SDK.\n\nimport {\n type Attributes,\n type Context,\n type HrTime,\n type Link,\n type SpanContext,\n type SpanKind,\n type SpanStatus,\n} from '@opentelemetry/api';\nimport { TraceState, hrTimeDuration } from '@opentelemetry/core';\nimport { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';\nimport { type Resource, defaultResource, resourceFromAttributes } from '@opentelemetry/resources';\nimport {\n BatchSpanProcessor,\n type ReadableSpan,\n type Span as SdkSpan,\n type SpanExporter,\n type SpanProcessor,\n} from '@opentelemetry/sdk-trace-base';\n\nimport * as AiContent from './ai-content.ts';\nimport { type OtelDestination, signalUrl } from './otel.ts';\nimport * as TailSampling from './tail-sampling.ts';\n\nexport type Init = {\n type: 'otel-traces-init';\n destinations: OtelDestination[];\n resourceAttributes: Record<string, string>;\n};\n\nexport type Span = {\n type: 'otel-span';\n name: string;\n kind: SpanKind;\n traceId: string;\n spanId: string;\n traceFlags: number;\n traceState?: string;\n parentSpanContext?: { traceId: string; spanId: string; traceFlags: number };\n startTime: HrTime;\n endTime: HrTime;\n status: SpanStatus;\n attributes: Attributes;\n events: { name: string; time: HrTime; attributes?: Attributes; droppedAttributesCount?: number }[];\n links: { context: { traceId: string; spanId: string; traceFlags: number }; attributes?: Attributes }[];\n droppedAttributesCount: number;\n droppedEventsCount: number;\n droppedLinksCount: number;\n instrumentationScope: { name: string; version?: string };\n};\n\nexport type Message = Init | Span;\n\nexport type Handle = { post: (record: Span) => void };\n\nexport const serializeReadableSpan = (span: ReadableSpan): Span => {\n const spanContext = span.spanContext();\n return {\n type: 'otel-span',\n name: span.name,\n kind: span.kind,\n traceId: spanContext.traceId,\n spanId: spanContext.spanId,\n traceFlags: spanContext.traceFlags,\n traceState: spanContext.traceState?.serialize(),\n parentSpanContext: span.parentSpanContext\n ? {\n traceId: span.parentSpanContext.traceId,\n spanId: span.parentSpanContext.spanId,\n traceFlags: span.parentSpanContext.traceFlags,\n }\n : undefined,\n startTime: span.startTime,\n endTime: span.endTime,\n status: span.status,\n attributes: { ...span.attributes },\n events: span.events.map((event) => ({\n name: event.name,\n time: event.time,\n attributes: event.attributes ? { ...event.attributes } : undefined,\n droppedAttributesCount: event.droppedAttributesCount,\n })),\n links: span.links.map((link) => ({\n context: {\n traceId: link.context.traceId,\n spanId: link.context.spanId,\n traceFlags: link.context.traceFlags,\n },\n attributes: link.attributes ? { ...link.attributes } : undefined,\n })),\n droppedAttributesCount: span.droppedAttributesCount,\n droppedEventsCount: span.droppedEventsCount,\n droppedLinksCount: span.droppedLinksCount,\n instrumentationScope: {\n name: span.instrumentationScope.name,\n version: span.instrumentationScope.version,\n },\n };\n};\n\nexport class PortSpanProcessor implements SpanProcessor {\n constructor(private readonly _post: (record: Span) => void) {}\n\n onStart(_span: SdkSpan, _parentContext: Context): void {}\n\n onEnd(span: ReadableSpan): void {\n this._post(serializeReadableSpan(span));\n }\n\n async shutdown(): Promise<void> {}\n\n async forceFlush(): Promise<void> {}\n}\n\nexport type Options = {\n exporter?: SpanExporter;\n /** Overrides the default tail-sampling rules; pass `{ ratio: 1 }` to export everything. */\n sampling?: TailSampling.Options;\n};\n\nexport class Sink {\n readonly #resource: Resource;\n readonly #processors: BatchSpanProcessor[];\n readonly #sampler: TailSampling.TailSampler;\n\n constructor(init: Init, options: Options = {}) {\n this.#sampler = new TailSampling.TailSampler(options.sampling);\n this.#resource = defaultResource().merge(resourceFromAttributes(init.resourceAttributes));\n this.#processors = init.destinations.map(\n (destination) =>\n new BatchSpanProcessor(\n options.exporter ??\n new OTLPTraceExporter({\n url: signalUrl(destination, 'traces'),\n headers: destination.headers,\n concurrencyLimit: 10,\n }),\n ),\n );\n }\n\n /** Keeps the rest of a trace something outside the span stream vouched for, e.g. a warning log. */\n promote(traceId: string): void {\n this.#sampler.promote(traceId);\n }\n\n append(record: Span): void {\n if (\n !this.#sampler.keep({\n traceId: record.traceId,\n status: record.status,\n attributes: record.attributes,\n durationMs: TailSampling.hrTimeToMs(hrTimeDuration(record.startTime, record.endTime)),\n })\n ) {\n return;\n }\n const span = this.#materialize(record);\n for (const processor of this.#processors) {\n processor.onEnd(span);\n }\n }\n\n async flush(): Promise<void> {\n await Promise.all(this.#processors.map((processor) => processor.forceFlush()));\n }\n\n async close(): Promise<void> {\n await Promise.all(this.#processors.map((processor) => processor.shutdown()));\n }\n\n #materialize(record: Span): ReadableSpan {\n const spanContext: SpanContext = {\n traceId: record.traceId,\n spanId: record.spanId,\n traceFlags: record.traceFlags,\n traceState: record.traceState !== undefined ? new TraceState(record.traceState) : undefined,\n };\n const links: Link[] = record.links.map((link) => ({\n context: { ...link.context },\n attributes: link.attributes,\n }));\n return {\n name: record.name,\n kind: record.kind,\n spanContext: () => spanContext,\n parentSpanContext: record.parentSpanContext ? { ...record.parentSpanContext } : undefined,\n startTime: record.startTime,\n endTime: record.endTime,\n status: record.status,\n attributes: AiContent.withoutAiContent(record.attributes),\n links,\n events: record.events.map((event) => ({\n name: event.name,\n time: event.time,\n attributes: event.attributes,\n droppedAttributesCount: event.droppedAttributesCount,\n })),\n duration: hrTimeDuration(record.startTime, record.endTime),\n ended: true,\n resource: this.#resource,\n instrumentationScope: { ...record.instrumentationScope },\n droppedAttributesCount: record.droppedAttributesCount,\n droppedEventsCount: record.droppedEventsCount,\n droppedLinksCount: record.droppedLinksCount,\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAcA,IAAa,wCAA6C,IAAI,IAAI;CAChE,eAAe,GAAG;CAClB,eAAe,GAAG;CAClB,eAAe,GAAG;AACpB,CAAC;AAED,IAAa,oBAAoB,eAC/B,OAAO,YAAY,OAAO,QAAQ,UAAU,CAAC,CAAC,QAAQ,CAAC,SAAS,CAAC,sBAAsB,IAAI,GAAG,CAAC,CAAC;;AAGlG,IAAa,kBAAkB,SAC7B,OAAO,OAAO,MAAM,EAAE,YAAY;CAAE,OAAO,iBAAiB,KAAK,UAAU;CAAG,YAAY;AAAK,EAAE,CAAC;;AAGpG,IAAa,kCAAb,MAAsE;CACvC;CAA7B,YAAY,WAA2C;EAA1B,KAAA,YAAA;CAA2B;CAExD,QAAQ,MAAY,eAA8B;EAChD,KAAK,UAAU,QAAQ,MAAM,aAAa;CAC5C;CAEA,MAAM,MAA0B;EAC9B,KAAK,UAAU,MAAM,eAAe,IAAI,CAAC;CAC3C;CAEA,aAA4B;EAC1B,OAAO,KAAK,UAAU,WAAW;CACnC;CAEA,WAA0B;EACxB,OAAO,KAAK,UAAU,SAAS;CACjC;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACKA,IAAa,gBAAgB;;;;;;;;;AAU7B,IAAa,kBAAkB;;;;;AAM/B,IAAM,6BAA6B;AAgBnC,IAAa,cAAb,MAAyB;CACvB;CACA;CACA;;CAEA,4BAA6B,IAAI,IAAY;CAE7C,YAAY,EACV,QAAQ,eACR,SAAS,iBACT,mBAAmB,+BACR,CAAC,GAAG;EACf,KAAK,SAAS;EACd,KAAK,UAAU;EACf,KAAK,oBAAoB;CAC3B;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EA,MAAM,QAAuB;EAC3B,MAAM,QAAQ,IAAI,KAAK,YAAY,KAAK,cAAc,UAAU,SAAS,CAAC,CAAC;CAC7E;CAEA,aAAa,QAA4B;EACvC,MAAM,cAA2B;GAC/B,SAAS,OAAO;GAChB,QAAQ,OAAO;GACf,YAAY,OAAO;GACnB,YAAY,OAAO,eAAe,KAAA,IAAY,IAAI,WAAW,OAAO,UAAU,IAAI,KAAA;EACpF;EACA,MAAM,QAAgB,OAAO,MAAM,KAAK,UAAU;GAChD,SAAS,EAAE,GAAG,KAAK,QAAQ;GAC3B,YAAY,KAAK;EACnB,EAAE;EACF,OAAO;GACL,MAAM,OAAO;GACb,MAAM,OAAO;GACb,mBAAmB;GACnB,mBAAmB,OAAO,oBAAoB,EAAE,GAAG,OAAO,kBAAkB,IAAI,KAAA;GAChF,WAAW,OAAO;GAClB,SAAS,OAAO;GAChB,QAAQ,OAAO;GACf,YAAYC,iBAA2B,OAAO,UAAU;GACxD;GACA,QAAQ,OAAO,OAAO,KAAK,WAAW;IACpC,MAAM,MAAM;IACZ,MAAM,MAAM;IACZ,YAAY,MAAM;IAClB,wBAAwB,MAAM;GAChC,EAAE;GACF,UAAU,eAAe,OAAO,WAAW,OAAO,OAAO;GACzD,OAAO;GACP,UAAU,KAAK;GACf,sBAAsB,EAAE,GAAG,OAAO,qBAAqB;GACvD,wBAAwB,OAAO;GAC/B,oBAAoB,OAAO;GAC3B,mBAAmB,OAAO;EAC5B;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"chunk-OtelSpanSink.mjs","names":["TailSampling.TailSampler","TailSampling.hrTimeToMs","AiContent.withoutAiContent"],"sources":["../../src/extensions/otel/ai-content.ts","../../src/extensions/otel/tail-sampling.ts","../../src/extensions/otel/OtelSpanSink.ts"],"sourcesContent":["//\n// Copyright 2026 DXOS.org\n//\n\nimport { type Attributes, type Context } from '@opentelemetry/api';\nimport { type ReadableSpan, type Span, type SpanProcessor } from '@opentelemetry/sdk-trace-base';\n\nimport * as SpanAttributes from '@dxos/effect/SpanAttributes';\n\n/**\n * The prompt, the response, and the tool names. They stay on the span for the AI analytics sink,\n * which applies the content policy, and never leave the process with it: a trace backend gets the\n * model call's metadata.\n */\nexport const AI_CONTENT_ATTRIBUTES: ReadonlySet<string> = new Set([\n SpanAttributes.AI.input,\n SpanAttributes.AI.output,\n SpanAttributes.AI.tools,\n]);\n\nexport const withoutAiContent = (attributes: Attributes): Attributes =>\n Object.fromEntries(Object.entries(attributes).filter(([key]) => !AI_CONTENT_ATTRIBUTES.has(key)));\n\n/** A view of the span without its content attributes; the span itself is what other processors read. */\nexport const stripAiContent = (span: ReadableSpan): ReadableSpan =>\n Object.create(span, { attributes: { value: withoutAiContent(span.attributes), enumerable: true } });\n\n/** Strips AI content from every span it forwards. Sits directly in front of an exporter. */\nexport class AiContentStrippingSpanProcessor implements SpanProcessor {\n constructor(private readonly _delegate: SpanProcessor) {}\n\n onStart(span: Span, parentContext: Context): void {\n this._delegate.onStart(span, parentContext);\n }\n\n onEnd(span: ReadableSpan): void {\n this._delegate.onEnd(stripAiContent(span));\n }\n\n forceFlush(): Promise<void> {\n return this._delegate.forceFlush();\n }\n\n shutdown(): Promise<void> {\n return this._delegate.shutdown();\n }\n}\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport { type Attributes, type Context, SpanStatusCode } from '@opentelemetry/api';\nimport type { ReadableSpan, Span, SpanProcessor } from '@opentelemetry/sdk-trace-base';\n\nimport * as SpanAttributes from '@dxos/effect/SpanAttributes';\n\n/**\n * Tail sampling for spans arriving at the observability worker.\n *\n * Head sampling cannot express either rule we want. A sampler runs when a span is *created*, so it\n * cannot know that the span will fail, and it sees the span name before the provider has annotated\n * it. Both decisions are only available once the span has ended — which is what \"tail\" means. The\n * canonical implementation of this is the OpenTelemetry Collector's tail-sampling processor, which\n * buffers whole traces server-side; there is no collector between Composer and PostHog, so the same\n * decisions are made here instead, on the spans this realm produced.\n *\n * The rules are the canonical tail-sampling set — keep what errored, keep what was slow, sample the\n * rest — as described in OpenTelemetry's own writeup and implemented by the Collector's\n * `tailsamplingprocessor` policies (`status_code`, `latency`, `probabilistic`):\n *\n * - https://opentelemetry.io/blog/2022/tail-sampling/\n * - https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/processor/tailsamplingprocessor\n *\n * Expressing them as a processor that filters in `onEnd` is the documented way to drop spans from a\n * JS SDK, since a `Sampler` cannot: https://github.com/open-telemetry/opentelemetry-js/discussions/2817\n *\n * In order:\n * - a span that **errored** is kept, and its trace is promoted;\n * - a span slower than {@link DEFAULT_SLOW_MS} is kept, and its trace is promoted;\n * - a span marked `dxos.sampling.keep` — a rare flow such as an invitation, which a dashboard counts\n * one by one and a 30% sample would mostly hide — is kept, and its trace is promoted;\n * - a span carrying `gen_ai.*` or `dxos.ai.kind` — a model call, or the turn and tool calls\n * around it that the AI analytics sink reports — is kept, and its trace is promoted, so a model call is never a\n * fraction of the calls that happened. This one is ours rather than canonical: the AI events are\n * what price the product, and a sampled fraction of them reports a fraction of the spend;\n * - any other span of a **promoted** trace is kept;\n * - everything else is kept at {@link DEFAULT_RATIO}, keyed on the trace id so the decision is the\n * same for every span of a trace.\n *\n * Promotion is remembered rather than buffered: holding span payloads until a trace settles would\n * mean an unbounded buffer and a decision delay, and a conversation's trace can stay open for\n * minutes. Remembering only the trace id costs nothing and recovers the case that matters, since a\n * parent ends *after* its children — so promoting on the first error keeps the ancestors that\n * explain it. Siblings that already ended and were dropped are not recovered; that is the price of\n * not buffering, and it is why an errored trace can arrive with gaps rather than whole.\n */\n\n/** Kept fraction for a trace that nothing promoted. Matches the head ratio this replaced. */\nexport const DEFAULT_RATIO = 0.3;\n\n/**\n * Above this, a span is kept as slow.\n *\n * Far above the 5s the Collector's examples use, because this app's slowest spans are model calls\n * and a conversation turn legitimately runs for tens of seconds — a 5s threshold would promote\n * nearly every AI trace and quietly turn the ratio off for exactly the traffic there is most of.\n * At 30s what is left is a hang rather than a slow answer.\n */\nexport const DEFAULT_SLOW_MS = 30_000;\n\n/**\n * Bound on remembered trace ids. Reached only under a burst far above normal span rates, and a trace\n * evicted early degrades to the ratio rather than to a dropped span.\n */\nconst DEFAULT_MAX_TRACKED_TRACES = 10_000;\n\nexport type Options = {\n ratio?: number;\n slowMs?: number;\n maxTrackedTraces?: number;\n};\n\n/** The parts of an ended span the rules read, whether it arrived over a port or ended in-process. */\nexport type Decidable = {\n readonly traceId: string;\n readonly status: { readonly code: SpanStatusCode };\n readonly attributes: Attributes;\n readonly durationMs: number;\n};\n\nexport class TailSampler {\n private readonly _ratio: number;\n private readonly _slowMs: number;\n private readonly _maxTrackedTraces: number;\n /** Insertion-ordered, so the oldest entry is the first key — an LRU without the bookkeeping. */\n private readonly _promoted = new Set<string>();\n\n constructor({\n ratio = DEFAULT_RATIO,\n slowMs = DEFAULT_SLOW_MS,\n maxTrackedTraces = DEFAULT_MAX_TRACKED_TRACES,\n }: Options = {}) {\n this._ratio = ratio;\n this._slowMs = slowMs;\n this._maxTrackedTraces = maxTrackedTraces;\n }\n\n /** Whether the span should be forwarded to the exporter. */\n keep(span: Decidable): boolean {\n if (this._isPromotable(span)) {\n this.promote(span.traceId);\n return true;\n }\n return this._promoted.has(span.traceId) || sampledByTraceId(span.traceId, this._ratio);\n }\n\n private _isPromotable(span: Decidable): boolean {\n return (\n span.status.code === SpanStatusCode.ERROR ||\n span.durationMs > this._slowMs ||\n isKeepMarked(span.attributes) ||\n Object.keys(span.attributes).some(isAiAttribute)\n );\n }\n\n /**\n * Keeps every later span of the trace. Called for what the sampler cannot see itself: a log at\n * warning or above names a trace worth keeping the same way an errored span does.\n */\n promote(traceId: string): void {\n // Re-inserting moves the id to the end, so an active trace is not evicted ahead of a stale one.\n this._promoted.delete(traceId);\n this._promoted.add(traceId);\n while (this._promoted.size > this._maxTrackedTraces) {\n const oldest = this._promoted.values().next();\n if (oldest.done) {\n break;\n }\n this._promoted.delete(oldest.value);\n }\n }\n}\n\nconst GEN_AI_PREFIX = 'gen_ai.';\n\n/** `gen_ai.*` marks a model call; `dxos.ai.kind` the turn around it and the tool calls inside it. */\nconst isAiAttribute = (key: string): boolean => key.startsWith(GEN_AI_PREFIX) || key === SpanAttributes.AI.kind;\n\n/** Manual `@dxos/tracing` spans namespace their attributes under `ctx.`, so the marker arrives either way. */\nconst isKeepMarked = (attributes: Attributes): boolean =>\n attributes[SpanAttributes.SAMPLING.keep] === true || attributes[`ctx.${SpanAttributes.SAMPLING.keep}`] === true;\n\n/**\n * Deterministic per trace, so every span of a trace decides the same way. Reads the low 8 hex digits\n * of the 32-hex-digit trace id — the id is random, so any window is uniform, and 32 bits is well\n * inside the exact range of a double.\n */\nconst sampledByTraceId = (traceId: string, ratio: number): boolean => {\n if (ratio >= 1) {\n return true;\n }\n if (ratio <= 0 || traceId.length < 8) {\n return false;\n }\n const value = Number.parseInt(traceId.slice(-8), 16);\n return Number.isNaN(value) ? false : value / 0x1_0000_0000 < ratio;\n};\n\n/** OTel reports durations as `[seconds, nanoseconds]`. */\nexport const hrTimeToMs = ([seconds, nanos]: [number, number]): number => seconds * 1_000 + nanos / 1e6;\n\n/**\n * Applies the same rules in-process, for the path that exports without a worker (node, and a browser\n * with no observability worker). Without it that path would export everything, since head sampling\n * no longer thins anything.\n */\nexport class TailSamplingSpanProcessor implements SpanProcessor {\n private readonly _sampler: TailSampler;\n\n constructor(\n private readonly _delegate: SpanProcessor,\n options?: Options,\n ) {\n this._sampler = new TailSampler(options);\n }\n\n onStart(span: Span, parentContext: Context): void {\n this._delegate.onStart(span, parentContext);\n }\n\n /** See {@link TailSampler.promote}. */\n promote(traceId: string): void {\n this._sampler.promote(traceId);\n }\n\n onEnd(span: ReadableSpan): void {\n const { traceId } = span.spanContext();\n const decidable = {\n traceId,\n status: span.status,\n attributes: span.attributes,\n durationMs: hrTimeToMs(span.duration),\n };\n if (this._sampler.keep(decidable)) {\n this._delegate.onEnd(span);\n }\n }\n\n forceFlush(): Promise<void> {\n return this._delegate.forceFlush();\n }\n\n shutdown(): Promise<void> {\n return this._delegate.shutdown();\n }\n}\n","//\n// Copyright 2026 DXOS.org\n//\n\n// @import-as-namespace\n\n// The log-writer worker imports this through its own subpath, so nothing else loads the\n// OpenTelemetry SDK.\n\nimport {\n type Attributes,\n type Context,\n type HrTime,\n type Link,\n type SpanContext,\n type SpanKind,\n type SpanStatus,\n} from '@opentelemetry/api';\nimport { TraceState, hrTimeDuration } from '@opentelemetry/core';\nimport { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';\nimport { type Resource, defaultResource, resourceFromAttributes } from '@opentelemetry/resources';\nimport {\n BatchSpanProcessor,\n type ReadableSpan,\n type Span as SdkSpan,\n type SpanExporter,\n type SpanProcessor,\n} from '@opentelemetry/sdk-trace-base';\n\nimport * as AiContent from './ai-content.ts';\nimport { type OtelDestination, signalUrl } from './otel.ts';\nimport * as TailSampling from './tail-sampling.ts';\n\nexport type Init = {\n type: 'otel-traces-init';\n destinations: OtelDestination[];\n resourceAttributes: Record<string, string>;\n};\n\nexport type Span = {\n type: 'otel-span';\n name: string;\n kind: SpanKind;\n traceId: string;\n spanId: string;\n traceFlags: number;\n traceState?: string;\n parentSpanContext?: { traceId: string; spanId: string; traceFlags: number };\n startTime: HrTime;\n endTime: HrTime;\n status: SpanStatus;\n attributes: Attributes;\n events: { name: string; time: HrTime; attributes?: Attributes; droppedAttributesCount?: number }[];\n links: { context: { traceId: string; spanId: string; traceFlags: number }; attributes?: Attributes }[];\n droppedAttributesCount: number;\n droppedEventsCount: number;\n droppedLinksCount: number;\n instrumentationScope: { name: string; version?: string };\n};\n\nexport type Message = Init | Span;\n\nexport type Handle = { post: (record: Span) => void };\n\nexport const serializeReadableSpan = (span: ReadableSpan): Span => {\n const spanContext = span.spanContext();\n return {\n type: 'otel-span',\n name: span.name,\n kind: span.kind,\n traceId: spanContext.traceId,\n spanId: spanContext.spanId,\n traceFlags: spanContext.traceFlags,\n traceState: spanContext.traceState?.serialize(),\n parentSpanContext: span.parentSpanContext\n ? {\n traceId: span.parentSpanContext.traceId,\n spanId: span.parentSpanContext.spanId,\n traceFlags: span.parentSpanContext.traceFlags,\n }\n : undefined,\n startTime: span.startTime,\n endTime: span.endTime,\n status: span.status,\n attributes: { ...span.attributes },\n events: span.events.map((event) => ({\n name: event.name,\n time: event.time,\n attributes: event.attributes ? { ...event.attributes } : undefined,\n droppedAttributesCount: event.droppedAttributesCount,\n })),\n links: span.links.map((link) => ({\n context: {\n traceId: link.context.traceId,\n spanId: link.context.spanId,\n traceFlags: link.context.traceFlags,\n },\n attributes: link.attributes ? { ...link.attributes } : undefined,\n })),\n droppedAttributesCount: span.droppedAttributesCount,\n droppedEventsCount: span.droppedEventsCount,\n droppedLinksCount: span.droppedLinksCount,\n instrumentationScope: {\n name: span.instrumentationScope.name,\n version: span.instrumentationScope.version,\n },\n };\n};\n\nexport class PortSpanProcessor implements SpanProcessor {\n constructor(private readonly _post: (record: Span) => void) {}\n\n onStart(_span: SdkSpan, _parentContext: Context): void {}\n\n onEnd(span: ReadableSpan): void {\n this._post(serializeReadableSpan(span));\n }\n\n async shutdown(): Promise<void> {}\n\n async forceFlush(): Promise<void> {}\n}\n\nexport type Options = {\n exporter?: SpanExporter;\n /** Overrides the default tail-sampling rules; pass `{ ratio: 1 }` to export everything. */\n sampling?: TailSampling.Options;\n};\n\nexport class Sink {\n readonly #resource: Resource;\n readonly #processors: BatchSpanProcessor[];\n readonly #sampler: TailSampling.TailSampler;\n\n constructor(init: Init, options: Options = {}) {\n this.#sampler = new TailSampling.TailSampler(options.sampling);\n this.#resource = defaultResource().merge(resourceFromAttributes(init.resourceAttributes));\n this.#processors = init.destinations.map(\n (destination) =>\n new BatchSpanProcessor(\n options.exporter ??\n new OTLPTraceExporter({\n url: signalUrl(destination, 'traces'),\n headers: destination.headers,\n concurrencyLimit: 10,\n }),\n ),\n );\n }\n\n /** Keeps the rest of a trace something outside the span stream vouched for, e.g. a warning log. */\n promote(traceId: string): void {\n this.#sampler.promote(traceId);\n }\n\n append(record: Span): void {\n if (\n !this.#sampler.keep({\n traceId: record.traceId,\n status: record.status,\n attributes: record.attributes,\n durationMs: TailSampling.hrTimeToMs(hrTimeDuration(record.startTime, record.endTime)),\n })\n ) {\n return;\n }\n const span = this.#materialize(record);\n for (const processor of this.#processors) {\n processor.onEnd(span);\n }\n }\n\n async flush(): Promise<void> {\n await Promise.all(this.#processors.map((processor) => processor.forceFlush()));\n }\n\n async close(): Promise<void> {\n await Promise.all(this.#processors.map((processor) => processor.shutdown()));\n }\n\n #materialize(record: Span): ReadableSpan {\n const spanContext: SpanContext = {\n traceId: record.traceId,\n spanId: record.spanId,\n traceFlags: record.traceFlags,\n traceState: record.traceState !== undefined ? new TraceState(record.traceState) : undefined,\n };\n const links: Link[] = record.links.map((link) => ({\n context: { ...link.context },\n attributes: link.attributes,\n }));\n return {\n name: record.name,\n kind: record.kind,\n spanContext: () => spanContext,\n parentSpanContext: record.parentSpanContext ? { ...record.parentSpanContext } : undefined,\n startTime: record.startTime,\n endTime: record.endTime,\n status: record.status,\n attributes: AiContent.withoutAiContent(record.attributes),\n links,\n events: record.events.map((event) => ({\n name: event.name,\n time: event.time,\n attributes: event.attributes,\n droppedAttributesCount: event.droppedAttributesCount,\n })),\n duration: hrTimeDuration(record.startTime, record.endTime),\n ended: true,\n resource: this.#resource,\n instrumentationScope: { ...record.instrumentationScope },\n droppedAttributesCount: record.droppedAttributesCount,\n droppedEventsCount: record.droppedEventsCount,\n droppedLinksCount: record.droppedLinksCount,\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAcA,IAAa,wCAA6C,IAAI,IAAI;CAChE,eAAe,GAAG;CAClB,eAAe,GAAG;CAClB,eAAe,GAAG;AACpB,CAAC;AAED,IAAa,oBAAoB,eAC/B,OAAO,YAAY,OAAO,QAAQ,UAAU,CAAC,CAAC,QAAQ,CAAC,SAAS,CAAC,sBAAsB,IAAI,GAAG,CAAC,CAAC;;AAGlG,IAAa,kBAAkB,SAC7B,OAAO,OAAO,MAAM,EAAE,YAA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F,WAAW,OAAO;GAClB,SAAS,OAAO;GAChB,QAAQ,OAAO;GACf,YAAYC,iBAA2B,OAAO,UAAU;GACxD;GACA,QAAQ,OAAO,OAAO,KAAK,WAAW;IACpC,MAAM,MAAM;IACZ,MAAM,MAAM;IACZ,YAAY,MAAM;IAClB,wBAAwB,MAAM;GAChC,EAAE;GACF,UAAU,eAAe,OAAO,WAAW,OAAO,OAAO;GACzD,OAAO;GACP,UAAU,KAAK;GACf,sBAAsB,EAAE,GAAG,OAAO,qBAAqB;GACvD,wBAAwB,OAAO;GAC/B,oBAAoB,OAAO;GAC3B,mBAAmB,OAAO;EAC5B;CACF;AACF"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { n as PREFIX, r as handle } from "../../chunk-OtelProxy.mjs";
|
package/dist/lib/index.mjs
CHANGED
|
@@ -4,6 +4,7 @@ import { t as Observability_exports } from "./chunk-Observability.mjs";
|
|
|
4
4
|
import { t as AiObservability_exports } from "./chunk-AiObservability.mjs";
|
|
5
5
|
import { t as OtelLogSink_exports } from "./chunk-OtelLogSink.mjs";
|
|
6
6
|
import { t as OtelMetricsSink_exports } from "./chunk-OtelMetricsSink.mjs";
|
|
7
|
+
import { t as OtelProxy_exports } from "./chunk-OtelProxy.mjs";
|
|
7
8
|
import { t as ObservabilityClientProvider_exports } from "./chunk-ObservabilityClientProvider.mjs";
|
|
8
9
|
import { t as ObservabilityProvider_exports } from "./chunk-ObservabilityProvider.mjs";
|
|
9
|
-
export { AiObservability_exports as AiObservability, Observability_exports as Observability, ObservabilityClientProvider_exports as ObservabilityClientProvider, ObservabilityExtension_exports as ObservabilityExtension, ObservabilityProvider_exports as ObservabilityProvider, OtelLogSink_exports as OtelLogSink, OtelMetricsSink_exports as OtelMetricsSink, OtelSpanSink_exports as OtelSpanSink };
|
|
10
|
+
export { AiObservability_exports as AiObservability, Observability_exports as Observability, ObservabilityClientProvider_exports as ObservabilityClientProvider, ObservabilityExtension_exports as ObservabilityExtension, ObservabilityProvider_exports as ObservabilityProvider, OtelLogSink_exports as OtelLogSink, OtelMetricsSink_exports as OtelMetricsSink, OtelProxy_exports as OtelProxy, OtelSpanSink_exports as OtelSpanSink };
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/** The route a client's OTel exporter posts to on the deployment that serves it. */
|
|
2
|
+
export declare const PREFIX = "/api/otel";
|
|
3
|
+
export type Options = {
|
|
4
|
+
/** PostHog's OTLP base URL, e.g. `https://eu.i.posthog.com/i`. */
|
|
5
|
+
url?: string;
|
|
6
|
+
/** The project token, sent upstream as the bearer token so it never reaches the client. */
|
|
7
|
+
token?: string;
|
|
8
|
+
/** Origins admitted besides the deployment's own, such as a native build's. */
|
|
9
|
+
extraOrigins?: ReadonlySet<string>;
|
|
10
|
+
/** Largest body forwarded, in bytes. */
|
|
11
|
+
maxBodySize: number;
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* Forwards an OTLP request on `/api/otel/v1/{traces,logs,metrics}` to PostHog with the project token.
|
|
15
|
+
* Returns `undefined` for any other path, so the caller can route it elsewhere.
|
|
16
|
+
*/
|
|
17
|
+
export declare const handle: (request: Request, options: Options) => Promise<Response> | undefined;
|
|
18
|
+
//# sourceMappingURL=OtelProxy.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"OtelProxy.d.ts","sourceRoot":"","sources":["../../../../../src/extensions/otel/OtelProxy.ts"],"names":[],"mappings":"AAQA,oFAAoF;AACpF,eAAO,MAAM,MAAM,cAAc,CAAC;AAIlC,MAAM,MAAM,OAAO,GAAG;IACpB,kEAAkE;IAClE,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,2FAA2F;IAC3F,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,+EAA+E;IAC/E,YAAY,CAAC,EAAE,WAAW,CAAC,MAAM,CAAC,CAAC;IACnC,wCAAwC;IACxC,WAAW,EAAE,MAAM,CAAC;CACrB,CAAC;AAiBF;;;GAGG;AACH,eAAO,MAAM,MAAM,YAAa,OAAO,WAAW,OAAO,KAAG,OAAO,CAAC,QAAQ,CAAC,GAAG,SAI/E,CAAC"}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
//
|
|
2
|
+
// Copyright 2026 DXOS.org
|
|
3
|
+
//
|
|
4
|
+
// @import-as-namespace
|
|
5
|
+
// Cloudflare Workers import this through its own subpath, so it uses only the Fetch API.
|
|
6
|
+
/** The route a client's OTel exporter posts to on the deployment that serves it. */
|
|
7
|
+
export const PREFIX = '/api/otel';
|
|
8
|
+
const SIGNALS = new Set(['/v1/traces', '/v1/logs', '/v1/metrics']);
|
|
9
|
+
/** A POST always carries `Origin`, so a missing one is refused. */
|
|
10
|
+
const isAllowedOrigin = (request, origin, extraOrigins) => origin !== null && (origin === new URL(request.url).origin || extraOrigins?.has(origin) === true);
|
|
11
|
+
const corsHeaders = (request, origin, extraOrigins) => ({
|
|
12
|
+
'Access-Control-Allow-Origin': isAllowedOrigin(request, origin, extraOrigins) ? (origin ?? '') : '',
|
|
13
|
+
'Access-Control-Allow-Methods': 'POST, OPTIONS',
|
|
14
|
+
'Access-Control-Allow-Headers': 'Content-Type, Content-Encoding',
|
|
15
|
+
'Vary': 'Origin',
|
|
16
|
+
});
|
|
17
|
+
/**
|
|
18
|
+
* Forwards an OTLP request on `/api/otel/v1/{traces,logs,metrics}` to PostHog with the project token.
|
|
19
|
+
* Returns `undefined` for any other path, so the caller can route it elsewhere.
|
|
20
|
+
*/
|
|
21
|
+
export const handle = (request, options) => {
|
|
22
|
+
const { pathname } = new URL(request.url);
|
|
23
|
+
const signal = pathname.startsWith(`${PREFIX}/`) ? pathname.slice(PREFIX.length) : undefined;
|
|
24
|
+
return signal && SIGNALS.has(signal) ? forward(request, options, signal) : undefined;
|
|
25
|
+
};
|
|
26
|
+
const forward = async (request, { url, token, extraOrigins, maxBodySize }, signal) => {
|
|
27
|
+
const origin = request.headers.get('Origin');
|
|
28
|
+
const cors = corsHeaders(request, origin, extraOrigins);
|
|
29
|
+
if (request.method === 'OPTIONS') {
|
|
30
|
+
return new Response(null, { status: 204, headers: cors });
|
|
31
|
+
}
|
|
32
|
+
if (request.method !== 'POST') {
|
|
33
|
+
return new Response('Method not allowed', { status: 405, headers: cors });
|
|
34
|
+
}
|
|
35
|
+
if (!isAllowedOrigin(request, origin, extraOrigins)) {
|
|
36
|
+
return new Response('Forbidden', { status: 403, headers: cors });
|
|
37
|
+
}
|
|
38
|
+
if (!url || !token) {
|
|
39
|
+
return new Response('OTel proxy not configured', { status: 503, headers: cors });
|
|
40
|
+
}
|
|
41
|
+
if (!request.body) {
|
|
42
|
+
return new Response('Empty body', { status: 400, headers: cors });
|
|
43
|
+
}
|
|
44
|
+
const headers = {
|
|
45
|
+
'Content-Type': request.headers.get('Content-Type') ?? 'application/json',
|
|
46
|
+
'Authorization': `Bearer ${token}`,
|
|
47
|
+
};
|
|
48
|
+
for (const name of ['Content-Encoding', 'Content-Length']) {
|
|
49
|
+
const value = request.headers.get(name);
|
|
50
|
+
if (value) {
|
|
51
|
+
headers[name] = value;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
let size = 0;
|
|
55
|
+
let tooLarge = false;
|
|
56
|
+
const { readable, writable } = new TransformStream({
|
|
57
|
+
transform: (chunk, controller) => {
|
|
58
|
+
size += chunk.byteLength;
|
|
59
|
+
if (size > maxBodySize) {
|
|
60
|
+
tooLarge = true;
|
|
61
|
+
controller.error(new Error('Payload too large'));
|
|
62
|
+
}
|
|
63
|
+
else {
|
|
64
|
+
controller.enqueue(chunk);
|
|
65
|
+
}
|
|
66
|
+
},
|
|
67
|
+
});
|
|
68
|
+
const piped = request.body.pipeTo(writable).catch(() => { });
|
|
69
|
+
let upstream;
|
|
70
|
+
try {
|
|
71
|
+
upstream = await fetch(`${url.replace(/\/$/, '')}${signal}`, { method: 'POST', headers, body: readable });
|
|
72
|
+
}
|
|
73
|
+
catch {
|
|
74
|
+
// An aborted body stream rejects the fetch, as does an unreachable upstream. A fetch that failed before reading
|
|
75
|
+
// leaves the pipe blocked on backpressure, so the body is cancelled to end it.
|
|
76
|
+
await readable.cancel().catch(() => { });
|
|
77
|
+
}
|
|
78
|
+
await piped;
|
|
79
|
+
if (tooLarge) {
|
|
80
|
+
return new Response('Payload too large', { status: 413, headers: cors });
|
|
81
|
+
}
|
|
82
|
+
if (!upstream) {
|
|
83
|
+
return new Response('Bad gateway', { status: 502, headers: cors });
|
|
84
|
+
}
|
|
85
|
+
return new Response(upstream.body, {
|
|
86
|
+
status: upstream.status,
|
|
87
|
+
headers: { 'Content-Type': upstream.headers.get('Content-Type') ?? 'application/json', ...cors },
|
|
88
|
+
});
|
|
89
|
+
};
|
|
90
|
+
//# sourceMappingURL=OtelProxy.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"OtelProxy.js","sourceRoot":"","sources":["../../../../../src/extensions/otel/OtelProxy.ts"],"names":[],"mappings":"AAAA,EAAE;AACF,0BAA0B;AAC1B,EAAE;AAEF,uBAAuB;AAEvB,yFAAyF;AAEzF,oFAAoF;AACpF,MAAM,CAAC,MAAM,MAAM,GAAG,WAAW,CAAC;AAElC,MAAM,OAAO,GAAG,IAAI,GAAG,CAAC,CAAC,YAAY,EAAE,UAAU,EAAE,aAAa,CAAC,CAAC,CAAC;AAanE,mEAAmE;AACnE,MAAM,eAAe,GAAG,CAAC,OAAgB,EAAE,MAAqB,EAAE,YAAkC,EAAW,EAAE,CAC/G,MAAM,KAAK,IAAI,IAAI,CAAC,MAAM,KAAK,IAAI,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,IAAI,YAAY,EAAE,GAAG,CAAC,MAAM,CAAC,KAAK,IAAI,CAAC,CAAC;AAEpG,MAAM,WAAW,GAAG,CAClB,OAAgB,EAChB,MAAqB,EACrB,YAAkC,EACV,EAAE,CAAC,CAAC;IAC5B,6BAA6B,EAAE,eAAe,CAAC,OAAO,EAAE,MAAM,EAAE,YAAY,CAAC,CAAC,CAAC,CAA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