@observyze/sdk 0.1.0 → 0.1.2
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 +21 -0
- package/README.md +10 -175
- package/dist/chunk-YRMQCX2P.mjs +372 -0
- package/dist/index-DEorAmFu.d.mts +405 -0
- package/dist/index-DEorAmFu.d.ts +405 -0
- package/dist/index.d.mts +60 -0
- package/dist/index.d.ts +60 -0
- package/dist/index.js +1029 -0
- package/dist/index.mjs +673 -0
- package/dist/opentelemetry/index.d.mts +1 -0
- package/dist/opentelemetry/index.d.ts +1 -0
- package/dist/opentelemetry/index.js +335 -0
- package/dist/opentelemetry/index.mjs +6 -0
- package/package.json +15 -8
- package/INSTRUMENTATION_SUMMARY.md +0 -184
- package/examples/auto-instrumentation.ts +0 -210
- package/src/client.ts +0 -578
- package/src/index.ts +0 -21
- package/src/instrumentation/README.md +0 -227
- package/src/instrumentation/anthropic.ts +0 -233
- package/src/instrumentation/index.ts +0 -43
- package/src/instrumentation/openai.ts +0 -193
- package/src/trace.ts +0 -242
- package/src/types.ts +0 -102
- package/tsconfig.json +0 -14
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,673 @@
|
|
|
1
|
+
import {
|
|
2
|
+
ObservyzeSpanExporter,
|
|
3
|
+
Span,
|
|
4
|
+
SpanType,
|
|
5
|
+
Trace,
|
|
6
|
+
TraceStatus,
|
|
7
|
+
__esm,
|
|
8
|
+
__export,
|
|
9
|
+
__require,
|
|
10
|
+
__toCommonJS,
|
|
11
|
+
init_types
|
|
12
|
+
} from "./chunk-YRMQCX2P.mjs";
|
|
13
|
+
|
|
14
|
+
// src/instrumentation/openai.ts
|
|
15
|
+
function wrapOpenAI(client, nwClient) {
|
|
16
|
+
const anyClient = client;
|
|
17
|
+
const originalCreate = client.chat.completions.create.bind(client.chat.completions);
|
|
18
|
+
client.chat.completions.create = async function(params, options) {
|
|
19
|
+
const trace = nwClient.startTrace(`openai.chat.completions.create`, {
|
|
20
|
+
provider: "openai",
|
|
21
|
+
model: params.model
|
|
22
|
+
});
|
|
23
|
+
const span = trace.startSpan("chat.completions.create", "llm" /* LLM */);
|
|
24
|
+
span.setMetadata("model", params.model);
|
|
25
|
+
span.setMetadata("provider", "openai");
|
|
26
|
+
if (params.temperature !== void 0) span.setMetadata("temperature", params.temperature);
|
|
27
|
+
if (params.max_tokens !== void 0) span.setMetadata("max_tokens", params.max_tokens);
|
|
28
|
+
span.setInput({
|
|
29
|
+
model: params.model,
|
|
30
|
+
messages: params.messages,
|
|
31
|
+
temperature: params.temperature,
|
|
32
|
+
max_tokens: params.max_tokens
|
|
33
|
+
});
|
|
34
|
+
const startTime = Date.now();
|
|
35
|
+
try {
|
|
36
|
+
const response = await originalCreate(params, options);
|
|
37
|
+
if (params.stream) {
|
|
38
|
+
return wrapOpenAIStream(response, span, trace, startTime);
|
|
39
|
+
}
|
|
40
|
+
const completionResponse = response;
|
|
41
|
+
const latency = Date.now() - startTime;
|
|
42
|
+
span.setOutput({
|
|
43
|
+
id: completionResponse.id,
|
|
44
|
+
model: completionResponse.model,
|
|
45
|
+
choices: completionResponse.choices
|
|
46
|
+
});
|
|
47
|
+
if (completionResponse.usage) {
|
|
48
|
+
span.setTokens({
|
|
49
|
+
input: completionResponse.usage.prompt_tokens,
|
|
50
|
+
output: completionResponse.usage.completion_tokens,
|
|
51
|
+
total: completionResponse.usage.total_tokens
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
span.setMetadata("latency_ms", latency);
|
|
55
|
+
span.end();
|
|
56
|
+
trace.end();
|
|
57
|
+
return response;
|
|
58
|
+
} catch (error) {
|
|
59
|
+
const latency = Date.now() - startTime;
|
|
60
|
+
span.setMetadata("latency_ms", latency);
|
|
61
|
+
span.setError(error);
|
|
62
|
+
span.end();
|
|
63
|
+
trace.end();
|
|
64
|
+
throw error;
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
return client;
|
|
68
|
+
}
|
|
69
|
+
function wrapOpenAIStream(stream, span, trace, startTime) {
|
|
70
|
+
const bufferedChunks = [];
|
|
71
|
+
let streamId = "";
|
|
72
|
+
let streamModel = "";
|
|
73
|
+
return {
|
|
74
|
+
[Symbol.asyncIterator]: async function* () {
|
|
75
|
+
try {
|
|
76
|
+
for await (const chunk of stream) {
|
|
77
|
+
if (chunk.id) streamId = chunk.id;
|
|
78
|
+
if (chunk.model) streamModel = chunk.model;
|
|
79
|
+
const delta = chunk.choices[0]?.delta;
|
|
80
|
+
if (delta?.content) {
|
|
81
|
+
bufferedChunks.push(delta.content);
|
|
82
|
+
}
|
|
83
|
+
yield chunk;
|
|
84
|
+
}
|
|
85
|
+
const latency = Date.now() - startTime;
|
|
86
|
+
const completeOutput = bufferedChunks.join("");
|
|
87
|
+
span.setOutput({
|
|
88
|
+
id: streamId,
|
|
89
|
+
model: streamModel,
|
|
90
|
+
content: completeOutput
|
|
91
|
+
});
|
|
92
|
+
span.setMetadata("latency_ms", latency);
|
|
93
|
+
span.setMetadata("streaming", true);
|
|
94
|
+
span.end();
|
|
95
|
+
trace.end();
|
|
96
|
+
} catch (error) {
|
|
97
|
+
const latency = Date.now() - startTime;
|
|
98
|
+
span.setMetadata("latency_ms", latency);
|
|
99
|
+
span.setError(error);
|
|
100
|
+
span.end();
|
|
101
|
+
trace.end();
|
|
102
|
+
throw error;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
var init_openai = __esm({
|
|
108
|
+
"src/instrumentation/openai.ts"() {
|
|
109
|
+
"use strict";
|
|
110
|
+
init_types();
|
|
111
|
+
}
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
// src/instrumentation/anthropic.ts
|
|
115
|
+
function wrapAnthropic(client, nwClient) {
|
|
116
|
+
const anyClient = client;
|
|
117
|
+
const originalCreate = client.messages.create.bind(client.messages);
|
|
118
|
+
client.messages.create = async function(params, options) {
|
|
119
|
+
const trace = nwClient.startTrace(`anthropic.messages.create`, {
|
|
120
|
+
provider: "anthropic",
|
|
121
|
+
model: params.model
|
|
122
|
+
});
|
|
123
|
+
const span = trace.startSpan("messages.create", "llm" /* LLM */);
|
|
124
|
+
span.setMetadata("model", params.model);
|
|
125
|
+
span.setMetadata("provider", "anthropic");
|
|
126
|
+
if (params.temperature !== void 0) span.setMetadata("temperature", params.temperature);
|
|
127
|
+
if (params.max_tokens !== void 0) span.setMetadata("max_tokens", params.max_tokens);
|
|
128
|
+
if (params.system !== void 0) span.setMetadata("system", params.system);
|
|
129
|
+
span.setInput({
|
|
130
|
+
model: params.model,
|
|
131
|
+
messages: params.messages,
|
|
132
|
+
max_tokens: params.max_tokens,
|
|
133
|
+
temperature: params.temperature,
|
|
134
|
+
system: params.system
|
|
135
|
+
});
|
|
136
|
+
const startTime = Date.now();
|
|
137
|
+
try {
|
|
138
|
+
const response = await originalCreate(params, options);
|
|
139
|
+
if (params.stream) {
|
|
140
|
+
return wrapAnthropicStream(response, span, trace, startTime);
|
|
141
|
+
}
|
|
142
|
+
const messageResponse = response;
|
|
143
|
+
const latency = Date.now() - startTime;
|
|
144
|
+
span.setOutput({
|
|
145
|
+
id: messageResponse.id,
|
|
146
|
+
model: messageResponse.model,
|
|
147
|
+
role: messageResponse.role,
|
|
148
|
+
content: messageResponse.content,
|
|
149
|
+
stop_reason: messageResponse.stop_reason
|
|
150
|
+
});
|
|
151
|
+
if (messageResponse.usage) {
|
|
152
|
+
span.setTokens({
|
|
153
|
+
input: messageResponse.usage.input_tokens,
|
|
154
|
+
output: messageResponse.usage.output_tokens,
|
|
155
|
+
total: messageResponse.usage.input_tokens + messageResponse.usage.output_tokens
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
span.setMetadata("latency_ms", latency);
|
|
159
|
+
span.end();
|
|
160
|
+
trace.end();
|
|
161
|
+
return response;
|
|
162
|
+
} catch (error) {
|
|
163
|
+
const latency = Date.now() - startTime;
|
|
164
|
+
span.setMetadata("latency_ms", latency);
|
|
165
|
+
span.setError(error);
|
|
166
|
+
span.end();
|
|
167
|
+
trace.end();
|
|
168
|
+
throw error;
|
|
169
|
+
}
|
|
170
|
+
};
|
|
171
|
+
return client;
|
|
172
|
+
}
|
|
173
|
+
function wrapAnthropicStream(stream, span, trace, startTime) {
|
|
174
|
+
const bufferedChunks = [];
|
|
175
|
+
let messageId = "";
|
|
176
|
+
let messageModel = "";
|
|
177
|
+
let stopReason = null;
|
|
178
|
+
let inputTokens = 0;
|
|
179
|
+
let outputTokens = 0;
|
|
180
|
+
return {
|
|
181
|
+
[Symbol.asyncIterator]: async function* () {
|
|
182
|
+
try {
|
|
183
|
+
for await (const event of stream) {
|
|
184
|
+
if (event.type === "message_start" && event.message) {
|
|
185
|
+
messageId = event.message.id;
|
|
186
|
+
messageModel = event.message.model;
|
|
187
|
+
if (event.message.usage) {
|
|
188
|
+
inputTokens = event.message.usage.input_tokens;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
if (event.type === "content_block_delta" && event.delta?.text) {
|
|
192
|
+
bufferedChunks.push(event.delta.text);
|
|
193
|
+
}
|
|
194
|
+
if (event.type === "message_delta" && event.delta) {
|
|
195
|
+
if (event.delta.stop_reason) {
|
|
196
|
+
stopReason = event.delta.stop_reason;
|
|
197
|
+
}
|
|
198
|
+
if (event.usage?.output_tokens) {
|
|
199
|
+
outputTokens = event.usage.output_tokens;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
yield event;
|
|
203
|
+
}
|
|
204
|
+
const latency = Date.now() - startTime;
|
|
205
|
+
const completeOutput = bufferedChunks.join("");
|
|
206
|
+
span.setOutput({
|
|
207
|
+
id: messageId,
|
|
208
|
+
model: messageModel,
|
|
209
|
+
content: completeOutput,
|
|
210
|
+
stop_reason: stopReason
|
|
211
|
+
});
|
|
212
|
+
if (inputTokens > 0 || outputTokens > 0) {
|
|
213
|
+
span.setTokens({
|
|
214
|
+
input: inputTokens,
|
|
215
|
+
output: outputTokens,
|
|
216
|
+
total: inputTokens + outputTokens
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
span.setMetadata("latency_ms", latency);
|
|
220
|
+
span.setMetadata("streaming", true);
|
|
221
|
+
span.end();
|
|
222
|
+
trace.end();
|
|
223
|
+
} catch (error) {
|
|
224
|
+
const latency = Date.now() - startTime;
|
|
225
|
+
span.setMetadata("latency_ms", latency);
|
|
226
|
+
span.setError(error);
|
|
227
|
+
span.end();
|
|
228
|
+
trace.end();
|
|
229
|
+
throw error;
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
var init_anthropic = __esm({
|
|
235
|
+
"src/instrumentation/anthropic.ts"() {
|
|
236
|
+
"use strict";
|
|
237
|
+
init_types();
|
|
238
|
+
}
|
|
239
|
+
});
|
|
240
|
+
|
|
241
|
+
// src/instrumentation/index.ts
|
|
242
|
+
var instrumentation_exports = {};
|
|
243
|
+
__export(instrumentation_exports, {
|
|
244
|
+
wrap: () => wrap,
|
|
245
|
+
wrapAnthropic: () => wrapAnthropic,
|
|
246
|
+
wrapOpenAI: () => wrapOpenAI
|
|
247
|
+
});
|
|
248
|
+
function wrap(client, nwClient) {
|
|
249
|
+
if ("chat" in client && client.chat && "completions" in client.chat) {
|
|
250
|
+
return wrapOpenAI(client, nwClient);
|
|
251
|
+
}
|
|
252
|
+
if ("messages" in client && client.messages && "create" in client.messages) {
|
|
253
|
+
return wrapAnthropic(client, nwClient);
|
|
254
|
+
}
|
|
255
|
+
throw new Error(
|
|
256
|
+
"Observyze SDK: Unsupported client type. Supported clients: OpenAI, Anthropic"
|
|
257
|
+
);
|
|
258
|
+
}
|
|
259
|
+
var init_instrumentation = __esm({
|
|
260
|
+
"src/instrumentation/index.ts"() {
|
|
261
|
+
"use strict";
|
|
262
|
+
init_openai();
|
|
263
|
+
init_anthropic();
|
|
264
|
+
init_openai();
|
|
265
|
+
init_anthropic();
|
|
266
|
+
}
|
|
267
|
+
});
|
|
268
|
+
|
|
269
|
+
// src/client.ts
|
|
270
|
+
init_types();
|
|
271
|
+
var DEFAULT_CONFIG = {
|
|
272
|
+
endpoint: "https://api.observyze.com",
|
|
273
|
+
batchSize: 100,
|
|
274
|
+
flushInterval: 5e3,
|
|
275
|
+
enableAutoInstrumentation: true,
|
|
276
|
+
debug: false,
|
|
277
|
+
dryRun: false,
|
|
278
|
+
enablePiiRedaction: true
|
|
279
|
+
};
|
|
280
|
+
var ObservyzeClient = class _ObservyzeClient {
|
|
281
|
+
config;
|
|
282
|
+
traceBuffer = [];
|
|
283
|
+
flushTimer = null;
|
|
284
|
+
isShuttingDown = false;
|
|
285
|
+
MAX_QUEUE_SIZE = 1e3;
|
|
286
|
+
RETRY_DELAYS = [1e3, 2e3, 4e3, 8e3, 16e3, 3e4];
|
|
287
|
+
// ms: 1s → 2s → 4s → 8s → 16s → 30s
|
|
288
|
+
constructor(config) {
|
|
289
|
+
if (!config.apiKey) {
|
|
290
|
+
throw new Error("Observyze SDK: apiKey is required");
|
|
291
|
+
}
|
|
292
|
+
this.config = {
|
|
293
|
+
...DEFAULT_CONFIG,
|
|
294
|
+
...config,
|
|
295
|
+
organizationId: config.organizationId || "",
|
|
296
|
+
projectId: config.projectId || ""
|
|
297
|
+
};
|
|
298
|
+
this.startFlushTimer();
|
|
299
|
+
if (this.config.debug) {
|
|
300
|
+
console.log("[Observyze SDK] Initialized with config:", {
|
|
301
|
+
endpoint: this.config.endpoint,
|
|
302
|
+
batchSize: this.config.batchSize,
|
|
303
|
+
flushInterval: this.config.flushInterval,
|
|
304
|
+
dryRun: this.config.dryRun
|
|
305
|
+
});
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
/**
|
|
309
|
+
* Start a new trace
|
|
310
|
+
*/
|
|
311
|
+
startTrace(name, metadata) {
|
|
312
|
+
const trace = new Trace(
|
|
313
|
+
name,
|
|
314
|
+
this.config.organizationId,
|
|
315
|
+
this.config.projectId
|
|
316
|
+
);
|
|
317
|
+
if (metadata) {
|
|
318
|
+
trace.setMetadataAll(metadata);
|
|
319
|
+
}
|
|
320
|
+
const originalEnd = trace.end.bind(trace);
|
|
321
|
+
trace.end = (status = "success" /* SUCCESS */) => {
|
|
322
|
+
originalEnd(status);
|
|
323
|
+
this.bufferTrace(trace);
|
|
324
|
+
};
|
|
325
|
+
return trace;
|
|
326
|
+
}
|
|
327
|
+
/**
|
|
328
|
+
* Buffer a completed trace for batch sending
|
|
329
|
+
*/
|
|
330
|
+
bufferTrace(trace) {
|
|
331
|
+
if (!trace.isEnded) {
|
|
332
|
+
if (this.config.debug) {
|
|
333
|
+
console.warn("[Observyze SDK] Attempted to buffer a trace that has not ended");
|
|
334
|
+
}
|
|
335
|
+
return;
|
|
336
|
+
}
|
|
337
|
+
if (this.traceBuffer.length >= this.MAX_QUEUE_SIZE) {
|
|
338
|
+
if (this.config.debug) {
|
|
339
|
+
console.warn(`[Observyze SDK] Queue at max capacity (${this.MAX_QUEUE_SIZE}), dropping oldest trace`);
|
|
340
|
+
}
|
|
341
|
+
this.traceBuffer.shift();
|
|
342
|
+
}
|
|
343
|
+
this.traceBuffer.push(trace);
|
|
344
|
+
if (this.config.debug) {
|
|
345
|
+
console.log(`[Observyze SDK] Buffered trace ${trace.id} (${this.traceBuffer.length}/${this.config.batchSize})`);
|
|
346
|
+
}
|
|
347
|
+
if (this.traceBuffer.length >= this.config.batchSize) {
|
|
348
|
+
this.flush().catch((err) => {
|
|
349
|
+
console.error("[Observyze SDK] Error flushing buffer:", err);
|
|
350
|
+
});
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
/**
|
|
354
|
+
* Start the auto-flush timer
|
|
355
|
+
*/
|
|
356
|
+
startFlushTimer() {
|
|
357
|
+
if (this.flushTimer) {
|
|
358
|
+
clearInterval(this.flushTimer);
|
|
359
|
+
}
|
|
360
|
+
this.flushTimer = setInterval(() => {
|
|
361
|
+
if (this.traceBuffer.length > 0) {
|
|
362
|
+
this.flush().catch((err) => {
|
|
363
|
+
console.error("[Observyze SDK] Error in auto-flush:", err);
|
|
364
|
+
});
|
|
365
|
+
}
|
|
366
|
+
}, this.config.flushInterval);
|
|
367
|
+
if (this.flushTimer.unref) {
|
|
368
|
+
this.flushTimer.unref();
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
/**
|
|
372
|
+
* Flush all buffered traces to the Ingestion Service
|
|
373
|
+
*/
|
|
374
|
+
async flush() {
|
|
375
|
+
if (this.traceBuffer.length === 0) {
|
|
376
|
+
return;
|
|
377
|
+
}
|
|
378
|
+
const tracesToSend = this.traceBuffer.splice(0, this.config.batchSize);
|
|
379
|
+
if (this.config.debug) {
|
|
380
|
+
console.log(`[Observyze SDK] Flushing ${tracesToSend.length} traces`);
|
|
381
|
+
}
|
|
382
|
+
if (this.config.dryRun) {
|
|
383
|
+
if (this.config.debug) {
|
|
384
|
+
console.log("[Observyze SDK] Dry-run mode: traces not sent");
|
|
385
|
+
}
|
|
386
|
+
return;
|
|
387
|
+
}
|
|
388
|
+
try {
|
|
389
|
+
await this.sendWithRetry(tracesToSend);
|
|
390
|
+
} catch (error) {
|
|
391
|
+
const remainingSpace = this.MAX_QUEUE_SIZE - this.traceBuffer.length;
|
|
392
|
+
if (remainingSpace > 0) {
|
|
393
|
+
this.traceBuffer.unshift(...tracesToSend.slice(0, remainingSpace));
|
|
394
|
+
if (this.config.debug) {
|
|
395
|
+
console.log(`[Observyze SDK] Re-queued ${Math.min(tracesToSend.length, remainingSpace)} traces after failure`);
|
|
396
|
+
}
|
|
397
|
+
} else {
|
|
398
|
+
if (this.config.debug) {
|
|
399
|
+
console.warn(`[Observyze SDK] Queue full, dropped ${tracesToSend.length} traces`);
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
if (this.config.debug) {
|
|
403
|
+
console.error("[Observyze SDK] Failed to send traces after retries:", error);
|
|
404
|
+
}
|
|
405
|
+
throw error;
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
/**
|
|
409
|
+
* Send traces with exponential backoff retry
|
|
410
|
+
*/
|
|
411
|
+
async sendWithRetry(traces) {
|
|
412
|
+
let lastError = null;
|
|
413
|
+
for (let attempt = 0; attempt < this.RETRY_DELAYS.length + 1; attempt++) {
|
|
414
|
+
try {
|
|
415
|
+
const response = await fetch(`${this.config.endpoint}/api/v1/ingest/batch`, {
|
|
416
|
+
method: "POST",
|
|
417
|
+
headers: {
|
|
418
|
+
"Content-Type": "application/json",
|
|
419
|
+
"Authorization": `Bearer ${this.config.apiKey}`
|
|
420
|
+
},
|
|
421
|
+
body: JSON.stringify({
|
|
422
|
+
traces: traces.map((trace) => {
|
|
423
|
+
const json = trace.toJSON();
|
|
424
|
+
if (this.config.enablePiiRedaction) {
|
|
425
|
+
json.spans = this.sanitizePII(json.spans);
|
|
426
|
+
}
|
|
427
|
+
return json;
|
|
428
|
+
})
|
|
429
|
+
})
|
|
430
|
+
});
|
|
431
|
+
if (!response.ok) {
|
|
432
|
+
const errorBody = await response.text();
|
|
433
|
+
throw new Error(`Ingestion failed: ${response.status} ${errorBody}`);
|
|
434
|
+
}
|
|
435
|
+
if (this.config.debug) {
|
|
436
|
+
console.log(`[Observyze SDK] Successfully sent ${traces.length} traces${attempt > 0 ? ` (after ${attempt} retries)` : ""}`);
|
|
437
|
+
}
|
|
438
|
+
return;
|
|
439
|
+
} catch (error) {
|
|
440
|
+
lastError = error;
|
|
441
|
+
if (attempt >= this.RETRY_DELAYS.length) {
|
|
442
|
+
break;
|
|
443
|
+
}
|
|
444
|
+
const delay = this.RETRY_DELAYS[attempt];
|
|
445
|
+
if (this.config.debug) {
|
|
446
|
+
console.warn(`[Observyze SDK] Attempt ${attempt + 1} failed, retrying in ${delay}ms...`, error);
|
|
447
|
+
}
|
|
448
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
throw lastError || new Error("Failed to send traces after all retries");
|
|
452
|
+
}
|
|
453
|
+
/**
|
|
454
|
+
* Shutdown the SDK and flush remaining traces
|
|
455
|
+
*/
|
|
456
|
+
async shutdown() {
|
|
457
|
+
if (this.isShuttingDown) {
|
|
458
|
+
return;
|
|
459
|
+
}
|
|
460
|
+
this.isShuttingDown = true;
|
|
461
|
+
if (this.config.debug) {
|
|
462
|
+
console.log("[Observyze SDK] Shutting down...");
|
|
463
|
+
}
|
|
464
|
+
if (this.flushTimer) {
|
|
465
|
+
clearInterval(this.flushTimer);
|
|
466
|
+
this.flushTimer = null;
|
|
467
|
+
}
|
|
468
|
+
try {
|
|
469
|
+
await this.flush();
|
|
470
|
+
} catch (error) {
|
|
471
|
+
console.error("[Observyze SDK] Error during shutdown flush:", error);
|
|
472
|
+
}
|
|
473
|
+
if (this.config.debug) {
|
|
474
|
+
console.log("[Observyze SDK] Shutdown complete");
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
/**
|
|
478
|
+
* Get current buffer size
|
|
479
|
+
*/
|
|
480
|
+
get bufferSize() {
|
|
481
|
+
return this.traceBuffer.length;
|
|
482
|
+
}
|
|
483
|
+
/**
|
|
484
|
+
* Get SDK configuration
|
|
485
|
+
*/
|
|
486
|
+
getConfig() {
|
|
487
|
+
return { ...this.config };
|
|
488
|
+
}
|
|
489
|
+
/**
|
|
490
|
+
* Wrap an LLM client (OpenAI, Anthropic) to enable auto-instrumentation
|
|
491
|
+
*
|
|
492
|
+
* @example
|
|
493
|
+
* ```typescript
|
|
494
|
+
* import OpenAI from 'openai'
|
|
495
|
+
* import { ObservyzeClient } from '@observyze/sdk'
|
|
496
|
+
*
|
|
497
|
+
* const nw = new ObservyzeClient({ apiKey: 'your-api-key' })
|
|
498
|
+
* const openai = new OpenAI({ apiKey: 'openai-key' })
|
|
499
|
+
*
|
|
500
|
+
* // Wrap the client to enable auto-instrumentation
|
|
501
|
+
* nw.wrap(openai)
|
|
502
|
+
*
|
|
503
|
+
* // All calls are now automatically traced
|
|
504
|
+
* const response = await openai.chat.completions.create({
|
|
505
|
+
* model: 'gpt-4',
|
|
506
|
+
* messages: [{ role: 'user', content: 'Hello!' }]
|
|
507
|
+
* })
|
|
508
|
+
* ```
|
|
509
|
+
*/
|
|
510
|
+
wrap(client) {
|
|
511
|
+
const { wrap: wrapClient } = (init_instrumentation(), __toCommonJS(instrumentation_exports));
|
|
512
|
+
return wrapClient(client, this);
|
|
513
|
+
}
|
|
514
|
+
/**
|
|
515
|
+
* Sync local agent .history file to Observyze cloud
|
|
516
|
+
* Parses JSON/NDJSON agent history and sends to ingestion endpoint.
|
|
517
|
+
*/
|
|
518
|
+
async syncLocalHistory(filePath) {
|
|
519
|
+
try {
|
|
520
|
+
if (typeof process === "undefined" || !process.versions?.node) {
|
|
521
|
+
throw new Error("syncLocalHistory is only available in Node.js environments");
|
|
522
|
+
}
|
|
523
|
+
const fs = __require("fs");
|
|
524
|
+
const path = __require("path");
|
|
525
|
+
const fullPath = path.resolve(process.cwd(), filePath);
|
|
526
|
+
if (!fs.existsSync(fullPath)) {
|
|
527
|
+
throw new Error(`History file not found: ${fullPath}`);
|
|
528
|
+
}
|
|
529
|
+
const content = fs.readFileSync(fullPath, "utf-8");
|
|
530
|
+
let items = [];
|
|
531
|
+
try {
|
|
532
|
+
items = JSON.parse(content);
|
|
533
|
+
} catch (e) {
|
|
534
|
+
items = content.split("\n").filter((l) => l.trim()).map((l) => JSON.parse(l));
|
|
535
|
+
}
|
|
536
|
+
if (!Array.isArray(items)) {
|
|
537
|
+
items = [items];
|
|
538
|
+
}
|
|
539
|
+
if (this.config.debug) {
|
|
540
|
+
console.log(`[Observyze SDK] Syncing ${items.length} traces from ${filePath}`);
|
|
541
|
+
}
|
|
542
|
+
for (let i = 0; i < items.length; i += this.config.batchSize) {
|
|
543
|
+
const batch = items.slice(i, i + this.config.batchSize);
|
|
544
|
+
const response = await fetch(`${this.config.endpoint}/api/v1/ingest/batch`, {
|
|
545
|
+
method: "POST",
|
|
546
|
+
headers: {
|
|
547
|
+
"Content-Type": "application/json",
|
|
548
|
+
"Authorization": `Bearer ${this.config.apiKey}`
|
|
549
|
+
},
|
|
550
|
+
body: JSON.stringify({ traces: batch })
|
|
551
|
+
});
|
|
552
|
+
if (!response.ok) {
|
|
553
|
+
const errorBody = await response.text();
|
|
554
|
+
throw new Error(`Batch sync failed: ${response.status} ${errorBody}`);
|
|
555
|
+
}
|
|
556
|
+
if (this.config.debug) {
|
|
557
|
+
console.log(`[Observyze SDK] Synced batch of ${batch.length} traces from local history`);
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
} catch (err) {
|
|
561
|
+
console.error("[Observyze SDK] Failed to sync local history:", err);
|
|
562
|
+
throw err;
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
/**
|
|
566
|
+
* Industry-grade PII Redaction (Compliance & RBAC)
|
|
567
|
+
*
|
|
568
|
+
* Recursively scrubs PII from trace data before transmission to the cloud.
|
|
569
|
+
* Coverage: emails, JWTs, bearer tokens, AWS/API keys, SSNs, credit cards,
|
|
570
|
+
* phone numbers (US + E.164), IPv4/IPv6, passport numbers, ZIP codes, plus
|
|
571
|
+
* key-based redaction for sensitive JSON fields (password, token, api_key, etc.).
|
|
572
|
+
*
|
|
573
|
+
* Design:
|
|
574
|
+
* - Pure function, never mutates the original object
|
|
575
|
+
* - Depth-limited to 16 levels to prevent stack overflow on deep agent outputs
|
|
576
|
+
* - Key-aware: sensitive key names are fully redacted regardless of value format
|
|
577
|
+
*/
|
|
578
|
+
static PII_PATTERNS = [
|
|
579
|
+
{ pattern: /\b[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}\b/gi, label: "[EMAIL_REDACTED]" },
|
|
580
|
+
{ pattern: /\beyJ[A-Za-z0-9_\-]+\.eyJ[A-Za-z0-9_\-]+\.[A-Za-z0-9_\-]+\b/g, label: "[JWT_REDACTED]" },
|
|
581
|
+
{ pattern: /\b(Bearer|Token|Basic)\s+[A-Za-z0-9\-.~+\/]+=*\b/gi, label: "[AUTH_TOKEN_REDACTED]" },
|
|
582
|
+
{ pattern: /\b(AKIA|ASIA|AROA|ANPA|ANVA|AIDA)[A-Z0-9]{16}\b/g, label: "[AWS_KEY_REDACTED]" },
|
|
583
|
+
{ pattern: /\b(sk-[A-Za-z0-9\-]{20,}|pk-[A-Za-z0-9\-]{20,}|ob_[A-Za-z0-9]{20,}|ghp_[A-Za-z0-9]{36,}|gho_[A-Za-z0-9]{36,})\b/g, label: "[API_KEY_REDACTED]" },
|
|
584
|
+
{ pattern: /\b\d{3}-\d{2}-\d{4}\b/g, label: "[SSN_REDACTED]" },
|
|
585
|
+
{ pattern: /\b(?:\d[ \-]?){13,18}\d\b/g, label: "[CC_REDACTED]" },
|
|
586
|
+
{ pattern: /(?:\+1[\s.\-]?)?\(?\d{3}\)?[\s.\-]?\d{3}[\s.\-]?\d{4}\b/g, label: "[PHONE_REDACTED]" },
|
|
587
|
+
{ pattern: /\+\d{1,3}[\s.\-]?\(?\d{1,4}\)?[\s.\-]?\d{1,4}[\s.\-]?\d{1,9}/g, label: "[PHONE_REDACTED]" },
|
|
588
|
+
{ pattern: /\b(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\b/g, label: "[IP_REDACTED]" },
|
|
589
|
+
{ pattern: /\b(?:[0-9a-fA-F]{1,4}:){2,7}[0-9a-fA-F]{1,4}\b/g, label: "[IP_REDACTED]" }
|
|
590
|
+
];
|
|
591
|
+
static SENSITIVE_KEYS = /* @__PURE__ */ new Set([
|
|
592
|
+
"password",
|
|
593
|
+
"passwd",
|
|
594
|
+
"secret",
|
|
595
|
+
"token",
|
|
596
|
+
"apikey",
|
|
597
|
+
"api_key",
|
|
598
|
+
"accesstoken",
|
|
599
|
+
"access_token",
|
|
600
|
+
"refreshtoken",
|
|
601
|
+
"refresh_token",
|
|
602
|
+
"authorization",
|
|
603
|
+
"auth",
|
|
604
|
+
"credential",
|
|
605
|
+
"credentials",
|
|
606
|
+
"private_key",
|
|
607
|
+
"privatekey",
|
|
608
|
+
"client_secret",
|
|
609
|
+
"clientsecret",
|
|
610
|
+
"ssn",
|
|
611
|
+
"social_security",
|
|
612
|
+
"dob",
|
|
613
|
+
"date_of_birth",
|
|
614
|
+
"dateofbirth",
|
|
615
|
+
"passport",
|
|
616
|
+
"passport_number",
|
|
617
|
+
"credit_card",
|
|
618
|
+
"creditcard",
|
|
619
|
+
"card_number",
|
|
620
|
+
"cardnumber",
|
|
621
|
+
"cvv",
|
|
622
|
+
"cvc",
|
|
623
|
+
"pin",
|
|
624
|
+
"bank_account",
|
|
625
|
+
"routing_number"
|
|
626
|
+
]);
|
|
627
|
+
static isSensitiveKey(key) {
|
|
628
|
+
const normalized = key.toLowerCase().replace(/-/g, "_");
|
|
629
|
+
if (_ObservyzeClient.SENSITIVE_KEYS.has(normalized)) return true;
|
|
630
|
+
const segments = normalized.split("_");
|
|
631
|
+
for (const segment of segments) {
|
|
632
|
+
if (_ObservyzeClient.SENSITIVE_KEYS.has(segment)) return true;
|
|
633
|
+
}
|
|
634
|
+
return false;
|
|
635
|
+
}
|
|
636
|
+
sanitizePII(data, depth = 0) {
|
|
637
|
+
if (depth > 16) return "[MAX_DEPTH_EXCEEDED]";
|
|
638
|
+
if (data === null || data === void 0) return data;
|
|
639
|
+
if (typeof data === "string") {
|
|
640
|
+
let result = data;
|
|
641
|
+
for (const { pattern, label } of _ObservyzeClient.PII_PATTERNS) {
|
|
642
|
+
pattern.lastIndex = 0;
|
|
643
|
+
result = result.replace(pattern, label);
|
|
644
|
+
}
|
|
645
|
+
return result;
|
|
646
|
+
}
|
|
647
|
+
if (typeof data === "number" || typeof data === "boolean") return data;
|
|
648
|
+
if (Array.isArray(data)) return data.map((item) => this.sanitizePII(item, depth + 1));
|
|
649
|
+
if (typeof data === "object") {
|
|
650
|
+
const sanitized = {};
|
|
651
|
+
for (const [k, v] of Object.entries(data)) {
|
|
652
|
+
sanitized[k] = _ObservyzeClient.isSensitiveKey(k) ? "[REDACTED]" : this.sanitizePII(v, depth + 1);
|
|
653
|
+
}
|
|
654
|
+
return sanitized;
|
|
655
|
+
}
|
|
656
|
+
return data;
|
|
657
|
+
}
|
|
658
|
+
};
|
|
659
|
+
|
|
660
|
+
// src/index.ts
|
|
661
|
+
init_types();
|
|
662
|
+
init_instrumentation();
|
|
663
|
+
export {
|
|
664
|
+
ObservyzeClient,
|
|
665
|
+
ObservyzeSpanExporter,
|
|
666
|
+
Span,
|
|
667
|
+
SpanType,
|
|
668
|
+
Trace,
|
|
669
|
+
TraceStatus,
|
|
670
|
+
wrap,
|
|
671
|
+
wrapAnthropic,
|
|
672
|
+
wrapOpenAI
|
|
673
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { a as ObservyzeExporterConfig, b as ObservyzeSpanExporter } from '../index-DEorAmFu.mjs';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { a as ObservyzeExporterConfig, b as ObservyzeSpanExporter } from '../index-DEorAmFu.js';
|