teckel-ai 0.3.2 → 0.3.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.
package/dist/index.d.ts CHANGED
@@ -1,10 +1,389 @@
1
+ import { z } from 'zod';
2
+
1
3
  /**
2
- * teckel-ai v0.3.1
3
- * Simple SDK for AI conversation tracking and RAG observability
4
+ * Type definitions for teckel-ai SDK v0.3.5
5
+ * Simple, clean types matching existing database schema
6
+ */
7
+ /**
8
+ * SDK Configuration
9
+ */
10
+ interface TeckelConfig {
11
+ apiKey: string;
12
+ endpoint?: string;
13
+ debug?: boolean;
14
+ timeoutMs?: number;
15
+ }
16
+ /**
17
+ * Conversation options
18
+ * sessionRef IS the conversation identifier
4
19
  *
5
- * @packageDocumentation
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
32
+ */
33
+ interface Document {
34
+ documentRef: string;
35
+ documentName: string;
36
+ documentText: string;
37
+ documentLastUpdated?: string;
38
+ sourceUri?: string;
39
+ sourceType?: string;
40
+ similarity?: number;
41
+ rank?: number;
42
+ ownerEmail?: string;
43
+ documentType?: string;
44
+ }
45
+ /**
46
+ * Token usage tracking
47
+ */
48
+ interface TokenUsage {
49
+ prompt: number;
50
+ completion: number;
51
+ total: number;
52
+ }
53
+ /**
54
+ * Trace data for a single query-response interaction
55
+ * Matches existing traces table schema
56
+ */
57
+ interface TraceData {
58
+ query: string;
59
+ response: string;
60
+ model?: string;
61
+ responseTimeMs?: number;
62
+ documents?: Document[];
63
+ tokens?: TokenUsage;
64
+ metadata?: Record<string, unknown>;
65
+ traceRef?: string;
66
+ userRef?: string;
67
+ }
68
+ /**
69
+ * Feedback types
70
+ */
71
+ type FeedbackType = 'thumbs_up' | 'thumbs_down' | 'flag' | 'rating';
72
+ /**
73
+ * User feedback signal
74
+ */
75
+ interface FeedbackData {
76
+ type: FeedbackType;
77
+ value?: string;
78
+ comment?: string;
79
+ traceRef?: string;
80
+ }
81
+ /**
82
+ * Result returned when a trace is created
83
+ */
84
+ interface TraceResult {
85
+ traceRef: string;
86
+ turnNumber: number;
87
+ }
88
+
89
+ /**
90
+ * Conversation class for teckel-ai SDK v0.3.5
91
+ * Manages a single conversation with fire-and-forget semantics
92
+ */
93
+
94
+ /** Internal type - sessionRef is guaranteed by TeckelTracer.start() */
95
+ interface ResolvedConversationOptions extends ConversationOptions {
96
+ sessionRef: string;
97
+ }
98
+ declare class Conversation {
99
+ private readonly apiKey;
100
+ private readonly endpoint;
101
+ private readonly sessionRef;
102
+ private readonly userRef?;
103
+ private readonly metadata?;
104
+ private readonly startedAt;
105
+ private readonly debug;
106
+ private readonly timeoutMs;
107
+ private turnCount;
108
+ private startPromise;
109
+ 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;
119
+ /**
120
+ * Add user feedback signal
121
+ * Never throws - gracefully handles errors
122
+ */
123
+ feedback(data: FeedbackData): Promise<void>;
124
+ /**
125
+ * End the conversation
126
+ * Flushes all pending traces before sending end signal
127
+ * Never throws - gracefully handles errors
128
+ */
129
+ end(): Promise<void>;
130
+ /**
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).
145
+ */
146
+ flush(timeoutMs?: number): Promise<void>;
147
+ }
148
+
149
+ /**
150
+ * TeckelTracer - Main SDK class for teckel-ai v0.3.5
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.5
170
+ */
171
+
172
+ /**
173
+ * Document schema
174
+ */
175
+ 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>;
182
+ similarity: z.ZodOptional<z.ZodNumber>;
183
+ rank: z.ZodOptional<z.ZodNumber>;
184
+ ownerEmail: z.ZodOptional<z.ZodString>;
185
+ documentType: z.ZodOptional<z.ZodString>;
186
+ }, "strip", z.ZodTypeAny, {
187
+ documentRef: string;
188
+ documentName: string;
189
+ documentText: string;
190
+ documentLastUpdated?: string | undefined;
191
+ sourceUri?: string | undefined;
192
+ sourceType?: string | undefined;
193
+ similarity?: number | undefined;
194
+ rank?: number | undefined;
195
+ ownerEmail?: string | undefined;
196
+ documentType?: string | undefined;
197
+ }, {
198
+ documentRef: string;
199
+ documentName: string;
200
+ documentText: string;
201
+ documentLastUpdated?: string | undefined;
202
+ sourceUri?: string | undefined;
203
+ sourceType?: string | undefined;
204
+ similarity?: number | undefined;
205
+ rank?: number | undefined;
206
+ ownerEmail?: string | undefined;
207
+ documentType?: string | undefined;
208
+ }>;
209
+ /**
210
+ * Token usage schema
211
+ */
212
+ declare const TokenUsageSchema: z.ZodObject<{
213
+ prompt: z.ZodNumber;
214
+ completion: z.ZodNumber;
215
+ total: z.ZodNumber;
216
+ }, "strip", z.ZodTypeAny, {
217
+ prompt: number;
218
+ completion: number;
219
+ total: number;
220
+ }, {
221
+ prompt: number;
222
+ completion: number;
223
+ total: number;
224
+ }>;
225
+ /**
226
+ * Trace data schema
227
+ */
228
+ declare const TraceDataSchema: z.ZodObject<{
229
+ query: z.ZodString;
230
+ response: z.ZodString;
231
+ 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">>;
267
+ tokens: z.ZodOptional<z.ZodObject<{
268
+ prompt: z.ZodNumber;
269
+ completion: z.ZodNumber;
270
+ total: z.ZodNumber;
271
+ }, "strip", z.ZodTypeAny, {
272
+ prompt: number;
273
+ completion: number;
274
+ total: number;
275
+ }, {
276
+ prompt: number;
277
+ completion: number;
278
+ total: number;
279
+ }>>;
280
+ metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
281
+ traceRef: z.ZodOptional<z.ZodString>;
282
+ userRef: z.ZodOptional<z.ZodString>;
283
+ }, "strip", z.ZodTypeAny, {
284
+ query: string;
285
+ response: string;
286
+ model?: string | undefined;
287
+ responseTimeMs?: number | undefined;
288
+ documents?: {
289
+ documentRef: string;
290
+ documentName: string;
291
+ documentText: string;
292
+ documentLastUpdated?: string | undefined;
293
+ sourceUri?: string | undefined;
294
+ sourceType?: string | undefined;
295
+ similarity?: number | undefined;
296
+ rank?: number | undefined;
297
+ ownerEmail?: string | undefined;
298
+ documentType?: string | undefined;
299
+ }[] | undefined;
300
+ tokens?: {
301
+ prompt: number;
302
+ completion: number;
303
+ total: number;
304
+ } | undefined;
305
+ metadata?: Record<string, unknown> | undefined;
306
+ traceRef?: string | undefined;
307
+ userRef?: string | undefined;
308
+ }, {
309
+ query: string;
310
+ response: string;
311
+ model?: string | undefined;
312
+ responseTimeMs?: number | undefined;
313
+ documents?: {
314
+ documentRef: string;
315
+ documentName: string;
316
+ documentText: string;
317
+ documentLastUpdated?: string | undefined;
318
+ sourceUri?: string | undefined;
319
+ sourceType?: string | undefined;
320
+ similarity?: number | undefined;
321
+ rank?: number | undefined;
322
+ ownerEmail?: string | undefined;
323
+ documentType?: string | undefined;
324
+ }[] | undefined;
325
+ tokens?: {
326
+ prompt: number;
327
+ completion: number;
328
+ total: number;
329
+ } | undefined;
330
+ 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
+ }>;
350
+ /**
351
+ * Feedback data schema
352
+ */
353
+ declare const FeedbackDataSchema: z.ZodObject<{
354
+ type: z.ZodEnum<["thumbs_up", "thumbs_down", "flag", "rating"]>;
355
+ value: z.ZodOptional<z.ZodString>;
356
+ comment: z.ZodOptional<z.ZodString>;
357
+ traceRef: z.ZodOptional<z.ZodString>;
358
+ }, "strip", z.ZodTypeAny, {
359
+ type: "thumbs_up" | "thumbs_down" | "flag" | "rating";
360
+ value?: string | undefined;
361
+ traceRef?: string | undefined;
362
+ comment?: string | undefined;
363
+ }, {
364
+ type: "thumbs_up" | "thumbs_down" | "flag" | "rating";
365
+ value?: string | undefined;
366
+ traceRef?: string | undefined;
367
+ comment?: string | undefined;
368
+ }>;
369
+ /**
370
+ * Config schema
6
371
  */
7
- export { TeckelTracer } from './tracer';
8
- export { Conversation } from './conversation';
9
- export type { TeckelConfig, ConversationOptions, TraceData, Document, TokenUsage, FeedbackData, FeedbackType, ValidationResult, TraceResult } from './types';
10
- export { TeckelConfigSchema, ConversationOptionsSchema, TraceDataSchema, DocumentSchema, TokenUsageSchema, FeedbackDataSchema } from './schemas';
372
+ declare const TeckelConfigSchema: z.ZodObject<{
373
+ apiKey: z.ZodString;
374
+ endpoint: z.ZodOptional<z.ZodString>;
375
+ debug: z.ZodOptional<z.ZodBoolean>;
376
+ timeoutMs: z.ZodOptional<z.ZodNumber>;
377
+ }, "strip", z.ZodTypeAny, {
378
+ apiKey: string;
379
+ endpoint?: string | undefined;
380
+ debug?: boolean | undefined;
381
+ timeoutMs?: number | undefined;
382
+ }, {
383
+ apiKey: string;
384
+ endpoint?: string | undefined;
385
+ debug?: boolean | undefined;
386
+ timeoutMs?: number | undefined;
387
+ }>;
388
+
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 };
package/dist/index.js CHANGED
@@ -1,22 +1,2 @@
1
- "use strict";
2
- /**
3
- * teckel-ai v0.3.1
4
- * Simple SDK for AI conversation tracking and RAG observability
5
- *
6
- * @packageDocumentation
7
- */
8
- Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.FeedbackDataSchema = exports.TokenUsageSchema = exports.DocumentSchema = exports.TraceDataSchema = exports.ConversationOptionsSchema = exports.TeckelConfigSchema = exports.Conversation = exports.TeckelTracer = void 0;
10
- // Main SDK exports
11
- var tracer_1 = require("./tracer");
12
- Object.defineProperty(exports, "TeckelTracer", { enumerable: true, get: function () { return tracer_1.TeckelTracer; } });
13
- var conversation_1 = require("./conversation");
14
- Object.defineProperty(exports, "Conversation", { enumerable: true, get: function () { return conversation_1.Conversation; } });
15
- // Schema exports (for advanced use cases)
16
- var schemas_1 = require("./schemas");
17
- Object.defineProperty(exports, "TeckelConfigSchema", { enumerable: true, get: function () { return schemas_1.TeckelConfigSchema; } });
18
- Object.defineProperty(exports, "ConversationOptionsSchema", { enumerable: true, get: function () { return schemas_1.ConversationOptionsSchema; } });
19
- Object.defineProperty(exports, "TraceDataSchema", { enumerable: true, get: function () { return schemas_1.TraceDataSchema; } });
20
- Object.defineProperty(exports, "DocumentSchema", { enumerable: true, get: function () { return schemas_1.DocumentSchema; } });
21
- Object.defineProperty(exports, "TokenUsageSchema", { enumerable: true, get: function () { return schemas_1.TokenUsageSchema; } });
22
- Object.defineProperty(exports, "FeedbackDataSchema", { enumerable: true, get: function () { return schemas_1.FeedbackDataSchema; } });
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.5",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;
package/dist/index.mjs ADDED
@@ -0,0 +1,2 @@
1
+ import {z}from'zod';var y=z.object({documentRef:z.string().min(1,"documentRef is required"),documentName:z.string().min(1,"documentName is required"),documentText:z.string().min(1,"documentText is required"),documentLastUpdated:z.string().optional(),sourceUri:z.string().optional(),sourceType:z.string().optional(),similarity:z.number().min(0).max(1).optional(),rank:z.number().int().nonnegative().optional(),ownerEmail:z.string().email().optional(),documentType:z.string().optional()}),b=z.object({prompt:z.number().int().nonnegative(),completion:z.number().int().nonnegative(),total:z.number().int().nonnegative()}),l=z.object({query:z.string().min(1,"query is required").max(1e4,"query too long (max 10,000 characters)"),response:z.string().min(1,"response is required").max(5e4,"response too long (max 50,000 characters)"),model:z.string().optional(),responseTimeMs:z.number().nonnegative().optional(),documents:z.array(y).max(50,"Too many documents (max 50)").optional(),tokens:b.optional(),metadata:z.record(z.string(),z.unknown()).optional(),traceRef:z.string().min(1).optional(),userRef:z.string().min(1).optional()}),h=z.object({sessionRef:z.string().min(1).optional(),userRef:z.string().optional(),metadata:z.record(z.string(),z.unknown()).optional()}),p=z.object({type:z.enum(["thumbs_up","thumbs_down","flag","rating"]),value:z.string().optional(),comment:z.string().optional(),traceRef:z.string().optional()}),f=z.object({apiKey:z.string().min(1,"apiKey is required"),endpoint:z.string().url().optional(),debug:z.boolean().optional(),timeoutMs: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.5",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
+ export{u as Conversation,h as ConversationOptionsSchema,y as DocumentSchema,p as FeedbackDataSchema,f as TeckelConfigSchema,g as TeckelTracer,b as TokenUsageSchema,l as TraceDataSchema};
package/package.json CHANGED
@@ -1,17 +1,31 @@
1
1
  {
2
2
  "name": "teckel-ai",
3
- "version": "0.3.2",
3
+ "version": "0.3.5",
4
4
  "description": "Simple SDK for AI conversation tracking and RAG observability",
5
5
  "main": "dist/index.js",
6
+ "module": "dist/index.mjs",
6
7
  "types": "dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "import": {
11
+ "types": "./dist/index.d.mts",
12
+ "default": "./dist/index.mjs"
13
+ },
14
+ "require": {
15
+ "types": "./dist/index.d.ts",
16
+ "default": "./dist/index.js"
17
+ }
18
+ }
19
+ },
7
20
  "files": [
8
21
  "dist/**/*",
9
22
  "README.md"
10
23
  ],
11
24
  "scripts": {
12
- "build": "tsc",
25
+ "build": "tsup",
13
26
  "clean": "rm -rf dist",
14
- "prepublishOnly": "npm run clean && npm run build"
27
+ "prepublishOnly": "npm run clean && npm run build",
28
+ "type-check": "tsc --noEmit"
15
29
  },
16
30
  "keywords": [
17
31
  "llm",
@@ -25,19 +39,16 @@
25
39
  ],
26
40
  "author": "Teckel AI",
27
41
  "license": "MIT",
42
+ "engines": {
43
+ "node": ">=18"
44
+ },
45
+ "sideEffects": false,
28
46
  "dependencies": {
29
47
  "zod": "^3.23.8"
30
48
  },
31
49
  "devDependencies": {
50
+ "tsup": "^8.3.5",
32
51
  "typescript": "^5.0.0"
33
52
  },
34
- "repository": {
35
- "type": "git",
36
- "url": "https://github.com/spencine/AI-Audit-Tool.git",
37
- "directory": "packages/tracer"
38
- },
39
- "homepage": "https://teckel.ai",
40
- "bugs": {
41
- "url": "https://github.com/spencine/AI-Audit-Tool/issues"
42
- }
53
+ "homepage": "https://teckel.ai"
43
54
  }
@@ -1,64 +0,0 @@
1
- /**
2
- * Conversation class for teckel-ai SDK v0.3.1
3
- * Manages a single conversation with fire-and-forget semantics
4
- */
5
- import type { TraceData, FeedbackData, ConversationOptions, TraceResult } from './types';
6
- export declare class Conversation {
7
- private readonly apiKey;
8
- private readonly endpoint;
9
- private readonly sessionRef;
10
- private readonly userId?;
11
- private readonly metadata?;
12
- private readonly startedAt;
13
- private readonly debug;
14
- private readonly timeoutMs;
15
- private turnCount;
16
- private startPromise;
17
- private sendQueue;
18
- constructor(apiKey: string, endpoint: string, options: ConversationOptions, debug?: boolean, extras?: {
19
- timeoutMs: number;
20
- });
21
- /**
22
- * Record a trace (single query-response interaction)
23
- * Fire-and-forget by default - never blocks
24
- * For serverless, call flush() before function termination
25
- */
26
- trace(data: TraceData): TraceResult | void;
27
- /**
28
- * Synchronous trace: waits for HTTP send to complete.
29
- * Throws on network/validation errors.
30
- * Respects send queue to maintain trace ordering.
31
- */
32
- traceSync(data: TraceData, opt?: {
33
- timeoutMs?: number;
34
- }): Promise<TraceResult>;
35
- /**
36
- * Add user feedback signal
37
- * Never throws - gracefully handles errors
38
- */
39
- feedback(data: FeedbackData): Promise<void>;
40
- /**
41
- * End the conversation
42
- * Flushes all pending traces before sending end signal
43
- * Never throws - gracefully handles errors
44
- */
45
- end(): Promise<void>;
46
- /**
47
- * Read-only properties
48
- */
49
- get id(): string;
50
- get turns(): number;
51
- get started(): Date;
52
- private fetchWithRetry;
53
- private _startConversation;
54
- private _sendTrace;
55
- private _sendFeedback;
56
- private _endConversation;
57
- private enqueueSend;
58
- /**
59
- * Flush queued sends with a bounded timeout.
60
- * Returns when the queue is empty or the timeout elapses (whichever comes first).
61
- */
62
- flush(timeoutMs?: number): Promise<void>;
63
- private mapOTelAliases;
64
- }