@sentry/cloudflare 10.69.0 → 10.71.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 (79) hide show
  1. package/build/cjs/durableobject.js +114 -36
  2. package/build/cjs/durableobject.js.map +1 -1
  3. package/build/cjs/flush.js.map +1 -1
  4. package/build/cjs/instrumentations/agents/index.js +2 -0
  5. package/build/cjs/instrumentations/agents/index.js.map +1 -1
  6. package/build/cjs/instrumentations/agents/instrumentAgentCallableRpc.js +2 -2
  7. package/build/cjs/instrumentations/agents/instrumentAgentCallableRpc.js.map +1 -1
  8. package/build/cjs/instrumentations/agents/instrumentAgentRequestConversation.js +19 -0
  9. package/build/cjs/instrumentations/agents/instrumentAgentRequestConversation.js.map +1 -0
  10. package/build/cjs/instrumentations/agents/instrumentChatAgentConversation.js +3 -3
  11. package/build/cjs/instrumentations/agents/instrumentChatAgentConversation.js.map +1 -1
  12. package/build/cjs/instrumentations/agents/types.js +58 -13
  13. package/build/cjs/instrumentations/agents/types.js.map +1 -1
  14. package/build/cjs/request.js +3 -2
  15. package/build/cjs/request.js.map +1 -1
  16. package/build/cjs/utils/invocationScope.js +12 -0
  17. package/build/cjs/utils/invocationScope.js.map +1 -0
  18. package/build/cjs/utils/rpcMeta.js +4 -0
  19. package/build/cjs/utils/rpcMeta.js.map +1 -1
  20. package/build/cjs/workflows.js +1 -1
  21. package/build/cjs/workflows.js.map +1 -1
  22. package/build/cjs/wrapMethodWithSentry.js +2 -3
  23. package/build/cjs/wrapMethodWithSentry.js.map +1 -1
  24. package/build/esm/durableobject.js +117 -39
  25. package/build/esm/durableobject.js.map +1 -1
  26. package/build/esm/flush.js.map +1 -1
  27. package/build/esm/instrumentations/agents/index.js +2 -0
  28. package/build/esm/instrumentations/agents/index.js.map +1 -1
  29. package/build/esm/instrumentations/agents/instrumentAgentCallableRpc.js +2 -2
  30. package/build/esm/instrumentations/agents/instrumentAgentCallableRpc.js.map +1 -1
  31. package/build/esm/instrumentations/agents/instrumentAgentRequestConversation.js +17 -0
  32. package/build/esm/instrumentations/agents/instrumentAgentRequestConversation.js.map +1 -0
  33. package/build/esm/instrumentations/agents/instrumentChatAgentConversation.js +4 -4
  34. package/build/esm/instrumentations/agents/instrumentChatAgentConversation.js.map +1 -1
  35. package/build/esm/instrumentations/agents/types.js +56 -13
  36. package/build/esm/instrumentations/agents/types.js.map +1 -1
  37. package/build/esm/package.json +1 -1
  38. package/build/esm/request.js +4 -3
  39. package/build/esm/request.js.map +1 -1
  40. package/build/esm/utils/invocationScope.js +10 -0
  41. package/build/esm/utils/invocationScope.js.map +1 -0
  42. package/build/esm/utils/rpcMeta.js +4 -1
  43. package/build/esm/utils/rpcMeta.js.map +1 -1
  44. package/build/esm/workflows.js +2 -2
  45. package/build/esm/workflows.js.map +1 -1
  46. package/build/esm/wrapMethodWithSentry.js +3 -4
  47. package/build/esm/wrapMethodWithSentry.js.map +1 -1
  48. package/build/types/durableobject.d.ts +17 -8
  49. package/build/types/durableobject.d.ts.map +1 -1
  50. package/build/types/flush.d.ts +1 -1
  51. package/build/types/flush.d.ts.map +1 -1
  52. package/build/types/instrumentations/agents/index.d.ts +4 -3
  53. package/build/types/instrumentations/agents/index.d.ts.map +1 -1
  54. package/build/types/instrumentations/agents/instrumentAgentCallableRpc.d.ts +4 -1
  55. package/build/types/instrumentations/agents/instrumentAgentCallableRpc.d.ts.map +1 -1
  56. package/build/types/instrumentations/agents/instrumentAgentRequestConversation.d.ts +16 -0
  57. package/build/types/instrumentations/agents/instrumentAgentRequestConversation.d.ts.map +1 -0
  58. package/build/types/instrumentations/agents/instrumentChatAgentConversation.d.ts +10 -9
  59. package/build/types/instrumentations/agents/instrumentChatAgentConversation.d.ts.map +1 -1
  60. package/build/types/instrumentations/agents/types.d.ts +63 -18
  61. package/build/types/instrumentations/agents/types.d.ts.map +1 -1
  62. package/build/types/request.d.ts.map +1 -1
  63. package/build/types/utils/invocationScope.d.ts +24 -0
  64. package/build/types/utils/invocationScope.d.ts.map +1 -0
  65. package/build/types/utils/rpcMeta.d.ts +8 -0
  66. package/build/types/utils/rpcMeta.d.ts.map +1 -1
  67. package/build/types/wrapMethodWithSentry.d.ts +1 -1
  68. package/build/types/wrapMethodWithSentry.d.ts.map +1 -1
  69. package/build/types-ts3.8/durableobject.d.ts +17 -8
  70. package/build/types-ts3.8/flush.d.ts +1 -1
  71. package/build/types-ts3.8/instrumentations/agents/index.d.ts +4 -3
  72. package/build/types-ts3.8/instrumentations/agents/instrumentAgentCallableRpc.d.ts +4 -1
  73. package/build/types-ts3.8/instrumentations/agents/instrumentAgentRequestConversation.d.ts +16 -0
  74. package/build/types-ts3.8/instrumentations/agents/instrumentChatAgentConversation.d.ts +10 -9
  75. package/build/types-ts3.8/instrumentations/agents/types.d.ts +63 -18
  76. package/build/types-ts3.8/utils/invocationScope.d.ts +24 -0
  77. package/build/types-ts3.8/utils/rpcMeta.d.ts +8 -0
  78. package/build/types-ts3.8/wrapMethodWithSentry.d.ts +1 -1
  79. package/package.json +3 -3
@@ -1 +1 @@
1
- {"version":3,"file":"workflows.js","sources":["../../src/workflows.ts"],"sourcesContent":["import type { PropagationContext } from '@sentry/core';\nimport {\n captureException,\n flush,\n getCurrentScope,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,\n startSpan,\n withIsolationScope,\n withScope,\n} from '@sentry/core';\nimport type {\n WorkflowDelayDuration,\n WorkflowEntrypoint,\n WorkflowEvent,\n WorkflowSleepDuration,\n WorkflowStep,\n WorkflowStepConfig,\n WorkflowStepContext,\n WorkflowStepEvent,\n WorkflowStepRollbackOptions,\n WorkflowTimeoutDuration,\n} from 'cloudflare:workers';\nimport { setAsyncLocalStorageAsyncContextStrategy } from './async';\nimport type { CloudflareOptions } from './client';\nimport { flushAndDispose } from './flush';\nimport { instrumentEnv } from './instrumentations/worker/instrumentEnv';\nimport { addCloudResourceContext } from './scope-utils';\nimport { init } from './sdk';\nimport { instrumentContext } from './utils/instrumentContext';\n\nconst UUID_REGEX = /^[0-9a-f]{8}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{12}$/i;\n\n/**\n * Hashes a string to a UUID using SHA-1.\n */\nexport async function deterministicTraceIdFromInstanceId(instanceId: string): Promise<string> {\n const buf = await crypto.subtle.digest('SHA-1', new TextEncoder().encode(instanceId));\n return (\n Array.from(new Uint8Array(buf))\n // We only need the first 16 bytes for the 32 characters\n .slice(0, 16)\n .map(b => b.toString(16).padStart(2, '0'))\n .join('')\n );\n}\n\nasync function propagationContextFromInstanceId(instanceId: string): Promise<PropagationContext> {\n const traceId = UUID_REGEX.test(instanceId)\n ? instanceId.replace(/-/g, '')\n : await deterministicTraceIdFromInstanceId(instanceId);\n\n // Derive sampleRand from last 4 characters of the random UUID\n //\n // We cannot store any state between workflow steps, so we derive the\n // sampleRand from the traceId itself. This ensures that the sampling is\n // consistent across all steps in the same workflow instance.\n const sampleRand = parseInt(traceId.slice(-4), 16) / 0xffff;\n\n return {\n traceId,\n sampleRand,\n };\n}\n\nclass WrappedWorkflowStep implements WorkflowStep {\n public constructor(\n private _instanceId: string,\n private _options: CloudflareOptions,\n private _step: WorkflowStep,\n private _waitUntil: ExecutionContext['waitUntil'],\n ) {}\n\n public async do<T extends Rpc.Serializable<T>>(\n name: string,\n callback: (ctx: WorkflowStepContext) => Promise<T>,\n rollbackOptions?: WorkflowStepRollbackOptions<T>,\n ): Promise<T>;\n public async do<T extends Rpc.Serializable<T>, const C extends WorkflowStepConfig>(\n name: string,\n config: C,\n callback: (\n ctx: WorkflowStepContext<C['retries'] extends { delay: infer D } ? D : WorkflowDelayDuration | number>,\n ) => Promise<T>,\n rollbackOptions?: WorkflowStepRollbackOptions<T>,\n ): Promise<T>;\n public async do<T extends Rpc.Serializable<T>>(\n name: string,\n configOrCallback: WorkflowStepConfig | ((ctx: WorkflowStepContext) => Promise<T>),\n callbackOrRollback?: ((ctx: WorkflowStepContext) => Promise<T>) | WorkflowStepRollbackOptions<T>,\n maybeRollback?: WorkflowStepRollbackOptions<T>,\n ): Promise<T> {\n // Capture the current scope, so parent span (e.g., a startSpan surrounding step.do) is preserved\n const scopeForStep = getCurrentScope();\n\n const hasConfig = typeof configOrCallback !== 'function';\n const config = hasConfig ? configOrCallback : undefined;\n const userCallback = (hasConfig ? callbackOrRollback : configOrCallback) as (\n ctx: WorkflowStepContext,\n ) => Promise<T>;\n const rollbackOptions = (hasConfig ? maybeRollback : callbackOrRollback) as\n | WorkflowStepRollbackOptions<T>\n | undefined;\n\n const instrumentedCallback = async (...args: unknown[]): Promise<T> => {\n // Feature detection: Cloudflare Workflows (April 2026+) pass a step context\n // with `attempt` and `config.retries.limit`. When available, we only capture\n // errors on the final attempt to avoid duplicates during retries.\n const stepContext = args[0] as { attempt?: number; config?: { retries?: { limit?: number } } } | undefined;\n const attempt = stepContext?.attempt;\n const retryLimit = stepContext?.config?.retries?.limit;\n const hasStepContext = typeof attempt === 'number' && typeof retryLimit === 'number';\n\n // Only capture error on final attempt (attempt > retryLimit means no more retries left)\n // or when step context is unavailable (legacy behavior - capture all errors)\n const isFinalAttempt = !hasStepContext || attempt > retryLimit;\n\n return startSpan(\n {\n op: 'function.step.do',\n name,\n scope: scopeForStep,\n attributes: {\n 'cloudflare.workflow.timeout': config?.timeout,\n 'cloudflare.workflow.retries.backoff': config?.retries?.backoff,\n // In workers-types v5, `delay` may be a `WorkflowDelayFunction`, which isn't a valid span attribute value.\n 'cloudflare.workflow.retries.delay':\n typeof config?.retries?.delay === 'function' ? undefined : config?.retries?.delay,\n 'cloudflare.workflow.retries.limit': config?.retries?.limit,\n 'cloudflare.workflow.attempt': attempt,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.faas.cloudflare.workflow',\n [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'task',\n },\n },\n async span => {\n try {\n const result = await (userCallback as (...args: unknown[]) => Promise<T>)(...args);\n span.setStatus({ code: 1 });\n return result;\n } catch (error) {\n if (isFinalAttempt) {\n captureException(error, { mechanism: { handled: true, type: 'auto.faas.cloudflare.workflow' } });\n }\n throw error;\n } finally {\n this._waitUntil(flush(2000));\n }\n },\n );\n };\n\n if (config) {\n return rollbackOptions\n ? this._step.do(name, config, instrumentedCallback, rollbackOptions)\n : this._step.do(name, config, instrumentedCallback);\n }\n\n return rollbackOptions\n ? this._step.do(name, instrumentedCallback, rollbackOptions)\n : this._step.do(name, instrumentedCallback);\n }\n\n public async sleep(name: string, duration: WorkflowSleepDuration): Promise<void> {\n return this._step.sleep(name, duration);\n }\n\n public async sleepUntil(name: string, timestamp: Date | number): Promise<void> {\n return this._step.sleepUntil(name, timestamp);\n }\n\n public async waitForEvent<T extends Rpc.Serializable<T>>(\n name: string,\n options: { type: string; timeout?: WorkflowTimeoutDuration | number },\n ): Promise<WorkflowStepEvent<T>> {\n return this._step.waitForEvent<T>(name, options);\n }\n}\n\n/**\n * Instruments a Cloudflare Workflow class with Sentry.\n *\n * @example\n * ```typescript\n * const InstrumentedWorkflow = instrumentWorkflowWithSentry(\n * (env) => ({ dsn: env.SENTRY_DSN }),\n * MyWorkflowClass\n * );\n *\n * export default InstrumentedWorkflow;\n * ```\n *\n * @param optionsCallback - Function that returns Sentry options to initialize Sentry\n * @param WorkflowClass - The workflow class to instrument\n * @returns Instrumented workflow class with the same interface\n */\nexport function instrumentWorkflowWithSentry<\n E, // Environment type\n P, // Payload type\n T extends WorkflowEntrypoint<E, P>, // WorkflowEntrypoint type\n C extends new (ctx: ExecutionContext, env: E) => T, // Constructor type of the WorkflowEntrypoint class\n>(optionsCallback: (env: E) => CloudflareOptions, WorkFlowClass: C): C {\n return new Proxy(WorkFlowClass, {\n construct(target: C, args: [ctx: ExecutionContext, env: E], newTarget) {\n const [ctx, env] = args;\n const context = instrumentContext(ctx);\n const options = optionsCallback(env);\n args[0] = context;\n args[1] = instrumentEnv(env as Record<string, unknown>, options) as E;\n const instance = Reflect.construct(target, args, newTarget) as T;\n return new Proxy(instance, {\n get(obj, prop, receiver) {\n if (prop === 'run') {\n return async function (event: WorkflowEvent<P>, step: WorkflowStep): Promise<unknown> {\n setAsyncLocalStorageAsyncContextStrategy();\n\n return withIsolationScope(async isolationScope => {\n const waitUntil = context.waitUntil.bind(context);\n const client = init({ ...options, ctx: context, enableDedupe: false });\n isolationScope.setClient(client);\n\n addCloudResourceContext(isolationScope);\n\n return withScope(async scope => {\n const propagationContext = await propagationContextFromInstanceId(event.instanceId);\n scope.setPropagationContext(propagationContext);\n\n try {\n return await obj.run.call(\n obj,\n event,\n new WrappedWorkflowStep(event.instanceId, options, step, waitUntil),\n );\n } finally {\n waitUntil(flushAndDispose(client));\n }\n });\n });\n };\n }\n return Reflect.get(obj, prop, receiver);\n },\n });\n },\n });\n}\n"],"names":[],"mappings":";;;;;;;;AA+BA,MAAM,UAAA,GAAa,qEAAA;AAKnB,eAAsB,mCAAmC,UAAA,EAAqC;AAC5F,EAAA,MAAM,GAAA,GAAM,MAAM,MAAA,CAAO,MAAA,CAAO,MAAA,CAAO,OAAA,EAAS,IAAI,WAAA,EAAY,CAAE,MAAA,CAAO,UAAU,CAAC,CAAA;AACpF,EAAA,OACE,KAAA,CAAM,KAAK,IAAI,UAAA,CAAW,GAAG,CAAC,CAAA,CAE3B,KAAA,CAAM,CAAA,EAAG,EAAE,CAAA,CACX,IAAI,CAAA,CAAA,KAAK,CAAA,CAAE,QAAA,CAAS,EAAE,CAAA,CAAE,QAAA,CAAS,GAAG,GAAG,CAAC,CAAA,CACxC,IAAA,CAAK,EAAE,CAAA;AAEd;AAEA,eAAe,iCAAiC,UAAA,EAAiD;AAC/F,EAAA,MAAM,OAAA,GAAU,UAAA,CAAW,IAAA,CAAK,UAAU,CAAA,GACtC,UAAA,CAAW,OAAA,CAAQ,IAAA,EAAM,EAAE,CAAA,GAC3B,MAAM,kCAAA,CAAmC,UAAU,CAAA;AAOvD,EAAA,MAAM,aAAa,QAAA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UAAA,IAAI,SAAS,KAAA,EAAO;AAClB,YAAA,OAAO,eAAgB,OAAyB,IAAA,EAAsC;AACpF,cAAA,wCAAA,EAAyC;AAEzC,cAAA,OAAO,kBAAA,CAAmB,OAAM,cAAA,KAAkB;AAChD,gBAAA,MAAM,SAAA,GAAY,OAAA,CAAQ,SAAA,CAAU,IAAA,CAAK,OAAO,CAAA;AAChD,gBAAA,MAAM,MAAA,GAAS,KAAK,EAAE,GAAG,SAAS,GAAA,EAAK,OAAA,EAAS,YAAA,EAAc,KAAA,EAAO,CAAA;AACrE,gBAAA,cAAA,CAAe,UAAU,MAAM,CAAA;AAE/B,gBAAA,uBAAA,CAAwB,cAAc,CAAA;AAEtC,gBAAA,OAAO,SAAA,CAAU,OAAM,KAAA,KAAS;AAC9B,kBAAA,MAAM,kBAAA,GAAqB,MAAM,gCAAA,CAAiC,KAAA,CAAM,UAAU,CAAA;AAClF,kBAAA,KAAA,CAAM,sBAAsB,kBAAkB,CAAA;AAE9C,kBAAA,IAAI;AACF,oBAAA,OAAO,MAAM,IAAI,GAAA,CAAI,IAAA;AAAA,sBACnB,GAAA;AAAA,sBACA,KAAA;AAAA,sBACA,IAAI,mBAAA,CAAoB,KAAA,CAAM,UAAA,EAAY,OAAA,EAAS,MAAM,SAAS;AAAA,qBACpE;AAAA,kBACF,CAAA,SAAE;AACA,oBAAA,SAAA,CAAU,eAAA,CAAgB,MAAM,CAAC,CAAA;AAAA,kBACnC;AAAA,gBACF,CAAC,CAAA;AAAA,cACH,CAAC,CAAA;AAAA,YACH,CAAA;AAAA,UACF;AACA,UAAA,OAAO,OAAA,CAAQ,GAAA,CAAI,GAAA,EAAK,IAAA,EAAM,QAAQ,CAAA;AAAA,QACxC;AAAA,OACD,CAAA;AAAA,IACH;AAAA,GACD,CAAA;AACH;;;;"}
1
+ {"version":3,"file":"workflows.js","sources":["../../src/workflows.ts"],"sourcesContent":["import type { PropagationContext } from '@sentry/core';\nimport {\n captureException,\n flush,\n getCurrentScope,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,\n startSpan,\n withIsolationScope,\n withScope,\n} from '@sentry/core';\nimport type {\n WorkflowDelayDuration,\n WorkflowEntrypoint,\n WorkflowEvent,\n WorkflowSleepDuration,\n WorkflowStep,\n WorkflowStepConfig,\n WorkflowStepContext,\n WorkflowStepEvent,\n WorkflowStepRollbackOptions,\n WorkflowTimeoutDuration,\n} from 'cloudflare:workers';\nimport { setAsyncLocalStorageAsyncContextStrategy } from './async';\nimport type { CloudflareOptions } from './client';\nimport { flushAndDispose, getOriginalWaitUntil } from './flush';\nimport { instrumentEnv } from './instrumentations/worker/instrumentEnv';\nimport { addCloudResourceContext } from './scope-utils';\nimport { init } from './sdk';\nimport { instrumentContext } from './utils/instrumentContext';\n\nconst UUID_REGEX = /^[0-9a-f]{8}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{12}$/i;\n\n/**\n * Hashes a string to a UUID using SHA-1.\n */\nexport async function deterministicTraceIdFromInstanceId(instanceId: string): Promise<string> {\n const buf = await crypto.subtle.digest('SHA-1', new TextEncoder().encode(instanceId));\n return (\n Array.from(new Uint8Array(buf))\n // We only need the first 16 bytes for the 32 characters\n .slice(0, 16)\n .map(b => b.toString(16).padStart(2, '0'))\n .join('')\n );\n}\n\nasync function propagationContextFromInstanceId(instanceId: string): Promise<PropagationContext> {\n const traceId = UUID_REGEX.test(instanceId)\n ? instanceId.replace(/-/g, '')\n : await deterministicTraceIdFromInstanceId(instanceId);\n\n // Derive sampleRand from last 4 characters of the random UUID\n //\n // We cannot store any state between workflow steps, so we derive the\n // sampleRand from the traceId itself. This ensures that the sampling is\n // consistent across all steps in the same workflow instance.\n const sampleRand = parseInt(traceId.slice(-4), 16) / 0xffff;\n\n return {\n traceId,\n sampleRand,\n };\n}\n\nclass WrappedWorkflowStep implements WorkflowStep {\n public constructor(\n private _instanceId: string,\n private _options: CloudflareOptions,\n private _step: WorkflowStep,\n private _waitUntil: ExecutionContext['waitUntil'],\n ) {}\n\n public async do<T extends Rpc.Serializable<T>>(\n name: string,\n callback: (ctx: WorkflowStepContext) => Promise<T>,\n rollbackOptions?: WorkflowStepRollbackOptions<T>,\n ): Promise<T>;\n public async do<T extends Rpc.Serializable<T>, const C extends WorkflowStepConfig>(\n name: string,\n config: C,\n callback: (\n ctx: WorkflowStepContext<C['retries'] extends { delay: infer D } ? D : WorkflowDelayDuration | number>,\n ) => Promise<T>,\n rollbackOptions?: WorkflowStepRollbackOptions<T>,\n ): Promise<T>;\n public async do<T extends Rpc.Serializable<T>>(\n name: string,\n configOrCallback: WorkflowStepConfig | ((ctx: WorkflowStepContext) => Promise<T>),\n callbackOrRollback?: ((ctx: WorkflowStepContext) => Promise<T>) | WorkflowStepRollbackOptions<T>,\n maybeRollback?: WorkflowStepRollbackOptions<T>,\n ): Promise<T> {\n // Capture the current scope, so parent span (e.g., a startSpan surrounding step.do) is preserved\n const scopeForStep = getCurrentScope();\n\n const hasConfig = typeof configOrCallback !== 'function';\n const config = hasConfig ? configOrCallback : undefined;\n const userCallback = (hasConfig ? callbackOrRollback : configOrCallback) as (\n ctx: WorkflowStepContext,\n ) => Promise<T>;\n const rollbackOptions = (hasConfig ? maybeRollback : callbackOrRollback) as\n | WorkflowStepRollbackOptions<T>\n | undefined;\n\n const instrumentedCallback = async (...args: unknown[]): Promise<T> => {\n // Feature detection: Cloudflare Workflows (April 2026+) pass a step context\n // with `attempt` and `config.retries.limit`. When available, we only capture\n // errors on the final attempt to avoid duplicates during retries.\n const stepContext = args[0] as { attempt?: number; config?: { retries?: { limit?: number } } } | undefined;\n const attempt = stepContext?.attempt;\n const retryLimit = stepContext?.config?.retries?.limit;\n const hasStepContext = typeof attempt === 'number' && typeof retryLimit === 'number';\n\n // Only capture error on final attempt (attempt > retryLimit means no more retries left)\n // or when step context is unavailable (legacy behavior - capture all errors)\n const isFinalAttempt = !hasStepContext || attempt > retryLimit;\n\n return startSpan(\n {\n op: 'function.step.do',\n name,\n scope: scopeForStep,\n attributes: {\n 'cloudflare.workflow.timeout': config?.timeout,\n 'cloudflare.workflow.retries.backoff': config?.retries?.backoff,\n // In workers-types v5, `delay` may be a `WorkflowDelayFunction`, which isn't a valid span attribute value.\n 'cloudflare.workflow.retries.delay':\n typeof config?.retries?.delay === 'function' ? undefined : config?.retries?.delay,\n 'cloudflare.workflow.retries.limit': config?.retries?.limit,\n 'cloudflare.workflow.attempt': attempt,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.faas.cloudflare.workflow',\n [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'task',\n },\n },\n async span => {\n try {\n const result = await (userCallback as (...args: unknown[]) => Promise<T>)(...args);\n span.setStatus({ code: 1 });\n return result;\n } catch (error) {\n if (isFinalAttempt) {\n captureException(error, { mechanism: { handled: true, type: 'auto.faas.cloudflare.workflow' } });\n }\n throw error;\n } finally {\n this._waitUntil(flush(2000));\n }\n },\n );\n };\n\n if (config) {\n return rollbackOptions\n ? this._step.do(name, config, instrumentedCallback, rollbackOptions)\n : this._step.do(name, config, instrumentedCallback);\n }\n\n return rollbackOptions\n ? this._step.do(name, instrumentedCallback, rollbackOptions)\n : this._step.do(name, instrumentedCallback);\n }\n\n public async sleep(name: string, duration: WorkflowSleepDuration): Promise<void> {\n return this._step.sleep(name, duration);\n }\n\n public async sleepUntil(name: string, timestamp: Date | number): Promise<void> {\n return this._step.sleepUntil(name, timestamp);\n }\n\n public async waitForEvent<T extends Rpc.Serializable<T>>(\n name: string,\n options: { type: string; timeout?: WorkflowTimeoutDuration | number },\n ): Promise<WorkflowStepEvent<T>> {\n return this._step.waitForEvent<T>(name, options);\n }\n}\n\n/**\n * Instruments a Cloudflare Workflow class with Sentry.\n *\n * @example\n * ```typescript\n * const InstrumentedWorkflow = instrumentWorkflowWithSentry(\n * (env) => ({ dsn: env.SENTRY_DSN }),\n * MyWorkflowClass\n * );\n *\n * export default InstrumentedWorkflow;\n * ```\n *\n * @param optionsCallback - Function that returns Sentry options to initialize Sentry\n * @param WorkflowClass - The workflow class to instrument\n * @returns Instrumented workflow class with the same interface\n */\nexport function instrumentWorkflowWithSentry<\n E, // Environment type\n P, // Payload type\n T extends WorkflowEntrypoint<E, P>, // WorkflowEntrypoint type\n C extends new (ctx: ExecutionContext, env: E) => T, // Constructor type of the WorkflowEntrypoint class\n>(optionsCallback: (env: E) => CloudflareOptions, WorkFlowClass: C): C {\n return new Proxy(WorkFlowClass, {\n construct(target: C, args: [ctx: ExecutionContext, env: E], newTarget) {\n const [ctx, env] = args;\n const context = instrumentContext(ctx);\n const options = optionsCallback(env);\n args[0] = context;\n args[1] = instrumentEnv(env as Record<string, unknown>, options) as E;\n const instance = Reflect.construct(target, args, newTarget) as T;\n return new Proxy(instance, {\n get(obj, prop, receiver) {\n if (prop === 'run') {\n return async function (event: WorkflowEvent<P>, step: WorkflowStep): Promise<unknown> {\n setAsyncLocalStorageAsyncContextStrategy();\n\n return withIsolationScope(async isolationScope => {\n const waitUntil = getOriginalWaitUntil(context).bind(context);\n const client = init({ ...options, ctx: context, enableDedupe: false });\n isolationScope.setClient(client);\n\n addCloudResourceContext(isolationScope);\n\n return withScope(async scope => {\n const propagationContext = await propagationContextFromInstanceId(event.instanceId);\n scope.setPropagationContext(propagationContext);\n\n try {\n return await obj.run.call(\n obj,\n event,\n new WrappedWorkflowStep(event.instanceId, options, step, waitUntil),\n );\n } finally {\n waitUntil(flushAndDispose(client));\n }\n });\n });\n };\n }\n return Reflect.get(obj, prop, receiver);\n },\n });\n },\n });\n}\n"],"names":[],"mappings":";;;;;;;;AA+BA,MAAM,UAAA,GAAa,qEAAA;AAKnB,eAAsB,mCAAmC,UAAA,EAAqC;AAC5F,EAAA,MAAM,GAAA,GAAM,MAAM,MAAA,CAAO,MAAA,CAAO,MAAA,CAAO,OAAA,EAAS,IAAI,WAAA,EAAY,CAAE,MAAA,CAAO,UAAU,CAAC,CAAA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,KAAA,CAAM,UAAA,EAAY,OAAA,EAAS,MAAM,SAAS;AAAA,qBACpE;AAAA,kBACF,CAAA,SAAE;AACA,oBAAA,SAAA,CAAU,eAAA,CAAgB,MAAM,CAAC,CAAA;AAAA,kBACnC;AAAA,gBACF,CAAC,CAAA;AAAA,cACH,CAAC,CAAA;AAAA,YACH,CAAA;AAAA,UACF;AACA,UAAA,OAAO,OAAA,CAAQ,GAAA,CAAI,GAAA,EAAK,IAAA,EAAM,QAAQ,CAAA;AAAA,QACxC;AAAA,OACD,CAAA;AAAA,IACH;AAAA,GACD,CAAA;AACH;;;;"}
@@ -1,7 +1,8 @@
1
- import { getClient, withIsolationScope, withScope, isThenable, SEMANTIC_ATTRIBUTE_SENTRY_OP, continueTrace, startNewTrace, captureException, startSpan, isObjectLike, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN } from '@sentry/core';
1
+ import { isThenable, SEMANTIC_ATTRIBUTE_SENTRY_OP, continueTrace, startNewTrace, captureException, startSpan, isObjectLike, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN } from '@sentry/core';
2
2
  import { getOriginalWaitUntil, flushAndDispose } from './flush.js';
3
3
  import { ensureInstrumented } from './instrument.js';
4
4
  import { init } from './sdk.js';
5
+ import { withInvocationIsolationScope } from './utils/invocationScope.js';
5
6
  import { extractRpcMeta } from './utils/rpcMeta.js';
6
7
  import { getStoredSpanContext, buildSpanLinks, storeSpanContext } from './utils/traceLinks.js';
7
8
 
@@ -30,8 +31,6 @@ function wrapMethodWithSentry(wrapperOptions, handler, callback, noMark) {
30
31
  args = extracted.args;
31
32
  rpcMeta = extracted.rpcMeta;
32
33
  }
33
- const currentClient = getClient();
34
- const sentryWithScope = startNewTrace$1 ? withIsolationScope : currentClient ? withScope : withIsolationScope;
35
34
  const wrappedFunction = (scope) => {
36
35
  const context = wrapperOptions.context;
37
36
  const waitUntil = context ? getOriginalWaitUntil(context)?.bind(context) : void 0;
@@ -122,7 +121,7 @@ function wrapMethodWithSentry(wrapperOptions, handler, callback, noMark) {
122
121
  }
123
122
  return executeSpan();
124
123
  };
125
- return sentryWithScope(wrappedFunction);
124
+ return withInvocationIsolationScope(wrappedFunction);
126
125
  }
127
126
  }),
128
127
  noMark
@@ -1 +1 @@
1
- {"version":3,"file":"wrapMethodWithSentry.js","sources":["../../src/wrapMethodWithSentry.ts"],"sourcesContent":["import type { DurableObjectStorage } from '@cloudflare/workers-types';\nimport type { SerializedTraceData } from '@sentry/core';\nimport {\n isObjectLike,\n captureException,\n continueTrace,\n getClient,\n isThenable,\n type Scope,\n SEMANTIC_ATTRIBUTE_SENTRY_OP,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n startNewTrace as startNewTraceCore,\n startSpan,\n withIsolationScope,\n withScope,\n} from '@sentry/core';\nimport type { CloudflareOptions } from './client';\nimport type { ExecutionContextCompat } from './executionContext';\nimport { flushAndDispose, getOriginalWaitUntil } from './flush';\nimport { ensureInstrumented } from './instrument';\nimport { init } from './sdk';\nimport { extractRpcMeta } from './utils/rpcMeta';\nimport { buildSpanLinks, getStoredSpanContext, storeSpanContext } from './utils/traceLinks';\n\n/** Extended DurableObjectState with originalStorage exposed by instrumentContext */\ninterface InstrumentedDurableObjectState extends DurableObjectState {\n originalStorage?: DurableObjectStorage;\n}\n\n/**\n * Resolves uninstrumented DO storage for the current invocation.\n * Prefer `thisArg.ctx` (the live Durable Object instance) over the context captured at\n * construction time to avoid cross-DO I/O errors in the same isolate.\n */\nfunction resolveOriginalStorage(\n context: ExecutionContext | InstrumentedDurableObjectState | undefined,\n thisArg: unknown,\n): DurableObjectStorage | undefined {\n if (isObjectLike(thisArg) && 'ctx' in thisArg) {\n const doCtx = (thisArg as { ctx: InstrumentedDurableObjectState }).ctx;\n if (doCtx?.originalStorage) {\n return doCtx.originalStorage;\n }\n }\n\n if (context && 'originalStorage' in context && context.originalStorage) {\n return context.originalStorage;\n }\n\n return undefined;\n}\n\ntype MethodWrapperOptions = {\n spanName?: string;\n spanOp?: string;\n options: CloudflareOptions;\n context: ExecutionContext | InstrumentedDurableObjectState;\n /**\n * If true, starts a fresh trace instead of inheriting from a parent trace.\n * Useful for scheduled/independent invocations like alarms.\n *\n * If true, it also stores the current span context and links to the previous invocation's span.\n * Uses Durable Object storage to persist the link. The link is set asynchronously via `span.addLinks()`\n * in a `waitUntil` to avoid blocking.\n *\n * @default false\n */\n startNewTrace?: boolean;\n /**\n * The trace origin identifying which instrumentation created the span, e.g. `auto.faas.cloudflare.durable_object`.\n * Used both as the span's `sentry.origin` attribute and as the `mechanism.type` for captured exceptions.\n */\n origin: string;\n};\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type UncheckedMethod = (...args: any[]) => any;\ntype OriginalMethod = UncheckedMethod;\n\n/**\n * Wraps a method with Sentry error tracking and optional tracing.\n * Supports starting new traces and linking to previous invocations via Durable Object storage.\n *\n * @param wrapperOptions - The options for the wrapper.\n * @param handler - The method to wrap.\n * @param callback - The callback to call.\n * @param noMark - Whether to mark the method as instrumented.\n * @returns The wrapped method.\n */\nexport function wrapMethodWithSentry<T extends OriginalMethod>(\n wrapperOptions: MethodWrapperOptions,\n handler: T,\n callback?: (...args: Parameters<T>) => void,\n noMark?: true,\n): T {\n return ensureInstrumented(\n handler,\n original =>\n new Proxy(original, {\n apply(target, thisArg, rawArgs: Parameters<T>) {\n const { startNewTrace, origin } = wrapperOptions;\n\n // For RPC methods, extract Sentry trace context from the trailing argument.\n // The caller side (instrumentDurableObjectStub / JSRPC proxy) appends it;\n // we strip it here so the user's method never sees it.\n let args = rawArgs;\n let rpcMeta: SerializedTraceData | undefined;\n\n if (wrapperOptions.spanOp === 'rpc') {\n const extracted = extractRpcMeta(rawArgs);\n args = extracted.args;\n rpcMeta = extracted.rpcMeta;\n }\n\n // For startNewTrace, always use withIsolationScope to ensure a fresh scope\n // Otherwise, use existing client's scope or isolation scope\n const currentClient = getClient();\n const sentryWithScope = startNewTrace ? withIsolationScope : currentClient ? withScope : withIsolationScope;\n\n const wrappedFunction = (scope: Scope): unknown | Promise<unknown> => {\n // In certain situations, the passed context can become undefined.\n // For example, for Astro while prerendering pages at build time.\n // see: https://github.com/getsentry/sentry-javascript/issues/13217\n const context: typeof wrapperOptions.context | undefined = wrapperOptions.context;\n\n // see: https://github.com/getsentry/sentry-javascript/issues/22328\n const waitUntil = context\n ? getOriginalWaitUntil(context as ExecutionContextCompat)?.bind(context)\n : undefined;\n const storage = resolveOriginalStorage(context, thisArg);\n\n let scopeClient = scope.getClient();\n // Check if client exists AND is still usable (transport not disposed)\n // This handles the case where a previous handler disposed the client\n // but the scope still holds a reference to it (e.g., alarm handlers in Durable Objects)\n // For startNewTrace, always create a fresh client\n if (startNewTrace || !scopeClient?.getTransport()) {\n const client = init({\n ...wrapperOptions.options,\n ctx: context as unknown as ExecutionContext | undefined,\n });\n scope.setClient(client);\n scopeClient = client;\n }\n\n const clientToDispose = scopeClient;\n const methodName = wrapperOptions.spanName || 'unknown';\n\n const teardown = async (): Promise<void> => {\n if (startNewTrace && storage) {\n storeSpanContext(storage, methodName);\n }\n await flushAndDispose(clientToDispose);\n };\n\n const onFulfilled = (res: unknown) => {\n waitUntil?.(teardown());\n return res;\n };\n\n const onRejected = (e: unknown) => {\n captureException(e, {\n mechanism: {\n type: origin,\n handled: false,\n },\n });\n waitUntil?.(teardown());\n throw e;\n };\n\n if (!wrapperOptions.spanName) {\n try {\n if (callback) {\n callback(...args);\n }\n\n const result = Reflect.apply(target, thisArg, args);\n\n if (isThenable(result)) {\n return result.then(onFulfilled, onRejected);\n } else {\n return onFulfilled(result);\n }\n } catch (e) {\n return onRejected(e);\n }\n }\n\n const attributes = wrapperOptions.spanOp\n ? {\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: wrapperOptions.spanOp,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: origin,\n }\n : {};\n\n const executeSpan = (): unknown => {\n return startSpan({ name: methodName, attributes }, span => {\n if (startNewTrace && storage) {\n const storedContext = getStoredSpanContext(storage, methodName);\n\n if (storedContext) {\n span.addLinks(buildSpanLinks(storedContext));\n // TODO: Remove this once EAP can store span links. We currently only set this attribute so that we\n // can obtain the previous trace information from the EAP store. Long-term, EAP will handle\n // span links and then we should remove this again. Also throwing in a TODO(v11), to remind us\n // to check this at v11 time :)\n const sampledFlag = storedContext.sampled ? '1' : '0';\n span.setAttribute(\n 'sentry.previous_trace',\n `${storedContext.traceId}-${storedContext.spanId}-${sampledFlag}`,\n );\n }\n }\n\n try {\n const result = Reflect.apply(target, thisArg, args);\n\n if (isThenable(result)) {\n return result.then(onFulfilled, onRejected);\n } else {\n return onFulfilled(result);\n }\n } catch (e) {\n return onRejected(e);\n }\n });\n };\n\n if (rpcMeta) {\n return continueTrace(\n { sentryTrace: rpcMeta['sentry-trace'] || '', baggage: rpcMeta.baggage || '' },\n executeSpan,\n );\n }\n\n if (startNewTrace) {\n return startNewTraceCore(() => executeSpan());\n }\n\n return executeSpan();\n };\n\n return sentryWithScope(wrappedFunction);\n },\n }),\n noMark,\n );\n}\n"],"names":["startNewTrace","startNewTraceCore"],"mappings":";;;;;;;AAkCA,SAAS,sBAAA,CACP,SACA,OAAA,EACkC;AAClC,EAAA,IAAI,YAAA,CAAa,OAAO,CAAA,IAAK,KAAA,IAAS,OAAA,EAAS;AAC7C,IAAA,MAAM,QAAS,OAAA,CAAoD,GAAA;AACnE,IAAA,IAAI,OAAO,eAAA,EAAiB;AAC1B,MAAA,OAAO,KAAA,CAAM,eAAA;AAAA,IACf;AAAA,EACF;AAEA,EAAA,IAAI,OAAA,IAAW,iBAAA,IAAqB,OAAA,IAAW,OAAA,CAAQ,eAAA,EAAiB;AACtE,IAAA,OAAO,OAAA,CAAQ,eAAA;AAAA,EACjB;AAEA,EAAA,OAAO,MAAA;AACT;AAuCO,SAAS,oBAAA,CACd,cAAA,EACA,OAAA,EACA,QAAA,EACA,MAAA,EACG;AACH,EAAA,OAAO,kBAAA;AAAA,IACL,OAAA;AAAA,IACA,CAAA,QA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A,CAAkB,MAAM,WAAA,EAAa,CAAA;AAAA,UAC9C;AAEA,UAAA,OAAO,WAAA,EAAY;AAAA,QACrB,CAAA;AAEA,QAAA,OAAO,gBAAgB,eAAe,CAAA;AAAA,MACxC;AAAA,KACD,CAAA;AAAA,IACH;AAAA,GACF;AACF;;;;"}
1
+ {"version":3,"file":"wrapMethodWithSentry.js","sources":["../../src/wrapMethodWithSentry.ts"],"sourcesContent":["import type { DurableObjectStorage } from '@cloudflare/workers-types';\nimport type { SerializedTraceData } from '@sentry/core';\nimport {\n isObjectLike,\n captureException,\n continueTrace,\n isThenable,\n type Scope,\n SEMANTIC_ATTRIBUTE_SENTRY_OP,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n startNewTrace as startNewTraceCore,\n startSpan,\n} from '@sentry/core';\nimport type { CloudflareOptions } from './client';\nimport type { ExecutionContextCompat } from './executionContext';\nimport { flushAndDispose, getOriginalWaitUntil } from './flush';\nimport { ensureInstrumented } from './instrument';\nimport { init } from './sdk';\nimport { withInvocationIsolationScope } from './utils/invocationScope';\nimport { extractRpcMeta } from './utils/rpcMeta';\nimport { buildSpanLinks, getStoredSpanContext, storeSpanContext } from './utils/traceLinks';\n\n/** Extended DurableObjectState with originalStorage exposed by instrumentContext */\nexport interface InstrumentedDurableObjectState extends DurableObjectState {\n originalStorage?: DurableObjectStorage;\n}\n\n/**\n * Resolves uninstrumented DO storage for the current invocation.\n * Prefer `thisArg.ctx` (the live Durable Object instance) over the context captured at\n * construction time to avoid cross-DO I/O errors in the same isolate.\n */\nfunction resolveOriginalStorage(\n context: ExecutionContext | InstrumentedDurableObjectState | undefined,\n thisArg: unknown,\n): DurableObjectStorage | undefined {\n if (isObjectLike(thisArg) && 'ctx' in thisArg) {\n const doCtx = (thisArg as { ctx: InstrumentedDurableObjectState }).ctx;\n if (doCtx?.originalStorage) {\n return doCtx.originalStorage;\n }\n }\n\n if (context && 'originalStorage' in context && context.originalStorage) {\n return context.originalStorage;\n }\n\n return undefined;\n}\n\ntype MethodWrapperOptions = {\n spanName?: string;\n spanOp?: string;\n options: CloudflareOptions;\n context: ExecutionContext | InstrumentedDurableObjectState;\n /**\n * If true, starts a fresh trace instead of inheriting from a parent trace.\n * Useful for scheduled/independent invocations like alarms.\n *\n * If true, it also stores the current span context and links to the previous invocation's span.\n * Uses Durable Object storage to persist the link. The link is set asynchronously via `span.addLinks()`\n * in a `waitUntil` to avoid blocking.\n *\n * @default false\n */\n startNewTrace?: boolean;\n /**\n * The trace origin identifying which instrumentation created the span, e.g. `auto.faas.cloudflare.durable_object`.\n * Used both as the span's `sentry.origin` attribute and as the `mechanism.type` for captured exceptions.\n */\n origin: string;\n};\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type UncheckedMethod = (...args: any[]) => any;\ntype OriginalMethod = UncheckedMethod;\n\n/**\n * Wraps a method with Sentry error tracking and optional tracing.\n * Supports starting new traces and linking to previous invocations via Durable Object storage.\n *\n * @param wrapperOptions - The options for the wrapper.\n * @param handler - The method to wrap.\n * @param callback - The callback to call.\n * @param noMark - Whether to mark the method as instrumented.\n * @returns The wrapped method.\n */\nexport function wrapMethodWithSentry<T extends OriginalMethod>(\n wrapperOptions: MethodWrapperOptions,\n handler: T,\n callback?: (...args: Parameters<T>) => void,\n noMark?: true,\n): T {\n return ensureInstrumented(\n handler,\n original =>\n new Proxy(original, {\n apply(target, thisArg, rawArgs: Parameters<T>) {\n const { startNewTrace, origin } = wrapperOptions;\n\n // For RPC methods, extract Sentry trace context from the trailing argument.\n // The caller side (instrumentDurableObjectStub / JSRPC proxy) appends it;\n // we strip it here so the user's method never sees it.\n let args = rawArgs;\n let rpcMeta: SerializedTraceData | undefined;\n\n if (wrapperOptions.spanOp === 'rpc') {\n const extracted = extractRpcMeta(rawArgs);\n args = extracted.args;\n rpcMeta = extracted.rpcMeta;\n }\n\n const wrappedFunction = (scope: Scope): unknown | Promise<unknown> => {\n // In certain situations, the passed context can become undefined.\n // For example, for Astro while prerendering pages at build time.\n // see: https://github.com/getsentry/sentry-javascript/issues/13217\n const context: typeof wrapperOptions.context | undefined = wrapperOptions.context;\n\n // see: https://github.com/getsentry/sentry-javascript/issues/22328\n const waitUntil = context\n ? getOriginalWaitUntil(context as ExecutionContextCompat)?.bind(context)\n : undefined;\n const storage = resolveOriginalStorage(context, thisArg);\n\n let scopeClient = scope.getClient();\n // Check if client exists AND is still usable (transport not disposed)\n // This handles the case where a previous handler disposed the client\n // but the scope still holds a reference to it (e.g., alarm handlers in Durable Objects)\n // For startNewTrace, always create a fresh client\n if (startNewTrace || !scopeClient?.getTransport()) {\n const client = init({\n ...wrapperOptions.options,\n ctx: context as unknown as ExecutionContext | undefined,\n });\n scope.setClient(client);\n scopeClient = client;\n }\n\n const clientToDispose = scopeClient;\n const methodName = wrapperOptions.spanName || 'unknown';\n\n const teardown = async (): Promise<void> => {\n if (startNewTrace && storage) {\n storeSpanContext(storage, methodName);\n }\n await flushAndDispose(clientToDispose);\n };\n\n const onFulfilled = (res: unknown) => {\n waitUntil?.(teardown());\n return res;\n };\n\n const onRejected = (e: unknown) => {\n captureException(e, {\n mechanism: {\n type: origin,\n handled: false,\n },\n });\n waitUntil?.(teardown());\n throw e;\n };\n\n if (!wrapperOptions.spanName) {\n try {\n if (callback) {\n callback(...args);\n }\n\n const result = Reflect.apply(target, thisArg, args);\n\n if (isThenable(result)) {\n return result.then(onFulfilled, onRejected);\n } else {\n return onFulfilled(result);\n }\n } catch (e) {\n return onRejected(e);\n }\n }\n\n const attributes = wrapperOptions.spanOp\n ? {\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: wrapperOptions.spanOp,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: origin,\n }\n : {};\n\n const executeSpan = (): unknown => {\n return startSpan({ name: methodName, attributes }, span => {\n if (startNewTrace && storage) {\n const storedContext = getStoredSpanContext(storage, methodName);\n\n if (storedContext) {\n span.addLinks(buildSpanLinks(storedContext));\n // TODO: Remove this once EAP can store span links. We currently only set this attribute so that we\n // can obtain the previous trace information from the EAP store. Long-term, EAP will handle\n // span links and then we should remove this again. Also throwing in a TODO(v11), to remind us\n // to check this at v11 time :)\n const sampledFlag = storedContext.sampled ? '1' : '0';\n span.setAttribute(\n 'sentry.previous_trace',\n `${storedContext.traceId}-${storedContext.spanId}-${sampledFlag}`,\n );\n }\n }\n\n try {\n const result = Reflect.apply(target, thisArg, args);\n\n if (isThenable(result)) {\n return result.then(onFulfilled, onRejected);\n } else {\n return onFulfilled(result);\n }\n } catch (e) {\n return onRejected(e);\n }\n });\n };\n\n if (rpcMeta) {\n return continueTrace(\n { sentryTrace: rpcMeta['sentry-trace'] || '', baggage: rpcMeta.baggage || '' },\n executeSpan,\n );\n }\n\n if (startNewTrace) {\n return startNewTraceCore(() => executeSpan());\n }\n\n return executeSpan();\n };\n\n return withInvocationIsolationScope(wrappedFunction);\n },\n }),\n noMark,\n );\n}\n"],"names":["startNewTrace","startNewTraceCore"],"mappings":";;;;;;;;AAgCA,SAAS,sBAAA,CACP,SACA,OAAA,EACkC;AAClC,EAAA,IAAI,YAAA,CAAa,OAAO,CAAA,IAAK,KAAA,IAAS,OAAA,EAAS;AAC7C,IAAA,MAAM,QAAS,OAAA,CAAoD,GAAA;AACnE,IAAA,IAAI,OAAO,eAAA,EAAiB;AAC1B,MAAA,OAAO,KAAA,CAAM,eAAA;AAAA,IACf;AAAA,EACF;AAEA,EAAA,IAAI,OAAA,IAAW,iBAAA,IAAqB,OAAA,IAAW,OAAA,CAAQ,eAAA,EAAiB;AACtE,IAAA,OAAO,OAAA,CAAQ,eAAA;AAAA,EACjB;AAEA,EAAA,OAAO,MAAA;AACT;AAuCO,SAAS,oBAAA,CACd,cAAA,EACA,OAAA,EACA,QAAA,EACA,MAAA,EACG;AACH,EAAA,OAAO,kBAAA;AAAA,IACL,OAAA;AAAA,IACA,CAAA,QAAA,KACE,IAAI,KAAA,CAAM,QAAA,EAAU;AAAA,MAClB,KAAA,CAAM,MAAA,EAAQ,OAA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@@ type InstrumentedDurableObjectContext = any;
18
18
  *
19
19
  * This is the shared construction path used by both {@link instrumentDurableObjectWithSentry}
20
20
  * and {@link instrumentAgentWithSentry}. It intentionally does NOT apply the RPC prototype-method
21
- * proxy — callers apply that last via {@link finalizeWithRpcInstrumentation}, after any additional
22
- * per-instance instrumentation has been layered onto the returned object.
21
+ * instrumentation — callers apply that last via {@link finalizeWithRpcInstrumentation}, after any
22
+ * additional per-instance instrumentation has been layered onto the returned object.
23
23
  *
24
24
  * @internal
25
25
  */
@@ -27,18 +27,27 @@ export declare function constructInstrumentedDurableObject<E, T extends DurableO
27
27
  obj: T;
28
28
  options: CloudflareOptions;
29
29
  context: InstrumentedDurableObjectContext;
30
+ frameworkManagedMethods: ReadonlySet<string>;
30
31
  };
31
32
  /**
32
- * Wraps a constructed (and already handler-instrumented) Durable Object instance with the RPC
33
- * prototype-method proxy, when RPC trace propagation is enabled. Returns the object unchanged when
34
- * RPC instrumentation is disabled.
33
+ * Adds trace propagation to a constructed Durable Object's RPC methods.
35
34
  *
36
- * This must be applied last, so that any per-instance instrumentation (own properties such as
37
- * `fetch`, `alarm`, or Agent-specific handlers) is excluded from RPC method tracing.
35
+ * RPC methods are wrapped on the prototype because Cloudflare dispatches them with the Durable
36
+ * Object instance as the receiver. This preserves native private-field access and keeps the methods
37
+ * visible to Cloudflare's RPC dispatcher. Built-in handlers, Agent handlers, and methods managed by
38
+ * another framework are left untouched.
38
39
  *
40
+ * Call this after all per-instance instrumentation has been applied. If RPC trace propagation is
41
+ * disabled, the object is returned unchanged.
42
+ *
43
+ * @param obj The constructed Durable Object instance.
44
+ * @param options The resolved SDK options for this instance.
45
+ * @param context The instrumented execution context for this instance.
46
+ * @param excludedMethods Method names owned by another framework and therefore not safe to wrap.
47
+ * @returns The same Durable Object instance, with eligible prototype methods instrumented.
39
48
  * @internal
40
49
  */
41
- export declare function finalizeWithRpcInstrumentation<T extends object>(obj: T, options: CloudflareOptions, context: InstrumentedDurableObjectContext): T;
50
+ export declare function finalizeWithRpcInstrumentation<T extends object>(obj: T, options: CloudflareOptions, context: InstrumentedDurableObjectContext, excludedMethods?: ReadonlySet<string>): T;
42
51
  /**
43
52
  * Instruments a Durable Object class to capture errors and performance data.
44
53
  *
@@ -1 +1 @@
1
- {"version":3,"file":"durableobject.d.ts","sourceRoot":"","sources":["../../src/durableobject.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAExD,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,UAAU,CAAC;AAWlD;;;;;;;;;;GAUG;AAEH,KAAK,gCAAgC,GAAG,GAAG,CAAC;AAE5C;;;;;;;;;;GAUG;AACH,wBAAgB,kCAAkC,CAAC,CAAC,EAAE,CAAC,SAAS,aAAa,CAAC,CAAC,CAAC,EAC9E,MAAM,EAAE,KAAK,KAAK,EAAE,kBAAkB,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC,EACpD,GAAG,EAAE,kBAAkB,EACvB,GAAG,EAAE,CAAC,EACN,SAAS,EAAE,eAAe,EAC1B,eAAe,EAAE,CAAC,GAAG,EAAE,CAAC,KAAK,iBAAiB,GAC7C;IAAE,GAAG,EAAE,CAAC,CAAC;IAAC,OAAO,EAAE,iBAAiB,CAAC;IAAC,OAAO,EAAE,gCAAgC,CAAA;CAAE,CAiBnF;AAgFD;;;;;;;;;GASG;AACH,wBAAgB,8BAA8B,CAAC,CAAC,SAAS,MAAM,EAC7D,GAAG,EAAE,CAAC,EACN,OAAO,EAAE,iBAAiB,EAC1B,OAAO,EAAE,gCAAgC,GACxC,CAAC,CAoFH;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,wBAAgB,iCAAiC,CAC/C,CAAC,EACD,CAAC,SAAS,aAAa,CAAC,CAAC,CAAC,EAC1B,CAAC,SAAS,KAAK,KAAK,EAAE,kBAAkB,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC,EACtD,eAAe,EAAE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AAC,EACN,OAAO,EAAE,iBAAiB,EAC1B,OAAO,EAAE,gCAAgC,EACzC,eAAe,CAAC,EAAE,WAAW,CAAC,MAAM,CAAC,GACpC,CAAC,CA0BH;AAqHD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,wBAAgB,iCAAiC,CAC/C,CAAC,EACD,CAAC,SAAS,aAAa,CAAC,CAAC,CAAC,EAC1B,CAAC,SAAS,KAAK,KAAK,EAAE,kBAAkB,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC,EACtD,eAAe,EAAE,CAAC,GAAG,EAAE,CAAC,KAAK,iBAAiB,EAAE,kBAAkB,EAAE,CAAC,GAAG,CAAC,CAc1E;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AACH,wBAAgB,yBAAyB,CACvC,CAAC,EACD,CAAC,SAAS,aAAa,CAAC,CAAC,CAAC,EAC1B,CAAC,SAAS,KAAK,KAAK,EAAE,kBAAkB,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC,EACtD,eAAe,EAAE,CAAC,GAAG,EAAE,CAAC,KAAK,iBAAiB,EAAE,UAAU,EAAE,CAAC,GAAG,CAAC,CAoBlE"}
@@ -19,7 +19,7 @@ type FlushLock = {
19
19
  *
20
20
  * By using the original waitUntil for flush operations, we bypass this issue.
21
21
  */
22
- export declare function getOriginalWaitUntil(context: ExecutionContextCompat): ExecutionContext['waitUntil'] | undefined;
22
+ export declare function getOriginalWaitUntil(context: ExecutionContextCompat): ExecutionContext['waitUntil'];
23
23
  /**
24
24
  * Enhances the given execution context by wrapping its `waitUntil` method with a proxy
25
25
  * to monitor pending tasks, and provides a flusher function to ensure all tasks
@@ -1 +1 @@
1
- {"version":3,"file":"flush.d.ts","sourceRoot":"","sources":["../../src/flush.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAClE,OAAO,KAAK,EAAE,MAAM,EAAE,MAA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wBAAsB,eAAe,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,EAAE,OAAO,SAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAgB/F"}
@@ -4,9 +4,10 @@
4
4
  *
5
5
  * - **Callable RPC spans** — a span (op `rpc`) for each `@callable()` method invoked over WebSocket.
6
6
  * - **Conversation correlation** — sets the conversation id on the scope for each unit of agent
7
- * work — chat turn or callable RPC call — so `gen_ai` spans created within it are correlated, for
8
- * chat and plain agents alike. Defaults to the instance `name` and is rotated when the chat is
9
- * cleared (the `message:clear` observability event).
7
+ * work — chat turn, callable RPC call, or HTTP request — so `gen_ai` spans created within it are
8
+ * correlated, for chat and plain agents alike. The id is minted once per agent instance and
9
+ * rotated when the chat is cleared (the `message:clear` observability event); it is persisted to
10
+ * Durable Object storage so it survives hibernation.
10
11
  *
11
12
  * It only hooks the `agents` package internals and uses Sentry's tracing primitives. On Cloudflare
12
13
  * Workers, prefer `instrumentAgentWithSentry`, which additionally instruments the Durable Object
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/instrumentations/agents/index.ts"],"names":[],"mappings":"AAIA;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAgB,yBAAyB,CAAC,CAAC,SAAS,MAAM,EAAE,KAAK,EAAE,CAAC,GAAG,CAAC,CAOvE"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/instrumentations/agents/index.ts"],"names":[],"mappings":"AAKA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,yBAAyB,CAAC,CAAC,SAAS,MAAM,EAAE,KAAK,EAAE,CAAC,GAAG,CAAC,CAQvE"}
@@ -5,7 +5,10 @@ import { type AgentInternals } from './types';
5
5
  * the WebSocket message (on Cloudflare, the instrumented Durable Object `webSocketMessage` hook).
6
6
  *
7
7
  * Also sets the conversation id on the scope for the duration of the call: callable methods are the
8
- * unit of work for plain (non-chat) agents, which run LLM calls just like chat turns do.
8
+ * unit of work for plain (non-chat) agents, which run LLM calls just like chat turns do. It is
9
+ * awaited so the id is on the scope before the method body creates any span; the `agents`
10
+ * `onMessage` own property this wraps is already `async`, so the promise return is nothing new to
11
+ * the WebSocket dispatch upstream.
9
12
  */
10
13
  export declare function instrumentAgentCallableRpc(obj: AgentInternals): void;
11
14
  //# sourceMappingURL=instrumentAgentCallableRpc.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"instrumentAgentCallableRpc.d.ts","sourceRoot":"","sources":["../../../../src/instrumentations/agents/instrumentAgentCallableRpc.ts"],"names":[],"mappings":"AAEA,OAAO,EAAqB,KAAK,cAAc,EAA8C,MAAM,SAAS,CAAC;AAE7G;;;;;;;GAOG;AACH,wBAAgB,0BAA0B,CAAC,GAAG,EAAE,cAAc,GAAG,IAAI,CA+BpE"}
1
+ {"version":3,"file":"instrumentAgentCallableRpc.d.ts","sourceRoot":"","sources":["../../../../src/instrumentations/agents/instrumentAgentCallableRpc.ts"],"names":[],"mappings":"AAEA,OAAO,EAAqB,KAAK,cAAc,EAA8C,MAAM,SAAS,CAAC;AAE7G;;;;;;;;;;GAUG;AACH,wBAAgB,0BAA0B,CAAC,GAAG,EAAE,cAAc,GAAG,IAAI,CA+BpE"}
@@ -0,0 +1,16 @@
1
+ import { type AgentInternals } from './types';
2
+ /**
3
+ * Correlates the AI spans of an HTTP-driven agent turn with a conversation id on the active scope.
4
+ *
5
+ * `onRequest` is the third unit of agent work, alongside chat turns and `@callable()` RPC: the
6
+ * `agents` router sends every non-WebSocket request to it, which is how REST endpoints and webhooks
7
+ * reach an agent.
8
+ *
9
+ * `agents` installs `onRequest` as an own property in the `Agent` constructor (as it does
10
+ * `onMessage`), and we instrument after construction, so wrapping the own property is what the
11
+ * router ends up calling. That own property is already `async`, and partyserver's `fetch` awaits it,
12
+ * so returning a promise from this wrapper — to get the conversation id onto the scope before the
13
+ * request handler creates any span — keeps the existing contract.
14
+ */
15
+ export declare function instrumentAgentRequestConversation(obj: AgentInternals): void;
16
+ //# sourceMappingURL=instrumentAgentRequestConversation.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"instrumentAgentRequestConversation.d.ts","sourceRoot":"","sources":["../../../../src/instrumentations/agents/instrumentAgentRequestConversation.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,cAAc,EAA0B,MAAM,SAAS,CAAC;AAEtE;;;;;;;;;;;;GAYG;AACH,wBAAgB,kCAAkC,CAAC,GAAG,EAAE,cAAc,GAAG,IAAI,CAc5E"}
@@ -3,16 +3,17 @@ import { type AgentInternals } from './types';
3
3
  * For chat agents (`AIChatAgent` from `@cloudflare/ai-chat`), correlates each chat turn's AI spans
4
4
  * with a conversation id on the active scope.
5
5
  *
6
- * In the Agents model one agent instance is one long-lived conversation, so the instance `name` is
7
- * the base conversation id. When the user clears the chat, they expect a fresh conversation — but
8
- * recreating the Durable Object for that would also drop the MCP/OAuth state stored per instance
9
- * (GitHub/Sentry sign-in). To get a fresh conversation id *without* losing that state, we rotate an
10
- * in-memory id on the instance when the SDK reports a cleared chat, and stamp that (falling back to
11
- * the instance `name` before the first clear).
6
+ * In the Agents model one agent instance is one long-lived conversation, so the conversation id is
7
+ * minted once per instance and persisted to Durable Object storage, which is what carries it across
8
+ * hibernation (that destroys the in-memory instance). When the user clears the chat, they expect a
9
+ * fresh conversation — but recreating the Durable Object for that would also drop the MCP/OAuth
10
+ * state stored per instance (GitHub/Sentry sign-in). To get a fresh conversation id *without*
11
+ * losing that state, we rotate the persisted id when the SDK reports a cleared chat.
12
12
  *
13
- * The id itself is not attached to spans here — the SDK's `conversationIdIntegration` reads it off
14
- * the scope at `spanStart` and stamps `gen_ai.conversation.id` onto the AI spans created inside the
15
- * turn (e.g. by the Workers AI instrumentation), which correlates a turn's model and tool calls.
13
+ * The id itself is not attached to spans here — `setAgentConversationId` resolves it, and the SDK's
14
+ * `conversationIdIntegration` picks it off the scope at `spanStart` to stamp
15
+ * `gen_ai.conversation.id` onto the AI spans created inside the turn (e.g. by the Workers AI
16
+ * instrumentation), which correlates a turn's model and tool calls.
16
17
  *
17
18
  * Plain (non-chat) `Agent`s do not define `onChatMessage`, so they are skipped here — their unit
18
19
  * of work is the callable RPC method, where `instrumentAgentCallableRpc` sets the conversation id
@@ -1 +1 @@
1
- {"version":3,"file":"instrumentChatAgentConversation.d.ts","sourceRoot":"","sources":["../../../../src/instrumentations/agents/instrumentChatAgentConversation.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,KAAK,cAAc,EAA0B,MAAM,SAAS,CAAC;AAEtE;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,+BAA+B,CAAC,GAAG,EAAE,cAAc,GAAG,IAAI,CAgCzE"}
1
+ {"version":3,"file":"instrumentChatAgentConversation.d.ts","sourceRoot":"","sources":["../../../../src/instrumentations/agents/instrumentChatAgentConversation.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,KAAK,cAAc,EAAoD,MAAM,SAAS,CAAC;AAEhG;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,+BAA+B,CAAC,GAAG,EAAE,cAAc,GAAG,IAAI,CAgCzE"}
@@ -1,6 +1,14 @@
1
+ import type { InstrumentedDurableObjectState } from '../../wrapMethodWithSentry';
1
2
  export declare const AGENT_SPAN_ORIGIN = "auto.faas.cloudflare.agents";
2
- export declare const AGENT_CLASS_ATTRIBUTE = "cloudflare.agent.class";
3
- export declare const AGENT_NAME_ATTRIBUTE = "cloudflare.agent.name";
3
+ /** DO storage key under which the conversation id is persisted so it survives hibernation. */
4
+ export declare const AGENT_CONVERSATION_ID_STORAGE_KEY = "__SENTRY_AGENT_CONVERSATION_ID__";
5
+ /**
6
+ * Instance keys for our conversation-id bookkeeping, keyed by symbol so the state stays invisible
7
+ * to anything enumerating the user-owned agent instance (`Object.keys`, `JSON.stringify`, spread).
8
+ * Exported because the exported `AgentInternals` interface references them.
9
+ */
10
+ export declare const AGENT_CONVERSATION_ID_SYMBOL: unique symbol;
11
+ export declare const AGENT_APPLIED_CONVERSATION_ID_SYMBOL: unique symbol;
4
12
  /**
5
13
  * The subset of the `agents` `Agent` instance internals that we instrument. These are runtime
6
14
  * implementation details of the `agents` package (v0.13.x) rather than part of its public type
@@ -16,34 +24,71 @@ export interface AgentInternals {
16
24
  * does not, so its presence discriminates a chat agent.
17
25
  */
18
26
  onChatMessage?: (...args: unknown[]) => unknown;
27
+ /** HTTP request handler; the router sends every non-WebSocket request here. */
28
+ onRequest?: (...args: unknown[]) => unknown;
19
29
  /** The user's Agent class (used by the SDK for the observability event `agent` field). */
20
30
  _ParentClass?: {
21
31
  name?: string;
22
32
  };
23
- /** The Agent instance name, which in the Agents model identifies the conversation/thread. */
33
+ /** The Agent instance name, reported as the `cloudflare.agent.name` span attribute. */
24
34
  name?: string;
25
35
  /**
26
- * Internal: the active conversation id, rotated when the chat is cleared (the `message:clear`
27
- * observability event) so a reset chat groups as a fresh conversation while the instance (and its
28
- * MCP/OAuth state) stays put. Set by `instrumentChatAgentConversation`; falls back to `name`
29
- * before the first clear.
36
+ * The Durable Object state of the instance. Present on every real Agent; guarded like the other
37
+ * internals so partially-mocked instances keep working.
38
+ */
39
+ ctx?: InstrumentedDurableObjectState;
40
+ /**
41
+ * The current conversation id for this agent instance. It is cached in memory after being loaded
42
+ * from Durable Object storage and updated when the conversation rotates. `undefined` means storage
43
+ * has not been read yet.
44
+ */
45
+ [AGENT_CONVERSATION_ID_SYMBOL]?: string;
46
+ /**
47
+ * The conversation id this instrumentation most recently applied to the isolation scope. It lets
48
+ * subsequent units of work distinguish an SDK-applied id, which may be replaced after rotation,
49
+ * from an id explicitly set by the user, which must be preserved.
30
50
  */
31
- __sentryConversationId?: string;
51
+ [AGENT_APPLIED_CONVERSATION_ID_SYMBOL]?: string;
32
52
  }
33
53
  /** Reads best-effort agent identity attributes from the instance, tolerating missing internals. */
34
54
  export declare function getAgentAttributes(instance: AgentInternals): Record<string, string>;
35
55
  /**
36
- * Sets the agent instance's conversation id on the current scope for the duration of the
37
- * surrounding unit of work (chat turn, callable RPC call). In the Agents model one instance is one
38
- * conversation, so the instance `name` is the natural conversation id — for chat and plain agents
39
- * alike, since plain agents run LLM calls too (e.g. inside `@callable()` methods). Once the chat
40
- * has been cleared, the rotated `__sentryConversationId` takes precedence so LLM calls from any
41
- * unit of work group under the fresh conversation.
56
+ * Persists the conversation id to Durable Object storage, so it survives hibernation, and updates
57
+ * the in-memory cache synchronously so the current wake is immediately consistent even if the
58
+ * write fails. Uses the async storage API, which exists on KV- and SQLite-backed DOs alike.
59
+ * The write is fire-and-forget: DO storage writes are tracked by the runtime and land without
60
+ * awaiting (`waitUntil` is a no-op in Durable Objects), and the catch keeps a rejection from
61
+ * surfacing as unhandled — a failed write just means the next wake starts a new conversation,
62
+ * which must never throw into user code. Uses the original uninstrumented storage so internal
63
+ * bookkeeping doesn't create spans.
64
+ */
65
+ export declare function storeAgentConversationId(instance: AgentInternals, conversationId: string): void;
66
+ /**
67
+ * Sets the agent instance's conversation id on the active scope for the duration of the
68
+ * surrounding unit of work (chat turn, callable RPC call, HTTP request). In the Agents model one
69
+ * instance is one long-lived conversation, so the id is minted once per instance and persisted to
70
+ * DO storage — for chat and plain agents alike, since plain agents run LLM calls too (e.g. inside
71
+ * `@callable()` methods). The instance `name` is deliberately not used: it is caller-chosen and can
72
+ * be a stable, guessable, or shared value, whereas a conversation id should identify exactly one
73
+ * conversation. Clearing the chat rotates it (see `storeAgentConversationId`) so subsequent LLM
74
+ * calls group under the fresh conversation.
75
+ *
76
+ * Every handler wrapper awaits this before invoking the original, so the id is on the scope before
77
+ * the unit of work — and any `gen_ai` span it creates — starts. Only the first unit of work per wake
78
+ * pays the storage read; the rest resolve from the in-memory cache. Awaiting is safe on all three
79
+ * paths because the `agents` `Agent` constructor already replaces `onMessage` and `onRequest` with
80
+ * `async` wrappers of its own, and `onChatMessage` is async by contract, so every caller upstream
81
+ * already handles a promise.
82
+ *
83
+ * An id the user set explicitly outranks this inferred one, in either order: a `setConversationId()`
84
+ * call that already happened is detected here and left alone, and one made inside the handler lands
85
+ * on the same scope afterwards and therefore wins. That is why the write targets the isolation scope
86
+ * — it is the scope the public `Sentry.setConversationId()` writes to, and `conversationIdIntegration`
87
+ * prefers the current scope over it, so writing there would make a user's call unoverridable.
42
88
  *
43
89
  * `conversationIdIntegration` reads the id off the scope at `spanStart` and stamps
44
- * `gen_ai.conversation.id` onto AI spans created within the unit of work, correlating its model
45
- * and tool calls. Callers run inside a per-event forked scope (`wrapMethodWithSentry`), so the id
46
- * does not leak into unrelated events.
90
+ * `gen_ai.conversation.id` onto AI spans created within the unit of work, correlating its model and
91
+ * tool calls.
47
92
  */
48
- export declare function setAgentConversationId(instance: AgentInternals): void;
93
+ export declare function setAgentConversationId(instance: AgentInternals): Promise<void>;
49
94
  //# sourceMappingURL=types.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../../src/instrumentations/agents/types.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,iBAAiB,gCAAgC,CAAC;AAC/D,eAAO,MAAM,qBAAqB,2BAA2B,CAAC;AAC9D,eAAO,MAAM,oBAAoB,0BAA0B,CAAC;AAE5D;;;;GAIG;AACH,MAAM,WAAW,cAAc;IAC7B,2FAA2F;IAC3F,KAAK,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,IAAI,CAAC;IAClE,wEAAwE;IACxE,SAAS,CAAC,EAAE,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,KAAK,OAAO,CAAC;IAC5C;;;OAGG;IACH,aAAa,CAAC,EAAE,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,KAAK,OAAO,CAAC;IAChD,0FAA0F;IAC1F,YAAY,CAAC,EAAE;QAAE,IAAI,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;IACjC,6FAA6F;IAC7F,IAAI,CAAC,EAAE,MAAM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AC5D,OAAO,CAAC,QAAQ,CAAC,CAsJnB"}
1
+ {"version":3,"file":"request.d.ts","sourceRoot":"","sources":["../../src/request.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,2BAA2B,EAAE,MAAM,2BAA2B,CAAC;AAc3F,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,UAAU,CAAC;AAClD,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,oBAAoB,CAAC;AAYjE,UAAU,4BAA4B;IACpC,OAAO,EAAE,iBAAiB,CAAC;IAC3B,OAAO,EAAE,OAAO,CAAC,OAAO,EAAE,2BAA2B,CAAC,OAAO,CAAC,GAAG,YAAY,CAAC,OAAO,CAAC,CAAC,CAAC;IACxF,OAAO,EAAE,sBAAsB,GAAG,SAAS,CAAC;IAC5C;;;;;;;;;OASG;IACH,aAAa,CAAC,EAAE,OAAO,CAAC;CACzB;AAED;;GAEG;AACH,wBAAgB,kBAAkB,CAChC,cAAc,EAAE,4BAA4B,EAC5C,OAAO,EAAE,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,KAAK,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC,GAC5D,OAAO,CAAC,QAAQ,CAAC,CAsJnB"}
@@ -0,0 +1,24 @@
1
+ import { type Scope } from '@sentry/core';
2
+ /**
3
+ * Runs `callback` on the isolation scope for the current invocation.
4
+ *
5
+ * An instrumented handler is either the entry point of an invocation or reentrant — reached from
6
+ * another instrumented handler already serving the same invocation (a Durable Object method calling
7
+ * its own `fetch`, an RPC method reaching a sibling method). Only the entry point may fork:
8
+ *
9
+ * - Forking at the entry point is mandatory. `setUser`/`setTag` write to the isolation scope, and a
10
+ * Durable Object's isolation scope outlives the invocation that touched it, so without a fork one
11
+ * invocation's user and tags reappear on the next invocation's events in the same isolate.
12
+ * Forking clones, so request data set by an enclosing wrapper is still inherited.
13
+ * - Forking again when reentrant would be wrong. Everything below the entry point is one logical
14
+ * unit of work: a nested call must see what the caller set and be able to add to it, the way it
15
+ * would if the SDK were not wrapping it at all.
16
+ *
17
+ * The AsyncLocalStorage strategy hands the default isolation scope back whenever no invocation is in
18
+ * flight, and a forked one while inside `withIsolationScope`. Reference-comparing against the default
19
+ * is therefore enough to tell the two cases apart. The stack fallback does not fork, so it reports the
20
+ * default scope even inside an invocation; there the fork degrades to a no-op, which the stack strategy
21
+ * tolerates. This matches the approach used by `patchEventHandler` in Nuxt.
22
+ */
23
+ export declare function withInvocationIsolationScope<T>(callback: (scope: Scope) => T): T;
24
+ //# sourceMappingURL=invocationScope.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"invocationScope.d.ts","sourceRoot":"","sources":["../../../src/utils/invocationScope.ts"],"names":[],"mappings":"AAAA,OAAO,EAA+C,KAAK,KAAK,EAAsB,MAAM,cAAc,CAAC;AAE3G;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAgB,4BAA4B,CAAC,CAAC,EAAE,QAAQ,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,CAAC,GAAG,CAAC,CAMhF"}
@@ -4,6 +4,14 @@ import { type SerializedTraceData } from '@sentry/core';
4
4
  * If no active trace exists, returns the original args unchanged.
5
5
  */
6
6
  export declare function appendRpcMeta(args: unknown[]): unknown[];
7
+ /**
8
+ * Whether the trailing argument carries Sentry RPC metadata.
9
+ *
10
+ * Separate from {@link extractRpcMeta} because the RPC method wrappers run this check on every
11
+ * call — including the instance's own internal method calls, which never carry metadata — and
12
+ * must not allocate on that path.
13
+ */
14
+ export declare function hasRpcMeta(args: unknown[]): boolean;
7
15
  /**
8
16
  * Extracts Sentry RPC metadata from the trailing argument of an args array.
9
17
  * Returns cleaned args (without meta) and the extracted trace data if found.
@@ -1 +1 @@
1
- {"version":3,"file":"rpcMeta.d.ts","sourceRoot":"","sources":["../../../src/utils/rpcMeta.ts"],"names":[],"mappings":"AAAA,OAAO,EAA8B,KAAK,mBAAmB,EAAE,MAAM,cAAc,CAAC;AAoBpF;;;GAGG;AACH,wBAAgB,aAAa,CAAC,IAAI,EAAE,OAAO,EAAE,GAAG,OAAO,EAAE,CAQxD;AAED;;;GAGG;AACH,wBAAgB,cAAc,CAAC,CAAC,SAAS,OAAO,EAAE,EAChD,IAAI,EAAE,CAAC,GACN;IACD,IAAI,EAAE,CAAC,CAAC;IACR,OAAO,CAAC,EAAE,mBAAmB,CAAC;CAC/B,CAcA"}
1
+ {"version":3,"file":"rpcMeta.d.ts","sourceRoot":"","sources":["../../../src/utils/rpcMeta.ts"],"names":[],"mappings":"AAAA,OAAO,EAA8B,KAAK,mBAAmB,EAAE,MAAM,cAAc,CAAC;AAoBpF;;;GAGG;AACH,wBAAgB,aAAa,CAAC,IAAI,EAAE,OAAO,EAAE,GAAG,OAAO,EAAE,CAQxD;AAED;;;;;;GAMG;AACH,wBAAgB,UAAU,CAAC,IAAI,EAAE,OAAO,EAAE,GAAG,OAAO,CAEnD;AAED;;;GAGG;AACH,wBAAgB,cAAc,CAAC,CAAC,SAAS,OAAO,EAAE,EAChD,IAAI,EAAE,CAAC,GACN;IACD,IAAI,EAAE,CAAC,CAAC;IACR,OAAO,CAAC,EAAE,mBAAmB,CAAC;CAC/B,CAcA"}
@@ -1,7 +1,7 @@
1
1
  import type { DurableObjectStorage } from '@cloudflare/workers-types';
2
2
  import type { CloudflareOptions } from './client';
3
3
  /** Extended DurableObjectState with originalStorage exposed by instrumentContext */
4
- interface InstrumentedDurableObjectState extends DurableObjectState {
4
+ export interface InstrumentedDurableObjectState extends DurableObjectState {
5
5
  originalStorage?: DurableObjectStorage;
6
6
  }
7
7
  type MethodWrapperOptions = {
@@ -1 +1 @@
1
- {"version":3,"file":"wrapMethodWithSentry.d.ts","sourceRoot":"","sources":["../../src/wrapMethodWithSentry.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,2BAA2B,CAAC;AAgBtE,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,UAAU,CAAC;AAQlD,oFAA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BAA8B,CAAC;IAC3D;;;;;;;;;OASG;IACH,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB;;;OAGG;IACH,MAAM,EAAE,MAAM,CAAC;CAChB,CAAC;AAGF,MAAM,MAAM,eAAe,GAAG,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,GAAG,CAAC;AACtD,KAAK,cAAc,GAAG,eAAe,CAAC;AAEtC;;;;;;;;;GASG;AACH,wBAAgB,oBAAoB,CAAC,CAAC,SAAS,cAAc,EAC3D,cAAc,EAAE,oBAAoB,EACpC,OAAO,EAAE,CAAC,EACV,QAAQ,CAAC,EAAE,CAAC,GAAG,IAAI,EAAE,UAAU,CAAC,CAAC,CAAC,KAAK,IAAI,EAC3C,MAAM,CAAC,EAAE,IAAI,GACZ,CAAC,CAqJH"}
@@ -18,8 +18,8 @@ type InstrumentedDurableObjectContext = any;
18
18
  *
19
19
  * This is the shared construction path used by both {@link instrumentDurableObjectWithSentry}
20
20
  * and {@link instrumentAgentWithSentry}. It intentionally does NOT apply the RPC prototype-method
21
- * proxy — callers apply that last via {@link finalizeWithRpcInstrumentation}, after any additional
22
- * per-instance instrumentation has been layered onto the returned object.
21
+ * instrumentation — callers apply that last via {@link finalizeWithRpcInstrumentation}, after any
22
+ * additional per-instance instrumentation has been layered onto the returned object.
23
23
  *
24
24
  * @internal
25
25
  */
@@ -27,18 +27,27 @@ export declare function constructInstrumentedDurableObject<E, T extends DurableO
27
27
  obj: T;
28
28
  options: CloudflareOptions;
29
29
  context: InstrumentedDurableObjectContext;
30
+ frameworkManagedMethods: ReadonlySet<string>;
30
31
  };
31
32
  /**
32
- * Wraps a constructed (and already handler-instrumented) Durable Object instance with the RPC
33
- * prototype-method proxy, when RPC trace propagation is enabled. Returns the object unchanged when
34
- * RPC instrumentation is disabled.
33
+ * Adds trace propagation to a constructed Durable Object's RPC methods.
35
34
  *
36
- * This must be applied last, so that any per-instance instrumentation (own properties such as
37
- * `fetch`, `alarm`, or Agent-specific handlers) is excluded from RPC method tracing.
35
+ * RPC methods are wrapped on the prototype because Cloudflare dispatches them with the Durable
36
+ * Object instance as the receiver. This preserves native private-field access and keeps the methods
37
+ * visible to Cloudflare's RPC dispatcher. Built-in handlers, Agent handlers, and methods managed by
38
+ * another framework are left untouched.
38
39
  *
40
+ * Call this after all per-instance instrumentation has been applied. If RPC trace propagation is
41
+ * disabled, the object is returned unchanged.
42
+ *
43
+ * @param obj The constructed Durable Object instance.
44
+ * @param options The resolved SDK options for this instance.
45
+ * @param context The instrumented execution context for this instance.
46
+ * @param excludedMethods Method names owned by another framework and therefore not safe to wrap.
47
+ * @returns The same Durable Object instance, with eligible prototype methods instrumented.
39
48
  * @internal
40
49
  */
41
- export declare function finalizeWithRpcInstrumentation<T extends object>(obj: T, options: CloudflareOptions, context: InstrumentedDurableObjectContext): T;
50
+ export declare function finalizeWithRpcInstrumentation<T extends object>(obj: T, options: CloudflareOptions, context: InstrumentedDurableObjectContext, excludedMethods?: ReadonlySet<string>): T;
42
51
  /**
43
52
  * Instruments a Durable Object class to capture errors and performance data.
44
53
  *
@@ -19,7 +19,7 @@ type FlushLock = {
19
19
  *
20
20
  * By using the original waitUntil for flush operations, we bypass this issue.
21
21
  */
22
- export declare function getOriginalWaitUntil(context: ExecutionContextCompat): ExecutionContext['waitUntil'] | undefined;
22
+ export declare function getOriginalWaitUntil(context: ExecutionContextCompat): ExecutionContext['waitUntil'];
23
23
  /**
24
24
  * Enhances the given execution context by wrapping its `waitUntil` method with a proxy
25
25
  * to monitor pending tasks, and provides a flusher function to ensure all tasks