@sentry/server-utils 11.15.0 → 11.17.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 (108) hide show
  1. package/build/cjs/chunks/config.js +60 -0
  2. package/build/cjs/chunks/config.js.map +1 -1
  3. package/build/cjs/chunks/exports.js +194 -58
  4. package/build/cjs/chunks/exports.js.map +1 -1
  5. package/build/cjs/chunks/moduleInjectedTransform.js +8 -0
  6. package/build/cjs/chunks/moduleInjectedTransform.js.map +1 -1
  7. package/build/cjs/index.js +299 -168
  8. package/build/cjs/index.js.map +1 -1
  9. package/build/cjs/index.request-handler.js +1 -0
  10. package/build/cjs/index.request-handler.js.map +1 -1
  11. package/build/esm/ai/flue/utils.js +1 -0
  12. package/build/esm/ai/flue/utils.js.map +1 -1
  13. package/build/esm/ai/google-genai/decisions.js +29 -1
  14. package/build/esm/ai/google-genai/decisions.js.map +1 -1
  15. package/build/esm/ai/langchain/embeddings.js +23 -8
  16. package/build/esm/ai/langchain/embeddings.js.map +1 -1
  17. package/build/esm/ai/langchain/index.js +41 -30
  18. package/build/esm/ai/langchain/index.js.map +1 -1
  19. package/build/esm/ai/langgraph/agent-span.js +6 -2
  20. package/build/esm/ai/langgraph/agent-span.js.map +1 -1
  21. package/build/esm/ai/langgraph/index.js +5 -1
  22. package/build/esm/ai/langgraph/index.js.map +1 -1
  23. package/build/esm/ai/langgraph/stream.js +4 -1
  24. package/build/esm/ai/langgraph/stream.js.map +1 -1
  25. package/build/esm/ai/openai/mapping.js +48 -1
  26. package/build/esm/ai/openai/mapping.js.map +1 -1
  27. package/build/esm/ai/pi-durable/index.js +10 -13
  28. package/build/esm/ai/pi-durable/index.js.map +1 -1
  29. package/build/esm/ai/pi-durable/runs.js +6 -5
  30. package/build/esm/ai/pi-durable/runs.js.map +1 -1
  31. package/build/esm/ai/pi-durable/tools.js +21 -17
  32. package/build/esm/ai/pi-durable/tools.js.map +1 -1
  33. package/build/esm/index.js +3 -2
  34. package/build/esm/index.js.map +1 -1
  35. package/build/esm/integrations/clickhouse-sql.js +31 -0
  36. package/build/esm/integrations/clickhouse-sql.js.map +1 -0
  37. package/build/esm/integrations/clickhouse.js +88 -0
  38. package/build/esm/integrations/clickhouse.js.map +1 -0
  39. package/build/esm/integrations/express/instrumentation.js +1 -0
  40. package/build/esm/integrations/express/instrumentation.js.map +1 -1
  41. package/build/esm/integrations/fastify/instrumentation.js +3 -1
  42. package/build/esm/integrations/fastify/instrumentation.js.map +1 -1
  43. package/build/esm/integrations/hapi/index.js +15 -1
  44. package/build/esm/integrations/hapi/index.js.map +1 -1
  45. package/build/esm/integrations/index.js +2 -0
  46. package/build/esm/integrations/index.js.map +1 -1
  47. package/build/esm/integrations/langchain.js +10 -3
  48. package/build/esm/integrations/langchain.js.map +1 -1
  49. package/build/esm/orchestrion/channels.js +2 -0
  50. package/build/esm/orchestrion/channels.js.map +1 -1
  51. package/build/esm/orchestrion/config/channel-integration-definitions.js +8 -0
  52. package/build/esm/orchestrion/config/channel-integration-definitions.js.map +1 -1
  53. package/build/esm/orchestrion/config/clickhouse.js +51 -0
  54. package/build/esm/orchestrion/config/clickhouse.js.map +1 -0
  55. package/build/esm/orchestrion/config/index.js +2 -0
  56. package/build/esm/orchestrion/config/index.js.map +1 -1
  57. package/build/esm/package.json +1 -1
  58. package/build/esm/utils/sql.js +37 -16
  59. package/build/esm/utils/sql.js.map +1 -1
  60. package/build/esm/utils/wrapServerRequestHandler.js +2 -1
  61. package/build/esm/utils/wrapServerRequestHandler.js.map +1 -1
  62. package/build/types/ai/flue/utils.d.ts.map +1 -1
  63. package/build/types/ai/google-genai/decisions.d.ts.map +1 -1
  64. package/build/types/ai/langchain/embeddings.d.ts +2 -2
  65. package/build/types/ai/langchain/embeddings.d.ts.map +1 -1
  66. package/build/types/ai/langchain/index.d.ts.map +1 -1
  67. package/build/types/ai/langchain/types.d.ts +8 -4
  68. package/build/types/ai/langchain/types.d.ts.map +1 -1
  69. package/build/types/ai/langgraph/agent-span.d.ts +5 -2
  70. package/build/types/ai/langgraph/agent-span.d.ts.map +1 -1
  71. package/build/types/ai/langgraph/index.d.ts.map +1 -1
  72. package/build/types/ai/langgraph/stream.d.ts.map +1 -1
  73. package/build/types/ai/langgraph/types.d.ts +10 -2
  74. package/build/types/ai/langgraph/types.d.ts.map +1 -1
  75. package/build/types/ai/openai/mapping.d.ts.map +1 -1
  76. package/build/types/ai/pi-durable/index.d.ts.map +1 -1
  77. package/build/types/ai/pi-durable/runs.d.ts +4 -2
  78. package/build/types/ai/pi-durable/runs.d.ts.map +1 -1
  79. package/build/types/ai/pi-durable/tools.d.ts +4 -6
  80. package/build/types/ai/pi-durable/tools.d.ts.map +1 -1
  81. package/build/types/ai/pi-durable/types.d.ts +10 -1
  82. package/build/types/ai/pi-durable/types.d.ts.map +1 -1
  83. package/build/types/ai/types.d.ts +1 -1
  84. package/build/types/ai/types.d.ts.map +1 -1
  85. package/build/types/index.d.ts +2 -1
  86. package/build/types/index.d.ts.map +1 -1
  87. package/build/types/integrations/clickhouse-sql.d.ts +8 -0
  88. package/build/types/integrations/clickhouse-sql.d.ts.map +1 -0
  89. package/build/types/integrations/clickhouse.d.ts +11 -0
  90. package/build/types/integrations/clickhouse.d.ts.map +1 -0
  91. package/build/types/integrations/express/types.d.ts +1 -0
  92. package/build/types/integrations/express/types.d.ts.map +1 -1
  93. package/build/types/integrations/fastify/instrumentation.d.ts.map +1 -1
  94. package/build/types/integrations/hapi/index.d.ts +12 -0
  95. package/build/types/integrations/hapi/index.d.ts.map +1 -1
  96. package/build/types/integrations/index.d.ts.map +1 -1
  97. package/build/types/integrations/langchain.d.ts.map +1 -1
  98. package/build/types/orchestrion/channels.d.ts +12 -0
  99. package/build/types/orchestrion/channels.d.ts.map +1 -1
  100. package/build/types/orchestrion/config/channel-integration-definitions.d.ts +3 -0
  101. package/build/types/orchestrion/config/channel-integration-definitions.d.ts.map +1 -1
  102. package/build/types/orchestrion/config/clickhouse.d.ts +18 -0
  103. package/build/types/orchestrion/config/clickhouse.d.ts.map +1 -0
  104. package/build/types/orchestrion/config/index.d.ts.map +1 -1
  105. package/build/types/utils/sql.d.ts +28 -3
  106. package/build/types/utils/sql.d.ts.map +1 -1
  107. package/build/types/utils/wrapServerRequestHandler.d.ts.map +1 -1
  108. package/package.json +4 -4
@@ -1 +1 @@
1
- {"version":3,"file":"runs.js","names":[],"sources":["../../../../src/ai/pi-durable/runs.ts"],"sourcesContent":["import type { MaybeWeakRef, Scope, Span, SpanStatus } from '@sentry/core';\nimport {\n continueTrace,\n debug,\n derefWeakRef,\n getDefaultIsolationScope,\n getRootSpan,\n SPAN_STATUS_ERROR,\n startInactiveSpan,\n startNewTrace,\n uuid4,\n} from '@sentry/core';\nimport { GEN_AI_CONVERSATION_ID, GEN_AI_OPERATION_NAME, SENTRY_ORIGIN } from '@sentry/conventions/attributes';\nimport { GEN_AI_INVOKE_AGENT } from '@sentry/conventions/op';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport { MAX_TRACKED_PI_RUNS, PI_DURABLE_ORIGIN, PI_LIVE_DOC_KIND, PI_PROVIDER_DOC_KIND } from './constants';\nimport type { PiCommitChange, PiDocToken, PiLiveState, PiProviderState, PiSettlement, PiTaskRuntime } from './types';\nimport { withCleanScopes } from '../../utils/withCleanScopes';\nimport { bound } from './utils';\n\n// The definition of `pi.provider` as pi-durable checks it on a read: the address, the version and the\n// persisted semantics of the document.\nconst PROVIDER_DOC = {\n definition: { kind: PI_PROVIDER_DOC_KIND, version: 1, scope: 'conversation', history: 'latest', fork: 'initial' },\n};\n\n// Unanswered reasons that mean the run was stopped, not that it failed.\nconst CANCELLED_REASONS = new Set(['aborted', 'reset']);\n\n/**\n * One run: the work from an input to its answer. It spans several `pi.generation` tasks (run control\n * moves to a new one after every tool round) and their `pi.tool` tasks, so it is tracked per\n * conversation, which runs at most one run at a time.\n */\nexport interface PiRun {\n conversationId: unknown;\n span: Span;\n isolationScope: Scope;\n /** The run's first input submission, which identifies the run in `pi.live`. */\n firstInput?: unknown;\n /** The conversation's provider session id, read by the first phase of the run. */\n sessionId?: string;\n /**\n * The status the run ends with, set while the commit that ends it is in flight. `harness.close()`\n * can begin in that gap, because `wait()` resolves as soon as the commit settles the inputs.\n */\n pendingEnd?: { status?: SpanStatus };\n}\n\n/** Open runs of one Harness, keyed by the pi-durable conversation id. */\nexport interface PiRuns {\n /**\n * Random id of this Harness, prefixed to `gen_ai.conversation.id` until the provider session id of\n * the conversation is known. pi-durable numbers conversations per storage from 1, so the bare id\n * would merge the root conversations of every Harness into one Sentry conversation.\n */\n harnessId: string;\n active: Map<unknown, PiRun>;\n /**\n * Tool calls that created a conversation they own, keyed by that conversation. The child's first\n * run becomes a child of the call while the call's trace is in progress, and otherwise continues\n * that trace with the call as parent. This is how a subagent's run joins the trace of the run that\n * delegated to it.\n */\n owners: Map<unknown, PiOwner>;\n /**\n * Tool calls of running `pi.tool` phases, keyed by task id. Their spans end when the phase ends,\n * after it has committed the result the model receives.\n */\n toolCalls: Map<unknown, PiToolCall[]>;\n}\n\n/** A tool call that created a conversation it owns. */\nexport interface PiOwner {\n /**\n * The call's `execute_tool` span, held weakly: a conversation whose first run never starts must\n * not keep the trace of the call alive.\n */\n span: MaybeWeakRef<Span>;\n /** The `sentry-trace` value of the span, used to continue its trace once that trace has ended. */\n sentryTrace: string;\n /** The `baggage` value of the span, used together with `sentryTrace`. */\n baggage: string | undefined;\n}\n\n/** One `execute()` of a tool. */\nexport interface PiToolCall {\n span: Span;\n callId?: string;\n recordOutputs: boolean;\n /** Set once the span has a status other than ok, so the committed result does not overwrite it. */\n failed?: boolean;\n /** When `execute()` settled, used as the span's end time. */\n endTimestamp?: number;\n /** Set once `execute()` settled. Runs `onSpanEnd` with its result. */\n onSpanEnd?: () => void;\n}\n\nexport function createRuns(): PiRuns {\n return {\n harnessId: uuid4(),\n active: new Map(),\n owners: new Map(),\n toolCalls: new Map(),\n };\n}\n\nexport function toSentryConversationId(runs: PiRuns, conversationId: unknown): string {\n return runs.active.get(conversationId)?.sessionId ?? `${runs.harnessId}:${String(conversationId)}`;\n}\n\n/**\n * Read the provider session id of the conversation, or `undefined` when pi-durable keeps none.\n *\n * pi-durable 1.0.2 and later keep a UUIDv7 per conversation in the `pi.provider` document, stored with\n * the conversation. Unlike the harness prefix, it stays the same when a Harness opens the storage\n * again, for example after a Durable Object restarts, and it is unique across storages.\n */\nexport async function readProviderSessionId(runtime: PiTaskRuntime, context: unknown): Promise<string | undefined> {\n try {\n const provider = (await runtime.snapshot?.(PROVIDER_DOC, runtime.conversationId, context)) as\n | PiProviderState\n | undefined;\n return typeof provider?.sessionId === 'string' && provider.sessionId ? provider.sessionId : undefined;\n } catch (error) {\n // A later version of the document fails the read. The harness prefix is used then.\n DEBUG_BUILD && debug.warn('[pi-durable] failed to read the provider session id', error);\n return undefined;\n }\n}\n\n/** Start a run of `conversationId`: a new trace, or a child of the tool call that owns the conversation. */\nexport function startRun(conversationId: unknown, runs: PiRuns): PiRun {\n if (runs.active.size >= MAX_TRACKED_PI_RUNS) {\n const oldest = runs.active.keys().next().value;\n runs.active.get(oldest)?.span.end();\n runs.active.delete(oldest);\n }\n\n const owner = runs.owners.get(conversationId);\n runs.owners.delete(conversationId);\n const ownerSpan = derefWeakRef(owner?.span);\n // Under a trace that has ended, the run would be split into one transaction per span when spans are\n // not streamed. Continuing the trace instead also gives the same result whether or not GC ran.\n const parentSpan = ownerSpan && getRootSpan(ownerSpan).isRecording() ? ownerSpan : undefined;\n\n const isolationScope = getDefaultIsolationScope().clone();\n const startRunSpan = (): Span =>\n startInactiveSpan({\n name: 'invoke_agent',\n op: GEN_AI_INVOKE_AGENT,\n ...(parentSpan ? { parentSpan } : {}),\n attributes: {\n [SENTRY_ORIGIN]: PI_DURABLE_ORIGIN,\n [GEN_AI_OPERATION_NAME]: 'invoke_agent',\n [GEN_AI_CONVERSATION_ID]: toSentryConversationId(runs, conversationId),\n },\n });\n const span = withCleanScopes(isolationScope, () => {\n if (parentSpan) {\n return startRunSpan();\n }\n return owner\n ? continueTrace({ sentryTrace: owner.sentryTrace, baggage: owner.baggage }, startRunSpan)\n : startNewTrace(startRunSpan);\n });\n\n const run: PiRun = { conversationId, span, isolationScope };\n runs.active.set(conversationId, run);\n DEBUG_BUILD && debug.log(`[pi-durable] run of conversation ${String(conversationId)} started`);\n return run;\n}\n\nexport function endRun(run: PiRun, runs: PiRuns, status?: SpanStatus): void {\n if (runs.active.get(run.conversationId) !== run) {\n return;\n }\n runs.active.delete(run.conversationId);\n DEBUG_BUILD && debug.log(`[pi-durable] run of conversation ${String(run.conversationId)} ended`, status ?? 'ok');\n if (status) {\n run.span.setStatus(status);\n }\n run.span.end();\n}\n\n/**\n * Watch the generation task's commits for the end of its run.\n *\n * pi-durable keeps run control in the conversation's `pi.live` document: `run` names the task that\n * owns the run and the run's inputs, it moves to the next generation after every tool round, and it\n * is removed, in the same commit that settles the inputs, when the run ends. Every commit that moves\n * or ends a run edits `pi.live` through `tx.doc()`, so reading that draft after the commit's change\n * function returns shows whether the run survived the commit.\n */\nexport function observeRunControl(runtime: PiTaskRuntime, run: PiRun, runs: PiRuns): PiTaskRuntime {\n const commit = (change: PiCommitChange, context: unknown): Promise<void> => {\n let ended = false;\n let settlement: PiSettlement | undefined;\n\n const observedChange: PiCommitChange = async (tx, current) => {\n // A commit can run its change again, so only the attempt that committed counts.\n ended = false;\n settlement = undefined;\n let live: Promise<unknown> | undefined;\n const observedTx = new Proxy(tx, {\n get(target, property) {\n const value = bound(target, property);\n if (typeof value !== 'function') {\n return value;\n }\n if (property === 'doc') {\n return (token: PiDocToken, id: unknown, ...rest: unknown[]) => {\n const draft = value(token, id, ...rest);\n if (token?.definition?.kind === PI_LIVE_DOC_KIND && id === run.conversationId) {\n live = Promise.resolve(draft);\n }\n return draft;\n };\n }\n if (property === 'settleSubmission') {\n return (id: unknown, submissionSettlement: PiSettlement, ...rest: unknown[]) => {\n if (run.firstInput === undefined || id === run.firstInput) {\n settlement = submissionSettlement;\n }\n return value(id, submissionSettlement, ...rest);\n };\n }\n return value;\n },\n });\n\n const result = await change(observedTx, current);\n const draft = (await live) as PiLiveState | undefined;\n if (draft) {\n const firstInput = draft.run?.inputs?.[0];\n if (firstInput === undefined) {\n ended = true;\n } else if (run.firstInput === undefined) {\n run.firstInput = firstInput;\n } else if (firstInput !== run.firstInput) {\n // The run ended and a queued input started the next one in the same commit.\n ended = true;\n }\n }\n run.pendingEnd = ended ? { status: toRunStatus(settlement) } : undefined;\n return result;\n };\n\n return runtime.commit(observedChange, context).then(\n () => {\n if (ended) {\n endRun(run, runs, toRunStatus(settlement));\n }\n },\n error => {\n run.pendingEnd = undefined;\n throw error;\n },\n );\n };\n\n return new Proxy(runtime, {\n get(target, property) {\n return property === 'commit' ? commit : bound(target, property);\n },\n });\n}\n\nfunction toRunStatus(settlement: PiSettlement | undefined): SpanStatus | undefined {\n if (settlement?.status !== 'unanswered') {\n return undefined;\n }\n const reason = settlement.reason ?? 'internal_error';\n return { code: SPAN_STATUS_ERROR, message: CANCELLED_REASONS.has(reason) ? 'cancelled' : reason };\n}\n"],"mappings":";;;;;;;;AAsBA,MAAM,eAAe,EACnB,YAAY;CAAE,MAAM;CAAsB,SAAS;CAAG,OAAO;CAAgB,SAAS;CAAU,MAAM;AAAU,EAClH;AAGA,MAAM,oCAAoB,IAAI,IAAI,CAAC,WAAW,OAAO,CAAC;AAuEtD,SAAgB,aAAqB;CACnC,OAAO;EACL,WAAW,MAAM;EACjB,wBAAQ,IAAI,IAAI;EAChB,wBAAQ,IAAI,IAAI;EAChB,2BAAW,IAAI,IAAI;CACrB;AACF;AAEA,SAAgB,uBAAuB,MAAc,gBAAiC;CACpF,OAAO,KAAK,OAAO,IAAI,cAAc,CAAC,EAAE,aAAa,GAAG,KAAK,UAAU,GAAG,OAAO,cAAc;AACjG;;;;;;;;AASA,eAAsB,sBAAsB,SAAwB,SAA+C;CACjH,IAAI;EACF,MAAM,WAAY,MAAM,QAAQ,WAAW,cAAc,QA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,OAAO;EACT;EAEA,OAAO,QAAQ,OAAO,gBAAgB,OAAO,CAAC,CAAC,WACvC;GACJ,IAAI,OACF,OAAO,KAAK,MAAM,YAAY,UAAU,CAAC;EAE7C,IACA,UAAS;GACP,IAAI,aAAa,KAAA;GACjB,MAAM;EACR,CACF;CACF;CAEA,OAAO,IAAI,MAAM,SAAS,EACxB,IAAI,QAAQ,UAAU;EACpB,OAAO,aAAa,WAAW,SAAS,MAAM,QAAQ,QAAQ;CAChE,EACF,CAAC;AACH;AAEA,SAAS,YAAY,YAA8D;CACjF,IAAI,YAAY,WAAW,cACzB;CAEF,MAAM,SAAS,WAAW,UAAU;CACpC,OAAO;EAAE,MAAM;EAAmB,SAAS,kBAAkB,IAAI,MAAM,IAAI,cAAc;CAAO;AAClG"}
1
+ {"version":3,"file":"runs.js","names":[],"sources":["../../../../src/ai/pi-durable/runs.ts"],"sourcesContent":["import type { MaybeWeakRef, Scope, Span, SpanStatus } from '@sentry/core';\nimport {\n continueTrace,\n debug,\n derefWeakRef,\n getDefaultIsolationScope,\n getRootSpan,\n SPAN_STATUS_ERROR,\n startInactiveSpan,\n startNewTrace,\n uuid4,\n} from '@sentry/core';\nimport { GEN_AI_CONVERSATION_ID, GEN_AI_OPERATION_NAME, SENTRY_ORIGIN } from '@sentry/conventions/attributes';\nimport { GEN_AI_INVOKE_AGENT } from '@sentry/conventions/op';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport { MAX_TRACKED_PI_RUNS, PI_DURABLE_ORIGIN, PI_LIVE_DOC_KIND, PI_PROVIDER_DOC_KIND } from './constants';\nimport type {\n PiCommitChange,\n PiDocToken,\n PiLiveState,\n PiProviderState,\n PiSettlement,\n PiTaskRuntime,\n PiToolResultMessage,\n} from './types';\nimport { withCleanScopes } from '../../utils/withCleanScopes';\nimport { bound } from './utils';\n\n// The definition of `pi.provider` as pi-durable checks it on a read: the address, the version and the\n// persisted semantics of the document.\nconst PROVIDER_DOC = {\n definition: { kind: PI_PROVIDER_DOC_KIND, version: 1, scope: 'conversation', history: 'latest', fork: 'initial' },\n};\n\n// Unanswered reasons that mean the run was stopped, not that it failed.\nconst CANCELLED_REASONS = new Set(['aborted', 'reset']);\n\n/**\n * One run: the work from an input to its answer. It spans several `pi.generation` tasks (run control\n * moves to a new one after every tool round) and their `pi.tool` tasks, so it is tracked per\n * conversation, which runs at most one run at a time.\n */\nexport interface PiRun {\n conversationId: unknown;\n span: Span;\n isolationScope: Scope;\n /** The run's first input submission, which identifies the run in `pi.live`. */\n firstInput?: unknown;\n /** The conversation's provider session id, read by the first phase of the run. */\n sessionId?: string;\n /**\n * The status the run ends with, set while the commit that ends it is in flight. `harness.close()`\n * can begin in that gap, because `wait()` resolves as soon as the commit settles the inputs.\n */\n pendingEnd?: { status?: SpanStatus };\n}\n\n/** Open runs of one Harness, keyed by the pi-durable conversation id. */\nexport interface PiRuns {\n /**\n * Random id of this Harness, prefixed to `gen_ai.conversation.id` until the provider session id of\n * the conversation is known. pi-durable numbers conversations per storage from 1, so the bare id\n * would merge the root conversations of every Harness into one Sentry conversation.\n */\n harnessId: string;\n active: Map<unknown, PiRun>;\n /**\n * Tool calls that created a conversation they own, keyed by that conversation. The child's first\n * run becomes a child of the call while the call's trace is in progress, and otherwise continues\n * that trace with the call as parent. This is how a subagent's run joins the trace of the run that\n * delegated to it.\n */\n owners: Map<unknown, PiOwner>;\n /**\n * Tool calls of running `pi.tool` phases, keyed by task id. Their spans end when the phase ends,\n * after it has committed the result the model receives.\n */\n toolCalls: Map<unknown, PiToolCall[]>;\n}\n\n/** A tool call that created a conversation it owns. */\nexport interface PiOwner {\n /**\n * The call's `execute_tool` span, held weakly: a conversation whose first run never starts must\n * not keep the trace of the call alive.\n */\n span: MaybeWeakRef<Span>;\n /** The `sentry-trace` value of the span, used to continue its trace once that trace has ended. */\n sentryTrace: string;\n /** The `baggage` value of the span, used together with `sentryTrace`. */\n baggage: string | undefined;\n}\n\n/** One `execute()` of a tool. */\nexport interface PiToolCall {\n span: Span;\n callId?: string;\n recordOutputs: boolean;\n /** Set once the span has a status other than ok, so the committed result does not overwrite it. */\n failed?: boolean;\n /** When `execute()` settled, used as the span's end time. */\n endTimestamp?: number;\n /** Set once `execute()` settled. Runs `onSpanEnd` with its result. */\n onSpanEnd?: () => void;\n /** What `execute()` returned, the result of a call that commits no result entry. */\n returned?: PiToolResultMessage;\n}\n\nexport function createRuns(): PiRuns {\n return {\n harnessId: uuid4(),\n active: new Map(),\n owners: new Map(),\n toolCalls: new Map(),\n };\n}\n\nexport function toSentryConversationId(runs: PiRuns, conversationId: unknown): string {\n return runs.active.get(conversationId)?.sessionId ?? `${runs.harnessId}:${String(conversationId)}`;\n}\n\n/**\n * Read the provider session id of the conversation, or `undefined` when pi-durable keeps none.\n *\n * pi-durable 1.0.2 and later keep a UUIDv7 per conversation in the `pi.provider` document, stored with\n * the conversation. Unlike the harness prefix, it stays the same when a Harness opens the storage\n * again, for example after a Durable Object restarts, and it is unique across storages.\n */\nexport async function readProviderSessionId(runtime: PiTaskRuntime, context: unknown): Promise<string | undefined> {\n try {\n const provider = (await runtime.snapshot?.(PROVIDER_DOC, runtime.conversationId, context)) as\n | PiProviderState\n | undefined;\n return typeof provider?.sessionId === 'string' && provider.sessionId ? provider.sessionId : undefined;\n } catch (error) {\n // A later version of the document fails the read. The harness prefix is used then.\n DEBUG_BUILD && debug.warn('[pi-durable] failed to read the provider session id', error);\n return undefined;\n }\n}\n\n/** Start a run of `conversationId`: a new trace, or a child of the tool call that owns the conversation. */\nexport function startRun(conversationId: unknown, runs: PiRuns): PiRun {\n if (runs.active.size >= MAX_TRACKED_PI_RUNS) {\n const oldest = runs.active.keys().next().value;\n runs.active.get(oldest)?.span.end();\n runs.active.delete(oldest);\n }\n\n const owner = runs.owners.get(conversationId);\n runs.owners.delete(conversationId);\n const ownerSpan = derefWeakRef(owner?.span);\n // Under a trace that has ended, the run would be split into one transaction per span when spans are\n // not streamed. Continuing the trace instead also gives the same result whether or not GC ran.\n const parentSpan = ownerSpan && getRootSpan(ownerSpan).isRecording() ? ownerSpan : undefined;\n\n const isolationScope = getDefaultIsolationScope().clone();\n const startRunSpan = (): Span =>\n startInactiveSpan({\n name: 'invoke_agent',\n op: GEN_AI_INVOKE_AGENT,\n ...(parentSpan ? { parentSpan } : {}),\n attributes: {\n [SENTRY_ORIGIN]: PI_DURABLE_ORIGIN,\n [GEN_AI_OPERATION_NAME]: 'invoke_agent',\n [GEN_AI_CONVERSATION_ID]: toSentryConversationId(runs, conversationId),\n },\n });\n const span = withCleanScopes(isolationScope, () => {\n if (parentSpan) {\n return startRunSpan();\n }\n return owner\n ? continueTrace({ sentryTrace: owner.sentryTrace, baggage: owner.baggage }, startRunSpan)\n : startNewTrace(startRunSpan);\n });\n\n const run: PiRun = { conversationId, span, isolationScope };\n runs.active.set(conversationId, run);\n DEBUG_BUILD && debug.log(`[pi-durable] run of conversation ${String(conversationId)} started`);\n return run;\n}\n\nexport function endRun(run: PiRun, runs: PiRuns, status?: SpanStatus): void {\n if (runs.active.get(run.conversationId) !== run) {\n return;\n }\n runs.active.delete(run.conversationId);\n DEBUG_BUILD && debug.log(`[pi-durable] run of conversation ${String(run.conversationId)} ended`, status ?? 'ok');\n if (status) {\n run.span.setStatus(status);\n }\n run.span.end();\n}\n\n/**\n * Watch the generation task's commits for the end of its run.\n *\n * pi-durable keeps run control in the conversation's `pi.live` document: `run` names the task that\n * owns the run and the run's inputs, it moves to the next generation after every tool round, and it\n * is removed, in the same commit that settles the inputs, when the run ends. Every commit that moves\n * or ends a run edits `pi.live` through `tx.doc()`, so reading that draft after the commit's change\n * function returns shows whether the run survived the commit.\n */\nexport function observeRunControl(runtime: PiTaskRuntime, run: PiRun, runs: PiRuns): () => void {\n const commit: PiTaskRuntime['commit'] = runtime.commit.bind(runtime);\n // Replaced on the runtime itself: pi-durable 1.6.0 finds the state it keeps for a runtime by\n // that object, so a phase that gets a Proxy of it faults. The returned function puts `commit`\n // back, as pi-durable can keep the runtime after the phase, and with it the run and its spans.\n runtime.commit = (change: PiCommitChange, context: unknown, ...rest: unknown[]): Promise<void> => {\n let ended = false;\n let settlement: PiSettlement | undefined;\n\n const observedChange: PiCommitChange = async (tx, current) => {\n // A commit can run its change again, so only the attempt that committed counts.\n ended = false;\n settlement = undefined;\n let live: Promise<unknown> | undefined;\n const observedTx = new Proxy(tx, {\n get(target, property) {\n const value = bound(target, property);\n if (typeof value !== 'function') {\n return value;\n }\n if (property === 'doc') {\n return (token: PiDocToken, id: unknown, ...rest: unknown[]) => {\n const draft = value(token, id, ...rest);\n if (token?.definition?.kind === PI_LIVE_DOC_KIND && id === run.conversationId) {\n live = Promise.resolve(draft);\n }\n return draft;\n };\n }\n if (property === 'settleSubmission') {\n return (id: unknown, submissionSettlement: PiSettlement, ...rest: unknown[]) => {\n if (run.firstInput === undefined || id === run.firstInput) {\n settlement = submissionSettlement;\n }\n return value(id, submissionSettlement, ...rest);\n };\n }\n return value;\n },\n });\n\n const result = await change(observedTx, current);\n const draft = (await live) as PiLiveState | undefined;\n if (draft) {\n const firstInput = draft.run?.inputs?.[0];\n if (firstInput === undefined) {\n ended = true;\n } else if (run.firstInput === undefined) {\n run.firstInput = firstInput;\n } else if (firstInput !== run.firstInput) {\n // The run ended and a queued input started the next one in the same commit.\n ended = true;\n }\n }\n run.pendingEnd = ended ? { status: toRunStatus(settlement) } : undefined;\n return result;\n };\n\n return commit(observedChange, context, ...rest).then(\n () => {\n if (ended) {\n endRun(run, runs, toRunStatus(settlement));\n }\n },\n error => {\n run.pendingEnd = undefined;\n throw error;\n },\n );\n };\n\n return () => {\n runtime.commit = commit;\n };\n}\n\nfunction toRunStatus(settlement: PiSettlement | undefined): SpanStatus | undefined {\n if (settlement?.status !== 'unanswered') {\n return undefined;\n }\n const reason = settlement.reason ?? 'internal_error';\n return { code: SPAN_STATUS_ERROR, message: CANCELLED_REASONS.has(reason) ? 'cancelled' : reason };\n}\n"],"mappings":";;;;;;;;AA8BA,MAAM,eAAe,EACnB,YAAY;CAAE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AO,IAAI,gBAC7D,OAAO,QAAQ,QAAQ,KAAK;KAE9B,OAAO;IACT;IAEF,IAAI,aAAa,oBACf,QAAQ,IAAa,sBAAoC,GAAG,SAAoB;KAC9E,IAAI,IAAI,eAAe,KAAA,KAAa,OAAO,IAAI,YAC7C,aAAa;KAEf,OAAO,MAAM,IAAI,sBAAsB,GAAG,IAAI;IAChD;IAEF,OAAO;GACT,EACF,CAEqC,GAAG,OAAO;GAC/C,MAAM,QAAS,MAAM;GACrB,IAAI,OAAO;IACT,MAAM,aAAa,MAAM,KAAK,SAAS;IACvC,IAAI,eAAe,KAAA,GACjB,QAAQ;SACH,IAAI,IAAI,eAAe,KAAA,GAC5B,IAAI,aAAa;SACZ,IAAI,eAAe,IAAI,YAE5B,QAAQ;GAEZ;GACA,IAAI,aAAa,QAAQ,EAAE,QAAQ,YAAY,UAAU,EAAE,IAAI,KAAA;GAC/D,OAAO;EACT;EAEA,OAAO,OAAO,gBAAgB,SAAS,GAAG,IAAI,CAAC,CAAC,WACxC;GACJ,IAAI,OACF,OAAO,KAAK,MAAM,YAAY,UAAU,CAAC;EAE7C,IACA,UAAS;GACP,IAAI,aAAa,KAAA;GACjB,MAAM;EACR,CACF;CACF;CAEA,aAAa;EACX,QAAQ,SAAS;CACnB;AACF;AAEA,SAAS,YAAY,YAA8D;CACjF,IAAI,YAAY,WAAW,cACzB;CAEF,MAAM,SAAS,WAAW,UAAU;CACpC,OAAO;EAAE,MAAM;EAAmB,SAAS,kBAAkB,IAAI,MAAM,IAAI,cAAc;CAAO;AAClG"}
@@ -22,35 +22,38 @@ function markBuiltInTool(tool) {
22
22
  /**
23
23
  * Prepare the runtime of a `pi.tool` phase. The tool task resolves the called tool from its agent,
24
24
  * so the runtime hands out traced tools, and it collects the result entries the phase commits.
25
- * `finish` ends the phase's tool spans with the result the model receives, which pi-durable builds
26
- * after `execute()` returns: from `api.output()`, through `afterTool` hooks and output limits.
25
+ * The returned function ends the phase's tool spans with the result the model receives, which
26
+ * pi-durable builds after `execute()` returns: from `api.output()`, through `afterTool` hooks and
27
+ * output limits.
27
28
  */
28
- function instrumentToolPhase(runtime, runs, wrapTool) {
29
+ function instrumentToolPhase(runtime, runs, wrapTool, isNested) {
29
30
  const results = /* @__PURE__ */ new Map();
30
31
  runs.toolCalls.set(runtime.taskId, []);
31
- const agent = (context) => runtime.agent(context).then((resolved) => resolved?.tools ? {
32
+ const agent = runtime.agent.bind(runtime);
33
+ const commit = runtime.commit.bind(runtime);
34
+ runtime.agent = (context) => agent(context).then((resolved) => resolved?.tools ? {
32
35
  ...resolved,
33
- tools: resolved.tools.map(wrapTool)
36
+ tools: resolved.tools.map(wrapTool),
37
+ ...resolved.callable ? { callable: resolved.callable.map(wrapTool) } : {}
34
38
  } : resolved);
35
- const commit = (change, context) => {
39
+ runtime.commit = (change, context, ...rest) => {
36
40
  let committed = [];
37
41
  const observedChange = (tx, current) => {
38
42
  committed = [];
39
43
  return change(observeToolResultEntries(tx, committed), current);
40
44
  };
41
- return runtime.commit(observedChange, context).then(() => {
45
+ return commit(observedChange, context, ...rest).then(() => {
42
46
  for (const message of committed) results.set(message.toolCallId, message);
43
47
  });
44
48
  };
45
- return {
46
- runtime: new Proxy(runtime, { get(target, property) {
47
- if (property === "agent") return agent;
48
- return property === "commit" ? commit : bound(target, property);
49
- } }),
50
- finish: () => {
51
- for (const call of runs.toolCalls.get(runtime.taskId) ?? []) finishToolCall(call, call.callId !== void 0 ? results.get(call.callId) : void 0);
52
- runs.toolCalls.delete(runtime.taskId);
49
+ return () => {
50
+ runtime.agent = agent;
51
+ runtime.commit = commit;
52
+ for (const call of runs.toolCalls.get(runtime.taskId) ?? []) {
53
+ const committed = call.callId !== void 0 ? results.get(call.callId) : void 0;
54
+ finishToolCall(call, isNested ? call.returned : committed);
53
55
  }
56
+ runs.toolCalls.delete(runtime.taskId);
54
57
  };
55
58
  }
56
59
  /** Wrap a tool so each call gets a `gen_ai.execute_tool` span. */
@@ -90,10 +93,11 @@ function instrumentTool(tool, runs, options) {
90
93
  const result = await tool.execute(args, trackOwnedConversations(api, span, runs), context);
91
94
  call.endTimestamp = timestampInSeconds();
92
95
  call.onSpanEnd = () => runGenAiSpanEnd(options, span, toolCall, { response: result });
93
- if (!calls) finishToolCall(call, {
96
+ call.returned = {
94
97
  content: result?.output ?? result?.content,
95
98
  isError: result?.isError
96
- });
99
+ };
100
+ if (!calls) finishToolCall(call, call.returned);
97
101
  return result;
98
102
  } catch (error) {
99
103
  call.endTimestamp = timestampInSeconds();
@@ -1 +1 @@
1
- {"version":3,"file":"tools.js","names":[],"sources":["../../../../src/ai/pi-durable/tools.ts"],"sourcesContent":["import type { Span } from '@sentry/core';\nimport {\n captureException,\n isObjectLike,\n makeWeakRef,\n SPAN_STATUS_ERROR,\n spanToBaggageHeader,\n spanToTraceHeader,\n startSpanManual,\n stringify,\n timestampInSeconds,\n} from '@sentry/core';\nimport {\n GEN_AI_CONVERSATION_ID,\n GEN_AI_OPERATION_NAME,\n GEN_AI_TOOL_CALL_ARGUMENTS,\n GEN_AI_TOOL_CALL_RESULT,\n GEN_AI_TOOL_DESCRIPTION,\n GEN_AI_TOOL_NAME,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { GEN_AI_EXECUTE_TOOL } from '@sentry/conventions/op';\nimport { GEN_AI_TOOL_CALL_ID_ATTRIBUTE } from '../core/gen-ai-attributes';\nimport type { GenAiSpanHooks } from '../core/span-hooks';\nimport { runGenAiSpanEnd, runGenAiSpanStart } from '../core/span-hooks';\nimport type { GenAiCallOptions } from '../core/utils';\nimport { resolveGenAiCallRecording } from '../core/utils';\nimport { piAiContentToString } from '../pi-ai/messages';\nimport { MAX_TRACKED_PI_RUNS, PI_DURABLE_ORIGIN, PI_TOOL_RESULT_ENTRY_KIND } from './constants';\nimport type { PiRuns, PiToolCall } from './runs';\nimport { toSentryConversationId } from './runs';\nimport type {\n PiAgent,\n PiCommitChange,\n PiDurableCallInfo,\n PiEntryToken,\n PiTaskRuntime,\n PiTool,\n PiToolExecutionApi,\n PiToolExecutionResult,\n PiToolResultMessage,\n} from './types';\nimport { bound } from './utils';\n\n/**\n * The tools pi-durable's `createBashTool`, `createReadTool`, `createEditTool` and `createWriteTool`\n * factories return. They throw to report expected failures to the model, such as a command that\n * exits non-zero, so their throws are not captured. Filled by the integration from the factories'\n * channels, which also covers the tools an app registers in an extension of its own.\n */\nconst BUILT_IN_TOOLS = new WeakSet<object>();\n\nexport function markBuiltInTool(tool: unknown): void {\n if (isObjectLike(tool)) {\n BUILT_IN_TOOLS.add(tool);\n }\n}\n\n/**\n * Prepare the runtime of a `pi.tool` phase. The tool task resolves the called tool from its agent,\n * so the runtime hands out traced tools, and it collects the result entries the phase commits.\n * `finish` ends the phase's tool spans with the result the model receives, which pi-durable builds\n * after `execute()` returns: from `api.output()`, through `afterTool` hooks and output limits.\n */\nexport function instrumentToolPhase(\n runtime: PiTaskRuntime,\n runs: PiRuns,\n wrapTool: (tool: PiTool) => PiTool,\n): { runtime: PiTaskRuntime; finish: () => void } {\n const results = new Map<unknown, PiToolResultMessage>();\n runs.toolCalls.set(runtime.taskId, []);\n\n const agent = (context: unknown): Promise<PiAgent> =>\n runtime\n .agent(context)\n .then(resolved => (resolved?.tools ? { ...resolved, tools: resolved.tools.map(wrapTool) } : resolved));\n\n const commit = (change: PiCommitChange, context: unknown): Promise<void> => {\n let committed: PiToolResultMessage[] = [];\n const observedChange: PiCommitChange = (tx, current) => {\n // A commit can run its change again, so only the attempt that committed counts.\n committed = [];\n return change(observeToolResultEntries(tx, committed), current);\n };\n return runtime.commit(observedChange, context).then(() => {\n for (const message of committed) {\n results.set(message.toolCallId, message);\n }\n });\n };\n\n return {\n runtime: new Proxy(runtime, {\n get(target, property) {\n if (property === 'agent') {\n return agent;\n }\n return property === 'commit' ? commit : bound(target, property);\n },\n }),\n finish: () => {\n for (const call of runs.toolCalls.get(runtime.taskId) ?? []) {\n finishToolCall(call, call.callId !== undefined ? results.get(call.callId) : undefined);\n }\n runs.toolCalls.delete(runtime.taskId);\n },\n };\n}\n\n/** Wrap a tool so each call gets a `gen_ai.execute_tool` span. */\nexport function instrumentTool(\n tool: PiTool,\n runs: PiRuns,\n options: GenAiCallOptions<PiDurableCallInfo> & GenAiSpanHooks<PiDurableCallInfo, PiToolExecutionResult>,\n): PiTool {\n const execute = (args: unknown, api: PiToolExecutionApi, context: unknown): Promise<unknown> => {\n const toolCall: PiDurableCallInfo = { operation: 'execute_tool', tool, args, api, context };\n const { recordInputs, recordOutputs } = resolveGenAiCallRecording(options, toolCall);\n const phaseCalls = runs.toolCalls.get(api?.taskId);\n // A tool that runs another tool of its agent passes its own `api` on, so the inner call shares\n // the call id. Only the outer call gets the committed result; the inner one ends with its own.\n const calls = phaseCalls?.some(call => call.callId !== undefined && call.callId === api?.callId)\n ? undefined\n : phaseCalls;\n\n return startSpanManual(\n {\n name: `execute_tool ${tool.name}`,\n op: GEN_AI_EXECUTE_TOOL,\n attributes: {\n [SENTRY_ORIGIN]: PI_DURABLE_ORIGIN,\n [GEN_AI_OPERATION_NAME]: 'execute_tool',\n [GEN_AI_TOOL_NAME]: tool.name,\n [GEN_AI_TOOL_DESCRIPTION]: tool.description,\n [GEN_AI_TOOL_CALL_ID_ATTRIBUTE]: api?.callId,\n ...(api?.conversationId !== undefined\n ? { [GEN_AI_CONVERSATION_ID]: toSentryConversationId(runs, api.conversationId) }\n : {}),\n ...(recordInputs && args !== undefined ? { [GEN_AI_TOOL_CALL_ARGUMENTS]: stringify(args) } : {}),\n },\n },\n async span => {\n const call: PiToolCall = { span, callId: api?.callId, recordOutputs };\n calls?.push(call);\n runGenAiSpanStart(options, span, toolCall);\n try {\n const result = await tool.execute(args, trackOwnedConversations(api, span, runs), context);\n call.endTimestamp = timestampInSeconds();\n call.onSpanEnd = () => runGenAiSpanEnd(options, span, toolCall, { response: result });\n if (!calls) {\n // No result entry follows a call outside a tool task phase, nor a nested call.\n finishToolCall(call, { content: result?.output ?? result?.content, isError: result?.isError });\n }\n return result;\n } catch (error) {\n call.endTimestamp = timestampInSeconds();\n call.failed = true;\n call.onSpanEnd = () => runGenAiSpanEnd(options, span, toolCall, { error });\n // pi-durable turns the throw into an error result for the model, so the app never gets a\n // chance to handle it. An aborted call is not a failure.\n if ((context as { abortSignal?: AbortSignal } | undefined)?.abortSignal?.aborted) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'cancelled' });\n } else {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n if (!BUILT_IN_TOOLS.has(tool)) {\n captureException(error, { mechanism: { handled: false, type: PI_DURABLE_ORIGIN } });\n }\n }\n if (!calls) {\n call.onSpanEnd();\n span.end(call.endTimestamp);\n }\n throw error;\n }\n },\n );\n };\n\n // The proxy's target is an empty object with the tool as prototype, not the tool itself, so a\n // frozen tool does not break the proxy invariants. Members are read bound to the tool, so a\n // method that reads a private field works.\n return new Proxy(Object.create(tool) as PiTool, {\n get(_target, property) {\n return property === 'execute' ? execute : bound(tool, property);\n },\n });\n}\n\nfunction finishToolCall(call: PiToolCall, message: PiToolResultMessage | undefined): void {\n if (message) {\n const result = call.recordOutputs ? piAiContentToString(message.content) : undefined;\n if (result !== undefined) {\n call.span.setAttribute(GEN_AI_TOOL_CALL_RESULT, result);\n }\n if (message.isError && !call.failed) {\n call.span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n }\n }\n call.onSpanEnd?.();\n call.span.end(call.endTimestamp);\n}\n\nfunction observeToolResultEntries(tx: object, committed: PiToolResultMessage[]): object {\n return new Proxy(tx, {\n get(target, property) {\n const value = bound(target, property);\n if (property !== 'appendEntry' || typeof value !== 'function') {\n return value;\n }\n return (\n token: PiEntryToken,\n conversationId: unknown,\n draft: { model?: unknown[] } | undefined,\n ...rest: unknown[]\n ) => {\n const message = token?.kind === PI_TOOL_RESULT_ENTRY_KIND ? draft?.model?.[0] : undefined;\n if (isObjectLike(message)) {\n committed.push(message);\n }\n return value(token, conversationId, draft, ...rest);\n };\n },\n });\n}\n\n/**\n * Record the conversations a tool call creates for itself, the subagent pattern: `api.commit()` with\n * `tx.createConversation()` or `tx.forkConversation()` and `ownership: { kind: 'task', taskId: api.taskId }`.\n */\nfunction trackOwnedConversations(api: PiToolExecutionApi, span: Span, runs: PiRuns): PiToolExecutionApi {\n if (typeof api?.commit !== 'function') {\n return api;\n }\n const commit = api.commit.bind(api);\n\n const trackCreatedConversations = (tx: object): object =>\n new Proxy(tx, {\n get(target, property) {\n const value = bound(target, property);\n if ((property !== 'createConversation' && property !== 'forkConversation') || typeof value !== 'function') {\n return value;\n }\n return async (...args: unknown[]) => {\n const record = (await value(...args)) as { id?: unknown } | undefined;\n const ownership = args.find(\n (arg): arg is { ownership: { kind?: string } } => isObjectLike(arg) && isObjectLike(arg.ownership),\n )?.ownership;\n if (ownership?.kind === 'task' && record?.id !== undefined) {\n if (runs.owners.size >= MAX_TRACKED_PI_RUNS) {\n runs.owners.delete(runs.owners.keys().next().value);\n }\n runs.owners.set(record.id, {\n span: makeWeakRef(span),\n sentryTrace: spanToTraceHeader(span),\n baggage: spanToBaggageHeader(span),\n });\n }\n return record;\n };\n },\n });\n\n return new Proxy(api, {\n get(target, property) {\n if (property !== 'commit') {\n return bound(target, property);\n }\n return (change: (tx: object) => unknown, context: unknown) =>\n commit((tx: object) => change(trackCreatedConversations(tx)), context);\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAkDA,MAAM,iCAAiB,IAAI,QAAgB;AAE3C,SAAgB,gBAAgB,MAAqB;CACnD,IAAI,aAAa,IAAI,GACnB,eAAe,IAAI,IAAI;AAE3B;;;;;;;AAQA,SAAgB,oBACd,SACA,MACA,UACgD;CAChD,MAAM,0BAAU,IAAI,IAAkC;CACtD,KAAK,UAAU,IAAI,QAAQ,QAAQ,CAAC,CAAC;CAErC,MAAM,SAAS,YACb,QACG,MAAM,OAAO,CAAC,CACd,MAAK,aAAa,UAAU,QAAQ;EAAE,GAAG;EAAU,OAAO,SAAS,MAAM,IAA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AE,UAAA,EACY,SAAS,UAAU,QAAQ,OAAO,KAAA,GAAW;IAC1D,IAAI,KAAK,OAAO,QAAA,KACd,KAAK,OAAO,OAAO,KAAK,OAAO,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,KAAK;IAEpD,KAAK,OAAO,IAAI,OAAO,IAAI;KACzB,MAAM,YAAY,IAAI;KACtB,aAAa,kBAAkB,IAAI;KACnC,SAAS,oBAAoB,IAAI;IACnC,CAAC;GACH;GACA,OAAO;EACT;CACF,EACF,CAAC;CAEH,OAAO,IAAI,MAAM,KAAK,EACpB,IAAI,QAAQ,UAAU;EACpB,IAAI,aAAa,UACf,OAAO,MAAM,QAAQ,QAAQ;EAE/B,QAAQ,QAAiC,YACvC,QAAQ,OAAe,OAAO,0BAA0B,EAAE,CAAC,GAAG,OAAO;CACzE,EACF,CAAC;AACH"}
1
+ {"version":3,"file":"tools.js","names":[],"sources":["../../../../src/ai/pi-durable/tools.ts"],"sourcesContent":["import type { Span } from '@sentry/core';\nimport {\n captureException,\n isObjectLike,\n makeWeakRef,\n SPAN_STATUS_ERROR,\n spanToBaggageHeader,\n spanToTraceHeader,\n startSpanManual,\n stringify,\n timestampInSeconds,\n} from '@sentry/core';\nimport {\n GEN_AI_CONVERSATION_ID,\n GEN_AI_OPERATION_NAME,\n GEN_AI_TOOL_CALL_ARGUMENTS,\n GEN_AI_TOOL_CALL_RESULT,\n GEN_AI_TOOL_DESCRIPTION,\n GEN_AI_TOOL_NAME,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { GEN_AI_EXECUTE_TOOL } from '@sentry/conventions/op';\nimport { GEN_AI_TOOL_CALL_ID_ATTRIBUTE } from '../core/gen-ai-attributes';\nimport type { GenAiSpanHooks } from '../core/span-hooks';\nimport { runGenAiSpanEnd, runGenAiSpanStart } from '../core/span-hooks';\nimport type { GenAiCallOptions } from '../core/utils';\nimport { resolveGenAiCallRecording } from '../core/utils';\nimport { piAiContentToString } from '../pi-ai/messages';\nimport { MAX_TRACKED_PI_RUNS, PI_DURABLE_ORIGIN, PI_TOOL_RESULT_ENTRY_KIND } from './constants';\nimport type { PiRuns, PiToolCall } from './runs';\nimport { toSentryConversationId } from './runs';\nimport type {\n PiAgent,\n PiCommitChange,\n PiDurableCallInfo,\n PiEntryToken,\n PiTaskRuntime,\n PiTool,\n PiToolExecutionApi,\n PiToolExecutionResult,\n PiToolResultMessage,\n} from './types';\nimport { bound } from './utils';\n\n/**\n * The tools pi-durable's `createBashTool`, `createReadTool`, `createEditTool` and `createWriteTool`\n * factories return. They throw to report expected failures to the model, such as a command that\n * exits non-zero, so their throws are not captured. Filled by the integration from the factories'\n * channels, which also covers the tools an app registers in an extension of its own.\n */\nconst BUILT_IN_TOOLS = new WeakSet<object>();\n\nexport function markBuiltInTool(tool: unknown): void {\n if (isObjectLike(tool)) {\n BUILT_IN_TOOLS.add(tool);\n }\n}\n\n/**\n * Prepare the runtime of a `pi.tool` phase. The tool task resolves the called tool from its agent,\n * so the runtime hands out traced tools, and it collects the result entries the phase commits.\n * The returned function ends the phase's tool spans with the result the model receives, which\n * pi-durable builds after `execute()` returns: from `api.output()`, through `afterTool` hooks and\n * output limits.\n */\nexport function instrumentToolPhase(\n runtime: PiTaskRuntime,\n runs: PiRuns,\n wrapTool: (tool: PiTool) => PiTool,\n isNested: boolean,\n): () => void {\n const results = new Map<unknown, PiToolResultMessage>();\n runs.toolCalls.set(runtime.taskId, []);\n\n const agent: PiTaskRuntime['agent'] = runtime.agent.bind(runtime);\n const commit: PiTaskRuntime['commit'] = runtime.commit.bind(runtime);\n\n // Replaced on the runtime itself and put back when the phase ends, see `observeRunControl`.\n runtime.agent = (context: unknown): Promise<PiAgent> =>\n agent(context).then(resolved =>\n resolved?.tools\n ? {\n ...resolved,\n tools: resolved.tools.map(wrapTool),\n // A call made with `api.executeTool()` resolves its tool among these.\n ...(resolved.callable ? { callable: resolved.callable.map(wrapTool) } : {}),\n }\n : resolved,\n );\n\n runtime.commit = (change: PiCommitChange, context: unknown, ...rest: unknown[]): Promise<void> => {\n let committed: PiToolResultMessage[] = [];\n const observedChange: PiCommitChange = (tx, current) => {\n // A commit can run its change again, so only the attempt that committed counts.\n committed = [];\n return change(observeToolResultEntries(tx, committed), current);\n };\n return commit(observedChange, context, ...rest).then(() => {\n for (const message of committed) {\n results.set(message.toolCallId, message);\n }\n });\n };\n\n return () => {\n runtime.agent = agent;\n runtime.commit = commit;\n for (const call of runs.toolCalls.get(runtime.taskId) ?? []) {\n // A nested call gives its result to the calling tool and commits no result entry.\n const committed = call.callId !== undefined ? results.get(call.callId) : undefined;\n finishToolCall(call, isNested ? call.returned : committed);\n }\n runs.toolCalls.delete(runtime.taskId);\n };\n}\n\n/** Wrap a tool so each call gets a `gen_ai.execute_tool` span. */\nexport function instrumentTool(\n tool: PiTool,\n runs: PiRuns,\n options: GenAiCallOptions<PiDurableCallInfo> & GenAiSpanHooks<PiDurableCallInfo, PiToolExecutionResult>,\n): PiTool {\n const execute = (args: unknown, api: PiToolExecutionApi, context: unknown): Promise<unknown> => {\n const toolCall: PiDurableCallInfo = { operation: 'execute_tool', tool, args, api, context };\n const { recordInputs, recordOutputs } = resolveGenAiCallRecording(options, toolCall);\n const phaseCalls = runs.toolCalls.get(api?.taskId);\n // A tool that runs another tool of its agent passes its own `api` on, so the inner call shares\n // the call id. Only the outer call gets the committed result; the inner one ends with its own.\n const calls = phaseCalls?.some(call => call.callId !== undefined && call.callId === api?.callId)\n ? undefined\n : phaseCalls;\n\n return startSpanManual(\n {\n name: `execute_tool ${tool.name}`,\n op: GEN_AI_EXECUTE_TOOL,\n attributes: {\n [SENTRY_ORIGIN]: PI_DURABLE_ORIGIN,\n [GEN_AI_OPERATION_NAME]: 'execute_tool',\n [GEN_AI_TOOL_NAME]: tool.name,\n [GEN_AI_TOOL_DESCRIPTION]: tool.description,\n [GEN_AI_TOOL_CALL_ID_ATTRIBUTE]: api?.callId,\n ...(api?.conversationId !== undefined\n ? { [GEN_AI_CONVERSATION_ID]: toSentryConversationId(runs, api.conversationId) }\n : {}),\n ...(recordInputs && args !== undefined ? { [GEN_AI_TOOL_CALL_ARGUMENTS]: stringify(args) } : {}),\n },\n },\n async span => {\n const call: PiToolCall = { span, callId: api?.callId, recordOutputs };\n calls?.push(call);\n runGenAiSpanStart(options, span, toolCall);\n try {\n const result = await tool.execute(args, trackOwnedConversations(api, span, runs), context);\n call.endTimestamp = timestampInSeconds();\n call.onSpanEnd = () => runGenAiSpanEnd(options, span, toolCall, { response: result });\n call.returned = { content: result?.output ?? result?.content, isError: result?.isError };\n if (!calls) {\n // No result entry follows a call outside a tool task phase, nor a call that got the api of another call.\n finishToolCall(call, call.returned);\n }\n return result;\n } catch (error) {\n call.endTimestamp = timestampInSeconds();\n call.failed = true;\n call.onSpanEnd = () => runGenAiSpanEnd(options, span, toolCall, { error });\n // pi-durable turns the throw into an error result for the model, so the app never gets a\n // chance to handle it. An aborted call is not a failure.\n if ((context as { abortSignal?: AbortSignal } | undefined)?.abortSignal?.aborted) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'cancelled' });\n } else {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n if (!BUILT_IN_TOOLS.has(tool)) {\n captureException(error, { mechanism: { handled: false, type: PI_DURABLE_ORIGIN } });\n }\n }\n if (!calls) {\n call.onSpanEnd();\n span.end(call.endTimestamp);\n }\n throw error;\n }\n },\n );\n };\n\n // The proxy's target is an empty object with the tool as prototype, not the tool itself, so a\n // frozen tool does not break the proxy invariants. Members are read bound to the tool, so a\n // method that reads a private field works.\n return new Proxy(Object.create(tool) as PiTool, {\n get(_target, property) {\n return property === 'execute' ? execute : bound(tool, property);\n },\n });\n}\n\nfunction finishToolCall(call: PiToolCall, message: PiToolResultMessage | undefined): void {\n if (message) {\n const result = call.recordOutputs ? piAiContentToString(message.content) : undefined;\n if (result !== undefined) {\n call.span.setAttribute(GEN_AI_TOOL_CALL_RESULT, result);\n }\n if (message.isError && !call.failed) {\n call.span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n }\n }\n call.onSpanEnd?.();\n call.span.end(call.endTimestamp);\n}\n\nfunction observeToolResultEntries(tx: object, committed: PiToolResultMessage[]): object {\n return new Proxy(tx, {\n get(target, property) {\n const value = bound(target, property);\n if (property !== 'appendEntry' || typeof value !== 'function') {\n return value;\n }\n return (\n token: PiEntryToken,\n conversationId: unknown,\n draft: { model?: unknown[] } | undefined,\n ...rest: unknown[]\n ) => {\n const message = token?.kind === PI_TOOL_RESULT_ENTRY_KIND ? draft?.model?.[0] : undefined;\n if (isObjectLike(message)) {\n committed.push(message);\n }\n return value(token, conversationId, draft, ...rest);\n };\n },\n });\n}\n\n/**\n * Record the conversations a tool call creates for itself, the subagent pattern: `api.commit()` with\n * `tx.createConversation()` or `tx.forkConversation()` and `ownership: { kind: 'task', taskId: api.taskId }`.\n */\nfunction trackOwnedConversations(api: PiToolExecutionApi, span: Span, runs: PiRuns): PiToolExecutionApi {\n if (typeof api?.commit !== 'function') {\n return api;\n }\n const commit = api.commit.bind(api);\n\n const trackCreatedConversations = (tx: object): object =>\n new Proxy(tx, {\n get(target, property) {\n const value = bound(target, property);\n if ((property !== 'createConversation' && property !== 'forkConversation') || typeof value !== 'function') {\n return value;\n }\n return async (...args: unknown[]) => {\n const record = (await value(...args)) as { id?: unknown } | undefined;\n const ownership = args.find(\n (arg): arg is { ownership: { kind?: string } } => isObjectLike(arg) && isObjectLike(arg.ownership),\n )?.ownership;\n if (ownership?.kind === 'task' && record?.id !== undefined) {\n if (runs.owners.size >= MAX_TRACKED_PI_RUNS) {\n runs.owners.delete(runs.owners.keys().next().value);\n }\n runs.owners.set(record.id, {\n span: makeWeakRef(span),\n sentryTrace: spanToTraceHeader(span),\n baggage: spanToBaggageHeader(span),\n });\n }\n return record;\n };\n },\n });\n\n return new Proxy(api, {\n get(target, property) {\n if (property !== 'commit') {\n return bound(target, property);\n }\n return (change: (tx: object) => unknown, context: unknown) =>\n commit((tx: object) => change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U,KAAK,OAAO;GAExB,OAAO,MAAM,OAAO,gBAAgB,OAAO,GAAG,IAAI;EACpD;CACF,EACF,CAAC;AACH;;;;;AAMA,SAAS,wBAAwB,KAAyB,MAAY,MAAkC;CACtG,IAAI,OAAO,KAAK,WAAW,YACzB,OAAO;CAET,MAAM,SAAS,IAAI,OAAO,KAAK,GAAG;CAElC,MAAM,6BAA6B,OACjC,IAAI,MAAM,IAAI,EACZ,IAAI,QAAQ,UAAU;EACpB,MAAM,QAAQ,MAAM,QAAQ,QAAQ;EACpC,IAAK,aAAa,wBAAwB,aAAa,sBAAuB,OAAO,UAAU,YAC7F,OAAO;EAET,OAAO,OAAO,GAAG,SAAoB;GACnC,MAAM,SAAU,MAAM,MAAM,GAAG,IAAI;GAInC,KAHkB,KAAK,MACpB,QAAiD,aAAa,GAAG,KAAK,aAAa,IAAI,SAAS,CACnG,CAAC,EAAE,UAAA,EACY,SAAS,UAAU,QAAQ,OAAO,KAAA,GAAW;IAC1D,IAAI,KAAK,OAAO,QAAA,KACd,KAAK,OAAO,OAAO,KAAK,OAAO,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,KAAK;IAEpD,KAAK,OAAO,IAAI,OAAO,IAAI;KACzB,MAAM,YAAY,IAAI;KACtB,aAAa,kBAAkB,IAAI;KACnC,SAAS,oBAAoB,IAAI;IACnC,CAAC;GACH;GACA,OAAO;EACT;CACF,EACF,CAAC;CAEH,OAAO,IAAI,MAAM,KAAK,EACpB,IAAI,QAAQ,UAAU;EACpB,IAAI,aAAa,UACf,OAAO,MAAM,QAAQ,QAAQ;EAE/B,QAAQ,QAAiC,YACvC,QAAQ,OAAe,OAAO,0BAA0B,EAAE,CAAC,GAAG,OAAO;CACzE,EACF,CAAC;AACH"}
@@ -39,7 +39,7 @@ import { cron } from "./cron/index.js";
39
39
  import { BullMQTelemetry } from "./integrations/bullmq/index.js";
40
40
  import { googleGenAIIntegration } from "./integrations/google-genai.js";
41
41
  import { graphqlIntegration } from "./integrations/graphql/index.js";
42
- import { hapiIntegration } from "./integrations/hapi/index.js";
42
+ import { hapiIntegration, setupHapiErrorHandler } from "./integrations/hapi/index.js";
43
43
  import "./integrations/hono/index.js";
44
44
  import { koaIntegration } from "./integrations/koa/index.js";
45
45
  import { honoIntegration, honoMiddleware } from "./integrations/hono/honoIntegration.js";
@@ -72,6 +72,7 @@ import { openAIIntegration } from "./integrations/openai.js";
72
72
  import { postgresIntegration } from "./integrations/pg.js";
73
73
  import { postgresJsIntegration } from "./integrations/postgresjs/index.js";
74
74
  import { neonIntegration } from "./integrations/neon.js";
75
+ import { clickhouseIntegration } from "./integrations/clickhouse.js";
75
76
  import { tediousIntegration } from "./integrations/tedious.js";
76
77
  import { vercelAIIntegration } from "./integrations/vercel-ai/index.js";
77
78
  import { expressIntegration } from "./integrations/express/index.js";
@@ -84,6 +85,6 @@ import { getErrorIntegrations, getTracingIntegrations } from "./integrations/ind
84
85
  * @deprecated This is a temporary export to avoid breaking changes. It will be removed in the next major version.
85
86
  */
86
87
  const attachHapiErrorHandler = attachHapiErrorHandler$1;
87
- export { BullMQTelemetry, SentryMastraExporter, cronExpressionToMonitorConfig as _INTERNAL_cronExpressionToMonitorConfig, instrumentTunnelServer as _INTERNAL_instrumentTunnelServer, instrumentTunnelServers as _INTERNAL_instrumentTunnelServers, amqplibIntegration, anthropicAIIntegration, applyHonoPatches, attachHapiErrorHandler, attachKoaErrorHandler, awsIntegration, bindTracingChannelToSpan, createFlueInstrumentation, createHonoRequestMiddleware, createLangChainCallbackHandler, createSentryWinstonTransport, cron, 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, pinoIntegration, postgresIntegration, postgresJsIntegration, prismaIntegration, redisIntegration, sanitizeSqlQuery, setAsyncLocalStorageAsyncContextStrategy, setHttpServerSpanRouteAttribute, setupExpressErrorHandler, setupFastifyErrorHandler, subscribe as subscribeDiagnosticsChannel, tediousIntegration, togetherAIIntegration, typesafeIntegration, vercelAIIntegration };
88
+ export { BullMQTelemetry, SentryMastraExporter, cronExpressionToMonitorConfig as _INTERNAL_cronExpressionToMonitorConfig, instrumentTunnelServer as _INTERNAL_instrumentTunnelServer, instrumentTunnelServers as _INTERNAL_instrumentTunnelServers, amqplibIntegration, anthropicAIIntegration, applyHonoPatches, attachHapiErrorHandler, attachKoaErrorHandler, awsIntegration, bindTracingChannelToSpan, clickhouseIntegration, createFlueInstrumentation, createHonoRequestMiddleware, createLangChainCallbackHandler, createSentryWinstonTransport, cron, 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, pinoIntegration, postgresIntegration, postgresJsIntegration, prismaIntegration, redisIntegration, sanitizeSqlQuery, setAsyncLocalStorageAsyncContextStrategy, setHttpServerSpanRouteAttribute, setupExpressErrorHandler, setupFastifyErrorHandler, setupHapiErrorHandler, subscribe as subscribeDiagnosticsChannel, tediousIntegration, togetherAIIntegration, typesafeIntegration, vercelAIIntegration };
88
89
 
89
90
  //# 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 { cronExpressionToMonitorConfig as _INTERNAL_cronExpressionToMonitorConfig } from './utils/cronMonitoring';\nexport { cron } from './cron';\nexport { BullMQTelemetry } from './integrations/bullmq';\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 { pinoIntegration } from './integrations/pino';\nexport { createSentryWinstonTransport } from './integrations/winston';\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 { 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 { cronExpressionToMonitorConfig as _INTERNAL_cronExpressionToMonitorConfig } from './utils/cronMonitoring';\nexport { cron } from './cron';\nexport { BullMQTelemetry } from './integrations/bullmq';\nexport { googleGenAIIntegration } from './integrations/google-genai';\nexport { graphqlIntegration } from './integrations/graphql';\nexport {\n hapiIntegration,\n // oxlint-disable-next-line typescript/no-deprecated\n setupHapiErrorHandler,\n} 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 { pinoIntegration } from './integrations/pino';\nexport { createSentryWinstonTransport } from './integrations/winston';\nexport { openAIIntegration } from './integrations/openai';\nexport { postgresIntegration } from './integrations/pg';\nexport { postgresJsIntegration } from './integrations/postgresjs';\nexport { neonIntegration } from './integrations/neon';\nexport { clickhouseIntegration } from './integrations/clickhouse';\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"}
@@ -0,0 +1,31 @@
1
+ import { isIdentifierChar } from "../utils/sql.js";
2
+ // src/integrations/clickhouse-sql.ts
3
+ const NUMBER_RE = /-?(?:0x[\dA-F_]+|0b[01_]+|(?:\d[\d_]*(?:\.[\d_]*)?|\.\d[\d_]*)(?:e[+-]?[\d_]+)?)(?![\w$])/iy;
4
+ const FORMAT_RE = /FORMAT(?!\s*[=<>!])(?:\s|\/\*|--|#)/iy;
5
+ const FORMAT_IDENTIFIER_RE = /(?:\b(?:INTO|TABLE|FROM|JOIN|ON|SELECT|PREWHERE|WHERE|HAVING|QUALIFY|AND|OR|NOT|BY|AS)|[,.=<>(])\s*$/i;
6
+ /**
7
+ * ClickHouse SQL: `"` quotes an identifier as in `standard`, but `\` escapes the next character, `#`
8
+ * starts a line comment, block comments nest, and `$$…$$` heredocs open a literal. Numbers can have
9
+ * `_` separators.
10
+ */
11
+ const CLICKHOUSE_SQL_RULES = {
12
+ hashComments: true,
13
+ nestedComments: true,
14
+ backslashEscapes: true,
15
+ dollarQuote: /\$\w*\$/y,
16
+ matchLiteral(sql, start) {
17
+ if (isIdentifierChar(sql[start - 1]) || sql[start - 1] === "?") return 0;
18
+ NUMBER_RE.lastIndex = start;
19
+ return NUMBER_RE.exec(sql)?.[0].length ?? 0;
20
+ },
21
+ isInlineData(sql, start, out) {
22
+ if (isIdentifierChar(sql[start - 1])) return false;
23
+ FORMAT_RE.lastIndex = start;
24
+ if (!FORMAT_RE.test(sql)) return false;
25
+ const before = out.join("");
26
+ return /^[\s;]*INSERT\b/i.test(before) && !FORMAT_IDENTIFIER_RE.test(before);
27
+ }
28
+ };
29
+ export { CLICKHOUSE_SQL_RULES };
30
+
31
+ //# sourceMappingURL=clickhouse-sql.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"clickhouse-sql.js","names":[],"sources":["../../../src/integrations/clickhouse-sql.ts"],"sourcesContent":["import type { SqlLexerRules } from '../utils/sql';\nimport { isIdentifierChar } from '../utils/sql';\n\nconst NUMBER_RE = /-?(?:0x[\\dA-F_]+|0b[01_]+|(?:\\d[\\d_]*(?:\\.[\\d_]*)?|\\.\\d[\\d_]*)(?:e[+-]?[\\d_]+)?)(?![\\w$])/iy;\n// A comparison operator can follow a column named `format`, but cannot start a format name.\nconst FORMAT_RE = /FORMAT(?!\\s*[=<>!])(?:\\s|\\/\\*|--|#)/iy;\n// After one of these tokens, `format` is a table, column or alias name.\nconst FORMAT_IDENTIFIER_RE =\n /(?:\\b(?:INTO|TABLE|FROM|JOIN|ON|SELECT|PREWHERE|WHERE|HAVING|QUALIFY|AND|OR|NOT|BY|AS)|[,.=<>(])\\s*$/i;\n\n/**\n * ClickHouse SQL: `\"` quotes an identifier as in `standard`, but `\\` escapes the next character, `#`\n * starts a line comment, block comments nest, and `$$…$$` heredocs open a literal. Numbers can have\n * `_` separators.\n */\nexport const CLICKHOUSE_SQL_RULES: SqlLexerRules = {\n hashComments: true,\n nestedComments: true,\n backslashEscapes: true,\n dollarQuote: /\\$\\w*\\$/y,\n matchLiteral(sql, start) {\n if (isIdentifierChar(sql[start - 1]) || sql[start - 1] === '?') {\n return 0;\n }\n NUMBER_RE.lastIndex = start;\n return NUMBER_RE.exec(sql)?.[0].length ?? 0;\n },\n // Everything after the FORMAT clause of an INSERT is inline data. That includes `INSERT ... SELECT`,\n // where the `input()` table function reads that data.\n isInlineData(sql, start, out) {\n if (isIdentifierChar(sql[start - 1])) {\n return false;\n }\n FORMAT_RE.lastIndex = start;\n if (!FORMAT_RE.test(sql)) {\n return false;\n }\n const before = out.join('');\n return /^[\\s;]*INSERT\\b/i.test(before) && !FORMAT_IDENTIFIER_RE.test(before);\n },\n};\n"],"mappings":";;AAGA,MAAM,YAAY;AAElB,MAAM,YAAY;AAElB,MAAM,uBACJ;;;;;;AAOF,MAAa,uBAAsC;CACjD,cAAc;CACd,gBAAgB;CAChB,kBAAkB;CAClB,aAAa;CACb,aAAa,KAAK,OAAO;EACvB,IAAI,iBAAiB,IAAI,QAAQ,EAAE,KAAK,IAAI,QAAQ,OAAO,KACzD,OAAO;EAET,UAAU,YAAY;EACtB,OAAO,UAAU,KAAK,GAAG,CAAC,GAAG,EAAE,CAAC,UAAU;CAC5C;CAGA,aAAa,KAAK,OAAO,KAAK;EAC5B,IAAI,iBAAiB,IAAI,QAAQ,EAAE,GACjC,OAAO;EAET,UAAU,YAAY;EACtB,IAAI,CAAC,UAAU,KAAK,GAAG,GACrB,OAAO;EAET,MAAM,SAAS,IAAI,KAAK,EAAE;EAC1B,OAAO,mBAAmB,KAAK,MAAM,KAAK,CAAC,qBAAqB,KAAK,MAAM;CAC7E;AACF"}
@@ -0,0 +1,88 @@
1
+ import { tracingChannel } from "../utils/diagnosticsChannel.js";
2
+ import { CHANNELS } from "../orchestrion/channels.js";
3
+ import { clickhouseModuleNames } from "../orchestrion/config/clickhouse.js";
4
+ import { invokeOrchestrionInstrumentation } from "../orchestrion/instrumentation.js";
5
+ import { bindTracingChannelToSpan } from "../tracing-channel.js";
6
+ import { getLowCardinalitySqlSpanName, getSqlQueryAttributes } from "../utils/sql.js";
7
+ import { CLICKHOUSE_SQL_RULES } from "./clickhouse-sql.js";
8
+ import { DB_COLLECTION_NAME, DB_NAMESPACE, DB_OPERATION_NAME, DB_QUERY_SUMMARY, DB_SYSTEM_NAME, DB_USER, SENTRY_KIND, SENTRY_OP, SENTRY_ORIGIN, SERVER_ADDRESS, SERVER_PORT } from "@sentry/conventions/attributes";
9
+ import { defineIntegration, startInactiveSpan } from "@sentry/core";
10
+ import { DB } from "@sentry/conventions/op";
11
+ // src/integrations/clickhouse.ts
12
+ const INTEGRATION_NAME = "ClickHouse";
13
+ const ORIGIN = "auto.db.clickhouse";
14
+ const DB_SYSTEM_CLICKHOUSE = "clickhouse";
15
+ const _clickhouseIntegration = (() => {
16
+ return {
17
+ name: INTEGRATION_NAME,
18
+ setup(client) {
19
+ invokeOrchestrionInstrumentation(client, clickhouseModuleNames, instrumentClickhouse, []);
20
+ }
21
+ };
22
+ });
23
+ function instrumentClickhouse() {
24
+ const channels = [
25
+ [CHANNELS.CLICKHOUSE_QUERY, "query"],
26
+ [CHANNELS.CLICKHOUSE_COMMAND, "command"],
27
+ [CHANNELS.CLICKHOUSE_EXEC, "exec"],
28
+ [CHANNELS.CLICKHOUSE_INSERT, "insert"],
29
+ [CHANNELS.CLICKHOUSE_WEB_QUERY, "query"],
30
+ [CHANNELS.CLICKHOUSE_WEB_COMMAND, "command"],
31
+ [CHANNELS.CLICKHOUSE_WEB_EXEC, "exec"],
32
+ [CHANNELS.CLICKHOUSE_WEB_INSERT, "insert"],
33
+ [CHANNELS.CLICKHOUSE_COMMON_QUERY, "query"],
34
+ [CHANNELS.CLICKHOUSE_COMMON_COMMAND, "command"],
35
+ [CHANNELS.CLICKHOUSE_COMMON_EXEC, "exec"],
36
+ [CHANNELS.CLICKHOUSE_COMMON_INSERT, "insert"]
37
+ ];
38
+ for (const [channelName, method] of channels) bindTracingChannelToSpan(tracingChannel(channelName), (data) => {
39
+ const params = data.arguments[0];
40
+ if (method === "insert" && Array.isArray(params?.values) && params.values.length === 0) return;
41
+ const attributes = {
42
+ [SENTRY_OP]: DB,
43
+ [SENTRY_KIND]: "client",
44
+ [SENTRY_ORIGIN]: ORIGIN,
45
+ ...getConnectionAttributes(data.self?.connectionParams, params),
46
+ ...method === "insert" ? getInsertAttributes(params) : getSqlQueryAttributes(typeof params?.query === "string" ? params.query : void 0, CLICKHOUSE_SQL_RULES)
47
+ };
48
+ return startInactiveSpan({
49
+ name: getLowCardinalitySqlSpanName(attributes, DB_SYSTEM_CLICKHOUSE),
50
+ attributes,
51
+ onlyIfParent: true
52
+ });
53
+ });
54
+ }
55
+ function getInsertAttributes(params) {
56
+ const table = typeof params?.table === "string" && params.table ? params.table : void 0;
57
+ return {
58
+ [DB_OPERATION_NAME]: "INSERT",
59
+ [DB_COLLECTION_NAME]: table,
60
+ [DB_QUERY_SUMMARY]: table ? `INSERT ${table}` : "INSERT"
61
+ };
62
+ }
63
+ function getConnectionAttributes(connectionParams, params) {
64
+ const url = connectionParams?.url;
65
+ const user = params?.auth?.username ?? connectionParams?.auth?.username ?? connectionParams?.username;
66
+ return {
67
+ [DB_SYSTEM_NAME]: DB_SYSTEM_CLICKHOUSE,
68
+ [DB_NAMESPACE]: connectionParams?.database,
69
+ [DB_USER]: typeof user === "string" ? user : void 0,
70
+ [SERVER_ADDRESS]: url?.hostname || void 0,
71
+ [SERVER_PORT]: url ? getServerPort(url) : void 0
72
+ };
73
+ }
74
+ function getServerPort(url) {
75
+ if (url.port) return Number(url.port);
76
+ return url.protocol === "https:" ? 443 : 80;
77
+ }
78
+ /**
79
+ * Diagnostics-channel-based `@clickhouse/client` and `@clickhouse/client-web` integration.
80
+ *
81
+ * Subscribes to the channels Sentry's code transform injects into `ClickHouseClient`'s `query`,
82
+ * `command`, `exec` and `insert` methods, and emits a `db` span for each call. Requires the Sentry
83
+ * runtime hook or bundler plugin to be active.
84
+ */
85
+ const clickhouseIntegration = defineIntegration(_clickhouseIntegration);
86
+ export { clickhouseIntegration };
87
+
88
+ //# sourceMappingURL=clickhouse.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"clickhouse.js","names":["diagnosticsChannel.tracingChannel"],"sources":["../../../src/integrations/clickhouse.ts"],"sourcesContent":["import * as diagnosticsChannel from '../utils/diagnosticsChannel';\nimport {\n DB_COLLECTION_NAME,\n DB_NAMESPACE,\n DB_OPERATION_NAME,\n DB_QUERY_SUMMARY,\n DB_SYSTEM_NAME,\n DB_USER,\n SENTRY_KIND,\n SENTRY_OP,\n SENTRY_ORIGIN,\n SERVER_ADDRESS,\n SERVER_PORT,\n} from '@sentry/conventions/attributes';\nimport { DB } from '@sentry/conventions/op';\nimport type { IntegrationFn, SpanAttributes } from '@sentry/core';\nimport { defineIntegration, startInactiveSpan } from '@sentry/core';\nimport type { OrchestrionChannelContext } from '../orchestrion/types';\nimport { CHANNELS } from '../orchestrion/channels';\nimport { clickhouseModuleNames } from '../orchestrion/config/clickhouse';\nimport { invokeOrchestrionInstrumentation } from '../orchestrion/instrumentation';\nimport { bindTracingChannelToSpan } from '../tracing-channel';\nimport { getLowCardinalitySqlSpanName, getSqlQueryAttributes } from '../utils/sql';\nimport { CLICKHOUSE_SQL_RULES } from './clickhouse-sql';\n\nconst INTEGRATION_NAME = 'ClickHouse' as const;\nconst ORIGIN = 'auto.db.clickhouse';\nconst DB_SYSTEM_CLICKHOUSE = 'clickhouse';\n\ntype ClickHouseMethod = 'query' | 'command' | 'exec' | 'insert';\n\n// The parts of `ClickHouseClient`'s `connectionParams` the span reads. `>=1.10` moved the username\n// into `auth` (which can hold an access token instead); older versions keep it at the top level.\ninterface ClickHouseConnectionParams {\n url?: URL;\n database?: string;\n username?: string;\n auth?: { username?: string };\n}\n\ninterface ClickHouseClient {\n connectionParams?: ClickHouseConnectionParams;\n}\n\n// `query`/`command`/`exec` take `{ query }`, `insert` takes `{ table, values }`. Every method accepts a\n// per-call `auth` override.\ninterface ClickHouseParams {\n query?: unknown;\n table?: unknown;\n values?: unknown;\n auth?: { username?: unknown };\n}\n\n/** Context orchestrion attaches to the channels wrapping `ClickHouseClient`'s methods. */\ninterface ClickHouseChannelContext extends OrchestrionChannelContext {\n arguments: [ClickHouseParams?, ...unknown[]];\n self?: ClickHouseClient;\n}\n\nconst _clickhouseIntegration = (() => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n invokeOrchestrionInstrumentation(client, clickhouseModuleNames, instrumentClickhouse, []);\n },\n };\n}) satisfies IntegrationFn;\n\nfunction instrumentClickhouse(): void {\n // The Node and web clients publish the same calls under their own module names. Before 1.23.0,\n // both use `@clickhouse/client-common`.\n const channels: [string, ClickHouseMethod][] = [\n [CHANNELS.CLICKHOUSE_QUERY, 'query'],\n [CHANNELS.CLICKHOUSE_COMMAND, 'command'],\n [CHANNELS.CLICKHOUSE_EXEC, 'exec'],\n [CHANNELS.CLICKHOUSE_INSERT, 'insert'],\n [CHANNELS.CLICKHOUSE_WEB_QUERY, 'query'],\n [CHANNELS.CLICKHOUSE_WEB_COMMAND, 'command'],\n [CHANNELS.CLICKHOUSE_WEB_EXEC, 'exec'],\n [CHANNELS.CLICKHOUSE_WEB_INSERT, 'insert'],\n [CHANNELS.CLICKHOUSE_COMMON_QUERY, 'query'],\n [CHANNELS.CLICKHOUSE_COMMON_COMMAND, 'command'],\n [CHANNELS.CLICKHOUSE_COMMON_EXEC, 'exec'],\n [CHANNELS.CLICKHOUSE_COMMON_INSERT, 'insert'],\n ];\n\n for (const [channelName, method] of channels) {\n // Failed calls only get an error status on the span. The error still rejects to the caller, who\n // decides whether to handle it, so it isn't captured here.\n bindTracingChannelToSpan(diagnosticsChannel.tracingChannel<ClickHouseChannelContext>(channelName), data => {\n const params = data.arguments[0];\n // `insert` with an empty array returns without sending a request.\n if (method === 'insert' && Array.isArray(params?.values) && params.values.length === 0) {\n return undefined;\n }\n\n const attributes: SpanAttributes = {\n [SENTRY_OP]: DB,\n [SENTRY_KIND]: 'client',\n [SENTRY_ORIGIN]: ORIGIN,\n ...getConnectionAttributes(data.self?.connectionParams, params),\n ...(method === 'insert'\n ? getInsertAttributes(params)\n : getSqlQueryAttributes(typeof params?.query === 'string' ? params.query : undefined, CLICKHOUSE_SQL_RULES)),\n };\n\n return startInactiveSpan({\n name: getLowCardinalitySqlSpanName(attributes, DB_SYSTEM_CLICKHOUSE),\n attributes,\n onlyIfParent: true,\n });\n });\n }\n}\n\n// `insert` builds its `INSERT INTO <table> FORMAT <format>` statement internally, so the span is\n// described from the target table instead of a statement.\nfunction getInsertAttributes(params: ClickHouseParams | undefined): SpanAttributes {\n const table = typeof params?.table === 'string' && params.table ? params.table : undefined;\n return {\n [DB_OPERATION_NAME]: 'INSERT',\n [DB_COLLECTION_NAME]: table,\n [DB_QUERY_SUMMARY]: table ? `INSERT ${table}` : 'INSERT',\n };\n}\n\nfunction getConnectionAttributes(\n connectionParams: ClickHouseConnectionParams | undefined,\n params: ClickHouseParams | undefined,\n): SpanAttributes {\n const url = connectionParams?.url;\n const user = params?.auth?.username ?? connectionParams?.auth?.username ?? connectionParams?.username;\n return {\n [DB_SYSTEM_NAME]: DB_SYSTEM_CLICKHOUSE,\n [DB_NAMESPACE]: connectionParams?.database,\n [DB_USER]: typeof user === 'string' ? user : undefined,\n [SERVER_ADDRESS]: url?.hostname || undefined,\n [SERVER_PORT]: url ? getServerPort(url) : undefined,\n };\n}\n\n// The client talks HTTP(S), so a URL without an explicit port uses the protocol's default.\nfunction getServerPort(url: URL): number {\n if (url.port) {\n return Number(url.port);\n }\n return url.protocol === 'https:' ? 443 : 80;\n}\n\n/**\n * Diagnostics-channel-based `@clickhouse/client` and `@clickhouse/client-web` integration.\n *\n * Subscribes to the channels Sentry's code transform injects into `ClickHouseClient`'s `query`,\n * `command`, `exec` and `insert` methods, and emits a `db` span for each call. Requires the Sentry\n * runtime hook or bundler plugin to be active.\n */\nexport const clickhouseIntegration = defineIntegration(_clickhouseIntegration);\n"],"mappings":";;;;;;;;;;;AAyBA,MAAM,mBAAmB;AACzB,MAAM,SAAS;AACf,MAAM,uBAAuB;AAgC7B,MAAM,gCAAgC;CACpC,OAAO;EACL,MAAM;EACN,MAAM,QAAQ;GACZ,iCAAiC,QAAQ,uBAAuB,sBAAsB,CAAC,CAAC;EAC1F;CACF;AACF;AAEA,SAAS,uBAA6B;CAGpC,MAAM,WAAyC;EAC7C,CAAC,SAAS,kBAAkB,OAAO;EACnC,CAAC,SAAS,oBAAoB,SAAS;EACvC,CAAC,SAAS,iBAAiB,MAAM;EACjC,CAAC,SAAS,mBAAmB,QAAQ;EACrC,CAAC,SAAS,sBAAsB,OAAO;EACvC,CAAC,SAAS,wBAAwB,SAAS;EAC3C,CAAC,SAAS,qBAAqB,MAAM;EACrC,CAAC,SAAS,uBAAuB,QAAQ;EACzC,CAAC,SAAS,yBAAyB,OAAO;EAC1C,CAAC,SAAS,2BAA2B,SAAS;EAC9C,CAAC,SAAS,wBAAwB,MAAM;EACxC,CAAC,SAAS,0BAA0B,QAAQ;CAC9C;CAEA,KAAK,MAAM,CAAC,aAAa,WAAW,UAGlC,yBAAyBA,eAA4D,WAAW,IAAG,SAAQ;EACzG,MAAM,SAAS,KAAK,UAAU;EAE9B,IAAI,WAAW,YAAY,MAAM,QAAQ,QAAQ,MAAM,KAAK,OAAO,OAAO,WAAW,GACnF;EAGF,MAAM,aAA6B;IAChC,YAAY;IACZ,cAAc;IACd,gBAAgB;GACjB,GAAG,wBAAwB,KAAK,MAAM,kBAAkB,MAAM;GAC9D,GAAI,WAAW,WACX,oBAAoB,MAAM,IAC1B,sBAAsB,OAAO,QAAQ,UAAU,WAAW,OAAO,QAAQ,KAAA,GAAW,oBAAoB;EAC9G;EAEA,OAAO,kBAAkB;GACvB,MAAM,6BAA6B,YAAY,oBAAoB;GACnE;GACA,cAAc;EAChB,CAAC;CACH,CAAC;AAEL;AAIA,SAAS,oBAAoB,QAAsD;CACjF,MAAM,QAAQ,OAAO,QAAQ,UAAU,YAAY,OAAO,QAAQ,OAAO,QAAQ,KAAA;CACjF,OAAO;GACJ,oBAAoB;GACpB,qBAAqB;GACrB,mBAAmB,QAAQ,UAAU,UAAU;CAClD;AACF;AAEA,SAAS,wBACP,kBACA,QACgB;CAChB,MAAM,MAAM,kBAAkB;CAC9B,MAAM,OAAO,QAAQ,MAAM,YAAY,kBAAkB,MAAM,YAAY,kBAAkB;CAC7F,OAAO;GACJ,iBAAiB;GACjB,eAAe,kBAAkB;GACjC,UAAU,OAAO,SAAS,WAAW,OAAO,KAAA;GAC5C,iBAAiB,KAAK,YAAY,KAAA;GAClC,cAAc,MAAM,cAAc,GAAG,IAAI,KAAA;CAC5C;AACF;AAGA,SAAS,cAAc,KAAkB;CACvC,IAAI,IAAI,MACN,OAAO,OAAO,IAAI,IAAI;CAExB,OAAO,IAAI,aAAa,WAAW,MAAM;AAC3C;;;;;;;;AASA,MAAa,wBAAwB,kBAAkB,sBAAsB"}
@@ -186,6 +186,7 @@ function getSpanForLayer(data, options) {
186
186
  */
187
187
  function getMatchedLayerPath(layer) {
188
188
  if (layer.route) return getLayerPath([layer.route.path]);
189
+ if (layer.rawPath !== void 0) return getLayerPath([layer.rawPath]);
189
190
  return layer.keys?.length ? void 0 : layer.path || void 0;
190
191
  }
191
192
  function getLayerType(layer) {
@@ -1 +1 @@
1
- {"version":3,"file":"instrumentation.js","names":[],"sources":["../../../../src/integrations/express/instrumentation.ts"],"sourcesContent":["import type * as diagnosticsChannel from 'node:diagnostics_channel';\nimport { HTTP_ROUTE, SENTRY_OP, SENTRY_ORIGIN } from '@sentry/conventions/attributes';\nimport { HANDLER, MIDDLEWARE, ROUTER } from '@sentry/conventions/op';\nimport type { Span } from '@sentry/core';\nimport {\n captureException,\n debug,\n getActiveSpan,\n getClient,\n getDefaultIsolationScope,\n getIsolationScope,\n hasSpanStreamingEnabled,\n REQUEST_HANDLER_SPAN_NAME_FALLBACK,\n ROUTER_SPAN_NAME_FALLBACK,\n SPAN_STATUS_ERROR,\n startInactiveSpan,\n stringMatchesSomePattern,\n withActiveSpan,\n} from '@sentry/core';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport { CHANNELS } from '../../orchestrion/channels';\nimport { bindTracingChannelToSpan } from '../../tracing-channel';\nimport {\n getActualMatchedRoute,\n getConstructedRoute,\n getLayerPath,\n getLayerRegisteredPath,\n popLayerPath,\n pushLayerPath,\n setLayerRegisteredPath,\n} from './route';\nimport type {\n ExpressIntegrationOptions,\n ExpressLayer,\n ExpressLayerType,\n ExpressRequest,\n ExpressResponse,\n ExpressShouldHandleError,\n HandleChannelContext,\n MiddlewareError,\n RegistrationChannelContext,\n} from './types';\nimport { defaultShouldHandleError } from './utils';\nimport { isExpressErrorHandled, markExpressErrorHandled } from './error-handled';\nimport { setHttpServerSpanRouteAttribute } from '../../utils/setHttpServerSpanRouteAttribute';\n\nconst ORIGIN = 'auto.http.express';\n\n// `express.name`/`express.type` are Sentry-internal Express attributes (not part\n// of `@sentry/conventions`); kept in sync with `@sentry/core`'s OTel-derived\n// Express integration so the emitted spans are identical across both code paths.\nconst ATTR_EXPRESS_NAME = 'express.name';\nconst ATTR_EXPRESS_TYPE = 'express.type';\n\nconst EXPRESS_TYPE_TO_SPAN_OP: Record<string, string> = {\n middleware: MIDDLEWARE,\n request_handler: HANDLER,\n router: ROUTER,\n};\n\nconst NOOP = (): void => {};\n\nlet _isInstrumented = false;\n\nexport function instrumentExpress(\n options: ExpressIntegrationOptions,\n tracingChannel: typeof diagnosticsChannel.tracingChannel,\n): void {\n if (_isInstrumented) {\n return;\n }\n _isInstrumented = true;\n\n // Record each layer's registered path *pattern* as it is registered, so the\n // matched route can be reconstructed with its parameters intact at request\n // time. Only the `end` event matters (the layer is on the router's stack by\n // then); the others are required by the subscriber type, so no-op them.\n for (const channelName of [CHANNELS.EXPRESS_REGISTER, CHANNELS.ROUTER_REGISTER]) {\n tracingChannel<RegistrationChannelContext>(channelName).subscribe({\n start: NOOP,\n asyncStart: NOOP,\n asyncEnd: NOOP,\n error: NOOP,\n end: captureRegisteredLayerPath,\n });\n }\n\n for (const channelName of [CHANNELS.EXPRESS_HANDLE, CHANNELS.ROUTER_HANDLE]) {\n const channel = tracingChannel<HandleChannelContext>(channelName);\n\n bindTracingChannelToSpan(channel, data => getSpanForLayer(data, options), {\n beforeSpanEnd(_span, data) {\n data._sentryCleanup?.();\n },\n });\n\n // Pop the layer path and end the layer span when the layer hands off via\n // `next`. `asyncStart` fires when `next` is called and *before* the\n // downstream layer runs, so the per-request path chain reflects only the\n // current chain when each layer reconstructs its route, and each span covers\n // only its own layer. The `error` event captures throws at the layer level\n // (see `captureLayerError`), before any user error-handling middleware.\n channel.subscribe({\n start: NOOP,\n asyncEnd: NOOP,\n end: NOOP,\n error: data => captureLayerError(data, options.shouldHandleError),\n asyncStart: data => {\n popLayerPathForLayer(data);\n endLayerSpanOnNext(data);\n },\n });\n }\n}\n\n/**\n * Capture an error surfaced on a layer's `handle_request` channel — the throw\n * site, which runs before any user error-handling middleware.\n *\n * Each request's error is handled exactly once: the same error surfaces on every\n * parent layer's `error` event as it bubbles, and a user may also still call the\n * deprecated `setupExpressErrorHandler`. We mark the request the first time we\n * see it, so later layers and that middleware defer to this decision — the\n * integration is the single registered handler and its `shouldHandleError` wins.\n * This deliberately does not rely on `captureException`'s global dedup, which is\n * only set when an error is actually captured and so cannot express a\n * \"deliberately skipped\" decision (leaving the deprecated middleware free to\n * capture it and override `shouldHandleError`).\n *\n * `shouldHandleError` is the raw integration option: `false` disables capture\n * entirely, a function customizes the gate, and `undefined` falls back to\n * {@link defaultShouldHandleError}.\n */\nexport function captureLayerError(\n data: HandleChannelContext,\n shouldHandleError: ExpressShouldHandleError | undefined,\n): void {\n const error = data.error;\n\n // `next('route')` / `next('router')` are Express control-flow signals, not errors.\n if (!error || error === 'route' || error === 'router') {\n return;\n }\n\n // Take responsibility for this request's error exactly once (see the doc comment above). The marker\n // lives on the request — the same instance across every bubbling layer and the error middleware,\n // and always a mutable object, unlike the thrown value which may be frozen or a primitive. Mark\n // before the `shouldHandleError` gate so a \"skip\" decision also suppresses the deprecated middleware.\n const request = data.arguments?.[0] as ExpressRequest | undefined;\n if (request) {\n if (isExpressErrorHandled(request)) {\n return;\n }\n markExpressErrorHandled(request);\n }\n\n if (shouldHandleError === false) {\n return;\n }\n\n if (!(shouldHandleError ?? defaultShouldHandleError)(error as MiddlewareError)) {\n return;\n }\n\n const capture = (): string =>\n captureException(error, {\n mechanism: {\n type: 'auto.http.express',\n handled: false,\n },\n });\n\n // The channel's `error` event runs outside the layer span's async context, so\n // re-activate the bound span (when present) to parent the error event to the\n // request's trace instead of capturing it context-free.\n if (data._sentrySpan) {\n withActiveSpan(data._sentrySpan, capture);\n } else {\n capture();\n }\n}\n\n/** Record the freshly-registered layer's path pattern from a `route`/`use` call. */\nfunction captureRegisteredLayerPath(data: RegistrationChannelContext): void {\n const stack = data.self?.stack;\n if (!Array.isArray(stack)) {\n return;\n }\n const layer = stack[stack.length - 1];\n if (layer) {\n setLayerRegisteredPath(layer, getLayerPath(data.arguments ?? []));\n }\n}\n\n/** Pop the path a layer pushed once it hands control onward via `next`. */\nfunction popLayerPathForLayer(data: HandleChannelContext): void {\n if (!data._sentryStoredLayer) {\n return;\n }\n // Clear the marker first so a layer that (incorrectly) calls `next` more than\n // once can't pop again and take a parent's entry off the stack with it.\n data._sentryStoredLayer = false;\n const req = data.arguments?.[0] as ExpressRequest | undefined;\n if (req) {\n popLayerPath(req);\n }\n}\n\n/**\n * End a layer's span once it hands control onward via `next`.\n *\n * The tracing-channel helper would otherwise end it on `asyncEnd`, which only\n * fires once `next` *returns*. Express runs the rest of the chain synchronously\n * inside `next`, so that would keep every layer on the synchronous chain open\n * (each holding a response `finish` listener) until the whole chain unwinds,\n * and inflate each span with the downstream layers' synchronous work. The\n * helper's later `asyncEnd` is then a no-op, since `span.end()` is idempotent.\n */\nfunction endLayerSpanOnNext(data: HandleChannelContext): void {\n const span = data._sentrySpan;\n if (!span) {\n return;\n }\n data._sentryCleanup?.();\n span.end();\n}\n\n/**\n * Open a span for one layer invocation. Returns `undefined` to opt the layer\n * out (error handlers, or a layer with no active parent trace) — the helper\n * then leaves the active context untouched.\n */\nfunction getSpanForLayer(data: HandleChannelContext, options: ExpressIntegrationOptions): Span | undefined {\n const layer = data.self;\n const args = data.arguments;\n if (!layer || !Array.isArray(args)) {\n return undefined;\n }\n\n // Express only treats a 4-arg handler as an error handler and skips it in\n // the normal request pipeline; match the OTel integration and don't trace it.\n if (layer.handle?.length === 4) {\n return undefined;\n }\n\n // A Route dispatches to its handlers via the same `handle_request` method,\n // but those inner layers already run inside the route-dispatch layer's\n // `request_handler` span. They carry `.method` (and no `.route`); skip them\n // so we emit one span per route, matching the OTel Express integration.\n if (layer.method && !layer.route) {\n return undefined;\n }\n\n const req = args[0] as ExpressRequest | undefined;\n const res = args[1] as ExpressResponse | undefined;\n if (!req) {\n return undefined;\n }\n\n // No active parent span means this request is being ignored (unsampled /\n // filtered), so don't open a span\n if (!getActiveSpan()) {\n return undefined;\n }\n\n const type = getLayerType(layer);\n\n // Push this layer's registered path onto the request's chain so a\n // `request_handler` can reconstruct the full route with parameters intact\n // (`req.baseUrl` only exposes the *resolved* mount prefix). The matching pop\n // happens on `asyncStart` when the layer hands off via `next`.\n const registeredPath = getLayerRegisteredPath(layer) ?? getMatchedLayerPath(layer);\n if (registeredPath != null) {\n pushLayerPath(req, registeredPath);\n data._sentryStoredLayer = true;\n }\n\n // `constructedRoute` (the full registered pattern) names the span/transaction;\n // `matchedRoute` (validated against the request URL) is the `http.route`.\n // Computed for every layer type (not just `request_handler`) so routes served\n // by mounted middleware (`app.use('/trpc', handler)`) still propagate their\n // path to the root `http.server` span — mirroring the OTel Express integration,\n // which resolves the route on every layer. Without this, such transactions keep\n // the raw URL name (e.g. `GET /trpc/foo` instead of `GET /trpc`).\n const constructedRoute = getConstructedRoute(req);\n const matchedRoute = constructedRoute != null ? getActualMatchedRoute(req, constructedRoute) : undefined;\n\n const name =\n type === 'request_handler'\n ? constructedRoute || 'request handler'\n : type === 'router'\n ? (layer.path ?? '/')\n : (layer.name ?? '<anonymous>');\n\n // Propagate the route to the root `http.server` span *before* the ignore\n // check, so the transaction is still named even when the layer's own span is\n // ignored — matches the OTel Express integration's `onRouteResolved` timing.\n if (matchedRoute) {\n setHttpServerSpanRouteAttribute(matchedRoute);\n }\n\n if (type === 'request_handler' && constructedRoute) {\n const isolationScope = getIsolationScope();\n if (isolationScope !== getDefaultIsolationScope()) {\n const method = typeof req.method === 'string' ? req.method.toUpperCase() : 'GET';\n isolationScope.setTransactionName(`${method} ${constructedRoute}`);\n } else {\n DEBUG_BUILD &&\n debug.warn(\n '[instrumentation:express] Isolation scope is still default isolation scope - skipping transaction name',\n );\n }\n }\n\n // Honor `ignoreLayers`/`ignoreLayersType`: skip the span for matching layers.\n // We intentionally do NOT pop the pushed path here (unlike OTel Express, which\n // pops on ignore): the path is still popped on `asyncStart` when the layer\n // calls `next`, so a following sibling isn't polluted, while an ignored\n // *router* keeps its mount prefix on the stack for the sub-stack it dispatches\n // — so routes under an ignored router stay correct. The only entries that\n // never pop come from layers that end the response without `next()`, and those\n // sit on a per-request store that is discarded when the request ends.\n if (isLayerIgnored(name, type, options)) {\n return undefined;\n }\n\n const client = getClient();\n // With span streaming, span names have to be low cardinality, so router\n // and request handler spans are named after their route. A route that did\n // not validate against the request URL can describe a different request,\n // so those spans take the static fallback instead.\n const isStreamedSpan = !!client && hasSpanStreamingEnabled(client);\n const isStreamedRouterSpan = isStreamedSpan && type === 'router';\n const isStreamedRequestHandlerSpan = isStreamedSpan && type === 'request_handler';\n\n const span = startInactiveSpan({\n name: isStreamedRouterSpan\n ? matchedRoute || ROUTER_SPAN_NAME_FALLBACK\n : isStreamedRequestHandlerSpan\n ? matchedRoute || REQUEST_HANDLER_SPAN_NAME_FALLBACK\n : name,\n attributes: {\n [SENTRY_ORIGIN]: ORIGIN,\n [SENTRY_OP]: EXPRESS_TYPE_TO_SPAN_OP[type],\n [ATTR_EXPRESS_NAME]: name,\n [ATTR_EXPRESS_TYPE]: type,\n [HTTP_ROUTE]: matchedRoute,\n },\n });\n\n // A layer that sends the response (route handlers, typically) never calls\n // `next`, so the channel's `asyncStart` never fires. End on the response's\n // `finish` in that case. When `next` *is* called, `endLayerSpanOnNext` ends\n // the span and removes these now-redundant listeners.\n // `finish` never fires when the client aborts, so also end on `close`, which\n // is when the `http.server` span ends. Otherwise the span and its subtree\n // would be dropped from the transaction.\n if (res && typeof res.once === 'function') {\n const cleanup = (): void => {\n res.removeListener('finish', onFinish);\n res.removeListener('close', onClose);\n };\n const onFinish = (): void => {\n cleanup();\n span.end();\n };\n const onClose = (): void => {\n cleanup();\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'cancelled' });\n span.end();\n };\n res.once('finish', onFinish);\n res.once('close', onClose);\n data._sentryCleanup = cleanup;\n }\n\n return span;\n}\n\n/**\n * The path of a matched layer for which no registration event recorded a path. That is the case when the events\n * arrive after the registration calls: Cloudflare delivers the events of calls at module scope with the first\n * request.\n */\nfunction getMatchedLayerPath(layer: ExpressLayer): string | undefined {\n if (layer.route) {\n return getLayerPath([layer.route.path]);\n }\n // A mount path without parameters is equal to the part of the URL that the layer matched.\n return layer.keys?.length ? undefined : layer.path || undefined;\n}\n\nfunction getLayerType(layer: ExpressLayer): ExpressLayerType {\n if (layer.name === 'router') {\n return 'router';\n }\n // `bound dispatch` (v4) / `handle` — the route-dispatch layer created by `router.route()`.\n if (layer.name === 'bound dispatch' || layer.name === 'handle') {\n return 'request_handler';\n }\n return 'middleware';\n}\n\n/**\n * Whether a layer should be skipped per the `ignoreLayers`/`ignoreLayersType`\n * options. Matches `@sentry/core`'s Express `isLayerIgnored`: `ignoreLayersType`\n * filters by layer type, `ignoreLayers` matches the layer's name against\n * string/RegExp/predicate patterns (exact string match).\n */\nfunction isLayerIgnored(name: string, type: ExpressLayerType, options: ExpressIntegrationOptions): boolean {\n const { ignoreLayers, ignoreLayersType } = options;\n\n if (Array.isArray(ignoreLayersType) && ignoreLayersType.includes(type)) {\n return true;\n }\n\n if (!Array.isArray(ignoreLayers)) {\n return false;\n }\n\n try {\n return stringMatchesSomePattern(name, ignoreLayers, true);\n } catch {\n return false;\n }\n}\n"],"mappings":";;;;;;;;;;;AA8CA,MAAM,SAAS;AAKf,MAAM,oBAAoB;AAC1B,MAAM,oBAAoB;AAE1B,MAAM,0BAAkD;CACtD,YAAY;CACZ,iBAAiB;CACjB,QAAQ;AACV;AAEA,MAAM,aAAmB,CAAC;AAE1B,IAAI,kBAAkB;AAEtB,SAAgB,kBACd,SACA,gBACM;CACN,IAAI,iBACF;CAEF,kBAAkB;CAMlB,KAAK,MAAM,eAAe,CAAC,SAAS,kBAAkB,SAAS,eAAe,GAC5E,eAA2C,WAAW,CAAC,CAAC,UAAU;EAChE,OAAO;EACP,YAAY;EACZ,UAAU;EACV,OAAO;EACP,KAAK;CACP,CAAC;CAGH,KAAK,MAAM,eAAe,CAAC,SAAS,gBAAgB,SAAS,aAAa,GAAG;EAC3E,MAAM,UAAU,eAAqC,WAAW;EAEhE,yBAAyB,UAAS,SAAQ,gBAAgB,MAAM,OAAO,GAAG,EACxE,cAAc,OAAO,MAAM;GACzB,KAAK,iBAAiB;EACxB,EACF,CAAC;EAQD,QAAQ,UAAU;GAChB,OAAO;GACP,UAAU;GACV,KAAK;GACL,QAAO,SAAQ,kBAAkB,MAAM,QAAQ,iBAAiB;GAChE,aAAY,SAAQ;IAClB,qBAAqB,IAAI;IACzB,mBAAmB,IAAI;GACzB;EACF,CA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IAAI;EACX;EACA,MAAM,gBAAsB;GAC1B,QAAQ;GACR,KAAK,UAAU;IAAE,MAAM;IAAmB,SAAS;GAAY,CAAC;GAChE,KAAK,IAAI;EACX;EACA,IAAI,KAAK,UAAU,QAAQ;EAC3B,IAAI,KAAK,SAAS,OAAO;EACzB,KAAK,iBAAiB;CACxB;CAEA,OAAO;AACT;;;;;;AAOA,SAAS,oBAAoB,OAAyC;CACpE,IAAI,MAAM,OACR,OAAO,aAAa,CAAC,MAAM,MAAM,IAAI,CAAC;CAGxC,OAAO,MAAM,MAAM,SAAS,KAAA,IAAY,MAAM,QAAQ,KAAA;AACxD;AAEA,SAAS,aAAa,OAAuC;CAC3D,IAAI,MAAM,SAAS,UACjB,OAAO;CAGT,IAAI,MAAM,SAAS,oBAAoB,MAAM,SAAS,UACpD,OAAO;CAET,OAAO;AACT;;;;;;;AAQA,SAAS,eAAe,MAAc,MAAwB,SAA6C;CACzG,MAAM,EAAE,cAAc,qBAAqB;CAE3C,IAAI,MAAM,QAAQ,gBAAgB,KAAK,iBAAiB,SAAS,IAAI,GACnE,OAAO;CAGT,IAAI,CAAC,MAAM,QAAQ,YAAY,GAC7B,OAAO;CAGT,IAAI;EACF,OAAO,yBAAyB,MAAM,cAAc,IAAI;CAC1D,QAAQ;EACN,OAAO;CACT;AACF"}
1
+ {"version":3,"file":"instrumentation.js","names":[],"sources":["../../../../src/integrations/express/instrumentation.ts"],"sourcesContent":["import type * as diagnosticsChannel from 'node:diagnostics_channel';\nimport { HTTP_ROUTE, SENTRY_OP, SENTRY_ORIGIN } from '@sentry/conventions/attributes';\nimport { HANDLER, MIDDLEWARE, ROUTER } from '@sentry/conventions/op';\nimport type { Span } from '@sentry/core';\nimport {\n captureException,\n debug,\n getActiveSpan,\n getClient,\n getDefaultIsolationScope,\n getIsolationScope,\n hasSpanStreamingEnabled,\n REQUEST_HANDLER_SPAN_NAME_FALLBACK,\n ROUTER_SPAN_NAME_FALLBACK,\n SPAN_STATUS_ERROR,\n startInactiveSpan,\n stringMatchesSomePattern,\n withActiveSpan,\n} from '@sentry/core';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport { CHANNELS } from '../../orchestrion/channels';\nimport { bindTracingChannelToSpan } from '../../tracing-channel';\nimport {\n getActualMatchedRoute,\n getConstructedRoute,\n getLayerPath,\n getLayerRegisteredPath,\n popLayerPath,\n pushLayerPath,\n setLayerRegisteredPath,\n} from './route';\nimport type {\n ExpressIntegrationOptions,\n ExpressLayer,\n ExpressLayerType,\n ExpressRequest,\n ExpressResponse,\n ExpressShouldHandleError,\n HandleChannelContext,\n MiddlewareError,\n RegistrationChannelContext,\n} from './types';\nimport { defaultShouldHandleError } from './utils';\nimport { isExpressErrorHandled, markExpressErrorHandled } from './error-handled';\nimport { setHttpServerSpanRouteAttribute } from '../../utils/setHttpServerSpanRouteAttribute';\n\nconst ORIGIN = 'auto.http.express';\n\n// `express.name`/`express.type` are Sentry-internal Express attributes (not part\n// of `@sentry/conventions`); kept in sync with `@sentry/core`'s OTel-derived\n// Express integration so the emitted spans are identical across both code paths.\nconst ATTR_EXPRESS_NAME = 'express.name';\nconst ATTR_EXPRESS_TYPE = 'express.type';\n\nconst EXPRESS_TYPE_TO_SPAN_OP: Record<string, string> = {\n middleware: MIDDLEWARE,\n request_handler: HANDLER,\n router: ROUTER,\n};\n\nconst NOOP = (): void => {};\n\nlet _isInstrumented = false;\n\nexport function instrumentExpress(\n options: ExpressIntegrationOptions,\n tracingChannel: typeof diagnosticsChannel.tracingChannel,\n): void {\n if (_isInstrumented) {\n return;\n }\n _isInstrumented = true;\n\n // Record each layer's registered path *pattern* as it is registered, so the\n // matched route can be reconstructed with its parameters intact at request\n // time. Only the `end` event matters (the layer is on the router's stack by\n // then); the others are required by the subscriber type, so no-op them.\n for (const channelName of [CHANNELS.EXPRESS_REGISTER, CHANNELS.ROUTER_REGISTER]) {\n tracingChannel<RegistrationChannelContext>(channelName).subscribe({\n start: NOOP,\n asyncStart: NOOP,\n asyncEnd: NOOP,\n error: NOOP,\n end: captureRegisteredLayerPath,\n });\n }\n\n for (const channelName of [CHANNELS.EXPRESS_HANDLE, CHANNELS.ROUTER_HANDLE]) {\n const channel = tracingChannel<HandleChannelContext>(channelName);\n\n bindTracingChannelToSpan(channel, data => getSpanForLayer(data, options), {\n beforeSpanEnd(_span, data) {\n data._sentryCleanup?.();\n },\n });\n\n // Pop the layer path and end the layer span when the layer hands off via\n // `next`. `asyncStart` fires when `next` is called and *before* the\n // downstream layer runs, so the per-request path chain reflects only the\n // current chain when each layer reconstructs its route, and each span covers\n // only its own layer. The `error` event captures throws at the layer level\n // (see `captureLayerError`), before any user error-handling middleware.\n channel.subscribe({\n start: NOOP,\n asyncEnd: NOOP,\n end: NOOP,\n error: data => captureLayerError(data, options.shouldHandleError),\n asyncStart: data => {\n popLayerPathForLayer(data);\n endLayerSpanOnNext(data);\n },\n });\n }\n}\n\n/**\n * Capture an error surfaced on a layer's `handle_request` channel — the throw\n * site, which runs before any user error-handling middleware.\n *\n * Each request's error is handled exactly once: the same error surfaces on every\n * parent layer's `error` event as it bubbles, and a user may also still call the\n * deprecated `setupExpressErrorHandler`. We mark the request the first time we\n * see it, so later layers and that middleware defer to this decision — the\n * integration is the single registered handler and its `shouldHandleError` wins.\n * This deliberately does not rely on `captureException`'s global dedup, which is\n * only set when an error is actually captured and so cannot express a\n * \"deliberately skipped\" decision (leaving the deprecated middleware free to\n * capture it and override `shouldHandleError`).\n *\n * `shouldHandleError` is the raw integration option: `false` disables capture\n * entirely, a function customizes the gate, and `undefined` falls back to\n * {@link defaultShouldHandleError}.\n */\nexport function captureLayerError(\n data: HandleChannelContext,\n shouldHandleError: ExpressShouldHandleError | undefined,\n): void {\n const error = data.error;\n\n // `next('route')` / `next('router')` are Express control-flow signals, not errors.\n if (!error || error === 'route' || error === 'router') {\n return;\n }\n\n // Take responsibility for this request's error exactly once (see the doc comment above). The marker\n // lives on the request — the same instance across every bubbling layer and the error middleware,\n // and always a mutable object, unlike the thrown value which may be frozen or a primitive. Mark\n // before the `shouldHandleError` gate so a \"skip\" decision also suppresses the deprecated middleware.\n const request = data.arguments?.[0] as ExpressRequest | undefined;\n if (request) {\n if (isExpressErrorHandled(request)) {\n return;\n }\n markExpressErrorHandled(request);\n }\n\n if (shouldHandleError === false) {\n return;\n }\n\n if (!(shouldHandleError ?? defaultShouldHandleError)(error as MiddlewareError)) {\n return;\n }\n\n const capture = (): string =>\n captureException(error, {\n mechanism: {\n type: 'auto.http.express',\n handled: false,\n },\n });\n\n // The channel's `error` event runs outside the layer span's async context, so\n // re-activate the bound span (when present) to parent the error event to the\n // request's trace instead of capturing it context-free.\n if (data._sentrySpan) {\n withActiveSpan(data._sentrySpan, capture);\n } else {\n capture();\n }\n}\n\n/** Record the freshly-registered layer's path pattern from a `route`/`use` call. */\nfunction captureRegisteredLayerPath(data: RegistrationChannelContext): void {\n const stack = data.self?.stack;\n if (!Array.isArray(stack)) {\n return;\n }\n const layer = stack[stack.length - 1];\n if (layer) {\n setLayerRegisteredPath(layer, getLayerPath(data.arguments ?? []));\n }\n}\n\n/** Pop the path a layer pushed once it hands control onward via `next`. */\nfunction popLayerPathForLayer(data: HandleChannelContext): void {\n if (!data._sentryStoredLayer) {\n return;\n }\n // Clear the marker first so a layer that (incorrectly) calls `next` more than\n // once can't pop again and take a parent's entry off the stack with it.\n data._sentryStoredLayer = false;\n const req = data.arguments?.[0] as ExpressRequest | undefined;\n if (req) {\n popLayerPath(req);\n }\n}\n\n/**\n * End a layer's span once it hands control onward via `next`.\n *\n * The tracing-channel helper would otherwise end it on `asyncEnd`, which only\n * fires once `next` *returns*. Express runs the rest of the chain synchronously\n * inside `next`, so that would keep every layer on the synchronous chain open\n * (each holding a response `finish` listener) until the whole chain unwinds,\n * and inflate each span with the downstream layers' synchronous work. The\n * helper's later `asyncEnd` is then a no-op, since `span.end()` is idempotent.\n */\nfunction endLayerSpanOnNext(data: HandleChannelContext): void {\n const span = data._sentrySpan;\n if (!span) {\n return;\n }\n data._sentryCleanup?.();\n span.end();\n}\n\n/**\n * Open a span for one layer invocation. Returns `undefined` to opt the layer\n * out (error handlers, or a layer with no active parent trace) — the helper\n * then leaves the active context untouched.\n */\nfunction getSpanForLayer(data: HandleChannelContext, options: ExpressIntegrationOptions): Span | undefined {\n const layer = data.self;\n const args = data.arguments;\n if (!layer || !Array.isArray(args)) {\n return undefined;\n }\n\n // Express only treats a 4-arg handler as an error handler and skips it in\n // the normal request pipeline; match the OTel integration and don't trace it.\n if (layer.handle?.length === 4) {\n return undefined;\n }\n\n // A Route dispatches to its handlers via the same `handle_request` method,\n // but those inner layers already run inside the route-dispatch layer's\n // `request_handler` span. They carry `.method` (and no `.route`); skip them\n // so we emit one span per route, matching the OTel Express integration.\n if (layer.method && !layer.route) {\n return undefined;\n }\n\n const req = args[0] as ExpressRequest | undefined;\n const res = args[1] as ExpressResponse | undefined;\n if (!req) {\n return undefined;\n }\n\n // No active parent span means this request is being ignored (unsampled /\n // filtered), so don't open a span\n if (!getActiveSpan()) {\n return undefined;\n }\n\n const type = getLayerType(layer);\n\n // Push this layer's registered path onto the request's chain so a\n // `request_handler` can reconstruct the full route with parameters intact\n // (`req.baseUrl` only exposes the *resolved* mount prefix). The matching pop\n // happens on `asyncStart` when the layer hands off via `next`.\n const registeredPath = getLayerRegisteredPath(layer) ?? getMatchedLayerPath(layer);\n if (registeredPath != null) {\n pushLayerPath(req, registeredPath);\n data._sentryStoredLayer = true;\n }\n\n // `constructedRoute` (the full registered pattern) names the span/transaction;\n // `matchedRoute` (validated against the request URL) is the `http.route`.\n // Computed for every layer type (not just `request_handler`) so routes served\n // by mounted middleware (`app.use('/trpc', handler)`) still propagate their\n // path to the root `http.server` span — mirroring the OTel Express integration,\n // which resolves the route on every layer. Without this, such transactions keep\n // the raw URL name (e.g. `GET /trpc/foo` instead of `GET /trpc`).\n const constructedRoute = getConstructedRoute(req);\n const matchedRoute = constructedRoute != null ? getActualMatchedRoute(req, constructedRoute) : undefined;\n\n const name =\n type === 'request_handler'\n ? constructedRoute || 'request handler'\n : type === 'router'\n ? (layer.path ?? '/')\n : (layer.name ?? '<anonymous>');\n\n // Propagate the route to the root `http.server` span *before* the ignore\n // check, so the transaction is still named even when the layer's own span is\n // ignored — matches the OTel Express integration's `onRouteResolved` timing.\n if (matchedRoute) {\n setHttpServerSpanRouteAttribute(matchedRoute);\n }\n\n if (type === 'request_handler' && constructedRoute) {\n const isolationScope = getIsolationScope();\n if (isolationScope !== getDefaultIsolationScope()) {\n const method = typeof req.method === 'string' ? req.method.toUpperCase() : 'GET';\n isolationScope.setTransactionName(`${method} ${constructedRoute}`);\n } else {\n DEBUG_BUILD &&\n debug.warn(\n '[instrumentation:express] Isolation scope is still default isolation scope - skipping transaction name',\n );\n }\n }\n\n // Honor `ignoreLayers`/`ignoreLayersType`: skip the span for matching layers.\n // We intentionally do NOT pop the pushed path here (unlike OTel Express, which\n // pops on ignore): the path is still popped on `asyncStart` when the layer\n // calls `next`, so a following sibling isn't polluted, while an ignored\n // *router* keeps its mount prefix on the stack for the sub-stack it dispatches\n // — so routes under an ignored router stay correct. The only entries that\n // never pop come from layers that end the response without `next()`, and those\n // sit on a per-request store that is discarded when the request ends.\n if (isLayerIgnored(name, type, options)) {\n return undefined;\n }\n\n const client = getClient();\n // With span streaming, span names have to be low cardinality, so router\n // and request handler spans are named after their route. A route that did\n // not validate against the request URL can describe a different request,\n // so those spans take the static fallback instead.\n const isStreamedSpan = !!client && hasSpanStreamingEnabled(client);\n const isStreamedRouterSpan = isStreamedSpan && type === 'router';\n const isStreamedRequestHandlerSpan = isStreamedSpan && type === 'request_handler';\n\n const span = startInactiveSpan({\n name: isStreamedRouterSpan\n ? matchedRoute || ROUTER_SPAN_NAME_FALLBACK\n : isStreamedRequestHandlerSpan\n ? matchedRoute || REQUEST_HANDLER_SPAN_NAME_FALLBACK\n : name,\n attributes: {\n [SENTRY_ORIGIN]: ORIGIN,\n [SENTRY_OP]: EXPRESS_TYPE_TO_SPAN_OP[type],\n [ATTR_EXPRESS_NAME]: name,\n [ATTR_EXPRESS_TYPE]: type,\n [HTTP_ROUTE]: matchedRoute,\n },\n });\n\n // A layer that sends the response (route handlers, typically) never calls\n // `next`, so the channel's `asyncStart` never fires. End on the response's\n // `finish` in that case. When `next` *is* called, `endLayerSpanOnNext` ends\n // the span and removes these now-redundant listeners.\n // `finish` never fires when the client aborts, so also end on `close`, which\n // is when the `http.server` span ends. Otherwise the span and its subtree\n // would be dropped from the transaction.\n if (res && typeof res.once === 'function') {\n const cleanup = (): void => {\n res.removeListener('finish', onFinish);\n res.removeListener('close', onClose);\n };\n const onFinish = (): void => {\n cleanup();\n span.end();\n };\n const onClose = (): void => {\n cleanup();\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'cancelled' });\n span.end();\n };\n res.once('finish', onFinish);\n res.once('close', onClose);\n data._sentryCleanup = cleanup;\n }\n\n return span;\n}\n\n/**\n * The path of a matched layer for which no registration event recorded a path. That is the case when the events\n * arrive after the registration calls: Cloudflare delivers the events of calls at module scope with the first\n * request.\n */\nfunction getMatchedLayerPath(layer: ExpressLayer): string | undefined {\n if (layer.route) {\n return getLayerPath([layer.route.path]);\n }\n // `router` 2.3.0 and later keep the registered mount path in `rawPath` and no longer store the matched `path`.\n if (layer.rawPath !== undefined) {\n return getLayerPath([layer.rawPath]);\n }\n // A mount path without parameters is equal to the part of the URL that the layer matched.\n return layer.keys?.length ? undefined : layer.path || undefined;\n}\n\nfunction getLayerType(layer: ExpressLayer): ExpressLayerType {\n if (layer.name === 'router') {\n return 'router';\n }\n // `bound dispatch` (v4) / `handle` — the route-dispatch layer created by `router.route()`.\n if (layer.name === 'bound dispatch' || layer.name === 'handle') {\n return 'request_handler';\n }\n return 'middleware';\n}\n\n/**\n * Whether a layer should be skipped per the `ignoreLayers`/`ignoreLayersType`\n * options. Matches `@sentry/core`'s Express `isLayerIgnored`: `ignoreLayersType`\n * filters by layer type, `ignoreLayers` matches the layer's name against\n * string/RegExp/predicate patterns (exact string match).\n */\nfunction isLayerIgnored(name: string, type: ExpressLayerType, options: ExpressIntegrationOptions): boolean {\n const { ignoreLayers, ignoreLayersType } = options;\n\n if (Array.isArray(ignoreLayersType) && ignoreLayersType.includes(type)) {\n return true;\n }\n\n if (!Array.isArray(ignoreLayers)) {\n return false;\n }\n\n try {\n return stringMatchesSomePattern(name, ignoreLayers, true);\n } catch {\n return false;\n }\n}\n"],"mappings":";;;;;;;;;;;AA8CA,MAAM,SAAS;AAKf,MAAM,oBAAoB;AAC1B,MAAM,oBAAoB;AAE1B,MAAM,0BAAkD;CACtD,YAAY;CACZ,iBAAiB;CACjB,QAAQ;AACV;AAEA,MAAM,aAAmB,CAAC;AAE1B,IAAI,kBAAkB;AAEtB,SAAgB,kBACd,SACA,gBACM;CACN,IAAI,iBACF;CAEF,kBAAkB;CAMlB,KAAK,MAAM,eAAe,CAAC,SAAS,kBAAkB,SAAS,eAAe,GAC5E,eAA2C,WAAW,CAAC,CAAC,UAAU;EAChE,OAAO;EACP,YAAY;EACZ,UAAU;EACV,OAAO;EACP,KAAK;CACP,CAAC;CAGH,KAAK,MAAM,eAAe,CAAC,SAAS,gBAAgB,SAAS,aAAa,GAAG;EAC3E,MAAM,UAAU,eAAqC,WAAW;EAEhE,yBAAyB,UAAS,SAAQ,gBAAgB,MAAM,OAAO,GAAG,EACxE,cAAc,OAAO,MAAM;GACzB,KAAK,iBAAiB;EACxB,EACF,CAAC;EAQD,QAAQ,UAAU;GAChB,OAAO;GACP,UAAU;GACV,KAAK;GACL,QAAO,SAAQ,kBAAkB,MAAM,QAAQ,iBAAiB;GAChE,aAAY,SAAQ;IAClB,qBAAqB,IAAI;IACzB,mBAAmB,IAAI;GACzB;EACF,CAAC;CACH;AACF;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,kBACd,MACA,mBACM;CACN,MAAM,QAAQ,KAAK;CAGnB,IAAI,CAAC,SAAS,UAAU,WAAW,UAAU,UAC3C;CAOF,MAAM,UAAU,KAAK,YAAY;CACjC,IA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AO;EACzB,KAAK,iBAAiB;CACxB;CAEA,OAAO;AACT;;;;;;AAOA,SAAS,oBAAoB,OAAyC;CACpE,IAAI,MAAM,OACR,OAAO,aAAa,CAAC,MAAM,MAAM,IAAI,CAAC;CAGxC,IAAI,MAAM,YAAY,KAAA,GACpB,OAAO,aAAa,CAAC,MAAM,OAAO,CAAC;CAGrC,OAAO,MAAM,MAAM,SAAS,KAAA,IAAY,MAAM,QAAQ,KAAA;AACxD;AAEA,SAAS,aAAa,OAAuC;CAC3D,IAAI,MAAM,SAAS,UACjB,OAAO;CAGT,IAAI,MAAM,SAAS,oBAAoB,MAAM,SAAS,UACpD,OAAO;CAET,OAAO;AACT;;;;;;;AAQA,SAAS,eAAe,MAAc,MAAwB,SAA6C;CACzG,MAAM,EAAE,cAAc,qBAAqB;CAE3C,IAAI,MAAM,QAAQ,gBAAgB,KAAK,iBAAiB,SAAS,IAAI,GACnE,OAAO;CAGT,IAAI,CAAC,MAAM,QAAQ,YAAY,GAC7B,OAAO;CAGT,IAAI;EACF,OAAO,yBAAyB,MAAM,cAAc,IAAI;CAC1D,QAAQ;EACN,OAAO;CACT;AACF"}
@@ -2,7 +2,7 @@ import { subscribe } from "../../utils/diagnosticsChannel.js";
2
2
  import { setHttpServerSpanRouteAttribute } from "../../utils/setHttpServerSpanRouteAttribute.js";
3
3
  import { handleFastifyError } from "./errors.js";
4
4
  import { HTTP_REQUEST_METHOD, HTTP_RESPONSE_STATUS_CODE, HTTP_ROUTE, SENTRY_OP, SENTRY_ORIGIN, URL_PATH } from "@sentry/conventions/attributes";
5
- import { REQUEST_HANDLER_SPAN_NAME_FALLBACK, SPAN_STATUS_ERROR, getClient, getIsolationScope, hasSpanStreamingEnabled, isObjectLike, startInactiveSpan, startSpan, withActiveSpan } from "@sentry/core";
5
+ import { REQUEST_HANDLER_SPAN_NAME_FALLBACK, SPAN_STATUS_ERROR, getActiveSpan, getClient, getIsolationScope, hasSpanStreamingEnabled, isObjectLike, spanIsSampled, startInactiveSpan, startSpan, withActiveSpan } from "@sentry/core";
6
6
  import { HANDLER, MIDDLEWARE } from "@sentry/conventions/op";
7
7
  // src/integrations/fastify/instrumentation.ts
8
8
  const ORIGIN = "auto.http.fastify";
@@ -194,6 +194,8 @@ function handlerWrapper(handler, hookName, spanAttributes = {}) {
194
194
  const request = getRequestFromArgs(args);
195
195
  if (!request) return handler.call(this, ...args);
196
196
  const parentSpan = request[kRequestSpan] ?? void 0;
197
+ const effectiveParentSpan = parentSpan ?? getActiveSpan();
198
+ if (effectiveParentSpan && !spanIsSampled(effectiveParentSpan)) return handler.call(this, ...args);
197
199
  const handlerName = handler.name?.length > 0 ? handler.name : this.pluginName ?? ANONYMOUS_FUNCTION_NAME;
198
200
  const hookType = spanAttributes[ATTRIBUTE_FASTIFY_TYPE];
199
201
  const op = hookType === HOOK_TYPE_INSTANCE ? MIDDLEWARE : hookType === HOOK_TYPE_HANDLER ? HANDLER : void 0;