@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,608 @@
1
+ import { Effect, Metric } from "effect";
2
+ import { incrementGauge } from "./_incrementGauge.js";
3
+ import { memoryFactWrites } from "./memoryFactWrites.js";
4
+ import { memoryRecallQueries } from "./memoryRecallQueries.js";
5
+ import { memoryMessageSaves } from "./memoryMessageSaves.js";
6
+ import { openApiToolCallsTotal } from "./openApiToolCallsTotal.js";
7
+ import { openApiToolCallErrorsTotal } from "./openApiToolCallErrorsTotal.js";
8
+ import { openApiToolDuration } from "./openApiToolDuration.js";
9
+ import { runsTotal } from "./runsTotal.js";
10
+ import { nodesStarted } from "./nodesStarted.js";
11
+ import { nodesFinished } from "./nodesFinished.js";
12
+ import { nodesFailed } from "./nodesFailed.js";
13
+ import { toolCallsTotal } from "./toolCallsTotal.js";
14
+ import { toolCallErrorsTotal } from "./toolCallErrorsTotal.js";
15
+ import { errorsTotal } from "./errorsTotal.js";
16
+ import { nodeRetriesTotal } from "./nodeRetriesTotal.js";
17
+ import { eventsEmittedTotal } from "./eventsEmittedTotal.js";
18
+ import { activeRuns } from "./activeRuns.js";
19
+ import { activeNodes } from "./activeNodes.js";
20
+ import { runsFinishedTotal } from "./runsFinishedTotal.js";
21
+ import { runsFailedTotal } from "./runsFailedTotal.js";
22
+ import { runsCancelledTotal } from "./runsCancelledTotal.js";
23
+ import { runsContinuedTotal } from "./runsContinuedTotal.js";
24
+ import { runsAncestryDepth } from "./runsAncestryDepth.js";
25
+ import { runsCarriedStateBytes } from "./runsCarriedStateBytes.js";
26
+ import { approvalsRequested } from "./approvalsRequested.js";
27
+ import { approvalsGranted } from "./approvalsGranted.js";
28
+ import { approvalsDenied } from "./approvalsDenied.js";
29
+ import { approvalPending } from "./approvalPending.js";
30
+ import { timersCreated } from "./timersCreated.js";
31
+ import { timersFired } from "./timersFired.js";
32
+ import { timersCancelled } from "./timersCancelled.js";
33
+ import { timersPending } from "./timersPending.js";
34
+ import { timerDelayDuration } from "./timerDelayDuration.js";
35
+ import { tokensInputTotal } from "./tokensInputTotal.js";
36
+ import { tokensOutputTotal } from "./tokensOutputTotal.js";
37
+ import { tokensCacheReadTotal } from "./tokensCacheReadTotal.js";
38
+ import { tokensCacheWriteTotal } from "./tokensCacheWriteTotal.js";
39
+ import { tokensReasoningTotal } from "./tokensReasoningTotal.js";
40
+ import { tokensContextWindowBucketTotal } from "./tokensContextWindowBucketTotal.js";
41
+ import { tokensInputPerCall } from "./tokensInputPerCall.js";
42
+ import { tokensOutputPerCall } from "./tokensOutputPerCall.js";
43
+ import { tokensContextWindowPerCall } from "./tokensContextWindowPerCall.js";
44
+ import { scorerEventsStarted } from "./scorerEventsStarted.js";
45
+ import { scorerEventsFinished } from "./scorerEventsFinished.js";
46
+ import { scorerEventsFailed } from "./scorerEventsFailed.js";
47
+ import { supervisorPollsTotal } from "./supervisorPollsTotal.js";
48
+ import { supervisorStaleDetected } from "./supervisorStaleDetected.js";
49
+ import { supervisorResumedTotal } from "./supervisorResumedTotal.js";
50
+ import { supervisorSkippedTotal } from "./supervisorSkippedTotal.js";
51
+ import { supervisorPollDuration } from "./supervisorPollDuration.js";
52
+ import { supervisorResumeLag } from "./supervisorResumeLag.js";
53
+ import { sandboxCreatedTotal } from "./sandboxCreatedTotal.js";
54
+ import { sandboxCompletedTotal } from "./sandboxCompletedTotal.js";
55
+ import { sandboxActive } from "./sandboxActive.js";
56
+ import { sandboxBundleSizeBytes } from "./sandboxBundleSizeBytes.js";
57
+ import { sandboxDurationMs } from "./sandboxDurationMs.js";
58
+ import { sandboxPatchCount } from "./sandboxPatchCount.js";
59
+ import { taskHeartbeatsTotal } from "./taskHeartbeatsTotal.js";
60
+ import { taskHeartbeatTimeoutTotal } from "./taskHeartbeatTimeoutTotal.js";
61
+ import { heartbeatDataSizeBytes } from "./heartbeatDataSizeBytes.js";
62
+ import { heartbeatIntervalMs } from "./heartbeatIntervalMs.js";
63
+ import { agentEventsTotal } from "./agentEventsTotal.js";
64
+ import { agentSessionsTotal } from "./agentSessionsTotal.js";
65
+ import { agentActionsTotal } from "./agentActionsTotal.js";
66
+ import { agentErrorsTotal } from "./agentErrorsTotal.js";
67
+ import { agentRetriesTotal } from "./agentRetriesTotal.js";
68
+ import { agentTokensTotal } from "./agentTokensTotal.js";
69
+ /** @typedef {import("@smthrs/observability/SmithersEvent").SmithersEvent} SmithersEvent */
70
+ /** @typedef {Extract<SmithersEvent, { type: "AgentEvent" }>["event"]} AgentEventPayload */
71
+ /** @typedef {{ inputTokens?: number; outputTokens?: number; cacheReadTokens?: number; cacheWriteTokens?: number; reasoningTokens?: number; totalTokens?: number }} AgentUsageTotals */
72
+
73
+ /**
74
+ * @param {unknown} value
75
+ * @returns {string | undefined}
76
+ */
77
+ function normalizeMetricTag(value) {
78
+ if (typeof value !== "string") return undefined;
79
+ const trimmed = value.trim();
80
+ return trimmed.length > 0 ? trimmed : undefined;
81
+ }
82
+ /**
83
+ * @template A
84
+ * @param {A} metric
85
+ * @param {Record<string, string | undefined>} tags
86
+ * @returns {A}
87
+ */
88
+ function tagMetricWithTags(metric, tags) {
89
+ let tagged = metric;
90
+ for (const [key, value] of Object.entries(tags)) {
91
+ if (!value) continue;
92
+ tagged = Metric.withAttributes(tagged, { [key]: String(value) });
93
+ }
94
+ return tagged;
95
+ }
96
+ /**
97
+ * @param {unknown} value
98
+ * @returns {number | undefined}
99
+ */
100
+ function asFiniteMetricCount(value) {
101
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : undefined;
102
+ }
103
+ /**
104
+ * @param {Extract<SmithersEvent, { type: "TokenUsageReported" }>} event
105
+ * @returns {number | undefined}
106
+ */
107
+ function resolveContextWindowTokens(event) {
108
+ const contextWindowTokens =
109
+ (asFiniteMetricCount(event.inputTokens) ?? 0) +
110
+ (asFiniteMetricCount(event.cacheReadTokens) ?? 0) +
111
+ (asFiniteMetricCount(event.cacheWriteTokens) ?? 0);
112
+ return contextWindowTokens > 0 ? contextWindowTokens : undefined;
113
+ }
114
+ /**
115
+ * @param {number} tokens
116
+ * @returns {string}
117
+ */
118
+ function classifyContextWindowBucket(tokens) {
119
+ if (tokens < 50_000) return "lt_50k";
120
+ if (tokens < 100_000) return "gte_50k_lt_100k";
121
+ if (tokens < 200_000) return "gte_100k_lt_200k";
122
+ if (tokens < 500_000) return "gte_200k_lt_500k";
123
+ if (tokens < 1_000_000) return "gte_500k_lt_1m";
124
+ return "gte_1m";
125
+ }
126
+ /**
127
+ * @param {Record<string, unknown> | undefined} usage
128
+ * @returns {AgentUsageTotals}
129
+ */
130
+ function extractAgentUsageTotals(usage) {
131
+ if (!usage) return {};
132
+ const value = usage;
133
+ const inputTokens =
134
+ asFiniteMetricCount(value.inputTokens) ??
135
+ asFiniteMetricCount(value.input_tokens) ??
136
+ asFiniteMetricCount(value.prompt_tokens);
137
+ const outputTokens =
138
+ asFiniteMetricCount(value.outputTokens) ??
139
+ asFiniteMetricCount(value.output_tokens) ??
140
+ asFiniteMetricCount(value.completion_tokens);
141
+ const cacheReadTokens =
142
+ asFiniteMetricCount(value.cacheReadTokens) ??
143
+ asFiniteMetricCount(value.cache_read_input_tokens) ??
144
+ asFiniteMetricCount(value.cached_input_tokens) ??
145
+ asFiniteMetricCount(value.inputTokenDetails?.cacheReadTokens);
146
+ const cacheWriteTokens =
147
+ asFiniteMetricCount(value.cacheWriteTokens) ??
148
+ asFiniteMetricCount(value.cache_creation_input_tokens) ??
149
+ asFiniteMetricCount(value.inputTokenDetails?.cacheWriteTokens);
150
+ const reasoningTokens =
151
+ asFiniteMetricCount(value.reasoningTokens) ??
152
+ asFiniteMetricCount(value.reasoning_tokens) ??
153
+ asFiniteMetricCount(value.outputTokenDetails?.reasoningTokens);
154
+ const totalTokens =
155
+ asFiniteMetricCount(value.totalTokens) ??
156
+ asFiniteMetricCount(
157
+ (inputTokens ?? 0) +
158
+ (outputTokens ?? 0) +
159
+ (cacheReadTokens ?? 0) +
160
+ (cacheWriteTokens ?? 0) +
161
+ (reasoningTokens ?? 0),
162
+ );
163
+ return {
164
+ inputTokens,
165
+ outputTokens,
166
+ cacheReadTokens,
167
+ cacheWriteTokens,
168
+ reasoningTokens,
169
+ totalTokens,
170
+ };
171
+ }
172
+ /**
173
+ * @param {Record<string, string | undefined>} tags
174
+ * @param {Record<string, unknown> | undefined} usage
175
+ * @returns {Effect.Effect<void>}
176
+ */
177
+ function recordAgentUsageMetrics(tags, usage) {
178
+ const totals = extractAgentUsageTotals(usage);
179
+ const effects = [];
180
+ /**
181
+ * @param {string} kind
182
+ * @param {number | undefined} value
183
+ */
184
+ const pushMetric = (kind, value) => {
185
+ if (!value || value <= 0) return;
186
+ effects.push(
187
+ Metric.update(
188
+ tagMetricWithTags(agentTokensTotal, {
189
+ ...tags,
190
+ kind,
191
+ }),
192
+ value,
193
+ ),
194
+ );
195
+ };
196
+ pushMetric("input", totals.inputTokens);
197
+ pushMetric("output", totals.outputTokens);
198
+ pushMetric("cache_read", totals.cacheReadTokens);
199
+ pushMetric("cache_write", totals.cacheWriteTokens);
200
+ pushMetric("reasoning", totals.reasoningTokens);
201
+ pushMetric("total", totals.totalTokens);
202
+ return effects.length > 0 ? Effect.all(effects, { discard: true }) : Effect.void;
203
+ }
204
+ /**
205
+ * @param {AgentEventPayload} event
206
+ * @returns {boolean}
207
+ */
208
+ function hasAgentRetrySignal(event) {
209
+ const retryPattern = /\bretry(?:ing|able| after)?\b|\bbackoff\b|\brate limit\b/i;
210
+ switch (event.type) {
211
+ case "started":
212
+ return false;
213
+ case "action": {
214
+ const detail = event.action.detail;
215
+ if (detail) {
216
+ const retryKeys = ["retryAfter", "retryAttempt", "retryDelayMs", "retryable", "backoffMs"];
217
+ if (retryKeys.some((key) => key in detail)) {
218
+ return true;
219
+ }
220
+ }
221
+ return retryPattern.test(`${event.action.title} ${event.message ?? ""}`);
222
+ }
223
+ case "completed":
224
+ return retryPattern.test(event.error ?? "");
225
+ }
226
+ }
227
+ // ---------------------------------------------------------------------------
228
+ // Event-driven metric tracking
229
+ // ---------------------------------------------------------------------------
230
+ /**
231
+ * @param {SmithersEvent} event
232
+ * @returns {Effect.Effect<void>}
233
+ */
234
+ export function trackEvent(event) {
235
+ // Always count the event by type
236
+ const countEvent = Metric.update(eventsEmittedTotal, 1);
237
+ switch (event.type) {
238
+ case "SupervisorStarted":
239
+ return countEvent;
240
+ case "SupervisorPollCompleted":
241
+ return Effect.all(
242
+ [
243
+ countEvent,
244
+ Metric.update(supervisorPollsTotal, 1),
245
+ Metric.update(supervisorStaleDetected, event.staleCount),
246
+ Metric.update(supervisorPollDuration, event.durationMs),
247
+ ],
248
+ { discard: true },
249
+ );
250
+ case "RunAutoResumed":
251
+ return Effect.all(
252
+ [
253
+ countEvent,
254
+ Metric.update(supervisorResumedTotal, 1),
255
+ Metric.update(supervisorResumeLag, event.staleDurationMs),
256
+ ],
257
+ { discard: true },
258
+ );
259
+ case "RunAutoResumeSkipped":
260
+ return Effect.all(
261
+ [
262
+ countEvent,
263
+ Metric.update(Metric.withAttributes(supervisorSkippedTotal, { ["reason"]: String(event.reason) }), 1),
264
+ ],
265
+ {
266
+ discard: true,
267
+ },
268
+ );
269
+ case "RunStarted":
270
+ return Effect.all([countEvent, Metric.update(runsTotal, 1), incrementGauge(activeRuns, 1)], {
271
+ discard: true,
272
+ });
273
+ case "SandboxCreated": {
274
+ const byRuntime =
275
+ event.runtime && event.runtime.length > 0
276
+ ? Metric.withAttributes(sandboxCreatedTotal, { ["runtime"]: String(event.runtime) })
277
+ : sandboxCreatedTotal;
278
+ return Effect.all(
279
+ [
280
+ countEvent,
281
+ Metric.update(byRuntime, 1),
282
+ incrementGauge(
283
+ event.runtime ? Metric.withAttributes(sandboxActive, { runtime: String(event.runtime) }) : sandboxActive,
284
+ 1,
285
+ ),
286
+ ],
287
+ { discard: true },
288
+ );
289
+ }
290
+ case "SandboxShipped":
291
+ return Effect.all([countEvent, Metric.update(sandboxBundleSizeBytes, event.bundleSizeBytes)], { discard: true });
292
+ case "SandboxBundleReceived":
293
+ return Effect.all(
294
+ [
295
+ countEvent,
296
+ Metric.update(sandboxBundleSizeBytes, event.bundleSizeBytes),
297
+ Metric.update(sandboxPatchCount, event.patchCount),
298
+ ],
299
+ { discard: true },
300
+ );
301
+ case "SandboxCompleted": {
302
+ const byStatus = Metric.withAttributes(sandboxCompletedTotal, { ["status"]: String(event.status) });
303
+ const byRuntime =
304
+ event.runtime && event.runtime.length > 0
305
+ ? Metric.withAttributes(byStatus, { ["runtime"]: String(event.runtime) })
306
+ : byStatus;
307
+ return Effect.all(
308
+ [
309
+ countEvent,
310
+ Metric.update(byRuntime, 1),
311
+ incrementGauge(
312
+ event.runtime ? Metric.withAttributes(sandboxActive, { runtime: String(event.runtime) }) : sandboxActive,
313
+ -1,
314
+ ),
315
+ Metric.update(sandboxDurationMs, event.durationMs),
316
+ ],
317
+ { discard: true },
318
+ );
319
+ }
320
+ case "SandboxFailed":
321
+ return Effect.all([countEvent, Metric.update(errorsTotal, 1)], { discard: true });
322
+ case "SandboxDiffReviewRequested":
323
+ return Effect.all([countEvent, Metric.update(sandboxPatchCount, event.patchCount)], { discard: true });
324
+ case "SandboxDiffAccepted":
325
+ return Effect.all([countEvent, Metric.update(sandboxPatchCount, event.patchCount)], { discard: true });
326
+ case "SandboxDiffRejected":
327
+ return Effect.all([countEvent, Metric.update(errorsTotal, 1)], { discard: true });
328
+ case "RunFinished":
329
+ return Effect.all([countEvent, incrementGauge(activeRuns, -1), Metric.update(runsFinishedTotal, 1)], {
330
+ discard: true,
331
+ });
332
+ case "RunFailed":
333
+ return Effect.all(
334
+ [countEvent, incrementGauge(activeRuns, -1), Metric.update(runsFailedTotal, 1), Metric.update(errorsTotal, 1)],
335
+ { discard: true },
336
+ );
337
+ case "RunCancelled":
338
+ return Effect.all([countEvent, incrementGauge(activeRuns, -1), Metric.update(runsCancelledTotal, 1)], {
339
+ discard: true,
340
+ });
341
+ case "RunContinuedAsNew":
342
+ return Effect.all(
343
+ [
344
+ countEvent,
345
+ incrementGauge(activeRuns, -1),
346
+ Metric.update(runsContinuedTotal, 1),
347
+ Metric.update(runsCarriedStateBytes, event.carriedStateSize),
348
+ ...(typeof event.ancestryDepth === "number" ? [Metric.update(runsAncestryDepth, event.ancestryDepth)] : []),
349
+ ],
350
+ { discard: true },
351
+ );
352
+ case "NodeStarted":
353
+ return Effect.all([countEvent, Metric.update(nodesStarted, 1), incrementGauge(activeNodes, 1)], {
354
+ discard: true,
355
+ });
356
+ case "TaskHeartbeat":
357
+ return Effect.all(
358
+ [
359
+ countEvent,
360
+ Metric.update(taskHeartbeatsTotal, 1),
361
+ Metric.update(heartbeatDataSizeBytes, event.dataSizeBytes),
362
+ ...(typeof event.intervalMs === "number" ? [Metric.update(heartbeatIntervalMs, event.intervalMs)] : []),
363
+ ],
364
+ { discard: true },
365
+ );
366
+ case "TaskHeartbeatTimeout":
367
+ return Effect.all([countEvent, Metric.update(taskHeartbeatTimeoutTotal, 1)], { discard: true });
368
+ case "NodeFinished":
369
+ return Effect.all([countEvent, Metric.update(nodesFinished, 1), incrementGauge(activeNodes, -1)], {
370
+ discard: true,
371
+ });
372
+ case "NodeFailed":
373
+ return Effect.all(
374
+ [countEvent, Metric.update(nodesFailed, 1), incrementGauge(activeNodes, -1), Metric.update(errorsTotal, 1)],
375
+ { discard: true },
376
+ );
377
+ case "NodeCancelled":
378
+ return Effect.all([countEvent, incrementGauge(activeNodes, -1)], { discard: true });
379
+ case "NodeRetrying":
380
+ return Effect.all([countEvent, Metric.update(nodeRetriesTotal, 1)], { discard: true });
381
+ case "ToolCallStarted":
382
+ return Effect.all([countEvent, Metric.update(toolCallsTotal, 1)], { discard: true });
383
+ case "ToolCallFinished":
384
+ return event.status === "error"
385
+ ? Effect.all([countEvent, Metric.update(toolCallErrorsTotal, 1)], { discard: true })
386
+ : countEvent;
387
+ case "ApprovalRequested":
388
+ return Effect.all([countEvent, Metric.update(approvalsRequested, 1), incrementGauge(approvalPending, 1)], {
389
+ discard: true,
390
+ });
391
+ case "ApprovalGranted":
392
+ return Effect.all([countEvent, Metric.update(approvalsGranted, 1), incrementGauge(approvalPending, -1)], {
393
+ discard: true,
394
+ });
395
+ case "ApprovalAutoApproved":
396
+ return Effect.all([countEvent, Metric.update(approvalsGranted, 1)], { discard: true });
397
+ case "ApprovalDenied":
398
+ return Effect.all([countEvent, Metric.update(approvalsDenied, 1), incrementGauge(approvalPending, -1)], {
399
+ discard: true,
400
+ });
401
+ case "TimerCreated":
402
+ return Effect.all([countEvent, Metric.update(timersCreated, 1), incrementGauge(timersPending, 1)], {
403
+ discard: true,
404
+ });
405
+ case "TimerFired":
406
+ return Effect.all(
407
+ [
408
+ countEvent,
409
+ Metric.update(timersFired, 1),
410
+ incrementGauge(timersPending, -1),
411
+ Metric.update(timerDelayDuration, event.delayMs),
412
+ ],
413
+ { discard: true },
414
+ );
415
+ case "TimerCancelled":
416
+ return Effect.all([countEvent, Metric.update(timersCancelled, 1), incrementGauge(timersPending, -1)], {
417
+ discard: true,
418
+ });
419
+ case "TokenUsageReported": {
420
+ const effects = [countEvent];
421
+ const tags = {};
422
+ if (event.model && event.model !== "unknown") tags.model = event.model;
423
+ if (event.agent && event.agent !== "unknown") tags.agent = event.agent;
424
+ // tags only ever holds non-empty strings, so tagMetricWithTags' falsy-skip is a no-op here.
425
+ /** @type {<A>(m: A) => A} */
426
+ const tagMetric = (m) => tagMetricWithTags(m, tags);
427
+ if (event.inputTokens > 0) {
428
+ effects.push(
429
+ Metric.update(tagMetric(tokensInputTotal), event.inputTokens),
430
+ Metric.update(tagMetric(tokensInputPerCall), event.inputTokens),
431
+ );
432
+ }
433
+ if (event.outputTokens > 0) {
434
+ effects.push(
435
+ Metric.update(tagMetric(tokensOutputTotal), event.outputTokens),
436
+ Metric.update(tagMetric(tokensOutputPerCall), event.outputTokens),
437
+ );
438
+ }
439
+ if (event.cacheReadTokens && event.cacheReadTokens > 0) {
440
+ effects.push(Metric.update(tagMetric(tokensCacheReadTotal), event.cacheReadTokens));
441
+ }
442
+ if (event.cacheWriteTokens && event.cacheWriteTokens > 0) {
443
+ effects.push(Metric.update(tagMetric(tokensCacheWriteTotal), event.cacheWriteTokens));
444
+ }
445
+ if (event.reasoningTokens && event.reasoningTokens > 0) {
446
+ effects.push(Metric.update(tagMetric(tokensReasoningTotal), event.reasoningTokens));
447
+ }
448
+ const contextWindowTokens = resolveContextWindowTokens(event);
449
+ if (contextWindowTokens) {
450
+ effects.push(
451
+ Metric.update(tagMetric(tokensContextWindowPerCall), contextWindowTokens),
452
+ Metric.update(
453
+ tagMetric(
454
+ Metric.withAttributes(tokensContextWindowBucketTotal, {
455
+ ["bucket"]: String(classifyContextWindowBucket(contextWindowTokens)),
456
+ }),
457
+ ),
458
+ 1,
459
+ ),
460
+ );
461
+ }
462
+ return Effect.all(effects, { discard: true });
463
+ }
464
+ case "AgentEvent": {
465
+ const agentEvent = event.event;
466
+ const engine = normalizeMetricTag(agentEvent.engine) ?? normalizeMetricTag(event.engine) ?? "unknown";
467
+ const baseTags = {
468
+ engine,
469
+ source: "event",
470
+ };
471
+ const effects = [
472
+ countEvent,
473
+ Metric.update(
474
+ tagMetricWithTags(agentEventsTotal, {
475
+ ...baseTags,
476
+ event_type: agentEvent.type,
477
+ }),
478
+ 1,
479
+ ),
480
+ ];
481
+ switch (agentEvent.type) {
482
+ case "started":
483
+ effects.push(
484
+ Metric.update(
485
+ tagMetricWithTags(agentSessionsTotal, {
486
+ ...baseTags,
487
+ status: "started",
488
+ resume: agentEvent.resume ? "true" : "false",
489
+ }),
490
+ 1,
491
+ ),
492
+ );
493
+ break;
494
+ case "action":
495
+ effects.push(
496
+ Metric.update(
497
+ tagMetricWithTags(agentActionsTotal, {
498
+ ...baseTags,
499
+ action_kind: agentEvent.action.kind,
500
+ phase: agentEvent.phase,
501
+ level: agentEvent.level,
502
+ entry_type: agentEvent.entryType,
503
+ ok: typeof agentEvent.ok === "boolean" ? String(agentEvent.ok) : undefined,
504
+ }),
505
+ 1,
506
+ ),
507
+ );
508
+ if (agentEvent.level === "error" || agentEvent.ok === false) {
509
+ effects.push(
510
+ Metric.update(
511
+ tagMetricWithTags(agentErrorsTotal, {
512
+ ...baseTags,
513
+ event_type: agentEvent.type,
514
+ action_kind: agentEvent.action.kind,
515
+ }),
516
+ 1,
517
+ ),
518
+ );
519
+ }
520
+ if (hasAgentRetrySignal(agentEvent)) {
521
+ effects.push(
522
+ Metric.update(
523
+ tagMetricWithTags(agentRetriesTotal, {
524
+ ...baseTags,
525
+ reason: "event_signal",
526
+ }),
527
+ 1,
528
+ ),
529
+ );
530
+ }
531
+ break;
532
+ case "completed":
533
+ effects.push(
534
+ Metric.update(
535
+ tagMetricWithTags(agentSessionsTotal, {
536
+ ...baseTags,
537
+ status: agentEvent.ok ? "completed" : "failed",
538
+ resume: agentEvent.resume ? "true" : "false",
539
+ }),
540
+ 1,
541
+ ),
542
+ );
543
+ effects.push(recordAgentUsageMetrics(baseTags, agentEvent.usage));
544
+ if (!agentEvent.ok) {
545
+ effects.push(
546
+ Metric.update(
547
+ tagMetricWithTags(agentErrorsTotal, {
548
+ ...baseTags,
549
+ event_type: agentEvent.type,
550
+ }),
551
+ 1,
552
+ ),
553
+ );
554
+ }
555
+ if (hasAgentRetrySignal(agentEvent)) {
556
+ effects.push(
557
+ Metric.update(
558
+ tagMetricWithTags(agentRetriesTotal, {
559
+ ...baseTags,
560
+ reason: "event_signal",
561
+ }),
562
+ 1,
563
+ ),
564
+ );
565
+ }
566
+ break;
567
+ }
568
+ return Effect.all(effects, { discard: true });
569
+ }
570
+ case "ScorerStarted":
571
+ return Effect.all([countEvent, Metric.update(scorerEventsStarted, 1)], { discard: true });
572
+ case "ScorerFinished":
573
+ return Effect.all([countEvent, Metric.update(scorerEventsFinished, 1)], { discard: true });
574
+ case "ScorerFailed":
575
+ return Effect.all([countEvent, Metric.update(scorerEventsFailed, 1), Metric.update(errorsTotal, 1)], {
576
+ discard: true,
577
+ });
578
+ case "SnapshotCaptured":
579
+ return countEvent;
580
+ case "RunForked":
581
+ return countEvent;
582
+ case "ReplayStarted":
583
+ return countEvent;
584
+ case "MemoryFactSet":
585
+ return Effect.all([countEvent, Metric.update(memoryFactWrites, 1)], { discard: true });
586
+ case "MemoryRecalled":
587
+ return Effect.all([countEvent, Metric.update(memoryRecallQueries, 1)], { discard: true });
588
+ case "MemoryMessageSaved":
589
+ return Effect.all([countEvent, Metric.update(memoryMessageSaves, 1)], { discard: true });
590
+ case "OpenApiToolCalled":
591
+ return event.status === "error"
592
+ ? Effect.all(
593
+ [
594
+ countEvent,
595
+ Metric.update(openApiToolCallsTotal, 1),
596
+ Metric.update(openApiToolCallErrorsTotal, 1),
597
+ Metric.update(openApiToolDuration, event.durationMs),
598
+ ],
599
+ { discard: true },
600
+ )
601
+ : Effect.all(
602
+ [countEvent, Metric.update(openApiToolCallsTotal, 1), Metric.update(openApiToolDuration, event.durationMs)],
603
+ { discard: true },
604
+ );
605
+ default:
606
+ return countEvent;
607
+ }
608
+ }
@@ -0,0 +1,18 @@
1
+ import { Effect, Metric } from "effect";
2
+ import { asyncExternalWaitCounts } from "./_asyncExternalWaitCounts.js";
3
+ import { externalWaitAsyncPending } from "./externalWaitAsyncPending.js";
4
+ /**
5
+ * @param {"approval" | "event"} kind
6
+ * @param {number} delta
7
+ * @returns {Effect.Effect<void>}
8
+ */
9
+ export function updateAsyncExternalWaitPending(kind, delta) {
10
+ return Effect.sync(() => {
11
+ asyncExternalWaitCounts[kind] = Math.max(0, asyncExternalWaitCounts[kind] + delta);
12
+ return asyncExternalWaitCounts[kind];
13
+ }).pipe(
14
+ Effect.flatMap((value) =>
15
+ Metric.update(Metric.withAttributes(externalWaitAsyncPending, { ["kind"]: String(kind) }), value),
16
+ ),
17
+ );
18
+ }
@@ -0,0 +1,20 @@
1
+ import { Effect, Metric } from "effect";
2
+ import { processStartMs } from "./_processStartMs.js";
3
+ import { processUptimeSeconds } from "./processUptimeSeconds.js";
4
+ import { processMemoryRssBytes } from "./processMemoryRssBytes.js";
5
+ import { processHeapUsedBytes } from "./processHeapUsedBytes.js";
6
+ /**
7
+ * @returns {Effect.Effect<void>}
8
+ */
9
+ export function updateProcessMetrics() {
10
+ const uptimeS = (Date.now() - processStartMs) / 1000;
11
+ const mem = process.memoryUsage();
12
+ return Effect.all(
13
+ [
14
+ Metric.update(processUptimeSeconds, uptimeS),
15
+ Metric.update(processMemoryRssBytes, mem.rss),
16
+ Metric.update(processHeapUsedBytes, mem.heapUsed),
17
+ ],
18
+ { discard: true },
19
+ );
20
+ }
@@ -0,0 +1,3 @@
1
+ import { Metric } from "effect";
2
+ import { fastBuckets } from "./_buckets.js";
3
+ export const vcsDuration = Metric.histogram("smithers.vcs.duration_ms", { boundaries: fastBuckets });
@@ -0,0 +1,15 @@
1
+ import { normalizeStructuredEventForFamily } from "./_traceEventNormalizers.js";
2
+ /**
3
+ * @typedef {import('./agentTrace.ts').AgentFamily} AgentFamily
4
+ * @typedef {import('./_traceEventNormalizers.js').NormalizedTraceBatch} NormalizedTraceBatch
5
+ */
6
+
7
+ /**
8
+ * @param {AgentFamily} agentFamily
9
+ * @param {any} parsed
10
+ * @param {string} rawType
11
+ * @returns {NormalizedTraceBatch}
12
+ */
13
+ export function normalizeStructuredEvent(agentFamily, parsed, rawType) {
14
+ return normalizeStructuredEventForFamily(agentFamily, parsed, rawType);
15
+ }
@@ -0,0 +1 @@
1
+ export const prometheusContentType = "text/plain; version=0.0.4; charset=utf-8";