@probelabs/probe 0.6.0-rc147 → 0.6.0-rc149

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.
@@ -1,358 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/agent/telemetry.js
21
- var telemetry_exports = {};
22
- __export(telemetry_exports, {
23
- TelemetryConfig: () => TelemetryConfig,
24
- initializeTelemetryFromOptions: () => initializeTelemetryFromOptions
25
- });
26
- module.exports = __toCommonJS(telemetry_exports);
27
- var import_sdk_node = require("@opentelemetry/sdk-node");
28
- var import_resources = require("@opentelemetry/resources");
29
- var import_semantic_conventions = require("@opentelemetry/semantic-conventions");
30
- var import_api = require("@opentelemetry/api");
31
- var import_exporter_trace_otlp_http = require("@opentelemetry/exporter-trace-otlp-http");
32
- var import_sdk_trace_base = require("@opentelemetry/sdk-trace-base");
33
- var import_fs2 = require("fs");
34
- var import_path = require("path");
35
-
36
- // src/agent/fileSpanExporter.js
37
- var import_fs = require("fs");
38
- var import_core = require("@opentelemetry/core");
39
- var FileSpanExporter = class {
40
- constructor(filePath = "./traces.jsonl") {
41
- this.filePath = filePath;
42
- this.stream = (0, import_fs.createWriteStream)(filePath, { flags: "a" });
43
- this.stream.on("error", (error) => {
44
- console.error(`[FileSpanExporter] Stream error: ${error.message}`);
45
- });
46
- }
47
- /**
48
- * Export spans to file
49
- * @param {ReadableSpan[]} spans - Array of spans to export
50
- * @param {function} resultCallback - Callback to call with the export result
51
- */
52
- export(spans, resultCallback) {
53
- if (!spans || spans.length === 0) {
54
- resultCallback({ code: import_core.ExportResultCode.SUCCESS });
55
- return;
56
- }
57
- try {
58
- const timestamp = Date.now();
59
- spans.forEach((span, index) => {
60
- let parentSpanId = void 0;
61
- if (span.parentSpanContext) {
62
- parentSpanId = span.parentSpanContext.spanId;
63
- } else if (span._parentSpanContext) {
64
- parentSpanId = span._parentSpanContext.spanId;
65
- } else if (span.parent) {
66
- parentSpanId = span.parent.spanId;
67
- } else if (span._parent) {
68
- parentSpanId = span._parent.spanId;
69
- } else if (span._parentId) {
70
- parentSpanId = span._parentId;
71
- } else if (span.parentSpanId) {
72
- parentSpanId = span.parentSpanId;
73
- }
74
- const spanData = {
75
- traceId: span.spanContext().traceId,
76
- spanId: span.spanContext().spanId,
77
- parentSpanId,
78
- name: span.name,
79
- kind: span.kind,
80
- startTimeUnixNano: span.startTime[0] * 1e9 + span.startTime[1],
81
- endTimeUnixNano: span.endTime[0] * 1e9 + span.endTime[1],
82
- attributes: this.convertAttributes(span.attributes),
83
- status: span.status,
84
- events: span.events?.map((event) => ({
85
- timeUnixNano: event.time[0] * 1e9 + event.time[1],
86
- name: event.name,
87
- attributes: this.convertAttributes(event.attributes)
88
- })) || [],
89
- links: span.links?.map((link) => ({
90
- traceId: link.context.traceId,
91
- spanId: link.context.spanId,
92
- attributes: this.convertAttributes(link.attributes)
93
- })) || [],
94
- resource: {
95
- attributes: this.convertAttributes(span.resource?.attributes || {})
96
- },
97
- instrumentationLibrary: {
98
- name: span.instrumentationLibrary?.name || "unknown",
99
- version: span.instrumentationLibrary?.version || "unknown"
100
- },
101
- timestamp
102
- };
103
- this.stream.write(JSON.stringify(spanData) + "\n");
104
- });
105
- resultCallback({ code: import_core.ExportResultCode.SUCCESS });
106
- } catch (error) {
107
- console.error(`[FileSpanExporter] Export error: ${error.message}`);
108
- resultCallback({
109
- code: import_core.ExportResultCode.FAILED,
110
- error
111
- });
112
- }
113
- }
114
- /**
115
- * Convert OpenTelemetry attributes to plain object
116
- * @param {Object} attributes - OpenTelemetry attributes
117
- * @returns {Object} Plain object with string values
118
- */
119
- convertAttributes(attributes) {
120
- if (!attributes) return {};
121
- const result = {};
122
- for (const [key, value] of Object.entries(attributes)) {
123
- if (typeof value === "object" && value !== null) {
124
- result[key] = JSON.stringify(value);
125
- } else {
126
- result[key] = String(value);
127
- }
128
- }
129
- return result;
130
- }
131
- /**
132
- * Shutdown the exporter
133
- * @returns {Promise<void>}
134
- */
135
- async shutdown() {
136
- return new Promise((resolve) => {
137
- if (this.stream) {
138
- this.stream.end(() => {
139
- console.log(`[FileSpanExporter] File stream closed: ${this.filePath}`);
140
- resolve();
141
- });
142
- } else {
143
- resolve();
144
- }
145
- });
146
- }
147
- /**
148
- * Force flush any pending spans
149
- * @returns {Promise<void>}
150
- */
151
- async forceFlush() {
152
- return new Promise((resolve, reject) => {
153
- if (this.stream) {
154
- const flushTimeout = setTimeout(() => {
155
- console.warn("[FileSpanExporter] Flush timeout after 5 seconds");
156
- resolve();
157
- }, 5e3);
158
- if (this.stream.writableCorked) {
159
- this.stream.uncork();
160
- }
161
- if (this.stream.writableNeedDrain) {
162
- this.stream.once("drain", () => {
163
- clearTimeout(flushTimeout);
164
- resolve();
165
- });
166
- } else {
167
- setImmediate(() => {
168
- clearTimeout(flushTimeout);
169
- resolve();
170
- });
171
- }
172
- } else {
173
- resolve();
174
- }
175
- });
176
- }
177
- };
178
-
179
- // src/agent/telemetry.js
180
- var TelemetryConfig = class {
181
- constructor(options = {}) {
182
- this.serviceName = options.serviceName || "probe-agent";
183
- this.serviceVersion = options.serviceVersion || "1.0.0";
184
- this.enableFile = options.enableFile || false;
185
- this.enableRemote = options.enableRemote || false;
186
- this.enableConsole = options.enableConsole || false;
187
- this.filePath = options.filePath || "./traces.jsonl";
188
- this.remoteEndpoint = options.remoteEndpoint || "http://localhost:4318/v1/traces";
189
- this.sdk = null;
190
- this.tracer = null;
191
- }
192
- /**
193
- * Initialize OpenTelemetry SDK
194
- */
195
- initialize() {
196
- if (this.sdk) {
197
- console.warn("Telemetry already initialized");
198
- return;
199
- }
200
- const resource = (0, import_resources.resourceFromAttributes)({
201
- [import_semantic_conventions.ATTR_SERVICE_NAME]: this.serviceName,
202
- [import_semantic_conventions.ATTR_SERVICE_VERSION]: this.serviceVersion
203
- });
204
- const spanProcessors = [];
205
- if (this.enableFile) {
206
- try {
207
- const dir = (0, import_path.dirname)(this.filePath);
208
- if (!(0, import_fs2.existsSync)(dir)) {
209
- (0, import_fs2.mkdirSync)(dir, { recursive: true });
210
- }
211
- const fileExporter = new FileSpanExporter(this.filePath);
212
- spanProcessors.push(new import_sdk_trace_base.BatchSpanProcessor(fileExporter, {
213
- maxQueueSize: 2048,
214
- maxExportBatchSize: 512,
215
- scheduledDelayMillis: 500,
216
- exportTimeoutMillis: 3e4
217
- }));
218
- console.log(`[Telemetry] File exporter enabled, writing to: ${this.filePath}`);
219
- } catch (error) {
220
- console.error(`[Telemetry] Failed to initialize file exporter: ${error.message}`);
221
- }
222
- }
223
- if (this.enableRemote) {
224
- try {
225
- const remoteExporter = new import_exporter_trace_otlp_http.OTLPTraceExporter({
226
- url: this.remoteEndpoint
227
- });
228
- spanProcessors.push(new import_sdk_trace_base.BatchSpanProcessor(remoteExporter, {
229
- maxQueueSize: 2048,
230
- maxExportBatchSize: 512,
231
- scheduledDelayMillis: 500,
232
- exportTimeoutMillis: 3e4
233
- }));
234
- console.log(`[Telemetry] Remote exporter enabled, endpoint: ${this.remoteEndpoint}`);
235
- } catch (error) {
236
- console.error(`[Telemetry] Failed to initialize remote exporter: ${error.message}`);
237
- }
238
- }
239
- if (this.enableConsole) {
240
- const consoleExporter = new import_sdk_trace_base.ConsoleSpanExporter();
241
- spanProcessors.push(new import_sdk_trace_base.BatchSpanProcessor(consoleExporter, {
242
- maxQueueSize: 2048,
243
- maxExportBatchSize: 512,
244
- scheduledDelayMillis: 500,
245
- exportTimeoutMillis: 3e4
246
- }));
247
- console.log(`[Telemetry] Console exporter enabled`);
248
- }
249
- if (spanProcessors.length === 0) {
250
- console.log("[Telemetry] No exporters configured, telemetry will not be collected");
251
- return;
252
- }
253
- this.sdk = new import_sdk_node.NodeSDK({
254
- resource,
255
- spanProcessors
256
- });
257
- try {
258
- this.sdk.start();
259
- this.tracer = import_api.trace.getTracer(this.serviceName, this.serviceVersion);
260
- console.log(`[Telemetry] OpenTelemetry SDK initialized successfully`);
261
- } catch (error) {
262
- console.error(`[Telemetry] Failed to start OpenTelemetry SDK: ${error.message}`);
263
- }
264
- }
265
- /**
266
- * Get the tracer instance
267
- */
268
- getTracer() {
269
- return this.tracer;
270
- }
271
- /**
272
- * Create a span with the given name and attributes
273
- */
274
- createSpan(name, attributes = {}) {
275
- if (!this.tracer) {
276
- return null;
277
- }
278
- return this.tracer.startSpan(name, {
279
- attributes
280
- });
281
- }
282
- /**
283
- * Wrap a function to automatically create spans
284
- */
285
- wrapFunction(name, fn, attributes = {}) {
286
- if (!this.tracer) {
287
- return fn;
288
- }
289
- return async (...args) => {
290
- const span = this.createSpan(name, attributes);
291
- if (!span) {
292
- return fn(...args);
293
- }
294
- try {
295
- const result = await import_api.context.with(import_api.trace.setSpan(import_api.context.active(), span), () => fn(...args));
296
- span.setStatus({ code: import_api.SpanStatusCode.OK });
297
- return result;
298
- } catch (error) {
299
- span.setStatus({
300
- code: import_api.SpanStatusCode.ERROR,
301
- message: error.message
302
- });
303
- span.recordException(error);
304
- throw error;
305
- } finally {
306
- span.end();
307
- }
308
- };
309
- }
310
- /**
311
- * Force flush all pending spans
312
- */
313
- async forceFlush() {
314
- if (this.sdk) {
315
- try {
316
- const tracerProvider = import_api.trace.getTracerProvider();
317
- if (tracerProvider && typeof tracerProvider.forceFlush === "function") {
318
- await tracerProvider.forceFlush();
319
- }
320
- await new Promise((resolve) => setTimeout(resolve, 100));
321
- console.log("[Telemetry] OpenTelemetry spans flushed successfully");
322
- } catch (error) {
323
- console.error(`[Telemetry] Failed to flush OpenTelemetry spans: ${error.message}`);
324
- }
325
- }
326
- }
327
- /**
328
- * Shutdown telemetry
329
- */
330
- async shutdown() {
331
- if (this.sdk) {
332
- try {
333
- await this.sdk.shutdown();
334
- console.log("[Telemetry] OpenTelemetry SDK shutdown successfully");
335
- } catch (error) {
336
- console.error(`[Telemetry] Failed to shutdown OpenTelemetry SDK: ${error.message}`);
337
- }
338
- }
339
- }
340
- };
341
- function initializeTelemetryFromOptions(options) {
342
- const config = new TelemetryConfig({
343
- serviceName: "probe-agent",
344
- serviceVersion: "1.0.0",
345
- enableFile: options.traceFile !== void 0,
346
- enableRemote: options.traceRemote !== void 0,
347
- enableConsole: options.traceConsole,
348
- filePath: options.traceFile || "./traces.jsonl",
349
- remoteEndpoint: options.traceRemote || "http://localhost:4318/v1/traces"
350
- });
351
- config.initialize();
352
- return config;
353
- }
354
- // Annotate the CommonJS export names for ESM import in node:
355
- 0 && (module.exports = {
356
- TelemetryConfig,
357
- initializeTelemetryFromOptions
358
- });
@@ -1,360 +0,0 @@
1
- import { trace, context, SpanStatusCode } from '@opentelemetry/api';
2
-
3
- /**
4
- * Application-specific tracing layer for probe-agent
5
- * Provides higher-level tracing functions for AI operations and tool calls
6
- */
7
- export class AppTracer {
8
- constructor(telemetryConfig, sessionId = null) {
9
- this.telemetryConfig = telemetryConfig;
10
- this.tracer = telemetryConfig?.getTracer();
11
- this.sessionId = sessionId || this.generateSessionId();
12
- this.traceId = this.generateTraceId();
13
- }
14
-
15
- /**
16
- * Generate a unique session ID
17
- */
18
- generateSessionId() {
19
- return Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
20
- }
21
-
22
- /**
23
- * Generate trace ID from session ID for consistent tracing
24
- */
25
- generateTraceId() {
26
- if (!this.sessionId) return null;
27
-
28
- // Create a deterministic trace ID from session ID
29
- const hash = this.hashString(this.sessionId);
30
- return hash.padEnd(32, '0').substring(0, 32);
31
- }
32
-
33
- /**
34
- * Simple hash function for session ID
35
- */
36
- hashString(str) {
37
- let hash = 0;
38
- for (let i = 0; i < str.length; i++) {
39
- const char = str.charCodeAt(i);
40
- hash = ((hash << 5) - hash) + char;
41
- hash = hash & hash; // Convert to 32bit integer
42
- }
43
- return Math.abs(hash).toString(16);
44
- }
45
-
46
- /**
47
- * Check if tracing is enabled
48
- */
49
- isEnabled() {
50
- return this.tracer !== null;
51
- }
52
-
53
- /**
54
- * Create a root span for the agent session
55
- */
56
- createSessionSpan(attributes = {}) {
57
- if (!this.isEnabled()) return null;
58
-
59
- return this.tracer.startSpan('agent.session', {
60
- attributes: {
61
- 'session.id': this.sessionId,
62
- 'trace.id': this.traceId,
63
- ...attributes,
64
- },
65
- });
66
- }
67
-
68
- /**
69
- * Create a span for AI model requests
70
- */
71
- createAISpan(modelName, provider, attributes = {}) {
72
- if (!this.isEnabled()) return null;
73
-
74
- return this.tracer.startSpan('ai.request', {
75
- attributes: {
76
- 'ai.model': modelName,
77
- 'ai.provider': provider,
78
- 'session.id': this.sessionId,
79
- ...attributes,
80
- },
81
- });
82
- }
83
-
84
- /**
85
- * Create a span for tool calls
86
- */
87
- createToolSpan(toolName, attributes = {}) {
88
- if (!this.isEnabled()) return null;
89
-
90
- return this.tracer.startSpan('tool.call', {
91
- attributes: {
92
- 'tool.name': toolName,
93
- 'session.id': this.sessionId,
94
- ...attributes,
95
- },
96
- });
97
- }
98
-
99
- /**
100
- * Create a span for code search operations
101
- */
102
- createSearchSpan(query, attributes = {}) {
103
- if (!this.isEnabled()) return null;
104
-
105
- return this.tracer.startSpan('search.query', {
106
- attributes: {
107
- 'search.query': query,
108
- 'session.id': this.sessionId,
109
- ...attributes,
110
- },
111
- });
112
- }
113
-
114
- /**
115
- * Create a span for code extraction operations
116
- */
117
- createExtractSpan(files, attributes = {}) {
118
- if (!this.isEnabled()) return null;
119
-
120
- return this.tracer.startSpan('extract.files', {
121
- attributes: {
122
- 'extract.file_count': Array.isArray(files) ? files.length : 1,
123
- 'extract.files': Array.isArray(files) ? files.join(',') : files,
124
- 'session.id': this.sessionId,
125
- ...attributes,
126
- },
127
- });
128
- }
129
-
130
- /**
131
- * Create a span for agent iterations
132
- */
133
- createIterationSpan(iteration, attributes = {}) {
134
- if (!this.isEnabled()) return null;
135
-
136
- return this.tracer.startSpan('agent.iteration', {
137
- attributes: {
138
- 'iteration.number': iteration,
139
- 'session.id': this.sessionId,
140
- ...attributes,
141
- },
142
- });
143
- }
144
-
145
- /**
146
- * Create a span for delegation operations
147
- */
148
- createDelegationSpan(task, attributes = {}) {
149
- if (!this.isEnabled()) return null;
150
-
151
- return this.tracer.startSpan('agent.delegation', {
152
- attributes: {
153
- 'delegation.task': task.substring(0, 200) + (task.length > 200 ? '...' : ''),
154
- 'delegation.task_length': task.length,
155
- 'session.id': this.sessionId,
156
- ...attributes,
157
- },
158
- });
159
- }
160
-
161
- /**
162
- * Create a span for JSON validation operations
163
- */
164
- createJsonValidationSpan(responseLength, attributes = {}) {
165
- if (!this.isEnabled()) return null;
166
-
167
- return this.tracer.startSpan('validation.json', {
168
- attributes: {
169
- 'validation.response_length': responseLength,
170
- 'session.id': this.sessionId,
171
- ...attributes,
172
- },
173
- });
174
- }
175
-
176
- /**
177
- * Create a span for Mermaid validation operations
178
- */
179
- createMermaidValidationSpan(diagramCount, attributes = {}) {
180
- if (!this.isEnabled()) return null;
181
-
182
- return this.tracer.startSpan('validation.mermaid', {
183
- attributes: {
184
- 'validation.diagram_count': diagramCount,
185
- 'session.id': this.sessionId,
186
- ...attributes,
187
- },
188
- });
189
- }
190
-
191
- /**
192
- * Create a span for schema processing operations
193
- */
194
- createSchemaProcessingSpan(schemaType, attributes = {}) {
195
- if (!this.isEnabled()) return null;
196
-
197
- return this.tracer.startSpan('schema.processing', {
198
- attributes: {
199
- 'schema.type': schemaType,
200
- 'session.id': this.sessionId,
201
- ...attributes,
202
- },
203
- });
204
- }
205
-
206
- /**
207
- * Record delegation events
208
- */
209
- recordDelegationEvent(eventType, data = {}) {
210
- if (!this.isEnabled()) return;
211
-
212
- this.addEvent(`delegation.${eventType}`, {
213
- 'session.id': this.sessionId,
214
- ...data
215
- });
216
- }
217
-
218
- /**
219
- * Record JSON validation events
220
- */
221
- recordJsonValidationEvent(eventType, data = {}) {
222
- if (!this.isEnabled()) return;
223
-
224
- this.addEvent(`json_validation.${eventType}`, {
225
- 'session.id': this.sessionId,
226
- ...data
227
- });
228
- }
229
-
230
- /**
231
- * Record Mermaid validation events
232
- */
233
- recordMermaidValidationEvent(eventType, data = {}) {
234
- if (!this.isEnabled()) return;
235
-
236
- this.addEvent(`mermaid_validation.${eventType}`, {
237
- 'session.id': this.sessionId,
238
- ...data
239
- });
240
- }
241
-
242
- /**
243
- * Add an event to the current or most recent span
244
- */
245
- addEvent(name, attributes = {}) {
246
- if (!this.isEnabled()) return;
247
-
248
- // Try to add to the current span in context
249
- const activeSpan = trace.getActiveSpan();
250
- if (activeSpan) {
251
- activeSpan.addEvent(name, {
252
- 'session.id': this.sessionId,
253
- ...attributes,
254
- });
255
- } else {
256
- // Fallback: log as structured data if no active span
257
- if (this.telemetryConfig?.enableConsole) {
258
- console.log(`[Event] ${name}:`, attributes);
259
- }
260
- }
261
- }
262
-
263
- /**
264
- * Set attributes on the current span
265
- */
266
- setAttributes(attributes) {
267
- if (!this.isEnabled()) return;
268
-
269
- const activeSpan = trace.getActiveSpan();
270
- if (activeSpan) {
271
- activeSpan.setAttributes({
272
- 'session.id': this.sessionId,
273
- ...attributes,
274
- });
275
- }
276
- }
277
-
278
- /**
279
- * Wrap a function with automatic span creation
280
- */
281
- wrapFunction(spanName, fn, attributes = {}) {
282
- if (!this.isEnabled()) {
283
- return fn;
284
- }
285
-
286
- return async (...args) => {
287
- const span = this.tracer.startSpan(spanName, {
288
- attributes: {
289
- 'session.id': this.sessionId,
290
- ...attributes,
291
- },
292
- });
293
-
294
- try {
295
- const result = await context.with(trace.setSpan(context.active(), span), () => fn(...args));
296
- span.setStatus({ code: SpanStatusCode.OK });
297
- return result;
298
- } catch (error) {
299
- span.setStatus({
300
- code: SpanStatusCode.ERROR,
301
- message: error.message,
302
- });
303
- span.recordException(error);
304
- throw error;
305
- } finally {
306
- span.end();
307
- }
308
- };
309
- }
310
-
311
- /**
312
- * Execute a function within a span context
313
- */
314
- async withSpan(spanName, fn, attributes = {}) {
315
- if (!this.isEnabled()) {
316
- return fn();
317
- }
318
-
319
- const span = this.tracer.startSpan(spanName, {
320
- attributes: {
321
- 'session.id': this.sessionId,
322
- ...attributes,
323
- },
324
- });
325
-
326
- try {
327
- const result = await context.with(trace.setSpan(context.active(), span), () => fn());
328
- span.setStatus({ code: SpanStatusCode.OK });
329
- return result;
330
- } catch (error) {
331
- span.setStatus({
332
- code: SpanStatusCode.ERROR,
333
- message: error.message,
334
- });
335
- span.recordException(error);
336
- throw error;
337
- } finally {
338
- span.end();
339
- }
340
- }
341
-
342
-
343
- /**
344
- * Force flush all pending spans
345
- */
346
- async flush() {
347
- if (this.telemetryConfig) {
348
- await this.telemetryConfig.forceFlush();
349
- }
350
- }
351
-
352
- /**
353
- * Shutdown tracing
354
- */
355
- async shutdown() {
356
- if (this.telemetryConfig) {
357
- await this.telemetryConfig.shutdown();
358
- }
359
- }
360
- }