@elizaos/plugin-trajectory-logger 2.0.0-alpha.4 → 2.0.0-alpha.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,2485 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __export = (target, all) => {
3
+ for (var name in all)
4
+ __defProp(target, name, {
5
+ get: all[name],
6
+ enumerable: true,
7
+ configurable: true,
8
+ set: (newValue) => all[name] = () => newValue
9
+ });
10
+ };
11
+ var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
12
+
13
+ // ../../../../node_modules/drizzle-orm/entity.js
14
+ function is(value, type) {
15
+ if (!value || typeof value !== "object") {
16
+ return false;
17
+ }
18
+ if (value instanceof type) {
19
+ return true;
20
+ }
21
+ if (!Object.prototype.hasOwnProperty.call(type, entityKind)) {
22
+ throw new Error(`Class "${type.name ?? "<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);
23
+ }
24
+ let cls = Object.getPrototypeOf(value).constructor;
25
+ if (cls) {
26
+ while (cls) {
27
+ if (entityKind in cls && cls[entityKind] === type[entityKind]) {
28
+ return true;
29
+ }
30
+ cls = Object.getPrototypeOf(cls);
31
+ }
32
+ }
33
+ return false;
34
+ }
35
+ var entityKind, hasOwnEntityKind;
36
+ var init_entity = __esm(() => {
37
+ entityKind = Symbol.for("drizzle:entityKind");
38
+ hasOwnEntityKind = Symbol.for("drizzle:hasOwnEntityKind");
39
+ });
40
+
41
+ // ../../../../node_modules/drizzle-orm/column.js
42
+ var Column;
43
+ var init_column = __esm(() => {
44
+ init_entity();
45
+ Column = class Column {
46
+ constructor(table, config) {
47
+ this.table = table;
48
+ this.config = config;
49
+ this.name = config.name;
50
+ this.keyAsName = config.keyAsName;
51
+ this.notNull = config.notNull;
52
+ this.default = config.default;
53
+ this.defaultFn = config.defaultFn;
54
+ this.onUpdateFn = config.onUpdateFn;
55
+ this.hasDefault = config.hasDefault;
56
+ this.primary = config.primaryKey;
57
+ this.isUnique = config.isUnique;
58
+ this.uniqueName = config.uniqueName;
59
+ this.uniqueType = config.uniqueType;
60
+ this.dataType = config.dataType;
61
+ this.columnType = config.columnType;
62
+ this.generated = config.generated;
63
+ this.generatedIdentity = config.generatedIdentity;
64
+ }
65
+ static [entityKind] = "Column";
66
+ name;
67
+ keyAsName;
68
+ primary;
69
+ notNull;
70
+ default;
71
+ defaultFn;
72
+ onUpdateFn;
73
+ hasDefault;
74
+ isUnique;
75
+ uniqueName;
76
+ uniqueType;
77
+ dataType;
78
+ columnType;
79
+ enumValues = undefined;
80
+ generated = undefined;
81
+ generatedIdentity = undefined;
82
+ config;
83
+ mapFromDriverValue(value) {
84
+ return value;
85
+ }
86
+ mapToDriverValue(value) {
87
+ return value;
88
+ }
89
+ shouldDisableInsert() {
90
+ return this.config.generated !== undefined && this.config.generated.type !== "byDefault";
91
+ }
92
+ };
93
+ });
94
+
95
+ // ../../../../node_modules/drizzle-orm/column-builder.js
96
+ var ColumnBuilder;
97
+ var init_column_builder = __esm(() => {
98
+ init_entity();
99
+ ColumnBuilder = class ColumnBuilder {
100
+ static [entityKind] = "ColumnBuilder";
101
+ config;
102
+ constructor(name, dataType, columnType) {
103
+ this.config = {
104
+ name,
105
+ keyAsName: name === "",
106
+ notNull: false,
107
+ default: undefined,
108
+ hasDefault: false,
109
+ primaryKey: false,
110
+ isUnique: false,
111
+ uniqueName: undefined,
112
+ uniqueType: undefined,
113
+ dataType,
114
+ columnType,
115
+ generated: undefined
116
+ };
117
+ }
118
+ $type() {
119
+ return this;
120
+ }
121
+ notNull() {
122
+ this.config.notNull = true;
123
+ return this;
124
+ }
125
+ default(value) {
126
+ this.config.default = value;
127
+ this.config.hasDefault = true;
128
+ return this;
129
+ }
130
+ $defaultFn(fn) {
131
+ this.config.defaultFn = fn;
132
+ this.config.hasDefault = true;
133
+ return this;
134
+ }
135
+ $default = this.$defaultFn;
136
+ $onUpdateFn(fn) {
137
+ this.config.onUpdateFn = fn;
138
+ this.config.hasDefault = true;
139
+ return this;
140
+ }
141
+ $onUpdate = this.$onUpdateFn;
142
+ primaryKey() {
143
+ this.config.primaryKey = true;
144
+ this.config.notNull = true;
145
+ return this;
146
+ }
147
+ setName(name) {
148
+ if (this.config.name !== "")
149
+ return;
150
+ this.config.name = name;
151
+ }
152
+ };
153
+ });
154
+
155
+ // ../../../../node_modules/drizzle-orm/table.utils.js
156
+ var TableName;
157
+ var init_table_utils = __esm(() => {
158
+ TableName = Symbol.for("drizzle:Name");
159
+ });
160
+
161
+ // ../../../../node_modules/drizzle-orm/tracing-utils.js
162
+ function iife(fn, ...args) {
163
+ return fn(...args);
164
+ }
165
+ var init_tracing_utils = () => {};
166
+
167
+ // ../../../../node_modules/drizzle-orm/pg-core/unique-constraint.js
168
+ function uniqueKeyName(table, columns) {
169
+ return `${table[TableName]}_${columns.join("_")}_unique`;
170
+ }
171
+ var init_unique_constraint = __esm(() => {
172
+ init_table_utils();
173
+ });
174
+
175
+ // ../../../../node_modules/drizzle-orm/pg-core/columns/common.js
176
+ var PgColumn, ExtraConfigColumn;
177
+ var init_common = __esm(() => {
178
+ init_column();
179
+ init_entity();
180
+ init_unique_constraint();
181
+ PgColumn = class PgColumn extends Column {
182
+ constructor(table, config) {
183
+ if (!config.uniqueName) {
184
+ config.uniqueName = uniqueKeyName(table, [config.name]);
185
+ }
186
+ super(table, config);
187
+ this.table = table;
188
+ }
189
+ static [entityKind] = "PgColumn";
190
+ };
191
+ ExtraConfigColumn = class ExtraConfigColumn extends PgColumn {
192
+ static [entityKind] = "ExtraConfigColumn";
193
+ getSQLType() {
194
+ return this.getSQLType();
195
+ }
196
+ indexConfig = {
197
+ order: this.config.order ?? "asc",
198
+ nulls: this.config.nulls ?? "last",
199
+ opClass: this.config.opClass
200
+ };
201
+ defaultConfig = {
202
+ order: "asc",
203
+ nulls: "last",
204
+ opClass: undefined
205
+ };
206
+ asc() {
207
+ this.indexConfig.order = "asc";
208
+ return this;
209
+ }
210
+ desc() {
211
+ this.indexConfig.order = "desc";
212
+ return this;
213
+ }
214
+ nullsFirst() {
215
+ this.indexConfig.nulls = "first";
216
+ return this;
217
+ }
218
+ nullsLast() {
219
+ this.indexConfig.nulls = "last";
220
+ return this;
221
+ }
222
+ op(opClass) {
223
+ this.indexConfig.opClass = opClass;
224
+ return this;
225
+ }
226
+ };
227
+ });
228
+
229
+ // ../../../../node_modules/drizzle-orm/pg-core/columns/enum.js
230
+ function isPgEnum(obj) {
231
+ return !!obj && typeof obj === "function" && isPgEnumSym in obj && obj[isPgEnumSym] === true;
232
+ }
233
+ var PgEnumObjectColumn, isPgEnumSym, PgEnumColumn;
234
+ var init_enum = __esm(() => {
235
+ init_entity();
236
+ init_common();
237
+ PgEnumObjectColumn = class PgEnumObjectColumn extends PgColumn {
238
+ static [entityKind] = "PgEnumObjectColumn";
239
+ enum;
240
+ enumValues = this.config.enum.enumValues;
241
+ constructor(table, config) {
242
+ super(table, config);
243
+ this.enum = config.enum;
244
+ }
245
+ getSQLType() {
246
+ return this.enum.enumName;
247
+ }
248
+ };
249
+ isPgEnumSym = Symbol.for("drizzle:isPgEnum");
250
+ PgEnumColumn = class PgEnumColumn extends PgColumn {
251
+ static [entityKind] = "PgEnumColumn";
252
+ enum = this.config.enum;
253
+ enumValues = this.config.enum.enumValues;
254
+ constructor(table, config) {
255
+ super(table, config);
256
+ this.enum = config.enum;
257
+ }
258
+ getSQLType() {
259
+ return this.enum.enumName;
260
+ }
261
+ };
262
+ });
263
+
264
+ // ../../../../node_modules/drizzle-orm/subquery.js
265
+ var Subquery, WithSubquery;
266
+ var init_subquery = __esm(() => {
267
+ init_entity();
268
+ Subquery = class Subquery {
269
+ static [entityKind] = "Subquery";
270
+ constructor(sql, fields, alias, isWith = false, usedTables = []) {
271
+ this._ = {
272
+ brand: "Subquery",
273
+ sql,
274
+ selectedFields: fields,
275
+ alias,
276
+ isWith,
277
+ usedTables
278
+ };
279
+ }
280
+ };
281
+ WithSubquery = class WithSubquery extends Subquery {
282
+ static [entityKind] = "WithSubquery";
283
+ };
284
+ });
285
+
286
+ // ../../../../node_modules/drizzle-orm/version.js
287
+ var version = "0.45.1";
288
+ var init_version = () => {};
289
+
290
+ // ../../../../node_modules/drizzle-orm/tracing.js
291
+ var otel, rawTracer, tracer;
292
+ var init_tracing = __esm(() => {
293
+ init_tracing_utils();
294
+ init_version();
295
+ tracer = {
296
+ startActiveSpan(name, fn) {
297
+ if (!otel) {
298
+ return fn();
299
+ }
300
+ if (!rawTracer) {
301
+ rawTracer = otel.trace.getTracer("drizzle-orm", version);
302
+ }
303
+ return iife((otel2, rawTracer2) => rawTracer2.startActiveSpan(name, (span) => {
304
+ try {
305
+ return fn(span);
306
+ } catch (e) {
307
+ span.setStatus({
308
+ code: otel2.SpanStatusCode.ERROR,
309
+ message: e instanceof Error ? e.message : "Unknown error"
310
+ });
311
+ throw e;
312
+ } finally {
313
+ span.end();
314
+ }
315
+ }), otel, rawTracer);
316
+ }
317
+ };
318
+ });
319
+
320
+ // ../../../../node_modules/drizzle-orm/view-common.js
321
+ var ViewBaseConfig;
322
+ var init_view_common = __esm(() => {
323
+ ViewBaseConfig = Symbol.for("drizzle:ViewBaseConfig");
324
+ });
325
+
326
+ // ../../../../node_modules/drizzle-orm/table.js
327
+ function isTable(table) {
328
+ return typeof table === "object" && table !== null && IsDrizzleTable in table;
329
+ }
330
+ function getTableName(table) {
331
+ return table[TableName];
332
+ }
333
+ function getTableUniqueName(table) {
334
+ return `${table[Schema] ?? "public"}.${table[TableName]}`;
335
+ }
336
+ var Schema, Columns, ExtraConfigColumns, OriginalName, BaseName, IsAlias, ExtraConfigBuilder, IsDrizzleTable, Table;
337
+ var init_table = __esm(() => {
338
+ init_entity();
339
+ init_table_utils();
340
+ Schema = Symbol.for("drizzle:Schema");
341
+ Columns = Symbol.for("drizzle:Columns");
342
+ ExtraConfigColumns = Symbol.for("drizzle:ExtraConfigColumns");
343
+ OriginalName = Symbol.for("drizzle:OriginalName");
344
+ BaseName = Symbol.for("drizzle:BaseName");
345
+ IsAlias = Symbol.for("drizzle:IsAlias");
346
+ ExtraConfigBuilder = Symbol.for("drizzle:ExtraConfigBuilder");
347
+ IsDrizzleTable = Symbol.for("drizzle:IsDrizzleTable");
348
+ Table = class Table {
349
+ static [entityKind] = "Table";
350
+ static Symbol = {
351
+ Name: TableName,
352
+ Schema,
353
+ OriginalName,
354
+ Columns,
355
+ ExtraConfigColumns,
356
+ BaseName,
357
+ IsAlias,
358
+ ExtraConfigBuilder
359
+ };
360
+ [TableName];
361
+ [OriginalName];
362
+ [Schema];
363
+ [Columns];
364
+ [ExtraConfigColumns];
365
+ [BaseName];
366
+ [IsAlias] = false;
367
+ [IsDrizzleTable] = true;
368
+ [ExtraConfigBuilder] = undefined;
369
+ constructor(name, schema, baseName) {
370
+ this[TableName] = this[OriginalName] = name;
371
+ this[Schema] = schema;
372
+ this[BaseName] = baseName;
373
+ }
374
+ };
375
+ });
376
+
377
+ // ../../../../node_modules/drizzle-orm/sql/sql.js
378
+ function isSQLWrapper(value) {
379
+ return value !== null && value !== undefined && typeof value.getSQL === "function";
380
+ }
381
+ function mergeQueries(queries) {
382
+ const result = { sql: "", params: [] };
383
+ for (const query of queries) {
384
+ result.sql += query.sql;
385
+ result.params.push(...query.params);
386
+ if (query.typings?.length) {
387
+ if (!result.typings) {
388
+ result.typings = [];
389
+ }
390
+ result.typings.push(...query.typings);
391
+ }
392
+ }
393
+ return result;
394
+ }
395
+ function name(value) {
396
+ return new Name(value);
397
+ }
398
+ function isDriverValueEncoder(value) {
399
+ return typeof value === "object" && value !== null && "mapToDriverValue" in value && typeof value.mapToDriverValue === "function";
400
+ }
401
+ function param(value, encoder) {
402
+ return new Param(value, encoder);
403
+ }
404
+ function sql(strings, ...params) {
405
+ const queryChunks = [];
406
+ if (params.length > 0 || strings.length > 0 && strings[0] !== "") {
407
+ queryChunks.push(new StringChunk(strings[0]));
408
+ }
409
+ for (const [paramIndex, param2] of params.entries()) {
410
+ queryChunks.push(param2, new StringChunk(strings[paramIndex + 1]));
411
+ }
412
+ return new SQL(queryChunks);
413
+ }
414
+ function placeholder(name2) {
415
+ return new Placeholder(name2);
416
+ }
417
+ function fillPlaceholders(params, values) {
418
+ return params.map((p) => {
419
+ if (is(p, Placeholder)) {
420
+ if (!(p.name in values)) {
421
+ throw new Error(`No value for placeholder "${p.name}" was provided`);
422
+ }
423
+ return values[p.name];
424
+ }
425
+ if (is(p, Param) && is(p.value, Placeholder)) {
426
+ if (!(p.value.name in values)) {
427
+ throw new Error(`No value for placeholder "${p.value.name}" was provided`);
428
+ }
429
+ return p.encoder.mapToDriverValue(values[p.value.name]);
430
+ }
431
+ return p;
432
+ });
433
+ }
434
+ function isView(view) {
435
+ return typeof view === "object" && view !== null && IsDrizzleView in view;
436
+ }
437
+ function getViewName(view) {
438
+ return view[ViewBaseConfig].name;
439
+ }
440
+ var FakePrimitiveParam, StringChunk, SQL, Name, noopDecoder, noopEncoder, noopMapper, Param, Placeholder, IsDrizzleView, View;
441
+ var init_sql = __esm(() => {
442
+ init_entity();
443
+ init_enum();
444
+ init_subquery();
445
+ init_tracing();
446
+ init_view_common();
447
+ init_column();
448
+ init_table();
449
+ FakePrimitiveParam = class FakePrimitiveParam {
450
+ static [entityKind] = "FakePrimitiveParam";
451
+ };
452
+ StringChunk = class StringChunk {
453
+ static [entityKind] = "StringChunk";
454
+ value;
455
+ constructor(value) {
456
+ this.value = Array.isArray(value) ? value : [value];
457
+ }
458
+ getSQL() {
459
+ return new SQL([this]);
460
+ }
461
+ };
462
+ SQL = class SQL {
463
+ constructor(queryChunks) {
464
+ this.queryChunks = queryChunks;
465
+ for (const chunk of queryChunks) {
466
+ if (is(chunk, Table)) {
467
+ const schemaName = chunk[Table.Symbol.Schema];
468
+ this.usedTables.push(schemaName === undefined ? chunk[Table.Symbol.Name] : schemaName + "." + chunk[Table.Symbol.Name]);
469
+ }
470
+ }
471
+ }
472
+ static [entityKind] = "SQL";
473
+ decoder = noopDecoder;
474
+ shouldInlineParams = false;
475
+ usedTables = [];
476
+ append(query) {
477
+ this.queryChunks.push(...query.queryChunks);
478
+ return this;
479
+ }
480
+ toQuery(config) {
481
+ return tracer.startActiveSpan("drizzle.buildSQL", (span) => {
482
+ const query = this.buildQueryFromSourceParams(this.queryChunks, config);
483
+ span?.setAttributes({
484
+ "drizzle.query.text": query.sql,
485
+ "drizzle.query.params": JSON.stringify(query.params)
486
+ });
487
+ return query;
488
+ });
489
+ }
490
+ buildQueryFromSourceParams(chunks, _config) {
491
+ const config = Object.assign({}, _config, {
492
+ inlineParams: _config.inlineParams || this.shouldInlineParams,
493
+ paramStartIndex: _config.paramStartIndex || { value: 0 }
494
+ });
495
+ const {
496
+ casing,
497
+ escapeName,
498
+ escapeParam,
499
+ prepareTyping,
500
+ inlineParams,
501
+ paramStartIndex
502
+ } = config;
503
+ return mergeQueries(chunks.map((chunk) => {
504
+ if (is(chunk, StringChunk)) {
505
+ return { sql: chunk.value.join(""), params: [] };
506
+ }
507
+ if (is(chunk, Name)) {
508
+ return { sql: escapeName(chunk.value), params: [] };
509
+ }
510
+ if (chunk === undefined) {
511
+ return { sql: "", params: [] };
512
+ }
513
+ if (Array.isArray(chunk)) {
514
+ const result = [new StringChunk("(")];
515
+ for (const [i, p] of chunk.entries()) {
516
+ result.push(p);
517
+ if (i < chunk.length - 1) {
518
+ result.push(new StringChunk(", "));
519
+ }
520
+ }
521
+ result.push(new StringChunk(")"));
522
+ return this.buildQueryFromSourceParams(result, config);
523
+ }
524
+ if (is(chunk, SQL)) {
525
+ return this.buildQueryFromSourceParams(chunk.queryChunks, {
526
+ ...config,
527
+ inlineParams: inlineParams || chunk.shouldInlineParams
528
+ });
529
+ }
530
+ if (is(chunk, Table)) {
531
+ const schemaName = chunk[Table.Symbol.Schema];
532
+ const tableName = chunk[Table.Symbol.Name];
533
+ return {
534
+ sql: schemaName === undefined || chunk[IsAlias] ? escapeName(tableName) : escapeName(schemaName) + "." + escapeName(tableName),
535
+ params: []
536
+ };
537
+ }
538
+ if (is(chunk, Column)) {
539
+ const columnName = casing.getColumnCasing(chunk);
540
+ if (_config.invokeSource === "indexes") {
541
+ return { sql: escapeName(columnName), params: [] };
542
+ }
543
+ const schemaName = chunk.table[Table.Symbol.Schema];
544
+ return {
545
+ sql: chunk.table[IsAlias] || schemaName === undefined ? escapeName(chunk.table[Table.Symbol.Name]) + "." + escapeName(columnName) : escapeName(schemaName) + "." + escapeName(chunk.table[Table.Symbol.Name]) + "." + escapeName(columnName),
546
+ params: []
547
+ };
548
+ }
549
+ if (is(chunk, View)) {
550
+ const schemaName = chunk[ViewBaseConfig].schema;
551
+ const viewName = chunk[ViewBaseConfig].name;
552
+ return {
553
+ sql: schemaName === undefined || chunk[ViewBaseConfig].isAlias ? escapeName(viewName) : escapeName(schemaName) + "." + escapeName(viewName),
554
+ params: []
555
+ };
556
+ }
557
+ if (is(chunk, Param)) {
558
+ if (is(chunk.value, Placeholder)) {
559
+ return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] };
560
+ }
561
+ const mappedValue = chunk.value === null ? null : chunk.encoder.mapToDriverValue(chunk.value);
562
+ if (is(mappedValue, SQL)) {
563
+ return this.buildQueryFromSourceParams([mappedValue], config);
564
+ }
565
+ if (inlineParams) {
566
+ return { sql: this.mapInlineParam(mappedValue, config), params: [] };
567
+ }
568
+ let typings = ["none"];
569
+ if (prepareTyping) {
570
+ typings = [prepareTyping(chunk.encoder)];
571
+ }
572
+ return { sql: escapeParam(paramStartIndex.value++, mappedValue), params: [mappedValue], typings };
573
+ }
574
+ if (is(chunk, Placeholder)) {
575
+ return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] };
576
+ }
577
+ if (is(chunk, SQL.Aliased) && chunk.fieldAlias !== undefined) {
578
+ return { sql: escapeName(chunk.fieldAlias), params: [] };
579
+ }
580
+ if (is(chunk, Subquery)) {
581
+ if (chunk._.isWith) {
582
+ return { sql: escapeName(chunk._.alias), params: [] };
583
+ }
584
+ return this.buildQueryFromSourceParams([
585
+ new StringChunk("("),
586
+ chunk._.sql,
587
+ new StringChunk(") "),
588
+ new Name(chunk._.alias)
589
+ ], config);
590
+ }
591
+ if (isPgEnum(chunk)) {
592
+ if (chunk.schema) {
593
+ return { sql: escapeName(chunk.schema) + "." + escapeName(chunk.enumName), params: [] };
594
+ }
595
+ return { sql: escapeName(chunk.enumName), params: [] };
596
+ }
597
+ if (isSQLWrapper(chunk)) {
598
+ if (chunk.shouldOmitSQLParens?.()) {
599
+ return this.buildQueryFromSourceParams([chunk.getSQL()], config);
600
+ }
601
+ return this.buildQueryFromSourceParams([
602
+ new StringChunk("("),
603
+ chunk.getSQL(),
604
+ new StringChunk(")")
605
+ ], config);
606
+ }
607
+ if (inlineParams) {
608
+ return { sql: this.mapInlineParam(chunk, config), params: [] };
609
+ }
610
+ return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] };
611
+ }));
612
+ }
613
+ mapInlineParam(chunk, { escapeString }) {
614
+ if (chunk === null) {
615
+ return "null";
616
+ }
617
+ if (typeof chunk === "number" || typeof chunk === "boolean") {
618
+ return chunk.toString();
619
+ }
620
+ if (typeof chunk === "string") {
621
+ return escapeString(chunk);
622
+ }
623
+ if (typeof chunk === "object") {
624
+ const mappedValueAsString = chunk.toString();
625
+ if (mappedValueAsString === "[object Object]") {
626
+ return escapeString(JSON.stringify(chunk));
627
+ }
628
+ return escapeString(mappedValueAsString);
629
+ }
630
+ throw new Error("Unexpected param value: " + chunk);
631
+ }
632
+ getSQL() {
633
+ return this;
634
+ }
635
+ as(alias) {
636
+ if (alias === undefined) {
637
+ return this;
638
+ }
639
+ return new SQL.Aliased(this, alias);
640
+ }
641
+ mapWith(decoder) {
642
+ this.decoder = typeof decoder === "function" ? { mapFromDriverValue: decoder } : decoder;
643
+ return this;
644
+ }
645
+ inlineParams() {
646
+ this.shouldInlineParams = true;
647
+ return this;
648
+ }
649
+ if(condition) {
650
+ return condition ? this : undefined;
651
+ }
652
+ };
653
+ Name = class Name {
654
+ constructor(value) {
655
+ this.value = value;
656
+ }
657
+ static [entityKind] = "Name";
658
+ brand;
659
+ getSQL() {
660
+ return new SQL([this]);
661
+ }
662
+ };
663
+ noopDecoder = {
664
+ mapFromDriverValue: (value) => value
665
+ };
666
+ noopEncoder = {
667
+ mapToDriverValue: (value) => value
668
+ };
669
+ noopMapper = {
670
+ ...noopDecoder,
671
+ ...noopEncoder
672
+ };
673
+ Param = class Param {
674
+ constructor(value, encoder = noopEncoder) {
675
+ this.value = value;
676
+ this.encoder = encoder;
677
+ }
678
+ static [entityKind] = "Param";
679
+ brand;
680
+ getSQL() {
681
+ return new SQL([this]);
682
+ }
683
+ };
684
+ ((sql2) => {
685
+ function empty() {
686
+ return new SQL([]);
687
+ }
688
+ sql2.empty = empty;
689
+ function fromList(list) {
690
+ return new SQL(list);
691
+ }
692
+ sql2.fromList = fromList;
693
+ function raw(str) {
694
+ return new SQL([new StringChunk(str)]);
695
+ }
696
+ sql2.raw = raw;
697
+ function join(chunks, separator) {
698
+ const result = [];
699
+ for (const [i, chunk] of chunks.entries()) {
700
+ if (i > 0 && separator !== undefined) {
701
+ result.push(separator);
702
+ }
703
+ result.push(chunk);
704
+ }
705
+ return new SQL(result);
706
+ }
707
+ sql2.join = join;
708
+ function identifier(value) {
709
+ return new Name(value);
710
+ }
711
+ sql2.identifier = identifier;
712
+ function placeholder2(name2) {
713
+ return new Placeholder(name2);
714
+ }
715
+ sql2.placeholder = placeholder2;
716
+ function param2(value, encoder) {
717
+ return new Param(value, encoder);
718
+ }
719
+ sql2.param = param2;
720
+ })(sql || (sql = {}));
721
+ ((SQL2) => {
722
+
723
+ class Aliased {
724
+ constructor(sql2, fieldAlias) {
725
+ this.sql = sql2;
726
+ this.fieldAlias = fieldAlias;
727
+ }
728
+ static [entityKind] = "SQL.Aliased";
729
+ isSelectionField = false;
730
+ getSQL() {
731
+ return this.sql;
732
+ }
733
+ clone() {
734
+ return new Aliased(this.sql, this.fieldAlias);
735
+ }
736
+ }
737
+ SQL2.Aliased = Aliased;
738
+ })(SQL || (SQL = {}));
739
+ Placeholder = class Placeholder {
740
+ constructor(name2) {
741
+ this.name = name2;
742
+ }
743
+ static [entityKind] = "Placeholder";
744
+ getSQL() {
745
+ return new SQL([this]);
746
+ }
747
+ };
748
+ IsDrizzleView = Symbol.for("drizzle:IsDrizzleView");
749
+ View = class View {
750
+ static [entityKind] = "View";
751
+ [ViewBaseConfig];
752
+ [IsDrizzleView] = true;
753
+ constructor({ name: name2, schema, selectedFields, query }) {
754
+ this[ViewBaseConfig] = {
755
+ name: name2,
756
+ originalName: name2,
757
+ schema,
758
+ selectedFields,
759
+ query,
760
+ isExisting: !query,
761
+ isAlias: false
762
+ };
763
+ }
764
+ getSQL() {
765
+ return new SQL([this]);
766
+ }
767
+ };
768
+ Column.prototype.getSQL = function() {
769
+ return new SQL([this]);
770
+ };
771
+ Table.prototype.getSQL = function() {
772
+ return new SQL([this]);
773
+ };
774
+ Subquery.prototype.getSQL = function() {
775
+ return new SQL([this]);
776
+ };
777
+ });
778
+
779
+ // ../../../../node_modules/drizzle-orm/alias.js
780
+ function aliasedTable(table, tableAlias) {
781
+ return new Proxy(table, new TableAliasProxyHandler(tableAlias, false));
782
+ }
783
+ function aliasedRelation(relation, tableAlias) {
784
+ return new Proxy(relation, new RelationTableAliasProxyHandler(tableAlias));
785
+ }
786
+ function aliasedTableColumn(column, tableAlias) {
787
+ return new Proxy(column, new ColumnAliasProxyHandler(new Proxy(column.table, new TableAliasProxyHandler(tableAlias, false))));
788
+ }
789
+ function mapColumnsInAliasedSQLToAlias(query, alias) {
790
+ return new SQL.Aliased(mapColumnsInSQLToAlias(query.sql, alias), query.fieldAlias);
791
+ }
792
+ function mapColumnsInSQLToAlias(query, alias) {
793
+ return sql.join(query.queryChunks.map((c) => {
794
+ if (is(c, Column)) {
795
+ return aliasedTableColumn(c, alias);
796
+ }
797
+ if (is(c, SQL)) {
798
+ return mapColumnsInSQLToAlias(c, alias);
799
+ }
800
+ if (is(c, SQL.Aliased)) {
801
+ return mapColumnsInAliasedSQLToAlias(c, alias);
802
+ }
803
+ return c;
804
+ }));
805
+ }
806
+ var ColumnAliasProxyHandler, TableAliasProxyHandler, RelationTableAliasProxyHandler;
807
+ var init_alias = __esm(() => {
808
+ init_column();
809
+ init_entity();
810
+ init_sql();
811
+ init_table();
812
+ init_view_common();
813
+ ColumnAliasProxyHandler = class ColumnAliasProxyHandler {
814
+ constructor(table) {
815
+ this.table = table;
816
+ }
817
+ static [entityKind] = "ColumnAliasProxyHandler";
818
+ get(columnObj, prop) {
819
+ if (prop === "table") {
820
+ return this.table;
821
+ }
822
+ return columnObj[prop];
823
+ }
824
+ };
825
+ TableAliasProxyHandler = class TableAliasProxyHandler {
826
+ constructor(alias, replaceOriginalName) {
827
+ this.alias = alias;
828
+ this.replaceOriginalName = replaceOriginalName;
829
+ }
830
+ static [entityKind] = "TableAliasProxyHandler";
831
+ get(target, prop) {
832
+ if (prop === Table.Symbol.IsAlias) {
833
+ return true;
834
+ }
835
+ if (prop === Table.Symbol.Name) {
836
+ return this.alias;
837
+ }
838
+ if (this.replaceOriginalName && prop === Table.Symbol.OriginalName) {
839
+ return this.alias;
840
+ }
841
+ if (prop === ViewBaseConfig) {
842
+ return {
843
+ ...target[ViewBaseConfig],
844
+ name: this.alias,
845
+ isAlias: true
846
+ };
847
+ }
848
+ if (prop === Table.Symbol.Columns) {
849
+ const columns = target[Table.Symbol.Columns];
850
+ if (!columns) {
851
+ return columns;
852
+ }
853
+ const proxiedColumns = {};
854
+ Object.keys(columns).map((key) => {
855
+ proxiedColumns[key] = new Proxy(columns[key], new ColumnAliasProxyHandler(new Proxy(target, this)));
856
+ });
857
+ return proxiedColumns;
858
+ }
859
+ const value = target[prop];
860
+ if (is(value, Column)) {
861
+ return new Proxy(value, new ColumnAliasProxyHandler(new Proxy(target, this)));
862
+ }
863
+ return value;
864
+ }
865
+ };
866
+ RelationTableAliasProxyHandler = class RelationTableAliasProxyHandler {
867
+ constructor(alias) {
868
+ this.alias = alias;
869
+ }
870
+ static [entityKind] = "RelationTableAliasProxyHandler";
871
+ get(target, prop) {
872
+ if (prop === "sourceTable") {
873
+ return aliasedTable(target.sourceTable, this.alias);
874
+ }
875
+ return target[prop];
876
+ }
877
+ };
878
+ });
879
+
880
+ // ../../../../node_modules/drizzle-orm/errors.js
881
+ var DrizzleError, DrizzleQueryError, TransactionRollbackError;
882
+ var init_errors = __esm(() => {
883
+ init_entity();
884
+ DrizzleError = class DrizzleError extends Error {
885
+ static [entityKind] = "DrizzleError";
886
+ constructor({ message, cause }) {
887
+ super(message);
888
+ this.name = "DrizzleError";
889
+ this.cause = cause;
890
+ }
891
+ };
892
+ DrizzleQueryError = class DrizzleQueryError extends Error {
893
+ constructor(query, params, cause) {
894
+ super(`Failed query: ${query}
895
+ params: ${params}`);
896
+ this.query = query;
897
+ this.params = params;
898
+ this.cause = cause;
899
+ Error.captureStackTrace(this, DrizzleQueryError);
900
+ if (cause)
901
+ this.cause = cause;
902
+ }
903
+ };
904
+ TransactionRollbackError = class TransactionRollbackError extends DrizzleError {
905
+ static [entityKind] = "TransactionRollbackError";
906
+ constructor() {
907
+ super({ message: "Rollback" });
908
+ }
909
+ };
910
+ });
911
+
912
+ // ../../../../node_modules/drizzle-orm/logger.js
913
+ var ConsoleLogWriter, DefaultLogger, NoopLogger;
914
+ var init_logger = __esm(() => {
915
+ init_entity();
916
+ ConsoleLogWriter = class ConsoleLogWriter {
917
+ static [entityKind] = "ConsoleLogWriter";
918
+ write(message) {
919
+ console.log(message);
920
+ }
921
+ };
922
+ DefaultLogger = class DefaultLogger {
923
+ static [entityKind] = "DefaultLogger";
924
+ writer;
925
+ constructor(config) {
926
+ this.writer = config?.writer ?? new ConsoleLogWriter;
927
+ }
928
+ logQuery(query, params) {
929
+ const stringifiedParams = params.map((p) => {
930
+ try {
931
+ return JSON.stringify(p);
932
+ } catch {
933
+ return String(p);
934
+ }
935
+ });
936
+ const paramsStr = stringifiedParams.length ? ` -- params: [${stringifiedParams.join(", ")}]` : "";
937
+ this.writer.write(`Query: ${query}${paramsStr}`);
938
+ }
939
+ };
940
+ NoopLogger = class NoopLogger {
941
+ static [entityKind] = "NoopLogger";
942
+ logQuery() {}
943
+ };
944
+ });
945
+
946
+ // ../../../../node_modules/drizzle-orm/query-promise.js
947
+ var QueryPromise;
948
+ var init_query_promise = __esm(() => {
949
+ init_entity();
950
+ QueryPromise = class QueryPromise {
951
+ static [entityKind] = "QueryPromise";
952
+ [Symbol.toStringTag] = "QueryPromise";
953
+ catch(onRejected) {
954
+ return this.then(undefined, onRejected);
955
+ }
956
+ finally(onFinally) {
957
+ return this.then((value) => {
958
+ onFinally?.();
959
+ return value;
960
+ }, (reason) => {
961
+ onFinally?.();
962
+ throw reason;
963
+ });
964
+ }
965
+ then(onFulfilled, onRejected) {
966
+ return this.execute().then(onFulfilled, onRejected);
967
+ }
968
+ };
969
+ });
970
+
971
+ // ../../../../node_modules/drizzle-orm/utils.js
972
+ function mapResultRow(columns, row, joinsNotNullableMap) {
973
+ const nullifyMap = {};
974
+ const result = columns.reduce((result2, { path, field }, columnIndex) => {
975
+ let decoder;
976
+ if (is(field, Column)) {
977
+ decoder = field;
978
+ } else if (is(field, SQL)) {
979
+ decoder = field.decoder;
980
+ } else if (is(field, Subquery)) {
981
+ decoder = field._.sql.decoder;
982
+ } else {
983
+ decoder = field.sql.decoder;
984
+ }
985
+ let node = result2;
986
+ for (const [pathChunkIndex, pathChunk] of path.entries()) {
987
+ if (pathChunkIndex < path.length - 1) {
988
+ if (!(pathChunk in node)) {
989
+ node[pathChunk] = {};
990
+ }
991
+ node = node[pathChunk];
992
+ } else {
993
+ const rawValue = row[columnIndex];
994
+ const value = node[pathChunk] = rawValue === null ? null : decoder.mapFromDriverValue(rawValue);
995
+ if (joinsNotNullableMap && is(field, Column) && path.length === 2) {
996
+ const objectName = path[0];
997
+ if (!(objectName in nullifyMap)) {
998
+ nullifyMap[objectName] = value === null ? getTableName(field.table) : false;
999
+ } else if (typeof nullifyMap[objectName] === "string" && nullifyMap[objectName] !== getTableName(field.table)) {
1000
+ nullifyMap[objectName] = false;
1001
+ }
1002
+ }
1003
+ }
1004
+ }
1005
+ return result2;
1006
+ }, {});
1007
+ if (joinsNotNullableMap && Object.keys(nullifyMap).length > 0) {
1008
+ for (const [objectName, tableName] of Object.entries(nullifyMap)) {
1009
+ if (typeof tableName === "string" && !joinsNotNullableMap[tableName]) {
1010
+ result[objectName] = null;
1011
+ }
1012
+ }
1013
+ }
1014
+ return result;
1015
+ }
1016
+ function orderSelectedFields(fields, pathPrefix) {
1017
+ return Object.entries(fields).reduce((result, [name2, field]) => {
1018
+ if (typeof name2 !== "string") {
1019
+ return result;
1020
+ }
1021
+ const newPath = pathPrefix ? [...pathPrefix, name2] : [name2];
1022
+ if (is(field, Column) || is(field, SQL) || is(field, SQL.Aliased) || is(field, Subquery)) {
1023
+ result.push({ path: newPath, field });
1024
+ } else if (is(field, Table)) {
1025
+ result.push(...orderSelectedFields(field[Table.Symbol.Columns], newPath));
1026
+ } else {
1027
+ result.push(...orderSelectedFields(field, newPath));
1028
+ }
1029
+ return result;
1030
+ }, []);
1031
+ }
1032
+ function haveSameKeys(left, right) {
1033
+ const leftKeys = Object.keys(left);
1034
+ const rightKeys = Object.keys(right);
1035
+ if (leftKeys.length !== rightKeys.length) {
1036
+ return false;
1037
+ }
1038
+ for (const [index, key] of leftKeys.entries()) {
1039
+ if (key !== rightKeys[index]) {
1040
+ return false;
1041
+ }
1042
+ }
1043
+ return true;
1044
+ }
1045
+ function mapUpdateSet(table, values) {
1046
+ const entries = Object.entries(values).filter(([, value]) => value !== undefined).map(([key, value]) => {
1047
+ if (is(value, SQL) || is(value, Column)) {
1048
+ return [key, value];
1049
+ } else {
1050
+ return [key, new Param(value, table[Table.Symbol.Columns][key])];
1051
+ }
1052
+ });
1053
+ if (entries.length === 0) {
1054
+ throw new Error("No values to set");
1055
+ }
1056
+ return Object.fromEntries(entries);
1057
+ }
1058
+ function applyMixins(baseClass, extendedClasses) {
1059
+ for (const extendedClass of extendedClasses) {
1060
+ for (const name2 of Object.getOwnPropertyNames(extendedClass.prototype)) {
1061
+ if (name2 === "constructor")
1062
+ continue;
1063
+ Object.defineProperty(baseClass.prototype, name2, Object.getOwnPropertyDescriptor(extendedClass.prototype, name2) || /* @__PURE__ */ Object.create(null));
1064
+ }
1065
+ }
1066
+ }
1067
+ function getTableColumns(table) {
1068
+ return table[Table.Symbol.Columns];
1069
+ }
1070
+ function getViewSelectedFields(view) {
1071
+ return view[ViewBaseConfig].selectedFields;
1072
+ }
1073
+ function getTableLikeName(table) {
1074
+ return is(table, Subquery) ? table._.alias : is(table, View) ? table[ViewBaseConfig].name : is(table, SQL) ? undefined : table[Table.Symbol.IsAlias] ? table[Table.Symbol.Name] : table[Table.Symbol.BaseName];
1075
+ }
1076
+ function getColumnNameAndConfig(a, b) {
1077
+ return {
1078
+ name: typeof a === "string" && a.length > 0 ? a : "",
1079
+ config: typeof a === "object" ? a : b
1080
+ };
1081
+ }
1082
+ function isConfig(data) {
1083
+ if (typeof data !== "object" || data === null)
1084
+ return false;
1085
+ if (data.constructor.name !== "Object")
1086
+ return false;
1087
+ if ("logger" in data) {
1088
+ const type = typeof data["logger"];
1089
+ if (type !== "boolean" && (type !== "object" || typeof data["logger"]["logQuery"] !== "function") && type !== "undefined")
1090
+ return false;
1091
+ return true;
1092
+ }
1093
+ if ("schema" in data) {
1094
+ const type = typeof data["schema"];
1095
+ if (type !== "object" && type !== "undefined")
1096
+ return false;
1097
+ return true;
1098
+ }
1099
+ if ("casing" in data) {
1100
+ const type = typeof data["casing"];
1101
+ if (type !== "string" && type !== "undefined")
1102
+ return false;
1103
+ return true;
1104
+ }
1105
+ if ("mode" in data) {
1106
+ if (data["mode"] !== "default" || data["mode"] !== "planetscale" || data["mode"] !== undefined)
1107
+ return false;
1108
+ return true;
1109
+ }
1110
+ if ("connection" in data) {
1111
+ const type = typeof data["connection"];
1112
+ if (type !== "string" && type !== "object" && type !== "undefined")
1113
+ return false;
1114
+ return true;
1115
+ }
1116
+ if ("client" in data) {
1117
+ const type = typeof data["client"];
1118
+ if (type !== "object" && type !== "function" && type !== "undefined")
1119
+ return false;
1120
+ return true;
1121
+ }
1122
+ if (Object.keys(data).length === 0)
1123
+ return true;
1124
+ return false;
1125
+ }
1126
+ var textDecoder;
1127
+ var init_utils = __esm(() => {
1128
+ init_column();
1129
+ init_entity();
1130
+ init_sql();
1131
+ init_subquery();
1132
+ init_table();
1133
+ init_view_common();
1134
+ textDecoder = typeof TextDecoder === "undefined" ? null : new TextDecoder;
1135
+ });
1136
+
1137
+ // ../../../../node_modules/drizzle-orm/pg-core/table.js
1138
+ var InlineForeignKeys, EnableRLS, PgTable;
1139
+ var init_table2 = __esm(() => {
1140
+ init_entity();
1141
+ init_table();
1142
+ InlineForeignKeys = Symbol.for("drizzle:PgInlineForeignKeys");
1143
+ EnableRLS = Symbol.for("drizzle:EnableRLS");
1144
+ PgTable = class PgTable extends Table {
1145
+ static [entityKind] = "PgTable";
1146
+ static Symbol = Object.assign({}, Table.Symbol, {
1147
+ InlineForeignKeys,
1148
+ EnableRLS
1149
+ });
1150
+ [InlineForeignKeys] = [];
1151
+ [EnableRLS] = false;
1152
+ [Table.Symbol.ExtraConfigBuilder] = undefined;
1153
+ [Table.Symbol.ExtraConfigColumns] = {};
1154
+ };
1155
+ });
1156
+
1157
+ // ../../../../node_modules/drizzle-orm/pg-core/primary-keys.js
1158
+ var PrimaryKeyBuilder, PrimaryKey;
1159
+ var init_primary_keys = __esm(() => {
1160
+ init_entity();
1161
+ init_table2();
1162
+ PrimaryKeyBuilder = class PrimaryKeyBuilder {
1163
+ static [entityKind] = "PgPrimaryKeyBuilder";
1164
+ columns;
1165
+ name;
1166
+ constructor(columns, name2) {
1167
+ this.columns = columns;
1168
+ this.name = name2;
1169
+ }
1170
+ build(table) {
1171
+ return new PrimaryKey(table, this.columns, this.name);
1172
+ }
1173
+ };
1174
+ PrimaryKey = class PrimaryKey {
1175
+ constructor(table, columns, name2) {
1176
+ this.table = table;
1177
+ this.columns = columns;
1178
+ this.name = name2;
1179
+ }
1180
+ static [entityKind] = "PgPrimaryKey";
1181
+ columns;
1182
+ name;
1183
+ getName() {
1184
+ return this.name ?? `${this.table[PgTable.Symbol.Name]}_${this.columns.map((column) => column.name).join("_")}_pk`;
1185
+ }
1186
+ };
1187
+ });
1188
+
1189
+ // ../../../../node_modules/drizzle-orm/sql/expressions/conditions.js
1190
+ function bindIfParam(value, column) {
1191
+ if (isDriverValueEncoder(column) && !isSQLWrapper(value) && !is(value, Param) && !is(value, Placeholder) && !is(value, Column) && !is(value, Table) && !is(value, View)) {
1192
+ return new Param(value, column);
1193
+ }
1194
+ return value;
1195
+ }
1196
+ function and(...unfilteredConditions) {
1197
+ const conditions = unfilteredConditions.filter((c) => c !== undefined);
1198
+ if (conditions.length === 0) {
1199
+ return;
1200
+ }
1201
+ if (conditions.length === 1) {
1202
+ return new SQL(conditions);
1203
+ }
1204
+ return new SQL([
1205
+ new StringChunk("("),
1206
+ sql.join(conditions, new StringChunk(" and ")),
1207
+ new StringChunk(")")
1208
+ ]);
1209
+ }
1210
+ function or(...unfilteredConditions) {
1211
+ const conditions = unfilteredConditions.filter((c) => c !== undefined);
1212
+ if (conditions.length === 0) {
1213
+ return;
1214
+ }
1215
+ if (conditions.length === 1) {
1216
+ return new SQL(conditions);
1217
+ }
1218
+ return new SQL([
1219
+ new StringChunk("("),
1220
+ sql.join(conditions, new StringChunk(" or ")),
1221
+ new StringChunk(")")
1222
+ ]);
1223
+ }
1224
+ function not(condition) {
1225
+ return sql`not ${condition}`;
1226
+ }
1227
+ function inArray(column, values) {
1228
+ if (Array.isArray(values)) {
1229
+ if (values.length === 0) {
1230
+ return sql`false`;
1231
+ }
1232
+ return sql`${column} in ${values.map((v) => bindIfParam(v, column))}`;
1233
+ }
1234
+ return sql`${column} in ${bindIfParam(values, column)}`;
1235
+ }
1236
+ function notInArray(column, values) {
1237
+ if (Array.isArray(values)) {
1238
+ if (values.length === 0) {
1239
+ return sql`true`;
1240
+ }
1241
+ return sql`${column} not in ${values.map((v) => bindIfParam(v, column))}`;
1242
+ }
1243
+ return sql`${column} not in ${bindIfParam(values, column)}`;
1244
+ }
1245
+ function isNull(value) {
1246
+ return sql`${value} is null`;
1247
+ }
1248
+ function isNotNull(value) {
1249
+ return sql`${value} is not null`;
1250
+ }
1251
+ function exists(subquery) {
1252
+ return sql`exists ${subquery}`;
1253
+ }
1254
+ function notExists(subquery) {
1255
+ return sql`not exists ${subquery}`;
1256
+ }
1257
+ function between(column, min, max) {
1258
+ return sql`${column} between ${bindIfParam(min, column)} and ${bindIfParam(max, column)}`;
1259
+ }
1260
+ function notBetween(column, min, max) {
1261
+ return sql`${column} not between ${bindIfParam(min, column)} and ${bindIfParam(max, column)}`;
1262
+ }
1263
+ function like(column, value) {
1264
+ return sql`${column} like ${value}`;
1265
+ }
1266
+ function notLike(column, value) {
1267
+ return sql`${column} not like ${value}`;
1268
+ }
1269
+ function ilike(column, value) {
1270
+ return sql`${column} ilike ${value}`;
1271
+ }
1272
+ function notIlike(column, value) {
1273
+ return sql`${column} not ilike ${value}`;
1274
+ }
1275
+ function arrayContains(column, values) {
1276
+ if (Array.isArray(values)) {
1277
+ if (values.length === 0) {
1278
+ throw new Error("arrayContains requires at least one value");
1279
+ }
1280
+ const array = sql`${bindIfParam(values, column)}`;
1281
+ return sql`${column} @> ${array}`;
1282
+ }
1283
+ return sql`${column} @> ${bindIfParam(values, column)}`;
1284
+ }
1285
+ function arrayContained(column, values) {
1286
+ if (Array.isArray(values)) {
1287
+ if (values.length === 0) {
1288
+ throw new Error("arrayContained requires at least one value");
1289
+ }
1290
+ const array = sql`${bindIfParam(values, column)}`;
1291
+ return sql`${column} <@ ${array}`;
1292
+ }
1293
+ return sql`${column} <@ ${bindIfParam(values, column)}`;
1294
+ }
1295
+ function arrayOverlaps(column, values) {
1296
+ if (Array.isArray(values)) {
1297
+ if (values.length === 0) {
1298
+ throw new Error("arrayOverlaps requires at least one value");
1299
+ }
1300
+ const array = sql`${bindIfParam(values, column)}`;
1301
+ return sql`${column} && ${array}`;
1302
+ }
1303
+ return sql`${column} && ${bindIfParam(values, column)}`;
1304
+ }
1305
+ var eq = (left, right) => {
1306
+ return sql`${left} = ${bindIfParam(right, left)}`;
1307
+ }, ne = (left, right) => {
1308
+ return sql`${left} <> ${bindIfParam(right, left)}`;
1309
+ }, gt = (left, right) => {
1310
+ return sql`${left} > ${bindIfParam(right, left)}`;
1311
+ }, gte = (left, right) => {
1312
+ return sql`${left} >= ${bindIfParam(right, left)}`;
1313
+ }, lt = (left, right) => {
1314
+ return sql`${left} < ${bindIfParam(right, left)}`;
1315
+ }, lte = (left, right) => {
1316
+ return sql`${left} <= ${bindIfParam(right, left)}`;
1317
+ };
1318
+ var init_conditions = __esm(() => {
1319
+ init_column();
1320
+ init_entity();
1321
+ init_table();
1322
+ init_sql();
1323
+ });
1324
+
1325
+ // ../../../../node_modules/drizzle-orm/sql/expressions/select.js
1326
+ function asc(column) {
1327
+ return sql`${column} asc`;
1328
+ }
1329
+ function desc(column) {
1330
+ return sql`${column} desc`;
1331
+ }
1332
+ var init_select = __esm(() => {
1333
+ init_sql();
1334
+ });
1335
+
1336
+ // ../../../../node_modules/drizzle-orm/sql/expressions/index.js
1337
+ var init_expressions = __esm(() => {
1338
+ init_conditions();
1339
+ init_select();
1340
+ });
1341
+
1342
+ // ../../../../node_modules/drizzle-orm/relations.js
1343
+ function getOperators() {
1344
+ return {
1345
+ and,
1346
+ between,
1347
+ eq,
1348
+ exists,
1349
+ gt,
1350
+ gte,
1351
+ ilike,
1352
+ inArray,
1353
+ isNull,
1354
+ isNotNull,
1355
+ like,
1356
+ lt,
1357
+ lte,
1358
+ ne,
1359
+ not,
1360
+ notBetween,
1361
+ notExists,
1362
+ notLike,
1363
+ notIlike,
1364
+ notInArray,
1365
+ or,
1366
+ sql
1367
+ };
1368
+ }
1369
+ function getOrderByOperators() {
1370
+ return {
1371
+ sql,
1372
+ asc,
1373
+ desc
1374
+ };
1375
+ }
1376
+ function extractTablesRelationalConfig(schema, configHelpers) {
1377
+ if (Object.keys(schema).length === 1 && "default" in schema && !is(schema["default"], Table)) {
1378
+ schema = schema["default"];
1379
+ }
1380
+ const tableNamesMap = {};
1381
+ const relationsBuffer = {};
1382
+ const tablesConfig = {};
1383
+ for (const [key, value] of Object.entries(schema)) {
1384
+ if (is(value, Table)) {
1385
+ const dbName = getTableUniqueName(value);
1386
+ const bufferedRelations = relationsBuffer[dbName];
1387
+ tableNamesMap[dbName] = key;
1388
+ tablesConfig[key] = {
1389
+ tsName: key,
1390
+ dbName: value[Table.Symbol.Name],
1391
+ schema: value[Table.Symbol.Schema],
1392
+ columns: value[Table.Symbol.Columns],
1393
+ relations: bufferedRelations?.relations ?? {},
1394
+ primaryKey: bufferedRelations?.primaryKey ?? []
1395
+ };
1396
+ for (const column of Object.values(value[Table.Symbol.Columns])) {
1397
+ if (column.primary) {
1398
+ tablesConfig[key].primaryKey.push(column);
1399
+ }
1400
+ }
1401
+ const extraConfig = value[Table.Symbol.ExtraConfigBuilder]?.(value[Table.Symbol.ExtraConfigColumns]);
1402
+ if (extraConfig) {
1403
+ for (const configEntry of Object.values(extraConfig)) {
1404
+ if (is(configEntry, PrimaryKeyBuilder)) {
1405
+ tablesConfig[key].primaryKey.push(...configEntry.columns);
1406
+ }
1407
+ }
1408
+ }
1409
+ } else if (is(value, Relations)) {
1410
+ const dbName = getTableUniqueName(value.table);
1411
+ const tableName = tableNamesMap[dbName];
1412
+ const relations2 = value.config(configHelpers(value.table));
1413
+ let primaryKey;
1414
+ for (const [relationName, relation] of Object.entries(relations2)) {
1415
+ if (tableName) {
1416
+ const tableConfig = tablesConfig[tableName];
1417
+ tableConfig.relations[relationName] = relation;
1418
+ if (primaryKey) {
1419
+ tableConfig.primaryKey.push(...primaryKey);
1420
+ }
1421
+ } else {
1422
+ if (!(dbName in relationsBuffer)) {
1423
+ relationsBuffer[dbName] = {
1424
+ relations: {},
1425
+ primaryKey
1426
+ };
1427
+ }
1428
+ relationsBuffer[dbName].relations[relationName] = relation;
1429
+ }
1430
+ }
1431
+ }
1432
+ }
1433
+ return { tables: tablesConfig, tableNamesMap };
1434
+ }
1435
+ function relations(table, relations2) {
1436
+ return new Relations(table, (helpers) => Object.fromEntries(Object.entries(relations2(helpers)).map(([key, value]) => [
1437
+ key,
1438
+ value.withFieldName(key)
1439
+ ])));
1440
+ }
1441
+ function createOne(sourceTable) {
1442
+ return function one(table, config) {
1443
+ return new One(sourceTable, table, config, config?.fields.reduce((res, f) => res && f.notNull, true) ?? false);
1444
+ };
1445
+ }
1446
+ function createMany(sourceTable) {
1447
+ return function many(referencedTable, config) {
1448
+ return new Many(sourceTable, referencedTable, config);
1449
+ };
1450
+ }
1451
+ function normalizeRelation(schema, tableNamesMap, relation) {
1452
+ if (is(relation, One) && relation.config) {
1453
+ return {
1454
+ fields: relation.config.fields,
1455
+ references: relation.config.references
1456
+ };
1457
+ }
1458
+ const referencedTableTsName = tableNamesMap[getTableUniqueName(relation.referencedTable)];
1459
+ if (!referencedTableTsName) {
1460
+ throw new Error(`Table "${relation.referencedTable[Table.Symbol.Name]}" not found in schema`);
1461
+ }
1462
+ const referencedTableConfig = schema[referencedTableTsName];
1463
+ if (!referencedTableConfig) {
1464
+ throw new Error(`Table "${referencedTableTsName}" not found in schema`);
1465
+ }
1466
+ const sourceTable = relation.sourceTable;
1467
+ const sourceTableTsName = tableNamesMap[getTableUniqueName(sourceTable)];
1468
+ if (!sourceTableTsName) {
1469
+ throw new Error(`Table "${sourceTable[Table.Symbol.Name]}" not found in schema`);
1470
+ }
1471
+ const reverseRelations = [];
1472
+ for (const referencedTableRelation of Object.values(referencedTableConfig.relations)) {
1473
+ if (relation.relationName && relation !== referencedTableRelation && referencedTableRelation.relationName === relation.relationName || !relation.relationName && referencedTableRelation.referencedTable === relation.sourceTable) {
1474
+ reverseRelations.push(referencedTableRelation);
1475
+ }
1476
+ }
1477
+ if (reverseRelations.length > 1) {
1478
+ throw relation.relationName ? new Error(`There are multiple relations with name "${relation.relationName}" in table "${referencedTableTsName}"`) : new Error(`There are multiple relations between "${referencedTableTsName}" and "${relation.sourceTable[Table.Symbol.Name]}". Please specify relation name`);
1479
+ }
1480
+ if (reverseRelations[0] && is(reverseRelations[0], One) && reverseRelations[0].config) {
1481
+ return {
1482
+ fields: reverseRelations[0].config.references,
1483
+ references: reverseRelations[0].config.fields
1484
+ };
1485
+ }
1486
+ throw new Error(`There is not enough information to infer relation "${sourceTableTsName}.${relation.fieldName}"`);
1487
+ }
1488
+ function createTableRelationsHelpers(sourceTable) {
1489
+ return {
1490
+ one: createOne(sourceTable),
1491
+ many: createMany(sourceTable)
1492
+ };
1493
+ }
1494
+ function mapRelationalRow(tablesConfig, tableConfig, row, buildQueryResultSelection, mapColumnValue = (value) => value) {
1495
+ const result = {};
1496
+ for (const [
1497
+ selectionItemIndex,
1498
+ selectionItem
1499
+ ] of buildQueryResultSelection.entries()) {
1500
+ if (selectionItem.isJson) {
1501
+ const relation = tableConfig.relations[selectionItem.tsKey];
1502
+ const rawSubRows = row[selectionItemIndex];
1503
+ const subRows = typeof rawSubRows === "string" ? JSON.parse(rawSubRows) : rawSubRows;
1504
+ result[selectionItem.tsKey] = is(relation, One) ? subRows && mapRelationalRow(tablesConfig, tablesConfig[selectionItem.relationTableTsKey], subRows, selectionItem.selection, mapColumnValue) : subRows.map((subRow) => mapRelationalRow(tablesConfig, tablesConfig[selectionItem.relationTableTsKey], subRow, selectionItem.selection, mapColumnValue));
1505
+ } else {
1506
+ const value = mapColumnValue(row[selectionItemIndex]);
1507
+ const field = selectionItem.field;
1508
+ let decoder;
1509
+ if (is(field, Column)) {
1510
+ decoder = field;
1511
+ } else if (is(field, SQL)) {
1512
+ decoder = field.decoder;
1513
+ } else {
1514
+ decoder = field.sql.decoder;
1515
+ }
1516
+ result[selectionItem.tsKey] = value === null ? null : decoder.mapFromDriverValue(value);
1517
+ }
1518
+ }
1519
+ return result;
1520
+ }
1521
+ var Relation, Relations, One, Many;
1522
+ var init_relations = __esm(() => {
1523
+ init_table();
1524
+ init_column();
1525
+ init_entity();
1526
+ init_primary_keys();
1527
+ init_expressions();
1528
+ init_sql();
1529
+ Relation = class Relation {
1530
+ constructor(sourceTable, referencedTable, relationName) {
1531
+ this.sourceTable = sourceTable;
1532
+ this.referencedTable = referencedTable;
1533
+ this.relationName = relationName;
1534
+ this.referencedTableName = referencedTable[Table.Symbol.Name];
1535
+ }
1536
+ static [entityKind] = "Relation";
1537
+ referencedTableName;
1538
+ fieldName;
1539
+ };
1540
+ Relations = class Relations {
1541
+ constructor(table, config) {
1542
+ this.table = table;
1543
+ this.config = config;
1544
+ }
1545
+ static [entityKind] = "Relations";
1546
+ };
1547
+ One = class One extends Relation {
1548
+ constructor(sourceTable, referencedTable, config, isNullable) {
1549
+ super(sourceTable, referencedTable, config?.relationName);
1550
+ this.config = config;
1551
+ this.isNullable = isNullable;
1552
+ }
1553
+ static [entityKind] = "One";
1554
+ withFieldName(fieldName) {
1555
+ const relation = new One(this.sourceTable, this.referencedTable, this.config, this.isNullable);
1556
+ relation.fieldName = fieldName;
1557
+ return relation;
1558
+ }
1559
+ };
1560
+ Many = class Many extends Relation {
1561
+ constructor(sourceTable, referencedTable, config) {
1562
+ super(sourceTable, referencedTable, config?.relationName);
1563
+ this.config = config;
1564
+ }
1565
+ static [entityKind] = "Many";
1566
+ withFieldName(fieldName) {
1567
+ const relation = new Many(this.sourceTable, this.referencedTable, this.config);
1568
+ relation.fieldName = fieldName;
1569
+ return relation;
1570
+ }
1571
+ };
1572
+ });
1573
+
1574
+ // ../../../../node_modules/drizzle-orm/sql/functions/aggregate.js
1575
+ function count(expression) {
1576
+ return sql`count(${expression || sql.raw("*")})`.mapWith(Number);
1577
+ }
1578
+ function countDistinct(expression) {
1579
+ return sql`count(distinct ${expression})`.mapWith(Number);
1580
+ }
1581
+ function avg(expression) {
1582
+ return sql`avg(${expression})`.mapWith(String);
1583
+ }
1584
+ function avgDistinct(expression) {
1585
+ return sql`avg(distinct ${expression})`.mapWith(String);
1586
+ }
1587
+ function sum(expression) {
1588
+ return sql`sum(${expression})`.mapWith(String);
1589
+ }
1590
+ function sumDistinct(expression) {
1591
+ return sql`sum(distinct ${expression})`.mapWith(String);
1592
+ }
1593
+ function max(expression) {
1594
+ return sql`max(${expression})`.mapWith(is(expression, Column) ? expression : String);
1595
+ }
1596
+ function min(expression) {
1597
+ return sql`min(${expression})`.mapWith(is(expression, Column) ? expression : String);
1598
+ }
1599
+ var init_aggregate = __esm(() => {
1600
+ init_column();
1601
+ init_entity();
1602
+ init_sql();
1603
+ });
1604
+
1605
+ // ../../../../node_modules/drizzle-orm/sql/functions/vector.js
1606
+ function toSql(value) {
1607
+ return JSON.stringify(value);
1608
+ }
1609
+ function l2Distance(column, value) {
1610
+ if (Array.isArray(value)) {
1611
+ return sql`${column} <-> ${toSql(value)}`;
1612
+ }
1613
+ return sql`${column} <-> ${value}`;
1614
+ }
1615
+ function l1Distance(column, value) {
1616
+ if (Array.isArray(value)) {
1617
+ return sql`${column} <+> ${toSql(value)}`;
1618
+ }
1619
+ return sql`${column} <+> ${value}`;
1620
+ }
1621
+ function innerProduct(column, value) {
1622
+ if (Array.isArray(value)) {
1623
+ return sql`${column} <#> ${toSql(value)}`;
1624
+ }
1625
+ return sql`${column} <#> ${value}`;
1626
+ }
1627
+ function cosineDistance(column, value) {
1628
+ if (Array.isArray(value)) {
1629
+ return sql`${column} <=> ${toSql(value)}`;
1630
+ }
1631
+ return sql`${column} <=> ${value}`;
1632
+ }
1633
+ function hammingDistance(column, value) {
1634
+ if (Array.isArray(value)) {
1635
+ return sql`${column} <~> ${toSql(value)}`;
1636
+ }
1637
+ return sql`${column} <~> ${value}`;
1638
+ }
1639
+ function jaccardDistance(column, value) {
1640
+ if (Array.isArray(value)) {
1641
+ return sql`${column} <%> ${toSql(value)}`;
1642
+ }
1643
+ return sql`${column} <%> ${value}`;
1644
+ }
1645
+ var init_vector = __esm(() => {
1646
+ init_sql();
1647
+ });
1648
+
1649
+ // ../../../../node_modules/drizzle-orm/sql/functions/index.js
1650
+ var init_functions = __esm(() => {
1651
+ init_aggregate();
1652
+ init_vector();
1653
+ });
1654
+
1655
+ // ../../../../node_modules/drizzle-orm/sql/index.js
1656
+ var init_sql2 = __esm(() => {
1657
+ init_expressions();
1658
+ init_functions();
1659
+ init_sql();
1660
+ });
1661
+
1662
+ // ../../../../node_modules/drizzle-orm/index.js
1663
+ var exports_drizzle_orm = {};
1664
+ __export(exports_drizzle_orm, {
1665
+ textDecoder: () => textDecoder,
1666
+ sumDistinct: () => sumDistinct,
1667
+ sum: () => sum,
1668
+ sql: () => sql,
1669
+ relations: () => relations,
1670
+ placeholder: () => placeholder,
1671
+ param: () => param,
1672
+ orderSelectedFields: () => orderSelectedFields,
1673
+ or: () => or,
1674
+ notLike: () => notLike,
1675
+ notInArray: () => notInArray,
1676
+ notIlike: () => notIlike,
1677
+ notExists: () => notExists,
1678
+ notBetween: () => notBetween,
1679
+ not: () => not,
1680
+ normalizeRelation: () => normalizeRelation,
1681
+ noopMapper: () => noopMapper,
1682
+ noopEncoder: () => noopEncoder,
1683
+ noopDecoder: () => noopDecoder,
1684
+ ne: () => ne,
1685
+ name: () => name,
1686
+ min: () => min,
1687
+ max: () => max,
1688
+ mapUpdateSet: () => mapUpdateSet,
1689
+ mapResultRow: () => mapResultRow,
1690
+ mapRelationalRow: () => mapRelationalRow,
1691
+ mapColumnsInSQLToAlias: () => mapColumnsInSQLToAlias,
1692
+ mapColumnsInAliasedSQLToAlias: () => mapColumnsInAliasedSQLToAlias,
1693
+ lte: () => lte,
1694
+ lt: () => lt,
1695
+ like: () => like,
1696
+ l2Distance: () => l2Distance,
1697
+ l1Distance: () => l1Distance,
1698
+ jaccardDistance: () => jaccardDistance,
1699
+ isView: () => isView,
1700
+ isTable: () => isTable,
1701
+ isSQLWrapper: () => isSQLWrapper,
1702
+ isNull: () => isNull,
1703
+ isNotNull: () => isNotNull,
1704
+ isDriverValueEncoder: () => isDriverValueEncoder,
1705
+ isConfig: () => isConfig,
1706
+ is: () => is,
1707
+ innerProduct: () => innerProduct,
1708
+ inArray: () => inArray,
1709
+ ilike: () => ilike,
1710
+ haveSameKeys: () => haveSameKeys,
1711
+ hasOwnEntityKind: () => hasOwnEntityKind,
1712
+ hammingDistance: () => hammingDistance,
1713
+ gte: () => gte,
1714
+ gt: () => gt,
1715
+ getViewSelectedFields: () => getViewSelectedFields,
1716
+ getViewName: () => getViewName,
1717
+ getTableUniqueName: () => getTableUniqueName,
1718
+ getTableName: () => getTableName,
1719
+ getTableLikeName: () => getTableLikeName,
1720
+ getTableColumns: () => getTableColumns,
1721
+ getOrderByOperators: () => getOrderByOperators,
1722
+ getOperators: () => getOperators,
1723
+ getColumnNameAndConfig: () => getColumnNameAndConfig,
1724
+ fillPlaceholders: () => fillPlaceholders,
1725
+ extractTablesRelationalConfig: () => extractTablesRelationalConfig,
1726
+ exists: () => exists,
1727
+ eq: () => eq,
1728
+ entityKind: () => entityKind,
1729
+ desc: () => desc,
1730
+ createTableRelationsHelpers: () => createTableRelationsHelpers,
1731
+ createOne: () => createOne,
1732
+ createMany: () => createMany,
1733
+ countDistinct: () => countDistinct,
1734
+ count: () => count,
1735
+ cosineDistance: () => cosineDistance,
1736
+ bindIfParam: () => bindIfParam,
1737
+ between: () => between,
1738
+ avgDistinct: () => avgDistinct,
1739
+ avg: () => avg,
1740
+ asc: () => asc,
1741
+ arrayOverlaps: () => arrayOverlaps,
1742
+ arrayContains: () => arrayContains,
1743
+ arrayContained: () => arrayContained,
1744
+ applyMixins: () => applyMixins,
1745
+ and: () => and,
1746
+ aliasedTableColumn: () => aliasedTableColumn,
1747
+ aliasedTable: () => aliasedTable,
1748
+ aliasedRelation: () => aliasedRelation,
1749
+ WithSubquery: () => WithSubquery,
1750
+ ViewBaseConfig: () => ViewBaseConfig,
1751
+ View: () => View,
1752
+ TransactionRollbackError: () => TransactionRollbackError,
1753
+ TableAliasProxyHandler: () => TableAliasProxyHandler,
1754
+ Table: () => Table,
1755
+ Subquery: () => Subquery,
1756
+ StringChunk: () => StringChunk,
1757
+ Schema: () => Schema,
1758
+ SQL: () => SQL,
1759
+ Relations: () => Relations,
1760
+ RelationTableAliasProxyHandler: () => RelationTableAliasProxyHandler,
1761
+ Relation: () => Relation,
1762
+ QueryPromise: () => QueryPromise,
1763
+ Placeholder: () => Placeholder,
1764
+ Param: () => Param,
1765
+ OriginalName: () => OriginalName,
1766
+ One: () => One,
1767
+ NoopLogger: () => NoopLogger,
1768
+ Name: () => Name,
1769
+ Many: () => Many,
1770
+ IsAlias: () => IsAlias,
1771
+ FakePrimitiveParam: () => FakePrimitiveParam,
1772
+ ExtraConfigColumns: () => ExtraConfigColumns,
1773
+ ExtraConfigBuilder: () => ExtraConfigBuilder,
1774
+ DrizzleQueryError: () => DrizzleQueryError,
1775
+ DrizzleError: () => DrizzleError,
1776
+ DefaultLogger: () => DefaultLogger,
1777
+ ConsoleLogWriter: () => ConsoleLogWriter,
1778
+ Columns: () => Columns,
1779
+ ColumnBuilder: () => ColumnBuilder,
1780
+ ColumnAliasProxyHandler: () => ColumnAliasProxyHandler,
1781
+ Column: () => Column,
1782
+ BaseName: () => BaseName
1783
+ });
1784
+ var init_drizzle_orm = __esm(() => {
1785
+ init_alias();
1786
+ init_column_builder();
1787
+ init_column();
1788
+ init_entity();
1789
+ init_errors();
1790
+ init_logger();
1791
+ init_query_promise();
1792
+ init_relations();
1793
+ init_sql2();
1794
+ init_subquery();
1795
+ init_table();
1796
+ init_utils();
1797
+ init_view_common();
1798
+ });
1799
+
1800
+ // TrajectoryLoggerService.ts
1801
+ import { logger as logger2, Service } from "@elizaos/core";
1802
+ import { v4 as uuidv4 } from "uuid";
1803
+ function asNumber(value) {
1804
+ if (typeof value === "number" && Number.isFinite(value))
1805
+ return value;
1806
+ if (typeof value === "string") {
1807
+ const parsed = Number(value);
1808
+ return Number.isFinite(parsed) ? parsed : null;
1809
+ }
1810
+ return null;
1811
+ }
1812
+ function asString(value) {
1813
+ if (typeof value === "string")
1814
+ return value;
1815
+ if (typeof value === "number" || typeof value === "boolean")
1816
+ return String(value);
1817
+ if (value instanceof Date)
1818
+ return value.toISOString();
1819
+ return null;
1820
+ }
1821
+ function asIsoString(value) {
1822
+ if (value instanceof Date)
1823
+ return value.toISOString();
1824
+ const asText = asString(value);
1825
+ if (!asText)
1826
+ return new Date(0).toISOString();
1827
+ const parsed = new Date(asText);
1828
+ if (Number.isNaN(parsed.getTime()))
1829
+ return new Date(0).toISOString();
1830
+ return parsed.toISOString();
1831
+ }
1832
+ function pickCell(row, ...keys) {
1833
+ for (const key of keys) {
1834
+ if (Object.hasOwn(row, key)) {
1835
+ return row[key];
1836
+ }
1837
+ }
1838
+ return;
1839
+ }
1840
+ function sqlLiteral(v) {
1841
+ if (v === null || v === undefined)
1842
+ return "NULL";
1843
+ if (typeof v === "number")
1844
+ return String(v);
1845
+ if (typeof v === "boolean")
1846
+ return v ? "TRUE" : "FALSE";
1847
+ if (typeof v === "object")
1848
+ return `'${JSON.stringify(v).replace(/'/g, "''")}'::jsonb`;
1849
+ return `'${String(v).replace(/'/g, "''")}'`;
1850
+ }
1851
+
1852
+ class TrajectoryLoggerService extends Service {
1853
+ static serviceType = "trajectory_logger";
1854
+ capabilityDescription = "Captures and persists LLM calls, provider accesses, and full trajectories for debugging, analysis, and RL training";
1855
+ enabled = true;
1856
+ initialized = false;
1857
+ activeTrajectories = new Map;
1858
+ activeStepIds = new Map;
1859
+ stepToTrajectory = new Map;
1860
+ static async start(runtime) {
1861
+ const service = new TrajectoryLoggerService(runtime);
1862
+ await service.initialize();
1863
+ return service;
1864
+ }
1865
+ async stop() {
1866
+ this.enabled = false;
1867
+ }
1868
+ setEnabled(enabled) {
1869
+ this.enabled = enabled;
1870
+ }
1871
+ isEnabled() {
1872
+ return this.enabled;
1873
+ }
1874
+ async getSqlHelper() {
1875
+ const drizzle = await Promise.resolve().then(() => (init_drizzle_orm(), exports_drizzle_orm));
1876
+ return drizzle.sql;
1877
+ }
1878
+ async executeRawSql(sqlText) {
1879
+ const runtime = this.runtime;
1880
+ if (!runtime?.adapter) {
1881
+ throw new Error("Database adapter not available");
1882
+ }
1883
+ const sqlHelper = await this.getSqlHelper();
1884
+ const db = runtime.adapter.db;
1885
+ const query = sqlHelper.raw(sqlText);
1886
+ const result = await db.execute(query);
1887
+ const rows = Array.isArray(result.rows) ? result.rows : [];
1888
+ const columns = result.fields && Array.isArray(result.fields) ? result.fields.map((field) => field.name) : rows.length > 0 ? Object.keys(rows[0]) : [];
1889
+ return { rows, columns };
1890
+ }
1891
+ async initialize() {
1892
+ if (this.initialized)
1893
+ return;
1894
+ const runtime = this.runtime;
1895
+ if (!runtime?.adapter) {
1896
+ logger2.warn("[trajectory-logger] No runtime adapter available, skipping initialization");
1897
+ return;
1898
+ }
1899
+ await this.ensureTablesExist();
1900
+ this.initialized = true;
1901
+ logger2.info("[trajectory-logger] Trajectory logger service initialized");
1902
+ }
1903
+ async ensureTablesExist() {
1904
+ await this.executeRawSql(`
1905
+ CREATE TABLE IF NOT EXISTS trajectories (
1906
+ id TEXT PRIMARY KEY,
1907
+ agent_id TEXT NOT NULL,
1908
+ source TEXT NOT NULL DEFAULT 'chat',
1909
+ status TEXT NOT NULL DEFAULT 'active',
1910
+ start_time BIGINT NOT NULL,
1911
+ end_time BIGINT,
1912
+ duration_ms BIGINT,
1913
+ step_count INTEGER NOT NULL DEFAULT 0,
1914
+ llm_call_count INTEGER NOT NULL DEFAULT 0,
1915
+ provider_access_count INTEGER NOT NULL DEFAULT 0,
1916
+ total_prompt_tokens INTEGER NOT NULL DEFAULT 0,
1917
+ total_completion_tokens INTEGER NOT NULL DEFAULT 0,
1918
+ total_reward REAL NOT NULL DEFAULT 0,
1919
+ scenario_id TEXT,
1920
+ episode_id TEXT,
1921
+ batch_id TEXT,
1922
+ group_index INTEGER,
1923
+ steps_json JSONB NOT NULL DEFAULT '[]',
1924
+ reward_components_json JSONB NOT NULL DEFAULT '{}',
1925
+ metrics_json JSONB NOT NULL DEFAULT '{}',
1926
+ metadata_json JSONB NOT NULL DEFAULT '{}',
1927
+ is_training_data BOOLEAN NOT NULL DEFAULT FALSE,
1928
+ is_evaluation BOOLEAN NOT NULL DEFAULT FALSE,
1929
+ used_in_training BOOLEAN NOT NULL DEFAULT FALSE,
1930
+ ai_judge_reward REAL,
1931
+ ai_judge_reasoning TEXT,
1932
+ judged_at TIMESTAMPTZ,
1933
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
1934
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
1935
+ )
1936
+ `);
1937
+ await this.executeRawSql(`CREATE INDEX IF NOT EXISTS idx_trajectories_agent_id ON trajectories(agent_id)`);
1938
+ await this.executeRawSql(`CREATE INDEX IF NOT EXISTS idx_trajectories_source ON trajectories(source)`);
1939
+ await this.executeRawSql(`CREATE INDEX IF NOT EXISTS idx_trajectories_status ON trajectories(status)`);
1940
+ await this.executeRawSql(`CREATE INDEX IF NOT EXISTS idx_trajectories_created_at ON trajectories(created_at)`);
1941
+ await this.executeRawSql(`CREATE INDEX IF NOT EXISTS idx_trajectories_scenario_id ON trajectories(scenario_id)`);
1942
+ await this.executeRawSql(`CREATE INDEX IF NOT EXISTS idx_trajectories_batch_id ON trajectories(batch_id)`);
1943
+ await this.executeRawSql(`CREATE INDEX IF NOT EXISTS idx_trajectories_is_training ON trajectories(is_training_data)`);
1944
+ }
1945
+ logLlmCall(params) {
1946
+ if (!this.enabled)
1947
+ return;
1948
+ const trajectoryId = this.stepToTrajectory.get(params.stepId);
1949
+ if (!trajectoryId) {
1950
+ logger2.debug({ stepId: params.stepId }, "[trajectory-logger] No active trajectory for LLM call");
1951
+ return;
1952
+ }
1953
+ const trajectory = this.activeTrajectories.get(trajectoryId);
1954
+ if (!trajectory)
1955
+ return;
1956
+ const currentStepId = this.activeStepIds.get(trajectoryId);
1957
+ const step = trajectory.steps.find((s) => s.stepId === currentStepId);
1958
+ if (step) {
1959
+ const llmCall = {
1960
+ callId: uuidv4(),
1961
+ timestamp: Date.now(),
1962
+ model: params.model,
1963
+ systemPrompt: params.systemPrompt,
1964
+ userPrompt: params.userPrompt,
1965
+ response: params.response,
1966
+ temperature: params.temperature,
1967
+ maxTokens: params.maxTokens,
1968
+ purpose: params.purpose,
1969
+ actionType: params.actionType,
1970
+ promptTokens: params.promptTokens,
1971
+ completionTokens: params.completionTokens,
1972
+ latencyMs: params.latencyMs
1973
+ };
1974
+ step.llmCalls.push(llmCall);
1975
+ }
1976
+ this.updateTrajectoryCountsInMemory(trajectoryId, {
1977
+ llmCallCount: 1,
1978
+ promptTokens: params.promptTokens ?? 0,
1979
+ completionTokens: params.completionTokens ?? 0
1980
+ });
1981
+ }
1982
+ logProviderAccess(params) {
1983
+ if (!this.enabled)
1984
+ return;
1985
+ const trajectoryId = this.stepToTrajectory.get(params.stepId);
1986
+ if (!trajectoryId) {
1987
+ logger2.debug({ stepId: params.stepId }, "[trajectory-logger] No active trajectory for provider access");
1988
+ return;
1989
+ }
1990
+ const trajectory = this.activeTrajectories.get(trajectoryId);
1991
+ if (!trajectory)
1992
+ return;
1993
+ const currentStepId = this.activeStepIds.get(trajectoryId);
1994
+ const step = trajectory.steps.find((s) => s.stepId === currentStepId);
1995
+ if (step) {
1996
+ const access = {
1997
+ providerId: uuidv4(),
1998
+ providerName: params.providerName,
1999
+ timestamp: Date.now(),
2000
+ data: params.data,
2001
+ query: params.query,
2002
+ purpose: params.purpose
2003
+ };
2004
+ step.providerAccesses.push(access);
2005
+ }
2006
+ }
2007
+ updateTrajectoryCountsInMemory(trajectoryId, counts) {}
2008
+ async startTrajectory(stepId, options) {
2009
+ if (!this.enabled)
2010
+ return stepId;
2011
+ const trajectoryId = uuidv4();
2012
+ const now = Date.now();
2013
+ const trajectory = {
2014
+ trajectoryId,
2015
+ agentId: options.agentId,
2016
+ startTime: now,
2017
+ endTime: now,
2018
+ durationMs: 0,
2019
+ scenarioId: options.scenarioId,
2020
+ episodeId: options.episodeId,
2021
+ batchId: options.batchId,
2022
+ groupIndex: options.groupIndex,
2023
+ steps: [],
2024
+ totalReward: 0,
2025
+ rewardComponents: { environmentReward: 0 },
2026
+ metrics: {
2027
+ episodeLength: 0,
2028
+ finalStatus: "completed"
2029
+ },
2030
+ metadata: {
2031
+ source: options.source ?? "chat",
2032
+ roomId: options.roomId,
2033
+ entityId: options.entityId,
2034
+ ...options.metadata ?? {}
2035
+ }
2036
+ };
2037
+ this.activeTrajectories.set(trajectoryId, trajectory);
2038
+ this.stepToTrajectory.set(stepId, trajectoryId);
2039
+ this.startStep(trajectoryId, {
2040
+ timestamp: now,
2041
+ agentBalance: 0,
2042
+ agentPoints: 0,
2043
+ agentPnL: 0,
2044
+ openPositions: 0
2045
+ });
2046
+ try {
2047
+ await this.executeRawSql(`
2048
+ INSERT INTO trajectories (
2049
+ id, agent_id, source, status, start_time, scenario_id, episode_id,
2050
+ batch_id, group_index, metadata_json
2051
+ ) VALUES (
2052
+ ${sqlLiteral(trajectoryId)},
2053
+ ${sqlLiteral(options.agentId)},
2054
+ ${sqlLiteral(options.source ?? "chat")},
2055
+ 'active',
2056
+ ${now},
2057
+ ${sqlLiteral(options.scenarioId ?? null)},
2058
+ ${sqlLiteral(options.episodeId ?? null)},
2059
+ ${sqlLiteral(options.batchId ?? null)},
2060
+ ${options.groupIndex ?? "NULL"},
2061
+ ${sqlLiteral(trajectory.metadata)}
2062
+ )
2063
+ `);
2064
+ } catch (err) {
2065
+ logger2.warn({ err, trajectoryId }, "[trajectory-logger] Failed to persist trajectory start");
2066
+ }
2067
+ return trajectoryId;
2068
+ }
2069
+ startStep(trajectoryId, envState) {
2070
+ const stepId = uuidv4();
2071
+ const trajectory = this.activeTrajectories.get(trajectoryId);
2072
+ if (!trajectory) {
2073
+ logger2.warn({ trajectoryId }, "[trajectory-logger] Trajectory not found for startStep");
2074
+ return stepId;
2075
+ }
2076
+ const step = {
2077
+ stepId,
2078
+ stepNumber: trajectory.steps.length,
2079
+ timestamp: envState.timestamp || Date.now(),
2080
+ environmentState: envState,
2081
+ observation: {},
2082
+ llmCalls: [],
2083
+ providerAccesses: [],
2084
+ action: {
2085
+ attemptId: "",
2086
+ timestamp: 0,
2087
+ actionType: "pending",
2088
+ actionName: "pending",
2089
+ parameters: {},
2090
+ success: false
2091
+ },
2092
+ reward: 0,
2093
+ done: false
2094
+ };
2095
+ trajectory.steps.push(step);
2096
+ this.activeStepIds.set(trajectoryId, stepId);
2097
+ return stepId;
2098
+ }
2099
+ completeStep(trajectoryId, action, rewardInfo) {
2100
+ const trajectory = this.activeTrajectories.get(trajectoryId);
2101
+ if (!trajectory)
2102
+ return;
2103
+ const stepId = this.activeStepIds.get(trajectoryId);
2104
+ const step = trajectory.steps.find((s) => s.stepId === stepId);
2105
+ if (!step)
2106
+ return;
2107
+ step.action = {
2108
+ attemptId: uuidv4(),
2109
+ timestamp: Date.now(),
2110
+ ...action
2111
+ };
2112
+ if (rewardInfo?.reward !== undefined) {
2113
+ step.reward = rewardInfo.reward;
2114
+ trajectory.totalReward += rewardInfo.reward;
2115
+ }
2116
+ if (rewardInfo?.components) {
2117
+ trajectory.rewardComponents = {
2118
+ ...trajectory.rewardComponents,
2119
+ ...rewardInfo.components
2120
+ };
2121
+ }
2122
+ this.activeStepIds.delete(trajectoryId);
2123
+ }
2124
+ async endTrajectory(stepIdOrTrajectoryId, status = "completed") {
2125
+ if (!this.enabled)
2126
+ return;
2127
+ let trajectoryId = this.stepToTrajectory.get(stepIdOrTrajectoryId);
2128
+ if (!trajectoryId) {
2129
+ trajectoryId = stepIdOrTrajectoryId;
2130
+ }
2131
+ const trajectory = this.activeTrajectories.get(trajectoryId);
2132
+ if (!trajectory) {
2133
+ logger2.debug({ stepIdOrTrajectoryId }, "[trajectory-logger] No active trajectory to end");
2134
+ return;
2135
+ }
2136
+ const now = Date.now();
2137
+ trajectory.endTime = now;
2138
+ trajectory.durationMs = now - trajectory.startTime;
2139
+ trajectory.metrics.finalStatus = status;
2140
+ trajectory.metrics.episodeLength = trajectory.steps.length;
2141
+ let totalLlmCalls = 0;
2142
+ let totalProviderAccesses = 0;
2143
+ let totalPromptTokens = 0;
2144
+ let totalCompletionTokens = 0;
2145
+ for (const step of trajectory.steps) {
2146
+ totalLlmCalls += step.llmCalls.length;
2147
+ totalProviderAccesses += step.providerAccesses.length;
2148
+ for (const call of step.llmCalls) {
2149
+ totalPromptTokens += call.promptTokens ?? 0;
2150
+ totalCompletionTokens += call.completionTokens ?? 0;
2151
+ }
2152
+ }
2153
+ try {
2154
+ await this.executeRawSql(`
2155
+ UPDATE trajectories SET
2156
+ status = ${sqlLiteral(status)},
2157
+ end_time = ${now},
2158
+ duration_ms = ${trajectory.durationMs},
2159
+ step_count = ${trajectory.steps.length},
2160
+ llm_call_count = ${totalLlmCalls},
2161
+ provider_access_count = ${totalProviderAccesses},
2162
+ total_prompt_tokens = ${totalPromptTokens},
2163
+ total_completion_tokens = ${totalCompletionTokens},
2164
+ total_reward = ${trajectory.totalReward},
2165
+ steps_json = ${sqlLiteral(trajectory.steps)},
2166
+ reward_components_json = ${sqlLiteral(trajectory.rewardComponents)},
2167
+ metrics_json = ${sqlLiteral(trajectory.metrics)},
2168
+ metadata_json = ${sqlLiteral(trajectory.metadata)},
2169
+ updated_at = NOW()
2170
+ WHERE id = ${sqlLiteral(trajectoryId)}
2171
+ `);
2172
+ } catch (err) {
2173
+ logger2.warn({ err, trajectoryId }, "[trajectory-logger] Failed to persist trajectory end");
2174
+ }
2175
+ this.activeTrajectories.delete(trajectoryId);
2176
+ this.activeStepIds.delete(trajectoryId);
2177
+ for (const [stepId, trajId] of this.stepToTrajectory.entries()) {
2178
+ if (trajId === trajectoryId) {
2179
+ this.stepToTrajectory.delete(stepId);
2180
+ }
2181
+ }
2182
+ }
2183
+ async listTrajectories(options = {}) {
2184
+ const runtime = this.runtime;
2185
+ if (!runtime?.adapter) {
2186
+ return { trajectories: [], total: 0, offset: 0, limit: 50 };
2187
+ }
2188
+ const offset = Math.max(0, options.offset ?? 0);
2189
+ const limit = Math.min(500, Math.max(1, options.limit ?? 50));
2190
+ const whereClauses = [];
2191
+ if (options.status) {
2192
+ whereClauses.push(`status = ${sqlLiteral(options.status)}`);
2193
+ }
2194
+ if (options.source) {
2195
+ whereClauses.push(`source = ${sqlLiteral(options.source)}`);
2196
+ }
2197
+ if (options.scenarioId) {
2198
+ whereClauses.push(`scenario_id = ${sqlLiteral(options.scenarioId)}`);
2199
+ }
2200
+ if (options.batchId) {
2201
+ whereClauses.push(`batch_id = ${sqlLiteral(options.batchId)}`);
2202
+ }
2203
+ if (options.isTrainingData !== undefined) {
2204
+ whereClauses.push(`is_training_data = ${options.isTrainingData}`);
2205
+ }
2206
+ if (options.startDate) {
2207
+ whereClauses.push(`created_at >= ${sqlLiteral(options.startDate)}::timestamptz`);
2208
+ }
2209
+ if (options.endDate) {
2210
+ whereClauses.push(`created_at <= ${sqlLiteral(options.endDate)}::timestamptz`);
2211
+ }
2212
+ if (options.search) {
2213
+ const escaped = options.search.replace(/'/g, "''").replace(/%/g, "\\%");
2214
+ whereClauses.push(`(
2215
+ id ILIKE '%${escaped}%' OR
2216
+ agent_id ILIKE '%${escaped}%' OR
2217
+ source ILIKE '%${escaped}%' OR
2218
+ scenario_id ILIKE '%${escaped}%'
2219
+ )`);
2220
+ }
2221
+ const whereClause = whereClauses.length > 0 ? `WHERE ${whereClauses.join(" AND ")}` : "";
2222
+ const countResult = await this.executeRawSql(`SELECT count(*)::int AS total FROM trajectories ${whereClause}`);
2223
+ const total = asNumber(pickCell(countResult.rows[0] ?? {}, "total")) ?? 0;
2224
+ const rowsResult = await this.executeRawSql(`
2225
+ SELECT
2226
+ id, agent_id, source, status, start_time, end_time, duration_ms,
2227
+ step_count, llm_call_count, total_prompt_tokens, total_completion_tokens,
2228
+ total_reward, scenario_id, batch_id, created_at
2229
+ FROM trajectories
2230
+ ${whereClause}
2231
+ ORDER BY created_at DESC
2232
+ LIMIT ${limit} OFFSET ${offset}
2233
+ `);
2234
+ const trajectories = rowsResult.rows.map((row) => ({
2235
+ id: asString(pickCell(row, "id")) ?? "",
2236
+ agentId: asString(pickCell(row, "agent_id")) ?? "",
2237
+ source: asString(pickCell(row, "source")) ?? "chat",
2238
+ status: asString(pickCell(row, "status")) ?? "completed",
2239
+ startTime: asNumber(pickCell(row, "start_time")) ?? 0,
2240
+ endTime: asNumber(pickCell(row, "end_time")),
2241
+ durationMs: asNumber(pickCell(row, "duration_ms")),
2242
+ stepCount: asNumber(pickCell(row, "step_count")) ?? 0,
2243
+ llmCallCount: asNumber(pickCell(row, "llm_call_count")) ?? 0,
2244
+ totalPromptTokens: asNumber(pickCell(row, "total_prompt_tokens")) ?? 0,
2245
+ totalCompletionTokens: asNumber(pickCell(row, "total_completion_tokens")) ?? 0,
2246
+ totalReward: asNumber(pickCell(row, "total_reward")) ?? 0,
2247
+ scenarioId: asString(pickCell(row, "scenario_id")),
2248
+ batchId: asString(pickCell(row, "batch_id")),
2249
+ createdAt: asIsoString(pickCell(row, "created_at"))
2250
+ }));
2251
+ return { trajectories, total, offset, limit };
2252
+ }
2253
+ async getTrajectoryDetail(trajectoryId) {
2254
+ const runtime = this.runtime;
2255
+ if (!runtime?.adapter)
2256
+ return null;
2257
+ const safeId = trajectoryId.replace(/'/g, "''");
2258
+ const result = await this.executeRawSql(`SELECT * FROM trajectories WHERE id = '${safeId}' LIMIT 1`);
2259
+ if (result.rows.length === 0)
2260
+ return null;
2261
+ const row = result.rows[0];
2262
+ return this.rowToTrajectory(row);
2263
+ }
2264
+ async getStats() {
2265
+ const runtime = this.runtime;
2266
+ if (!runtime?.adapter) {
2267
+ return {
2268
+ totalTrajectories: 0,
2269
+ totalSteps: 0,
2270
+ totalLlmCalls: 0,
2271
+ totalPromptTokens: 0,
2272
+ totalCompletionTokens: 0,
2273
+ averageDurationMs: 0,
2274
+ averageReward: 0,
2275
+ bySource: {},
2276
+ byStatus: {},
2277
+ byScenario: {}
2278
+ };
2279
+ }
2280
+ const statsResult = await this.executeRawSql(`
2281
+ SELECT
2282
+ count(*)::int AS total_trajectories,
2283
+ COALESCE(sum(step_count), 0)::int AS total_steps,
2284
+ COALESCE(sum(llm_call_count), 0)::int AS total_llm_calls,
2285
+ COALESCE(sum(total_prompt_tokens), 0)::int AS total_prompt_tokens,
2286
+ COALESCE(sum(total_completion_tokens), 0)::int AS total_completion_tokens,
2287
+ COALESCE(avg(duration_ms), 0)::int AS avg_duration_ms,
2288
+ COALESCE(avg(total_reward), 0)::real AS avg_reward
2289
+ FROM trajectories
2290
+ `);
2291
+ const sourceResult = await this.executeRawSql(`
2292
+ SELECT source, count(*)::int AS cnt
2293
+ FROM trajectories
2294
+ GROUP BY source
2295
+ `);
2296
+ const statusResult = await this.executeRawSql(`
2297
+ SELECT status, count(*)::int AS cnt
2298
+ FROM trajectories
2299
+ GROUP BY status
2300
+ `);
2301
+ const scenarioResult = await this.executeRawSql(`
2302
+ SELECT scenario_id, count(*)::int AS cnt
2303
+ FROM trajectories
2304
+ WHERE scenario_id IS NOT NULL
2305
+ GROUP BY scenario_id
2306
+ `);
2307
+ const stats = statsResult.rows[0] ?? {};
2308
+ const bySource = {};
2309
+ const byStatus = {};
2310
+ const byScenario = {};
2311
+ for (const row of sourceResult.rows) {
2312
+ const source = asString(pickCell(row, "source"));
2313
+ const cnt = asNumber(pickCell(row, "cnt"));
2314
+ if (source && cnt !== null)
2315
+ bySource[source] = cnt;
2316
+ }
2317
+ for (const row of statusResult.rows) {
2318
+ const status = asString(pickCell(row, "status"));
2319
+ const cnt = asNumber(pickCell(row, "cnt"));
2320
+ if (status && cnt !== null)
2321
+ byStatus[status] = cnt;
2322
+ }
2323
+ for (const row of scenarioResult.rows) {
2324
+ const scenario = asString(pickCell(row, "scenario_id"));
2325
+ const cnt = asNumber(pickCell(row, "cnt"));
2326
+ if (scenario && cnt !== null)
2327
+ byScenario[scenario] = cnt;
2328
+ }
2329
+ return {
2330
+ totalTrajectories: asNumber(pickCell(stats, "total_trajectories")) ?? 0,
2331
+ totalSteps: asNumber(pickCell(stats, "total_steps")) ?? 0,
2332
+ totalLlmCalls: asNumber(pickCell(stats, "total_llm_calls")) ?? 0,
2333
+ totalPromptTokens: asNumber(pickCell(stats, "total_prompt_tokens")) ?? 0,
2334
+ totalCompletionTokens: asNumber(pickCell(stats, "total_completion_tokens")) ?? 0,
2335
+ averageDurationMs: asNumber(pickCell(stats, "avg_duration_ms")) ?? 0,
2336
+ averageReward: asNumber(pickCell(stats, "avg_reward")) ?? 0,
2337
+ bySource,
2338
+ byStatus,
2339
+ byScenario
2340
+ };
2341
+ }
2342
+ async deleteTrajectories(trajectoryIds) {
2343
+ const runtime = this.runtime;
2344
+ if (!runtime?.adapter)
2345
+ return 0;
2346
+ if (trajectoryIds.length === 0)
2347
+ return 0;
2348
+ const ids = trajectoryIds.map(sqlLiteral).join(", ");
2349
+ const result = await this.executeRawSql(`DELETE FROM trajectories WHERE id IN (${ids}) RETURNING id`);
2350
+ return result.rows.length;
2351
+ }
2352
+ async clearAllTrajectories() {
2353
+ const runtime = this.runtime;
2354
+ if (!runtime?.adapter)
2355
+ return 0;
2356
+ const countResult = await this.executeRawSql(`SELECT count(*)::int AS cnt FROM trajectories`);
2357
+ const count2 = asNumber(pickCell(countResult.rows[0] ?? {}, "cnt")) ?? 0;
2358
+ await this.executeRawSql(`DELETE FROM trajectories`);
2359
+ return count2;
2360
+ }
2361
+ async exportTrajectories(options) {
2362
+ const runtime = this.runtime;
2363
+ if (!runtime?.adapter) {
2364
+ throw new Error("Database not available");
2365
+ }
2366
+ const whereClauses = [];
2367
+ if (options.trajectoryIds && options.trajectoryIds.length > 0) {
2368
+ const ids = options.trajectoryIds.map(sqlLiteral).join(", ");
2369
+ whereClauses.push(`id IN (${ids})`);
2370
+ }
2371
+ if (options.startDate) {
2372
+ whereClauses.push(`created_at >= ${sqlLiteral(options.startDate)}::timestamptz`);
2373
+ }
2374
+ if (options.endDate) {
2375
+ whereClauses.push(`created_at <= ${sqlLiteral(options.endDate)}::timestamptz`);
2376
+ }
2377
+ if (options.scenarioId) {
2378
+ whereClauses.push(`scenario_id = ${sqlLiteral(options.scenarioId)}`);
2379
+ }
2380
+ if (options.batchId) {
2381
+ whereClauses.push(`batch_id = ${sqlLiteral(options.batchId)}`);
2382
+ }
2383
+ const whereClause = whereClauses.length > 0 ? `WHERE ${whereClauses.join(" AND ")}` : "";
2384
+ const result = await this.executeRawSql(`SELECT * FROM trajectories ${whereClause} ORDER BY created_at DESC`);
2385
+ const trajectories = result.rows.map((row) => this.rowToTrajectory(row));
2386
+ const timestamp = new Date().toISOString().replace(/[:.]/g, "-");
2387
+ if (options.format === "csv") {
2388
+ const lines = [
2389
+ "id,agent_id,source,status,start_time,end_time,duration_ms,step_count,llm_call_count,total_reward,scenario_id"
2390
+ ];
2391
+ for (const t of trajectories) {
2392
+ lines.push([
2393
+ t.trajectoryId,
2394
+ t.agentId,
2395
+ t.metadata.source ?? "chat",
2396
+ t.metrics.finalStatus,
2397
+ t.startTime,
2398
+ t.endTime,
2399
+ t.durationMs,
2400
+ t.steps.length,
2401
+ t.steps.reduce((sum2, s) => sum2 + s.llmCalls.length, 0),
2402
+ t.totalReward,
2403
+ t.scenarioId ?? ""
2404
+ ].join(","));
2405
+ }
2406
+ return {
2407
+ data: lines.join(`
2408
+ `),
2409
+ filename: `trajectories-${timestamp}.csv`,
2410
+ mimeType: "text/csv"
2411
+ };
2412
+ }
2413
+ let exportData = trajectories;
2414
+ if (!options.includePrompts) {
2415
+ exportData = trajectories.map((t) => ({
2416
+ ...t,
2417
+ steps: t.steps.map((s) => ({
2418
+ ...s,
2419
+ llmCalls: s.llmCalls.map((c) => ({
2420
+ ...c,
2421
+ systemPrompt: "[redacted]",
2422
+ userPrompt: "[redacted]",
2423
+ response: "[redacted]"
2424
+ }))
2425
+ }))
2426
+ }));
2427
+ }
2428
+ return {
2429
+ data: JSON.stringify(exportData, null, 2),
2430
+ filename: `trajectories-${timestamp}.json`,
2431
+ mimeType: "application/json"
2432
+ };
2433
+ }
2434
+ rowToTrajectory(row) {
2435
+ const parseJson = (cell, fallback) => {
2436
+ if (typeof cell === "string") {
2437
+ try {
2438
+ return JSON.parse(cell);
2439
+ } catch {
2440
+ return fallback;
2441
+ }
2442
+ }
2443
+ if (typeof cell === "object" && cell !== null && !Array.isArray(cell)) {
2444
+ return cell;
2445
+ }
2446
+ return fallback;
2447
+ };
2448
+ return {
2449
+ trajectoryId: asString(pickCell(row, "id")) ?? "",
2450
+ agentId: asString(pickCell(row, "agent_id")) ?? "",
2451
+ startTime: asNumber(pickCell(row, "start_time")) ?? 0,
2452
+ endTime: asNumber(pickCell(row, "end_time")) ?? 0,
2453
+ durationMs: asNumber(pickCell(row, "duration_ms")) ?? 0,
2454
+ scenarioId: asString(pickCell(row, "scenario_id")) ?? undefined,
2455
+ episodeId: asString(pickCell(row, "episode_id")) ?? undefined,
2456
+ batchId: asString(pickCell(row, "batch_id")) ?? undefined,
2457
+ groupIndex: asNumber(pickCell(row, "group_index")) ?? undefined,
2458
+ steps: parseJson(pickCell(row, "steps_json"), []),
2459
+ totalReward: asNumber(pickCell(row, "total_reward")) ?? 0,
2460
+ rewardComponents: parseJson(pickCell(row, "reward_components_json"), { environmentReward: 0 }),
2461
+ metrics: parseJson(pickCell(row, "metrics_json"), {
2462
+ episodeLength: 0,
2463
+ finalStatus: "completed"
2464
+ }),
2465
+ metadata: parseJson(pickCell(row, "metadata_json"), {})
2466
+ };
2467
+ }
2468
+ getActiveTrajectory(trajectoryId) {
2469
+ return this.activeTrajectories.get(trajectoryId) || null;
2470
+ }
2471
+ getCurrentStepId(trajectoryId) {
2472
+ return this.activeStepIds.get(trajectoryId) || null;
2473
+ }
2474
+ getProviderAccessLogs() {
2475
+ return [];
2476
+ }
2477
+ getLlmCallLogs() {
2478
+ return [];
2479
+ }
2480
+ }
1
2481
  // action-interceptor.ts
2
- import { logger } from "@elizaos/core";
2482
+ import { logger as logger3 } from "@elizaos/core";
3
2483
  var trajectoryContexts = new WeakMap;
4
2484
  function setTrajectoryContext(runtime, trajectoryId, trajectoryLogger) {
5
2485
  trajectoryContexts.set(runtime, { trajectoryId, logger: trajectoryLogger });
@@ -23,7 +2503,7 @@ function wrapActionWithLogging(action, _trajectoryLogger) {
23
2503
  const { trajectoryId, logger: loggerService } = context;
24
2504
  const stepId = loggerService.getCurrentStepId(trajectoryId);
25
2505
  if (!stepId) {
26
- logger.warn({ action: action.name, trajectoryId }, "No active step for action execution");
2506
+ logger3.warn({ action: action.name, trajectoryId }, "No active step for action execution");
27
2507
  const result = await originalHandler(runtime, message, state, options, callback);
28
2508
  return result ?? undefined;
29
2509
  }
@@ -43,7 +2523,7 @@ function wrapActionWithLogging(action, _trajectoryLogger) {
43
2523
  };
44
2524
  const errorHandler = (err) => {
45
2525
  const error = err instanceof Error ? err.message : typeof err === "string" ? err : err.message || String(err);
46
- logger.error({ action: action.name, trajectoryId, error }, "Action execution failed");
2526
+ logger3.error({ action: action.name, trajectoryId, error }, "Action execution failed");
47
2527
  const stateSnapshot = state ? JSON.parse(JSON.stringify(state)) : null;
48
2528
  loggerService.completeStep(trajectoryId, stepId, {
49
2529
  actionType: action.name,
@@ -86,7 +2566,7 @@ function wrapPluginActions(plugin, trajectoryLogger) {
86
2566
  function logLLMCallFromAction(actionContext, trajectoryLogger, trajectoryId) {
87
2567
  const stepId = trajectoryLogger.getCurrentStepId(trajectoryId);
88
2568
  if (!stepId) {
89
- logger.warn({ trajectoryId }, "No active step for LLM call from action");
2569
+ logger3.warn({ trajectoryId }, "No active step for LLM call from action");
90
2570
  return;
91
2571
  }
92
2572
  trajectoryLogger.logLLMCall(stepId, {
@@ -107,7 +2587,7 @@ function logLLMCallFromAction(actionContext, trajectoryLogger, trajectoryId) {
107
2587
  function logProviderFromAction(actionContext, trajectoryLogger, trajectoryId) {
108
2588
  const stepId = trajectoryLogger.getCurrentStepId(trajectoryId);
109
2589
  if (!stepId) {
110
- logger.warn({ trajectoryId }, "No active step for provider access from action");
2590
+ logger3.warn({ trajectoryId }, "No active step for provider access from action");
111
2591
  return;
112
2592
  }
113
2593
  trajectoryLogger.logProviderAccess(stepId, {
@@ -129,7 +2609,7 @@ function wrapProviderWithLogging(provider, _trajectoryLogger) {
129
2609
  const { trajectoryId, logger: loggerService } = context;
130
2610
  const stepId = loggerService.getCurrentStepId(trajectoryId);
131
2611
  if (!stepId) {
132
- logger.warn({ provider: provider.name, trajectoryId }, "No active step for provider access");
2612
+ logger3.warn({ provider: provider.name, trajectoryId }, "No active step for provider access");
133
2613
  return originalGet?.(runtime, message, state) || { text: "" };
134
2614
  }
135
2615
  const result = await originalGet?.(runtime, message, state) || { text: "" };
@@ -331,14 +2811,14 @@ function toARTJSONL(trajectory) {
331
2811
  return JSON.stringify(toARTTrajectory(trajectory));
332
2812
  }
333
2813
  function validateARTCompatibility(trajectory) {
334
- const errors = [];
2814
+ const errors2 = [];
335
2815
  const warnings = [];
336
2816
  if (trajectory.steps.length === 0) {
337
- errors.push("Trajectory has no steps");
2817
+ errors2.push("Trajectory has no steps");
338
2818
  }
339
2819
  for (const [idx, step] of trajectory.steps.entries()) {
340
2820
  if (step.llmCalls.length === 0) {
341
- errors.push(`Step ${idx} has no LLM calls - can't extract messages`);
2821
+ errors2.push(`Step ${idx} has no LLM calls - can't extract messages`);
342
2822
  }
343
2823
  for (const llmCall of step.llmCalls) {
344
2824
  if (!llmCall.userPrompt || llmCall.userPrompt.length < 10) {
@@ -350,15 +2830,15 @@ function validateARTCompatibility(trajectory) {
350
2830
  }
351
2831
  }
352
2832
  if (trajectory.totalReward === undefined || Number.isNaN(trajectory.totalReward)) {
353
- errors.push("Trajectory has no valid reward");
2833
+ errors2.push("Trajectory has no valid reward");
354
2834
  }
355
2835
  const artTraj = toARTTrajectory(trajectory);
356
2836
  if (artTraj.messages.length < 2) {
357
2837
  warnings.push("Trajectory converts to very few messages (< 2)");
358
2838
  }
359
2839
  return {
360
- valid: errors.length === 0,
361
- errors,
2840
+ valid: errors2.length === 0,
2841
+ errors: errors2,
362
2842
  warnings
363
2843
  };
364
2844
  }
@@ -454,7 +2934,7 @@ async function buildGameStateFromDB(_trajectoryId) {
454
2934
  }
455
2935
  async function recomputeTrajectoryRewards(_trajectoryIds) {}
456
2936
  // integration.ts
457
- import { logger as logger2 } from "@elizaos/core";
2937
+ import { logger as logger4 } from "@elizaos/core";
458
2938
  function startAutonomousTick(trajectoryLogger, context) {
459
2939
  const trajectoryId = trajectoryLogger.startTrajectory(context.agentId, {
460
2940
  scenarioId: context.scenarioId,
@@ -470,17 +2950,17 @@ function startAutonomousTick(trajectoryLogger, context) {
470
2950
  openPositions: 0
471
2951
  };
472
2952
  trajectoryLogger.startStep(trajectoryId, envState);
473
- logger2.info({ trajectoryId, agentId: context.agentId }, "Started autonomous tick trajectory");
2953
+ logger4.info({ trajectoryId, agentId: context.agentId }, "Started autonomous tick trajectory");
474
2954
  return trajectoryId;
475
2955
  }
476
2956
  async function endAutonomousTick(trajectoryLogger, trajectoryId, status = "completed", finalMetrics) {
477
2957
  await trajectoryLogger.endTrajectory(trajectoryId, status, finalMetrics);
478
- logger2.info({ trajectoryId, status }, "Ended autonomous tick trajectory");
2958
+ logger4.info({ trajectoryId, status }, "Ended autonomous tick trajectory");
479
2959
  }
480
2960
  async function loggedLLMCall(trajectoryLogger, trajectoryId, options, llmCallFn) {
481
2961
  const stepId = trajectoryLogger.getCurrentStepId(trajectoryId);
482
2962
  if (!stepId) {
483
- logger2.warn({ trajectoryId }, "No active step for LLM call");
2963
+ logger4.warn({ trajectoryId }, "No active step for LLM call");
484
2964
  const result2 = await llmCallFn();
485
2965
  return result2.text;
486
2966
  }
@@ -585,13 +3065,13 @@ class RewardService {
585
3065
  return (score + 1) / 2;
586
3066
  }
587
3067
  normalizeScoresForGroup(scores) {
588
- const min = Math.min(...scores);
589
- const max = Math.max(...scores);
590
- const range = max - min;
3068
+ const min2 = Math.min(...scores);
3069
+ const max2 = Math.max(...scores);
3070
+ const range = max2 - min2;
591
3071
  if (range === 0) {
592
3072
  return scores.map(() => 0.5);
593
3073
  }
594
- return scores.map((s) => (s - min) / range);
3074
+ return scores.map((s) => (s - min2) / range);
595
3075
  }
596
3076
  }
597
3077
  function createRewardService(options = {}) {
@@ -605,197 +3085,13 @@ async function scoreTrajectoryGroup(trajectories) {
605
3085
  const service = new RewardService;
606
3086
  return service.scoreTrajectoryGroup(trajectories);
607
3087
  }
608
- // TrajectoryLoggerService.ts
609
- import { asUUID, logger as logger3 } from "@elizaos/core";
610
- import { v4 as uuidv4 } from "uuid";
611
-
612
- class TrajectoryLoggerService {
613
- activeTrajectories = new Map;
614
- activeStepIds = new Map;
615
- startTrajectory(agentId, options = {}) {
616
- const trajectoryId = uuidv4();
617
- const now = Date.now();
618
- const trajectory = {
619
- trajectoryId: asUUID(trajectoryId),
620
- agentId: asUUID(agentId),
621
- startTime: now,
622
- endTime: now,
623
- durationMs: 0,
624
- episodeId: options.episodeId,
625
- scenarioId: options.scenarioId,
626
- batchId: options.batchId,
627
- groupIndex: options.groupIndex,
628
- steps: [],
629
- totalReward: 0,
630
- rewardComponents: {
631
- environmentReward: 0
632
- },
633
- metrics: {
634
- episodeLength: 0,
635
- finalStatus: "completed"
636
- },
637
- metadata: options.metadata || {}
638
- };
639
- this.activeTrajectories.set(trajectoryId, trajectory);
640
- return trajectoryId;
641
- }
642
- startStep(trajectoryId, envState) {
643
- const stepId = uuidv4();
644
- const trajectory = this.activeTrajectories.get(trajectoryId);
645
- if (!trajectory) {
646
- throw new Error(`Trajectory ${trajectoryId} not found`);
647
- }
648
- const step = {
649
- stepId: asUUID(stepId),
650
- stepNumber: trajectory.steps.length,
651
- timestamp: envState.timestamp || Date.now(),
652
- environmentState: envState,
653
- observation: {},
654
- llmCalls: [],
655
- providerAccesses: [],
656
- action: {
657
- attemptId: "",
658
- timestamp: 0,
659
- actionType: "pending",
660
- actionName: "pending",
661
- parameters: {},
662
- success: false
663
- },
664
- reward: 0,
665
- done: false
666
- };
667
- trajectory.steps.push(step);
668
- this.activeStepIds.set(trajectoryId, stepId);
669
- return stepId;
670
- }
671
- logLLMCall(stepId, llmCall) {
672
- const trajectory = this.findTrajectoryByStepId(stepId);
673
- if (!trajectory) {
674
- logger3.warn({ stepId }, "Trajectory not found for LLM call");
675
- return;
676
- }
677
- const step = trajectory.steps.find((s) => s.stepId === stepId);
678
- if (!step) {
679
- logger3.warn({ stepId }, "Step not found for LLM call");
680
- return;
681
- }
682
- const fullLLMCall = {
683
- callId: uuidv4(),
684
- timestamp: Date.now(),
685
- ...llmCall
686
- };
687
- step.llmCalls.push(fullLLMCall);
688
- }
689
- logProviderAccess(stepId, access) {
690
- const trajectory = this.findTrajectoryByStepId(stepId);
691
- if (!trajectory) {
692
- logger3.warn({ stepId }, "Trajectory not found for provider access");
693
- return;
694
- }
695
- const step = trajectory.steps.find((s) => s.stepId === stepId);
696
- if (!step) {
697
- logger3.warn({ stepId }, "Step not found for provider access");
698
- return;
699
- }
700
- const fullAccess = {
701
- providerId: uuidv4(),
702
- timestamp: Date.now(),
703
- ...access
704
- };
705
- step.providerAccesses.push(fullAccess);
706
- }
707
- logLLMCallByTrajectoryId(trajectoryId, llmCall) {
708
- const stepId = this.activeStepIds.get(trajectoryId);
709
- if (!stepId) {
710
- logger3.warn({ trajectoryId }, "No active step for trajectory");
711
- return;
712
- }
713
- this.logLLMCall(stepId, llmCall);
714
- }
715
- logProviderAccessByTrajectoryId(trajectoryId, access) {
716
- const stepId = this.activeStepIds.get(trajectoryId);
717
- if (!stepId) {
718
- logger3.warn({ trajectoryId }, "No active step for trajectory");
719
- return;
720
- }
721
- this.logProviderAccess(stepId, access);
722
- }
723
- getCurrentStepId(trajectoryId) {
724
- return this.activeStepIds.get(trajectoryId) || null;
725
- }
726
- completeStep(trajectoryId, stepId, action, rewardInfo) {
727
- const trajectory = this.activeTrajectories.get(trajectoryId);
728
- if (!trajectory) {
729
- logger3.warn({ trajectoryId }, "Trajectory not found for completeStep");
730
- return;
731
- }
732
- const step = trajectory.steps.find((s) => s.stepId === stepId);
733
- if (!step) {
734
- logger3.warn({ trajectoryId, stepId }, "Step not found for completeStep");
735
- return;
736
- }
737
- step.action = {
738
- attemptId: uuidv4(),
739
- timestamp: Date.now(),
740
- ...action
741
- };
742
- if (rewardInfo?.reward !== undefined) {
743
- step.reward = rewardInfo.reward;
744
- trajectory.totalReward += rewardInfo.reward;
745
- }
746
- if (rewardInfo?.components) {
747
- trajectory.rewardComponents = {
748
- ...trajectory.rewardComponents,
749
- ...rewardInfo.components
750
- };
751
- }
752
- this.activeStepIds.delete(trajectoryId);
753
- }
754
- completeCurrentStep(trajectoryId, action, rewardInfo) {
755
- const stepId = this.activeStepIds.get(trajectoryId);
756
- if (!stepId) {
757
- logger3.warn({ trajectoryId }, "No active step for trajectory");
758
- return;
759
- }
760
- this.completeStep(trajectoryId, stepId, action, rewardInfo);
761
- }
762
- async endTrajectory(trajectoryId, status, finalMetrics) {
763
- const trajectory = this.activeTrajectories.get(trajectoryId);
764
- if (!trajectory) {
765
- logger3.warn({ trajectoryId }, "Trajectory not found for endTrajectory");
766
- return;
767
- }
768
- trajectory.endTime = Date.now();
769
- trajectory.durationMs = trajectory.endTime - trajectory.startTime;
770
- trajectory.metrics.finalStatus = status;
771
- trajectory.metrics.episodeLength = trajectory.steps.length;
772
- if (finalMetrics) {
773
- trajectory.metrics = {
774
- ...trajectory.metrics,
775
- ...finalMetrics
776
- };
777
- }
778
- this.activeStepIds.delete(trajectoryId);
779
- }
780
- getActiveTrajectory(trajectoryId) {
781
- return this.activeTrajectories.get(trajectoryId) || null;
782
- }
783
- findTrajectoryByStepId(stepId) {
784
- for (const trajectory of this.activeTrajectories.values()) {
785
- if (trajectory.steps.some((s) => s.stepId === stepId)) {
786
- return trajectory;
787
- }
788
- }
789
- return null;
790
- }
791
- }
792
3088
 
793
3089
  // index.ts
794
3090
  var trajectoryLoggerPlugin = {
795
3091
  name: "@elizaos/plugin-trajectory-logger",
796
- description: "Collects complete agent interaction trajectory data for RL training. Records LLM calls, provider access, actions, environment state, and computes rewards.",
797
- dependencies: [],
798
- services: []
3092
+ description: "Captures and persists complete agent interaction trajectories for debugging, analysis, and RL training. " + "Records LLM calls, provider accesses, actions, environment state, and computes rewards.",
3093
+ dependencies: ["@elizaos/plugin-sql"],
3094
+ services: [TrajectoryLoggerService]
799
3095
  };
800
3096
  var typescript_default = trajectoryLoggerPlugin;
801
3097
  export {
@@ -838,4 +3134,4 @@ export {
838
3134
  RewardService
839
3135
  };
840
3136
 
841
- //# debugId=8E8ACF830258000B64756E2164756E21
3137
+ //# debugId=61D715423871574264756E2164756E21