@posthog/ai 8.22.0 → 8.22.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 (53) hide show
  1. package/dist/adk/index.cjs +76 -28
  2. package/dist/adk/index.cjs.map +1 -1
  3. package/dist/adk/index.mjs +76 -28
  4. package/dist/adk/index.mjs.map +1 -1
  5. package/dist/anthropic/index.cjs +77 -29
  6. package/dist/anthropic/index.cjs.map +1 -1
  7. package/dist/anthropic/index.mjs +77 -29
  8. package/dist/anthropic/index.mjs.map +1 -1
  9. package/dist/claude-agent-sdk/index.cjs +76 -28
  10. package/dist/claude-agent-sdk/index.cjs.map +1 -1
  11. package/dist/claude-agent-sdk/index.mjs +76 -28
  12. package/dist/claude-agent-sdk/index.mjs.map +1 -1
  13. package/dist/gemini/index.cjs +77 -29
  14. package/dist/gemini/index.cjs.map +1 -1
  15. package/dist/gemini/index.mjs +77 -29
  16. package/dist/gemini/index.mjs.map +1 -1
  17. package/dist/genkit/index.cjs +84 -41
  18. package/dist/genkit/index.cjs.map +1 -1
  19. package/dist/genkit/index.mjs +84 -41
  20. package/dist/genkit/index.mjs.map +1 -1
  21. package/dist/index.cjs +77 -29
  22. package/dist/index.cjs.map +1 -1
  23. package/dist/index.mjs +77 -29
  24. package/dist/index.mjs.map +1 -1
  25. package/dist/langchain/index.cjs +76 -28
  26. package/dist/langchain/index.cjs.map +1 -1
  27. package/dist/langchain/index.mjs +77 -29
  28. package/dist/langchain/index.mjs.map +1 -1
  29. package/dist/langchain/middleware/index.cjs +76 -28
  30. package/dist/langchain/middleware/index.cjs.map +1 -1
  31. package/dist/langchain/middleware/index.mjs +77 -29
  32. package/dist/langchain/middleware/index.mjs.map +1 -1
  33. package/dist/openai/index.cjs +144 -75
  34. package/dist/openai/index.cjs.map +1 -1
  35. package/dist/openai/index.mjs +144 -75
  36. package/dist/openai/index.mjs.map +1 -1
  37. package/dist/openai-agents/index.cjs +26 -1
  38. package/dist/openai-agents/index.cjs.map +1 -1
  39. package/dist/openai-agents/index.mjs +26 -1
  40. package/dist/openai-agents/index.mjs.map +1 -1
  41. package/dist/otel/index.browser.cjs +51 -2
  42. package/dist/otel/index.browser.cjs.map +1 -1
  43. package/dist/otel/index.browser.mjs +51 -2
  44. package/dist/otel/index.browser.mjs.map +1 -1
  45. package/dist/otel/index.cjs +51 -2
  46. package/dist/otel/index.cjs.map +1 -1
  47. package/dist/otel/index.mjs +51 -2
  48. package/dist/otel/index.mjs.map +1 -1
  49. package/dist/vercel/index.cjs +77 -29
  50. package/dist/vercel/index.cjs.map +1 -1
  51. package/dist/vercel/index.mjs +77 -29
  52. package/dist/vercel/index.mjs.map +1 -1
  53. package/package.json +3 -3
@@ -14,6 +14,81 @@ const isObject = (value) => {
14
14
  return value !== null && typeof value === "object" && !Array.isArray(value);
15
15
  };
16
16
  //#endregion
17
+ //#region src/mcpCredentials.ts
18
+ const MCP_CREDENTIAL_FIELDS = ["headers", "authorization"];
19
+ const MCP_TOOL_TYPES = /* @__PURE__ */ new Set(["mcp", "mcp_server"]);
20
+ const MCP_PROVIDER_TOOL_IDS = /* @__PURE__ */ new Set([
21
+ "openai.mcp",
22
+ "xai.mcp",
23
+ "google.mcp_server"
24
+ ]);
25
+ const isMcpProviderTool = (tool) => (tool.type === "provider" || tool.type === "provider-defined") && typeof tool.id === "string" && MCP_PROVIDER_TOOL_IDS.has(tool.id);
26
+ const withoutMcpCredentials = (config) => {
27
+ const redacted = { ...config };
28
+ for (const field of MCP_CREDENTIAL_FIELDS) if (field in redacted) redacted[field] = "[REDACTED]";
29
+ return redacted;
30
+ };
31
+ const normalizeKey = (key) => key.toLowerCase().replace(/[-_]/g, "");
32
+ const isPlainObject = (value) => {
33
+ if (!isObject(value)) return false;
34
+ const prototype = Object.getPrototypeOf(value);
35
+ return prototype === Object.prototype || prototype === null;
36
+ };
37
+ /**
38
+ * Replaces the value of every key in `keys` (normalized) with `[REDACTED]`, through plain objects and arrays.
39
+ * Class instances, such as the MCP client inside an `mcpToTool()` tool, are returned as they are.
40
+ */
41
+ function redactKeys(value, keys) {
42
+ if (Array.isArray(value)) return value.map((item) => redactKeys(item, keys));
43
+ if (!isPlainObject(value)) return value;
44
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, keys.has(normalizeKey(key)) ? "[REDACTED]" : redactKeys(item, keys)]));
45
+ }
46
+ const GEMINI_TOOL_FIELDS = new Set([
47
+ "codeExecution",
48
+ "computerUse",
49
+ "enterpriseWebSearch",
50
+ "exaAiSearch",
51
+ "fileSearch",
52
+ "functionDeclarations",
53
+ "googleMaps",
54
+ "googleSearch",
55
+ "googleSearchRetrieval",
56
+ "mcpServers",
57
+ "parallelAiSearch",
58
+ "retrieval",
59
+ "urlContext"
60
+ ].map(normalizeKey));
61
+ const GEMINI_SCHEMA_FIELD = normalizeKey("functionDeclarations");
62
+ const GEMINI_CREDENTIAL_KEYS = new Set([
63
+ "apiAuth",
64
+ "authConfig",
65
+ "apiKey",
66
+ "headers"
67
+ ].map(normalizeKey));
68
+ const isGeminiTool = (tool) => Object.keys(tool).map(normalizeKey).some((key) => key !== GEMINI_SCHEMA_FIELD && GEMINI_TOOL_FIELDS.has(key));
69
+ /**
70
+ * Masks the credential keys under every field of a `@google/genai` tool except its function declarations.
71
+ * A class-based tool, such as `mcpToTool(client)`, holds a live client with its auth headers, so only a stub is kept.
72
+ */
73
+ function redactGeminiToolDefinition(tool) {
74
+ if (!isPlainObject(tool)) return isObject(tool) ? { type: "callable_tool" } : tool;
75
+ return Object.fromEntries(Object.entries(tool).map(([key, value]) => [key, normalizeKey(key) === GEMINI_SCHEMA_FIELD ? value : redactKeys((0, _posthog_core.toJsonSafeValue)(value), GEMINI_CREDENTIAL_KEYS)]));
76
+ }
77
+ /** Hides the credentials of a remote MCP or Gemini tool definition; everything else is kept as sent. */
78
+ function redactMcpToolDefinition(tool) {
79
+ if (!isObject(tool)) return tool;
80
+ if (typeof tool.type === "string" && MCP_TOOL_TYPES.has(tool.type)) return withoutMcpCredentials(tool);
81
+ if (isMcpProviderTool(tool) && isObject(tool.args)) return {
82
+ ...tool,
83
+ args: withoutMcpCredentials(tool.args)
84
+ };
85
+ if (isPlainObject(tool) && isGeminiTool(tool)) return redactGeminiToolDefinition(tool);
86
+ return tool;
87
+ }
88
+ function redactMcpToolCredentials(tools) {
89
+ return Array.isArray(tools) ? tools.map(redactMcpToolDefinition) : tools;
90
+ }
91
+ //#endregion
17
92
  //#region src/captureAiEvent.ts
18
93
  /** @internal */
19
94
  function isFullAiCaptureEnabled(client) {
@@ -552,7 +627,7 @@ const extractAvailableToolCalls = (provider, params) => {
552
627
  if (params.tools) return params.tools;
553
628
  return null;
554
629
  } else if (provider === "gemini") {
555
- if (params.config && params.config.tools) return params.config.tools;
630
+ if (params.config && Array.isArray(params.config.tools)) return params.config.tools.map(redactGeminiToolDefinition);
556
631
  return null;
557
632
  } else if (provider === "openai") {
558
633
  if (params.tools) return params.tools;
@@ -635,7 +710,7 @@ function formatOpenAIResponsesInput(input, instructions) {
635
710
  }
636
711
  //#endregion
637
712
  //#region package.json
638
- var version = "8.22.0";
713
+ var version = "8.22.2";
639
714
  //#endregion
640
715
  //#region src/serializeError.ts
641
716
  const DEFAULT_MAX_DEPTH = 3;
@@ -774,33 +849,6 @@ function truncateStack(stack) {
774
849
  return [...lines.slice(0, MAX_STACK_LINES), "... (truncated)"].join("\n");
775
850
  }
776
851
  //#endregion
777
- //#region src/mcpCredentials.ts
778
- const MCP_CREDENTIAL_FIELDS = ["headers", "authorization"];
779
- const MCP_PROVIDER_TOOL_IDS = /* @__PURE__ */ new Set([
780
- "openai.mcp",
781
- "xai.mcp",
782
- "google.mcp_server"
783
- ]);
784
- const isMcpProviderTool = (tool) => (tool.type === "provider" || tool.type === "provider-defined") && typeof tool.id === "string" && MCP_PROVIDER_TOOL_IDS.has(tool.id);
785
- const withoutMcpCredentials = (config) => {
786
- const redacted = { ...config };
787
- for (const field of MCP_CREDENTIAL_FIELDS) if (field in redacted) redacted[field] = "[REDACTED]";
788
- return redacted;
789
- };
790
- /** Hides the credentials of a remote MCP tool definition; everything else is kept as sent. */
791
- function redactMcpToolDefinition(tool) {
792
- if (!isObject(tool)) return tool;
793
- if (tool.type === "mcp") return withoutMcpCredentials(tool);
794
- if (isMcpProviderTool(tool) && isObject(tool.args)) return {
795
- ...tool,
796
- args: withoutMcpCredentials(tool.args)
797
- };
798
- return tool;
799
- }
800
- function redactMcpToolCredentials(tools) {
801
- return Array.isArray(tools) ? tools.map(redactMcpToolDefinition) : tools;
802
- }
803
- //#endregion
804
852
  //#region src/gatewayWarning.ts
805
853
  const POSTHOG_AI_GATEWAY_HOSTS = [
806
854
  "gateway.posthog.com",
@@ -1376,36 +1424,75 @@ function monitoredStreamTee(source, createStream) {
1376
1424
  }
1377
1425
  //#endregion
1378
1426
  //#region src/openai/stream-accumulators.ts
1427
+ function formatChoiceContent(state) {
1428
+ const content = [];
1429
+ if (state.content) content.push({
1430
+ type: "text",
1431
+ text: state.content
1432
+ });
1433
+ if (state.refusal) content.push({
1434
+ type: "refusal",
1435
+ refusal: state.refusal
1436
+ });
1437
+ for (const toolCall of state.toolCalls.values()) if (toolCall.name) content.push({
1438
+ type: "function",
1439
+ id: toolCall.id,
1440
+ function: {
1441
+ name: toolCall.name,
1442
+ arguments: toolCall.arguments
1443
+ }
1444
+ });
1445
+ return content;
1446
+ }
1379
1447
  /** Pure state accumulator for OpenAI-compatible Chat Completions chunks. */
1380
1448
  var OpenAIChatStreamAccumulator = class {
1381
1449
  constructor() {
1382
- this.accumulatedContent = "";
1383
- this.accumulatedRefusal = "";
1450
+ this.choices = /* @__PURE__ */ new Map();
1384
1451
  this.usage = { webSearchCount: 0 };
1385
- this.toolCalls = /* @__PURE__ */ new Map();
1386
1452
  }
1387
1453
  consume(chunk, receivedAt = Date.now()) {
1388
1454
  this.model ||= chunk.model || void 0;
1389
1455
  this.completionId ||= chunk.id || void 0;
1390
1456
  this.systemFingerprint ||= chunk.system_fingerprint || void 0;
1391
1457
  if (chunk.service_tier != null) this.serviceTier = chunk.service_tier;
1392
- const choice = chunk.choices?.[0];
1393
- if (choice?.finish_reason) this.stopReason = choice.finish_reason;
1394
1458
  const webSearchCount = calculateWebSearchCount(chunk);
1395
1459
  if (webSearchCount > (this.usage.webSearchCount ?? 0)) this.usage.webSearchCount = webSearchCount;
1396
- if (choice?.delta?.content) {
1460
+ for (const choice of chunk.choices ?? []) this.consumeChoice(choice, receivedAt);
1461
+ if (chunk.usage) this.usage = {
1462
+ ...this.usage,
1463
+ inputTokens: chunk.usage.prompt_tokens ?? 0,
1464
+ outputTokens: chunk.usage.completion_tokens ?? 0,
1465
+ reasoningTokens: chunk.usage.completion_tokens_details?.reasoning_tokens ?? 0,
1466
+ cacheReadInputTokens: chunk.usage.prompt_tokens_details?.cached_tokens ?? 0,
1467
+ cacheCreationInputTokens: extractCacheWriteTokens(chunk.usage.prompt_tokens_details),
1468
+ rawUsage: chunk.usage
1469
+ };
1470
+ }
1471
+ consumeChoice(choice, receivedAt) {
1472
+ const index = choice.index ?? 0;
1473
+ let state = this.choices.get(index);
1474
+ if (!state) {
1475
+ state = {
1476
+ content: "",
1477
+ refusal: "",
1478
+ toolCalls: /* @__PURE__ */ new Map()
1479
+ };
1480
+ this.choices.set(index, state);
1481
+ }
1482
+ if (choice.finish_reason && index === 0) this.stopReason = choice.finish_reason;
1483
+ if (choice.delta?.content) {
1397
1484
  this.firstTokenTime ??= receivedAt;
1398
- this.accumulatedContent += choice.delta.content;
1485
+ state.content += choice.delta.content;
1399
1486
  }
1400
- if (choice?.delta?.refusal) {
1487
+ if (choice.delta?.refusal) {
1401
1488
  this.firstTokenTime ??= receivedAt;
1402
- this.accumulatedRefusal += choice.delta.refusal;
1489
+ state.refusal += choice.delta.refusal;
1403
1490
  }
1404
- if (Array.isArray(choice?.delta?.tool_calls)) {
1491
+ if (Array.isArray(choice.delta?.tool_calls)) {
1405
1492
  this.firstTokenTime ??= receivedAt;
1406
1493
  for (const toolCall of choice.delta.tool_calls) {
1407
- const key = this.toolCallKey(toolCall);
1408
- const current = this.toolCalls.get(key) ?? {
1494
+ const key = this.toolCallKey(state, toolCall);
1495
+ const current = state.toolCalls.get(key) ?? {
1409
1496
  id: "",
1410
1497
  name: "",
1411
1498
  arguments: ""
@@ -1415,55 +1502,37 @@ var OpenAIChatStreamAccumulator = class {
1415
1502
  const argumentsDelta = toolCall.function?.arguments ?? toolCall.custom?.input;
1416
1503
  if (name) current.name = name;
1417
1504
  if (argumentsDelta) current.arguments += argumentsDelta;
1418
- this.toolCalls.set(key, current);
1419
- this.lastToolCallKey = key;
1505
+ state.toolCalls.set(key, current);
1506
+ state.lastToolCallKey = key;
1420
1507
  }
1421
1508
  }
1422
- if (chunk.usage) this.usage = {
1423
- ...this.usage,
1424
- inputTokens: chunk.usage.prompt_tokens ?? 0,
1425
- outputTokens: chunk.usage.completion_tokens ?? 0,
1426
- reasoningTokens: chunk.usage.completion_tokens_details?.reasoning_tokens ?? 0,
1427
- cacheReadInputTokens: chunk.usage.prompt_tokens_details?.cached_tokens ?? 0,
1428
- cacheCreationInputTokens: extractCacheWriteTokens(chunk.usage.prompt_tokens_details),
1429
- rawUsage: chunk.usage
1430
- };
1431
1509
  }
1432
1510
  /**
1433
1511
  * Some OpenAI-compatible providers stream tool calls without an `index`. Match those deltas by a known
1434
1512
  * `id`; a new `id`, a function name, or a custom tool name opens a new call, and anything else continues
1435
1513
  * the latest call.
1436
1514
  */
1437
- toolCallKey(toolCall) {
1515
+ toolCallKey(state, toolCall) {
1438
1516
  if (toolCall.index !== void 0) return toolCall.index;
1439
1517
  if (toolCall.id) {
1440
- for (const [key, existing] of this.toolCalls) if (existing.id === toolCall.id) return key;
1518
+ for (const [key, existing] of state.toolCalls) if (existing.id === toolCall.id) return key;
1441
1519
  }
1442
- if (toolCall.id || toolCall.function?.name || toolCall.custom?.name || this.lastToolCallKey === void 0) return `no-index-${this.toolCalls.size}`;
1443
- return this.lastToolCallKey;
1520
+ if (toolCall.id || toolCall.function?.name || toolCall.custom?.name || state.lastToolCallKey === void 0) return `no-index-${state.toolCalls.size}`;
1521
+ return state.lastToolCallKey;
1444
1522
  }
1445
1523
  result() {
1446
- const content = [];
1447
- if (this.accumulatedContent) content.push({
1448
- type: "text",
1449
- text: this.accumulatedContent
1450
- });
1451
- if (this.accumulatedRefusal) content.push({
1452
- type: "refusal",
1453
- refusal: this.accumulatedRefusal
1454
- });
1455
- for (const toolCall of this.toolCalls.values()) if (toolCall.name) content.push({
1456
- type: "function",
1457
- id: toolCall.id,
1458
- function: {
1459
- name: toolCall.name,
1460
- arguments: toolCall.arguments
1461
- }
1462
- });
1524
+ const output = [];
1525
+ for (const [, state] of [...this.choices].sort(([a], [b]) => a - b)) {
1526
+ const content = formatChoiceContent(state);
1527
+ if (content.length > 0) output.push({
1528
+ role: "assistant",
1529
+ content
1530
+ });
1531
+ }
1463
1532
  return {
1464
- output: [{
1533
+ output: output.length > 0 ? output : [{
1465
1534
  role: "assistant",
1466
- content: content.length > 0 ? content : [{
1535
+ content: [{
1467
1536
  type: "text",
1468
1537
  text: ""
1469
1538
  }]