@prefactor/sdk 0.1.3 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/README.md +49 -259
  2. package/dist/index.cjs +16 -1253
  3. package/dist/index.cjs.map +4 -17
  4. package/dist/index.d.ts +2 -81
  5. package/dist/index.d.ts.map +1 -1
  6. package/dist/index.js +4 -1255
  7. package/dist/index.js.map +4 -17
  8. package/package.json +6 -22
  9. package/LICENSE +0 -14
  10. package/dist/LICENSE +0 -14
  11. package/dist/README.md +0 -313
  12. package/dist/config.d.ts +0 -259
  13. package/dist/config.d.ts.map +0 -1
  14. package/dist/config.js +0 -110
  15. package/dist/config.js.map +0 -1
  16. package/dist/instrumentation/langchain/metadata-extractor.d.ts +0 -20
  17. package/dist/instrumentation/langchain/metadata-extractor.d.ts.map +0 -1
  18. package/dist/instrumentation/langchain/metadata-extractor.js +0 -54
  19. package/dist/instrumentation/langchain/metadata-extractor.js.map +0 -1
  20. package/dist/instrumentation/langchain/middleware.d.ts +0 -84
  21. package/dist/instrumentation/langchain/middleware.d.ts.map +0 -1
  22. package/dist/instrumentation/langchain/middleware.js +0 -181
  23. package/dist/instrumentation/langchain/middleware.js.map +0 -1
  24. package/dist/package.json +0 -56
  25. package/dist/tracing/context.d.ts +0 -53
  26. package/dist/tracing/context.d.ts.map +0 -1
  27. package/dist/tracing/context.js +0 -65
  28. package/dist/tracing/context.js.map +0 -1
  29. package/dist/tracing/span.d.ts +0 -68
  30. package/dist/tracing/span.d.ts.map +0 -1
  31. package/dist/tracing/span.js +0 -21
  32. package/dist/tracing/span.js.map +0 -1
  33. package/dist/tracing/tracer.d.ts +0 -100
  34. package/dist/tracing/tracer.d.ts.map +0 -1
  35. package/dist/tracing/tracer.js +0 -151
  36. package/dist/tracing/tracer.js.map +0 -1
  37. package/dist/transport/base.d.ts +0 -38
  38. package/dist/transport/base.d.ts.map +0 -1
  39. package/dist/transport/base.js +0 -2
  40. package/dist/transport/base.js.map +0 -1
  41. package/dist/transport/http.d.ts +0 -90
  42. package/dist/transport/http.d.ts.map +0 -1
  43. package/dist/transport/http.js +0 -399
  44. package/dist/transport/http.js.map +0 -1
  45. package/dist/transport/stdio.d.ts +0 -48
  46. package/dist/transport/stdio.d.ts.map +0 -1
  47. package/dist/transport/stdio.js +0 -71
  48. package/dist/transport/stdio.js.map +0 -1
  49. package/dist/utils/logging.d.ts +0 -29
  50. package/dist/utils/logging.d.ts.map +0 -1
  51. package/dist/utils/logging.js +0 -71
  52. package/dist/utils/logging.js.map +0 -1
  53. package/dist/utils/serialization.d.ts +0 -24
  54. package/dist/utils/serialization.d.ts.map +0 -1
  55. package/dist/utils/serialization.js +0 -60
  56. package/dist/utils/serialization.js.map +0 -1
@@ -1,181 +0,0 @@
1
- import { SpanContext } from '../../tracing/context.js';
2
- import { SpanType } from '../../tracing/span.js';
3
- import { extractTokenUsage } from './metadata-extractor.js';
4
- /**
5
- * Prefactor middleware for LangChain.js agents.
6
- *
7
- * This middleware automatically traces LLM calls, tool executions, and agent workflows.
8
- * It integrates with LangChain.js middleware API to provide transparent instrumentation.
9
- *
10
- * Features:
11
- * - Automatic parent-child span relationships via context propagation
12
- * - Token usage extraction for LLM calls
13
- * - Error tracking and debugging
14
- * - Zero-overhead instrumentation (graceful failure)
15
- *
16
- * @example
17
- * ```typescript
18
- * import { init } from '@prefactor/sdk';
19
- * import { createReactAgent } from '@langchain/langgraph/prebuilt';
20
- *
21
- * const middleware = init();
22
- * const agent = createReactAgent({
23
- * llm: model,
24
- * tools: [myTool],
25
- * middleware: [middleware],
26
- * });
27
- * ```
28
- */
29
- export class PrefactorMiddleware {
30
- tracer;
31
- rootSpan = null;
32
- constructor(tracer) {
33
- this.tracer = tracer;
34
- }
35
- /**
36
- * Called before agent execution starts
37
- *
38
- * @param state - Agent state containing messages
39
- */
40
- // biome-ignore lint/suspicious/noExplicitAny: LangChain state can be any structure
41
- async beforeAgent(state) {
42
- const parentSpan = SpanContext.getCurrent();
43
- const messages = state?.messages ?? [];
44
- this.tracer.startAgentInstance();
45
- const span = this.tracer.startSpan({
46
- name: 'agent',
47
- spanType: SpanType.AGENT,
48
- inputs: { messages: messages.slice(-3).map((m) => String(m)) },
49
- parentSpanId: parentSpan?.spanId,
50
- traceId: parentSpan?.traceId,
51
- });
52
- this.rootSpan = span;
53
- }
54
- /**
55
- * Called after agent execution completes
56
- *
57
- * @param state - Agent state containing messages
58
- */
59
- // biome-ignore lint/suspicious/noExplicitAny: LangChain state can be any structure
60
- async afterAgent(state) {
61
- if (!this.rootSpan) {
62
- return;
63
- }
64
- const messages = state?.messages ?? [];
65
- this.tracer.endSpan(this.rootSpan, {
66
- outputs: { messages: messages.slice(-3).map((m) => String(m)) },
67
- });
68
- this.tracer.finishAgentInstance();
69
- SpanContext.clear();
70
- this.rootSpan = null;
71
- }
72
- /**
73
- * Wrap a model call to trace LLM invocations
74
- *
75
- * @param request - Model invocation request
76
- * @param handler - The actual model call function
77
- * @returns Promise resolving to the model response
78
- */
79
- // biome-ignore lint/suspicious/noExplicitAny: LangChain request/handler types are dynamic
80
- async wrapModelCall(request, handler) {
81
- const parentSpan = SpanContext.getCurrent();
82
- const span = this.tracer.startSpan({
83
- name: this.extractModelName(request),
84
- spanType: SpanType.LLM,
85
- inputs: this.extractModelInputs(request),
86
- parentSpanId: parentSpan?.spanId,
87
- traceId: parentSpan?.traceId,
88
- });
89
- try {
90
- // CRITICAL: Wrap handler in context so child operations see this span
91
- const response = await SpanContext.runAsync(span, async () => {
92
- return handler(request);
93
- });
94
- const outputs = this.extractModelOutputs(response);
95
- const tokenUsage = extractTokenUsage(response);
96
- this.tracer.endSpan(span, { outputs, tokenUsage: tokenUsage ?? undefined });
97
- return response;
98
- }
99
- catch (error) {
100
- this.tracer.endSpan(span, { error: error });
101
- throw error;
102
- }
103
- }
104
- /**
105
- * Wrap a tool call to trace tool executions
106
- *
107
- * @param request - Tool invocation request
108
- * @param handler - The actual tool call function
109
- * @returns Promise resolving to the tool response
110
- */
111
- // biome-ignore lint/suspicious/noExplicitAny: LangChain request/handler types are dynamic
112
- async wrapToolCall(request, handler) {
113
- const parentSpan = SpanContext.getCurrent();
114
- const span = this.tracer.startSpan({
115
- name: this.extractToolName(request),
116
- spanType: SpanType.TOOL,
117
- inputs: this.extractToolInputs(request),
118
- parentSpanId: parentSpan?.spanId,
119
- traceId: parentSpan?.traceId,
120
- });
121
- try {
122
- // CRITICAL: Wrap handler in context so child operations see this span
123
- const response = await SpanContext.runAsync(span, async () => {
124
- return handler(request);
125
- });
126
- this.tracer.endSpan(span, {
127
- outputs: this.extractToolOutputs(response),
128
- });
129
- return response;
130
- }
131
- catch (error) {
132
- this.tracer.endSpan(span, { error: error });
133
- throw error;
134
- }
135
- }
136
- /**
137
- * Extract model name from request
138
- */
139
- // biome-ignore lint/suspicious/noExplicitAny: LangChain request structure is dynamic
140
- extractModelName(request) {
141
- return request?.model ?? request?.modelName ?? 'unknown';
142
- }
143
- /**
144
- * Extract model inputs from request
145
- */
146
- // biome-ignore lint/suspicious/noExplicitAny: LangChain request structure is dynamic
147
- extractModelInputs(request) {
148
- const messages = request?.messages ?? [];
149
- return { messages: messages.slice(-3).map((m) => String(m)) };
150
- }
151
- /**
152
- * Extract model outputs from response
153
- */
154
- // biome-ignore lint/suspicious/noExplicitAny: LangChain response structure is dynamic
155
- extractModelOutputs(response) {
156
- const content = response?.content ?? response?.text ?? '';
157
- return { content: String(content) };
158
- }
159
- /**
160
- * Extract tool name from request
161
- */
162
- // biome-ignore lint/suspicious/noExplicitAny: LangChain request structure is dynamic
163
- extractToolName(request) {
164
- return request?.name ?? request?.tool ?? 'unknown';
165
- }
166
- /**
167
- * Extract tool inputs from request
168
- */
169
- // biome-ignore lint/suspicious/noExplicitAny: LangChain request structure is dynamic
170
- extractToolInputs(request) {
171
- return { input: request?.input ?? request?.args ?? {} };
172
- }
173
- /**
174
- * Extract tool outputs from response
175
- */
176
- // biome-ignore lint/suspicious/noExplicitAny: LangChain response structure is dynamic
177
- extractToolOutputs(response) {
178
- return { output: response?.output ?? response };
179
- }
180
- }
181
- //# sourceMappingURL=middleware.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"middleware.js","sourceRoot":"","sources":["../../../src/instrumentation/langchain/middleware.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AACvD,OAAO,EAAE,QAAQ,EAAE,MAAM,uBAAuB,CAAC;AAEjD,OAAO,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAE5D;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,MAAM,OAAO,mBAAmB;IAGV;IAFZ,QAAQ,GAAgB,IAAI,CAAC;IAErC,YAAoB,MAAc;QAAd,WAAM,GAAN,MAAM,CAAQ;IAAG,CAAC;IAEtC;;;;OAIG;IACH,mFAAmF;IACnF,KAAK,CAAC,WAAW,CAAC,KAAU;QAC1B,MAAM,UAAU,GAAG,WAAW,CAAC,UAAU,EAAE,CAAC;QAC5C,MAAM,QAAQ,GAAG,KAAK,EAAE,QAAQ,IAAI,EAAE,CAAC;QAEvC,IAAI,CAAC,MAAM,CAAC,kBAAkB,EAAE,CAAC;QAEjC,MAAM,IAAI,GAAG,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC;YACjC,IAAI,EAAE,OAAO;YACb,QAAQ,EAAE,QAAQ,CAAC,KAAK;YACxB,MAAM,EAAE,EAAE,QAAQ,EAAE,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAU,EAAE,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,EAAE;YACvE,YAAY,EAAE,UAAU,EAAE,MAAM;YAChC,OAAO,EAAE,UAAU,EAAE,OAAO;SAC7B,CAAC,CAAC;QAEH,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC;IACvB,CAAC;IAED;;;;OAIG;IACH,mFAAmF;IACnF,KAA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/dist/package.json DELETED
@@ -1,56 +0,0 @@
1
- {
2
- "name": "@prefactor/sdk",
3
- "version": "0.1.3",
4
- "description": "Automatic observability for LangChain.js agents",
5
- "type": "module",
6
- "main": "dist/index.cjs",
7
- "module": "dist/index.js",
8
- "types": "dist/index.d.ts",
9
- "exports": {
10
- ".": {
11
- "types": "./dist/index.d.ts",
12
- "import": "./dist/index.js",
13
- "require": "./dist/index.cjs"
14
- }
15
- },
16
- "files": [
17
- "dist"
18
- ],
19
- "scripts": {
20
- "build": "bun run scripts/build.ts",
21
- "test": "bun test",
22
- "test:watch": "bun test --watch",
23
- "typecheck": "tsc --noEmit",
24
- "lint": "biome check .",
25
- "format": "biome format --write .",
26
- "example:basic": "bun examples/basic.ts",
27
- "example:anthropic": "bun examples/anthropic-agent/simple-agent.ts",
28
- "prepublishOnly": "bun run build && bun run test && bun run typecheck"
29
- },
30
- "keywords": [
31
- "prefactor",
32
- "observability",
33
- "tracing",
34
- "langchain",
35
- "llm",
36
- "agent",
37
- "monitoring"
38
- ],
39
- "author": "Prefactor",
40
- "license": "MIT",
41
- "dependencies": {
42
- "@langchain/core": "^0.3.0",
43
- "@prefactor/pfid": "^0.1.0",
44
- "zod": "^3.23.0"
45
- },
46
- "devDependencies": {
47
- "@biomejs/biome": "2.3.11",
48
- "@types/node": "^20.0.0",
49
- "bun-types": "latest",
50
- "langchain": "^1.0.0",
51
- "typescript": "^5.3.0"
52
- },
53
- "engines": {
54
- "node": ">=18.0.0"
55
- }
56
- }
@@ -1,53 +0,0 @@
1
- import type { Span } from './span.js';
2
- /**
3
- * SpanContext manages the current span in async execution contexts.
4
- * This enables automatic parent-child span relationships without manual tracking.
5
- *
6
- * Uses Node.js AsyncLocalStorage which provides async-safe context propagation.
7
- *
8
- * @example
9
- * ```typescript
10
- * const span = tracer.startSpan({ name: 'parent', ... });
11
- *
12
- * await SpanContext.runAsync(span, async () => {
13
- * // Inside this function, getCurrent() returns the parent span
14
- * const parent = SpanContext.getCurrent();
15
- *
16
- * const child = tracer.startSpan({
17
- * name: 'child',
18
- * parentSpanId: parent?.spanId,
19
- * traceId: parent?.traceId,
20
- * });
21
- * // ...
22
- * });
23
- * ```
24
- */
25
- export declare class SpanContext {
26
- /**
27
- * Get the current span from the async context
28
- *
29
- * @returns The current span, or undefined if no span is active
30
- */
31
- static getCurrent(): Span | undefined;
32
- /**
33
- * Run a synchronous function with the given span as the current context
34
- *
35
- * @param span - The span to set as current
36
- * @param fn - The function to execute
37
- * @returns The return value of the function
38
- */
39
- static run<T>(span: Span, fn: () => T): T;
40
- /**
41
- * Run an asynchronous function with the given span as the current context
42
- *
43
- * @param span - The span to set as current
44
- * @param fn - The async function to execute
45
- * @returns A promise resolving to the return value of the function
46
- */
47
- static runAsync<T>(span: Span, fn: () => Promise<T>): Promise<T>;
48
- /**
49
- * Clear the current context (primarily for testing)
50
- */
51
- static clear(): void;
52
- }
53
- //# sourceMappingURL=context.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"context.d.ts","sourceRoot":"","sources":["../../src/tracing/context.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAOtC;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,qBAAa,WAAW;IACtB;;;;OAIG;IACH,MAAM,CAAC,UAAU,IAAI,IAAI,GAAG,SAAS;IAIrC;;;;;;OAMG;IACH,MAAM,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE,EAAE,MAAM,CAAC,GAAG,CAAC;IAIzC;;;;;;OAMG;WACU,QAAQ,CAAC,CAAC,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC;IAItE;;OAEG;IACH,MAAM,CAAC,KAAK,IAAI,IAAI;CAGrB"}
@@ -1,65 +0,0 @@
1
- import { AsyncLocalStorage } from 'node:async_hooks';
2
- /**
3
- * Storage for the current span in async context
4
- */
5
- const spanStorage = new AsyncLocalStorage();
6
- /**
7
- * SpanContext manages the current span in async execution contexts.
8
- * This enables automatic parent-child span relationships without manual tracking.
9
- *
10
- * Uses Node.js AsyncLocalStorage which provides async-safe context propagation.
11
- *
12
- * @example
13
- * ```typescript
14
- * const span = tracer.startSpan({ name: 'parent', ... });
15
- *
16
- * await SpanContext.runAsync(span, async () => {
17
- * // Inside this function, getCurrent() returns the parent span
18
- * const parent = SpanContext.getCurrent();
19
- *
20
- * const child = tracer.startSpan({
21
- * name: 'child',
22
- * parentSpanId: parent?.spanId,
23
- * traceId: parent?.traceId,
24
- * });
25
- * // ...
26
- * });
27
- * ```
28
- */
29
- export class SpanContext {
30
- /**
31
- * Get the current span from the async context
32
- *
33
- * @returns The current span, or undefined if no span is active
34
- */
35
- static getCurrent() {
36
- return spanStorage.getStore();
37
- }
38
- /**
39
- * Run a synchronous function with the given span as the current context
40
- *
41
- * @param span - The span to set as current
42
- * @param fn - The function to execute
43
- * @returns The return value of the function
44
- */
45
- static run(span, fn) {
46
- return spanStorage.run(span, fn);
47
- }
48
- /**
49
- * Run an asynchronous function with the given span as the current context
50
- *
51
- * @param span - The span to set as current
52
- * @param fn - The async function to execute
53
- * @returns A promise resolving to the return value of the function
54
- */
55
- static async runAsync(span, fn) {
56
- return spanStorage.run(span, fn);
57
- }
58
- /**
59
- * Clear the current context (primarily for testing)
60
- */
61
- static clear() {
62
- spanStorage.disable();
63
- }
64
- }
65
- //# sourceMappingURL=context.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"context.js","sourceRoot":"","sources":["../../src/tracing/context.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAGrD;;GAEG;AACH,MAAM,WAAW,GAAG,IAAI,iBAAiB,EAAQ,CAAC;AAElD;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,MAAM,OAAO,WAAW;IACtB;;;;OAIG;IACH,MAAM,CAAC,UAAU;QACf,OAAO,WAAW,CAAC,QAAQ,EAAE,CAAC;IAChC,CAAC;IAED;;;;;;OAMG;IACH,MAAM,CAAC,GAAG,CAAI,IAAU,EAAE,EAAW;QACnC,OAAO,WAAW,CAAC,GAAG,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;IACnC,CAAC;IAED;;;;;;OAMG;IACH,MAAM,CAAC,KAAK,CAAC,QAAQ,CAAI,IAAU,EAAE,EAAoB;QACvD,OAAO,WAAW,CAAC,GAAG,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;IACnC,CAAC;IAED;;OAEG;IACH,MAAM,CAAC,KAAK;QACV,WAAW,CAAC,OAAO,EAAE,CAAC;IACxB,CAAC;CACF"}
@@ -1,68 +0,0 @@
1
- /**
2
- * Types of spans that can be traced
3
- */
4
- export declare enum SpanType {
5
- AGENT = "agent",
6
- LLM = "llm",
7
- TOOL = "tool",
8
- CHAIN = "chain",
9
- RETRIEVER = "retriever"
10
- }
11
- /**
12
- * Status of a span
13
- */
14
- export declare enum SpanStatus {
15
- RUNNING = "running",
16
- SUCCESS = "success",
17
- ERROR = "error"
18
- }
19
- /**
20
- * Token usage information for LLM calls
21
- */
22
- export interface TokenUsage {
23
- promptTokens: number;
24
- completionTokens: number;
25
- totalTokens: number;
26
- }
27
- /**
28
- * Error information captured when a span fails
29
- */
30
- export interface ErrorInfo {
31
- errorType: string;
32
- message: string;
33
- stacktrace: string;
34
- }
35
- /**
36
- * A span represents a single operation in a trace
37
- */
38
- export interface Span {
39
- /** Unique identifier for this span */
40
- spanId: string;
41
- /** ID of the parent span, or null if this is a root span */
42
- parentSpanId: string | null;
43
- /** Trace ID shared by all spans in a single trace */
44
- traceId: string;
45
- /** Human-readable name for this span */
46
- name: string;
47
- /** Type of operation this span represents */
48
- spanType: SpanType;
49
- /** Start time in milliseconds since Unix epoch */
50
- startTime: number;
51
- /** End time in milliseconds since Unix epoch, or null if still running */
52
- endTime: number | null;
53
- /** Current status of the span */
54
- status: SpanStatus;
55
- /** Input data for this operation */
56
- inputs: Record<string, unknown>;
57
- /** Output data from this operation, or null if not completed */
58
- outputs: Record<string, unknown> | null;
59
- /** Token usage for LLM calls, or null if not applicable */
60
- tokenUsage: TokenUsage | null;
61
- /** Error information if the span failed, or null if successful */
62
- error: ErrorInfo | null;
63
- /** Additional metadata about this span */
64
- metadata: Record<string, unknown>;
65
- /** Tags for categorizing and filtering spans */
66
- tags: string[];
67
- }
68
- //# sourceMappingURL=span.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"span.d.ts","sourceRoot":"","sources":["../../src/tracing/span.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,oBAAY,QAAQ;IAClB,KAAK,UAAU;IACf,GAAG,QAAQ;IACX,IAAI,SAAS;IACb,KAAK,UAAU;IACf,SAAS,cAAc;CACxB;AAED;;GAEG;AACH,oBAAY,UAAU;IACpB,OAAO,YAAY;IACnB,OAAO,YAAY;IACnB,KAAK,UAAU;CAChB;AAED;;GAEG;AACH,MAAM,WAAW,UAAU;IACzB,YAAY,EAAE,MAAM,CAAC;IACrB,gBAAgB,EAAE,MAAM,CAAC;IACzB,WAAW,EAAE,MAAM,CAAC;CACrB;AAED;;GAEG;AACH,MAAM,WAAW,SAAS;IACxB,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,MAAM,CAAC;CACpB;AAED;;GAEG;AACH,MAAM,WAAW,IAAI;IACnB,sCAAsC;IACtC,MAAM,EAAE,MAAM,CAAC;IAEf,4DAA4D;IAC5D,YAAY,EAAE,MAAM,GAAG,IAAI,CAAC;IAE5B,qDAAqD;IACrD,OAAO,EAAE,MAAM,CAAC;IAEhB,wCAAwC;IACxC,IAAI,EAAE,MAAM,CAAC;IAEb,6CAA6C;IAC7C,QAAQ,EAAE,QAAQ,CAAC;IAEnB,kDAAkD;IAClD,SAAS,EAAE,MAAM,CAAC;IAElB,0EAA0E;IAC1E,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IAEvB,iCAAiC;IACjC,MAAM,EAAE,UAAU,CAAC;IAEnB,oCAAoC;IACpC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAEhC,gEAAgE;IAChE,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAAC;IAExC,2DAA2D;IAC3D,UAAU,EAAE,UAAU,GAAG,IAAI,CAAC;IAE9B,kEAAkE;IAClE,KAAK,EAAE,SAAS,GAAG,IAAI,CAAC;IAExB,0CAA0C;IAC1C,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAElC,gDAAgD;IAChD,IAAI,EAAE,MAAM,EAAE,CAAC;CAChB"}
@@ -1,21 +0,0 @@
1
- /**
2
- * Types of spans that can be traced
3
- */
4
- export var SpanType;
5
- (function (SpanType) {
6
- SpanType["AGENT"] = "agent";
7
- SpanType["LLM"] = "llm";
8
- SpanType["TOOL"] = "tool";
9
- SpanType["CHAIN"] = "chain";
10
- SpanType["RETRIEVER"] = "retriever";
11
- })(SpanType || (SpanType = {}));
12
- /**
13
- * Status of a span
14
- */
15
- export var SpanStatus;
16
- (function (SpanStatus) {
17
- SpanStatus["RUNNING"] = "running";
18
- SpanStatus["SUCCESS"] = "success";
19
- SpanStatus["ERROR"] = "error";
20
- })(SpanStatus || (SpanStatus = {}));
21
- //# sourceMappingURL=span.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"span.js","sourceRoot":"","sources":["../../src/tracing/span.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,CAAN,IAAY,QAMX;AAND,WAAY,QAAQ;IAClB,2BAAe,CAAA;IACf,uBAAW,CAAA;IACX,yBAAa,CAAA;IACb,2BAAe,CAAA;IACf,mCAAuB,CAAA;AACzB,CAAC,EANW,QAAQ,KAAR,QAAQ,QAMnB;AAED;;GAEG;AACH,MAAM,CAAN,IAAY,UAIX;AAJD,WAAY,UAAU;IACpB,iCAAmB,CAAA;IACnB,iCAAmB,CAAA;IACnB,6BAAe,CAAA;AACjB,CAAC,EAJW,UAAU,KAAV,UAAU,QAIrB"}
@@ -1,100 +0,0 @@
1
- import { type Partition } from '@prefactor/pfid';
2
- import type { Transport } from '../transport/base.js';
3
- import type { Span, SpanType, TokenUsage } from './span.js';
4
- /**
5
- * Options for starting a new span
6
- */
7
- export interface StartSpanOptions {
8
- /** Name of the span */
9
- name: string;
10
- /** Type of operation this span represents */
11
- spanType: SpanType;
12
- /** Input data for this operation */
13
- inputs: Record<string, unknown>;
14
- /** ID of the parent span (optional) */
15
- parentSpanId?: string;
16
- /** Trace ID to use (optional, will generate if not provided) */
17
- traceId?: string;
18
- /** Additional metadata (optional) */
19
- metadata?: Record<string, unknown>;
20
- /** Tags for categorizing the span (optional) */
21
- tags?: string[];
22
- }
23
- /**
24
- * Options for ending a span
25
- */
26
- export interface EndSpanOptions {
27
- /** Output data from the operation */
28
- outputs?: Record<string, unknown>;
29
- /** Error that occurred (if any) */
30
- error?: Error;
31
- /** Token usage information (for LLM calls) */
32
- tokenUsage?: TokenUsage;
33
- }
34
- /**
35
- * Tracer manages the lifecycle of spans.
36
- *
37
- * The tracer is responsible for:
38
- * - Creating spans with unique IDs
39
- * - Managing span lifecycle (start/end)
40
- * - Delegating to the transport layer for span emission
41
- * - Handling agent instance lifecycle
42
- *
43
- * @example
44
- * ```typescript
45
- * const tracer = new Tracer(transport);
46
- *
47
- * const span = tracer.startSpan({
48
- * name: 'llm-call',
49
- * spanType: SpanType.LLM,
50
- * inputs: { prompt: 'Hello' }
51
- * });
52
- *
53
- * try {
54
- * // ... do work ...
55
- * tracer.endSpan(span, { outputs: { response: 'Hi!' } });
56
- * } catch (error) {
57
- * tracer.endSpan(span, { error });
58
- * }
59
- * ```
60
- */
61
- export declare class Tracer {
62
- private transport;
63
- private partition;
64
- /**
65
- * Initialize the tracer.
66
- *
67
- * @param transport - The transport to use for emitting spans
68
- * @param partition - The partition for ID generation. If not provided, a random partition will be generated.
69
- */
70
- constructor(transport: Transport, partition?: Partition);
71
- /**
72
- * Start a new span
73
- *
74
- * @param options - Span configuration options
75
- * @returns The created span
76
- */
77
- startSpan(options: StartSpanOptions): Span;
78
- /**
79
- * End a span and emit it to the transport
80
- *
81
- * @param span - The span to end
82
- * @param options - End span options (outputs, error, token usage)
83
- */
84
- endSpan(span: Span, options?: EndSpanOptions): void;
85
- /**
86
- * Signal the start of an agent instance execution
87
- */
88
- startAgentInstance(): void;
89
- /**
90
- * Signal the completion of an agent instance execution
91
- */
92
- finishAgentInstance(): void;
93
- /**
94
- * Close the tracer and flush any pending spans
95
- *
96
- * @returns Promise that resolves when the tracer is closed
97
- */
98
- close(): Promise<void>;
99
- }
100
- //# sourceMappingURL=tracer.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"tracer.d.ts","sourceRoot":"","sources":["../../src/tracing/tracer.ts"],"names":[],"mappings":"AAAA,OAAO,EAA+B,KAAK,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAC9E,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAC;AACtD,OAAO,KAAK,EAAE,IAAI,EAAE,QAAQ,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AAG5D;;GAEG;AACH,MAAM,WAAW,gBAAgB;IAC/B,uBAAuB;IACvB,IAAI,EAAE,MAAM,CAAC;IAEb,6CAA6C;IAC7C,QAAQ,EAAE,QAAQ,CAAC;IAEnB,oCAAoC;IACpC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAEhC,uCAAuC;IACvC,YAAY,CAAC,EAAE,MAAM,CAAC;IAEtB,gEAAgE;IAChE,OAAO,CAAC,EAAE,MAAM,CAAC;IAEjB,qCAAqC;IACrC,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAEnC,gDAAgD;IAChD,IAAI,CAAC,EAAE,MAAM,EAAE,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