@osfactory/otel-hook 0.13.2 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/README.md +43 -0
  2. package/dist/{adapter-DyCb7y1N.d.ts → adapter-D5R8lhfl.d.ts} +1 -1
  3. package/dist/cli.js +427 -37
  4. package/dist/cli.js.map +1 -1
  5. package/dist/config.d.ts +30 -4
  6. package/dist/config.js +161 -9
  7. package/dist/config.js.map +1 -1
  8. package/dist/{destinations-C4sSKjDO.d.ts → destinations-2KrcRslo.d.ts} +92 -2
  9. package/dist/{export-destinations-BjRXDots.d.ts → export-destinations-DvoH4QOe.d.ts} +101 -9
  10. package/dist/{hook-CKLpgrYP.d.ts → hook-DVK8Don-.d.ts} +4 -4
  11. package/dist/index.d.ts +10 -10
  12. package/dist/index.js +424 -36
  13. package/dist/index.js.map +1 -1
  14. package/dist/install.d.ts +3 -3
  15. package/dist/integration.d.ts +7 -7
  16. package/dist/integration.js +376 -34
  17. package/dist/integration.js.map +1 -1
  18. package/dist/lifecycle.js +1 -1
  19. package/dist/lifecycle.js.map +1 -1
  20. package/dist/{payload-DLK7QaBB.d.ts → payload-D4r71EL-.d.ts} +1 -1
  21. package/dist/privacy.d.ts +2 -2
  22. package/dist/privacy.js +42 -1
  23. package/dist/privacy.js.map +1 -1
  24. package/dist/providers.d.ts +8 -8
  25. package/dist/{registry-DM-4YvIA.d.ts → registry-DOJh9mzB.d.ts} +2 -2
  26. package/dist/runtime.d.ts +5 -5
  27. package/dist/runtime.js +128 -2
  28. package/dist/runtime.js.map +1 -1
  29. package/dist/{schema-CD61uW99.d.ts → schema-oRsbo7WO.d.ts} +45 -0
  30. package/dist/{service-CbI9CObT.d.ts → service-DySC7KQM.d.ts} +6 -1
  31. package/dist/telemetry.d.ts +5 -4
  32. package/dist/telemetry.js +285 -15
  33. package/dist/telemetry.js.map +1 -1
  34. package/dist/testing.d.ts +5 -5
  35. package/dist/testing.js +128 -2
  36. package/dist/testing.js.map +1 -1
  37. package/package.json +1 -1
package/dist/install.d.ts CHANGED
@@ -1,15 +1,15 @@
1
- import { d as AntigravityHookEventName, m as ClaudeHookEventName, n as CodexHookEventName, o as CursorHookEventName, s as GeminiHookEventName, q as GEMINI_PROVIDER_ID, b as ANTIGRAVITY_PROVIDER_ID, C as CLAUDE_CODE_PROVIDER_ID, h as CODEX_PROVIDER_ID, k as CURSOR_PROVIDER_ID } from './payload-DLK7QaBB.js';
1
+ import { d as AntigravityHookEventName, m as ClaudeHookEventName, n as CodexHookEventName, o as CursorHookEventName, s as GeminiHookEventName, q as GEMINI_PROVIDER_ID, b as ANTIGRAVITY_PROVIDER_ID, C as CLAUDE_CODE_PROVIDER_ID, h as CODEX_PROVIDER_ID, k as CURSOR_PROVIDER_ID } from './payload-D4r71EL-.js';
2
2
  import { C as Clock } from './ports-DhpSDIkp.js';
3
3
  import 'zod';
4
4
  import './primitives-CJ8-rn-f.js';
5
- import './adapter-DyCb7y1N.js';
5
+ import './adapter-D5R8lhfl.js';
6
6
  import './errors.js';
7
7
  import './taxonomy-DwhTtuWd.js';
8
8
  import './events-fcomX6d5.js';
9
9
  import './identity-BrVBs901.js';
10
10
  import './policy-CimmCfRp.js';
11
11
  import './content-M9xIKG7h.js';
12
- import './service-CbI9CObT.js';
12
+ import './service-DySC7KQM.js';
13
13
 
14
14
  /**
15
15
  * Pure merge/removal engine for the "nested command hooks" configuration family.
@@ -1,13 +1,13 @@
1
- import { O as OtelHookConfig } from './schema-CD61uW99.js';
1
+ import { O as OtelHookConfig } from './schema-oRsbo7WO.js';
2
2
  import { OverallHealth } from './diagnostics.js';
3
3
  import { OtelHookErrorInfo } from './errors.js';
4
4
  import { DeliveryClaimOutcome, UsageAccumulatorSnapshot, LifecycleCleanupReport, CallbackDeduplicator, UsageAccumulator, SpanCorrelator, MetricSeriesStore, LifecycleJanitor } from './lifecycle.js';
5
- import { P as PrivacyService } from './service-CbI9CObT.js';
6
- import { P as ProviderRegistry } from './registry-DM-4YvIA.js';
7
- import { a as DeliveryOrigin, c as DeliveryUnavailableReason, H as HookIngestInput, e as HookIngestOutcome, U as UsageObservation, O as OtelHook } from './hook-CKLpgrYP.js';
5
+ import { P as PrivacyService } from './service-DySC7KQM.js';
6
+ import { P as ProviderRegistry } from './registry-DOJh9mzB.js';
7
+ import { a as DeliveryOrigin, c as DeliveryUnavailableReason, H as HookIngestInput, e as HookIngestOutcome, U as UsageObservation, O as OtelHook } from './hook-DVK8Don-.js';
8
8
  import { C as Clock, I as IdGenerator, d as Logger, W as WorktreeLocator, P as PayloadEnricher, S as SessionContextReader } from './ports-DhpSDIkp.js';
9
9
  import { F as FilesystemStateStore } from './filesystem-store-B3CpiIRl.js';
10
- import { w as OtlpTelemetrySink, t as OtlpLogTelemetrySink, d as DurableSpool, D as DurableLogSpool, E as ExportDestinationSinks, B as SkippedExportDestination } from './export-destinations-BjRXDots.js';
10
+ import { y as OtlpTelemetrySink, v as OtlpLogTelemetrySink, f as DurableSpool, b as DurableLogSpool, E as ExportDestinationSinks, I as SkippedExportDestination } from './export-destinations-DvoH4QOe.js';
11
11
  import 'zod';
12
12
  import './primitives-CJ8-rn-f.js';
13
13
  import './taxonomy-DwhTtuWd.js';
@@ -19,10 +19,10 @@ import '@opentelemetry/resources';
19
19
  import '@opentelemetry/sdk-trace';
20
20
  import './content-M9xIKG7h.js';
21
21
  import './policy-CimmCfRp.js';
22
- import './adapter-DyCb7y1N.js';
22
+ import './adapter-D5R8lhfl.js';
23
23
  import './identity-BrVBs901.js';
24
24
  import './keys-Dej5bN3L.js';
25
- import './destinations-C4sSKjDO.js';
25
+ import './destinations-2KrcRslo.js';
26
26
  import '@opentelemetry/sdk-logs';
27
27
 
28
28
  /**
@@ -153,6 +153,60 @@ var OTLP_HEADER_VARIABLES = Object.freeze({
153
153
  logs: "OTEL_EXPORTER_OTLP_LOGS_HEADERS"
154
154
  });
155
155
 
156
+ // src/config/repository-key.ts
157
+ var ATTR_VCS_REPOSITORY_URL_FULL = "vcs.repository.url.full";
158
+ var MAX_REPOSITORY_REFERENCE_LENGTH = 2048;
159
+ var SCHEME_PATTERN = /^[a-z][a-z0-9+.-]*:\/\//i;
160
+ var SCP_LIKE_PATTERN = /^(?:[^@/\s]+@)?([^:/\s]+):(?!\/\/)(.+)$/;
161
+ var trimTrailingSlashes = (value) => {
162
+ let end = value.length;
163
+ while (end > 0 && value.charCodeAt(end - 1) === 47) end -= 1;
164
+ return value.slice(0, end);
165
+ };
166
+ var keyOf = (host, pathname) => {
167
+ const withoutSlashes = trimTrailingSlashes(pathname);
168
+ const cleanedPath = trimTrailingSlashes(
169
+ withoutSlashes.toLowerCase().endsWith(".git") ? withoutSlashes.slice(0, -4) : withoutSlashes
170
+ );
171
+ if (host.length === 0 || cleanedPath.length === 0 || cleanedPath === "/") {
172
+ return void 0;
173
+ }
174
+ const withSlash = cleanedPath.startsWith("/") ? cleanedPath : `/${cleanedPath}`;
175
+ return `${host}${withSlash}`.toLowerCase();
176
+ };
177
+ var normalizeRepositoryKey = (reference) => {
178
+ const trimmed = reference.trim();
179
+ if (trimmed.length === 0 || trimmed.length > MAX_REPOSITORY_REFERENCE_LENGTH) {
180
+ return void 0;
181
+ }
182
+ if (SCHEME_PATTERN.test(trimmed)) {
183
+ let url;
184
+ try {
185
+ url = new URL(trimmed);
186
+ } catch {
187
+ return void 0;
188
+ }
189
+ if (url.protocol === "file:") {
190
+ return void 0;
191
+ }
192
+ return keyOf(url.hostname, url.pathname);
193
+ }
194
+ if (trimmed.startsWith("/") || trimmed.startsWith(".") || trimmed.includes("\\")) {
195
+ return void 0;
196
+ }
197
+ const scp = SCP_LIKE_PATTERN.exec(trimmed);
198
+ if (scp !== null && !trimmed.split(":")[0]?.includes("/")) {
199
+ const [, host, pathPart] = scp;
200
+ return host === void 0 || pathPart === void 0 ? void 0 : keyOf(host, pathPart);
201
+ }
202
+ try {
203
+ const url = new URL(`https://${trimmed}`);
204
+ return keyOf(url.hostname, url.pathname);
205
+ } catch {
206
+ return void 0;
207
+ }
208
+ };
209
+
156
210
  // src/config/destinations.ts
157
211
  var DEFAULT_DESTINATION_NAME = "default";
158
212
  var DESTINATION_NAME_PATTERN = /^[a-z0-9][a-z0-9_-]{0,62}$/;
@@ -171,6 +225,30 @@ var headerValueSchema = z3.string().min(1).max(MAX_HEADER_VALUE_LENGTH).refine(
171
225
  "an env: header reference must name an environment variable, e.g. env:COLLECTOR_TOKEN"
172
226
  );
173
227
  var endpointSchema = z3.string().url().max(2048);
228
+ var MAX_DESTINATION_SCOPES = 64;
229
+ var MAX_SCOPE_REPOSITORIES = 256;
230
+ var ALL_REPOSITORIES = "*";
231
+ var repositoryReferenceSchema = z3.string().min(1).max(MAX_REPOSITORY_REFERENCE_LENGTH).refine(
232
+ (value) => normalizeRepositoryKey(value) !== void 0,
233
+ "not a repository URL: use https://host/owner/repo, git@host:owner/repo.git, or host/owner/repo"
234
+ );
235
+ var destinationScopeSchema = z3.strictObject({
236
+ /**
237
+ * Repository URLs (any spelling of the remote; compared by host and path,
238
+ * case-insensitively, without `.git`), or `"*"` for every record that names
239
+ * a repository. A record that names none never matches a scope.
240
+ */
241
+ repositories: z3.union([
242
+ z3.literal(ALL_REPOSITORIES),
243
+ z3.array(repositoryReferenceSchema).min(1).max(MAX_SCOPE_REPOSITORIES).readonly()
244
+ ]),
245
+ /** Signals sent for these repositories. Default: every signal the destination takes. */
246
+ signals: z3.array(exportSignalSchema).min(1).max(3).readonly().optional(),
247
+ /** Content disclosure for these repositories, never above `privacy.contentMode`. Default: unchanged. */
248
+ contentMode: contentModeSchema.optional(),
249
+ /** False leaves `session.id` off metric data points for these repositories. Default true. */
250
+ includeSessionId: z3.boolean().optional()
251
+ });
174
252
  var exportDestinationSchema = z3.strictObject({
175
253
  /** Unique, lowercase, filesystem-safe. `default` is reserved for the single-endpoint settings. */
176
254
  name: z3.string().regex(DESTINATION_NAME_PATTERN, "destination names are lowercase letters, digits, _ and -"),
@@ -204,7 +282,15 @@ var exportDestinationSchema = z3.strictObject({
204
282
  * opt-in for content-bearing records leaving the host. `metrics` is never on by
205
283
  * default: a destination receives hook-derived metrics only when it lists them.
206
284
  */
207
- signals: z3.array(exportSignalSchema).min(1).max(3).readonly().optional()
285
+ signals: z3.array(exportSignalSchema).min(1).max(3).readonly().optional(),
286
+ /**
287
+ * Per-repository filter. Absent: every record goes to this destination, as
288
+ * before scopes existed. Present: a record goes only when its repository
289
+ * (`vcs.repository.url.full`) matches a scope — the first matching scope
290
+ * decides its signals, content mode, and session id — and a record that
291
+ * names no repository is not sent here at all.
292
+ */
293
+ scopes: z3.array(destinationScopeSchema).min(1).max(MAX_DESTINATION_SCOPES).readonly().optional()
208
294
  }).refine(
209
295
  (destination) => destination.endpoint !== void 0 || destination.tracesEndpoint !== void 0 || destination.logsEndpoint !== void 0 || destination.metricsEndpoint !== void 0,
210
296
  "a destination needs an endpoint, or a tracesEndpoint / logsEndpoint / metricsEndpoint"
@@ -248,6 +334,32 @@ var effectiveSpoolPolicy = (exporter) => ({
248
334
  maxAgeMillis: exporter.spool?.maxAgeMillis ?? DEFAULT_SPOOL_POLICY.maxAgeMillis,
249
335
  maxBatches: exporter.spool?.maxBatches ?? DEFAULT_SPOOL_POLICY.maxBatches
250
336
  });
337
+ var resolveDestinationScopes = (scopes, destinationSignals) => scopes.map((scope) => {
338
+ const listed = scope.signals ?? exportSignalSchema.options;
339
+ return {
340
+ repositories: scope.repositories === ALL_REPOSITORIES ? ALL_REPOSITORIES : new Set(
341
+ scope.repositories.flatMap((reference) => {
342
+ const key = normalizeRepositoryKey(reference);
343
+ return key === void 0 ? [] : [key];
344
+ })
345
+ ),
346
+ signals: {
347
+ traces: destinationSignals.traces && listed.includes("traces"),
348
+ logs: destinationSignals.logs && listed.includes("logs"),
349
+ metrics: destinationSignals.metrics && listed.includes("metrics")
350
+ },
351
+ ...scope.contentMode === void 0 ? {} : { contentMode: scope.contentMode },
352
+ includeSessionId: scope.includeSessionId ?? true
353
+ };
354
+ });
355
+ var matchDestinationScope = (scopes, repositoryKey) => {
356
+ if (repositoryKey === void 0) {
357
+ return void 0;
358
+ }
359
+ return scopes.find(
360
+ (scope) => scope.repositories === ALL_REPOSITORIES || scope.repositories.has(repositoryKey)
361
+ );
362
+ };
251
363
  var legacyDestination = (exporter) => ({
252
364
  name: DEFAULT_DESTINATION_NAME,
253
365
  source: "exporter",
@@ -272,6 +384,11 @@ var resolveExportDestinations = (exporter) => {
272
384
  continue;
273
385
  }
274
386
  const signals = destination.signals ?? DEFAULT_DESTINATION_SIGNALS;
387
+ const flags = {
388
+ traces: signals.includes("traces"),
389
+ logs: exporter.logs.enabled && signals.includes("logs"),
390
+ metrics: signals.includes("metrics")
391
+ };
275
392
  resolved.push({
276
393
  name: destination.name,
277
394
  source: "destinations",
@@ -280,12 +397,9 @@ var resolveExportDestinations = (exporter) => {
280
397
  ...destination.tracesEndpoint === void 0 ? {} : { tracesEndpoint: destination.tracesEndpoint },
281
398
  ...destination.logsEndpoint === void 0 ? {} : { logsEndpoint: destination.logsEndpoint },
282
399
  ...destination.metricsEndpoint === void 0 ? {} : { metricsEndpoint: destination.metricsEndpoint },
283
- signals: {
284
- traces: signals.includes("traces"),
285
- logs: exporter.logs.enabled && signals.includes("logs"),
286
- metrics: signals.includes("metrics")
287
- },
288
- headers: { ...destination.headers ?? {} }
400
+ signals: flags,
401
+ headers: { ...destination.headers ?? {} },
402
+ ...destination.scopes === void 0 ? {} : { scopes: resolveDestinationScopes(destination.scopes, flags) }
289
403
  });
290
404
  }
291
405
  return resolved;
@@ -2443,7 +2557,7 @@ import {
2443
2557
  } from "@opentelemetry/semantic-conventions/incubating";
2444
2558
 
2445
2559
  // src/version.ts
2446
- var VERSION = "0.13.2";
2560
+ var VERSION = "0.14.0";
2447
2561
 
2448
2562
  // src/telemetry/semconv.ts
2449
2563
  var SCOPE_NAME = "@osfactory/otel-hook";
@@ -2926,6 +3040,17 @@ var planGroup = (group, correlation, correlationAvailable) => {
2926
3040
  };
2927
3041
  var runDiscriminatorOf = (correlation) => correlation?.runSpanIdDiscriminator === void 0 ? void 0 : `run:${correlation.runSpanIdDiscriminator}`;
2928
3042
  var resumedSessionParent = (ref, correlation) => ref.family === "session" && correlation?.runSpanIdDiscriminator !== void 0 ? ref : void 0;
3043
+ var spanEndEdgesOf = (events) => {
3044
+ const layout = layoutBatch(events);
3045
+ const ends = /* @__PURE__ */ new Map();
3046
+ for (const [eventId, groupKey] of layout.groupOf) {
3047
+ const end = layout.groups.get(groupKey)?.end;
3048
+ if (end !== void 0) {
3049
+ ends.set(eventId, end);
3050
+ }
3051
+ }
3052
+ return ends;
3053
+ };
2929
3054
  var canonicalEventTraceIdentities = (events, options = {}) => {
2930
3055
  const layout = layoutBatch(events);
2931
3056
  const correlations = indexCorrelations(options.correlations);
@@ -3493,6 +3618,23 @@ var createUsageAccumulator = (deps) => {
3493
3618
 
3494
3619
  // src/privacy/service.ts
3495
3620
  import { createHash as createHash3 } from "crypto";
3621
+ var DISCLOSURE_RANK = Object.freeze({
3622
+ omitted: 0,
3623
+ masked: 1,
3624
+ redacted: 2,
3625
+ raw: 3
3626
+ });
3627
+ var WHITESPACE = /\s/u;
3628
+ var withoutTrailingToken = (text) => {
3629
+ let end = text.length;
3630
+ while (end > 0) {
3631
+ const low = text.charCodeAt(end - 1);
3632
+ const width = end >= 2 && low >= 56320 && low <= 57343 ? 2 : 1;
3633
+ if (WHITESPACE.test(text.slice(end - width, end))) break;
3634
+ end -= width;
3635
+ }
3636
+ return text.slice(0, end);
3637
+ };
3496
3638
  var compilePatterns = (sources, flags) => {
3497
3639
  const compiled = [];
3498
3640
  for (const source of sources) {
@@ -3830,7 +3972,31 @@ var createPrivacyService = (policyInput) => {
3830
3972
  flattenToAttributes,
3831
3973
  sanitizeAttributes,
3832
3974
  sanitizeExtensions,
3833
- boundString
3975
+ boundString,
3976
+ restrictContent: (fact, mode) => {
3977
+ const target = CONTENT_MODE_DISCLOSURE[mode];
3978
+ if (fact.text === void 0 || DISCLOSURE_RANK[fact.disclosure] <= DISCLOSURE_RANK[target]) {
3979
+ return fact;
3980
+ }
3981
+ const { text, ...rest } = fact;
3982
+ switch (target) {
3983
+ case "omitted":
3984
+ return { ...rest, disclosure: "omitted", truncated: false };
3985
+ case "masked":
3986
+ return { ...rest, disclosure: "masked", text: maskText(text) };
3987
+ case "redacted": {
3988
+ const redacted = redactSecretSpans(fact.truncated ? withoutTrailingToken(text) : text);
3989
+ return {
3990
+ ...rest,
3991
+ disclosure: "redacted",
3992
+ text: redacted.text,
3993
+ secretsRedacted: fact.secretsRedacted + redacted.count
3994
+ };
3995
+ }
3996
+ case "raw":
3997
+ return fact;
3998
+ }
3999
+ }
3834
4000
  };
3835
4001
  };
3836
4002
 
@@ -9172,6 +9338,101 @@ var createOtlpTraceSink = (options) => {
9172
9338
  };
9173
9339
  };
9174
9340
 
9341
+ // src/telemetry/destination-scope.ts
9342
+ var DISCLOSURE_RANK2 = Object.freeze({
9343
+ omitted: 0,
9344
+ masked: 1,
9345
+ redacted: 2,
9346
+ raw: 3
9347
+ });
9348
+ var omitRestrictedContent = (fact, mode) => {
9349
+ if (fact.text === void 0 || DISCLOSURE_RANK2[fact.disclosure] <= DISCLOSURE_RANK2[CONTENT_MODE_DISCLOSURE[mode]]) {
9350
+ return fact;
9351
+ }
9352
+ const { text, ...rest } = fact;
9353
+ void text;
9354
+ return { ...rest, disclosure: "omitted", truncated: false };
9355
+ };
9356
+ var keyOfValue = (value) => typeof value === "string" ? normalizeRepositoryKey(value) : void 0;
9357
+ var resourceRepositoryKey = (attributes) => keyOfValue(attributes[ATTR_VCS_REPOSITORY_URL_FULL]);
9358
+ var eventRepositoryKey = (event2, fallbackKey) => {
9359
+ const stamped = event2.contextAttributes?.[ATTR_VCS_REPOSITORY_URL_FULL];
9360
+ return stamped === void 0 ? fallbackKey : keyOfValue(stamped);
9361
+ };
9362
+ var pointRepositoryKey = (point, fallbackKey) => {
9363
+ const stamped = point.attributes[ATTR_VCS_REPOSITORY_URL_FULL];
9364
+ return stamped === void 0 ? fallbackKey : keyOfValue(stamped);
9365
+ };
9366
+ var restrictFacts = (facts, mode, restrict) => facts?.map((fact) => restrict(fact, mode));
9367
+ var restrictEventContent = (event2, mode, restrict) => {
9368
+ switch (event2.type) {
9369
+ case "prompt.submitted":
9370
+ return event2.content === void 0 ? event2 : { ...event2, content: restrict(event2.content, mode) };
9371
+ case "generation.start": {
9372
+ const inputContent = restrictFacts(event2.inputContent, mode, restrict);
9373
+ return inputContent === void 0 ? event2 : { ...event2, inputContent };
9374
+ }
9375
+ case "generation.end": {
9376
+ const outputContent = restrictFacts(event2.outputContent, mode, restrict);
9377
+ return outputContent === void 0 ? event2 : { ...event2, outputContent };
9378
+ }
9379
+ case "tool.start":
9380
+ return event2.input === void 0 ? event2 : { ...event2, input: restrict(event2.input, mode) };
9381
+ case "tool.end":
9382
+ return event2.output === void 0 ? event2 : { ...event2, output: restrict(event2.output, mode) };
9383
+ case "error.raised":
9384
+ return event2.message === void 0 ? event2 : { ...event2, message: restrict(event2.message, mode) };
9385
+ default:
9386
+ return event2;
9387
+ }
9388
+ };
9389
+ var routeEventsToScopes = (events, scopes, options) => {
9390
+ const ends = spanEndEdgesOf(events);
9391
+ const traces = [];
9392
+ const logs = [];
9393
+ let unchanged = true;
9394
+ for (const event2 of events) {
9395
+ const anchor = ends.get(event2.eventId) ?? event2;
9396
+ const scope = matchDestinationScope(scopes, eventRepositoryKey(anchor, options.resourceRepositoryKey));
9397
+ if (scope === void 0 || !scope.signals.traces || !scope.signals.logs) {
9398
+ unchanged = false;
9399
+ }
9400
+ if (scope === void 0) {
9401
+ continue;
9402
+ }
9403
+ const restricted = scope.contentMode === void 0 ? event2 : restrictEventContent(event2, scope.contentMode, options.restrict);
9404
+ if (restricted !== event2) {
9405
+ unchanged = false;
9406
+ }
9407
+ if (scope.signals.traces) {
9408
+ traces.push(restricted);
9409
+ }
9410
+ if (scope.signals.logs) {
9411
+ logs.push(restricted);
9412
+ }
9413
+ }
9414
+ return unchanged ? { traces: events, logs: events } : { traces, logs };
9415
+ };
9416
+ var routePointsToScopes = (scopes, pointsFor, options) => {
9417
+ const effective = (scope) => options.includeSessionId && scope.includeSessionId;
9418
+ const kept = [];
9419
+ for (const variant of [true, false]) {
9420
+ if (!scopes.some((scope) => scope.signals.metrics && effective(scope) === variant)) {
9421
+ continue;
9422
+ }
9423
+ for (const point of pointsFor(variant) ?? []) {
9424
+ const scope = matchDestinationScope(scopes, pointRepositoryKey(point, options.fallbackKey));
9425
+ if (scope?.signals.metrics === true && effective(scope) === variant) {
9426
+ kept.push(point);
9427
+ }
9428
+ }
9429
+ }
9430
+ return kept;
9431
+ };
9432
+ var sessionIdVariantsFor = (scopes, includeSessionId) => new Set(
9433
+ scopes.filter((scope) => scope.signals.metrics).map((scope) => includeSessionId && scope.includeSessionId)
9434
+ );
9435
+
9175
9436
  // src/telemetry/signal-fanout.ts
9176
9437
  var createSignalFanout = (options) => {
9177
9438
  const emit = async (events) => {
@@ -9204,14 +9465,20 @@ var createSignalFanout = (options) => {
9204
9465
  };
9205
9466
  var shareCorrelationPerBatch = (correlate) => {
9206
9467
  let pending;
9207
- return (events) => {
9208
- if (pending?.events === events) {
9468
+ const resolve3 = (events) => {
9469
+ if (pending !== void 0 && (pending.events === events || pending.aliases.has(events))) {
9209
9470
  return pending.result;
9210
9471
  }
9211
9472
  const result = correlate(events);
9212
- pending = { events, result };
9473
+ pending = { events, aliases: /* @__PURE__ */ new Set(), result };
9213
9474
  return result;
9214
9475
  };
9476
+ const alias = (subset, batch) => {
9477
+ if (pending?.events === batch && subset !== batch) {
9478
+ pending.aliases.add(subset);
9479
+ }
9480
+ };
9481
+ return Object.assign(resolve3, { alias });
9215
9482
  };
9216
9483
 
9217
9484
  // src/telemetry/export-destinations.ts
@@ -9280,6 +9547,8 @@ var createExportDestinationSinks = (options) => {
9280
9547
  ...options.exporter.endpointDownMillis === void 0 ? {} : { downMillis: options.exporter.endpointDownMillis },
9281
9548
  probeMillis: effectiveExportTimeoutMillis(options.exporter) + 1e3
9282
9549
  });
9550
+ const scopedResourceKey = resourceRepositoryKey(resourceFromExporterPolicy(options.exporter).attributes);
9551
+ const restrict = options.restrictContent ?? omitRestrictedContent;
9283
9552
  for (const destination of resolveExportDestinations(options.exporter)) {
9284
9553
  let headers;
9285
9554
  let logHeaders;
@@ -9369,17 +9638,51 @@ var createExportDestinationSinks = (options) => {
9369
9638
  metrics,
9370
9639
  ...spool === void 0 ? {} : { spool },
9371
9640
  ...logSpool === void 0 ? {} : { logSpool },
9372
- ...metricSpool === void 0 ? {} : { metricSpool }
9641
+ ...metricSpool === void 0 ? {} : { metricSpool },
9642
+ ...destination.scopes === void 0 ? {} : {
9643
+ scopes: destination.scopes,
9644
+ route: (events) => routeEventsToScopes(events, destination.scopes ?? [], {
9645
+ ...scopedResourceKey === void 0 ? {} : { resourceRepositoryKey: scopedResourceKey },
9646
+ restrict
9647
+ })
9648
+ }
9373
9649
  });
9374
9650
  }
9375
9651
  return { destinations, skipped };
9376
9652
  };
9377
- var createDestinationFanout = (destinations) => {
9653
+ var createScopedFanout = (destination, correlate) => {
9654
+ const route = destination.route;
9655
+ const unscoped = createSignalFanout({ traces: destination.traces, logs: destination.logs });
9656
+ if (route === void 0) {
9657
+ return unscoped;
9658
+ }
9659
+ const none = { accepted: 0, rejected: 0, errors: [] };
9660
+ return {
9661
+ ...unscoped,
9662
+ emit: async (events) => {
9663
+ const batch = route(events);
9664
+ if (correlate !== void 0 && (batch.traces.length > 0 || batch.logs.length > 0)) {
9665
+ await correlate(events);
9666
+ correlate.alias(batch.traces, events);
9667
+ correlate.alias(batch.logs, events);
9668
+ }
9669
+ const traces = batch.traces.length === 0 ? none : await destination.traces.emit(batch.traces);
9670
+ const logs = batch.logs.length === 0 ? none : await destination.logs.emit(batch.logs);
9671
+ return {
9672
+ accepted: traces.accepted + logs.accepted,
9673
+ rejected: traces.rejected + logs.rejected,
9674
+ errors: [...traces.errors, ...logs.errors]
9675
+ };
9676
+ }
9677
+ };
9678
+ };
9679
+ var createDestinationFanout = (destinations, options = {}) => {
9378
9680
  const fanouts = destinations.map((destination) => ({
9379
9681
  name: destination.name,
9380
- sink: createSignalFanout({ traces: destination.traces, logs: destination.logs })
9682
+ sink: createScopedFanout(destination, options.correlate)
9381
9683
  }));
9382
- const only = fanouts.length === 1 ? fanouts[0] : void 0;
9684
+ const scoped = destinations.some((destination) => destination.route !== void 0);
9685
+ const only = fanouts.length === 1 && !scoped ? fanouts[0] : void 0;
9383
9686
  if (only !== void 0) {
9384
9687
  return only.sink;
9385
9688
  }
@@ -9500,7 +9803,8 @@ var createHookRuntime = (options) => {
9500
9803
  // has always been governed by.
9501
9804
  allowRawContent: privacy.policy.allowRawContent
9502
9805
  },
9503
- correlate
9806
+ correlate,
9807
+ restrictContent: (fact, mode) => privacy.restrictContent(fact, mode)
9504
9808
  });
9505
9809
  const primary = exportDestinations.destinations[0];
9506
9810
  const traceSink = primary?.traces ?? createOtlpTraceSink({
@@ -9517,7 +9821,7 @@ var createHookRuntime = (options) => {
9517
9821
  });
9518
9822
  const spool = primary?.spool;
9519
9823
  const logSpool = primary?.logSpool;
9520
- const sink = createDestinationFanout(exportDestinations.destinations);
9824
+ const sink = createDestinationFanout(exportDestinations.destinations, { correlate });
9521
9825
  const hookDeps = {
9522
9826
  stateStore,
9523
9827
  config: options.config,
@@ -9558,6 +9862,8 @@ var createHookRuntime = (options) => {
9558
9862
  (destination) => destination.metrics.enabled
9559
9863
  );
9560
9864
  const metricResource = resourceFromExporterPolicy(options.config.exporter);
9865
+ const scopedMetricDestinations = metricDestinations.filter((destination) => destination.scopes !== void 0);
9866
+ const unscopedMetricDestinations = metricDestinations.filter((destination) => destination.scopes === void 0);
9561
9867
  const deliveryRetentionMillis = options.deliveryRetentionMillis ?? lifecycleMaxAge;
9562
9868
  if (deliveryRetentionMillis < staleClaimMillis) {
9563
9869
  logger.warn("delivery retention is shorter than the stale-claim window", {
@@ -9623,28 +9929,63 @@ var createHookRuntime = (options) => {
9623
9929
  turnStarts.set(event2.sessionId, await metricSeries.readTurnStart(event2.sessionId));
9624
9930
  }
9625
9931
  }
9626
- const observations = deriveMetricObservations({
9627
- events: ingest.events,
9628
- usage: ingest.usageObservations,
9629
- resource: metricResource,
9630
- includeSessionId: metricsPolicy.includeSessionId,
9631
- ...generationStarts === void 0 ? {} : { generationStarts },
9632
- turnStart: (sessionId) => turnStarts.get(sessionId)
9633
- });
9634
- if (observations.length === 0) {
9932
+ const scopedRepositoryFallback = scopedMetricDestinations.length === 0 ? void 0 : resourceRepositoryKey(metricResource.attributes);
9933
+ const resourceRepository = metricResource.attributes[ATTR_VCS_REPOSITORY_URL_FULL];
9934
+ const metricEvents = scopedRepositoryFallback === void 0 || typeof resourceRepository !== "string" ? ingest.events : ingest.events.map(
9935
+ (event2) => event2.contextAttributes?.[ATTR_VCS_REPOSITORY_URL_FULL] === void 0 ? {
9936
+ ...event2,
9937
+ contextAttributes: {
9938
+ ...event2.contextAttributes,
9939
+ [ATTR_VCS_REPOSITORY_URL_FULL]: resourceRepository
9940
+ }
9941
+ } : event2
9942
+ );
9943
+ const pointsByVariant = /* @__PURE__ */ new Map();
9944
+ const variants = new Set(
9945
+ unscopedMetricDestinations.length > 0 ? [metricsPolicy.includeSessionId] : []
9946
+ );
9947
+ for (const destination of scopedMetricDestinations) {
9948
+ for (const variant of sessionIdVariantsFor(destination.scopes ?? [], metricsPolicy.includeSessionId)) {
9949
+ variants.add(variant);
9950
+ }
9951
+ }
9952
+ for (const includeSessionId of variants) {
9953
+ const observations = deriveMetricObservations({
9954
+ events: metricEvents,
9955
+ usage: ingest.usageObservations,
9956
+ resource: metricResource,
9957
+ includeSessionId,
9958
+ ...generationStarts === void 0 ? {} : { generationStarts },
9959
+ turnStart: (sessionId) => turnStarts.get(sessionId)
9960
+ });
9961
+ if (observations.length === 0) {
9962
+ continue;
9963
+ }
9964
+ pointsByVariant.set(
9965
+ includeSessionId,
9966
+ metricsPolicy.temporality === "delta" ? aggregateDeltaPoints(observations, clock.now()) : await metricSeries.recordCumulative(observations, {
9967
+ perSession: includeSessionId,
9968
+ ...deliveryToken === void 0 ? {} : { deliveryToken }
9969
+ })
9970
+ );
9971
+ }
9972
+ if (pointsByVariant.size === 0) {
9635
9973
  return void 0;
9636
9974
  }
9637
- const points = metricsPolicy.temporality === "delta" ? aggregateDeltaPoints(observations, clock.now()) : await metricSeries.recordCumulative(observations, {
9638
- perSession: metricsPolicy.includeSessionId,
9639
- ...deliveryToken === void 0 ? {} : { deliveryToken }
9640
- });
9641
9975
  const context = agreedContextAttributes(ingest.events);
9642
9976
  const results = await Promise.all(
9643
9977
  metricDestinations.map(async (destination) => {
9644
- const result = await destination.metrics.exportPoints(points, context).catch(
9978
+ const points2 = destination.scopes === void 0 ? pointsByVariant.get(metricsPolicy.includeSessionId) ?? [] : routePointsToScopes(destination.scopes, (variant) => pointsByVariant.get(variant), {
9979
+ fallbackKey: scopedRepositoryFallback,
9980
+ includeSessionId: metricsPolicy.includeSessionId
9981
+ });
9982
+ if (points2.length === 0) {
9983
+ return { name: destination.name, accepted: 0, rejected: 0 };
9984
+ }
9985
+ const result = await destination.metrics.exportPoints(points2, context).catch(
9645
9986
  (thrown) => ({
9646
9987
  accepted: 0,
9647
- rejected: points.length,
9988
+ rejected: points2.length,
9648
9989
  errors: [
9649
9990
  errorInfoFromThrown(thrown, { code: "telemetry-export-failure", phase: "export" })
9650
9991
  ]
@@ -9654,7 +9995,8 @@ var createHookRuntime = (options) => {
9654
9995
  return { name: destination.name, accepted: result.accepted, rejected: result.rejected };
9655
9996
  })
9656
9997
  );
9657
- return { points: points.length, destinations: results };
9998
+ const points = Math.max(0, ...[...pointsByVariant.values()].map((variant) => variant.length));
9999
+ return { points, destinations: results };
9658
10000
  } catch (thrown) {
9659
10001
  diagnostics.push(stateDiagnostic(thrown));
9660
10002
  logger.warn("hook-derived metrics could not be recorded for this callback", {});