@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
package/dist/cli.js CHANGED
@@ -1,5 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
 
3
+ // src/cli/args.ts
4
+ import { isAbsolute } from "path";
5
+
3
6
  // src/config/resource-attributes.ts
4
7
  import { z as z3 } from "zod";
5
8
 
@@ -334,6 +337,7 @@ var VALUE_FLAGS = /* @__PURE__ */ new Set([
334
337
  "--logs-endpoint",
335
338
  "--metrics-endpoint",
336
339
  "--metrics-temporality",
340
+ "--session-context-dir",
337
341
  "--max-input-bytes",
338
342
  "--scope",
339
343
  "--project-dir",
@@ -534,6 +538,10 @@ var parsePolicy = (tokens, errors) => {
534
538
  errors.push("flag --metrics-temporality must be cumulative or delta");
535
539
  }
536
540
  }
541
+ const sessionContextDir2 = single(tokens, "--session-context-dir", errors);
542
+ if (sessionContextDir2 !== void 0 && !isAbsolute(sessionContextDir2)) {
543
+ errors.push("flag --session-context-dir expects an absolute path");
544
+ }
537
545
  return {
538
546
  ...configFile === void 0 ? {} : { configFile },
539
547
  ...endpoint === void 0 ? {} : { endpoint },
@@ -558,7 +566,8 @@ var parsePolicy = (tokens, errors) => {
558
566
  ...metricsEndpoint === void 0 ? {} : { metricsEndpoint },
559
567
  ...metricsTemporality === void 0 ? {} : { metricsTemporality },
560
568
  ...tokens.booleans.has("--no-metrics-session-id") ? { metricsIncludeSessionId: false } : {},
561
- ...tokens.booleans.has("--claude-transcript-usage") ? { claudeTranscriptUsage: true } : {}
569
+ ...tokens.booleans.has("--claude-transcript-usage") ? { claudeTranscriptUsage: true } : {},
570
+ ...sessionContextDir2 === void 0 || !isAbsolute(sessionContextDir2) ? {} : { sessionContextDir: sessionContextDir2 }
562
571
  };
563
572
  };
564
573
  var parseIdentity = (tokens, errors) => {
@@ -619,6 +628,7 @@ var RUN_FLAGS = /* @__PURE__ */ new Set([
619
628
  "--metrics-temporality",
620
629
  "--no-metrics-session-id",
621
630
  "--claude-transcript-usage",
631
+ "--session-context-dir",
622
632
  "--max-input-bytes",
623
633
  "--no-export",
624
634
  "--no-spool",
@@ -654,6 +664,7 @@ var DOCTOR_FLAGS = /* @__PURE__ */ new Set([
654
664
  "--metrics-temporality",
655
665
  "--no-metrics-session-id",
656
666
  "--claude-transcript-usage",
667
+ "--session-context-dir",
657
668
  "--include-experimental",
658
669
  "--no-experimental"
659
670
  ]);
@@ -910,6 +921,13 @@ Exporter and runtime policy (never identity):
910
921
  payload names (bounded) for the turn's model and
911
922
  summed token usage. Off by default; also
912
923
  OTEL_HOOK_CLAUDE_TRANSCRIPT_USAGE=1
924
+ --session-context-dir <dir>
925
+ absolute directory of session context files
926
+ (<dir>/<agent-tool>/<session-id>.json); the
927
+ attributes of the segment in force are put on
928
+ every span, log record and metric point. Overrides
929
+ sessionContext.dir in --config-file. No environment
930
+ variable, by design
913
931
  --max-input-bytes <n> stdin bound (default 1048576)
914
932
  --attr <key=value> opaque consumer attribute for this invocation,
915
933
  carried unchanged (not a resource attribute)
@@ -1828,6 +1846,7 @@ var describeExportDestinations = (exporter) => {
1828
1846
  };
1829
1847
 
1830
1848
  // src/config/schema.ts
1849
+ import { isAbsolute as isAbsolute2 } from "path";
1831
1850
  import { z as z7 } from "zod";
1832
1851
  var logsPolicySchema = z7.strictObject({
1833
1852
  enabled: z7.boolean(),
@@ -1929,13 +1948,19 @@ var providersPolicySchema = z7.strictObject({
1929
1948
  readTranscriptUsage: z7.boolean()
1930
1949
  }).optional()
1931
1950
  });
1951
+ var sessionContextPolicySchema = z7.strictObject({
1952
+ /** Absolute path of the context directory. */
1953
+ dir: z7.string().min(1).max(4096).refine((value) => isAbsolute2(value), { message: "must be an absolute path" })
1954
+ });
1932
1955
  var otelHookConfigSchema = z7.strictObject({
1933
1956
  exporter: exporterPolicySchema,
1934
1957
  privacy: privacyPolicySchema,
1935
1958
  detection: detectionPolicySchema,
1936
1959
  diagnostics: diagnosticsPolicySchema,
1937
1960
  /** Optional so a hand-built configuration from before it existed stays valid. */
1938
- providers: providersPolicySchema.optional()
1961
+ providers: providersPolicySchema.optional(),
1962
+ /** Optional: absent means no session context is read. */
1963
+ sessionContext: sessionContextPolicySchema.optional()
1939
1964
  });
1940
1965
  var otelHookConfigPatchSchema = z7.strictObject({
1941
1966
  // `logs` is unwrapped and re-partialled for the same reason `privacy.limits` is:
@@ -1951,7 +1976,8 @@ var otelHookConfigPatchSchema = z7.strictObject({
1951
1976
  diagnostics: diagnosticsPolicySchema.partial().optional(),
1952
1977
  providers: z7.strictObject({
1953
1978
  claudeCode: z7.strictObject({ readTranscriptUsage: z7.boolean() }).partial().optional()
1954
- }).partial().optional()
1979
+ }).partial().optional(),
1980
+ sessionContext: sessionContextPolicySchema.partial().optional()
1955
1981
  });
1956
1982
  var DEFAULT_EXPORTER_POLICY = Object.freeze({
1957
1983
  enabled: true,
@@ -1986,6 +2012,7 @@ var DEFAULT_CONFIG = Object.freeze({
1986
2012
  providers: DEFAULT_PROVIDERS_POLICY
1987
2013
  });
1988
2014
  var readsClaudeTranscriptUsage = (config) => config.providers?.claudeCode?.readTranscriptUsage === true;
2015
+ var sessionContextDir = (config) => config.sessionContext?.dir;
1989
2016
  var effectiveMetricsPolicy = (exporter) => ({
1990
2017
  ...DEFAULT_METRICS_POLICY,
1991
2018
  ...exporter.metrics ?? {}
@@ -1995,12 +2022,12 @@ var effectiveMetricsPolicy = (exporter) => ({
1995
2022
  var CONFIG_SOURCE_PRECEDENCE = ["defaults", "file", "environment", "inline-override"];
1996
2023
  var configSourceSchema = z8.enum(CONFIG_SOURCE_PRECEDENCE);
1997
2024
  var isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1998
- var mergeLeaf = (target, patch, source, provenance, path14) => {
2025
+ var mergeLeaf = (target, patch, source, provenance, path15) => {
1999
2026
  for (const [key, value] of Object.entries(patch)) {
2000
2027
  if (value === void 0) {
2001
2028
  continue;
2002
2029
  }
2003
- const childPath = path14 === "" ? key : `${path14}.${key}`;
2030
+ const childPath = path15 === "" ? key : `${path15}.${key}`;
2004
2031
  const existing = target[key];
2005
2032
  if (isPlainObject(value) && (isPlainObject(existing) || existing === void 0)) {
2006
2033
  const child = { ...existing ?? {} };
@@ -2014,14 +2041,14 @@ var mergeLeaf = (target, patch, source, provenance, path14) => {
2014
2041
  };
2015
2042
  var initialProvenance = (config) => {
2016
2043
  const provenance = {};
2017
- const walk = (value, path14) => {
2044
+ const walk = (value, path15) => {
2018
2045
  if (isPlainObject(value)) {
2019
2046
  for (const [key, child] of Object.entries(value)) {
2020
- walk(child, path14 === "" ? key : `${path14}.${key}`);
2047
+ walk(child, path15 === "" ? key : `${path15}.${key}`);
2021
2048
  }
2022
2049
  return;
2023
2050
  }
2024
- provenance[path14] = "defaults";
2051
+ provenance[path15] = "defaults";
2025
2052
  };
2026
2053
  walk(config, "");
2027
2054
  return provenance;
@@ -2192,7 +2219,9 @@ var describeResolvedConfig = (config) => {
2192
2219
  "detection.minimum_confidence": config.detection.minimumConfidence,
2193
2220
  "detection.allow_ambiguous_fallback": config.detection.allowAmbiguousFallback,
2194
2221
  "diagnostics.log_level": config.diagnostics.logLevel,
2195
- "diagnostics.emit_error_events": config.diagnostics.emitErrorEvents
2222
+ "diagnostics.emit_error_events": config.diagnostics.emitErrorEvents,
2223
+ // Whether, never where: the directory is a local path.
2224
+ "session_context.enabled": config.sessionContext?.dir !== void 0
2196
2225
  };
2197
2226
  };
2198
2227
 
@@ -2762,7 +2791,15 @@ var baseEventFields = {
2762
2791
  * factory, never by hand.
2763
2792
  */
2764
2793
  subagentId: subagentIdSchema.optional(),
2765
- extensions: extensionsSchema.default(emptyExtensions)
2794
+ extensions: extensionsSchema.default(emptyExtensions),
2795
+ /**
2796
+ * Attributes of the session context segment in force when the event
2797
+ * occurred (`docs/session-context.md`), stamped by the core from a file a
2798
+ * harness wrote. Exported on every record of the event, over the same keys
2799
+ * from the Resource. Absent when no context applies. Set by the core only,
2800
+ * never by an adapter.
2801
+ */
2802
+ contextAttributes: z15.record(z15.string().min(1).max(255), z15.union([z15.string(), z15.number(), z15.boolean()])).optional()
2766
2803
  };
2767
2804
  var event = (shape) => z15.strictObject({ ...baseEventFields, ...shape });
2768
2805
  var sessionStartEventSchema = event({
@@ -3091,7 +3128,8 @@ var policyFlagsToPatch = (policy) => {
3091
3128
  ...Object.keys(exporter).length === 0 ? {} : { exporter },
3092
3129
  ...Object.keys(privacy).length === 0 ? {} : { privacy },
3093
3130
  ...Object.keys(diagnostics).length === 0 ? {} : { diagnostics },
3094
- ...policy.claudeTranscriptUsage === true ? { providers: { claudeCode: { readTranscriptUsage: true } } } : {}
3131
+ ...policy.claudeTranscriptUsage === true ? { providers: { claudeCode: { readTranscriptUsage: true } } } : {},
3132
+ ...policy.sessionContextDir === void 0 ? {} : { sessionContext: { dir: policy.sessionContextDir } }
3095
3133
  };
3096
3134
  };
3097
3135
  var resolveCliExporterHeaders = (policy, io) => {
@@ -3180,7 +3218,7 @@ var createCliLogger = (io, level) => createStderrLogger({
3180
3218
  var readIdentityFile = readJsonFile;
3181
3219
 
3182
3220
  // src/cli/doctor.ts
3183
- import { readdir as readdir3 } from "fs/promises";
3221
+ import { readdir as readdir3, stat as stat2 } from "fs/promises";
3184
3222
  import * as path4 from "path";
3185
3223
 
3186
3224
  // src/diagnostics/health.ts
@@ -3445,11 +3483,11 @@ var createPrivacyService = (policyInput) => {
3445
3483
  };
3446
3484
  const flattenToAttributes = (value, prefix) => {
3447
3485
  const attributes = {};
3448
- const walk = (current, path14) => {
3486
+ const walk = (current, path15) => {
3449
3487
  if (typeof current === "string" || typeof current === "number" || typeof current === "boolean") {
3450
3488
  const primitive = toAttributePrimitive(current);
3451
3489
  if (primitive !== void 0) {
3452
- attributes[path14] = primitive;
3490
+ attributes[path15] = primitive;
3453
3491
  }
3454
3492
  return;
3455
3493
  }
@@ -3468,16 +3506,16 @@ var createPrivacyService = (policyInput) => {
3468
3506
  primitives.push(entryPrimitive);
3469
3507
  }
3470
3508
  if (uniform) {
3471
- attributes[path14] = primitives.slice(0, MAX_ATTRIBUTE_ARRAY_LENGTH);
3509
+ attributes[path15] = primitives.slice(0, MAX_ATTRIBUTE_ARRAY_LENGTH);
3472
3510
  return;
3473
3511
  }
3474
3512
  for (const [index, entry] of current.entries()) {
3475
- walk(entry, `${path14}.${index}`);
3513
+ walk(entry, `${path15}.${index}`);
3476
3514
  }
3477
3515
  return;
3478
3516
  }
3479
3517
  for (const [key, entry] of Object.entries(current)) {
3480
- walk(entry, path14 === "" ? key : `${path14}.${key}`);
3518
+ walk(entry, path15 === "" ? key : `${path15}.${key}`);
3481
3519
  }
3482
3520
  };
3483
3521
  walk(value, prefix);
@@ -3777,6 +3815,7 @@ var createEventFactory = (input) => {
3777
3815
  const rest = { ...drafted };
3778
3816
  delete rest.target;
3779
3817
  delete rest.subagentId;
3818
+ delete rest.contextAttributes;
3780
3819
  const sanitized = extensions === void 0 ? { extensions: {}, droppedKeys: [] } : context.privacy.sanitizeExtensions(extensions);
3781
3820
  dropped.push(...sanitized.droppedKeys);
3782
3821
  const currentSequence = sequence;
@@ -8508,6 +8547,33 @@ var replayResource = (attributes, policy) => {
8508
8547
  }
8509
8548
  return resourceFromAttributes(safe);
8510
8549
  };
8550
+ var agreedContextAttributes = (events) => {
8551
+ const [first, ...rest] = events;
8552
+ if (first?.contextAttributes === void 0) {
8553
+ return {};
8554
+ }
8555
+ const agreed = { ...first.contextAttributes };
8556
+ for (const event3 of rest) {
8557
+ for (const key of Object.keys(agreed)) {
8558
+ if (event3.contextAttributes?.[key] !== agreed[key]) {
8559
+ delete agreed[key];
8560
+ }
8561
+ }
8562
+ }
8563
+ return agreed;
8564
+ };
8565
+ var resourceWithContext = (resource, context) => {
8566
+ const overrides = {};
8567
+ for (const [key, value] of Object.entries(context)) {
8568
+ if (Object.hasOwn(resource.attributes, key) && !isReservedResourceAttributeKey(key) && resource.attributes[key] !== value) {
8569
+ overrides[key] = value;
8570
+ }
8571
+ }
8572
+ if (Object.keys(overrides).length === 0) {
8573
+ return resource;
8574
+ }
8575
+ return resourceFromAttributes({ ...resource.attributes, ...overrides });
8576
+ };
8511
8577
 
8512
8578
  // src/telemetry/log-records.ts
8513
8579
  import { SeverityNumber, TraceFlags as TraceFlags2 } from "@opentelemetry/api";
@@ -8577,6 +8643,11 @@ var passthroughResourceAttributes = (resource) => {
8577
8643
  }
8578
8644
  return attributes;
8579
8645
  };
8646
+ var contextAttributesOf = (event3) => event3.contextAttributes === void 0 ? {} : { ...event3.contextAttributes };
8647
+ var profileAttributes = (event3, resource) => ({
8648
+ ...passthroughResourceAttributes(resource),
8649
+ ...contextAttributesOf(event3)
8650
+ });
8580
8651
  var resolveExportedSessionId = (eventSessionId, resource) => {
8581
8652
  for (const key of EXTERNAL_SESSION_KEY_ATTRIBUTES) {
8582
8653
  const supplied = resource.attributes[key];
@@ -8597,6 +8668,8 @@ var hexTraceAttributes = (ids) => ({
8597
8668
  var exportIdentityAttributes = (event3, resource, ids) => {
8598
8669
  const { sessionId, providerSessionId } = resolveExportedSessionId(event3.sessionId, resource);
8599
8670
  return {
8671
+ // First, so nothing in the profile layer can replace an identity attribute.
8672
+ ...profileAttributes(event3, resource),
8600
8673
  [ATTR_SESSION_ID]: sessionId,
8601
8674
  [ATTR_OTELHOOK_SESSION_ID]: providerSessionId,
8602
8675
  [ATTR_GEN_AI_CONVERSATION_ID]: providerSessionId,
@@ -8605,7 +8678,6 @@ var exportIdentityAttributes = (event3, resource, ids) => {
8605
8678
  ...event3.provenance.providerVersion === void 0 ? {} : { [ATTR_OTELHOOK_PROVIDER_VERSION]: event3.provenance.providerVersion },
8606
8679
  [ATTR_OTELHOOK_WORKSPACE_ID]: event3.workspace.workspaceId,
8607
8680
  ...event3.subagentId === void 0 ? {} : { [ATTR_OTELHOOK_SUBAGENT_ID]: event3.subagentId },
8608
- ...passthroughResourceAttributes(resource),
8609
8681
  ...hexTraceAttributes(ids)
8610
8682
  };
8611
8683
  };
@@ -8630,7 +8702,7 @@ import {
8630
8702
  } from "@opentelemetry/semantic-conventions/incubating";
8631
8703
 
8632
8704
  // src/version.ts
8633
- var VERSION = "0.11.0";
8705
+ var VERSION = "0.12.0";
8634
8706
 
8635
8707
  // src/telemetry/semconv.ts
8636
8708
  var SCOPE_NAME = "@osfactory/otel-hook";
@@ -8778,12 +8850,12 @@ var pickTarget = (attributes) => {
8778
8850
  }
8779
8851
  return picked;
8780
8852
  };
8781
- var withoutTarget = (attributes, resource) => {
8853
+ var withoutTarget = (attributes, resource, event3) => {
8782
8854
  const rest = { ...attributes };
8783
8855
  for (const key of TARGET_KEYS) {
8784
8856
  delete rest[key];
8785
8857
  }
8786
- return { ...rest, ...pickTarget(passthroughResourceAttributes(resource)) };
8858
+ return { ...rest, ...pickTarget(profileAttributes(event3, resource)) };
8787
8859
  };
8788
8860
  var rankOf = (candidate) => {
8789
8861
  const source = candidate[ATTR_OTELHOOK_TARGET_SOURCE];
@@ -8888,7 +8960,7 @@ var buildLifecycleSpan = (plan, resource, scope) => {
8888
8960
  name = "session";
8889
8961
  kind = SpanKind.INTERNAL;
8890
8962
  attributes = {
8891
- ...withoutTarget(attributes, resource),
8963
+ ...withoutTarget(attributes, resource, anchor),
8892
8964
  ...strongestTarget([pickTarget(resolved.recovered), start === void 0 ? {} : targetAttributes(start)]),
8893
8965
  ...start?.agentName === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_NAME]: start.agentName },
8894
8966
  ...start?.agentVersion === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_VERSION]: start.agentVersion },
@@ -8930,7 +9002,7 @@ var buildLifecycleSpan = (plan, resource, scope) => {
8930
9002
  kind = SpanKind.CLIENT;
8931
9003
  attributes = {
8932
9004
  // Target keys are re-chosen below as one unit, never mixed across edges.
8933
- ...withoutTarget(attributes, resource),
9005
+ ...withoutTarget(attributes, resource, anchor),
8934
9006
  [ATTR_GEN_AI_TOOL_NAME]: toolName,
8935
9007
  [ATTR_GEN_AI_TOOL_CALL_ID]: start?.toolCallId ?? end?.toolCallId ?? group.ref.scopeKey,
8936
9008
  ...start?.toolKind === void 0 ? {} : { [ATTR_OTELHOOK_TOOL_KIND]: start.toolKind },
@@ -9660,10 +9732,10 @@ var createOtlpLogSink = (options) => {
9660
9732
  const exportRecords = (records) => new Promise((resolve8) => {
9661
9733
  exporter.export([...records], (result) => resolve8(result));
9662
9734
  });
9663
- const toSpoolBatch = (records) => ({
9735
+ const toSpoolBatch = (records, batchResource) => ({
9664
9736
  providerId: options.providerId,
9665
9737
  installationId: options.installationId,
9666
- resourceAttributes: { ...resource.attributes },
9738
+ resourceAttributes: { ...batchResource.attributes },
9667
9739
  instrumentationScope: {
9668
9740
  name: scope.name,
9669
9741
  ...scope.version === void 0 ? {} : { version: scope.version }
@@ -9698,8 +9770,9 @@ var createOtlpLogSink = (options) => {
9698
9770
  return { accepted: 0, rejected: 0, errors: [] };
9699
9771
  }
9700
9772
  const resolved = await resolveCorrelations(events);
9773
+ const batchResource = resourceWithContext(resource, agreedContextAttributes(events));
9701
9774
  const mapped = canonicalEventsToLogRecords(events, {
9702
- resource,
9775
+ resource: batchResource,
9703
9776
  instrumentationScope: scope,
9704
9777
  content,
9705
9778
  correlations: resolved.correlations,
@@ -9734,7 +9807,7 @@ var createOtlpLogSink = (options) => {
9734
9807
  health.recordFailure("telemetry-export-failure", batch.length, options.clock.now());
9735
9808
  const permanent = isPermanentExportFailure(result);
9736
9809
  if (options.spool !== void 0 && !permanent) {
9737
- const spoolResult = await options.spool.enqueue(toSpoolBatch(batch)).catch(() => ({
9810
+ const spoolResult = await options.spool.enqueue(toSpoolBatch(batch, batchResource)).catch(() => ({
9738
9811
  spooled: false,
9739
9812
  reason: "capacity-exceeded"
9740
9813
  }));
@@ -9887,10 +9960,10 @@ var createOtlpTraceSink = (options) => {
9887
9960
  const exportSpans = (spans) => new Promise((resolve8) => {
9888
9961
  exporter.export([...spans], (result) => resolve8(result));
9889
9962
  });
9890
- const toSpoolBatch = (spans) => ({
9963
+ const toSpoolBatch = (spans, batchResource) => ({
9891
9964
  providerId: options.providerId,
9892
9965
  installationId: options.installationId,
9893
- resourceAttributes: { ...resource.attributes },
9966
+ resourceAttributes: { ...batchResource.attributes },
9894
9967
  instrumentationScope: { name: scope.name, ...scope.version === void 0 ? {} : { version: scope.version } },
9895
9968
  spans: spans.map(serializeSpan),
9896
9969
  enqueuedAt: options.clock.now()
@@ -9920,8 +9993,9 @@ var createOtlpTraceSink = (options) => {
9920
9993
  return { accepted: 0, rejected: 0, errors: [] };
9921
9994
  }
9922
9995
  const resolved = await resolveCorrelations(events);
9996
+ const batchResource = resourceWithContext(resource, agreedContextAttributes(events));
9923
9997
  const spans = canonicalEventsToReadableSpans(events, {
9924
- resource,
9998
+ resource: batchResource,
9925
9999
  instrumentationScope: scope,
9926
10000
  correlations: resolved.correlations,
9927
10001
  ...resolved.available === void 0 ? {} : { correlationAvailable: resolved.available }
@@ -9947,7 +10021,7 @@ var createOtlpTraceSink = (options) => {
9947
10021
  health.recordFailure("telemetry-export-failure", batch.length, options.clock.now());
9948
10022
  const permanent = isPermanentExportFailure(result);
9949
10023
  if (options.spool !== void 0 && !permanent) {
9950
- const spoolResult = await options.spool.enqueue(toSpoolBatch(batch)).catch(() => ({
10024
+ const spoolResult = await options.spool.enqueue(toSpoolBatch(batch, batchResource)).catch(() => ({
9951
10025
  spooled: false,
9952
10026
  reason: "capacity-exceeded"
9953
10027
  }));
@@ -10099,6 +10173,9 @@ var ATTR_OTELHOOK_PROVIDER_ID2 = "otelhook.provider.id";
10099
10173
  var ATTR_OTELHOOK_OUTCOME3 = "otelhook.outcome";
10100
10174
  var ATTR_OTELHOOK_SESSION_KIND2 = "otelhook.session.kind";
10101
10175
  var commonAttributes = (event3, resource, includeSessionId) => ({
10176
+ // Session context first, so the metric's own attributes always win; and never
10177
+ // anything account-shaped, whatever the context says.
10178
+ ...event3.contextAttributes === void 0 ? {} : withoutAccountIdentity(event3.contextAttributes),
10102
10179
  [ATTR_OTELHOOK_PROVIDER_ID2]: event3.provenance.providerId,
10103
10180
  ...includeSessionId ? { [ATTR_SESSION_ID2]: resolveExportedSessionId(event3.sessionId, resource).sessionId } : {}
10104
10181
  });
@@ -10521,10 +10598,10 @@ var createOtlpMetricSink = (options) => {
10521
10598
  });
10522
10599
  }
10523
10600
  });
10524
- const toSpoolBatch = (points) => ({
10601
+ const toSpoolBatch = (points, batchResource) => ({
10525
10602
  providerId: options.providerId,
10526
10603
  installationId: options.installationId,
10527
- resourceAttributes: { ...resource.attributes },
10604
+ resourceAttributes: { ...batchResource.attributes },
10528
10605
  instrumentationScope: {
10529
10606
  name: scope.name,
10530
10607
  ...scope.version === void 0 ? {} : { version: scope.version }
@@ -10542,11 +10619,12 @@ var createOtlpMetricSink = (options) => {
10542
10619
  }
10543
10620
  return isPermanentExportFailure(result) ? "discard" : false;
10544
10621
  };
10545
- const exportPoints = async (points) => {
10622
+ const exportPoints = async (points, context) => {
10546
10623
  if (points.length === 0) {
10547
10624
  return { accepted: 0, rejected: 0, errors: [] };
10548
10625
  }
10549
- const result = await exportResourceMetrics(points, resource, scope);
10626
+ const batchResource = context === void 0 ? resource : resourceWithContext(resource, context);
10627
+ const result = await exportResourceMetrics(points, batchResource, scope);
10550
10628
  if (result.code === ExportResultCode3.SUCCESS) {
10551
10629
  health.recordSuccess(points.length, options.clock.now());
10552
10630
  return { accepted: points.length, rejected: 0, errors: [] };
@@ -10554,7 +10632,7 @@ var createOtlpMetricSink = (options) => {
10554
10632
  health.recordFailure("telemetry-export-failure", points.length, options.clock.now());
10555
10633
  const permanent = isPermanentExportFailure(result);
10556
10634
  if (options.spool !== void 0 && !permanent) {
10557
- const spooled = await options.spool.enqueue(toSpoolBatch(points)).catch(() => ({
10635
+ const spooled = await options.spool.enqueue(toSpoolBatch(points, batchResource)).catch(() => ({
10558
10636
  spooled: false,
10559
10637
  reason: "capacity-exceeded"
10560
10638
  }));
@@ -10970,6 +11048,20 @@ var collectDoctorReport = async (command, io) => {
10970
11048
  ok: resolved.config.privacy.contentMode === "omit" || resolved.config.privacy.allowRawContent,
10971
11049
  detail: `content mode is "${privacy.policy.contentMode}"${privacy.policyNotes.length === 0 ? "" : `; ${privacy.policyNotes.join("; ")}`}`
10972
11050
  });
11051
+ const contextDir = resolved.config.sessionContext?.dir;
11052
+ let contextDirExists = false;
11053
+ if (contextDir !== void 0) {
11054
+ try {
11055
+ contextDirExists = (await stat2(contextDir)).isDirectory();
11056
+ } catch {
11057
+ contextDirExists = false;
11058
+ }
11059
+ }
11060
+ checks.push({
11061
+ name: "session-context",
11062
+ ok: true,
11063
+ detail: contextDir === void 0 ? "off (sessionContext.dir is not set)" : `reading ${path4.join(contextDir, "<agent-tool>", "<session-id>.json")}${contextDirExists ? "" : " (directory does not exist yet; nothing is stamped until it does)"}`
11064
+ });
10973
11065
  const providers = describeProviderCatalog({
10974
11066
  includeExperimental: command.policy.includeExperimental ?? true
10975
11067
  });
@@ -12086,7 +12178,7 @@ var resolveInstallPath = (location, roots) => path5.resolve(
12086
12178
 
12087
12179
  // src/install/document.ts
12088
12180
  import { randomBytes as randomBytes3 } from "crypto";
12089
- import { chmod, mkdir as mkdir3, open as open2, readFile as readFile4, rename as rename3, stat as stat2, unlink as unlink3 } from "fs/promises";
12181
+ import { chmod, mkdir as mkdir3, open as open2, readFile as readFile4, rename as rename3, stat as stat3, unlink as unlink3 } from "fs/promises";
12090
12182
  import * as path6 from "path";
12091
12183
  var DEFAULT_DOCUMENT_FORMAT = Object.freeze({
12092
12184
  indent: " ",
@@ -12166,7 +12258,7 @@ var writeDocumentAtomically = async (filePath, contents) => {
12166
12258
  );
12167
12259
  let existingMode;
12168
12260
  try {
12169
- existingMode = (await stat2(filePath)).mode & 4095;
12261
+ existingMode = (await stat3(filePath)).mode & 4095;
12170
12262
  } catch (thrown) {
12171
12263
  if (!isErrnoException3(thrown, "ENOENT")) {
12172
12264
  throw thrown;
@@ -12191,7 +12283,7 @@ var writeDocumentAtomically = async (filePath, contents) => {
12191
12283
 
12192
12284
  // src/install/file-lock.ts
12193
12285
  import { randomBytes as randomBytes4 } from "crypto";
12194
- import { mkdir as mkdir4, open as open3, readFile as readFile5, rename as rename4, stat as stat3, unlink as unlink4 } from "fs/promises";
12286
+ import { mkdir as mkdir4, open as open3, readFile as readFile5, rename as rename4, stat as stat4, unlink as unlink4 } from "fs/promises";
12195
12287
  import * as path7 from "path";
12196
12288
  var FileLockTimeoutError = class extends Error {
12197
12289
  constructor(lockPath, timeoutMillis) {
@@ -12256,7 +12348,7 @@ var isStale = async (lockPath, clock, staleMillis) => {
12256
12348
  } catch {
12257
12349
  }
12258
12350
  try {
12259
- const stats = await stat3(lockPath);
12351
+ const stats = await stat4(lockPath);
12260
12352
  return { stale: clock.now() - stats.mtimeMs > staleMillis };
12261
12353
  } catch (thrown) {
12262
12354
  return { stale: !isErrnoException4(thrown, "ENOENT") };
@@ -12746,7 +12838,7 @@ var runRegistrationCommand = async (command, io) => {
12746
12838
  };
12747
12839
 
12748
12840
  // src/cli/run.ts
12749
- import * as path13 from "path";
12841
+ import * as path14 from "path";
12750
12842
 
12751
12843
  // src/lifecycle/dedup.ts
12752
12844
  import { randomBytes as randomBytes5 } from "crypto";
@@ -13632,7 +13724,7 @@ var createUsageAccumulator = (deps) => {
13632
13724
 
13633
13725
  // src/providers/claude/transcript.ts
13634
13726
  import { createHash as createHash5 } from "crypto";
13635
- import { open as open4, stat as stat4 } from "fs/promises";
13727
+ import { open as open4, stat as stat5 } from "fs/promises";
13636
13728
  import path10 from "path";
13637
13729
  var DEFAULT_CLAUDE_TRANSCRIPT_TAIL_BYTES = 1048576;
13638
13730
  var DEFAULT_CLAUDE_TRANSCRIPT_TIMEOUT_MILLIS = 250;
@@ -13721,7 +13813,7 @@ var withTimeout = async (work, timeoutMillis, onError) => {
13721
13813
  var withRegularFile = async (transcriptPath, body) => {
13722
13814
  let info;
13723
13815
  try {
13724
- info = await stat4(transcriptPath);
13816
+ info = await stat5(transcriptPath);
13725
13817
  } catch {
13726
13818
  return { status: "unavailable", reason: "unreadable" };
13727
13819
  }
@@ -13853,7 +13945,7 @@ var sourceDigest = (transcriptPath) => createHash5("sha256").update(transcriptPa
13853
13945
  var createClaudeTranscriptUsageEnricher = (options = {}) => {
13854
13946
  const fileSize = async (transcriptPath) => {
13855
13947
  try {
13856
- const info = await stat4(transcriptPath);
13948
+ const info = await stat5(transcriptPath);
13857
13949
  return info.isFile() ? info.size : void 0;
13858
13950
  } catch (thrown) {
13859
13951
  return thrown?.code === "ENOENT" ? "absent" : void 0;
@@ -13926,7 +14018,7 @@ var createClaudeTranscriptUsageEnricher = (options = {}) => {
13926
14018
  };
13927
14019
 
13928
14020
  // src/runtime/hook.ts
13929
- import { z as z23 } from "zod";
14021
+ import { z as z24 } from "zod";
13930
14022
 
13931
14023
  // src/runtime/delivery.ts
13932
14024
  var PROVIDER_SCOPE_PREFIX = "provider-session";
@@ -14086,8 +14178,200 @@ var resolveEventTargets = async (input) => {
14086
14178
  return { events, resolved: settled.size, timedOut: finished === "timeout" };
14087
14179
  };
14088
14180
 
14181
+ // src/runtime/session-context.ts
14182
+ import { open as open5 } from "fs/promises";
14183
+ import * as path12 from "path";
14184
+ import { z as z23 } from "zod";
14185
+ var SESSION_CONTEXT_FILE_VERSION = 1;
14186
+ var DEFAULT_SESSION_CONTEXT_MAX_BYTES = 256 * 1024;
14187
+ var DEFAULT_SESSION_CONTEXT_BUDGET_MILLIS = 100;
14188
+ var MAX_SESSION_CONTEXT_SEGMENTS = 1024;
14189
+ var SESSION_CONTEXT_AGENT_TOOLS = Object.freeze({
14190
+ "claude-code": "claude_code",
14191
+ codex: "codex",
14192
+ cursor: "cursor",
14193
+ "gemini-cli": "gemini_cli",
14194
+ antigravity: "antigravity"
14195
+ });
14196
+ var sessionContextAgentTool = (providerId) => Object.hasOwn(SESSION_CONTEXT_AGENT_TOOLS, providerId) ? SESSION_CONTEXT_AGENT_TOOLS[providerId] : void 0;
14197
+ var SESSION_FILE_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/;
14198
+ var isSessionContextFileName = (sessionId) => SESSION_FILE_NAME_PATTERN.test(sessionId) && !sessionId.includes("..");
14199
+ var sessionContextFilePath = (dir, providerId, sessionId) => {
14200
+ const tool = sessionContextAgentTool(providerId);
14201
+ if (tool === void 0 || !isSessionContextFileName(sessionId) || !path12.isAbsolute(dir)) {
14202
+ return void 0;
14203
+ }
14204
+ return path12.join(dir, tool, `${sessionId}.json`);
14205
+ };
14206
+ var RESERVED_CONTEXT_KEYS = /* @__PURE__ */ new Set([
14207
+ "session.id",
14208
+ "trace_id",
14209
+ "span_id",
14210
+ "parent_span_id",
14211
+ "gen_ai.conversation.id",
14212
+ "factory.local"
14213
+ ]);
14214
+ var RESERVED_CONTEXT_PREFIXES = Object.freeze(["factory.local.", "otelhook."]);
14215
+ var isReservedSessionContextKey = (key) => RESERVED_CONTEXT_KEYS.has(key) || RESERVED_CONTEXT_PREFIXES.some((prefix) => key.startsWith(prefix));
14216
+ var sanitizeSessionContextAttributes = (attributes) => {
14217
+ const kept = {};
14218
+ let count = 0;
14219
+ for (const [key, value] of Object.entries(attributes)) {
14220
+ if (count >= MAX_RESOURCE_ATTRIBUTES) {
14221
+ break;
14222
+ }
14223
+ if (checkResourceAttributeKey(key) !== void 0 || isReservedSessionContextKey(key)) {
14224
+ continue;
14225
+ }
14226
+ if (typeof value === "string") {
14227
+ if (value.length > MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH) {
14228
+ continue;
14229
+ }
14230
+ } else if (typeof value === "number") {
14231
+ if (!Number.isFinite(value)) {
14232
+ continue;
14233
+ }
14234
+ } else if (typeof value !== "boolean") {
14235
+ continue;
14236
+ }
14237
+ kept[key] = value;
14238
+ count += 1;
14239
+ }
14240
+ return kept;
14241
+ };
14242
+ 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})$/;
14243
+ var isoInstantSchema = z23.string().max(64).regex(ISO_INSTANT_PATTERN).transform((value, ctx) => {
14244
+ const millis = Date.parse(value);
14245
+ if (!Number.isFinite(millis)) {
14246
+ ctx.issues.push({ code: "custom", input: value, message: "not a valid instant" });
14247
+ return z23.NEVER;
14248
+ }
14249
+ return millis;
14250
+ });
14251
+ var segmentSchema = z23.object({
14252
+ from: isoInstantSchema,
14253
+ to: isoInstantSchema.nullable(),
14254
+ reason: z23.string().max(256).optional(),
14255
+ attributes: z23.record(z23.string(), z23.unknown())
14256
+ });
14257
+ var sessionContextFileSchema = z23.object({
14258
+ version: z23.literal(SESSION_CONTEXT_FILE_VERSION),
14259
+ agentTool: z23.string().max(64).optional(),
14260
+ sessionId: z23.string().max(256).optional(),
14261
+ segments: z23.array(segmentSchema).max(MAX_SESSION_CONTEXT_SEGMENTS)
14262
+ });
14263
+ var parseSessionContextFile = (value, expected) => {
14264
+ const parsed = sessionContextFileSchema.safeParse(value);
14265
+ if (!parsed.success) {
14266
+ return void 0;
14267
+ }
14268
+ const file = parsed.data;
14269
+ 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) {
14270
+ return void 0;
14271
+ }
14272
+ return file.segments.map((segment) => ({
14273
+ from: segment.from,
14274
+ to: segment.to,
14275
+ attributes: sanitizeSessionContextAttributes(segment.attributes)
14276
+ }));
14277
+ };
14278
+ var segmentInForce = (segments, at) => {
14279
+ let best;
14280
+ for (const segment of segments) {
14281
+ if (segment.from <= at && (segment.to === null || at < segment.to)) {
14282
+ if (best === void 0 || segment.from >= best.from) {
14283
+ best = segment;
14284
+ }
14285
+ }
14286
+ }
14287
+ return best;
14288
+ };
14289
+ var stampSessionContext = (events, segments) => events.map((event3) => {
14290
+ const { contextAttributes: _discarded, ...rest } = event3;
14291
+ const segment = segments === void 0 ? void 0 : segmentInForce(segments, event3.occurredAt);
14292
+ if (segment === void 0 || Object.keys(segment.attributes).length === 0) {
14293
+ return _discarded === void 0 ? event3 : rest;
14294
+ }
14295
+ return { ...rest, contextAttributes: { ...segment.attributes } };
14296
+ });
14297
+ var readBounded = async (file, maxBytes) => {
14298
+ let handle;
14299
+ try {
14300
+ handle = await open5(file, "r");
14301
+ } catch {
14302
+ return void 0;
14303
+ }
14304
+ try {
14305
+ const stats = await handle.stat();
14306
+ if (!stats.isFile() || stats.size > maxBytes) {
14307
+ return void 0;
14308
+ }
14309
+ const buffer = Buffer.alloc(maxBytes + 1);
14310
+ let length = 0;
14311
+ while (length < buffer.length) {
14312
+ const { bytesRead } = await handle.read(buffer, length, buffer.length - length, length);
14313
+ if (bytesRead === 0) {
14314
+ break;
14315
+ }
14316
+ length += bytesRead;
14317
+ }
14318
+ if (length > maxBytes) {
14319
+ return void 0;
14320
+ }
14321
+ return buffer.subarray(0, length).toString("utf8");
14322
+ } catch {
14323
+ return void 0;
14324
+ } finally {
14325
+ await handle.close().catch(() => void 0);
14326
+ }
14327
+ };
14328
+ var createDirectorySessionContextReader = (options) => {
14329
+ const maxBytes = options.maxBytes ?? DEFAULT_SESSION_CONTEXT_MAX_BYTES;
14330
+ const budgetMillis = options.budgetMillis ?? DEFAULT_SESSION_CONTEXT_BUDGET_MILLIS;
14331
+ const readOnce = async (providerId, sessionId) => {
14332
+ const file = sessionContextFilePath(options.dir, providerId, sessionId);
14333
+ if (file === void 0) {
14334
+ return void 0;
14335
+ }
14336
+ const text = await readBounded(file, maxBytes);
14337
+ if (text === void 0) {
14338
+ return void 0;
14339
+ }
14340
+ let decoded;
14341
+ try {
14342
+ decoded = JSON.parse(text);
14343
+ } catch {
14344
+ return void 0;
14345
+ }
14346
+ const agentTool = sessionContextAgentTool(providerId);
14347
+ return parseSessionContextFile(decoded, {
14348
+ ...agentTool === void 0 ? {} : { agentTool },
14349
+ sessionId
14350
+ });
14351
+ };
14352
+ return {
14353
+ read: async (request) => {
14354
+ let timer;
14355
+ const timeout = new Promise((resolve8) => {
14356
+ timer = setTimeout(() => resolve8(void 0), budgetMillis);
14357
+ timer.unref?.();
14358
+ });
14359
+ try {
14360
+ return await Promise.race([
14361
+ readOnce(request.providerId, request.sessionId).catch(() => void 0),
14362
+ timeout
14363
+ ]);
14364
+ } finally {
14365
+ if (timer !== void 0) {
14366
+ clearTimeout(timer);
14367
+ }
14368
+ }
14369
+ }
14370
+ };
14371
+ };
14372
+
14089
14373
  // src/runtime/hook.ts
14090
- var usageScopeSchema = z23.enum(["session", "generation", "subagent"]);
14374
+ var usageScopeSchema = z24.enum(["session", "generation", "subagent"]);
14091
14375
  var classifyDurability = (input) => {
14092
14376
  if (!input.attempted) {
14093
14377
  return "nothing-to-deliver";
@@ -14796,6 +15080,10 @@ var createOtelHook = (deps) => {
14796
15080
  });
14797
15081
  }
14798
15082
  }
15083
+ batch = stampSessionContext(
15084
+ batch,
15085
+ !suppress && batch.length > 0 && deps.sessionContext !== void 0 ? await readSessionContext(deps.sessionContext, detection.providerId, identity.sessionId) : void 0
15086
+ );
14799
15087
  let emitted = 0;
14800
15088
  let exportRejected = 0;
14801
15089
  if (!suppress && batch.length > 0) {
@@ -14911,6 +15199,13 @@ var createOtelHook = (deps) => {
14911
15199
  };
14912
15200
  return { resolveDelivery, ingest, flush, shutdown, config };
14913
15201
  };
15202
+ var readSessionContext = async (reader, providerId, sessionId) => {
15203
+ try {
15204
+ return await reader.read({ providerId, sessionId });
15205
+ } catch {
15206
+ return void 0;
15207
+ }
15208
+ };
14914
15209
  var buildErrorEvents = (diagnostics, identity, sequenceBase, ids, privacy) => {
14915
15210
  const events = [];
14916
15211
  for (const [index, info] of diagnostics.slice(0, MAX_ERROR_EVENTS).entries()) {
@@ -14945,8 +15240,8 @@ var buildErrorEvents = (diagnostics, identity, sequenceBase, ids, privacy) => {
14945
15240
  };
14946
15241
 
14947
15242
  // src/runtime/git-worktree.ts
14948
- import { lstat, open as open5, stat as stat5 } from "fs/promises";
14949
- import * as path12 from "path";
15243
+ import { lstat, open as open6, stat as stat6 } from "fs/promises";
15244
+ import * as path13 from "path";
14950
15245
  var MAX_WORKTREE_WALK_DEPTH = 128;
14951
15246
  var MAX_GIT_FILE_BYTES = 4096;
14952
15247
  var MAX_CACHE_ENTRIES = 1024;
@@ -14954,10 +15249,10 @@ var DEFAULT_WORKTREE_CACHE_TTL_MILLIS = 5e3;
14954
15249
  var MAX_BRANCH_NAME_LENGTH = 255;
14955
15250
  var ABSENT = Object.freeze({ kind: "absent" });
14956
15251
  var INVALID = Object.freeze({ kind: "invalid" });
14957
- var readBounded = async (filePath) => {
15252
+ var readBounded2 = async (filePath) => {
14958
15253
  let handle;
14959
15254
  try {
14960
- handle = await open5(filePath, "r");
15255
+ handle = await open6(filePath, "r");
14961
15256
  const buffer = Buffer.alloc(MAX_GIT_FILE_BYTES);
14962
15257
  const { bytesRead } = await handle.read(buffer, 0, MAX_GIT_FILE_BYTES, 0);
14963
15258
  return buffer.subarray(0, bytesRead).toString("utf8");
@@ -14978,7 +15273,7 @@ var parseHeadBranch = (head) => {
14978
15273
  return branch;
14979
15274
  };
14980
15275
  var firstLine = (content) => content.split(/\r?\n/, 1)[0]?.trim() ?? "";
14981
- var resolveGitPath = (target, base) => target === void 0 || target.length === 0 || target.includes("\0") ? void 0 : path12.resolve(base, target);
15276
+ var resolveGitPath = (target, base) => target === void 0 || target.length === 0 || target.includes("\0") ? void 0 : path13.resolve(base, target);
14982
15277
  var parseGitDirFile = (content, worktreeRoot) => {
14983
15278
  const line = firstLine(content);
14984
15279
  return resolveGitPath(
@@ -14998,26 +15293,26 @@ var isMissing = async (filePath) => {
14998
15293
  };
14999
15294
  var isDirectory = async (directory) => {
15000
15295
  try {
15001
- return (await stat5(directory)).isDirectory();
15296
+ return (await stat6(directory)).isDirectory();
15002
15297
  } catch {
15003
15298
  return false;
15004
15299
  }
15005
15300
  };
15006
15301
  var repositoryOf = async (worktreeRoot, gitDir) => {
15007
- const commonDirFile = path12.join(gitDir, "commondir");
15008
- const content = await readBounded(commonDirFile);
15302
+ const commonDirFile = path13.join(gitDir, "commondir");
15303
+ const content = await readBounded2(commonDirFile);
15009
15304
  if (content === void 0) {
15010
15305
  return await isMissing(commonDirFile) ? { kind: "main", mainRoot: worktreeRoot } : { kind: "linked" };
15011
15306
  }
15012
15307
  const commonDir = parseCommonDirFile(content, gitDir);
15013
- const mainRoot = commonDir !== void 0 && path12.basename(commonDir) === ".git" && await isDirectory(commonDir) ? path12.dirname(commonDir) : void 0;
15308
+ const mainRoot = commonDir !== void 0 && path13.basename(commonDir) === ".git" && await isDirectory(commonDir) ? path13.dirname(commonDir) : void 0;
15014
15309
  return { kind: "linked", ...mainRoot === void 0 ? {} : { mainRoot } };
15015
15310
  };
15016
15311
  var probeDirectory = async (directory) => {
15017
- const dotGit = path12.join(directory, ".git");
15312
+ const dotGit = path13.join(directory, ".git");
15018
15313
  let info;
15019
15314
  try {
15020
- info = await stat5(dotGit);
15315
+ info = await stat6(dotGit);
15021
15316
  } catch {
15022
15317
  return ABSENT;
15023
15318
  }
@@ -15025,13 +15320,13 @@ var probeDirectory = async (directory) => {
15025
15320
  if (info.isDirectory()) {
15026
15321
  gitDir = dotGit;
15027
15322
  } else if (info.isFile()) {
15028
- const content = await readBounded(dotGit);
15323
+ const content = await readBounded2(dotGit);
15029
15324
  gitDir = content === void 0 ? void 0 : parseGitDirFile(content, directory);
15030
15325
  }
15031
15326
  if (gitDir === void 0) {
15032
15327
  return INVALID;
15033
15328
  }
15034
- const head = await readBounded(path12.join(gitDir, "HEAD"));
15329
+ const head = await readBounded2(path13.join(gitDir, "HEAD"));
15035
15330
  if (head === void 0) {
15036
15331
  return INVALID;
15037
15332
  }
@@ -15061,10 +15356,10 @@ var createFilesystemWorktreeLocator = (options = {}) => {
15061
15356
  };
15062
15357
  const locate = async (absolutePath) => {
15063
15358
  try {
15064
- if (!path12.isAbsolute(absolutePath) || absolutePath.includes("\0")) {
15359
+ if (!path13.isAbsolute(absolutePath) || absolutePath.includes("\0")) {
15065
15360
  return void 0;
15066
15361
  }
15067
- let directory = path12.resolve(absolutePath);
15362
+ let directory = path13.resolve(absolutePath);
15068
15363
  for (let depth = 0; depth < MAX_WORKTREE_WALK_DEPTH; depth += 1) {
15069
15364
  const probe = await cachedProbe(directory);
15070
15365
  if (probe.kind === "worktree") {
@@ -15073,7 +15368,7 @@ var createFilesystemWorktreeLocator = (options = {}) => {
15073
15368
  if (probe.kind === "invalid") {
15074
15369
  return void 0;
15075
15370
  }
15076
- const parent = path12.dirname(directory);
15371
+ const parent = path13.dirname(directory);
15077
15372
  if (parent === directory) {
15078
15373
  return void 0;
15079
15374
  }
@@ -15200,6 +15495,16 @@ var createHookRuntime = (options) => {
15200
15495
  logger,
15201
15496
  installationId: options.installationId,
15202
15497
  payloadEnrichers: options.payloadEnrichers ?? (readsClaudeTranscriptUsage(options.config) ? [createClaudeTranscriptUsageEnricher()] : []),
15498
+ ...(() => {
15499
+ if (options.sessionContextReader === null) {
15500
+ return {};
15501
+ }
15502
+ if (options.sessionContextReader !== void 0) {
15503
+ return { sessionContext: options.sessionContextReader };
15504
+ }
15505
+ const dir = sessionContextDir(options.config);
15506
+ return dir === void 0 ? {} : { sessionContext: createDirectorySessionContextReader({ dir }) };
15507
+ })(),
15203
15508
  ...options.worktreeLocator === null ? {} : {
15204
15509
  worktreeLocator: options.worktreeLocator ?? createFilesystemWorktreeLocator({ monotonicMillis: () => clock.monotonicMillis() })
15205
15510
  }
@@ -15293,9 +15598,10 @@ var createHookRuntime = (options) => {
15293
15598
  perSession: metricsPolicy.includeSessionId,
15294
15599
  ...deliveryToken === void 0 ? {} : { deliveryToken }
15295
15600
  });
15601
+ const context = agreedContextAttributes(ingest.events);
15296
15602
  const results = await Promise.all(
15297
15603
  metricDestinations.map(async (destination) => {
15298
- const result = await destination.metrics.exportPoints(points).catch(
15604
+ const result = await destination.metrics.exportPoints(points, context).catch(
15299
15605
  (thrown) => ({
15300
15606
  accepted: 0,
15301
15607
  rejected: points.length,
@@ -15864,13 +16170,13 @@ var runHookCommand = async (command, io) => {
15864
16170
  }
15865
16171
  const identityClaims = [];
15866
16172
  if (command.identity.identityFile !== void 0) {
15867
- const read = await readIdentityFile(path13.resolve(command.identity.identityFile));
16173
+ const read = await readIdentityFile(path14.resolve(command.identity.identityFile));
15868
16174
  if ("error" in read) {
15869
16175
  logDiagnostics(logger, [read.error]);
15870
16176
  } else {
15871
16177
  const fromFile = claimFromIdentityFile(
15872
16178
  read.value,
15873
- path13.basename(command.identity.identityFile)
16179
+ path14.basename(command.identity.identityFile)
15874
16180
  );
15875
16181
  logDiagnostics(logger, fromFile.errors);
15876
16182
  identityClaims.push(...fromFile.claims);