@osfactory/otel-hook 0.11.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +32 -5
  2. package/dist/{adapter-DiLknaTF.d.ts → adapter-DyCb7y1N.d.ts} +2 -2
  3. package/dist/cli.js +507 -108
  4. package/dist/cli.js.map +1 -1
  5. package/dist/config.d.ts +3 -3
  6. package/dist/config.js +16 -3
  7. package/dist/config.js.map +1 -1
  8. package/dist/{destinations-BIl3gGzx.d.ts → destinations-DvqsPulb.d.ts} +1 -1
  9. package/dist/{events-CSD_YiJ2.d.ts → events-fcomX6d5.d.ts} +22 -0
  10. package/dist/{export-destinations-QWKGGEjk.d.ts → export-destinations-Bey2djRk.d.ts} +11 -6
  11. package/dist/{filesystem-store-D3SCNmbX.d.ts → filesystem-store-B3CpiIRl.d.ts} +1 -1
  12. package/dist/{hook-BOecWGSz.d.ts → hook-D5imE0Qc.d.ts} +11 -5
  13. package/dist/index.d.ts +14 -14
  14. package/dist/index.js +525 -143
  15. package/dist/index.js.map +1 -1
  16. package/dist/install.d.ts +4 -4
  17. package/dist/install.js +19 -2
  18. package/dist/install.js.map +1 -1
  19. package/dist/integration.d.ts +16 -10
  20. package/dist/integration.js +447 -111
  21. package/dist/integration.js.map +1 -1
  22. package/dist/lifecycle.d.ts +3 -3
  23. package/dist/lifecycle.js +10 -2
  24. package/dist/lifecycle.js.map +1 -1
  25. package/dist/{memory-Cs51jyRk.d.ts → memory-B3r6sZtC.d.ts} +2 -2
  26. package/dist/{metric-model-DDnWxL9d.d.ts → metric-model-CFIeUwqd.d.ts} +6 -2
  27. package/dist/model.d.ts +1 -1
  28. package/dist/model.js +9 -1
  29. package/dist/model.js.map +1 -1
  30. package/dist/{payload-ChtrEX6A.d.ts → payload-CdDKeRpH.d.ts} +1 -1
  31. package/dist/{ports-CeqLq31i.d.ts → ports-DhpSDIkp.d.ts} +41 -3
  32. package/dist/providers.d.ts +30 -14
  33. package/dist/providers.js +131 -42
  34. package/dist/providers.js.map +1 -1
  35. package/dist/{registry-CcJNF3WY.d.ts → registry-BKQhhIO3.d.ts} +2 -2
  36. package/dist/runtime.d.ts +97 -9
  37. package/dist/runtime.js +269 -26
  38. package/dist/runtime.js.map +1 -1
  39. package/dist/{schema-DMnoU1V_.d.ts → schema-SpFM6YQY.d.ts} +24 -1
  40. package/dist/state.d.ts +4 -4
  41. package/dist/state.js +9 -1
  42. package/dist/state.js.map +1 -1
  43. package/dist/telemetry.d.ts +6 -6
  44. package/dist/telemetry.js +80 -22
  45. package/dist/telemetry.js.map +1 -1
  46. package/dist/testing.d.ts +10 -8
  47. package/dist/testing.js +161 -30
  48. package/dist/testing.js.map +1 -1
  49. package/package.json +1 -1
@@ -1,6 +1,6 @@
1
- import { g as DetectionPolicy } from './schema-DMnoU1V_.js';
1
+ import { g as DetectionPolicy } from './schema-SpFM6YQY.js';
2
2
  import { OtelHookErrorInfo } from './errors.js';
3
- import { P as ProviderAdapter, h as ProviderDetection, i as ProviderDetectionInput, e as ProviderContext } from './adapter-DiLknaTF.js';
3
+ import { P as ProviderAdapter, h as ProviderDetection, i as ProviderDetectionInput, e as ProviderContext } from './adapter-DyCb7y1N.js';
4
4
 
5
5
  type DetectionCandidate = {
6
6
  readonly adapter: ProviderAdapter;
package/dist/runtime.d.ts CHANGED
@@ -1,19 +1,19 @@
1
- import { c as LogLevel, d as Logger, W as WorktreeLocator } from './ports-CeqLq31i.js';
2
- export { A as AppliedDelivery, C as Clock, E as EventIdSeed, I as IdGenerator, a as InvocationIdSeed, L as LOG_LEVEL_RANK, b as LocatedWorktree, P as PayloadEnricher, e as PayloadEnrichment, f as PayloadEnrichmentInput, R as ReadCursor, S as StateRecord, g as StateStore, h as StateValue, T as TelemetryEmitResult, i as TelemetrySink, j as appliedDeliverySchema, l as logLevelSchema, s as stateRecordSchema, k as stateValueSchema } from './ports-CeqLq31i.js';
3
- export { D as DeterministicIdOptions, F as FixedClock, a as FixedClockOptions, I as InMemoryStateStore, b as InMemoryStateStoreOptions, L as LogRecord, R as RecordingLogger, c as RecordingTelemetrySink, d as RecordingTelemetrySinkOptions, e as createDeterministicIdGenerator, f as createFixedClock, g as createInMemoryStateStore, h as createNullTelemetrySink, i as createRandomIdGenerator, j as createRecordingLogger, k as createRecordingTelemetrySink, l as createSystemClock } from './memory-Cs51jyRk.js';
4
- export { C as CumulativeUsageSeries, D as DeliveryDurability, a as DeliveryOrigin, b as DeliveryResolution, c as DeliveryUnavailableReason, H as HookIngestInput, d as HookIngestOptions, e as HookIngestOutcome, O as OtelHook, f as OtelHookDependencies, R as ResolvedDeliveryIdentity, U as UsageObservation, g as UsageScope, h as classifyDurability, i as createOtelHook, j as hostDeliveryIdentity, k as isCommittable, r as resolveDeliveryIdentity, u as usageScopeSchema } from './hook-BOecWGSz.js';
5
- import { b as CanonicalEvent, u as TargetHint } from './events-CSD_YiJ2.js';
1
+ import { c as LogLevel, d as Logger, W as WorktreeLocator, S as SessionContextReader, h as SessionContextSegment } from './ports-DhpSDIkp.js';
2
+ export { A as AppliedDelivery, C as Clock, E as EventIdSeed, I as IdGenerator, a as InvocationIdSeed, L as LOG_LEVEL_RANK, b as LocatedWorktree, P as PayloadEnricher, e as PayloadEnrichment, f as PayloadEnrichmentInput, R as ReadCursor, g as SessionContextRequest, i as StateRecord, j as StateStore, k as StateValue, T as TelemetryEmitResult, l as TelemetrySink, m as appliedDeliverySchema, n as logLevelSchema, s as stateRecordSchema, o as stateValueSchema } from './ports-DhpSDIkp.js';
3
+ export { D as DeterministicIdOptions, F as FixedClock, a as FixedClockOptions, I as InMemoryStateStore, b as InMemoryStateStoreOptions, L as LogRecord, R as RecordingLogger, c as RecordingTelemetrySink, d as RecordingTelemetrySinkOptions, e as createDeterministicIdGenerator, f as createFixedClock, g as createInMemoryStateStore, h as createNullTelemetrySink, i as createRandomIdGenerator, j as createRecordingLogger, k as createRecordingTelemetrySink, l as createSystemClock } from './memory-B3r6sZtC.js';
4
+ export { C as CumulativeUsageSeries, D as DeliveryDurability, a as DeliveryOrigin, b as DeliveryResolution, c as DeliveryUnavailableReason, H as HookIngestInput, d as HookIngestOptions, e as HookIngestOutcome, O as OtelHook, f as OtelHookDependencies, R as ResolvedDeliveryIdentity, U as UsageObservation, g as UsageScope, h as classifyDurability, i as createOtelHook, j as hostDeliveryIdentity, k as isCommittable, r as resolveDeliveryIdentity, u as usageScopeSchema } from './hook-D5imE0Qc.js';
5
+ import { b as CanonicalEvent, u as TargetHint } from './events-fcomX6d5.js';
6
6
  import { d as EventId } from './primitives-CJ8-rn-f.js';
7
7
  import { P as PrivacyService } from './service-CbI9CObT.js';
8
8
  import 'zod';
9
9
  import './errors.js';
10
10
  import './taxonomy-DwhTtuWd.js';
11
- import './schema-DMnoU1V_.js';
11
+ import './schema-SpFM6YQY.js';
12
12
  import './identity-BrVBs901.js';
13
- import './adapter-DiLknaTF.js';
13
+ import './adapter-DyCb7y1N.js';
14
14
  import './policy-CimmCfRp.js';
15
15
  import './content-M9xIKG7h.js';
16
- import './registry-CcJNF3WY.js';
16
+ import './registry-BKQhhIO3.js';
17
17
 
18
18
  declare const createNullLogger: () => Logger;
19
19
  type StderrLoggerOptions = {
@@ -121,4 +121,92 @@ type ResolveEventTargetsResult = {
121
121
  */
122
122
  declare const resolveEventTargets: (input: ResolveEventTargetsInput) => Promise<ResolveEventTargetsResult>;
123
123
 
124
- export { DEFAULT_TARGET_RESOLUTION_BUDGET_MILLIS, DEFAULT_WORKTREE_CACHE_TTL_MILLIS, type FilesystemWorktreeLocatorOptions, LogLevel, Logger, MAX_WORKTREE_WALK_DEPTH, type ResolveEventTargetsInput, type ResolveEventTargetsResult, type StderrLoggerOptions, WorktreeLocator, createFilesystemWorktreeLocator, createNullLogger, createStderrLogger, parseCommonDirFile, parseGitDirFile, parseHeadBranch, resolveEventTargets };
124
+ /**
125
+ * Session context: attributes a harness wants on every record of one agent
126
+ * session, for a window of time.
127
+ *
128
+ * A harness (HAR, or anything else) writes one JSON file per agent session:
129
+ *
130
+ * ```text
131
+ * <dir>/<agent-tool>/<session-id>.json
132
+ * { "version": 1, "agentTool": "claude_code", "sessionId": "…",
133
+ * "segments": [ { "from": "<ISO-8601>", "to": "<ISO-8601>" | null,
134
+ * "reason": "launch", "attributes": { "k": "v" } } ] }
135
+ * ```
136
+ *
137
+ * On every hook event the core reads the one file for the event's session,
138
+ * picks the segment in force at each event's time, and stamps its attributes on
139
+ * every record the event produces. otel-hook knows nothing about what the
140
+ * attributes mean: it applies an attribute map. See `docs/session-context.md`.
141
+ *
142
+ * Fail-open throughout: a missing, unreadable, oversized, invalid, or
143
+ * wrong-version file — or no segment in force — stamps nothing and never fails
144
+ * the hook.
145
+ */
146
+ /** The only file format version this build reads. Any other is ignored whole. */
147
+ declare const SESSION_CONTEXT_FILE_VERSION: 1;
148
+ /** Largest file read; anything bigger is ignored rather than truncated. */
149
+ declare const DEFAULT_SESSION_CONTEXT_MAX_BYTES: number;
150
+ /** Ceiling on one read; a slow filesystem costs the stamp, never the hook. */
151
+ declare const DEFAULT_SESSION_CONTEXT_BUDGET_MILLIS = 100;
152
+ /** Upper bound on segments considered in one file. */
153
+ declare const MAX_SESSION_CONTEXT_SEGMENTS = 1024;
154
+ /**
155
+ * otel-hook provider id → the agent-tool directory a harness writes under.
156
+ *
157
+ * The names are the ones HAR derives from the agent process it finds
158
+ * (`claude_code`, `codex`, `cursor`). A provider absent from this table has no
159
+ * session context: nothing is read for it.
160
+ */
161
+ declare const SESSION_CONTEXT_AGENT_TOOLS: Readonly<Record<string, string>>;
162
+ declare const sessionContextAgentTool: (providerId: string) => string | undefined;
163
+ declare const isSessionContextFileName: (sessionId: string) => boolean;
164
+ /**
165
+ * Where the context of one session lives, or `undefined` when the provider has
166
+ * no agent-tool directory or the session id cannot be a file name.
167
+ */
168
+ declare const sessionContextFilePath: (dir: string, providerId: string, sessionId: string) => string | undefined;
169
+ declare const isReservedSessionContextKey: (key: string) => boolean;
170
+ /**
171
+ * Screen one segment's attribute map: primitive values only, bounded, and no
172
+ * reserved or unsafe key. Dropped entries are dropped silently, one by one; the
173
+ * rest of the map still applies.
174
+ */
175
+ declare const sanitizeSessionContextAttributes: (attributes: Readonly<Record<string, unknown>>) => Readonly<Record<string, string | number | boolean>>;
176
+ /**
177
+ * Parse a decoded context file into screened segments.
178
+ *
179
+ * `expected` guards against a file that names another session or tool than the
180
+ * one it was read for (a copy, a misplaced write): such a file applies to
181
+ * nobody. Returns `undefined` for anything invalid; never throws.
182
+ */
183
+ declare const parseSessionContextFile: (value: unknown, expected?: {
184
+ readonly agentTool?: string;
185
+ readonly sessionId?: string;
186
+ }) => readonly SessionContextSegment[] | undefined;
187
+ /**
188
+ * The segment in force at `at`: `from <= at` and (`to` is null or `at < to`).
189
+ * Should a writer ever leave two overlapping, the one that started last wins,
190
+ * because it is the more recent statement.
191
+ */
192
+ declare const segmentInForce: (segments: readonly SessionContextSegment[], at: number) => SessionContextSegment | undefined;
193
+ /**
194
+ * Stamp each event with the attributes of the segment in force at its own
195
+ * `occurredAt`, and strip any `contextAttributes` an event already carried: only
196
+ * this core step may set them. An event with no segment in force, or one whose
197
+ * segment has no usable attribute, carries none.
198
+ */
199
+ declare const stampSessionContext: (events: readonly CanonicalEvent[], segments: readonly SessionContextSegment[] | undefined) => readonly CanonicalEvent[];
200
+ type DirectorySessionContextReaderOptions = {
201
+ /** Absolute directory holding `<agent-tool>/<session-id>.json`. */
202
+ readonly dir: string;
203
+ readonly maxBytes?: number;
204
+ readonly budgetMillis?: number;
205
+ };
206
+ /**
207
+ * The filesystem {@link SessionContextReader}: one bounded read of one file per
208
+ * call, never a directory scan. Never throws.
209
+ */
210
+ declare const createDirectorySessionContextReader: (options: DirectorySessionContextReaderOptions) => SessionContextReader;
211
+
212
+ export { DEFAULT_SESSION_CONTEXT_BUDGET_MILLIS, DEFAULT_SESSION_CONTEXT_MAX_BYTES, DEFAULT_TARGET_RESOLUTION_BUDGET_MILLIS, DEFAULT_WORKTREE_CACHE_TTL_MILLIS, type DirectorySessionContextReaderOptions, type FilesystemWorktreeLocatorOptions, LogLevel, Logger, MAX_SESSION_CONTEXT_SEGMENTS, MAX_WORKTREE_WALK_DEPTH, type ResolveEventTargetsInput, type ResolveEventTargetsResult, SESSION_CONTEXT_AGENT_TOOLS, SESSION_CONTEXT_FILE_VERSION, SessionContextReader, SessionContextSegment, type StderrLoggerOptions, WorktreeLocator, createDirectorySessionContextReader, createFilesystemWorktreeLocator, createNullLogger, createStderrLogger, isReservedSessionContextKey, isSessionContextFileName, parseCommonDirFile, parseGitDirFile, parseHeadBranch, parseSessionContextFile, resolveEventTargets, sanitizeSessionContextAttributes, segmentInForce, sessionContextAgentTool, sessionContextFilePath, stampSessionContext };
package/dist/runtime.js CHANGED
@@ -808,7 +808,15 @@ var baseEventFields = {
808
808
  * factory, never by hand.
809
809
  */
810
810
  subagentId: subagentIdSchema.optional(),
811
- extensions: extensionsSchema.default(emptyExtensions)
811
+ extensions: extensionsSchema.default(emptyExtensions),
812
+ /**
813
+ * Attributes of the session context segment in force when the event
814
+ * occurred (`docs/session-context.md`), stamped by the core from a file a
815
+ * harness wrote. Exported on every record of the event, over the same keys
816
+ * from the Resource. Absent when no context applies. Set by the core only,
817
+ * never by an adapter.
818
+ */
819
+ contextAttributes: z9.record(z9.string().min(1).max(255), z9.union([z9.string(), z9.number(), z9.boolean()])).optional()
812
820
  };
813
821
  var event = (shape) => z9.strictObject({ ...baseEventFields, ...shape });
814
822
  var sessionStartEventSchema = event({
@@ -1353,9 +1361,10 @@ var resolveDeliveryIdentity = (input) => {
1353
1361
  };
1354
1362
 
1355
1363
  // src/runtime/hook.ts
1356
- import { z as z17 } from "zod";
1364
+ import { z as z18 } from "zod";
1357
1365
 
1358
1366
  // src/config/schema.ts
1367
+ import { isAbsolute } from "path";
1359
1368
  import { z as z15 } from "zod";
1360
1369
 
1361
1370
  // src/privacy/policy.ts
@@ -1726,13 +1735,19 @@ var providersPolicySchema = z15.strictObject({
1726
1735
  readTranscriptUsage: z15.boolean()
1727
1736
  }).optional()
1728
1737
  });
1738
+ var sessionContextPolicySchema = z15.strictObject({
1739
+ /** Absolute path of the context directory. */
1740
+ dir: z15.string().min(1).max(4096).refine((value) => isAbsolute(value), { message: "must be an absolute path" })
1741
+ });
1729
1742
  var otelHookConfigSchema = z15.strictObject({
1730
1743
  exporter: exporterPolicySchema,
1731
1744
  privacy: privacyPolicySchema,
1732
1745
  detection: detectionPolicySchema,
1733
1746
  diagnostics: diagnosticsPolicySchema,
1734
1747
  /** Optional so a hand-built configuration from before it existed stays valid. */
1735
- providers: providersPolicySchema.optional()
1748
+ providers: providersPolicySchema.optional(),
1749
+ /** Optional: absent means no session context is read. */
1750
+ sessionContext: sessionContextPolicySchema.optional()
1736
1751
  });
1737
1752
  var otelHookConfigPatchSchema = z15.strictObject({
1738
1753
  // `logs` is unwrapped and re-partialled for the same reason `privacy.limits` is:
@@ -1748,7 +1763,8 @@ var otelHookConfigPatchSchema = z15.strictObject({
1748
1763
  diagnostics: diagnosticsPolicySchema.partial().optional(),
1749
1764
  providers: z15.strictObject({
1750
1765
  claudeCode: z15.strictObject({ readTranscriptUsage: z15.boolean() }).partial().optional()
1751
- }).partial().optional()
1766
+ }).partial().optional(),
1767
+ sessionContext: sessionContextPolicySchema.partial().optional()
1752
1768
  });
1753
1769
  var DEFAULT_EXPORTER_POLICY = Object.freeze({
1754
1770
  enabled: true,
@@ -2002,11 +2018,11 @@ var createPrivacyService = (policyInput) => {
2002
2018
  };
2003
2019
  const flattenToAttributes = (value, prefix) => {
2004
2020
  const attributes = {};
2005
- const walk = (current, path3) => {
2021
+ const walk = (current, path4) => {
2006
2022
  if (typeof current === "string" || typeof current === "number" || typeof current === "boolean") {
2007
2023
  const primitive = toAttributePrimitive(current);
2008
2024
  if (primitive !== void 0) {
2009
- attributes[path3] = primitive;
2025
+ attributes[path4] = primitive;
2010
2026
  }
2011
2027
  return;
2012
2028
  }
@@ -2025,16 +2041,16 @@ var createPrivacyService = (policyInput) => {
2025
2041
  primitives.push(entryPrimitive);
2026
2042
  }
2027
2043
  if (uniform) {
2028
- attributes[path3] = primitives.slice(0, MAX_ATTRIBUTE_ARRAY_LENGTH);
2044
+ attributes[path4] = primitives.slice(0, MAX_ATTRIBUTE_ARRAY_LENGTH);
2029
2045
  return;
2030
2046
  }
2031
2047
  for (const [index, entry] of current.entries()) {
2032
- walk(entry, `${path3}.${index}`);
2048
+ walk(entry, `${path4}.${index}`);
2033
2049
  }
2034
2050
  return;
2035
2051
  }
2036
2052
  for (const [key, entry] of Object.entries(current)) {
2037
- walk(entry, path3 === "" ? key : `${path3}.${key}`);
2053
+ walk(entry, path4 === "" ? key : `${path4}.${key}`);
2038
2054
  }
2039
2055
  };
2040
2056
  walk(value, prefix);
@@ -2553,8 +2569,200 @@ var withOptionalSessionLock = async (store, sessionId, fn, options) => {
2553
2569
  return fn();
2554
2570
  };
2555
2571
 
2572
+ // src/runtime/session-context.ts
2573
+ import { open } from "fs/promises";
2574
+ import * as path2 from "path";
2575
+ import { z as z17 } from "zod";
2576
+ var SESSION_CONTEXT_FILE_VERSION = 1;
2577
+ var DEFAULT_SESSION_CONTEXT_MAX_BYTES = 256 * 1024;
2578
+ var DEFAULT_SESSION_CONTEXT_BUDGET_MILLIS = 100;
2579
+ var MAX_SESSION_CONTEXT_SEGMENTS = 1024;
2580
+ var SESSION_CONTEXT_AGENT_TOOLS = Object.freeze({
2581
+ "claude-code": "claude_code",
2582
+ codex: "codex",
2583
+ cursor: "cursor",
2584
+ "gemini-cli": "gemini_cli",
2585
+ antigravity: "antigravity"
2586
+ });
2587
+ var sessionContextAgentTool = (providerId) => Object.hasOwn(SESSION_CONTEXT_AGENT_TOOLS, providerId) ? SESSION_CONTEXT_AGENT_TOOLS[providerId] : void 0;
2588
+ var SESSION_FILE_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/;
2589
+ var isSessionContextFileName = (sessionId) => SESSION_FILE_NAME_PATTERN.test(sessionId) && !sessionId.includes("..");
2590
+ var sessionContextFilePath = (dir, providerId, sessionId) => {
2591
+ const tool = sessionContextAgentTool(providerId);
2592
+ if (tool === void 0 || !isSessionContextFileName(sessionId) || !path2.isAbsolute(dir)) {
2593
+ return void 0;
2594
+ }
2595
+ return path2.join(dir, tool, `${sessionId}.json`);
2596
+ };
2597
+ var RESERVED_CONTEXT_KEYS = /* @__PURE__ */ new Set([
2598
+ "session.id",
2599
+ "trace_id",
2600
+ "span_id",
2601
+ "parent_span_id",
2602
+ "gen_ai.conversation.id",
2603
+ "factory.local"
2604
+ ]);
2605
+ var RESERVED_CONTEXT_PREFIXES = Object.freeze(["factory.local.", "otelhook."]);
2606
+ var isReservedSessionContextKey = (key) => RESERVED_CONTEXT_KEYS.has(key) || RESERVED_CONTEXT_PREFIXES.some((prefix) => key.startsWith(prefix));
2607
+ var sanitizeSessionContextAttributes = (attributes) => {
2608
+ const kept = {};
2609
+ let count = 0;
2610
+ for (const [key, value] of Object.entries(attributes)) {
2611
+ if (count >= MAX_RESOURCE_ATTRIBUTES) {
2612
+ break;
2613
+ }
2614
+ if (checkResourceAttributeKey(key) !== void 0 || isReservedSessionContextKey(key)) {
2615
+ continue;
2616
+ }
2617
+ if (typeof value === "string") {
2618
+ if (value.length > MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH) {
2619
+ continue;
2620
+ }
2621
+ } else if (typeof value === "number") {
2622
+ if (!Number.isFinite(value)) {
2623
+ continue;
2624
+ }
2625
+ } else if (typeof value !== "boolean") {
2626
+ continue;
2627
+ }
2628
+ kept[key] = value;
2629
+ count += 1;
2630
+ }
2631
+ return kept;
2632
+ };
2633
+ 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})$/;
2634
+ var isoInstantSchema = z17.string().max(64).regex(ISO_INSTANT_PATTERN).transform((value, ctx) => {
2635
+ const millis = Date.parse(value);
2636
+ if (!Number.isFinite(millis)) {
2637
+ ctx.issues.push({ code: "custom", input: value, message: "not a valid instant" });
2638
+ return z17.NEVER;
2639
+ }
2640
+ return millis;
2641
+ });
2642
+ var segmentSchema = z17.object({
2643
+ from: isoInstantSchema,
2644
+ to: isoInstantSchema.nullable(),
2645
+ reason: z17.string().max(256).optional(),
2646
+ attributes: z17.record(z17.string(), z17.unknown())
2647
+ });
2648
+ var sessionContextFileSchema = z17.object({
2649
+ version: z17.literal(SESSION_CONTEXT_FILE_VERSION),
2650
+ agentTool: z17.string().max(64).optional(),
2651
+ sessionId: z17.string().max(256).optional(),
2652
+ segments: z17.array(segmentSchema).max(MAX_SESSION_CONTEXT_SEGMENTS)
2653
+ });
2654
+ var parseSessionContextFile = (value, expected) => {
2655
+ const parsed = sessionContextFileSchema.safeParse(value);
2656
+ if (!parsed.success) {
2657
+ return void 0;
2658
+ }
2659
+ const file = parsed.data;
2660
+ 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) {
2661
+ return void 0;
2662
+ }
2663
+ return file.segments.map((segment) => ({
2664
+ from: segment.from,
2665
+ to: segment.to,
2666
+ attributes: sanitizeSessionContextAttributes(segment.attributes)
2667
+ }));
2668
+ };
2669
+ var segmentInForce = (segments, at) => {
2670
+ let best;
2671
+ for (const segment of segments) {
2672
+ if (segment.from <= at && (segment.to === null || at < segment.to)) {
2673
+ if (best === void 0 || segment.from >= best.from) {
2674
+ best = segment;
2675
+ }
2676
+ }
2677
+ }
2678
+ return best;
2679
+ };
2680
+ var stampSessionContext = (events, segments) => events.map((event2) => {
2681
+ const { contextAttributes: _discarded, ...rest } = event2;
2682
+ const segment = segments === void 0 ? void 0 : segmentInForce(segments, event2.occurredAt);
2683
+ if (segment === void 0 || Object.keys(segment.attributes).length === 0) {
2684
+ return _discarded === void 0 ? event2 : rest;
2685
+ }
2686
+ return { ...rest, contextAttributes: { ...segment.attributes } };
2687
+ });
2688
+ var readBounded = async (file, maxBytes) => {
2689
+ let handle;
2690
+ try {
2691
+ handle = await open(file, "r");
2692
+ } catch {
2693
+ return void 0;
2694
+ }
2695
+ try {
2696
+ const stats = await handle.stat();
2697
+ if (!stats.isFile() || stats.size > maxBytes) {
2698
+ return void 0;
2699
+ }
2700
+ const buffer = Buffer.alloc(maxBytes + 1);
2701
+ let length = 0;
2702
+ while (length < buffer.length) {
2703
+ const { bytesRead } = await handle.read(buffer, length, buffer.length - length, length);
2704
+ if (bytesRead === 0) {
2705
+ break;
2706
+ }
2707
+ length += bytesRead;
2708
+ }
2709
+ if (length > maxBytes) {
2710
+ return void 0;
2711
+ }
2712
+ return buffer.subarray(0, length).toString("utf8");
2713
+ } catch {
2714
+ return void 0;
2715
+ } finally {
2716
+ await handle.close().catch(() => void 0);
2717
+ }
2718
+ };
2719
+ var createDirectorySessionContextReader = (options) => {
2720
+ const maxBytes = options.maxBytes ?? DEFAULT_SESSION_CONTEXT_MAX_BYTES;
2721
+ const budgetMillis = options.budgetMillis ?? DEFAULT_SESSION_CONTEXT_BUDGET_MILLIS;
2722
+ const readOnce = async (providerId, sessionId) => {
2723
+ const file = sessionContextFilePath(options.dir, providerId, sessionId);
2724
+ if (file === void 0) {
2725
+ return void 0;
2726
+ }
2727
+ const text = await readBounded(file, maxBytes);
2728
+ if (text === void 0) {
2729
+ return void 0;
2730
+ }
2731
+ let decoded;
2732
+ try {
2733
+ decoded = JSON.parse(text);
2734
+ } catch {
2735
+ return void 0;
2736
+ }
2737
+ const agentTool = sessionContextAgentTool(providerId);
2738
+ return parseSessionContextFile(decoded, {
2739
+ ...agentTool === void 0 ? {} : { agentTool },
2740
+ sessionId
2741
+ });
2742
+ };
2743
+ return {
2744
+ read: async (request) => {
2745
+ let timer;
2746
+ const timeout = new Promise((resolve3) => {
2747
+ timer = setTimeout(() => resolve3(void 0), budgetMillis);
2748
+ timer.unref?.();
2749
+ });
2750
+ try {
2751
+ return await Promise.race([
2752
+ readOnce(request.providerId, request.sessionId).catch(() => void 0),
2753
+ timeout
2754
+ ]);
2755
+ } finally {
2756
+ if (timer !== void 0) {
2757
+ clearTimeout(timer);
2758
+ }
2759
+ }
2760
+ }
2761
+ };
2762
+ };
2763
+
2556
2764
  // src/runtime/hook.ts
2557
- var usageScopeSchema = z17.enum(["session", "generation", "subagent"]);
2765
+ var usageScopeSchema = z18.enum(["session", "generation", "subagent"]);
2558
2766
  var classifyDurability = (input) => {
2559
2767
  if (!input.attempted) {
2560
2768
  return "nothing-to-deliver";
@@ -2613,7 +2821,7 @@ var usageScopeOf = (event2) => {
2613
2821
  };
2614
2822
  var sequenceKey = (sessionId) => `sequence:${sessionId}`;
2615
2823
  var sessionModelKey = (sessionId) => `model:${sessionId}`;
2616
- var readCursorKey = (enricherId, sessionId) => `cursor:${enricherId}:${sessionId}`;
2824
+ var readCursorKey = (enricherId, sessionId, scope) => scope === void 0 ? `cursor:${enricherId}:${sessionId}` : `cursor:${enricherId}:${sessionId}:${scope}`;
2617
2825
  var UNKNOWN_MODEL_ID = "unknown";
2618
2826
  var latestSessionModel = (events) => {
2619
2827
  let latest;
@@ -2681,7 +2889,17 @@ var createOtelHook = (deps) => {
2681
2889
  if (enricher.providerId !== providerId) {
2682
2890
  continue;
2683
2891
  }
2684
- const key = readCursorKey(enricher.id, sessionId);
2892
+ let scope;
2893
+ try {
2894
+ scope = enricher.cursorScope?.(current);
2895
+ } catch (thrown) {
2896
+ logger.warn("payload enricher failed; parsing the payload as delivered", {
2897
+ "enricher.id": enricher.id,
2898
+ "error.name": thrown instanceof Error ? thrown.name : typeof thrown
2899
+ });
2900
+ continue;
2901
+ }
2902
+ const key = readCursorKey(enricher.id, sessionId, scope);
2685
2903
  let cursor;
2686
2904
  try {
2687
2905
  const record = await deps.stateStore.read(key);
@@ -3263,6 +3481,10 @@ var createOtelHook = (deps) => {
3263
3481
  });
3264
3482
  }
3265
3483
  }
3484
+ batch = stampSessionContext(
3485
+ batch,
3486
+ !suppress && batch.length > 0 && deps.sessionContext !== void 0 ? await readSessionContext(deps.sessionContext, detection.providerId, identity.sessionId) : void 0
3487
+ );
3266
3488
  let emitted = 0;
3267
3489
  let exportRejected = 0;
3268
3490
  if (!suppress && batch.length > 0) {
@@ -3378,6 +3600,13 @@ var createOtelHook = (deps) => {
3378
3600
  };
3379
3601
  return { resolveDelivery, ingest, flush, shutdown, config };
3380
3602
  };
3603
+ var readSessionContext = async (reader, providerId, sessionId) => {
3604
+ try {
3605
+ return await reader.read({ providerId, sessionId });
3606
+ } catch {
3607
+ return void 0;
3608
+ }
3609
+ };
3381
3610
  var buildErrorEvents = (diagnostics, identity, sequenceBase, ids, privacy) => {
3382
3611
  const events = [];
3383
3612
  for (const [index, info] of diagnostics.slice(0, MAX_ERROR_EVENTS).entries()) {
@@ -3412,8 +3641,8 @@ var buildErrorEvents = (diagnostics, identity, sequenceBase, ids, privacy) => {
3412
3641
  };
3413
3642
 
3414
3643
  // src/runtime/git-worktree.ts
3415
- import { lstat, open, stat } from "fs/promises";
3416
- import * as path2 from "path";
3644
+ import { lstat, open as open2, stat } from "fs/promises";
3645
+ import * as path3 from "path";
3417
3646
  var MAX_WORKTREE_WALK_DEPTH = 128;
3418
3647
  var MAX_GIT_FILE_BYTES = 4096;
3419
3648
  var MAX_CACHE_ENTRIES = 1024;
@@ -3421,10 +3650,10 @@ var DEFAULT_WORKTREE_CACHE_TTL_MILLIS = 5e3;
3421
3650
  var MAX_BRANCH_NAME_LENGTH = 255;
3422
3651
  var ABSENT = Object.freeze({ kind: "absent" });
3423
3652
  var INVALID = Object.freeze({ kind: "invalid" });
3424
- var readBounded = async (filePath) => {
3653
+ var readBounded2 = async (filePath) => {
3425
3654
  let handle;
3426
3655
  try {
3427
- handle = await open(filePath, "r");
3656
+ handle = await open2(filePath, "r");
3428
3657
  const buffer = Buffer.alloc(MAX_GIT_FILE_BYTES);
3429
3658
  const { bytesRead } = await handle.read(buffer, 0, MAX_GIT_FILE_BYTES, 0);
3430
3659
  return buffer.subarray(0, bytesRead).toString("utf8");
@@ -3445,7 +3674,7 @@ var parseHeadBranch = (head) => {
3445
3674
  return branch;
3446
3675
  };
3447
3676
  var firstLine = (content) => content.split(/\r?\n/, 1)[0]?.trim() ?? "";
3448
- var resolveGitPath = (target, base) => target === void 0 || target.length === 0 || target.includes("\0") ? void 0 : path2.resolve(base, target);
3677
+ var resolveGitPath = (target, base) => target === void 0 || target.length === 0 || target.includes("\0") ? void 0 : path3.resolve(base, target);
3449
3678
  var parseGitDirFile = (content, worktreeRoot) => {
3450
3679
  const line = firstLine(content);
3451
3680
  return resolveGitPath(
@@ -3471,17 +3700,17 @@ var isDirectory = async (directory) => {
3471
3700
  }
3472
3701
  };
3473
3702
  var repositoryOf = async (worktreeRoot, gitDir) => {
3474
- const commonDirFile = path2.join(gitDir, "commondir");
3475
- const content = await readBounded(commonDirFile);
3703
+ const commonDirFile = path3.join(gitDir, "commondir");
3704
+ const content = await readBounded2(commonDirFile);
3476
3705
  if (content === void 0) {
3477
3706
  return await isMissing(commonDirFile) ? { kind: "main", mainRoot: worktreeRoot } : { kind: "linked" };
3478
3707
  }
3479
3708
  const commonDir = parseCommonDirFile(content, gitDir);
3480
- const mainRoot = commonDir !== void 0 && path2.basename(commonDir) === ".git" && await isDirectory(commonDir) ? path2.dirname(commonDir) : void 0;
3709
+ const mainRoot = commonDir !== void 0 && path3.basename(commonDir) === ".git" && await isDirectory(commonDir) ? path3.dirname(commonDir) : void 0;
3481
3710
  return { kind: "linked", ...mainRoot === void 0 ? {} : { mainRoot } };
3482
3711
  };
3483
3712
  var probeDirectory = async (directory) => {
3484
- const dotGit = path2.join(directory, ".git");
3713
+ const dotGit = path3.join(directory, ".git");
3485
3714
  let info;
3486
3715
  try {
3487
3716
  info = await stat(dotGit);
@@ -3492,13 +3721,13 @@ var probeDirectory = async (directory) => {
3492
3721
  if (info.isDirectory()) {
3493
3722
  gitDir = dotGit;
3494
3723
  } else if (info.isFile()) {
3495
- const content = await readBounded(dotGit);
3724
+ const content = await readBounded2(dotGit);
3496
3725
  gitDir = content === void 0 ? void 0 : parseGitDirFile(content, directory);
3497
3726
  }
3498
3727
  if (gitDir === void 0) {
3499
3728
  return INVALID;
3500
3729
  }
3501
- const head = await readBounded(path2.join(gitDir, "HEAD"));
3730
+ const head = await readBounded2(path3.join(gitDir, "HEAD"));
3502
3731
  if (head === void 0) {
3503
3732
  return INVALID;
3504
3733
  }
@@ -3528,10 +3757,10 @@ var createFilesystemWorktreeLocator = (options = {}) => {
3528
3757
  };
3529
3758
  const locate = async (absolutePath) => {
3530
3759
  try {
3531
- if (!path2.isAbsolute(absolutePath) || absolutePath.includes("\0")) {
3760
+ if (!path3.isAbsolute(absolutePath) || absolutePath.includes("\0")) {
3532
3761
  return void 0;
3533
3762
  }
3534
- let directory = path2.resolve(absolutePath);
3763
+ let directory = path3.resolve(absolutePath);
3535
3764
  for (let depth = 0; depth < MAX_WORKTREE_WALK_DEPTH; depth += 1) {
3536
3765
  const probe = await cachedProbe(directory);
3537
3766
  if (probe.kind === "worktree") {
@@ -3540,7 +3769,7 @@ var createFilesystemWorktreeLocator = (options = {}) => {
3540
3769
  if (probe.kind === "invalid") {
3541
3770
  return void 0;
3542
3771
  }
3543
- const parent = path2.dirname(directory);
3772
+ const parent = path3.dirname(directory);
3544
3773
  if (parent === directory) {
3545
3774
  return void 0;
3546
3775
  }
@@ -3554,13 +3783,19 @@ var createFilesystemWorktreeLocator = (options = {}) => {
3554
3783
  return { locate };
3555
3784
  };
3556
3785
  export {
3786
+ DEFAULT_SESSION_CONTEXT_BUDGET_MILLIS,
3787
+ DEFAULT_SESSION_CONTEXT_MAX_BYTES,
3557
3788
  DEFAULT_TARGET_RESOLUTION_BUDGET_MILLIS,
3558
3789
  DEFAULT_WORKTREE_CACHE_TTL_MILLIS,
3559
3790
  LOG_LEVEL_RANK,
3791
+ MAX_SESSION_CONTEXT_SEGMENTS,
3560
3792
  MAX_WORKTREE_WALK_DEPTH,
3793
+ SESSION_CONTEXT_AGENT_TOOLS,
3794
+ SESSION_CONTEXT_FILE_VERSION,
3561
3795
  appliedDeliverySchema,
3562
3796
  classifyDurability,
3563
3797
  createDeterministicIdGenerator,
3798
+ createDirectorySessionContextReader,
3564
3799
  createFilesystemWorktreeLocator,
3565
3800
  createFixedClock,
3566
3801
  createInMemoryStateStore,
@@ -3574,12 +3809,20 @@ export {
3574
3809
  createSystemClock,
3575
3810
  hostDeliveryIdentity,
3576
3811
  isCommittable,
3812
+ isReservedSessionContextKey,
3813
+ isSessionContextFileName,
3577
3814
  logLevelSchema,
3578
3815
  parseCommonDirFile,
3579
3816
  parseGitDirFile,
3580
3817
  parseHeadBranch,
3818
+ parseSessionContextFile,
3581
3819
  resolveDeliveryIdentity,
3582
3820
  resolveEventTargets,
3821
+ sanitizeSessionContextAttributes,
3822
+ segmentInForce,
3823
+ sessionContextAgentTool,
3824
+ sessionContextFilePath,
3825
+ stampSessionContext,
3583
3826
  stateRecordSchema,
3584
3827
  stateValueSchema,
3585
3828
  usageScopeSchema