@atrim/instrument-node 1.0.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.
@@ -0,0 +1,669 @@
1
+ import { Data, Effect, Cache, Layer, FiberSet as FiberSet$1, Duration, Schedule, Tracer } from 'effect';
2
+ import * as Otlp from '@effect/opentelemetry/Otlp';
3
+ import { FetchHttpClient } from '@effect/platform';
4
+ import { TraceFlags, trace, context } from '@opentelemetry/api';
5
+ import { existsSync, readFileSync } from 'fs';
6
+ import { join } from 'path';
7
+ import { parse } from 'yaml';
8
+ import { z } from 'zod';
9
+
10
+ // src/integrations/effect/effect-tracer.ts
11
+ var __defProp = Object.defineProperty;
12
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
13
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
14
+ var PatternConfigSchema = z.object({
15
+ pattern: z.string(),
16
+ enabled: z.boolean().optional(),
17
+ description: z.string().optional()
18
+ });
19
+ var AutoIsolationConfigSchema = z.object({
20
+ // Global enable/disable for auto-isolation
21
+ enabled: z.boolean().default(false),
22
+ // Which operators to auto-isolate
23
+ operators: z.object({
24
+ fiberset_run: z.boolean().default(true),
25
+ effect_fork: z.boolean().default(true),
26
+ effect_fork_daemon: z.boolean().default(true),
27
+ effect_fork_in: z.boolean().default(false)
28
+ }).default({}),
29
+ // Virtual parent tracking configuration
30
+ tracking: z.object({
31
+ use_span_links: z.boolean().default(true),
32
+ use_attributes: z.boolean().default(true),
33
+ capture_logical_parent: z.boolean().default(true)
34
+ }).default({}),
35
+ // Span categorization
36
+ attributes: z.object({
37
+ category: z.string().default("background_task"),
38
+ add_metadata: z.boolean().default(true)
39
+ }).default({})
40
+ });
41
+ var InstrumentationConfigSchema = z.object({
42
+ version: z.string(),
43
+ instrumentation: z.object({
44
+ enabled: z.boolean(),
45
+ description: z.string().optional(),
46
+ logging: z.enum(["on", "off", "minimal"]).optional().default("on"),
47
+ instrument_patterns: z.array(PatternConfigSchema),
48
+ ignore_patterns: z.array(PatternConfigSchema)
49
+ }),
50
+ effect: z.object({
51
+ auto_extract_metadata: z.boolean(),
52
+ auto_isolation: AutoIsolationConfigSchema.optional()
53
+ }).optional()
54
+ });
55
+ (class extends Data.TaggedError("ConfigError") {
56
+ });
57
+ var ConfigUrlError = class extends Data.TaggedError("ConfigUrlError") {
58
+ };
59
+ var ConfigValidationError = class extends Data.TaggedError("ConfigValidationError") {
60
+ };
61
+ var ConfigFileError = class extends Data.TaggedError("ConfigFileError") {
62
+ };
63
+ (class extends Data.TaggedError("ServiceDetectionError") {
64
+ });
65
+ (class extends Data.TaggedError("InitializationError") {
66
+ });
67
+ (class extends Data.TaggedError("ExportError") {
68
+ });
69
+ (class extends Data.TaggedError("ShutdownError") {
70
+ });
71
+ var SECURITY_DEFAULTS = {
72
+ maxConfigSize: 1e6,
73
+ // 1MB
74
+ requestTimeout: 5e3,
75
+ allowedProtocols: ["https:"],
76
+ // Only HTTPS for remote configs
77
+ cacheTimeout: 3e5
78
+ // 5 minutes
79
+ };
80
+ function getDefaultConfig() {
81
+ return {
82
+ version: "1.0",
83
+ instrumentation: {
84
+ enabled: true,
85
+ logging: "on",
86
+ description: "Default instrumentation configuration",
87
+ instrument_patterns: [
88
+ { pattern: "^app\\.", enabled: true, description: "Application operations" },
89
+ { pattern: "^http\\.server\\.", enabled: true, description: "HTTP server operations" },
90
+ { pattern: "^http\\.client\\.", enabled: true, description: "HTTP client operations" }
91
+ ],
92
+ ignore_patterns: [
93
+ { pattern: "^test\\.", description: "Test utilities" },
94
+ { pattern: "^internal\\.", description: "Internal operations" },
95
+ { pattern: "^health\\.", description: "Health checks" }
96
+ ]
97
+ },
98
+ effect: {
99
+ auto_extract_metadata: true
100
+ }
101
+ };
102
+ }
103
+ var validateConfigEffect = (rawConfig) => Effect.try({
104
+ try: () => InstrumentationConfigSchema.parse(rawConfig),
105
+ catch: (error) => new ConfigValidationError({
106
+ reason: "Invalid configuration schema",
107
+ cause: error
108
+ })
109
+ });
110
+ var loadConfigFromFileEffect = (filePath) => Effect.gen(function* () {
111
+ const fileContents = yield* Effect.try({
112
+ try: () => readFileSync(filePath, "utf8"),
113
+ catch: (error) => new ConfigFileError({
114
+ reason: `Failed to read config file at ${filePath}`,
115
+ cause: error
116
+ })
117
+ });
118
+ if (fileContents.length > SECURITY_DEFAULTS.maxConfigSize) {
119
+ return yield* Effect.fail(
120
+ new ConfigFileError({
121
+ reason: `Config file exceeds maximum size of ${SECURITY_DEFAULTS.maxConfigSize} bytes`
122
+ })
123
+ );
124
+ }
125
+ let rawConfig;
126
+ try {
127
+ rawConfig = parse(fileContents);
128
+ } catch (error) {
129
+ return yield* Effect.fail(
130
+ new ConfigValidationError({
131
+ reason: "Invalid YAML syntax",
132
+ cause: error
133
+ })
134
+ );
135
+ }
136
+ return yield* validateConfigEffect(rawConfig);
137
+ });
138
+ var fetchAndParseConfig = (url) => Effect.gen(function* () {
139
+ let urlObj;
140
+ try {
141
+ urlObj = new URL(url);
142
+ } catch (error) {
143
+ return yield* Effect.fail(
144
+ new ConfigUrlError({
145
+ reason: `Invalid URL: ${url}`,
146
+ cause: error
147
+ })
148
+ );
149
+ }
150
+ if (!SECURITY_DEFAULTS.allowedProtocols.includes(urlObj.protocol)) {
151
+ return yield* Effect.fail(
152
+ new ConfigUrlError({
153
+ reason: `Insecure protocol ${urlObj.protocol}. Only ${SECURITY_DEFAULTS.allowedProtocols.join(", ")} are allowed`
154
+ })
155
+ );
156
+ }
157
+ const response = yield* Effect.tryPromise({
158
+ try: () => fetch(url, {
159
+ redirect: "follow",
160
+ headers: {
161
+ Accept: "application/yaml, text/yaml, text/x-yaml"
162
+ }
163
+ }),
164
+ catch: (error) => new ConfigUrlError({
165
+ reason: `Failed to load config from URL ${url}`,
166
+ cause: error
167
+ })
168
+ }).pipe(
169
+ Effect.timeout(Duration.millis(SECURITY_DEFAULTS.requestTimeout)),
170
+ Effect.retry({
171
+ times: 3,
172
+ schedule: Schedule.exponential(Duration.millis(100))
173
+ }),
174
+ Effect.catchAll((error) => {
175
+ if (error._tag === "TimeoutException") {
176
+ return Effect.fail(
177
+ new ConfigUrlError({
178
+ reason: `Config fetch timeout after ${SECURITY_DEFAULTS.requestTimeout}ms`
179
+ })
180
+ );
181
+ }
182
+ return Effect.fail(error);
183
+ })
184
+ );
185
+ if (!response.ok) {
186
+ return yield* Effect.fail(
187
+ new ConfigUrlError({
188
+ reason: `HTTP ${response.status}: ${response.statusText}`
189
+ })
190
+ );
191
+ }
192
+ const contentLength = response.headers.get("content-length");
193
+ if (contentLength && parseInt(contentLength) > SECURITY_DEFAULTS.maxConfigSize) {
194
+ return yield* Effect.fail(
195
+ new ConfigUrlError({
196
+ reason: `Config exceeds maximum size of ${SECURITY_DEFAULTS.maxConfigSize} bytes`
197
+ })
198
+ );
199
+ }
200
+ const text = yield* Effect.tryPromise({
201
+ try: () => response.text(),
202
+ catch: (error) => new ConfigUrlError({
203
+ reason: "Failed to read response body",
204
+ cause: error
205
+ })
206
+ });
207
+ if (text.length > SECURITY_DEFAULTS.maxConfigSize) {
208
+ return yield* Effect.fail(
209
+ new ConfigUrlError({
210
+ reason: `Config exceeds maximum size of ${SECURITY_DEFAULTS.maxConfigSize} bytes`
211
+ })
212
+ );
213
+ }
214
+ let rawConfig;
215
+ try {
216
+ rawConfig = parse(text);
217
+ } catch (error) {
218
+ return yield* Effect.fail(
219
+ new ConfigValidationError({
220
+ reason: "Invalid YAML syntax",
221
+ cause: error
222
+ })
223
+ );
224
+ }
225
+ return yield* validateConfigEffect(rawConfig);
226
+ });
227
+ var makeConfigCache = () => Cache.make({
228
+ capacity: 100,
229
+ timeToLive: Duration.minutes(5),
230
+ lookup: (url) => fetchAndParseConfig(url)
231
+ });
232
+ var cacheInstance = null;
233
+ var getCache = Effect.gen(function* () {
234
+ if (!cacheInstance) {
235
+ cacheInstance = yield* makeConfigCache();
236
+ }
237
+ return cacheInstance;
238
+ });
239
+ var loadConfigFromUrlEffect = (url, cacheTimeout = SECURITY_DEFAULTS.cacheTimeout) => Effect.gen(function* () {
240
+ if (cacheTimeout === 0) {
241
+ return yield* fetchAndParseConfig(url);
242
+ }
243
+ const cache = yield* getCache;
244
+ return yield* cache.get(url);
245
+ });
246
+ var loadConfigEffect = (options = {}) => Effect.gen(function* () {
247
+ if (options.config) {
248
+ return yield* validateConfigEffect(options.config);
249
+ }
250
+ const envConfigPath = process.env.ATRIM_INSTRUMENTATION_CONFIG;
251
+ if (envConfigPath) {
252
+ if (envConfigPath.startsWith("http://") || envConfigPath.startsWith("https://")) {
253
+ return yield* loadConfigFromUrlEffect(envConfigPath, options.cacheTimeout);
254
+ }
255
+ return yield* loadConfigFromFileEffect(envConfigPath);
256
+ }
257
+ if (options.configUrl) {
258
+ return yield* loadConfigFromUrlEffect(options.configUrl, options.cacheTimeout);
259
+ }
260
+ if (options.configPath) {
261
+ return yield* loadConfigFromFileEffect(options.configPath);
262
+ }
263
+ const defaultPath = join(process.cwd(), "instrumentation.yaml");
264
+ const exists = yield* Effect.sync(() => existsSync(defaultPath));
265
+ if (exists) {
266
+ return yield* loadConfigFromFileEffect(defaultPath);
267
+ }
268
+ return getDefaultConfig();
269
+ });
270
+ async function loadConfig(options = {}) {
271
+ return Effect.runPromise(
272
+ loadConfigEffect(options).pipe(
273
+ // Convert typed errors to regular Error with reason message for backward compatibility
274
+ Effect.mapError((error) => {
275
+ const message = error.reason;
276
+ const newError = new Error(message);
277
+ newError.cause = error.cause;
278
+ return newError;
279
+ })
280
+ )
281
+ );
282
+ }
283
+ var PatternMatcher = class {
284
+ constructor(config) {
285
+ __publicField(this, "ignorePatterns", []);
286
+ __publicField(this, "instrumentPatterns", []);
287
+ __publicField(this, "enabled", true);
288
+ this.enabled = config.instrumentation.enabled;
289
+ this.ignorePatterns = config.instrumentation.ignore_patterns.map((p) => this.compilePattern(p));
290
+ this.instrumentPatterns = config.instrumentation.instrument_patterns.filter((p) => p.enabled !== false).map((p) => this.compilePattern(p));
291
+ }
292
+ /**
293
+ * Compile a pattern configuration into a RegExp
294
+ */
295
+ compilePattern(pattern) {
296
+ try {
297
+ const compiled = {
298
+ regex: new RegExp(pattern.pattern),
299
+ enabled: pattern.enabled !== false
300
+ };
301
+ if (pattern.description !== void 0) {
302
+ compiled.description = pattern.description;
303
+ }
304
+ return compiled;
305
+ } catch (error) {
306
+ throw new Error(
307
+ `Failed to compile pattern "${pattern.pattern}": ${error instanceof Error ? error.message : String(error)}`
308
+ );
309
+ }
310
+ }
311
+ /**
312
+ * Check if a span should be instrumented
313
+ *
314
+ * Returns true if the span should be created, false otherwise.
315
+ *
316
+ * Logic:
317
+ * 1. If instrumentation disabled globally, return false
318
+ * 2. Check ignore patterns - if any match, return false
319
+ * 3. Check instrument patterns - if any match, return true
320
+ * 4. Default: return true (fail-open - create span if no patterns match)
321
+ */
322
+ shouldInstrument(spanName) {
323
+ if (!this.enabled) {
324
+ return false;
325
+ }
326
+ for (const pattern of this.ignorePatterns) {
327
+ if (pattern.regex.test(spanName)) {
328
+ return false;
329
+ }
330
+ }
331
+ for (const pattern of this.instrumentPatterns) {
332
+ if (pattern.enabled && pattern.regex.test(spanName)) {
333
+ return true;
334
+ }
335
+ }
336
+ return true;
337
+ }
338
+ /**
339
+ * Get statistics about pattern matching (for debugging/monitoring)
340
+ */
341
+ getStats() {
342
+ return {
343
+ enabled: this.enabled,
344
+ ignorePatternCount: this.ignorePatterns.length,
345
+ instrumentPatternCount: this.instrumentPatterns.filter((p) => p.enabled).length
346
+ };
347
+ }
348
+ };
349
+ function initializePatternMatcher(config) {
350
+ new PatternMatcher(config);
351
+ }
352
+ var Logger = class {
353
+ constructor() {
354
+ __publicField(this, "level", "on");
355
+ __publicField(this, "hasLoggedMinimal", false);
356
+ }
357
+ /**
358
+ * Set the logging level
359
+ */
360
+ setLevel(level) {
361
+ this.level = level;
362
+ this.hasLoggedMinimal = false;
363
+ }
364
+ /**
365
+ * Get the current logging level
366
+ */
367
+ getLevel() {
368
+ return this.level;
369
+ }
370
+ /**
371
+ * Log a minimal initialization message (only shown once in minimal mode)
372
+ */
373
+ minimal(message) {
374
+ if (this.level === "off") {
375
+ return;
376
+ }
377
+ if (this.level === "minimal" && !this.hasLoggedMinimal) {
378
+ console.log(message);
379
+ this.hasLoggedMinimal = true;
380
+ return;
381
+ }
382
+ if (this.level === "on") {
383
+ console.log(message);
384
+ }
385
+ }
386
+ /**
387
+ * Log an informational message
388
+ */
389
+ log(...args) {
390
+ if (this.level === "on") {
391
+ console.log(...args);
392
+ }
393
+ }
394
+ /**
395
+ * Log a warning message (shown in minimal mode)
396
+ */
397
+ warn(...args) {
398
+ if (this.level !== "off") {
399
+ console.warn(...args);
400
+ }
401
+ }
402
+ /**
403
+ * Log an error message (shown in minimal mode)
404
+ */
405
+ error(...args) {
406
+ if (this.level !== "off") {
407
+ console.error(...args);
408
+ }
409
+ }
410
+ /**
411
+ * Check if full logging is enabled
412
+ */
413
+ isEnabled() {
414
+ return this.level === "on";
415
+ }
416
+ /**
417
+ * Check if minimal logging is enabled
418
+ */
419
+ isMinimal() {
420
+ return this.level === "minimal";
421
+ }
422
+ /**
423
+ * Check if logging is completely disabled
424
+ */
425
+ isDisabled() {
426
+ return this.level === "off";
427
+ }
428
+ };
429
+ var logger = new Logger();
430
+
431
+ // src/integrations/effect/effect-tracer.ts
432
+ function createEffectInstrumentation(options = {}) {
433
+ return Layer.unwrapEffect(
434
+ Effect.gen(function* () {
435
+ const config = yield* Effect.tryPromise({
436
+ try: () => loadConfig(options),
437
+ catch: (error) => ({
438
+ _tag: "ConfigError",
439
+ message: error instanceof Error ? error.message : String(error)
440
+ })
441
+ });
442
+ yield* Effect.sync(() => {
443
+ const loggingLevel = config.instrumentation.logging || "on";
444
+ logger.setLevel(loggingLevel);
445
+ });
446
+ yield* Effect.sync(() => initializePatternMatcher(config));
447
+ const otlpEndpoint = options.otlpEndpoint || process.env.OTEL_EXPORTER_OTLP_ENDPOINT || "http://localhost:4318";
448
+ const serviceName = options.serviceName || process.env.OTEL_SERVICE_NAME || "effect-service";
449
+ const serviceVersion = options.serviceVersion || process.env.npm_package_version || "1.0.0";
450
+ const autoExtractMetadata = options.autoExtractMetadata ?? config.effect?.auto_extract_metadata ?? true;
451
+ const continueExistingTraces = options.continueExistingTraces ?? true;
452
+ logger.log("\u{1F50D} Effect OpenTelemetry instrumentation");
453
+ logger.log(` \u{1F4E1} Endpoint: ${otlpEndpoint}`);
454
+ logger.log(` \u{1F3F7}\uFE0F Service: ${serviceName}`);
455
+ logger.log(` \u2705 Auto metadata extraction: ${autoExtractMetadata}`);
456
+ logger.log(` \u2705 Continue existing traces: ${continueExistingTraces}`);
457
+ const otlpLayer = Otlp.layer({
458
+ baseUrl: otlpEndpoint,
459
+ resource: {
460
+ serviceName,
461
+ serviceVersion,
462
+ attributes: {
463
+ "platform.component": "effect",
464
+ "effect.auto_metadata": autoExtractMetadata,
465
+ "effect.context_propagation": continueExistingTraces
466
+ }
467
+ },
468
+ // Bridge Effect context to OpenTelemetry global context
469
+ // This is essential for context propagation to work properly
470
+ tracerContext: (f, span) => {
471
+ if (span._tag !== "Span") {
472
+ return f();
473
+ }
474
+ const spanContext = {
475
+ traceId: span.traceId,
476
+ spanId: span.spanId,
477
+ traceFlags: span.sampled ? TraceFlags.SAMPLED : TraceFlags.NONE
478
+ };
479
+ const otelSpan = trace.wrapSpanContext(spanContext);
480
+ return context.with(trace.setSpan(context.active(), otelSpan), f);
481
+ }
482
+ }).pipe(Layer.provide(FetchHttpClient.layer));
483
+ if (autoExtractMetadata) {
484
+ return otlpLayer;
485
+ }
486
+ return otlpLayer;
487
+ })
488
+ ).pipe(Layer.orDie);
489
+ }
490
+ var EffectInstrumentationLive = Effect.sync(() => {
491
+ const endpoint = process.env.OTEL_EXPORTER_OTLP_ENDPOINT || "http://localhost:4318";
492
+ const serviceName = process.env.OTEL_SERVICE_NAME || "effect-service";
493
+ const serviceVersion = process.env.npm_package_version || "1.0.0";
494
+ logger.log("\u{1F50D} Effect OpenTelemetry tracer (Otlp.layer)");
495
+ logger.log(` \u{1F4E1} Endpoint: ${endpoint}`);
496
+ logger.log(` \u{1F3F7}\uFE0F Service: ${serviceName}`);
497
+ return Otlp.layer({
498
+ baseUrl: endpoint,
499
+ resource: {
500
+ serviceName,
501
+ serviceVersion,
502
+ attributes: {
503
+ "platform.component": "effect"
504
+ }
505
+ },
506
+ // CRITICAL: Bridge Effect context to OpenTelemetry global context
507
+ // This allows NodeSDK auto-instrumentation to see Effect spans as parent spans
508
+ tracerContext: (f, span) => {
509
+ if (span._tag !== "Span") {
510
+ return f();
511
+ }
512
+ const spanContext = {
513
+ traceId: span.traceId,
514
+ spanId: span.spanId,
515
+ traceFlags: span.sampled ? TraceFlags.SAMPLED : TraceFlags.NONE
516
+ };
517
+ const otelSpan = trace.wrapSpanContext(spanContext);
518
+ return context.with(trace.setSpan(context.active(), otelSpan), f);
519
+ }
520
+ }).pipe(Layer.provide(FetchHttpClient.layer));
521
+ }).pipe(Layer.unwrapEffect);
522
+
523
+ // src/integrations/effect/effect-helpers.ts
524
+ function annotateUser(_userId, _email) {
525
+ }
526
+ function annotateDataSize(_bytes, _count) {
527
+ }
528
+ function annotateBatch(_size, _batchSize) {
529
+ }
530
+ function annotateLLM(_model, _operation, _inputTokens, _outputTokens) {
531
+ }
532
+ function annotateQuery(_query, _database) {
533
+ }
534
+ function annotateHttpRequest(_method, _url, _statusCode) {
535
+ }
536
+ function annotateError(_error, _context) {
537
+ }
538
+ function annotatePriority(_priority) {
539
+ }
540
+ function annotateCache(_operation, _hit) {
541
+ }
542
+ var createLogicalParentLink = (parentSpan, useSpanLinks) => {
543
+ if (!useSpanLinks) {
544
+ return [];
545
+ }
546
+ return [
547
+ {
548
+ _tag: "SpanLink",
549
+ span: parentSpan,
550
+ attributes: {
551
+ "link.type": "logical_parent",
552
+ "atrim.relationship": "spawned_by",
553
+ description: "Logical parent (isolated to prevent context leakage)"
554
+ }
555
+ }
556
+ ];
557
+ };
558
+ var createLogicalParentAttributes = (parentSpan, useAttributes, category, useSpanLinks, customAttributes) => {
559
+ if (!useAttributes) {
560
+ return customAttributes;
561
+ }
562
+ return {
563
+ // Logical parent tracking (works in ALL tools)
564
+ "atrim.logical_parent.span_id": parentSpan.spanId,
565
+ "atrim.logical_parent.trace_id": parentSpan.traceId,
566
+ "atrim.logical_parent.name": parentSpan._tag === "Span" ? parentSpan.name : "external",
567
+ // Categorization and metadata
568
+ "atrim.fiberset.isolated": true,
569
+ "atrim.span.category": category,
570
+ "atrim.has_logical_parent": true,
571
+ "atrim.isolation.method": useSpanLinks ? "hybrid" : "attributes_only",
572
+ // User-provided attributes
573
+ ...customAttributes
574
+ };
575
+ };
576
+ var runIsolated = (set, effect, name, options) => {
577
+ const {
578
+ createRoot = true,
579
+ captureLogicalParent = true,
580
+ useSpanLinks = true,
581
+ useAttributes = true,
582
+ propagateInterruption,
583
+ attributes = {},
584
+ category = "background_task"
585
+ } = options ?? {};
586
+ if (!createRoot && !captureLogicalParent) {
587
+ return FiberSet$1.run(set, effect, { propagateInterruption });
588
+ }
589
+ return Effect.gen(function* () {
590
+ const maybeParent = yield* Effect.serviceOption(Tracer.ParentSpan);
591
+ if (maybeParent._tag === "None" || !captureLogicalParent) {
592
+ const isolated2 = effect.pipe(
593
+ Effect.withSpan(name, {
594
+ root: createRoot,
595
+ attributes: {
596
+ "atrim.fiberset.isolated": createRoot,
597
+ "atrim.span.category": category,
598
+ "atrim.has_logical_parent": false,
599
+ ...attributes
600
+ }
601
+ })
602
+ );
603
+ return yield* FiberSet$1.run(set, isolated2, { propagateInterruption });
604
+ }
605
+ const parent = maybeParent.value;
606
+ const links = createLogicalParentLink(parent, useSpanLinks);
607
+ const spanAttributes = createLogicalParentAttributes(
608
+ parent,
609
+ useAttributes,
610
+ category,
611
+ useSpanLinks,
612
+ attributes
613
+ );
614
+ const isolated = effect.pipe(
615
+ Effect.withSpan(name, {
616
+ root: createRoot,
617
+ links: links.length > 0 ? links : void 0,
618
+ attributes: spanAttributes
619
+ })
620
+ );
621
+ return yield* FiberSet$1.run(set, isolated, { propagateInterruption });
622
+ });
623
+ };
624
+ var runWithSpan = (set, name, effect, options) => {
625
+ return runIsolated(set, effect, name, {
626
+ createRoot: true,
627
+ captureLogicalParent: true,
628
+ useSpanLinks: true,
629
+ useAttributes: true,
630
+ ...options
631
+ });
632
+ };
633
+ var annotateSpawnedTasks = (tasks) => {
634
+ return Effect.annotateCurrentSpan({
635
+ "atrim.fiberset.spawned_count": tasks.length,
636
+ "atrim.fiberset.task_names": tasks.map((t) => t.name).join(","),
637
+ "atrim.has_background_tasks": true,
638
+ "atrim.spawned_tasks": JSON.stringify(
639
+ tasks.map((t) => ({
640
+ name: t.name,
641
+ ...t.spanId && { span_id: t.spanId },
642
+ ...t.category && { category: t.category }
643
+ }))
644
+ )
645
+ });
646
+ };
647
+ var FiberSet = {
648
+ // Re-export all original FiberSet functions
649
+ make: FiberSet$1.make,
650
+ add: FiberSet$1.add,
651
+ unsafeAdd: FiberSet$1.unsafeAdd,
652
+ run: FiberSet$1.run,
653
+ clear: FiberSet$1.clear,
654
+ join: FiberSet$1.join,
655
+ awaitEmpty: FiberSet$1.awaitEmpty,
656
+ size: FiberSet$1.size,
657
+ runtime: FiberSet$1.runtime,
658
+ runtimePromise: FiberSet$1.runtimePromise,
659
+ makeRuntime: FiberSet$1.makeRuntime,
660
+ makeRuntimePromise: FiberSet$1.makeRuntimePromise,
661
+ isFiberSet: FiberSet$1.isFiberSet,
662
+ // Add our isolation helpers
663
+ runIsolated,
664
+ runWithSpan
665
+ };
666
+
667
+ export { EffectInstrumentationLive, FiberSet, annotateBatch, annotateCache, annotateDataSize, annotateError, annotateHttpRequest, annotateLLM, annotatePriority, annotateQuery, annotateSpawnedTasks, annotateUser, createEffectInstrumentation, runIsolated, runWithSpan };
668
+ //# sourceMappingURL=index.js.map
669
+ //# sourceMappingURL=index.js.map