@posthog/ai 8.10.0 → 8.10.2

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 (51) hide show
  1. package/dist/adk/index.cjs +908 -1198
  2. package/dist/adk/index.cjs.map +1 -1
  3. package/dist/adk/index.d.ts +109 -109
  4. package/dist/adk/index.mjs +907 -1196
  5. package/dist/adk/index.mjs.map +1 -1
  6. package/dist/anthropic/index.cjs +927 -1111
  7. package/dist/anthropic/index.cjs.map +1 -1
  8. package/dist/anthropic/index.d.ts +34 -33
  9. package/dist/anthropic/index.mjs +899 -1102
  10. package/dist/anthropic/index.mjs.map +1 -1
  11. package/dist/gemini/index.cjs +863 -1108
  12. package/dist/gemini/index.cjs.map +1 -1
  13. package/dist/gemini/index.d.ts +38 -35
  14. package/dist/gemini/index.mjs +858 -1103
  15. package/dist/gemini/index.mjs.map +1 -1
  16. package/dist/index.cjs +1218 -1546
  17. package/dist/index.cjs.map +1 -1
  18. package/dist/index.d.ts +170 -163
  19. package/dist/index.mjs +1216 -1544
  20. package/dist/index.mjs.map +1 -1
  21. package/dist/langchain/index.cjs +851 -1029
  22. package/dist/langchain/index.cjs.map +1 -1
  23. package/dist/langchain/index.d.ts +75 -75
  24. package/dist/langchain/index.mjs +850 -1027
  25. package/dist/langchain/index.mjs.map +1 -1
  26. package/dist/langchain/middleware/index.cjs +1016 -1225
  27. package/dist/langchain/middleware/index.cjs.map +1 -1
  28. package/dist/langchain/middleware/index.d.ts +29 -25
  29. package/dist/langchain/middleware/index.mjs +1015 -1223
  30. package/dist/langchain/middleware/index.mjs.map +1 -1
  31. package/dist/openai/index.cjs +1990 -2523
  32. package/dist/openai/index.cjs.map +1 -1
  33. package/dist/openai/index.d.ts +106 -104
  34. package/dist/openai/index.mjs +1985 -2518
  35. package/dist/openai/index.mjs.map +1 -1
  36. package/dist/openai-agents/index.cjs +745 -827
  37. package/dist/openai-agents/index.cjs.map +1 -1
  38. package/dist/openai-agents/index.d.ts +48 -47
  39. package/dist/openai-agents/index.mjs +744 -825
  40. package/dist/openai-agents/index.mjs.map +1 -1
  41. package/dist/otel/index.cjs +427 -486
  42. package/dist/otel/index.cjs.map +1 -1
  43. package/dist/otel/index.d.ts +36 -35
  44. package/dist/otel/index.mjs +426 -484
  45. package/dist/otel/index.mjs.map +1 -1
  46. package/dist/vercel/index.cjs +992 -1343
  47. package/dist/vercel/index.cjs.map +1 -1
  48. package/dist/vercel/index.d.ts +21 -16
  49. package/dist/vercel/index.mjs +991 -1341
  50. package/dist/vercel/index.mjs.map +1 -1
  51. package/package.json +15 -14
@@ -1,1265 +1,976 @@
1
- import { BasePlugin } from '@google/adk';
2
- import { v4 } from 'uuid';
3
- import { toJsonSafeValue, uuidv7 } from '@posthog/core';
4
-
5
- var version = "8.10.0";
6
-
7
- /** @internal */
8
-
9
- /** @internal */
10
-
1
+ import { BasePlugin } from "@google/adk";
2
+ import { v4 } from "uuid";
3
+ import { toJsonSafeValue, uuidv7 } from "@posthog/core";
4
+ //#region package.json
5
+ var version = "8.10.2";
6
+ //#endregion
7
+ //#region src/captureAiEvent.ts
11
8
  /** @internal */
12
9
  function isFullAiCaptureEnabled(client) {
13
- return client?.enableFullAiCapture === true;
10
+ return client?.enableFullAiCapture === true;
14
11
  }
15
-
16
12
  /** @internal */
17
13
  function captureAiEvent(client, event) {
18
- if (isFullAiCaptureEnabled(client) && typeof client.captureAi === 'function') {
19
- client.captureAi(event);
20
- return;
21
- }
22
- client.capture(event);
14
+ if (isFullAiCaptureEnabled(client) && typeof client.captureAi === "function") {
15
+ client.captureAi(event);
16
+ return;
17
+ }
18
+ client.capture(event);
23
19
  }
24
-
25
20
  /** @internal */
26
21
  async function captureAiEventImmediate(client, event) {
27
- if (isFullAiCaptureEnabled(client) && typeof client.captureAiImmediate === 'function') {
28
- await client.captureAiImmediate(event);
29
- return;
30
- }
31
- await client.captureImmediate(event);
22
+ if (isFullAiCaptureEnabled(client) && typeof client.captureAiImmediate === "function") {
23
+ await client.captureAiImmediate(event);
24
+ return;
25
+ }
26
+ await client.captureImmediate(event);
32
27
  }
33
-
28
+ //#endregion
29
+ //#region src/sanitization/base64_recognizer.ts
34
30
  const DATA_URL_PREFIX_RE = /^data:([^;,\s]+)(?:;[^;,\s]+)*;base64,/i;
35
31
  const BASE64_ALPHABET_RE = /^[A-Za-z0-9+/_=-]+$/;
36
- class Base64Recognizer {
37
- recognize(value, minLength) {
38
- const dataUrl = DATA_URL_PREFIX_RE.exec(value);
39
- if (dataUrl) return {
40
- kind: 'data-url',
41
- mediaType: dataUrl[1]
42
- };
43
- if (value.length < minLength) return {
44
- kind: 'none'
45
- };
46
- const confidencePrefix = value.slice(0, minLength);
47
- if (BASE64_ALPHABET_RE.test(confidencePrefix)) {
48
- return {
49
- kind: 'raw'
50
- };
51
- } else {
52
- return {
53
- kind: 'none'
54
- };
55
- }
56
- }
57
- }
58
-
59
- const MIME_HINT_KEYS = ['mediaType', 'media_type', 'mimeType', 'mime_type'];
60
- const STRONG_CONTEXT_KEYS = new Set(['data', 'file_data', 'fileData', 'image_url', 'imageUrl', 'video_url', 'videoUrl', 'audio', 'audio_data', 'audioData', 'inline_data', 'inlineData', 'source', 'result']);
61
- const STRONG_CONTEXT_TYPES = new Set(['image', 'image_url', 'input_image', 'audio', 'input_audio', 'video', 'video_url', 'file', 'input_file', 'document', 'media', 'file-data']);
62
- const FILE_FAMILY_TYPES = new Set(['file', 'input_file', 'document', 'media', 'file-data']);
63
- const KNOWN_AUDIO_FORMATS = new Set(['wav', 'mp3', 'ogg', 'flac', 'm4a', 'aac', 'webm']);
64
- class MediaTypeContext {
65
- static EMPTY = new MediaTypeContext(undefined, undefined);
66
- constructor(parent, key, explicitMediaType) {
67
- this.parent = parent;
68
- this.key = key;
69
- this.explicitMediaType = explicitMediaType;
70
- }
71
- inferMediaType() {
72
- return this.inferFromSiblingMime() ?? this.inferFromSiblingFormat() ?? this.inferFromParentType() ?? this.inferFromKey();
73
- }
74
- inferFromSiblingMime() {
75
- if (this.explicitMediaType) return this.explicitMediaType;
76
- if (!this.parent) return undefined;
77
- for (const hint of MIME_HINT_KEYS) {
78
- const v = this.parent[hint];
79
- if (typeof v === 'string') return v;
80
- }
81
- return undefined;
82
- }
83
- inferFromSiblingFormat() {
84
- if (!this.parent) return undefined;
85
- const fmt = this.parent.format;
86
- if (typeof fmt === 'string' && KNOWN_AUDIO_FORMATS.has(fmt.toLowerCase())) {
87
- return `audio/${fmt.toLowerCase()}`;
88
- }
89
- return undefined;
90
- }
91
- inferFromParentType() {
92
- if (!this.parent) return undefined;
93
- const t = this.parent.type;
94
- if (typeof t !== 'string') return undefined;
95
- if (t === 'image' || t === 'image_url' || t === 'input_image') return 'image';
96
- if (t === 'audio' || t === 'input_audio') return 'audio';
97
- if (t === 'video' || t === 'video_url') return 'video';
98
- if (FILE_FAMILY_TYPES.has(t)) return 'application/octet-stream';
99
- return undefined;
100
- }
101
- inferFromKey() {
102
- if (!this.key) return undefined;
103
- const key = this.key.toLowerCase();
104
- if (key.includes('audio')) return 'audio';
105
- if (key.includes('video')) return 'video';
106
- if (key.includes('image')) return 'image';
107
- if (key.includes('file') || key.includes('document')) return 'application/octet-stream';
108
- return undefined;
109
- }
110
- hasExplicitBinaryMediaType() {
111
- if (!this.explicitMediaType && (!this.parent || !this.key || !STRONG_CONTEXT_KEYS.has(this.key))) return false;
112
- const mediaType = this.inferFromSiblingMime();
113
- return mediaType !== undefined && !mediaType.toLowerCase().startsWith('text/');
114
- }
115
- signalsBinary() {
116
- if (this.explicitMediaType) return true;
117
- if (this.parent) {
118
- for (const hint of MIME_HINT_KEYS) {
119
- if (typeof this.parent[hint] === 'string') return true;
120
- }
121
- const fmt = this.parent.format;
122
- if (typeof fmt === 'string' && KNOWN_AUDIO_FORMATS.has(fmt.toLowerCase())) return true;
123
- const t = this.parent.type;
124
- if (typeof t === 'string' && STRONG_CONTEXT_TYPES.has(t)) return true;
125
- }
126
- if (this.key && STRONG_CONTEXT_KEYS.has(this.key)) return true;
127
- return false;
128
- }
129
- }
130
-
32
+ var Base64Recognizer = class {
33
+ recognize(value, minLength) {
34
+ const dataUrl = DATA_URL_PREFIX_RE.exec(value);
35
+ if (dataUrl) return {
36
+ kind: "data-url",
37
+ mediaType: dataUrl[1]
38
+ };
39
+ if (value.length < minLength) return { kind: "none" };
40
+ const confidencePrefix = value.slice(0, minLength);
41
+ if (BASE64_ALPHABET_RE.test(confidencePrefix)) return { kind: "raw" };
42
+ else return { kind: "none" };
43
+ }
44
+ };
45
+ //#endregion
46
+ //#region src/sanitization/media_type_context.ts
47
+ const MIME_HINT_KEYS = [
48
+ "mediaType",
49
+ "media_type",
50
+ "mimeType",
51
+ "mime_type"
52
+ ];
53
+ const STRONG_CONTEXT_KEYS = /* @__PURE__ */ new Set([
54
+ "data",
55
+ "file_data",
56
+ "fileData",
57
+ "image_url",
58
+ "imageUrl",
59
+ "video_url",
60
+ "videoUrl",
61
+ "audio",
62
+ "audio_data",
63
+ "audioData",
64
+ "inline_data",
65
+ "inlineData",
66
+ "source",
67
+ "result"
68
+ ]);
69
+ const STRONG_CONTEXT_TYPES = /* @__PURE__ */ new Set([
70
+ "image",
71
+ "image_url",
72
+ "input_image",
73
+ "audio",
74
+ "input_audio",
75
+ "video",
76
+ "video_url",
77
+ "file",
78
+ "input_file",
79
+ "document",
80
+ "media",
81
+ "file-data"
82
+ ]);
83
+ const FILE_FAMILY_TYPES = /* @__PURE__ */ new Set([
84
+ "file",
85
+ "input_file",
86
+ "document",
87
+ "media",
88
+ "file-data"
89
+ ]);
90
+ const KNOWN_AUDIO_FORMATS = /* @__PURE__ */ new Set([
91
+ "wav",
92
+ "mp3",
93
+ "ogg",
94
+ "flac",
95
+ "m4a",
96
+ "aac",
97
+ "webm"
98
+ ]);
99
+ var MediaTypeContext = class MediaTypeContext {
100
+ static {
101
+ this.EMPTY = new MediaTypeContext(void 0, void 0);
102
+ }
103
+ constructor(parent, key, explicitMediaType) {
104
+ this.parent = parent;
105
+ this.key = key;
106
+ this.explicitMediaType = explicitMediaType;
107
+ }
108
+ inferMediaType() {
109
+ return this.inferFromSiblingMime() ?? this.inferFromSiblingFormat() ?? this.inferFromParentType() ?? this.inferFromKey();
110
+ }
111
+ inferFromSiblingMime() {
112
+ if (this.explicitMediaType) return this.explicitMediaType;
113
+ if (!this.parent) return void 0;
114
+ for (const hint of MIME_HINT_KEYS) {
115
+ const v = this.parent[hint];
116
+ if (typeof v === "string") return v;
117
+ }
118
+ }
119
+ inferFromSiblingFormat() {
120
+ if (!this.parent) return void 0;
121
+ const fmt = this.parent.format;
122
+ if (typeof fmt === "string" && KNOWN_AUDIO_FORMATS.has(fmt.toLowerCase())) return `audio/${fmt.toLowerCase()}`;
123
+ }
124
+ inferFromParentType() {
125
+ if (!this.parent) return void 0;
126
+ const t = this.parent.type;
127
+ if (typeof t !== "string") return void 0;
128
+ if (t === "image" || t === "image_url" || t === "input_image") return "image";
129
+ if (t === "audio" || t === "input_audio") return "audio";
130
+ if (t === "video" || t === "video_url") return "video";
131
+ if (FILE_FAMILY_TYPES.has(t)) return "application/octet-stream";
132
+ }
133
+ inferFromKey() {
134
+ if (!this.key) return void 0;
135
+ const key = this.key.toLowerCase();
136
+ if (key.includes("audio")) return "audio";
137
+ if (key.includes("video")) return "video";
138
+ if (key.includes("image")) return "image";
139
+ if (key.includes("file") || key.includes("document")) return "application/octet-stream";
140
+ }
141
+ hasExplicitBinaryMediaType() {
142
+ if (!this.explicitMediaType && (!this.parent || !this.key || !STRONG_CONTEXT_KEYS.has(this.key))) return false;
143
+ const mediaType = this.inferFromSiblingMime();
144
+ return mediaType !== void 0 && !mediaType.toLowerCase().startsWith("text/");
145
+ }
146
+ signalsBinary() {
147
+ if (this.explicitMediaType) return true;
148
+ if (this.parent) {
149
+ for (const hint of MIME_HINT_KEYS) if (typeof this.parent[hint] === "string") return true;
150
+ const fmt = this.parent.format;
151
+ if (typeof fmt === "string" && KNOWN_AUDIO_FORMATS.has(fmt.toLowerCase())) return true;
152
+ const t = this.parent.type;
153
+ if (typeof t === "string" && STRONG_CONTEXT_TYPES.has(t)) return true;
154
+ }
155
+ if (this.key && STRONG_CONTEXT_KEYS.has(this.key)) return true;
156
+ return false;
157
+ }
158
+ };
159
+ //#endregion
160
+ //#region src/sanitization/binary_content_redactor.ts
131
161
  const STRONG_CONTEXT_MIN_LENGTH = 64;
132
162
  const WEAK_CONTEXT_MIN_LENGTH = 1024;
133
- class BinaryContentRedactor {
134
- visited = new WeakSet();
135
- constructor(recognizer = new Base64Recognizer()) {
136
- this.recognizer = recognizer;
137
- }
138
- redact(value, mediaType) {
139
- this.visited = new WeakSet();
140
- return this.walk(value, mediaType ? new MediaTypeContext(undefined, undefined, mediaType) : MediaTypeContext.EMPTY);
141
- }
142
- walk(value, ctx) {
143
- if (value === null || value === undefined) return value;
144
- if (typeof value === 'string') return this.redactString(value, ctx);
145
- if (typeof value !== 'object') return value;
146
-
147
- // Buffer extends Uint8Array, so this branch catches both.
148
- if (typeof Uint8Array !== 'undefined' && value instanceof Uint8Array) {
149
- return this.placeholderFor(ctx.inferMediaType());
150
- }
151
- if (this.visited.has(value)) return null;
152
- this.visited.add(value);
153
- if (Array.isArray(value)) {
154
- return value.map(item => this.walk(item, ctx));
155
- }
156
- const obj = value;
157
- const out = {};
158
- for (const k of Object.keys(obj)) {
159
- out[k] = this.walk(obj[k], new MediaTypeContext(obj, k));
160
- }
161
- return out;
162
- }
163
- redactString(value, ctx) {
164
- const hasExplicitBinaryMediaType = ctx.hasExplicitBinaryMediaType();
165
- const recognitionValue = hasExplicitBinaryMediaType ? value.replace(/[\r\n]/g, '') : value;
166
- const minLength = hasExplicitBinaryMediaType ? Math.min(recognitionValue.length, STRONG_CONTEXT_MIN_LENGTH) : ctx.signalsBinary() ? STRONG_CONTEXT_MIN_LENGTH : WEAK_CONTEXT_MIN_LENGTH;
167
- const recognition = this.recognizer.recognize(recognitionValue, minLength);
168
- switch (recognition.kind) {
169
- case 'data-url':
170
- return this.placeholderFor(recognition.mediaType);
171
- case 'raw':
172
- return this.placeholderFor(ctx.inferMediaType());
173
- case 'none':
174
- return value;
175
- }
176
- }
177
- placeholderFor(mediaType) {
178
- if (!mediaType) return '[base64 redacted]';
179
- if (mediaType === 'application/octet-stream') return '[base64 file redacted]';
180
- return `[base64 ${mediaType} redacted]`;
181
- }
182
- }
183
-
163
+ var BinaryContentRedactor = class {
164
+ constructor(recognizer = new Base64Recognizer()) {
165
+ this.recognizer = recognizer;
166
+ this.visited = /* @__PURE__ */ new WeakSet();
167
+ }
168
+ redact(value, mediaType) {
169
+ this.visited = /* @__PURE__ */ new WeakSet();
170
+ return this.walk(value, mediaType ? new MediaTypeContext(void 0, void 0, mediaType) : MediaTypeContext.EMPTY);
171
+ }
172
+ walk(value, ctx) {
173
+ if (value === null || value === void 0) return value;
174
+ if (typeof value === "string") return this.redactString(value, ctx);
175
+ if (typeof value !== "object") return value;
176
+ if (typeof Uint8Array !== "undefined" && value instanceof Uint8Array) return this.placeholderFor(ctx.inferMediaType());
177
+ if (this.visited.has(value)) return null;
178
+ this.visited.add(value);
179
+ if (Array.isArray(value)) return value.map((item) => this.walk(item, ctx));
180
+ const obj = value;
181
+ const out = {};
182
+ for (const k of Object.keys(obj)) out[k] = this.walk(obj[k], new MediaTypeContext(obj, k));
183
+ return out;
184
+ }
185
+ redactString(value, ctx) {
186
+ const hasExplicitBinaryMediaType = ctx.hasExplicitBinaryMediaType();
187
+ const recognitionValue = hasExplicitBinaryMediaType ? value.replace(/[\r\n]/g, "") : value;
188
+ const minLength = hasExplicitBinaryMediaType ? Math.min(recognitionValue.length, STRONG_CONTEXT_MIN_LENGTH) : ctx.signalsBinary() ? STRONG_CONTEXT_MIN_LENGTH : WEAK_CONTEXT_MIN_LENGTH;
189
+ const recognition = this.recognizer.recognize(recognitionValue, minLength);
190
+ switch (recognition.kind) {
191
+ case "data-url": return this.placeholderFor(recognition.mediaType);
192
+ case "raw": return this.placeholderFor(ctx.inferMediaType());
193
+ case "none": return value;
194
+ }
195
+ }
196
+ placeholderFor(mediaType) {
197
+ if (!mediaType) return "[base64 redacted]";
198
+ if (mediaType === "application/octet-stream") return "[base64 file redacted]";
199
+ return `[base64 ${mediaType} redacted]`;
200
+ }
201
+ };
202
+ //#endregion
203
+ //#region src/sanitization.ts
184
204
  const redactor = new BinaryContentRedactor();
185
205
  function redactBase64DataUrl(str, mediaType) {
186
- return redactor.redact(str, mediaType);
206
+ return redactor.redact(str, mediaType);
187
207
  }
188
208
  const sanitize = (data, client) => isFullAiCaptureEnabled(client) ? data : redactor.redact(data);
189
209
  const sanitizeGemini = (data, client) => sanitize(data, client);
190
-
191
- const TOKEN_PROPERTY_KEYS = new Set(['$ai_input_tokens', '$ai_output_tokens', '$ai_cache_read_input_tokens', '$ai_cache_creation_input_tokens', '$ai_total_tokens', '$ai_reasoning_tokens']);
192
-
210
+ //#endregion
211
+ //#region src/utils.ts
212
+ const TOKEN_PROPERTY_KEYS = /* @__PURE__ */ new Set([
213
+ "$ai_input_tokens",
214
+ "$ai_output_tokens",
215
+ "$ai_cache_read_input_tokens",
216
+ "$ai_cache_creation_input_tokens",
217
+ "$ai_total_tokens",
218
+ "$ai_reasoning_tokens"
219
+ ]);
193
220
  /**
194
- * Whether the caller supplied their own token counts, which override the ones the SDK
195
- * derived from the provider response.
196
- */
221
+ * Whether the caller supplied their own token counts, which override the ones the SDK
222
+ * derived from the provider response.
223
+ */
197
224
  function hasTokenOverrides(posthogProperties) {
198
- return !!posthogProperties && Object.keys(posthogProperties).some(key => TOKEN_PROPERTY_KEYS.has(key));
225
+ return !!posthogProperties && Object.keys(posthogProperties).some((key) => TOKEN_PROPERTY_KEYS.has(key));
199
226
  }
200
227
  function getTokensSource(posthogProperties) {
201
- return hasTokenOverrides(posthogProperties) ? 'passthrough' : 'sdk';
228
+ return hasTokenOverrides(posthogProperties) ? "passthrough" : "sdk";
202
229
  }
203
- const STRING_FORMAT = 'utf8';
204
-
205
- // Reused across calls to avoid per-invocation allocation; truncate() runs
206
- // hundreds of times for prompts with many parts.
230
+ const STRING_FORMAT = "utf8";
207
231
  new TextEncoder();
208
- new TextDecoder(STRING_FORMAT, {
209
- fatal: false
210
- });
211
-
232
+ new TextDecoder(STRING_FORMAT, { fatal: false });
212
233
  /**
213
- * Safely converts content to a string, preserving structure for objects/arrays.
214
- * - If content is already a string, returns it as-is
215
- * - If content is an object or array, stringifies it with JSON.stringify to preserve structure
216
- * - Otherwise, converts to string with String()
217
- *
218
- * This prevents the "[object Object]" bug when objects are naively converted to strings.
219
- *
220
- * @param content - The content to convert to a string
221
- * @returns A string representation that preserves structure for complex types
222
- */
234
+ * Safely converts content to a string, preserving structure for objects/arrays.
235
+ * - If content is already a string, returns it as-is
236
+ * - If content is an object or array, stringifies it with JSON.stringify to preserve structure
237
+ * - Otherwise, converts to string with String()
238
+ *
239
+ * This prevents the "[object Object]" bug when objects are naively converted to strings.
240
+ *
241
+ * @param content - The content to convert to a string
242
+ * @returns A string representation that preserves structure for complex types
243
+ */
223
244
  function toContentString(content) {
224
- if (typeof content === 'string') {
225
- return content;
226
- }
227
- if (content !== undefined && content !== null && typeof content === 'object') {
228
- try {
229
- return JSON.stringify(content);
230
- } catch {
231
- // Fallback for circular refs, BigInt, or objects with throwing toJSON
232
- return String(content);
233
- }
234
- }
235
- return String(content);
245
+ if (typeof content === "string") return content;
246
+ if (content !== void 0 && content !== null && typeof content === "object") try {
247
+ return JSON.stringify(content);
248
+ } catch {
249
+ return String(content);
250
+ }
251
+ return String(content);
236
252
  }
237
253
  const buildInlineDataBlock = (mimeType, data) => {
238
- if (mimeType.startsWith('audio/')) {
239
- return {
240
- type: 'audio',
241
- mime_type: mimeType,
242
- data
243
- };
244
- }
245
- if (mimeType.startsWith('image/')) {
246
- return {
247
- type: 'image',
248
- inline_data: {
249
- mime_type: mimeType,
250
- data
251
- }
252
- };
253
- }
254
- return {
255
- type: 'document',
256
- inline_data: {
257
- mime_type: mimeType,
258
- data
259
- }
260
- };
254
+ if (mimeType.startsWith("audio/")) return {
255
+ type: "audio",
256
+ mime_type: mimeType,
257
+ data
258
+ };
259
+ if (mimeType.startsWith("image/")) return {
260
+ type: "image",
261
+ inline_data: {
262
+ mime_type: mimeType,
263
+ data
264
+ }
265
+ };
266
+ return {
267
+ type: "document",
268
+ inline_data: {
269
+ mime_type: mimeType,
270
+ data
271
+ }
272
+ };
261
273
  };
262
274
  const formatInlineDataBlock = (inlineData, client) => {
263
- const mimeType = inlineData.mimeType || inlineData.mime_type || 'application/octet-stream';
264
- let data = inlineData.data;
265
- if (data instanceof Uint8Array) {
266
- if (typeof Buffer !== 'undefined') {
267
- data = Buffer.from(data).toString('base64');
268
- } else {
269
- let binary = '';
270
- for (let i = 0; i < data.length; i++) {
271
- binary += String.fromCharCode(data[i]);
272
- }
273
- data = btoa(binary);
274
- }
275
- }
276
- data = isFullAiCaptureEnabled(client) ? data : redactBase64DataUrl(data, mimeType);
277
- return buildInlineDataBlock(mimeType, String(data ?? ''));
275
+ const mimeType = inlineData.mimeType || inlineData.mime_type || "application/octet-stream";
276
+ let data = inlineData.data;
277
+ if (data instanceof Uint8Array) {
278
+ if (typeof Buffer !== "undefined") data = Buffer.from(data).toString("base64");
279
+ else {
280
+ let binary = "";
281
+ for (let i = 0; i < data.length; i++) binary += String.fromCharCode(data[i]);
282
+ data = btoa(binary);
283
+ }
284
+ }
285
+ data = isFullAiCaptureEnabled(client) ? data : redactBase64DataUrl(data, mimeType);
286
+ return buildInlineDataBlock(mimeType, String(data ?? ""));
278
287
  };
279
288
  const formatResponseGemini = (response, client) => {
280
- const output = [];
281
- if (response.candidates && Array.isArray(response.candidates)) {
282
- for (const candidate of response.candidates) {
283
- if (candidate.content && candidate.content.parts) {
284
- const content = [];
285
- for (const part of candidate.content.parts) {
286
- if (part.text) {
287
- content.push({
288
- type: 'text',
289
- text: part.text
290
- });
291
- } else if (part.functionCall) {
292
- content.push({
293
- type: 'function',
294
- function: {
295
- name: part.functionCall.name,
296
- arguments: part.functionCall.args
297
- }
298
- });
299
- } else if (part.inlineData) {
300
- content.push(formatInlineDataBlock(part.inlineData, client));
301
- }
302
- }
303
- if (content.length > 0) {
304
- output.push({
305
- role: 'assistant',
306
- content
307
- });
308
- }
309
- } else if (candidate.text) {
310
- output.push({
311
- role: 'assistant',
312
- content: [{
313
- type: 'text',
314
- text: candidate.text
315
- }]
316
- });
317
- }
318
- }
319
- } else if (response.text) {
320
- output.push({
321
- role: 'assistant',
322
- content: [{
323
- type: 'text',
324
- text: response.text
325
- }]
326
- });
327
- }
328
- return output;
289
+ const output = [];
290
+ if (response.candidates && Array.isArray(response.candidates)) {
291
+ for (const candidate of response.candidates) if (candidate.content && candidate.content.parts) {
292
+ const content = [];
293
+ for (const part of candidate.content.parts) if (part.text) content.push({
294
+ type: "text",
295
+ text: part.text
296
+ });
297
+ else if (part.functionCall) content.push({
298
+ type: "function",
299
+ function: {
300
+ name: part.functionCall.name,
301
+ arguments: part.functionCall.args
302
+ }
303
+ });
304
+ else if (part.inlineData) content.push(formatInlineDataBlock(part.inlineData, client));
305
+ if (content.length > 0) output.push({
306
+ role: "assistant",
307
+ content
308
+ });
309
+ } else if (candidate.text) output.push({
310
+ role: "assistant",
311
+ content: [{
312
+ type: "text",
313
+ text: candidate.text
314
+ }]
315
+ });
316
+ } else if (response.text) output.push({
317
+ role: "assistant",
318
+ content: [{
319
+ type: "text",
320
+ text: response.text
321
+ }]
322
+ });
323
+ return output;
329
324
  };
330
325
  const withPrivacyMode = (client, privacyMode, input) => {
331
- return client.privacy_mode || privacyMode ? null : input;
326
+ return client.privacy_mode || privacyMode ? null : input;
332
327
  };
333
- let AIEvent = /*#__PURE__*/function (AIEvent) {
334
- AIEvent["Generation"] = "$ai_generation";
335
- AIEvent["Embedding"] = "$ai_embedding";
336
- return AIEvent;
337
- }({});
338
328
  function sanitizeValues(obj) {
339
- if (obj === undefined || obj === null) {
340
- return obj;
341
- }
342
- const jsonSafe = JSON.parse(JSON.stringify(obj));
343
- if (typeof jsonSafe === 'string') {
344
- // Sanitize lone surrogates by round-tripping through UTF-8
345
- return new TextDecoder().decode(new TextEncoder().encode(jsonSafe));
346
- } else if (Array.isArray(jsonSafe)) {
347
- return jsonSafe.map(sanitizeValues);
348
- } else if (jsonSafe && typeof jsonSafe === 'object') {
349
- return Object.fromEntries(Object.entries(jsonSafe).map(([k, v]) => [k, sanitizeValues(v)]));
350
- }
351
- return jsonSafe;
329
+ if (obj === void 0 || obj === null) return obj;
330
+ const jsonSafe = JSON.parse(JSON.stringify(obj));
331
+ if (typeof jsonSafe === "string") return new TextDecoder().decode(new TextEncoder().encode(jsonSafe));
332
+ else if (Array.isArray(jsonSafe)) return jsonSafe.map(sanitizeValues);
333
+ else if (jsonSafe && typeof jsonSafe === "object") return Object.fromEntries(Object.entries(jsonSafe).map(([k, v]) => [k, sanitizeValues(v)]));
334
+ return jsonSafe;
352
335
  }
353
-
336
+ //#endregion
337
+ //#region src/serializeError.ts
354
338
  const DEFAULT_MAX_DEPTH = 3;
355
339
  const MAX_STACK_LINES = 20;
356
340
  function serializeError(value, depth = DEFAULT_MAX_DEPTH) {
357
- if (depth < 0 || value === null || typeof value !== 'object') {
358
- return value;
359
- }
360
- if (value instanceof Error) {
361
- const out = {
362
- name: value.name,
363
- message: value.message,
364
- stack: truncateStack(value.stack)
365
- };
366
- for (const key of Object.keys(value)) {
367
- out[key] = serializeError(value[key], depth - 1);
368
- }
369
- if (value.cause !== undefined) {
370
- out.cause = serializeError(value.cause, depth - 1);
371
- }
372
- return out;
373
- }
374
- if (Array.isArray(value)) {
375
- return value.map(item => serializeError(item, depth - 1));
376
- }
377
- return value;
341
+ if (depth < 0 || value === null || typeof value !== "object") return value;
342
+ if (value instanceof Error) {
343
+ const out = {
344
+ name: value.name,
345
+ message: value.message,
346
+ stack: truncateStack(value.stack)
347
+ };
348
+ for (const key of Object.keys(value)) out[key] = serializeError(value[key], depth - 1);
349
+ if (value.cause !== void 0) out.cause = serializeError(value.cause, depth - 1);
350
+ return out;
351
+ }
352
+ if (Array.isArray(value)) return value.map((item) => serializeError(item, depth - 1));
353
+ return value;
378
354
  }
379
355
  function stringifyError(error) {
380
- try {
381
- return JSON.stringify(sanitizeValues(serializeError(error)));
382
- } catch {
383
- if (error instanceof Error) {
384
- return JSON.stringify({
385
- name: error.name,
386
- message: error.message
387
- });
388
- }
389
- return JSON.stringify({
390
- message: String(error)
391
- });
392
- }
356
+ try {
357
+ return JSON.stringify(sanitizeValues(serializeError(error)));
358
+ } catch {
359
+ if (error instanceof Error) return JSON.stringify({
360
+ name: error.name,
361
+ message: error.message
362
+ });
363
+ return JSON.stringify({ message: String(error) });
364
+ }
393
365
  }
394
366
  function truncateStack(stack) {
395
- if (!stack) {
396
- return stack;
397
- }
398
- const lines = stack.split('\n');
399
- if (lines.length <= MAX_STACK_LINES) {
400
- return stack;
401
- }
402
- return [...lines.slice(0, MAX_STACK_LINES), '... (truncated)'].join('\n');
367
+ if (!stack) return stack;
368
+ const lines = stack.split("\n");
369
+ if (lines.length <= MAX_STACK_LINES) return stack;
370
+ return [...lines.slice(0, MAX_STACK_LINES), "... (truncated)"].join("\n");
403
371
  }
404
-
405
- // Warn when a wrapper's base_url points at the PostHog AI Gateway: the gateway
406
- // emits its own $ai_generation, so each call would be captured (and, for billable
407
- // products, billed) twice. We only warn — the wrapper's event carries data the
408
- // gateway never sees (groups, custom properties, trace hierarchy).
409
-
410
- // Keep in sync with the gateway's deployed hosts (see services/llm-gateway in the
411
- // main repo). gateway.us.posthog.com is live today; the rest are listed ahead of
412
- // any traffic moving to them.
413
- const POSTHOG_AI_GATEWAY_HOSTS = ['gateway.posthog.com', 'gateway.us.posthog.com', 'gateway.eu.posthog.com', 'ai-gateway.us.posthog.com', 'ai-gateway.eu.posthog.com'];
414
-
415
- // Swap for the dedicated AI Gateway page once it ships.
416
- const GATEWAY_DOCS_URL = 'https://posthog.com/docs/ai-observability';
417
- const extractHost = baseURL => {
418
- try {
419
- // Tolerate bare hosts that omit a scheme, e.g. "gateway.us.posthog.com/v1".
420
- const hasScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(baseURL);
421
- return new URL(hasScheme ? baseURL : `https://${baseURL}`).hostname.toLowerCase();
422
- } catch {
423
- return undefined;
424
- }
372
+ //#endregion
373
+ //#region src/gatewayWarning.ts
374
+ const POSTHOG_AI_GATEWAY_HOSTS = [
375
+ "gateway.posthog.com",
376
+ "gateway.us.posthog.com",
377
+ "gateway.eu.posthog.com",
378
+ "ai-gateway.us.posthog.com",
379
+ "ai-gateway.eu.posthog.com"
380
+ ];
381
+ const GATEWAY_DOCS_URL = "https://posthog.com/docs/ai-observability";
382
+ const extractHost = (baseURL) => {
383
+ try {
384
+ const hasScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(baseURL);
385
+ return new URL(hasScheme ? baseURL : `https://${baseURL}`).hostname.toLowerCase();
386
+ } catch {
387
+ return;
388
+ }
425
389
  };
426
- const isPostHogAiGatewayUrl = baseURL => {
427
- if (!baseURL) {
428
- return false;
429
- }
430
- const host = extractHost(baseURL);
431
- return host !== undefined && POSTHOG_AI_GATEWAY_HOSTS.includes(host);
390
+ const isPostHogAiGatewayUrl = (baseURL) => {
391
+ if (!baseURL) return false;
392
+ const host = extractHost(baseURL);
393
+ return host !== void 0 && POSTHOG_AI_GATEWAY_HOSTS.includes(host);
432
394
  };
433
-
434
- // Warns on every gateway call by design: the misconfiguration is impossible to
435
- // miss that way, and a doubled bill is worse than noisy logs.
436
- const warnIfPostHogAiGateway = baseURL => {
437
- if (!isPostHogAiGatewayUrl(baseURL)) {
438
- return;
439
- }
440
- console.warn('[PostHog] The PostHog AI wrapper is pointed at the PostHog AI Gateway. ' + 'Both capture $ai_generation, so every call is double-counted and double-billed. ' + `Use one or the other — see ${GATEWAY_DOCS_URL}.`);
395
+ const warnIfPostHogAiGateway = (baseURL) => {
396
+ if (!isPostHogAiGatewayUrl(baseURL)) return;
397
+ console.warn(`[PostHog] The PostHog AI wrapper is pointed at the PostHog AI Gateway. Both capture \$ai_generation, so every call is double-counted and double-billed. Use one or the other see ${GATEWAY_DOCS_URL}.`);
441
398
  };
442
-
399
+ //#endregion
400
+ //#region src/captureAiGeneration.ts
443
401
  /**
444
- * Options for `captureAiGeneration`. Mirrors the `$ai_generation` event shape
445
- * directly so that any caller — first-party SDK wrappers and external code
446
- * alike produces an identical event.
447
- */
448
-
449
- /**
450
- * Capture an `$ai_generation` (or `$ai_embedding`) event to PostHog.
451
- *
452
- * This is the canonical primitive that every `@posthog/ai` wrapper
453
- * (`withTracing`, `OpenAI`, `Anthropic`, `GoogleGenAI`, …) funnels through, so
454
- * external code can use it directly to instrument LLM calls made through
455
- * arbitrary clients (Cloudflare Workers AI, custom HTTP, etc.) and get the
456
- * same events the SDK wrappers produce.
457
- *
458
- * When `error` is set, the event is captured as an error. If the error is an
459
- * object, it is mutated in place to set `__posthog_previously_captured_error`
460
- * so callers can re-throw the original error reference safely.
461
- */
402
+ * Capture an `$ai_generation` (or `$ai_embedding`) event to PostHog.
403
+ *
404
+ * This is the canonical primitive that every `@posthog/ai` wrapper
405
+ * (`withTracing`, `OpenAI`, `Anthropic`, `GoogleGenAI`, …) funnels through, so
406
+ * external code can use it directly to instrument LLM calls made through
407
+ * arbitrary clients (Cloudflare Workers AI, custom HTTP, etc.) and get the
408
+ * same events the SDK wrappers produce.
409
+ *
410
+ * When `error` is set, the event is captured as an error. If the error is an
411
+ * object, it is mutated in place to set `__posthog_previously_captured_error`
412
+ * so callers can re-throw the original error reference safely.
413
+ */
462
414
  const captureAiGeneration = async (client, options) => {
463
- try {
464
- if (!client.capture) {
465
- return;
466
- }
467
- warnIfPostHogAiGateway(options.baseURL);
468
- const traceId = options.traceId ?? v4();
469
- const eventType = options.eventType ?? AIEvent.Generation;
470
- const privacyMode = options.privacyMode ?? false;
471
- const usage = options.usage ?? {};
472
-
473
- // Check privacy before reading or traversing input/output. Besides avoiding
474
- // needless work, this ensures hostile getters/proxies cannot observe a value
475
- // that the caller explicitly requested us to redact.
476
- const shouldRedact = withPrivacyMode(client, privacyMode, false) === null;
477
- const safeInput = shouldRedact ? null : toJsonSafeValue(options.input);
478
- const safeOutput = shouldRedact ? null : toJsonSafeValue(options.output);
479
- let httpStatus = options.httpStatus;
480
- let errorData = {};
481
- if (options.error) {
482
- if (httpStatus === undefined) {
483
- if (typeof options.error === 'object' && 'status' in options.error && typeof options.error.status === 'number') {
484
- httpStatus = options.error.status;
485
- } else if (typeof options.error === 'object' && 'statusCode' in options.error && typeof options.error.statusCode === 'number') {
486
- httpStatus = options.error.statusCode;
487
- } else {
488
- httpStatus = 500;
489
- }
490
- }
491
- let exceptionId;
492
- if (client.options?.enableExceptionAutocapture) {
493
- exceptionId = uuidv7();
494
- client.captureException(options.error, undefined, {
495
- $ai_trace_id: traceId
496
- }, exceptionId);
497
- if (typeof options.error === 'object') {
498
- ;
499
- options.error.__posthog_previously_captured_error = true;
500
- }
501
- }
502
- errorData = {
503
- $ai_is_error: true,
504
- $ai_error: stringifyError(options.error),
505
- $exception_event_id: exceptionId
506
- };
507
- }
508
- httpStatus = httpStatus ?? 200;
509
-
510
- // A configured price applies only to a count the provider reported, so a call with no
511
- // reported usage sends no cost instead of asserting $0. $ai_total_cost_usd sums the sides
512
- // that were priced, which makes it the cost of the known side alone when the other side
513
- // went unreported: a lower bound on the true total, not an assertion of it.
514
- const costOverrideData = {};
515
- if (options.costOverride) {
516
- if (usage.inputTokens !== undefined) {
517
- costOverrideData.$ai_input_cost_usd = (options.costOverride.inputCost ?? 0) * usage.inputTokens;
518
- }
519
- if (usage.outputTokens !== undefined) {
520
- costOverrideData.$ai_output_cost_usd = (options.costOverride.outputCost ?? 0) * usage.outputTokens;
521
- }
522
- if (Object.keys(costOverrideData).length > 0) {
523
- costOverrideData.$ai_total_cost_usd = (costOverrideData.$ai_input_cost_usd ?? 0) + (costOverrideData.$ai_output_cost_usd ?? 0);
524
- }
525
- }
526
-
527
- // The caller's own token counts override the SDK-derived ones further down, via the
528
- // `options.properties` spread.
529
- const tokensOverridden = hasTokenOverrides(options.properties);
530
- const additionalTokenValues = {
531
- ...(usage.reasoningTokens ? {
532
- $ai_reasoning_tokens: usage.reasoningTokens
533
- } : {}),
534
- ...(usage.cacheReadInputTokens ? {
535
- $ai_cache_read_input_tokens: usage.cacheReadInputTokens
536
- } : {}),
537
- ...(usage.cacheCreationInputTokens ? {
538
- $ai_cache_creation_input_tokens: usage.cacheCreationInputTokens
539
- } : {}),
540
- // Checked against undefined rather than truthiness, because false is the meaningful
541
- // value here and a truthiness guard would drop it.
542
- //
543
- // Dropped entirely when the caller overrides the token counts: the flag describes how
544
- // the SDK-derived counts relate to each other, so against passthrough counts it can be
545
- // wrong in the expensive direction. Declaring inclusive over counts that are actually
546
- // exclusive makes ingestion subtract the cache pool that was never in the input. A
547
- // caller who knows their own accounting model can still pass
548
- // `$ai_cache_reporting_exclusive` themselves, and that value wins.
549
- ...(usage.cacheReportingExclusive !== undefined && !tokensOverridden ? {
550
- $ai_cache_reporting_exclusive: usage.cacheReportingExclusive
551
- } : {}),
552
- ...(usage.webSearchCount ? {
553
- $ai_web_search_count: usage.webSearchCount
554
- } : {}),
555
- ...(usage.rawUsage ? {
556
- $ai_usage: usage.rawUsage
557
- } : {})
558
- };
559
- const properties = {
560
- $ai_lib: 'posthog-ai',
561
- $ai_lib_version: version,
562
- $ai_provider: options.providerOverride ?? options.provider,
563
- $ai_model: options.modelOverride ?? options.model,
564
- $ai_model_parameters: options.modelParameters ?? {},
565
- $ai_input: safeInput,
566
- $ai_output_choices: safeOutput,
567
- $ai_http_status: httpStatus,
568
- ...(usage.inputTokens !== undefined ? {
569
- $ai_input_tokens: usage.inputTokens
570
- } : {}),
571
- ...(usage.outputTokens !== undefined ? {
572
- $ai_output_tokens: usage.outputTokens
573
- } : {}),
574
- ...additionalTokenValues,
575
- ...(options.latency !== undefined ? {
576
- $ai_latency: options.latency
577
- } : {}),
578
- ...(options.timeToFirstToken !== undefined ? {
579
- $ai_time_to_first_token: options.timeToFirstToken
580
- } : {}),
581
- $ai_trace_id: traceId,
582
- ...(options.baseURL === null ? {} : {
583
- $ai_base_url: options.baseURL ?? ''
584
- }),
585
- ...options.properties,
586
- $ai_tokens_source: getTokensSource(options.properties),
587
- ...(options.distinctId ? {} : {
588
- $process_person_profile: false
589
- }),
590
- ...(options.stopReason ? {
591
- $ai_stop_reason: options.stopReason
592
- } : {}),
593
- ...(options.tools ? {
594
- $ai_tools: options.tools
595
- } : {}),
596
- ...(options.completionId ? {
597
- $ai_completion_id: options.completionId
598
- } : {}),
599
- ...(options.providerMetadata && Object.keys(options.providerMetadata).length > 0 ? {
600
- $ai_provider_metadata: options.providerMetadata
601
- } : {}),
602
- ...errorData,
603
- ...costOverrideData
604
- };
605
- const event = {
606
- distinctId: options.distinctId ?? traceId,
607
- event: eventType,
608
- properties,
609
- groups: options.groups
610
- };
611
- if (options.captureImmediate) {
612
- await captureAiEventImmediate(client, event);
613
- } else {
614
- captureAiEvent(client, event);
615
- }
616
- } catch (error) {
617
- // Telemetry failures must never affect the instrumented provider call.
618
- try {
619
- options.onError?.(error);
620
- } catch {
621
- // Error reporting must not affect the instrumented provider call either.
622
- }
623
- console.warn('[PostHog AI] Failed to capture generation telemetry:', error);
624
- }
415
+ try {
416
+ if (!client.capture) return;
417
+ warnIfPostHogAiGateway(options.baseURL);
418
+ const traceId = options.traceId ?? v4();
419
+ const eventType = options.eventType ?? "$ai_generation";
420
+ const privacyMode = options.privacyMode ?? false;
421
+ const usage = options.usage ?? {};
422
+ const shouldRedact = withPrivacyMode(client, privacyMode, false) === null;
423
+ const safeInput = shouldRedact ? null : toJsonSafeValue(options.input);
424
+ const safeOutput = shouldRedact ? null : toJsonSafeValue(options.output);
425
+ let httpStatus = options.httpStatus;
426
+ let errorData = {};
427
+ if (options.error) {
428
+ if (httpStatus === void 0) {
429
+ if (typeof options.error === "object" && "status" in options.error && typeof options.error.status === "number") httpStatus = options.error.status;
430
+ else if (typeof options.error === "object" && "statusCode" in options.error && typeof options.error.statusCode === "number") httpStatus = options.error.statusCode;
431
+ else httpStatus = 500;
432
+ }
433
+ let exceptionId;
434
+ if (client.options?.enableExceptionAutocapture) {
435
+ exceptionId = uuidv7();
436
+ client.captureException(options.error, void 0, { $ai_trace_id: traceId }, exceptionId);
437
+ if (typeof options.error === "object") options.error.__posthog_previously_captured_error = true;
438
+ }
439
+ errorData = {
440
+ $ai_is_error: true,
441
+ $ai_error: stringifyError(options.error),
442
+ $exception_event_id: exceptionId
443
+ };
444
+ }
445
+ httpStatus = httpStatus ?? 200;
446
+ const costOverrideData = {};
447
+ if (options.costOverride) {
448
+ if (usage.inputTokens !== void 0) costOverrideData.$ai_input_cost_usd = (options.costOverride.inputCost ?? 0) * usage.inputTokens;
449
+ if (usage.outputTokens !== void 0) costOverrideData.$ai_output_cost_usd = (options.costOverride.outputCost ?? 0) * usage.outputTokens;
450
+ if (Object.keys(costOverrideData).length > 0) costOverrideData.$ai_total_cost_usd = (costOverrideData.$ai_input_cost_usd ?? 0) + (costOverrideData.$ai_output_cost_usd ?? 0);
451
+ }
452
+ const tokensOverridden = hasTokenOverrides(options.properties);
453
+ const additionalTokenValues = {
454
+ ...usage.reasoningTokens ? { $ai_reasoning_tokens: usage.reasoningTokens } : {},
455
+ ...usage.cacheReadInputTokens ? { $ai_cache_read_input_tokens: usage.cacheReadInputTokens } : {},
456
+ ...usage.cacheCreationInputTokens ? { $ai_cache_creation_input_tokens: usage.cacheCreationInputTokens } : {},
457
+ ...usage.cacheReportingExclusive !== void 0 && !tokensOverridden ? { $ai_cache_reporting_exclusive: usage.cacheReportingExclusive } : {},
458
+ ...usage.webSearchCount ? { $ai_web_search_count: usage.webSearchCount } : {},
459
+ ...usage.rawUsage ? { $ai_usage: usage.rawUsage } : {}
460
+ };
461
+ const properties = {
462
+ $ai_lib: "posthog-ai",
463
+ $ai_lib_version: version,
464
+ $ai_provider: options.providerOverride ?? options.provider,
465
+ $ai_model: options.modelOverride ?? options.model,
466
+ $ai_model_parameters: options.modelParameters ?? {},
467
+ $ai_input: safeInput,
468
+ $ai_output_choices: safeOutput,
469
+ $ai_http_status: httpStatus,
470
+ ...usage.inputTokens !== void 0 ? { $ai_input_tokens: usage.inputTokens } : {},
471
+ ...usage.outputTokens !== void 0 ? { $ai_output_tokens: usage.outputTokens } : {},
472
+ ...additionalTokenValues,
473
+ ...options.latency !== void 0 ? { $ai_latency: options.latency } : {},
474
+ ...options.timeToFirstToken !== void 0 ? { $ai_time_to_first_token: options.timeToFirstToken } : {},
475
+ $ai_trace_id: traceId,
476
+ ...options.baseURL === null ? {} : { $ai_base_url: options.baseURL ?? "" },
477
+ ...options.properties,
478
+ $ai_tokens_source: getTokensSource(options.properties),
479
+ ...options.distinctId ? {} : { $process_person_profile: false },
480
+ ...options.stopReason ? { $ai_stop_reason: options.stopReason } : {},
481
+ ...options.tools ? { $ai_tools: options.tools } : {},
482
+ ...options.completionId ? { $ai_completion_id: options.completionId } : {},
483
+ ...options.providerMetadata && Object.keys(options.providerMetadata).length > 0 ? { $ai_provider_metadata: options.providerMetadata } : {},
484
+ ...errorData,
485
+ ...costOverrideData
486
+ };
487
+ const event = {
488
+ distinctId: options.distinctId ?? traceId,
489
+ event: eventType,
490
+ properties,
491
+ groups: options.groups
492
+ };
493
+ if (options.captureImmediate) await captureAiEventImmediate(client, event);
494
+ else captureAiEvent(client, event);
495
+ } catch (error) {
496
+ try {
497
+ options.onError?.(error);
498
+ } catch {}
499
+ console.warn("[PostHog AI] Failed to capture generation telemetry:", error);
500
+ }
625
501
  };
626
-
502
+ //#endregion
503
+ //#region src/gemini/usage.ts
627
504
  /** Map Gemini usage metadata to PostHog's provider-agnostic token fields. */
628
505
  function mapGeminiUsage(metadata, additionalUsage = {}) {
629
- return {
630
- inputTokens: metadata?.promptTokenCount ?? 0,
631
- outputTokens: metadata?.candidatesTokenCount ?? 0,
632
- reasoningTokens: metadata?.thoughtsTokenCount ?? 0,
633
- cacheReadInputTokens: metadata?.cachedContentTokenCount ?? 0,
634
- // Gemini counts cachedContentTokenCount inside promptTokenCount, so declare
635
- // the accounting model rather than leaving ingestion to infer it. Under
636
- // explicit context caching the two measurements can differ by a few percent.
637
- ...(metadata?.cachedContentTokenCount ? {
638
- cacheReportingExclusive: false
639
- } : {}),
640
- ...additionalUsage,
641
- rawUsage: metadata
642
- };
506
+ return {
507
+ inputTokens: metadata?.promptTokenCount ?? 0,
508
+ outputTokens: metadata?.candidatesTokenCount ?? 0,
509
+ reasoningTokens: metadata?.thoughtsTokenCount ?? 0,
510
+ cacheReadInputTokens: metadata?.cachedContentTokenCount ?? 0,
511
+ ...metadata?.cachedContentTokenCount ? { cacheReportingExclusive: false } : {},
512
+ ...additionalUsage,
513
+ rawUsage: metadata
514
+ };
643
515
  }
644
-
645
- /**
646
- * Resolver for the PostHog distinct ID. Either a static string, or a function
647
- * that derives it from the ADK model callback context (e.g. from
648
- * `context.userId`). Return `null`/`undefined` to fall back to the ADK
649
- * `userId`, and finally to anonymous (personless) capture keyed by trace ID.
650
- */
651
-
516
+ //#endregion
517
+ //#region src/adk/plugin.ts
652
518
  /** Calls older than this are treated as abandoned rather than evicting live calls by count. */
653
- const MAX_PENDING_AGE_MS = 60 * 60 * 1000;
654
-
519
+ const MAX_PENDING_AGE_MS = 36e5;
655
520
  /**
656
- * A Google ADK (`@google/adk`) `BasePlugin` that captures PostHog AI traces,
657
- * agent and tool spans, and a full `$ai_generation` event for every model call.
658
- *
659
- * Run, agent, and tool callbacks build the trace hierarchy. Model callbacks
660
- * record input, output, model, token usage, latency, and finish reason through
661
- * the shared {@link captureAiGeneration} primitive so PostHog derives cost from
662
- * the model and tokens (never hardcoded here).
663
- *
664
- * ADK already emits OpenTelemetry `gen_ai.*` spans; this plugin is the
665
- * complement for users who capture LLM analytics through the PostHog SDK rather
666
- * than an OTEL exporter.
667
- *
668
- * @example
669
- * ```typescript
670
- * import { PostHogADKPlugin } from '@posthog/ai/adk'
671
- * import { Runner } from '@google/adk'
672
- * import { PostHog } from 'posthog-node'
673
- *
674
- * const phClient = new PostHog('<POSTHOG_API_KEY>')
675
- *
676
- * const runner = new Runner({
677
- * appName: 'my-app',
678
- * agent,
679
- * sessionService,
680
- * plugins: [new PostHogADKPlugin({ client: phClient, distinctId: 'user@example.com' })],
681
- * })
682
- * ```
683
- */
684
- class PostHogADKPlugin extends BasePlugin {
685
- /** FIFO of in-flight model calls for each invocation branch and agent. */
686
- _pending = new Map();
687
- _traces = new Map();
688
- _pendingAgents = new Map();
689
- _pendingTools = new Map();
690
- constructor(options) {
691
- super('posthog');
692
- this._client = options.client;
693
- this._distinctId = options.distinctId;
694
- this._provider = options.provider ?? 'gemini';
695
- this._privacyMode = options.privacyMode ?? false;
696
- this._groups = options.groups;
697
- this._properties = options.properties ?? {};
698
- this._captureImmediate = options.captureImmediate ?? false;
699
- this._onError = options.onError;
700
- }
701
- async beforeRunCallback({
702
- invocationContext
703
- }) {
704
- try {
705
- this._evictStalePending();
706
- this._traces.set(invocationContext.invocationId, {
707
- startTime: Date.now(),
708
- spanId: invocationContext.invocationId,
709
- name: invocationContext.agent?.name ?? 'ADK invocation',
710
- input: invocationContext.userContent,
711
- distinctId: this._resolveInvocationDistinctId(invocationContext),
712
- sessionId: invocationContext.session?.id
713
- });
714
- } catch (error) {
715
- this._handleError(error);
716
- }
717
- return undefined;
718
- }
719
- async afterRunCallback({
720
- invocationContext
721
- }) {
722
- try {
723
- const trace = this._traces.get(invocationContext.invocationId);
724
- this._traces.delete(invocationContext.invocationId);
725
- this._clearPendingInvocation(invocationContext.invocationId);
726
- if (!trace) {
727
- return;
728
- }
729
- await this._captureLifecycleEvent('$ai_trace', trace.distinctId, {
730
- $ai_trace_id: invocationContext.invocationId,
731
- $ai_span_id: trace.spanId,
732
- $ai_span_name: trace.name,
733
- $ai_input_state: withPrivacyMode(this._client, this._privacyMode, trace.input),
734
- $ai_latency: (Date.now() - trace.startTime) / 1000,
735
- ...(trace.sessionId ? {
736
- $ai_session_id: trace.sessionId
737
- } : {})
738
- });
739
- } catch (error) {
740
- this._handleError(error);
741
- }
742
- }
743
- async beforeAgentCallback({
744
- agent,
745
- callbackContext
746
- }) {
747
- try {
748
- this._evictStalePending();
749
- this._rememberContext(callbackContext);
750
- const key = this._pendingKey(callbackContext);
751
- const pending = {
752
- startTime: Date.now(),
753
- spanId: v4(),
754
- name: agent.name,
755
- input: callbackContext.userContent
756
- };
757
- const queue = this._pendingAgents.get(key);
758
- if (queue) {
759
- queue.push(pending);
760
- } else {
761
- this._pendingAgents.set(key, [pending]);
762
- }
763
- } catch (error) {
764
- this._handleError(error);
765
- }
766
- return undefined;
767
- }
768
- async afterAgentCallback({
769
- callbackContext
770
- }) {
771
- try {
772
- const pending = this._takePendingAgent(this._pendingKey(callbackContext));
773
- if (pending) {
774
- await this._captureLifecycleEvent('$ai_span', this._resolveDistinctId(callbackContext), {
775
- $ai_trace_id: callbackContext.invocationId,
776
- $ai_span_id: pending.spanId,
777
- ...(this._traces.get(callbackContext.invocationId)?.spanId ? {
778
- $ai_parent_id: this._traces.get(callbackContext.invocationId)?.spanId
779
- } : {}),
780
- $ai_span_name: pending.name,
781
- $ai_input_state: withPrivacyMode(this._client, this._privacyMode, pending.input),
782
- $ai_latency: (Date.now() - pending.startTime) / 1000,
783
- ...(callbackContext.sessionId ? {
784
- $ai_session_id: callbackContext.sessionId
785
- } : {}),
786
- ...(callbackContext.agentName ? {
787
- $ai_agent_name: callbackContext.agentName
788
- } : {})
789
- });
790
- }
791
- } catch (error) {
792
- this._handleError(error);
793
- }
794
- return undefined;
795
- }
796
- async beforeModelCallback({
797
- callbackContext,
798
- llmRequest
799
- }) {
800
- try {
801
- this._evictStalePending();
802
- this._rememberContext(callbackContext);
803
- const pending = {
804
- startTime: Date.now(),
805
- spanId: v4(),
806
- input: this._formatInput(llmRequest),
807
- model: llmRequest.model,
808
- modelParameters: extractModelParameters(llmRequest.config),
809
- tools: extractTools(llmRequest),
810
- streamedOutput: []
811
- };
812
- const key = this._pendingKey(callbackContext);
813
- const queue = this._pending.get(key);
814
- if (queue) {
815
- queue.push(pending);
816
- } else {
817
- this._pending.set(key, [pending]);
818
- }
819
- } catch (error) {
820
- this._handleError(error);
821
- }
822
- return undefined;
823
- }
824
- async afterModelCallback({
825
- callbackContext,
826
- llmResponse
827
- }) {
828
- try {
829
- // Streaming delivers partial responses before the terminal one; the
830
- // terminal response carries the full content and usage, so only emit then.
831
- if (llmResponse.partial) {
832
- return undefined;
833
- }
834
- const key = this._pendingKey(callbackContext);
835
- const pending = this._peekPending(key);
836
- if (this._isNonTerminalStreamResponse(llmResponse)) {
837
- if (pending) {
838
- pending.streamedOutput.push(...this._formatOutput(llmResponse));
839
- }
840
- return undefined;
841
- }
842
- const completedPending = this._takePending(key);
843
- const error = llmResponse.errorCode ? new Error(llmResponse.errorMessage ?? String(llmResponse.errorCode)) : undefined;
844
- const output = error ? [] : this._formatOutput(llmResponse);
845
- await this._capture(callbackContext, {
846
- pending: completedPending,
847
- output: !error && output.length === 0 && completedPending?.streamedOutput.length ? completedPending.streamedOutput : output,
848
- model: llmResponse.modelVersion ?? completedPending?.model,
849
- usage: llmResponse.usageMetadata,
850
- stopReason: llmResponse.finishReason ? String(llmResponse.finishReason) : undefined,
851
- error
852
- });
853
- } catch (error) {
854
- this._handleError(error);
855
- }
856
- return undefined;
857
- }
858
- async onModelErrorCallback({
859
- callbackContext,
860
- llmRequest,
861
- error
862
- }) {
863
- try {
864
- const pending = this._takePending(this._pendingKey(callbackContext));
865
- await this._capture(callbackContext, {
866
- pending: pending ?? {
867
- startTime: Date.now(),
868
- spanId: v4(),
869
- input: this._formatInput(llmRequest),
870
- model: llmRequest.model,
871
- modelParameters: extractModelParameters(llmRequest.config),
872
- tools: extractTools(llmRequest),
873
- streamedOutput: []
874
- },
875
- output: [],
876
- model: llmRequest.model,
877
- usage: undefined,
878
- error
879
- });
880
- } catch (captureError) {
881
- this._handleError(captureError);
882
- }
883
- return undefined;
884
- }
885
- async beforeToolCallback({
886
- tool,
887
- toolArgs,
888
- toolContext
889
- }) {
890
- try {
891
- this._evictStalePending();
892
- this._rememberContext(toolContext);
893
- const key = this._toolKey(toolContext, tool.name);
894
- const pending = {
895
- startTime: Date.now(),
896
- spanId: toolContext.functionCallId ?? v4(),
897
- name: tool.name,
898
- input: toolArgs
899
- };
900
- const queue = this._pendingTools.get(key);
901
- if (queue) {
902
- queue.push(pending);
903
- } else {
904
- this._pendingTools.set(key, [pending]);
905
- }
906
- } catch (error) {
907
- this._handleError(error);
908
- }
909
- return undefined;
910
- }
911
- async afterToolCallback({
912
- tool,
913
- toolContext,
914
- result
915
- }) {
916
- try {
917
- const pending = this._takePendingTool(this._toolKey(toolContext, tool.name));
918
- if (pending) {
919
- await this._captureToolSpan(toolContext, pending, result);
920
- }
921
- } catch (error) {
922
- this._handleError(error);
923
- }
924
- return undefined;
925
- }
926
- async onToolErrorCallback({
927
- tool,
928
- toolContext,
929
- error
930
- }) {
931
- try {
932
- const pending = this._takePendingTool(this._toolKey(toolContext, tool.name));
933
- if (pending) {
934
- await this._captureToolSpan(toolContext, pending, undefined, error);
935
- }
936
- } catch (captureError) {
937
- this._handleError(captureError);
938
- }
939
- return undefined;
940
- }
941
- async _capture(callbackContext, args) {
942
- const {
943
- pending,
944
- output,
945
- model,
946
- usage,
947
- stopReason,
948
- error
949
- } = args;
950
- const latency = pending ? (Date.now() - pending.startTime) / 1000 : undefined;
951
- await captureAiGeneration(this._client, {
952
- distinctId: this._resolveDistinctId(callbackContext),
953
- traceId: callbackContext.invocationId,
954
- model,
955
- provider: this._provider,
956
- baseURL: null,
957
- input: pending?.input ?? [],
958
- output,
959
- latency,
960
- modelParameters: pending?.modelParameters,
961
- usage: mapGeminiUsage(usage),
962
- stopReason,
963
- tools: pending?.tools,
964
- groups: this._groups,
965
- privacyMode: this._privacyMode,
966
- captureImmediate: this._captureImmediate,
967
- onError: this._onError,
968
- properties: {
969
- $ai_framework: 'google-adk',
970
- $ai_span_id: pending?.spanId ?? v4(),
971
- ...(this._parentSpanId(callbackContext) ? {
972
- $ai_parent_id: this._parentSpanId(callbackContext)
973
- } : {}),
974
- ...(callbackContext.sessionId ? {
975
- $ai_session_id: callbackContext.sessionId
976
- } : {}),
977
- ...(callbackContext.agentName ? {
978
- $ai_agent_name: callbackContext.agentName,
979
- $ai_span_name: callbackContext.agentName
980
- } : {}),
981
- ...this._properties
982
- },
983
- error
984
- });
985
- }
986
- async _captureToolSpan(context, pending, result, error) {
987
- await this._captureLifecycleEvent('$ai_span', this._resolveDistinctId(context), {
988
- $ai_trace_id: context.invocationId,
989
- $ai_span_id: pending.spanId,
990
- ...(this._parentSpanId(context) ? {
991
- $ai_parent_id: this._parentSpanId(context)
992
- } : {}),
993
- $ai_span_name: pending.name,
994
- $ai_input_state: withPrivacyMode(this._client, this._privacyMode, pending.input),
995
- ...(result !== undefined ? {
996
- $ai_output_state: withPrivacyMode(this._client, this._privacyMode, result)
997
- } : {}),
998
- $ai_latency: (Date.now() - pending.startTime) / 1000,
999
- ...(context.sessionId ? {
1000
- $ai_session_id: context.sessionId
1001
- } : {}),
1002
- ...(context.agentName ? {
1003
- $ai_agent_name: context.agentName
1004
- } : {}),
1005
- ...(error ? {
1006
- $ai_is_error: true,
1007
- $ai_error: stringifyError(error)
1008
- } : {})
1009
- });
1010
- }
1011
- async _captureLifecycleEvent(event, distinctId, properties) {
1012
- const message = {
1013
- distinctId: distinctId ?? String(properties.$ai_trace_id),
1014
- event,
1015
- properties: {
1016
- $ai_lib: 'posthog-ai',
1017
- $ai_lib_version: version,
1018
- $ai_framework: 'google-adk',
1019
- ...properties,
1020
- ...this._properties,
1021
- ...(distinctId ? {} : {
1022
- $process_person_profile: false
1023
- })
1024
- },
1025
- groups: this._groups
1026
- };
1027
- if (this._captureImmediate) {
1028
- await captureAiEventImmediate(this._client, message);
1029
- } else {
1030
- captureAiEvent(this._client, message);
1031
- }
1032
- }
1033
- _resolveDistinctId(context) {
1034
- if (typeof this._distinctId === 'function') {
1035
- const resolved = this._distinctId(context);
1036
- if (resolved) {
1037
- return String(resolved);
1038
- }
1039
- } else if (this._distinctId) {
1040
- return String(this._distinctId);
1041
- }
1042
- return context.userId ? String(context.userId) : undefined;
1043
- }
1044
- _resolveInvocationDistinctId(context) {
1045
- if (typeof this._distinctId === 'string' && this._distinctId) {
1046
- return String(this._distinctId);
1047
- }
1048
- return context.userId ? String(context.userId) : undefined;
1049
- }
1050
- _rememberContext(context) {
1051
- const trace = this._traces.get(context.invocationId);
1052
- if (trace) {
1053
- trace.distinctId = this._resolveDistinctId(context);
1054
- trace.sessionId = context.sessionId || trace.sessionId;
1055
- }
1056
- }
1057
- _parentSpanId(context) {
1058
- return this._pendingAgents.get(this._pendingKey(context))?.[0]?.spanId ?? this._traces.get(context.invocationId)?.spanId;
1059
- }
1060
- _pendingKey(context) {
1061
- return [context.invocationId, context.invocationContext?.branch ?? '', context.agentName].join('\0');
1062
- }
1063
- _toolKey(context, toolName) {
1064
- return [this._pendingKey(context), context.functionCallId ?? '', toolName].join('\0');
1065
- }
1066
- _peekPending(key) {
1067
- return this._pending.get(key)?.[0];
1068
- }
1069
- _takePending(key) {
1070
- const queue = this._pending.get(key);
1071
- if (!queue || queue.length === 0) {
1072
- return undefined;
1073
- }
1074
- const pending = queue.shift();
1075
- if (queue.length === 0) {
1076
- this._pending.delete(key);
1077
- }
1078
- return pending;
1079
- }
1080
- _takePendingAgent(key) {
1081
- const queue = this._pendingAgents.get(key);
1082
- if (!queue || queue.length === 0) {
1083
- return undefined;
1084
- }
1085
- const pending = queue.shift();
1086
- if (queue.length === 0) {
1087
- this._pendingAgents.delete(key);
1088
- }
1089
- return pending;
1090
- }
1091
- _takePendingTool(key) {
1092
- const queue = this._pendingTools.get(key);
1093
- if (!queue || queue.length === 0) {
1094
- return undefined;
1095
- }
1096
- const pending = queue.shift();
1097
- if (queue.length === 0) {
1098
- this._pendingTools.delete(key);
1099
- }
1100
- return pending;
1101
- }
1102
- _isNonTerminalStreamResponse(llmResponse) {
1103
- if (llmResponse.turnComplete === false) {
1104
- return true;
1105
- }
1106
- return llmResponse.partial === false && llmResponse.turnComplete !== true && llmResponse.content !== undefined && llmResponse.finishReason === undefined && llmResponse.errorCode === undefined;
1107
- }
1108
- _evictStalePending() {
1109
- const cutoff = Date.now() - MAX_PENDING_AGE_MS;
1110
- this._evictStaleQueueEntries(this._pending, cutoff);
1111
- this._evictStaleQueueEntries(this._pendingAgents, cutoff);
1112
- this._evictStaleQueueEntries(this._pendingTools, cutoff);
1113
- for (const [invocationId, trace] of this._traces) {
1114
- if (trace.startTime < cutoff) {
1115
- this._traces.delete(invocationId);
1116
- }
1117
- }
1118
- }
1119
- _evictStaleQueueEntries(queues, cutoff) {
1120
- for (const [key, queue] of queues) {
1121
- const active = queue.filter(entry => entry.startTime >= cutoff);
1122
- if (active.length > 0) {
1123
- queues.set(key, active);
1124
- } else {
1125
- queues.delete(key);
1126
- }
1127
- }
1128
- }
1129
- _clearPendingInvocation(invocationId) {
1130
- const prefix = `${invocationId}\0`;
1131
- for (const key of this._pending.keys()) {
1132
- if (key.startsWith(prefix)) {
1133
- this._pending.delete(key);
1134
- }
1135
- }
1136
- for (const key of this._pendingAgents.keys()) {
1137
- if (key.startsWith(prefix)) {
1138
- this._pendingAgents.delete(key);
1139
- }
1140
- }
1141
- for (const key of this._pendingTools.keys()) {
1142
- if (key.startsWith(prefix)) {
1143
- this._pendingTools.delete(key);
1144
- }
1145
- }
1146
- }
1147
- _formatInput(llmRequest) {
1148
- const contents = sanitizeGemini(llmRequest.contents, this._client) ?? [];
1149
- const messages = Array.isArray(contents) ? contents.map(content => formatContent(content, this._client)) : [];
1150
- const systemInstruction = extractSystemInstruction(llmRequest);
1151
- if (systemInstruction && !messages.some(message => message.role === 'system')) {
1152
- return [{
1153
- role: 'system',
1154
- content: systemInstruction
1155
- }, ...messages];
1156
- }
1157
- return messages;
1158
- }
1159
- _formatOutput(llmResponse) {
1160
- // Reuse the Gemini response formatter (text/functionCall/inlineData +
1161
- // base64 redaction) by adapting the ADK response into a candidates shape.
1162
- return formatResponseGemini({
1163
- candidates: llmResponse.content ? [{
1164
- content: llmResponse.content
1165
- }] : []
1166
- }, this._client);
1167
- }
1168
- _handleError(error) {
1169
- try {
1170
- this._onError?.(error);
1171
- } catch {
1172
- // The plugin must never throw into the ADK model flow.
1173
- }
1174
- }
1175
- }
1176
-
521
+ * A Google ADK (`@google/adk`) `BasePlugin` that captures PostHog AI traces,
522
+ * agent and tool spans, and a full `$ai_generation` event for every model call.
523
+ *
524
+ * Run, agent, and tool callbacks build the trace hierarchy. Model callbacks
525
+ * record input, output, model, token usage, latency, and finish reason through
526
+ * the shared {@link captureAiGeneration} primitive so PostHog derives cost from
527
+ * the model and tokens (never hardcoded here).
528
+ *
529
+ * ADK already emits OpenTelemetry `gen_ai.*` spans; this plugin is the
530
+ * complement for users who capture LLM analytics through the PostHog SDK rather
531
+ * than an OTEL exporter.
532
+ *
533
+ * @example
534
+ * ```typescript
535
+ * import { PostHogADKPlugin } from '@posthog/ai/adk'
536
+ * import { Runner } from '@google/adk'
537
+ * import { PostHog } from 'posthog-node'
538
+ *
539
+ * const phClient = new PostHog('<POSTHOG_API_KEY>')
540
+ *
541
+ * const runner = new Runner({
542
+ * appName: 'my-app',
543
+ * agent,
544
+ * sessionService,
545
+ * plugins: [new PostHogADKPlugin({ client: phClient, distinctId: 'user@example.com' })],
546
+ * })
547
+ * ```
548
+ */
549
+ var PostHogADKPlugin = class extends BasePlugin {
550
+ constructor(options) {
551
+ super("posthog");
552
+ this._pending = /* @__PURE__ */ new Map();
553
+ this._traces = /* @__PURE__ */ new Map();
554
+ this._pendingAgents = /* @__PURE__ */ new Map();
555
+ this._pendingTools = /* @__PURE__ */ new Map();
556
+ this._client = options.client;
557
+ this._distinctId = options.distinctId;
558
+ this._provider = options.provider ?? "gemini";
559
+ this._privacyMode = options.privacyMode ?? false;
560
+ this._groups = options.groups;
561
+ this._properties = options.properties ?? {};
562
+ this._captureImmediate = options.captureImmediate ?? false;
563
+ this._onError = options.onError;
564
+ }
565
+ async beforeRunCallback({ invocationContext }) {
566
+ try {
567
+ this._evictStalePending();
568
+ this._traces.set(invocationContext.invocationId, {
569
+ startTime: Date.now(),
570
+ spanId: invocationContext.invocationId,
571
+ name: invocationContext.agent?.name ?? "ADK invocation",
572
+ input: invocationContext.userContent,
573
+ distinctId: this._resolveInvocationDistinctId(invocationContext),
574
+ sessionId: invocationContext.session?.id
575
+ });
576
+ } catch (error) {
577
+ this._handleError(error);
578
+ }
579
+ }
580
+ async afterRunCallback({ invocationContext }) {
581
+ try {
582
+ const trace = this._traces.get(invocationContext.invocationId);
583
+ this._traces.delete(invocationContext.invocationId);
584
+ this._clearPendingInvocation(invocationContext.invocationId);
585
+ if (!trace) return;
586
+ await this._captureLifecycleEvent("$ai_trace", trace.distinctId, {
587
+ $ai_trace_id: invocationContext.invocationId,
588
+ $ai_span_id: trace.spanId,
589
+ $ai_span_name: trace.name,
590
+ $ai_input_state: withPrivacyMode(this._client, this._privacyMode, trace.input),
591
+ $ai_latency: (Date.now() - trace.startTime) / 1e3,
592
+ ...trace.sessionId ? { $ai_session_id: trace.sessionId } : {}
593
+ });
594
+ } catch (error) {
595
+ this._handleError(error);
596
+ }
597
+ }
598
+ async beforeAgentCallback({ agent, callbackContext }) {
599
+ try {
600
+ this._evictStalePending();
601
+ this._rememberContext(callbackContext);
602
+ const key = this._pendingKey(callbackContext);
603
+ const pending = {
604
+ startTime: Date.now(),
605
+ spanId: v4(),
606
+ name: agent.name,
607
+ input: callbackContext.userContent
608
+ };
609
+ const queue = this._pendingAgents.get(key);
610
+ if (queue) queue.push(pending);
611
+ else this._pendingAgents.set(key, [pending]);
612
+ } catch (error) {
613
+ this._handleError(error);
614
+ }
615
+ }
616
+ async afterAgentCallback({ callbackContext }) {
617
+ try {
618
+ const pending = this._takePendingAgent(this._pendingKey(callbackContext));
619
+ if (pending) await this._captureLifecycleEvent("$ai_span", this._resolveDistinctId(callbackContext), {
620
+ $ai_trace_id: callbackContext.invocationId,
621
+ $ai_span_id: pending.spanId,
622
+ ...this._traces.get(callbackContext.invocationId)?.spanId ? { $ai_parent_id: this._traces.get(callbackContext.invocationId)?.spanId } : {},
623
+ $ai_span_name: pending.name,
624
+ $ai_input_state: withPrivacyMode(this._client, this._privacyMode, pending.input),
625
+ $ai_latency: (Date.now() - pending.startTime) / 1e3,
626
+ ...callbackContext.sessionId ? { $ai_session_id: callbackContext.sessionId } : {},
627
+ ...callbackContext.agentName ? { $ai_agent_name: callbackContext.agentName } : {}
628
+ });
629
+ } catch (error) {
630
+ this._handleError(error);
631
+ }
632
+ }
633
+ async beforeModelCallback({ callbackContext, llmRequest }) {
634
+ try {
635
+ this._evictStalePending();
636
+ this._rememberContext(callbackContext);
637
+ const pending = {
638
+ startTime: Date.now(),
639
+ spanId: v4(),
640
+ input: this._formatInput(llmRequest),
641
+ model: llmRequest.model,
642
+ modelParameters: extractModelParameters(llmRequest.config),
643
+ tools: extractTools(llmRequest),
644
+ streamedOutput: []
645
+ };
646
+ const key = this._pendingKey(callbackContext);
647
+ const queue = this._pending.get(key);
648
+ if (queue) queue.push(pending);
649
+ else this._pending.set(key, [pending]);
650
+ } catch (error) {
651
+ this._handleError(error);
652
+ }
653
+ }
654
+ async afterModelCallback({ callbackContext, llmResponse }) {
655
+ try {
656
+ if (llmResponse.partial) return;
657
+ const key = this._pendingKey(callbackContext);
658
+ const pending = this._peekPending(key);
659
+ if (this._isNonTerminalStreamResponse(llmResponse)) {
660
+ if (pending) pending.streamedOutput.push(...this._formatOutput(llmResponse));
661
+ return;
662
+ }
663
+ const completedPending = this._takePending(key);
664
+ const error = llmResponse.errorCode ? new Error(llmResponse.errorMessage ?? String(llmResponse.errorCode)) : void 0;
665
+ const output = error ? [] : this._formatOutput(llmResponse);
666
+ await this._capture(callbackContext, {
667
+ pending: completedPending,
668
+ output: !error && output.length === 0 && completedPending?.streamedOutput.length ? completedPending.streamedOutput : output,
669
+ model: llmResponse.modelVersion ?? completedPending?.model,
670
+ usage: llmResponse.usageMetadata,
671
+ stopReason: llmResponse.finishReason ? String(llmResponse.finishReason) : void 0,
672
+ error
673
+ });
674
+ } catch (error) {
675
+ this._handleError(error);
676
+ }
677
+ }
678
+ async onModelErrorCallback({ callbackContext, llmRequest, error }) {
679
+ try {
680
+ const pending = this._takePending(this._pendingKey(callbackContext));
681
+ await this._capture(callbackContext, {
682
+ pending: pending ?? {
683
+ startTime: Date.now(),
684
+ spanId: v4(),
685
+ input: this._formatInput(llmRequest),
686
+ model: llmRequest.model,
687
+ modelParameters: extractModelParameters(llmRequest.config),
688
+ tools: extractTools(llmRequest),
689
+ streamedOutput: []
690
+ },
691
+ output: [],
692
+ model: llmRequest.model,
693
+ usage: void 0,
694
+ error
695
+ });
696
+ } catch (captureError) {
697
+ this._handleError(captureError);
698
+ }
699
+ }
700
+ async beforeToolCallback({ tool, toolArgs, toolContext }) {
701
+ try {
702
+ this._evictStalePending();
703
+ this._rememberContext(toolContext);
704
+ const key = this._toolKey(toolContext, tool.name);
705
+ const pending = {
706
+ startTime: Date.now(),
707
+ spanId: toolContext.functionCallId ?? v4(),
708
+ name: tool.name,
709
+ input: toolArgs
710
+ };
711
+ const queue = this._pendingTools.get(key);
712
+ if (queue) queue.push(pending);
713
+ else this._pendingTools.set(key, [pending]);
714
+ } catch (error) {
715
+ this._handleError(error);
716
+ }
717
+ }
718
+ async afterToolCallback({ tool, toolContext, result }) {
719
+ try {
720
+ const pending = this._takePendingTool(this._toolKey(toolContext, tool.name));
721
+ if (pending) await this._captureToolSpan(toolContext, pending, result);
722
+ } catch (error) {
723
+ this._handleError(error);
724
+ }
725
+ }
726
+ async onToolErrorCallback({ tool, toolContext, error }) {
727
+ try {
728
+ const pending = this._takePendingTool(this._toolKey(toolContext, tool.name));
729
+ if (pending) await this._captureToolSpan(toolContext, pending, void 0, error);
730
+ } catch (captureError) {
731
+ this._handleError(captureError);
732
+ }
733
+ }
734
+ async _capture(callbackContext, args) {
735
+ const { pending, output, model, usage, stopReason, error } = args;
736
+ const latency = pending ? (Date.now() - pending.startTime) / 1e3 : void 0;
737
+ await captureAiGeneration(this._client, {
738
+ distinctId: this._resolveDistinctId(callbackContext),
739
+ traceId: callbackContext.invocationId,
740
+ model,
741
+ provider: this._provider,
742
+ baseURL: null,
743
+ input: pending?.input ?? [],
744
+ output,
745
+ latency,
746
+ modelParameters: pending?.modelParameters,
747
+ usage: mapGeminiUsage(usage),
748
+ stopReason,
749
+ tools: pending?.tools,
750
+ groups: this._groups,
751
+ privacyMode: this._privacyMode,
752
+ captureImmediate: this._captureImmediate,
753
+ onError: this._onError,
754
+ properties: {
755
+ $ai_framework: "google-adk",
756
+ $ai_span_id: pending?.spanId ?? v4(),
757
+ ...this._parentSpanId(callbackContext) ? { $ai_parent_id: this._parentSpanId(callbackContext) } : {},
758
+ ...callbackContext.sessionId ? { $ai_session_id: callbackContext.sessionId } : {},
759
+ ...callbackContext.agentName ? {
760
+ $ai_agent_name: callbackContext.agentName,
761
+ $ai_span_name: callbackContext.agentName
762
+ } : {},
763
+ ...this._properties
764
+ },
765
+ error
766
+ });
767
+ }
768
+ async _captureToolSpan(context, pending, result, error) {
769
+ await this._captureLifecycleEvent("$ai_span", this._resolveDistinctId(context), {
770
+ $ai_trace_id: context.invocationId,
771
+ $ai_span_id: pending.spanId,
772
+ ...this._parentSpanId(context) ? { $ai_parent_id: this._parentSpanId(context) } : {},
773
+ $ai_span_name: pending.name,
774
+ $ai_input_state: withPrivacyMode(this._client, this._privacyMode, pending.input),
775
+ ...result !== void 0 ? { $ai_output_state: withPrivacyMode(this._client, this._privacyMode, result) } : {},
776
+ $ai_latency: (Date.now() - pending.startTime) / 1e3,
777
+ ...context.sessionId ? { $ai_session_id: context.sessionId } : {},
778
+ ...context.agentName ? { $ai_agent_name: context.agentName } : {},
779
+ ...error ? {
780
+ $ai_is_error: true,
781
+ $ai_error: stringifyError(error)
782
+ } : {}
783
+ });
784
+ }
785
+ async _captureLifecycleEvent(event, distinctId, properties) {
786
+ const message = {
787
+ distinctId: distinctId ?? String(properties.$ai_trace_id),
788
+ event,
789
+ properties: {
790
+ $ai_lib: "posthog-ai",
791
+ $ai_lib_version: version,
792
+ $ai_framework: "google-adk",
793
+ ...properties,
794
+ ...this._properties,
795
+ ...distinctId ? {} : { $process_person_profile: false }
796
+ },
797
+ groups: this._groups
798
+ };
799
+ if (this._captureImmediate) await captureAiEventImmediate(this._client, message);
800
+ else captureAiEvent(this._client, message);
801
+ }
802
+ _resolveDistinctId(context) {
803
+ if (typeof this._distinctId === "function") {
804
+ const resolved = this._distinctId(context);
805
+ if (resolved) return String(resolved);
806
+ } else if (this._distinctId) return String(this._distinctId);
807
+ return context.userId ? String(context.userId) : void 0;
808
+ }
809
+ _resolveInvocationDistinctId(context) {
810
+ if (typeof this._distinctId === "string" && this._distinctId) return String(this._distinctId);
811
+ return context.userId ? String(context.userId) : void 0;
812
+ }
813
+ _rememberContext(context) {
814
+ const trace = this._traces.get(context.invocationId);
815
+ if (trace) {
816
+ trace.distinctId = this._resolveDistinctId(context);
817
+ trace.sessionId = context.sessionId || trace.sessionId;
818
+ }
819
+ }
820
+ _parentSpanId(context) {
821
+ return this._pendingAgents.get(this._pendingKey(context))?.[0]?.spanId ?? this._traces.get(context.invocationId)?.spanId;
822
+ }
823
+ _pendingKey(context) {
824
+ return [
825
+ context.invocationId,
826
+ context.invocationContext?.branch ?? "",
827
+ context.agentName
828
+ ].join("\0");
829
+ }
830
+ _toolKey(context, toolName) {
831
+ return [
832
+ this._pendingKey(context),
833
+ context.functionCallId ?? "",
834
+ toolName
835
+ ].join("\0");
836
+ }
837
+ _peekPending(key) {
838
+ return this._pending.get(key)?.[0];
839
+ }
840
+ _takePending(key) {
841
+ const queue = this._pending.get(key);
842
+ if (!queue || queue.length === 0) return;
843
+ const pending = queue.shift();
844
+ if (queue.length === 0) this._pending.delete(key);
845
+ return pending;
846
+ }
847
+ _takePendingAgent(key) {
848
+ const queue = this._pendingAgents.get(key);
849
+ if (!queue || queue.length === 0) return;
850
+ const pending = queue.shift();
851
+ if (queue.length === 0) this._pendingAgents.delete(key);
852
+ return pending;
853
+ }
854
+ _takePendingTool(key) {
855
+ const queue = this._pendingTools.get(key);
856
+ if (!queue || queue.length === 0) return;
857
+ const pending = queue.shift();
858
+ if (queue.length === 0) this._pendingTools.delete(key);
859
+ return pending;
860
+ }
861
+ _isNonTerminalStreamResponse(llmResponse) {
862
+ if (llmResponse.turnComplete === false) return true;
863
+ return llmResponse.partial === false && llmResponse.turnComplete !== true && llmResponse.content !== void 0 && llmResponse.finishReason === void 0 && llmResponse.errorCode === void 0;
864
+ }
865
+ _evictStalePending() {
866
+ const cutoff = Date.now() - MAX_PENDING_AGE_MS;
867
+ this._evictStaleQueueEntries(this._pending, cutoff);
868
+ this._evictStaleQueueEntries(this._pendingAgents, cutoff);
869
+ this._evictStaleQueueEntries(this._pendingTools, cutoff);
870
+ for (const [invocationId, trace] of this._traces) if (trace.startTime < cutoff) this._traces.delete(invocationId);
871
+ }
872
+ _evictStaleQueueEntries(queues, cutoff) {
873
+ for (const [key, queue] of queues) {
874
+ const active = queue.filter((entry) => entry.startTime >= cutoff);
875
+ if (active.length > 0) queues.set(key, active);
876
+ else queues.delete(key);
877
+ }
878
+ }
879
+ _clearPendingInvocation(invocationId) {
880
+ const prefix = `${invocationId}\0`;
881
+ for (const key of this._pending.keys()) if (key.startsWith(prefix)) this._pending.delete(key);
882
+ for (const key of this._pendingAgents.keys()) if (key.startsWith(prefix)) this._pendingAgents.delete(key);
883
+ for (const key of this._pendingTools.keys()) if (key.startsWith(prefix)) this._pendingTools.delete(key);
884
+ }
885
+ _formatInput(llmRequest) {
886
+ const contents = sanitizeGemini(llmRequest.contents, this._client) ?? [];
887
+ const messages = Array.isArray(contents) ? contents.map((content) => formatContent(content, this._client)) : [];
888
+ const systemInstruction = extractSystemInstruction(llmRequest);
889
+ if (systemInstruction && !messages.some((message) => message.role === "system")) return [{
890
+ role: "system",
891
+ content: systemInstruction
892
+ }, ...messages];
893
+ return messages;
894
+ }
895
+ _formatOutput(llmResponse) {
896
+ return formatResponseGemini({ candidates: llmResponse.content ? [{ content: llmResponse.content }] : [] }, this._client);
897
+ }
898
+ _handleError(error) {
899
+ try {
900
+ this._onError?.(error);
901
+ } catch {}
902
+ }
903
+ };
1177
904
  /** Map a genai content role to PostHog's convention (`model` -> `assistant`). */
1178
905
  function mapRole(role) {
1179
- if (role === 'model') {
1180
- return 'assistant';
1181
- }
1182
- return role ?? 'user';
906
+ if (role === "model") return "assistant";
907
+ return role ?? "user";
1183
908
  }
1184
909
  function formatContent(content, client) {
1185
- const parts = Array.isArray(content?.parts) ? content.parts : [];
1186
- const blocks = [];
1187
- for (const part of parts) {
1188
- if (part == null) {
1189
- continue;
1190
- }
1191
- if (part.text) {
1192
- blocks.push({
1193
- type: 'text',
1194
- text: String(part.text)
1195
- });
1196
- } else if (part.functionCall) {
1197
- blocks.push({
1198
- type: 'function',
1199
- id: part.functionCall.id,
1200
- function: {
1201
- name: part.functionCall.name,
1202
- arguments: part.functionCall.args ?? {}
1203
- }
1204
- });
1205
- } else if (part.functionResponse) {
1206
- blocks.push({
1207
- type: 'text',
1208
- text: toContentString(part.functionResponse.response ?? part.functionResponse)
1209
- });
1210
- } else if (part.inlineData) {
1211
- blocks.push(formatInlineDataBlock(part.inlineData, client));
1212
- }
1213
- }
1214
- return {
1215
- role: mapRole(content?.role),
1216
- content: blocks
1217
- };
910
+ const parts = Array.isArray(content?.parts) ? content.parts : [];
911
+ const blocks = [];
912
+ for (const part of parts) {
913
+ if (part == null) continue;
914
+ if (part.text) blocks.push({
915
+ type: "text",
916
+ text: String(part.text)
917
+ });
918
+ else if (part.functionCall) blocks.push({
919
+ type: "function",
920
+ id: part.functionCall.id,
921
+ function: {
922
+ name: part.functionCall.name,
923
+ arguments: part.functionCall.args ?? {}
924
+ }
925
+ });
926
+ else if (part.functionResponse) blocks.push({
927
+ type: "text",
928
+ text: toContentString(part.functionResponse.response ?? part.functionResponse)
929
+ });
930
+ else if (part.inlineData) blocks.push(formatInlineDataBlock(part.inlineData, client));
931
+ }
932
+ return {
933
+ role: mapRole(content?.role),
934
+ content: blocks
935
+ };
1218
936
  }
1219
-
1220
937
  /** Extract the system instruction text from an LlmRequest's config, if any. */
1221
938
  function extractSystemInstruction(llmRequest) {
1222
- const systemInstruction = llmRequest.config?.systemInstruction;
1223
- if (!systemInstruction) {
1224
- return null;
1225
- }
1226
- if (typeof systemInstruction === 'string') {
1227
- return systemInstruction;
1228
- }
1229
- const asObject = systemInstruction;
1230
- if (typeof asObject.text === 'string') {
1231
- return asObject.text;
1232
- }
1233
- const parts = Array.isArray(asObject.parts) ? asObject.parts : Array.isArray(systemInstruction) ? systemInstruction : [];
1234
- const textParts = parts.flatMap(part => {
1235
- if (typeof part === 'string') {
1236
- return [part];
1237
- }
1238
- if (part && typeof part === 'object' && typeof part.text === 'string') {
1239
- return [part.text];
1240
- }
1241
- return [];
1242
- });
1243
- return textParts.length > 0 ? textParts.join('') : null;
939
+ const systemInstruction = llmRequest.config?.systemInstruction;
940
+ if (!systemInstruction) return null;
941
+ if (typeof systemInstruction === "string") return systemInstruction;
942
+ const asObject = systemInstruction;
943
+ if (typeof asObject.text === "string") return asObject.text;
944
+ const textParts = (Array.isArray(asObject.parts) ? asObject.parts : Array.isArray(systemInstruction) ? systemInstruction : []).flatMap((part) => {
945
+ if (typeof part === "string") return [part];
946
+ if (part && typeof part === "object" && typeof part.text === "string") return [part.text];
947
+ return [];
948
+ });
949
+ return textParts.length > 0 ? textParts.join("") : null;
1244
950
  }
1245
- const MODEL_PARAM_KEYS = ['temperature', 'topP', 'topK', 'maxOutputTokens', 'candidateCount', 'stopSequences', 'presencePenalty', 'frequencyPenalty', 'seed'];
951
+ const MODEL_PARAM_KEYS = [
952
+ "temperature",
953
+ "topP",
954
+ "topK",
955
+ "maxOutputTokens",
956
+ "candidateCount",
957
+ "stopSequences",
958
+ "presencePenalty",
959
+ "frequencyPenalty",
960
+ "seed"
961
+ ];
1246
962
  function extractModelParameters(config) {
1247
- const params = {};
1248
- if (!config || typeof config !== 'object') {
1249
- return params;
1250
- }
1251
- const source = config;
1252
- for (const key of MODEL_PARAM_KEYS) {
1253
- if (source[key] !== undefined) {
1254
- params[key] = source[key];
1255
- }
1256
- }
1257
- return params;
963
+ const params = {};
964
+ if (!config || typeof config !== "object") return params;
965
+ const source = config;
966
+ for (const key of MODEL_PARAM_KEYS) if (source[key] !== void 0) params[key] = source[key];
967
+ return params;
1258
968
  }
1259
969
  function extractTools(llmRequest) {
1260
- const tools = llmRequest.config?.tools;
1261
- return Array.isArray(tools) && tools.length > 0 ? tools : null;
970
+ const tools = llmRequest.config?.tools;
971
+ return Array.isArray(tools) && tools.length > 0 ? tools : null;
1262
972
  }
1263
-
973
+ //#endregion
1264
974
  export { PostHogADKPlugin };
1265
- //# sourceMappingURL=index.mjs.map
975
+
976
+ //# sourceMappingURL=index.mjs.map