@sentry/server-utils 11.13.0 → 11.14.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 (88) hide show
  1. package/build/cjs/chunks/config.js +19 -5
  2. package/build/cjs/chunks/config.js.map +1 -1
  3. package/build/cjs/chunks/exports.js +72 -26
  4. package/build/cjs/chunks/exports.js.map +1 -1
  5. package/build/cjs/chunks/moduleInjectedTransform.js +6 -5
  6. package/build/cjs/chunks/moduleInjectedTransform.js.map +1 -1
  7. package/build/cjs/index.js +161 -65
  8. package/build/cjs/index.js.map +1 -1
  9. package/build/cjs/orchestrion/bundler/rollup.js +4 -4
  10. package/build/cjs/orchestrion/bundler/rollup.js.map +1 -1
  11. package/build/esm/ai/google-genai/constants.js +2 -1
  12. package/build/esm/ai/google-genai/constants.js.map +1 -1
  13. package/build/esm/ai/google-genai/decisions.js +25 -0
  14. package/build/esm/ai/google-genai/decisions.js.map +1 -0
  15. package/build/esm/ai/google-genai/index.js +16 -5
  16. package/build/esm/ai/google-genai/index.js.map +1 -1
  17. package/build/esm/ai/mistral/index.js +9 -8
  18. package/build/esm/ai/mistral/index.js.map +1 -1
  19. package/build/esm/ai/mistral/streaming.js +3 -7
  20. package/build/esm/ai/mistral/streaming.js.map +1 -1
  21. package/build/esm/ai/mistral/utils.js +9 -1
  22. package/build/esm/ai/mistral/utils.js.map +1 -1
  23. package/build/esm/ai/vercel-ai/index.js +3 -1
  24. package/build/esm/ai/vercel-ai/index.js.map +1 -1
  25. package/build/esm/ai/workers-ai/index.js +8 -7
  26. package/build/esm/ai/workers-ai/index.js.map +1 -1
  27. package/build/esm/ai/workers-ai/streaming.js +3 -7
  28. package/build/esm/ai/workers-ai/streaming.js.map +1 -1
  29. package/build/esm/index.js +3 -2
  30. package/build/esm/index.js.map +1 -1
  31. package/build/esm/integrations/cron.js +2 -2
  32. package/build/esm/integrations/cron.js.map +1 -1
  33. package/build/esm/integrations/google-genai.js +10 -6
  34. package/build/esm/integrations/google-genai.js.map +1 -1
  35. package/build/esm/integrations/mistral.js +4 -3
  36. package/build/esm/integrations/mistral.js.map +1 -1
  37. package/build/esm/integrations/node-cron.js +5 -4
  38. package/build/esm/integrations/node-cron.js.map +1 -1
  39. package/build/esm/integrations/node-schedule.js +2 -2
  40. package/build/esm/integrations/node-schedule.js.map +1 -1
  41. package/build/esm/integrations/vercel-ai/vercel-ai-dc-subscriber.js +9 -1
  42. package/build/esm/integrations/vercel-ai/vercel-ai-dc-subscriber.js.map +1 -1
  43. package/build/esm/orchestrion/bundler/moduleInjectedTransform.js +6 -5
  44. package/build/esm/orchestrion/bundler/moduleInjectedTransform.js.map +1 -1
  45. package/build/esm/orchestrion/bundler/rollup.js +4 -4
  46. package/build/esm/orchestrion/bundler/rollup.js.map +1 -1
  47. package/build/esm/orchestrion/config/google-genai.js +19 -5
  48. package/build/esm/orchestrion/config/google-genai.js.map +1 -1
  49. package/build/esm/package.json +1 -1
  50. package/build/esm/utils/cronMonitoring.js +128 -50
  51. package/build/esm/utils/cronMonitoring.js.map +1 -1
  52. package/build/types/ai/google-genai/constants.d.ts +3 -0
  53. package/build/types/ai/google-genai/constants.d.ts.map +1 -1
  54. package/build/types/ai/google-genai/decisions.d.ts +8 -0
  55. package/build/types/ai/google-genai/decisions.d.ts.map +1 -0
  56. package/build/types/ai/google-genai/index.d.ts +3 -1
  57. package/build/types/ai/google-genai/index.d.ts.map +1 -1
  58. package/build/types/ai/mistral/index.d.ts.map +1 -1
  59. package/build/types/ai/mistral/streaming.d.ts +1 -1
  60. package/build/types/ai/mistral/streaming.d.ts.map +1 -1
  61. package/build/types/ai/mistral/utils.d.ts +5 -0
  62. package/build/types/ai/mistral/utils.d.ts.map +1 -1
  63. package/build/types/ai/vercel-ai/index.d.ts.map +1 -1
  64. package/build/types/ai/vercel-ai/vercel-ai-attributes.d.ts +3 -0
  65. package/build/types/ai/vercel-ai/vercel-ai-attributes.d.ts.map +1 -1
  66. package/build/types/ai/workers-ai/index.d.ts.map +1 -1
  67. package/build/types/ai/workers-ai/streaming.d.ts +1 -1
  68. package/build/types/ai/workers-ai/streaming.d.ts.map +1 -1
  69. package/build/types/index.d.ts +3 -1
  70. package/build/types/index.d.ts.map +1 -1
  71. package/build/types/integrations/cron.d.ts.map +1 -1
  72. package/build/types/integrations/google-genai.d.ts +3 -3
  73. package/build/types/integrations/google-genai.d.ts.map +1 -1
  74. package/build/types/integrations/mistral.d.ts.map +1 -1
  75. package/build/types/integrations/node-cron.d.ts +1 -1
  76. package/build/types/integrations/node-cron.d.ts.map +1 -1
  77. package/build/types/integrations/node-schedule.d.ts.map +1 -1
  78. package/build/types/integrations/vercel-ai/vercel-ai-dc-subscriber.d.ts.map +1 -1
  79. package/build/types/orchestrion/bundler/moduleInjectedTransform.d.ts.map +1 -1
  80. package/build/types/orchestrion/bundler/rollup.d.ts +3 -3
  81. package/build/types/orchestrion/bundler/rollup.d.ts.map +1 -1
  82. package/build/types/orchestrion/channels.d.ts +1 -0
  83. package/build/types/orchestrion/channels.d.ts.map +1 -1
  84. package/build/types/orchestrion/config/google-genai.d.ts +13 -0
  85. package/build/types/orchestrion/config/google-genai.d.ts.map +1 -1
  86. package/build/types/utils/cronMonitoring.d.ts +4 -5
  87. package/build/types/utils/cronMonitoring.d.ts.map +1 -1
  88. package/package.json +3 -3
@@ -1,4 +1,4 @@
1
- import { GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS, GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, GEN_AI_USAGE_OUTPUT_TOKENS, GEN_AI_USAGE_REASONING_OUTPUT_TOKENS, GEN_AI_USAGE_TOTAL_TOKENS } from "@sentry/conventions/attributes";
1
+ import { GEN_AI_COST_TOTAL_TOKENS, GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS, GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, GEN_AI_USAGE_OUTPUT_TOKENS, GEN_AI_USAGE_REASONING_OUTPUT_TOKENS, GEN_AI_USAGE_TOTAL_TOKENS } from "@sentry/conventions/attributes";
2
2
  // src/ai/vercel-ai/index.ts
3
3
  /**
4
4
  * Derive the `gen_ai.usage.*` cache/reasoning/prediction token attributes from an AI SDK
@@ -38,6 +38,8 @@ function getProviderMetadataAttributes(providerMetadata) {
38
38
  setAttributeIfDefined(attributes, GEN_AI_USAGE_TOTAL_TOKENS, googleUsage.totalTokenCount);
39
39
  setAttributeIfDefined(attributes, GEN_AI_USAGE_REASONING_OUTPUT_TOKENS, googleUsage.thoughtsTokenCount);
40
40
  }
41
+ const gatewayCost = Number(metadata.gateway?.cost);
42
+ if (metadata.gateway?.cost != null && Number.isFinite(gatewayCost)) attributes[GEN_AI_COST_TOTAL_TOKENS] = gatewayCost;
41
43
  return attributes;
42
44
  }
43
45
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../../../src/ai/vercel-ai/index.ts"],"sourcesContent":["import type { SpanAttributeValue } from '@sentry/core';\nimport {\n GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,\n GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,\n GEN_AI_USAGE_OUTPUT_TOKENS,\n GEN_AI_USAGE_REASONING_OUTPUT_TOKENS,\n GEN_AI_USAGE_TOTAL_TOKENS,\n} from '@sentry/conventions/attributes';\nimport type { OpenAiProviderMetadata, ProviderMetadata } from './vercel-ai-attributes';\n\n/**\n * Derive the `gen_ai.usage.*` cache/reasoning/prediction token attributes from an AI SDK\n * `providerMetadata` object.\n *\n * Used by the `ai` >= 7 tracing-channel subscriber, which receives `providerMetadata` as an object on\n * the channel result. Pass the already-parsed object; unknown/empty input yields `{}`.\n */\nexport function getProviderMetadataAttributes(providerMetadata: unknown): Record<string, number | string> {\n const attributes: Record<string, number | string> = {};\n\n if (!providerMetadata || typeof providerMetadata !== 'object') {\n return attributes;\n }\n const metadata = providerMetadata as ProviderMetadata;\n\n // OpenAI (v5 uses 'openai', v6 Azure Responses API uses 'azure')\n const openaiMetadata: OpenAiProviderMetadata | undefined = metadata.openai ?? metadata.azure;\n if (openaiMetadata) {\n setAttributeIfDefined(attributes, GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, openaiMetadata.cachedPromptTokens);\n setAttributeIfDefined(attributes, GEN_AI_USAGE_REASONING_OUTPUT_TOKENS, openaiMetadata.reasoningTokens);\n setAttributeIfDefined(\n attributes,\n 'gen_ai.usage.output_tokens.prediction_accepted',\n openaiMetadata.acceptedPredictionTokens,\n );\n setAttributeIfDefined(\n attributes,\n 'gen_ai.usage.output_tokens.prediction_rejected',\n openaiMetadata.rejectedPredictionTokens,\n );\n }\n\n if (metadata.anthropic) {\n const cachedInputTokens =\n metadata.anthropic.usage?.cache_read_input_tokens ?? metadata.anthropic.cacheReadInputTokens;\n setAttributeIfDefined(attributes, GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, cachedInputTokens);\n\n const cacheWriteInputTokens =\n metadata.anthropic.usage?.cache_creation_input_tokens ?? metadata.anthropic.cacheCreationInputTokens;\n setAttributeIfDefined(attributes, GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS, cacheWriteInputTokens);\n }\n\n if (metadata.bedrock?.usage) {\n setAttributeIfDefined(\n attributes,\n GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,\n metadata.bedrock.usage.cacheReadInputTokens,\n );\n setAttributeIfDefined(\n attributes,\n GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,\n metadata.bedrock.usage.cacheWriteInputTokens,\n );\n }\n\n if (metadata.deepseek) {\n setAttributeIfDefined(attributes, GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, metadata.deepseek.promptCacheHitTokens);\n setAttributeIfDefined(attributes, 'gen_ai.usage.input_tokens.cache_miss', metadata.deepseek.promptCacheMissTokens);\n }\n\n // Google (v5 uses 'google', v6 Vertex AI uses 'vertex'). Gemini reports its reasoning (\"thoughts\")\n // tokens separately from the candidate output count, so the SDK's `outputTokens` covers only the\n // visible answer. Recompute output from `candidatesTokenCount + thoughtsTokenCount` rather than\n // adding onto the existing value, which stays correct on `ai` v6+ where `outputTokens` already\n // folds reasoning in. `candidatesTokenCount` is omitted when the response is truncated during\n // thinking, which means no candidate tokens, so it counts as zero. Reasoning is a subset of\n // output per the conventions, so it is only written alongside the output it belongs to.\n const googleUsage = (metadata.google ?? metadata.vertex)?.usageMetadata;\n if (googleUsage && typeof googleUsage.thoughtsTokenCount === 'number' && googleUsage.thoughtsTokenCount > 0) {\n attributes[GEN_AI_USAGE_OUTPUT_TOKENS] = (googleUsage.candidatesTokenCount ?? 0) + googleUsage.thoughtsTokenCount;\n setAttributeIfDefined(attributes, GEN_AI_USAGE_TOTAL_TOKENS, googleUsage.totalTokenCount);\n setAttributeIfDefined(attributes, GEN_AI_USAGE_REASONING_OUTPUT_TOKENS, googleUsage.thoughtsTokenCount);\n }\n\n return attributes;\n}\n\n/**\n * Usage attributes derived from `providerMetadata`, which describes only the last step of a call.\n * They must not be written onto a span that reports usage aggregated across steps\n * (`gen_ai.invoke_agent`), where they would replace the aggregate with one step's figures.\n */\nexport const LAST_STEP_ONLY_USAGE_KEYS = new Set<string>([\n GEN_AI_USAGE_OUTPUT_TOKENS,\n GEN_AI_USAGE_TOTAL_TOKENS,\n GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,\n GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,\n]);\n\n/**\n * Sets an attribute only if the value is not null or undefined.\n */\nfunction setAttributeIfDefined(\n attributes: Record<string, unknown>,\n key: string,\n value: SpanAttributeValue | undefined,\n): void {\n if (value != null) {\n attributes[key] = value;\n }\n}\n"],"mappings":";;;;;;;;;AAiBA,SAAgB,8BAA8B,kBAA4D;CACxG,MAAM,aAA8C,CAAC;CAErD,IAAI,CAAC,oBAAoB,OAAO,qBAAqB,UACnD,OAAO;CAET,MAAM,WAAW;CAGjB,MAAM,iBAAqD,SAAS,UAAU,SAAS;CACvF,IAAI,gBAAgB;EAClB,sBAAsB,YAAY,sCAAsC,eAAe,kBAAkB;EACzG,sBAAsB,YAAY,sCAAsC,eAAe,eAAe;EACtG,sBACE,YACA,kDACA,eAAe,wBACjB;EACA,sBACE,YACA,kDACA,eAAe,wBACjB;CACF;CAEA,IAAI,SAAS,WAAW;EACtB,MAAM,oBACJ,SAAS,UAAU,OAAO,2BAA2B,SAAS,UAAU;EAC1E,sBAAsB,YAAY,sCAAsC,iBAAiB;EAEzF,MAAM,wBACJ,SAAS,UAAU,OAAO,+BAA+B,SAAS,UAAU;EAC9E,sBAAsB,YAAY,0CAA0C,qBAAqB;CACnG;CAEA,IAAI,SAAS,SAAS,OAAO;EAC3B,sBACE,YACA,sCACA,SAAS,QAAQ,MAAM,oBACzB;EACA,sBACE,YACA,0CACA,SAAS,QAAQ,MAAM,qBACzB;CACF;CAEA,IAAI,SAAS,UAAU;EACrB,sBAAsB,YAAY,sCAAsC,SAAS,SAAS,oBAAoB;EAC9G,sBAAsB,YAAY,wCAAwC,SAAS,SAAS,qBAAqB;CACnH;CASA,MAAM,eAAe,SAAS,UAAU,SAAS,OAAA,EAAS;CAC1D,IAAI,eAAe,OAAO,YAAY,uBAAuB,YAAY,YAAY,qBAAqB,GAAG;EAC3G,WAAW,+BAA+B,YAAY,wBAAwB,KAAK,YAAY;EAC/F,sBAAsB,YAAY,2BAA2B,YAAY,eAAe;EACxF,sBAAsB,YAAY,sCAAsC,YAAY,kBAAkB;CACxG;CAEA,OAAO;AACT;;;;;;AAOA,MAAa,4CAA4B,IAAI,IAAY;CACvD;CACA;CACA;CACA;AACF,CAAC;;;;AAKD,SAAS,sBACP,YACA,KACA,OACM;CACN,IAAI,SAAS,MACX,WAAW,OAAO;AAEtB"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../../../src/ai/vercel-ai/index.ts"],"sourcesContent":["import type { SpanAttributeValue } from '@sentry/core';\nimport {\n GEN_AI_COST_TOTAL_TOKENS,\n GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,\n GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,\n GEN_AI_USAGE_OUTPUT_TOKENS,\n GEN_AI_USAGE_REASONING_OUTPUT_TOKENS,\n GEN_AI_USAGE_TOTAL_TOKENS,\n} from '@sentry/conventions/attributes';\nimport type { OpenAiProviderMetadata, ProviderMetadata } from './vercel-ai-attributes';\n\n/**\n * Derive the `gen_ai.usage.*` cache/reasoning/prediction token attributes from an AI SDK\n * `providerMetadata` object.\n *\n * Used by the `ai` >= 7 tracing-channel subscriber, which receives `providerMetadata` as an object on\n * the channel result. Pass the already-parsed object; unknown/empty input yields `{}`.\n */\nexport function getProviderMetadataAttributes(providerMetadata: unknown): Record<string, number | string> {\n const attributes: Record<string, number | string> = {};\n\n if (!providerMetadata || typeof providerMetadata !== 'object') {\n return attributes;\n }\n const metadata = providerMetadata as ProviderMetadata;\n\n // OpenAI (v5 uses 'openai', v6 Azure Responses API uses 'azure')\n const openaiMetadata: OpenAiProviderMetadata | undefined = metadata.openai ?? metadata.azure;\n if (openaiMetadata) {\n setAttributeIfDefined(attributes, GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, openaiMetadata.cachedPromptTokens);\n setAttributeIfDefined(attributes, GEN_AI_USAGE_REASONING_OUTPUT_TOKENS, openaiMetadata.reasoningTokens);\n setAttributeIfDefined(\n attributes,\n 'gen_ai.usage.output_tokens.prediction_accepted',\n openaiMetadata.acceptedPredictionTokens,\n );\n setAttributeIfDefined(\n attributes,\n 'gen_ai.usage.output_tokens.prediction_rejected',\n openaiMetadata.rejectedPredictionTokens,\n );\n }\n\n if (metadata.anthropic) {\n const cachedInputTokens =\n metadata.anthropic.usage?.cache_read_input_tokens ?? metadata.anthropic.cacheReadInputTokens;\n setAttributeIfDefined(attributes, GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, cachedInputTokens);\n\n const cacheWriteInputTokens =\n metadata.anthropic.usage?.cache_creation_input_tokens ?? metadata.anthropic.cacheCreationInputTokens;\n setAttributeIfDefined(attributes, GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS, cacheWriteInputTokens);\n }\n\n if (metadata.bedrock?.usage) {\n setAttributeIfDefined(\n attributes,\n GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,\n metadata.bedrock.usage.cacheReadInputTokens,\n );\n setAttributeIfDefined(\n attributes,\n GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,\n metadata.bedrock.usage.cacheWriteInputTokens,\n );\n }\n\n if (metadata.deepseek) {\n setAttributeIfDefined(attributes, GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, metadata.deepseek.promptCacheHitTokens);\n setAttributeIfDefined(attributes, 'gen_ai.usage.input_tokens.cache_miss', metadata.deepseek.promptCacheMissTokens);\n }\n\n // Google (v5 uses 'google', v6 Vertex AI uses 'vertex'). Gemini reports its reasoning (\"thoughts\")\n // tokens separately from the candidate output count, so the SDK's `outputTokens` covers only the\n // visible answer. Recompute output from `candidatesTokenCount + thoughtsTokenCount` rather than\n // adding onto the existing value, which stays correct on `ai` v6+ where `outputTokens` already\n // folds reasoning in. `candidatesTokenCount` is omitted when the response is truncated during\n // thinking, which means no candidate tokens, so it counts as zero. Reasoning is a subset of\n // output per the conventions, so it is only written alongside the output it belongs to.\n const googleUsage = (metadata.google ?? metadata.vertex)?.usageMetadata;\n if (googleUsage && typeof googleUsage.thoughtsTokenCount === 'number' && googleUsage.thoughtsTokenCount > 0) {\n attributes[GEN_AI_USAGE_OUTPUT_TOKENS] = (googleUsage.candidatesTokenCount ?? 0) + googleUsage.thoughtsTokenCount;\n setAttributeIfDefined(attributes, GEN_AI_USAGE_TOTAL_TOKENS, googleUsage.totalTokenCount);\n setAttributeIfDefined(attributes, GEN_AI_USAGE_REASONING_OUTPUT_TOKENS, googleUsage.thoughtsTokenCount);\n }\n\n // Vercel AI Gateway reports the billed USD cost of the call, as a decimal string.\n const gatewayCost = Number(metadata.gateway?.cost);\n if (metadata.gateway?.cost != null && Number.isFinite(gatewayCost)) {\n attributes[GEN_AI_COST_TOTAL_TOKENS] = gatewayCost;\n }\n\n return attributes;\n}\n\n/**\n * Usage attributes derived from `providerMetadata`, which describes only the last step of a call.\n * They must not be written onto a span that reports usage aggregated across steps\n * (`gen_ai.invoke_agent`), where they would replace the aggregate with one step's figures.\n */\nexport const LAST_STEP_ONLY_USAGE_KEYS = new Set<string>([\n GEN_AI_USAGE_OUTPUT_TOKENS,\n GEN_AI_USAGE_TOTAL_TOKENS,\n GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,\n GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,\n]);\n\n/**\n * Sets an attribute only if the value is not null or undefined.\n */\nfunction setAttributeIfDefined(\n attributes: Record<string, unknown>,\n key: string,\n value: SpanAttributeValue | undefined,\n): void {\n if (value != null) {\n attributes[key] = value;\n }\n}\n"],"mappings":";;;;;;;;;AAkBA,SAAgB,8BAA8B,kBAA4D;CACxG,MAAM,aAA8C,CAAC;CAErD,IAAI,CAAC,oBAAoB,OAAO,qBAAqB,UACnD,OAAO;CAET,MAAM,WAAW;CAGjB,MAAM,iBAAqD,SAAS,UAAU,SAAS;CACvF,IAAI,gBAAgB;EAClB,sBAAsB,YAAY,sCAAsC,eAAe,kBAAkB;EACzG,sBAAsB,YAAY,sCAAsC,eAAe,eAAe;EACtG,sBACE,YACA,kDACA,eAAe,wBACjB;EACA,sBACE,YACA,kDACA,eAAe,wBACjB;CACF;CAEA,IAAI,SAAS,WAAW;EACtB,MAAM,oBACJ,SAAS,UAAU,OAAO,2BAA2B,SAAS,UAAU;EAC1E,sBAAsB,YAAY,sCAAsC,iBAAiB;EAEzF,MAAM,wBACJ,SAAS,UAAU,OAAO,+BAA+B,SAAS,UAAU;EAC9E,sBAAsB,YAAY,0CAA0C,qBAAqB;CACnG;CAEA,IAAI,SAAS,SAAS,OAAO;EAC3B,sBACE,YACA,sCACA,SAAS,QAAQ,MAAM,oBACzB;EACA,sBACE,YACA,0CACA,SAAS,QAAQ,MAAM,qBACzB;CACF;CAEA,IAAI,SAAS,UAAU;EACrB,sBAAsB,YAAY,sCAAsC,SAAS,SAAS,oBAAoB;EAC9G,sBAAsB,YAAY,wCAAwC,SAAS,SAAS,qBAAqB;CACnH;CASA,MAAM,eAAe,SAAS,UAAU,SAAS,OAAA,EAAS;CAC1D,IAAI,eAAe,OAAO,YAAY,uBAAuB,YAAY,YAAY,qBAAqB,GAAG;EAC3G,WAAW,+BAA+B,YAAY,wBAAwB,KAAK,YAAY;EAC/F,sBAAsB,YAAY,2BAA2B,YAAY,eAAe;EACxF,sBAAsB,YAAY,sCAAsC,YAAY,kBAAkB;CACxG;CAGA,MAAM,cAAc,OAAO,SAAS,SAAS,IAAI;CACjD,IAAI,SAAS,SAAS,QAAQ,QAAQ,OAAO,SAAS,WAAW,GAC/D,WAAW,4BAA4B;CAGzC,OAAO;AACT;;;;;;AAOA,MAAa,4CAA4B,IAAI,IAAY;CACvD;CACA;CACA;CACA;AACF,CAAC;;;;AAKD,SAAS,sBACP,YACA,KACA,OACM;CACN,IAAI,SAAS,MACX,WAAW,OAAO;AAEtB"}
@@ -1,10 +1,10 @@
1
- import { isReadableStream, resolveAIRecordingOptions } from "../core/utils.js";
1
+ import { getErrorStatus, getRequestSignal, isReadableStream, resolveAIRecordingOptions } from "../core/utils.js";
2
2
  import { shouldSkipAiProviderSpan } from "../pi-ai/providers.js";
3
3
  import "./constants.js";
4
4
  import { instrumentWorkersAiStream } from "./streaming.js";
5
5
  import { WORKERS_AI_OPERATION_SPAN_OPS, addRequestAttributes, addResponseAttributes, extractRequestAttributes, getOperationName } from "./utils.js";
6
6
  import { SENTRY_OP } from "@sentry/conventions/attributes";
7
- import { SPAN_STATUS_ERROR, getClient, hasSpanStreamingEnabled, startSpan, startSpanManual } from "@sentry/core";
7
+ import { getClient, hasSpanStreamingEnabled, startSpan, startSpanManual } from "@sentry/core";
8
8
  // src/ai/workers-ai/index.ts
9
9
  /**
10
10
  * Wrap the `run` method of the Workers AI binding with Sentry tracing.
@@ -16,6 +16,7 @@ function instrumentRun(originalRun, context, options) {
16
16
  const operationName = getOperationName(model, inputs);
17
17
  const requestAttributes = extractRequestAttributes(model, inputs, operationName);
18
18
  const modelName = typeof model === "string" && model ? model : "unknown";
19
+ const abortSignal = getRequestSignal(runOptions);
19
20
  const client = getClient();
20
21
  const isStreamRequested = !!inputs && typeof inputs === "object" && inputs.stream === true;
21
22
  const returnsRawResponse = !!runOptions && typeof runOptions === "object" && (runOptions.returnRawResponse === true || runOptions.websocket === true);
@@ -28,10 +29,7 @@ function instrumentRun(originalRun, context, options) {
28
29
  };
29
30
  if (isStreamRequested && !returnsRawResponse) return startSpanManual(spanConfig, (span) => {
30
31
  const handleError = (error) => {
31
- span.setStatus({
32
- code: SPAN_STATUS_ERROR,
33
- message: "internal_error"
34
- });
32
+ span.setStatus(getErrorStatus(abortSignal));
35
33
  span.end();
36
34
  throw error;
37
35
  };
@@ -43,7 +41,7 @@ function instrumentRun(originalRun, context, options) {
43
41
  }
44
42
  if (options.recordInputs) addRequestAttributes(span, inputs, operationName);
45
43
  return originalResult.then((result) => {
46
- if (isReadableStream(result)) return instrumentWorkersAiStream(result, span, options.recordOutputs);
44
+ if (isReadableStream(result)) return instrumentWorkersAiStream(result, span, options.recordOutputs, abortSignal);
47
45
  addResponseAttributes(span, result, options.recordOutputs, operationName);
48
46
  span.end();
49
47
  return result;
@@ -55,6 +53,9 @@ function instrumentRun(originalRun, context, options) {
55
53
  return originalResult.then((result) => {
56
54
  if (!returnsRawResponse) addResponseAttributes(span, result, options.recordOutputs, operationName);
57
55
  return result;
56
+ }, (error) => {
57
+ span.setStatus(getErrorStatus(abortSignal));
58
+ throw error;
58
59
  });
59
60
  });
60
61
  };
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../../../src/ai/workers-ai/index.ts"],"sourcesContent":["import { SENTRY_OP } from '@sentry/conventions/attributes';\nimport { getClient, hasSpanStreamingEnabled, SPAN_STATUS_ERROR, startSpan, startSpanManual } from '@sentry/core';\nimport type { Span } from '@sentry/core';\nimport { isReadableStream, resolveAIRecordingOptions } from '../core/utils';\nimport { shouldSkipAiProviderSpan } from '../pi-ai/providers';\nimport { WORKERS_AI_INTEGRATION_NAME } from './constants';\nimport { instrumentWorkersAiStream } from './streaming';\nimport type { WorkersAiOptions } from './types';\nimport {\n addRequestAttributes,\n addResponseAttributes,\n extractRequestAttributes,\n getOperationName,\n WORKERS_AI_OPERATION_SPAN_OPS,\n} from './utils';\n\n/**\n * Wrap the `run` method of the Workers AI binding with Sentry tracing.\n */\nfunction instrumentRun(\n originalRun: (...args: unknown[]) => Promise<unknown>,\n context: unknown,\n options: WorkersAiOptions & Required<Pick<WorkersAiOptions, 'recordInputs' | 'recordOutputs'>>,\n): (...args: unknown[]) => Promise<unknown> {\n return function instrumentedRun(...args: unknown[]): Promise<unknown> {\n if (shouldSkipAiProviderSpan(WORKERS_AI_INTEGRATION_NAME)) {\n return originalRun.apply(context, args);\n }\n\n const [model, inputs, runOptions] = args as [unknown, unknown, Record<string, unknown> | undefined];\n\n const operationName = getOperationName(model, inputs);\n const requestAttributes = extractRequestAttributes(model, inputs, operationName);\n const modelName = typeof model === 'string' && model ? model : 'unknown';\n const client = getClient();\n\n const isStreamRequested =\n !!inputs && typeof inputs === 'object' && (inputs as { stream?: unknown }).stream === true;\n const returnsRawResponse =\n !!runOptions &&\n typeof runOptions === 'object' &&\n (runOptions.returnRawResponse === true || runOptions.websocket === true);\n\n const spanConfig = {\n // With span streaming, omit the `'unknown'` model sentinel so the name stays low-cardinality.\n name:\n modelName !== 'unknown' || !(client && hasSpanStreamingEnabled(client))\n ? `${operationName} ${modelName}`\n : operationName,\n attributes: {\n [SENTRY_OP]: WORKERS_AI_OPERATION_SPAN_OPS[operationName],\n ...requestAttributes,\n },\n };\n\n if (isStreamRequested && !returnsRawResponse) {\n return startSpanManual(spanConfig, (span: Span) => {\n // `startSpanManual` does not auto-end the span, so we must end it on every exit path,\n // including a synchronous throw from `run`.\n const handleError = (error: unknown): never => {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n span.end();\n throw error;\n };\n\n let originalResult: Promise<unknown>;\n\n try {\n originalResult = originalRun.apply(context, args) as Promise<unknown>;\n } catch (error) {\n return handleError(error);\n }\n\n if (options.recordInputs) {\n addRequestAttributes(span, inputs, operationName);\n }\n\n return originalResult.then(result => {\n if (isReadableStream<Uint8Array>(result)) {\n return instrumentWorkersAiStream(result, span, options.recordOutputs);\n }\n\n // The model did not actually return a stream — finalize the span eagerly.\n addResponseAttributes(span, result, options.recordOutputs, operationName);\n span.end();\n return result;\n }, handleError);\n });\n }\n\n return startSpan(spanConfig, (span: Span) => {\n const originalResult = originalRun.apply(context, args) as Promise<unknown>;\n\n if (options.recordInputs) {\n addRequestAttributes(span, inputs, operationName);\n }\n\n return originalResult.then(result => {\n if (!returnsRawResponse) {\n addResponseAttributes(span, result, options.recordOutputs, operationName);\n }\n return result;\n });\n });\n };\n}\n\n/**\n * Instrument a Cloudflare Workers AI binding (`env.AI`) with Sentry tracing.\n *\n * This wraps the binding's `run` method to create `gen_ai` spans following the\n * Sentry AI Agents conventions. All other methods are passed through untouched.\n *\n * In `@sentry/cloudflare`, the `env.AI` binding is instrumented automatically —\n * wrapping manually is only needed to pass custom options.\n *\n * @example\n * ```javascript\n * const ai = Sentry.instrumentWorkersAiClient(env.AI, { recordInputs: true, recordOutputs: true });\n * const result = await ai.run('@cf/meta/llama-3.1-8b-instruct', { prompt: 'Hello' });\n * ```\n */\nexport function instrumentWorkersAiClient<T extends object>(client: T, options?: WorkersAiOptions): T {\n const resolvedOptions = resolveAIRecordingOptions(options);\n\n const instrumented = new Proxy(client, {\n get(target: object, prop: string | symbol, receiver: unknown): unknown {\n const value = Reflect.get(target, prop, receiver);\n\n if (prop === 'run' && typeof value === 'function') {\n return instrumentRun(value as (...args: unknown[]) => Promise<unknown>, target, resolvedOptions);\n }\n\n // Bind passed-through functions to the original target to preserve `this` (e.g. private fields).\n return typeof value === 'function' ? (value as (...args: unknown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I;IACT,OAAO;GACT,GAAG,WAAW;EAChB,CAAC;EAGH,OAAO,UAAU,aAAa,SAAe;GAC3C,MAAM,iBAAiB,YAAY,MAAM,SAAS,IAAI;GAEtD,IAAI,QAAQ,cACV,qBAAqB,MAAM,QAAQ,aAAa;GAGlD,OAAO,eAAe,MAAK,WAAU;IACnC,IAAI,CAAC,oBACH,sBAAsB,MAAM,QAAQ,QAAQ,eAAe,aAAa;IAE1E,OAAO;GACT,CAAC;EACH,CAAC;CACH;AACF;;;;;;;;;;;;;;;;AAiBA,SAAgB,0BAA4C,QAAW,SAA+B;CACpG,MAAM,kBAAkB,0BAA0B,OAAO;CAezD,OAAO,IAbkB,MAAM,QAAQ,EACrC,IAAI,QAAgB,MAAuB,UAA4B;EACrE,MAAM,QAAQ,QAAQ,IAAI,QAAQ,MAAM,QAAQ;EAEhD,IAAI,SAAS,SAAS,OAAO,UAAU,YACrC,OAAO,cAAc,OAAmD,QAAQ,eAAe;EAIjG,OAAO,OAAO,UAAU,aAAc,MAA0C,KAAK,MAAM,IAAI;CACjG,EACF,CAEkB;AACpB"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../../../src/ai/workers-ai/index.ts"],"sourcesContent":["import { SENTRY_OP } from '@sentry/conventions/attributes';\nimport { getClient, hasSpanStreamingEnabled, startSpan, startSpanManual } from '@sentry/core';\nimport type { Span } from '@sentry/core';\nimport { getErrorStatus, getRequestSignal, isReadableStream, resolveAIRecordingOptions } from '../core/utils';\nimport { shouldSkipAiProviderSpan } from '../pi-ai/providers';\nimport { WORKERS_AI_INTEGRATION_NAME } from './constants';\nimport { instrumentWorkersAiStream } from './streaming';\nimport type { WorkersAiOptions } from './types';\nimport {\n addRequestAttributes,\n addResponseAttributes,\n extractRequestAttributes,\n getOperationName,\n WORKERS_AI_OPERATION_SPAN_OPS,\n} from './utils';\n\n/**\n * Wrap the `run` method of the Workers AI binding with Sentry tracing.\n */\nfunction instrumentRun(\n originalRun: (...args: unknown[]) => Promise<unknown>,\n context: unknown,\n options: WorkersAiOptions & Required<Pick<WorkersAiOptions, 'recordInputs' | 'recordOutputs'>>,\n): (...args: unknown[]) => Promise<unknown> {\n return function instrumentedRun(...args: unknown[]): Promise<unknown> {\n if (shouldSkipAiProviderSpan(WORKERS_AI_INTEGRATION_NAME)) {\n return originalRun.apply(context, args);\n }\n\n const [model, inputs, runOptions] = args as [unknown, unknown, Record<string, unknown> | undefined];\n\n const operationName = getOperationName(model, inputs);\n const requestAttributes = extractRequestAttributes(model, inputs, operationName);\n const modelName = typeof model === 'string' && model ? model : 'unknown';\n const abortSignal = getRequestSignal(runOptions);\n const client = getClient();\n\n const isStreamRequested =\n !!inputs && typeof inputs === 'object' && (inputs as { stream?: unknown }).stream === true;\n const returnsRawResponse =\n !!runOptions &&\n typeof runOptions === 'object' &&\n (runOptions.returnRawResponse === true || runOptions.websocket === true);\n\n const spanConfig = {\n // With span streaming, omit the `'unknown'` model sentinel so the name stays low-cardinality.\n name:\n modelName !== 'unknown' || !(client && hasSpanStreamingEnabled(client))\n ? `${operationName} ${modelName}`\n : operationName,\n attributes: {\n [SENTRY_OP]: WORKERS_AI_OPERATION_SPAN_OPS[operationName],\n ...requestAttributes,\n },\n };\n\n if (isStreamRequested && !returnsRawResponse) {\n return startSpanManual(spanConfig, (span: Span) => {\n // `startSpanManual` does not auto-end the span, so we must end it on every exit path,\n // including a synchronous throw from `run`.\n const handleError = (error: unknown): never => {\n span.setStatus(getErrorStatus(abortSignal));\n span.end();\n throw error;\n };\n\n let originalResult: Promise<unknown>;\n\n try {\n originalResult = originalRun.apply(context, args) as Promise<unknown>;\n } catch (error) {\n return handleError(error);\n }\n\n if (options.recordInputs) {\n addRequestAttributes(span, inputs, operationName);\n }\n\n return originalResult.then(result => {\n if (isReadableStream<Uint8Array>(result)) {\n return instrumentWorkersAiStream(result, span, options.recordOutputs, abortSignal);\n }\n\n // The model did not actually return a stream — finalize the span eagerly.\n addResponseAttributes(span, result, options.recordOutputs, operationName);\n span.end();\n return result;\n }, handleError);\n });\n }\n\n return startSpan(spanConfig, (span: Span) => {\n const originalResult = originalRun.apply(context, args) as Promise<unknown>;\n\n if (options.recordInputs) {\n addRequestAttributes(span, inputs, operationName);\n }\n\n return originalResult.then(\n result => {\n if (!returnsRawResponse) {\n addResponseAttributes(span, result, options.recordOutputs, operationName);\n }\n return result;\n },\n error => {\n span.setStatus(getErrorStatus(abortSignal));\n throw error;\n },\n );\n });\n };\n}\n\n/**\n * Instrument a Cloudflare Workers AI binding (`env.AI`) with Sentry tracing.\n *\n * This wraps the binding's `run` method to create `gen_ai` spans following the\n * Sentry AI Agents conventions. All other methods are passed through untouched.\n *\n * In `@sentry/cloudflare`, the `env.AI` binding is instrumented automatically —\n * wrapping manually is only needed to pass custom options.\n *\n * @example\n * ```javascript\n * const ai = Sentry.instrumentWorkersAiClient(env.AI, { recordInputs: true, recordOutputs: true });\n * const result = await ai.run('@cf/meta/llama-3.1-8b-instruct', { prompt: 'Hello' });\n * ```\n */\nexport function instrumentWorkersAiClient<T extends object>(client: T, options?: WorkersAiOptions): T {\n const resolvedOptions = resolveAIRecordingOptions(options);\n\n const instrumented = new Proxy(client, {\n get(target: object, prop: string | symbol, receiver: unknown): unknown {\n const value = Reflect.get(target, prop, receiver);\n\n if (prop === 'run' && typeof value === 'function') {\n return instrumentRun(value as (...args: unknown[]) => Promise<unknown>, target, resolvedOptions);\n }\n\n // Bind passed-through functions to the original target to preserve `this` (e.g. private fields).\n return typeof value === 'function' ? (value as (...args: unknown[]) => unknown).bind(target) : value;\n },\n }) as T;\n\n return instrumented;\n}\n"],"mappings":";;;;;;;;;;;AAmBA,SAAS,cACP,aACA,SACA,SAC0C;CAC1C,OAAO,SAAS,gBAAgB,GAAG,MAAmC;EACpE,IAAI,yBAAA,WAAoD,GACtD,OAAO,YAAY,MAAM,SAAS,IAAI;EAGxC,MAAM,CAAC,OAAO,QAAQ,cAAc;EAEpC,MAAM,gBAAgB,iBAAiB,OAAO,MAAM;EACpD,MAAM,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T,IACA,UAAS;IACP,KAAK,UAAU,eAAe,WAAW,CAAC;IAC1C,MAAM;GACR,CACF;EACF,CAAC;CACH;AACF;;;;;;;;;;;;;;;;AAiBA,SAAgB,0BAA4C,QAAW,SAA+B;CACpG,MAAM,kBAAkB,0BAA0B,OAAO;CAezD,OAAO,IAbkB,MAAM,QAAQ,EACrC,IAAI,QAAgB,MAAuB,UAA4B;EACrE,MAAM,QAAQ,QAAQ,IAAI,QAAQ,MAAM,QAAQ;EAEhD,IAAI,SAAS,SAAS,OAAO,UAAU,YACrC,OAAO,cAAc,OAAmD,QAAQ,eAAe;EAIjG,OAAO,OAAO,UAAU,aAAc,MAA0C,KAAK,MAAM,IAAI;CACjG,EACF,CAEkB;AACpB"}
@@ -1,7 +1,6 @@
1
1
  import { getToolCallKey } from "../core/streaming-tool-calls.js";
2
- import { endStreamSpan, setOutputMessagesAttribute } from "../core/utils.js";
2
+ import { endStreamSpan, getErrorStatus, setOutputMessagesAttribute } from "../core/utils.js";
3
3
  import "./utils.js";
4
- import { SPAN_STATUS_ERROR } from "@sentry/core";
5
4
  // src/ai/workers-ai/streaming.ts
6
5
  /**
7
6
  * Accumulate a fragmented OpenAI-compatible tool call (delivered across multiple
@@ -71,7 +70,7 @@ function processLine(line, state, recordOutputs, toolCallAccumulator) {
71
70
  *
72
71
  * The span is ended once the consumer finishes reading (or cancels) the stream.
73
72
  */
74
- function instrumentWorkersAiStream(stream, span, recordOutputs) {
73
+ function instrumentWorkersAiStream(stream, span, recordOutputs, abortSignal) {
75
74
  const reader = stream.getReader();
76
75
  const decoder = new TextDecoder();
77
76
  const state = {
@@ -124,10 +123,7 @@ function instrumentWorkersAiStream(stream, span, recordOutputs) {
124
123
  flushBuffer(false);
125
124
  controller.enqueue(value);
126
125
  } catch (error) {
127
- span.setStatus({
128
- code: SPAN_STATUS_ERROR,
129
- message: "internal_error"
130
- });
126
+ span.setStatus(getErrorStatus(abortSignal));
131
127
  finish();
132
128
  controller.error(error);
133
129
  }
@@ -1 +1 @@
1
- {"version":3,"file":"streaming.js","names":[],"sources":["../../../../src/ai/workers-ai/streaming.ts"],"sourcesContent":["import { SPAN_STATUS_ERROR } from '@sentry/core';\nimport type { Span } from '@sentry/core';\nimport { getToolCallKey } from '../core/streaming-tool-calls';\nimport { endStreamSpan, type StreamResponseState } from '../core/utils';\nimport type { WorkersAiUsage } from './types';\nimport { setOutputMessagesAttribute } from './utils';\n\ninterface WorkersAiStreamingToolCall {\n index?: number | null;\n id?: string;\n type?: string;\n function?: { name?: string; arguments?: string };\n // Some Workers AI models stream tool calls with the name/arguments at the top\n // level of the tool-call object instead of nested under `function`.\n name?: string;\n arguments?: string;\n}\n\ninterface WorkersAiStreamChunk {\n // Native Workers AI streaming shape (`env.AI.run` with `stream: true`).\n response?: unknown;\n tool_calls?: unknown[];\n // OpenAI-compatible streaming shape emitted for models routed through the\n // OpenAI-compatible endpoint (e.g. via `workers-ai-provider`).\n id?: unknown;\n model?: unknown;\n choices?: Array<{\n delta?: { content?: unknown; tool_calls?: WorkersAiStreamingToolCall[] };\n finish_reason?: unknown;\n }>;\n usage?: WorkersAiUsage & { prompt_tokens?: number; completion_tokens?: number; total_tokens?: number };\n}\n\n/**\n * Tool calls accumulated from a stream, keyed in the order they were opened (so output order is arrival order).\n */\ninterface ToolCallAccumulator {\n calls: Map<string, WorkersAiStreamingToolCall>;\n /** Key of the latest call, which argument fragments with neither `index`, `id` nor name continue. */\n lastKey?: string;\n /** Key of the call currently open for a reported `index`, when a new `id` reused that index. */\n keyByIndex: Map<number, string>;\n}\n\n/**\n * Accumulate a fragmented OpenAI-compatible tool call (delivered across multiple\n * `choices[].delta.tool_calls` chunks) into the accumulator.\n */\nfunction accumulateStreamingToolCalls(toolCalls: WorkersAiStreamingToolCall[], accumulator: ToolCallAccumulator): void {\n for (const toolCall of toolCalls) {\n // Normalize both shapes: name/arguments nested under `function`, or at the top level.\n const name = toolCall.function?.name ?? toolCall.name;\n const args = toolCall.function?.arguments ?? toolCall.arguments;\n\n // A tool call must carry at least a name or argument fragment to be meaningful.\n if (name == null && args == null) {\n continue;\n }\n\n const key = getToolCallKey(toolCall, name, accumulator);\n const existing = accumulator.calls.get(key);\n\n if (!existing) {\n accumulator.calls.set(key, {\n index: toolCall.index,\n id: toolCall.id,\n type: toolCall.type,\n function: {\n name,\n arguments: args ?? '',\n },\n });\n } else if (existing.function) {\n if (name && !existing.function.name) {\n existing.function.name = name;\n }\n if (args) {\n existing.function.arguments = `${existing.function.arguments ?? ''}${args}`;\n }\n }\n accumulator.lastKey = key;\n }\n}\n\n/**\n * Parse a single SSE line (`data: {...}`) and accumulate its data into the streaming state.\n *\n * Handles both the native Workers AI shape (top-level `response`/`tool_calls`) and the\n * OpenAI-compatible shape (`choices[].delta.content`/`choices[].delta.tool_calls`), because\n * the same `run()` call transparently yields either format depending on the model.\n */\nfunction processLine(\n line: string,\n state: StreamResponseState,\n recordOutputs: boolean,\n toolCallAccumulator: ToolCallAccumulator,\n): void {\n const trimmed = line.trim();\n if (!trimmed.startsWith('data:')) {\n return;\n }\n\n const data = trimmed.slice('data:'.length).trim();\n if (!data || data === '[DONE]') {\n return;\n }\n\n let parsed: WorkersAiStreamChunk;\n try {\n parsed = JSON.parse(data) as WorkersAiStreamChunk;\n } catch {\n return;\n }\n\n if (parsed.usage) {\n if (typeof parsed.usage.prompt_tokens === 'number') {\n state.promptTokens = parsed.usage.prompt_tokens;\n }\n if (typeof parsed.usage.completion_tokens === 'number') {\n state.completionTokens = parsed.usage.completion_tokens;\n }\n if (typeof parsed.usage.total_tokens === 'number') {\n state.totalTokens = parsed.usage.total_tokens;\n }\n }\n\n if (recordOutputs && typeof parsed.response === 'string') {\n state.responseTexts.push(parsed.response);\n }\n\n if (recordOutputs && Array.isArray(parsed.tool_calls) && parsed.tool_calls.length > 0) {\n state.toolCalls.push(...parsed.tool_calls);\n }\n\n if (Array.isArray(parsed.choices)) {\n if (typeof parsed.id === 'string') {\n state.responseId = parsed.id;\n }\n if (typeof parsed.model === 'string') {\n state.responseModel = parsed.model;\n }\n\n for (const choice of parsed.choices) {\n if (recordOutputs && typeof choice.delta?.content === 'string' && choice.delta.content) {\n state.responseTexts.push(choice.delta.content);\n }\n if (recordOutputs && Array.isArray(choice.delta?.tool_calls)) {\n accumulateStreamingToolCalls(choice.delta.tool_calls, toolCallAccumulator);\n }\n if (typeof choice.finish_reason === 'string') {\n state.finishReasons.push(choice.finish_reason);\n }\n }\n }\n}\n\n/**\n * Wrap a Workers AI streaming response (a server-sent-events `ReadableStream`) so we can\n * accumulate the response text and token usage while passing the original bytes through untouched.\n *\n * The span is ended once the consumer finishes reading (or cancels) the stream.\n */\nexport function instrumentWorkersAiStream(\n stream: ReadableStream<Uint8Array>,\n span: Span,\n recordOutputs: boolean,\n): ReadableStream<Uint8Array> {\n const reader = stream.getReader();\n const decoder = new TextDecoder();\n\n const state: StreamResponseState = {\n responseId: '',\n responseModel: '',\n finishReasons: [],\n responseTexts: [],\n toolCalls: [],\n promptTokens: undefined,\n completionTokens: undefined,\n totalTokens: undefined,\n };\n\n // OpenAI-compatible tool calls arrive fragmented across chunks and are keyed by index;\n // accumulate them here and flatten into `state.toolCalls` once the stream ends.\n const toolCallAccumulator: ToolCallAccumulator = { calls: new Map(), keyByIndex: new Map() };\n\n let buffer = '';\n let spanEnded = false;\n\n const finish = (): void => {\n if (spanEnded) {\n return;\n }\n spanEnded = true;\n\n if (recordOutputs) {\n const accumulatedToolCalls = [...toolCallAccumulator.calls.values()];\n if (accumulatedToolCalls.length > 0) {\n state.toolCalls.push(...accumulatedToolCalls);\n }\n\n // Set the authoritative `gen_ai.output.messages` alongside the deprecated response\n // attributes `endStreamSpan` writes, so tool calls survive Relay's lossy migration.\n setOutputMessagesAttribute(span, {\n responseText: state.responseTexts.join(''),\n toolCalls: state.toolCalls,\n finishReason: state.finishReasons[0],\n });\n }\n\n endStreamSpan(span, state, recordOutputs);\n };\n\n const flushBuffer = (isDone: boolean): void => {\n const lines = buffer.split('\\n');\n // Keep the last (potentially incomplete) line in the buffer unless the stream is done.\n buffer = isDone ? '' : (lines.pop() ?? '');\n for (const line of lines) {\n processLine(line, state, recordOutputs, toolCallAccumulator);\n }\n };\n\n return new ReadableStream<Uint8Array>({\n async pull(controller) {\n try {\n const { done, value } = await reader.read();\n\n if (done) {\n buffer += decoder.decode();\n flushBuffer(true);\n finish();\n controller.close();\n return;\n }\n\n buffer += decoder.decode(value, { stream: true });\n flushBuffer(false);\n controller.enqueue(value);\n } catch (error) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n finish();\n controller.error(error);\n }\n },\n async cancel(reason) {\n finish();\n await reader.cancel(reason);\n },\n });\n}\n"],"mappings":";;;;;;;;;AAgDA,SAAS,6BAA6B,WAAyC,aAAwC;CACrH,KAAK,MAAM,YAAY,WAAW;EAEhC,MAAM,OAAO,SAAS,UAAU,QAAQ,SAAS;EACjD,MAAM,OAAO,SAAS,UAAU,aAAa,SAAS;EAGtD,IAAI,QAAQ,QAAQ,QAAQ,MAC1B;EAGF,MAAM,MAAM,eAAe,UAAU,MAAM,WAAW;EACtD,MAAM,WAAW,YAAY,MAAM,IAAI,GAAG;EAE1C,IAAI,CAAC,UACH,YAAY,MAAM,IAAI,KAAK;GACzB,OAAO,SAAS;GAChB,IAAI,SAAS;GACb,MAAM,SAAS;GACf,UAAU;IACR;IACA,WAAW,QAAQ;GACrB;EACF,CAAC;OACI,IAAI,SAAS,UAAU;GAC5B,IAAI,QAAQ,CAAC,SAAS,SAAS,MAC7B,SAAS,SAAS,OAAO;GAE3B,IAAI,MACF,SAAS,SAAS,YAAY,GAAG,SAAS,SAAS,aAAa,KAAK;EAEzE;EACA,YAAY,UAAU;CACxB;AACF;;;;;;;;AASA,SAAS,YACP,MACA,OACA,eACA,qBACM;CACN,MAAM,UAAU,KAAK,KAAK;CAC1B,IAAI,CAAC,QAAQ,WAAW,OAAO,GAC7B;CAGF,MAAM,OAAO,QAAQ,MAAM,CAAc,CAAC,CAAC,KAA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":"streaming.js","names":[],"sources":["../../../../src/ai/workers-ai/streaming.ts"],"sourcesContent":["import type { Span } from '@sentry/core';\nimport { getToolCallKey } from '../core/streaming-tool-calls';\nimport { endStreamSpan, getErrorStatus, type StreamResponseState } from '../core/utils';\nimport type { WorkersAiUsage } from './types';\nimport { setOutputMessagesAttribute } from './utils';\n\ninterface WorkersAiStreamingToolCall {\n index?: number | null;\n id?: string;\n type?: string;\n function?: { name?: string; arguments?: string };\n // Some Workers AI models stream tool calls with the name/arguments at the top\n // level of the tool-call object instead of nested under `function`.\n name?: string;\n arguments?: string;\n}\n\ninterface WorkersAiStreamChunk {\n // Native Workers AI streaming shape (`env.AI.run` with `stream: true`).\n response?: unknown;\n tool_calls?: unknown[];\n // OpenAI-compatible streaming shape emitted for models routed through the\n // OpenAI-compatible endpoint (e.g. via `workers-ai-provider`).\n id?: unknown;\n model?: unknown;\n choices?: Array<{\n delta?: { content?: unknown; tool_calls?: WorkersAiStreamingToolCall[] };\n finish_reason?: unknown;\n }>;\n usage?: WorkersAiUsage & { prompt_tokens?: number; completion_tokens?: number; total_tokens?: number };\n}\n\n/**\n * Tool calls accumulated from a stream, keyed in the order they were opened (so output order is arrival order).\n */\ninterface ToolCallAccumulator {\n calls: Map<string, WorkersAiStreamingToolCall>;\n /** Key of the latest call, which argument fragments with neither `index`, `id` nor name continue. */\n lastKey?: string;\n /** Key of the call currently open for a reported `index`, when a new `id` reused that index. */\n keyByIndex: Map<number, string>;\n}\n\n/**\n * Accumulate a fragmented OpenAI-compatible tool call (delivered across multiple\n * `choices[].delta.tool_calls` chunks) into the accumulator.\n */\nfunction accumulateStreamingToolCalls(toolCalls: WorkersAiStreamingToolCall[], accumulator: ToolCallAccumulator): void {\n for (const toolCall of toolCalls) {\n // Normalize both shapes: name/arguments nested under `function`, or at the top level.\n const name = toolCall.function?.name ?? toolCall.name;\n const args = toolCall.function?.arguments ?? toolCall.arguments;\n\n // A tool call must carry at least a name or argument fragment to be meaningful.\n if (name == null && args == null) {\n continue;\n }\n\n const key = getToolCallKey(toolCall, name, accumulator);\n const existing = accumulator.calls.get(key);\n\n if (!existing) {\n accumulator.calls.set(key, {\n index: toolCall.index,\n id: toolCall.id,\n type: toolCall.type,\n function: {\n name,\n arguments: args ?? '',\n },\n });\n } else if (existing.function) {\n if (name && !existing.function.name) {\n existing.function.name = name;\n }\n if (args) {\n existing.function.arguments = `${existing.function.arguments ?? ''}${args}`;\n }\n }\n accumulator.lastKey = key;\n }\n}\n\n/**\n * Parse a single SSE line (`data: {...}`) and accumulate its data into the streaming state.\n *\n * Handles both the native Workers AI shape (top-level `response`/`tool_calls`) and the\n * OpenAI-compatible shape (`choices[].delta.content`/`choices[].delta.tool_calls`), because\n * the same `run()` call transparently yields either format depending on the model.\n */\nfunction processLine(\n line: string,\n state: StreamResponseState,\n recordOutputs: boolean,\n toolCallAccumulator: ToolCallAccumulator,\n): void {\n const trimmed = line.trim();\n if (!trimmed.startsWith('data:')) {\n return;\n }\n\n const data = trimmed.slice('data:'.length).trim();\n if (!data || data === '[DONE]') {\n return;\n }\n\n let parsed: WorkersAiStreamChunk;\n try {\n parsed = JSON.parse(data) as WorkersAiStreamChunk;\n } catch {\n return;\n }\n\n if (parsed.usage) {\n if (typeof parsed.usage.prompt_tokens === 'number') {\n state.promptTokens = parsed.usage.prompt_tokens;\n }\n if (typeof parsed.usage.completion_tokens === 'number') {\n state.completionTokens = parsed.usage.completion_tokens;\n }\n if (typeof parsed.usage.total_tokens === 'number') {\n state.totalTokens = parsed.usage.total_tokens;\n }\n }\n\n if (recordOutputs && typeof parsed.response === 'string') {\n state.responseTexts.push(parsed.response);\n }\n\n if (recordOutputs && Array.isArray(parsed.tool_calls) && parsed.tool_calls.length > 0) {\n state.toolCalls.push(...parsed.tool_calls);\n }\n\n if (Array.isArray(parsed.choices)) {\n if (typeof parsed.id === 'string') {\n state.responseId = parsed.id;\n }\n if (typeof parsed.model === 'string') {\n state.responseModel = parsed.model;\n }\n\n for (const choice of parsed.choices) {\n if (recordOutputs && typeof choice.delta?.content === 'string' && choice.delta.content) {\n state.responseTexts.push(choice.delta.content);\n }\n if (recordOutputs && Array.isArray(choice.delta?.tool_calls)) {\n accumulateStreamingToolCalls(choice.delta.tool_calls, toolCallAccumulator);\n }\n if (typeof choice.finish_reason === 'string') {\n state.finishReasons.push(choice.finish_reason);\n }\n }\n }\n}\n\n/**\n * Wrap a Workers AI streaming response (a server-sent-events `ReadableStream`) so we can\n * accumulate the response text and token usage while passing the original bytes through untouched.\n *\n * The span is ended once the consumer finishes reading (or cancels) the stream.\n */\nexport function instrumentWorkersAiStream(\n stream: ReadableStream<Uint8Array>,\n span: Span,\n recordOutputs: boolean,\n abortSignal?: AbortSignal,\n): ReadableStream<Uint8Array> {\n const reader = stream.getReader();\n const decoder = new TextDecoder();\n\n const state: StreamResponseState = {\n responseId: '',\n responseModel: '',\n finishReasons: [],\n responseTexts: [],\n toolCalls: [],\n promptTokens: undefined,\n completionTokens: undefined,\n totalTokens: undefined,\n };\n\n // OpenAI-compatible tool calls arrive fragmented across chunks and are keyed by index;\n // accumulate them here and flatten into `state.toolCalls` once the stream ends.\n const toolCallAccumulator: ToolCallAccumulator = { calls: new Map(), keyByIndex: new Map() };\n\n let buffer = '';\n let spanEnded = false;\n\n const finish = (): void => {\n if (spanEnded) {\n return;\n }\n spanEnded = true;\n\n if (recordOutputs) {\n const accumulatedToolCalls = [...toolCallAccumulator.calls.values()];\n if (accumulatedToolCalls.length > 0) {\n state.toolCalls.push(...accumulatedToolCalls);\n }\n\n // Set the authoritative `gen_ai.output.messages` alongside the deprecated response\n // attributes `endStreamSpan` writes, so tool calls survive Relay's lossy migration.\n setOutputMessagesAttribute(span, {\n responseText: state.responseTexts.join(''),\n toolCalls: state.toolCalls,\n finishReason: state.finishReasons[0],\n });\n }\n\n endStreamSpan(span, state, recordOutputs);\n };\n\n const flushBuffer = (isDone: boolean): void => {\n const lines = buffer.split('\\n');\n // Keep the last (potentially incomplete) line in the buffer unless the stream is done.\n buffer = isDone ? '' : (lines.pop() ?? '');\n for (const line of lines) {\n processLine(line, state, recordOutputs, toolCallAccumulator);\n }\n };\n\n return new ReadableStream<Uint8Array>({\n async pull(controller) {\n try {\n const { done, value } = await reader.read();\n\n if (done) {\n buffer += decoder.decode();\n flushBuffer(true);\n finish();\n controller.close();\n return;\n }\n\n buffer += decoder.decode(value, { stream: true });\n flushBuffer(false);\n controller.enqueue(value);\n } catch (error) {\n span.setStatus(getErrorStatus(abortSignal));\n finish();\n controller.error(error);\n }\n },\n async cancel(reason) {\n finish();\n await reader.cancel(reason);\n },\n });\n}\n"],"mappings":";;;;;;;;AA+CA,SAAS,6BAA6B,WAAyC,aAAwC;CACrH,KAAK,MAAM,YAAY,WAAW;EAEhC,MAAM,OAAO,SAAS,UAAU,QAAQ,SAAS;EACjD,MAAM,OAAO,SAAS,UAAU,aAAa,SAAS;EAGtD,IAAI,QAAQ,QAAQ,QAAQ,MAC1B;EAGF,MAAM,MAAM,eAAe,UAAU,MAAM,WAAW;EACtD,MAAM,WAAW,YAAY,MAAM,IAAI,GAAG;EAE1C,IAAI,CAAC,UACH,YAAY,MAAM,IAAI,KAAK;GACzB,OAAO,SAAS;GAChB,IAAI,SAAS;GACb,MAAM,SAAS;GACf,UAAU;IACR;IACA,WAAW,QAAQ;GACrB;EACF,CAAC;OACI,IAAI,SAAS,UAAU;GAC5B,IAAI,QAAQ,CAAC,SAAS,SAAS,MAC7B,SAAS,SAAS,OAAO;GAE3B,IAAI,MACF,SAAS,SAAS,YAAY,GAAG,SAAS,SAAS,aAAa,KAAK;EAEzE;EACA,YAAY,UAAU;CACxB;AACF;;;;;;;;AASA,SAAS,YACP,MACA,OACA,eACA,qBACM;CACN,MAAM,UAAU,KAAK,KAAK;CAC1B,IAAI,CAAC,QAAQ,WAAW,OAAO,GAC7B;CAGF,MAAM,OAAO,QAAQ,MAAM,CAAc,CAAC,CAAC,KAAK;CAChD,IAAI,CAAC,QAAQ,SAAS,UACpB;CAGF,IAAI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ations/dataloader.js";
33
33
  import { genericPoolIntegration } from "./integrations/generic-pool.js";
34
34
  import { cronJobIntegration } from "./integrations/cron.js";
35
- import { nodeCronIntegration } from "./integrations/node-cron.js";
35
+ import { isReadAlikeByNodeCron3, nodeCronIntegration } from "./integrations/node-cron.js";
36
36
  import { nodeScheduleIntegration } from "./integrations/node-schedule.js";
37
+ import { cronExpressionToMonitorConfig } from "./utils/cronMonitoring.js";
37
38
  import { googleGenAIIntegration } from "./integrations/google-genai.js";
38
39
  import { graphqlIntegration } from "./integrations/graphql/index.js";
39
40
  import { hapiIntegration } from "./integrations/hapi/index.js";
@@ -79,6 +80,6 @@ import { getErrorIntegrations, getTracingIntegrations } from "./integrations/ind
79
80
  * @deprecated This is a temporary export to avoid breaking changes. It will be removed in the next major version.
80
81
  */
81
82
  const attachHapiErrorHandler = attachHapiErrorHandler$1;
82
- export { SentryMastraExporter, instrumentTunnelServer as _INTERNAL_instrumentTunnelServer, instrumentTunnelServers as _INTERNAL_instrumentTunnelServers, amqplibIntegration, anthropicAIIntegration, applyHonoPatches, attachHapiErrorHandler, attachKoaErrorHandler, awsIntegration, bindTracingChannelToSpan, createFlueInstrumentation, createHonoRequestMiddleware, createLangChainCallbackHandler, cronJobIntegration, dataloaderIntegration, detectOrchestrionSetup, tracingChannel as diagnosticsTracingChannel, earlyPatchHono, eveConversationHook, eveIntegration, eveTracePolicy, expressErrorHandler, expressIntegration, fastifyIntegration, firebaseIntegration, flueIntegration, genericPoolIntegration, getErrorIntegrations, getInstrumentedModuleNames, getOtlpTracesEndpoint, getSqlQueryAttributes, getSqlQuerySummary, getSqlSpanName, getTracingIntegrations, googleGenAIIntegration, graphqlIntegration, groqIntegration, hapiIntegration, honoIntegration, honoMiddleware, instrumentAnthropicAiClient, instrumentCreateReactAgent, instrumentGoogleGenAIClient, instrumentLangChainEmbeddings, instrumentMistralAiClient, instrumentOpenAiClient, instrumentPostgresJsSql, instrumentStateGraph, instrumentStateGraphCompile, instrumentTypeSafeClient, instrumentWorkersAiClient, isBun, isCloudflareWorkers, isDeno, kafkaIntegration, knexIntegration, koaIntegration, langChainIntegration, langGraphIntegration, lruMemoizerIntegration, makeServeTunnelIntegration, mastraIntegration, mcpServerIntegration, mistralAIIntegration, mongoIntegration, mongooseIntegration, mysql2Integration, mysqlIntegration, neonIntegration, nitroIntegration, nodeCronIntegration, nodeScheduleIntegration, openAIIntegration, openTelemetryIntegration, orchestrionModuleInjected, piAiIntegration, piDurableIntegration, postgresIntegration, postgresJsIntegration, prismaIntegration, redisIntegration, sanitizeSqlQuery, setAsyncLocalStorageAsyncContextStrategy, setHttpServerSpanRouteAttribute, setupExpressErrorHandler, setupFastifyErrorHandler, subscribe as subscribeDiagnosticsChannel, tediousIntegration, togetherAIIntegration, typesafeIntegration, vercelAIIntegration };
83
+ export { SentryMastraExporter, cronExpressionToMonitorConfig as _INTERNAL_cronExpressionToMonitorConfig, instrumentTunnelServer as _INTERNAL_instrumentTunnelServer, instrumentTunnelServers as _INTERNAL_instrumentTunnelServers, isReadAlikeByNodeCron3 as _INTERNAL_isReadAlikeByNodeCron3, amqplibIntegration, anthropicAIIntegration, applyHonoPatches, attachHapiErrorHandler, attachKoaErrorHandler, awsIntegration, bindTracingChannelToSpan, createFlueInstrumentation, createHonoRequestMiddleware, createLangChainCallbackHandler, cronJobIntegration, dataloaderIntegration, detectOrchestrionSetup, tracingChannel as diagnosticsTracingChannel, earlyPatchHono, eveConversationHook, eveIntegration, eveTracePolicy, expressErrorHandler, expressIntegration, fastifyIntegration, firebaseIntegration, flueIntegration, genericPoolIntegration, getErrorIntegrations, getInstrumentedModuleNames, getOtlpTracesEndpoint, getSqlQueryAttributes, getSqlQuerySummary, getSqlSpanName, getTracingIntegrations, googleGenAIIntegration, graphqlIntegration, groqIntegration, hapiIntegration, honoIntegration, honoMiddleware, instrumentAnthropicAiClient, instrumentCreateReactAgent, instrumentGoogleGenAIClient, instrumentLangChainEmbeddings, instrumentMistralAiClient, instrumentOpenAiClient, instrumentPostgresJsSql, instrumentStateGraph, instrumentStateGraphCompile, instrumentTypeSafeClient, instrumentWorkersAiClient, isBun, isCloudflareWorkers, isDeno, kafkaIntegration, knexIntegration, koaIntegration, langChainIntegration, langGraphIntegration, lruMemoizerIntegration, makeServeTunnelIntegration, mastraIntegration, mcpServerIntegration, mistralAIIntegration, mongoIntegration, mongooseIntegration, mysql2Integration, mysqlIntegration, neonIntegration, nitroIntegration, nodeCronIntegration, nodeScheduleIntegration, openAIIntegration, openTelemetryIntegration, orchestrionModuleInjected, piAiIntegration, piDurableIntegration, postgresIntegration, postgresJsIntegration, prismaIntegration, redisIntegration, sanitizeSqlQuery, setAsyncLocalStorageAsyncContextStrategy, setHttpServerSpanRouteAttribute, setupExpressErrorHandler, setupFastifyErrorHandler, subscribe as subscribeDiagnosticsChannel, tediousIntegration, togetherAIIntegration, typesafeIntegration, vercelAIIntegration };
83
84
 
84
85
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["_attachHapiErrorHandler"],"sources":["../../src/index.ts"],"sourcesContent":["export * from './exports';\n\n// Exports using diagnostics channels\nexport { detectOrchestrionSetup } from './orchestrion/detect';\n// oxlint-disable-next-line typescript/no-deprecated -- re-exported so the deprecated `setupKoaErrorHandler` can delegate\nexport { attachKoaErrorHandler } from './integrations/koa/koa-error-handler';\nimport { attachHapiErrorHandler as _attachHapiErrorHandler } from './integrations/hapi/hapi-error-handler';\nexport { bindTracingChannelToSpan } from './tracing-channel';\nexport type { TracingChannelPayloadWithSpan } from './tracing-channel';\nexport type { InstrumentationConfig } from './orchestrion/apmTypes';\nexport type { OrchestrionChannelContext } from './orchestrion/types';\n// Runtime target of the bundler-injected module snippet. The snippet imports it\n// from this entry alongside the module's subscriber factory (see\n// `orchestrion/bundler/moduleInjectedTransform.ts`); it is a plain runtime\n// helper with no orchestrion build-time dependency.\nexport { orchestrionModuleInjected } from './utils/moduleInjected';\nexport {\n subscribe as subscribeDiagnosticsChannel,\n tracingChannel as diagnosticsTracingChannel,\n} from './utils/diagnosticsChannel';\nexport { eveConversationHook, eveIntegration, eveTracePolicy } from './eve';\nexport { getInstrumentedModuleNames } from './orchestrion/config';\nexport {\n fastifyIntegration,\n // oxlint-disable-next-line typescript/no-deprecated\n setupFastifyErrorHandler,\n} from './integrations/fastify';\n\n/**\n * @deprecated This is a temporary export to avoid breaking changes. It will be removed in the next major version.\n */\nexport const attachHapiErrorHandler = _attachHapiErrorHandler;\n\n// Integrations\nexport { prismaIntegration } from './integrations/prisma';\nexport { amqplibIntegration } from './integrations/amqplib';\nexport { anthropicAIIntegration } from './integrations/anthropic';\nexport { awsIntegration } from './integrations/aws-sdk';\nexport { dataloaderIntegration } from './integrations/dataloader';\nexport { genericPoolIntegration } from './integrations/generic-pool';\nexport { cronJobIntegration } from './integrations/cron';\nexport type { CronJobIntegrationOptions } from './integrations/cron';\nexport { nodeCronIntegration } from './integrations/node-cron';\nexport type { NodeCronIntegrationOptions } from './integrations/node-cron';\nexport { nodeScheduleIntegration } from './integrations/node-schedule';\nexport type { NodeScheduleIntegrationOptions } from './integrations/node-schedule';\nexport { googleGenAIIntegration } from './integrations/google-genai';\nexport { graphqlIntegration } from './integrations/graphql';\nexport { hapiIntegration } from './integrations/hapi';\nexport { honoIntegration, honoMiddleware } from './integrations/hono';\nexport type { HonoIntegrationOptions } from './integrations/hono';\nexport { koaIntegration } from './integrations/koa';\nexport { redisIntegration } from './integrations/redis';\nexport { kafkaIntegration } from './integrations/kafkajs';\nexport { knexIntegration } from './integrations/knex';\nexport { langChainIntegration } from './integrations/langchain';\nexport { langGraphIntegration } from './integrations/langgraph';\nexport { createFlueInstrumentation } from './ai/flue';\nexport { flueIntegration } from './integrations/flue';\nexport { piAiIntegration } from './integrations/pi-ai';\nexport { piDurableIntegration } from './integrations/pi-durable';\nexport type { FlueOptions } from './ai/flue';\nexport { mastraIntegration } from './integrations/mastra';\nexport { mcpServerIntegration } from './integrations/mcp-server';\nexport {\n instrumentTunnelServers as _INTERNAL_instrumentTunnelServers,\n makeServeTunnelIntegration,\n} from './integrations/serveTunnel';\nexport { instrumentTunnelServer as _INTERNAL_instrumentTunnelServer } from './utils/tunnelServer';\nexport { SentryMastraExporter } from './ai/mastra';\nexport { lruMemoizerIntegration } from './integrations/lru-memoizer';\nexport { mongoIntegration } from './integrations/mongodb';\nexport { mongooseIntegration } from './integrations/mongoose';\nexport { mistralAIIntegration } from './integrations/mistral';\nexport { groqIntegration } from './integrations/groq';\nexport { togetherAIIntegration } from './integrations/together-ai';\nexport { typesafeIntegration } from './integrations/typesafe';\nexport { mysqlIntegration } from './integrations/mysql';\nexport { mysql2Integration } from './integrations/mysql2';\nexport { openAIIntegration } from './integrations/openai';\nexport { postgresIntegration } from './integrations/pg';\nexport { postgresJsIntegration } from './integrations/postgresjs';\nexport { neonIntegration } from './integrations/neon';\nexport { tediousIntegration } from './integrations/tedious';\nexport { vercelAIIntegration } from './integrations/vercel-ai';\nexport { expressIntegration } from './integrations/express';\nexport type { ExpressIntegrationOptions } from './integrations/express/types';\n/* oxlint-disable typescript/no-deprecated -- deprecated Express error-handler exports, kept until the next major */\nexport { expressErrorHandler, setupExpressErrorHandler } from './integrations/express/error-handler';\n/* oxlint-enable typescript/no-deprecated */\nexport { firebaseIntegration } from './integrations/firebase';\nexport { nitroIntegration } from './integrations/nitro';\nexport type { NitroIntegrationOptions } from './integrations/nitro';\n\nexport { getTracingIntegrations, getErrorIntegrations } from './integrations';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,MAAa,yBAAyBA"}
1
+ {"version":3,"file":"index.js","names":["_attachHapiErrorHandler"],"sources":["../../src/index.ts"],"sourcesContent":["export * from './exports';\n\n// Exports using diagnostics channels\nexport { detectOrchestrionSetup } from './orchestrion/detect';\n// oxlint-disable-next-line typescript/no-deprecated -- re-exported so the deprecated `setupKoaErrorHandler` can delegate\nexport { attachKoaErrorHandler } from './integrations/koa/koa-error-handler';\nimport { attachHapiErrorHandler as _attachHapiErrorHandler } from './integrations/hapi/hapi-error-handler';\nexport { bindTracingChannelToSpan } from './tracing-channel';\nexport type { TracingChannelPayloadWithSpan } from './tracing-channel';\nexport type { InstrumentationConfig } from './orchestrion/apmTypes';\nexport type { OrchestrionChannelContext } from './orchestrion/types';\n// Runtime target of the bundler-injected module snippet. The snippet imports it\n// from this entry alongside the module's subscriber factory (see\n// `orchestrion/bundler/moduleInjectedTransform.ts`); it is a plain runtime\n// helper with no orchestrion build-time dependency.\nexport { orchestrionModuleInjected } from './utils/moduleInjected';\nexport {\n subscribe as subscribeDiagnosticsChannel,\n tracingChannel as diagnosticsTracingChannel,\n} from './utils/diagnosticsChannel';\nexport { eveConversationHook, eveIntegration, eveTracePolicy } from './eve';\nexport { getInstrumentedModuleNames } from './orchestrion/config';\nexport {\n fastifyIntegration,\n // oxlint-disable-next-line typescript/no-deprecated\n setupFastifyErrorHandler,\n} from './integrations/fastify';\n\n/**\n * @deprecated This is a temporary export to avoid breaking changes. It will be removed in the next major version.\n */\nexport const attachHapiErrorHandler = _attachHapiErrorHandler;\n\n// Integrations\nexport { prismaIntegration } from './integrations/prisma';\nexport { amqplibIntegration } from './integrations/amqplib';\nexport { anthropicAIIntegration } from './integrations/anthropic';\nexport { awsIntegration } from './integrations/aws-sdk';\nexport { dataloaderIntegration } from './integrations/dataloader';\nexport { genericPoolIntegration } from './integrations/generic-pool';\nexport { cronJobIntegration } from './integrations/cron';\nexport type { CronJobIntegrationOptions } from './integrations/cron';\nexport {\n isReadAlikeByNodeCron3 as _INTERNAL_isReadAlikeByNodeCron3,\n nodeCronIntegration,\n} from './integrations/node-cron';\nexport type { NodeCronIntegrationOptions } from './integrations/node-cron';\nexport { nodeScheduleIntegration } from './integrations/node-schedule';\nexport type { NodeScheduleIntegrationOptions } from './integrations/node-schedule';\nexport { cronExpressionToMonitorConfig as _INTERNAL_cronExpressionToMonitorConfig } from './utils/cronMonitoring';\nexport type { CronDialect as _INTERNAL_CronDialect } from './utils/cronMonitoring';\nexport { googleGenAIIntegration } from './integrations/google-genai';\nexport { graphqlIntegration } from './integrations/graphql';\nexport { hapiIntegration } from './integrations/hapi';\nexport { honoIntegration, honoMiddleware } from './integrations/hono';\nexport type { HonoIntegrationOptions } from './integrations/hono';\nexport { koaIntegration } from './integrations/koa';\nexport { redisIntegration } from './integrations/redis';\nexport { kafkaIntegration } from './integrations/kafkajs';\nexport { knexIntegration } from './integrations/knex';\nexport { langChainIntegration } from './integrations/langchain';\nexport { langGraphIntegration } from './integrations/langgraph';\nexport { createFlueInstrumentation } from './ai/flue';\nexport { flueIntegration } from './integrations/flue';\nexport { piAiIntegration } from './integrations/pi-ai';\nexport { piDurableIntegration } from './integrations/pi-durable';\nexport type { FlueOptions } from './ai/flue';\nexport { mastraIntegration } from './integrations/mastra';\nexport { mcpServerIntegration } from './integrations/mcp-server';\nexport {\n instrumentTunnelServers as _INTERNAL_instrumentTunnelServers,\n makeServeTunnelIntegration,\n} from './integrations/serveTunnel';\nexport { instrumentTunnelServer as _INTERNAL_instrumentTunnelServer } from './utils/tunnelServer';\nexport { SentryMastraExporter } from './ai/mastra';\nexport { lruMemoizerIntegration } from './integrations/lru-memoizer';\nexport { mongoIntegration } from './integrations/mongodb';\nexport { mongooseIntegration } from './integrations/mongoose';\nexport { mistralAIIntegration } from './integrations/mistral';\nexport { groqIntegration } from './integrations/groq';\nexport { togetherAIIntegration } from './integrations/together-ai';\nexport { typesafeIntegration } from './integrations/typesafe';\nexport { mysqlIntegration } from './integrations/mysql';\nexport { mysql2Integration } from './integrations/mysql2';\nexport { openAIIntegration } from './integrations/openai';\nexport { postgresIntegration } from './integrations/pg';\nexport { postgresJsIntegration } from './integrations/postgresjs';\nexport { neonIntegration } from './integrations/neon';\nexport { tediousIntegration } from './integrations/tedious';\nexport { vercelAIIntegration } from './integrations/vercel-ai';\nexport { expressIntegration } from './integrations/express';\nexport type { ExpressIntegrationOptions } from './integrations/express/types';\n/* oxlint-disable typescript/no-deprecated -- deprecated Express error-handler exports, kept until the next major */\nexport { expressErrorHandler, setupExpressErrorHandler } from './integrations/express/error-handler';\n/* oxlint-enable typescript/no-deprecated */\nexport { firebaseIntegration } from './integrations/firebase';\nexport { nitroIntegration } from './integrations/nitro';\nexport type { NitroIntegrationOptions } from './integrations/nitro';\n\nexport { getTracingIntegrations, getErrorIntegrations } from './integrations';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,MAAa,yBAAyBA"}
@@ -28,7 +28,7 @@ function onSetTime({ arguments: [cronTime], self }) {
28
28
  const job = self;
29
29
  if (!job || job.cronTime !== cronTime) return;
30
30
  const { source, timeZone, utcOffset } = cronTime;
31
- const monitorConfig = typeof source === "string" && utcOffset == null ? cronExpressionToMonitorConfig(source, timeZone, "or") : void 0;
31
+ const monitorConfig = typeof source === "string" && utcOffset == null ? cronExpressionToMonitorConfig(source, timeZone, "cron") : void 0;
32
32
  for (const callback of job._callbacks || []) updateMonitorConfig(callback, monitorConfig);
33
33
  }
34
34
  function wrapJob(args, options) {
@@ -36,7 +36,7 @@ function wrapJob(args, options) {
36
36
  const utcOffset = args[7];
37
37
  const name = args[11];
38
38
  if (typeof cronTime !== "string" || !shouldMonitorJob(name, onTick, options.excludeJobs)) return;
39
- const monitorConfig = utcOffset == null ? cronExpressionToMonitorConfig(cronTime, timeZone, "or") : void 0;
39
+ const monitorConfig = utcOffset == null ? cronExpressionToMonitorConfig(cronTime, timeZone, "cron") : void 0;
40
40
  args[1] = wrapScheduledJob(onTick, name, monitorConfig, "auto.function.cron");
41
41
  }
42
42
  export { cronJobIntegration, onSetTime };
@@ -1 +1 @@
1
- {"version":3,"file":"cron.js","names":[],"sources":["../../../src/integrations/cron.ts"],"sourcesContent":["import type { IntegrationFn, MonitorConfig } from '@sentry/core';\nimport { defineIntegration } from '@sentry/core';\nimport { CHANNELS } from '../orchestrion/channels';\nimport { cronModuleNames } from '../orchestrion/config/cron';\nimport { invokeOrchestrionInstrumentation } from '../orchestrion/instrumentation';\nimport type { AnyFn, ScheduleChange } from '../utils/cronMonitoring';\nimport {\n cronExpressionToMonitorConfig,\n shouldMonitorJob,\n subscribeToJobCreation,\n subscribeToScheduleChange,\n updateMonitorConfig,\n wrapScheduledJob,\n} from '../utils/cronMonitoring';\n\nconst INTEGRATION_NAME = 'CronJob' as const;\n\nexport interface CronJobIntegrationOptions {\n /** Job names not to monitor. Strings must match the name exactly. */\n excludeJobs?: Array<string | RegExp>;\n}\n\nconst _cronJobIntegration = ((options: CronJobIntegrationOptions = {}) => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n invokeOrchestrionInstrumentation(client, cronModuleNames, subscribe, [options], {\n requiresTracingChannelBinding: false,\n });\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Sends Crons check-ins for every `CronJob` of the `cron` package (4.3+) that has a `name`.\n * The monitor slug is the job name. Jobs without a name, one-off jobs, and jobs with a schedule Crons can't express\n * are not monitored.\n */\nexport const cronJobIntegration = defineIntegration(_cronJobIntegration);\n\nfunction subscribe(options: CronJobIntegrationOptions): void {\n subscribeToJobCreation(CHANNELS.CRON_JOB_CONSTRUCTOR, INTEGRATION_NAME, args => wrapJob(args, options));\n subscribeToScheduleChange(CHANNELS.CRON_JOB_SET_TIME, INTEGRATION_NAME, onSetTime);\n}\n\n/** Sets the new time's config after `job.setTime(cronTime)`. Without one, the job doesn't check in. */\nexport function onSetTime({ arguments: [cronTime], self }: ScheduleChange): void {\n const job = self as { cronTime?: unknown; _callbacks?: unknown[] } | undefined;\n // `setTime` throws and keeps the old time when it isn't given a `CronTime`.\n if (!job || job.cronTime !== cronTime) {\n return;\n }\n const { source, timeZone, utcOffset } = cronTime as { source?: unknown; timeZone?: unknown; utcOffset?: unknown };\n const monitorConfig: MonitorConfig | undefined =\n typeof source === 'string' && utcOffset == null ? cronExpressionToMonitorConfig(source, timeZone, 'or') : undefined;\n for (const callback of job._callbacks || []) {\n updateMonitorConfig(callback, monitorConfig);\n }\n}\n\n// `new CronJob(cronTime, onTick, onComplete, start, timeZone, context, runOnInit, utcOffset, ..., name)`\nfunction wrapJob(args: unknown[], options: CronJobIntegrationOptions): void {\n const [cronTime, onTick, , , timeZone] = args;\n const utcOffset = args[7];\n const name = args[11];\n if (typeof cronTime !== 'string' || !shouldMonitorJob(name, onTick, options.excludeJobs)) {\n return;\n }\n const monitorConfig = utcOffset == null ? cronExpressionToMonitorConfig(cronTime, timeZone, 'or') : undefined;\n args[1] = wrapScheduledJob(onTick as AnyFn, name, monitorConfig, 'auto.function.cron');\n}\n"],"mappings":";;;;;;AAeA,MAAM,mBAAmB;AAOzB,MAAM,wBAAwB,UAAqC,CAAC,MAAM;CACxE,OAAO;EACL,MAAM;EACN,MAAM,QAAQ;GACZ,iCAAiC,QAAQ,iBAAiB,WAAW,CAAC,OAAO,GAAG,EAC9E,+BAA+B,MACjC,CAAC;EACH;CACF;AACF;;;;;;AAOA,MAAa,qBAAqB,kBAAkB,mBAAmB;AAEvE,SAAS,UAAU,SAA0C;CAC3D,uBAAuB,SAAS,sBAAsB,mBAAkB,SAAQ,QAAQ,MAAM,OAAO,CAAC;CACtG,0BAA0B,SAAS,mBAAmB,kBAAkB,SAAS;AACnF;;AAGA,SAAgB,UAAU,EAAE,WAAW,CAAC,WAAW,QAA8B;CAC/E,MAAM,MAAM;CAEZ,IAAI,CAAC,OAAO,IAAI,aAAa,UAC3B;CAEF,MAAM,EAAE,QAAQ,UAAU,cAAc;CACxC,MAAM,gBACJ,OAAO,WAAW,YAAY,aAAa,OAAO,8BAA8B,QAAQ,UAAU,IAAI,IAAI,KAAA;CAC5G,KAAK,MAAM,YAAY,IAAI,cAAc,CAAC,GACxC,oBAAoB,UAAU,aAAa;AAE/C;AAGA,SAAS,QAAQ,MAAiB,SAA0C;CAC1E,MAAM,CAAC,UAAU,YAAY,YAAY;CACzC,MAAM,YAAY,KAAK;CACvB,MAAM,OAAO,KAAK;CAClB,IAAI,OAAO,aAAa,YAAY,CAAC,iBAAiB,MAAM,QAAQ,QAAQ,WAAW,GACrF;CAEF,MAAM,gBAAgB,aAAa,OAAO,8BAA8B,UAAU,UAAU,IAAI,IAAI,KAAA;CACpG,KAAK,KAAK,iBAAiB,QAAiB,MAAM,eAAe,oBAAoB;AACvF"}
1
+ {"version":3,"file":"cron.js","names":[],"sources":["../../../src/integrations/cron.ts"],"sourcesContent":["import type { IntegrationFn, MonitorConfig } from '@sentry/core';\nimport { defineIntegration } from '@sentry/core';\nimport { CHANNELS } from '../orchestrion/channels';\nimport { cronModuleNames } from '../orchestrion/config/cron';\nimport { invokeOrchestrionInstrumentation } from '../orchestrion/instrumentation';\nimport type { AnyFn, ScheduleChange } from '../utils/cronMonitoring';\nimport {\n cronExpressionToMonitorConfig,\n shouldMonitorJob,\n subscribeToJobCreation,\n subscribeToScheduleChange,\n updateMonitorConfig,\n wrapScheduledJob,\n} from '../utils/cronMonitoring';\n\nconst INTEGRATION_NAME = 'CronJob' as const;\n\nexport interface CronJobIntegrationOptions {\n /** Job names not to monitor. Strings must match the name exactly. */\n excludeJobs?: Array<string | RegExp>;\n}\n\nconst _cronJobIntegration = ((options: CronJobIntegrationOptions = {}) => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n invokeOrchestrionInstrumentation(client, cronModuleNames, subscribe, [options], {\n requiresTracingChannelBinding: false,\n });\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Sends Crons check-ins for every `CronJob` of the `cron` package (4.3+) that has a `name`.\n * The monitor slug is the job name. Jobs without a name, one-off jobs, and jobs with a schedule Crons can't express\n * are not monitored.\n */\nexport const cronJobIntegration = defineIntegration(_cronJobIntegration);\n\nfunction subscribe(options: CronJobIntegrationOptions): void {\n subscribeToJobCreation(CHANNELS.CRON_JOB_CONSTRUCTOR, INTEGRATION_NAME, args => wrapJob(args, options));\n subscribeToScheduleChange(CHANNELS.CRON_JOB_SET_TIME, INTEGRATION_NAME, onSetTime);\n}\n\n/** Sets the new time's config after `job.setTime(cronTime)`. Without one, the job doesn't check in. */\nexport function onSetTime({ arguments: [cronTime], self }: ScheduleChange): void {\n const job = self as { cronTime?: unknown; _callbacks?: unknown[] } | undefined;\n // `setTime` throws and keeps the old time when it isn't given a `CronTime`.\n if (!job || job.cronTime !== cronTime) {\n return;\n }\n const { source, timeZone, utcOffset } = cronTime as { source?: unknown; timeZone?: unknown; utcOffset?: unknown };\n const monitorConfig: MonitorConfig | undefined =\n typeof source === 'string' && utcOffset == null\n ? cronExpressionToMonitorConfig(source, timeZone, 'cron')\n : undefined;\n for (const callback of job._callbacks || []) {\n updateMonitorConfig(callback, monitorConfig);\n }\n}\n\n// `new CronJob(cronTime, onTick, onComplete, start, timeZone, context, runOnInit, utcOffset, ..., name)`\nfunction wrapJob(args: unknown[], options: CronJobIntegrationOptions): void {\n const [cronTime, onTick, , , timeZone] = args;\n const utcOffset = args[7];\n const name = args[11];\n if (typeof cronTime !== 'string' || !shouldMonitorJob(name, onTick, options.excludeJobs)) {\n return;\n }\n const monitorConfig = utcOffset == null ? cronExpressionToMonitorConfig(cronTime, timeZone, 'cron') : undefined;\n args[1] = wrapScheduledJob(onTick as AnyFn, name, monitorConfig, 'auto.function.cron');\n}\n"],"mappings":";;;;;;AAeA,MAAM,mBAAmB;AAOzB,MAAM,wBAAwB,UAAqC,CAAC,MAAM;CACxE,OAAO;EACL,MAAM;EACN,MAAM,QAAQ;GACZ,iCAAiC,QAAQ,iBAAiB,WAAW,CAAC,OAAO,GAAG,EAC9E,+BAA+B,MACjC,CAAC;EACH;CACF;AACF;;;;;;AAOA,MAAa,qBAAqB,kBAAkB,mBAAmB;AAEvE,SAAS,UAAU,SAA0C;CAC3D,uBAAuB,SAAS,sBAAsB,mBAAkB,SAAQ,QAAQ,MAAM,OAAO,CAAC;CACtG,0BAA0B,SAAS,mBAAmB,kBAAkB,SAAS;AACnF;;AAGA,SAAgB,UAAU,EAAE,WAAW,CAAC,WAAW,QAA8B;CAC/E,MAAM,MAAM;CAEZ,IAAI,CAAC,OAAO,IAAI,aAAa,UAC3B;CAEF,MAAM,EAAE,QAAQ,UAAU,cAAc;CACxC,MAAM,gBACJ,OAAO,WAAW,YAAY,aAAa,OACvC,8BAA8B,QAAQ,UAAU,MAAM,IACtD,KAAA;CACN,KAAK,MAAM,YAAY,IAAI,cAAc,CAAC,GACxC,oBAAoB,UAAU,aAAa;AAE/C;AAGA,SAAS,QAAQ,MAAiB,SAA0C;CAC1E,MAAM,CAAC,UAAU,YAAY,YAAY;CACzC,MAAM,YAAY,KAAK;CACvB,MAAM,OAAO,KAAK;CAClB,IAAI,OAAO,aAAa,YAAY,CAAC,iBAAiB,MAAM,QAAQ,QAAQ,WAAW,GACrF;CAEF,MAAM,gBAAgB,aAAa,OAAO,8BAA8B,UAAU,UAAU,MAAM,IAAI,KAAA;CACtG,KAAK,KAAK,iBAAiB,QAAiB,MAAM,eAAe,oBAAoB;AACvF"}
@@ -1,6 +1,6 @@
1
1
  import { tracingChannel } from "../utils/diagnosticsChannel.js";
2
2
  import { getGenAiSpanOp, markCancelledIfAborted, resolveAIRecordingOptions } from "../ai/core/utils.js";
3
- import { addPrivateRequestAttributes, addResponseAttributes, extractRequestAttributes, getAbortSignal, resolveChatParams } from "../ai/google-genai/index.js";
3
+ import { addPrivateRequestAttributes, addResponseAttributes, extractRequestAttributes, getAbortSignal, getCallAbortSignal, resolveChatParams } from "../ai/google-genai/index.js";
4
4
  import { shouldSkipAiProviderSpan } from "../ai/pi-ai/providers.js";
5
5
  import { instrumentStream } from "../ai/google-genai/streaming.js";
6
6
  import { CHANNELS } from "../orchestrion/channels.js";
@@ -24,6 +24,10 @@ const INSTRUMENTED_CHANNELS = [
24
24
  {
25
25
  channel: CHANNELS.GOOGLE_GENAI_CHAT,
26
26
  operation: "chat"
27
+ },
28
+ {
29
+ channel: CHANNELS.GOOGLE_GENAI_DECIDE,
30
+ operation: "decide"
27
31
  }
28
32
  ];
29
33
  const _googleGenAIIntegration = ((options = {}) => {
@@ -39,9 +43,9 @@ function instrumentGoogleGenai(options) {
39
43
  beforeSpanEnd: (span, data) => {
40
44
  if ("error" in data) {
41
45
  const params = resolveChatParams(operation, data.arguments?.[0], data.self);
42
- markCancelledIfAborted(span, getAbortSignal(params));
46
+ markCancelledIfAborted(span, getCallAbortSignal(operation, params, data.arguments?.[1]));
43
47
  }
44
- if (operation !== "embeddings") addResponseAttributes(span, data.result, resolveAIRecordingOptions(options).recordOutputs);
48
+ if (operation !== "embeddings") addResponseAttributes(span, data.result, resolveAIRecordingOptions(options).recordOutputs, operation);
45
49
  },
46
50
  deferSpanEnd: ({ span, data }) => wrapStreamResult(span, data, operation, options)
47
51
  });
@@ -95,9 +99,9 @@ function wrapStreamResult(span, data, operation, options) {
95
99
  /**
96
100
  * Diagnostics-channel-based Google GenAI integration. Subscribes to the
97
101
  * `orchestrion:@google/genai:*` diagnostics_channels injected into the SDK's `Models`
98
- * (`generateContent`/`generateContentStream`/`embedContent`) and `Chat`
99
- * (`sendMessage`/`sendMessageStream`) methods, so it requires the Sentry runtime hook or
100
- * bundler plugin.
102
+ * (`generateContent`/`generateContentStream`/`embedContent`), `Chat`
103
+ * (`sendMessage`/`sendMessageStream`) and decisions (`create`) methods, so it requires the Sentry
104
+ * runtime hook or bundler plugin.
101
105
  */
102
106
  const googleGenAIIntegration = defineIntegration(_googleGenAIIntegration);
103
107
  export { googleGenAIIntegration };
@@ -1 +1 @@
1
- {"version":3,"file":"google-genai.js","names":["diagnosticsChannel.tracingChannel"],"sources":["../../../src/integrations/google-genai.ts"],"sourcesContent":["import { GEN_AI_REQUEST_MODEL, SENTRY_OP, SENTRY_ORIGIN } from '@sentry/conventions/attributes';\nimport * as diagnosticsChannel from '../utils/diagnosticsChannel';\nimport type { IntegrationFn, Span } from '@sentry/core';\nimport {\n defineIntegration,\n getActiveSpan,\n getClient,\n hasSpanStreamingEnabled,\n spanToJSON,\n startInactiveSpan,\n} from '@sentry/core';\nimport { getGenAiSpanOp, markCancelledIfAborted, resolveAIRecordingOptions } from '../ai/core/utils';\nimport {\n addPrivateRequestAttributes,\n addResponseAttributes,\n extractRequestAttributes,\n getAbortSignal,\n resolveChatParams,\n} from '../ai/google-genai';\nimport { shouldSkipAiProviderSpan } from '../ai/pi-ai/providers';\nimport { instrumentStream } from '../ai/google-genai/streaming';\nimport type { GoogleGenAIOptions, GoogleGenAIResponse } from '../ai/google-genai/types';\nimport type { OrchestrionChannelContext } from '../orchestrion/types';\nimport { CHANNELS } from '../orchestrion/channels';\nimport { bindTracingChannelToSpan } from '../tracing-channel';\nimport { googleGenAiModuleNames } from '../orchestrion/config/google-genai';\nimport { invokeOrchestrionInstrumentation } from '../orchestrion/instrumentation';\n\n// Same name as the OTel integration by design, so the OTel 'Google_GenAI'\n// integration is deduplicated out of the default set.\nconst INTEGRATION_NAME = 'Google_GenAI' as const;\n\nconst ORIGIN = 'auto.ai.google_genai';\n\n// Each instrumented method maps to the gen_ai operation its span reports.\nconst INSTRUMENTED_CHANNELS = [\n { channel: CHANNELS.GOOGLE_GENAI_GENERATE_CONTENT, operation: 'generate_content' },\n { channel: CHANNELS.GOOGLE_GENAI_EMBED_CONTENT, operation: 'embeddings' },\n { channel: CHANNELS.GOOGLE_GENAI_CHAT, operation: 'chat' },\n] as const;\n\nconst _googleGenAIIntegration = ((options: GoogleGenAIOptions = {}) => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n invokeOrchestrionInstrumentation(client, googleGenAiModuleNames, instrumentGoogleGenai, [options]);\n },\n };\n}) satisfies IntegrationFn;\n\nfunction instrumentGoogleGenai(options: GoogleGenAIOptions): void {\n for (const { channel, operation } of INSTRUMENTED_CHANNELS) {\n bindTracingChannelToSpan(\n diagnosticsChannel.tracingChannel<OrchestrionChannelContext>(channel),\n data => createGenAiSpan(data, operation, options),\n {\n beforeSpanEnd: (span, data) => {\n if ('error' in data) {\n const params = resolveChatParams(\n operation,\n data.arguments?.[0] as Record<string, unknown> | undefined,\n data.self,\n );\n markCancelledIfAborted(span, getAbortSignal(params));\n }\n // Embeddings responses carry no content attributes.\n if (operation !== 'embeddings') {\n addResponseAttributes(\n span,\n data.result as GoogleGenAIResponse,\n resolveAIRecordingOptions(options).recordOutputs,\n );\n }\n },\n deferSpanEnd: ({ span, data }) => wrapStreamResult(span, data, operation, options),\n },\n );\n }\n}\n\n/**\n * Build the span for an instrumented call.\n * Returning `undefined` opts the payload out so no span is opened.\n */\nfunction createGenAiSpan(\n data: OrchestrionChannelContext,\n operation: string,\n options: GoogleGenAIOptions,\n): Span | undefined {\n if (shouldSkipAiProviderSpan(INTEGRATION_NAME)) {\n return undefined;\n }\n\n // `chat.sendMessage()`/`sendMessageStream()` internally call `Models.generateContent(Stream)`, which\n // publishes the `generate-content` channel while the chat span is active. Skip that nested event so a\n // chat call yields a single `gen_ai.chat` span instead of a chat span wrapping a generate_content one.\n if (operation !== 'chat') {\n const activeSpan = getActiveSpan();\n if (activeSpan) {\n const {\n attributes: { [SENTRY_OP]: op, [SENTRY_ORIGIN]: origin },\n } = spanToJSON(activeSpan);\n if (origin === ORIGIN && op === 'gen_ai.chat') {\n return undefined;\n }\n }\n }\n\n const args = data.arguments ?? [];\n // `chat.sendMessage()` carries no config of its own unless the caller passes one, so recover the\n // one `chats.create()` left on the chat instance that the transform stashed in `data.self`.\n const params = resolveChatParams(operation, args[0] as Record<string, unknown> | undefined, data.self);\n\n const { recordInputs } = resolveAIRecordingOptions(options);\n\n const attributes = extractRequestAttributes(operation, params, data.self, recordInputs);\n const model = (attributes[GEN_AI_REQUEST_MODEL] as string) || 'unknown';\n attributes[SENTRY_ORIGIN] = ORIGIN;\n const client = getClient();\n\n const span = startInactiveSpan({\n // With span streaming, omit the `'unknown'` model sentinel so the name stays low-cardinality.\n name: model !== 'unknown' || !(client && hasSpanStreamingEnabled(client)) ? `${operation} ${model}` : operation,\n op: getGenAiSpanOp(operation),\n attributes,\n });\n\n if (recordInputs && params) {\n addPrivateRequestAttributes(span, params, operation);\n }\n\n return span;\n}\n\ntype AsyncIterableStream = { [Symbol.asyncIterator]: () => AsyncIterator<unknown> };\n\nfunction isAsyncIterable(value: unknown): value is AsyncIterableStream {\n return !!value && typeof (value as AsyncIterableStream)[Symbol.asyncIterator] === 'function';\n}\n\n/**\n * Only the streaming methods (`generateContentStream`/`sendMessageStream`) resolve to an async iterable.\n * For a stream we patch `result[Symbol.asyncIterator]` in place so `instrumentStream` ends the\n * span when iteration finishes.\n */\nfunction wrapStreamResult(\n span: Span,\n data: OrchestrionChannelContext,\n operation: string,\n options: GoogleGenAIOptions,\n): boolean {\n const result = data.result;\n if (!isAsyncIterable(result)) {\n return false;\n }\n\n const { recordOutputs } = resolveAIRecordingOptions(options);\n const iterate = result[Symbol.asyncIterator].bind(result);\n const params = resolveChatParams(operation, data.arguments?.[0] as Record<string, unknown> | undefined, data.self);\n const instrumented = instrumentStream(\n { [Symbol.asyncIterator]: iterate },\n span,\n recordOutputs ?? false,\n getAbortSignal(params),\n );\n result[Symbol.asyncIterator] = () => instrumented;\n\n return true;\n}\n\n/**\n * Diagnostics-channel-based Google GenAI integration. Subscribes to the\n * `orchestrion:@google/genai:*` diagnostics_channels injected into the SDK's `Models`\n * (`generateContent`/`generateContentStream`/`embedContent`) and `Chat`\n * (`sendMessage`/`sendMessageStream`) methods, so it requires the Sentry runtime hook or\n * bundler plugin.\n */\nexport const googleGenAIIntegration = defineIntegration(_googleGenAIIntegration);\n"],"mappings":";;;;;;;;;;;;AA8BA,MAAM,mBAAmB;AAEzB,MAAM,SAAS;AAGf,MAAM,wBAAwB;CAC5B;EAAE,SAAS,SAAS;EAA+B,WAAW;CAAmB;CACjF;EAAE,SAAS,SAAS;EAA4B,WAAW;CAAa;CACxE;EAAE,SAAS,SAAS;EAAmB,WAAW;CAAO;AAC3D;AAEA,MAAM,4BAA4B,UAA8B,CAAC,MAAM;CACrE,OAAO;EACL,MAA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CAED,IAAI,gBAAgB,QAClB,4BAA4B,MAAM,QAAQ,SAAS;CAGrD,OAAO;AACT;AAIA,SAAS,gBAAgB,OAA8C;CACrE,OAAO,CAAC,CAAC,SAAS,OAAQ,MAA8B,OAAO,mBAAmB;AACpF;;;;;;AAOA,SAAS,iBACP,MACA,MACA,WACA,SACS;CACT,MAAM,SAAS,KAAK;CACpB,IAAI,CAAC,gBAAgB,MAAM,GACzB,OAAO;CAGT,MAAM,EAAE,kBAAkB,0BAA0B,OAAO;CAC3D,MAAM,UAAU,OAAO,OAAO,cAAc,CAAC,KAAK,MAAM;CACxD,MAAM,SAAS,kBAAkB,WAAW,KAAK,YAAY,IAA2C,KAAK,IAAI;CACjH,MAAM,eAAe,iBACnB,GAAG,OAAO,gBAAgB,QAAQ,GAClC,MACA,iBAAiB,OACjB,eAAe,MAAM,CACvB;CACA,OAAO,OAAO,uBAAuB;CAErC,OAAO;AACT;;;;;;;;AASA,MAAa,yBAAyB,kBAAkB,uBAAuB"}
1
+ {"version":3,"file":"google-genai.js","names":["diagnosticsChannel.tracingChannel"],"sources":["../../../src/integrations/google-genai.ts"],"sourcesContent":["import { GEN_AI_REQUEST_MODEL, SENTRY_OP, SENTRY_ORIGIN } from '@sentry/conventions/attributes';\nimport * as diagnosticsChannel from '../utils/diagnosticsChannel';\nimport type { IntegrationFn, Span } from '@sentry/core';\nimport {\n defineIntegration,\n getActiveSpan,\n getClient,\n hasSpanStreamingEnabled,\n spanToJSON,\n startInactiveSpan,\n} from '@sentry/core';\nimport { getGenAiSpanOp, markCancelledIfAborted, resolveAIRecordingOptions } from '../ai/core/utils';\nimport {\n addPrivateRequestAttributes,\n addResponseAttributes,\n extractRequestAttributes,\n getAbortSignal,\n getCallAbortSignal,\n resolveChatParams,\n} from '../ai/google-genai';\nimport { shouldSkipAiProviderSpan } from '../ai/pi-ai/providers';\nimport { instrumentStream } from '../ai/google-genai/streaming';\nimport type { GoogleGenAIOptions, GoogleGenAIResponse } from '../ai/google-genai/types';\nimport type { OrchestrionChannelContext } from '../orchestrion/types';\nimport { CHANNELS } from '../orchestrion/channels';\nimport { bindTracingChannelToSpan } from '../tracing-channel';\nimport { googleGenAiModuleNames } from '../orchestrion/config/google-genai';\nimport { invokeOrchestrionInstrumentation } from '../orchestrion/instrumentation';\n\n// Same name as the OTel integration by design, so the OTel 'Google_GenAI'\n// integration is deduplicated out of the default set.\nconst INTEGRATION_NAME = 'Google_GenAI' as const;\n\nconst ORIGIN = 'auto.ai.google_genai';\n\n// Each instrumented method maps to the gen_ai operation its span reports.\nconst INSTRUMENTED_CHANNELS = [\n { channel: CHANNELS.GOOGLE_GENAI_GENERATE_CONTENT, operation: 'generate_content' },\n { channel: CHANNELS.GOOGLE_GENAI_EMBED_CONTENT, operation: 'embeddings' },\n { channel: CHANNELS.GOOGLE_GENAI_CHAT, operation: 'chat' },\n { channel: CHANNELS.GOOGLE_GENAI_DECIDE, operation: 'decide' },\n] as const;\n\nconst _googleGenAIIntegration = ((options: GoogleGenAIOptions = {}) => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n invokeOrchestrionInstrumentation(client, googleGenAiModuleNames, instrumentGoogleGenai, [options]);\n },\n };\n}) satisfies IntegrationFn;\n\nfunction instrumentGoogleGenai(options: GoogleGenAIOptions): void {\n for (const { channel, operation } of INSTRUMENTED_CHANNELS) {\n bindTracingChannelToSpan(\n diagnosticsChannel.tracingChannel<OrchestrionChannelContext>(channel),\n data => createGenAiSpan(data, operation, options),\n {\n beforeSpanEnd: (span, data) => {\n if ('error' in data) {\n const params = resolveChatParams(\n operation,\n data.arguments?.[0] as Record<string, unknown> | undefined,\n data.self,\n );\n markCancelledIfAborted(span, getCallAbortSignal(operation, params, data.arguments?.[1]));\n }\n // Embeddings responses carry no content attributes.\n if (operation !== 'embeddings') {\n addResponseAttributes(\n span,\n data.result as GoogleGenAIResponse,\n resolveAIRecordingOptions(options).recordOutputs,\n operation,\n );\n }\n },\n deferSpanEnd: ({ span, data }) => wrapStreamResult(span, data, operation, options),\n },\n );\n }\n}\n\n/**\n * Build the span for an instrumented call.\n * Returning `undefined` opts the payload out so no span is opened.\n */\nfunction createGenAiSpan(\n data: OrchestrionChannelContext,\n operation: string,\n options: GoogleGenAIOptions,\n): Span | undefined {\n if (shouldSkipAiProviderSpan(INTEGRATION_NAME)) {\n return undefined;\n }\n\n // `chat.sendMessage()`/`sendMessageStream()` internally call `Models.generateContent(Stream)`, which\n // publishes the `generate-content` channel while the chat span is active. Skip that nested event so a\n // chat call yields a single `gen_ai.chat` span instead of a chat span wrapping a generate_content one.\n if (operation !== 'chat') {\n const activeSpan = getActiveSpan();\n if (activeSpan) {\n const {\n attributes: { [SENTRY_OP]: op, [SENTRY_ORIGIN]: origin },\n } = spanToJSON(activeSpan);\n if (origin === ORIGIN && op === 'gen_ai.chat') {\n return undefined;\n }\n }\n }\n\n const args = data.arguments ?? [];\n // `chat.sendMessage()` carries no config of its own unless the caller passes one, so recover the\n // one `chats.create()` left on the chat instance that the transform stashed in `data.self`.\n const params = resolveChatParams(operation, args[0] as Record<string, unknown> | undefined, data.self);\n\n const { recordInputs } = resolveAIRecordingOptions(options);\n\n const attributes = extractRequestAttributes(operation, params, data.self, recordInputs);\n const model = (attributes[GEN_AI_REQUEST_MODEL] as string) || 'unknown';\n attributes[SENTRY_ORIGIN] = ORIGIN;\n const client = getClient();\n\n const span = startInactiveSpan({\n // With span streaming, omit the `'unknown'` model sentinel so the name stays low-cardinality.\n name: model !== 'unknown' || !(client && hasSpanStreamingEnabled(client)) ? `${operation} ${model}` : operation,\n op: getGenAiSpanOp(operation),\n attributes,\n });\n\n if (recordInputs && params) {\n addPrivateRequestAttributes(span, params, operation);\n }\n\n return span;\n}\n\ntype AsyncIterableStream = { [Symbol.asyncIterator]: () => AsyncIterator<unknown> };\n\nfunction isAsyncIterable(value: unknown): value is AsyncIterableStream {\n return !!value && typeof (value as AsyncIterableStream)[Symbol.asyncIterator] === 'function';\n}\n\n/**\n * Only the streaming methods (`generateContentStream`/`sendMessageStream`) resolve to an async iterable.\n * For a stream we patch `result[Symbol.asyncIterator]` in place so `instrumentStream` ends the\n * span when iteration finishes.\n */\nfunction wrapStreamResult(\n span: Span,\n data: OrchestrionChannelContext,\n operation: string,\n options: GoogleGenAIOptions,\n): boolean {\n const result = data.result;\n if (!isAsyncIterable(result)) {\n return false;\n }\n\n const { recordOutputs } = resolveAIRecordingOptions(options);\n const iterate = result[Symbol.asyncIterator].bind(result);\n const params = resolveChatParams(operation, data.arguments?.[0] as Record<string, unknown> | undefined, data.self);\n const instrumented = instrumentStream(\n { [Symbol.asyncIterator]: iterate },\n span,\n recordOutputs ?? false,\n getAbortSignal(params),\n );\n result[Symbol.asyncIterator] = () => instrumented;\n\n return true;\n}\n\n/**\n * Diagnostics-channel-based Google GenAI integration. Subscribes to the\n * `orchestrion:@google/genai:*` diagnostics_channels injected into the SDK's `Models`\n * (`generateContent`/`generateContentStream`/`embedContent`), `Chat`\n * (`sendMessage`/`sendMessageStream`) and decisions (`create`) methods, so it requires the Sentry\n * runtime hook or bundler plugin.\n */\nexport const googleGenAIIntegration = defineIntegration(_googleGenAIIntegration);\n"],"mappings":";;;;;;;;;;;;AA+BA,MAAM,mBAAmB;AAEzB,MAAM,SAAS;AAGf,MAAM,wBAAwB;CAC5B;EAAE,SAAS,SAAS;EAA+B,WAAW;CAAmB;CACjF;EAAE,SAAS,SAAS;EAA4B,WAAW;CAAa;CACxE;EAAE,SAAS,SAAS;EAAmB,WAAW;CAAO;CACzD;EAAE,SAAS,SAAS;EAAqB,WAAW;CAAS;AAC/D;AAEA,MAAM,4BAA4B,UAA8B,CAAC,MAAM;CACrE,OAAO;EACL,MAAM;EACN,MAAM,QAAQ;GACZ,iCAAiC,QAAQ,wBAAwB,uBAAuB,CAAC,OAAO,CAAC;EACnG;CACF;AACF;AAEA,SAAS,sBAAsB,SAAmC;CAChE,KAAK,MAAM,EAAE,SAAS,eAAe,uBACnC,yBACEA,eAA6D,OAAO,IACpE,SAAQ,g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;;;AAOA,SAAS,iBACP,MACA,MACA,WACA,SACS;CACT,MAAM,SAAS,KAAK;CACpB,IAAI,CAAC,gBAAgB,MAAM,GACzB,OAAO;CAGT,MAAM,EAAE,kBAAkB,0BAA0B,OAAO;CAC3D,MAAM,UAAU,OAAO,OAAO,cAAc,CAAC,KAAK,MAAM;CACxD,MAAM,SAAS,kBAAkB,WAAW,KAAK,YAAY,IAA2C,KAAK,IAAI;CACjH,MAAM,eAAe,iBACnB,GAAG,OAAO,gBAAgB,QAAQ,GAClC,MACA,iBAAiB,OACjB,eAAe,MAAM,CACvB;CACA,OAAO,OAAO,uBAAuB;CAErC,OAAO;AACT;;;;;;;;AASA,MAAa,yBAAyB,kBAAkB,uBAAuB"}
@@ -1,9 +1,9 @@
1
1
  import { tracingChannel } from "../utils/diagnosticsChannel.js";
2
- import { getGenAiSpanOp, resolveAIRecordingOptions } from "../ai/core/utils.js";
2
+ import { getGenAiSpanOp, markCancelledIfAborted, resolveAIRecordingOptions } from "../ai/core/utils.js";
3
3
  import { addRequestAttributes, extractRequestAttributes } from "../ai/mistral/index.js";
4
4
  import { MISTRAL_INTEGRATION_NAME, MISTRAL_ORIGIN } from "../ai/mistral/constants.js";
5
5
  import { instrumentEventStream } from "../ai/mistral/streaming.js";
6
- import { addResponseAttributes, getSpanName } from "../ai/mistral/utils.js";
6
+ import { addResponseAttributes, getMistralRequestSignal, getSpanName } from "../ai/mistral/utils.js";
7
7
  import { shouldSkipAiProviderSpan } from "../ai/pi-ai/providers.js";
8
8
  import { CHANNELS } from "../orchestrion/channels.js";
9
9
  import { mistralModuleNames } from "../orchestrion/config/mistral.js";
@@ -51,9 +51,10 @@ const _mistralAIIntegration = ((options = {}) => {
51
51
  function instrumentMistral(options) {
52
52
  for (const { channel, operation, streaming } of INSTRUMENTED_CHANNELS) bindTracingChannelToSpan(tracingChannel(channel), (data) => createGenAiSpan(data, operation, streaming, options), {
53
53
  beforeSpanEnd: (span, data) => {
54
+ if ("error" in data) markCancelledIfAborted(span, getMistralRequestSignal(data.arguments?.[1]));
54
55
  addResponseAttributes(span, data.result, resolveAIRecordingOptions(options).recordOutputs);
55
56
  },
56
- deferSpanEnd: ({ span, data }) => streaming && instrumentEventStream(data.result, span, resolveAIRecordingOptions(options).recordOutputs)
57
+ deferSpanEnd: ({ span, data }) => streaming && instrumentEventStream(data.result, span, resolveAIRecordingOptions(options).recordOutputs, getMistralRequestSignal(data.arguments?.[1]))
57
58
  });
58
59
  }
59
60
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"mistral.js","names":["diagnosticsChannel.tracingChannel"],"sources":["../../../src/integrations/mistral.ts"],"sourcesContent":["import { SENTRY_ORIGIN } from '@sentry/conventions/attributes';\nimport * as diagnosticsChannel from '../utils/diagnosticsChannel';\nimport type { IntegrationFn, Span, SpanAttributeValue } from '@sentry/core';\nimport { defineIntegration, startInactiveSpan } from '@sentry/core';\nimport { getGenAiSpanOp, resolveAIRecordingOptions } from '../ai/core/utils';\nimport { addRequestAttributes, extractRequestAttributes } from '../ai/mistral';\nimport { MISTRAL_INTEGRATION_NAME, MISTRAL_ORIGIN } from '../ai/mistral/constants';\nimport { instrumentEventStream } from '../ai/mistral/streaming';\nimport type { MistralOptions } from '../ai/mistral/types';\nimport { addResponseAttributes, getSpanName } from '../ai/mistral/utils';\nimport { shouldSkipAiProviderSpan } from '../ai/pi-ai/providers';\nimport type { OrchestrionChannelContext } from '../orchestrion/types';\nimport { CHANNELS } from '../orchestrion/channels';\nimport { mistralModuleNames } from '../orchestrion/config/mistral';\nimport { invokeOrchestrionInstrumentation } from '../orchestrion/instrumentation';\nimport { bindTracingChannelToSpan } from '../tracing-channel';\n\nconst INTEGRATION_NAME = MISTRAL_INTEGRATION_NAME;\n\n// Each instrumented channel maps to the gen_ai operation its span reports. Streaming methods publish\n// on their own channel, so the span knows it is a stream before the result exists.\nconst INSTRUMENTED_CHANNELS = [\n { channel: CHANNELS.MISTRAL_CHAT, operation: 'chat', streaming: false },\n { channel: CHANNELS.MISTRAL_CHAT_STREAM, operation: 'chat', streaming: true },\n { channel: CHANNELS.MISTRAL_EMBEDDINGS, operation: 'embeddings', streaming: false },\n { channel: CHANNELS.MISTRAL_AGENTS, operation: 'invoke_agent', streaming: false },\n { channel: CHANNELS.MISTRAL_AGENTS_STREAM, operation: 'invoke_agent', streaming: true },\n] as const;\n\nconst _mistralAIIntegration = ((options: MistralOptions = {}) => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n invokeOrchestrionInstrumentation(client, mistralModuleNames, instrumentMistral, [options]);\n },\n };\n}) satisfies IntegrationFn;\n\nfunction instrumentMistral(options: MistralOptions): void {\n for (const { channel, operation, streaming } of INSTRUMENTED_CHANNELS) {\n bindTracingChannelToSpan(\n diagnosticsChannel.tracingChannel<OrchestrionChannelContext>(channel),\n data => createGenAiSpan(data, operation, streaming, options),\n {\n beforeSpanEnd: (span, data) => {\n addResponseAttributes(span, data.result, resolveAIRecordingOptions(options).recordOutputs);\n },\n // Streaming: the result is an `EventStream` consumed later, so instrument it and let it end the span.\n deferSpanEnd: ({ span, data }) =>\n streaming && instrumentEventStream(data.result, span, resolveAIRecordingOptions(options).recordOutputs),\n },\n );\n }\n}\n\n/**\n * Build the span for an instrumented Mistral call.\n * Returning `undefined` opts the payload out so no span is opened.\n */\nfunction createGenAiSpan(\n data: OrchestrionChannelContext,\n operation: string,\n streaming: boolean,\n options: MistralOptions,\n): Span | undefined {\n if (shouldSkipAiProviderSpan(INTEGRATION_NAME)) {\n return undefined;\n }\n\n const args = data.arguments ?? [];\n const params = args[0] as Record<string, unknown> | undefined;\n\n const { recordInputs } = resolveAIRecordingOptions(options);\n\n const attributes = extractRequestAttributes(args, operation, recordInputs, streaming);\n attributes[SENTRY_ORIGIN] = MISTRAL_ORIGIN;\n\n const span = startInactiveSpan({\n name: getSpanName(operation, attributes),\n op: getGenAiSpanOp(operation),\n attributes: attributes as Record<string, SpanAttributeValue>,\n });\n\n if (recordInputs && params) {\n addRequestAttributes(span, params, operation);\n }\n\n return span;\n}\n\n/**\n * An integration to instrument @mistralai/mistrailai.\n */\nexport const mistralAIIntegration = defineIntegration(_mistralAIIntegration);\n"],"mappings":";;;;;;;;;;;;;;AAiBA,MAAM,mBAAmB;AAIzB,MAAM,wBAAwB;CAC5B;EAAE,SAAS,SAAS;EAAc,WAAW;EAAQ,WAAW;CAAM;CACtE;EAAE,SAAS,SAAS;EAAqB,WAAW;EAAQ,WAAW;CAAK;CAC5E;EAAE,SAAS,SAAS;EAAoB,WAAW;EAAc,WAAW;CAAM;CAClF;EAAE,SAAS,SAAS;EAAgB,WAAW;EAAgB,WAAW;CAAM;CAChF;EAAE,SAAS,SAAS;EAAuB,WAAW;EAAgB,WAAW;CAAK;AACxF;AAEA,MAAM,0BAA0B,UAA0B,CAAC,MAAM;CAC/D,OAAO;EACL,MAAM;EACN,MAAM,QAAQ;GACZ,iCAAiC,QAAQ,oBAAoB,mBAAmB,CAAC,OAAO,CAAC;EAC3F;CACF;AACF;AAEA,SAAS,kBAAkB,SAA+B;CACxD,KAAK,MAAM,EAAE,SAAS,WAAW,eAAe,uBAC9C,yBACEA,eAA6D,OAAO,IACpE,SAAQ,gBAAgB,MAAM,WAAW,WAAW,OAAO,GAC3D;EACE,gBAAgB,MAAM,SAAS;GAC7B,sBAAsB,MAAM,KAAK,QAAQ,0BAA0B,OAAO,CAAC,CAAC,aAAa;EAC3F;EAEA,eAAe,EAAE,MAAM,WACrB,aAAa,sBAAsB,KAAK,QAAQ,MAAM,0BAA0B,OAAO,CAAC,CAAC,aAAa;CAC1G,CACF;AAEJ;;;;;AAMA,SAAS,gBACP,MACA,WACA,WACA,SACkB;CAClB,IAAI,yBAAyB,gBAAgB,GAC3C;CAGF,MAAM,OAAO,KAAK,aAAa,CAAC;CAChC,MAAM,SAAS,KAAK;CAEpB,MAAM,EAAE,iBAAiB,0BAA0B,OAAO;CAE1D,MAAM,aAAa,yBAAyB,MAAM,WAAW,cAAc,SAAS;CACpF,WAAW,iBAAiB;CAE5B,MAAM,OAAO,kBAAkB;EAC7B,MAAM,YAAY,WAAW,UAAU;EACvC,IAAI,eAAe,SAAS;EAChB;CACd,CAAC;CAED,IAAI,gBAAgB,QAClB,qBAAqB,MAAM,QAAQ,SAAS;CAG9C,OAAO;AACT;;;;AAKA,MAAa,uBAAuB,kBAAkB,qBAAqB"}
1
+ {"version":3,"file":"mistral.js","names":["diagnosticsChannel.tracingChannel"],"sources":["../../../src/integrations/mistral.ts"],"sourcesContent":["import { SENTRY_ORIGIN } from '@sentry/conventions/attributes';\nimport * as diagnosticsChannel from '../utils/diagnosticsChannel';\nimport type { IntegrationFn, Span, SpanAttributeValue } from '@sentry/core';\nimport { defineIntegration, startInactiveSpan } from '@sentry/core';\nimport { getGenAiSpanOp, markCancelledIfAborted, resolveAIRecordingOptions } from '../ai/core/utils';\nimport { addRequestAttributes, extractRequestAttributes } from '../ai/mistral';\nimport { MISTRAL_INTEGRATION_NAME, MISTRAL_ORIGIN } from '../ai/mistral/constants';\nimport { instrumentEventStream } from '../ai/mistral/streaming';\nimport type { MistralOptions } from '../ai/mistral/types';\nimport { addResponseAttributes, getMistralRequestSignal, getSpanName } from '../ai/mistral/utils';\nimport { shouldSkipAiProviderSpan } from '../ai/pi-ai/providers';\nimport type { OrchestrionChannelContext } from '../orchestrion/types';\nimport { CHANNELS } from '../orchestrion/channels';\nimport { mistralModuleNames } from '../orchestrion/config/mistral';\nimport { invokeOrchestrionInstrumentation } from '../orchestrion/instrumentation';\nimport { bindTracingChannelToSpan } from '../tracing-channel';\n\nconst INTEGRATION_NAME = MISTRAL_INTEGRATION_NAME;\n\n// Each instrumented channel maps to the gen_ai operation its span reports. Streaming methods publish\n// on their own channel, so the span knows it is a stream before the result exists.\nconst INSTRUMENTED_CHANNELS = [\n { channel: CHANNELS.MISTRAL_CHAT, operation: 'chat', streaming: false },\n { channel: CHANNELS.MISTRAL_CHAT_STREAM, operation: 'chat', streaming: true },\n { channel: CHANNELS.MISTRAL_EMBEDDINGS, operation: 'embeddings', streaming: false },\n { channel: CHANNELS.MISTRAL_AGENTS, operation: 'invoke_agent', streaming: false },\n { channel: CHANNELS.MISTRAL_AGENTS_STREAM, operation: 'invoke_agent', streaming: true },\n] as const;\n\nconst _mistralAIIntegration = ((options: MistralOptions = {}) => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n invokeOrchestrionInstrumentation(client, mistralModuleNames, instrumentMistral, [options]);\n },\n };\n}) satisfies IntegrationFn;\n\nfunction instrumentMistral(options: MistralOptions): void {\n for (const { channel, operation, streaming } of INSTRUMENTED_CHANNELS) {\n bindTracingChannelToSpan(\n diagnosticsChannel.tracingChannel<OrchestrionChannelContext>(channel),\n data => createGenAiSpan(data, operation, streaming, options),\n {\n beforeSpanEnd: (span, data) => {\n if ('error' in data) {\n markCancelledIfAborted(span, getMistralRequestSignal(data.arguments?.[1]));\n }\n addResponseAttributes(span, data.result, resolveAIRecordingOptions(options).recordOutputs);\n },\n // Streaming: the result is an `EventStream` consumed later, so instrument it and let it end the span.\n deferSpanEnd: ({ span, data }) =>\n streaming &&\n instrumentEventStream(\n data.result,\n span,\n resolveAIRecordingOptions(options).recordOutputs,\n getMistralRequestSignal(data.arguments?.[1]),\n ),\n },\n );\n }\n}\n\n/**\n * Build the span for an instrumented Mistral call.\n * Returning `undefined` opts the payload out so no span is opened.\n */\nfunction createGenAiSpan(\n data: OrchestrionChannelContext,\n operation: string,\n streaming: boolean,\n options: MistralOptions,\n): Span | undefined {\n if (shouldSkipAiProviderSpan(INTEGRATION_NAME)) {\n return undefined;\n }\n\n const args = data.arguments ?? [];\n const params = args[0] as Record<string, unknown> | undefined;\n\n const { recordInputs } = resolveAIRecordingOptions(options);\n\n const attributes = extractRequestAttributes(args, operation, recordInputs, streaming);\n attributes[SENTRY_ORIGIN] = MISTRAL_ORIGIN;\n\n const span = startInactiveSpan({\n name: getSpanName(operation, attributes),\n op: getGenAiSpanOp(operation),\n attributes: attributes as Record<string, SpanAttributeValue>,\n });\n\n if (recordInputs && params) {\n addRequestAttributes(span, params, operation);\n }\n\n return span;\n}\n\n/**\n * An integration to instrument @mistralai/mistrailai.\n */\nexport const mistralAIIntegration = defineIntegration(_mistralAIIntegration);\n"],"mappings":";;;;;;;;;;;;;;AAiBA,MAAM,mBAAmB;AAIzB,MAAM,wBAAwB;CAC5B;EAAE,SAAS,SAAS;EAAc,WAAW;EAAQ,WAAW;CAAM;CACtE;EAAE,SAAS,SAAS;EAAqB,WAAW;EAAQ,WAAW;CAAK;CAC5E;EAAE,SAAS,SAAS;EAAoB,WAAW;EAAc,WAAW;CAAM;CAClF;EAAE,SAAS,SAAS;EAAgB,WAAW;EAAgB,WAAW;CAAM;CAChF;EAAE,SAAS,SAAS;EAAuB,WAAW;EAAgB,WAAW;CAAK;AACxF;AAEA,MAAM,0BAA0B,UAA0B,CAAC,MAAM;CAC/D,OAAO;EACL,MAAM;EACN,MAAM,QAAQ;GACZ,iCAAiC,QAAQ,oBAAoB,mBAAmB,CAAC,OAAO,CAAC;EAC3F;CACF;AACF;AAEA,SAAS,kBAAkB,SAA+B;CACxD,KAAK,MAAM,EAAE,SAAS,WAAW,eAAe,uBAC9C,yBACEA,eAA6D,OAAO,IACpE,SAAQ,gBAAgB,MAAM,WAAW,WAAW,OAAO,GAC3D;EACE,gBAAgB,MAAM,SAAS;GAC7B,IAAI,WAAW,MACb,uBAAuB,MAAM,wBAAwB,KAAK,YAAY,EAAE,CAAC;GAE3E,sBAAsB,MAAM,KAAK,QAAQ,0BAA0B,OAAO,CAAC,CAAC,aAAa;EAC3F;EAEA,eAAe,EAAE,MAAM,WACrB,aACA,sBACE,KAAK,QACL,MACA,0BAA0B,OAAO,CAAC,CAAC,eACnC,wBAAwB,KAAK,YAAY,EAAE,CAC7C;CACJ,CACF;AAEJ;;;;;AAMA,SAAS,gBACP,MACA,WACA,WACA,SACkB;CAClB,IAAI,yBAAyB,gBAAgB,GAC3C;CAGF,MAAM,OAAO,KAAK,aAAa,CAAC;CAChC,MAAM,SAAS,KAAK;CAEpB,MAAM,EAAE,iBAAiB,0BAA0B,OAAO;CAE1D,MAAM,aAAa,yBAAyB,MAAM,WAAW,cAAc,SAAS;CACpF,WAAW,iBAAiB;CAE5B,MAAM,OAAO,kBAAkB;EAC7B,MAAM,YAAY,WAAW,UAAU;EACvC,IAAI,eAAe,SAAS;EAChB;CACd,CAAC;CAED,IAAI,gBAAgB,QAClB,qBAAqB,MAAM,QAAQ,SAAS;CAG9C,OAAO;AACT;;;;AAKA,MAAa,uBAAuB,kBAAkB,qBAAqB"}
@@ -33,7 +33,7 @@ function wrapTask(args, options, isReadAlike) {
33
33
  }
34
34
  /** The monitor config for a task, or `undefined` if `isReadAlike` says this node-cron version reads it differently. */
35
35
  function getMonitorConfig(expression, timezone, isReadAlike) {
36
- return isReadAlike && !isReadAlike(expression) ? void 0 : cronExpressionToMonitorConfig(expression, timezone, "and");
36
+ return isReadAlike && !isReadAlike(expression) ? void 0 : cronExpressionToMonitorConfig(expression, timezone, "node-cron");
37
37
  }
38
38
  const NODE_CRON_3_FIELD_MINIMUMS = [
39
39
  0,
@@ -44,11 +44,12 @@ const NODE_CRON_3_FIELD_MINIMUMS = [
44
44
  ];
45
45
  /**
46
46
  * node-cron before 4.6 reads `7` as `0` and swaps reversed ranges, so it runs `sat-sun`, `6-0` and `6-7` every day.
47
- * Returns `false` for weekday ranges that could hit that.
47
+ * It also reads a step without a range, like `5/10`, as its start. Returns `false` where that could differ.
48
48
  */
49
49
  function isReadAlikeByNodeCron4(expression) {
50
- const weekday = expression.trim().split(/\s+/).pop() || "";
51
- return !(weekday.includes("-") && (weekday.includes("7") || /-(?:0|sun)/i.test(weekday)));
50
+ const fields = expression.trim().split(/\s+/);
51
+ const weekday = fields[fields.length - 1] || "";
52
+ return !(weekday.includes("-") && (weekday.includes("7") || /-(?:0|sun)/i.test(weekday))) && !fields.some((field) => field.split(",").some((part) => /^[a-z\d]+\//i.test(part)));
52
53
  }
53
54
  /**
54
55
  * node-cron 3 keeps the values of a stepped field that are multiples of the step (`*\/2` days are 2, 4, ...)
@@ -1 +1 @@
1
- {"version":3,"file":"node-cron.js","names":[],"sources":["../../../src/integrations/node-cron.ts"],"sourcesContent":["import type { IntegrationFn, MonitorConfig } from '@sentry/core';\nimport { defineIntegration } from '@sentry/core';\nimport { CHANNELS } from '../orchestrion/channels';\nimport { nodeCronModuleNames } from '../orchestrion/config/node-cron';\nimport { invokeOrchestrionInstrumentation } from '../orchestrion/instrumentation';\nimport type { AnyFn } from '../utils/cronMonitoring';\nimport {\n cronExpressionToMonitorConfig,\n shouldMonitorJob,\n subscribeToJobCreation,\n wrapScheduledJob,\n} from '../utils/cronMonitoring';\n\nconst INTEGRATION_NAME = 'NodeCron' as const;\n\nexport interface NodeCronIntegrationOptions {\n /** Task names not to monitor. Strings must match the name exactly. */\n excludeJobs?: Array<string | RegExp>;\n}\n\nconst _nodeCronIntegration = ((options: NodeCronIntegrationOptions = {}) => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n invokeOrchestrionInstrumentation(client, nodeCronModuleNames, subscribe, [options], {\n // The binding only parents spans, and this integration creates none.\n requiresTracingChannelBinding: false,\n });\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Sends Crons check-ins for every named `node-cron` task, with its schedule as the monitor config.\n * The monitor slug is the task's `name` option. Tasks without a name, or with a schedule Sentry can't express, are not\n * monitored.\n */\nexport const nodeCronIntegration = defineIntegration(_nodeCronIntegration);\n\nfunction subscribe(options: NodeCronIntegrationOptions): void {\n subscribeToJobCreation(CHANNELS.NODE_CRON_CREATE_TASK, INTEGRATION_NAME, args => wrapTask(args, options));\n subscribeToJobCreation(CHANNELS.NODE_CRON_V4_CREATE_TASK, INTEGRATION_NAME, args =>\n wrapTask(args, options, isReadAlikeByNodeCron4),\n );\n subscribeToJobCreation(CHANNELS.NODE_CRON_V3_CREATE_TASK, INTEGRATION_NAME, args =>\n wrapTask(args, options, isReadAlikeByNodeCron3),\n );\n}\n\n// `createTask(expression, func, options)`\nfunction wrapTask(\n args: unknown[],\n options: NodeCronIntegrationOptions,\n isReadAlike?: (expression: string) => boolean,\n): void {\n const [expression, func, taskOptions] = args;\n const { name, timezone } = (taskOptions || {}) as { name?: unknown; timezone?: unknown };\n if (!shouldMonitorJob(name, func, options.excludeJobs)) {\n return;\n }\n const monitorConfig = getMonitorConfig(String(expression), timezone, isReadAlike);\n args[1] = wrapScheduledJob(func as AnyFn, name, monitorConfig, 'auto.function.node-cron');\n}\n\n/** The monitor config for a task, or `undefined` if `isReadAlike` says this node-cron version reads it differently. */\nexport function getMonitorConfig(\n expression: string,\n timezone: unknown,\n isReadAlike?: (expression: string) => boolean,\n): MonitorConfig | undefined {\n return isReadAlike && !isReadAlike(expression)\n ? undefined\n : cronExpressionToMonitorConfig(expression, timezone, 'and');\n}\n\nconst NODE_CRON_3_FIELD_MINIMUMS = [0, 0, 1, 1, 0];\n\n/**\n * node-cron before 4.6 reads `7` as `0` and swaps reversed ranges, so it runs `sat-sun`, `6-0` and `6-7` every day.\n * Returns `false` for weekday ranges that could hit that.\n */\nexport function isReadAlikeByNodeCron4(expression: string): boolean {\n const weekday = expression.trim().split(/\\s+/).pop() || '';\n return !(weekday.includes('-') && (weekday.includes('7') || /-(?:0|sun)/i.test(weekday)));\n}\n\n/**\n * node-cron 3 keeps the values of a stepped field that are multiples of the step (`*\\/2` days are 2, 4, ...)\n * and reads weekday ranges like node-cron 4 before 4.6. Returns `false` where that differs from standard cron.\n */\nexport function isReadAlikeByNodeCron3(expression: string): boolean {\n const fields = expression.trim().split(/\\s+/);\n const minimums = fields.length === 6 ? [0, ...NODE_CRON_3_FIELD_MINIMUMS] : NODE_CRON_3_FIELD_MINIMUMS;\n return (\n isReadAlikeByNodeCron4(expression) &&\n fields.every((field, index) => {\n if (!field.includes('/')) {\n return true;\n }\n const match = /^(?:\\*|(\\d+)-\\d+)\\/(\\d+)$/.exec(field);\n return !!match && Number(match[1] ?? minimums[index]) % Number(match[2]) === 0;\n })\n );\n}\n"],"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,WAAW,KAAK,CAAC,CAAC,MAAM,KAAK;CAC5C,MAAM,WAAW,OAAO,WAAW,IAAI,CAAC,GAAG,GAAG,0BAA0B,IAAI;CAC5E,OACE,uBAAuB,UAAU,KACjC,OAAO,OAAO,OAAO,UAAU;EAC7B,IAAI,CAAC,MAAM,SAAS,GAAG,GACrB,OAAO;EAET,MAAM,QAAQ,4BAA4B,KAAK,KAAK;EACpD,OAAO,CAAC,CAAC,SAAS,OAAO,MAAM,MAAM,SAAS,MAAM,IAAI,OAAO,MAAM,EAAE,MAAM;CAC/E,CAAC;AAEL"}
1
+ {"version":3,"file":"node-cron.js","names":[],"sources":["../../../src/integrations/node-cron.ts"],"sourcesContent":["import type { IntegrationFn, MonitorConfig } from '@sentry/core';\nimport { defineIntegration } from '@sentry/core';\nimport { CHANNELS } from '../orchestrion/channels';\nimport { nodeCronModuleNames } from '../orchestrion/config/node-cron';\nimport { invokeOrchestrionInstrumentation } from '../orchestrion/instrumentation';\nimport type { AnyFn } from '../utils/cronMonitoring';\nimport {\n cronExpressionToMonitorConfig,\n shouldMonitorJob,\n subscribeToJobCreation,\n wrapScheduledJob,\n} from '../utils/cronMonitoring';\n\nconst INTEGRATION_NAME = 'NodeCron' as const;\n\nexport interface NodeCronIntegrationOptions {\n /** Task names not to monitor. Strings must match the name exactly. */\n excludeJobs?: Array<string | RegExp>;\n}\n\nconst _nodeCronIntegration = ((options: NodeCronIntegrationOptions = {}) => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n invokeOrchestrionInstrumentation(client, nodeCronModuleNames, subscribe, [options], {\n // The binding only parents spans, and this integration creates none.\n requiresTracingChannelBinding: false,\n });\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Sends Crons check-ins for every named `node-cron` task, with its schedule as the monitor config.\n * The monitor slug is the task's `name` option. Tasks without a name, or with a schedule Sentry can't express, are not\n * monitored.\n */\nexport const nodeCronIntegration = defineIntegration(_nodeCronIntegration);\n\nfunction subscribe(options: NodeCronIntegrationOptions): void {\n subscribeToJobCreation(CHANNELS.NODE_CRON_CREATE_TASK, INTEGRATION_NAME, args => wrapTask(args, options));\n subscribeToJobCreation(CHANNELS.NODE_CRON_V4_CREATE_TASK, INTEGRATION_NAME, args =>\n wrapTask(args, options, isReadAlikeByNodeCron4),\n );\n subscribeToJobCreation(CHANNELS.NODE_CRON_V3_CREATE_TASK, INTEGRATION_NAME, args =>\n wrapTask(args, options, isReadAlikeByNodeCron3),\n );\n}\n\n// `createTask(expression, func, options)`\nfunction wrapTask(\n args: unknown[],\n options: NodeCronIntegrationOptions,\n isReadAlike?: (expression: string) => boolean,\n): void {\n const [expression, func, taskOptions] = args;\n const { name, timezone } = (taskOptions || {}) as { name?: unknown; timezone?: unknown };\n if (!shouldMonitorJob(name, func, options.excludeJobs)) {\n return;\n }\n const monitorConfig = getMonitorConfig(String(expression), timezone, isReadAlike);\n args[1] = wrapScheduledJob(func as AnyFn, name, monitorConfig, 'auto.function.node-cron');\n}\n\n/** The monitor config for a task, or `undefined` if `isReadAlike` says this node-cron version reads it differently. */\nexport function getMonitorConfig(\n expression: string,\n timezone: unknown,\n isReadAlike?: (expression: string) => boolean,\n): MonitorConfig | undefined {\n return isReadAlike && !isReadAlike(expression)\n ? undefined\n : cronExpressionToMonitorConfig(expression, timezone, 'node-cron');\n}\n\nconst NODE_CRON_3_FIELD_MINIMUMS = [0, 0, 1, 1, 0];\n\n/**\n * node-cron before 4.6 reads `7` as `0` and swaps reversed ranges, so it runs `sat-sun`, `6-0` and `6-7` every day.\n * It also reads a step without a range, like `5/10`, as its start. Returns `false` where that could differ.\n */\nexport function isReadAlikeByNodeCron4(expression: string): boolean {\n const fields = expression.trim().split(/\\s+/);\n const weekday = fields[fields.length - 1] || '';\n return (\n !(weekday.includes('-') && (weekday.includes('7') || /-(?:0|sun)/i.test(weekday))) &&\n !fields.some(field => field.split(',').some(part => /^[a-z\\d]+\\//i.test(part)))\n );\n}\n\n/**\n * node-cron 3 keeps the values of a stepped field that are multiples of the step (`*\\/2` days are 2, 4, ...)\n * and reads weekday ranges like node-cron 4 before 4.6. Returns `false` where that differs from standard cron.\n */\nexport function isReadAlikeByNodeCron3(expression: string): boolean {\n const fields = expression.trim().split(/\\s+/);\n const minimums = fields.length === 6 ? [0, ...NODE_CRON_3_FIELD_MINIMUMS] : NODE_CRON_3_FIELD_MINIMUMS;\n return (\n isReadAlikeByNodeCron4(expression) &&\n fields.every((field, index) => {\n if (!field.includes('/')) {\n return true;\n }\n const match = /^(?:\\*|(\\d+)-\\d+)\\/(\\d+)$/.exec(field);\n return !!match && Number(match[1] ?? minimums[index]) % Number(match[2]) === 0;\n })\n );\n}\n"],"mappings":";;;;;;AAaA,MAAM,mBAAmB;AAOzB,MAAM,yBAAyB,UAAsC,CAAC,MAAM;CAC1E,OAAO;EACL,MAAM;EACN,MAAM,QAAQ;GACZ,iCAAiC,QAAQ,qBAAqB,WAAW,CAAC,OAAO,GAAG,EAElF,+BAA+B,MACjC,CAAC;EACH;CACF;AACF;;;;;;AAOA,MAAa,sBAAsB,kBAAkB,oBAAoB;AAEzE,SAAS,UAAU,SAA2C;CAC5D,uBAAuB,SAAS,uBAAuB,mBAAkB,SAAQ,SAAS,MAAM,OAAO,CAAC;CACxG,uBAAuB,SAAS,0BAA0B,mBAAkB,SAC1E,SAAS,MAAM,SAAS,sBAAsB,CAChD;CACA,uBAAuB,SAAS,0BAA0B,mBAAkB,SAC1E,SAAS,MAAM,SAAS,sBAAsB,CAChD;AACF;AAGA,SAAS,SACP,MACA,SACA,aACM;CACN,MAAM,CAAC,YAAY,MAAM,eAAe;CACxC,MAAM,EAAE,MAAM,aAAc,eAAe,CAAC;CAC5C,IAAI,CAAC,iBAAiB,MAAM,MAAM,QAAQ,WAAW,GACnD;CAEF,MAAM,gBAAgB,iBAAiB,OAAO,UAAU,GAAG,UAAU,WAAW;CAChF,KAAK,KAAK,iBAAiB,MAAe,MAAM,eAAe,yBAAyB;AAC1F;;AAGA,SAAgB,iBACd,YACA,UACA,aAC2B;CAC3B,OAAO,eAAe,CAAC,YAAY,UAAU,IACzC,KAAA,IACA,8BAA8B,YAAY,UAAU,WAAW;AACrE;AAEA,MAAM,6BAA6B;CAAC;CAAG;CAAG;CAAG;CAAG;AAAC;;;;;AAMjD,SAAgB,uBAAuB,YAA6B;CAClE,MAAM,SAAS,WAAW,KAAK,CAAC,CAAC,MAAM,KAAK;CAC5C,MAAM,UAAU,OAAO,OAAO,SAAS,MAAM;CAC7C,OACE,EAAE,QAAQ,SAAS,GAAG,MAAM,QAAQ,SAAS,GAAG,KAAK,cAAc,KAAK,OAAO,OAC/E,CAAC,OAAO,MAAK,UAAS,MAAM,MAAM,GAAG,CAAC,CAAC,MAAK,SAAQ,eAAe,KAAK,IAAI,CAAC,CAAC;AAElF;;;;;AAMA,SAAgB,uBAAuB,YAA6B;CAClE,MAAM,SAAS,WAAW,KAAK,CAAC,CAAC,MAAM,KAAK;CAC5C,MAAM,WAAW,OAAO,WAAW,IAAI,CAAC,GAAG,GAAG,0BAA0B,IAAI;CAC5E,OACE,uBAAuB,UAAU,KACjC,OAAO,OAAO,OAAO,UAAU;EAC7B,IAAI,CAAC,MAAM,SAAS,GAAG,GACrB,OAAO;EAET,MAAM,QAAQ,4BAA4B,KAAK,KAAK;EACpD,OAAO,CAAC,CAAC,SAAS,OAAO,MAAM,MAAM,SAAS,MAAM,IAAI,OAAO,MAAM,EAAE,MAAM;CAC/E,CAAC;AAEL"}
@@ -55,9 +55,9 @@ function isCronShaped(value) {
55
55
  return /^@[a-z]+$/i.test(value.trim()) || (fields.length === 5 || fields.length === 6) && fields.every((field) => /^[\d*,/?#a-z-]+$/i.test(field));
56
56
  }
57
57
  function getMonitorConfig(spec) {
58
- if (typeof spec === "string") return cronExpressionToMonitorConfig(spec, void 0, "or");
58
+ if (typeof spec === "string") return cronExpressionToMonitorConfig(spec, void 0, "cron-parser");
59
59
  const { rule, tz, start, end } = spec || {};
60
- return typeof rule === "string" && !start && !end ? cronExpressionToMonitorConfig(rule, tz, "or") : void 0;
60
+ return typeof rule === "string" && !start && !end ? cronExpressionToMonitorConfig(rule, tz, "cron-parser") : void 0;
61
61
  }
62
62
  export { beforeSchedule, getMonitorConfig, isOneOffSpec, nodeScheduleIntegration, onSchedule };
63
63
 
@@ -1 +1 @@
1
- {"version":3,"file":"node-schedule.js","names":[],"sources":["../../../src/integrations/node-schedule.ts"],"sourcesContent":["import type { IntegrationFn, MonitorConfig } from '@sentry/core';\nimport { defineIntegration } from '@sentry/core';\nimport { CHANNELS } from '../orchestrion/channels';\nimport { nodeScheduleModuleNames } from '../orchestrion/config/node-schedule';\nimport { invokeOrchestrionInstrumentation } from '../orchestrion/instrumentation';\nimport type { AnyFn, ScheduleChange } from '../utils/cronMonitoring';\nimport {\n cronExpressionToMonitorConfig,\n shouldMonitorJob,\n subscribeToScheduleChange,\n updateMonitorConfig,\n wrapScheduledJob,\n} from '../utils/cronMonitoring';\n\nconst INTEGRATION_NAME = 'NodeSchedule' as const;\n\nexport interface NodeScheduleIntegrationOptions {\n /** Job names not to monitor. Strings must match the name exactly. */\n excludeJobs?: Array<string | RegExp>;\n}\n\nconst _nodeScheduleIntegration = ((options: NodeScheduleIntegrationOptions = {}) => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n invokeOrchestrionInstrumentation(client, nodeScheduleModuleNames, subscribe, [options], {\n requiresTracingChannelBinding: false,\n });\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Sends Crons check-ins for every named `node-schedule` job, whether it's created with `scheduleJob` or `new Job()`.\n * The monitor slug is the job name. Jobs without a name, one-off jobs, and jobs with a schedule Crons can't express\n * are not monitored.\n */\nexport const nodeScheduleIntegration = defineIntegration(_nodeScheduleIntegration);\n\nfunction subscribe(options: NodeScheduleIntegrationOptions): void {\n subscribeToScheduleChange(CHANNELS.NODE_SCHEDULE_SCHEDULE, INTEGRATION_NAME, onSchedule, change =>\n beforeSchedule(change, options),\n );\n}\n\ninterface Job {\n name?: unknown;\n job?: unknown;\n nextInvocation?: () => unknown;\n}\n\n// The name node-schedule gives jobs created without one.\nconst ANONYMOUS_NAME = /^<Anonymous Job \\d+[ >]/;\n\n// `job.schedule(spec)` calls that add to runs the job already has pending, rather than replace them.\nconst addsToPendingRuns = new WeakSet<ScheduleChange>();\n\n/** Wraps a named job's method before `job.schedule(spec)` with a recurring spec, unless it's already wrapped. */\nexport function beforeSchedule(change: ScheduleChange, options: NodeScheduleIntegrationOptions): void {\n const job = change.self as Job | undefined;\n if (!job) {\n return;\n }\n if (typeof job.nextInvocation === 'function' && job.nextInvocation() != null) {\n addsToPendingRuns.add(change);\n }\n const name = typeof job.name === 'string' && !ANONYMOUS_NAME.test(job.name) ? job.name : undefined;\n if (isOneOffSpec(change.arguments[0]) || !shouldMonitorJob(name, job.job, options.excludeJobs)) {\n return;\n }\n job.job = wrapScheduledJob(job.job as AnyFn, name, undefined, 'auto.function.node-schedule');\n}\n\n/**\n * Sets the spec's config after `job.schedule(spec)`. Without one, from a spec Crons can't express or a job that also\n * keeps runs from an earlier spec, the job doesn't check in.\n */\nexport function onSchedule(change: ScheduleChange): void {\n // `schedule` returns false when it scheduled nothing, and `reschedule` then keeps the old schedule.\n if (change.result === true) {\n const job = change.self as Job | undefined;\n updateMonitorConfig(job?.job, addsToPendingRuns.has(change) ? undefined : getMonitorConfig(change.arguments[0]));\n }\n}\n\n/** Whether node-schedule runs a job with this spec once: a `Date`, a timestamp, or a date string. */\nexport function isOneOffSpec(spec: unknown): boolean {\n const { rule } = (spec || {}) as { rule?: unknown };\n const when = typeof spec === 'object' && rule ? rule : spec;\n if (typeof when === 'string') {\n // `Date.parse` also accepts some crons, like `0 9 * * *`.\n return !isCronShaped(when) && !Number.isNaN(Date.parse(when));\n }\n return when instanceof Date || typeof when === 'number';\n}\n\nfunction isCronShaped(value: string): boolean {\n const fields = value.trim().split(/\\s+/);\n return (\n /^@[a-z]+$/i.test(value.trim()) ||\n ((fields.length === 5 || fields.length === 6) && fields.every(field => /^[\\d*,/?#a-z-]+$/i.test(field)))\n );\n}\n\n// Only cron strings convert; recurrence rules and rules limited by `start` or `end` don't.\nexport function getMonitorConfig(spec: unknown): MonitorConfig | undefined {\n if (typeof spec === 'string') {\n return cronExpressionToMonitorConfig(spec, undefined, 'or');\n }\n const { rule, tz, start, end } = (spec || {}) as { rule?: unknown; tz?: unknown; start?: unknown; end?: unknown };\n return typeof rule === 'string' && !start && !end ? cronExpressionToMonitorConfig(rule, tz, 'or') : undefined;\n}\n"],"mappings":";;;;;;AAcA,MAAM,mBAAmB;AAOzB,MAAM,6BAA6B,UAA0C,CAAC,MAAM;CAClF,OAAO;EACL,MAAM;EACN,MAAM,QAAQ;GACZ,iCAAiC,QAAQ,yBAAyB,WAAW,CAAC,OAAO,GAAG,EACtF,+BAA+B,MACjC,CAAC;EACH;CACF;AACF;;;;;;AAOA,MAAa,0BAA0B,kBAAkB,wBAAwB;AAEjF,SAAS,UAAU,SAA+C;CAChE,0BAA0B,SAAS,wBAAwB,kBAAkB,aAAY,WACvF,eAAe,QAAQ,OAAO,CAChC;AACF;AASA,MAAM,iBAAiB;AAGvB,MAAM,oCAAoB,IAAI,QAAwB;;AAGtD,SAAgB,eAAe,QAAwB,SAA+C;CACpG,MAAM,MAAM,OAAO;CACnB,IAAI,CAAC,KACH;CAEF,IAAI,OAAO,IAAI,mBAAmB,cAAc,IAAI,eAAe,KAAK,MACtE,kBAAkB,IAAI,MAAM;CAE9B,MAAM,OAAO,OAAO,IAAI,SAAS,YAAY,CAAC,eAAe,KAAK,IAAI,IAAI,IAAI,IAAI,OAAO,KAAA;CACzF,IAAI,aAAa,OAAO,UAAU,EAAE,KAAK,CAAC,iBAAiB,MAAM,IAAI,KAAK,QAAQ,WAAW,GAC3F;CAEF,IAAI,MAAM,iBAAiB,IAAI,KAAc,MAAM,KAAA,GAAW,6BAA6B;AAC7F;;;;;AAMA,SAAgB,WAAW,QAA8B;CAEvD,IAAI,OAAO,WAAW,MAAM;EAC1B,MAAM,MAAM,OAAO;EACnB,oBAAoB,KAAK,KAAK,kBAAkB,IAAI,MAAM,IAAI,KAAA,IAAY,iBAAiB,OAAO,UAAU,EAAE,CAAC;CACjH;AACF;;AAGA,SAAgB,aAAa,MAAwB;CACnD,MAAM,EAAE,SAAU,QAAQ,CAAC;CAC3B,MAAM,OAAO,OAAO,SAAS,YAAY,OAAO,OAAO;CACvD,IAAI,OAAO,SAAS,UAElB,OAAO,CAAC,aAAa,IAAI,KAAK,CAAC,OAAO,MAAM,KAAK,MAAM,IAAI,CAAC;CAE9D,OAAO,gBAAgB,QAAQ,OAAO,SAAS;AACjD;AAEA,SAAS,aAAa,OAAwB;CAC5C,MAAM,SAAS,MAAM,KAAK,CAAC,CAAC,MAAM,KAAK;CACvC,OACE,aAAa,KAAK,MAAM,KAAK,CAAC,MAC5B,OAAO,WAAW,KAAK,OAAO,WAAW,MAAM,OAAO,OAAM,UAAS,oBAAoB,KAAK,KAAK,CAAC;AAE1G;AAGA,SAAgB,iBAAiB,MAA0C;CACzE,IAAI,OAAO,SAAS,UAClB,OAAO,8BAA8B,MAAM,KAAA,GAAW,IAAI;CAE5D,MAAM,EAAE,MAAM,IAAI,OAAO,QAAS,QAAQ,CAAC;CAC3C,OAAO,OAAO,SAAS,YAAY,CAAC,SAAS,CAAC,MAAM,8BAA8B,MAAM,IAAI,IAAI,IAAI,KAAA;AACtG"}
1
+ {"version":3,"file":"node-schedule.js","names":[],"sources":["../../../src/integrations/node-schedule.ts"],"sourcesContent":["import type { IntegrationFn, MonitorConfig } from '@sentry/core';\nimport { defineIntegration } from '@sentry/core';\nimport { CHANNELS } from '../orchestrion/channels';\nimport { nodeScheduleModuleNames } from '../orchestrion/config/node-schedule';\nimport { invokeOrchestrionInstrumentation } from '../orchestrion/instrumentation';\nimport type { AnyFn, ScheduleChange } from '../utils/cronMonitoring';\nimport {\n cronExpressionToMonitorConfig,\n shouldMonitorJob,\n subscribeToScheduleChange,\n updateMonitorConfig,\n wrapScheduledJob,\n} from '../utils/cronMonitoring';\n\nconst INTEGRATION_NAME = 'NodeSchedule' as const;\n\nexport interface NodeScheduleIntegrationOptions {\n /** Job names not to monitor. Strings must match the name exactly. */\n excludeJobs?: Array<string | RegExp>;\n}\n\nconst _nodeScheduleIntegration = ((options: NodeScheduleIntegrationOptions = {}) => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n invokeOrchestrionInstrumentation(client, nodeScheduleModuleNames, subscribe, [options], {\n requiresTracingChannelBinding: false,\n });\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Sends Crons check-ins for every named `node-schedule` job, whether it's created with `scheduleJob` or `new Job()`.\n * The monitor slug is the job name. Jobs without a name, one-off jobs, and jobs with a schedule Crons can't express\n * are not monitored.\n */\nexport const nodeScheduleIntegration = defineIntegration(_nodeScheduleIntegration);\n\nfunction subscribe(options: NodeScheduleIntegrationOptions): void {\n subscribeToScheduleChange(CHANNELS.NODE_SCHEDULE_SCHEDULE, INTEGRATION_NAME, onSchedule, change =>\n beforeSchedule(change, options),\n );\n}\n\ninterface Job {\n name?: unknown;\n job?: unknown;\n nextInvocation?: () => unknown;\n}\n\n// The name node-schedule gives jobs created without one.\nconst ANONYMOUS_NAME = /^<Anonymous Job \\d+[ >]/;\n\n// `job.schedule(spec)` calls that add to runs the job already has pending, rather than replace them.\nconst addsToPendingRuns = new WeakSet<ScheduleChange>();\n\n/** Wraps a named job's method before `job.schedule(spec)` with a recurring spec, unless it's already wrapped. */\nexport function beforeSchedule(change: ScheduleChange, options: NodeScheduleIntegrationOptions): void {\n const job = change.self as Job | undefined;\n if (!job) {\n return;\n }\n if (typeof job.nextInvocation === 'function' && job.nextInvocation() != null) {\n addsToPendingRuns.add(change);\n }\n const name = typeof job.name === 'string' && !ANONYMOUS_NAME.test(job.name) ? job.name : undefined;\n if (isOneOffSpec(change.arguments[0]) || !shouldMonitorJob(name, job.job, options.excludeJobs)) {\n return;\n }\n job.job = wrapScheduledJob(job.job as AnyFn, name, undefined, 'auto.function.node-schedule');\n}\n\n/**\n * Sets the spec's config after `job.schedule(spec)`. Without one, from a spec Crons can't express or a job that also\n * keeps runs from an earlier spec, the job doesn't check in.\n */\nexport function onSchedule(change: ScheduleChange): void {\n // `schedule` returns false when it scheduled nothing, and `reschedule` then keeps the old schedule.\n if (change.result === true) {\n const job = change.self as Job | undefined;\n updateMonitorConfig(job?.job, addsToPendingRuns.has(change) ? undefined : getMonitorConfig(change.arguments[0]));\n }\n}\n\n/** Whether node-schedule runs a job with this spec once: a `Date`, a timestamp, or a date string. */\nexport function isOneOffSpec(spec: unknown): boolean {\n const { rule } = (spec || {}) as { rule?: unknown };\n const when = typeof spec === 'object' && rule ? rule : spec;\n if (typeof when === 'string') {\n // `Date.parse` also accepts some crons, like `0 9 * * *`.\n return !isCronShaped(when) && !Number.isNaN(Date.parse(when));\n }\n return when instanceof Date || typeof when === 'number';\n}\n\nfunction isCronShaped(value: string): boolean {\n const fields = value.trim().split(/\\s+/);\n return (\n /^@[a-z]+$/i.test(value.trim()) ||\n ((fields.length === 5 || fields.length === 6) && fields.every(field => /^[\\d*,/?#a-z-]+$/i.test(field)))\n );\n}\n\n// Only cron strings convert; recurrence rules and rules limited by `start` or `end` don't.\nexport function getMonitorConfig(spec: unknown): MonitorConfig | undefined {\n if (typeof spec === 'string') {\n return cronExpressionToMonitorConfig(spec, undefined, 'cron-parser');\n }\n const { rule, tz, start, end } = (spec || {}) as { rule?: unknown; tz?: unknown; start?: unknown; end?: unknown };\n return typeof rule === 'string' && !start && !end\n ? cronExpressionToMonitorConfig(rule, tz, 'cron-parser')\n : undefined;\n}\n"],"mappings":";;;;;;AAcA,MAAM,mBAAmB;AAOzB,MAAM,6BAA6B,UAA0C,CAAC,MAAM;CAClF,OAAO;EACL,MAAM;EACN,MAAM,QAAQ;GACZ,iCAAiC,QAAQ,yBAAyB,WAAW,CAAC,OAAO,GAAG,EACtF,+BAA+B,MACjC,CAAC;EACH;CACF;AACF;;;;;;AAOA,MAAa,0BAA0B,kBAAkB,wBAAwB;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