@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
package/README.md CHANGED
@@ -1,17 +1,6 @@
1
- # Prefactor SDK for TypeScript
1
+ # @prefactor/sdk
2
2
 
3
- Automatic observability for LangChain.js agents. Capture distributed traces of LLM calls, tool executions, and agent workflows with minimal integration effort.
4
-
5
- ## Features
6
-
7
- - ✅ Automatic tracing of LLM calls with token usage
8
- - ✅ Tool execution tracking
9
- - ✅ Agent workflow visualization
10
- - ✅ Parent-child span relationships
11
- - ✅ Error tracking and debugging
12
- - ✅ Zero-overhead instrumentation
13
- - ✅ TypeScript type safety
14
- - ✅ Supports stdio and HTTP transports
3
+ Unified SDK for Prefactor observability. This package re-exports everything from `@prefactor/core` and `@prefactor/langchain` for a single-import experience.
15
4
 
16
5
  ## Installation
17
6
 
@@ -21,293 +10,94 @@ npm install @prefactor/sdk
21
10
  bun add @prefactor/sdk
22
11
  ```
23
12
 
13
+ ## When to Use This Package
14
+
15
+ **Use `@prefactor/sdk`** (this package) when:
16
+
17
+ - You're building a LangChain.js application and want all Prefactor features
18
+ - You want a single import for both core primitives and LangChain integration
19
+ - You're not concerned about bundle size optimization
20
+
21
+ **Use individual packages** when:
22
+
23
+ - You need only core tracing without LangChain (`@prefactor/core`)
24
+ - You want to minimize dependencies in a LangChain project (`@prefactor/langchain`)
25
+ - You're building a custom framework integration (`@prefactor/core`)
26
+
24
27
  ## Quick Start
25
28
 
26
29
  ```typescript
27
- import { init } from '@prefactor/sdk';
28
- import { ChatAnthropic } from '@langchain/anthropic';
29
- import { createReactAgent } from '@langchain/langgraph/prebuilt';
30
+ import { createAgent, tool } from 'langchain';
31
+ import { z } from 'zod';
32
+ import { init, shutdown } from '@prefactor/sdk';
30
33
 
31
- // Initialize Prefactor (defaults to stdio transport)
34
+ // Initialize Prefactor
32
35
  const middleware = init();
33
36
 
34
- // Create your agent with middleware
35
- const model = new ChatAnthropic({ model: 'claude-sonnet-4-5-20250929' });
36
- const agent = createReactAgent({
37
- llm: model,
37
+ // Create agent with middleware
38
+ const agent = createAgent({
39
+ model: 'claude-sonnet-4-5-20250929',
38
40
  tools: [],
41
+ systemPrompt: 'You are a helpful assistant.',
39
42
  middleware: [middleware],
40
43
  });
41
44
 
42
- // All operations are automatically traced!
45
+ // All operations are automatically traced
43
46
  const result = await agent.invoke({
44
- messages: [{ role: 'user', content: 'What is 2+2?' }],
47
+ messages: [{ role: 'user', content: 'Hello!' }],
45
48
  });
46
49
 
47
- console.log(result.messages[result.messages.length - 1].content);
50
+ // Graceful shutdown
51
+ await shutdown();
48
52
  ```
49
53
 
50
- ## Configuration
51
-
52
- ### Environment Variables
53
-
54
- The SDK can be configured using environment variables:
55
-
56
- - `PREFACTOR_TRANSPORT`: `"stdio"` | `"http"` (default: `"stdio"`)
57
- - `PREFACTOR_API_URL`: API endpoint for HTTP transport
58
- - `PREFACTOR_API_TOKEN`: Authentication token for HTTP transport
59
- - `PREFACTOR_SAMPLE_RATE`: Sampling rate 0.0-1.0 (default: `1.0`)
60
- - `PREFACTOR_CAPTURE_INPUTS`: Capture span inputs (default: `true`)
61
- - `PREFACTOR_CAPTURE_OUTPUTS`: Capture span outputs (default: `true`)
62
- - `PREFACTOR_MAX_INPUT_LENGTH`: Max input string length (default: `10000`)
63
- - `PREFACTOR_MAX_OUTPUT_LENGTH`: Max output string length (default: `10000`)
64
- - `PREFACTOR_LOG_LEVEL`: `"debug"` | `"info"` | `"warn"` | `"error"` (default: `"info"`)
65
-
66
- ### Programmatic Configuration
54
+ ## What's Included
67
55
 
68
- ```typescript
69
- import { init } from '@prefactor/sdk';
56
+ This package re-exports everything from:
70
57
 
71
- // HTTP Transport
72
- const middleware = init({
73
- transportType: 'http',
74
- httpConfig: {
75
- apiUrl: 'https://api.prefactor.ai',
76
- apiToken: process.env.PREFACTOR_API_TOKEN!,
77
- agentId: 'my-agent',
78
- agentVersion: '1.0.0',
79
- },
80
- });
58
+ ### From `@prefactor/langchain`
81
59
 
82
- // Custom sampling
83
- const middleware = init({
84
- sampleRate: 0.1, // Sample 10% of traces
85
- maxInputLength: 5000,
86
- maxOutputLength: 5000,
87
- });
88
- ```
60
+ - `init()` - Initialize SDK and return middleware
61
+ - `shutdown()` - Flush spans and close connections
62
+ - `getTracer()` - Get tracer for manual instrumentation
63
+ - `PrefactorMiddleware` - LangChain.js middleware class
64
+ - `extractTokenUsage()` - Token usage extraction utility
89
65
 
90
- ## Transports
66
+ ### From `@prefactor/core`
91
67
 
92
- ### STDIO Transport (Default)
68
+ - Configuration: `Config`, `createConfig`, `ConfigSchema`, `HttpTransportConfig`
69
+ - Tracing: `Tracer`, `SpanContext`, `Span`, `SpanType`, `SpanStatus`, `TokenUsage`, `ErrorInfo`
70
+ - Transports: `Transport`, `StdioTransport`, `HttpTransport`
71
+ - Utilities: `getLogger`, `configureLogging`, `serializeValue`, `truncateString`
93
72
 
94
- The STDIO transport writes spans as newline-delimited JSON to stdout. This is useful for local development and piping to other tools.
73
+ ## Configuration
95
74
 
96
75
  ```typescript
97
76
  import { init } from '@prefactor/sdk';
98
77
 
99
- const middleware = init(); // Uses stdio by default
100
- ```
101
-
102
- ### HTTP Transport
103
-
104
- The HTTP transport sends spans to a remote API endpoint with retry logic and queue-based processing.
105
-
106
- ```typescript
107
- import { init } from '@prefactor/sdk';
78
+ // STDIO transport (default, good for development)
79
+ const middleware = init();
108
80
 
81
+ // HTTP transport (for production)
109
82
  const middleware = init({
110
83
  transportType: 'http',
111
84
  httpConfig: {
112
85
  apiUrl: 'https://api.prefactor.ai',
113
86
  apiToken: process.env.PREFACTOR_API_TOKEN!,
114
87
  agentId: 'my-agent',
115
- agentVersion: '1.0.0',
116
- maxRetries: 3,
117
- requestTimeout: 30000,
118
88
  },
119
89
  });
120
90
  ```
121
91
 
122
- ## API Reference
123
-
124
- ### `init(config?: Partial<Config>): PrefactorMiddleware`
125
-
126
- Initialize the SDK and return middleware instance.
127
-
128
- **Parameters:**
129
- - `config` - Optional configuration object
130
-
131
- **Returns:**
132
- - `PrefactorMiddleware` - Middleware instance to use with LangChain.js agents
133
-
134
- **Example:**
135
- ```typescript
136
- const middleware = init({
137
- transportType: 'stdio',
138
- sampleRate: 1.0,
139
- });
140
- ```
141
-
142
- ### `shutdown(): Promise<void>`
143
-
144
- Flush pending spans and close connections. Call before application exit.
145
-
146
- **Example:**
147
- ```typescript
148
- import { shutdown } from '@prefactor/sdk';
149
-
150
- process.on('SIGTERM', async () => {
151
- await shutdown();
152
- process.exit(0);
153
- });
154
- ```
155
-
156
- ### `getTracer(): Tracer`
157
-
158
- Get the global tracer instance for manual instrumentation.
159
-
160
- **Returns:**
161
- - `Tracer` - Tracer instance
162
-
163
- **Example:**
164
- ```typescript
165
- import { getTracer, SpanType } from '@prefactor/sdk';
166
-
167
- const tracer = getTracer();
168
- const span = tracer.startSpan({
169
- name: 'custom-operation',
170
- spanType: SpanType.TOOL,
171
- inputs: { data: 'example' },
172
- });
173
-
174
- try {
175
- // ... do work ...
176
- tracer.endSpan(span, { outputs: { result: 'done' } });
177
- } catch (error) {
178
- tracer.endSpan(span, { error });
179
- }
180
- ```
181
-
182
- ## Advanced Usage
183
-
184
- ### Manual Instrumentation
185
-
186
- For operations not automatically traced by the middleware:
187
-
188
- ```typescript
189
- import { getTracer, SpanType } from '@prefactor/sdk';
190
-
191
- const tracer = getTracer();
192
-
193
- const span = tracer.startSpan({
194
- name: 'database-query',
195
- spanType: SpanType.TOOL,
196
- inputs: { query: 'SELECT * FROM users' },
197
- metadata: { database: 'postgres' },
198
- tags: ['database', 'query'],
199
- });
200
-
201
- try {
202
- const result = await db.query('SELECT * FROM users');
203
- tracer.endSpan(span, { outputs: { rowCount: result.rows.length } });
204
- } catch (error) {
205
- tracer.endSpan(span, { error });
206
- }
207
- ```
208
-
209
- ### Context Propagation
210
-
211
- The SDK automatically propagates span context through async operations using Node.js AsyncLocalStorage. Child spans automatically inherit the trace ID and parent span ID from the current context.
212
-
213
- ```typescript
214
- import { SpanContext } from '@prefactor/sdk';
215
-
216
- // Get the current span (if any)
217
- const currentSpan = SpanContext.getCurrent();
218
-
219
- // Child spans automatically use the current span as parent
220
- const child = tracer.startSpan({
221
- name: 'child-operation',
222
- spanType: SpanType.TOOL,
223
- inputs: {},
224
- parentSpanId: currentSpan?.spanId,
225
- traceId: currentSpan?.traceId,
226
- });
227
- ```
228
-
229
- ## TypeScript Support
230
-
231
- The SDK is written in TypeScript and provides full type definitions:
232
-
233
- ```typescript
234
- import type {
235
- Config,
236
- HttpTransportConfig,
237
- Span,
238
- SpanType,
239
- SpanStatus,
240
- TokenUsage,
241
- ErrorInfo
242
- } from '@prefactor/sdk';
243
-
244
- const config: Config = {
245
- transportType: 'stdio',
246
- sampleRate: 1.0,
247
- captureInputs: true,
248
- captureOutputs: true,
249
- };
250
- ```
251
-
252
- ## Examples
253
-
254
- See the `examples/` directory for complete examples:
255
-
256
- - `examples/basic.ts` - Simple LangChain.js agent with stdio transport
257
- - `examples/http-transport.ts` - Using HTTP transport
258
- - `examples/custom-tools.ts` - Tracing custom tools
259
- - `examples/manual-instrumentation.ts` - Manual span creation
260
-
261
- ## Architecture
262
-
263
- The SDK consists of five main layers:
264
-
265
- 1. **Tracing Layer**: Span data models, Tracer for lifecycle management, Context propagation
266
- 2. **Transport Layer**: Pluggable backends (stdio, HTTP) for span emission
267
- 3. **Instrumentation Layer**: LangChain.js middleware integration
268
- 4. **Configuration**: Environment variable support, validation with Zod
269
- 5. **Utilities**: Logging, serialization helpers
270
-
271
- For more details, see `docs/architecture.md`.
272
-
273
92
  ## Requirements
274
93
 
275
- - Node.js >= 18.0.0
276
- - TypeScript >= 5.0.0 (for TypeScript projects)
277
- - Bun >= 1.0.0 (optional, for development)
278
-
279
- ## Development
280
-
281
- ```bash
282
- # Install dependencies
283
- bun install
284
-
285
- # Run tests
286
- bun test
287
-
288
- # Type check
289
- bun run typecheck
94
+ - Node.js >= 24.0.0
95
+ - LangChain.js >= 1.0.0 (peer dependency)
290
96
 
291
- # Lint
292
- bun run lint
97
+ ## Documentation
293
98
 
294
- # Format
295
- bun run format
296
-
297
- # Build
298
- bun run build
299
- ```
300
-
301
- ## Contributing
302
-
303
- Contributions are welcome! Please see `CONTRIBUTING.md` for guidelines.
99
+ For detailed documentation, see the [main repository README](https://github.com/prefactor/typescript-sdk).
304
100
 
305
101
  ## License
306
102
 
307
103
  MIT
308
-
309
- ## Support
310
-
311
- - Documentation: [https://docs.prefactor.ai](https://docs.prefactor.ai)
312
- - Issues: [GitHub Issues](https://github.com/prefactor/typescript-sdk/issues)
313
- - Email: support@prefactor.ai