@osfactory/otel-hook 0.2.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 (52) hide show
  1. package/dist/{adapter-DIgRACtL.d.ts → adapter-BgqtlADe.d.ts} +12 -5
  2. package/dist/cli.js +1439 -626
  3. package/dist/cli.js.map +1 -1
  4. package/dist/config.d.ts +2 -2
  5. package/dist/config.js +5 -1
  6. package/dist/config.js.map +1 -1
  7. package/dist/{content-CoB7aNP1.d.ts → content-M9xIKG7h.d.ts} +8 -1
  8. package/dist/{events-VxBnDFaO.d.ts → events-C3h3GvHj.d.ts} +58 -0
  9. package/dist/{filesystem-store-J8jjDMTh.d.ts → filesystem-store-BAq3VGVv.d.ts} +1 -1
  10. package/dist/{hook-CGpo-vks.d.ts → hook-CQiNa88Q.d.ts} +13 -5
  11. package/dist/index.d.ts +16 -15
  12. package/dist/index.js +1569 -741
  13. package/dist/index.js.map +1 -1
  14. package/dist/install.d.ts +8 -7
  15. package/dist/install.js +132 -68
  16. package/dist/install.js.map +1 -1
  17. package/dist/integration.d.ts +18 -11
  18. package/dist/integration.js +618 -158
  19. package/dist/integration.js.map +1 -1
  20. package/dist/lifecycle.d.ts +3 -3
  21. package/dist/lifecycle.js +27 -4
  22. package/dist/lifecycle.js.map +1 -1
  23. package/dist/{memory-DXVBc8V9.d.ts → memory-kflYgZbg.d.ts} +2 -2
  24. package/dist/model.d.ts +3 -2
  25. package/dist/model.js +81 -41
  26. package/dist/model.js.map +1 -1
  27. package/dist/{otlp-log-sink-CeIFDDpn.d.ts → otlp-log-sink-BZIgYPKN.d.ts} +4 -4
  28. package/dist/{payload-CHr53E_v.d.ts → payload-DpyU8F-z.d.ts} +1 -1
  29. package/dist/{policy-D1CrlYn3.d.ts → policy-CimmCfRp.d.ts} +1 -1
  30. package/dist/{ports-Q8x0ODhs.d.ts → ports-B_iwJQPQ.d.ts} +20 -2
  31. package/dist/privacy.d.ts +4 -4
  32. package/dist/privacy.js +11 -0
  33. package/dist/privacy.js.map +1 -1
  34. package/dist/providers.d.ts +30 -12
  35. package/dist/providers.js +983 -552
  36. package/dist/providers.js.map +1 -1
  37. package/dist/{registry-BzYmC9OC.d.ts → registry-BSBS8t7S.d.ts} +1 -1
  38. package/dist/runtime.d.ts +88 -12
  39. package/dist/runtime.js +392 -68
  40. package/dist/runtime.js.map +1 -1
  41. package/dist/{semconv-Baoz-0OI.d.ts → semconv-BeUPQ7_q.d.ts} +2 -1
  42. package/dist/{service-j4jEO6cZ.d.ts → service-CbI9CObT.d.ts} +8 -2
  43. package/dist/state.d.ts +4 -4
  44. package/dist/state.js.map +1 -1
  45. package/dist/target-8RfaVxp8.d.ts +83 -0
  46. package/dist/telemetry.d.ts +7 -7
  47. package/dist/telemetry.js +186 -46
  48. package/dist/telemetry.js.map +1 -1
  49. package/dist/testing.d.ts +17 -10
  50. package/dist/testing.js +1149 -593
  51. package/dist/testing.js.map +1 -1
  52. package/package.json +4 -1
package/dist/index.js CHANGED
@@ -132,6 +132,7 @@ var contentFactSchema = z4.strictObject({
132
132
  });
133
133
  var contentFactsSchema = z4.array(contentFactSchema).max(64);
134
134
  var isContentFactConsistent = (fact) => fact.disclosure === "omitted" ? fact.text === void 0 : fact.text !== void 0;
135
+ var isUnavailableContentFact = (fact) => fact.disclosure === "omitted" && fact.text === void 0 && fact.characterLength === 0 && fact.byteLength === 0;
135
136
 
136
137
  // src/model/usage.ts
137
138
  import { z as z5 } from "zod";
@@ -563,12 +564,33 @@ var resolveInvocationIdentity = (input) => {
563
564
  return { status: "resolved", identity: parsed.data };
564
565
  };
565
566
 
567
+ // src/model/target.ts
568
+ import { z as z7 } from "zod";
569
+ var targetSourceSchema = z7.enum(["tool-path", "shell-cwd", "session-cwd"]);
570
+ var MAX_TARGET_HINT_PATHS = 8;
571
+ var MAX_TARGET_PATH_LENGTH = 4096;
572
+ var localPathSchema = z7.string().min(1).max(MAX_TARGET_PATH_LENGTH).refine((value) => !value.includes("\0"), "path must not contain NUL");
573
+ var targetHintSchema = z7.strictObject({
574
+ source: targetSourceSchema,
575
+ paths: z7.array(localPathSchema).min(1).max(MAX_TARGET_HINT_PATHS).readonly(),
576
+ /** Absolute directory that relative `paths` resolve against. */
577
+ baseDirectory: localPathSchema.optional()
578
+ }).readonly();
579
+ var workspaceTargetSchema = z7.strictObject({
580
+ workspaceId: workspaceIdSchema,
581
+ /** Branch checked out in that worktree; absent on a detached HEAD. */
582
+ vcsBranchName: nonEmptyStringSchema.optional(),
583
+ source: targetSourceSchema
584
+ }).readonly();
585
+ var SUBAGENT_ID_PATTERN = /^[A-Za-z0-9_.:@+=-]{1,256}$/;
586
+ var subagentIdSchema = z7.string().regex(SUBAGENT_ID_PATTERN);
587
+
566
588
  // src/model/events.ts
567
- import { z as z8 } from "zod";
589
+ import { z as z9 } from "zod";
568
590
 
569
591
  // src/errors/taxonomy.ts
570
- import { z as z7 } from "zod";
571
- var otelHookErrorCodeSchema = z7.enum([
592
+ import { z as z8 } from "zod";
593
+ var otelHookErrorCodeSchema = z8.enum([
572
594
  /** Input was not usable at all (empty stdin, unparsable JSON). */
573
595
  "invalid-input",
574
596
  /** Input parsed but failed canonical schema validation. */
@@ -604,8 +626,8 @@ var otelHookErrorCodeSchema = z7.enum([
604
626
  /** Anything unanticipated. Always reported, never fatal to the host. */
605
627
  "internal-error"
606
628
  ]);
607
- var errorSeveritySchema = z7.enum(["warning", "error"]);
608
- var errorPhaseSchema = z7.enum([
629
+ var errorSeveritySchema = z8.enum(["warning", "error"]);
630
+ var errorPhaseSchema = z8.enum([
609
631
  "configuration",
610
632
  "detection",
611
633
  "identity",
@@ -616,7 +638,7 @@ var errorPhaseSchema = z7.enum([
616
638
  "export",
617
639
  "shutdown"
618
640
  ]);
619
- var failurePostureSchema = z7.enum(["fail-open", "fail-closed-attribution"]);
641
+ var failurePostureSchema = z8.enum(["fail-open", "fail-closed-attribution"]);
620
642
  var ERROR_TAXONOMY = Object.freeze({
621
643
  "invalid-input": {
622
644
  code: "invalid-input",
@@ -741,7 +763,7 @@ var ERROR_TAXONOMY = Object.freeze({
741
763
  }
742
764
  });
743
765
  var describeErrorCode = (code) => ERROR_TAXONOMY[code];
744
- var attributionOutcomeSchema = z7.enum([
766
+ var attributionOutcomeSchema = z8.enum([
745
767
  /** Identity resolved; events carry provider and session identity. */
746
768
  "attributed",
747
769
  /** Identity could not be established safely; nothing was attributed. */
@@ -751,7 +773,7 @@ var attributionOutcomeSchema = z7.enum([
751
773
  /** Input was recognized but intentionally carried no telemetry. */
752
774
  "not-applicable"
753
775
  ]);
754
- var attributionReasonSchema = z7.enum([
776
+ var attributionReasonSchema = z8.enum([
755
777
  "provider-unknown",
756
778
  "provider-detection-ambiguous",
757
779
  "identity-conflict",
@@ -763,19 +785,19 @@ var attributionReasonSchema = z7.enum([
763
785
  ]);
764
786
 
765
787
  // src/model/events.ts
766
- var modelDescriptorSchema = z8.strictObject({
788
+ var modelDescriptorSchema = z9.strictObject({
767
789
  modelId: nonEmptyStringSchema,
768
790
  /** Vendor of the model, e.g. `anthropic`. Distinct from the agent provider. */
769
791
  vendor: nonEmptyStringSchema.optional(),
770
792
  family: nonEmptyStringSchema.optional()
771
793
  });
772
- var costFactsSchema = z8.strictObject({
794
+ var costFactsSchema = z9.strictObject({
773
795
  /** ISO 4217 code. */
774
- currency: z8.string().length(3),
775
- amount: z8.number().min(0).finite(),
776
- source: z8.enum(["provider-reported", "computed"])
796
+ currency: z9.string().length(3),
797
+ amount: z9.number().min(0).finite(),
798
+ source: z9.enum(["provider-reported", "computed"])
777
799
  });
778
- var canonicalEventTypeSchema = z8.enum([
800
+ var canonicalEventTypeSchema = z9.enum([
779
801
  "session.start",
780
802
  "session.end",
781
803
  "prompt.submitted",
@@ -789,7 +811,7 @@ var canonicalEventTypeSchema = z8.enum([
789
811
  "error.raised"
790
812
  ]);
791
813
  var CANONICAL_EVENT_TYPES = canonicalEventTypeSchema.options;
792
- var outcomeSchema = z8.enum(["ok", "error", "cancelled", "timeout", "denied", "unknown"]);
814
+ var outcomeSchema = z9.enum(["ok", "error", "cancelled", "timeout", "denied", "unknown"]);
793
815
  var baseEventFields = {
794
816
  schemaVersion: canonicalSchemaVersionSchema,
795
817
  eventId: eventIdSchema,
@@ -800,39 +822,45 @@ var baseEventFields = {
800
822
  occurredAt: epochMillisSchema,
801
823
  provenance: sourceProvenanceSchema,
802
824
  workspace: workspaceIdentitySchema,
825
+ /**
826
+ * The provider's own id for the subagent this event was emitted inside (e.g.
827
+ * Claude Code's `agent_id`). Absent for the top-level agent. Set by the event
828
+ * factory, never by hand.
829
+ */
830
+ subagentId: subagentIdSchema.optional(),
803
831
  extensions: extensionsSchema.default(emptyExtensions)
804
832
  };
805
- var event = (shape) => z8.strictObject({ ...baseEventFields, ...shape });
833
+ var event = (shape) => z9.strictObject({ ...baseEventFields, ...shape });
806
834
  var sessionStartEventSchema = event({
807
- type: z8.literal("session.start"),
808
- sessionKind: z8.enum(["interactive", "non-interactive", "unknown"]),
835
+ type: z9.literal("session.start"),
836
+ sessionKind: z9.enum(["interactive", "non-interactive", "unknown"]),
809
837
  agentName: nonEmptyStringSchema.optional(),
810
838
  agentVersion: nonEmptyStringSchema.optional(),
811
839
  model: modelDescriptorSchema.optional()
812
840
  });
813
841
  var sessionEndEventSchema = event({
814
- type: z8.literal("session.end"),
815
- reason: z8.enum(["completed", "aborted", "error", "timeout", "unknown"]),
842
+ type: z9.literal("session.end"),
843
+ reason: z9.enum(["completed", "aborted", "error", "timeout", "unknown"]),
816
844
  durationMillis: durationMillisSchema.optional(),
817
845
  /** Session totals, typically cumulative. */
818
846
  usage: canonicalUsageSchema.optional(),
819
847
  cost: costFactsSchema.optional()
820
848
  });
821
849
  var promptSubmittedEventSchema = event({
822
- type: z8.literal("prompt.submitted"),
823
- promptSource: z8.enum(["user", "automation", "resumed", "unknown"]),
850
+ type: z9.literal("prompt.submitted"),
851
+ promptSource: z9.enum(["user", "automation", "resumed", "unknown"]),
824
852
  content: contentFactSchema.optional(),
825
- turnIndex: z8.number().int().min(0).optional()
853
+ turnIndex: z9.number().int().min(0).optional()
826
854
  });
827
855
  var generationStartEventSchema = event({
828
- type: z8.literal("generation.start"),
856
+ type: z9.literal("generation.start"),
829
857
  generationId: nonEmptyStringSchema,
830
858
  model: modelDescriptorSchema,
831
859
  requestedMaxOutputTokens: tokenCountSchema.optional(),
832
860
  inputContent: contentFactsSchema.optional()
833
861
  });
834
862
  var generationEndEventSchema = event({
835
- type: z8.literal("generation.end"),
863
+ type: z9.literal("generation.end"),
836
864
  generationId: nonEmptyStringSchema,
837
865
  model: modelDescriptorSchema,
838
866
  outcome: outcomeSchema,
@@ -842,7 +870,7 @@ var generationEndEventSchema = event({
842
870
  cost: costFactsSchema.optional(),
843
871
  outputContent: contentFactsSchema.optional()
844
872
  });
845
- var toolKindSchema = z8.enum([
873
+ var toolKindSchema = z9.enum([
846
874
  "read",
847
875
  "write",
848
876
  "execute",
@@ -853,59 +881,63 @@ var toolKindSchema = z8.enum([
853
881
  "unknown"
854
882
  ]);
855
883
  var toolStartEventSchema = event({
856
- type: z8.literal("tool.start"),
884
+ type: z9.literal("tool.start"),
857
885
  toolCallId: nonEmptyStringSchema,
858
886
  toolName: nonEmptyStringSchema,
859
887
  toolKind: toolKindSchema,
860
888
  generationId: nonEmptyStringSchema.optional(),
861
- input: contentFactSchema.optional()
889
+ input: contentFactSchema.optional(),
890
+ /** The git worktree this call targeted, resolved by the core (ADR 0008). */
891
+ target: workspaceTargetSchema.optional()
862
892
  });
863
893
  var toolEndEventSchema = event({
864
- type: z8.literal("tool.end"),
894
+ type: z9.literal("tool.end"),
865
895
  toolCallId: nonEmptyStringSchema,
866
896
  toolName: nonEmptyStringSchema,
867
897
  outcome: outcomeSchema,
868
898
  durationMillis: durationMillisSchema.optional(),
869
899
  /** Present when the host asked for or recorded a permission decision. */
870
- permissionDecision: z8.enum(["allowed", "denied", "deferred", "not-required"]).optional(),
871
- output: contentFactSchema.optional()
900
+ permissionDecision: z9.enum(["allowed", "denied", "deferred", "not-required"]).optional(),
901
+ output: contentFactSchema.optional(),
902
+ /** The git worktree this call targeted, resolved by the core (ADR 0008). */
903
+ target: workspaceTargetSchema.optional()
872
904
  });
873
905
  var subagentStartEventSchema = event({
874
- type: z8.literal("subagent.start"),
906
+ type: z9.literal("subagent.start"),
875
907
  subagentInvocationId: invocationIdSchema,
876
908
  subagentType: nonEmptyStringSchema.optional(),
877
909
  /** 0 for the top-level agent; 1 for its direct children. */
878
- delegationDepth: z8.number().int().min(0).max(64),
910
+ delegationDepth: z9.number().int().min(0).max(64),
879
911
  model: modelDescriptorSchema.optional()
880
912
  });
881
913
  var subagentEndEventSchema = event({
882
- type: z8.literal("subagent.end"),
914
+ type: z9.literal("subagent.end"),
883
915
  subagentInvocationId: invocationIdSchema,
884
916
  outcome: outcomeSchema,
885
917
  durationMillis: durationMillisSchema.optional(),
886
918
  usage: canonicalUsageSchema.optional()
887
919
  });
888
920
  var compactionPerformedEventSchema = event({
889
- type: z8.literal("compaction.performed"),
890
- trigger: z8.enum(["automatic", "manual", "unknown"]),
921
+ type: z9.literal("compaction.performed"),
922
+ trigger: z9.enum(["automatic", "manual", "unknown"]),
891
923
  /** Provider-reported context size before and after compaction, if known. */
892
924
  contextTokensBefore: tokenCountSchema.optional(),
893
925
  contextTokensAfter: tokenCountSchema.optional(),
894
- droppedMessageCount: z8.number().int().min(0).optional(),
926
+ droppedMessageCount: z9.number().int().min(0).optional(),
895
927
  usage: canonicalUsageSchema.optional()
896
928
  });
897
929
  var errorRaisedEventSchema = event({
898
- type: z8.literal("error.raised"),
930
+ type: z9.literal("error.raised"),
899
931
  errorCode: otelHookErrorCodeSchema,
900
932
  severity: errorSeveritySchema,
901
933
  phase: errorPhaseSchema,
902
- retryable: z8.boolean(),
934
+ retryable: z9.boolean(),
903
935
  /** Error text is content: it is described, never embedded verbatim by default. */
904
936
  message: contentFactSchema.optional(),
905
937
  /** Non-sensitive, provider-agnostic short label. */
906
938
  detail: nonEmptyStringSchema.optional()
907
939
  });
908
- var canonicalEventSchema = z8.discriminatedUnion("type", [
940
+ var canonicalEventSchema = z9.discriminatedUnion("type", [
909
941
  sessionStartEventSchema,
910
942
  sessionEndEventSchema,
911
943
  promptSubmittedEventSchema,
@@ -935,14 +967,14 @@ var eventUsage = (event3) => "usage" in event3 ? event3.usage : void 0;
935
967
  var compareEvents = (a, b) => a.sequence - b.sequence || a.occurredAt - b.occurredAt || a.eventId.localeCompare(b.eventId);
936
968
 
937
969
  // src/errors/index.ts
938
- import { z as z9 } from "zod";
939
- var otelHookErrorInfoSchema = z9.strictObject({
970
+ import { z as z10 } from "zod";
971
+ var otelHookErrorInfoSchema = z10.strictObject({
940
972
  code: otelHookErrorCodeSchema,
941
973
  severity: errorSeveritySchema,
942
974
  phase: errorPhaseSchema,
943
975
  posture: failurePostureSchema,
944
- retryable: z9.boolean(),
945
- message: z9.string().min(1).max(512),
976
+ retryable: z10.boolean(),
977
+ message: z10.string().min(1).max(512),
946
978
  details: attributesSchema.optional(),
947
979
  occurredAt: epochMillisSchema.optional()
948
980
  });
@@ -996,8 +1028,8 @@ var errorInfoFromThrown = (thrown, input) => {
996
1028
  };
997
1029
 
998
1030
  // src/privacy/policy.ts
999
- import { z as z10 } from "zod";
1000
- var contentModeSchema = z10.enum(["omit", "mask", "redact", "raw"]);
1031
+ import { z as z11 } from "zod";
1032
+ var contentModeSchema = z11.enum(["omit", "mask", "redact", "raw"]);
1001
1033
  var CONTENT_MODE_DISCLOSURE = Object.freeze({
1002
1034
  omit: "omitted",
1003
1035
  mask: "masked",
@@ -1023,35 +1055,35 @@ var DEFAULT_SECRET_VALUE_PATTERNS = Object.freeze([
1023
1055
  "eyJ[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,}",
1024
1056
  "(?:Bearer|Basic)\\s+[A-Za-z0-9._~+/=-]{12,}"
1025
1057
  ]);
1026
- var privacyLimitsSchema = z10.strictObject({
1058
+ var privacyLimitsSchema = z11.strictObject({
1027
1059
  /** Maximum characters of disclosed text per content fact or string value. */
1028
- maxStringLength: z10.number().int().min(0).max(65536),
1060
+ maxStringLength: z11.number().int().min(0).max(65536),
1029
1061
  /** Maximum nesting depth walked when sanitizing structured values. */
1030
- maxDepth: z10.number().int().min(1).max(32),
1062
+ maxDepth: z11.number().int().min(1).max(32),
1031
1063
  /** Maximum array entries retained when sanitizing structured values. */
1032
- maxArrayLength: z10.number().int().min(1).max(4096),
1064
+ maxArrayLength: z11.number().int().min(1).max(4096),
1033
1065
  /** Maximum canonical events emitted per invocation. */
1034
- maxEventsPerInvocation: z10.number().int().min(1).max(1e4),
1066
+ maxEventsPerInvocation: z11.number().int().min(1).max(1e4),
1035
1067
  /** Maximum object keys retained per level when sanitizing. */
1036
- maxObjectKeys: z10.number().int().min(1).max(1024)
1068
+ maxObjectKeys: z11.number().int().min(1).max(1024)
1037
1069
  });
1038
- var privacyPolicySchema = z10.strictObject({
1070
+ var privacyPolicySchema = z11.strictObject({
1039
1071
  contentMode: contentModeSchema,
1040
1072
  /**
1041
1073
  * `raw` mode is refused unless this is also true, so a single mistyped
1042
1074
  * environment variable cannot start exporting prompts.
1043
1075
  */
1044
- allowRawContent: z10.boolean(),
1076
+ allowRawContent: z11.boolean(),
1045
1077
  /**
1046
1078
  * Salt mixed into every hash. A per-deployment salt makes hashes
1047
1079
  * non-correlatable across deployments; an empty salt makes them globally
1048
1080
  * comparable. Both are legitimate; the choice is explicit.
1049
1081
  */
1050
- hashSalt: z10.string().max(256),
1051
- maskCharacter: z10.string().length(1),
1052
- redactionPlaceholder: z10.string().min(1).max(64),
1053
- secretKeyPatterns: z10.array(z10.string().min(1)).max(128).readonly(),
1054
- secretValuePatterns: z10.array(z10.string().min(1)).max(128).readonly(),
1082
+ hashSalt: z11.string().max(256),
1083
+ maskCharacter: z11.string().length(1),
1084
+ redactionPlaceholder: z11.string().min(1).max(64),
1085
+ secretKeyPatterns: z11.array(z11.string().min(1)).max(128).readonly(),
1086
+ secretValuePatterns: z11.array(z11.string().min(1)).max(128).readonly(),
1055
1087
  limits: privacyLimitsSchema
1056
1088
  });
1057
1089
  var DEFAULT_PRIVACY_LIMITS = Object.freeze({
@@ -1301,11 +1333,11 @@ var createPrivacyService = (policyInput) => {
1301
1333
  };
1302
1334
  const flattenToAttributes = (value, prefix) => {
1303
1335
  const attributes = {};
1304
- const walk = (current, path7) => {
1336
+ const walk = (current, path9) => {
1305
1337
  if (typeof current === "string" || typeof current === "number" || typeof current === "boolean") {
1306
1338
  const primitive = toAttributePrimitive(current);
1307
1339
  if (primitive !== void 0) {
1308
- attributes[path7] = primitive;
1340
+ attributes[path9] = primitive;
1309
1341
  }
1310
1342
  return;
1311
1343
  }
@@ -1324,16 +1356,16 @@ var createPrivacyService = (policyInput) => {
1324
1356
  primitives.push(entryPrimitive);
1325
1357
  }
1326
1358
  if (uniform) {
1327
- attributes[path7] = primitives.slice(0, MAX_ATTRIBUTE_ARRAY_LENGTH);
1359
+ attributes[path9] = primitives.slice(0, MAX_ATTRIBUTE_ARRAY_LENGTH);
1328
1360
  return;
1329
1361
  }
1330
1362
  for (const [index, entry] of current.entries()) {
1331
- walk(entry, `${path7}.${index}`);
1363
+ walk(entry, `${path9}.${index}`);
1332
1364
  }
1333
1365
  return;
1334
1366
  }
1335
1367
  for (const [key, entry] of Object.entries(current)) {
1336
- walk(entry, path7 === "" ? key : `${path7}.${key}`);
1368
+ walk(entry, path9 === "" ? key : `${path9}.${key}`);
1337
1369
  }
1338
1370
  };
1339
1371
  walk(value, prefix);
@@ -1385,6 +1417,17 @@ var createPrivacyService = (policyInput) => {
1385
1417
  hash,
1386
1418
  deriveOpaqueId: (namespace, value) => hash(`${namespace}\0${value}`),
1387
1419
  describeContent: describeText,
1420
+ describeUnavailableContent: (input) => ({
1421
+ kind: input.kind,
1422
+ ...input.role === void 0 ? {} : { role: input.role },
1423
+ characterLength: 0,
1424
+ byteLength: 0,
1425
+ contentHash: hash(""),
1426
+ disclosure: "omitted",
1427
+ truncated: false,
1428
+ secretsRedacted: 0,
1429
+ ...input.label === void 0 ? {} : { label: input.label }
1430
+ }),
1388
1431
  describeStructured: (input) => {
1389
1432
  const serialized = stableStringify(input.value);
1390
1433
  const sanitized = sanitizeStructured(input.value);
@@ -1462,7 +1505,7 @@ var deriveWorkspaceIdentity = (privacy, input, labels = {}) => {
1462
1505
  };
1463
1506
 
1464
1507
  // src/config/resource-attributes.ts
1465
- import { z as z11 } from "zod";
1508
+ import { z as z12 } from "zod";
1466
1509
  var MAX_RESOURCE_ATTRIBUTES = 64;
1467
1510
  var MAX_RESOURCE_ATTRIBUTE_KEY_LENGTH = 255;
1468
1511
  var MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH = 2048;
@@ -1507,12 +1550,12 @@ var checkResourceAttributeKey = (key) => {
1507
1550
  }
1508
1551
  return void 0;
1509
1552
  };
1510
- var resourceAttributeValueSchema = z11.union([
1511
- z11.string().max(MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH),
1512
- z11.number().finite(),
1513
- z11.boolean()
1553
+ var resourceAttributeValueSchema = z12.union([
1554
+ z12.string().max(MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH),
1555
+ z12.number().finite(),
1556
+ z12.boolean()
1514
1557
  ]);
1515
- var resourceAttributesSchema = z11.record(z11.string(), resourceAttributeValueSchema).superRefine((value, ctx) => {
1558
+ var resourceAttributesSchema = z12.record(z12.string(), resourceAttributeValueSchema).superRefine((value, ctx) => {
1516
1559
  const keys = Object.keys(value);
1517
1560
  if (keys.length > MAX_RESOURCE_ATTRIBUTES) {
1518
1561
  ctx.addIssue({
@@ -1621,37 +1664,37 @@ var sanitizeResourceAttributes = (attributes) => {
1621
1664
  var describeResourceAttributeNames = (attributes) => Object.keys(attributes).sort();
1622
1665
 
1623
1666
  // src/config/schema.ts
1624
- import { z as z12 } from "zod";
1625
- var logsPolicySchema = z12.strictObject({
1626
- enabled: z12.boolean(),
1667
+ import { z as z13 } from "zod";
1668
+ var logsPolicySchema = z13.strictObject({
1669
+ enabled: z13.boolean(),
1627
1670
  /**
1628
1671
  * Full URL for the logs signal.
1629
1672
  *
1630
1673
  * Absent, it is derived from `endpoint`: a trailing `/v1/traces` becomes
1631
1674
  * `/v1/logs`, and an endpoint with no signal path has `/v1/logs` appended.
1632
1675
  */
1633
- endpoint: z12.string().url().max(2048).optional(),
1634
- includeContent: z12.boolean(),
1635
- maxBatchSize: z12.number().int().min(1).max(4096)
1676
+ endpoint: z13.string().url().max(2048).optional(),
1677
+ includeContent: z13.boolean(),
1678
+ maxBatchSize: z13.number().int().min(1).max(4096)
1636
1679
  });
1637
1680
  var DEFAULT_LOGS_POLICY = Object.freeze({
1638
1681
  enabled: false,
1639
1682
  includeContent: false,
1640
1683
  maxBatchSize: 128
1641
1684
  });
1642
- var exporterPolicySchema = z12.strictObject({
1643
- enabled: z12.boolean(),
1644
- protocol: z12.enum(["http/protobuf", "http/json", "none"]),
1645
- endpoint: z12.string().url().max(2048).optional(),
1685
+ var exporterPolicySchema = z13.strictObject({
1686
+ enabled: z13.boolean(),
1687
+ protocol: z13.enum(["http/protobuf", "http/json", "none"]),
1688
+ endpoint: z13.string().url().max(2048).optional(),
1646
1689
  /**
1647
1690
  * Header names only. Values are supplied separately at construction time and
1648
1691
  * are never part of a resolved-config snapshot, which is logged and exported.
1649
1692
  */
1650
- headerNames: z12.array(nonEmptyStringSchema).max(32).readonly(),
1651
- timeoutMillis: z12.number().int().min(1).max(6e5),
1652
- maxBatchSize: z12.number().int().min(1).max(4096),
1653
- maxQueueSize: z12.number().int().min(1).max(65536),
1654
- maxRetryAttempts: z12.number().int().min(0).max(10),
1693
+ headerNames: z13.array(nonEmptyStringSchema).max(32).readonly(),
1694
+ timeoutMillis: z13.number().int().min(1).max(6e5),
1695
+ maxBatchSize: z13.number().int().min(1).max(4096),
1696
+ maxQueueSize: z13.number().int().min(1).max(65536),
1697
+ maxRetryAttempts: z13.number().int().min(0).max(10),
1655
1698
  serviceName: nonEmptyStringSchema,
1656
1699
  serviceNamespace: nonEmptyStringSchema.optional(),
1657
1700
  /**
@@ -1670,26 +1713,26 @@ var exporterPolicySchema = z12.strictObject({
1670
1713
  */
1671
1714
  logs: logsPolicySchema
1672
1715
  });
1673
- var detectionPolicySchema = z12.strictObject({
1716
+ var detectionPolicySchema = z13.strictObject({
1674
1717
  /** Detections below this confidence resolve to the unknown provider. */
1675
1718
  minimumConfidence: detectionConfidenceSchema,
1676
1719
  /** When false, an ambiguous detection is an error rather than unknown. */
1677
- allowAmbiguousFallback: z12.boolean(),
1720
+ allowAmbiguousFallback: z13.boolean(),
1678
1721
  /** Optional allow-list of provider ids; empty means "any registered". */
1679
- allowedProviderIds: z12.array(nonEmptyStringSchema).max(32).readonly()
1722
+ allowedProviderIds: z13.array(nonEmptyStringSchema).max(32).readonly()
1680
1723
  });
1681
- var diagnosticsPolicySchema = z12.strictObject({
1682
- logLevel: z12.enum(["silent", "error", "warn", "info", "debug"]),
1724
+ var diagnosticsPolicySchema = z13.strictObject({
1725
+ logLevel: z13.enum(["silent", "error", "warn", "info", "debug"]),
1683
1726
  /** Emit `error.raised` events for contained failures. */
1684
- emitErrorEvents: z12.boolean()
1727
+ emitErrorEvents: z13.boolean()
1685
1728
  });
1686
- var otelHookConfigSchema = z12.strictObject({
1729
+ var otelHookConfigSchema = z13.strictObject({
1687
1730
  exporter: exporterPolicySchema,
1688
1731
  privacy: privacyPolicySchema,
1689
1732
  detection: detectionPolicySchema,
1690
1733
  diagnostics: diagnosticsPolicySchema
1691
1734
  });
1692
- var otelHookConfigPatchSchema = z12.strictObject({
1735
+ var otelHookConfigPatchSchema = z13.strictObject({
1693
1736
  // `logs` is unwrapped and re-partialled for the same reason `privacy.limits` is:
1694
1737
  // merging happens per leaf, so a layer must be able to set `logs.enabled` alone
1695
1738
  // without also restating the endpoint and the batch size.
@@ -1727,16 +1770,16 @@ var DEFAULT_CONFIG = Object.freeze({
1727
1770
  });
1728
1771
 
1729
1772
  // src/config/resolve.ts
1730
- import { z as z13 } from "zod";
1773
+ import { z as z14 } from "zod";
1731
1774
  var CONFIG_SOURCE_PRECEDENCE = ["defaults", "file", "environment", "inline-override"];
1732
- var configSourceSchema = z13.enum(CONFIG_SOURCE_PRECEDENCE);
1775
+ var configSourceSchema = z14.enum(CONFIG_SOURCE_PRECEDENCE);
1733
1776
  var isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1734
- var mergeLeaf = (target, patch, source, provenance, path7) => {
1777
+ var mergeLeaf = (target, patch, source, provenance, path9) => {
1735
1778
  for (const [key, value] of Object.entries(patch)) {
1736
1779
  if (value === void 0) {
1737
1780
  continue;
1738
1781
  }
1739
- const childPath = path7 === "" ? key : `${path7}.${key}`;
1782
+ const childPath = path9 === "" ? key : `${path9}.${key}`;
1740
1783
  const existing = target[key];
1741
1784
  if (isPlainObject(value) && isPlainObject(existing)) {
1742
1785
  const child = { ...existing };
@@ -1750,14 +1793,14 @@ var mergeLeaf = (target, patch, source, provenance, path7) => {
1750
1793
  };
1751
1794
  var initialProvenance = (config) => {
1752
1795
  const provenance = {};
1753
- const walk = (value, path7) => {
1796
+ const walk = (value, path9) => {
1754
1797
  if (isPlainObject(value)) {
1755
1798
  for (const [key, child] of Object.entries(value)) {
1756
- walk(child, path7 === "" ? key : `${path7}.${key}`);
1799
+ walk(child, path9 === "" ? key : `${path9}.${key}`);
1757
1800
  }
1758
1801
  return;
1759
1802
  }
1760
- provenance[path7] = "defaults";
1803
+ provenance[path9] = "defaults";
1761
1804
  };
1762
1805
  walk(config, "");
1763
1806
  return provenance;
@@ -1955,7 +1998,11 @@ var parseEnvironmentConfig = (env) => {
1955
1998
  for (const detail of resource?.warnings ?? []) {
1956
1999
  warn(ENVIRONMENT_VARIABLES.resourceAttributes, detail);
1957
2000
  }
1958
- const resourceAttributes = resource?.attributes ?? {};
2001
+ const resourceAttributes = { ...resource?.attributes ?? {} };
2002
+ const harSessionKey = readString("HAR_SESSION_KEY");
2003
+ if (harSessionKey !== void 0 && resourceAttributes["har.session_key"] === void 0 && harSessionKey.length <= MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH && checkResourceAttributeKey("har.session_key") === void 0) {
2004
+ resourceAttributes["har.session_key"] = harSessionKey;
2005
+ }
1959
2006
  const resolveServiceField = (sources) => {
1960
2007
  const present = sources.filter(
1961
2008
  (source) => source.value !== void 0
@@ -2070,27 +2117,27 @@ var parseEnvironmentConfig = (env) => {
2070
2117
  };
2071
2118
 
2072
2119
  // src/providers/adapter.ts
2073
- import { z as z14 } from "zod";
2074
- var providerDetectionSchema = z14.strictObject({
2120
+ import { z as z15 } from "zod";
2121
+ var providerDetectionSchema = z15.strictObject({
2075
2122
  providerId: resolvedProviderIdSchema,
2076
2123
  confidence: detectionConfidenceSchema,
2077
2124
  /**
2078
2125
  * Short, non-sensitive justifications, e.g. `"payload.hook_event_name present"`.
2079
2126
  * Reasons are exported in diagnostics, so they must not quote payload values.
2080
2127
  */
2081
- reasons: z14.array(z14.string().min(1).max(160)).max(8),
2128
+ reasons: z15.array(z15.string().min(1).max(160)).max(8),
2082
2129
  providerVersion: nonEmptyStringSchema.optional(),
2083
2130
  /** The provider's own name for this event, when the payload states one. */
2084
2131
  sourceEventName: nonEmptyStringSchema.optional()
2085
2132
  });
2086
- var deliveryIdentifierSupportSchema = z14.enum(["none", "partial", "all"]);
2133
+ var deliveryIdentifierSupportSchema = z15.enum(["none", "partial", "all"]);
2087
2134
  var DELIVERY_COMPONENT_PATTERN = /^[A-Za-z0-9_.:@+=-]{1,256}$/;
2088
- var deliveryComponentSchema = z14.string().regex(
2135
+ var deliveryComponentSchema = z15.string().regex(
2089
2136
  DELIVERY_COMPONENT_PATTERN,
2090
2137
  "delivery component must be identifier-shaped: no whitespace, no path separators"
2091
2138
  );
2092
2139
  var MAX_DELIVERY_COMPONENTS = 8;
2093
- var providerDeliveryClaimSchema = z14.strictObject({
2140
+ var providerDeliveryClaimSchema = z15.strictObject({
2094
2141
  /**
2095
2142
  * The provider's own session/conversation id. Scopes the callback identity, so
2096
2143
  * two sessions reusing one tool-call id never collide.
@@ -2102,26 +2149,26 @@ var providerDeliveryClaimSchema = z14.strictObject({
2102
2149
  * Identifier-shaped payload fields that, together with `sourceEventName`,
2103
2150
  * name this callback within the session exactly once.
2104
2151
  */
2105
- components: z14.array(deliveryComponentSchema).min(1).max(MAX_DELIVERY_COMPONENTS).readonly(),
2152
+ components: z15.array(deliveryComponentSchema).min(1).max(MAX_DELIVERY_COMPONENTS).readonly(),
2106
2153
  /**
2107
2154
  * Short, non-sensitive justifications, e.g. `"payload.tool_use_id names one
2108
2155
  * tool call"`. Evidence reaches diagnostics, so it must name fields, never
2109
2156
  * quote their values.
2110
2157
  */
2111
- evidence: z14.array(z14.string().min(1).max(160)).min(1).max(4).readonly()
2158
+ evidence: z15.array(z15.string().min(1).max(160)).min(1).max(4).readonly()
2112
2159
  });
2113
2160
  var DELIVERY_GAP_REASON_PATTERN = /^[^\n\r\t\\/]{1,240}$/;
2114
- var deliveryGapReasonSchema = z14.string().regex(
2161
+ var deliveryGapReasonSchema = z15.string().regex(
2115
2162
  DELIVERY_GAP_REASON_PATTERN,
2116
2163
  "delivery gap reason must be one line of prose: no path separators, no control characters"
2117
2164
  );
2118
2165
  var MAX_DELIVERY_GAPS = 48;
2119
- var providerDeliveryGapsSchema = z14.record(deliveryComponentSchema, deliveryGapReasonSchema).refine((gaps) => Object.keys(gaps).length <= MAX_DELIVERY_GAPS, {
2166
+ var providerDeliveryGapsSchema = z15.record(deliveryComponentSchema, deliveryGapReasonSchema).refine((gaps) => Object.keys(gaps).length <= MAX_DELIVERY_GAPS, {
2120
2167
  message: `at most ${String(MAX_DELIVERY_GAPS)} delivery gaps may be declared`
2121
2168
  });
2122
- var providerCapabilitiesSchema = z14.strictObject({
2169
+ var providerCapabilitiesSchema = z15.strictObject({
2123
2170
  /** Event types the adapter can produce. */
2124
- lifecycleEvents: z14.array(canonicalEventTypeSchema).max(32).readonly(),
2171
+ lifecycleEvents: z15.array(canonicalEventTypeSchema).max(32).readonly(),
2125
2172
  usageTemporality: usageTemporalitySchema,
2126
2173
  /**
2127
2174
  * Which accumulator series a `cumulative` report continues — that is, which
@@ -2140,32 +2187,32 @@ var providerCapabilitiesSchema = z14.strictObject({
2140
2187
  * Subagent snapshots keep their own series regardless: a delegated agent's
2141
2188
  * counter is not a point on the parent session's curve.
2142
2189
  */
2143
- cumulativeUsageSeries: z14.enum(["event-scope", "session-lifetime"]).optional(),
2144
- reportsCachedInput: z14.boolean(),
2145
- reportsCacheCreation: z14.boolean(),
2190
+ cumulativeUsageSeries: z15.enum(["event-scope", "session-lifetime"]).optional(),
2191
+ reportsCachedInput: z15.boolean(),
2192
+ reportsCacheCreation: z15.boolean(),
2146
2193
  cacheCreationAccounting: cacheCreationAccountingSchema,
2147
- reportsReasoningOutput: z14.boolean(),
2148
- reportsProviderTotal: z14.boolean(),
2149
- reportsCost: z14.boolean(),
2150
- emitsSubagentEvents: z14.boolean(),
2151
- emitsCompactionEvents: z14.boolean(),
2194
+ reportsReasoningOutput: z15.boolean(),
2195
+ reportsProviderTotal: z15.boolean(),
2196
+ reportsCost: z15.boolean(),
2197
+ emitsSubagentEvents: z15.boolean(),
2198
+ emitsCompactionEvents: z15.boolean(),
2152
2199
  /** True when the provider reads a structured response from stdout. */
2153
- requiresHookResponse: z14.boolean(),
2200
+ requiresHookResponse: z15.boolean(),
2154
2201
  /** How much of this provider's hook traffic is replay-identifiable. */
2155
2202
  deliveryIdentifier: deliveryIdentifierSupportSchema
2156
2203
  });
2157
- var providerHookResponseSchema = z14.strictObject({
2204
+ var providerHookResponseSchema = z15.strictObject({
2158
2205
  /**
2159
2206
  * Always 0. A telemetry hook that can fail the host agent is a liability, so
2160
2207
  * the type forbids expressing anything else (ADR 0004).
2161
2208
  */
2162
- exitCode: z14.literal(0),
2209
+ exitCode: z15.literal(0),
2163
2210
  /** Protocol response text. Omit to write nothing at all. */
2164
- stdout: z14.string().max(8192).optional(),
2211
+ stdout: z15.string().max(8192).optional(),
2165
2212
  /** Non-sensitive diagnostic text for stderr. */
2166
- stderr: z14.string().max(8192).optional(),
2213
+ stderr: z15.string().max(8192).optional(),
2167
2214
  /** Declares which of the two stdout contracts this response follows. */
2168
- contract: z14.enum(["silent", "provider-protocol"])
2215
+ contract: z15.enum(["silent", "provider-protocol"])
2169
2216
  });
2170
2217
  var SILENT_HOOK_RESPONSE = Object.freeze({
2171
2218
  exitCode: 0,
@@ -2222,10 +2269,15 @@ var createEventFactory = (input) => {
2222
2269
  const { identity, context } = input;
2223
2270
  const built = [];
2224
2271
  const dropped = [];
2272
+ const hints = /* @__PURE__ */ new Map();
2225
2273
  let sequence = input.sequenceBase;
2274
+ const subagentId = input.subagentId !== void 0 && subagentIdSchema.safeParse(input.subagentId).success ? input.subagentId : void 0;
2226
2275
  return {
2227
2276
  build: (draft) => {
2228
- const { occurredAt, extensions, idDiscriminator, ...rest } = draft;
2277
+ const { occurredAt, extensions, idDiscriminator, targetHint, ...drafted } = draft;
2278
+ const rest = { ...drafted };
2279
+ delete rest.target;
2280
+ delete rest.subagentId;
2229
2281
  const sanitized = extensions === void 0 ? { extensions: {}, droppedKeys: [] } : context.privacy.sanitizeExtensions(extensions);
2230
2282
  dropped.push(...sanitized.droppedKeys);
2231
2283
  const currentSequence = sequence;
@@ -2245,6 +2297,7 @@ var createEventFactory = (input) => {
2245
2297
  occurredAt: occurredAt ?? context.clock.now(),
2246
2298
  provenance: identity.provenance,
2247
2299
  workspace: identity.workspace,
2300
+ ...subagentId === void 0 ? {} : { subagentId },
2248
2301
  extensions: sanitized.extensions
2249
2302
  };
2250
2303
  const parsed = canonicalEventSchema.safeParse(candidate);
@@ -2257,11 +2310,18 @@ var createEventFactory = (input) => {
2257
2310
  });
2258
2311
  }
2259
2312
  built.push(parsed.data);
2313
+ if (targetHint !== void 0 && (parsed.data.type === "tool.start" || parsed.data.type === "tool.end")) {
2314
+ const hint = targetHintSchema.safeParse(targetHint);
2315
+ if (hint.success) {
2316
+ hints.set(parsed.data.eventId, hint.data);
2317
+ }
2318
+ }
2260
2319
  return parsed.data;
2261
2320
  },
2262
2321
  events: () => [...built],
2263
2322
  nextSequence: () => sequence,
2264
- droppedExtensionKeys: () => [...dropped]
2323
+ droppedExtensionKeys: () => [...dropped],
2324
+ targetHints: () => new Map(hints)
2265
2325
  };
2266
2326
  };
2267
2327
 
@@ -2421,35 +2481,35 @@ var CLAUDE_CODE_CAPABILITIES = Object.freeze({
2421
2481
  });
2422
2482
 
2423
2483
  // src/providers/claude/schema.ts
2424
- import { z as z15 } from "zod";
2484
+ import { z as z16 } from "zod";
2425
2485
  var commonFields = {
2426
- session_id: z15.string().min(1),
2427
- transcript_path: z15.string().min(1).optional(),
2428
- cwd: z15.string().min(1).optional(),
2429
- permission_mode: z15.string().min(1).optional(),
2486
+ session_id: z16.string().min(1),
2487
+ transcript_path: z16.string().min(1).optional(),
2488
+ cwd: z16.string().min(1).optional(),
2489
+ permission_mode: z16.string().min(1).optional(),
2430
2490
  /** Correlates a hook firing with the user prompt that triggered it (Claude Code v2.1.196+). */
2431
- prompt_id: z15.string().min(1).optional(),
2491
+ prompt_id: z16.string().min(1).optional(),
2432
2492
  /** Present when the hook fired while running inside a subagent. */
2433
- agent_id: z15.string().min(1).optional(),
2434
- agent_type: z15.string().min(1).optional()
2435
- };
2436
- var claudeCacheCreationSchema = z15.object({
2437
- ephemeral_5m_input_tokens: z15.number().int().min(0).optional(),
2438
- ephemeral_1h_input_tokens: z15.number().int().min(0).optional()
2439
- });
2440
- var claudeUsageIterationSchema = z15.object({
2441
- input_tokens: z15.number().int().min(0).optional(),
2442
- output_tokens: z15.number().int().min(0).optional(),
2443
- cache_creation_input_tokens: z15.number().int().min(0).optional(),
2444
- cache_read_input_tokens: z15.number().int().min(0).optional()
2445
- });
2446
- var claudeUsageSchema = z15.object({
2447
- input_tokens: z15.number().int().min(0),
2448
- output_tokens: z15.number().int().min(0),
2449
- cache_creation_input_tokens: z15.number().int().min(0).optional(),
2450
- cache_read_input_tokens: z15.number().int().min(0).optional(),
2493
+ agent_id: z16.string().min(1).optional(),
2494
+ agent_type: z16.string().min(1).optional()
2495
+ };
2496
+ var claudeCacheCreationSchema = z16.object({
2497
+ ephemeral_5m_input_tokens: z16.number().int().min(0).optional(),
2498
+ ephemeral_1h_input_tokens: z16.number().int().min(0).optional()
2499
+ });
2500
+ var claudeUsageIterationSchema = z16.object({
2501
+ input_tokens: z16.number().int().min(0).optional(),
2502
+ output_tokens: z16.number().int().min(0).optional(),
2503
+ cache_creation_input_tokens: z16.number().int().min(0).optional(),
2504
+ cache_read_input_tokens: z16.number().int().min(0).optional()
2505
+ });
2506
+ var claudeUsageSchema = z16.object({
2507
+ input_tokens: z16.number().int().min(0),
2508
+ output_tokens: z16.number().int().min(0),
2509
+ cache_creation_input_tokens: z16.number().int().min(0).optional(),
2510
+ cache_read_input_tokens: z16.number().int().min(0).optional(),
2451
2511
  cache_creation: claudeCacheCreationSchema.optional(),
2452
- iterations: z15.array(claudeUsageIterationSchema).optional(),
2512
+ iterations: z16.array(claudeUsageIterationSchema).optional(),
2453
2513
  /**
2454
2514
  * Counters the canonical model has a home for but Claude Code never reports:
2455
2515
  * 0 of 4,999 real usage objects carried either (finding 5).
@@ -2458,105 +2518,112 @@ var claudeUsageSchema = z15.object({
2458
2518
  * that a harness attaching one gets told it was excluded, instead of watching
2459
2519
  * it vanish. See `CLAUDE_EXCLUDED_USAGE_COUNTERS`.
2460
2520
  */
2461
- total_tokens: z15.number().int().min(0).optional(),
2462
- reasoning_output_tokens: z15.number().int().min(0).optional()
2521
+ total_tokens: z16.number().int().min(0).optional(),
2522
+ reasoning_output_tokens: z16.number().int().min(0).optional()
2463
2523
  });
2464
- var sessionStartPayloadSchema = z15.object({
2524
+ var sessionStartPayloadSchema = z16.object({
2465
2525
  ...commonFields,
2466
- hook_event_name: z15.literal("SessionStart"),
2526
+ hook_event_name: z16.literal("SessionStart"),
2467
2527
  /** Matcher values: startup | resume | clear | compact | fork. Forward-compatible: any string. */
2468
- source: z15.string().min(1).optional(),
2469
- model: z15.string().min(1).optional(),
2470
- session_title: z15.string().min(1).optional()
2528
+ source: z16.string().min(1).optional(),
2529
+ model: z16.string().min(1).optional(),
2530
+ session_title: z16.string().min(1).optional()
2471
2531
  });
2472
- var sessionEndPayloadSchema = z15.object({
2532
+ var sessionEndPayloadSchema = z16.object({
2473
2533
  ...commonFields,
2474
- hook_event_name: z15.literal("SessionEnd"),
2534
+ hook_event_name: z16.literal("SessionEnd"),
2475
2535
  /** Current Claude Code field; values include clear, logout, prompt_input_exit, and other. */
2476
- reason: z15.string().min(1).optional(),
2536
+ reason: z16.string().min(1).optional(),
2477
2537
  /** Compatibility alias emitted by older wrappers and hook integrations. */
2478
- end_reason: z15.string().min(1).optional()
2538
+ end_reason: z16.string().min(1).optional()
2479
2539
  });
2480
- var userPromptSubmitPayloadSchema = z15.object({
2540
+ var userPromptSubmitPayloadSchema = z16.object({
2481
2541
  ...commonFields,
2482
- hook_event_name: z15.literal("UserPromptSubmit"),
2483
- prompt: z15.string()
2542
+ hook_event_name: z16.literal("UserPromptSubmit"),
2543
+ prompt: z16.string()
2484
2544
  });
2485
- var preToolUsePayloadSchema = z15.object({
2545
+ var preToolUsePayloadSchema = z16.object({
2486
2546
  ...commonFields,
2487
- hook_event_name: z15.literal("PreToolUse"),
2488
- tool_name: z15.string().min(1),
2489
- tool_input: z15.unknown(),
2490
- tool_use_id: z15.string().min(1)
2547
+ hook_event_name: z16.literal("PreToolUse"),
2548
+ tool_name: z16.string().min(1),
2549
+ tool_input: z16.unknown(),
2550
+ tool_use_id: z16.string().min(1)
2491
2551
  });
2492
- var postToolUsePayloadSchema = z15.object({
2552
+ var postToolUsePayloadSchema = z16.object({
2493
2553
  ...commonFields,
2494
- hook_event_name: z15.literal("PostToolUse"),
2495
- tool_name: z15.string().min(1),
2496
- tool_input: z15.unknown().optional(),
2497
- tool_response: z15.unknown(),
2498
- tool_use_id: z15.string().min(1)
2554
+ hook_event_name: z16.literal("PostToolUse"),
2555
+ tool_name: z16.string().min(1),
2556
+ tool_input: z16.unknown().optional(),
2557
+ tool_response: z16.unknown(),
2558
+ tool_use_id: z16.string().min(1)
2499
2559
  });
2500
- var postToolUseFailurePayloadSchema = z15.object({
2560
+ var postToolUseFailurePayloadSchema = z16.object({
2501
2561
  ...commonFields,
2502
- hook_event_name: z15.literal("PostToolUseFailure"),
2503
- tool_name: z15.string().min(1),
2504
- tool_input: z15.unknown().optional(),
2505
- tool_error: z15.unknown(),
2506
- tool_use_id: z15.string().min(1)
2562
+ hook_event_name: z16.literal("PostToolUseFailure"),
2563
+ tool_name: z16.string().min(1),
2564
+ tool_input: z16.unknown().optional(),
2565
+ tool_error: z16.unknown(),
2566
+ tool_use_id: z16.string().min(1)
2507
2567
  });
2508
- var permissionRequestPayloadSchema = z15.object({
2568
+ var permissionRequestPayloadSchema = z16.object({
2509
2569
  ...commonFields,
2510
- hook_event_name: z15.literal("PermissionRequest"),
2511
- tool_name: z15.string().min(1),
2512
- tool_input: z15.unknown().optional(),
2513
- tool_use_id: z15.string().min(1)
2570
+ hook_event_name: z16.literal("PermissionRequest"),
2571
+ tool_name: z16.string().min(1),
2572
+ tool_input: z16.unknown().optional(),
2573
+ tool_use_id: z16.string().min(1)
2514
2574
  });
2515
- var subagentStartPayloadSchema = z15.object({
2575
+ var subagentStartPayloadSchema = z16.object({
2516
2576
  ...commonFields,
2517
- hook_event_name: z15.literal("SubagentStart"),
2518
- agent_type: z15.string().min(1),
2519
- agent_id: z15.string().min(1)
2577
+ hook_event_name: z16.literal("SubagentStart"),
2578
+ agent_type: z16.string().min(1),
2579
+ agent_id: z16.string().min(1)
2520
2580
  });
2521
- var subagentStopPayloadSchema = z15.object({
2581
+ var subagentStopPayloadSchema = z16.object({
2522
2582
  ...commonFields,
2523
- hook_event_name: z15.literal("SubagentStop"),
2524
- agent_type: z15.string().min(1),
2525
- agent_id: z15.string().min(1),
2526
- last_assistant_message: z15.string().optional(),
2583
+ hook_event_name: z16.literal("SubagentStop"),
2584
+ agent_type: z16.string().min(1),
2585
+ agent_id: z16.string().min(1),
2586
+ last_assistant_message: z16.string().optional(),
2527
2587
  /** True when this stop fired because a hook continued the subagent's turn. */
2528
- stop_hook_active: z15.boolean().optional(),
2588
+ stop_hook_active: z16.boolean().optional(),
2529
2589
  usage: claudeUsageSchema.optional()
2530
2590
  });
2531
- var preCompactPayloadSchema = z15.object({
2591
+ var preCompactPayloadSchema = z16.object({
2532
2592
  ...commonFields,
2533
- hook_event_name: z15.literal("PreCompact"),
2593
+ hook_event_name: z16.literal("PreCompact"),
2534
2594
  /** Upstream values: manual | auto. Forward-compatible: any string. */
2535
- trigger: z15.string().min(1).optional(),
2595
+ trigger: z16.string().min(1).optional(),
2536
2596
  /** Compatibility alias emitted by older wrappers and hook integrations. */
2537
- compact_trigger: z15.string().min(1).optional(),
2597
+ compact_trigger: z16.string().min(1).optional(),
2538
2598
  /**
2539
2599
  * Harness-supplied, never upstream. Reported as an explicit exclusion rather
2540
2600
  * than carried across the process boundary: see `events.ts`.
2541
2601
  */
2542
- context_tokens_before: z15.number().int().min(0).optional(),
2543
- estimated_tokens_removed: z15.number().int().min(0).optional()
2602
+ context_tokens_before: z16.number().int().min(0).optional(),
2603
+ estimated_tokens_removed: z16.number().int().min(0).optional()
2544
2604
  });
2545
- var postCompactPayloadSchema = z15.object({
2605
+ var postCompactPayloadSchema = z16.object({
2546
2606
  ...commonFields,
2547
- hook_event_name: z15.literal("PostCompact"),
2548
- trigger: z15.string().min(1).optional(),
2549
- compact_trigger: z15.string().min(1).optional(),
2607
+ hook_event_name: z16.literal("PostCompact"),
2608
+ trigger: z16.string().min(1).optional(),
2609
+ compact_trigger: z16.string().min(1).optional(),
2550
2610
  /** Harness-supplied, never upstream; accepted here because one callback carries both. */
2551
- context_tokens_before: z15.number().int().min(0).optional(),
2552
- context_tokens_after: z15.number().int().min(0).optional(),
2553
- dropped_message_count: z15.number().int().min(0).optional(),
2611
+ context_tokens_before: z16.number().int().min(0).optional(),
2612
+ context_tokens_after: z16.number().int().min(0).optional(),
2613
+ dropped_message_count: z16.number().int().min(0).optional(),
2554
2614
  usage: claudeUsageSchema.optional()
2555
2615
  });
2556
- var stopPayloadSchema = z15.object({
2616
+ var stopPayloadSchema = z16.object({
2557
2617
  ...commonFields,
2558
- hook_event_name: z15.literal("Stop"),
2559
- last_assistant_message: z15.string().optional(),
2618
+ hook_event_name: z16.literal("Stop"),
2619
+ /**
2620
+ * Interactive Stop field (Claude Code ≥ 2.1.47). Print / `-p` / Agent SDK
2621
+ * result messages use `result` instead; `events.ts` reads both (and camelCase
2622
+ * `lastAssistantMessage`) through `extractClaudeAssistantText`.
2623
+ */
2624
+ last_assistant_message: z16.string().optional(),
2625
+ /** Print / `-p` JSON result field; accepted so a harness can attach it as-is. */
2626
+ result: z16.string().optional(),
2560
2627
  /**
2561
2628
  * True when this stop fired because a hook continued the turn.
2562
2629
  *
@@ -2564,22 +2631,22 @@ var stopPayloadSchema = z15.object({
2564
2631
  * stop from a continuation stop, which is what lets `delivery.ts` deduplicate
2565
2632
  * the former without suppressing the latter.
2566
2633
  */
2567
- stop_hook_active: z15.boolean().optional(),
2634
+ stop_hook_active: z16.boolean().optional(),
2568
2635
  usage: claudeUsageSchema.optional()
2569
2636
  });
2570
- var stopFailurePayloadSchema = z15.object({
2637
+ var stopFailurePayloadSchema = z16.object({
2571
2638
  ...commonFields,
2572
- hook_event_name: z15.literal("StopFailure"),
2639
+ hook_event_name: z16.literal("StopFailure"),
2573
2640
  /**
2574
2641
  * Matcher values: rate_limit | overloaded | authentication_failed |
2575
2642
  * oauth_org_not_allowed | billing_error | invalid_request | model_not_found
2576
2643
  * | server_error | max_output_tokens | unknown.
2577
2644
  */
2578
- error_type: z15.string().min(1),
2579
- error_message: z15.string().optional(),
2645
+ error_type: z16.string().min(1),
2646
+ error_message: z16.string().optional(),
2580
2647
  usage: claudeUsageSchema.optional()
2581
2648
  });
2582
- var claudeHookPayloadSchema = z15.discriminatedUnion("hook_event_name", [
2649
+ var claudeHookPayloadSchema = z16.discriminatedUnion("hook_event_name", [
2583
2650
  sessionStartPayloadSchema,
2584
2651
  sessionEndPayloadSchema,
2585
2652
  userPromptSubmitPayloadSchema,
@@ -2609,17 +2676,240 @@ var CLAUDE_HOOK_EVENT_NAMES = [
2609
2676
  "Stop",
2610
2677
  "StopFailure"
2611
2678
  ];
2612
- var claudeIdentityFieldsSchema = z15.object({
2613
- session_id: z15.string().min(1),
2614
- hook_event_name: z15.string().min(1),
2615
- cwd: z15.string().min(1).optional(),
2616
- prompt_id: z15.string().min(1).optional(),
2617
- agent_id: z15.string().min(1).optional(),
2618
- tool_use_id: z15.string().min(1).optional(),
2679
+ var claudeIdentityFieldsSchema = z16.object({
2680
+ session_id: z16.string().min(1),
2681
+ hook_event_name: z16.string().min(1),
2682
+ cwd: z16.string().min(1).optional(),
2683
+ prompt_id: z16.string().min(1).optional(),
2684
+ agent_id: z16.string().min(1).optional(),
2685
+ tool_use_id: z16.string().min(1).optional(),
2619
2686
  /** Read by `delivery.ts` to tell a once-per-prompt stop from a continuation. */
2620
- stop_hook_active: z15.boolean().optional()
2687
+ stop_hook_active: z16.boolean().optional()
2621
2688
  });
2622
2689
 
2690
+ // src/providers/claude/usage.ts
2691
+ var CLAUDE_EXCLUDED_USAGE_COUNTERS = Object.freeze({
2692
+ total_tokens: `usage.total_tokens is outside Claude Code's usage contract (capability reportsProviderTotal=false): it is not read, so providerTotalAgreement stays "unreported"`,
2693
+ reasoning_output_tokens: "usage.reasoning_output_tokens is outside Claude Code's usage contract (capability reportsReasoningOutput=false): Anthropic bills thinking tokens inside output_tokens with no separate counter, so it is not read and reasoningOutputTokens stays 0"
2694
+ });
2695
+ var ITERATION_COUNTERS = [
2696
+ "input_tokens",
2697
+ "output_tokens",
2698
+ "cache_read_input_tokens",
2699
+ "cache_creation_input_tokens"
2700
+ ];
2701
+ var ttlSplitTotal = (raw) => {
2702
+ const split = raw.cache_creation;
2703
+ if (split === void 0) {
2704
+ return void 0;
2705
+ }
2706
+ return (split.ephemeral_5m_input_tokens ?? 0) + (split.ephemeral_1h_input_tokens ?? 0);
2707
+ };
2708
+ var resolveCacheCreationTokens = (raw, warnings) => {
2709
+ const declared = raw.cache_creation_input_tokens;
2710
+ const split = ttlSplitTotal(raw);
2711
+ if (declared === void 0) {
2712
+ return split ?? 0;
2713
+ }
2714
+ if (split !== void 0 && split !== declared) {
2715
+ warnings.push(
2716
+ `usage.cache_creation TTL buckets sum to ${String(split)} but usage.cache_creation_input_tokens reports ${String(declared)}; the explicit counter is used and the buckets are never added to it`
2717
+ );
2718
+ }
2719
+ return declared;
2720
+ };
2721
+ var auditIterations = (raw, cacheCreationInputTokens, warnings) => {
2722
+ const iterations = raw.iterations;
2723
+ if (iterations === void 0 || iterations.length === 0) {
2724
+ return;
2725
+ }
2726
+ const outer = {
2727
+ input_tokens: raw.input_tokens,
2728
+ output_tokens: raw.output_tokens,
2729
+ cache_read_input_tokens: raw.cache_read_input_tokens ?? 0,
2730
+ cache_creation_input_tokens: cacheCreationInputTokens
2731
+ };
2732
+ for (const counter of ITERATION_COUNTERS) {
2733
+ const summed = iterations.reduce((total, iteration) => total + (iteration[counter] ?? 0), 0);
2734
+ if (summed !== outer[counter]) {
2735
+ warnings.push(
2736
+ `usage.iterations[].${counter} sums to ${String(summed)} but usage.${counter} reports ${String(outer[counter])}; the outer counter is used and per-iteration figures are never added to it`
2737
+ );
2738
+ }
2739
+ }
2740
+ };
2741
+ var auditExcludedCounters = (raw, warnings) => {
2742
+ if (raw.total_tokens !== void 0) {
2743
+ warnings.push(CLAUDE_EXCLUDED_USAGE_COUNTERS.total_tokens);
2744
+ }
2745
+ if (raw.reasoning_output_tokens !== void 0) {
2746
+ warnings.push(CLAUDE_EXCLUDED_USAGE_COUNTERS.reasoning_output_tokens);
2747
+ }
2748
+ };
2749
+ var ACCOUNTING_RETAINED_NOTE_PREFIX = "cacheCreationAccounting=";
2750
+ var forwardableNotes = (notes) => notes.filter((note) => !note.startsWith(ACCOUNTING_RETAINED_NOTE_PREFIX));
2751
+ var asRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
2752
+ var asNonNegativeInt = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : void 0;
2753
+ var coerceClaudeUsage = (value) => {
2754
+ const record = asRecord(value);
2755
+ if (record === void 0) {
2756
+ return void 0;
2757
+ }
2758
+ const inputTokens = asNonNegativeInt(record.input_tokens ?? record.inputTokens);
2759
+ const outputTokens = asNonNegativeInt(record.output_tokens ?? record.outputTokens);
2760
+ if (inputTokens === void 0 || outputTokens === void 0) {
2761
+ return void 0;
2762
+ }
2763
+ const cacheCreation = asRecord(record.cache_creation ?? record.cacheCreation);
2764
+ const parsed = claudeUsageSchema.safeParse({
2765
+ input_tokens: inputTokens,
2766
+ output_tokens: outputTokens,
2767
+ ...asNonNegativeInt(record.cache_creation_input_tokens ?? record.cacheCreationInputTokens) === void 0 ? {} : {
2768
+ cache_creation_input_tokens: asNonNegativeInt(
2769
+ record.cache_creation_input_tokens ?? record.cacheCreationInputTokens
2770
+ )
2771
+ },
2772
+ ...asNonNegativeInt(record.cache_read_input_tokens ?? record.cacheReadInputTokens) === void 0 ? {} : {
2773
+ cache_read_input_tokens: asNonNegativeInt(
2774
+ record.cache_read_input_tokens ?? record.cacheReadInputTokens
2775
+ )
2776
+ },
2777
+ ...cacheCreation === void 0 ? {} : {
2778
+ cache_creation: {
2779
+ ...asNonNegativeInt(
2780
+ cacheCreation.ephemeral_5m_input_tokens ?? cacheCreation.ephemeral5mInputTokens
2781
+ ) === void 0 ? {} : {
2782
+ ephemeral_5m_input_tokens: asNonNegativeInt(
2783
+ cacheCreation.ephemeral_5m_input_tokens ?? cacheCreation.ephemeral5mInputTokens
2784
+ )
2785
+ },
2786
+ ...asNonNegativeInt(
2787
+ cacheCreation.ephemeral_1h_input_tokens ?? cacheCreation.ephemeral1hInputTokens
2788
+ ) === void 0 ? {} : {
2789
+ ephemeral_1h_input_tokens: asNonNegativeInt(
2790
+ cacheCreation.ephemeral_1h_input_tokens ?? cacheCreation.ephemeral1hInputTokens
2791
+ )
2792
+ }
2793
+ }
2794
+ },
2795
+ ...Array.isArray(record.iterations) ? { iterations: record.iterations } : {},
2796
+ ...asNonNegativeInt(record.total_tokens ?? record.totalTokens) === void 0 ? {} : { total_tokens: asNonNegativeInt(record.total_tokens ?? record.totalTokens) },
2797
+ ...asNonNegativeInt(record.reasoning_output_tokens ?? record.reasoningOutputTokens) === void 0 ? {} : {
2798
+ reasoning_output_tokens: asNonNegativeInt(
2799
+ record.reasoning_output_tokens ?? record.reasoningOutputTokens
2800
+ )
2801
+ }
2802
+ });
2803
+ return parsed.success ? parsed.data : void 0;
2804
+ };
2805
+ var extractClaudeUsage = (payload) => {
2806
+ const record = asRecord(payload);
2807
+ if (record === void 0) {
2808
+ return void 0;
2809
+ }
2810
+ const message = asRecord(record.message);
2811
+ const candidates = [
2812
+ record.usage,
2813
+ record.token_usage,
2814
+ record.tokenUsage,
2815
+ message?.usage,
2816
+ record
2817
+ ];
2818
+ for (const candidate of candidates) {
2819
+ const usage = coerceClaudeUsage(candidate);
2820
+ if (usage !== void 0) {
2821
+ return usage;
2822
+ }
2823
+ }
2824
+ return void 0;
2825
+ };
2826
+ var normalizeClaudeUsage = (raw) => {
2827
+ if (raw === void 0) {
2828
+ return { warnings: [] };
2829
+ }
2830
+ const warnings = [];
2831
+ const cachedInputTokens = raw.cache_read_input_tokens ?? 0;
2832
+ const cacheCreationInputTokens = resolveCacheCreationTokens(raw, warnings);
2833
+ auditIterations(raw, cacheCreationInputTokens, warnings);
2834
+ auditExcludedCounters(raw, warnings);
2835
+ const result = normalizeUsage({
2836
+ temporality: "delta",
2837
+ inputTokens: raw.input_tokens + cachedInputTokens + cacheCreationInputTokens,
2838
+ cachedInputTokens,
2839
+ cacheCreationInputTokens,
2840
+ cacheCreationAccounting: "included-in-input",
2841
+ outputTokens: raw.output_tokens
2842
+ });
2843
+ if (result.status === "invalid") {
2844
+ return { warnings: [...warnings, ...result.issues.map((issue) => issue.message)] };
2845
+ }
2846
+ return { usage: result.usage, warnings: [...warnings, ...forwardableNotes(result.notes)] };
2847
+ };
2848
+
2849
+ // src/providers/claude/payload-normalize.ts
2850
+ var FIELD_ALIASES = Object.freeze({
2851
+ hookEventName: "hook_event_name",
2852
+ sessionId: "session_id",
2853
+ lastAssistantMessage: "last_assistant_message",
2854
+ transcriptPath: "transcript_path",
2855
+ promptId: "prompt_id",
2856
+ toolUseId: "tool_use_id",
2857
+ toolName: "tool_name",
2858
+ toolInput: "tool_input",
2859
+ toolResponse: "tool_response",
2860
+ toolError: "tool_error",
2861
+ stopHookActive: "stop_hook_active",
2862
+ agentId: "agent_id",
2863
+ agentType: "agent_type",
2864
+ errorType: "error_type",
2865
+ errorMessage: "error_message",
2866
+ tokenUsage: "token_usage"
2867
+ });
2868
+ var asRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
2869
+ var applyFieldAliases = (record) => {
2870
+ const normalized = { ...record };
2871
+ for (const [alias, canonical] of Object.entries(FIELD_ALIASES)) {
2872
+ if (normalized[canonical] === void 0 && normalized[alias] !== void 0) {
2873
+ normalized[canonical] = normalized[alias];
2874
+ }
2875
+ }
2876
+ return normalized;
2877
+ };
2878
+ var applyPrintResultShape = (record) => {
2879
+ if (record.hook_event_name !== void 0 || record.type !== "result") {
2880
+ return record;
2881
+ }
2882
+ if (typeof record.session_id !== "string" || record.session_id.length === 0) {
2883
+ return record;
2884
+ }
2885
+ const isError = record.subtype === "error" || record.is_error === true;
2886
+ const normalized = {
2887
+ ...record,
2888
+ hook_event_name: isError ? "StopFailure" : "Stop"
2889
+ };
2890
+ if (normalized.last_assistant_message === void 0 && typeof record.result === "string" && record.result.length > 0) {
2891
+ normalized.last_assistant_message = record.result;
2892
+ }
2893
+ if (isError && (typeof normalized.error_type !== "string" || normalized.error_type.length === 0)) {
2894
+ normalized.error_type = "unknown";
2895
+ }
2896
+ return normalized;
2897
+ };
2898
+ var normalizeClaudeHookPayload = (payload) => {
2899
+ const record = asRecord2(payload);
2900
+ if (record === void 0) {
2901
+ return payload;
2902
+ }
2903
+ return applyUsageShape(applyPrintResultShape(applyFieldAliases(record)));
2904
+ };
2905
+ var applyUsageShape = (record) => {
2906
+ const usage = coerceClaudeUsage(record.usage) ?? coerceClaudeUsage(record.token_usage) ?? coerceClaudeUsage(record.tokenUsage);
2907
+ if (usage === void 0) {
2908
+ return record;
2909
+ }
2910
+ return { ...record, usage };
2911
+ };
2912
+
2623
2913
  // src/providers/claude/delivery.ts
2624
2914
  var TOOL_SCOPED_EVENTS = [
2625
2915
  "PreToolUse",
@@ -2628,7 +2918,7 @@ var TOOL_SCOPED_EVENTS = [
2628
2918
  "PermissionRequest"
2629
2919
  ];
2630
2920
  var claudeDeliveryIdentity = (input) => {
2631
- const parsed = claudeIdentityFieldsSchema.safeParse(input.payload);
2921
+ const parsed = claudeIdentityFieldsSchema.safeParse(normalizeClaudeHookPayload(input.payload));
2632
2922
  if (!parsed.success) {
2633
2923
  return void 0;
2634
2924
  }
@@ -2704,7 +2994,7 @@ var none = (reason) => providerDetectionSchema.parse({
2704
2994
  reasons: [reason]
2705
2995
  });
2706
2996
  var detectClaudeCode = (input) => {
2707
- const { payload } = input;
2997
+ const payload = normalizeClaudeHookPayload(input.payload);
2708
2998
  if (typeof payload !== "object" || payload === null || Array.isArray(payload)) {
2709
2999
  return none("payload is not a JSON object");
2710
3000
  }
@@ -2718,14 +3008,16 @@ var detectClaudeCode = (input) => {
2718
3008
  return none("session_id is missing");
2719
3009
  }
2720
3010
  const hasTranscriptPath = typeof record.transcript_path === "string" && record.transcript_path.length > 0;
3011
+ const isPrintResult = record.type === "result";
2721
3012
  const hinted = input.providerHint === CLAUDE_CODE_PROVIDER_ID;
2722
3013
  return providerDetectionSchema.parse({
2723
3014
  providerId: CLAUDE_CODE_PROVIDER_ID,
2724
- confidence: hinted ? "exact" : hasTranscriptPath ? "strong" : "weak",
3015
+ confidence: hinted ? "exact" : hasTranscriptPath || isPrintResult ? "strong" : "weak",
2725
3016
  reasons: [
2726
3017
  `hook_event_name=${hookEventName} matches the Claude Code hooks protocol`,
2727
3018
  "session_id present",
2728
3019
  ...hasTranscriptPath ? ["transcript_path present"] : [],
3020
+ ...isPrintResult ? ["type=result print/SDK result message"] : [],
2729
3021
  ...hinted ? ["caller asserted providerHint=claude-code"] : []
2730
3022
  ],
2731
3023
  sourceEventName: hookEventName
@@ -2735,7 +3027,7 @@ var detectClaudeCode = (input) => {
2735
3027
  // src/providers/claude/identity.ts
2736
3028
  var subagentInvocationIdFor = (context, sessionId, agentId) => invocationIdSchema.parse(`subagent_${context.ids.newOpaqueId(["claude-subagent", sessionId, agentId])}`);
2737
3029
  var identifyClaudeCode = (input, context) => {
2738
- const parsed = claudeIdentityFieldsSchema.safeParse(input.payload);
3030
+ const parsed = claudeIdentityFieldsSchema.safeParse(normalizeClaudeHookPayload(input.payload));
2739
3031
  if (!parsed.success) {
2740
3032
  return [];
2741
3033
  }
@@ -2767,6 +3059,93 @@ var identifyClaudeCode = (input, context) => {
2767
3059
  return [claim];
2768
3060
  };
2769
3061
 
3062
+ // src/providers/claude/stop-content.ts
3063
+ var TOP_LEVEL_TEXT_FIELDS = [
3064
+ "last_assistant_message",
3065
+ "lastAssistantMessage",
3066
+ "result",
3067
+ "assistant_message",
3068
+ "final_message"
3069
+ ];
3070
+ var MESSAGE_TEXT_FIELDS = ["content", "text", "result"];
3071
+ var asRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
3072
+ var nonEmptyString = (value) => typeof value === "string" && value.length > 0 ? value : void 0;
3073
+ var textFromContentBlocks = (value) => {
3074
+ if (!Array.isArray(value)) {
3075
+ return void 0;
3076
+ }
3077
+ const parts = [];
3078
+ for (const block of value) {
3079
+ const record = asRecord3(block);
3080
+ if (record === void 0) {
3081
+ continue;
3082
+ }
3083
+ const text = nonEmptyString(record.text);
3084
+ if (text !== void 0 && (record.type === void 0 || record.type === "text")) {
3085
+ parts.push(text);
3086
+ }
3087
+ }
3088
+ return parts.length === 0 ? void 0 : parts.join("");
3089
+ };
3090
+ var extractClaudeAssistantText = (payload) => {
3091
+ const record = asRecord3(payload);
3092
+ if (record === void 0) {
3093
+ return void 0;
3094
+ }
3095
+ for (const field of TOP_LEVEL_TEXT_FIELDS) {
3096
+ const text = nonEmptyString(record[field]);
3097
+ if (text !== void 0) {
3098
+ return text;
3099
+ }
3100
+ }
3101
+ const messageText2 = nonEmptyString(record.message);
3102
+ if (messageText2 !== void 0) {
3103
+ return messageText2;
3104
+ }
3105
+ const message = asRecord3(record.message);
3106
+ if (message === void 0) {
3107
+ return void 0;
3108
+ }
3109
+ for (const field of MESSAGE_TEXT_FIELDS) {
3110
+ const text = nonEmptyString(message[field]) ?? textFromContentBlocks(message[field]);
3111
+ if (text !== void 0) {
3112
+ return text;
3113
+ }
3114
+ }
3115
+ return void 0;
3116
+ };
3117
+
3118
+ // src/providers/claude/target.ts
3119
+ var PATH_FIELDS = Object.freeze({
3120
+ Read: ["file_path"],
3121
+ Write: ["file_path"],
3122
+ Edit: ["file_path"],
3123
+ MultiEdit: ["file_path"],
3124
+ NotebookEdit: ["notebook_path"],
3125
+ NotebookRead: ["notebook_path"],
3126
+ // Optional on both: absent means "search the session's directory".
3127
+ Glob: ["path"],
3128
+ Grep: ["path"]
3129
+ });
3130
+ var asRecord4 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
3131
+ var claudeTargetHint = (toolName, toolInput, cwd) => {
3132
+ const fields = Object.hasOwn(PATH_FIELDS, toolName) ? PATH_FIELDS[toolName] : void 0;
3133
+ const input = asRecord4(toolInput);
3134
+ if (fields !== void 0 && input !== void 0) {
3135
+ for (const field of fields) {
3136
+ const candidate = input[field];
3137
+ if (typeof candidate === "string" && candidate.length > 0) {
3138
+ return {
3139
+ source: "tool-path",
3140
+ paths: [candidate],
3141
+ ...cwd === void 0 ? {} : { baseDirectory: cwd }
3142
+ };
3143
+ }
3144
+ }
3145
+ }
3146
+ return cwd === void 0 ? void 0 : { source: "session-cwd", paths: [cwd] };
3147
+ };
3148
+
2770
3149
  // src/providers/claude/tool-kind.ts
2771
3150
  var BUILT_IN_TOOL_KIND = Object.freeze({
2772
3151
  Bash: "execute",
@@ -2795,90 +3174,6 @@ var inferToolKind = (toolName) => {
2795
3174
  return BUILT_IN_TOOL_KIND[toolName] ?? "unknown";
2796
3175
  };
2797
3176
 
2798
- // src/providers/claude/usage.ts
2799
- var CLAUDE_EXCLUDED_USAGE_COUNTERS = Object.freeze({
2800
- total_tokens: `usage.total_tokens is outside Claude Code's usage contract (capability reportsProviderTotal=false): it is not read, so providerTotalAgreement stays "unreported"`,
2801
- reasoning_output_tokens: "usage.reasoning_output_tokens is outside Claude Code's usage contract (capability reportsReasoningOutput=false): Anthropic bills thinking tokens inside output_tokens with no separate counter, so it is not read and reasoningOutputTokens stays 0"
2802
- });
2803
- var ITERATION_COUNTERS = [
2804
- "input_tokens",
2805
- "output_tokens",
2806
- "cache_read_input_tokens",
2807
- "cache_creation_input_tokens"
2808
- ];
2809
- var ttlSplitTotal = (raw) => {
2810
- const split = raw.cache_creation;
2811
- if (split === void 0) {
2812
- return void 0;
2813
- }
2814
- return (split.ephemeral_5m_input_tokens ?? 0) + (split.ephemeral_1h_input_tokens ?? 0);
2815
- };
2816
- var resolveCacheCreationTokens = (raw, warnings) => {
2817
- const declared = raw.cache_creation_input_tokens;
2818
- const split = ttlSplitTotal(raw);
2819
- if (declared === void 0) {
2820
- return split ?? 0;
2821
- }
2822
- if (split !== void 0 && split !== declared) {
2823
- warnings.push(
2824
- `usage.cache_creation TTL buckets sum to ${String(split)} but usage.cache_creation_input_tokens reports ${String(declared)}; the explicit counter is used and the buckets are never added to it`
2825
- );
2826
- }
2827
- return declared;
2828
- };
2829
- var auditIterations = (raw, cacheCreationInputTokens, warnings) => {
2830
- const iterations = raw.iterations;
2831
- if (iterations === void 0 || iterations.length === 0) {
2832
- return;
2833
- }
2834
- const outer = {
2835
- input_tokens: raw.input_tokens,
2836
- output_tokens: raw.output_tokens,
2837
- cache_read_input_tokens: raw.cache_read_input_tokens ?? 0,
2838
- cache_creation_input_tokens: cacheCreationInputTokens
2839
- };
2840
- for (const counter of ITERATION_COUNTERS) {
2841
- const summed = iterations.reduce((total, iteration) => total + (iteration[counter] ?? 0), 0);
2842
- if (summed !== outer[counter]) {
2843
- warnings.push(
2844
- `usage.iterations[].${counter} sums to ${String(summed)} but usage.${counter} reports ${String(outer[counter])}; the outer counter is used and per-iteration figures are never added to it`
2845
- );
2846
- }
2847
- }
2848
- };
2849
- var auditExcludedCounters = (raw, warnings) => {
2850
- if (raw.total_tokens !== void 0) {
2851
- warnings.push(CLAUDE_EXCLUDED_USAGE_COUNTERS.total_tokens);
2852
- }
2853
- if (raw.reasoning_output_tokens !== void 0) {
2854
- warnings.push(CLAUDE_EXCLUDED_USAGE_COUNTERS.reasoning_output_tokens);
2855
- }
2856
- };
2857
- var ACCOUNTING_RETAINED_NOTE_PREFIX = "cacheCreationAccounting=";
2858
- var forwardableNotes = (notes) => notes.filter((note) => !note.startsWith(ACCOUNTING_RETAINED_NOTE_PREFIX));
2859
- var normalizeClaudeUsage = (raw) => {
2860
- if (raw === void 0) {
2861
- return { warnings: [] };
2862
- }
2863
- const warnings = [];
2864
- const cachedInputTokens = raw.cache_read_input_tokens ?? 0;
2865
- const cacheCreationInputTokens = resolveCacheCreationTokens(raw, warnings);
2866
- auditIterations(raw, cacheCreationInputTokens, warnings);
2867
- auditExcludedCounters(raw, warnings);
2868
- const result = normalizeUsage({
2869
- temporality: "delta",
2870
- inputTokens: raw.input_tokens + cachedInputTokens + cacheCreationInputTokens,
2871
- cachedInputTokens,
2872
- cacheCreationInputTokens,
2873
- cacheCreationAccounting: "included-in-input",
2874
- outputTokens: raw.output_tokens
2875
- });
2876
- if (result.status === "invalid") {
2877
- return { warnings: [...warnings, ...result.issues.map((issue) => issue.message)] };
2878
- }
2879
- return { usage: result.usage, warnings: [...warnings, ...forwardableNotes(result.notes)] };
2880
- };
2881
-
2882
3177
  // src/providers/claude/events.ts
2883
3178
  var UNKNOWN_MODEL = { modelId: "unknown" };
2884
3179
  var SESSION_END_REASON = Object.freeze({
@@ -2911,7 +3206,8 @@ var DENIED_STOP_FAILURE_TYPES = /* @__PURE__ */ new Set([
2911
3206
  var mapStopFailureOutcome = (errorType) => DENIED_STOP_FAILURE_TYPES.has(errorType) ? "denied" : "error";
2912
3207
  var applyUsage = (normalized) => normalized.usage === void 0 ? {} : { usage: normalized.usage };
2913
3208
  var parseClaudeCode = (input, context) => {
2914
- const parsed = claudeHookPayloadSchema.safeParse(input.payload);
3209
+ const normalizedPayload = normalizeClaudeHookPayload(input.payload);
3210
+ const parsed = claudeHookPayloadSchema.safeParse(normalizedPayload);
2915
3211
  if (!parsed.success) {
2916
3212
  const rawEventName = typeof input.payload === "object" && input.payload !== null ? input.payload.hook_event_name : void 0;
2917
3213
  return {
@@ -2925,12 +3221,20 @@ var parseClaudeCode = (input, context) => {
2925
3221
  };
2926
3222
  }
2927
3223
  const payload = parsed.data;
3224
+ const extractedUsage = extractClaudeUsage(normalizedPayload);
2928
3225
  const factory = createEventFactory({
2929
3226
  identity: input.identity,
2930
3227
  sequenceBase: input.sequenceBase,
2931
- context
3228
+ context,
3229
+ // Present exactly when the hook fired inside a subagent (or describes one,
3230
+ // on SubagentStart/SubagentStop).
3231
+ ...payload.agent_id === void 0 ? {} : { subagentId: payload.agent_id }
2932
3232
  });
2933
3233
  const warnings = [];
3234
+ const targetHintFor = (toolName, toolInput) => {
3235
+ const hint = claudeTargetHint(toolName, toolInput, payload.cwd);
3236
+ return hint === void 0 ? {} : { targetHint: hint };
3237
+ };
2934
3238
  const withUsage = (usage) => {
2935
3239
  const normalized = normalizeClaudeUsage(usage);
2936
3240
  warnings.push(...normalized.warnings);
@@ -2948,7 +3252,8 @@ var parseClaudeCode = (input, context) => {
2948
3252
  case "SessionEnd":
2949
3253
  factory.build({
2950
3254
  type: "session.end",
2951
- reason: mapSessionEndReason(payload.reason ?? payload.end_reason)
3255
+ reason: mapSessionEndReason(payload.reason ?? payload.end_reason),
3256
+ ...withUsage(extractedUsage)
2952
3257
  });
2953
3258
  break;
2954
3259
  case "UserPromptSubmit":
@@ -2964,6 +3269,7 @@ var parseClaudeCode = (input, context) => {
2964
3269
  toolCallId: payload.tool_use_id,
2965
3270
  toolName: payload.tool_name,
2966
3271
  toolKind: inferToolKind(payload.tool_name),
3272
+ ...targetHintFor(payload.tool_name, payload.tool_input),
2967
3273
  ...payload.tool_input === void 0 ? {} : {
2968
3274
  input: context.privacy.describeStructured({
2969
3275
  kind: "tool-input",
@@ -2979,6 +3285,7 @@ var parseClaudeCode = (input, context) => {
2979
3285
  toolCallId: payload.tool_use_id,
2980
3286
  toolName: payload.tool_name,
2981
3287
  outcome: "ok",
3288
+ ...targetHintFor(payload.tool_name, payload.tool_input),
2982
3289
  output: context.privacy.describeStructured({
2983
3290
  kind: "tool-output",
2984
3291
  value: payload.tool_response,
@@ -2992,6 +3299,7 @@ var parseClaudeCode = (input, context) => {
2992
3299
  toolCallId: payload.tool_use_id,
2993
3300
  toolName: payload.tool_name,
2994
3301
  outcome: "error",
3302
+ ...targetHintFor(payload.tool_name, payload.tool_input),
2995
3303
  output: context.privacy.describeStructured({
2996
3304
  kind: "tool-output",
2997
3305
  value: payload.tool_error,
@@ -3041,22 +3349,24 @@ var parseClaudeCode = (input, context) => {
3041
3349
  payload.session_id,
3042
3350
  payload.prompt_id ?? String(input.sequenceBase)
3043
3351
  ]);
3352
+ const assistantText = extractClaudeAssistantText(normalizedPayload);
3044
3353
  factory.build({ type: "generation.start", generationId, model: UNKNOWN_MODEL });
3045
3354
  factory.build({
3046
- type: "generation.end",
3047
- generationId,
3048
- model: UNKNOWN_MODEL,
3049
- outcome: "ok",
3050
- ...payload.last_assistant_message === void 0 || payload.last_assistant_message === "" ? {} : {
3051
- outputContent: [
3052
- context.privacy.describeContent({
3053
- kind: "response",
3054
- role: "assistant",
3055
- text: payload.last_assistant_message
3056
- })
3057
- ]
3058
- },
3059
- ...withUsage(payload.usage)
3355
+ type: "generation.end",
3356
+ generationId,
3357
+ model: UNKNOWN_MODEL,
3358
+ outcome: "ok",
3359
+ // Always a response fact: a body when Claude sent text, otherwise a
3360
+ // zero-length omitted fact so the log mapping can emit metadata_only
3361
+ // instead of a generation.end with no content.kind.
3362
+ outputContent: [
3363
+ assistantText === void 0 ? context.privacy.describeUnavailableContent({ kind: "response", role: "assistant" }) : context.privacy.describeContent({
3364
+ kind: "response",
3365
+ role: "assistant",
3366
+ text: assistantText
3367
+ })
3368
+ ],
3369
+ ...withUsage(extractedUsage ?? payload.usage)
3060
3370
  });
3061
3371
  break;
3062
3372
  }
@@ -3066,6 +3376,7 @@ var parseClaudeCode = (input, context) => {
3066
3376
  payload.session_id,
3067
3377
  payload.prompt_id ?? String(input.sequenceBase)
3068
3378
  ]);
3379
+ const assistantText = extractClaudeAssistantText(normalizedPayload);
3069
3380
  factory.build({ type: "generation.start", generationId, model: UNKNOWN_MODEL });
3070
3381
  factory.build({
3071
3382
  type: "generation.end",
@@ -3073,15 +3384,26 @@ var parseClaudeCode = (input, context) => {
3073
3384
  model: UNKNOWN_MODEL,
3074
3385
  outcome: mapStopFailureOutcome(payload.error_type),
3075
3386
  stopReason: payload.error_type,
3076
- ...withUsage(payload.usage)
3387
+ ...assistantText === void 0 ? {} : {
3388
+ outputContent: [
3389
+ context.privacy.describeContent({
3390
+ kind: "response",
3391
+ role: "assistant",
3392
+ text: assistantText
3393
+ })
3394
+ ]
3395
+ },
3396
+ ...withUsage(extractedUsage ?? payload.usage)
3077
3397
  });
3078
3398
  break;
3079
3399
  }
3080
3400
  }
3401
+ const targetHints = factory.targetHints();
3081
3402
  return {
3082
3403
  status: "parsed",
3083
3404
  events: factory.events(),
3084
- ...warnings.length === 0 ? {} : { warnings }
3405
+ ...warnings.length === 0 ? {} : { warnings },
3406
+ ...targetHints.size === 0 ? {} : { targetHints }
3085
3407
  };
3086
3408
  };
3087
3409
 
@@ -3099,7 +3421,7 @@ var createClaudeCodeAdapter = (options = {}) => ({
3099
3421
  });
3100
3422
 
3101
3423
  // src/providers/cursor/payload.ts
3102
- import { z as z16 } from "zod";
3424
+ import { z as z17 } from "zod";
3103
3425
  var CURSOR_PROVIDER_ID = "cursor";
3104
3426
  var CURSOR_HOOK_EVENT_NAMES = [
3105
3427
  "sessionStart",
@@ -3134,23 +3456,23 @@ var CURSOR_DECISION_EVENTS = Object.freeze({
3134
3456
  subagentStart: "permission",
3135
3457
  beforeSubmitPrompt: "continue"
3136
3458
  });
3137
- var modelParamSchema = z16.object({
3138
- id: z16.string(),
3139
- value: z16.string()
3459
+ var modelParamSchema = z17.object({
3460
+ id: z17.string(),
3461
+ value: z17.string()
3140
3462
  });
3141
- var attachmentSchema = z16.object({
3142
- type: z16.string().optional(),
3143
- file_path: z16.string().optional()
3463
+ var attachmentSchema = z17.object({
3464
+ type: z17.string().optional(),
3465
+ file_path: z17.string().optional()
3144
3466
  });
3145
- var fileEditSchema = z16.object({
3146
- old_string: z16.string().optional(),
3147
- new_string: z16.string().optional()
3467
+ var fileEditSchema = z17.object({
3468
+ old_string: z17.string().optional(),
3469
+ new_string: z17.string().optional()
3148
3470
  });
3149
3471
  var usageFields = {
3150
- input_tokens: z16.number().int().min(0).optional(),
3151
- output_tokens: z16.number().int().min(0).optional(),
3152
- cache_read_tokens: z16.number().int().min(0).optional(),
3153
- cache_write_tokens: z16.number().int().min(0).optional()
3472
+ input_tokens: z17.number().int().min(0).optional(),
3473
+ output_tokens: z17.number().int().min(0).optional(),
3474
+ cache_read_tokens: z17.number().int().min(0).optional(),
3475
+ cache_write_tokens: z17.number().int().min(0).optional()
3154
3476
  };
3155
3477
  var envelopeShape = {
3156
3478
  // Not `.min(1)`: see `cursorSessionId`. A payload naming neither
@@ -3158,136 +3480,136 @@ var envelopeShape = {
3158
3480
  // `recognizeCursorPayload`'s post-parse check — but rejecting it here would
3159
3481
  // fail the whole discriminated union on a field the adapter can source from
3160
3482
  // either name.
3161
- conversation_id: z16.string().optional(),
3162
- generation_id: z16.string().optional(),
3163
- session_id: z16.string().optional(),
3164
- model: z16.string().optional(),
3165
- model_id: z16.string().optional(),
3166
- model_params: z16.array(modelParamSchema).max(64).optional(),
3167
- cursor_version: z16.string().optional(),
3168
- workspace_roots: z16.array(z16.string()).max(64).optional(),
3169
- cwd: z16.string().optional(),
3483
+ conversation_id: z17.string().optional(),
3484
+ generation_id: z17.string().optional(),
3485
+ session_id: z17.string().optional(),
3486
+ model: z17.string().optional(),
3487
+ model_id: z17.string().optional(),
3488
+ model_params: z17.array(modelParamSchema).max(64).optional(),
3489
+ cursor_version: z17.string().optional(),
3490
+ workspace_roots: z17.array(z17.string()).max(64).optional(),
3491
+ cwd: z17.string().optional(),
3170
3492
  /** Never propagated. */
3171
- user_email: z16.string().nullish(),
3493
+ user_email: z17.string().nullish(),
3172
3494
  /** Never propagated. */
3173
- transcript_path: z16.string().nullish()
3495
+ transcript_path: z17.string().nullish()
3174
3496
  };
3175
- var event2 = (name, shape) => z16.object({ ...envelopeShape, hook_event_name: z16.literal(name), ...shape });
3497
+ var event2 = (name, shape) => z17.object({ ...envelopeShape, hook_event_name: z17.literal(name), ...shape });
3176
3498
  var sessionStartPayloadSchema2 = event2("sessionStart", {
3177
- is_background_agent: z16.boolean().optional(),
3178
- composer_mode: z16.string().optional()
3499
+ is_background_agent: z17.boolean().optional(),
3500
+ composer_mode: z17.string().optional()
3179
3501
  });
3180
3502
  var sessionEndPayloadSchema2 = event2("sessionEnd", {
3181
- reason: z16.string().optional(),
3182
- duration_ms: z16.number().min(0).optional(),
3183
- is_background_agent: z16.boolean().optional(),
3184
- final_status: z16.string().optional(),
3185
- error_message: z16.string().optional()
3503
+ reason: z17.string().optional(),
3504
+ duration_ms: z17.number().min(0).optional(),
3505
+ is_background_agent: z17.boolean().optional(),
3506
+ final_status: z17.string().optional(),
3507
+ error_message: z17.string().optional()
3186
3508
  });
3187
3509
  var beforeSubmitPromptPayloadSchema = event2("beforeSubmitPrompt", {
3188
- prompt: z16.string().optional(),
3189
- attachments: z16.array(attachmentSchema).max(256).optional(),
3190
- composer_mode: z16.string().optional()
3510
+ prompt: z17.string().optional(),
3511
+ attachments: z17.array(attachmentSchema).max(256).optional(),
3512
+ composer_mode: z17.string().optional()
3191
3513
  });
3192
3514
  var afterAgentResponsePayloadSchema = event2("afterAgentResponse", {
3193
- text: z16.string().optional(),
3515
+ text: z17.string().optional(),
3194
3516
  ...usageFields
3195
3517
  });
3196
3518
  var afterAgentThoughtPayloadSchema = event2("afterAgentThought", {
3197
- text: z16.string().optional(),
3198
- duration_ms: z16.number().min(0).optional()
3519
+ text: z17.string().optional(),
3520
+ duration_ms: z17.number().min(0).optional()
3199
3521
  });
3200
3522
  var preToolUsePayloadSchema2 = event2("preToolUse", {
3201
- tool_name: z16.string().min(1),
3202
- tool_input: z16.unknown().optional(),
3203
- tool_use_id: z16.string().optional(),
3204
- agent_message: z16.string().optional()
3523
+ tool_name: z17.string().min(1),
3524
+ tool_input: z17.unknown().optional(),
3525
+ tool_use_id: z17.string().optional(),
3526
+ agent_message: z17.string().optional()
3205
3527
  });
3206
3528
  var postToolUsePayloadSchema2 = event2("postToolUse", {
3207
- tool_name: z16.string().min(1),
3208
- tool_input: z16.unknown().optional(),
3209
- tool_output: z16.unknown().optional(),
3210
- tool_use_id: z16.string().optional(),
3211
- duration: z16.number().min(0).optional()
3529
+ tool_name: z17.string().min(1),
3530
+ tool_input: z17.unknown().optional(),
3531
+ tool_output: z17.unknown().optional(),
3532
+ tool_use_id: z17.string().optional(),
3533
+ duration: z17.number().min(0).optional()
3212
3534
  });
3213
3535
  var postToolUseFailurePayloadSchema2 = event2("postToolUseFailure", {
3214
- tool_name: z16.string().min(1),
3215
- tool_input: z16.unknown().optional(),
3216
- tool_use_id: z16.string().optional(),
3217
- error_message: z16.string().optional(),
3218
- failure_type: z16.string().optional(),
3219
- duration: z16.number().min(0).optional(),
3220
- is_interrupt: z16.boolean().optional()
3536
+ tool_name: z17.string().min(1),
3537
+ tool_input: z17.unknown().optional(),
3538
+ tool_use_id: z17.string().optional(),
3539
+ error_message: z17.string().optional(),
3540
+ failure_type: z17.string().optional(),
3541
+ duration: z17.number().min(0).optional(),
3542
+ is_interrupt: z17.boolean().optional()
3221
3543
  });
3222
3544
  var beforeShellExecutionPayloadSchema = event2("beforeShellExecution", {
3223
- command: z16.string(),
3224
- sandbox: z16.boolean().optional()
3545
+ command: z17.string(),
3546
+ sandbox: z17.boolean().optional()
3225
3547
  });
3226
3548
  var afterShellExecutionPayloadSchema = event2("afterShellExecution", {
3227
- command: z16.string(),
3228
- output: z16.string().optional(),
3229
- duration: z16.number().min(0).optional(),
3230
- sandbox: z16.boolean().optional()
3549
+ command: z17.string(),
3550
+ output: z17.string().optional(),
3551
+ duration: z17.number().min(0).optional(),
3552
+ sandbox: z17.boolean().optional()
3231
3553
  });
3232
3554
  var beforeMcpExecutionPayloadSchema = event2("beforeMCPExecution", {
3233
- tool_name: z16.string().min(1),
3234
- tool_input: z16.unknown().optional(),
3235
- url: z16.string().optional(),
3236
- command: z16.string().optional()
3555
+ tool_name: z17.string().min(1),
3556
+ tool_input: z17.unknown().optional(),
3557
+ url: z17.string().optional(),
3558
+ command: z17.string().optional()
3237
3559
  });
3238
3560
  var afterMcpExecutionPayloadSchema = event2("afterMCPExecution", {
3239
- tool_name: z16.string().min(1),
3240
- tool_input: z16.unknown().optional(),
3241
- result_json: z16.string().optional(),
3242
- duration: z16.number().min(0).optional()
3561
+ tool_name: z17.string().min(1),
3562
+ tool_input: z17.unknown().optional(),
3563
+ result_json: z17.string().optional(),
3564
+ duration: z17.number().min(0).optional()
3243
3565
  });
3244
3566
  var beforeReadFilePayloadSchema = event2("beforeReadFile", {
3245
- file_path: z16.string(),
3246
- content: z16.string().optional(),
3247
- attachments: z16.array(attachmentSchema).max(256).optional()
3567
+ file_path: z17.string(),
3568
+ content: z17.string().optional(),
3569
+ attachments: z17.array(attachmentSchema).max(256).optional()
3248
3570
  });
3249
3571
  var afterFileEditPayloadSchema = event2("afterFileEdit", {
3250
- file_path: z16.string(),
3251
- edits: z16.array(fileEditSchema).max(1024).optional()
3572
+ file_path: z17.string(),
3573
+ edits: z17.array(fileEditSchema).max(1024).optional()
3252
3574
  });
3253
3575
  var subagentStartPayloadSchema2 = event2("subagentStart", {
3254
- subagent_id: z16.string().optional(),
3255
- subagent_type: z16.string().optional(),
3256
- task: z16.string().optional(),
3257
- parent_conversation_id: z16.string().optional(),
3258
- tool_call_id: z16.string().optional(),
3259
- subagent_model: z16.string().optional(),
3260
- is_parallel_worker: z16.boolean().optional(),
3261
- git_branch: z16.string().optional()
3576
+ subagent_id: z17.string().optional(),
3577
+ subagent_type: z17.string().optional(),
3578
+ task: z17.string().optional(),
3579
+ parent_conversation_id: z17.string().optional(),
3580
+ tool_call_id: z17.string().optional(),
3581
+ subagent_model: z17.string().optional(),
3582
+ is_parallel_worker: z17.boolean().optional(),
3583
+ git_branch: z17.string().optional()
3262
3584
  });
3263
3585
  var subagentStopPayloadSchema2 = event2("subagentStop", {
3264
- subagent_type: z16.string().optional(),
3265
- status: z16.string().optional(),
3266
- task: z16.string().optional(),
3267
- description: z16.string().optional(),
3268
- summary: z16.string().optional(),
3269
- duration_ms: z16.number().min(0).optional(),
3270
- message_count: z16.number().int().min(0).optional(),
3271
- tool_call_count: z16.number().int().min(0).optional(),
3272
- loop_count: z16.number().int().min(0).optional(),
3273
- modified_files: z16.array(z16.string()).max(1024).optional(),
3274
- agent_transcript_path: z16.string().nullish()
3586
+ subagent_type: z17.string().optional(),
3587
+ status: z17.string().optional(),
3588
+ task: z17.string().optional(),
3589
+ description: z17.string().optional(),
3590
+ summary: z17.string().optional(),
3591
+ duration_ms: z17.number().min(0).optional(),
3592
+ message_count: z17.number().int().min(0).optional(),
3593
+ tool_call_count: z17.number().int().min(0).optional(),
3594
+ loop_count: z17.number().int().min(0).optional(),
3595
+ modified_files: z17.array(z17.string()).max(1024).optional(),
3596
+ agent_transcript_path: z17.string().nullish()
3275
3597
  });
3276
3598
  var preCompactPayloadSchema2 = event2("preCompact", {
3277
- trigger: z16.string().optional(),
3278
- context_usage_percent: z16.number().optional(),
3279
- context_tokens: z16.number().int().min(0).optional(),
3280
- context_window_size: z16.number().int().min(0).optional(),
3281
- message_count: z16.number().int().min(0).optional(),
3282
- messages_to_compact: z16.number().int().min(0).optional(),
3283
- is_first_compaction: z16.boolean().optional()
3599
+ trigger: z17.string().optional(),
3600
+ context_usage_percent: z17.number().optional(),
3601
+ context_tokens: z17.number().int().min(0).optional(),
3602
+ context_window_size: z17.number().int().min(0).optional(),
3603
+ message_count: z17.number().int().min(0).optional(),
3604
+ messages_to_compact: z17.number().int().min(0).optional(),
3605
+ is_first_compaction: z17.boolean().optional()
3284
3606
  });
3285
3607
  var stopPayloadSchema2 = event2("stop", {
3286
- status: z16.string().optional(),
3287
- loop_count: z16.number().int().min(0).optional(),
3608
+ status: z17.string().optional(),
3609
+ loop_count: z17.number().int().min(0).optional(),
3288
3610
  ...usageFields
3289
3611
  });
3290
- var cursorPayloadSchema = z16.discriminatedUnion("hook_event_name", [
3612
+ var cursorPayloadSchema = z17.discriminatedUnion("hook_event_name", [
3291
3613
  sessionStartPayloadSchema2,
3292
3614
  sessionEndPayloadSchema2,
3293
3615
  beforeSubmitPromptPayloadSchema,
@@ -3424,6 +3746,33 @@ var cursorDeliveryIdentity = (input) => {
3424
3746
  };
3425
3747
  };
3426
3748
 
3749
+ // src/providers/cursor/target.ts
3750
+ var singleWorkspaceRoot = (payload) => {
3751
+ const roots = (payload.workspace_roots ?? []).filter((root) => root.length > 0);
3752
+ return roots.length === 1 ? roots[0] : void 0;
3753
+ };
3754
+ var sessionHint = (root) => root === void 0 ? void 0 : { source: "session-cwd", paths: [root] };
3755
+ var cursorTargetHint = (payload) => {
3756
+ const root = singleWorkspaceRoot(payload);
3757
+ const base = root === void 0 ? {} : { baseDirectory: root };
3758
+ switch (payload.hook_event_name) {
3759
+ case "afterFileEdit":
3760
+ case "beforeReadFile":
3761
+ return payload.file_path.length === 0 ? sessionHint(root) : { source: "tool-path", paths: [payload.file_path], ...base };
3762
+ case "beforeShellExecution":
3763
+ case "afterShellExecution":
3764
+ return payload.cwd !== void 0 && payload.cwd.length > 0 ? { source: "shell-cwd", paths: [payload.cwd], ...base } : sessionHint(root);
3765
+ case "preToolUse":
3766
+ case "postToolUse":
3767
+ case "postToolUseFailure":
3768
+ case "beforeMCPExecution":
3769
+ case "afterMCPExecution":
3770
+ return sessionHint(root);
3771
+ default:
3772
+ return void 0;
3773
+ }
3774
+ };
3775
+
3427
3776
  // src/providers/cursor/usage.ts
3428
3777
  var normalizeCursorUsage = (raw) => {
3429
3778
  const inputTokens = raw.input_tokens;
@@ -3679,12 +4028,6 @@ var createCursorAdapter = (options = {}) => {
3679
4028
  reason: "afterAgentThought is a reasoning notification, not a generation lifecycle event; no canonical event type represents it and thought text is never exported"
3680
4029
  };
3681
4030
  }
3682
- if (payload.hook_event_name === "beforeReadFile") {
3683
- return {
3684
- status: "ignored",
3685
- reason: "beforeReadFile has no completion callback in the cursor hook protocol, so emitting tool.start here would leave a tool lifecycle that never closes"
3686
- };
3687
- }
3688
4031
  if (payload.hook_event_name === "subagentStart" || payload.hook_event_name === "subagentStop") {
3689
4032
  return {
3690
4033
  status: "ignored",
@@ -3699,6 +4042,8 @@ var createCursorAdapter = (options = {}) => {
3699
4042
  const warnings = [];
3700
4043
  const sessionId = input.identity.sessionId;
3701
4044
  const model = toModelDescriptor(payload);
4045
+ const targetHint = cursorTargetHint(payload);
4046
+ const targetHintField = targetHint === void 0 ? {} : { targetHint };
3702
4047
  switch (payload.hook_event_name) {
3703
4048
  case "sessionStart":
3704
4049
  factory.build({
@@ -3751,6 +4096,7 @@ var createCursorAdapter = (options = {}) => {
3751
4096
  case "preToolUse":
3752
4097
  factory.build({
3753
4098
  type: "tool.start",
4099
+ ...targetHintField,
3754
4100
  toolCallId: payload.tool_use_id ?? derivedToolCallId(context, sessionId, [
3755
4101
  "tool",
3756
4102
  payload.generation_id ?? "",
@@ -3774,6 +4120,7 @@ var createCursorAdapter = (options = {}) => {
3774
4120
  case "postToolUse":
3775
4121
  factory.build({
3776
4122
  type: "tool.end",
4123
+ ...targetHintField,
3777
4124
  toolCallId: payload.tool_use_id ?? derivedToolCallId(context, sessionId, [
3778
4125
  "tool",
3779
4126
  payload.generation_id ?? "",
@@ -3796,6 +4143,7 @@ var createCursorAdapter = (options = {}) => {
3796
4143
  case "postToolUseFailure":
3797
4144
  factory.build({
3798
4145
  type: "tool.end",
4146
+ ...targetHintField,
3799
4147
  toolCallId: payload.tool_use_id ?? derivedToolCallId(context, sessionId, [
3800
4148
  "tool",
3801
4149
  payload.generation_id ?? "",
@@ -3816,6 +4164,7 @@ var createCursorAdapter = (options = {}) => {
3816
4164
  case "beforeShellExecution":
3817
4165
  factory.build({
3818
4166
  type: "tool.start",
4167
+ ...targetHintField,
3819
4168
  toolCallId: derivedToolCallId(context, sessionId, [
3820
4169
  "shell",
3821
4170
  payload.generation_id ?? "",
@@ -3835,6 +4184,7 @@ var createCursorAdapter = (options = {}) => {
3835
4184
  case "afterShellExecution":
3836
4185
  factory.build({
3837
4186
  type: "tool.end",
4187
+ ...targetHintField,
3838
4188
  toolCallId: derivedToolCallId(context, sessionId, [
3839
4189
  "shell",
3840
4190
  payload.generation_id ?? "",
@@ -3859,6 +4209,7 @@ var createCursorAdapter = (options = {}) => {
3859
4209
  case "beforeMCPExecution":
3860
4210
  factory.build({
3861
4211
  type: "tool.start",
4212
+ ...targetHintField,
3862
4213
  toolCallId: derivedToolCallId(context, sessionId, [
3863
4214
  "mcp",
3864
4215
  payload.generation_id ?? "",
@@ -3879,6 +4230,7 @@ var createCursorAdapter = (options = {}) => {
3879
4230
  case "afterMCPExecution":
3880
4231
  factory.build({
3881
4232
  type: "tool.end",
4233
+ ...targetHintField,
3882
4234
  toolCallId: derivedToolCallId(context, sessionId, [
3883
4235
  "mcp",
3884
4236
  payload.generation_id ?? "",
@@ -3906,6 +4258,7 @@ var createCursorAdapter = (options = {}) => {
3906
4258
  ]);
3907
4259
  factory.build({
3908
4260
  type: "tool.start",
4261
+ ...targetHintField,
3909
4262
  toolCallId,
3910
4263
  toolName: "edit_file",
3911
4264
  toolKind: "write",
@@ -3918,6 +4271,7 @@ var createCursorAdapter = (options = {}) => {
3918
4271
  });
3919
4272
  factory.build({
3920
4273
  type: "tool.end",
4274
+ ...targetHintField,
3921
4275
  toolCallId,
3922
4276
  toolName: "edit_file",
3923
4277
  outcome: "ok",
@@ -3927,6 +4281,34 @@ var createCursorAdapter = (options = {}) => {
3927
4281
  });
3928
4282
  break;
3929
4283
  }
4284
+ case "beforeReadFile": {
4285
+ const toolCallId = derivedToolCallId(context, sessionId, [
4286
+ "read-file",
4287
+ payload.generation_id ?? "",
4288
+ payload.file_path
4289
+ ]);
4290
+ factory.build({
4291
+ type: "tool.start",
4292
+ ...targetHintField,
4293
+ toolCallId,
4294
+ toolName: "read_file",
4295
+ toolKind: "read",
4296
+ ...payload.generation_id === void 0 || payload.generation_id.length === 0 ? {} : { generationId: payload.generation_id },
4297
+ input: context.privacy.describeContent({
4298
+ kind: "tool-input",
4299
+ text: payload.file_path,
4300
+ label: "read_file"
4301
+ })
4302
+ });
4303
+ factory.build({
4304
+ type: "tool.end",
4305
+ ...targetHintField,
4306
+ toolCallId,
4307
+ toolName: "read_file",
4308
+ outcome: "unknown"
4309
+ });
4310
+ break;
4311
+ }
3930
4312
  case "preCompact":
3931
4313
  factory.build({
3932
4314
  type: "compaction.performed",
@@ -3964,10 +4346,12 @@ var createCursorAdapter = (options = {}) => {
3964
4346
  break;
3965
4347
  }
3966
4348
  }
4349
+ const targetHints = factory.targetHints();
3967
4350
  return {
3968
4351
  status: "parsed",
3969
4352
  events: factory.events(),
3970
- ...warnings.length === 0 ? {} : { warnings }
4353
+ ...warnings.length === 0 ? {} : { warnings },
4354
+ ...targetHints.size === 0 ? {} : { targetHints }
3971
4355
  };
3972
4356
  };
3973
4357
  const hookResponse2 = (input) => {
@@ -3998,105 +4382,105 @@ var createCursorAdapter = (options = {}) => {
3998
4382
  };
3999
4383
 
4000
4384
  // src/providers/codex/payload.ts
4001
- import { z as z17 } from "zod";
4002
- var permissionModeSchema = z17.enum([
4385
+ import { z as z18 } from "zod";
4386
+ var permissionModeSchema = z18.enum([
4003
4387
  "default",
4004
4388
  "acceptEdits",
4005
4389
  "plan",
4006
4390
  "dontAsk",
4007
4391
  "bypassPermissions"
4008
4392
  ]);
4009
- var codexUsageSchema = z17.object({
4010
- input_tokens: z17.number().int().min(0).optional(),
4011
- cached_input_tokens: z17.number().int().min(0).optional(),
4012
- output_tokens: z17.number().int().min(0).optional(),
4013
- reasoning_output_tokens: z17.number().int().min(0).optional(),
4014
- total_tokens: z17.number().int().min(0).optional()
4393
+ var codexUsageSchema = z18.object({
4394
+ input_tokens: z18.number().int().min(0).optional(),
4395
+ cached_input_tokens: z18.number().int().min(0).optional(),
4396
+ output_tokens: z18.number().int().min(0).optional(),
4397
+ reasoning_output_tokens: z18.number().int().min(0).optional(),
4398
+ total_tokens: z18.number().int().min(0).optional()
4015
4399
  });
4016
4400
  var baseFields = {
4017
- session_id: z17.string().min(1).max(256),
4018
- cwd: z17.string().min(1).max(4096).optional(),
4019
- model: z17.string().min(1).max(256).optional(),
4401
+ session_id: z18.string().min(1).max(256),
4402
+ cwd: z18.string().min(1).max(4096).optional(),
4403
+ model: z18.string().min(1).max(256).optional(),
4020
4404
  permission_mode: permissionModeSchema.optional(),
4021
- transcript_path: z17.string().min(1).max(4096).optional(),
4022
- codex_version: z17.string().min(1).max(64).optional(),
4405
+ transcript_path: z18.string().min(1).max(4096).optional(),
4406
+ codex_version: z18.string().min(1).max(64).optional(),
4023
4407
  /** Not part of the documented protocol; lets tests and replay stay deterministic. */
4024
- occurred_at: z17.number().int().min(0).optional()
4408
+ occurred_at: z18.number().int().min(0).optional()
4025
4409
  };
4026
- var codexSessionStartPayloadSchema = z17.object({
4410
+ var codexSessionStartPayloadSchema = z18.object({
4027
4411
  ...baseFields,
4028
- hook_event_name: z17.literal("SessionStart"),
4029
- source: z17.enum(["startup", "resume", "clear", "compact"]).optional()
4412
+ hook_event_name: z18.literal("SessionStart"),
4413
+ source: z18.enum(["startup", "resume", "clear", "compact"]).optional()
4030
4414
  });
4031
- var codexUserPromptSubmitPayloadSchema = z17.object({
4415
+ var codexUserPromptSubmitPayloadSchema = z18.object({
4032
4416
  ...baseFields,
4033
- hook_event_name: z17.literal("UserPromptSubmit"),
4034
- turn_id: z17.string().min(1).max(256).optional(),
4035
- prompt: z17.string().max(1e6).optional()
4417
+ hook_event_name: z18.literal("UserPromptSubmit"),
4418
+ turn_id: z18.string().min(1).max(256).optional(),
4419
+ prompt: z18.string().max(1e6).optional()
4036
4420
  });
4037
- var codexPreToolUsePayloadSchema = z17.object({
4421
+ var codexPreToolUsePayloadSchema = z18.object({
4038
4422
  ...baseFields,
4039
- hook_event_name: z17.literal("PreToolUse"),
4040
- turn_id: z17.string().min(1).max(256).optional(),
4041
- tool_name: z17.string().min(1).max(256),
4042
- tool_call_id: z17.string().min(1).max(256).optional(),
4043
- tool_input: z17.unknown().optional()
4423
+ hook_event_name: z18.literal("PreToolUse"),
4424
+ turn_id: z18.string().min(1).max(256).optional(),
4425
+ tool_name: z18.string().min(1).max(256),
4426
+ tool_call_id: z18.string().min(1).max(256).optional(),
4427
+ tool_input: z18.unknown().optional()
4044
4428
  });
4045
- var codexPermissionRequestPayloadSchema = z17.object({
4429
+ var codexPermissionRequestPayloadSchema = z18.object({
4046
4430
  ...baseFields,
4047
- hook_event_name: z17.literal("PermissionRequest"),
4048
- turn_id: z17.string().min(1).max(256).optional(),
4049
- tool_name: z17.string().min(1).max(256).optional(),
4050
- tool_call_id: z17.string().min(1).max(256).optional(),
4051
- tool_input: z17.unknown().optional()
4431
+ hook_event_name: z18.literal("PermissionRequest"),
4432
+ turn_id: z18.string().min(1).max(256).optional(),
4433
+ tool_name: z18.string().min(1).max(256).optional(),
4434
+ tool_call_id: z18.string().min(1).max(256).optional(),
4435
+ tool_input: z18.unknown().optional()
4052
4436
  });
4053
- var codexPostToolUsePayloadSchema = z17.object({
4437
+ var codexPostToolUsePayloadSchema = z18.object({
4054
4438
  ...baseFields,
4055
- hook_event_name: z17.literal("PostToolUse"),
4056
- turn_id: z17.string().min(1).max(256).optional(),
4057
- tool_name: z17.string().min(1).max(256),
4058
- tool_call_id: z17.string().min(1).max(256).optional(),
4059
- tool_input: z17.unknown().optional(),
4060
- tool_response: z17.unknown().optional(),
4061
- permission_decision: z17.enum(["allowed", "denied", "deferred"]).optional(),
4062
- duration_ms: z17.number().min(0).optional()
4439
+ hook_event_name: z18.literal("PostToolUse"),
4440
+ turn_id: z18.string().min(1).max(256).optional(),
4441
+ tool_name: z18.string().min(1).max(256),
4442
+ tool_call_id: z18.string().min(1).max(256).optional(),
4443
+ tool_input: z18.unknown().optional(),
4444
+ tool_response: z18.unknown().optional(),
4445
+ permission_decision: z18.enum(["allowed", "denied", "deferred"]).optional(),
4446
+ duration_ms: z18.number().min(0).optional()
4063
4447
  });
4064
- var codexPreCompactPayloadSchema = z17.object({
4448
+ var codexPreCompactPayloadSchema = z18.object({
4065
4449
  ...baseFields,
4066
- hook_event_name: z17.literal("PreCompact"),
4067
- trigger: z17.enum(["auto", "manual"]).optional(),
4068
- context_tokens_before: z17.number().int().min(0).optional()
4450
+ hook_event_name: z18.literal("PreCompact"),
4451
+ trigger: z18.enum(["auto", "manual"]).optional(),
4452
+ context_tokens_before: z18.number().int().min(0).optional()
4069
4453
  });
4070
- var codexPostCompactPayloadSchema = z17.object({
4454
+ var codexPostCompactPayloadSchema = z18.object({
4071
4455
  ...baseFields,
4072
- hook_event_name: z17.literal("PostCompact"),
4073
- trigger: z17.enum(["auto", "manual"]).optional(),
4074
- context_tokens_after: z17.number().int().min(0).optional(),
4075
- dropped_message_count: z17.number().int().min(0).optional(),
4456
+ hook_event_name: z18.literal("PostCompact"),
4457
+ trigger: z18.enum(["auto", "manual"]).optional(),
4458
+ context_tokens_after: z18.number().int().min(0).optional(),
4459
+ dropped_message_count: z18.number().int().min(0).optional(),
4076
4460
  usage: codexUsageSchema.optional()
4077
4461
  });
4078
- var codexSubagentStartPayloadSchema = z17.object({
4462
+ var codexSubagentStartPayloadSchema = z18.object({
4079
4463
  ...baseFields,
4080
- hook_event_name: z17.literal("SubagentStart"),
4081
- turn_id: z17.string().min(1).max(256).optional(),
4082
- subagent_id: z17.string().min(1).max(256),
4083
- subagent_type: z17.string().min(1).max(256).optional()
4464
+ hook_event_name: z18.literal("SubagentStart"),
4465
+ turn_id: z18.string().min(1).max(256).optional(),
4466
+ subagent_id: z18.string().min(1).max(256),
4467
+ subagent_type: z18.string().min(1).max(256).optional()
4084
4468
  });
4085
- var codexSubagentStopPayloadSchema = z17.object({
4469
+ var codexSubagentStopPayloadSchema = z18.object({
4086
4470
  ...baseFields,
4087
- hook_event_name: z17.literal("SubagentStop"),
4088
- turn_id: z17.string().min(1).max(256).optional(),
4089
- subagent_id: z17.string().min(1).max(256),
4090
- status: z17.enum(["completed", "failed", "cancelled"]).optional(),
4471
+ hook_event_name: z18.literal("SubagentStop"),
4472
+ turn_id: z18.string().min(1).max(256).optional(),
4473
+ subagent_id: z18.string().min(1).max(256),
4474
+ status: z18.enum(["completed", "failed", "cancelled"]).optional(),
4091
4475
  usage: codexUsageSchema.optional()
4092
4476
  });
4093
- var codexStopPayloadSchema = z17.object({
4477
+ var codexStopPayloadSchema = z18.object({
4094
4478
  ...baseFields,
4095
- hook_event_name: z17.literal("Stop"),
4096
- turn_id: z17.string().min(1).max(256).optional(),
4097
- stop_reason: z17.string().min(1).max(256).optional(),
4479
+ hook_event_name: z18.literal("Stop"),
4480
+ turn_id: z18.string().min(1).max(256).optional(),
4481
+ stop_reason: z18.string().min(1).max(256).optional(),
4098
4482
  usage: codexUsageSchema.optional(),
4099
- duration_ms: z17.number().min(0).optional()
4483
+ duration_ms: z18.number().min(0).optional()
4100
4484
  });
4101
4485
  var CODEX_HOOK_EVENT_NAMES = [
4102
4486
  "SessionStart",
@@ -4110,7 +4494,7 @@ var CODEX_HOOK_EVENT_NAMES = [
4110
4494
  "SubagentStop",
4111
4495
  "Stop"
4112
4496
  ];
4113
- var codexHookPayloadSchema = z17.discriminatedUnion("hook_event_name", [
4497
+ var codexHookPayloadSchema = z18.discriminatedUnion("hook_event_name", [
4114
4498
  codexSessionStartPayloadSchema,
4115
4499
  codexUserPromptSubmitPayloadSchema,
4116
4500
  codexPreToolUsePayloadSchema,
@@ -4122,9 +4506,9 @@ var codexHookPayloadSchema = z17.discriminatedUnion("hook_event_name", [
4122
4506
  codexSubagentStopPayloadSchema,
4123
4507
  codexStopPayloadSchema
4124
4508
  ]);
4125
- var codexHookEnvelopeSchema = z17.object({
4126
- session_id: z17.string().min(1),
4127
- hook_event_name: z17.enum(CODEX_HOOK_EVENT_NAMES)
4509
+ var codexHookEnvelopeSchema = z18.object({
4510
+ session_id: z18.string().min(1),
4511
+ hook_event_name: z18.enum(CODEX_HOOK_EVENT_NAMES)
4128
4512
  });
4129
4513
 
4130
4514
  // src/providers/codex/delivery.ts
@@ -4185,6 +4569,61 @@ var codexDeliveryIdentity = (input) => {
4185
4569
  };
4186
4570
  };
4187
4571
 
4572
+ // src/providers/codex/target.ts
4573
+ var PATCH_HEADER = /^\*\*\* (?:Add File|Update File|Delete File|Move to): (.+)$/;
4574
+ var asRecord5 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
4575
+ var nonEmptyString2 = (value) => typeof value === "string" && value.length > 0 ? value : void 0;
4576
+ var commandText = (input) => {
4577
+ const command = input?.command ?? input?.cmd;
4578
+ if (typeof command === "string") {
4579
+ return command;
4580
+ }
4581
+ if (Array.isArray(command) && command.every((part) => typeof part === "string")) {
4582
+ return command.join(" ");
4583
+ }
4584
+ return void 0;
4585
+ };
4586
+ var patchHeaderPaths = (patch) => {
4587
+ const paths = /* @__PURE__ */ new Set();
4588
+ for (const line of patch.split(/\r?\n/)) {
4589
+ const match = PATCH_HEADER.exec(line.trimEnd());
4590
+ const named = match?.[1]?.trim();
4591
+ if (named !== void 0 && named.length > 0) {
4592
+ paths.add(named);
4593
+ }
4594
+ }
4595
+ return paths.size === 0 || paths.size > MAX_TARGET_HINT_PATHS ? void 0 : [...paths];
4596
+ };
4597
+ var patchTextOf = (toolName, input) => {
4598
+ if (typeof input === "string") {
4599
+ return /^apply[_-]?patch$/i.test(toolName) ? input : void 0;
4600
+ }
4601
+ const record = asRecord5(input);
4602
+ if (/^apply[_-]?patch$/i.test(toolName)) {
4603
+ return nonEmptyString2(record?.patch) ?? nonEmptyString2(record?.input) ?? commandText(record);
4604
+ }
4605
+ const command = commandText(record);
4606
+ return command !== void 0 && /^\s*apply_patch\b/.test(command) ? command : void 0;
4607
+ };
4608
+ var codexTargetHint = (toolName, toolInput, cwd) => {
4609
+ const record = asRecord5(toolInput);
4610
+ const workdir = nonEmptyString2(record?.workdir);
4611
+ const base = workdir ?? cwd;
4612
+ const patch = patchTextOf(toolName, toolInput);
4613
+ if (patch !== void 0) {
4614
+ const paths = patchHeaderPaths(patch);
4615
+ return paths === void 0 ? void 0 : { source: "tool-path", paths, ...base === void 0 ? {} : { baseDirectory: base } };
4616
+ }
4617
+ if (workdir !== void 0) {
4618
+ return {
4619
+ source: "shell-cwd",
4620
+ paths: [workdir],
4621
+ ...cwd === void 0 ? {} : { baseDirectory: cwd }
4622
+ };
4623
+ }
4624
+ return cwd === void 0 ? void 0 : { source: "session-cwd", paths: [cwd] };
4625
+ };
4626
+
4188
4627
  // src/providers/codex/tool-kind.ts
4189
4628
  var PATTERNS = [
4190
4629
  [/^(apply[_-]?patch|patch)$/i, "write"],
@@ -4249,7 +4688,7 @@ var CODEX_CAPABILITIES = Object.freeze({
4249
4688
  // compaction callbacks do not. See `./delivery.ts` for which and why.
4250
4689
  deliveryIdentifier: "partial"
4251
4690
  });
4252
- var asRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
4691
+ var asRecord6 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
4253
4692
  var hasExactMarker = (payload) => {
4254
4693
  if (payload.codex_version !== void 0) {
4255
4694
  return true;
@@ -4342,7 +4781,7 @@ var outcomeFromToolResponse = (toolResponse) => {
4342
4781
  if (toolResponse === void 0) {
4343
4782
  return "unknown";
4344
4783
  }
4345
- const record = asRecord(toolResponse);
4784
+ const record = asRecord6(toolResponse);
4346
4785
  if (record === void 0) {
4347
4786
  return "ok";
4348
4787
  }
@@ -4414,6 +4853,10 @@ var parse = (input, context) => {
4414
4853
  context
4415
4854
  });
4416
4855
  const warnings = [];
4856
+ const targetHintFor = (toolName, toolInput) => {
4857
+ const hint = codexTargetHint(toolName, toolInput, payload.cwd);
4858
+ return hint === void 0 ? {} : { targetHint: hint };
4859
+ };
4417
4860
  const buildUsage = (usage) => {
4418
4861
  if (usage === void 0) {
4419
4862
  return void 0;
@@ -4458,6 +4901,7 @@ var parse = (input, context) => {
4458
4901
  toolName: payload.tool_name,
4459
4902
  toolKind: classifyCodexToolKind(payload.tool_name),
4460
4903
  occurredAt,
4904
+ ...targetHintFor(payload.tool_name, payload.tool_input),
4461
4905
  ...payload.tool_input === void 0 ? {} : {
4462
4906
  input: context.privacy.describeStructured({
4463
4907
  kind: "tool-input",
@@ -4484,6 +4928,7 @@ var parse = (input, context) => {
4484
4928
  outcome,
4485
4929
  permissionDecision,
4486
4930
  occurredAt,
4931
+ ...targetHintFor(payload.tool_name, payload.tool_input),
4487
4932
  ...payload.duration_ms === void 0 ? {} : { durationMillis: payload.duration_ms },
4488
4933
  ...payload.tool_response === void 0 ? {} : {
4489
4934
  output: context.privacy.describeStructured({
@@ -4566,10 +5011,12 @@ var parse = (input, context) => {
4566
5011
  break;
4567
5012
  }
4568
5013
  }
5014
+ const targetHints = factory.targetHints();
4569
5015
  return {
4570
5016
  status: "parsed",
4571
5017
  events: factory.events(),
4572
- ...warnings.length === 0 ? {} : { warnings }
5018
+ ...warnings.length === 0 ? {} : { warnings },
5019
+ ...targetHints.size === 0 ? {} : { targetHints }
4573
5020
  };
4574
5021
  };
4575
5022
  var hookResponse = () => SILENT_HOOK_RESPONSE;
@@ -4676,7 +5123,7 @@ var geminiCorrelationSeed = (input) => {
4676
5123
  };
4677
5124
 
4678
5125
  // src/providers/gemini/schema.ts
4679
- import { z as z18 } from "zod";
5126
+ import { z as z19 } from "zod";
4680
5127
  var GEMINI_HOOK_EVENT_NAMES = [
4681
5128
  "SessionStart",
4682
5129
  "SessionEnd",
@@ -4690,113 +5137,113 @@ var GEMINI_HOOK_EVENT_NAMES = [
4690
5137
  "PreCompress",
4691
5138
  "Notification"
4692
5139
  ];
4693
- var baseHookInputSchema = z18.object({
4694
- session_id: z18.string().min(1),
4695
- transcript_path: z18.string().optional(),
4696
- cwd: z18.string().optional(),
4697
- timestamp: z18.string().min(1).optional()
4698
- });
4699
- var llmMessageSchema = z18.object({
4700
- role: z18.enum(["user", "model", "system"]).optional(),
4701
- content: z18.union([z18.string(), z18.array(z18.unknown())]).optional()
5140
+ var baseHookInputSchema = z19.object({
5141
+ session_id: z19.string().min(1),
5142
+ transcript_path: z19.string().optional(),
5143
+ cwd: z19.string().optional(),
5144
+ timestamp: z19.string().min(1).optional()
5145
+ });
5146
+ var llmMessageSchema = z19.object({
5147
+ role: z19.enum(["user", "model", "system"]).optional(),
5148
+ content: z19.union([z19.string(), z19.array(z19.unknown())]).optional()
4702
5149
  }).loose();
4703
- var llmRequestConfigSchema = z18.object({
4704
- temperature: z18.number().optional(),
4705
- maxOutputTokens: z18.number().int().min(0).optional()
5150
+ var llmRequestConfigSchema = z19.object({
5151
+ temperature: z19.number().optional(),
5152
+ maxOutputTokens: z19.number().int().min(0).optional()
4706
5153
  }).loose();
4707
- var geminiLlmRequestSchema = z18.object({
4708
- model: z18.string().min(1).optional(),
4709
- messages: z18.array(llmMessageSchema).optional(),
5154
+ var geminiLlmRequestSchema = z19.object({
5155
+ model: z19.string().min(1).optional(),
5156
+ messages: z19.array(llmMessageSchema).optional(),
4710
5157
  config: llmRequestConfigSchema.optional(),
4711
- toolConfig: z18.unknown().optional()
5158
+ toolConfig: z19.unknown().optional()
4712
5159
  }).loose();
4713
- var geminiUsageMetadataSchema = z18.object({
4714
- promptTokenCount: z18.number().int().min(0).optional(),
4715
- cachedContentTokenCount: z18.number().int().min(0).optional(),
4716
- candidatesTokenCount: z18.number().int().min(0).optional(),
4717
- thoughtsTokenCount: z18.number().int().min(0).optional(),
4718
- totalTokenCount: z18.number().int().min(0).optional()
5160
+ var geminiUsageMetadataSchema = z19.object({
5161
+ promptTokenCount: z19.number().int().min(0).optional(),
5162
+ cachedContentTokenCount: z19.number().int().min(0).optional(),
5163
+ candidatesTokenCount: z19.number().int().min(0).optional(),
5164
+ thoughtsTokenCount: z19.number().int().min(0).optional(),
5165
+ totalTokenCount: z19.number().int().min(0).optional()
4719
5166
  }).loose();
4720
- var geminiCandidateSchema = z18.object({
4721
- content: z18.object({
4722
- role: z18.string().optional(),
4723
- parts: z18.array(z18.unknown()).optional()
5167
+ var geminiCandidateSchema = z19.object({
5168
+ content: z19.object({
5169
+ role: z19.string().optional(),
5170
+ parts: z19.array(z19.unknown()).optional()
4724
5171
  }).loose().optional(),
4725
- finishReason: z18.string().optional(),
4726
- index: z18.number().int().min(0).optional()
5172
+ finishReason: z19.string().optional(),
5173
+ index: z19.number().int().min(0).optional()
4727
5174
  }).loose();
4728
- var geminiLlmResponseSchema = z18.object({
5175
+ var geminiLlmResponseSchema = z19.object({
4729
5176
  /** Whole-response text, set by the translator from `getResponseText`. */
4730
- text: z18.string().optional(),
4731
- candidates: z18.array(geminiCandidateSchema).optional(),
5177
+ text: z19.string().optional(),
5178
+ candidates: z19.array(geminiCandidateSchema).optional(),
4732
5179
  usageMetadata: geminiUsageMetadataSchema.optional()
4733
5180
  }).loose();
4734
- var geminiMcpContextSchema = z18.object({
4735
- server_name: z18.string().optional(),
4736
- tool_name: z18.string().optional()
5181
+ var geminiMcpContextSchema = z19.object({
5182
+ server_name: z19.string().optional(),
5183
+ tool_name: z19.string().optional()
4737
5184
  }).loose();
4738
- var geminiToolResponseSchema = z18.object({
4739
- llmContent: z18.unknown().optional(),
4740
- returnDisplay: z18.unknown().optional(),
4741
- error: z18.unknown().optional()
5185
+ var geminiToolResponseSchema = z19.object({
5186
+ llmContent: z19.unknown().optional(),
5187
+ returnDisplay: z19.unknown().optional(),
5188
+ error: z19.unknown().optional()
4742
5189
  }).loose();
4743
5190
  var sessionStartInputSchema = baseHookInputSchema.extend({
4744
- hook_event_name: z18.literal("SessionStart"),
4745
- source: z18.enum(["startup", "resume", "clear"]).optional()
5191
+ hook_event_name: z19.literal("SessionStart"),
5192
+ source: z19.enum(["startup", "resume", "clear"]).optional()
4746
5193
  });
4747
5194
  var sessionEndInputSchema = baseHookInputSchema.extend({
4748
- hook_event_name: z18.literal("SessionEnd"),
4749
- reason: z18.enum(["exit", "clear", "logout", "prompt_input_exit", "other"]).optional()
5195
+ hook_event_name: z19.literal("SessionEnd"),
5196
+ reason: z19.enum(["exit", "clear", "logout", "prompt_input_exit", "other"]).optional()
4750
5197
  });
4751
5198
  var beforeAgentInputSchema = baseHookInputSchema.extend({
4752
- hook_event_name: z18.literal("BeforeAgent"),
4753
- prompt: z18.string().optional()
5199
+ hook_event_name: z19.literal("BeforeAgent"),
5200
+ prompt: z19.string().optional()
4754
5201
  });
4755
5202
  var afterAgentInputSchema = baseHookInputSchema.extend({
4756
- hook_event_name: z18.literal("AfterAgent"),
4757
- prompt: z18.string().optional(),
4758
- prompt_response: z18.string().optional(),
4759
- stop_hook_active: z18.boolean().optional()
5203
+ hook_event_name: z19.literal("AfterAgent"),
5204
+ prompt: z19.string().optional(),
5205
+ prompt_response: z19.string().optional(),
5206
+ stop_hook_active: z19.boolean().optional()
4760
5207
  });
4761
5208
  var beforeModelInputSchema = baseHookInputSchema.extend({
4762
- hook_event_name: z18.literal("BeforeModel"),
5209
+ hook_event_name: z19.literal("BeforeModel"),
4763
5210
  llm_request: geminiLlmRequestSchema
4764
5211
  });
4765
5212
  var afterModelInputSchema = baseHookInputSchema.extend({
4766
- hook_event_name: z18.literal("AfterModel"),
5213
+ hook_event_name: z19.literal("AfterModel"),
4767
5214
  llm_request: geminiLlmRequestSchema,
4768
5215
  llm_response: geminiLlmResponseSchema
4769
5216
  });
4770
5217
  var beforeToolSelectionInputSchema = baseHookInputSchema.extend({
4771
- hook_event_name: z18.literal("BeforeToolSelection"),
5218
+ hook_event_name: z19.literal("BeforeToolSelection"),
4772
5219
  llm_request: geminiLlmRequestSchema
4773
5220
  });
4774
5221
  var beforeToolInputSchema = baseHookInputSchema.extend({
4775
- hook_event_name: z18.literal("BeforeTool"),
4776
- tool_name: z18.string().min(1),
4777
- tool_input: z18.unknown().optional(),
5222
+ hook_event_name: z19.literal("BeforeTool"),
5223
+ tool_name: z19.string().min(1),
5224
+ tool_input: z19.unknown().optional(),
4778
5225
  mcp_context: geminiMcpContextSchema.optional(),
4779
- original_request_name: z18.string().min(1).optional()
5226
+ original_request_name: z19.string().min(1).optional()
4780
5227
  });
4781
5228
  var afterToolInputSchema = baseHookInputSchema.extend({
4782
- hook_event_name: z18.literal("AfterTool"),
4783
- tool_name: z18.string().min(1),
4784
- tool_input: z18.unknown().optional(),
5229
+ hook_event_name: z19.literal("AfterTool"),
5230
+ tool_name: z19.string().min(1),
5231
+ tool_input: z19.unknown().optional(),
4785
5232
  tool_response: geminiToolResponseSchema.optional(),
4786
5233
  mcp_context: geminiMcpContextSchema.optional(),
4787
- original_request_name: z18.string().min(1).optional()
5234
+ original_request_name: z19.string().min(1).optional()
4788
5235
  });
4789
5236
  var preCompressInputSchema = baseHookInputSchema.extend({
4790
- hook_event_name: z18.literal("PreCompress"),
4791
- trigger: z18.enum(["auto", "manual"]).optional()
5237
+ hook_event_name: z19.literal("PreCompress"),
5238
+ trigger: z19.enum(["auto", "manual"]).optional()
4792
5239
  });
4793
5240
  var notificationInputSchema = baseHookInputSchema.extend({
4794
- hook_event_name: z18.literal("Notification"),
4795
- notification_type: z18.string().optional(),
4796
- message: z18.string().optional(),
4797
- details: z18.unknown().optional()
5241
+ hook_event_name: z19.literal("Notification"),
5242
+ notification_type: z19.string().optional(),
5243
+ message: z19.string().optional(),
5244
+ details: z19.unknown().optional()
4798
5245
  });
4799
- var geminiHookInputSchema = z18.discriminatedUnion("hook_event_name", [
5246
+ var geminiHookInputSchema = z19.discriminatedUnion("hook_event_name", [
4800
5247
  sessionStartInputSchema,
4801
5248
  sessionEndInputSchema,
4802
5249
  beforeAgentInputSchema,
@@ -5241,7 +5688,7 @@ var normalizeUsageOrWarn = (usage, warnings) => {
5241
5688
  };
5242
5689
 
5243
5690
  // src/providers/antigravity/payload.ts
5244
- import { z as z19 } from "zod";
5691
+ import { z as z20 } from "zod";
5245
5692
  var ANTIGRAVITY_HOOK_EVENT_NAMES = [
5246
5693
  "PreInvocation",
5247
5694
  "PostInvocation",
@@ -5249,48 +5696,48 @@ var ANTIGRAVITY_HOOK_EVENT_NAMES = [
5249
5696
  "PostToolUse",
5250
5697
  "Stop"
5251
5698
  ];
5252
- var hookEventNameSchema = z19.enum(ANTIGRAVITY_HOOK_EVENT_NAMES);
5253
- var antigravityWeakShapeSchema = z19.object({ hookEventName: hookEventNameSchema }).passthrough();
5699
+ var hookEventNameSchema = z20.enum(ANTIGRAVITY_HOOK_EVENT_NAMES);
5700
+ var antigravityWeakShapeSchema = z20.object({ hookEventName: hookEventNameSchema }).passthrough();
5254
5701
  var commonFields2 = {
5255
- conversationId: z19.string().min(1),
5256
- workspacePaths: z19.array(z19.string().min(1)).max(64),
5257
- invocationNum: z19.number().int().min(0),
5702
+ conversationId: z20.string().min(1),
5703
+ workspacePaths: z20.array(z20.string().min(1)).max(64),
5704
+ invocationNum: z20.number().int().min(0),
5258
5705
  /** Never disclosed: a real filesystem path. Accepted, never propagated. */
5259
- transcriptPath: z19.string().min(1).optional(),
5706
+ transcriptPath: z20.string().min(1).optional(),
5260
5707
  /** Never disclosed: a real filesystem path. Accepted, never propagated. */
5261
- artifactDirectoryPath: z19.string().min(1).optional()
5708
+ artifactDirectoryPath: z20.string().min(1).optional()
5262
5709
  };
5263
- var preInvocationPayloadSchema = z19.object({
5264
- hookEventName: z19.literal("PreInvocation"),
5710
+ var preInvocationPayloadSchema = z20.object({
5711
+ hookEventName: z20.literal("PreInvocation"),
5265
5712
  ...commonFields2,
5266
- agentVersion: z19.string().min(1).optional()
5713
+ agentVersion: z20.string().min(1).optional()
5267
5714
  });
5268
- var postInvocationPayloadSchema = z19.object({
5269
- hookEventName: z19.literal("PostInvocation"),
5715
+ var postInvocationPayloadSchema = z20.object({
5716
+ hookEventName: z20.literal("PostInvocation"),
5270
5717
  ...commonFields2,
5271
- agentVersion: z19.string().min(1).optional()
5718
+ agentVersion: z20.string().min(1).optional()
5272
5719
  });
5273
- var preToolUsePayloadSchema3 = z19.object({
5274
- hookEventName: z19.literal("PreToolUse"),
5720
+ var preToolUsePayloadSchema3 = z20.object({
5721
+ hookEventName: z20.literal("PreToolUse"),
5275
5722
  ...commonFields2,
5276
- stepIdx: z19.number().int().min(0),
5277
- toolName: z19.string().min(1),
5278
- toolInput: z19.unknown().optional()
5723
+ stepIdx: z20.number().int().min(0),
5724
+ toolName: z20.string().min(1),
5725
+ toolInput: z20.unknown().optional()
5279
5726
  });
5280
- var postToolUsePayloadSchema3 = z19.object({
5281
- hookEventName: z19.literal("PostToolUse"),
5727
+ var postToolUsePayloadSchema3 = z20.object({
5728
+ hookEventName: z20.literal("PostToolUse"),
5282
5729
  ...commonFields2,
5283
- stepIdx: z19.number().int().min(0),
5284
- toolName: z19.string().min(1),
5285
- toolResponse: z19.unknown().optional(),
5286
- isError: z19.boolean().optional()
5730
+ stepIdx: z20.number().int().min(0),
5731
+ toolName: z20.string().min(1),
5732
+ toolResponse: z20.unknown().optional(),
5733
+ isError: z20.boolean().optional()
5287
5734
  });
5288
- var stopPayloadSchema3 = z19.object({
5289
- hookEventName: z19.literal("Stop"),
5735
+ var stopPayloadSchema3 = z20.object({
5736
+ hookEventName: z20.literal("Stop"),
5290
5737
  ...commonFields2,
5291
- fullyIdle: z19.boolean()
5738
+ fullyIdle: z20.boolean()
5292
5739
  });
5293
- var antigravityHookPayloadSchema = z19.discriminatedUnion("hookEventName", [
5740
+ var antigravityHookPayloadSchema = z20.discriminatedUnion("hookEventName", [
5294
5741
  preInvocationPayloadSchema,
5295
5742
  postInvocationPayloadSchema,
5296
5743
  preToolUsePayloadSchema3,
@@ -5604,15 +6051,15 @@ var describeProviderCatalog = (options = {}) => {
5604
6051
  };
5605
6052
 
5606
6053
  // src/runtime/ports.ts
5607
- import { z as z20 } from "zod";
5608
- var appliedDeliverySchema = z20.strictObject({
5609
- callbackId: z20.string().regex(/^[A-Za-z0-9_-]{1,128}$/),
6054
+ import { z as z21 } from "zod";
6055
+ var appliedDeliverySchema = z21.strictObject({
6056
+ callbackId: z21.string().regex(/^[A-Za-z0-9_-]{1,128}$/),
5610
6057
  /** How many of that delivery's observations are folded in, counted from one. */
5611
- applications: z20.number().int().min(1).max(4096)
6058
+ applications: z21.number().int().min(1).max(4096)
5612
6059
  });
5613
- var stateValueSchema = z20.discriminatedUnion("kind", [
5614
- z20.strictObject({
5615
- kind: z20.literal("usage-cumulative"),
6060
+ var stateValueSchema = z21.discriminatedUnion("kind", [
6061
+ z21.strictObject({
6062
+ kind: z21.literal("usage-cumulative"),
5616
6063
  usage: canonicalUsageSchema,
5617
6064
  /**
5618
6065
  * Optional: absent on every record written before this field existed, which
@@ -5621,22 +6068,22 @@ var stateValueSchema = z20.discriminatedUnion("kind", [
5621
6068
  */
5622
6069
  appliedDelivery: appliedDeliverySchema.optional()
5623
6070
  }),
5624
- z20.strictObject({
5625
- kind: z20.literal("sequence"),
6071
+ z21.strictObject({
6072
+ kind: z21.literal("sequence"),
5626
6073
  next: sequenceNumberSchema
5627
6074
  }),
5628
- z20.strictObject({
5629
- kind: z20.literal("attributes"),
6075
+ z21.strictObject({
6076
+ kind: z21.literal("attributes"),
5630
6077
  attributes: attributesSchema
5631
6078
  })
5632
6079
  ]);
5633
- var stateRecordSchema = z20.strictObject({
6080
+ var stateRecordSchema = z21.strictObject({
5634
6081
  /** Incremented on each write; lets callers detect lost updates. */
5635
- revision: z20.number().int().min(0),
6082
+ revision: z21.number().int().min(0),
5636
6083
  updatedAt: epochMillisSchema,
5637
6084
  value: stateValueSchema
5638
6085
  });
5639
- var logLevelSchema = z20.enum(["silent", "error", "warn", "info", "debug"]);
6086
+ var logLevelSchema = z21.enum(["silent", "error", "warn", "info", "debug"]);
5640
6087
  var LOG_LEVEL_RANK = Object.freeze({
5641
6088
  silent: 0,
5642
6089
  error: 1,
@@ -5908,7 +6355,94 @@ var resolveDeliveryIdentity = (input) => {
5908
6355
  };
5909
6356
 
5910
6357
  // src/runtime/hook.ts
5911
- import { z as z21 } from "zod";
6358
+ import { z as z22 } from "zod";
6359
+
6360
+ // src/runtime/target-resolution.ts
6361
+ import * as path from "path";
6362
+ var DEFAULT_TARGET_RESOLUTION_BUDGET_MILLIS = 50;
6363
+ var absolutePathsOf = (hint) => {
6364
+ const base = hint.baseDirectory !== void 0 && path.isAbsolute(hint.baseDirectory) ? hint.baseDirectory : void 0;
6365
+ const resolved = [];
6366
+ for (const candidate of hint.paths) {
6367
+ if (path.isAbsolute(candidate)) {
6368
+ resolved.push(path.resolve(candidate));
6369
+ } else if (base !== void 0) {
6370
+ resolved.push(path.resolve(base, candidate));
6371
+ } else {
6372
+ return void 0;
6373
+ }
6374
+ }
6375
+ return resolved;
6376
+ };
6377
+ var resolveHint = async (hint, locator, privacy) => {
6378
+ const paths = absolutePathsOf(hint);
6379
+ if (paths === void 0) {
6380
+ return void 0;
6381
+ }
6382
+ const located = await Promise.all(
6383
+ [...new Set(paths)].map((candidate) => locator.locate(candidate))
6384
+ );
6385
+ const [first] = located;
6386
+ if (first === void 0 || located.some((entry) => entry?.root !== first.root)) {
6387
+ return void 0;
6388
+ }
6389
+ const identity = deriveWorkspaceIdentity(
6390
+ privacy,
6391
+ { kind: "git-root", absolutePath: first.root },
6392
+ first.branch === void 0 ? {} : { vcsBranchName: first.branch }
6393
+ );
6394
+ if (identity.keySource !== "git-root") {
6395
+ return void 0;
6396
+ }
6397
+ const parsed = workspaceTargetSchema.safeParse({
6398
+ workspaceId: identity.workspaceId,
6399
+ ...identity.vcsBranchName === void 0 ? {} : { vcsBranchName: identity.vcsBranchName },
6400
+ source: hint.source
6401
+ });
6402
+ return parsed.success ? parsed.data : void 0;
6403
+ };
6404
+ var resolveEventTargets = async (input) => {
6405
+ const pending = input.events.filter(
6406
+ (event3) => (event3.type === "tool.start" || event3.type === "tool.end") && input.hints.has(event3.eventId)
6407
+ );
6408
+ if (pending.length === 0) {
6409
+ return { events: input.events, resolved: 0, timedOut: false };
6410
+ }
6411
+ const targets = /* @__PURE__ */ new Map();
6412
+ const work = Promise.all(
6413
+ pending.map(async (event3) => {
6414
+ const hint = input.hints.get(event3.eventId);
6415
+ if (hint === void 0) {
6416
+ return;
6417
+ }
6418
+ try {
6419
+ const target = await resolveHint(hint, input.locator, input.privacy);
6420
+ if (target !== void 0) {
6421
+ targets.set(event3.eventId, target);
6422
+ }
6423
+ } catch {
6424
+ }
6425
+ })
6426
+ ).then(() => "done");
6427
+ let timer;
6428
+ const deadline = new Promise((resolve5) => {
6429
+ timer = setTimeout(() => resolve5("timeout"), Math.max(0, input.budgetMillis));
6430
+ timer.unref?.();
6431
+ });
6432
+ const finished = await Promise.race([work, deadline]);
6433
+ if (timer !== void 0) {
6434
+ clearTimeout(timer);
6435
+ }
6436
+ const settled = new Map(targets);
6437
+ const events = input.events.map((event3) => {
6438
+ const target = settled.get(event3.eventId);
6439
+ if (target === void 0 || event3.type !== "tool.start" && event3.type !== "tool.end") {
6440
+ return event3;
6441
+ }
6442
+ return { ...event3, target };
6443
+ });
6444
+ return { events, resolved: settled.size, timedOut: finished === "timeout" };
6445
+ };
5912
6446
 
5913
6447
  // src/state/async-lock.ts
5914
6448
  var LockWaitTimeoutError = class extends Error {
@@ -5990,7 +6524,7 @@ var withOptionalSessionLock = async (store, sessionId, fn, options) => {
5990
6524
  };
5991
6525
 
5992
6526
  // src/runtime/hook.ts
5993
- var usageScopeSchema = z21.enum(["session", "generation", "subagent"]);
6527
+ var usageScopeSchema = z22.enum(["session", "generation", "subagent"]);
5994
6528
  var classifyDurability = (input) => {
5995
6529
  if (!input.attempted) {
5996
6530
  return "nothing-to-deliver";
@@ -6232,7 +6766,7 @@ var createOtelHook = (deps) => {
6232
6766
  }
6233
6767
  const facts = collectContentFacts(event3);
6234
6768
  const offending = facts.find(
6235
- (fact) => fact.disclosure !== expectedDisclosure || !isContentFactConsistent(fact)
6769
+ (fact) => !isUnavailableContentFact(fact) && (fact.disclosure !== expectedDisclosure || !isContentFactConsistent(fact))
6236
6770
  );
6237
6771
  if (offending !== void 0) {
6238
6772
  reject(
@@ -6529,7 +7063,12 @@ var createOtelHook = (deps) => {
6529
7063
  );
6530
7064
  }
6531
7065
  }
6532
- return { kind: "ready", batch: batch2, dropped: screened.dropped };
7066
+ return {
7067
+ kind: "ready",
7068
+ batch: batch2,
7069
+ dropped: screened.dropped,
7070
+ ...parsed.targetHints === void 0 ? {} : { targetHints: parsed.targetHints }
7071
+ };
6533
7072
  };
6534
7073
  let prepared;
6535
7074
  try {
@@ -6574,7 +7113,24 @@ var createOtelHook = (deps) => {
6574
7113
  if (prepared.kind === "early") {
6575
7114
  return prepared.outcome;
6576
7115
  }
6577
- const { batch, dropped } = prepared;
7116
+ const { dropped } = prepared;
7117
+ let batch = prepared.batch;
7118
+ if (!suppress && deps.worktreeLocator !== void 0 && prepared.targetHints !== void 0 && prepared.targetHints.size > 0) {
7119
+ const targeted = await resolveEventTargets({
7120
+ events: batch,
7121
+ hints: prepared.targetHints,
7122
+ locator: deps.worktreeLocator,
7123
+ privacy,
7124
+ budgetMillis: deps.targetResolutionBudgetMillis ?? DEFAULT_TARGET_RESOLUTION_BUDGET_MILLIS
7125
+ });
7126
+ batch = targeted.events;
7127
+ if (targeted.timedOut) {
7128
+ logger.debug("worktree target resolution exceeded its budget", {
7129
+ "provider.id": detection.providerId,
7130
+ "target.resolved": targeted.resolved
7131
+ });
7132
+ }
7133
+ }
6578
7134
  let emitted = 0;
6579
7135
  let exportRejected = 0;
6580
7136
  if (!suppress && batch.length > 0) {
@@ -6723,6 +7279,120 @@ var buildErrorEvents = (diagnostics, identity, sequenceBase, ids, privacy) => {
6723
7279
  return events;
6724
7280
  };
6725
7281
 
7282
+ // src/runtime/git-worktree.ts
7283
+ import { open, stat } from "fs/promises";
7284
+ import * as path2 from "path";
7285
+ var MAX_WORKTREE_WALK_DEPTH = 128;
7286
+ var MAX_GIT_FILE_BYTES = 4096;
7287
+ var MAX_CACHE_ENTRIES = 1024;
7288
+ var DEFAULT_WORKTREE_CACHE_TTL_MILLIS = 5e3;
7289
+ var MAX_BRANCH_NAME_LENGTH = 255;
7290
+ var ABSENT = Object.freeze({ kind: "absent" });
7291
+ var INVALID = Object.freeze({ kind: "invalid" });
7292
+ var readBounded = async (filePath) => {
7293
+ let handle;
7294
+ try {
7295
+ handle = await open(filePath, "r");
7296
+ const buffer = Buffer.alloc(MAX_GIT_FILE_BYTES);
7297
+ const { bytesRead } = await handle.read(buffer, 0, MAX_GIT_FILE_BYTES, 0);
7298
+ return buffer.subarray(0, bytesRead).toString("utf8");
7299
+ } catch {
7300
+ return void 0;
7301
+ } finally {
7302
+ await handle?.close().catch(() => void 0);
7303
+ }
7304
+ };
7305
+ var parseHeadBranch = (head) => {
7306
+ const line = head.split(/\r?\n/, 1)[0]?.trim() ?? "";
7307
+ const match = /^ref:\s*refs\/heads\/(.+)$/.exec(line);
7308
+ const branch = match?.[1];
7309
+ 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.
7310
+ [...branch].some((char) => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127) || /[ ~^:?*[\\]/.test(branch)) {
7311
+ return void 0;
7312
+ }
7313
+ return branch;
7314
+ };
7315
+ var parseGitDirFile = (content, worktreeRoot) => {
7316
+ const line = content.split(/\r?\n/, 1)[0]?.trim() ?? "";
7317
+ const target = line.startsWith("gitdir:") ? line.slice("gitdir:".length).trim() : void 0;
7318
+ if (target === void 0 || target.length === 0 || target.includes("\0")) {
7319
+ return void 0;
7320
+ }
7321
+ return path2.resolve(worktreeRoot, target);
7322
+ };
7323
+ var probeDirectory = async (directory) => {
7324
+ const dotGit = path2.join(directory, ".git");
7325
+ let info;
7326
+ try {
7327
+ info = await stat(dotGit);
7328
+ } catch {
7329
+ return ABSENT;
7330
+ }
7331
+ let gitDir;
7332
+ if (info.isDirectory()) {
7333
+ gitDir = dotGit;
7334
+ } else if (info.isFile()) {
7335
+ const content = await readBounded(dotGit);
7336
+ gitDir = content === void 0 ? void 0 : parseGitDirFile(content, directory);
7337
+ }
7338
+ if (gitDir === void 0) {
7339
+ return INVALID;
7340
+ }
7341
+ const head = await readBounded(path2.join(gitDir, "HEAD"));
7342
+ if (head === void 0) {
7343
+ return INVALID;
7344
+ }
7345
+ const branch = parseHeadBranch(head);
7346
+ return {
7347
+ kind: "worktree",
7348
+ located: { root: directory, ...branch === void 0 ? {} : { branch } }
7349
+ };
7350
+ };
7351
+ var createFilesystemWorktreeLocator = (options = {}) => {
7352
+ const now = options.monotonicMillis ?? (() => performance.now());
7353
+ const ttl = options.cacheTtlMillis ?? DEFAULT_WORKTREE_CACHE_TTL_MILLIS;
7354
+ const cache = /* @__PURE__ */ new Map();
7355
+ const cachedProbe = (directory) => {
7356
+ const hit = cache.get(directory);
7357
+ const at = now();
7358
+ if (hit !== void 0 && at - hit.at <= ttl) {
7359
+ return hit.probe;
7360
+ }
7361
+ if (cache.size >= MAX_CACHE_ENTRIES) {
7362
+ cache.clear();
7363
+ }
7364
+ const probe = probeDirectory(directory).catch(() => INVALID);
7365
+ cache.set(directory, { at, probe });
7366
+ return probe;
7367
+ };
7368
+ const locate = async (absolutePath) => {
7369
+ try {
7370
+ if (!path2.isAbsolute(absolutePath) || absolutePath.includes("\0")) {
7371
+ return void 0;
7372
+ }
7373
+ let directory = path2.resolve(absolutePath);
7374
+ for (let depth = 0; depth < MAX_WORKTREE_WALK_DEPTH; depth += 1) {
7375
+ const probe = await cachedProbe(directory);
7376
+ if (probe.kind === "worktree") {
7377
+ return probe.located;
7378
+ }
7379
+ if (probe.kind === "invalid") {
7380
+ return void 0;
7381
+ }
7382
+ const parent = path2.dirname(directory);
7383
+ if (parent === directory) {
7384
+ return void 0;
7385
+ }
7386
+ directory = parent;
7387
+ }
7388
+ return void 0;
7389
+ } catch {
7390
+ return void 0;
7391
+ }
7392
+ };
7393
+ return { locate };
7394
+ };
7395
+
6726
7396
  // src/lifecycle/dedup.ts
6727
7397
  import { randomBytes } from "crypto";
6728
7398
 
@@ -6954,12 +7624,83 @@ import {
6954
7624
  ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,
6955
7625
  ATTR_GEN_AI_USAGE_INPUT_TOKENS,
6956
7626
  ATTR_GEN_AI_USAGE_OUTPUT_TOKENS,
6957
- ATTR_GEN_AI_USAGE_REASONING_OUTPUT_TOKENS,
6958
- ATTR_SESSION_ID
7627
+ ATTR_GEN_AI_USAGE_REASONING_OUTPUT_TOKENS
6959
7628
  } from "@opentelemetry/semantic-conventions/incubating";
6960
7629
 
6961
7630
  // src/version.ts
6962
- var VERSION = "0.2.0";
7631
+ var VERSION = "0.4.1";
7632
+
7633
+ // src/telemetry/export-identity.ts
7634
+ import { ATTR_SESSION_ID } from "@opentelemetry/semantic-conventions/incubating";
7635
+ var ATTR_TRACE_ID = "trace_id";
7636
+ var ATTR_SPAN_ID = "span_id";
7637
+ var ATTR_PARENT_SPAN_ID = "parent_span_id";
7638
+ var ATTR_OTELHOOK_SESSION_ID = "otelhook.session.id";
7639
+ var ATTR_GEN_AI_CONVERSATION_ID = "gen_ai.conversation.id";
7640
+ var TRACE_ID_HEX_PATTERN = /^[0-9a-f]{32}$/;
7641
+ var SPAN_ID_HEX_PATTERN = /^[0-9a-f]{16}$/;
7642
+ var ATTR_OTELHOOK_INVOCATION_ID = "otelhook.invocation.id";
7643
+ var ATTR_OTELHOOK_PROVIDER_ID = "otelhook.provider.id";
7644
+ var ATTR_OTELHOOK_PROVIDER_VERSION = "otelhook.provider.version";
7645
+ var ATTR_OTELHOOK_WORKSPACE_ID = "otelhook.workspace.id";
7646
+ var HAR_SESSION_KEY = "har.session_key";
7647
+ var ATTR_OTELHOOK_SUBAGENT_ID = "otelhook.subagent.id";
7648
+ var ATTR_VCS_REF_HEAD_NAME = "vcs.ref.head.name";
7649
+ var ATTR_OTELHOOK_TARGET_WORKSPACE_ID = "otelhook.target.workspace.id";
7650
+ var ATTR_OTELHOOK_TARGET_SOURCE = "otelhook.target.source";
7651
+ var ATTR_OTELHOOK_USAGE_TEMPORALITY = "otelhook.usage.temporality";
7652
+ var targetAttributes = (event3) => {
7653
+ if (event3.type !== "tool.start" && event3.type !== "tool.end" || event3.target === void 0) {
7654
+ return {};
7655
+ }
7656
+ const { target } = event3;
7657
+ return {
7658
+ [ATTR_OTELHOOK_TARGET_WORKSPACE_ID]: target.workspaceId,
7659
+ [ATTR_OTELHOOK_TARGET_SOURCE]: target.source,
7660
+ ...target.vcsBranchName === void 0 ? {} : { [ATTR_VCS_REF_HEAD_NAME]: target.vcsBranchName }
7661
+ };
7662
+ };
7663
+ var usageTemporalityAttributes = (usage) => usage === void 0 ? {} : { [ATTR_OTELHOOK_USAGE_TEMPORALITY]: usage.temporality };
7664
+ var isPrimitiveAttribute = (value) => typeof value === "string" || typeof value === "number" || typeof value === "boolean";
7665
+ var passthroughHarAttributes = (resource) => {
7666
+ const attributes = {};
7667
+ for (const [key, value] of Object.entries(resource.attributes)) {
7668
+ if (key.startsWith("har.") && isPrimitiveAttribute(value)) {
7669
+ attributes[key] = value;
7670
+ }
7671
+ }
7672
+ return attributes;
7673
+ };
7674
+ var resolveExportedSessionId = (eventSessionId, resource) => {
7675
+ const har = resource.attributes[HAR_SESSION_KEY];
7676
+ if (typeof har === "string") {
7677
+ const trimmed = har.trim();
7678
+ if (trimmed.length > 0) {
7679
+ return { sessionId: trimmed, providerSessionId: eventSessionId };
7680
+ }
7681
+ }
7682
+ return { sessionId: eventSessionId, providerSessionId: eventSessionId };
7683
+ };
7684
+ var hexTraceAttributes = (ids) => ({
7685
+ ...TRACE_ID_HEX_PATTERN.test(ids.traceId) ? { [ATTR_TRACE_ID]: ids.traceId } : {},
7686
+ ...SPAN_ID_HEX_PATTERN.test(ids.spanId) ? { [ATTR_SPAN_ID]: ids.spanId } : {},
7687
+ ...ids.parentSpanId !== void 0 && SPAN_ID_HEX_PATTERN.test(ids.parentSpanId) ? { [ATTR_PARENT_SPAN_ID]: ids.parentSpanId } : {}
7688
+ });
7689
+ var exportIdentityAttributes = (event3, resource, ids) => {
7690
+ const { sessionId, providerSessionId } = resolveExportedSessionId(event3.sessionId, resource);
7691
+ return {
7692
+ [ATTR_SESSION_ID]: sessionId,
7693
+ [ATTR_OTELHOOK_SESSION_ID]: providerSessionId,
7694
+ [ATTR_GEN_AI_CONVERSATION_ID]: providerSessionId,
7695
+ [ATTR_OTELHOOK_INVOCATION_ID]: event3.invocationId,
7696
+ [ATTR_OTELHOOK_PROVIDER_ID]: event3.provenance.providerId,
7697
+ ...event3.provenance.providerVersion === void 0 ? {} : { [ATTR_OTELHOOK_PROVIDER_VERSION]: event3.provenance.providerVersion },
7698
+ [ATTR_OTELHOOK_WORKSPACE_ID]: event3.workspace.workspaceId,
7699
+ ...event3.subagentId === void 0 ? {} : { [ATTR_OTELHOOK_SUBAGENT_ID]: event3.subagentId },
7700
+ ...passthroughHarAttributes(resource),
7701
+ ...hexTraceAttributes(ids)
7702
+ };
7703
+ };
6963
7704
 
6964
7705
  // src/telemetry/semconv.ts
6965
7706
  var SCOPE_NAME = "@osfactory/otel-hook";
@@ -6967,10 +7708,6 @@ var DEFAULT_INSTRUMENTATION_SCOPE = Object.freeze({
6967
7708
  name: SCOPE_NAME,
6968
7709
  version: VERSION
6969
7710
  });
6970
- var ATTR_OTELHOOK_INVOCATION_ID = "otelhook.invocation.id";
6971
- var ATTR_OTELHOOK_PROVIDER_ID = "otelhook.provider.id";
6972
- var ATTR_OTELHOOK_PROVIDER_VERSION = "otelhook.provider.version";
6973
- var ATTR_OTELHOOK_WORKSPACE_ID = "otelhook.workspace.id";
6974
7711
  var ATTR_OTELHOOK_SPAN_PAIRED = "otelhook.span.paired";
6975
7712
  var ATTR_OTELHOOK_SPAN_PAIRING = "otelhook.span.pairing";
6976
7713
  var ATTR_OTELHOOK_SPAN_ORPHAN = "otelhook.span.orphan";
@@ -6981,6 +7718,7 @@ var ATTR_OTELHOOK_DELEGATION_DEPTH = "otelhook.delegation_depth";
6981
7718
  var ATTR_OTELHOOK_COMPACTION_TRIGGER = "otelhook.compaction.trigger";
6982
7719
  var ATTR_OTELHOOK_AGENT_NAME = "otelhook.agent.name";
6983
7720
  var ATTR_OTELHOOK_AGENT_VERSION = "otelhook.agent.version";
7721
+ var ATTR_OTELHOOK_GENERATION_ID = "otelhook.generation.id";
6984
7722
  var FIELD_SEPARATOR = "\0";
6985
7723
  var digestHex = (parts, length) => createHash3("sha256").update(parts.join(FIELD_SEPARATOR)).digest("hex").slice(0, length);
6986
7724
  var MAX_RECOVERED_START_ATTRIBUTES = 16;
@@ -7047,8 +7785,10 @@ var startOnlySpanAttributes = (event3) => {
7047
7785
  };
7048
7786
  // `toolName` and `toolCallId` are on both tool edges, so they are not
7049
7787
  // start-only and persisting them would just pad every record.
7788
+ // The target is carried forward too: an end-only process may see a payload
7789
+ // with less to go on (no tool input), and the start's evidence still holds.
7050
7790
  case "tool.start":
7051
- return { [ATTR_OTELHOOK_TOOL_KIND]: event3.toolKind };
7791
+ return { [ATTR_OTELHOOK_TOOL_KIND]: event3.toolKind, ...targetAttributes(event3) };
7052
7792
  case "subagent.start":
7053
7793
  return { [ATTR_OTELHOOK_DELEGATION_DEPTH]: event3.delegationDepth };
7054
7794
  default:
@@ -7068,13 +7808,7 @@ var outcomeStatus = (outcome) => {
7068
7808
  }
7069
7809
  return { code: SpanStatusCode.ERROR, message: outcome };
7070
7810
  };
7071
- var identityAttributes = (event3) => ({
7072
- [ATTR_SESSION_ID]: event3.sessionId,
7073
- [ATTR_OTELHOOK_INVOCATION_ID]: event3.invocationId,
7074
- [ATTR_OTELHOOK_PROVIDER_ID]: event3.provenance.providerId,
7075
- ...event3.provenance.providerVersion === void 0 ? {} : { [ATTR_OTELHOOK_PROVIDER_VERSION]: event3.provenance.providerVersion },
7076
- [ATTR_OTELHOOK_WORKSPACE_ID]: event3.workspace.workspaceId
7077
- });
7811
+ var identityAttributes = (event3, resource, ids) => exportIdentityAttributes(event3, resource, ids);
7078
7812
  var usageAttributes = (usage, resetDetected) => {
7079
7813
  if (usage === void 0) {
7080
7814
  return {};
@@ -7085,9 +7819,52 @@ var usageAttributes = (usage, resetDetected) => {
7085
7819
  [ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS]: usage.cachedInputTokens,
7086
7820
  [ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS]: usage.cacheCreationInputTokens,
7087
7821
  [ATTR_GEN_AI_USAGE_REASONING_OUTPUT_TOKENS]: usage.reasoningOutputTokens,
7822
+ ...usageTemporalityAttributes(usage),
7088
7823
  ...resetDetected ? { [ATTR_OTELHOOK_RESET_DETECTED]: true } : {}
7089
7824
  };
7090
7825
  };
7826
+ var TARGET_SOURCE_RANK = Object.freeze({
7827
+ "tool-path": 3,
7828
+ "shell-cwd": 2,
7829
+ "session-cwd": 1
7830
+ });
7831
+ var TARGET_KEYS = [
7832
+ ATTR_OTELHOOK_TARGET_WORKSPACE_ID,
7833
+ ATTR_OTELHOOK_TARGET_SOURCE,
7834
+ ATTR_VCS_REF_HEAD_NAME
7835
+ ];
7836
+ var pickTarget = (attributes) => {
7837
+ const picked = {};
7838
+ for (const key of TARGET_KEYS) {
7839
+ if (attributes[key] !== void 0) {
7840
+ picked[key] = attributes[key];
7841
+ }
7842
+ }
7843
+ return picked;
7844
+ };
7845
+ var withoutTarget = (attributes) => {
7846
+ const rest = { ...attributes };
7847
+ for (const key of TARGET_KEYS) {
7848
+ delete rest[key];
7849
+ }
7850
+ return rest;
7851
+ };
7852
+ var rankOf = (candidate) => {
7853
+ const source = candidate[ATTR_OTELHOOK_TARGET_SOURCE];
7854
+ return typeof source === "string" && Object.hasOwn(TARGET_SOURCE_RANK, source) ? TARGET_SOURCE_RANK[source] ?? 0 : 0;
7855
+ };
7856
+ var strongestTarget = (candidates) => {
7857
+ let best = {};
7858
+ let bestRank = 0;
7859
+ for (const candidate of candidates) {
7860
+ const rank = rankOf(candidate);
7861
+ if (rank > 0 && rank >= bestRank) {
7862
+ best = candidate;
7863
+ bestRank = rank;
7864
+ }
7865
+ }
7866
+ return best;
7867
+ };
7091
7868
  var buildSpanContext = (traceId, spanId) => ({
7092
7869
  traceId,
7093
7870
  spanId,
@@ -7158,7 +7935,11 @@ var buildLifecycleSpan = (plan, resource, scope) => {
7158
7935
  let kind = SpanKind.INTERNAL;
7159
7936
  let status = { code: SpanStatusCode.UNSET };
7160
7937
  let attributes = {
7161
- ...identityAttributes(anchor),
7938
+ ...identityAttributes(anchor, resource, {
7939
+ traceId,
7940
+ spanId,
7941
+ ...parentSpanId === void 0 ? {} : { parentSpanId }
7942
+ }),
7162
7943
  ...resolved.recovered,
7163
7944
  [ATTR_OTELHOOK_SPAN_PAIRED]: resolved.pairing !== "unpaired",
7164
7945
  [ATTR_OTELHOOK_SPAN_PAIRING]: resolved.pairing,
@@ -7194,6 +7975,9 @@ var buildLifecycleSpan = (plan, resource, scope) => {
7194
7975
  ...model?.vendor === void 0 ? {} : { [ATTR_GEN_AI_SYSTEM]: model.vendor },
7195
7976
  ...start?.model?.modelId === void 0 ? {} : { [ATTR_GEN_AI_REQUEST_MODEL]: start.model.modelId },
7196
7977
  ...end?.model?.modelId === void 0 ? {} : { [ATTR_GEN_AI_RESPONSE_MODEL]: end.model.modelId },
7978
+ // The provider's own id for this unit of work (Cursor generation,
7979
+ // Codex turn): the key a consumer stores a usage observation under.
7980
+ [ATTR_OTELHOOK_GENERATION_ID]: group.ref.scopeKey,
7197
7981
  ...end?.outcome === void 0 ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.outcome },
7198
7982
  ...usageAttributes(end?.usage, false)
7199
7983
  };
@@ -7207,11 +7991,17 @@ var buildLifecycleSpan = (plan, resource, scope) => {
7207
7991
  name = `tool ${toolName}`;
7208
7992
  kind = SpanKind.CLIENT;
7209
7993
  attributes = {
7210
- ...attributes,
7994
+ // Target keys are re-chosen below as one unit, never mixed across edges.
7995
+ ...withoutTarget(attributes),
7211
7996
  [ATTR_GEN_AI_TOOL_NAME]: toolName,
7212
7997
  [ATTR_GEN_AI_TOOL_CALL_ID]: start?.toolCallId ?? end?.toolCallId ?? group.ref.scopeKey,
7213
7998
  ...start?.toolKind === void 0 ? {} : { [ATTR_OTELHOOK_TOOL_KIND]: start.toolKind },
7214
- ...end?.outcome === void 0 ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.outcome }
7999
+ ...end?.outcome === void 0 ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.outcome },
8000
+ ...strongestTarget([
8001
+ pickTarget(resolved.recovered),
8002
+ start === void 0 ? {} : targetAttributes(start),
8003
+ end === void 0 ? {} : targetAttributes(end)
8004
+ ])
7215
8005
  };
7216
8006
  status = outcomeStatus(end?.outcome);
7217
8007
  break;
@@ -7253,7 +8043,15 @@ var buildStandaloneSpan = (event3, resource, scope) => {
7253
8043
  const traceId = deriveTraceId(providerId, event3.sessionId);
7254
8044
  const spanId = deriveStandaloneSpanId(providerId, event3.sessionId, event3.type, event3.eventId);
7255
8045
  const parent = parentScopeRefOf(event3);
7256
- let attributes = { ...identityAttributes(event3), [ATTR_OTELHOOK_SPAN_PAIRED]: true };
8046
+ const parentSpanId = parent === void 0 ? void 0 : deriveSpanId(providerId, event3.sessionId, parent);
8047
+ let attributes = {
8048
+ ...identityAttributes(event3, resource, {
8049
+ traceId,
8050
+ spanId,
8051
+ ...parentSpanId === void 0 ? {} : { parentSpanId }
8052
+ }),
8053
+ [ATTR_OTELHOOK_SPAN_PAIRED]: true
8054
+ };
7257
8055
  let status = { code: SpanStatusCode.UNSET };
7258
8056
  let name = event3.type;
7259
8057
  switch (event3.type) {
@@ -7291,7 +8089,7 @@ var buildStandaloneSpan = (event3, resource, scope) => {
7291
8089
  status,
7292
8090
  traceId,
7293
8091
  spanId,
7294
- ...parent === void 0 ? {} : { parentSpanId: deriveSpanId(providerId, event3.sessionId, parent) },
8092
+ ...parentSpanId === void 0 ? {} : { parentSpanId },
7295
8093
  resource,
7296
8094
  instrumentationScope: scope
7297
8095
  });
@@ -7390,13 +8188,20 @@ var canonicalEventTraceIdentities = (events, options = {}) => {
7390
8188
  const groupKey = layout.groupOf.get(event3.eventId);
7391
8189
  const plan = groupKey === void 0 ? void 0 : plans.get(groupKey);
7392
8190
  if (plan === void 0) {
8191
+ const parent2 = parentScopeRefOf(event3);
7393
8192
  identities.set(event3.eventId, {
7394
8193
  traceId: deriveTraceId(providerId, event3.sessionId),
7395
- spanId: deriveStandaloneSpanId(providerId, event3.sessionId, event3.type, event3.eventId)
8194
+ spanId: deriveStandaloneSpanId(providerId, event3.sessionId, event3.type, event3.eventId),
8195
+ ...parent2 === void 0 ? {} : { parentSpanId: deriveSpanId(providerId, event3.sessionId, parent2) }
7396
8196
  });
7397
8197
  continue;
7398
8198
  }
7399
- identities.set(event3.eventId, { traceId: plan.traceId, spanId: plan.spanId });
8199
+ const parent = plan.correlation?.parent ?? parentScopeRefOf(event3);
8200
+ identities.set(event3.eventId, {
8201
+ traceId: plan.traceId,
8202
+ spanId: plan.spanId,
8203
+ ...parent === void 0 ? {} : { parentSpanId: deriveSpanId(providerId, event3.sessionId, parent) }
8204
+ });
7400
8205
  }
7401
8206
  return identities;
7402
8207
  };
@@ -8027,8 +8832,8 @@ var createBoundedMemoryStateStore = (options) => {
8027
8832
 
8028
8833
  // src/state/filesystem-store.ts
8029
8834
  import { randomBytes as randomBytes2 } from "crypto";
8030
- import { mkdir, open, readFile, readdir, rename, unlink, writeFile } from "fs/promises";
8031
- import * as path from "path";
8835
+ import { mkdir, open as open2, readFile, readdir, rename, unlink, writeFile } from "fs/promises";
8836
+ import * as path3 from "path";
8032
8837
 
8033
8838
  // src/state/keys.ts
8034
8839
  import { createHash as createHash4 } from "crypto";
@@ -8048,8 +8853,8 @@ var keyDigest = (key) => createHash4("sha256").update(key, "utf8").digest("hex")
8048
8853
 
8049
8854
  // src/state/filesystem-store.ts
8050
8855
  var isErrnoException = (thrown, code) => thrown instanceof Error && thrown.code === code;
8051
- var sleep = (millis) => new Promise((resolve3) => {
8052
- const timer = setTimeout(resolve3, millis);
8856
+ var sleep = (millis) => new Promise((resolve5) => {
8857
+ const timer = setTimeout(resolve5, millis);
8053
8858
  timer.unref?.();
8054
8859
  });
8055
8860
  var wrapFsError = (thrown, operation) => {
@@ -8060,10 +8865,10 @@ var wrapFsError = (thrown, operation) => {
8060
8865
  };
8061
8866
  var createFilesystemStateStore = (options) => {
8062
8867
  const [providerSegment, installationSegment] = namespaceSegments(options);
8063
- const baseDir = path.join(options.rootDir, providerSegment, installationSegment);
8064
- const recordsDir = path.join(baseDir, "records");
8065
- const quarantineDir = path.join(baseDir, "quarantine");
8066
- const locksDir = path.join(baseDir, "locks");
8868
+ const baseDir = path3.join(options.rootDir, providerSegment, installationSegment);
8869
+ const recordsDir = path3.join(baseDir, "records");
8870
+ const quarantineDir = path3.join(baseDir, "quarantine");
8871
+ const locksDir = path3.join(baseDir, "locks");
8067
8872
  const lockTimeoutMillis = options.lockTimeoutMillis ?? 5e3;
8068
8873
  const lockStaleMillis = options.lockStaleMillis ?? 3e4;
8069
8874
  const lockPollIntervalMillis = options.lockPollIntervalMillis ?? 25;
@@ -8087,11 +8892,11 @@ var createFilesystemStateStore = (options) => {
8087
8892
  throw wrapFsError(thrown, "ensure-dirs");
8088
8893
  }
8089
8894
  };
8090
- const recordPath = (key) => path.join(recordsDir, `${keyDigest(key)}.json`);
8091
- const tempPath = (key) => path.join(recordsDir, `.tmp-${keyDigest(key)}-${randomBytes2(6).toString("hex")}.json`);
8092
- const lockPath = (sessionId) => path.join(locksDir, `${sanitizeSegment(sessionId)}.lock`);
8895
+ const recordPath = (key) => path3.join(recordsDir, `${keyDigest(key)}.json`);
8896
+ const tempPath = (key) => path3.join(recordsDir, `.tmp-${keyDigest(key)}-${randomBytes2(6).toString("hex")}.json`);
8897
+ const lockPath = (sessionId) => path3.join(locksDir, `${sanitizeSegment(sessionId)}.lock`);
8093
8898
  const quarantine = async (filePath, key, reason) => {
8094
- const dest = path.join(quarantineDir, `${options.clock.now()}-${keyDigest(key)}-${reason}.json`);
8899
+ const dest = path3.join(quarantineDir, `${options.clock.now()}-${keyDigest(key)}-${reason}.json`);
8095
8900
  try {
8096
8901
  await rename(filePath, dest);
8097
8902
  } catch {
@@ -8155,7 +8960,7 @@ var createFilesystemStateStore = (options) => {
8155
8960
  const startedAt = options.clock.monotonicMillis();
8156
8961
  for (; ; ) {
8157
8962
  try {
8158
- const handle = await open(filePath, "wx");
8963
+ const handle = await open2(filePath, "wx");
8159
8964
  try {
8160
8965
  await handle.writeFile(JSON.stringify({ pid: process.pid, acquiredAt: options.clock.now() }));
8161
8966
  } finally {
@@ -8223,7 +9028,7 @@ var createFilesystemStateStore = (options) => {
8223
9028
  }
8224
9029
  let raw;
8225
9030
  try {
8226
- raw = await readFile(path.join(recordsDir, entry), "utf8");
9031
+ raw = await readFile(path3.join(recordsDir, entry), "utf8");
8227
9032
  } catch {
8228
9033
  continue;
8229
9034
  }
@@ -8276,7 +9081,7 @@ var createFilesystemStateStore = (options) => {
8276
9081
  continue;
8277
9082
  }
8278
9083
  scanned += 1;
8279
- const filePath = path.join(recordsDir, entry);
9084
+ const filePath = path3.join(recordsDir, entry);
8280
9085
  try {
8281
9086
  const raw = await readFile(filePath, "utf8");
8282
9087
  const envelope = JSON.parse(raw);
@@ -8296,7 +9101,7 @@ var createFilesystemStateStore = (options) => {
8296
9101
  lockEntries = [];
8297
9102
  }
8298
9103
  for (const entry of lockEntries) {
8299
- const filePath = path.join(locksDir, entry);
9104
+ const filePath = path3.join(locksDir, entry);
8300
9105
  try {
8301
9106
  const raw = await readFile(filePath, "utf8");
8302
9107
  const parsed = JSON.parse(raw);
@@ -8315,13 +9120,13 @@ var createFilesystemStateStore = (options) => {
8315
9120
  // src/telemetry/spool-queue.ts
8316
9121
  import { randomBytes as randomBytes3 } from "crypto";
8317
9122
  import { mkdir as mkdir2, readFile as readFile2, readdir as readdir2, rename as rename2, unlink as unlink2, writeFile as writeFile2 } from "fs/promises";
8318
- import * as path2 from "path";
9123
+ import * as path4 from "path";
8319
9124
  var DEFAULT_DRAIN_MAX_BATCHES = 20;
8320
9125
  var isErrnoException2 = (thrown, code) => thrown instanceof Error && thrown.code === code;
8321
9126
  var createSpoolQueue = (options) => {
8322
9127
  const [providerSegment, installationSegment] = namespaceSegments(options);
8323
- const queueDir = path2.join(options.rootDir, providerSegment, installationSegment, options.queueName);
8324
- const corruptDir = path2.join(
9128
+ const queueDir = path4.join(options.rootDir, providerSegment, installationSegment, options.queueName);
9129
+ const corruptDir = path4.join(
8325
9130
  options.rootDir,
8326
9131
  providerSegment,
8327
9132
  installationSegment,
@@ -8367,8 +9172,8 @@ var createSpoolQueue = (options) => {
8367
9172
  return { spooled: false, reason: "capacity-exceeded" };
8368
9173
  }
8369
9174
  const fileName = `${String(options.clock.now()).padStart(16, "0")}-${randomBytes3(6).toString("hex")}.json`;
8370
- const target = path2.join(queueDir, fileName);
8371
- const tmp = path2.join(queueDir, `.tmp-${randomBytes3(6).toString("hex")}.json`);
9175
+ const target = path4.join(queueDir, fileName);
9176
+ const tmp = path4.join(queueDir, `.tmp-${randomBytes3(6).toString("hex")}.json`);
8372
9177
  await writeFile2(tmp, JSON.stringify(batch), "utf8");
8373
9178
  await rename2(tmp, target);
8374
9179
  return { spooled: true };
@@ -8386,7 +9191,7 @@ var createSpoolQueue = (options) => {
8386
9191
  if (fileName === void 0) {
8387
9192
  break;
8388
9193
  }
8389
- const filePath = path2.join(queueDir, fileName);
9194
+ const filePath = path4.join(queueDir, fileName);
8390
9195
  const quarantine = async (rejection) => {
8391
9196
  quarantined += 1;
8392
9197
  options.logger?.error("durable spool quarantined an unusable batch", {
@@ -8395,7 +9200,7 @@ var createSpoolQueue = (options) => {
8395
9200
  "spool.queue": options.queueName
8396
9201
  });
8397
9202
  try {
8398
- await rename2(filePath, path2.join(corruptDir, fileName));
9203
+ await rename2(filePath, path4.join(corruptDir, fileName));
8399
9204
  } catch {
8400
9205
  await unlink2(filePath).catch(() => void 0);
8401
9206
  }
@@ -8686,8 +9491,8 @@ var createOtlpTraceSink = (options) => {
8686
9491
  timeoutMillis: options.exporter.timeoutMillis
8687
9492
  });
8688
9493
  let shutdownCompleted = false;
8689
- const exportSpans = (spans) => new Promise((resolve3) => {
8690
- exporter.export([...spans], (result) => resolve3(result));
9494
+ const exportSpans = (spans) => new Promise((resolve5) => {
9495
+ exporter.export([...spans], (result) => resolve5(result));
8691
9496
  });
8692
9497
  const toSpoolBatch = (spans) => ({
8693
9498
  providerId: options.providerId,
@@ -8811,9 +9616,10 @@ import {
8811
9616
  ATTR_GEN_AI_SYSTEM as ATTR_GEN_AI_SYSTEM2,
8812
9617
  ATTR_GEN_AI_TOOL_CALL_ID as ATTR_GEN_AI_TOOL_CALL_ID2,
8813
9618
  ATTR_GEN_AI_TOOL_NAME as ATTR_GEN_AI_TOOL_NAME2,
9619
+ ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS as ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS2,
9620
+ ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS as ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS2,
8814
9621
  ATTR_GEN_AI_USAGE_INPUT_TOKENS as ATTR_GEN_AI_USAGE_INPUT_TOKENS2,
8815
- ATTR_GEN_AI_USAGE_OUTPUT_TOKENS as ATTR_GEN_AI_USAGE_OUTPUT_TOKENS2,
8816
- ATTR_SESSION_ID as ATTR_SESSION_ID2
9622
+ ATTR_GEN_AI_USAGE_OUTPUT_TOKENS as ATTR_GEN_AI_USAGE_OUTPUT_TOKENS2
8817
9623
  } from "@opentelemetry/semantic-conventions/incubating";
8818
9624
  var LOG_MAPPING_VERSION = 1;
8819
9625
  var LOG_SIGNALS = [
@@ -8833,10 +9639,6 @@ var MCP_TOOL_NAME_PATTERN = /^mcp__/i;
8833
9639
  var MAX_LOG_RECORDS_PER_EVENT = 64;
8834
9640
  var MAX_LOG_RECORDS_PER_BATCH = 2048;
8835
9641
  var MAX_LOG_BODY_CHARACTERS = 8192;
8836
- var ATTR_OTELHOOK_INVOCATION_ID2 = "otelhook.invocation.id";
8837
- var ATTR_OTELHOOK_PROVIDER_ID2 = "otelhook.provider.id";
8838
- var ATTR_OTELHOOK_PROVIDER_VERSION2 = "otelhook.provider.version";
8839
- var ATTR_OTELHOOK_WORKSPACE_ID2 = "otelhook.workspace.id";
8840
9642
  var ATTR_OTELHOOK_EVENT_TYPE = "otelhook.event.type";
8841
9643
  var ATTR_OTELHOOK_EVENT_ID = "otelhook.event.id";
8842
9644
  var ATTR_OTELHOOK_EVENT_SEQUENCE = "otelhook.event.sequence";
@@ -8852,7 +9654,7 @@ var ATTR_OTELHOOK_AGENT_VERSION2 = "otelhook.agent.version";
8852
9654
  var ATTR_OTELHOOK_SESSION_KIND = "otelhook.session.kind";
8853
9655
  var ATTR_OTELHOOK_PROMPT_SOURCE = "otelhook.prompt.source";
8854
9656
  var ATTR_OTELHOOK_PROMPT_TURN_INDEX = "otelhook.prompt.turn_index";
8855
- var ATTR_OTELHOOK_GENERATION_ID = "otelhook.generation.id";
9657
+ var ATTR_OTELHOOK_GENERATION_ID2 = "otelhook.generation.id";
8856
9658
  var ATTR_OTELHOOK_STOP_REASON = "otelhook.generation.stop_reason";
8857
9659
  var ATTR_OTELHOOK_COMPACTION_TRIGGER2 = "otelhook.compaction.trigger";
8858
9660
  var ATTR_OTELHOOK_CONTEXT_TOKENS_BEFORE = "otelhook.compaction.context_tokens_before";
@@ -8988,13 +9790,7 @@ var SEVERITY_TEXT = Object.freeze({
8988
9790
  [SeverityNumber.WARN]: "WARN",
8989
9791
  [SeverityNumber.ERROR]: "ERROR"
8990
9792
  });
8991
- var identityAttributes2 = (event3) => ({
8992
- [ATTR_SESSION_ID2]: event3.sessionId,
8993
- [ATTR_OTELHOOK_INVOCATION_ID2]: event3.invocationId,
8994
- [ATTR_OTELHOOK_PROVIDER_ID2]: event3.provenance.providerId,
8995
- ...event3.provenance.providerVersion === void 0 ? {} : { [ATTR_OTELHOOK_PROVIDER_VERSION2]: event3.provenance.providerVersion },
8996
- [ATTR_OTELHOOK_WORKSPACE_ID2]: event3.workspace.workspaceId
8997
- });
9793
+ var identityAttributes2 = (event3, resource, ids) => exportIdentityAttributes(event3, resource, ids);
8998
9794
  var eventAttributes = (event3) => {
8999
9795
  switch (event3.type) {
9000
9796
  case "session.start":
@@ -9017,14 +9813,14 @@ var eventAttributes = (event3) => {
9017
9813
  case "generation.start":
9018
9814
  return {
9019
9815
  [ATTR_GEN_AI_OPERATION_NAME2]: "chat",
9020
- [ATTR_OTELHOOK_GENERATION_ID]: event3.generationId,
9816
+ [ATTR_OTELHOOK_GENERATION_ID2]: event3.generationId,
9021
9817
  [ATTR_GEN_AI_REQUEST_MODEL2]: event3.model.modelId,
9022
9818
  ...event3.model.vendor === void 0 ? {} : { [ATTR_GEN_AI_SYSTEM2]: event3.model.vendor }
9023
9819
  };
9024
9820
  case "generation.end":
9025
9821
  return {
9026
9822
  [ATTR_GEN_AI_OPERATION_NAME2]: "chat",
9027
- [ATTR_OTELHOOK_GENERATION_ID]: event3.generationId,
9823
+ [ATTR_OTELHOOK_GENERATION_ID2]: event3.generationId,
9028
9824
  [ATTR_GEN_AI_RESPONSE_MODEL2]: event3.model.modelId,
9029
9825
  ...event3.model.vendor === void 0 ? {} : { [ATTR_GEN_AI_SYSTEM2]: event3.model.vendor },
9030
9826
  [ATTR_OTELHOOK_OUTCOME2]: event3.outcome,
@@ -9036,14 +9832,16 @@ var eventAttributes = (event3) => {
9036
9832
  [ATTR_GEN_AI_TOOL_NAME2]: event3.toolName,
9037
9833
  [ATTR_GEN_AI_TOOL_CALL_ID2]: event3.toolCallId,
9038
9834
  [ATTR_OTELHOOK_TOOL_KIND2]: event3.toolKind,
9039
- ...event3.generationId === void 0 ? {} : { [ATTR_OTELHOOK_GENERATION_ID]: event3.generationId }
9835
+ ...event3.generationId === void 0 ? {} : { [ATTR_OTELHOOK_GENERATION_ID2]: event3.generationId },
9836
+ ...targetAttributes(event3)
9040
9837
  };
9041
9838
  case "tool.end":
9042
9839
  return {
9043
9840
  [ATTR_GEN_AI_TOOL_NAME2]: event3.toolName,
9044
9841
  [ATTR_GEN_AI_TOOL_CALL_ID2]: event3.toolCallId,
9045
9842
  [ATTR_OTELHOOK_OUTCOME2]: event3.outcome,
9046
- ...event3.permissionDecision === void 0 ? {} : { [ATTR_OTELHOOK_TOOL_PERMISSION]: event3.permissionDecision }
9843
+ ...event3.permissionDecision === void 0 ? {} : { [ATTR_OTELHOOK_TOOL_PERMISSION]: event3.permissionDecision },
9844
+ ...targetAttributes(event3)
9047
9845
  };
9048
9846
  case "subagent.start":
9049
9847
  return {
@@ -9075,7 +9873,10 @@ var eventAttributes = (event3) => {
9075
9873
  };
9076
9874
  var usageAttributes2 = (usage) => usage === void 0 ? {} : {
9077
9875
  [ATTR_GEN_AI_USAGE_INPUT_TOKENS2]: usage.inputTokens,
9078
- [ATTR_GEN_AI_USAGE_OUTPUT_TOKENS2]: usage.outputTokens
9876
+ [ATTR_GEN_AI_USAGE_OUTPUT_TOKENS2]: usage.outputTokens,
9877
+ [ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS2]: usage.cachedInputTokens,
9878
+ [ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS2]: usage.cacheCreationInputTokens,
9879
+ ...usageTemporalityAttributes(usage)
9079
9880
  };
9080
9881
  var contentFactsOf = (event3) => {
9081
9882
  switch (event3.type) {
@@ -9096,6 +9897,9 @@ var contentFactsOf = (event3) => {
9096
9897
  }
9097
9898
  };
9098
9899
  var discloseBody = (fact, policy) => {
9900
+ if (fact.text === void 0 && fact.characterLength === 0) {
9901
+ return { metadataOnly: true };
9902
+ }
9099
9903
  if (fact.text === void 0) {
9100
9904
  return { withheld: "privacy-policy" };
9101
9905
  }
@@ -9111,14 +9915,14 @@ var discloseBody = (fact, policy) => {
9111
9915
  var contentAttributes = (fact, body) => ({
9112
9916
  [ATTR_CONTENT_KIND]: fact.kind,
9113
9917
  ...fact.role === void 0 ? {} : { [ATTR_CONTENT_ROLE]: fact.role },
9114
- [ATTR_CONTENT_DISCLOSURE]: fact.disclosure,
9918
+ [ATTR_CONTENT_DISCLOSURE]: "metadataOnly" in body ? "metadata_only" : fact.disclosure,
9115
9919
  [ATTR_CONTENT_CHARACTER_LENGTH]: fact.characterLength,
9116
9920
  [ATTR_CONTENT_BYTE_LENGTH]: fact.byteLength,
9117
9921
  [ATTR_CONTENT_HASH]: fact.contentHash,
9118
9922
  [ATTR_CONTENT_TRUNCATED]: fact.truncated,
9119
9923
  [ATTR_CONTENT_SECRETS_REDACTED]: fact.secretsRedacted,
9120
9924
  ...fact.label === void 0 ? {} : { [ATTR_CONTENT_LABEL]: fact.label },
9121
- ..."withheld" in body ? { [ATTR_CONTENT_WITHHELD]: body.withheld } : { [ATTR_CONTENT_BODY_TRUNCATED]: body.truncated }
9925
+ ..."withheld" in body ? { [ATTR_CONTENT_WITHHELD]: body.withheld } : "metadataOnly" in body ? {} : { [ATTR_CONTENT_BODY_TRUNCATED]: body.truncated }
9122
9926
  });
9123
9927
  var buildRecord = (input) => {
9124
9928
  const severityNumber = severityFor(input.event);
@@ -9138,7 +9942,11 @@ var buildRecord = (input) => {
9138
9942
  resource: input.resource,
9139
9943
  instrumentationScope: input.scope,
9140
9944
  attributes: {
9141
- ...identityAttributes2(input.event),
9945
+ ...identityAttributes2(input.event, input.resource, {
9946
+ traceId: input.spanContext.traceId,
9947
+ spanId: input.spanContext.spanId,
9948
+ ...input.parentSpanId === void 0 ? {} : { parentSpanId: input.parentSpanId }
9949
+ }),
9142
9950
  [ATTR_OTELHOOK_EVENT_TYPE]: input.event.type,
9143
9951
  [ATTR_OTELHOOK_EVENT_ID]: input.event.eventId,
9144
9952
  [ATTR_OTELHOOK_EVENT_SEQUENCE]: input.event.sequence,
@@ -9180,8 +9988,9 @@ var canonicalEventsToLogRecords = (events, options) => {
9180
9988
  buildRecord({
9181
9989
  event: event3,
9182
9990
  signal: logSignalOf(event3),
9183
- attributes: shared,
9991
+ attributes: event3.type === "generation.end" ? { ...shared, [ATTR_CONTENT_KIND]: "response", [ATTR_CONTENT_DISCLOSURE]: "metadata_only" } : shared,
9184
9992
  spanContext,
9993
+ ...identity.parentSpanId === void 0 ? {} : { parentSpanId: identity.parentSpanId },
9185
9994
  resource: options.resource,
9186
9995
  scope
9187
9996
  })
@@ -9201,8 +10010,9 @@ var canonicalEventsToLogRecords = (events, options) => {
9201
10010
  event: event3,
9202
10011
  signal: logSignalOf(event3, fact.kind),
9203
10012
  attributes: { ...shared, ...contentAttributes(fact, body) },
9204
- ..."withheld" in body ? {} : { body: body.text },
10013
+ ..."text" in body ? { body: body.text } : {},
9205
10014
  spanContext,
10015
+ ...identity.parentSpanId === void 0 ? {} : { parentSpanId: identity.parentSpanId },
9206
10016
  resource: options.resource,
9207
10017
  scope
9208
10018
  })
@@ -9458,8 +10268,8 @@ var createOtlpLogSink = (options) => {
9458
10268
  timeoutMillis: options.exporter.timeoutMillis
9459
10269
  });
9460
10270
  let shutdownCompleted = false;
9461
- const exportRecords = (records) => new Promise((resolve3) => {
9462
- exporter.export([...records], (result) => resolve3(result));
10271
+ const exportRecords = (records) => new Promise((resolve5) => {
10272
+ exporter.export([...records], (result) => resolve5(result));
9463
10273
  });
9464
10274
  const toSpoolBatch = (records) => ({
9465
10275
  providerId: options.providerId,
@@ -9638,8 +10448,8 @@ var DEFAULT_FLUSH_TIMEOUT_MILLIS = 2e3;
9638
10448
  var DEFAULT_STATE_LOCK_TIMEOUT_MILLIS = 1e3;
9639
10449
  var DEFAULT_LIFECYCLE_MAX_AGE_MILLIS = 24 * 60 * 60 * 1e3;
9640
10450
  var DEFAULT_STALE_CLAIM_MILLIS2 = 6e4;
9641
- var delay = (millis) => new Promise((resolve3) => {
9642
- const timer = setTimeout(() => resolve3("timeout"), millis);
10451
+ var delay = (millis) => new Promise((resolve5) => {
10452
+ const timer = setTimeout(() => resolve5("timeout"), millis);
9643
10453
  timer.unref?.();
9644
10454
  });
9645
10455
  var containsSessionEnd = (events) => events.some((event3) => event3.type === "session.end");
@@ -9751,7 +10561,10 @@ var createHookRuntime = (options) => {
9751
10561
  ids,
9752
10562
  privacy,
9753
10563
  logger,
9754
- installationId: options.installationId
10564
+ installationId: options.installationId,
10565
+ ...options.worktreeLocator === null ? {} : {
10566
+ worktreeLocator: options.worktreeLocator ?? createFilesystemWorktreeLocator({ monotonicMillis: () => clock.monotonicMillis() })
10567
+ }
9755
10568
  };
9756
10569
  const hook = createOtelHook({ ...hookDeps, sink });
9757
10570
  const deduplicator = createCallbackDeduplicator({ stateStore, clock });
@@ -10440,7 +11253,7 @@ var CURSOR_UNREGISTERED_HOOK_EVENTS = Object.freeze({
10440
11253
  afterShellExecution: "the same shell call also fires postToolUse, which duplicates this tool end and \u2014 unlike this callback \u2014 carries both a tool_use_id and a success/failure signal",
10441
11254
  beforeMCPExecution: "an MCP call also fires preToolUse/postToolUse, which additionally carry tool_use_id; registering this one duplicates the tool call",
10442
11255
  afterMCPExecution: "the same MCP call also fires postToolUse, which duplicates this tool end and, unlike this callback, reports a success/failure signal",
10443
- beforeReadFile: "no completion callback exists for it, so a tool.start emitted here would never close",
11256
+ beforeReadFile: "an agent read also fires preToolUse/postToolUse, so registering it by default would report one read twice; opt in with --event for its file_path target evidence",
10444
11257
  subagentStart: "subagentStop carries no subagent id to pair with, so no closable delegation lifecycle can be produced",
10445
11258
  subagentStop: "it carries no subagent id, so it cannot be paired with the subagentStart it ends",
10446
11259
  beforeTabFileRead: "a Tab (inline-completion) hook, not an agent-session hook; not modelled by this adapter",
@@ -10880,7 +11693,7 @@ var SUPPORTED_REGISTRATION_PROVIDER_IDS = Object.freeze(
10880
11693
  );
10881
11694
 
10882
11695
  // src/install/scopes.ts
10883
- import * as path3 from "path";
11696
+ import * as path5 from "path";
10884
11697
  var REGISTRATION_SCOPES = Object.freeze([
10885
11698
  "global",
10886
11699
  "project"
@@ -10948,15 +11761,15 @@ var PROVIDERS_WITH_VERIFIED_LOCATION = Object.freeze([
10948
11761
  var findInstallLocation = (providerId, scope) => PROVIDER_INSTALL_LOCATIONS.find(
10949
11762
  (entry) => entry.providerId === providerId && entry.scope === scope
10950
11763
  );
10951
- var resolveInstallPath = (location, roots) => path3.resolve(
11764
+ var resolveInstallPath = (location, roots) => path5.resolve(
10952
11765
  location.scope === "global" ? roots.homeDir : roots.projectDir,
10953
11766
  ...location.segments
10954
11767
  );
10955
11768
 
10956
11769
  // src/install/document.ts
10957
11770
  import { randomBytes as randomBytes4 } from "crypto";
10958
- import { chmod, mkdir as mkdir3, open as open2, readFile as readFile3, rename as rename3, stat, unlink as unlink3 } from "fs/promises";
10959
- import * as path4 from "path";
11771
+ import { chmod, mkdir as mkdir3, open as open3, readFile as readFile3, rename as rename3, stat as stat2, unlink as unlink3 } from "fs/promises";
11772
+ import * as path6 from "path";
10960
11773
  var DEFAULT_DOCUMENT_FORMAT = Object.freeze({
10961
11774
  indent: " ",
10962
11775
  eol: "\n",
@@ -11006,8 +11819,8 @@ var readJsonDocument = async (filePath) => {
11006
11819
  }
11007
11820
  };
11008
11821
  var RENAME_RETRY_DELAYS_MILLIS = [10, 25, 50, 100];
11009
- var delay2 = (millis) => new Promise((resolve3) => {
11010
- setTimeout(resolve3, millis);
11822
+ var delay2 = (millis) => new Promise((resolve5) => {
11823
+ setTimeout(resolve5, millis);
11011
11824
  });
11012
11825
  var renameWithRetry = async (from, to) => {
11013
11826
  for (let attempt = 0; ; attempt += 1) {
@@ -11027,15 +11840,15 @@ var renameWithRetry = async (from, to) => {
11027
11840
  var NEW_DOCUMENT_MODE = 384;
11028
11841
  var TEMPORARY_DOCUMENT_MODE = 384;
11029
11842
  var writeDocumentAtomically = async (filePath, contents) => {
11030
- const directory = path4.dirname(filePath);
11843
+ const directory = path6.dirname(filePath);
11031
11844
  await mkdir3(directory, { recursive: true });
11032
- const temporary = path4.join(
11845
+ const temporary = path6.join(
11033
11846
  directory,
11034
- `.${path4.basename(filePath)}.${randomBytes4(6).toString("hex")}.tmp`
11847
+ `.${path6.basename(filePath)}.${randomBytes4(6).toString("hex")}.tmp`
11035
11848
  );
11036
11849
  let existingMode;
11037
11850
  try {
11038
- existingMode = (await stat(filePath)).mode & 4095;
11851
+ existingMode = (await stat2(filePath)).mode & 4095;
11039
11852
  } catch (thrown) {
11040
11853
  if (!isErrnoException3(thrown, "ENOENT")) {
11041
11854
  throw thrown;
@@ -11043,7 +11856,7 @@ var writeDocumentAtomically = async (filePath, contents) => {
11043
11856
  }
11044
11857
  const targetMode = existingMode ?? NEW_DOCUMENT_MODE;
11045
11858
  try {
11046
- const handle = await open2(temporary, "wx", TEMPORARY_DOCUMENT_MODE);
11859
+ const handle = await open3(temporary, "wx", TEMPORARY_DOCUMENT_MODE);
11047
11860
  try {
11048
11861
  await handle.writeFile(contents, "utf8");
11049
11862
  await handle.sync();
@@ -11060,12 +11873,12 @@ var writeDocumentAtomically = async (filePath, contents) => {
11060
11873
 
11061
11874
  // src/install/file-lock.ts
11062
11875
  import { randomBytes as randomBytes5 } from "crypto";
11063
- import { mkdir as mkdir4, open as open3, readFile as readFile4, rename as rename4, stat as stat2, unlink as unlink4 } from "fs/promises";
11064
- import * as path5 from "path";
11876
+ import { mkdir as mkdir4, open as open4, readFile as readFile4, rename as rename4, stat as stat3, unlink as unlink4 } from "fs/promises";
11877
+ import * as path7 from "path";
11065
11878
  var FileLockTimeoutError = class extends Error {
11066
11879
  constructor(lockPath, timeoutMillis) {
11067
11880
  super(
11068
- `timed out after ${String(timeoutMillis)}ms waiting for the lock on ${path5.basename(lockPath)}`
11881
+ `timed out after ${String(timeoutMillis)}ms waiting for the lock on ${path7.basename(lockPath)}`
11069
11882
  );
11070
11883
  this.name = "FileLockTimeoutError";
11071
11884
  }
@@ -11104,8 +11917,8 @@ var releaseIfOwned = async (lockPath, token) => {
11104
11917
  await unlink4(tombstone).catch(() => void 0);
11105
11918
  return true;
11106
11919
  };
11107
- var delay3 = (millis) => new Promise((resolve3) => {
11108
- setTimeout(resolve3, millis);
11920
+ var delay3 = (millis) => new Promise((resolve5) => {
11921
+ setTimeout(resolve5, millis);
11109
11922
  });
11110
11923
  var isStale = async (lockPath, clock, staleMillis) => {
11111
11924
  let raw;
@@ -11125,7 +11938,7 @@ var isStale = async (lockPath, clock, staleMillis) => {
11125
11938
  } catch {
11126
11939
  }
11127
11940
  try {
11128
- const stats = await stat2(lockPath);
11941
+ const stats = await stat3(lockPath);
11129
11942
  return { stale: clock.now() - stats.mtimeMs > staleMillis };
11130
11943
  } catch (thrown) {
11131
11944
  return { stale: !isErrnoException4(thrown, "ENOENT") };
@@ -11137,12 +11950,12 @@ var withFileLock = async (filePath, options, fn) => {
11137
11950
  const pollIntervalMillis = options.pollIntervalMillis ?? 25;
11138
11951
  const lockPath = lockPathFor(filePath);
11139
11952
  const startedAt = options.clock.monotonicMillis();
11140
- await mkdir4(path5.dirname(filePath), { recursive: true });
11953
+ await mkdir4(path7.dirname(filePath), { recursive: true });
11141
11954
  for (; ; ) {
11142
11955
  const token = randomBytes5(16).toString("hex");
11143
11956
  let acquired = false;
11144
11957
  try {
11145
- const handle = await open3(lockPath, "wx", 384);
11958
+ const handle = await open4(lockPath, "wx", 384);
11146
11959
  try {
11147
11960
  const contents = {
11148
11961
  token,
@@ -11185,7 +11998,7 @@ var withFileLock = async (filePath, options, fn) => {
11185
11998
 
11186
11999
  // src/install/lifecycle.ts
11187
12000
  import { readFile as readFile5 } from "fs/promises";
11188
- import * as path6 from "path";
12001
+ import * as path8 from "path";
11189
12002
  var defaultHookCommand = (providerId) => `otel-hook run --provider ${providerId}`;
11190
12003
  var unsupportedOutcome = (providerId, scope, reason) => ({
11191
12004
  providerId,
@@ -11202,7 +12015,7 @@ var unsupportedOutcome = (providerId, scope, reason) => ({
11202
12015
  var resolveTarget = (providerId, scope, request) => {
11203
12016
  if (request.configFile !== void 0) {
11204
12017
  return {
11205
- configPath: path6.resolve(request.configFile),
12018
+ configPath: path8.resolve(request.configFile),
11206
12019
  evidence: "path supplied by the caller with --settings-file"
11207
12020
  };
11208
12021
  }
@@ -11219,14 +12032,14 @@ var resolveTarget = (providerId, scope, request) => {
11219
12032
  };
11220
12033
  };
11221
12034
  var codexFeatureNote = async (configPath) => {
11222
- const tomlPath = path6.join(path6.dirname(configPath), "config.toml");
12035
+ const tomlPath = path8.join(path8.dirname(configPath), "config.toml");
11223
12036
  let raw;
11224
12037
  try {
11225
12038
  raw = await readFile5(tomlPath, "utf8");
11226
12039
  } catch {
11227
12040
  return void 0;
11228
12041
  }
11229
- return readCodexHooksFeatureFlag(raw) === "disabled" ? `${path6.basename(tomlPath)} sets [features] hooks = false; registered hooks will not fire until that is removed` : void 0;
12042
+ return readCodexHooksFeatureFlag(raw) === "disabled" ? `${path8.basename(tomlPath)} sets [features] hooks = false; registered hooks will not fire until that is removed` : void 0;
11230
12043
  };
11231
12044
  var readState = async (configPath) => {
11232
12045
  const read = await readJsonDocument(configPath);
@@ -11238,12 +12051,12 @@ var readState = async (configPath) => {
11238
12051
  case "unparseable":
11239
12052
  return {
11240
12053
  status: "blocked",
11241
- problem: `${path6.basename(configPath)} is not well-formed JSON (${read.detail}); it was left untouched`
12054
+ problem: `${path8.basename(configPath)} is not well-formed JSON (${read.detail}); it was left untouched`
11242
12055
  };
11243
12056
  case "unreadable":
11244
12057
  return {
11245
12058
  status: "failed",
11246
- problem: `${path6.basename(configPath)} could not be read (${read.detail})`
12059
+ problem: `${path8.basename(configPath)} could not be read (${read.detail})`
11247
12060
  };
11248
12061
  }
11249
12062
  };
@@ -11355,7 +12168,7 @@ var runOneTarget = async (providerId, scope, request, command) => {
11355
12168
  missingEvents: [],
11356
12169
  notes,
11357
12170
  problems: planned.conflicts.map(
11358
- (conflict) => `${path6.basename(configPath)} has an unexpected shape at ${conflict.location}: ${conflict.detail}; it was left untouched`
12171
+ (conflict) => `${path8.basename(configPath)} has an unexpected shape at ${conflict.location}: ${conflict.detail}; it was left untouched`
11359
12172
  )
11360
12173
  };
11361
12174
  }
@@ -11366,7 +12179,7 @@ var runOneTarget = async (providerId, scope, request, command) => {
11366
12179
  changed: false,
11367
12180
  registeredEvents: [],
11368
12181
  missingEvents: [],
11369
- notes: [...notes, `${path6.basename(configPath)} does not exist; nothing to remove`],
12182
+ notes: [...notes, `${path8.basename(configPath)} does not exist; nothing to remove`],
11370
12183
  problems: []
11371
12184
  };
11372
12185
  }
@@ -11409,7 +12222,7 @@ var runOneTarget = async (providerId, scope, request, command) => {
11409
12222
  missingEvents: [],
11410
12223
  notes,
11411
12224
  problems: [
11412
- `could not write ${path6.basename(configPath)} (${thrown instanceof Error ? thrown.name : typeof thrown})`
12225
+ `could not write ${path8.basename(configPath)} (${thrown instanceof Error ? thrown.name : typeof thrown})`
11413
12226
  ]
11414
12227
  };
11415
12228
  }
@@ -11436,7 +12249,7 @@ var runOneTarget = async (providerId, scope, request, command) => {
11436
12249
  missingEvents: [],
11437
12250
  notes,
11438
12251
  problems: [
11439
- thrown instanceof Error ? `${path6.basename(configPath)}: ${thrown.message}` : `${path6.basename(configPath)}: the configuration file could not be locked`
12252
+ thrown instanceof Error ? `${path8.basename(configPath)}: ${thrown.message}` : `${path8.basename(configPath)}: the configuration file could not be locked`
11440
12253
  ]
11441
12254
  };
11442
12255
  }
@@ -11563,6 +12376,8 @@ export {
11563
12376
  DEFAULT_PRIVACY_POLICY,
11564
12377
  DEFAULT_SECRET_KEY_PATTERNS,
11565
12378
  DEFAULT_SECRET_VALUE_PATTERNS,
12379
+ DEFAULT_TARGET_RESOLUTION_BUDGET_MILLIS,
12380
+ DEFAULT_WORKTREE_CACHE_TTL_MILLIS,
11566
12381
  DELIVERY_COMPONENT_PATTERN,
11567
12382
  DELIVERY_GAP_REASON_PATTERN,
11568
12383
  DELIVERY_IDENTIFIER_SUMMARY,
@@ -11597,6 +12412,9 @@ export {
11597
12412
  MAX_RESOURCE_ATTRIBUTES,
11598
12413
  MAX_RESOURCE_ATTRIBUTE_KEY_LENGTH,
11599
12414
  MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH,
12415
+ MAX_TARGET_HINT_PATHS,
12416
+ MAX_TARGET_PATH_LENGTH,
12417
+ MAX_WORKTREE_WALK_DEPTH,
11600
12418
  MCP_TOOL_NAME_PATTERN,
11601
12419
  NO_LOG_CONTENT,
11602
12420
  OtelHookError,
@@ -11614,6 +12432,7 @@ export {
11614
12432
  RESOURCE_ATTRIBUTE_KEY_REJECTION_DETAIL,
11615
12433
  SILENT_HOOK_RESPONSE,
11616
12434
  SPAN_RECORD_VERSION,
12435
+ SUBAGENT_ID_PATTERN,
11617
12436
  SUPPORTED_REGISTRATION_PROVIDER_IDS,
11618
12437
  UNKNOWN_PROVIDER_ID,
11619
12438
  UNKNOWN_WORKSPACE_ID,
@@ -11666,6 +12485,7 @@ export {
11666
12485
  createFileDurableLogSpool,
11667
12486
  createFileDurableSpool,
11668
12487
  createFilesystemStateStore,
12488
+ createFilesystemWorktreeLocator,
11669
12489
  createFixedClock,
11670
12490
  createGeminiCliAdapter,
11671
12491
  createHealthTracker,
@@ -11736,6 +12556,7 @@ export {
11736
12556
  isReservedExtensionNamespace,
11737
12557
  isReservedResourceAttributeKey,
11738
12558
  isSecretResourceAttributeKey,
12559
+ isUnavailableContentFact,
11739
12560
  isUnknownProvider,
11740
12561
  isValidExtensionKey,
11741
12562
  lockPathFor,
@@ -11762,6 +12583,8 @@ export {
11762
12583
  parentScopeRefOf,
11763
12584
  parseCanonicalEvent,
11764
12585
  parseEnvironmentConfig,
12586
+ parseGitDirFile,
12587
+ parseHeadBranch,
11765
12588
  parseResourceAttributesValue,
11766
12589
  planProviderRegistration,
11767
12590
  privacyLimitsSchema,
@@ -11793,6 +12616,7 @@ export {
11793
12616
  renderJsonDocument,
11794
12617
  resolveConfig,
11795
12618
  resolveDeliveryIdentity,
12619
+ resolveEventTargets,
11796
12620
  resolveInstallPath,
11797
12621
  resolveInvocationIdentity,
11798
12622
  resolveLogsEndpoint,
@@ -11814,8 +12638,11 @@ export {
11814
12638
  stateRecordSchema,
11815
12639
  stateValueSchema,
11816
12640
  subagentEndEventSchema,
12641
+ subagentIdSchema,
11817
12642
  subagentStartEventSchema,
11818
12643
  summarizeHealth,
12644
+ targetHintSchema,
12645
+ targetSourceSchema,
11819
12646
  toReport,
11820
12647
  tokenCountSchema,
11821
12648
  toolEndEventSchema,
@@ -11832,6 +12659,7 @@ export {
11832
12659
  workspaceIdSchema,
11833
12660
  workspaceIdentitySchema,
11834
12661
  workspaceKeySourceSchema,
12662
+ workspaceTargetSchema,
11835
12663
  writeDocumentAtomically
11836
12664
  };
11837
12665
  //# sourceMappingURL=index.js.map