@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/index.js CHANGED
@@ -833,7 +833,15 @@ var baseEventFields = {
833
833
  * factory, never by hand.
834
834
  */
835
835
  subagentId: subagentIdSchema.optional(),
836
- extensions: extensionsSchema.default(emptyExtensions)
836
+ extensions: extensionsSchema.default(emptyExtensions),
837
+ /**
838
+ * Attributes of the session context segment in force when the event
839
+ * occurred (`docs/session-context.md`), stamped by the core from a file a
840
+ * harness wrote. Exported on every record of the event, over the same keys
841
+ * from the Resource. Absent when no context applies. Set by the core only,
842
+ * never by an adapter.
843
+ */
844
+ contextAttributes: z9.record(z9.string().min(1).max(255), z9.union([z9.string(), z9.number(), z9.boolean()])).optional()
837
845
  };
838
846
  var event = (shape) => z9.strictObject({ ...baseEventFields, ...shape });
839
847
  var sessionStartEventSchema = event({
@@ -1352,11 +1360,11 @@ var createPrivacyService = (policyInput) => {
1352
1360
  };
1353
1361
  const flattenToAttributes = (value, prefix) => {
1354
1362
  const attributes = {};
1355
- const walk = (current, path10) => {
1363
+ const walk = (current, path11) => {
1356
1364
  if (typeof current === "string" || typeof current === "number" || typeof current === "boolean") {
1357
1365
  const primitive = toAttributePrimitive(current);
1358
1366
  if (primitive !== void 0) {
1359
- attributes[path10] = primitive;
1367
+ attributes[path11] = primitive;
1360
1368
  }
1361
1369
  return;
1362
1370
  }
@@ -1375,16 +1383,16 @@ var createPrivacyService = (policyInput) => {
1375
1383
  primitives.push(entryPrimitive);
1376
1384
  }
1377
1385
  if (uniform) {
1378
- attributes[path10] = primitives.slice(0, MAX_ATTRIBUTE_ARRAY_LENGTH);
1386
+ attributes[path11] = primitives.slice(0, MAX_ATTRIBUTE_ARRAY_LENGTH);
1379
1387
  return;
1380
1388
  }
1381
1389
  for (const [index, entry] of current.entries()) {
1382
- walk(entry, `${path10}.${index}`);
1390
+ walk(entry, `${path11}.${index}`);
1383
1391
  }
1384
1392
  return;
1385
1393
  }
1386
1394
  for (const [key, entry] of Object.entries(current)) {
1387
- walk(entry, path10 === "" ? key : `${path10}.${key}`);
1395
+ walk(entry, path11 === "" ? key : `${path11}.${key}`);
1388
1396
  }
1389
1397
  };
1390
1398
  walk(value, prefix);
@@ -1683,6 +1691,7 @@ var sanitizeResourceAttributes = (attributes) => {
1683
1691
  var describeResourceAttributeNames = (attributes) => Object.keys(attributes).sort();
1684
1692
 
1685
1693
  // src/config/schema.ts
1694
+ import { isAbsolute } from "path";
1686
1695
  import { z as z14 } from "zod";
1687
1696
 
1688
1697
  // src/config/destinations.ts
@@ -2119,13 +2128,19 @@ var providersPolicySchema = z14.strictObject({
2119
2128
  readTranscriptUsage: z14.boolean()
2120
2129
  }).optional()
2121
2130
  });
2131
+ var sessionContextPolicySchema = z14.strictObject({
2132
+ /** Absolute path of the context directory. */
2133
+ dir: z14.string().min(1).max(4096).refine((value) => isAbsolute(value), { message: "must be an absolute path" })
2134
+ });
2122
2135
  var otelHookConfigSchema = z14.strictObject({
2123
2136
  exporter: exporterPolicySchema,
2124
2137
  privacy: privacyPolicySchema,
2125
2138
  detection: detectionPolicySchema,
2126
2139
  diagnostics: diagnosticsPolicySchema,
2127
2140
  /** Optional so a hand-built configuration from before it existed stays valid. */
2128
- providers: providersPolicySchema.optional()
2141
+ providers: providersPolicySchema.optional(),
2142
+ /** Optional: absent means no session context is read. */
2143
+ sessionContext: sessionContextPolicySchema.optional()
2129
2144
  });
2130
2145
  var otelHookConfigPatchSchema = z14.strictObject({
2131
2146
  // `logs` is unwrapped and re-partialled for the same reason `privacy.limits` is:
@@ -2141,7 +2156,8 @@ var otelHookConfigPatchSchema = z14.strictObject({
2141
2156
  diagnostics: diagnosticsPolicySchema.partial().optional(),
2142
2157
  providers: z14.strictObject({
2143
2158
  claudeCode: z14.strictObject({ readTranscriptUsage: z14.boolean() }).partial().optional()
2144
- }).partial().optional()
2159
+ }).partial().optional(),
2160
+ sessionContext: sessionContextPolicySchema.partial().optional()
2145
2161
  });
2146
2162
  var DEFAULT_EXPORTER_POLICY = Object.freeze({
2147
2163
  enabled: true,
@@ -2176,6 +2192,7 @@ var DEFAULT_CONFIG = Object.freeze({
2176
2192
  providers: DEFAULT_PROVIDERS_POLICY
2177
2193
  });
2178
2194
  var readsClaudeTranscriptUsage = (config) => config.providers?.claudeCode?.readTranscriptUsage === true;
2195
+ var sessionContextDir = (config) => config.sessionContext?.dir;
2179
2196
  var effectiveMetricsPolicy = (exporter) => ({
2180
2197
  ...DEFAULT_METRICS_POLICY,
2181
2198
  ...exporter.metrics ?? {}
@@ -2186,12 +2203,12 @@ import { z as z15 } from "zod";
2186
2203
  var CONFIG_SOURCE_PRECEDENCE = ["defaults", "file", "environment", "inline-override"];
2187
2204
  var configSourceSchema = z15.enum(CONFIG_SOURCE_PRECEDENCE);
2188
2205
  var isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2189
- var mergeLeaf = (target, patch, source, provenance, path10) => {
2206
+ var mergeLeaf = (target, patch, source, provenance, path11) => {
2190
2207
  for (const [key, value] of Object.entries(patch)) {
2191
2208
  if (value === void 0) {
2192
2209
  continue;
2193
2210
  }
2194
- const childPath = path10 === "" ? key : `${path10}.${key}`;
2211
+ const childPath = path11 === "" ? key : `${path11}.${key}`;
2195
2212
  const existing = target[key];
2196
2213
  if (isPlainObject(value) && (isPlainObject(existing) || existing === void 0)) {
2197
2214
  const child = { ...existing ?? {} };
@@ -2205,14 +2222,14 @@ var mergeLeaf = (target, patch, source, provenance, path10) => {
2205
2222
  };
2206
2223
  var initialProvenance = (config) => {
2207
2224
  const provenance = {};
2208
- const walk = (value, path10) => {
2225
+ const walk = (value, path11) => {
2209
2226
  if (isPlainObject(value)) {
2210
2227
  for (const [key, child] of Object.entries(value)) {
2211
- walk(child, path10 === "" ? key : `${path10}.${key}`);
2228
+ walk(child, path11 === "" ? key : `${path11}.${key}`);
2212
2229
  }
2213
2230
  return;
2214
2231
  }
2215
- provenance[path10] = "defaults";
2232
+ provenance[path11] = "defaults";
2216
2233
  };
2217
2234
  walk(config, "");
2218
2235
  return provenance;
@@ -2383,7 +2400,9 @@ var describeResolvedConfig = (config) => {
2383
2400
  "detection.minimum_confidence": config.detection.minimumConfidence,
2384
2401
  "detection.allow_ambiguous_fallback": config.detection.allowAmbiguousFallback,
2385
2402
  "diagnostics.log_level": config.diagnostics.logLevel,
2386
- "diagnostics.emit_error_events": config.diagnostics.emitErrorEvents
2403
+ "diagnostics.emit_error_events": config.diagnostics.emitErrorEvents,
2404
+ // Whether, never where: the directory is a local path.
2405
+ "session_context.enabled": config.sessionContext?.dir !== void 0
2387
2406
  };
2388
2407
  };
2389
2408
 
@@ -2835,6 +2854,7 @@ var createEventFactory = (input) => {
2835
2854
  const rest = { ...drafted };
2836
2855
  delete rest.target;
2837
2856
  delete rest.subagentId;
2857
+ delete rest.contextAttributes;
2838
2858
  const sanitized = extensions === void 0 ? { extensions: {}, droppedKeys: [] } : context.privacy.sanitizeExtensions(extensions);
2839
2859
  dropped.push(...sanitized.droppedKeys);
2840
2860
  const currentSequence = sequence;
@@ -3143,7 +3163,16 @@ var subagentStopPayloadSchema = z17.object({
3143
3163
  last_assistant_message: z17.string().optional(),
3144
3164
  /** True when this stop fired because a hook continued the subagent's turn. */
3145
3165
  stop_hook_active: z17.boolean().optional(),
3146
- usage: claudeUsageSchema.optional()
3166
+ /**
3167
+ * The subagent run's tokens since its previous stop — harness- or
3168
+ * enricher-supplied, never upstream. Reported on the subagent's own
3169
+ * generation, never on the parent turn (issue #68).
3170
+ */
3171
+ usage: claudeUsageSchema.optional(),
3172
+ /** Harness-supplied, never upstream: the subagent's model, from its transcript. */
3173
+ model: z17.string().min(1).max(256).optional().catch(void 0),
3174
+ /** Harness-supplied, never upstream: see `stopPayloadSchema.usage_partial`. */
3175
+ usage_partial: z17.boolean().optional().catch(void 0)
3147
3176
  });
3148
3177
  var preCompactPayloadSchema = z17.object({
3149
3178
  ...commonFields,
@@ -3741,6 +3770,8 @@ var BUILT_IN_TOOL_KIND = Object.freeze({
3741
3770
  WebFetch: "network",
3742
3771
  WebSearch: "network",
3743
3772
  Task: "delegate",
3773
+ // Current Claude Code releases (observed on 2.1.332) name the subagent tool `Agent`.
3774
+ Agent: "delegate",
3744
3775
  TodoWrite: "other",
3745
3776
  ExitPlanMode: "other",
3746
3777
  AskUserQuestion: "other",
@@ -3914,14 +3945,39 @@ var parseClaudeCode = (input, context) => {
3914
3945
  delegationDepth: 1
3915
3946
  });
3916
3947
  break;
3917
- case "SubagentStop":
3948
+ case "SubagentStop": {
3949
+ const usage = withPartialUsage(extractedUsage ?? payload.usage, payload.usage_partial);
3950
+ if (usage.usage !== void 0 || payload.model !== void 0) {
3951
+ const generationId = context.ids.newOpaqueId([
3952
+ "claude-subagent-generation",
3953
+ payload.session_id,
3954
+ payload.agent_id,
3955
+ ...payload.stop_hook_active === true ? [String(input.sequenceBase)] : []
3956
+ ]);
3957
+ const models = generationModels(payload.model, void 0);
3958
+ factory.build({ type: "generation.start", generationId, model: models.request });
3959
+ factory.build({
3960
+ type: "generation.end",
3961
+ generationId,
3962
+ model: models.response,
3963
+ outcome: "ok",
3964
+ outputContent: [
3965
+ payload.last_assistant_message === void 0 ? context.privacy.describeUnavailableContent({ kind: "response", role: "assistant" }) : context.privacy.describeContent({
3966
+ kind: "response",
3967
+ role: "assistant",
3968
+ text: payload.last_assistant_message
3969
+ })
3970
+ ],
3971
+ ...usage
3972
+ });
3973
+ }
3918
3974
  factory.build({
3919
3975
  type: "subagent.end",
3920
3976
  subagentInvocationId: subagentInvocationIdFor(context, payload.session_id, payload.agent_id),
3921
- outcome: "ok",
3922
- ...withUsage(payload.usage)
3977
+ outcome: "ok"
3923
3978
  });
3924
3979
  break;
3980
+ }
3925
3981
  case "PreCompact":
3926
3982
  return {
3927
3983
  status: "ignored",
@@ -4041,7 +4097,8 @@ var clamp = (value, fallback, min, max) => {
4041
4097
  };
4042
4098
  var asRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
4043
4099
  var isTranscriptPath = (transcriptPath) => typeof transcriptPath === "string" && transcriptPath.length > 0 && !transcriptPath.includes("\0") && path.isAbsolute(transcriptPath) && path.extname(transcriptPath) === ".jsonl";
4044
- var assistantRecordOf = (line) => {
4100
+ var isRecordOfAgent = (record, agentId) => record.isSidechain === true && (typeof record.agentId !== "string" || record.agentId === agentId);
4101
+ var assistantRecordOf = (line, agentId) => {
4045
4102
  if (!line.includes('"assistant"')) {
4046
4103
  return void 0;
4047
4104
  }
@@ -4052,7 +4109,10 @@ var assistantRecordOf = (line) => {
4052
4109
  return void 0;
4053
4110
  }
4054
4111
  const record = asRecord5(parsed);
4055
- if (record === void 0 || record.type !== "assistant" || record.isSidechain === true) {
4112
+ if (record === void 0 || record.type !== "assistant") {
4113
+ return void 0;
4114
+ }
4115
+ if (agentId === void 0 ? record.isSidechain === true : !isRecordOfAgent(record, agentId)) {
4056
4116
  return void 0;
4057
4117
  }
4058
4118
  const message = asRecord5(record.message);
@@ -4145,7 +4205,7 @@ var completeLinesEnd = (bytes, start) => {
4145
4205
  const lastNewline = bytes.lastIndexOf(10);
4146
4206
  return lastNewline < 0 ? start : start + lastNewline + 1;
4147
4207
  };
4148
- var readTail = (transcriptPath, maxTailBytes) => withRegularFile(transcriptPath, async (handle, size) => {
4208
+ var readTail = (transcriptPath, maxTailBytes, agentId) => withRegularFile(transcriptPath, async (handle, size) => {
4149
4209
  const length = Math.min(size, maxTailBytes);
4150
4210
  const start = size - length;
4151
4211
  const bytes = await readBytes(handle, start, length);
@@ -4155,7 +4215,7 @@ var readTail = (transcriptPath, maxTailBytes) => withRegularFile(transcriptPath,
4155
4215
  lines.shift();
4156
4216
  }
4157
4217
  for (let index = lines.length - 1; index >= 0; index -= 1) {
4158
- const record = assistantRecordOf((lines[index] ?? "").trim());
4218
+ const record = assistantRecordOf((lines[index] ?? "").trim(), agentId);
4159
4219
  if (record !== void 0) {
4160
4220
  return {
4161
4221
  turn: {
@@ -4169,10 +4229,11 @@ var readTail = (transcriptPath, maxTailBytes) => withRegularFile(transcriptPath,
4169
4229
  }
4170
4230
  return { turn: { status: "unavailable", reason: "no-assistant-message" }, endOffset };
4171
4231
  });
4172
- var boundedTail = async (transcriptPath, options) => withTimeout(
4232
+ var boundedTail = async (transcriptPath, options, agentId) => withTimeout(
4173
4233
  readTail(
4174
4234
  transcriptPath,
4175
- clamp(options.maxTailBytes, DEFAULT_CLAUDE_TRANSCRIPT_TAIL_BYTES, MIN_TAIL_BYTES, MAX_TAIL_BYTES)
4235
+ clamp(options.maxTailBytes, DEFAULT_CLAUDE_TRANSCRIPT_TAIL_BYTES, MIN_TAIL_BYTES, MAX_TAIL_BYTES),
4236
+ agentId
4176
4237
  ),
4177
4238
  clamp(options.timeoutMillis, DEFAULT_CLAUDE_TRANSCRIPT_TIMEOUT_MILLIS, MIN_TIMEOUT_MILLIS, MAX_TIMEOUT_MILLIS),
4178
4239
  { status: "unavailable", reason: "unreadable" }
@@ -4212,7 +4273,7 @@ var readClaudeTranscriptRange = async (transcriptPath, fromOffset, options = {})
4212
4273
  let anonymous = 0;
4213
4274
  let model;
4214
4275
  for (const line of complete.split("\n")) {
4215
- const record = assistantRecordOf(line.trim());
4276
+ const record = assistantRecordOf(line.trim(), options.agentId);
4216
4277
  if (record === void 0) {
4217
4278
  continue;
4218
4279
  }
@@ -4274,6 +4335,20 @@ var attachClaudeTranscriptTurn = async (payload, options = {}) => {
4274
4335
  };
4275
4336
  var CLAUDE_TRANSCRIPT_USAGE_ENRICHER_ID = "claude-transcript-usage";
4276
4337
  var sourceDigest = (transcriptPath) => createHash2("sha256").update(transcriptPath, "utf8").digest("hex").slice(0, 32);
4338
+ var SUBAGENT_STOP = "SubagentStop";
4339
+ var agentIdOf = (record) => {
4340
+ const agentId = record.agent_id ?? record.agentId;
4341
+ return typeof agentId === "string" && agentId.length > 0 && agentId.length <= 256 ? agentId : void 0;
4342
+ };
4343
+ var agentTranscriptPathOf = (record) => record.agent_transcript_path ?? record.agentTranscriptPath;
4344
+ var subagentCursorScope = (payload) => {
4345
+ const record = asRecord5(payload);
4346
+ if (record === void 0 || eventNameOf(record) !== SUBAGENT_STOP) {
4347
+ return void 0;
4348
+ }
4349
+ const agentId = agentIdOf(record);
4350
+ return agentId === void 0 ? void 0 : `agent-${createHash2("sha256").update(agentId, "utf8").digest("hex").slice(0, 32)}`;
4351
+ };
4277
4352
  var createClaudeTranscriptUsageEnricher = (options = {}) => {
4278
4353
  const fileSize = async (transcriptPath) => {
4279
4354
  try {
@@ -4283,6 +4358,46 @@ var createClaudeTranscriptUsageEnricher = (options = {}) => {
4283
4358
  return thrown?.code === "ENOENT" ? "absent" : void 0;
4284
4359
  }
4285
4360
  };
4361
+ const readOptions = (agentId) => ({
4362
+ ...options.maxRangeBytes === void 0 ? {} : { maxRangeBytes: options.maxRangeBytes },
4363
+ ...options.rangeTimeoutMillis === void 0 ? {} : { rangeTimeoutMillis: options.rangeTimeoutMillis },
4364
+ ...agentId === void 0 ? {} : { agentId }
4365
+ });
4366
+ const attachSince = async (record, transcriptPath, fromOffset, agentId) => {
4367
+ const source = sourceDigest(transcriptPath);
4368
+ const attach = (model, usage, partial) => ({
4369
+ ...record,
4370
+ ...record.model === void 0 && model !== void 0 ? { model } : {},
4371
+ ...usage === void 0 ? {} : { usage, usage_partial: partial }
4372
+ });
4373
+ if (fromOffset !== void 0) {
4374
+ const range = await readClaudeTranscriptRange(transcriptPath, fromOffset, readOptions(agentId));
4375
+ if (range.status === "found") {
4376
+ return {
4377
+ payload: attach(range.model, range.usage, false),
4378
+ cursor: { source, offset: range.endOffset },
4379
+ notes: [`summed ${String(range.requestCount)} request(s) since the last stop`]
4380
+ };
4381
+ }
4382
+ if (range.reason !== "truncated" && range.reason !== "over-cap") {
4383
+ return { payload: record, notes: [`transcript range not read (${range.reason}); cursor kept`] };
4384
+ }
4385
+ }
4386
+ const tail = await boundedTail(transcriptPath, options, agentId);
4387
+ if (tail === TIMED_OUT || !("turn" in tail)) {
4388
+ return { payload: record, notes: [`transcript tail not read (${tail === TIMED_OUT ? "timeout" : tail.reason})`] };
4389
+ }
4390
+ const why = fromOffset === void 0 ? "no cursor for this transcript" : "range not summable within bounds";
4391
+ return {
4392
+ payload: tail.turn.status === "found" ? attach(tail.turn.model, tail.turn.usage, true) : record,
4393
+ cursor: { source, offset: tail.endOffset },
4394
+ notes: [`${why}; attached the last request only (usage_partial)`]
4395
+ };
4396
+ };
4397
+ const skipAttached = async (payload, transcriptPath) => {
4398
+ const size = await fileSize(transcriptPath);
4399
+ return typeof size === "number" ? { payload, cursor: { source: sourceDigest(transcriptPath), offset: size } } : { payload };
4400
+ };
4286
4401
  const enrich = async (input) => {
4287
4402
  const unchanged = { payload: input.payload };
4288
4403
  const record = asRecord5(input.payload);
@@ -4290,6 +4405,18 @@ var createClaudeTranscriptUsageEnricher = (options = {}) => {
4290
4405
  return unchanged;
4291
4406
  }
4292
4407
  const eventName = eventNameOf(record);
4408
+ if (eventName === SUBAGENT_STOP) {
4409
+ const agentTranscriptPath = agentTranscriptPathOf(record);
4410
+ const agentId = agentIdOf(record);
4411
+ if (agentId === void 0 || !isTranscriptPath(agentTranscriptPath)) {
4412
+ return unchanged;
4413
+ }
4414
+ if (hasUsage(record)) {
4415
+ return skipAttached(input.payload, agentTranscriptPath);
4416
+ }
4417
+ const cursor2 = input.cursor?.source === sourceDigest(agentTranscriptPath) ? input.cursor : void 0;
4418
+ return attachSince(record, agentTranscriptPath, cursor2?.offset ?? 0, agentId);
4419
+ }
4293
4420
  const transcriptPath = transcriptPathOf(record);
4294
4421
  if (typeof eventName !== "string" || !isTranscriptPath(transcriptPath)) {
4295
4422
  return unchanged;
@@ -4310,41 +4437,14 @@ var createClaudeTranscriptUsageEnricher = (options = {}) => {
4310
4437
  return unchanged;
4311
4438
  }
4312
4439
  if (hasUsage(record)) {
4313
- const size = await fileSize(transcriptPath);
4314
- return typeof size === "number" ? { payload: input.payload, cursor: { source, offset: size } } : unchanged;
4315
- }
4316
- const attach = (model, usage, partial) => ({
4317
- ...record,
4318
- ...record.model === void 0 && model !== void 0 ? { model } : {},
4319
- ...usage === void 0 ? {} : { usage, usage_partial: partial }
4320
- });
4321
- if (cursor !== void 0) {
4322
- const range = await readClaudeTranscriptRange(transcriptPath, cursor.offset, options);
4323
- if (range.status === "found") {
4324
- return {
4325
- payload: attach(range.model, range.usage, false),
4326
- cursor: { source, offset: range.endOffset },
4327
- notes: [`summed ${String(range.requestCount)} request(s) since the last stop`]
4328
- };
4329
- }
4330
- if (range.reason !== "truncated" && range.reason !== "over-cap") {
4331
- return { ...unchanged, notes: [`transcript range not read (${range.reason}); cursor kept`] };
4332
- }
4333
- }
4334
- const tail = await boundedTail(transcriptPath, options);
4335
- if (tail === TIMED_OUT || !("turn" in tail)) {
4336
- return { ...unchanged, notes: [`transcript tail not read (${tail === TIMED_OUT ? "timeout" : tail.reason})`] };
4440
+ return skipAttached(input.payload, transcriptPath);
4337
4441
  }
4338
- const why = cursor === void 0 ? "no cursor for this transcript" : "range not summable within bounds";
4339
- return {
4340
- payload: tail.turn.status === "found" ? attach(tail.turn.model, tail.turn.usage, true) : input.payload,
4341
- cursor: { source, offset: tail.endOffset },
4342
- notes: [`${why}; attached the last request only (usage_partial)`]
4343
- };
4442
+ return attachSince(record, transcriptPath, cursor?.offset, void 0);
4344
4443
  };
4345
4444
  return Object.freeze({
4346
4445
  id: CLAUDE_TRANSCRIPT_USAGE_ENRICHER_ID,
4347
4446
  providerId: CLAUDE_CODE_PROVIDER_ID,
4447
+ cursorScope: subagentCursorScope,
4348
4448
  enrich
4349
4449
  });
4350
4450
  };
@@ -7334,7 +7434,7 @@ var resolveDeliveryIdentity = (input) => {
7334
7434
  };
7335
7435
 
7336
7436
  // src/runtime/hook.ts
7337
- import { z as z23 } from "zod";
7437
+ import { z as z24 } from "zod";
7338
7438
 
7339
7439
  // src/runtime/target-resolution.ts
7340
7440
  import * as path2 from "path";
@@ -7503,8 +7603,200 @@ var withOptionalSessionLock = async (store, sessionId, fn, options) => {
7503
7603
  return fn();
7504
7604
  };
7505
7605
 
7606
+ // src/runtime/session-context.ts
7607
+ import { open as open2 } from "fs/promises";
7608
+ import * as path3 from "path";
7609
+ import { z as z23 } from "zod";
7610
+ var SESSION_CONTEXT_FILE_VERSION = 1;
7611
+ var DEFAULT_SESSION_CONTEXT_MAX_BYTES = 256 * 1024;
7612
+ var DEFAULT_SESSION_CONTEXT_BUDGET_MILLIS = 100;
7613
+ var MAX_SESSION_CONTEXT_SEGMENTS = 1024;
7614
+ var SESSION_CONTEXT_AGENT_TOOLS = Object.freeze({
7615
+ "claude-code": "claude_code",
7616
+ codex: "codex",
7617
+ cursor: "cursor",
7618
+ "gemini-cli": "gemini_cli",
7619
+ antigravity: "antigravity"
7620
+ });
7621
+ var sessionContextAgentTool = (providerId) => Object.hasOwn(SESSION_CONTEXT_AGENT_TOOLS, providerId) ? SESSION_CONTEXT_AGENT_TOOLS[providerId] : void 0;
7622
+ var SESSION_FILE_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/;
7623
+ var isSessionContextFileName = (sessionId) => SESSION_FILE_NAME_PATTERN.test(sessionId) && !sessionId.includes("..");
7624
+ var sessionContextFilePath = (dir, providerId, sessionId) => {
7625
+ const tool = sessionContextAgentTool(providerId);
7626
+ if (tool === void 0 || !isSessionContextFileName(sessionId) || !path3.isAbsolute(dir)) {
7627
+ return void 0;
7628
+ }
7629
+ return path3.join(dir, tool, `${sessionId}.json`);
7630
+ };
7631
+ var RESERVED_CONTEXT_KEYS = /* @__PURE__ */ new Set([
7632
+ "session.id",
7633
+ "trace_id",
7634
+ "span_id",
7635
+ "parent_span_id",
7636
+ "gen_ai.conversation.id",
7637
+ "factory.local"
7638
+ ]);
7639
+ var RESERVED_CONTEXT_PREFIXES = Object.freeze(["factory.local.", "otelhook."]);
7640
+ var isReservedSessionContextKey = (key) => RESERVED_CONTEXT_KEYS.has(key) || RESERVED_CONTEXT_PREFIXES.some((prefix) => key.startsWith(prefix));
7641
+ var sanitizeSessionContextAttributes = (attributes) => {
7642
+ const kept = {};
7643
+ let count = 0;
7644
+ for (const [key, value] of Object.entries(attributes)) {
7645
+ if (count >= MAX_RESOURCE_ATTRIBUTES) {
7646
+ break;
7647
+ }
7648
+ if (checkResourceAttributeKey(key) !== void 0 || isReservedSessionContextKey(key)) {
7649
+ continue;
7650
+ }
7651
+ if (typeof value === "string") {
7652
+ if (value.length > MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH) {
7653
+ continue;
7654
+ }
7655
+ } else if (typeof value === "number") {
7656
+ if (!Number.isFinite(value)) {
7657
+ continue;
7658
+ }
7659
+ } else if (typeof value !== "boolean") {
7660
+ continue;
7661
+ }
7662
+ kept[key] = value;
7663
+ count += 1;
7664
+ }
7665
+ return kept;
7666
+ };
7667
+ 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})$/;
7668
+ var isoInstantSchema = z23.string().max(64).regex(ISO_INSTANT_PATTERN).transform((value, ctx) => {
7669
+ const millis = Date.parse(value);
7670
+ if (!Number.isFinite(millis)) {
7671
+ ctx.issues.push({ code: "custom", input: value, message: "not a valid instant" });
7672
+ return z23.NEVER;
7673
+ }
7674
+ return millis;
7675
+ });
7676
+ var segmentSchema = z23.object({
7677
+ from: isoInstantSchema,
7678
+ to: isoInstantSchema.nullable(),
7679
+ reason: z23.string().max(256).optional(),
7680
+ attributes: z23.record(z23.string(), z23.unknown())
7681
+ });
7682
+ var sessionContextFileSchema = z23.object({
7683
+ version: z23.literal(SESSION_CONTEXT_FILE_VERSION),
7684
+ agentTool: z23.string().max(64).optional(),
7685
+ sessionId: z23.string().max(256).optional(),
7686
+ segments: z23.array(segmentSchema).max(MAX_SESSION_CONTEXT_SEGMENTS)
7687
+ });
7688
+ var parseSessionContextFile = (value, expected) => {
7689
+ const parsed = sessionContextFileSchema.safeParse(value);
7690
+ if (!parsed.success) {
7691
+ return void 0;
7692
+ }
7693
+ const file = parsed.data;
7694
+ 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) {
7695
+ return void 0;
7696
+ }
7697
+ return file.segments.map((segment) => ({
7698
+ from: segment.from,
7699
+ to: segment.to,
7700
+ attributes: sanitizeSessionContextAttributes(segment.attributes)
7701
+ }));
7702
+ };
7703
+ var segmentInForce = (segments, at) => {
7704
+ let best;
7705
+ for (const segment of segments) {
7706
+ if (segment.from <= at && (segment.to === null || at < segment.to)) {
7707
+ if (best === void 0 || segment.from >= best.from) {
7708
+ best = segment;
7709
+ }
7710
+ }
7711
+ }
7712
+ return best;
7713
+ };
7714
+ var stampSessionContext = (events, segments) => events.map((event3) => {
7715
+ const { contextAttributes: _discarded, ...rest } = event3;
7716
+ const segment = segments === void 0 ? void 0 : segmentInForce(segments, event3.occurredAt);
7717
+ if (segment === void 0 || Object.keys(segment.attributes).length === 0) {
7718
+ return _discarded === void 0 ? event3 : rest;
7719
+ }
7720
+ return { ...rest, contextAttributes: { ...segment.attributes } };
7721
+ });
7722
+ var readBounded = async (file, maxBytes) => {
7723
+ let handle;
7724
+ try {
7725
+ handle = await open2(file, "r");
7726
+ } catch {
7727
+ return void 0;
7728
+ }
7729
+ try {
7730
+ const stats = await handle.stat();
7731
+ if (!stats.isFile() || stats.size > maxBytes) {
7732
+ return void 0;
7733
+ }
7734
+ const buffer = Buffer.alloc(maxBytes + 1);
7735
+ let length = 0;
7736
+ while (length < buffer.length) {
7737
+ const { bytesRead } = await handle.read(buffer, length, buffer.length - length, length);
7738
+ if (bytesRead === 0) {
7739
+ break;
7740
+ }
7741
+ length += bytesRead;
7742
+ }
7743
+ if (length > maxBytes) {
7744
+ return void 0;
7745
+ }
7746
+ return buffer.subarray(0, length).toString("utf8");
7747
+ } catch {
7748
+ return void 0;
7749
+ } finally {
7750
+ await handle.close().catch(() => void 0);
7751
+ }
7752
+ };
7753
+ var createDirectorySessionContextReader = (options) => {
7754
+ const maxBytes = options.maxBytes ?? DEFAULT_SESSION_CONTEXT_MAX_BYTES;
7755
+ const budgetMillis = options.budgetMillis ?? DEFAULT_SESSION_CONTEXT_BUDGET_MILLIS;
7756
+ const readOnce = async (providerId, sessionId) => {
7757
+ const file = sessionContextFilePath(options.dir, providerId, sessionId);
7758
+ if (file === void 0) {
7759
+ return void 0;
7760
+ }
7761
+ const text = await readBounded(file, maxBytes);
7762
+ if (text === void 0) {
7763
+ return void 0;
7764
+ }
7765
+ let decoded;
7766
+ try {
7767
+ decoded = JSON.parse(text);
7768
+ } catch {
7769
+ return void 0;
7770
+ }
7771
+ const agentTool = sessionContextAgentTool(providerId);
7772
+ return parseSessionContextFile(decoded, {
7773
+ ...agentTool === void 0 ? {} : { agentTool },
7774
+ sessionId
7775
+ });
7776
+ };
7777
+ return {
7778
+ read: async (request) => {
7779
+ let timer;
7780
+ const timeout = new Promise((resolve5) => {
7781
+ timer = setTimeout(() => resolve5(void 0), budgetMillis);
7782
+ timer.unref?.();
7783
+ });
7784
+ try {
7785
+ return await Promise.race([
7786
+ readOnce(request.providerId, request.sessionId).catch(() => void 0),
7787
+ timeout
7788
+ ]);
7789
+ } finally {
7790
+ if (timer !== void 0) {
7791
+ clearTimeout(timer);
7792
+ }
7793
+ }
7794
+ }
7795
+ };
7796
+ };
7797
+
7506
7798
  // src/runtime/hook.ts
7507
- var usageScopeSchema = z23.enum(["session", "generation", "subagent"]);
7799
+ var usageScopeSchema = z24.enum(["session", "generation", "subagent"]);
7508
7800
  var classifyDurability = (input) => {
7509
7801
  if (!input.attempted) {
7510
7802
  return "nothing-to-deliver";
@@ -7563,7 +7855,7 @@ var usageScopeOf = (event3) => {
7563
7855
  };
7564
7856
  var sequenceKey = (sessionId) => `sequence:${sessionId}`;
7565
7857
  var sessionModelKey = (sessionId) => `model:${sessionId}`;
7566
- var readCursorKey = (enricherId, sessionId) => `cursor:${enricherId}:${sessionId}`;
7858
+ var readCursorKey = (enricherId, sessionId, scope) => scope === void 0 ? `cursor:${enricherId}:${sessionId}` : `cursor:${enricherId}:${sessionId}:${scope}`;
7567
7859
  var UNKNOWN_MODEL_ID = "unknown";
7568
7860
  var latestSessionModel = (events) => {
7569
7861
  let latest;
@@ -7631,7 +7923,17 @@ var createOtelHook = (deps) => {
7631
7923
  if (enricher.providerId !== providerId) {
7632
7924
  continue;
7633
7925
  }
7634
- const key = readCursorKey(enricher.id, sessionId);
7926
+ let scope;
7927
+ try {
7928
+ scope = enricher.cursorScope?.(current);
7929
+ } catch (thrown) {
7930
+ logger.warn("payload enricher failed; parsing the payload as delivered", {
7931
+ "enricher.id": enricher.id,
7932
+ "error.name": thrown instanceof Error ? thrown.name : typeof thrown
7933
+ });
7934
+ continue;
7935
+ }
7936
+ const key = readCursorKey(enricher.id, sessionId, scope);
7635
7937
  let cursor;
7636
7938
  try {
7637
7939
  const record = await deps.stateStore.read(key);
@@ -8213,6 +8515,10 @@ var createOtelHook = (deps) => {
8213
8515
  });
8214
8516
  }
8215
8517
  }
8518
+ batch = stampSessionContext(
8519
+ batch,
8520
+ !suppress && batch.length > 0 && deps.sessionContext !== void 0 ? await readSessionContext(deps.sessionContext, detection.providerId, identity.sessionId) : void 0
8521
+ );
8216
8522
  let emitted = 0;
8217
8523
  let exportRejected = 0;
8218
8524
  if (!suppress && batch.length > 0) {
@@ -8328,6 +8634,13 @@ var createOtelHook = (deps) => {
8328
8634
  };
8329
8635
  return { resolveDelivery, ingest, flush, shutdown, config };
8330
8636
  };
8637
+ var readSessionContext = async (reader, providerId, sessionId) => {
8638
+ try {
8639
+ return await reader.read({ providerId, sessionId });
8640
+ } catch {
8641
+ return void 0;
8642
+ }
8643
+ };
8331
8644
  var buildErrorEvents = (diagnostics, identity, sequenceBase, ids, privacy) => {
8332
8645
  const events = [];
8333
8646
  for (const [index, info] of diagnostics.slice(0, MAX_ERROR_EVENTS).entries()) {
@@ -8362,8 +8675,8 @@ var buildErrorEvents = (diagnostics, identity, sequenceBase, ids, privacy) => {
8362
8675
  };
8363
8676
 
8364
8677
  // src/runtime/git-worktree.ts
8365
- import { lstat, open as open2, stat as stat2 } from "fs/promises";
8366
- import * as path3 from "path";
8678
+ import { lstat, open as open3, stat as stat2 } from "fs/promises";
8679
+ import * as path4 from "path";
8367
8680
  var MAX_WORKTREE_WALK_DEPTH = 128;
8368
8681
  var MAX_GIT_FILE_BYTES = 4096;
8369
8682
  var MAX_CACHE_ENTRIES = 1024;
@@ -8371,10 +8684,10 @@ var DEFAULT_WORKTREE_CACHE_TTL_MILLIS = 5e3;
8371
8684
  var MAX_BRANCH_NAME_LENGTH = 255;
8372
8685
  var ABSENT = Object.freeze({ kind: "absent" });
8373
8686
  var INVALID = Object.freeze({ kind: "invalid" });
8374
- var readBounded = async (filePath) => {
8687
+ var readBounded2 = async (filePath) => {
8375
8688
  let handle;
8376
8689
  try {
8377
- handle = await open2(filePath, "r");
8690
+ handle = await open3(filePath, "r");
8378
8691
  const buffer = Buffer.alloc(MAX_GIT_FILE_BYTES);
8379
8692
  const { bytesRead } = await handle.read(buffer, 0, MAX_GIT_FILE_BYTES, 0);
8380
8693
  return buffer.subarray(0, bytesRead).toString("utf8");
@@ -8395,7 +8708,7 @@ var parseHeadBranch = (head) => {
8395
8708
  return branch;
8396
8709
  };
8397
8710
  var firstLine = (content) => content.split(/\r?\n/, 1)[0]?.trim() ?? "";
8398
- var resolveGitPath = (target, base) => target === void 0 || target.length === 0 || target.includes("\0") ? void 0 : path3.resolve(base, target);
8711
+ var resolveGitPath = (target, base) => target === void 0 || target.length === 0 || target.includes("\0") ? void 0 : path4.resolve(base, target);
8399
8712
  var parseGitDirFile = (content, worktreeRoot) => {
8400
8713
  const line = firstLine(content);
8401
8714
  return resolveGitPath(
@@ -8421,17 +8734,17 @@ var isDirectory = async (directory) => {
8421
8734
  }
8422
8735
  };
8423
8736
  var repositoryOf = async (worktreeRoot, gitDir) => {
8424
- const commonDirFile = path3.join(gitDir, "commondir");
8425
- const content = await readBounded(commonDirFile);
8737
+ const commonDirFile = path4.join(gitDir, "commondir");
8738
+ const content = await readBounded2(commonDirFile);
8426
8739
  if (content === void 0) {
8427
8740
  return await isMissing(commonDirFile) ? { kind: "main", mainRoot: worktreeRoot } : { kind: "linked" };
8428
8741
  }
8429
8742
  const commonDir = parseCommonDirFile(content, gitDir);
8430
- const mainRoot = commonDir !== void 0 && path3.basename(commonDir) === ".git" && await isDirectory(commonDir) ? path3.dirname(commonDir) : void 0;
8743
+ const mainRoot = commonDir !== void 0 && path4.basename(commonDir) === ".git" && await isDirectory(commonDir) ? path4.dirname(commonDir) : void 0;
8431
8744
  return { kind: "linked", ...mainRoot === void 0 ? {} : { mainRoot } };
8432
8745
  };
8433
8746
  var probeDirectory = async (directory) => {
8434
- const dotGit = path3.join(directory, ".git");
8747
+ const dotGit = path4.join(directory, ".git");
8435
8748
  let info;
8436
8749
  try {
8437
8750
  info = await stat2(dotGit);
@@ -8442,13 +8755,13 @@ var probeDirectory = async (directory) => {
8442
8755
  if (info.isDirectory()) {
8443
8756
  gitDir = dotGit;
8444
8757
  } else if (info.isFile()) {
8445
- const content = await readBounded(dotGit);
8758
+ const content = await readBounded2(dotGit);
8446
8759
  gitDir = content === void 0 ? void 0 : parseGitDirFile(content, directory);
8447
8760
  }
8448
8761
  if (gitDir === void 0) {
8449
8762
  return INVALID;
8450
8763
  }
8451
- const head = await readBounded(path3.join(gitDir, "HEAD"));
8764
+ const head = await readBounded2(path4.join(gitDir, "HEAD"));
8452
8765
  if (head === void 0) {
8453
8766
  return INVALID;
8454
8767
  }
@@ -8478,10 +8791,10 @@ var createFilesystemWorktreeLocator = (options = {}) => {
8478
8791
  };
8479
8792
  const locate = async (absolutePath) => {
8480
8793
  try {
8481
- if (!path3.isAbsolute(absolutePath) || absolutePath.includes("\0")) {
8794
+ if (!path4.isAbsolute(absolutePath) || absolutePath.includes("\0")) {
8482
8795
  return void 0;
8483
8796
  }
8484
- let directory = path3.resolve(absolutePath);
8797
+ let directory = path4.resolve(absolutePath);
8485
8798
  for (let depth = 0; depth < MAX_WORKTREE_WALK_DEPTH; depth += 1) {
8486
8799
  const probe = await cachedProbe(directory);
8487
8800
  if (probe.kind === "worktree") {
@@ -8490,7 +8803,7 @@ var createFilesystemWorktreeLocator = (options = {}) => {
8490
8803
  if (probe.kind === "invalid") {
8491
8804
  return void 0;
8492
8805
  }
8493
- const parent = path3.dirname(directory);
8806
+ const parent = path4.dirname(directory);
8494
8807
  if (parent === directory) {
8495
8808
  return void 0;
8496
8809
  }
@@ -8721,7 +9034,7 @@ import {
8721
9034
  } from "@opentelemetry/semantic-conventions/incubating";
8722
9035
 
8723
9036
  // src/version.ts
8724
- var VERSION = "0.11.0";
9037
+ var VERSION = "0.13.0";
8725
9038
 
8726
9039
  // src/telemetry/export-identity.ts
8727
9040
  import { ATTR_SESSION_ID } from "@opentelemetry/semantic-conventions/incubating";
@@ -8774,6 +9087,11 @@ var passthroughResourceAttributes = (resource) => {
8774
9087
  }
8775
9088
  return attributes;
8776
9089
  };
9090
+ var contextAttributesOf = (event3) => event3.contextAttributes === void 0 ? {} : { ...event3.contextAttributes };
9091
+ var profileAttributes = (event3, resource) => ({
9092
+ ...passthroughResourceAttributes(resource),
9093
+ ...contextAttributesOf(event3)
9094
+ });
8777
9095
  var resolveExportedSessionId = (eventSessionId, resource) => {
8778
9096
  for (const key of EXTERNAL_SESSION_KEY_ATTRIBUTES) {
8779
9097
  const supplied = resource.attributes[key];
@@ -8794,6 +9112,8 @@ var hexTraceAttributes = (ids) => ({
8794
9112
  var exportIdentityAttributes = (event3, resource, ids) => {
8795
9113
  const { sessionId, providerSessionId } = resolveExportedSessionId(event3.sessionId, resource);
8796
9114
  return {
9115
+ // First, so nothing in the profile layer can replace an identity attribute.
9116
+ ...profileAttributes(event3, resource),
8797
9117
  [ATTR_SESSION_ID]: sessionId,
8798
9118
  [ATTR_OTELHOOK_SESSION_ID]: providerSessionId,
8799
9119
  [ATTR_GEN_AI_CONVERSATION_ID]: providerSessionId,
@@ -8802,7 +9122,6 @@ var exportIdentityAttributes = (event3, resource, ids) => {
8802
9122
  ...event3.provenance.providerVersion === void 0 ? {} : { [ATTR_OTELHOOK_PROVIDER_VERSION]: event3.provenance.providerVersion },
8803
9123
  [ATTR_OTELHOOK_WORKSPACE_ID]: event3.workspace.workspaceId,
8804
9124
  ...event3.subagentId === void 0 ? {} : { [ATTR_OTELHOOK_SUBAGENT_ID]: event3.subagentId },
8805
- ...passthroughResourceAttributes(resource),
8806
9125
  ...hexTraceAttributes(ids)
8807
9126
  };
8808
9127
  };
@@ -8953,12 +9272,12 @@ var pickTarget = (attributes) => {
8953
9272
  }
8954
9273
  return picked;
8955
9274
  };
8956
- var withoutTarget = (attributes, resource) => {
9275
+ var withoutTarget = (attributes, resource, event3) => {
8957
9276
  const rest = { ...attributes };
8958
9277
  for (const key of TARGET_KEYS) {
8959
9278
  delete rest[key];
8960
9279
  }
8961
- return { ...rest, ...pickTarget(passthroughResourceAttributes(resource)) };
9280
+ return { ...rest, ...pickTarget(profileAttributes(event3, resource)) };
8962
9281
  };
8963
9282
  var rankOf = (candidate) => {
8964
9283
  const source = candidate[ATTR_OTELHOOK_TARGET_SOURCE];
@@ -9063,7 +9382,7 @@ var buildLifecycleSpan = (plan, resource, scope) => {
9063
9382
  name = "session";
9064
9383
  kind = SpanKind.INTERNAL;
9065
9384
  attributes = {
9066
- ...withoutTarget(attributes, resource),
9385
+ ...withoutTarget(attributes, resource, anchor),
9067
9386
  ...strongestTarget([pickTarget(resolved.recovered), start === void 0 ? {} : targetAttributes(start)]),
9068
9387
  ...start?.agentName === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_NAME]: start.agentName },
9069
9388
  ...start?.agentVersion === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_VERSION]: start.agentVersion },
@@ -9105,7 +9424,7 @@ var buildLifecycleSpan = (plan, resource, scope) => {
9105
9424
  kind = SpanKind.CLIENT;
9106
9425
  attributes = {
9107
9426
  // Target keys are re-chosen below as one unit, never mixed across edges.
9108
- ...withoutTarget(attributes, resource),
9427
+ ...withoutTarget(attributes, resource, anchor),
9109
9428
  [ATTR_GEN_AI_TOOL_NAME]: toolName,
9110
9429
  [ATTR_GEN_AI_TOOL_CALL_ID]: start?.toolCallId ?? end?.toolCallId ?? group.ref.scopeKey,
9111
9430
  ...start?.toolKind === void 0 ? {} : { [ATTR_OTELHOOK_TOOL_KIND]: start.toolKind },
@@ -9936,6 +10255,9 @@ var ATTR_OTELHOOK_PROVIDER_ID2 = "otelhook.provider.id";
9936
10255
  var ATTR_OTELHOOK_OUTCOME2 = "otelhook.outcome";
9937
10256
  var ATTR_OTELHOOK_SESSION_KIND = "otelhook.session.kind";
9938
10257
  var commonAttributes = (event3, resource, includeSessionId) => ({
10258
+ // Session context first, so the metric's own attributes always win; and never
10259
+ // anything account-shaped, whatever the context says.
10260
+ ...event3.contextAttributes === void 0 ? {} : withoutAccountIdentity(event3.contextAttributes),
9939
10261
  [ATTR_OTELHOOK_PROVIDER_ID2]: event3.provenance.providerId,
9940
10262
  ...includeSessionId ? { [ATTR_SESSION_ID2]: resolveExportedSessionId(event3.sessionId, resource).sessionId } : {}
9941
10263
  });
@@ -9982,6 +10304,9 @@ var deriveMetricObservations = (input) => {
9982
10304
  if (recovered !== void 0) {
9983
10305
  return end.occurredAt - recovered.startMillis;
9984
10306
  }
10307
+ if (end.subagentId !== void 0) {
10308
+ return void 0;
10309
+ }
9985
10310
  const turn = lastPromptInBatch?.get(end.sessionId) ?? input.turnStart?.(end.sessionId);
9986
10311
  return turn === void 0 || turn > end.occurredAt ? void 0 : end.occurredAt - turn;
9987
10312
  };
@@ -10363,8 +10688,8 @@ var createBoundedMemoryStateStore = (options) => {
10363
10688
 
10364
10689
  // src/state/filesystem-store.ts
10365
10690
  import { randomBytes as randomBytes2 } from "crypto";
10366
- import { mkdir, open as open3, readFile, readdir, rename, unlink, writeFile } from "fs/promises";
10367
- import * as path4 from "path";
10691
+ import { mkdir, open as open4, readFile, readdir, rename, unlink, writeFile } from "fs/promises";
10692
+ import * as path5 from "path";
10368
10693
 
10369
10694
  // src/state/keys.ts
10370
10695
  import { createHash as createHash6 } from "crypto";
@@ -10396,10 +10721,10 @@ var wrapFsError = (thrown, operation) => {
10396
10721
  };
10397
10722
  var createFilesystemStateStore = (options) => {
10398
10723
  const [providerSegment, installationSegment] = namespaceSegments(options);
10399
- const baseDir = path4.join(options.rootDir, providerSegment, installationSegment);
10400
- const recordsDir = path4.join(baseDir, "records");
10401
- const quarantineDir = path4.join(baseDir, "quarantine");
10402
- const locksDir = path4.join(baseDir, "locks");
10724
+ const baseDir = path5.join(options.rootDir, providerSegment, installationSegment);
10725
+ const recordsDir = path5.join(baseDir, "records");
10726
+ const quarantineDir = path5.join(baseDir, "quarantine");
10727
+ const locksDir = path5.join(baseDir, "locks");
10403
10728
  const lockTimeoutMillis = options.lockTimeoutMillis ?? 5e3;
10404
10729
  const lockStaleMillis = options.lockStaleMillis ?? 3e4;
10405
10730
  const lockPollIntervalMillis = options.lockPollIntervalMillis ?? 25;
@@ -10423,11 +10748,11 @@ var createFilesystemStateStore = (options) => {
10423
10748
  throw wrapFsError(thrown, "ensure-dirs");
10424
10749
  }
10425
10750
  };
10426
- const recordPath = (key) => path4.join(recordsDir, `${keyDigest(key)}.json`);
10427
- const tempPath = (key) => path4.join(recordsDir, `.tmp-${keyDigest(key)}-${randomBytes2(6).toString("hex")}.json`);
10428
- const lockPath = (sessionId) => path4.join(locksDir, `${sanitizeSegment(sessionId)}.lock`);
10751
+ const recordPath = (key) => path5.join(recordsDir, `${keyDigest(key)}.json`);
10752
+ const tempPath = (key) => path5.join(recordsDir, `.tmp-${keyDigest(key)}-${randomBytes2(6).toString("hex")}.json`);
10753
+ const lockPath = (sessionId) => path5.join(locksDir, `${sanitizeSegment(sessionId)}.lock`);
10429
10754
  const quarantine = async (filePath, key, reason) => {
10430
- const dest = path4.join(quarantineDir, `${options.clock.now()}-${keyDigest(key)}-${reason}.json`);
10755
+ const dest = path5.join(quarantineDir, `${options.clock.now()}-${keyDigest(key)}-${reason}.json`);
10431
10756
  try {
10432
10757
  await rename(filePath, dest);
10433
10758
  } catch {
@@ -10491,7 +10816,7 @@ var createFilesystemStateStore = (options) => {
10491
10816
  const startedAt = options.clock.monotonicMillis();
10492
10817
  for (; ; ) {
10493
10818
  try {
10494
- const handle = await open3(filePath, "wx");
10819
+ const handle = await open4(filePath, "wx");
10495
10820
  try {
10496
10821
  await handle.writeFile(JSON.stringify({ pid: process.pid, acquiredAt: options.clock.now() }));
10497
10822
  } finally {
@@ -10559,7 +10884,7 @@ var createFilesystemStateStore = (options) => {
10559
10884
  }
10560
10885
  let raw;
10561
10886
  try {
10562
- raw = await readFile(path4.join(recordsDir, entry), "utf8");
10887
+ raw = await readFile(path5.join(recordsDir, entry), "utf8");
10563
10888
  } catch {
10564
10889
  continue;
10565
10890
  }
@@ -10612,7 +10937,7 @@ var createFilesystemStateStore = (options) => {
10612
10937
  continue;
10613
10938
  }
10614
10939
  scanned += 1;
10615
- const filePath = path4.join(recordsDir, entry);
10940
+ const filePath = path5.join(recordsDir, entry);
10616
10941
  try {
10617
10942
  const raw = await readFile(filePath, "utf8");
10618
10943
  const envelope = JSON.parse(raw);
@@ -10632,7 +10957,7 @@ var createFilesystemStateStore = (options) => {
10632
10957
  lockEntries = [];
10633
10958
  }
10634
10959
  for (const entry of lockEntries) {
10635
- const filePath = path4.join(locksDir, entry);
10960
+ const filePath = path5.join(locksDir, entry);
10636
10961
  try {
10637
10962
  const raw = await readFile(filePath, "utf8");
10638
10963
  const parsed = JSON.parse(raw);
@@ -10651,7 +10976,7 @@ var createFilesystemStateStore = (options) => {
10651
10976
  // src/telemetry/spool-queue.ts
10652
10977
  import { randomBytes as randomBytes3 } from "crypto";
10653
10978
  import { mkdir as mkdir2, readFile as readFile2, readdir as readdir2, rename as rename2, stat as stat3, unlink as unlink2, writeFile as writeFile2 } from "fs/promises";
10654
- import * as path5 from "path";
10979
+ import * as path6 from "path";
10655
10980
  var EMPTY_SPOOL_DROP_COUNTS = Object.freeze({
10656
10981
  total: 0,
10657
10982
  age: 0,
@@ -10667,7 +10992,7 @@ var enqueuedAtOf = (fileName) => {
10667
10992
  var isCount = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0;
10668
10993
  var readSpoolDropCounts = async (queueDir) => {
10669
10994
  try {
10670
- const parsed = JSON.parse(await readFile2(path5.join(queueDir, SPOOL_DROPS_FILE), "utf8"));
10995
+ const parsed = JSON.parse(await readFile2(path6.join(queueDir, SPOOL_DROPS_FILE), "utf8"));
10671
10996
  if (typeof parsed !== "object" || parsed === null) {
10672
10997
  return EMPTY_SPOOL_DROP_COUNTS;
10673
10998
  }
@@ -10696,7 +11021,7 @@ var readSpoolQueueStats = async (queueDir) => {
10696
11021
  let bytes = 0;
10697
11022
  for (const file of files) {
10698
11023
  try {
10699
- bytes += (await stat3(path5.join(queueDir, file))).size;
11024
+ bytes += (await stat3(path6.join(queueDir, file))).size;
10700
11025
  } catch {
10701
11026
  }
10702
11027
  }
@@ -10712,8 +11037,8 @@ var DEFAULT_DRAIN_MAX_BATCHES = 20;
10712
11037
  var isErrnoException2 = (thrown, code) => thrown instanceof Error && thrown.code === code;
10713
11038
  var createSpoolQueue = (options) => {
10714
11039
  const [providerSegment, installationSegment] = namespaceSegments(options);
10715
- const queueDir = path5.join(options.rootDir, providerSegment, installationSegment, options.queueName);
10716
- const corruptDir = path5.join(
11040
+ const queueDir = path6.join(options.rootDir, providerSegment, installationSegment, options.queueName);
11041
+ const corruptDir = path6.join(
10717
11042
  options.rootDir,
10718
11043
  providerSegment,
10719
11044
  installationSegment,
@@ -10760,9 +11085,9 @@ var createSpoolQueue = (options) => {
10760
11085
  [reason]: current[reason] + dropped,
10761
11086
  lastDroppedAt: options.clock.now()
10762
11087
  };
10763
- const tmp = path5.join(queueDir, `.tmp-${randomBytes3(6).toString("hex")}.drops`);
11088
+ const tmp = path6.join(queueDir, `.tmp-${randomBytes3(6).toString("hex")}.drops`);
10764
11089
  await writeFile2(tmp, JSON.stringify(next), "utf8");
10765
- await rename2(tmp, path5.join(queueDir, SPOOL_DROPS_FILE));
11090
+ await rename2(tmp, path6.join(queueDir, SPOOL_DROPS_FILE));
10766
11091
  } catch {
10767
11092
  }
10768
11093
  options.logger?.warn("durable spool dropped batches", {
@@ -10778,7 +11103,7 @@ var createSpoolQueue = (options) => {
10778
11103
  let bytes = 0;
10779
11104
  if (options.maxBytes !== void 0) {
10780
11105
  try {
10781
- bytes = (await stat3(path5.join(queueDir, name))).size;
11106
+ bytes = (await stat3(path6.join(queueDir, name))).size;
10782
11107
  } catch {
10783
11108
  continue;
10784
11109
  }
@@ -10792,7 +11117,7 @@ var createSpoolQueue = (options) => {
10792
11117
  let removed = 0;
10793
11118
  for (const file of files) {
10794
11119
  try {
10795
- await unlink2(path5.join(queueDir, file.name));
11120
+ await unlink2(path6.join(queueDir, file.name));
10796
11121
  removed += 1;
10797
11122
  } catch {
10798
11123
  }
@@ -10852,8 +11177,8 @@ var createSpoolQueue = (options) => {
10852
11177
  }
10853
11178
  }
10854
11179
  const fileName = `${String(now).padStart(16, "0")}-${randomBytes3(6).toString("hex")}.json`;
10855
- const target = path5.join(queueDir, fileName);
10856
- const tmp = path5.join(queueDir, `.tmp-${randomBytes3(6).toString("hex")}.json`);
11180
+ const target = path6.join(queueDir, fileName);
11181
+ const tmp = path6.join(queueDir, `.tmp-${randomBytes3(6).toString("hex")}.json`);
10857
11182
  await writeFile2(tmp, serialized, "utf8");
10858
11183
  await rename2(tmp, target);
10859
11184
  return { spooled: true };
@@ -10883,7 +11208,7 @@ var createSpoolQueue = (options) => {
10883
11208
  if (fileName === void 0) {
10884
11209
  break;
10885
11210
  }
10886
- const filePath = path5.join(queueDir, fileName);
11211
+ const filePath = path6.join(queueDir, fileName);
10887
11212
  const quarantine = async (rejection) => {
10888
11213
  quarantined += 1;
10889
11214
  options.logger?.error("durable spool quarantined an unusable batch", {
@@ -10892,7 +11217,7 @@ var createSpoolQueue = (options) => {
10892
11217
  "spool.queue": options.queueName
10893
11218
  });
10894
11219
  try {
10895
- await rename2(filePath, path5.join(corruptDir, fileName));
11220
+ await rename2(filePath, path6.join(corruptDir, fileName));
10896
11221
  } catch {
10897
11222
  await unlink2(filePath).catch(() => void 0);
10898
11223
  }
@@ -11129,6 +11454,33 @@ var replayResource = (attributes, policy) => {
11129
11454
  }
11130
11455
  return resourceFromAttributes(safe);
11131
11456
  };
11457
+ var agreedContextAttributes = (events) => {
11458
+ const [first, ...rest] = events;
11459
+ if (first?.contextAttributes === void 0) {
11460
+ return {};
11461
+ }
11462
+ const agreed = { ...first.contextAttributes };
11463
+ for (const event3 of rest) {
11464
+ for (const key of Object.keys(agreed)) {
11465
+ if (event3.contextAttributes?.[key] !== agreed[key]) {
11466
+ delete agreed[key];
11467
+ }
11468
+ }
11469
+ }
11470
+ return agreed;
11471
+ };
11472
+ var resourceWithContext = (resource, context) => {
11473
+ const overrides = {};
11474
+ for (const [key, value] of Object.entries(context)) {
11475
+ if (Object.hasOwn(resource.attributes, key) && !isReservedResourceAttributeKey(key) && resource.attributes[key] !== value) {
11476
+ overrides[key] = value;
11477
+ }
11478
+ }
11479
+ if (Object.keys(overrides).length === 0) {
11480
+ return resource;
11481
+ }
11482
+ return resourceFromAttributes({ ...resource.attributes, ...overrides });
11483
+ };
11132
11484
 
11133
11485
  // src/telemetry/otlp-sink.ts
11134
11486
  var chunk = (items, size) => {
@@ -11213,10 +11565,10 @@ var createOtlpTraceSink = (options) => {
11213
11565
  const exportSpans = (spans) => new Promise((resolve5) => {
11214
11566
  exporter.export([...spans], (result) => resolve5(result));
11215
11567
  });
11216
- const toSpoolBatch = (spans) => ({
11568
+ const toSpoolBatch = (spans, batchResource) => ({
11217
11569
  providerId: options.providerId,
11218
11570
  installationId: options.installationId,
11219
- resourceAttributes: { ...resource.attributes },
11571
+ resourceAttributes: { ...batchResource.attributes },
11220
11572
  instrumentationScope: { name: scope.name, ...scope.version === void 0 ? {} : { version: scope.version } },
11221
11573
  spans: spans.map(serializeSpan),
11222
11574
  enqueuedAt: options.clock.now()
@@ -11246,8 +11598,9 @@ var createOtlpTraceSink = (options) => {
11246
11598
  return { accepted: 0, rejected: 0, errors: [] };
11247
11599
  }
11248
11600
  const resolved = await resolveCorrelations(events);
11601
+ const batchResource = resourceWithContext(resource, agreedContextAttributes(events));
11249
11602
  const spans = canonicalEventsToReadableSpans(events, {
11250
- resource,
11603
+ resource: batchResource,
11251
11604
  instrumentationScope: scope,
11252
11605
  correlations: resolved.correlations,
11253
11606
  ...resolved.available === void 0 ? {} : { correlationAvailable: resolved.available }
@@ -11273,7 +11626,7 @@ var createOtlpTraceSink = (options) => {
11273
11626
  health.recordFailure("telemetry-export-failure", batch.length, options.clock.now());
11274
11627
  const permanent = isPermanentExportFailure(result);
11275
11628
  if (options.spool !== void 0 && !permanent) {
11276
- const spoolResult = await options.spool.enqueue(toSpoolBatch(batch)).catch(() => ({
11629
+ const spoolResult = await options.spool.enqueue(toSpoolBatch(batch, batchResource)).catch(() => ({
11277
11630
  spooled: false,
11278
11631
  reason: "capacity-exceeded"
11279
11632
  }));
@@ -12008,10 +12361,10 @@ var createOtlpLogSink = (options) => {
12008
12361
  const exportRecords = (records) => new Promise((resolve5) => {
12009
12362
  exporter.export([...records], (result) => resolve5(result));
12010
12363
  });
12011
- const toSpoolBatch = (records) => ({
12364
+ const toSpoolBatch = (records, batchResource) => ({
12012
12365
  providerId: options.providerId,
12013
12366
  installationId: options.installationId,
12014
- resourceAttributes: { ...resource.attributes },
12367
+ resourceAttributes: { ...batchResource.attributes },
12015
12368
  instrumentationScope: {
12016
12369
  name: scope.name,
12017
12370
  ...scope.version === void 0 ? {} : { version: scope.version }
@@ -12046,8 +12399,9 @@ var createOtlpLogSink = (options) => {
12046
12399
  return { accepted: 0, rejected: 0, errors: [] };
12047
12400
  }
12048
12401
  const resolved = await resolveCorrelations(events);
12402
+ const batchResource = resourceWithContext(resource, agreedContextAttributes(events));
12049
12403
  const mapped = canonicalEventsToLogRecords(events, {
12050
- resource,
12404
+ resource: batchResource,
12051
12405
  instrumentationScope: scope,
12052
12406
  content,
12053
12407
  correlations: resolved.correlations,
@@ -12082,7 +12436,7 @@ var createOtlpLogSink = (options) => {
12082
12436
  health.recordFailure("telemetry-export-failure", batch.length, options.clock.now());
12083
12437
  const permanent = isPermanentExportFailure(result);
12084
12438
  if (options.spool !== void 0 && !permanent) {
12085
- const spoolResult = await options.spool.enqueue(toSpoolBatch(batch)).catch(() => ({
12439
+ const spoolResult = await options.spool.enqueue(toSpoolBatch(batch, batchResource)).catch(() => ({
12086
12440
  spooled: false,
12087
12441
  reason: "capacity-exceeded"
12088
12442
  }));
@@ -12434,10 +12788,10 @@ var createOtlpMetricSink = (options) => {
12434
12788
  });
12435
12789
  }
12436
12790
  });
12437
- const toSpoolBatch = (points) => ({
12791
+ const toSpoolBatch = (points, batchResource) => ({
12438
12792
  providerId: options.providerId,
12439
12793
  installationId: options.installationId,
12440
- resourceAttributes: { ...resource.attributes },
12794
+ resourceAttributes: { ...batchResource.attributes },
12441
12795
  instrumentationScope: {
12442
12796
  name: scope.name,
12443
12797
  ...scope.version === void 0 ? {} : { version: scope.version }
@@ -12455,11 +12809,12 @@ var createOtlpMetricSink = (options) => {
12455
12809
  }
12456
12810
  return isPermanentExportFailure(result) ? "discard" : false;
12457
12811
  };
12458
- const exportPoints = async (points) => {
12812
+ const exportPoints = async (points, context) => {
12459
12813
  if (points.length === 0) {
12460
12814
  return { accepted: 0, rejected: 0, errors: [] };
12461
12815
  }
12462
- const result = await exportResourceMetrics(points, resource, scope);
12816
+ const batchResource = context === void 0 ? resource : resourceWithContext(resource, context);
12817
+ const result = await exportResourceMetrics(points, batchResource, scope);
12463
12818
  if (result.code === ExportResultCode3.SUCCESS) {
12464
12819
  health.recordSuccess(points.length, options.clock.now());
12465
12820
  return { accepted: points.length, rejected: 0, errors: [] };
@@ -12467,7 +12822,7 @@ var createOtlpMetricSink = (options) => {
12467
12822
  health.recordFailure("telemetry-export-failure", points.length, options.clock.now());
12468
12823
  const permanent = isPermanentExportFailure(result);
12469
12824
  if (options.spool !== void 0 && !permanent) {
12470
- const spooled = await options.spool.enqueue(toSpoolBatch(points)).catch(() => ({
12825
+ const spooled = await options.spool.enqueue(toSpoolBatch(points, batchResource)).catch(() => ({
12471
12826
  spooled: false,
12472
12827
  reason: "capacity-exceeded"
12473
12828
  }));
@@ -12841,6 +13196,16 @@ var createHookRuntime = (options) => {
12841
13196
  logger,
12842
13197
  installationId: options.installationId,
12843
13198
  payloadEnrichers: options.payloadEnrichers ?? (readsClaudeTranscriptUsage(options.config) ? [createClaudeTranscriptUsageEnricher()] : []),
13199
+ ...(() => {
13200
+ if (options.sessionContextReader === null) {
13201
+ return {};
13202
+ }
13203
+ if (options.sessionContextReader !== void 0) {
13204
+ return { sessionContext: options.sessionContextReader };
13205
+ }
13206
+ const dir = sessionContextDir(options.config);
13207
+ return dir === void 0 ? {} : { sessionContext: createDirectorySessionContextReader({ dir }) };
13208
+ })(),
12844
13209
  ...options.worktreeLocator === null ? {} : {
12845
13210
  worktreeLocator: options.worktreeLocator ?? createFilesystemWorktreeLocator({ monotonicMillis: () => clock.monotonicMillis() })
12846
13211
  }
@@ -12934,9 +13299,10 @@ var createHookRuntime = (options) => {
12934
13299
  perSession: metricsPolicy.includeSessionId,
12935
13300
  ...deliveryToken === void 0 ? {} : { deliveryToken }
12936
13301
  });
13302
+ const context = agreedContextAttributes(ingest.events);
12937
13303
  const results = await Promise.all(
12938
13304
  metricDestinations.map(async (destination) => {
12939
- const result = await destination.metrics.exportPoints(points).catch(
13305
+ const result = await destination.metrics.exportPoints(points, context).catch(
12940
13306
  (thrown) => ({
12941
13307
  accepted: 0,
12942
13308
  rejected: points.length,
@@ -14076,7 +14442,7 @@ var SUPPORTED_REGISTRATION_PROVIDER_IDS = Object.freeze(
14076
14442
  );
14077
14443
 
14078
14444
  // src/install/scopes.ts
14079
- import * as path6 from "path";
14445
+ import * as path7 from "path";
14080
14446
  var REGISTRATION_SCOPES = Object.freeze([
14081
14447
  "global",
14082
14448
  "project"
@@ -14144,15 +14510,15 @@ var PROVIDERS_WITH_VERIFIED_LOCATION = Object.freeze([
14144
14510
  var findInstallLocation = (providerId, scope) => PROVIDER_INSTALL_LOCATIONS.find(
14145
14511
  (entry) => entry.providerId === providerId && entry.scope === scope
14146
14512
  );
14147
- var resolveInstallPath = (location, roots) => path6.resolve(
14513
+ var resolveInstallPath = (location, roots) => path7.resolve(
14148
14514
  location.scope === "global" ? roots.homeDir : roots.projectDir,
14149
14515
  ...location.segments
14150
14516
  );
14151
14517
 
14152
14518
  // src/install/document.ts
14153
14519
  import { randomBytes as randomBytes4 } from "crypto";
14154
- import { chmod, mkdir as mkdir3, open as open4, readFile as readFile3, rename as rename3, stat as stat4, unlink as unlink3 } from "fs/promises";
14155
- import * as path7 from "path";
14520
+ import { chmod, mkdir as mkdir3, open as open5, readFile as readFile3, rename as rename3, stat as stat4, unlink as unlink3 } from "fs/promises";
14521
+ import * as path8 from "path";
14156
14522
  var DEFAULT_DOCUMENT_FORMAT = Object.freeze({
14157
14523
  indent: " ",
14158
14524
  eol: "\n",
@@ -14223,11 +14589,11 @@ var renameWithRetry = async (from, to) => {
14223
14589
  var NEW_DOCUMENT_MODE = 384;
14224
14590
  var TEMPORARY_DOCUMENT_MODE = 384;
14225
14591
  var writeDocumentAtomically = async (filePath, contents) => {
14226
- const directory = path7.dirname(filePath);
14592
+ const directory = path8.dirname(filePath);
14227
14593
  await mkdir3(directory, { recursive: true });
14228
- const temporary = path7.join(
14594
+ const temporary = path8.join(
14229
14595
  directory,
14230
- `.${path7.basename(filePath)}.${randomBytes4(6).toString("hex")}.tmp`
14596
+ `.${path8.basename(filePath)}.${randomBytes4(6).toString("hex")}.tmp`
14231
14597
  );
14232
14598
  let existingMode;
14233
14599
  try {
@@ -14239,7 +14605,7 @@ var writeDocumentAtomically = async (filePath, contents) => {
14239
14605
  }
14240
14606
  const targetMode = existingMode ?? NEW_DOCUMENT_MODE;
14241
14607
  try {
14242
- const handle = await open4(temporary, "wx", TEMPORARY_DOCUMENT_MODE);
14608
+ const handle = await open5(temporary, "wx", TEMPORARY_DOCUMENT_MODE);
14243
14609
  try {
14244
14610
  await handle.writeFile(contents, "utf8");
14245
14611
  await handle.sync();
@@ -14256,12 +14622,12 @@ var writeDocumentAtomically = async (filePath, contents) => {
14256
14622
 
14257
14623
  // src/install/file-lock.ts
14258
14624
  import { randomBytes as randomBytes5 } from "crypto";
14259
- import { mkdir as mkdir4, open as open5, readFile as readFile4, rename as rename4, stat as stat5, unlink as unlink4 } from "fs/promises";
14260
- import * as path8 from "path";
14625
+ import { mkdir as mkdir4, open as open6, readFile as readFile4, rename as rename4, stat as stat5, unlink as unlink4 } from "fs/promises";
14626
+ import * as path9 from "path";
14261
14627
  var FileLockTimeoutError = class extends Error {
14262
14628
  constructor(lockPath, timeoutMillis) {
14263
14629
  super(
14264
- `timed out after ${String(timeoutMillis)}ms waiting for the lock on ${path8.basename(lockPath)}`
14630
+ `timed out after ${String(timeoutMillis)}ms waiting for the lock on ${path9.basename(lockPath)}`
14265
14631
  );
14266
14632
  this.name = "FileLockTimeoutError";
14267
14633
  }
@@ -14333,12 +14699,12 @@ var withFileLock = async (filePath, options, fn) => {
14333
14699
  const pollIntervalMillis = options.pollIntervalMillis ?? 25;
14334
14700
  const lockPath = lockPathFor(filePath);
14335
14701
  const startedAt = options.clock.monotonicMillis();
14336
- await mkdir4(path8.dirname(filePath), { recursive: true });
14702
+ await mkdir4(path9.dirname(filePath), { recursive: true });
14337
14703
  for (; ; ) {
14338
14704
  const token = randomBytes5(16).toString("hex");
14339
14705
  let acquired = false;
14340
14706
  try {
14341
- const handle = await open5(lockPath, "wx", 384);
14707
+ const handle = await open6(lockPath, "wx", 384);
14342
14708
  try {
14343
14709
  const contents = {
14344
14710
  token,
@@ -14381,7 +14747,7 @@ var withFileLock = async (filePath, options, fn) => {
14381
14747
 
14382
14748
  // src/install/lifecycle.ts
14383
14749
  import { readFile as readFile5 } from "fs/promises";
14384
- import * as path9 from "path";
14750
+ import * as path10 from "path";
14385
14751
  var defaultHookCommand = (providerId) => `otel-hook run --provider ${providerId}`;
14386
14752
  var unsupportedOutcome = (providerId, scope, reason) => ({
14387
14753
  providerId,
@@ -14398,7 +14764,7 @@ var unsupportedOutcome = (providerId, scope, reason) => ({
14398
14764
  var resolveTarget = (providerId, scope, request) => {
14399
14765
  if (request.configFile !== void 0) {
14400
14766
  return {
14401
- configPath: path9.resolve(request.configFile),
14767
+ configPath: path10.resolve(request.configFile),
14402
14768
  evidence: "path supplied by the caller with --settings-file"
14403
14769
  };
14404
14770
  }
@@ -14415,14 +14781,14 @@ var resolveTarget = (providerId, scope, request) => {
14415
14781
  };
14416
14782
  };
14417
14783
  var codexFeatureNote = async (configPath) => {
14418
- const tomlPath = path9.join(path9.dirname(configPath), "config.toml");
14784
+ const tomlPath = path10.join(path10.dirname(configPath), "config.toml");
14419
14785
  let raw;
14420
14786
  try {
14421
14787
  raw = await readFile5(tomlPath, "utf8");
14422
14788
  } catch {
14423
14789
  return void 0;
14424
14790
  }
14425
- return readCodexHooksFeatureFlag(raw) === "disabled" ? `${path9.basename(tomlPath)} sets [features] hooks = false; registered hooks will not fire until that is removed` : void 0;
14791
+ return readCodexHooksFeatureFlag(raw) === "disabled" ? `${path10.basename(tomlPath)} sets [features] hooks = false; registered hooks will not fire until that is removed` : void 0;
14426
14792
  };
14427
14793
  var readState = async (configPath) => {
14428
14794
  const read = await readJsonDocument(configPath);
@@ -14434,12 +14800,12 @@ var readState = async (configPath) => {
14434
14800
  case "unparseable":
14435
14801
  return {
14436
14802
  status: "blocked",
14437
- problem: `${path9.basename(configPath)} is not well-formed JSON (${read.detail}); it was left untouched`
14803
+ problem: `${path10.basename(configPath)} is not well-formed JSON (${read.detail}); it was left untouched`
14438
14804
  };
14439
14805
  case "unreadable":
14440
14806
  return {
14441
14807
  status: "failed",
14442
- problem: `${path9.basename(configPath)} could not be read (${read.detail})`
14808
+ problem: `${path10.basename(configPath)} could not be read (${read.detail})`
14443
14809
  };
14444
14810
  }
14445
14811
  };
@@ -14551,7 +14917,7 @@ var runOneTarget = async (providerId, scope, request, command) => {
14551
14917
  missingEvents: [],
14552
14918
  notes,
14553
14919
  problems: planned.conflicts.map(
14554
- (conflict) => `${path9.basename(configPath)} has an unexpected shape at ${conflict.location}: ${conflict.detail}; it was left untouched`
14920
+ (conflict) => `${path10.basename(configPath)} has an unexpected shape at ${conflict.location}: ${conflict.detail}; it was left untouched`
14555
14921
  )
14556
14922
  };
14557
14923
  }
@@ -14562,7 +14928,7 @@ var runOneTarget = async (providerId, scope, request, command) => {
14562
14928
  changed: false,
14563
14929
  registeredEvents: [],
14564
14930
  missingEvents: [],
14565
- notes: [...notes, `${path9.basename(configPath)} does not exist; nothing to remove`],
14931
+ notes: [...notes, `${path10.basename(configPath)} does not exist; nothing to remove`],
14566
14932
  problems: []
14567
14933
  };
14568
14934
  }
@@ -14605,7 +14971,7 @@ var runOneTarget = async (providerId, scope, request, command) => {
14605
14971
  missingEvents: [],
14606
14972
  notes,
14607
14973
  problems: [
14608
- `could not write ${path9.basename(configPath)} (${thrown instanceof Error ? thrown.name : typeof thrown})`
14974
+ `could not write ${path10.basename(configPath)} (${thrown instanceof Error ? thrown.name : typeof thrown})`
14609
14975
  ]
14610
14976
  };
14611
14977
  }
@@ -14632,7 +14998,7 @@ var runOneTarget = async (providerId, scope, request, command) => {
14632
14998
  missingEvents: [],
14633
14999
  notes,
14634
15000
  problems: [
14635
- thrown instanceof Error ? `${path9.basename(configPath)}: ${thrown.message}` : `${path9.basename(configPath)}: the configuration file could not be locked`
15001
+ thrown instanceof Error ? `${path10.basename(configPath)}: ${thrown.message}` : `${path10.basename(configPath)}: the configuration file could not be locked`
14636
15002
  ]
14637
15003
  };
14638
15004
  }
@@ -14768,6 +15134,8 @@ export {
14768
15134
  DEFAULT_PROVIDERS_POLICY,
14769
15135
  DEFAULT_SECRET_KEY_PATTERNS,
14770
15136
  DEFAULT_SECRET_VALUE_PATTERNS,
15137
+ DEFAULT_SESSION_CONTEXT_BUDGET_MILLIS,
15138
+ DEFAULT_SESSION_CONTEXT_MAX_BYTES,
14771
15139
  DEFAULT_SPOOL_POLICY,
14772
15140
  DEFAULT_TARGET_RESOLUTION_BUDGET_MILLIS,
14773
15141
  DEFAULT_WORKTREE_CACHE_TTL_MILLIS,
@@ -14810,6 +15178,7 @@ export {
14810
15178
  MAX_RESOURCE_ATTRIBUTES,
14811
15179
  MAX_RESOURCE_ATTRIBUTE_KEY_LENGTH,
14812
15180
  MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH,
15181
+ MAX_SESSION_CONTEXT_SEGMENTS,
14813
15182
  MAX_TARGET_HINT_PATHS,
14814
15183
  MAX_TARGET_PATH_LENGTH,
14815
15184
  MAX_WORKTREE_WALK_DEPTH,
@@ -14837,6 +15206,8 @@ export {
14837
15206
  RESERVED_RESOURCE_ATTRIBUTE_KEYS,
14838
15207
  RESOURCE_ATTRIBUTE_KEY_PATTERN,
14839
15208
  RESOURCE_ATTRIBUTE_KEY_REJECTION_DETAIL,
15209
+ SESSION_CONTEXT_AGENT_TOOLS,
15210
+ SESSION_CONTEXT_FILE_VERSION,
14840
15211
  SILENT_HOOK_RESPONSE,
14841
15212
  SPAN_RECORD_VERSION,
14842
15213
  SUBAGENT_ID_PATTERN,
@@ -14893,6 +15264,7 @@ export {
14893
15264
  createDefaultProviderRegistry,
14894
15265
  createDestinationFanout,
14895
15266
  createDeterministicIdGenerator,
15267
+ createDirectorySessionContextReader,
14896
15268
  createErrorInfo,
14897
15269
  createEventFactory,
14898
15270
  createExportDestinationSinks,
@@ -14985,7 +15357,9 @@ export {
14985
15357
  isPermanentExportFailure,
14986
15358
  isReservedExtensionNamespace,
14987
15359
  isReservedResourceAttributeKey,
15360
+ isReservedSessionContextKey,
14988
15361
  isSecretResourceAttributeKey,
15362
+ isSessionContextFileName,
14989
15363
  isTargetedEvent,
14990
15364
  isUnavailableContentFact,
14991
15365
  isUnknownProvider,
@@ -15023,6 +15397,7 @@ export {
15023
15397
  parseHeaderValueReference,
15024
15398
  parseOtlpHeadersValue,
15025
15399
  parseResourceAttributesValue,
15400
+ parseSessionContextFile,
15026
15401
  planProviderRegistration,
15027
15402
  privacyLimitsSchema,
15028
15403
  privacyPolicySchema,
@@ -15071,7 +15446,13 @@ export {
15071
15446
  resourceAttributesSchema,
15072
15447
  runRegistrationLifecycle,
15073
15448
  sanitizeResourceAttributes,
15449
+ sanitizeSessionContextAttributes,
15450
+ segmentInForce,
15074
15451
  sequenceNumberSchema,
15452
+ sessionContextAgentTool,
15453
+ sessionContextDir,
15454
+ sessionContextFilePath,
15455
+ sessionContextPolicySchema,
15075
15456
  sessionCwdHint,
15076
15457
  sessionEndEventSchema,
15077
15458
  sessionIdSchema,
@@ -15082,6 +15463,7 @@ export {
15082
15463
  spanScopeRefOf,
15083
15464
  spoolPolicySchema,
15084
15465
  spoolQueueNamesFor,
15466
+ stampSessionContext,
15085
15467
  startOnlySpanAttributes,
15086
15468
  stateRecordSchema,
15087
15469
  stateValueSchema,