agentv 2.6.0 → 2.7.1-next.3

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 (85) hide show
  1. package/README.md +128 -33
  2. package/dist/chunk-3L2L5GIL.js +51 -0
  3. package/dist/{chunk-BKMQNEUD.js.map → chunk-3L2L5GIL.js.map} +1 -1
  4. package/dist/{chunk-BKMQNEUD.js → chunk-5H446C7X.js} +2 -45
  5. package/dist/{chunk-LJVS3JAK.js → chunk-BL4PVUAT.js} +6 -4
  6. package/dist/{chunk-LJVS3JAK.js.map → chunk-BL4PVUAT.js.map} +1 -1
  7. package/dist/{chunk-MGK6HHRR.js → chunk-BWLYFF5N.js} +9813 -11237
  8. package/dist/chunk-BWLYFF5N.js.map +1 -0
  9. package/dist/chunk-C5GOHBQM.js +84 -0
  10. package/dist/chunk-C5GOHBQM.js.map +1 -0
  11. package/dist/chunk-EJEG3DU2.js +5476 -0
  12. package/dist/chunk-EJEG3DU2.js.map +1 -0
  13. package/dist/chunk-FV32QHPB.js +565 -0
  14. package/dist/chunk-FV32QHPB.js.map +1 -0
  15. package/dist/chunk-H5FFZCKI.js +2957 -0
  16. package/dist/chunk-H5FFZCKI.js.map +1 -0
  17. package/dist/chunk-JK6V4KVD.js +114 -0
  18. package/dist/chunk-JK6V4KVD.js.map +1 -0
  19. package/dist/chunk-LRULMAAA.js +1711 -0
  20. package/dist/chunk-LRULMAAA.js.map +1 -0
  21. package/dist/chunk-SR4I5KET.js +1238 -0
  22. package/dist/chunk-SR4I5KET.js.map +1 -0
  23. package/dist/chunk-VQ2ZO7XJ.js +2098 -0
  24. package/dist/chunk-VQ2ZO7XJ.js.map +1 -0
  25. package/dist/chunk-XALGXSKB.js +21 -0
  26. package/dist/chunk-XALGXSKB.js.map +1 -0
  27. package/dist/cli.js +8 -2
  28. package/dist/cli.js.map +1 -1
  29. package/dist/dist-R3OCWGXH.js +257 -0
  30. package/dist/dist-R3OCWGXH.js.map +1 -0
  31. package/dist/esm-5Q4BZALM-5REQWAUV.js +924 -0
  32. package/dist/esm-5Q4BZALM-5REQWAUV.js.map +1 -0
  33. package/dist/esm-DX3WQKEN.js +32 -0
  34. package/dist/esm-DX3WQKEN.js.map +1 -0
  35. package/dist/esm-QNEMCJPL.js +933 -0
  36. package/dist/esm-QNEMCJPL.js.map +1 -0
  37. package/dist/esm-R77SNOF5.js +65 -0
  38. package/dist/esm-R77SNOF5.js.map +1 -0
  39. package/dist/esm-RVQPUGWH.js +1207 -0
  40. package/dist/esm-RVQPUGWH.js.map +1 -0
  41. package/dist/getMachineId-bsd-HSK5LZMG.js +41 -0
  42. package/dist/getMachineId-bsd-HSK5LZMG.js.map +1 -0
  43. package/dist/getMachineId-darwin-4DP6CCJV.js +41 -0
  44. package/dist/getMachineId-darwin-4DP6CCJV.js.map +1 -0
  45. package/dist/getMachineId-linux-44LJ5UJB.js +33 -0
  46. package/dist/getMachineId-linux-44LJ5UJB.js.map +1 -0
  47. package/dist/getMachineId-unsupported-NVK6IATM.js +24 -0
  48. package/dist/getMachineId-unsupported-NVK6IATM.js.map +1 -0
  49. package/dist/getMachineId-win-YZ36S7VA.js +43 -0
  50. package/dist/getMachineId-win-YZ36S7VA.js.map +1 -0
  51. package/dist/index.js +10 -2
  52. package/dist/interactive-33TCZXLF.js +333 -0
  53. package/dist/interactive-33TCZXLF.js.map +1 -0
  54. package/dist/otlp-json-file-exporter-77FDBRSY-EZAPHWP6.js +9 -0
  55. package/dist/otlp-json-file-exporter-77FDBRSY-EZAPHWP6.js.map +1 -0
  56. package/dist/simple-trace-file-exporter-S76DMABU-5FCJESD2.js +9 -0
  57. package/dist/simple-trace-file-exporter-S76DMABU-5FCJESD2.js.map +1 -0
  58. package/dist/src-2N5EJ2N6.js +1733 -0
  59. package/dist/src-2N5EJ2N6.js.map +1 -0
  60. package/dist/templates/.agents/skills/agentv-chat-to-eval/README.md +84 -0
  61. package/dist/templates/.agents/skills/agentv-chat-to-eval/SKILL.md +144 -0
  62. package/dist/templates/.agents/skills/agentv-chat-to-eval/examples/transcript-json.md +67 -0
  63. package/dist/templates/.agents/skills/agentv-chat-to-eval/examples/transcript-markdown.md +101 -0
  64. package/dist/templates/.agents/skills/agentv-eval-builder/SKILL.md +433 -0
  65. package/dist/templates/.agents/skills/agentv-eval-builder/references/config-schema.json +36 -0
  66. package/dist/templates/.agents/skills/agentv-eval-builder/references/custom-evaluators.md +118 -0
  67. package/dist/templates/.agents/skills/agentv-eval-builder/references/eval-schema.json +251 -0
  68. package/dist/templates/.agents/skills/agentv-eval-builder/references/rubric-evaluator.md +77 -0
  69. package/dist/templates/.agents/skills/agentv-eval-orchestrator/SKILL.md +50 -0
  70. package/dist/templates/.agents/skills/agentv-prompt-optimizer/SKILL.md +78 -0
  71. package/dist/templates/.agentv/.env.example +23 -23
  72. package/dist/templates/.agentv/config.yaml +15 -15
  73. package/dist/templates/.claude/skills/agentv-eval-builder/SKILL.md +38 -13
  74. package/dist/templates/.claude/skills/agentv-eval-builder/references/custom-evaluators.md +9 -6
  75. package/dist/templates/.claude/skills/agentv-eval-builder/references/eval-schema.json +4 -4
  76. package/dist/templates/.claude/skills/agentv-eval-builder/references/rubric-evaluator.md +7 -9
  77. package/dist/templates/.github/prompts/agentv-eval-build.prompt.md +4 -4
  78. package/dist/templates/.github/prompts/agentv-optimize.prompt.md +3 -3
  79. package/dist/{token-D3IYDJQZ.js → token-POXF46NU.js} +6 -4
  80. package/dist/{token-D3IYDJQZ.js.map → token-POXF46NU.js.map} +1 -1
  81. package/dist/{token-util-FWFPR2BV.js → token-util-6GWYZWGE.js} +4 -3
  82. package/dist/token-util-6GWYZWGE.js.map +1 -0
  83. package/package.json +7 -3
  84. package/dist/chunk-MGK6HHRR.js.map +0 -1
  85. /package/dist/{token-util-FWFPR2BV.js.map → chunk-5H446C7X.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../node_modules/.bun/@opentelemetry+context-async-hooks@2.5.1+460773ef8ff1e07c/node_modules/@opentelemetry/context-async-hooks/src/AbstractAsyncHooksContextManager.ts","../../../node_modules/.bun/@opentelemetry+context-async-hooks@2.5.1+460773ef8ff1e07c/node_modules/@opentelemetry/context-async-hooks/src/AsyncHooksContextManager.ts","../../../node_modules/.bun/@opentelemetry+context-async-hooks@2.5.1+460773ef8ff1e07c/node_modules/@opentelemetry/context-async-hooks/src/AsyncLocalStorageContextManager.ts","../../../node_modules/.bun/@opentelemetry+context-async-hooks@2.5.1+460773ef8ff1e07c/node_modules/@opentelemetry/context-async-hooks/src/index.ts","../../../node_modules/.bun/@opentelemetry+sdk-trace-base@2.5.1+460773ef8ff1e07c/node_modules/@opentelemetry/sdk-trace-base/src/enums.ts","../../../node_modules/.bun/@opentelemetry+sdk-trace-base@2.5.1+460773ef8ff1e07c/node_modules/@opentelemetry/sdk-trace-base/src/Span.ts","../../../node_modules/.bun/@opentelemetry+sdk-trace-base@2.5.1+460773ef8ff1e07c/node_modules/@opentelemetry/sdk-trace-base/src/Sampler.ts","../../../node_modules/.bun/@opentelemetry+sdk-trace-base@2.5.1+460773ef8ff1e07c/node_modules/@opentelemetry/sdk-trace-base/src/sampler/AlwaysOffSampler.ts","../../../node_modules/.bun/@opentelemetry+sdk-trace-base@2.5.1+460773ef8ff1e07c/node_modules/@opentelemetry/sdk-trace-base/src/sampler/AlwaysOnSampler.ts","../../../node_modules/.bun/@opentelemetry+sdk-trace-base@2.5.1+460773ef8ff1e07c/node_modules/@opentelemetry/sdk-trace-base/src/sampler/ParentBasedSampler.ts","../../../node_modules/.bun/@opentelemetry+sdk-trace-base@2.5.1+460773ef8ff1e07c/node_modules/@opentelemetry/sdk-trace-base/src/sampler/TraceIdRatioBasedSampler.ts","../../../node_modules/.bun/@opentelemetry+sdk-trace-base@2.5.1+460773ef8ff1e07c/node_modules/@opentelemetry/sdk-trace-base/src/config.ts","../../../node_modules/.bun/@opentelemetry+sdk-trace-base@2.5.1+460773ef8ff1e07c/node_modules/@opentelemetry/sdk-trace-base/src/utility.ts","../../../node_modules/.bun/@opentelemetry+sdk-trace-base@2.5.1+460773ef8ff1e07c/node_modules/@opentelemetry/sdk-trace-base/src/export/BatchSpanProcessorBase.ts","../../../node_modules/.bun/@opentelemetry+sdk-trace-base@2.5.1+460773ef8ff1e07c/node_modules/@opentelemetry/sdk-trace-base/src/platform/node/export/BatchSpanProcessor.ts","../../../node_modules/.bun/@opentelemetry+sdk-trace-base@2.5.1+460773ef8ff1e07c/node_modules/@opentelemetry/sdk-trace-base/src/platform/node/RandomIdGenerator.ts","../../../node_modules/.bun/@opentelemetry+sdk-trace-base@2.5.1+460773ef8ff1e07c/node_modules/@opentelemetry/sdk-trace-base/src/platform/node/index.ts","../../../node_modules/.bun/@opentelemetry+sdk-trace-base@2.5.1+460773ef8ff1e07c/node_modules/@opentelemetry/sdk-trace-base/src/platform/index.ts","../../../node_modules/.bun/@opentelemetry+sdk-trace-base@2.5.1+460773ef8ff1e07c/node_modules/@opentelemetry/sdk-trace-base/src/Tracer.ts","../../../node_modules/.bun/@opentelemetry+sdk-trace-base@2.5.1+460773ef8ff1e07c/node_modules/@opentelemetry/sdk-trace-base/src/MultiSpanProcessor.ts","../../../node_modules/.bun/@opentelemetry+sdk-trace-base@2.5.1+460773ef8ff1e07c/node_modules/@opentelemetry/sdk-trace-base/src/BasicTracerProvider.ts","../../../node_modules/.bun/@opentelemetry+sdk-trace-base@2.5.1+460773ef8ff1e07c/node_modules/@opentelemetry/sdk-trace-base/src/export/ConsoleSpanExporter.ts","../../../node_modules/.bun/@opentelemetry+sdk-trace-base@2.5.1+460773ef8ff1e07c/node_modules/@opentelemetry/sdk-trace-base/src/export/InMemorySpanExporter.ts","../../../node_modules/.bun/@opentelemetry+sdk-trace-base@2.5.1+460773ef8ff1e07c/node_modules/@opentelemetry/sdk-trace-base/src/export/SimpleSpanProcessor.ts","../../../node_modules/.bun/@opentelemetry+sdk-trace-base@2.5.1+460773ef8ff1e07c/node_modules/@opentelemetry/sdk-trace-base/src/export/NoopSpanProcessor.ts","../../../node_modules/.bun/@opentelemetry+sdk-trace-base@2.5.1+460773ef8ff1e07c/node_modules/@opentelemetry/sdk-trace-base/src/index.ts","../../../node_modules/.bun/@opentelemetry+sdk-trace-node@2.5.1+460773ef8ff1e07c/node_modules/@opentelemetry/sdk-trace-node/src/NodeTracerProvider.ts","../../../node_modules/.bun/@opentelemetry+sdk-trace-node@2.5.1+460773ef8ff1e07c/node_modules/@opentelemetry/sdk-trace-node/src/index.ts"],"sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ContextManager, Context } from '@opentelemetry/api';\nimport { EventEmitter } from 'events';\n\ntype Func<T> = (...args: unknown[]) => T;\n\n/**\n * Store a map for each event of all original listeners and their \"patched\"\n * version. So when a listener is removed by the user, the corresponding\n * patched function will be also removed.\n */\ninterface PatchMap {\n [name: string]: WeakMap<Func<void>, Func<void>>;\n}\n\nconst ADD_LISTENER_METHODS = [\n 'addListener' as const,\n 'on' as const,\n 'once' as const,\n 'prependListener' as const,\n 'prependOnceListener' as const,\n];\n\nexport abstract class AbstractAsyncHooksContextManager\n implements ContextManager\n{\n abstract active(): Context;\n\n abstract with<A extends unknown[], F extends (...args: A) => ReturnType<F>>(\n context: Context,\n fn: F,\n thisArg?: ThisParameterType<F>,\n ...args: A\n ): ReturnType<F>;\n\n abstract enable(): this;\n\n abstract disable(): this;\n\n /**\n * Binds a the certain context or the active one to the target function and then returns the target\n * @param context A context (span) to be bind to target\n * @param target a function or event emitter. When target or one of its callbacks is called,\n * the provided context will be used as the active context for the duration of the call.\n */\n bind<T>(context: Context, target: T): T {\n if (target instanceof EventEmitter) {\n return this._bindEventEmitter(context, target);\n }\n\n if (typeof target === 'function') {\n return this._bindFunction(context, target);\n }\n return target;\n }\n\n private _bindFunction<T extends Function>(context: Context, target: T): T {\n const manager = this;\n const contextWrapper = function (this: never, ...args: unknown[]) {\n return manager.with(context, () => target.apply(this, args));\n };\n Object.defineProperty(contextWrapper, 'length', {\n enumerable: false,\n configurable: true,\n writable: false,\n value: target.length,\n });\n /**\n * It isn't possible to tell Typescript that contextWrapper is the same as T\n * so we forced to cast as any here.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return contextWrapper as any;\n }\n\n /**\n * By default, EventEmitter call their callback with their context, which we do\n * not want, instead we will bind a specific context to all callbacks that\n * go through it.\n * @param context the context we want to bind\n * @param ee EventEmitter an instance of EventEmitter to patch\n */\n private _bindEventEmitter<T extends EventEmitter>(\n context: Context,\n ee: T\n ): T {\n const map = this._getPatchMap(ee);\n if (map !== undefined) return ee;\n this._createPatchMap(ee);\n\n // patch methods that add a listener to propagate context\n ADD_LISTENER_METHODS.forEach(methodName => {\n if (ee[methodName] === undefined) return;\n ee[methodName] = this._patchAddListener(ee, ee[methodName], context);\n });\n // patch methods that remove a listener\n if (typeof ee.removeListener === 'function') {\n ee.removeListener = this._patchRemoveListener(ee, ee.removeListener);\n }\n if (typeof ee.off === 'function') {\n ee.off = this._patchRemoveListener(ee, ee.off);\n }\n // patch method that remove all listeners\n if (typeof ee.removeAllListeners === 'function') {\n ee.removeAllListeners = this._patchRemoveAllListeners(\n ee,\n ee.removeAllListeners\n );\n }\n return ee;\n }\n\n /**\n * Patch methods that remove a given listener so that we match the \"patched\"\n * version of that listener (the one that propagate context).\n * @param ee EventEmitter instance\n * @param original reference to the patched method\n */\n private _patchRemoveListener(ee: EventEmitter, original: Function) {\n const contextManager = this;\n return function (this: never, event: string, listener: Func<void>) {\n const events = contextManager._getPatchMap(ee)?.[event];\n if (events === undefined) {\n return original.call(this, event, listener);\n }\n const patchedListener = events.get(listener);\n return original.call(this, event, patchedListener || listener);\n };\n }\n\n /**\n * Patch methods that remove all listeners so we remove our\n * internal references for a given event.\n * @param ee EventEmitter instance\n * @param original reference to the patched method\n */\n private _patchRemoveAllListeners(ee: EventEmitter, original: Function) {\n const contextManager = this;\n return function (this: never, event: string) {\n const map = contextManager._getPatchMap(ee);\n if (map !== undefined) {\n if (arguments.length === 0) {\n contextManager._createPatchMap(ee);\n } else if (map[event] !== undefined) {\n delete map[event];\n }\n }\n return original.apply(this, arguments);\n };\n }\n\n /**\n * Patch methods on an event emitter instance that can add listeners so we\n * can force them to propagate a given context.\n * @param ee EventEmitter instance\n * @param original reference to the patched method\n * @param [context] context to propagate when calling listeners\n */\n private _patchAddListener(\n ee: EventEmitter,\n original: Function,\n context: Context\n ) {\n const contextManager = this;\n return function (this: never, event: string, listener: Func<void>) {\n /**\n * This check is required to prevent double-wrapping the listener.\n * The implementation for ee.once wraps the listener and calls ee.on.\n * Without this check, we would wrap that wrapped listener.\n * This causes an issue because ee.removeListener depends on the onceWrapper\n * to properly remove the listener. If we wrap their wrapper, we break\n * that detection.\n */\n if (contextManager._wrapped) {\n return original.call(this, event, listener);\n }\n let map = contextManager._getPatchMap(ee);\n if (map === undefined) {\n map = contextManager._createPatchMap(ee);\n }\n let listeners = map[event];\n if (listeners === undefined) {\n listeners = new WeakMap();\n map[event] = listeners;\n }\n const patchedListener = contextManager.bind(context, listener);\n // store a weak reference of the user listener to ours\n listeners.set(listener, patchedListener);\n\n /**\n * See comment at the start of this function for the explanation of this property.\n */\n contextManager._wrapped = true;\n try {\n return original.call(this, event, patchedListener);\n } finally {\n contextManager._wrapped = false;\n }\n };\n }\n\n private _createPatchMap(ee: EventEmitter): PatchMap {\n const map = Object.create(null);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (ee as any)[this._kOtListeners] = map;\n return map;\n }\n private _getPatchMap(ee: EventEmitter): PatchMap | undefined {\n return (ee as never)[this._kOtListeners];\n }\n\n private readonly _kOtListeners = Symbol('OtListeners');\n private _wrapped = false;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context, ROOT_CONTEXT } from '@opentelemetry/api';\nimport * as asyncHooks from 'async_hooks';\nimport { AbstractAsyncHooksContextManager } from './AbstractAsyncHooksContextManager';\n\n/**\n * @deprecated Use AsyncLocalStorageContextManager instead.\n */\nexport class AsyncHooksContextManager extends AbstractAsyncHooksContextManager {\n private _asyncHook: asyncHooks.AsyncHook;\n private _contexts: Map<number, Context> = new Map();\n private _stack: Array<Context | undefined> = [];\n\n constructor() {\n super();\n this._asyncHook = asyncHooks.createHook({\n init: this._init.bind(this),\n before: this._before.bind(this),\n after: this._after.bind(this),\n destroy: this._destroy.bind(this),\n promiseResolve: this._destroy.bind(this),\n });\n }\n\n active(): Context {\n return this._stack[this._stack.length - 1] ?? ROOT_CONTEXT;\n }\n\n with<A extends unknown[], F extends (...args: A) => ReturnType<F>>(\n context: Context,\n fn: F,\n thisArg?: ThisParameterType<F>,\n ...args: A\n ): ReturnType<F> {\n this._enterContext(context);\n try {\n return fn.call(thisArg!, ...args);\n } finally {\n this._exitContext();\n }\n }\n\n enable(): this {\n this._asyncHook.enable();\n return this;\n }\n\n disable(): this {\n this._asyncHook.disable();\n this._contexts.clear();\n this._stack = [];\n return this;\n }\n\n /**\n * Init hook will be called when userland create a async context, setting the\n * context as the current one if it exist.\n * @param uid id of the async context\n * @param type the resource type\n */\n private _init(uid: number, type: string) {\n // ignore TIMERWRAP as they combine timers with same timeout which can lead to\n // false context propagation. TIMERWRAP has been removed in node 11\n // every timer has it's own `Timeout` resource anyway which is used to propagate\n // context.\n if (type === 'TIMERWRAP') return;\n\n const context = this._stack[this._stack.length - 1];\n if (context !== undefined) {\n this._contexts.set(uid, context);\n }\n }\n\n /**\n * Destroy hook will be called when a given context is no longer used so we can\n * remove its attached context.\n * @param uid uid of the async context\n */\n private _destroy(uid: number) {\n this._contexts.delete(uid);\n }\n\n /**\n * Before hook is called just before executing a async context.\n * @param uid uid of the async context\n */\n private _before(uid: number) {\n const context = this._contexts.get(uid);\n if (context !== undefined) {\n this._enterContext(context);\n }\n }\n\n /**\n * After hook is called just after completing the execution of a async context.\n */\n private _after() {\n this._exitContext();\n }\n\n /**\n * Set the given context as active\n */\n private _enterContext(context: Context) {\n this._stack.push(context);\n }\n\n /**\n * Remove the context at the root of the stack\n */\n private _exitContext() {\n this._stack.pop();\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context, ROOT_CONTEXT } from '@opentelemetry/api';\nimport { AsyncLocalStorage } from 'async_hooks';\nimport { AbstractAsyncHooksContextManager } from './AbstractAsyncHooksContextManager';\n\nexport class AsyncLocalStorageContextManager extends AbstractAsyncHooksContextManager {\n private _asyncLocalStorage: AsyncLocalStorage<Context>;\n\n constructor() {\n super();\n this._asyncLocalStorage = new AsyncLocalStorage();\n }\n\n active(): Context {\n return this._asyncLocalStorage.getStore() ?? ROOT_CONTEXT;\n }\n\n with<A extends unknown[], F extends (...args: A) => ReturnType<F>>(\n context: Context,\n fn: F,\n thisArg?: ThisParameterType<F>,\n ...args: A\n ): ReturnType<F> {\n const cb = thisArg == null ? fn : fn.bind(thisArg);\n return this._asyncLocalStorage.run(context, cb as never, ...args);\n }\n\n enable(): this {\n return this;\n }\n\n disable(): this {\n this._asyncLocalStorage.disable();\n return this;\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport { AsyncHooksContextManager } from './AsyncHooksContextManager';\nexport { AsyncLocalStorageContextManager } from './AsyncLocalStorageContextManager';\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Event name definitions\nexport const ExceptionEventName = 'exception';\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Context,\n diag,\n Exception,\n HrTime,\n Link,\n Span as APISpan,\n Attributes,\n AttributeValue,\n SpanContext,\n SpanKind,\n SpanStatus,\n SpanStatusCode,\n TimeInput,\n} from '@opentelemetry/api';\nimport {\n addHrTimes,\n millisToHrTime,\n hrTime,\n hrTimeDuration,\n InstrumentationScope,\n isAttributeValue,\n isTimeInput,\n isTimeInputHrTime,\n otperformance,\n sanitizeAttributes,\n} from '@opentelemetry/core';\nimport { Resource } from '@opentelemetry/resources';\nimport {\n ATTR_EXCEPTION_MESSAGE,\n ATTR_EXCEPTION_STACKTRACE,\n ATTR_EXCEPTION_TYPE,\n} from '@opentelemetry/semantic-conventions';\nimport { ReadableSpan } from './export/ReadableSpan';\nimport { ExceptionEventName } from './enums';\nimport { SpanProcessor } from './SpanProcessor';\nimport { TimedEvent } from './TimedEvent';\nimport { SpanLimits } from './types';\n\n/**\n * This type provides the properties of @link{ReadableSpan} at the same time\n * of the Span API\n */\nexport type Span = APISpan & ReadableSpan;\n\ninterface SpanOptions {\n resource: Resource;\n scope: InstrumentationScope;\n context: Context;\n spanContext: SpanContext;\n name: string;\n kind: SpanKind;\n parentSpanContext?: SpanContext;\n links?: Link[];\n startTime?: TimeInput;\n attributes?: Attributes;\n spanLimits: SpanLimits;\n spanProcessor: SpanProcessor;\n}\n\n/**\n * This class represents a span.\n */\nexport class SpanImpl implements Span {\n // Below properties are included to implement ReadableSpan for export\n // purposes but are not intended to be written-to directly.\n private readonly _spanContext: SpanContext;\n readonly kind: SpanKind;\n readonly parentSpanContext?: SpanContext;\n readonly attributes: Attributes = {};\n readonly links: Link[] = [];\n readonly events: TimedEvent[] = [];\n readonly startTime: HrTime;\n readonly resource: Resource;\n readonly instrumentationScope: InstrumentationScope;\n\n private _droppedAttributesCount = 0;\n private _droppedEventsCount: number = 0;\n private _droppedLinksCount: number = 0;\n private _attributesCount: number = 0;\n\n name: string;\n status: SpanStatus = {\n code: SpanStatusCode.UNSET,\n };\n endTime: HrTime = [0, 0];\n private _ended = false;\n private _duration: HrTime = [-1, -1];\n private readonly _spanProcessor: SpanProcessor;\n private readonly _spanLimits: SpanLimits;\n private readonly _attributeValueLengthLimit: number;\n\n private readonly _performanceStartTime: number;\n private readonly _performanceOffset: number;\n private readonly _startTimeProvided: boolean;\n\n /**\n * Constructs a new SpanImpl instance.\n */\n constructor(opts: SpanOptions) {\n const now = Date.now();\n\n this._spanContext = opts.spanContext;\n this._performanceStartTime = otperformance.now();\n this._performanceOffset =\n now - (this._performanceStartTime + otperformance.timeOrigin);\n this._startTimeProvided = opts.startTime != null;\n this._spanLimits = opts.spanLimits;\n this._attributeValueLengthLimit =\n this._spanLimits.attributeValueLengthLimit || 0;\n this._spanProcessor = opts.spanProcessor;\n\n this.name = opts.name;\n this.parentSpanContext = opts.parentSpanContext;\n this.kind = opts.kind;\n this.links = opts.links || [];\n this.startTime = this._getTime(opts.startTime ?? now);\n this.resource = opts.resource;\n this.instrumentationScope = opts.scope;\n\n if (opts.attributes != null) {\n this.setAttributes(opts.attributes);\n }\n\n this._spanProcessor.onStart(this, opts.context);\n }\n\n spanContext(): SpanContext {\n return this._spanContext;\n }\n\n setAttribute(key: string, value?: AttributeValue): this;\n setAttribute(key: string, value: unknown): this {\n if (value == null || this._isSpanEnded()) return this;\n if (key.length === 0) {\n diag.warn(`Invalid attribute key: ${key}`);\n return this;\n }\n if (!isAttributeValue(value)) {\n diag.warn(`Invalid attribute value set for key: ${key}`);\n return this;\n }\n\n const { attributeCountLimit } = this._spanLimits;\n const isNewKey = !Object.prototype.hasOwnProperty.call(\n this.attributes,\n key\n );\n\n if (\n attributeCountLimit !== undefined &&\n this._attributesCount >= attributeCountLimit &&\n isNewKey\n ) {\n this._droppedAttributesCount++;\n return this;\n }\n\n this.attributes[key] = this._truncateToSize(value);\n if (isNewKey) {\n this._attributesCount++;\n }\n return this;\n }\n\n setAttributes(attributes: Attributes): this {\n for (const [k, v] of Object.entries(attributes)) {\n this.setAttribute(k, v);\n }\n return this;\n }\n\n /**\n *\n * @param name Span Name\n * @param [attributesOrStartTime] Span attributes or start time\n * if type is {@type TimeInput} and 3rd param is undefined\n * @param [timeStamp] Specified time stamp for the event\n */\n addEvent(\n name: string,\n attributesOrStartTime?: Attributes | TimeInput,\n timeStamp?: TimeInput\n ): this {\n if (this._isSpanEnded()) return this;\n\n const { eventCountLimit } = this._spanLimits;\n\n if (eventCountLimit === 0) {\n diag.warn('No events allowed.');\n this._droppedEventsCount++;\n return this;\n }\n\n if (\n eventCountLimit !== undefined &&\n this.events.length >= eventCountLimit\n ) {\n if (this._droppedEventsCount === 0) {\n diag.debug('Dropping extra events.');\n }\n this.events.shift();\n this._droppedEventsCount++;\n }\n\n if (isTimeInput(attributesOrStartTime)) {\n if (!isTimeInput(timeStamp)) {\n timeStamp = attributesOrStartTime;\n }\n attributesOrStartTime = undefined;\n }\n\n const attributes = sanitizeAttributes(attributesOrStartTime);\n\n this.events.push({\n name,\n attributes,\n time: this._getTime(timeStamp),\n droppedAttributesCount: 0,\n });\n return this;\n }\n\n addLink(link: Link): this {\n this.links.push(link);\n return this;\n }\n\n addLinks(links: Link[]): this {\n this.links.push(...links);\n return this;\n }\n\n setStatus(status: SpanStatus): this {\n if (this._isSpanEnded()) return this;\n this.status = { ...status };\n\n // When using try-catch, the caught \"error\" is of type `any`. When then assigning `any` to `status.message`,\n // TypeScript will not error. While this can happen during use of any API, it is more common on Span#setStatus()\n // as it's likely used in a catch-block. Therefore, we validate if `status.message` is actually a string, null, or\n // undefined to avoid an incorrect type causing issues downstream.\n if (this.status.message != null && typeof status.message !== 'string') {\n diag.warn(\n `Dropping invalid status.message of type '${typeof status.message}', expected 'string'`\n );\n delete this.status.message;\n }\n\n return this;\n }\n\n updateName(name: string): this {\n if (this._isSpanEnded()) return this;\n this.name = name;\n return this;\n }\n\n end(endTime?: TimeInput): void {\n if (this._isSpanEnded()) {\n diag.error(\n `${this.name} ${this._spanContext.traceId}-${this._spanContext.spanId} - You can only call end() on a span once.`\n );\n return;\n }\n this.endTime = this._getTime(endTime);\n this._duration = hrTimeDuration(this.startTime, this.endTime);\n\n if (this._duration[0] < 0) {\n diag.warn(\n 'Inconsistent start and end time, startTime > endTime. Setting span duration to 0ms.',\n this.startTime,\n this.endTime\n );\n this.endTime = this.startTime.slice() as HrTime;\n this._duration = [0, 0];\n }\n\n if (this._droppedEventsCount > 0) {\n diag.warn(\n `Dropped ${this._droppedEventsCount} events because eventCountLimit reached`\n );\n }\n if (this._spanProcessor.onEnding) {\n this._spanProcessor.onEnding(this);\n }\n\n this._ended = true;\n this._spanProcessor.onEnd(this);\n }\n\n private _getTime(inp?: TimeInput): HrTime {\n if (typeof inp === 'number' && inp <= otperformance.now()) {\n // must be a performance timestamp\n // apply correction and convert to hrtime\n return hrTime(inp + this._performanceOffset);\n }\n\n if (typeof inp === 'number') {\n return millisToHrTime(inp);\n }\n\n if (inp instanceof Date) {\n return millisToHrTime(inp.getTime());\n }\n\n if (isTimeInputHrTime(inp)) {\n return inp;\n }\n\n if (this._startTimeProvided) {\n // if user provided a time for the start manually\n // we can't use duration to calculate event/end times\n return millisToHrTime(Date.now());\n }\n\n const msDuration = otperformance.now() - this._performanceStartTime;\n return addHrTimes(this.startTime, millisToHrTime(msDuration));\n }\n\n isRecording(): boolean {\n return this._ended === false;\n }\n\n recordException(exception: Exception, time?: TimeInput): void {\n const attributes: Attributes = {};\n if (typeof exception === 'string') {\n attributes[ATTR_EXCEPTION_MESSAGE] = exception;\n } else if (exception) {\n if (exception.code) {\n attributes[ATTR_EXCEPTION_TYPE] = exception.code.toString();\n } else if (exception.name) {\n attributes[ATTR_EXCEPTION_TYPE] = exception.name;\n }\n if (exception.message) {\n attributes[ATTR_EXCEPTION_MESSAGE] = exception.message;\n }\n if (exception.stack) {\n attributes[ATTR_EXCEPTION_STACKTRACE] = exception.stack;\n }\n }\n\n // these are minimum requirements from spec\n if (attributes[ATTR_EXCEPTION_TYPE] || attributes[ATTR_EXCEPTION_MESSAGE]) {\n this.addEvent(ExceptionEventName, attributes, time);\n } else {\n diag.warn(`Failed to record an exception ${exception}`);\n }\n }\n\n get duration(): HrTime {\n return this._duration;\n }\n\n get ended(): boolean {\n return this._ended;\n }\n\n get droppedAttributesCount(): number {\n return this._droppedAttributesCount;\n }\n\n get droppedEventsCount(): number {\n return this._droppedEventsCount;\n }\n\n get droppedLinksCount(): number {\n return this._droppedLinksCount;\n }\n\n private _isSpanEnded(): boolean {\n if (this._ended) {\n const error = new Error(\n `Operation attempted on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`\n );\n\n diag.warn(\n `Cannot execute the operation on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`,\n error\n );\n }\n return this._ended;\n }\n\n // Utility function to truncate given value within size\n // for value type of string, will truncate to given limit\n // for type of non-string, will return same value\n private _truncateToLimitUtil(value: string, limit: number): string {\n if (value.length <= limit) {\n return value;\n }\n return value.substring(0, limit);\n }\n\n /**\n * If the given attribute value is of type string and has more characters than given {@code attributeValueLengthLimit} then\n * return string with truncated to {@code attributeValueLengthLimit} characters\n *\n * If the given attribute value is array of strings then\n * return new array of strings with each element truncated to {@code attributeValueLengthLimit} characters\n *\n * Otherwise return same Attribute {@code value}\n *\n * @param value Attribute value\n * @returns truncated attribute value if required, otherwise same value\n */\n private _truncateToSize(value: AttributeValue): AttributeValue {\n const limit = this._attributeValueLengthLimit;\n // Check limit\n if (limit <= 0) {\n // Negative values are invalid, so do not truncate\n diag.warn(`Attribute value limit must be positive, got ${limit}`);\n return value;\n }\n\n // String\n if (typeof value === 'string') {\n return this._truncateToLimitUtil(value, limit);\n }\n\n // Array of strings\n if (Array.isArray(value)) {\n return (value as []).map(val =>\n typeof val === 'string' ? this._truncateToLimitUtil(val, limit) : val\n );\n }\n\n // Other types, no need to apply value length limit\n return value;\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Context,\n Link,\n Attributes,\n SpanKind,\n TraceState,\n} from '@opentelemetry/api';\n\n/**\n * A sampling decision that determines how a {@link Span} will be recorded\n * and collected.\n */\nexport enum SamplingDecision {\n /**\n * `Span.isRecording() === false`, span will not be recorded and all events\n * and attributes will be dropped.\n */\n NOT_RECORD,\n /**\n * `Span.isRecording() === true`, but `Sampled` flag in {@link TraceFlags}\n * MUST NOT be set.\n */\n RECORD,\n /**\n * `Span.isRecording() === true` AND `Sampled` flag in {@link TraceFlags}\n * MUST be set.\n */\n RECORD_AND_SAMPLED,\n}\n\n/**\n * A sampling result contains a decision for a {@link Span} and additional\n * attributes the sampler would like to added to the Span.\n */\nexport interface SamplingResult {\n /**\n * A sampling decision, refer to {@link SamplingDecision} for details.\n */\n decision: SamplingDecision;\n /**\n * The list of attributes returned by SamplingResult MUST be immutable.\n * Caller may call {@link Sampler}.shouldSample any number of times and\n * can safely cache the returned value.\n */\n attributes?: Readonly<Attributes>;\n /**\n * A {@link TraceState} that will be associated with the {@link Span} through\n * the new {@link SpanContext}. Samplers SHOULD return the TraceState from\n * the passed-in {@link Context} if they do not intend to change it. Leaving\n * the value undefined will also leave the TraceState unchanged.\n */\n traceState?: TraceState;\n}\n\n/**\n * This interface represent a sampler. Sampling is a mechanism to control the\n * noise and overhead introduced by OpenTelemetry by reducing the number of\n * samples of traces collected and sent to the backend.\n */\nexport interface Sampler {\n /**\n * Checks whether span needs to be created and tracked.\n *\n * @param context Parent Context which may contain a span.\n * @param traceId of the span to be created. It can be different from the\n * traceId in the {@link SpanContext}. Typically in situations when the\n * span to be created starts a new trace.\n * @param spanName of the span to be created.\n * @param spanKind of the span to be created.\n * @param attributes Initial set of Attributes for the Span being constructed.\n * @param links Collection of links that will be associated with the Span to\n * be created. Typically useful for batch operations.\n * @returns a {@link SamplingResult}.\n */\n shouldSample(\n context: Context,\n traceId: string,\n spanName: string,\n spanKind: SpanKind,\n attributes: Attributes,\n links: Link[]\n ): SamplingResult;\n\n /** Returns the sampler name or short description with the configuration. */\n toString(): string;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Sampler, SamplingDecision, SamplingResult } from '../Sampler';\n\n/** Sampler that samples no traces. */\nexport class AlwaysOffSampler implements Sampler {\n shouldSample(): SamplingResult {\n return {\n decision: SamplingDecision.NOT_RECORD,\n };\n }\n\n toString(): string {\n return 'AlwaysOffSampler';\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Sampler, SamplingDecision, SamplingResult } from '../Sampler';\n\n/** Sampler that samples all traces. */\nexport class AlwaysOnSampler implements Sampler {\n shouldSample(): SamplingResult {\n return {\n decision: SamplingDecision.RECORD_AND_SAMPLED,\n };\n }\n\n toString(): string {\n return 'AlwaysOnSampler';\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Context,\n isSpanContextValid,\n Link,\n Attributes,\n SpanKind,\n TraceFlags,\n trace,\n} from '@opentelemetry/api';\nimport { globalErrorHandler } from '@opentelemetry/core';\nimport { AlwaysOffSampler } from './AlwaysOffSampler';\nimport { AlwaysOnSampler } from './AlwaysOnSampler';\nimport { Sampler, SamplingResult } from '../Sampler';\n\n/**\n * A composite sampler that either respects the parent span's sampling decision\n * or delegates to `delegateSampler` for root spans.\n */\nexport class ParentBasedSampler implements Sampler {\n private _root: Sampler;\n private _remoteParentSampled: Sampler;\n private _remoteParentNotSampled: Sampler;\n private _localParentSampled: Sampler;\n private _localParentNotSampled: Sampler;\n\n constructor(config: ParentBasedSamplerConfig) {\n this._root = config.root;\n\n if (!this._root) {\n globalErrorHandler(\n new Error('ParentBasedSampler must have a root sampler configured')\n );\n this._root = new AlwaysOnSampler();\n }\n\n this._remoteParentSampled =\n config.remoteParentSampled ?? new AlwaysOnSampler();\n this._remoteParentNotSampled =\n config.remoteParentNotSampled ?? new AlwaysOffSampler();\n this._localParentSampled =\n config.localParentSampled ?? new AlwaysOnSampler();\n this._localParentNotSampled =\n config.localParentNotSampled ?? new AlwaysOffSampler();\n }\n\n shouldSample(\n context: Context,\n traceId: string,\n spanName: string,\n spanKind: SpanKind,\n attributes: Attributes,\n links: Link[]\n ): SamplingResult {\n const parentContext = trace.getSpanContext(context);\n\n if (!parentContext || !isSpanContextValid(parentContext)) {\n return this._root.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n\n if (parentContext.isRemote) {\n if (parentContext.traceFlags & TraceFlags.SAMPLED) {\n return this._remoteParentSampled.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n return this._remoteParentNotSampled.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n\n if (parentContext.traceFlags & TraceFlags.SAMPLED) {\n return this._localParentSampled.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n\n return this._localParentNotSampled.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n\n toString(): string {\n return `ParentBased{root=${this._root.toString()}, remoteParentSampled=${this._remoteParentSampled.toString()}, remoteParentNotSampled=${this._remoteParentNotSampled.toString()}, localParentSampled=${this._localParentSampled.toString()}, localParentNotSampled=${this._localParentNotSampled.toString()}}`;\n }\n}\n\ninterface ParentBasedSamplerConfig {\n /** Sampler called for spans with no parent */\n root: Sampler;\n /** Sampler called for spans with a remote parent which was sampled. Default AlwaysOn */\n remoteParentSampled?: Sampler;\n /** Sampler called for spans with a remote parent which was not sampled. Default AlwaysOff */\n remoteParentNotSampled?: Sampler;\n /** Sampler called for spans with a local parent which was sampled. Default AlwaysOn */\n localParentSampled?: Sampler;\n /** Sampler called for spans with a local parent which was not sampled. Default AlwaysOff */\n localParentNotSampled?: Sampler;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isValidTraceId } from '@opentelemetry/api';\nimport { Sampler, SamplingDecision, SamplingResult } from '../Sampler';\n\n/** Sampler that samples a given fraction of traces based of trace id deterministically. */\nexport class TraceIdRatioBasedSampler implements Sampler {\n private readonly _ratio;\n private _upperBound: number;\n\n constructor(ratio = 0) {\n this._ratio = this._normalize(ratio);\n this._upperBound = Math.floor(this._ratio * 0xffffffff);\n }\n\n shouldSample(context: unknown, traceId: string): SamplingResult {\n return {\n decision:\n isValidTraceId(traceId) && this._accumulate(traceId) < this._upperBound\n ? SamplingDecision.RECORD_AND_SAMPLED\n : SamplingDecision.NOT_RECORD,\n };\n }\n\n toString(): string {\n return `TraceIdRatioBased{${this._ratio}}`;\n }\n\n private _normalize(ratio: number): number {\n if (typeof ratio !== 'number' || isNaN(ratio)) return 0;\n return ratio >= 1 ? 1 : ratio <= 0 ? 0 : ratio;\n }\n\n private _accumulate(traceId: string): number {\n let accumulation = 0;\n for (let i = 0; i < traceId.length / 8; i++) {\n const pos = i * 8;\n const part = parseInt(traceId.slice(pos, pos + 8), 16);\n accumulation = (accumulation ^ part) >>> 0;\n }\n return accumulation;\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { diag } from '@opentelemetry/api';\nimport { getNumberFromEnv, getStringFromEnv } from '@opentelemetry/core';\nimport { Sampler } from './Sampler';\nimport { AlwaysOffSampler } from './sampler/AlwaysOffSampler';\nimport { AlwaysOnSampler } from './sampler/AlwaysOnSampler';\nimport { ParentBasedSampler } from './sampler/ParentBasedSampler';\nimport { TraceIdRatioBasedSampler } from './sampler/TraceIdRatioBasedSampler';\n\nconst enum TracesSamplerValues {\n AlwaysOff = 'always_off',\n AlwaysOn = 'always_on',\n ParentBasedAlwaysOff = 'parentbased_always_off',\n ParentBasedAlwaysOn = 'parentbased_always_on',\n ParentBasedTraceIdRatio = 'parentbased_traceidratio',\n TraceIdRatio = 'traceidratio',\n}\n\nconst DEFAULT_RATIO = 1;\n\n/**\n * Load default configuration. For fields with primitive values, any user-provided\n * value will override the corresponding default value. For fields with\n * non-primitive values (like `spanLimits`), the user-provided value will be\n * used to extend the default value.\n */\n\n// object needs to be wrapped in this function and called when needed otherwise\n// envs are parsed before tests are ran - causes tests using these envs to fail\nexport function loadDefaultConfig() {\n return {\n sampler: buildSamplerFromEnv(),\n forceFlushTimeoutMillis: 30000,\n generalLimits: {\n attributeValueLengthLimit:\n getNumberFromEnv('OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT') ?? Infinity,\n attributeCountLimit:\n getNumberFromEnv('OTEL_ATTRIBUTE_COUNT_LIMIT') ?? 128,\n },\n spanLimits: {\n attributeValueLengthLimit:\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT') ?? Infinity,\n attributeCountLimit:\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT') ?? 128,\n linkCountLimit: getNumberFromEnv('OTEL_SPAN_LINK_COUNT_LIMIT') ?? 128,\n eventCountLimit: getNumberFromEnv('OTEL_SPAN_EVENT_COUNT_LIMIT') ?? 128,\n attributePerEventCountLimit:\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT') ?? 128,\n attributePerLinkCountLimit:\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT') ?? 128,\n },\n };\n}\n\n/**\n * Based on environment, builds a sampler, complies with specification.\n */\nexport function buildSamplerFromEnv(): Sampler {\n const sampler =\n getStringFromEnv('OTEL_TRACES_SAMPLER') ??\n TracesSamplerValues.ParentBasedAlwaysOn;\n switch (sampler) {\n case TracesSamplerValues.AlwaysOn:\n return new AlwaysOnSampler();\n case TracesSamplerValues.AlwaysOff:\n return new AlwaysOffSampler();\n case TracesSamplerValues.ParentBasedAlwaysOn:\n return new ParentBasedSampler({\n root: new AlwaysOnSampler(),\n });\n case TracesSamplerValues.ParentBasedAlwaysOff:\n return new ParentBasedSampler({\n root: new AlwaysOffSampler(),\n });\n case TracesSamplerValues.TraceIdRatio:\n return new TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv());\n case TracesSamplerValues.ParentBasedTraceIdRatio:\n return new ParentBasedSampler({\n root: new TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv()),\n });\n default:\n diag.error(\n `OTEL_TRACES_SAMPLER value \"${sampler}\" invalid, defaulting to \"${TracesSamplerValues.ParentBasedAlwaysOn}\".`\n );\n return new ParentBasedSampler({\n root: new AlwaysOnSampler(),\n });\n }\n}\n\nfunction getSamplerProbabilityFromEnv(): number | undefined {\n const probability = getNumberFromEnv('OTEL_TRACES_SAMPLER_ARG');\n if (probability == null) {\n diag.error(\n `OTEL_TRACES_SAMPLER_ARG is blank, defaulting to ${DEFAULT_RATIO}.`\n );\n return DEFAULT_RATIO;\n }\n\n if (probability < 0 || probability > 1) {\n diag.error(\n `OTEL_TRACES_SAMPLER_ARG=${probability} was given, but it is out of range ([0..1]), defaulting to ${DEFAULT_RATIO}.`\n );\n return DEFAULT_RATIO;\n }\n\n return probability;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { buildSamplerFromEnv, loadDefaultConfig } from './config';\nimport { Sampler } from './Sampler';\nimport { SpanLimits, TracerConfig, GeneralLimits } from './types';\nimport { getNumberFromEnv } from '@opentelemetry/core';\n\nexport const DEFAULT_ATTRIBUTE_COUNT_LIMIT = 128;\nexport const DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT = Infinity;\n\n/**\n * Function to merge Default configuration (as specified in './config') with\n * user provided configurations.\n */\nexport function mergeConfig(userConfig: TracerConfig): TracerConfig & {\n sampler: Sampler;\n spanLimits: SpanLimits;\n generalLimits: GeneralLimits;\n} {\n const perInstanceDefaults: Partial<TracerConfig> = {\n sampler: buildSamplerFromEnv(),\n };\n\n const DEFAULT_CONFIG = loadDefaultConfig();\n\n const target = Object.assign(\n {},\n DEFAULT_CONFIG,\n perInstanceDefaults,\n userConfig\n );\n\n target.generalLimits = Object.assign(\n {},\n DEFAULT_CONFIG.generalLimits,\n userConfig.generalLimits || {}\n );\n\n target.spanLimits = Object.assign(\n {},\n DEFAULT_CONFIG.spanLimits,\n userConfig.spanLimits || {}\n );\n\n return target;\n}\n\n/**\n * When general limits are provided and model specific limits are not,\n * configures the model specific limits by using the values from the general ones.\n * @param userConfig User provided tracer configuration\n */\nexport function reconfigureLimits(userConfig: TracerConfig): TracerConfig {\n const spanLimits = Object.assign({}, userConfig.spanLimits);\n\n /**\n * Reassign span attribute count limit to use first non null value defined by user or use default value\n */\n spanLimits.attributeCountLimit =\n userConfig.spanLimits?.attributeCountLimit ??\n userConfig.generalLimits?.attributeCountLimit ??\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT') ??\n getNumberFromEnv('OTEL_ATTRIBUTE_COUNT_LIMIT') ??\n DEFAULT_ATTRIBUTE_COUNT_LIMIT;\n\n /**\n * Reassign span attribute value length limit to use first non null value defined by user or use default value\n */\n spanLimits.attributeValueLengthLimit =\n userConfig.spanLimits?.attributeValueLengthLimit ??\n userConfig.generalLimits?.attributeValueLengthLimit ??\n getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT') ??\n getNumberFromEnv('OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT') ??\n DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT;\n\n return Object.assign({}, userConfig, { spanLimits });\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { context, Context, diag, TraceFlags } from '@opentelemetry/api';\nimport {\n BindOnceFuture,\n ExportResultCode,\n getNumberFromEnv,\n globalErrorHandler,\n suppressTracing,\n} from '@opentelemetry/core';\nimport { Span } from '../Span';\nimport { SpanProcessor } from '../SpanProcessor';\nimport { BufferConfig } from '../types';\nimport { ReadableSpan } from './ReadableSpan';\nimport { SpanExporter } from './SpanExporter';\n\n/**\n * Implementation of the {@link SpanProcessor} that batches spans exported by\n * the SDK then pushes them to the exporter pipeline.\n */\nexport abstract class BatchSpanProcessorBase<T extends BufferConfig>\n implements SpanProcessor\n{\n private readonly _maxExportBatchSize: number;\n private readonly _maxQueueSize: number;\n private readonly _scheduledDelayMillis: number;\n private readonly _exportTimeoutMillis: number;\n private readonly _exporter: SpanExporter;\n\n private _isExporting = false;\n private _finishedSpans: ReadableSpan[] = [];\n private _timer: NodeJS.Timeout | number | undefined;\n private _shutdownOnce: BindOnceFuture<void>;\n private _droppedSpansCount: number = 0;\n\n constructor(exporter: SpanExporter, config?: T) {\n this._exporter = exporter;\n this._maxExportBatchSize =\n typeof config?.maxExportBatchSize === 'number'\n ? config.maxExportBatchSize\n : (getNumberFromEnv('OTEL_BSP_MAX_EXPORT_BATCH_SIZE') ?? 512);\n this._maxQueueSize =\n typeof config?.maxQueueSize === 'number'\n ? config.maxQueueSize\n : (getNumberFromEnv('OTEL_BSP_MAX_QUEUE_SIZE') ?? 2048);\n this._scheduledDelayMillis =\n typeof config?.scheduledDelayMillis === 'number'\n ? config.scheduledDelayMillis\n : (getNumberFromEnv('OTEL_BSP_SCHEDULE_DELAY') ?? 5000);\n this._exportTimeoutMillis =\n typeof config?.exportTimeoutMillis === 'number'\n ? config.exportTimeoutMillis\n : (getNumberFromEnv('OTEL_BSP_EXPORT_TIMEOUT') ?? 30000);\n\n this._shutdownOnce = new BindOnceFuture(this._shutdown, this);\n\n if (this._maxExportBatchSize > this._maxQueueSize) {\n diag.warn(\n 'BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize'\n );\n this._maxExportBatchSize = this._maxQueueSize;\n }\n }\n\n forceFlush(): Promise<void> {\n if (this._shutdownOnce.isCalled) {\n return this._shutdownOnce.promise;\n }\n return this._flushAll();\n }\n\n // does nothing.\n onStart(_span: Span, _parentContext: Context): void {}\n\n onEnd(span: ReadableSpan): void {\n if (this._shutdownOnce.isCalled) {\n return;\n }\n\n if ((span.spanContext().traceFlags & TraceFlags.SAMPLED) === 0) {\n return;\n }\n\n this._addToBuffer(span);\n }\n\n shutdown(): Promise<void> {\n return this._shutdownOnce.call();\n }\n\n private _shutdown() {\n return Promise.resolve()\n .then(() => {\n return this.onShutdown();\n })\n .then(() => {\n return this._flushAll();\n })\n .then(() => {\n return this._exporter.shutdown();\n });\n }\n\n /** Add a span in the buffer. */\n private _addToBuffer(span: ReadableSpan) {\n if (this._finishedSpans.length >= this._maxQueueSize) {\n // limit reached, drop span\n\n if (this._droppedSpansCount === 0) {\n diag.debug('maxQueueSize reached, dropping spans');\n }\n this._droppedSpansCount++;\n\n return;\n }\n\n if (this._droppedSpansCount > 0) {\n // some spans were dropped, log once with count of spans dropped\n diag.warn(\n `Dropped ${this._droppedSpansCount} spans because maxQueueSize reached`\n );\n this._droppedSpansCount = 0;\n }\n\n this._finishedSpans.push(span);\n this._maybeStartTimer();\n }\n\n /**\n * Send all spans to the exporter respecting the batch size limit\n * This function is used only on forceFlush or shutdown,\n * for all other cases _flush should be used\n * */\n private _flushAll(): Promise<void> {\n return new Promise((resolve, reject) => {\n const promises = [];\n // calculate number of batches\n const count = Math.ceil(\n this._finishedSpans.length / this._maxExportBatchSize\n );\n for (let i = 0, j = count; i < j; i++) {\n promises.push(this._flushOneBatch());\n }\n Promise.all(promises)\n .then(() => {\n resolve();\n })\n .catch(reject);\n });\n }\n\n private _flushOneBatch(): Promise<void> {\n this._clearTimer();\n if (this._finishedSpans.length === 0) {\n return Promise.resolve();\n }\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n // don't wait anymore for export, this way the next batch can start\n reject(new Error('Timeout'));\n }, this._exportTimeoutMillis);\n // prevent downstream exporter calls from generating spans\n context.with(suppressTracing(context.active()), () => {\n // Reset the finished spans buffer here because the next invocations of the _flush method\n // could pass the same finished spans to the exporter if the buffer is cleared\n // outside the execution of this callback.\n let spans: ReadableSpan[];\n if (this._finishedSpans.length <= this._maxExportBatchSize) {\n spans = this._finishedSpans;\n this._finishedSpans = [];\n } else {\n spans = this._finishedSpans.splice(0, this._maxExportBatchSize);\n }\n\n const doExport = () =>\n this._exporter.export(spans, result => {\n clearTimeout(timer);\n if (result.code === ExportResultCode.SUCCESS) {\n resolve();\n } else {\n reject(\n result.error ??\n new Error('BatchSpanProcessor: span export failed')\n );\n }\n });\n\n let pendingResources: Array<Promise<void>> | null = null;\n for (let i = 0, len = spans.length; i < len; i++) {\n const span = spans[i];\n if (\n span.resource.asyncAttributesPending &&\n span.resource.waitForAsyncAttributes\n ) {\n pendingResources ??= [];\n pendingResources.push(span.resource.waitForAsyncAttributes());\n }\n }\n\n // Avoid scheduling a promise to make the behavior more predictable and easier to test\n if (pendingResources === null) {\n doExport();\n } else {\n Promise.all(pendingResources).then(doExport, err => {\n globalErrorHandler(err);\n reject(err);\n });\n }\n });\n });\n }\n\n private _maybeStartTimer() {\n if (this._isExporting) return;\n const flush = () => {\n this._isExporting = true;\n this._flushOneBatch()\n .finally(() => {\n this._isExporting = false;\n if (this._finishedSpans.length > 0) {\n this._clearTimer();\n this._maybeStartTimer();\n }\n })\n .catch(e => {\n this._isExporting = false;\n globalErrorHandler(e);\n });\n };\n // we only wait if the queue doesn't have enough elements yet\n if (this._finishedSpans.length >= this._maxExportBatchSize) {\n return flush();\n }\n if (this._timer !== undefined) return;\n this._timer = setTimeout(() => flush(), this._scheduledDelayMillis);\n\n // depending on runtime, this may be a 'number' or NodeJS.Timeout\n if (typeof this._timer !== 'number') {\n this._timer.unref();\n }\n }\n\n private _clearTimer() {\n if (this._timer !== undefined) {\n clearTimeout(this._timer);\n this._timer = undefined;\n }\n }\n\n protected abstract onShutdown(): void;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BatchSpanProcessorBase } from '../../../export/BatchSpanProcessorBase';\nimport { BufferConfig } from '../../../types';\n\nexport class BatchSpanProcessor extends BatchSpanProcessorBase<BufferConfig> {\n protected onShutdown(): void {}\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { IdGenerator } from '../../IdGenerator';\n\nconst SPAN_ID_BYTES = 8;\nconst TRACE_ID_BYTES = 16;\n\nexport class RandomIdGenerator implements IdGenerator {\n /**\n * Returns a random 16-byte trace ID formatted/encoded as a 32 lowercase hex\n * characters corresponding to 128 bits.\n */\n generateTraceId = getIdGenerator(TRACE_ID_BYTES);\n\n /**\n * Returns a random 8-byte span ID formatted/encoded as a 16 lowercase hex\n * characters corresponding to 64 bits.\n */\n generateSpanId = getIdGenerator(SPAN_ID_BYTES);\n}\n\nconst SHARED_BUFFER = Buffer.allocUnsafe(TRACE_ID_BYTES);\nfunction getIdGenerator(bytes: number): () => string {\n return function generateId() {\n for (let i = 0; i < bytes / 4; i++) {\n // unsigned right shift drops decimal part of the number\n // it is required because if a number between 2**32 and 2**32 - 1 is generated, an out of range error is thrown by writeUInt32BE\n SHARED_BUFFER.writeUInt32BE((Math.random() * 2 ** 32) >>> 0, i * 4);\n }\n\n // If buffer is all 0, set the last byte to 1 to guarantee a valid w3c id is generated\n for (let i = 0; i < bytes; i++) {\n if (SHARED_BUFFER[i] > 0) {\n break;\n } else if (i === bytes - 1) {\n SHARED_BUFFER[bytes - 1] = 1;\n }\n }\n\n return SHARED_BUFFER.toString('hex', 0, bytes);\n };\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport { BatchSpanProcessor } from './export/BatchSpanProcessor';\nexport { RandomIdGenerator } from './RandomIdGenerator';\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport { BatchSpanProcessor, RandomIdGenerator } from './node';\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as api from '@opentelemetry/api';\nimport {\n InstrumentationScope,\n sanitizeAttributes,\n isTracingSuppressed,\n} from '@opentelemetry/core';\nimport { SpanImpl } from './Span';\nimport { GeneralLimits, SpanLimits, TracerConfig } from './types';\nimport { mergeConfig } from './utility';\nimport { SpanProcessor } from './SpanProcessor';\nimport { Sampler } from './Sampler';\nimport { IdGenerator } from './IdGenerator';\nimport { RandomIdGenerator } from './platform';\nimport { Resource } from '@opentelemetry/resources';\n\n/**\n * This class represents a basic tracer.\n */\nexport class Tracer implements api.Tracer {\n private readonly _sampler: Sampler;\n private readonly _generalLimits: GeneralLimits;\n private readonly _spanLimits: SpanLimits;\n private readonly _idGenerator: IdGenerator;\n readonly instrumentationScope: InstrumentationScope;\n\n private readonly _resource: Resource;\n private readonly _spanProcessor: SpanProcessor;\n\n /**\n * Constructs a new Tracer instance.\n */\n constructor(\n instrumentationScope: InstrumentationScope,\n config: TracerConfig,\n resource: Resource,\n spanProcessor: SpanProcessor\n ) {\n const localConfig = mergeConfig(config);\n this._sampler = localConfig.sampler;\n this._generalLimits = localConfig.generalLimits;\n this._spanLimits = localConfig.spanLimits;\n this._idGenerator = config.idGenerator || new RandomIdGenerator();\n this._resource = resource;\n this._spanProcessor = spanProcessor;\n this.instrumentationScope = instrumentationScope;\n }\n\n /**\n * Starts a new Span or returns the default NoopSpan based on the sampling\n * decision.\n */\n startSpan(\n name: string,\n options: api.SpanOptions = {},\n context = api.context.active()\n ): api.Span {\n // remove span from context in case a root span is requested via options\n if (options.root) {\n context = api.trace.deleteSpan(context);\n }\n const parentSpan = api.trace.getSpan(context);\n\n if (isTracingSuppressed(context)) {\n api.diag.debug('Instrumentation suppressed, returning Noop Span');\n const nonRecordingSpan = api.trace.wrapSpanContext(\n api.INVALID_SPAN_CONTEXT\n );\n return nonRecordingSpan;\n }\n\n const parentSpanContext = parentSpan?.spanContext();\n const spanId = this._idGenerator.generateSpanId();\n let validParentSpanContext;\n let traceId;\n let traceState;\n if (\n !parentSpanContext ||\n !api.trace.isSpanContextValid(parentSpanContext)\n ) {\n // New root span.\n traceId = this._idGenerator.generateTraceId();\n } else {\n // New child span.\n traceId = parentSpanContext.traceId;\n traceState = parentSpanContext.traceState;\n validParentSpanContext = parentSpanContext;\n }\n\n const spanKind = options.kind ?? api.SpanKind.INTERNAL;\n const links = (options.links ?? []).map(link => {\n return {\n context: link.context,\n attributes: sanitizeAttributes(link.attributes),\n };\n });\n const attributes = sanitizeAttributes(options.attributes);\n // make sampling decision\n const samplingResult = this._sampler.shouldSample(\n context,\n traceId,\n name,\n spanKind,\n attributes,\n links\n );\n\n traceState = samplingResult.traceState ?? traceState;\n\n const traceFlags =\n samplingResult.decision === api.SamplingDecision.RECORD_AND_SAMPLED\n ? api.TraceFlags.SAMPLED\n : api.TraceFlags.NONE;\n const spanContext = { traceId, spanId, traceFlags, traceState };\n if (samplingResult.decision === api.SamplingDecision.NOT_RECORD) {\n api.diag.debug(\n 'Recording is off, propagating context in a non-recording span'\n );\n const nonRecordingSpan = api.trace.wrapSpanContext(spanContext);\n return nonRecordingSpan;\n }\n\n // Set initial span attributes. The attributes object may have been mutated\n // by the sampler, so we sanitize the merged attributes before setting them.\n const initAttributes = sanitizeAttributes(\n Object.assign(attributes, samplingResult.attributes)\n );\n\n const span = new SpanImpl({\n resource: this._resource,\n scope: this.instrumentationScope,\n context,\n spanContext,\n name,\n kind: spanKind,\n links,\n parentSpanContext: validParentSpanContext,\n attributes: initAttributes,\n startTime: options.startTime,\n spanProcessor: this._spanProcessor,\n spanLimits: this._spanLimits,\n });\n return span;\n }\n\n /**\n * Starts a new {@link Span} and calls the given function passing it the\n * created span as first argument.\n * Additionally the new span gets set in context and this context is activated\n * for the duration of the function call.\n *\n * @param name The name of the span\n * @param [options] SpanOptions used for span creation\n * @param [context] Context to use to extract parent\n * @param fn function called in the context of the span and receives the newly created span as an argument\n * @returns return value of fn\n * @example\n * const something = tracer.startActiveSpan('op', span => {\n * try {\n * do some work\n * span.setStatus({code: SpanStatusCode.OK});\n * return something;\n * } catch (err) {\n * span.setStatus({\n * code: SpanStatusCode.ERROR,\n * message: err.message,\n * });\n * throw err;\n * } finally {\n * span.end();\n * }\n * });\n * @example\n * const span = tracer.startActiveSpan('op', span => {\n * try {\n * do some work\n * return span;\n * } catch (err) {\n * span.setStatus({\n * code: SpanStatusCode.ERROR,\n * message: err.message,\n * });\n * throw err;\n * }\n * });\n * do some more work\n * span.end();\n */\n startActiveSpan<F extends (span: api.Span) => ReturnType<F>>(\n name: string,\n fn: F\n ): ReturnType<F>;\n startActiveSpan<F extends (span: api.Span) => ReturnType<F>>(\n name: string,\n opts: api.SpanOptions,\n fn: F\n ): ReturnType<F>;\n startActiveSpan<F extends (span: api.Span) => ReturnType<F>>(\n name: string,\n opts: api.SpanOptions,\n ctx: api.Context,\n fn: F\n ): ReturnType<F>;\n startActiveSpan<F extends (span: api.Span) => ReturnType<F>>(\n name: string,\n arg2?: F | api.SpanOptions,\n arg3?: F | api.Context,\n arg4?: F\n ): ReturnType<F> | undefined {\n let opts: api.SpanOptions | undefined;\n let ctx: api.Context | undefined;\n let fn: F;\n\n if (arguments.length < 2) {\n return;\n } else if (arguments.length === 2) {\n fn = arg2 as F;\n } else if (arguments.length === 3) {\n opts = arg2 as api.SpanOptions | undefined;\n fn = arg3 as F;\n } else {\n opts = arg2 as api.SpanOptions | undefined;\n ctx = arg3 as api.Context | undefined;\n fn = arg4 as F;\n }\n\n const parentContext = ctx ?? api.context.active();\n const span = this.startSpan(name, opts, parentContext);\n const contextWithSpanSet = api.trace.setSpan(parentContext, span);\n\n return api.context.with(contextWithSpanSet, fn, undefined, span);\n }\n\n /** Returns the active {@link GeneralLimits}. */\n getGeneralLimits(): GeneralLimits {\n return this._generalLimits;\n }\n\n /** Returns the active {@link SpanLimits}. */\n getSpanLimits(): SpanLimits {\n return this._spanLimits;\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context } from '@opentelemetry/api';\nimport { globalErrorHandler } from '@opentelemetry/core';\nimport { ReadableSpan } from './export/ReadableSpan';\nimport { Span } from './Span';\nimport { SpanProcessor } from './SpanProcessor';\n\n/**\n * Implementation of the {@link SpanProcessor} that simply forwards all\n * received events to a list of {@link SpanProcessor}s.\n */\nexport class MultiSpanProcessor implements SpanProcessor {\n private readonly _spanProcessors: SpanProcessor[];\n constructor(spanProcessors: SpanProcessor[]) {\n this._spanProcessors = spanProcessors;\n }\n\n forceFlush(): Promise<void> {\n const promises: Promise<void>[] = [];\n\n for (const spanProcessor of this._spanProcessors) {\n promises.push(spanProcessor.forceFlush());\n }\n return new Promise(resolve => {\n Promise.all(promises)\n .then(() => {\n resolve();\n })\n .catch(error => {\n globalErrorHandler(\n error || new Error('MultiSpanProcessor: forceFlush failed')\n );\n resolve();\n });\n });\n }\n\n onStart(span: Span, context: Context): void {\n for (const spanProcessor of this._spanProcessors) {\n spanProcessor.onStart(span, context);\n }\n }\n\n onEnding(span: Span): void {\n for (const spanProcessor of this._spanProcessors) {\n if (spanProcessor.onEnding) {\n spanProcessor.onEnding(span);\n }\n }\n }\n\n onEnd(span: ReadableSpan): void {\n for (const spanProcessor of this._spanProcessors) {\n spanProcessor.onEnd(span);\n }\n }\n\n shutdown(): Promise<void> {\n const promises: Promise<void>[] = [];\n\n for (const spanProcessor of this._spanProcessors) {\n promises.push(spanProcessor.shutdown());\n }\n return new Promise((resolve, reject) => {\n Promise.all(promises).then(() => {\n resolve();\n }, reject);\n });\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TracerProvider, Tracer as ApiTracer } from '@opentelemetry/api';\nimport { merge } from '@opentelemetry/core';\nimport { defaultResource, Resource } from '@opentelemetry/resources';\nimport { SpanProcessor } from './SpanProcessor';\nimport { Tracer } from './Tracer';\nimport { loadDefaultConfig } from './config';\nimport { MultiSpanProcessor } from './MultiSpanProcessor';\nimport { TracerConfig } from './types';\nimport { reconfigureLimits } from './utility';\n\nexport enum ForceFlushState {\n 'resolved',\n 'timeout',\n 'error',\n 'unresolved',\n}\n\n/**\n * This class represents a basic tracer provider which platform libraries can extend\n */\nexport class BasicTracerProvider implements TracerProvider {\n private readonly _config: TracerConfig;\n private readonly _tracers: Map<string, Tracer> = new Map();\n private readonly _resource: Resource;\n private readonly _activeSpanProcessor: MultiSpanProcessor;\n\n constructor(config: TracerConfig = {}) {\n const mergedConfig = merge(\n {},\n loadDefaultConfig(),\n reconfigureLimits(config)\n );\n this._resource = mergedConfig.resource ?? defaultResource();\n\n this._config = Object.assign({}, mergedConfig, {\n resource: this._resource,\n });\n\n const spanProcessors: SpanProcessor[] = [];\n\n if (config.spanProcessors?.length) {\n spanProcessors.push(...config.spanProcessors);\n }\n\n this._activeSpanProcessor = new MultiSpanProcessor(spanProcessors);\n }\n\n getTracer(\n name: string,\n version?: string,\n options?: { schemaUrl?: string }\n ): ApiTracer {\n const key = `${name}@${version || ''}:${options?.schemaUrl || ''}`;\n if (!this._tracers.has(key)) {\n this._tracers.set(\n key,\n new Tracer(\n { name, version, schemaUrl: options?.schemaUrl },\n this._config,\n this._resource,\n this._activeSpanProcessor\n )\n );\n }\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return this._tracers.get(key)!;\n }\n\n forceFlush(): Promise<void> {\n const timeout = this._config.forceFlushTimeoutMillis;\n const promises = this._activeSpanProcessor['_spanProcessors'].map(\n (spanProcessor: SpanProcessor) => {\n return new Promise(resolve => {\n let state: ForceFlushState;\n const timeoutInterval = setTimeout(() => {\n resolve(\n new Error(\n `Span processor did not completed within timeout period of ${timeout} ms`\n )\n );\n state = ForceFlushState.timeout;\n }, timeout);\n\n spanProcessor\n .forceFlush()\n .then(() => {\n clearTimeout(timeoutInterval);\n if (state !== ForceFlushState.timeout) {\n state = ForceFlushState.resolved;\n resolve(state);\n }\n })\n .catch(error => {\n clearTimeout(timeoutInterval);\n state = ForceFlushState.error;\n resolve(error);\n });\n });\n }\n );\n\n return new Promise<void>((resolve, reject) => {\n Promise.all(promises)\n .then(results => {\n const errors = results.filter(\n result => result !== ForceFlushState.resolved\n );\n if (errors.length > 0) {\n reject(errors);\n } else {\n resolve();\n }\n })\n .catch(error => reject([error]));\n });\n }\n\n shutdown(): Promise<void> {\n return this._activeSpanProcessor.shutdown();\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SpanExporter } from './SpanExporter';\nimport { ReadableSpan } from './ReadableSpan';\nimport {\n ExportResult,\n ExportResultCode,\n hrTimeToMicroseconds,\n} from '@opentelemetry/core';\n\n/**\n * This is implementation of {@link SpanExporter} that prints spans to the\n * console. This class can be used for diagnostic purposes.\n *\n * NOTE: This {@link SpanExporter} is intended for diagnostics use only, output rendered to the console may change at any time.\n */\n\n/* eslint-disable no-console */\nexport class ConsoleSpanExporter implements SpanExporter {\n /**\n * Export spans.\n * @param spans\n * @param resultCallback\n */\n export(\n spans: ReadableSpan[],\n resultCallback: (result: ExportResult) => void\n ): void {\n return this._sendSpans(spans, resultCallback);\n }\n\n /**\n * Shutdown the exporter.\n */\n shutdown(): Promise<void> {\n this._sendSpans([]);\n return this.forceFlush();\n }\n\n /**\n * Exports any pending spans in exporter\n */\n forceFlush(): Promise<void> {\n return Promise.resolve();\n }\n\n /**\n * converts span info into more readable format\n * @param span\n */\n private _exportInfo(span: ReadableSpan) {\n return {\n resource: {\n attributes: span.resource.attributes,\n },\n instrumentationScope: span.instrumentationScope,\n traceId: span.spanContext().traceId,\n parentSpanContext: span.parentSpanContext,\n traceState: span.spanContext().traceState?.serialize(),\n name: span.name,\n id: span.spanContext().spanId,\n kind: span.kind,\n timestamp: hrTimeToMicroseconds(span.startTime),\n duration: hrTimeToMicroseconds(span.duration),\n attributes: span.attributes,\n status: span.status,\n events: span.events,\n links: span.links,\n };\n }\n\n /**\n * Showing spans in console\n * @param spans\n * @param done\n */\n private _sendSpans(\n spans: ReadableSpan[],\n done?: (result: ExportResult) => void\n ): void {\n for (const span of spans) {\n console.dir(this._exportInfo(span), { depth: 3 });\n }\n if (done) {\n return done({ code: ExportResultCode.SUCCESS });\n }\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SpanExporter } from './SpanExporter';\nimport { ReadableSpan } from './ReadableSpan';\nimport { ExportResult, ExportResultCode } from '@opentelemetry/core';\n\n/**\n * This class can be used for testing purposes. It stores the exported spans\n * in a list in memory that can be retrieved using the `getFinishedSpans()`\n * method.\n */\nexport class InMemorySpanExporter implements SpanExporter {\n private _finishedSpans: ReadableSpan[] = [];\n /**\n * Indicates if the exporter has been \"shutdown.\"\n * When false, exported spans will not be stored in-memory.\n */\n protected _stopped = false;\n\n export(\n spans: ReadableSpan[],\n resultCallback: (result: ExportResult) => void\n ): void {\n if (this._stopped)\n return resultCallback({\n code: ExportResultCode.FAILED,\n error: new Error('Exporter has been stopped'),\n });\n this._finishedSpans.push(...spans);\n\n setTimeout(() => resultCallback({ code: ExportResultCode.SUCCESS }), 0);\n }\n\n shutdown(): Promise<void> {\n this._stopped = true;\n this._finishedSpans = [];\n return this.forceFlush();\n }\n\n /**\n * Exports any pending spans in the exporter\n */\n forceFlush(): Promise<void> {\n return Promise.resolve();\n }\n\n reset(): void {\n this._finishedSpans = [];\n }\n\n getFinishedSpans(): ReadableSpan[] {\n return this._finishedSpans;\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context, TraceFlags } from '@opentelemetry/api';\nimport {\n internal,\n ExportResultCode,\n globalErrorHandler,\n BindOnceFuture,\n} from '@opentelemetry/core';\nimport { Span } from '../Span';\nimport { SpanProcessor } from '../SpanProcessor';\nimport { ReadableSpan } from './ReadableSpan';\nimport { SpanExporter } from './SpanExporter';\n\n/**\n * An implementation of the {@link SpanProcessor} that converts the {@link Span}\n * to {@link ReadableSpan} and passes it to the configured exporter.\n *\n * Only spans that are sampled are converted.\n *\n * NOTE: This {@link SpanProcessor} exports every ended span individually instead of batching spans together, which causes significant performance overhead with most exporters. For production use, please consider using the {@link BatchSpanProcessor} instead.\n */\nexport class SimpleSpanProcessor implements SpanProcessor {\n private readonly _exporter: SpanExporter;\n private _shutdownOnce: BindOnceFuture<void>;\n private _pendingExports: Set<Promise<void>>;\n\n constructor(exporter: SpanExporter) {\n this._exporter = exporter;\n this._shutdownOnce = new BindOnceFuture(this._shutdown, this);\n this._pendingExports = new Set<Promise<void>>();\n }\n\n async forceFlush(): Promise<void> {\n await Promise.all(Array.from(this._pendingExports));\n if (this._exporter.forceFlush) {\n await this._exporter.forceFlush();\n }\n }\n\n onStart(_span: Span, _parentContext: Context): void {}\n\n onEnd(span: ReadableSpan): void {\n if (this._shutdownOnce.isCalled) {\n return;\n }\n\n if ((span.spanContext().traceFlags & TraceFlags.SAMPLED) === 0) {\n return;\n }\n\n const pendingExport = this._doExport(span).catch(err =>\n globalErrorHandler(err)\n );\n // Enqueue this export to the pending list so it can be flushed by the user.\n this._pendingExports.add(pendingExport);\n void pendingExport.finally(() =>\n this._pendingExports.delete(pendingExport)\n );\n }\n\n private async _doExport(span: ReadableSpan): Promise<void> {\n if (span.resource.asyncAttributesPending) {\n // Ensure resource is fully resolved before exporting.\n await span.resource.waitForAsyncAttributes?.();\n }\n\n const result = await internal._export(this._exporter, [span]);\n if (result.code !== ExportResultCode.SUCCESS) {\n throw (\n result.error ??\n new Error(`SimpleSpanProcessor: span export failed (status ${result})`)\n );\n }\n }\n\n shutdown(): Promise<void> {\n return this._shutdownOnce.call();\n }\n\n private _shutdown(): Promise<void> {\n return this._exporter.shutdown();\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context } from '@opentelemetry/api';\nimport { ReadableSpan } from './ReadableSpan';\nimport { Span } from '../Span';\nimport { SpanProcessor } from '../SpanProcessor';\n\n/** No-op implementation of SpanProcessor */\nexport class NoopSpanProcessor implements SpanProcessor {\n onStart(_span: Span, _context: Context): void {}\n onEnd(_span: ReadableSpan): void {}\n shutdown(): Promise<void> {\n return Promise.resolve();\n }\n forceFlush(): Promise<void> {\n return Promise.resolve();\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport { BasicTracerProvider } from './BasicTracerProvider';\nexport { BatchSpanProcessor, RandomIdGenerator } from './platform';\nexport { ConsoleSpanExporter } from './export/ConsoleSpanExporter';\nexport { InMemorySpanExporter } from './export/InMemorySpanExporter';\nexport type { ReadableSpan } from './export/ReadableSpan';\nexport { SimpleSpanProcessor } from './export/SimpleSpanProcessor';\nexport type { SpanExporter } from './export/SpanExporter';\nexport { NoopSpanProcessor } from './export/NoopSpanProcessor';\nexport { AlwaysOffSampler } from './sampler/AlwaysOffSampler';\nexport { AlwaysOnSampler } from './sampler/AlwaysOnSampler';\nexport { ParentBasedSampler } from './sampler/ParentBasedSampler';\nexport { TraceIdRatioBasedSampler } from './sampler/TraceIdRatioBasedSampler';\nexport { SamplingDecision } from './Sampler';\nexport type { Sampler, SamplingResult } from './Sampler';\nexport type { Span } from './Span';\nexport type { SpanProcessor } from './SpanProcessor';\nexport type { TimedEvent } from './TimedEvent';\nexport type {\n BatchSpanProcessorBrowserConfig,\n BufferConfig,\n GeneralLimits,\n SDKRegistrationConfig,\n SpanLimits,\n TracerConfig,\n} from './types';\nexport type { IdGenerator } from './IdGenerator';\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { AsyncLocalStorageContextManager } from '@opentelemetry/context-async-hooks';\nimport {\n BasicTracerProvider,\n SDKRegistrationConfig,\n} from '@opentelemetry/sdk-trace-base';\nimport { NodeTracerConfig } from './config';\nimport {\n context,\n ContextManager,\n propagation,\n TextMapPropagator,\n trace,\n} from '@opentelemetry/api';\nimport {\n CompositePropagator,\n W3CBaggagePropagator,\n W3CTraceContextPropagator,\n} from '@opentelemetry/core';\n\nfunction setupContextManager(\n contextManager: ContextManager | null | undefined\n) {\n // null means 'do not register'\n if (contextManager === null) {\n return;\n }\n\n // undefined means 'register default'\n if (contextManager === undefined) {\n const defaultContextManager = new AsyncLocalStorageContextManager();\n defaultContextManager.enable();\n context.setGlobalContextManager(defaultContextManager);\n return;\n }\n\n contextManager.enable();\n context.setGlobalContextManager(contextManager);\n}\n\nfunction setupPropagator(propagator: TextMapPropagator | null | undefined) {\n // null means 'do not register'\n if (propagator === null) {\n return;\n }\n\n // undefined means 'register default'\n if (propagator === undefined) {\n propagation.setGlobalPropagator(\n new CompositePropagator({\n propagators: [\n new W3CTraceContextPropagator(),\n new W3CBaggagePropagator(),\n ],\n })\n );\n return;\n }\n\n propagation.setGlobalPropagator(propagator);\n}\n\n/**\n * Register this TracerProvider for use with the OpenTelemetry API.\n * Undefined values may be replaced with defaults, and\n * null values will be skipped.\n *\n * @param config Configuration object for SDK registration\n */\nexport class NodeTracerProvider extends BasicTracerProvider {\n constructor(config: NodeTracerConfig = {}) {\n super(config);\n }\n\n /**\n * Register this TracerProvider for use with the OpenTelemetry API.\n * Undefined values may be replaced with defaults, and\n * null values will be skipped.\n *\n * @param config Configuration object for SDK registration\n */\n register(config: SDKRegistrationConfig = {}): void {\n trace.setGlobalTracerProvider(this);\n setupContextManager(config.contextManager);\n setupPropagator(config.propagator);\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport type { NodeTracerConfig } from './config';\nexport { NodeTracerProvider } from './NodeTracerProvider';\nexport {\n AlwaysOffSampler,\n AlwaysOnSampler,\n BasicTracerProvider,\n BatchSpanProcessor,\n ConsoleSpanExporter,\n InMemorySpanExporter,\n NoopSpanProcessor,\n ParentBasedSampler,\n RandomIdGenerator,\n SamplingDecision,\n SimpleSpanProcessor,\n TraceIdRatioBasedSampler,\n} from '@opentelemetry/sdk-trace-base';\nexport type {\n BatchSpanProcessorBrowserConfig,\n BufferConfig,\n GeneralLimits,\n IdGenerator,\n ReadableSpan,\n Sampler,\n SamplingResult,\n SDKRegistrationConfig,\n Span,\n SpanExporter,\n SpanLimits,\n SpanProcessor,\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AA,iBAAA;IAAmB,EAAA,CAAA;AACnB,WAAA,eAAA,SAAA,4BAAA,EAAA,YAAA,MAAA,KAAA,WAAA;AAAA,aAAA,iBAAA;IAAwB,EAAA,CAAA;;;","names":["context","context","context","init_esm","SamplingDecision","SamplingDecision","SamplingDecision","init_esm","context","context","SamplingDecision","init_esm","TracesSamplerValues","init_esm","init_esm","init_esm","context","init_esm","context","init_esm","ForceFlushState","init_esm","init_esm","init_esm","esm_exports","SamplingDecision","init_esm"]}
@@ -0,0 +1,84 @@
1
+ # agentv-chat-to-eval
2
+
3
+ An AgentV skill that converts chat conversations into evaluation YAML files.
4
+
5
+ ## What It Does
6
+
7
+ This skill takes a chat transcript — either as markdown conversation or JSON messages — and generates an AgentV-compatible eval file with test cases derived from the exchanges.
8
+
9
+ The LLM analyzes the conversation to:
10
+ 1. Identify test-worthy exchanges (factual Q&A, task completion, edge cases)
11
+ 2. Derive evaluation criteria from context
12
+ 3. Generate valid YAML with `tests:`, `assert` evaluators, and rubrics
13
+
14
+ ## Usage
15
+
16
+ Provide a chat transcript and ask the agent to convert it:
17
+
18
+ ```
19
+ Convert this conversation into an AgentV eval file:
20
+
21
+ User: What's the capital of France?
22
+ Assistant: The capital of France is Paris.
23
+
24
+ User: How do I reverse a list in Python?
25
+ Assistant: Use the `reverse()` method or slicing: `my_list[::-1]`
26
+ ```
27
+
28
+ Or provide a JSON message array:
29
+
30
+ ```json
31
+ [
32
+ {"role": "user", "content": "What's the capital of France?"},
33
+ {"role": "assistant", "content": "The capital of France is Paris."}
34
+ ]
35
+ ```
36
+
37
+ ## Example Output
38
+
39
+ ```yaml
40
+ description: "General knowledge and coding Q&A"
41
+
42
+ tests:
43
+ - id: capital-of-france
44
+ criteria: "Correctly identify the capital of France"
45
+ input: "What's the capital of France?"
46
+ expected_output: "The capital of France is Paris."
47
+ assert:
48
+ - type: rubrics
49
+ criteria:
50
+ - States Paris as the capital
51
+ - Response is concise and direct
52
+
53
+ - id: python-reverse-list
54
+ criteria: "Explain how to reverse a list in Python"
55
+ input: "How do I reverse a list in Python?"
56
+ expected_output: "Use the `reverse()` method or slicing: `my_list[::-1]`"
57
+ assert:
58
+ - type: rubrics
59
+ criteria:
60
+ - Provides at least one valid method to reverse a list
61
+ - Code syntax is correct
62
+ - Explanation is clear and actionable
63
+
64
+ # Suggested additional evaluators:
65
+ # assert:
66
+ # - name: quality
67
+ # type: llm_judge
68
+ # prompt: ./prompts/quality.md
69
+ # - name: accuracy
70
+ # type: code_judge
71
+ # script: ./scripts/check_accuracy.py
72
+ ```
73
+
74
+ ## When to Use
75
+
76
+ - You have a real conversation that demonstrates desired agent behavior
77
+ - You want to create regression tests from production interactions
78
+ - You're bootstrapping an eval suite from existing chat logs
79
+ - You need to convert Q&A pairs into structured test cases
80
+
81
+ ## Related Skills
82
+
83
+ - **agentv-eval-builder** — Create eval files from scratch with full schema reference
84
+ - **agentv-eval-orchestrator** — Run evaluations without API keys
@@ -0,0 +1,144 @@
1
+ ---
2
+ name: agentv-chat-to-eval
3
+ description: Convert chat conversations into AgentV evaluation YAML files. Use this skill when you have a chat transcript (markdown or JSON messages) and want to generate eval test cases from it.
4
+ ---
5
+
6
+ # Chat-to-Eval Converter
7
+
8
+ Convert chat transcripts into AgentV evaluation YAML files by extracting test-worthy exchanges.
9
+
10
+ ## Input Variables
11
+
12
+ - `transcript`: Chat transcript as markdown conversation or JSON message array
13
+ - `eval-path` (optional): Output path for the generated YAML file
14
+
15
+ ## Workflow
16
+
17
+ ### 1. Parse the Transcript
18
+
19
+ Accept input in either format:
20
+
21
+ **Markdown conversation:**
22
+ ```
23
+ User: How do I reset my password?
24
+ Assistant: Go to Settings > Security > Reset Password...
25
+ ```
26
+
27
+ **JSON messages:**
28
+ ```json
29
+ [
30
+ {"role": "user", "content": "How do I reset my password?"},
31
+ {"role": "assistant", "content": "Go to Settings > Security > Reset Password..."}
32
+ ]
33
+ ```
34
+
35
+ Normalize both formats into `{role, content}` message pairs.
36
+
37
+ ### 2. Identify Test-Worthy Exchanges
38
+
39
+ Extract exchanges that are good eval candidates. Prioritize:
40
+
41
+ - **Factual Q&A** — User asks a question, agent gives a verifiable answer
42
+ - **Task completion** — User requests an action, agent performs it
43
+ - **Multi-turn reasoning** — Exchanges where context from earlier turns matters
44
+ - **Edge cases** — Unusual inputs, error handling, boundary conditions
45
+ - **Domain expertise** — Responses requiring specialized knowledge
46
+
47
+ Skip:
48
+ - Greetings and small talk (unless testing social behavior)
49
+ - Acknowledgments without substance ("OK", "Got it")
50
+ - Repeated or redundant exchanges
51
+
52
+ ### 3. Derive Criteria and Rubrics
53
+
54
+ For each selected exchange, infer evaluation criteria from the conversation context:
55
+
56
+ - What the user implicitly expected
57
+ - Quality signals in the assistant's response (accuracy, completeness, tone)
58
+ - Any corrections or follow-ups that reveal what "good" looks like
59
+
60
+ Generate rubrics that capture these quality dimensions.
61
+
62
+ ### 4. Generate EVAL YAML
63
+
64
+ Produce a valid AgentV eval file using **`tests:`** (not `cases:`).
65
+
66
+ **Structure:**
67
+
68
+ ```yaml
69
+ description: "<Summarize what this eval covers>"
70
+
71
+ tests:
72
+ - id: <kebab-case-id>
73
+ criteria: "<What the response should accomplish>"
74
+ input: "<User message>"
75
+ expected_output: "<Assistant response from transcript>"
76
+ assert:
77
+ - type: rubrics
78
+ criteria:
79
+ - <Quality criterion 1>
80
+ - <Quality criterion 2>
81
+ ```
82
+
83
+ **Rules:**
84
+ - Use `tests:` as the top-level array key — never `cases:`
85
+ - Generate kebab-case `id` values derived from the exchange topic
86
+ - Write `criteria` as a concise statement of what a good response achieves
87
+ - Use `input` for single user messages; use `input` for multi-turn
88
+ - Set `expected_output` to the actual assistant response from the transcript
89
+ - Include 2–4 rubrics per test as `type: rubrics` under `assert` capturing distinct quality dimensions
90
+
91
+ ### 5. Suggest Evaluators
92
+
93
+ Append a commented evaluator configuration based on the test content:
94
+
95
+ ```yaml
96
+ # Suggested additional evaluators:
97
+ # assert:
98
+ # - name: quality
99
+ # type: llm_judge
100
+ # prompt: ./prompts/quality.md
101
+ # - name: accuracy
102
+ # type: code_judge
103
+ # script: ./scripts/check_accuracy.py
104
+ ```
105
+
106
+ - Recommend `llm_judge` for subjective quality (tone, helpfulness, completeness)
107
+ - Recommend `code_judge` for deterministic checks (format, required fields, exact values)
108
+ - Recommend `field_accuracy` when expected output has structured fields
109
+
110
+ ### 6. Write Output
111
+
112
+ - If `eval-path` is provided, write the YAML to that path
113
+ - Otherwise, output the YAML to the conversation for the user to copy
114
+
115
+ ## Multi-Turn Conversations
116
+
117
+ For conversations with context dependencies across turns, use `input`:
118
+
119
+ ```yaml
120
+ tests:
121
+ - id: multi-turn-context
122
+ criteria: "Agent remembers prior context"
123
+ input:
124
+ - role: user
125
+ content: "My name is Alice"
126
+ - role: assistant
127
+ content: "Nice to meet you, Alice!"
128
+ - role: user
129
+ content: "What's my name?"
130
+ expected_output: "Your name is Alice."
131
+ assert:
132
+ - type: rubrics
133
+ criteria:
134
+ - Correctly recalls the user's name from earlier in the conversation
135
+ - Response is natural and conversational
136
+ ```
137
+
138
+ ## Guidelines
139
+
140
+ - **Preserve original wording** in `expected_output` — use the actual transcript text
141
+ - **Be selective** — not every exchange makes a good test; aim for 5–15 tests per transcript
142
+ - **Diverse coverage** — pick exchanges that test different capabilities
143
+ - **Actionable rubrics** — each rubric should be independently evaluable (pass/fail)
144
+ - **Validate output** — the generated YAML must pass `agentv validate <file>`
@@ -0,0 +1,67 @@
1
+ # Example: JSON Messages Input
2
+
3
+ ## Input
4
+
5
+ ```json
6
+ [
7
+ {"role": "user", "content": "Convert 72°F to Celsius"},
8
+ {"role": "assistant", "content": "72°F is approximately 22.2°C. The formula is: (°F - 32) × 5/9 = °C"},
9
+ {"role": "user", "content": "What about -40?"},
10
+ {"role": "assistant", "content": "-40°F equals exactly -40°C. This is the unique point where Fahrenheit and Celsius scales intersect."},
11
+ {"role": "user", "content": "Is 0 Kelvin the same as -273.15°C?"},
12
+ {"role": "assistant", "content": "Yes, 0 Kelvin (absolute zero) equals -273.15°C. It's the theoretical lowest possible temperature where all molecular motion stops."}
13
+ ]
14
+ ```
15
+
16
+ ## Output
17
+
18
+ ```yaml
19
+ description: "Temperature conversion and thermodynamics knowledge"
20
+
21
+ tests:
22
+ - id: fahrenheit-to-celsius
23
+ criteria: "Convert Fahrenheit to Celsius with correct formula"
24
+ input: "Convert 72°F to Celsius"
25
+ expected_output: "72°F is approximately 22.2°C. The formula is: (°F - 32) × 5/9 = °C"
26
+ assert:
27
+ - type: rubrics
28
+ criteria:
29
+ - Provides the correct converted value (approximately 22.2°C)
30
+ - Shows or references the conversion formula
31
+ - Uses appropriate precision
32
+
33
+ - id: negative-forty-intersection
34
+ criteria: "Identify the Fahrenheit-Celsius intersection point"
35
+ input:
36
+ - role: user
37
+ content: "Convert 72°F to Celsius"
38
+ - role: assistant
39
+ content: "72°F is approximately 22.2°C."
40
+ - role: user
41
+ content: "What about -40?"
42
+ expected_output: "-40°F equals exactly -40°C. This is the unique point where Fahrenheit and Celsius scales intersect."
43
+ assert:
44
+ - type: rubrics
45
+ criteria:
46
+ - States that -40°F equals -40°C
47
+ - Mentions this is the intersection point of both scales
48
+
49
+ - id: absolute-zero
50
+ criteria: "Confirm absolute zero equivalence and explain its significance"
51
+ input: "Is 0 Kelvin the same as -273.15°C?"
52
+ expected_output: "Yes, 0 Kelvin (absolute zero) equals -273.15°C. It's the theoretical lowest possible temperature where all molecular motion stops."
53
+ assert:
54
+ - type: rubrics
55
+ criteria:
56
+ - Confirms the equivalence of 0K and -273.15°C
57
+ - Explains the physical significance of absolute zero
58
+
59
+ # Suggested additional evaluators:
60
+ # assert:
61
+ # - name: accuracy
62
+ # type: code_judge
63
+ # script: ./scripts/check_conversion.py
64
+ # - name: quality
65
+ # type: llm_judge
66
+ # prompt: ./prompts/quality.md
67
+ ```