@smthrs/observability 0.33.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (247) hide show
  1. package/LICENSE +21 -0
  2. package/docker-compose.otel.yml +104 -0
  3. package/grafana/dashboards/smithers-dashboard.json +453 -0
  4. package/grafana/provisioning/dashboards/dashboards.yml +12 -0
  5. package/grafana/provisioning/datasources/datasources.yml +49 -0
  6. package/loki/loki-config.yaml +35 -0
  7. package/otel-collector-config.yml +38 -0
  8. package/package.json +47 -0
  9. package/prometheus/prometheus.yml +8 -0
  10. package/src/MetricName.ts +1 -0
  11. package/src/MetricsServiceLive.js +9 -0
  12. package/src/README.md +28 -0
  13. package/src/ResolvedSmithersObservabilityOptions.ts +12 -0
  14. package/src/SmithersEvent.ts +773 -0
  15. package/src/SmithersLogFormat.ts +1 -0
  16. package/src/SmithersMetricDefinition.ts +15 -0
  17. package/src/SmithersMetricType.ts +1 -0
  18. package/src/SmithersMetricUnit.ts +1 -0
  19. package/src/SmithersObservability.js +15 -0
  20. package/src/SmithersObservabilityOptions.ts +12 -0
  21. package/src/SmithersObservabilityService.ts +13 -0
  22. package/src/_coreCorrelation/CorrelationContext.ts +10 -0
  23. package/src/_coreCorrelation/CorrelationContextLive.js +11 -0
  24. package/src/_coreCorrelation/CorrelationContextService.js +15 -0
  25. package/src/_coreCorrelation/CorrelationContextServiceShape.ts +12 -0
  26. package/src/_coreCorrelation/CorrelationPatch.ts +3 -0
  27. package/src/_coreCorrelation/README.md +20 -0
  28. package/src/_coreCorrelation/_correlationStorage.js +4 -0
  29. package/src/_coreCorrelation/correlationContextFiberRef.js +5 -0
  30. package/src/_coreCorrelation/correlationContextToLogAnnotations.js +18 -0
  31. package/src/_coreCorrelation/getCurrentCorrelationContext.js +9 -0
  32. package/src/_coreCorrelation/getCurrentCorrelationContextEffect.js +11 -0
  33. package/src/_coreCorrelation/index.js +14 -0
  34. package/src/_coreCorrelation/mergeCorrelationContext.js +51 -0
  35. package/src/_coreCorrelation/runWithCorrelationContext.js +14 -0
  36. package/src/_coreCorrelation/updateCurrentCorrelationContext.js +17 -0
  37. package/src/_coreCorrelation/withCorrelationContext.js +38 -0
  38. package/src/_coreCorrelation/withCurrentCorrelationContext.js +11 -0
  39. package/src/_coreMetrics.js +14 -0
  40. package/src/_coreMetricsShape.ts +44 -0
  41. package/src/_corePrometheus.js +91 -0
  42. package/src/_corePrometheusShape.ts +11 -0
  43. package/src/_coreTracing.js +132 -0
  44. package/src/_coreTracingShape.ts +17 -0
  45. package/src/_otelLogBuilders.js +102 -0
  46. package/src/_sessionFileResolvers.js +164 -0
  47. package/src/_smithersSpanAttributeAliases.js +19 -0
  48. package/src/_smithersTraceSpanStorage.js +3 -0
  49. package/src/_traceEventNormalizers.js +499 -0
  50. package/src/_traceRedaction.js +162 -0
  51. package/src/agentSessionEventToOtelLogRecord.js +55 -0
  52. package/src/agentTrace.ts +144 -0
  53. package/src/agentTraceCapabilities.js +151 -0
  54. package/src/annotateSmithersTrace.js +11 -0
  55. package/src/canonicalTraceEventToOtelLogRecord.js +55 -0
  56. package/src/correlation.js +56 -0
  57. package/src/createSmithersObservabilityLayer.js +59 -0
  58. package/src/createSmithersOtelLayer.js +23 -0
  59. package/src/createSmithersRuntimeLayer.js +2 -0
  60. package/src/detectAgentFamily.js +26 -0
  61. package/src/detectCaptureMode.js +24 -0
  62. package/src/emitOtelLogRecord.js +19 -0
  63. package/src/getCurrentSmithersTraceAnnotations.js +14 -0
  64. package/src/getCurrentSmithersTraceSpan.js +7 -0
  65. package/src/index.d.ts +1321 -0
  66. package/src/index.js +136 -0
  67. package/src/kindPhase.js +17 -0
  68. package/src/logging.js +248 -0
  69. package/src/makeSmithersSpanAttributes.js +20 -0
  70. package/src/metrics/README.md +22 -0
  71. package/src/metrics/SmithersMetricDefinition.ts +17 -0
  72. package/src/metrics/SmithersMetricType.ts +1 -0
  73. package/src/metrics/SmithersMetricUnit.ts +1 -0
  74. package/src/metrics/_asyncExternalWaitCounts.js +4 -0
  75. package/src/metrics/_buckets.js +37 -0
  76. package/src/metrics/_incrementGauge.js +11 -0
  77. package/src/metrics/_processStartMs.js +1 -0
  78. package/src/metrics/activeNodes.js +2 -0
  79. package/src/metrics/activeRuns.js +2 -0
  80. package/src/metrics/agentActionsTotal.js +2 -0
  81. package/src/metrics/agentDurationMs.js +3 -0
  82. package/src/metrics/agentErrorsTotal.js +2 -0
  83. package/src/metrics/agentEventsTotal.js +2 -0
  84. package/src/metrics/agentInvocationsTotal.js +2 -0
  85. package/src/metrics/agentRetriesTotal.js +2 -0
  86. package/src/metrics/agentSessionsTotal.js +2 -0
  87. package/src/metrics/agentTokensTotal.js +2 -0
  88. package/src/metrics/alertDeliveriesAttempted.js +2 -0
  89. package/src/metrics/alertDeliveriesSuppressed.js +2 -0
  90. package/src/metrics/alertsAcknowledgedTotal.js +2 -0
  91. package/src/metrics/alertsActive.js +2 -0
  92. package/src/metrics/alertsEscalatedTotal.js +2 -0
  93. package/src/metrics/alertsFiredTotal.js +2 -0
  94. package/src/metrics/alertsReopenedTotal.js +2 -0
  95. package/src/metrics/alertsResolvedTotal.js +2 -0
  96. package/src/metrics/alertsSilencedTotal.js +2 -0
  97. package/src/metrics/approvalPending.js +2 -0
  98. package/src/metrics/approvalWaitDuration.js +5 -0
  99. package/src/metrics/approvalsDenied.js +2 -0
  100. package/src/metrics/approvalsGranted.js +2 -0
  101. package/src/metrics/approvalsRequested.js +2 -0
  102. package/src/metrics/attemptDuration.js +3 -0
  103. package/src/metrics/attentionBacklog.js +2 -0
  104. package/src/metrics/cacheHits.js +2 -0
  105. package/src/metrics/cacheMisses.js +2 -0
  106. package/src/metrics/dbQueryDuration.js +3 -0
  107. package/src/metrics/dbRetries.js +2 -0
  108. package/src/metrics/dbTransactionDuration.js +3 -0
  109. package/src/metrics/dbTransactionRetries.js +2 -0
  110. package/src/metrics/dbTransactionRollbacks.js +2 -0
  111. package/src/metrics/devtoolsActiveSubscribers.js +2 -0
  112. package/src/metrics/devtoolsBackpressureDisconnectTotal.js +2 -0
  113. package/src/metrics/devtoolsDeltaBuildMs.js +3 -0
  114. package/src/metrics/devtoolsEventBytes.js +3 -0
  115. package/src/metrics/devtoolsEventTotal.js +2 -0
  116. package/src/metrics/devtoolsSnapshotBuildMs.js +5 -0
  117. package/src/metrics/devtoolsSubscribeTotal.js +2 -0
  118. package/src/metrics/errorsTotal.js +2 -0
  119. package/src/metrics/eventsEmittedTotal.js +2 -0
  120. package/src/metrics/externalWaitAsyncPending.js +2 -0
  121. package/src/metrics/gatewayApprovalDecisionsTotal.js +2 -0
  122. package/src/metrics/gatewayAuthEventsTotal.js +2 -0
  123. package/src/metrics/gatewayConnectionsActive.js +2 -0
  124. package/src/metrics/gatewayConnectionsClosedTotal.js +2 -0
  125. package/src/metrics/gatewayConnectionsTotal.js +2 -0
  126. package/src/metrics/gatewayCronTriggersTotal.js +2 -0
  127. package/src/metrics/gatewayErrorsTotal.js +2 -0
  128. package/src/metrics/gatewayHeartbeatTicksTotal.js +2 -0
  129. package/src/metrics/gatewayMessagesReceivedTotal.js +2 -0
  130. package/src/metrics/gatewayMessagesSentTotal.js +2 -0
  131. package/src/metrics/gatewayRpcCallsTotal.js +2 -0
  132. package/src/metrics/gatewayRpcDuration.js +3 -0
  133. package/src/metrics/gatewayRunEventBackpressureDisconnectTotal.js +4 -0
  134. package/src/metrics/gatewayRunsCompletedTotal.js +2 -0
  135. package/src/metrics/gatewayRunsStartedTotal.js +2 -0
  136. package/src/metrics/gatewaySignalsTotal.js +2 -0
  137. package/src/metrics/gatewayWebhooksReceivedTotal.js +2 -0
  138. package/src/metrics/gatewayWebhooksRejectedTotal.js +2 -0
  139. package/src/metrics/gatewayWebhooksVerifiedTotal.js +2 -0
  140. package/src/metrics/heartbeatDataSizeBytes.js +5 -0
  141. package/src/metrics/heartbeatIntervalMs.js +3 -0
  142. package/src/metrics/hotReloadDuration.js +3 -0
  143. package/src/metrics/hotReloadFailures.js +2 -0
  144. package/src/metrics/hotReloads.js +2 -0
  145. package/src/metrics/httpRequestDuration.js +3 -0
  146. package/src/metrics/httpRequests.js +2 -0
  147. package/src/metrics/index.d.ts +1163 -0
  148. package/src/metrics/index.js +168 -0
  149. package/src/metrics/memoryFactReads.js +3 -0
  150. package/src/metrics/memoryFactWrites.js +3 -0
  151. package/src/metrics/memoryMessageSaves.js +3 -0
  152. package/src/metrics/memoryRecallDuration.js +11 -0
  153. package/src/metrics/memoryRecallQueries.js +3 -0
  154. package/src/metrics/metricsServiceAdapter.js +181 -0
  155. package/src/metrics/nodeDuration.js +3 -0
  156. package/src/metrics/nodeRetriesTotal.js +2 -0
  157. package/src/metrics/nodesFailed.js +2 -0
  158. package/src/metrics/nodesFinished.js +2 -0
  159. package/src/metrics/nodesStarted.js +2 -0
  160. package/src/metrics/openApiToolCallErrorsTotal.js +3 -0
  161. package/src/metrics/openApiToolCallsTotal.js +3 -0
  162. package/src/metrics/openApiToolDuration.js +9 -0
  163. package/src/metrics/processHeapUsedBytes.js +2 -0
  164. package/src/metrics/processMemoryRssBytes.js +2 -0
  165. package/src/metrics/processUptimeSeconds.js +2 -0
  166. package/src/metrics/promptSizeBytes.js +3 -0
  167. package/src/metrics/replaysStarted.js +3 -0
  168. package/src/metrics/responseSizeBytes.js +3 -0
  169. package/src/metrics/rewindDurationMs.js +3 -0
  170. package/src/metrics/rewindFramesDeleted.js +3 -0
  171. package/src/metrics/rewindRollbackTotal.js +2 -0
  172. package/src/metrics/rewindSandboxesReverted.js +3 -0
  173. package/src/metrics/rewindTotal.js +2 -0
  174. package/src/metrics/runDuration.js +3 -0
  175. package/src/metrics/runForksCreated.js +3 -0
  176. package/src/metrics/runsAncestryDepth.js +3 -0
  177. package/src/metrics/runsCancelledTotal.js +2 -0
  178. package/src/metrics/runsCarriedStateBytes.js +5 -0
  179. package/src/metrics/runsContinuedTotal.js +2 -0
  180. package/src/metrics/runsFailedTotal.js +2 -0
  181. package/src/metrics/runsFinishedTotal.js +2 -0
  182. package/src/metrics/runsResumedTotal.js +2 -0
  183. package/src/metrics/runsTotal.js +2 -0
  184. package/src/metrics/sandboxActive.js +2 -0
  185. package/src/metrics/sandboxBundleSizeBytes.js +5 -0
  186. package/src/metrics/sandboxCompletedTotal.js +2 -0
  187. package/src/metrics/sandboxCreatedTotal.js +2 -0
  188. package/src/metrics/sandboxDurationMs.js +3 -0
  189. package/src/metrics/sandboxPatchCount.js +3 -0
  190. package/src/metrics/sandboxTransportDurationMs.js +5 -0
  191. package/src/metrics/schedulerConcurrencyUtilization.js +2 -0
  192. package/src/metrics/schedulerQueueDepth.js +2 -0
  193. package/src/metrics/schedulerWaitDuration.js +5 -0
  194. package/src/metrics/scorerDuration.js +9 -0
  195. package/src/metrics/scorerEventsFailed.js +2 -0
  196. package/src/metrics/scorerEventsFinished.js +2 -0
  197. package/src/metrics/scorerEventsStarted.js +2 -0
  198. package/src/metrics/scorersFailed.js +3 -0
  199. package/src/metrics/scorersFinished.js +3 -0
  200. package/src/metrics/scorersStarted.js +3 -0
  201. package/src/metrics/smithersMetricCatalog.js +893 -0
  202. package/src/metrics/smithersMetricCatalogByKey.js +2 -0
  203. package/src/metrics/smithersMetricCatalogByName.js +2 -0
  204. package/src/metrics/smithersMetricCatalogByPrometheusName.js +4 -0
  205. package/src/metrics/snapshotDuration.js +9 -0
  206. package/src/metrics/snapshotsCaptured.js +3 -0
  207. package/src/metrics/supervisorPollDuration.js +5 -0
  208. package/src/metrics/supervisorPollsTotal.js +2 -0
  209. package/src/metrics/supervisorResumeLag.js +5 -0
  210. package/src/metrics/supervisorResumedTotal.js +2 -0
  211. package/src/metrics/supervisorSkippedTotal.js +2 -0
  212. package/src/metrics/supervisorStaleDetected.js +2 -0
  213. package/src/metrics/taskHeartbeatTimeoutTotal.js +2 -0
  214. package/src/metrics/taskHeartbeatsTotal.js +2 -0
  215. package/src/metrics/timerDelayDuration.js +3 -0
  216. package/src/metrics/timersCancelled.js +2 -0
  217. package/src/metrics/timersCreated.js +2 -0
  218. package/src/metrics/timersFired.js +2 -0
  219. package/src/metrics/timersPending.js +2 -0
  220. package/src/metrics/toPrometheusMetricName.js +8 -0
  221. package/src/metrics/tokensCacheReadTotal.js +2 -0
  222. package/src/metrics/tokensCacheWriteTotal.js +2 -0
  223. package/src/metrics/tokensContextWindowBucketTotal.js +2 -0
  224. package/src/metrics/tokensContextWindowPerCall.js +5 -0
  225. package/src/metrics/tokensInputPerCall.js +3 -0
  226. package/src/metrics/tokensInputTotal.js +2 -0
  227. package/src/metrics/tokensOutputPerCall.js +3 -0
  228. package/src/metrics/tokensOutputTotal.js +2 -0
  229. package/src/metrics/tokensReasoningTotal.js +2 -0
  230. package/src/metrics/toolCallErrorsTotal.js +2 -0
  231. package/src/metrics/toolCallsTotal.js +2 -0
  232. package/src/metrics/toolDuration.js +3 -0
  233. package/src/metrics/toolOutputTruncatedTotal.js +2 -0
  234. package/src/metrics/trackEvent.js +608 -0
  235. package/src/metrics/updateAsyncExternalWaitPending.js +18 -0
  236. package/src/metrics/updateProcessMetrics.js +20 -0
  237. package/src/metrics/vcsDuration.js +3 -0
  238. package/src/normalizeStructuredEvent.js +15 -0
  239. package/src/prometheusContentType.js +1 -0
  240. package/src/renderPrometheusMetrics.js +212 -0
  241. package/src/resolveAgentTraceCapabilities.js +59 -0
  242. package/src/resolveSmithersObservabilityOptions.js +109 -0
  243. package/src/smithersMetrics.js +2 -0
  244. package/src/smithersSpanNames.js +6 -0
  245. package/src/unsupportedKindsForCapabilities.js +32 -0
  246. package/src/withSmithersSpan.js +17 -0
  247. package/tempo/tempo.yml +17 -0
@@ -0,0 +1,212 @@
1
+ import { Effect, Metric, Option } from "effect";
2
+ import { smithersMetricCatalog, toPrometheusMetricName, updateProcessMetrics } from "./metrics/index.js";
3
+ /** @typedef {import("./metrics/SmithersMetricDefinition.ts").SmithersMetricDefinition} SmithersMetricDefinition */
4
+ /** @typedef {{ boundary: number; count: number | bigint }} PrometheusBucket */
5
+ /** @typedef {"counter" | "gauge" | "histogram" | "summary"} PrometheusMetricType */
6
+ /** @typedef {{ type: PrometheusMetricType; help: string | undefined; lines: string[] }} PrometheusMetricRecord */
7
+
8
+ /**
9
+ * @param {string} text
10
+ * @returns {string}
11
+ */
12
+ function escapePrometheusText(text) {
13
+ return text.replace(/\\/g, "\\\\").replace(/\n/g, "\\n");
14
+ }
15
+ /**
16
+ * @param {string} value
17
+ * @returns {string}
18
+ */
19
+ function escapePrometheusLabelValue(value) {
20
+ return escapePrometheusText(value).replace(/"/g, '\\"');
21
+ }
22
+ /**
23
+ * @param {number | bigint} value
24
+ * @returns {string}
25
+ */
26
+ function formatPrometheusNumber(value) {
27
+ if (typeof value === "bigint") return value.toString();
28
+ if (Number.isNaN(value)) return "NaN";
29
+ if (value === Number.POSITIVE_INFINITY) return "+Inf";
30
+ if (value === Number.NEGATIVE_INFINITY) return "-Inf";
31
+ return String(value);
32
+ }
33
+ /**
34
+ * @param {ReadonlyArray<[string, string]>} labels
35
+ * @returns {string}
36
+ */
37
+ function formatPrometheusLabels(labels) {
38
+ if (labels.length === 0) return "";
39
+ return `{${labels
40
+ .map(([key, value]) => `${toPrometheusMetricName(key)}="${escapePrometheusLabelValue(value)}"`)
41
+ .join(",")}}`;
42
+ }
43
+ /**
44
+ * @param {ReadonlyArray<[string, string]>} base
45
+ * @param {ReadonlyArray<[string, string]>} extra
46
+ * @returns {string}
47
+ */
48
+ function mergePrometheusLabels(base, extra) {
49
+ const merged = [...base, ...extra].sort(([left], [right]) => left.localeCompare(right));
50
+ return formatPrometheusLabels(merged);
51
+ }
52
+ /**
53
+ * @param {Record<string, string> | undefined} attributes
54
+ * @returns {ReadonlyArray<[string, string]>}
55
+ */
56
+ function metricLabels(attributes) {
57
+ return Object.entries(attributes ?? {}).sort(([left], [right]) => left.localeCompare(right));
58
+ }
59
+ /**
60
+ * @param {string | undefined} description
61
+ * @returns {string | undefined}
62
+ */
63
+ function metricHelp(description) {
64
+ return description?.trim() ? description : undefined;
65
+ }
66
+ /**
67
+ * @param {any} metricState
68
+ * @returns {PrometheusBucket[]}
69
+ */
70
+ function histogramBuckets(metricState) {
71
+ const buckets = [];
72
+ if (!metricState?.buckets || typeof metricState.buckets[Symbol.iterator] !== "function") {
73
+ return buckets;
74
+ }
75
+ for (const [boundary, count] of metricState.buckets) {
76
+ // Effect appends a +Inf boundary to every histogram; the explicit +Inf line below emits it.
77
+ if (!Number.isFinite(boundary)) continue;
78
+ buckets.push({ boundary, count });
79
+ }
80
+ return buckets.sort((left, right) => left.boundary - right.boundary);
81
+ }
82
+ /**
83
+ * @param {SmithersMetricDefinition} definition
84
+ * @returns {string[]}
85
+ */
86
+ function defaultPrometheusMetricLines(definition) {
87
+ const labelSets =
88
+ definition.defaultLabels && definition.defaultLabels.length > 0
89
+ ? definition.defaultLabels.map((labels) => Object.entries(labels))
90
+ : [[]];
91
+ if (definition.type === "histogram") {
92
+ const boundaries = (definition.boundaries ?? []).filter(Number.isFinite);
93
+ return labelSets.flatMap((labelSet) => {
94
+ const baseLabels = labelSet;
95
+ return [
96
+ ...boundaries.map(
97
+ (boundary) =>
98
+ `${definition.prometheusName}_bucket${mergePrometheusLabels(baseLabels, [["le", String(boundary)]])} 0`,
99
+ ),
100
+ `${definition.prometheusName}_bucket${mergePrometheusLabels(baseLabels, [["le", "+Inf"]])} 0`,
101
+ `${definition.prometheusName}_sum${formatPrometheusLabels(baseLabels)} 0`,
102
+ `${definition.prometheusName}_count${formatPrometheusLabels(baseLabels)} 0`,
103
+ ];
104
+ });
105
+ }
106
+ return labelSets.map((labelSet) => `${definition.prometheusName}${formatPrometheusLabels(labelSet)} 0`);
107
+ }
108
+ /**
109
+ * @param {Map<string, PrometheusMetricRecord>} registry
110
+ * @param {string} name
111
+ * @param {PrometheusMetricType} type
112
+ * @param {string | undefined} help
113
+ */
114
+ function registerPrometheusMetric(registry, name, type, help) {
115
+ const existing = registry.get(name);
116
+ if (existing) {
117
+ if (!existing.help && help) {
118
+ existing.help = help;
119
+ }
120
+ return existing;
121
+ }
122
+ const created = { type, help, lines: [] };
123
+ registry.set(name, created);
124
+ return created;
125
+ }
126
+ /**
127
+ * @returns {string}
128
+ */
129
+ export function renderPrometheusMetrics() {
130
+ // Snapshot process-level gauges before rendering
131
+ try {
132
+ Effect.runSync(updateProcessMetrics());
133
+ } catch {
134
+ /* non-critical */
135
+ }
136
+ const registry = new Map();
137
+ for (const snapshot of Effect.runSync(Metric.snapshot)) {
138
+ const metricState = snapshot.state;
139
+ const name = toPrometheusMetricName(snapshot.id);
140
+ if (!name) continue;
141
+ const labels = metricLabels(snapshot.attributes);
142
+ const help = metricHelp(snapshot.description);
143
+ if (snapshot.type === "Counter") {
144
+ const metric = registerPrometheusMetric(registry, name, "counter", help);
145
+ metric.lines.push(`${name}${formatPrometheusLabels(labels)} ${formatPrometheusNumber(metricState.count)}`);
146
+ continue;
147
+ }
148
+ if (snapshot.type === "Gauge") {
149
+ const metric = registerPrometheusMetric(registry, name, "gauge", help);
150
+ metric.lines.push(`${name}${formatPrometheusLabels(labels)} ${formatPrometheusNumber(metricState.value)}`);
151
+ continue;
152
+ }
153
+ if (snapshot.type === "Histogram") {
154
+ const metric = registerPrometheusMetric(registry, name, "histogram", help);
155
+ for (const bucket of histogramBuckets(metricState)) {
156
+ metric.lines.push(
157
+ `${name}_bucket${mergePrometheusLabels(labels, [["le", String(bucket.boundary)]])} ${formatPrometheusNumber(bucket.count)}`,
158
+ );
159
+ }
160
+ metric.lines.push(
161
+ `${name}_bucket${mergePrometheusLabels(labels, [["le", "+Inf"]])} ${formatPrometheusNumber(metricState.count)}`,
162
+ );
163
+ metric.lines.push(`${name}_sum${formatPrometheusLabels(labels)} ${formatPrometheusNumber(metricState.sum)}`);
164
+ metric.lines.push(`${name}_count${formatPrometheusLabels(labels)} ${formatPrometheusNumber(metricState.count)}`);
165
+ continue;
166
+ }
167
+ if (snapshot.type === "Frequency") {
168
+ const metric = registerPrometheusMetric(registry, name, "counter", help);
169
+ for (const [key, count] of metricState.occurrences) {
170
+ metric.lines.push(`${name}${mergePrometheusLabels(labels, [["key", key]])} ${formatPrometheusNumber(count)}`);
171
+ }
172
+ continue;
173
+ }
174
+ if (snapshot.type === "Summary") {
175
+ const metric = registerPrometheusMetric(registry, name, "summary", help);
176
+ metric.lines.push(
177
+ `${name}${mergePrometheusLabels(labels, [["quantile", "min"]])} ${formatPrometheusNumber(metricState.min)}`,
178
+ );
179
+ for (const [quantile, value] of metricState.quantiles) {
180
+ metric.lines.push(
181
+ `${name}${mergePrometheusLabels(labels, [["quantile", String(quantile)]])} ${formatPrometheusNumber(Option.getOrElse(value, () => 0))}`,
182
+ );
183
+ }
184
+ metric.lines.push(
185
+ `${name}${mergePrometheusLabels(labels, [["quantile", "max"]])} ${formatPrometheusNumber(metricState.max)}`,
186
+ );
187
+ metric.lines.push(`${name}_sum${formatPrometheusLabels(labels)} ${formatPrometheusNumber(metricState.sum)}`);
188
+ metric.lines.push(`${name}_count${formatPrometheusLabels(labels)} ${formatPrometheusNumber(metricState.count)}`);
189
+ }
190
+ }
191
+ for (const definition of smithersMetricCatalog) {
192
+ // description is the long-form HELP text; label is the required short human name.
193
+ const metric = registerPrometheusMetric(
194
+ registry,
195
+ definition.prometheusName,
196
+ definition.type,
197
+ definition.description ?? definition.label,
198
+ );
199
+ if (metric.lines.length === 0) {
200
+ metric.lines.push(...defaultPrometheusMetricLines(definition));
201
+ }
202
+ }
203
+ const lines = [];
204
+ for (const [name, metric] of [...registry.entries()].sort(([left], [right]) => left.localeCompare(right))) {
205
+ if (metric.help) {
206
+ lines.push(`# HELP ${name} ${escapePrometheusText(metric.help)}`);
207
+ }
208
+ lines.push(`# TYPE ${name} ${metric.type}`);
209
+ lines.push(...metric.lines);
210
+ }
211
+ return lines.join("\n") + (lines.length > 0 ? "\n" : "");
212
+ }
@@ -0,0 +1,59 @@
1
+ import { agentTraceCapabilities } from "./agentTraceCapabilities.js";
2
+ /**
3
+ * @typedef {import('./agentTrace.ts').AgentFamily} AgentFamily
4
+ * @typedef {import('./agentTrace.ts').AgentCaptureMode} AgentCaptureMode
5
+ * @typedef {import('./agentTrace.ts').AgentTraceCapabilityProfile} AgentTraceCapabilityProfile
6
+ */
7
+
8
+ /**
9
+ * @param {AgentFamily} agentFamily
10
+ * @param {AgentCaptureMode} captureMode
11
+ * @returns {AgentTraceCapabilityProfile}
12
+ */
13
+ export function resolveAgentTraceCapabilities(agentFamily, captureMode) {
14
+ const base = {
15
+ ...agentTraceCapabilities[agentFamily],
16
+ // Smithers persists a canonical NDJSON trace artifact for every successful
17
+ // flush regardless of the upstream agent family.
18
+ persistedSessionArtifact: true,
19
+ };
20
+ if (captureMode === "sdk-events" || captureMode === "cli-text") {
21
+ return base;
22
+ }
23
+ if (agentFamily === "codex") {
24
+ return {
25
+ ...base,
26
+ assistantTextDeltas: captureMode === "cli-json-stream",
27
+ toolExecutionStart: captureMode === "cli-json-stream",
28
+ toolExecutionUpdate: captureMode === "cli-json-stream",
29
+ toolExecutionEnd: captureMode === "cli-json-stream",
30
+ };
31
+ }
32
+ if (agentFamily === "claude-code") {
33
+ return {
34
+ ...base,
35
+ toolExecutionStart: captureMode === "cli-json-stream",
36
+ toolExecutionUpdate: captureMode === "cli-json-stream",
37
+ toolExecutionEnd: captureMode === "cli-json-stream",
38
+ };
39
+ }
40
+ if (agentFamily === "gemini" || agentFamily === "antigravity") {
41
+ return {
42
+ ...base,
43
+ assistantTextDeltas: captureMode === "cli-json-stream",
44
+ toolExecutionStart: captureMode === "cli-json-stream",
45
+ toolExecutionUpdate: captureMode === "cli-json-stream",
46
+ toolExecutionEnd: captureMode === "cli-json-stream",
47
+ };
48
+ }
49
+ if (agentFamily === "kimi") {
50
+ return {
51
+ ...base,
52
+ assistantTextDeltas: captureMode === "cli-json-stream",
53
+ toolExecutionStart: captureMode === "cli-json-stream",
54
+ toolExecutionUpdate: captureMode === "cli-json-stream",
55
+ toolExecutionEnd: captureMode === "cli-json-stream",
56
+ };
57
+ }
58
+ return base;
59
+ }
@@ -0,0 +1,109 @@
1
+ import { LogLevel } from "effect";
2
+ /** @typedef {import("./SmithersLogFormat.ts").SmithersLogFormat} SmithersLogFormat */
3
+
4
+ /** @typedef {import("./ResolvedSmithersObservabilityOptions.ts").ResolvedSmithersObservabilityOptions} ResolvedSmithersObservabilityOptions */
5
+ /** @typedef {import("./SmithersObservabilityOptions.ts").SmithersObservabilityOptions} SmithersObservabilityOptions */
6
+
7
+ // 4318 is the OTLP/HTTP receiver port of the local collector started by
8
+ // `smithers observability` (docker-compose.otel.yml).
9
+ const DEFAULT_OTLP_HTTP_ENDPOINT = "http://localhost:4318";
10
+
11
+ /**
12
+ * @param {LogLevel.LogLevel | string | undefined} value
13
+ * @returns {LogLevel.LogLevel}
14
+ */
15
+ function resolveLogLevel(value) {
16
+ if (typeof value !== "string") {
17
+ return value ?? "Info";
18
+ }
19
+ switch (value.toLowerCase()) {
20
+ case "none":
21
+ return "None";
22
+ case "trace":
23
+ return "Trace";
24
+ case "debug":
25
+ return "Debug";
26
+ case "warning":
27
+ case "warn":
28
+ return "Warn";
29
+ case "error":
30
+ return "Error";
31
+ case "fatal":
32
+ return "Fatal";
33
+ case "all":
34
+ return "All";
35
+ case "info":
36
+ default:
37
+ return "Info";
38
+ }
39
+ }
40
+ /**
41
+ * @param {string | undefined} value
42
+ * @returns {SmithersLogFormat}
43
+ */
44
+ function resolveLogFormat(value) {
45
+ switch ((value ?? "").toLowerCase()) {
46
+ case "json":
47
+ return "json";
48
+ case "pretty":
49
+ return "pretty";
50
+ case "string":
51
+ return "string";
52
+ case "logfmt":
53
+ default:
54
+ return "logfmt";
55
+ }
56
+ }
57
+ /**
58
+ * @param {boolean | undefined} value
59
+ * @returns {boolean}
60
+ */
61
+ function resolveEnabled(value) {
62
+ if (typeof value === "boolean") return value;
63
+ const env = (process.env.SMITHERS_OTEL_ENABLED ?? "").toLowerCase();
64
+ return env === "1" || env === "true";
65
+ }
66
+ /**
67
+ * @param {string | undefined} value
68
+ * @returns {Record<string, string> | undefined}
69
+ */
70
+ export function parseOtlpHeaders(value) {
71
+ if (!value) {
72
+ return undefined;
73
+ }
74
+ /** @type {Record<string, string>} */
75
+ const headers = {};
76
+ for (const entry of value.split(",")) {
77
+ const separator = entry.indexOf("=");
78
+ if (separator === -1) {
79
+ continue;
80
+ }
81
+ const key = entry.slice(0, separator).trim();
82
+ if (!key) {
83
+ continue;
84
+ }
85
+ try {
86
+ headers[key] = decodeURIComponent(entry.slice(separator + 1).trim());
87
+ } catch {
88
+ continue;
89
+ }
90
+ }
91
+ return Object.keys(headers).length > 0 ? headers : undefined;
92
+ }
93
+ /**
94
+ * @param {SmithersObservabilityOptions} [options]
95
+ * @returns {ResolvedSmithersObservabilityOptions}
96
+ */
97
+ export function resolveSmithersObservabilityOptions(options = {}) {
98
+ return {
99
+ enabled: resolveEnabled(options.enabled),
100
+ endpoint: options.endpoint ?? process.env.OTEL_EXPORTER_OTLP_ENDPOINT ?? DEFAULT_OTLP_HTTP_ENDPOINT,
101
+ headers: options.headers ?? parseOtlpHeaders(process.env.OTEL_EXPORTER_OTLP_HEADERS),
102
+ serviceName: options.serviceName ?? process.env.OTEL_SERVICE_NAME ?? "smithers",
103
+ logFormat: options.logFormat
104
+ ? resolveLogFormat(options.logFormat)
105
+ : resolveLogFormat(process.env.SMITHERS_LOG_FORMAT),
106
+ logLevel: resolveLogLevel(options.logLevel ?? process.env.SMITHERS_LOG_LEVEL),
107
+ installLogger: options.installLogger !== false,
108
+ };
109
+ }
@@ -0,0 +1,2 @@
1
+ import { smithersMetricCatalog } from "./metrics/index.js";
2
+ export const smithersMetrics = Object.fromEntries(smithersMetricCatalog.map((metric) => [metric.key, metric.metric]));
@@ -0,0 +1,6 @@
1
+ export const smithersSpanNames = {
2
+ run: "smithers.run",
3
+ task: "smithers.task",
4
+ agent: "smithers.agent",
5
+ tool: "smithers.tool",
6
+ };
@@ -0,0 +1,32 @@
1
+ /**
2
+ * @typedef {import('./agentTrace.ts').AgentTraceCapabilityProfile} AgentTraceCapabilityProfile
3
+ * @typedef {import('./agentTrace.ts').CanonicalAgentTraceEventKind} CanonicalAgentTraceEventKind
4
+ */
5
+
6
+ /** @type {Array<[keyof AgentTraceCapabilityProfile, CanonicalAgentTraceEventKind[]]>} */
7
+ const capabilityKindMap = [
8
+ ["sessionMetadata", ["session.start", "session.end"]],
9
+ ["assistantTextDeltas", ["assistant.text.delta"]],
10
+ ["visibleThinkingDeltas", ["assistant.thinking.delta"]],
11
+ ["finalAssistantMessage", ["assistant.message.final"]],
12
+ ["toolExecutionStart", ["tool.execution.start"]],
13
+ ["toolExecutionUpdate", ["tool.execution.update"]],
14
+ ["toolExecutionEnd", ["tool.execution.end", "tool.result"]],
15
+ ["retryEvents", ["retry.start", "retry.end"]],
16
+ ["compactionEvents", ["compaction.start", "compaction.end"]],
17
+ ["rawStderrDiagnostics", ["stderr"]],
18
+ ["persistedSessionArtifact", ["artifact.created"]],
19
+ ];
20
+
21
+ /**
22
+ * @param {AgentTraceCapabilityProfile} profile
23
+ * @returns {CanonicalAgentTraceEventKind[]}
24
+ */
25
+ export function unsupportedKindsForCapabilities(profile) {
26
+ /** @type {CanonicalAgentTraceEventKind[]} */
27
+ const kinds = [];
28
+ for (const [field, mappedKinds] of capabilityKindMap) {
29
+ if (!profile[field]) kinds.push(...mappedKinds);
30
+ }
31
+ return kinds;
32
+ }
@@ -0,0 +1,17 @@
1
+ import { TracingService, withSmithersSpan as withCoreSmithersSpan } from "./_coreTracing.js";
2
+ import { Effect } from "effect";
3
+ /**
4
+ * @template A, E, R
5
+ * @param {string} name
6
+ * @param {Effect.Effect<A, E, R>} effect
7
+ * @param {Readonly<Record<string, unknown>>} [attributes]
8
+ * @param {Omit<import("effect/Tracer").SpanOptions, "attributes" | "kind"> & { readonly kind?: import("effect/Tracer").SpanKind; }} [_options]
9
+ * @returns {Effect.Effect<A, E, Exclude<R, import("effect/Tracer").ParentSpan>>}
10
+ */
11
+ export function withSmithersSpan(name, effect, attributes, _options) {
12
+ return Effect.flatMap(Effect.serviceOption(TracingService), (service) =>
13
+ service._tag === "Some"
14
+ ? service.value.withSpan(name, effect, attributes ? { ...attributes } : undefined)
15
+ : withCoreSmithersSpan(name, effect, attributes),
16
+ );
17
+ }
@@ -0,0 +1,17 @@
1
+ server:
2
+ http_listen_port: 3200
3
+
4
+ distributor:
5
+ receivers:
6
+ otlp:
7
+ protocols:
8
+ grpc:
9
+ endpoint: "0.0.0.0:4317"
10
+
11
+ storage:
12
+ trace:
13
+ backend: local
14
+ local:
15
+ path: /tmp/tempo/blocks
16
+ wal:
17
+ path: /tmp/tempo/wal