@osfactory/otel-hook 0.3.0 → 0.4.1

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 (43) hide show
  1. package/dist/{adapter-DXpNtnaf.d.ts → adapter-BgqtlADe.d.ts} +10 -3
  2. package/dist/cli.js +1001 -487
  3. package/dist/cli.js.map +1 -1
  4. package/dist/{events-VxBnDFaO.d.ts → events-C3h3GvHj.d.ts} +58 -0
  5. package/dist/{filesystem-store-J8jjDMTh.d.ts → filesystem-store-BAq3VGVv.d.ts} +1 -1
  6. package/dist/{hook-_mlO3akA.d.ts → hook-CQiNa88Q.d.ts} +12 -4
  7. package/dist/index.d.ts +13 -12
  8. package/dist/index.js +1127 -599
  9. package/dist/index.js.map +1 -1
  10. package/dist/install.d.ts +5 -4
  11. package/dist/install.js +99 -68
  12. package/dist/install.js.map +1 -1
  13. package/dist/integration.d.ts +15 -8
  14. package/dist/integration.js +505 -121
  15. package/dist/integration.js.map +1 -1
  16. package/dist/lifecycle.d.ts +3 -3
  17. package/dist/lifecycle.js +23 -2
  18. package/dist/lifecycle.js.map +1 -1
  19. package/dist/{memory-DXVBc8V9.d.ts → memory-kflYgZbg.d.ts} +2 -2
  20. package/dist/model.d.ts +2 -1
  21. package/dist/model.js +79 -41
  22. package/dist/model.js.map +1 -1
  23. package/dist/{otlp-log-sink-DTSa0KRF.d.ts → otlp-log-sink-BZIgYPKN.d.ts} +3 -3
  24. package/dist/{payload-BWV5-4n3.d.ts → payload-DpyU8F-z.d.ts} +1 -1
  25. package/dist/{ports-Q8x0ODhs.d.ts → ports-B_iwJQPQ.d.ts} +20 -2
  26. package/dist/providers.d.ts +27 -9
  27. package/dist/providers.js +664 -452
  28. package/dist/providers.js.map +1 -1
  29. package/dist/{registry-Dqr3VNmT.d.ts → registry-BSBS8t7S.d.ts} +1 -1
  30. package/dist/runtime.d.ts +87 -11
  31. package/dist/runtime.js +379 -67
  32. package/dist/runtime.js.map +1 -1
  33. package/dist/{semconv-CIU-2kGO.d.ts → semconv-BeUPQ7_q.d.ts} +1 -1
  34. package/dist/state.d.ts +4 -4
  35. package/dist/state.js.map +1 -1
  36. package/dist/target-8RfaVxp8.d.ts +83 -0
  37. package/dist/telemetry.d.ts +6 -6
  38. package/dist/telemetry.js +86 -10
  39. package/dist/telemetry.js.map +1 -1
  40. package/dist/testing.d.ts +14 -7
  41. package/dist/testing.js +814 -492
  42. package/dist/testing.js.map +1 -1
  43. package/package.json +4 -1
@@ -692,7 +692,7 @@ import {
692
692
  } from "@opentelemetry/semantic-conventions/incubating";
693
693
 
694
694
  // src/version.ts
695
- var VERSION = "0.3.0";
695
+ var VERSION = "0.4.1";
696
696
 
697
697
  // src/telemetry/export-identity.ts
698
698
  import { ATTR_SESSION_ID } from "@opentelemetry/semantic-conventions/incubating";
@@ -708,6 +708,23 @@ var ATTR_OTELHOOK_PROVIDER_ID = "otelhook.provider.id";
708
708
  var ATTR_OTELHOOK_PROVIDER_VERSION = "otelhook.provider.version";
709
709
  var ATTR_OTELHOOK_WORKSPACE_ID = "otelhook.workspace.id";
710
710
  var HAR_SESSION_KEY = "har.session_key";
711
+ var ATTR_OTELHOOK_SUBAGENT_ID = "otelhook.subagent.id";
712
+ var ATTR_VCS_REF_HEAD_NAME = "vcs.ref.head.name";
713
+ var ATTR_OTELHOOK_TARGET_WORKSPACE_ID = "otelhook.target.workspace.id";
714
+ var ATTR_OTELHOOK_TARGET_SOURCE = "otelhook.target.source";
715
+ var ATTR_OTELHOOK_USAGE_TEMPORALITY = "otelhook.usage.temporality";
716
+ var targetAttributes = (event2) => {
717
+ if (event2.type !== "tool.start" && event2.type !== "tool.end" || event2.target === void 0) {
718
+ return {};
719
+ }
720
+ const { target } = event2;
721
+ return {
722
+ [ATTR_OTELHOOK_TARGET_WORKSPACE_ID]: target.workspaceId,
723
+ [ATTR_OTELHOOK_TARGET_SOURCE]: target.source,
724
+ ...target.vcsBranchName === void 0 ? {} : { [ATTR_VCS_REF_HEAD_NAME]: target.vcsBranchName }
725
+ };
726
+ };
727
+ var usageTemporalityAttributes = (usage) => usage === void 0 ? {} : { [ATTR_OTELHOOK_USAGE_TEMPORALITY]: usage.temporality };
711
728
  var isPrimitiveAttribute = (value) => typeof value === "string" || typeof value === "number" || typeof value === "boolean";
712
729
  var passthroughHarAttributes = (resource) => {
713
730
  const attributes = {};
@@ -743,6 +760,7 @@ var exportIdentityAttributes = (event2, resource, ids) => {
743
760
  [ATTR_OTELHOOK_PROVIDER_ID]: event2.provenance.providerId,
744
761
  ...event2.provenance.providerVersion === void 0 ? {} : { [ATTR_OTELHOOK_PROVIDER_VERSION]: event2.provenance.providerVersion },
745
762
  [ATTR_OTELHOOK_WORKSPACE_ID]: event2.workspace.workspaceId,
763
+ ...event2.subagentId === void 0 ? {} : { [ATTR_OTELHOOK_SUBAGENT_ID]: event2.subagentId },
746
764
  ...passthroughHarAttributes(resource),
747
765
  ...hexTraceAttributes(ids)
748
766
  };
@@ -764,6 +782,7 @@ var ATTR_OTELHOOK_DELEGATION_DEPTH = "otelhook.delegation_depth";
764
782
  var ATTR_OTELHOOK_COMPACTION_TRIGGER = "otelhook.compaction.trigger";
765
783
  var ATTR_OTELHOOK_AGENT_NAME = "otelhook.agent.name";
766
784
  var ATTR_OTELHOOK_AGENT_VERSION = "otelhook.agent.version";
785
+ var ATTR_OTELHOOK_GENERATION_ID = "otelhook.generation.id";
767
786
  var FIELD_SEPARATOR = "\0";
768
787
  var digestHex = (parts, length) => createHash("sha256").update(parts.join(FIELD_SEPARATOR)).digest("hex").slice(0, length);
769
788
  var MAX_RECOVERED_START_ATTRIBUTES = 16;
@@ -830,8 +849,10 @@ var startOnlySpanAttributes = (event2) => {
830
849
  };
831
850
  // `toolName` and `toolCallId` are on both tool edges, so they are not
832
851
  // start-only and persisting them would just pad every record.
852
+ // The target is carried forward too: an end-only process may see a payload
853
+ // with less to go on (no tool input), and the start's evidence still holds.
833
854
  case "tool.start":
834
- return { [ATTR_OTELHOOK_TOOL_KIND]: event2.toolKind };
855
+ return { [ATTR_OTELHOOK_TOOL_KIND]: event2.toolKind, ...targetAttributes(event2) };
835
856
  case "subagent.start":
836
857
  return { [ATTR_OTELHOOK_DELEGATION_DEPTH]: event2.delegationDepth };
837
858
  default:
@@ -862,9 +883,52 @@ var usageAttributes = (usage, resetDetected) => {
862
883
  [ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS]: usage.cachedInputTokens,
863
884
  [ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS]: usage.cacheCreationInputTokens,
864
885
  [ATTR_GEN_AI_USAGE_REASONING_OUTPUT_TOKENS]: usage.reasoningOutputTokens,
886
+ ...usageTemporalityAttributes(usage),
865
887
  ...resetDetected ? { [ATTR_OTELHOOK_RESET_DETECTED]: true } : {}
866
888
  };
867
889
  };
890
+ var TARGET_SOURCE_RANK = Object.freeze({
891
+ "tool-path": 3,
892
+ "shell-cwd": 2,
893
+ "session-cwd": 1
894
+ });
895
+ var TARGET_KEYS = [
896
+ ATTR_OTELHOOK_TARGET_WORKSPACE_ID,
897
+ ATTR_OTELHOOK_TARGET_SOURCE,
898
+ ATTR_VCS_REF_HEAD_NAME
899
+ ];
900
+ var pickTarget = (attributes) => {
901
+ const picked = {};
902
+ for (const key of TARGET_KEYS) {
903
+ if (attributes[key] !== void 0) {
904
+ picked[key] = attributes[key];
905
+ }
906
+ }
907
+ return picked;
908
+ };
909
+ var withoutTarget = (attributes) => {
910
+ const rest = { ...attributes };
911
+ for (const key of TARGET_KEYS) {
912
+ delete rest[key];
913
+ }
914
+ return rest;
915
+ };
916
+ var rankOf = (candidate) => {
917
+ const source = candidate[ATTR_OTELHOOK_TARGET_SOURCE];
918
+ return typeof source === "string" && Object.hasOwn(TARGET_SOURCE_RANK, source) ? TARGET_SOURCE_RANK[source] ?? 0 : 0;
919
+ };
920
+ var strongestTarget = (candidates) => {
921
+ let best = {};
922
+ let bestRank = 0;
923
+ for (const candidate of candidates) {
924
+ const rank = rankOf(candidate);
925
+ if (rank > 0 && rank >= bestRank) {
926
+ best = candidate;
927
+ bestRank = rank;
928
+ }
929
+ }
930
+ return best;
931
+ };
868
932
  var buildSpanContext = (traceId, spanId) => ({
869
933
  traceId,
870
934
  spanId,
@@ -975,6 +1039,9 @@ var buildLifecycleSpan = (plan, resource, scope) => {
975
1039
  ...model?.vendor === void 0 ? {} : { [ATTR_GEN_AI_SYSTEM]: model.vendor },
976
1040
  ...start?.model?.modelId === void 0 ? {} : { [ATTR_GEN_AI_REQUEST_MODEL]: start.model.modelId },
977
1041
  ...end?.model?.modelId === void 0 ? {} : { [ATTR_GEN_AI_RESPONSE_MODEL]: end.model.modelId },
1042
+ // The provider's own id for this unit of work (Cursor generation,
1043
+ // Codex turn): the key a consumer stores a usage observation under.
1044
+ [ATTR_OTELHOOK_GENERATION_ID]: group.ref.scopeKey,
978
1045
  ...end?.outcome === void 0 ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.outcome },
979
1046
  ...usageAttributes(end?.usage, false)
980
1047
  };
@@ -988,11 +1055,17 @@ var buildLifecycleSpan = (plan, resource, scope) => {
988
1055
  name = `tool ${toolName}`;
989
1056
  kind = SpanKind.CLIENT;
990
1057
  attributes = {
991
- ...attributes,
1058
+ // Target keys are re-chosen below as one unit, never mixed across edges.
1059
+ ...withoutTarget(attributes),
992
1060
  [ATTR_GEN_AI_TOOL_NAME]: toolName,
993
1061
  [ATTR_GEN_AI_TOOL_CALL_ID]: start?.toolCallId ?? end?.toolCallId ?? group.ref.scopeKey,
994
1062
  ...start?.toolKind === void 0 ? {} : { [ATTR_OTELHOOK_TOOL_KIND]: start.toolKind },
995
- ...end?.outcome === void 0 ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.outcome }
1063
+ ...end?.outcome === void 0 ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.outcome },
1064
+ ...strongestTarget([
1065
+ pickTarget(resolved.recovered),
1066
+ start === void 0 ? {} : targetAttributes(start),
1067
+ end === void 0 ? {} : targetAttributes(end)
1068
+ ])
996
1069
  };
997
1070
  status = outcomeStatus(end?.outcome);
998
1071
  break;
@@ -2299,11 +2372,11 @@ var createPrivacyService = (policyInput) => {
2299
2372
  };
2300
2373
  const flattenToAttributes = (value, prefix) => {
2301
2374
  const attributes = {};
2302
- const walk = (current, path3) => {
2375
+ const walk = (current, path5) => {
2303
2376
  if (typeof current === "string" || typeof current === "number" || typeof current === "boolean") {
2304
2377
  const primitive = toAttributePrimitive(current);
2305
2378
  if (primitive !== void 0) {
2306
- attributes[path3] = primitive;
2379
+ attributes[path5] = primitive;
2307
2380
  }
2308
2381
  return;
2309
2382
  }
@@ -2322,16 +2395,16 @@ var createPrivacyService = (policyInput) => {
2322
2395
  primitives.push(entryPrimitive);
2323
2396
  }
2324
2397
  if (uniform) {
2325
- attributes[path3] = primitives.slice(0, MAX_ATTRIBUTE_ARRAY_LENGTH);
2398
+ attributes[path5] = primitives.slice(0, MAX_ATTRIBUTE_ARRAY_LENGTH);
2326
2399
  return;
2327
2400
  }
2328
2401
  for (const [index, entry] of current.entries()) {
2329
- walk(entry, `${path3}.${index}`);
2402
+ walk(entry, `${path5}.${index}`);
2330
2403
  }
2331
2404
  return;
2332
2405
  }
2333
2406
  for (const [key, entry] of Object.entries(current)) {
2334
- walk(entry, path3 === "" ? key : `${path3}.${key}`);
2407
+ walk(entry, path5 === "" ? key : `${path5}.${key}`);
2335
2408
  }
2336
2409
  };
2337
2410
  walk(value, prefix);
@@ -2430,7 +2503,7 @@ var createSystemClock = () => ({
2430
2503
  });
2431
2504
 
2432
2505
  // src/runtime/hook.ts
2433
- import { z as z15 } from "zod";
2506
+ import { z as z16 } from "zod";
2434
2507
 
2435
2508
  // src/config/schema.ts
2436
2509
  import { z as z8 } from "zod";
@@ -2846,23 +2919,46 @@ var CANONICAL_SCHEMA_VERSION = 1;
2846
2919
  var canonicalSchemaVersionSchema = z11.literal(CANONICAL_SCHEMA_VERSION);
2847
2920
 
2848
2921
  // src/providers/adapter.ts
2849
- import { z as z13 } from "zod";
2922
+ import { z as z14 } from "zod";
2850
2923
 
2851
2924
  // src/model/events.ts
2925
+ import { z as z13 } from "zod";
2926
+
2927
+ // src/model/target.ts
2852
2928
  import { z as z12 } from "zod";
2853
- var modelDescriptorSchema = z12.strictObject({
2929
+ var targetSourceSchema = z12.enum(["tool-path", "shell-cwd", "session-cwd"]);
2930
+ var MAX_TARGET_HINT_PATHS = 8;
2931
+ var MAX_TARGET_PATH_LENGTH = 4096;
2932
+ var localPathSchema = z12.string().min(1).max(MAX_TARGET_PATH_LENGTH).refine((value) => !value.includes("\0"), "path must not contain NUL");
2933
+ var targetHintSchema = z12.strictObject({
2934
+ source: targetSourceSchema,
2935
+ paths: z12.array(localPathSchema).min(1).max(MAX_TARGET_HINT_PATHS).readonly(),
2936
+ /** Absolute directory that relative `paths` resolve against. */
2937
+ baseDirectory: localPathSchema.optional()
2938
+ }).readonly();
2939
+ var workspaceTargetSchema = z12.strictObject({
2940
+ workspaceId: workspaceIdSchema,
2941
+ /** Branch checked out in that worktree; absent on a detached HEAD. */
2942
+ vcsBranchName: nonEmptyStringSchema.optional(),
2943
+ source: targetSourceSchema
2944
+ }).readonly();
2945
+ var SUBAGENT_ID_PATTERN = /^[A-Za-z0-9_.:@+=-]{1,256}$/;
2946
+ var subagentIdSchema = z12.string().regex(SUBAGENT_ID_PATTERN);
2947
+
2948
+ // src/model/events.ts
2949
+ var modelDescriptorSchema = z13.strictObject({
2854
2950
  modelId: nonEmptyStringSchema,
2855
2951
  /** Vendor of the model, e.g. `anthropic`. Distinct from the agent provider. */
2856
2952
  vendor: nonEmptyStringSchema.optional(),
2857
2953
  family: nonEmptyStringSchema.optional()
2858
2954
  });
2859
- var costFactsSchema = z12.strictObject({
2955
+ var costFactsSchema = z13.strictObject({
2860
2956
  /** ISO 4217 code. */
2861
- currency: z12.string().length(3),
2862
- amount: z12.number().min(0).finite(),
2863
- source: z12.enum(["provider-reported", "computed"])
2957
+ currency: z13.string().length(3),
2958
+ amount: z13.number().min(0).finite(),
2959
+ source: z13.enum(["provider-reported", "computed"])
2864
2960
  });
2865
- var canonicalEventTypeSchema = z12.enum([
2961
+ var canonicalEventTypeSchema = z13.enum([
2866
2962
  "session.start",
2867
2963
  "session.end",
2868
2964
  "prompt.submitted",
@@ -2876,7 +2972,7 @@ var canonicalEventTypeSchema = z12.enum([
2876
2972
  "error.raised"
2877
2973
  ]);
2878
2974
  var CANONICAL_EVENT_TYPES = canonicalEventTypeSchema.options;
2879
- var outcomeSchema = z12.enum(["ok", "error", "cancelled", "timeout", "denied", "unknown"]);
2975
+ var outcomeSchema = z13.enum(["ok", "error", "cancelled", "timeout", "denied", "unknown"]);
2880
2976
  var baseEventFields = {
2881
2977
  schemaVersion: canonicalSchemaVersionSchema,
2882
2978
  eventId: eventIdSchema,
@@ -2887,39 +2983,45 @@ var baseEventFields = {
2887
2983
  occurredAt: epochMillisSchema,
2888
2984
  provenance: sourceProvenanceSchema,
2889
2985
  workspace: workspaceIdentitySchema,
2986
+ /**
2987
+ * The provider's own id for the subagent this event was emitted inside (e.g.
2988
+ * Claude Code's `agent_id`). Absent for the top-level agent. Set by the event
2989
+ * factory, never by hand.
2990
+ */
2991
+ subagentId: subagentIdSchema.optional(),
2890
2992
  extensions: extensionsSchema.default(emptyExtensions)
2891
2993
  };
2892
- var event = (shape) => z12.strictObject({ ...baseEventFields, ...shape });
2994
+ var event = (shape) => z13.strictObject({ ...baseEventFields, ...shape });
2893
2995
  var sessionStartEventSchema = event({
2894
- type: z12.literal("session.start"),
2895
- sessionKind: z12.enum(["interactive", "non-interactive", "unknown"]),
2996
+ type: z13.literal("session.start"),
2997
+ sessionKind: z13.enum(["interactive", "non-interactive", "unknown"]),
2896
2998
  agentName: nonEmptyStringSchema.optional(),
2897
2999
  agentVersion: nonEmptyStringSchema.optional(),
2898
3000
  model: modelDescriptorSchema.optional()
2899
3001
  });
2900
3002
  var sessionEndEventSchema = event({
2901
- type: z12.literal("session.end"),
2902
- reason: z12.enum(["completed", "aborted", "error", "timeout", "unknown"]),
3003
+ type: z13.literal("session.end"),
3004
+ reason: z13.enum(["completed", "aborted", "error", "timeout", "unknown"]),
2903
3005
  durationMillis: durationMillisSchema.optional(),
2904
3006
  /** Session totals, typically cumulative. */
2905
3007
  usage: canonicalUsageSchema.optional(),
2906
3008
  cost: costFactsSchema.optional()
2907
3009
  });
2908
3010
  var promptSubmittedEventSchema = event({
2909
- type: z12.literal("prompt.submitted"),
2910
- promptSource: z12.enum(["user", "automation", "resumed", "unknown"]),
3011
+ type: z13.literal("prompt.submitted"),
3012
+ promptSource: z13.enum(["user", "automation", "resumed", "unknown"]),
2911
3013
  content: contentFactSchema.optional(),
2912
- turnIndex: z12.number().int().min(0).optional()
3014
+ turnIndex: z13.number().int().min(0).optional()
2913
3015
  });
2914
3016
  var generationStartEventSchema = event({
2915
- type: z12.literal("generation.start"),
3017
+ type: z13.literal("generation.start"),
2916
3018
  generationId: nonEmptyStringSchema,
2917
3019
  model: modelDescriptorSchema,
2918
3020
  requestedMaxOutputTokens: tokenCountSchema.optional(),
2919
3021
  inputContent: contentFactsSchema.optional()
2920
3022
  });
2921
3023
  var generationEndEventSchema = event({
2922
- type: z12.literal("generation.end"),
3024
+ type: z13.literal("generation.end"),
2923
3025
  generationId: nonEmptyStringSchema,
2924
3026
  model: modelDescriptorSchema,
2925
3027
  outcome: outcomeSchema,
@@ -2929,7 +3031,7 @@ var generationEndEventSchema = event({
2929
3031
  cost: costFactsSchema.optional(),
2930
3032
  outputContent: contentFactsSchema.optional()
2931
3033
  });
2932
- var toolKindSchema = z12.enum([
3034
+ var toolKindSchema = z13.enum([
2933
3035
  "read",
2934
3036
  "write",
2935
3037
  "execute",
@@ -2940,59 +3042,63 @@ var toolKindSchema = z12.enum([
2940
3042
  "unknown"
2941
3043
  ]);
2942
3044
  var toolStartEventSchema = event({
2943
- type: z12.literal("tool.start"),
3045
+ type: z13.literal("tool.start"),
2944
3046
  toolCallId: nonEmptyStringSchema,
2945
3047
  toolName: nonEmptyStringSchema,
2946
3048
  toolKind: toolKindSchema,
2947
3049
  generationId: nonEmptyStringSchema.optional(),
2948
- input: contentFactSchema.optional()
3050
+ input: contentFactSchema.optional(),
3051
+ /** The git worktree this call targeted, resolved by the core (ADR 0008). */
3052
+ target: workspaceTargetSchema.optional()
2949
3053
  });
2950
3054
  var toolEndEventSchema = event({
2951
- type: z12.literal("tool.end"),
3055
+ type: z13.literal("tool.end"),
2952
3056
  toolCallId: nonEmptyStringSchema,
2953
3057
  toolName: nonEmptyStringSchema,
2954
3058
  outcome: outcomeSchema,
2955
3059
  durationMillis: durationMillisSchema.optional(),
2956
3060
  /** Present when the host asked for or recorded a permission decision. */
2957
- permissionDecision: z12.enum(["allowed", "denied", "deferred", "not-required"]).optional(),
2958
- output: contentFactSchema.optional()
3061
+ permissionDecision: z13.enum(["allowed", "denied", "deferred", "not-required"]).optional(),
3062
+ output: contentFactSchema.optional(),
3063
+ /** The git worktree this call targeted, resolved by the core (ADR 0008). */
3064
+ target: workspaceTargetSchema.optional()
2959
3065
  });
2960
3066
  var subagentStartEventSchema = event({
2961
- type: z12.literal("subagent.start"),
3067
+ type: z13.literal("subagent.start"),
2962
3068
  subagentInvocationId: invocationIdSchema,
2963
3069
  subagentType: nonEmptyStringSchema.optional(),
2964
3070
  /** 0 for the top-level agent; 1 for its direct children. */
2965
- delegationDepth: z12.number().int().min(0).max(64),
3071
+ delegationDepth: z13.number().int().min(0).max(64),
2966
3072
  model: modelDescriptorSchema.optional()
2967
3073
  });
2968
3074
  var subagentEndEventSchema = event({
2969
- type: z12.literal("subagent.end"),
3075
+ type: z13.literal("subagent.end"),
2970
3076
  subagentInvocationId: invocationIdSchema,
2971
3077
  outcome: outcomeSchema,
2972
3078
  durationMillis: durationMillisSchema.optional(),
2973
3079
  usage: canonicalUsageSchema.optional()
2974
3080
  });
2975
3081
  var compactionPerformedEventSchema = event({
2976
- type: z12.literal("compaction.performed"),
2977
- trigger: z12.enum(["automatic", "manual", "unknown"]),
3082
+ type: z13.literal("compaction.performed"),
3083
+ trigger: z13.enum(["automatic", "manual", "unknown"]),
2978
3084
  /** Provider-reported context size before and after compaction, if known. */
2979
3085
  contextTokensBefore: tokenCountSchema.optional(),
2980
3086
  contextTokensAfter: tokenCountSchema.optional(),
2981
- droppedMessageCount: z12.number().int().min(0).optional(),
3087
+ droppedMessageCount: z13.number().int().min(0).optional(),
2982
3088
  usage: canonicalUsageSchema.optional()
2983
3089
  });
2984
3090
  var errorRaisedEventSchema = event({
2985
- type: z12.literal("error.raised"),
3091
+ type: z13.literal("error.raised"),
2986
3092
  errorCode: otelHookErrorCodeSchema,
2987
3093
  severity: errorSeveritySchema,
2988
3094
  phase: errorPhaseSchema,
2989
- retryable: z12.boolean(),
3095
+ retryable: z13.boolean(),
2990
3096
  /** Error text is content: it is described, never embedded verbatim by default. */
2991
3097
  message: contentFactSchema.optional(),
2992
3098
  /** Non-sensitive, provider-agnostic short label. */
2993
3099
  detail: nonEmptyStringSchema.optional()
2994
3100
  });
2995
- var canonicalEventSchema = z12.discriminatedUnion("type", [
3101
+ var canonicalEventSchema = z13.discriminatedUnion("type", [
2996
3102
  sessionStartEventSchema,
2997
3103
  sessionEndEventSchema,
2998
3104
  promptSubmittedEventSchema,
@@ -3007,26 +3113,26 @@ var canonicalEventSchema = z12.discriminatedUnion("type", [
3007
3113
  ]);
3008
3114
 
3009
3115
  // src/providers/adapter.ts
3010
- var providerDetectionSchema = z13.strictObject({
3116
+ var providerDetectionSchema = z14.strictObject({
3011
3117
  providerId: resolvedProviderIdSchema,
3012
3118
  confidence: detectionConfidenceSchema,
3013
3119
  /**
3014
3120
  * Short, non-sensitive justifications, e.g. `"payload.hook_event_name present"`.
3015
3121
  * Reasons are exported in diagnostics, so they must not quote payload values.
3016
3122
  */
3017
- reasons: z13.array(z13.string().min(1).max(160)).max(8),
3123
+ reasons: z14.array(z14.string().min(1).max(160)).max(8),
3018
3124
  providerVersion: nonEmptyStringSchema.optional(),
3019
3125
  /** The provider's own name for this event, when the payload states one. */
3020
3126
  sourceEventName: nonEmptyStringSchema.optional()
3021
3127
  });
3022
- var deliveryIdentifierSupportSchema = z13.enum(["none", "partial", "all"]);
3128
+ var deliveryIdentifierSupportSchema = z14.enum(["none", "partial", "all"]);
3023
3129
  var DELIVERY_COMPONENT_PATTERN = /^[A-Za-z0-9_.:@+=-]{1,256}$/;
3024
- var deliveryComponentSchema = z13.string().regex(
3130
+ var deliveryComponentSchema = z14.string().regex(
3025
3131
  DELIVERY_COMPONENT_PATTERN,
3026
3132
  "delivery component must be identifier-shaped: no whitespace, no path separators"
3027
3133
  );
3028
3134
  var MAX_DELIVERY_COMPONENTS = 8;
3029
- var providerDeliveryClaimSchema = z13.strictObject({
3135
+ var providerDeliveryClaimSchema = z14.strictObject({
3030
3136
  /**
3031
3137
  * The provider's own session/conversation id. Scopes the callback identity, so
3032
3138
  * two sessions reusing one tool-call id never collide.
@@ -3038,26 +3144,26 @@ var providerDeliveryClaimSchema = z13.strictObject({
3038
3144
  * Identifier-shaped payload fields that, together with `sourceEventName`,
3039
3145
  * name this callback within the session exactly once.
3040
3146
  */
3041
- components: z13.array(deliveryComponentSchema).min(1).max(MAX_DELIVERY_COMPONENTS).readonly(),
3147
+ components: z14.array(deliveryComponentSchema).min(1).max(MAX_DELIVERY_COMPONENTS).readonly(),
3042
3148
  /**
3043
3149
  * Short, non-sensitive justifications, e.g. `"payload.tool_use_id names one
3044
3150
  * tool call"`. Evidence reaches diagnostics, so it must name fields, never
3045
3151
  * quote their values.
3046
3152
  */
3047
- evidence: z13.array(z13.string().min(1).max(160)).min(1).max(4).readonly()
3153
+ evidence: z14.array(z14.string().min(1).max(160)).min(1).max(4).readonly()
3048
3154
  });
3049
3155
  var DELIVERY_GAP_REASON_PATTERN = /^[^\n\r\t\\/]{1,240}$/;
3050
- var deliveryGapReasonSchema = z13.string().regex(
3156
+ var deliveryGapReasonSchema = z14.string().regex(
3051
3157
  DELIVERY_GAP_REASON_PATTERN,
3052
3158
  "delivery gap reason must be one line of prose: no path separators, no control characters"
3053
3159
  );
3054
3160
  var MAX_DELIVERY_GAPS = 48;
3055
- var providerDeliveryGapsSchema = z13.record(deliveryComponentSchema, deliveryGapReasonSchema).refine((gaps) => Object.keys(gaps).length <= MAX_DELIVERY_GAPS, {
3161
+ var providerDeliveryGapsSchema = z14.record(deliveryComponentSchema, deliveryGapReasonSchema).refine((gaps) => Object.keys(gaps).length <= MAX_DELIVERY_GAPS, {
3056
3162
  message: `at most ${String(MAX_DELIVERY_GAPS)} delivery gaps may be declared`
3057
3163
  });
3058
- var providerCapabilitiesSchema = z13.strictObject({
3164
+ var providerCapabilitiesSchema = z14.strictObject({
3059
3165
  /** Event types the adapter can produce. */
3060
- lifecycleEvents: z13.array(canonicalEventTypeSchema).max(32).readonly(),
3166
+ lifecycleEvents: z14.array(canonicalEventTypeSchema).max(32).readonly(),
3061
3167
  usageTemporality: usageTemporalitySchema,
3062
3168
  /**
3063
3169
  * Which accumulator series a `cumulative` report continues — that is, which
@@ -3076,32 +3182,32 @@ var providerCapabilitiesSchema = z13.strictObject({
3076
3182
  * Subagent snapshots keep their own series regardless: a delegated agent's
3077
3183
  * counter is not a point on the parent session's curve.
3078
3184
  */
3079
- cumulativeUsageSeries: z13.enum(["event-scope", "session-lifetime"]).optional(),
3080
- reportsCachedInput: z13.boolean(),
3081
- reportsCacheCreation: z13.boolean(),
3185
+ cumulativeUsageSeries: z14.enum(["event-scope", "session-lifetime"]).optional(),
3186
+ reportsCachedInput: z14.boolean(),
3187
+ reportsCacheCreation: z14.boolean(),
3082
3188
  cacheCreationAccounting: cacheCreationAccountingSchema,
3083
- reportsReasoningOutput: z13.boolean(),
3084
- reportsProviderTotal: z13.boolean(),
3085
- reportsCost: z13.boolean(),
3086
- emitsSubagentEvents: z13.boolean(),
3087
- emitsCompactionEvents: z13.boolean(),
3189
+ reportsReasoningOutput: z14.boolean(),
3190
+ reportsProviderTotal: z14.boolean(),
3191
+ reportsCost: z14.boolean(),
3192
+ emitsSubagentEvents: z14.boolean(),
3193
+ emitsCompactionEvents: z14.boolean(),
3088
3194
  /** True when the provider reads a structured response from stdout. */
3089
- requiresHookResponse: z13.boolean(),
3195
+ requiresHookResponse: z14.boolean(),
3090
3196
  /** How much of this provider's hook traffic is replay-identifiable. */
3091
3197
  deliveryIdentifier: deliveryIdentifierSupportSchema
3092
3198
  });
3093
- var providerHookResponseSchema = z13.strictObject({
3199
+ var providerHookResponseSchema = z14.strictObject({
3094
3200
  /**
3095
3201
  * Always 0. A telemetry hook that can fail the host agent is a liability, so
3096
3202
  * the type forbids expressing anything else (ADR 0004).
3097
3203
  */
3098
- exitCode: z13.literal(0),
3204
+ exitCode: z14.literal(0),
3099
3205
  /** Protocol response text. Omit to write nothing at all. */
3100
- stdout: z13.string().max(8192).optional(),
3206
+ stdout: z14.string().max(8192).optional(),
3101
3207
  /** Non-sensitive diagnostic text for stderr. */
3102
- stderr: z13.string().max(8192).optional(),
3208
+ stderr: z14.string().max(8192).optional(),
3103
3209
  /** Declares which of the two stdout contracts this response follows. */
3104
- contract: z13.enum(["silent", "provider-protocol"])
3210
+ contract: z14.enum(["silent", "provider-protocol"])
3105
3211
  });
3106
3212
  var SILENT_HOOK_RESPONSE = Object.freeze({
3107
3213
  exitCode: 0,
@@ -3338,15 +3444,15 @@ var createDeterministicIdGenerator = (options = {}) => {
3338
3444
  };
3339
3445
 
3340
3446
  // src/runtime/ports.ts
3341
- import { z as z14 } from "zod";
3342
- var appliedDeliverySchema = z14.strictObject({
3343
- callbackId: z14.string().regex(/^[A-Za-z0-9_-]{1,128}$/),
3447
+ import { z as z15 } from "zod";
3448
+ var appliedDeliverySchema = z15.strictObject({
3449
+ callbackId: z15.string().regex(/^[A-Za-z0-9_-]{1,128}$/),
3344
3450
  /** How many of that delivery's observations are folded in, counted from one. */
3345
- applications: z14.number().int().min(1).max(4096)
3451
+ applications: z15.number().int().min(1).max(4096)
3346
3452
  });
3347
- var stateValueSchema = z14.discriminatedUnion("kind", [
3348
- z14.strictObject({
3349
- kind: z14.literal("usage-cumulative"),
3453
+ var stateValueSchema = z15.discriminatedUnion("kind", [
3454
+ z15.strictObject({
3455
+ kind: z15.literal("usage-cumulative"),
3350
3456
  usage: canonicalUsageSchema,
3351
3457
  /**
3352
3458
  * Optional: absent on every record written before this field existed, which
@@ -3355,22 +3461,22 @@ var stateValueSchema = z14.discriminatedUnion("kind", [
3355
3461
  */
3356
3462
  appliedDelivery: appliedDeliverySchema.optional()
3357
3463
  }),
3358
- z14.strictObject({
3359
- kind: z14.literal("sequence"),
3464
+ z15.strictObject({
3465
+ kind: z15.literal("sequence"),
3360
3466
  next: sequenceNumberSchema
3361
3467
  }),
3362
- z14.strictObject({
3363
- kind: z14.literal("attributes"),
3468
+ z15.strictObject({
3469
+ kind: z15.literal("attributes"),
3364
3470
  attributes: attributesSchema
3365
3471
  })
3366
3472
  ]);
3367
- var stateRecordSchema = z14.strictObject({
3473
+ var stateRecordSchema = z15.strictObject({
3368
3474
  /** Incremented on each write; lets callers detect lost updates. */
3369
- revision: z14.number().int().min(0),
3475
+ revision: z15.number().int().min(0),
3370
3476
  updatedAt: epochMillisSchema,
3371
3477
  value: stateValueSchema
3372
3478
  });
3373
- var logLevelSchema = z14.enum(["silent", "error", "warn", "info", "debug"]);
3479
+ var logLevelSchema = z15.enum(["silent", "error", "warn", "info", "debug"]);
3374
3480
  var LOG_LEVEL_RANK = Object.freeze({
3375
3481
  silent: 0,
3376
3482
  error: 1,
@@ -3387,8 +3493,144 @@ var createNullLogger = () => ({
3387
3493
  debug: () => void 0
3388
3494
  });
3389
3495
 
3496
+ // src/runtime/target-resolution.ts
3497
+ import * as path from "path";
3498
+
3499
+ // src/privacy/workspace.ts
3500
+ var canonicalizeGitRemote = (remoteUrl) => {
3501
+ const trimmed = remoteUrl.trim();
3502
+ const scpLike = /^([^@/]+)@([^:]+):(.+)$/.exec(trimmed);
3503
+ const withoutScheme = scpLike ? `${scpLike[2] ?? ""}/${scpLike[3] ?? ""}` : trimmed.replace(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//, "").replace(/^[^@/]+@/, "");
3504
+ return withoutScheme.replace(/:\d+\//, "/").replace(/\/+$/, "").replace(/\.git$/i, "").replace(/\/+$/, "").toLowerCase();
3505
+ };
3506
+ var keySourceOf = (input) => {
3507
+ switch (input.kind) {
3508
+ case "git-remote":
3509
+ return "git-remote";
3510
+ case "git-root":
3511
+ return "git-root";
3512
+ case "working-directory":
3513
+ return "working-directory";
3514
+ case "explicit":
3515
+ return "explicit";
3516
+ case "unknown":
3517
+ return "unknown";
3518
+ }
3519
+ };
3520
+ var keyMaterialOf = (input) => {
3521
+ switch (input.kind) {
3522
+ case "git-remote":
3523
+ return canonicalizeGitRemote(input.remoteUrl);
3524
+ case "git-root":
3525
+ case "working-directory":
3526
+ return input.absolutePath.replace(/[/\\]+$/, "");
3527
+ case "explicit":
3528
+ return input.value;
3529
+ case "unknown":
3530
+ return void 0;
3531
+ }
3532
+ };
3533
+ var deriveWorkspaceIdentity = (privacy, input, labels = {}) => {
3534
+ const keySource = keySourceOf(input);
3535
+ const material = keyMaterialOf(input);
3536
+ const workspaceId = material === void 0 || material === "" ? "unknown:0000000000000000" : privacy.deriveOpaqueId(`workspace/${keySource}`, material);
3537
+ return workspaceIdentitySchema.parse({
3538
+ workspaceId,
3539
+ keySource: material === void 0 || material === "" ? "unknown" : keySource,
3540
+ ...labels.repositoryName === void 0 ? {} : { repositoryName: labels.repositoryName.slice(0, 128) },
3541
+ ...labels.vcsBranchName === void 0 ? {} : { vcsBranchName: labels.vcsBranchName.slice(0, 128) },
3542
+ ...labels.vcsRevisionId === void 0 ? {} : { vcsRevisionId: privacy.deriveOpaqueId("workspace/revision", labels.vcsRevisionId) }
3543
+ });
3544
+ };
3545
+
3546
+ // src/runtime/target-resolution.ts
3547
+ var DEFAULT_TARGET_RESOLUTION_BUDGET_MILLIS = 50;
3548
+ var absolutePathsOf = (hint) => {
3549
+ const base = hint.baseDirectory !== void 0 && path.isAbsolute(hint.baseDirectory) ? hint.baseDirectory : void 0;
3550
+ const resolved = [];
3551
+ for (const candidate of hint.paths) {
3552
+ if (path.isAbsolute(candidate)) {
3553
+ resolved.push(path.resolve(candidate));
3554
+ } else if (base !== void 0) {
3555
+ resolved.push(path.resolve(base, candidate));
3556
+ } else {
3557
+ return void 0;
3558
+ }
3559
+ }
3560
+ return resolved;
3561
+ };
3562
+ var resolveHint = async (hint, locator, privacy) => {
3563
+ const paths = absolutePathsOf(hint);
3564
+ if (paths === void 0) {
3565
+ return void 0;
3566
+ }
3567
+ const located = await Promise.all(
3568
+ [...new Set(paths)].map((candidate) => locator.locate(candidate))
3569
+ );
3570
+ const [first] = located;
3571
+ if (first === void 0 || located.some((entry) => entry?.root !== first.root)) {
3572
+ return void 0;
3573
+ }
3574
+ const identity = deriveWorkspaceIdentity(
3575
+ privacy,
3576
+ { kind: "git-root", absolutePath: first.root },
3577
+ first.branch === void 0 ? {} : { vcsBranchName: first.branch }
3578
+ );
3579
+ if (identity.keySource !== "git-root") {
3580
+ return void 0;
3581
+ }
3582
+ const parsed = workspaceTargetSchema.safeParse({
3583
+ workspaceId: identity.workspaceId,
3584
+ ...identity.vcsBranchName === void 0 ? {} : { vcsBranchName: identity.vcsBranchName },
3585
+ source: hint.source
3586
+ });
3587
+ return parsed.success ? parsed.data : void 0;
3588
+ };
3589
+ var resolveEventTargets = async (input) => {
3590
+ const pending = input.events.filter(
3591
+ (event2) => (event2.type === "tool.start" || event2.type === "tool.end") && input.hints.has(event2.eventId)
3592
+ );
3593
+ if (pending.length === 0) {
3594
+ return { events: input.events, resolved: 0, timedOut: false };
3595
+ }
3596
+ const targets = /* @__PURE__ */ new Map();
3597
+ const work = Promise.all(
3598
+ pending.map(async (event2) => {
3599
+ const hint = input.hints.get(event2.eventId);
3600
+ if (hint === void 0) {
3601
+ return;
3602
+ }
3603
+ try {
3604
+ const target = await resolveHint(hint, input.locator, input.privacy);
3605
+ if (target !== void 0) {
3606
+ targets.set(event2.eventId, target);
3607
+ }
3608
+ } catch {
3609
+ }
3610
+ })
3611
+ ).then(() => "done");
3612
+ let timer;
3613
+ const deadline = new Promise((resolve3) => {
3614
+ timer = setTimeout(() => resolve3("timeout"), Math.max(0, input.budgetMillis));
3615
+ timer.unref?.();
3616
+ });
3617
+ const finished = await Promise.race([work, deadline]);
3618
+ if (timer !== void 0) {
3619
+ clearTimeout(timer);
3620
+ }
3621
+ const settled = new Map(targets);
3622
+ const events = input.events.map((event2) => {
3623
+ const target = settled.get(event2.eventId);
3624
+ if (target === void 0 || event2.type !== "tool.start" && event2.type !== "tool.end") {
3625
+ return event2;
3626
+ }
3627
+ return { ...event2, target };
3628
+ });
3629
+ return { events, resolved: settled.size, timedOut: finished === "timeout" };
3630
+ };
3631
+
3390
3632
  // src/runtime/hook.ts
3391
- var usageScopeSchema = z15.enum(["session", "generation", "subagent"]);
3633
+ var usageScopeSchema = z16.enum(["session", "generation", "subagent"]);
3392
3634
  var classifyDurability = (input) => {
3393
3635
  if (!input.attempted) {
3394
3636
  return "nothing-to-deliver";
@@ -3927,7 +4169,12 @@ var createOtelHook = (deps) => {
3927
4169
  );
3928
4170
  }
3929
4171
  }
3930
- return { kind: "ready", batch: batch2, dropped: screened.dropped };
4172
+ return {
4173
+ kind: "ready",
4174
+ batch: batch2,
4175
+ dropped: screened.dropped,
4176
+ ...parsed.targetHints === void 0 ? {} : { targetHints: parsed.targetHints }
4177
+ };
3931
4178
  };
3932
4179
  let prepared;
3933
4180
  try {
@@ -3972,7 +4219,24 @@ var createOtelHook = (deps) => {
3972
4219
  if (prepared.kind === "early") {
3973
4220
  return prepared.outcome;
3974
4221
  }
3975
- const { batch, dropped } = prepared;
4222
+ const { dropped } = prepared;
4223
+ let batch = prepared.batch;
4224
+ if (!suppress && deps.worktreeLocator !== void 0 && prepared.targetHints !== void 0 && prepared.targetHints.size > 0) {
4225
+ const targeted = await resolveEventTargets({
4226
+ events: batch,
4227
+ hints: prepared.targetHints,
4228
+ locator: deps.worktreeLocator,
4229
+ privacy,
4230
+ budgetMillis: deps.targetResolutionBudgetMillis ?? DEFAULT_TARGET_RESOLUTION_BUDGET_MILLIS
4231
+ });
4232
+ batch = targeted.events;
4233
+ if (targeted.timedOut) {
4234
+ logger.debug("worktree target resolution exceeded its budget", {
4235
+ "provider.id": detection.providerId,
4236
+ "target.resolved": targeted.resolved
4237
+ });
4238
+ }
4239
+ }
3976
4240
  let emitted = 0;
3977
4241
  let exportRejected = 0;
3978
4242
  if (!suppress && batch.length > 0) {
@@ -4121,10 +4385,124 @@ var buildErrorEvents = (diagnostics, identity, sequenceBase, ids, privacy) => {
4121
4385
  return events;
4122
4386
  };
4123
4387
 
4388
+ // src/runtime/git-worktree.ts
4389
+ import { open, stat } from "fs/promises";
4390
+ import * as path2 from "path";
4391
+ var MAX_WORKTREE_WALK_DEPTH = 128;
4392
+ var MAX_GIT_FILE_BYTES = 4096;
4393
+ var MAX_CACHE_ENTRIES = 1024;
4394
+ var DEFAULT_WORKTREE_CACHE_TTL_MILLIS = 5e3;
4395
+ var MAX_BRANCH_NAME_LENGTH = 255;
4396
+ var ABSENT = Object.freeze({ kind: "absent" });
4397
+ var INVALID = Object.freeze({ kind: "invalid" });
4398
+ var readBounded = async (filePath) => {
4399
+ let handle;
4400
+ try {
4401
+ handle = await open(filePath, "r");
4402
+ const buffer = Buffer.alloc(MAX_GIT_FILE_BYTES);
4403
+ const { bytesRead } = await handle.read(buffer, 0, MAX_GIT_FILE_BYTES, 0);
4404
+ return buffer.subarray(0, bytesRead).toString("utf8");
4405
+ } catch {
4406
+ return void 0;
4407
+ } finally {
4408
+ await handle?.close().catch(() => void 0);
4409
+ }
4410
+ };
4411
+ var parseHeadBranch = (head) => {
4412
+ const line = head.split(/\r?\n/, 1)[0]?.trim() ?? "";
4413
+ const match = /^ref:\s*refs\/heads\/(.+)$/.exec(line);
4414
+ const branch = match?.[1];
4415
+ if (branch === void 0 || branch.length === 0 || branch.length > MAX_BRANCH_NAME_LENGTH || // git forbids these in ref names; their presence means this is not one.
4416
+ [...branch].some((char) => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127) || /[ ~^:?*[\\]/.test(branch)) {
4417
+ return void 0;
4418
+ }
4419
+ return branch;
4420
+ };
4421
+ var parseGitDirFile = (content, worktreeRoot) => {
4422
+ const line = content.split(/\r?\n/, 1)[0]?.trim() ?? "";
4423
+ const target = line.startsWith("gitdir:") ? line.slice("gitdir:".length).trim() : void 0;
4424
+ if (target === void 0 || target.length === 0 || target.includes("\0")) {
4425
+ return void 0;
4426
+ }
4427
+ return path2.resolve(worktreeRoot, target);
4428
+ };
4429
+ var probeDirectory = async (directory) => {
4430
+ const dotGit = path2.join(directory, ".git");
4431
+ let info;
4432
+ try {
4433
+ info = await stat(dotGit);
4434
+ } catch {
4435
+ return ABSENT;
4436
+ }
4437
+ let gitDir;
4438
+ if (info.isDirectory()) {
4439
+ gitDir = dotGit;
4440
+ } else if (info.isFile()) {
4441
+ const content = await readBounded(dotGit);
4442
+ gitDir = content === void 0 ? void 0 : parseGitDirFile(content, directory);
4443
+ }
4444
+ if (gitDir === void 0) {
4445
+ return INVALID;
4446
+ }
4447
+ const head = await readBounded(path2.join(gitDir, "HEAD"));
4448
+ if (head === void 0) {
4449
+ return INVALID;
4450
+ }
4451
+ const branch = parseHeadBranch(head);
4452
+ return {
4453
+ kind: "worktree",
4454
+ located: { root: directory, ...branch === void 0 ? {} : { branch } }
4455
+ };
4456
+ };
4457
+ var createFilesystemWorktreeLocator = (options = {}) => {
4458
+ const now = options.monotonicMillis ?? (() => performance.now());
4459
+ const ttl = options.cacheTtlMillis ?? DEFAULT_WORKTREE_CACHE_TTL_MILLIS;
4460
+ const cache = /* @__PURE__ */ new Map();
4461
+ const cachedProbe = (directory) => {
4462
+ const hit = cache.get(directory);
4463
+ const at = now();
4464
+ if (hit !== void 0 && at - hit.at <= ttl) {
4465
+ return hit.probe;
4466
+ }
4467
+ if (cache.size >= MAX_CACHE_ENTRIES) {
4468
+ cache.clear();
4469
+ }
4470
+ const probe = probeDirectory(directory).catch(() => INVALID);
4471
+ cache.set(directory, { at, probe });
4472
+ return probe;
4473
+ };
4474
+ const locate = async (absolutePath) => {
4475
+ try {
4476
+ if (!path2.isAbsolute(absolutePath) || absolutePath.includes("\0")) {
4477
+ return void 0;
4478
+ }
4479
+ let directory = path2.resolve(absolutePath);
4480
+ for (let depth = 0; depth < MAX_WORKTREE_WALK_DEPTH; depth += 1) {
4481
+ const probe = await cachedProbe(directory);
4482
+ if (probe.kind === "worktree") {
4483
+ return probe.located;
4484
+ }
4485
+ if (probe.kind === "invalid") {
4486
+ return void 0;
4487
+ }
4488
+ const parent = path2.dirname(directory);
4489
+ if (parent === directory) {
4490
+ return void 0;
4491
+ }
4492
+ directory = parent;
4493
+ }
4494
+ return void 0;
4495
+ } catch {
4496
+ return void 0;
4497
+ }
4498
+ };
4499
+ return { locate };
4500
+ };
4501
+
4124
4502
  // src/state/filesystem-store.ts
4125
4503
  import { randomBytes as randomBytes2 } from "crypto";
4126
- import { mkdir, open, readFile, readdir, rename, unlink, writeFile } from "fs/promises";
4127
- import * as path from "path";
4504
+ import { mkdir, open as open2, readFile, readdir, rename, unlink, writeFile } from "fs/promises";
4505
+ import * as path3 from "path";
4128
4506
 
4129
4507
  // src/state/keys.ts
4130
4508
  import { createHash as createHash4 } from "crypto";
@@ -4144,8 +4522,8 @@ var keyDigest = (key) => createHash4("sha256").update(key, "utf8").digest("hex")
4144
4522
 
4145
4523
  // src/state/filesystem-store.ts
4146
4524
  var isErrnoException = (thrown, code) => thrown instanceof Error && thrown.code === code;
4147
- var sleep = (millis) => new Promise((resolve) => {
4148
- const timer = setTimeout(resolve, millis);
4525
+ var sleep = (millis) => new Promise((resolve3) => {
4526
+ const timer = setTimeout(resolve3, millis);
4149
4527
  timer.unref?.();
4150
4528
  });
4151
4529
  var wrapFsError = (thrown, operation) => {
@@ -4156,10 +4534,10 @@ var wrapFsError = (thrown, operation) => {
4156
4534
  };
4157
4535
  var createFilesystemStateStore = (options) => {
4158
4536
  const [providerSegment, installationSegment] = namespaceSegments(options);
4159
- const baseDir = path.join(options.rootDir, providerSegment, installationSegment);
4160
- const recordsDir = path.join(baseDir, "records");
4161
- const quarantineDir = path.join(baseDir, "quarantine");
4162
- const locksDir = path.join(baseDir, "locks");
4537
+ const baseDir = path3.join(options.rootDir, providerSegment, installationSegment);
4538
+ const recordsDir = path3.join(baseDir, "records");
4539
+ const quarantineDir = path3.join(baseDir, "quarantine");
4540
+ const locksDir = path3.join(baseDir, "locks");
4163
4541
  const lockTimeoutMillis = options.lockTimeoutMillis ?? 5e3;
4164
4542
  const lockStaleMillis = options.lockStaleMillis ?? 3e4;
4165
4543
  const lockPollIntervalMillis = options.lockPollIntervalMillis ?? 25;
@@ -4183,11 +4561,11 @@ var createFilesystemStateStore = (options) => {
4183
4561
  throw wrapFsError(thrown, "ensure-dirs");
4184
4562
  }
4185
4563
  };
4186
- const recordPath = (key) => path.join(recordsDir, `${keyDigest(key)}.json`);
4187
- const tempPath = (key) => path.join(recordsDir, `.tmp-${keyDigest(key)}-${randomBytes2(6).toString("hex")}.json`);
4188
- const lockPath = (sessionId) => path.join(locksDir, `${sanitizeSegment(sessionId)}.lock`);
4564
+ const recordPath = (key) => path3.join(recordsDir, `${keyDigest(key)}.json`);
4565
+ const tempPath = (key) => path3.join(recordsDir, `.tmp-${keyDigest(key)}-${randomBytes2(6).toString("hex")}.json`);
4566
+ const lockPath = (sessionId) => path3.join(locksDir, `${sanitizeSegment(sessionId)}.lock`);
4189
4567
  const quarantine = async (filePath, key, reason) => {
4190
- const dest = path.join(quarantineDir, `${options.clock.now()}-${keyDigest(key)}-${reason}.json`);
4568
+ const dest = path3.join(quarantineDir, `${options.clock.now()}-${keyDigest(key)}-${reason}.json`);
4191
4569
  try {
4192
4570
  await rename(filePath, dest);
4193
4571
  } catch {
@@ -4251,7 +4629,7 @@ var createFilesystemStateStore = (options) => {
4251
4629
  const startedAt = options.clock.monotonicMillis();
4252
4630
  for (; ; ) {
4253
4631
  try {
4254
- const handle = await open(filePath, "wx");
4632
+ const handle = await open2(filePath, "wx");
4255
4633
  try {
4256
4634
  await handle.writeFile(JSON.stringify({ pid: process.pid, acquiredAt: options.clock.now() }));
4257
4635
  } finally {
@@ -4319,7 +4697,7 @@ var createFilesystemStateStore = (options) => {
4319
4697
  }
4320
4698
  let raw;
4321
4699
  try {
4322
- raw = await readFile(path.join(recordsDir, entry), "utf8");
4700
+ raw = await readFile(path3.join(recordsDir, entry), "utf8");
4323
4701
  } catch {
4324
4702
  continue;
4325
4703
  }
@@ -4372,7 +4750,7 @@ var createFilesystemStateStore = (options) => {
4372
4750
  continue;
4373
4751
  }
4374
4752
  scanned += 1;
4375
- const filePath = path.join(recordsDir, entry);
4753
+ const filePath = path3.join(recordsDir, entry);
4376
4754
  try {
4377
4755
  const raw = await readFile(filePath, "utf8");
4378
4756
  const envelope = JSON.parse(raw);
@@ -4392,7 +4770,7 @@ var createFilesystemStateStore = (options) => {
4392
4770
  lockEntries = [];
4393
4771
  }
4394
4772
  for (const entry of lockEntries) {
4395
- const filePath = path.join(locksDir, entry);
4773
+ const filePath = path3.join(locksDir, entry);
4396
4774
  try {
4397
4775
  const raw = await readFile(filePath, "utf8");
4398
4776
  const parsed = JSON.parse(raw);
@@ -4411,13 +4789,13 @@ var createFilesystemStateStore = (options) => {
4411
4789
  // src/telemetry/spool-queue.ts
4412
4790
  import { randomBytes as randomBytes3 } from "crypto";
4413
4791
  import { mkdir as mkdir2, readFile as readFile2, readdir as readdir2, rename as rename2, unlink as unlink2, writeFile as writeFile2 } from "fs/promises";
4414
- import * as path2 from "path";
4792
+ import * as path4 from "path";
4415
4793
  var DEFAULT_DRAIN_MAX_BATCHES = 20;
4416
4794
  var isErrnoException2 = (thrown, code) => thrown instanceof Error && thrown.code === code;
4417
4795
  var createSpoolQueue = (options) => {
4418
4796
  const [providerSegment, installationSegment] = namespaceSegments(options);
4419
- const queueDir = path2.join(options.rootDir, providerSegment, installationSegment, options.queueName);
4420
- const corruptDir = path2.join(
4797
+ const queueDir = path4.join(options.rootDir, providerSegment, installationSegment, options.queueName);
4798
+ const corruptDir = path4.join(
4421
4799
  options.rootDir,
4422
4800
  providerSegment,
4423
4801
  installationSegment,
@@ -4463,8 +4841,8 @@ var createSpoolQueue = (options) => {
4463
4841
  return { spooled: false, reason: "capacity-exceeded" };
4464
4842
  }
4465
4843
  const fileName = `${String(options.clock.now()).padStart(16, "0")}-${randomBytes3(6).toString("hex")}.json`;
4466
- const target = path2.join(queueDir, fileName);
4467
- const tmp = path2.join(queueDir, `.tmp-${randomBytes3(6).toString("hex")}.json`);
4844
+ const target = path4.join(queueDir, fileName);
4845
+ const tmp = path4.join(queueDir, `.tmp-${randomBytes3(6).toString("hex")}.json`);
4468
4846
  await writeFile2(tmp, JSON.stringify(batch), "utf8");
4469
4847
  await rename2(tmp, target);
4470
4848
  return { spooled: true };
@@ -4482,7 +4860,7 @@ var createSpoolQueue = (options) => {
4482
4860
  if (fileName === void 0) {
4483
4861
  break;
4484
4862
  }
4485
- const filePath = path2.join(queueDir, fileName);
4863
+ const filePath = path4.join(queueDir, fileName);
4486
4864
  const quarantine = async (rejection) => {
4487
4865
  quarantined += 1;
4488
4866
  options.logger?.error("durable spool quarantined an unusable batch", {
@@ -4491,7 +4869,7 @@ var createSpoolQueue = (options) => {
4491
4869
  "spool.queue": options.queueName
4492
4870
  });
4493
4871
  try {
4494
- await rename2(filePath, path2.join(corruptDir, fileName));
4872
+ await rename2(filePath, path4.join(corruptDir, fileName));
4495
4873
  } catch {
4496
4874
  await unlink2(filePath).catch(() => void 0);
4497
4875
  }
@@ -4804,7 +5182,7 @@ var ATTR_OTELHOOK_AGENT_VERSION2 = "otelhook.agent.version";
4804
5182
  var ATTR_OTELHOOK_SESSION_KIND = "otelhook.session.kind";
4805
5183
  var ATTR_OTELHOOK_PROMPT_SOURCE = "otelhook.prompt.source";
4806
5184
  var ATTR_OTELHOOK_PROMPT_TURN_INDEX = "otelhook.prompt.turn_index";
4807
- var ATTR_OTELHOOK_GENERATION_ID = "otelhook.generation.id";
5185
+ var ATTR_OTELHOOK_GENERATION_ID2 = "otelhook.generation.id";
4808
5186
  var ATTR_OTELHOOK_STOP_REASON = "otelhook.generation.stop_reason";
4809
5187
  var ATTR_OTELHOOK_COMPACTION_TRIGGER2 = "otelhook.compaction.trigger";
4810
5188
  var ATTR_OTELHOOK_CONTEXT_TOKENS_BEFORE = "otelhook.compaction.context_tokens_before";
@@ -4923,14 +5301,14 @@ var eventAttributes = (event2) => {
4923
5301
  case "generation.start":
4924
5302
  return {
4925
5303
  [ATTR_GEN_AI_OPERATION_NAME2]: "chat",
4926
- [ATTR_OTELHOOK_GENERATION_ID]: event2.generationId,
5304
+ [ATTR_OTELHOOK_GENERATION_ID2]: event2.generationId,
4927
5305
  [ATTR_GEN_AI_REQUEST_MODEL2]: event2.model.modelId,
4928
5306
  ...event2.model.vendor === void 0 ? {} : { [ATTR_GEN_AI_SYSTEM2]: event2.model.vendor }
4929
5307
  };
4930
5308
  case "generation.end":
4931
5309
  return {
4932
5310
  [ATTR_GEN_AI_OPERATION_NAME2]: "chat",
4933
- [ATTR_OTELHOOK_GENERATION_ID]: event2.generationId,
5311
+ [ATTR_OTELHOOK_GENERATION_ID2]: event2.generationId,
4934
5312
  [ATTR_GEN_AI_RESPONSE_MODEL2]: event2.model.modelId,
4935
5313
  ...event2.model.vendor === void 0 ? {} : { [ATTR_GEN_AI_SYSTEM2]: event2.model.vendor },
4936
5314
  [ATTR_OTELHOOK_OUTCOME2]: event2.outcome,
@@ -4942,14 +5320,16 @@ var eventAttributes = (event2) => {
4942
5320
  [ATTR_GEN_AI_TOOL_NAME2]: event2.toolName,
4943
5321
  [ATTR_GEN_AI_TOOL_CALL_ID2]: event2.toolCallId,
4944
5322
  [ATTR_OTELHOOK_TOOL_KIND2]: event2.toolKind,
4945
- ...event2.generationId === void 0 ? {} : { [ATTR_OTELHOOK_GENERATION_ID]: event2.generationId }
5323
+ ...event2.generationId === void 0 ? {} : { [ATTR_OTELHOOK_GENERATION_ID2]: event2.generationId },
5324
+ ...targetAttributes(event2)
4946
5325
  };
4947
5326
  case "tool.end":
4948
5327
  return {
4949
5328
  [ATTR_GEN_AI_TOOL_NAME2]: event2.toolName,
4950
5329
  [ATTR_GEN_AI_TOOL_CALL_ID2]: event2.toolCallId,
4951
5330
  [ATTR_OTELHOOK_OUTCOME2]: event2.outcome,
4952
- ...event2.permissionDecision === void 0 ? {} : { [ATTR_OTELHOOK_TOOL_PERMISSION]: event2.permissionDecision }
5331
+ ...event2.permissionDecision === void 0 ? {} : { [ATTR_OTELHOOK_TOOL_PERMISSION]: event2.permissionDecision },
5332
+ ...targetAttributes(event2)
4953
5333
  };
4954
5334
  case "subagent.start":
4955
5335
  return {
@@ -4983,7 +5363,8 @@ var usageAttributes2 = (usage) => usage === void 0 ? {} : {
4983
5363
  [ATTR_GEN_AI_USAGE_INPUT_TOKENS2]: usage.inputTokens,
4984
5364
  [ATTR_GEN_AI_USAGE_OUTPUT_TOKENS2]: usage.outputTokens,
4985
5365
  [ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS2]: usage.cachedInputTokens,
4986
- [ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS2]: usage.cacheCreationInputTokens
5366
+ [ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS2]: usage.cacheCreationInputTokens,
5367
+ ...usageTemporalityAttributes(usage)
4987
5368
  };
4988
5369
  var contentFactsOf = (event2) => {
4989
5370
  switch (event2.type) {
@@ -5274,8 +5655,8 @@ var createOtlpLogSink = (options) => {
5274
5655
  timeoutMillis: options.exporter.timeoutMillis
5275
5656
  });
5276
5657
  let shutdownCompleted = false;
5277
- const exportRecords = (records) => new Promise((resolve) => {
5278
- exporter.export([...records], (result) => resolve(result));
5658
+ const exportRecords = (records) => new Promise((resolve3) => {
5659
+ exporter.export([...records], (result) => resolve3(result));
5279
5660
  });
5280
5661
  const toSpoolBatch = (records) => ({
5281
5662
  providerId: options.providerId,
@@ -5480,8 +5861,8 @@ var createOtlpTraceSink = (options) => {
5480
5861
  timeoutMillis: options.exporter.timeoutMillis
5481
5862
  });
5482
5863
  let shutdownCompleted = false;
5483
- const exportSpans = (spans) => new Promise((resolve) => {
5484
- exporter.export([...spans], (result) => resolve(result));
5864
+ const exportSpans = (spans) => new Promise((resolve3) => {
5865
+ exporter.export([...spans], (result) => resolve3(result));
5485
5866
  });
5486
5867
  const toSpoolBatch = (spans) => ({
5487
5868
  providerId: options.providerId,
@@ -5641,8 +6022,8 @@ var DEFAULT_FLUSH_TIMEOUT_MILLIS = 2e3;
5641
6022
  var DEFAULT_STATE_LOCK_TIMEOUT_MILLIS = 1e3;
5642
6023
  var DEFAULT_LIFECYCLE_MAX_AGE_MILLIS = 24 * 60 * 60 * 1e3;
5643
6024
  var DEFAULT_STALE_CLAIM_MILLIS2 = 6e4;
5644
- var delay = (millis) => new Promise((resolve) => {
5645
- const timer = setTimeout(() => resolve("timeout"), millis);
6025
+ var delay = (millis) => new Promise((resolve3) => {
6026
+ const timer = setTimeout(() => resolve3("timeout"), millis);
5646
6027
  timer.unref?.();
5647
6028
  });
5648
6029
  var containsSessionEnd = (events) => events.some((event2) => event2.type === "session.end");
@@ -5754,7 +6135,10 @@ var createHookRuntime = (options) => {
5754
6135
  ids,
5755
6136
  privacy,
5756
6137
  logger,
5757
- installationId: options.installationId
6138
+ installationId: options.installationId,
6139
+ ...options.worktreeLocator === null ? {} : {
6140
+ worktreeLocator: options.worktreeLocator ?? createFilesystemWorktreeLocator({ monotonicMillis: () => clock.monotonicMillis() })
6141
+ }
5758
6142
  };
5759
6143
  const hook = createOtelHook({ ...hookDeps, sink });
5760
6144
  const deduplicator = createCallbackDeduplicator({ stateStore, clock });