@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/index.js CHANGED
@@ -833,7 +833,15 @@ var baseEventFields = {
833
833
  * factory, never by hand.
834
834
  */
835
835
  subagentId: subagentIdSchema.optional(),
836
- extensions: extensionsSchema.default(emptyExtensions)
836
+ extensions: extensionsSchema.default(emptyExtensions),
837
+ /**
838
+ * Attributes of the session context segment in force when the event
839
+ * occurred (`docs/session-context.md`), stamped by the core from a file a
840
+ * harness wrote. Exported on every record of the event, over the same keys
841
+ * from the Resource. Absent when no context applies. Set by the core only,
842
+ * never by an adapter.
843
+ */
844
+ contextAttributes: z9.record(z9.string().min(1).max(255), z9.union([z9.string(), z9.number(), z9.boolean()])).optional()
837
845
  };
838
846
  var event = (shape) => z9.strictObject({ ...baseEventFields, ...shape });
839
847
  var sessionStartEventSchema = event({
@@ -1352,11 +1360,11 @@ var createPrivacyService = (policyInput) => {
1352
1360
  };
1353
1361
  const flattenToAttributes = (value, prefix) => {
1354
1362
  const attributes = {};
1355
- const walk = (current, path10) => {
1363
+ const walk = (current, path11) => {
1356
1364
  if (typeof current === "string" || typeof current === "number" || typeof current === "boolean") {
1357
1365
  const primitive = toAttributePrimitive(current);
1358
1366
  if (primitive !== void 0) {
1359
- attributes[path10] = primitive;
1367
+ attributes[path11] = primitive;
1360
1368
  }
1361
1369
  return;
1362
1370
  }
@@ -1375,16 +1383,16 @@ var createPrivacyService = (policyInput) => {
1375
1383
  primitives.push(entryPrimitive);
1376
1384
  }
1377
1385
  if (uniform) {
1378
- attributes[path10] = primitives.slice(0, MAX_ATTRIBUTE_ARRAY_LENGTH);
1386
+ attributes[path11] = primitives.slice(0, MAX_ATTRIBUTE_ARRAY_LENGTH);
1379
1387
  return;
1380
1388
  }
1381
1389
  for (const [index, entry] of current.entries()) {
1382
- walk(entry, `${path10}.${index}`);
1390
+ walk(entry, `${path11}.${index}`);
1383
1391
  }
1384
1392
  return;
1385
1393
  }
1386
1394
  for (const [key, entry] of Object.entries(current)) {
1387
- walk(entry, path10 === "" ? key : `${path10}.${key}`);
1395
+ walk(entry, path11 === "" ? key : `${path11}.${key}`);
1388
1396
  }
1389
1397
  };
1390
1398
  walk(value, prefix);
@@ -1683,6 +1691,7 @@ var sanitizeResourceAttributes = (attributes) => {
1683
1691
  var describeResourceAttributeNames = (attributes) => Object.keys(attributes).sort();
1684
1692
 
1685
1693
  // src/config/schema.ts
1694
+ import { isAbsolute } from "path";
1686
1695
  import { z as z14 } from "zod";
1687
1696
 
1688
1697
  // src/config/destinations.ts
@@ -2119,13 +2128,19 @@ var providersPolicySchema = z14.strictObject({
2119
2128
  readTranscriptUsage: z14.boolean()
2120
2129
  }).optional()
2121
2130
  });
2131
+ var sessionContextPolicySchema = z14.strictObject({
2132
+ /** Absolute path of the context directory. */
2133
+ dir: z14.string().min(1).max(4096).refine((value) => isAbsolute(value), { message: "must be an absolute path" })
2134
+ });
2122
2135
  var otelHookConfigSchema = z14.strictObject({
2123
2136
  exporter: exporterPolicySchema,
2124
2137
  privacy: privacyPolicySchema,
2125
2138
  detection: detectionPolicySchema,
2126
2139
  diagnostics: diagnosticsPolicySchema,
2127
2140
  /** Optional so a hand-built configuration from before it existed stays valid. */
2128
- providers: providersPolicySchema.optional()
2141
+ providers: providersPolicySchema.optional(),
2142
+ /** Optional: absent means no session context is read. */
2143
+ sessionContext: sessionContextPolicySchema.optional()
2129
2144
  });
2130
2145
  var otelHookConfigPatchSchema = z14.strictObject({
2131
2146
  // `logs` is unwrapped and re-partialled for the same reason `privacy.limits` is:
@@ -2141,7 +2156,8 @@ var otelHookConfigPatchSchema = z14.strictObject({
2141
2156
  diagnostics: diagnosticsPolicySchema.partial().optional(),
2142
2157
  providers: z14.strictObject({
2143
2158
  claudeCode: z14.strictObject({ readTranscriptUsage: z14.boolean() }).partial().optional()
2144
- }).partial().optional()
2159
+ }).partial().optional(),
2160
+ sessionContext: sessionContextPolicySchema.partial().optional()
2145
2161
  });
2146
2162
  var DEFAULT_EXPORTER_POLICY = Object.freeze({
2147
2163
  enabled: true,
@@ -2176,6 +2192,7 @@ var DEFAULT_CONFIG = Object.freeze({
2176
2192
  providers: DEFAULT_PROVIDERS_POLICY
2177
2193
  });
2178
2194
  var readsClaudeTranscriptUsage = (config) => config.providers?.claudeCode?.readTranscriptUsage === true;
2195
+ var sessionContextDir = (config) => config.sessionContext?.dir;
2179
2196
  var effectiveMetricsPolicy = (exporter) => ({
2180
2197
  ...DEFAULT_METRICS_POLICY,
2181
2198
  ...exporter.metrics ?? {}
@@ -2186,12 +2203,12 @@ import { z as z15 } from "zod";
2186
2203
  var CONFIG_SOURCE_PRECEDENCE = ["defaults", "file", "environment", "inline-override"];
2187
2204
  var configSourceSchema = z15.enum(CONFIG_SOURCE_PRECEDENCE);
2188
2205
  var isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2189
- var mergeLeaf = (target, patch, source, provenance, path10) => {
2206
+ var mergeLeaf = (target, patch, source, provenance, path11) => {
2190
2207
  for (const [key, value] of Object.entries(patch)) {
2191
2208
  if (value === void 0) {
2192
2209
  continue;
2193
2210
  }
2194
- const childPath = path10 === "" ? key : `${path10}.${key}`;
2211
+ const childPath = path11 === "" ? key : `${path11}.${key}`;
2195
2212
  const existing = target[key];
2196
2213
  if (isPlainObject(value) && (isPlainObject(existing) || existing === void 0)) {
2197
2214
  const child = { ...existing ?? {} };
@@ -2205,14 +2222,14 @@ var mergeLeaf = (target, patch, source, provenance, path10) => {
2205
2222
  };
2206
2223
  var initialProvenance = (config) => {
2207
2224
  const provenance = {};
2208
- const walk = (value, path10) => {
2225
+ const walk = (value, path11) => {
2209
2226
  if (isPlainObject(value)) {
2210
2227
  for (const [key, child] of Object.entries(value)) {
2211
- walk(child, path10 === "" ? key : `${path10}.${key}`);
2228
+ walk(child, path11 === "" ? key : `${path11}.${key}`);
2212
2229
  }
2213
2230
  return;
2214
2231
  }
2215
- provenance[path10] = "defaults";
2232
+ provenance[path11] = "defaults";
2216
2233
  };
2217
2234
  walk(config, "");
2218
2235
  return provenance;
@@ -2383,7 +2400,9 @@ var describeResolvedConfig = (config) => {
2383
2400
  "detection.minimum_confidence": config.detection.minimumConfidence,
2384
2401
  "detection.allow_ambiguous_fallback": config.detection.allowAmbiguousFallback,
2385
2402
  "diagnostics.log_level": config.diagnostics.logLevel,
2386
- "diagnostics.emit_error_events": config.diagnostics.emitErrorEvents
2403
+ "diagnostics.emit_error_events": config.diagnostics.emitErrorEvents,
2404
+ // Whether, never where: the directory is a local path.
2405
+ "session_context.enabled": config.sessionContext?.dir !== void 0
2387
2406
  };
2388
2407
  };
2389
2408
 
@@ -2835,6 +2854,7 @@ var createEventFactory = (input) => {
2835
2854
  const rest = { ...drafted };
2836
2855
  delete rest.target;
2837
2856
  delete rest.subagentId;
2857
+ delete rest.contextAttributes;
2838
2858
  const sanitized = extensions === void 0 ? { extensions: {}, droppedKeys: [] } : context.privacy.sanitizeExtensions(extensions);
2839
2859
  dropped.push(...sanitized.droppedKeys);
2840
2860
  const currentSequence = sequence;
@@ -7334,7 +7354,7 @@ var resolveDeliveryIdentity = (input) => {
7334
7354
  };
7335
7355
 
7336
7356
  // src/runtime/hook.ts
7337
- import { z as z23 } from "zod";
7357
+ import { z as z24 } from "zod";
7338
7358
 
7339
7359
  // src/runtime/target-resolution.ts
7340
7360
  import * as path2 from "path";
@@ -7503,8 +7523,200 @@ var withOptionalSessionLock = async (store, sessionId, fn, options) => {
7503
7523
  return fn();
7504
7524
  };
7505
7525
 
7526
+ // src/runtime/session-context.ts
7527
+ import { open as open2 } from "fs/promises";
7528
+ import * as path3 from "path";
7529
+ import { z as z23 } from "zod";
7530
+ var SESSION_CONTEXT_FILE_VERSION = 1;
7531
+ var DEFAULT_SESSION_CONTEXT_MAX_BYTES = 256 * 1024;
7532
+ var DEFAULT_SESSION_CONTEXT_BUDGET_MILLIS = 100;
7533
+ var MAX_SESSION_CONTEXT_SEGMENTS = 1024;
7534
+ var SESSION_CONTEXT_AGENT_TOOLS = Object.freeze({
7535
+ "claude-code": "claude_code",
7536
+ codex: "codex",
7537
+ cursor: "cursor",
7538
+ "gemini-cli": "gemini_cli",
7539
+ antigravity: "antigravity"
7540
+ });
7541
+ var sessionContextAgentTool = (providerId) => Object.hasOwn(SESSION_CONTEXT_AGENT_TOOLS, providerId) ? SESSION_CONTEXT_AGENT_TOOLS[providerId] : void 0;
7542
+ var SESSION_FILE_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/;
7543
+ var isSessionContextFileName = (sessionId) => SESSION_FILE_NAME_PATTERN.test(sessionId) && !sessionId.includes("..");
7544
+ var sessionContextFilePath = (dir, providerId, sessionId) => {
7545
+ const tool = sessionContextAgentTool(providerId);
7546
+ if (tool === void 0 || !isSessionContextFileName(sessionId) || !path3.isAbsolute(dir)) {
7547
+ return void 0;
7548
+ }
7549
+ return path3.join(dir, tool, `${sessionId}.json`);
7550
+ };
7551
+ var RESERVED_CONTEXT_KEYS = /* @__PURE__ */ new Set([
7552
+ "session.id",
7553
+ "trace_id",
7554
+ "span_id",
7555
+ "parent_span_id",
7556
+ "gen_ai.conversation.id",
7557
+ "factory.local"
7558
+ ]);
7559
+ var RESERVED_CONTEXT_PREFIXES = Object.freeze(["factory.local.", "otelhook."]);
7560
+ var isReservedSessionContextKey = (key) => RESERVED_CONTEXT_KEYS.has(key) || RESERVED_CONTEXT_PREFIXES.some((prefix) => key.startsWith(prefix));
7561
+ var sanitizeSessionContextAttributes = (attributes) => {
7562
+ const kept = {};
7563
+ let count = 0;
7564
+ for (const [key, value] of Object.entries(attributes)) {
7565
+ if (count >= MAX_RESOURCE_ATTRIBUTES) {
7566
+ break;
7567
+ }
7568
+ if (checkResourceAttributeKey(key) !== void 0 || isReservedSessionContextKey(key)) {
7569
+ continue;
7570
+ }
7571
+ if (typeof value === "string") {
7572
+ if (value.length > MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH) {
7573
+ continue;
7574
+ }
7575
+ } else if (typeof value === "number") {
7576
+ if (!Number.isFinite(value)) {
7577
+ continue;
7578
+ }
7579
+ } else if (typeof value !== "boolean") {
7580
+ continue;
7581
+ }
7582
+ kept[key] = value;
7583
+ count += 1;
7584
+ }
7585
+ return kept;
7586
+ };
7587
+ 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})$/;
7588
+ var isoInstantSchema = z23.string().max(64).regex(ISO_INSTANT_PATTERN).transform((value, ctx) => {
7589
+ const millis = Date.parse(value);
7590
+ if (!Number.isFinite(millis)) {
7591
+ ctx.issues.push({ code: "custom", input: value, message: "not a valid instant" });
7592
+ return z23.NEVER;
7593
+ }
7594
+ return millis;
7595
+ });
7596
+ var segmentSchema = z23.object({
7597
+ from: isoInstantSchema,
7598
+ to: isoInstantSchema.nullable(),
7599
+ reason: z23.string().max(256).optional(),
7600
+ attributes: z23.record(z23.string(), z23.unknown())
7601
+ });
7602
+ var sessionContextFileSchema = z23.object({
7603
+ version: z23.literal(SESSION_CONTEXT_FILE_VERSION),
7604
+ agentTool: z23.string().max(64).optional(),
7605
+ sessionId: z23.string().max(256).optional(),
7606
+ segments: z23.array(segmentSchema).max(MAX_SESSION_CONTEXT_SEGMENTS)
7607
+ });
7608
+ var parseSessionContextFile = (value, expected) => {
7609
+ const parsed = sessionContextFileSchema.safeParse(value);
7610
+ if (!parsed.success) {
7611
+ return void 0;
7612
+ }
7613
+ const file = parsed.data;
7614
+ 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) {
7615
+ return void 0;
7616
+ }
7617
+ return file.segments.map((segment) => ({
7618
+ from: segment.from,
7619
+ to: segment.to,
7620
+ attributes: sanitizeSessionContextAttributes(segment.attributes)
7621
+ }));
7622
+ };
7623
+ var segmentInForce = (segments, at) => {
7624
+ let best;
7625
+ for (const segment of segments) {
7626
+ if (segment.from <= at && (segment.to === null || at < segment.to)) {
7627
+ if (best === void 0 || segment.from >= best.from) {
7628
+ best = segment;
7629
+ }
7630
+ }
7631
+ }
7632
+ return best;
7633
+ };
7634
+ var stampSessionContext = (events, segments) => events.map((event3) => {
7635
+ const { contextAttributes: _discarded, ...rest } = event3;
7636
+ const segment = segments === void 0 ? void 0 : segmentInForce(segments, event3.occurredAt);
7637
+ if (segment === void 0 || Object.keys(segment.attributes).length === 0) {
7638
+ return _discarded === void 0 ? event3 : rest;
7639
+ }
7640
+ return { ...rest, contextAttributes: { ...segment.attributes } };
7641
+ });
7642
+ var readBounded = async (file, maxBytes) => {
7643
+ let handle;
7644
+ try {
7645
+ handle = await open2(file, "r");
7646
+ } catch {
7647
+ return void 0;
7648
+ }
7649
+ try {
7650
+ const stats = await handle.stat();
7651
+ if (!stats.isFile() || stats.size > maxBytes) {
7652
+ return void 0;
7653
+ }
7654
+ const buffer = Buffer.alloc(maxBytes + 1);
7655
+ let length = 0;
7656
+ while (length < buffer.length) {
7657
+ const { bytesRead } = await handle.read(buffer, length, buffer.length - length, length);
7658
+ if (bytesRead === 0) {
7659
+ break;
7660
+ }
7661
+ length += bytesRead;
7662
+ }
7663
+ if (length > maxBytes) {
7664
+ return void 0;
7665
+ }
7666
+ return buffer.subarray(0, length).toString("utf8");
7667
+ } catch {
7668
+ return void 0;
7669
+ } finally {
7670
+ await handle.close().catch(() => void 0);
7671
+ }
7672
+ };
7673
+ var createDirectorySessionContextReader = (options) => {
7674
+ const maxBytes = options.maxBytes ?? DEFAULT_SESSION_CONTEXT_MAX_BYTES;
7675
+ const budgetMillis = options.budgetMillis ?? DEFAULT_SESSION_CONTEXT_BUDGET_MILLIS;
7676
+ const readOnce = async (providerId, sessionId) => {
7677
+ const file = sessionContextFilePath(options.dir, providerId, sessionId);
7678
+ if (file === void 0) {
7679
+ return void 0;
7680
+ }
7681
+ const text = await readBounded(file, maxBytes);
7682
+ if (text === void 0) {
7683
+ return void 0;
7684
+ }
7685
+ let decoded;
7686
+ try {
7687
+ decoded = JSON.parse(text);
7688
+ } catch {
7689
+ return void 0;
7690
+ }
7691
+ const agentTool = sessionContextAgentTool(providerId);
7692
+ return parseSessionContextFile(decoded, {
7693
+ ...agentTool === void 0 ? {} : { agentTool },
7694
+ sessionId
7695
+ });
7696
+ };
7697
+ return {
7698
+ read: async (request) => {
7699
+ let timer;
7700
+ const timeout = new Promise((resolve5) => {
7701
+ timer = setTimeout(() => resolve5(void 0), budgetMillis);
7702
+ timer.unref?.();
7703
+ });
7704
+ try {
7705
+ return await Promise.race([
7706
+ readOnce(request.providerId, request.sessionId).catch(() => void 0),
7707
+ timeout
7708
+ ]);
7709
+ } finally {
7710
+ if (timer !== void 0) {
7711
+ clearTimeout(timer);
7712
+ }
7713
+ }
7714
+ }
7715
+ };
7716
+ };
7717
+
7506
7718
  // src/runtime/hook.ts
7507
- var usageScopeSchema = z23.enum(["session", "generation", "subagent"]);
7719
+ var usageScopeSchema = z24.enum(["session", "generation", "subagent"]);
7508
7720
  var classifyDurability = (input) => {
7509
7721
  if (!input.attempted) {
7510
7722
  return "nothing-to-deliver";
@@ -8213,6 +8425,10 @@ var createOtelHook = (deps) => {
8213
8425
  });
8214
8426
  }
8215
8427
  }
8428
+ batch = stampSessionContext(
8429
+ batch,
8430
+ !suppress && batch.length > 0 && deps.sessionContext !== void 0 ? await readSessionContext(deps.sessionContext, detection.providerId, identity.sessionId) : void 0
8431
+ );
8216
8432
  let emitted = 0;
8217
8433
  let exportRejected = 0;
8218
8434
  if (!suppress && batch.length > 0) {
@@ -8328,6 +8544,13 @@ var createOtelHook = (deps) => {
8328
8544
  };
8329
8545
  return { resolveDelivery, ingest, flush, shutdown, config };
8330
8546
  };
8547
+ var readSessionContext = async (reader, providerId, sessionId) => {
8548
+ try {
8549
+ return await reader.read({ providerId, sessionId });
8550
+ } catch {
8551
+ return void 0;
8552
+ }
8553
+ };
8331
8554
  var buildErrorEvents = (diagnostics, identity, sequenceBase, ids, privacy) => {
8332
8555
  const events = [];
8333
8556
  for (const [index, info] of diagnostics.slice(0, MAX_ERROR_EVENTS).entries()) {
@@ -8362,8 +8585,8 @@ var buildErrorEvents = (diagnostics, identity, sequenceBase, ids, privacy) => {
8362
8585
  };
8363
8586
 
8364
8587
  // src/runtime/git-worktree.ts
8365
- import { lstat, open as open2, stat as stat2 } from "fs/promises";
8366
- import * as path3 from "path";
8588
+ import { lstat, open as open3, stat as stat2 } from "fs/promises";
8589
+ import * as path4 from "path";
8367
8590
  var MAX_WORKTREE_WALK_DEPTH = 128;
8368
8591
  var MAX_GIT_FILE_BYTES = 4096;
8369
8592
  var MAX_CACHE_ENTRIES = 1024;
@@ -8371,10 +8594,10 @@ var DEFAULT_WORKTREE_CACHE_TTL_MILLIS = 5e3;
8371
8594
  var MAX_BRANCH_NAME_LENGTH = 255;
8372
8595
  var ABSENT = Object.freeze({ kind: "absent" });
8373
8596
  var INVALID = Object.freeze({ kind: "invalid" });
8374
- var readBounded = async (filePath) => {
8597
+ var readBounded2 = async (filePath) => {
8375
8598
  let handle;
8376
8599
  try {
8377
- handle = await open2(filePath, "r");
8600
+ handle = await open3(filePath, "r");
8378
8601
  const buffer = Buffer.alloc(MAX_GIT_FILE_BYTES);
8379
8602
  const { bytesRead } = await handle.read(buffer, 0, MAX_GIT_FILE_BYTES, 0);
8380
8603
  return buffer.subarray(0, bytesRead).toString("utf8");
@@ -8395,7 +8618,7 @@ var parseHeadBranch = (head) => {
8395
8618
  return branch;
8396
8619
  };
8397
8620
  var firstLine = (content) => content.split(/\r?\n/, 1)[0]?.trim() ?? "";
8398
- var resolveGitPath = (target, base) => target === void 0 || target.length === 0 || target.includes("\0") ? void 0 : path3.resolve(base, target);
8621
+ var resolveGitPath = (target, base) => target === void 0 || target.length === 0 || target.includes("\0") ? void 0 : path4.resolve(base, target);
8399
8622
  var parseGitDirFile = (content, worktreeRoot) => {
8400
8623
  const line = firstLine(content);
8401
8624
  return resolveGitPath(
@@ -8421,17 +8644,17 @@ var isDirectory = async (directory) => {
8421
8644
  }
8422
8645
  };
8423
8646
  var repositoryOf = async (worktreeRoot, gitDir) => {
8424
- const commonDirFile = path3.join(gitDir, "commondir");
8425
- const content = await readBounded(commonDirFile);
8647
+ const commonDirFile = path4.join(gitDir, "commondir");
8648
+ const content = await readBounded2(commonDirFile);
8426
8649
  if (content === void 0) {
8427
8650
  return await isMissing(commonDirFile) ? { kind: "main", mainRoot: worktreeRoot } : { kind: "linked" };
8428
8651
  }
8429
8652
  const commonDir = parseCommonDirFile(content, gitDir);
8430
- const mainRoot = commonDir !== void 0 && path3.basename(commonDir) === ".git" && await isDirectory(commonDir) ? path3.dirname(commonDir) : void 0;
8653
+ const mainRoot = commonDir !== void 0 && path4.basename(commonDir) === ".git" && await isDirectory(commonDir) ? path4.dirname(commonDir) : void 0;
8431
8654
  return { kind: "linked", ...mainRoot === void 0 ? {} : { mainRoot } };
8432
8655
  };
8433
8656
  var probeDirectory = async (directory) => {
8434
- const dotGit = path3.join(directory, ".git");
8657
+ const dotGit = path4.join(directory, ".git");
8435
8658
  let info;
8436
8659
  try {
8437
8660
  info = await stat2(dotGit);
@@ -8442,13 +8665,13 @@ var probeDirectory = async (directory) => {
8442
8665
  if (info.isDirectory()) {
8443
8666
  gitDir = dotGit;
8444
8667
  } else if (info.isFile()) {
8445
- const content = await readBounded(dotGit);
8668
+ const content = await readBounded2(dotGit);
8446
8669
  gitDir = content === void 0 ? void 0 : parseGitDirFile(content, directory);
8447
8670
  }
8448
8671
  if (gitDir === void 0) {
8449
8672
  return INVALID;
8450
8673
  }
8451
- const head = await readBounded(path3.join(gitDir, "HEAD"));
8674
+ const head = await readBounded2(path4.join(gitDir, "HEAD"));
8452
8675
  if (head === void 0) {
8453
8676
  return INVALID;
8454
8677
  }
@@ -8478,10 +8701,10 @@ var createFilesystemWorktreeLocator = (options = {}) => {
8478
8701
  };
8479
8702
  const locate = async (absolutePath) => {
8480
8703
  try {
8481
- if (!path3.isAbsolute(absolutePath) || absolutePath.includes("\0")) {
8704
+ if (!path4.isAbsolute(absolutePath) || absolutePath.includes("\0")) {
8482
8705
  return void 0;
8483
8706
  }
8484
- let directory = path3.resolve(absolutePath);
8707
+ let directory = path4.resolve(absolutePath);
8485
8708
  for (let depth = 0; depth < MAX_WORKTREE_WALK_DEPTH; depth += 1) {
8486
8709
  const probe = await cachedProbe(directory);
8487
8710
  if (probe.kind === "worktree") {
@@ -8490,7 +8713,7 @@ var createFilesystemWorktreeLocator = (options = {}) => {
8490
8713
  if (probe.kind === "invalid") {
8491
8714
  return void 0;
8492
8715
  }
8493
- const parent = path3.dirname(directory);
8716
+ const parent = path4.dirname(directory);
8494
8717
  if (parent === directory) {
8495
8718
  return void 0;
8496
8719
  }
@@ -8721,7 +8944,7 @@ import {
8721
8944
  } from "@opentelemetry/semantic-conventions/incubating";
8722
8945
 
8723
8946
  // src/version.ts
8724
- var VERSION = "0.11.0";
8947
+ var VERSION = "0.12.0";
8725
8948
 
8726
8949
  // src/telemetry/export-identity.ts
8727
8950
  import { ATTR_SESSION_ID } from "@opentelemetry/semantic-conventions/incubating";
@@ -8774,6 +8997,11 @@ var passthroughResourceAttributes = (resource) => {
8774
8997
  }
8775
8998
  return attributes;
8776
8999
  };
9000
+ var contextAttributesOf = (event3) => event3.contextAttributes === void 0 ? {} : { ...event3.contextAttributes };
9001
+ var profileAttributes = (event3, resource) => ({
9002
+ ...passthroughResourceAttributes(resource),
9003
+ ...contextAttributesOf(event3)
9004
+ });
8777
9005
  var resolveExportedSessionId = (eventSessionId, resource) => {
8778
9006
  for (const key of EXTERNAL_SESSION_KEY_ATTRIBUTES) {
8779
9007
  const supplied = resource.attributes[key];
@@ -8794,6 +9022,8 @@ var hexTraceAttributes = (ids) => ({
8794
9022
  var exportIdentityAttributes = (event3, resource, ids) => {
8795
9023
  const { sessionId, providerSessionId } = resolveExportedSessionId(event3.sessionId, resource);
8796
9024
  return {
9025
+ // First, so nothing in the profile layer can replace an identity attribute.
9026
+ ...profileAttributes(event3, resource),
8797
9027
  [ATTR_SESSION_ID]: sessionId,
8798
9028
  [ATTR_OTELHOOK_SESSION_ID]: providerSessionId,
8799
9029
  [ATTR_GEN_AI_CONVERSATION_ID]: providerSessionId,
@@ -8802,7 +9032,6 @@ var exportIdentityAttributes = (event3, resource, ids) => {
8802
9032
  ...event3.provenance.providerVersion === void 0 ? {} : { [ATTR_OTELHOOK_PROVIDER_VERSION]: event3.provenance.providerVersion },
8803
9033
  [ATTR_OTELHOOK_WORKSPACE_ID]: event3.workspace.workspaceId,
8804
9034
  ...event3.subagentId === void 0 ? {} : { [ATTR_OTELHOOK_SUBAGENT_ID]: event3.subagentId },
8805
- ...passthroughResourceAttributes(resource),
8806
9035
  ...hexTraceAttributes(ids)
8807
9036
  };
8808
9037
  };
@@ -8953,12 +9182,12 @@ var pickTarget = (attributes) => {
8953
9182
  }
8954
9183
  return picked;
8955
9184
  };
8956
- var withoutTarget = (attributes, resource) => {
9185
+ var withoutTarget = (attributes, resource, event3) => {
8957
9186
  const rest = { ...attributes };
8958
9187
  for (const key of TARGET_KEYS) {
8959
9188
  delete rest[key];
8960
9189
  }
8961
- return { ...rest, ...pickTarget(passthroughResourceAttributes(resource)) };
9190
+ return { ...rest, ...pickTarget(profileAttributes(event3, resource)) };
8962
9191
  };
8963
9192
  var rankOf = (candidate) => {
8964
9193
  const source = candidate[ATTR_OTELHOOK_TARGET_SOURCE];
@@ -9063,7 +9292,7 @@ var buildLifecycleSpan = (plan, resource, scope) => {
9063
9292
  name = "session";
9064
9293
  kind = SpanKind.INTERNAL;
9065
9294
  attributes = {
9066
- ...withoutTarget(attributes, resource),
9295
+ ...withoutTarget(attributes, resource, anchor),
9067
9296
  ...strongestTarget([pickTarget(resolved.recovered), start === void 0 ? {} : targetAttributes(start)]),
9068
9297
  ...start?.agentName === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_NAME]: start.agentName },
9069
9298
  ...start?.agentVersion === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_VERSION]: start.agentVersion },
@@ -9105,7 +9334,7 @@ var buildLifecycleSpan = (plan, resource, scope) => {
9105
9334
  kind = SpanKind.CLIENT;
9106
9335
  attributes = {
9107
9336
  // Target keys are re-chosen below as one unit, never mixed across edges.
9108
- ...withoutTarget(attributes, resource),
9337
+ ...withoutTarget(attributes, resource, anchor),
9109
9338
  [ATTR_GEN_AI_TOOL_NAME]: toolName,
9110
9339
  [ATTR_GEN_AI_TOOL_CALL_ID]: start?.toolCallId ?? end?.toolCallId ?? group.ref.scopeKey,
9111
9340
  ...start?.toolKind === void 0 ? {} : { [ATTR_OTELHOOK_TOOL_KIND]: start.toolKind },
@@ -9936,6 +10165,9 @@ var ATTR_OTELHOOK_PROVIDER_ID2 = "otelhook.provider.id";
9936
10165
  var ATTR_OTELHOOK_OUTCOME2 = "otelhook.outcome";
9937
10166
  var ATTR_OTELHOOK_SESSION_KIND = "otelhook.session.kind";
9938
10167
  var commonAttributes = (event3, resource, includeSessionId) => ({
10168
+ // Session context first, so the metric's own attributes always win; and never
10169
+ // anything account-shaped, whatever the context says.
10170
+ ...event3.contextAttributes === void 0 ? {} : withoutAccountIdentity(event3.contextAttributes),
9939
10171
  [ATTR_OTELHOOK_PROVIDER_ID2]: event3.provenance.providerId,
9940
10172
  ...includeSessionId ? { [ATTR_SESSION_ID2]: resolveExportedSessionId(event3.sessionId, resource).sessionId } : {}
9941
10173
  });
@@ -10363,8 +10595,8 @@ var createBoundedMemoryStateStore = (options) => {
10363
10595
 
10364
10596
  // src/state/filesystem-store.ts
10365
10597
  import { randomBytes as randomBytes2 } from "crypto";
10366
- import { mkdir, open as open3, readFile, readdir, rename, unlink, writeFile } from "fs/promises";
10367
- import * as path4 from "path";
10598
+ import { mkdir, open as open4, readFile, readdir, rename, unlink, writeFile } from "fs/promises";
10599
+ import * as path5 from "path";
10368
10600
 
10369
10601
  // src/state/keys.ts
10370
10602
  import { createHash as createHash6 } from "crypto";
@@ -10396,10 +10628,10 @@ var wrapFsError = (thrown, operation) => {
10396
10628
  };
10397
10629
  var createFilesystemStateStore = (options) => {
10398
10630
  const [providerSegment, installationSegment] = namespaceSegments(options);
10399
- const baseDir = path4.join(options.rootDir, providerSegment, installationSegment);
10400
- const recordsDir = path4.join(baseDir, "records");
10401
- const quarantineDir = path4.join(baseDir, "quarantine");
10402
- const locksDir = path4.join(baseDir, "locks");
10631
+ const baseDir = path5.join(options.rootDir, providerSegment, installationSegment);
10632
+ const recordsDir = path5.join(baseDir, "records");
10633
+ const quarantineDir = path5.join(baseDir, "quarantine");
10634
+ const locksDir = path5.join(baseDir, "locks");
10403
10635
  const lockTimeoutMillis = options.lockTimeoutMillis ?? 5e3;
10404
10636
  const lockStaleMillis = options.lockStaleMillis ?? 3e4;
10405
10637
  const lockPollIntervalMillis = options.lockPollIntervalMillis ?? 25;
@@ -10423,11 +10655,11 @@ var createFilesystemStateStore = (options) => {
10423
10655
  throw wrapFsError(thrown, "ensure-dirs");
10424
10656
  }
10425
10657
  };
10426
- const recordPath = (key) => path4.join(recordsDir, `${keyDigest(key)}.json`);
10427
- const tempPath = (key) => path4.join(recordsDir, `.tmp-${keyDigest(key)}-${randomBytes2(6).toString("hex")}.json`);
10428
- const lockPath = (sessionId) => path4.join(locksDir, `${sanitizeSegment(sessionId)}.lock`);
10658
+ const recordPath = (key) => path5.join(recordsDir, `${keyDigest(key)}.json`);
10659
+ const tempPath = (key) => path5.join(recordsDir, `.tmp-${keyDigest(key)}-${randomBytes2(6).toString("hex")}.json`);
10660
+ const lockPath = (sessionId) => path5.join(locksDir, `${sanitizeSegment(sessionId)}.lock`);
10429
10661
  const quarantine = async (filePath, key, reason) => {
10430
- const dest = path4.join(quarantineDir, `${options.clock.now()}-${keyDigest(key)}-${reason}.json`);
10662
+ const dest = path5.join(quarantineDir, `${options.clock.now()}-${keyDigest(key)}-${reason}.json`);
10431
10663
  try {
10432
10664
  await rename(filePath, dest);
10433
10665
  } catch {
@@ -10491,7 +10723,7 @@ var createFilesystemStateStore = (options) => {
10491
10723
  const startedAt = options.clock.monotonicMillis();
10492
10724
  for (; ; ) {
10493
10725
  try {
10494
- const handle = await open3(filePath, "wx");
10726
+ const handle = await open4(filePath, "wx");
10495
10727
  try {
10496
10728
  await handle.writeFile(JSON.stringify({ pid: process.pid, acquiredAt: options.clock.now() }));
10497
10729
  } finally {
@@ -10559,7 +10791,7 @@ var createFilesystemStateStore = (options) => {
10559
10791
  }
10560
10792
  let raw;
10561
10793
  try {
10562
- raw = await readFile(path4.join(recordsDir, entry), "utf8");
10794
+ raw = await readFile(path5.join(recordsDir, entry), "utf8");
10563
10795
  } catch {
10564
10796
  continue;
10565
10797
  }
@@ -10612,7 +10844,7 @@ var createFilesystemStateStore = (options) => {
10612
10844
  continue;
10613
10845
  }
10614
10846
  scanned += 1;
10615
- const filePath = path4.join(recordsDir, entry);
10847
+ const filePath = path5.join(recordsDir, entry);
10616
10848
  try {
10617
10849
  const raw = await readFile(filePath, "utf8");
10618
10850
  const envelope = JSON.parse(raw);
@@ -10632,7 +10864,7 @@ var createFilesystemStateStore = (options) => {
10632
10864
  lockEntries = [];
10633
10865
  }
10634
10866
  for (const entry of lockEntries) {
10635
- const filePath = path4.join(locksDir, entry);
10867
+ const filePath = path5.join(locksDir, entry);
10636
10868
  try {
10637
10869
  const raw = await readFile(filePath, "utf8");
10638
10870
  const parsed = JSON.parse(raw);
@@ -10651,7 +10883,7 @@ var createFilesystemStateStore = (options) => {
10651
10883
  // src/telemetry/spool-queue.ts
10652
10884
  import { randomBytes as randomBytes3 } from "crypto";
10653
10885
  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";
10654
- import * as path5 from "path";
10886
+ import * as path6 from "path";
10655
10887
  var EMPTY_SPOOL_DROP_COUNTS = Object.freeze({
10656
10888
  total: 0,
10657
10889
  age: 0,
@@ -10667,7 +10899,7 @@ var enqueuedAtOf = (fileName) => {
10667
10899
  var isCount = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0;
10668
10900
  var readSpoolDropCounts = async (queueDir) => {
10669
10901
  try {
10670
- const parsed = JSON.parse(await readFile2(path5.join(queueDir, SPOOL_DROPS_FILE), "utf8"));
10902
+ const parsed = JSON.parse(await readFile2(path6.join(queueDir, SPOOL_DROPS_FILE), "utf8"));
10671
10903
  if (typeof parsed !== "object" || parsed === null) {
10672
10904
  return EMPTY_SPOOL_DROP_COUNTS;
10673
10905
  }
@@ -10696,7 +10928,7 @@ var readSpoolQueueStats = async (queueDir) => {
10696
10928
  let bytes = 0;
10697
10929
  for (const file of files) {
10698
10930
  try {
10699
- bytes += (await stat3(path5.join(queueDir, file))).size;
10931
+ bytes += (await stat3(path6.join(queueDir, file))).size;
10700
10932
  } catch {
10701
10933
  }
10702
10934
  }
@@ -10712,8 +10944,8 @@ var DEFAULT_DRAIN_MAX_BATCHES = 20;
10712
10944
  var isErrnoException2 = (thrown, code) => thrown instanceof Error && thrown.code === code;
10713
10945
  var createSpoolQueue = (options) => {
10714
10946
  const [providerSegment, installationSegment] = namespaceSegments(options);
10715
- const queueDir = path5.join(options.rootDir, providerSegment, installationSegment, options.queueName);
10716
- const corruptDir = path5.join(
10947
+ const queueDir = path6.join(options.rootDir, providerSegment, installationSegment, options.queueName);
10948
+ const corruptDir = path6.join(
10717
10949
  options.rootDir,
10718
10950
  providerSegment,
10719
10951
  installationSegment,
@@ -10760,9 +10992,9 @@ var createSpoolQueue = (options) => {
10760
10992
  [reason]: current[reason] + dropped,
10761
10993
  lastDroppedAt: options.clock.now()
10762
10994
  };
10763
- const tmp = path5.join(queueDir, `.tmp-${randomBytes3(6).toString("hex")}.drops`);
10995
+ const tmp = path6.join(queueDir, `.tmp-${randomBytes3(6).toString("hex")}.drops`);
10764
10996
  await writeFile2(tmp, JSON.stringify(next), "utf8");
10765
- await rename2(tmp, path5.join(queueDir, SPOOL_DROPS_FILE));
10997
+ await rename2(tmp, path6.join(queueDir, SPOOL_DROPS_FILE));
10766
10998
  } catch {
10767
10999
  }
10768
11000
  options.logger?.warn("durable spool dropped batches", {
@@ -10778,7 +11010,7 @@ var createSpoolQueue = (options) => {
10778
11010
  let bytes = 0;
10779
11011
  if (options.maxBytes !== void 0) {
10780
11012
  try {
10781
- bytes = (await stat3(path5.join(queueDir, name))).size;
11013
+ bytes = (await stat3(path6.join(queueDir, name))).size;
10782
11014
  } catch {
10783
11015
  continue;
10784
11016
  }
@@ -10792,7 +11024,7 @@ var createSpoolQueue = (options) => {
10792
11024
  let removed = 0;
10793
11025
  for (const file of files) {
10794
11026
  try {
10795
- await unlink2(path5.join(queueDir, file.name));
11027
+ await unlink2(path6.join(queueDir, file.name));
10796
11028
  removed += 1;
10797
11029
  } catch {
10798
11030
  }
@@ -10852,8 +11084,8 @@ var createSpoolQueue = (options) => {
10852
11084
  }
10853
11085
  }
10854
11086
  const fileName = `${String(now).padStart(16, "0")}-${randomBytes3(6).toString("hex")}.json`;
10855
- const target = path5.join(queueDir, fileName);
10856
- const tmp = path5.join(queueDir, `.tmp-${randomBytes3(6).toString("hex")}.json`);
11087
+ const target = path6.join(queueDir, fileName);
11088
+ const tmp = path6.join(queueDir, `.tmp-${randomBytes3(6).toString("hex")}.json`);
10857
11089
  await writeFile2(tmp, serialized, "utf8");
10858
11090
  await rename2(tmp, target);
10859
11091
  return { spooled: true };
@@ -10883,7 +11115,7 @@ var createSpoolQueue = (options) => {
10883
11115
  if (fileName === void 0) {
10884
11116
  break;
10885
11117
  }
10886
- const filePath = path5.join(queueDir, fileName);
11118
+ const filePath = path6.join(queueDir, fileName);
10887
11119
  const quarantine = async (rejection) => {
10888
11120
  quarantined += 1;
10889
11121
  options.logger?.error("durable spool quarantined an unusable batch", {
@@ -10892,7 +11124,7 @@ var createSpoolQueue = (options) => {
10892
11124
  "spool.queue": options.queueName
10893
11125
  });
10894
11126
  try {
10895
- await rename2(filePath, path5.join(corruptDir, fileName));
11127
+ await rename2(filePath, path6.join(corruptDir, fileName));
10896
11128
  } catch {
10897
11129
  await unlink2(filePath).catch(() => void 0);
10898
11130
  }
@@ -11129,6 +11361,33 @@ var replayResource = (attributes, policy) => {
11129
11361
  }
11130
11362
  return resourceFromAttributes(safe);
11131
11363
  };
11364
+ var agreedContextAttributes = (events) => {
11365
+ const [first, ...rest] = events;
11366
+ if (first?.contextAttributes === void 0) {
11367
+ return {};
11368
+ }
11369
+ const agreed = { ...first.contextAttributes };
11370
+ for (const event3 of rest) {
11371
+ for (const key of Object.keys(agreed)) {
11372
+ if (event3.contextAttributes?.[key] !== agreed[key]) {
11373
+ delete agreed[key];
11374
+ }
11375
+ }
11376
+ }
11377
+ return agreed;
11378
+ };
11379
+ var resourceWithContext = (resource, context) => {
11380
+ const overrides = {};
11381
+ for (const [key, value] of Object.entries(context)) {
11382
+ if (Object.hasOwn(resource.attributes, key) && !isReservedResourceAttributeKey(key) && resource.attributes[key] !== value) {
11383
+ overrides[key] = value;
11384
+ }
11385
+ }
11386
+ if (Object.keys(overrides).length === 0) {
11387
+ return resource;
11388
+ }
11389
+ return resourceFromAttributes({ ...resource.attributes, ...overrides });
11390
+ };
11132
11391
 
11133
11392
  // src/telemetry/otlp-sink.ts
11134
11393
  var chunk = (items, size) => {
@@ -11213,10 +11472,10 @@ var createOtlpTraceSink = (options) => {
11213
11472
  const exportSpans = (spans) => new Promise((resolve5) => {
11214
11473
  exporter.export([...spans], (result) => resolve5(result));
11215
11474
  });
11216
- const toSpoolBatch = (spans) => ({
11475
+ const toSpoolBatch = (spans, batchResource) => ({
11217
11476
  providerId: options.providerId,
11218
11477
  installationId: options.installationId,
11219
- resourceAttributes: { ...resource.attributes },
11478
+ resourceAttributes: { ...batchResource.attributes },
11220
11479
  instrumentationScope: { name: scope.name, ...scope.version === void 0 ? {} : { version: scope.version } },
11221
11480
  spans: spans.map(serializeSpan),
11222
11481
  enqueuedAt: options.clock.now()
@@ -11246,8 +11505,9 @@ var createOtlpTraceSink = (options) => {
11246
11505
  return { accepted: 0, rejected: 0, errors: [] };
11247
11506
  }
11248
11507
  const resolved = await resolveCorrelations(events);
11508
+ const batchResource = resourceWithContext(resource, agreedContextAttributes(events));
11249
11509
  const spans = canonicalEventsToReadableSpans(events, {
11250
- resource,
11510
+ resource: batchResource,
11251
11511
  instrumentationScope: scope,
11252
11512
  correlations: resolved.correlations,
11253
11513
  ...resolved.available === void 0 ? {} : { correlationAvailable: resolved.available }
@@ -11273,7 +11533,7 @@ var createOtlpTraceSink = (options) => {
11273
11533
  health.recordFailure("telemetry-export-failure", batch.length, options.clock.now());
11274
11534
  const permanent = isPermanentExportFailure(result);
11275
11535
  if (options.spool !== void 0 && !permanent) {
11276
- const spoolResult = await options.spool.enqueue(toSpoolBatch(batch)).catch(() => ({
11536
+ const spoolResult = await options.spool.enqueue(toSpoolBatch(batch, batchResource)).catch(() => ({
11277
11537
  spooled: false,
11278
11538
  reason: "capacity-exceeded"
11279
11539
  }));
@@ -12008,10 +12268,10 @@ var createOtlpLogSink = (options) => {
12008
12268
  const exportRecords = (records) => new Promise((resolve5) => {
12009
12269
  exporter.export([...records], (result) => resolve5(result));
12010
12270
  });
12011
- const toSpoolBatch = (records) => ({
12271
+ const toSpoolBatch = (records, batchResource) => ({
12012
12272
  providerId: options.providerId,
12013
12273
  installationId: options.installationId,
12014
- resourceAttributes: { ...resource.attributes },
12274
+ resourceAttributes: { ...batchResource.attributes },
12015
12275
  instrumentationScope: {
12016
12276
  name: scope.name,
12017
12277
  ...scope.version === void 0 ? {} : { version: scope.version }
@@ -12046,8 +12306,9 @@ var createOtlpLogSink = (options) => {
12046
12306
  return { accepted: 0, rejected: 0, errors: [] };
12047
12307
  }
12048
12308
  const resolved = await resolveCorrelations(events);
12309
+ const batchResource = resourceWithContext(resource, agreedContextAttributes(events));
12049
12310
  const mapped = canonicalEventsToLogRecords(events, {
12050
- resource,
12311
+ resource: batchResource,
12051
12312
  instrumentationScope: scope,
12052
12313
  content,
12053
12314
  correlations: resolved.correlations,
@@ -12082,7 +12343,7 @@ var createOtlpLogSink = (options) => {
12082
12343
  health.recordFailure("telemetry-export-failure", batch.length, options.clock.now());
12083
12344
  const permanent = isPermanentExportFailure(result);
12084
12345
  if (options.spool !== void 0 && !permanent) {
12085
- const spoolResult = await options.spool.enqueue(toSpoolBatch(batch)).catch(() => ({
12346
+ const spoolResult = await options.spool.enqueue(toSpoolBatch(batch, batchResource)).catch(() => ({
12086
12347
  spooled: false,
12087
12348
  reason: "capacity-exceeded"
12088
12349
  }));
@@ -12434,10 +12695,10 @@ var createOtlpMetricSink = (options) => {
12434
12695
  });
12435
12696
  }
12436
12697
  });
12437
- const toSpoolBatch = (points) => ({
12698
+ const toSpoolBatch = (points, batchResource) => ({
12438
12699
  providerId: options.providerId,
12439
12700
  installationId: options.installationId,
12440
- resourceAttributes: { ...resource.attributes },
12701
+ resourceAttributes: { ...batchResource.attributes },
12441
12702
  instrumentationScope: {
12442
12703
  name: scope.name,
12443
12704
  ...scope.version === void 0 ? {} : { version: scope.version }
@@ -12455,11 +12716,12 @@ var createOtlpMetricSink = (options) => {
12455
12716
  }
12456
12717
  return isPermanentExportFailure(result) ? "discard" : false;
12457
12718
  };
12458
- const exportPoints = async (points) => {
12719
+ const exportPoints = async (points, context) => {
12459
12720
  if (points.length === 0) {
12460
12721
  return { accepted: 0, rejected: 0, errors: [] };
12461
12722
  }
12462
- const result = await exportResourceMetrics(points, resource, scope);
12723
+ const batchResource = context === void 0 ? resource : resourceWithContext(resource, context);
12724
+ const result = await exportResourceMetrics(points, batchResource, scope);
12463
12725
  if (result.code === ExportResultCode3.SUCCESS) {
12464
12726
  health.recordSuccess(points.length, options.clock.now());
12465
12727
  return { accepted: points.length, rejected: 0, errors: [] };
@@ -12467,7 +12729,7 @@ var createOtlpMetricSink = (options) => {
12467
12729
  health.recordFailure("telemetry-export-failure", points.length, options.clock.now());
12468
12730
  const permanent = isPermanentExportFailure(result);
12469
12731
  if (options.spool !== void 0 && !permanent) {
12470
- const spooled = await options.spool.enqueue(toSpoolBatch(points)).catch(() => ({
12732
+ const spooled = await options.spool.enqueue(toSpoolBatch(points, batchResource)).catch(() => ({
12471
12733
  spooled: false,
12472
12734
  reason: "capacity-exceeded"
12473
12735
  }));
@@ -12841,6 +13103,16 @@ var createHookRuntime = (options) => {
12841
13103
  logger,
12842
13104
  installationId: options.installationId,
12843
13105
  payloadEnrichers: options.payloadEnrichers ?? (readsClaudeTranscriptUsage(options.config) ? [createClaudeTranscriptUsageEnricher()] : []),
13106
+ ...(() => {
13107
+ if (options.sessionContextReader === null) {
13108
+ return {};
13109
+ }
13110
+ if (options.sessionContextReader !== void 0) {
13111
+ return { sessionContext: options.sessionContextReader };
13112
+ }
13113
+ const dir = sessionContextDir(options.config);
13114
+ return dir === void 0 ? {} : { sessionContext: createDirectorySessionContextReader({ dir }) };
13115
+ })(),
12844
13116
  ...options.worktreeLocator === null ? {} : {
12845
13117
  worktreeLocator: options.worktreeLocator ?? createFilesystemWorktreeLocator({ monotonicMillis: () => clock.monotonicMillis() })
12846
13118
  }
@@ -12934,9 +13206,10 @@ var createHookRuntime = (options) => {
12934
13206
  perSession: metricsPolicy.includeSessionId,
12935
13207
  ...deliveryToken === void 0 ? {} : { deliveryToken }
12936
13208
  });
13209
+ const context = agreedContextAttributes(ingest.events);
12937
13210
  const results = await Promise.all(
12938
13211
  metricDestinations.map(async (destination) => {
12939
- const result = await destination.metrics.exportPoints(points).catch(
13212
+ const result = await destination.metrics.exportPoints(points, context).catch(
12940
13213
  (thrown) => ({
12941
13214
  accepted: 0,
12942
13215
  rejected: points.length,
@@ -14076,7 +14349,7 @@ var SUPPORTED_REGISTRATION_PROVIDER_IDS = Object.freeze(
14076
14349
  );
14077
14350
 
14078
14351
  // src/install/scopes.ts
14079
- import * as path6 from "path";
14352
+ import * as path7 from "path";
14080
14353
  var REGISTRATION_SCOPES = Object.freeze([
14081
14354
  "global",
14082
14355
  "project"
@@ -14144,15 +14417,15 @@ var PROVIDERS_WITH_VERIFIED_LOCATION = Object.freeze([
14144
14417
  var findInstallLocation = (providerId, scope) => PROVIDER_INSTALL_LOCATIONS.find(
14145
14418
  (entry) => entry.providerId === providerId && entry.scope === scope
14146
14419
  );
14147
- var resolveInstallPath = (location, roots) => path6.resolve(
14420
+ var resolveInstallPath = (location, roots) => path7.resolve(
14148
14421
  location.scope === "global" ? roots.homeDir : roots.projectDir,
14149
14422
  ...location.segments
14150
14423
  );
14151
14424
 
14152
14425
  // src/install/document.ts
14153
14426
  import { randomBytes as randomBytes4 } from "crypto";
14154
- import { chmod, mkdir as mkdir3, open as open4, readFile as readFile3, rename as rename3, stat as stat4, unlink as unlink3 } from "fs/promises";
14155
- import * as path7 from "path";
14427
+ import { chmod, mkdir as mkdir3, open as open5, readFile as readFile3, rename as rename3, stat as stat4, unlink as unlink3 } from "fs/promises";
14428
+ import * as path8 from "path";
14156
14429
  var DEFAULT_DOCUMENT_FORMAT = Object.freeze({
14157
14430
  indent: " ",
14158
14431
  eol: "\n",
@@ -14223,11 +14496,11 @@ var renameWithRetry = async (from, to) => {
14223
14496
  var NEW_DOCUMENT_MODE = 384;
14224
14497
  var TEMPORARY_DOCUMENT_MODE = 384;
14225
14498
  var writeDocumentAtomically = async (filePath, contents) => {
14226
- const directory = path7.dirname(filePath);
14499
+ const directory = path8.dirname(filePath);
14227
14500
  await mkdir3(directory, { recursive: true });
14228
- const temporary = path7.join(
14501
+ const temporary = path8.join(
14229
14502
  directory,
14230
- `.${path7.basename(filePath)}.${randomBytes4(6).toString("hex")}.tmp`
14503
+ `.${path8.basename(filePath)}.${randomBytes4(6).toString("hex")}.tmp`
14231
14504
  );
14232
14505
  let existingMode;
14233
14506
  try {
@@ -14239,7 +14512,7 @@ var writeDocumentAtomically = async (filePath, contents) => {
14239
14512
  }
14240
14513
  const targetMode = existingMode ?? NEW_DOCUMENT_MODE;
14241
14514
  try {
14242
- const handle = await open4(temporary, "wx", TEMPORARY_DOCUMENT_MODE);
14515
+ const handle = await open5(temporary, "wx", TEMPORARY_DOCUMENT_MODE);
14243
14516
  try {
14244
14517
  await handle.writeFile(contents, "utf8");
14245
14518
  await handle.sync();
@@ -14256,12 +14529,12 @@ var writeDocumentAtomically = async (filePath, contents) => {
14256
14529
 
14257
14530
  // src/install/file-lock.ts
14258
14531
  import { randomBytes as randomBytes5 } from "crypto";
14259
- import { mkdir as mkdir4, open as open5, readFile as readFile4, rename as rename4, stat as stat5, unlink as unlink4 } from "fs/promises";
14260
- import * as path8 from "path";
14532
+ import { mkdir as mkdir4, open as open6, readFile as readFile4, rename as rename4, stat as stat5, unlink as unlink4 } from "fs/promises";
14533
+ import * as path9 from "path";
14261
14534
  var FileLockTimeoutError = class extends Error {
14262
14535
  constructor(lockPath, timeoutMillis) {
14263
14536
  super(
14264
- `timed out after ${String(timeoutMillis)}ms waiting for the lock on ${path8.basename(lockPath)}`
14537
+ `timed out after ${String(timeoutMillis)}ms waiting for the lock on ${path9.basename(lockPath)}`
14265
14538
  );
14266
14539
  this.name = "FileLockTimeoutError";
14267
14540
  }
@@ -14333,12 +14606,12 @@ var withFileLock = async (filePath, options, fn) => {
14333
14606
  const pollIntervalMillis = options.pollIntervalMillis ?? 25;
14334
14607
  const lockPath = lockPathFor(filePath);
14335
14608
  const startedAt = options.clock.monotonicMillis();
14336
- await mkdir4(path8.dirname(filePath), { recursive: true });
14609
+ await mkdir4(path9.dirname(filePath), { recursive: true });
14337
14610
  for (; ; ) {
14338
14611
  const token = randomBytes5(16).toString("hex");
14339
14612
  let acquired = false;
14340
14613
  try {
14341
- const handle = await open5(lockPath, "wx", 384);
14614
+ const handle = await open6(lockPath, "wx", 384);
14342
14615
  try {
14343
14616
  const contents = {
14344
14617
  token,
@@ -14381,7 +14654,7 @@ var withFileLock = async (filePath, options, fn) => {
14381
14654
 
14382
14655
  // src/install/lifecycle.ts
14383
14656
  import { readFile as readFile5 } from "fs/promises";
14384
- import * as path9 from "path";
14657
+ import * as path10 from "path";
14385
14658
  var defaultHookCommand = (providerId) => `otel-hook run --provider ${providerId}`;
14386
14659
  var unsupportedOutcome = (providerId, scope, reason) => ({
14387
14660
  providerId,
@@ -14398,7 +14671,7 @@ var unsupportedOutcome = (providerId, scope, reason) => ({
14398
14671
  var resolveTarget = (providerId, scope, request) => {
14399
14672
  if (request.configFile !== void 0) {
14400
14673
  return {
14401
- configPath: path9.resolve(request.configFile),
14674
+ configPath: path10.resolve(request.configFile),
14402
14675
  evidence: "path supplied by the caller with --settings-file"
14403
14676
  };
14404
14677
  }
@@ -14415,14 +14688,14 @@ var resolveTarget = (providerId, scope, request) => {
14415
14688
  };
14416
14689
  };
14417
14690
  var codexFeatureNote = async (configPath) => {
14418
- const tomlPath = path9.join(path9.dirname(configPath), "config.toml");
14691
+ const tomlPath = path10.join(path10.dirname(configPath), "config.toml");
14419
14692
  let raw;
14420
14693
  try {
14421
14694
  raw = await readFile5(tomlPath, "utf8");
14422
14695
  } catch {
14423
14696
  return void 0;
14424
14697
  }
14425
- return readCodexHooksFeatureFlag(raw) === "disabled" ? `${path9.basename(tomlPath)} sets [features] hooks = false; registered hooks will not fire until that is removed` : void 0;
14698
+ return readCodexHooksFeatureFlag(raw) === "disabled" ? `${path10.basename(tomlPath)} sets [features] hooks = false; registered hooks will not fire until that is removed` : void 0;
14426
14699
  };
14427
14700
  var readState = async (configPath) => {
14428
14701
  const read = await readJsonDocument(configPath);
@@ -14434,12 +14707,12 @@ var readState = async (configPath) => {
14434
14707
  case "unparseable":
14435
14708
  return {
14436
14709
  status: "blocked",
14437
- problem: `${path9.basename(configPath)} is not well-formed JSON (${read.detail}); it was left untouched`
14710
+ problem: `${path10.basename(configPath)} is not well-formed JSON (${read.detail}); it was left untouched`
14438
14711
  };
14439
14712
  case "unreadable":
14440
14713
  return {
14441
14714
  status: "failed",
14442
- problem: `${path9.basename(configPath)} could not be read (${read.detail})`
14715
+ problem: `${path10.basename(configPath)} could not be read (${read.detail})`
14443
14716
  };
14444
14717
  }
14445
14718
  };
@@ -14551,7 +14824,7 @@ var runOneTarget = async (providerId, scope, request, command) => {
14551
14824
  missingEvents: [],
14552
14825
  notes,
14553
14826
  problems: planned.conflicts.map(
14554
- (conflict) => `${path9.basename(configPath)} has an unexpected shape at ${conflict.location}: ${conflict.detail}; it was left untouched`
14827
+ (conflict) => `${path10.basename(configPath)} has an unexpected shape at ${conflict.location}: ${conflict.detail}; it was left untouched`
14555
14828
  )
14556
14829
  };
14557
14830
  }
@@ -14562,7 +14835,7 @@ var runOneTarget = async (providerId, scope, request, command) => {
14562
14835
  changed: false,
14563
14836
  registeredEvents: [],
14564
14837
  missingEvents: [],
14565
- notes: [...notes, `${path9.basename(configPath)} does not exist; nothing to remove`],
14838
+ notes: [...notes, `${path10.basename(configPath)} does not exist; nothing to remove`],
14566
14839
  problems: []
14567
14840
  };
14568
14841
  }
@@ -14605,7 +14878,7 @@ var runOneTarget = async (providerId, scope, request, command) => {
14605
14878
  missingEvents: [],
14606
14879
  notes,
14607
14880
  problems: [
14608
- `could not write ${path9.basename(configPath)} (${thrown instanceof Error ? thrown.name : typeof thrown})`
14881
+ `could not write ${path10.basename(configPath)} (${thrown instanceof Error ? thrown.name : typeof thrown})`
14609
14882
  ]
14610
14883
  };
14611
14884
  }
@@ -14632,7 +14905,7 @@ var runOneTarget = async (providerId, scope, request, command) => {
14632
14905
  missingEvents: [],
14633
14906
  notes,
14634
14907
  problems: [
14635
- thrown instanceof Error ? `${path9.basename(configPath)}: ${thrown.message}` : `${path9.basename(configPath)}: the configuration file could not be locked`
14908
+ thrown instanceof Error ? `${path10.basename(configPath)}: ${thrown.message}` : `${path10.basename(configPath)}: the configuration file could not be locked`
14636
14909
  ]
14637
14910
  };
14638
14911
  }
@@ -14768,6 +15041,8 @@ export {
14768
15041
  DEFAULT_PROVIDERS_POLICY,
14769
15042
  DEFAULT_SECRET_KEY_PATTERNS,
14770
15043
  DEFAULT_SECRET_VALUE_PATTERNS,
15044
+ DEFAULT_SESSION_CONTEXT_BUDGET_MILLIS,
15045
+ DEFAULT_SESSION_CONTEXT_MAX_BYTES,
14771
15046
  DEFAULT_SPOOL_POLICY,
14772
15047
  DEFAULT_TARGET_RESOLUTION_BUDGET_MILLIS,
14773
15048
  DEFAULT_WORKTREE_CACHE_TTL_MILLIS,
@@ -14810,6 +15085,7 @@ export {
14810
15085
  MAX_RESOURCE_ATTRIBUTES,
14811
15086
  MAX_RESOURCE_ATTRIBUTE_KEY_LENGTH,
14812
15087
  MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH,
15088
+ MAX_SESSION_CONTEXT_SEGMENTS,
14813
15089
  MAX_TARGET_HINT_PATHS,
14814
15090
  MAX_TARGET_PATH_LENGTH,
14815
15091
  MAX_WORKTREE_WALK_DEPTH,
@@ -14837,6 +15113,8 @@ export {
14837
15113
  RESERVED_RESOURCE_ATTRIBUTE_KEYS,
14838
15114
  RESOURCE_ATTRIBUTE_KEY_PATTERN,
14839
15115
  RESOURCE_ATTRIBUTE_KEY_REJECTION_DETAIL,
15116
+ SESSION_CONTEXT_AGENT_TOOLS,
15117
+ SESSION_CONTEXT_FILE_VERSION,
14840
15118
  SILENT_HOOK_RESPONSE,
14841
15119
  SPAN_RECORD_VERSION,
14842
15120
  SUBAGENT_ID_PATTERN,
@@ -14893,6 +15171,7 @@ export {
14893
15171
  createDefaultProviderRegistry,
14894
15172
  createDestinationFanout,
14895
15173
  createDeterministicIdGenerator,
15174
+ createDirectorySessionContextReader,
14896
15175
  createErrorInfo,
14897
15176
  createEventFactory,
14898
15177
  createExportDestinationSinks,
@@ -14985,7 +15264,9 @@ export {
14985
15264
  isPermanentExportFailure,
14986
15265
  isReservedExtensionNamespace,
14987
15266
  isReservedResourceAttributeKey,
15267
+ isReservedSessionContextKey,
14988
15268
  isSecretResourceAttributeKey,
15269
+ isSessionContextFileName,
14989
15270
  isTargetedEvent,
14990
15271
  isUnavailableContentFact,
14991
15272
  isUnknownProvider,
@@ -15023,6 +15304,7 @@ export {
15023
15304
  parseHeaderValueReference,
15024
15305
  parseOtlpHeadersValue,
15025
15306
  parseResourceAttributesValue,
15307
+ parseSessionContextFile,
15026
15308
  planProviderRegistration,
15027
15309
  privacyLimitsSchema,
15028
15310
  privacyPolicySchema,
@@ -15071,7 +15353,13 @@ export {
15071
15353
  resourceAttributesSchema,
15072
15354
  runRegistrationLifecycle,
15073
15355
  sanitizeResourceAttributes,
15356
+ sanitizeSessionContextAttributes,
15357
+ segmentInForce,
15074
15358
  sequenceNumberSchema,
15359
+ sessionContextAgentTool,
15360
+ sessionContextDir,
15361
+ sessionContextFilePath,
15362
+ sessionContextPolicySchema,
15075
15363
  sessionCwdHint,
15076
15364
  sessionEndEventSchema,
15077
15365
  sessionIdSchema,
@@ -15082,6 +15370,7 @@ export {
15082
15370
  spanScopeRefOf,
15083
15371
  spoolPolicySchema,
15084
15372
  spoolQueueNamesFor,
15373
+ stampSessionContext,
15085
15374
  startOnlySpanAttributes,
15086
15375
  stateRecordSchema,
15087
15376
  stateValueSchema,