@atrim/instrument-node 0.1.3-12a8f92-20251118011211

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