@fro.bot/opencode-plugin 0.3.5 → 0.3.7
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.
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"tracing-CHrTlTyx.mjs","names":["VERSION","VERSION","VERSION","__read","__spreadArray","__read","__spreadArray","API_NAME","__read","__spreadArray","API_NAME","SamplingDecision","VERSION","VERSION","hrTime","performance","VERSION","VERSION","hrTime","api.createNoopMeter","context","api.INVALID_SPAN_CONTEXT","MAX_IDENTIFIER_CHARS","Buffer","isRecord","asString","isRecord","asString"],"sources":["../../../node_modules/@opentelemetry/api/build/esm/platform/node/globalThis.js","../../../node_modules/@opentelemetry/api/build/esm/version.js","../../../node_modules/@opentelemetry/api/build/esm/internal/semver.js","../../../node_modules/@opentelemetry/api/build/esm/internal/global-utils.js","../../../node_modules/@opentelemetry/api/build/esm/diag/ComponentLogger.js","../../../node_modules/@opentelemetry/api/build/esm/diag/types.js","../../../node_modules/@opentelemetry/api/build/esm/diag/internal/logLevelLogger.js","../../../node_modules/@opentelemetry/api/build/esm/api/diag.js","../../../node_modules/@opentelemetry/api/build/esm/context/context.js","../../../node_modules/@opentelemetry/api/build/esm/metrics/NoopMeter.js","../../../node_modules/@opentelemetry/api/build/esm/context/NoopContextManager.js","../../../node_modules/@opentelemetry/api/build/esm/api/context.js","../../../node_modules/@opentelemetry/api/build/esm/trace/trace_flags.js","../../../node_modules/@opentelemetry/api/build/esm/trace/invalid-span-constants.js","../../../node_modules/@opentelemetry/api/build/esm/trace/NonRecordingSpan.js","../../../node_modules/@opentelemetry/api/build/esm/trace/context-utils.js","../../../node_modules/@opentelemetry/api/build/esm/trace/spancontext-utils.js","../../../node_modules/@opentelemetry/api/build/esm/trace/NoopTracer.js","../../../node_modules/@opentelemetry/api/build/esm/trace/ProxyTracer.js","../../../node_modules/@opentelemetry/api/build/esm/trace/NoopTracerProvider.js","../../../node_modules/@opentelemetry/api/build/esm/trace/ProxyTracerProvider.js","../../../node_modules/@opentelemetry/api/build/esm/trace/SamplingResult.js","../../../node_modules/@opentelemetry/api/build/esm/trace/span_kind.js","../../../node_modules/@opentelemetry/api/build/esm/trace/status.js","../../../node_modules/@opentelemetry/api/build/esm/context-api.js","../../../node_modules/@opentelemetry/api/build/esm/diag-api.js","../../../node_modules/@opentelemetry/api/build/esm/api/trace.js","../../../node_modules/@opentelemetry/api/build/esm/trace-api.js","../../../node_modules/@opentelemetry/otlp-exporter-base/build/esm/OTLPExporterBase.js","../../../node_modules/@opentelemetry/otlp-exporter-base/build/esm/types.js","../../../node_modules/@opentelemetry/otlp-exporter-base/build/esm/bounded-queue-export-promise-handler.js","../../../node_modules/@opentelemetry/core/build/esm/trace/suppress-tracing.js","../../../node_modules/@opentelemetry/core/build/esm/common/attributes.js","../../../node_modules/@opentelemetry/core/build/esm/common/logging-error-handler.js","../../../node_modules/@opentelemetry/core/build/esm/common/global-error-handler.js","../../../node_modules/@opentelemetry/core/build/esm/platform/node/environment.js","../../../node_modules/@opentelemetry/core/build/esm/version.js","../../../node_modules/@opentelemetry/semantic-conventions/build/esm/stable_attributes.js","../../../node_modules/@opentelemetry/core/build/esm/semconv.js","../../../node_modules/@opentelemetry/core/build/esm/platform/node/sdk-info.js","../../../node_modules/@opentelemetry/core/build/esm/platform/node/index.js","../../../node_modules/@opentelemetry/core/build/esm/common/time.js","../../../node_modules/@opentelemetry/core/build/esm/ExportResult.js","../../../node_modules/@opentelemetry/core/build/esm/utils/lodash.merge.js","../../../node_modules/@opentelemetry/core/build/esm/utils/merge.js","../../../node_modules/@opentelemetry/otlp-exporter-base/build/esm/logging-response-handler.js","../../../node_modules/@opentelemetry/otlp-exporter-base/build/esm/otlp-export-delegate.js","../../../node_modules/@opentelemetry/otlp-exporter-base/build/esm/configuration/otlp-node-http-configuration.js","../../../node_modules/@opentelemetry/otlp-exporter-base/build/esm/is-export-retryable.js","../../../node_modules/@opentelemetry/otlp-exporter-base/build/esm/version.js","../../../node_modules/@opentelemetry/otlp-exporter-base/build/esm/transport/http-transport-utils.js","../../../node_modules/@opentelemetry/otlp-exporter-base/build/esm/transport/http-exporter-transport.js","../../../node_modules/@opentelemetry/otlp-exporter-base/build/esm/retrying-transport.js","../../../node_modules/@opentelemetry/otlp-exporter-base/build/esm/otlp-http-export-delegate.js","../../../node_modules/@opentelemetry/resources/build/esm/default-service-name.js","../../../node_modules/@opentelemetry/resources/build/esm/utils.js","../../../node_modules/@opentelemetry/resources/build/esm/ResourceImpl.js","../../../node_modules/@opentelemetry/otlp-transformer/build/esm/common/internal.js","../../../node_modules/@opentelemetry/otlp-transformer/build/esm/common/utils.js","../../../node_modules/@opentelemetry/otlp-transformer/build/esm/trace/internal.js","../../../node_modules/@opentelemetry/otlp-transformer/build/esm/trace/json/trace.js","../../../node_modules/@opentelemetry/sdk-trace-base/build/esm/enums.js","../../../node_modules/@opentelemetry/sdk-trace-base/build/esm/inspect.js","../../../node_modules/@opentelemetry/sdk-trace-base/build/esm/Span.js","../../../node_modules/@opentelemetry/sdk-trace-base/build/esm/Sampler.js","../../../node_modules/@opentelemetry/sdk-trace-base/build/esm/sampler/AlwaysOffSampler.js","../../../node_modules/@opentelemetry/sdk-trace-base/build/esm/sampler/AlwaysOnSampler.js","../../../node_modules/@opentelemetry/sdk-trace-base/build/esm/sampler/ParentBasedSampler.js","../../../node_modules/@opentelemetry/sdk-trace-base/build/esm/sampler/TraceIdRatioBasedSampler.js","../../../node_modules/@opentelemetry/sdk-trace-base/build/esm/config.js","../../../node_modules/@opentelemetry/sdk-trace-base/build/esm/utility.js","../../../node_modules/@opentelemetry/sdk-trace-base/build/esm/platform/node/RandomIdGenerator.js","../../../node_modules/@opentelemetry/sdk-trace-base/build/esm/semconv.js","../../../node_modules/@opentelemetry/sdk-trace-base/build/esm/TracerMetrics.js","../../../node_modules/@opentelemetry/sdk-trace-base/build/esm/version.js","../../../node_modules/@opentelemetry/sdk-trace-base/build/esm/Tracer.js","../../../node_modules/@opentelemetry/sdk-trace-base/build/esm/MultiSpanProcessor.js","../../../node_modules/@opentelemetry/sdk-trace-base/build/esm/BasicTracerProvider.js","../../runtime/src/tracing/scrub.ts","../../runtime/src/tracing/exporter.ts","../src/tracing/content.ts","../src/tracing/snapshot.ts","../src/tracing/genai-attributes.ts","../src/tracing/turn-model.ts","../src/tracing/pipeline.ts","../src/tracing/record-observations.ts","../src/tracing/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/** only globals that common to node and browsers are allowed */\n// eslint-disable-next-line node/no-unsupported-features/es-builtins\nexport var _globalThis = typeof globalThis === 'object' ? globalThis : global;\n//# sourceMappingURL=globalThis.js.map","/*\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// this is autogenerated file, see scripts/version-update.js\nexport var VERSION = '1.9.0';\n//# sourceMappingURL=version.js.map","/*\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 { VERSION } from '../version';\nvar re = /^(\\d+)\\.(\\d+)\\.(\\d+)(-(.+))?$/;\n/**\n * Create a function to test an API version to see if it is compatible with the provided ownVersion.\n *\n * The returned function has the following semantics:\n * - Exact match is always compatible\n * - Major versions must match exactly\n * - 1.x package cannot use global 2.x package\n * - 2.x package cannot use global 1.x package\n * - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API\n * - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects\n * - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3\n * - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor\n * - Patch and build tag differences are not considered at this time\n *\n * @param ownVersion version which should be checked against\n */\nexport function _makeCompatibilityCheck(ownVersion) {\n var acceptedVersions = new Set([ownVersion]);\n var rejectedVersions = new Set();\n var myVersionMatch = ownVersion.match(re);\n if (!myVersionMatch) {\n // we cannot guarantee compatibility so we always return noop\n return function () { return false; };\n }\n var ownVersionParsed = {\n major: +myVersionMatch[1],\n minor: +myVersionMatch[2],\n patch: +myVersionMatch[3],\n prerelease: myVersionMatch[4],\n };\n // if ownVersion has a prerelease tag, versions must match exactly\n if (ownVersionParsed.prerelease != null) {\n return function isExactmatch(globalVersion) {\n return globalVersion === ownVersion;\n };\n }\n function _reject(v) {\n rejectedVersions.add(v);\n return false;\n }\n function _accept(v) {\n acceptedVersions.add(v);\n return true;\n }\n return function isCompatible(globalVersion) {\n if (acceptedVersions.has(globalVersion)) {\n return true;\n }\n if (rejectedVersions.has(globalVersion)) {\n return false;\n }\n var globalVersionMatch = globalVersion.match(re);\n if (!globalVersionMatch) {\n // cannot parse other version\n // we cannot guarantee compatibility so we always noop\n return _reject(globalVersion);\n }\n var globalVersionParsed = {\n major: +globalVersionMatch[1],\n minor: +globalVersionMatch[2],\n patch: +globalVersionMatch[3],\n prerelease: globalVersionMatch[4],\n };\n // if globalVersion has a prerelease tag, versions must match exactly\n if (globalVersionParsed.prerelease != null) {\n return _reject(globalVersion);\n }\n // major versions must match\n if (ownVersionParsed.major !== globalVersionParsed.major) {\n return _reject(globalVersion);\n }\n if (ownVersionParsed.major === 0) {\n if (ownVersionParsed.minor === globalVersionParsed.minor &&\n ownVersionParsed.patch <= globalVersionParsed.patch) {\n return _accept(globalVersion);\n }\n return _reject(globalVersion);\n }\n if (ownVersionParsed.minor <= globalVersionParsed.minor) {\n return _accept(globalVersion);\n }\n return _reject(globalVersion);\n };\n}\n/**\n * Test an API version to see if it is compatible with this API.\n *\n * - Exact match is always compatible\n * - Major versions must match exactly\n * - 1.x package cannot use global 2.x package\n * - 2.x package cannot use global 1.x package\n * - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API\n * - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects\n * - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3\n * - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor\n * - Patch and build tag differences are not considered at this time\n *\n * @param version version of the API requesting an instance of the global API\n */\nexport var isCompatible = _makeCompatibilityCheck(VERSION);\n//# sourceMappingURL=semver.js.map","/*\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 { _globalThis } from '../platform';\nimport { VERSION } from '../version';\nimport { isCompatible } from './semver';\nvar major = VERSION.split('.')[0];\nvar GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for(\"opentelemetry.js.api.\" + major);\nvar _global = _globalThis;\nexport function registerGlobal(type, instance, diag, allowOverride) {\n var _a;\n if (allowOverride === void 0) { allowOverride = false; }\n var api = (_global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a !== void 0 ? _a : {\n version: VERSION,\n });\n if (!allowOverride && api[type]) {\n // already registered an API of this type\n var err = new Error(\"@opentelemetry/api: Attempted duplicate registration of API: \" + type);\n diag.error(err.stack || err.message);\n return false;\n }\n if (api.version !== VERSION) {\n // All registered APIs must be of the same version exactly\n var err = new Error(\"@opentelemetry/api: Registration of version v\" + api.version + \" for \" + type + \" does not match previously registered API v\" + VERSION);\n diag.error(err.stack || err.message);\n return false;\n }\n api[type] = instance;\n diag.debug(\"@opentelemetry/api: Registered a global for \" + type + \" v\" + VERSION + \".\");\n return true;\n}\nexport function getGlobal(type) {\n var _a, _b;\n var globalVersion = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a === void 0 ? void 0 : _a.version;\n if (!globalVersion || !isCompatible(globalVersion)) {\n return;\n }\n return (_b = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _b === void 0 ? void 0 : _b[type];\n}\nexport function unregisterGlobal(type, diag) {\n diag.debug(\"@opentelemetry/api: Unregistering a global for \" + type + \" v\" + VERSION + \".\");\n var api = _global[GLOBAL_OPENTELEMETRY_API_KEY];\n if (api) {\n delete api[type];\n }\n}\n//# sourceMappingURL=global-utils.js.map","/*\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 */\nvar __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n};\nvar __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\nimport { getGlobal } from '../internal/global-utils';\n/**\n * Component Logger which is meant to be used as part of any component which\n * will add automatically additional namespace in front of the log message.\n * It will then forward all message to global diag logger\n * @example\n * const cLogger = diag.createComponentLogger({ namespace: '@opentelemetry/instrumentation-http' });\n * cLogger.debug('test');\n * // @opentelemetry/instrumentation-http test\n */\nvar DiagComponentLogger = /** @class */ (function () {\n function DiagComponentLogger(props) {\n this._namespace = props.namespace || 'DiagComponentLogger';\n }\n DiagComponentLogger.prototype.debug = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n return logProxy('debug', this._namespace, args);\n };\n DiagComponentLogger.prototype.error = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n return logProxy('error', this._namespace, args);\n };\n DiagComponentLogger.prototype.info = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n return logProxy('info', this._namespace, args);\n };\n DiagComponentLogger.prototype.warn = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n return logProxy('warn', this._namespace, args);\n };\n DiagComponentLogger.prototype.verbose = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n return logProxy('verbose', this._namespace, args);\n };\n return DiagComponentLogger;\n}());\nexport { DiagComponentLogger };\nfunction logProxy(funcName, namespace, args) {\n var logger = getGlobal('diag');\n // shortcut if logger not set\n if (!logger) {\n return;\n }\n args.unshift(namespace);\n return logger[funcName].apply(logger, __spreadArray([], __read(args), false));\n}\n//# sourceMappingURL=ComponentLogger.js.map","/*\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 * Defines the available internal logging levels for the diagnostic logger, the numeric values\n * of the levels are defined to match the original values from the initial LogLevel to avoid\n * compatibility/migration issues for any implementation that assume the numeric ordering.\n */\nexport var DiagLogLevel;\n(function (DiagLogLevel) {\n /** Diagnostic Logging level setting to disable all logging (except and forced logs) */\n DiagLogLevel[DiagLogLevel[\"NONE\"] = 0] = \"NONE\";\n /** Identifies an error scenario */\n DiagLogLevel[DiagLogLevel[\"ERROR\"] = 30] = \"ERROR\";\n /** Identifies a warning scenario */\n DiagLogLevel[DiagLogLevel[\"WARN\"] = 50] = \"WARN\";\n /** General informational log message */\n DiagLogLevel[DiagLogLevel[\"INFO\"] = 60] = \"INFO\";\n /** General debug log message */\n DiagLogLevel[DiagLogLevel[\"DEBUG\"] = 70] = \"DEBUG\";\n /**\n * Detailed trace level logging should only be used for development, should only be set\n * in a development environment.\n */\n DiagLogLevel[DiagLogLevel[\"VERBOSE\"] = 80] = \"VERBOSE\";\n /** Used to set the logging level to include all logging */\n DiagLogLevel[DiagLogLevel[\"ALL\"] = 9999] = \"ALL\";\n})(DiagLogLevel || (DiagLogLevel = {}));\n//# sourceMappingURL=types.js.map","/*\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 { DiagLogLevel } from '../types';\nexport function createLogLevelDiagLogger(maxLevel, logger) {\n if (maxLevel < DiagLogLevel.NONE) {\n maxLevel = DiagLogLevel.NONE;\n }\n else if (maxLevel > DiagLogLevel.ALL) {\n maxLevel = DiagLogLevel.ALL;\n }\n // In case the logger is null or undefined\n logger = logger || {};\n function _filterFunc(funcName, theLevel) {\n var theFunc = logger[funcName];\n if (typeof theFunc === 'function' && maxLevel >= theLevel) {\n return theFunc.bind(logger);\n }\n return function () { };\n }\n return {\n error: _filterFunc('error', DiagLogLevel.ERROR),\n warn: _filterFunc('warn', DiagLogLevel.WARN),\n info: _filterFunc('info', DiagLogLevel.INFO),\n debug: _filterFunc('debug', DiagLogLevel.DEBUG),\n verbose: _filterFunc('verbose', DiagLogLevel.VERBOSE),\n };\n}\n//# sourceMappingURL=logLevelLogger.js.map","/*\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 */\nvar __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n};\nvar __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\nimport { DiagComponentLogger } from '../diag/ComponentLogger';\nimport { createLogLevelDiagLogger } from '../diag/internal/logLevelLogger';\nimport { DiagLogLevel, } from '../diag/types';\nimport { getGlobal, registerGlobal, unregisterGlobal, } from '../internal/global-utils';\nvar API_NAME = 'diag';\n/**\n * Singleton object which represents the entry point to the OpenTelemetry internal\n * diagnostic API\n */\nvar DiagAPI = /** @class */ (function () {\n /**\n * Private internal constructor\n * @private\n */\n function DiagAPI() {\n function _logProxy(funcName) {\n return function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n var logger = getGlobal('diag');\n // shortcut if logger not set\n if (!logger)\n return;\n return logger[funcName].apply(logger, __spreadArray([], __read(args), false));\n };\n }\n // Using self local variable for minification purposes as 'this' cannot be minified\n var self = this;\n // DiagAPI specific functions\n var setLogger = function (logger, optionsOrLogLevel) {\n var _a, _b, _c;\n if (optionsOrLogLevel === void 0) { optionsOrLogLevel = { logLevel: DiagLogLevel.INFO }; }\n if (logger === self) {\n // There isn't much we can do here.\n // Logging to the console might break the user application.\n // Try to log to self. If a logger was previously registered it will receive the log.\n var err = new Error('Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation');\n self.error((_a = err.stack) !== null && _a !== void 0 ? _a : err.message);\n return false;\n }\n if (typeof optionsOrLogLevel === 'number') {\n optionsOrLogLevel = {\n logLevel: optionsOrLogLevel,\n };\n }\n var oldLogger = getGlobal('diag');\n var newLogger = createLogLevelDiagLogger((_b = optionsOrLogLevel.logLevel) !== null && _b !== void 0 ? _b : DiagLogLevel.INFO, logger);\n // There already is an logger registered. We'll let it know before overwriting it.\n if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) {\n var stack = (_c = new Error().stack) !== null && _c !== void 0 ? _c : '<failed to generate stacktrace>';\n oldLogger.warn(\"Current logger will be overwritten from \" + stack);\n newLogger.warn(\"Current logger will overwrite one already registered from \" + stack);\n }\n return registerGlobal('diag', newLogger, self, true);\n };\n self.setLogger = setLogger;\n self.disable = function () {\n unregisterGlobal(API_NAME, self);\n };\n self.createComponentLogger = function (options) {\n return new DiagComponentLogger(options);\n };\n self.verbose = _logProxy('verbose');\n self.debug = _logProxy('debug');\n self.info = _logProxy('info');\n self.warn = _logProxy('warn');\n self.error = _logProxy('error');\n }\n /** Get the singleton instance of the DiagAPI API */\n DiagAPI.instance = function () {\n if (!this._instance) {\n this._instance = new DiagAPI();\n }\n return this._instance;\n };\n return DiagAPI;\n}());\nexport { DiagAPI };\n//# sourceMappingURL=diag.js.map","/*\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/** Get a key to uniquely identify a context value */\nexport function createContextKey(description) {\n // The specification states that for the same input, multiple calls should\n // return different keys. Due to the nature of the JS dependency management\n // system, this creates problems where multiple versions of some package\n // could hold different keys for the same property.\n //\n // Therefore, we use Symbol.for which returns the same key for the same input.\n return Symbol.for(description);\n}\nvar BaseContext = /** @class */ (function () {\n /**\n * Construct a new context which inherits values from an optional parent context.\n *\n * @param parentContext a context from which to inherit values\n */\n function BaseContext(parentContext) {\n // for minification\n var self = this;\n self._currentContext = parentContext ? new Map(parentContext) : new Map();\n self.getValue = function (key) { return self._currentContext.get(key); };\n self.setValue = function (key, value) {\n var context = new BaseContext(self._currentContext);\n context._currentContext.set(key, value);\n return context;\n };\n self.deleteValue = function (key) {\n var context = new BaseContext(self._currentContext);\n context._currentContext.delete(key);\n return context;\n };\n }\n return BaseContext;\n}());\n/** The root context is used as the default parent context when there is no active context */\nexport var ROOT_CONTEXT = new BaseContext();\n//# sourceMappingURL=context.js.map","/*\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n if (typeof b !== \"function\" && b !== null)\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\n/**\n * NoopMeter is a noop implementation of the {@link Meter} interface. It reuses\n * constant NoopMetrics for all of its methods.\n */\nvar NoopMeter = /** @class */ (function () {\n function NoopMeter() {\n }\n /**\n * @see {@link Meter.createGauge}\n */\n NoopMeter.prototype.createGauge = function (_name, _options) {\n return NOOP_GAUGE_METRIC;\n };\n /**\n * @see {@link Meter.createHistogram}\n */\n NoopMeter.prototype.createHistogram = function (_name, _options) {\n return NOOP_HISTOGRAM_METRIC;\n };\n /**\n * @see {@link Meter.createCounter}\n */\n NoopMeter.prototype.createCounter = function (_name, _options) {\n return NOOP_COUNTER_METRIC;\n };\n /**\n * @see {@link Meter.createUpDownCounter}\n */\n NoopMeter.prototype.createUpDownCounter = function (_name, _options) {\n return NOOP_UP_DOWN_COUNTER_METRIC;\n };\n /**\n * @see {@link Meter.createObservableGauge}\n */\n NoopMeter.prototype.createObservableGauge = function (_name, _options) {\n return NOOP_OBSERVABLE_GAUGE_METRIC;\n };\n /**\n * @see {@link Meter.createObservableCounter}\n */\n NoopMeter.prototype.createObservableCounter = function (_name, _options) {\n return NOOP_OBSERVABLE_COUNTER_METRIC;\n };\n /**\n * @see {@link Meter.createObservableUpDownCounter}\n */\n NoopMeter.prototype.createObservableUpDownCounter = function (_name, _options) {\n return NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC;\n };\n /**\n * @see {@link Meter.addBatchObservableCallback}\n */\n NoopMeter.prototype.addBatchObservableCallback = function (_callback, _observables) { };\n /**\n * @see {@link Meter.removeBatchObservableCallback}\n */\n NoopMeter.prototype.removeBatchObservableCallback = function (_callback) { };\n return NoopMeter;\n}());\nexport { NoopMeter };\nvar NoopMetric = /** @class */ (function () {\n function NoopMetric() {\n }\n return NoopMetric;\n}());\nexport { NoopMetric };\nvar NoopCounterMetric = /** @class */ (function (_super) {\n __extends(NoopCounterMetric, _super);\n function NoopCounterMetric() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n NoopCounterMetric.prototype.add = function (_value, _attributes) { };\n return NoopCounterMetric;\n}(NoopMetric));\nexport { NoopCounterMetric };\nvar NoopUpDownCounterMetric = /** @class */ (function (_super) {\n __extends(NoopUpDownCounterMetric, _super);\n function NoopUpDownCounterMetric() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n NoopUpDownCounterMetric.prototype.add = function (_value, _attributes) { };\n return NoopUpDownCounterMetric;\n}(NoopMetric));\nexport { NoopUpDownCounterMetric };\nvar NoopGaugeMetric = /** @class */ (function (_super) {\n __extends(NoopGaugeMetric, _super);\n function NoopGaugeMetric() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n NoopGaugeMetric.prototype.record = function (_value, _attributes) { };\n return NoopGaugeMetric;\n}(NoopMetric));\nexport { NoopGaugeMetric };\nvar NoopHistogramMetric = /** @class */ (function (_super) {\n __extends(NoopHistogramMetric, _super);\n function NoopHistogramMetric() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n NoopHistogramMetric.prototype.record = function (_value, _attributes) { };\n return NoopHistogramMetric;\n}(NoopMetric));\nexport { NoopHistogramMetric };\nvar NoopObservableMetric = /** @class */ (function () {\n function NoopObservableMetric() {\n }\n NoopObservableMetric.prototype.addCallback = function (_callback) { };\n NoopObservableMetric.prototype.removeCallback = function (_callback) { };\n return NoopObservableMetric;\n}());\nexport { NoopObservableMetric };\nvar NoopObservableCounterMetric = /** @class */ (function (_super) {\n __extends(NoopObservableCounterMetric, _super);\n function NoopObservableCounterMetric() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n return NoopObservableCounterMetric;\n}(NoopObservableMetric));\nexport { NoopObservableCounterMetric };\nvar NoopObservableGaugeMetric = /** @class */ (function (_super) {\n __extends(NoopObservableGaugeMetric, _super);\n function NoopObservableGaugeMetric() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n return NoopObservableGaugeMetric;\n}(NoopObservableMetric));\nexport { NoopObservableGaugeMetric };\nvar NoopObservableUpDownCounterMetric = /** @class */ (function (_super) {\n __extends(NoopObservableUpDownCounterMetric, _super);\n function NoopObservableUpDownCounterMetric() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n return NoopObservableUpDownCounterMetric;\n}(NoopObservableMetric));\nexport { NoopObservableUpDownCounterMetric };\nexport var NOOP_METER = new NoopMeter();\n// Synchronous instruments\nexport var NOOP_COUNTER_METRIC = new NoopCounterMetric();\nexport var NOOP_GAUGE_METRIC = new NoopGaugeMetric();\nexport var NOOP_HISTOGRAM_METRIC = new NoopHistogramMetric();\nexport var NOOP_UP_DOWN_COUNTER_METRIC = new NoopUpDownCounterMetric();\n// Asynchronous instruments\nexport var NOOP_OBSERVABLE_COUNTER_METRIC = new NoopObservableCounterMetric();\nexport var NOOP_OBSERVABLE_GAUGE_METRIC = new NoopObservableGaugeMetric();\nexport var NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC = new NoopObservableUpDownCounterMetric();\n/**\n * Create a no-op Meter\n */\nexport function createNoopMeter() {\n return NOOP_METER;\n}\n//# sourceMappingURL=NoopMeter.js.map","/*\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 */\nvar __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n};\nvar __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\nimport { ROOT_CONTEXT } from './context';\nvar NoopContextManager = /** @class */ (function () {\n function NoopContextManager() {\n }\n NoopContextManager.prototype.active = function () {\n return ROOT_CONTEXT;\n };\n NoopContextManager.prototype.with = function (_context, fn, thisArg) {\n var args = [];\n for (var _i = 3; _i < arguments.length; _i++) {\n args[_i - 3] = arguments[_i];\n }\n return fn.call.apply(fn, __spreadArray([thisArg], __read(args), false));\n };\n NoopContextManager.prototype.bind = function (_context, target) {\n return target;\n };\n NoopContextManager.prototype.enable = function () {\n return this;\n };\n NoopContextManager.prototype.disable = function () {\n return this;\n };\n return NoopContextManager;\n}());\nexport { NoopContextManager };\n//# sourceMappingURL=NoopContextManager.js.map","/*\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 */\nvar __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n};\nvar __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\nimport { NoopContextManager } from '../context/NoopContextManager';\nimport { getGlobal, registerGlobal, unregisterGlobal, } from '../internal/global-utils';\nimport { DiagAPI } from './diag';\nvar API_NAME = 'context';\nvar NOOP_CONTEXT_MANAGER = new NoopContextManager();\n/**\n * Singleton object which represents the entry point to the OpenTelemetry Context API\n */\nvar ContextAPI = /** @class */ (function () {\n /** Empty private constructor prevents end users from constructing a new instance of the API */\n function ContextAPI() {\n }\n /** Get the singleton instance of the Context API */\n ContextAPI.getInstance = function () {\n if (!this._instance) {\n this._instance = new ContextAPI();\n }\n return this._instance;\n };\n /**\n * Set the current context manager.\n *\n * @returns true if the context manager was successfully registered, else false\n */\n ContextAPI.prototype.setGlobalContextManager = function (contextManager) {\n return registerGlobal(API_NAME, contextManager, DiagAPI.instance());\n };\n /**\n * Get the currently active context\n */\n ContextAPI.prototype.active = function () {\n return this._getContextManager().active();\n };\n /**\n * Execute a function with an active context\n *\n * @param context context to be active during function execution\n * @param fn function to execute in a context\n * @param thisArg optional receiver to be used for calling fn\n * @param args optional arguments forwarded to fn\n */\n ContextAPI.prototype.with = function (context, fn, thisArg) {\n var _a;\n var args = [];\n for (var _i = 3; _i < arguments.length; _i++) {\n args[_i - 3] = arguments[_i];\n }\n return (_a = this._getContextManager()).with.apply(_a, __spreadArray([context, fn, thisArg], __read(args), false));\n };\n /**\n * Bind a context to a target function or event emitter\n *\n * @param context context to bind to the event emitter or function. Defaults to the currently active context\n * @param target function or event emitter to bind\n */\n ContextAPI.prototype.bind = function (context, target) {\n return this._getContextManager().bind(context, target);\n };\n ContextAPI.prototype._getContextManager = function () {\n return getGlobal(API_NAME) || NOOP_CONTEXT_MANAGER;\n };\n /** Disable and remove the global context manager */\n ContextAPI.prototype.disable = function () {\n this._getContextManager().disable();\n unregisterGlobal(API_NAME, DiagAPI.instance());\n };\n return ContextAPI;\n}());\nexport { ContextAPI };\n//# sourceMappingURL=context.js.map","/*\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 */\nexport var TraceFlags;\n(function (TraceFlags) {\n /** Represents no flag set. */\n TraceFlags[TraceFlags[\"NONE\"] = 0] = \"NONE\";\n /** Bit to represent whether trace is sampled in trace flags. */\n TraceFlags[TraceFlags[\"SAMPLED\"] = 1] = \"SAMPLED\";\n})(TraceFlags || (TraceFlags = {}));\n//# sourceMappingURL=trace_flags.js.map","/*\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 { TraceFlags } from './trace_flags';\nexport var INVALID_SPANID = '0000000000000000';\nexport var INVALID_TRACEID = '00000000000000000000000000000000';\nexport var INVALID_SPAN_CONTEXT = {\n traceId: INVALID_TRACEID,\n spanId: INVALID_SPANID,\n traceFlags: TraceFlags.NONE,\n};\n//# sourceMappingURL=invalid-span-constants.js.map","/*\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 { INVALID_SPAN_CONTEXT } from './invalid-span-constants';\n/**\n * The NonRecordingSpan is the default {@link Span} that is used when no Span\n * implementation is available. All operations are no-op including context\n * propagation.\n */\nvar NonRecordingSpan = /** @class */ (function () {\n function NonRecordingSpan(_spanContext) {\n if (_spanContext === void 0) { _spanContext = INVALID_SPAN_CONTEXT; }\n this._spanContext = _spanContext;\n }\n // Returns a SpanContext.\n NonRecordingSpan.prototype.spanContext = function () {\n return this._spanContext;\n };\n // By default does nothing\n NonRecordingSpan.prototype.setAttribute = function (_key, _value) {\n return this;\n };\n // By default does nothing\n NonRecordingSpan.prototype.setAttributes = function (_attributes) {\n return this;\n };\n // By default does nothing\n NonRecordingSpan.prototype.addEvent = function (_name, _attributes) {\n return this;\n };\n NonRecordingSpan.prototype.addLink = function (_link) {\n return this;\n };\n NonRecordingSpan.prototype.addLinks = function (_links) {\n return this;\n };\n // By default does nothing\n NonRecordingSpan.prototype.setStatus = function (_status) {\n return this;\n };\n // By default does nothing\n NonRecordingSpan.prototype.updateName = function (_name) {\n return this;\n };\n // By default does nothing\n NonRecordingSpan.prototype.end = function (_endTime) { };\n // isRecording always returns false for NonRecordingSpan.\n NonRecordingSpan.prototype.isRecording = function () {\n return false;\n };\n // By default does nothing\n NonRecordingSpan.prototype.recordException = function (_exception, _time) { };\n return NonRecordingSpan;\n}());\nexport { NonRecordingSpan };\n//# sourceMappingURL=NonRecordingSpan.js.map","/*\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 { createContextKey } from '../context/context';\nimport { NonRecordingSpan } from './NonRecordingSpan';\nimport { ContextAPI } from '../api/context';\n/**\n * span key\n */\nvar SPAN_KEY = createContextKey('OpenTelemetry Context Key SPAN');\n/**\n * Return the span if one exists\n *\n * @param context context to get span from\n */\nexport function getSpan(context) {\n return context.getValue(SPAN_KEY) || undefined;\n}\n/**\n * Gets the span from the current context, if one exists.\n */\nexport function getActiveSpan() {\n return getSpan(ContextAPI.getInstance().active());\n}\n/**\n * Set the span on a context\n *\n * @param context context to use as parent\n * @param span span to set active\n */\nexport function setSpan(context, span) {\n return context.setValue(SPAN_KEY, span);\n}\n/**\n * Remove current span stored in the context\n *\n * @param context context to delete span from\n */\nexport function deleteSpan(context) {\n return context.deleteValue(SPAN_KEY);\n}\n/**\n * Wrap span context in a NoopSpan and set as span in a new\n * context\n *\n * @param context context to set active span on\n * @param spanContext span context to be wrapped\n */\nexport function setSpanContext(context, spanContext) {\n return setSpan(context, new NonRecordingSpan(spanContext));\n}\n/**\n * Get the span context of the span if it exists.\n *\n * @param context context to get values from\n */\nexport function getSpanContext(context) {\n var _a;\n return (_a = getSpan(context)) === null || _a === void 0 ? void 0 : _a.spanContext();\n}\n//# sourceMappingURL=context-utils.js.map","/*\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 { INVALID_SPANID, INVALID_TRACEID } from './invalid-span-constants';\nimport { NonRecordingSpan } from './NonRecordingSpan';\nvar VALID_TRACEID_REGEX = /^([0-9a-f]{32})$/i;\nvar VALID_SPANID_REGEX = /^[0-9a-f]{16}$/i;\nexport function isValidTraceId(traceId) {\n return VALID_TRACEID_REGEX.test(traceId) && traceId !== INVALID_TRACEID;\n}\nexport function isValidSpanId(spanId) {\n return VALID_SPANID_REGEX.test(spanId) && spanId !== INVALID_SPANID;\n}\n/**\n * Returns true if this {@link SpanContext} is valid.\n * @return true if this {@link SpanContext} is valid.\n */\nexport function isSpanContextValid(spanContext) {\n return (isValidTraceId(spanContext.traceId) && isValidSpanId(spanContext.spanId));\n}\n/**\n * Wrap the given {@link SpanContext} in a new non-recording {@link Span}\n *\n * @param spanContext span context to be wrapped\n * @returns a new non-recording {@link Span} with the provided context\n */\nexport function wrapSpanContext(spanContext) {\n return new NonRecordingSpan(spanContext);\n}\n//# sourceMappingURL=spancontext-utils.js.map","/*\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 { ContextAPI } from '../api/context';\nimport { getSpanContext, setSpan } from '../trace/context-utils';\nimport { NonRecordingSpan } from './NonRecordingSpan';\nimport { isSpanContextValid } from './spancontext-utils';\nvar contextApi = ContextAPI.getInstance();\n/**\n * No-op implementations of {@link Tracer}.\n */\nvar NoopTracer = /** @class */ (function () {\n function NoopTracer() {\n }\n // startSpan starts a noop span.\n NoopTracer.prototype.startSpan = function (name, options, context) {\n if (context === void 0) { context = contextApi.active(); }\n var root = Boolean(options === null || options === void 0 ? void 0 : options.root);\n if (root) {\n return new NonRecordingSpan();\n }\n var parentFromContext = context && getSpanContext(context);\n if (isSpanContext(parentFromContext) &&\n isSpanContextValid(parentFromContext)) {\n return new NonRecordingSpan(parentFromContext);\n }\n else {\n return new NonRecordingSpan();\n }\n };\n NoopTracer.prototype.startActiveSpan = function (name, arg2, arg3, arg4) {\n var opts;\n var ctx;\n var fn;\n if (arguments.length < 2) {\n return;\n }\n else if (arguments.length === 2) {\n fn = arg2;\n }\n else if (arguments.length === 3) {\n opts = arg2;\n fn = arg3;\n }\n else {\n opts = arg2;\n ctx = arg3;\n fn = arg4;\n }\n var parentContext = ctx !== null && ctx !== void 0 ? ctx : contextApi.active();\n var span = this.startSpan(name, opts, parentContext);\n var contextWithSpanSet = setSpan(parentContext, span);\n return contextApi.with(contextWithSpanSet, fn, undefined, span);\n };\n return NoopTracer;\n}());\nexport { NoopTracer };\nfunction isSpanContext(spanContext) {\n return (typeof spanContext === 'object' &&\n typeof spanContext['spanId'] === 'string' &&\n typeof spanContext['traceId'] === 'string' &&\n typeof spanContext['traceFlags'] === 'number');\n}\n//# sourceMappingURL=NoopTracer.js.map","/*\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 { NoopTracer } from './NoopTracer';\nvar NOOP_TRACER = new NoopTracer();\n/**\n * Proxy tracer provided by the proxy tracer provider\n */\nvar ProxyTracer = /** @class */ (function () {\n function ProxyTracer(_provider, name, version, options) {\n this._provider = _provider;\n this.name = name;\n this.version = version;\n this.options = options;\n }\n ProxyTracer.prototype.startSpan = function (name, options, context) {\n return this._getTracer().startSpan(name, options, context);\n };\n ProxyTracer.prototype.startActiveSpan = function (_name, _options, _context, _fn) {\n var tracer = this._getTracer();\n return Reflect.apply(tracer.startActiveSpan, tracer, arguments);\n };\n /**\n * Try to get a tracer from the proxy tracer provider.\n * If the proxy tracer provider has no delegate, return a noop tracer.\n */\n ProxyTracer.prototype._getTracer = function () {\n if (this._delegate) {\n return this._delegate;\n }\n var tracer = this._provider.getDelegateTracer(this.name, this.version, this.options);\n if (!tracer) {\n return NOOP_TRACER;\n }\n this._delegate = tracer;\n return this._delegate;\n };\n return ProxyTracer;\n}());\nexport { ProxyTracer };\n//# sourceMappingURL=ProxyTracer.js.map","/*\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 { NoopTracer } from './NoopTracer';\n/**\n * An implementation of the {@link TracerProvider} which returns an impotent\n * Tracer for all calls to `getTracer`.\n *\n * All operations are no-op.\n */\nvar NoopTracerProvider = /** @class */ (function () {\n function NoopTracerProvider() {\n }\n NoopTracerProvider.prototype.getTracer = function (_name, _version, _options) {\n return new NoopTracer();\n };\n return NoopTracerProvider;\n}());\nexport { NoopTracerProvider };\n//# sourceMappingURL=NoopTracerProvider.js.map","/*\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 { ProxyTracer } from './ProxyTracer';\nimport { NoopTracerProvider } from './NoopTracerProvider';\nvar NOOP_TRACER_PROVIDER = new NoopTracerProvider();\n/**\n * Tracer provider which provides {@link ProxyTracer}s.\n *\n * Before a delegate is set, tracers provided are NoOp.\n * When a delegate is set, traces are provided from the delegate.\n * When a delegate is set after tracers have already been provided,\n * all tracers already provided will use the provided delegate implementation.\n */\nvar ProxyTracerProvider = /** @class */ (function () {\n function ProxyTracerProvider() {\n }\n /**\n * Get a {@link ProxyTracer}\n */\n ProxyTracerProvider.prototype.getTracer = function (name, version, options) {\n var _a;\n return ((_a = this.getDelegateTracer(name, version, options)) !== null && _a !== void 0 ? _a : new ProxyTracer(this, name, version, options));\n };\n ProxyTracerProvider.prototype.getDelegate = function () {\n var _a;\n return (_a = this._delegate) !== null && _a !== void 0 ? _a : NOOP_TRACER_PROVIDER;\n };\n /**\n * Set the delegate tracer provider\n */\n ProxyTracerProvider.prototype.setDelegate = function (delegate) {\n this._delegate = delegate;\n };\n ProxyTracerProvider.prototype.getDelegateTracer = function (name, version, options) {\n var _a;\n return (_a = this._delegate) === null || _a === void 0 ? void 0 : _a.getTracer(name, version, options);\n };\n return ProxyTracerProvider;\n}());\nexport { ProxyTracerProvider };\n//# sourceMappingURL=ProxyTracerProvider.js.map","/*\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 * @deprecated use the one declared in @opentelemetry/sdk-trace-base instead.\n * A sampling decision that determines how a {@link Span} will be recorded\n * and collected.\n */\nexport var SamplingDecision;\n(function (SamplingDecision) {\n /**\n * `Span.isRecording() === false`, span will not be recorded and all events\n * and attributes will be dropped.\n */\n SamplingDecision[SamplingDecision[\"NOT_RECORD\"] = 0] = \"NOT_RECORD\";\n /**\n * `Span.isRecording() === true`, but `Sampled` flag in {@link TraceFlags}\n * MUST NOT be set.\n */\n SamplingDecision[SamplingDecision[\"RECORD\"] = 1] = \"RECORD\";\n /**\n * `Span.isRecording() === true` AND `Sampled` flag in {@link TraceFlags}\n * MUST be set.\n */\n SamplingDecision[SamplingDecision[\"RECORD_AND_SAMPLED\"] = 2] = \"RECORD_AND_SAMPLED\";\n})(SamplingDecision || (SamplingDecision = {}));\n//# sourceMappingURL=SamplingResult.js.map","/*\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 */\nexport var SpanKind;\n(function (SpanKind) {\n /** Default value. Indicates that the span is used internally. */\n SpanKind[SpanKind[\"INTERNAL\"] = 0] = \"INTERNAL\";\n /**\n * Indicates that the span covers server-side handling of an RPC or other\n * remote request.\n */\n SpanKind[SpanKind[\"SERVER\"] = 1] = \"SERVER\";\n /**\n * Indicates that the span covers the client-side wrapper around an RPC or\n * other remote request.\n */\n SpanKind[SpanKind[\"CLIENT\"] = 2] = \"CLIENT\";\n /**\n * Indicates that the span describes producer sending a message to a\n * broker. Unlike client and server, there is no direct critical path latency\n * relationship between producer and consumer spans.\n */\n SpanKind[SpanKind[\"PRODUCER\"] = 3] = \"PRODUCER\";\n /**\n * Indicates that the span describes consumer receiving a message from a\n * broker. Unlike client and server, there is no direct critical path latency\n * relationship between producer and consumer spans.\n */\n SpanKind[SpanKind[\"CONSUMER\"] = 4] = \"CONSUMER\";\n})(SpanKind || (SpanKind = {}));\n//# sourceMappingURL=span_kind.js.map","/**\n * An enumeration of status codes.\n */\nexport var SpanStatusCode;\n(function (SpanStatusCode) {\n /**\n * The default status.\n */\n SpanStatusCode[SpanStatusCode[\"UNSET\"] = 0] = \"UNSET\";\n /**\n * The operation has been validated by an Application developer or\n * Operator to have completed successfully.\n */\n SpanStatusCode[SpanStatusCode[\"OK\"] = 1] = \"OK\";\n /**\n * The operation contains an error.\n */\n SpanStatusCode[SpanStatusCode[\"ERROR\"] = 2] = \"ERROR\";\n})(SpanStatusCode || (SpanStatusCode = {}));\n//# sourceMappingURL=status.js.map","/*\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// Split module-level variable definition into separate files to allow\n// tree-shaking on each api instance.\nimport { ContextAPI } from './api/context';\n/** Entrypoint for context API */\nexport var context = ContextAPI.getInstance();\n//# sourceMappingURL=context-api.js.map","/*\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// Split module-level variable definition into separate files to allow\n// tree-shaking on each api instance.\nimport { DiagAPI } from './api/diag';\n/**\n * Entrypoint for Diag API.\n * Defines Diagnostic handler used for internal diagnostic logging operations.\n * The default provides a Noop DiagLogger implementation which may be changed via the\n * diag.setLogger(logger: DiagLogger) function.\n */\nexport var diag = DiagAPI.instance();\n//# sourceMappingURL=diag-api.js.map","/*\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 { getGlobal, registerGlobal, unregisterGlobal, } from '../internal/global-utils';\nimport { ProxyTracerProvider } from '../trace/ProxyTracerProvider';\nimport { isSpanContextValid, wrapSpanContext, } from '../trace/spancontext-utils';\nimport { deleteSpan, getActiveSpan, getSpan, getSpanContext, setSpan, setSpanContext, } from '../trace/context-utils';\nimport { DiagAPI } from './diag';\nvar API_NAME = 'trace';\n/**\n * Singleton object which represents the entry point to the OpenTelemetry Tracing API\n */\nvar TraceAPI = /** @class */ (function () {\n /** Empty private constructor prevents end users from constructing a new instance of the API */\n function TraceAPI() {\n this._proxyTracerProvider = new ProxyTracerProvider();\n this.wrapSpanContext = wrapSpanContext;\n this.isSpanContextValid = isSpanContextValid;\n this.deleteSpan = deleteSpan;\n this.getSpan = getSpan;\n this.getActiveSpan = getActiveSpan;\n this.getSpanContext = getSpanContext;\n this.setSpan = setSpan;\n this.setSpanContext = setSpanContext;\n }\n /** Get the singleton instance of the Trace API */\n TraceAPI.getInstance = function () {\n if (!this._instance) {\n this._instance = new TraceAPI();\n }\n return this._instance;\n };\n /**\n * Set the current global tracer.\n *\n * @returns true if the tracer provider was successfully registered, else false\n */\n TraceAPI.prototype.setGlobalTracerProvider = function (provider) {\n var success = registerGlobal(API_NAME, this._proxyTracerProvider, DiagAPI.instance());\n if (success) {\n this._proxyTracerProvider.setDelegate(provider);\n }\n return success;\n };\n /**\n * Returns the global tracer provider.\n */\n TraceAPI.prototype.getTracerProvider = function () {\n return getGlobal(API_NAME) || this._proxyTracerProvider;\n };\n /**\n * Returns a tracer from the global tracer provider.\n */\n TraceAPI.prototype.getTracer = function (name, version) {\n return this.getTracerProvider().getTracer(name, version);\n };\n /** Remove the global tracer provider */\n TraceAPI.prototype.disable = function () {\n unregisterGlobal(API_NAME, DiagAPI.instance());\n this._proxyTracerProvider = new ProxyTracerProvider();\n };\n return TraceAPI;\n}());\nexport { TraceAPI };\n//# sourceMappingURL=trace.js.map","/*\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// Split module-level variable definition into separate files to allow\n// tree-shaking on each api instance.\nimport { TraceAPI } from './api/trace';\n/** Entrypoint for trace API */\nexport var trace = TraceAPI.getInstance();\n//# sourceMappingURL=trace-api.js.map","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nexport class OTLPExporterBase {\n _delegate;\n constructor(delegate) {\n this._delegate = delegate;\n }\n /**\n * Export items.\n * @param items\n * @param resultCallback\n */\n export(items, resultCallback) {\n this._delegate.export(items, resultCallback);\n }\n forceFlush() {\n return this._delegate.forceFlush();\n }\n shutdown() {\n return this._delegate.shutdown();\n }\n}\n//# sourceMappingURL=OTLPExporterBase.js.map","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n/**\n * Interface for handling error\n */\nexport class OTLPExporterError extends Error {\n code;\n name = 'OTLPExporterError';\n data;\n constructor(message, code, data) {\n super(message);\n this.data = data;\n this.code = code;\n }\n}\n//# sourceMappingURL=types.js.map","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nclass BoundedQueueExportPromiseHandler {\n _concurrencyLimit;\n _sendingPromises = [];\n /**\n * @param concurrencyLimit maximum promises allowed in a queue at the same time.\n */\n constructor(concurrencyLimit) {\n this._concurrencyLimit = concurrencyLimit;\n }\n pushPromise(promise) {\n if (this.hasReachedLimit()) {\n throw new Error('Concurrency Limit reached');\n }\n this._sendingPromises.push(promise);\n const popPromise = () => {\n const index = this._sendingPromises.indexOf(promise);\n void this._sendingPromises.splice(index, 1);\n };\n promise.then(popPromise, popPromise);\n }\n hasReachedLimit() {\n return this._sendingPromises.length >= this._concurrencyLimit;\n }\n async awaitAll() {\n await Promise.all(this._sendingPromises);\n }\n}\n/**\n * Promise queue for keeping track of export promises. Finished promises will be auto-dequeued.\n * Allows for awaiting all promises in the queue.\n */\nexport function createBoundedQueueExportPromiseHandler(options) {\n return new BoundedQueueExportPromiseHandler(options.concurrencyLimit);\n}\n//# sourceMappingURL=bounded-queue-export-promise-handler.js.map","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { createContextKey } from '@opentelemetry/api';\nconst SUPPRESS_TRACING_KEY = createContextKey('OpenTelemetry SDK Context Key SUPPRESS_TRACING');\nexport function suppressTracing(context) {\n return context.setValue(SUPPRESS_TRACING_KEY, true);\n}\nexport function unsuppressTracing(context) {\n return context.deleteValue(SUPPRESS_TRACING_KEY);\n}\nexport function isTracingSuppressed(context) {\n return context.getValue(SUPPRESS_TRACING_KEY) === true;\n}\n//# sourceMappingURL=suppress-tracing.js.map","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { diag } from '@opentelemetry/api';\nexport function sanitizeAttributes(attributes) {\n const out = {};\n if (typeof attributes !== 'object' || attributes == null) {\n return out;\n }\n for (const key in attributes) {\n if (!Object.prototype.hasOwnProperty.call(attributes, key)) {\n continue;\n }\n if (!isAttributeKey(key)) {\n diag.warn(`Invalid attribute key: ${key}`);\n continue;\n }\n const val = attributes[key];\n if (!isAttributeValue(val)) {\n diag.warn(`Invalid attribute value set for key: ${key}`);\n continue;\n }\n if (Array.isArray(val)) {\n out[key] = val.slice();\n }\n else {\n out[key] = val;\n }\n }\n return out;\n}\nexport function isAttributeKey(key) {\n return typeof key === 'string' && key !== '';\n}\nexport function isAttributeValue(val) {\n if (val == null) {\n return true;\n }\n if (Array.isArray(val)) {\n return isHomogeneousAttributeValueArray(val);\n }\n return isValidPrimitiveAttributeValueType(typeof val);\n}\nfunction isHomogeneousAttributeValueArray(arr) {\n let type;\n for (const element of arr) {\n // null/undefined elements are allowed\n if (element == null)\n continue;\n const elementType = typeof element;\n if (elementType === type) {\n continue;\n }\n if (!type) {\n if (isValidPrimitiveAttributeValueType(elementType)) {\n type = elementType;\n continue;\n }\n // encountered an invalid primitive\n return false;\n }\n return false;\n }\n return true;\n}\nfunction isValidPrimitiveAttributeValueType(valType) {\n switch (valType) {\n case 'number':\n case 'boolean':\n case 'string':\n return true;\n }\n return false;\n}\n//# sourceMappingURL=attributes.js.map","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { diag } from '@opentelemetry/api';\n/**\n * Returns a function that logs an error using the provided logger, or a\n * console logger if one was not provided.\n */\nexport function loggingErrorHandler() {\n return (ex) => {\n diag.error(stringifyException(ex));\n };\n}\n/**\n * Converts an exception into a string representation\n * @param {Exception} ex\n */\nfunction stringifyException(ex) {\n if (typeof ex === 'string') {\n return ex;\n }\n else {\n return JSON.stringify(flattenException(ex));\n }\n}\n/**\n * Flattens an exception into key-value pairs by traversing the prototype chain\n * and coercing values to strings. Duplicate properties will not be overwritten;\n * the first insert wins.\n */\nfunction flattenException(ex) {\n const result = {};\n let current = ex;\n while (current !== null) {\n Object.getOwnPropertyNames(current).forEach(propertyName => {\n if (result[propertyName])\n return;\n const value = current[propertyName];\n if (value) {\n result[propertyName] = String(value);\n }\n });\n current = Object.getPrototypeOf(current);\n }\n return result;\n}\n//# sourceMappingURL=logging-error-handler.js.map","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { loggingErrorHandler } from './logging-error-handler';\n/** The global error handler delegate */\nlet delegateHandler = loggingErrorHandler();\n/**\n * Set the global error handler\n * @param {ErrorHandler} handler\n */\nexport function setGlobalErrorHandler(handler) {\n delegateHandler = handler;\n}\n/**\n * Return the global error handler\n * @param {Exception} ex\n */\nexport function globalErrorHandler(ex) {\n try {\n delegateHandler(ex);\n }\n catch { } // eslint-disable-line no-empty\n}\n//# sourceMappingURL=global-error-handler.js.map","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { diag } from '@opentelemetry/api';\nimport { inspect } from 'util';\n/**\n * Retrieves a number from an environment variable.\n * - Returns `undefined` if the environment variable is empty, unset, contains only whitespace, or is not a number.\n * - Returns a number in all other cases.\n *\n * @param {string} key - The name of the environment variable to retrieve.\n * @returns {number | undefined} - The number value or `undefined`.\n */\nexport function getNumberFromEnv(key) {\n const raw = process.env[key];\n if (raw == null || raw.trim() === '') {\n return undefined;\n }\n const value = Number(raw);\n if (isNaN(value)) {\n diag.warn(`Unknown value ${inspect(raw)} for ${key}, expected a number, using defaults`);\n return undefined;\n }\n return value;\n}\n/**\n * Retrieves a string from an environment variable.\n * - Returns `undefined` if the environment variable is empty, unset, or contains only whitespace.\n *\n * @param {string} key - The name of the environment variable to retrieve.\n * @returns {string | undefined} - The string value or `undefined`.\n */\nexport function getStringFromEnv(key) {\n const raw = process.env[key];\n if (raw == null || raw.trim() === '') {\n return undefined;\n }\n return raw;\n}\n/**\n * Retrieves a boolean value from an environment variable.\n * - Trims leading and trailing whitespace and ignores casing.\n * - Returns `false` if the environment variable is empty, unset, or contains only whitespace.\n * - Returns `false` for strings that cannot be mapped to a boolean.\n *\n * @param {string} key - The name of the environment variable to retrieve.\n * @returns {boolean} - The boolean value or `false` if the environment variable is unset empty, unset, or contains only whitespace.\n */\nexport function getBooleanFromEnv(key) {\n const raw = process.env[key]?.trim().toLowerCase();\n if (raw == null || raw === '') {\n // NOTE: falling back to `false` instead of `undefined` as required by the specification.\n // If you have a use-case that requires `undefined`, consider using `getStringFromEnv()` and applying the necessary\n // normalizations in the consuming code.\n return false;\n }\n if (raw === 'true') {\n return true;\n }\n else if (raw === 'false') {\n return false;\n }\n else {\n diag.warn(`Unknown value ${inspect(raw)} for ${key}, expected 'true' or 'false', falling back to 'false' (default)`);\n return false;\n }\n}\n/**\n * Retrieves a list of strings from an environment variable.\n * - Uses ',' as the delimiter.\n * - Trims leading and trailing whitespace from each entry.\n * - Excludes empty entries.\n * - Returns `undefined` if the environment variable is empty or contains only whitespace.\n * - Returns an empty array if all entries are empty or whitespace.\n *\n * @param {string} key - The name of the environment variable to retrieve.\n * @returns {string[] | undefined} - The list of strings or `undefined`.\n */\nexport function getStringListFromEnv(key) {\n return getStringFromEnv(key)\n ?.split(',')\n .map(v => v.trim())\n .filter(s => s !== '');\n}\n//# sourceMappingURL=environment.js.map","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '2.8.0';\n//# sourceMappingURL=version.js.map","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n//----------------------------------------------------------------------------------------------------------\n// DO NOT EDIT, this is an Auto-generated file from scripts/semconv/templates/registry/stable/attributes.ts.j2\n//----------------------------------------------------------------------------------------------------------\n/**\n * ASP.NET Core exception middleware handling result.\n *\n * @example handled\n * @example unhandled\n */\nexport const ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT = 'aspnetcore.diagnostics.exception.result';\n/**\n * Enum value \"aborted\" for attribute {@link ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT}.\n *\n * Exception handling didn't run because the request was aborted.\n */\nexport const ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_ABORTED = \"aborted\";\n/**\n * Enum value \"handled\" for attribute {@link ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT}.\n *\n * Exception was handled by the exception handling middleware.\n */\nexport const ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_HANDLED = \"handled\";\n/**\n * Enum value \"skipped\" for attribute {@link ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT}.\n *\n * Exception handling was skipped because the response had started.\n */\nexport const ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_SKIPPED = \"skipped\";\n/**\n * Enum value \"unhandled\" for attribute {@link ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT}.\n *\n * Exception was not handled by the exception handling middleware.\n */\nexport const ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_UNHANDLED = \"unhandled\";\n/**\n * Full type name of the [`IExceptionHandler`](https://learn.microsoft.com/dotnet/api/microsoft.aspnetcore.diagnostics.iexceptionhandler) implementation that handled the exception.\n *\n * @example Contoso.MyHandler\n */\nexport const ATTR_ASPNETCORE_DIAGNOSTICS_HANDLER_TYPE = 'aspnetcore.diagnostics.handler.type';\n/**\n * Rate limiting policy name.\n *\n * @example fixed\n * @example sliding\n * @example token\n */\nexport const ATTR_ASPNETCORE_RATE_LIMITING_POLICY = 'aspnetcore.rate_limiting.policy';\n/**\n * Rate-limiting result, shows whether the lease was acquired or contains a rejection reason\n *\n * @example acquired\n * @example request_canceled\n */\nexport const ATTR_ASPNETCORE_RATE_LIMITING_RESULT = 'aspnetcore.rate_limiting.result';\n/**\n * Enum value \"acquired\" for attribute {@link ATTR_ASPNETCORE_RATE_LIMITING_RESULT}.\n *\n * Lease was acquired\n */\nexport const ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ACQUIRED = \"acquired\";\n/**\n * Enum value \"endpoint_limiter\" for attribute {@link ATTR_ASPNETCORE_RATE_LIMITING_RESULT}.\n *\n * Lease request was rejected by the endpoint limiter\n */\nexport const ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ENDPOINT_LIMITER = \"endpoint_limiter\";\n/**\n * Enum value \"global_limiter\" for attribute {@link ATTR_ASPNETCORE_RATE_LIMITING_RESULT}.\n *\n * Lease request was rejected by the global limiter\n */\nexport const ASPNETCORE_RATE_LIMITING_RESULT_VALUE_GLOBAL_LIMITER = \"global_limiter\";\n/**\n * Enum value \"request_canceled\" for attribute {@link ATTR_ASPNETCORE_RATE_LIMITING_RESULT}.\n *\n * Lease request was canceled\n */\nexport const ASPNETCORE_RATE_LIMITING_RESULT_VALUE_REQUEST_CANCELED = \"request_canceled\";\n/**\n * Flag indicating if request was handled by the application pipeline.\n *\n * @example true\n */\nexport const ATTR_ASPNETCORE_REQUEST_IS_UNHANDLED = 'aspnetcore.request.is_unhandled';\n/**\n * A value that indicates whether the matched route is a fallback route.\n *\n * @example true\n */\nexport const ATTR_ASPNETCORE_ROUTING_IS_FALLBACK = 'aspnetcore.routing.is_fallback';\n/**\n * Match result - success or failure\n *\n * @example success\n * @example failure\n */\nexport const ATTR_ASPNETCORE_ROUTING_MATCH_STATUS = 'aspnetcore.routing.match_status';\n/**\n * Enum value \"failure\" for attribute {@link ATTR_ASPNETCORE_ROUTING_MATCH_STATUS}.\n *\n * Match failed\n */\nexport const ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_FAILURE = \"failure\";\n/**\n * Enum value \"success\" for attribute {@link ATTR_ASPNETCORE_ROUTING_MATCH_STATUS}.\n *\n * Match succeeded\n */\nexport const ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_SUCCESS = \"success\";\n/**\n * A value that indicates whether the user is authenticated.\n *\n * @example true\n */\nexport const ATTR_ASPNETCORE_USER_IS_AUTHENTICATED = 'aspnetcore.user.is_authenticated';\n/**\n * Client address - domain name if available without reverse DNS lookup; otherwise, IP address or Unix domain socket name.\n *\n * @example client.example.com\n * @example 10.1.2.80\n * @example /tmp/my.sock\n *\n * @note When observed from the server side, and when communicating through an intermediary, `client.address` **SHOULD** represent the client address behind any intermediaries, for example proxies, if it's available.\n */\nexport const ATTR_CLIENT_ADDRESS = 'client.address';\n/**\n * Client port number.\n *\n * @example 65123\n *\n * @note When observed from the server side, and when communicating through an intermediary, `client.port` **SHOULD** represent the client port behind any intermediaries, for example proxies, if it's available.\n */\nexport const ATTR_CLIENT_PORT = 'client.port';\n/**\n * The column number in `code.file.path` best representing the operation. It **SHOULD** point within the code unit named in `code.function.name`. This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Line'. This constraint is imposed to prevent redundancy and maintain data integrity.\n *\n * @example 16\n */\nexport const ATTR_CODE_COLUMN_NUMBER = 'code.column.number';\n/**\n * The source code file name that identifies the code unit as uniquely as possible (preferably an absolute file path). This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Function'. This constraint is imposed to prevent redundancy and maintain data integrity.\n *\n * @example \"/usr/local/MyApplication/content_root/app/index.php\"\n */\nexport const ATTR_CODE_FILE_PATH = 'code.file.path';\n/**\n * The method or function fully-qualified name without arguments. The value should fit the natural representation of the language runtime, which is also likely the same used within `code.stacktrace` attribute value. This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Function'. This constraint is imposed to prevent redundancy and maintain data integrity.\n *\n * @example com.example.MyHttpService.serveRequest\n * @example GuzzleHttp\\\\Client::transfer\n * @example fopen\n *\n * @note Values and format depends on each language runtime, thus it is impossible to provide an exhaustive list of examples.\n * The values are usually the same (or prefixes of) the ones found in native stack trace representation stored in\n * `code.stacktrace` without information on arguments.\n *\n * Examples:\n *\n * - Java method: `com.example.MyHttpService.serveRequest`\n * - Java anonymous class method: `com.mycompany.Main$1.myMethod`\n * - Java lambda method: `com.mycompany.Main$$Lambda/0x0000748ae4149c00.myMethod`\n * - PHP function: `GuzzleHttp\\Client::transfer`\n * - Go function: `github.com/my/repo/pkg.foo.func5`\n * - Elixir: `OpenTelemetry.Ctx.new`\n * - Erlang: `opentelemetry_ctx:new`\n * - Rust: `playground::my_module::my_cool_func`\n * - C function: `fopen`\n */\nexport const ATTR_CODE_FUNCTION_NAME = 'code.function.name';\n/**\n * The line number in `code.file.path` best representing the operation. It **SHOULD** point within the code unit named in `code.function.name`. This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Line'. This constraint is imposed to prevent redundancy and maintain data integrity.\n *\n * @example 42\n */\nexport const ATTR_CODE_LINE_NUMBER = 'code.line.number';\n/**\n * A stacktrace as a string in the natural representation for the language runtime. The representation is identical to [`exception.stacktrace`](/docs/exceptions/exceptions-spans.md#stacktrace-representation). This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Location'. This constraint is imposed to prevent redundancy and maintain data integrity.\n *\n * @example \"at com.example.GenerateTrace.methodB(GenerateTrace.java:13)\\\\n at com.example.GenerateTrace.methodA(GenerateTrace.java:9)\\\\n at com.example.GenerateTrace.main(GenerateTrace.java:5)\\\\n\"\n */\nexport const ATTR_CODE_STACKTRACE = 'code.stacktrace';\n/**\n * Container ID. Usually a UUID, as for example used to [identify Docker containers](https://docs.docker.com/engine/containers/run/#container-identification). The UUID might be abbreviated.\n *\n * @example a3bf90e006b2\n */\nexport const ATTR_CONTAINER_ID = 'container.id';\n/**\n * Name of the image the container was built on.\n *\n * @example gcr.io/opentelemetry/operator\n */\nexport const ATTR_CONTAINER_IMAGE_NAME = 'container.image.name';\n/**\n * Repo digests of the container image as provided by the container runtime.\n *\n * @example [\"example@sha256:afcc7f1ac1b49db317a7196c902e61c6c3c4607d63599ee1a82d702d249a0ccb\", \"internal.registry.example.com:5000/example@sha256:b69959407d21e8a062e0416bf13405bb2b71ed7a84dde4158ebafacfa06f5578\"]\n *\n * @note [Docker](https://docs.docker.com/reference/api/engine/version/v1.52/#tag/Image/operation/ImageInspect) and [CRI](https://github.com/kubernetes/cri-api/blob/c75ef5b473bbe2d0a4fc92f82235efd665ea8e9f/pkg/apis/runtime/v1/api.proto#L1237-L1238) report those under the `RepoDigests` field.\n */\nexport const ATTR_CONTAINER_IMAGE_REPO_DIGESTS = 'container.image.repo_digests';\n/**\n * Container image tags. An example can be found in [Docker Image Inspect](https://docs.docker.com/reference/api/engine/version/v1.52/#tag/Image/operation/ImageInspect). Should be only the `<tag>` section of the full name for example from `registry.example.com/my-org/my-image:<tag>`.\n *\n * @example [\"v1.27.1\", \"3.5.7-0\"]\n */\nexport const ATTR_CONTAINER_IMAGE_TAGS = 'container.image.tags';\n/**\n * The name of a collection (table, container) within the database.\n *\n * @example public.users\n * @example customers\n *\n * @note It is **RECOMMENDED** to capture the value as provided by the application\n * without attempting to do any case normalization.\n *\n * The collection name **SHOULD NOT** be extracted from `db.query.text`,\n * when the database system supports query text with multiple collections\n * in non-batch operations.\n *\n * For batch operations, if the individual operations are known to have the same\n * collection name then that collection name **SHOULD** be used.\n */\nexport const ATTR_DB_COLLECTION_NAME = 'db.collection.name';\n/**\n * The name of the database, fully qualified within the server address and port.\n *\n * @example customers\n * @example test.users\n *\n * @note If a database system has multiple namespace components, they **SHOULD** be concatenated from the most general to the most specific namespace component, using `|` as a separator between the components. Any missing components (and their associated separators) **SHOULD** be omitted.\n * Semantic conventions for individual database systems **SHOULD** document what `db.namespace` means in the context of that system.\n * It is **RECOMMENDED** to capture the value as provided by the application without attempting to do any case normalization.\n */\nexport const ATTR_DB_NAMESPACE = 'db.namespace';\n/**\n * The number of database operations included in a batch operation.\n *\n * @example 2\n * @example 3\n * @example 4\n *\n * @note Except for empty batch requests described below, a batch operation contains two\n * or more database operations explicitly submitted as separate operations in a single\n * client call, protocol message, or database command.\n *\n * Requests to batch APIs that contain only one operation **SHOULD** be modeled as single\n * operations, not as batch operations.\n *\n * A database call is not a batch operation solely because one operation accepts\n * multiple operands, such as keys, rows, documents, points, or other data elements,\n * including Redis [`MGET`](https://redis.io/docs/latest/commands/mget/) with\n * multiple keys.\n *\n * In batch APIs that execute the same parameterized operation with parameter sets,\n * each parameter set represents one database operation for determining whether the\n * request is a batch operation. Requests with only one parameter set **SHOULD** be modeled\n * as single operations, not as batch operations.\n *\n * `db.operation.batch.size` **SHOULD** be set to the number of operations in the batch.\n * It **SHOULD NOT** be set for non-batch operations.\n *\n * A request to execute a batch operation with no operations **SHOULD** also be treated\n * as a batch operation, and `db.operation.batch.size` **SHOULD** be set to `0`.\n */\nexport const ATTR_DB_OPERATION_BATCH_SIZE = 'db.operation.batch.size';\n/**\n * The name of the operation or command being executed.\n *\n * @example findAndModify\n * @example HMSET\n * @example SELECT\n *\n * @note It is **RECOMMENDED** to capture the value as provided by the application\n * without attempting to do any case normalization.\n *\n * The operation name **SHOULD NOT** be extracted from `db.query.text`,\n * when the database system supports query text with multiple operations\n * in non-batch operations.\n *\n * If spaces can occur in the operation name, multiple consecutive spaces\n * **SHOULD** be normalized to a single space.\n *\n * For batch operations, if the individual operations are known to have the same operation name\n * then that operation name **SHOULD** be used prepended by `BATCH `,\n * otherwise `db.operation.name` **SHOULD** be `BATCH` or some other database\n * system specific term if more applicable.\n */\nexport const ATTR_DB_OPERATION_NAME = 'db.operation.name';\n/**\n * Low cardinality summary of a database query.\n *\n * @example SELECT wuser_table\n * @example INSERT shipping_details SELECT orders\n * @example get user by id\n *\n * @note The query summary describes a class of database queries and is useful\n * as a grouping key, especially when analyzing telemetry for database\n * calls involving complex queries.\n *\n * Summary may be available to the instrumentation through\n * instrumentation hooks or other means. If it is not available, instrumentations\n * that support query parsing **SHOULD** generate a summary following\n * [Generating query summary](/docs/db/database-spans.md#generating-a-summary-of-the-query)\n * section.\n *\n * For batch operations, if the individual operations are known to have the same query summary\n * then that query summary **SHOULD** be used prepended by `BATCH `,\n * otherwise `db.query.summary` **SHOULD** be `BATCH` or some other database\n * system specific term if more applicable.\n */\nexport const ATTR_DB_QUERY_SUMMARY = 'db.query.summary';\n/**\n * The database query being executed.\n *\n * @example SELECT * FROM wuser_table where username = ?\n * @example SET mykey ?\n *\n * @note For sanitization see [Sanitization of `db.query.text`](/docs/db/database-spans.md#sanitization-of-dbquerytext).\n * For batch operations, if the individual operations are known to have the same query text then that query text **SHOULD** be used, otherwise all of the individual query texts **SHOULD** be concatenated with separator `; ` or some other database system specific separator if more applicable.\n * Parameterized query text **SHOULD NOT** be sanitized. Even though parameterized query text can potentially have sensitive data, by using a parameterized query the user is giving a strong signal that any sensitive data will be passed as parameter values, and the benefit to observability of capturing the static part of the query text by default outweighs the risk.\n */\nexport const ATTR_DB_QUERY_TEXT = 'db.query.text';\n/**\n * Database response status code.\n *\n * @example 102\n * @example ORA-17002\n * @example 08P01\n * @example 404\n *\n * @note The status code returned by the database. Usually it represents an error code, but may also represent partial success, warning, or differentiate between various types of successful outcomes.\n * Semantic conventions for individual database systems **SHOULD** document what `db.response.status_code` means in the context of that system.\n */\nexport const ATTR_DB_RESPONSE_STATUS_CODE = 'db.response.status_code';\n/**\n * The name of a stored procedure within the database.\n *\n * @example GetCustomer\n *\n * @note It is **RECOMMENDED** to capture the value as provided by the application\n * without attempting to do any case normalization.\n *\n * For batch operations, if the individual operations are known to have the same\n * stored procedure name then that stored procedure name **SHOULD** be used.\n */\nexport const ATTR_DB_STORED_PROCEDURE_NAME = 'db.stored_procedure.name';\n/**\n * The database management system (DBMS) product as identified by the client instrumentation.\n *\n * @note The actual DBMS may differ from the one identified by the client. For example, when using PostgreSQL client libraries to connect to a CockroachDB, the `db.system.name` is set to `postgresql` based on the instrumentation's best knowledge.\n */\nexport const ATTR_DB_SYSTEM_NAME = 'db.system.name';\n/**\n * Enum value \"mariadb\" for attribute {@link ATTR_DB_SYSTEM_NAME}.\n *\n * [MariaDB](https://mariadb.org/)\n */\nexport const DB_SYSTEM_NAME_VALUE_MARIADB = \"mariadb\";\n/**\n * Enum value \"microsoft.sql_server\" for attribute {@link ATTR_DB_SYSTEM_NAME}.\n *\n * [Microsoft SQL Server](https://www.microsoft.com/sql-server)\n */\nexport const DB_SYSTEM_NAME_VALUE_MICROSOFT_SQL_SERVER = \"microsoft.sql_server\";\n/**\n * Enum value \"mysql\" for attribute {@link ATTR_DB_SYSTEM_NAME}.\n *\n * [MySQL](https://www.mysql.com/)\n */\nexport const DB_SYSTEM_NAME_VALUE_MYSQL = \"mysql\";\n/**\n * Enum value \"postgresql\" for attribute {@link ATTR_DB_SYSTEM_NAME}.\n *\n * [PostgreSQL](https://www.postgresql.org/)\n */\nexport const DB_SYSTEM_NAME_VALUE_POSTGRESQL = \"postgresql\";\n/**\n * Name of the [deployment environment](https://wikipedia.org/wiki/Deployment_environment) (aka deployment tier).\n *\n * @example staging\n * @example production\n *\n * @note `deployment.environment.name` does not affect the uniqueness constraints defined through\n * the `service.namespace`, `service.name` and `service.instance.id` resource attributes.\n * This implies that resources carrying the following attribute combinations **MUST** be\n * considered to be identifying the same service:\n *\n * - `service.name=frontend`, `deployment.environment.name=production`\n * - `service.name=frontend`, `deployment.environment.name=staging`.\n */\nexport const ATTR_DEPLOYMENT_ENVIRONMENT_NAME = 'deployment.environment.name';\n/**\n * Enum value \"development\" for attribute {@link ATTR_DEPLOYMENT_ENVIRONMENT_NAME}.\n *\n * Development environment\n */\nexport const DEPLOYMENT_ENVIRONMENT_NAME_VALUE_DEVELOPMENT = \"development\";\n/**\n * Enum value \"production\" for attribute {@link ATTR_DEPLOYMENT_ENVIRONMENT_NAME}.\n *\n * Production environment\n */\nexport const DEPLOYMENT_ENVIRONMENT_NAME_VALUE_PRODUCTION = \"production\";\n/**\n * Enum value \"staging\" for attribute {@link ATTR_DEPLOYMENT_ENVIRONMENT_NAME}.\n *\n * Staging environment\n */\nexport const DEPLOYMENT_ENVIRONMENT_NAME_VALUE_STAGING = \"staging\";\n/**\n * Enum value \"test\" for attribute {@link ATTR_DEPLOYMENT_ENVIRONMENT_NAME}.\n *\n * Testing environment\n */\nexport const DEPLOYMENT_ENVIRONMENT_NAME_VALUE_TEST = \"test\";\n/**\n * Name of the garbage collector managed heap generation.\n *\n * @example gen0\n * @example gen1\n * @example gen2\n */\nexport const ATTR_DOTNET_GC_HEAP_GENERATION = 'dotnet.gc.heap.generation';\n/**\n * Enum value \"gen0\" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}.\n *\n * Generation 0\n */\nexport const DOTNET_GC_HEAP_GENERATION_VALUE_GEN0 = \"gen0\";\n/**\n * Enum value \"gen1\" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}.\n *\n * Generation 1\n */\nexport const DOTNET_GC_HEAP_GENERATION_VALUE_GEN1 = \"gen1\";\n/**\n * Enum value \"gen2\" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}.\n *\n * Generation 2\n */\nexport const DOTNET_GC_HEAP_GENERATION_VALUE_GEN2 = \"gen2\";\n/**\n * Enum value \"loh\" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}.\n *\n * Large Object Heap\n */\nexport const DOTNET_GC_HEAP_GENERATION_VALUE_LOH = \"loh\";\n/**\n * Enum value \"poh\" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}.\n *\n * Pinned Object Heap\n */\nexport const DOTNET_GC_HEAP_GENERATION_VALUE_POH = \"poh\";\n/**\n * Describes a class of error the operation ended with.\n *\n * @example timeout\n * @example java.net.UnknownHostException\n * @example server_certificate_invalid\n * @example 500\n *\n * @note The `error.type` **SHOULD** be predictable, and **SHOULD** have low cardinality.\n *\n * When `error.type` is set to a type (e.g., an exception type), its\n * canonical class name identifying the type within the artifact **SHOULD** be used.\n *\n * If the recorded error type is a wrapper that is not meaningful for\n * failure classification, instrumentation **MAY** use the type of the inner\n * error instead. For example, in Go, errors created with `fmt.Errorf`\n * using `%w` **MAY** be unwrapped when the wrapper type does not help\n * classify the failure.\n *\n * Instrumentations **SHOULD** document the list of errors they report.\n *\n * The cardinality of `error.type` within one instrumentation library **SHOULD** be low.\n * Telemetry consumers that aggregate data from multiple instrumentation libraries and applications\n * should be prepared for `error.type` to have high cardinality at query time when no\n * additional filters are applied.\n *\n * If the operation has completed successfully, instrumentations **SHOULD NOT** set `error.type`.\n *\n * If a specific domain defines its own set of error identifiers (such as HTTP or RPC status codes),\n * it's **RECOMMENDED** to:\n *\n * - Use a domain-specific attribute\n * - Set `error.type` to capture all errors, regardless of whether they are defined within the domain-specific set or not.\n */\nexport const ATTR_ERROR_TYPE = 'error.type';\n/**\n * Enum value \"_OTHER\" for attribute {@link ATTR_ERROR_TYPE}.\n *\n * A fallback error value to be used when the instrumentation doesn't define a custom value.\n */\nexport const ERROR_TYPE_VALUE_OTHER = \"_OTHER\";\n/**\n * Indicates that the exception is escaping the scope of the span.\n *\n * @deprecated It's no longer recommended to record exceptions that are handled and do not escape the scope of a span.\n */\nexport const ATTR_EXCEPTION_ESCAPED = 'exception.escaped';\n/**\n * The exception message.\n *\n * @example Division by zero\n * @example Can't convert 'int' object to str implicitly\n *\n * @note > [!WARNING]\n *\n * > This attribute may contain sensitive information.\n */\nexport const ATTR_EXCEPTION_MESSAGE = 'exception.message';\n/**\n * A stacktrace as a string in the natural representation for the language runtime. The representation is to be determined and documented by each language SIG.\n *\n * @example \"Exception in thread \"main\" java.lang.RuntimeException: Test exception\\\\n at com.example.GenerateTrace.methodB(GenerateTrace.java:13)\\\\n at com.example.GenerateTrace.methodA(GenerateTrace.java:9)\\\\n at com.example.GenerateTrace.main(GenerateTrace.java:5)\\\\n\"\n */\nexport const ATTR_EXCEPTION_STACKTRACE = 'exception.stacktrace';\n/**\n * The type of the exception (its fully-qualified class name, if applicable). The dynamic type of the exception should be preferred over the static type in languages that support it.\n *\n * @example java.net.ConnectException\n * @example OSError\n *\n * @note If the recorded exception type is a wrapper that is not meaningful for\n * failure classification, instrumentation **MAY** use the type of the inner\n * exception instead. For example, in Go, errors created with `fmt.Errorf`\n * using `%w` **MAY** be unwrapped when the wrapper type does not help\n * classify the failure.\n */\nexport const ATTR_EXCEPTION_TYPE = 'exception.type';\n/**\n * HTTP request headers, `<key>` being the normalized HTTP Header name (lowercase), the value being the header values.\n *\n * @example [\"application/json\"]\n * @example [\"1.2.3.4\", \"1.2.3.5\"]\n *\n * @note Instrumentations **SHOULD** require an explicit configuration of which headers are to be captured.\n * Including all request headers can be a security risk - explicit configuration helps avoid leaking sensitive information.\n *\n * The `User-Agent` header is already captured in the `user_agent.original` attribute.\n * Users **MAY** explicitly configure instrumentations to capture them even though it is not recommended.\n *\n * The attribute value **MUST** consist of either multiple header values as an array of strings\n * or a single-item array containing a possibly comma-concatenated string, depending on the way\n * the HTTP library provides access to headers.\n *\n * Examples:\n *\n * - A header `Content-Type: application/json` **SHOULD** be recorded as the `http.request.header.content-type`\n * attribute with value `[\"application/json\"]`.\n * - A header `X-Forwarded-For: 1.2.3.4, 1.2.3.5` **SHOULD** be recorded as the `http.request.header.x-forwarded-for`\n * attribute with value `[\"1.2.3.4\", \"1.2.3.5\"]` or `[\"1.2.3.4, 1.2.3.5\"]` depending on the HTTP library.\n */\nexport const ATTR_HTTP_REQUEST_HEADER = (key) => `http.request.header.${key}`;\n/**\n * HTTP request method.\n *\n * @example GET\n * @example POST\n * @example HEAD\n *\n * @note HTTP request method value **SHOULD** be \"known\" to the instrumentation.\n * By default, this convention defines \"known\" methods as the ones listed in [RFC9110](https://www.rfc-editor.org/rfc/rfc9110.html#name-methods),\n * the PATCH method defined in [RFC5789](https://www.rfc-editor.org/rfc/rfc5789.html)\n * and the QUERY method defined in [httpbis-safe-method-w-body](https://datatracker.ietf.org/doc/draft-ietf-httpbis-safe-method-w-body/?include_text=1).\n *\n * If the HTTP request method is not known to instrumentation, it **MUST** set the `http.request.method` attribute to `_OTHER`.\n *\n * If the HTTP instrumentation could end up converting valid HTTP request methods to `_OTHER`, then it **MUST** provide a way to override\n * the list of known HTTP methods. If this override is done via environment variable, then the environment variable **MUST** be named\n * OTEL_INSTRUMENTATION_HTTP_KNOWN_METHODS and support a comma-separated list of case-sensitive known HTTP methods.\n *\n *\n * If this override is done via declarative configuration, then the list **MUST** be configurable via the `known_methods` property\n * (an array of case-sensitive strings with minimum items 0) under `.instrumentation/development.general.http.client` and/or\n * `.instrumentation/development.general.http.server`.\n *\n * In either case, this list **MUST** be a full override of the default known methods,\n * it is not a list of known methods in addition to the defaults.\n *\n * HTTP method names are case-sensitive and `http.request.method` attribute value **MUST** match a known HTTP method name exactly.\n * Instrumentations for specific web frameworks that consider HTTP methods to be case insensitive, **SHOULD** populate a canonical equivalent.\n * Tracing instrumentations that do so, **MUST** also set `http.request.method_original` to the original value.\n */\nexport const ATTR_HTTP_REQUEST_METHOD = 'http.request.method';\n/**\n * Enum value \"_OTHER\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * Any HTTP method that the instrumentation has no prior knowledge of.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_OTHER = \"_OTHER\";\n/**\n * Enum value \"CONNECT\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * CONNECT method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_CONNECT = \"CONNECT\";\n/**\n * Enum value \"DELETE\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * DELETE method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_DELETE = \"DELETE\";\n/**\n * Enum value \"GET\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * GET method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_GET = \"GET\";\n/**\n * Enum value \"HEAD\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * HEAD method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_HEAD = \"HEAD\";\n/**\n * Enum value \"OPTIONS\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * OPTIONS method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_OPTIONS = \"OPTIONS\";\n/**\n * Enum value \"PATCH\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * PATCH method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_PATCH = \"PATCH\";\n/**\n * Enum value \"POST\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * POST method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_POST = \"POST\";\n/**\n * Enum value \"PUT\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * PUT method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_PUT = \"PUT\";\n/**\n * Enum value \"TRACE\" for attribute {@link ATTR_HTTP_REQUEST_METHOD}.\n *\n * TRACE method.\n */\nexport const HTTP_REQUEST_METHOD_VALUE_TRACE = \"TRACE\";\n/**\n * Original HTTP method sent by the client in the request line.\n *\n * @example GeT\n * @example ACL\n * @example foo\n */\nexport const ATTR_HTTP_REQUEST_METHOD_ORIGINAL = 'http.request.method_original';\n/**\n * The ordinal number of request resending attempt (for any reason, including redirects).\n *\n * @example 3\n *\n * @note The resend count **SHOULD** be updated each time an HTTP request gets resent by the client, regardless of what was the cause of the resending (e.g. redirection, authorization failure, 503 Server Unavailable, network issues, or any other).\n */\nexport const ATTR_HTTP_REQUEST_RESEND_COUNT = 'http.request.resend_count';\n/**\n * HTTP response headers, `<key>` being the normalized HTTP Header name (lowercase), the value being the header values.\n *\n * @example [\"application/json\"]\n * @example [\"abc\", \"def\"]\n *\n * @note Instrumentations **SHOULD** require an explicit configuration of which headers are to be captured.\n * Including all response headers can be a security risk - explicit configuration helps avoid leaking sensitive information.\n *\n * Users **MAY** explicitly configure instrumentations to capture them even though it is not recommended.\n *\n * The attribute value **MUST** consist of either multiple header values as an array of strings\n * or a single-item array containing a possibly comma-concatenated string, depending on the way\n * the HTTP library provides access to headers.\n *\n * Examples:\n *\n * - A header `Content-Type: application/json` header **SHOULD** be recorded as the `http.request.response.content-type`\n * attribute with value `[\"application/json\"]`.\n * - A header `My-custom-header: abc, def` header **SHOULD** be recorded as the `http.response.header.my-custom-header`\n * attribute with value `[\"abc\", \"def\"]` or `[\"abc, def\"]` depending on the HTTP library.\n */\nexport const ATTR_HTTP_RESPONSE_HEADER = (key) => `http.response.header.${key}`;\n/**\n * [HTTP response status code](https://tools.ietf.org/html/rfc7231#section-6).\n *\n * @example 200\n */\nexport const ATTR_HTTP_RESPONSE_STATUS_CODE = 'http.response.status_code';\n/**\n * The matched route template for the request. This **MUST** be low-cardinality and include all static path segments, with dynamic path segments represented with placeholders.\n *\n * @example /users/:userID?\n * @example my-controller/my-action/{id?}\n *\n * @note **MUST NOT** be populated when this is not supported by the HTTP server framework as the route attribute should have low-cardinality and the URI path can NOT substitute it.\n * **SHOULD** include the [application root](/docs/http/http-spans.md#http-server-definitions) if there is one.\n *\n * A static path segment is a part of the route template with a fixed, low-cardinality value. This includes literal strings like `/users/` and placeholders that\n * are constrained to a finite, predefined set of values, e.g. `{controller}` or `{action}`.\n *\n * A dynamic path segment is a placeholder for a value that can have high cardinality and is not constrained to a predefined list like static path segments.\n *\n * Instrumentations **SHOULD** use routing information provided by the corresponding web framework. They **SHOULD** pick the most precise source of routing information and **MAY**\n * support custom route formatting. Instrumentations **SHOULD** document the format and the API used to obtain the route string.\n */\nexport const ATTR_HTTP_ROUTE = 'http.route';\n/**\n * Name of the garbage collector action.\n *\n * @example end of minor GC\n * @example end of major GC\n *\n * @note Garbage collector action is generally obtained via [GarbageCollectionNotificationInfo#getGcAction()](https://docs.oracle.com/en/java/javase/11/docs/api/jdk.management/com/sun/management/GarbageCollectionNotificationInfo.html#getGcAction()).\n */\nexport const ATTR_JVM_GC_ACTION = 'jvm.gc.action';\n/**\n * Name of the garbage collector.\n *\n * @example G1 Young Generation\n * @example G1 Old Generation\n *\n * @note Garbage collector name is generally obtained via [GarbageCollectionNotificationInfo#getGcName()](https://docs.oracle.com/en/java/javase/11/docs/api/jdk.management/com/sun/management/GarbageCollectionNotificationInfo.html#getGcName()).\n */\nexport const ATTR_JVM_GC_NAME = 'jvm.gc.name';\n/**\n * Name of the memory pool.\n *\n * @example G1 Old Gen\n * @example G1 Eden space\n * @example G1 Survivor Space\n *\n * @note Pool names are generally obtained via [MemoryPoolMXBean#getName()](https://docs.oracle.com/en/java/javase/11/docs/api/java.management/java/lang/management/MemoryPoolMXBean.html#getName()).\n */\nexport const ATTR_JVM_MEMORY_POOL_NAME = 'jvm.memory.pool.name';\n/**\n * The type of memory.\n *\n * @example heap\n * @example non_heap\n */\nexport const ATTR_JVM_MEMORY_TYPE = 'jvm.memory.type';\n/**\n * Enum value \"heap\" for attribute {@link ATTR_JVM_MEMORY_TYPE}.\n *\n * Heap memory.\n */\nexport const JVM_MEMORY_TYPE_VALUE_HEAP = \"heap\";\n/**\n * Enum value \"non_heap\" for attribute {@link ATTR_JVM_MEMORY_TYPE}.\n *\n * Non-heap memory\n */\nexport const JVM_MEMORY_TYPE_VALUE_NON_HEAP = \"non_heap\";\n/**\n * Whether the thread is daemon or not.\n */\nexport const ATTR_JVM_THREAD_DAEMON = 'jvm.thread.daemon';\n/**\n * State of the thread.\n *\n * @example runnable\n * @example blocked\n */\nexport const ATTR_JVM_THREAD_STATE = 'jvm.thread.state';\n/**\n * Enum value \"blocked\" for attribute {@link ATTR_JVM_THREAD_STATE}.\n *\n * A thread that is blocked waiting for a monitor lock is in this state.\n */\nexport const JVM_THREAD_STATE_VALUE_BLOCKED = \"blocked\";\n/**\n * Enum value \"new\" for attribute {@link ATTR_JVM_THREAD_STATE}.\n *\n * A thread that has not yet started is in this state.\n */\nexport const JVM_THREAD_STATE_VALUE_NEW = \"new\";\n/**\n * Enum value \"runnable\" for attribute {@link ATTR_JVM_THREAD_STATE}.\n *\n * A thread executing in the Java virtual machine is in this state.\n */\nexport const JVM_THREAD_STATE_VALUE_RUNNABLE = \"runnable\";\n/**\n * Enum value \"terminated\" for attribute {@link ATTR_JVM_THREAD_STATE}.\n *\n * A thread that has exited is in this state.\n */\nexport const JVM_THREAD_STATE_VALUE_TERMINATED = \"terminated\";\n/**\n * Enum value \"timed_waiting\" for attribute {@link ATTR_JVM_THREAD_STATE}.\n *\n * A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state.\n */\nexport const JVM_THREAD_STATE_VALUE_TIMED_WAITING = \"timed_waiting\";\n/**\n * Enum value \"waiting\" for attribute {@link ATTR_JVM_THREAD_STATE}.\n *\n * A thread that is waiting indefinitely for another thread to perform a particular action is in this state.\n */\nexport const JVM_THREAD_STATE_VALUE_WAITING = \"waiting\";\n/**\n * The name of the cluster.\n *\n * @example opentelemetry-cluster\n */\nexport const ATTR_K8S_CLUSTER_NAME = 'k8s.cluster.name';\n/**\n * A pseudo-ID for the cluster, set to the UID of the `kube-system` namespace.\n *\n * @example 218fc5a9-a5f1-4b54-aa05-46717d0ab26d\n *\n * @note K8s doesn't have support for obtaining a cluster ID. If this is ever\n * added, we will recommend collecting the `k8s.cluster.uid` through the\n * official APIs. In the meantime, we are able to use the `uid` of the\n * `kube-system` namespace as a proxy for cluster ID. Read on for the\n * rationale.\n *\n * Every object created in a K8s cluster is assigned a distinct UID. The\n * `kube-system` namespace is used by Kubernetes itself and will exist\n * for the lifetime of the cluster. Using the `uid` of the `kube-system`\n * namespace is a reasonable proxy for the K8s ClusterID as it will only\n * change if the cluster is rebuilt. Furthermore, Kubernetes UIDs are\n * UUIDs as standardized by\n * [ISO/IEC 9834-8 and ITU-T X.667](https://www.itu.int/ITU-T/studygroups/com17/oid.html).\n * Which states:\n *\n * > If generated according to one of the mechanisms defined in Rec.\n * > ITU-T X.667 | ISO/IEC 9834-8, a UUID is either guaranteed to be\n * > different from all other UUIDs generated before 3603 A.D., or is\n * > extremely likely to be different (depending on the mechanism chosen).\n *\n * Therefore, UIDs between clusters should be extremely unlikely to\n * conflict.\n */\nexport const ATTR_K8S_CLUSTER_UID = 'k8s.cluster.uid';\n/**\n * The name of the Container from Pod specification, must be unique within a Pod. Container runtime usually uses different globally unique name (`container.name`).\n *\n * @example redis\n */\nexport const ATTR_K8S_CONTAINER_NAME = 'k8s.container.name';\n/**\n * Number of times the container was restarted. This attribute can be used to identify a particular container (running or stopped) within a container spec.\n */\nexport const ATTR_K8S_CONTAINER_RESTART_COUNT = 'k8s.container.restart_count';\n/**\n * The cronjob annotation placed on the CronJob, the `<key>` being the annotation name, the value being the annotation value.\n *\n * @example 4\n * @example\n *\n * @note Examples:\n *\n * - An annotation `retries` with value `4` **SHOULD** be recorded as the\n * `k8s.cronjob.annotation.retries` attribute with value `\"4\"`.\n * - An annotation `data` with empty string value **SHOULD** be recorded as\n * the `k8s.cronjob.annotation.data` attribute with value `\"\"`.\n */\nexport const ATTR_K8S_CRONJOB_ANNOTATION = (key) => `k8s.cronjob.annotation.${key}`;\n/**\n * The label placed on the CronJob, the `<key>` being the label name, the value being the label value.\n *\n * @example weekly\n * @example\n *\n * @note Examples:\n *\n * - A label `type` with value `weekly` **SHOULD** be recorded as the\n * `k8s.cronjob.label.type` attribute with value `\"weekly\"`.\n * - A label `automated` with empty string value **SHOULD** be recorded as\n * the `k8s.cronjob.label.automated` attribute with value `\"\"`.\n */\nexport const ATTR_K8S_CRONJOB_LABEL = (key) => `k8s.cronjob.label.${key}`;\n/**\n * The name of the CronJob.\n *\n * @example opentelemetry\n */\nexport const ATTR_K8S_CRONJOB_NAME = 'k8s.cronjob.name';\n/**\n * The UID of the CronJob.\n *\n * @example 275ecb36-5aa8-4c2a-9c47-d8bb681b9aff\n */\nexport const ATTR_K8S_CRONJOB_UID = 'k8s.cronjob.uid';\n/**\n * The annotation placed on the DaemonSet, the `<key>` being the annotation name, the value being the annotation value, even if the value is empty.\n *\n * @example 1\n * @example\n *\n * @note\n * Examples:\n *\n * - An annotation `replicas` with value `1` **SHOULD** be recorded\n * as the `k8s.daemonset.annotation.replicas` attribute with value `\"1\"`.\n * - An annotation `data` with empty string value **SHOULD** be recorded as\n * the `k8s.daemonset.annotation.data` attribute with value `\"\"`.\n */\nexport const ATTR_K8S_DAEMONSET_ANNOTATION = (key) => `k8s.daemonset.annotation.${key}`;\n/**\n * The label placed on the DaemonSet, the `<key>` being the label name, the value being the label value, even if the value is empty.\n *\n * @example guestbook\n * @example\n *\n * @note\n * Examples:\n *\n * - A label `app` with value `guestbook` **SHOULD** be recorded\n * as the `k8s.daemonset.label.app` attribute with value `\"guestbook\"`.\n * - A label `injected` with empty string value **SHOULD** be recorded as\n * the `k8s.daemonset.label.injected` attribute with value `\"\"`.\n */\nexport const ATTR_K8S_DAEMONSET_LABEL = (key) => `k8s.daemonset.label.${key}`;\n/**\n * The name of the DaemonSet.\n *\n * @example opentelemetry\n */\nexport const ATTR_K8S_DAEMONSET_NAME = 'k8s.daemonset.name';\n/**\n * The UID of the DaemonSet.\n *\n * @example 275ecb36-5aa8-4c2a-9c47-d8bb681b9aff\n */\nexport const ATTR_K8S_DAEMONSET_UID = 'k8s.daemonset.uid';\n/**\n * The annotation placed on the Deployment, the `<key>` being the annotation name, the value being the annotation value, even if the value is empty.\n *\n * @example 1\n * @example\n *\n * @note\n * Examples:\n *\n * - An annotation `replicas` with value `1` **SHOULD** be recorded\n * as the `k8s.deployment.annotation.replicas` attribute with value `\"1\"`.\n * - An annotation `data` with empty string value **SHOULD** be recorded as\n * the `k8s.deployment.annotation.data` attribute with value `\"\"`.\n */\nexport const ATTR_K8S_DEPLOYMENT_ANNOTATION = (key) => `k8s.deployment.annotation.${key}`;\n/**\n * The label placed on the Deployment, the `<key>` being the label name, the value being the label value, even if the value is empty.\n *\n * @example guestbook\n * @example\n *\n * @note\n * Examples:\n *\n * - A label `app` with value `guestbook` **SHOULD** be recorded\n * as the `k8s.deployment.label.app` attribute with value `\"guestbook\"`.\n * - A label `injected` with empty string value **SHOULD** be recorded as\n * the `k8s.deployment.label.injected` attribute with value `\"\"`.\n */\nexport const ATTR_K8S_DEPLOYMENT_LABEL = (key) => `k8s.deployment.label.${key}`;\n/**\n * The name of the Deployment.\n *\n * @example opentelemetry\n */\nexport const ATTR_K8S_DEPLOYMENT_NAME = 'k8s.deployment.name';\n/**\n * The UID of the Deployment.\n *\n * @example 275ecb36-5aa8-4c2a-9c47-d8bb681b9aff\n */\nexport const ATTR_K8S_DEPLOYMENT_UID = 'k8s.deployment.uid';\n/**\n * The annotation placed on the Job, the `<key>` being the annotation name, the value being the annotation value, even if the value is empty.\n *\n * @example 1\n * @example\n *\n * @note\n * Examples:\n *\n * - An annotation `number` with value `1` **SHOULD** be recorded\n * as the `k8s.job.annotation.number` attribute with value `\"1\"`.\n * - An annotation `data` with empty string value **SHOULD** be recorded as\n * the `k8s.job.annotation.data` attribute with value `\"\"`.\n */\nexport const ATTR_K8S_JOB_ANNOTATION = (key) => `k8s.job.annotation.${key}`;\n/**\n * The label placed on the Job, the `<key>` being the label name, the value being the label value, even if the value is empty.\n *\n * @example ci\n * @example\n *\n * @note\n * Examples:\n *\n * - A label `jobtype` with value `ci` **SHOULD** be recorded\n * as the `k8s.job.label.jobtype` attribute with value `\"ci\"`.\n * - A label `automated` with empty string value **SHOULD** be recorded as\n * the `k8s.job.label.automated` attribute with value `\"\"`.\n */\nexport const ATTR_K8S_JOB_LABEL = (key) => `k8s.job.label.${key}`;\n/**\n * The name of the Job.\n *\n * @example opentelemetry\n */\nexport const ATTR_K8S_JOB_NAME = 'k8s.job.name';\n/**\n * The UID of the Job.\n *\n * @example 275ecb36-5aa8-4c2a-9c47-d8bb681b9aff\n */\nexport const ATTR_K8S_JOB_UID = 'k8s.job.uid';\n/**\n * The annotation placed on the Namespace, the `<key>` being the annotation name, the value being the annotation value, even if the value is empty.\n *\n * @example 0\n * @example\n *\n * @note\n * Examples:\n *\n * - An annotation `ttl` with value `0` **SHOULD** be recorded\n * as the `k8s.namespace.annotation.ttl` attribute with value `\"0\"`.\n * - An annotation `data` with empty string value **SHOULD** be recorded as\n * the `k8s.namespace.annotation.data` attribute with value `\"\"`.\n */\nexport const ATTR_K8S_NAMESPACE_ANNOTATION = (key) => `k8s.namespace.annotation.${key}`;\n/**\n * The label placed on the Namespace, the `<key>` being the label name, the value being the label value, even if the value is empty.\n *\n * @example default\n * @example\n *\n * @note\n * Examples:\n *\n * - A label `kubernetes.io/metadata.name` with value `default` **SHOULD** be recorded\n * as the `k8s.namespace.label.kubernetes.io/metadata.name` attribute with value `\"default\"`.\n * - A label `data` with empty string value **SHOULD** be recorded as\n * the `k8s.namespace.label.data` attribute with value `\"\"`.\n */\nexport const ATTR_K8S_NAMESPACE_LABEL = (key) => `k8s.namespace.label.${key}`;\n/**\n * The name of the namespace that the pod is running in.\n *\n * @example default\n */\nexport const ATTR_K8S_NAMESPACE_NAME = 'k8s.namespace.name';\n/**\n * The annotation placed on the Node, the `<key>` being the annotation name, the value being the annotation value, even if the value is empty.\n *\n * @example 0\n * @example\n *\n * @note Examples:\n *\n * - An annotation `node.alpha.kubernetes.io/ttl` with value `0` **SHOULD** be recorded as\n * the `k8s.node.annotation.node.alpha.kubernetes.io/ttl` attribute with value `\"0\"`.\n * - An annotation `data` with empty string value **SHOULD** be recorded as\n * the `k8s.node.annotation.data` attribute with value `\"\"`.\n */\nexport const ATTR_K8S_NODE_ANNOTATION = (key) => `k8s.node.annotation.${key}`;\n/**\n * The label placed on the Node, the `<key>` being the label name, the value being the label value, even if the value is empty.\n *\n * @example arm64\n * @example\n *\n * @note Examples:\n *\n * - A label `kubernetes.io/arch` with value `arm64` **SHOULD** be recorded\n * as the `k8s.node.label.kubernetes.io/arch` attribute with value `\"arm64\"`.\n * - A label `data` with empty string value **SHOULD** be recorded as\n * the `k8s.node.label.data` attribute with value `\"\"`.\n */\nexport const ATTR_K8S_NODE_LABEL = (key) => `k8s.node.label.${key}`;\n/**\n * The name of the Node.\n *\n * @example node-1\n */\nexport const ATTR_K8S_NODE_NAME = 'k8s.node.name';\n/**\n * The UID of the Node.\n *\n * @example 1eb3a0c6-0477-4080-a9cb-0cb7db65c6a2\n */\nexport const ATTR_K8S_NODE_UID = 'k8s.node.uid';\n/**\n * The annotation placed on the Pod, the `<key>` being the annotation name, the value being the annotation value.\n *\n * @example true\n * @example x64\n * @example\n *\n * @note Examples:\n *\n * - An annotation `kubernetes.io/enforce-mountable-secrets` with value `true` **SHOULD** be recorded as\n * the `k8s.pod.annotation.kubernetes.io/enforce-mountable-secrets` attribute with value `\"true\"`.\n * - An annotation `mycompany.io/arch` with value `x64` **SHOULD** be recorded as\n * the `k8s.pod.annotation.mycompany.io/arch` attribute with value `\"x64\"`.\n * - An annotation `data` with empty string value **SHOULD** be recorded as\n * the `k8s.pod.annotation.data` attribute with value `\"\"`.\n */\nexport const ATTR_K8S_POD_ANNOTATION = (key) => `k8s.pod.annotation.${key}`;\n/**\n * Specifies the hostname of the Pod.\n *\n * @example collector-gateway\n *\n * @note The K8s Pod spec has an optional hostname field, which can be used to specify a hostname.\n * Refer to [K8s docs](https://kubernetes.io/docs/concepts/services-networking/dns-pod-service/#pod-hostname-and-subdomain-field)\n * for more information about this field.\n *\n * This attribute aligns with the `hostname` field of the\n * [K8s PodSpec](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.34/#podspec-v1-core).\n */\nexport const ATTR_K8S_POD_HOSTNAME = 'k8s.pod.hostname';\n/**\n * IP address allocated to the Pod.\n *\n * @example 172.18.0.2\n *\n * @note This attribute aligns with the `podIP` field of the\n * [K8s PodStatus](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.34/#podstatus-v1-core).\n */\nexport const ATTR_K8S_POD_IP = 'k8s.pod.ip';\n/**\n * The label placed on the Pod, the `<key>` being the label name, the value being the label value.\n *\n * @example my-app\n * @example x64\n * @example\n *\n * @note Examples:\n *\n * - A label `app` with value `my-app` **SHOULD** be recorded as\n * the `k8s.pod.label.app` attribute with value `\"my-app\"`.\n * - A label `mycompany.io/arch` with value `x64` **SHOULD** be recorded as\n * the `k8s.pod.label.mycompany.io/arch` attribute with value `\"x64\"`.\n * - A label `data` with empty string value **SHOULD** be recorded as\n * the `k8s.pod.label.data` attribute with value `\"\"`.\n */\nexport const ATTR_K8S_POD_LABEL = (key) => `k8s.pod.label.${key}`;\n/**\n * The name of the Pod.\n *\n * @example opentelemetry-pod-autoconf\n */\nexport const ATTR_K8S_POD_NAME = 'k8s.pod.name';\n/**\n * The start timestamp of the Pod.\n *\n * @example 2025-12-04T08:41:03Z\n *\n * @note Date and time at which the object was acknowledged by the Kubelet.\n * This is before the Kubelet pulled the container image(s) for the pod.\n *\n * This attribute aligns with the `startTime` field of the\n * [K8s PodStatus](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.34/#podstatus-v1-core),\n * in ISO 8601 (RFC 3339 compatible) format.\n */\nexport const ATTR_K8S_POD_START_TIME = 'k8s.pod.start_time';\n/**\n * The UID of the Pod.\n *\n * @example 275ecb36-5aa8-4c2a-9c47-d8bb681b9aff\n */\nexport const ATTR_K8S_POD_UID = 'k8s.pod.uid';\n/**\n * The annotation placed on the ReplicaSet, the `<key>` being the annotation name, the value being the annotation value, even if the value is empty.\n *\n * @example 0\n * @example\n *\n * @note\n * Examples:\n *\n * - An annotation `replicas` with value `0` **SHOULD** be recorded\n * as the `k8s.replicaset.annotation.replicas` attribute with value `\"0\"`.\n * - An annotation `data` with empty string value **SHOULD** be recorded as\n * the `k8s.replicaset.annotation.data` attribute with value `\"\"`.\n */\nexport const ATTR_K8S_REPLICASET_ANNOTATION = (key) => `k8s.replicaset.annotation.${key}`;\n/**\n * The label placed on the ReplicaSet, the `<key>` being the label name, the value being the label value, even if the value is empty.\n *\n * @example guestbook\n * @example\n *\n * @note\n * Examples:\n *\n * - A label `app` with value `guestbook` **SHOULD** be recorded\n * as the `k8s.replicaset.label.app` attribute with value `\"guestbook\"`.\n * - A label `injected` with empty string value **SHOULD** be recorded as\n * the `k8s.replicaset.label.injected` attribute with value `\"\"`.\n */\nexport const ATTR_K8S_REPLICASET_LABEL = (key) => `k8s.replicaset.label.${key}`;\n/**\n * The name of the ReplicaSet.\n *\n * @example opentelemetry\n */\nexport const ATTR_K8S_REPLICASET_NAME = 'k8s.replicaset.name';\n/**\n * The UID of the ReplicaSet.\n *\n * @example 275ecb36-5aa8-4c2a-9c47-d8bb681b9aff\n */\nexport const ATTR_K8S_REPLICASET_UID = 'k8s.replicaset.uid';\n/**\n * The annotation placed on the StatefulSet, the `<key>` being the annotation name, the value being the annotation value, even if the value is empty.\n *\n * @example 1\n * @example\n *\n * @note\n * Examples:\n *\n * - An annotation `replicas` with value `1` **SHOULD** be recorded\n * as the `k8s.statefulset.annotation.replicas` attribute with value `\"1\"`.\n * - An annotation `data` with empty string value **SHOULD** be recorded as\n * the `k8s.statefulset.annotation.data` attribute with value `\"\"`.\n */\nexport const ATTR_K8S_STATEFULSET_ANNOTATION = (key) => `k8s.statefulset.annotation.${key}`;\n/**\n * The label placed on the StatefulSet, the `<key>` being the label name, the value being the label value, even if the value is empty.\n *\n * @example guestbook\n * @example\n *\n * @note\n * Examples:\n *\n * - A label `app` with value `guestbook` **SHOULD** be recorded\n * as the `k8s.statefulset.label.app` attribute with value `\"guestbook\"`.\n * - A label `injected` with empty string value **SHOULD** be recorded as\n * the `k8s.statefulset.label.injected` attribute with value `\"\"`.\n */\nexport const ATTR_K8S_STATEFULSET_LABEL = (key) => `k8s.statefulset.label.${key}`;\n/**\n * The name of the StatefulSet.\n *\n * @example opentelemetry\n */\nexport const ATTR_K8S_STATEFULSET_NAME = 'k8s.statefulset.name';\n/**\n * The UID of the StatefulSet.\n *\n * @example 275ecb36-5aa8-4c2a-9c47-d8bb681b9aff\n */\nexport const ATTR_K8S_STATEFULSET_UID = 'k8s.statefulset.uid';\n/**\n * Local address of the network connection - IP address or Unix domain socket name.\n *\n * @example 10.1.2.80\n * @example /tmp/my.sock\n */\nexport const ATTR_NETWORK_LOCAL_ADDRESS = 'network.local.address';\n/**\n * Local port number of the network connection.\n *\n * @example 65123\n */\nexport const ATTR_NETWORK_LOCAL_PORT = 'network.local.port';\n/**\n * Peer address of the network connection - IP address or Unix domain socket name.\n *\n * @example 10.1.2.80\n * @example /tmp/my.sock\n */\nexport const ATTR_NETWORK_PEER_ADDRESS = 'network.peer.address';\n/**\n * Peer port number of the network connection.\n *\n * @example 65123\n */\nexport const ATTR_NETWORK_PEER_PORT = 'network.peer.port';\n/**\n * [OSI application layer](https://wikipedia.org/wiki/Application_layer) or non-OSI equivalent.\n *\n * @example amqp\n * @example http\n * @example mqtt\n *\n * @note The value **SHOULD** be normalized to lowercase.\n */\nexport const ATTR_NETWORK_PROTOCOL_NAME = 'network.protocol.name';\n/**\n * The actual version of the protocol used for network communication.\n *\n * @example 1.1\n * @example 2\n *\n * @note If protocol version is subject to negotiation (for example using [ALPN](https://www.rfc-editor.org/rfc/rfc7301.html)), this attribute **SHOULD** be set to the negotiated version. If the actual protocol version is not known, this attribute **SHOULD NOT** be set.\n */\nexport const ATTR_NETWORK_PROTOCOL_VERSION = 'network.protocol.version';\n/**\n * [OSI transport layer](https://wikipedia.org/wiki/Transport_layer) or [inter-process communication method](https://wikipedia.org/wiki/Inter-process_communication).\n *\n * @example tcp\n * @example udp\n *\n * @note The value **SHOULD** be normalized to lowercase.\n *\n * Consider always setting the transport when setting a port number, since\n * a port number is ambiguous without knowing the transport. For example\n * different processes could be listening on TCP port 12345 and UDP port 12345.\n */\nexport const ATTR_NETWORK_TRANSPORT = 'network.transport';\n/**\n * Enum value \"pipe\" for attribute {@link ATTR_NETWORK_TRANSPORT}.\n *\n * Named or anonymous pipe.\n */\nexport const NETWORK_TRANSPORT_VALUE_PIPE = \"pipe\";\n/**\n * Enum value \"quic\" for attribute {@link ATTR_NETWORK_TRANSPORT}.\n *\n * QUIC\n */\nexport const NETWORK_TRANSPORT_VALUE_QUIC = \"quic\";\n/**\n * Enum value \"tcp\" for attribute {@link ATTR_NETWORK_TRANSPORT}.\n *\n * TCP\n */\nexport const NETWORK_TRANSPORT_VALUE_TCP = \"tcp\";\n/**\n * Enum value \"udp\" for attribute {@link ATTR_NETWORK_TRANSPORT}.\n *\n * UDP\n */\nexport const NETWORK_TRANSPORT_VALUE_UDP = \"udp\";\n/**\n * Enum value \"unix\" for attribute {@link ATTR_NETWORK_TRANSPORT}.\n *\n * Unix domain socket\n */\nexport const NETWORK_TRANSPORT_VALUE_UNIX = \"unix\";\n/**\n * [OSI network layer](https://wikipedia.org/wiki/Network_layer) or non-OSI equivalent.\n *\n * @example ipv4\n * @example ipv6\n *\n * @note The value **SHOULD** be normalized to lowercase.\n */\nexport const ATTR_NETWORK_TYPE = 'network.type';\n/**\n * Enum value \"ipv4\" for attribute {@link ATTR_NETWORK_TYPE}.\n *\n * IPv4\n */\nexport const NETWORK_TYPE_VALUE_IPV4 = \"ipv4\";\n/**\n * Enum value \"ipv6\" for attribute {@link ATTR_NETWORK_TYPE}.\n *\n * IPv6\n */\nexport const NETWORK_TYPE_VALUE_IPV6 = \"ipv6\";\n/**\n * Identifies the class / type of event.\n *\n * @example browser.mouse.click\n * @example device.app.lifecycle\n *\n * @note This attribute **SHOULD** be used by non-OTLP exporters when destination does not support `EventName` or equivalent field. This attribute **MAY** be used by applications using existing logging libraries so that it can be used to set the `EventName` field by Collector or SDK components.\n */\nexport const ATTR_OTEL_EVENT_NAME = 'otel.event.name';\n/**\n * The name of the instrumentation scope - (`InstrumentationScope.Name` in OTLP).\n *\n * @example io.opentelemetry.contrib.mongodb\n */\nexport const ATTR_OTEL_SCOPE_NAME = 'otel.scope.name';\n/**\n * The version of the instrumentation scope - (`InstrumentationScope.Version` in OTLP).\n *\n * @example 1.0.0\n */\nexport const ATTR_OTEL_SCOPE_VERSION = 'otel.scope.version';\n/**\n * Name of the code, either \"OK\" or \"ERROR\". **MUST NOT** be set if the status code is UNSET.\n */\nexport const ATTR_OTEL_STATUS_CODE = 'otel.status_code';\n/**\n * Enum value \"ERROR\" for attribute {@link ATTR_OTEL_STATUS_CODE}.\n *\n * The operation contains an error.\n */\nexport const OTEL_STATUS_CODE_VALUE_ERROR = \"ERROR\";\n/**\n * Enum value \"OK\" for attribute {@link ATTR_OTEL_STATUS_CODE}.\n *\n * The operation has been validated by an Application developer or Operator to have completed successfully.\n */\nexport const OTEL_STATUS_CODE_VALUE_OK = \"OK\";\n/**\n * Description of the Status if it has a value, otherwise not set.\n *\n * @example resource not found\n */\nexport const ATTR_OTEL_STATUS_DESCRIPTION = 'otel.status_description';\n/**\n * Server domain name if available without reverse DNS lookup; otherwise, IP address or Unix domain socket name.\n *\n * @example example.com\n * @example 10.1.2.80\n * @example /tmp/my.sock\n *\n * @note When observed from the client side, and when communicating through an intermediary, `server.address` **SHOULD** represent the server address behind any intermediaries, for example proxies, if it's available.\n */\nexport const ATTR_SERVER_ADDRESS = 'server.address';\n/**\n * Server port number.\n *\n * @example 80\n * @example 8080\n * @example 443\n *\n * @note When observed from the client side, and when communicating through an intermediary, `server.port` **SHOULD** represent the server port behind any intermediaries, for example proxies, if it's available.\n */\nexport const ATTR_SERVER_PORT = 'server.port';\n/**\n * The string ID of the service instance.\n *\n * @example 627cc493-f310-47de-96bd-71410b7dec09\n *\n * @note **MUST** be unique for each instance of the same `service.namespace,service.name` pair (in other words\n * `service.namespace,service.name,service.instance.id` triplet **MUST** be globally unique). The ID helps to\n * distinguish instances of the same service that exist at the same time (e.g. instances of a horizontally scaled\n * service).\n *\n * Implementations, such as SDKs, are recommended to generate a random Version 1 or Version 4 [RFC\n * 4122](https://www.ietf.org/rfc/rfc4122.txt) UUID, but are free to use an inherent unique ID as the source of\n * this value if stability is desirable. In that case, the ID **SHOULD** be used as source of a UUID Version 5 and\n * **SHOULD** use the following UUID as the namespace: `4d63009a-8d0f-11ee-aad7-4c796ed8e320`.\n *\n * UUIDs are typically recommended, as only an opaque value for the purposes of identifying a service instance is\n * needed. Similar to what can be seen in the man page for the\n * [`/etc/machine-id`](https://www.freedesktop.org/software/systemd/man/latest/machine-id.html) file, the underlying\n * data, such as pod name and namespace should be treated as confidential, being the user's choice to expose it\n * or not via another resource attribute.\n *\n * For applications running behind an application server (like unicorn), we do not recommend using one identifier\n * for all processes participating in the application. Instead, it's recommended each division (e.g. a worker\n * thread in unicorn) to have its own instance.id.\n *\n * It's not recommended for a Collector to set `service.instance.id` if it can't unambiguously determine the\n * service instance that is generating that telemetry. For instance, creating an UUID based on `pod.name` will\n * likely be wrong, as the Collector might not know from which container within that pod the telemetry originated.\n * However, Collectors can set the `service.instance.id` if they can unambiguously determine the service instance\n * for that telemetry. This is typically the case for scraping receivers, as they know the target address and\n * port.\n */\nexport const ATTR_SERVICE_INSTANCE_ID = 'service.instance.id';\n/**\n * Logical name of the service.\n *\n * @example shoppingcart\n *\n * @note **MUST** be the same for all instances of horizontally scaled services. If the value was not specified, SDKs **MUST** fallback to `unknown_service:` concatenated with the process executable name, e.g. `unknown_service:bash`. If the process executable name is not available, the value **MUST** be set to `unknown_service`.\n * The process executable name is the name of the process executable, the same value as described by the [`process.executable.name`](process.md) resource attribute.\n */\nexport const ATTR_SERVICE_NAME = 'service.name';\n/**\n * A namespace for `service.name`.\n *\n * @example Shop\n *\n * @note A string value having a meaning that helps to distinguish a group of services, for example the team name that owns a group of services. `service.name` is expected to be unique within the same namespace. If `service.namespace` is not specified in the Resource then `service.name` is expected to be unique for all services that have no explicit namespace defined (so the empty/unspecified namespace is simply one more valid namespace). Zero-length namespace string is assumed equal to unspecified namespace.\n */\nexport const ATTR_SERVICE_NAMESPACE = 'service.namespace';\n/**\n * The version string of the service component. The format is not defined by these conventions.\n *\n * @example 2.0.0\n * @example a01dbef8a\n */\nexport const ATTR_SERVICE_VERSION = 'service.version';\n/**\n * SignalR HTTP connection closure status.\n *\n * @example app_shutdown\n * @example timeout\n */\nexport const ATTR_SIGNALR_CONNECTION_STATUS = 'signalr.connection.status';\n/**\n * Enum value \"app_shutdown\" for attribute {@link ATTR_SIGNALR_CONNECTION_STATUS}.\n *\n * The connection was closed because the app is shutting down.\n */\nexport const SIGNALR_CONNECTION_STATUS_VALUE_APP_SHUTDOWN = \"app_shutdown\";\n/**\n * Enum value \"normal_closure\" for attribute {@link ATTR_SIGNALR_CONNECTION_STATUS}.\n *\n * The connection was closed normally.\n */\nexport const SIGNALR_CONNECTION_STATUS_VALUE_NORMAL_CLOSURE = \"normal_closure\";\n/**\n * Enum value \"timeout\" for attribute {@link ATTR_SIGNALR_CONNECTION_STATUS}.\n *\n * The connection was closed due to a timeout.\n */\nexport const SIGNALR_CONNECTION_STATUS_VALUE_TIMEOUT = \"timeout\";\n/**\n * [SignalR transport type](https://github.com/dotnet/aspnetcore/blob/main/src/SignalR/docs/specs/TransportProtocols.md)\n *\n * @example web_sockets\n * @example long_polling\n */\nexport const ATTR_SIGNALR_TRANSPORT = 'signalr.transport';\n/**\n * Enum value \"long_polling\" for attribute {@link ATTR_SIGNALR_TRANSPORT}.\n *\n * LongPolling protocol\n */\nexport const SIGNALR_TRANSPORT_VALUE_LONG_POLLING = \"long_polling\";\n/**\n * Enum value \"server_sent_events\" for attribute {@link ATTR_SIGNALR_TRANSPORT}.\n *\n * ServerSentEvents protocol\n */\nexport const SIGNALR_TRANSPORT_VALUE_SERVER_SENT_EVENTS = \"server_sent_events\";\n/**\n * Enum value \"web_sockets\" for attribute {@link ATTR_SIGNALR_TRANSPORT}.\n *\n * WebSockets protocol\n */\nexport const SIGNALR_TRANSPORT_VALUE_WEB_SOCKETS = \"web_sockets\";\n/**\n * The name of the auto instrumentation agent or distribution, if used.\n *\n * @example parts-unlimited-java\n *\n * @note Official auto instrumentation agents and distributions **SHOULD** set the `telemetry.distro.name` attribute to\n * a string starting with `opentelemetry-`, e.g. `opentelemetry-java-instrumentation`.\n */\nexport const ATTR_TELEMETRY_DISTRO_NAME = 'telemetry.distro.name';\n/**\n * The version string of the auto instrumentation agent or distribution, if used.\n *\n * @example 1.2.3\n */\nexport const ATTR_TELEMETRY_DISTRO_VERSION = 'telemetry.distro.version';\n/**\n * The language of the telemetry SDK.\n */\nexport const ATTR_TELEMETRY_SDK_LANGUAGE = 'telemetry.sdk.language';\n/**\n * Enum value \"cpp\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_CPP = \"cpp\";\n/**\n * Enum value \"dotnet\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_DOTNET = \"dotnet\";\n/**\n * Enum value \"erlang\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_ERLANG = \"erlang\";\n/**\n * Enum value \"go\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_GO = \"go\";\n/**\n * Enum value \"java\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_JAVA = \"java\";\n/**\n * Enum value \"kotlin\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_KOTLIN = \"kotlin\";\n/**\n * Enum value \"nodejs\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS = \"nodejs\";\n/**\n * Enum value \"php\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_PHP = \"php\";\n/**\n * Enum value \"python\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_PYTHON = \"python\";\n/**\n * Enum value \"ruby\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_RUBY = \"ruby\";\n/**\n * Enum value \"rust\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_RUST = \"rust\";\n/**\n * Enum value \"swift\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_SWIFT = \"swift\";\n/**\n * Enum value \"webjs\" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}.\n */\nexport const TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS = \"webjs\";\n/**\n * The name of the telemetry SDK as defined above.\n *\n * @example opentelemetry\n *\n * @note The OpenTelemetry SDK **MUST** set the `telemetry.sdk.name` attribute to `opentelemetry`.\n * If another SDK, like a fork or a vendor-provided implementation, is used, this SDK **MUST** set the\n * `telemetry.sdk.name` attribute to the fully-qualified class or module name of this SDK's main entry point\n * or another suitable identifier depending on the language.\n * The identifier `opentelemetry` is reserved and **MUST NOT** be used in this case.\n * All custom identifiers **SHOULD** be stable across different versions of an implementation.\n */\nexport const ATTR_TELEMETRY_SDK_NAME = 'telemetry.sdk.name';\n/**\n * The version string of the telemetry SDK.\n *\n * @example 1.2.3\n */\nexport const ATTR_TELEMETRY_SDK_VERSION = 'telemetry.sdk.version';\n/**\n * The [URI fragment](https://www.rfc-editor.org/rfc/rfc3986#section-3.5) component\n *\n * @example SemConv\n */\nexport const ATTR_URL_FRAGMENT = 'url.fragment';\n/**\n * Absolute URL describing a network resource according to [RFC3986](https://www.rfc-editor.org/rfc/rfc3986)\n *\n * @example https://www.foo.bar/search?q=OpenTelemetry#SemConv\n * @example //localhost\n *\n * @note For network calls, URL usually has `scheme://host[:port][path][?query][#fragment]` format, where the fragment\n * is not transmitted over HTTP, but if it is known, it **SHOULD** be included nevertheless.\n *\n * `url.full` **MUST NOT** contain credentials passed via URL in form of `https://username:password@www.example.com/`.\n * In such case username and password **SHOULD** be redacted and attribute's value **SHOULD** be `https://REDACTED:REDACTED@www.example.com/`.\n *\n * `url.full` **SHOULD** capture the absolute URL when it is available (or can be reconstructed).\n *\n * Sensitive content provided in `url.full` **SHOULD** be scrubbed when instrumentations can identify it.\n *\n *\n * Query string values for the following keys **SHOULD** be redacted by default and replaced by the\n * value `REDACTED`:\n *\n * - [`X-Amz-Signature`](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv-authentication-methods.html)\n * - [`X-Amz-Credential`](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv-authentication-methods.html)\n * - [`X-Amz-Security-Token`](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv-authentication-methods.html)\n * - [`sig`](https://learn.microsoft.com/azure/storage/common/storage-sas-overview#sas-token)\n * - [`X-Goog-Signature`](https://cloud.google.com/storage/docs/access-control/signed-urls)\n *\n * This list is subject to change over time.\n *\n * Matching of query parameter keys against the sensitive list **SHOULD** be case-sensitive.\n *\n *\n * Instrumentation **MAY** provide a way to override this list via declarative configuration.\n * If so, it **SHOULD** use the `sensitive_query_parameters` property\n * (an array of case-sensitive strings with minimum items 0) under\n * `.instrumentation/development.general.sanitization.url`.\n * This list is a full override of the default sensitive query parameter keys,\n * it is not a list of keys in addition to the defaults.\n *\n * When a query string value is redacted, the query string key **SHOULD** still be preserved, e.g.\n * `https://www.example.com/path?color=blue&sig=REDACTED`.\n */\nexport const ATTR_URL_FULL = 'url.full';\n/**\n * The [URI path](https://www.rfc-editor.org/rfc/rfc3986#section-3.3) component\n *\n * @example /search\n *\n * @note Sensitive content provided in `url.path` **SHOULD** be scrubbed when instrumentations can identify it.\n */\nexport const ATTR_URL_PATH = 'url.path';\n/**\n * The [URI query](https://www.rfc-editor.org/rfc/rfc3986#section-3.4) component\n *\n * @example q=OpenTelemetry\n *\n * @note Sensitive content provided in `url.query` **SHOULD** be scrubbed when instrumentations can identify it.\n *\n *\n * Query string values for the following keys **SHOULD** be redacted by default and replaced by the value `REDACTED`:\n *\n * - [`X-Amz-Signature`](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv-authentication-methods.html)\n * - [`X-Amz-Credential`](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv-authentication-methods.html)\n * - [`X-Amz-Security-Token`](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv-authentication-methods.html)\n * - [`sig`](https://learn.microsoft.com/azure/storage/common/storage-sas-overview#sas-token)\n * - [`X-Goog-Signature`](https://cloud.google.com/storage/docs/access-control/signed-urls)\n *\n * This list is subject to change over time.\n *\n * Matching of query parameter keys against the sensitive list **SHOULD** be case-sensitive.\n *\n * Instrumentation **MAY** provide a way to override this list via declarative configuration.\n * If so, it **SHOULD** use the `sensitive_query_parameters` property\n * (an array of case-sensitive strings with minimum items 0) under\n * `.instrumentation/development.general.sanitization.url`.\n * This list is a full override of the default sensitive query parameter keys,\n * it is not a list of keys in addition to the defaults.\n *\n * When a query string value is redacted, the query string key **SHOULD** still be preserved, e.g.\n * `q=OpenTelemetry&sig=REDACTED`.\n */\nexport const ATTR_URL_QUERY = 'url.query';\n/**\n * The [URI scheme](https://www.rfc-editor.org/rfc/rfc3986#section-3.1) component identifying the used protocol.\n *\n * @example https\n * @example ftp\n * @example telnet\n */\nexport const ATTR_URL_SCHEME = 'url.scheme';\n/**\n * Value of the [HTTP User-Agent](https://www.rfc-editor.org/rfc/rfc9110.html#field.user-agent) header sent by the client.\n *\n * @example CERN-LineMode/2.15 libwww/2.17b3\n * @example Mozilla/5.0 (iPhone; CPU iPhone OS 14_7_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.2 Mobile/15E148 Safari/604.1\n * @example YourApp/1.0.0 grpc-java-okhttp/1.27.2\n */\nexport const ATTR_USER_AGENT_ORIGINAL = 'user_agent.original';\n//# sourceMappingURL=stable_attributes.js.map","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n/*\n * This file contains a copy of unstable semantic convention definitions\n * used by this package.\n * @see https://github.com/open-telemetry/opentelemetry-js/tree/main/semantic-conventions#unstable-semconv\n */\n/**\n * The name of the runtime of this process.\n *\n * @example OpenJDK Runtime Environment\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_PROCESS_RUNTIME_NAME = 'process.runtime.name';\n//# sourceMappingURL=semconv.js.map","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { VERSION } from '../../version';\nimport { ATTR_TELEMETRY_SDK_NAME, ATTR_TELEMETRY_SDK_LANGUAGE, TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS, ATTR_TELEMETRY_SDK_VERSION, } from '@opentelemetry/semantic-conventions';\nimport { ATTR_PROCESS_RUNTIME_NAME } from '../../semconv';\n/** Constants describing the SDK in use */\nexport const SDK_INFO = {\n [ATTR_TELEMETRY_SDK_NAME]: 'opentelemetry',\n [ATTR_PROCESS_RUNTIME_NAME]: 'node',\n [ATTR_TELEMETRY_SDK_LANGUAGE]: TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS,\n [ATTR_TELEMETRY_SDK_VERSION]: VERSION,\n};\n//# sourceMappingURL=sdk-info.js.map","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nexport { getStringFromEnv, getBooleanFromEnv, getNumberFromEnv, getStringListFromEnv, } from './environment';\nexport { _globalThis } from '../../common/globalThis';\nexport { SDK_INFO } from './sdk-info';\n/**\n * @deprecated Use performance directly.\n */\nexport const otperformance = performance;\n//# sourceMappingURL=index.js.map","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { otperformance as performance } from '../platform';\nconst NANOSECOND_DIGITS = 9;\nconst NANOSECOND_DIGITS_IN_MILLIS = 6;\nconst MILLISECONDS_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS_IN_MILLIS);\nconst SECOND_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS);\n/**\n * Converts a number of milliseconds from epoch to HrTime([seconds, remainder in nanoseconds]).\n * @param epochMillis\n */\nexport function millisToHrTime(epochMillis) {\n const epochSeconds = epochMillis / 1000;\n // Decimals only.\n const seconds = Math.trunc(epochSeconds);\n // Round sub-nanosecond accuracy to nanosecond.\n const nanos = Math.round((epochMillis % 1000) * MILLISECONDS_TO_NANOSECONDS);\n return [seconds, nanos];\n}\n/**\n * @deprecated Use `performance.timeOrigin` directly.\n */\nexport function getTimeOrigin() {\n return performance.timeOrigin;\n}\n/**\n * Returns an hrtime calculated via performance component.\n * @param performanceNow\n */\nexport function hrTime(performanceNow) {\n const timeOrigin = millisToHrTime(performance.timeOrigin);\n const now = millisToHrTime(typeof performanceNow === 'number' ? performanceNow : performance.now());\n return addHrTimes(timeOrigin, now);\n}\n/**\n *\n * Converts a TimeInput to an HrTime, defaults to _hrtime().\n * @param time\n */\nexport function timeInputToHrTime(time) {\n // process.hrtime\n if (isTimeInputHrTime(time)) {\n return time;\n }\n else if (typeof time === 'number') {\n // Must be a performance.now() if it's smaller than process start time.\n if (time < performance.timeOrigin) {\n return hrTime(time);\n }\n else {\n // epoch milliseconds or performance.timeOrigin\n return millisToHrTime(time);\n }\n }\n else if (time instanceof Date) {\n return millisToHrTime(time.getTime());\n }\n else {\n throw TypeError('Invalid input type');\n }\n}\n/**\n * Returns a duration of two hrTime.\n * @param startTime\n * @param endTime\n */\nexport function hrTimeDuration(startTime, endTime) {\n let seconds = endTime[0] - startTime[0];\n let nanos = endTime[1] - startTime[1];\n // overflow\n if (nanos < 0) {\n seconds -= 1;\n // negate\n nanos += SECOND_TO_NANOSECONDS;\n }\n return [seconds, nanos];\n}\n/**\n * Convert hrTime to timestamp, for example \"2019-05-14T17:00:00.000123456Z\"\n * @param time\n */\nexport function hrTimeToTimeStamp(time) {\n const precision = NANOSECOND_DIGITS;\n const tmp = `${'0'.repeat(precision)}${time[1]}Z`;\n const nanoString = tmp.substring(tmp.length - precision - 1);\n const date = new Date(time[0] * 1000).toISOString();\n return date.replace('000Z', nanoString);\n}\n/**\n * Convert hrTime to nanoseconds.\n * @param time\n */\nexport function hrTimeToNanoseconds(time) {\n return time[0] * SECOND_TO_NANOSECONDS + time[1];\n}\n/**\n * Convert hrTime to microseconds.\n * @param time\n */\nexport function hrTimeToMicroseconds(time) {\n return time[0] * 1e6 + time[1] / 1e3;\n}\n/**\n * Convert hrTime to milliseconds.\n * @param time\n */\nexport function hrTimeToMilliseconds(time) {\n return time[0] * 1e3 + time[1] / 1e6;\n}\n/**\n * Convert hrTime to seconds.\n * @param time\n */\nexport function hrTimeToSeconds(time) {\n return time[0] + time[1] / SECOND_TO_NANOSECONDS;\n}\n/**\n * check if time is HrTime\n * @param value\n */\nexport function isTimeInputHrTime(value) {\n return (Array.isArray(value) &&\n value.length === 2 &&\n typeof value[0] === 'number' &&\n typeof value[1] === 'number');\n}\n/**\n * check if input value is a correct types.TimeInput\n * @param value\n */\nexport function isTimeInput(value) {\n return (isTimeInputHrTime(value) ||\n typeof value === 'number' ||\n value instanceof Date);\n}\n/**\n * Given 2 HrTime formatted times, return their sum as an HrTime.\n */\nexport function addHrTimes(time1, time2) {\n const out = [time1[0] + time2[0], time1[1] + time2[1]];\n // Nanoseconds\n if (out[1] >= SECOND_TO_NANOSECONDS) {\n out[1] -= SECOND_TO_NANOSECONDS;\n out[0] += 1;\n }\n return out;\n}\n//# sourceMappingURL=time.js.map","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nexport var ExportResultCode;\n(function (ExportResultCode) {\n ExportResultCode[ExportResultCode[\"SUCCESS\"] = 0] = \"SUCCESS\";\n ExportResultCode[ExportResultCode[\"FAILED\"] = 1] = \"FAILED\";\n})(ExportResultCode || (ExportResultCode = {}));\n//# sourceMappingURL=ExportResult.js.map","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/**\n * based on lodash in order to support esm builds without esModuleInterop.\n * lodash is using MIT License.\n **/\nconst objectTag = '[object Object]';\nconst nullTag = '[object Null]';\nconst undefinedTag = '[object Undefined]';\nconst funcProto = Function.prototype;\nconst funcToString = funcProto.toString;\nconst objectCtorString = funcToString.call(Object);\nconst getPrototypeOf = Object.getPrototypeOf;\nconst objectProto = Object.prototype;\nconst hasOwnProperty = objectProto.hasOwnProperty;\nconst symToStringTag = Symbol ? Symbol.toStringTag : undefined;\nconst nativeObjectToString = objectProto.toString;\n/**\n * Checks if `value` is a plain object, that is, an object created by the\n * `Object` constructor or one with a `[[Prototype]]` of `null`.\n *\n * @static\n * @memberOf _\n * @since 0.8.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * }\n *\n * _.isPlainObject(new Foo);\n * // => false\n *\n * _.isPlainObject([1, 2, 3]);\n * // => false\n *\n * _.isPlainObject({ 'x': 0, 'y': 0 });\n * // => true\n *\n * _.isPlainObject(Object.create(null));\n * // => true\n */\nexport function isPlainObject(value) {\n if (!isObjectLike(value) || baseGetTag(value) !== objectTag) {\n return false;\n }\n const proto = getPrototypeOf(value);\n if (proto === null) {\n return true;\n }\n const Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;\n return (typeof Ctor == 'function' &&\n Ctor instanceof Ctor &&\n funcToString.call(Ctor) === objectCtorString);\n}\n/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return value != null && typeof value == 'object';\n}\n/**\n * The base implementation of `getTag` without fallbacks for buggy environments.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nfunction baseGetTag(value) {\n if (value == null) {\n return value === undefined ? undefinedTag : nullTag;\n }\n return symToStringTag && symToStringTag in Object(value)\n ? getRawTag(value)\n : objectToString(value);\n}\n/**\n * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the raw `toStringTag`.\n */\nfunction getRawTag(value) {\n const isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag];\n let unmasked = false;\n try {\n value[symToStringTag] = undefined;\n unmasked = true;\n }\n catch {\n // silence\n }\n const result = nativeObjectToString.call(value);\n if (unmasked) {\n if (isOwn) {\n value[symToStringTag] = tag;\n }\n else {\n delete value[symToStringTag];\n }\n }\n return result;\n}\n/**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\nfunction objectToString(value) {\n return nativeObjectToString.call(value);\n}\n//# sourceMappingURL=lodash.merge.js.map","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { isPlainObject } from './lodash.merge';\nconst MAX_LEVEL = 20;\n/**\n * Merges objects together\n * @param args - objects / values to be merged\n */\nexport function merge(...args) {\n let result = args.shift();\n const objects = new WeakMap();\n while (args.length > 0) {\n result = mergeTwoObjects(result, args.shift(), 0, objects);\n }\n return result;\n}\nfunction takeValue(value) {\n if (isArray(value)) {\n return value.slice();\n }\n return value;\n}\n/**\n * Merges two objects\n * @param one - first object\n * @param two - second object\n * @param level - current deep level\n * @param objects - objects holder that has been already referenced - to prevent\n * cyclic dependency\n */\nfunction mergeTwoObjects(one, two, level = 0, objects) {\n let result;\n if (level > MAX_LEVEL) {\n return undefined;\n }\n level++;\n if (isPrimitive(one) || isPrimitive(two) || isFunction(two)) {\n result = takeValue(two);\n }\n else if (isArray(one)) {\n result = one.slice();\n if (isArray(two)) {\n for (let i = 0, j = two.length; i < j; i++) {\n result.push(takeValue(two[i]));\n }\n }\n else if (isObject(two)) {\n const keys = Object.keys(two);\n for (let i = 0, j = keys.length; i < j; i++) {\n const key = keys[i];\n if (key === '__proto__' ||\n key === 'constructor' ||\n key === 'prototype') {\n continue;\n }\n result[key] = takeValue(two[key]);\n }\n }\n }\n else if (isObject(one)) {\n if (isObject(two)) {\n if (!shouldMerge(one, two)) {\n return two;\n }\n result = Object.assign({}, one);\n const keys = Object.keys(two);\n for (let i = 0, j = keys.length; i < j; i++) {\n const key = keys[i];\n if (key === '__proto__' ||\n key === 'constructor' ||\n key === 'prototype') {\n continue;\n }\n const twoValue = two[key];\n if (isPrimitive(twoValue)) {\n if (typeof twoValue === 'undefined') {\n delete result[key];\n }\n else {\n // result[key] = takeValue(twoValue);\n result[key] = twoValue;\n }\n }\n else {\n const obj1 = result[key];\n const obj2 = twoValue;\n if (wasObjectReferenced(one, key, objects) ||\n wasObjectReferenced(two, key, objects)) {\n delete result[key];\n }\n else {\n if (isObject(obj1) && isObject(obj2)) {\n const arr1 = objects.get(obj1) || [];\n const arr2 = objects.get(obj2) || [];\n arr1.push({ obj: one, key });\n arr2.push({ obj: two, key });\n objects.set(obj1, arr1);\n objects.set(obj2, arr2);\n }\n result[key] = mergeTwoObjects(result[key], twoValue, level, objects);\n }\n }\n }\n }\n else {\n result = two;\n }\n }\n return result;\n}\n/**\n * Function to check if object has been already reference\n * @param obj\n * @param key\n * @param objects\n */\nfunction wasObjectReferenced(obj, key, objects) {\n const arr = objects.get(obj[key]) || [];\n for (let i = 0, j = arr.length; i < j; i++) {\n const info = arr[i];\n if (info.key === key && info.obj === obj) {\n return true;\n }\n }\n return false;\n}\nfunction isArray(value) {\n return Array.isArray(value);\n}\nfunction isFunction(value) {\n return typeof value === 'function';\n}\nfunction isObject(value) {\n return (!isPrimitive(value) &&\n !isArray(value) &&\n !isFunction(value) &&\n typeof value === 'object');\n}\nfunction isPrimitive(value) {\n return (typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean' ||\n typeof value === 'undefined' ||\n value instanceof Date ||\n value instanceof RegExp ||\n value === null);\n}\nfunction shouldMerge(one, two) {\n if (!isPlainObject(one) || !isPlainObject(two)) {\n return false;\n }\n return true;\n}\n//# sourceMappingURL=merge.js.map","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { diag } from '@opentelemetry/api';\nfunction isPartialSuccessResponse(response) {\n return Object.prototype.hasOwnProperty.call(response, 'partialSuccess');\n}\n/**\n * Default response handler that logs a partial success to the console.\n */\nexport function createLoggingPartialSuccessResponseHandler() {\n return {\n handleResponse(response) {\n // Partial success MUST never be an empty object according the specification\n // see https://opentelemetry.io/docs/specs/otlp/#partial-success\n if (response == null ||\n !isPartialSuccessResponse(response) ||\n response.partialSuccess == null ||\n Object.keys(response.partialSuccess).length === 0) {\n return;\n }\n diag.warn('Received Partial Success response:', JSON.stringify(response.partialSuccess));\n },\n };\n}\n//# sourceMappingURL=logging-response-handler.js.map","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { ExportResultCode } from '@opentelemetry/core';\nimport { OTLPExporterError } from './types';\nimport { createLoggingPartialSuccessResponseHandler } from './logging-response-handler';\nimport { diag } from '@opentelemetry/api';\nclass OTLPExportDelegate {\n _diagLogger;\n _transport;\n _serializer;\n _responseHandler;\n _promiseQueue;\n _timeout;\n constructor(transport, serializer, responseHandler, promiseQueue, timeout) {\n this._transport = transport;\n this._serializer = serializer;\n this._responseHandler = responseHandler;\n this._promiseQueue = promiseQueue;\n this._timeout = timeout;\n this._diagLogger = diag.createComponentLogger({\n namespace: 'OTLPExportDelegate',\n });\n }\n export(internalRepresentation, resultCallback) {\n this._diagLogger.debug('items to be sent', internalRepresentation);\n // don't do any work if too many exports are in progress.\n if (this._promiseQueue.hasReachedLimit()) {\n resultCallback({\n code: ExportResultCode.FAILED,\n error: new Error('Concurrent export limit reached'),\n });\n return;\n }\n const serializedRequest = this._serializer.serializeRequest(internalRepresentation);\n if (serializedRequest == null) {\n resultCallback({\n code: ExportResultCode.FAILED,\n error: new Error('Nothing to send'),\n });\n return;\n }\n this._promiseQueue.pushPromise(this._transport.send(serializedRequest, this._timeout).then(response => {\n if (response.status === 'success') {\n if (response.data != null) {\n try {\n this._responseHandler.handleResponse(this._serializer.deserializeResponse(response.data));\n }\n catch (e) {\n this._diagLogger.warn('Export succeeded but could not deserialize response - is the response specification compliant?', e, response.data);\n }\n }\n // No matter the response, we can consider the export still successful.\n resultCallback({\n code: ExportResultCode.SUCCESS,\n });\n return;\n }\n else if (response.status === 'failure' && response.error) {\n resultCallback({\n code: ExportResultCode.FAILED,\n error: response.error,\n });\n return;\n }\n else if (response.status === 'retryable') {\n resultCallback({\n code: ExportResultCode.FAILED,\n error: response.error ??\n new OTLPExporterError('Export failed with retryable status'),\n });\n }\n else {\n resultCallback({\n code: ExportResultCode.FAILED,\n error: new OTLPExporterError('Export failed with unknown error'),\n });\n }\n }, reason => resultCallback({\n code: ExportResultCode.FAILED,\n error: reason,\n })));\n }\n forceFlush() {\n return this._promiseQueue.awaitAll();\n }\n async shutdown() {\n this._diagLogger.debug('shutdown started');\n await this.forceFlush();\n this._transport.shutdown();\n }\n}\n/**\n * Creates a generic delegate for OTLP exports which only contains parts of the OTLP export that are shared across all\n * signals.\n */\nexport function createOtlpExportDelegate(components, settings) {\n return new OTLPExportDelegate(components.transport, components.serializer, createLoggingPartialSuccessResponseHandler(), components.promiseHandler, settings.timeout);\n}\n//# sourceMappingURL=otlp-export-delegate.js.map","import { getHttpConfigurationDefaults, mergeOtlpHttpConfigurationWithDefaults, } from './otlp-http-configuration';\nexport function httpAgentFactoryFromOptions(options) {\n return async (protocol) => {\n const isInsecure = protocol === 'http:';\n const module = isInsecure ? import('http') : import('https');\n const { Agent } = await module;\n if (isInsecure) {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars -- these props should not be used in agent options\n const { ca, cert, key, ...insecureOptions } = options;\n return new Agent(insecureOptions);\n }\n return new Agent(options);\n };\n}\n/**\n * @param userProvidedConfiguration Configuration options provided by the user in code.\n * @param fallbackConfiguration Fallback to use when the {@link userProvidedConfiguration} does not specify an option.\n * @param defaultConfiguration The defaults as defined by the exporter specification\n */\nexport function mergeOtlpNodeHttpConfigurationWithDefaults(userProvidedConfiguration, fallbackConfiguration, defaultConfiguration) {\n return {\n ...mergeOtlpHttpConfigurationWithDefaults(userProvidedConfiguration, fallbackConfiguration, defaultConfiguration),\n agentFactory: userProvidedConfiguration.agentFactory ??\n fallbackConfiguration.agentFactory ??\n defaultConfiguration.agentFactory,\n userAgent: userProvidedConfiguration.userAgent,\n };\n}\nexport function getNodeHttpConfigurationDefaults(requiredHeaders, signalResourcePath) {\n return {\n ...getHttpConfigurationDefaults(requiredHeaders, signalResourcePath),\n agentFactory: httpAgentFactoryFromOptions({ keepAlive: true }),\n };\n}\n//# sourceMappingURL=otlp-node-http-configuration.js.map","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nexport function isExportHTTPErrorRetryable(statusCode) {\n return (statusCode === 429 ||\n statusCode === 502 ||\n statusCode === 503 ||\n statusCode === 504);\n}\nexport function parseRetryAfterToMills(retryAfter) {\n if (retryAfter == null) {\n return undefined;\n }\n const seconds = Number.parseInt(retryAfter, 10);\n if (Number.isInteger(seconds)) {\n return seconds > 0 ? seconds * 1000 : -1;\n }\n // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After#directives\n const delay = new Date(retryAfter).getTime() - Date.now();\n if (delay >= 0) {\n return delay;\n }\n return 0;\n}\n//# sourceMappingURL=is-export-retryable.js.map","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '0.219.0';\n//# sourceMappingURL=version.js.map","import * as zlib from 'zlib';\nimport { Readable } from 'stream';\nimport { isExportHTTPErrorRetryable, parseRetryAfterToMills, } from '../is-export-retryable';\nimport { OTLPExporterError } from '../types';\nimport { VERSION } from '../version';\nconst DEFAULT_USER_AGENT = `OTel-OTLP-Exporter-JavaScript/${VERSION}`;\n/**\n * Maximum response body size (4 MB) that the HTTP transport will read.\n * If the server sends more data the connection is destroyed and the export\n * is treated as a non-retryable error regardless of status code.\n */\nexport const MAX_RESPONSE_BODY_SIZE = 4 * 1024 * 1024;\n/**\n * Sends data using http\n * @param request\n * @param url\n * @param headers\n * @param compression\n * @param userAgent\n * @param agent\n * @param data\n * @param timeoutMillis\n */\nexport function sendWithHttp(request, url, headers, compression, userAgent, agent, data, timeoutMillis) {\n return new Promise(resolve => {\n const parsedUrl = new URL(url);\n if (userAgent) {\n headers['User-Agent'] = `${userAgent} ${DEFAULT_USER_AGENT}`;\n }\n else {\n headers['User-Agent'] = DEFAULT_USER_AGENT;\n }\n const options = {\n method: 'POST',\n headers,\n agent,\n };\n const req = request(parsedUrl, options, (res) => {\n const responseData = [];\n let responseSize = 0;\n res.on('data', (chunk) => {\n responseSize += chunk.length;\n if (responseSize > MAX_RESPONSE_BODY_SIZE) {\n const sizeError = new Error(`OTLP export response body exceeded size limit of ${MAX_RESPONSE_BODY_SIZE} bytes`);\n // Oversized responses are treated as non-retryable errors\n // regardless of status code.\n // Resolve before destroying: res.destroy() tears down the socket which\n // triggers ECONNRESET on req.on('error'), so, resolving first makes that\n // a no-op. res.on('error') does not fire because destroy() is called\n // without an error argument.\n resolve({ status: 'failure', error: sizeError });\n res.destroy();\n return;\n }\n responseData.push(chunk);\n });\n res.on('end', () => {\n if (res.statusCode && res.statusCode <= 299) {\n resolve({\n status: 'success',\n data: Buffer.concat(responseData),\n });\n }\n else if (res.statusCode &&\n isExportHTTPErrorRetryable(res.statusCode)) {\n resolve({\n status: 'retryable',\n retryInMillis: parseRetryAfterToMills(res.headers['retry-after']),\n });\n }\n else {\n const error = new OTLPExporterError(res.statusMessage, res.statusCode, Buffer.concat(responseData).toString());\n resolve({\n status: 'failure',\n error,\n });\n }\n });\n res.on('error', (error) => {\n // Note: 'end' may still be emitted after 'error' on the same response object, since we're resolving a promise,\n // the first call to resolve() will determine the final state.\n if (res.statusCode && res.statusCode <= 299) {\n // If the response is successful but an error occurs while reading the response,\n // we consider it a success since the data has been sent successfully.\n resolve({\n status: 'success',\n });\n }\n else if (res.statusCode &&\n isExportHTTPErrorRetryable(res.statusCode)) {\n resolve({\n status: 'retryable',\n error: error,\n retryInMillis: parseRetryAfterToMills(res.headers['retry-after']),\n });\n }\n else {\n resolve({\n status: 'failure',\n error,\n });\n }\n });\n });\n req.setTimeout(timeoutMillis, () => {\n req.destroy();\n resolve({\n status: 'retryable',\n error: new Error('Request timed out'),\n });\n });\n req.on('error', (error) => {\n if (isHttpTransportNetworkErrorRetryable(error)) {\n resolve({\n status: 'retryable',\n error,\n });\n }\n else {\n resolve({\n status: 'failure',\n error,\n });\n }\n });\n compressAndSend(req, compression, data, (error) => {\n resolve({\n status: 'failure',\n error,\n });\n });\n });\n}\nexport function compressAndSend(req, compression, data, onError) {\n let dataStream = readableFromUint8Array(data);\n if (compression === 'gzip') {\n req.setHeader('Content-Encoding', 'gzip');\n dataStream = dataStream\n .on('error', onError)\n .pipe(zlib.createGzip())\n .on('error', onError);\n }\n dataStream.pipe(req).on('error', onError);\n}\nfunction readableFromUint8Array(buff) {\n const readable = new Readable();\n readable.push(buff);\n readable.push(null);\n return readable;\n}\nfunction isHttpTransportNetworkErrorRetryable(error) {\n const RETRYABLE_NETWORK_ERROR_CODES = new Set([\n 'ECONNRESET',\n 'ECONNREFUSED',\n 'EPIPE',\n 'ETIMEDOUT',\n 'EAI_AGAIN',\n 'ENOTFOUND',\n 'ENETUNREACH',\n 'EHOSTUNREACH',\n ]);\n if ('code' in error && typeof error.code === 'string') {\n return RETRYABLE_NETWORK_ERROR_CODES.has(error.code);\n }\n return false;\n}\n//# sourceMappingURL=http-transport-utils.js.map","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { sendWithHttp } from './http-transport-utils';\nclass HttpExporterTransport {\n _utils = null;\n _parameters;\n constructor(parameters) {\n this._parameters = parameters;\n }\n async send(data, timeoutMillis) {\n const { agent, request } = await this._loadUtils();\n const headers = await this._parameters.headers();\n return sendWithHttp(request, this._parameters.url, headers, this._parameters.compression, this._parameters.userAgent, agent, data, timeoutMillis);\n }\n shutdown() {\n // intentionally left empty, nothing to do.\n }\n async _loadUtils() {\n let utils = this._utils;\n if (utils === null) {\n const protocol = new URL(this._parameters.url).protocol;\n const [agent, request] = await Promise.all([\n this._parameters.agentFactory(protocol),\n requestFunctionFactory(protocol),\n ]);\n utils = this._utils = { agent, request };\n }\n return utils;\n }\n}\nasync function requestFunctionFactory(protocol) {\n const module = protocol === 'http:' ? import('http') : import('https');\n const { request } = await module;\n return request;\n}\nexport function createHttpExporterTransport(parameters) {\n return new HttpExporterTransport(parameters);\n}\n//# sourceMappingURL=http-exporter-transport.js.map","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { diag } from '@opentelemetry/api';\nconst MAX_ATTEMPTS = 5;\nconst INITIAL_BACKOFF = 1000;\nconst MAX_BACKOFF = 5000;\nconst BACKOFF_MULTIPLIER = 1.5;\nconst JITTER = 0.2;\n/**\n * Get a pseudo-random jitter that falls in the range of [-JITTER, +JITTER]\n */\nfunction getJitter() {\n return Math.random() * (2 * JITTER) - JITTER;\n}\nclass RetryingTransport {\n _transport;\n constructor(transport) {\n this._transport = transport;\n }\n retry(data, timeoutMillis, inMillis) {\n return new Promise((resolve, reject) => {\n setTimeout(() => {\n this._transport.send(data, timeoutMillis).then(resolve, reject);\n }, inMillis);\n });\n }\n async send(data, timeoutMillis) {\n let attempts = MAX_ATTEMPTS;\n let nextBackoff = INITIAL_BACKOFF;\n const deadline = Date.now() + timeoutMillis;\n let result = await this._transport.send(data, timeoutMillis);\n while (result.status === 'retryable' && attempts > 0) {\n attempts--;\n // use maximum of computed backoff and 0 to avoid negative timeouts\n const backoff = Math.max(Math.min(nextBackoff * (1 + getJitter()), MAX_BACKOFF), 0);\n nextBackoff = nextBackoff * BACKOFF_MULTIPLIER;\n const retryInMillis = result.retryInMillis ?? backoff;\n // return when expected retry time is after the export deadline.\n const remainingTimeoutMillis = deadline - Date.now();\n if (retryInMillis > remainingTimeoutMillis) {\n diag.info(`Export retry time ${Math.round(retryInMillis)}ms exceeds remaining timeout ${Math.round(remainingTimeoutMillis)}ms, not retrying further.`);\n return result;\n }\n diag.verbose(`Scheduling export retry in ${Math.round(retryInMillis)}ms`);\n result = await this.retry(data, remainingTimeoutMillis, retryInMillis);\n }\n if (result.status === 'success') {\n diag.verbose(`Export succeeded after ${MAX_ATTEMPTS - attempts} retry attempts.`);\n }\n else if (result.status === 'retryable') {\n diag.info(`Export failed after maximum retry attempts (${MAX_ATTEMPTS}).`);\n }\n else {\n diag.info(`Export failed with non-retryable error: ${result.error}`);\n }\n return result;\n }\n shutdown() {\n return this._transport.shutdown();\n }\n}\n/**\n * Creates an Exporter Transport that retries on 'retryable' response.\n */\nexport function createRetryingTransport(options) {\n return new RetryingTransport(options.transport);\n}\n//# sourceMappingURL=retrying-transport.js.map","import { createOtlpExportDelegate } from './otlp-export-delegate';\nimport { createHttpExporterTransport } from './transport/http-exporter-transport';\nimport { createBoundedQueueExportPromiseHandler } from './bounded-queue-export-promise-handler';\nimport { createRetryingTransport } from './retrying-transport';\nexport function createOtlpHttpExportDelegate(options, serializer) {\n return createOtlpExportDelegate({\n transport: createRetryingTransport({\n transport: createHttpExporterTransport(options),\n }),\n serializer: serializer,\n promiseHandler: createBoundedQueueExportPromiseHandler(options),\n }, { timeout: options.timeoutMillis });\n}\n//# sourceMappingURL=otlp-http-export-delegate.js.map","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nlet serviceName;\n/**\n * Returns the default service name for OpenTelemetry resources.\n * In Node.js environments, returns \"unknown_service:<process.argv0>\".\n * In browser/edge environments, returns \"unknown_service\".\n */\nexport function defaultServiceName() {\n if (serviceName === undefined) {\n try {\n const argv0 = globalThis.process.argv0;\n serviceName = argv0 ? `unknown_service:${argv0}` : 'unknown_service';\n }\n catch {\n serviceName = 'unknown_service';\n }\n }\n return serviceName;\n}\n/** @internal For testing purposes only */\nexport function _clearDefaultServiceNameCache() {\n serviceName = undefined;\n}\n//# sourceMappingURL=default-service-name.js.map","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nexport const isPromiseLike = (val) => {\n return (val !== null &&\n typeof val === 'object' &&\n typeof val.then === 'function');\n};\n//# sourceMappingURL=utils.js.map","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { diag } from '@opentelemetry/api';\nimport { SDK_INFO } from '@opentelemetry/core';\nimport { ATTR_SERVICE_NAME, ATTR_TELEMETRY_SDK_LANGUAGE, ATTR_TELEMETRY_SDK_NAME, ATTR_TELEMETRY_SDK_VERSION, } from '@opentelemetry/semantic-conventions';\nimport { defaultServiceName } from './default-service-name';\nimport { isPromiseLike } from './utils';\nclass ResourceImpl {\n _rawAttributes;\n _asyncAttributesPending = false;\n _schemaUrl;\n _memoizedAttributes;\n static FromAttributeList(attributes, options) {\n const res = new ResourceImpl({}, options);\n res._rawAttributes = guardedRawAttributes(attributes);\n res._asyncAttributesPending =\n attributes.filter(([_, val]) => isPromiseLike(val)).length > 0;\n return res;\n }\n constructor(\n /**\n * A dictionary of attributes with string keys and values that provide\n * information about the entity as numbers, strings or booleans\n * TODO: Consider to add check/validation on attributes.\n */\n resource, options) {\n const attributes = resource.attributes ?? {};\n this._rawAttributes = Object.entries(attributes).map(([k, v]) => {\n if (isPromiseLike(v)) {\n // side-effect\n this._asyncAttributesPending = true;\n }\n return [k, v];\n });\n this._rawAttributes = guardedRawAttributes(this._rawAttributes);\n this._schemaUrl = validateSchemaUrl(options?.schemaUrl);\n }\n get asyncAttributesPending() {\n return this._asyncAttributesPending;\n }\n async waitForAsyncAttributes() {\n if (!this.asyncAttributesPending) {\n return;\n }\n for (let i = 0; i < this._rawAttributes.length; i++) {\n const [k, v] = this._rawAttributes[i];\n this._rawAttributes[i] = [k, isPromiseLike(v) ? await v : v];\n }\n this._asyncAttributesPending = false;\n }\n get attributes() {\n if (this.asyncAttributesPending) {\n diag.error('Accessing resource attributes before async attributes settled');\n }\n if (this._memoizedAttributes) {\n return this._memoizedAttributes;\n }\n const attrs = {};\n for (const [k, v] of this._rawAttributes) {\n if (isPromiseLike(v)) {\n diag.debug(`Unsettled resource attribute ${k} skipped`);\n continue;\n }\n if (v != null) {\n attrs[k] ??= v;\n }\n }\n // only memoize output if all attributes are settled\n if (!this._asyncAttributesPending) {\n this._memoizedAttributes = attrs;\n }\n return attrs;\n }\n getRawAttributes() {\n return this._rawAttributes;\n }\n get schemaUrl() {\n return this._schemaUrl;\n }\n merge(resource) {\n if (resource == null)\n return this;\n // Order is important\n // Spec states incoming attributes override existing attributes\n const mergedSchemaUrl = mergeSchemaUrl(this, resource);\n const mergedOptions = mergedSchemaUrl\n ? { schemaUrl: mergedSchemaUrl }\n : undefined;\n return ResourceImpl.FromAttributeList([...resource.getRawAttributes(), ...this.getRawAttributes()], mergedOptions);\n }\n}\nexport function resourceFromAttributes(attributes, options) {\n return ResourceImpl.FromAttributeList(Object.entries(attributes), options);\n}\nexport function resourceFromDetectedResource(detectedResource, options) {\n return new ResourceImpl(detectedResource, options);\n}\nexport function emptyResource() {\n return resourceFromAttributes({});\n}\nexport function defaultResource() {\n return resourceFromAttributes({\n [ATTR_SERVICE_NAME]: defaultServiceName(),\n [ATTR_TELEMETRY_SDK_LANGUAGE]: SDK_INFO[ATTR_TELEMETRY_SDK_LANGUAGE],\n [ATTR_TELEMETRY_SDK_NAME]: SDK_INFO[ATTR_TELEMETRY_SDK_NAME],\n [ATTR_TELEMETRY_SDK_VERSION]: SDK_INFO[ATTR_TELEMETRY_SDK_VERSION],\n });\n}\nfunction guardedRawAttributes(attributes) {\n return attributes.map(([k, v]) => {\n if (isPromiseLike(v)) {\n return [\n k,\n v.catch(err => {\n diag.debug('promise rejection for resource attribute: %s - %s', k, err);\n return undefined;\n }),\n ];\n }\n return [k, v];\n });\n}\nfunction validateSchemaUrl(schemaUrl) {\n if (typeof schemaUrl === 'string' || schemaUrl === undefined) {\n return schemaUrl;\n }\n diag.warn('Schema URL must be string or undefined, got %s. Schema URL will be ignored.', schemaUrl);\n return undefined;\n}\nfunction mergeSchemaUrl(old, updating) {\n const oldSchemaUrl = old?.schemaUrl;\n const updatingSchemaUrl = updating?.schemaUrl;\n const isOldEmpty = oldSchemaUrl === undefined || oldSchemaUrl === '';\n const isUpdatingEmpty = updatingSchemaUrl === undefined || updatingSchemaUrl === '';\n if (isOldEmpty) {\n return updatingSchemaUrl;\n }\n if (isUpdatingEmpty) {\n return oldSchemaUrl;\n }\n if (oldSchemaUrl === updatingSchemaUrl) {\n return oldSchemaUrl;\n }\n diag.warn('Schema URL merge conflict: old resource has \"%s\", updating resource has \"%s\". Resulting resource will have undefined Schema URL.', oldSchemaUrl, updatingSchemaUrl);\n return undefined;\n}\n//# sourceMappingURL=ResourceImpl.js.map","export function createResource(resource, encoder) {\n const result = {\n attributes: toAttributes(resource.attributes, encoder),\n droppedAttributesCount: 0,\n };\n const schemaUrl = resource.schemaUrl;\n if (schemaUrl && schemaUrl !== '')\n result.schemaUrl = schemaUrl;\n return result;\n}\nexport function createInstrumentationScope(scope, encoder) {\n const result = {\n name: scope.name,\n version: scope.version,\n };\n if (scope.attributes && Object.keys(scope.attributes).length > 0) {\n result.attributes = toAttributes(scope.attributes, encoder);\n result.droppedAttributesCount = scope.droppedAttributesCount ?? 0;\n }\n return result;\n}\nexport function toAttributes(attributes, encoder) {\n return Object.keys(attributes).map(key => toKeyValue(key, attributes[key], encoder));\n}\nexport function toKeyValue(key, value, encoder) {\n return {\n key: key,\n value: toAnyValue(value, encoder),\n };\n}\nexport function toAnyValue(value, encoder) {\n const t = typeof value;\n if (t === 'string')\n return { stringValue: value };\n if (t === 'number') {\n if (!Number.isInteger(value))\n return { doubleValue: value };\n return { intValue: value };\n }\n if (t === 'boolean')\n return { boolValue: value };\n if (value instanceof Uint8Array)\n return { bytesValue: encoder.encodeUint8Array(value) };\n if (Array.isArray(value)) {\n const values = new Array(value.length);\n for (let i = 0; i < value.length; i++) {\n values[i] = toAnyValue(value[i], encoder);\n }\n return { arrayValue: { values } };\n }\n if (t === 'object' && value != null) {\n const keys = Object.keys(value);\n const values = new Array(keys.length);\n for (let i = 0; i < keys.length; i++) {\n values[i] = {\n key: keys[i],\n value: toAnyValue(value[keys[i]], encoder),\n };\n }\n return { kvlistValue: { values } };\n }\n return {};\n}\n//# sourceMappingURL=internal.js.map","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { hrTimeToNanoseconds } from '@opentelemetry/core';\nimport { hexToBinary } from './hex-to-binary';\nexport function hrTimeToNanos(hrTime) {\n const NANOSECONDS = BigInt(1000000000);\n return (BigInt(Math.trunc(hrTime[0])) * NANOSECONDS + BigInt(Math.trunc(hrTime[1])));\n}\nexport function toLongBits(value) {\n const low = Number(BigInt.asUintN(32, value));\n const high = Number(BigInt.asUintN(32, value >> BigInt(32)));\n return { low, high };\n}\nexport function encodeAsLongBits(hrTime) {\n const nanos = hrTimeToNanos(hrTime);\n return toLongBits(nanos);\n}\nexport function encodeAsString(hrTime) {\n const nanos = hrTimeToNanos(hrTime);\n return nanos.toString();\n}\nconst encodeTimestamp = typeof BigInt !== 'undefined' ? encodeAsString : hrTimeToNanoseconds;\nfunction identity(value) {\n return value;\n}\nfunction optionalHexToBinary(str) {\n if (str === undefined)\n return undefined;\n return hexToBinary(str);\n}\n/**\n * Encoder for protobuf format.\n * Uses { high, low } timestamps and binary for span/trace IDs, leaves Uint8Array attributes as-is.\n */\nexport const PROTOBUF_ENCODER = {\n encodeHrTime: encodeAsLongBits,\n encodeSpanContext: hexToBinary,\n encodeOptionalSpanContext: optionalHexToBinary,\n encodeUint8Array: identity,\n};\n/**\n * Encoder for JSON format.\n * Uses string timestamps, hex for span/trace IDs, and base64 for Uint8Array.\n */\nexport const JSON_ENCODER = {\n encodeHrTime: encodeTimestamp,\n encodeSpanContext: identity,\n encodeOptionalSpanContext: identity,\n encodeUint8Array: (bytes) => {\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(bytes).toString('base64');\n }\n // implementation note: not using spread operator and passing to\n // btoa to avoid stack overflow on large Uint8Arrays\n const chars = new Array(bytes.length);\n for (let i = 0; i < bytes.length; i++) {\n chars[i] = String.fromCharCode(bytes[i]);\n }\n return btoa(chars.join(''));\n },\n};\n//# sourceMappingURL=utils.js.map","import { createInstrumentationScope, createResource, toAttributes, } from '../common/internal';\n// Span flags constants matching the OTLP specification\nconst SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE_MASK = 0x100;\nconst SPAN_FLAGS_CONTEXT_IS_REMOTE_MASK = 0x200;\n/**\n * Builds the 32-bit span flags value combining the low 8-bit W3C TraceFlags\n * with the HAS_IS_REMOTE and IS_REMOTE bits according to the OTLP spec.\n */\nfunction buildSpanFlagsFrom(traceFlags, isRemote) {\n // low 8 bits are W3C TraceFlags (e.g., sampled)\n let flags = (traceFlags & 0xff) | SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE_MASK;\n if (isRemote) {\n flags |= SPAN_FLAGS_CONTEXT_IS_REMOTE_MASK;\n }\n return flags;\n}\nexport function sdkSpanToOtlpSpan(span, encoder) {\n const ctx = span.spanContext();\n const status = span.status;\n const parentSpanId = span.parentSpanContext?.spanId\n ? encoder.encodeSpanContext(span.parentSpanContext?.spanId)\n : undefined;\n return {\n traceId: encoder.encodeSpanContext(ctx.traceId),\n spanId: encoder.encodeSpanContext(ctx.spanId),\n parentSpanId: parentSpanId,\n traceState: ctx.traceState?.serialize(),\n name: span.name,\n // Span kind is offset by 1 because the API does not define a value for unset\n kind: span.kind == null ? 0 : span.kind + 1,\n startTimeUnixNano: encoder.encodeHrTime(span.startTime),\n endTimeUnixNano: encoder.encodeHrTime(span.endTime),\n attributes: toAttributes(span.attributes, encoder),\n droppedAttributesCount: span.droppedAttributesCount,\n events: span.events.map(event => toOtlpSpanEvent(event, encoder)),\n droppedEventsCount: span.droppedEventsCount,\n status: {\n // API and proto enums share the same values\n code: status.code,\n message: status.message,\n },\n links: span.links.map(link => toOtlpLink(link, encoder)),\n droppedLinksCount: span.droppedLinksCount,\n flags: buildSpanFlagsFrom(ctx.traceFlags, span.parentSpanContext?.isRemote),\n };\n}\nexport function toOtlpLink(link, encoder) {\n return {\n attributes: link.attributes ? toAttributes(link.attributes, encoder) : [],\n spanId: encoder.encodeSpanContext(link.context.spanId),\n traceId: encoder.encodeSpanContext(link.context.traceId),\n traceState: link.context.traceState?.serialize(),\n droppedAttributesCount: link.droppedAttributesCount || 0,\n flags: buildSpanFlagsFrom(link.context.traceFlags, link.context.isRemote),\n };\n}\nexport function toOtlpSpanEvent(timedEvent, encoder) {\n return {\n attributes: timedEvent.attributes\n ? toAttributes(timedEvent.attributes, encoder)\n : [],\n name: timedEvent.name,\n timeUnixNano: encoder.encodeHrTime(timedEvent.time),\n droppedAttributesCount: timedEvent.droppedAttributesCount || 0,\n };\n}\nexport function createExportTraceServiceRequest(spans, encoder) {\n return {\n resourceSpans: spanRecordsToResourceSpans(spans, encoder),\n };\n}\nfunction createResourceMap(readableSpans) {\n const resourceMap = new Map();\n for (const record of readableSpans) {\n let ilsMap = resourceMap.get(record.resource);\n if (!ilsMap) {\n ilsMap = new Map();\n resourceMap.set(record.resource, ilsMap);\n }\n // TODO this is duplicated in basic tracer. Consolidate on a common helper in core\n const instrumentationScopeKey = `${record.instrumentationScope.name}@${record.instrumentationScope.version || ''}:${record.instrumentationScope.schemaUrl || ''}`;\n let records = ilsMap.get(instrumentationScopeKey);\n if (!records) {\n records = [];\n ilsMap.set(instrumentationScopeKey, records);\n }\n records.push(record);\n }\n return resourceMap;\n}\nfunction spanRecordsToResourceSpans(readableSpans, encoder) {\n const resourceMap = createResourceMap(readableSpans);\n const out = [];\n const entryIterator = resourceMap.entries();\n let entry = entryIterator.next();\n while (!entry.done) {\n const [resource, ilmMap] = entry.value;\n const scopeResourceSpans = [];\n const ilmIterator = ilmMap.values();\n let ilmEntry = ilmIterator.next();\n while (!ilmEntry.done) {\n const scopeSpans = ilmEntry.value;\n if (scopeSpans.length > 0) {\n const spans = scopeSpans.map(readableSpan => sdkSpanToOtlpSpan(readableSpan, encoder));\n scopeResourceSpans.push({\n scope: createInstrumentationScope(scopeSpans[0].instrumentationScope, encoder),\n spans: spans,\n schemaUrl: scopeSpans[0].instrumentationScope.schemaUrl,\n });\n }\n ilmEntry = ilmIterator.next();\n }\n const processedResource = createResource(resource, encoder);\n const transformedSpans = {\n resource: processedResource,\n scopeSpans: scopeResourceSpans,\n schemaUrl: processedResource.schemaUrl,\n };\n out.push(transformedSpans);\n entry = entryIterator.next();\n }\n return out;\n}\n//# sourceMappingURL=internal.js.map","import { createExportTraceServiceRequest } from '../internal';\nimport { JSON_ENCODER } from '../../common/utils';\nimport { diag } from '@opentelemetry/api';\nexport const JsonTraceSerializer = {\n serializeRequest: (arg) => {\n const request = createExportTraceServiceRequest(arg, JSON_ENCODER);\n const encoder = new TextEncoder();\n return encoder.encode(JSON.stringify(request));\n },\n deserializeResponse: (arg) => {\n if (arg.length === 0) {\n return {};\n }\n const decoder = new TextDecoder();\n try {\n return JSON.parse(decoder.decode(arg));\n }\n catch (err) {\n diag.warn(`Failed to parse trace export response: ${err.message}. Returning empty response`);\n return {};\n }\n },\n};\n//# sourceMappingURL=trace.js.map","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n// Event name definitions\nexport const ExceptionEventName = 'exception';\n//# sourceMappingURL=enums.js.map","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n/**\n * Well-known symbol used by Node.js `util.inspect` (and `console.*`) to\n * render an object via a custom representation. Defined as a global Symbol\n * so it works without importing from `node:util`, keeping this module safe\n * for browser builds (where the symbol is simply never looked up).\n */\nexport const inspectCustom = Symbol.for('nodejs.util.inspect.custom');\n/**\n * Collect a Resource's settled attributes without touching the\n * `attributes` getter, which emits diag.error/debug entries when async\n * attribute detectors are still pending. Promise-like (unsettled)\n * entries are silently skipped so logging a Span/Tracer/Provider during\n * startup doesn't recurse through the diag pipeline.\n */\nexport function settledResourceAttributes(resource) {\n const attrs = {};\n for (const [k, v] of resource.getRawAttributes()) {\n if (typeof v?.then === 'function') {\n continue;\n }\n if (v != null) {\n attrs[k] ??= v;\n }\n }\n return attrs;\n}\n/**\n * Build a class-tagged inspect representation. Returns a stub like\n * `[ClassName]` once the recursion budget is exhausted, otherwise returns\n * `ClassName <inspected payload>` so nested fields keep proper coloring,\n * indentation, and depth handling. In environments that don't supply an\n * `inspect` callback (e.g. browsers), falls back to returning the raw\n * payload object.\n */\nexport function formatInspect(className, payload, depth, options, inspect) {\n if (typeof depth === 'number' && depth < 0) {\n const tag = `[${className}]`;\n return options?.stylize ? options.stylize(tag, 'special') : tag;\n }\n if (typeof inspect !== 'function' || !options) {\n return payload;\n }\n const childOptions = {\n ...options,\n depth: options.depth == null ? options.depth : options.depth - 1,\n };\n return `${className} ${inspect(payload, childOptions)}`;\n}\n//# sourceMappingURL=inspect.js.map","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { diag, SpanStatusCode } from '@opentelemetry/api';\nimport { addHrTimes, millisToHrTime, hrTime, hrTimeDuration, isAttributeValue, isTimeInput, isTimeInputHrTime, otperformance, sanitizeAttributes, } from '@opentelemetry/core';\nimport { ATTR_EXCEPTION_MESSAGE, ATTR_EXCEPTION_STACKTRACE, ATTR_EXCEPTION_TYPE, } from '@opentelemetry/semantic-conventions';\nimport { ExceptionEventName } from './enums';\nimport { formatInspect, inspectCustom, settledResourceAttributes, } from './inspect';\n/**\n * This class represents a span.\n */\nexport class SpanImpl {\n // Below properties are included to implement ReadableSpan for export\n // purposes but are not intended to be written-to directly.\n _spanContext;\n kind;\n parentSpanContext;\n attributes = {};\n links = [];\n events = [];\n startTime;\n resource;\n instrumentationScope;\n _droppedAttributesCount = 0;\n _droppedEventsCount = 0;\n _droppedLinksCount = 0;\n _attributesCount = 0;\n name;\n status = {\n code: SpanStatusCode.UNSET,\n };\n endTime = [0, 0];\n _ended = false;\n _duration = [-1, -1];\n _spanProcessor;\n _spanLimits;\n _attributeValueLengthLimit;\n _recordEndMetrics;\n _performanceStartTime;\n _performanceOffset;\n _startTimeProvided;\n /**\n * Constructs a new SpanImpl instance.\n */\n constructor(opts) {\n const now = Date.now();\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 this.name = opts.name;\n this.parentSpanContext = opts.parentSpanContext;\n this.kind = opts.kind;\n if (opts.links) {\n for (const link of opts.links) {\n this.addLink(link);\n }\n }\n this.startTime = this._getTime(opts.startTime ?? now);\n this.resource = opts.resource;\n this.instrumentationScope = opts.scope;\n this._recordEndMetrics = opts.recordEndMetrics;\n if (opts.attributes != null) {\n this.setAttributes(opts.attributes);\n }\n this._spanProcessor.onStart(this, opts.context);\n }\n spanContext() {\n return this._spanContext;\n }\n setAttribute(key, value) {\n if (value == null || this._isSpanEnded())\n 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 const { attributeCountLimit } = this._spanLimits;\n const isNewKey = !Object.prototype.hasOwnProperty.call(this.attributes, key);\n if (attributeCountLimit !== undefined &&\n this._attributesCount >= attributeCountLimit &&\n isNewKey) {\n this._droppedAttributesCount++;\n return this;\n }\n this.attributes[key] = this._truncateToSize(value);\n if (isNewKey) {\n this._attributesCount++;\n }\n return this;\n }\n setAttributes(attributes) {\n for (const key in attributes) {\n if (Object.prototype.hasOwnProperty.call(attributes, key)) {\n this.setAttribute(key, attributes[key]);\n }\n }\n return this;\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(name, attributesOrStartTime, timeStamp) {\n if (this._isSpanEnded())\n return this;\n const { eventCountLimit } = this._spanLimits;\n if (eventCountLimit === 0) {\n diag.warn('No events allowed.');\n this._droppedEventsCount++;\n return this;\n }\n if (eventCountLimit !== undefined &&\n this.events.length >= eventCountLimit) {\n if (this._droppedEventsCount === 0) {\n diag.debug('Dropping extra events.');\n }\n this.events.shift();\n this._droppedEventsCount++;\n }\n if (isTimeInput(attributesOrStartTime)) {\n if (!isTimeInput(timeStamp)) {\n timeStamp = attributesOrStartTime;\n }\n attributesOrStartTime = undefined;\n }\n const sanitized = sanitizeAttributes(attributesOrStartTime);\n const { attributePerEventCountLimit } = this._spanLimits;\n const attributes = {};\n let droppedAttributesCount = 0;\n let eventAttributesCount = 0;\n for (const attr in sanitized) {\n if (!Object.prototype.hasOwnProperty.call(sanitized, attr)) {\n continue;\n }\n const attrVal = sanitized[attr];\n if (attributePerEventCountLimit !== undefined &&\n eventAttributesCount >= attributePerEventCountLimit) {\n droppedAttributesCount++;\n continue;\n }\n attributes[attr] = this._truncateToSize(attrVal);\n eventAttributesCount++;\n }\n this.events.push({\n name,\n attributes,\n time: this._getTime(timeStamp),\n droppedAttributesCount,\n });\n return this;\n }\n addLink(link) {\n if (this._isSpanEnded())\n return this;\n const { linkCountLimit } = this._spanLimits;\n if (linkCountLimit === 0) {\n this._droppedLinksCount++;\n return this;\n }\n if (linkCountLimit !== undefined && this.links.length >= linkCountLimit) {\n if (this._droppedLinksCount === 0) {\n diag.debug('Dropping extra links.');\n }\n this.links.shift();\n this._droppedLinksCount++;\n }\n const { attributePerLinkCountLimit } = this._spanLimits;\n const sanitized = sanitizeAttributes(link.attributes);\n const attributes = {};\n let droppedAttributesCount = 0;\n let linkAttributesCount = 0;\n for (const attr in sanitized) {\n if (!Object.prototype.hasOwnProperty.call(sanitized, attr)) {\n continue;\n }\n const attrVal = sanitized[attr];\n if (attributePerLinkCountLimit !== undefined &&\n linkAttributesCount >= attributePerLinkCountLimit) {\n droppedAttributesCount++;\n continue;\n }\n attributes[attr] = this._truncateToSize(attrVal);\n linkAttributesCount++;\n }\n const processedLink = { context: link.context };\n if (linkAttributesCount > 0) {\n processedLink.attributes = attributes;\n }\n if (droppedAttributesCount > 0) {\n processedLink.droppedAttributesCount = droppedAttributesCount;\n }\n this.links.push(processedLink);\n return this;\n }\n addLinks(links) {\n for (const link of links) {\n this.addLink(link);\n }\n return this;\n }\n setStatus(status) {\n if (this._isSpanEnded())\n return this;\n if (status.code === SpanStatusCode.UNSET)\n return this;\n if (this.status.code === SpanStatusCode.OK)\n return this;\n const newStatus = { code: status.code };\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 (status.code === SpanStatusCode.ERROR) {\n if (typeof status.message === 'string') {\n newStatus.message = status.message;\n }\n else if (status.message != null) {\n diag.warn(`Dropping invalid status.message of type '${typeof status.message}', expected 'string'`);\n }\n }\n this.status = newStatus;\n return this;\n }\n updateName(name) {\n if (this._isSpanEnded())\n return this;\n this.name = name;\n return this;\n }\n end(endTime) {\n if (this._isSpanEnded()) {\n diag.error(`${this.name} ${this._spanContext.traceId}-${this._spanContext.spanId} - You can only call end() on a span once.`);\n return;\n }\n this.endTime = this._getTime(endTime);\n this._duration = hrTimeDuration(this.startTime, this.endTime);\n if (this._duration[0] < 0) {\n diag.warn('Inconsistent start and end time, startTime > endTime. Setting span duration to 0ms.', this.startTime, this.endTime);\n this.endTime = this.startTime.slice();\n this._duration = [0, 0];\n }\n if (this._droppedEventsCount > 0) {\n diag.warn(`Dropped ${this._droppedEventsCount} events because eventCountLimit reached`);\n }\n if (this._droppedLinksCount > 0) {\n diag.warn(`Dropped ${this._droppedLinksCount} links because linkCountLimit reached`);\n }\n if (this._spanProcessor.onEnding) {\n this._spanProcessor.onEnding(this);\n }\n this._recordEndMetrics?.();\n this._ended = true;\n this._spanProcessor.onEnd(this);\n }\n _getTime(inp) {\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 if (typeof inp === 'number') {\n return millisToHrTime(inp);\n }\n if (inp instanceof Date) {\n return millisToHrTime(inp.getTime());\n }\n if (isTimeInputHrTime(inp)) {\n return inp;\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 const msDuration = otperformance.now() - this._performanceStartTime;\n return addHrTimes(this.startTime, millisToHrTime(msDuration));\n }\n isRecording() {\n return this._ended === false;\n }\n recordException(exception, time) {\n const attributes = {};\n if (typeof exception === 'string') {\n attributes[ATTR_EXCEPTION_MESSAGE] = exception;\n }\n else if (exception) {\n if (exception.code) {\n attributes[ATTR_EXCEPTION_TYPE] = exception.code.toString();\n }\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 // these are minimum requirements from spec\n if (attributes[ATTR_EXCEPTION_TYPE] || attributes[ATTR_EXCEPTION_MESSAGE]) {\n this.addEvent(ExceptionEventName, attributes, time);\n }\n else {\n diag.warn(`Failed to record an exception ${exception}`);\n }\n }\n get duration() {\n return this._duration;\n }\n get ended() {\n return this._ended;\n }\n get droppedAttributesCount() {\n return this._droppedAttributesCount;\n }\n get droppedEventsCount() {\n return this._droppedEventsCount;\n }\n get droppedLinksCount() {\n return this._droppedLinksCount;\n }\n _isSpanEnded() {\n if (this._ended) {\n const error = new Error(`Operation attempted on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`);\n diag.warn(`Cannot execute the operation on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`, error);\n }\n return this._ended;\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 _truncateToLimitUtil(value, limit) {\n if (value.length <= limit) {\n return value;\n }\n return value.substring(0, limit);\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 _truncateToSize(value) {\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 // String\n if (typeof value === 'string') {\n return this._truncateToLimitUtil(value, limit);\n }\n // Array of strings\n if (Array.isArray(value)) {\n return value.map(val => typeof val === 'string' ? this._truncateToLimitUtil(val, limit) : val);\n }\n // Other types, no need to apply value length limit\n return value;\n }\n [inspectCustom](depth, options, inspect) {\n const payload = {\n name: this.name,\n kind: this.kind,\n spanContext: this._spanContext,\n parentSpanContext: this.parentSpanContext,\n status: this.status,\n startTime: this.startTime,\n endTime: this.endTime,\n duration: this._duration,\n ended: this._ended,\n attributes: this.attributes,\n events: this.events,\n links: this.links,\n droppedAttributesCount: this._droppedAttributesCount,\n droppedEventsCount: this._droppedEventsCount,\n droppedLinksCount: this._droppedLinksCount,\n instrumentationScope: this.instrumentationScope,\n resource: { attributes: settledResourceAttributes(this.resource) },\n };\n return formatInspect('SpanImpl', payload, depth, options, inspect);\n }\n}\n//# sourceMappingURL=Span.js.map","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n/**\n * A sampling decision that determines how a {@link Span} will be recorded\n * and collected.\n */\nexport var SamplingDecision;\n(function (SamplingDecision) {\n /**\n * `Span.isRecording() === false`, span will not be recorded and all events\n * and attributes will be dropped.\n */\n SamplingDecision[SamplingDecision[\"NOT_RECORD\"] = 0] = \"NOT_RECORD\";\n /**\n * `Span.isRecording() === true`, but `Sampled` flag in {@link TraceFlags}\n * MUST NOT be set.\n */\n SamplingDecision[SamplingDecision[\"RECORD\"] = 1] = \"RECORD\";\n /**\n * `Span.isRecording() === true` AND `Sampled` flag in {@link TraceFlags}\n * MUST be set.\n */\n SamplingDecision[SamplingDecision[\"RECORD_AND_SAMPLED\"] = 2] = \"RECORD_AND_SAMPLED\";\n})(SamplingDecision || (SamplingDecision = {}));\n//# sourceMappingURL=Sampler.js.map","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { SamplingDecision } from '../Sampler';\n/** Sampler that samples no traces. */\nexport class AlwaysOffSampler {\n shouldSample() {\n return {\n decision: SamplingDecision.NOT_RECORD,\n };\n }\n toString() {\n return 'AlwaysOffSampler';\n }\n}\n//# sourceMappingURL=AlwaysOffSampler.js.map","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { SamplingDecision } from '../Sampler';\n/** Sampler that samples all traces. */\nexport class AlwaysOnSampler {\n shouldSample() {\n return {\n decision: SamplingDecision.RECORD_AND_SAMPLED,\n };\n }\n toString() {\n return 'AlwaysOnSampler';\n }\n}\n//# sourceMappingURL=AlwaysOnSampler.js.map","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { isSpanContextValid, TraceFlags, trace } from '@opentelemetry/api';\nimport { globalErrorHandler } from '@opentelemetry/core';\nimport { AlwaysOffSampler } from './AlwaysOffSampler';\nimport { AlwaysOnSampler } from './AlwaysOnSampler';\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 {\n _root;\n _remoteParentSampled;\n _remoteParentNotSampled;\n _localParentSampled;\n _localParentNotSampled;\n constructor(config) {\n this._root = config.root;\n if (!this._root) {\n globalErrorHandler(new Error('ParentBasedSampler must have a root sampler configured'));\n this._root = new AlwaysOnSampler();\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 shouldSample(context, traceId, spanName, spanKind, attributes, links) {\n const parentContext = trace.getSpanContext(context);\n if (!parentContext || !isSpanContextValid(parentContext)) {\n return this._root.shouldSample(context, traceId, spanName, spanKind, attributes, links);\n }\n if (parentContext.isRemote) {\n if (parentContext.traceFlags & TraceFlags.SAMPLED) {\n return this._remoteParentSampled.shouldSample(context, traceId, spanName, spanKind, attributes, links);\n }\n return this._remoteParentNotSampled.shouldSample(context, traceId, spanName, spanKind, attributes, links);\n }\n if (parentContext.traceFlags & TraceFlags.SAMPLED) {\n return this._localParentSampled.shouldSample(context, traceId, spanName, spanKind, attributes, links);\n }\n return this._localParentNotSampled.shouldSample(context, traceId, spanName, spanKind, attributes, links);\n }\n toString() {\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//# sourceMappingURL=ParentBasedSampler.js.map","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { isValidTraceId } from '@opentelemetry/api';\nimport { SamplingDecision } from '../Sampler';\n/** Sampler that samples a given fraction of traces based of trace id deterministically. */\nexport class TraceIdRatioBasedSampler {\n _ratio;\n _upperBound;\n constructor(ratio = 0) {\n this._ratio = this._normalize(ratio);\n this._upperBound = Math.floor(this._ratio * 0xffffffff);\n }\n shouldSample(context, traceId) {\n return {\n decision: isValidTraceId(traceId) && this._accumulate(traceId) < this._upperBound\n ? SamplingDecision.RECORD_AND_SAMPLED\n : SamplingDecision.NOT_RECORD,\n };\n }\n toString() {\n return `TraceIdRatioBased{${this._ratio}}`;\n }\n _normalize(ratio) {\n if (typeof ratio !== 'number' || isNaN(ratio))\n return 0;\n return ratio >= 1 ? 1 : ratio <= 0 ? 0 : ratio;\n }\n _accumulate(traceId) {\n let accumulation = 0;\n for (let i = 0; i < 32; i += 8) {\n let part = 0;\n for (let j = 0; j < 8; j++) {\n const c = traceId.charCodeAt(i + j);\n // Convert hex char code to value: '0'-'9' -> 0-9, 'a'-'f' -> 10-15, 'A'-'F' -> 10-15\n const v = c < 58 ? c - 48 : c < 71 ? c - 55 : c - 87;\n part = (part << 4) | v;\n }\n accumulation = (accumulation ^ part) >>> 0;\n }\n return accumulation;\n }\n}\n//# sourceMappingURL=TraceIdRatioBasedSampler.js.map","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { diag } from '@opentelemetry/api';\nimport { getNumberFromEnv, getStringFromEnv } from '@opentelemetry/core';\nimport { AlwaysOffSampler } from './sampler/AlwaysOffSampler';\nimport { AlwaysOnSampler } from './sampler/AlwaysOnSampler';\nimport { ParentBasedSampler } from './sampler/ParentBasedSampler';\nimport { TraceIdRatioBasedSampler } from './sampler/TraceIdRatioBasedSampler';\nvar TracesSamplerValues;\n(function (TracesSamplerValues) {\n TracesSamplerValues[\"AlwaysOff\"] = \"always_off\";\n TracesSamplerValues[\"AlwaysOn\"] = \"always_on\";\n TracesSamplerValues[\"ParentBasedAlwaysOff\"] = \"parentbased_always_off\";\n TracesSamplerValues[\"ParentBasedAlwaysOn\"] = \"parentbased_always_on\";\n TracesSamplerValues[\"ParentBasedTraceIdRatio\"] = \"parentbased_traceidratio\";\n TracesSamplerValues[\"TraceIdRatio\"] = \"traceidratio\";\n})(TracesSamplerValues || (TracesSamplerValues = {}));\nconst DEFAULT_RATIO = 1;\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// 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: getNumberFromEnv('OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT') ?? Infinity,\n attributeCountLimit: getNumberFromEnv('OTEL_ATTRIBUTE_COUNT_LIMIT') ?? 128,\n },\n spanLimits: {\n attributeValueLengthLimit: getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT') ?? Infinity,\n attributeCountLimit: 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: getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT') ?? 128,\n attributePerLinkCountLimit: getNumberFromEnv('OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT') ?? 128,\n },\n };\n}\n/**\n * Based on environment, builds a sampler, complies with specification.\n */\nexport function buildSamplerFromEnv() {\n const sampler = 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(`OTEL_TRACES_SAMPLER value \"${sampler}\" invalid, defaulting to \"${TracesSamplerValues.ParentBasedAlwaysOn}\".`);\n return new ParentBasedSampler({\n root: new AlwaysOnSampler(),\n });\n }\n}\nfunction getSamplerProbabilityFromEnv() {\n const probability = getNumberFromEnv('OTEL_TRACES_SAMPLER_ARG');\n if (probability == null) {\n diag.error(`OTEL_TRACES_SAMPLER_ARG is blank, defaulting to ${DEFAULT_RATIO}.`);\n return DEFAULT_RATIO;\n }\n if (probability < 0 || probability > 1) {\n diag.error(`OTEL_TRACES_SAMPLER_ARG=${probability} was given, but it is out of range ([0..1]), defaulting to ${DEFAULT_RATIO}.`);\n return DEFAULT_RATIO;\n }\n return probability;\n}\n//# sourceMappingURL=config.js.map","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { buildSamplerFromEnv, loadDefaultConfig } from './config';\nimport { getNumberFromEnv } from '@opentelemetry/core';\nexport const DEFAULT_ATTRIBUTE_COUNT_LIMIT = 128;\nexport const DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT = Infinity;\n/**\n * Function to merge Default configuration (as specified in './config') with\n * user provided configurations.\n */\nexport function mergeConfig(userConfig) {\n const perInstanceDefaults = {\n sampler: buildSamplerFromEnv(),\n };\n const DEFAULT_CONFIG = loadDefaultConfig();\n const target = Object.assign({}, DEFAULT_CONFIG, perInstanceDefaults, userConfig);\n target.generalLimits = Object.assign({}, DEFAULT_CONFIG.generalLimits, userConfig.generalLimits || {});\n target.spanLimits = Object.assign({}, DEFAULT_CONFIG.spanLimits, userConfig.spanLimits || {});\n return target;\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) {\n const spanLimits = Object.assign({}, userConfig.spanLimits);\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 * 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 return Object.assign({}, userConfig, { spanLimits });\n}\n//# sourceMappingURL=utility.js.map","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nconst SPAN_ID_BYTES = 8;\nconst TRACE_ID_BYTES = 16;\nexport class RandomIdGenerator {\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 * 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}\nconst SHARED_BUFFER = Buffer.allocUnsafe(TRACE_ID_BYTES);\nfunction getIdGenerator(bytes) {\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 // 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 }\n else if (i === bytes - 1) {\n SHARED_BUFFER[bytes - 1] = 1;\n }\n }\n return SHARED_BUFFER.toString('hex', 0, bytes);\n };\n}\n//# sourceMappingURL=RandomIdGenerator.js.map","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n/*\n * This file contains a copy of unstable semantic convention definitions\n * used by this package.\n * @see https://github.com/open-telemetry/opentelemetry-js/tree/main/semantic-conventions#unstable-semconv\n */\n/**\n * Determines whether the span has a parent span, and if so, [whether it is a remote parent](https://opentelemetry.io/docs/specs/otel/trace/api/#isremote)\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_OTEL_SPAN_PARENT_ORIGIN = 'otel.span.parent.origin';\n/**\n * The result value of the sampler for this span\n *\n * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const ATTR_OTEL_SPAN_SAMPLING_RESULT = 'otel.span.sampling_result';\n/**\n * The number of created spans with `recording=true` for which the end operation has not been called yet.\n *\n * @experimental This metric is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const METRIC_OTEL_SDK_SPAN_LIVE = 'otel.sdk.span.live';\n/**\n * The number of created spans.\n *\n * @note Implementations **MUST** record this metric for all spans, even for non-recording ones.\n *\n * @experimental This metric is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`.\n */\nexport const METRIC_OTEL_SDK_SPAN_STARTED = 'otel.sdk.span.started';\n//# sourceMappingURL=semconv.js.map","import { SamplingDecision } from './Sampler';\nimport { ATTR_OTEL_SPAN_PARENT_ORIGIN, ATTR_OTEL_SPAN_SAMPLING_RESULT, METRIC_OTEL_SDK_SPAN_LIVE, METRIC_OTEL_SDK_SPAN_STARTED, } from './semconv';\n/**\n * Generates `otel.sdk.span.*` metrics.\n * https://opentelemetry.io/docs/specs/semconv/otel/sdk-metrics/#span-metrics\n */\nexport class TracerMetrics {\n startedSpans;\n liveSpans;\n constructor(meter) {\n this.startedSpans = meter.createCounter(METRIC_OTEL_SDK_SPAN_STARTED, {\n unit: '{span}',\n description: 'The number of created spans.',\n });\n this.liveSpans = meter.createUpDownCounter(METRIC_OTEL_SDK_SPAN_LIVE, {\n unit: '{span}',\n description: 'The number of currently live spans.',\n });\n }\n startSpan(parentSpanCtx, samplingDecision) {\n const samplingDecisionStr = samplingDecisionToString(samplingDecision);\n this.startedSpans.add(1, {\n [ATTR_OTEL_SPAN_PARENT_ORIGIN]: parentOrigin(parentSpanCtx),\n [ATTR_OTEL_SPAN_SAMPLING_RESULT]: samplingDecisionStr,\n });\n if (samplingDecision === SamplingDecision.NOT_RECORD) {\n return () => { };\n }\n const liveSpanAttributes = {\n [ATTR_OTEL_SPAN_SAMPLING_RESULT]: samplingDecisionStr,\n };\n this.liveSpans.add(1, liveSpanAttributes);\n return () => {\n this.liveSpans.add(-1, liveSpanAttributes);\n };\n }\n}\nfunction parentOrigin(parentSpanContext) {\n if (!parentSpanContext) {\n return 'none';\n }\n if (parentSpanContext.isRemote) {\n return 'remote';\n }\n return 'local';\n}\nfunction samplingDecisionToString(decision) {\n switch (decision) {\n case SamplingDecision.RECORD_AND_SAMPLED:\n return 'RECORD_AND_SAMPLE';\n case SamplingDecision.RECORD:\n return 'RECORD_ONLY';\n case SamplingDecision.NOT_RECORD:\n return 'DROP';\n }\n}\n//# sourceMappingURL=TracerMetrics.js.map","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '2.8.0';\n//# sourceMappingURL=version.js.map","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport * as api from '@opentelemetry/api';\nimport { sanitizeAttributes, isTracingSuppressed } from '@opentelemetry/core';\nimport { SpanImpl } from './Span';\nimport { mergeConfig } from './utility';\nimport { RandomIdGenerator } from './platform';\nimport { TracerMetrics } from './TracerMetrics';\nimport { VERSION } from './version';\nimport { formatInspect, inspectCustom, settledResourceAttributes, } from './inspect';\n/**\n * This class represents a basic tracer.\n */\nexport class Tracer {\n _sampler;\n _generalLimits;\n _spanLimits;\n _idGenerator;\n instrumentationScope;\n _resource;\n _spanProcessor;\n _tracerMetrics;\n /**\n * Constructs a new Tracer instance.\n */\n constructor(instrumentationScope, config, resource, spanProcessor) {\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 const meter = localConfig.meterProvider\n ? localConfig.meterProvider.getMeter('@opentelemetry/sdk-trace', VERSION)\n : api.createNoopMeter();\n this._tracerMetrics = new TracerMetrics(meter);\n }\n /**\n * Starts a new Span or returns the default NoopSpan based on the sampling\n * decision.\n */\n startSpan(name, options = {}, context = api.context.active()) {\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 if (isTracingSuppressed(context)) {\n api.diag.debug('Instrumentation suppressed, returning Noop Span');\n const nonRecordingSpan = api.trace.wrapSpanContext(api.INVALID_SPAN_CONTEXT);\n return nonRecordingSpan;\n }\n const parentSpanContext = parentSpan?.spanContext();\n const spanId = this._idGenerator.generateSpanId();\n let validParentSpanContext;\n let traceId;\n let traceState;\n if (!parentSpanContext ||\n !api.trace.isSpanContextValid(parentSpanContext)) {\n // New root span.\n traceId = this._idGenerator.generateTraceId();\n }\n else {\n // New child span.\n traceId = parentSpanContext.traceId;\n traceState = parentSpanContext.traceState;\n validParentSpanContext = parentSpanContext;\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(context, traceId, name, spanKind, attributes, links);\n const recordEndMetrics = this._tracerMetrics.startSpan(parentSpanContext, samplingResult.decision);\n traceState = samplingResult.traceState ?? traceState;\n const traceFlags = 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('Recording is off, propagating context in a non-recording span');\n const nonRecordingSpan = api.trace.wrapSpanContext(spanContext);\n return nonRecordingSpan;\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(Object.assign(attributes, samplingResult.attributes));\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 recordEndMetrics,\n });\n return span;\n }\n startActiveSpan(name, arg2, arg3, arg4) {\n let opts;\n let ctx;\n let fn;\n if (arguments.length < 2) {\n return;\n }\n else if (arguments.length === 2) {\n fn = arg2;\n }\n else if (arguments.length === 3) {\n opts = arg2;\n fn = arg3;\n }\n else {\n opts = arg2;\n ctx = arg3;\n fn = arg4;\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 return api.context.with(contextWithSpanSet, fn, undefined, span);\n }\n /** Returns the active {@link GeneralLimits}. */\n getGeneralLimits() {\n return this._generalLimits;\n }\n /** Returns the active {@link SpanLimits}. */\n getSpanLimits() {\n return this._spanLimits;\n }\n [inspectCustom](depth, options, inspect) {\n const payload = {\n instrumentationScope: this.instrumentationScope,\n resource: { attributes: settledResourceAttributes(this._resource) },\n spanLimits: this._spanLimits,\n generalLimits: this._generalLimits,\n };\n return formatInspect('Tracer', payload, depth, options, inspect);\n }\n}\n//# sourceMappingURL=Tracer.js.map","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { globalErrorHandler } from '@opentelemetry/core';\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 {\n _spanProcessors;\n constructor(spanProcessors) {\n this._spanProcessors = spanProcessors;\n }\n forceFlush() {\n const promises = [];\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(error || new Error('MultiSpanProcessor: forceFlush failed'));\n resolve();\n });\n });\n }\n onStart(span, context) {\n for (const spanProcessor of this._spanProcessors) {\n spanProcessor.onStart(span, context);\n }\n }\n onEnding(span) {\n for (const spanProcessor of this._spanProcessors) {\n if (spanProcessor.onEnding) {\n spanProcessor.onEnding(span);\n }\n }\n }\n onEnd(span) {\n for (const spanProcessor of this._spanProcessors) {\n spanProcessor.onEnd(span);\n }\n }\n shutdown() {\n const promises = [];\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//# sourceMappingURL=MultiSpanProcessor.js.map","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { merge } from '@opentelemetry/core';\nimport { defaultResource } from '@opentelemetry/resources';\nimport { Tracer } from './Tracer';\nimport { loadDefaultConfig } from './config';\nimport { MultiSpanProcessor } from './MultiSpanProcessor';\nimport { reconfigureLimits } from './utility';\nimport { formatInspect, inspectCustom, settledResourceAttributes, } from './inspect';\nexport var ForceFlushState;\n(function (ForceFlushState) {\n ForceFlushState[ForceFlushState[\"resolved\"] = 0] = \"resolved\";\n ForceFlushState[ForceFlushState[\"timeout\"] = 1] = \"timeout\";\n ForceFlushState[ForceFlushState[\"error\"] = 2] = \"error\";\n ForceFlushState[ForceFlushState[\"unresolved\"] = 3] = \"unresolved\";\n})(ForceFlushState || (ForceFlushState = {}));\n/**\n * This class represents a basic tracer provider which platform libraries can extend\n */\nexport class BasicTracerProvider {\n _config;\n _tracers = new Map();\n _resource;\n _activeSpanProcessor;\n constructor(config = {}) {\n const mergedConfig = merge({}, loadDefaultConfig(), reconfigureLimits(config));\n this._resource = mergedConfig.resource ?? defaultResource();\n this._config = Object.assign({}, mergedConfig, {\n resource: this._resource,\n });\n const spanProcessors = [];\n if (config.spanProcessors?.length) {\n spanProcessors.push(...config.spanProcessors);\n }\n this._activeSpanProcessor = new MultiSpanProcessor(spanProcessors);\n }\n getTracer(name, version, options) {\n const key = `${name}@${version || ''}:${options?.schemaUrl || ''}`;\n if (!this._tracers.has(key)) {\n this._tracers.set(key, new Tracer({ name, version, schemaUrl: options?.schemaUrl }, this._config, this._resource, this._activeSpanProcessor));\n }\n return this._tracers.get(key);\n }\n forceFlush() {\n const timeout = this._config.forceFlushTimeoutMillis;\n const promises = this._activeSpanProcessor['_spanProcessors'].map((spanProcessor) => {\n return new Promise(resolve => {\n let state;\n const timeoutInterval = setTimeout(() => {\n resolve(new Error(`Span processor did not completed within timeout period of ${timeout} ms`));\n state = ForceFlushState.timeout;\n }, timeout);\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 return new Promise((resolve, reject) => {\n Promise.all(promises)\n .then(results => {\n const errors = results.filter(result => result !== ForceFlushState.resolved);\n if (errors.length > 0) {\n reject(errors);\n }\n else {\n resolve();\n }\n })\n .catch(error => reject([error]));\n });\n }\n shutdown() {\n return this._activeSpanProcessor.shutdown();\n }\n [inspectCustom](depth, options, inspect) {\n const processors = this._activeSpanProcessor['_spanProcessors'];\n const payload = {\n resource: { attributes: settledResourceAttributes(this._resource) },\n tracers: Array.from(this._tracers.keys()),\n spanProcessors: processors.map(p => p.constructor?.name ?? 'SpanProcessor'),\n };\n return formatInspect('BasicTracerProvider', payload, depth, options, inspect);\n }\n}\n//# sourceMappingURL=BasicTracerProvider.js.map","/**\n * The shared scrubber: scrubbing, bounding, and the one function that makes a span exportable.\n *\n * The OpenCode plugin and the Action both use this module (the plugin bundles it inline; see the plugin's `tsdown.config.ts`).\n * Extracting content from OpenCode data is not here: it stays in the plugin, which hands this module spans to scrub.\n *\n * `scrubSpan` is the only way to produce a `ScrubbedSpan`, and the exporter takes nothing else. It scrubs every string of\n * a finished span (attribute values, name, status message, event text) and, for content attributes, scrubs the whole\n * serialized value BEFORE bounding it, so a secret that straddles a cut is already gone. A value over the input ceiling,\n * or one the scrubber fails on, is omitted with a marker, never exported raw.\n *\n * Scrubbing is best-effort: it removes the secret shapes listed in `SCRUB_PATTERNS` and the values of the caller's own\n * secret-named environment variables. It does not find a secret that has no recognizable shape.\n *\n * The design that makes it safe to extend: every text rule is a pure matcher over the ORIGINAL string that only reports\n * ranges (`ScrubMatcher`); `scrubWithMatchers` unites all ranges and builds the output once. No rule ever reads text another\n * rule rewrote, so rule order cannot matter (`scrub.order.test.ts` proves it). Structured content is walked once\n * (`scrubStructured`): sensitive-named keys go whole, every other string is scrubbed from its original text, and the result is\n * serialized, never scanned again.\n *\n * Plain functions only: no SDK, no I/O, no clock. Every matcher is linear-time (no nested quantifier, no backreference,\n * no adjacent unbounded quantifiers) and the union is a sort bounded by `MAX_RANGES`; `scrub.test.ts` times each on its own\n * adversarial input.\n */\n\n/** What a scrubbed value is replaced with. A fixed string: it never reflects the secret. */\nexport const REDACTION = '[REDACTED]'\n\n// ---------------------------------------------------------------------------------------------------------------------\n// Limits\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport interface ContentLimits {\n /** A string longer than this is not scanned: it is omitted. Bounds the scrubber's worst-case cost. */\n readonly inputCeilingChars: number\n /** Total characters of content attributes on one span. */\n readonly spanContentChars: number\n /** A plain string (name, status message, event text, ordinary attribute) is cut to this after scrubbing. */\n readonly plainStringChars: number\n}\n\nexport const DEFAULT_CONTENT_LIMITS: ContentLimits = {\n inputCeilingChars: 8 * 1024 * 1024,\n spanContentChars: 1024 * 1024,\n plainStringChars: 8 * 1024,\n}\n\n/**\n * The attributes that carry captured content (the model's input, output, instructions and tool definitions, and a call's\n * arguments and result), as `genai-attributes.ts` sets them. The exporter may omit one of these, and only these, to bring an\n * oversized span under the collector's body limit; identity, outcome, marker and every other attribute is never a candidate.\n */\nexport const CONTENT_ATTRIBUTE_NAMES = [\n 'gen_ai.input.messages',\n 'gen_ai.output.messages',\n 'gen_ai.system_instructions',\n 'gen_ai.tool.definitions',\n 'gen_ai.tool.call.arguments',\n 'gen_ai.tool.call.result',\n] as const\n\n/** Added to a cut string; counted against the bound so the result stays under it. */\nconst TRUNCATION_OVERHEAD = 40\nconst TRUNCATION_SUFFIX = (removed: number): string => `…[truncated ${removed} chars]`\n\n// ---------------------------------------------------------------------------------------------------------------------\n// Scrubber\n// ---------------------------------------------------------------------------------------------------------------------\n\n/**\n * A text rule. A pure matcher over the ORIGINAL, unmodified string: it reports each range `[start, end)` it would redact\n * through `emit`, and nothing else. It never reads another matcher's output, never rewrites text and never needs to\n * recognise the redaction marker, so the order matchers run in cannot change what is removed (`scrubWithMatchers`).\n */\nexport interface ScrubMatcher {\n /** The rule's name: used in tests and nowhere in output (a marker never names the rule that matched). */\n readonly id: string\n /**\n * `lower` is `text` case-folded once, for cheap needle checks. Ranges may arrive in any order and may overlap. `withhold` is the\n * one fail-closed signal: a matcher that has recognised a secret but cannot establish where it ends calls it, and the whole\n * string is withheld (`sensitive-value-unbounded`), never redacted \"up to\" a guess.\n */\n readonly find: (text: string, lower: string, emit: Emit, withhold: Withhold) => void\n}\n\nexport type Emit = (start: number, end: number) => void\nexport type Withhold = () => void\n\nexport interface Range {\n readonly start: number\n readonly end: number\n}\n\n/** Ranges one value may produce before it is omitted instead of scanned further. Bounds memory and the merge's sort. */\nexport const MAX_RANGES = 50_000\n\nclass TooManyRangesError extends Error {}\n\n/** Calls `matcher` and returns the ranges it reports, uncapped. For tests and tools: `scrubWithMatchers` caps them. */\nexport function matchRanges(matcher: ScrubMatcher, text: string): Range[] {\n const found: Range[] = []\n matcher.find(\n text,\n text.toLowerCase(),\n (start, end) => {\n found.push({start, end})\n },\n () => {},\n )\n return found\n}\n\n/** Whether `matcher` withholds `text` (it recognised a secret and could not establish where its value ends). */\nexport function matchWithholds(matcher: ScrubMatcher, text: string): boolean {\n let withheld = false\n matcher.find(\n text,\n text.toLowerCase(),\n () => {},\n () => {\n withheld = true\n },\n )\n return withheld\n}\n\n/**\n * Reports every match of `regex` (a global regex, reset before use) as the range `rangeOf` picks out of it. Skips the scan\n * when none of `needles` occur (case-folded). `rangeOf` returns the part to redact: a token whole, or only the value\n * after a name or a scheme word that stays visible.\n */\nfunction regexMatcher(\n id: string,\n regex: RegExp,\n rangeOf: (match: RegExpExecArray, text: string) => Range,\n needles?: readonly string[],\n): ScrubMatcher {\n return {\n id,\n find: (text, lower, emit) => {\n if (needles !== undefined && !needles.some(needle => lower.includes(needle))) return\n regex.lastIndex = 0\n for (let match = regex.exec(text); match !== null; match = regex.exec(text)) {\n const range = rangeOf(match, text)\n emit(range.start, range.end)\n }\n },\n }\n}\n\nconst wholeMatch = (match: RegExpExecArray): Range => ({start: match.index, end: match.index + match[0].length})\n\n/**\n * A private-key block: from its header to its end line, or, when the tool cut the block short, to the end of the string\n * value (the next `\"`) or of the text. Found by header regex and `indexOf`, never by a lazy match across the body.\n */\nfunction pemMatcher(): ScrubMatcher {\n const header = /-----BEGIN [A-Z0-9 ]{0,40}(?:PRIVATE KEY|KEY BLOCK)-----/g\n return {\n id: 'pem-private-key',\n find: (text, lower, emit) => {\n if (!lower.includes('-----begin ')) return\n header.lastIndex = 0\n // The next end line and the next quote are searched forward once and only moved when a header passes them, so a\n // text of many headers and no end line costs one scan, not one per header.\n let nextEnd = text.indexOf('-----END ')\n let nextQuote = text.indexOf('\"')\n let covered = 0\n for (;;) {\n const match = header.exec(text)\n if (match === null) break\n const from = match.index\n // A header inside a block already reported: the block covers it.\n if (from < covered) continue\n const bodyStart = from + match[0].length\n if (nextEnd !== -1 && nextEnd < bodyStart) nextEnd = text.indexOf('-----END ', bodyStart)\n if (nextQuote !== -1 && nextQuote < bodyStart) nextQuote = text.indexOf('\"', bodyStart)\n let stop = text.length\n if (nextEnd !== -1 && (nextQuote === -1 || nextEnd < nextQuote)) {\n const close = text.indexOf('-----', nextEnd + '-----END '.length)\n stop = close === -1 ? text.length : close + '-----'.length\n } else if (nextQuote !== -1) {\n stop = nextQuote\n }\n emit(from, stop)\n covered = stop\n header.lastIndex = Math.max(stop, header.lastIndex)\n }\n },\n }\n}\n\n/** `[\\w-]`: what a JWT segment is made of. */\nconst isSegmentChar = (code: number): boolean =>\n (code >= 0x30 && code <= 0x39) ||\n (code >= 0x41 && code <= 0x5a) ||\n (code >= 0x61 && code <= 0x7a) ||\n code === 0x5f ||\n code === 0x2d\n\n/** `\\w`, for the boundary before `eyJ`. */\nconst isWordChar = (code: number): boolean => code !== 0x2d && isSegmentChar(code)\n\n/**\n * A JSON Web Token: `eyJ`, a header of at least 8 segment characters, a dot, a payload of at least 8, a dot, a signature\n * of at least 4. The same language as `\\beyJ[\\w-]{8,}\\.[\\w-]{8,}\\.[\\w-]{4,}`, found by one forward walk.\n *\n * Why not the regex: `[\\w-]` takes the dash, so in `eyJ-eyJ-eyJ-…` every `eyJ` starts inside the previous one's run, each\n * attempt walks to the end of the run and backtracks over it, and the whole is quadratic (0.18 s at 20 KB, 2.9 s at 80 KB).\n * Here a run's end is found once and remembered, and a candidate inside a run that already failed is skipped, so no\n * position is walked more than three times (once as each segment).\n */\nfunction jwtMatcher(): ScrubMatcher {\n return {\n id: 'jwt',\n find: (text, lower, emit) => {\n if (!lower.includes('eyj')) return\n const length = text.length\n // The most recent maximal run of segment characters, so a start inside it does not walk it again.\n let runFrom = -1\n let runTo = -1\n const runEnd = (start: number): number => {\n if (start >= runFrom && start <= runTo && runFrom !== -1) return runTo\n let end = start\n while (end < length && isSegmentChar(text.charCodeAt(end))) end += 1\n runFrom = start\n runTo = end\n return end\n }\n let from = 0\n for (;;) {\n const start = text.indexOf('eyJ', from)\n if (start === -1) break\n from = start + 3\n // `\\b` before `e`: the character before is not a word character. A dash is not one, but is a segment character.\n if (start > 0 && isWordChar(text.charCodeAt(start - 1))) continue\n const headerEnd = runEnd(start + 3)\n // Every start inside this run has the same end and a shorter header: if this one fails on the dot, they all do.\n if (headerEnd - (start + 3) < 8 || text.charCodeAt(headerEnd) !== 0x2e) {\n from = Math.max(from, headerEnd)\n continue\n }\n const payloadEnd = runEnd(headerEnd + 1)\n if (payloadEnd - (headerEnd + 1) < 8 || text.charCodeAt(payloadEnd) !== 0x2e) {\n // Later starts inside the header run reach the same payload and fail alike; the payload itself may hold starts.\n from = Math.max(from, headerEnd + 1)\n continue\n }\n const signatureEnd = runEnd(payloadEnd + 1)\n if (signatureEnd - (payloadEnd + 1) < 4) {\n from = Math.max(from, headerEnd + 1)\n continue\n }\n emit(start, signatureEnd)\n from = signatureEnd\n }\n },\n }\n}\n\n/** Words that make a name secret-like. Matched inside a name, so `X_API_KEY` and `dbPassword` both qualify. */\nconst SECRET_WORDS =\n 'password|passwd|pwd|passphrase|secret|token|api[_-]?key|access[_-]?key|private[_-]?key|credential|authorization|auth[_-]?key|session[_-]?key|client[_-]?secret|signature|bearer'\n/** A key whose name says it holds a credential. Same words as the text rules. */\nconst SENSITIVE_KEY = new RegExp(SECRET_WORDS, 'i')\nconst SECRET_NEEDLES: readonly string[] = [\n 'pass',\n 'pwd',\n 'secret',\n 'token',\n 'key',\n 'credential',\n 'authorization',\n 'signature',\n 'bearer',\n]\n\n/** Characters that end an unquoted value: whitespace, quotes, a backslash and the delimiters of a URL or a list. */\nconst UNQUOTED_STOP: ReadonlySet<number> = new Set(\n [' ', '\\t', '\\n', '\\r', '\\f', '\\v', '\"', \"'\", '\\\\', '<', '>', ',', ';', '&', ')', '}', ']'].map(char =>\n char.charCodeAt(0),\n ),\n)\n\n/**\n * Names that are a count or a limit, not a credential: `max_tokens`, `token_count`, `tokens`, `input_tokens`. Only these may\n * keep a numeric value; a password, secret, credential or authorization name never does. Tested on a bounded identifier.\n */\nconst COUNTER_NAME =\n /(?:^|[_.-])(?:max|min|total|num|count|limit|input|output|prompt|completion|cache|reasoning|used|remaining|budget)[_.-]?tokens$|^tokens$|tokens?[_.-]?(?:count|limit|used|budget|remaining|total|usage)$/i\nconst MAX_IDENTIFIER_CHARS = 64\n\nfunction isCounterName(identifier: string): boolean {\n return COUNTER_NAME.test(identifier.slice(-MAX_IDENTIFIER_CHARS))\n}\n\n/** A value that is only a short number: a count, never a password. */\nconst isShortNumber = (text: string): boolean => /^\\d{1,8}$/.test(text)\n\nconst isIdentifierCode = (code: number): boolean =>\n (code >= 0x30 && code <= 0x39) ||\n (code >= 0x41 && code <= 0x5a) ||\n (code >= 0x61 && code <= 0x7a) ||\n code === 0x5f ||\n code === 0x2e ||\n code === 0x2d\n\n/** The number of JSON-string encodings a document is under, from the backslash run before its first quote: `2^d - 1`; -1 if it is not of that form. */\nfunction layersOfRun(run: number): number {\n for (let candidate = 0; candidate <= 4; candidate += 1) if (run === 2 ** candidate - 1) return candidate\n return -1\n}\n\n/** The most whitespace (real or escaped, newlines included) allowed between a QUOTED key's colon and its value. */\nconst MAX_GAP_CHARS = 256\n\n/**\n * The whitespace between a quoted key's `:` and its value, from `from`: spaces, tabs, line feeds and carriage returns, and, for a\n * document under `layers` JSON encodings, the escaped forms a serializer writes for them there (`\\n`, `\\r`, `\\t` after\n * `2^(layers-1)` backslashes: one at depth 1, two at depth 2, four at depth 3). Returns where the value starts and whether the\n * whitespace was longer than `MAX_GAP_CHARS` (the caller then fails closed: it cannot tell where the value is, so the rest of the\n * line goes). One forward scan; the caller continues after it.\n */\nfunction skipGap(text: string, from: number, layers: number): {readonly end: number; readonly over: boolean} {\n const escapedRun = layers >= 1 ? 2 ** (layers - 1) : 0\n let index = from\n while (index < text.length) {\n const code = text.charCodeAt(index)\n if (code === 0x20 || code === 0x09 || code === 0x0a || code === 0x0d) {\n index += 1\n } else if (code === 0x5c && escapedRun > 0) {\n let run = 1\n while (run <= escapedRun && text.charCodeAt(index + run) === 0x5c) run += 1\n const next = text.charCodeAt(index + run)\n if (run === escapedRun && (next === 0x6e || next === 0x72 || next === 0x74)) index += run + 1\n else break\n } else {\n break\n }\n }\n return {end: index, over: index - from > MAX_GAP_CHARS}\n}\n\n/** The most a bracketed value (`{...}` or `[...]`) is scanned for its balanced close. Past it the end is not established and the string is withheld. */\nconst MAX_STRUCTURE_VALUE_CHARS = 256 * 1024\n\n/** The deepest bracket nesting the scan follows. Deeper, the end of the value is not established and the string is withheld. */\nconst MAX_BRACKET_DEPTH = 64\n\n/**\n * A value that begins with `{` or `[`, read by one forward scan to its balanced close: brackets count outside strings only, each\n * closer must be the one the innermost open bracket expects (`}` for `{`, `]` for `[`), a string ends at its own closing quote,\n * and quotes are read at the escape depth the document is written in. Returns the index after the close, or -1 when there is\n * none within `MAX_STRUCTURE_VALUE_CHARS` or the shared `budget`, a closer does not match, or the nesting is deeper than\n * `MAX_BRACKET_DEPTH` (then the caller withholds the string). `budget.left` is the work all such scans of one text may do together, so a text of many\n * unterminated openers costs a constant multiple of its length, not a scan each.\n *\n * Escape depth: the first quote inside the value is preceded by `r` backslashes, and `r = 2^d - 1` for a document encoded `d`\n * times as a JSON string (0, 1, 3, 7, ...). A quote after a run `n` is a delimiter when peeling `d` layers off `n`\n * (`n = 2m + 1` each time) leaves an even run, and an escaped quote when it leaves an odd one. A first run that is not of that\n * form is not a document the scan can read: -1.\n */\nfunction structureEnd(text: string, from: number, budget: {left: number}): number {\n const limit = Math.min(text.length, from + MAX_STRUCTURE_VALUE_CHARS)\n let layers = -1\n // The closer each open bracket expects, innermost last: `}` (0x7d) for `{`, `]` (0x5d) for `[`.\n const expected = new Uint8Array(MAX_BRACKET_DEPTH)\n let depth = 0\n /** Whether a quote after `run` backslashes delimits a string (true) or is escaped inside one (false); undefined: not at this depth. */\n const delimits = (run: number): boolean | undefined => {\n let remaining = run\n for (let layer = 0; layer < layers; layer += 1) {\n if (remaining % 2 === 0) return undefined\n remaining = (remaining - 1) / 2\n }\n return remaining % 2 === 0\n }\n let index = from\n let inString = false\n while (index < limit) {\n budget.left -= 1\n if (budget.left < 0) return -1\n const code = text.charCodeAt(index)\n if (code === 0x5c) {\n let run = 1\n while (text.charCodeAt(index + run) === 0x5c) run += 1\n if (text.charCodeAt(index + run) === 0x22) {\n if (layers === -1) {\n layers = layersOfRun(run)\n if (layers === -1) return -1\n }\n const delimiter = delimits(run)\n if (delimiter === true) inString = !inString\n index += run + 1\n budget.left -= run\n continue\n }\n index += run\n budget.left -= run\n continue\n }\n if (code === 0x22) {\n if (layers === -1) layers = 0\n if (layers === 0 && delimits(0) === true) inString = !inString\n } else if (!inString) {\n if (code === 0x7b || code === 0x5b) {\n if (depth === MAX_BRACKET_DEPTH) return -1\n expected[depth] = code === 0x7b ? 0x7d : 0x5d\n depth += 1\n } else if (code === 0x7d || code === 0x5d) {\n // A closer that is not the innermost open bracket's: the value is malformed and its end cannot be established.\n depth -= 1\n if (expected[depth] !== code) return -1\n if (depth === 0) return index + 1\n }\n }\n index += 1\n }\n return -1\n}\n\n/** The most a quoted value is searched for its closing quote. Past it the end is not established and the string is withheld. */\nconst MAX_QUOTED_VALUE_CHARS = 8192\n\n/** Where an unquoted value that starts at `from` ends: at the first delimiter. */\nfunction unquotedEnd(text: string, from: number): number {\n let end = from\n while (end < text.length && !UNQUOTED_STOP.has(text.charCodeAt(end))) end += 1\n return end\n}\n\nconst SCHEME_WORD = /^(?:bearer|basic|token|digest)$/i\n\n/**\n * `Authorization: Bearer <credential>`: when an assignment's first token is a scheme word, the value is the scheme AND the\n * credential after it (up to eight blanks, then the next token). This is the rule's own boundary, read from the original\n * text; the scheme rule (`auth-scheme-value`) finds the same credential on its own and the two ranges are united.\n */\nfunction schemeCredentialEnd(text: string, end: number): number {\n let index = end\n while (index < text.length && index - end < 8 && (text.charCodeAt(index) === 0x20 || text.charCodeAt(index) === 0x09))\n index += 1\n if (index === end) return end\n const tokenEnd = unquotedEnd(text, index)\n return tokenEnd === index ? end : tokenEnd\n}\n\n/** Characters that are invisible inside a key and never part of a real name: zero-width space, joiners, word joiner, BOM. */\nconst ZERO_WIDTH = /[\\u200B-\\u200D\\u2060\\uFEFF]/\nconst ZERO_WIDTH_ALL = /[\\u200B-\\u200D\\u2060\\uFEFF]/g\n\n/** The longest raw key (between its quotes) the quoted-key pass inspects. A longer one is not a name. */\nconst MAX_KEY_RAW_CHARS = 1024\n\n/** The most backslashes counted before a quote. A longer run is not a delimiter at a supported depth. */\nconst MAX_QUOTE_RUN = 64\n\n/**\n * The escape depth a quote delimits at, from the backslash run before it. A quote of a document under `d` JSON encodings is\n * preceded by `2^d - 1` backslashes, plus any number of escaped backslashes that end the string before it (`2^(d+1)` each):\n * the run plus one has exactly `d` trailing zero bits. Depth 0 to 4; -1 for anything deeper or a run too long to be one.\n */\nfunction depthOfDelimiterRun(run: number): number {\n if (run >= MAX_QUOTE_RUN) return -1\n const depth = Math.clz32((run + 1) & -(run + 1)) ^ 31\n return depth <= 4 ? depth : -1\n}\n\nconst SIMPLE_ESCAPES: Readonly<Record<number, string>> = {\n 0x22: '\"',\n 0x5c: '\\\\',\n 0x2f: '/',\n 0x62: '\\b',\n 0x66: '\\f',\n 0x6e: '\\n',\n 0x72: '\\r',\n 0x74: '\\t',\n}\n\n/**\n * One layer of JSON string-body decoding: `\\\"` `\\\\` `\\/` `\\b` `\\f` `\\n` `\\r` `\\t` and `\\uXXXX` (upper- or lower-case hex; a\n * surrogate pair is two escapes that join). Undefined for anything that is not a valid body: an unescaped quote, a lone\n * backslash at the end, an escape this does not know, a `\\u` without four hex digits. One forward pass, no exceptions.\n */\nfunction decodeLayer(body: string): string | undefined {\n let out = ''\n let index = 0\n while (index < body.length) {\n const code = body.charCodeAt(index)\n if (code === 0x22) return undefined\n if (code !== 0x5c) {\n out += body.charAt(index)\n index += 1\n continue\n }\n const next = body.charCodeAt(index + 1)\n const simple = SIMPLE_ESCAPES[next]\n if (simple !== undefined) {\n out += simple\n index += 2\n } else if (next === 0x75) {\n const hex = body.slice(index + 2, index + 6)\n if (!/^[\\da-f]{4}$/i.test(hex)) return undefined\n out += String.fromCharCode(Number.parseInt(hex, 16))\n index += 6\n } else {\n return undefined\n }\n }\n return out\n}\n\n/**\n * A quoted key's text, as the document means it: its escapes decoded at the depth the document is written in (a document\n * under `d` encodings has `d + 1` layers of escaping to remove). Undefined when it cannot be decoded.\n */\nfunction decodeKey(raw: string, layers: number): string | undefined {\n if (!raw.includes('\\\\')) return raw\n let current = raw\n for (let pass = 0; pass <= layers; pass += 1) {\n const next = decodeLayer(current)\n if (next === undefined) return undefined\n current = next\n }\n return current\n}\n\n/**\n * `name=value` and `name: value`, in plain text and in JSON text (`\\\"name\\\": \\\"value\\\"`): the range is the value.\n *\n * Two ways in, both reading the ORIGINAL text:\n * 1. A secret word, then (for an unquoted name) up to four blanks and `:` or `=`; or (for a name in quotes) the key's closing\n * quote, then any JSON whitespace up to `MAX_GAP_CHARS` and `:`.\n * 2. Every double-quoted JSON key at the supported escape depths, found by pairing consecutive delimiting quotes of one depth\n * (so it does not depend on how the key is spelled): its text is DECODED (`\\u0061`, `\\n`, `\\/`, surrogate pairs, at the\n * depth it is written in), zero-width characters are dropped, and if the result holds a secret word the value after the\n * colon is read exactly as in 1. This is what finds `\"p\\u0061ssword\"` and a key whose word has a long suffix.\n *\n * A key that cannot be decoded (a malformed escape, longer than `MAX_KEY_RAW_CHARS`, an escape depth beyond four) is not\n * inspected and does not withhold: it is not valid JSON, or not a name, and withholding on it would withhold most text with\n * a backslash in it. The value is read by hand, once, forward:\n * - a quoted value runs to its closing quote, honouring escapes (in an escaped layer, `\\\"` closes and `\\\\\\\"` does not); if\n * no closing quote is found within `MAX_QUOTED_VALUE_CHARS` the end is not established and the string is withheld;\n * - an unquoted value is a run of non-delimiter characters (the first token only), plus the credential after a scheme word;\n * - a `{` or `[` value runs to its balanced close, or the string is withheld;\n * - a number of up to eight digits survives only after a counter or limit name (`max_tokens: 8000`), never after a name that\n * says password, secret, credential or authorization.\n * Scanning resumes after the value, so no character is scanned more than a bounded number of times.\n */\nfunction nameValueMatcher(): ScrubMatcher {\n const prefix = new RegExp(\n // A word and its suffix, then EITHER the closing quote of a quoted name (a run of backslashes before it is an escaped layer;\n // what follows is read by hand, since a quoted key allows wide whitespace before its colon) OR, for an unquoted name, up to\n // four blanks and the separator.\n String.raw`((?:${SECRET_WORDS})[\\w.-]{0,20})(?:(\\\\{0,64}[\"'])|[ \\t]{0,4}([:=]))`,\n 'gi',\n )\n const SKIP = -1\n const WITHHELD = -2\n return {\n id: 'name-value-pair',\n find: (text, lower, emit, withhold) => {\n const named = SECRET_NEEDLES.some(needle => lower.includes(needle))\n // A key whose word is spelled with escapes or zero-width characters has no needle in its raw text.\n const keyed = named || text.includes(String.raw`\\u`) || ZERO_WIDTH.test(text)\n if (!keyed) return\n // The work every value of this text may spend scanning for its close, all together: a text of many unterminated openers\n // costs a constant multiple of its length, not a scan each. When it is spent the value's end cannot be established, and\n // the string is withheld. (A value can be read by both ways in, so it is twice what one way needs.)\n const budget = {left: 8 * text.length + 65_536}\n\n /** Reads the value that starts after a separator ending at `sepEnd`. Returns where scanning resumes, SKIP or WITHHELD. */\n const readValue = (sepEnd: number, jsonForm: boolean, layers: number, counter: boolean): number => {\n // The gap between the separator and the value. For a QUOTED key and a colon (the JSON form) it may hold newlines, real or\n // escaped at the document's depth, up to `MAX_GAP_CHARS`; for every other form it is up to four spaces or tabs, so prose\n // like `password:` at the end of a line does not reach the next one.\n let at = sepEnd\n if (jsonForm) {\n const gap = skipGap(text, at, layers)\n // More whitespace than the bound: where the value starts cannot be told.\n if (gap.over) return WITHHELD\n at = gap.end\n } else {\n for (\n let blanks = 0;\n blanks < 4 && (text.charCodeAt(at) === 0x20 || text.charCodeAt(at) === 0x09);\n blanks += 1\n )\n at += 1\n }\n // The value's opening quote, in an escaped layer: up to 15 backslashes before it.\n let runEnd = at\n while (runEnd - at <= 15 && text.charCodeAt(runEnd) === 0x5c) runEnd += 1\n const quoteCode = text.charCodeAt(runEnd)\n const opened = runEnd - at <= 15 && (quoteCode === 0x22 || quoteCode === 0x27)\n const opener = opened ? text.slice(at, runEnd + 1) : undefined\n const valueStart = opened ? runEnd + 1 : at\n // After a quoted key, a backslash that is not an opening quote is an escape this matcher did not recognise (a run too long,\n // a whitespace escape of another depth): the value's start is unknown, so its end is.\n if (jsonForm && !opened && text.charCodeAt(at) === 0x5c) return WITHHELD\n\n // Every branch below either establishes the value's end (a balanced close, a closing quote, a delimiter) or withholds the\n // string. There is no \"to the end of the line\".\n let valueEnd: number\n const first = text.charCodeAt(valueStart)\n if (opener === undefined && (first === 0x7b || first === 0x5b)) {\n // A whole object or array after a sensitive name: consumed to its balanced close. No close within the size bound, or\n // within the shared work budget, or an unreadable escape depth inside: the end is not established.\n const close = structureEnd(text, valueStart, budget)\n if (close === -1) return WITHHELD\n valueEnd = close\n } else if (opener === undefined) {\n // Unquoted: the value ends at the first delimiter (whitespace, a quote, a bracket, a comma...). That is the rule for this\n // form, not a guess: a delimiter or the end of the text always ends it.\n valueEnd = unquotedEnd(text, valueStart)\n if (SCHEME_WORD.test(text.slice(valueStart, valueEnd))) valueEnd = schemeCredentialEnd(text, valueEnd)\n const value = text.slice(valueStart, valueEnd)\n if (counter && isShortNumber(value)) return SKIP\n // A counter name keeps the old floor of three characters; a credential name has none.\n if (value.length < (counter ? 3 : 1)) return SKIP\n } else {\n // Quoted: ends at its closing quote. None within the scan bound, or the shared work budget is spent: not established.\n const close = budget.left > MAX_QUOTED_VALUE_CHARS ? closingQuote(text, valueStart, opener) : -1\n if (close === -1) return WITHHELD\n valueEnd = close\n budget.left -= valueEnd - valueStart\n if (valueEnd === valueStart) return SKIP\n }\n emit(valueStart, valueEnd)\n return valueEnd\n }\n\n /** Way in 2: every double-quoted key at a supported depth, by its DECODED text. */\n const quotedKeys = (): void => {\n // The most recent delimiting quote at each depth: the opening quote of whatever string the next one closes.\n const lastQuote = [-1, -1, -1, -1, -1]\n for (let quote = text.indexOf('\"'); quote !== -1; quote = text.indexOf('\"', quote + 1)) {\n let run = 0\n while (run < MAX_QUOTE_RUN && text.charCodeAt(quote - 1 - run) === 0x5c) run += 1\n const depth = depthOfDelimiterRun(run)\n if (depth === -1) continue\n // The `2^d - 1` backslashes right before the quote belong to it; any before those are the key's own escaped backslashes.\n const delimiterRun = 2 ** depth - 1\n const open = lastQuote[depth] ?? -1\n lastQuote[depth] = quote\n if (open === -1 || quote - open > MAX_KEY_RAW_CHARS) continue\n // Is it a key at all? A closing quote, then JSON whitespace, then a colon. Cheap, and it comes first.\n const gap = skipGap(text, quote + 1, depth)\n if (text.charCodeAt(gap.end) !== 0x3a) continue\n const key = decodeKey(text.slice(open + 1, quote - delimiterRun), depth)\n // A key that cannot be decoded is not inspected (see above).\n if (key === undefined) continue\n const name = ZERO_WIDTH.test(key) ? key.replaceAll(ZERO_WIDTH_ALL, '') : key\n if (!SENSITIVE_KEY.test(name)) continue\n // The sensitive name is recognised: from here the outcome is the same as for a key found by its spelling.\n if (gap.over) return withhold()\n const result = readValue(gap.end + 1, true, depth, isCounterName(name))\n if (result === WITHHELD) return withhold()\n }\n }\n\n if (named) {\n prefix.lastIndex = 0\n for (;;) {\n const match = prefix.exec(text)\n if (match === null) break\n const name = match[1] ?? ''\n const nameQuote = match[2]\n const afterName = match.index + match[0].length\n // The identifier the name belongs to: what precedes the secret word (`max_` of `max_tokens`) counts.\n let from = match.index\n while (from > 0 && match.index - from < MAX_IDENTIFIER_CHARS && isIdentifierCode(text.charCodeAt(from - 1)))\n from -= 1\n const counter = isCounterName(text.slice(from, match.index) + name)\n\n let result: number\n if (nameQuote === undefined) {\n result = readValue(afterName, false, 0, counter)\n } else {\n const layers = depthOfDelimiterRun(nameQuote.length - 1)\n // Up to four blanks and a separator, the form a name in quotes had before the JSON whitespace rule.\n let blanksEnd = afterName\n while (\n blanksEnd - afterName < 4 &&\n (text.charCodeAt(blanksEnd) === 0x20 || text.charCodeAt(blanksEnd) === 0x09)\n )\n blanksEnd += 1\n if (layers === -1) {\n // An escape depth this matcher cannot read (deeper than it supports, or a backslash run that is not `2^d - 1`): a\n // key followed by a colon cannot be read, so it cannot tell where the value ends.\n if (text.charCodeAt(blanksEnd) === 0x3a) return withhold()\n if (text.charCodeAt(blanksEnd) !== 0x3d) continue\n result = readValue(blanksEnd + 1, false, 0, counter)\n } else {\n // The JSON form: any JSON whitespace, real or escaped at this depth, up to the bound, then a colon.\n const gap = skipGap(text, afterName, layers)\n if (text.charCodeAt(gap.end) === 0x3a) {\n // More whitespace than the bound before the colon: the key is recognised but where its value starts cannot be told.\n if (gap.over) return withhold()\n result = readValue(gap.end + 1, true, layers, counter)\n } else if (text.charCodeAt(blanksEnd) === 0x3d) {\n result = readValue(blanksEnd + 1, false, 0, counter)\n } else {\n continue\n }\n }\n }\n if (result === WITHHELD) return withhold()\n if (result !== SKIP) prefix.lastIndex = Math.max(prefix.lastIndex, result)\n }\n }\n if (keyed) quotedKeys()\n },\n }\n}\n\n/**\n * Where a quoted value that starts at `from` ends: the index of its closing delimiter, or -1 when none is found within the\n * bound (the caller then withholds the string). `opener` is the quote and any backslashes before it (`\"`, `'`, `\\\"`, `\\\\\\\"`): the run of backslashes\n * says how many layers of JSON escaping the text is in. In a layer, the delimiter is exactly that run and a quote; a quote\n * of the value itself is written with a longer run and does not close it.\n */\nfunction closingQuote(text: string, from: number, opener: string): number {\n const quote = opener.endsWith('\"') ? 0x22 : 0x27\n const delimiterRun = opener.length - 1\n const limit = Math.min(text.length, from + MAX_QUOTED_VALUE_CHARS)\n let index = from\n while (index < limit) {\n const code = text.charCodeAt(index)\n if (code === 0x5c) {\n let run = 1\n while (text.charCodeAt(index + run) === 0x5c) run += 1\n const next = text.charCodeAt(index + run)\n if (delimiterRun > 0) {\n if (next === quote) {\n if (run === delimiterRun) return index\n index += run + 1\n } else {\n index += run\n }\n } else {\n // Not in an escaped layer: an odd run escapes the character after it; an even run is escaped backslashes only.\n index += run + (run % 2 === 1 ? 1 : 0)\n }\n continue\n }\n if (delimiterRun === 0 && code === quote) return index\n index += 1\n }\n return -1\n}\n\n/**\n * URL userinfo: everything between `scheme://` and the `@`, whatever its length. Userinfo can only be in the authority, so the\n * run stops at the first raw `/`, `?` or `#` (and at whitespace, quotes and a backslash): an `@` in a query, a fragment or a\n * path is not userinfo, and treating it as one would erase the real hostname. Percent-encoded characters are allowed. The run\n * cannot cross a delimiter, so a scan never reaches into another candidate and the rule stays linear.\n */\nconst URL_USERINFO = /([a-z][a-z0-9+.-]{1,15}:\\/\\/)[^\\s/?#@\"'\\\\]+@/gi\n\n/** A secret-like query parameter's value. */\nconst QUERY_SECRET = new RegExp(\n String.raw`([?&;][\\w.-]{0,30}(?:${SECRET_WORDS}|sig|key)[\\w.-]{0,10}=)[^\\s&\"'#\\\\]{3,}`,\n 'gi',\n)\n\n/** Where the value starts after a scheme word and its blanks: the scheme word stays visible. */\nconst afterScheme = (match: RegExpExecArray, text: string): Range => {\n let start = match.index + (match[1] ?? match[2] ?? '').length\n while (text.charCodeAt(start) === 0x20 || text.charCodeAt(start) === 0x09) start += 1\n return {start, end: match.index + match[0].length}\n}\n\n/**\n * The text rules. Each is a pure matcher over the original string; the list's order carries no meaning (`scrubWithMatchers`\n * takes the union of every range), and `scrub.test.ts` runs it in other orders to show that.\n */\nexport const SCRUB_PATTERNS: readonly ScrubMatcher[] = [\n pemMatcher(),\n regexMatcher('github-token', /\\b(?:gh[pousr]_[A-Za-z0-9]{36,}|github_pat_\\w{22,})\\b/g, wholeMatch, [\n 'ghp_',\n 'gho_',\n 'ghu_',\n 'ghs_',\n 'ghr_',\n 'github_pat_',\n ]),\n regexMatcher(\n 'aws-access-key-id',\n /(?<![A-Za-z0-9])(?:AKIA|ASIA|AGPA|AIDA|AROA|ANPA|ANVA|ABIA|ACCA)[A-Z0-9]{16}\\b/g,\n wholeMatch,\n ['akia', 'asia', 'agpa', 'aida', 'aroa', 'anpa', 'anva', 'abia', 'acca'],\n ),\n regexMatcher(\n 'vendor-key-prefix',\n /\\b(?:sk-[\\w-]{20,}|sk_(?:live|test)_[A-Za-z0-9]{16,}|rk_(?:live|test)_[A-Za-z0-9]{16,}|xai-[A-Za-z0-9]{20,}|gsk_[A-Za-z0-9]{20,}|AIza[\\w-]{35}|hf_[A-Za-z0-9]{30,}|pplx-[A-Za-z0-9]{30,}|fw_[A-Za-z0-9]{20,}|nvapi-[\\w-]{30,}|npm_[A-Za-z0-9]{36}|glpat-[\\w-]{20,}|xox[abposr]-[A-Za-z0-9-]{10,}|SG\\.[\\w-]{16,}\\.[\\w-]{16,}|ya29\\.[\\w-]{20,}|r8_[A-Za-z0-9]{30,}|dop_v1_[a-f0-9]{40,})/g,\n wholeMatch,\n [\n 'sk-',\n 'sk_',\n 'rk_',\n 'xai-',\n 'gsk_',\n 'aiza',\n 'hf_',\n 'pplx-',\n 'fw_',\n 'nvapi-',\n 'npm_',\n 'glpat-',\n 'xox',\n 'sg.',\n 'ya29.',\n 'r8_',\n 'dop_v1_',\n ],\n ),\n jwtMatcher(),\n // `Bearer` is a credential marker on its own; the other schemes are also English words, so their value must contain a\n // digit or a base64 or token punctuation character. The scheme word stays visible: the range is the credential.\n regexMatcher(\n 'auth-scheme-value',\n /\\b(?:(Bearer)[ \\t]{1,8}[\\w.~+/=-]{8,}|(Basic|Token|Digest)[ \\t]{1,8}(?=[\\w.~+/=-]*[\\d._~+/=-])[\\w.~+/=-]{8,})/gi,\n afterScheme,\n ['bearer', 'basic', 'token', 'digest'],\n ),\n regexMatcher(\n 'connection-string',\n /\\b(?:postgres(?:ql)?|mysql|mariadb|mongodb(?:\\+srv)?|redis|rediss|amqps?|mssql|sqlserver|clickhouse|cockroachdb):\\/\\/[^\\s\"'<>\\\\]{3,}/gi,\n wholeMatch,\n ['postgres', 'mysql', 'mariadb', 'mongodb', 'redis', 'amqp', 'mssql', 'sqlserver', 'clickhouse', 'cockroachdb'],\n ),\n // `scheme://user:password@host`: the range is the userinfo; the scheme and the `@` stay.\n regexMatcher(\n 'url-userinfo',\n URL_USERINFO,\n match => ({start: match.index + (match[1] ?? '').length, end: match.index + match[0].length - 1}),\n ['://'],\n ),\n // `?name=value`: the range is the value; the name stays.\n regexMatcher(\n 'url-query-secret',\n QUERY_SECRET,\n match => ({start: match.index + (match[1] ?? '').length, end: match.index + match[0].length}),\n ['pass', 'pwd', 'secret', 'token', 'key', 'credential', 'authorization', 'signature', 'bearer', 'sig='],\n ),\n nameValueMatcher(),\n]\n\n/** Env names whose value the literal pass removes. `OPENCODE_PASSWORD` is the server's own credential. */\nexport const SECRET_ENV_NAME =\n /SECRET|TOKEN|PASSWORD|PASSWD|PASSPHRASE|CREDENTIAL|API_?KEY|PRIVATE_?KEY|ACCESS_?KEY|AUTHORIZATION/i\n/**\n * The length range a literal secret must be in to be matched. Exported so a caller can tell what the scrubber cannot match.\n * The ceiling is 64 KiB because real credentials are long: a JavaScript action's `ACTIONS_RUNTIME_TOKEN` is 4,152 characters,\n * and a value the scrubber cannot match makes the Action's lifecycle tracer drop every free-text field of the run.\n */\nexport const MIN_LITERAL_CHARS = 8\nexport const MAX_LITERAL_CHARS = 65_536\nconst MAX_LITERALS = 128\n\n/**\n * The forms of one secret to remove: the value, and its JSON-escaped text when that differs. None for a value outside the\n * length bounds: one shorter than `MIN_LITERAL_CHARS` would redact ordinary text, one longer than `MAX_LITERAL_CHARS` is not a\n * secret anyone typed.\n */\nfunction literalForms(value: string | undefined): readonly string[] {\n if (value === undefined || value.length < MIN_LITERAL_CHARS || value.length > MAX_LITERAL_CHARS) return []\n const escaped = JSON.stringify(value).slice(1, -1)\n return escaped !== value && escaped.length <= MAX_LITERAL_CHARS * 2 ? [value, escaped] : [value]\n}\n\n/**\n * The literal secrets to remove: from the environment once, raw and JSON-escaped, longest first and at most `MAX_LITERALS`.\n * Never returns names. The cap bounds the cost of scanning every string for every literal; secrets added after the scrubber\n * exists go through `Scrubber.addLiterals`, which does not apply it.\n */\nexport function collectLiterals(\n env: Readonly<Record<string, string | undefined>>,\n extra: readonly string[] = [],\n): readonly string[] {\n const found = new Set<string>()\n const add = (value: string | undefined): void => {\n for (const form of literalForms(value)) found.add(form)\n }\n for (const [name, value] of Object.entries(env)) {\n // `OPENCODE_PASSWORD`, the server's own credential, matches `PASSWORD`.\n if (SECRET_ENV_NAME.test(name)) add(value)\n }\n for (const value of extra) add(value)\n return [...found].toSorted((a, b) => b.length - a.length).slice(0, MAX_LITERALS)\n}\n\n/**\n * Literals longer than this are searched with a search that cannot go quadratic. `String.prototype.indexOf` is fast (native,\n * and skips ahead on a mismatch) but not linear in the worst case: V8 takes seconds to search a megabyte for a 64 KiB literal\n * when each alignment matches almost to the end. Short literals are bounded by their own length, so they stay native.\n */\nconst NATIVE_SEARCH_MAX_CHARS = 64\n\n/** Where a literal can resume after a partial match: `table[i]` is the length of the longest proper border of `literal[0..i]`. */\nfunction failureTable(literal: string): Int32Array {\n const table = new Int32Array(literal.length)\n for (let index = 1, matched = 0; index < literal.length; index += 1) {\n while (matched > 0 && literal.charCodeAt(index) !== literal.charCodeAt(matched)) matched = table[matched - 1] ?? 0\n if (literal.charCodeAt(index) === literal.charCodeAt(matched)) matched += 1\n table[index] = matched\n }\n return table\n}\n\n/**\n * Finds literals in text: every occurrence, overlapping ones included, in time linear in the text for any literal. Tables of\n * the long literals are built on first use and kept, so a scrubber that scrubs many strings builds each once.\n */\nexport interface LiteralSearch {\n /** Calls `found(start, end)` for every occurrence of `literal` in `text`. */\n readonly each: (text: string, literal: string, found: (start: number, end: number) => void) => void\n /** Whether `text` holds `literal`. Stops at the first occurrence. */\n readonly has: (text: string, literal: string) => boolean\n}\n\nexport function createLiteralSearch(): LiteralSearch {\n const tables = new Map<string, Int32Array>()\n const tableOf = (literal: string): Int32Array => {\n let table = tables.get(literal)\n if (table === undefined) {\n table = failureTable(literal)\n tables.set(literal, table)\n }\n return table\n }\n // Calls `found` at each end of an occurrence; returns early when `found` says to stop.\n const scan = (text: string, literal: string, found: (end: number) => boolean): void => {\n const table = tableOf(literal)\n for (let index = 0, matched = 0; index < text.length; index += 1) {\n const code = text.charCodeAt(index)\n while (matched > 0 && code !== literal.charCodeAt(matched)) matched = table[matched - 1] ?? 0\n if (code === literal.charCodeAt(matched)) matched += 1\n if (matched === literal.length) {\n if (found(index + 1)) return\n matched = table[matched - 1] ?? 0\n }\n }\n }\n return {\n each: (text, literal, found) => {\n if (literal.length <= NATIVE_SEARCH_MAX_CHARS) {\n for (let at = text.indexOf(literal); at !== -1; at = text.indexOf(literal, at + 1))\n found(at, at + literal.length)\n return\n }\n scan(text, literal, end => {\n found(end - literal.length, end)\n return false\n })\n },\n has: (text, literal) => {\n if (literal.length <= NATIVE_SEARCH_MAX_CHARS) return text.includes(literal)\n let seen = false\n scan(text, literal, () => {\n seen = true\n return true\n })\n return seen\n },\n }\n}\n\n/**\n * The environment's literal secrets as a matcher: every occurrence of each, overlapping ones included (the union covers a\n * secret that overlaps itself or another). The literals were collected once at start; they are never named.\n */\nexport function literalMatcher(\n literals: readonly string[],\n search: LiteralSearch = createLiteralSearch(),\n): ScrubMatcher {\n return {\n id: 'environment-literal',\n find: (text, _lower, emit) => {\n for (const literal of literals) search.each(text, literal, emit)\n },\n }\n}\n\nexport type ScrubResult =\n | {readonly ok: true; readonly text: string; readonly redactions: number}\n | {\n readonly ok: false\n readonly reason: 'over-input-ceiling' | 'scrub-failed' | 'too-many-ranges' | 'sensitive-value-unbounded'\n }\n\nexport interface Scrubber {\n /** Scrubs one string: the ORIGINAL text in, text with each united range replaced by one marker out. */\n readonly scrub: (text: string) => ScrubResult\n /** The longest string `scrub` accepts; a content attribute whose serialization is longer is omitted unscanned. */\n readonly inputCeilingChars?: number\n /**\n * The safety net, run on every string about to be exported: whether `text` still holds one of the environment's literal\n * secrets (raw or JSON-escaped, the set the literal matcher uses). When it does the caller withholds the whole value. A\n * pure search of the final text: nothing it finds is fed back into the matchers. Each `true` is counted.\n */\n readonly survived?: (text: string) => boolean\n /** How many values `survived` has reported so far. Normally 0: a non-zero count means a matcher missed a known literal. */\n readonly survivalCount?: () => number\n /**\n * Adds literal secrets that became known after the scrubber was created (a credential minted mid-run). Every later `scrub`\n * and `survived` treats them like the construction-time literals: raw and JSON-escaped, with the same length bounds (a value\n * under eight characters is not matched, so it cannot redact ordinary text). Unlike the construction-time set, which keeps\n * only the longest `MAX_LITERALS`, none of these is dropped for want of room: dropping one would export a secret the caller\n * said it knew. A value already known is ignored. The cost of a scrub grows with the number of literals, so a caller adds\n * secrets, not arbitrary text.\n */\n readonly addLiterals?: (values: readonly string[]) => void\n}\n\nexport interface ScrubberOptions {\n /** The plugin's own environment, read once here. */\n readonly env?: Readonly<Record<string, string | undefined>>\n /** Extra literal secrets, such as the trace credential this plugin was configured with. */\n readonly extraSecrets?: readonly string[]\n readonly limits?: Partial<ContentLimits>\n /** Replaces the text rules (tests). The environment's literals are always matched as well. */\n readonly patterns?: readonly ScrubMatcher[]\n}\n\nconst isHighSurrogate = (code: number): boolean => code >= 0xd8_00 && code <= 0xdb_ff\nconst isLowSurrogate = (code: number): boolean => code >= 0xdc_00 && code <= 0xdf_ff\n\n/**\n * The scrub, in one step. Every matcher reads the same original `text`; their ranges are collected, sorted, united (ranges\n * that overlap or touch become one) and the output is built in a single left-to-right pass with one marker per united\n * range. Nothing is ever matched against text a marker was put into, so the result is the same whatever order `matchers`\n * are in, and no rule can make another skip or split a match.\n *\n * The redaction count is the number of united ranges (markers in the output): a range several rules contributed to counts once.\n * A range edge that falls inside a surrogate pair moves outward to the pair's edge, so a lone half is never left behind.\n * Throws `TooManyRangesError` past `MAX_RANGES`: the caller omits the value rather than scan on.\n */\nexport function scrubWithMatchers(\n text: string,\n matchers: readonly ScrubMatcher[],\n): {readonly text: string; readonly redactions: number; readonly withheld: boolean} {\n const lower = text.toLowerCase()\n const starts: number[] = []\n const ends: number[] = []\n let withheld = false\n let overCap = false\n const emit: Emit = (start, end) => {\n if (end <= start || overCap) return\n if (starts.length >= MAX_RANGES) {\n overCap = true\n return\n }\n starts.push(Math.max(0, start))\n ends.push(Math.min(text.length, end))\n }\n const withhold: Withhold = () => {\n withheld = true\n }\n for (const matcher of matchers) matcher.find(text, lower, emit, withhold)\n // Withholding outranks the range cap, so the outcome does not depend on the order the matchers ran in.\n if (withheld) return {text: '', redactions: 0, withheld: true}\n if (overCap) throw new TooManyRangesError()\n if (starts.length === 0) return {text, redactions: 0, withheld: false}\n\n const order = starts.map((_start, index) => index).toSorted((a, b) => (starts[a] ?? 0) - (starts[b] ?? 0))\n let out = ''\n let cursor = 0\n let redactions = 0\n let index = 0\n while (index < order.length) {\n const first = order[index] ?? 0\n let start = starts[first] ?? 0\n let end = ends[first] ?? 0\n index += 1\n // Unite everything that overlaps or touches.\n while (index < order.length && (starts[order[index] ?? 0] ?? 0) <= end) {\n end = Math.max(end, ends[order[index] ?? 0] ?? 0)\n index += 1\n }\n if (start > 0 && isLowSurrogate(text.charCodeAt(start)) && isHighSurrogate(text.charCodeAt(start - 1))) start -= 1\n if (end < text.length && isHighSurrogate(text.charCodeAt(end - 1)) && isLowSurrogate(text.charCodeAt(end))) end += 1\n // A pair-edge move can make this range reach back into the previous one: continue from where that ended.\n if (start < cursor) start = cursor\n out += text.slice(cursor, start) + REDACTION\n cursor = end\n redactions += 1\n }\n return {text: out + text.slice(cursor), redactions, withheld: false}\n}\n\nexport function createScrubber(options: ScrubberOptions = {}): Scrubber {\n const ceiling = options.limits?.inputCeilingChars ?? DEFAULT_CONTENT_LIMITS.inputCeilingChars\n // Mutable: `addLiterals` appends, and the literal matcher reads this same array on every scrub.\n const literals = [...collectLiterals(options.env ?? {}, options.extraSecrets)]\n const known = new Set(literals)\n const search = createLiteralSearch()\n const matchers = [...(options.patterns ?? SCRUB_PATTERNS), literalMatcher(literals, search)]\n let survivals = 0\n return {\n addLiterals: values => {\n for (const value of values) {\n for (const form of literalForms(value)) {\n if (known.has(form)) continue\n known.add(form)\n literals.push(form)\n }\n }\n },\n inputCeilingChars: ceiling,\n survived: text => {\n for (const literal of literals) {\n if (search.has(text, literal)) {\n survivals += 1\n return true\n }\n }\n return false\n },\n survivalCount: () => survivals,\n scrub: text => {\n if (text.length > ceiling) return {ok: false, reason: 'over-input-ceiling'}\n try {\n const result = scrubWithMatchers(text, matchers)\n return result.withheld\n ? {ok: false, reason: 'sensitive-value-unbounded'}\n : {ok: true, text: result.text, redactions: result.redactions}\n } catch (error) {\n return {ok: false, reason: error instanceof TooManyRangesError ? 'too-many-ranges' : 'scrub-failed'}\n }\n },\n }\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n// Bounding\n// ---------------------------------------------------------------------------------------------------------------------\n\ninterface Leaf {\n readonly holder: Record<string, unknown> | unknown[]\n readonly key: string | number\n readonly length: number\n}\n\nconst MAX_DEPTH = 64\n\nfunction collectLeaves(root: unknown): Leaf[] {\n const leaves: Leaf[] = []\n const stack: {value: unknown; depth: number}[] = [{value: root, depth: 0}]\n while (stack.length > 0) {\n const item = stack.pop()\n if (item === undefined || item.depth > MAX_DEPTH) continue\n const {value, depth} = item\n if (Array.isArray(value)) {\n value.forEach((child, index) => {\n if (typeof child === 'string') leaves.push({holder: value, key: index, length: child.length})\n else stack.push({value: child, depth: depth + 1})\n })\n } else if (typeof value === 'object' && value !== null) {\n const record = value as Record<string, unknown>\n for (const key of Object.keys(record)) {\n const child = record[key]\n if (typeof child === 'string') leaves.push({holder: record, key, length: child.length})\n else stack.push({value: child, depth: depth + 1})\n }\n }\n }\n return leaves\n}\n\nconst encodedLength = (text: string): number => JSON.stringify(text).length\n\n/** Cuts a string to `keep` characters without splitting a surrogate pair, and says how much was removed. */\nfunction cutString(text: string, keep: number): string {\n let end = Math.max(0, Math.min(keep, text.length))\n const last = text.charCodeAt(end - 1)\n if (end > 0 && last >= 0xd8_00 && last <= 0xdb_ff) end -= 1\n return `${text.slice(0, end)}${TRUNCATION_SUFFIX(text.length - end)}`\n}\n\nexport interface Bounded {\n readonly json: string\n readonly truncated: boolean\n /** Items dropped from the front of an array (the oldest history), when `dropOldest` applied. */\n readonly dropped: number\n}\n\n/**\n * Bounds a parsed value to `maxChars` of JSON. Oldest array items go first when `dropOldest`; then the longest string\n * leaves are cut. Structure is never cut, so the result is always valid JSON. Undefined: the structure alone is over.\n */\nexport function boundJson(value: unknown, maxChars: number, dropOldest: boolean): Bounded | undefined {\n let json = JSON.stringify(value)\n if (json.length <= maxChars) return {json, truncated: false, dropped: 0}\n let current = value\n let dropped = 0\n if (dropOldest && Array.isArray(value)) {\n const sizes = value.map(item => JSON.stringify(item).length)\n let total = 2 + sizes.reduce((sum, size) => sum + size, 0) + Math.max(0, sizes.length - 1)\n let first = 0\n while (total > maxChars && sizes.length - first > 1) {\n total -= (sizes[first] ?? 0) + 1\n first += 1\n }\n dropped = first\n current = value.slice(first)\n json = JSON.stringify(current)\n if (json.length <= maxChars) return {json, truncated: dropped > 0, dropped}\n }\n const root = structuredClone(current)\n const leaves = collectLeaves(root).toSorted((a, b) => b.length - a.length)\n let excess = json.length - maxChars\n for (const leaf of leaves) {\n // Leaves are longest first: one this short cannot shrink (the suffix is about as long), and neither can the rest.\n if (excess <= 0 || leaf.length <= TRUNCATION_OVERHEAD * 2) break\n const holder = leaf.holder as Record<string | number, unknown>\n const original = holder[leaf.key]\n if (typeof original !== 'string') continue\n const before = encodedLength(original)\n const keep = Math.max(0, original.length - excess - TRUNCATION_OVERHEAD)\n const cut = cutString(original, keep)\n holder[leaf.key] = cut\n excess -= before - encodedLength(cut)\n }\n json = JSON.stringify(root)\n return json.length <= maxChars ? {json, truncated: true, dropped} : undefined\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n// The span that is about to be exported\n// ---------------------------------------------------------------------------------------------------------------------\n\n/** A content attribute: structured, not yet scrubbed or bounded. `scrubSpan` serializes, scrubs, then bounds it. */\nexport interface ContentAttribute {\n readonly kind: 'content'\n readonly value: unknown\n readonly maxChars: number\n /** Drop the oldest array items first when over the bound, and say how many. */\n readonly dropOldest?: boolean\n}\n\nexport const contentAttribute = (value: unknown, maxChars: number, dropOldest = false): ContentAttribute => ({\n kind: 'content',\n value,\n maxChars,\n ...(dropOldest ? {dropOldest} : {}),\n})\n\nconst isContentAttribute = (value: unknown): value is ContentAttribute =>\n typeof value === 'object' && value !== null && !Array.isArray(value) && (value as {kind?: unknown}).kind === 'content'\n\nexport type PlainAttributeValue = string | number | boolean | readonly string[]\nexport type PendingAttributeValue = PlainAttributeValue | ContentAttribute\n\n/**\n * A link from a span to another span, in this trace or another. Ids only: a link carries no text, so nothing in it needs\n * scrubbing and nothing a caller supplies can reach the wire through it.\n */\nexport interface SpanLink {\n /** 32 lowercase hex characters, not all zero. */\n readonly traceId: string\n /** 16 lowercase hex characters, not all zero. */\n readonly spanId: string\n}\n\nconst TRACE_ID = /^(?!0{32}$)[0-9a-f]{32}$/\nconst SPAN_ID = /^(?!0{16}$)[0-9a-f]{16}$/\n\n/**\n * The links whose ids are well formed, in order. An invalid link is dropped; the span that held it is not. Both ids must be\n * strings before either is matched: `RegExp.test` coerces, so an array or an object that stringifies to valid hex would pass.\n */\nexport function validSpanLinks(links: readonly SpanLink[] | undefined): readonly SpanLink[] {\n return (links ?? []).filter(\n link =>\n typeof link.traceId === 'string' &&\n typeof link.spanId === 'string' &&\n TRACE_ID.test(link.traceId) &&\n SPAN_ID.test(link.spanId),\n )\n}\n\nexport interface PendingSpan {\n readonly traceId: string\n readonly spanId: string\n readonly parentSpanId: string | undefined\n readonly name: string\n readonly kind: 'client' | 'internal'\n readonly startMs: number\n readonly endMs: number\n /** Insertion order is processing order: the span's content budget goes to earlier content attributes first. */\n readonly attributes: Readonly<Record<string, PendingAttributeValue>>\n readonly status: {readonly code: 'unset' | 'error'; readonly message?: string | undefined}\n readonly events: readonly {\n readonly name: string\n readonly timeMs: number\n readonly attributes: Readonly<Record<string, string>>\n }[]\n /** Links to other spans. Absent for a span with none. */\n readonly links?: readonly SpanLink[]\n /** Content the hook-time snapshot could not take, as `attribute:reason`. Carried into the span's omission marker. */\n readonly omitted?: readonly string[]\n /** Items already left out before this point (oldest history over the snapshot's ceiling), per attribute. */\n readonly dropped?: Readonly<Record<string, number>>\n}\n\n/** Set only by `scrubSpan`. The exporter takes `ScrubbedSpan`, so a span that skipped the scrubber does not type-check. */\nexport const scrubbedBrand: unique symbol = Symbol('fro-bot.scrubbed-span')\n\nexport interface ScrubbedSpan {\n readonly [scrubbedBrand]: true\n readonly traceId: string\n readonly spanId: string\n readonly parentSpanId: string | undefined\n readonly name: string\n readonly kind: 'client' | 'internal'\n readonly startMs: number\n readonly endMs: number\n readonly attributes: Readonly<Record<string, string | number | boolean | readonly string[]>>\n readonly status: {readonly code: 'unset' | 'error'; readonly message?: string}\n readonly events: readonly {\n readonly name: string\n readonly timeMs: number\n readonly attributes: Readonly<Record<string, string>>\n }[]\n /** Present only when the span had a valid link. */\n readonly links?: readonly SpanLink[]\n}\n\n/** Marker attribute names. Fixed vocabulary: none reflects content. */\nexport const MARKER = {\n redactions: 'fro_bot.content.redactions',\n truncated: 'fro_bot.content.truncated',\n omitted: 'fro_bot.content.omitted',\n dropped: (attribute: string): string => `fro_bot.content.dropped.${attribute}`,\n} as const\n\nconst OMITTED_TEXT = '[omitted]'\n\ninterface Tally {\n redactions: number\n readonly truncated: string[]\n readonly omitted: string[]\n readonly dropped: [string, number][]\n}\n\n/** Scrubs and bounds a plain string. Omitted (with `[omitted]`) when the scrubber cannot handle it. */\nfunction scrubPlain(text: string, label: string, scrubber: Scrubber, limits: ContentLimits, tally: Tally): string {\n const result = safeScrub(scrubber, text)\n if (!result.ok) {\n tally.omitted.push(`${label}:${result.reason}`)\n return OMITTED_TEXT\n }\n tally.redactions += result.redactions\n // The safety net: a known literal that is still here is withheld whole, never rewritten (see `Scrubber.survived`).\n if (scrubber.survived?.(result.text) === true) {\n tally.omitted.push(`${label}:literal-survived`)\n return OMITTED_TEXT\n }\n if (result.text.length <= limits.plainStringChars) return result.text\n tally.truncated.push(label)\n return cutString(result.text, limits.plainStringChars - TRUNCATION_OVERHEAD)\n}\n\nfunction safeScrub(scrubber: Scrubber, text: string): ScrubResult {\n try {\n return scrubber.scrub(text)\n } catch {\n return {ok: false, reason: 'scrub-failed'}\n }\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n// Structured redaction\n// ---------------------------------------------------------------------------------------------------------------------\n\nconst MAX_KEY_CHARS = 200\n/** Nodes visited and depth reached in one structured pass. Past either, the attribute is omitted, not exported. */\nconst MAX_REDACTION_NODES = 500_000\nconst MAX_REDACTION_DEPTH = 64\n\n/** Whether a key's value is removed whole. A counter or limit name keeps a number. */\nfunction isSensitiveKey(key: string, value: unknown): boolean {\n const name = key.slice(0, MAX_KEY_CHARS)\n if (!SENSITIVE_KEY.test(name)) return false\n if (isCounterName(name) && (typeof value === 'number' || (typeof value === 'string' && isShortNumber(value))))\n return false\n return true\n}\n\ninterface TreeWalk {\n nodes: number\n redactions: number\n /** String leaves withheld because a sensitive value's end could not be established. */\n withheld: number\n /** Entries dropped because every key they could take was occupied (see `freeKey`). */\n droppedKeys: number\n}\n\ntype TreeFailureReason = 'over-input-ceiling' | 'scrub-failed' | 'too-many-ranges'\n\nclass TreeFailure extends Error {\n readonly reason: TreeFailureReason\n constructor(reason: TreeFailureReason) {\n super(reason)\n this.reason = reason\n }\n}\n\n/** One string of the structure, scrubbed once, from its original text. A failure fails the whole attribute. */\nfunction scrubLeaf(text: string, scrubber: Scrubber, walk: TreeWalk): string {\n const result = safeScrub(scrubber, text)\n if (!result.ok) {\n // A sensitive value whose end cannot be established withholds THIS leaf; every other failure fails the whole attribute.\n if (result.reason === 'sensitive-value-unbounded') {\n walk.withheld += 1\n return OMITTED_TEXT\n }\n throw new TreeFailure(result.reason)\n }\n walk.redactions += result.redactions\n return result.text\n}\n\n/** The most entries that may share one scrubbed key name (the plain name and the suffixes ` (2)` to ` (64)`). */\nconst MAX_KEY_COLLISIONS = 64\n\n/**\n * The key to write a scrubbed entry under, or undefined when there is none. Two distinct keys that differ only inside text the\n * scrubber redacts become the same text, and the later entry would overwrite the earlier. THE RULE: this only ever returns an\n * unoccupied key, so an entry is never overwritten, whether the occupant is a scrubbed key or a genuine input key that happens to\n * look like a suffixed name (`name (2)`, before or after the colliding keys: a later genuine key is itself a collision with an\n * occupied key and probes from its own name). A colliding key takes ` (2)`, ` (3)`... in order, skipping any that are taken. With\n * every one up to ` (64)` taken, there is no free key: the caller drops the entry and counts it (`key-collision-overflow`). No\n * original text is kept, and the probe is bounded.\n */\nfunction freeKey(target: Record<string, unknown>, name: string): string | undefined {\n if (!Object.prototype.hasOwnProperty.call(target, name)) return name\n for (let n = 2; n <= MAX_KEY_COLLISIONS; n += 1) {\n const candidate = `${name} (${String(n)})`\n if (!Object.prototype.hasOwnProperty.call(target, candidate)) return candidate\n }\n return undefined\n}\n\nfunction scrubNode(value: unknown, depth: number, scrubber: Scrubber, walk: TreeWalk): unknown {\n walk.nodes += 1\n if (walk.nodes > MAX_REDACTION_NODES || depth > MAX_REDACTION_DEPTH) throw new TreeFailure('scrub-failed')\n // THE INVARIANT: every string, key or value, is scrubbed from its ORIGINAL text, in full, before anything is decided about it,\n // and what is returned is that scrubbed text (or the fixed marker): never the source, never a parse of it. A string that\n // happens to look like JSON is just a string; whole-value redaction inside it is the name/value matcher's job.\n if (typeof value === 'string') return scrubLeaf(value, scrubber, walk)\n if (Array.isArray(value)) return value.map(item => scrubNode(item, depth + 1, scrubber, walk))\n if (typeof value === 'object' && value !== null) {\n const copy: Record<string, unknown> = {}\n for (const key of Object.keys(value)) {\n if (key === '__proto__') continue\n const child = (value as Record<string, unknown>)[key]\n if (isSensitiveKey(key, child)) {\n // The whole value goes, whatever its type; nothing inside it is read, and the marker is never scanned.\n walk.redactions += 1\n const slot = freeKey(copy, scrubLeaf(key, scrubber, walk))\n if (slot === undefined) walk.droppedKeys += 1\n else copy[slot] = REDACTION\n } else {\n const slot = freeKey(copy, scrubLeaf(key, scrubber, walk))\n if (slot === undefined) walk.droppedKeys += 1\n else copy[slot] = scrubNode(child, depth + 1, scrubber, walk)\n }\n }\n return copy\n }\n return value\n}\n\n/**\n * Scrubs a structured value (the objects and arrays the plugin itself builds) in ONE walk. A sensitive-named key has its\n * entire value replaced, whatever its type, without reading it; every other string and every key goes through the text\n * matchers once, from its original text. A string that holds JSON is not parsed: it is a string. The two never feed each other:\n * a marker the walk inserts is a node of the output tree, and no matcher ever reads it. The caller serializes the result and\n * does not scan that text again.\n */\nexport function scrubStructured(\n value: unknown,\n scrubber: Scrubber,\n):\n | {\n readonly ok: true\n readonly value: unknown\n readonly redactions: number\n readonly withheld: number\n readonly droppedKeys: number\n }\n | {readonly ok: false; readonly reason: TreeFailureReason} {\n const walk: TreeWalk = {nodes: 0, redactions: 0, withheld: 0, droppedKeys: 0}\n try {\n return {\n ok: true,\n value: scrubNode(value, 0, scrubber, walk),\n redactions: walk.redactions,\n withheld: walk.withheld,\n droppedKeys: walk.droppedKeys,\n }\n } catch (error) {\n return {ok: false, reason: error instanceof TreeFailure ? error.reason : 'scrub-failed'}\n }\n}\n\nfunction serialize(value: unknown): string | undefined {\n try {\n return JSON.stringify(value)\n } catch {\n return undefined\n }\n}\n\n/**\n * The only path to export. Scrubs every string of `span`, bounds content, and returns a span the exporter accepts.\n * Never throws and never lets a raw value through: what cannot be scrubbed is replaced by `[omitted]` or dropped, and\n * the span says so in marker attributes.\n */\nexport function scrubSpan(\n span: PendingSpan,\n scrubber: Scrubber,\n limits: ContentLimits = DEFAULT_CONTENT_LIMITS,\n): ScrubbedSpan {\n const tally: Tally = {redactions: 0, truncated: [], omitted: [...(span.omitted ?? [])], dropped: []}\n let budget = limits.spanContentChars\n const attributes: Record<string, string | number | boolean | readonly string[]> = {}\n\n for (const [name, value] of Object.entries(span.attributes)) {\n if (isContentAttribute(value)) {\n // The serialization of the ORIGINAL value, for the ceiling and to catch what cannot be serialized at all.\n const original = serialize(value.value)\n if (original === undefined) {\n tally.omitted.push(`${name}:unserializable`)\n continue\n }\n if (original.length > (scrubber.inputCeilingChars ?? limits.inputCeilingChars)) {\n tally.omitted.push(`${name}:over-input-ceiling`)\n continue\n }\n const walked = scrubStructured(value.value, scrubber)\n if (!walked.ok) {\n tally.omitted.push(`${name}:${walked.reason}`)\n continue\n }\n tally.redactions += walked.redactions\n // Leaves withheld for an unbounded sensitive value are the marker in the output; the span says so once per attribute.\n if (walked.withheld > 0) tally.omitted.push(`${name}:sensitive-value-unbounded`)\n // Entries dropped for want of a free key: counted once per attribute, with a fixed reason.\n if (walked.droppedKeys > 0) tally.omitted.push(`${name}:key-collision-overflow`)\n // Already scrubbed, leaf by leaf: only serialized here, to bound it, never scanned.\n const json = serialize(walked.value)\n if (json === undefined) {\n tally.omitted.push(`${name}:unserializable`)\n continue\n }\n const parsed: unknown = JSON.parse(json)\n const bounded = boundJson(parsed, Math.min(value.maxChars, Math.max(0, budget)), value.dropOldest === true)\n if (bounded === undefined) {\n tally.omitted.push(`${name}:over-budget`)\n continue\n }\n // The safety net, on the exact text that would be exported.\n if (scrubber.survived?.(bounded.json) === true) {\n tally.omitted.push(`${name}:literal-survived`)\n continue\n }\n budget -= bounded.json.length\n if (bounded.truncated) tally.truncated.push(name)\n const before = span.dropped?.[name] ?? 0\n if (bounded.dropped > 0 || before > 0) tally.dropped.push([name, bounded.dropped + before])\n attributes[name] = bounded.json\n } else if (typeof value === 'string') {\n attributes[name] = scrubPlain(value, name, scrubber, limits, tally)\n } else if (typeof value === 'number' || typeof value === 'boolean') {\n attributes[name] = value\n } else {\n attributes[name] = value.map(item => scrubPlain(item, name, scrubber, limits, tally))\n }\n }\n\n const name = scrubPlain(span.name, 'name', scrubber, limits, tally)\n const statusMessage =\n span.status.message === undefined ? undefined : scrubPlain(span.status.message, 'status', scrubber, limits, tally)\n const events = span.events.map(event => ({\n name: event.name,\n timeMs: event.timeMs,\n attributes: Object.fromEntries(\n Object.entries(event.attributes).map(([key, text]) => [\n key,\n scrubPlain(text, `event.${key}`, scrubber, limits, tally),\n ]),\n ),\n }))\n\n const links = validSpanLinks(span.links).map(link => ({traceId: link.traceId, spanId: link.spanId}))\n // A fixed marker: it names no id and no value.\n if (links.length < (span.links?.length ?? 0)) tally.omitted.push('links:invalid-id')\n\n if (tally.redactions > 0) attributes[MARKER.redactions] = tally.redactions\n if (tally.truncated.length > 0) attributes[MARKER.truncated] = tally.truncated\n if (tally.omitted.length > 0) attributes[MARKER.omitted] = tally.omitted\n for (const [attribute, count] of tally.dropped) attributes[MARKER.dropped(attribute)] = count\n\n return {\n [scrubbedBrand]: true,\n traceId: span.traceId,\n spanId: span.spanId,\n parentSpanId: span.parentSpanId,\n name,\n kind: span.kind,\n startMs: span.startMs,\n endMs: span.endMs,\n attributes,\n status: statusMessage === undefined ? {code: span.status.code} : {code: span.status.code, message: statusMessage},\n events,\n ...(links.length === 0 ? {} : {links}),\n }\n}\n","/**\n * The span exporter: scrubbed spans in, OTLP/HTTP JSON out, with explicit configuration and exact counts.\n *\n * Built on the OpenTelemetry SDK's own pieces, constructed by hand: a tracer provider with a hand-built resource and no\n * detectors (so no process arguments or host data), explicit span limits, an id generator that hands out the ids the turn\n * model already chose, and the SDK's HTTP export delegate. It reads no `OTEL_*` variable and sets no global provider. The\n * `OTLPTraceExporter` class is not used: it merges `OTEL_EXPORTER_OTLP_HEADERS` into the headers it is given.\n *\n * The queue and the batch loop are this module's, not the SDK's batch processor, because the counts matter: the SDK's\n * processor drops silently when full. Here every span ends up counted exactly once, as exported (its batch was accepted)\n * or dropped (queue overflow, a failed batch, the circuit open, or abandoned at shutdown).\n *\n * What the SDK's delegate does with a response (read from `@opentelemetry/otlp-exporter-base` 0.219.0, and pinned by\n * `exporter.test.ts`): status up to 299 is success; 429, 502, 503 and 504 and these network errors (ECONNRESET,\n * ECONNREFUSED, EPIPE, ETIMEDOUT, EAI_AGAIN, ENOTFOUND, ENETUNREACH, EHOSTUNREACH) are retried with backoff (1 s growing\n * by 1.5, at most five retries) until the per-batch timeout; every other status is final, a 3xx included: Node's `http`\n * does not follow redirects and the delegate does not either (pinned by `exporter.test.ts`), so the credential in a\n * local-mode header goes only to the URL in the settings file, which must be `https` for a remote collector with\n * certificate verification left at the platform default (the plugin's `settings.ts` accepts nothing else). The relay's `503` is\n * therefore a retry and its `422` a drop. One batch is in flight at a time, far under the relay's refusal threshold of eight;\n * the next one starts only after the delegate has finished with the last (see `startBatch`).\n */\n\nimport type {ReadableSpan, SpanProcessor} from '@opentelemetry/sdk-trace-base'\nimport type {ScrubbedSpan} from './scrub.js'\n\nimport {Buffer} from 'node:buffer'\n\nimport {ROOT_CONTEXT, SpanKind, SpanStatusCode, trace, TraceFlags} from '@opentelemetry/api'\nimport {OTLPExporterBase} from '@opentelemetry/otlp-exporter-base'\nimport {createOtlpHttpExportDelegate, httpAgentFactoryFromOptions} from '@opentelemetry/otlp-exporter-base/node-http'\nimport {JsonTraceSerializer} from '@opentelemetry/otlp-transformer'\nimport {resourceFromAttributes} from '@opentelemetry/resources'\nimport {AlwaysOnSampler, BasicTracerProvider} from '@opentelemetry/sdk-trace-base'\n\nimport {CONTENT_ATTRIBUTE_NAMES, MARKER, validSpanLinks} from './scrub.js'\n\n/**\n * The request header that carries the plugin's running totals to the Action's relay, in Action mode only.\n * MIRRORS `TRACE_RELAY_COUNTS_HEADER` and `formatTraceRelayCountsHeader` in `packages/runtime/src/agent/trace-relay-wire.ts`,\n * which is the source of truth: this module does not import it, because that module reaches the network and IP\n * classification code and the plugin bundles this one whole. `runtime-parity.test.ts` pins the two together. The form is\n * exactly `exported=<n>;dropped=<n>`, each `n` one to twelve ASCII digits.\n */\nexport const TRACE_COUNTS_HEADER = 'x-frobot-trace-counts'\n\n/** Largest total the header can carry: twelve digits. Beyond it a count saturates rather than break the form. */\nconst MAX_COUNT = 999_999_999_999\n\nexport interface SpanCounts {\n readonly exported: number\n readonly dropped: number\n}\n\n/** The header value for `counts`. */\nexport function formatCountsHeader(counts: SpanCounts): string {\n return `exported=${Math.min(counts.exported, MAX_COUNT)};dropped=${Math.min(counts.dropped, MAX_COUNT)}`\n}\n\nexport interface ExporterLimits {\n /** Spans waiting for export. A span past this is dropped and counted. */\n readonly maxQueueSpans: number\n /** Estimated bytes waiting for export. */\n /** Encoded bytes waiting for export (each span counted at the size it will have on the wire). */\n readonly maxQueueBytes: number\n readonly maxBatchSpans: number\n /**\n * The most bytes in one request BODY, as encoded on the wire (UTF-8 bytes of the OTLP JSON, envelope included). Exact, not\n * estimated: every span is serialized once when it is queued, and a batch closes before its body would pass this. A span that\n * alone would pass it has its content omitted (see `exportSpan`) or is dropped; nothing over the limit is ever sent.\n */\n readonly maxBatchBytes: number\n /** From the first queued span to its batch. Short, so a trace is visible soon after the turn. */\n readonly batchIntervalMs: number\n /**\n * One batch, retries included. Above the relay's own upstream timeout (8 s) so the plugin never gives up on a forward\n * the relay is still making, which would send the same batch twice.\n */\n readonly requestTimeoutMs: number\n /** After this many failed batches in a row, exporting stops and everything else is dropped. */\n readonly maxConsecutiveFailures: number\n}\n\n/**\n * The most the collector's front proxy accepts in one request body: 4.5 MiB. Over it the answer is 413, which is final, so the\n * batch is lost. (Measured there: 4,192,616 bytes accepted, 5 MiB refused.) `maxBatchBytes` stays at least half a mebibyte under\n * it, and under the Action relay's own body cap (16 MiB, `trace-relay.ts`); `runtime-parity.test.ts` pins both relations.\n */\nexport const COLLECTOR_BODY_LIMIT_BYTES = 4_718_592\n\nexport const DEFAULT_EXPORTER_LIMITS: ExporterLimits = {\n maxQueueSpans: 512,\n maxQueueBytes: 32 * 1024 * 1024,\n maxBatchSpans: 32,\n maxBatchBytes: 4_000_000,\n batchIntervalMs: 1_000,\n requestTimeoutMs: 10_000,\n maxConsecutiveFailures: 3,\n}\n\n/**\n * SDK span limits, set explicitly so no `OTEL_*` variable and no SDK default cuts content the plugin already bounded.\n * The value-length limit is unbounded because `scrubSpan` has bounded every value; the count limits are the SDK's own\n * defaults (a span carries about 45 attributes and at most one event), stated here so they cannot be changed from outside.\n */\nexport const SDK_SPAN_LIMITS = {\n attributeValueLengthLimit: Number.POSITIVE_INFINITY,\n attributeCountLimit: 128,\n eventCountLimit: 128,\n linkCountLimit: 128,\n attributePerEventCountLimit: 128,\n attributePerLinkCountLimit: 128,\n} as const\n\nexport interface SpanExporterOptions {\n /** Full OTLP traces URL. */\n readonly url: string\n /** The resource's `service.name`, and the tracer's name: which sender a span came from. Fixed text, never content. */\n readonly serviceName: string\n readonly headers: Readonly<Record<string, string>>\n /** Action mode: send the running counts on every batch. Local mode: never. */\n readonly reportCounts: boolean\n readonly limits?: Partial<ExporterLimits>\n /** Called once if the circuit opens. Fixed text only. */\n readonly onStopped?: () => void\n /** Test seams only; nothing in production sets them. */\n readonly testing?: {\n /** Cancelling a request cannot reach its socket: the delegate never lets go, as if its transport could not be stopped. */\n readonly ignoreAgentDestroy?: boolean\n }\n}\n\nexport interface SpanExporter {\n /** Queues a span. Never throws; a span that cannot be queued is counted as dropped. */\n readonly export: (span: ScrubbedSpan) => void\n readonly counts: () => SpanCounts\n /** Counts spans that never reached `export`, for example one whose mapping failed, so the totals stay honest. */\n readonly drop: (spans?: number) => void\n /**\n * Stops accepting spans, exports what is queued within `boundMs`, counts whatever is left as dropped, and returns the\n * final totals.\n */\n readonly close: (boundMs: number) => Promise<SpanCounts>\n}\n\ninterface Queued {\n readonly span: ReadableSpan\n readonly size: number\n}\n\n/** The most content attributes omitted from one span to bring it under the body limit, and the smallest one worth omitting. */\n/** How long the delegate may take to let go of a cancelled request before the transport is given up on. */\nconst DRAIN_GRACE_MS = 1_000\nconst MAX_OMISSIONS = 32\nconst MIN_OMIT_BYTES = 256\n\nconst hrTime = (ms: number): [number, number] => {\n const seconds = Math.floor(ms / 1000)\n return [seconds, Math.round((ms - seconds * 1000) * 1e6)]\n}\n\nconst sleep = async (ms: number): Promise<void> =>\n new Promise(resolve => {\n setTimeout(resolve, ms).unref()\n })\n\n/** What an attribute costs on the wire: its key and its value as JSON, in UTF-8 bytes (the OTLP JSON encodes a string as JSON does). */\nconst wireBytes = (name: string, value: string): number =>\n Buffer.byteLength(JSON.stringify(name), 'utf8') + Buffer.byteLength(JSON.stringify(value), 'utf8')\n\n/**\n * The span without the content attribute that costs the most bytes on the wire, which it names in the omission marker; or\n * undefined. Only the content attributes are candidates (never identity, outcome or any other metadata), ranked by encoded bytes\n * saved, not by character count: escaped or multi-byte text costs far more than its length says.\n */\nfunction omitLargestContent(span: ScrubbedSpan): ScrubbedSpan | undefined {\n let largest: string | undefined\n let weight = 0\n for (const name of CONTENT_ATTRIBUTE_NAMES) {\n const value = span.attributes[name]\n if (typeof value !== 'string') continue\n const bytes = wireBytes(name, value)\n if (bytes > weight) {\n largest = name\n weight = bytes\n }\n }\n // Nothing of content is left to omit: whatever makes the span too large is not something that can be taken out.\n if (largest === undefined || weight < MIN_OMIT_BYTES) return undefined\n const attributes: Record<string, string | number | boolean | readonly string[]> = {}\n for (const [name, value] of Object.entries(span.attributes)) if (name !== largest) attributes[name] = value\n const marked = span.attributes[MARKER.omitted]\n attributes[MARKER.omitted] = [...(typeof marked === 'object' ? marked : []), `${largest}:span-too-large`]\n return {...span, attributes}\n}\n\nexport function createSpanExporter(options: SpanExporterOptions): SpanExporter {\n const limits: ExporterLimits = {...DEFAULT_EXPORTER_LIMITS, ...options.limits}\n let exported = 0\n let dropped = 0\n let queue: Queued[] = []\n let queuedBytes = 0\n // The batch the delegate holds. `counted` and \"the delegate has let go\" are separate facts: a batch is counted (exported or\n // dropped) once, by whichever of its result, the watchdog or shutdown comes first, while `inFlight` stays set until the delegate\n // has drained (its slot is free), because a batch handed to an occupied delegate is refused and its spans would be lost.\n let inFlight: {readonly done: Promise<void>; readonly size: number; counted: boolean} | undefined\n let timer: NodeJS.Timeout | undefined\n let consecutiveFailures = 0\n let tripped = false\n let closed = false\n\n // The next ids the SDK hands to a span: the ones the turn model already chose, so records and parents agree.\n let nextTraceId = ''\n let nextSpanId = ''\n const idGenerator = {generateTraceId: () => nextTraceId, generateSpanId: () => nextSpanId}\n\n const counts = (): SpanCounts => ({exported, dropped})\n const baseHeaders = {'Content-Type': 'application/json', ...options.headers}\n\n // The SDK's delegate cannot be told to stop: its shutdown does nothing, and a retry is a timer it does not expose. Two\n // things under our control cancel it: the agent (destroying it closes every open socket, so an in-flight request fails at\n // once) and the headers function, which the transport awaits before EVERY request including each retry (once cancelled it\n // throws, so no further request is made). Both are used at the cleanup deadline.\n let cancelled = false\n // Set while the request of a batch the watchdog gave up on is being cancelled: nothing may be sent until the delegate lets go.\n let cancelling = false\n let agent: {readonly destroy: () => void} | undefined\n const makeAgent = httpAgentFactoryFromOptions({keepAlive: true, rejectUnauthorized: true})\n\n const exporter = new OTLPExporterBase<ReadableSpan[]>(\n createOtlpHttpExportDelegate(\n {\n url: options.url,\n // Read on every request, so each batch carries the totals as of its start.\n headers: async () => {\n if (cancelled || cancelling) throw new Error('export cancelled')\n return options.reportCounts\n ? {...baseHeaders, [TRACE_COUNTS_HEADER]: formatCountsHeader(counts())}\n : baseHeaders\n },\n timeoutMillis: limits.requestTimeoutMs,\n // One batch in flight is enforced here; the delegate's own limit is a second guard.\n concurrencyLimit: 1,\n compression: 'none',\n // Certificate validation is set here, for every https export, so a process-wide `NODE_TLS_REJECT_UNAUTHORIZED=0` cannot\n // turn it off: the credential in a local-mode header goes only to a destination whose certificate verified.\n agentFactory: async protocol => {\n const made = await makeAgent(protocol)\n agent = options.testing?.ignoreAgentDestroy === true ? undefined : made\n return made\n },\n },\n JsonTraceSerializer,\n ),\n )\n\n // The span the SDK just finished, handed over by the processor to `build`, which sizes it before it is queued.\n let ended: ReadableSpan | undefined\n // The bytes of a request body that are not spans (the resource and the scope); derived from the first span, see `spanBytes`.\n let envelopeBytes = 0\n const processor: SpanProcessor = {\n onStart: () => {},\n onEnd: span => {\n ended = span\n },\n forceFlush: async () => {},\n shutdown: async () => {},\n }\n const provider = new BasicTracerProvider({\n // Hand-built: no detectors, so no process arguments, host name or environment-derived attributes.\n resource: resourceFromAttributes({'service.name': options.serviceName}),\n sampler: new AlwaysOnSampler(),\n idGenerator,\n spanLimits: SDK_SPAN_LIMITS,\n generalLimits: {\n attributeCountLimit: SDK_SPAN_LIMITS.attributeCountLimit,\n attributeValueLengthLimit: Number.POSITIVE_INFINITY,\n },\n spanProcessors: [processor],\n })\n const tracer = provider.getTracer(options.serviceName)\n\n function trip(): void {\n // Shutdown's permanent cancellation (`cancelled`) already counted the queue and returned the totals: a stop announced after\n // close() has returned would report a state the caller no longer sees.\n if (tripped || cancelled) return\n tripped = true\n dropped += queue.length\n queue = []\n queuedBytes = 0\n if (timer !== undefined) clearTimeout(timer)\n timer = undefined\n try {\n options.onStopped?.()\n } catch {\n // A log failure must not matter.\n }\n }\n\n function takeBatch(): Queued[] {\n const batch: Queued[] = []\n // The body is the envelope, the spans' own JSON, and a comma between each pair: exact, so the sum is the request's size.\n let bytes = envelopeBytes\n while (queue.length > 0 && batch.length < limits.maxBatchSpans) {\n const next = queue[0]\n if (next === undefined) break\n if (batch.length > 0 && bytes + batch.length + next.size > limits.maxBatchBytes) break\n batch.push(next)\n bytes += next.size\n queue.shift()\n queuedBytes -= next.size\n }\n return batch\n }\n\n /**\n * Cancels the request the delegate holds and waits, for a bound, until it has let go of its slot. Used when the watchdog gives\n * up on a batch: the SDK's request timeout is an IDLE timeout on the socket, so a collector that keeps the connection active\n * (a response that trickles) outlasts the watchdog, and the next batch handed to the delegate would be refused as over its\n * concurrency limit. Destroying the agent closes every open socket, which ends the request, and the headers function refuses\n * every request until the delegate has drained. If it has not drained within the grace period the transport cannot be stopped:\n * the breaker trips (everything queued is counted dropped) and nothing more is sent.\n */\n async function cancelInFlight(): Promise<void> {\n cancelling = true\n try {\n agent?.destroy()\n } catch {\n // The headers function still stops every further request.\n }\n const drained = await Promise.race([\n exporter.forceFlush().then(\n () => true,\n () => true,\n ),\n sleep(DRAIN_GRACE_MS).then(() => false),\n ])\n if (drained) {\n cancelling = false\n return\n }\n trip()\n cancelled = true\n }\n\n function startBatch(): void {\n if (inFlight !== undefined || queue.length === 0 || tripped) return\n const batch = takeBatch()\n const current = {counted: false, size: batch.length} as {done: Promise<void>; size: number; counted: boolean}\n /** Counts the batch, once, whatever order the result, the watchdog and shutdown come in. */\n const settle = (ok: boolean): void => {\n if (current.counted) return\n current.counted = true\n if (ok) {\n exported += batch.length\n consecutiveFailures = 0\n } else {\n dropped += batch.length\n consecutiveFailures += 1\n if (consecutiveFailures >= limits.maxConsecutiveFailures) trip()\n }\n }\n current.done = new Promise<void>(resolve => {\n // A watchdog over the whole batch, in case a result never comes back: a lost result is a failed batch. The request is then\n // cancelled and the next batch waits until the delegate has let go of it.\n const watchdog = setTimeout(() => {\n settle(false)\n cancelInFlight().then(resolve, resolve)\n }, limits.requestTimeoutMs + 2_000)\n watchdog.unref()\n try {\n exporter.export(\n batch.map(item => item.span),\n result => {\n clearTimeout(watchdog)\n settle(result.code === 0)\n // The delegate calls this from inside the promise it keeps in its own in-flight set (`otlp-export-delegate.js`:\n // `this._promiseQueue.pushPromise(this._transport.send(...).then(response => { ...resultCallback(...) }))`), and\n // takes that promise out of the set only AFTER it settles (`bounded-queue-export-promise-handler.js`:\n // `promise.then(popPromise, popPromise)`). Starting the next batch from here would find the set still full and be\n // refused with `Concurrent export limit reached` (a whole batch counted dropped). So the batch is not over until the\n // delegate says nothing is in flight: `forceFlush()` is `Promise.all` over that set, and the set's own removal was\n // registered on the same promise first, so by the time it resolves the entry is gone.\n exporter.forceFlush().then(resolve, resolve)\n },\n )\n } catch {\n clearTimeout(watchdog)\n settle(false)\n resolve()\n }\n }).finally(() => {\n inFlight = undefined\n if (!closed) schedule()\n })\n inFlight = current\n }\n\n function schedule(): void {\n if (timer !== undefined || queue.length === 0 || inFlight !== undefined || tripped || closed) return\n if (queue.length >= limits.maxBatchSpans) {\n startBatch()\n return\n }\n timer = setTimeout(() => {\n timer = undefined\n startBatch()\n }, limits.batchIntervalMs)\n timer.unref()\n }\n\n /** Hands the SDK a span with the ids the turn model chose, and returns what it ended up with, or undefined. */\n function build(span: ScrubbedSpan): ReadableSpan | undefined {\n const parent =\n span.parentSpanId === undefined\n ? ROOT_CONTEXT\n : trace.setSpanContext(ROOT_CONTEXT, {\n traceId: span.traceId,\n spanId: span.parentSpanId,\n traceFlags: TraceFlags.SAMPLED,\n })\n const links = validSpanLinks(span.links)\n nextTraceId = span.traceId\n nextSpanId = span.spanId\n ended = undefined\n const sdkSpan = tracer.startSpan(\n span.name,\n {\n kind: span.kind === 'client' ? SpanKind.CLIENT : SpanKind.INTERNAL,\n startTime: hrTime(span.startMs),\n attributes: {...span.attributes} as Record<string, string | number | boolean | string[]>,\n // Re-checked here: an id the SDK cannot use would otherwise be dropped without a trace.\n ...(links.length === 0\n ? {}\n : {\n links: links.map(link => ({\n context: {traceId: link.traceId, spanId: link.spanId, traceFlags: TraceFlags.SAMPLED},\n })),\n }),\n },\n // Always explicit: an ambient context another library registered in this process must never become a parent.\n parent,\n )\n if (span.status.code === 'error') {\n sdkSpan.setStatus({\n code: SpanStatusCode.ERROR,\n ...(span.status.message === undefined ? {} : {message: span.status.message}),\n })\n }\n for (const event of span.events) sdkSpan.addEvent(event.name, {...event.attributes}, hrTime(event.timeMs))\n // `end` hands the finished span to the processor above, which leaves it in `ended`.\n sdkSpan.end(hrTime(span.endMs))\n const finished = ended\n ended = undefined\n return finished\n }\n\n function encodedLength(spans: ReadableSpan[]): number {\n const body = JsonTraceSerializer.serializeRequest(spans)\n if (body === undefined) throw new Error('nothing to encode')\n return body.byteLength\n }\n\n /**\n * The span's own bytes in a request body, exact: the body of a request holding it alone, less the envelope (the resource and the\n * scope, the same for every span). The envelope is derived once, from the first span: a request of one span is `E + a`, of the\n * same span twice `E + 2a + 1` (a comma), so `a` is the difference less one and `E` is what is left. The sum for a batch of n is\n * then `E + (a1 + ... + an) + (n - 1)`, which is what the delegate's serializer produces (pinned by `exporter.test.ts`).\n */\n function spanBytes(readable: ReadableSpan): number {\n const alone = encodedLength([readable])\n if (envelopeBytes === 0) {\n const twice = encodedLength([readable, readable])\n envelopeBytes = alone - (twice - alone - 1)\n }\n return alone - envelopeBytes\n }\n\n function exportSpan(span: ScrubbedSpan): void {\n try {\n if (closed || tripped || queue.length >= limits.maxQueueSpans) {\n dropped += 1\n return\n }\n // Sized once, exactly, before it is queued. A span that alone would pass the body limit has its largest content omitted,\n // again and again up to a bound, so the span itself still arrives; one that cannot be brought under is dropped and counted.\n let candidate = span\n for (let attempt = 0; ; attempt += 1) {\n const readable = build(candidate)\n if (readable === undefined) {\n dropped += 1\n return\n }\n const size = spanBytes(readable)\n if (envelopeBytes + size <= limits.maxBatchBytes) {\n if (queuedBytes + size > limits.maxQueueBytes) {\n dropped += 1\n return\n }\n queue.push({span: readable, size})\n queuedBytes += size\n break\n }\n const trimmed = attempt < MAX_OMISSIONS ? omitLargestContent(candidate) : undefined\n if (trimmed === undefined) {\n dropped += 1\n return\n }\n candidate = trimmed\n }\n schedule()\n } catch {\n dropped += 1\n }\n }\n\n return {\n export: exportSpan,\n counts,\n drop: (spans = 1) => {\n dropped += spans\n },\n close: async boundMs => {\n closed = true\n if (timer !== undefined) clearTimeout(timer)\n timer = undefined\n const deadline = Date.now() + boundMs\n for (;;) {\n // `tripped` and the queue change as batches settle.\n if (tripped || (queue.length === 0 && inFlight === undefined)) break\n const remaining = deadline - Date.now()\n if (remaining <= 0) break\n if (inFlight === undefined) startBatch()\n const waiting = inFlight\n if (waiting === undefined) break\n await Promise.race([waiting.done, sleep(remaining)])\n }\n // Whatever is still queued or in flight is cancelled and counted dropped (a request already fully received may still have\n // been accepted: a dropped count is an upper bound, and the Action-mode counts header, which only has exported and\n // dropped, reports it the same way).\n // What this does not cancel: the SDK's retry wait. `retrying-transport.js` holds it as a plain, referenced `setTimeout`\n // (v0.219.0, no handle exposed, and the package's exports map allows no deep import to build the transport ourselves), so\n // a host that waits for its event loop to drain stays up until it fires. That timer is bounded by the request timeout\n // (`requestTimeoutMs`, 10 s): the wait is at most 5 s of backoff, or a server-sent `Retry-After` up to the time left of the\n // request. Measured with `Retry-After: 9`: the process exits about 7.4 s after cleanup returns; without it, about 0.5 to\n // 1.1 s. When it fires the headers function above throws, so nothing is sent. OpenCode's server does not wait for it.\n cancelled = true\n try {\n agent?.destroy()\n } catch {\n // Nothing more can be done: the headers function stops every further request.\n }\n if (inFlight !== undefined && !inFlight.counted) {\n dropped += inFlight.size\n inFlight.counted = true\n }\n dropped += queue.length\n queue = []\n queuedBytes = 0\n // Shut the transport down without waiting on a request that is still open.\n await Promise.race([exporter.shutdown().catch(() => {}), sleep(250)])\n return counts()\n },\n }\n}\n","/**\n * Span content: extraction by named field, the content ceilings, and the Action identity attributes.\n *\n * Scrubbing and bounding live in the shared runtime (`@fro-bot/runtime/tracing/scrub`): `scrubSpan` is the only way to\n * produce a `ScrubbedSpan`, and the exporter takes nothing else. They are re-exported here so the rest of the plugin keeps\n * one import site for \"span content\". The plugin bundles that module inline; it never imports the runtime when it runs.\n *\n * Extraction is plain functions over what OpenCode reports, by named field: no SDK, no I/O, no clock.\n */\n\nimport type {ActionIdentity} from './settings.js'\n\nexport * from '@fro-bot/runtime/tracing/scrub'\n\n/** Per-attribute ceilings for content, in serialized characters. */\nexport const CONTENT_MAX_CHARS = {\n systemInstructions: 128 * 1024,\n toolDefinitions: 128 * 1024,\n inputMessages: 512 * 1024,\n outputMessages: 128 * 1024,\n toolArguments: 64 * 1024,\n toolResult: 64 * 1024,\n prompt: 64 * 1024,\n} as const\n\n// ---------------------------------------------------------------------------------------------------------------------\n// Extraction by named field\n// ---------------------------------------------------------------------------------------------------------------------\n\ntype Json = Record<string, unknown>\nconst isRecord = (value: unknown): value is Json => typeof value === 'object' && value !== null && !Array.isArray(value)\nconst asString = (value: unknown): string | undefined => (typeof value === 'string' ? value : undefined)\n\n/** `gen_ai.system_instructions`: `[{type: 'text', content}]`. Takes each part's `text` and nothing else (no metadata). */\nexport function extractSystemInstructions(system: unknown): {type: 'text'; content: string}[] | undefined {\n if (!Array.isArray(system)) return undefined\n const parts: {type: 'text'; content: string}[] = []\n for (const part of system) {\n const text = isRecord(part) ? asString(part.text) : undefined\n if (text !== undefined) parts.push({type: 'text', content: text})\n }\n return parts.length === 0 ? undefined : parts\n}\n\nexport interface MessageExtraction {\n readonly messages: readonly Json[]\n /** Parts that were attachments or of a kind this plugin does not read, counted, never serialized. */\n readonly omittedParts: number\n}\n\n/** The value of a tool result part as the spec's `response`: text for `text` and `content`, the value for `json`. */\nfunction responseOf(result: unknown): unknown {\n if (!isRecord(result)) return result\n const value = result.value\n if (result.type === 'content' && Array.isArray(value)) {\n return value\n .map(item => {\n if (!isRecord(item)) return ''\n if (item.type === 'text') return asString(item.text) ?? ''\n return `[file: ${asString(item.name) ?? asString(item.mime) ?? 'attachment'}]`\n })\n .join('\\n')\n }\n return value\n}\n\nfunction messagePart(part: unknown): {part?: Json; omitted: boolean} {\n if (!isRecord(part)) return {omitted: true}\n switch (part.type) {\n case 'text': {\n const text = asString(part.text)\n return text === undefined ? {omitted: true} : {part: {type: 'text', content: text}, omitted: false}\n }\n case 'reasoning': {\n const text = asString(part.text)\n return text === undefined ? {omitted: true} : {part: {type: 'reasoning', content: text}, omitted: false}\n }\n case 'tool-call':\n return {\n part: {\n type: 'tool_call',\n id: asString(part.id) ?? null,\n name: asString(part.name) ?? 'unknown',\n arguments: part.input,\n },\n omitted: false,\n }\n case 'tool-result':\n return {\n part: {type: 'tool_call_response', id: asString(part.id) ?? null, response: responseOf(part.result)},\n omitted: false,\n }\n default:\n // media, files and anything unknown: not serialized.\n return {omitted: true}\n }\n}\n\n/** `gen_ai.input.messages`: role and parts of each message, by named field. */\nexport function extractInputMessages(messages: unknown): MessageExtraction | undefined {\n if (!Array.isArray(messages)) return undefined\n const out: Json[] = []\n let omittedParts = 0\n for (const message of messages) {\n if (!isRecord(message)) continue\n const role = asString(message.role)\n if (role === undefined) continue\n const content = message.content\n const rawParts =\n typeof content === 'string' ? [{type: 'text', text: content}] : Array.isArray(content) ? content : []\n const parts: Json[] = []\n for (const raw of rawParts) {\n const {part, omitted} = messagePart(raw)\n if (part !== undefined) parts.push(part)\n if (omitted) omittedParts += 1\n }\n out.push({role, parts})\n }\n return {messages: out, omittedParts}\n}\n\n/** `gen_ai.tool.definitions`: `[{type: 'function', name, description, parameters}]`. */\nexport function extractToolDefinitions(tools: unknown): Json[] | undefined {\n if (!isRecord(tools)) return undefined\n const names = Object.keys(tools)\n if (names.length === 0) return undefined\n return names.map(name => {\n const tool = tools[name]\n const description = isRecord(tool) ? asString(tool.description) : undefined\n const parameters = isRecord(tool) && isRecord(tool.input) ? tool.input : undefined\n return {\n type: 'function',\n name,\n ...(description === undefined ? {} : {description}),\n ...(parameters === undefined ? {} : {parameters}),\n }\n })\n}\n\n/** `gen_ai.tool.call.arguments`: an object. A string is parsed; anything else is wrapped as `{value}`. */\nexport function extractToolArguments(input: unknown): Json | undefined {\n if (input === undefined) return undefined\n if (isRecord(input)) return input\n if (typeof input === 'string') {\n try {\n const parsed: unknown = JSON.parse(input)\n if (isRecord(parsed)) return parsed\n } catch {\n // Not JSON: wrapped below.\n }\n }\n return {value: input}\n}\n\nexport interface ToolResultExtraction {\n readonly value: Json\n /** The tool reported that it cut its own output. */\n readonly ownTruncation: boolean\n}\n\n/**\n * `gen_ai.tool.call.result`: the content the model saw, `{content: [...]}` (files by name and type only, never their\n * location), or `{output}` for a tool that returned only structured output. Metadata is not captured; only its\n * `truncated` flag, as a marker.\n */\nexport function extractToolResult(result: unknown): ToolResultExtraction | undefined {\n if (!isRecord(result)) return undefined\n const metadata = isRecord(result.metadata) ? result.metadata : undefined\n const ownTruncation = metadata?.truncated === true\n const content = result.content\n if (typeof content === 'string') return {value: {content: [{type: 'text', text: content}]}, ownTruncation}\n if (Array.isArray(content)) {\n const parts = content.flatMap((item): Json[] => {\n if (!isRecord(item)) return []\n if (item.type === 'text') return [{type: 'text', text: asString(item.text) ?? ''}]\n if (item.type === 'file') {\n const name = asString(item.name)\n return [\n {\n type: 'file',\n mime: asString(item.mime) ?? 'application/octet-stream',\n ...(name === undefined ? {} : {name}),\n },\n ]\n }\n return []\n })\n return {value: {content: parts}, ownTruncation}\n }\n if (result.output !== undefined) return {value: {output: result.output}, ownTruncation}\n return undefined\n}\n\nexport interface OutputInput {\n readonly texts: readonly string[]\n readonly reasoning: readonly string[]\n readonly toolCalls: readonly {readonly callId: string; readonly tool: string; readonly input?: unknown}[]\n}\n\n/** `gen_ai.output.messages`: one assistant message with reasoning, text and the tool calls the response asked for. */\nexport function extractOutputMessages(output: OutputInput): Json[] | undefined {\n const parts: Json[] = [\n ...output.reasoning.map(content => ({type: 'reasoning', content})),\n ...output.texts.map(content => ({type: 'text', content})),\n ...output.toolCalls.map(call => ({\n type: 'tool_call',\n id: call.callId,\n name: call.tool,\n arguments: extractToolArguments(call.input) ?? null,\n })),\n ]\n return parts.length === 0 ? undefined : [{role: 'assistant', parts}]\n}\n\n/** A user prompt's `text`, as an input message. Attachments are not read. */\nexport function extractPromptMessage(prompt: unknown): Json | undefined {\n const text = isRecord(prompt) ? asString(prompt.text) : undefined\n return text === undefined ? undefined : {role: 'user', parts: [{type: 'text', content: text}]}\n}\n\n/**\n * Identity the Action supplies, as the attributes every span of its runs carries: the `fro_bot.*` names, and a mirror of each\n * under `langfuse.trace.metadata.<key>`. Langfuse's OTLP ingestion (`extractMetadata` in langfuse/langfuse\n * `OtelIngestionProcessor.ts`) reads every `langfuse.trace.metadata.*` attribute of every span into that span's metadata at the top\n * level, where it is shown and filterable, and treats a span carrying one as a trace update; a string value is kept as sent\n * (JSON-decoding applies only to its own SDKs). The values are strings and the very same ones as their twins, so they pass the\n * same scrubber and identifier bounds. The keys are short and stable.\n *\n * The launcher's invocation id, when it has one, is part of the same identity: it names the one Action step that started the\n * server, which `run.id`, `run.attempt` and `job` cannot do (two steps of one job share all three).\n */\nexport const actionIdentityAttributes = (\n identity: ActionIdentity,\n invocationId?: string | undefined,\n): Record<string, string> => ({\n 'fro_bot.repository': identity.repository,\n 'fro_bot.run.id': identity.runId,\n 'fro_bot.run.attempt': identity.attempt,\n 'fro_bot.job': identity.job,\n 'fro_bot.trigger': identity.trigger,\n 'langfuse.trace.metadata.repository': identity.repository,\n 'langfuse.trace.metadata.run_id': identity.runId,\n 'langfuse.trace.metadata.run_attempt': identity.attempt,\n 'langfuse.trace.metadata.job': identity.job,\n 'langfuse.trace.metadata.trigger': identity.trigger,\n ...(invocationId === undefined\n ? {}\n : {'fro_bot.invocation.id': invocationId, 'langfuse.trace.metadata.invocation_id': invocationId}),\n})\n","/**\n * The hook-time snapshot: an immutable, bounded copy of exactly the named fields the content module reads, taken before\n * the hook returns.\n *\n * Why: a hook's input is a live object. OpenCode, or a plugin that runs after this one, may edit it once the hook has\n * returned, and a span must say what the model request carried when the hook fired, not what a later edit made of it. So\n * the handler copies the named fields (system text, message text, tool definitions, tool arguments and results) into\n * frozen values and keeps nothing of the input. Strings are immutable, so a string is shared, not copied: the cost is the\n * walk over the structure, not the bytes. Scrubbing, bounding and serialization still happen later, off the host's path.\n *\n * What a snapshot is NOT: it is not scrubbed. It holds the raw named content until the one scrub pass at export.\n *\n * Bounds. Each snapshot has a size ceiling of its own, and every held snapshot counts against a ledger (count and\n * characters) that is separate from the exporter's queue. Past a bound, a field is replaced by an `OmittedContent` marker,\n * which the attribute mapping turns into a marker on the span, so a span keeps its structure and says what is missing.\n * For a request over its ceiling the oldest history messages go first and the snapshot says how many.\n *\n * Each snapshot is raw-shaped (the same field names the host uses, pruned to the named fields), so the extractors in\n * `content.ts` read a snapshot exactly as they would read the host's input.\n *\n * Plain functions: no SDK, no I/O, no clock. Nothing here throws; anything unreadable becomes `OmittedContent`.\n */\n\ntype Json = Record<string, unknown>\n\nconst isRecord = (value: unknown): value is Json => typeof value === 'object' && value !== null && !Array.isArray(value)\nconst asString = (value: unknown): string | undefined => (typeof value === 'string' ? value : undefined)\n\nexport interface SnapshotLimits {\n /** Characters of one request snapshot: system, tool definitions and the newest history that fits. */\n readonly requestChars: number\n readonly systemChars: number\n readonly toolDefinitionChars: number\n /** One prompt, one tool call's arguments, one tool result. At the scrubber's input ceiling: over it the value would be omitted anyway. */\n readonly valueChars: number\n /**\n * A JSON-string argument longer than this is carried as the text it is (`{value: text}`), not parsed: parsing is the one\n * step whose cost is not a walk we count.\n */\n readonly argumentParseChars: number\n /** Depth of a copied value. Past it (a cycle included) the value is omitted. */\n readonly maxDepth: number\n /**\n * Everything visited in one snapshot: objects, arrays, strings, and every entry looked at and skipped (a part left as a\n * placeholder, an entry that is not a message). One budget for the whole request, so a huge array of cheap things is stopped.\n */\n readonly maxNodes: number\n}\n\nexport const DEFAULT_SNAPSHOT_LIMITS: SnapshotLimits = {\n requestChars: 4 * 1024 * 1024,\n systemChars: 512 * 1024,\n toolDefinitionChars: 512 * 1024,\n valueChars: 8 * 1024 * 1024,\n argumentParseChars: 256 * 1024,\n maxDepth: 24,\n maxNodes: 200_000,\n}\n\nexport interface PendingLimits {\n /** Snapshots held at once: taken in a hook and not yet exported or dropped. */\n readonly maxPending: number\n /** Characters held at once, across all pending snapshots. */\n readonly maxPendingChars: number\n}\n\nexport const DEFAULT_PENDING_LIMITS: PendingLimits = {maxPending: 256, maxPendingChars: 32 * 1024 * 1024}\n\nexport type OmissionReason = 'snapshot-bound' | 'pending-bound' | 'unreadable'\n\n/** In place of a field that was not captured. A value, not an error: the attribute mapping reads it into a span marker. */\nexport interface OmittedContent {\n readonly kind: 'snapshot-omitted'\n readonly reason: OmissionReason\n}\n\n/** Stands for a message part that is not copied (media, files, anything unknown); the count of these is the parts left out. */\nconst PLACEHOLDER: Json = Object.freeze({type: 'omitted'})\n\nconst OMITTED: Readonly<Record<OmissionReason, OmittedContent>> = {\n 'snapshot-bound': Object.freeze({kind: 'snapshot-omitted', reason: 'snapshot-bound'}),\n 'pending-bound': Object.freeze({kind: 'snapshot-omitted', reason: 'pending-bound'}),\n unreadable: Object.freeze({kind: 'snapshot-omitted', reason: 'unreadable'}),\n}\n\nexport const omittedContent = (reason: OmissionReason): OmittedContent => OMITTED[reason]\n\n/** The reason a field was omitted, or undefined when `value` is real content. */\nexport function omittedReason(value: unknown): OmissionReason | undefined {\n if (!isRecord(value) || value.kind !== 'snapshot-omitted') return undefined\n const reason = value.reason\n return reason === 'snapshot-bound' || reason === 'pending-bound' || reason === 'unreadable' ? reason : undefined\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n// The ledger of pending snapshots\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport interface LedgerStats {\n readonly pending: number\n readonly pendingChars: number\n /** Snapshots refused because the ledger was full. */\n readonly refused: number\n}\n\nexport interface SnapshotLedger {\n /** Characters a new snapshot may take, or undefined when the ledger is full by count or by characters. */\n readonly room: () => number | undefined\n /** Records a snapshot as pending. Idempotent per snapshot. */\n readonly hold: (snapshot: object, chars: number) => void\n /** Gives a held snapshot one more owner: it is freed when every owner has released it. Ignored if not held. */\n readonly retain: (snapshot: unknown) => void\n /** One owner lets go; the last frees it. Safe on anything: a value the ledger does not hold is ignored. */\n readonly release: (snapshot: unknown) => void\n /** Notes a snapshot refused for lack of room. */\n readonly refuse: () => void\n readonly stats: () => LedgerStats\n}\n\n/**\n * Counts what is pending. Freed explicitly when the span the snapshot belongs to is exported or dropped. A snapshot that\n * leaves the pipeline by some other route (a discarded observation, a model failure) is freed when it is garbage\n * collected, so a leak on a rare path costs delay, never a permanent hole in the budget.\n */\nexport function createSnapshotLedger(options: Partial<PendingLimits> = {}): SnapshotLedger {\n const limits: PendingLimits = {...DEFAULT_PENDING_LIMITS, ...options}\n /** Characters and the number of owners that have not released it yet. */\n const held = new WeakMap<object, {readonly chars: number; owners: number}>()\n let pending = 0\n let pendingChars = 0\n let refused = 0\n const free = (chars: number): void => {\n pending = Math.max(0, pending - 1)\n pendingChars = Math.max(0, pendingChars - chars)\n }\n const backstop = new FinalizationRegistry<number>(free)\n return {\n room: () => {\n if (pending >= limits.maxPending) return undefined\n const remaining = limits.maxPendingChars - pendingChars\n return remaining > 0 ? remaining : undefined\n },\n hold: (snapshot, chars) => {\n if (held.has(snapshot)) return\n held.set(snapshot, {chars, owners: 1})\n pending += 1\n pendingChars += chars\n backstop.register(snapshot, chars, snapshot)\n },\n retain: snapshot => {\n if (typeof snapshot !== 'object' || snapshot === null) return\n const entry = held.get(snapshot)\n if (entry !== undefined) entry.owners += 1\n },\n release: snapshot => {\n if (typeof snapshot !== 'object' || snapshot === null) return\n const entry = held.get(snapshot)\n if (entry === undefined) return\n entry.owners -= 1\n if (entry.owners > 0) return\n held.delete(snapshot)\n backstop.unregister(snapshot)\n free(entry.chars)\n },\n refuse: () => {\n refused += 1\n },\n stats: () => ({pending, pendingChars, refused}),\n }\n}\n\nexport interface SnapshotContext {\n readonly ledger?: SnapshotLedger | undefined\n readonly limits?: Partial<SnapshotLimits> | undefined\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n// Bounded, frozen copy\n// ---------------------------------------------------------------------------------------------------------------------\n\n/** Nodes visited so far, shared by every meter of one snapshot so the budget is request-wide. */\ninterface NodeCount {\n nodes: number\n}\n\ninterface Meter {\n readonly limit: number\n readonly maxDepth: number\n readonly maxNodes: number\n readonly shared: NodeCount\n chars: number\n over: boolean\n}\n\nconst meterFor = (limit: number, limits: SnapshotLimits, shared: NodeCount = {nodes: 0}): Meter => ({\n limit,\n maxDepth: limits.maxDepth,\n maxNodes: limits.maxNodes,\n shared,\n chars: 0,\n over: false,\n})\n\nfunction spend(meter: Meter, chars: number, nodes: number): boolean {\n meter.chars += chars\n meter.shared.nodes += nodes\n if (meter.chars > meter.limit || meter.shared.nodes > meter.maxNodes) meter.over = true\n return !meter.over\n}\n\nfunction readKey(source: Json, key: string): unknown {\n try {\n return source[key]\n } catch {\n // A getter that throws: the field is not read.\n return undefined\n }\n}\n\n/** A frozen deep copy of a JSON-like value. Sets `meter.over` and returns undefined when a bound is crossed. */\nfunction copyValue(value: unknown, meter: Meter, depth: number): unknown {\n if (meter.over) return undefined\n switch (typeof value) {\n case 'string':\n spend(meter, value.length, 1)\n return value\n case 'number':\n case 'boolean':\n spend(meter, 8, 1)\n return value\n case 'bigint':\n spend(meter, 24, 1)\n return value.toString()\n case 'object': {\n if (value === null) {\n spend(meter, 4, 1)\n return meter.over ? undefined : null\n }\n if (depth >= meter.maxDepth) {\n meter.over = true\n return undefined\n }\n if (!spend(meter, 8, 1)) return undefined\n if (Array.isArray(value)) {\n const items: unknown[] = []\n // Every slot is charged BEFORE it is read or allocated, holes and nulls included, so a huge sparse or null-filled\n // array stops at the budget instead of being walked and copied.\n for (const element of value) {\n if (!spend(meter, 4, 1)) return undefined\n items.push(copyValue(element, meter, depth + 1) ?? null)\n if (meter.over) return undefined\n }\n return Object.freeze(items)\n }\n const copy: Json = {}\n for (const key of Object.keys(value)) {\n if (key === '__proto__') continue\n const child = copyValue(readKey(value as Json, key), meter, depth + 1)\n if (meter.over) return undefined\n if (child === undefined) continue\n spend(meter, key.length, 0)\n copy[key] = child\n }\n return Object.freeze(copy)\n }\n case 'undefined':\n case 'function':\n case 'symbol':\n // Not content.\n return undefined\n }\n}\n\nfunction copyBounded(\n value: unknown,\n limit: number,\n limits: SnapshotLimits,\n): {value: unknown; chars: number} | undefined {\n const meter = meterFor(limit, limits)\n const copy = copyValue(value, meter, 0)\n return meter.over ? undefined : {value: copy, chars: meter.chars}\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n// The four snapshots\n// ---------------------------------------------------------------------------------------------------------------------\n\n/** A request's content, raw-shaped: `system`, `messages` and `tools` pruned to the named fields. */\nexport interface RequestSnapshot {\n readonly system?: readonly {readonly text: string}[] | OmittedContent\n readonly messages?: readonly Json[] | OmittedContent\n readonly tools?: Readonly<Record<string, {readonly description?: string; readonly input?: unknown}>> | OmittedContent\n /**\n * Entries of the history not kept (the oldest, left out to fit the snapshot's bounds). Counted by arithmetic on the\n * array's length, so it is an upper bound: it also counts entries that were not messages.\n */\n readonly droppedMessages?: number\n /** Characters this snapshot holds; what the ledger counts. */\n readonly size: number\n}\n\nexport interface PromptSnapshot {\n readonly text?: string | OmittedContent\n readonly size: number\n}\n\nexport interface ToolResultSnapshot {\n readonly content?: string | readonly Json[]\n readonly output?: unknown\n readonly metadata?: {readonly truncated: boolean}\n readonly size: number\n}\n\nfunction resolve(context: SnapshotContext): {limits: SnapshotLimits; room: number | undefined} {\n const limits: SnapshotLimits = {...DEFAULT_SNAPSHOT_LIMITS, ...context.limits}\n const room = context.ledger === undefined ? Number.POSITIVE_INFINITY : context.ledger.room()\n if (room === undefined) context.ledger?.refuse()\n return {limits, room}\n}\n\nfunction pruneToolResultValue(value: unknown, type: unknown, meter: Meter): unknown {\n if (type === 'content' && Array.isArray(value)) {\n const items: Json[] = []\n for (const item of value) {\n if (!isRecord(item)) {\n spend(meter, 0, 1)\n if (meter.over) return undefined\n items.push(Object.freeze({type: 'text', text: ''}))\n continue\n }\n if (item.type === 'text') {\n const text = asString(readKey(item, 'text')) ?? ''\n spend(meter, text.length, 1)\n items.push(Object.freeze({type: 'text', text}))\n } else {\n // Files are named, never carried: the name and type are all the span reads.\n const name = asString(readKey(item, 'name'))\n const mime = asString(readKey(item, 'mime'))\n spend(meter, (name?.length ?? 0) + (mime?.length ?? 0), 1)\n items.push(\n Object.freeze({type: 'file', ...(name === undefined ? {} : {name}), ...(mime === undefined ? {} : {mime})}),\n )\n }\n if (meter.over) return undefined\n }\n return Object.freeze(items)\n }\n return copyValue(value, meter, 1)\n}\n\nfunction pruneMessagePart(part: unknown, meter: Meter): Json {\n // Every part visited costs a node, the ones that are only a placeholder included.\n spend(meter, 0, 1)\n if (meter.over || !isRecord(part)) return PLACEHOLDER\n const type = readKey(part, 'type')\n switch (type) {\n case 'text':\n case 'reasoning': {\n const text = asString(readKey(part, 'text'))\n if (text === undefined) return PLACEHOLDER\n spend(meter, text.length, 1)\n return Object.freeze({type, text})\n }\n case 'tool-call': {\n const input = copyValue(readKey(part, 'input'), meter, 2)\n return Object.freeze({\n type,\n ...(asString(readKey(part, 'id')) === undefined ? {} : {id: readKey(part, 'id')}),\n ...(asString(readKey(part, 'name')) === undefined ? {} : {name: readKey(part, 'name')}),\n ...(input === undefined ? {} : {input}),\n })\n }\n case 'tool-result': {\n const result = readKey(part, 'result')\n const resultType = isRecord(result) ? readKey(result, 'type') : undefined\n const value = isRecord(result) ? pruneToolResultValue(readKey(result, 'value'), resultType, meter) : undefined\n return Object.freeze({\n type,\n ...(asString(readKey(part, 'id')) === undefined ? {} : {id: readKey(part, 'id')}),\n result: Object.freeze({type: resultType, ...(value === undefined ? {} : {value})}),\n })\n }\n default:\n // Media, files and anything unknown are not copied; the placeholder keeps the count of parts left out.\n return PLACEHOLDER\n }\n}\n\nfunction pruneMessage(raw: unknown, meter: Meter): Json | undefined {\n if (!isRecord(raw)) return undefined\n const role = asString(readKey(raw, 'role'))\n if (role === undefined) return undefined\n spend(meter, role.length, 1)\n const content = readKey(raw, 'content')\n if (typeof content === 'string') {\n spend(meter, content.length, 1)\n return Object.freeze({role, content})\n }\n const parts: Json[] = []\n if (Array.isArray(content)) {\n for (const part of content) {\n parts.push(pruneMessagePart(part, meter))\n if (meter.over) break\n }\n }\n return Object.freeze({role, content: Object.freeze(parts)})\n}\n\nfunction pruneSystem(\n system: unknown,\n limit: number,\n limits: SnapshotLimits,\n shared: NodeCount,\n): {value: RequestSnapshot['system']; chars: number} | undefined {\n if (!Array.isArray(system)) return undefined\n const meter = meterFor(limit, limits, shared)\n const parts: {text: string}[] = []\n for (const part of system) {\n spend(meter, 0, 1)\n if (meter.over) return {value: omittedContent('snapshot-bound'), chars: 0}\n const text = isRecord(part) ? asString(readKey(part, 'text')) : undefined\n if (text === undefined) continue\n spend(meter, text.length, 1)\n parts.push(Object.freeze({text}))\n if (meter.over) return {value: omittedContent('snapshot-bound'), chars: 0}\n }\n return {value: Object.freeze(parts), chars: meter.chars}\n}\n\nfunction pruneTools(\n tools: unknown,\n limit: number,\n limits: SnapshotLimits,\n shared: NodeCount,\n): {value: RequestSnapshot['tools']; chars: number} | undefined {\n if (!isRecord(tools)) return undefined\n const meter = meterFor(limit, limits, shared)\n const copy: Record<string, {description?: string; input?: unknown}> = {}\n for (const name of Object.keys(tools)) {\n if (name === '__proto__') continue\n spend(meter, 0, 1)\n if (meter.over) return {value: omittedContent('snapshot-bound'), chars: 0}\n const tool = readKey(tools, name)\n if (!isRecord(tool)) continue\n spend(meter, name.length, 1)\n const description = asString(readKey(tool, 'description'))\n if (description !== undefined) spend(meter, description.length, 0)\n const rawInput = readKey(tool, 'input')\n const input = isRecord(rawInput) ? copyValue(rawInput, meter, 1) : undefined\n if (meter.over) return {value: omittedContent('snapshot-bound'), chars: 0}\n copy[name] = Object.freeze({\n ...(description === undefined ? {} : {description}),\n ...(input === undefined ? {} : {input}),\n })\n }\n return {value: Object.freeze(copy), chars: meter.chars}\n}\n\nfunction omittedRequest(reason: OmissionReason): RequestSnapshot {\n const omitted = omittedContent(reason)\n return Object.freeze({system: omitted, messages: omitted, tools: omitted, size: 0})\n}\n\n/**\n * The request a `context`, `compaction`, `generate` or `title` hook carries, as it is now. Takes the system text, each\n * message's role and text/reasoning/tool-call/tool-result parts, and each tool's name, description and input schema.\n * Never takes the request's model or options objects, headers, attachments or binary parts.\n */\nexport function snapshotRequest(\n input: {readonly system?: unknown; readonly messages?: unknown; readonly tools?: unknown},\n context: SnapshotContext = {},\n): RequestSnapshot {\n try {\n const {limits, room} = resolve(context)\n if (room === undefined) return omittedRequest('pending-bound')\n const total = Math.min(limits.requestChars, room)\n // One node budget for the whole request: the system text, the tools and every message draw on it.\n const shared: NodeCount = {nodes: 0}\n const system = pruneSystem(input.system, Math.min(limits.systemChars, total), limits, shared)\n let used = system?.chars ?? 0\n const tools = pruneTools(\n input.tools,\n Math.min(limits.toolDefinitionChars, Math.max(0, total - used)),\n limits,\n shared,\n )\n used += tools?.chars ?? 0\n\n // The newest history that fits, kept in order. The walk ends at the first message that does not fit or when the node\n // budget is spent, and what is older is counted by its length, not walked: the cost is the budget's, not the history's.\n let messages: RequestSnapshot['messages']\n let droppedMessages = 0\n if (Array.isArray(input.messages)) {\n const kept: Json[] = []\n let remaining = Math.max(0, total - used)\n let index = input.messages.length - 1\n for (; index >= 0; index -= 1) {\n // An entry costs a node whether or not it is a message.\n shared.nodes += 1\n if (shared.nodes > limits.maxNodes) break\n const meter = meterFor(remaining, limits, shared)\n const message = pruneMessage(input.messages[index], meter)\n if (message === undefined) continue\n if (meter.over) break\n remaining -= meter.chars\n used += meter.chars\n kept.push(message)\n }\n // Entries not kept, by length: an upper bound, since it also counts entries that were not messages.\n droppedMessages = index + 1\n kept.reverse()\n messages = Object.freeze(kept)\n }\n\n const snapshot: RequestSnapshot = Object.freeze({\n ...(system === undefined ? {} : {system: system.value}),\n ...(messages === undefined ? {} : {messages}),\n ...(tools === undefined ? {} : {tools: tools.value}),\n ...(droppedMessages > 0 ? {droppedMessages} : {}),\n size: used,\n })\n context.ledger?.hold(snapshot, used)\n return snapshot\n } catch {\n return omittedRequest('unreadable')\n }\n}\n\n/** A user prompt's `text`. Attachments are not read. */\nexport function snapshotPrompt(prompt: unknown, context: SnapshotContext = {}): PromptSnapshot {\n try {\n const {limits, room} = resolve(context)\n if (room === undefined) return Object.freeze({text: omittedContent('pending-bound'), size: 0})\n const text = isRecord(prompt) ? asString(readKey(prompt, 'text')) : undefined\n if (text === undefined) return Object.freeze({size: 0})\n if (text.length > Math.min(limits.valueChars, room)) {\n return Object.freeze({text: omittedContent('snapshot-bound'), size: 0})\n }\n const snapshot: PromptSnapshot = Object.freeze({text, size: text.length})\n context.ledger?.hold(snapshot, text.length)\n return snapshot\n } catch {\n return Object.freeze({text: omittedContent('unreadable'), size: 0})\n }\n}\n\n/** A tool call's arguments: an object, as the span carries it. A JSON string is parsed; any other value is wrapped. */\nexport function snapshotToolArguments(\n input: unknown,\n context: SnapshotContext = {},\n): Json | OmittedContent | undefined {\n try {\n if (input === undefined) return undefined\n const {limits, room} = resolve(context)\n if (room === undefined) return omittedContent('pending-bound')\n let value: unknown = input\n if (typeof input === 'string') {\n // Length first: a string over its bound is omitted unparsed, and one over the parse ceiling is carried as text.\n if (input.length > Math.min(limits.valueChars, room)) return omittedContent('snapshot-bound')\n value = {value: input}\n if (input.length <= limits.argumentParseChars) {\n try {\n const parsed: unknown = JSON.parse(input)\n if (isRecord(parsed)) value = parsed\n } catch {\n // Not JSON: wrapped.\n }\n }\n } else if (!isRecord(input)) {\n value = {value: input}\n }\n const copy = copyBounded(value, Math.min(limits.valueChars, room), limits)\n if (copy === undefined || !isRecord(copy.value)) return omittedContent('snapshot-bound')\n context.ledger?.hold(copy.value, copy.chars)\n return copy.value\n } catch {\n return omittedContent('unreadable')\n }\n}\n\n/**\n * A tool result: the content the model saw (text, and files by name and type only), `output` for a tool that returned\n * only structured output, and whether the tool cut its own output. Metadata is not taken.\n */\nexport function snapshotToolResult(\n result: unknown,\n context: SnapshotContext = {},\n): ToolResultSnapshot | OmittedContent | undefined {\n try {\n if (!isRecord(result)) return undefined\n const {limits, room} = resolve(context)\n if (room === undefined) return omittedContent('pending-bound')\n const meter = meterFor(Math.min(limits.valueChars, room), limits)\n const raw = readKey(result, 'content')\n let content: string | readonly Json[] | undefined\n if (typeof raw === 'string') {\n spend(meter, raw.length, 1)\n content = raw\n } else if (Array.isArray(raw)) {\n const parts: Json[] = []\n for (const item of raw) {\n spend(meter, 0, 1)\n if (meter.over) break\n if (!isRecord(item)) continue\n const type = readKey(item, 'type')\n if (type === 'text') {\n const text = asString(readKey(item, 'text')) ?? ''\n spend(meter, text.length, 1)\n parts.push(Object.freeze({type: 'text', text}))\n } else if (type === 'file') {\n const name = asString(readKey(item, 'name'))\n const mime = asString(readKey(item, 'mime'))\n spend(meter, (name?.length ?? 0) + (mime?.length ?? 0), 1)\n parts.push(\n Object.freeze({type: 'file', ...(mime === undefined ? {} : {mime}), ...(name === undefined ? {} : {name})}),\n )\n }\n if (meter.over) break\n }\n content = Object.freeze(parts)\n }\n const output = content === undefined ? copyValue(readKey(result, 'output'), meter, 1) : undefined\n if (meter.over) return omittedContent('snapshot-bound')\n const metadata = readKey(result, 'metadata')\n const truncated = isRecord(metadata) && readKey(metadata, 'truncated') === true\n if (content === undefined && output === undefined) return undefined\n const snapshot: ToolResultSnapshot = Object.freeze({\n ...(content === undefined ? {} : {content}),\n ...(output === undefined ? {} : {output}),\n metadata: Object.freeze({truncated}),\n size: meter.chars,\n })\n context.ledger?.hold(snapshot, meter.chars)\n return snapshot\n } catch {\n return omittedContent('unreadable')\n }\n}\n\n/** The size a snapshot reports, for the buffer bound; zero for anything else. */\nexport function snapshotSize(value: unknown): number {\n return isRecord(value) && typeof value.size === 'number' ? value.size : 0\n}\n","/**\n * Span records to GenAI-convention attributes.\n *\n * Pinned to the OpenTelemetry GenAI semantic conventions at `open-telemetry/semantic-conventions-genai` commit\n * `76e0c19` (attribute registry `docs/registry/attributes/gen-ai.md`; JSON shapes `model/gen-ai/gen-ai-input-messages.json`,\n * `-output-messages.json`, `-system-instructions.json`, `-tool-definitions.json`, `-tool-call-arguments.json`,\n * `-tool-call-result.json`). The conventions are in Development: a revision bump is a deliberate change here.\n *\n * What follows from that revision:\n * - Span names: `chat {model}`, `invoke_agent {agent}`, `execute_tool {tool}`.\n * - `gen_ai.usage.input_tokens` includes cached tokens (`cache_read` and `cache_write` are included in it) and\n * `gen_ai.usage.output_tokens` includes reasoning tokens. OpenCode reports them split, so they are summed here.\n * - Content (`gen_ai.input.messages`, `output.messages`, `system_instructions`, `tool.definitions`, `tool.call.arguments`,\n * `tool.call.result`) is an AnyValue; the JavaScript SDK carries attributes as primitives, so each is a JSON string\n * conforming to the schema, which Langfuse and Tempo both read.\n * - `gen_ai.response.finish_reasons` carries the provider's reason; for a failed generation the revision says to report\n * `error` rather than omit, and `interrupted` for one that was cut short.\n *\n * An uncaptured field sets no attribute: it is named in `fro_bot.span.gaps` instead. Identity and markers outside the\n * convention use the `fro_bot.` prefix, so they never collide with OpenCode's own `opencode.*` attributes.\n */\n\nimport type {ActionIdentity, ActionRunContext} from './settings.js'\nimport type {ChatRecord, InvokeRecord, SpanRecord, ToolRecord} from './turn-model.js'\n\nimport {\n actionIdentityAttributes,\n CONTENT_MAX_CHARS,\n contentAttribute,\n extractInputMessages,\n extractOutputMessages,\n extractPromptMessage,\n extractSystemInstructions,\n extractToolArguments,\n extractToolDefinitions,\n extractToolResult,\n MARKER,\n scrubSpan,\n type ContentLimits,\n type PendingAttributeValue,\n type PendingSpan,\n type ScrubbedSpan,\n type Scrubber,\n} from './content.js'\nimport {omittedReason} from './snapshot.js'\n\nexport const GENAI_SEMCONV_REVISION = 'open-telemetry/semantic-conventions-genai@76e0c19'\n\nexport interface AttributeOptions extends ActionRunContext {\n /** Set in Action mode: repository and run identity go on every span. Absent in local mode: none do. */\n readonly identity?: ActionIdentity | undefined\n}\n\ntype Attributes = Record<string, PendingAttributeValue>\n\n/** Set only when the value is defined: an uncaptured field sets no attribute. */\nfunction set(attributes: Attributes, name: string, value: PendingAttributeValue | undefined): void {\n if (value !== undefined) attributes[name] = value\n}\n\nfunction identityAttributes(record: SpanRecord, options: AttributeOptions): Attributes {\n const attributes: Attributes = {\n 'session.id': record.sessionId,\n 'gen_ai.conversation.id': record.sessionId,\n 'fro_bot.root_session.id': record.rootSessionId,\n // Langfuse's OTLP ingestion reads the session from `langfuse.session.id` first and from `session.id` only when that is absent\n // (`extractSessionId` in langfuse/langfuse `OtelIngestionProcessor.ts`; the keys are listed in that order, and the docs'\n // attribute-mapping table names both), and it groups its Sessions view by it. Every span of a tree carries the ROOT session's\n // id here, so a subagent shows under its parent's session; `session.id` stays each span's own session. It is set on every span,\n // not only the root: Langfuse filters and aggregates per observation. The turn model sets `rootSessionId` when a child's\n // dispatch link resolves (a child that finished before its link is replayed with it), and an unlinked session is its own root.\n // An Action run overrides it with the launcher's session id, which the Action computed (`<owner>/<repo>:<logical key>`) so the\n // run's own trace and every turn trace share one Langfuse session. It is used verbatim: never derived or altered here.\n 'langfuse.session.id': options.sessionId ?? record.rootSessionId,\n }\n set(attributes, 'gen_ai.agent.name', record.agent)\n if (options.identity !== undefined) {\n Object.assign(attributes, actionIdentityAttributes(options.identity, options.invocationId))\n }\n return attributes\n}\n\nfunction outcomeAttributes(record: SpanRecord): Attributes {\n const attributes: Attributes = {'fro_bot.outcome': record.status}\n if (record.marks.length > 0) attributes['fro_bot.span.marks'] = record.marks\n if (record.gaps.length > 0) attributes['fro_bot.span.gaps'] = record.gaps\n if (record.status === 'error' && record.error?.type !== undefined) attributes['error.type'] = record.error.type\n return attributes\n}\n\nfunction statusOf(record: SpanRecord): PendingSpan['status'] {\n if (record.status !== 'error') return {code: 'unset'}\n return {code: 'error', message: record.error?.message ?? record.error?.type ?? 'error'}\n}\n\nfunction eventsOf(record: SpanRecord): PendingSpan['events'] {\n if (record.status !== 'error' || record.error === undefined) return []\n const attributes: Record<string, string> = {'exception.type': record.error.type}\n if (record.error.message !== undefined) attributes['exception.message'] = record.error.message\n return [{name: 'exception', timeMs: record.end, attributes}]\n}\n\n/** OpenCode's split counts to the convention's totals. */\nfunction usageAttributes(usage: ChatRecord['usage']): Attributes {\n if (usage === undefined) return {}\n const attributes: Attributes = {\n 'gen_ai.usage.input_tokens': usage.input + usage.cacheRead + usage.cacheWrite,\n 'gen_ai.usage.output_tokens': usage.output + usage.reasoning,\n }\n if (usage.cacheRead > 0) attributes['gen_ai.usage.cache_read.input_tokens'] = usage.cacheRead\n if (usage.cacheWrite > 0) attributes['gen_ai.usage.cache_write.input_tokens'] = usage.cacheWrite\n if (usage.reasoning > 0) attributes['gen_ai.usage.reasoning.output_tokens'] = usage.reasoning\n return attributes\n}\n\nfunction finishReasons(record: ChatRecord): readonly string[] | undefined {\n // A span whose step data was withheld (binding uncertain) has an unknown response, not an interrupted one.\n if (record.gaps.includes('step-binding-uncertain')) return undefined\n const reported = record.rawFinishReason ?? record.finishReason\n if (reported !== undefined) return [reported]\n if (record.status === 'error') return ['error']\n if (record.status === 'interrupted') return ['interrupted']\n return undefined\n}\n\n/**\n * The value of a snapshot field, or undefined when the snapshot could not take it: the omission is then recorded under the\n * attribute's name, and the span says so in its markers.\n */\nfunction noting(value: unknown, attribute: string, omitted: string[]): unknown {\n const reason = omittedReason(value)\n if (reason === undefined) return value\n omitted.push(`${attribute}:${reason}`)\n return undefined\n}\n\nfunction chatSpan(record: ChatRecord, options: AttributeOptions): PendingSpan {\n const omitted: string[] = []\n const preDropped: Record<string, number> = {}\n const attributes: Attributes = {\n 'gen_ai.operation.name': 'chat',\n ...identityAttributes(record, options),\n ...outcomeAttributes(record),\n 'fro_bot.request.kind': record.requestKind,\n // The request content is what the hook saw when it fired. A later plugin's edits are not in it.\n 'fro_bot.content.view': 'hook-time',\n }\n set(attributes, 'gen_ai.provider.name', record.provider)\n set(attributes, 'gen_ai.request.model', record.model)\n if (record.requestKind === 'primary') attributes['fro_bot.request.attempt'] = record.attempt\n // Retried below the hook where nothing observes it: one span stands for however many provider attempts there were.\n if (record.attemptCountUnknown) attributes['fro_bot.request.attempt_count_unknown'] = true\n set(attributes, 'gen_ai.response.finish_reasons', finishReasons(record))\n Object.assign(attributes, usageAttributes(record.usage))\n if (record.cost !== undefined) attributes['fro_bot.usage.cost_usd'] = record.cost\n if (record.followOnOf.length > 0) attributes['fro_bot.turn.follow_on_of'] = record.followOnOf\n\n // Content, in the order the span's budget is spent: the small values first, the long history last. The request is the\n // hook-time snapshot; a field it could not take is a sentinel, which becomes a marker on the span.\n const request = (record.request ?? {}) as {\n system?: unknown\n messages?: unknown\n tools?: unknown\n droppedMessages?: unknown\n }\n const system = extractSystemInstructions(noting(request.system, 'gen_ai.system_instructions', omitted))\n if (system !== undefined)\n attributes['gen_ai.system_instructions'] = contentAttribute(system, CONTENT_MAX_CHARS.systemInstructions)\n const definitions = extractToolDefinitions(noting(request.tools, 'gen_ai.tool.definitions', omitted))\n if (definitions !== undefined)\n attributes['gen_ai.tool.definitions'] = contentAttribute(definitions, CONTENT_MAX_CHARS.toolDefinitions)\n const output = extractOutputMessages({texts: record.texts, reasoning: record.reasoning, toolCalls: record.toolCalls})\n if (output !== undefined)\n attributes['gen_ai.output.messages'] = contentAttribute(output, CONTENT_MAX_CHARS.outputMessages)\n const input = extractInputMessages(noting(request.messages, 'gen_ai.input.messages', omitted))\n if (typeof request.droppedMessages === 'number' && request.droppedMessages > 0) {\n preDropped['gen_ai.input.messages'] = request.droppedMessages\n }\n if (input !== undefined) {\n if (input.omittedParts > 0) attributes['fro_bot.content.parts_omitted'] = input.omittedParts\n attributes['gen_ai.input.messages'] = contentAttribute(input.messages, CONTENT_MAX_CHARS.inputMessages, true)\n }\n\n return {\n traceId: record.traceId,\n spanId: record.spanId,\n parentSpanId: record.parentSpanId,\n name: `chat ${record.model ?? record.requestKind}`,\n kind: 'client',\n startMs: record.start,\n endMs: record.end,\n attributes,\n status: statusOf(record),\n events: eventsOf(record),\n ...(omitted.length === 0 ? {} : {omitted}),\n ...(Object.keys(preDropped).length === 0 ? {} : {dropped: preDropped}),\n }\n}\n\nfunction toolSpan(record: ToolRecord, options: AttributeOptions): PendingSpan {\n const attributes: Attributes = {\n 'gen_ai.operation.name': 'execute_tool',\n ...identityAttributes(record, options),\n ...outcomeAttributes(record),\n 'gen_ai.tool.name': record.tool,\n 'gen_ai.tool.call.id': record.callId,\n 'gen_ai.tool.type': 'function',\n 'fro_bot.tool.outcome': record.outcome,\n }\n set(attributes, 'fro_bot.tool.error_type', record.errorType)\n set(attributes, 'fro_bot.subagent.session_id', record.childSessionId)\n if (record.providerExecuted) attributes['fro_bot.tool.provider_executed'] = true\n\n const omitted: string[] = []\n const args = extractToolArguments(noting(record.input, 'gen_ai.tool.call.arguments', omitted))\n if (args !== undefined)\n attributes['gen_ai.tool.call.arguments'] = contentAttribute(args, CONTENT_MAX_CHARS.toolArguments)\n const result = extractToolResult(noting(record.result, 'gen_ai.tool.call.result', omitted))\n if (result !== undefined)\n attributes['gen_ai.tool.call.result'] = contentAttribute(result.value, CONTENT_MAX_CHARS.toolResult)\n // The tool cut its own output: said apart from this plugin's truncation (`fro_bot.content.truncated`).\n if (record.toolTruncated === true || result?.ownTruncation === true)\n attributes['fro_bot.tool.output_truncated'] = true\n\n return {\n traceId: record.traceId,\n spanId: record.spanId,\n parentSpanId: record.parentSpanId,\n name: `execute_tool ${record.tool}`,\n kind: 'internal',\n startMs: record.start,\n endMs: record.end,\n attributes,\n status: statusOf(record),\n events: eventsOf(record),\n ...(omitted.length === 0 ? {} : {omitted}),\n }\n}\n\n/**\n * A turn's root span links to the Action run's root span: a link, not a parent, because the turn is a trace of its own (Langfuse\n * ignores links; Tempo follows them). Any other span of the turn is reached through its root. The link is its two ids and\n * nothing else, as the shared core's `SpanLink` is.\n */\nfunction runLinks(record: InvokeRecord, options: AttributeOptions): Pick<PendingSpan, 'links'> {\n if (record.role !== 'root' || options.rootSpan === undefined) return {}\n return {links: [{traceId: options.rootSpan.traceId, spanId: options.rootSpan.spanId}]}\n}\n\nfunction invokeSpan(record: InvokeRecord, options: AttributeOptions): PendingSpan {\n const omitted: string[] = []\n const attributes: Attributes = {\n 'gen_ai.operation.name': 'invoke_agent',\n ...identityAttributes(record, options),\n ...outcomeAttributes(record),\n 'fro_bot.agent.role': record.role,\n }\n if (record.standalone !== undefined) attributes['fro_bot.turn.standalone'] = record.standalone\n set(attributes, 'fro_bot.turn.continuation_of', record.continuationOf)\n set(attributes, 'fro_bot.turn.report_delivered_in', record.reportDeliveredInTrace)\n if (record.prompts.length > 0) {\n attributes['fro_bot.prompt.count'] = record.prompts.length\n if (record.prompts.some(prompt => prompt.midTurn)) attributes['fro_bot.prompt.mid_turn'] = true\n const messages = record.prompts.flatMap(prompt => {\n const text = (prompt.content as {text?: unknown} | undefined)?.text\n const reason = omittedReason(text)\n if (reason !== undefined) omitted.push(`gen_ai.input.messages:${reason}`)\n const message = extractPromptMessage(prompt.content)\n return message === undefined ? [] : [message]\n })\n if (messages.length > 0)\n attributes['gen_ai.input.messages'] = contentAttribute(messages, CONTENT_MAX_CHARS.prompt, true)\n }\n\n return {\n traceId: record.traceId,\n spanId: record.spanId,\n parentSpanId: record.parentSpanId,\n name: `invoke_agent ${record.agent ?? 'unknown'}`,\n kind: 'internal',\n startMs: record.start,\n endMs: record.end,\n attributes,\n status: statusOf(record),\n events: eventsOf(record),\n ...runLinks(record, options),\n ...(omitted.length === 0 ? {} : {omitted}),\n }\n}\n\n/** The span as it would be exported if nothing needed scrubbing. Not exportable: `toExportSpan` is. */\nexport function toPendingSpan(record: SpanRecord, options: AttributeOptions = {}): PendingSpan {\n switch (record.kind) {\n case 'chat':\n return chatSpan(record, options)\n case 'execute_tool':\n return toolSpan(record, options)\n case 'invoke_agent':\n return invokeSpan(record, options)\n }\n}\n\nconst SESSION_ATTRIBUTE = 'langfuse.session.id'\n\n/**\n * The trace's name in Langfuse, whose OTLP ingestion reads it from this attribute on the trace's root span (the span names\n * `invoke_agent <agent>` name observations, not the trace). One fixed string for every trace, so it holds no content.\n */\nexport const TRACE_NAME_ATTRIBUTE = 'langfuse.trace.name'\nexport const TRACE_NAME = 'fro-bot run'\n\n/**\n * Names the trace on a span that is its root, and on nothing else. A span with no parent is the root: the turn model opens\n * every trace with a parentless `invoke_agent` (a continuation of a closed trace included) and gives every other span a parent.\n *\n * Added after the scrub, never through it: the string is fixed text, and a scrubber that rewrote it (a registered value that\n * happens to match a word of it) would split one name into several in Langfuse. A span that is not a root is returned as is.\n */\nfunction withTraceName(span: ScrubbedSpan): ScrubbedSpan {\n if (span.parentSpanId !== undefined) return span\n return {...span, attributes: {...span.attributes, [TRACE_NAME_ATTRIBUTE]: TRACE_NAME}}\n}\n\n/**\n * Whether the span carries the launcher's session id exactly as given. Equal text is not enough: a value the scrubber withheld\n * is exported as the fixed marker `[omitted]`, so an id that is literally `[omitted]` would equal its own withheld form. The\n * omission status the scrub wrote (`<attribute>:<reason>`) is what says whether it was withheld.\n */\nfunction sessionIdExportedAsGiven(span: ScrubbedSpan, sessionId: string): boolean {\n if (span.attributes[SESSION_ATTRIBUTE] !== sessionId) return false\n const omitted = span.attributes[MARKER.omitted]\n return !(\n Array.isArray(omitted) &&\n omitted.some((entry: unknown) => typeof entry === 'string' && entry.startsWith(`${SESSION_ATTRIBUTE}:`))\n )\n}\n\n/**\n * Record to an exportable span: attributes, then the one scrubbing pass.\n *\n * The launcher's session id is the one value exported as given or not at all. The exporter scrubs every string, and a redacted\n * session id (`acme/password-manager:[REDACTED]`) would merge conversations into one Langfuse session. So when the scrub changed\n * it, or withheld or cut it, the span is built again with OpenCode's root session in its place. Everything else on the span is\n * scrubbed as before.\n */\nexport function toExportSpan(\n record: SpanRecord,\n options: AttributeOptions,\n scrubber: Scrubber,\n limits?: ContentLimits,\n): ScrubbedSpan {\n const span = scrubSpan(toPendingSpan(record, options), scrubber, limits)\n if (options.sessionId === undefined || sessionIdExportedAsGiven(span, options.sessionId)) return withTraceName(span)\n return withTraceName(scrubSpan(toPendingSpan(record, {...options, sessionId: undefined}), scrubber, limits))\n}\n","/**\n * The turn model: normalized observations in, span records out. Pure: no SDK, no I/O, no clock of its own (time comes in\n * on observations as epoch milliseconds, and a `tick` observation lets the caller's timer advance it), no ids of its own\n * (they come from the injected `IdSource`).\n *\n * What it encodes, each fact observed on the pinned OpenCode 2.3.2 binary (see `turn-model.fixtures.ts`):\n * - Every subagent is a background job. The `subagent` tool returns in milliseconds with the child session id, so a\n * child's spans arrive after the tool span that started it has ended. The link is `tool.after` / `tool.success`\n * metadata `sessionID`, keyed by the tool call.\n * - The child's first `prompt` hook can arrive BEFORE that link, so observations of an unknown session are buffered\n * while a dispatch is unresolved.\n * - A parent's execution can end while its child still runs. The child's report is a synthetic inbox item that starts a\n * new parent execution with no prompt, or is delivered into an execution already running. A child that itself has\n * background work reports `state=\"running\"` first and `completed` later.\n * - A hook for a model request can arrive before the `execution.started` event of the execution it belongs to, and\n * before the `inbox.delivered` event that consumed its trigger. Executions are therefore begun from pending inbox\n * items, not from the event.\n * - A request hook carries no message id. A primary request is joined to its `step.started` by order within the session.\n * A failed attempt shows as a `retry` hook BEFORE its `step.started`.\n */\n\nimport type {ErrorInfo, InboxItemKind, Observation, RequestKind, Usage} from './observation.js'\n\nexport type {ErrorInfo, ExecutionOutcome, InboxItemKind, Observation, RequestKind, Usage} from './observation.js'\n\nexport type ToolOutcome = 'success' | 'error' | 'rejected' | 'interrupted'\n\nexport type SpanKind = 'invoke_agent' | 'chat' | 'execute_tool'\nexport type SpanStatus = 'ok' | 'error' | 'interrupted'\n\nexport interface PromptRecord {\n readonly messageId: string\n readonly at: number\n readonly content?: unknown\n readonly delivery?: string | undefined\n /** Arrived while the turn's execution was already running. */\n readonly midTurn: boolean\n}\n\ninterface RecordBase {\n readonly spanId: string\n readonly traceId: string\n readonly parentSpanId: string | undefined\n readonly name: string\n readonly start: number\n readonly end: number\n readonly status: SpanStatus\n readonly error?: ErrorInfo | undefined\n readonly sessionId: string\n /** The session whose turn this trace is: the grouping key for a whole tree. */\n readonly rootSessionId: string\n readonly agent: string | undefined\n /** Fields that were not captured, by name. Absent means not captured, never empty. */\n readonly gaps: readonly string[]\n /** `incomplete`, `unattributed`, `continuation`. */\n readonly marks: readonly string[]\n}\n\nexport interface InvokeRecord extends RecordBase {\n readonly kind: 'invoke_agent'\n readonly role: 'root' | 'child'\n readonly prompts: readonly PromptRecord[]\n /** Set when this trace continues a closed one: a report that arrived after the trace ended. */\n readonly continuationOf?: string | undefined\n /** Set when this turn's subagent report was consumed by another turn's execution. */\n readonly reportDeliveredInTrace?: string | undefined\n readonly standalone?: 'compaction' | 'generate' | undefined\n}\n\nexport interface ChatRecord extends RecordBase {\n readonly kind: 'chat'\n readonly requestKind: RequestKind\n readonly provider?: string | undefined\n readonly model?: string | undefined\n readonly attempt: number\n readonly messageId?: string | undefined\n /** The hook-time request, as the observation carried it. */\n readonly request?: unknown\n readonly texts: readonly string[]\n readonly reasoning: readonly string[]\n /** Tool calls this response asked for, in order: the response's output alongside its text. */\n readonly toolCalls: readonly RequestedToolCall[]\n readonly finishReason?: string | undefined\n readonly rawFinishReason?: string | undefined\n readonly usage?: Usage | undefined\n readonly cost?: number | undefined\n /** Traces whose subagent report this request carried while running inside another turn's execution. */\n readonly followOnOf: readonly string[]\n /**\n * A title, compaction or generate request is prepared once and retried below the hook (v2.3.2 `generate.ts`,\n * `compaction.ts` `deliver`), so how many provider attempts it took cannot be seen: this one span stands for all of them.\n */\n readonly attemptCountUnknown: boolean\n}\n\nexport interface RequestedToolCall {\n readonly callId: string\n readonly tool: string\n readonly input?: unknown\n}\n\nexport interface ToolRecord extends RecordBase {\n readonly kind: 'execute_tool'\n readonly tool: string\n readonly callId: string\n readonly input?: unknown\n readonly result?: unknown\n readonly outcome: ToolOutcome\n readonly errorType?: string | undefined\n readonly toolTruncated?: boolean | undefined\n readonly childSessionId?: string | undefined\n /** The provider ran the tool: the session events are all there is, no hook fires for it. */\n readonly providerExecuted: boolean\n /** Snapshots this span replaced (the call event's arguments, when a hook's replaced them). For whoever counts them. */\n readonly discarded: readonly unknown[]\n}\n\nexport type SpanRecord = InvokeRecord | ChatRecord | ToolRecord\n\nexport interface IdSource {\n readonly trace: () => string\n readonly span: () => string\n}\n\n/** Every bound the model applies. Overridable so a test can hit each boundary. */\nexport interface TurnModelLimits {\n /** Observations held for one session whose parent is not yet known. */\n readonly maxBufferedObservations: number\n readonly maxBufferedBytes: number\n /** Sessions held at once. */\n readonly maxBufferedSessions: number\n /** How long an unknown session may wait for its dispatch link before it gets its own trace. */\n readonly bufferWindowMs: number\n /** A trace with no observation for this long closes, marked incomplete. */\n readonly rootInactivityMs: number\n /** Open traces at once. The least recently active closes, marked incomplete. */\n readonly maxOpenTraces: number\n /** Closed traces remembered so a late report can name them. */\n readonly maxTombstones: number\n /** A title's text arrives in an event that can follow the end of its turn; the trace waits this long for it. */\n readonly titleWaitMs: number\n /** A standalone `generate` request has no end event; it closes after this long. */\n readonly standaloneRequestTimeoutMs: number\n /** Open request and tool spans per trace. Beyond this a span is dropped and counted. */\n readonly maxOpenSpansPerTrace: number\n /** Output parts kept per request. */\n readonly maxOutputParts: number\n /** Prompts kept per span. */\n readonly maxPromptsPerSpan: number\n /**\n * Per session: tool names and hook observations held while the session event that opens or closes the call has not\n * arrived. Past this the oldest is dropped, silently.\n */\n readonly maxPendingToolNotes: number\n /**\n * Characters of model output (text and reasoning, a compaction summary, a title) one open request keeps. A part that does\n * not fit is omitted whole, never clipped (a cut before redaction could split a secret), and the span says so. Equal to the\n * span's own output bound.\n */\n readonly maxOutputChars: number\n /** The same, summed over every open request in the model: past it, parts are cut or omitted the same way. */\n readonly maxHeldOutputChars: number\n /**\n * A session with no trace, no running execution and nothing open is forgotten after this long without an observation, and\n * its held snapshots are handed back. Independent of open traces: a prompt for a session that never starts an execution\n * has no trace to close it.\n */\n readonly sessionIdleMs: number\n /**\n * Idle sessions kept, a limit applied when a session record is created: past it the least recently active is forgotten. A running\n * session never counts. Records that go idle later can exceed it until the next allocation or their idle expiry.\n */\n readonly maxIdleSessions: number\n /**\n * Finished call ids remembered per session, so a repeated terminal event (or a late hook) for a call that already ended\n * is ignored instead of opening a second span. Past it the oldest id is forgotten.\n */\n readonly maxCompletedCallsPerSession: number\n /** Prompts one session holds while waiting for an execution; past it the oldest is dropped. */\n readonly maxPendingPromptsPerSession: number\n /** How long such a note waits for its event before it is dropped, silently. Checked on a tick and on the next note. */\n readonly toolNoteWaitMs: number\n /**\n * How long a closed trace's id is remembered so a late subagent report can name it. After it, the report is an\n * unattributed trace. The count bound (`maxTombstones`) applies too.\n */\n readonly tombstoneTtlMs: number\n /**\n * Primary request hook times kept per session for the step join (see \"Binding steps to requests\"). Oldest first out, so a step\n * whose hook was dropped finds no hook at all and binds nothing; it never falls through to an older one.\n */\n readonly maxHookTimes: number\n}\n\nexport const DEFAULT_LIMITS: TurnModelLimits = {\n maxBufferedObservations: 64,\n maxBufferedBytes: 256 * 1024,\n maxBufferedSessions: 16,\n bufferWindowMs: 5_000,\n rootInactivityMs: 30 * 60_000,\n maxOpenTraces: 32,\n maxTombstones: 256,\n titleWaitMs: 10_000,\n standaloneRequestTimeoutMs: 120_000,\n maxOpenSpansPerTrace: 1_024,\n maxOutputParts: 64,\n maxPromptsPerSpan: 32,\n maxOutputChars: 128 * 1024,\n maxHeldOutputChars: 8 * 1024 * 1024,\n sessionIdleMs: 10 * 60_000,\n maxIdleSessions: 64,\n maxCompletedCallsPerSession: 256,\n maxPendingPromptsPerSession: 64,\n maxPendingToolNotes: 64,\n toolNoteWaitMs: 10_000,\n tombstoneTtlMs: 24 * 60 * 60_000,\n maxHookTimes: 64,\n}\n\nexport interface TurnModelStats {\n readonly openTraces: number\n readonly sessions: number\n readonly bufferedSessions: number\n readonly bufferedBytes: number\n /** Refused primary requests still holding a place for their step events. */\n /** Primary request hook times held across sessions (bounded per session by `maxHookTimes`). */\n readonly hookTimes: number\n /** Hook entries that still reference a request: only requests that are open. */\n readonly historyRequestsHeld: number\n /** Times a session was withheld (see \"Binding steps to requests\"): zero in any run whose steps and hooks the join could place. */\n readonly withholds: number\n /** Steps bound to a request and still open, across sessions: each is released when its step ends or fails. */\n readonly openSteps: number\n readonly tombstones: number\n readonly unresolvedDispatches: number\n /** Tool names and hook observations waiting for their session event. */\n readonly pendingToolNotes: number\n /** Characters of model output held by open requests. */\n readonly heldOutputChars: number\n readonly droppedSpans: number\n}\n\nexport interface TurnModel {\n /** Feeds one observation. Returns the spans that finished because of it. */\n readonly observe: (observation: Observation) => SpanRecord[]\n /** Closes everything still open as interrupted and incomplete, and releases all state. */\n readonly flush: (at: number) => SpanRecord[]\n readonly stats: () => TurnModelStats\n /**\n * The snapshots the model dropped without a span to carry them (an expired session's prompts, a hook note that timed out,\n * a repeated terminal event). Returned once, for whoever counts them to release.\n */\n readonly takeDiscarded: () => unknown[]\n /**\n * The snapshots that now have a second owner (a tool call's arguments are in the model's record of what was asked and in\n * the tool span). Returned once; each needs one more release.\n */\n readonly takeRetained: () => unknown[]\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n// Internal mutable state. Per-invocation trackers in a closure, never exported.\n// ---------------------------------------------------------------------------------------------------------------------\n\ninterface InvokeState {\n readonly spanId: string\n readonly parentSpanId: string | undefined\n readonly role: 'root' | 'child'\n readonly sessionId: string\n start: number\n agent: string | undefined\n prompts: PromptRecord[]\n gaps: Set<string>\n marks: Set<string>\n status: SpanStatus\n error: ErrorInfo | undefined\n closed: boolean\n continuationOf: string | undefined\n reportDeliveredInTrace: string | undefined\n standalone: 'compaction' | 'generate' | undefined\n}\n\ninterface TraceState {\n readonly id: string\n readonly rootSessionId: string\n readonly root: InvokeState\n readonly nodes: Map<string, SessionNode>\n /** Children dispatched in this trace whose final report has not been delivered: child id to its parent session. */\n readonly outstanding: Map<string, string>\n lastActivity: number\n activeExecutions: number\n openSpans: number\n closed: boolean\n}\n\ninterface PendingItem {\n readonly inboxId: string\n readonly kind: InboxItemKind\n readonly at: number\n readonly childSessionId: string | undefined\n readonly reportState: string | undefined\n /** The trace whose child this report is about, or the id of a closed trace that was. */\n readonly reportTrace: TraceState | undefined\n readonly reportTombstone: string | undefined\n /** Enqueued while an execution was running: that execution will consume it. */\n joined: boolean\n claimed: boolean\n}\n\ninterface RequestState {\n readonly spanId: string\n readonly trace: TraceState\n readonly sessionId: string\n readonly parentSpanId: string\n readonly requestKind: RequestKind\n readonly start: number\n agent: string | undefined\n model: string | undefined\n provider: string | undefined\n readonly request: unknown\n readonly attempt: number\n messageId: string | undefined\n texts: string[]\n reasoning: string[]\n /** Characters of `texts` and `reasoning`, counted against the output budgets. */\n outputChars: number\n toolCalls: RequestedToolCall[]\n finishReason: string | undefined\n rawFinishReason: string | undefined\n usage: Usage | undefined\n cost: number | undefined\n followOnOf: string[]\n gaps: Set<string>\n marks: Set<string>\n /** Closed by a `retry` hook: waiting only for its `step.started` to be skipped. */\n closed: boolean\n /** The agent, model and provider its step named. Kept apart from the hook's own, which a span prefers and a withheld one is limited to. */\n stepAgent: string | undefined\n stepModel: string | undefined\n stepProvider: string | undefined\n /**\n * Its step may not be its own, or its step data may be incomplete (a loss was reported while it waited for a step or ran): it\n * carries nothing a step produced, only\n * an incomplete outcome and its hook-time metadata.\n */\n bindUncertain: boolean\n}\n\ninterface ToolState {\n readonly spanId: string\n readonly trace: TraceState\n readonly sessionId: string\n readonly parentSpanId: string\n readonly callId: string\n tool: string\n readonly start: number\n agent: string | undefined\n input: unknown\n /** The call event's arguments, kept until a hook's replace them. */\n callInput: unknown\n inputFromHook: boolean\n result: unknown\n resultFromHook: boolean\n providerExecuted: boolean\n afterStatus: 'completed' | 'error' | undefined\n afterError: unknown\n interrupted: boolean\n childSessionId: string | undefined\n discarded: unknown[]\n gaps: Set<string>\n}\n\n/** What the hooks and the input-started event told us about a call, held until its session event arrives. */\ninterface ToolNote {\n readonly at: number\n tool?: string | undefined\n before?: Extract<Observation, {kind: 'tool.before'}> | undefined\n after?: Extract<Observation, {kind: 'tool.after'}> | undefined\n}\n\n/**\n * One primary request hook: when the plugin received it, and the request it opened while that request is open. None when the span\n * cap refused it or a loss stood for it, and none once the request closed: the record keeps no payload alive.\n */\ninterface HookRecord {\n readonly at: number\n request: RequestState | undefined\n /** A step has resolved to this hook (bound or not), or its execution ended after it: its own step is done with, or will never come. */\n consumed: boolean\n}\n\ninterface SessionNode {\n readonly id: string\n /** Set for a child session: its trace and its own invoke span. */\n readonly childOf: {readonly trace: TraceState; readonly invoke: InvokeState} | undefined\n readonly traces: Set<TraceState>\n active: {readonly trace: TraceState} | undefined\n agent: string | undefined\n readonly pending: PendingItem[]\n readonly prompts: Map<string, Extract<Observation, {kind: 'prompt'}>>\n readonly requests: RequestState[]\n readonly tools: Map<string, ToolState>\n /** Calls with no span yet, by call id, oldest first. */\n readonly notes: Map<string, ToolNote>\n /** Call ids that have ended, oldest first. */\n readonly completed: Set<string>\n readonly stepOwner: Map<string, RequestState>\n /** The session's primary request hooks, in the order they arrived: the step join's record (see \"Binding steps to requests\"). */\n readonly hooks: HookRecord[]\n /**\n * This session binds nothing until its execution ends (see \"Binding steps to requests\"). Stored with the hook record, so it lives\n * exactly as long as the record does.\n */\n withheld: boolean\n /** The newest primary hook time this session was told of, recorded or not: what an execution's end is compared with. */\n newestHookAt: number\n /** When the session's latest execution ended, by the end event's own time. */\n lastEndedAt: number\n nextAttempt: number\n lastActivity: number\n}\n\ninterface BufferedSession {\n readonly sessionId: string\n readonly firstAt: number\n readonly items: Observation[]\n bytes: number\n}\n\nconst CREATING_KINDS: ReadonlySet<Observation['kind']> = new Set([\n 'prompt',\n 'inbox.enqueued',\n 'session.created',\n 'execution.started',\n 'request',\n])\n\nfunction applyBefore(tool: ToolState, o: Extract<Observation, {kind: 'tool.before'}>): void {\n tool.agent = o.agent ?? tool.agent\n if (tool.tool === 'unknown') tool.tool = o.tool\n if (o.input !== undefined) {\n // The arguments the tool received win over the ones the model wrote; the superseded snapshot is handed back.\n if (tool.input !== undefined) tool.discarded.push(tool.input)\n tool.input = o.input\n tool.inputFromHook = true\n }\n}\n\n/** What an observation holds, for the buffer's byte bound: its stated bytes, or the text it carries. */\nfunction observedSize(observation: Observation): number {\n if (observation.bytes !== undefined) return observation.bytes\n if (observation.kind === 'output') return observation.text.length\n if (observation.kind === 'title') return observation.title.length\n return 0\n}\n\n/** A confirmed subagent dispatch: the stock `subagent` tool, by the same test the called-event path uses. */\nconst isSubagentDispatch = (tool: {readonly tool: string}): boolean => tool.tool === 'subagent'\n\nexport function createTurnModel(options: {\n readonly ids: IdSource\n readonly limits?: Partial<TurnModelLimits>\n}): TurnModel {\n const limits: TurnModelLimits = {...DEFAULT_LIMITS, ...options.limits}\n const {ids} = options\n\n const traces = new Set<TraceState>()\n /** Lost hooks' times for sessions with no node yet, newest per session, bounded: applied when the session's node is created. */\n const earlyLostHooks = new Map<string, number>()\n let withholds = 0\n const sessions = new Map<string, SessionNode>()\n const buffered = new Map<string, BufferedSession>()\n /** Session ids a `session.created` event said have a parent, before any dispatch link arrived. */\n const parentHints = new Map<string, string>()\n /** Subagent dispatches whose child session id is not known yet: `<session>/<call>`. */\n const unresolved = new Set<string>()\n /** Child sessions that have been placed under a dispatch. */\n const linked = new Set<string>()\n /** Children already given their own unattributed trace (their buffer was released before a link came), oldest first. */\n const releasedChildren = new Set<string>()\n /** Characters of model output held by open requests, against `maxHeldOutputChars`. */\n let heldOutputChars = 0\n\n /** Snapshots dropped with no span to carry them, until `takeDiscarded` hands them back. */\n let discarded: unknown[] = []\n /** Snapshots that gained a second owner, until `takeRetained` hands them over. */\n let retained: unknown[] = []\n const discard = (value: unknown): void => {\n if (typeof value === 'object' && value !== null) discarded.push(value)\n }\n\n /** Child session id to the closed trace it belonged to, and when it closed. Oldest first. */\n const tombstones = new Map<string, {readonly traceId: string; readonly at: number}>()\n /** Marks to put on a root trace the moment it is opened for a session. */\n const pendingMarks = new Map<string, string>()\n let droppedSpans = 0\n let bufferedBytes = 0\n let out: SpanRecord[] = []\n let clock = 0\n\n const emit = (record: SpanRecord): void => {\n out.push(record)\n }\n\n // ------------------------------------------------------------------ traces and sessions\n\n function newInvoke(\n role: 'root' | 'child',\n sessionId: string,\n start: number,\n parentSpanId: string | undefined,\n ): InvokeState {\n return {\n spanId: ids.span(),\n parentSpanId,\n role,\n sessionId,\n start,\n agent: undefined,\n prompts: [],\n gaps: new Set(),\n marks: new Set(),\n status: 'ok',\n error: undefined,\n closed: false,\n continuationOf: undefined,\n reportDeliveredInTrace: undefined,\n standalone: undefined,\n }\n }\n\n function openTrace(\n rootSessionId: string,\n start: number,\n extra: {continuationOf?: string; mark?: string; standalone?: 'compaction' | 'generate'} = {},\n ): TraceState {\n if (traces.size >= limits.maxOpenTraces) {\n let oldest: TraceState | undefined\n for (const trace of traces) if (oldest === undefined || trace.lastActivity < oldest.lastActivity) oldest = trace\n if (oldest !== undefined) closeTrace(oldest, clock, 'ok', {incomplete: true})\n }\n const root = newInvoke('root', rootSessionId, start, undefined)\n if (extra.continuationOf !== undefined) {\n root.continuationOf = extra.continuationOf\n root.marks.add('continuation')\n }\n if (extra.mark !== undefined) root.marks.add(extra.mark)\n root.standalone = extra.standalone\n const trace: TraceState = {\n id: ids.trace(),\n rootSessionId,\n root,\n nodes: new Map(),\n outstanding: new Map(),\n lastActivity: start,\n activeExecutions: 0,\n openSpans: 0,\n closed: false,\n }\n traces.add(trace)\n return trace\n }\n\n function newNode(sessionId: string, childOf: SessionNode['childOf'], at: number): SessionNode {\n const node: SessionNode = {\n id: sessionId,\n childOf,\n traces: new Set(),\n active: undefined,\n agent: undefined,\n pending: [],\n prompts: new Map(),\n requests: [],\n tools: new Map(),\n notes: new Map(),\n completed: new Set(),\n stepOwner: new Map(),\n hooks: [],\n withheld: false,\n newestHookAt: Number.NEGATIVE_INFINITY,\n lastEndedAt: Number.NEGATIVE_INFINITY,\n nextAttempt: 1,\n lastActivity: at,\n }\n sessions.set(sessionId, node)\n // A hook lost before the session was seen leaves its time all the same.\n const lost = earlyLostHooks.get(sessionId)\n if (lost !== undefined) {\n earlyLostHooks.delete(sessionId)\n recordHook(node, lost, undefined, true)\n }\n // The idle limit applies when a node is created; a node left idle later stays until it expires.\n enforceIdleBound(node)\n return node\n }\n\n /** Nothing running, open or owed: only queued prompts and notes, which no trace will ever close. */\n const isIdle = (node: SessionNode): boolean =>\n node.childOf === undefined &&\n node.traces.size === 0 &&\n node.active === undefined &&\n node.requests.length === 0 &&\n node.tools.size === 0\n\n /** Forgets an idle session and hands back what it held. */\n function forgetSession(node: SessionNode): void {\n for (const prompt of node.prompts.values()) discard(prompt.content)\n for (const note of node.notes.values()) discardNote(note)\n sessions.delete(node.id)\n }\n\n function discardNote(note: ToolNote): void {\n discard(note.before?.input)\n discard(note.after?.result)\n }\n\n /** Keeps the idle sessions within `maxIdleSessions`, forgetting the least recently active. `keep` is never forgotten. */\n function enforceIdleBound(keep: SessionNode): void {\n const idle = [...sessions.values()].filter(node => node !== keep && isIdle(node))\n if (idle.length < limits.maxIdleSessions) return\n idle.sort((a, b) => a.lastActivity - b.lastActivity)\n for (const node of idle.slice(0, idle.length - limits.maxIdleSessions + 1)) forgetSession(node)\n }\n\n function expireIdleSessions(now: number): void {\n for (const node of [...sessions.values()]) {\n if (isIdle(node) && now - node.lastActivity > limits.sessionIdleMs) forgetSession(node)\n }\n }\n\n const touch = (trace: TraceState, at: number): void => {\n trace.lastActivity = Math.max(trace.lastActivity, at)\n }\n\n /** The invoke span a session's own work hangs under, in `trace`. */\n function invokeOf(node: SessionNode, trace: TraceState): InvokeState {\n return node.childOf !== undefined && node.childOf.trace === trace ? node.childOf.invoke : trace.root\n }\n\n function addPrompt(invoke: InvokeState, prompt: PromptRecord): void {\n if (invoke.prompts.length >= limits.maxPromptsPerSpan) {\n invoke.gaps.add('prompts-over-limit')\n return\n }\n invoke.prompts.push(prompt)\n }\n\n // ------------------------------------------------------------------ emitting\n\n function emitInvoke(trace: TraceState, invoke: InvokeState, at: number, extraMarks: readonly string[] = []): void {\n if (invoke.closed) return\n invoke.closed = true\n emit({\n kind: 'invoke_agent',\n role: invoke.role,\n spanId: invoke.spanId,\n traceId: trace.id,\n parentSpanId: invoke.parentSpanId,\n name: `invoke_agent ${invoke.agent ?? 'unknown'}`,\n start: invoke.start,\n end: Math.max(at, invoke.start),\n status: invoke.status,\n error: invoke.error,\n sessionId: invoke.sessionId,\n rootSessionId: trace.rootSessionId,\n agent: invoke.agent,\n gaps: [...invoke.gaps],\n marks: [...invoke.marks, ...extraMarks],\n prompts: invoke.prompts,\n continuationOf: invoke.continuationOf,\n reportDeliveredInTrace: invoke.reportDeliveredInTrace,\n standalone: invoke.standalone,\n })\n }\n\n function emitRequest(\n request: RequestState,\n at: number,\n status: SpanStatus,\n error?: ErrorInfo,\n extraMarks: readonly string[] = [],\n ): void {\n if (request.closed) return\n request.closed = true\n const hook = sessions.get(request.sessionId)?.hooks.find(candidate => candidate.request === request)\n if (hook !== undefined) hook.request = undefined\n // The request's output moves into its record: it no longer counts against what open requests hold.\n heldOutputChars = Math.max(0, heldOutputChars - request.outputChars)\n request.trace.openSpans = Math.max(0, request.trace.openSpans - 1)\n // An uncertain request holds nothing a step produced, however much arrived: no output, message id, finish reason, usage, cost,\n // status or error, and none of the step's agent, model or provider. A request whose step was never bound, one whose step\n // may be someone else's, and one whose events were partly lost are all this one case: a partial answer with no way to know\n // what is missing is worse than none, and there is one gap name for it. The outcome is only \"incomplete\".\n const unbound = request.bindUncertain\n const model = request.model ?? (unbound ? undefined : request.stepModel)\n emit({\n kind: 'chat',\n spanId: request.spanId,\n traceId: request.trace.id,\n parentSpanId: request.parentSpanId,\n name: `chat ${model ?? request.requestKind}`,\n start: request.start,\n end: Math.max(at, request.start),\n status: unbound ? 'interrupted' : status,\n error: unbound ? undefined : error,\n sessionId: request.sessionId,\n rootSessionId: request.trace.rootSessionId,\n agent: request.agent ?? (unbound ? undefined : request.stepAgent),\n gaps: unbound\n ? ['step-binding-uncertain', ...(request.gaps.has('request') ? ['request'] : [])]\n : [...request.gaps],\n marks: unbound ? [...request.marks, 'incomplete', ...extraMarks] : [...request.marks, ...extraMarks],\n requestKind: request.requestKind,\n provider: request.provider ?? (unbound ? undefined : request.stepProvider),\n model,\n attempt: request.attempt,\n messageId: unbound ? undefined : request.messageId,\n request: request.request,\n texts: unbound ? [] : request.texts,\n reasoning: unbound ? [] : request.reasoning,\n toolCalls: unbound ? [] : request.toolCalls,\n finishReason: unbound ? undefined : request.finishReason,\n rawFinishReason: unbound ? undefined : request.rawFinishReason,\n usage: unbound ? undefined : request.usage,\n cost: unbound ? undefined : request.cost,\n followOnOf: request.followOnOf,\n attemptCountUnknown: request.requestKind !== 'primary',\n })\n }\n\n function emitTool(\n tool: ToolState,\n at: number,\n outcome: ToolOutcome,\n extra: {\n errorType?: string | undefined\n message?: string | undefined\n truncated?: boolean | undefined\n marks?: readonly string[]\n },\n ): void {\n tool.trace.openSpans = Math.max(0, tool.trace.openSpans - 1)\n const failed = outcome !== 'success'\n emit({\n kind: 'execute_tool',\n spanId: tool.spanId,\n traceId: tool.trace.id,\n parentSpanId: tool.parentSpanId,\n name: `execute_tool ${tool.tool}`,\n start: tool.start,\n end: Math.max(at, tool.start),\n status: outcome === 'interrupted' ? 'interrupted' : failed ? 'error' : 'ok',\n error: failed ? {type: extra.errorType ?? 'tool.execution', message: extra.message} : undefined,\n sessionId: tool.sessionId,\n rootSessionId: tool.trace.rootSessionId,\n agent: tool.agent,\n gaps: [...tool.gaps],\n marks: [...(extra.marks ?? [])],\n tool: tool.tool,\n callId: tool.callId,\n input: tool.input,\n result: tool.result,\n outcome,\n errorType: extra.errorType,\n toolTruncated: extra.truncated,\n childSessionId: tool.childSessionId,\n providerExecuted: tool.providerExecuted,\n discarded: tool.discarded,\n })\n }\n\n // ------------------------------------------------------------------ closing\n\n /** Closes a trace: its descendants first, then its root. `incomplete` marks every span that was still open. */\n function closeTrace(\n trace: TraceState,\n at: number,\n status: SpanStatus,\n close: {incomplete?: boolean; error?: ErrorInfo; deliveredIn?: string} = {},\n ): void {\n if (trace.closed) return\n trace.closed = true\n const marks = close.incomplete === true ? ['incomplete'] : []\n for (const node of trace.nodes.values()) {\n // A root session's node is shared by every trace of its turns: close only what belongs to this trace.\n for (const request of node.requests.filter(candidate => candidate.trace === trace)) {\n if (request.closed) continue\n // A title that never saw its `renamed` event, or a request cut off with its trace.\n if (request.messageId === undefined || request.requestKind !== 'primary') request.gaps.add('output')\n emitRequest(\n request,\n at,\n close.incomplete === true || request.messageId !== undefined ? 'interrupted' : 'ok',\n undefined,\n marks,\n )\n removeRequest(node, request)\n }\n for (const tool of [...node.tools.values()].filter(candidate => candidate.trace === trace)) {\n node.tools.delete(tool.callId)\n tool.gaps.add('outcome')\n emitTool(tool, at, 'interrupted', {marks: ['incomplete']})\n unresolved.delete(`${tool.sessionId}/${tool.callId}`)\n }\n if (node.childOf?.trace === trace) {\n node.childOf.invoke.status = close.incomplete === true ? 'interrupted' : node.childOf.invoke.status\n emitInvoke(trace, node.childOf.invoke, at, marks)\n linked.delete(node.id)\n }\n node.traces.delete(trace)\n }\n for (const childId of trace.outstanding.keys()) rememberTombstone(childId, trace.id)\n trace.root.status = status\n trace.root.error = close.error\n if (close.deliveredIn !== undefined) trace.root.reportDeliveredInTrace = close.deliveredIn\n emitInvoke(trace, trace.root, at, marks)\n for (const node of trace.nodes.values()) {\n node.active = node.active?.trace === trace ? undefined : node.active\n if (node.traces.size === 0 && node.childOf?.trace === trace) sessions.delete(node.id)\n else if (\n node.traces.size === 0 &&\n node.pending.length === 0 &&\n node.requests.every(r => r.closed) &&\n // The record is kept while it holds a hook no step has settled (the next execution's, seen before this end) or the\n // session is withheld: the idle bounds forget it.\n !node.withheld &&\n node.hooks.every(hook => hook.consumed)\n ) {\n sessions.delete(node.id)\n }\n }\n traces.delete(trace)\n }\n\n function rememberTombstone(childId: string, traceId: string): void {\n tombstones.delete(childId)\n tombstones.set(childId, {traceId, at: clock})\n while (tombstones.size > limits.maxTombstones) {\n const oldest = tombstones.keys().next()\n if (oldest.done === true) break\n tombstones.delete(oldest.value)\n }\n }\n\n const titlePending = (trace: TraceState): boolean => {\n for (const node of trace.nodes.values()) {\n if (node.requests.some(request => request.requestKind === 'title' && !request.closed)) return true\n }\n return false\n }\n\n /** Closes `node`'s own span, or the trace, when nothing is running and nothing is owed to it. */\n function maybeClose(node: SessionNode, trace: TraceState, at: number): void {\n if (trace.closed) return\n if (node.active?.trace === trace) return\n for (const parent of trace.outstanding.values()) if (parent === node.id) return\n if (node.childOf === undefined || node.id === trace.rootSessionId) {\n if (trace.outstanding.size > 0 || trace.activeExecutions > 0) return\n // A title's text can still arrive; `sweep` closes the trace if it never does.\n if (titlePending(trace)) return\n closeTrace(trace, at, trace.root.status === 'ok' ? 'ok' : trace.root.status, {error: trace.root.error})\n return\n }\n emitInvoke(trace, node.childOf.invoke, at)\n }\n\n // ------------------------------------------------------------------ routing and buffering\n\n const shouldBuffer = (sessionId: string): boolean => unresolved.size > 0 || parentHints.has(sessionId)\n\n function bufferObservation(sessionId: string, observation: Observation): void {\n let entry = buffered.get(sessionId)\n if (entry === undefined) {\n if (buffered.size >= limits.maxBufferedSessions) {\n // No room to wait: this session gets its own trace now, and the new observation with it.\n releaseBuffer(sessionId, [observation], 'unattributed')\n return\n }\n entry = {sessionId, firstAt: observation.at, items: [], bytes: 0}\n buffered.set(sessionId, entry)\n }\n const size = observedSize(observation)\n if (entry.items.length + 1 > limits.maxBufferedObservations || entry.bytes + size > limits.maxBufferedBytes) {\n const items = [...entry.items, observation]\n bufferedBytes -= entry.bytes\n buffered.delete(sessionId)\n releaseBuffer(sessionId, items, 'unattributed')\n return\n }\n entry.items.push(observation)\n entry.bytes += size\n bufferedBytes += size\n }\n\n /** Gives a buffered session its own trace. `unattributed` when something said it is a child whose parent never proved. */\n function releaseBuffer(sessionId: string, items: readonly Observation[], reason: 'unattributed' | 'root'): void {\n const hinted = parentHints.has(sessionId)\n if (hinted || reason === 'unattributed') {\n // A link that arrives later must not create a second, empty child for work that already has its own trace.\n releasedChildren.add(sessionId)\n while (releasedChildren.size > limits.maxTombstones) {\n const oldest = releasedChildren.values().next()\n if (oldest.done === true) break\n releasedChildren.delete(oldest.value)\n }\n }\n createRootNode(sessionId, items[0]?.at ?? clock)\n const node = sessions.get(sessionId)\n if (node !== undefined && (hinted || reason === 'unattributed')) pendingMarks.set(sessionId, 'unattributed')\n for (const item of items) dispatch(item)\n }\n\n function createRootNode(sessionId: string, at: number): SessionNode {\n return sessions.get(sessionId) ?? newNode(sessionId, undefined, at)\n }\n\n function expireBuffers(now: number): void {\n for (const [sessionId, entry] of [...buffered]) {\n if (now - entry.firstAt < limits.bufferWindowMs) continue\n buffered.delete(sessionId)\n bufferedBytes -= entry.bytes\n releaseBuffer(sessionId, entry.items, parentHints.has(sessionId) ? 'unattributed' : 'root')\n }\n }\n\n /** The node for `sessionId`, creating a root-session node when nothing says it is a child. Undefined: buffered. */\n function route(observation: Observation & {readonly sessionId: string}): SessionNode | undefined {\n const existing = sessions.get(observation.sessionId)\n if (existing !== undefined) return existing\n if (buffered.has(observation.sessionId)) {\n bufferObservation(observation.sessionId, observation)\n return undefined\n }\n if (!CREATING_KINDS.has(observation.kind)) return undefined\n if (shouldBuffer(observation.sessionId)) {\n bufferObservation(observation.sessionId, observation)\n return undefined\n }\n return newNode(observation.sessionId, undefined, observation.at)\n }\n\n // ------------------------------------------------------------------ executions\n\n function beginExecution(node: SessionNode, at: number): TraceState {\n if (node.active !== undefined) return node.active.trace\n if (node.childOf !== undefined) {\n const {trace, invoke} = node.childOf\n node.active = {trace}\n trace.activeExecutions += 1\n attachPendingPrompts(node, invoke, at)\n return trace\n }\n\n const waiting = node.pending.filter(item => !item.joined)\n const users = waiting.filter(item => item.kind === 'user')\n const reports = waiting.filter(item => item.kind === 'synthetic')\n const compaction = waiting.find(item => item.kind === 'compaction')\n const extra: {continuationOf?: string; mark?: string; standalone?: 'compaction' | 'generate'} = {}\n let owner: TraceState | undefined\n let start = at\n\n if (users.length > 0) {\n start = Math.min(...users.map(item => promptTime(node, item)))\n } else if (compaction !== undefined) {\n extra.standalone = 'compaction'\n start = compaction.at\n } else if (reports.length > 0) {\n // A report with nothing else: the turn that started the child carries on.\n owner = reports.map(item => item.reportTrace).find(trace => trace !== undefined && !trace.closed)\n const tombstone = reports.map(item => item.reportTombstone).find(id => id !== undefined)\n if (owner === undefined) {\n if (tombstone === undefined) extra.mark = 'unattributed'\n else extra.continuationOf = tombstone\n start = Math.min(...reports.map(item => item.at))\n }\n } else {\n extra.mark = 'trigger-unknown'\n }\n\n const trace = owner ?? openTrace(node.id, start, extra)\n const pendingMark = pendingMarks.get(node.id)\n if (pendingMark !== undefined && owner === undefined) {\n trace.root.marks.add(pendingMark)\n pendingMarks.delete(node.id)\n }\n if (extra.mark === 'trigger-unknown') trace.root.gaps.add('trigger')\n trace.nodes.set(node.id, node)\n node.traces.add(trace)\n node.active = {trace}\n trace.activeExecutions += 1\n touch(trace, at)\n if (owner === undefined) attachPendingPrompts(node, trace.root, at)\n return trace\n }\n\n function promptTime(node: SessionNode, item: PendingItem): number {\n return node.prompts.get(item.inboxId)?.at ?? item.at\n }\n\n /** Moves the user prompts that started an execution onto the span that carries them. */\n function attachPendingPrompts(node: SessionNode, invoke: InvokeState, at: number): void {\n for (const item of node.pending) {\n if (item.kind !== 'user' || item.joined) continue\n const prompt = node.prompts.get(item.inboxId)\n addPrompt(invoke, {\n messageId: item.inboxId,\n at: prompt?.at ?? item.at,\n content: prompt?.content,\n delivery: prompt?.delivery,\n midTurn: false,\n })\n if (prompt === undefined) invoke.gaps.add('prompt-content')\n item.joined = true\n }\n // Prompts that arrived with no inbox item yet (the hook leads the event): the turn's own.\n for (const [id, prompt] of node.prompts) {\n if (invoke.prompts.some(existing => existing.messageId === id)) continue\n if (node.pending.some(item => item.inboxId === id)) continue\n addPrompt(invoke, {\n messageId: id,\n at: prompt.at,\n content: prompt.content,\n delivery: prompt.delivery,\n midTurn: false,\n })\n }\n invoke.start = Math.min(invoke.start, invoke.prompts[0]?.at ?? at)\n }\n\n // ------------------------------------------------------------------ handlers\n\n function onPrompt(o: Extract<Observation, {kind: 'prompt'}>): void {\n const node = route(o)\n if (node === undefined) return\n const active = node.active\n if (active === undefined) {\n node.prompts.set(o.messageId, o)\n while (node.prompts.size > limits.maxPendingPromptsPerSession) {\n const oldest = node.prompts.entries().next()\n if (oldest.done === true) break\n node.prompts.delete(oldest.value[0])\n discard(oldest.value[1].content)\n const queued = node.pending.findIndex(item => item.inboxId === oldest.value[0])\n if (queued !== -1) node.pending.splice(queued, 1)\n }\n } else {\n // Mid-execution: it joins the running turn and opens no root of its own.\n addPrompt(invokeOf(node, active.trace), {\n messageId: o.messageId,\n at: o.at,\n content: o.content,\n delivery: o.delivery,\n midTurn: true,\n })\n touch(active.trace, o.at)\n }\n }\n\n function onEnqueued(o: Extract<Observation, {kind: 'inbox.enqueued'}>): void {\n const node = route(o)\n if (node === undefined) return\n let reportTrace: TraceState | undefined\n let reportTombstone: string | undefined\n if (o.item === 'synthetic' && o.childSessionId !== undefined) {\n for (const trace of traces) if (trace.outstanding.has(o.childSessionId)) reportTrace = trace\n const remembered = tombstones.get(o.childSessionId)\n // At exactly the ttl it is still remembered; one millisecond later it is not.\n reportTombstone =\n remembered !== undefined && o.at - remembered.at <= limits.tombstoneTtlMs ? remembered.traceId : undefined\n }\n const item: PendingItem = {\n inboxId: o.inboxId,\n kind: o.item,\n at: o.at,\n childSessionId: o.childSessionId,\n reportState: o.reportState,\n reportTrace,\n reportTombstone,\n joined: node.active !== undefined,\n claimed: false,\n }\n node.pending.push(item)\n if (node.active !== undefined) touch(node.active.trace, o.at)\n }\n\n function onDelivered(o: Extract<Observation, {kind: 'inbox.delivered'}>): void {\n const node = sessions.get(o.sessionId)\n if (node === undefined) return\n const index = node.pending.findIndex(item => item.inboxId === o.inboxId)\n if (index === -1) return\n const [item] = node.pending.splice(index, 1)\n node.prompts.delete(o.inboxId)\n if (item === undefined || item.kind !== 'synthetic' || item.childSessionId === undefined) return\n const trace = item.reportTrace\n if (trace === undefined || trace.closed || item.reportState === 'running') return\n trace.outstanding.delete(item.childSessionId)\n touch(trace, o.at)\n const parent = sessions.get(o.sessionId)\n // Delivered into a different turn's execution: this turn is done, and says where its report went.\n const runningIn = parent?.active?.trace\n if (parent !== undefined && runningIn !== undefined && runningIn !== trace && parent.id === trace.rootSessionId) {\n trace.root.reportDeliveredInTrace = runningIn.id\n }\n if (parent !== undefined) maybeClose(parent, trace, o.at)\n }\n\n function onCreated(o: Extract<Observation, {kind: 'session.created'}>): void {\n if (o.parentSessionId !== undefined && !linked.has(o.sessionId) && !sessions.has(o.sessionId)) {\n parentHints.set(o.sessionId, o.parentSessionId)\n while (parentHints.size > limits.maxTombstones) {\n const oldest = parentHints.keys().next()\n if (oldest.done === true) break\n parentHints.delete(oldest.value)\n }\n }\n const node = sessions.get(o.sessionId)\n if (node !== undefined && o.agent !== undefined) node.agent = o.agent\n if (node?.childOf !== undefined && o.agent !== undefined) node.childOf.invoke.agent ??= o.agent\n }\n\n function onExecutionStarted(o: Extract<Observation, {kind: 'execution.started'}>): void {\n const node = route(o)\n if (node === undefined) return\n // An execution cannot start before the previous one ended (or in the same millisecond, in any recording): the clock stepped\n // back across the boundary, and the previous end event settles hooks by a time that no longer orders them.\n if (o.at <= node.lastEndedAt) withhold(node)\n if (node.active === undefined) beginExecution(node, o.at)\n }\n\n function onExecutionEnded(o: Extract<Observation, {kind: 'execution.ended'}>): void {\n const node = sessions.get(o.sessionId)\n // The execution is over: what waited for a step that cannot be trusted is closed here, as incomplete.\n if (node !== undefined) closeUncertain(node, o.at)\n const trace = node?.active?.trace\n if (node === undefined || trace === undefined) return\n node.active = undefined\n trace.activeExecutions = Math.max(0, trace.activeExecutions - 1)\n touch(trace, o.at)\n const invoke = invokeOf(node, trace)\n if (o.outcome === 'succeeded') {\n maybeClose(node, trace, o.at)\n return\n }\n const status: SpanStatus = o.outcome === 'failed' ? 'error' : 'interrupted'\n const error: ErrorInfo | undefined =\n o.outcome === 'failed' ? (o.error ?? {type: 'execution.failed'}) : {type: 'interrupted', message: o.reason}\n invoke.status = status\n invoke.error = error\n if (node.id === trace.rootSessionId && node.childOf === undefined) {\n closeTrace(trace, o.at, status, {error})\n } else {\n emitInvoke(trace, invoke, o.at)\n }\n }\n\n function followOnClaims(node: SessionNode, trace: TraceState): string[] {\n const traceIds: string[] = []\n for (const item of node.pending) {\n if (item.kind !== 'synthetic' || item.claimed) continue\n item.claimed = true\n // The origin's id: from the trace itself when it is known (open or since closed), else from the tombstone it left.\n const origin = item.reportTrace?.id ?? item.reportTombstone\n if (origin !== undefined && origin !== trace.id) traceIds.push(origin)\n }\n return traceIds\n }\n\n function onRequest(o: Extract<Observation, {kind: 'request'}>): void {\n const node = route(o)\n if (node === undefined) return\n let trace = node.active?.trace\n if (trace === undefined) {\n const standalone = o.requestKind === 'generate' && node.pending.every(item => item.joined)\n if (standalone) {\n trace = openTrace(node.id, o.at, {standalone: 'generate'})\n trace.nodes.set(node.id, node)\n node.traces.add(trace)\n trace.root.agent = o.agent\n } else {\n trace = beginExecution(node, o.at)\n }\n }\n touch(trace, o.at)\n const invoke = invokeOf(node, trace)\n invoke.agent ??= o.agent\n node.agent ??= o.agent\n // Every primary hook, admitted or refused, consumes the retry hook's attempt number that came before it.\n const attempt = o.requestKind === 'primary' ? node.nextAttempt : 1\n if (o.requestKind === 'primary') node.nextAttempt = 1\n if (trace.openSpans >= limits.maxOpenSpansPerTrace) {\n droppedSpans += 1\n invoke.gaps.add('spans-over-limit')\n // No span, but its step still arrives and must find its own hook, which holds no request.\n if (o.requestKind === 'primary') recordHook(node, o.at, undefined)\n return\n }\n trace.openSpans += 1\n const request: RequestState = {\n spanId: ids.span(),\n trace,\n sessionId: node.id,\n parentSpanId: invoke.spanId,\n requestKind: o.requestKind,\n start: o.at,\n agent: o.requestKind === 'title' ? 'title' : o.agent,\n model: o.model,\n provider: o.provider,\n request: o.content,\n attempt,\n messageId: undefined,\n texts: [],\n outputChars: 0,\n reasoning: [],\n toolCalls: [],\n finishReason: undefined,\n rawFinishReason: undefined,\n usage: undefined,\n cost: undefined,\n followOnOf: o.requestKind === 'primary' ? followOnClaims(node, trace) : [],\n gaps: new Set(o.requestKind === 'primary' ? [] : ['finishReason', 'usage']),\n marks: new Set(),\n closed: false,\n bindUncertain: false,\n stepAgent: undefined,\n stepModel: undefined,\n stepProvider: undefined,\n }\n if (o.content === undefined) request.gaps.add('request')\n node.requests.push(request)\n if (o.requestKind === 'primary') {\n if (node.withheld) request.bindUncertain = true\n recordHook(node, o.at, request)\n }\n }\n\n // ------------------------------------------------------------------ binding steps to requests\n //\n // THE RULE. A primary request's hook carries no message id, and the step events that follow name only a message id, so a step is\n // joined to its request by TIME, never by arrival order. A `step.started` carries `started`, the server's clock at the start of\n // its attempt, taken after the request hook returned and before the provider was called: hook(n) <= started(n) <= hook(n+1) in\n // real time, as integers of the same clock. So a step belongs to the session's LATEST primary hook whose receive time is at or\n // before `started`, provided every earlier hook already has its step. It is wrong only when an earlier hook's step is the one in\n // hand: `started(n) == hook(n+1)` (a step that starts, runs and ends in the very millisecond the next hook arrives; the gap\n // between hook(n) and `started(n)` can be anything, another plugin's hook may sit in it), or a wall clock that stepped back\n // between hook(n) and `started(n)`, so that hook(n+1) reads earlier than `started(n)`. Arrival order cannot be used: the hook is\n // a direct call and the events come through a pull loop, so hook(n+1) is often seen before step.started(n).\n //\n // A step binds the request of that hook if it is still open and has no step, and the session is not withheld. Otherwise it binds\n // nothing and its later events (by message id) are ignored. A step older than every recorded hook binds nothing, and nothing\n // else: it cannot be confused with any recorded hook.\n //\n // ONE WITHHOLD STATE. A session that is withheld binds nothing until its execution ends. Every primary request of it that has\n // not finished (waiting or bound) and every later one exports no step data: only the hook's own agent, model, provider and\n // request, an incomplete outcome and the gap `step-binding-uncertain`, with no synthesized finish reason. It clears only on an\n // observed `execution.ended` for the session, and then the hook record restarts empty. It is set by exactly these triggers:\n // 1. An ambiguous step: it resolves to a hook and an EARLIER hook is still unconsumed. That earlier hook may own the step\n // (equal-millisecond start, or a clock step-back between its hook and its start). A hook is consumed when a step has\n // resolved to it, bound or not (a refused or lost hook's time-only entry too), or when its execution ended before it. Steps of a\n // session arrive in publish order, so ordinarily every earlier hook has had its step and nothing is ever withheld; a hook\n // observed AHEAD of earlier step events is not an earlier hook of any step before it. Over-withholding is accepted: an\n // abandoned request (a hook that never gets a step, as after a recovery) withholds the session at its next step, until the\n // execution ends. Under-withholding is not.\n // 2. The clock went backwards: a primary hook earlier than the previous one. Old-epoch steps may still be in flight and no\n // time can be trusted. (A step-back that leaves the later hook later than the previous one is trigger 1's: the step in flight\n // finds its own hook still waiting. Residual, undetectable: one across an execution boundary that reads the next execution's\n // hook before the previous end event's time and after the previous hook.)\n // 3. A loss without complete evidence: a loss marker that is a broadcast (it names no session: an unattributed drop, or more\n // sessions than a marker can hold), or whose lost-hook times no longer fit. A marker that names its session and carries the\n // time of every primary hook it stands for does not withhold: the hook is recorded like a refused one (it holds no request,\n // so a step that resolves to it binds nothing, and it counts for trigger 1 and 2: its own step is awaited), and the session's unfinished requests are\n // marked uncertain (the loss may have been a request's `step.started` or part of its output, which would show as the whole).\n // 4. A step whose `started` is missing or not a finite number: an event the join cannot place.\n // 5. An execution that starts at or before the previous one's end (by the events' own times; no recording has a gap under\n // 45 ms): the clock stepped back across the boundary, so the end event settles hooks by a time that no longer orders them.\n // (Residual, undetectable: a step-back after the start, and one across a boundary whose session was forgotten at its end,\n // which nothing remembers.)\n // Also: the hook record is bounded (`maxHookTimes`); evicting a hook that was never consumed withholds (its step could still\n // arrive and there would be nothing to compare it with).\n // Not a trigger: a request refused at the span cap. Its hook is recorded with no request, so its step resolves to it and binds\n // nothing; whether that step could be someone else's is trigger 1's question like any other.\n\n function recordHook(node: SessionNode, at: number, request: RequestState | undefined, lost = false): void {\n // A lost hook is told by an event, in event order: its time says nothing about the clock, only that the hook happened.\n node.newestHookAt = lost ? Math.max(node.newestHookAt, at) : at\n if (node.withheld) return\n const newest = node.hooks.at(-1)\n if (newest !== undefined && at < newest.at) {\n withhold(node)\n return\n }\n node.hooks.push({at, request, consumed: false})\n while (node.hooks.length > limits.maxHookTimes) {\n const gone = node.hooks.shift()\n if (gone !== undefined && !gone.consumed) {\n withhold(node)\n return\n }\n }\n }\n\n /** The session binds nothing until its execution ends: everything unfinished is uncertain, and so is everything that follows. */\n function withhold(node: SessionNode): void {\n if (!node.withheld) withholds += 1\n node.withheld = true\n node.hooks.length = 0\n markUnfinished(node)\n }\n\n /**\n * Marks every primary request of the session that has not finished as uncertain. Its step data is withheld whole, so what it\n * already holds is let go: the tool call arguments it shares with the tool spans are handed back (the chat span will not carry\n * them).\n */\n function markUnfinished(node: SessionNode): void {\n for (const request of node.requests) {\n if (request.requestKind !== 'primary' || request.closed || request.bindUncertain) continue\n request.bindUncertain = true\n for (const call of request.toolCalls) discard(call.input)\n request.toolCalls = []\n }\n }\n\n /** The hook a step started at `started` belongs to: the latest hook at or before it. Withholds when that is ambiguous. */\n function resolveStep(node: SessionNode, started: number): HookRecord | undefined {\n let index = node.hooks.length - 1\n while (index >= 0 && (node.hooks[index]?.at ?? Number.POSITIVE_INFINITY) > started) index -= 1\n const found = node.hooks[index]\n if (found === undefined) return undefined\n const waiting = node.hooks.findIndex(hook => !hook.consumed)\n if (waiting !== -1 && waiting < index) {\n withhold(node)\n return undefined\n }\n found.consumed = true\n return found\n }\n\n /**\n * The pipeline lost something here in the sequence. A buffered child hears of it in its own buffer, in order. A marker that\n * names its sessions and the time of each primary hook it lost records those hooks and marks what is unfinished; a marker that\n * does not (a broadcast, or one whose times no longer fit) withholds every session.\n */\n function onLoss(o: Extract<Observation, {kind: 'loss'}>): void {\n const broadcast = o.sessionIds === undefined || o.incomplete === true\n const named = (sessionId: string): void => {\n const lostHook = o.hookAt?.get(sessionId)\n const node = sessions.get(sessionId)\n if (node !== undefined) {\n if (broadcast) withhold(node)\n else {\n if (lostHook !== undefined) recordHook(node, lostHook, undefined, true)\n markUnfinished(node)\n }\n } else if (buffered.has(sessionId)) {\n bufferObservation(sessionId, {\n ...o,\n sessionIds: [sessionId],\n hookAt: lostHook === undefined ? undefined : new Map([[sessionId, lostHook]]),\n incomplete: broadcast,\n })\n } else if (lostHook !== undefined) rememberEarlyLostHook(sessionId, lostHook)\n }\n if (o.sessionIds !== undefined) {\n for (const sessionId of o.sessionIds) named(sessionId)\n return\n }\n // A broadcast reaches every session the model knows, and keeps the times it does carry for the sessions they belong to.\n for (const sessionId of new Set([...sessions.keys(), ...buffered.keys(), ...(o.hookAt?.keys() ?? [])]))\n named(sessionId)\n }\n\n /** A hook lost before its session was seen leaves its time all the same, applied when the session's node is created. */\n function rememberEarlyLostHook(sessionId: string, at: number): void {\n earlyLostHooks.delete(sessionId)\n earlyLostHooks.set(sessionId, Math.max(at, earlyLostHooks.get(sessionId) ?? at))\n while (earlyLostHooks.size > limits.maxTombstones) {\n const oldest = earlyLostHooks.keys().next()\n if (oldest.done === true) break\n earlyLostHooks.delete(oldest.value)\n }\n }\n\n /** The execution ended: what waited for a step that cannot be trusted is closed, as incomplete, and the withhold is over. */\n function closeUncertain(node: SessionNode, at: number): void {\n node.nextAttempt = 1\n node.lastEndedAt = at\n // A hook at or after the end time is the next execution's, observed before this event (hooks are direct calls, events a pull\n // loop). While the session was withheld such hooks were not recorded, and their steps would find a clean record: the withhold\n // then carries over to the next execution's end, and what is that execution's is left open.\n const carriesOver = node.withheld && node.newestHookAt >= at\n node.withheld = carriesOver\n // A step is published before its execution's end, so a hook of that execution that still has none never gets it. `at` is the\n // end event's own server time, taken when it was published; the next execution's hooks come after it. A hook at exactly that\n // time is left alone: it may be the next execution's. A settled hook never receives a step.\n for (const hook of node.hooks) {\n if (hook.at >= at) continue\n hook.consumed = true\n hook.request = undefined\n }\n for (const request of [...node.requests]) {\n if (!request.bindUncertain || request.closed || (carriesOver && request.start >= at)) continue\n request.gaps.add('output')\n emitRequest(request, at, 'interrupted', undefined, ['incomplete'])\n removeRequest(node, request)\n }\n }\n\n const oldestPending = (node: SessionNode, kind: RequestKind): RequestState | undefined =>\n node.requests.find(request => request.requestKind === kind && !request.closed && request.messageId === undefined)\n\n /** A closed request leaves the session's records: a session can outlive the trace the request belonged to. */\n function removeRequest(node: SessionNode, request: RequestState): void {\n const index = node.requests.indexOf(request)\n if (index !== -1) node.requests.splice(index, 1)\n if (request.messageId !== undefined && node.stepOwner.get(request.messageId) === request) {\n node.stepOwner.delete(request.messageId)\n }\n }\n\n function onRetry(o: Extract<Observation, {kind: 'retry'}>): void {\n const node = sessions.get(o.sessionId)\n if (node === undefined) return\n node.nextAttempt = o.willRetry ? o.attempt : 1\n // The retry hook follows the failed attempt's request hook on the hook channel, so the attempt that failed is the session's\n // newest primary hook. One that already has a step is closed by that step's failure; one with none is closed here, since no\n // output will ever join it, and its own `step.started`, when it comes, finds a closed request and binds nothing.\n const request = node.hooks.at(-1)?.request\n if (request === undefined || request.closed || request.messageId !== undefined || request.bindUncertain) return\n request.gaps.add('output')\n emitRequest(request, o.at, 'error', o.error)\n removeRequest(node, request)\n touch(request.trace, o.at)\n }\n\n function onStepStarted(o: Extract<Observation, {kind: 'step.started'}>): void {\n const node = sessions.get(o.sessionId)\n if (node === undefined) return\n if (o.started === undefined || !Number.isFinite(o.started)) {\n withhold(node)\n return\n }\n // A withheld session records no hooks, so a step finds none and binds nothing.\n const request = resolveStep(node, o.started)?.request\n if (request === undefined || request.closed || request.messageId !== undefined || request.bindUncertain) return\n request.messageId = o.messageId\n request.stepAgent = o.agent\n request.stepModel = o.model\n request.stepProvider = o.provider\n node.stepOwner.set(o.messageId, request)\n touch(request.trace, o.at)\n }\n\n function onStepEnded(o: Extract<Observation, {kind: 'step.ended'}>): void {\n const node = sessions.get(o.sessionId)\n const request = node?.stepOwner.get(o.messageId)\n if (node === undefined || request === undefined) return\n request.finishReason = o.finish\n request.rawFinishReason = o.rawFinish\n request.usage = o.usage\n request.cost = o.cost\n if (o.finish === undefined) request.gaps.add('finishReason')\n if (o.usage === undefined) request.gaps.add('usage')\n emitRequest(request, o.at, 'ok')\n removeRequest(node, request)\n touch(request.trace, o.at)\n }\n\n function onStepFailed(o: Extract<Observation, {kind: 'step.failed'}>): void {\n const node = sessions.get(o.sessionId)\n const request = node?.stepOwner.get(o.messageId)\n if (node === undefined || request === undefined) return\n request.usage = o.usage\n request.gaps.add('finishReason')\n emitRequest(request, o.at, o.error.type === 'aborted' ? 'interrupted' : 'error', o.error)\n removeRequest(node, request)\n touch(request.trace, o.at)\n }\n\n function onOutput(o: Extract<Observation, {kind: 'output'}>): void {\n const request = sessions.get(o.sessionId)?.stepOwner.get(o.messageId)\n if (request === undefined || request.bindUncertain) return\n if (o.omitted === true) {\n // The pipeline's inbox was full of raw text: the text is not here, and the span says so.\n request.gaps.add('output-omitted')\n return\n }\n addOutput(request, o.part === 'text' ? request.texts : request.reasoning, o.text)\n }\n\n /**\n * Keeps one output part, within the per-request and the aggregate character budgets and the part-count limit. A part that\n * does not fit is omitted whole, never clipped: a cut before redaction could split a secret. The request says so.\n */\n function addOutput(request: RequestState, parts: string[], text: string): void {\n if (request.closed) return\n if (parts.length >= limits.maxOutputParts) {\n request.gaps.add('output-over-limit')\n return\n }\n const room = Math.min(limits.maxOutputChars - request.outputChars, limits.maxHeldOutputChars - heldOutputChars)\n if (room <= 0) {\n request.gaps.add('output-omitted')\n return\n }\n // Raw text is never clipped before redaction (a cut could split a secret and leave its prefix): a part that does not fit\n // is omitted whole, and the span says so.\n if (text.length > room) {\n request.gaps.add('output-omitted')\n return\n }\n const kept = text\n parts.push(kept)\n request.outputChars += kept.length\n heldOutputChars += kept.length\n }\n\n // ------------------------------------------------------------------ tool calls\n //\n // A call's lifecycle comes from the session events: `session.tool.called` opens the span (published before any local\n // execution, v2.3.2 `step.ts`) and `session.tool.success` or `.failed` closes it, keyed by call id. A provider-executed\n // call never reaches the local path, so it has no hook at all. The `execute.before` and `execute.after` hooks only add\n // what the events do not carry: the agent, the arguments the tool received, and the result the hook saw. A hook that\n // arrives before its event is a note, held briefly and boundedly; one whose event never comes opens nothing.\n\n function noteFor(node: SessionNode, callId: string, at: number): ToolNote {\n let note = node.notes.get(callId)\n if (note === undefined) {\n note = {at}\n node.notes.set(callId, note)\n while (node.notes.size > limits.maxPendingToolNotes) {\n const oldest = node.notes.entries().next()\n if (oldest.done === true) break\n node.notes.delete(oldest.value[0])\n discardNote(oldest.value[1])\n }\n }\n return note\n }\n\n function expireNotes(now: number): void {\n for (const node of sessions.values()) {\n for (const [callId, note] of node.notes) {\n if (now - note.at > limits.toolNoteWaitMs) {\n node.notes.delete(callId)\n discardNote(note)\n } else break\n }\n }\n }\n\n /** Opens the span for a call, or returns the one already open. Undefined when no trace can hold it. */\n function openTool(\n node: SessionNode,\n callId: string,\n at: number,\n init: {tool?: string | undefined; gaps?: readonly string[]},\n ): ToolState | undefined {\n const existing = node.tools.get(callId)\n if (existing !== undefined) return existing\n const trace = node.active?.trace ?? node.childOf?.trace\n if (trace === undefined) return undefined\n if (trace.openSpans >= limits.maxOpenSpansPerTrace) {\n droppedSpans += 1\n invokeOf(node, trace).gaps.add('spans-over-limit')\n return undefined\n }\n trace.openSpans += 1\n const note = node.notes.get(callId)\n const tool: ToolState = {\n spanId: ids.span(),\n trace,\n sessionId: node.id,\n parentSpanId: invokeOf(node, trace).spanId,\n callId,\n tool: init.tool ?? note?.tool ?? note?.before?.tool ?? note?.after?.tool ?? 'unknown',\n start: at,\n agent: undefined,\n input: undefined,\n callInput: undefined,\n inputFromHook: false,\n result: undefined,\n resultFromHook: false,\n providerExecuted: false,\n afterStatus: undefined,\n afterError: undefined,\n interrupted: false,\n childSessionId: undefined,\n discarded: [],\n gaps: new Set(init.gaps ?? []),\n }\n node.tools.set(callId, tool)\n if (tool.tool === 'unknown') tool.gaps.add('tool-name')\n if (note?.before !== undefined) applyBefore(tool, note.before)\n if (note?.after !== undefined) applyAfter(node, tool, note.after)\n node.notes.delete(callId)\n touch(trace, at)\n return tool\n }\n\n function applyAfter(node: SessionNode, tool: ToolState, o: Extract<Observation, {kind: 'tool.after'}>): void {\n tool.afterStatus = o.status\n tool.afterError = o.error\n tool.interrupted = o.interrupted === true\n if (o.status === 'completed' && o.result !== undefined) {\n if (tool.result !== undefined) tool.discarded.push(tool.result)\n tool.result = o.result\n tool.resultFromHook = true\n }\n if (o.childSessionId !== undefined && isSubagentDispatch(tool)) link(node, tool, o.childSessionId, o.at)\n }\n\n function onToolNamed(o: Extract<Observation, {kind: 'tool.named'}>): void {\n const node = sessions.get(o.sessionId)\n if (node === undefined) return\n expireNotes(o.at)\n noteFor(node, o.callId, o.at).tool = o.tool\n }\n\n function onToolCalled(o: Extract<Observation, {kind: 'tool.called'}>): void {\n const node = sessions.get(o.sessionId)\n if (node === undefined) {\n discard(o.input)\n return\n }\n if (node.completed.has(o.callId)) {\n discard(o.input)\n return\n }\n const tool = openTool(node, o.callId, o.at, {})\n if (tool === undefined) {\n discard(o.input)\n return\n }\n tool.providerExecuted = o.executed\n tool.callInput = o.input\n if (!tool.inputFromHook) tool.input = o.input\n else if (o.input !== undefined) tool.discarded.push(o.input)\n const asked = o.messageId === undefined ? undefined : node.stepOwner.get(o.messageId)\n // An uncertain request's chat span carries no tool calls, so it takes no second owner of the arguments (nothing would release it).\n if (asked !== undefined && !asked.bindUncertain) {\n if (asked.toolCalls.length >= limits.maxOutputParts) asked.gaps.add('tool-calls-over-limit')\n else {\n asked.toolCalls.push({callId: o.callId, tool: tool.tool, input: o.input})\n // The same object is now held by the request's record and by the tool span: two owners.\n if (typeof o.input === 'object' && o.input !== null) retained.push(o.input)\n }\n }\n if (isSubagentDispatch(tool)) unresolved.add(`${node.id}/${o.callId}`)\n }\n\n function onToolBefore(o: Extract<Observation, {kind: 'tool.before'}>): void {\n const node = sessions.get(o.sessionId)\n if (node === undefined || node.completed.has(o.callId)) {\n discard(o.input)\n return\n }\n const tool = node.tools.get(o.callId)\n if (tool !== undefined) {\n applyBefore(tool, o)\n if (tool.tool === 'subagent') unresolved.add(`${node.id}/${o.callId}`)\n return\n }\n // The hook came first: hold it for the event, boundedly. If the event never comes this opens nothing.\n expireNotes(o.at)\n noteFor(node, o.callId, o.at).before = o\n }\n\n /** The dispatch link: this tool call started that child session. */\n function link(parent: SessionNode, tool: ToolState | undefined, childId: string, at: number): void {\n if (tool !== undefined) {\n tool.childSessionId ??= childId\n unresolved.delete(`${tool.sessionId}/${tool.callId}`)\n }\n if (linked.has(childId) || sessions.has(childId) || releasedChildren.has(childId)) return\n const trace = tool?.trace ?? parent.active?.trace ?? parent.childOf?.trace\n const entry = buffered.get(childId)\n buffered.delete(childId)\n if (entry !== undefined) bufferedBytes -= entry.bytes\n parentHints.delete(childId)\n if (trace === undefined || trace.closed) {\n // The dispatching turn is gone: the child cannot be placed in it.\n if (entry !== undefined) releaseBuffer(childId, entry.items, 'unattributed')\n return\n }\n const start = entry?.firstAt ?? at\n const invoke = newInvoke('child', childId, Math.min(start, at), tool?.spanId ?? invokeOf(parent, trace).spanId)\n if (tool === undefined) invoke.gaps.add('dispatch-call')\n const node = newNode(childId, {trace, invoke}, start)\n trace.nodes.set(childId, node)\n node.traces.add(trace)\n trace.outstanding.set(childId, parent.id)\n linked.add(childId)\n touch(trace, at)\n for (const item of entry?.items ?? []) dispatch(item)\n }\n\n function onToolAfter(o: Extract<Observation, {kind: 'tool.after'}>): void {\n const node = sessions.get(o.sessionId)\n if (node === undefined || node.completed.has(o.callId)) {\n discard(o.result)\n return\n }\n const tool = node.tools.get(o.callId)\n if (tool !== undefined) {\n applyAfter(node, tool, o)\n return\n }\n expireNotes(o.at)\n noteFor(node, o.callId, o.at).after = o\n }\n\n /** Error types that mean the call was refused before it ran, by the user's rules or by this plugin's own guard. */\n const REFUSED_ERROR_TYPES: ReadonlySet<string> = new Set(['permission.rejected', 'plugin.reuse-guard'])\n\n function onToolEnded(o: Extract<Observation, {kind: 'tool.ended'}>): void {\n const node = sessions.get(o.sessionId)\n if (node === undefined || node.completed.has(o.callId)) {\n // A repeat of a terminal event (or one for a session we do not hold): ignored, its snapshot handed back.\n discard(o.result)\n return\n }\n // A call can end with no called event: its input never parsed, or the events were lost. The end event is the authority.\n const tool = node.tools.get(o.callId) ?? openTool(node, o.callId, o.at, {gaps: ['call-event', 'input']})\n if (tool === undefined) return\n if (o.executed === true) tool.providerExecuted = true\n if (o.childSessionId !== undefined && isSubagentDispatch(tool)) link(node, tool, o.childSessionId, o.at)\n // What the hook saw wins; the event's content is what the model saw, for a call no hook fired for.\n if (!tool.resultFromHook && o.result !== undefined) {\n if (tool.result !== undefined) tool.discarded.push(tool.result)\n tool.result = o.result\n } else if (o.result !== undefined) {\n tool.discarded.push(o.result)\n }\n const outcome: ToolOutcome = o.succeeded\n ? 'success'\n : o.errorType !== undefined && REFUSED_ERROR_TYPES.has(o.errorType)\n ? 'rejected'\n : o.errorType === 'aborted' || tool.interrupted\n ? 'interrupted'\n : 'error'\n if (outcome !== 'success' || tool.result === undefined) tool.gaps.add('result')\n node.tools.delete(o.callId)\n unresolved.delete(`${node.id}/${o.callId}`)\n node.completed.add(o.callId)\n while (node.completed.size > limits.maxCompletedCallsPerSession) {\n const oldest = node.completed.values().next()\n if (oldest.done === true) break\n node.completed.delete(oldest.value)\n }\n emitTool(tool, o.at, outcome, {errorType: o.errorType, message: o.message, truncated: o.truncated})\n touch(tool.trace, o.at)\n }\n\n function onCompactionStarted(o: Extract<Observation, {kind: 'compaction.started'}>): void {\n const node = sessions.get(o.sessionId)\n const request = node === undefined ? undefined : oldestPending(node, 'compaction')\n if (request !== undefined && o.reason !== undefined) request.marks.add(`reason:${o.reason}`)\n }\n\n function onCompactionEnded(o: Extract<Observation, {kind: 'compaction.ended'}>): void {\n const node = sessions.get(o.sessionId)\n const request = node === undefined ? undefined : oldestPending(node, 'compaction')\n if (node === undefined || request === undefined) return\n if (o.ok) {\n if (o.omitted === true) request.gaps.add('output-omitted')\n else if (o.text !== undefined) addOutput(request, request.texts, o.text)\n request.usage = o.usage\n request.cost = o.cost\n request.gaps.delete('usage')\n if (o.usage === undefined) request.gaps.add('usage')\n }\n emitRequest(request, o.at, o.ok ? 'ok' : 'error', o.error)\n removeRequest(node, request)\n touch(request.trace, o.at)\n }\n\n function onTitle(o: Extract<Observation, {kind: 'title'}>): void {\n const node = sessions.get(o.sessionId)\n const request = node === undefined ? undefined : oldestPending(node, 'title')\n if (node === undefined || request === undefined) return\n if (o.omitted === true) request.gaps.add('output-omitted')\n else addOutput(request, request.texts, o.title)\n emitRequest(request, o.at, 'ok')\n removeRequest(node, request)\n touch(request.trace, o.at)\n const rootNode = request.trace.nodes.get(request.trace.rootSessionId)\n if (rootNode !== undefined && request.trace.activeExecutions === 0) maybeClose(rootNode, request.trace, o.at)\n }\n\n /** Cumulative usage moved with no execution running: the only completion signal a `generate` request has. */\n function onUsage(o: Extract<Observation, {kind: 'usage'}>): void {\n const node = sessions.get(o.sessionId)\n if (node === undefined || node.active !== undefined) return\n const request = oldestPending(node, 'generate')\n if (request === undefined) return\n emitRequest(request, o.at, 'ok')\n removeRequest(node, request)\n const trace = request.trace\n trace.root.start = Math.min(trace.root.start, request.start)\n closeTrace(trace, o.at, 'ok')\n }\n\n // ------------------------------------------------------------------ time\n\n function sweep(now: number): void {\n expireBuffers(now)\n expireIdleSessions(now)\n for (const trace of [...traces]) {\n if (trace.closed) continue\n const standalone = trace.root.standalone === 'generate'\n const limit = standalone ? limits.standaloneRequestTimeoutMs : limits.rootInactivityMs\n if (now - trace.lastActivity > limit) {\n closeTrace(trace, now, 'ok', {incomplete: true})\n } else if (\n trace.activeExecutions === 0 &&\n trace.outstanding.size === 0 &&\n now - trace.lastActivity > limits.titleWaitMs &&\n titlePending(trace)\n ) {\n // The turn is over and only a title's text is missing: close without it, not as incomplete.\n closeTrace(trace, now, trace.root.status)\n }\n }\n }\n\n function dispatch(observation: Observation): void {\n // A session waiting for its dispatch link keeps ALL its observations in order, whatever their kind: the step, output,\n // tool and end events of a child that finished before the link arrived are replayed with its start, never dropped.\n // (The buffer entry is removed before a replay, so replayed observations do not come back here.)\n if ('sessionId' in observation && buffered.has(observation.sessionId) && !sessions.has(observation.sessionId)) {\n bufferObservation(observation.sessionId, observation)\n return\n }\n switch (observation.kind) {\n case 'prompt':\n onPrompt(observation)\n break\n case 'inbox.enqueued':\n onEnqueued(observation)\n break\n case 'inbox.delivered':\n onDelivered(observation)\n break\n case 'session.created':\n onCreated(observation)\n break\n case 'execution.started':\n onExecutionStarted(observation)\n break\n case 'execution.ended':\n onExecutionEnded(observation)\n break\n case 'request':\n onRequest(observation)\n break\n case 'retry':\n onRetry(observation)\n break\n case 'step.started':\n onStepStarted(observation)\n break\n case 'step.ended':\n onStepEnded(observation)\n break\n case 'step.failed':\n onStepFailed(observation)\n break\n case 'output':\n onOutput(observation)\n break\n case 'loss':\n onLoss(observation)\n break\n case 'tool.named':\n onToolNamed(observation)\n break\n case 'tool.called':\n onToolCalled(observation)\n break\n case 'tool.before':\n onToolBefore(observation)\n break\n case 'tool.after':\n onToolAfter(observation)\n break\n case 'tool.ended':\n onToolEnded(observation)\n break\n case 'compaction.started':\n onCompactionStarted(observation)\n break\n case 'compaction.ended':\n onCompactionEnded(observation)\n break\n case 'title':\n onTitle(observation)\n break\n case 'usage':\n onUsage(observation)\n break\n case 'tick':\n expireNotes(observation.at)\n break\n }\n }\n\n return {\n observe: observation => {\n out = []\n clock = Math.max(clock, observation.at)\n sweep(clock)\n if ('sessionId' in observation) {\n const known = sessions.get(observation.sessionId)\n if (known !== undefined) known.lastActivity = clock\n }\n dispatch(observation)\n return out\n },\n takeRetained: () => {\n const taken = retained\n retained = []\n return taken\n },\n takeDiscarded: () => {\n const taken = discarded\n discarded = []\n return taken\n },\n flush: at => {\n out = []\n clock = Math.max(clock, at)\n for (const [sessionId, entry] of [...buffered]) {\n buffered.delete(sessionId)\n bufferedBytes -= entry.bytes\n releaseBuffer(sessionId, entry.items, 'unattributed')\n }\n for (const trace of [...traces]) closeTrace(trace, clock, 'interrupted', {incomplete: true})\n for (const node of sessions.values()) forgetSession(node)\n sessions.clear()\n tombstones.clear()\n bufferedBytes = 0\n unresolved.clear()\n linked.clear()\n releasedChildren.clear()\n parentHints.clear()\n pendingMarks.clear()\n return out\n },\n stats: () => ({\n openTraces: traces.size,\n sessions: sessions.size,\n bufferedSessions: buffered.size,\n bufferedBytes,\n hookTimes: [...sessions.values()].reduce((sum, node) => sum + node.hooks.length, 0),\n historyRequestsHeld: [...sessions.values()].reduce(\n (sum, node) => sum + node.hooks.filter(hook => hook.request !== undefined).length,\n 0,\n ),\n withholds,\n openSteps: [...sessions.values()].reduce((sum, node) => sum + node.stepOwner.size, 0),\n tombstones: tombstones.size,\n unresolvedDispatches: unresolved.size,\n heldOutputChars,\n pendingToolNotes: [...sessions.values()].reduce((sum, node) => sum + node.notes.size, 0),\n droppedSpans,\n }),\n }\n}\n","/**\n * The path from a hook call to an exported span, kept off the host's request path.\n *\n * A hook handler normalizes its payload into an observation, which already carries an immutable bounded snapshot of the\n * named content fields (`snapshot.ts`), and calls `observe`, which appends it to a bounded inbox and returns. The turn\n * model, attribute mapping, scrubbing, bounding, serialization and export all run later, from `setImmediate`, a few\n * milliseconds at a time, so a large request never delays the model call that fired the hook. Nothing here holds a\n * reference to a hook's input, so a later edit to it cannot change what a span records.\n *\n * Snapshots are counted by a ledger (count and characters, apart from the exporter's queue) and freed when the span they\n * belong to is exported or dropped, or when their observation is discarded.\n *\n * No SDK import: the exporter is an interface, so the whole path is testable without the OpenTelemetry packages.\n */\n\nimport type {ScrubbedSpan, Scrubber} from './content.js'\nimport type {AttributeOptions} from './genai-attributes.js'\nimport type {Observation} from './observation.js'\nimport type {ActionIdentity, ActionRunContext} from './settings.js'\nimport type {SnapshotLedger} from './snapshot.js'\nimport type {IdSource, SpanRecord, TurnModelLimits} from './turn-model.js'\n\nimport {randomBytes} from 'node:crypto'\nimport {toExportSpan} from './genai-attributes.js'\nimport {createTurnModel} from './turn-model.js'\n\nexport interface SpanSink {\n readonly export: (span: ScrubbedSpan) => void\n /** Spans that never reached `export`. */\n readonly drop: (spans?: number) => void\n}\n\n/**\n * What the inbox can hold, in two separate bounds (there is no third budget):\n * - FREE TEXT (`maxInboxChars`): model output, titles, summaries, error messages. Past it the text is omitted and marked.\n * - IDENTIFIER-ONLY entries (ids, names, labels): bounded by COUNT (`maxInbox` entries) and by SIZE per identifier\n * (`MAX_IDENTIFIER_CHARS`, 512 characters; a longer one is dropped as malformed). The identifier characters an entry holds\n * are counted in `stats().inboxChars` but never omitted. Worst case, an adversary filling every slot with the observation\n * kind that carries the most identifier fields (6, a `tool.after`) holds 8,192 x 6 x 512 = 25,165,824 characters\n * (24 Mi), on top of the 8 Mi of free text. Real identifiers are tens of characters (the longest seen in real-binary runs is\n * 30: session, message and inbox ids), so a full inbox holds about 1 Mi in practice.\n */\nexport interface PipelineLimits {\n /** Observations waiting for the model. Past this a new one is discarded and counted. */\n readonly maxInbox: number\n /** Records waiting to be mapped, scrubbed and exported. Past this a record is dropped and counted as a dropped span. */\n readonly maxRecords: number\n /** Time one scheduled turn of the loop may spend before yielding to the host. */\n readonly sliceMs: number\n /**\n * Raw text (model output, a title, a compaction summary, error messages) the inbox may hold at once, in characters. An\n * observation that would pass it is replaced by its structure with the text omitted and marked, never clipped: a cut\n * before redaction could split a secret. Snapshots (prompt, request and tool content) have their own ledger.\n */\n readonly maxInboxChars: number\n /** How often the model is told the time, so its inactivity bounds fire with no traffic. */\n readonly tickMs: number\n}\n\nexport const DEFAULT_PIPELINE_LIMITS: PipelineLimits = {\n maxInbox: 8_192,\n maxRecords: 2_048,\n sliceMs: 8,\n maxInboxChars: 8 * 1024 * 1024,\n tickMs: 60_000,\n}\n\nexport interface TracePipelineOptions extends ActionRunContext {\n readonly sink: SpanSink\n readonly scrubber: Scrubber\n /** Action mode only. */\n readonly identity?: ActionIdentity | undefined\n /** Frees each snapshot as its span leaves the pipeline. Absent: nothing is counted. */\n readonly ledger?: SnapshotLedger | undefined\n readonly now?: () => number\n readonly ids?: IdSource\n readonly modelLimits?: Partial<TurnModelLimits>\n readonly limits?: Partial<PipelineLimits>\n}\n\nexport interface PipelineStats {\n /** Observations discarded because the inbox was full. */\n readonly observationsDropped: number\n /** Records that could not be mapped or scrubbed. */\n readonly recordsFailed: number\n /** Observations whose text was replaced by its structure because the inbox's text budget was spent. */\n readonly observationsOmitted: number\n /** Characters of raw text the inbox holds right now. */\n readonly inboxChars: number\n /** Entries (session ids and lost-hook times) the loss markers in the inbox hold right now: bounded per marker. */\n readonly markerEntries: number\n}\n\nexport interface TracePipeline {\n /** Cheap: appends and schedules. Never throws. */\n readonly observe: (observation: Observation) => void\n /**\n * Runs what is pending, closes every open span as interrupted and incomplete, and stops, working for at most `budgetMs`\n * (one scrub can run over it, never more). What it has not done by then is dropped and counted, and its snapshots\n * released, so the caller can give the exporter the rest of its own bound.\n */\n readonly stop: (budgetMs?: number) => void\n readonly stats: () => PipelineStats\n}\n\n/** W3C-valid ids: 32 and 16 lowercase hex characters, never all zero. */\nexport const randomIds = (): IdSource => ({\n trace: () => randomBytes(16).toString('hex'),\n span: () => randomBytes(8).toString('hex'),\n})\n\n/**\n * Which strings an observation carries, by kind and what the inbox does with them. Every string-valued field is counted\n * against `maxInboxChars`; the table is the audit:\n *\n * | kind | free text (counted, omittable) | identifiers and labels (counted, never omitted) |\n * | ------------------- | --------------------------------------- | ------------------------------------------------------------------ |\n * | prompt | content when it is a raw string | sessionId, messageId, delivery |\n * | inbox.enqueued | | sessionId, inboxId, item, childSessionId, reportState |\n * | inbox.delivered | | sessionId, inboxId |\n * | session.created | | sessionId, parentSessionId, agent |\n * | execution.started | | sessionId |\n * | execution.ended | reason, error.message | sessionId, outcome, error.type |\n * | request | content when it is a raw string | sessionId, requestKind, agent, model, provider |\n * | retry | error.message | sessionId, error.type |\n * | step.started | | sessionId, messageId, agent, model, provider |\n * | step.ended | | sessionId, messageId, finish, rawFinish |\n * | step.failed | error.message | sessionId, messageId, error.type |\n * | output | text | sessionId, messageId, part |\n * | tool.named | | sessionId, callId, tool |\n * | tool.called | input when it is a raw string | sessionId, callId, messageId |\n * | tool.before | input when it is a raw string | sessionId, callId, tool, messageId, agent |\n * | tool.after | error.message, result when raw string | sessionId, callId, tool, status, childSessionId, error.type |\n * | tool.ended | message, result when it is a raw string | sessionId, callId, errorType, childSessionId |\n * | compaction.started | reason | sessionId, inputId |\n * | compaction.ended | text, error.message | sessionId, error.type |\n * | title | title | sessionId |\n * | usage, tick | | sessionId |\n *\n * A snapshot (a frozen object in `content`, `input` or `result`) is not text: the ledger bounds it. An identifier over\n * `MAX_IDENTIFIER_CHARS` is not real: the observation is dropped as malformed.\n */\nconst FREE_TEXT_KEYS: ReadonlySet<string> = new Set([\n 'text',\n 'title',\n 'message',\n 'reason',\n 'content',\n 'input',\n 'result',\n])\nconst MAX_IDENTIFIER_CHARS = 512\n\ninterface Measured {\n /** Characters of omittable free text. */\n readonly text: number\n /** Characters of identifiers and labels. */\n readonly identifiers: number\n /** An identifier too long to be real. */\n readonly oversized: boolean\n}\n\nconst isPlainRecord = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null\n\n/** What an observation holds in raw strings, by the audit above. Never throws. */\nfunction measure(observation: Observation): Measured {\n if (!isPlainRecord(observation)) return {text: 0, identifiers: 0, oversized: false}\n let text = 0\n let identifiers = 0\n let oversized = false\n const label = (value: string): void => {\n identifiers += value.length\n if (value.length > MAX_IDENTIFIER_CHARS) oversized = true\n }\n for (const [key, value] of Object.entries(observation)) {\n if (key === 'kind') continue\n if (typeof value === 'string') {\n if (FREE_TEXT_KEYS.has(key)) text += value.length\n else label(value)\n } else if (key === 'error') {\n if (typeof value === 'string') text += value.length\n else if (isPlainRecord(value)) {\n for (const [errorKey, errorValue] of Object.entries(value)) {\n if (typeof errorValue !== 'string') continue\n if (errorKey === 'message') text += errorValue.length\n else label(errorValue)\n }\n }\n }\n }\n return {text, identifiers, oversized}\n}\n\nconst OMITTED_MESSAGE = '[omitted]'\n\n/** The same observation without its free text, marked omitted: its place in the sequence, its identifiers and its snapshots are kept. */\nfunction withoutText(observation: Observation): Observation {\n const copy: Record<string, unknown> = {...observation}\n for (const [key, value] of Object.entries(observation)) {\n if (typeof value === 'string' && FREE_TEXT_KEYS.has(key)) {\n // A part's text stays a string (the model reads its absence from the flag); a message keeps a visible marker.\n copy[key] = key === 'text' || key === 'title' ? '' : key === 'message' ? OMITTED_MESSAGE : undefined\n } else if (key === 'error' && isPlainRecord(value)) {\n const error: Record<string, unknown> = {...value}\n if (typeof error.message === 'string') error.message = OMITTED_MESSAGE\n copy.error = error\n } else if (key === 'error' && typeof value === 'string') {\n copy.error = OMITTED_MESSAGE\n }\n }\n copy.omitted = true\n return copy as unknown as Observation\n}\n\nexport function createTracePipeline(options: TracePipelineOptions): TracePipeline {\n const limits: PipelineLimits = {...DEFAULT_PIPELINE_LIMITS, ...options.limits}\n const now = options.now ?? Date.now\n const model = createTurnModel({\n ids: options.ids ?? randomIds(),\n ...(options.modelLimits === undefined ? {} : {limits: options.modelLimits}),\n })\n const attributeOptions: AttributeOptions = {\n identity: options.identity,\n rootSpan: options.rootSpan,\n sessionId: options.sessionId,\n invocationId: options.invocationId,\n }\n /** Observations waiting for the model, each with the raw text it holds against `maxInboxChars`. */\n const inbox: {readonly observation: Observation; readonly chars: number}[] = []\n /**\n * Loss markers in `inbox`. They are not counted against `maxInbox` (the room for ordinary observations): a marker has a\n * reserved slot and can never be dropped. Markers merge when adjacent, so there are never more than one more than the\n * ordinary observations: the inbox stays bounded.\n */\n let markers = 0\n let inboxChars = 0\n let observationsOmitted = 0\n const records: SpanRecord[] = []\n let scheduled = false\n let stopped = false\n let observationsDropped = 0\n let recordsFailed = 0\n let tick: NodeJS.Timeout | undefined\n\n /** The most sessions one marker names; past it the marker names none, which means every session. */\n const MAX_MARKER_SESSIONS = 32\n\n const atOf = (observation: Observation): number => {\n try {\n return isPlainRecord(observation) && typeof observation.at === 'number' ? observation.at : now()\n } catch {\n return now()\n }\n }\n const sessionOf = (observation: Observation): string | undefined => {\n try {\n return isPlainRecord(observation) && typeof observation.sessionId === 'string' ? observation.sessionId : undefined\n } catch {\n return undefined\n }\n }\n\n /** The receive time of a primary request hook, when `observation` is one: the loss of a hook is told with its time. */\n const hookTimeOf = (observation: Observation): number | undefined => {\n try {\n return isPlainRecord(observation) && observation.kind === 'request' && observation.requestKind === 'primary'\n ? atOf(observation)\n : undefined\n } catch {\n return undefined\n }\n }\n\n /**\n * A marker's lost-hook times with `time` for `session` folded in (the newest per session); nothing for a drop with no session.\n * At most MAX_MARKER_SESSIONS sessions: a time that does not fit is not kept, and the marker is then a broadcast (it names every\n * session), which the model treats as evidence it cannot complete. A burst of drops cannot grow the marker.\n */\n const hookTimes = (\n known: ReadonlyMap<string, number> | undefined,\n session: string | undefined,\n time: number | undefined,\n ): {hookAt?: ReadonlyMap<string, number>} => {\n const merged = new Map(known)\n if (session !== undefined && time !== undefined && (merged.has(session) || merged.size < MAX_MARKER_SESSIONS)) {\n merged.set(session, Math.max(time, merged.get(session) ?? time))\n }\n return merged.size === 0 ? {} : {hookAt: merged}\n }\n\n /**\n * Tells the model, in order, that `observation` never reached it: a marker at the tail (it happened after everything queued)\n * or, for one the model just failed on, at the front. A marker next to another one joins it. A drop with no known session\n * makes a marker that names none: every session.\n */\n function lose(observation: Observation, reason: string, position: 'tail' | 'front' = 'tail'): void {\n // A session id that size is malformed (it is not stored): the loss counts for every session.\n const named = sessionOf(observation)\n const session = named !== undefined && named.length <= MAX_IDENTIFIER_CHARS ? named : undefined\n const edge = position === 'tail' ? inbox.at(-1) : inbox[0]\n const merged = edge?.observation\n if (isPlainRecord(merged) && merged.kind === 'loss') {\n const sessionIds =\n merged.sessionIds === undefined || session === undefined\n ? undefined\n : merged.sessionIds.includes(session)\n ? merged.sessionIds\n : merged.sessionIds.length >= MAX_MARKER_SESSIONS\n ? undefined\n : [...merged.sessionIds, session]\n const joined: Observation = {...merged, sessionIds, ...hookTimes(merged.hookAt, session, hookTimeOf(observation))}\n if (position === 'tail') inbox[inbox.length - 1] = {observation: joined, chars: 0}\n else inbox[0] = {observation: joined, chars: 0}\n return\n }\n const marker: Observation = {\n kind: 'loss',\n at: atOf(observation),\n sessionIds: session === undefined ? undefined : [session],\n reason,\n ...hookTimes(undefined, session, hookTimeOf(observation)),\n }\n if (position === 'tail') inbox.push({observation: marker, chars: 0})\n else inbox.unshift({observation: marker, chars: 0})\n markers += 1\n }\n\n /** Every snapshot a record holds: the request, the prompts, a tool's arguments and its result. */\n function release(record: SpanRecord): void {\n const {ledger} = options\n if (ledger === undefined) return\n if (record.kind === 'chat') ledger.release(record.request)\n else if (record.kind === 'execute_tool') {\n ledger.release(record.input)\n ledger.release(record.result)\n for (const replaced of record.discarded) ledger.release(replaced)\n } else for (const prompt of record.prompts) ledger.release(prompt.content)\n if (record.kind === 'chat') for (const call of record.toolCalls) ledger.release(call.input)\n }\n\n /** An observation that never reaches the model gives its snapshot back. */\n function releaseObservation(observation: Observation): void {\n const {ledger} = options\n if (ledger === undefined || typeof observation !== 'object' || observation === null) return\n if (observation.kind === 'prompt' || observation.kind === 'request') ledger.release(observation.content)\n else if (observation.kind === 'tool.before' || observation.kind === 'tool.called') ledger.release(observation.input)\n else if (observation.kind === 'tool.ended') ledger.release(observation.result)\n else if (observation.kind === 'tool.after') ledger.release(observation.result)\n }\n\n /** Snapshots the model dropped with no span (an expired session's prompts, a timed-out hook note): freed here. */\n /** A snapshot the model now holds twice needs two releases: the ledger counts its owners. */\n function retainShared(): void {\n const shared = model.takeRetained()\n if (options.ledger === undefined) return\n for (const snapshot of shared) options.ledger.retain(snapshot)\n }\n\n function releaseDiscarded(): void {\n const dropped = model.takeDiscarded()\n if (options.ledger === undefined) return\n for (const snapshot of dropped) options.ledger.release(snapshot)\n }\n\n /** Spans the model refused at its open-span limit that the sink has been told about. */\n let forwardedDrops = 0\n /** Tells the sink about spans the model refused, once each: the model keeps a running total, this sends the difference. */\n function forwardDrops(): void {\n const total = model.stats().droppedSpans\n if (total <= forwardedDrops) return\n const owed = total - forwardedDrops\n // Counted as told before the sink hears it: a sink that throws loses these counts, it never makes them repeat.\n forwardedDrops = total\n tellSink(owed)\n }\n\n /** The sink's `drop`, which may throw: its failure is its own, and never a reason to treat the model's work as lost. */\n function tellSink(count: number): void {\n try {\n options.sink.drop(count)\n } catch {\n // Nothing more can be done with a count the sink will not take.\n }\n }\n\n function enqueue(spans: readonly SpanRecord[]): void {\n for (const record of spans) {\n if (records.length >= limits.maxRecords) {\n tellSink(1)\n release(record)\n continue\n }\n records.push(record)\n }\n }\n\n function exportRecord(record: SpanRecord): void {\n try {\n options.sink.export(toExportSpan(record, attributeOptions, options.scrubber))\n } catch {\n recordsFailed += 1\n tellSink(1)\n } finally {\n release(record)\n }\n }\n\n function step(): boolean {\n const queued = inbox.shift()\n if (queued !== undefined) {\n inboxChars -= queued.chars\n const next = queued.observation\n if (isPlainRecord(next) && next.kind === 'loss') markers -= 1\n let produced: SpanRecord[] | undefined\n try {\n produced = model.observe(next)\n } catch {\n // A model failure loses this observation, never the session; the model hears of it before it sees anything else.\n observationsDropped += 1\n releaseObservation(next)\n lose(next, 'model-failed', 'front')\n }\n if (produced !== undefined) {\n try {\n enqueue(produced)\n retainShared()\n releaseDiscarded()\n forwardDrops()\n } catch {\n // What the model did is done; a failure handing it on is not a failure of the observation.\n }\n }\n return true\n }\n const record = records.shift()\n if (record === undefined) return false\n exportRecord(record)\n return true\n }\n\n function run(): void {\n scheduled = false\n const started = performance.now()\n while (performance.now() - started < limits.sliceMs && step()) {\n // Work until the slice is spent.\n }\n if (inbox.length > 0 || records.length > 0) schedule()\n }\n\n function schedule(): void {\n if (scheduled || stopped) return\n scheduled = true\n setImmediate(run)\n }\n\n tick = setInterval(() => {\n inbox.push({observation: {kind: 'tick', at: now()}, chars: 0})\n schedule()\n }, limits.tickMs)\n tick.unref()\n\n return {\n observe: observation => {\n if (stopped) return\n if (inbox.length - markers >= limits.maxInbox) {\n observationsDropped += 1\n releaseObservation(observation)\n lose(observation, 'inbox-full')\n return\n }\n const measured = measure(observation)\n if (measured.oversized) {\n // An identifier that size is not real: malformed, dropped, and anything it holds is freed.\n observationsDropped += 1\n releaseObservation(observation)\n lose(observation, 'identifier-too-long')\n return\n }\n // Raw text over the remaining budget is replaced by its structure with the text omitted and marked. The replacement\n // keeps the snapshots the observation holds, so they stay charged in the ledger until their span goes.\n let held = observation\n let heldChars = measured.text + measured.identifiers\n if (measured.text > 0 && inboxChars + heldChars > limits.maxInboxChars) {\n held = withoutText(observation)\n heldChars = measured.identifiers\n observationsOmitted += 1\n }\n inboxChars += heldChars\n inbox.push({observation: held, chars: heldChars})\n schedule()\n },\n stop: (budgetMs = Number.POSITIVE_INFINITY) => {\n if (stopped) return\n if (tick !== undefined) clearInterval(tick)\n tick = undefined\n const deadline = performance.now() + budgetMs\n const timeLeft = (): boolean => performance.now() < deadline\n // Observations first, so the model sees everything that happened; each step may be a slow one.\n while (inbox.length > 0 && timeLeft()) step()\n // Out of time: what was never processed is lost, and its snapshots go back to the ledger. The model flushes next and closes\n // every span as incomplete, so it needs no marker: nothing more will arrive for it to pair wrongly.\n for (const unprocessed of inbox.splice(0)) {\n if (isPlainRecord(unprocessed.observation) && unprocessed.observation.kind === 'loss') continue\n observationsDropped += 1\n releaseObservation(unprocessed.observation)\n }\n markers = 0\n inboxChars = 0\n try {\n enqueue(model.flush(now()))\n retainShared()\n releaseDiscarded()\n forwardDrops()\n } catch {\n observationsDropped += 1\n }\n stopped = true\n while (records.length > 0 && timeLeft()) step()\n // Whatever is left is counted as dropped spans and released.\n for (const left of records.splice(0)) {\n tellSink(1)\n release(left)\n }\n },\n stats: () => ({\n observationsDropped,\n recordsFailed,\n observationsOmitted,\n inboxChars,\n markerEntries: inbox.reduce(\n (sum, queued) =>\n queued.observation.kind === 'loss'\n ? sum + (queued.observation.sessionIds?.length ?? 0) + (queued.observation.hookAt?.size ?? 0)\n : sum,\n 0,\n ),\n }),\n }\n}\n","/**\n * From OpenCode hook payloads and bus events to the turn model's observations, and the recorder that registers every\n * hook and event the model needs. The recorder is what produced `turn-model.fixtures.ts` from a real binary; the same\n * normalizers feed the model in production.\n *\n * Payload shapes are the ones the pinned 2.3.2 binary sends. A field that is absent or of another type yields no\n * observation or an observation without that field: a drifted shape shows up as a gap, never as a throw.\n */\n\nimport type {ErrorInfo, Observation, RequestKind, Usage} from './observation.js'\nimport type {SnapshotContext} from './snapshot.js'\n\nimport {snapshotPrompt, snapshotRequest, snapshotSize, snapshotToolArguments, snapshotToolResult} from './snapshot.js'\n\ntype Json = Record<string, unknown>\n\nconst isRecord = (value: unknown): value is Json => typeof value === 'object' && value !== null && !Array.isArray(value)\nconst asRecord = (value: unknown): Json | undefined => (isRecord(value) ? value : undefined)\nconst asString = (value: unknown): string | undefined => (typeof value === 'string' ? value : undefined)\nconst asNumber = (value: unknown): number | undefined =>\n typeof value === 'number' && Number.isFinite(value) ? value : undefined\n\nfunction modelOf(value: unknown): {model: string | undefined; provider: string | undefined} {\n const model = asRecord(value)\n return {model: asString(model?.id), provider: asString(model?.providerID)}\n}\n\nfunction errorOf(value: unknown): ErrorInfo {\n const error = asRecord(value)\n return {type: asString(error?.type) ?? 'unknown', message: asString(error?.message), status: asNumber(error?.status)}\n}\n\nfunction usageOf(value: unknown): Usage | undefined {\n const tokens = asRecord(value)\n if (tokens === undefined) return undefined\n const cache = asRecord(tokens.cache)\n const input = asNumber(tokens.input)\n const output = asNumber(tokens.output)\n if (input === undefined || output === undefined) return undefined\n return {\n input,\n output,\n reasoning: asNumber(tokens.reasoning) ?? 0,\n cacheRead: asNumber(cache?.read) ?? 0,\n cacheWrite: asNumber(cache?.write) ?? 0,\n }\n}\n\nconst REQUEST_HOOKS: Readonly<Record<string, RequestKind>> = {\n context: 'primary',\n compaction: 'compaction',\n title: 'title',\n generate: 'generate',\n}\n\n/** The child session a `subagent` tool call started, from the metadata its result and its success event carry. */\nfunction childOfSubagent(tool: string, metadata: unknown): string | undefined {\n return tool === 'subagent' ? asString(asRecord(metadata)?.sessionID) : undefined\n}\n\n/**\n * One hook call as an observation. `name` is `session.<hook>` or `tool.<hook>`.\n *\n * Nothing of the payload is kept. What the span will carry (request, prompt, tool arguments and result) is taken here, as\n * an immutable bounded snapshot of the named fields (`snapshot.ts`), so a later edit to the hook's input by the host or by\n * another plugin cannot change the hook-time view. Everything else is read into primitives. The work is a walk over the\n * named fields: strings are shared, never copied or serialized.\n */\nexport function observeHook(\n name: string,\n payload: unknown,\n at: number,\n snapshot: SnapshotContext = {},\n): Observation | undefined {\n const event = asRecord(payload)\n if (event === undefined) return undefined\n const sessionId = asString(event.sessionID)\n if (sessionId === undefined) return undefined\n\n if (name === 'session.prompt') {\n const messageId = asString(event.messageID)\n if (messageId === undefined) return undefined\n const content = snapshotPrompt(event.prompt, snapshot)\n return {kind: 'prompt', at, sessionId, messageId, delivery: asString(event.delivery), content, bytes: content.size}\n }\n\n const requestKind = name.startsWith('session.') ? REQUEST_HOOKS[name.slice('session.'.length)] : undefined\n if (requestKind !== undefined) {\n const {model, provider} = modelOf(event.model)\n const content = snapshotRequest({system: event.system, messages: event.messages, tools: event.tools}, snapshot)\n return {\n kind: 'request',\n at,\n sessionId,\n requestKind,\n agent: asString(event.agent),\n model,\n provider,\n content,\n bytes: content.size,\n }\n }\n\n if (name === 'session.retry') {\n const decision = asRecord(event.decision)\n return {\n kind: 'retry',\n at,\n sessionId,\n attempt: asNumber(event.attempt) ?? 0,\n willRetry: decision?.retry === true,\n error: errorOf(event.error),\n }\n }\n\n if (name === 'tool.execute.before') {\n const callId = asString(event.id)\n const tool = asString(event.tool)\n if (callId === undefined || tool === undefined) return undefined\n return {\n kind: 'tool.before',\n at,\n sessionId,\n callId,\n tool,\n messageId: asString(event.messageID),\n agent: asString(event.agent),\n input: snapshotToolArguments(event.input, snapshot),\n }\n }\n\n if (name === 'tool.execute.after') {\n const callId = asString(event.id)\n const tool = asString(event.tool)\n if (callId === undefined || tool === undefined) return undefined\n const failed = event.status === 'error'\n const result = asRecord(event.result)\n const error = asRecord(event.error)\n return {\n kind: 'tool.after',\n at,\n sessionId,\n callId,\n tool,\n status: failed ? 'error' : 'completed',\n result: failed ? undefined : snapshotToolResult(event.result, snapshot),\n error: failed ? errorOf(event.error) : undefined,\n interrupted: asRecord(error?.metadata)?.interrupted === true,\n childSessionId: childOfSubagent(tool, result?.metadata),\n }\n }\n\n return undefined\n}\n\n/**\n * The error type a failed tool event carries, or `plugin.reuse-guard` when the message is this plugin's own guard's fixed\n * refusal. The guard throws in the `execute.before` hook; the server publishes that as a failed call whose error type is\n * `unknown` (measured on 2.3.2), so the fixed text is the only thing that says who refused it.\n */\n/**\n * The guard's fixed refusal text, copied here, not imported: a module shared with the entry would make the bundler hoist\n * it into a chunk the entry imports statically, and the entry may import nothing but host modules. `record-observations.test.ts`\n * pins this copy to `TASK_REUSE_REJECTION`.\n */\nexport const GUARD_REFUSAL_TEXT =\n 'Session reuse is disabled in this environment. Start a new task and include the context it needs.'\n\nfunction toolErrorType(type: string | undefined, message: string | undefined): string | undefined {\n return message === GUARD_REFUSAL_TEXT ? 'plugin.reuse-guard' : type\n}\n\n/** How far into a report's text the subagent header is looked for. */\nconst REPORT_HEADER_WINDOW = 400\n\n/**\n * The two header forms a subagent report opens with. OpenCode 2.3.2 writes `<subagent sessionID=… state=… …>`; 2.4.1\n * (upstream #64971) writes `<background-result kind=\"subagent\" sessionID=… state=… …>`. A `<background-result>` of any\n * other kind (`shell`, `image`, `codemode`) is not a subagent report.\n */\nconst REPORT_HEADER_PREFIXES = ['<subagent ', '<background-result kind=\"subagent\" '] as const\n\n/**\n * The state a subagent report carries. The report's own header is the truth (`<subagent … state=\"running\" …>` on 2.3.2,\n * `<background-result kind=\"subagent\" … state=\"running\" …>` on 2.4.1): the item's `metadata.state` says `completed` even\n * on the interim report a parent gets while the child's own background work still runs. Reads only the head of the text,\n * by `indexOf`, so cost does not grow with a report's size.\n */\nexport function reportStateOf(text: unknown, metadata: Json | undefined): string | undefined {\n if (typeof text === 'string') {\n const head = text.slice(0, REPORT_HEADER_WINDOW)\n const close = head.indexOf('>')\n const marker = head.indexOf(' state=\"')\n if (\n REPORT_HEADER_PREFIXES.some(prefix => head.startsWith(prefix)) &&\n marker !== -1 &&\n (close === -1 || marker < close)\n ) {\n const from = marker + ' state=\"'.length\n const to = head.indexOf('\"', from)\n if (to !== -1) return head.slice(from, to)\n }\n }\n return asString(metadata?.state)\n}\n\nfunction itemKind(item: Json | undefined): 'user' | 'synthetic' | 'compaction' | 'other' {\n const type = asString(item?.type)\n return type === 'user' || type === 'synthetic' || type === 'compaction' ? type : 'other'\n}\n\n/** One bus event as an observation. Events the model does not read (deltas, config updates, usage detail) yield none. */\nexport function observeEvent(raw: unknown, snapshot: SnapshotContext = {}): Observation | undefined {\n const event = asRecord(raw)\n const type = asString(event?.type)\n const data = asRecord(event?.data)\n const at = asNumber(event?.created)\n if (event === undefined || type === undefined || data === undefined || at === undefined) return undefined\n const sessionId = asString(data.sessionID)\n if (sessionId === undefined) return undefined\n const messageId = asString(data.assistantMessageID)\n\n switch (type) {\n case 'session.created':\n return {\n kind: 'session.created',\n at,\n sessionId,\n parentSessionId: asString(data.parentID),\n agent: asString(data.agent),\n }\n case 'session.inbox.enqueued': {\n const inboxId = asString(data.inboxID)\n if (inboxId === undefined) return undefined\n const item = asRecord(data.item)\n const payload = asRecord(item?.payload)\n const metadata = asRecord(payload?.metadata)\n const report = asString(metadata?.source) === 'subagent'\n return {\n kind: 'inbox.enqueued',\n at,\n sessionId,\n inboxId,\n item: itemKind(item),\n childSessionId: report ? asString(metadata?.childID) : undefined,\n reportState: report ? reportStateOf(payload?.text, metadata) : undefined,\n }\n }\n case 'session.inbox.delivered': {\n const inboxId = asString(data.inboxID)\n return inboxId === undefined ? undefined : {kind: 'inbox.delivered', at, sessionId, inboxId}\n }\n case 'session.execution.started':\n return {kind: 'execution.started', at, sessionId}\n case 'session.execution.succeeded':\n return {kind: 'execution.ended', at, sessionId, outcome: 'succeeded'}\n case 'session.execution.failed':\n return {kind: 'execution.ended', at, sessionId, outcome: 'failed', error: errorOf(data.error)}\n case 'session.execution.interrupted':\n return {kind: 'execution.ended', at, sessionId, outcome: 'interrupted', reason: asString(data.reason)}\n case 'session.step.started': {\n if (messageId === undefined) return undefined\n const {model, provider} = modelOf(data.model)\n return {\n kind: 'step.started',\n at,\n sessionId,\n messageId,\n started: asNumber(data.started),\n agent: asString(data.agent),\n model,\n provider,\n }\n }\n case 'session.step.ended':\n return messageId === undefined\n ? undefined\n : {\n kind: 'step.ended',\n at,\n sessionId,\n messageId,\n finish: asString(data.finish),\n rawFinish: asString(data.rawFinish),\n usage: usageOf(data.tokens),\n cost: asNumber(data.cost),\n }\n case 'session.step.failed':\n return messageId === undefined\n ? undefined\n : {kind: 'step.failed', at, sessionId, messageId, error: errorOf(data.error), usage: usageOf(data.tokens)}\n case 'session.text.ended':\n case 'session.reasoning.ended': {\n const text = asString(data.text)\n if (messageId === undefined || text === undefined) return undefined\n return {\n kind: 'output',\n at,\n sessionId,\n messageId,\n part: type === 'session.text.ended' ? 'text' : 'reasoning',\n text,\n bytes: text.length,\n }\n }\n case 'session.tool.input.started': {\n const callId = asString(data.id)\n const tool = asString(data.name)\n return callId === undefined || tool === undefined ? undefined : {kind: 'tool.named', at, sessionId, callId, tool}\n }\n case 'session.tool.called': {\n const callId = asString(data.id)\n if (callId === undefined) return undefined\n const input = snapshotToolArguments(data.input, snapshot)\n return {\n kind: 'tool.called',\n at,\n sessionId,\n callId,\n messageId,\n executed: data.executed === true,\n input,\n bytes: snapshotSize(input),\n }\n }\n case 'session.tool.success':\n case 'session.tool.failed': {\n const callId = asString(data.id)\n if (callId === undefined) return undefined\n const metadata = asRecord(data.metadata)\n const error = asRecord(data.error)\n const succeeded = type === 'session.tool.success'\n return {\n kind: 'tool.ended',\n at,\n sessionId,\n callId,\n executed: data.executed === true,\n result: succeeded ? snapshotToolResult({content: data.content, metadata}, snapshot) : undefined,\n succeeded,\n errorType: toolErrorType(asString(error?.type), asString(error?.message)),\n message: asString(error?.message),\n truncated: typeof metadata?.truncated === 'boolean' ? metadata.truncated : undefined,\n // Only the stock `subagent` tool puts a child session id here; the model checks the tool when it links.\n childSessionId: asString(metadata?.sessionID),\n }\n }\n case 'session.compaction.started':\n return {kind: 'compaction.started', at, sessionId, reason: asString(data.reason), inputId: asString(data.inputID)}\n case 'session.compaction.ended':\n return {\n kind: 'compaction.ended',\n at,\n sessionId,\n ok: true,\n text: asString(data.text),\n usage: usageOf(data.tokens),\n cost: asNumber(data.cost),\n }\n case 'session.compaction.failed':\n return {kind: 'compaction.ended', at, sessionId, ok: false, error: errorOf(data.error)}\n case 'session.renamed': {\n const title = asString(data.title)\n return title === undefined ? undefined : {kind: 'title', at, sessionId, title}\n }\n case 'session.usage.updated':\n return {kind: 'usage', at, sessionId}\n default:\n return undefined\n }\n}\n\nexport type SessionHookName = 'prompt' | 'context' | 'compaction' | 'generate' | 'title' | 'retry'\n\n/**\n * The slice of the plugin context the observers register on. Structural, so a fake host can stand in and the real\n * `Plugin.Context` still fits.\n */\nexport interface ObserverHost {\n readonly session: {\n hook: (name: SessionHookName, callback: (event: unknown) => void) => Promise<unknown>\n }\n readonly tool: {\n hook: (name: 'execute.before' | 'execute.after', callback: (event: unknown) => void) => Promise<unknown>\n }\n readonly event: {\n subscribe: () => AsyncIterable<unknown>\n }\n}\n\n/**\n * Registers every hook and the bus subscription the model reads, and passes each observation to `emit`. Handlers read and\n * return; they never touch the hook's arguments, and a throwing `emit` or normalizer never reaches the host.\n * Returns a stop function for the event subscription.\n */\nexport async function registerObservers(\n host: ObserverHost,\n emit: (observation: Observation) => void,\n now: () => number = Date.now,\n snapshot: SnapshotContext = {},\n): Promise<() => void> {\n const deliver = (observation: Observation | undefined): void => {\n if (observation === undefined) return\n try {\n emit(observation)\n } catch {\n // Observation must never fail a session.\n }\n }\n const sessionHook = async (name: SessionHookName): Promise<void> => {\n await host.session.hook(name, event => {\n try {\n deliver(observeHook(`session.${name}`, event, now(), snapshot))\n } catch {\n // See above.\n }\n })\n }\n for (const name of ['prompt', 'context', 'compaction', 'generate', 'title', 'retry'] as const) await sessionHook(name)\n for (const name of ['execute.before', 'execute.after'] as const) {\n await host.tool.hook(name, event => {\n try {\n deliver(observeHook(`tool.${name}`, event, now(), snapshot))\n } catch {\n // See above.\n }\n })\n }\n\n let stopped = false\n const pump = async (): Promise<void> => {\n try {\n for await (const event of host.event.subscribe()) {\n if (stopped) break\n try {\n deliver(observeEvent(event, snapshot))\n } catch {\n // See above.\n }\n }\n } catch {\n // A closed subscription ends the stream.\n }\n }\n pump().catch(() => {})\n return () => {\n stopped = true\n }\n}\n","/**\n * Lazy tracing entry. `setup.ts` reaches this module through one dynamic `import()` so the bundler emits it, and the\n * OpenTelemetry SDK it pulls in, as a separate chunk that is evaluated only when tracing resolves to on.\n *\n * `startTracing` builds the whole path (scrubber, exporter, pipeline, hook and event observers) and returns a handle whose\n * `stop` closes open spans, flushes within a bound and logs the counts. Nothing here is awaited on the host's request\n * path: handlers only append observations.\n */\n\nimport type {TracingSettings} from './settings.js'\n\nimport {createSpanExporter} from '@fro-bot/runtime/tracing/exporter'\nimport {createScrubber, type Scrubber} from './content.js'\nimport {createTracePipeline} from './pipeline.js'\nimport {registerObservers, type ObserverHost} from './record-observations.js'\nimport {createSnapshotLedger, type PendingLimits} from './snapshot.js'\n\n/**\n * How long cleanup may take, all of it: closing spans, the final batch, the transport.\n *\n * The server waits for plugin cleanup with no cap of its own, and the Action SIGKILLs the process 5 s after it closes\n * stdin, starting before this cleanup does (measured: the cleanup begins about 6 ms after stdin closes). Three seconds\n * leaves two for any other plugin's cleanup and the process exit, and is still longer than a healthy loopback relay or a\n * nearby collector needs for one batch. A batch still in flight at the bound is abandoned and counted as dropped.\n */\nexport const CLEANUP_BOUND_MS = 3_000\n\n/**\n * The most of the cleanup bound the pipeline may spend mapping and scrubbing what is left, so the exporter keeps the\n * rest (about two thirds) to deliver the final batch. What the pipeline has not done by then is dropped and counted.\n */\nexport const DRAIN_BOUND_MS = 1_000\n\n/** The `service.name` of every span this plugin exports. The Action's own spans carry a different one. */\nconst PLUGIN_SERVICE_NAME = 'fro-bot-opencode-plugin'\n\nexport type OnSettings = Extract<TracingSettings, {mode: 'on'}>\n\nexport interface TracingHandle {\n /** Closes everything, flushes within `CLEANUP_BOUND_MS` and logs the counts. Never throws. */\n readonly stop: () => Promise<void>\n}\n\nexport interface StartTracingOptions {\n /** The plugin's own environment, read once for secret-named variables. Never exported, never logged. */\n readonly env: Readonly<Record<string, string | undefined>>\n readonly log: (line: string) => void\n readonly now?: () => number\n /** Bounds on snapshots pending export. Tests lower them; production uses the defaults. */\n readonly pending?: Partial<PendingLimits>\n /** The most of the cleanup bound the pipeline may spend on what is left. Tests lower it; production uses `DRAIN_BOUND_MS`. */\n readonly drainBoundMs?: number\n /** Replaces the scrubber (tests that force the safety net). Production builds its own from `env`. */\n readonly scrubber?: Scrubber\n}\n\nexport async function startTracing(\n host: ObserverHost,\n settings: OnSettings,\n options: StartTracingOptions,\n): Promise<TracingHandle> {\n const {log} = options\n const local = settings.host === 'local'\n const scrubber =\n options.scrubber ??\n createScrubber({\n env: options.env,\n // The collector credential is a literal secret too: it must not come back in a tool result or an error message.\n extraSecrets: local ? Object.values(settings.headers) : [],\n })\n const exporter = createSpanExporter({\n url: settings.endpoint,\n serviceName: PLUGIN_SERVICE_NAME,\n headers: local ? settings.headers : {},\n // Action mode only: a local collector did not ask for the header.\n reportCounts: !local,\n onStopped: () => {\n log('tracing stopped exporting after repeated failures')\n },\n })\n // Snapshots pending export are counted apart from the exporter's queue; the pipeline frees each as its span leaves.\n const ledger = createSnapshotLedger(options.pending)\n const pipeline = createTracePipeline({\n sink: exporter,\n scrubber,\n ledger,\n ...(settings.host === 'action'\n ? {\n identity: settings.identity,\n rootSpan: settings.rootSpan,\n sessionId: settings.sessionId,\n invocationId: settings.invocationId,\n }\n : {}),\n ...(options.now === undefined ? {} : {now: options.now}),\n })\n\n let stopObserving: () => void\n try {\n stopObserving = await registerObservers(\n host,\n observation => {\n pipeline.observe(observation)\n },\n options.now,\n {ledger},\n )\n } catch (error) {\n // Some hooks may already be registered: they only append to a pipeline that is stopped now.\n pipeline.stop()\n await exporter.close(0)\n throw error\n }\n\n let stopping: Promise<void> | undefined\n return {\n stop: async () => {\n stopping ??= (async () => {\n const started = Date.now()\n try {\n stopObserving()\n pipeline.stop(options.drainBoundMs ?? DRAIN_BOUND_MS)\n } catch {\n // Counted below as whatever the exporter holds.\n }\n let counts = exporter.counts()\n try {\n counts = await exporter.close(Math.max(0, CLEANUP_BOUND_MS - (Date.now() - started)))\n } catch {\n // The line below reports what is known.\n }\n const {observationsDropped} = pipeline.stats()\n const lost = observationsDropped > 0 ? `, ${observationsDropped} observations lost` : ''\n // Normally absent: a number here means a known literal got past the matchers and the safety net withheld the value.\n const withheld = scrubber.survivalCount?.() ?? 0\n const survived = withheld > 0 ? `, ${withheld} values withheld (literal survived)` : ''\n log(`tracing stopped, exported ${counts.exported} spans, dropped ${counts.dropped}${lost}${survived}`)\n })()\n await stopping\n },\n }\n}\n"],"ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77],"mappings":";;;;;;;AAiBA,IAAW,cAAc,OAAO,eAAe,WAAW,aAAa;;ACDvE,IAAWA,YAAU;;ACArB,IAAI,KAAK;;;;;;;;;;;;;;;;;AAiBT,SAAgB,wBAAwB,YAAY;CAChD,IAAI,mCAAmB,IAAI,IAA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