@prefactor/sdk 0.1.3 → 0.1.4
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.cjs +16 -1253
- package/dist/index.cjs.map +4 -17
- package/dist/index.d.ts +2 -81
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -1255
- package/dist/index.js.map +4 -17
- package/package.json +6 -22
- package/LICENSE +0 -14
- package/README.md +0 -313
- package/dist/LICENSE +0 -14
- package/dist/README.md +0 -313
- package/dist/config.d.ts +0 -259
- package/dist/config.d.ts.map +0 -1
- package/dist/config.js +0 -110
- package/dist/config.js.map +0 -1
- package/dist/instrumentation/langchain/metadata-extractor.d.ts +0 -20
- package/dist/instrumentation/langchain/metadata-extractor.d.ts.map +0 -1
- package/dist/instrumentation/langchain/metadata-extractor.js +0 -54
- package/dist/instrumentation/langchain/metadata-extractor.js.map +0 -1
- package/dist/instrumentation/langchain/middleware.d.ts +0 -84
- package/dist/instrumentation/langchain/middleware.d.ts.map +0 -1
- package/dist/instrumentation/langchain/middleware.js +0 -181
- package/dist/instrumentation/langchain/middleware.js.map +0 -1
- package/dist/package.json +0 -56
- package/dist/tracing/context.d.ts +0 -53
- package/dist/tracing/context.d.ts.map +0 -1
- package/dist/tracing/context.js +0 -65
- package/dist/tracing/context.js.map +0 -1
- package/dist/tracing/span.d.ts +0 -68
- package/dist/tracing/span.d.ts.map +0 -1
- package/dist/tracing/span.js +0 -21
- package/dist/tracing/span.js.map +0 -1
- package/dist/tracing/tracer.d.ts +0 -100
- package/dist/tracing/tracer.d.ts.map +0 -1
- package/dist/tracing/tracer.js +0 -151
- package/dist/tracing/tracer.js.map +0 -1
- package/dist/transport/base.d.ts +0 -38
- package/dist/transport/base.d.ts.map +0 -1
- package/dist/transport/base.js +0 -2
- package/dist/transport/base.js.map +0 -1
- package/dist/transport/http.d.ts +0 -90
- package/dist/transport/http.d.ts.map +0 -1
- package/dist/transport/http.js +0 -399
- package/dist/transport/http.js.map +0 -1
- package/dist/transport/stdio.d.ts +0 -48
- package/dist/transport/stdio.d.ts.map +0 -1
- package/dist/transport/stdio.js +0 -71
- package/dist/transport/stdio.js.map +0 -1
- package/dist/utils/logging.d.ts +0 -29
- package/dist/utils/logging.d.ts.map +0 -1
- package/dist/utils/logging.js +0 -71
- package/dist/utils/logging.js.map +0 -1
- package/dist/utils/serialization.d.ts +0 -24
- package/dist/utils/serialization.d.ts.map +0 -1
- package/dist/utils/serialization.js +0 -60
- package/dist/utils/serialization.js.map +0 -1
package/dist/index.js
CHANGED
|
@@ -1,1256 +1,5 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
var __defProp = Object.defineProperty;
|
|
5
|
-
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
-
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
7
|
-
var __toESM = (mod, isNodeMode, target) => {
|
|
8
|
-
target = mod != null ? __create(__getProtoOf(mod)) : {};
|
|
9
|
-
const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
|
|
10
|
-
for (let key of __getOwnPropNames(mod))
|
|
11
|
-
if (!__hasOwnProp.call(to, key))
|
|
12
|
-
__defProp(to, key, {
|
|
13
|
-
get: () => mod[key],
|
|
14
|
-
enumerable: true
|
|
15
|
-
});
|
|
16
|
-
return to;
|
|
17
|
-
};
|
|
18
|
-
var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
|
|
19
|
-
var __require = /* @__PURE__ */ createRequire(import.meta.url);
|
|
1
|
+
// packages/sdk/src/index.ts
|
|
2
|
+
export * from "@prefactor/core";
|
|
3
|
+
export * from "@prefactor/langchain";
|
|
20
4
|
|
|
21
|
-
|
|
22
|
-
var require_errors = __commonJS((exports) => {
|
|
23
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
24
|
-
exports.PfidError = undefined;
|
|
25
|
-
|
|
26
|
-
class PfidError extends Error {
|
|
27
|
-
constructor(code, message) {
|
|
28
|
-
super(message);
|
|
29
|
-
this.name = "PfidError";
|
|
30
|
-
this.code = code;
|
|
31
|
-
Object.setPrototypeOf(this, PfidError.prototype);
|
|
32
|
-
}
|
|
33
|
-
static make(code, problem) {
|
|
34
|
-
const message = (() => {
|
|
35
|
-
switch (code) {
|
|
36
|
-
case "invalid_binary":
|
|
37
|
-
return `invalid binary PFID: ${JSON.stringify(problem)}`;
|
|
38
|
-
case "invalid_pfid":
|
|
39
|
-
return `invalid PFID: ${JSON.stringify(problem)}`;
|
|
40
|
-
case "invalid_partition":
|
|
41
|
-
return `invalid partition: ${JSON.stringify(problem)}`;
|
|
42
|
-
}
|
|
43
|
-
})();
|
|
44
|
-
return new PfidError(code, message);
|
|
45
|
-
}
|
|
46
|
-
}
|
|
47
|
-
exports.PfidError = PfidError;
|
|
48
|
-
});
|
|
49
|
-
|
|
50
|
-
// node_modules/@prefactor/pfid/dist/pfid.js
|
|
51
|
-
var require_pfid = __commonJS((exports) => {
|
|
52
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
53
|
-
exports.zero = zero;
|
|
54
|
-
exports.generate = generate;
|
|
55
|
-
exports.generateWithTimestamp = generateWithTimestamp;
|
|
56
|
-
exports.generateExample = generateExample;
|
|
57
|
-
exports.generateRelated = generateRelated;
|
|
58
|
-
exports.generateRoot = generateRoot;
|
|
59
|
-
exports.generateBinary = generateBinary;
|
|
60
|
-
exports.generateBinaryWithTimestamp = generateBinaryWithTimestamp;
|
|
61
|
-
exports.isPfid = isPfid;
|
|
62
|
-
exports.encode = encode;
|
|
63
|
-
exports.decode = decode;
|
|
64
|
-
exports.extractPartition = extractPartition;
|
|
65
|
-
exports.generatePartition = generatePartition;
|
|
66
|
-
var crypto_1 = __require("crypto");
|
|
67
|
-
var errors_1 = require_errors();
|
|
68
|
-
var MAX_TIMESTAMP = 281474976710655;
|
|
69
|
-
var MAX_PARTITION = 1073741823;
|
|
70
|
-
var ENCODE_CHARS = "0123456789abcdefghjkmnpqrstvwxyz";
|
|
71
|
-
var DECODE_MAP = {
|
|
72
|
-
"0": 0,
|
|
73
|
-
"1": 1,
|
|
74
|
-
"2": 2,
|
|
75
|
-
"3": 3,
|
|
76
|
-
"4": 4,
|
|
77
|
-
"5": 5,
|
|
78
|
-
"6": 6,
|
|
79
|
-
"7": 7,
|
|
80
|
-
"8": 8,
|
|
81
|
-
"9": 9,
|
|
82
|
-
a: 10,
|
|
83
|
-
b: 11,
|
|
84
|
-
c: 12,
|
|
85
|
-
d: 13,
|
|
86
|
-
e: 14,
|
|
87
|
-
f: 15,
|
|
88
|
-
g: 16,
|
|
89
|
-
h: 17,
|
|
90
|
-
j: 18,
|
|
91
|
-
k: 19,
|
|
92
|
-
m: 20,
|
|
93
|
-
n: 21,
|
|
94
|
-
p: 22,
|
|
95
|
-
q: 23,
|
|
96
|
-
r: 24,
|
|
97
|
-
s: 25,
|
|
98
|
-
t: 26,
|
|
99
|
-
v: 27,
|
|
100
|
-
w: 28,
|
|
101
|
-
x: 29,
|
|
102
|
-
y: 30,
|
|
103
|
-
z: 31
|
|
104
|
-
};
|
|
105
|
-
function encodeChar(value) {
|
|
106
|
-
return ENCODE_CHARS[value];
|
|
107
|
-
}
|
|
108
|
-
function decodeChar(char) {
|
|
109
|
-
const value = DECODE_MAP[char.toLowerCase()];
|
|
110
|
-
if (value === undefined) {
|
|
111
|
-
throw new Error(`Invalid character: ${char}`);
|
|
112
|
-
}
|
|
113
|
-
return value;
|
|
114
|
-
}
|
|
115
|
-
function isValidTimestamp(timestamp) {
|
|
116
|
-
return Number.isInteger(timestamp) && timestamp >= 0 && timestamp <= MAX_TIMESTAMP;
|
|
117
|
-
}
|
|
118
|
-
function isValidPartition(partition) {
|
|
119
|
-
return Number.isInteger(partition) && partition >= 0 && partition <= MAX_PARTITION;
|
|
120
|
-
}
|
|
121
|
-
function zero() {
|
|
122
|
-
return "00000000000000000000000000000000";
|
|
123
|
-
}
|
|
124
|
-
function generate(partition) {
|
|
125
|
-
if (!isValidPartition(partition)) {
|
|
126
|
-
throw new Error(`Invalid partition: ${partition}`);
|
|
127
|
-
}
|
|
128
|
-
return unsafeEncode(generateBinary(partition));
|
|
129
|
-
}
|
|
130
|
-
function generateWithTimestamp(partition, timestamp) {
|
|
131
|
-
if (!isValidPartition(partition)) {
|
|
132
|
-
throw new Error(`Invalid partition: ${partition}`);
|
|
133
|
-
}
|
|
134
|
-
if (!isValidTimestamp(timestamp)) {
|
|
135
|
-
throw new Error(`Invalid timestamp: ${timestamp}`);
|
|
136
|
-
}
|
|
137
|
-
return unsafeEncode(generateBinaryWithTimestamp(partition, timestamp));
|
|
138
|
-
}
|
|
139
|
-
function generateExample() {
|
|
140
|
-
return generateWithTimestamp(123456789, 1234567890000);
|
|
141
|
-
}
|
|
142
|
-
function generateRelated(existingPfid) {
|
|
143
|
-
return generate(extractPartition(existingPfid));
|
|
144
|
-
}
|
|
145
|
-
function generateRoot() {
|
|
146
|
-
return generate(generatePartition());
|
|
147
|
-
}
|
|
148
|
-
function generateBinary(partition) {
|
|
149
|
-
if (!isValidPartition(partition)) {
|
|
150
|
-
throw new Error(`Invalid partition: ${partition}`);
|
|
151
|
-
}
|
|
152
|
-
const timestamp = Date.now();
|
|
153
|
-
return generateBinaryWithTimestamp(partition, timestamp);
|
|
154
|
-
}
|
|
155
|
-
function generateBinaryWithTimestamp(partition, timestamp) {
|
|
156
|
-
if (!isValidPartition(partition)) {
|
|
157
|
-
throw new Error(`Invalid partition: ${partition}`);
|
|
158
|
-
}
|
|
159
|
-
if (!isValidTimestamp(timestamp)) {
|
|
160
|
-
throw new Error(`Invalid timestamp: ${timestamp}`);
|
|
161
|
-
}
|
|
162
|
-
const buffer = Buffer.allocUnsafe(20);
|
|
163
|
-
buffer[0] = Math.floor(timestamp / 1099511627776) & 255;
|
|
164
|
-
buffer[1] = Math.floor(timestamp / 4294967296) & 255;
|
|
165
|
-
buffer[2] = timestamp >> 24 & 255;
|
|
166
|
-
buffer[3] = timestamp >> 16 & 255;
|
|
167
|
-
buffer[4] = timestamp >> 8 & 255;
|
|
168
|
-
buffer[5] = timestamp & 255;
|
|
169
|
-
buffer.writeUInt32BE(partition, 6);
|
|
170
|
-
(0, crypto_1.randomBytes)(10).copy(buffer, 10);
|
|
171
|
-
return buffer;
|
|
172
|
-
}
|
|
173
|
-
function isPfid(string) {
|
|
174
|
-
if (typeof string !== "string") {
|
|
175
|
-
return false;
|
|
176
|
-
}
|
|
177
|
-
if (string.length !== 32) {
|
|
178
|
-
return false;
|
|
179
|
-
}
|
|
180
|
-
if (string[0] < "0" || string[0] > "7") {
|
|
181
|
-
return false;
|
|
182
|
-
}
|
|
183
|
-
const validPattern = /^[0-7][0-9abcdefghjkmnpqrstvwxyz]{31}$/;
|
|
184
|
-
return validPattern.test(string);
|
|
185
|
-
}
|
|
186
|
-
function encode(binary) {
|
|
187
|
-
if (!Buffer.isBuffer(binary) || binary.length !== 20) {
|
|
188
|
-
throw errors_1.PfidError.make("invalid_binary", binary);
|
|
189
|
-
}
|
|
190
|
-
try {
|
|
191
|
-
const encoded = unsafeEncode(binary);
|
|
192
|
-
if (isPfid(encoded)) {
|
|
193
|
-
return encoded;
|
|
194
|
-
} else {
|
|
195
|
-
throw errors_1.PfidError.make("invalid_binary", binary);
|
|
196
|
-
}
|
|
197
|
-
} catch (error) {
|
|
198
|
-
if (error instanceof errors_1.PfidError) {
|
|
199
|
-
throw error;
|
|
200
|
-
}
|
|
201
|
-
throw errors_1.PfidError.make("invalid_binary", binary);
|
|
202
|
-
}
|
|
203
|
-
}
|
|
204
|
-
function decode(pfid) {
|
|
205
|
-
if (typeof pfid !== "string" || pfid.length !== 32) {
|
|
206
|
-
throw errors_1.PfidError.make("invalid_pfid", pfid);
|
|
207
|
-
}
|
|
208
|
-
if (pfid[0] < "0" || pfid[0] > "7") {
|
|
209
|
-
throw errors_1.PfidError.make("invalid_pfid", pfid);
|
|
210
|
-
}
|
|
211
|
-
try {
|
|
212
|
-
return unsafeDecode(pfid);
|
|
213
|
-
} catch (error) {
|
|
214
|
-
if (error instanceof errors_1.PfidError) {
|
|
215
|
-
throw error;
|
|
216
|
-
}
|
|
217
|
-
throw errors_1.PfidError.make("invalid_pfid", pfid);
|
|
218
|
-
}
|
|
219
|
-
}
|
|
220
|
-
function extractPartition(pfid) {
|
|
221
|
-
if (!isPfid(pfid)) {
|
|
222
|
-
throw errors_1.PfidError.make("invalid_pfid", pfid);
|
|
223
|
-
}
|
|
224
|
-
try {
|
|
225
|
-
const partitionStr = pfid.substring(10, 16);
|
|
226
|
-
return decodePartition(partitionStr);
|
|
227
|
-
} catch (error) {
|
|
228
|
-
if (error instanceof errors_1.PfidError) {
|
|
229
|
-
throw error;
|
|
230
|
-
}
|
|
231
|
-
throw errors_1.PfidError.make("invalid_pfid", pfid);
|
|
232
|
-
}
|
|
233
|
-
}
|
|
234
|
-
function generatePartition() {
|
|
235
|
-
const buffer = (0, crypto_1.randomBytes)(4);
|
|
236
|
-
buffer[0] = buffer[0] & 63;
|
|
237
|
-
const partition = buffer.readUInt32BE(0) & 1073741823;
|
|
238
|
-
return partition;
|
|
239
|
-
}
|
|
240
|
-
function unsafeEncode(binary) {
|
|
241
|
-
let bitOffset = 0;
|
|
242
|
-
function readBits(count) {
|
|
243
|
-
let value = 0;
|
|
244
|
-
for (let i = 0;i < count; i++) {
|
|
245
|
-
const byteIndex = Math.floor(bitOffset / 8);
|
|
246
|
-
const bitIndex = 7 - bitOffset % 8;
|
|
247
|
-
const bit = binary[byteIndex] >> bitIndex & 1;
|
|
248
|
-
value = value << 1 | bit;
|
|
249
|
-
bitOffset++;
|
|
250
|
-
}
|
|
251
|
-
return value;
|
|
252
|
-
}
|
|
253
|
-
const t1 = readBits(3);
|
|
254
|
-
const t2 = readBits(5);
|
|
255
|
-
const t3 = readBits(5);
|
|
256
|
-
const t4 = readBits(5);
|
|
257
|
-
const t5 = readBits(5);
|
|
258
|
-
const t6 = readBits(5);
|
|
259
|
-
const t7 = readBits(5);
|
|
260
|
-
const t8 = readBits(5);
|
|
261
|
-
const t9 = readBits(5);
|
|
262
|
-
const t10 = readBits(5);
|
|
263
|
-
readBits(2);
|
|
264
|
-
const p1 = readBits(5);
|
|
265
|
-
const p2 = readBits(5);
|
|
266
|
-
const p3 = readBits(5);
|
|
267
|
-
const p4 = readBits(5);
|
|
268
|
-
const p5 = readBits(5);
|
|
269
|
-
const p6 = readBits(5);
|
|
270
|
-
const r1 = readBits(5);
|
|
271
|
-
const r2 = readBits(5);
|
|
272
|
-
const r3 = readBits(5);
|
|
273
|
-
const r4 = readBits(5);
|
|
274
|
-
const r5 = readBits(5);
|
|
275
|
-
const r6 = readBits(5);
|
|
276
|
-
const r7 = readBits(5);
|
|
277
|
-
const r8 = readBits(5);
|
|
278
|
-
const r9 = readBits(5);
|
|
279
|
-
const r10 = readBits(5);
|
|
280
|
-
const r11 = readBits(5);
|
|
281
|
-
const r12 = readBits(5);
|
|
282
|
-
const r13 = readBits(5);
|
|
283
|
-
const r14 = readBits(5);
|
|
284
|
-
const r15 = readBits(5);
|
|
285
|
-
const r16 = readBits(5);
|
|
286
|
-
return encodeChar(t1) + encodeChar(t2) + encodeChar(t3) + encodeChar(t4) + encodeChar(t5) + encodeChar(t6) + encodeChar(t7) + encodeChar(t8) + encodeChar(t9) + encodeChar(t10) + encodeChar(p1) + encodeChar(p2) + encodeChar(p3) + encodeChar(p4) + encodeChar(p5) + encodeChar(p6) + encodeChar(r1) + encodeChar(r2) + encodeChar(r3) + encodeChar(r4) + encodeChar(r5) + encodeChar(r6) + encodeChar(r7) + encodeChar(r8) + encodeChar(r9) + encodeChar(r10) + encodeChar(r11) + encodeChar(r12) + encodeChar(r13) + encodeChar(r14) + encodeChar(r15) + encodeChar(r16);
|
|
287
|
-
}
|
|
288
|
-
function unsafeDecode(pfid) {
|
|
289
|
-
const t1 = decodeChar(pfid[0]);
|
|
290
|
-
const t2 = decodeChar(pfid[1]);
|
|
291
|
-
const t3 = decodeChar(pfid[2]);
|
|
292
|
-
const t4 = decodeChar(pfid[3]);
|
|
293
|
-
const t5 = decodeChar(pfid[4]);
|
|
294
|
-
const t6 = decodeChar(pfid[5]);
|
|
295
|
-
const t7 = decodeChar(pfid[6]);
|
|
296
|
-
const t8 = decodeChar(pfid[7]);
|
|
297
|
-
const t9 = decodeChar(pfid[8]);
|
|
298
|
-
const t10 = decodeChar(pfid[9]);
|
|
299
|
-
const p1 = decodeChar(pfid[10]);
|
|
300
|
-
const p2 = decodeChar(pfid[11]);
|
|
301
|
-
const p3 = decodeChar(pfid[12]);
|
|
302
|
-
const p4 = decodeChar(pfid[13]);
|
|
303
|
-
const p5 = decodeChar(pfid[14]);
|
|
304
|
-
const p6 = decodeChar(pfid[15]);
|
|
305
|
-
const r1 = decodeChar(pfid[16]);
|
|
306
|
-
const r2 = decodeChar(pfid[17]);
|
|
307
|
-
const r3 = decodeChar(pfid[18]);
|
|
308
|
-
const r4 = decodeChar(pfid[19]);
|
|
309
|
-
const r5 = decodeChar(pfid[20]);
|
|
310
|
-
const r6 = decodeChar(pfid[21]);
|
|
311
|
-
const r7 = decodeChar(pfid[22]);
|
|
312
|
-
const r8 = decodeChar(pfid[23]);
|
|
313
|
-
const r9 = decodeChar(pfid[24]);
|
|
314
|
-
const r10 = decodeChar(pfid[25]);
|
|
315
|
-
const r11 = decodeChar(pfid[26]);
|
|
316
|
-
const r12 = decodeChar(pfid[27]);
|
|
317
|
-
const r13 = decodeChar(pfid[28]);
|
|
318
|
-
const r14 = decodeChar(pfid[29]);
|
|
319
|
-
const r15 = decodeChar(pfid[30]);
|
|
320
|
-
const r16 = decodeChar(pfid[31]);
|
|
321
|
-
const buffer = Buffer.alloc(20, 0);
|
|
322
|
-
let bitOffset = 0;
|
|
323
|
-
function writeBits(value, count) {
|
|
324
|
-
for (let i = count - 1;i >= 0; i--) {
|
|
325
|
-
const byteIndex = Math.floor(bitOffset / 8);
|
|
326
|
-
const bitIndex = 7 - bitOffset % 8;
|
|
327
|
-
const bit = value >> i & 1;
|
|
328
|
-
buffer[byteIndex] |= bit << bitIndex;
|
|
329
|
-
bitOffset++;
|
|
330
|
-
}
|
|
331
|
-
}
|
|
332
|
-
writeBits(t1, 3);
|
|
333
|
-
writeBits(t2, 5);
|
|
334
|
-
writeBits(t3, 5);
|
|
335
|
-
writeBits(t4, 5);
|
|
336
|
-
writeBits(t5, 5);
|
|
337
|
-
writeBits(t6, 5);
|
|
338
|
-
writeBits(t7, 5);
|
|
339
|
-
writeBits(t8, 5);
|
|
340
|
-
writeBits(t9, 5);
|
|
341
|
-
writeBits(t10, 5);
|
|
342
|
-
writeBits(0, 2);
|
|
343
|
-
writeBits(p1, 5);
|
|
344
|
-
writeBits(p2, 5);
|
|
345
|
-
writeBits(p3, 5);
|
|
346
|
-
writeBits(p4, 5);
|
|
347
|
-
writeBits(p5, 5);
|
|
348
|
-
writeBits(p6, 5);
|
|
349
|
-
writeBits(r1, 5);
|
|
350
|
-
writeBits(r2, 5);
|
|
351
|
-
writeBits(r3, 5);
|
|
352
|
-
writeBits(r4, 5);
|
|
353
|
-
writeBits(r5, 5);
|
|
354
|
-
writeBits(r6, 5);
|
|
355
|
-
writeBits(r7, 5);
|
|
356
|
-
writeBits(r8, 5);
|
|
357
|
-
writeBits(r9, 5);
|
|
358
|
-
writeBits(r10, 5);
|
|
359
|
-
writeBits(r11, 5);
|
|
360
|
-
writeBits(r12, 5);
|
|
361
|
-
writeBits(r13, 5);
|
|
362
|
-
writeBits(r14, 5);
|
|
363
|
-
writeBits(r15, 5);
|
|
364
|
-
writeBits(r16, 5);
|
|
365
|
-
return buffer;
|
|
366
|
-
}
|
|
367
|
-
function decodePartition(partitionStr) {
|
|
368
|
-
if (typeof partitionStr !== "string" || partitionStr.length !== 6) {
|
|
369
|
-
throw errors_1.PfidError.make("invalid_partition", partitionStr);
|
|
370
|
-
}
|
|
371
|
-
try {
|
|
372
|
-
const p1 = decodeChar(partitionStr[0]);
|
|
373
|
-
const p2 = decodeChar(partitionStr[1]);
|
|
374
|
-
const p3 = decodeChar(partitionStr[2]);
|
|
375
|
-
const p4 = decodeChar(partitionStr[3]);
|
|
376
|
-
const p5 = decodeChar(partitionStr[4]);
|
|
377
|
-
const p6 = decodeChar(partitionStr[5]);
|
|
378
|
-
const buffer = Buffer.allocUnsafe(4);
|
|
379
|
-
buffer[0] = 0 << 6 | p1 << 1 | p2 >> 4;
|
|
380
|
-
buffer[1] = (p2 & 15) << 4 | p3 >> 1;
|
|
381
|
-
buffer[2] = (p3 & 1) << 7 | p4 << 2 | p5 >> 3;
|
|
382
|
-
buffer[3] = (p5 & 7) << 5 | p6 >> 0;
|
|
383
|
-
const partition = buffer.readUInt32BE(0) & 1073741823;
|
|
384
|
-
return partition;
|
|
385
|
-
} catch (error) {
|
|
386
|
-
if (error instanceof errors_1.PfidError) {
|
|
387
|
-
throw error;
|
|
388
|
-
}
|
|
389
|
-
throw errors_1.PfidError.make("invalid_partition", partitionStr);
|
|
390
|
-
}
|
|
391
|
-
}
|
|
392
|
-
});
|
|
393
|
-
|
|
394
|
-
// node_modules/@prefactor/pfid/dist/index.js
|
|
395
|
-
var require_dist = __commonJS((exports) => {
|
|
396
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
397
|
-
exports.PfidError = exports.generatePartition = exports.extractPartition = exports.decode = exports.encode = exports.isPfid = exports.generateBinaryWithTimestamp = exports.generateBinary = exports.generateRoot = exports.generateRelated = exports.generateExample = exports.generateWithTimestamp = exports.generate = exports.zero = undefined;
|
|
398
|
-
var pfid_1 = require_pfid();
|
|
399
|
-
Object.defineProperty(exports, "zero", { enumerable: true, get: function() {
|
|
400
|
-
return pfid_1.zero;
|
|
401
|
-
} });
|
|
402
|
-
Object.defineProperty(exports, "generate", { enumerable: true, get: function() {
|
|
403
|
-
return pfid_1.generate;
|
|
404
|
-
} });
|
|
405
|
-
Object.defineProperty(exports, "generateWithTimestamp", { enumerable: true, get: function() {
|
|
406
|
-
return pfid_1.generateWithTimestamp;
|
|
407
|
-
} });
|
|
408
|
-
Object.defineProperty(exports, "generateExample", { enumerable: true, get: function() {
|
|
409
|
-
return pfid_1.generateExample;
|
|
410
|
-
} });
|
|
411
|
-
Object.defineProperty(exports, "generateRelated", { enumerable: true, get: function() {
|
|
412
|
-
return pfid_1.generateRelated;
|
|
413
|
-
} });
|
|
414
|
-
Object.defineProperty(exports, "generateRoot", { enumerable: true, get: function() {
|
|
415
|
-
return pfid_1.generateRoot;
|
|
416
|
-
} });
|
|
417
|
-
Object.defineProperty(exports, "generateBinary", { enumerable: true, get: function() {
|
|
418
|
-
return pfid_1.generateBinary;
|
|
419
|
-
} });
|
|
420
|
-
Object.defineProperty(exports, "generateBinaryWithTimestamp", { enumerable: true, get: function() {
|
|
421
|
-
return pfid_1.generateBinaryWithTimestamp;
|
|
422
|
-
} });
|
|
423
|
-
Object.defineProperty(exports, "isPfid", { enumerable: true, get: function() {
|
|
424
|
-
return pfid_1.isPfid;
|
|
425
|
-
} });
|
|
426
|
-
Object.defineProperty(exports, "encode", { enumerable: true, get: function() {
|
|
427
|
-
return pfid_1.encode;
|
|
428
|
-
} });
|
|
429
|
-
Object.defineProperty(exports, "decode", { enumerable: true, get: function() {
|
|
430
|
-
return pfid_1.decode;
|
|
431
|
-
} });
|
|
432
|
-
Object.defineProperty(exports, "extractPartition", { enumerable: true, get: function() {
|
|
433
|
-
return pfid_1.extractPartition;
|
|
434
|
-
} });
|
|
435
|
-
Object.defineProperty(exports, "generatePartition", { enumerable: true, get: function() {
|
|
436
|
-
return pfid_1.generatePartition;
|
|
437
|
-
} });
|
|
438
|
-
var errors_1 = require_errors();
|
|
439
|
-
Object.defineProperty(exports, "PfidError", { enumerable: true, get: function() {
|
|
440
|
-
return errors_1.PfidError;
|
|
441
|
-
} });
|
|
442
|
-
});
|
|
443
|
-
|
|
444
|
-
// src/index.ts
|
|
445
|
-
var import_pfid2 = __toESM(require_dist(), 1);
|
|
446
|
-
|
|
447
|
-
// src/tracing/tracer.ts
|
|
448
|
-
var import_pfid = __toESM(require_dist(), 1);
|
|
449
|
-
|
|
450
|
-
// src/tracing/span.ts
|
|
451
|
-
var SpanType;
|
|
452
|
-
((SpanType2) => {
|
|
453
|
-
SpanType2["AGENT"] = "agent";
|
|
454
|
-
SpanType2["LLM"] = "llm";
|
|
455
|
-
SpanType2["TOOL"] = "tool";
|
|
456
|
-
SpanType2["CHAIN"] = "chain";
|
|
457
|
-
SpanType2["RETRIEVER"] = "retriever";
|
|
458
|
-
})(SpanType ||= {});
|
|
459
|
-
var SpanStatus;
|
|
460
|
-
((SpanStatus2) => {
|
|
461
|
-
SpanStatus2["RUNNING"] = "running";
|
|
462
|
-
SpanStatus2["SUCCESS"] = "success";
|
|
463
|
-
SpanStatus2["ERROR"] = "error";
|
|
464
|
-
})(SpanStatus ||= {});
|
|
465
|
-
|
|
466
|
-
// src/tracing/tracer.ts
|
|
467
|
-
class Tracer {
|
|
468
|
-
transport;
|
|
469
|
-
partition;
|
|
470
|
-
constructor(transport, partition) {
|
|
471
|
-
this.transport = transport;
|
|
472
|
-
this.partition = partition ?? import_pfid.generatePartition();
|
|
473
|
-
}
|
|
474
|
-
startSpan(options) {
|
|
475
|
-
const spanId = import_pfid.generate(this.partition);
|
|
476
|
-
const traceId = options.traceId ?? import_pfid.generate(this.partition);
|
|
477
|
-
const span = {
|
|
478
|
-
spanId,
|
|
479
|
-
parentSpanId: options.parentSpanId ?? null,
|
|
480
|
-
traceId,
|
|
481
|
-
name: options.name,
|
|
482
|
-
spanType: options.spanType,
|
|
483
|
-
startTime: Date.now(),
|
|
484
|
-
endTime: null,
|
|
485
|
-
status: "running" /* RUNNING */,
|
|
486
|
-
inputs: options.inputs,
|
|
487
|
-
outputs: null,
|
|
488
|
-
tokenUsage: null,
|
|
489
|
-
error: null,
|
|
490
|
-
metadata: options.metadata ?? {},
|
|
491
|
-
tags: options.tags ?? []
|
|
492
|
-
};
|
|
493
|
-
if (options.spanType === "agent") {
|
|
494
|
-
try {
|
|
495
|
-
this.transport.emit(span);
|
|
496
|
-
} catch (error) {
|
|
497
|
-
console.error("Failed to emit agent span:", error);
|
|
498
|
-
}
|
|
499
|
-
}
|
|
500
|
-
return span;
|
|
501
|
-
}
|
|
502
|
-
endSpan(span, options) {
|
|
503
|
-
span.endTime = Date.now();
|
|
504
|
-
span.outputs = options?.outputs ?? null;
|
|
505
|
-
span.tokenUsage = options?.tokenUsage ?? null;
|
|
506
|
-
if (options?.error) {
|
|
507
|
-
span.status = "error" /* ERROR */;
|
|
508
|
-
span.error = {
|
|
509
|
-
errorType: options.error.constructor.name,
|
|
510
|
-
message: options.error.message,
|
|
511
|
-
stacktrace: options.error.stack ?? ""
|
|
512
|
-
};
|
|
513
|
-
} else {
|
|
514
|
-
span.status = "success" /* SUCCESS */;
|
|
515
|
-
}
|
|
516
|
-
try {
|
|
517
|
-
if (span.spanType === "agent") {
|
|
518
|
-
this.transport.finishSpan(span.spanId, span.endTime);
|
|
519
|
-
} else {
|
|
520
|
-
this.transport.emit(span);
|
|
521
|
-
}
|
|
522
|
-
} catch (error) {
|
|
523
|
-
console.error("Failed to emit/finish span:", error);
|
|
524
|
-
}
|
|
525
|
-
}
|
|
526
|
-
startAgentInstance() {
|
|
527
|
-
try {
|
|
528
|
-
this.transport.startAgentInstance();
|
|
529
|
-
} catch (error) {
|
|
530
|
-
console.error("Failed to start agent instance:", error);
|
|
531
|
-
}
|
|
532
|
-
}
|
|
533
|
-
finishAgentInstance() {
|
|
534
|
-
try {
|
|
535
|
-
this.transport.finishAgentInstance();
|
|
536
|
-
} catch (error) {
|
|
537
|
-
console.error("Failed to finish agent instance:", error);
|
|
538
|
-
}
|
|
539
|
-
}
|
|
540
|
-
async close() {
|
|
541
|
-
try {
|
|
542
|
-
await this.transport.close();
|
|
543
|
-
} catch (error) {
|
|
544
|
-
console.error("Failed to close transport:", error);
|
|
545
|
-
}
|
|
546
|
-
}
|
|
547
|
-
}
|
|
548
|
-
|
|
549
|
-
// src/tracing/context.ts
|
|
550
|
-
import { AsyncLocalStorage } from "node:async_hooks";
|
|
551
|
-
var spanStorage = new AsyncLocalStorage;
|
|
552
|
-
|
|
553
|
-
class SpanContext {
|
|
554
|
-
static getCurrent() {
|
|
555
|
-
return spanStorage.getStore();
|
|
556
|
-
}
|
|
557
|
-
static run(span, fn) {
|
|
558
|
-
return spanStorage.run(span, fn);
|
|
559
|
-
}
|
|
560
|
-
static async runAsync(span, fn) {
|
|
561
|
-
return spanStorage.run(span, fn);
|
|
562
|
-
}
|
|
563
|
-
static clear() {
|
|
564
|
-
spanStorage.disable();
|
|
565
|
-
}
|
|
566
|
-
}
|
|
567
|
-
|
|
568
|
-
// src/instrumentation/langchain/metadata-extractor.ts
|
|
569
|
-
function extractTokenUsage(response) {
|
|
570
|
-
try {
|
|
571
|
-
const tokenUsage = response?.token_usage ?? response?.usage;
|
|
572
|
-
if (tokenUsage) {
|
|
573
|
-
return {
|
|
574
|
-
promptTokens: tokenUsage.prompt_tokens ?? 0,
|
|
575
|
-
completionTokens: tokenUsage.completion_tokens ?? 0,
|
|
576
|
-
totalTokens: tokenUsage.total_tokens ?? 0
|
|
577
|
-
};
|
|
578
|
-
}
|
|
579
|
-
const usageMetadata = response?.usage_metadata;
|
|
580
|
-
if (usageMetadata) {
|
|
581
|
-
return {
|
|
582
|
-
promptTokens: usageMetadata.input_tokens ?? 0,
|
|
583
|
-
completionTokens: usageMetadata.output_tokens ?? 0,
|
|
584
|
-
totalTokens: usageMetadata.total_tokens ?? 0
|
|
585
|
-
};
|
|
586
|
-
}
|
|
587
|
-
const responseMetadata = response?.response_metadata;
|
|
588
|
-
if (responseMetadata?.token_usage) {
|
|
589
|
-
return {
|
|
590
|
-
promptTokens: responseMetadata.token_usage.prompt_tokens ?? 0,
|
|
591
|
-
completionTokens: responseMetadata.token_usage.completion_tokens ?? 0,
|
|
592
|
-
totalTokens: responseMetadata.token_usage.total_tokens ?? 0
|
|
593
|
-
};
|
|
594
|
-
}
|
|
595
|
-
return null;
|
|
596
|
-
} catch {
|
|
597
|
-
return null;
|
|
598
|
-
}
|
|
599
|
-
}
|
|
600
|
-
|
|
601
|
-
// src/instrumentation/langchain/middleware.ts
|
|
602
|
-
class PrefactorMiddleware {
|
|
603
|
-
tracer;
|
|
604
|
-
rootSpan = null;
|
|
605
|
-
constructor(tracer) {
|
|
606
|
-
this.tracer = tracer;
|
|
607
|
-
}
|
|
608
|
-
async beforeAgent(state) {
|
|
609
|
-
const parentSpan = SpanContext.getCurrent();
|
|
610
|
-
const messages = state?.messages ?? [];
|
|
611
|
-
this.tracer.startAgentInstance();
|
|
612
|
-
const span = this.tracer.startSpan({
|
|
613
|
-
name: "agent",
|
|
614
|
-
spanType: "agent" /* AGENT */,
|
|
615
|
-
inputs: { messages: messages.slice(-3).map((m) => String(m)) },
|
|
616
|
-
parentSpanId: parentSpan?.spanId,
|
|
617
|
-
traceId: parentSpan?.traceId
|
|
618
|
-
});
|
|
619
|
-
this.rootSpan = span;
|
|
620
|
-
}
|
|
621
|
-
async afterAgent(state) {
|
|
622
|
-
if (!this.rootSpan) {
|
|
623
|
-
return;
|
|
624
|
-
}
|
|
625
|
-
const messages = state?.messages ?? [];
|
|
626
|
-
this.tracer.endSpan(this.rootSpan, {
|
|
627
|
-
outputs: { messages: messages.slice(-3).map((m) => String(m)) }
|
|
628
|
-
});
|
|
629
|
-
this.tracer.finishAgentInstance();
|
|
630
|
-
SpanContext.clear();
|
|
631
|
-
this.rootSpan = null;
|
|
632
|
-
}
|
|
633
|
-
async wrapModelCall(request, handler) {
|
|
634
|
-
const parentSpan = SpanContext.getCurrent();
|
|
635
|
-
const span = this.tracer.startSpan({
|
|
636
|
-
name: this.extractModelName(request),
|
|
637
|
-
spanType: "llm" /* LLM */,
|
|
638
|
-
inputs: this.extractModelInputs(request),
|
|
639
|
-
parentSpanId: parentSpan?.spanId,
|
|
640
|
-
traceId: parentSpan?.traceId
|
|
641
|
-
});
|
|
642
|
-
try {
|
|
643
|
-
const response = await SpanContext.runAsync(span, async () => {
|
|
644
|
-
return handler(request);
|
|
645
|
-
});
|
|
646
|
-
const outputs = this.extractModelOutputs(response);
|
|
647
|
-
const tokenUsage = extractTokenUsage(response);
|
|
648
|
-
this.tracer.endSpan(span, { outputs, tokenUsage: tokenUsage ?? undefined });
|
|
649
|
-
return response;
|
|
650
|
-
} catch (error) {
|
|
651
|
-
this.tracer.endSpan(span, { error });
|
|
652
|
-
throw error;
|
|
653
|
-
}
|
|
654
|
-
}
|
|
655
|
-
async wrapToolCall(request, handler) {
|
|
656
|
-
const parentSpan = SpanContext.getCurrent();
|
|
657
|
-
const span = this.tracer.startSpan({
|
|
658
|
-
name: this.extractToolName(request),
|
|
659
|
-
spanType: "tool" /* TOOL */,
|
|
660
|
-
inputs: this.extractToolInputs(request),
|
|
661
|
-
parentSpanId: parentSpan?.spanId,
|
|
662
|
-
traceId: parentSpan?.traceId
|
|
663
|
-
});
|
|
664
|
-
try {
|
|
665
|
-
const response = await SpanContext.runAsync(span, async () => {
|
|
666
|
-
return handler(request);
|
|
667
|
-
});
|
|
668
|
-
this.tracer.endSpan(span, {
|
|
669
|
-
outputs: this.extractToolOutputs(response)
|
|
670
|
-
});
|
|
671
|
-
return response;
|
|
672
|
-
} catch (error) {
|
|
673
|
-
this.tracer.endSpan(span, { error });
|
|
674
|
-
throw error;
|
|
675
|
-
}
|
|
676
|
-
}
|
|
677
|
-
extractModelName(request) {
|
|
678
|
-
return request?.model ?? request?.modelName ?? "unknown";
|
|
679
|
-
}
|
|
680
|
-
extractModelInputs(request) {
|
|
681
|
-
const messages = request?.messages ?? [];
|
|
682
|
-
return { messages: messages.slice(-3).map((m) => String(m)) };
|
|
683
|
-
}
|
|
684
|
-
extractModelOutputs(response) {
|
|
685
|
-
const content = response?.content ?? response?.text ?? "";
|
|
686
|
-
return { content: String(content) };
|
|
687
|
-
}
|
|
688
|
-
extractToolName(request) {
|
|
689
|
-
return request?.name ?? request?.tool ?? "unknown";
|
|
690
|
-
}
|
|
691
|
-
extractToolInputs(request) {
|
|
692
|
-
return { input: request?.input ?? request?.args ?? {} };
|
|
693
|
-
}
|
|
694
|
-
extractToolOutputs(response) {
|
|
695
|
-
return { output: response?.output ?? response };
|
|
696
|
-
}
|
|
697
|
-
}
|
|
698
|
-
|
|
699
|
-
// src/utils/serialization.ts
|
|
700
|
-
function truncateString(value, maxLength) {
|
|
701
|
-
if (value.length <= maxLength) {
|
|
702
|
-
return value;
|
|
703
|
-
}
|
|
704
|
-
return value.slice(0, maxLength) + "... [truncated]";
|
|
705
|
-
}
|
|
706
|
-
function serializeValue(value, maxLength = 1e4) {
|
|
707
|
-
if (value === null || value === undefined) {
|
|
708
|
-
return value;
|
|
709
|
-
}
|
|
710
|
-
if (typeof value === "boolean" || typeof value === "number") {
|
|
711
|
-
return value;
|
|
712
|
-
}
|
|
713
|
-
if (typeof value === "string") {
|
|
714
|
-
return maxLength !== null ? truncateString(value, maxLength) : value;
|
|
715
|
-
}
|
|
716
|
-
if (Array.isArray(value)) {
|
|
717
|
-
return value.map((item) => serializeValue(item, maxLength));
|
|
718
|
-
}
|
|
719
|
-
if (typeof value === "object") {
|
|
720
|
-
const result = {};
|
|
721
|
-
for (const [key, val] of Object.entries(value)) {
|
|
722
|
-
result[key] = serializeValue(val, maxLength);
|
|
723
|
-
}
|
|
724
|
-
return result;
|
|
725
|
-
}
|
|
726
|
-
try {
|
|
727
|
-
return String(value);
|
|
728
|
-
} catch {
|
|
729
|
-
return `<${typeof value} object>`;
|
|
730
|
-
}
|
|
731
|
-
}
|
|
732
|
-
|
|
733
|
-
// src/transport/stdio.ts
|
|
734
|
-
class StdioTransport {
|
|
735
|
-
closed = false;
|
|
736
|
-
writeLock = Promise.resolve();
|
|
737
|
-
emit(span) {
|
|
738
|
-
if (this.closed) {
|
|
739
|
-
return;
|
|
740
|
-
}
|
|
741
|
-
this.writeLock = this.writeLock.then(async () => {
|
|
742
|
-
try {
|
|
743
|
-
const serialized = serializeValue(span);
|
|
744
|
-
const json = JSON.stringify(serialized);
|
|
745
|
-
await Bun.write(Bun.stdout, json + `
|
|
746
|
-
`);
|
|
747
|
-
} catch (error) {
|
|
748
|
-
console.error("Failed to emit span to stdout:", error);
|
|
749
|
-
}
|
|
750
|
-
});
|
|
751
|
-
}
|
|
752
|
-
finishSpan() {}
|
|
753
|
-
startAgentInstance() {}
|
|
754
|
-
finishAgentInstance() {}
|
|
755
|
-
async close() {
|
|
756
|
-
this.closed = true;
|
|
757
|
-
await this.writeLock;
|
|
758
|
-
}
|
|
759
|
-
}
|
|
760
|
-
|
|
761
|
-
// src/utils/logging.ts
|
|
762
|
-
class Logger {
|
|
763
|
-
namespace;
|
|
764
|
-
static level = 1 /* INFO */;
|
|
765
|
-
constructor(namespace) {
|
|
766
|
-
this.namespace = namespace;
|
|
767
|
-
}
|
|
768
|
-
debug(message, ...args) {
|
|
769
|
-
if (Logger.level <= 0 /* DEBUG */) {
|
|
770
|
-
console.debug(`[prefactor:${this.namespace}] ${message}`, ...args);
|
|
771
|
-
}
|
|
772
|
-
}
|
|
773
|
-
info(message, ...args) {
|
|
774
|
-
if (Logger.level <= 1 /* INFO */) {
|
|
775
|
-
console.info(`[prefactor:${this.namespace}] ${message}`, ...args);
|
|
776
|
-
}
|
|
777
|
-
}
|
|
778
|
-
warn(message, ...args) {
|
|
779
|
-
if (Logger.level <= 2 /* WARN */) {
|
|
780
|
-
console.warn(`[prefactor:${this.namespace}] ${message}`, ...args);
|
|
781
|
-
}
|
|
782
|
-
}
|
|
783
|
-
error(message, ...args) {
|
|
784
|
-
if (Logger.level <= 3 /* ERROR */) {
|
|
785
|
-
console.error(`[prefactor:${this.namespace}] ${message}`, ...args);
|
|
786
|
-
}
|
|
787
|
-
}
|
|
788
|
-
static setLevel(level) {
|
|
789
|
-
const levelMap = {
|
|
790
|
-
debug: 0 /* DEBUG */,
|
|
791
|
-
info: 1 /* INFO */,
|
|
792
|
-
warn: 2 /* WARN */,
|
|
793
|
-
error: 3 /* ERROR */
|
|
794
|
-
};
|
|
795
|
-
Logger.level = levelMap[level];
|
|
796
|
-
}
|
|
797
|
-
}
|
|
798
|
-
function getLogger(namespace) {
|
|
799
|
-
return new Logger(namespace);
|
|
800
|
-
}
|
|
801
|
-
function configureLogging() {
|
|
802
|
-
const level = process.env.PREFACTOR_LOG_LEVEL?.toLowerCase();
|
|
803
|
-
if (level) {
|
|
804
|
-
Logger.setLevel(level);
|
|
805
|
-
}
|
|
806
|
-
}
|
|
807
|
-
|
|
808
|
-
// src/transport/http.ts
|
|
809
|
-
var logger = getLogger("http-transport");
|
|
810
|
-
|
|
811
|
-
class HttpTransport {
|
|
812
|
-
config;
|
|
813
|
-
queue = [];
|
|
814
|
-
processing = false;
|
|
815
|
-
closed = false;
|
|
816
|
-
agentInstanceId = null;
|
|
817
|
-
spanIdMap = new Map;
|
|
818
|
-
constructor(config) {
|
|
819
|
-
this.config = config;
|
|
820
|
-
this.startProcessing();
|
|
821
|
-
}
|
|
822
|
-
emit(span) {
|
|
823
|
-
if (this.closed) {
|
|
824
|
-
return;
|
|
825
|
-
}
|
|
826
|
-
this.queue.push({ type: "span", data: span });
|
|
827
|
-
}
|
|
828
|
-
finishSpan(spanId, endTime) {
|
|
829
|
-
if (this.closed) {
|
|
830
|
-
return;
|
|
831
|
-
}
|
|
832
|
-
const timestamp = new Date(endTime).toISOString();
|
|
833
|
-
this.queue.push({ type: "finish_span", data: { spanId, timestamp } });
|
|
834
|
-
}
|
|
835
|
-
startAgentInstance() {
|
|
836
|
-
if (this.closed) {
|
|
837
|
-
return;
|
|
838
|
-
}
|
|
839
|
-
this.queue.push({ type: "start_agent", data: null });
|
|
840
|
-
}
|
|
841
|
-
finishAgentInstance() {
|
|
842
|
-
if (this.closed) {
|
|
843
|
-
return;
|
|
844
|
-
}
|
|
845
|
-
this.queue.push({ type: "finish_agent", data: null });
|
|
846
|
-
}
|
|
847
|
-
async startProcessing() {
|
|
848
|
-
this.processing = true;
|
|
849
|
-
while (!this.closed || this.queue.length > 0) {
|
|
850
|
-
if (this.queue.length === 0) {
|
|
851
|
-
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
852
|
-
continue;
|
|
853
|
-
}
|
|
854
|
-
const item = this.queue.shift();
|
|
855
|
-
try {
|
|
856
|
-
if (!this.agentInstanceId && item.type !== "start_agent") {
|
|
857
|
-
await this.ensureAgentRegistered();
|
|
858
|
-
}
|
|
859
|
-
switch (item.type) {
|
|
860
|
-
case "span":
|
|
861
|
-
await this.sendSpan(item.data);
|
|
862
|
-
break;
|
|
863
|
-
case "finish_span":
|
|
864
|
-
await this.finishSpanHttp(item.data);
|
|
865
|
-
break;
|
|
866
|
-
case "start_agent":
|
|
867
|
-
await this.startAgentInstanceHttp();
|
|
868
|
-
break;
|
|
869
|
-
case "finish_agent":
|
|
870
|
-
await this.finishAgentInstanceHttp();
|
|
871
|
-
break;
|
|
872
|
-
}
|
|
873
|
-
} catch (error) {
|
|
874
|
-
logger.error("Error processing queue item:", error);
|
|
875
|
-
}
|
|
876
|
-
}
|
|
877
|
-
this.processing = false;
|
|
878
|
-
}
|
|
879
|
-
async sendSpan(span, retry = 0) {
|
|
880
|
-
const url = `${this.config.apiUrl}/api/v1/agent_spans`;
|
|
881
|
-
const payload = this.transformSpanToApiFormat(span);
|
|
882
|
-
try {
|
|
883
|
-
const response = await fetch(url, {
|
|
884
|
-
method: "POST",
|
|
885
|
-
headers: {
|
|
886
|
-
Authorization: `Bearer ${this.config.apiToken}`,
|
|
887
|
-
"Content-Type": "application/json"
|
|
888
|
-
},
|
|
889
|
-
body: JSON.stringify(payload),
|
|
890
|
-
signal: AbortSignal.timeout(this.config.requestTimeout)
|
|
891
|
-
});
|
|
892
|
-
if (response.ok) {
|
|
893
|
-
const data = await response.json();
|
|
894
|
-
const backendSpanId = data?.details?.id;
|
|
895
|
-
if (backendSpanId) {
|
|
896
|
-
this.spanIdMap.set(span.spanId, backendSpanId);
|
|
897
|
-
}
|
|
898
|
-
return;
|
|
899
|
-
}
|
|
900
|
-
if ((response.status >= 500 || response.status === 429) && retry < this.config.maxRetries) {
|
|
901
|
-
const delay = Math.min(this.config.initialRetryDelay * Math.pow(this.config.retryMultiplier, retry), this.config.maxRetryDelay);
|
|
902
|
-
logger.debug(`Retrying span send after ${delay}ms (attempt ${retry + 1})`);
|
|
903
|
-
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
904
|
-
return this.sendSpan(span, retry + 1);
|
|
905
|
-
}
|
|
906
|
-
logger.error(`Failed to send span: ${response.status} ${response.statusText}`);
|
|
907
|
-
} catch (error) {
|
|
908
|
-
logger.error("Error sending span:", error);
|
|
909
|
-
if (retry < this.config.maxRetries) {
|
|
910
|
-
const delay = Math.min(this.config.initialRetryDelay * Math.pow(this.config.retryMultiplier, retry), this.config.maxRetryDelay);
|
|
911
|
-
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
912
|
-
return this.sendSpan(span, retry + 1);
|
|
913
|
-
}
|
|
914
|
-
}
|
|
915
|
-
}
|
|
916
|
-
transformSpanToApiFormat(span) {
|
|
917
|
-
const startedAt = new Date(span.startTime).toISOString();
|
|
918
|
-
const finishedAt = span.endTime ? new Date(span.endTime).toISOString() : null;
|
|
919
|
-
const payload = {
|
|
920
|
-
span_id: span.spanId,
|
|
921
|
-
trace_id: span.traceId,
|
|
922
|
-
name: span.name,
|
|
923
|
-
status: span.status,
|
|
924
|
-
inputs: span.inputs,
|
|
925
|
-
outputs: span.outputs,
|
|
926
|
-
metadata: span.metadata,
|
|
927
|
-
tags: span.tags,
|
|
928
|
-
token_usage: null,
|
|
929
|
-
error: null
|
|
930
|
-
};
|
|
931
|
-
if (span.tokenUsage) {
|
|
932
|
-
payload.token_usage = {
|
|
933
|
-
prompt_tokens: span.tokenUsage.promptTokens,
|
|
934
|
-
completion_tokens: span.tokenUsage.completionTokens,
|
|
935
|
-
total_tokens: span.tokenUsage.totalTokens
|
|
936
|
-
};
|
|
937
|
-
}
|
|
938
|
-
if (span.error) {
|
|
939
|
-
payload.error = {
|
|
940
|
-
error_type: span.error.errorType,
|
|
941
|
-
message: span.error.message,
|
|
942
|
-
stacktrace: span.error.stacktrace
|
|
943
|
-
};
|
|
944
|
-
}
|
|
945
|
-
const parentSpanId = span.parentSpanId ? this.spanIdMap.get(span.parentSpanId) ?? null : null;
|
|
946
|
-
return {
|
|
947
|
-
details: {
|
|
948
|
-
agent_instance_id: this.agentInstanceId,
|
|
949
|
-
schema_name: span.spanType,
|
|
950
|
-
payload,
|
|
951
|
-
parent_span_id: parentSpanId,
|
|
952
|
-
started_at: startedAt,
|
|
953
|
-
finished_at: finishedAt
|
|
954
|
-
}
|
|
955
|
-
};
|
|
956
|
-
}
|
|
957
|
-
getDefaultSchema() {
|
|
958
|
-
return {
|
|
959
|
-
external_identifier: "1.0.0",
|
|
960
|
-
span_schemas: {
|
|
961
|
-
agent: {
|
|
962
|
-
type: "object",
|
|
963
|
-
properties: { type: { type: "string", const: "agent" } }
|
|
964
|
-
},
|
|
965
|
-
llm: {
|
|
966
|
-
type: "object",
|
|
967
|
-
properties: { type: { type: "string", const: "llm" } }
|
|
968
|
-
},
|
|
969
|
-
tool: {
|
|
970
|
-
type: "object",
|
|
971
|
-
properties: { type: { type: "string", const: "tool" } }
|
|
972
|
-
},
|
|
973
|
-
chain: {
|
|
974
|
-
type: "object",
|
|
975
|
-
properties: { type: { type: "string", const: "chain" } }
|
|
976
|
-
},
|
|
977
|
-
retriever: {
|
|
978
|
-
type: "object",
|
|
979
|
-
properties: { type: { type: "string", const: "retriever" } }
|
|
980
|
-
}
|
|
981
|
-
}
|
|
982
|
-
};
|
|
983
|
-
}
|
|
984
|
-
async ensureAgentRegistered() {
|
|
985
|
-
if (this.agentInstanceId) {
|
|
986
|
-
return;
|
|
987
|
-
}
|
|
988
|
-
const url = `${this.config.apiUrl}/api/v1/agent_instance/register`;
|
|
989
|
-
const payload = {};
|
|
990
|
-
if (this.config.agentId)
|
|
991
|
-
payload.agent_id = this.config.agentId;
|
|
992
|
-
if (this.config.agentVersion) {
|
|
993
|
-
payload.agent_version = {
|
|
994
|
-
external_identifier: this.config.agentVersion,
|
|
995
|
-
name: this.config.agentName || "Agent",
|
|
996
|
-
description: this.config.agentDescription || ""
|
|
997
|
-
};
|
|
998
|
-
}
|
|
999
|
-
if (this.config.skipSchema) {
|
|
1000
|
-
logger.debug("Skipping schema in registration (skipSchema=true)");
|
|
1001
|
-
} else if (this.config.agentSchema) {
|
|
1002
|
-
logger.debug("Using custom agent schema");
|
|
1003
|
-
payload.agent_schema_version = this.config.agentSchema;
|
|
1004
|
-
} else if (this.config.agentSchemaVersion) {
|
|
1005
|
-
logger.debug(`Using schema version: ${this.config.agentSchemaVersion}`);
|
|
1006
|
-
payload.agent_schema_version = {
|
|
1007
|
-
external_identifier: this.config.agentSchemaVersion
|
|
1008
|
-
};
|
|
1009
|
-
} else {
|
|
1010
|
-
logger.debug("Using default hardcoded schema (v1.0.0)");
|
|
1011
|
-
payload.agent_schema_version = this.getDefaultSchema();
|
|
1012
|
-
}
|
|
1013
|
-
try {
|
|
1014
|
-
const response = await fetch(url, {
|
|
1015
|
-
method: "POST",
|
|
1016
|
-
headers: {
|
|
1017
|
-
Authorization: `Bearer ${this.config.apiToken}`,
|
|
1018
|
-
"Content-Type": "application/json"
|
|
1019
|
-
},
|
|
1020
|
-
body: JSON.stringify(payload),
|
|
1021
|
-
signal: AbortSignal.timeout(this.config.requestTimeout)
|
|
1022
|
-
});
|
|
1023
|
-
if (response.ok) {
|
|
1024
|
-
const data = await response.json();
|
|
1025
|
-
this.agentInstanceId = data?.details?.id ?? null;
|
|
1026
|
-
logger.debug(`Registered agent instance: ${this.agentInstanceId}`);
|
|
1027
|
-
} else {
|
|
1028
|
-
logger.error(`Failed to register agent: ${response.status} ${response.statusText}`);
|
|
1029
|
-
}
|
|
1030
|
-
} catch (error) {
|
|
1031
|
-
logger.error("Error registering agent:", error);
|
|
1032
|
-
}
|
|
1033
|
-
}
|
|
1034
|
-
async startAgentInstanceHttp() {
|
|
1035
|
-
await this.ensureAgentRegistered();
|
|
1036
|
-
if (!this.agentInstanceId) {
|
|
1037
|
-
logger.error("Cannot start agent instance: not registered");
|
|
1038
|
-
return;
|
|
1039
|
-
}
|
|
1040
|
-
const url = `${this.config.apiUrl}/api/v1/agent_instance/${this.agentInstanceId}/start`;
|
|
1041
|
-
try {
|
|
1042
|
-
const response = await fetch(url, {
|
|
1043
|
-
method: "POST",
|
|
1044
|
-
headers: {
|
|
1045
|
-
Authorization: `Bearer ${this.config.apiToken}`,
|
|
1046
|
-
"Content-Type": "application/json"
|
|
1047
|
-
},
|
|
1048
|
-
body: JSON.stringify({}),
|
|
1049
|
-
signal: AbortSignal.timeout(this.config.requestTimeout)
|
|
1050
|
-
});
|
|
1051
|
-
if (!response.ok) {
|
|
1052
|
-
logger.error(`Failed to start agent instance: ${response.status} ${response.statusText}`);
|
|
1053
|
-
}
|
|
1054
|
-
} catch (error) {
|
|
1055
|
-
logger.error("Error starting agent instance:", error);
|
|
1056
|
-
}
|
|
1057
|
-
}
|
|
1058
|
-
async finishAgentInstanceHttp() {
|
|
1059
|
-
if (!this.agentInstanceId) {
|
|
1060
|
-
logger.error("Cannot finish agent instance: not registered");
|
|
1061
|
-
return;
|
|
1062
|
-
}
|
|
1063
|
-
const url = `${this.config.apiUrl}/api/v1/agent_instance/${this.agentInstanceId}/finish`;
|
|
1064
|
-
try {
|
|
1065
|
-
const response = await fetch(url, {
|
|
1066
|
-
method: "POST",
|
|
1067
|
-
headers: {
|
|
1068
|
-
Authorization: `Bearer ${this.config.apiToken}`,
|
|
1069
|
-
"Content-Type": "application/json"
|
|
1070
|
-
},
|
|
1071
|
-
body: JSON.stringify({}),
|
|
1072
|
-
signal: AbortSignal.timeout(this.config.requestTimeout)
|
|
1073
|
-
});
|
|
1074
|
-
if (!response.ok) {
|
|
1075
|
-
logger.error(`Failed to finish agent instance: ${response.status} ${response.statusText}`);
|
|
1076
|
-
}
|
|
1077
|
-
} catch (error) {
|
|
1078
|
-
logger.error("Error finishing agent instance:", error);
|
|
1079
|
-
}
|
|
1080
|
-
}
|
|
1081
|
-
async finishSpanHttp(data) {
|
|
1082
|
-
const backendSpanId = this.spanIdMap.get(data.spanId);
|
|
1083
|
-
if (!backendSpanId) {
|
|
1084
|
-
logger.warn(`Cannot finish span ${data.spanId}: backend ID not found`);
|
|
1085
|
-
return;
|
|
1086
|
-
}
|
|
1087
|
-
const url = `${this.config.apiUrl}/api/v1/agent_spans/${backendSpanId}/finish`;
|
|
1088
|
-
try {
|
|
1089
|
-
const response = await fetch(url, {
|
|
1090
|
-
method: "POST",
|
|
1091
|
-
headers: {
|
|
1092
|
-
Authorization: `Bearer ${this.config.apiToken}`,
|
|
1093
|
-
"Content-Type": "application/json"
|
|
1094
|
-
},
|
|
1095
|
-
body: JSON.stringify({ timestamp: data.timestamp }),
|
|
1096
|
-
signal: AbortSignal.timeout(this.config.requestTimeout)
|
|
1097
|
-
});
|
|
1098
|
-
if (!response.ok) {
|
|
1099
|
-
logger.error(`Failed to finish span: ${response.status} ${response.statusText}`);
|
|
1100
|
-
}
|
|
1101
|
-
} catch (error) {
|
|
1102
|
-
logger.error("Error finishing span:", error);
|
|
1103
|
-
}
|
|
1104
|
-
}
|
|
1105
|
-
async close() {
|
|
1106
|
-
this.closed = true;
|
|
1107
|
-
const timeout = 1e4;
|
|
1108
|
-
const start = Date.now();
|
|
1109
|
-
while (this.processing && Date.now() - start < timeout) {
|
|
1110
|
-
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
1111
|
-
}
|
|
1112
|
-
if (this.processing) {
|
|
1113
|
-
logger.warn("Transport closed with pending queue items");
|
|
1114
|
-
}
|
|
1115
|
-
}
|
|
1116
|
-
}
|
|
1117
|
-
|
|
1118
|
-
// src/config.ts
|
|
1119
|
-
import { z } from "zod";
|
|
1120
|
-
var HttpTransportConfigSchema = z.object({
|
|
1121
|
-
apiUrl: z.string().url(),
|
|
1122
|
-
apiToken: z.string().min(1),
|
|
1123
|
-
agentId: z.string().optional(),
|
|
1124
|
-
agentVersion: z.string().optional(),
|
|
1125
|
-
agentName: z.string().optional(),
|
|
1126
|
-
agentDescription: z.string().optional(),
|
|
1127
|
-
agentSchema: z.record(z.unknown()).optional(),
|
|
1128
|
-
agentSchemaVersion: z.string().optional(),
|
|
1129
|
-
skipSchema: z.boolean().default(false),
|
|
1130
|
-
requestTimeout: z.number().positive().default(30000),
|
|
1131
|
-
connectTimeout: z.number().positive().default(1e4),
|
|
1132
|
-
maxRetries: z.number().int().nonnegative().default(3),
|
|
1133
|
-
initialRetryDelay: z.number().positive().default(1000),
|
|
1134
|
-
maxRetryDelay: z.number().positive().default(60000),
|
|
1135
|
-
retryMultiplier: z.number().positive().default(2)
|
|
1136
|
-
});
|
|
1137
|
-
var PartialHttpConfigSchema = z.object({
|
|
1138
|
-
apiUrl: z.string().url(),
|
|
1139
|
-
apiToken: z.string().min(1),
|
|
1140
|
-
agentId: z.string().optional(),
|
|
1141
|
-
agentVersion: z.string().optional(),
|
|
1142
|
-
agentName: z.string().optional(),
|
|
1143
|
-
agentDescription: z.string().optional(),
|
|
1144
|
-
agentSchema: z.record(z.unknown()).optional(),
|
|
1145
|
-
agentSchemaVersion: z.string().optional(),
|
|
1146
|
-
skipSchema: z.boolean().optional(),
|
|
1147
|
-
requestTimeout: z.number().positive().optional(),
|
|
1148
|
-
connectTimeout: z.number().positive().optional(),
|
|
1149
|
-
maxRetries: z.number().int().nonnegative().optional(),
|
|
1150
|
-
initialRetryDelay: z.number().positive().optional(),
|
|
1151
|
-
maxRetryDelay: z.number().positive().optional(),
|
|
1152
|
-
retryMultiplier: z.number().positive().optional()
|
|
1153
|
-
});
|
|
1154
|
-
var ConfigSchema = z.object({
|
|
1155
|
-
transportType: z.enum(["stdio", "http"]).default("stdio"),
|
|
1156
|
-
sampleRate: z.number().min(0).max(1).default(1),
|
|
1157
|
-
captureInputs: z.boolean().default(true),
|
|
1158
|
-
captureOutputs: z.boolean().default(true),
|
|
1159
|
-
maxInputLength: z.number().int().positive().default(1e4),
|
|
1160
|
-
maxOutputLength: z.number().int().positive().default(1e4),
|
|
1161
|
-
httpConfig: PartialHttpConfigSchema.optional()
|
|
1162
|
-
});
|
|
1163
|
-
function createConfig(options) {
|
|
1164
|
-
const config = {
|
|
1165
|
-
transportType: options?.transportType ?? process.env.PREFACTOR_TRANSPORT ?? "stdio",
|
|
1166
|
-
sampleRate: options?.sampleRate ?? parseFloat(process.env.PREFACTOR_SAMPLE_RATE ?? "1.0"),
|
|
1167
|
-
captureInputs: options?.captureInputs ?? process.env.PREFACTOR_CAPTURE_INPUTS !== "false",
|
|
1168
|
-
captureOutputs: options?.captureOutputs ?? process.env.PREFACTOR_CAPTURE_OUTPUTS !== "false",
|
|
1169
|
-
maxInputLength: options?.maxInputLength ?? parseInt(process.env.PREFACTOR_MAX_INPUT_LENGTH ?? "10000", 10),
|
|
1170
|
-
maxOutputLength: options?.maxOutputLength ?? parseInt(process.env.PREFACTOR_MAX_OUTPUT_LENGTH ?? "10000", 10),
|
|
1171
|
-
httpConfig: options?.httpConfig
|
|
1172
|
-
};
|
|
1173
|
-
return ConfigSchema.parse(config);
|
|
1174
|
-
}
|
|
1175
|
-
|
|
1176
|
-
// src/index.ts
|
|
1177
|
-
import { createMiddleware } from "langchain";
|
|
1178
|
-
var logger2 = getLogger("init");
|
|
1179
|
-
var globalTracer = null;
|
|
1180
|
-
var globalMiddleware = null;
|
|
1181
|
-
function init(config) {
|
|
1182
|
-
configureLogging();
|
|
1183
|
-
const finalConfig = createConfig(config);
|
|
1184
|
-
logger2.info("Initializing Prefactor SDK", { transport: finalConfig.transportType });
|
|
1185
|
-
if (globalMiddleware !== null) {
|
|
1186
|
-
return globalMiddleware;
|
|
1187
|
-
}
|
|
1188
|
-
let transport;
|
|
1189
|
-
if (finalConfig.transportType === "stdio") {
|
|
1190
|
-
transport = new StdioTransport;
|
|
1191
|
-
} else {
|
|
1192
|
-
if (!finalConfig.httpConfig) {
|
|
1193
|
-
throw new Error("HTTP transport requires httpConfig to be provided in configuration");
|
|
1194
|
-
}
|
|
1195
|
-
const httpConfig = HttpTransportConfigSchema.parse(finalConfig.httpConfig);
|
|
1196
|
-
transport = new HttpTransport(httpConfig);
|
|
1197
|
-
}
|
|
1198
|
-
let partition;
|
|
1199
|
-
if (finalConfig.httpConfig?.agentId) {
|
|
1200
|
-
try {
|
|
1201
|
-
partition = import_pfid2.extractPartition(finalConfig.httpConfig.agentId);
|
|
1202
|
-
logger2.debug("Extracted partition from agent_id", { partition });
|
|
1203
|
-
} catch (error) {
|
|
1204
|
-
logger2.warn("Failed to extract partition from agent_id, using random partition", { error });
|
|
1205
|
-
}
|
|
1206
|
-
}
|
|
1207
|
-
globalTracer = new Tracer(transport, partition);
|
|
1208
|
-
const prefactorMiddleware = new PrefactorMiddleware(globalTracer);
|
|
1209
|
-
const middleware = createMiddleware({
|
|
1210
|
-
name: "prefactor",
|
|
1211
|
-
wrapModelCall: async (request, handler) => {
|
|
1212
|
-
return prefactorMiddleware.wrapModelCall(request, handler);
|
|
1213
|
-
},
|
|
1214
|
-
wrapToolCall: async (request, handler) => {
|
|
1215
|
-
return prefactorMiddleware.wrapToolCall(request, handler);
|
|
1216
|
-
},
|
|
1217
|
-
beforeAgent: async (state) => {
|
|
1218
|
-
await prefactorMiddleware.beforeAgent(state);
|
|
1219
|
-
},
|
|
1220
|
-
afterAgent: async (state) => {
|
|
1221
|
-
await prefactorMiddleware.afterAgent(state);
|
|
1222
|
-
}
|
|
1223
|
-
});
|
|
1224
|
-
globalMiddleware = middleware;
|
|
1225
|
-
return middleware;
|
|
1226
|
-
}
|
|
1227
|
-
function getTracer() {
|
|
1228
|
-
if (!globalTracer) {
|
|
1229
|
-
init();
|
|
1230
|
-
}
|
|
1231
|
-
return globalTracer;
|
|
1232
|
-
}
|
|
1233
|
-
async function shutdown() {
|
|
1234
|
-
if (globalTracer) {
|
|
1235
|
-
logger2.info("Shutting down Prefactor SDK");
|
|
1236
|
-
await globalTracer.close();
|
|
1237
|
-
}
|
|
1238
|
-
globalTracer = null;
|
|
1239
|
-
globalMiddleware = null;
|
|
1240
|
-
}
|
|
1241
|
-
process.on("beforeExit", () => {
|
|
1242
|
-
shutdown().catch((error) => {
|
|
1243
|
-
console.error("Error during Prefactor SDK shutdown:", error);
|
|
1244
|
-
});
|
|
1245
|
-
});
|
|
1246
|
-
export {
|
|
1247
|
-
shutdown,
|
|
1248
|
-
init,
|
|
1249
|
-
getTracer,
|
|
1250
|
-
Tracer,
|
|
1251
|
-
SpanType,
|
|
1252
|
-
SpanStatus,
|
|
1253
|
-
PrefactorMiddleware
|
|
1254
|
-
};
|
|
1255
|
-
|
|
1256
|
-
//# debugId=1DD2DA9AA541304F64756E2164756E21
|
|
5
|
+
//# debugId=51D31C5E4283DDA964756E2164756E21
|