@posthog/ai 8.20.1 → 8.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/README.md +20 -0
  2. package/dist/adk/index.cjs +125 -36
  3. package/dist/adk/index.cjs.map +1 -1
  4. package/dist/adk/index.d.ts +7 -0
  5. package/dist/adk/index.mjs +126 -37
  6. package/dist/adk/index.mjs.map +1 -1
  7. package/dist/anthropic/index.cjs +115 -22
  8. package/dist/anthropic/index.cjs.map +1 -1
  9. package/dist/anthropic/index.d.ts +7 -0
  10. package/dist/anthropic/index.mjs +116 -23
  11. package/dist/anthropic/index.mjs.map +1 -1
  12. package/dist/claude-agent-sdk/index.cjs +131 -35
  13. package/dist/claude-agent-sdk/index.cjs.map +1 -1
  14. package/dist/claude-agent-sdk/index.d.ts +6 -0
  15. package/dist/claude-agent-sdk/index.mjs +132 -36
  16. package/dist/claude-agent-sdk/index.mjs.map +1 -1
  17. package/dist/gemini/index.cjs +116 -23
  18. package/dist/gemini/index.cjs.map +1 -1
  19. package/dist/gemini/index.d.ts +7 -0
  20. package/dist/gemini/index.mjs +116 -23
  21. package/dist/gemini/index.mjs.map +1 -1
  22. package/dist/genkit/index.cjs +138 -43
  23. package/dist/genkit/index.cjs.map +1 -1
  24. package/dist/genkit/index.d.ts +7 -0
  25. package/dist/genkit/index.mjs +138 -43
  26. package/dist/genkit/index.mjs.map +1 -1
  27. package/dist/index.cjs +114 -21
  28. package/dist/index.cjs.map +1 -1
  29. package/dist/index.d.ts +11 -0
  30. package/dist/index.mjs +115 -22
  31. package/dist/index.mjs.map +1 -1
  32. package/dist/langchain/index.cjs +99 -21
  33. package/dist/langchain/index.cjs.map +1 -1
  34. package/dist/langchain/index.d.ts +7 -0
  35. package/dist/langchain/index.mjs +99 -21
  36. package/dist/langchain/index.mjs.map +1 -1
  37. package/dist/langchain/middleware/index.cjs +99 -21
  38. package/dist/langchain/middleware/index.cjs.map +1 -1
  39. package/dist/langchain/middleware/index.d.ts +6 -0
  40. package/dist/langchain/middleware/index.mjs +99 -21
  41. package/dist/langchain/middleware/index.mjs.map +1 -1
  42. package/dist/openai/index.cjs +115 -22
  43. package/dist/openai/index.cjs.map +1 -1
  44. package/dist/openai/index.d.ts +7 -0
  45. package/dist/openai/index.mjs +116 -23
  46. package/dist/openai/index.mjs.map +1 -1
  47. package/dist/openai-agents/index.cjs +139 -60
  48. package/dist/openai-agents/index.cjs.map +1 -1
  49. package/dist/openai-agents/index.d.ts +7 -0
  50. package/dist/openai-agents/index.mjs +139 -60
  51. package/dist/openai-agents/index.mjs.map +1 -1
  52. package/dist/otel/index.browser.cjs +24 -14
  53. package/dist/otel/index.browser.cjs.map +1 -1
  54. package/dist/otel/index.browser.mjs +24 -14
  55. package/dist/otel/index.browser.mjs.map +1 -1
  56. package/dist/otel/index.cjs +24 -14
  57. package/dist/otel/index.cjs.map +1 -1
  58. package/dist/otel/index.d.ts +3 -3
  59. package/dist/otel/index.mjs +24 -14
  60. package/dist/otel/index.mjs.map +1 -1
  61. package/dist/vercel/index.cjs +114 -21
  62. package/dist/vercel/index.cjs.map +1 -1
  63. package/dist/vercel/index.d.ts +6 -0
  64. package/dist/vercel/index.mjs +115 -22
  65. package/dist/vercel/index.mjs.map +1 -1
  66. package/package.json +5 -5
package/README.md CHANGED
@@ -21,6 +21,26 @@ For OpenTelemetry, pass `privacyMode: true` to `PostHogTraceExporter`, or to `Po
21
21
 
22
22
  Remote MCP tool `headers` and `authorization` values are always replaced with `[REDACTED]`.
23
23
 
24
+ ## Event options
25
+
26
+ Pass posthog-node per-event options with `posthogOptions` on a wrapped provider call or on `withTracing()`, or with `options` on the LangChain callback handler and the OpenAI Agents, Claude Agent SDK, Google ADK and Genkit integrations.
27
+
28
+ ```ts
29
+ await openai.responses.create({
30
+ model: 'gpt-5-mini',
31
+ input: 'Hello',
32
+ posthogDistinctId: 'user_123',
33
+ posthogOptions: { process_person_profile: false },
34
+ })
35
+
36
+ const handler = new LangChainCallbackHandler({ client: posthog, options: { process_person_profile: false } })
37
+ ```
38
+
39
+ - Per-call options beat options from `registerOptions()` and `withContext()`.
40
+ - An event with no distinct id always has person processing turned off, whatever its options say.
41
+ - posthog-node 5.x.x has no per-event options. `@posthog/ai` sends each option posthog-node 5.x.x knows in the form it reads, and drops other keys.
42
+ - An `options` value that is not an object is logged and ignored. The event is still sent.
43
+
24
44
  ## Gemini Interactions
25
45
 
26
46
  `PostHogGoogleGenAI.interactions.create` traces foreground model calls with `@google/genai` 2.18 or later in the 2.x series.
@@ -3,7 +3,7 @@ let _google_adk = require("@google/adk");
3
3
  let uuid = require("uuid");
4
4
  let _posthog_core = require("@posthog/core");
5
5
  //#region package.json
6
- var version = "8.20.1";
6
+ var version = "8.21.0";
7
7
  //#endregion
8
8
  //#region src/typeGuards.ts
9
9
  const isObject = (value) => {
@@ -15,9 +15,77 @@ const isObject = (value) => {
15
15
  function isFullAiCaptureEnabled(client) {
16
16
  return client?.enableFullAiCapture === true;
17
17
  }
18
+ /**
19
+ * The caller's distinct id as a string, or undefined when it is missing, empty or only whitespace.
20
+ *
21
+ * @internal
22
+ */
23
+ function userDistinctId(value) {
24
+ if (!value) return;
25
+ const id = String(value);
26
+ return id.trim() === "" ? void 0 : id;
27
+ }
28
+ /**
29
+ * The caller's per-event options when they are an object. A missing or `null` value means no
30
+ * options. An array or any other value is reported and ignored, so it is never spread.
31
+ *
32
+ * @internal
33
+ */
34
+ function readAiEventOptions(value) {
35
+ if (value === void 0 || value === null) return;
36
+ if (typeof value === "object" && !Array.isArray(value)) return value;
37
+ console.warn(`[PostHog AI] options must be an object, got ${Array.isArray(value) ? "array" : typeof value}; ignoring them`);
38
+ }
39
+ /**
40
+ * The `properties` and `options` for an AI event. `personless` (no user distinct id) turns person
41
+ * processing off and beats the caller's `process_person_profile`.
42
+ *
43
+ * posthog-node 6 takes the options as they are, so no option is written as a property.
44
+ * posthog-node 5 has no per-event options: each known option is sent as the property that version
45
+ * reads, and an unknown key is dropped.
46
+ *
47
+ * @internal
48
+ */
49
+ function eventOptionFields(client, properties, options, personless) {
50
+ const userOptions = readAiEventOptions(options);
51
+ if (isPostHogNode6(client)) {
52
+ const eventOptions = {
53
+ ...userOptions,
54
+ ...personless ? { process_person_profile: false } : {}
55
+ };
56
+ return Object.keys(eventOptions).length > 0 ? {
57
+ properties,
58
+ options: eventOptions
59
+ } : { properties };
60
+ }
61
+ const withOptionProperties = {
62
+ ...properties,
63
+ ...(0, _posthog_core.eventOptionsAsLegacyProperties)(userOptions)
64
+ };
65
+ if (personless) withOptionProperties.$process_person_profile = false;
66
+ return { properties: withOptionProperties };
67
+ }
68
+ /**
69
+ * Whether the client is posthog-node 6 or later, the first major with per-event options.
70
+ *
71
+ * @internal
72
+ */
73
+ function isPostHogNode6(client) {
74
+ return (0, _posthog_core.acceptsEventOptions)(client);
75
+ }
76
+ /**
77
+ * posthog-node 6 sends every AI event on its capture v1 AI lane; `enableFullAiCapture` then only
78
+ * controls truncation and media redaction. posthog-node 5 keeps the opt-in, so an `@posthog/ai`
79
+ * upgrade never changes how a 5.x client sends.
80
+ *
81
+ * @internal
82
+ */
83
+ function usesAiLane(client) {
84
+ return isPostHogNode6(client) || isFullAiCaptureEnabled(client);
85
+ }
18
86
  /** @internal */
19
87
  function captureAiEvent(client, event) {
20
- if (isFullAiCaptureEnabled(client) && typeof client.captureAi === "function") {
88
+ if (usesAiLane(client) && typeof client.captureAi === "function") {
21
89
  client.captureAi(event);
22
90
  return;
23
91
  }
@@ -25,7 +93,7 @@ function captureAiEvent(client, event) {
25
93
  }
26
94
  /** @internal */
27
95
  async function captureAiEventImmediate(client, event) {
28
- if (isFullAiCaptureEnabled(client) && typeof client.captureAiImmediate === "function") {
96
+ if (usesAiLane(client) && typeof client.captureAiImmediate === "function") {
29
97
  await client.captureAiImmediate(event);
30
98
  return;
31
99
  }
@@ -173,13 +241,17 @@ var MediaTypeContext = class MediaTypeContext {
173
241
  //#region src/sanitization/binary_content_redactor.ts
174
242
  const STRONG_CONTEXT_MIN_LENGTH = 64;
175
243
  const WEAK_CONTEXT_MIN_LENGTH = 1024;
244
+ const MAX_NODES = 1e4;
245
+ const TRUNCATED = "[Truncated]";
176
246
  var BinaryContentRedactor = class {
177
247
  constructor(recognizer = new Base64Recognizer()) {
178
248
  this.recognizer = recognizer;
179
- this.visited = /* @__PURE__ */ new WeakSet();
249
+ this.ancestors = /* @__PURE__ */ new WeakSet();
250
+ this.remainingNodes = MAX_NODES;
180
251
  }
181
252
  redact(value, mediaType) {
182
- this.visited = /* @__PURE__ */ new WeakSet();
253
+ this.ancestors = /* @__PURE__ */ new WeakSet();
254
+ this.remainingNodes = MAX_NODES;
183
255
  return this.walk(value, mediaType ? new MediaTypeContext(void 0, void 0, mediaType) : MediaTypeContext.EMPTY);
184
256
  }
185
257
  /** Redact one leaf while a caller owns bounded, type-preserving traversal. @internal */
@@ -191,18 +263,24 @@ var BinaryContentRedactor = class {
191
263
  if (typeof value === "string") return this.redactLeaf(value, ctx);
192
264
  if (typeof value !== "object") return value;
193
265
  if (typeof Uint8Array !== "undefined" && value instanceof Uint8Array) return this.redactLeaf(value, ctx);
194
- if (this.visited.has(value)) return null;
195
- this.visited.add(value);
196
- if (Array.isArray(value)) return value.map((item) => this.walk(item, ctx));
197
- const obj = value;
198
- const out = {};
199
- for (const k of Object.keys(obj)) Object.defineProperty(out, k, {
200
- value: this.walk(obj[k], new MediaTypeContext(obj, k)),
201
- enumerable: true,
202
- writable: true,
203
- configurable: true
204
- });
205
- return out;
266
+ if (this.ancestors.has(value)) return null;
267
+ if (this.remainingNodes <= 0) return TRUNCATED;
268
+ this.remainingNodes--;
269
+ this.ancestors.add(value);
270
+ try {
271
+ if (Array.isArray(value)) return value.map((item) => this.walk(item, ctx));
272
+ const obj = value;
273
+ const out = {};
274
+ for (const k of Object.keys(obj)) Object.defineProperty(out, k, {
275
+ value: this.walk(obj[k], new MediaTypeContext(obj, k)),
276
+ enumerable: true,
277
+ writable: true,
278
+ configurable: true
279
+ });
280
+ return out;
281
+ } finally {
282
+ this.ancestors.delete(value);
283
+ }
206
284
  }
207
285
  redactString(value, ctx) {
208
286
  const hasDefiniteBinaryData = ctx.hasDefiniteBinaryData();
@@ -561,6 +639,20 @@ const warnIfPostHogAiGateway = (baseURL) => {
561
639
  //#endregion
562
640
  //#region src/captureAiGeneration.ts
563
641
  /**
642
+ * posthog-node 6 takes an options object; 5.x, which has no `registerOptions`, takes positional
643
+ * arguments. The 6.x positional fallback works too, but logs a deprecation error in the app.
644
+ */
645
+ const captureAiException = (client, error, properties, uuid$1) => {
646
+ if (isPostHogNode6(client)) {
647
+ client.captureException(error, {
648
+ properties,
649
+ uuid: uuid$1
650
+ });
651
+ return;
652
+ }
653
+ client.captureException.call(client, error, void 0, properties, uuid$1);
654
+ };
655
+ /**
564
656
  * Capture an `$ai_generation` (or `$ai_embedding`) event to PostHog.
565
657
  *
566
658
  * This is the canonical primitive that every `@posthog/ai` wrapper
@@ -596,7 +688,7 @@ const captureAiGeneration = async (client, options) => {
596
688
  if (client.options?.enableExceptionAutocapture) {
597
689
  if (!shouldRedact) {
598
690
  exceptionId = (0, _posthog_core.uuidv7)();
599
- client.captureException(options.error, void 0, { $ai_trace_id: traceId }, exceptionId);
691
+ captureAiException(client, options.error, { $ai_trace_id: traceId }, exceptionId);
600
692
  }
601
693
  if (typeof options.error === "object") options.error.__posthog_previously_captured_error = true;
602
694
  }
@@ -622,6 +714,7 @@ const captureAiGeneration = async (client, options) => {
622
714
  ...usage.webSearchCount ? { $ai_web_search_count: usage.webSearchCount } : {},
623
715
  ...usage.rawUsage ? { $ai_usage: usage.rawUsage } : {}
624
716
  };
717
+ const distinctId = userDistinctId(options.distinctId);
625
718
  const properties = {
626
719
  $ai_lib: "posthog-ai",
627
720
  $ai_lib_version: version,
@@ -641,7 +734,6 @@ const captureAiGeneration = async (client, options) => {
641
734
  ...options.baseURL === null ? {} : { $ai_base_url: options.baseURL ?? "" },
642
735
  ...options.properties,
643
736
  $ai_tokens_source: getTokensSource(options.properties),
644
- ...options.distinctId ? {} : { $process_person_profile: false },
645
737
  ...options.stopReason ? { $ai_stop_reason: options.stopReason } : {},
646
738
  ...options.tools ? { $ai_tools: redactMcpToolCredentials(options.tools) } : {},
647
739
  ...options.completionId ? { $ai_completion_id: options.completionId } : {},
@@ -650,9 +742,9 @@ const captureAiGeneration = async (client, options) => {
650
742
  ...costOverrideData
651
743
  };
652
744
  const event = {
653
- distinctId: options.distinctId ?? traceId,
745
+ distinctId: distinctId ?? traceId,
654
746
  event: eventType,
655
- properties,
747
+ ...eventOptionFields(client, properties, options.options, !distinctId),
656
748
  groups: options.groups
657
749
  };
658
750
  if (options.captureImmediate) await captureAiEventImmediate(client, event);
@@ -724,6 +816,7 @@ var PostHogADKPlugin = class extends _google_adk.BasePlugin {
724
816
  this._privacyMode = options.privacyMode ?? false;
725
817
  this._groups = options.groups;
726
818
  this._properties = options.properties ?? {};
819
+ this._eventOptions = options.options;
727
820
  this._captureImmediate = options.captureImmediate ?? false;
728
821
  this._onError = options.onError;
729
822
  }
@@ -913,6 +1006,7 @@ var PostHogADKPlugin = class extends _google_adk.BasePlugin {
913
1006
  stopReason,
914
1007
  tools: pending?.tools,
915
1008
  groups: this._groups,
1009
+ options: this._eventOptions,
916
1010
  privacyMode: this._privacyMode,
917
1011
  captureImmediate: this._captureImmediate,
918
1012
  onError: this._onError,
@@ -948,32 +1042,27 @@ var PostHogADKPlugin = class extends _google_adk.BasePlugin {
948
1042
  });
949
1043
  }
950
1044
  async _captureLifecycleEvent(event, distinctId, properties) {
1045
+ const eventProperties = {
1046
+ $ai_lib: "posthog-ai",
1047
+ $ai_lib_version: version,
1048
+ $ai_framework: "google-adk",
1049
+ ...properties,
1050
+ ...this._properties
1051
+ };
951
1052
  const message = {
952
1053
  distinctId: distinctId ?? String(properties.$ai_trace_id),
953
1054
  event,
954
- properties: {
955
- $ai_lib: "posthog-ai",
956
- $ai_lib_version: version,
957
- $ai_framework: "google-adk",
958
- ...properties,
959
- ...this._properties,
960
- ...distinctId ? {} : { $process_person_profile: false }
961
- },
1055
+ ...eventOptionFields(this._client, eventProperties, this._eventOptions, !distinctId),
962
1056
  groups: this._groups
963
1057
  };
964
1058
  if (this._captureImmediate) await captureAiEventImmediate(this._client, message);
965
1059
  else captureAiEvent(this._client, message);
966
1060
  }
967
1061
  _resolveDistinctId(context) {
968
- if (typeof this._distinctId === "function") {
969
- const resolved = this._distinctId(context);
970
- if (resolved) return String(resolved);
971
- } else if (this._distinctId) return String(this._distinctId);
972
- return context.userId ? String(context.userId) : void 0;
1062
+ return userDistinctId(typeof this._distinctId === "function" ? this._distinctId(context) : this._distinctId) ?? userDistinctId(context.userId);
973
1063
  }
974
1064
  _resolveInvocationDistinctId(context) {
975
- if (typeof this._distinctId === "string" && this._distinctId) return String(this._distinctId);
976
- return context.userId ? String(context.userId) : void 0;
1065
+ return userDistinctId(typeof this._distinctId === "string" ? this._distinctId : void 0) ?? userDistinctId(context.userId);
977
1066
  }
978
1067
  _rememberContext(context) {
979
1068
  const trace = this._traces.get(context.invocationId);