@uselemma/tracing 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Forge AI Labs, Inc
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,119 @@
1
+ # Tracing Module
2
+
3
+ OpenTelemetry-based tracing module for Lemma.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @uselemma/tracing
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ### Basic Setup
14
+
15
+ ```typescript
16
+ import { Tracer, TraceRunner, SpanType } from "@uselemma/tracing";
17
+
18
+ // Create a tracer
19
+ const tracer = new Tracer("my-service");
20
+
21
+ // Use TraceRunner for managing traces
22
+ const traceRunner = new TraceRunner(tracer, {
23
+ "prompt-name": "override template here",
24
+ });
25
+
26
+ // Run code within tracing context
27
+ await traceRunner.run(async () => {
28
+ // Your code here
29
+ const renderedPrompt = await tracer.prompt(
30
+ "prompt-name",
31
+ "Hello {{ name }}!",
32
+ { name: "World" }
33
+ );
34
+
35
+ // ... use renderedPrompt ...
36
+
37
+ tracer.addLlmOutput("LLM response", "gpt-4", {
38
+ prompt_tokens: 100,
39
+ completion_tokens: 50,
40
+ total_tokens: 150,
41
+ });
42
+ });
43
+
44
+ // Get trace data
45
+ const traceData = await traceRunner.record();
46
+ console.log(traceData.trace_id);
47
+ console.log(traceData.spans);
48
+ ```
49
+
50
+ ### Function Tracing
51
+
52
+ ```typescript
53
+ // Wrap a function for tracing
54
+ const tracedFunction = tracer.wrap(SpanType.TOOL, myFunction);
55
+
56
+ // Or use manually
57
+ const span = tracer.getCurrentSpan();
58
+ tracer.addMetadata("key", "value");
59
+ tracer.addEvent("event-name", { data: "value" });
60
+ ```
61
+
62
+ ### Prompt Tracing
63
+
64
+ ```typescript
65
+ // Method 1: Using prompt() (returns rendered prompt)
66
+ const renderedPrompt = await tracer.prompt(
67
+ "translation",
68
+ "Translate: {{ text }}",
69
+ { text: "Hello" }
70
+ );
71
+ // ... use renderedPrompt ...
72
+ tracer.addLlmOutput(result.content);
73
+
74
+ // Method 2: Using startPrompt() (returns context object)
75
+ const promptCtx = tracer.startPrompt("translation", "Translate: {{ text }}", {
76
+ text: "Hello",
77
+ });
78
+ // ... use promptCtx.renderedPrompt ...
79
+ tracer.addLlmOutput(result.content);
80
+ promptCtx.end(); // Manually end span
81
+ ```
82
+
83
+ ## API
84
+
85
+ ### SpanType
86
+
87
+ Enum for specifying span types:
88
+ - `SpanType.AGENT` - For agent operations
89
+ - `SpanType.NODE` - For node operations
90
+ - `SpanType.TOOL` - For tool operations
91
+
92
+ ### Tracer
93
+
94
+ - `wrap<T>(spanType: SpanType, func: T): T` - Wrap a function for tracing
95
+ - `prompt(promptName: string, promptTemplate: string, inputVars: Record<string, unknown>): Promise<string>` - Create a prompt span and render template
96
+ - `startPrompt(...)`: Start a prompt span and return context object
97
+ - `addLlmOutput(output: string, model?: string, usage?: {...}): void` - Add LLM output to current prompt span
98
+ - `addMetadata(key: string, value: unknown): void` - Add metadata to current span
99
+ - `addEvent(eventName: string, attributes?: Record<string, unknown>): void` - Add event to current span
100
+ - `getTraceId(): string | undefined` - Get current trace ID
101
+ - `forceFlush(): Promise<void>` - Force flush all pending spans
102
+ - `getSpans(): ReadableSpan[]` - Get all collected spans
103
+ - `getSpansAsDicts(): SpanDict[]` - Get all collected spans as dictionaries
104
+
105
+ ### TraceRunner
106
+
107
+ - `run<T>(callback: () => Promise<T> | T): Promise<T>` - Run callback within tracing context
108
+ - `record(): Promise<TraceData>` - Export spans and return trace data
109
+
110
+ ### CandidatePromptManager
111
+
112
+ - `run<T>(candidatePrompts: Record<string, string> | null, callback: () => Promise<T> | T): Promise<T>` - Run callback with candidate prompts
113
+ - `getEffectiveTemplate(promptName: string, defaultTemplate: string): [string, boolean]` - Get effective template
114
+
115
+ ### MemorySpanExporter
116
+
117
+ - `getSpans(): ReadableSpan[]` - Get all stored spans
118
+ - `getSpansAsDicts(): SpanDict[]` - Get all stored spans as dictionaries
119
+ - `clear(): void` - Clear stored spans
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Manages candidate prompt overrides using AsyncLocalStorage for context-local state.
3
+ */
4
+ export declare class CandidatePromptManager {
5
+ private readonly _overrides;
6
+ constructor();
7
+ /**
8
+ * Runs a callback with candidate prompts set in the async context.
9
+ *
10
+ * @param candidatePrompts - Optional dictionary of prompt name -> candidate template
11
+ * @param callback - Function to run with the context
12
+ * @returns Result of the callback
13
+ */
14
+ run<T>(candidatePrompts: Record<string, string> | null | undefined, callback: () => Promise<T> | T): Promise<T>;
15
+ /**
16
+ * Get the effective template, applying candidate override if present.
17
+ *
18
+ * @param promptName - Name of the prompt
19
+ * @param defaultTemplate - Default template to use if no override
20
+ * @returns Tuple of [effectiveTemplate, overrideApplied]
21
+ */
22
+ getEffectiveTemplate(promptName: string, defaultTemplate: string): [string, boolean];
23
+ /**
24
+ * Annotate span with candidate prompt metadata.
25
+ *
26
+ * @param span - OpenTelemetry span to annotate
27
+ */
28
+ annotateSpan(span: {
29
+ setAttribute: (key: string, value: unknown) => void;
30
+ }): void;
31
+ }
32
+ //# sourceMappingURL=candidate-prompt-manager.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"candidate-prompt-manager.d.ts","sourceRoot":"","sources":["../src/candidate-prompt-manager.ts"],"names":[],"mappings":"AAEA;;GAEG;AACH,qBAAa,sBAAsB;IACjC,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAmD;;IAM9E;;;;;;OAMG;IACG,GAAG,CAAC,CAAC,EACT,gBAAgB,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,IAAI,GAAG,SAAS,EAC3D,QAAQ,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC,GAC7B,OAAO,CAAC,CAAC,CAAC;IAIb;;;;;;OAMG;IACH,oBAAoB,CAClB,UAAU,EAAE,MAAM,EAClB,eAAe,EAAE,MAAM,GACtB,CAAC,MAAM,EAAE,OAAO,CAAC;IAQpB;;;;OAIG;IACH,YAAY,CAAC,IAAI,EAAE;QACjB,YAAY,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,KAAK,IAAI,CAAC;KACrD,GAAG,IAAI;CAaT"}
@@ -0,0 +1,55 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CandidatePromptManager = void 0;
4
+ const node_async_hooks_1 = require("node:async_hooks");
5
+ /**
6
+ * Manages candidate prompt overrides using AsyncLocalStorage for context-local state.
7
+ */
8
+ class CandidatePromptManager {
9
+ _overrides;
10
+ constructor() {
11
+ this._overrides = new node_async_hooks_1.AsyncLocalStorage();
12
+ }
13
+ /**
14
+ * Runs a callback with candidate prompts set in the async context.
15
+ *
16
+ * @param candidatePrompts - Optional dictionary of prompt name -> candidate template
17
+ * @param callback - Function to run with the context
18
+ * @returns Result of the callback
19
+ */
20
+ async run(candidatePrompts, callback) {
21
+ return this._overrides.run(candidatePrompts ?? null, callback);
22
+ }
23
+ /**
24
+ * Get the effective template, applying candidate override if present.
25
+ *
26
+ * @param promptName - Name of the prompt
27
+ * @param defaultTemplate - Default template to use if no override
28
+ * @returns Tuple of [effectiveTemplate, overrideApplied]
29
+ */
30
+ getEffectiveTemplate(promptName, defaultTemplate) {
31
+ const overrides = this._overrides.getStore();
32
+ if (overrides && promptName in overrides) {
33
+ return [overrides[promptName], true];
34
+ }
35
+ return [defaultTemplate, false];
36
+ }
37
+ /**
38
+ * Annotate span with candidate prompt metadata.
39
+ *
40
+ * @param span - OpenTelemetry span to annotate
41
+ */
42
+ annotateSpan(span) {
43
+ const overrides = this._overrides.getStore();
44
+ if (overrides !== null && overrides !== undefined) {
45
+ try {
46
+ span.setAttribute("candidate_prompts.count", Object.keys(overrides).length);
47
+ }
48
+ catch {
49
+ // Best-effort; avoid breaking tracing on attribute errors
50
+ }
51
+ }
52
+ }
53
+ }
54
+ exports.CandidatePromptManager = CandidatePromptManager;
55
+ //# sourceMappingURL=candidate-prompt-manager.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"candidate-prompt-manager.js","sourceRoot":"","sources":["../src/candidate-prompt-manager.ts"],"names":[],"mappings":";;;AAAA,uDAAqD;AAErD;;GAEG;AACH,MAAa,sBAAsB;IAChB,UAAU,CAAmD;IAE9E;QACE,IAAI,CAAC,UAAU,GAAG,IAAI,oCAAiB,EAAiC,CAAC;IAC3E,CAAC;IAED;;;;;;OAMG;IACH,KAAK,CAAC,GAAG,CACP,gBAA2D,EAC3D,QAA8B;QAE9B,OAAO,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,gBAAgB,IAAI,IAAI,EAAE,QAAQ,CAAC,CAAC;IACjE,CAAC;IAED;;;;;;OAMG;IACH,oBAAoB,CAClB,UAAkB,EAClB,eAAuB;QAEvB,MAAM,SAAS,GAAG,IAAI,CAAC,UAAU,CAAC,QAAQ,EAAE,CAAC;QAC7C,IAAI,SAAS,IAAI,UAAU,IAAI,SAAS,EAAE,CAAC;YACzC,OAAO,CAAC,SAAS,CAAC,UAAU,CAAC,EAAE,IAAI,CAAC,CAAC;QACvC,CAAC;QACD,OAAO,CAAC,eAAe,EAAE,KAAK,CAAC,CAAC;IAClC,CAAC;IAED;;;;OAIG;IACH,YAAY,CAAC,IAEZ;QACC,MAAM,SAAS,GAAG,IAAI,CAAC,UAAU,CAAC,QAAQ,EAAE,CAAC;QAC7C,IAAI,SAAS,KAAK,IAAI,IAAI,SAAS,KAAK,SAAS,EAAE,CAAC;YAClD,IAAI,CAAC;gBACH,IAAI,CAAC,YAAY,CACf,yBAAyB,EACzB,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,MAAM,CAC9B,CAAC;YACJ,CAAC;YAAC,MAAM,CAAC;gBACP,0DAA0D;YAC5D,CAAC;QACH,CAAC;IACH,CAAC;CACF;AA3DD,wDA2DC"}
@@ -0,0 +1,42 @@
1
+ import { ExportResultCode } from "@opentelemetry/core";
2
+ import type { ReadableSpan, SpanExporter } from "@opentelemetry/sdk-trace-base";
3
+ export interface SpanDict {
4
+ timestamp: string;
5
+ trace_id: string;
6
+ span_id: string;
7
+ parent_span_id: string | null;
8
+ name: string;
9
+ kind: string;
10
+ start_time_ns: bigint;
11
+ end_time_ns: bigint | null;
12
+ duration_ms: number | null;
13
+ attributes: Record<string, unknown>;
14
+ status: {
15
+ status_code: string;
16
+ description?: string;
17
+ } | null;
18
+ events: Array<{
19
+ name: string;
20
+ timestamp_ns: bigint;
21
+ attributes: Record<string, unknown>;
22
+ }>;
23
+ resource: Record<string, unknown>;
24
+ }
25
+ /**
26
+ * Span exporter that stores spans in memory for retrieval.
27
+ */
28
+ export declare class MemorySpanExporter implements SpanExporter {
29
+ private readonly _spans;
30
+ export(spans: ReadableSpan[]): Promise<{
31
+ code: ExportResultCode;
32
+ }>;
33
+ getSpans(): ReadableSpan[];
34
+ getSpansAsDicts(): SpanDict[];
35
+ private _formatTraceId;
36
+ private _formatSpanId;
37
+ private _spanToDict;
38
+ clear(): void;
39
+ shutdown(): Promise<void>;
40
+ forceFlush(): Promise<void>;
41
+ }
42
+ //# sourceMappingURL=exporter.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"exporter.d.ts","sourceRoot":"","sources":["../src/exporter.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,KAAK,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAEhF,MAAM,WAAW,QAAQ;IACvB,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;IAChB,cAAc,EAAE,MAAM,GAAG,IAAI,CAAC;IAC9B,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,aAAa,EAAE,MAAM,CAAC;IACtB,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACpC,MAAM,EAAE;QACN,WAAW,EAAE,MAAM,CAAC;QACpB,WAAW,CAAC,EAAE,MAAM,CAAC;KACtB,GAAG,IAAI,CAAC;IACT,MAAM,EAAE,KAAK,CAAC;QACZ,IAAI,EAAE,MAAM,CAAC;QACb,YAAY,EAAE,MAAM,CAAC;QACrB,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;KACrC,CAAC,CAAC;IACH,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACnC;AAED;;GAEG;AACH,qBAAa,kBAAmB,YAAW,YAAY;IACrD,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAsB;IAE7C,MAAM,CAAC,KAAK,EAAE,YAAY,EAAE,GAAG,OAAO,CAAC;QAAE,IAAI,EAAE,gBAAgB,CAAA;KAAE,CAAC;IAKlE,QAAQ,IAAI,YAAY,EAAE;IAI1B,eAAe,IAAI,QAAQ,EAAE;IAI7B,OAAO,CAAC,cAAc;IAKtB,OAAO,CAAC,aAAa;IAKrB,OAAO,CAAC,WAAW;IA2CnB,KAAK,IAAI,IAAI;IAIb,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC;IAIzB,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC;CAG5B"}
@@ -0,0 +1,78 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MemorySpanExporter = void 0;
4
+ const core_1 = require("@opentelemetry/core");
5
+ /**
6
+ * Span exporter that stores spans in memory for retrieval.
7
+ */
8
+ class MemorySpanExporter {
9
+ _spans = [];
10
+ export(spans) {
11
+ this._spans.push(...spans);
12
+ return Promise.resolve({ code: core_1.ExportResultCode.SUCCESS });
13
+ }
14
+ getSpans() {
15
+ return [...this._spans];
16
+ }
17
+ getSpansAsDicts() {
18
+ return this._spans.map((span) => this._spanToDict(span));
19
+ }
20
+ _formatTraceId(traceId) {
21
+ // Ensure trace ID is 32-character hex string
22
+ return traceId.padStart(32, "0").slice(0, 32);
23
+ }
24
+ _formatSpanId(spanId) {
25
+ // Ensure span ID is 16-character hex string
26
+ return spanId.padStart(16, "0").slice(0, 16);
27
+ }
28
+ _spanToDict(span) {
29
+ const spanCtx = span.spanContext();
30
+ const traceId = this._formatTraceId(spanCtx.traceId);
31
+ const spanId = this._formatSpanId(spanCtx.spanId);
32
+ const parentSpanId = span.parentSpanId
33
+ ? this._formatSpanId(span.parentSpanId)
34
+ : null;
35
+ return {
36
+ timestamp: new Date().toISOString(),
37
+ trace_id: traceId,
38
+ span_id: spanId,
39
+ parent_span_id: parentSpanId,
40
+ name: span.name,
41
+ kind: span.kind.toString(),
42
+ start_time_ns: BigInt(span.startTime[0]) * 1000000000n + BigInt(span.startTime[1]),
43
+ end_time_ns: span.endTime
44
+ ? BigInt(span.endTime[0]) * 1000000000n + BigInt(span.endTime[1])
45
+ : null,
46
+ duration_ms: span.endTime
47
+ ? (span.endTime[0] - span.startTime[0]) * 1000 +
48
+ (span.endTime[1] - span.startTime[1]) / 1_000_000
49
+ : null,
50
+ attributes: span.attributes ? { ...span.attributes } : {},
51
+ status: span.status
52
+ ? {
53
+ status_code: span.status.code.toString(),
54
+ description: span.status.message,
55
+ }
56
+ : null,
57
+ events: (span.events || []).map((event) => ({
58
+ name: event.name,
59
+ timestamp_ns: BigInt(event.time[0]) * 1000000000n + BigInt(event.time[1]),
60
+ attributes: event.attributes ? { ...event.attributes } : {},
61
+ })),
62
+ resource: span.resource?.attributes
63
+ ? { ...span.resource.attributes }
64
+ : {},
65
+ };
66
+ }
67
+ clear() {
68
+ this._spans.length = 0;
69
+ }
70
+ shutdown() {
71
+ return Promise.resolve();
72
+ }
73
+ forceFlush() {
74
+ return Promise.resolve();
75
+ }
76
+ }
77
+ exports.MemorySpanExporter = MemorySpanExporter;
78
+ //# sourceMappingURL=exporter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"exporter.js","sourceRoot":"","sources":["../src/exporter.ts"],"names":[],"mappings":";;;AAAA,8CAAuD;AA0BvD;;GAEG;AACH,MAAa,kBAAkB;IACZ,MAAM,GAAmB,EAAE,CAAC;IAE7C,MAAM,CAAC,KAAqB;QAC1B,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,KAAK,CAAC,CAAC;QAC3B,OAAO,OAAO,CAAC,OAAO,CAAC,EAAE,IAAI,EAAE,uBAAgB,CAAC,OAAO,EAAE,CAAC,CAAC;IAC7D,CAAC;IAED,QAAQ;QACN,OAAO,CAAC,GAAG,IAAI,CAAC,MAAM,CAAC,CAAC;IAC1B,CAAC;IAED,eAAe;QACb,OAAO,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC,CAAC;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C,EAAE;SACP,CAAC;IACJ,CAAC;IAED,KAAK;QACH,IAAI,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC;IACzB,CAAC;IAED,QAAQ;QACN,OAAO,OAAO,CAAC,OAAO,EAAE,CAAC;IAC3B,CAAC;IAED,UAAU;QACR,OAAO,OAAO,CAAC,OAAO,EAAE,CAAC;IAC3B,CAAC;CACF;AAhFD,gDAgFC"}
@@ -0,0 +1,5 @@
1
+ export { CandidatePromptManager } from './candidate-prompt-manager';
2
+ export { MemorySpanExporter, type SpanDict } from './exporter';
3
+ export { TraceRunner, type TraceData } from './trace-runner';
4
+ export { SpanType, Tracer } from './tracer';
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,MAAM,4BAA4B,CAAC;AACpE,OAAO,EAAE,kBAAkB,EAAE,KAAK,QAAQ,EAAE,MAAM,YAAY,CAAC;AAC/D,OAAO,EAAE,WAAW,EAAE,KAAK,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAC7D,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Tracer = exports.SpanType = exports.TraceRunner = exports.MemorySpanExporter = exports.CandidatePromptManager = void 0;
4
+ var candidate_prompt_manager_1 = require("./candidate-prompt-manager");
5
+ Object.defineProperty(exports, "CandidatePromptManager", { enumerable: true, get: function () { return candidate_prompt_manager_1.CandidatePromptManager; } });
6
+ var exporter_1 = require("./exporter");
7
+ Object.defineProperty(exports, "MemorySpanExporter", { enumerable: true, get: function () { return exporter_1.MemorySpanExporter; } });
8
+ var trace_runner_1 = require("./trace-runner");
9
+ Object.defineProperty(exports, "TraceRunner", { enumerable: true, get: function () { return trace_runner_1.TraceRunner; } });
10
+ var tracer_1 = require("./tracer");
11
+ Object.defineProperty(exports, "SpanType", { enumerable: true, get: function () { return tracer_1.SpanType; } });
12
+ Object.defineProperty(exports, "Tracer", { enumerable: true, get: function () { return tracer_1.Tracer; } });
13
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAAA,uEAAoE;AAA3D,kIAAA,sBAAsB,OAAA;AAC/B,uCAA+D;AAAtD,8GAAA,kBAAkB,OAAA;AAC3B,+CAA6D;AAApD,2GAAA,WAAW,OAAA;AACpB,mCAA4C;AAAnC,kGAAA,QAAQ,OAAA;AAAE,gGAAA,MAAM,OAAA"}
@@ -0,0 +1,67 @@
1
+ import type { Tracer } from './tracer';
2
+ export interface TraceData {
3
+ trace_id: string;
4
+ spans: Array<{
5
+ timestamp: string;
6
+ trace_id: string;
7
+ span_id: string;
8
+ parent_span_id: string | null;
9
+ name: string;
10
+ kind: string;
11
+ start_time_ns: bigint;
12
+ end_time_ns: bigint | null;
13
+ duration_ms: number | null;
14
+ attributes: Record<string, unknown>;
15
+ status: {
16
+ status_code: string;
17
+ description?: string;
18
+ } | null;
19
+ events: Array<{
20
+ name: string;
21
+ timestamp_ns: bigint;
22
+ attributes: Record<string, unknown>;
23
+ }>;
24
+ resource: Record<string, unknown>;
25
+ }>;
26
+ }
27
+ /**
28
+ * Wrapper around Tracer that manages candidate prompts and tracks trace_id.
29
+ *
30
+ * Usage:
31
+ * const traceRunner = new TraceRunner(tracer, { "prompt1": "..." });
32
+ *
33
+ * await traceRunner.run(async () => {
34
+ * // ... tracing code ...
35
+ * });
36
+ *
37
+ * const traceData = traceRunner.record();
38
+ * const traceId = traceData.trace_id;
39
+ * const spans = traceData.spans;
40
+ */
41
+ export declare class TraceRunner {
42
+ private readonly _tracer;
43
+ private readonly _cpm;
44
+ private readonly _candidatePrompts;
45
+ private _traceId;
46
+ private _contextEntered;
47
+ private _alreadyRecorded;
48
+ constructor(tracer: Tracer, candidatePrompts?: Record<string, string> | null);
49
+ /**
50
+ * Run a callback with candidate prompts set in the async context.
51
+ *
52
+ * All spans created within this context will be part of the same trace.
53
+ * The trace_id is captured from spans created within the context and can be retrieved via record().
54
+ *
55
+ * @param callback - Function to run within the tracing context
56
+ * @returns Result of the callback
57
+ */
58
+ run<T>(callback: () => Promise<T> | T): Promise<T>;
59
+ /**
60
+ * Export all spans and return the full trace with all child spans.
61
+ *
62
+ * @returns Dictionary with trace_id and spans
63
+ * @throws Error if called before context is entered or after already recorded
64
+ */
65
+ record(): Promise<TraceData>;
66
+ }
67
+ //# sourceMappingURL=trace-runner.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"trace-runner.d.ts","sourceRoot":"","sources":["../src/trace-runner.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAGvC,MAAM,WAAW,SAAS;IACxB,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,KAAK,CAAC;QACX,SAAS,EAAE,MAAM,CAAC;QAClB,QAAQ,EAAE,MAAM,CAAC;QACjB,OAAO,EAAE,MAAM,CAAC;QAChB,cAAc,EAAE,MAAM,GAAG,IAAI,CAAC;QAC9B,IAAI,EAAE,MAAM,CAAC;QACb,IAAI,EAAE,MAAM,CAAC;QACb,aAAa,EAAE,MAAM,CAAC;QACtB,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;QAC3B,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;QAC3B,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;QACpC,MAAM,EAAE;YACN,WAAW,EAAE,MAAM,CAAC;YACpB,WAAW,CAAC,EAAE,MAAM,CAAC;SACtB,GAAG,IAAI,CAAC;QACT,MAAM,EAAE,KAAK,CAAC;YACZ,IAAI,EAAE,MAAM,CAAC;YACb,YAAY,EAAE,MAAM,CAAC;YACrB,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;SACrC,CAAC,CAAC;QACH,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;KACnC,CAAC,CAAC;CACJ;AAED;;;;;;;;;;;;;GAaG;AACH,qBAAa,WAAW;IACtB,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAS;IACjC,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAyB;IAC9C,OAAO,CAAC,QAAQ,CAAC,iBAAiB,CAAgC;IAClE,OAAO,CAAC,QAAQ,CAAqB;IACrC,OAAO,CAAC,eAAe,CAAS;IAChC,OAAO,CAAC,gBAAgB,CAAS;gBAG/B,MAAM,EAAE,MAAM,EACd,gBAAgB,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,IAAI;IAUlD;;;;;;;;OAQG;IACG,GAAG,CAAC,CAAC,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC;IAqBxD;;;;;OAKG;IACG,MAAM,IAAI,OAAO,CAAC,SAAS,CAAC;CAmCnC"}
@@ -0,0 +1,93 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TraceRunner = void 0;
4
+ const candidate_prompt_manager_1 = require("./candidate-prompt-manager");
5
+ /**
6
+ * Wrapper around Tracer that manages candidate prompts and tracks trace_id.
7
+ *
8
+ * Usage:
9
+ * const traceRunner = new TraceRunner(tracer, { "prompt1": "..." });
10
+ *
11
+ * await traceRunner.run(async () => {
12
+ * // ... tracing code ...
13
+ * });
14
+ *
15
+ * const traceData = traceRunner.record();
16
+ * const traceId = traceData.trace_id;
17
+ * const spans = traceData.spans;
18
+ */
19
+ class TraceRunner {
20
+ _tracer;
21
+ _cpm;
22
+ _candidatePrompts;
23
+ _traceId;
24
+ _contextEntered = false;
25
+ _alreadyRecorded = false;
26
+ constructor(tracer, candidatePrompts) {
27
+ this._tracer = tracer;
28
+ this._cpm = new candidate_prompt_manager_1.CandidatePromptManager();
29
+ this._candidatePrompts = candidatePrompts ?? null;
30
+ this._traceId = undefined;
31
+ this._contextEntered = false;
32
+ this._alreadyRecorded = false;
33
+ }
34
+ /**
35
+ * Run a callback with candidate prompts set in the async context.
36
+ *
37
+ * All spans created within this context will be part of the same trace.
38
+ * The trace_id is captured from spans created within the context and can be retrieved via record().
39
+ *
40
+ * @param callback - Function to run within the tracing context
41
+ * @returns Result of the callback
42
+ */
43
+ async run(callback) {
44
+ if (this._alreadyRecorded) {
45
+ throw new Error('Cannot enter context after record() has been called');
46
+ }
47
+ // Set up candidate prompts context
48
+ return this._cpm.run(this._candidatePrompts, async () => {
49
+ this._contextEntered = true;
50
+ try {
51
+ const result = await callback();
52
+ // Capture trace_id from tracer after execution completes
53
+ this._traceId = this._tracer.getTraceId();
54
+ return result;
55
+ }
56
+ finally {
57
+ // Reset state when context exits
58
+ this._contextEntered = false;
59
+ }
60
+ });
61
+ }
62
+ /**
63
+ * Export all spans and return the full trace with all child spans.
64
+ *
65
+ * @returns Dictionary with trace_id and spans
66
+ * @throws Error if called before context is entered or after already recorded
67
+ */
68
+ async record() {
69
+ if (this._alreadyRecorded) {
70
+ throw new Error('record() can only be called once per TraceRunner instance');
71
+ }
72
+ // Capture trace_id from tracer if we haven't captured it yet
73
+ if (this._traceId === undefined) {
74
+ this._traceId = this._tracer.getTraceId();
75
+ }
76
+ if (this._traceId === undefined) {
77
+ throw new Error('trace_id could not be captured. Ensure spans are created within the context.');
78
+ }
79
+ // Force flush all pending spans
80
+ await this._tracer.forceFlush();
81
+ // Get all spans for this trace
82
+ const allSpans = this._tracer.getSpansAsDicts();
83
+ // Filter spans to only include those matching the trace_id
84
+ const traceSpans = allSpans.filter((span) => span.trace_id === this._traceId);
85
+ this._alreadyRecorded = true;
86
+ return {
87
+ trace_id: this._traceId,
88
+ spans: traceSpans,
89
+ };
90
+ }
91
+ }
92
+ exports.TraceRunner = TraceRunner;
93
+ //# sourceMappingURL=trace-runner.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"trace-runner.js","sourceRoot":"","sources":["../src/trace-runner.ts"],"names":[],"mappings":";;;AACA,yEAAoE;AA4BpE;;;;;;;;;;;;;GAaG;AACH,MAAa,WAAW;IACL,OAAO,CAAS;IAChB,IAAI,CAAyB;IAC7B,iBAAiB,CAAgC;IAC1D,QAAQ,CAAqB;IAC7B,eAAe,GAAG,KAAK,CAAC;IACxB,gBAAgB,GAAG,KAAK,CAAC;IAEjC,YACE,MAAc,EACd,gBAAgD;QAEhD,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC;QACtB,IAAI,CAAC,IAAI,GAAG,IAAI,iDAAsB,EAAE,CAAC;QACzC,IAAI,CAAC,iBAAiB,GAAG,gBAAgB,IAAI,IAAI,CAAC;QAClD,IAAI,CAAC,QAAQ,GAAG,SAAS,CAAC;QAC1B,IAAI,CAAC,eAAe,GAAG,KAAK,CAAC;QAC7B,IAAI,CAAC,gBAAgB,GAAG,KAAK,CAAC;IAChC,CAAC;IAED;;;;;;;;OAQG;IACH,KAAK,CAAC,GAAG,CAAI,QAA8B;QACzC,IAAI,IAAI,CAAC,gBAAgB,EAAE,CAAC;YAC1B,MAAM,IAAI,KAAK,CAAC,qDAAqD,CAAC,CAAC;QACzE,CAAC;QAED,mCAAmC;QACnC,OAAO,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,iBAAiB,EAAE,KAAK,IAAI,EAAE;YACtD,IAAI,CAAC,eAAe,GAAG,IAAI,CAAC;YAE5B,IAAI,CAAC;gBACH,MAAM,MAAM,GAAG,MAAM,QAAQ,EAAE,CAAC;gBAChC,yDAAyD;gBACzD,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC,OAAO,CAAC,UAAU,EAAE,CAAC;gBAC1C,OAAO,MAAM,CAAC;YAChB,CAAC;oBAAS,CAAC;gBACT,iCAAiC;gBACjC,IAAI,CAAC,eAAe,GAAG,KAAK,CAAC;YAC/B,CAAC;QACH,CAAC,CAAC,CAAC;IACL,CAAC;IAED;;;;;OAKG;IACH,KAAK,CAAC,MAAM;QACV,IAAI,IAAI,CAAC,gBAAgB,EAAE,CAAC;YAC1B,MAAM,IAAI,KAAK,CACb,2DAA2D,CAC5D,CAAC;QACJ,CAAC;QAED,6DAA6D;QAC7D,IAAI,IAAI,CAAC,QAAQ,KAAK,SAAS,EAAE,CAAC;YAChC,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC,OAAO,CAAC,UAAU,EAAE,CAAC;QAC5C,CAAC;QAED,IAAI,IAAI,CAAC,QAAQ,KAAK,SAAS,EAAE,CAAC;YAChC,MAAM,IAAI,KAAK,CACb,8EAA8E,CAC/E,CAAC;QACJ,CAAC;QAED,gCAAgC;QAChC,MAAM,IAAI,CAAC,OAAO,CAAC,UAAU,EAAE,CAAC;QAEhC,+BAA+B;QAC/B,MAAM,QAAQ,GAAG,IAAI,CAAC,OAAO,CAAC,eAAe,EAAE,CAAC;QAChD,2DAA2D;QAC3D,MAAM,UAAU,GAAG,QAAQ,CAAC,MAAM,CAChC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,KAAK,IAAI,CAAC,QAAQ,CAC1C,CAAC;QAEF,IAAI,CAAC,gBAAgB,GAAG,IAAI,CAAC;QAE7B,OAAO;YACL,QAAQ,EAAE,IAAI,CAAC,QAAQ;YACvB,KAAK,EAAE,UAAU;SAClB,CAAC;IACJ,CAAC;CACF;AA3FD,kCA2FC"}
@@ -0,0 +1,147 @@
1
+ import { type Span } from "@opentelemetry/api";
2
+ import type { SpanExporter } from "@opentelemetry/sdk-trace-base";
3
+ import { ReadableSpan } from "@opentelemetry/sdk-trace-base";
4
+ import { CandidatePromptManager } from "./candidate-prompt-manager";
5
+ import { MemorySpanExporter } from "./exporter";
6
+ type AnyFunction = (...args: unknown[]) => unknown;
7
+ /**
8
+ * Span type for tracing different kinds of operations.
9
+ */
10
+ export declare enum SpanType {
11
+ AGENT = "agent",
12
+ NODE = "node",
13
+ TOOL = "tool"
14
+ }
15
+ /**
16
+ * OpenTelemetry-based tracer that mimics agentbridge API.
17
+ */
18
+ export declare class Tracer {
19
+ private readonly _tracer;
20
+ private readonly _cpm;
21
+ private readonly _memoryExporter;
22
+ private readonly _currentPromptSpan;
23
+ private readonly _llmStartTime;
24
+ private readonly _traceId;
25
+ constructor(serviceName: string, exporter?: SpanExporter, candidatePromptManager?: CandidatePromptManager);
26
+ /**
27
+ * Wraps a function to trace it as a span.
28
+ *
29
+ * @param spanType - Type of span (SpanType.AGENT, SpanType.NODE, or SpanType.TOOL)
30
+ * @param func - Function to wrap
31
+ * @returns Wrapped function
32
+ */
33
+ wrap<T extends AnyFunction>(spanType: SpanType, func: T): T;
34
+ /**
35
+ * Context manager for tracing prompt rendering and LLM calls.
36
+ *
37
+ * Usage:
38
+ * const renderedPrompt = await tracer.prompt(
39
+ * "translation",
40
+ * promptTemplate,
41
+ * { premises: [...], conclusion: "..." }
42
+ * );
43
+ * const result = await llm.invoke([{ role: "user", content: renderedPrompt }]);
44
+ * tracer.addLlmOutput(result.content);
45
+ *
46
+ * @param promptName - Name of the prompt
47
+ * @param promptTemplate - Template string (Nunjucks format)
48
+ * @param inputVars - Variables to render into the template
49
+ * @returns Promise that resolves to the rendered prompt
50
+ */
51
+ prompt(promptName: string, promptTemplate: string, inputVars: Record<string, unknown>): Promise<string>;
52
+ /**
53
+ * Start a prompt span and return a context manager-like object.
54
+ *
55
+ * Usage:
56
+ * const promptCtx = tracer.startPrompt("translation", template, vars);
57
+ * const renderedPrompt = promptCtx.renderedPrompt;
58
+ * // ... use renderedPrompt ...
59
+ * tracer.addLlmOutput(result.content);
60
+ * promptCtx.end();
61
+ *
62
+ * @param promptName - Name of the prompt
63
+ * @param promptTemplate - Template string (Nunjucks format)
64
+ * @param inputVars - Variables to render into the template
65
+ * @returns Object with renderedPrompt and end() method
66
+ */
67
+ startPrompt(promptName: string, promptTemplate: string, inputVars: Record<string, unknown>): {
68
+ renderedPrompt: string;
69
+ span: Span;
70
+ end: () => void;
71
+ };
72
+ /**
73
+ * Add LLM output metadata to the current prompt span.
74
+ *
75
+ * Usage:
76
+ * tracer.addLLMOutput(result.content);
77
+ * // or with more metadata:
78
+ * tracer.addLlmOutput(
79
+ * result.content,
80
+ * "gpt-4",
81
+ * { prompt_tokens: 100, completion_tokens: 50 }
82
+ * );
83
+ *
84
+ * @param output - LLM output text
85
+ * @param model - Optional model name
86
+ * @param usage - Optional token usage information
87
+ */
88
+ addLLMOutput(output: string, model?: string, usage?: {
89
+ prompt_tokens?: number;
90
+ completion_tokens?: number;
91
+ total_tokens?: number;
92
+ }): void;
93
+ /**
94
+ * Get the current active span.
95
+ *
96
+ * @returns Current span or undefined
97
+ */
98
+ getCurrentSpan(): Span | undefined;
99
+ /**
100
+ * Add metadata to the current span.
101
+ *
102
+ * Usage:
103
+ * tracer.addMetadata("decision", "True");
104
+ *
105
+ * @param key - Attribute key
106
+ * @param value - Attribute value
107
+ */
108
+ addMetadata(key: string, value: unknown): void;
109
+ /**
110
+ * Add an event to the current span.
111
+ *
112
+ * Usage:
113
+ * tracer.addEvent("processing_started", { item_count: 10 });
114
+ *
115
+ * @param eventName - Name of the event
116
+ * @param attributes - Optional event attributes
117
+ */
118
+ addEvent(eventName: string, attributes?: Record<string, string | number | boolean>): void;
119
+ /**
120
+ * Get the trace_id from the current context.
121
+ *
122
+ * @returns trace_id as a 32-character hexadecimal string, or undefined if not available
123
+ */
124
+ getTraceId(): string | undefined;
125
+ /**
126
+ * Helper to format trace ID as 32-character hex string.
127
+ */
128
+ private _formatTraceId;
129
+ /**
130
+ * Force flush all pending spans.
131
+ */
132
+ forceFlush(): Promise<void>;
133
+ /**
134
+ * Get all collected spans from memory.
135
+ *
136
+ * @returns List of ReadableSpan objects for all spans collected so far
137
+ */
138
+ getSpans(): ReadableSpan[];
139
+ /**
140
+ * Get all collected spans as dictionaries.
141
+ *
142
+ * @returns List of span dictionaries with all span data
143
+ */
144
+ getSpansAsDicts(): ReturnType<MemorySpanExporter["getSpansAsDicts"]>;
145
+ }
146
+ export {};
147
+ //# sourceMappingURL=tracer.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tracer.d.ts","sourceRoot":"","sources":["../src/tracer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAW,KAAK,IAAI,EAAyB,MAAM,oBAAoB,CAAC;AAE/E,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAClE,OAAO,EAGL,YAAY,EACb,MAAM,+BAA+B,CAAC;AAIvC,OAAO,EAAE,sBAAsB,EAAE,MAAM,4BAA4B,CAAC;AACpE,OAAO,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAEhD,KAAK,WAAW,GAAG,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,KAAK,OAAO,CAAC;AAEnD;;GAEG;AACH,oBAAY,QAAQ;IAClB,KAAK,UAAU;IACf,IAAI,SAAS;IACb,IAAI,SAAS;CACd;AAED;;GAEG;AACH,qBAAa,MAAM;IACjB,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAqC;IAC7D,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAyB;IAC9C,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAqB;IACrD,OAAO,CAAC,QAAQ,CAAC,kBAAkB,CAA2C;IAC9E,OAAO,CAAC,QAAQ,CAAC,aAAa,CAA6C;IAC3E,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAgD;gBAGvE,WAAW,EAAE,MAAM,EACnB,QAAQ,CAAC,EAAE,YAAY,EACvB,sBAAsB,CAAC,EAAE,sBAAsB;IAiCjD;;;;;;OAMG;IACH,IAAI,CAAC,CAAC,SAAS,WAAW,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC,GAAG,CAAC;IA+E3D;;;;;;;;;;;;;;;;OAgBG;IACG,MAAM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,379 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.Tracer = exports.SpanType = void 0;
7
+ const api_1 = require("@opentelemetry/api");
8
+ const resources_1 = require("@opentelemetry/resources");
9
+ const sdk_trace_base_1 = require("@opentelemetry/sdk-trace-base");
10
+ const node_async_hooks_1 = require("node:async_hooks");
11
+ const nunjucks_1 = __importDefault(require("nunjucks"));
12
+ const candidate_prompt_manager_1 = require("./candidate-prompt-manager");
13
+ const exporter_1 = require("./exporter");
14
+ /**
15
+ * Span type for tracing different kinds of operations.
16
+ */
17
+ var SpanType;
18
+ (function (SpanType) {
19
+ SpanType["AGENT"] = "agent";
20
+ SpanType["NODE"] = "node";
21
+ SpanType["TOOL"] = "tool";
22
+ })(SpanType || (exports.SpanType = SpanType = {}));
23
+ /**
24
+ * OpenTelemetry-based tracer that mimics agentbridge API.
25
+ */
26
+ class Tracer {
27
+ _tracer;
28
+ _cpm;
29
+ _memoryExporter;
30
+ _currentPromptSpan;
31
+ _llmStartTime;
32
+ _traceId;
33
+ constructor(serviceName, exporter, candidatePromptManager) {
34
+ const resource = resources_1.Resource.default().merge(new resources_1.Resource({
35
+ "service.name": serviceName,
36
+ }));
37
+ // Create memory exporter to collect spans (always used)
38
+ this._memoryExporter = new exporter_1.MemorySpanExporter();
39
+ // Prepare span processors
40
+ const spanProcessors = [new sdk_trace_base_1.BatchSpanProcessor(this._memoryExporter)];
41
+ if (exporter) {
42
+ spanProcessors.push(new sdk_trace_base_1.BatchSpanProcessor(exporter));
43
+ }
44
+ const provider = new sdk_trace_base_1.BasicTracerProvider({
45
+ resource,
46
+ spanProcessors,
47
+ });
48
+ api_1.trace.setGlobalTracerProvider(provider);
49
+ this._tracer = api_1.trace.getTracer(serviceName);
50
+ this._cpm = candidatePromptManager ?? new candidate_prompt_manager_1.CandidatePromptManager();
51
+ // Context-local state for prompt spans and timing
52
+ this._currentPromptSpan = new node_async_hooks_1.AsyncLocalStorage();
53
+ this._llmStartTime = new node_async_hooks_1.AsyncLocalStorage();
54
+ this._traceId = new node_async_hooks_1.AsyncLocalStorage();
55
+ }
56
+ /**
57
+ * Wraps a function to trace it as a span.
58
+ *
59
+ * @param spanType - Type of span (SpanType.AGENT, SpanType.NODE, or SpanType.TOOL)
60
+ * @param func - Function to wrap
61
+ * @returns Wrapped function
62
+ */
63
+ wrap(spanType, func) {
64
+ const wrapped = ((...args) => {
65
+ const span = this._tracer.startSpan(func.name);
66
+ const activeContext = api_1.trace.setSpan(api_1.context.active(), span);
67
+ // Capture trace_id from span context
68
+ const spanContext = span.spanContext();
69
+ if (spanContext.traceFlags !== undefined) {
70
+ const traceId = this._formatTraceId(spanContext.traceId);
71
+ // Store trace ID in async context for later retrieval
72
+ const currentStore = this._traceId.getStore();
73
+ if (!currentStore) {
74
+ this._traceId.enterWith({ traceId });
75
+ }
76
+ }
77
+ span.setAttribute("span.type", spanType);
78
+ span.setAttribute("function.name", func.name);
79
+ // Add input metadata for agent spans
80
+ const inputArgs = args.slice(0);
81
+ try {
82
+ span.setAttribute("function.input", JSON.stringify(inputArgs));
83
+ }
84
+ catch {
85
+ // Skip if args can't be serialized
86
+ }
87
+ return api_1.context.with(activeContext, () => {
88
+ try {
89
+ const result = func(...args);
90
+ if (result instanceof Promise) {
91
+ return result
92
+ .then((res) => {
93
+ try {
94
+ span.setAttribute("function.result", JSON.stringify(res));
95
+ }
96
+ catch {
97
+ // Skip if result can't be serialized
98
+ }
99
+ span.setStatus({ code: api_1.SpanStatusCode.OK });
100
+ span.end();
101
+ return res;
102
+ })
103
+ .catch((error) => {
104
+ span.setStatus({
105
+ code: api_1.SpanStatusCode.ERROR,
106
+ message: error.message,
107
+ });
108
+ span.recordException(error);
109
+ span.end();
110
+ throw error;
111
+ });
112
+ }
113
+ try {
114
+ span.setAttribute("function.result", JSON.stringify(result));
115
+ }
116
+ catch {
117
+ // Skip if result can't be serialized
118
+ }
119
+ span.setStatus({ code: api_1.SpanStatusCode.OK });
120
+ span.end();
121
+ return result;
122
+ }
123
+ catch (error) {
124
+ const err = error instanceof Error ? error : new Error(String(error));
125
+ span.setStatus({
126
+ code: api_1.SpanStatusCode.ERROR,
127
+ message: err.message,
128
+ });
129
+ span.recordException(err);
130
+ span.end();
131
+ throw error;
132
+ }
133
+ });
134
+ });
135
+ Object.defineProperty(wrapped, "name", { value: func.name });
136
+ return wrapped;
137
+ }
138
+ /**
139
+ * Context manager for tracing prompt rendering and LLM calls.
140
+ *
141
+ * Usage:
142
+ * const renderedPrompt = await tracer.prompt(
143
+ * "translation",
144
+ * promptTemplate,
145
+ * { premises: [...], conclusion: "..." }
146
+ * );
147
+ * const result = await llm.invoke([{ role: "user", content: renderedPrompt }]);
148
+ * tracer.addLlmOutput(result.content);
149
+ *
150
+ * @param promptName - Name of the prompt
151
+ * @param promptTemplate - Template string (Nunjucks format)
152
+ * @param inputVars - Variables to render into the template
153
+ * @returns Promise that resolves to the rendered prompt
154
+ */
155
+ async prompt(promptName, promptTemplate, inputVars) {
156
+ const span = this._tracer.startSpan(promptName);
157
+ const activeContext = api_1.trace.setSpan(api_1.context.active(), span);
158
+ // Capture trace_id from span context and store in async context
159
+ const spanContext = span.spanContext();
160
+ if (spanContext.traceFlags !== undefined) {
161
+ const traceId = this._formatTraceId(spanContext.traceId);
162
+ // Store trace ID in async context for later retrieval
163
+ const currentStore = this._traceId.getStore();
164
+ if (!currentStore) {
165
+ this._traceId.enterWith({ traceId });
166
+ }
167
+ }
168
+ span.setAttribute("span.type", "prompt");
169
+ span.setAttribute("prompt.name", promptName);
170
+ span.setAttribute("prompt.template", promptTemplate);
171
+ span.setAttribute("prompt.input_vars", JSON.stringify(inputVars));
172
+ // Select effective template (apply candidate override if present) and render
173
+ const [effectiveTemplate, overrideApplied] = this._cpm.getEffectiveTemplate(promptName, promptTemplate);
174
+ span.setAttribute("prompt.override_applied", overrideApplied);
175
+ const renderedPrompt = nunjucks_1.default.renderString(effectiveTemplate, inputVars);
176
+ span.setAttribute("prompt.rendered_length", renderedPrompt.length);
177
+ span.addEvent("prompt_rendered");
178
+ const startTime = Date.now();
179
+ // Store span and start time in context for add_llm_output to use
180
+ // Use run() to ensure these are available in the async context
181
+ return this._currentPromptSpan.run({ span }, () => {
182
+ return this._llmStartTime.run({ time: startTime }, () => {
183
+ // Return the rendered prompt with active context
184
+ // The span and time will be available when addLlmOutput is called
185
+ // as long as it's called within this async context
186
+ return api_1.context.with(activeContext, async () => {
187
+ return renderedPrompt;
188
+ });
189
+ });
190
+ });
191
+ }
192
+ /**
193
+ * Start a prompt span and return a context manager-like object.
194
+ *
195
+ * Usage:
196
+ * const promptCtx = tracer.startPrompt("translation", template, vars);
197
+ * const renderedPrompt = promptCtx.renderedPrompt;
198
+ * // ... use renderedPrompt ...
199
+ * tracer.addLlmOutput(result.content);
200
+ * promptCtx.end();
201
+ *
202
+ * @param promptName - Name of the prompt
203
+ * @param promptTemplate - Template string (Nunjucks format)
204
+ * @param inputVars - Variables to render into the template
205
+ * @returns Object with renderedPrompt and end() method
206
+ */
207
+ startPrompt(promptName, promptTemplate, inputVars) {
208
+ const span = this._tracer.startSpan(promptName);
209
+ const activeContext = api_1.trace.setSpan(api_1.context.active(), span);
210
+ // Capture trace_id from span context and store in async context
211
+ const spanContext = span.spanContext();
212
+ if (spanContext.traceFlags !== undefined) {
213
+ const traceId = this._formatTraceId(spanContext.traceId);
214
+ // Store trace ID in async context for later retrieval
215
+ const currentStore = this._traceId.getStore();
216
+ if (!currentStore) {
217
+ this._traceId.enterWith({ traceId });
218
+ }
219
+ }
220
+ span.setAttribute("span.type", "prompt");
221
+ span.setAttribute("prompt.name", promptName);
222
+ span.setAttribute("prompt.template", promptTemplate);
223
+ span.setAttribute("prompt.input_vars", JSON.stringify(inputVars));
224
+ // Select effective template (apply candidate override if present) and render
225
+ const [effectiveTemplate, overrideApplied] = this._cpm.getEffectiveTemplate(promptName, promptTemplate);
226
+ span.setAttribute("prompt.override_applied", overrideApplied);
227
+ const renderedPrompt = nunjucks_1.default.renderString(effectiveTemplate, inputVars);
228
+ span.setAttribute("prompt.rendered_length", renderedPrompt.length);
229
+ span.addEvent("prompt_rendered");
230
+ const startTime = Date.now();
231
+ // Store span and start time in context for add_llm_output to use
232
+ // Note: These will only be available if addLlmOutput is called
233
+ // within the same async context chain
234
+ this._currentPromptSpan.enterWith({ span });
235
+ this._llmStartTime.enterWith({ time: startTime });
236
+ return {
237
+ renderedPrompt,
238
+ span,
239
+ end: () => {
240
+ span.end();
241
+ },
242
+ };
243
+ }
244
+ /**
245
+ * Add LLM output metadata to the current prompt span.
246
+ *
247
+ * Usage:
248
+ * tracer.addLLMOutput(result.content);
249
+ * // or with more metadata:
250
+ * tracer.addLlmOutput(
251
+ * result.content,
252
+ * "gpt-4",
253
+ * { prompt_tokens: 100, completion_tokens: 50 }
254
+ * );
255
+ *
256
+ * @param output - LLM output text
257
+ * @param model - Optional model name
258
+ * @param usage - Optional token usage information
259
+ */
260
+ addLLMOutput(output, model, usage) {
261
+ const store = this._currentPromptSpan.getStore();
262
+ const timeStore = this._llmStartTime.getStore();
263
+ const span = store?.span ?? null;
264
+ const startTime = timeStore?.time ?? null;
265
+ if (!span || startTime === null) {
266
+ return;
267
+ }
268
+ const durationMs = Date.now() - startTime;
269
+ span.setAttribute("gen_ai.response", output.slice(0, 1000)); // Truncate
270
+ span.setAttribute("gen_ai.response.length", output.length);
271
+ span.setAttribute("llm.duration_ms", durationMs);
272
+ if (model) {
273
+ span.setAttribute("gen_ai.request.model", model);
274
+ }
275
+ if (usage) {
276
+ span.setAttribute("gen_ai.usage.prompt_tokens", usage.prompt_tokens ?? 0);
277
+ span.setAttribute("gen_ai.usage.completion_tokens", usage.completion_tokens ?? 0);
278
+ span.setAttribute("gen_ai.usage.total_tokens", usage.total_tokens ?? 0);
279
+ }
280
+ span.addEvent("llm_call_completed", {
281
+ duration_ms: durationMs,
282
+ response_length: output.length,
283
+ });
284
+ span.end();
285
+ }
286
+ /**
287
+ * Get the current active span.
288
+ *
289
+ * @returns Current span or undefined
290
+ */
291
+ getCurrentSpan() {
292
+ const span = api_1.trace.getActiveSpan();
293
+ return span;
294
+ }
295
+ /**
296
+ * Add metadata to the current span.
297
+ *
298
+ * Usage:
299
+ * tracer.addMetadata("decision", "True");
300
+ *
301
+ * @param key - Attribute key
302
+ * @param value - Attribute value
303
+ */
304
+ addMetadata(key, value) {
305
+ const span = this.getCurrentSpan();
306
+ if (span) {
307
+ if (typeof value === "string" ||
308
+ typeof value === "number" ||
309
+ typeof value === "boolean") {
310
+ span.setAttribute(key, value);
311
+ }
312
+ else if (Array.isArray(value) || typeof value === "object") {
313
+ const serialized = JSON.stringify(value);
314
+ span.setAttribute(key, serialized.slice(0, 1000));
315
+ }
316
+ else {
317
+ span.setAttribute(key, String(value).slice(0, 1000));
318
+ }
319
+ }
320
+ }
321
+ /**
322
+ * Add an event to the current span.
323
+ *
324
+ * Usage:
325
+ * tracer.addEvent("processing_started", { item_count: 10 });
326
+ *
327
+ * @param eventName - Name of the event
328
+ * @param attributes - Optional event attributes
329
+ */
330
+ addEvent(eventName, attributes) {
331
+ const span = this.getCurrentSpan();
332
+ if (span) {
333
+ span.addEvent(eventName, attributes);
334
+ }
335
+ }
336
+ /**
337
+ * Get the trace_id from the current context.
338
+ *
339
+ * @returns trace_id as a 32-character hexadecimal string, or undefined if not available
340
+ */
341
+ getTraceId() {
342
+ const store = this._traceId.getStore();
343
+ return store?.traceId;
344
+ }
345
+ /**
346
+ * Helper to format trace ID as 32-character hex string.
347
+ */
348
+ _formatTraceId(traceId) {
349
+ // Trace ID from OpenTelemetry is already a hex string, but ensure it's 32 chars
350
+ return traceId.padStart(32, "0").slice(0, 32);
351
+ }
352
+ /**
353
+ * Force flush all pending spans.
354
+ */
355
+ async forceFlush() {
356
+ const provider = api_1.trace.getTracerProvider();
357
+ if ("forceFlush" in provider) {
358
+ await provider.forceFlush();
359
+ }
360
+ }
361
+ /**
362
+ * Get all collected spans from memory.
363
+ *
364
+ * @returns List of ReadableSpan objects for all spans collected so far
365
+ */
366
+ getSpans() {
367
+ return this._memoryExporter.getSpans();
368
+ }
369
+ /**
370
+ * Get all collected spans as dictionaries.
371
+ *
372
+ * @returns List of span dictionaries with all span data
373
+ */
374
+ getSpansAsDicts() {
375
+ return this._memoryExporter.getSpansAsDicts();
376
+ }
377
+ }
378
+ exports.Tracer = Tracer;
379
+ //# sourceMappingURL=tracer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tracer.js","sourceRoot":"","sources":["../src/tracer.ts"],"names":[],"mappings":";;;;;;AAAA,4CAA+E;AAC/E,wDAAoD;AAEpD,kEAIuC;AACvC,uDAAqD;AACrD,wDAAgC;AAEhC,yEAAoE;AACpE,yCAAgD;AAIhD;;GAEG;AACH,IAAY,QAIX;AAJD,WAAY,QAAQ;IAClB,2BAAe,CAAA;IACf,yBAAa,CAAA;IACb,yBAAa,CAAA;AACf,CAAC,EAJW,QAAQ,wBAAR,QAAQ,QAInB;AAED;;GAEG;AACH,MAAa,MAAM;IACA,OAAO,CAAqC;IAC5C,IAAI,CAAyB;IAC7B,eAAe,CAAqB;IACpC,kBAAkB,CAA2C;IAC7D,aAAa,CAA6C;IAC1D,QAAQ,CAAgD;IAEzE,YACE,WAAmB,EACnB,QAAuB,EACvB,sBAA+C;QAE/C,MAAM,QAAQ,GAAG,oBAAQ,CAAC,OAAO,EAAE,CAAC,KAAK,CACvC,IAAI,oBAAQ,CAAC;YACX,cAAc,EAAE,WAAW;SAC5B,CAAC,CACH,CAAC;QAEF,wDAAwD;QACxD,IAAI,CAAC,eAAe,GAAG,IAAI,6BAAkB,EAAE,CAAC;QAEhD,0BAA0B;QAC1B,MAAM,cAAc,GAAG,CAAC,IAAI,mCAAkB,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC,CAAC;QACtE,IAAI,QAAQ,EAAE,CAAC;YACb,cAAc,CAAC,IAAI,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IACH,KAAK,CAAC,UAAU;QACd,MAAM,QAAQ,GAAG,WAAK,CAAC,iBAAiB,EAAE,CAAC;QAC3C,IAAI,YAAY,IAAI,QAAQ,EAAE,CAAC;YAC7B,MAAO,QAAgD,CAAC,UAAU,EAAE,CAAC;QACvE,CAAC;IACH,CAAC;IAED;;;;OAIG;IACH,QAAQ;QACN,OAAO,IAAI,CAAC,eAAe,CAAC,QAAQ,EAAE,CAAC;IACzC,CAAC;IAED;;;;OAIG;IACH,eAAe;QACb,OAAO,IAAI,CAAC,eAAe,CAAC,eAAe,EAAE,CAAC;IAChD,CAAC;CACF;AAjbD,wBAibC"}
package/package.json ADDED
@@ -0,0 +1,53 @@
1
+ {
2
+ "name": "@uselemma/tracing",
3
+ "version": "0.1.0",
4
+ "description": "OpenTelemetry-based tracing module for Lemma",
5
+ "license": "MIT",
6
+ "author": "Lemma",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/uselemma/tracing"
10
+ },
11
+ "homepage": "https://github.com/uselemma/tracing#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/uselemma/tracing/issues"
14
+ },
15
+ "keywords": [
16
+ "opentelemetry",
17
+ "tracing",
18
+ "observability",
19
+ "monitoring",
20
+ "llm",
21
+ "instrumentation"
22
+ ],
23
+ "main": "./dist/index.js",
24
+ "types": "./dist/index.d.ts",
25
+ "exports": {
26
+ ".": "./dist/index.js"
27
+ },
28
+ "files": [
29
+ "dist",
30
+ "README.md",
31
+ "LICENSE"
32
+ ],
33
+ "dependencies": {
34
+ "@opentelemetry/api": "^1.9.0",
35
+ "@opentelemetry/core": "^2.2.0",
36
+ "@opentelemetry/resources": "^1.27.0",
37
+ "@opentelemetry/sdk-trace-base": "^1.27.0",
38
+ "nunjucks": "^3.2.4"
39
+ },
40
+ "devDependencies": {
41
+ "@trivago/prettier-plugin-sort-imports": "^5.2.2",
42
+ "@types/node": "^22.18.8",
43
+ "@types/nunjucks": "^3.2.6",
44
+ "prettier": "^3.6.2",
45
+ "prettier-plugin-tailwindcss": "^0.6.14",
46
+ "typescript": "^5.9.3"
47
+ },
48
+ "scripts": {
49
+ "type-check": "tsc --noEmit",
50
+ "build": "tsc",
51
+ "clean": "rm -rf dist"
52
+ }
53
+ }