@osfactory/otel-hook 0.11.0 → 0.12.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 (49) hide show
  1. package/README.md +26 -1
  2. package/dist/{adapter-DiLknaTF.d.ts → adapter-DQiPu8xF.d.ts} +2 -2
  3. package/dist/cli.js +371 -65
  4. package/dist/cli.js.map +1 -1
  5. package/dist/config.d.ts +3 -3
  6. package/dist/config.js +16 -3
  7. package/dist/config.js.map +1 -1
  8. package/dist/{destinations-BIl3gGzx.d.ts → destinations-DvqsPulb.d.ts} +1 -1
  9. package/dist/{events-CSD_YiJ2.d.ts → events-fcomX6d5.d.ts} +22 -0
  10. package/dist/{export-destinations-QWKGGEjk.d.ts → export-destinations-CI7z4n3i.d.ts} +11 -6
  11. package/dist/{filesystem-store-D3SCNmbX.d.ts → filesystem-store-CmnUlj1O.d.ts} +1 -1
  12. package/dist/{hook-BOecWGSz.d.ts → hook-vM_cgqS2.d.ts} +11 -5
  13. package/dist/index.d.ts +14 -14
  14. package/dist/index.js +389 -100
  15. package/dist/index.js.map +1 -1
  16. package/dist/install.d.ts +4 -4
  17. package/dist/install.js +9 -1
  18. package/dist/install.js.map +1 -1
  19. package/dist/integration.d.ts +16 -10
  20. package/dist/integration.js +341 -71
  21. package/dist/integration.js.map +1 -1
  22. package/dist/lifecycle.d.ts +3 -3
  23. package/dist/lifecycle.js +10 -2
  24. package/dist/lifecycle.js.map +1 -1
  25. package/dist/{memory-Cs51jyRk.d.ts → memory-DdU1U91y.d.ts} +2 -2
  26. package/dist/{metric-model-DDnWxL9d.d.ts → metric-model-C9lLqqpI.d.ts} +4 -1
  27. package/dist/model.d.ts +1 -1
  28. package/dist/model.js +9 -1
  29. package/dist/model.js.map +1 -1
  30. package/dist/{payload-ChtrEX6A.d.ts → payload-BT19hiVZ.d.ts} +1 -1
  31. package/dist/{ports-CeqLq31i.d.ts → ports-C3k_5eOQ.d.ts} +33 -2
  32. package/dist/providers.d.ts +10 -10
  33. package/dist/providers.js +10 -1
  34. package/dist/providers.js.map +1 -1
  35. package/dist/{registry-CcJNF3WY.d.ts → registry-gyJqaWmp.d.ts} +2 -2
  36. package/dist/runtime.d.ts +97 -9
  37. package/dist/runtime.js +257 -24
  38. package/dist/runtime.js.map +1 -1
  39. package/dist/{schema-DMnoU1V_.d.ts → schema-SpFM6YQY.d.ts} +24 -1
  40. package/dist/state.d.ts +4 -4
  41. package/dist/state.js +9 -1
  42. package/dist/state.js.map +1 -1
  43. package/dist/telemetry.d.ts +6 -6
  44. package/dist/telemetry.js +77 -22
  45. package/dist/telemetry.js.map +1 -1
  46. package/dist/testing.d.ts +10 -8
  47. package/dist/testing.js +109 -24
  48. package/dist/testing.js.map +1 -1
  49. package/package.json +1 -1
@@ -1,4 +1,5 @@
1
1
  // src/config/schema.ts
2
+ import { isAbsolute } from "path";
2
3
  import { z as z5 } from "zod";
3
4
 
4
5
  // src/model/primitives.ts
@@ -495,13 +496,19 @@ var providersPolicySchema = z5.strictObject({
495
496
  readTranscriptUsage: z5.boolean()
496
497
  }).optional()
497
498
  });
499
+ var sessionContextPolicySchema = z5.strictObject({
500
+ /** Absolute path of the context directory. */
501
+ dir: z5.string().min(1).max(4096).refine((value) => isAbsolute(value), { message: "must be an absolute path" })
502
+ });
498
503
  var otelHookConfigSchema = z5.strictObject({
499
504
  exporter: exporterPolicySchema,
500
505
  privacy: privacyPolicySchema,
501
506
  detection: detectionPolicySchema,
502
507
  diagnostics: diagnosticsPolicySchema,
503
508
  /** Optional so a hand-built configuration from before it existed stays valid. */
504
- providers: providersPolicySchema.optional()
509
+ providers: providersPolicySchema.optional(),
510
+ /** Optional: absent means no session context is read. */
511
+ sessionContext: sessionContextPolicySchema.optional()
505
512
  });
506
513
  var otelHookConfigPatchSchema = z5.strictObject({
507
514
  // `logs` is unwrapped and re-partialled for the same reason `privacy.limits` is:
@@ -517,7 +524,8 @@ var otelHookConfigPatchSchema = z5.strictObject({
517
524
  diagnostics: diagnosticsPolicySchema.partial().optional(),
518
525
  providers: z5.strictObject({
519
526
  claudeCode: z5.strictObject({ readTranscriptUsage: z5.boolean() }).partial().optional()
520
- }).partial().optional()
527
+ }).partial().optional(),
528
+ sessionContext: sessionContextPolicySchema.partial().optional()
521
529
  });
522
530
  var DEFAULT_EXPORTER_POLICY = Object.freeze({
523
531
  enabled: true,
@@ -552,6 +560,7 @@ var DEFAULT_CONFIG = Object.freeze({
552
560
  providers: DEFAULT_PROVIDERS_POLICY
553
561
  });
554
562
  var readsClaudeTranscriptUsage = (config) => config.providers?.claudeCode?.readTranscriptUsage === true;
563
+ var sessionContextDir = (config) => config.sessionContext?.dir;
555
564
  var effectiveMetricsPolicy = (exporter) => ({
556
565
  ...DEFAULT_METRICS_POLICY,
557
566
  ...exporter.metrics ?? {}
@@ -1703,7 +1712,15 @@ var baseEventFields = {
1703
1712
  * factory, never by hand.
1704
1713
  */
1705
1714
  subagentId: subagentIdSchema.optional(),
1706
- extensions: extensionsSchema.default(emptyExtensions)
1715
+ extensions: extensionsSchema.default(emptyExtensions),
1716
+ /**
1717
+ * Attributes of the session context segment in force when the event
1718
+ * occurred (`docs/session-context.md`), stamped by the core from a file a
1719
+ * harness wrote. Exported on every record of the event, over the same keys
1720
+ * from the Resource. Absent when no context applies. Set by the core only,
1721
+ * never by an adapter.
1722
+ */
1723
+ contextAttributes: z14.record(z14.string().min(1).max(255), z14.union([z14.string(), z14.number(), z14.boolean()])).optional()
1707
1724
  };
1708
1725
  var event = (shape) => z14.strictObject({ ...baseEventFields, ...shape });
1709
1726
  var sessionStartEventSchema = event({
@@ -1890,6 +1907,11 @@ var passthroughResourceAttributes = (resource) => {
1890
1907
  }
1891
1908
  return attributes;
1892
1909
  };
1910
+ var contextAttributesOf = (event2) => event2.contextAttributes === void 0 ? {} : { ...event2.contextAttributes };
1911
+ var profileAttributes = (event2, resource) => ({
1912
+ ...passthroughResourceAttributes(resource),
1913
+ ...contextAttributesOf(event2)
1914
+ });
1893
1915
  var resolveExportedSessionId = (eventSessionId, resource) => {
1894
1916
  for (const key of EXTERNAL_SESSION_KEY_ATTRIBUTES) {
1895
1917
  const supplied = resource.attributes[key];
@@ -1910,6 +1932,8 @@ var hexTraceAttributes = (ids) => ({
1910
1932
  var exportIdentityAttributes = (event2, resource, ids) => {
1911
1933
  const { sessionId, providerSessionId } = resolveExportedSessionId(event2.sessionId, resource);
1912
1934
  return {
1935
+ // First, so nothing in the profile layer can replace an identity attribute.
1936
+ ...profileAttributes(event2, resource),
1913
1937
  [ATTR_SESSION_ID]: sessionId,
1914
1938
  [ATTR_OTELHOOK_SESSION_ID]: providerSessionId,
1915
1939
  [ATTR_GEN_AI_CONVERSATION_ID]: providerSessionId,
@@ -1918,7 +1942,6 @@ var exportIdentityAttributes = (event2, resource, ids) => {
1918
1942
  ...event2.provenance.providerVersion === void 0 ? {} : { [ATTR_OTELHOOK_PROVIDER_VERSION]: event2.provenance.providerVersion },
1919
1943
  [ATTR_OTELHOOK_WORKSPACE_ID]: event2.workspace.workspaceId,
1920
1944
  ...event2.subagentId === void 0 ? {} : { [ATTR_OTELHOOK_SUBAGENT_ID]: event2.subagentId },
1921
- ...passthroughResourceAttributes(resource),
1922
1945
  ...hexTraceAttributes(ids)
1923
1946
  };
1924
1947
  };
@@ -2013,6 +2036,9 @@ var ATTR_OTELHOOK_PROVIDER_ID2 = "otelhook.provider.id";
2013
2036
  var ATTR_OTELHOOK_OUTCOME = "otelhook.outcome";
2014
2037
  var ATTR_OTELHOOK_SESSION_KIND = "otelhook.session.kind";
2015
2038
  var commonAttributes = (event2, resource, includeSessionId) => ({
2039
+ // Session context first, so the metric's own attributes always win; and never
2040
+ // anything account-shaped, whatever the context says.
2041
+ ...event2.contextAttributes === void 0 ? {} : withoutAccountIdentity(event2.contextAttributes),
2016
2042
  [ATTR_OTELHOOK_PROVIDER_ID2]: event2.provenance.providerId,
2017
2043
  ...includeSessionId ? { [ATTR_SESSION_ID2]: resolveExportedSessionId(event2.sessionId, resource).sessionId } : {}
2018
2044
  });
@@ -2390,7 +2416,7 @@ import {
2390
2416
  } from "@opentelemetry/semantic-conventions/incubating";
2391
2417
 
2392
2418
  // src/version.ts
2393
- var VERSION = "0.11.0";
2419
+ var VERSION = "0.12.0";
2394
2420
 
2395
2421
  // src/telemetry/semconv.ts
2396
2422
  var SCOPE_NAME = "@osfactory/otel-hook";
@@ -2538,12 +2564,12 @@ var pickTarget = (attributes) => {
2538
2564
  }
2539
2565
  return picked;
2540
2566
  };
2541
- var withoutTarget = (attributes, resource) => {
2567
+ var withoutTarget = (attributes, resource, event2) => {
2542
2568
  const rest = { ...attributes };
2543
2569
  for (const key of TARGET_KEYS) {
2544
2570
  delete rest[key];
2545
2571
  }
2546
- return { ...rest, ...pickTarget(passthroughResourceAttributes(resource)) };
2572
+ return { ...rest, ...pickTarget(profileAttributes(event2, resource)) };
2547
2573
  };
2548
2574
  var rankOf = (candidate) => {
2549
2575
  const source = candidate[ATTR_OTELHOOK_TARGET_SOURCE];
@@ -2648,7 +2674,7 @@ var buildLifecycleSpan = (plan, resource, scope) => {
2648
2674
  name = "session";
2649
2675
  kind = SpanKind.INTERNAL;
2650
2676
  attributes = {
2651
- ...withoutTarget(attributes, resource),
2677
+ ...withoutTarget(attributes, resource, anchor),
2652
2678
  ...strongestTarget([pickTarget(resolved.recovered), start === void 0 ? {} : targetAttributes(start)]),
2653
2679
  ...start?.agentName === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_NAME]: start.agentName },
2654
2680
  ...start?.agentVersion === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_VERSION]: start.agentVersion },
@@ -2690,7 +2716,7 @@ var buildLifecycleSpan = (plan, resource, scope) => {
2690
2716
  kind = SpanKind.CLIENT;
2691
2717
  attributes = {
2692
2718
  // Target keys are re-chosen below as one unit, never mixed across edges.
2693
- ...withoutTarget(attributes, resource),
2719
+ ...withoutTarget(attributes, resource, anchor),
2694
2720
  [ATTR_GEN_AI_TOOL_NAME2]: toolName,
2695
2721
  [ATTR_GEN_AI_TOOL_CALL_ID]: start?.toolCallId ?? end?.toolCallId ?? group.ref.scopeKey,
2696
2722
  ...start?.toolKind === void 0 ? {} : { [ATTR_OTELHOOK_TOOL_KIND]: start.toolKind },
@@ -3647,11 +3673,11 @@ var createPrivacyService = (policyInput) => {
3647
3673
  };
3648
3674
  const flattenToAttributes = (value, prefix) => {
3649
3675
  const attributes = {};
3650
- const walk = (current, path6) => {
3676
+ const walk = (current, path7) => {
3651
3677
  if (typeof current === "string" || typeof current === "number" || typeof current === "boolean") {
3652
3678
  const primitive = toAttributePrimitive(current);
3653
3679
  if (primitive !== void 0) {
3654
- attributes[path6] = primitive;
3680
+ attributes[path7] = primitive;
3655
3681
  }
3656
3682
  return;
3657
3683
  }
@@ -3670,16 +3696,16 @@ var createPrivacyService = (policyInput) => {
3670
3696
  primitives.push(entryPrimitive);
3671
3697
  }
3672
3698
  if (uniform) {
3673
- attributes[path6] = primitives.slice(0, MAX_ATTRIBUTE_ARRAY_LENGTH);
3699
+ attributes[path7] = primitives.slice(0, MAX_ATTRIBUTE_ARRAY_LENGTH);
3674
3700
  return;
3675
3701
  }
3676
3702
  for (const [index, entry] of current.entries()) {
3677
- walk(entry, `${path6}.${index}`);
3703
+ walk(entry, `${path7}.${index}`);
3678
3704
  }
3679
3705
  return;
3680
3706
  }
3681
3707
  for (const [key, entry] of Object.entries(current)) {
3682
- walk(entry, path6 === "" ? key : `${path6}.${key}`);
3708
+ walk(entry, path7 === "" ? key : `${path7}.${key}`);
3683
3709
  }
3684
3710
  };
3685
3711
  walk(value, prefix);
@@ -4528,7 +4554,7 @@ var createSystemClock = () => ({
4528
4554
  });
4529
4555
 
4530
4556
  // src/runtime/hook.ts
4531
- import { z as z18 } from "zod";
4557
+ import { z as z19 } from "zod";
4532
4558
 
4533
4559
  // src/providers/registry.ts
4534
4560
  var createProviderRegistry = (adapters) => {
@@ -4953,8 +4979,200 @@ var resolveEventTargets = async (input) => {
4953
4979
  return { events, resolved: settled.size, timedOut: finished === "timeout" };
4954
4980
  };
4955
4981
 
4982
+ // src/runtime/session-context.ts
4983
+ import { open as open2 } from "fs/promises";
4984
+ import * as path3 from "path";
4985
+ import { z as z18 } from "zod";
4986
+ var SESSION_CONTEXT_FILE_VERSION = 1;
4987
+ var DEFAULT_SESSION_CONTEXT_MAX_BYTES = 256 * 1024;
4988
+ var DEFAULT_SESSION_CONTEXT_BUDGET_MILLIS = 100;
4989
+ var MAX_SESSION_CONTEXT_SEGMENTS = 1024;
4990
+ var SESSION_CONTEXT_AGENT_TOOLS = Object.freeze({
4991
+ "claude-code": "claude_code",
4992
+ codex: "codex",
4993
+ cursor: "cursor",
4994
+ "gemini-cli": "gemini_cli",
4995
+ antigravity: "antigravity"
4996
+ });
4997
+ var sessionContextAgentTool = (providerId) => Object.hasOwn(SESSION_CONTEXT_AGENT_TOOLS, providerId) ? SESSION_CONTEXT_AGENT_TOOLS[providerId] : void 0;
4998
+ var SESSION_FILE_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/;
4999
+ var isSessionContextFileName = (sessionId) => SESSION_FILE_NAME_PATTERN.test(sessionId) && !sessionId.includes("..");
5000
+ var sessionContextFilePath = (dir, providerId, sessionId) => {
5001
+ const tool = sessionContextAgentTool(providerId);
5002
+ if (tool === void 0 || !isSessionContextFileName(sessionId) || !path3.isAbsolute(dir)) {
5003
+ return void 0;
5004
+ }
5005
+ return path3.join(dir, tool, `${sessionId}.json`);
5006
+ };
5007
+ var RESERVED_CONTEXT_KEYS = /* @__PURE__ */ new Set([
5008
+ "session.id",
5009
+ "trace_id",
5010
+ "span_id",
5011
+ "parent_span_id",
5012
+ "gen_ai.conversation.id",
5013
+ "factory.local"
5014
+ ]);
5015
+ var RESERVED_CONTEXT_PREFIXES = Object.freeze(["factory.local.", "otelhook."]);
5016
+ var isReservedSessionContextKey = (key) => RESERVED_CONTEXT_KEYS.has(key) || RESERVED_CONTEXT_PREFIXES.some((prefix) => key.startsWith(prefix));
5017
+ var sanitizeSessionContextAttributes = (attributes) => {
5018
+ const kept = {};
5019
+ let count = 0;
5020
+ for (const [key, value] of Object.entries(attributes)) {
5021
+ if (count >= MAX_RESOURCE_ATTRIBUTES) {
5022
+ break;
5023
+ }
5024
+ if (checkResourceAttributeKey(key) !== void 0 || isReservedSessionContextKey(key)) {
5025
+ continue;
5026
+ }
5027
+ if (typeof value === "string") {
5028
+ if (value.length > MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH) {
5029
+ continue;
5030
+ }
5031
+ } else if (typeof value === "number") {
5032
+ if (!Number.isFinite(value)) {
5033
+ continue;
5034
+ }
5035
+ } else if (typeof value !== "boolean") {
5036
+ continue;
5037
+ }
5038
+ kept[key] = value;
5039
+ count += 1;
5040
+ }
5041
+ return kept;
5042
+ };
5043
+ var ISO_INSTANT_PATTERN = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d{1,9})?)?(?:Z|[+-]\d{2}:\d{2})$/;
5044
+ var isoInstantSchema = z18.string().max(64).regex(ISO_INSTANT_PATTERN).transform((value, ctx) => {
5045
+ const millis = Date.parse(value);
5046
+ if (!Number.isFinite(millis)) {
5047
+ ctx.issues.push({ code: "custom", input: value, message: "not a valid instant" });
5048
+ return z18.NEVER;
5049
+ }
5050
+ return millis;
5051
+ });
5052
+ var segmentSchema = z18.object({
5053
+ from: isoInstantSchema,
5054
+ to: isoInstantSchema.nullable(),
5055
+ reason: z18.string().max(256).optional(),
5056
+ attributes: z18.record(z18.string(), z18.unknown())
5057
+ });
5058
+ var sessionContextFileSchema = z18.object({
5059
+ version: z18.literal(SESSION_CONTEXT_FILE_VERSION),
5060
+ agentTool: z18.string().max(64).optional(),
5061
+ sessionId: z18.string().max(256).optional(),
5062
+ segments: z18.array(segmentSchema).max(MAX_SESSION_CONTEXT_SEGMENTS)
5063
+ });
5064
+ var parseSessionContextFile = (value, expected) => {
5065
+ const parsed = sessionContextFileSchema.safeParse(value);
5066
+ if (!parsed.success) {
5067
+ return void 0;
5068
+ }
5069
+ const file = parsed.data;
5070
+ if (expected?.agentTool !== void 0 && file.agentTool !== void 0 && file.agentTool !== expected.agentTool || expected?.sessionId !== void 0 && file.sessionId !== void 0 && file.sessionId !== expected.sessionId) {
5071
+ return void 0;
5072
+ }
5073
+ return file.segments.map((segment) => ({
5074
+ from: segment.from,
5075
+ to: segment.to,
5076
+ attributes: sanitizeSessionContextAttributes(segment.attributes)
5077
+ }));
5078
+ };
5079
+ var segmentInForce = (segments, at) => {
5080
+ let best;
5081
+ for (const segment of segments) {
5082
+ if (segment.from <= at && (segment.to === null || at < segment.to)) {
5083
+ if (best === void 0 || segment.from >= best.from) {
5084
+ best = segment;
5085
+ }
5086
+ }
5087
+ }
5088
+ return best;
5089
+ };
5090
+ var stampSessionContext = (events, segments) => events.map((event2) => {
5091
+ const { contextAttributes: _discarded, ...rest } = event2;
5092
+ const segment = segments === void 0 ? void 0 : segmentInForce(segments, event2.occurredAt);
5093
+ if (segment === void 0 || Object.keys(segment.attributes).length === 0) {
5094
+ return _discarded === void 0 ? event2 : rest;
5095
+ }
5096
+ return { ...rest, contextAttributes: { ...segment.attributes } };
5097
+ });
5098
+ var readBounded = async (file, maxBytes) => {
5099
+ let handle;
5100
+ try {
5101
+ handle = await open2(file, "r");
5102
+ } catch {
5103
+ return void 0;
5104
+ }
5105
+ try {
5106
+ const stats = await handle.stat();
5107
+ if (!stats.isFile() || stats.size > maxBytes) {
5108
+ return void 0;
5109
+ }
5110
+ const buffer = Buffer.alloc(maxBytes + 1);
5111
+ let length = 0;
5112
+ while (length < buffer.length) {
5113
+ const { bytesRead } = await handle.read(buffer, length, buffer.length - length, length);
5114
+ if (bytesRead === 0) {
5115
+ break;
5116
+ }
5117
+ length += bytesRead;
5118
+ }
5119
+ if (length > maxBytes) {
5120
+ return void 0;
5121
+ }
5122
+ return buffer.subarray(0, length).toString("utf8");
5123
+ } catch {
5124
+ return void 0;
5125
+ } finally {
5126
+ await handle.close().catch(() => void 0);
5127
+ }
5128
+ };
5129
+ var createDirectorySessionContextReader = (options) => {
5130
+ const maxBytes = options.maxBytes ?? DEFAULT_SESSION_CONTEXT_MAX_BYTES;
5131
+ const budgetMillis = options.budgetMillis ?? DEFAULT_SESSION_CONTEXT_BUDGET_MILLIS;
5132
+ const readOnce = async (providerId, sessionId) => {
5133
+ const file = sessionContextFilePath(options.dir, providerId, sessionId);
5134
+ if (file === void 0) {
5135
+ return void 0;
5136
+ }
5137
+ const text = await readBounded(file, maxBytes);
5138
+ if (text === void 0) {
5139
+ return void 0;
5140
+ }
5141
+ let decoded;
5142
+ try {
5143
+ decoded = JSON.parse(text);
5144
+ } catch {
5145
+ return void 0;
5146
+ }
5147
+ const agentTool = sessionContextAgentTool(providerId);
5148
+ return parseSessionContextFile(decoded, {
5149
+ ...agentTool === void 0 ? {} : { agentTool },
5150
+ sessionId
5151
+ });
5152
+ };
5153
+ return {
5154
+ read: async (request) => {
5155
+ let timer;
5156
+ const timeout = new Promise((resolve3) => {
5157
+ timer = setTimeout(() => resolve3(void 0), budgetMillis);
5158
+ timer.unref?.();
5159
+ });
5160
+ try {
5161
+ return await Promise.race([
5162
+ readOnce(request.providerId, request.sessionId).catch(() => void 0),
5163
+ timeout
5164
+ ]);
5165
+ } finally {
5166
+ if (timer !== void 0) {
5167
+ clearTimeout(timer);
5168
+ }
5169
+ }
5170
+ }
5171
+ };
5172
+ };
5173
+
4956
5174
  // src/runtime/hook.ts
4957
- var usageScopeSchema = z18.enum(["session", "generation", "subagent"]);
5175
+ var usageScopeSchema = z19.enum(["session", "generation", "subagent"]);
4958
5176
  var classifyDurability = (input) => {
4959
5177
  if (!input.attempted) {
4960
5178
  return "nothing-to-deliver";
@@ -5663,6 +5881,10 @@ var createOtelHook = (deps) => {
5663
5881
  });
5664
5882
  }
5665
5883
  }
5884
+ batch = stampSessionContext(
5885
+ batch,
5886
+ !suppress && batch.length > 0 && deps.sessionContext !== void 0 ? await readSessionContext(deps.sessionContext, detection.providerId, identity.sessionId) : void 0
5887
+ );
5666
5888
  let emitted = 0;
5667
5889
  let exportRejected = 0;
5668
5890
  if (!suppress && batch.length > 0) {
@@ -5778,6 +6000,13 @@ var createOtelHook = (deps) => {
5778
6000
  };
5779
6001
  return { resolveDelivery, ingest, flush, shutdown, config };
5780
6002
  };
6003
+ var readSessionContext = async (reader, providerId, sessionId) => {
6004
+ try {
6005
+ return await reader.read({ providerId, sessionId });
6006
+ } catch {
6007
+ return void 0;
6008
+ }
6009
+ };
5781
6010
  var buildErrorEvents = (diagnostics, identity, sequenceBase, ids, privacy) => {
5782
6011
  const events = [];
5783
6012
  for (const [index, info] of diagnostics.slice(0, MAX_ERROR_EVENTS).entries()) {
@@ -5812,8 +6041,8 @@ var buildErrorEvents = (diagnostics, identity, sequenceBase, ids, privacy) => {
5812
6041
  };
5813
6042
 
5814
6043
  // src/runtime/git-worktree.ts
5815
- import { lstat, open as open2, stat as stat2 } from "fs/promises";
5816
- import * as path3 from "path";
6044
+ import { lstat, open as open3, stat as stat2 } from "fs/promises";
6045
+ import * as path4 from "path";
5817
6046
  var MAX_WORKTREE_WALK_DEPTH = 128;
5818
6047
  var MAX_GIT_FILE_BYTES = 4096;
5819
6048
  var MAX_CACHE_ENTRIES = 1024;
@@ -5821,10 +6050,10 @@ var DEFAULT_WORKTREE_CACHE_TTL_MILLIS = 5e3;
5821
6050
  var MAX_BRANCH_NAME_LENGTH = 255;
5822
6051
  var ABSENT = Object.freeze({ kind: "absent" });
5823
6052
  var INVALID = Object.freeze({ kind: "invalid" });
5824
- var readBounded = async (filePath) => {
6053
+ var readBounded2 = async (filePath) => {
5825
6054
  let handle;
5826
6055
  try {
5827
- handle = await open2(filePath, "r");
6056
+ handle = await open3(filePath, "r");
5828
6057
  const buffer = Buffer.alloc(MAX_GIT_FILE_BYTES);
5829
6058
  const { bytesRead } = await handle.read(buffer, 0, MAX_GIT_FILE_BYTES, 0);
5830
6059
  return buffer.subarray(0, bytesRead).toString("utf8");
@@ -5845,7 +6074,7 @@ var parseHeadBranch = (head) => {
5845
6074
  return branch;
5846
6075
  };
5847
6076
  var firstLine = (content) => content.split(/\r?\n/, 1)[0]?.trim() ?? "";
5848
- var resolveGitPath = (target, base) => target === void 0 || target.length === 0 || target.includes("\0") ? void 0 : path3.resolve(base, target);
6077
+ var resolveGitPath = (target, base) => target === void 0 || target.length === 0 || target.includes("\0") ? void 0 : path4.resolve(base, target);
5849
6078
  var parseGitDirFile = (content, worktreeRoot) => {
5850
6079
  const line = firstLine(content);
5851
6080
  return resolveGitPath(
@@ -5871,17 +6100,17 @@ var isDirectory = async (directory) => {
5871
6100
  }
5872
6101
  };
5873
6102
  var repositoryOf = async (worktreeRoot, gitDir) => {
5874
- const commonDirFile = path3.join(gitDir, "commondir");
5875
- const content = await readBounded(commonDirFile);
6103
+ const commonDirFile = path4.join(gitDir, "commondir");
6104
+ const content = await readBounded2(commonDirFile);
5876
6105
  if (content === void 0) {
5877
6106
  return await isMissing(commonDirFile) ? { kind: "main", mainRoot: worktreeRoot } : { kind: "linked" };
5878
6107
  }
5879
6108
  const commonDir = parseCommonDirFile(content, gitDir);
5880
- const mainRoot = commonDir !== void 0 && path3.basename(commonDir) === ".git" && await isDirectory(commonDir) ? path3.dirname(commonDir) : void 0;
6109
+ const mainRoot = commonDir !== void 0 && path4.basename(commonDir) === ".git" && await isDirectory(commonDir) ? path4.dirname(commonDir) : void 0;
5881
6110
  return { kind: "linked", ...mainRoot === void 0 ? {} : { mainRoot } };
5882
6111
  };
5883
6112
  var probeDirectory = async (directory) => {
5884
- const dotGit = path3.join(directory, ".git");
6113
+ const dotGit = path4.join(directory, ".git");
5885
6114
  let info;
5886
6115
  try {
5887
6116
  info = await stat2(dotGit);
@@ -5892,13 +6121,13 @@ var probeDirectory = async (directory) => {
5892
6121
  if (info.isDirectory()) {
5893
6122
  gitDir = dotGit;
5894
6123
  } else if (info.isFile()) {
5895
- const content = await readBounded(dotGit);
6124
+ const content = await readBounded2(dotGit);
5896
6125
  gitDir = content === void 0 ? void 0 : parseGitDirFile(content, directory);
5897
6126
  }
5898
6127
  if (gitDir === void 0) {
5899
6128
  return INVALID;
5900
6129
  }
5901
- const head = await readBounded(path3.join(gitDir, "HEAD"));
6130
+ const head = await readBounded2(path4.join(gitDir, "HEAD"));
5902
6131
  if (head === void 0) {
5903
6132
  return INVALID;
5904
6133
  }
@@ -5928,10 +6157,10 @@ var createFilesystemWorktreeLocator = (options = {}) => {
5928
6157
  };
5929
6158
  const locate = async (absolutePath) => {
5930
6159
  try {
5931
- if (!path3.isAbsolute(absolutePath) || absolutePath.includes("\0")) {
6160
+ if (!path4.isAbsolute(absolutePath) || absolutePath.includes("\0")) {
5932
6161
  return void 0;
5933
6162
  }
5934
- let directory = path3.resolve(absolutePath);
6163
+ let directory = path4.resolve(absolutePath);
5935
6164
  for (let depth = 0; depth < MAX_WORKTREE_WALK_DEPTH; depth += 1) {
5936
6165
  const probe = await cachedProbe(directory);
5937
6166
  if (probe.kind === "worktree") {
@@ -5940,7 +6169,7 @@ var createFilesystemWorktreeLocator = (options = {}) => {
5940
6169
  if (probe.kind === "invalid") {
5941
6170
  return void 0;
5942
6171
  }
5943
- const parent = path3.dirname(directory);
6172
+ const parent = path4.dirname(directory);
5944
6173
  if (parent === directory) {
5945
6174
  return void 0;
5946
6175
  }
@@ -5956,8 +6185,8 @@ var createFilesystemWorktreeLocator = (options = {}) => {
5956
6185
 
5957
6186
  // src/state/filesystem-store.ts
5958
6187
  import { randomBytes as randomBytes2 } from "crypto";
5959
- import { mkdir, open as open3, readFile, readdir, rename, unlink, writeFile } from "fs/promises";
5960
- import * as path4 from "path";
6188
+ import { mkdir, open as open4, readFile, readdir, rename, unlink, writeFile } from "fs/promises";
6189
+ import * as path5 from "path";
5961
6190
 
5962
6191
  // src/state/keys.ts
5963
6192
  import { createHash as createHash6 } from "crypto";
@@ -5989,10 +6218,10 @@ var wrapFsError = (thrown, operation) => {
5989
6218
  };
5990
6219
  var createFilesystemStateStore = (options) => {
5991
6220
  const [providerSegment, installationSegment] = namespaceSegments(options);
5992
- const baseDir = path4.join(options.rootDir, providerSegment, installationSegment);
5993
- const recordsDir = path4.join(baseDir, "records");
5994
- const quarantineDir = path4.join(baseDir, "quarantine");
5995
- const locksDir = path4.join(baseDir, "locks");
6221
+ const baseDir = path5.join(options.rootDir, providerSegment, installationSegment);
6222
+ const recordsDir = path5.join(baseDir, "records");
6223
+ const quarantineDir = path5.join(baseDir, "quarantine");
6224
+ const locksDir = path5.join(baseDir, "locks");
5996
6225
  const lockTimeoutMillis = options.lockTimeoutMillis ?? 5e3;
5997
6226
  const lockStaleMillis = options.lockStaleMillis ?? 3e4;
5998
6227
  const lockPollIntervalMillis = options.lockPollIntervalMillis ?? 25;
@@ -6016,11 +6245,11 @@ var createFilesystemStateStore = (options) => {
6016
6245
  throw wrapFsError(thrown, "ensure-dirs");
6017
6246
  }
6018
6247
  };
6019
- const recordPath = (key) => path4.join(recordsDir, `${keyDigest(key)}.json`);
6020
- const tempPath = (key) => path4.join(recordsDir, `.tmp-${keyDigest(key)}-${randomBytes2(6).toString("hex")}.json`);
6021
- const lockPath = (sessionId) => path4.join(locksDir, `${sanitizeSegment(sessionId)}.lock`);
6248
+ const recordPath = (key) => path5.join(recordsDir, `${keyDigest(key)}.json`);
6249
+ const tempPath = (key) => path5.join(recordsDir, `.tmp-${keyDigest(key)}-${randomBytes2(6).toString("hex")}.json`);
6250
+ const lockPath = (sessionId) => path5.join(locksDir, `${sanitizeSegment(sessionId)}.lock`);
6022
6251
  const quarantine = async (filePath, key, reason) => {
6023
- const dest = path4.join(quarantineDir, `${options.clock.now()}-${keyDigest(key)}-${reason}.json`);
6252
+ const dest = path5.join(quarantineDir, `${options.clock.now()}-${keyDigest(key)}-${reason}.json`);
6024
6253
  try {
6025
6254
  await rename(filePath, dest);
6026
6255
  } catch {
@@ -6084,7 +6313,7 @@ var createFilesystemStateStore = (options) => {
6084
6313
  const startedAt = options.clock.monotonicMillis();
6085
6314
  for (; ; ) {
6086
6315
  try {
6087
- const handle = await open3(filePath, "wx");
6316
+ const handle = await open4(filePath, "wx");
6088
6317
  try {
6089
6318
  await handle.writeFile(JSON.stringify({ pid: process.pid, acquiredAt: options.clock.now() }));
6090
6319
  } finally {
@@ -6152,7 +6381,7 @@ var createFilesystemStateStore = (options) => {
6152
6381
  }
6153
6382
  let raw;
6154
6383
  try {
6155
- raw = await readFile(path4.join(recordsDir, entry), "utf8");
6384
+ raw = await readFile(path5.join(recordsDir, entry), "utf8");
6156
6385
  } catch {
6157
6386
  continue;
6158
6387
  }
@@ -6205,7 +6434,7 @@ var createFilesystemStateStore = (options) => {
6205
6434
  continue;
6206
6435
  }
6207
6436
  scanned += 1;
6208
- const filePath = path4.join(recordsDir, entry);
6437
+ const filePath = path5.join(recordsDir, entry);
6209
6438
  try {
6210
6439
  const raw = await readFile(filePath, "utf8");
6211
6440
  const envelope = JSON.parse(raw);
@@ -6225,7 +6454,7 @@ var createFilesystemStateStore = (options) => {
6225
6454
  lockEntries = [];
6226
6455
  }
6227
6456
  for (const entry of lockEntries) {
6228
- const filePath = path4.join(locksDir, entry);
6457
+ const filePath = path5.join(locksDir, entry);
6229
6458
  try {
6230
6459
  const raw = await readFile(filePath, "utf8");
6231
6460
  const parsed = JSON.parse(raw);
@@ -6278,7 +6507,7 @@ var siblingSignalEndpoint = (tracesEndpoint, signal) => {
6278
6507
  // src/telemetry/spool-queue.ts
6279
6508
  import { randomBytes as randomBytes3 } from "crypto";
6280
6509
  import { mkdir as mkdir2, readFile as readFile2, readdir as readdir2, rename as rename2, stat as stat3, unlink as unlink2, writeFile as writeFile2 } from "fs/promises";
6281
- import * as path5 from "path";
6510
+ import * as path6 from "path";
6282
6511
  var EMPTY_SPOOL_DROP_COUNTS = Object.freeze({
6283
6512
  total: 0,
6284
6513
  age: 0,
@@ -6294,7 +6523,7 @@ var enqueuedAtOf = (fileName) => {
6294
6523
  var isCount = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0;
6295
6524
  var readSpoolDropCounts = async (queueDir) => {
6296
6525
  try {
6297
- const parsed = JSON.parse(await readFile2(path5.join(queueDir, SPOOL_DROPS_FILE), "utf8"));
6526
+ const parsed = JSON.parse(await readFile2(path6.join(queueDir, SPOOL_DROPS_FILE), "utf8"));
6298
6527
  if (typeof parsed !== "object" || parsed === null) {
6299
6528
  return EMPTY_SPOOL_DROP_COUNTS;
6300
6529
  }
@@ -6323,7 +6552,7 @@ var readSpoolQueueStats = async (queueDir) => {
6323
6552
  let bytes = 0;
6324
6553
  for (const file of files) {
6325
6554
  try {
6326
- bytes += (await stat3(path5.join(queueDir, file))).size;
6555
+ bytes += (await stat3(path6.join(queueDir, file))).size;
6327
6556
  } catch {
6328
6557
  }
6329
6558
  }
@@ -6339,8 +6568,8 @@ var DEFAULT_DRAIN_MAX_BATCHES = 20;
6339
6568
  var isErrnoException2 = (thrown, code) => thrown instanceof Error && thrown.code === code;
6340
6569
  var createSpoolQueue = (options) => {
6341
6570
  const [providerSegment, installationSegment] = namespaceSegments(options);
6342
- const queueDir = path5.join(options.rootDir, providerSegment, installationSegment, options.queueName);
6343
- const corruptDir = path5.join(
6571
+ const queueDir = path6.join(options.rootDir, providerSegment, installationSegment, options.queueName);
6572
+ const corruptDir = path6.join(
6344
6573
  options.rootDir,
6345
6574
  providerSegment,
6346
6575
  installationSegment,
@@ -6387,9 +6616,9 @@ var createSpoolQueue = (options) => {
6387
6616
  [reason]: current[reason] + dropped,
6388
6617
  lastDroppedAt: options.clock.now()
6389
6618
  };
6390
- const tmp = path5.join(queueDir, `.tmp-${randomBytes3(6).toString("hex")}.drops`);
6619
+ const tmp = path6.join(queueDir, `.tmp-${randomBytes3(6).toString("hex")}.drops`);
6391
6620
  await writeFile2(tmp, JSON.stringify(next), "utf8");
6392
- await rename2(tmp, path5.join(queueDir, SPOOL_DROPS_FILE));
6621
+ await rename2(tmp, path6.join(queueDir, SPOOL_DROPS_FILE));
6393
6622
  } catch {
6394
6623
  }
6395
6624
  options.logger?.warn("durable spool dropped batches", {
@@ -6405,7 +6634,7 @@ var createSpoolQueue = (options) => {
6405
6634
  let bytes = 0;
6406
6635
  if (options.maxBytes !== void 0) {
6407
6636
  try {
6408
- bytes = (await stat3(path5.join(queueDir, name))).size;
6637
+ bytes = (await stat3(path6.join(queueDir, name))).size;
6409
6638
  } catch {
6410
6639
  continue;
6411
6640
  }
@@ -6419,7 +6648,7 @@ var createSpoolQueue = (options) => {
6419
6648
  let removed = 0;
6420
6649
  for (const file of files) {
6421
6650
  try {
6422
- await unlink2(path5.join(queueDir, file.name));
6651
+ await unlink2(path6.join(queueDir, file.name));
6423
6652
  removed += 1;
6424
6653
  } catch {
6425
6654
  }
@@ -6479,8 +6708,8 @@ var createSpoolQueue = (options) => {
6479
6708
  }
6480
6709
  }
6481
6710
  const fileName = `${String(now).padStart(16, "0")}-${randomBytes3(6).toString("hex")}.json`;
6482
- const target = path5.join(queueDir, fileName);
6483
- const tmp = path5.join(queueDir, `.tmp-${randomBytes3(6).toString("hex")}.json`);
6711
+ const target = path6.join(queueDir, fileName);
6712
+ const tmp = path6.join(queueDir, `.tmp-${randomBytes3(6).toString("hex")}.json`);
6484
6713
  await writeFile2(tmp, serialized, "utf8");
6485
6714
  await rename2(tmp, target);
6486
6715
  return { spooled: true };
@@ -6510,7 +6739,7 @@ var createSpoolQueue = (options) => {
6510
6739
  if (fileName === void 0) {
6511
6740
  break;
6512
6741
  }
6513
- const filePath = path5.join(queueDir, fileName);
6742
+ const filePath = path6.join(queueDir, fileName);
6514
6743
  const quarantine = async (rejection) => {
6515
6744
  quarantined += 1;
6516
6745
  options.logger?.error("durable spool quarantined an unusable batch", {
@@ -6519,7 +6748,7 @@ var createSpoolQueue = (options) => {
6519
6748
  "spool.queue": options.queueName
6520
6749
  });
6521
6750
  try {
6522
- await rename2(filePath, path5.join(corruptDir, fileName));
6751
+ await rename2(filePath, path6.join(corruptDir, fileName));
6523
6752
  } catch {
6524
6753
  await unlink2(filePath).catch(() => void 0);
6525
6754
  }
@@ -6896,6 +7125,33 @@ var replayResource = (attributes, policy) => {
6896
7125
  }
6897
7126
  return resourceFromAttributes(safe);
6898
7127
  };
7128
+ var agreedContextAttributes = (events) => {
7129
+ const [first, ...rest] = events;
7130
+ if (first?.contextAttributes === void 0) {
7131
+ return {};
7132
+ }
7133
+ const agreed = { ...first.contextAttributes };
7134
+ for (const event2 of rest) {
7135
+ for (const key of Object.keys(agreed)) {
7136
+ if (event2.contextAttributes?.[key] !== agreed[key]) {
7137
+ delete agreed[key];
7138
+ }
7139
+ }
7140
+ }
7141
+ return agreed;
7142
+ };
7143
+ var resourceWithContext = (resource, context) => {
7144
+ const overrides = {};
7145
+ for (const [key, value] of Object.entries(context)) {
7146
+ if (Object.hasOwn(resource.attributes, key) && !isReservedResourceAttributeKey(key) && resource.attributes[key] !== value) {
7147
+ overrides[key] = value;
7148
+ }
7149
+ }
7150
+ if (Object.keys(overrides).length === 0) {
7151
+ return resource;
7152
+ }
7153
+ return resourceFromAttributes({ ...resource.attributes, ...overrides });
7154
+ };
6899
7155
 
6900
7156
  // src/telemetry/log-records.ts
6901
7157
  import { SeverityNumber, TraceFlags as TraceFlags2 } from "@opentelemetry/api";
@@ -7411,10 +7667,10 @@ var createOtlpLogSink = (options) => {
7411
7667
  const exportRecords = (records) => new Promise((resolve3) => {
7412
7668
  exporter.export([...records], (result) => resolve3(result));
7413
7669
  });
7414
- const toSpoolBatch = (records) => ({
7670
+ const toSpoolBatch = (records, batchResource) => ({
7415
7671
  providerId: options.providerId,
7416
7672
  installationId: options.installationId,
7417
- resourceAttributes: { ...resource.attributes },
7673
+ resourceAttributes: { ...batchResource.attributes },
7418
7674
  instrumentationScope: {
7419
7675
  name: scope.name,
7420
7676
  ...scope.version === void 0 ? {} : { version: scope.version }
@@ -7449,8 +7705,9 @@ var createOtlpLogSink = (options) => {
7449
7705
  return { accepted: 0, rejected: 0, errors: [] };
7450
7706
  }
7451
7707
  const resolved = await resolveCorrelations(events);
7708
+ const batchResource = resourceWithContext(resource, agreedContextAttributes(events));
7452
7709
  const mapped = canonicalEventsToLogRecords(events, {
7453
- resource,
7710
+ resource: batchResource,
7454
7711
  instrumentationScope: scope,
7455
7712
  content,
7456
7713
  correlations: resolved.correlations,
@@ -7485,7 +7742,7 @@ var createOtlpLogSink = (options) => {
7485
7742
  health.recordFailure("telemetry-export-failure", batch.length, options.clock.now());
7486
7743
  const permanent = isPermanentExportFailure(result);
7487
7744
  if (options.spool !== void 0 && !permanent) {
7488
- const spoolResult = await options.spool.enqueue(toSpoolBatch(batch)).catch(() => ({
7745
+ const spoolResult = await options.spool.enqueue(toSpoolBatch(batch, batchResource)).catch(() => ({
7489
7746
  spooled: false,
7490
7747
  reason: "capacity-exceeded"
7491
7748
  }));
@@ -7716,10 +7973,10 @@ var createOtlpMetricSink = (options) => {
7716
7973
  });
7717
7974
  }
7718
7975
  });
7719
- const toSpoolBatch = (points) => ({
7976
+ const toSpoolBatch = (points, batchResource) => ({
7720
7977
  providerId: options.providerId,
7721
7978
  installationId: options.installationId,
7722
- resourceAttributes: { ...resource.attributes },
7979
+ resourceAttributes: { ...batchResource.attributes },
7723
7980
  instrumentationScope: {
7724
7981
  name: scope.name,
7725
7982
  ...scope.version === void 0 ? {} : { version: scope.version }
@@ -7737,11 +7994,12 @@ var createOtlpMetricSink = (options) => {
7737
7994
  }
7738
7995
  return isPermanentExportFailure(result) ? "discard" : false;
7739
7996
  };
7740
- const exportPoints = async (points) => {
7997
+ const exportPoints = async (points, context) => {
7741
7998
  if (points.length === 0) {
7742
7999
  return { accepted: 0, rejected: 0, errors: [] };
7743
8000
  }
7744
- const result = await exportResourceMetrics(points, resource, scope);
8001
+ const batchResource = context === void 0 ? resource : resourceWithContext(resource, context);
8002
+ const result = await exportResourceMetrics(points, batchResource, scope);
7745
8003
  if (result.code === ExportResultCode2.SUCCESS) {
7746
8004
  health.recordSuccess(points.length, options.clock.now());
7747
8005
  return { accepted: points.length, rejected: 0, errors: [] };
@@ -7749,7 +8007,7 @@ var createOtlpMetricSink = (options) => {
7749
8007
  health.recordFailure("telemetry-export-failure", points.length, options.clock.now());
7750
8008
  const permanent = isPermanentExportFailure(result);
7751
8009
  if (options.spool !== void 0 && !permanent) {
7752
- const spooled = await options.spool.enqueue(toSpoolBatch(points)).catch(() => ({
8010
+ const spooled = await options.spool.enqueue(toSpoolBatch(points, batchResource)).catch(() => ({
7753
8011
  spooled: false,
7754
8012
  reason: "capacity-exceeded"
7755
8013
  }));
@@ -7903,10 +8161,10 @@ var createOtlpTraceSink = (options) => {
7903
8161
  const exportSpans = (spans) => new Promise((resolve3) => {
7904
8162
  exporter.export([...spans], (result) => resolve3(result));
7905
8163
  });
7906
- const toSpoolBatch = (spans) => ({
8164
+ const toSpoolBatch = (spans, batchResource) => ({
7907
8165
  providerId: options.providerId,
7908
8166
  installationId: options.installationId,
7909
- resourceAttributes: { ...resource.attributes },
8167
+ resourceAttributes: { ...batchResource.attributes },
7910
8168
  instrumentationScope: { name: scope.name, ...scope.version === void 0 ? {} : { version: scope.version } },
7911
8169
  spans: spans.map(serializeSpan),
7912
8170
  enqueuedAt: options.clock.now()
@@ -7936,8 +8194,9 @@ var createOtlpTraceSink = (options) => {
7936
8194
  return { accepted: 0, rejected: 0, errors: [] };
7937
8195
  }
7938
8196
  const resolved = await resolveCorrelations(events);
8197
+ const batchResource = resourceWithContext(resource, agreedContextAttributes(events));
7939
8198
  const spans = canonicalEventsToReadableSpans(events, {
7940
- resource,
8199
+ resource: batchResource,
7941
8200
  instrumentationScope: scope,
7942
8201
  correlations: resolved.correlations,
7943
8202
  ...resolved.available === void 0 ? {} : { correlationAvailable: resolved.available }
@@ -7963,7 +8222,7 @@ var createOtlpTraceSink = (options) => {
7963
8222
  health.recordFailure("telemetry-export-failure", batch.length, options.clock.now());
7964
8223
  const permanent = isPermanentExportFailure(result);
7965
8224
  if (options.spool !== void 0 && !permanent) {
7966
- const spoolResult = await options.spool.enqueue(toSpoolBatch(batch)).catch(() => ({
8225
+ const spoolResult = await options.spool.enqueue(toSpoolBatch(batch, batchResource)).catch(() => ({
7967
8226
  spooled: false,
7968
8227
  reason: "capacity-exceeded"
7969
8228
  }));
@@ -8372,6 +8631,16 @@ var createHookRuntime = (options) => {
8372
8631
  logger,
8373
8632
  installationId: options.installationId,
8374
8633
  payloadEnrichers: options.payloadEnrichers ?? (readsClaudeTranscriptUsage(options.config) ? [createClaudeTranscriptUsageEnricher()] : []),
8634
+ ...(() => {
8635
+ if (options.sessionContextReader === null) {
8636
+ return {};
8637
+ }
8638
+ if (options.sessionContextReader !== void 0) {
8639
+ return { sessionContext: options.sessionContextReader };
8640
+ }
8641
+ const dir = sessionContextDir(options.config);
8642
+ return dir === void 0 ? {} : { sessionContext: createDirectorySessionContextReader({ dir }) };
8643
+ })(),
8375
8644
  ...options.worktreeLocator === null ? {} : {
8376
8645
  worktreeLocator: options.worktreeLocator ?? createFilesystemWorktreeLocator({ monotonicMillis: () => clock.monotonicMillis() })
8377
8646
  }
@@ -8465,9 +8734,10 @@ var createHookRuntime = (options) => {
8465
8734
  perSession: metricsPolicy.includeSessionId,
8466
8735
  ...deliveryToken === void 0 ? {} : { deliveryToken }
8467
8736
  });
8737
+ const context = agreedContextAttributes(ingest.events);
8468
8738
  const results = await Promise.all(
8469
8739
  metricDestinations.map(async (destination) => {
8470
- const result = await destination.metrics.exportPoints(points).catch(
8740
+ const result = await destination.metrics.exportPoints(points, context).catch(
8471
8741
  (thrown) => ({
8472
8742
  accepted: 0,
8473
8743
  rejected: points.length,