@elizaos/plugin-trajectory-logger 2.0.0-alpha.13 → 2.0.0-alpha.20

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,193 +1,3068 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __returnValue = (v) => v;
3
+ function __exportSetter(name, newValue) {
4
+ this[name] = __returnValue.bind(null, newValue);
5
+ }
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, {
9
+ get: all[name],
10
+ enumerable: true,
11
+ configurable: true,
12
+ set: __exportSetter.bind(all, name)
13
+ });
14
+ };
15
+ var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
16
+
17
+ // ../../../../node_modules/drizzle-orm/entity.js
18
+ function is(value, type) {
19
+ if (!value || typeof value !== "object") {
20
+ return false;
21
+ }
22
+ if (value instanceof type) {
23
+ return true;
24
+ }
25
+ if (!Object.prototype.hasOwnProperty.call(type, entityKind)) {
26
+ 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.`);
27
+ }
28
+ let cls = Object.getPrototypeOf(value).constructor;
29
+ if (cls) {
30
+ while (cls) {
31
+ if (entityKind in cls && cls[entityKind] === type[entityKind]) {
32
+ return true;
33
+ }
34
+ cls = Object.getPrototypeOf(cls);
35
+ }
36
+ }
37
+ return false;
38
+ }
39
+ var entityKind, hasOwnEntityKind;
40
+ var init_entity = __esm(() => {
41
+ entityKind = Symbol.for("drizzle:entityKind");
42
+ hasOwnEntityKind = Symbol.for("drizzle:hasOwnEntityKind");
43
+ });
44
+
45
+ // ../../../../node_modules/drizzle-orm/column.js
46
+ var Column;
47
+ var init_column = __esm(() => {
48
+ init_entity();
49
+ Column = class Column {
50
+ constructor(table, config) {
51
+ this.table = table;
52
+ this.config = config;
53
+ this.name = config.name;
54
+ this.keyAsName = config.keyAsName;
55
+ this.notNull = config.notNull;
56
+ this.default = config.default;
57
+ this.defaultFn = config.defaultFn;
58
+ this.onUpdateFn = config.onUpdateFn;
59
+ this.hasDefault = config.hasDefault;
60
+ this.primary = config.primaryKey;
61
+ this.isUnique = config.isUnique;
62
+ this.uniqueName = config.uniqueName;
63
+ this.uniqueType = config.uniqueType;
64
+ this.dataType = config.dataType;
65
+ this.columnType = config.columnType;
66
+ this.generated = config.generated;
67
+ this.generatedIdentity = config.generatedIdentity;
68
+ }
69
+ static [entityKind] = "Column";
70
+ name;
71
+ keyAsName;
72
+ primary;
73
+ notNull;
74
+ default;
75
+ defaultFn;
76
+ onUpdateFn;
77
+ hasDefault;
78
+ isUnique;
79
+ uniqueName;
80
+ uniqueType;
81
+ dataType;
82
+ columnType;
83
+ enumValues = undefined;
84
+ generated = undefined;
85
+ generatedIdentity = undefined;
86
+ config;
87
+ mapFromDriverValue(value) {
88
+ return value;
89
+ }
90
+ mapToDriverValue(value) {
91
+ return value;
92
+ }
93
+ shouldDisableInsert() {
94
+ return this.config.generated !== undefined && this.config.generated.type !== "byDefault";
95
+ }
96
+ };
97
+ });
98
+
99
+ // ../../../../node_modules/drizzle-orm/column-builder.js
100
+ var ColumnBuilder;
101
+ var init_column_builder = __esm(() => {
102
+ init_entity();
103
+ ColumnBuilder = class ColumnBuilder {
104
+ static [entityKind] = "ColumnBuilder";
105
+ config;
106
+ constructor(name, dataType, columnType) {
107
+ this.config = {
108
+ name,
109
+ keyAsName: name === "",
110
+ notNull: false,
111
+ default: undefined,
112
+ hasDefault: false,
113
+ primaryKey: false,
114
+ isUnique: false,
115
+ uniqueName: undefined,
116
+ uniqueType: undefined,
117
+ dataType,
118
+ columnType,
119
+ generated: undefined
120
+ };
121
+ }
122
+ $type() {
123
+ return this;
124
+ }
125
+ notNull() {
126
+ this.config.notNull = true;
127
+ return this;
128
+ }
129
+ default(value) {
130
+ this.config.default = value;
131
+ this.config.hasDefault = true;
132
+ return this;
133
+ }
134
+ $defaultFn(fn) {
135
+ this.config.defaultFn = fn;
136
+ this.config.hasDefault = true;
137
+ return this;
138
+ }
139
+ $default = this.$defaultFn;
140
+ $onUpdateFn(fn) {
141
+ this.config.onUpdateFn = fn;
142
+ this.config.hasDefault = true;
143
+ return this;
144
+ }
145
+ $onUpdate = this.$onUpdateFn;
146
+ primaryKey() {
147
+ this.config.primaryKey = true;
148
+ this.config.notNull = true;
149
+ return this;
150
+ }
151
+ setName(name) {
152
+ if (this.config.name !== "")
153
+ return;
154
+ this.config.name = name;
155
+ }
156
+ };
157
+ });
158
+
159
+ // ../../../../node_modules/drizzle-orm/table.utils.js
160
+ var TableName;
161
+ var init_table_utils = __esm(() => {
162
+ TableName = Symbol.for("drizzle:Name");
163
+ });
164
+
165
+ // ../../../../node_modules/drizzle-orm/tracing-utils.js
166
+ function iife(fn, ...args) {
167
+ return fn(...args);
168
+ }
169
+ var init_tracing_utils = () => {};
170
+
171
+ // ../../../../node_modules/drizzle-orm/pg-core/unique-constraint.js
172
+ function uniqueKeyName(table, columns) {
173
+ return `${table[TableName]}_${columns.join("_")}_unique`;
174
+ }
175
+ var init_unique_constraint = __esm(() => {
176
+ init_table_utils();
177
+ });
178
+
179
+ // ../../../../node_modules/drizzle-orm/pg-core/columns/common.js
180
+ var PgColumn, ExtraConfigColumn;
181
+ var init_common = __esm(() => {
182
+ init_column();
183
+ init_entity();
184
+ init_unique_constraint();
185
+ PgColumn = class PgColumn extends Column {
186
+ constructor(table, config) {
187
+ if (!config.uniqueName) {
188
+ config.uniqueName = uniqueKeyName(table, [config.name]);
189
+ }
190
+ super(table, config);
191
+ this.table = table;
192
+ }
193
+ static [entityKind] = "PgColumn";
194
+ };
195
+ ExtraConfigColumn = class ExtraConfigColumn extends PgColumn {
196
+ static [entityKind] = "ExtraConfigColumn";
197
+ getSQLType() {
198
+ return this.getSQLType();
199
+ }
200
+ indexConfig = {
201
+ order: this.config.order ?? "asc",
202
+ nulls: this.config.nulls ?? "last",
203
+ opClass: this.config.opClass
204
+ };
205
+ defaultConfig = {
206
+ order: "asc",
207
+ nulls: "last",
208
+ opClass: undefined
209
+ };
210
+ asc() {
211
+ this.indexConfig.order = "asc";
212
+ return this;
213
+ }
214
+ desc() {
215
+ this.indexConfig.order = "desc";
216
+ return this;
217
+ }
218
+ nullsFirst() {
219
+ this.indexConfig.nulls = "first";
220
+ return this;
221
+ }
222
+ nullsLast() {
223
+ this.indexConfig.nulls = "last";
224
+ return this;
225
+ }
226
+ op(opClass) {
227
+ this.indexConfig.opClass = opClass;
228
+ return this;
229
+ }
230
+ };
231
+ });
232
+
233
+ // ../../../../node_modules/drizzle-orm/pg-core/columns/enum.js
234
+ function isPgEnum(obj) {
235
+ return !!obj && typeof obj === "function" && isPgEnumSym in obj && obj[isPgEnumSym] === true;
236
+ }
237
+ var PgEnumObjectColumn, isPgEnumSym, PgEnumColumn;
238
+ var init_enum = __esm(() => {
239
+ init_entity();
240
+ init_common();
241
+ PgEnumObjectColumn = class PgEnumObjectColumn extends PgColumn {
242
+ static [entityKind] = "PgEnumObjectColumn";
243
+ enum;
244
+ enumValues = this.config.enum.enumValues;
245
+ constructor(table, config) {
246
+ super(table, config);
247
+ this.enum = config.enum;
248
+ }
249
+ getSQLType() {
250
+ return this.enum.enumName;
251
+ }
252
+ };
253
+ isPgEnumSym = Symbol.for("drizzle:isPgEnum");
254
+ PgEnumColumn = class PgEnumColumn extends PgColumn {
255
+ static [entityKind] = "PgEnumColumn";
256
+ enum = this.config.enum;
257
+ enumValues = this.config.enum.enumValues;
258
+ constructor(table, config) {
259
+ super(table, config);
260
+ this.enum = config.enum;
261
+ }
262
+ getSQLType() {
263
+ return this.enum.enumName;
264
+ }
265
+ };
266
+ });
267
+
268
+ // ../../../../node_modules/drizzle-orm/subquery.js
269
+ var Subquery, WithSubquery;
270
+ var init_subquery = __esm(() => {
271
+ init_entity();
272
+ Subquery = class Subquery {
273
+ static [entityKind] = "Subquery";
274
+ constructor(sql, fields, alias, isWith = false, usedTables = []) {
275
+ this._ = {
276
+ brand: "Subquery",
277
+ sql,
278
+ selectedFields: fields,
279
+ alias,
280
+ isWith,
281
+ usedTables
282
+ };
283
+ }
284
+ };
285
+ WithSubquery = class WithSubquery extends Subquery {
286
+ static [entityKind] = "WithSubquery";
287
+ };
288
+ });
289
+
290
+ // ../../../../node_modules/drizzle-orm/version.js
291
+ var version = "0.45.1";
292
+ var init_version = () => {};
293
+
294
+ // ../../../../node_modules/drizzle-orm/tracing.js
295
+ var otel, rawTracer, tracer;
296
+ var init_tracing = __esm(() => {
297
+ init_tracing_utils();
298
+ init_version();
299
+ tracer = {
300
+ startActiveSpan(name, fn) {
301
+ if (!otel) {
302
+ return fn();
303
+ }
304
+ if (!rawTracer) {
305
+ rawTracer = otel.trace.getTracer("drizzle-orm", version);
306
+ }
307
+ return iife((otel2, rawTracer2) => rawTracer2.startActiveSpan(name, (span) => {
308
+ try {
309
+ return fn(span);
310
+ } catch (e) {
311
+ span.setStatus({
312
+ code: otel2.SpanStatusCode.ERROR,
313
+ message: e instanceof Error ? e.message : "Unknown error"
314
+ });
315
+ throw e;
316
+ } finally {
317
+ span.end();
318
+ }
319
+ }), otel, rawTracer);
320
+ }
321
+ };
322
+ });
323
+
324
+ // ../../../../node_modules/drizzle-orm/view-common.js
325
+ var ViewBaseConfig;
326
+ var init_view_common = __esm(() => {
327
+ ViewBaseConfig = Symbol.for("drizzle:ViewBaseConfig");
328
+ });
329
+
330
+ // ../../../../node_modules/drizzle-orm/table.js
331
+ function isTable(table) {
332
+ return typeof table === "object" && table !== null && IsDrizzleTable in table;
333
+ }
334
+ function getTableName(table) {
335
+ return table[TableName];
336
+ }
337
+ function getTableUniqueName(table) {
338
+ return `${table[Schema] ?? "public"}.${table[TableName]}`;
339
+ }
340
+ var Schema, Columns, ExtraConfigColumns, OriginalName, BaseName, IsAlias, ExtraConfigBuilder, IsDrizzleTable, Table;
341
+ var init_table = __esm(() => {
342
+ init_entity();
343
+ init_table_utils();
344
+ Schema = Symbol.for("drizzle:Schema");
345
+ Columns = Symbol.for("drizzle:Columns");
346
+ ExtraConfigColumns = Symbol.for("drizzle:ExtraConfigColumns");
347
+ OriginalName = Symbol.for("drizzle:OriginalName");
348
+ BaseName = Symbol.for("drizzle:BaseName");
349
+ IsAlias = Symbol.for("drizzle:IsAlias");
350
+ ExtraConfigBuilder = Symbol.for("drizzle:ExtraConfigBuilder");
351
+ IsDrizzleTable = Symbol.for("drizzle:IsDrizzleTable");
352
+ Table = class Table {
353
+ static [entityKind] = "Table";
354
+ static Symbol = {
355
+ Name: TableName,
356
+ Schema,
357
+ OriginalName,
358
+ Columns,
359
+ ExtraConfigColumns,
360
+ BaseName,
361
+ IsAlias,
362
+ ExtraConfigBuilder
363
+ };
364
+ [TableName];
365
+ [OriginalName];
366
+ [Schema];
367
+ [Columns];
368
+ [ExtraConfigColumns];
369
+ [BaseName];
370
+ [IsAlias] = false;
371
+ [IsDrizzleTable] = true;
372
+ [ExtraConfigBuilder] = undefined;
373
+ constructor(name, schema, baseName) {
374
+ this[TableName] = this[OriginalName] = name;
375
+ this[Schema] = schema;
376
+ this[BaseName] = baseName;
377
+ }
378
+ };
379
+ });
380
+
381
+ // ../../../../node_modules/drizzle-orm/sql/sql.js
382
+ function isSQLWrapper(value) {
383
+ return value !== null && value !== undefined && typeof value.getSQL === "function";
384
+ }
385
+ function mergeQueries(queries) {
386
+ const result = { sql: "", params: [] };
387
+ for (const query of queries) {
388
+ result.sql += query.sql;
389
+ result.params.push(...query.params);
390
+ if (query.typings?.length) {
391
+ if (!result.typings) {
392
+ result.typings = [];
393
+ }
394
+ result.typings.push(...query.typings);
395
+ }
396
+ }
397
+ return result;
398
+ }
399
+ function name(value) {
400
+ return new Name(value);
401
+ }
402
+ function isDriverValueEncoder(value) {
403
+ return typeof value === "object" && value !== null && "mapToDriverValue" in value && typeof value.mapToDriverValue === "function";
404
+ }
405
+ function param(value, encoder) {
406
+ return new Param(value, encoder);
407
+ }
408
+ function sql(strings, ...params) {
409
+ const queryChunks = [];
410
+ if (params.length > 0 || strings.length > 0 && strings[0] !== "") {
411
+ queryChunks.push(new StringChunk(strings[0]));
412
+ }
413
+ for (const [paramIndex, param2] of params.entries()) {
414
+ queryChunks.push(param2, new StringChunk(strings[paramIndex + 1]));
415
+ }
416
+ return new SQL(queryChunks);
417
+ }
418
+ function placeholder(name2) {
419
+ return new Placeholder(name2);
420
+ }
421
+ function fillPlaceholders(params, values) {
422
+ return params.map((p) => {
423
+ if (is(p, Placeholder)) {
424
+ if (!(p.name in values)) {
425
+ throw new Error(`No value for placeholder "${p.name}" was provided`);
426
+ }
427
+ return values[p.name];
428
+ }
429
+ if (is(p, Param) && is(p.value, Placeholder)) {
430
+ if (!(p.value.name in values)) {
431
+ throw new Error(`No value for placeholder "${p.value.name}" was provided`);
432
+ }
433
+ return p.encoder.mapToDriverValue(values[p.value.name]);
434
+ }
435
+ return p;
436
+ });
437
+ }
438
+ function isView(view) {
439
+ return typeof view === "object" && view !== null && IsDrizzleView in view;
440
+ }
441
+ function getViewName(view) {
442
+ return view[ViewBaseConfig].name;
443
+ }
444
+ var FakePrimitiveParam, StringChunk, SQL, Name, noopDecoder, noopEncoder, noopMapper, Param, Placeholder, IsDrizzleView, View;
445
+ var init_sql = __esm(() => {
446
+ init_entity();
447
+ init_enum();
448
+ init_subquery();
449
+ init_tracing();
450
+ init_view_common();
451
+ init_column();
452
+ init_table();
453
+ FakePrimitiveParam = class FakePrimitiveParam {
454
+ static [entityKind] = "FakePrimitiveParam";
455
+ };
456
+ StringChunk = class StringChunk {
457
+ static [entityKind] = "StringChunk";
458
+ value;
459
+ constructor(value) {
460
+ this.value = Array.isArray(value) ? value : [value];
461
+ }
462
+ getSQL() {
463
+ return new SQL([this]);
464
+ }
465
+ };
466
+ SQL = class SQL {
467
+ constructor(queryChunks) {
468
+ this.queryChunks = queryChunks;
469
+ for (const chunk of queryChunks) {
470
+ if (is(chunk, Table)) {
471
+ const schemaName = chunk[Table.Symbol.Schema];
472
+ this.usedTables.push(schemaName === undefined ? chunk[Table.Symbol.Name] : schemaName + "." + chunk[Table.Symbol.Name]);
473
+ }
474
+ }
475
+ }
476
+ static [entityKind] = "SQL";
477
+ decoder = noopDecoder;
478
+ shouldInlineParams = false;
479
+ usedTables = [];
480
+ append(query) {
481
+ this.queryChunks.push(...query.queryChunks);
482
+ return this;
483
+ }
484
+ toQuery(config) {
485
+ return tracer.startActiveSpan("drizzle.buildSQL", (span) => {
486
+ const query = this.buildQueryFromSourceParams(this.queryChunks, config);
487
+ span?.setAttributes({
488
+ "drizzle.query.text": query.sql,
489
+ "drizzle.query.params": JSON.stringify(query.params)
490
+ });
491
+ return query;
492
+ });
493
+ }
494
+ buildQueryFromSourceParams(chunks, _config) {
495
+ const config = Object.assign({}, _config, {
496
+ inlineParams: _config.inlineParams || this.shouldInlineParams,
497
+ paramStartIndex: _config.paramStartIndex || { value: 0 }
498
+ });
499
+ const {
500
+ casing,
501
+ escapeName,
502
+ escapeParam,
503
+ prepareTyping,
504
+ inlineParams,
505
+ paramStartIndex
506
+ } = config;
507
+ return mergeQueries(chunks.map((chunk) => {
508
+ if (is(chunk, StringChunk)) {
509
+ return { sql: chunk.value.join(""), params: [] };
510
+ }
511
+ if (is(chunk, Name)) {
512
+ return { sql: escapeName(chunk.value), params: [] };
513
+ }
514
+ if (chunk === undefined) {
515
+ return { sql: "", params: [] };
516
+ }
517
+ if (Array.isArray(chunk)) {
518
+ const result = [new StringChunk("(")];
519
+ for (const [i, p] of chunk.entries()) {
520
+ result.push(p);
521
+ if (i < chunk.length - 1) {
522
+ result.push(new StringChunk(", "));
523
+ }
524
+ }
525
+ result.push(new StringChunk(")"));
526
+ return this.buildQueryFromSourceParams(result, config);
527
+ }
528
+ if (is(chunk, SQL)) {
529
+ return this.buildQueryFromSourceParams(chunk.queryChunks, {
530
+ ...config,
531
+ inlineParams: inlineParams || chunk.shouldInlineParams
532
+ });
533
+ }
534
+ if (is(chunk, Table)) {
535
+ const schemaName = chunk[Table.Symbol.Schema];
536
+ const tableName = chunk[Table.Symbol.Name];
537
+ return {
538
+ sql: schemaName === undefined || chunk[IsAlias] ? escapeName(tableName) : escapeName(schemaName) + "." + escapeName(tableName),
539
+ params: []
540
+ };
541
+ }
542
+ if (is(chunk, Column)) {
543
+ const columnName = casing.getColumnCasing(chunk);
544
+ if (_config.invokeSource === "indexes") {
545
+ return { sql: escapeName(columnName), params: [] };
546
+ }
547
+ const schemaName = chunk.table[Table.Symbol.Schema];
548
+ return {
549
+ sql: chunk.table[IsAlias] || schemaName === undefined ? escapeName(chunk.table[Table.Symbol.Name]) + "." + escapeName(columnName) : escapeName(schemaName) + "." + escapeName(chunk.table[Table.Symbol.Name]) + "." + escapeName(columnName),
550
+ params: []
551
+ };
552
+ }
553
+ if (is(chunk, View)) {
554
+ const schemaName = chunk[ViewBaseConfig].schema;
555
+ const viewName = chunk[ViewBaseConfig].name;
556
+ return {
557
+ sql: schemaName === undefined || chunk[ViewBaseConfig].isAlias ? escapeName(viewName) : escapeName(schemaName) + "." + escapeName(viewName),
558
+ params: []
559
+ };
560
+ }
561
+ if (is(chunk, Param)) {
562
+ if (is(chunk.value, Placeholder)) {
563
+ return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] };
564
+ }
565
+ const mappedValue = chunk.value === null ? null : chunk.encoder.mapToDriverValue(chunk.value);
566
+ if (is(mappedValue, SQL)) {
567
+ return this.buildQueryFromSourceParams([mappedValue], config);
568
+ }
569
+ if (inlineParams) {
570
+ return { sql: this.mapInlineParam(mappedValue, config), params: [] };
571
+ }
572
+ let typings = ["none"];
573
+ if (prepareTyping) {
574
+ typings = [prepareTyping(chunk.encoder)];
575
+ }
576
+ return { sql: escapeParam(paramStartIndex.value++, mappedValue), params: [mappedValue], typings };
577
+ }
578
+ if (is(chunk, Placeholder)) {
579
+ return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] };
580
+ }
581
+ if (is(chunk, SQL.Aliased) && chunk.fieldAlias !== undefined) {
582
+ return { sql: escapeName(chunk.fieldAlias), params: [] };
583
+ }
584
+ if (is(chunk, Subquery)) {
585
+ if (chunk._.isWith) {
586
+ return { sql: escapeName(chunk._.alias), params: [] };
587
+ }
588
+ return this.buildQueryFromSourceParams([
589
+ new StringChunk("("),
590
+ chunk._.sql,
591
+ new StringChunk(") "),
592
+ new Name(chunk._.alias)
593
+ ], config);
594
+ }
595
+ if (isPgEnum(chunk)) {
596
+ if (chunk.schema) {
597
+ return { sql: escapeName(chunk.schema) + "." + escapeName(chunk.enumName), params: [] };
598
+ }
599
+ return { sql: escapeName(chunk.enumName), params: [] };
600
+ }
601
+ if (isSQLWrapper(chunk)) {
602
+ if (chunk.shouldOmitSQLParens?.()) {
603
+ return this.buildQueryFromSourceParams([chunk.getSQL()], config);
604
+ }
605
+ return this.buildQueryFromSourceParams([
606
+ new StringChunk("("),
607
+ chunk.getSQL(),
608
+ new StringChunk(")")
609
+ ], config);
610
+ }
611
+ if (inlineParams) {
612
+ return { sql: this.mapInlineParam(chunk, config), params: [] };
613
+ }
614
+ return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] };
615
+ }));
616
+ }
617
+ mapInlineParam(chunk, { escapeString }) {
618
+ if (chunk === null) {
619
+ return "null";
620
+ }
621
+ if (typeof chunk === "number" || typeof chunk === "boolean") {
622
+ return chunk.toString();
623
+ }
624
+ if (typeof chunk === "string") {
625
+ return escapeString(chunk);
626
+ }
627
+ if (typeof chunk === "object") {
628
+ const mappedValueAsString = chunk.toString();
629
+ if (mappedValueAsString === "[object Object]") {
630
+ return escapeString(JSON.stringify(chunk));
631
+ }
632
+ return escapeString(mappedValueAsString);
633
+ }
634
+ throw new Error("Unexpected param value: " + chunk);
635
+ }
636
+ getSQL() {
637
+ return this;
638
+ }
639
+ as(alias) {
640
+ if (alias === undefined) {
641
+ return this;
642
+ }
643
+ return new SQL.Aliased(this, alias);
644
+ }
645
+ mapWith(decoder) {
646
+ this.decoder = typeof decoder === "function" ? { mapFromDriverValue: decoder } : decoder;
647
+ return this;
648
+ }
649
+ inlineParams() {
650
+ this.shouldInlineParams = true;
651
+ return this;
652
+ }
653
+ if(condition) {
654
+ return condition ? this : undefined;
655
+ }
656
+ };
657
+ Name = class Name {
658
+ constructor(value) {
659
+ this.value = value;
660
+ }
661
+ static [entityKind] = "Name";
662
+ brand;
663
+ getSQL() {
664
+ return new SQL([this]);
665
+ }
666
+ };
667
+ noopDecoder = {
668
+ mapFromDriverValue: (value) => value
669
+ };
670
+ noopEncoder = {
671
+ mapToDriverValue: (value) => value
672
+ };
673
+ noopMapper = {
674
+ ...noopDecoder,
675
+ ...noopEncoder
676
+ };
677
+ Param = class Param {
678
+ constructor(value, encoder = noopEncoder) {
679
+ this.value = value;
680
+ this.encoder = encoder;
681
+ }
682
+ static [entityKind] = "Param";
683
+ brand;
684
+ getSQL() {
685
+ return new SQL([this]);
686
+ }
687
+ };
688
+ ((sql2) => {
689
+ function empty() {
690
+ return new SQL([]);
691
+ }
692
+ sql2.empty = empty;
693
+ function fromList(list) {
694
+ return new SQL(list);
695
+ }
696
+ sql2.fromList = fromList;
697
+ function raw(str) {
698
+ return new SQL([new StringChunk(str)]);
699
+ }
700
+ sql2.raw = raw;
701
+ function join(chunks, separator) {
702
+ const result = [];
703
+ for (const [i, chunk] of chunks.entries()) {
704
+ if (i > 0 && separator !== undefined) {
705
+ result.push(separator);
706
+ }
707
+ result.push(chunk);
708
+ }
709
+ return new SQL(result);
710
+ }
711
+ sql2.join = join;
712
+ function identifier(value) {
713
+ return new Name(value);
714
+ }
715
+ sql2.identifier = identifier;
716
+ function placeholder2(name2) {
717
+ return new Placeholder(name2);
718
+ }
719
+ sql2.placeholder = placeholder2;
720
+ function param2(value, encoder) {
721
+ return new Param(value, encoder);
722
+ }
723
+ sql2.param = param2;
724
+ })(sql || (sql = {}));
725
+ ((SQL2) => {
726
+
727
+ class Aliased {
728
+ constructor(sql2, fieldAlias) {
729
+ this.sql = sql2;
730
+ this.fieldAlias = fieldAlias;
731
+ }
732
+ static [entityKind] = "SQL.Aliased";
733
+ isSelectionField = false;
734
+ getSQL() {
735
+ return this.sql;
736
+ }
737
+ clone() {
738
+ return new Aliased(this.sql, this.fieldAlias);
739
+ }
740
+ }
741
+ SQL2.Aliased = Aliased;
742
+ })(SQL || (SQL = {}));
743
+ Placeholder = class Placeholder {
744
+ constructor(name2) {
745
+ this.name = name2;
746
+ }
747
+ static [entityKind] = "Placeholder";
748
+ getSQL() {
749
+ return new SQL([this]);
750
+ }
751
+ };
752
+ IsDrizzleView = Symbol.for("drizzle:IsDrizzleView");
753
+ View = class View {
754
+ static [entityKind] = "View";
755
+ [ViewBaseConfig];
756
+ [IsDrizzleView] = true;
757
+ constructor({ name: name2, schema, selectedFields, query }) {
758
+ this[ViewBaseConfig] = {
759
+ name: name2,
760
+ originalName: name2,
761
+ schema,
762
+ selectedFields,
763
+ query,
764
+ isExisting: !query,
765
+ isAlias: false
766
+ };
767
+ }
768
+ getSQL() {
769
+ return new SQL([this]);
770
+ }
771
+ };
772
+ Column.prototype.getSQL = function() {
773
+ return new SQL([this]);
774
+ };
775
+ Table.prototype.getSQL = function() {
776
+ return new SQL([this]);
777
+ };
778
+ Subquery.prototype.getSQL = function() {
779
+ return new SQL([this]);
780
+ };
781
+ });
782
+
783
+ // ../../../../node_modules/drizzle-orm/alias.js
784
+ function aliasedTable(table, tableAlias) {
785
+ return new Proxy(table, new TableAliasProxyHandler(tableAlias, false));
786
+ }
787
+ function aliasedRelation(relation, tableAlias) {
788
+ return new Proxy(relation, new RelationTableAliasProxyHandler(tableAlias));
789
+ }
790
+ function aliasedTableColumn(column, tableAlias) {
791
+ return new Proxy(column, new ColumnAliasProxyHandler(new Proxy(column.table, new TableAliasProxyHandler(tableAlias, false))));
792
+ }
793
+ function mapColumnsInAliasedSQLToAlias(query, alias) {
794
+ return new SQL.Aliased(mapColumnsInSQLToAlias(query.sql, alias), query.fieldAlias);
795
+ }
796
+ function mapColumnsInSQLToAlias(query, alias) {
797
+ return sql.join(query.queryChunks.map((c) => {
798
+ if (is(c, Column)) {
799
+ return aliasedTableColumn(c, alias);
800
+ }
801
+ if (is(c, SQL)) {
802
+ return mapColumnsInSQLToAlias(c, alias);
803
+ }
804
+ if (is(c, SQL.Aliased)) {
805
+ return mapColumnsInAliasedSQLToAlias(c, alias);
806
+ }
807
+ return c;
808
+ }));
809
+ }
810
+ var ColumnAliasProxyHandler, TableAliasProxyHandler, RelationTableAliasProxyHandler;
811
+ var init_alias = __esm(() => {
812
+ init_column();
813
+ init_entity();
814
+ init_sql();
815
+ init_table();
816
+ init_view_common();
817
+ ColumnAliasProxyHandler = class ColumnAliasProxyHandler {
818
+ constructor(table) {
819
+ this.table = table;
820
+ }
821
+ static [entityKind] = "ColumnAliasProxyHandler";
822
+ get(columnObj, prop) {
823
+ if (prop === "table") {
824
+ return this.table;
825
+ }
826
+ return columnObj[prop];
827
+ }
828
+ };
829
+ TableAliasProxyHandler = class TableAliasProxyHandler {
830
+ constructor(alias, replaceOriginalName) {
831
+ this.alias = alias;
832
+ this.replaceOriginalName = replaceOriginalName;
833
+ }
834
+ static [entityKind] = "TableAliasProxyHandler";
835
+ get(target, prop) {
836
+ if (prop === Table.Symbol.IsAlias) {
837
+ return true;
838
+ }
839
+ if (prop === Table.Symbol.Name) {
840
+ return this.alias;
841
+ }
842
+ if (this.replaceOriginalName && prop === Table.Symbol.OriginalName) {
843
+ return this.alias;
844
+ }
845
+ if (prop === ViewBaseConfig) {
846
+ return {
847
+ ...target[ViewBaseConfig],
848
+ name: this.alias,
849
+ isAlias: true
850
+ };
851
+ }
852
+ if (prop === Table.Symbol.Columns) {
853
+ const columns = target[Table.Symbol.Columns];
854
+ if (!columns) {
855
+ return columns;
856
+ }
857
+ const proxiedColumns = {};
858
+ Object.keys(columns).map((key) => {
859
+ proxiedColumns[key] = new Proxy(columns[key], new ColumnAliasProxyHandler(new Proxy(target, this)));
860
+ });
861
+ return proxiedColumns;
862
+ }
863
+ const value = target[prop];
864
+ if (is(value, Column)) {
865
+ return new Proxy(value, new ColumnAliasProxyHandler(new Proxy(target, this)));
866
+ }
867
+ return value;
868
+ }
869
+ };
870
+ RelationTableAliasProxyHandler = class RelationTableAliasProxyHandler {
871
+ constructor(alias) {
872
+ this.alias = alias;
873
+ }
874
+ static [entityKind] = "RelationTableAliasProxyHandler";
875
+ get(target, prop) {
876
+ if (prop === "sourceTable") {
877
+ return aliasedTable(target.sourceTable, this.alias);
878
+ }
879
+ return target[prop];
880
+ }
881
+ };
882
+ });
883
+
884
+ // ../../../../node_modules/drizzle-orm/errors.js
885
+ var DrizzleError, DrizzleQueryError, TransactionRollbackError;
886
+ var init_errors = __esm(() => {
887
+ init_entity();
888
+ DrizzleError = class DrizzleError extends Error {
889
+ static [entityKind] = "DrizzleError";
890
+ constructor({ message, cause }) {
891
+ super(message);
892
+ this.name = "DrizzleError";
893
+ this.cause = cause;
894
+ }
895
+ };
896
+ DrizzleQueryError = class DrizzleQueryError extends Error {
897
+ constructor(query, params, cause) {
898
+ super(`Failed query: ${query}
899
+ params: ${params}`);
900
+ this.query = query;
901
+ this.params = params;
902
+ this.cause = cause;
903
+ Error.captureStackTrace(this, DrizzleQueryError);
904
+ if (cause)
905
+ this.cause = cause;
906
+ }
907
+ };
908
+ TransactionRollbackError = class TransactionRollbackError extends DrizzleError {
909
+ static [entityKind] = "TransactionRollbackError";
910
+ constructor() {
911
+ super({ message: "Rollback" });
912
+ }
913
+ };
914
+ });
915
+
916
+ // ../../../../node_modules/drizzle-orm/logger.js
917
+ var ConsoleLogWriter, DefaultLogger, NoopLogger;
918
+ var init_logger = __esm(() => {
919
+ init_entity();
920
+ ConsoleLogWriter = class ConsoleLogWriter {
921
+ static [entityKind] = "ConsoleLogWriter";
922
+ write(message) {
923
+ console.log(message);
924
+ }
925
+ };
926
+ DefaultLogger = class DefaultLogger {
927
+ static [entityKind] = "DefaultLogger";
928
+ writer;
929
+ constructor(config) {
930
+ this.writer = config?.writer ?? new ConsoleLogWriter;
931
+ }
932
+ logQuery(query, params) {
933
+ const stringifiedParams = params.map((p) => {
934
+ try {
935
+ return JSON.stringify(p);
936
+ } catch {
937
+ return String(p);
938
+ }
939
+ });
940
+ const paramsStr = stringifiedParams.length ? ` -- params: [${stringifiedParams.join(", ")}]` : "";
941
+ this.writer.write(`Query: ${query}${paramsStr}`);
942
+ }
943
+ };
944
+ NoopLogger = class NoopLogger {
945
+ static [entityKind] = "NoopLogger";
946
+ logQuery() {}
947
+ };
948
+ });
949
+
950
+ // ../../../../node_modules/drizzle-orm/query-promise.js
951
+ var QueryPromise;
952
+ var init_query_promise = __esm(() => {
953
+ init_entity();
954
+ QueryPromise = class QueryPromise {
955
+ static [entityKind] = "QueryPromise";
956
+ [Symbol.toStringTag] = "QueryPromise";
957
+ catch(onRejected) {
958
+ return this.then(undefined, onRejected);
959
+ }
960
+ finally(onFinally) {
961
+ return this.then((value) => {
962
+ onFinally?.();
963
+ return value;
964
+ }, (reason) => {
965
+ onFinally?.();
966
+ throw reason;
967
+ });
968
+ }
969
+ then(onFulfilled, onRejected) {
970
+ return this.execute().then(onFulfilled, onRejected);
971
+ }
972
+ };
973
+ });
974
+
975
+ // ../../../../node_modules/drizzle-orm/utils.js
976
+ function mapResultRow(columns, row, joinsNotNullableMap) {
977
+ const nullifyMap = {};
978
+ const result = columns.reduce((result2, { path, field }, columnIndex) => {
979
+ let decoder;
980
+ if (is(field, Column)) {
981
+ decoder = field;
982
+ } else if (is(field, SQL)) {
983
+ decoder = field.decoder;
984
+ } else if (is(field, Subquery)) {
985
+ decoder = field._.sql.decoder;
986
+ } else {
987
+ decoder = field.sql.decoder;
988
+ }
989
+ let node = result2;
990
+ for (const [pathChunkIndex, pathChunk] of path.entries()) {
991
+ if (pathChunkIndex < path.length - 1) {
992
+ if (!(pathChunk in node)) {
993
+ node[pathChunk] = {};
994
+ }
995
+ node = node[pathChunk];
996
+ } else {
997
+ const rawValue = row[columnIndex];
998
+ const value = node[pathChunk] = rawValue === null ? null : decoder.mapFromDriverValue(rawValue);
999
+ if (joinsNotNullableMap && is(field, Column) && path.length === 2) {
1000
+ const objectName = path[0];
1001
+ if (!(objectName in nullifyMap)) {
1002
+ nullifyMap[objectName] = value === null ? getTableName(field.table) : false;
1003
+ } else if (typeof nullifyMap[objectName] === "string" && nullifyMap[objectName] !== getTableName(field.table)) {
1004
+ nullifyMap[objectName] = false;
1005
+ }
1006
+ }
1007
+ }
1008
+ }
1009
+ return result2;
1010
+ }, {});
1011
+ if (joinsNotNullableMap && Object.keys(nullifyMap).length > 0) {
1012
+ for (const [objectName, tableName] of Object.entries(nullifyMap)) {
1013
+ if (typeof tableName === "string" && !joinsNotNullableMap[tableName]) {
1014
+ result[objectName] = null;
1015
+ }
1016
+ }
1017
+ }
1018
+ return result;
1019
+ }
1020
+ function orderSelectedFields(fields, pathPrefix) {
1021
+ return Object.entries(fields).reduce((result, [name2, field]) => {
1022
+ if (typeof name2 !== "string") {
1023
+ return result;
1024
+ }
1025
+ const newPath = pathPrefix ? [...pathPrefix, name2] : [name2];
1026
+ if (is(field, Column) || is(field, SQL) || is(field, SQL.Aliased) || is(field, Subquery)) {
1027
+ result.push({ path: newPath, field });
1028
+ } else if (is(field, Table)) {
1029
+ result.push(...orderSelectedFields(field[Table.Symbol.Columns], newPath));
1030
+ } else {
1031
+ result.push(...orderSelectedFields(field, newPath));
1032
+ }
1033
+ return result;
1034
+ }, []);
1035
+ }
1036
+ function haveSameKeys(left, right) {
1037
+ const leftKeys = Object.keys(left);
1038
+ const rightKeys = Object.keys(right);
1039
+ if (leftKeys.length !== rightKeys.length) {
1040
+ return false;
1041
+ }
1042
+ for (const [index, key] of leftKeys.entries()) {
1043
+ if (key !== rightKeys[index]) {
1044
+ return false;
1045
+ }
1046
+ }
1047
+ return true;
1048
+ }
1049
+ function mapUpdateSet(table, values) {
1050
+ const entries = Object.entries(values).filter(([, value]) => value !== undefined).map(([key, value]) => {
1051
+ if (is(value, SQL) || is(value, Column)) {
1052
+ return [key, value];
1053
+ } else {
1054
+ return [key, new Param(value, table[Table.Symbol.Columns][key])];
1055
+ }
1056
+ });
1057
+ if (entries.length === 0) {
1058
+ throw new Error("No values to set");
1059
+ }
1060
+ return Object.fromEntries(entries);
1061
+ }
1062
+ function applyMixins(baseClass, extendedClasses) {
1063
+ for (const extendedClass of extendedClasses) {
1064
+ for (const name2 of Object.getOwnPropertyNames(extendedClass.prototype)) {
1065
+ if (name2 === "constructor")
1066
+ continue;
1067
+ Object.defineProperty(baseClass.prototype, name2, Object.getOwnPropertyDescriptor(extendedClass.prototype, name2) || /* @__PURE__ */ Object.create(null));
1068
+ }
1069
+ }
1070
+ }
1071
+ function getTableColumns(table) {
1072
+ return table[Table.Symbol.Columns];
1073
+ }
1074
+ function getViewSelectedFields(view) {
1075
+ return view[ViewBaseConfig].selectedFields;
1076
+ }
1077
+ function getTableLikeName(table) {
1078
+ 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];
1079
+ }
1080
+ function getColumnNameAndConfig(a, b) {
1081
+ return {
1082
+ name: typeof a === "string" && a.length > 0 ? a : "",
1083
+ config: typeof a === "object" ? a : b
1084
+ };
1085
+ }
1086
+ function isConfig(data) {
1087
+ if (typeof data !== "object" || data === null)
1088
+ return false;
1089
+ if (data.constructor.name !== "Object")
1090
+ return false;
1091
+ if ("logger" in data) {
1092
+ const type = typeof data["logger"];
1093
+ if (type !== "boolean" && (type !== "object" || typeof data["logger"]["logQuery"] !== "function") && type !== "undefined")
1094
+ return false;
1095
+ return true;
1096
+ }
1097
+ if ("schema" in data) {
1098
+ const type = typeof data["schema"];
1099
+ if (type !== "object" && type !== "undefined")
1100
+ return false;
1101
+ return true;
1102
+ }
1103
+ if ("casing" in data) {
1104
+ const type = typeof data["casing"];
1105
+ if (type !== "string" && type !== "undefined")
1106
+ return false;
1107
+ return true;
1108
+ }
1109
+ if ("mode" in data) {
1110
+ if (data["mode"] !== "default" || data["mode"] !== "planetscale" || data["mode"] !== undefined)
1111
+ return false;
1112
+ return true;
1113
+ }
1114
+ if ("connection" in data) {
1115
+ const type = typeof data["connection"];
1116
+ if (type !== "string" && type !== "object" && type !== "undefined")
1117
+ return false;
1118
+ return true;
1119
+ }
1120
+ if ("client" in data) {
1121
+ const type = typeof data["client"];
1122
+ if (type !== "object" && type !== "function" && type !== "undefined")
1123
+ return false;
1124
+ return true;
1125
+ }
1126
+ if (Object.keys(data).length === 0)
1127
+ return true;
1128
+ return false;
1129
+ }
1130
+ var textDecoder;
1131
+ var init_utils = __esm(() => {
1132
+ init_column();
1133
+ init_entity();
1134
+ init_sql();
1135
+ init_subquery();
1136
+ init_table();
1137
+ init_view_common();
1138
+ textDecoder = typeof TextDecoder === "undefined" ? null : new TextDecoder;
1139
+ });
1140
+
1141
+ // ../../../../node_modules/drizzle-orm/pg-core/table.js
1142
+ var InlineForeignKeys, EnableRLS, PgTable;
1143
+ var init_table2 = __esm(() => {
1144
+ init_entity();
1145
+ init_table();
1146
+ InlineForeignKeys = Symbol.for("drizzle:PgInlineForeignKeys");
1147
+ EnableRLS = Symbol.for("drizzle:EnableRLS");
1148
+ PgTable = class PgTable extends Table {
1149
+ static [entityKind] = "PgTable";
1150
+ static Symbol = Object.assign({}, Table.Symbol, {
1151
+ InlineForeignKeys,
1152
+ EnableRLS
1153
+ });
1154
+ [InlineForeignKeys] = [];
1155
+ [EnableRLS] = false;
1156
+ [Table.Symbol.ExtraConfigBuilder] = undefined;
1157
+ [Table.Symbol.ExtraConfigColumns] = {};
1158
+ };
1159
+ });
1160
+
1161
+ // ../../../../node_modules/drizzle-orm/pg-core/primary-keys.js
1162
+ var PrimaryKeyBuilder, PrimaryKey;
1163
+ var init_primary_keys = __esm(() => {
1164
+ init_entity();
1165
+ init_table2();
1166
+ PrimaryKeyBuilder = class PrimaryKeyBuilder {
1167
+ static [entityKind] = "PgPrimaryKeyBuilder";
1168
+ columns;
1169
+ name;
1170
+ constructor(columns, name2) {
1171
+ this.columns = columns;
1172
+ this.name = name2;
1173
+ }
1174
+ build(table) {
1175
+ return new PrimaryKey(table, this.columns, this.name);
1176
+ }
1177
+ };
1178
+ PrimaryKey = class PrimaryKey {
1179
+ constructor(table, columns, name2) {
1180
+ this.table = table;
1181
+ this.columns = columns;
1182
+ this.name = name2;
1183
+ }
1184
+ static [entityKind] = "PgPrimaryKey";
1185
+ columns;
1186
+ name;
1187
+ getName() {
1188
+ return this.name ?? `${this.table[PgTable.Symbol.Name]}_${this.columns.map((column) => column.name).join("_")}_pk`;
1189
+ }
1190
+ };
1191
+ });
1192
+
1193
+ // ../../../../node_modules/drizzle-orm/sql/expressions/conditions.js
1194
+ function bindIfParam(value, column) {
1195
+ if (isDriverValueEncoder(column) && !isSQLWrapper(value) && !is(value, Param) && !is(value, Placeholder) && !is(value, Column) && !is(value, Table) && !is(value, View)) {
1196
+ return new Param(value, column);
1197
+ }
1198
+ return value;
1199
+ }
1200
+ function and(...unfilteredConditions) {
1201
+ const conditions = unfilteredConditions.filter((c) => c !== undefined);
1202
+ if (conditions.length === 0) {
1203
+ return;
1204
+ }
1205
+ if (conditions.length === 1) {
1206
+ return new SQL(conditions);
1207
+ }
1208
+ return new SQL([
1209
+ new StringChunk("("),
1210
+ sql.join(conditions, new StringChunk(" and ")),
1211
+ new StringChunk(")")
1212
+ ]);
1213
+ }
1214
+ function or(...unfilteredConditions) {
1215
+ const conditions = unfilteredConditions.filter((c) => c !== undefined);
1216
+ if (conditions.length === 0) {
1217
+ return;
1218
+ }
1219
+ if (conditions.length === 1) {
1220
+ return new SQL(conditions);
1221
+ }
1222
+ return new SQL([
1223
+ new StringChunk("("),
1224
+ sql.join(conditions, new StringChunk(" or ")),
1225
+ new StringChunk(")")
1226
+ ]);
1227
+ }
1228
+ function not(condition) {
1229
+ return sql`not ${condition}`;
1230
+ }
1231
+ function inArray(column, values) {
1232
+ if (Array.isArray(values)) {
1233
+ if (values.length === 0) {
1234
+ return sql`false`;
1235
+ }
1236
+ return sql`${column} in ${values.map((v) => bindIfParam(v, column))}`;
1237
+ }
1238
+ return sql`${column} in ${bindIfParam(values, column)}`;
1239
+ }
1240
+ function notInArray(column, values) {
1241
+ if (Array.isArray(values)) {
1242
+ if (values.length === 0) {
1243
+ return sql`true`;
1244
+ }
1245
+ return sql`${column} not in ${values.map((v) => bindIfParam(v, column))}`;
1246
+ }
1247
+ return sql`${column} not in ${bindIfParam(values, column)}`;
1248
+ }
1249
+ function isNull(value) {
1250
+ return sql`${value} is null`;
1251
+ }
1252
+ function isNotNull(value) {
1253
+ return sql`${value} is not null`;
1254
+ }
1255
+ function exists(subquery) {
1256
+ return sql`exists ${subquery}`;
1257
+ }
1258
+ function notExists(subquery) {
1259
+ return sql`not exists ${subquery}`;
1260
+ }
1261
+ function between(column, min, max) {
1262
+ return sql`${column} between ${bindIfParam(min, column)} and ${bindIfParam(max, column)}`;
1263
+ }
1264
+ function notBetween(column, min, max) {
1265
+ return sql`${column} not between ${bindIfParam(min, column)} and ${bindIfParam(max, column)}`;
1266
+ }
1267
+ function like(column, value) {
1268
+ return sql`${column} like ${value}`;
1269
+ }
1270
+ function notLike(column, value) {
1271
+ return sql`${column} not like ${value}`;
1272
+ }
1273
+ function ilike(column, value) {
1274
+ return sql`${column} ilike ${value}`;
1275
+ }
1276
+ function notIlike(column, value) {
1277
+ return sql`${column} not ilike ${value}`;
1278
+ }
1279
+ function arrayContains(column, values) {
1280
+ if (Array.isArray(values)) {
1281
+ if (values.length === 0) {
1282
+ throw new Error("arrayContains requires at least one value");
1283
+ }
1284
+ const array = sql`${bindIfParam(values, column)}`;
1285
+ return sql`${column} @> ${array}`;
1286
+ }
1287
+ return sql`${column} @> ${bindIfParam(values, column)}`;
1288
+ }
1289
+ function arrayContained(column, values) {
1290
+ if (Array.isArray(values)) {
1291
+ if (values.length === 0) {
1292
+ throw new Error("arrayContained requires at least one value");
1293
+ }
1294
+ const array = sql`${bindIfParam(values, column)}`;
1295
+ return sql`${column} <@ ${array}`;
1296
+ }
1297
+ return sql`${column} <@ ${bindIfParam(values, column)}`;
1298
+ }
1299
+ function arrayOverlaps(column, values) {
1300
+ if (Array.isArray(values)) {
1301
+ if (values.length === 0) {
1302
+ throw new Error("arrayOverlaps requires at least one value");
1303
+ }
1304
+ const array = sql`${bindIfParam(values, column)}`;
1305
+ return sql`${column} && ${array}`;
1306
+ }
1307
+ return sql`${column} && ${bindIfParam(values, column)}`;
1308
+ }
1309
+ var eq = (left, right) => {
1310
+ return sql`${left} = ${bindIfParam(right, left)}`;
1311
+ }, ne = (left, right) => {
1312
+ return sql`${left} <> ${bindIfParam(right, left)}`;
1313
+ }, gt = (left, right) => {
1314
+ return sql`${left} > ${bindIfParam(right, left)}`;
1315
+ }, gte = (left, right) => {
1316
+ return sql`${left} >= ${bindIfParam(right, left)}`;
1317
+ }, lt = (left, right) => {
1318
+ return sql`${left} < ${bindIfParam(right, left)}`;
1319
+ }, lte = (left, right) => {
1320
+ return sql`${left} <= ${bindIfParam(right, left)}`;
1321
+ };
1322
+ var init_conditions = __esm(() => {
1323
+ init_column();
1324
+ init_entity();
1325
+ init_table();
1326
+ init_sql();
1327
+ });
1328
+
1329
+ // ../../../../node_modules/drizzle-orm/sql/expressions/select.js
1330
+ function asc(column) {
1331
+ return sql`${column} asc`;
1332
+ }
1333
+ function desc(column) {
1334
+ return sql`${column} desc`;
1335
+ }
1336
+ var init_select = __esm(() => {
1337
+ init_sql();
1338
+ });
1339
+
1340
+ // ../../../../node_modules/drizzle-orm/sql/expressions/index.js
1341
+ var init_expressions = __esm(() => {
1342
+ init_conditions();
1343
+ init_select();
1344
+ });
1345
+
1346
+ // ../../../../node_modules/drizzle-orm/relations.js
1347
+ function getOperators() {
1348
+ return {
1349
+ and,
1350
+ between,
1351
+ eq,
1352
+ exists,
1353
+ gt,
1354
+ gte,
1355
+ ilike,
1356
+ inArray,
1357
+ isNull,
1358
+ isNotNull,
1359
+ like,
1360
+ lt,
1361
+ lte,
1362
+ ne,
1363
+ not,
1364
+ notBetween,
1365
+ notExists,
1366
+ notLike,
1367
+ notIlike,
1368
+ notInArray,
1369
+ or,
1370
+ sql
1371
+ };
1372
+ }
1373
+ function getOrderByOperators() {
1374
+ return {
1375
+ sql,
1376
+ asc,
1377
+ desc
1378
+ };
1379
+ }
1380
+ function extractTablesRelationalConfig(schema, configHelpers) {
1381
+ if (Object.keys(schema).length === 1 && "default" in schema && !is(schema["default"], Table)) {
1382
+ schema = schema["default"];
1383
+ }
1384
+ const tableNamesMap = {};
1385
+ const relationsBuffer = {};
1386
+ const tablesConfig = {};
1387
+ for (const [key, value] of Object.entries(schema)) {
1388
+ if (is(value, Table)) {
1389
+ const dbName = getTableUniqueName(value);
1390
+ const bufferedRelations = relationsBuffer[dbName];
1391
+ tableNamesMap[dbName] = key;
1392
+ tablesConfig[key] = {
1393
+ tsName: key,
1394
+ dbName: value[Table.Symbol.Name],
1395
+ schema: value[Table.Symbol.Schema],
1396
+ columns: value[Table.Symbol.Columns],
1397
+ relations: bufferedRelations?.relations ?? {},
1398
+ primaryKey: bufferedRelations?.primaryKey ?? []
1399
+ };
1400
+ for (const column of Object.values(value[Table.Symbol.Columns])) {
1401
+ if (column.primary) {
1402
+ tablesConfig[key].primaryKey.push(column);
1403
+ }
1404
+ }
1405
+ const extraConfig = value[Table.Symbol.ExtraConfigBuilder]?.(value[Table.Symbol.ExtraConfigColumns]);
1406
+ if (extraConfig) {
1407
+ for (const configEntry of Object.values(extraConfig)) {
1408
+ if (is(configEntry, PrimaryKeyBuilder)) {
1409
+ tablesConfig[key].primaryKey.push(...configEntry.columns);
1410
+ }
1411
+ }
1412
+ }
1413
+ } else if (is(value, Relations)) {
1414
+ const dbName = getTableUniqueName(value.table);
1415
+ const tableName = tableNamesMap[dbName];
1416
+ const relations2 = value.config(configHelpers(value.table));
1417
+ let primaryKey;
1418
+ for (const [relationName, relation] of Object.entries(relations2)) {
1419
+ if (tableName) {
1420
+ const tableConfig = tablesConfig[tableName];
1421
+ tableConfig.relations[relationName] = relation;
1422
+ if (primaryKey) {
1423
+ tableConfig.primaryKey.push(...primaryKey);
1424
+ }
1425
+ } else {
1426
+ if (!(dbName in relationsBuffer)) {
1427
+ relationsBuffer[dbName] = {
1428
+ relations: {},
1429
+ primaryKey
1430
+ };
1431
+ }
1432
+ relationsBuffer[dbName].relations[relationName] = relation;
1433
+ }
1434
+ }
1435
+ }
1436
+ }
1437
+ return { tables: tablesConfig, tableNamesMap };
1438
+ }
1439
+ function relations(table, relations2) {
1440
+ return new Relations(table, (helpers) => Object.fromEntries(Object.entries(relations2(helpers)).map(([key, value]) => [
1441
+ key,
1442
+ value.withFieldName(key)
1443
+ ])));
1444
+ }
1445
+ function createOne(sourceTable) {
1446
+ return function one(table, config) {
1447
+ return new One(sourceTable, table, config, config?.fields.reduce((res, f) => res && f.notNull, true) ?? false);
1448
+ };
1449
+ }
1450
+ function createMany(sourceTable) {
1451
+ return function many(referencedTable, config) {
1452
+ return new Many(sourceTable, referencedTable, config);
1453
+ };
1454
+ }
1455
+ function normalizeRelation(schema, tableNamesMap, relation) {
1456
+ if (is(relation, One) && relation.config) {
1457
+ return {
1458
+ fields: relation.config.fields,
1459
+ references: relation.config.references
1460
+ };
1461
+ }
1462
+ const referencedTableTsName = tableNamesMap[getTableUniqueName(relation.referencedTable)];
1463
+ if (!referencedTableTsName) {
1464
+ throw new Error(`Table "${relation.referencedTable[Table.Symbol.Name]}" not found in schema`);
1465
+ }
1466
+ const referencedTableConfig = schema[referencedTableTsName];
1467
+ if (!referencedTableConfig) {
1468
+ throw new Error(`Table "${referencedTableTsName}" not found in schema`);
1469
+ }
1470
+ const sourceTable = relation.sourceTable;
1471
+ const sourceTableTsName = tableNamesMap[getTableUniqueName(sourceTable)];
1472
+ if (!sourceTableTsName) {
1473
+ throw new Error(`Table "${sourceTable[Table.Symbol.Name]}" not found in schema`);
1474
+ }
1475
+ const reverseRelations = [];
1476
+ for (const referencedTableRelation of Object.values(referencedTableConfig.relations)) {
1477
+ if (relation.relationName && relation !== referencedTableRelation && referencedTableRelation.relationName === relation.relationName || !relation.relationName && referencedTableRelation.referencedTable === relation.sourceTable) {
1478
+ reverseRelations.push(referencedTableRelation);
1479
+ }
1480
+ }
1481
+ if (reverseRelations.length > 1) {
1482
+ 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`);
1483
+ }
1484
+ if (reverseRelations[0] && is(reverseRelations[0], One) && reverseRelations[0].config) {
1485
+ return {
1486
+ fields: reverseRelations[0].config.references,
1487
+ references: reverseRelations[0].config.fields
1488
+ };
1489
+ }
1490
+ throw new Error(`There is not enough information to infer relation "${sourceTableTsName}.${relation.fieldName}"`);
1491
+ }
1492
+ function createTableRelationsHelpers(sourceTable) {
1493
+ return {
1494
+ one: createOne(sourceTable),
1495
+ many: createMany(sourceTable)
1496
+ };
1497
+ }
1498
+ function mapRelationalRow(tablesConfig, tableConfig, row, buildQueryResultSelection, mapColumnValue = (value) => value) {
1499
+ const result = {};
1500
+ for (const [
1501
+ selectionItemIndex,
1502
+ selectionItem
1503
+ ] of buildQueryResultSelection.entries()) {
1504
+ if (selectionItem.isJson) {
1505
+ const relation = tableConfig.relations[selectionItem.tsKey];
1506
+ const rawSubRows = row[selectionItemIndex];
1507
+ const subRows = typeof rawSubRows === "string" ? JSON.parse(rawSubRows) : rawSubRows;
1508
+ 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));
1509
+ } else {
1510
+ const value = mapColumnValue(row[selectionItemIndex]);
1511
+ const field = selectionItem.field;
1512
+ let decoder;
1513
+ if (is(field, Column)) {
1514
+ decoder = field;
1515
+ } else if (is(field, SQL)) {
1516
+ decoder = field.decoder;
1517
+ } else {
1518
+ decoder = field.sql.decoder;
1519
+ }
1520
+ result[selectionItem.tsKey] = value === null ? null : decoder.mapFromDriverValue(value);
1521
+ }
1522
+ }
1523
+ return result;
1524
+ }
1525
+ var Relation, Relations, One, Many;
1526
+ var init_relations = __esm(() => {
1527
+ init_table();
1528
+ init_column();
1529
+ init_entity();
1530
+ init_primary_keys();
1531
+ init_expressions();
1532
+ init_sql();
1533
+ Relation = class Relation {
1534
+ constructor(sourceTable, referencedTable, relationName) {
1535
+ this.sourceTable = sourceTable;
1536
+ this.referencedTable = referencedTable;
1537
+ this.relationName = relationName;
1538
+ this.referencedTableName = referencedTable[Table.Symbol.Name];
1539
+ }
1540
+ static [entityKind] = "Relation";
1541
+ referencedTableName;
1542
+ fieldName;
1543
+ };
1544
+ Relations = class Relations {
1545
+ constructor(table, config) {
1546
+ this.table = table;
1547
+ this.config = config;
1548
+ }
1549
+ static [entityKind] = "Relations";
1550
+ };
1551
+ One = class One extends Relation {
1552
+ constructor(sourceTable, referencedTable, config, isNullable) {
1553
+ super(sourceTable, referencedTable, config?.relationName);
1554
+ this.config = config;
1555
+ this.isNullable = isNullable;
1556
+ }
1557
+ static [entityKind] = "One";
1558
+ withFieldName(fieldName) {
1559
+ const relation = new One(this.sourceTable, this.referencedTable, this.config, this.isNullable);
1560
+ relation.fieldName = fieldName;
1561
+ return relation;
1562
+ }
1563
+ };
1564
+ Many = class Many extends Relation {
1565
+ constructor(sourceTable, referencedTable, config) {
1566
+ super(sourceTable, referencedTable, config?.relationName);
1567
+ this.config = config;
1568
+ }
1569
+ static [entityKind] = "Many";
1570
+ withFieldName(fieldName) {
1571
+ const relation = new Many(this.sourceTable, this.referencedTable, this.config);
1572
+ relation.fieldName = fieldName;
1573
+ return relation;
1574
+ }
1575
+ };
1576
+ });
1577
+
1578
+ // ../../../../node_modules/drizzle-orm/sql/functions/aggregate.js
1579
+ function count(expression) {
1580
+ return sql`count(${expression || sql.raw("*")})`.mapWith(Number);
1581
+ }
1582
+ function countDistinct(expression) {
1583
+ return sql`count(distinct ${expression})`.mapWith(Number);
1584
+ }
1585
+ function avg(expression) {
1586
+ return sql`avg(${expression})`.mapWith(String);
1587
+ }
1588
+ function avgDistinct(expression) {
1589
+ return sql`avg(distinct ${expression})`.mapWith(String);
1590
+ }
1591
+ function sum(expression) {
1592
+ return sql`sum(${expression})`.mapWith(String);
1593
+ }
1594
+ function sumDistinct(expression) {
1595
+ return sql`sum(distinct ${expression})`.mapWith(String);
1596
+ }
1597
+ function max(expression) {
1598
+ return sql`max(${expression})`.mapWith(is(expression, Column) ? expression : String);
1599
+ }
1600
+ function min(expression) {
1601
+ return sql`min(${expression})`.mapWith(is(expression, Column) ? expression : String);
1602
+ }
1603
+ var init_aggregate = __esm(() => {
1604
+ init_column();
1605
+ init_entity();
1606
+ init_sql();
1607
+ });
1608
+
1609
+ // ../../../../node_modules/drizzle-orm/sql/functions/vector.js
1610
+ function toSql(value) {
1611
+ return JSON.stringify(value);
1612
+ }
1613
+ function l2Distance(column, value) {
1614
+ if (Array.isArray(value)) {
1615
+ return sql`${column} <-> ${toSql(value)}`;
1616
+ }
1617
+ return sql`${column} <-> ${value}`;
1618
+ }
1619
+ function l1Distance(column, value) {
1620
+ if (Array.isArray(value)) {
1621
+ return sql`${column} <+> ${toSql(value)}`;
1622
+ }
1623
+ return sql`${column} <+> ${value}`;
1624
+ }
1625
+ function innerProduct(column, value) {
1626
+ if (Array.isArray(value)) {
1627
+ return sql`${column} <#> ${toSql(value)}`;
1628
+ }
1629
+ return sql`${column} <#> ${value}`;
1630
+ }
1631
+ function cosineDistance(column, value) {
1632
+ if (Array.isArray(value)) {
1633
+ return sql`${column} <=> ${toSql(value)}`;
1634
+ }
1635
+ return sql`${column} <=> ${value}`;
1636
+ }
1637
+ function hammingDistance(column, value) {
1638
+ if (Array.isArray(value)) {
1639
+ return sql`${column} <~> ${toSql(value)}`;
1640
+ }
1641
+ return sql`${column} <~> ${value}`;
1642
+ }
1643
+ function jaccardDistance(column, value) {
1644
+ if (Array.isArray(value)) {
1645
+ return sql`${column} <%> ${toSql(value)}`;
1646
+ }
1647
+ return sql`${column} <%> ${value}`;
1648
+ }
1649
+ var init_vector = __esm(() => {
1650
+ init_sql();
1651
+ });
1652
+
1653
+ // ../../../../node_modules/drizzle-orm/sql/functions/index.js
1654
+ var init_functions = __esm(() => {
1655
+ init_aggregate();
1656
+ init_vector();
1657
+ });
1658
+
1659
+ // ../../../../node_modules/drizzle-orm/sql/index.js
1660
+ var init_sql2 = __esm(() => {
1661
+ init_expressions();
1662
+ init_functions();
1663
+ init_sql();
1664
+ });
1665
+
1666
+ // ../../../../node_modules/drizzle-orm/index.js
1667
+ var exports_drizzle_orm = {};
1668
+ __export(exports_drizzle_orm, {
1669
+ textDecoder: () => textDecoder,
1670
+ sumDistinct: () => sumDistinct,
1671
+ sum: () => sum,
1672
+ sql: () => sql,
1673
+ relations: () => relations,
1674
+ placeholder: () => placeholder,
1675
+ param: () => param,
1676
+ orderSelectedFields: () => orderSelectedFields,
1677
+ or: () => or,
1678
+ notLike: () => notLike,
1679
+ notInArray: () => notInArray,
1680
+ notIlike: () => notIlike,
1681
+ notExists: () => notExists,
1682
+ notBetween: () => notBetween,
1683
+ not: () => not,
1684
+ normalizeRelation: () => normalizeRelation,
1685
+ noopMapper: () => noopMapper,
1686
+ noopEncoder: () => noopEncoder,
1687
+ noopDecoder: () => noopDecoder,
1688
+ ne: () => ne,
1689
+ name: () => name,
1690
+ min: () => min,
1691
+ max: () => max,
1692
+ mapUpdateSet: () => mapUpdateSet,
1693
+ mapResultRow: () => mapResultRow,
1694
+ mapRelationalRow: () => mapRelationalRow,
1695
+ mapColumnsInSQLToAlias: () => mapColumnsInSQLToAlias,
1696
+ mapColumnsInAliasedSQLToAlias: () => mapColumnsInAliasedSQLToAlias,
1697
+ lte: () => lte,
1698
+ lt: () => lt,
1699
+ like: () => like,
1700
+ l2Distance: () => l2Distance,
1701
+ l1Distance: () => l1Distance,
1702
+ jaccardDistance: () => jaccardDistance,
1703
+ isView: () => isView,
1704
+ isTable: () => isTable,
1705
+ isSQLWrapper: () => isSQLWrapper,
1706
+ isNull: () => isNull,
1707
+ isNotNull: () => isNotNull,
1708
+ isDriverValueEncoder: () => isDriverValueEncoder,
1709
+ isConfig: () => isConfig,
1710
+ is: () => is,
1711
+ innerProduct: () => innerProduct,
1712
+ inArray: () => inArray,
1713
+ ilike: () => ilike,
1714
+ haveSameKeys: () => haveSameKeys,
1715
+ hasOwnEntityKind: () => hasOwnEntityKind,
1716
+ hammingDistance: () => hammingDistance,
1717
+ gte: () => gte,
1718
+ gt: () => gt,
1719
+ getViewSelectedFields: () => getViewSelectedFields,
1720
+ getViewName: () => getViewName,
1721
+ getTableUniqueName: () => getTableUniqueName,
1722
+ getTableName: () => getTableName,
1723
+ getTableLikeName: () => getTableLikeName,
1724
+ getTableColumns: () => getTableColumns,
1725
+ getOrderByOperators: () => getOrderByOperators,
1726
+ getOperators: () => getOperators,
1727
+ getColumnNameAndConfig: () => getColumnNameAndConfig,
1728
+ fillPlaceholders: () => fillPlaceholders,
1729
+ extractTablesRelationalConfig: () => extractTablesRelationalConfig,
1730
+ exists: () => exists,
1731
+ eq: () => eq,
1732
+ entityKind: () => entityKind,
1733
+ desc: () => desc,
1734
+ createTableRelationsHelpers: () => createTableRelationsHelpers,
1735
+ createOne: () => createOne,
1736
+ createMany: () => createMany,
1737
+ countDistinct: () => countDistinct,
1738
+ count: () => count,
1739
+ cosineDistance: () => cosineDistance,
1740
+ bindIfParam: () => bindIfParam,
1741
+ between: () => between,
1742
+ avgDistinct: () => avgDistinct,
1743
+ avg: () => avg,
1744
+ asc: () => asc,
1745
+ arrayOverlaps: () => arrayOverlaps,
1746
+ arrayContains: () => arrayContains,
1747
+ arrayContained: () => arrayContained,
1748
+ applyMixins: () => applyMixins,
1749
+ and: () => and,
1750
+ aliasedTableColumn: () => aliasedTableColumn,
1751
+ aliasedTable: () => aliasedTable,
1752
+ aliasedRelation: () => aliasedRelation,
1753
+ WithSubquery: () => WithSubquery,
1754
+ ViewBaseConfig: () => ViewBaseConfig,
1755
+ View: () => View,
1756
+ TransactionRollbackError: () => TransactionRollbackError,
1757
+ TableAliasProxyHandler: () => TableAliasProxyHandler,
1758
+ Table: () => Table,
1759
+ Subquery: () => Subquery,
1760
+ StringChunk: () => StringChunk,
1761
+ Schema: () => Schema,
1762
+ SQL: () => SQL,
1763
+ Relations: () => Relations,
1764
+ RelationTableAliasProxyHandler: () => RelationTableAliasProxyHandler,
1765
+ Relation: () => Relation,
1766
+ QueryPromise: () => QueryPromise,
1767
+ Placeholder: () => Placeholder,
1768
+ Param: () => Param,
1769
+ OriginalName: () => OriginalName,
1770
+ One: () => One,
1771
+ NoopLogger: () => NoopLogger,
1772
+ Name: () => Name,
1773
+ Many: () => Many,
1774
+ IsAlias: () => IsAlias,
1775
+ FakePrimitiveParam: () => FakePrimitiveParam,
1776
+ ExtraConfigColumns: () => ExtraConfigColumns,
1777
+ ExtraConfigBuilder: () => ExtraConfigBuilder,
1778
+ DrizzleQueryError: () => DrizzleQueryError,
1779
+ DrizzleError: () => DrizzleError,
1780
+ DefaultLogger: () => DefaultLogger,
1781
+ ConsoleLogWriter: () => ConsoleLogWriter,
1782
+ Columns: () => Columns,
1783
+ ColumnBuilder: () => ColumnBuilder,
1784
+ ColumnAliasProxyHandler: () => ColumnAliasProxyHandler,
1785
+ Column: () => Column,
1786
+ BaseName: () => BaseName
1787
+ });
1788
+ var init_drizzle_orm = __esm(() => {
1789
+ init_alias();
1790
+ init_column_builder();
1791
+ init_column();
1792
+ init_entity();
1793
+ init_errors();
1794
+ init_logger();
1795
+ init_query_promise();
1796
+ init_relations();
1797
+ init_sql2();
1798
+ init_subquery();
1799
+ init_table();
1800
+ init_utils();
1801
+ init_view_common();
1802
+ });
1803
+
1
1804
  // index.ts
2
- import { createUniqueUuid } from "@elizaos/core";
1805
+ import {
1806
+ createUniqueUuid
1807
+ } from "@elizaos/core";
1808
+ import crypto from "node:crypto";
3
1809
 
4
1810
  // TrajectoryLoggerService.ts
5
- import { asUUID, logger } from "@elizaos/core";
1811
+ import { logger as logger2, Service } from "@elizaos/core";
6
1812
  import { v4 as uuidv4 } from "uuid";
1813
+ function asNumber(value) {
1814
+ if (typeof value === "number" && Number.isFinite(value))
1815
+ return value;
1816
+ if (typeof value === "string") {
1817
+ const parsed = Number(value);
1818
+ return Number.isFinite(parsed) ? parsed : null;
1819
+ }
1820
+ return null;
1821
+ }
1822
+ function asString(value) {
1823
+ if (typeof value === "string")
1824
+ return value;
1825
+ if (typeof value === "number" || typeof value === "boolean")
1826
+ return String(value);
1827
+ if (value instanceof Date)
1828
+ return value.toISOString();
1829
+ return null;
1830
+ }
1831
+ function asIsoString(value) {
1832
+ if (value instanceof Date)
1833
+ return value.toISOString();
1834
+ const asText = asString(value);
1835
+ if (!asText)
1836
+ return new Date(0).toISOString();
1837
+ const parsed = new Date(asText);
1838
+ if (Number.isNaN(parsed.getTime()))
1839
+ return new Date(0).toISOString();
1840
+ return parsed.toISOString();
1841
+ }
1842
+ function pickCell(row, ...keys) {
1843
+ for (const key of keys) {
1844
+ if (Object.hasOwn(row, key)) {
1845
+ return row[key];
1846
+ }
1847
+ }
1848
+ return;
1849
+ }
1850
+ function sqlLiteral(v) {
1851
+ if (v === null || v === undefined)
1852
+ return "NULL";
1853
+ if (typeof v === "number")
1854
+ return String(v);
1855
+ if (typeof v === "boolean")
1856
+ return v ? "TRUE" : "FALSE";
1857
+ if (typeof v === "object")
1858
+ return `'${JSON.stringify(v).replace(/'/g, "''")}'`;
1859
+ return `'${String(v).replace(/'/g, "''")}'`;
1860
+ }
7
1861
 
8
- class TrajectoryLoggerService {
9
- activeTrajectories = new Map;
1862
+ class TrajectoryLoggerService extends Service {
1863
+ static serviceType = "trajectory_logger";
1864
+ get serviceType() {
1865
+ return TrajectoryLoggerService.serviceType;
1866
+ }
1867
+ capabilityDescription = "Captures and persists LLM calls, provider accesses, and full trajectories for debugging, analysis, and RL training";
1868
+ enabled = true;
1869
+ initialized = false;
10
1870
  activeStepIds = new Map;
11
- startTrajectory(agentId, options = {}) {
1871
+ stepToTrajectory = new Map;
1872
+ writeQueues = new Map;
1873
+ static async start(runtime) {
1874
+ const service = new this(runtime);
1875
+ await service.initialize();
1876
+ return service;
1877
+ }
1878
+ async stop() {
1879
+ this.enabled = false;
1880
+ }
1881
+ setEnabled(enabled) {
1882
+ this.enabled = enabled;
1883
+ }
1884
+ isEnabled() {
1885
+ return this.enabled;
1886
+ }
1887
+ async getSqlHelper() {
1888
+ const drizzle = await Promise.resolve().then(() => (init_drizzle_orm(), exports_drizzle_orm));
1889
+ return drizzle.sql;
1890
+ }
1891
+ async executeRawSql(sqlText) {
1892
+ const runtime = this.runtime;
1893
+ if (!runtime?.adapter) {
1894
+ throw new Error("Database adapter not available");
1895
+ }
1896
+ const sqlHelper = await this.getSqlHelper();
1897
+ const db = runtime.adapter.db;
1898
+ const query = sqlHelper.raw(sqlText);
1899
+ const result = await db.execute(query);
1900
+ const rows = Array.isArray(result.rows) ? result.rows : [];
1901
+ const columns = result.fields && Array.isArray(result.fields) ? result.fields.map((field) => field.name) : rows.length > 0 ? Object.keys(rows[0]) : [];
1902
+ return { rows, columns };
1903
+ }
1904
+ async initialize() {
1905
+ if (this.initialized)
1906
+ return;
1907
+ const runtime = this.runtime;
1908
+ if (!runtime?.adapter) {
1909
+ logger2.warn("[trajectory-logger] No runtime adapter available, skipping initialization");
1910
+ return;
1911
+ }
1912
+ await this.ensureTablesExist();
1913
+ await this.backfillTrajectoriesMissingLlmCalls();
1914
+ this.initialized = true;
1915
+ logger2.info("[trajectory-logger] Trajectory logger service initialized");
1916
+ }
1917
+ async getTableColumnNames(tableName) {
1918
+ const names = new Set;
1919
+ try {
1920
+ const result = await this.executeRawSql(`
1921
+ SELECT column_name
1922
+ FROM information_schema.columns
1923
+ WHERE table_name = ${sqlLiteral(tableName)}
1924
+ AND table_schema NOT IN ('pg_catalog', 'information_schema')
1925
+ `);
1926
+ for (const row of result.rows) {
1927
+ const name2 = asString(pickCell(row, "column_name"));
1928
+ if (name2)
1929
+ names.add(name2);
1930
+ }
1931
+ if (names.size > 0)
1932
+ return names;
1933
+ } catch {}
1934
+ const safeTableName = tableName.replace(/[^a-zA-Z0-9_]/g, "");
1935
+ if (!safeTableName)
1936
+ return names;
1937
+ try {
1938
+ const pragma = await this.executeRawSql(`PRAGMA table_info(${safeTableName})`);
1939
+ for (const row of pragma.rows) {
1940
+ const name2 = asString(pickCell(row, "name"));
1941
+ if (name2)
1942
+ names.add(name2);
1943
+ }
1944
+ } catch {}
1945
+ return names;
1946
+ }
1947
+ async ensureTrajectoryColumnsExist() {
1948
+ const columns = await this.getTableColumnNames("trajectories");
1949
+ const requiredColumns = [
1950
+ ["scenario_id", "TEXT"],
1951
+ ["episode_id", "TEXT"],
1952
+ ["batch_id", "TEXT"],
1953
+ ["group_index", "INTEGER"],
1954
+ ["steps_json", "JSONB NOT NULL DEFAULT '[]'"],
1955
+ ["reward_components_json", "JSONB NOT NULL DEFAULT '{}'"],
1956
+ ["metrics_json", "JSONB NOT NULL DEFAULT '{}'"],
1957
+ ["metadata_json", "JSONB NOT NULL DEFAULT '{}'"],
1958
+ ["is_training_data", "BOOLEAN NOT NULL DEFAULT FALSE"],
1959
+ ["is_evaluation", "BOOLEAN NOT NULL DEFAULT FALSE"],
1960
+ ["used_in_training", "BOOLEAN NOT NULL DEFAULT FALSE"],
1961
+ ["judged_at", "TIMESTAMPTZ"]
1962
+ ];
1963
+ for (const [columnName, definition] of requiredColumns) {
1964
+ if (columns.has(columnName))
1965
+ continue;
1966
+ try {
1967
+ await this.executeRawSql(`
1968
+ ALTER TABLE trajectories
1969
+ ADD COLUMN IF NOT EXISTS ${columnName} ${definition}
1970
+ `);
1971
+ } catch (errWithIfExists) {
1972
+ try {
1973
+ await this.executeRawSql(`
1974
+ ALTER TABLE trajectories
1975
+ ADD COLUMN ${columnName} ${definition}
1976
+ `);
1977
+ } catch (errPlain) {
1978
+ const combinedMessage = `${errWithIfExists instanceof Error ? errWithIfExists.message : String(errWithIfExists)} | ${errPlain instanceof Error ? errPlain.message : String(errPlain)}`.toLowerCase();
1979
+ if (combinedMessage.includes("already exists") || combinedMessage.includes("duplicate column") || combinedMessage.includes("duplicate_column")) {
1980
+ continue;
1981
+ }
1982
+ logger2.warn(`[trajectory-logger] Failed to add trajectories.${columnName} (non-fatal): ${errPlain instanceof Error ? errPlain.message : String(errPlain)}`);
1983
+ }
1984
+ }
1985
+ }
1986
+ for (const statement of [
1987
+ `ALTER TABLE trajectories
1988
+ ALTER COLUMN start_time TYPE BIGINT USING start_time::BIGINT`,
1989
+ `ALTER TABLE trajectories
1990
+ ALTER COLUMN end_time TYPE BIGINT USING end_time::BIGINT`,
1991
+ `ALTER TABLE trajectories
1992
+ ALTER COLUMN duration_ms TYPE BIGINT USING duration_ms::BIGINT`
1993
+ ]) {
1994
+ try {
1995
+ await this.executeRawSql(statement);
1996
+ } catch {}
1997
+ }
1998
+ }
1999
+ async ensureTablesExist() {
2000
+ await this.executeRawSql(`
2001
+ CREATE TABLE IF NOT EXISTS trajectories (
2002
+ id TEXT PRIMARY KEY,
2003
+ agent_id TEXT NOT NULL,
2004
+ source TEXT NOT NULL DEFAULT 'chat',
2005
+ status TEXT NOT NULL DEFAULT 'active',
2006
+ start_time BIGINT NOT NULL,
2007
+ end_time BIGINT,
2008
+ duration_ms BIGINT,
2009
+ step_count INTEGER NOT NULL DEFAULT 0,
2010
+ llm_call_count INTEGER NOT NULL DEFAULT 0,
2011
+ provider_access_count INTEGER NOT NULL DEFAULT 0,
2012
+ total_prompt_tokens INTEGER NOT NULL DEFAULT 0,
2013
+ total_completion_tokens INTEGER NOT NULL DEFAULT 0,
2014
+ total_reward REAL NOT NULL DEFAULT 0,
2015
+ scenario_id TEXT,
2016
+ episode_id TEXT,
2017
+ batch_id TEXT,
2018
+ group_index INTEGER,
2019
+ steps_json JSONB NOT NULL DEFAULT '[]',
2020
+ reward_components_json JSONB NOT NULL DEFAULT '{}',
2021
+ metrics_json JSONB NOT NULL DEFAULT '{}',
2022
+ metadata_json JSONB NOT NULL DEFAULT '{}',
2023
+ is_training_data BOOLEAN NOT NULL DEFAULT FALSE,
2024
+ is_evaluation BOOLEAN NOT NULL DEFAULT FALSE,
2025
+ used_in_training BOOLEAN NOT NULL DEFAULT FALSE,
2026
+ ai_judge_reward REAL,
2027
+ ai_judge_reasoning TEXT,
2028
+ judged_at TIMESTAMPTZ,
2029
+ created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
2030
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
2031
+ )
2032
+ `);
2033
+ await this.ensureTrajectoryColumnsExist();
2034
+ try {
2035
+ await this.executeRawSql(`CREATE INDEX IF NOT EXISTS idx_trajectories_agent_id ON trajectories(agent_id)`);
2036
+ await this.executeRawSql(`CREATE INDEX IF NOT EXISTS idx_trajectories_source ON trajectories(source)`);
2037
+ await this.executeRawSql(`CREATE INDEX IF NOT EXISTS idx_trajectories_status ON trajectories(status)`);
2038
+ await this.executeRawSql(`CREATE INDEX IF NOT EXISTS idx_trajectories_created_at ON trajectories(created_at)`);
2039
+ await this.executeRawSql(`CREATE INDEX IF NOT EXISTS idx_trajectories_scenario_id ON trajectories(scenario_id)`);
2040
+ await this.executeRawSql(`CREATE INDEX IF NOT EXISTS idx_trajectories_batch_id ON trajectories(batch_id)`);
2041
+ await this.executeRawSql(`CREATE INDEX IF NOT EXISTS idx_trajectories_is_training ON trajectories(is_training_data)`);
2042
+ } catch (e) {
2043
+ logger2.warn(`[trajectory-logger] Failed to create indexes (non-fatal): ${e instanceof Error ? e.message : String(e)}`);
2044
+ }
2045
+ await this.executeRawSql(`
2046
+ CREATE TABLE IF NOT EXISTS trajectory_step_index (
2047
+ step_id TEXT PRIMARY KEY,
2048
+ trajectory_id TEXT NOT NULL REFERENCES trajectories(id) ON DELETE CASCADE,
2049
+ step_number INTEGER NOT NULL DEFAULT 0,
2050
+ is_active BOOLEAN NOT NULL DEFAULT FALSE,
2051
+ created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
2052
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
2053
+ )
2054
+ `);
2055
+ await this.executeRawSql(`CREATE INDEX IF NOT EXISTS idx_trajectory_step_index_trajectory_id ON trajectory_step_index(trajectory_id)`);
2056
+ await this.executeRawSql(`CREATE INDEX IF NOT EXISTS idx_trajectory_step_index_is_active ON trajectory_step_index(is_active)`);
2057
+ }
2058
+ normalizeTrajectoryStatus(value) {
2059
+ switch (value) {
2060
+ case "active":
2061
+ case "completed":
2062
+ case "error":
2063
+ case "timeout":
2064
+ case "terminated":
2065
+ return value;
2066
+ default:
2067
+ return "completed";
2068
+ }
2069
+ }
2070
+ async backfillTrajectoriesMissingLlmCalls() {
2071
+ const maxRows = 2000;
2072
+ let fixed = 0;
2073
+ try {
2074
+ const rows = await this.executeRawSql(`
2075
+ SELECT id, status
2076
+ FROM trajectories
2077
+ WHERE COALESCE(llm_call_count, 0) = 0
2078
+ AND status <> 'active'
2079
+ ORDER BY created_at ASC
2080
+ LIMIT ${maxRows}
2081
+ `);
2082
+ for (const row of rows.rows) {
2083
+ const trajectoryId = asString(pickCell(row, "id"));
2084
+ if (!trajectoryId)
2085
+ continue;
2086
+ const status = this.normalizeTrajectoryStatus(asString(pickCell(row, "status")));
2087
+ await this.withTrajectoryWriteLock(trajectoryId, async () => {
2088
+ const trajectory = await this.getTrajectoryById(trajectoryId);
2089
+ if (!trajectory)
2090
+ return;
2091
+ const inserted = this.ensureAtLeastOneLlmCall(trajectory, "backfill");
2092
+ if (!inserted)
2093
+ return;
2094
+ await this.persistTrajectory(trajectoryId, trajectory, status);
2095
+ fixed += 1;
2096
+ });
2097
+ }
2098
+ if (fixed > 0) {
2099
+ logger2.info(`[trajectory-logger] Backfilled ${fixed} completed trajectories with synthetic LLM calls`);
2100
+ }
2101
+ if (rows.rows.length >= maxRows) {
2102
+ logger2.warn(`[trajectory-logger] Backfill hit safety cap (${maxRows}); remaining older trajectories will be fixed lazily when touched`);
2103
+ }
2104
+ } catch (err) {
2105
+ logger2.warn(`[trajectory-logger] Failed to backfill trajectories missing LLM calls (non-fatal): ${err instanceof Error ? err.message : String(err)}`);
2106
+ }
2107
+ }
2108
+ normalizePurpose(value) {
2109
+ switch (value) {
2110
+ case "action":
2111
+ case "reasoning":
2112
+ case "evaluation":
2113
+ case "response":
2114
+ case "other":
2115
+ return value;
2116
+ default:
2117
+ return "other";
2118
+ }
2119
+ }
2120
+ defaultEnvironmentState(timestamp = Date.now()) {
2121
+ return {
2122
+ timestamp,
2123
+ agentBalance: 0,
2124
+ agentPoints: 0,
2125
+ agentPnL: 0,
2126
+ openPositions: 0
2127
+ };
2128
+ }
2129
+ createPendingAction(stepTimestamp) {
2130
+ return {
2131
+ attemptId: "",
2132
+ timestamp: stepTimestamp,
2133
+ actionType: "pending",
2134
+ actionName: "pending",
2135
+ parameters: {},
2136
+ success: false
2137
+ };
2138
+ }
2139
+ createStep(stepId, stepNumber, envState) {
2140
+ const timestamp = envState.timestamp || Date.now();
2141
+ return {
2142
+ stepId,
2143
+ stepNumber,
2144
+ timestamp,
2145
+ environmentState: envState,
2146
+ observation: {},
2147
+ llmCalls: [],
2148
+ providerAccesses: [],
2149
+ action: this.createPendingAction(timestamp),
2150
+ reward: 0,
2151
+ done: false
2152
+ };
2153
+ }
2154
+ ensureAtLeastOneLlmCall(trajectory, source) {
2155
+ if (this.computeTotals(trajectory.steps).llmCallCount > 0) {
2156
+ return false;
2157
+ }
2158
+ const timestamp = Date.now();
2159
+ let step = trajectory.steps[trajectory.steps.length - 1];
2160
+ if (!step) {
2161
+ step = this.createStep(uuidv4(), 0, this.defaultEnvironmentState(timestamp));
2162
+ step.done = true;
2163
+ trajectory.steps.push(step);
2164
+ }
2165
+ if (!Array.isArray(step.llmCalls)) {
2166
+ step.llmCalls = [];
2167
+ }
2168
+ const syntheticCall = {
2169
+ callId: uuidv4(),
2170
+ timestamp,
2171
+ model: "milady/synthetic-trajectory-fallback",
2172
+ systemPrompt: "[synthetic] inserted by trajectory logger because no LLM calls were captured",
2173
+ userPrompt: "[synthetic] this trajectory completed without recorded model activity",
2174
+ response: "[synthetic] placeholder call inserted to enforce minimum llm_call_count=1",
2175
+ temperature: 0,
2176
+ maxTokens: 0,
2177
+ promptTokens: 0,
2178
+ completionTokens: 0,
2179
+ latencyMs: 0,
2180
+ purpose: "other",
2181
+ actionType: "TRAJECTORY_FALLBACK"
2182
+ };
2183
+ step.llmCalls.push(syntheticCall);
2184
+ if (!step.metadata)
2185
+ step.metadata = {};
2186
+ step.metadata.syntheticLlmCall = true;
2187
+ step.metadata.syntheticLlmCallSource = source;
2188
+ trajectory.metadata.syntheticLlmCall = true;
2189
+ trajectory.metadata.syntheticLlmCallSource = source;
2190
+ const existingFallbackCount = trajectory.metrics.syntheticLlmFallbackCount;
2191
+ trajectory.metrics.syntheticLlmFallbackCount = typeof existingFallbackCount === "number" && Number.isFinite(existingFallbackCount) ? existingFallbackCount + 1 : 1;
2192
+ return true;
2193
+ }
2194
+ computeTotals(steps) {
2195
+ let llmCallCount = 0;
2196
+ let providerAccessCount = 0;
2197
+ let totalPromptTokens = 0;
2198
+ let totalCompletionTokens = 0;
2199
+ for (const step of steps) {
2200
+ const llmCalls = Array.isArray(step.llmCalls) ? step.llmCalls : [];
2201
+ const providerAccesses = Array.isArray(step.providerAccesses) ? step.providerAccesses : [];
2202
+ llmCallCount += llmCalls.length;
2203
+ providerAccessCount += providerAccesses.length;
2204
+ for (const call of llmCalls) {
2205
+ totalPromptTokens += call.promptTokens ?? 0;
2206
+ totalCompletionTokens += call.completionTokens ?? 0;
2207
+ }
2208
+ }
2209
+ return {
2210
+ stepCount: steps.length,
2211
+ llmCallCount,
2212
+ providerAccessCount,
2213
+ totalPromptTokens,
2214
+ totalCompletionTokens
2215
+ };
2216
+ }
2217
+ async withTrajectoryWriteLock(trajectoryId, task) {
2218
+ const previous = this.writeQueues.get(trajectoryId) ?? Promise.resolve();
2219
+ const next = previous.catch(() => {}).then(task);
2220
+ this.writeQueues.set(trajectoryId, next);
2221
+ try {
2222
+ await next;
2223
+ } finally {
2224
+ if (this.writeQueues.get(trajectoryId) === next) {
2225
+ this.writeQueues.delete(trajectoryId);
2226
+ }
2227
+ }
2228
+ }
2229
+ async getTrajectoryById(trajectoryId) {
2230
+ const result = await this.executeRawSql(`SELECT * FROM trajectories WHERE id = ${sqlLiteral(trajectoryId)} LIMIT 1`);
2231
+ if (result.rows.length === 0)
2232
+ return null;
2233
+ return this.rowToTrajectory(result.rows[0]);
2234
+ }
2235
+ async getStepIndex(stepId) {
2236
+ const result = await this.executeRawSql(`SELECT trajectory_id, step_number, is_active FROM trajectory_step_index WHERE step_id = ${sqlLiteral(stepId)} LIMIT 1`);
2237
+ const row = result.rows[0];
2238
+ if (!row)
2239
+ return null;
2240
+ const trajectoryId = asString(pickCell(row, "trajectory_id"));
2241
+ if (!trajectoryId)
2242
+ return null;
2243
+ const stepNumber = asNumber(pickCell(row, "step_number")) ?? 0;
2244
+ const isActiveText = asString(pickCell(row, "is_active"));
2245
+ const isActive = isActiveText === "true" || isActiveText === "t" || pickCell(row, "is_active") === true;
2246
+ return { trajectoryId, stepNumber, isActive };
2247
+ }
2248
+ async setStepIndex(stepId, trajectoryId, stepNumber, isActive) {
2249
+ await this.executeRawSql(`
2250
+ INSERT INTO trajectory_step_index (
2251
+ step_id, trajectory_id, step_number, is_active, updated_at
2252
+ ) VALUES (
2253
+ ${sqlLiteral(stepId)},
2254
+ ${sqlLiteral(trajectoryId)},
2255
+ ${stepNumber},
2256
+ ${isActive ? "TRUE" : "FALSE"},
2257
+ CURRENT_TIMESTAMP
2258
+ )
2259
+ ON CONFLICT (step_id) DO UPDATE SET
2260
+ trajectory_id = EXCLUDED.trajectory_id,
2261
+ step_number = EXCLUDED.step_number,
2262
+ is_active = EXCLUDED.is_active,
2263
+ updated_at = CURRENT_TIMESTAMP
2264
+ `);
2265
+ }
2266
+ async markAllStepsInactive(trajectoryId) {
2267
+ await this.executeRawSql(`
2268
+ UPDATE trajectory_step_index
2269
+ SET is_active = FALSE, updated_at = CURRENT_TIMESTAMP
2270
+ WHERE trajectory_id = ${sqlLiteral(trajectoryId)}
2271
+ `);
2272
+ }
2273
+ async resolveTrajectoryId(stepIdOrTrajectoryId) {
2274
+ const cached = this.stepToTrajectory.get(stepIdOrTrajectoryId);
2275
+ if (cached)
2276
+ return cached;
2277
+ const byStep = await this.getStepIndex(stepIdOrTrajectoryId);
2278
+ if (byStep?.trajectoryId) {
2279
+ this.stepToTrajectory.set(stepIdOrTrajectoryId, byStep.trajectoryId);
2280
+ return byStep.trajectoryId;
2281
+ }
2282
+ const byId = await this.executeRawSql(`SELECT id FROM trajectories WHERE id = ${sqlLiteral(stepIdOrTrajectoryId)} LIMIT 1`);
2283
+ const row = byId.rows[0];
2284
+ const id = row ? asString(pickCell(row, "id")) : null;
2285
+ return id;
2286
+ }
2287
+ async getCurrentStepIdFromDb(trajectoryId) {
2288
+ const result = await this.executeRawSql(`
2289
+ SELECT step_id
2290
+ FROM trajectory_step_index
2291
+ WHERE trajectory_id = ${sqlLiteral(trajectoryId)} AND is_active = TRUE
2292
+ ORDER BY step_number DESC, updated_at DESC
2293
+ LIMIT 1
2294
+ `);
2295
+ const row = result.rows[0];
2296
+ return row ? asString(pickCell(row, "step_id")) : null;
2297
+ }
2298
+ async persistTrajectory(trajectoryId, trajectory, status = "active") {
2299
+ if (status !== "active") {
2300
+ this.ensureAtLeastOneLlmCall(trajectory, "finalize");
2301
+ }
2302
+ const totals = this.computeTotals(trajectory.steps);
2303
+ const isFinalStatus = status !== "active";
2304
+ const persistedEndTime = isFinalStatus ? trajectory.endTime : null;
2305
+ const persistedDuration = isFinalStatus ? trajectory.durationMs : null;
2306
+ const updatedAtIso = new Date().toISOString();
2307
+ try {
2308
+ await this.executeRawSql(`
2309
+ UPDATE trajectories SET
2310
+ status = ${sqlLiteral(status)},
2311
+ end_time = ${sqlLiteral(persistedEndTime)},
2312
+ duration_ms = ${sqlLiteral(persistedDuration)},
2313
+ step_count = ${totals.stepCount},
2314
+ llm_call_count = ${totals.llmCallCount},
2315
+ provider_access_count = ${totals.providerAccessCount},
2316
+ total_prompt_tokens = ${totals.totalPromptTokens},
2317
+ total_completion_tokens = ${totals.totalCompletionTokens},
2318
+ total_reward = ${trajectory.totalReward},
2319
+ steps_json = ${sqlLiteral(trajectory.steps)},
2320
+ reward_components_json = ${sqlLiteral(trajectory.rewardComponents)},
2321
+ metrics_json = ${sqlLiteral(trajectory.metrics)},
2322
+ metadata_json = ${sqlLiteral(trajectory.metadata)},
2323
+ updated_at = ${sqlLiteral(updatedAtIso)}
2324
+ WHERE id = ${sqlLiteral(trajectoryId)}
2325
+ `);
2326
+ } catch (modernErr) {
2327
+ await this.executeRawSql(`
2328
+ UPDATE trajectories SET
2329
+ status = ${sqlLiteral(status)},
2330
+ end_time = ${sqlLiteral(persistedEndTime)},
2331
+ duration_ms = ${sqlLiteral(persistedDuration)},
2332
+ step_count = ${totals.stepCount},
2333
+ llm_call_count = ${totals.llmCallCount},
2334
+ provider_access_count = ${totals.providerAccessCount},
2335
+ total_prompt_tokens = ${totals.totalPromptTokens},
2336
+ total_completion_tokens = ${totals.totalCompletionTokens},
2337
+ total_reward = ${trajectory.totalReward},
2338
+ steps_json = ${sqlLiteral(trajectory.steps)},
2339
+ metadata = ${sqlLiteral(trajectory.metadata)},
2340
+ updated_at = ${sqlLiteral(updatedAtIso)}
2341
+ WHERE id = ${sqlLiteral(trajectoryId)}
2342
+ `).catch((legacyErr) => {
2343
+ logger2.warn({ err: legacyErr, trajectoryId }, `[trajectory-logger] Failed to persist trajectory update after compatibility fallback: ${modernErr instanceof Error ? modernErr.message : String(modernErr)}`);
2344
+ throw legacyErr;
2345
+ });
2346
+ }
2347
+ }
2348
+ async ensureStepExists(trajectory, stepId) {
2349
+ let step = trajectory.steps.find((entry) => entry.stepId === stepId);
2350
+ if (step) {
2351
+ if (!Array.isArray(step.llmCalls))
2352
+ step.llmCalls = [];
2353
+ if (!Array.isArray(step.providerAccesses))
2354
+ step.providerAccesses = [];
2355
+ return step;
2356
+ }
2357
+ const index = await this.getStepIndex(stepId);
2358
+ const stepNumber = index?.stepNumber ?? trajectory.steps.length;
2359
+ step = this.createStep(stepId, stepNumber, this.defaultEnvironmentState());
2360
+ trajectory.steps.push(step);
2361
+ trajectory.steps.sort((a, b) => a.stepNumber - b.stepNumber);
2362
+ return step;
2363
+ }
2364
+ logLlmCall(params) {
2365
+ if (!this.enabled)
2366
+ return;
2367
+ (async () => {
2368
+ const trajectoryId = await this.resolveTrajectoryId(params.stepId);
2369
+ if (!trajectoryId) {
2370
+ logger2.debug({ stepId: params.stepId }, "[trajectory-logger] No trajectory mapping for LLM call");
2371
+ return;
2372
+ }
2373
+ await this.withTrajectoryWriteLock(trajectoryId, async () => {
2374
+ const trajectory = await this.getTrajectoryById(trajectoryId);
2375
+ if (!trajectory)
2376
+ return;
2377
+ const step = await this.ensureStepExists(trajectory, params.stepId);
2378
+ const llmCall = {
2379
+ callId: uuidv4(),
2380
+ timestamp: Date.now(),
2381
+ model: params.model,
2382
+ modelVersion: params.modelVersion,
2383
+ systemPrompt: params.systemPrompt,
2384
+ userPrompt: params.userPrompt,
2385
+ response: params.response,
2386
+ reasoning: params.reasoning,
2387
+ temperature: params.temperature,
2388
+ maxTokens: params.maxTokens,
2389
+ purpose: this.normalizePurpose(params.purpose),
2390
+ actionType: params.actionType,
2391
+ promptTokens: params.promptTokens,
2392
+ completionTokens: params.completionTokens,
2393
+ latencyMs: params.latencyMs
2394
+ };
2395
+ step.llmCalls.push(llmCall);
2396
+ await this.persistTrajectory(trajectoryId, trajectory, "active");
2397
+ });
2398
+ })().catch((err) => {
2399
+ logger2.warn({ err, stepId: params.stepId }, "[trajectory-logger] Failed to persist LLM call");
2400
+ });
2401
+ }
2402
+ logLLMCall(stepId, details) {
2403
+ this.logLlmCall({
2404
+ stepId,
2405
+ model: details.model,
2406
+ modelVersion: details.modelVersion,
2407
+ systemPrompt: details.systemPrompt,
2408
+ userPrompt: details.userPrompt,
2409
+ response: details.response,
2410
+ reasoning: details.reasoning,
2411
+ temperature: details.temperature,
2412
+ maxTokens: details.maxTokens,
2413
+ purpose: details.purpose,
2414
+ actionType: details.actionType ?? "",
2415
+ latencyMs: details.latencyMs ?? 0,
2416
+ promptTokens: details.promptTokens,
2417
+ completionTokens: details.completionTokens
2418
+ });
2419
+ }
2420
+ logProviderAccess(arg1, arg2) {
2421
+ if (!this.enabled)
2422
+ return;
2423
+ const params = typeof arg1 === "string" ? {
2424
+ stepId: arg1,
2425
+ providerName: arg2?.providerName ?? "unknown",
2426
+ data: arg2?.data ?? {},
2427
+ purpose: arg2?.purpose ?? "other",
2428
+ query: arg2?.query
2429
+ } : arg1;
2430
+ (async () => {
2431
+ const trajectoryId = await this.resolveTrajectoryId(params.stepId);
2432
+ if (!trajectoryId) {
2433
+ logger2.debug({ stepId: params.stepId }, "[trajectory-logger] No trajectory mapping for provider access");
2434
+ return;
2435
+ }
2436
+ await this.withTrajectoryWriteLock(trajectoryId, async () => {
2437
+ const trajectory = await this.getTrajectoryById(trajectoryId);
2438
+ if (!trajectory)
2439
+ return;
2440
+ const step = await this.ensureStepExists(trajectory, params.stepId);
2441
+ const access = {
2442
+ providerId: uuidv4(),
2443
+ providerName: params.providerName,
2444
+ timestamp: Date.now(),
2445
+ data: params.data,
2446
+ query: params.query,
2447
+ purpose: params.purpose
2448
+ };
2449
+ step.providerAccesses.push(access);
2450
+ await this.persistTrajectory(trajectoryId, trajectory, "active");
2451
+ });
2452
+ })().catch((err) => {
2453
+ logger2.warn({ err, stepId: params.stepId }, "[trajectory-logger] Failed to persist provider access");
2454
+ });
2455
+ }
2456
+ logProviderAccessByTrajectoryId(trajectoryId, access) {
2457
+ const stepId = this.getCurrentStepId(trajectoryId);
2458
+ if (!stepId) {
2459
+ logger2.debug({ trajectoryId }, "[trajectory-logger] No active step for provider access by trajectory");
2460
+ return;
2461
+ }
2462
+ this.logProviderAccess(stepId, access);
2463
+ }
2464
+ async startTrajectory(stepIdOrAgentId, options = {}) {
2465
+ if (!this.enabled)
2466
+ return uuidv4();
2467
+ const legacyStepId = typeof options.agentId === "string" && options.agentId.length > 0 ? stepIdOrAgentId : null;
2468
+ const agentId = (typeof options.agentId === "string" && options.agentId.length > 0 ? options.agentId : stepIdOrAgentId) ?? stepIdOrAgentId;
12
2469
  const trajectoryId = uuidv4();
13
2470
  const now = Date.now();
2471
+ const timestampIso = new Date(now).toISOString();
2472
+ const metadata = {
2473
+ ...options.metadata ?? {}
2474
+ };
2475
+ if (options.roomId)
2476
+ metadata.roomId = options.roomId;
2477
+ if (options.entityId)
2478
+ metadata.entityId = options.entityId;
14
2479
  const trajectory = {
15
- trajectoryId: asUUID(trajectoryId),
16
- agentId: asUUID(agentId),
2480
+ trajectoryId,
2481
+ agentId,
17
2482
  startTime: now,
18
2483
  endTime: now,
19
2484
  durationMs: 0,
20
- episodeId: options.episodeId,
21
2485
  scenarioId: options.scenarioId,
2486
+ episodeId: options.episodeId,
22
2487
  batchId: options.batchId,
23
2488
  groupIndex: options.groupIndex,
24
2489
  steps: [],
25
2490
  totalReward: 0,
26
- rewardComponents: {
27
- environmentReward: 0
28
- },
2491
+ rewardComponents: { environmentReward: 0 },
29
2492
  metrics: {
30
2493
  episodeLength: 0,
31
2494
  finalStatus: "completed"
32
2495
  },
33
- metadata: options.metadata || {}
2496
+ metadata: {
2497
+ source: options.source ?? "chat",
2498
+ ...metadata
2499
+ }
34
2500
  };
35
- this.activeTrajectories.set(trajectoryId, trajectory);
2501
+ let persistedStart = false;
2502
+ try {
2503
+ await this.executeRawSql(`
2504
+ INSERT INTO trajectories (
2505
+ id, agent_id, source, status, start_time, scenario_id, episode_id,
2506
+ batch_id, group_index, metadata_json, steps_json, reward_components_json, metrics_json,
2507
+ created_at, updated_at
2508
+ ) VALUES (
2509
+ ${sqlLiteral(trajectoryId)},
2510
+ ${sqlLiteral(agentId)},
2511
+ ${sqlLiteral(options.source ?? "chat")},
2512
+ 'active',
2513
+ ${now},
2514
+ ${sqlLiteral(options.scenarioId ?? null)},
2515
+ ${sqlLiteral(options.episodeId ?? null)},
2516
+ ${sqlLiteral(options.batchId ?? null)},
2517
+ ${options.groupIndex ?? "NULL"},
2518
+ ${sqlLiteral(trajectory.metadata)},
2519
+ ${sqlLiteral([])},
2520
+ ${sqlLiteral(trajectory.rewardComponents)},
2521
+ ${sqlLiteral(trajectory.metrics)},
2522
+ ${sqlLiteral(timestampIso)},
2523
+ ${sqlLiteral(timestampIso)}
2524
+ )
2525
+ `);
2526
+ persistedStart = true;
2527
+ } catch (err) {
2528
+ try {
2529
+ await this.executeRawSql(`
2530
+ INSERT INTO trajectories (
2531
+ id, agent_id, source, status, start_time, steps_json, metadata, created_at, updated_at
2532
+ ) VALUES (
2533
+ ${sqlLiteral(trajectoryId)},
2534
+ ${sqlLiteral(agentId)},
2535
+ ${sqlLiteral(options.source ?? "chat")},
2536
+ 'active',
2537
+ ${now},
2538
+ ${sqlLiteral([])},
2539
+ ${sqlLiteral(trajectory.metadata)},
2540
+ ${sqlLiteral(timestampIso)},
2541
+ ${sqlLiteral(timestampIso)}
2542
+ )
2543
+ `);
2544
+ persistedStart = true;
2545
+ } catch (legacyErr) {
2546
+ logger2.warn({ err: legacyErr, trajectoryId }, "[trajectory-logger] Failed to persist trajectory start");
2547
+ }
2548
+ }
2549
+ if (persistedStart && legacyStepId) {
2550
+ this.stepToTrajectory.set(legacyStepId, trajectoryId);
2551
+ try {
2552
+ await this.setStepIndex(legacyStepId, trajectoryId, -1, false);
2553
+ } catch (indexErr) {
2554
+ logger2.warn({ err: indexErr, trajectoryId, stepId: legacyStepId }, "[trajectory-logger] Failed to persist step index for trajectory start");
2555
+ }
2556
+ }
36
2557
  return trajectoryId;
37
2558
  }
38
2559
  startStep(trajectoryId, envState) {
2560
+ if (!this.enabled)
2561
+ return uuidv4();
39
2562
  const stepId = uuidv4();
40
- const trajectory = this.activeTrajectories.get(trajectoryId);
41
- if (!trajectory) {
42
- throw new Error(`Trajectory ${trajectoryId} not found`);
43
- }
44
- const step = {
45
- stepId: asUUID(stepId),
46
- stepNumber: trajectory.steps.length,
47
- timestamp: envState.timestamp || Date.now(),
48
- environmentState: envState,
49
- observation: {},
50
- llmCalls: [],
51
- providerAccesses: [],
52
- action: {
53
- attemptId: "",
54
- timestamp: 0,
55
- actionType: "pending",
56
- actionName: "pending",
57
- parameters: {},
58
- success: false
59
- },
60
- reward: 0,
61
- done: false
62
- };
63
- trajectory.steps.push(step);
64
2563
  this.activeStepIds.set(trajectoryId, stepId);
2564
+ this.stepToTrajectory.set(stepId, trajectoryId);
2565
+ this.withTrajectoryWriteLock(trajectoryId, async () => {
2566
+ const trajectory = await this.getTrajectoryById(trajectoryId);
2567
+ if (!trajectory) {
2568
+ logger2.warn({ trajectoryId }, "[trajectory-logger] Trajectory not found for startStep");
2569
+ return;
2570
+ }
2571
+ const step = this.createStep(stepId, trajectory.steps.length, envState);
2572
+ trajectory.steps.push(step);
2573
+ await this.markAllStepsInactive(trajectoryId);
2574
+ await this.setStepIndex(stepId, trajectoryId, step.stepNumber, true);
2575
+ await this.persistTrajectory(trajectoryId, trajectory, "active");
2576
+ }).catch((err) => {
2577
+ logger2.warn({ err, trajectoryId, stepId }, "[trajectory-logger] Failed to persist startStep");
2578
+ });
65
2579
  return stepId;
66
2580
  }
67
- logLLMCall(stepId, llmCall) {
68
- const trajectory = this.findTrajectoryByStepId(stepId);
69
- if (!trajectory) {
70
- logger.warn({ stepId }, "Trajectory not found for LLM call");
2581
+ completeStep(trajectoryId, actionOrStepId, actionOrReward, maybeReward) {
2582
+ if (!this.enabled)
71
2583
  return;
72
- }
73
- const step = trajectory.steps.find((s) => s.stepId === stepId);
74
- if (!step) {
75
- logger.warn({ stepId }, "Step not found for LLM call");
2584
+ const explicitStepId = typeof actionOrStepId === "string" ? actionOrStepId : null;
2585
+ const action = typeof actionOrStepId === "string" ? actionOrReward : actionOrStepId;
2586
+ const rewardInfo = typeof actionOrStepId === "string" ? maybeReward : actionOrReward;
2587
+ if (!action)
76
2588
  return;
77
- }
78
- const fullLLMCall = {
79
- callId: uuidv4(),
80
- timestamp: Date.now(),
81
- ...llmCall
82
- };
83
- step.llmCalls.push(fullLLMCall);
2589
+ this.withTrajectoryWriteLock(trajectoryId, async () => {
2590
+ const trajectory = await this.getTrajectoryById(trajectoryId);
2591
+ if (!trajectory)
2592
+ return;
2593
+ const stepId = explicitStepId ?? this.activeStepIds.get(trajectoryId) ?? await this.getCurrentStepIdFromDb(trajectoryId);
2594
+ if (!stepId)
2595
+ return;
2596
+ const step = await this.ensureStepExists(trajectory, stepId);
2597
+ step.action = {
2598
+ attemptId: uuidv4(),
2599
+ timestamp: Date.now(),
2600
+ ...action
2601
+ };
2602
+ step.done = true;
2603
+ if (rewardInfo?.reward !== undefined) {
2604
+ step.reward = rewardInfo.reward;
2605
+ trajectory.totalReward += rewardInfo.reward;
2606
+ }
2607
+ if (rewardInfo?.components) {
2608
+ trajectory.rewardComponents = {
2609
+ ...trajectory.rewardComponents,
2610
+ ...rewardInfo.components
2611
+ };
2612
+ }
2613
+ await this.setStepIndex(stepId, trajectoryId, step.stepNumber, false);
2614
+ this.activeStepIds.delete(trajectoryId);
2615
+ await this.persistTrajectory(trajectoryId, trajectory, "active");
2616
+ }).catch((err) => {
2617
+ logger2.warn({ err, trajectoryId }, "[trajectory-logger] Failed to complete step");
2618
+ });
84
2619
  }
85
- logProviderAccess(stepId, access) {
86
- const trajectory = this.findTrajectoryByStepId(stepId);
87
- if (!trajectory) {
88
- logger.warn({ stepId }, "Trajectory not found for provider access");
2620
+ async endTrajectory(stepIdOrTrajectoryId, status = "completed", finalMetrics) {
2621
+ if (!this.enabled)
89
2622
  return;
90
- }
91
- const step = trajectory.steps.find((s) => s.stepId === stepId);
92
- if (!step) {
93
- logger.warn({ stepId }, "Step not found for provider access");
2623
+ const trajectoryId = await this.resolveTrajectoryId(stepIdOrTrajectoryId);
2624
+ if (!trajectoryId) {
2625
+ logger2.debug({ stepIdOrTrajectoryId }, "[trajectory-logger] No trajectory to end");
94
2626
  return;
95
2627
  }
96
- const fullAccess = {
97
- providerId: uuidv4(),
98
- timestamp: Date.now(),
99
- ...access
100
- };
101
- step.providerAccesses.push(fullAccess);
102
- }
103
- logLLMCallByTrajectoryId(trajectoryId, llmCall) {
104
- const stepId = this.activeStepIds.get(trajectoryId);
105
- if (!stepId) {
106
- logger.warn({ trajectoryId }, "No active step for trajectory");
107
- return;
2628
+ await this.withTrajectoryWriteLock(trajectoryId, async () => {
2629
+ const trajectory = await this.getTrajectoryById(trajectoryId);
2630
+ if (!trajectory) {
2631
+ logger2.debug({ trajectoryId }, "[trajectory-logger] Trajectory not found while ending");
2632
+ return;
2633
+ }
2634
+ const now = Date.now();
2635
+ trajectory.endTime = now;
2636
+ trajectory.durationMs = now - trajectory.startTime;
2637
+ trajectory.metrics.finalStatus = status;
2638
+ trajectory.metrics.episodeLength = trajectory.steps.length;
2639
+ if (finalMetrics) {
2640
+ trajectory.metrics = {
2641
+ ...trajectory.metrics,
2642
+ ...finalMetrics
2643
+ };
2644
+ }
2645
+ await this.markAllStepsInactive(trajectoryId);
2646
+ this.activeStepIds.delete(trajectoryId);
2647
+ await this.persistTrajectory(trajectoryId, trajectory, status);
2648
+ });
2649
+ for (const [stepId, mappedTrajectoryId] of this.stepToTrajectory.entries()) {
2650
+ if (mappedTrajectoryId === trajectoryId) {
2651
+ this.stepToTrajectory.delete(stepId);
2652
+ }
108
2653
  }
109
- this.logLLMCall(stepId, llmCall);
110
2654
  }
111
- logProviderAccessByTrajectoryId(trajectoryId, access) {
112
- const stepId = this.activeStepIds.get(trajectoryId);
113
- if (!stepId) {
114
- logger.warn({ trajectoryId }, "No active step for trajectory");
115
- return;
2655
+ async listTrajectories(options = {}) {
2656
+ const runtime = this.runtime;
2657
+ if (!runtime?.adapter) {
2658
+ return { trajectories: [], total: 0, offset: 0, limit: 50 };
116
2659
  }
117
- this.logProviderAccess(stepId, access);
2660
+ const offset = Math.max(0, options.offset ?? 0);
2661
+ const limit = Math.min(500, Math.max(1, options.limit ?? 50));
2662
+ const whereClauses = [];
2663
+ if (options.status) {
2664
+ whereClauses.push(`status = ${sqlLiteral(options.status)}`);
2665
+ }
2666
+ if (options.source) {
2667
+ whereClauses.push(`source = ${sqlLiteral(options.source)}`);
2668
+ }
2669
+ if (options.scenarioId) {
2670
+ whereClauses.push(`scenario_id = ${sqlLiteral(options.scenarioId)}`);
2671
+ }
2672
+ if (options.batchId) {
2673
+ whereClauses.push(`batch_id = ${sqlLiteral(options.batchId)}`);
2674
+ }
2675
+ if (options.isTrainingData !== undefined) {
2676
+ whereClauses.push(`is_training_data = ${options.isTrainingData}`);
2677
+ }
2678
+ if (options.startDate) {
2679
+ whereClauses.push(`created_at >= ${sqlLiteral(options.startDate)}::timestamptz`);
2680
+ }
2681
+ if (options.endDate) {
2682
+ whereClauses.push(`created_at <= ${sqlLiteral(options.endDate)}::timestamptz`);
2683
+ }
2684
+ if (options.search) {
2685
+ const escaped = options.search.replace(/'/g, "''").replace(/%/g, "\\%");
2686
+ whereClauses.push(`(
2687
+ id ILIKE '%${escaped}%' OR
2688
+ agent_id ILIKE '%${escaped}%' OR
2689
+ source ILIKE '%${escaped}%' OR
2690
+ scenario_id ILIKE '%${escaped}%'
2691
+ )`);
2692
+ }
2693
+ const whereClause = whereClauses.length > 0 ? `WHERE ${whereClauses.join(" AND ")}` : "";
2694
+ const countResult = await this.executeRawSql(`SELECT count(*)::int AS total FROM trajectories ${whereClause}`);
2695
+ const total = asNumber(pickCell(countResult.rows[0] ?? {}, "total")) ?? 0;
2696
+ const rowsResult = await this.executeRawSql(`
2697
+ SELECT
2698
+ id, agent_id, source, status, start_time, end_time, duration_ms,
2699
+ step_count, llm_call_count, total_prompt_tokens, total_completion_tokens,
2700
+ total_reward, scenario_id, batch_id, created_at
2701
+ FROM trajectories
2702
+ ${whereClause}
2703
+ ORDER BY created_at DESC
2704
+ LIMIT ${limit} OFFSET ${offset}
2705
+ `);
2706
+ const trajectories = rowsResult.rows.map((row) => {
2707
+ const status = asString(pickCell(row, "status")) ?? "completed";
2708
+ const rawLlmCallCount = asNumber(pickCell(row, "llm_call_count")) ?? 0;
2709
+ const llmCallCount = status === "active" ? rawLlmCallCount : Math.max(1, rawLlmCallCount);
2710
+ return {
2711
+ id: asString(pickCell(row, "id")) ?? "",
2712
+ agentId: asString(pickCell(row, "agent_id")) ?? "",
2713
+ source: asString(pickCell(row, "source")) ?? "chat",
2714
+ status,
2715
+ startTime: asNumber(pickCell(row, "start_time")) ?? 0,
2716
+ endTime: asNumber(pickCell(row, "end_time")),
2717
+ durationMs: asNumber(pickCell(row, "duration_ms")),
2718
+ stepCount: asNumber(pickCell(row, "step_count")) ?? 0,
2719
+ llmCallCount,
2720
+ totalPromptTokens: asNumber(pickCell(row, "total_prompt_tokens")) ?? 0,
2721
+ totalCompletionTokens: asNumber(pickCell(row, "total_completion_tokens")) ?? 0,
2722
+ totalReward: asNumber(pickCell(row, "total_reward")) ?? 0,
2723
+ scenarioId: asString(pickCell(row, "scenario_id")),
2724
+ batchId: asString(pickCell(row, "batch_id")),
2725
+ createdAt: asIsoString(pickCell(row, "created_at"))
2726
+ };
2727
+ });
2728
+ return { trajectories, total, offset, limit };
118
2729
  }
119
- getCurrentStepId(trajectoryId) {
120
- return this.activeStepIds.get(trajectoryId) || null;
2730
+ async getTrajectoryDetail(trajectoryId) {
2731
+ const runtime = this.runtime;
2732
+ if (!runtime?.adapter)
2733
+ return null;
2734
+ const safeId = trajectoryId.replace(/'/g, "''");
2735
+ const result = await this.executeRawSql(`SELECT * FROM trajectories WHERE id = '${safeId}' LIMIT 1`);
2736
+ if (result.rows.length === 0)
2737
+ return null;
2738
+ const row = result.rows[0];
2739
+ const trajectory = this.rowToTrajectory(row);
2740
+ const status = this.normalizeTrajectoryStatus(asString(pickCell(row, "status")));
2741
+ if (status !== "active") {
2742
+ const inserted = this.ensureAtLeastOneLlmCall(trajectory, "backfill");
2743
+ if (inserted) {
2744
+ await this.withTrajectoryWriteLock(trajectoryId, async () => {
2745
+ await this.persistTrajectory(trajectoryId, trajectory, status);
2746
+ });
2747
+ }
2748
+ }
2749
+ return trajectory;
121
2750
  }
122
- completeStep(trajectoryId, stepId, action, rewardInfo) {
123
- const trajectory = this.activeTrajectories.get(trajectoryId);
124
- if (!trajectory) {
125
- logger.warn({ trajectoryId }, "Trajectory not found for completeStep");
126
- return;
2751
+ async getStats() {
2752
+ const runtime = this.runtime;
2753
+ if (!runtime?.adapter) {
2754
+ return {
2755
+ totalTrajectories: 0,
2756
+ totalSteps: 0,
2757
+ totalLlmCalls: 0,
2758
+ totalPromptTokens: 0,
2759
+ totalCompletionTokens: 0,
2760
+ averageDurationMs: 0,
2761
+ averageReward: 0,
2762
+ bySource: {},
2763
+ byStatus: {},
2764
+ byScenario: {}
2765
+ };
127
2766
  }
128
- const step = trajectory.steps.find((s) => s.stepId === stepId);
129
- if (!step) {
130
- logger.warn({ trajectoryId, stepId }, "Step not found for completeStep");
131
- return;
2767
+ const statsResult = await this.executeRawSql(`
2768
+ SELECT
2769
+ count(*)::int AS total_trajectories,
2770
+ COALESCE(sum(step_count), 0)::int AS total_steps,
2771
+ COALESCE(sum(llm_call_count), 0)::int AS total_llm_calls,
2772
+ COALESCE(sum(total_prompt_tokens), 0)::int AS total_prompt_tokens,
2773
+ COALESCE(sum(total_completion_tokens), 0)::int AS total_completion_tokens,
2774
+ COALESCE(avg(duration_ms), 0)::int AS avg_duration_ms,
2775
+ COALESCE(avg(total_reward), 0)::real AS avg_reward
2776
+ FROM trajectories
2777
+ `);
2778
+ const sourceResult = await this.executeRawSql(`
2779
+ SELECT source, count(*)::int AS cnt
2780
+ FROM trajectories
2781
+ GROUP BY source
2782
+ `);
2783
+ const statusResult = await this.executeRawSql(`
2784
+ SELECT status, count(*)::int AS cnt
2785
+ FROM trajectories
2786
+ GROUP BY status
2787
+ `);
2788
+ const scenarioResult = await this.executeRawSql(`
2789
+ SELECT scenario_id, count(*)::int AS cnt
2790
+ FROM trajectories
2791
+ WHERE scenario_id IS NOT NULL
2792
+ GROUP BY scenario_id
2793
+ `);
2794
+ const stats = statsResult.rows[0] ?? {};
2795
+ const bySource = {};
2796
+ const byStatus = {};
2797
+ const byScenario = {};
2798
+ for (const row of sourceResult.rows) {
2799
+ const source = asString(pickCell(row, "source"));
2800
+ const cnt = asNumber(pickCell(row, "cnt"));
2801
+ if (source && cnt !== null)
2802
+ bySource[source] = cnt;
132
2803
  }
133
- step.action = {
134
- attemptId: uuidv4(),
135
- timestamp: Date.now(),
136
- ...action
2804
+ for (const row of statusResult.rows) {
2805
+ const status = asString(pickCell(row, "status"));
2806
+ const cnt = asNumber(pickCell(row, "cnt"));
2807
+ if (status && cnt !== null)
2808
+ byStatus[status] = cnt;
2809
+ }
2810
+ for (const row of scenarioResult.rows) {
2811
+ const scenario = asString(pickCell(row, "scenario_id"));
2812
+ const cnt = asNumber(pickCell(row, "cnt"));
2813
+ if (scenario && cnt !== null)
2814
+ byScenario[scenario] = cnt;
2815
+ }
2816
+ return {
2817
+ totalTrajectories: asNumber(pickCell(stats, "total_trajectories")) ?? 0,
2818
+ totalSteps: asNumber(pickCell(stats, "total_steps")) ?? 0,
2819
+ totalLlmCalls: asNumber(pickCell(stats, "total_llm_calls")) ?? 0,
2820
+ totalPromptTokens: asNumber(pickCell(stats, "total_prompt_tokens")) ?? 0,
2821
+ totalCompletionTokens: asNumber(pickCell(stats, "total_completion_tokens")) ?? 0,
2822
+ averageDurationMs: asNumber(pickCell(stats, "avg_duration_ms")) ?? 0,
2823
+ averageReward: asNumber(pickCell(stats, "avg_reward")) ?? 0,
2824
+ bySource,
2825
+ byStatus,
2826
+ byScenario
137
2827
  };
138
- if (rewardInfo?.reward !== undefined) {
139
- step.reward = rewardInfo.reward;
140
- trajectory.totalReward += rewardInfo.reward;
141
- }
142
- if (rewardInfo?.components) {
143
- trajectory.rewardComponents = {
144
- ...trajectory.rewardComponents,
145
- ...rewardInfo.components
146
- };
2828
+ }
2829
+ async deleteTrajectories(trajectoryIds) {
2830
+ const runtime = this.runtime;
2831
+ if (!runtime?.adapter)
2832
+ return 0;
2833
+ if (trajectoryIds.length === 0)
2834
+ return 0;
2835
+ const ids = trajectoryIds.map(sqlLiteral).join(", ");
2836
+ const result = await this.executeRawSql(`DELETE FROM trajectories WHERE id IN (${ids}) RETURNING id`);
2837
+ return result.rows.length;
2838
+ }
2839
+ async clearAllTrajectories() {
2840
+ const runtime = this.runtime;
2841
+ if (!runtime?.adapter)
2842
+ return 0;
2843
+ const countResult = await this.executeRawSql(`SELECT count(*)::int AS cnt FROM trajectories`);
2844
+ const count2 = asNumber(pickCell(countResult.rows[0] ?? {}, "cnt")) ?? 0;
2845
+ await this.executeRawSql(`DELETE FROM trajectories`);
2846
+ return count2;
2847
+ }
2848
+ sanitizeZipFolderName(value) {
2849
+ const sanitized = value.trim().replace(/[^a-zA-Z0-9._-]+/g, "_").replace(/^_+|_+$/g, "");
2850
+ return sanitized || "trajectory";
2851
+ }
2852
+ redactTrajectoryPrompts(trajectory) {
2853
+ return {
2854
+ ...trajectory,
2855
+ steps: trajectory.steps.map((step) => ({
2856
+ ...step,
2857
+ llmCalls: step.llmCalls.map((call) => ({
2858
+ ...call,
2859
+ systemPrompt: "[redacted]",
2860
+ userPrompt: "[redacted]",
2861
+ response: "[redacted]"
2862
+ }))
2863
+ }))
2864
+ };
2865
+ }
2866
+ buildZipSummary(trajectory) {
2867
+ const finalStatus = trajectory.metrics?.finalStatus ?? "completed";
2868
+ const normalizedEndTime = typeof trajectory.endTime === "number" && trajectory.endTime > 0 ? trajectory.endTime : null;
2869
+ const status = finalStatus === "timeout" || finalStatus === "terminated" || finalStatus === "error" ? "error" : finalStatus === "completed" ? "completed" : normalizedEndTime ? "completed" : "active";
2870
+ let llmCallCount = 0;
2871
+ let providerAccessCount = 0;
2872
+ let totalPromptTokens = 0;
2873
+ let totalCompletionTokens = 0;
2874
+ for (const step of trajectory.steps) {
2875
+ providerAccessCount += step.providerAccesses.length;
2876
+ llmCallCount += step.llmCalls.length;
2877
+ for (const call of step.llmCalls) {
2878
+ totalPromptTokens += call.promptTokens ?? 0;
2879
+ totalCompletionTokens += call.completionTokens ?? 0;
2880
+ }
147
2881
  }
148
- this.activeStepIds.delete(trajectoryId);
2882
+ const metadata = trajectory.metadata ?? {};
2883
+ const asNullableString = (value) => typeof value === "string" ? value : null;
2884
+ const source = typeof metadata.source === "string" ? metadata.source : "chat";
2885
+ const normalizedDurationMs = status === "active" ? null : typeof trajectory.durationMs === "number" ? trajectory.durationMs : null;
2886
+ const updatedAtMs = normalizedEndTime ?? (trajectory.startTime || Date.now());
2887
+ return {
2888
+ id: trajectory.trajectoryId,
2889
+ agentId: trajectory.agentId,
2890
+ roomId: asNullableString(metadata.roomId),
2891
+ entityId: asNullableString(metadata.entityId),
2892
+ conversationId: asNullableString(metadata.conversationId),
2893
+ source,
2894
+ status,
2895
+ startTime: trajectory.startTime,
2896
+ endTime: normalizedEndTime,
2897
+ durationMs: normalizedDurationMs,
2898
+ llmCallCount,
2899
+ providerAccessCount,
2900
+ totalPromptTokens,
2901
+ totalCompletionTokens,
2902
+ metadata,
2903
+ createdAt: new Date(trajectory.startTime).toISOString(),
2904
+ updatedAt: new Date(updatedAtMs).toISOString()
2905
+ };
149
2906
  }
150
- completeCurrentStep(trajectoryId, action, rewardInfo) {
151
- const stepId = this.activeStepIds.get(trajectoryId);
152
- if (!stepId) {
153
- logger.warn({ trajectoryId }, "No active step for trajectory");
154
- return;
2907
+ async exportTrajectoriesZip(options = {}) {
2908
+ let targetIds = Array.isArray(options.trajectoryIds) ? options.trajectoryIds.filter((id) => typeof id === "string" && id.trim().length > 0) : [];
2909
+ if (targetIds.length === 0) {
2910
+ const list = await this.listTrajectories({
2911
+ limit: 500,
2912
+ startDate: options.startDate,
2913
+ endDate: options.endDate,
2914
+ scenarioId: options.scenarioId,
2915
+ batchId: options.batchId
2916
+ });
2917
+ targetIds = list.trajectories.map((trajectory) => trajectory.id);
2918
+ }
2919
+ const entries = [];
2920
+ const manifestRows = [];
2921
+ for (const trajectoryId of targetIds) {
2922
+ const detail = await this.getTrajectoryDetail(trajectoryId);
2923
+ if (!detail)
2924
+ continue;
2925
+ const exportTrajectory = options.includePrompts === false ? this.redactTrajectoryPrompts(detail) : detail;
2926
+ const summary = this.buildZipSummary(exportTrajectory);
2927
+ const folderName = this.sanitizeZipFolderName(trajectoryId);
2928
+ entries.push({
2929
+ name: `${folderName}/trajectory.json`,
2930
+ data: JSON.stringify(exportTrajectory, null, 2)
2931
+ });
2932
+ entries.push({
2933
+ name: `${folderName}/summary.json`,
2934
+ data: JSON.stringify(summary, null, 2)
2935
+ });
2936
+ manifestRows.push({
2937
+ trajectoryId,
2938
+ folder: folderName,
2939
+ createdAt: summary.createdAt
2940
+ });
155
2941
  }
156
- this.completeStep(trajectoryId, stepId, action, rewardInfo);
2942
+ entries.unshift({
2943
+ name: "manifest.json",
2944
+ data: JSON.stringify({
2945
+ exportedAt: new Date().toISOString(),
2946
+ trajectories: manifestRows
2947
+ }, null, 2)
2948
+ });
2949
+ const timestamp = new Date().toISOString().replace(/[:.]/g, "-");
2950
+ return {
2951
+ filename: `trajectories-${timestamp}.zip`,
2952
+ entries
2953
+ };
157
2954
  }
158
- async endTrajectory(trajectoryId, status, finalMetrics) {
159
- const trajectory = this.activeTrajectories.get(trajectoryId);
160
- if (!trajectory) {
161
- logger.warn({ trajectoryId }, "Trajectory not found for endTrajectory");
162
- return;
2955
+ async exportTrajectories(options) {
2956
+ const runtime = this.runtime;
2957
+ if (!runtime?.adapter) {
2958
+ throw new Error("Database not available");
2959
+ }
2960
+ const whereClauses = [];
2961
+ if (options.trajectoryIds && options.trajectoryIds.length > 0) {
2962
+ const ids = options.trajectoryIds.map(sqlLiteral).join(", ");
2963
+ whereClauses.push(`id IN (${ids})`);
2964
+ }
2965
+ if (options.startDate) {
2966
+ whereClauses.push(`created_at >= ${sqlLiteral(options.startDate)}::timestamptz`);
2967
+ }
2968
+ if (options.endDate) {
2969
+ whereClauses.push(`created_at <= ${sqlLiteral(options.endDate)}::timestamptz`);
163
2970
  }
164
- trajectory.endTime = Date.now();
165
- trajectory.durationMs = trajectory.endTime - trajectory.startTime;
166
- trajectory.metrics.finalStatus = status;
167
- trajectory.metrics.episodeLength = trajectory.steps.length;
168
- if (finalMetrics) {
169
- trajectory.metrics = {
170
- ...trajectory.metrics,
171
- ...finalMetrics
2971
+ if (options.scenarioId) {
2972
+ whereClauses.push(`scenario_id = ${sqlLiteral(options.scenarioId)}`);
2973
+ }
2974
+ if (options.batchId) {
2975
+ whereClauses.push(`batch_id = ${sqlLiteral(options.batchId)}`);
2976
+ }
2977
+ const whereClause = whereClauses.length > 0 ? `WHERE ${whereClauses.join(" AND ")}` : "";
2978
+ const result = await this.executeRawSql(`SELECT * FROM trajectories ${whereClause} ORDER BY created_at DESC`);
2979
+ const trajectories = result.rows.map((row) => this.rowToTrajectory(row));
2980
+ const timestamp = new Date().toISOString().replace(/[:.]/g, "-");
2981
+ if (options.format === "csv") {
2982
+ const lines = [
2983
+ "id,agent_id,source,status,start_time,end_time,duration_ms,step_count,llm_call_count,total_reward,scenario_id"
2984
+ ];
2985
+ for (const t of trajectories) {
2986
+ lines.push([
2987
+ t.trajectoryId,
2988
+ t.agentId,
2989
+ t.metadata.source ?? "chat",
2990
+ t.metrics.finalStatus,
2991
+ t.startTime,
2992
+ t.endTime,
2993
+ t.durationMs,
2994
+ t.steps.length,
2995
+ t.steps.reduce((sum2, s) => sum2 + s.llmCalls.length, 0),
2996
+ t.totalReward,
2997
+ t.scenarioId ?? ""
2998
+ ].join(","));
2999
+ }
3000
+ return {
3001
+ data: lines.join(`
3002
+ `),
3003
+ filename: `trajectories-${timestamp}.csv`,
3004
+ mimeType: "text/csv"
172
3005
  };
173
3006
  }
174
- this.activeStepIds.delete(trajectoryId);
175
- }
176
- getActiveTrajectory(trajectoryId) {
177
- return this.activeTrajectories.get(trajectoryId) || null;
3007
+ let exportData = trajectories;
3008
+ if (!options.includePrompts) {
3009
+ exportData = trajectories.map((trajectory) => this.redactTrajectoryPrompts(trajectory));
3010
+ }
3011
+ return {
3012
+ data: JSON.stringify(exportData, null, 2),
3013
+ filename: `trajectories-${timestamp}.json`,
3014
+ mimeType: "application/json"
3015
+ };
178
3016
  }
179
- findTrajectoryByStepId(stepId) {
180
- for (const trajectory of this.activeTrajectories.values()) {
181
- if (trajectory.steps.some((s) => s.stepId === stepId)) {
182
- return trajectory;
3017
+ rowToTrajectory(row) {
3018
+ const parseJson = (cell, fallback) => {
3019
+ if (typeof cell === "string") {
3020
+ try {
3021
+ return JSON.parse(cell);
3022
+ } catch {
3023
+ return fallback;
3024
+ }
183
3025
  }
184
- }
3026
+ if (typeof cell === "object" && cell !== null && !Array.isArray(cell)) {
3027
+ return cell;
3028
+ }
3029
+ return fallback;
3030
+ };
3031
+ return {
3032
+ trajectoryId: asString(pickCell(row, "id")) ?? "",
3033
+ agentId: asString(pickCell(row, "agent_id")) ?? "",
3034
+ startTime: asNumber(pickCell(row, "start_time")) ?? 0,
3035
+ endTime: asNumber(pickCell(row, "end_time")) ?? 0,
3036
+ durationMs: asNumber(pickCell(row, "duration_ms")) ?? 0,
3037
+ scenarioId: asString(pickCell(row, "scenario_id")) ?? undefined,
3038
+ episodeId: asString(pickCell(row, "episode_id")) ?? undefined,
3039
+ batchId: asString(pickCell(row, "batch_id")) ?? undefined,
3040
+ groupIndex: asNumber(pickCell(row, "group_index")) ?? undefined,
3041
+ steps: parseJson(pickCell(row, "steps_json", "steps"), []),
3042
+ totalReward: asNumber(pickCell(row, "total_reward")) ?? 0,
3043
+ rewardComponents: parseJson(pickCell(row, "reward_components_json", "reward_components"), { environmentReward: 0 }),
3044
+ metrics: parseJson(pickCell(row, "metrics_json", "metrics"), {
3045
+ episodeLength: 0,
3046
+ finalStatus: "completed"
3047
+ }),
3048
+ metadata: parseJson(pickCell(row, "metadata_json", "metadata"), {})
3049
+ };
3050
+ }
3051
+ getActiveTrajectory(trajectoryId) {
185
3052
  return null;
186
3053
  }
3054
+ getCurrentStepId(trajectoryId) {
3055
+ return this.activeStepIds.get(trajectoryId) || null;
3056
+ }
3057
+ getProviderAccessLogs() {
3058
+ return [];
3059
+ }
3060
+ getLlmCallLogs() {
3061
+ return [];
3062
+ }
187
3063
  }
188
-
189
3064
  // action-interceptor.ts
190
- import { logger as logger2 } from "@elizaos/core";
3065
+ import { logger as logger3 } from "@elizaos/core";
191
3066
  var trajectoryContexts = new WeakMap;
192
3067
  function setTrajectoryContext(runtime, trajectoryId, trajectoryLogger) {
193
3068
  trajectoryContexts.set(runtime, { trajectoryId, logger: trajectoryLogger });
@@ -211,7 +3086,7 @@ function wrapActionWithLogging(action, _trajectoryLogger) {
211
3086
  const { trajectoryId, logger: loggerService } = context;
212
3087
  const stepId = loggerService.getCurrentStepId(trajectoryId);
213
3088
  if (!stepId) {
214
- logger2.warn({ action: action.name, trajectoryId }, "No active step for action execution");
3089
+ logger3.warn({ action: action.name, trajectoryId }, "No active step for action execution");
215
3090
  const result = await originalHandler(runtime, message, state, options, callback);
216
3091
  return result ?? undefined;
217
3092
  }
@@ -231,7 +3106,7 @@ function wrapActionWithLogging(action, _trajectoryLogger) {
231
3106
  };
232
3107
  const errorHandler = (err) => {
233
3108
  const error = err instanceof Error ? err.message : typeof err === "string" ? err : err.message || String(err);
234
- logger2.error({ action: action.name, trajectoryId, error }, "Action execution failed");
3109
+ logger3.error({ action: action.name, trajectoryId, error }, "Action execution failed");
235
3110
  const stateSnapshot = state ? JSON.parse(JSON.stringify(state)) : null;
236
3111
  loggerService.completeStep(trajectoryId, stepId, {
237
3112
  actionType: action.name,
@@ -274,7 +3149,7 @@ function wrapPluginActions(plugin, trajectoryLogger) {
274
3149
  function logLLMCallFromAction(actionContext, trajectoryLogger, trajectoryId) {
275
3150
  const stepId = trajectoryLogger.getCurrentStepId(trajectoryId);
276
3151
  if (!stepId) {
277
- logger2.warn({ trajectoryId }, "No active step for LLM call from action");
3152
+ logger3.warn({ trajectoryId }, "No active step for LLM call from action");
278
3153
  return;
279
3154
  }
280
3155
  trajectoryLogger.logLLMCall(stepId, {
@@ -295,7 +3170,7 @@ function logLLMCallFromAction(actionContext, trajectoryLogger, trajectoryId) {
295
3170
  function logProviderFromAction(actionContext, trajectoryLogger, trajectoryId) {
296
3171
  const stepId = trajectoryLogger.getCurrentStepId(trajectoryId);
297
3172
  if (!stepId) {
298
- logger2.warn({ trajectoryId }, "No active step for provider access from action");
3173
+ logger3.warn({ trajectoryId }, "No active step for provider access from action");
299
3174
  return;
300
3175
  }
301
3176
  trajectoryLogger.logProviderAccess(stepId, {
@@ -317,7 +3192,7 @@ function wrapProviderWithLogging(provider, _trajectoryLogger) {
317
3192
  const { trajectoryId, logger: loggerService } = context;
318
3193
  const stepId = loggerService.getCurrentStepId(trajectoryId);
319
3194
  if (!stepId) {
320
- logger2.warn({ provider: provider.name, trajectoryId }, "No active step for provider access");
3195
+ logger3.warn({ provider: provider.name, trajectoryId }, "No active step for provider access");
321
3196
  return originalGet?.(runtime, message, state) || { text: "" };
322
3197
  }
323
3198
  const result = await originalGet?.(runtime, message, state) || { text: "" };
@@ -519,14 +3394,14 @@ function toARTJSONL(trajectory) {
519
3394
  return JSON.stringify(toARTTrajectory(trajectory));
520
3395
  }
521
3396
  function validateARTCompatibility(trajectory) {
522
- const errors = [];
3397
+ const errors2 = [];
523
3398
  const warnings = [];
524
3399
  if (trajectory.steps.length === 0) {
525
- errors.push("Trajectory has no steps");
3400
+ errors2.push("Trajectory has no steps");
526
3401
  }
527
3402
  for (const [idx, step] of trajectory.steps.entries()) {
528
3403
  if (step.llmCalls.length === 0) {
529
- errors.push(`Step ${idx} has no LLM calls - can't extract messages`);
3404
+ errors2.push(`Step ${idx} has no LLM calls - can't extract messages`);
530
3405
  }
531
3406
  for (const llmCall of step.llmCalls) {
532
3407
  if (!llmCall.userPrompt || llmCall.userPrompt.length < 10) {
@@ -538,15 +3413,15 @@ function validateARTCompatibility(trajectory) {
538
3413
  }
539
3414
  }
540
3415
  if (trajectory.totalReward === undefined || Number.isNaN(trajectory.totalReward)) {
541
- errors.push("Trajectory has no valid reward");
3416
+ errors2.push("Trajectory has no valid reward");
542
3417
  }
543
3418
  const artTraj = toARTTrajectory(trajectory);
544
3419
  if (artTraj.messages.length < 2) {
545
3420
  warnings.push("Trajectory converts to very few messages (< 2)");
546
3421
  }
547
3422
  return {
548
- valid: errors.length === 0,
549
- errors,
3423
+ valid: errors2.length === 0,
3424
+ errors: errors2,
550
3425
  warnings
551
3426
  };
552
3427
  }
@@ -642,9 +3517,9 @@ async function buildGameStateFromDB(_trajectoryId) {
642
3517
  }
643
3518
  async function recomputeTrajectoryRewards(_trajectoryIds) {}
644
3519
  // integration.ts
645
- import { logger as logger3 } from "@elizaos/core";
646
- function startAutonomousTick(trajectoryLogger, context) {
647
- const trajectoryId = trajectoryLogger.startTrajectory(context.agentId, {
3520
+ import { logger as logger4 } from "@elizaos/core";
3521
+ async function startAutonomousTick(trajectoryLogger, context) {
3522
+ const trajectoryId = await trajectoryLogger.startTrajectory(context.agentId, {
648
3523
  scenarioId: context.scenarioId,
649
3524
  episodeId: context.episodeId,
650
3525
  batchId: context.batchId,
@@ -658,17 +3533,17 @@ function startAutonomousTick(trajectoryLogger, context) {
658
3533
  openPositions: 0
659
3534
  };
660
3535
  trajectoryLogger.startStep(trajectoryId, envState);
661
- logger3.info({ trajectoryId, agentId: context.agentId }, "Started autonomous tick trajectory");
3536
+ logger4.info({ trajectoryId, agentId: context.agentId }, "Started autonomous tick trajectory");
662
3537
  return trajectoryId;
663
3538
  }
664
3539
  async function endAutonomousTick(trajectoryLogger, trajectoryId, status = "completed", finalMetrics) {
665
3540
  await trajectoryLogger.endTrajectory(trajectoryId, status, finalMetrics);
666
- logger3.info({ trajectoryId, status }, "Ended autonomous tick trajectory");
3541
+ logger4.info({ trajectoryId, status }, "Ended autonomous tick trajectory");
667
3542
  }
668
3543
  async function loggedLLMCall(trajectoryLogger, trajectoryId, options, llmCallFn) {
669
3544
  const stepId = trajectoryLogger.getCurrentStepId(trajectoryId);
670
3545
  if (!stepId) {
671
- logger3.warn({ trajectoryId }, "No active step for LLM call");
3546
+ logger4.warn({ trajectoryId }, "No active step for LLM call");
672
3547
  const result2 = await llmCallFn();
673
3548
  return result2.text;
674
3549
  }
@@ -773,13 +3648,13 @@ class RewardService {
773
3648
  return (score + 1) / 2;
774
3649
  }
775
3650
  normalizeScoresForGroup(scores) {
776
- const min = Math.min(...scores);
777
- const max = Math.max(...scores);
778
- const range = max - min;
3651
+ const min2 = Math.min(...scores);
3652
+ const max2 = Math.max(...scores);
3653
+ const range = max2 - min2;
779
3654
  if (range === 0) {
780
3655
  return scores.map(() => 0.5);
781
3656
  }
782
- return scores.map((s) => (s - min) / range);
3657
+ return scores.map((s) => (s - min2) / range);
783
3658
  }
784
3659
  }
785
3660
  function createRewardService(options = {}) {
@@ -809,16 +3684,18 @@ var trajectoryLoggerPlugin = {
809
3684
  if (!message || !runtime)
810
3685
  return;
811
3686
  if (!message.metadata) {
812
- message.metadata = { type: "message" };
3687
+ message.metadata = {
3688
+ type: "message"
3689
+ };
813
3690
  }
814
3691
  const meta = message.metadata;
815
- const logger4 = runtime.getService("trajectory_logger");
816
- if (!logger4)
3692
+ const logger5 = runtime.getService("trajectory_logger");
3693
+ if (!logger5)
817
3694
  return;
818
3695
  let trajectoryStepId = crypto.randomUUID();
819
3696
  meta.trajectoryStepId = trajectoryStepId;
820
3697
  try {
821
- const trajectoryId = await logger4.startTrajectory(runtime.agentId, {
3698
+ const trajectoryId = await logger5.startTrajectory(runtime.agentId, {
822
3699
  source: source ?? meta.source ?? "chat",
823
3700
  metadata: {
824
3701
  roomId: message.roomId,
@@ -830,7 +3707,7 @@ var trajectoryLoggerPlugin = {
830
3707
  });
831
3708
  const normalizedTrajectoryId = typeof trajectoryId === "string" && trajectoryId.trim().length > 0 ? trajectoryId : null;
832
3709
  if (normalizedTrajectoryId) {
833
- const runtimeStepId = logger4.startStep(normalizedTrajectoryId, {
3710
+ const runtimeStepId = logger5.startStep(normalizedTrajectoryId, {
834
3711
  timestamp: Date.now(),
835
3712
  agentBalance: 0,
836
3713
  agentPoints: 0,
@@ -841,13 +3718,17 @@ var trajectoryLoggerPlugin = {
841
3718
  trajectoryStepId = normalizedStepId;
842
3719
  meta.trajectoryStepId = trajectoryStepId;
843
3720
  pendingTrajectoryEndTargetByStepId.set(trajectoryStepId, normalizedTrajectoryId);
844
- }
3721
+ } else {}
845
3722
  if (message.id) {
846
3723
  const replyId = createUniqueUuid(runtime, message.id);
847
3724
  pendingTrajectoryStepByReplyId.set(replyId, trajectoryStepId);
848
3725
  }
849
3726
  } catch (err) {
850
- runtime.logger?.warn({ err, src: "plugin-trajectory-logger", roomId: message.roomId }, "Failed to start trajectory logging");
3727
+ runtime.logger?.warn({
3728
+ err,
3729
+ src: "plugin-trajectory-logger",
3730
+ roomId: message.roomId
3731
+ }, "Failed to start trajectory logging");
851
3732
  }
852
3733
  }
853
3734
  ],
@@ -864,14 +3745,18 @@ var trajectoryLoggerPlugin = {
864
3745
  }
865
3746
  if (!trajectoryStepId)
866
3747
  return;
867
- const logger4 = runtime.getService("trajectory_logger");
868
- if (!logger4)
3748
+ const logger5 = runtime.getService("trajectory_logger");
3749
+ if (!logger5)
869
3750
  return;
870
3751
  try {
871
3752
  const endTarget = pendingTrajectoryEndTargetByStepId.get(trajectoryStepId) ?? trajectoryStepId;
872
- await logger4.endTrajectory(endTarget, "completed");
3753
+ await logger5.endTrajectory(endTarget, "completed");
873
3754
  } catch (err) {
874
- runtime.logger?.warn({ err, src: "plugin-trajectory-logger", trajectoryStepId }, "Failed to end trajectory logging");
3755
+ runtime.logger?.warn({
3756
+ err,
3757
+ src: "plugin-trajectory-logger",
3758
+ trajectoryStepId
3759
+ }, "Failed to end trajectory logging");
875
3760
  }
876
3761
  if (inReplyTo) {
877
3762
  pendingTrajectoryStepByReplyId.delete(inReplyTo);
@@ -922,4 +3807,4 @@ export {
922
3807
  RewardService
923
3808
  };
924
3809
 
925
- //# debugId=F0E0006C38150F8464756E2164756E21
3810
+ //# debugId=621E07B14B9A695B64756E2164756E21