@osfactory/otel-hook 0.11.0 → 0.13.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 +32 -5
  2. package/dist/{adapter-DiLknaTF.d.ts → adapter-DyCb7y1N.d.ts} +2 -2
  3. package/dist/cli.js +507 -108
  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-Bey2djRk.d.ts} +11 -6
  11. package/dist/{filesystem-store-D3SCNmbX.d.ts → filesystem-store-B3CpiIRl.d.ts} +1 -1
  12. package/dist/{hook-BOecWGSz.d.ts → hook-D5imE0Qc.d.ts} +11 -5
  13. package/dist/index.d.ts +14 -14
  14. package/dist/index.js +525 -143
  15. package/dist/index.js.map +1 -1
  16. package/dist/install.d.ts +4 -4
  17. package/dist/install.js +19 -2
  18. package/dist/install.js.map +1 -1
  19. package/dist/integration.d.ts +16 -10
  20. package/dist/integration.js +447 -111
  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-B3r6sZtC.d.ts} +2 -2
  26. package/dist/{metric-model-DDnWxL9d.d.ts → metric-model-CFIeUwqd.d.ts} +6 -2
  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-CdDKeRpH.d.ts} +1 -1
  31. package/dist/{ports-CeqLq31i.d.ts → ports-DhpSDIkp.d.ts} +41 -3
  32. package/dist/providers.d.ts +30 -14
  33. package/dist/providers.js +131 -42
  34. package/dist/providers.js.map +1 -1
  35. package/dist/{registry-CcJNF3WY.d.ts → registry-BKQhhIO3.d.ts} +2 -2
  36. package/dist/runtime.d.ts +97 -9
  37. package/dist/runtime.js +269 -26
  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 +80 -22
  45. package/dist/telemetry.js.map +1 -1
  46. package/dist/testing.d.ts +10 -8
  47. package/dist/testing.js +161 -30
  48. package/dist/testing.js.map +1 -1
  49. package/package.json +1 -1
@@ -1,4 +1,5 @@
1
1
  // src/config/schema.ts
2
+ import { isAbsolute } from "path";
2
3
  import { z as z5 } from "zod";
3
4
 
4
5
  // src/model/primitives.ts
@@ -495,13 +496,19 @@ var providersPolicySchema = z5.strictObject({
495
496
  readTranscriptUsage: z5.boolean()
496
497
  }).optional()
497
498
  });
499
+ var sessionContextPolicySchema = z5.strictObject({
500
+ /** Absolute path of the context directory. */
501
+ dir: z5.string().min(1).max(4096).refine((value) => isAbsolute(value), { message: "must be an absolute path" })
502
+ });
498
503
  var otelHookConfigSchema = z5.strictObject({
499
504
  exporter: exporterPolicySchema,
500
505
  privacy: privacyPolicySchema,
501
506
  detection: detectionPolicySchema,
502
507
  diagnostics: diagnosticsPolicySchema,
503
508
  /** Optional so a hand-built configuration from before it existed stays valid. */
504
- providers: providersPolicySchema.optional()
509
+ providers: providersPolicySchema.optional(),
510
+ /** Optional: absent means no session context is read. */
511
+ sessionContext: sessionContextPolicySchema.optional()
505
512
  });
506
513
  var otelHookConfigPatchSchema = z5.strictObject({
507
514
  // `logs` is unwrapped and re-partialled for the same reason `privacy.limits` is:
@@ -517,7 +524,8 @@ var otelHookConfigPatchSchema = z5.strictObject({
517
524
  diagnostics: diagnosticsPolicySchema.partial().optional(),
518
525
  providers: z5.strictObject({
519
526
  claudeCode: z5.strictObject({ readTranscriptUsage: z5.boolean() }).partial().optional()
520
- }).partial().optional()
527
+ }).partial().optional(),
528
+ sessionContext: sessionContextPolicySchema.partial().optional()
521
529
  });
522
530
  var DEFAULT_EXPORTER_POLICY = Object.freeze({
523
531
  enabled: true,
@@ -552,6 +560,7 @@ var DEFAULT_CONFIG = Object.freeze({
552
560
  providers: DEFAULT_PROVIDERS_POLICY
553
561
  });
554
562
  var readsClaudeTranscriptUsage = (config) => config.providers?.claudeCode?.readTranscriptUsage === true;
563
+ var sessionContextDir = (config) => config.sessionContext?.dir;
555
564
  var effectiveMetricsPolicy = (exporter) => ({
556
565
  ...DEFAULT_METRICS_POLICY,
557
566
  ...exporter.metrics ?? {}
@@ -1703,7 +1712,15 @@ var baseEventFields = {
1703
1712
  * factory, never by hand.
1704
1713
  */
1705
1714
  subagentId: subagentIdSchema.optional(),
1706
- extensions: extensionsSchema.default(emptyExtensions)
1715
+ extensions: extensionsSchema.default(emptyExtensions),
1716
+ /**
1717
+ * Attributes of the session context segment in force when the event
1718
+ * occurred (`docs/session-context.md`), stamped by the core from a file a
1719
+ * harness wrote. Exported on every record of the event, over the same keys
1720
+ * from the Resource. Absent when no context applies. Set by the core only,
1721
+ * never by an adapter.
1722
+ */
1723
+ contextAttributes: z14.record(z14.string().min(1).max(255), z14.union([z14.string(), z14.number(), z14.boolean()])).optional()
1707
1724
  };
1708
1725
  var event = (shape) => z14.strictObject({ ...baseEventFields, ...shape });
1709
1726
  var sessionStartEventSchema = event({
@@ -1890,6 +1907,11 @@ var passthroughResourceAttributes = (resource) => {
1890
1907
  }
1891
1908
  return attributes;
1892
1909
  };
1910
+ var contextAttributesOf = (event2) => event2.contextAttributes === void 0 ? {} : { ...event2.contextAttributes };
1911
+ var profileAttributes = (event2, resource) => ({
1912
+ ...passthroughResourceAttributes(resource),
1913
+ ...contextAttributesOf(event2)
1914
+ });
1893
1915
  var resolveExportedSessionId = (eventSessionId, resource) => {
1894
1916
  for (const key of EXTERNAL_SESSION_KEY_ATTRIBUTES) {
1895
1917
  const supplied = resource.attributes[key];
@@ -1910,6 +1932,8 @@ var hexTraceAttributes = (ids) => ({
1910
1932
  var exportIdentityAttributes = (event2, resource, ids) => {
1911
1933
  const { sessionId, providerSessionId } = resolveExportedSessionId(event2.sessionId, resource);
1912
1934
  return {
1935
+ // First, so nothing in the profile layer can replace an identity attribute.
1936
+ ...profileAttributes(event2, resource),
1913
1937
  [ATTR_SESSION_ID]: sessionId,
1914
1938
  [ATTR_OTELHOOK_SESSION_ID]: providerSessionId,
1915
1939
  [ATTR_GEN_AI_CONVERSATION_ID]: providerSessionId,
@@ -1918,7 +1942,6 @@ var exportIdentityAttributes = (event2, resource, ids) => {
1918
1942
  ...event2.provenance.providerVersion === void 0 ? {} : { [ATTR_OTELHOOK_PROVIDER_VERSION]: event2.provenance.providerVersion },
1919
1943
  [ATTR_OTELHOOK_WORKSPACE_ID]: event2.workspace.workspaceId,
1920
1944
  ...event2.subagentId === void 0 ? {} : { [ATTR_OTELHOOK_SUBAGENT_ID]: event2.subagentId },
1921
- ...passthroughResourceAttributes(resource),
1922
1945
  ...hexTraceAttributes(ids)
1923
1946
  };
1924
1947
  };
@@ -2013,6 +2036,9 @@ var ATTR_OTELHOOK_PROVIDER_ID2 = "otelhook.provider.id";
2013
2036
  var ATTR_OTELHOOK_OUTCOME = "otelhook.outcome";
2014
2037
  var ATTR_OTELHOOK_SESSION_KIND = "otelhook.session.kind";
2015
2038
  var commonAttributes = (event2, resource, includeSessionId) => ({
2039
+ // Session context first, so the metric's own attributes always win; and never
2040
+ // anything account-shaped, whatever the context says.
2041
+ ...event2.contextAttributes === void 0 ? {} : withoutAccountIdentity(event2.contextAttributes),
2016
2042
  [ATTR_OTELHOOK_PROVIDER_ID2]: event2.provenance.providerId,
2017
2043
  ...includeSessionId ? { [ATTR_SESSION_ID2]: resolveExportedSessionId(event2.sessionId, resource).sessionId } : {}
2018
2044
  });
@@ -2059,6 +2085,9 @@ var deriveMetricObservations = (input) => {
2059
2085
  if (recovered !== void 0) {
2060
2086
  return end.occurredAt - recovered.startMillis;
2061
2087
  }
2088
+ if (end.subagentId !== void 0) {
2089
+ return void 0;
2090
+ }
2062
2091
  const turn = lastPromptInBatch?.get(end.sessionId) ?? input.turnStart?.(end.sessionId);
2063
2092
  return turn === void 0 || turn > end.occurredAt ? void 0 : end.occurredAt - turn;
2064
2093
  };
@@ -2390,7 +2419,7 @@ import {
2390
2419
  } from "@opentelemetry/semantic-conventions/incubating";
2391
2420
 
2392
2421
  // src/version.ts
2393
- var VERSION = "0.11.0";
2422
+ var VERSION = "0.13.0";
2394
2423
 
2395
2424
  // src/telemetry/semconv.ts
2396
2425
  var SCOPE_NAME = "@osfactory/otel-hook";
@@ -2538,12 +2567,12 @@ var pickTarget = (attributes) => {
2538
2567
  }
2539
2568
  return picked;
2540
2569
  };
2541
- var withoutTarget = (attributes, resource) => {
2570
+ var withoutTarget = (attributes, resource, event2) => {
2542
2571
  const rest = { ...attributes };
2543
2572
  for (const key of TARGET_KEYS) {
2544
2573
  delete rest[key];
2545
2574
  }
2546
- return { ...rest, ...pickTarget(passthroughResourceAttributes(resource)) };
2575
+ return { ...rest, ...pickTarget(profileAttributes(event2, resource)) };
2547
2576
  };
2548
2577
  var rankOf = (candidate) => {
2549
2578
  const source = candidate[ATTR_OTELHOOK_TARGET_SOURCE];
@@ -2648,7 +2677,7 @@ var buildLifecycleSpan = (plan, resource, scope) => {
2648
2677
  name = "session";
2649
2678
  kind = SpanKind.INTERNAL;
2650
2679
  attributes = {
2651
- ...withoutTarget(attributes, resource),
2680
+ ...withoutTarget(attributes, resource, anchor),
2652
2681
  ...strongestTarget([pickTarget(resolved.recovered), start === void 0 ? {} : targetAttributes(start)]),
2653
2682
  ...start?.agentName === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_NAME]: start.agentName },
2654
2683
  ...start?.agentVersion === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_VERSION]: start.agentVersion },
@@ -2690,7 +2719,7 @@ var buildLifecycleSpan = (plan, resource, scope) => {
2690
2719
  kind = SpanKind.CLIENT;
2691
2720
  attributes = {
2692
2721
  // Target keys are re-chosen below as one unit, never mixed across edges.
2693
- ...withoutTarget(attributes, resource),
2722
+ ...withoutTarget(attributes, resource, anchor),
2694
2723
  [ATTR_GEN_AI_TOOL_NAME2]: toolName,
2695
2724
  [ATTR_GEN_AI_TOOL_CALL_ID]: start?.toolCallId ?? end?.toolCallId ?? group.ref.scopeKey,
2696
2725
  ...start?.toolKind === void 0 ? {} : { [ATTR_OTELHOOK_TOOL_KIND]: start.toolKind },
@@ -3647,11 +3676,11 @@ var createPrivacyService = (policyInput) => {
3647
3676
  };
3648
3677
  const flattenToAttributes = (value, prefix) => {
3649
3678
  const attributes = {};
3650
- const walk = (current, path6) => {
3679
+ const walk = (current, path7) => {
3651
3680
  if (typeof current === "string" || typeof current === "number" || typeof current === "boolean") {
3652
3681
  const primitive = toAttributePrimitive(current);
3653
3682
  if (primitive !== void 0) {
3654
- attributes[path6] = primitive;
3683
+ attributes[path7] = primitive;
3655
3684
  }
3656
3685
  return;
3657
3686
  }
@@ -3670,16 +3699,16 @@ var createPrivacyService = (policyInput) => {
3670
3699
  primitives.push(entryPrimitive);
3671
3700
  }
3672
3701
  if (uniform) {
3673
- attributes[path6] = primitives.slice(0, MAX_ATTRIBUTE_ARRAY_LENGTH);
3702
+ attributes[path7] = primitives.slice(0, MAX_ATTRIBUTE_ARRAY_LENGTH);
3674
3703
  return;
3675
3704
  }
3676
3705
  for (const [index, entry] of current.entries()) {
3677
- walk(entry, `${path6}.${index}`);
3706
+ walk(entry, `${path7}.${index}`);
3678
3707
  }
3679
3708
  return;
3680
3709
  }
3681
3710
  for (const [key, entry] of Object.entries(current)) {
3682
- walk(entry, path6 === "" ? key : `${path6}.${key}`);
3711
+ walk(entry, path7 === "" ? key : `${path7}.${key}`);
3683
3712
  }
3684
3713
  };
3685
3714
  walk(value, prefix);
@@ -4022,7 +4051,16 @@ var subagentStopPayloadSchema = z16.object({
4022
4051
  last_assistant_message: z16.string().optional(),
4023
4052
  /** True when this stop fired because a hook continued the subagent's turn. */
4024
4053
  stop_hook_active: z16.boolean().optional(),
4025
- usage: claudeUsageSchema.optional()
4054
+ /**
4055
+ * The subagent run's tokens since its previous stop — harness- or
4056
+ * enricher-supplied, never upstream. Reported on the subagent's own
4057
+ * generation, never on the parent turn (issue #68).
4058
+ */
4059
+ usage: claudeUsageSchema.optional(),
4060
+ /** Harness-supplied, never upstream: the subagent's model, from its transcript. */
4061
+ model: z16.string().min(1).max(256).optional().catch(void 0),
4062
+ /** Harness-supplied, never upstream: see `stopPayloadSchema.usage_partial`. */
4063
+ usage_partial: z16.boolean().optional().catch(void 0)
4026
4064
  });
4027
4065
  var preCompactPayloadSchema = z16.object({
4028
4066
  ...commonFields,
@@ -4251,7 +4289,8 @@ var clamp = (value, fallback, min, max) => {
4251
4289
  };
4252
4290
  var asRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
4253
4291
  var isTranscriptPath = (transcriptPath) => typeof transcriptPath === "string" && transcriptPath.length > 0 && !transcriptPath.includes("\0") && path.isAbsolute(transcriptPath) && path.extname(transcriptPath) === ".jsonl";
4254
- var assistantRecordOf = (line) => {
4292
+ var isRecordOfAgent = (record, agentId) => record.isSidechain === true && (typeof record.agentId !== "string" || record.agentId === agentId);
4293
+ var assistantRecordOf = (line, agentId) => {
4255
4294
  if (!line.includes('"assistant"')) {
4256
4295
  return void 0;
4257
4296
  }
@@ -4262,7 +4301,10 @@ var assistantRecordOf = (line) => {
4262
4301
  return void 0;
4263
4302
  }
4264
4303
  const record = asRecord2(parsed);
4265
- if (record === void 0 || record.type !== "assistant" || record.isSidechain === true) {
4304
+ if (record === void 0 || record.type !== "assistant") {
4305
+ return void 0;
4306
+ }
4307
+ if (agentId === void 0 ? record.isSidechain === true : !isRecordOfAgent(record, agentId)) {
4266
4308
  return void 0;
4267
4309
  }
4268
4310
  const message = asRecord2(record.message);
@@ -4355,7 +4397,7 @@ var completeLinesEnd = (bytes, start) => {
4355
4397
  const lastNewline = bytes.lastIndexOf(10);
4356
4398
  return lastNewline < 0 ? start : start + lastNewline + 1;
4357
4399
  };
4358
- var readTail = (transcriptPath, maxTailBytes) => withRegularFile(transcriptPath, async (handle, size) => {
4400
+ var readTail = (transcriptPath, maxTailBytes, agentId) => withRegularFile(transcriptPath, async (handle, size) => {
4359
4401
  const length = Math.min(size, maxTailBytes);
4360
4402
  const start = size - length;
4361
4403
  const bytes = await readBytes(handle, start, length);
@@ -4365,7 +4407,7 @@ var readTail = (transcriptPath, maxTailBytes) => withRegularFile(transcriptPath,
4365
4407
  lines.shift();
4366
4408
  }
4367
4409
  for (let index = lines.length - 1; index >= 0; index -= 1) {
4368
- const record = assistantRecordOf((lines[index] ?? "").trim());
4410
+ const record = assistantRecordOf((lines[index] ?? "").trim(), agentId);
4369
4411
  if (record !== void 0) {
4370
4412
  return {
4371
4413
  turn: {
@@ -4379,10 +4421,11 @@ var readTail = (transcriptPath, maxTailBytes) => withRegularFile(transcriptPath,
4379
4421
  }
4380
4422
  return { turn: { status: "unavailable", reason: "no-assistant-message" }, endOffset };
4381
4423
  });
4382
- var boundedTail = async (transcriptPath, options) => withTimeout(
4424
+ var boundedTail = async (transcriptPath, options, agentId) => withTimeout(
4383
4425
  readTail(
4384
4426
  transcriptPath,
4385
- clamp(options.maxTailBytes, DEFAULT_CLAUDE_TRANSCRIPT_TAIL_BYTES, MIN_TAIL_BYTES, MAX_TAIL_BYTES)
4427
+ clamp(options.maxTailBytes, DEFAULT_CLAUDE_TRANSCRIPT_TAIL_BYTES, MIN_TAIL_BYTES, MAX_TAIL_BYTES),
4428
+ agentId
4386
4429
  ),
4387
4430
  clamp(options.timeoutMillis, DEFAULT_CLAUDE_TRANSCRIPT_TIMEOUT_MILLIS, MIN_TIMEOUT_MILLIS, MAX_TIMEOUT_MILLIS),
4388
4431
  { status: "unavailable", reason: "unreadable" }
@@ -4412,7 +4455,7 @@ var readClaudeTranscriptRange = async (transcriptPath, fromOffset, options = {})
4412
4455
  let anonymous = 0;
4413
4456
  let model;
4414
4457
  for (const line of complete.split("\n")) {
4415
- const record = assistantRecordOf(line.trim());
4458
+ const record = assistantRecordOf(line.trim(), options.agentId);
4416
4459
  if (record === void 0) {
4417
4460
  continue;
4418
4461
  }
@@ -4446,6 +4489,20 @@ var eventNameOf = (record) => record.hook_event_name ?? record.hookEventName;
4446
4489
  var transcriptPathOf = (record) => record.transcript_path ?? record.transcriptPath;
4447
4490
  var CLAUDE_TRANSCRIPT_USAGE_ENRICHER_ID = "claude-transcript-usage";
4448
4491
  var sourceDigest = (transcriptPath) => createHash4("sha256").update(transcriptPath, "utf8").digest("hex").slice(0, 32);
4492
+ var SUBAGENT_STOP = "SubagentStop";
4493
+ var agentIdOf = (record) => {
4494
+ const agentId = record.agent_id ?? record.agentId;
4495
+ return typeof agentId === "string" && agentId.length > 0 && agentId.length <= 256 ? agentId : void 0;
4496
+ };
4497
+ var agentTranscriptPathOf = (record) => record.agent_transcript_path ?? record.agentTranscriptPath;
4498
+ var subagentCursorScope = (payload) => {
4499
+ const record = asRecord2(payload);
4500
+ if (record === void 0 || eventNameOf(record) !== SUBAGENT_STOP) {
4501
+ return void 0;
4502
+ }
4503
+ const agentId = agentIdOf(record);
4504
+ return agentId === void 0 ? void 0 : `agent-${createHash4("sha256").update(agentId, "utf8").digest("hex").slice(0, 32)}`;
4505
+ };
4449
4506
  var createClaudeTranscriptUsageEnricher = (options = {}) => {
4450
4507
  const fileSize = async (transcriptPath) => {
4451
4508
  try {
@@ -4455,6 +4512,46 @@ var createClaudeTranscriptUsageEnricher = (options = {}) => {
4455
4512
  return thrown?.code === "ENOENT" ? "absent" : void 0;
4456
4513
  }
4457
4514
  };
4515
+ const readOptions = (agentId) => ({
4516
+ ...options.maxRangeBytes === void 0 ? {} : { maxRangeBytes: options.maxRangeBytes },
4517
+ ...options.rangeTimeoutMillis === void 0 ? {} : { rangeTimeoutMillis: options.rangeTimeoutMillis },
4518
+ ...agentId === void 0 ? {} : { agentId }
4519
+ });
4520
+ const attachSince = async (record, transcriptPath, fromOffset, agentId) => {
4521
+ const source = sourceDigest(transcriptPath);
4522
+ const attach = (model, usage, partial) => ({
4523
+ ...record,
4524
+ ...record.model === void 0 && model !== void 0 ? { model } : {},
4525
+ ...usage === void 0 ? {} : { usage, usage_partial: partial }
4526
+ });
4527
+ if (fromOffset !== void 0) {
4528
+ const range = await readClaudeTranscriptRange(transcriptPath, fromOffset, readOptions(agentId));
4529
+ if (range.status === "found") {
4530
+ return {
4531
+ payload: attach(range.model, range.usage, false),
4532
+ cursor: { source, offset: range.endOffset },
4533
+ notes: [`summed ${String(range.requestCount)} request(s) since the last stop`]
4534
+ };
4535
+ }
4536
+ if (range.reason !== "truncated" && range.reason !== "over-cap") {
4537
+ return { payload: record, notes: [`transcript range not read (${range.reason}); cursor kept`] };
4538
+ }
4539
+ }
4540
+ const tail = await boundedTail(transcriptPath, options, agentId);
4541
+ if (tail === TIMED_OUT || !("turn" in tail)) {
4542
+ return { payload: record, notes: [`transcript tail not read (${tail === TIMED_OUT ? "timeout" : tail.reason})`] };
4543
+ }
4544
+ const why = fromOffset === void 0 ? "no cursor for this transcript" : "range not summable within bounds";
4545
+ return {
4546
+ payload: tail.turn.status === "found" ? attach(tail.turn.model, tail.turn.usage, true) : record,
4547
+ cursor: { source, offset: tail.endOffset },
4548
+ notes: [`${why}; attached the last request only (usage_partial)`]
4549
+ };
4550
+ };
4551
+ const skipAttached = async (payload, transcriptPath) => {
4552
+ const size = await fileSize(transcriptPath);
4553
+ return typeof size === "number" ? { payload, cursor: { source: sourceDigest(transcriptPath), offset: size } } : { payload };
4554
+ };
4458
4555
  const enrich = async (input) => {
4459
4556
  const unchanged = { payload: input.payload };
4460
4557
  const record = asRecord2(input.payload);
@@ -4462,6 +4559,18 @@ var createClaudeTranscriptUsageEnricher = (options = {}) => {
4462
4559
  return unchanged;
4463
4560
  }
4464
4561
  const eventName = eventNameOf(record);
4562
+ if (eventName === SUBAGENT_STOP) {
4563
+ const agentTranscriptPath = agentTranscriptPathOf(record);
4564
+ const agentId = agentIdOf(record);
4565
+ if (agentId === void 0 || !isTranscriptPath(agentTranscriptPath)) {
4566
+ return unchanged;
4567
+ }
4568
+ if (hasUsage(record)) {
4569
+ return skipAttached(input.payload, agentTranscriptPath);
4570
+ }
4571
+ const cursor2 = input.cursor?.source === sourceDigest(agentTranscriptPath) ? input.cursor : void 0;
4572
+ return attachSince(record, agentTranscriptPath, cursor2?.offset ?? 0, agentId);
4573
+ }
4465
4574
  const transcriptPath = transcriptPathOf(record);
4466
4575
  if (typeof eventName !== "string" || !isTranscriptPath(transcriptPath)) {
4467
4576
  return unchanged;
@@ -4482,41 +4591,14 @@ var createClaudeTranscriptUsageEnricher = (options = {}) => {
4482
4591
  return unchanged;
4483
4592
  }
4484
4593
  if (hasUsage(record)) {
4485
- const size = await fileSize(transcriptPath);
4486
- return typeof size === "number" ? { payload: input.payload, cursor: { source, offset: size } } : unchanged;
4594
+ return skipAttached(input.payload, transcriptPath);
4487
4595
  }
4488
- const attach = (model, usage, partial) => ({
4489
- ...record,
4490
- ...record.model === void 0 && model !== void 0 ? { model } : {},
4491
- ...usage === void 0 ? {} : { usage, usage_partial: partial }
4492
- });
4493
- if (cursor !== void 0) {
4494
- const range = await readClaudeTranscriptRange(transcriptPath, cursor.offset, options);
4495
- if (range.status === "found") {
4496
- return {
4497
- payload: attach(range.model, range.usage, false),
4498
- cursor: { source, offset: range.endOffset },
4499
- notes: [`summed ${String(range.requestCount)} request(s) since the last stop`]
4500
- };
4501
- }
4502
- if (range.reason !== "truncated" && range.reason !== "over-cap") {
4503
- return { ...unchanged, notes: [`transcript range not read (${range.reason}); cursor kept`] };
4504
- }
4505
- }
4506
- const tail = await boundedTail(transcriptPath, options);
4507
- if (tail === TIMED_OUT || !("turn" in tail)) {
4508
- return { ...unchanged, notes: [`transcript tail not read (${tail === TIMED_OUT ? "timeout" : tail.reason})`] };
4509
- }
4510
- const why = cursor === void 0 ? "no cursor for this transcript" : "range not summable within bounds";
4511
- return {
4512
- payload: tail.turn.status === "found" ? attach(tail.turn.model, tail.turn.usage, true) : input.payload,
4513
- cursor: { source, offset: tail.endOffset },
4514
- notes: [`${why}; attached the last request only (usage_partial)`]
4515
- };
4596
+ return attachSince(record, transcriptPath, cursor?.offset, void 0);
4516
4597
  };
4517
4598
  return Object.freeze({
4518
4599
  id: CLAUDE_TRANSCRIPT_USAGE_ENRICHER_ID,
4519
4600
  providerId: CLAUDE_CODE_PROVIDER_ID,
4601
+ cursorScope: subagentCursorScope,
4520
4602
  enrich
4521
4603
  });
4522
4604
  };
@@ -4528,7 +4610,7 @@ var createSystemClock = () => ({
4528
4610
  });
4529
4611
 
4530
4612
  // src/runtime/hook.ts
4531
- import { z as z18 } from "zod";
4613
+ import { z as z19 } from "zod";
4532
4614
 
4533
4615
  // src/providers/registry.ts
4534
4616
  var createProviderRegistry = (adapters) => {
@@ -4953,8 +5035,200 @@ var resolveEventTargets = async (input) => {
4953
5035
  return { events, resolved: settled.size, timedOut: finished === "timeout" };
4954
5036
  };
4955
5037
 
5038
+ // src/runtime/session-context.ts
5039
+ import { open as open2 } from "fs/promises";
5040
+ import * as path3 from "path";
5041
+ import { z as z18 } from "zod";
5042
+ var SESSION_CONTEXT_FILE_VERSION = 1;
5043
+ var DEFAULT_SESSION_CONTEXT_MAX_BYTES = 256 * 1024;
5044
+ var DEFAULT_SESSION_CONTEXT_BUDGET_MILLIS = 100;
5045
+ var MAX_SESSION_CONTEXT_SEGMENTS = 1024;
5046
+ var SESSION_CONTEXT_AGENT_TOOLS = Object.freeze({
5047
+ "claude-code": "claude_code",
5048
+ codex: "codex",
5049
+ cursor: "cursor",
5050
+ "gemini-cli": "gemini_cli",
5051
+ antigravity: "antigravity"
5052
+ });
5053
+ var sessionContextAgentTool = (providerId) => Object.hasOwn(SESSION_CONTEXT_AGENT_TOOLS, providerId) ? SESSION_CONTEXT_AGENT_TOOLS[providerId] : void 0;
5054
+ var SESSION_FILE_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/;
5055
+ var isSessionContextFileName = (sessionId) => SESSION_FILE_NAME_PATTERN.test(sessionId) && !sessionId.includes("..");
5056
+ var sessionContextFilePath = (dir, providerId, sessionId) => {
5057
+ const tool = sessionContextAgentTool(providerId);
5058
+ if (tool === void 0 || !isSessionContextFileName(sessionId) || !path3.isAbsolute(dir)) {
5059
+ return void 0;
5060
+ }
5061
+ return path3.join(dir, tool, `${sessionId}.json`);
5062
+ };
5063
+ var RESERVED_CONTEXT_KEYS = /* @__PURE__ */ new Set([
5064
+ "session.id",
5065
+ "trace_id",
5066
+ "span_id",
5067
+ "parent_span_id",
5068
+ "gen_ai.conversation.id",
5069
+ "factory.local"
5070
+ ]);
5071
+ var RESERVED_CONTEXT_PREFIXES = Object.freeze(["factory.local.", "otelhook."]);
5072
+ var isReservedSessionContextKey = (key) => RESERVED_CONTEXT_KEYS.has(key) || RESERVED_CONTEXT_PREFIXES.some((prefix) => key.startsWith(prefix));
5073
+ var sanitizeSessionContextAttributes = (attributes) => {
5074
+ const kept = {};
5075
+ let count = 0;
5076
+ for (const [key, value] of Object.entries(attributes)) {
5077
+ if (count >= MAX_RESOURCE_ATTRIBUTES) {
5078
+ break;
5079
+ }
5080
+ if (checkResourceAttributeKey(key) !== void 0 || isReservedSessionContextKey(key)) {
5081
+ continue;
5082
+ }
5083
+ if (typeof value === "string") {
5084
+ if (value.length > MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH) {
5085
+ continue;
5086
+ }
5087
+ } else if (typeof value === "number") {
5088
+ if (!Number.isFinite(value)) {
5089
+ continue;
5090
+ }
5091
+ } else if (typeof value !== "boolean") {
5092
+ continue;
5093
+ }
5094
+ kept[key] = value;
5095
+ count += 1;
5096
+ }
5097
+ return kept;
5098
+ };
5099
+ 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})$/;
5100
+ var isoInstantSchema = z18.string().max(64).regex(ISO_INSTANT_PATTERN).transform((value, ctx) => {
5101
+ const millis = Date.parse(value);
5102
+ if (!Number.isFinite(millis)) {
5103
+ ctx.issues.push({ code: "custom", input: value, message: "not a valid instant" });
5104
+ return z18.NEVER;
5105
+ }
5106
+ return millis;
5107
+ });
5108
+ var segmentSchema = z18.object({
5109
+ from: isoInstantSchema,
5110
+ to: isoInstantSchema.nullable(),
5111
+ reason: z18.string().max(256).optional(),
5112
+ attributes: z18.record(z18.string(), z18.unknown())
5113
+ });
5114
+ var sessionContextFileSchema = z18.object({
5115
+ version: z18.literal(SESSION_CONTEXT_FILE_VERSION),
5116
+ agentTool: z18.string().max(64).optional(),
5117
+ sessionId: z18.string().max(256).optional(),
5118
+ segments: z18.array(segmentSchema).max(MAX_SESSION_CONTEXT_SEGMENTS)
5119
+ });
5120
+ var parseSessionContextFile = (value, expected) => {
5121
+ const parsed = sessionContextFileSchema.safeParse(value);
5122
+ if (!parsed.success) {
5123
+ return void 0;
5124
+ }
5125
+ const file = parsed.data;
5126
+ 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) {
5127
+ return void 0;
5128
+ }
5129
+ return file.segments.map((segment) => ({
5130
+ from: segment.from,
5131
+ to: segment.to,
5132
+ attributes: sanitizeSessionContextAttributes(segment.attributes)
5133
+ }));
5134
+ };
5135
+ var segmentInForce = (segments, at) => {
5136
+ let best;
5137
+ for (const segment of segments) {
5138
+ if (segment.from <= at && (segment.to === null || at < segment.to)) {
5139
+ if (best === void 0 || segment.from >= best.from) {
5140
+ best = segment;
5141
+ }
5142
+ }
5143
+ }
5144
+ return best;
5145
+ };
5146
+ var stampSessionContext = (events, segments) => events.map((event2) => {
5147
+ const { contextAttributes: _discarded, ...rest } = event2;
5148
+ const segment = segments === void 0 ? void 0 : segmentInForce(segments, event2.occurredAt);
5149
+ if (segment === void 0 || Object.keys(segment.attributes).length === 0) {
5150
+ return _discarded === void 0 ? event2 : rest;
5151
+ }
5152
+ return { ...rest, contextAttributes: { ...segment.attributes } };
5153
+ });
5154
+ var readBounded = async (file, maxBytes) => {
5155
+ let handle;
5156
+ try {
5157
+ handle = await open2(file, "r");
5158
+ } catch {
5159
+ return void 0;
5160
+ }
5161
+ try {
5162
+ const stats = await handle.stat();
5163
+ if (!stats.isFile() || stats.size > maxBytes) {
5164
+ return void 0;
5165
+ }
5166
+ const buffer = Buffer.alloc(maxBytes + 1);
5167
+ let length = 0;
5168
+ while (length < buffer.length) {
5169
+ const { bytesRead } = await handle.read(buffer, length, buffer.length - length, length);
5170
+ if (bytesRead === 0) {
5171
+ break;
5172
+ }
5173
+ length += bytesRead;
5174
+ }
5175
+ if (length > maxBytes) {
5176
+ return void 0;
5177
+ }
5178
+ return buffer.subarray(0, length).toString("utf8");
5179
+ } catch {
5180
+ return void 0;
5181
+ } finally {
5182
+ await handle.close().catch(() => void 0);
5183
+ }
5184
+ };
5185
+ var createDirectorySessionContextReader = (options) => {
5186
+ const maxBytes = options.maxBytes ?? DEFAULT_SESSION_CONTEXT_MAX_BYTES;
5187
+ const budgetMillis = options.budgetMillis ?? DEFAULT_SESSION_CONTEXT_BUDGET_MILLIS;
5188
+ const readOnce = async (providerId, sessionId) => {
5189
+ const file = sessionContextFilePath(options.dir, providerId, sessionId);
5190
+ if (file === void 0) {
5191
+ return void 0;
5192
+ }
5193
+ const text = await readBounded(file, maxBytes);
5194
+ if (text === void 0) {
5195
+ return void 0;
5196
+ }
5197
+ let decoded;
5198
+ try {
5199
+ decoded = JSON.parse(text);
5200
+ } catch {
5201
+ return void 0;
5202
+ }
5203
+ const agentTool = sessionContextAgentTool(providerId);
5204
+ return parseSessionContextFile(decoded, {
5205
+ ...agentTool === void 0 ? {} : { agentTool },
5206
+ sessionId
5207
+ });
5208
+ };
5209
+ return {
5210
+ read: async (request) => {
5211
+ let timer;
5212
+ const timeout = new Promise((resolve3) => {
5213
+ timer = setTimeout(() => resolve3(void 0), budgetMillis);
5214
+ timer.unref?.();
5215
+ });
5216
+ try {
5217
+ return await Promise.race([
5218
+ readOnce(request.providerId, request.sessionId).catch(() => void 0),
5219
+ timeout
5220
+ ]);
5221
+ } finally {
5222
+ if (timer !== void 0) {
5223
+ clearTimeout(timer);
5224
+ }
5225
+ }
5226
+ }
5227
+ };
5228
+ };
5229
+
4956
5230
  // src/runtime/hook.ts
4957
- var usageScopeSchema = z18.enum(["session", "generation", "subagent"]);
5231
+ var usageScopeSchema = z19.enum(["session", "generation", "subagent"]);
4958
5232
  var classifyDurability = (input) => {
4959
5233
  if (!input.attempted) {
4960
5234
  return "nothing-to-deliver";
@@ -5013,7 +5287,7 @@ var usageScopeOf = (event2) => {
5013
5287
  };
5014
5288
  var sequenceKey = (sessionId) => `sequence:${sessionId}`;
5015
5289
  var sessionModelKey = (sessionId) => `model:${sessionId}`;
5016
- var readCursorKey = (enricherId, sessionId) => `cursor:${enricherId}:${sessionId}`;
5290
+ var readCursorKey = (enricherId, sessionId, scope) => scope === void 0 ? `cursor:${enricherId}:${sessionId}` : `cursor:${enricherId}:${sessionId}:${scope}`;
5017
5291
  var UNKNOWN_MODEL_ID = "unknown";
5018
5292
  var latestSessionModel = (events) => {
5019
5293
  let latest;
@@ -5081,7 +5355,17 @@ var createOtelHook = (deps) => {
5081
5355
  if (enricher.providerId !== providerId) {
5082
5356
  continue;
5083
5357
  }
5084
- const key = readCursorKey(enricher.id, sessionId);
5358
+ let scope;
5359
+ try {
5360
+ scope = enricher.cursorScope?.(current);
5361
+ } catch (thrown) {
5362
+ logger.warn("payload enricher failed; parsing the payload as delivered", {
5363
+ "enricher.id": enricher.id,
5364
+ "error.name": thrown instanceof Error ? thrown.name : typeof thrown
5365
+ });
5366
+ continue;
5367
+ }
5368
+ const key = readCursorKey(enricher.id, sessionId, scope);
5085
5369
  let cursor;
5086
5370
  try {
5087
5371
  const record = await deps.stateStore.read(key);
@@ -5663,6 +5947,10 @@ var createOtelHook = (deps) => {
5663
5947
  });
5664
5948
  }
5665
5949
  }
5950
+ batch = stampSessionContext(
5951
+ batch,
5952
+ !suppress && batch.length > 0 && deps.sessionContext !== void 0 ? await readSessionContext(deps.sessionContext, detection.providerId, identity.sessionId) : void 0
5953
+ );
5666
5954
  let emitted = 0;
5667
5955
  let exportRejected = 0;
5668
5956
  if (!suppress && batch.length > 0) {
@@ -5778,6 +6066,13 @@ var createOtelHook = (deps) => {
5778
6066
  };
5779
6067
  return { resolveDelivery, ingest, flush, shutdown, config };
5780
6068
  };
6069
+ var readSessionContext = async (reader, providerId, sessionId) => {
6070
+ try {
6071
+ return await reader.read({ providerId, sessionId });
6072
+ } catch {
6073
+ return void 0;
6074
+ }
6075
+ };
5781
6076
  var buildErrorEvents = (diagnostics, identity, sequenceBase, ids, privacy) => {
5782
6077
  const events = [];
5783
6078
  for (const [index, info] of diagnostics.slice(0, MAX_ERROR_EVENTS).entries()) {
@@ -5812,8 +6107,8 @@ var buildErrorEvents = (diagnostics, identity, sequenceBase, ids, privacy) => {
5812
6107
  };
5813
6108
 
5814
6109
  // src/runtime/git-worktree.ts
5815
- import { lstat, open as open2, stat as stat2 } from "fs/promises";
5816
- import * as path3 from "path";
6110
+ import { lstat, open as open3, stat as stat2 } from "fs/promises";
6111
+ import * as path4 from "path";
5817
6112
  var MAX_WORKTREE_WALK_DEPTH = 128;
5818
6113
  var MAX_GIT_FILE_BYTES = 4096;
5819
6114
  var MAX_CACHE_ENTRIES = 1024;
@@ -5821,10 +6116,10 @@ var DEFAULT_WORKTREE_CACHE_TTL_MILLIS = 5e3;
5821
6116
  var MAX_BRANCH_NAME_LENGTH = 255;
5822
6117
  var ABSENT = Object.freeze({ kind: "absent" });
5823
6118
  var INVALID = Object.freeze({ kind: "invalid" });
5824
- var readBounded = async (filePath) => {
6119
+ var readBounded2 = async (filePath) => {
5825
6120
  let handle;
5826
6121
  try {
5827
- handle = await open2(filePath, "r");
6122
+ handle = await open3(filePath, "r");
5828
6123
  const buffer = Buffer.alloc(MAX_GIT_FILE_BYTES);
5829
6124
  const { bytesRead } = await handle.read(buffer, 0, MAX_GIT_FILE_BYTES, 0);
5830
6125
  return buffer.subarray(0, bytesRead).toString("utf8");
@@ -5845,7 +6140,7 @@ var parseHeadBranch = (head) => {
5845
6140
  return branch;
5846
6141
  };
5847
6142
  var firstLine = (content) => content.split(/\r?\n/, 1)[0]?.trim() ?? "";
5848
- var resolveGitPath = (target, base) => target === void 0 || target.length === 0 || target.includes("\0") ? void 0 : path3.resolve(base, target);
6143
+ var resolveGitPath = (target, base) => target === void 0 || target.length === 0 || target.includes("\0") ? void 0 : path4.resolve(base, target);
5849
6144
  var parseGitDirFile = (content, worktreeRoot) => {
5850
6145
  const line = firstLine(content);
5851
6146
  return resolveGitPath(
@@ -5871,17 +6166,17 @@ var isDirectory = async (directory) => {
5871
6166
  }
5872
6167
  };
5873
6168
  var repositoryOf = async (worktreeRoot, gitDir) => {
5874
- const commonDirFile = path3.join(gitDir, "commondir");
5875
- const content = await readBounded(commonDirFile);
6169
+ const commonDirFile = path4.join(gitDir, "commondir");
6170
+ const content = await readBounded2(commonDirFile);
5876
6171
  if (content === void 0) {
5877
6172
  return await isMissing(commonDirFile) ? { kind: "main", mainRoot: worktreeRoot } : { kind: "linked" };
5878
6173
  }
5879
6174
  const commonDir = parseCommonDirFile(content, gitDir);
5880
- const mainRoot = commonDir !== void 0 && path3.basename(commonDir) === ".git" && await isDirectory(commonDir) ? path3.dirname(commonDir) : void 0;
6175
+ const mainRoot = commonDir !== void 0 && path4.basename(commonDir) === ".git" && await isDirectory(commonDir) ? path4.dirname(commonDir) : void 0;
5881
6176
  return { kind: "linked", ...mainRoot === void 0 ? {} : { mainRoot } };
5882
6177
  };
5883
6178
  var probeDirectory = async (directory) => {
5884
- const dotGit = path3.join(directory, ".git");
6179
+ const dotGit = path4.join(directory, ".git");
5885
6180
  let info;
5886
6181
  try {
5887
6182
  info = await stat2(dotGit);
@@ -5892,13 +6187,13 @@ var probeDirectory = async (directory) => {
5892
6187
  if (info.isDirectory()) {
5893
6188
  gitDir = dotGit;
5894
6189
  } else if (info.isFile()) {
5895
- const content = await readBounded(dotGit);
6190
+ const content = await readBounded2(dotGit);
5896
6191
  gitDir = content === void 0 ? void 0 : parseGitDirFile(content, directory);
5897
6192
  }
5898
6193
  if (gitDir === void 0) {
5899
6194
  return INVALID;
5900
6195
  }
5901
- const head = await readBounded(path3.join(gitDir, "HEAD"));
6196
+ const head = await readBounded2(path4.join(gitDir, "HEAD"));
5902
6197
  if (head === void 0) {
5903
6198
  return INVALID;
5904
6199
  }
@@ -5928,10 +6223,10 @@ var createFilesystemWorktreeLocator = (options = {}) => {
5928
6223
  };
5929
6224
  const locate = async (absolutePath) => {
5930
6225
  try {
5931
- if (!path3.isAbsolute(absolutePath) || absolutePath.includes("\0")) {
6226
+ if (!path4.isAbsolute(absolutePath) || absolutePath.includes("\0")) {
5932
6227
  return void 0;
5933
6228
  }
5934
- let directory = path3.resolve(absolutePath);
6229
+ let directory = path4.resolve(absolutePath);
5935
6230
  for (let depth = 0; depth < MAX_WORKTREE_WALK_DEPTH; depth += 1) {
5936
6231
  const probe = await cachedProbe(directory);
5937
6232
  if (probe.kind === "worktree") {
@@ -5940,7 +6235,7 @@ var createFilesystemWorktreeLocator = (options = {}) => {
5940
6235
  if (probe.kind === "invalid") {
5941
6236
  return void 0;
5942
6237
  }
5943
- const parent = path3.dirname(directory);
6238
+ const parent = path4.dirname(directory);
5944
6239
  if (parent === directory) {
5945
6240
  return void 0;
5946
6241
  }
@@ -5956,8 +6251,8 @@ var createFilesystemWorktreeLocator = (options = {}) => {
5956
6251
 
5957
6252
  // src/state/filesystem-store.ts
5958
6253
  import { randomBytes as randomBytes2 } from "crypto";
5959
- import { mkdir, open as open3, readFile, readdir, rename, unlink, writeFile } from "fs/promises";
5960
- import * as path4 from "path";
6254
+ import { mkdir, open as open4, readFile, readdir, rename, unlink, writeFile } from "fs/promises";
6255
+ import * as path5 from "path";
5961
6256
 
5962
6257
  // src/state/keys.ts
5963
6258
  import { createHash as createHash6 } from "crypto";
@@ -5989,10 +6284,10 @@ var wrapFsError = (thrown, operation) => {
5989
6284
  };
5990
6285
  var createFilesystemStateStore = (options) => {
5991
6286
  const [providerSegment, installationSegment] = namespaceSegments(options);
5992
- const baseDir = path4.join(options.rootDir, providerSegment, installationSegment);
5993
- const recordsDir = path4.join(baseDir, "records");
5994
- const quarantineDir = path4.join(baseDir, "quarantine");
5995
- const locksDir = path4.join(baseDir, "locks");
6287
+ const baseDir = path5.join(options.rootDir, providerSegment, installationSegment);
6288
+ const recordsDir = path5.join(baseDir, "records");
6289
+ const quarantineDir = path5.join(baseDir, "quarantine");
6290
+ const locksDir = path5.join(baseDir, "locks");
5996
6291
  const lockTimeoutMillis = options.lockTimeoutMillis ?? 5e3;
5997
6292
  const lockStaleMillis = options.lockStaleMillis ?? 3e4;
5998
6293
  const lockPollIntervalMillis = options.lockPollIntervalMillis ?? 25;
@@ -6016,11 +6311,11 @@ var createFilesystemStateStore = (options) => {
6016
6311
  throw wrapFsError(thrown, "ensure-dirs");
6017
6312
  }
6018
6313
  };
6019
- const recordPath = (key) => path4.join(recordsDir, `${keyDigest(key)}.json`);
6020
- const tempPath = (key) => path4.join(recordsDir, `.tmp-${keyDigest(key)}-${randomBytes2(6).toString("hex")}.json`);
6021
- const lockPath = (sessionId) => path4.join(locksDir, `${sanitizeSegment(sessionId)}.lock`);
6314
+ const recordPath = (key) => path5.join(recordsDir, `${keyDigest(key)}.json`);
6315
+ const tempPath = (key) => path5.join(recordsDir, `.tmp-${keyDigest(key)}-${randomBytes2(6).toString("hex")}.json`);
6316
+ const lockPath = (sessionId) => path5.join(locksDir, `${sanitizeSegment(sessionId)}.lock`);
6022
6317
  const quarantine = async (filePath, key, reason) => {
6023
- const dest = path4.join(quarantineDir, `${options.clock.now()}-${keyDigest(key)}-${reason}.json`);
6318
+ const dest = path5.join(quarantineDir, `${options.clock.now()}-${keyDigest(key)}-${reason}.json`);
6024
6319
  try {
6025
6320
  await rename(filePath, dest);
6026
6321
  } catch {
@@ -6084,7 +6379,7 @@ var createFilesystemStateStore = (options) => {
6084
6379
  const startedAt = options.clock.monotonicMillis();
6085
6380
  for (; ; ) {
6086
6381
  try {
6087
- const handle = await open3(filePath, "wx");
6382
+ const handle = await open4(filePath, "wx");
6088
6383
  try {
6089
6384
  await handle.writeFile(JSON.stringify({ pid: process.pid, acquiredAt: options.clock.now() }));
6090
6385
  } finally {
@@ -6152,7 +6447,7 @@ var createFilesystemStateStore = (options) => {
6152
6447
  }
6153
6448
  let raw;
6154
6449
  try {
6155
- raw = await readFile(path4.join(recordsDir, entry), "utf8");
6450
+ raw = await readFile(path5.join(recordsDir, entry), "utf8");
6156
6451
  } catch {
6157
6452
  continue;
6158
6453
  }
@@ -6205,7 +6500,7 @@ var createFilesystemStateStore = (options) => {
6205
6500
  continue;
6206
6501
  }
6207
6502
  scanned += 1;
6208
- const filePath = path4.join(recordsDir, entry);
6503
+ const filePath = path5.join(recordsDir, entry);
6209
6504
  try {
6210
6505
  const raw = await readFile(filePath, "utf8");
6211
6506
  const envelope = JSON.parse(raw);
@@ -6225,7 +6520,7 @@ var createFilesystemStateStore = (options) => {
6225
6520
  lockEntries = [];
6226
6521
  }
6227
6522
  for (const entry of lockEntries) {
6228
- const filePath = path4.join(locksDir, entry);
6523
+ const filePath = path5.join(locksDir, entry);
6229
6524
  try {
6230
6525
  const raw = await readFile(filePath, "utf8");
6231
6526
  const parsed = JSON.parse(raw);
@@ -6278,7 +6573,7 @@ var siblingSignalEndpoint = (tracesEndpoint, signal) => {
6278
6573
  // src/telemetry/spool-queue.ts
6279
6574
  import { randomBytes as randomBytes3 } from "crypto";
6280
6575
  import { mkdir as mkdir2, readFile as readFile2, readdir as readdir2, rename as rename2, stat as stat3, unlink as unlink2, writeFile as writeFile2 } from "fs/promises";
6281
- import * as path5 from "path";
6576
+ import * as path6 from "path";
6282
6577
  var EMPTY_SPOOL_DROP_COUNTS = Object.freeze({
6283
6578
  total: 0,
6284
6579
  age: 0,
@@ -6294,7 +6589,7 @@ var enqueuedAtOf = (fileName) => {
6294
6589
  var isCount = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0;
6295
6590
  var readSpoolDropCounts = async (queueDir) => {
6296
6591
  try {
6297
- const parsed = JSON.parse(await readFile2(path5.join(queueDir, SPOOL_DROPS_FILE), "utf8"));
6592
+ const parsed = JSON.parse(await readFile2(path6.join(queueDir, SPOOL_DROPS_FILE), "utf8"));
6298
6593
  if (typeof parsed !== "object" || parsed === null) {
6299
6594
  return EMPTY_SPOOL_DROP_COUNTS;
6300
6595
  }
@@ -6323,7 +6618,7 @@ var readSpoolQueueStats = async (queueDir) => {
6323
6618
  let bytes = 0;
6324
6619
  for (const file of files) {
6325
6620
  try {
6326
- bytes += (await stat3(path5.join(queueDir, file))).size;
6621
+ bytes += (await stat3(path6.join(queueDir, file))).size;
6327
6622
  } catch {
6328
6623
  }
6329
6624
  }
@@ -6339,8 +6634,8 @@ var DEFAULT_DRAIN_MAX_BATCHES = 20;
6339
6634
  var isErrnoException2 = (thrown, code) => thrown instanceof Error && thrown.code === code;
6340
6635
  var createSpoolQueue = (options) => {
6341
6636
  const [providerSegment, installationSegment] = namespaceSegments(options);
6342
- const queueDir = path5.join(options.rootDir, providerSegment, installationSegment, options.queueName);
6343
- const corruptDir = path5.join(
6637
+ const queueDir = path6.join(options.rootDir, providerSegment, installationSegment, options.queueName);
6638
+ const corruptDir = path6.join(
6344
6639
  options.rootDir,
6345
6640
  providerSegment,
6346
6641
  installationSegment,
@@ -6387,9 +6682,9 @@ var createSpoolQueue = (options) => {
6387
6682
  [reason]: current[reason] + dropped,
6388
6683
  lastDroppedAt: options.clock.now()
6389
6684
  };
6390
- const tmp = path5.join(queueDir, `.tmp-${randomBytes3(6).toString("hex")}.drops`);
6685
+ const tmp = path6.join(queueDir, `.tmp-${randomBytes3(6).toString("hex")}.drops`);
6391
6686
  await writeFile2(tmp, JSON.stringify(next), "utf8");
6392
- await rename2(tmp, path5.join(queueDir, SPOOL_DROPS_FILE));
6687
+ await rename2(tmp, path6.join(queueDir, SPOOL_DROPS_FILE));
6393
6688
  } catch {
6394
6689
  }
6395
6690
  options.logger?.warn("durable spool dropped batches", {
@@ -6405,7 +6700,7 @@ var createSpoolQueue = (options) => {
6405
6700
  let bytes = 0;
6406
6701
  if (options.maxBytes !== void 0) {
6407
6702
  try {
6408
- bytes = (await stat3(path5.join(queueDir, name))).size;
6703
+ bytes = (await stat3(path6.join(queueDir, name))).size;
6409
6704
  } catch {
6410
6705
  continue;
6411
6706
  }
@@ -6419,7 +6714,7 @@ var createSpoolQueue = (options) => {
6419
6714
  let removed = 0;
6420
6715
  for (const file of files) {
6421
6716
  try {
6422
- await unlink2(path5.join(queueDir, file.name));
6717
+ await unlink2(path6.join(queueDir, file.name));
6423
6718
  removed += 1;
6424
6719
  } catch {
6425
6720
  }
@@ -6479,8 +6774,8 @@ var createSpoolQueue = (options) => {
6479
6774
  }
6480
6775
  }
6481
6776
  const fileName = `${String(now).padStart(16, "0")}-${randomBytes3(6).toString("hex")}.json`;
6482
- const target = path5.join(queueDir, fileName);
6483
- const tmp = path5.join(queueDir, `.tmp-${randomBytes3(6).toString("hex")}.json`);
6777
+ const target = path6.join(queueDir, fileName);
6778
+ const tmp = path6.join(queueDir, `.tmp-${randomBytes3(6).toString("hex")}.json`);
6484
6779
  await writeFile2(tmp, serialized, "utf8");
6485
6780
  await rename2(tmp, target);
6486
6781
  return { spooled: true };
@@ -6510,7 +6805,7 @@ var createSpoolQueue = (options) => {
6510
6805
  if (fileName === void 0) {
6511
6806
  break;
6512
6807
  }
6513
- const filePath = path5.join(queueDir, fileName);
6808
+ const filePath = path6.join(queueDir, fileName);
6514
6809
  const quarantine = async (rejection) => {
6515
6810
  quarantined += 1;
6516
6811
  options.logger?.error("durable spool quarantined an unusable batch", {
@@ -6519,7 +6814,7 @@ var createSpoolQueue = (options) => {
6519
6814
  "spool.queue": options.queueName
6520
6815
  });
6521
6816
  try {
6522
- await rename2(filePath, path5.join(corruptDir, fileName));
6817
+ await rename2(filePath, path6.join(corruptDir, fileName));
6523
6818
  } catch {
6524
6819
  await unlink2(filePath).catch(() => void 0);
6525
6820
  }
@@ -6896,6 +7191,33 @@ var replayResource = (attributes, policy) => {
6896
7191
  }
6897
7192
  return resourceFromAttributes(safe);
6898
7193
  };
7194
+ var agreedContextAttributes = (events) => {
7195
+ const [first, ...rest] = events;
7196
+ if (first?.contextAttributes === void 0) {
7197
+ return {};
7198
+ }
7199
+ const agreed = { ...first.contextAttributes };
7200
+ for (const event2 of rest) {
7201
+ for (const key of Object.keys(agreed)) {
7202
+ if (event2.contextAttributes?.[key] !== agreed[key]) {
7203
+ delete agreed[key];
7204
+ }
7205
+ }
7206
+ }
7207
+ return agreed;
7208
+ };
7209
+ var resourceWithContext = (resource, context) => {
7210
+ const overrides = {};
7211
+ for (const [key, value] of Object.entries(context)) {
7212
+ if (Object.hasOwn(resource.attributes, key) && !isReservedResourceAttributeKey(key) && resource.attributes[key] !== value) {
7213
+ overrides[key] = value;
7214
+ }
7215
+ }
7216
+ if (Object.keys(overrides).length === 0) {
7217
+ return resource;
7218
+ }
7219
+ return resourceFromAttributes({ ...resource.attributes, ...overrides });
7220
+ };
6899
7221
 
6900
7222
  // src/telemetry/log-records.ts
6901
7223
  import { SeverityNumber, TraceFlags as TraceFlags2 } from "@opentelemetry/api";
@@ -7411,10 +7733,10 @@ var createOtlpLogSink = (options) => {
7411
7733
  const exportRecords = (records) => new Promise((resolve3) => {
7412
7734
  exporter.export([...records], (result) => resolve3(result));
7413
7735
  });
7414
- const toSpoolBatch = (records) => ({
7736
+ const toSpoolBatch = (records, batchResource) => ({
7415
7737
  providerId: options.providerId,
7416
7738
  installationId: options.installationId,
7417
- resourceAttributes: { ...resource.attributes },
7739
+ resourceAttributes: { ...batchResource.attributes },
7418
7740
  instrumentationScope: {
7419
7741
  name: scope.name,
7420
7742
  ...scope.version === void 0 ? {} : { version: scope.version }
@@ -7449,8 +7771,9 @@ var createOtlpLogSink = (options) => {
7449
7771
  return { accepted: 0, rejected: 0, errors: [] };
7450
7772
  }
7451
7773
  const resolved = await resolveCorrelations(events);
7774
+ const batchResource = resourceWithContext(resource, agreedContextAttributes(events));
7452
7775
  const mapped = canonicalEventsToLogRecords(events, {
7453
- resource,
7776
+ resource: batchResource,
7454
7777
  instrumentationScope: scope,
7455
7778
  content,
7456
7779
  correlations: resolved.correlations,
@@ -7485,7 +7808,7 @@ var createOtlpLogSink = (options) => {
7485
7808
  health.recordFailure("telemetry-export-failure", batch.length, options.clock.now());
7486
7809
  const permanent = isPermanentExportFailure(result);
7487
7810
  if (options.spool !== void 0 && !permanent) {
7488
- const spoolResult = await options.spool.enqueue(toSpoolBatch(batch)).catch(() => ({
7811
+ const spoolResult = await options.spool.enqueue(toSpoolBatch(batch, batchResource)).catch(() => ({
7489
7812
  spooled: false,
7490
7813
  reason: "capacity-exceeded"
7491
7814
  }));
@@ -7716,10 +8039,10 @@ var createOtlpMetricSink = (options) => {
7716
8039
  });
7717
8040
  }
7718
8041
  });
7719
- const toSpoolBatch = (points) => ({
8042
+ const toSpoolBatch = (points, batchResource) => ({
7720
8043
  providerId: options.providerId,
7721
8044
  installationId: options.installationId,
7722
- resourceAttributes: { ...resource.attributes },
8045
+ resourceAttributes: { ...batchResource.attributes },
7723
8046
  instrumentationScope: {
7724
8047
  name: scope.name,
7725
8048
  ...scope.version === void 0 ? {} : { version: scope.version }
@@ -7737,11 +8060,12 @@ var createOtlpMetricSink = (options) => {
7737
8060
  }
7738
8061
  return isPermanentExportFailure(result) ? "discard" : false;
7739
8062
  };
7740
- const exportPoints = async (points) => {
8063
+ const exportPoints = async (points, context) => {
7741
8064
  if (points.length === 0) {
7742
8065
  return { accepted: 0, rejected: 0, errors: [] };
7743
8066
  }
7744
- const result = await exportResourceMetrics(points, resource, scope);
8067
+ const batchResource = context === void 0 ? resource : resourceWithContext(resource, context);
8068
+ const result = await exportResourceMetrics(points, batchResource, scope);
7745
8069
  if (result.code === ExportResultCode2.SUCCESS) {
7746
8070
  health.recordSuccess(points.length, options.clock.now());
7747
8071
  return { accepted: points.length, rejected: 0, errors: [] };
@@ -7749,7 +8073,7 @@ var createOtlpMetricSink = (options) => {
7749
8073
  health.recordFailure("telemetry-export-failure", points.length, options.clock.now());
7750
8074
  const permanent = isPermanentExportFailure(result);
7751
8075
  if (options.spool !== void 0 && !permanent) {
7752
- const spooled = await options.spool.enqueue(toSpoolBatch(points)).catch(() => ({
8076
+ const spooled = await options.spool.enqueue(toSpoolBatch(points, batchResource)).catch(() => ({
7753
8077
  spooled: false,
7754
8078
  reason: "capacity-exceeded"
7755
8079
  }));
@@ -7903,10 +8227,10 @@ var createOtlpTraceSink = (options) => {
7903
8227
  const exportSpans = (spans) => new Promise((resolve3) => {
7904
8228
  exporter.export([...spans], (result) => resolve3(result));
7905
8229
  });
7906
- const toSpoolBatch = (spans) => ({
8230
+ const toSpoolBatch = (spans, batchResource) => ({
7907
8231
  providerId: options.providerId,
7908
8232
  installationId: options.installationId,
7909
- resourceAttributes: { ...resource.attributes },
8233
+ resourceAttributes: { ...batchResource.attributes },
7910
8234
  instrumentationScope: { name: scope.name, ...scope.version === void 0 ? {} : { version: scope.version } },
7911
8235
  spans: spans.map(serializeSpan),
7912
8236
  enqueuedAt: options.clock.now()
@@ -7936,8 +8260,9 @@ var createOtlpTraceSink = (options) => {
7936
8260
  return { accepted: 0, rejected: 0, errors: [] };
7937
8261
  }
7938
8262
  const resolved = await resolveCorrelations(events);
8263
+ const batchResource = resourceWithContext(resource, agreedContextAttributes(events));
7939
8264
  const spans = canonicalEventsToReadableSpans(events, {
7940
- resource,
8265
+ resource: batchResource,
7941
8266
  instrumentationScope: scope,
7942
8267
  correlations: resolved.correlations,
7943
8268
  ...resolved.available === void 0 ? {} : { correlationAvailable: resolved.available }
@@ -7963,7 +8288,7 @@ var createOtlpTraceSink = (options) => {
7963
8288
  health.recordFailure("telemetry-export-failure", batch.length, options.clock.now());
7964
8289
  const permanent = isPermanentExportFailure(result);
7965
8290
  if (options.spool !== void 0 && !permanent) {
7966
- const spoolResult = await options.spool.enqueue(toSpoolBatch(batch)).catch(() => ({
8291
+ const spoolResult = await options.spool.enqueue(toSpoolBatch(batch, batchResource)).catch(() => ({
7967
8292
  spooled: false,
7968
8293
  reason: "capacity-exceeded"
7969
8294
  }));
@@ -8372,6 +8697,16 @@ var createHookRuntime = (options) => {
8372
8697
  logger,
8373
8698
  installationId: options.installationId,
8374
8699
  payloadEnrichers: options.payloadEnrichers ?? (readsClaudeTranscriptUsage(options.config) ? [createClaudeTranscriptUsageEnricher()] : []),
8700
+ ...(() => {
8701
+ if (options.sessionContextReader === null) {
8702
+ return {};
8703
+ }
8704
+ if (options.sessionContextReader !== void 0) {
8705
+ return { sessionContext: options.sessionContextReader };
8706
+ }
8707
+ const dir = sessionContextDir(options.config);
8708
+ return dir === void 0 ? {} : { sessionContext: createDirectorySessionContextReader({ dir }) };
8709
+ })(),
8375
8710
  ...options.worktreeLocator === null ? {} : {
8376
8711
  worktreeLocator: options.worktreeLocator ?? createFilesystemWorktreeLocator({ monotonicMillis: () => clock.monotonicMillis() })
8377
8712
  }
@@ -8465,9 +8800,10 @@ var createHookRuntime = (options) => {
8465
8800
  perSession: metricsPolicy.includeSessionId,
8466
8801
  ...deliveryToken === void 0 ? {} : { deliveryToken }
8467
8802
  });
8803
+ const context = agreedContextAttributes(ingest.events);
8468
8804
  const results = await Promise.all(
8469
8805
  metricDestinations.map(async (destination) => {
8470
- const result = await destination.metrics.exportPoints(points).catch(
8806
+ const result = await destination.metrics.exportPoints(points, context).catch(
8471
8807
  (thrown) => ({
8472
8808
  accepted: 0,
8473
8809
  rejected: points.length,