@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
package/dist/cli.js CHANGED
@@ -1,5 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
 
3
+ // src/cli/args.ts
4
+ import { isAbsolute } from "path";
5
+
3
6
  // src/config/resource-attributes.ts
4
7
  import { z as z3 } from "zod";
5
8
 
@@ -334,6 +337,7 @@ var VALUE_FLAGS = /* @__PURE__ */ new Set([
334
337
  "--logs-endpoint",
335
338
  "--metrics-endpoint",
336
339
  "--metrics-temporality",
340
+ "--session-context-dir",
337
341
  "--max-input-bytes",
338
342
  "--scope",
339
343
  "--project-dir",
@@ -534,6 +538,10 @@ var parsePolicy = (tokens, errors) => {
534
538
  errors.push("flag --metrics-temporality must be cumulative or delta");
535
539
  }
536
540
  }
541
+ const sessionContextDir2 = single(tokens, "--session-context-dir", errors);
542
+ if (sessionContextDir2 !== void 0 && !isAbsolute(sessionContextDir2)) {
543
+ errors.push("flag --session-context-dir expects an absolute path");
544
+ }
537
545
  return {
538
546
  ...configFile === void 0 ? {} : { configFile },
539
547
  ...endpoint === void 0 ? {} : { endpoint },
@@ -558,7 +566,8 @@ var parsePolicy = (tokens, errors) => {
558
566
  ...metricsEndpoint === void 0 ? {} : { metricsEndpoint },
559
567
  ...metricsTemporality === void 0 ? {} : { metricsTemporality },
560
568
  ...tokens.booleans.has("--no-metrics-session-id") ? { metricsIncludeSessionId: false } : {},
561
- ...tokens.booleans.has("--claude-transcript-usage") ? { claudeTranscriptUsage: true } : {}
569
+ ...tokens.booleans.has("--claude-transcript-usage") ? { claudeTranscriptUsage: true } : {},
570
+ ...sessionContextDir2 === void 0 || !isAbsolute(sessionContextDir2) ? {} : { sessionContextDir: sessionContextDir2 }
562
571
  };
563
572
  };
564
573
  var parseIdentity = (tokens, errors) => {
@@ -619,6 +628,7 @@ var RUN_FLAGS = /* @__PURE__ */ new Set([
619
628
  "--metrics-temporality",
620
629
  "--no-metrics-session-id",
621
630
  "--claude-transcript-usage",
631
+ "--session-context-dir",
622
632
  "--max-input-bytes",
623
633
  "--no-export",
624
634
  "--no-spool",
@@ -654,6 +664,7 @@ var DOCTOR_FLAGS = /* @__PURE__ */ new Set([
654
664
  "--metrics-temporality",
655
665
  "--no-metrics-session-id",
656
666
  "--claude-transcript-usage",
667
+ "--session-context-dir",
657
668
  "--include-experimental",
658
669
  "--no-experimental"
659
670
  ]);
@@ -910,6 +921,13 @@ Exporter and runtime policy (never identity):
910
921
  payload names (bounded) for the turn's model and
911
922
  summed token usage. Off by default; also
912
923
  OTEL_HOOK_CLAUDE_TRANSCRIPT_USAGE=1
924
+ --session-context-dir <dir>
925
+ absolute directory of session context files
926
+ (<dir>/<agent-tool>/<session-id>.json); the
927
+ attributes of the segment in force are put on
928
+ every span, log record and metric point. Overrides
929
+ sessionContext.dir in --config-file. No environment
930
+ variable, by design
913
931
  --max-input-bytes <n> stdin bound (default 1048576)
914
932
  --attr <key=value> opaque consumer attribute for this invocation,
915
933
  carried unchanged (not a resource attribute)
@@ -1828,6 +1846,7 @@ var describeExportDestinations = (exporter) => {
1828
1846
  };
1829
1847
 
1830
1848
  // src/config/schema.ts
1849
+ import { isAbsolute as isAbsolute2 } from "path";
1831
1850
  import { z as z7 } from "zod";
1832
1851
  var logsPolicySchema = z7.strictObject({
1833
1852
  enabled: z7.boolean(),
@@ -1929,13 +1948,19 @@ var providersPolicySchema = z7.strictObject({
1929
1948
  readTranscriptUsage: z7.boolean()
1930
1949
  }).optional()
1931
1950
  });
1951
+ var sessionContextPolicySchema = z7.strictObject({
1952
+ /** Absolute path of the context directory. */
1953
+ dir: z7.string().min(1).max(4096).refine((value) => isAbsolute2(value), { message: "must be an absolute path" })
1954
+ });
1932
1955
  var otelHookConfigSchema = z7.strictObject({
1933
1956
  exporter: exporterPolicySchema,
1934
1957
  privacy: privacyPolicySchema,
1935
1958
  detection: detectionPolicySchema,
1936
1959
  diagnostics: diagnosticsPolicySchema,
1937
1960
  /** Optional so a hand-built configuration from before it existed stays valid. */
1938
- providers: providersPolicySchema.optional()
1961
+ providers: providersPolicySchema.optional(),
1962
+ /** Optional: absent means no session context is read. */
1963
+ sessionContext: sessionContextPolicySchema.optional()
1939
1964
  });
1940
1965
  var otelHookConfigPatchSchema = z7.strictObject({
1941
1966
  // `logs` is unwrapped and re-partialled for the same reason `privacy.limits` is:
@@ -1951,7 +1976,8 @@ var otelHookConfigPatchSchema = z7.strictObject({
1951
1976
  diagnostics: diagnosticsPolicySchema.partial().optional(),
1952
1977
  providers: z7.strictObject({
1953
1978
  claudeCode: z7.strictObject({ readTranscriptUsage: z7.boolean() }).partial().optional()
1954
- }).partial().optional()
1979
+ }).partial().optional(),
1980
+ sessionContext: sessionContextPolicySchema.partial().optional()
1955
1981
  });
1956
1982
  var DEFAULT_EXPORTER_POLICY = Object.freeze({
1957
1983
  enabled: true,
@@ -1986,6 +2012,7 @@ var DEFAULT_CONFIG = Object.freeze({
1986
2012
  providers: DEFAULT_PROVIDERS_POLICY
1987
2013
  });
1988
2014
  var readsClaudeTranscriptUsage = (config) => config.providers?.claudeCode?.readTranscriptUsage === true;
2015
+ var sessionContextDir = (config) => config.sessionContext?.dir;
1989
2016
  var effectiveMetricsPolicy = (exporter) => ({
1990
2017
  ...DEFAULT_METRICS_POLICY,
1991
2018
  ...exporter.metrics ?? {}
@@ -1995,12 +2022,12 @@ var effectiveMetricsPolicy = (exporter) => ({
1995
2022
  var CONFIG_SOURCE_PRECEDENCE = ["defaults", "file", "environment", "inline-override"];
1996
2023
  var configSourceSchema = z8.enum(CONFIG_SOURCE_PRECEDENCE);
1997
2024
  var isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1998
- var mergeLeaf = (target, patch, source, provenance, path14) => {
2025
+ var mergeLeaf = (target, patch, source, provenance, path15) => {
1999
2026
  for (const [key, value] of Object.entries(patch)) {
2000
2027
  if (value === void 0) {
2001
2028
  continue;
2002
2029
  }
2003
- const childPath = path14 === "" ? key : `${path14}.${key}`;
2030
+ const childPath = path15 === "" ? key : `${path15}.${key}`;
2004
2031
  const existing = target[key];
2005
2032
  if (isPlainObject(value) && (isPlainObject(existing) || existing === void 0)) {
2006
2033
  const child = { ...existing ?? {} };
@@ -2014,14 +2041,14 @@ var mergeLeaf = (target, patch, source, provenance, path14) => {
2014
2041
  };
2015
2042
  var initialProvenance = (config) => {
2016
2043
  const provenance = {};
2017
- const walk = (value, path14) => {
2044
+ const walk = (value, path15) => {
2018
2045
  if (isPlainObject(value)) {
2019
2046
  for (const [key, child] of Object.entries(value)) {
2020
- walk(child, path14 === "" ? key : `${path14}.${key}`);
2047
+ walk(child, path15 === "" ? key : `${path15}.${key}`);
2021
2048
  }
2022
2049
  return;
2023
2050
  }
2024
- provenance[path14] = "defaults";
2051
+ provenance[path15] = "defaults";
2025
2052
  };
2026
2053
  walk(config, "");
2027
2054
  return provenance;
@@ -2192,7 +2219,9 @@ var describeResolvedConfig = (config) => {
2192
2219
  "detection.minimum_confidence": config.detection.minimumConfidence,
2193
2220
  "detection.allow_ambiguous_fallback": config.detection.allowAmbiguousFallback,
2194
2221
  "diagnostics.log_level": config.diagnostics.logLevel,
2195
- "diagnostics.emit_error_events": config.diagnostics.emitErrorEvents
2222
+ "diagnostics.emit_error_events": config.diagnostics.emitErrorEvents,
2223
+ // Whether, never where: the directory is a local path.
2224
+ "session_context.enabled": config.sessionContext?.dir !== void 0
2196
2225
  };
2197
2226
  };
2198
2227
 
@@ -2762,7 +2791,15 @@ var baseEventFields = {
2762
2791
  * factory, never by hand.
2763
2792
  */
2764
2793
  subagentId: subagentIdSchema.optional(),
2765
- extensions: extensionsSchema.default(emptyExtensions)
2794
+ extensions: extensionsSchema.default(emptyExtensions),
2795
+ /**
2796
+ * Attributes of the session context segment in force when the event
2797
+ * occurred (`docs/session-context.md`), stamped by the core from a file a
2798
+ * harness wrote. Exported on every record of the event, over the same keys
2799
+ * from the Resource. Absent when no context applies. Set by the core only,
2800
+ * never by an adapter.
2801
+ */
2802
+ contextAttributes: z15.record(z15.string().min(1).max(255), z15.union([z15.string(), z15.number(), z15.boolean()])).optional()
2766
2803
  };
2767
2804
  var event = (shape) => z15.strictObject({ ...baseEventFields, ...shape });
2768
2805
  var sessionStartEventSchema = event({
@@ -3091,7 +3128,8 @@ var policyFlagsToPatch = (policy) => {
3091
3128
  ...Object.keys(exporter).length === 0 ? {} : { exporter },
3092
3129
  ...Object.keys(privacy).length === 0 ? {} : { privacy },
3093
3130
  ...Object.keys(diagnostics).length === 0 ? {} : { diagnostics },
3094
- ...policy.claudeTranscriptUsage === true ? { providers: { claudeCode: { readTranscriptUsage: true } } } : {}
3131
+ ...policy.claudeTranscriptUsage === true ? { providers: { claudeCode: { readTranscriptUsage: true } } } : {},
3132
+ ...policy.sessionContextDir === void 0 ? {} : { sessionContext: { dir: policy.sessionContextDir } }
3095
3133
  };
3096
3134
  };
3097
3135
  var resolveCliExporterHeaders = (policy, io) => {
@@ -3180,7 +3218,7 @@ var createCliLogger = (io, level) => createStderrLogger({
3180
3218
  var readIdentityFile = readJsonFile;
3181
3219
 
3182
3220
  // src/cli/doctor.ts
3183
- import { readdir as readdir3 } from "fs/promises";
3221
+ import { readdir as readdir3, stat as stat2 } from "fs/promises";
3184
3222
  import * as path4 from "path";
3185
3223
 
3186
3224
  // src/diagnostics/health.ts
@@ -3445,11 +3483,11 @@ var createPrivacyService = (policyInput) => {
3445
3483
  };
3446
3484
  const flattenToAttributes = (value, prefix) => {
3447
3485
  const attributes = {};
3448
- const walk = (current, path14) => {
3486
+ const walk = (current, path15) => {
3449
3487
  if (typeof current === "string" || typeof current === "number" || typeof current === "boolean") {
3450
3488
  const primitive = toAttributePrimitive(current);
3451
3489
  if (primitive !== void 0) {
3452
- attributes[path14] = primitive;
3490
+ attributes[path15] = primitive;
3453
3491
  }
3454
3492
  return;
3455
3493
  }
@@ -3468,16 +3506,16 @@ var createPrivacyService = (policyInput) => {
3468
3506
  primitives.push(entryPrimitive);
3469
3507
  }
3470
3508
  if (uniform) {
3471
- attributes[path14] = primitives.slice(0, MAX_ATTRIBUTE_ARRAY_LENGTH);
3509
+ attributes[path15] = primitives.slice(0, MAX_ATTRIBUTE_ARRAY_LENGTH);
3472
3510
  return;
3473
3511
  }
3474
3512
  for (const [index, entry] of current.entries()) {
3475
- walk(entry, `${path14}.${index}`);
3513
+ walk(entry, `${path15}.${index}`);
3476
3514
  }
3477
3515
  return;
3478
3516
  }
3479
3517
  for (const [key, entry] of Object.entries(current)) {
3480
- walk(entry, path14 === "" ? key : `${path14}.${key}`);
3518
+ walk(entry, path15 === "" ? key : `${path15}.${key}`);
3481
3519
  }
3482
3520
  };
3483
3521
  walk(value, prefix);
@@ -3777,6 +3815,7 @@ var createEventFactory = (input) => {
3777
3815
  const rest = { ...drafted };
3778
3816
  delete rest.target;
3779
3817
  delete rest.subagentId;
3818
+ delete rest.contextAttributes;
3780
3819
  const sanitized = extensions === void 0 ? { extensions: {}, droppedKeys: [] } : context.privacy.sanitizeExtensions(extensions);
3781
3820
  dropped.push(...sanitized.droppedKeys);
3782
3821
  const currentSequence = sequence;
@@ -4228,7 +4267,16 @@ var subagentStopPayloadSchema = z19.object({
4228
4267
  last_assistant_message: z19.string().optional(),
4229
4268
  /** True when this stop fired because a hook continued the subagent's turn. */
4230
4269
  stop_hook_active: z19.boolean().optional(),
4231
- usage: claudeUsageSchema.optional()
4270
+ /**
4271
+ * The subagent run's tokens since its previous stop — harness- or
4272
+ * enricher-supplied, never upstream. Reported on the subagent's own
4273
+ * generation, never on the parent turn (issue #68).
4274
+ */
4275
+ usage: claudeUsageSchema.optional(),
4276
+ /** Harness-supplied, never upstream: the subagent's model, from its transcript. */
4277
+ model: z19.string().min(1).max(256).optional().catch(void 0),
4278
+ /** Harness-supplied, never upstream: see `stopPayloadSchema.usage_partial`. */
4279
+ usage_partial: z19.boolean().optional().catch(void 0)
4232
4280
  });
4233
4281
  var preCompactPayloadSchema = z19.object({
4234
4282
  ...commonFields2,
@@ -4826,6 +4874,8 @@ var BUILT_IN_TOOL_KIND = Object.freeze({
4826
4874
  WebFetch: "network",
4827
4875
  WebSearch: "network",
4828
4876
  Task: "delegate",
4877
+ // Current Claude Code releases (observed on 2.1.332) name the subagent tool `Agent`.
4878
+ Agent: "delegate",
4829
4879
  TodoWrite: "other",
4830
4880
  ExitPlanMode: "other",
4831
4881
  AskUserQuestion: "other",
@@ -4999,14 +5049,39 @@ var parseClaudeCode = (input, context) => {
4999
5049
  delegationDepth: 1
5000
5050
  });
5001
5051
  break;
5002
- case "SubagentStop":
5052
+ case "SubagentStop": {
5053
+ const usage = withPartialUsage(extractedUsage ?? payload.usage, payload.usage_partial);
5054
+ if (usage.usage !== void 0 || payload.model !== void 0) {
5055
+ const generationId = context.ids.newOpaqueId([
5056
+ "claude-subagent-generation",
5057
+ payload.session_id,
5058
+ payload.agent_id,
5059
+ ...payload.stop_hook_active === true ? [String(input.sequenceBase)] : []
5060
+ ]);
5061
+ const models = generationModels(payload.model, void 0);
5062
+ factory.build({ type: "generation.start", generationId, model: models.request });
5063
+ factory.build({
5064
+ type: "generation.end",
5065
+ generationId,
5066
+ model: models.response,
5067
+ outcome: "ok",
5068
+ outputContent: [
5069
+ payload.last_assistant_message === void 0 ? context.privacy.describeUnavailableContent({ kind: "response", role: "assistant" }) : context.privacy.describeContent({
5070
+ kind: "response",
5071
+ role: "assistant",
5072
+ text: payload.last_assistant_message
5073
+ })
5074
+ ],
5075
+ ...usage
5076
+ });
5077
+ }
5003
5078
  factory.build({
5004
5079
  type: "subagent.end",
5005
5080
  subagentInvocationId: subagentInvocationIdFor(context, payload.session_id, payload.agent_id),
5006
- outcome: "ok",
5007
- ...withUsage(payload.usage)
5081
+ outcome: "ok"
5008
5082
  });
5009
5083
  break;
5084
+ }
5010
5085
  case "PreCompact":
5011
5086
  return {
5012
5087
  status: "ignored",
@@ -8508,6 +8583,33 @@ var replayResource = (attributes, policy) => {
8508
8583
  }
8509
8584
  return resourceFromAttributes(safe);
8510
8585
  };
8586
+ var agreedContextAttributes = (events) => {
8587
+ const [first, ...rest] = events;
8588
+ if (first?.contextAttributes === void 0) {
8589
+ return {};
8590
+ }
8591
+ const agreed = { ...first.contextAttributes };
8592
+ for (const event3 of rest) {
8593
+ for (const key of Object.keys(agreed)) {
8594
+ if (event3.contextAttributes?.[key] !== agreed[key]) {
8595
+ delete agreed[key];
8596
+ }
8597
+ }
8598
+ }
8599
+ return agreed;
8600
+ };
8601
+ var resourceWithContext = (resource, context) => {
8602
+ const overrides = {};
8603
+ for (const [key, value] of Object.entries(context)) {
8604
+ if (Object.hasOwn(resource.attributes, key) && !isReservedResourceAttributeKey(key) && resource.attributes[key] !== value) {
8605
+ overrides[key] = value;
8606
+ }
8607
+ }
8608
+ if (Object.keys(overrides).length === 0) {
8609
+ return resource;
8610
+ }
8611
+ return resourceFromAttributes({ ...resource.attributes, ...overrides });
8612
+ };
8511
8613
 
8512
8614
  // src/telemetry/log-records.ts
8513
8615
  import { SeverityNumber, TraceFlags as TraceFlags2 } from "@opentelemetry/api";
@@ -8577,6 +8679,11 @@ var passthroughResourceAttributes = (resource) => {
8577
8679
  }
8578
8680
  return attributes;
8579
8681
  };
8682
+ var contextAttributesOf = (event3) => event3.contextAttributes === void 0 ? {} : { ...event3.contextAttributes };
8683
+ var profileAttributes = (event3, resource) => ({
8684
+ ...passthroughResourceAttributes(resource),
8685
+ ...contextAttributesOf(event3)
8686
+ });
8580
8687
  var resolveExportedSessionId = (eventSessionId, resource) => {
8581
8688
  for (const key of EXTERNAL_SESSION_KEY_ATTRIBUTES) {
8582
8689
  const supplied = resource.attributes[key];
@@ -8597,6 +8704,8 @@ var hexTraceAttributes = (ids) => ({
8597
8704
  var exportIdentityAttributes = (event3, resource, ids) => {
8598
8705
  const { sessionId, providerSessionId } = resolveExportedSessionId(event3.sessionId, resource);
8599
8706
  return {
8707
+ // First, so nothing in the profile layer can replace an identity attribute.
8708
+ ...profileAttributes(event3, resource),
8600
8709
  [ATTR_SESSION_ID]: sessionId,
8601
8710
  [ATTR_OTELHOOK_SESSION_ID]: providerSessionId,
8602
8711
  [ATTR_GEN_AI_CONVERSATION_ID]: providerSessionId,
@@ -8605,7 +8714,6 @@ var exportIdentityAttributes = (event3, resource, ids) => {
8605
8714
  ...event3.provenance.providerVersion === void 0 ? {} : { [ATTR_OTELHOOK_PROVIDER_VERSION]: event3.provenance.providerVersion },
8606
8715
  [ATTR_OTELHOOK_WORKSPACE_ID]: event3.workspace.workspaceId,
8607
8716
  ...event3.subagentId === void 0 ? {} : { [ATTR_OTELHOOK_SUBAGENT_ID]: event3.subagentId },
8608
- ...passthroughResourceAttributes(resource),
8609
8717
  ...hexTraceAttributes(ids)
8610
8718
  };
8611
8719
  };
@@ -8630,7 +8738,7 @@ import {
8630
8738
  } from "@opentelemetry/semantic-conventions/incubating";
8631
8739
 
8632
8740
  // src/version.ts
8633
- var VERSION = "0.11.0";
8741
+ var VERSION = "0.13.0";
8634
8742
 
8635
8743
  // src/telemetry/semconv.ts
8636
8744
  var SCOPE_NAME = "@osfactory/otel-hook";
@@ -8778,12 +8886,12 @@ var pickTarget = (attributes) => {
8778
8886
  }
8779
8887
  return picked;
8780
8888
  };
8781
- var withoutTarget = (attributes, resource) => {
8889
+ var withoutTarget = (attributes, resource, event3) => {
8782
8890
  const rest = { ...attributes };
8783
8891
  for (const key of TARGET_KEYS) {
8784
8892
  delete rest[key];
8785
8893
  }
8786
- return { ...rest, ...pickTarget(passthroughResourceAttributes(resource)) };
8894
+ return { ...rest, ...pickTarget(profileAttributes(event3, resource)) };
8787
8895
  };
8788
8896
  var rankOf = (candidate) => {
8789
8897
  const source = candidate[ATTR_OTELHOOK_TARGET_SOURCE];
@@ -8888,7 +8996,7 @@ var buildLifecycleSpan = (plan, resource, scope) => {
8888
8996
  name = "session";
8889
8997
  kind = SpanKind.INTERNAL;
8890
8998
  attributes = {
8891
- ...withoutTarget(attributes, resource),
8999
+ ...withoutTarget(attributes, resource, anchor),
8892
9000
  ...strongestTarget([pickTarget(resolved.recovered), start === void 0 ? {} : targetAttributes(start)]),
8893
9001
  ...start?.agentName === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_NAME]: start.agentName },
8894
9002
  ...start?.agentVersion === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_VERSION]: start.agentVersion },
@@ -8930,7 +9038,7 @@ var buildLifecycleSpan = (plan, resource, scope) => {
8930
9038
  kind = SpanKind.CLIENT;
8931
9039
  attributes = {
8932
9040
  // Target keys are re-chosen below as one unit, never mixed across edges.
8933
- ...withoutTarget(attributes, resource),
9041
+ ...withoutTarget(attributes, resource, anchor),
8934
9042
  [ATTR_GEN_AI_TOOL_NAME]: toolName,
8935
9043
  [ATTR_GEN_AI_TOOL_CALL_ID]: start?.toolCallId ?? end?.toolCallId ?? group.ref.scopeKey,
8936
9044
  ...start?.toolKind === void 0 ? {} : { [ATTR_OTELHOOK_TOOL_KIND]: start.toolKind },
@@ -9660,10 +9768,10 @@ var createOtlpLogSink = (options) => {
9660
9768
  const exportRecords = (records) => new Promise((resolve8) => {
9661
9769
  exporter.export([...records], (result) => resolve8(result));
9662
9770
  });
9663
- const toSpoolBatch = (records) => ({
9771
+ const toSpoolBatch = (records, batchResource) => ({
9664
9772
  providerId: options.providerId,
9665
9773
  installationId: options.installationId,
9666
- resourceAttributes: { ...resource.attributes },
9774
+ resourceAttributes: { ...batchResource.attributes },
9667
9775
  instrumentationScope: {
9668
9776
  name: scope.name,
9669
9777
  ...scope.version === void 0 ? {} : { version: scope.version }
@@ -9698,8 +9806,9 @@ var createOtlpLogSink = (options) => {
9698
9806
  return { accepted: 0, rejected: 0, errors: [] };
9699
9807
  }
9700
9808
  const resolved = await resolveCorrelations(events);
9809
+ const batchResource = resourceWithContext(resource, agreedContextAttributes(events));
9701
9810
  const mapped = canonicalEventsToLogRecords(events, {
9702
- resource,
9811
+ resource: batchResource,
9703
9812
  instrumentationScope: scope,
9704
9813
  content,
9705
9814
  correlations: resolved.correlations,
@@ -9734,7 +9843,7 @@ var createOtlpLogSink = (options) => {
9734
9843
  health.recordFailure("telemetry-export-failure", batch.length, options.clock.now());
9735
9844
  const permanent = isPermanentExportFailure(result);
9736
9845
  if (options.spool !== void 0 && !permanent) {
9737
- const spoolResult = await options.spool.enqueue(toSpoolBatch(batch)).catch(() => ({
9846
+ const spoolResult = await options.spool.enqueue(toSpoolBatch(batch, batchResource)).catch(() => ({
9738
9847
  spooled: false,
9739
9848
  reason: "capacity-exceeded"
9740
9849
  }));
@@ -9887,10 +9996,10 @@ var createOtlpTraceSink = (options) => {
9887
9996
  const exportSpans = (spans) => new Promise((resolve8) => {
9888
9997
  exporter.export([...spans], (result) => resolve8(result));
9889
9998
  });
9890
- const toSpoolBatch = (spans) => ({
9999
+ const toSpoolBatch = (spans, batchResource) => ({
9891
10000
  providerId: options.providerId,
9892
10001
  installationId: options.installationId,
9893
- resourceAttributes: { ...resource.attributes },
10002
+ resourceAttributes: { ...batchResource.attributes },
9894
10003
  instrumentationScope: { name: scope.name, ...scope.version === void 0 ? {} : { version: scope.version } },
9895
10004
  spans: spans.map(serializeSpan),
9896
10005
  enqueuedAt: options.clock.now()
@@ -9920,8 +10029,9 @@ var createOtlpTraceSink = (options) => {
9920
10029
  return { accepted: 0, rejected: 0, errors: [] };
9921
10030
  }
9922
10031
  const resolved = await resolveCorrelations(events);
10032
+ const batchResource = resourceWithContext(resource, agreedContextAttributes(events));
9923
10033
  const spans = canonicalEventsToReadableSpans(events, {
9924
- resource,
10034
+ resource: batchResource,
9925
10035
  instrumentationScope: scope,
9926
10036
  correlations: resolved.correlations,
9927
10037
  ...resolved.available === void 0 ? {} : { correlationAvailable: resolved.available }
@@ -9947,7 +10057,7 @@ var createOtlpTraceSink = (options) => {
9947
10057
  health.recordFailure("telemetry-export-failure", batch.length, options.clock.now());
9948
10058
  const permanent = isPermanentExportFailure(result);
9949
10059
  if (options.spool !== void 0 && !permanent) {
9950
- const spoolResult = await options.spool.enqueue(toSpoolBatch(batch)).catch(() => ({
10060
+ const spoolResult = await options.spool.enqueue(toSpoolBatch(batch, batchResource)).catch(() => ({
9951
10061
  spooled: false,
9952
10062
  reason: "capacity-exceeded"
9953
10063
  }));
@@ -10099,6 +10209,9 @@ var ATTR_OTELHOOK_PROVIDER_ID2 = "otelhook.provider.id";
10099
10209
  var ATTR_OTELHOOK_OUTCOME3 = "otelhook.outcome";
10100
10210
  var ATTR_OTELHOOK_SESSION_KIND2 = "otelhook.session.kind";
10101
10211
  var commonAttributes = (event3, resource, includeSessionId) => ({
10212
+ // Session context first, so the metric's own attributes always win; and never
10213
+ // anything account-shaped, whatever the context says.
10214
+ ...event3.contextAttributes === void 0 ? {} : withoutAccountIdentity(event3.contextAttributes),
10102
10215
  [ATTR_OTELHOOK_PROVIDER_ID2]: event3.provenance.providerId,
10103
10216
  ...includeSessionId ? { [ATTR_SESSION_ID2]: resolveExportedSessionId(event3.sessionId, resource).sessionId } : {}
10104
10217
  });
@@ -10145,6 +10258,9 @@ var deriveMetricObservations = (input) => {
10145
10258
  if (recovered !== void 0) {
10146
10259
  return end.occurredAt - recovered.startMillis;
10147
10260
  }
10261
+ if (end.subagentId !== void 0) {
10262
+ return void 0;
10263
+ }
10148
10264
  const turn = lastPromptInBatch?.get(end.sessionId) ?? input.turnStart?.(end.sessionId);
10149
10265
  return turn === void 0 || turn > end.occurredAt ? void 0 : end.occurredAt - turn;
10150
10266
  };
@@ -10521,10 +10637,10 @@ var createOtlpMetricSink = (options) => {
10521
10637
  });
10522
10638
  }
10523
10639
  });
10524
- const toSpoolBatch = (points) => ({
10640
+ const toSpoolBatch = (points, batchResource) => ({
10525
10641
  providerId: options.providerId,
10526
10642
  installationId: options.installationId,
10527
- resourceAttributes: { ...resource.attributes },
10643
+ resourceAttributes: { ...batchResource.attributes },
10528
10644
  instrumentationScope: {
10529
10645
  name: scope.name,
10530
10646
  ...scope.version === void 0 ? {} : { version: scope.version }
@@ -10542,11 +10658,12 @@ var createOtlpMetricSink = (options) => {
10542
10658
  }
10543
10659
  return isPermanentExportFailure(result) ? "discard" : false;
10544
10660
  };
10545
- const exportPoints = async (points) => {
10661
+ const exportPoints = async (points, context) => {
10546
10662
  if (points.length === 0) {
10547
10663
  return { accepted: 0, rejected: 0, errors: [] };
10548
10664
  }
10549
- const result = await exportResourceMetrics(points, resource, scope);
10665
+ const batchResource = context === void 0 ? resource : resourceWithContext(resource, context);
10666
+ const result = await exportResourceMetrics(points, batchResource, scope);
10550
10667
  if (result.code === ExportResultCode3.SUCCESS) {
10551
10668
  health.recordSuccess(points.length, options.clock.now());
10552
10669
  return { accepted: points.length, rejected: 0, errors: [] };
@@ -10554,7 +10671,7 @@ var createOtlpMetricSink = (options) => {
10554
10671
  health.recordFailure("telemetry-export-failure", points.length, options.clock.now());
10555
10672
  const permanent = isPermanentExportFailure(result);
10556
10673
  if (options.spool !== void 0 && !permanent) {
10557
- const spooled = await options.spool.enqueue(toSpoolBatch(points)).catch(() => ({
10674
+ const spooled = await options.spool.enqueue(toSpoolBatch(points, batchResource)).catch(() => ({
10558
10675
  spooled: false,
10559
10676
  reason: "capacity-exceeded"
10560
10677
  }));
@@ -10970,6 +11087,20 @@ var collectDoctorReport = async (command, io) => {
10970
11087
  ok: resolved.config.privacy.contentMode === "omit" || resolved.config.privacy.allowRawContent,
10971
11088
  detail: `content mode is "${privacy.policy.contentMode}"${privacy.policyNotes.length === 0 ? "" : `; ${privacy.policyNotes.join("; ")}`}`
10972
11089
  });
11090
+ const contextDir = resolved.config.sessionContext?.dir;
11091
+ let contextDirExists = false;
11092
+ if (contextDir !== void 0) {
11093
+ try {
11094
+ contextDirExists = (await stat2(contextDir)).isDirectory();
11095
+ } catch {
11096
+ contextDirExists = false;
11097
+ }
11098
+ }
11099
+ checks.push({
11100
+ name: "session-context",
11101
+ ok: true,
11102
+ detail: contextDir === void 0 ? "off (sessionContext.dir is not set)" : `reading ${path4.join(contextDir, "<agent-tool>", "<session-id>.json")}${contextDirExists ? "" : " (directory does not exist yet; nothing is stamped until it does)"}`
11103
+ });
10973
11104
  const providers = describeProviderCatalog({
10974
11105
  includeExperimental: command.policy.includeExperimental ?? true
10975
11106
  });
@@ -12086,7 +12217,7 @@ var resolveInstallPath = (location, roots) => path5.resolve(
12086
12217
 
12087
12218
  // src/install/document.ts
12088
12219
  import { randomBytes as randomBytes3 } from "crypto";
12089
- import { chmod, mkdir as mkdir3, open as open2, readFile as readFile4, rename as rename3, stat as stat2, unlink as unlink3 } from "fs/promises";
12220
+ import { chmod, mkdir as mkdir3, open as open2, readFile as readFile4, rename as rename3, stat as stat3, unlink as unlink3 } from "fs/promises";
12090
12221
  import * as path6 from "path";
12091
12222
  var DEFAULT_DOCUMENT_FORMAT = Object.freeze({
12092
12223
  indent: " ",
@@ -12166,7 +12297,7 @@ var writeDocumentAtomically = async (filePath, contents) => {
12166
12297
  );
12167
12298
  let existingMode;
12168
12299
  try {
12169
- existingMode = (await stat2(filePath)).mode & 4095;
12300
+ existingMode = (await stat3(filePath)).mode & 4095;
12170
12301
  } catch (thrown) {
12171
12302
  if (!isErrnoException3(thrown, "ENOENT")) {
12172
12303
  throw thrown;
@@ -12191,7 +12322,7 @@ var writeDocumentAtomically = async (filePath, contents) => {
12191
12322
 
12192
12323
  // src/install/file-lock.ts
12193
12324
  import { randomBytes as randomBytes4 } from "crypto";
12194
- import { mkdir as mkdir4, open as open3, readFile as readFile5, rename as rename4, stat as stat3, unlink as unlink4 } from "fs/promises";
12325
+ import { mkdir as mkdir4, open as open3, readFile as readFile5, rename as rename4, stat as stat4, unlink as unlink4 } from "fs/promises";
12195
12326
  import * as path7 from "path";
12196
12327
  var FileLockTimeoutError = class extends Error {
12197
12328
  constructor(lockPath, timeoutMillis) {
@@ -12256,7 +12387,7 @@ var isStale = async (lockPath, clock, staleMillis) => {
12256
12387
  } catch {
12257
12388
  }
12258
12389
  try {
12259
- const stats = await stat3(lockPath);
12390
+ const stats = await stat4(lockPath);
12260
12391
  return { stale: clock.now() - stats.mtimeMs > staleMillis };
12261
12392
  } catch (thrown) {
12262
12393
  return { stale: !isErrnoException4(thrown, "ENOENT") };
@@ -12746,7 +12877,7 @@ var runRegistrationCommand = async (command, io) => {
12746
12877
  };
12747
12878
 
12748
12879
  // src/cli/run.ts
12749
- import * as path13 from "path";
12880
+ import * as path14 from "path";
12750
12881
 
12751
12882
  // src/lifecycle/dedup.ts
12752
12883
  import { randomBytes as randomBytes5 } from "crypto";
@@ -13632,7 +13763,7 @@ var createUsageAccumulator = (deps) => {
13632
13763
 
13633
13764
  // src/providers/claude/transcript.ts
13634
13765
  import { createHash as createHash5 } from "crypto";
13635
- import { open as open4, stat as stat4 } from "fs/promises";
13766
+ import { open as open4, stat as stat5 } from "fs/promises";
13636
13767
  import path10 from "path";
13637
13768
  var DEFAULT_CLAUDE_TRANSCRIPT_TAIL_BYTES = 1048576;
13638
13769
  var DEFAULT_CLAUDE_TRANSCRIPT_TIMEOUT_MILLIS = 250;
@@ -13655,7 +13786,8 @@ var clamp = (value, fallback, min, max) => {
13655
13786
  };
13656
13787
  var asRecord7 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
13657
13788
  var isTranscriptPath = (transcriptPath) => typeof transcriptPath === "string" && transcriptPath.length > 0 && !transcriptPath.includes("\0") && path10.isAbsolute(transcriptPath) && path10.extname(transcriptPath) === ".jsonl";
13658
- var assistantRecordOf = (line) => {
13789
+ var isRecordOfAgent = (record, agentId) => record.isSidechain === true && (typeof record.agentId !== "string" || record.agentId === agentId);
13790
+ var assistantRecordOf = (line, agentId) => {
13659
13791
  if (!line.includes('"assistant"')) {
13660
13792
  return void 0;
13661
13793
  }
@@ -13666,7 +13798,10 @@ var assistantRecordOf = (line) => {
13666
13798
  return void 0;
13667
13799
  }
13668
13800
  const record = asRecord7(parsed);
13669
- if (record === void 0 || record.type !== "assistant" || record.isSidechain === true) {
13801
+ if (record === void 0 || record.type !== "assistant") {
13802
+ return void 0;
13803
+ }
13804
+ if (agentId === void 0 ? record.isSidechain === true : !isRecordOfAgent(record, agentId)) {
13670
13805
  return void 0;
13671
13806
  }
13672
13807
  const message = asRecord7(record.message);
@@ -13721,7 +13856,7 @@ var withTimeout = async (work, timeoutMillis, onError) => {
13721
13856
  var withRegularFile = async (transcriptPath, body) => {
13722
13857
  let info;
13723
13858
  try {
13724
- info = await stat4(transcriptPath);
13859
+ info = await stat5(transcriptPath);
13725
13860
  } catch {
13726
13861
  return { status: "unavailable", reason: "unreadable" };
13727
13862
  }
@@ -13759,7 +13894,7 @@ var completeLinesEnd = (bytes, start) => {
13759
13894
  const lastNewline = bytes.lastIndexOf(10);
13760
13895
  return lastNewline < 0 ? start : start + lastNewline + 1;
13761
13896
  };
13762
- var readTail = (transcriptPath, maxTailBytes) => withRegularFile(transcriptPath, async (handle, size) => {
13897
+ var readTail = (transcriptPath, maxTailBytes, agentId) => withRegularFile(transcriptPath, async (handle, size) => {
13763
13898
  const length = Math.min(size, maxTailBytes);
13764
13899
  const start = size - length;
13765
13900
  const bytes = await readBytes(handle, start, length);
@@ -13769,7 +13904,7 @@ var readTail = (transcriptPath, maxTailBytes) => withRegularFile(transcriptPath,
13769
13904
  lines.shift();
13770
13905
  }
13771
13906
  for (let index = lines.length - 1; index >= 0; index -= 1) {
13772
- const record = assistantRecordOf((lines[index] ?? "").trim());
13907
+ const record = assistantRecordOf((lines[index] ?? "").trim(), agentId);
13773
13908
  if (record !== void 0) {
13774
13909
  return {
13775
13910
  turn: {
@@ -13783,10 +13918,11 @@ var readTail = (transcriptPath, maxTailBytes) => withRegularFile(transcriptPath,
13783
13918
  }
13784
13919
  return { turn: { status: "unavailable", reason: "no-assistant-message" }, endOffset };
13785
13920
  });
13786
- var boundedTail = async (transcriptPath, options) => withTimeout(
13921
+ var boundedTail = async (transcriptPath, options, agentId) => withTimeout(
13787
13922
  readTail(
13788
13923
  transcriptPath,
13789
- clamp(options.maxTailBytes, DEFAULT_CLAUDE_TRANSCRIPT_TAIL_BYTES, MIN_TAIL_BYTES, MAX_TAIL_BYTES)
13924
+ clamp(options.maxTailBytes, DEFAULT_CLAUDE_TRANSCRIPT_TAIL_BYTES, MIN_TAIL_BYTES, MAX_TAIL_BYTES),
13925
+ agentId
13790
13926
  ),
13791
13927
  clamp(options.timeoutMillis, DEFAULT_CLAUDE_TRANSCRIPT_TIMEOUT_MILLIS, MIN_TIMEOUT_MILLIS, MAX_TIMEOUT_MILLIS),
13792
13928
  { status: "unavailable", reason: "unreadable" }
@@ -13816,7 +13952,7 @@ var readClaudeTranscriptRange = async (transcriptPath, fromOffset, options = {})
13816
13952
  let anonymous = 0;
13817
13953
  let model;
13818
13954
  for (const line of complete.split("\n")) {
13819
- const record = assistantRecordOf(line.trim());
13955
+ const record = assistantRecordOf(line.trim(), options.agentId);
13820
13956
  if (record === void 0) {
13821
13957
  continue;
13822
13958
  }
@@ -13850,15 +13986,69 @@ var eventNameOf = (record) => record.hook_event_name ?? record.hookEventName;
13850
13986
  var transcriptPathOf = (record) => record.transcript_path ?? record.transcriptPath;
13851
13987
  var CLAUDE_TRANSCRIPT_USAGE_ENRICHER_ID = "claude-transcript-usage";
13852
13988
  var sourceDigest = (transcriptPath) => createHash5("sha256").update(transcriptPath, "utf8").digest("hex").slice(0, 32);
13989
+ var SUBAGENT_STOP = "SubagentStop";
13990
+ var agentIdOf = (record) => {
13991
+ const agentId = record.agent_id ?? record.agentId;
13992
+ return typeof agentId === "string" && agentId.length > 0 && agentId.length <= 256 ? agentId : void 0;
13993
+ };
13994
+ var agentTranscriptPathOf = (record) => record.agent_transcript_path ?? record.agentTranscriptPath;
13995
+ var subagentCursorScope = (payload) => {
13996
+ const record = asRecord7(payload);
13997
+ if (record === void 0 || eventNameOf(record) !== SUBAGENT_STOP) {
13998
+ return void 0;
13999
+ }
14000
+ const agentId = agentIdOf(record);
14001
+ return agentId === void 0 ? void 0 : `agent-${createHash5("sha256").update(agentId, "utf8").digest("hex").slice(0, 32)}`;
14002
+ };
13853
14003
  var createClaudeTranscriptUsageEnricher = (options = {}) => {
13854
14004
  const fileSize = async (transcriptPath) => {
13855
14005
  try {
13856
- const info = await stat4(transcriptPath);
14006
+ const info = await stat5(transcriptPath);
13857
14007
  return info.isFile() ? info.size : void 0;
13858
14008
  } catch (thrown) {
13859
14009
  return thrown?.code === "ENOENT" ? "absent" : void 0;
13860
14010
  }
13861
14011
  };
14012
+ const readOptions = (agentId) => ({
14013
+ ...options.maxRangeBytes === void 0 ? {} : { maxRangeBytes: options.maxRangeBytes },
14014
+ ...options.rangeTimeoutMillis === void 0 ? {} : { rangeTimeoutMillis: options.rangeTimeoutMillis },
14015
+ ...agentId === void 0 ? {} : { agentId }
14016
+ });
14017
+ const attachSince = async (record, transcriptPath, fromOffset, agentId) => {
14018
+ const source = sourceDigest(transcriptPath);
14019
+ const attach = (model, usage, partial) => ({
14020
+ ...record,
14021
+ ...record.model === void 0 && model !== void 0 ? { model } : {},
14022
+ ...usage === void 0 ? {} : { usage, usage_partial: partial }
14023
+ });
14024
+ if (fromOffset !== void 0) {
14025
+ const range = await readClaudeTranscriptRange(transcriptPath, fromOffset, readOptions(agentId));
14026
+ if (range.status === "found") {
14027
+ return {
14028
+ payload: attach(range.model, range.usage, false),
14029
+ cursor: { source, offset: range.endOffset },
14030
+ notes: [`summed ${String(range.requestCount)} request(s) since the last stop`]
14031
+ };
14032
+ }
14033
+ if (range.reason !== "truncated" && range.reason !== "over-cap") {
14034
+ return { payload: record, notes: [`transcript range not read (${range.reason}); cursor kept`] };
14035
+ }
14036
+ }
14037
+ const tail = await boundedTail(transcriptPath, options, agentId);
14038
+ if (tail === TIMED_OUT || !("turn" in tail)) {
14039
+ return { payload: record, notes: [`transcript tail not read (${tail === TIMED_OUT ? "timeout" : tail.reason})`] };
14040
+ }
14041
+ const why = fromOffset === void 0 ? "no cursor for this transcript" : "range not summable within bounds";
14042
+ return {
14043
+ payload: tail.turn.status === "found" ? attach(tail.turn.model, tail.turn.usage, true) : record,
14044
+ cursor: { source, offset: tail.endOffset },
14045
+ notes: [`${why}; attached the last request only (usage_partial)`]
14046
+ };
14047
+ };
14048
+ const skipAttached = async (payload, transcriptPath) => {
14049
+ const size = await fileSize(transcriptPath);
14050
+ return typeof size === "number" ? { payload, cursor: { source: sourceDigest(transcriptPath), offset: size } } : { payload };
14051
+ };
13862
14052
  const enrich = async (input) => {
13863
14053
  const unchanged = { payload: input.payload };
13864
14054
  const record = asRecord7(input.payload);
@@ -13866,6 +14056,18 @@ var createClaudeTranscriptUsageEnricher = (options = {}) => {
13866
14056
  return unchanged;
13867
14057
  }
13868
14058
  const eventName = eventNameOf(record);
14059
+ if (eventName === SUBAGENT_STOP) {
14060
+ const agentTranscriptPath = agentTranscriptPathOf(record);
14061
+ const agentId = agentIdOf(record);
14062
+ if (agentId === void 0 || !isTranscriptPath(agentTranscriptPath)) {
14063
+ return unchanged;
14064
+ }
14065
+ if (hasUsage(record)) {
14066
+ return skipAttached(input.payload, agentTranscriptPath);
14067
+ }
14068
+ const cursor2 = input.cursor?.source === sourceDigest(agentTranscriptPath) ? input.cursor : void 0;
14069
+ return attachSince(record, agentTranscriptPath, cursor2?.offset ?? 0, agentId);
14070
+ }
13869
14071
  const transcriptPath = transcriptPathOf(record);
13870
14072
  if (typeof eventName !== "string" || !isTranscriptPath(transcriptPath)) {
13871
14073
  return unchanged;
@@ -13886,47 +14088,20 @@ var createClaudeTranscriptUsageEnricher = (options = {}) => {
13886
14088
  return unchanged;
13887
14089
  }
13888
14090
  if (hasUsage(record)) {
13889
- const size = await fileSize(transcriptPath);
13890
- return typeof size === "number" ? { payload: input.payload, cursor: { source, offset: size } } : unchanged;
13891
- }
13892
- const attach = (model, usage, partial) => ({
13893
- ...record,
13894
- ...record.model === void 0 && model !== void 0 ? { model } : {},
13895
- ...usage === void 0 ? {} : { usage, usage_partial: partial }
13896
- });
13897
- if (cursor !== void 0) {
13898
- const range = await readClaudeTranscriptRange(transcriptPath, cursor.offset, options);
13899
- if (range.status === "found") {
13900
- return {
13901
- payload: attach(range.model, range.usage, false),
13902
- cursor: { source, offset: range.endOffset },
13903
- notes: [`summed ${String(range.requestCount)} request(s) since the last stop`]
13904
- };
13905
- }
13906
- if (range.reason !== "truncated" && range.reason !== "over-cap") {
13907
- return { ...unchanged, notes: [`transcript range not read (${range.reason}); cursor kept`] };
13908
- }
14091
+ return skipAttached(input.payload, transcriptPath);
13909
14092
  }
13910
- const tail = await boundedTail(transcriptPath, options);
13911
- if (tail === TIMED_OUT || !("turn" in tail)) {
13912
- return { ...unchanged, notes: [`transcript tail not read (${tail === TIMED_OUT ? "timeout" : tail.reason})`] };
13913
- }
13914
- const why = cursor === void 0 ? "no cursor for this transcript" : "range not summable within bounds";
13915
- return {
13916
- payload: tail.turn.status === "found" ? attach(tail.turn.model, tail.turn.usage, true) : input.payload,
13917
- cursor: { source, offset: tail.endOffset },
13918
- notes: [`${why}; attached the last request only (usage_partial)`]
13919
- };
14093
+ return attachSince(record, transcriptPath, cursor?.offset, void 0);
13920
14094
  };
13921
14095
  return Object.freeze({
13922
14096
  id: CLAUDE_TRANSCRIPT_USAGE_ENRICHER_ID,
13923
14097
  providerId: CLAUDE_CODE_PROVIDER_ID,
14098
+ cursorScope: subagentCursorScope,
13924
14099
  enrich
13925
14100
  });
13926
14101
  };
13927
14102
 
13928
14103
  // src/runtime/hook.ts
13929
- import { z as z23 } from "zod";
14104
+ import { z as z24 } from "zod";
13930
14105
 
13931
14106
  // src/runtime/delivery.ts
13932
14107
  var PROVIDER_SCOPE_PREFIX = "provider-session";
@@ -14086,8 +14261,200 @@ var resolveEventTargets = async (input) => {
14086
14261
  return { events, resolved: settled.size, timedOut: finished === "timeout" };
14087
14262
  };
14088
14263
 
14264
+ // src/runtime/session-context.ts
14265
+ import { open as open5 } from "fs/promises";
14266
+ import * as path12 from "path";
14267
+ import { z as z23 } from "zod";
14268
+ var SESSION_CONTEXT_FILE_VERSION = 1;
14269
+ var DEFAULT_SESSION_CONTEXT_MAX_BYTES = 256 * 1024;
14270
+ var DEFAULT_SESSION_CONTEXT_BUDGET_MILLIS = 100;
14271
+ var MAX_SESSION_CONTEXT_SEGMENTS = 1024;
14272
+ var SESSION_CONTEXT_AGENT_TOOLS = Object.freeze({
14273
+ "claude-code": "claude_code",
14274
+ codex: "codex",
14275
+ cursor: "cursor",
14276
+ "gemini-cli": "gemini_cli",
14277
+ antigravity: "antigravity"
14278
+ });
14279
+ var sessionContextAgentTool = (providerId) => Object.hasOwn(SESSION_CONTEXT_AGENT_TOOLS, providerId) ? SESSION_CONTEXT_AGENT_TOOLS[providerId] : void 0;
14280
+ var SESSION_FILE_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/;
14281
+ var isSessionContextFileName = (sessionId) => SESSION_FILE_NAME_PATTERN.test(sessionId) && !sessionId.includes("..");
14282
+ var sessionContextFilePath = (dir, providerId, sessionId) => {
14283
+ const tool = sessionContextAgentTool(providerId);
14284
+ if (tool === void 0 || !isSessionContextFileName(sessionId) || !path12.isAbsolute(dir)) {
14285
+ return void 0;
14286
+ }
14287
+ return path12.join(dir, tool, `${sessionId}.json`);
14288
+ };
14289
+ var RESERVED_CONTEXT_KEYS = /* @__PURE__ */ new Set([
14290
+ "session.id",
14291
+ "trace_id",
14292
+ "span_id",
14293
+ "parent_span_id",
14294
+ "gen_ai.conversation.id",
14295
+ "factory.local"
14296
+ ]);
14297
+ var RESERVED_CONTEXT_PREFIXES = Object.freeze(["factory.local.", "otelhook."]);
14298
+ var isReservedSessionContextKey = (key) => RESERVED_CONTEXT_KEYS.has(key) || RESERVED_CONTEXT_PREFIXES.some((prefix) => key.startsWith(prefix));
14299
+ var sanitizeSessionContextAttributes = (attributes) => {
14300
+ const kept = {};
14301
+ let count = 0;
14302
+ for (const [key, value] of Object.entries(attributes)) {
14303
+ if (count >= MAX_RESOURCE_ATTRIBUTES) {
14304
+ break;
14305
+ }
14306
+ if (checkResourceAttributeKey(key) !== void 0 || isReservedSessionContextKey(key)) {
14307
+ continue;
14308
+ }
14309
+ if (typeof value === "string") {
14310
+ if (value.length > MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH) {
14311
+ continue;
14312
+ }
14313
+ } else if (typeof value === "number") {
14314
+ if (!Number.isFinite(value)) {
14315
+ continue;
14316
+ }
14317
+ } else if (typeof value !== "boolean") {
14318
+ continue;
14319
+ }
14320
+ kept[key] = value;
14321
+ count += 1;
14322
+ }
14323
+ return kept;
14324
+ };
14325
+ 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})$/;
14326
+ var isoInstantSchema = z23.string().max(64).regex(ISO_INSTANT_PATTERN).transform((value, ctx) => {
14327
+ const millis = Date.parse(value);
14328
+ if (!Number.isFinite(millis)) {
14329
+ ctx.issues.push({ code: "custom", input: value, message: "not a valid instant" });
14330
+ return z23.NEVER;
14331
+ }
14332
+ return millis;
14333
+ });
14334
+ var segmentSchema = z23.object({
14335
+ from: isoInstantSchema,
14336
+ to: isoInstantSchema.nullable(),
14337
+ reason: z23.string().max(256).optional(),
14338
+ attributes: z23.record(z23.string(), z23.unknown())
14339
+ });
14340
+ var sessionContextFileSchema = z23.object({
14341
+ version: z23.literal(SESSION_CONTEXT_FILE_VERSION),
14342
+ agentTool: z23.string().max(64).optional(),
14343
+ sessionId: z23.string().max(256).optional(),
14344
+ segments: z23.array(segmentSchema).max(MAX_SESSION_CONTEXT_SEGMENTS)
14345
+ });
14346
+ var parseSessionContextFile = (value, expected) => {
14347
+ const parsed = sessionContextFileSchema.safeParse(value);
14348
+ if (!parsed.success) {
14349
+ return void 0;
14350
+ }
14351
+ const file = parsed.data;
14352
+ 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) {
14353
+ return void 0;
14354
+ }
14355
+ return file.segments.map((segment) => ({
14356
+ from: segment.from,
14357
+ to: segment.to,
14358
+ attributes: sanitizeSessionContextAttributes(segment.attributes)
14359
+ }));
14360
+ };
14361
+ var segmentInForce = (segments, at) => {
14362
+ let best;
14363
+ for (const segment of segments) {
14364
+ if (segment.from <= at && (segment.to === null || at < segment.to)) {
14365
+ if (best === void 0 || segment.from >= best.from) {
14366
+ best = segment;
14367
+ }
14368
+ }
14369
+ }
14370
+ return best;
14371
+ };
14372
+ var stampSessionContext = (events, segments) => events.map((event3) => {
14373
+ const { contextAttributes: _discarded, ...rest } = event3;
14374
+ const segment = segments === void 0 ? void 0 : segmentInForce(segments, event3.occurredAt);
14375
+ if (segment === void 0 || Object.keys(segment.attributes).length === 0) {
14376
+ return _discarded === void 0 ? event3 : rest;
14377
+ }
14378
+ return { ...rest, contextAttributes: { ...segment.attributes } };
14379
+ });
14380
+ var readBounded = async (file, maxBytes) => {
14381
+ let handle;
14382
+ try {
14383
+ handle = await open5(file, "r");
14384
+ } catch {
14385
+ return void 0;
14386
+ }
14387
+ try {
14388
+ const stats = await handle.stat();
14389
+ if (!stats.isFile() || stats.size > maxBytes) {
14390
+ return void 0;
14391
+ }
14392
+ const buffer = Buffer.alloc(maxBytes + 1);
14393
+ let length = 0;
14394
+ while (length < buffer.length) {
14395
+ const { bytesRead } = await handle.read(buffer, length, buffer.length - length, length);
14396
+ if (bytesRead === 0) {
14397
+ break;
14398
+ }
14399
+ length += bytesRead;
14400
+ }
14401
+ if (length > maxBytes) {
14402
+ return void 0;
14403
+ }
14404
+ return buffer.subarray(0, length).toString("utf8");
14405
+ } catch {
14406
+ return void 0;
14407
+ } finally {
14408
+ await handle.close().catch(() => void 0);
14409
+ }
14410
+ };
14411
+ var createDirectorySessionContextReader = (options) => {
14412
+ const maxBytes = options.maxBytes ?? DEFAULT_SESSION_CONTEXT_MAX_BYTES;
14413
+ const budgetMillis = options.budgetMillis ?? DEFAULT_SESSION_CONTEXT_BUDGET_MILLIS;
14414
+ const readOnce = async (providerId, sessionId) => {
14415
+ const file = sessionContextFilePath(options.dir, providerId, sessionId);
14416
+ if (file === void 0) {
14417
+ return void 0;
14418
+ }
14419
+ const text = await readBounded(file, maxBytes);
14420
+ if (text === void 0) {
14421
+ return void 0;
14422
+ }
14423
+ let decoded;
14424
+ try {
14425
+ decoded = JSON.parse(text);
14426
+ } catch {
14427
+ return void 0;
14428
+ }
14429
+ const agentTool = sessionContextAgentTool(providerId);
14430
+ return parseSessionContextFile(decoded, {
14431
+ ...agentTool === void 0 ? {} : { agentTool },
14432
+ sessionId
14433
+ });
14434
+ };
14435
+ return {
14436
+ read: async (request) => {
14437
+ let timer;
14438
+ const timeout = new Promise((resolve8) => {
14439
+ timer = setTimeout(() => resolve8(void 0), budgetMillis);
14440
+ timer.unref?.();
14441
+ });
14442
+ try {
14443
+ return await Promise.race([
14444
+ readOnce(request.providerId, request.sessionId).catch(() => void 0),
14445
+ timeout
14446
+ ]);
14447
+ } finally {
14448
+ if (timer !== void 0) {
14449
+ clearTimeout(timer);
14450
+ }
14451
+ }
14452
+ }
14453
+ };
14454
+ };
14455
+
14089
14456
  // src/runtime/hook.ts
14090
- var usageScopeSchema = z23.enum(["session", "generation", "subagent"]);
14457
+ var usageScopeSchema = z24.enum(["session", "generation", "subagent"]);
14091
14458
  var classifyDurability = (input) => {
14092
14459
  if (!input.attempted) {
14093
14460
  return "nothing-to-deliver";
@@ -14146,7 +14513,7 @@ var usageScopeOf = (event3) => {
14146
14513
  };
14147
14514
  var sequenceKey = (sessionId) => `sequence:${sessionId}`;
14148
14515
  var sessionModelKey = (sessionId) => `model:${sessionId}`;
14149
- var readCursorKey = (enricherId, sessionId) => `cursor:${enricherId}:${sessionId}`;
14516
+ var readCursorKey = (enricherId, sessionId, scope) => scope === void 0 ? `cursor:${enricherId}:${sessionId}` : `cursor:${enricherId}:${sessionId}:${scope}`;
14150
14517
  var UNKNOWN_MODEL_ID = "unknown";
14151
14518
  var latestSessionModel = (events) => {
14152
14519
  let latest;
@@ -14214,7 +14581,17 @@ var createOtelHook = (deps) => {
14214
14581
  if (enricher.providerId !== providerId) {
14215
14582
  continue;
14216
14583
  }
14217
- const key = readCursorKey(enricher.id, sessionId);
14584
+ let scope;
14585
+ try {
14586
+ scope = enricher.cursorScope?.(current);
14587
+ } catch (thrown) {
14588
+ logger.warn("payload enricher failed; parsing the payload as delivered", {
14589
+ "enricher.id": enricher.id,
14590
+ "error.name": thrown instanceof Error ? thrown.name : typeof thrown
14591
+ });
14592
+ continue;
14593
+ }
14594
+ const key = readCursorKey(enricher.id, sessionId, scope);
14218
14595
  let cursor;
14219
14596
  try {
14220
14597
  const record = await deps.stateStore.read(key);
@@ -14796,6 +15173,10 @@ var createOtelHook = (deps) => {
14796
15173
  });
14797
15174
  }
14798
15175
  }
15176
+ batch = stampSessionContext(
15177
+ batch,
15178
+ !suppress && batch.length > 0 && deps.sessionContext !== void 0 ? await readSessionContext(deps.sessionContext, detection.providerId, identity.sessionId) : void 0
15179
+ );
14799
15180
  let emitted = 0;
14800
15181
  let exportRejected = 0;
14801
15182
  if (!suppress && batch.length > 0) {
@@ -14911,6 +15292,13 @@ var createOtelHook = (deps) => {
14911
15292
  };
14912
15293
  return { resolveDelivery, ingest, flush, shutdown, config };
14913
15294
  };
15295
+ var readSessionContext = async (reader, providerId, sessionId) => {
15296
+ try {
15297
+ return await reader.read({ providerId, sessionId });
15298
+ } catch {
15299
+ return void 0;
15300
+ }
15301
+ };
14914
15302
  var buildErrorEvents = (diagnostics, identity, sequenceBase, ids, privacy) => {
14915
15303
  const events = [];
14916
15304
  for (const [index, info] of diagnostics.slice(0, MAX_ERROR_EVENTS).entries()) {
@@ -14945,8 +15333,8 @@ var buildErrorEvents = (diagnostics, identity, sequenceBase, ids, privacy) => {
14945
15333
  };
14946
15334
 
14947
15335
  // src/runtime/git-worktree.ts
14948
- import { lstat, open as open5, stat as stat5 } from "fs/promises";
14949
- import * as path12 from "path";
15336
+ import { lstat, open as open6, stat as stat6 } from "fs/promises";
15337
+ import * as path13 from "path";
14950
15338
  var MAX_WORKTREE_WALK_DEPTH = 128;
14951
15339
  var MAX_GIT_FILE_BYTES = 4096;
14952
15340
  var MAX_CACHE_ENTRIES = 1024;
@@ -14954,10 +15342,10 @@ var DEFAULT_WORKTREE_CACHE_TTL_MILLIS = 5e3;
14954
15342
  var MAX_BRANCH_NAME_LENGTH = 255;
14955
15343
  var ABSENT = Object.freeze({ kind: "absent" });
14956
15344
  var INVALID = Object.freeze({ kind: "invalid" });
14957
- var readBounded = async (filePath) => {
15345
+ var readBounded2 = async (filePath) => {
14958
15346
  let handle;
14959
15347
  try {
14960
- handle = await open5(filePath, "r");
15348
+ handle = await open6(filePath, "r");
14961
15349
  const buffer = Buffer.alloc(MAX_GIT_FILE_BYTES);
14962
15350
  const { bytesRead } = await handle.read(buffer, 0, MAX_GIT_FILE_BYTES, 0);
14963
15351
  return buffer.subarray(0, bytesRead).toString("utf8");
@@ -14978,7 +15366,7 @@ var parseHeadBranch = (head) => {
14978
15366
  return branch;
14979
15367
  };
14980
15368
  var firstLine = (content) => content.split(/\r?\n/, 1)[0]?.trim() ?? "";
14981
- var resolveGitPath = (target, base) => target === void 0 || target.length === 0 || target.includes("\0") ? void 0 : path12.resolve(base, target);
15369
+ var resolveGitPath = (target, base) => target === void 0 || target.length === 0 || target.includes("\0") ? void 0 : path13.resolve(base, target);
14982
15370
  var parseGitDirFile = (content, worktreeRoot) => {
14983
15371
  const line = firstLine(content);
14984
15372
  return resolveGitPath(
@@ -14998,26 +15386,26 @@ var isMissing = async (filePath) => {
14998
15386
  };
14999
15387
  var isDirectory = async (directory) => {
15000
15388
  try {
15001
- return (await stat5(directory)).isDirectory();
15389
+ return (await stat6(directory)).isDirectory();
15002
15390
  } catch {
15003
15391
  return false;
15004
15392
  }
15005
15393
  };
15006
15394
  var repositoryOf = async (worktreeRoot, gitDir) => {
15007
- const commonDirFile = path12.join(gitDir, "commondir");
15008
- const content = await readBounded(commonDirFile);
15395
+ const commonDirFile = path13.join(gitDir, "commondir");
15396
+ const content = await readBounded2(commonDirFile);
15009
15397
  if (content === void 0) {
15010
15398
  return await isMissing(commonDirFile) ? { kind: "main", mainRoot: worktreeRoot } : { kind: "linked" };
15011
15399
  }
15012
15400
  const commonDir = parseCommonDirFile(content, gitDir);
15013
- const mainRoot = commonDir !== void 0 && path12.basename(commonDir) === ".git" && await isDirectory(commonDir) ? path12.dirname(commonDir) : void 0;
15401
+ const mainRoot = commonDir !== void 0 && path13.basename(commonDir) === ".git" && await isDirectory(commonDir) ? path13.dirname(commonDir) : void 0;
15014
15402
  return { kind: "linked", ...mainRoot === void 0 ? {} : { mainRoot } };
15015
15403
  };
15016
15404
  var probeDirectory = async (directory) => {
15017
- const dotGit = path12.join(directory, ".git");
15405
+ const dotGit = path13.join(directory, ".git");
15018
15406
  let info;
15019
15407
  try {
15020
- info = await stat5(dotGit);
15408
+ info = await stat6(dotGit);
15021
15409
  } catch {
15022
15410
  return ABSENT;
15023
15411
  }
@@ -15025,13 +15413,13 @@ var probeDirectory = async (directory) => {
15025
15413
  if (info.isDirectory()) {
15026
15414
  gitDir = dotGit;
15027
15415
  } else if (info.isFile()) {
15028
- const content = await readBounded(dotGit);
15416
+ const content = await readBounded2(dotGit);
15029
15417
  gitDir = content === void 0 ? void 0 : parseGitDirFile(content, directory);
15030
15418
  }
15031
15419
  if (gitDir === void 0) {
15032
15420
  return INVALID;
15033
15421
  }
15034
- const head = await readBounded(path12.join(gitDir, "HEAD"));
15422
+ const head = await readBounded2(path13.join(gitDir, "HEAD"));
15035
15423
  if (head === void 0) {
15036
15424
  return INVALID;
15037
15425
  }
@@ -15061,10 +15449,10 @@ var createFilesystemWorktreeLocator = (options = {}) => {
15061
15449
  };
15062
15450
  const locate = async (absolutePath) => {
15063
15451
  try {
15064
- if (!path12.isAbsolute(absolutePath) || absolutePath.includes("\0")) {
15452
+ if (!path13.isAbsolute(absolutePath) || absolutePath.includes("\0")) {
15065
15453
  return void 0;
15066
15454
  }
15067
- let directory = path12.resolve(absolutePath);
15455
+ let directory = path13.resolve(absolutePath);
15068
15456
  for (let depth = 0; depth < MAX_WORKTREE_WALK_DEPTH; depth += 1) {
15069
15457
  const probe = await cachedProbe(directory);
15070
15458
  if (probe.kind === "worktree") {
@@ -15073,7 +15461,7 @@ var createFilesystemWorktreeLocator = (options = {}) => {
15073
15461
  if (probe.kind === "invalid") {
15074
15462
  return void 0;
15075
15463
  }
15076
- const parent = path12.dirname(directory);
15464
+ const parent = path13.dirname(directory);
15077
15465
  if (parent === directory) {
15078
15466
  return void 0;
15079
15467
  }
@@ -15200,6 +15588,16 @@ var createHookRuntime = (options) => {
15200
15588
  logger,
15201
15589
  installationId: options.installationId,
15202
15590
  payloadEnrichers: options.payloadEnrichers ?? (readsClaudeTranscriptUsage(options.config) ? [createClaudeTranscriptUsageEnricher()] : []),
15591
+ ...(() => {
15592
+ if (options.sessionContextReader === null) {
15593
+ return {};
15594
+ }
15595
+ if (options.sessionContextReader !== void 0) {
15596
+ return { sessionContext: options.sessionContextReader };
15597
+ }
15598
+ const dir = sessionContextDir(options.config);
15599
+ return dir === void 0 ? {} : { sessionContext: createDirectorySessionContextReader({ dir }) };
15600
+ })(),
15203
15601
  ...options.worktreeLocator === null ? {} : {
15204
15602
  worktreeLocator: options.worktreeLocator ?? createFilesystemWorktreeLocator({ monotonicMillis: () => clock.monotonicMillis() })
15205
15603
  }
@@ -15293,9 +15691,10 @@ var createHookRuntime = (options) => {
15293
15691
  perSession: metricsPolicy.includeSessionId,
15294
15692
  ...deliveryToken === void 0 ? {} : { deliveryToken }
15295
15693
  });
15694
+ const context = agreedContextAttributes(ingest.events);
15296
15695
  const results = await Promise.all(
15297
15696
  metricDestinations.map(async (destination) => {
15298
- const result = await destination.metrics.exportPoints(points).catch(
15697
+ const result = await destination.metrics.exportPoints(points, context).catch(
15299
15698
  (thrown) => ({
15300
15699
  accepted: 0,
15301
15700
  rejected: points.length,
@@ -15864,13 +16263,13 @@ var runHookCommand = async (command, io) => {
15864
16263
  }
15865
16264
  const identityClaims = [];
15866
16265
  if (command.identity.identityFile !== void 0) {
15867
- const read = await readIdentityFile(path13.resolve(command.identity.identityFile));
16266
+ const read = await readIdentityFile(path14.resolve(command.identity.identityFile));
15868
16267
  if ("error" in read) {
15869
16268
  logDiagnostics(logger, [read.error]);
15870
16269
  } else {
15871
16270
  const fromFile = claimFromIdentityFile(
15872
16271
  read.value,
15873
- path13.basename(command.identity.identityFile)
16272
+ path14.basename(command.identity.identityFile)
15874
16273
  );
15875
16274
  logDiagnostics(logger, fromFile.errors);
15876
16275
  identityClaims.push(...fromFile.claims);