@smthrs/observability 0.35.0 → 1.0.0-rc.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (363) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/LICENSE +1 -1
  3. package/README.md +87 -0
  4. package/dist/cjs/BrowserOtel.d.ts +37 -0
  5. package/dist/cjs/BrowserOtel.d.ts.map +1 -0
  6. package/dist/cjs/BrowserOtel.js +47 -0
  7. package/dist/cjs/BrowserOtel.js.map +7 -0
  8. package/dist/cjs/Endpoint.d.ts +70 -0
  9. package/dist/cjs/Endpoint.d.ts.map +1 -0
  10. package/dist/cjs/Endpoint.js +85 -0
  11. package/dist/cjs/Endpoint.js.map +7 -0
  12. package/dist/cjs/JournalLogger.d.ts +232 -0
  13. package/dist/cjs/JournalLogger.d.ts.map +1 -0
  14. package/dist/cjs/JournalLogger.js +415 -0
  15. package/dist/cjs/JournalLogger.js.map +7 -0
  16. package/dist/cjs/Logger.d.ts +56 -0
  17. package/dist/cjs/Logger.d.ts.map +1 -0
  18. package/dist/cjs/Logger.js +72 -0
  19. package/dist/cjs/Logger.js.map +7 -0
  20. package/dist/cjs/Metric.d.ts +67 -0
  21. package/dist/cjs/Metric.d.ts.map +1 -0
  22. package/dist/cjs/Metric.js +68 -0
  23. package/dist/cjs/Metric.js.map +7 -0
  24. package/dist/cjs/NodeOtel.d.ts +42 -0
  25. package/dist/cjs/NodeOtel.d.ts.map +1 -0
  26. package/dist/cjs/NodeOtel.js +78 -0
  27. package/dist/cjs/NodeOtel.js.map +7 -0
  28. package/dist/cjs/Otel.d.ts +63 -0
  29. package/dist/cjs/Otel.d.ts.map +1 -0
  30. package/dist/cjs/Otel.js +75 -0
  31. package/dist/cjs/Otel.js.map +7 -0
  32. package/dist/cjs/Otlp.d.ts +203 -0
  33. package/dist/cjs/Otlp.d.ts.map +1 -0
  34. package/dist/cjs/Otlp.js +251 -0
  35. package/dist/cjs/Otlp.js.map +7 -0
  36. package/dist/cjs/Resource.d.ts +163 -0
  37. package/dist/cjs/Resource.d.ts.map +1 -0
  38. package/dist/cjs/Resource.js +186 -0
  39. package/dist/cjs/Resource.js.map +7 -0
  40. package/dist/cjs/index.d.ts +61 -0
  41. package/dist/cjs/index.d.ts.map +1 -0
  42. package/dist/cjs/index.js +47 -0
  43. package/dist/cjs/index.js.map +7 -0
  44. package/dist/cjs/internal/schemaIssuePath.d.ts +31 -0
  45. package/dist/cjs/internal/schemaIssuePath.d.ts.map +1 -0
  46. package/dist/cjs/internal/schemaIssuePath.js +49 -0
  47. package/dist/cjs/internal/schemaIssuePath.js.map +7 -0
  48. package/dist/cjs/package.json +1 -0
  49. package/dist/esm/BrowserOtel.d.ts +37 -0
  50. package/dist/esm/BrowserOtel.d.ts.map +1 -0
  51. package/dist/esm/BrowserOtel.js +24 -0
  52. package/dist/esm/BrowserOtel.js.map +1 -0
  53. package/dist/esm/Endpoint.d.ts +70 -0
  54. package/dist/esm/Endpoint.d.ts.map +1 -0
  55. package/dist/esm/Endpoint.js +110 -0
  56. package/dist/esm/Endpoint.js.map +1 -0
  57. package/dist/esm/JournalLogger.d.ts +232 -0
  58. package/dist/esm/JournalLogger.d.ts.map +1 -0
  59. package/dist/esm/JournalLogger.js +520 -0
  60. package/dist/esm/JournalLogger.js.map +1 -0
  61. package/dist/esm/Logger.d.ts +56 -0
  62. package/dist/esm/Logger.d.ts.map +1 -0
  63. package/dist/esm/Logger.js +61 -0
  64. package/dist/esm/Logger.js.map +1 -0
  65. package/dist/esm/Metric.d.ts +67 -0
  66. package/dist/esm/Metric.d.ts.map +1 -0
  67. package/dist/esm/Metric.js +80 -0
  68. package/dist/esm/Metric.js.map +1 -0
  69. package/dist/esm/NodeOtel.d.ts +42 -0
  70. package/dist/esm/NodeOtel.d.ts.map +1 -0
  71. package/dist/esm/NodeOtel.js +56 -0
  72. package/dist/esm/NodeOtel.js.map +1 -0
  73. package/dist/esm/Otel.d.ts +63 -0
  74. package/dist/esm/Otel.d.ts.map +1 -0
  75. package/dist/esm/Otel.js +52 -0
  76. package/dist/esm/Otel.js.map +1 -0
  77. package/dist/esm/Otlp.d.ts +203 -0
  78. package/dist/esm/Otlp.d.ts.map +1 -0
  79. package/dist/esm/Otlp.js +384 -0
  80. package/dist/esm/Otlp.js.map +1 -0
  81. package/dist/esm/Resource.d.ts +163 -0
  82. package/dist/esm/Resource.d.ts.map +1 -0
  83. package/dist/esm/Resource.js +238 -0
  84. package/dist/esm/Resource.js.map +1 -0
  85. package/dist/esm/index.d.ts +61 -0
  86. package/dist/esm/index.d.ts.map +1 -0
  87. package/dist/esm/index.js +61 -0
  88. package/dist/esm/index.js.map +1 -0
  89. package/dist/esm/internal/schemaIssuePath.d.ts +31 -0
  90. package/dist/esm/internal/schemaIssuePath.d.ts.map +1 -0
  91. package/dist/esm/internal/schemaIssuePath.js +59 -0
  92. package/dist/esm/internal/schemaIssuePath.js.map +1 -0
  93. package/docs/README.md +164 -0
  94. package/docs/api.md +780 -0
  95. package/docs/concepts/instrumentation-and-export.md +98 -0
  96. package/docs/concepts/layer-map.md +73 -0
  97. package/docs/concepts/validated-acquisition.md +106 -0
  98. package/docs/guides/export-to-a-collector.md +190 -0
  99. package/docs/guides/forward-logs-to-the-journal.md +226 -0
  100. package/docs/guides/install-a-logger.md +111 -0
  101. package/docs/guides/read-runtime-metrics.md +83 -0
  102. package/docs/guides/testing.md +134 -0
  103. package/docs/guides/wire-an-opentelemetry-sdk.md +226 -0
  104. package/docs/installation.md +102 -0
  105. package/docs/quickstart.md +145 -0
  106. package/docs/troubleshooting.md +168 -0
  107. package/package.json +221 -32
  108. package/src/BrowserOtel.ts +51 -0
  109. package/src/Endpoint.ts +131 -0
  110. package/src/JournalLogger.ts +635 -0
  111. package/src/Logger.ts +107 -0
  112. package/src/Metric.ts +88 -0
  113. package/src/NodeOtel.ts +90 -0
  114. package/src/Otel.ts +118 -0
  115. package/src/Otlp.ts +514 -0
  116. package/src/Resource.ts +325 -0
  117. package/src/index.ts +67 -0
  118. package/src/internal/schemaIssuePath.ts +65 -0
  119. package/docker-compose.otel.yml +0 -104
  120. package/grafana/dashboards/smithers-dashboard.json +0 -453
  121. package/grafana/provisioning/dashboards/dashboards.yml +0 -12
  122. package/grafana/provisioning/datasources/datasources.yml +0 -49
  123. package/loki/loki-config.yaml +0 -35
  124. package/otel-collector-config.yml +0 -38
  125. package/prometheus/prometheus.yml +0 -8
  126. package/src/MetricName.ts +0 -1
  127. package/src/MetricsServiceLive.js +0 -9
  128. package/src/README.md +0 -28
  129. package/src/ResolvedSmithersObservabilityOptions.ts +0 -12
  130. package/src/SmithersEvent.ts +0 -843
  131. package/src/SmithersLogFormat.ts +0 -1
  132. package/src/SmithersMetricDefinition.ts +0 -15
  133. package/src/SmithersMetricType.ts +0 -1
  134. package/src/SmithersMetricUnit.ts +0 -1
  135. package/src/SmithersObservability.js +0 -15
  136. package/src/SmithersObservabilityOptions.ts +0 -12
  137. package/src/SmithersObservabilityService.ts +0 -13
  138. package/src/_coreCorrelation/CorrelationContext.ts +0 -10
  139. package/src/_coreCorrelation/CorrelationContextLive.js +0 -11
  140. package/src/_coreCorrelation/CorrelationContextService.js +0 -15
  141. package/src/_coreCorrelation/CorrelationContextServiceShape.ts +0 -12
  142. package/src/_coreCorrelation/CorrelationPatch.ts +0 -3
  143. package/src/_coreCorrelation/README.md +0 -20
  144. package/src/_coreCorrelation/_correlationStorage.js +0 -4
  145. package/src/_coreCorrelation/correlationContextFiberRef.js +0 -5
  146. package/src/_coreCorrelation/correlationContextToLogAnnotations.js +0 -18
  147. package/src/_coreCorrelation/getCurrentCorrelationContext.js +0 -9
  148. package/src/_coreCorrelation/getCurrentCorrelationContextEffect.js +0 -11
  149. package/src/_coreCorrelation/index.js +0 -14
  150. package/src/_coreCorrelation/mergeCorrelationContext.js +0 -51
  151. package/src/_coreCorrelation/runWithCorrelationContext.js +0 -14
  152. package/src/_coreCorrelation/updateCurrentCorrelationContext.js +0 -17
  153. package/src/_coreCorrelation/withCorrelationContext.js +0 -38
  154. package/src/_coreCorrelation/withCurrentCorrelationContext.js +0 -11
  155. package/src/_coreMetrics.js +0 -14
  156. package/src/_coreMetricsShape.ts +0 -44
  157. package/src/_corePrometheus.js +0 -91
  158. package/src/_corePrometheusShape.ts +0 -11
  159. package/src/_coreTracing.js +0 -132
  160. package/src/_coreTracingShape.ts +0 -17
  161. package/src/_otelLogBuilders.js +0 -102
  162. package/src/_sessionFileResolvers.js +0 -164
  163. package/src/_smithersSpanAttributeAliases.js +0 -19
  164. package/src/_smithersTraceSpanStorage.js +0 -3
  165. package/src/_traceEventNormalizers.js +0 -499
  166. package/src/_traceRedaction.js +0 -162
  167. package/src/agentSessionEventToOtelLogRecord.js +0 -55
  168. package/src/agentTrace.ts +0 -144
  169. package/src/agentTraceCapabilities.js +0 -151
  170. package/src/annotateSmithersTrace.js +0 -11
  171. package/src/canonicalTraceEventToOtelLogRecord.js +0 -55
  172. package/src/correlation.js +0 -56
  173. package/src/createSmithersObservabilityLayer.js +0 -59
  174. package/src/createSmithersOtelLayer.js +0 -23
  175. package/src/createSmithersRuntimeLayer.js +0 -2
  176. package/src/detectAgentFamily.js +0 -26
  177. package/src/detectCaptureMode.js +0 -29
  178. package/src/emitOtelLogRecord.js +0 -19
  179. package/src/getCurrentSmithersTraceAnnotations.js +0 -14
  180. package/src/getCurrentSmithersTraceSpan.js +0 -7
  181. package/src/index.d.ts +0 -1392
  182. package/src/index.js +0 -137
  183. package/src/kindPhase.js +0 -17
  184. package/src/logging.js +0 -264
  185. package/src/makeSmithersSpanAttributes.js +0 -20
  186. package/src/metrics/README.md +0 -22
  187. package/src/metrics/SmithersMetricDefinition.ts +0 -17
  188. package/src/metrics/SmithersMetricType.ts +0 -1
  189. package/src/metrics/SmithersMetricUnit.ts +0 -1
  190. package/src/metrics/_asyncExternalWaitCounts.js +0 -4
  191. package/src/metrics/_buckets.js +0 -37
  192. package/src/metrics/_incrementGauge.js +0 -11
  193. package/src/metrics/_processStartMs.js +0 -1
  194. package/src/metrics/activeNodes.js +0 -2
  195. package/src/metrics/activeRuns.js +0 -2
  196. package/src/metrics/agentActionsTotal.js +0 -2
  197. package/src/metrics/agentDurationMs.js +0 -3
  198. package/src/metrics/agentErrorsTotal.js +0 -2
  199. package/src/metrics/agentEventsTotal.js +0 -2
  200. package/src/metrics/agentInvocationsTotal.js +0 -2
  201. package/src/metrics/agentRetriesTotal.js +0 -2
  202. package/src/metrics/agentSessionsTotal.js +0 -2
  203. package/src/metrics/agentTokensTotal.js +0 -2
  204. package/src/metrics/alertDeliveriesAttempted.js +0 -2
  205. package/src/metrics/alertDeliveriesSuppressed.js +0 -2
  206. package/src/metrics/alertsAcknowledgedTotal.js +0 -2
  207. package/src/metrics/alertsActive.js +0 -2
  208. package/src/metrics/alertsEscalatedTotal.js +0 -2
  209. package/src/metrics/alertsFiredTotal.js +0 -2
  210. package/src/metrics/alertsReopenedTotal.js +0 -2
  211. package/src/metrics/alertsResolvedTotal.js +0 -2
  212. package/src/metrics/alertsSilencedTotal.js +0 -2
  213. package/src/metrics/approvalPending.js +0 -2
  214. package/src/metrics/approvalWaitDuration.js +0 -5
  215. package/src/metrics/approvalsDenied.js +0 -2
  216. package/src/metrics/approvalsGranted.js +0 -2
  217. package/src/metrics/approvalsRequested.js +0 -2
  218. package/src/metrics/attemptDuration.js +0 -3
  219. package/src/metrics/attentionBacklog.js +0 -2
  220. package/src/metrics/cacheHits.js +0 -2
  221. package/src/metrics/cacheMisses.js +0 -2
  222. package/src/metrics/dbQueryDuration.js +0 -3
  223. package/src/metrics/dbRetries.js +0 -2
  224. package/src/metrics/dbTransactionDuration.js +0 -3
  225. package/src/metrics/dbTransactionRetries.js +0 -2
  226. package/src/metrics/dbTransactionRollbacks.js +0 -2
  227. package/src/metrics/devtoolsActiveSubscribers.js +0 -2
  228. package/src/metrics/devtoolsBackpressureDisconnectTotal.js +0 -2
  229. package/src/metrics/devtoolsDeltaBuildMs.js +0 -3
  230. package/src/metrics/devtoolsEventBytes.js +0 -3
  231. package/src/metrics/devtoolsEventTotal.js +0 -2
  232. package/src/metrics/devtoolsSnapshotBuildMs.js +0 -5
  233. package/src/metrics/devtoolsSubscribeTotal.js +0 -2
  234. package/src/metrics/errorsTotal.js +0 -2
  235. package/src/metrics/eventsEmittedTotal.js +0 -2
  236. package/src/metrics/externalWaitAsyncPending.js +0 -2
  237. package/src/metrics/gatewayApprovalDecisionsTotal.js +0 -2
  238. package/src/metrics/gatewayAuthEventsTotal.js +0 -2
  239. package/src/metrics/gatewayConnectionsActive.js +0 -2
  240. package/src/metrics/gatewayConnectionsClosedTotal.js +0 -2
  241. package/src/metrics/gatewayConnectionsTotal.js +0 -2
  242. package/src/metrics/gatewayCronTriggersTotal.js +0 -2
  243. package/src/metrics/gatewayErrorsTotal.js +0 -2
  244. package/src/metrics/gatewayHeartbeatTicksTotal.js +0 -2
  245. package/src/metrics/gatewayMessagesReceivedTotal.js +0 -2
  246. package/src/metrics/gatewayMessagesSentTotal.js +0 -2
  247. package/src/metrics/gatewayRpcCallsTotal.js +0 -2
  248. package/src/metrics/gatewayRpcDuration.js +0 -3
  249. package/src/metrics/gatewayRunEventBackpressureDisconnectTotal.js +0 -4
  250. package/src/metrics/gatewayRunsCompletedTotal.js +0 -2
  251. package/src/metrics/gatewayRunsStartedTotal.js +0 -2
  252. package/src/metrics/gatewaySignalsTotal.js +0 -2
  253. package/src/metrics/gatewayWebhooksReceivedTotal.js +0 -2
  254. package/src/metrics/gatewayWebhooksRejectedTotal.js +0 -2
  255. package/src/metrics/gatewayWebhooksVerifiedTotal.js +0 -2
  256. package/src/metrics/heartbeatDataSizeBytes.js +0 -5
  257. package/src/metrics/heartbeatIntervalMs.js +0 -3
  258. package/src/metrics/hotReloadDuration.js +0 -3
  259. package/src/metrics/hotReloadFailures.js +0 -2
  260. package/src/metrics/hotReloads.js +0 -2
  261. package/src/metrics/httpRequestDuration.js +0 -3
  262. package/src/metrics/httpRequests.js +0 -2
  263. package/src/metrics/index.d.ts +0 -1222
  264. package/src/metrics/index.js +0 -168
  265. package/src/metrics/memoryFactReads.js +0 -3
  266. package/src/metrics/memoryFactWrites.js +0 -3
  267. package/src/metrics/memoryMessageSaves.js +0 -3
  268. package/src/metrics/memoryRecallDuration.js +0 -11
  269. package/src/metrics/memoryRecallQueries.js +0 -3
  270. package/src/metrics/metricsServiceAdapter.js +0 -181
  271. package/src/metrics/nodeDuration.js +0 -3
  272. package/src/metrics/nodeRetriesTotal.js +0 -2
  273. package/src/metrics/nodesFailed.js +0 -2
  274. package/src/metrics/nodesFinished.js +0 -2
  275. package/src/metrics/nodesStarted.js +0 -2
  276. package/src/metrics/openApiToolCallErrorsTotal.js +0 -3
  277. package/src/metrics/openApiToolCallsTotal.js +0 -3
  278. package/src/metrics/openApiToolDuration.js +0 -9
  279. package/src/metrics/processHeapUsedBytes.js +0 -2
  280. package/src/metrics/processMemoryRssBytes.js +0 -2
  281. package/src/metrics/processUptimeSeconds.js +0 -2
  282. package/src/metrics/promptSizeBytes.js +0 -3
  283. package/src/metrics/replaysStarted.js +0 -3
  284. package/src/metrics/responseSizeBytes.js +0 -3
  285. package/src/metrics/rewindDurationMs.js +0 -3
  286. package/src/metrics/rewindFramesDeleted.js +0 -3
  287. package/src/metrics/rewindRollbackTotal.js +0 -2
  288. package/src/metrics/rewindSandboxesReverted.js +0 -3
  289. package/src/metrics/rewindTotal.js +0 -2
  290. package/src/metrics/runDuration.js +0 -3
  291. package/src/metrics/runForksCreated.js +0 -3
  292. package/src/metrics/runsAncestryDepth.js +0 -3
  293. package/src/metrics/runsCancelledTotal.js +0 -2
  294. package/src/metrics/runsCarriedStateBytes.js +0 -5
  295. package/src/metrics/runsContinuedTotal.js +0 -2
  296. package/src/metrics/runsFailedTotal.js +0 -2
  297. package/src/metrics/runsFinishedTotal.js +0 -2
  298. package/src/metrics/runsResumedTotal.js +0 -2
  299. package/src/metrics/runsTotal.js +0 -2
  300. package/src/metrics/sandboxActive.js +0 -2
  301. package/src/metrics/sandboxBundleSizeBytes.js +0 -5
  302. package/src/metrics/sandboxCompletedTotal.js +0 -2
  303. package/src/metrics/sandboxCreatedTotal.js +0 -2
  304. package/src/metrics/sandboxDurationMs.js +0 -3
  305. package/src/metrics/sandboxPatchCount.js +0 -3
  306. package/src/metrics/sandboxTransportDurationMs.js +0 -5
  307. package/src/metrics/schedulerConcurrencyUtilization.js +0 -2
  308. package/src/metrics/schedulerQueueDepth.js +0 -2
  309. package/src/metrics/schedulerWaitDuration.js +0 -5
  310. package/src/metrics/scorerDuration.js +0 -9
  311. package/src/metrics/scorerEventsFailed.js +0 -2
  312. package/src/metrics/scorerEventsFinished.js +0 -2
  313. package/src/metrics/scorerEventsStarted.js +0 -2
  314. package/src/metrics/scorersFailed.js +0 -3
  315. package/src/metrics/scorersFinished.js +0 -3
  316. package/src/metrics/scorersStarted.js +0 -3
  317. package/src/metrics/smithersMetricCatalog.js +0 -893
  318. package/src/metrics/smithersMetricCatalogByKey.js +0 -2
  319. package/src/metrics/smithersMetricCatalogByName.js +0 -2
  320. package/src/metrics/smithersMetricCatalogByPrometheusName.js +0 -4
  321. package/src/metrics/snapshotDuration.js +0 -9
  322. package/src/metrics/snapshotsCaptured.js +0 -3
  323. package/src/metrics/supervisorPollDuration.js +0 -5
  324. package/src/metrics/supervisorPollsTotal.js +0 -2
  325. package/src/metrics/supervisorResumeLag.js +0 -5
  326. package/src/metrics/supervisorResumedTotal.js +0 -2
  327. package/src/metrics/supervisorSkippedTotal.js +0 -2
  328. package/src/metrics/supervisorStaleDetected.js +0 -2
  329. package/src/metrics/taskHeartbeatTimeoutTotal.js +0 -2
  330. package/src/metrics/taskHeartbeatsTotal.js +0 -2
  331. package/src/metrics/timerDelayDuration.js +0 -3
  332. package/src/metrics/timersCancelled.js +0 -2
  333. package/src/metrics/timersCreated.js +0 -2
  334. package/src/metrics/timersFired.js +0 -2
  335. package/src/metrics/timersPending.js +0 -2
  336. package/src/metrics/toPrometheusMetricName.js +0 -8
  337. package/src/metrics/tokensCacheReadTotal.js +0 -2
  338. package/src/metrics/tokensCacheWriteTotal.js +0 -2
  339. package/src/metrics/tokensContextWindowBucketTotal.js +0 -2
  340. package/src/metrics/tokensContextWindowPerCall.js +0 -5
  341. package/src/metrics/tokensInputPerCall.js +0 -3
  342. package/src/metrics/tokensInputTotal.js +0 -2
  343. package/src/metrics/tokensOutputPerCall.js +0 -3
  344. package/src/metrics/tokensOutputTotal.js +0 -2
  345. package/src/metrics/tokensReasoningTotal.js +0 -2
  346. package/src/metrics/toolCallErrorsTotal.js +0 -2
  347. package/src/metrics/toolCallsTotal.js +0 -2
  348. package/src/metrics/toolDuration.js +0 -3
  349. package/src/metrics/toolOutputTruncatedTotal.js +0 -2
  350. package/src/metrics/trackEvent.js +0 -608
  351. package/src/metrics/updateAsyncExternalWaitPending.js +0 -18
  352. package/src/metrics/updateProcessMetrics.js +0 -20
  353. package/src/metrics/vcsDuration.js +0 -3
  354. package/src/normalizeStructuredEvent.js +0 -15
  355. package/src/prometheusContentType.js +0 -1
  356. package/src/renderPrometheusMetrics.js +0 -212
  357. package/src/resolveAgentTraceCapabilities.js +0 -59
  358. package/src/resolveSmithersObservabilityOptions.js +0 -109
  359. package/src/smithersMetrics.js +0 -2
  360. package/src/smithersSpanNames.js +0 -6
  361. package/src/unsupportedKindsForCapabilities.js +0 -32
  362. package/src/withSmithersSpan.js +0 -17
  363. package/tempo/tempo.yml +0 -17
@@ -1 +0,0 @@
1
- export type SmithersLogFormat = "json" | "pretty" | "string" | "logfmt";
@@ -1,15 +0,0 @@
1
- import type { MetricLabels } from "./_corePrometheusShape.ts";
2
- import type { SmithersMetricType } from "./SmithersMetricType.ts";
3
- import type { SmithersMetricUnit } from "./SmithersMetricUnit.ts";
4
-
5
- export type SmithersMetricDefinition = {
6
- readonly key: string;
7
- readonly name: string;
8
- readonly prometheusName: string;
9
- readonly type: SmithersMetricType;
10
- readonly label: string;
11
- readonly unit?: SmithersMetricUnit;
12
- readonly labels?: readonly string[];
13
- readonly defaultLabels?: readonly MetricLabels[];
14
- readonly boundaries?: readonly number[];
15
- };
@@ -1 +0,0 @@
1
- export type SmithersMetricType = "counter" | "gauge" | "histogram";
@@ -1 +0,0 @@
1
- export type SmithersMetricUnit = "count" | "milliseconds" | "seconds" | "bytes" | "tokens" | "ratio" | "depth";
@@ -1,15 +0,0 @@
1
- import { Context } from "effect";
2
- /** @typedef {import("./SmithersObservabilityService.ts").SmithersObservabilityService} SmithersObservabilityService */
3
-
4
- /** @typedef {Context.ServiceClass.Shape<"SmithersObservability", SmithersObservabilityService>} SmithersObservability */
5
- const SmithersObservabilityTag =
6
- /** @type {Context.ServiceClass<SmithersObservability, "SmithersObservability", SmithersObservabilityService>} */ (
7
- Context.Service()("SmithersObservability")
8
- );
9
- export const SmithersObservability = /** @type {Context.ServiceClass<SmithersObservability, "SmithersObservability", SmithersObservabilityService>} */ (
10
- class SmithersObservability extends SmithersObservabilityTag {
11
- constructor(...args) {
12
- super(...args);
13
- }
14
- }
15
- );
@@ -1,12 +0,0 @@
1
- import type { LogLevel } from "effect";
2
- import type { SmithersLogFormat } from "./SmithersLogFormat";
3
-
4
- export type SmithersObservabilityOptions = {
5
- readonly enabled?: boolean;
6
- readonly endpoint?: string;
7
- readonly headers?: Record<string, string>;
8
- readonly serviceName?: string;
9
- readonly logFormat?: SmithersLogFormat;
10
- readonly logLevel?: LogLevel.LogLevel | string;
11
- readonly installLogger?: boolean;
12
- };
@@ -1,13 +0,0 @@
1
- import type { Effect } from "effect";
2
- import type * as Tracer from "effect/Tracer";
3
- import type { ResolvedSmithersObservabilityOptions } from "./ResolvedSmithersObservabilityOptions";
4
-
5
- export type SmithersObservabilityService = {
6
- readonly options: ResolvedSmithersObservabilityOptions;
7
- readonly annotate: (attributes: Readonly<Record<string, unknown>>) => Effect.Effect<void>;
8
- readonly withSpan: <A, E, R>(
9
- name: string,
10
- effect: Effect.Effect<A, E, R>,
11
- attributes?: Readonly<Record<string, unknown>>,
12
- ) => Effect.Effect<A, E, Exclude<R, Tracer.ParentSpan>>;
13
- };
@@ -1,10 +0,0 @@
1
- export type CorrelationContext = {
2
- runId: string;
3
- nodeId?: string;
4
- iteration?: number;
5
- attempt?: number;
6
- workflowName?: string;
7
- parentRunId?: string;
8
- traceId?: string;
9
- spanId?: string;
10
- };
@@ -1,11 +0,0 @@
1
- import { Layer } from "effect";
2
- import { CorrelationContextService } from "./CorrelationContextService.js";
3
- import { correlationContextToLogAnnotations } from "./correlationContextToLogAnnotations.js";
4
- import { getCurrentCorrelationContextEffect } from "./getCurrentCorrelationContextEffect.js";
5
- import { withCorrelationContext } from "./withCorrelationContext.js";
6
- /** @type {Layer.Layer<CorrelationContextService, never, never>} */
7
- export const CorrelationContextLive = Layer.succeed(CorrelationContextService, {
8
- current: () => getCurrentCorrelationContextEffect(),
9
- withCorrelation: (patch, effect) => withCorrelationContext(effect, patch),
10
- toLogAnnotations: correlationContextToLogAnnotations,
11
- });
@@ -1,15 +0,0 @@
1
- import { Context } from "effect";
2
- /** @typedef {import("./CorrelationContextServiceShape.ts").CorrelationContextServiceShape} CorrelationContextServiceShape */
3
-
4
- /** @typedef {Context.ServiceClass.Shape<"CorrelationContextService", CorrelationContextServiceShape>} CorrelationContextService */
5
- const CorrelationContextServiceTag =
6
- /** @type {Context.ServiceClass<CorrelationContextService, "CorrelationContextService", CorrelationContextServiceShape>} */ (
7
- Context.Service()("CorrelationContextService")
8
- );
9
- export const CorrelationContextService = /** @type {Context.ServiceClass<CorrelationContextService, "CorrelationContextService", CorrelationContextServiceShape>} */ (
10
- class CorrelationContextService extends CorrelationContextServiceTag {
11
- constructor(...args) {
12
- super(...args);
13
- }
14
- }
15
- );
@@ -1,12 +0,0 @@
1
- import type { Effect } from "effect";
2
- import type { CorrelationContext } from "./CorrelationContext.ts";
3
- import type { CorrelationPatch } from "./CorrelationPatch.ts";
4
-
5
- export type CorrelationContextServiceShape = {
6
- readonly current: () => Effect.Effect<CorrelationContext | undefined>;
7
- readonly withCorrelation: <A, E, R>(
8
- patch: CorrelationPatch,
9
- effect: Effect.Effect<A, E, R>,
10
- ) => Effect.Effect<A, E, R>;
11
- readonly toLogAnnotations: (context?: CorrelationContext | null) => Record<string, unknown> | undefined;
12
- };
@@ -1,3 +0,0 @@
1
- import type { CorrelationContext } from "./CorrelationContext.ts";
2
-
3
- export type CorrelationPatch = Partial<CorrelationContext> | undefined | null;
@@ -1,20 +0,0 @@
1
- # _coreCorrelation/
2
-
3
- The correlation-context core: a per-run/node/attempt context (`{ runId,
4
- nodeId, iteration, attempt, workflowName, parentRunId, traceId, spanId }`)
5
- tracked on TWO stores at once — an AsyncLocalStorage
6
- (`_correlationStorage.js`) for synchronous, non-Effect readers (the imperative
7
- logger) and a FiberRef (`correlationContextFiberRef.js`) for Effect code.
8
-
9
- How the pieces fit: `mergeCorrelationContext.js` normalizes patches and
10
- requires a `runId` for a context to exist; `withCorrelationContext.js` bridges
11
- a patch onto BOTH stores; `getCurrentCorrelationContextEffect.js` prefers the
12
- FiberRef and falls back to the ALS; `CorrelationContextLive.js` packages the
13
- whole thing as an Effect service; `index.js` is the barrel that
14
- `../correlation.js` re-exports from.
15
-
16
- Gotcha: run effects wrapped by `withCorrelationContext` with `runPromise` or
17
- `runFork`, never `runSync` — its acquire step calls
18
- `AsyncLocalStorage.enterWith()`, which under `runSync` leaks the context into
19
- the caller's synchronous async-context (documented in
20
- `withCorrelationContext.js`).
@@ -1,4 +0,0 @@
1
- import { AsyncLocalStorage } from "node:async_hooks";
2
- /** @typedef {import("./CorrelationContext.ts").CorrelationContext} CorrelationContext */
3
- /** @type {AsyncLocalStorage<CorrelationContext>} */
4
- export const correlationStorage = new AsyncLocalStorage();
@@ -1,5 +0,0 @@
1
- import { Context } from "effect";
2
-
3
- export const correlationContextFiberRef = Context.Reference("smithers/observability/correlation-context", {
4
- defaultValue: () => undefined,
5
- });
@@ -1,18 +0,0 @@
1
- /** @typedef {import("./CorrelationContext.ts").CorrelationContext} CorrelationContext */
2
- /**
3
- * @param {CorrelationContext | null} [context]
4
- * @returns {Record<string, unknown> | undefined}
5
- */
6
- export function correlationContextToLogAnnotations(context) {
7
- if (!context) return undefined;
8
- const annotations = {};
9
- if (context.runId) annotations.runId = context.runId;
10
- if (context.nodeId) annotations.nodeId = context.nodeId;
11
- if (context.workflowName) annotations.workflowName = context.workflowName;
12
- if (context.parentRunId) annotations.parentRunId = context.parentRunId;
13
- if (context.traceId) annotations.traceId = context.traceId;
14
- if (context.spanId) annotations.spanId = context.spanId;
15
- if (typeof context.iteration === "number") annotations.iteration = context.iteration;
16
- if (typeof context.attempt === "number") annotations.attempt = context.attempt;
17
- return Object.keys(annotations).length > 0 ? annotations : undefined;
18
- }
@@ -1,9 +0,0 @@
1
- import { correlationStorage } from "./_correlationStorage.js";
2
- /** @typedef {import("./CorrelationContext.ts").CorrelationContext} CorrelationContext */
3
-
4
- /**
5
- * @returns {CorrelationContext | undefined}
6
- */
7
- export function getCurrentCorrelationContext() {
8
- return correlationStorage.getStore();
9
- }
@@ -1,11 +0,0 @@
1
- import { Effect } from "effect";
2
- import { correlationContextFiberRef } from "./correlationContextFiberRef.js";
3
- import { correlationStorage } from "./_correlationStorage.js";
4
- /** @typedef {import("./CorrelationContext.ts").CorrelationContext} CorrelationContext */
5
-
6
- /**
7
- * @returns {Effect.Effect< CorrelationContext | undefined >}
8
- */
9
- export function getCurrentCorrelationContextEffect() {
10
- return correlationContextFiberRef.pipe(Effect.map((fiberContext) => fiberContext ?? correlationStorage.getStore()));
11
- }
@@ -1,14 +0,0 @@
1
- /** @typedef {import("./CorrelationContext.ts").CorrelationContext} CorrelationContext */
2
- /** @typedef {import("./CorrelationPatch.ts").CorrelationPatch} CorrelationPatch */
3
-
4
- export { correlationContextFiberRef } from "./correlationContextFiberRef.js";
5
- export { CorrelationContextService } from "./CorrelationContextService.js";
6
- export { CorrelationContextLive } from "./CorrelationContextLive.js";
7
- export { mergeCorrelationContext } from "./mergeCorrelationContext.js";
8
- export { getCurrentCorrelationContext } from "./getCurrentCorrelationContext.js";
9
- export { getCurrentCorrelationContextEffect } from "./getCurrentCorrelationContextEffect.js";
10
- export { updateCurrentCorrelationContext } from "./updateCurrentCorrelationContext.js";
11
- export { runWithCorrelationContext } from "./runWithCorrelationContext.js";
12
- export { withCorrelationContext } from "./withCorrelationContext.js";
13
- export { withCurrentCorrelationContext } from "./withCurrentCorrelationContext.js";
14
- export { correlationContextToLogAnnotations } from "./correlationContextToLogAnnotations.js";
@@ -1,51 +0,0 @@
1
- /** @typedef {import("./CorrelationContext.ts").CorrelationContext} CorrelationContext */
2
- /** @typedef {import("./CorrelationPatch.ts").CorrelationPatch} CorrelationPatch */
3
- /**
4
- * @param {unknown} value
5
- * @returns {string | undefined}
6
- */
7
- function cleanString(value) {
8
- return typeof value === "string" && value.length > 0 ? value : undefined;
9
- }
10
- /**
11
- * @param {unknown} value
12
- * @returns {number | undefined}
13
- */
14
- function cleanNumber(value) {
15
- return typeof value === "number" && Number.isFinite(value) ? value : undefined;
16
- }
17
- /**
18
- * @param {CorrelationPatch} patch
19
- * @returns {Partial<CorrelationContext> | undefined}
20
- */
21
- function normalizePatch(patch) {
22
- if (!patch) return undefined;
23
- const normalized = {};
24
- const runId = cleanString(patch.runId);
25
- const nodeId = cleanString(patch.nodeId);
26
- const workflowName = cleanString(patch.workflowName);
27
- const parentRunId = cleanString(patch.parentRunId);
28
- const traceId = cleanString(patch.traceId);
29
- const spanId = cleanString(patch.spanId);
30
- const iteration = cleanNumber(patch.iteration);
31
- const attempt = cleanNumber(patch.attempt);
32
- if (runId) normalized.runId = runId;
33
- if (nodeId) normalized.nodeId = nodeId;
34
- if (workflowName) normalized.workflowName = workflowName;
35
- if (parentRunId) normalized.parentRunId = parentRunId;
36
- if (traceId) normalized.traceId = traceId;
37
- if (spanId) normalized.spanId = spanId;
38
- if (iteration !== undefined) normalized.iteration = iteration;
39
- if (attempt !== undefined) normalized.attempt = attempt;
40
- return Object.keys(normalized).length > 0 ? normalized : undefined;
41
- }
42
- /**
43
- * @param {CorrelationContext | null} [base]
44
- * @param {CorrelationPatch} [patch]
45
- * @returns {CorrelationContext | undefined}
46
- */
47
- export function mergeCorrelationContext(base, patch) {
48
- const normalizedPatch = normalizePatch(patch);
49
- const merged = { ...base, ...normalizedPatch };
50
- return merged.runId ? merged : undefined;
51
- }
@@ -1,14 +0,0 @@
1
- import { correlationStorage } from "./_correlationStorage.js";
2
- import { mergeCorrelationContext } from "./mergeCorrelationContext.js";
3
- /** @typedef {import("./CorrelationPatch.ts").CorrelationPatch} CorrelationPatch */
4
-
5
- /**
6
- * @template T
7
- * @param {CorrelationPatch} patch
8
- * @param {() => T} fn
9
- * @returns {T}
10
- */
11
- export function runWithCorrelationContext(patch, fn) {
12
- const next = mergeCorrelationContext(correlationStorage.getStore(), patch);
13
- return next ? correlationStorage.run(next, fn) : fn();
14
- }
@@ -1,17 +0,0 @@
1
- import { Effect } from "effect";
2
- import { getCurrentCorrelationContextEffect } from "./getCurrentCorrelationContextEffect.js";
3
- import { mergeCorrelationContext } from "./mergeCorrelationContext.js";
4
- /** @typedef {import("./CorrelationContext.ts").CorrelationContext} CorrelationContext */
5
- /** @typedef {import("./CorrelationPatch.ts").CorrelationPatch} CorrelationPatch */
6
-
7
- /**
8
- * @param {CorrelationPatch} patch
9
- * @returns {Effect.Effect<CorrelationContext | undefined>}
10
- */
11
- export function updateCurrentCorrelationContext(patch) {
12
- return Effect.gen(function* () {
13
- const current = yield* getCurrentCorrelationContextEffect();
14
- const next = mergeCorrelationContext(current, patch);
15
- return next;
16
- });
17
- }
@@ -1,38 +0,0 @@
1
- import { Effect } from "effect";
2
- import { correlationContextFiberRef } from "./correlationContextFiberRef.js";
3
- import { correlationStorage } from "./_correlationStorage.js";
4
- import { mergeCorrelationContext } from "./mergeCorrelationContext.js";
5
- /** @typedef {import("./CorrelationPatch.ts").CorrelationPatch} CorrelationPatch */
6
-
7
- /**
8
- * Bridge the Effect-tracked correlation context onto the imperative
9
- * AsyncLocalStorage store so plain (non-Effect) `getCurrentCorrelationContext()`
10
- * reads — e.g. from the imperative logger — see the active run/node correlation
11
- * while the effect executes.
12
- *
13
- * IMPORTANT: run the resulting effect with `Effect.runPromise`/`runFork`, never
14
- * `Effect.runSync`. The acquire step calls `AsyncLocalStorage.enterWith()`, which
15
- * mutates the *caller's* async context. Under `runSync` the caller is whatever
16
- * synchronous context invoked it (e.g. a test-runner's root context); enabling
17
- * ALS async-hooks there leaks into every subsequent timer/promise on that
18
- * context. `runPromise`/`runFork` execute on an ephemeral fiber context, keeping
19
- * the enterWith scoped to that fiber.
20
- *
21
- * @template A, E, R
22
- * @param {Effect.Effect<A, E, R>} effect
23
- * @param {CorrelationPatch} patch
24
- */
25
- export function withCorrelationContext(effect, patch) {
26
- const next = mergeCorrelationContext(correlationStorage.getStore(), patch);
27
- if (!next) return effect;
28
- const located = effect.pipe(Effect.provideService(correlationContextFiberRef, next));
29
- return Effect.acquireUseRelease(
30
- Effect.sync(() => {
31
- const previous = correlationStorage.getStore();
32
- correlationStorage.enterWith(next);
33
- return previous;
34
- }),
35
- () => located,
36
- (previous) => Effect.sync(() => correlationStorage.enterWith(previous)),
37
- );
38
- }
@@ -1,11 +0,0 @@
1
- import { Effect } from "effect";
2
- import { correlationContextFiberRef } from "./correlationContextFiberRef.js";
3
- import { correlationStorage } from "./_correlationStorage.js";
4
- /**
5
- * @template A, E, R
6
- * @param {Effect.Effect<A, E, R>} effect
7
- */
8
- export function withCurrentCorrelationContext(effect) {
9
- const current = correlationStorage.getStore();
10
- return current ? effect.pipe(Effect.provideService(correlationContextFiberRef, current)) : effect;
11
- }
@@ -1,14 +0,0 @@
1
- import { Context } from "effect";
2
- /** @typedef {import("./_coreMetricsShape.ts").MetricsServiceShape} MetricsServiceShape */
3
-
4
- /** @typedef {Context.ServiceClass.Shape<"MetricsService", MetricsServiceShape>} MetricsService */
5
- const MetricsServiceTag = /** @type {Context.ServiceClass<MetricsService, "MetricsService", MetricsServiceShape>} */ (
6
- Context.Service()("MetricsService")
7
- );
8
- export const MetricsService = /** @type {Context.ServiceClass<MetricsService, "MetricsService", MetricsServiceShape>} */ (
9
- class MetricsService extends MetricsServiceTag {
10
- constructor(...args) {
11
- super(...args);
12
- }
13
- }
14
- );
@@ -1,44 +0,0 @@
1
- import type { Effect } from "effect";
2
- import type { MetricLabels } from "./_corePrometheusShape.ts";
3
- import type { MetricName } from "./MetricName.ts";
4
-
5
- export type SmithersMetricEvent = {
6
- readonly type: string;
7
- readonly [key: string]: unknown;
8
- };
9
-
10
- export type CounterEntry = {
11
- readonly type: "counter";
12
- value: number;
13
- readonly labels: MetricLabels;
14
- };
15
-
16
- export type GaugeEntry = {
17
- readonly type: "gauge";
18
- value: number;
19
- readonly labels: MetricLabels;
20
- };
21
-
22
- export type HistogramEntry = {
23
- readonly type: "histogram";
24
- sum: number;
25
- count: number;
26
- readonly labels: MetricLabels;
27
- readonly buckets: Map<number, number>;
28
- };
29
-
30
- export type MetricEntry = CounterEntry | GaugeEntry | HistogramEntry;
31
-
32
- export type MetricsSnapshot = ReadonlyMap<string, MetricEntry>;
33
-
34
- export type MetricsServiceShape = {
35
- readonly increment: (name: MetricName, labels?: MetricLabels) => Effect.Effect<void>;
36
- readonly incrementBy: (name: MetricName, value: number, labels?: MetricLabels) => Effect.Effect<void>;
37
- readonly gauge: (name: MetricName, value: number, labels?: MetricLabels) => Effect.Effect<void>;
38
- readonly histogram: (name: MetricName, value: number, labels?: MetricLabels) => Effect.Effect<void>;
39
- readonly recordEvent: (event: SmithersMetricEvent) => Effect.Effect<void>;
40
- readonly updateProcessMetrics: () => Effect.Effect<void>;
41
- readonly updateAsyncExternalWaitPending: (kind: "approval" | "event", delta: number) => Effect.Effect<void>;
42
- readonly renderPrometheus: () => Effect.Effect<string>;
43
- readonly snapshot: () => Effect.Effect<MetricsSnapshot>;
44
- };
@@ -1,91 +0,0 @@
1
- /** @typedef {import("./_corePrometheusShape.ts").MetricLabels} MetricLabels */
2
- /** @typedef {import("./_corePrometheusShape.ts").PrometheusSample} PrometheusSample */
3
- /**
4
- * @param {string} name
5
- * @returns {string}
6
- */
7
- export function toPrometheusMetricName(name) {
8
- const next = name.replace(/[^a-zA-Z0-9_:]/g, "_");
9
- return /^[a-zA-Z_:]/.test(next) ? next : `_${next}`;
10
- }
11
- /**
12
- * @param {string} text
13
- * @returns {string}
14
- */
15
- function escapeText(text) {
16
- return text.replace(/\\/g, "\\\\").replace(/\n/g, "\\n");
17
- }
18
- /**
19
- * @param {string} value
20
- * @returns {string}
21
- */
22
- function escapeLabelValue(value) {
23
- return escapeText(value).replace(/"/g, '\\"');
24
- }
25
- /**
26
- * @param {number} value
27
- * @returns {string}
28
- */
29
- function formatNumber(value) {
30
- if (Number.isNaN(value)) return "NaN";
31
- if (value === Number.POSITIVE_INFINITY) return "+Inf";
32
- if (value === Number.NEGATIVE_INFINITY) return "-Inf";
33
- return String(value);
34
- }
35
- /**
36
- * @param {MetricLabels} labels
37
- * @returns {string}
38
- */
39
- function formatLabels(labels) {
40
- const entries = Object.entries(labels).sort(([left], [right]) => left.localeCompare(right));
41
- if (entries.length === 0) return "";
42
- return `{${entries
43
- .map(([key, value]) => `${toPrometheusMetricName(key)}="${escapeLabelValue(String(value))}"`)
44
- .join(",")}}`;
45
- }
46
- /**
47
- * @param {MetricLabels} labels
48
- * @param {MetricLabels} extra
49
- * @returns {MetricLabels}
50
- */
51
- function mergeLabels(labels, extra) {
52
- return { ...labels, ...extra };
53
- }
54
- /**
55
- * @param {readonly PrometheusSample[]} samples
56
- * @returns {string}
57
- */
58
- export function renderPrometheusSamples(samples) {
59
- const grouped = new Map();
60
- for (const sample of samples) {
61
- const name = toPrometheusMetricName(sample.name);
62
- const group =
63
- grouped.get(name) ??
64
- (() => {
65
- const created = { type: sample.type, lines: [] };
66
- grouped.set(name, created);
67
- return created;
68
- })();
69
- if (sample.type === "histogram") {
70
- const buckets = [...(sample.buckets ?? new Map()).entries()].sort(([left], [right]) => left - right);
71
- for (const [boundary, count] of buckets) {
72
- group.lines.push(
73
- `${name}_bucket${formatLabels(mergeLabels(sample.labels, { le: boundary }))} ${formatNumber(count)}`,
74
- );
75
- }
76
- group.lines.push(
77
- `${name}_bucket${formatLabels(mergeLabels(sample.labels, { le: "+Inf" }))} ${formatNumber(sample.count ?? 0)}`,
78
- );
79
- group.lines.push(`${name}_sum${formatLabels(sample.labels)} ${formatNumber(sample.sum ?? 0)}`);
80
- group.lines.push(`${name}_count${formatLabels(sample.labels)} ${formatNumber(sample.count ?? 0)}`);
81
- } else {
82
- group.lines.push(`${name}${formatLabels(sample.labels)} ${formatNumber(sample.value ?? 0)}`);
83
- }
84
- }
85
- const lines = [];
86
- for (const [name, group] of [...grouped.entries()].sort(([left], [right]) => left.localeCompare(right))) {
87
- lines.push(`# TYPE ${name} ${group.type}`);
88
- lines.push(...group.lines.sort());
89
- }
90
- return lines.join("\n") + (lines.length > 0 ? "\n" : "");
91
- }
@@ -1,11 +0,0 @@
1
- export type MetricLabels = Readonly<Record<string, string | number | boolean>>;
2
-
3
- export type PrometheusSample = {
4
- readonly name: string;
5
- readonly type: "counter" | "gauge" | "histogram";
6
- readonly labels: MetricLabels;
7
- readonly value?: number;
8
- readonly buckets?: ReadonlyMap<number, number>;
9
- readonly sum?: number;
10
- readonly count?: number;
11
- };
@@ -1,132 +0,0 @@
1
- import { Context, Effect, Layer } from "effect";
2
- import {
3
- correlationContextToLogAnnotations,
4
- getCurrentCorrelationContext,
5
- withCorrelationContext,
6
- } from "./_coreCorrelation/index.js";
7
- import { smithersSpanAttributeAliases } from "./_smithersSpanAttributeAliases.js";
8
- /** @typedef {import("./SmithersLogFormat.ts").SmithersLogFormat} SmithersLogFormat */
9
- /** @typedef {import("./_coreTracingShape.ts").SmithersSpanAttributesInput} SmithersSpanAttributesInput */
10
- /** @typedef {import("./_coreTracingShape.ts").TracingServiceShape} TracingServiceShape */
11
-
12
- /** @type {"text/plain; version=0.0.4; charset=utf-8"} */
13
- export const prometheusContentType = "text/plain; version=0.0.4; charset=utf-8";
14
- /** @type {{ readonly run: "smithers.run"; readonly task: "smithers.task"; readonly agent: "smithers.agent"; readonly tool: "smithers.tool" }} */
15
- export const smithersSpanNames = {
16
- run: "smithers.run",
17
- task: "smithers.task",
18
- agent: "smithers.agent",
19
- tool: "smithers.tool",
20
- };
21
- /** @typedef {Context.ServiceClass.Shape<"TracingService", TracingServiceShape>} TracingService */
22
- const TracingServiceTag = /** @type {Context.ServiceClass<TracingService, "TracingService", TracingServiceShape>} */ (
23
- Context.Service()("TracingService")
24
- );
25
- export const TracingService = /** @type {Context.ServiceClass<TracingService, "TracingService", TracingServiceShape>} */ (
26
- class TracingService extends TracingServiceTag {
27
- constructor(...args) {
28
- super(...args);
29
- }
30
- }
31
- );
32
- /**
33
- * @param {SmithersSpanAttributesInput} [attributes]
34
- * @returns {Record<string, unknown>}
35
- */
36
- export function makeSmithersSpanAttributes(attributes = {}) {
37
- const aliases = smithersSpanAttributeAliases;
38
- const result = {};
39
- for (const [key, value] of Object.entries(attributes)) {
40
- if (value !== undefined) {
41
- result[key.startsWith("smithers.") ? key : (aliases[key] ?? key)] = value;
42
- }
43
- }
44
- return result;
45
- }
46
- /**
47
- * @param {SmithersSpanAttributesInput} [attributes]
48
- * @returns {attributes is SmithersSpanAttributesInput}
49
- */
50
- function hasAttributes(attributes) {
51
- return Boolean(attributes && Object.keys(attributes).length > 0);
52
- }
53
- /**
54
- * @param {string} name
55
- * @param {SmithersSpanAttributesInput} [attributes]
56
- * @returns {string}
57
- */
58
- function inferSmithersSpanName(name, attributes) {
59
- if (name.startsWith("smithers.")) return name;
60
- if (name.startsWith("tool:") || "toolName" in (attributes ?? {}) || "tool_name" in (attributes ?? {})) {
61
- return smithersSpanNames.tool;
62
- }
63
- if (name.startsWith("agent:") || name.startsWith("agent.") || "agent" in (attributes ?? {})) {
64
- return smithersSpanNames.agent;
65
- }
66
- if ("nodeId" in (attributes ?? {}) || "node_id" in (attributes ?? {})) {
67
- return smithersSpanNames.task;
68
- }
69
- if ("runId" in (attributes ?? {}) || "run_id" in (attributes ?? {})) {
70
- return smithersSpanNames.run;
71
- }
72
- return name;
73
- }
74
- /**
75
- * @param {SmithersSpanAttributesInput} [attributes]
76
- * @returns {Effect.Effect<void>}
77
- */
78
- export function annotateSmithersTrace(attributes = {}) {
79
- const spanAttributes = makeSmithersSpanAttributes(attributes);
80
- let program = Effect.void;
81
- if (Object.keys(spanAttributes).length > 0) {
82
- program = program.pipe(
83
- Effect.tap(() => Effect.annotateCurrentSpan(spanAttributes).pipe(Effect.catch(() => Effect.void))),
84
- );
85
- }
86
- if (hasAttributes(attributes)) {
87
- program = program.pipe(Effect.annotateLogs(attributes));
88
- }
89
- return program;
90
- }
91
- /**
92
- * @template A, E, R
93
- * @param {string} name
94
- * @param {Effect.Effect<A, E, R>} effect
95
- * @param {SmithersSpanAttributesInput} [attributes]
96
- * @returns {Effect.Effect<A, E, R>}
97
- */
98
- export function withSmithersSpan(name, effect, attributes) {
99
- const spanAttributes = makeSmithersSpanAttributes(attributes);
100
- return Effect.suspend(() => {
101
- const annotations = correlationContextToLogAnnotations(getCurrentCorrelationContext());
102
- let program = effect;
103
- if (Object.keys(spanAttributes).length > 0) {
104
- program = program.pipe(Effect.annotateSpans(spanAttributes));
105
- }
106
- if (hasAttributes(attributes)) {
107
- program = program.pipe(Effect.annotateLogs(attributes));
108
- }
109
- if (annotations) {
110
- program = program.pipe(Effect.annotateLogs(annotations));
111
- }
112
- return program.pipe(
113
- Effect.withLogSpan(name),
114
- Effect.withSpan(inferSmithersSpanName(name, attributes), {
115
- attributes: spanAttributes,
116
- }),
117
- );
118
- });
119
- }
120
- /** @type {Layer.Layer<TracingService, never, never>} */
121
- export const TracingServiceLive = Layer.succeed(TracingService, {
122
- withSpan: (name, effect, attributes) => {
123
- return withSmithersSpan(name, effect, attributes);
124
- },
125
- annotate: (attributes) => {
126
- const spanAttributes = makeSmithersSpanAttributes(attributes);
127
- return Object.keys(spanAttributes).length > 0
128
- ? Effect.annotateCurrentSpan(spanAttributes).pipe(Effect.catch(() => Effect.void))
129
- : Effect.void;
130
- },
131
- withCorrelation: (context, effect) => withCorrelationContext(effect, context),
132
- });