teckel-ai 0.3.6 → 0.5.1

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/dist/index.d.ts CHANGED
@@ -1,214 +1,179 @@
1
1
  import { z } from 'zod';
2
2
 
3
3
  /**
4
- * Type definitions for teckel-ai SDK v0.3.6
5
- * Simple, clean types matching existing database schema
6
- */
7
- /**
8
- * SDK Configuration
4
+ * Type definitions for teckel-ai SDK
9
5
  */
10
6
  interface TeckelConfig {
7
+ /** Teckel API key (tk_live_...) */
11
8
  apiKey: string;
9
+ /** API endpoint (default: https://app.teckel.ai/api) */
12
10
  endpoint?: string;
11
+ /** Enable debug logging */
13
12
  debug?: boolean;
13
+ /** Network timeout in ms (default: 5000) */
14
14
  timeoutMs?: number;
15
15
  }
16
16
  /**
17
- * Conversation options
18
- * sessionRef IS the conversation identifier
19
- *
20
- * Naming convention:
21
- * - *Ref = Client-provided identifier (TEXT)
22
- * - *Id = Server-generated internal ID (UUID)
23
- */
24
- interface ConversationOptions {
25
- sessionRef?: string;
26
- userRef?: string;
27
- metadata?: Record<string, unknown>;
28
- }
29
- /**
30
- * Document structure for RAG systems
31
- * Matches existing documents + chunk_events schema
17
+ * Document/chunk from your RAG pipeline.
18
+ * The `id` field is your stable identifier - server generates internal UUIDs via deterministic hashing.
32
19
  */
33
20
  interface Document {
34
- documentRef: string;
35
- documentName: string;
36
- documentText: string;
37
- documentLastUpdated?: string;
38
- sourceUri?: string;
39
- sourceType?: string;
21
+ /** Your document identifier (any format: "overview.md", "doc-123", etc.) */
22
+ id: string;
23
+ /** Human-readable document name */
24
+ name: string;
25
+ /** The actual text/chunk content */
26
+ text: string;
27
+ /** ISO 8601 timestamp - enables version tracking */
28
+ lastUpdated?: string;
29
+ /** Link to source (URL, intranet, file://) */
30
+ url?: string;
31
+ /** Storage platform: confluence, slack, gdrive, etc. */
32
+ source?: string;
33
+ /** File format: pdf, docx, md, etc. */
34
+ fileFormat?: string;
35
+ /** Vector similarity score (0-1) */
40
36
  similarity?: number;
37
+ /** Position in results */
41
38
  rank?: number;
39
+ /** Document owner email */
42
40
  ownerEmail?: string;
43
- documentType?: string;
44
41
  }
45
- /**
46
- * Token usage tracking
47
- */
48
42
  interface TokenUsage {
49
43
  prompt: number;
50
44
  completion: number;
51
45
  total: number;
52
46
  }
53
47
  /**
54
- * Trace data for a single query-response interaction
55
- * Matches existing traces table schema
48
+ * Trace data for a single query-response interaction.
49
+ * Sessions are created implicitly when traces share the same sessionId.
56
50
  */
57
51
  interface TraceData {
52
+ /** User's question/prompt */
58
53
  query: string;
54
+ /** LLM's response */
59
55
  response: string;
56
+ /** Model name (e.g., 'gpt-4') */
60
57
  model?: string;
61
- responseTimeMs?: number;
62
- documents?: Document[];
58
+ /** Response time in milliseconds */
59
+ latencyMs?: number;
60
+ /** Token usage */
63
61
  tokens?: TokenUsage;
62
+ /** Source documents used in RAG */
63
+ documents?: Document[];
64
+ /** Groups traces into a session (any string up to 200 chars, OTEL compatible) */
65
+ sessionId?: string;
66
+ /** User identifier */
67
+ userId?: string;
68
+ /** Client-provided trace ID (UUID, auto-generated if omitted) */
69
+ traceId?: string;
70
+ /** LLM system prompt/instructions */
71
+ systemPrompt?: string;
72
+ /** Custom metadata (max 10KB) */
64
73
  metadata?: Record<string, unknown>;
65
- traceRef?: string;
66
- userRef?: string;
67
74
  }
68
- /**
69
- * Feedback types
70
- */
71
75
  type FeedbackType = 'thumbs_up' | 'thumbs_down' | 'flag' | 'rating';
72
76
  /**
73
- * User feedback signal
77
+ * User feedback signal. Target either a specific trace or an entire session.
74
78
  */
75
79
  interface FeedbackData {
80
+ /** Target trace (UUID) */
81
+ traceId?: string;
82
+ /** Target session (any string up to 200 chars) */
83
+ sessionId?: string;
84
+ /** Feedback type */
76
85
  type: FeedbackType;
86
+ /** For ratings: '1'-'5' */
77
87
  value?: string;
88
+ /** Optional comment */
78
89
  comment?: string;
79
- traceRef?: string;
80
90
  }
81
- /**
82
- * Result returned when a trace is created
83
- */
84
91
  interface TraceResult {
85
- traceRef: string;
86
- turnNumber: number;
92
+ traceId: string;
93
+ sessionId?: string;
94
+ chunkCount: number;
95
+ }
96
+ interface FeedbackResult {
97
+ feedbackId: string;
98
+ type: FeedbackType;
99
+ traceId?: string;
100
+ sessionId?: string;
87
101
  }
88
102
 
89
103
  /**
90
- * Conversation class for teckel-ai SDK v0.3.6
91
- * Manages a single conversation with fire-and-forget semantics
104
+ * TeckelTracer - Fire-and-forget trace collection for AI applications
92
105
  */
93
106
 
94
- /** Internal type - sessionRef is guaranteed by TeckelTracer.start() */
95
- interface ResolvedConversationOptions extends ConversationOptions {
96
- sessionRef: string;
97
- }
98
- declare class Conversation {
107
+ declare class TeckelTracer {
99
108
  private readonly apiKey;
100
109
  private readonly endpoint;
101
- private readonly sessionRef;
102
- private readonly userRef?;
103
- private readonly metadata?;
104
- private readonly startedAt;
105
110
  private readonly debug;
106
111
  private readonly timeoutMs;
107
- private turnCount;
108
- private startPromise;
109
112
  private sendQueue;
110
- constructor(apiKey: string, endpoint: string, options: ResolvedConversationOptions, debug?: boolean, extras?: {
111
- timeoutMs: number;
112
- });
113
- /**
114
- * Record a trace (single query-response interaction)
115
- * Fire-and-forget by default - never blocks
116
- * For serverless, call flush() before function termination
117
- */
118
- trace(data: TraceData): TraceResult | void;
113
+ constructor(config: TeckelConfig);
119
114
  /**
120
- * Add user feedback signal
121
- * Never throws - gracefully handles errors
115
+ * Record a trace. Fire-and-forget - call flush() in serverless before termination.
122
116
  */
123
- feedback(data: FeedbackData): Promise<void>;
117
+ trace(data: TraceData): void;
124
118
  /**
125
- * End the conversation
126
- * Flushes all pending traces before sending end signal
127
- * Never throws - gracefully handles errors
119
+ * Submit feedback for a trace or session.
128
120
  */
129
- end(): Promise<void>;
121
+ feedback(data: FeedbackData): void;
130
122
  /**
131
- * Read-only properties
132
- */
133
- get id(): string;
134
- get turns(): number;
135
- get started(): Date;
136
- private fetchWithRetry;
137
- private _startConversation;
138
- private _sendTrace;
139
- private _sendFeedback;
140
- private _endConversation;
141
- private enqueueSend;
142
- /**
143
- * Flush queued sends with a bounded timeout.
144
- * Returns when the queue is empty or the timeout elapses (whichever comes first).
123
+ * Wait for queued requests to complete. Essential for serverless environments.
145
124
  */
146
125
  flush(timeoutMs?: number): Promise<void>;
126
+ private send;
127
+ private fetchWithRetry;
128
+ private enqueue;
129
+ private logValidationError;
130
+ private logHttpError;
147
131
  }
148
132
 
149
133
  /**
150
- * TeckelTracer - Main SDK class for teckel-ai v0.3.6
151
- * Simple, lightweight SDK for AI conversation tracking
152
- */
153
-
154
- declare class TeckelTracer {
155
- private readonly apiKey;
156
- private readonly endpoint;
157
- private readonly debug;
158
- private readonly timeoutMs;
159
- constructor(config: TeckelConfig);
160
- /**
161
- * Start a new conversation
162
- * sessionRef IS the public conversation identifier
163
- * If not provided, auto-generates one as 'auto:{8-char-uuid}'
164
- */
165
- start(options?: ConversationOptions): Conversation;
166
- }
167
-
168
- /**
169
- * Zod validation schemas for teckel-ai SDK v0.3.6
134
+ * Zod validation schemas for teckel-ai SDK
170
135
  */
171
136
 
172
- /**
173
- * Document schema
174
- */
137
+ /** Payload size limits */
138
+ declare const TRACE_SIZE_LIMITS: {
139
+ readonly METADATA_MAX_BYTES: 10000;
140
+ readonly TRACE_MAX_BYTES: 3000000;
141
+ readonly MAX_DOCUMENTS: 15;
142
+ };
175
143
  declare const DocumentSchema: z.ZodObject<{
176
- documentRef: z.ZodString;
177
- documentName: z.ZodString;
178
- documentText: z.ZodString;
179
- documentLastUpdated: z.ZodOptional<z.ZodString>;
180
- sourceUri: z.ZodOptional<z.ZodString>;
181
- sourceType: z.ZodOptional<z.ZodString>;
144
+ id: z.ZodString;
145
+ name: z.ZodString;
146
+ text: z.ZodString;
147
+ lastUpdated: z.ZodOptional<z.ZodString>;
148
+ url: z.ZodOptional<z.ZodString>;
149
+ source: z.ZodOptional<z.ZodString>;
150
+ fileFormat: z.ZodOptional<z.ZodString>;
182
151
  similarity: z.ZodOptional<z.ZodNumber>;
183
152
  rank: z.ZodOptional<z.ZodNumber>;
184
153
  ownerEmail: z.ZodOptional<z.ZodString>;
185
- documentType: z.ZodOptional<z.ZodString>;
186
154
  }, "strip", z.ZodTypeAny, {
187
- documentRef: string;
188
- documentName: string;
189
- documentText: string;
190
- documentLastUpdated?: string | undefined;
191
- sourceUri?: string | undefined;
192
- sourceType?: string | undefined;
155
+ id: string;
156
+ name: string;
157
+ text: string;
158
+ lastUpdated?: string | undefined;
159
+ url?: string | undefined;
160
+ source?: string | undefined;
161
+ fileFormat?: string | undefined;
193
162
  similarity?: number | undefined;
194
163
  rank?: number | undefined;
195
164
  ownerEmail?: string | undefined;
196
- documentType?: string | undefined;
197
165
  }, {
198
- documentRef: string;
199
- documentName: string;
200
- documentText: string;
201
- documentLastUpdated?: string | undefined;
202
- sourceUri?: string | undefined;
203
- sourceType?: string | undefined;
166
+ id: string;
167
+ name: string;
168
+ text: string;
169
+ lastUpdated?: string | undefined;
170
+ url?: string | undefined;
171
+ source?: string | undefined;
172
+ fileFormat?: string | undefined;
204
173
  similarity?: number | undefined;
205
174
  rank?: number | undefined;
206
175
  ownerEmail?: string | undefined;
207
- documentType?: string | undefined;
208
176
  }>;
209
- /**
210
- * Token usage schema
211
- */
212
177
  declare const TokenUsageSchema: z.ZodObject<{
213
178
  prompt: z.ZodNumber;
214
179
  completion: z.ZodNumber;
@@ -222,48 +187,11 @@ declare const TokenUsageSchema: z.ZodObject<{
222
187
  completion: number;
223
188
  total: number;
224
189
  }>;
225
- /**
226
- * Trace data schema
227
- */
228
- declare const TraceDataSchema: z.ZodObject<{
190
+ declare const TraceDataSchema: z.ZodEffects<z.ZodObject<{
229
191
  query: z.ZodString;
230
192
  response: z.ZodString;
231
193
  model: z.ZodOptional<z.ZodString>;
232
- responseTimeMs: z.ZodOptional<z.ZodNumber>;
233
- documents: z.ZodOptional<z.ZodArray<z.ZodObject<{
234
- documentRef: z.ZodString;
235
- documentName: z.ZodString;
236
- documentText: z.ZodString;
237
- documentLastUpdated: z.ZodOptional<z.ZodString>;
238
- sourceUri: z.ZodOptional<z.ZodString>;
239
- sourceType: z.ZodOptional<z.ZodString>;
240
- similarity: z.ZodOptional<z.ZodNumber>;
241
- rank: z.ZodOptional<z.ZodNumber>;
242
- ownerEmail: z.ZodOptional<z.ZodString>;
243
- documentType: z.ZodOptional<z.ZodString>;
244
- }, "strip", z.ZodTypeAny, {
245
- documentRef: string;
246
- documentName: string;
247
- documentText: string;
248
- documentLastUpdated?: string | undefined;
249
- sourceUri?: string | undefined;
250
- sourceType?: string | undefined;
251
- similarity?: number | undefined;
252
- rank?: number | undefined;
253
- ownerEmail?: string | undefined;
254
- documentType?: string | undefined;
255
- }, {
256
- documentRef: string;
257
- documentName: string;
258
- documentText: string;
259
- documentLastUpdated?: string | undefined;
260
- sourceUri?: string | undefined;
261
- sourceType?: string | undefined;
262
- similarity?: number | undefined;
263
- rank?: number | undefined;
264
- ownerEmail?: string | undefined;
265
- documentType?: string | undefined;
266
- }>, "many">>;
194
+ latencyMs: z.ZodOptional<z.ZodNumber>;
267
195
  tokens: z.ZodOptional<z.ZodObject<{
268
196
  prompt: z.ZodNumber;
269
197
  completion: z.ZodNumber;
@@ -277,98 +205,185 @@ declare const TraceDataSchema: z.ZodObject<{
277
205
  completion: number;
278
206
  total: number;
279
207
  }>>;
280
- metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
281
- traceRef: z.ZodOptional<z.ZodString>;
282
- userRef: z.ZodOptional<z.ZodString>;
208
+ documents: z.ZodOptional<z.ZodArray<z.ZodObject<{
209
+ id: z.ZodString;
210
+ name: z.ZodString;
211
+ text: z.ZodString;
212
+ lastUpdated: z.ZodOptional<z.ZodString>;
213
+ url: z.ZodOptional<z.ZodString>;
214
+ source: z.ZodOptional<z.ZodString>;
215
+ fileFormat: z.ZodOptional<z.ZodString>;
216
+ similarity: z.ZodOptional<z.ZodNumber>;
217
+ rank: z.ZodOptional<z.ZodNumber>;
218
+ ownerEmail: z.ZodOptional<z.ZodString>;
219
+ }, "strip", z.ZodTypeAny, {
220
+ id: string;
221
+ name: string;
222
+ text: string;
223
+ lastUpdated?: string | undefined;
224
+ url?: string | undefined;
225
+ source?: string | undefined;
226
+ fileFormat?: string | undefined;
227
+ similarity?: number | undefined;
228
+ rank?: number | undefined;
229
+ ownerEmail?: string | undefined;
230
+ }, {
231
+ id: string;
232
+ name: string;
233
+ text: string;
234
+ lastUpdated?: string | undefined;
235
+ url?: string | undefined;
236
+ source?: string | undefined;
237
+ fileFormat?: string | undefined;
238
+ similarity?: number | undefined;
239
+ rank?: number | undefined;
240
+ ownerEmail?: string | undefined;
241
+ }>, "many">>;
242
+ sessionId: z.ZodOptional<z.ZodString>;
243
+ userId: z.ZodOptional<z.ZodString>;
244
+ traceId: z.ZodOptional<z.ZodString>;
245
+ systemPrompt: z.ZodOptional<z.ZodString>;
246
+ metadata: z.ZodEffects<z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>, Record<string, unknown> | undefined, Record<string, unknown> | undefined>;
283
247
  }, "strip", z.ZodTypeAny, {
284
248
  query: string;
285
249
  response: string;
286
250
  model?: string | undefined;
287
- responseTimeMs?: number | undefined;
251
+ latencyMs?: number | undefined;
252
+ tokens?: {
253
+ prompt: number;
254
+ completion: number;
255
+ total: number;
256
+ } | undefined;
288
257
  documents?: {
289
- documentRef: string;
290
- documentName: string;
291
- documentText: string;
292
- documentLastUpdated?: string | undefined;
293
- sourceUri?: string | undefined;
294
- sourceType?: string | undefined;
258
+ id: string;
259
+ name: string;
260
+ text: string;
261
+ lastUpdated?: string | undefined;
262
+ url?: string | undefined;
263
+ source?: string | undefined;
264
+ fileFormat?: string | undefined;
295
265
  similarity?: number | undefined;
296
266
  rank?: number | undefined;
297
267
  ownerEmail?: string | undefined;
298
- documentType?: string | undefined;
299
268
  }[] | undefined;
269
+ sessionId?: string | undefined;
270
+ userId?: string | undefined;
271
+ traceId?: string | undefined;
272
+ systemPrompt?: string | undefined;
273
+ metadata?: Record<string, unknown> | undefined;
274
+ }, {
275
+ query: string;
276
+ response: string;
277
+ model?: string | undefined;
278
+ latencyMs?: number | undefined;
300
279
  tokens?: {
301
280
  prompt: number;
302
281
  completion: number;
303
282
  total: number;
304
283
  } | undefined;
284
+ documents?: {
285
+ id: string;
286
+ name: string;
287
+ text: string;
288
+ lastUpdated?: string | undefined;
289
+ url?: string | undefined;
290
+ source?: string | undefined;
291
+ fileFormat?: string | undefined;
292
+ similarity?: number | undefined;
293
+ rank?: number | undefined;
294
+ ownerEmail?: string | undefined;
295
+ }[] | undefined;
296
+ sessionId?: string | undefined;
297
+ userId?: string | undefined;
298
+ traceId?: string | undefined;
299
+ systemPrompt?: string | undefined;
305
300
  metadata?: Record<string, unknown> | undefined;
306
- traceRef?: string | undefined;
307
- userRef?: string | undefined;
308
- }, {
301
+ }>, {
309
302
  query: string;
310
303
  response: string;
311
304
  model?: string | undefined;
312
- responseTimeMs?: number | undefined;
305
+ latencyMs?: number | undefined;
306
+ tokens?: {
307
+ prompt: number;
308
+ completion: number;
309
+ total: number;
310
+ } | undefined;
313
311
  documents?: {
314
- documentRef: string;
315
- documentName: string;
316
- documentText: string;
317
- documentLastUpdated?: string | undefined;
318
- sourceUri?: string | undefined;
319
- sourceType?: string | undefined;
312
+ id: string;
313
+ name: string;
314
+ text: string;
315
+ lastUpdated?: string | undefined;
316
+ url?: string | undefined;
317
+ source?: string | undefined;
318
+ fileFormat?: string | undefined;
320
319
  similarity?: number | undefined;
321
320
  rank?: number | undefined;
322
321
  ownerEmail?: string | undefined;
323
- documentType?: string | undefined;
324
322
  }[] | undefined;
323
+ sessionId?: string | undefined;
324
+ userId?: string | undefined;
325
+ traceId?: string | undefined;
326
+ systemPrompt?: string | undefined;
327
+ metadata?: Record<string, unknown> | undefined;
328
+ }, {
329
+ query: string;
330
+ response: string;
331
+ model?: string | undefined;
332
+ latencyMs?: number | undefined;
325
333
  tokens?: {
326
334
  prompt: number;
327
335
  completion: number;
328
336
  total: number;
329
337
  } | undefined;
338
+ documents?: {
339
+ id: string;
340
+ name: string;
341
+ text: string;
342
+ lastUpdated?: string | undefined;
343
+ url?: string | undefined;
344
+ source?: string | undefined;
345
+ fileFormat?: string | undefined;
346
+ similarity?: number | undefined;
347
+ rank?: number | undefined;
348
+ ownerEmail?: string | undefined;
349
+ }[] | undefined;
350
+ sessionId?: string | undefined;
351
+ userId?: string | undefined;
352
+ traceId?: string | undefined;
353
+ systemPrompt?: string | undefined;
330
354
  metadata?: Record<string, unknown> | undefined;
331
- traceRef?: string | undefined;
332
- userRef?: string | undefined;
333
- }>;
334
- /**
335
- * Conversation options schema
336
- */
337
- declare const ConversationOptionsSchema: z.ZodObject<{
338
- sessionRef: z.ZodOptional<z.ZodString>;
339
- userRef: z.ZodOptional<z.ZodString>;
340
- metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
341
- }, "strip", z.ZodTypeAny, {
342
- metadata?: Record<string, unknown> | undefined;
343
- userRef?: string | undefined;
344
- sessionRef?: string | undefined;
345
- }, {
346
- metadata?: Record<string, unknown> | undefined;
347
- userRef?: string | undefined;
348
- sessionRef?: string | undefined;
349
355
  }>;
350
- /**
351
- * Feedback data schema
352
- */
353
- declare const FeedbackDataSchema: z.ZodObject<{
356
+ declare const FeedbackDataSchema: z.ZodEffects<z.ZodObject<{
357
+ traceId: z.ZodOptional<z.ZodString>;
358
+ sessionId: z.ZodOptional<z.ZodString>;
354
359
  type: z.ZodEnum<["thumbs_up", "thumbs_down", "flag", "rating"]>;
355
360
  value: z.ZodOptional<z.ZodString>;
356
361
  comment: z.ZodOptional<z.ZodString>;
357
- traceRef: z.ZodOptional<z.ZodString>;
358
362
  }, "strip", z.ZodTypeAny, {
359
363
  type: "thumbs_up" | "thumbs_down" | "flag" | "rating";
360
364
  value?: string | undefined;
361
- traceRef?: string | undefined;
365
+ sessionId?: string | undefined;
366
+ traceId?: string | undefined;
367
+ comment?: string | undefined;
368
+ }, {
369
+ type: "thumbs_up" | "thumbs_down" | "flag" | "rating";
370
+ value?: string | undefined;
371
+ sessionId?: string | undefined;
372
+ traceId?: string | undefined;
373
+ comment?: string | undefined;
374
+ }>, {
375
+ type: "thumbs_up" | "thumbs_down" | "flag" | "rating";
376
+ value?: string | undefined;
377
+ sessionId?: string | undefined;
378
+ traceId?: string | undefined;
362
379
  comment?: string | undefined;
363
380
  }, {
364
381
  type: "thumbs_up" | "thumbs_down" | "flag" | "rating";
365
382
  value?: string | undefined;
366
- traceRef?: string | undefined;
383
+ sessionId?: string | undefined;
384
+ traceId?: string | undefined;
367
385
  comment?: string | undefined;
368
386
  }>;
369
- /**
370
- * Config schema
371
- */
372
387
  declare const TeckelConfigSchema: z.ZodObject<{
373
388
  apiKey: z.ZodString;
374
389
  endpoint: z.ZodOptional<z.ZodString>;
@@ -386,4 +401,4 @@ declare const TeckelConfigSchema: z.ZodObject<{
386
401
  timeoutMs?: number | undefined;
387
402
  }>;
388
403
 
389
- export { Conversation, type ConversationOptions, ConversationOptionsSchema, type Document, DocumentSchema, type FeedbackData, FeedbackDataSchema, type FeedbackType, type TeckelConfig, TeckelConfigSchema, TeckelTracer, type TokenUsage, TokenUsageSchema, type TraceData, TraceDataSchema, type TraceResult };
404
+ export { type Document, DocumentSchema, type FeedbackData, FeedbackDataSchema, type FeedbackResult, type FeedbackType, TRACE_SIZE_LIMITS, type TeckelConfig, TeckelConfigSchema, TeckelTracer, type TokenUsage, TokenUsageSchema, type TraceData, TraceDataSchema, type TraceResult };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- 'use strict';var zod=require('zod');var y=zod.z.object({documentRef:zod.z.string().min(1,"documentRef is required"),documentName:zod.z.string().min(1,"documentName is required"),documentText:zod.z.string().min(1,"documentText is required"),documentLastUpdated:zod.z.string().optional(),sourceUri:zod.z.string().optional(),sourceType:zod.z.string().optional(),similarity:zod.z.number().min(0).max(1).optional(),rank:zod.z.number().int().nonnegative().optional(),ownerEmail:zod.z.string().email().optional(),documentType:zod.z.string().optional()}),b=zod.z.object({prompt:zod.z.number().int().nonnegative(),completion:zod.z.number().int().nonnegative(),total:zod.z.number().int().nonnegative()}),l=zod.z.object({query:zod.z.string().min(1,"query is required").max(1e4,"query too long (max 10,000 characters)"),response:zod.z.string().min(1,"response is required").max(5e4,"response too long (max 50,000 characters)"),model:zod.z.string().optional(),responseTimeMs:zod.z.number().nonnegative().optional(),documents:zod.z.array(y).max(50,"Too many documents (max 50)").optional(),tokens:b.optional(),metadata:zod.z.record(zod.z.string(),zod.z.unknown()).optional(),traceRef:zod.z.string().min(1).optional(),userRef:zod.z.string().min(1).optional()}),h=zod.z.object({sessionRef:zod.z.string().min(1).optional(),userRef:zod.z.string().optional(),metadata:zod.z.record(zod.z.string(),zod.z.unknown()).optional()}),p=zod.z.object({type:zod.z.enum(["thumbs_up","thumbs_down","flag","rating"]),value:zod.z.string().optional(),comment:zod.z.string().optional(),traceRef:zod.z.string().optional()}),f=zod.z.object({apiKey:zod.z.string().min(1,"apiKey is required"),endpoint:zod.z.string().url().optional(),debug:zod.z.boolean().optional(),timeoutMs:zod.z.number().int().positive().max(6e4).optional()});var u=class{constructor(n,e,s,o=false,a={timeoutMs:5e3}){this.turnCount=0;this.sendQueue=Promise.resolve();this.apiKey=n,this.endpoint=e,this.sessionRef=s.sessionRef,this.userRef=s.userRef,this.metadata=s.metadata,this.startedAt=new Date,this.debug=o,this.timeoutMs=a.timeoutMs,this.debug&&console.log("[Teckel] Conversation started:",{sessionRef:this.sessionRef,userRef:this.userRef}),this.startPromise=this._startConversation().catch(i=>{this.debug&&console.warn("[Teckel] Start failed:",i.message);});}trace(n){try{let e=l.parse(n),s=++this.turnCount,o=e.traceRef&&e.traceRef.length>0?e.traceRef:`${this.sessionRef}:${s}`;this.debug&&console.log("[Teckel] Queueing trace:",{sessionRef:this.sessionRef,turnNumber:s,queryLength:e.query.length,responseLength:e.response.length,documentCount:e.documents?.length||0});let a={...e,traceRef:o,userRef:e.userRef||this.userRef};return this.enqueueSend(async()=>{try{await this.startPromise,await this._sendTrace(a);}catch(i){if(this.debug){let d=i instanceof Error?i.message:String(i);console.warn("[Teckel] Trace send failed (non-blocking):",d);}}}),{traceRef:o,turnNumber:s}}catch(e){this.debug&&console.warn("[Teckel] Invalid trace data:",e);}}async feedback(n){try{let e=p.parse(n);this.debug&&console.log("[Teckel] Sending feedback:",{sessionRef:this.sessionRef,type:e.type}),this.enqueueSend(async()=>{try{await this._sendFeedback(e);}catch(s){if(this.debug){let o=s instanceof Error?s.message:String(s);console.warn("[Teckel] Feedback failed:",o);}}});}catch(e){this.debug&&console.warn("[Teckel] Invalid feedback data:",e);}}async end(){let n=Date.now()-this.startedAt.getTime();this.debug&&console.log("[Teckel] Ending conversation:",{sessionRef:this.sessionRef,durationMs:n,turnCount:this.turnCount}),this.enqueueSend(async()=>{try{await this._endConversation(n);}catch(e){if(this.debug){let s=e instanceof Error?e.message:String(e);console.warn("[Teckel] End failed:",s);}}}),await this.flush();}get id(){return this.sessionRef}get turns(){return this.turnCount}get started(){return this.startedAt}async fetchWithRetry(n,e,s){let o=s?.retries??1,a=s?.retryDelayMs??250,i=0,d=r=>new Promise(T=>setTimeout(T,r));for(;;)try{let r=await fetch(n,e);if(!r.ok&&(r.status===429||r.status>=500&&r.status<=599)&&i<o){i++,this.debug&&console.warn("[Teckel] HTTP retry",{url:n,status:r.status,attempt:i}),await d(a+Math.floor(Math.random()*100));continue}return r}catch(r){if(i<o){i++,this.debug&&console.warn("[Teckel] Network retry",{url:n,attempt:i,error:r instanceof Error?r.message:String(r)}),await d(a+Math.floor(Math.random()*100));continue}throw r}}async _startConversation(){let n=await this.fetchWithRetry(`${this.endpoint}/conversations`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},keepalive:true,signal:m(this.timeoutMs),body:JSON.stringify({sessionRef:this.sessionRef,userRef:this.userRef,metadata:this.metadata})},{retries:1,retryDelayMs:300});if(!n.ok)throw new Error(`HTTP ${n.status}: ${n.statusText}`)}async _sendTrace(n,e){let s=await this.fetchWithRetry(`${this.endpoint}/conversations/${this.sessionRef}/traces`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},keepalive:true,signal:m(e?.timeoutMs??this.timeoutMs),body:JSON.stringify(n)},{retries:1,retryDelayMs:300});if(!s.ok)throw new Error(`HTTP ${s.status}: ${s.statusText}`);return await s.json()}async _sendFeedback(n){let e=await this.fetchWithRetry(`${this.endpoint}/conversations/${this.sessionRef}/feedback`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},keepalive:true,signal:m(this.timeoutMs),body:JSON.stringify(n)},{retries:1,retryDelayMs:300});if(!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`)}async _endConversation(n){let e=await this.fetchWithRetry(`${this.endpoint}/conversations/${this.sessionRef}`,{method:"PATCH",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},keepalive:true,signal:m(this.timeoutMs),body:JSON.stringify({durationMs:n,turnCount:this.turnCount})},{retries:1,retryDelayMs:300});if(!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`)}enqueueSend(n){this.sendQueue=this.sendQueue.then(()=>n()).catch(()=>{});}async flush(n){let e=typeof n=="number"&&Number.isFinite(n)&&n>=0?n:this.timeoutMs,s=this.sendQueue.catch(()=>{}),o;try{await Promise.race([s,new Promise((a,i)=>{o=setTimeout(()=>i(new Error("Flush timeout")),e);})]);}catch(a){if(this.debug){let i=a instanceof Error?a.message:String(a);console.warn("[Teckel] Flush incomplete:",i);}throw a}finally{o&&clearTimeout(o);}}};function m(c){if(!(typeof c!="number"||c<=0)&&typeof AbortSignal.timeout=="function")return AbortSignal.timeout(c)}var g=class{constructor(n){let e=f.parse(n);e.apiKey.startsWith("tk_live_")||console.warn('[Teckel] API key should start with "tk_live_". Current key: '+e.apiKey.substring(0,10)+"..."),this.apiKey=e.apiKey,this.endpoint=e.endpoint||"https://app.teckel.ai/api",this.debug=e.debug||false,this.timeoutMs=typeof e.timeoutMs=="number"?e.timeoutMs:5e3,this.debug&&console.log("[Teckel] SDK initialized:",{endpoint:this.endpoint,version:"0.3.6",timeoutMs:this.timeoutMs});}start(n={}){let e=h.parse(n),s=e.sessionRef||`auto:${crypto.randomUUID().slice(0,8)}`;return new u(this.apiKey,this.endpoint,{...e,sessionRef:s},this.debug,{timeoutMs:this.timeoutMs})}};
2
- exports.Conversation=u;exports.ConversationOptionsSchema=h;exports.DocumentSchema=y;exports.FeedbackDataSchema=p;exports.TeckelConfigSchema=f;exports.TeckelTracer=g;exports.TokenUsageSchema=b;exports.TraceDataSchema=l;
1
+ 'use strict';var zod=require('zod');var c={METADATA_MAX_BYTES:1e4,TRACE_MAX_BYTES:3e6,MAX_DOCUMENTS:15},u=zod.z.object({id:zod.z.string().min(1,"id is required").max(500),name:zod.z.string().min(1,"name is required").max(500),text:zod.z.string().min(1,"text is required").max(5e4),lastUpdated:zod.z.string().datetime({offset:true}).optional(),url:zod.z.string().max(2e3).optional(),source:zod.z.string().max(100).optional(),fileFormat:zod.z.string().max(100).optional(),similarity:zod.z.number().min(0).max(1).optional(),rank:zod.z.number().int().nonnegative().optional(),ownerEmail:zod.z.string().email().max(254).optional()}),g=zod.z.object({prompt:zod.z.number().int().nonnegative(),completion:zod.z.number().int().nonnegative(),total:zod.z.number().int().nonnegative()}),m=zod.z.object({query:zod.z.string().min(1,"query is required").max(1e4,"query too long (max 10,000 chars)"),response:zod.z.string().min(1,"response is required").max(5e4,"response too long (max 50,000 chars)"),model:zod.z.string().max(100).optional(),latencyMs:zod.z.number().int().nonnegative().max(6e5).optional(),tokens:g.optional(),documents:zod.z.array(u).max(c.MAX_DOCUMENTS,`Too many documents (max ${c.MAX_DOCUMENTS})`).optional(),sessionId:zod.z.string().min(1).max(200,"sessionId must be 200 chars or less").optional(),userId:zod.z.string().min(1).max(255).optional(),traceId:zod.z.string().uuid("traceId must be a valid UUID").optional(),systemPrompt:zod.z.string().max(5e4,"systemPrompt too long (max 50,000 chars)").optional(),metadata:zod.z.record(zod.z.string(),zod.z.unknown()).optional().refine(r=>!r||JSON.stringify(r).length<=c.METADATA_MAX_BYTES,`metadata exceeds ${c.METADATA_MAX_BYTES/1e3}KB limit`)}).superRefine((r,i)=>{JSON.stringify(r).length>c.TRACE_MAX_BYTES&&i.addIssue({code:zod.z.ZodIssueCode.custom,message:`trace payload exceeds ${c.TRACE_MAX_BYTES/1e6}MB limit`,path:[]});}),d=zod.z.object({traceId:zod.z.string().uuid("traceId must be a valid UUID").optional(),sessionId:zod.z.string().min(1).max(200,"sessionId must be 200 chars or less").optional(),type:zod.z.enum(["thumbs_up","thumbs_down","flag","rating"]),value:zod.z.string().min(1).max(10).optional(),comment:zod.z.string().max(2e3).optional()}).refine(r=>r.traceId||r.sessionId,{message:"Either traceId or sessionId is required"}),l=zod.z.object({apiKey:zod.z.string().min(1,"apiKey is required"),endpoint:zod.z.string().url().optional(),debug:zod.z.boolean().optional(),timeoutMs:zod.z.number().int().positive().max(6e4).optional()});var p=class{constructor(i){this.sendQueue=Promise.resolve();let e=l.parse(i);if(!e.apiKey.startsWith("tk_live_")){let o=e.apiKey.startsWith("tk_")?"tk_***":"invalid prefix";console.error(`[Teckel] Invalid API key format. Expected "tk_live_***", got "${o}". Get your key at https://app.teckel.ai/settings/api-keys`);}this.apiKey=e.apiKey,this.endpoint=e.endpoint||"https://app.teckel.ai/api",this.debug=e.debug||false,this.timeoutMs=e.timeoutMs??5e3,this.debug&&console.log("[Teckel] Initialized",{endpoint:this.endpoint,timeoutMs:this.timeoutMs});}trace(i){try{let e=m.parse(i);this.debug&&console.log("[Teckel] Queueing trace:",{traceId:e.traceId,sessionId:e.sessionId,queryLength:e.query.length,documentCount:e.documents?.length||0}),this.enqueue(()=>this.send("/sdk/traces",e),"trace");}catch(e){this.logValidationError("Trace",e);}}feedback(i){try{let e=d.parse(i);this.debug&&console.log("[Teckel] Sending feedback:",{type:e.type,traceId:e.traceId}),this.enqueue(()=>this.send("/sdk/feedback",e),"feedback");}catch(e){this.logValidationError("Feedback",e);}}async flush(i){let e=i??this.timeoutMs,o=this.sendQueue.catch(()=>{}),n;try{await Promise.race([o,new Promise((a,s)=>{n=setTimeout(()=>s(new Error("Flush timeout")),e);})]);}catch(a){throw this.debug&&console.warn("[Teckel] Flush incomplete:",a.message),a}finally{n&&clearTimeout(n);}}async send(i,e){let o=`${this.endpoint}${i}`,n=await this.fetchWithRetry(o,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},keepalive:true,signal:AbortSignal.timeout?.(this.timeoutMs),body:JSON.stringify(e)});if(!n.ok)throw this.logHttpError(i,n.status),new Error(`HTTP ${n.status}`);return n.json()}async fetchWithRetry(i,e){let n=()=>new Promise(a=>setTimeout(a,250+Math.random()*100));for(let a=1;a<=2;a++)try{let s=await fetch(i,e);if(s.ok||a===2)return s;if(s.status===429||s.status>=500){this.debug&&console.warn("[Teckel] Retrying",{status:s.status,attempt:a}),await n();continue}return s}catch(s){if(a===2)throw s;this.debug&&console.warn("[Teckel] Retry after error",{attempt:a}),await n();}throw new Error("Unreachable")}enqueue(i,e){this.sendQueue=this.sendQueue.then(()=>i()).catch(o=>{if(!(o instanceof Error&&o.message.startsWith("HTTP "))){let n=o instanceof Error?o.message:String(o);n.includes("timeout")||n.includes("abort")?console.warn(`[Teckel] ${e} timed out. Consider increasing timeoutMs.`):console.warn(`[Teckel] ${e} failed: ${n}`);}});}logValidationError(i,e){if(e instanceof zod.ZodError){let o=e.errors.map(n=>n.path.length?`${n.path.join(".")}: ${n.message}`:n.message).join("; ");console.error(`[Teckel] ${i} dropped - validation failed: ${o}`);}else this.debug&&console.error(`[Teckel] ${i} dropped:`,e);}logHttpError(i,e){let o=i.includes("trace")?"Trace":"Feedback",a={401:`${o} failed - invalid API key. Check https://app.teckel.ai/settings/api-keys`,400:`${o} failed - invalid request. Enable debug mode for details.`,404:`${o} failed - endpoint not found. Check your configuration.`,429:`${o} dropped - rate limit exceeded.`}[e]||(e>=500?`${o} dropped - server error (${e})`:`${o} failed - HTTP ${e}`);e>=500||e===429?console.warn(`[Teckel] ${a}`):console.error(`[Teckel] ${a}`);}};
2
+ exports.DocumentSchema=u;exports.FeedbackDataSchema=d;exports.TRACE_SIZE_LIMITS=c;exports.TeckelConfigSchema=l;exports.TeckelTracer=p;exports.TokenUsageSchema=g;exports.TraceDataSchema=m;