@posthog/ai 8.9.2 → 8.10.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 (39) hide show
  1. package/dist/adk/index.cjs +1267 -0
  2. package/dist/adk/index.cjs.map +1 -0
  3. package/dist/adk/index.d.ts +149 -0
  4. package/dist/adk/index.mjs +1265 -0
  5. package/dist/adk/index.mjs.map +1 -0
  6. package/dist/anthropic/index.cjs +9 -2
  7. package/dist/anthropic/index.cjs.map +1 -1
  8. package/dist/anthropic/index.mjs +9 -2
  9. package/dist/anthropic/index.mjs.map +1 -1
  10. package/dist/gemini/index.cjs +51 -51
  11. package/dist/gemini/index.cjs.map +1 -1
  12. package/dist/gemini/index.mjs +51 -51
  13. package/dist/gemini/index.mjs.map +1 -1
  14. package/dist/index.cjs +9 -2
  15. package/dist/index.cjs.map +1 -1
  16. package/dist/index.d.ts +7 -1
  17. package/dist/index.mjs +9 -2
  18. package/dist/index.mjs.map +1 -1
  19. package/dist/langchain/index.cjs +6 -2
  20. package/dist/langchain/index.cjs.map +1 -1
  21. package/dist/langchain/index.mjs +6 -2
  22. package/dist/langchain/index.mjs.map +1 -1
  23. package/dist/langchain/middleware/index.cjs +6 -2
  24. package/dist/langchain/middleware/index.cjs.map +1 -1
  25. package/dist/langchain/middleware/index.mjs +6 -2
  26. package/dist/langchain/middleware/index.mjs.map +1 -1
  27. package/dist/openai/index.cjs +9 -2
  28. package/dist/openai/index.cjs.map +1 -1
  29. package/dist/openai/index.mjs +9 -2
  30. package/dist/openai/index.mjs.map +1 -1
  31. package/dist/openai-agents/index.cjs +1 -1
  32. package/dist/openai-agents/index.cjs.map +1 -1
  33. package/dist/openai-agents/index.mjs +1 -1
  34. package/dist/openai-agents/index.mjs.map +1 -1
  35. package/dist/vercel/index.cjs +9 -2
  36. package/dist/vercel/index.cjs.map +1 -1
  37. package/dist/vercel/index.mjs +9 -2
  38. package/dist/vercel/index.mjs.map +1 -1
  39. package/package.json +13 -3
@@ -0,0 +1,1265 @@
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
+
11
+ /** @internal */
12
+ function isFullAiCaptureEnabled(client) {
13
+ return client?.enableFullAiCapture === true;
14
+ }
15
+
16
+ /** @internal */
17
+ function captureAiEvent(client, event) {
18
+ if (isFullAiCaptureEnabled(client) && typeof client.captureAi === 'function') {
19
+ client.captureAi(event);
20
+ return;
21
+ }
22
+ client.capture(event);
23
+ }
24
+
25
+ /** @internal */
26
+ 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);
32
+ }
33
+
34
+ const DATA_URL_PREFIX_RE = /^data:([^;,\s]+)(?:;[^;,\s]+)*;base64,/i;
35
+ 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
+
131
+ const STRONG_CONTEXT_MIN_LENGTH = 64;
132
+ 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
+
184
+ const redactor = new BinaryContentRedactor();
185
+ function redactBase64DataUrl(str, mediaType) {
186
+ return redactor.redact(str, mediaType);
187
+ }
188
+ const sanitize = (data, client) => isFullAiCaptureEnabled(client) ? data : redactor.redact(data);
189
+ 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
+
193
+ /**
194
+ * Whether the caller supplied their own token counts, which override the ones the SDK
195
+ * derived from the provider response.
196
+ */
197
+ function hasTokenOverrides(posthogProperties) {
198
+ return !!posthogProperties && Object.keys(posthogProperties).some(key => TOKEN_PROPERTY_KEYS.has(key));
199
+ }
200
+ function getTokensSource(posthogProperties) {
201
+ return hasTokenOverrides(posthogProperties) ? 'passthrough' : 'sdk';
202
+ }
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.
207
+ new TextEncoder();
208
+ new TextDecoder(STRING_FORMAT, {
209
+ fatal: false
210
+ });
211
+
212
+ /**
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
+ */
223
+ 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);
236
+ }
237
+ 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
+ };
261
+ };
262
+ 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 ?? ''));
278
+ };
279
+ 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;
329
+ };
330
+ const withPrivacyMode = (client, privacyMode, input) => {
331
+ return client.privacy_mode || privacyMode ? null : input;
332
+ };
333
+ let AIEvent = /*#__PURE__*/function (AIEvent) {
334
+ AIEvent["Generation"] = "$ai_generation";
335
+ AIEvent["Embedding"] = "$ai_embedding";
336
+ return AIEvent;
337
+ }({});
338
+ 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;
352
+ }
353
+
354
+ const DEFAULT_MAX_DEPTH = 3;
355
+ const MAX_STACK_LINES = 20;
356
+ 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;
378
+ }
379
+ 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
+ }
393
+ }
394
+ 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');
403
+ }
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
+ }
425
+ };
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);
432
+ };
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}.`);
441
+ };
442
+
443
+ /**
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
+ */
462
+ 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
+ }
625
+ };
626
+
627
+ /** Map Gemini usage metadata to PostHog's provider-agnostic token fields. */
628
+ 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
+ };
643
+ }
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
+
652
+ /** 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
+
655
+ /**
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
+
1177
+ /** Map a genai content role to PostHog's convention (`model` -> `assistant`). */
1178
+ function mapRole(role) {
1179
+ if (role === 'model') {
1180
+ return 'assistant';
1181
+ }
1182
+ return role ?? 'user';
1183
+ }
1184
+ 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
+ };
1218
+ }
1219
+
1220
+ /** Extract the system instruction text from an LlmRequest's config, if any. */
1221
+ 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;
1244
+ }
1245
+ const MODEL_PARAM_KEYS = ['temperature', 'topP', 'topK', 'maxOutputTokens', 'candidateCount', 'stopSequences', 'presencePenalty', 'frequencyPenalty', 'seed'];
1246
+ 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;
1258
+ }
1259
+ function extractTools(llmRequest) {
1260
+ const tools = llmRequest.config?.tools;
1261
+ return Array.isArray(tools) && tools.length > 0 ? tools : null;
1262
+ }
1263
+
1264
+ export { PostHogADKPlugin };
1265
+ //# sourceMappingURL=index.mjs.map