@prefactor/sdk 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.
Files changed (56) hide show
  1. package/LICENSE +14 -0
  2. package/README.md +313 -0
  3. package/dist/LICENSE +14 -0
  4. package/dist/README.md +313 -0
  5. package/dist/config.d.ts +247 -0
  6. package/dist/config.d.ts.map +1 -0
  7. package/dist/config.js +107 -0
  8. package/dist/config.js.map +1 -0
  9. package/dist/index.cjs +1224 -0
  10. package/dist/index.cjs.map +23 -0
  11. package/dist/index.d.ts +82 -0
  12. package/dist/index.d.ts.map +1 -0
  13. package/dist/index.js +1200 -0
  14. package/dist/index.js.map +23 -0
  15. package/dist/instrumentation/langchain/metadata-extractor.d.ts +20 -0
  16. package/dist/instrumentation/langchain/metadata-extractor.d.ts.map +1 -0
  17. package/dist/instrumentation/langchain/metadata-extractor.js +54 -0
  18. package/dist/instrumentation/langchain/metadata-extractor.js.map +1 -0
  19. package/dist/instrumentation/langchain/middleware.d.ts +84 -0
  20. package/dist/instrumentation/langchain/middleware.d.ts.map +1 -0
  21. package/dist/instrumentation/langchain/middleware.js +181 -0
  22. package/dist/instrumentation/langchain/middleware.js.map +1 -0
  23. package/dist/package.json +56 -0
  24. package/dist/tracing/context.d.ts +53 -0
  25. package/dist/tracing/context.d.ts.map +1 -0
  26. package/dist/tracing/context.js +65 -0
  27. package/dist/tracing/context.js.map +1 -0
  28. package/dist/tracing/span.d.ts +68 -0
  29. package/dist/tracing/span.d.ts.map +1 -0
  30. package/dist/tracing/span.js +21 -0
  31. package/dist/tracing/span.js.map +1 -0
  32. package/dist/tracing/tracer.d.ts +100 -0
  33. package/dist/tracing/tracer.d.ts.map +1 -0
  34. package/dist/tracing/tracer.js +151 -0
  35. package/dist/tracing/tracer.js.map +1 -0
  36. package/dist/transport/base.d.ts +38 -0
  37. package/dist/transport/base.d.ts.map +1 -0
  38. package/dist/transport/base.js +2 -0
  39. package/dist/transport/base.js.map +1 -0
  40. package/dist/transport/http.d.ts +86 -0
  41. package/dist/transport/http.d.ts.map +1 -0
  42. package/dist/transport/http.js +331 -0
  43. package/dist/transport/http.js.map +1 -0
  44. package/dist/transport/stdio.d.ts +48 -0
  45. package/dist/transport/stdio.d.ts.map +1 -0
  46. package/dist/transport/stdio.js +71 -0
  47. package/dist/transport/stdio.js.map +1 -0
  48. package/dist/utils/logging.d.ts +29 -0
  49. package/dist/utils/logging.d.ts.map +1 -0
  50. package/dist/utils/logging.js +71 -0
  51. package/dist/utils/logging.js.map +1 -0
  52. package/dist/utils/serialization.d.ts +24 -0
  53. package/dist/utils/serialization.d.ts.map +1 -0
  54. package/dist/utils/serialization.js +60 -0
  55. package/dist/utils/serialization.js.map +1 -0
  56. package/package.json +56 -0
@@ -0,0 +1,56 @@
1
+ {
2
+ "name": "@prefactor/sdk",
3
+ "version": "0.1.0",
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
+ }
@@ -0,0 +1,53 @@
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
@@ -0,0 +1 @@
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"}
@@ -0,0 +1,65 @@
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
@@ -0,0 +1 @@
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"}
@@ -0,0 +1,68 @@
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
@@ -0,0 +1 @@
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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B"}
@@ -0,0 +1,21 @@
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
@@ -0,0 +1 @@
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"}
@@ -0,0 +1,100 @@
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
@@ -0,0 +1 @@
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,CAAC;CACjB;AAED;;GAEG;AACH,MAAM,WAAW,cAAc;IAC7B,qCAAqC;IACrC,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAElC,mCAAmC;IACnC,KAAK,CAAC,EAAE,KAAK,CAAC;IAEd,8CAA8C;IAC9C,UAAU,CAAC,EAAE,UAAU,CAAC;CACzB;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,qBAAa,MAAM;IASL,OAAO,CAAC,SAAS;IAR7B,OAAO,CAAC,SAAS,CAAY;IAE7B;;;;;OAKG;gBACiB,SAAS,EAAE,SAAS,EAAE,SAAS,CAAC,EAAE,SAAS;IAI/D;;;;;OAKG;IACH,SAAS,CAAC,OAAO,EAAE,gBAAgB,GAAG,IAAI;IAkC1C;;;;;OAKG;IACH,OAAO,CAAC,IAAI,EAAE,IAAI,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,IAAI;IA6BnD;;OAEG;IACH,kBAAkB,IAAI,IAAI;IAQ1B;;OAEG;IACH,mBAAmB,IAAI,IAAI;IAQ3B;;;;OAIG;IACG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;CAO7B"}
@@ -0,0 +1,151 @@
1
+ import { generate, generatePartition } from '@prefactor/pfid';
2
+ import { SpanStatus } from './span.js';
3
+ /**
4
+ * Tracer manages the lifecycle of spans.
5
+ *
6
+ * The tracer is responsible for:
7
+ * - Creating spans with unique IDs
8
+ * - Managing span lifecycle (start/end)
9
+ * - Delegating to the transport layer for span emission
10
+ * - Handling agent instance lifecycle
11
+ *
12
+ * @example
13
+ * ```typescript
14
+ * const tracer = new Tracer(transport);
15
+ *
16
+ * const span = tracer.startSpan({
17
+ * name: 'llm-call',
18
+ * spanType: SpanType.LLM,
19
+ * inputs: { prompt: 'Hello' }
20
+ * });
21
+ *
22
+ * try {
23
+ * // ... do work ...
24
+ * tracer.endSpan(span, { outputs: { response: 'Hi!' } });
25
+ * } catch (error) {
26
+ * tracer.endSpan(span, { error });
27
+ * }
28
+ * ```
29
+ */
30
+ export class Tracer {
31
+ transport;
32
+ partition;
33
+ /**
34
+ * Initialize the tracer.
35
+ *
36
+ * @param transport - The transport to use for emitting spans
37
+ * @param partition - The partition for ID generation. If not provided, a random partition will be generated.
38
+ */
39
+ constructor(transport, partition) {
40
+ this.transport = transport;
41
+ this.partition = partition ?? generatePartition();
42
+ }
43
+ /**
44
+ * Start a new span
45
+ *
46
+ * @param options - Span configuration options
47
+ * @returns The created span
48
+ */
49
+ startSpan(options) {
50
+ const spanId = generate(this.partition);
51
+ const traceId = options.traceId ?? generate(this.partition);
52
+ const span = {
53
+ spanId,
54
+ parentSpanId: options.parentSpanId ?? null,
55
+ traceId,
56
+ name: options.name,
57
+ spanType: options.spanType,
58
+ startTime: Date.now(),
59
+ endTime: null,
60
+ status: SpanStatus.RUNNING,
61
+ inputs: options.inputs,
62
+ outputs: null,
63
+ tokenUsage: null,
64
+ error: null,
65
+ metadata: options.metadata ?? {},
66
+ tags: options.tags ?? [],
67
+ };
68
+ // AGENT spans are emitted immediately for real-time tracking
69
+ // They will be finished later with finishSpan()
70
+ if (options.spanType === 'agent') {
71
+ try {
72
+ this.transport.emit(span);
73
+ }
74
+ catch (error) {
75
+ console.error('Failed to emit agent span:', error);
76
+ }
77
+ }
78
+ return span;
79
+ }
80
+ /**
81
+ * End a span and emit it to the transport
82
+ *
83
+ * @param span - The span to end
84
+ * @param options - End span options (outputs, error, token usage)
85
+ */
86
+ endSpan(span, options) {
87
+ span.endTime = Date.now();
88
+ span.outputs = options?.outputs ?? null;
89
+ span.tokenUsage = options?.tokenUsage ?? null;
90
+ if (options?.error) {
91
+ span.status = SpanStatus.ERROR;
92
+ span.error = {
93
+ errorType: options.error.constructor.name,
94
+ message: options.error.message,
95
+ stacktrace: options.error.stack ?? '',
96
+ };
97
+ }
98
+ else {
99
+ span.status = SpanStatus.SUCCESS;
100
+ }
101
+ try {
102
+ // AGENT spans use finishSpan API (they were already emitted on start)
103
+ // Other span types are emitted here
104
+ if (span.spanType === 'agent') {
105
+ this.transport.finishSpan(span.spanId, span.endTime);
106
+ }
107
+ else {
108
+ this.transport.emit(span);
109
+ }
110
+ }
111
+ catch (error) {
112
+ console.error('Failed to emit/finish span:', error);
113
+ }
114
+ }
115
+ /**
116
+ * Signal the start of an agent instance execution
117
+ */
118
+ startAgentInstance() {
119
+ try {
120
+ this.transport.startAgentInstance();
121
+ }
122
+ catch (error) {
123
+ console.error('Failed to start agent instance:', error);
124
+ }
125
+ }
126
+ /**
127
+ * Signal the completion of an agent instance execution
128
+ */
129
+ finishAgentInstance() {
130
+ try {
131
+ this.transport.finishAgentInstance();
132
+ }
133
+ catch (error) {
134
+ console.error('Failed to finish agent instance:', error);
135
+ }
136
+ }
137
+ /**
138
+ * Close the tracer and flush any pending spans
139
+ *
140
+ * @returns Promise that resolves when the tracer is closed
141
+ */
142
+ async close() {
143
+ try {
144
+ await this.transport.close();
145
+ }
146
+ catch (error) {
147
+ console.error('Failed to close transport:', error);
148
+ }
149
+ }
150
+ }
151
+ //# sourceMappingURL=tracer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tracer.js","sourceRoot":"","sources":["../../src/tracing/tracer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,iBAAiB,EAAkB,MAAM,iBAAiB,CAAC;AAG9E,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AA0CvC;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,MAAM,OAAO,MAAM;IASG;IARZ,SAAS,CAAY;IAE7B;;;;;OAKG;IACH,YAAoB,SAAoB,EAAE,SAAqB;QAA3C,cAAS,GAAT,SAAS,CAAW;QACtC,IAAI,CAAC,SAAS,GAAG,SAAS,IAAI,iBAAiB,EAAE,CAAC;IACpD,CAAC;IAED;;;;;OAKG;IACH,SAAS,CAAC,OAAyB;QACjC,MAAM,MAAM,GAAG,QAAQ,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;QACxC,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,IAAI,QAAQ,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;QAE5D,MAAM,IAAI,GAAS;YACjB,MAAM;YACN,YAAY,EAAE,OAAO,CAAC,YAAY,IAAI,IAAI;YAC1C,OAAO;YACP,IAAI,EAAE,OAAO,CAAC,IAAI;YAClB,QAAQ,EAAE,OAAO,CAAC,QAAQ;YAC1B,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE;YACrB,OAAO,EA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AAC;QAED,IAAI,CAAC;YACH,sEAAsE;YACtE,oCAAoC;YACpC,IAAI,IAAI,CAAC,QAAQ,KAAK,OAAO,EAAE,CAAC;gBAC9B,IAAI,CAAC,SAAS,CAAC,UAAU,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;YACvD,CAAC;iBAAM,CAAC;gBACN,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;YAC5B,CAAC;QACH,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,KAAK,CAAC,6BAA6B,EAAE,KAAK,CAAC,CAAC;QACtD,CAAC;IACH,CAAC;IAED;;OAEG;IACH,kBAAkB;QAChB,IAAI,CAAC;YACH,IAAI,CAAC,SAAS,CAAC,kBAAkB,EAAE,CAAC;QACtC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,KAAK,CAAC,iCAAiC,EAAE,KAAK,CAAC,CAAC;QAC1D,CAAC;IACH,CAAC;IAED;;OAEG;IACH,mBAAmB;QACjB,IAAI,CAAC;YACH,IAAI,CAAC,SAAS,CAAC,mBAAmB,EAAE,CAAC;QACvC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,KAAK,CAAC,kCAAkC,EAAE,KAAK,CAAC,CAAC;QAC3D,CAAC;IACH,CAAC;IAED;;;;OAIG;IACH,KAAK,CAAC,KAAK;QACT,IAAI,CAAC;YACH,MAAM,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,CAAC;QAC/B,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,KAAK,CAAC,4BAA4B,EAAE,KAAK,CAAC,CAAC;QACrD,CAAC;IACH,CAAC;CACF"}
@@ -0,0 +1,38 @@
1
+ import type { Span } from '../tracing/span.js';
2
+ /**
3
+ * Transport interface for emitting spans to different backends
4
+ *
5
+ * Transports are responsible for sending span data to a destination
6
+ * (e.g., stdout, HTTP API). They implement the strategy pattern to allow
7
+ * pluggable backends.
8
+ */
9
+ export interface Transport {
10
+ /**
11
+ * Emit a span to the transport destination
12
+ *
13
+ * @param span - The span to emit
14
+ */
15
+ emit(span: Span): void;
16
+ /**
17
+ * Finish a previously emitted span (for long-running spans like AGENT spans)
18
+ *
19
+ * @param spanId - ID of the span to finish
20
+ * @param endTime - End time in milliseconds since Unix epoch
21
+ */
22
+ finishSpan(spanId: string, endTime: number): void;
23
+ /**
24
+ * Signal the start of an agent instance execution
25
+ */
26
+ startAgentInstance(): void;
27
+ /**
28
+ * Signal the completion of an agent instance execution
29
+ */
30
+ finishAgentInstance(): void;
31
+ /**
32
+ * Close the transport and flush any pending data
33
+ *
34
+ * @returns Promise that resolves when the transport is fully closed
35
+ */
36
+ close(): void | Promise<void>;
37
+ }
38
+ //# sourceMappingURL=base.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"base.d.ts","sourceRoot":"","sources":["../../src/transport/base.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAE/C;;;;;;GAMG;AACH,MAAM,WAAW,SAAS;IACxB;;;;OAIG;IACH,IAAI,CAAC,IAAI,EAAE,IAAI,GAAG,IAAI,CAAC;IAEvB;;;;;OAKG;IACH,UAAU,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IAElD;;OAEG;IACH,kBAAkB,IAAI,IAAI,CAAC;IAE3B;;OAEG;IACH,mBAAmB,IAAI,IAAI,CAAC;IAE5B;;;;OAIG;IACH,KAAK,IAAI,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CAC/B"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=base.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"base.js","sourceRoot":"","sources":["../../src/transport/base.ts"],"names":[],"mappings":""}
@@ -0,0 +1,86 @@
1
+ import type { Transport } from './base.js';
2
+ import type { HttpTransportConfig } from '../config.js';
3
+ import type { Span } from '../tracing/span.js';
4
+ /**
5
+ * HTTP transport sends spans to a remote API endpoint.
6
+ *
7
+ * Features:
8
+ * - Queue-based async processing
9
+ * - Exponential backoff retry logic
10
+ * - Span ID mapping (SDK ID → backend ID)
11
+ * - Agent instance lifecycle management
12
+ * - Graceful shutdown with timeout
13
+ *
14
+ * @example
15
+ * ```typescript
16
+ * const transport = new HttpTransport({
17
+ * apiUrl: 'https://api.prefactor.ai',
18
+ * apiToken: process.env.PREFACTOR_API_TOKEN!,
19
+ * });
20
+ * ```
21
+ */
22
+ export declare class HttpTransport implements Transport {
23
+ private config;
24
+ private queue;
25
+ private processing;
26
+ private closed;
27
+ private agentInstanceId;
28
+ private spanIdMap;
29
+ constructor(config: HttpTransportConfig);
30
+ /**
31
+ * Emit a span (adds to queue for async processing)
32
+ *
33
+ * @param span - The span to emit
34
+ */
35
+ emit(span: Span): void;
36
+ /**
37
+ * Finish a previously emitted span (for AGENT spans)
38
+ *
39
+ * @param spanId - ID of the span to finish
40
+ * @param endTime - End time in milliseconds since Unix epoch
41
+ */
42
+ finishSpan(spanId: string, endTime: number): void;
43
+ /**
44
+ * Signal the start of an agent instance execution
45
+ */
46
+ startAgentInstance(): void;
47
+ /**
48
+ * Signal the completion of an agent instance execution
49
+ */
50
+ finishAgentInstance(): void;
51
+ /**
52
+ * Start background queue processing
53
+ */
54
+ private startProcessing;
55
+ /**
56
+ * Send a span to the API
57
+ */
58
+ private sendSpan;
59
+ /**
60
+ * Transform span to backend API format (snake_case)
61
+ */
62
+ private transformSpanToApiFormat;
63
+ /**
64
+ * Ensure an agent instance is registered
65
+ */
66
+ private ensureAgentRegistered;
67
+ /**
68
+ * Start agent instance execution
69
+ */
70
+ private startAgentInstanceHttp;
71
+ /**
72
+ * Finish agent instance execution
73
+ */
74
+ private finishAgentInstanceHttp;
75
+ /**
76
+ * Finish a span via HTTP
77
+ */
78
+ private finishSpanHttp;
79
+ /**
80
+ * Close the transport and wait for queue to drain
81
+ *
82
+ * @returns Promise that resolves when transport is closed
83
+ */
84
+ close(): Promise<void>;
85
+ }
86
+ //# sourceMappingURL=http.d.ts.map