@elizaos/plugin-sql 1.6.5-alpha.9 → 1.6.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. package/dist/browser/index.browser.js +1907 -436
  2. package/dist/browser/index.browser.js.map +26 -23
  3. package/dist/browser/tsconfig.build.tsbuildinfo +1 -1
  4. package/dist/node/index.d.ts +2 -2
  5. package/dist/node/index.node.js +1436 -662
  6. package/dist/node/index.node.js.map +33 -31
  7. package/dist/node/tsconfig.build.node.tsbuildinfo +1 -1
  8. package/package.json +17 -14
  9. package/dist/browser/base.d.ts +0 -926
  10. package/dist/browser/index.browser.d.ts +0 -11
  11. package/dist/browser/migration-service.d.ts +0 -43
  12. package/dist/browser/pglite/adapter.d.ts +0 -68
  13. package/dist/browser/pglite/manager.d.ts +0 -21
  14. package/dist/browser/runtime-migrator/drizzle-adapters/database-introspector.d.ts +0 -62
  15. package/dist/browser/runtime-migrator/drizzle-adapters/diff-calculator.d.ts +0 -59
  16. package/dist/browser/runtime-migrator/drizzle-adapters/snapshot-generator.d.ts +0 -18
  17. package/dist/browser/runtime-migrator/drizzle-adapters/sql-generator.d.ts +0 -38
  18. package/dist/browser/runtime-migrator/extension-manager.d.ts +0 -6
  19. package/dist/browser/runtime-migrator/index.d.ts +0 -8
  20. package/dist/browser/runtime-migrator/runtime-migrator.d.ts +0 -96
  21. package/dist/browser/runtime-migrator/schema-transformer.d.ts +0 -16
  22. package/dist/browser/runtime-migrator/storage/journal-storage.d.ts +0 -10
  23. package/dist/browser/runtime-migrator/storage/migration-tracker.d.ts +0 -13
  24. package/dist/browser/runtime-migrator/storage/snapshot-storage.d.ts +0 -9
  25. package/dist/browser/runtime-migrator/types.d.ts +0 -48
  26. package/dist/browser/schema/agent.d.ts +0 -344
  27. package/dist/browser/schema/cache.d.ts +0 -97
  28. package/dist/browser/schema/channel.d.ts +0 -177
  29. package/dist/browser/schema/channelParticipant.d.ts +0 -41
  30. package/dist/browser/schema/component.d.ts +0 -163
  31. package/dist/browser/schema/embedding.d.ts +0 -193
  32. package/dist/browser/schema/entity.d.ts +0 -122
  33. package/dist/browser/schema/index.d.ts +0 -18
  34. package/dist/browser/schema/log.d.ts +0 -114
  35. package/dist/browser/schema/memory.d.ts +0 -188
  36. package/dist/browser/schema/message.d.ts +0 -1
  37. package/dist/browser/schema/messageServer.d.ts +0 -126
  38. package/dist/browser/schema/owners.d.ts +0 -63
  39. package/dist/browser/schema/participant.d.ts +0 -114
  40. package/dist/browser/schema/relationship.d.ts +0 -156
  41. package/dist/browser/schema/room.d.ts +0 -192
  42. package/dist/browser/schema/serverAgent.d.ts +0 -41
  43. package/dist/browser/schema/tasks.d.ts +0 -225
  44. package/dist/browser/schema/types.d.ts +0 -68
  45. package/dist/browser/schema/world.d.ts +0 -114
  46. package/dist/browser/src/base.d.ts +0 -926
  47. package/dist/browser/src/index.browser.d.ts +0 -11
  48. package/dist/browser/src/migration-service.d.ts +0 -43
  49. package/dist/browser/src/pglite/adapter.d.ts +0 -68
  50. package/dist/browser/src/pglite/manager.d.ts +0 -21
  51. package/dist/browser/src/runtime-migrator/drizzle-adapters/database-introspector.d.ts +0 -62
  52. package/dist/browser/src/runtime-migrator/drizzle-adapters/diff-calculator.d.ts +0 -59
  53. package/dist/browser/src/runtime-migrator/drizzle-adapters/snapshot-generator.d.ts +0 -18
  54. package/dist/browser/src/runtime-migrator/drizzle-adapters/sql-generator.d.ts +0 -38
  55. package/dist/browser/src/runtime-migrator/extension-manager.d.ts +0 -6
  56. package/dist/browser/src/runtime-migrator/index.d.ts +0 -8
  57. package/dist/browser/src/runtime-migrator/runtime-migrator.d.ts +0 -96
  58. package/dist/browser/src/runtime-migrator/schema-transformer.d.ts +0 -16
  59. package/dist/browser/src/runtime-migrator/storage/journal-storage.d.ts +0 -10
  60. package/dist/browser/src/runtime-migrator/storage/migration-tracker.d.ts +0 -13
  61. package/dist/browser/src/runtime-migrator/storage/snapshot-storage.d.ts +0 -9
  62. package/dist/browser/src/runtime-migrator/types.d.ts +0 -48
  63. package/dist/browser/src/schema/agent.d.ts +0 -344
  64. package/dist/browser/src/schema/cache.d.ts +0 -97
  65. package/dist/browser/src/schema/channel.d.ts +0 -177
  66. package/dist/browser/src/schema/channelParticipant.d.ts +0 -41
  67. package/dist/browser/src/schema/component.d.ts +0 -163
  68. package/dist/browser/src/schema/embedding.d.ts +0 -193
  69. package/dist/browser/src/schema/entity.d.ts +0 -122
  70. package/dist/browser/src/schema/index.d.ts +0 -18
  71. package/dist/browser/src/schema/log.d.ts +0 -114
  72. package/dist/browser/src/schema/memory.d.ts +0 -188
  73. package/dist/browser/src/schema/message.d.ts +0 -1
  74. package/dist/browser/src/schema/messageServer.d.ts +0 -126
  75. package/dist/browser/src/schema/owners.d.ts +0 -63
  76. package/dist/browser/src/schema/participant.d.ts +0 -114
  77. package/dist/browser/src/schema/relationship.d.ts +0 -156
  78. package/dist/browser/src/schema/room.d.ts +0 -192
  79. package/dist/browser/src/schema/serverAgent.d.ts +0 -41
  80. package/dist/browser/src/schema/tasks.d.ts +0 -225
  81. package/dist/browser/src/schema/types.d.ts +0 -68
  82. package/dist/browser/src/schema/world.d.ts +0 -114
  83. package/dist/browser/src/types.d.ts +0 -15
  84. package/dist/browser/src/utils.browser.d.ts +0 -21
  85. package/dist/browser/types.d.ts +0 -15
  86. package/dist/browser/utils.browser.d.ts +0 -21
  87. package/dist/node/src/base.d.ts +0 -926
  88. package/dist/node/src/index.d.ts +0 -33
  89. package/dist/node/src/index.node.d.ts +0 -10
  90. package/dist/node/src/migration-service.d.ts +0 -43
  91. package/dist/node/src/pg/adapter.d.ts +0 -69
  92. package/dist/node/src/pg/manager.d.ts +0 -17
  93. package/dist/node/src/pglite/adapter.d.ts +0 -68
  94. package/dist/node/src/pglite/manager.d.ts +0 -21
  95. package/dist/node/src/rls.d.ts +0 -43
  96. package/dist/node/src/runtime-migrator/drizzle-adapters/database-introspector.d.ts +0 -62
  97. package/dist/node/src/runtime-migrator/drizzle-adapters/diff-calculator.d.ts +0 -59
  98. package/dist/node/src/runtime-migrator/drizzle-adapters/snapshot-generator.d.ts +0 -18
  99. package/dist/node/src/runtime-migrator/drizzle-adapters/sql-generator.d.ts +0 -38
  100. package/dist/node/src/runtime-migrator/extension-manager.d.ts +0 -6
  101. package/dist/node/src/runtime-migrator/index.d.ts +0 -8
  102. package/dist/node/src/runtime-migrator/runtime-migrator.d.ts +0 -96
  103. package/dist/node/src/runtime-migrator/schema-transformer.d.ts +0 -16
  104. package/dist/node/src/runtime-migrator/storage/journal-storage.d.ts +0 -10
  105. package/dist/node/src/runtime-migrator/storage/migration-tracker.d.ts +0 -13
  106. package/dist/node/src/runtime-migrator/storage/snapshot-storage.d.ts +0 -9
  107. package/dist/node/src/runtime-migrator/types.d.ts +0 -48
  108. package/dist/node/src/schema/agent.d.ts +0 -344
  109. package/dist/node/src/schema/cache.d.ts +0 -97
  110. package/dist/node/src/schema/channel.d.ts +0 -177
  111. package/dist/node/src/schema/channelParticipant.d.ts +0 -41
  112. package/dist/node/src/schema/component.d.ts +0 -163
  113. package/dist/node/src/schema/embedding.d.ts +0 -193
  114. package/dist/node/src/schema/entity.d.ts +0 -122
  115. package/dist/node/src/schema/index.d.ts +0 -18
  116. package/dist/node/src/schema/log.d.ts +0 -114
  117. package/dist/node/src/schema/memory.d.ts +0 -188
  118. package/dist/node/src/schema/message.d.ts +0 -1
  119. package/dist/node/src/schema/messageServer.d.ts +0 -126
  120. package/dist/node/src/schema/owners.d.ts +0 -63
  121. package/dist/node/src/schema/participant.d.ts +0 -114
  122. package/dist/node/src/schema/relationship.d.ts +0 -156
  123. package/dist/node/src/schema/room.d.ts +0 -192
  124. package/dist/node/src/schema/serverAgent.d.ts +0 -41
  125. package/dist/node/src/schema/tasks.d.ts +0 -225
  126. package/dist/node/src/schema/types.d.ts +0 -68
  127. package/dist/node/src/schema/world.d.ts +0 -114
  128. package/dist/node/src/types.d.ts +0 -15
  129. package/dist/node/src/utils.d.ts +0 -32
  130. package/dist/node/src/utils.node.d.ts +0 -6
@@ -35,6 +35,44 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
35
35
  throw Error('Dynamic require of "' + x + '" is not supported');
36
36
  });
37
37
 
38
+ // src/schema/agent.ts
39
+ import { sql } from "drizzle-orm";
40
+ import { boolean, jsonb, pgTable, text, timestamp, uuid } from "drizzle-orm/pg-core";
41
+ var agentTable;
42
+ var init_agent = __esm(() => {
43
+ agentTable = pgTable("agents", {
44
+ id: uuid("id").primaryKey().defaultRandom(),
45
+ enabled: boolean("enabled").default(true).notNull(),
46
+ server_id: uuid("server_id"),
47
+ createdAt: timestamp("created_at", { withTimezone: true }).default(sql`now()`).notNull(),
48
+ updatedAt: timestamp("updated_at", { withTimezone: true }).default(sql`now()`).notNull(),
49
+ name: text("name").notNull(),
50
+ username: text("username"),
51
+ system: text("system").default(""),
52
+ bio: jsonb("bio").$type().default(sql`'[]'::jsonb`),
53
+ messageExamples: jsonb("message_examples").$type().default(sql`'[]'::jsonb`).notNull(),
54
+ postExamples: jsonb("post_examples").$type().default(sql`'[]'::jsonb`).notNull(),
55
+ topics: jsonb("topics").$type().default(sql`'[]'::jsonb`).notNull(),
56
+ adjectives: jsonb("adjectives").$type().default(sql`'[]'::jsonb`).notNull(),
57
+ knowledge: jsonb("knowledge").$type().default(sql`'[]'::jsonb`).notNull(),
58
+ plugins: jsonb("plugins").$type().default(sql`'[]'::jsonb`).notNull(),
59
+ settings: jsonb("settings").$type().default(sql`'{}'::jsonb`).notNull(),
60
+ style: jsonb("style").$type().default(sql`'{}'::jsonb`).notNull()
61
+ });
62
+ });
63
+
64
+ // src/schema/server.ts
65
+ import { sql as sql10 } from "drizzle-orm";
66
+ import { pgTable as pgTable10, timestamp as timestamp10, uuid as uuid10 } from "drizzle-orm/pg-core";
67
+ var serverTable;
68
+ var init_server = __esm(() => {
69
+ serverTable = pgTable10("servers", {
70
+ id: uuid10("id").primaryKey(),
71
+ createdAt: timestamp10("created_at", { withTimezone: true }).default(sql10`now()`).notNull(),
72
+ updatedAt: timestamp10("updated_at", { withTimezone: true }).default(sql10`now()`).notNull()
73
+ });
74
+ });
75
+
38
76
  // src/runtime-migrator/storage/migration-tracker.ts
39
77
  import { sql as sql17 } from "drizzle-orm";
40
78
 
@@ -213,14 +251,14 @@ class ExtensionManager {
213
251
  for (const extension of extensions) {
214
252
  try {
215
253
  if (!/^[a-zA-Z0-9_-]+$/.test(extension)) {
216
- logger.warn(`[RuntimeMigrator] Invalid extension name "${extension}" - contains invalid characters`);
254
+ logger.warn({ src: "plugin:sql", extension }, "Invalid extension name - contains invalid characters");
217
255
  continue;
218
256
  }
219
257
  await this.db.execute(sql20`CREATE EXTENSION IF NOT EXISTS ${sql20.identifier(extension)}`);
220
- logger.debug(`[RuntimeMigrator] Extension installed: ${extension}`);
258
+ logger.debug({ src: "plugin:sql", extension }, "Extension installed");
221
259
  } catch (error) {
222
260
  const errorMessage = error instanceof Error ? error.message : String(error);
223
- logger.warn(`[RuntimeMigrator] Could not install extension ${extension}: ${errorMessage}`);
261
+ logger.warn({ src: "plugin:sql", extension, error: errorMessage }, "Could not install extension");
224
262
  }
225
263
  }
226
264
  }
@@ -2351,7 +2389,7 @@ var require_stream = __commonJS((exports, module) => {
2351
2389
  var __commonJS2 = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
2352
2390
  var require_primordials = __commonJS2((exports2, module2) => {
2353
2391
 
2354
- class AggregateError extends Error {
2392
+ class AggregateError2 extends Error {
2355
2393
  constructor(errors) {
2356
2394
  if (!Array.isArray(errors))
2357
2395
  throw TypeError(`Expected input to be an Array, got ${typeof errors}`);
@@ -2363,7 +2401,7 @@ var require_stream = __commonJS((exports, module) => {
2363
2401
  this.name = "AggregateError", this.errors = errors;
2364
2402
  }
2365
2403
  }
2366
- module2.exports = { AggregateError, ArrayIsArray(self2) {
2404
+ module2.exports = { AggregateError: AggregateError2, ArrayIsArray(self2) {
2367
2405
  return Array.isArray(self2);
2368
2406
  }, ArrayPrototypeIncludes(self2, el) {
2369
2407
  return self2.includes(el);
@@ -2455,7 +2493,7 @@ var require_stream = __commonJS((exports, module) => {
2455
2493
  } };
2456
2494
  });
2457
2495
  var require_errors = __commonJS2((exports2, module2) => {
2458
- var { format: format2, inspect: inspect2 } = require_inspect(), { AggregateError: CustomAggregateError } = require_primordials(), AggregateError = globalThis.AggregateError || CustomAggregateError, kIsNodeError = Symbol("kIsNodeError"), kTypes = ["string", "function", "number", "object", "Function", "Object", "boolean", "bigint", "symbol"], classRegExp = /^([A-Z][a-z0-9]*)+$/, codes = {};
2496
+ var { format: format2, inspect: inspect2 } = require_inspect(), { AggregateError: CustomAggregateError } = require_primordials(), AggregateError2 = globalThis.AggregateError || CustomAggregateError, kIsNodeError = Symbol("kIsNodeError"), kTypes = ["string", "function", "number", "object", "Function", "Object", "boolean", "bigint", "symbol"], classRegExp = /^([A-Z][a-z0-9]*)+$/, codes = {};
2459
2497
  function assert(value, message) {
2460
2498
  if (!value)
2461
2499
  throw new codes.ERR_INTERNAL_ASSERTION(message);
@@ -2498,7 +2536,7 @@ var require_stream = __commonJS((exports, module) => {
2498
2536
  if (innerError && outerError && innerError !== outerError) {
2499
2537
  if (Array.isArray(outerError.errors))
2500
2538
  return outerError.errors.push(innerError), outerError;
2501
- let err = new AggregateError([outerError, innerError], outerError.message);
2539
+ let err = new AggregateError2([outerError, innerError], outerError.message);
2502
2540
  return err.code = outerError.code, err;
2503
2541
  }
2504
2542
  return innerError || outerError;
@@ -3007,7 +3045,7 @@ var require_stream = __commonJS((exports, module) => {
3007
3045
  module2.exports.AbortSignal = AbortSignal;
3008
3046
  });
3009
3047
  var require_util = __commonJS2((exports2, module2) => {
3010
- var bufferModule = (init_buffer(), __toCommonJS(exports_buffer)), { format: format2, inspect: inspect2 } = require_inspect(), { codes: { ERR_INVALID_ARG_TYPE: ERR_INVALID_ARG_TYPE3 } } = require_errors(), { kResistStopPropagation, AggregateError, SymbolDispose } = require_primordials(), AbortSignal = globalThis.AbortSignal || require_abort_controller().AbortSignal, AbortController = globalThis.AbortController || require_abort_controller().AbortController, AsyncFunction = Object.getPrototypeOf(async function() {}).constructor, Blob2 = globalThis.Blob || bufferModule.Blob, isBlob = typeof Blob2 < "u" ? function(b) {
3048
+ var bufferModule = (init_buffer(), __toCommonJS(exports_buffer)), { format: format2, inspect: inspect2 } = require_inspect(), { codes: { ERR_INVALID_ARG_TYPE: ERR_INVALID_ARG_TYPE3 } } = require_errors(), { kResistStopPropagation, AggregateError: AggregateError2, SymbolDispose } = require_primordials(), AbortSignal = globalThis.AbortSignal || require_abort_controller().AbortSignal, AbortController = globalThis.AbortController || require_abort_controller().AbortController, AsyncFunction = Object.getPrototypeOf(async function() {}).constructor, Blob2 = globalThis.Blob || bufferModule.Blob, isBlob = typeof Blob2 < "u" ? function(b) {
3011
3049
  return b instanceof Blob2;
3012
3050
  } : function(b) {
3013
3051
  return false;
@@ -3018,7 +3056,7 @@ var require_stream = __commonJS((exports, module) => {
3018
3056
  if (typeof value !== "function")
3019
3057
  throw new ERR_INVALID_ARG_TYPE3(name, "Function", value);
3020
3058
  };
3021
- module2.exports = { AggregateError, kEmptyObject: Object.freeze({}), once(callback) {
3059
+ module2.exports = { AggregateError: AggregateError2, kEmptyObject: Object.freeze({}), once(callback) {
3022
3060
  let called = false;
3023
3061
  return function(...args) {
3024
3062
  if (called)
@@ -6327,7 +6365,7 @@ var __create, __getProtoOf, __defProp2, __getOwnPropNames2, __hasOwnProp2, __toE
6327
6365
  if (!__hasOwnProp2.call(to, key))
6328
6366
  __defProp2(to, key, { get: () => mod[key], enumerable: true });
6329
6367
  return to;
6330
- }, __commonJS2 = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports), require_randombytes, require_create_hash, require_create_hmac, require_algorithms, require_precondition, require_default_encoding, require_safe_buffer, require_to_buffer, require_sync, require_async, require_pbkdf2, require_browserify_cipher, require_diffie_hellman, require_browserify_sign, require_package, require_bn, require_minimalistic_assert, require_utils, require_utils2, require_brorand, require_base, require_inherits_browser, require_inherits, require_short, require_mont, require_edwards, require_curve, require_utils3, require_common, require_common2, require_1, require_256, require_224, require_512, require_384, require_sha, require_ripemd, require_hmac, require_hash, require_secp256k1, require_curves, require_hmac_drbg, require_key, require_signature, require_ec, require_key2, require_signature2, require_eddsa, require_elliptic, require_bn2, require_browser, require_create_ecdh, require_bn3, require_api, require_reporter, require_buffer, require_node, require_base2, require_der, require_constants, require_der2, require_pem, require_decoders, require_der3, require_pem2, require_encoders, require_asn1, require_certificate, require_asn12, require_aesid, require_hash_base, require_md5, require_evp_bytestokey, require_browserify_aes, require_fixProc, require_parse_asn1, require_mgf, require_xor, require_bn4, require_withPublic, require_bn5, require_browserify_rsa, require_publicEncrypt, require_privateDecrypt, require_browser2, require_public_encrypt, require_browser3, require_randomfill, require_crypto_browserify, cryptoBrowserify, prng2, pseudoRandomBytes2, rng2, randomBytes2, Hash2, createHash2, Hmac2, createHmac2, getHashes2, pbkdf22, pbkdf2Sync2, Cipher2, createCipher2, Cipheriv2, createCipheriv2, Decipher2, createDecipher2, Decipheriv2, createDecipheriv2, getCiphers2, listCiphers2, DiffieHellmanGroup2, createDiffieHellmanGroup2, getDiffieHellman2, createDiffieHellman2, DiffieHellman2, createSign2, Sign2, createVerify2, Verify2, createECDH2, publicEncrypt2, privateEncrypt2, publicDecrypt2, privateDecrypt2, randomFill2, randomFillSync2, createCredentials2, constants2, DEFAULT_ENCODING = "buffer", getRandomValues2 = (array) => {
6368
+ }, __commonJS2 = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports), require_randombytes, require_create_hash, require_create_hmac, require_algorithms, require_precondition, require_default_encoding, require_safe_buffer, require_isarray, require_type, require_es_object_atoms, require_es_errors, require_eval, require_range, require_ref, require_syntax, require_uri, require_abs, require_floor, require_max, require_min, require_pow, require_round, require_isNaN, require_sign, require_gOPD, require_gopd, require_es_define_property, require_shams, require_has_symbols, require_Reflect_getPrototypeOf, require_Object_getPrototypeOf, require_implementation, require_function_bind, require_functionCall, require_functionApply, require_reflectApply, require_actualApply, require_call_bind_apply_helpers, require_get, require_get_proto, require_hasown, require_get_intrinsic, require_call_bound, require_is_callable, require_for_each, require_possible_typed_array_names, require_available_typed_arrays, require_define_data_property, require_has_property_descriptors, require_set_function_length, require_applyBind, require_call_bind, require_shams2, require_which_typed_array, require_is_typed_array, require_typed_array_buffer, require_to_buffer, require_to_buffer2, require_sync, require_async, require_pbkdf2, require_browserify_cipher, require_diffie_hellman, require_browserify_sign, require_package, require_bn, require_minimalistic_assert, require_utils, require_utils2, require_brorand, require_base, require_inherits_browser, require_inherits, require_short, require_mont, require_edwards, require_curve, require_utils3, require_common, require_common2, require_1, require_256, require_224, require_512, require_384, require_sha, require_ripemd, require_hmac, require_hash, require_secp256k1, require_curves, require_hmac_drbg, require_key, require_signature, require_ec, require_key2, require_signature2, require_eddsa, require_elliptic, require_bn2, require_browser, require_create_ecdh, require_bn3, require_api, require_reporter, require_buffer, require_node, require_base2, require_der, require_constants, require_der2, require_pem, require_decoders, require_der3, require_pem2, require_encoders, require_asn1, require_certificate, require_asn12, require_aesid, require_hash_base, require_md5, require_evp_bytestokey, require_browserify_aes, require_fixProc, require_parse_asn1, require_mgf, require_xor, require_bn4, require_withPublic, require_bn5, require_browserify_rsa, require_publicEncrypt, require_privateDecrypt, require_browser2, require_public_encrypt, require_browser3, require_randomfill, require_crypto_browserify, cryptoBrowserify, prng2, pseudoRandomBytes2, rng2, randomBytes2, Hash2, createHash2, Hmac2, createHmac2, getHashes2, pbkdf22, pbkdf2Sync2, Cipher2, createCipher2, Cipheriv2, createCipheriv2, Decipher2, createDecipher2, Decipheriv2, createDecipheriv2, getCiphers2, listCiphers2, DiffieHellmanGroup2, createDiffieHellmanGroup2, getDiffieHellman2, createDiffieHellman2, DiffieHellman2, createSign2, Sign2, createVerify2, Verify2, createECDH2, publicEncrypt2, privateEncrypt2, publicDecrypt2, privateDecrypt2, randomFill2, randomFillSync2, createCredentials2, constants2, DEFAULT_ENCODING = "buffer", getRandomValues2 = (array) => {
6331
6369
  return crypto.getRandomValues(array);
6332
6370
  }, randomUUID2 = () => {
6333
6371
  return crypto.randomUUID();
@@ -6349,11 +6387,11 @@ var init_crypto = __esm(() => {
6349
6387
  module.exports = { sha224WithRSAEncryption: { sign: "rsa", hash: "sha224", id: "302d300d06096086480165030402040500041c" }, "RSA-SHA224": { sign: "ecdsa/rsa", hash: "sha224", id: "302d300d06096086480165030402040500041c" }, sha256WithRSAEncryption: { sign: "rsa", hash: "sha256", id: "3031300d060960864801650304020105000420" }, "RSA-SHA256": { sign: "ecdsa/rsa", hash: "sha256", id: "3031300d060960864801650304020105000420" }, sha384WithRSAEncryption: { sign: "rsa", hash: "sha384", id: "3041300d060960864801650304020205000430" }, "RSA-SHA384": { sign: "ecdsa/rsa", hash: "sha384", id: "3041300d060960864801650304020205000430" }, sha512WithRSAEncryption: { sign: "rsa", hash: "sha512", id: "3051300d060960864801650304020305000440" }, "RSA-SHA512": { sign: "ecdsa/rsa", hash: "sha512", id: "3051300d060960864801650304020305000440" }, "RSA-SHA1": { sign: "rsa", hash: "sha1", id: "3021300906052b0e03021a05000414" }, "ecdsa-with-SHA1": { sign: "ecdsa", hash: "sha1", id: "" }, sha256: { sign: "ecdsa", hash: "sha256", id: "" }, sha224: { sign: "ecdsa", hash: "sha224", id: "" }, sha384: { sign: "ecdsa", hash: "sha384", id: "" }, sha512: { sign: "ecdsa", hash: "sha512", id: "" }, "DSA-SHA": { sign: "dsa", hash: "sha1", id: "" }, "DSA-SHA1": { sign: "dsa", hash: "sha1", id: "" }, DSA: { sign: "dsa", hash: "sha1", id: "" }, "DSA-WITH-SHA224": { sign: "dsa", hash: "sha224", id: "" }, "DSA-SHA224": { sign: "dsa", hash: "sha224", id: "" }, "DSA-WITH-SHA256": { sign: "dsa", hash: "sha256", id: "" }, "DSA-SHA256": { sign: "dsa", hash: "sha256", id: "" }, "DSA-WITH-SHA384": { sign: "dsa", hash: "sha384", id: "" }, "DSA-SHA384": { sign: "dsa", hash: "sha384", id: "" }, "DSA-WITH-SHA512": { sign: "dsa", hash: "sha512", id: "" }, "DSA-SHA512": { sign: "dsa", hash: "sha512", id: "" }, "DSA-RIPEMD160": { sign: "dsa", hash: "rmd160", id: "" }, ripemd160WithRSA: { sign: "rsa", hash: "rmd160", id: "3021300906052b2403020105000414" }, "RSA-RIPEMD160": { sign: "rsa", hash: "rmd160", id: "3021300906052b2403020105000414" }, md5WithRSAEncryption: { sign: "rsa", hash: "md5", id: "3020300c06082a864886f70d020505000410" }, "RSA-MD5": { sign: "rsa", hash: "md5", id: "3020300c06082a864886f70d020505000410" } };
6350
6388
  });
6351
6389
  require_precondition = __commonJS2((exports, module) => {
6352
- var MAX_ALLOC = Math.pow(2, 30) - 1;
6390
+ var $isFinite = isFinite, MAX_ALLOC = Math.pow(2, 30) - 1;
6353
6391
  module.exports = function(iterations, keylen) {
6354
6392
  if (typeof iterations !== "number")
6355
6393
  throw TypeError("Iterations not a number");
6356
- if (iterations < 0)
6394
+ if (iterations < 0 || !$isFinite(iterations))
6357
6395
  throw TypeError("Bad iterations");
6358
6396
  if (typeof keylen !== "number")
6359
6397
  throw TypeError("Key length not a number");
@@ -6417,31 +6455,706 @@ var init_crypto = __esm(() => {
6417
6455
  return buffer.SlowBuffer(size);
6418
6456
  };
6419
6457
  });
6458
+ require_isarray = __commonJS2((exports, module) => {
6459
+ var toString = {}.toString;
6460
+ module.exports = Array.isArray || function(arr) {
6461
+ return toString.call(arr) == "[object Array]";
6462
+ };
6463
+ });
6464
+ require_type = __commonJS2((exports, module) => {
6465
+ module.exports = TypeError;
6466
+ });
6467
+ require_es_object_atoms = __commonJS2((exports, module) => {
6468
+ module.exports = Object;
6469
+ });
6470
+ require_es_errors = __commonJS2((exports, module) => {
6471
+ module.exports = Error;
6472
+ });
6473
+ require_eval = __commonJS2((exports, module) => {
6474
+ module.exports = EvalError;
6475
+ });
6476
+ require_range = __commonJS2((exports, module) => {
6477
+ module.exports = RangeError;
6478
+ });
6479
+ require_ref = __commonJS2((exports, module) => {
6480
+ module.exports = ReferenceError;
6481
+ });
6482
+ require_syntax = __commonJS2((exports, module) => {
6483
+ module.exports = SyntaxError;
6484
+ });
6485
+ require_uri = __commonJS2((exports, module) => {
6486
+ module.exports = URIError;
6487
+ });
6488
+ require_abs = __commonJS2((exports, module) => {
6489
+ module.exports = Math.abs;
6490
+ });
6491
+ require_floor = __commonJS2((exports, module) => {
6492
+ module.exports = Math.floor;
6493
+ });
6494
+ require_max = __commonJS2((exports, module) => {
6495
+ module.exports = Math.max;
6496
+ });
6497
+ require_min = __commonJS2((exports, module) => {
6498
+ module.exports = Math.min;
6499
+ });
6500
+ require_pow = __commonJS2((exports, module) => {
6501
+ module.exports = Math.pow;
6502
+ });
6503
+ require_round = __commonJS2((exports, module) => {
6504
+ module.exports = Math.round;
6505
+ });
6506
+ require_isNaN = __commonJS2((exports, module) => {
6507
+ module.exports = Number.isNaN || function(a) {
6508
+ return a !== a;
6509
+ };
6510
+ });
6511
+ require_sign = __commonJS2((exports, module) => {
6512
+ var $isNaN = require_isNaN();
6513
+ module.exports = function(number) {
6514
+ if ($isNaN(number) || number === 0)
6515
+ return number;
6516
+ return number < 0 ? -1 : 1;
6517
+ };
6518
+ });
6519
+ require_gOPD = __commonJS2((exports, module) => {
6520
+ module.exports = Object.getOwnPropertyDescriptor;
6521
+ });
6522
+ require_gopd = __commonJS2((exports, module) => {
6523
+ var $gOPD = require_gOPD();
6524
+ if ($gOPD)
6525
+ try {
6526
+ $gOPD([], "length");
6527
+ } catch (e) {
6528
+ $gOPD = null;
6529
+ }
6530
+ module.exports = $gOPD;
6531
+ });
6532
+ require_es_define_property = __commonJS2((exports, module) => {
6533
+ var $defineProperty = Object.defineProperty || false;
6534
+ if ($defineProperty)
6535
+ try {
6536
+ $defineProperty({}, "a", { value: 1 });
6537
+ } catch (e) {
6538
+ $defineProperty = false;
6539
+ }
6540
+ module.exports = $defineProperty;
6541
+ });
6542
+ require_shams = __commonJS2((exports, module) => {
6543
+ module.exports = function() {
6544
+ if (typeof Symbol !== "function" || typeof Object.getOwnPropertySymbols !== "function")
6545
+ return false;
6546
+ if (typeof Symbol.iterator === "symbol")
6547
+ return true;
6548
+ var obj = {}, sym = Symbol("test"), symObj = Object(sym);
6549
+ if (typeof sym === "string")
6550
+ return false;
6551
+ if (Object.prototype.toString.call(sym) !== "[object Symbol]")
6552
+ return false;
6553
+ if (Object.prototype.toString.call(symObj) !== "[object Symbol]")
6554
+ return false;
6555
+ var symVal = 42;
6556
+ obj[sym] = symVal;
6557
+ for (var _ in obj)
6558
+ return false;
6559
+ if (typeof Object.keys === "function" && Object.keys(obj).length !== 0)
6560
+ return false;
6561
+ if (typeof Object.getOwnPropertyNames === "function" && Object.getOwnPropertyNames(obj).length !== 0)
6562
+ return false;
6563
+ var syms = Object.getOwnPropertySymbols(obj);
6564
+ if (syms.length !== 1 || syms[0] !== sym)
6565
+ return false;
6566
+ if (!Object.prototype.propertyIsEnumerable.call(obj, sym))
6567
+ return false;
6568
+ if (typeof Object.getOwnPropertyDescriptor === "function") {
6569
+ var descriptor = Object.getOwnPropertyDescriptor(obj, sym);
6570
+ if (descriptor.value !== symVal || descriptor.enumerable !== true)
6571
+ return false;
6572
+ }
6573
+ return true;
6574
+ };
6575
+ });
6576
+ require_has_symbols = __commonJS2((exports, module) => {
6577
+ var origSymbol = typeof Symbol < "u" && Symbol, hasSymbolSham = require_shams();
6578
+ module.exports = function() {
6579
+ if (typeof origSymbol !== "function")
6580
+ return false;
6581
+ if (typeof Symbol !== "function")
6582
+ return false;
6583
+ if (typeof origSymbol("foo") !== "symbol")
6584
+ return false;
6585
+ if (typeof Symbol("bar") !== "symbol")
6586
+ return false;
6587
+ return hasSymbolSham();
6588
+ };
6589
+ });
6590
+ require_Reflect_getPrototypeOf = __commonJS2((exports, module) => {
6591
+ module.exports = typeof Reflect < "u" && Reflect.getPrototypeOf || null;
6592
+ });
6593
+ require_Object_getPrototypeOf = __commonJS2((exports, module) => {
6594
+ var $Object = require_es_object_atoms();
6595
+ module.exports = $Object.getPrototypeOf || null;
6596
+ });
6597
+ require_implementation = __commonJS2((exports, module) => {
6598
+ var ERROR_MESSAGE = "Function.prototype.bind called on incompatible ", toStr = Object.prototype.toString, max = Math.max, funcType = "[object Function]", concatty = function(a, b) {
6599
+ var arr = [];
6600
+ for (var i2 = 0;i2 < a.length; i2 += 1)
6601
+ arr[i2] = a[i2];
6602
+ for (var j = 0;j < b.length; j += 1)
6603
+ arr[j + a.length] = b[j];
6604
+ return arr;
6605
+ }, slicy = function(arrLike, offset) {
6606
+ var arr = [];
6607
+ for (var i2 = offset || 0, j = 0;i2 < arrLike.length; i2 += 1, j += 1)
6608
+ arr[j] = arrLike[i2];
6609
+ return arr;
6610
+ }, joiny = function(arr, joiner) {
6611
+ var str = "";
6612
+ for (var i2 = 0;i2 < arr.length; i2 += 1)
6613
+ if (str += arr[i2], i2 + 1 < arr.length)
6614
+ str += joiner;
6615
+ return str;
6616
+ };
6617
+ module.exports = function(that) {
6618
+ var target = this;
6619
+ if (typeof target !== "function" || toStr.apply(target) !== funcType)
6620
+ throw TypeError(ERROR_MESSAGE + target);
6621
+ var args = slicy(arguments, 1), bound, binder = function() {
6622
+ if (this instanceof bound) {
6623
+ var result = target.apply(this, concatty(args, arguments));
6624
+ if (Object(result) === result)
6625
+ return result;
6626
+ return this;
6627
+ }
6628
+ return target.apply(that, concatty(args, arguments));
6629
+ }, boundLength = max(0, target.length - args.length), boundArgs = [];
6630
+ for (var i2 = 0;i2 < boundLength; i2++)
6631
+ boundArgs[i2] = "$" + i2;
6632
+ if (bound = Function("binder", "return function (" + joiny(boundArgs, ",") + "){ return binder.apply(this,arguments); }")(binder), target.prototype) {
6633
+ var Empty = function() {};
6634
+ Empty.prototype = target.prototype, bound.prototype = new Empty, Empty.prototype = null;
6635
+ }
6636
+ return bound;
6637
+ };
6638
+ });
6639
+ require_function_bind = __commonJS2((exports, module) => {
6640
+ var implementation = require_implementation();
6641
+ module.exports = Function.prototype.bind || implementation;
6642
+ });
6643
+ require_functionCall = __commonJS2((exports, module) => {
6644
+ module.exports = Function.prototype.call;
6645
+ });
6646
+ require_functionApply = __commonJS2((exports, module) => {
6647
+ module.exports = Function.prototype.apply;
6648
+ });
6649
+ require_reflectApply = __commonJS2((exports, module) => {
6650
+ module.exports = typeof Reflect < "u" && Reflect && Reflect.apply;
6651
+ });
6652
+ require_actualApply = __commonJS2((exports, module) => {
6653
+ var bind = require_function_bind(), $apply = require_functionApply(), $call = require_functionCall(), $reflectApply = require_reflectApply();
6654
+ module.exports = $reflectApply || bind.call($call, $apply);
6655
+ });
6656
+ require_call_bind_apply_helpers = __commonJS2((exports, module) => {
6657
+ var bind = require_function_bind(), $TypeError = require_type(), $call = require_functionCall(), $actualApply = require_actualApply();
6658
+ module.exports = function(args) {
6659
+ if (args.length < 1 || typeof args[0] !== "function")
6660
+ throw new $TypeError("a function is required");
6661
+ return $actualApply(bind, $call, args);
6662
+ };
6663
+ });
6664
+ require_get = __commonJS2((exports, module) => {
6665
+ var callBind = require_call_bind_apply_helpers(), gOPD = require_gopd(), hasProtoAccessor;
6666
+ try {
6667
+ hasProtoAccessor = [].__proto__ === Array.prototype;
6668
+ } catch (e) {
6669
+ if (!e || typeof e !== "object" || !("code" in e) || e.code !== "ERR_PROTO_ACCESS")
6670
+ throw e;
6671
+ }
6672
+ var desc = !!hasProtoAccessor && gOPD && gOPD(Object.prototype, "__proto__"), $Object = Object, $getPrototypeOf = $Object.getPrototypeOf;
6673
+ module.exports = desc && typeof desc.get === "function" ? callBind([desc.get]) : typeof $getPrototypeOf === "function" ? function(value) {
6674
+ return $getPrototypeOf(value == null ? value : $Object(value));
6675
+ } : false;
6676
+ });
6677
+ require_get_proto = __commonJS2((exports, module) => {
6678
+ var reflectGetProto = require_Reflect_getPrototypeOf(), originalGetProto = require_Object_getPrototypeOf(), getDunderProto = require_get();
6679
+ module.exports = reflectGetProto ? function(O) {
6680
+ return reflectGetProto(O);
6681
+ } : originalGetProto ? function(O) {
6682
+ if (!O || typeof O !== "object" && typeof O !== "function")
6683
+ throw TypeError("getProto: not an object");
6684
+ return originalGetProto(O);
6685
+ } : getDunderProto ? function(O) {
6686
+ return getDunderProto(O);
6687
+ } : null;
6688
+ });
6689
+ require_hasown = __commonJS2((exports, module) => {
6690
+ var call = Function.prototype.call, $hasOwn = Object.prototype.hasOwnProperty, bind = require_function_bind();
6691
+ module.exports = bind.call(call, $hasOwn);
6692
+ });
6693
+ require_get_intrinsic = __commonJS2((exports, module) => {
6694
+ var undefined2, $Object = require_es_object_atoms(), $Error = require_es_errors(), $EvalError = require_eval(), $RangeError = require_range(), $ReferenceError = require_ref(), $SyntaxError = require_syntax(), $TypeError = require_type(), $URIError = require_uri(), abs = require_abs(), floor = require_floor(), max = require_max(), min = require_min(), pow = require_pow(), round = require_round(), sign = require_sign(), $Function = Function, getEvalledConstructor = function(expressionSyntax) {
6695
+ try {
6696
+ return $Function('"use strict"; return (' + expressionSyntax + ").constructor;")();
6697
+ } catch (e) {}
6698
+ }, $gOPD = require_gopd(), $defineProperty = require_es_define_property(), throwTypeError = function() {
6699
+ throw new $TypeError;
6700
+ }, ThrowTypeError = $gOPD ? function() {
6701
+ try {
6702
+ return arguments.callee, throwTypeError;
6703
+ } catch (calleeThrows) {
6704
+ try {
6705
+ return $gOPD(arguments, "callee").get;
6706
+ } catch (gOPDthrows) {
6707
+ return throwTypeError;
6708
+ }
6709
+ }
6710
+ }() : throwTypeError, hasSymbols = require_has_symbols()(), getProto = require_get_proto(), $ObjectGPO = require_Object_getPrototypeOf(), $ReflectGPO = require_Reflect_getPrototypeOf(), $apply = require_functionApply(), $call = require_functionCall(), needsEval = {}, TypedArray = typeof Uint8Array > "u" || !getProto ? undefined2 : getProto(Uint8Array), INTRINSICS = { __proto__: null, "%AggregateError%": typeof AggregateError > "u" ? undefined2 : AggregateError, "%Array%": Array, "%ArrayBuffer%": typeof ArrayBuffer > "u" ? undefined2 : ArrayBuffer, "%ArrayIteratorPrototype%": hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined2, "%AsyncFromSyncIteratorPrototype%": undefined2, "%AsyncFunction%": needsEval, "%AsyncGenerator%": needsEval, "%AsyncGeneratorFunction%": needsEval, "%AsyncIteratorPrototype%": needsEval, "%Atomics%": typeof Atomics > "u" ? undefined2 : Atomics, "%BigInt%": typeof BigInt > "u" ? undefined2 : BigInt, "%BigInt64Array%": typeof BigInt64Array > "u" ? undefined2 : BigInt64Array, "%BigUint64Array%": typeof BigUint64Array > "u" ? undefined2 : BigUint64Array, "%Boolean%": Boolean, "%DataView%": typeof DataView > "u" ? undefined2 : DataView, "%Date%": Date, "%decodeURI%": decodeURI, "%decodeURIComponent%": decodeURIComponent, "%encodeURI%": encodeURI, "%encodeURIComponent%": encodeURIComponent, "%Error%": $Error, "%eval%": eval, "%EvalError%": $EvalError, "%Float16Array%": typeof Float16Array > "u" ? undefined2 : Float16Array, "%Float32Array%": typeof Float32Array > "u" ? undefined2 : Float32Array, "%Float64Array%": typeof Float64Array > "u" ? undefined2 : Float64Array, "%FinalizationRegistry%": typeof FinalizationRegistry > "u" ? undefined2 : FinalizationRegistry, "%Function%": $Function, "%GeneratorFunction%": needsEval, "%Int8Array%": typeof Int8Array > "u" ? undefined2 : Int8Array, "%Int16Array%": typeof Int16Array > "u" ? undefined2 : Int16Array, "%Int32Array%": typeof Int32Array > "u" ? undefined2 : Int32Array, "%isFinite%": isFinite, "%isNaN%": isNaN, "%IteratorPrototype%": hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined2, "%JSON%": typeof JSON === "object" ? JSON : undefined2, "%Map%": typeof Map > "u" ? undefined2 : Map, "%MapIteratorPrototype%": typeof Map > "u" || !hasSymbols || !getProto ? undefined2 : getProto(new Map()[Symbol.iterator]()), "%Math%": Math, "%Number%": Number, "%Object%": $Object, "%Object.getOwnPropertyDescriptor%": $gOPD, "%parseFloat%": parseFloat, "%parseInt%": parseInt, "%Promise%": typeof Promise > "u" ? undefined2 : Promise, "%Proxy%": typeof Proxy > "u" ? undefined2 : Proxy, "%RangeError%": $RangeError, "%ReferenceError%": $ReferenceError, "%Reflect%": typeof Reflect > "u" ? undefined2 : Reflect, "%RegExp%": RegExp, "%Set%": typeof Set > "u" ? undefined2 : Set, "%SetIteratorPrototype%": typeof Set > "u" || !hasSymbols || !getProto ? undefined2 : getProto(new Set()[Symbol.iterator]()), "%SharedArrayBuffer%": typeof SharedArrayBuffer > "u" ? undefined2 : SharedArrayBuffer, "%String%": String, "%StringIteratorPrototype%": hasSymbols && getProto ? getProto(""[Symbol.iterator]()) : undefined2, "%Symbol%": hasSymbols ? Symbol : undefined2, "%SyntaxError%": $SyntaxError, "%ThrowTypeError%": ThrowTypeError, "%TypedArray%": TypedArray, "%TypeError%": $TypeError, "%Uint8Array%": typeof Uint8Array > "u" ? undefined2 : Uint8Array, "%Uint8ClampedArray%": typeof Uint8ClampedArray > "u" ? undefined2 : Uint8ClampedArray, "%Uint16Array%": typeof Uint16Array > "u" ? undefined2 : Uint16Array, "%Uint32Array%": typeof Uint32Array > "u" ? undefined2 : Uint32Array, "%URIError%": $URIError, "%WeakMap%": typeof WeakMap > "u" ? undefined2 : WeakMap, "%WeakRef%": typeof WeakRef > "u" ? undefined2 : WeakRef, "%WeakSet%": typeof WeakSet > "u" ? undefined2 : WeakSet, "%Function.prototype.call%": $call, "%Function.prototype.apply%": $apply, "%Object.defineProperty%": $defineProperty, "%Object.getPrototypeOf%": $ObjectGPO, "%Math.abs%": abs, "%Math.floor%": floor, "%Math.max%": max, "%Math.min%": min, "%Math.pow%": pow, "%Math.round%": round, "%Math.sign%": sign, "%Reflect.getPrototypeOf%": $ReflectGPO };
6711
+ if (getProto)
6712
+ try {
6713
+ null.error;
6714
+ } catch (e) {
6715
+ errorProto = getProto(getProto(e)), INTRINSICS["%Error.prototype%"] = errorProto;
6716
+ }
6717
+ var errorProto, doEval = function doEval(name) {
6718
+ var value;
6719
+ if (name === "%AsyncFunction%")
6720
+ value = getEvalledConstructor("async function () {}");
6721
+ else if (name === "%GeneratorFunction%")
6722
+ value = getEvalledConstructor("function* () {}");
6723
+ else if (name === "%AsyncGeneratorFunction%")
6724
+ value = getEvalledConstructor("async function* () {}");
6725
+ else if (name === "%AsyncGenerator%") {
6726
+ var fn = doEval("%AsyncGeneratorFunction%");
6727
+ if (fn)
6728
+ value = fn.prototype;
6729
+ } else if (name === "%AsyncIteratorPrototype%") {
6730
+ var gen = doEval("%AsyncGenerator%");
6731
+ if (gen && getProto)
6732
+ value = getProto(gen.prototype);
6733
+ }
6734
+ return INTRINSICS[name] = value, value;
6735
+ }, LEGACY_ALIASES = { __proto__: null, "%ArrayBufferPrototype%": ["ArrayBuffer", "prototype"], "%ArrayPrototype%": ["Array", "prototype"], "%ArrayProto_entries%": ["Array", "prototype", "entries"], "%ArrayProto_forEach%": ["Array", "prototype", "forEach"], "%ArrayProto_keys%": ["Array", "prototype", "keys"], "%ArrayProto_values%": ["Array", "prototype", "values"], "%AsyncFunctionPrototype%": ["AsyncFunction", "prototype"], "%AsyncGenerator%": ["AsyncGeneratorFunction", "prototype"], "%AsyncGeneratorPrototype%": ["AsyncGeneratorFunction", "prototype", "prototype"], "%BooleanPrototype%": ["Boolean", "prototype"], "%DataViewPrototype%": ["DataView", "prototype"], "%DatePrototype%": ["Date", "prototype"], "%ErrorPrototype%": ["Error", "prototype"], "%EvalErrorPrototype%": ["EvalError", "prototype"], "%Float32ArrayPrototype%": ["Float32Array", "prototype"], "%Float64ArrayPrototype%": ["Float64Array", "prototype"], "%FunctionPrototype%": ["Function", "prototype"], "%Generator%": ["GeneratorFunction", "prototype"], "%GeneratorPrototype%": ["GeneratorFunction", "prototype", "prototype"], "%Int8ArrayPrototype%": ["Int8Array", "prototype"], "%Int16ArrayPrototype%": ["Int16Array", "prototype"], "%Int32ArrayPrototype%": ["Int32Array", "prototype"], "%JSONParse%": ["JSON", "parse"], "%JSONStringify%": ["JSON", "stringify"], "%MapPrototype%": ["Map", "prototype"], "%NumberPrototype%": ["Number", "prototype"], "%ObjectPrototype%": ["Object", "prototype"], "%ObjProto_toString%": ["Object", "prototype", "toString"], "%ObjProto_valueOf%": ["Object", "prototype", "valueOf"], "%PromisePrototype%": ["Promise", "prototype"], "%PromiseProto_then%": ["Promise", "prototype", "then"], "%Promise_all%": ["Promise", "all"], "%Promise_reject%": ["Promise", "reject"], "%Promise_resolve%": ["Promise", "resolve"], "%RangeErrorPrototype%": ["RangeError", "prototype"], "%ReferenceErrorPrototype%": ["ReferenceError", "prototype"], "%RegExpPrototype%": ["RegExp", "prototype"], "%SetPrototype%": ["Set", "prototype"], "%SharedArrayBufferPrototype%": ["SharedArrayBuffer", "prototype"], "%StringPrototype%": ["String", "prototype"], "%SymbolPrototype%": ["Symbol", "prototype"], "%SyntaxErrorPrototype%": ["SyntaxError", "prototype"], "%TypedArrayPrototype%": ["TypedArray", "prototype"], "%TypeErrorPrototype%": ["TypeError", "prototype"], "%Uint8ArrayPrototype%": ["Uint8Array", "prototype"], "%Uint8ClampedArrayPrototype%": ["Uint8ClampedArray", "prototype"], "%Uint16ArrayPrototype%": ["Uint16Array", "prototype"], "%Uint32ArrayPrototype%": ["Uint32Array", "prototype"], "%URIErrorPrototype%": ["URIError", "prototype"], "%WeakMapPrototype%": ["WeakMap", "prototype"], "%WeakSetPrototype%": ["WeakSet", "prototype"] }, bind = require_function_bind(), hasOwn = require_hasown(), $concat = bind.call($call, Array.prototype.concat), $spliceApply = bind.call($apply, Array.prototype.splice), $replace = bind.call($call, String.prototype.replace), $strSlice = bind.call($call, String.prototype.slice), $exec = bind.call($call, RegExp.prototype.exec), rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g, reEscapeChar = /\\(\\)?/g, stringToPath = function(string) {
6736
+ var first = $strSlice(string, 0, 1), last = $strSlice(string, -1);
6737
+ if (first === "%" && last !== "%")
6738
+ throw new $SyntaxError("invalid intrinsic syntax, expected closing `%`");
6739
+ else if (last === "%" && first !== "%")
6740
+ throw new $SyntaxError("invalid intrinsic syntax, expected opening `%`");
6741
+ var result = [];
6742
+ return $replace(string, rePropName, function(match, number, quote, subString) {
6743
+ result[result.length] = quote ? $replace(subString, reEscapeChar, "$1") : number || match;
6744
+ }), result;
6745
+ }, getBaseIntrinsic = function(name, allowMissing) {
6746
+ var intrinsicName = name, alias;
6747
+ if (hasOwn(LEGACY_ALIASES, intrinsicName))
6748
+ alias = LEGACY_ALIASES[intrinsicName], intrinsicName = "%" + alias[0] + "%";
6749
+ if (hasOwn(INTRINSICS, intrinsicName)) {
6750
+ var value = INTRINSICS[intrinsicName];
6751
+ if (value === needsEval)
6752
+ value = doEval(intrinsicName);
6753
+ if (typeof value > "u" && !allowMissing)
6754
+ throw new $TypeError("intrinsic " + name + " exists, but is not available. Please file an issue!");
6755
+ return { alias, name: intrinsicName, value };
6756
+ }
6757
+ throw new $SyntaxError("intrinsic " + name + " does not exist!");
6758
+ };
6759
+ module.exports = function(name, allowMissing) {
6760
+ if (typeof name !== "string" || name.length === 0)
6761
+ throw new $TypeError("intrinsic name must be a non-empty string");
6762
+ if (arguments.length > 1 && typeof allowMissing !== "boolean")
6763
+ throw new $TypeError('"allowMissing" argument must be a boolean');
6764
+ if ($exec(/^%?[^%]*%?$/, name) === null)
6765
+ throw new $SyntaxError("`%` may not be present anywhere but at the beginning and end of the intrinsic name");
6766
+ var parts = stringToPath(name), intrinsicBaseName = parts.length > 0 ? parts[0] : "", intrinsic = getBaseIntrinsic("%" + intrinsicBaseName + "%", allowMissing), intrinsicRealName = intrinsic.name, value = intrinsic.value, skipFurtherCaching = false, alias = intrinsic.alias;
6767
+ if (alias)
6768
+ intrinsicBaseName = alias[0], $spliceApply(parts, $concat([0, 1], alias));
6769
+ for (var i2 = 1, isOwn = true;i2 < parts.length; i2 += 1) {
6770
+ var part = parts[i2], first = $strSlice(part, 0, 1), last = $strSlice(part, -1);
6771
+ if ((first === '"' || first === "'" || first === "`" || (last === '"' || last === "'" || last === "`")) && first !== last)
6772
+ throw new $SyntaxError("property names with quotes must have matching quotes");
6773
+ if (part === "constructor" || !isOwn)
6774
+ skipFurtherCaching = true;
6775
+ if (intrinsicBaseName += "." + part, intrinsicRealName = "%" + intrinsicBaseName + "%", hasOwn(INTRINSICS, intrinsicRealName))
6776
+ value = INTRINSICS[intrinsicRealName];
6777
+ else if (value != null) {
6778
+ if (!(part in value)) {
6779
+ if (!allowMissing)
6780
+ throw new $TypeError("base intrinsic for " + name + " exists, but the property is not available.");
6781
+ return;
6782
+ }
6783
+ if ($gOPD && i2 + 1 >= parts.length) {
6784
+ var desc = $gOPD(value, part);
6785
+ if (isOwn = !!desc, isOwn && "get" in desc && !("originalValue" in desc.get))
6786
+ value = desc.get;
6787
+ else
6788
+ value = value[part];
6789
+ } else
6790
+ isOwn = hasOwn(value, part), value = value[part];
6791
+ if (isOwn && !skipFurtherCaching)
6792
+ INTRINSICS[intrinsicRealName] = value;
6793
+ }
6794
+ }
6795
+ return value;
6796
+ };
6797
+ });
6798
+ require_call_bound = __commonJS2((exports, module) => {
6799
+ var GetIntrinsic = require_get_intrinsic(), callBindBasic = require_call_bind_apply_helpers(), $indexOf = callBindBasic([GetIntrinsic("%String.prototype.indexOf%")]);
6800
+ module.exports = function(name, allowMissing) {
6801
+ var intrinsic = GetIntrinsic(name, !!allowMissing);
6802
+ if (typeof intrinsic === "function" && $indexOf(name, ".prototype.") > -1)
6803
+ return callBindBasic([intrinsic]);
6804
+ return intrinsic;
6805
+ };
6806
+ });
6807
+ require_is_callable = __commonJS2((exports, module) => {
6808
+ var fnToStr = Function.prototype.toString, reflectApply = typeof Reflect === "object" && Reflect !== null && Reflect.apply, badArrayLike, isCallableMarker;
6809
+ if (typeof reflectApply === "function" && typeof Object.defineProperty === "function")
6810
+ try {
6811
+ badArrayLike = Object.defineProperty({}, "length", { get: function() {
6812
+ throw isCallableMarker;
6813
+ } }), isCallableMarker = {}, reflectApply(function() {
6814
+ throw 42;
6815
+ }, null, badArrayLike);
6816
+ } catch (_) {
6817
+ if (_ !== isCallableMarker)
6818
+ reflectApply = null;
6819
+ }
6820
+ else
6821
+ reflectApply = null;
6822
+ var constructorRegex = /^\s*class\b/, isES6ClassFn = function(value) {
6823
+ try {
6824
+ var fnStr = fnToStr.call(value);
6825
+ return constructorRegex.test(fnStr);
6826
+ } catch (e) {
6827
+ return false;
6828
+ }
6829
+ }, tryFunctionObject = function(value) {
6830
+ try {
6831
+ if (isES6ClassFn(value))
6832
+ return false;
6833
+ return fnToStr.call(value), true;
6834
+ } catch (e) {
6835
+ return false;
6836
+ }
6837
+ }, toStr = Object.prototype.toString, objectClass = "[object Object]", fnClass = "[object Function]", genClass = "[object GeneratorFunction]", ddaClass = "[object HTMLAllCollection]", ddaClass2 = "[object HTML document.all class]", ddaClass3 = "[object HTMLCollection]", hasToStringTag = typeof Symbol === "function" && !!Symbol.toStringTag, isIE68 = !(0 in [,]), isDDA = function() {
6838
+ return false;
6839
+ };
6840
+ if (typeof document === "object") {
6841
+ if (all = document.all, toStr.call(all) === toStr.call(document.all))
6842
+ isDDA = function(value) {
6843
+ if ((isIE68 || !value) && (typeof value > "u" || typeof value === "object"))
6844
+ try {
6845
+ var str = toStr.call(value);
6846
+ return (str === ddaClass || str === ddaClass2 || str === ddaClass3 || str === objectClass) && value("") == null;
6847
+ } catch (e) {}
6848
+ return false;
6849
+ };
6850
+ }
6851
+ var all;
6852
+ module.exports = reflectApply ? function(value) {
6853
+ if (isDDA(value))
6854
+ return true;
6855
+ if (!value)
6856
+ return false;
6857
+ if (typeof value !== "function" && typeof value !== "object")
6858
+ return false;
6859
+ try {
6860
+ reflectApply(value, null, badArrayLike);
6861
+ } catch (e) {
6862
+ if (e !== isCallableMarker)
6863
+ return false;
6864
+ }
6865
+ return !isES6ClassFn(value) && tryFunctionObject(value);
6866
+ } : function(value) {
6867
+ if (isDDA(value))
6868
+ return true;
6869
+ if (!value)
6870
+ return false;
6871
+ if (typeof value !== "function" && typeof value !== "object")
6872
+ return false;
6873
+ if (hasToStringTag)
6874
+ return tryFunctionObject(value);
6875
+ if (isES6ClassFn(value))
6876
+ return false;
6877
+ var strClass = toStr.call(value);
6878
+ if (strClass !== fnClass && strClass !== genClass && !/^\[object HTML/.test(strClass))
6879
+ return false;
6880
+ return tryFunctionObject(value);
6881
+ };
6882
+ });
6883
+ require_for_each = __commonJS2((exports, module) => {
6884
+ var isCallable = require_is_callable(), toStr = Object.prototype.toString, hasOwnProperty2 = Object.prototype.hasOwnProperty, forEachArray = function(array, iterator, receiver) {
6885
+ for (var i2 = 0, len2 = array.length;i2 < len2; i2++)
6886
+ if (hasOwnProperty2.call(array, i2))
6887
+ if (receiver == null)
6888
+ iterator(array[i2], i2, array);
6889
+ else
6890
+ iterator.call(receiver, array[i2], i2, array);
6891
+ }, forEachString = function(string, iterator, receiver) {
6892
+ for (var i2 = 0, len2 = string.length;i2 < len2; i2++)
6893
+ if (receiver == null)
6894
+ iterator(string.charAt(i2), i2, string);
6895
+ else
6896
+ iterator.call(receiver, string.charAt(i2), i2, string);
6897
+ }, forEachObject = function(object, iterator, receiver) {
6898
+ for (var k in object)
6899
+ if (hasOwnProperty2.call(object, k))
6900
+ if (receiver == null)
6901
+ iterator(object[k], k, object);
6902
+ else
6903
+ iterator.call(receiver, object[k], k, object);
6904
+ };
6905
+ function isArray2(x) {
6906
+ return toStr.call(x) === "[object Array]";
6907
+ }
6908
+ module.exports = function(list, iterator, thisArg) {
6909
+ if (!isCallable(iterator))
6910
+ throw TypeError("iterator must be a function");
6911
+ var receiver;
6912
+ if (arguments.length >= 3)
6913
+ receiver = thisArg;
6914
+ if (isArray2(list))
6915
+ forEachArray(list, iterator, receiver);
6916
+ else if (typeof list === "string")
6917
+ forEachString(list, iterator, receiver);
6918
+ else
6919
+ forEachObject(list, iterator, receiver);
6920
+ };
6921
+ });
6922
+ require_possible_typed_array_names = __commonJS2((exports, module) => {
6923
+ module.exports = ["Float16Array", "Float32Array", "Float64Array", "Int8Array", "Int16Array", "Int32Array", "Uint8Array", "Uint8ClampedArray", "Uint16Array", "Uint32Array", "BigInt64Array", "BigUint64Array"];
6924
+ });
6925
+ require_available_typed_arrays = __commonJS2((exports, module) => {
6926
+ var possibleNames = require_possible_typed_array_names(), g = typeof globalThis > "u" ? globalThis : globalThis;
6927
+ module.exports = function() {
6928
+ var out = [];
6929
+ for (var i2 = 0;i2 < possibleNames.length; i2++)
6930
+ if (typeof g[possibleNames[i2]] === "function")
6931
+ out[out.length] = possibleNames[i2];
6932
+ return out;
6933
+ };
6934
+ });
6935
+ require_define_data_property = __commonJS2((exports, module) => {
6936
+ var $defineProperty = require_es_define_property(), $SyntaxError = require_syntax(), $TypeError = require_type(), gopd = require_gopd();
6937
+ module.exports = function(obj, property, value) {
6938
+ if (!obj || typeof obj !== "object" && typeof obj !== "function")
6939
+ throw new $TypeError("`obj` must be an object or a function`");
6940
+ if (typeof property !== "string" && typeof property !== "symbol")
6941
+ throw new $TypeError("`property` must be a string or a symbol`");
6942
+ if (arguments.length > 3 && typeof arguments[3] !== "boolean" && arguments[3] !== null)
6943
+ throw new $TypeError("`nonEnumerable`, if provided, must be a boolean or null");
6944
+ if (arguments.length > 4 && typeof arguments[4] !== "boolean" && arguments[4] !== null)
6945
+ throw new $TypeError("`nonWritable`, if provided, must be a boolean or null");
6946
+ if (arguments.length > 5 && typeof arguments[5] !== "boolean" && arguments[5] !== null)
6947
+ throw new $TypeError("`nonConfigurable`, if provided, must be a boolean or null");
6948
+ if (arguments.length > 6 && typeof arguments[6] !== "boolean")
6949
+ throw new $TypeError("`loose`, if provided, must be a boolean");
6950
+ var nonEnumerable = arguments.length > 3 ? arguments[3] : null, nonWritable = arguments.length > 4 ? arguments[4] : null, nonConfigurable = arguments.length > 5 ? arguments[5] : null, loose = arguments.length > 6 ? arguments[6] : false, desc = !!gopd && gopd(obj, property);
6951
+ if ($defineProperty)
6952
+ $defineProperty(obj, property, { configurable: nonConfigurable === null && desc ? desc.configurable : !nonConfigurable, enumerable: nonEnumerable === null && desc ? desc.enumerable : !nonEnumerable, value, writable: nonWritable === null && desc ? desc.writable : !nonWritable });
6953
+ else if (loose || !nonEnumerable && !nonWritable && !nonConfigurable)
6954
+ obj[property] = value;
6955
+ else
6956
+ throw new $SyntaxError("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.");
6957
+ };
6958
+ });
6959
+ require_has_property_descriptors = __commonJS2((exports, module) => {
6960
+ var $defineProperty = require_es_define_property(), hasPropertyDescriptors = function() {
6961
+ return !!$defineProperty;
6962
+ };
6963
+ hasPropertyDescriptors.hasArrayLengthDefineBug = function() {
6964
+ if (!$defineProperty)
6965
+ return null;
6966
+ try {
6967
+ return $defineProperty([], "length", { value: 1 }).length !== 1;
6968
+ } catch (e) {
6969
+ return true;
6970
+ }
6971
+ };
6972
+ module.exports = hasPropertyDescriptors;
6973
+ });
6974
+ require_set_function_length = __commonJS2((exports, module) => {
6975
+ var GetIntrinsic = require_get_intrinsic(), define = require_define_data_property(), hasDescriptors = require_has_property_descriptors()(), gOPD = require_gopd(), $TypeError = require_type(), $floor = GetIntrinsic("%Math.floor%");
6976
+ module.exports = function(fn, length) {
6977
+ if (typeof fn !== "function")
6978
+ throw new $TypeError("`fn` is not a function");
6979
+ if (typeof length !== "number" || length < 0 || length > 4294967295 || $floor(length) !== length)
6980
+ throw new $TypeError("`length` must be a positive 32-bit integer");
6981
+ var loose = arguments.length > 2 && !!arguments[2], functionLengthIsConfigurable = true, functionLengthIsWritable = true;
6982
+ if ("length" in fn && gOPD) {
6983
+ var desc = gOPD(fn, "length");
6984
+ if (desc && !desc.configurable)
6985
+ functionLengthIsConfigurable = false;
6986
+ if (desc && !desc.writable)
6987
+ functionLengthIsWritable = false;
6988
+ }
6989
+ if (functionLengthIsConfigurable || functionLengthIsWritable || !loose)
6990
+ if (hasDescriptors)
6991
+ define(fn, "length", length, true, true);
6992
+ else
6993
+ define(fn, "length", length);
6994
+ return fn;
6995
+ };
6996
+ });
6997
+ require_applyBind = __commonJS2((exports, module) => {
6998
+ var bind = require_function_bind(), $apply = require_functionApply(), actualApply = require_actualApply();
6999
+ module.exports = function() {
7000
+ return actualApply(bind, $apply, arguments);
7001
+ };
7002
+ });
7003
+ require_call_bind = __commonJS2((exports, module) => {
7004
+ var setFunctionLength = require_set_function_length(), $defineProperty = require_es_define_property(), callBindBasic = require_call_bind_apply_helpers(), applyBind = require_applyBind();
7005
+ module.exports = function(originalFunction) {
7006
+ var func = callBindBasic(arguments), adjustedLength = originalFunction.length - (arguments.length - 1);
7007
+ return setFunctionLength(func, 1 + (adjustedLength > 0 ? adjustedLength : 0), true);
7008
+ };
7009
+ if ($defineProperty)
7010
+ $defineProperty(module.exports, "apply", { value: applyBind });
7011
+ else
7012
+ module.exports.apply = applyBind;
7013
+ });
7014
+ require_shams2 = __commonJS2((exports, module) => {
7015
+ var hasSymbols = require_shams();
7016
+ module.exports = function() {
7017
+ return hasSymbols() && !!Symbol.toStringTag;
7018
+ };
7019
+ });
7020
+ require_which_typed_array = __commonJS2((exports, module) => {
7021
+ var forEach = require_for_each(), availableTypedArrays = require_available_typed_arrays(), callBind = require_call_bind(), callBound = require_call_bound(), gOPD = require_gopd(), getProto = require_get_proto(), $toString = callBound("Object.prototype.toString"), hasToStringTag = require_shams2()(), g = typeof globalThis > "u" ? globalThis : globalThis, typedArrays = availableTypedArrays(), $slice = callBound("String.prototype.slice"), $indexOf = callBound("Array.prototype.indexOf", true) || function(array, value) {
7022
+ for (var i2 = 0;i2 < array.length; i2 += 1)
7023
+ if (array[i2] === value)
7024
+ return i2;
7025
+ return -1;
7026
+ }, cache = { __proto__: null };
7027
+ if (hasToStringTag && gOPD && getProto)
7028
+ forEach(typedArrays, function(typedArray) {
7029
+ var arr = new g[typedArray];
7030
+ if (Symbol.toStringTag in arr && getProto) {
7031
+ var proto = getProto(arr), descriptor = gOPD(proto, Symbol.toStringTag);
7032
+ if (!descriptor && proto) {
7033
+ var superProto = getProto(proto);
7034
+ descriptor = gOPD(superProto, Symbol.toStringTag);
7035
+ }
7036
+ cache["$" + typedArray] = callBind(descriptor.get);
7037
+ }
7038
+ });
7039
+ else
7040
+ forEach(typedArrays, function(typedArray) {
7041
+ var arr = new g[typedArray], fn = arr.slice || arr.set;
7042
+ if (fn)
7043
+ cache["$" + typedArray] = callBind(fn);
7044
+ });
7045
+ var tryTypedArrays = function(value) {
7046
+ var found = false;
7047
+ return forEach(cache, function(getter, typedArray) {
7048
+ if (!found)
7049
+ try {
7050
+ if ("$" + getter(value) === typedArray)
7051
+ found = $slice(typedArray, 1);
7052
+ } catch (e) {}
7053
+ }), found;
7054
+ }, trySlices = function(value) {
7055
+ var found = false;
7056
+ return forEach(cache, function(getter, name) {
7057
+ if (!found)
7058
+ try {
7059
+ getter(value), found = $slice(name, 1);
7060
+ } catch (e) {}
7061
+ }), found;
7062
+ };
7063
+ module.exports = function(value) {
7064
+ if (!value || typeof value !== "object")
7065
+ return false;
7066
+ if (!hasToStringTag) {
7067
+ var tag = $slice($toString(value), 8, -1);
7068
+ if ($indexOf(typedArrays, tag) > -1)
7069
+ return tag;
7070
+ if (tag !== "Object")
7071
+ return false;
7072
+ return trySlices(value);
7073
+ }
7074
+ if (!gOPD)
7075
+ return null;
7076
+ return tryTypedArrays(value);
7077
+ };
7078
+ });
7079
+ require_is_typed_array = __commonJS2((exports, module) => {
7080
+ var whichTypedArray = require_which_typed_array();
7081
+ module.exports = function(value) {
7082
+ return !!whichTypedArray(value);
7083
+ };
7084
+ });
7085
+ require_typed_array_buffer = __commonJS2((exports, module) => {
7086
+ var $TypeError = require_type(), callBound = require_call_bound(), $typedArrayBuffer = callBound("TypedArray.prototype.buffer", true), isTypedArray = require_is_typed_array();
7087
+ module.exports = $typedArrayBuffer || function(x) {
7088
+ if (!isTypedArray(x))
7089
+ throw new $TypeError("Not a Typed Array");
7090
+ return x.buffer;
7091
+ };
7092
+ });
6420
7093
  require_to_buffer = __commonJS2((exports, module) => {
6421
- var Buffer22 = require_safe_buffer().Buffer;
7094
+ var Buffer22 = require_safe_buffer().Buffer, isArray2 = require_isarray(), typedArrayBuffer = require_typed_array_buffer(), isView = ArrayBuffer.isView || function(obj) {
7095
+ try {
7096
+ return typedArrayBuffer(obj), true;
7097
+ } catch (e) {
7098
+ return false;
7099
+ }
7100
+ }, useUint8Array = typeof Uint8Array < "u", useArrayBuffer = typeof ArrayBuffer < "u" && typeof Uint8Array < "u", useFromArrayBuffer = useArrayBuffer && (Buffer22.prototype instanceof Uint8Array || Buffer22.TYPED_ARRAY_SUPPORT);
7101
+ module.exports = function(data, encoding) {
7102
+ if (Buffer22.isBuffer(data)) {
7103
+ if (data.constructor && !("isBuffer" in data))
7104
+ return Buffer22.from(data);
7105
+ return data;
7106
+ }
7107
+ if (typeof data === "string")
7108
+ return Buffer22.from(data, encoding);
7109
+ if (useArrayBuffer && isView(data)) {
7110
+ if (data.byteLength === 0)
7111
+ return Buffer22.alloc(0);
7112
+ if (useFromArrayBuffer) {
7113
+ var res = Buffer22.from(data.buffer, data.byteOffset, data.byteLength);
7114
+ if (res.byteLength === data.byteLength)
7115
+ return res;
7116
+ }
7117
+ var uint8 = data instanceof Uint8Array ? data : new Uint8Array(data.buffer, data.byteOffset, data.byteLength), result = Buffer22.from(uint8);
7118
+ if (result.length === data.byteLength)
7119
+ return result;
7120
+ }
7121
+ if (useUint8Array && data instanceof Uint8Array)
7122
+ return Buffer22.from(data);
7123
+ var isArr = isArray2(data);
7124
+ if (isArr)
7125
+ for (var i2 = 0;i2 < data.length; i2 += 1) {
7126
+ var x = data[i2];
7127
+ if (typeof x !== "number" || x < 0 || x > 255 || ~~x !== x)
7128
+ throw RangeError("Array items must be numbers in the range 0-255.");
7129
+ }
7130
+ if (isArr || Buffer22.isBuffer(data) && data.constructor && typeof data.constructor.isBuffer === "function" && data.constructor.isBuffer(data))
7131
+ return Buffer22.from(data);
7132
+ throw TypeError('The "data" argument must be a string, an Array, a Buffer, a Uint8Array, or a DataView.');
7133
+ };
7134
+ });
7135
+ require_to_buffer2 = __commonJS2((exports, module) => {
7136
+ var Buffer22 = require_safe_buffer().Buffer, toBuffer = require_to_buffer(), useUint8Array = typeof Uint8Array < "u", useArrayBuffer = useUint8Array && typeof ArrayBuffer < "u", isView = useArrayBuffer && ArrayBuffer.isView;
6422
7137
  module.exports = function(thing, encoding, name) {
6423
- if (Buffer22.isBuffer(thing))
6424
- return thing;
6425
- else if (typeof thing === "string")
6426
- return Buffer22.from(thing, encoding);
6427
- else if (ArrayBuffer.isView(thing))
6428
- return Buffer22.from(thing.buffer);
6429
- else
6430
- throw TypeError(name + " must be a string, a Buffer, a typed array or a DataView");
7138
+ if (typeof thing === "string" || Buffer22.isBuffer(thing) || useUint8Array && thing instanceof Uint8Array || isView && isView(thing))
7139
+ return toBuffer(thing, encoding);
7140
+ throw TypeError(name + " must be a string, a Buffer, a Uint8Array, or a DataView");
6431
7141
  };
6432
7142
  });
6433
7143
  require_sync = __commonJS2((exports, module) => {
6434
- var sizes = { md5: 16, sha1: 20, sha224: 28, sha256: 32, sha384: 48, sha512: 64, rmd160: 20, ripemd160: 20 }, createHmac = require_create_hmac(), Buffer22 = require_safe_buffer().Buffer, checkParameters = require_precondition(), defaultEncoding = require_default_encoding(), toBuffer = require_to_buffer();
7144
+ var sizes = { __proto__: null, md5: 16, sha1: 20, sha224: 28, sha256: 32, sha384: 48, sha512: 64, "sha512-256": 32, rmd160: 20, ripemd160: 20 }, mapping = { __proto__: null, "sha-1": "sha1", "sha-224": "sha224", "sha-256": "sha256", "sha-384": "sha384", "sha-512": "sha512", "ripemd-160": "ripemd160" }, createHmac = require_create_hmac(), Buffer22 = require_safe_buffer().Buffer, checkParameters = require_precondition(), defaultEncoding = require_default_encoding(), toBuffer = require_to_buffer2();
6435
7145
  function pbkdf2(password, salt, iterations, keylen, digest) {
6436
- checkParameters(iterations, keylen), password = toBuffer(password, defaultEncoding, "Password"), salt = toBuffer(salt, defaultEncoding, "Salt"), digest = digest || "sha1";
7146
+ checkParameters(iterations, keylen), password = toBuffer(password, defaultEncoding, "Password"), salt = toBuffer(salt, defaultEncoding, "Salt");
7147
+ var lowerDigest = (digest || "sha1").toLowerCase(), mappedDigest = mapping[lowerDigest] || lowerDigest, size = sizes[mappedDigest];
7148
+ if (typeof size !== "number" || !size)
7149
+ throw TypeError("Digest algorithm not supported: " + digest);
6437
7150
  var DK = Buffer22.allocUnsafe(keylen), block1 = Buffer22.allocUnsafe(salt.length + 4);
6438
7151
  salt.copy(block1, 0, 0, salt.length);
6439
- var destPos = 0, hLen = sizes[digest], l = Math.ceil(keylen / hLen);
7152
+ var destPos = 0, hLen = size, l = Math.ceil(keylen / hLen);
6440
7153
  for (var i2 = 1;i2 <= l; i2++) {
6441
7154
  block1.writeUInt32BE(i2, salt.length);
6442
- var T = createHmac(digest, password).update(block1).digest(), U = T;
7155
+ var T = createHmac(mappedDigest, password).update(block1).digest(), U = T;
6443
7156
  for (var j = 1;j < iterations; j++) {
6444
- U = createHmac(digest, password).update(U).digest();
7157
+ U = createHmac(mappedDigest, password).update(U).digest();
6445
7158
  for (var k = 0;k < hLen; k++)
6446
7159
  T[k] ^= U[k];
6447
7160
  }
@@ -6452,23 +7165,7 @@ var init_crypto = __esm(() => {
6452
7165
  module.exports = pbkdf2;
6453
7166
  });
6454
7167
  require_async = __commonJS2((exports, module) => {
6455
- var Buffer22 = require_safe_buffer().Buffer, checkParameters = require_precondition(), defaultEncoding = require_default_encoding(), sync = require_sync(), toBuffer = require_to_buffer(), ZERO_BUF, subtle = globalThis.crypto && globalThis.crypto.subtle, toBrowser = { sha: "SHA-1", "sha-1": "SHA-1", sha1: "SHA-1", sha256: "SHA-256", "sha-256": "SHA-256", sha384: "SHA-384", "sha-384": "SHA-384", "sha-512": "SHA-512", sha512: "SHA-512" }, checks = [];
6456
- function checkNative(algo) {
6457
- if (globalThis.process && !globalThis.process.browser)
6458
- return Promise.resolve(false);
6459
- if (!subtle || !subtle.importKey || !subtle.deriveBits)
6460
- return Promise.resolve(false);
6461
- if (checks[algo] !== undefined)
6462
- return checks[algo];
6463
- ZERO_BUF = ZERO_BUF || Buffer22.alloc(8);
6464
- var prom = browserPbkdf2(ZERO_BUF, ZERO_BUF, 10, 128, algo).then(function() {
6465
- return true;
6466
- }).catch(function() {
6467
- return false;
6468
- });
6469
- return checks[algo] = prom, prom;
6470
- }
6471
- var nextTick;
7168
+ var Buffer22 = require_safe_buffer().Buffer, checkParameters = require_precondition(), defaultEncoding = require_default_encoding(), sync = require_sync(), toBuffer = require_to_buffer2(), ZERO_BUF, subtle = globalThis.crypto && globalThis.crypto.subtle, toBrowser = { sha: "SHA-1", "sha-1": "SHA-1", sha1: "SHA-1", sha256: "SHA-256", "sha-256": "SHA-256", sha384: "SHA-384", "sha-384": "SHA-384", "sha-512": "SHA-512", sha512: "SHA-512" }, checks = [], nextTick;
6472
7169
  function getNextTick() {
6473
7170
  if (nextTick)
6474
7171
  return nextTick;
@@ -6489,6 +7186,21 @@ var init_crypto = __esm(() => {
6489
7186
  return Buffer22.from(res);
6490
7187
  });
6491
7188
  }
7189
+ function checkNative(algo) {
7190
+ if (globalThis.process && !globalThis.process.browser)
7191
+ return Promise.resolve(false);
7192
+ if (!subtle || !subtle.importKey || !subtle.deriveBits)
7193
+ return Promise.resolve(false);
7194
+ if (checks[algo] !== undefined)
7195
+ return checks[algo];
7196
+ ZERO_BUF = ZERO_BUF || Buffer22.alloc(8);
7197
+ var prom = browserPbkdf2(ZERO_BUF, ZERO_BUF, 10, 128, algo).then(function() {
7198
+ return true;
7199
+ }, function() {
7200
+ return false;
7201
+ });
7202
+ return checks[algo] = prom, prom;
7203
+ }
6492
7204
  function resolvePromise(promise, callback) {
6493
7205
  promise.then(function(out) {
6494
7206
  getNextTick()(function() {
@@ -6503,6 +7215,8 @@ var init_crypto = __esm(() => {
6503
7215
  module.exports = function(password, salt, iterations, keylen, digest, callback) {
6504
7216
  if (typeof digest === "function")
6505
7217
  callback = digest, digest = undefined;
7218
+ if (checkParameters(iterations, keylen), password = toBuffer(password, defaultEncoding, "Password"), salt = toBuffer(salt, defaultEncoding, "Salt"), typeof callback !== "function")
7219
+ throw Error("No callback provided to pbkdf2");
6506
7220
  digest = digest || "sha1";
6507
7221
  var algo = toBrowser[digest.toLowerCase()];
6508
7222
  if (!algo || typeof globalThis.Promise !== "function") {
@@ -6511,14 +7225,13 @@ var init_crypto = __esm(() => {
6511
7225
  try {
6512
7226
  out = sync(password, salt, iterations, keylen, digest);
6513
7227
  } catch (e) {
6514
- return callback(e);
7228
+ callback(e);
7229
+ return;
6515
7230
  }
6516
7231
  callback(null, out);
6517
7232
  });
6518
7233
  return;
6519
7234
  }
6520
- if (checkParameters(iterations, keylen), password = toBuffer(password, defaultEncoding, "Password"), salt = toBuffer(salt, defaultEncoding, "Salt"), typeof callback !== "function")
6521
- throw Error("No callback provided to pbkdf2");
6522
7235
  resolvePromise(checkNative(algo).then(function(resp) {
6523
7236
  if (resp)
6524
7237
  return browserPbkdf2(password, salt, iterations, keylen, algo);
@@ -6527,18 +7240,18 @@ var init_crypto = __esm(() => {
6527
7240
  };
6528
7241
  });
6529
7242
  require_pbkdf2 = __commonJS2((exports) => {
6530
- var native = (init_crypto(), __toCommonJS(exports_crypto)), checkParameters = require_precondition(), defaultEncoding = require_default_encoding(), toBuffer = require_to_buffer();
7243
+ var nativeImpl = (init_crypto(), __toCommonJS(exports_crypto)), checkParameters = require_precondition(), defaultEncoding = require_default_encoding(), toBuffer = require_to_buffer2();
6531
7244
  function nativePBKDF2(password, salt, iterations, keylen, digest, callback) {
6532
7245
  if (checkParameters(iterations, keylen), password = toBuffer(password, defaultEncoding, "Password"), salt = toBuffer(salt, defaultEncoding, "Salt"), typeof digest === "function")
6533
7246
  callback = digest, digest = "sha1";
6534
7247
  if (typeof callback !== "function")
6535
7248
  throw Error("No callback provided to pbkdf2");
6536
- return native.pbkdf2(password, salt, iterations, keylen, digest, callback);
7249
+ return nativeImpl.pbkdf2(password, salt, iterations, keylen, digest, callback);
6537
7250
  }
6538
7251
  function nativePBKDF2Sync(password, salt, iterations, keylen, digest) {
6539
- return checkParameters(iterations, keylen), password = toBuffer(password, defaultEncoding, "Password"), salt = toBuffer(salt, defaultEncoding, "Salt"), digest = digest || "sha1", native.pbkdf2Sync(password, salt, iterations, keylen, digest);
7252
+ return checkParameters(iterations, keylen), password = toBuffer(password, defaultEncoding, "Password"), salt = toBuffer(salt, defaultEncoding, "Salt"), digest = digest || "sha1", nativeImpl.pbkdf2Sync(password, salt, iterations, keylen, digest);
6540
7253
  }
6541
- if (!native.pbkdf2Sync || native.pbkdf2Sync.toString().indexOf("keylen, digest") === -1)
7254
+ if (!nativeImpl.pbkdf2Sync || nativeImpl.pbkdf2Sync.toString().indexOf("keylen, digest") === -1)
6542
7255
  exports.pbkdf2Sync = require_sync(), exports.pbkdf2 = require_async();
6543
7256
  else
6544
7257
  exports.pbkdf2Sync = nativePBKDF2Sync, exports.pbkdf2 = nativePBKDF2;
@@ -14371,9 +15084,9 @@ var init_crypto = __esm(() => {
14371
15084
  };
14372
15085
  });
14373
15086
  require_parse_asn1 = __commonJS2((exports, module) => {
14374
- var asn1 = require_asn12(), aesid = require_aesid(), fixProc = require_fixProc(), ciphers = require_browserify_aes(), compat = require_pbkdf2(), Buffer22 = require_safe_buffer().Buffer;
15087
+ var asn1 = require_asn12(), aesid = require_aesid(), fixProc = require_fixProc(), ciphers = require_browserify_aes(), pbkdf2Sync = require_pbkdf2().pbkdf2Sync, Buffer22 = require_safe_buffer().Buffer;
14375
15088
  function decrypt(data, password) {
14376
- var salt = data.algorithm.decrypt.kde.kdeparams.salt, iters = parseInt(data.algorithm.decrypt.kde.kdeparams.iters.toString(), 10), algo = aesid[data.algorithm.decrypt.cipher.algo.join(".")], iv = data.algorithm.decrypt.cipher.iv, cipherText = data.subjectPrivateKey, keylen = parseInt(algo.split("-")[1], 10) / 8, key = compat.pbkdf2Sync(password, salt, iters, keylen, "sha1"), cipher = ciphers.createDecipheriv(algo, key, iv), out = [];
15089
+ var salt = data.algorithm.decrypt.kde.kdeparams.salt, iters = parseInt(data.algorithm.decrypt.kde.kdeparams.iters.toString(), 10), algo = aesid[data.algorithm.decrypt.cipher.algo.join(".")], iv = data.algorithm.decrypt.cipher.iv, cipherText = data.subjectPrivateKey, keylen = parseInt(algo.split("-")[1], 10) / 8, key = pbkdf2Sync(password, salt, iters, keylen, "sha1"), cipher = ciphers.createDecipheriv(algo, key, iv), out = [];
14377
15090
  return out.push(cipher.update(cipherText)), out.push(cipher.final()), Buffer22.concat(out);
14378
15091
  }
14379
15092
  function parseKeys(buffer) {
@@ -18340,10 +19053,7 @@ async function generateMigrationSQL(previousSnapshot, currentSnapshot, diff) {
18340
19053
  }
18341
19054
  const dataLossCheck = checkForDataLoss(diff);
18342
19055
  if (dataLossCheck.warnings.length > 0) {
18343
- logger2.warn("[RuntimeMigrator] Schema changes may cause data loss:");
18344
- for (const warning of dataLossCheck.warnings) {
18345
- logger2.warn(` - ${warning}`);
18346
- }
19056
+ logger2.warn({ src: "plugin:sql", warnings: dataLossCheck.warnings }, "Schema changes may cause data loss");
18347
19057
  }
18348
19058
  const schemasToCreate = new Set;
18349
19059
  for (const tableName of diff.tables.created) {
@@ -18768,7 +19478,7 @@ class DatabaseIntrospector {
18768
19478
  this.db = db;
18769
19479
  }
18770
19480
  async introspectSchema(schemaName = "public") {
18771
- logger4.info(`[DatabaseIntrospector] Starting introspection for schema: ${schemaName}`);
19481
+ logger4.info({ src: "plugin:sql", schemaName }, "Starting database introspection");
18772
19482
  const tables = {};
18773
19483
  const schemas = {};
18774
19484
  const enums = {};
@@ -18776,7 +19486,7 @@ class DatabaseIntrospector {
18776
19486
  for (const tableInfo of allTables) {
18777
19487
  const tableName = tableInfo.table_name;
18778
19488
  const tableSchema = tableInfo.table_schema || "public";
18779
- logger4.debug(`[DatabaseIntrospector] Introspecting table: ${tableSchema}.${tableName}`);
19489
+ logger4.debug({ src: "plugin:sql", tableSchema, tableName }, "Introspecting table");
18780
19490
  const columns = await this.getColumns(tableSchema, tableName);
18781
19491
  const columnsObject = {};
18782
19492
  const uniqueConstraintObject = {};
@@ -18793,15 +19503,17 @@ class DatabaseIntrospector {
18793
19503
  const indexesObject = {};
18794
19504
  for (const idx of indexes) {
18795
19505
  if (!idx.is_primary && !idx.is_unique_constraint) {
18796
- indexesObject[idx.name] = {
18797
- name: idx.name,
18798
- columns: idx.columns.map((col) => ({
18799
- expression: col,
18800
- isExpression: false
18801
- })),
18802
- isUnique: idx.is_unique,
18803
- method: idx.method || "btree"
18804
- };
19506
+ if (idx.columns && Array.isArray(idx.columns) && idx.columns.length > 0) {
19507
+ indexesObject[idx.name] = {
19508
+ name: idx.name,
19509
+ columns: idx.columns.map((col) => ({
19510
+ expression: col,
19511
+ isExpression: false
19512
+ })),
19513
+ isUnique: idx.is_unique,
19514
+ method: idx.method || "btree"
19515
+ };
19516
+ }
18805
19517
  }
18806
19518
  }
18807
19519
  const foreignKeys = await this.getForeignKeys(tableSchema, tableName);
@@ -18869,7 +19581,7 @@ class DatabaseIntrospector {
18869
19581
  }
18870
19582
  enums[key].values.push(enumInfo.value);
18871
19583
  }
18872
- logger4.info(`[DatabaseIntrospector] Introspection complete. Found ${Object.keys(tables).length} tables`);
19584
+ logger4.info({ src: "plugin:sql", tableCount: Object.keys(tables).length }, "Database introspection complete");
18873
19585
  return {
18874
19586
  version: "7",
18875
19587
  dialect: "postgresql",
@@ -19129,7 +19841,7 @@ class RuntimeMigrator {
19129
19841
  }
19130
19842
  }
19131
19843
  for (const schemaName of schemasToCreate) {
19132
- logger5.debug(`[RuntimeMigrator] Ensuring schema '${schemaName}' exists`);
19844
+ logger5.debug({ src: "plugin:sql", schemaName }, "Ensuring schema exists");
19133
19845
  await this.db.execute(sql22.raw(`CREATE SCHEMA IF NOT EXISTS "${schemaName}"`));
19134
19846
  }
19135
19847
  }
@@ -19140,10 +19852,15 @@ class RuntimeMigrator {
19140
19852
  const tableData = table;
19141
19853
  const actualSchema = tableData.schema || "public";
19142
19854
  if (!isCorePLugin && actualSchema === "public") {
19143
- logger5.warn(`[RuntimeMigrator] WARNING: Plugin '${pluginName}' table '${tableData.name}' is using public schema. ` + `Consider using pgSchema('${expectedSchema}').table(...) for better isolation.`);
19855
+ logger5.warn({ src: "plugin:sql", pluginName, tableName: tableData.name, expectedSchema }, "Plugin table is using public schema - consider using pgSchema for better isolation");
19144
19856
  }
19145
19857
  if (isCorePLugin && actualSchema !== "public") {
19146
- logger5.warn(`[RuntimeMigrator] WARNING: Core plugin '@elizaos/plugin-sql' table '${tableData.name}' is using schema '${actualSchema}'. ` + `Core tables should use public schema.`);
19858
+ logger5.warn({
19859
+ src: "plugin:sql",
19860
+ pluginName: "@elizaos/plugin-sql",
19861
+ tableName: tableData.name,
19862
+ actualSchema
19863
+ }, "Core plugin table should use public schema");
19147
19864
  }
19148
19865
  }
19149
19866
  }
@@ -19354,13 +20071,13 @@ class RuntimeMigrator {
19354
20071
  }
19355
20072
  }
19356
20073
  }
19357
- logger5.debug(`[RuntimeMigrator] Connection string did not match any PostgreSQL patterns: ${url.substring(0, 50)}...`);
20074
+ logger5.debug({ src: "plugin:sql", urlPreview: url.substring(0, 50) }, "Connection string did not match any PostgreSQL patterns");
19358
20075
  return false;
19359
20076
  }
19360
20077
  async initialize() {
19361
- logger5.info("[RuntimeMigrator] Initializing migration system...");
20078
+ logger5.info({ src: "plugin:sql" }, "Initializing migration system");
19362
20079
  await this.migrationTracker.ensureTables();
19363
- logger5.info("[RuntimeMigrator] Migration system initialized");
20080
+ logger5.info({ src: "plugin:sql" }, "Migration system initialized");
19364
20081
  }
19365
20082
  async migrate(pluginName, schema, options = {}) {
19366
20083
  const lockId = this.getAdvisoryLockId(pluginName);
@@ -19369,46 +20086,54 @@ class RuntimeMigrator {
19369
20086
  }
19370
20087
  let lockAcquired = false;
19371
20088
  try {
19372
- logger5.info(`[RuntimeMigrator] Starting migration for plugin: ${pluginName}`);
20089
+ logger5.info({ src: "plugin:sql", pluginName }, "Starting migration for plugin");
19373
20090
  await this.initialize();
19374
20091
  const postgresUrl = process.env.POSTGRES_URL || process.env.DATABASE_URL || "";
19375
20092
  const isRealPostgres = this.isRealPostgresDatabase(postgresUrl);
19376
20093
  if (isRealPostgres) {
19377
20094
  try {
19378
- logger5.debug(`[RuntimeMigrator] Using PostgreSQL advisory locks for ${pluginName}`);
20095
+ logger5.debug({ src: "plugin:sql", pluginName }, "Using PostgreSQL advisory locks");
19379
20096
  const lockIdStr = lockId.toString();
19380
20097
  const lockResult = await this.db.execute(sql22`SELECT pg_try_advisory_lock(CAST(${lockIdStr} AS bigint)) as acquired`);
19381
20098
  lockAcquired = lockResult.rows[0]?.acquired === true;
19382
20099
  if (!lockAcquired) {
19383
- logger5.info(`[RuntimeMigrator] Migration already in progress for ${pluginName}, waiting for lock...`);
20100
+ logger5.info({ src: "plugin:sql", pluginName }, "Migration already in progress, waiting for lock");
19384
20101
  await this.db.execute(sql22`SELECT pg_advisory_lock(CAST(${lockIdStr} AS bigint))`);
19385
20102
  lockAcquired = true;
19386
- logger5.info(`[RuntimeMigrator] Lock acquired for ${pluginName}`);
20103
+ logger5.info({ src: "plugin:sql", pluginName }, "Lock acquired");
19387
20104
  } else {
19388
- logger5.debug(`[RuntimeMigrator] Advisory lock acquired for ${pluginName} (lock ID: ${lockIdStr})`);
20105
+ logger5.debug({ src: "plugin:sql", pluginName, lockId: lockIdStr }, "Advisory lock acquired");
19389
20106
  }
19390
20107
  } catch (lockError) {
19391
- logger5.warn(`[RuntimeMigrator] Failed to acquire advisory lock, continuing without lock: ${lockError}`);
20108
+ logger5.warn({
20109
+ src: "plugin:sql",
20110
+ pluginName,
20111
+ error: lockError instanceof Error ? lockError.message : String(lockError)
20112
+ }, "Failed to acquire advisory lock, continuing without lock");
19392
20113
  lockAcquired = false;
19393
20114
  }
19394
20115
  } else {
19395
- logger5.debug(`[RuntimeMigrator] Development database detected (PGLite or non-PostgreSQL), skipping advisory locks`);
20116
+ logger5.debug({ src: "plugin:sql" }, "Development database detected, skipping advisory locks");
19396
20117
  }
19397
- await this.extensionManager.installRequiredExtensions(["vector", "fuzzystrmatch"]);
20118
+ await this.extensionManager.installRequiredExtensions([
20119
+ "vector",
20120
+ "fuzzystrmatch",
20121
+ "pgcrypto"
20122
+ ]);
19398
20123
  const currentSnapshot = await generateSnapshot(schema);
19399
20124
  await this.ensureSchemasExist(currentSnapshot);
19400
20125
  this.validateSchemaUsage(pluginName, currentSnapshot);
19401
20126
  const currentHash = hashSnapshot(currentSnapshot);
19402
20127
  const lastMigration = await this.migrationTracker.getLastMigration(pluginName);
19403
20128
  if (lastMigration && lastMigration.hash === currentHash) {
19404
- logger5.info(`[RuntimeMigrator] No changes detected for ${pluginName}, skipping migration (hash: ${currentHash})`);
20129
+ logger5.info({ src: "plugin:sql", pluginName, hash: currentHash }, "No changes detected, skipping migration");
19405
20130
  return;
19406
20131
  }
19407
20132
  let previousSnapshot = await this.snapshotStorage.getLatestSnapshot(pluginName);
19408
20133
  if (!previousSnapshot && Object.keys(currentSnapshot.tables).length > 0) {
19409
20134
  const hasExistingTables = await this.introspector.hasExistingTables(pluginName);
19410
20135
  if (hasExistingTables) {
19411
- logger5.info(`[RuntimeMigrator] No snapshot found for ${pluginName} but tables exist in database. Introspecting...`);
20136
+ logger5.info({ src: "plugin:sql", pluginName }, "No snapshot found but tables exist in database, introspecting");
19412
20137
  const schemaName = this.getExpectedSchemaName(pluginName);
19413
20138
  const introspectedSnapshot = await this.introspector.introspectSchema(schemaName);
19414
20139
  if (Object.keys(introspectedSnapshot.tables).length > 0) {
@@ -19416,15 +20141,15 @@ class RuntimeMigrator {
19416
20141
  await this.journalStorage.updateJournal(pluginName, 0, `introspected_${Date.now()}`, true);
19417
20142
  const introspectedHash = hashSnapshot(introspectedSnapshot);
19418
20143
  await this.migrationTracker.recordMigration(pluginName, introspectedHash, Date.now());
19419
- logger5.info(`[RuntimeMigrator] Created initial snapshot from existing database for ${pluginName}`);
20144
+ logger5.info({ src: "plugin:sql", pluginName }, "Created initial snapshot from existing database");
19420
20145
  previousSnapshot = introspectedSnapshot;
19421
20146
  }
19422
20147
  }
19423
20148
  }
19424
20149
  if (!hasChanges(previousSnapshot, currentSnapshot)) {
19425
- logger5.info(`[RuntimeMigrator] No schema changes for ${pluginName}`);
20150
+ logger5.info({ src: "plugin:sql", pluginName }, "No schema changes");
19426
20151
  if (!previousSnapshot && Object.keys(currentSnapshot.tables).length === 0) {
19427
- logger5.info(`[RuntimeMigrator] Recording empty schema for ${pluginName}`);
20152
+ logger5.info({ src: "plugin:sql", pluginName }, "Recording empty schema");
19428
20153
  await this.migrationTracker.recordMigration(pluginName, currentHash, Date.now());
19429
20154
  const idx = await this.journalStorage.getNextIdx(pluginName);
19430
20155
  const tag = this.generateMigrationTag(idx, pluginName);
@@ -19435,7 +20160,7 @@ class RuntimeMigrator {
19435
20160
  }
19436
20161
  const diff = await calculateDiff(previousSnapshot, currentSnapshot);
19437
20162
  if (!hasDiffChanges(diff)) {
19438
- logger5.info(`[RuntimeMigrator] No actionable changes for ${pluginName}`);
20163
+ logger5.info({ src: "plugin:sql", pluginName }, "No actionable changes");
19439
20164
  return;
19440
20165
  }
19441
20166
  const dataLossCheck = checkForDataLoss(diff);
@@ -19443,55 +20168,43 @@ class RuntimeMigrator {
19443
20168
  const isProduction = false;
19444
20169
  const allowDestructive = options.force || options.allowDataLoss || process.env.ELIZA_ALLOW_DESTRUCTIVE_MIGRATIONS === "true";
19445
20170
  if (!allowDestructive) {
19446
- logger5.error("[RuntimeMigrator] Destructive migration blocked");
19447
- logger5.error(`[RuntimeMigrator] Plugin: ${pluginName}`);
19448
- logger5.error(`[RuntimeMigrator] Environment: ${isProduction ? "PRODUCTION" : "DEVELOPMENT"}`);
19449
- logger5.error("[RuntimeMigrator] Destructive operations detected:");
19450
- for (const warning of dataLossCheck.warnings) {
19451
- logger5.error(`[RuntimeMigrator] - ${warning}`);
19452
- }
19453
- logger5.error("[RuntimeMigrator] To proceed with destructive migrations:");
19454
- logger5.error("[RuntimeMigrator] 1. Set environment variable: export ELIZA_ALLOW_DESTRUCTIVE_MIGRATIONS=true");
19455
- logger5.error("[RuntimeMigrator] 2. Or use option: migrate(plugin, schema, { force: true })");
19456
- if (isProduction) {
19457
- logger5.error("[RuntimeMigrator] 3. For production, consider using drizzle-kit for manual migration");
19458
- }
20171
+ logger5.error({
20172
+ src: "plugin:sql",
20173
+ pluginName,
20174
+ environment: isProduction ? "PRODUCTION" : "DEVELOPMENT",
20175
+ warnings: dataLossCheck.warnings
20176
+ }, "Destructive migration blocked - set ELIZA_ALLOW_DESTRUCTIVE_MIGRATIONS=true or use force option");
19459
20177
  const errorMessage = isProduction ? `Destructive migration blocked in production for ${pluginName}. Set ELIZA_ALLOW_DESTRUCTIVE_MIGRATIONS=true or use drizzle-kit.` : `Destructive migration blocked for ${pluginName}. Set ELIZA_ALLOW_DESTRUCTIVE_MIGRATIONS=true to proceed.`;
19460
20178
  throw new Error(errorMessage);
19461
20179
  }
19462
20180
  if (dataLossCheck.requiresConfirmation) {
19463
- logger5.warn("[RuntimeMigrator] Proceeding with destructive migration");
19464
- logger5.warn(`[RuntimeMigrator] Plugin: ${pluginName}`);
19465
- logger5.warn("[RuntimeMigrator] The following operations will be performed:");
19466
- for (const warning of dataLossCheck.warnings) {
19467
- logger5.warn(`[RuntimeMigrator] ⚠️ ${warning}`);
19468
- }
20181
+ logger5.warn({ src: "plugin:sql", pluginName, warnings: dataLossCheck.warnings }, "Proceeding with destructive migration");
19469
20182
  }
19470
20183
  }
19471
20184
  const sqlStatements = await generateMigrationSQL(previousSnapshot, currentSnapshot, diff);
19472
20185
  if (sqlStatements.length === 0) {
19473
- logger5.info(`[RuntimeMigrator] No SQL statements to execute for ${pluginName}`);
20186
+ logger5.info({ src: "plugin:sql", pluginName }, "No SQL statements to execute");
19474
20187
  return;
19475
20188
  }
19476
- logger5.info(`[RuntimeMigrator] Executing ${sqlStatements.length} SQL statements for ${pluginName}`);
20189
+ logger5.info({ src: "plugin:sql", pluginName, statementCount: sqlStatements.length }, "Executing SQL statements");
19477
20190
  if (options.verbose) {
19478
20191
  sqlStatements.forEach((stmt, i2) => {
19479
- logger5.debug(`[RuntimeMigrator] Statement ${i2 + 1}: ${stmt}`);
20192
+ logger5.debug({ src: "plugin:sql", statementIndex: i2 + 1, statement: stmt }, "SQL statement");
19480
20193
  });
19481
20194
  }
19482
20195
  if (options.dryRun) {
19483
- logger5.info("[RuntimeMigrator] DRY RUN mode - not executing statements");
19484
- logger5.info("[RuntimeMigrator] Would execute:");
19485
- sqlStatements.forEach((stmt, i2) => {
19486
- logger5.info(` ${i2 + 1}. ${stmt}`);
19487
- });
20196
+ logger5.info({ src: "plugin:sql", pluginName, statements: sqlStatements }, "DRY RUN mode - not executing statements");
19488
20197
  return;
19489
20198
  }
19490
20199
  await this.executeMigration(pluginName, currentSnapshot, currentHash, sqlStatements);
19491
- logger5.info(`[RuntimeMigrator] Migration completed successfully for ${pluginName}`);
20200
+ logger5.info({ src: "plugin:sql", pluginName }, "Migration completed successfully");
19492
20201
  return;
19493
20202
  } catch (error) {
19494
- logger5.error(`[RuntimeMigrator] Migration failed for ${pluginName}:`, JSON.stringify(error));
20203
+ logger5.error({
20204
+ src: "plugin:sql",
20205
+ pluginName,
20206
+ error: error instanceof Error ? error.message : String(error)
20207
+ }, "Migration failed");
19495
20208
  throw error;
19496
20209
  } finally {
19497
20210
  const postgresUrl = process.env.POSTGRES_URL || process.env.DATABASE_URL || "";
@@ -19500,9 +20213,13 @@ class RuntimeMigrator {
19500
20213
  try {
19501
20214
  const lockIdStr = lockId.toString();
19502
20215
  await this.db.execute(sql22`SELECT pg_advisory_unlock(CAST(${lockIdStr} AS bigint))`);
19503
- logger5.debug(`[RuntimeMigrator] Advisory lock released for ${pluginName}`);
20216
+ logger5.debug({ src: "plugin:sql", pluginName }, "Advisory lock released");
19504
20217
  } catch (unlockError) {
19505
- logger5.warn(`[RuntimeMigrator] Failed to release advisory lock for ${pluginName}:`, JSON.stringify(unlockError));
20218
+ logger5.warn({
20219
+ src: "plugin:sql",
20220
+ pluginName,
20221
+ error: unlockError instanceof Error ? unlockError.message : String(unlockError)
20222
+ }, "Failed to release advisory lock");
19506
20223
  }
19507
20224
  }
19508
20225
  }
@@ -19513,7 +20230,7 @@ class RuntimeMigrator {
19513
20230
  await this.db.execute(sql22`BEGIN`);
19514
20231
  transactionStarted = true;
19515
20232
  for (const stmt of sqlStatements) {
19516
- logger5.debug(`[RuntimeMigrator] Executing: ${stmt}`);
20233
+ logger5.debug({ src: "plugin:sql", statement: stmt }, "Executing SQL statement");
19517
20234
  await this.db.execute(sql22.raw(stmt));
19518
20235
  }
19519
20236
  const idx = await this.journalStorage.getNextIdx(pluginName);
@@ -19522,14 +20239,17 @@ class RuntimeMigrator {
19522
20239
  await this.journalStorage.updateJournal(pluginName, idx, tag, true);
19523
20240
  await this.snapshotStorage.saveSnapshot(pluginName, idx, snapshot);
19524
20241
  await this.db.execute(sql22`COMMIT`);
19525
- logger5.info(`[RuntimeMigrator] Recorded migration ${tag} for ${pluginName}`);
20242
+ logger5.info({ src: "plugin:sql", pluginName, tag }, "Recorded migration");
19526
20243
  } catch (error) {
19527
20244
  if (transactionStarted) {
19528
20245
  try {
19529
20246
  await this.db.execute(sql22`ROLLBACK`);
19530
- logger5.error("[RuntimeMigrator] Migration failed, rolled back:", JSON.stringify(error));
20247
+ logger5.error({ src: "plugin:sql", error: error instanceof Error ? error.message : String(error) }, "Migration failed, rolled back");
19531
20248
  } catch (rollbackError) {
19532
- logger5.error("[RuntimeMigrator] Failed to rollback transaction:", JSON.stringify(rollbackError));
20249
+ logger5.error({
20250
+ src: "plugin:sql",
20251
+ error: rollbackError instanceof Error ? rollbackError.message : String(rollbackError)
20252
+ }, "Failed to rollback transaction");
19533
20253
  }
19534
20254
  }
19535
20255
  throw error;
@@ -19552,31 +20272,35 @@ class RuntimeMigrator {
19552
20272
  };
19553
20273
  }
19554
20274
  async reset(pluginName) {
19555
- logger5.warn(`[RuntimeMigrator] Resetting migrations for ${pluginName}`);
20275
+ logger5.warn({ src: "plugin:sql", pluginName }, "Resetting migrations");
19556
20276
  await this.db.execute(sql22`DELETE FROM migrations._migrations WHERE plugin_name = ${pluginName}`);
19557
20277
  await this.db.execute(sql22`DELETE FROM migrations._journal WHERE plugin_name = ${pluginName}`);
19558
20278
  await this.db.execute(sql22`DELETE FROM migrations._snapshots WHERE plugin_name = ${pluginName}`);
19559
- logger5.warn(`[RuntimeMigrator] Reset complete for ${pluginName}`);
20279
+ logger5.warn({ src: "plugin:sql", pluginName }, "Reset complete");
19560
20280
  }
19561
20281
  async checkMigration(pluginName, schema) {
19562
20282
  try {
19563
- logger5.info(`[RuntimeMigrator] Checking migration for ${pluginName}...`);
20283
+ logger5.info({ src: "plugin:sql", pluginName }, "Checking migration");
19564
20284
  const currentSnapshot = await generateSnapshot(schema);
19565
20285
  const previousSnapshot = await this.snapshotStorage.getLatestSnapshot(pluginName);
19566
20286
  if (!hasChanges(previousSnapshot, currentSnapshot)) {
19567
- logger5.info(`[RuntimeMigrator] No changes detected for ${pluginName}`);
20287
+ logger5.info({ src: "plugin:sql", pluginName }, "No changes detected");
19568
20288
  return null;
19569
20289
  }
19570
20290
  const diff = await calculateDiff(previousSnapshot, currentSnapshot);
19571
20291
  const dataLossCheck = checkForDataLoss(diff);
19572
20292
  if (dataLossCheck.hasDataLoss) {
19573
- logger5.warn(`[RuntimeMigrator] Migration for ${pluginName} would cause data loss`);
20293
+ logger5.warn({ src: "plugin:sql", pluginName }, "Migration would cause data loss");
19574
20294
  } else {
19575
- logger5.info(`[RuntimeMigrator] Migration for ${pluginName} is safe (no data loss)`);
20295
+ logger5.info({ src: "plugin:sql", pluginName }, "Migration is safe (no data loss)");
19576
20296
  }
19577
20297
  return dataLossCheck;
19578
20298
  } catch (error) {
19579
- logger5.error(`[RuntimeMigrator] Failed to check migration for ${pluginName}:`, JSON.stringify(error));
20299
+ logger5.error({
20300
+ src: "plugin:sql",
20301
+ pluginName,
20302
+ error: error instanceof Error ? error.message : String(error)
20303
+ }, "Failed to check migration");
19580
20304
  throw error;
19581
20305
  }
19582
20306
  }
@@ -19598,12 +20322,660 @@ var init_runtime_migrator2 = __esm(() => {
19598
20322
  init_runtime_migrator();
19599
20323
  });
19600
20324
 
20325
+ // src/migrations.ts
20326
+ import { logger as logger6 } from "@elizaos/core";
20327
+ import { sql as sql23 } from "drizzle-orm";
20328
+ async function migrateToEntityRLS(adapter) {
20329
+ const db = adapter.db;
20330
+ try {
20331
+ await db.execute(sql23`SELECT 1 FROM pg_tables LIMIT 1`);
20332
+ } catch {
20333
+ logger6.debug("[Migration] ⊘ Not PostgreSQL, skipping PostgreSQL-specific migrations");
20334
+ return;
20335
+ }
20336
+ logger6.info("[Migration] Starting develop → feat/entity-rls migration...");
20337
+ try {
20338
+ logger6.debug("[Migration] → Clearing RuntimeMigrator snapshot cache...");
20339
+ try {
20340
+ await db.execute(sql23`DELETE FROM migrations._snapshots WHERE plugin_name = '@elizaos/plugin-sql'`);
20341
+ logger6.debug("[Migration] ✓ Snapshot cache cleared");
20342
+ } catch (error) {
20343
+ logger6.debug("[Migration] ⊘ No snapshot cache to clear (migrations schema not yet created)");
20344
+ }
20345
+ logger6.debug("[Migration] → Disabling Row Level Security on all tables...");
20346
+ try {
20347
+ const tablesResult = await db.execute(sql23`
20348
+ SELECT tablename
20349
+ FROM pg_tables
20350
+ WHERE schemaname = 'public'
20351
+ ORDER BY tablename
20352
+ `);
20353
+ for (const row of tablesResult.rows || []) {
20354
+ const tableName = row.tablename;
20355
+ try {
20356
+ await db.execute(sql23.raw(`ALTER TABLE "${tableName}" DISABLE ROW LEVEL SECURITY`));
20357
+ logger6.debug(`[Migration] ✓ Disabled RLS on ${tableName}`);
20358
+ } catch (error) {
20359
+ logger6.debug(`[Migration] ⊘ Could not disable RLS on ${tableName}`);
20360
+ }
20361
+ }
20362
+ } catch (error) {
20363
+ logger6.debug("[Migration] ⊘ Could not disable RLS (may not have permissions)");
20364
+ }
20365
+ logger6.debug("[Migration] → Handling server_id → message_server_id migrations...");
20366
+ const tablesToMigrate = ["channels", "worlds", "rooms"];
20367
+ for (const tableName of tablesToMigrate) {
20368
+ try {
20369
+ const columnsResult = await db.execute(sql23`
20370
+ SELECT column_name, data_type, is_nullable
20371
+ FROM information_schema.columns
20372
+ WHERE table_schema = 'public'
20373
+ AND table_name = ${tableName}
20374
+ AND column_name IN ('server_id', 'message_server_id')
20375
+ ORDER BY column_name
20376
+ `);
20377
+ const columns = columnsResult.rows || [];
20378
+ const serverId = columns.find((c) => c.column_name === "server_id");
20379
+ const messageServerId = columns.find((c) => c.column_name === "message_server_id");
20380
+ if (serverId && !messageServerId) {
20381
+ logger6.debug(`[Migration] → Renaming ${tableName}.server_id to message_server_id...`);
20382
+ await db.execute(sql23.raw(`ALTER TABLE "${tableName}" RENAME COLUMN "server_id" TO "message_server_id"`));
20383
+ logger6.debug(`[Migration] ✓ Renamed ${tableName}.server_id → message_server_id`);
20384
+ if (serverId.data_type === "text") {
20385
+ try {
20386
+ logger6.debug(`[Migration] → Dropping DEFAULT constraint on ${tableName}.message_server_id...`);
20387
+ await db.execute(sql23.raw(`ALTER TABLE "${tableName}" ALTER COLUMN "message_server_id" DROP DEFAULT`));
20388
+ logger6.debug(`[Migration] ✓ Dropped DEFAULT constraint`);
20389
+ logger6.debug(`[Migration] → Converting ${tableName}.message_server_id from text to uuid...`);
20390
+ await db.execute(sql23.raw(`ALTER TABLE "${tableName}" ALTER COLUMN "message_server_id" TYPE uuid USING "message_server_id"::uuid`));
20391
+ logger6.debug(`[Migration] ✓ Converted ${tableName}.message_server_id to uuid`);
20392
+ } catch (convertError) {
20393
+ logger6.warn(`[Migration] ⚠️ Could not convert ${tableName}.message_server_id to uuid - data may not be valid UUIDs`);
20394
+ logger6.debug(`[Migration] → Setting invalid UUIDs to NULL in ${tableName}.message_server_id...`);
20395
+ await db.execute(sql23.raw(`ALTER TABLE "${tableName}" ALTER COLUMN "message_server_id" TYPE uuid USING CASE WHEN "message_server_id" ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' THEN "message_server_id"::uuid ELSE NULL END`));
20396
+ }
20397
+ }
20398
+ if (tableName === "channels") {
20399
+ const nullCountResult = await db.execute(sql23.raw(`SELECT COUNT(*) as count FROM "${tableName}" WHERE "message_server_id" IS NULL`));
20400
+ const nullCount = nullCountResult.rows?.[0]?.count;
20401
+ if (nullCount && parseInt(nullCount) > 0) {
20402
+ logger6.warn(`[Migration] ⚠️ ${tableName} has ${nullCount} rows with NULL message_server_id - these will be deleted`);
20403
+ await db.execute(sql23.raw(`DELETE FROM "${tableName}" WHERE "message_server_id" IS NULL`));
20404
+ logger6.debug(`[Migration] ✓ Deleted ${nullCount} rows with NULL message_server_id from ${tableName}`);
20405
+ }
20406
+ logger6.debug(`[Migration] → Making ${tableName}.message_server_id NOT NULL...`);
20407
+ await db.execute(sql23.raw(`ALTER TABLE "${tableName}" ALTER COLUMN "message_server_id" SET NOT NULL`));
20408
+ logger6.debug(`[Migration] ✓ Set ${tableName}.message_server_id NOT NULL`);
20409
+ }
20410
+ } else if (serverId && messageServerId) {
20411
+ logger6.debug(`[Migration] → ${tableName} has both columns, dropping server_id...`);
20412
+ await db.execute(sql23.raw(`ALTER TABLE "${tableName}" DROP COLUMN "server_id" CASCADE`));
20413
+ logger6.debug(`[Migration] ✓ Dropped ${tableName}.server_id (will be re-added by RuntimeMigrator for RLS)`);
20414
+ } else if (!serverId && messageServerId) {
20415
+ if (messageServerId.data_type === "text") {
20416
+ logger6.debug(`[Migration] → ${tableName}.message_server_id exists but is TEXT, needs UUID conversion...`);
20417
+ logger6.debug(`[Migration] → Dropping DEFAULT constraint on ${tableName}.message_server_id...`);
20418
+ await db.execute(sql23.raw(`ALTER TABLE "${tableName}" ALTER COLUMN "message_server_id" DROP DEFAULT`));
20419
+ logger6.debug(`[Migration] ✓ Dropped DEFAULT constraint`);
20420
+ logger6.debug(`[Migration] → Converting ${tableName}.message_server_id from text to uuid (generating UUIDs from text)...`);
20421
+ await db.execute(sql23.raw(`
20422
+ ALTER TABLE "${tableName}"
20423
+ ALTER COLUMN "message_server_id" TYPE uuid
20424
+ USING CASE
20425
+ WHEN "message_server_id" ~ '^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$'
20426
+ THEN "message_server_id"::uuid
20427
+ ELSE md5("message_server_id")::uuid
20428
+ END
20429
+ `));
20430
+ logger6.debug(`[Migration] ✓ Converted ${tableName}.message_server_id to uuid`);
20431
+ } else {
20432
+ logger6.debug(`[Migration] ⊘ ${tableName}.message_server_id already UUID, skipping`);
20433
+ }
20434
+ } else {
20435
+ logger6.debug(`[Migration] ⊘ ${tableName} already migrated, skipping`);
20436
+ }
20437
+ } catch (error) {
20438
+ logger6.warn(`[Migration] ⚠️ Error migrating ${tableName}.server_id: ${error}`);
20439
+ }
20440
+ }
20441
+ logger6.debug("[Migration] → Dropping all remaining RLS-managed server_id columns...");
20442
+ try {
20443
+ const serverIdColumnsResult = await db.execute(sql23`
20444
+ SELECT table_name
20445
+ FROM information_schema.columns
20446
+ WHERE table_schema = 'public'
20447
+ AND column_name = 'server_id'
20448
+ AND table_name NOT IN (
20449
+ 'servers', -- server_id is the primary key
20450
+ 'agents', -- server_id is in the schema (for RLS)
20451
+ 'channels', -- already handled above
20452
+ 'worlds', -- already handled above
20453
+ 'rooms', -- already handled above
20454
+ 'server_agents', -- server_id is part of composite key
20455
+ 'drizzle_migrations',
20456
+ '__drizzle_migrations'
20457
+ )
20458
+ ORDER BY table_name
20459
+ `);
20460
+ const tablesToClean = serverIdColumnsResult.rows || [];
20461
+ logger6.debug(`[Migration] → Found ${tablesToClean.length} tables with server_id columns`);
20462
+ for (const row of tablesToClean) {
20463
+ const tableName = row.table_name;
20464
+ try {
20465
+ await db.execute(sql23.raw(`ALTER TABLE "${tableName}" DROP COLUMN IF EXISTS server_id CASCADE`));
20466
+ logger6.debug(`[Migration] ✓ Dropped server_id from ${tableName}`);
20467
+ } catch (error) {
20468
+ logger6.debug(`[Migration] ⊘ Could not drop server_id from ${tableName}`);
20469
+ }
20470
+ }
20471
+ } catch (error) {
20472
+ logger6.debug("[Migration] ⊘ Could not drop server_id columns (may not have permissions)");
20473
+ }
20474
+ logger6.debug("[Migration] → Checking server_agents table rename...");
20475
+ try {
20476
+ const tablesResult = await db.execute(sql23`
20477
+ SELECT table_name
20478
+ FROM information_schema.tables
20479
+ WHERE table_schema = 'public'
20480
+ AND table_name IN ('server_agents', 'message_server_agents')
20481
+ ORDER BY table_name
20482
+ `);
20483
+ const tables = tablesResult.rows || [];
20484
+ const hasServerAgents = tables.some((t) => t.table_name === "server_agents");
20485
+ const hasMessageServerAgents = tables.some((t) => t.table_name === "message_server_agents");
20486
+ if (hasServerAgents && !hasMessageServerAgents) {
20487
+ logger6.debug("[Migration] → Renaming server_agents to message_server_agents...");
20488
+ await db.execute(sql23.raw(`ALTER TABLE "server_agents" RENAME TO "message_server_agents"`));
20489
+ logger6.debug("[Migration] ✓ Renamed server_agents → message_server_agents");
20490
+ logger6.debug("[Migration] → Renaming message_server_agents.server_id to message_server_id...");
20491
+ await db.execute(sql23.raw(`ALTER TABLE "message_server_agents" RENAME COLUMN "server_id" TO "message_server_id"`));
20492
+ logger6.debug("[Migration] ✓ Renamed message_server_agents.server_id → message_server_id");
20493
+ } else if (!hasServerAgents && !hasMessageServerAgents) {
20494
+ logger6.debug("[Migration] ⊘ No server_agents table to migrate");
20495
+ } else if (hasMessageServerAgents) {
20496
+ logger6.debug("[Migration] → Checking message_server_agents columns...");
20497
+ const columnsResult = await db.execute(sql23`
20498
+ SELECT column_name
20499
+ FROM information_schema.columns
20500
+ WHERE table_schema = 'public'
20501
+ AND table_name = 'message_server_agents'
20502
+ AND column_name IN ('server_id', 'message_server_id')
20503
+ ORDER BY column_name
20504
+ `);
20505
+ const columns = columnsResult.rows || [];
20506
+ const hasServerId = columns.some((c) => c.column_name === "server_id");
20507
+ const hasMessageServerId = columns.some((c) => c.column_name === "message_server_id");
20508
+ if (hasServerId && !hasMessageServerId) {
20509
+ logger6.debug("[Migration] → Renaming message_server_agents.server_id to message_server_id...");
20510
+ await db.execute(sql23.raw(`ALTER TABLE "message_server_agents" RENAME COLUMN "server_id" TO "message_server_id"`));
20511
+ logger6.debug("[Migration] ✓ Renamed message_server_agents.server_id → message_server_id");
20512
+ } else if (!hasServerId && !hasMessageServerId) {
20513
+ logger6.debug("[Migration] → message_server_agents exists without required columns, truncating...");
20514
+ await db.execute(sql23`TRUNCATE TABLE message_server_agents CASCADE`);
20515
+ logger6.debug("[Migration] ✓ Truncated message_server_agents");
20516
+ } else {
20517
+ logger6.debug("[Migration] ⊘ message_server_agents already has correct schema");
20518
+ }
20519
+ }
20520
+ } catch (error) {
20521
+ logger6.debug("[Migration] ⊘ Could not check/migrate server_agents table");
20522
+ }
20523
+ logger6.debug("[Migration] → Checking channel_participants table...");
20524
+ try {
20525
+ const columnsResult = await db.execute(sql23`
20526
+ SELECT column_name
20527
+ FROM information_schema.columns
20528
+ WHERE table_schema = 'public'
20529
+ AND table_name = 'channel_participants'
20530
+ AND column_name IN ('user_id', 'entity_id')
20531
+ ORDER BY column_name
20532
+ `);
20533
+ const columns = columnsResult.rows || [];
20534
+ const hasUserId = columns.some((c) => c.column_name === "user_id");
20535
+ const hasEntityId = columns.some((c) => c.column_name === "entity_id");
20536
+ if (hasUserId && !hasEntityId) {
20537
+ logger6.debug("[Migration] → Renaming channel_participants.user_id to entity_id...");
20538
+ await db.execute(sql23.raw(`ALTER TABLE "channel_participants" RENAME COLUMN "user_id" TO "entity_id"`));
20539
+ logger6.debug("[Migration] ✓ Renamed channel_participants.user_id → entity_id");
20540
+ } else if (!hasUserId && !hasEntityId) {
20541
+ logger6.debug("[Migration] → channel_participants exists without entity_id or user_id, truncating...");
20542
+ await db.execute(sql23`TRUNCATE TABLE channel_participants CASCADE`);
20543
+ logger6.debug("[Migration] ✓ Truncated channel_participants");
20544
+ } else {
20545
+ logger6.debug("[Migration] ⊘ channel_participants already has entity_id column");
20546
+ }
20547
+ } catch (error) {
20548
+ logger6.debug("[Migration] ⊘ Could not check/migrate channel_participants");
20549
+ }
20550
+ logger6.debug("[Migration] → Discovering and dropping all regular indexes...");
20551
+ try {
20552
+ const indexesResult = await db.execute(sql23`
20553
+ SELECT i.relname AS index_name
20554
+ FROM pg_index idx
20555
+ JOIN pg_class i ON i.oid = idx.indexrelid
20556
+ JOIN pg_class c ON c.oid = idx.indrelid
20557
+ JOIN pg_namespace n ON n.oid = c.relnamespace
20558
+ LEFT JOIN pg_constraint con ON con.conindid = idx.indexrelid
20559
+ WHERE n.nspname = 'public'
20560
+ AND NOT idx.indisprimary -- Not a primary key
20561
+ AND con.contype IS NULL -- Not a constraint (unique, etc)
20562
+ ORDER BY i.relname
20563
+ `);
20564
+ const indexesToDrop = indexesResult.rows || [];
20565
+ logger6.debug(`[Migration] → Found ${indexesToDrop.length} indexes to drop`);
20566
+ for (const row of indexesToDrop) {
20567
+ const indexName = row.index_name;
20568
+ try {
20569
+ await db.execute(sql23.raw(`DROP INDEX IF EXISTS "${indexName}"`));
20570
+ logger6.debug(`[Migration] ✓ Dropped index ${indexName}`);
20571
+ } catch (error) {
20572
+ logger6.debug(`[Migration] ⊘ Could not drop index ${indexName}`);
20573
+ }
20574
+ }
20575
+ } catch (error) {
20576
+ logger6.debug("[Migration] ⊘ Could not drop indexes (may not have permissions)");
20577
+ }
20578
+ logger6.info("[Migration] ✓ Migration complete - develop to feat/entity-rls migration finished");
20579
+ } catch (error) {
20580
+ logger6.error("[Migration] Migration failed:", String(error));
20581
+ throw error;
20582
+ }
20583
+ }
20584
+ var init_migrations = () => {};
20585
+
20586
+ // src/rls.ts
20587
+ import { logger as logger7, validateUuid } from "@elizaos/core";
20588
+ import { sql as sql24, eq } from "drizzle-orm";
20589
+ async function installRLSFunctions(adapter) {
20590
+ const db = adapter.db;
20591
+ await db.execute(sql24`
20592
+ CREATE TABLE IF NOT EXISTS servers (
20593
+ id UUID PRIMARY KEY,
20594
+ created_at TIMESTAMPTZ DEFAULT NOW() NOT NULL,
20595
+ updated_at TIMESTAMPTZ DEFAULT NOW() NOT NULL
20596
+ )
20597
+ `);
20598
+ await db.execute(sql24`
20599
+ CREATE OR REPLACE FUNCTION current_server_id() RETURNS UUID AS $$
20600
+ DECLARE
20601
+ app_name TEXT;
20602
+ BEGIN
20603
+ app_name := NULLIF(current_setting('application_name', TRUE), '');
20604
+
20605
+ -- Return NULL if application_name is not set or not a valid UUID
20606
+ -- This allows admin queries to work without RLS restrictions
20607
+ BEGIN
20608
+ RETURN app_name::UUID;
20609
+ EXCEPTION WHEN OTHERS THEN
20610
+ RETURN NULL;
20611
+ END;
20612
+ END;
20613
+ $$ LANGUAGE plpgsql STABLE;
20614
+ `);
20615
+ await db.execute(sql24`
20616
+ CREATE OR REPLACE FUNCTION add_server_isolation(
20617
+ schema_name text,
20618
+ table_name text
20619
+ ) RETURNS void AS $$
20620
+ DECLARE
20621
+ full_table_name text;
20622
+ column_exists boolean;
20623
+ orphaned_count bigint;
20624
+ BEGIN
20625
+ full_table_name := schema_name || '.' || table_name;
20626
+
20627
+ -- Check if server_id column already exists
20628
+ SELECT EXISTS (
20629
+ SELECT 1 FROM information_schema.columns
20630
+ WHERE information_schema.columns.table_schema = schema_name
20631
+ AND information_schema.columns.table_name = add_server_isolation.table_name
20632
+ AND information_schema.columns.column_name = 'server_id'
20633
+ ) INTO column_exists;
20634
+
20635
+ -- Add server_id column if missing (DEFAULT populates it automatically for new rows)
20636
+ IF NOT column_exists THEN
20637
+ EXECUTE format('ALTER TABLE %I.%I ADD COLUMN server_id UUID DEFAULT current_server_id()', schema_name, table_name);
20638
+
20639
+ -- Backfill existing rows with current server_id
20640
+ -- This ensures all existing data belongs to the server instance that is enabling RLS
20641
+ EXECUTE format('UPDATE %I.%I SET server_id = current_server_id() WHERE server_id IS NULL', schema_name, table_name);
20642
+ ELSE
20643
+ -- Column already exists (RLS was previously enabled then disabled)
20644
+ -- Restore the DEFAULT clause (may have been removed during uninstallRLS)
20645
+ EXECUTE format('ALTER TABLE %I.%I ALTER COLUMN server_id SET DEFAULT current_server_id()', schema_name, table_name);
20646
+
20647
+ -- Only backfill NULL server_id rows, do NOT steal data from other servers
20648
+ EXECUTE format('SELECT COUNT(*) FROM %I.%I WHERE server_id IS NULL', schema_name, table_name) INTO orphaned_count;
20649
+
20650
+ IF orphaned_count > 0 THEN
20651
+ RAISE NOTICE 'Backfilling % rows with NULL server_id in %.%', orphaned_count, schema_name, table_name;
20652
+ EXECUTE format('UPDATE %I.%I SET server_id = current_server_id() WHERE server_id IS NULL', schema_name, table_name);
20653
+ END IF;
20654
+ END IF;
20655
+
20656
+ -- Create index for efficient server_id filtering
20657
+ EXECUTE format('CREATE INDEX IF NOT EXISTS idx_%I_server_id ON %I.%I(server_id)', table_name, schema_name, table_name);
20658
+
20659
+ -- Enable RLS on the table
20660
+ EXECUTE format('ALTER TABLE %I.%I ENABLE ROW LEVEL SECURITY', schema_name, table_name);
20661
+
20662
+ -- FORCE RLS even for table owners (critical for security)
20663
+ EXECUTE format('ALTER TABLE %I.%I FORCE ROW LEVEL SECURITY', schema_name, table_name);
20664
+
20665
+ -- Drop existing policy if present
20666
+ EXECUTE format('DROP POLICY IF EXISTS server_isolation_policy ON %I.%I', schema_name, table_name);
20667
+
20668
+ -- Create isolation policy: users can only see/modify rows where server_id matches current server instance
20669
+ -- No NULL clause - all rows must have a valid server_id (backfilled during column addition)
20670
+ EXECUTE format('
20671
+ CREATE POLICY server_isolation_policy ON %I.%I
20672
+ USING (server_id = current_server_id())
20673
+ WITH CHECK (server_id = current_server_id())
20674
+ ', schema_name, table_name);
20675
+ END;
20676
+ $$ LANGUAGE plpgsql;
20677
+ `);
20678
+ await db.execute(sql24`
20679
+ CREATE OR REPLACE FUNCTION apply_rls_to_all_tables() RETURNS void AS $$
20680
+ DECLARE
20681
+ tbl record;
20682
+ BEGIN
20683
+ FOR tbl IN
20684
+ SELECT schemaname, tablename
20685
+ FROM pg_tables
20686
+ WHERE schemaname = 'public'
20687
+ AND tablename NOT IN (
20688
+ 'servers',
20689
+ 'drizzle_migrations',
20690
+ '__drizzle_migrations'
20691
+ )
20692
+ LOOP
20693
+ BEGIN
20694
+ PERFORM add_server_isolation(tbl.schemaname, tbl.tablename);
20695
+ EXCEPTION WHEN OTHERS THEN
20696
+ RAISE WARNING 'Failed to apply RLS to %.%: %', tbl.schemaname, tbl.tablename, SQLERRM;
20697
+ END;
20698
+ END LOOP;
20699
+ END;
20700
+ $$ LANGUAGE plpgsql;
20701
+ `);
20702
+ logger7.info({ src: "plugin:sql" }, "RLS PostgreSQL functions installed");
20703
+ await installEntityRLS(adapter);
20704
+ }
20705
+ async function applyRLSToNewTables(adapter) {
20706
+ const db = adapter.db;
20707
+ try {
20708
+ await db.execute(sql24`SELECT apply_rls_to_all_tables()`);
20709
+ logger7.info({ src: "plugin:sql" }, "RLS applied to all tables");
20710
+ } catch (error) {
20711
+ logger7.warn({ src: "plugin:sql", error: String(error) }, "Failed to apply RLS to some tables");
20712
+ }
20713
+ }
20714
+ async function installEntityRLS(adapter) {
20715
+ const db = adapter.db;
20716
+ logger7.info("[Entity RLS] Installing entity RLS functions and policies...");
20717
+ await db.execute(sql24`
20718
+ CREATE OR REPLACE FUNCTION current_entity_id()
20719
+ RETURNS UUID AS $$
20720
+ DECLARE
20721
+ entity_id_text TEXT;
20722
+ BEGIN
20723
+ -- Read from transaction-local variable
20724
+ entity_id_text := NULLIF(current_setting('app.entity_id', TRUE), '');
20725
+
20726
+ IF entity_id_text IS NULL OR entity_id_text = '' THEN
20727
+ RETURN NULL;
20728
+ END IF;
20729
+
20730
+ BEGIN
20731
+ RETURN entity_id_text::UUID;
20732
+ EXCEPTION WHEN OTHERS THEN
20733
+ RETURN NULL;
20734
+ END;
20735
+ END;
20736
+ $$ LANGUAGE plpgsql STABLE;
20737
+ `);
20738
+ logger7.info("[Entity RLS] Created current_entity_id() function");
20739
+ await db.execute(sql24`
20740
+ CREATE OR REPLACE FUNCTION add_entity_isolation(
20741
+ schema_name text,
20742
+ table_name text,
20743
+ require_entity boolean DEFAULT false
20744
+ ) RETURNS void AS $$
20745
+ DECLARE
20746
+ full_table_name text;
20747
+ has_entity_id boolean;
20748
+ has_author_id boolean;
20749
+ has_channel_id boolean;
20750
+ has_room_id boolean;
20751
+ entity_column_name text;
20752
+ room_column_name text;
20753
+ BEGIN
20754
+ full_table_name := schema_name || '.' || table_name;
20755
+
20756
+ -- Check which columns exist (using camelCase as per schema definition)
20757
+ SELECT EXISTS (
20758
+ SELECT 1 FROM information_schema.columns
20759
+ WHERE information_schema.columns.table_schema = schema_name
20760
+ AND information_schema.columns.table_name = add_entity_isolation.table_name
20761
+ AND information_schema.columns.column_name = 'entityId'
20762
+ ) INTO has_entity_id;
20763
+
20764
+ SELECT EXISTS (
20765
+ SELECT 1 FROM information_schema.columns
20766
+ WHERE information_schema.columns.table_schema = schema_name
20767
+ AND information_schema.columns.table_name = add_entity_isolation.table_name
20768
+ AND information_schema.columns.column_name = 'authorId'
20769
+ ) INTO has_author_id;
20770
+
20771
+ SELECT EXISTS (
20772
+ SELECT 1 FROM information_schema.columns
20773
+ WHERE information_schema.columns.table_schema = schema_name
20774
+ AND information_schema.columns.table_name = add_entity_isolation.table_name
20775
+ AND information_schema.columns.column_name = 'roomId'
20776
+ ) INTO has_room_id;
20777
+
20778
+ -- Skip if no entity-related columns
20779
+ IF NOT (has_entity_id OR has_author_id OR has_room_id) THEN
20780
+ RAISE NOTICE '[Entity RLS] Skipping %.%: no entity columns found', schema_name, table_name;
20781
+ RETURN;
20782
+ END IF;
20783
+
20784
+ -- Determine which column to use for entity filtering
20785
+ -- Priority: roomId (shared access via participants) > entityId/authorId (direct access)
20786
+ --
20787
+ -- SPECIAL CASE: participants table must use direct entityId to avoid infinite recursion
20788
+ IF table_name = 'participants' AND has_entity_id THEN
20789
+ entity_column_name := 'entityId';
20790
+ room_column_name := NULL;
20791
+ ELSIF has_room_id THEN
20792
+ room_column_name := 'roomId';
20793
+ entity_column_name := NULL;
20794
+ ELSIF has_entity_id THEN
20795
+ entity_column_name := 'entityId';
20796
+ room_column_name := NULL;
20797
+ ELSIF has_author_id THEN
20798
+ entity_column_name := 'authorId';
20799
+ room_column_name := NULL;
20800
+ ELSE
20801
+ entity_column_name := NULL;
20802
+ room_column_name := NULL;
20803
+ END IF;
20804
+
20805
+ -- Enable RLS on the table
20806
+ EXECUTE format('ALTER TABLE %I.%I ENABLE ROW LEVEL SECURITY', schema_name, table_name);
20807
+ EXECUTE format('ALTER TABLE %I.%I FORCE ROW LEVEL SECURITY', schema_name, table_name);
20808
+
20809
+ -- Drop existing entity policies if present
20810
+ EXECUTE format('DROP POLICY IF EXISTS entity_isolation_policy ON %I.%I', schema_name, table_name);
20811
+
20812
+ -- CASE 1: Table has roomId or channelId (shared access via participants)
20813
+ IF room_column_name IS NOT NULL THEN
20814
+ -- Determine the corresponding column name in participants table
20815
+ -- If the table has roomId, look for roomId in participants.roomId
20816
+ -- participants table uses: entityId (for participant), roomId (for room)
20817
+ -- RESTRICTIVE: Must pass BOTH server RLS AND entity RLS (combined with AND)
20818
+
20819
+ -- Build policy with or without NULL check based on require_entity parameter
20820
+ IF require_entity THEN
20821
+ -- STRICT MODE: Entity context is REQUIRED (blocks NULL entity_id)
20822
+ EXECUTE format('
20823
+ CREATE POLICY entity_isolation_policy ON %I.%I
20824
+ AS RESTRICTIVE
20825
+ USING (
20826
+ current_entity_id() IS NOT NULL
20827
+ AND %I IN (
20828
+ SELECT "roomId"
20829
+ FROM participants
20830
+ WHERE "entityId" = current_entity_id()
20831
+ )
20832
+ )
20833
+ WITH CHECK (
20834
+ current_entity_id() IS NOT NULL
20835
+ AND %I IN (
20836
+ SELECT "roomId"
20837
+ FROM participants
20838
+ WHERE "entityId" = current_entity_id()
20839
+ )
20840
+ )
20841
+ ', schema_name, table_name, room_column_name, room_column_name);
20842
+ RAISE NOTICE '[Entity RLS] Applied STRICT RESTRICTIVE to %.% (via % → participants.roomId, entity REQUIRED)', schema_name, table_name, room_column_name;
20843
+ ELSE
20844
+ -- PERMISSIVE MODE: NULL entity_id allows system/admin access
20845
+ EXECUTE format('
20846
+ CREATE POLICY entity_isolation_policy ON %I.%I
20847
+ AS RESTRICTIVE
20848
+ USING (
20849
+ current_entity_id() IS NULL
20850
+ OR %I IN (
20851
+ SELECT "roomId"
20852
+ FROM participants
20853
+ WHERE "entityId" = current_entity_id()
20854
+ )
20855
+ )
20856
+ WITH CHECK (
20857
+ current_entity_id() IS NULL
20858
+ OR %I IN (
20859
+ SELECT "roomId"
20860
+ FROM participants
20861
+ WHERE "entityId" = current_entity_id()
20862
+ )
20863
+ )
20864
+ ', schema_name, table_name, room_column_name, room_column_name);
20865
+ RAISE NOTICE '[Entity RLS] Applied PERMISSIVE RESTRICTIVE to %.% (via % → participants.roomId, NULL allowed)', schema_name, table_name, room_column_name;
20866
+ END IF;
20867
+
20868
+ -- CASE 2: Table has direct entity_id or author_id column
20869
+ ELSIF entity_column_name IS NOT NULL THEN
20870
+ -- RESTRICTIVE: Must pass BOTH server RLS AND entity RLS (combined with AND)
20871
+
20872
+ IF require_entity THEN
20873
+ -- STRICT MODE: Entity context is REQUIRED
20874
+ EXECUTE format('
20875
+ CREATE POLICY entity_isolation_policy ON %I.%I
20876
+ AS RESTRICTIVE
20877
+ USING (
20878
+ current_entity_id() IS NOT NULL
20879
+ AND %I = current_entity_id()
20880
+ )
20881
+ WITH CHECK (
20882
+ current_entity_id() IS NOT NULL
20883
+ AND %I = current_entity_id()
20884
+ )
20885
+ ', schema_name, table_name, entity_column_name, entity_column_name);
20886
+ RAISE NOTICE '[Entity RLS] Applied STRICT RESTRICTIVE to %.% (direct column: %, entity REQUIRED)', schema_name, table_name, entity_column_name;
20887
+ ELSE
20888
+ -- PERMISSIVE MODE: NULL entity_id allows system/admin access
20889
+ EXECUTE format('
20890
+ CREATE POLICY entity_isolation_policy ON %I.%I
20891
+ AS RESTRICTIVE
20892
+ USING (
20893
+ current_entity_id() IS NULL
20894
+ OR %I = current_entity_id()
20895
+ )
20896
+ WITH CHECK (
20897
+ current_entity_id() IS NULL
20898
+ OR %I = current_entity_id()
20899
+ )
20900
+ ', schema_name, table_name, entity_column_name, entity_column_name);
20901
+ RAISE NOTICE '[Entity RLS] Applied PERMISSIVE RESTRICTIVE to %.% (direct column: %, NULL allowed)', schema_name, table_name, entity_column_name;
20902
+ END IF;
20903
+ END IF;
20904
+
20905
+ -- Create indexes for efficient entity filtering
20906
+ IF room_column_name IS NOT NULL THEN
20907
+ EXECUTE format('CREATE INDEX IF NOT EXISTS idx_%I_room ON %I.%I(%I)',
20908
+ table_name, schema_name, table_name, room_column_name);
20909
+ END IF;
20910
+
20911
+ IF entity_column_name IS NOT NULL THEN
20912
+ EXECUTE format('CREATE INDEX IF NOT EXISTS idx_%I_entity ON %I.%I(%I)',
20913
+ table_name, schema_name, table_name, entity_column_name);
20914
+ END IF;
20915
+ END;
20916
+ $$ LANGUAGE plpgsql;
20917
+ `);
20918
+ logger7.info("[Entity RLS] Created add_entity_isolation() function");
20919
+ await db.execute(sql24`
20920
+ CREATE OR REPLACE FUNCTION apply_entity_rls_to_all_tables() RETURNS void AS $$
20921
+ DECLARE
20922
+ tbl record;
20923
+ require_entity_for_table boolean;
20924
+ BEGIN
20925
+ FOR tbl IN
20926
+ SELECT schemaname, tablename
20927
+ FROM pg_tables
20928
+ WHERE schemaname = 'public'
20929
+ AND tablename NOT IN (
20930
+ 'servers', -- Server RLS table
20931
+ 'users', -- Authentication table (no entity isolation needed)
20932
+ 'entity_mappings', -- Mapping table (no entity isolation needed)
20933
+ 'drizzle_migrations', -- Migration tracking
20934
+ '__drizzle_migrations' -- Migration tracking
20935
+ )
20936
+ LOOP
20937
+ BEGIN
20938
+ -- Apply STRICT mode (require_entity=true) to sensitive user-facing tables
20939
+ -- These tables MUST have entity context set to access data
20940
+ -- STRICT tables: memories, logs, components, tasks (user data requiring isolation)
20941
+ -- NOTE: Excluded tables:
20942
+ -- - 'participants': Adding participants is a privileged operation during initialization
20943
+ IF tbl.tablename IN ('memories', 'logs', 'components', 'tasks') THEN
20944
+ require_entity_for_table := true;
20945
+ ELSE
20946
+ -- PERMISSIVE mode (require_entity=false) for system/privileged tables
20947
+ -- This includes: participants, rooms, channels, entities, etc.
20948
+ require_entity_for_table := false;
20949
+ END IF;
20950
+
20951
+ PERFORM add_entity_isolation(tbl.schemaname, tbl.tablename, require_entity_for_table);
20952
+ EXCEPTION WHEN OTHERS THEN
20953
+ RAISE WARNING '[Entity RLS] Failed to apply to %.%: %', tbl.schemaname, tbl.tablename, SQLERRM;
20954
+ END;
20955
+ END LOOP;
20956
+ END;
20957
+ $$ LANGUAGE plpgsql;
20958
+ `);
20959
+ logger7.info("[Entity RLS] Created apply_entity_rls_to_all_tables() function");
20960
+ logger7.info("[Entity RLS] Entity RLS functions installed successfully");
20961
+ }
20962
+ async function applyEntityRLSToAllTables(adapter) {
20963
+ const db = adapter.db;
20964
+ try {
20965
+ await db.execute(sql24`SELECT apply_entity_rls_to_all_tables()`);
20966
+ logger7.info("[Entity RLS] Applied entity RLS to all eligible tables");
20967
+ } catch (error) {
20968
+ logger7.warn("[Entity RLS] Failed to apply entity RLS to some tables:", String(error));
20969
+ }
20970
+ }
20971
+ var init_rls = () => {};
20972
+
19601
20973
  // src/migration-service.ts
19602
20974
  var exports_migration_service = {};
19603
20975
  __export(exports_migration_service, {
19604
20976
  DatabaseMigrationService: () => DatabaseMigrationService
19605
20977
  });
19606
- import { logger as logger6 } from "@elizaos/core";
20978
+ import { logger as logger8 } from "@elizaos/core";
19607
20979
 
19608
20980
  class DatabaseMigrationService {
19609
20981
  db = null;
@@ -19612,22 +20984,26 @@ class DatabaseMigrationService {
19612
20984
  constructor() {}
19613
20985
  async initializeWithDatabase(db) {
19614
20986
  this.db = db;
20987
+ await migrateToEntityRLS({ db });
19615
20988
  this.migrator = new RuntimeMigrator(db);
19616
20989
  await this.migrator.initialize();
19617
- logger6.info("DatabaseMigrationService initialized with database and runtime migrator");
20990
+ logger8.info({ src: "plugin:sql" }, "DatabaseMigrationService initialized");
19618
20991
  }
19619
20992
  discoverAndRegisterPluginSchemas(plugins) {
19620
20993
  for (const plugin of plugins) {
19621
20994
  if (plugin.schema) {
19622
20995
  this.registeredSchemas.set(plugin.name, plugin.schema);
19623
- logger6.info(`Registered schema for plugin: ${plugin.name}`);
19624
20996
  }
19625
20997
  }
19626
- logger6.info(`Discovered ${this.registeredSchemas.size} plugin schemas out of ${plugins.length} plugins`);
20998
+ logger8.info({
20999
+ src: "plugin:sql",
21000
+ schemasDiscovered: this.registeredSchemas.size,
21001
+ totalPlugins: plugins.length
21002
+ }, "Plugin schemas discovered");
19627
21003
  }
19628
21004
  registerSchema(pluginName, schema) {
19629
21005
  this.registeredSchemas.set(pluginName, schema);
19630
- logger6.info(`Registered schema for plugin: ${pluginName}`);
21006
+ logger8.debug({ src: "plugin:sql", pluginName }, "Schema registered");
19631
21007
  }
19632
21008
  async runAllPluginMigrations(options) {
19633
21009
  if (!this.db || !this.migrator) {
@@ -19639,12 +21015,12 @@ class DatabaseMigrationService {
19639
21015
  force: options?.force ?? false,
19640
21016
  dryRun: options?.dryRun ?? false
19641
21017
  };
19642
- logger6.info("[DatabaseMigrationService] Starting migrations");
19643
- logger6.info(`[DatabaseMigrationService] Environment: ${isProduction ? "PRODUCTION" : "DEVELOPMENT"}`);
19644
- logger6.info(`[DatabaseMigrationService] Plugins to migrate: ${this.registeredSchemas.size}`);
19645
- if (migrationOptions.dryRun) {
19646
- logger6.info("[DatabaseMigrationService] DRY RUN mode - no changes will be applied");
19647
- }
21018
+ logger8.info({
21019
+ src: "plugin:sql",
21020
+ environment: isProduction ? "PRODUCTION" : "DEVELOPMENT",
21021
+ pluginCount: this.registeredSchemas.size,
21022
+ dryRun: migrationOptions.dryRun
21023
+ }, "Starting migrations");
19648
21024
  let successCount = 0;
19649
21025
  let failureCount = 0;
19650
21026
  const errors = [];
@@ -19652,27 +21028,37 @@ class DatabaseMigrationService {
19652
21028
  try {
19653
21029
  await this.migrator.migrate(pluginName, schema, migrationOptions);
19654
21030
  successCount++;
19655
- logger6.info(`[DatabaseMigrationService] Completed: ${pluginName}`);
21031
+ logger8.info({ src: "plugin:sql", pluginName }, "Migration completed");
19656
21032
  } catch (error) {
19657
21033
  failureCount++;
19658
21034
  const errorMessage = error.message;
19659
21035
  errors.push({ pluginName, error });
19660
21036
  if (errorMessage.includes("Destructive migration blocked")) {
19661
- logger6.error(`[DatabaseMigrationService] Blocked: ${pluginName} (destructive changes detected)`);
19662
- if (!migrationOptions.force && process.env.ELIZA_ALLOW_DESTRUCTIVE_MIGRATIONS !== "true") {
19663
- logger6.error("[DatabaseMigrationService] To allow destructive migrations:");
19664
- logger6.error("[DatabaseMigrationService] - Set ELIZA_ALLOW_DESTRUCTIVE_MIGRATIONS=true");
19665
- logger6.error("[DatabaseMigrationService] - Or pass { force: true } to this method");
19666
- }
21037
+ logger8.error({ src: "plugin:sql", pluginName }, "Migration blocked - destructive changes detected. Set ELIZA_ALLOW_DESTRUCTIVE_MIGRATIONS=true or use force option");
19667
21038
  } else {
19668
- logger6.error(`[DatabaseMigrationService] Failed: ${pluginName}`, JSON.stringify(error));
21039
+ logger8.error({ src: "plugin:sql", pluginName, error: errorMessage }, "Migration failed");
19669
21040
  }
19670
21041
  }
19671
21042
  }
19672
21043
  if (failureCount === 0) {
19673
- logger6.info(`[DatabaseMigrationService] All ${successCount} migrations completed successfully`);
21044
+ logger8.info({ src: "plugin:sql", successCount }, "All migrations completed successfully");
21045
+ const dataIsolationEnabled = process.env.ENABLE_DATA_ISOLATION === "true";
21046
+ if (dataIsolationEnabled) {
21047
+ try {
21048
+ logger8.info({ src: "plugin:sql" }, "Re-applying Row Level Security...");
21049
+ await installRLSFunctions({ db: this.db });
21050
+ await applyRLSToNewTables({ db: this.db });
21051
+ await applyEntityRLSToAllTables({ db: this.db });
21052
+ logger8.info({ src: "plugin:sql" }, "RLS re-applied successfully");
21053
+ } catch (rlsError) {
21054
+ const errorMsg = rlsError instanceof Error ? rlsError.message : String(rlsError);
21055
+ logger8.warn({ src: "plugin:sql", error: errorMsg }, "Failed to re-apply RLS (this is OK if server_id columns are not yet in schemas)");
21056
+ }
21057
+ } else {
21058
+ logger8.info({ src: "plugin:sql" }, "Skipping RLS re-application (ENABLE_DATA_ISOLATION is not true)");
21059
+ }
19674
21060
  } else {
19675
- logger6.error(`[DatabaseMigrationService] Migrations failed: ${failureCount} failed, ${successCount} succeeded`);
21061
+ logger8.error({ src: "plugin:sql", failureCount, successCount }, "Some migrations failed");
19676
21062
  const errorSummary = errors.map((e) => `${e.pluginName}: ${e.error.message}`).join(`
19677
21063
  `);
19678
21064
  throw new Error(`${failureCount} migration(s) failed:
@@ -19685,38 +21071,40 @@ class DatabaseMigrationService {
19685
21071
  }
19686
21072
  var init_migration_service = __esm(() => {
19687
21073
  init_runtime_migrator2();
21074
+ init_migrations();
21075
+ init_rls();
19688
21076
  });
19689
21077
 
19690
21078
  // src/index.browser.ts
19691
21079
  import {
19692
- logger as logger9
21080
+ logger as logger11
19693
21081
  } from "@elizaos/core/browser";
19694
21082
 
19695
21083
  // src/pglite/adapter.ts
19696
- import { logger as logger8 } from "@elizaos/core";
21084
+ import { logger as logger10 } from "@elizaos/core";
19697
21085
  import { drizzle } from "drizzle-orm/pglite";
19698
21086
 
19699
21087
  // src/base.ts
19700
21088
  import {
19701
21089
  ChannelType,
19702
21090
  DatabaseAdapter,
19703
- logger as logger7
21091
+ logger as logger9
19704
21092
  } from "@elizaos/core";
19705
21093
  import {
19706
21094
  and,
19707
21095
  cosineDistance,
19708
21096
  count,
19709
21097
  desc,
19710
- eq,
21098
+ eq as eq2,
19711
21099
  gte,
19712
21100
  inArray,
19713
21101
  lt,
19714
21102
  lte,
19715
21103
  or,
19716
- sql as sql23
21104
+ sql as sql25
19717
21105
  } from "drizzle-orm";
19718
21106
 
19719
- // node_modules/uuid/dist/esm-browser/stringify.js
21107
+ // ../../node_modules/uuid/dist/stringify.js
19720
21108
  var byteToHex = [];
19721
21109
  for (let i = 0;i < 256; ++i) {
19722
21110
  byteToHex.push((i + 256).toString(16).slice(1));
@@ -19725,7 +21113,7 @@ function unsafeStringify(arr, offset = 0) {
19725
21113
  return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + "-" + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + "-" + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + "-" + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + "-" + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase();
19726
21114
  }
19727
21115
 
19728
- // node_modules/uuid/dist/esm-browser/rng.js
21116
+ // ../../node_modules/uuid/dist/rng.js
19729
21117
  var getRandomValues;
19730
21118
  var rnds8 = new Uint8Array(16);
19731
21119
  function rng() {
@@ -19738,15 +21126,12 @@ function rng() {
19738
21126
  return getRandomValues(rnds8);
19739
21127
  }
19740
21128
 
19741
- // node_modules/uuid/dist/esm-browser/native.js
21129
+ // ../../node_modules/uuid/dist/native.js
19742
21130
  var randomUUID = typeof crypto !== "undefined" && crypto.randomUUID && crypto.randomUUID.bind(crypto);
19743
21131
  var native_default = { randomUUID };
19744
21132
 
19745
- // node_modules/uuid/dist/esm-browser/v4.js
19746
- function v4(options, buf, offset) {
19747
- if (native_default.randomUUID && !buf && !options) {
19748
- return native_default.randomUUID();
19749
- }
21133
+ // ../../node_modules/uuid/dist/v4.js
21134
+ function _v4(options, buf, offset) {
19750
21135
  options = options || {};
19751
21136
  const rnds = options.random ?? options.rng?.() ?? rng();
19752
21137
  if (rnds.length < 16) {
@@ -19766,6 +21151,12 @@ function v4(options, buf, offset) {
19766
21151
  }
19767
21152
  return unsafeStringify(rnds);
19768
21153
  }
21154
+ function v4(options, buf, offset) {
21155
+ if (native_default.randomUUID && !buf && !options) {
21156
+ return native_default.randomUUID();
21157
+ }
21158
+ return _v4(options, buf, offset);
21159
+ }
19769
21160
  var v4_default = v4;
19770
21161
  // src/schema/embedding.ts
19771
21162
  import { sql as sql5 } from "drizzle-orm";
@@ -19773,6 +21164,7 @@ import { check as check2, foreignKey as foreignKey2, index as index2, pgTable as
19773
21164
  import { VECTOR_DIMS } from "@elizaos/core";
19774
21165
 
19775
21166
  // src/schema/memory.ts
21167
+ init_agent();
19776
21168
  import { relations, sql as sql4 } from "drizzle-orm";
19777
21169
  import {
19778
21170
  boolean as boolean2,
@@ -19786,30 +21178,8 @@ import {
19786
21178
  uuid as uuid4
19787
21179
  } from "drizzle-orm/pg-core";
19788
21180
 
19789
- // src/schema/agent.ts
19790
- import { sql } from "drizzle-orm";
19791
- import { boolean, jsonb, pgTable, text, timestamp, uuid } from "drizzle-orm/pg-core";
19792
- var agentTable = pgTable("agents", {
19793
- id: uuid("id").primaryKey().defaultRandom(),
19794
- enabled: boolean("enabled").default(true).notNull(),
19795
- owner_id: uuid("owner_id"),
19796
- createdAt: timestamp("created_at", { withTimezone: true }).default(sql`now()`).notNull(),
19797
- updatedAt: timestamp("updated_at", { withTimezone: true }).default(sql`now()`).notNull(),
19798
- name: text("name").notNull(),
19799
- username: text("username"),
19800
- system: text("system").default(""),
19801
- bio: jsonb("bio").$type().default(sql`'[]'::jsonb`),
19802
- messageExamples: jsonb("message_examples").$type().default(sql`'[]'::jsonb`).notNull(),
19803
- postExamples: jsonb("post_examples").$type().default(sql`'[]'::jsonb`).notNull(),
19804
- topics: jsonb("topics").$type().default(sql`'[]'::jsonb`).notNull(),
19805
- adjectives: jsonb("adjectives").$type().default(sql`'[]'::jsonb`).notNull(),
19806
- knowledge: jsonb("knowledge").$type().default(sql`'[]'::jsonb`).notNull(),
19807
- plugins: jsonb("plugins").$type().default(sql`'[]'::jsonb`).notNull(),
19808
- settings: jsonb("settings").$type().default(sql`'{}'::jsonb`).notNull(),
19809
- style: jsonb("style").$type().default(sql`'{}'::jsonb`).notNull()
19810
- });
19811
-
19812
21181
  // src/schema/entity.ts
21182
+ init_agent();
19813
21183
  import { sql as sql2 } from "drizzle-orm";
19814
21184
  import { jsonb as jsonb2, pgTable as pgTable2, text as text2, timestamp as timestamp2, unique, uuid as uuid2 } from "drizzle-orm/pg-core";
19815
21185
  var entityTable = pgTable2("entities", {
@@ -19827,6 +21197,7 @@ var entityTable = pgTable2("entities", {
19827
21197
  });
19828
21198
 
19829
21199
  // src/schema/room.ts
21200
+ init_agent();
19830
21201
  import { sql as sql3 } from "drizzle-orm";
19831
21202
  import { jsonb as jsonb3, pgTable as pgTable3, text as text3, timestamp as timestamp3, uuid as uuid3 } from "drizzle-orm/pg-core";
19832
21203
  var roomTable = pgTable3("rooms", {
@@ -19836,12 +21207,12 @@ var roomTable = pgTable3("rooms", {
19836
21207
  }),
19837
21208
  source: text3("source").notNull(),
19838
21209
  type: text3("type").notNull(),
19839
- serverId: text3("serverId"),
21210
+ messageServerId: uuid3("message_server_id"),
19840
21211
  worldId: uuid3("worldId"),
19841
21212
  name: text3("name"),
19842
21213
  metadata: jsonb3("metadata"),
19843
- channelId: text3("channelId"),
19844
- createdAt: timestamp3("createdAt").default(sql3`now()`).notNull()
21214
+ channelId: text3("channel_id"),
21215
+ createdAt: timestamp3("created_at").default(sql3`now()`).notNull()
19845
21216
  });
19846
21217
 
19847
21218
  // src/schema/memory.ts
@@ -19933,17 +21304,18 @@ var embeddingTable = pgTable5("embeddings", {
19933
21304
  ]);
19934
21305
 
19935
21306
  // src/schema/index.ts
21307
+ init_agent();
19936
21308
  var exports_schema = {};
19937
21309
  __export(exports_schema, {
19938
21310
  worldTable: () => worldTable,
19939
21311
  taskTable: () => taskTable,
19940
- serverAgentsTable: () => serverAgentsTable,
21312
+ serverTable: () => serverTable,
19941
21313
  roomTable: () => roomTable,
19942
21314
  relationshipTable: () => relationshipTable,
19943
21315
  participantTable: () => participantTable,
19944
- ownersTable: () => ownersTable,
19945
21316
  messageTable: () => messageTable,
19946
21317
  messageServerTable: () => messageServerTable,
21318
+ messageServerAgentsTable: () => messageServerAgentsTable,
19947
21319
  memoryTable: () => memoryTable,
19948
21320
  logTable: () => logTable,
19949
21321
  entityTable: () => entityTable,
@@ -19956,6 +21328,7 @@ __export(exports_schema, {
19956
21328
  });
19957
21329
 
19958
21330
  // src/schema/cache.ts
21331
+ init_agent();
19959
21332
  import { sql as sql6 } from "drizzle-orm";
19960
21333
  import { jsonb as jsonb5, pgTable as pgTable6, text as text5, primaryKey, timestamp as timestamp6, uuid as uuid6 } from "drizzle-orm/pg-core";
19961
21334
  var cacheTable = pgTable6("cache", {
@@ -19964,14 +21337,14 @@ var cacheTable = pgTable6("cache", {
19964
21337
  value: jsonb5("value").notNull(),
19965
21338
  createdAt: timestamp6("created_at", { withTimezone: true }).default(sql6`now()`).notNull(),
19966
21339
  expiresAt: timestamp6("expires_at", { withTimezone: true })
19967
- }, (table) => ({
19968
- pk: primaryKey({ columns: [table.key, table.agentId] })
19969
- }));
21340
+ }, (table) => [primaryKey({ columns: [table.key, table.agentId] })]);
19970
21341
  // src/schema/component.ts
21342
+ init_agent();
19971
21343
  import { sql as sql8 } from "drizzle-orm";
19972
21344
  import { jsonb as jsonb7, pgTable as pgTable8, text as text7, timestamp as timestamp8, uuid as uuid8 } from "drizzle-orm/pg-core";
19973
21345
 
19974
21346
  // src/schema/world.ts
21347
+ init_agent();
19975
21348
  import { sql as sql7 } from "drizzle-orm";
19976
21349
  import { jsonb as jsonb6, pgTable as pgTable7, text as text6, timestamp as timestamp7, uuid as uuid7 } from "drizzle-orm/pg-core";
19977
21350
  var worldTable = pgTable7("worlds", {
@@ -19979,8 +21352,8 @@ var worldTable = pgTable7("worlds", {
19979
21352
  agentId: uuid7("agentId").notNull().references(() => agentTable.id, { onDelete: "cascade" }),
19980
21353
  name: text6("name").notNull(),
19981
21354
  metadata: jsonb6("metadata"),
19982
- serverId: text6("serverId").notNull().default("local"),
19983
- createdAt: timestamp7("createdAt").default(sql7`now()`).notNull()
21355
+ messageServerId: uuid7("message_server_id"),
21356
+ createdAt: timestamp7("created_at").default(sql7`now()`).notNull()
19984
21357
  });
19985
21358
 
19986
21359
  // src/schema/component.ts
@@ -20017,15 +21390,12 @@ var logTable = pgTable9("logs", {
20017
21390
  foreignColumns: [entityTable.id]
20018
21391
  }).onDelete("cascade")
20019
21392
  ]);
20020
- // src/schema/owners.ts
20021
- import { sql as sql10 } from "drizzle-orm";
20022
- import { pgTable as pgTable10, timestamp as timestamp10, uuid as uuid10 } from "drizzle-orm/pg-core";
20023
- var ownersTable = pgTable10("owners", {
20024
- id: uuid10("id").primaryKey(),
20025
- createdAt: timestamp10("created_at", { withTimezone: true }).default(sql10`now()`).notNull(),
20026
- updatedAt: timestamp10("updated_at", { withTimezone: true }).default(sql10`now()`).notNull()
20027
- });
21393
+
21394
+ // src/schema/index.ts
21395
+ init_server();
21396
+
20028
21397
  // src/schema/participant.ts
21398
+ init_agent();
20029
21399
  import { sql as sql11 } from "drizzle-orm";
20030
21400
  import { foreignKey as foreignKey4, index as index3, pgTable as pgTable11, text as text9, timestamp as timestamp11, uuid as uuid11 } from "drizzle-orm/pg-core";
20031
21401
  var participantTable = pgTable11("participants", {
@@ -20056,6 +21426,7 @@ var participantTable = pgTable11("participants", {
20056
21426
  }).onDelete("cascade")
20057
21427
  ]);
20058
21428
  // src/schema/relationship.ts
21429
+ init_agent();
20059
21430
  import { sql as sql12 } from "drizzle-orm";
20060
21431
  import {
20061
21432
  foreignKey as foreignKey5,
@@ -20090,6 +21461,7 @@ var relationshipTable = pgTable12("relationships", {
20090
21461
  }).onDelete("cascade")
20091
21462
  ]);
20092
21463
  // src/schema/tasks.ts
21464
+ init_agent();
20093
21465
  import { jsonb as jsonb10, pgTable as pgTable13, text as text11, timestamp as timestamp13, uuid as uuid13 } from "drizzle-orm/pg-core";
20094
21466
  import { sql as sql13 } from "drizzle-orm";
20095
21467
  var taskTable = pgTable13("tasks", {
@@ -20099,7 +21471,7 @@ var taskTable = pgTable13("tasks", {
20099
21471
  roomId: uuid13("roomId"),
20100
21472
  worldId: uuid13("worldId"),
20101
21473
  entityId: uuid13("entityId"),
20102
- agentId: uuid13("agent_id").notNull().references(() => agentTable.id, { onDelete: "cascade" }),
21474
+ agentId: uuid13("agentId").notNull().references(() => agentTable.id, { onDelete: "cascade" }),
20103
21475
  tags: text11("tags").array().default(sql13`'{}'::text[]`),
20104
21476
  metadata: jsonb10("metadata").default(sql13`'{}'::jsonb`),
20105
21477
  createdAt: timestamp13("created_at", { withTimezone: true }).defaultNow(),
@@ -20122,7 +21494,7 @@ import { pgTable as pgTable15, text as text13, jsonb as jsonb12, timestamp as ti
20122
21494
  import { sql as sql15 } from "drizzle-orm";
20123
21495
  var channelTable = pgTable15("channels", {
20124
21496
  id: text13("id").primaryKey(),
20125
- messageServerId: uuid15("server_id").notNull().references(() => messageServerTable.id, { onDelete: "cascade" }),
21497
+ messageServerId: uuid15("message_server_id").notNull().references(() => messageServerTable.id, { onDelete: "cascade" }),
20126
21498
  name: text13("name").notNull(),
20127
21499
  type: text13("type").notNull(),
20128
21500
  sourceType: text13("source_type"),
@@ -20154,18 +21526,15 @@ var messageTable = pgTable16("central_messages", {
20154
21526
  import { pgTable as pgTable17, text as text15, primaryKey as primaryKey2 } from "drizzle-orm/pg-core";
20155
21527
  var channelParticipantsTable = pgTable17("channel_participants", {
20156
21528
  channelId: text15("channel_id").notNull().references(() => channelTable.id, { onDelete: "cascade" }),
20157
- userId: text15("user_id").notNull()
20158
- }, (table) => ({
20159
- pk: primaryKey2({ columns: [table.channelId, table.userId] })
20160
- }));
20161
- // src/schema/serverAgent.ts
21529
+ entityId: text15("entity_id").notNull()
21530
+ }, (table) => [primaryKey2({ columns: [table.channelId, table.entityId] })]);
21531
+ // src/schema/messageServerAgent.ts
20162
21532
  import { pgTable as pgTable18, uuid as uuid16, primaryKey as primaryKey3 } from "drizzle-orm/pg-core";
20163
- var serverAgentsTable = pgTable18("server_agents", {
20164
- serverId: uuid16("server_id").notNull().references(() => messageServerTable.id, { onDelete: "cascade" }),
21533
+ init_agent();
21534
+ var messageServerAgentsTable = pgTable18("message_server_agents", {
21535
+ messageServerId: uuid16("message_server_id").notNull().references(() => messageServerTable.id, { onDelete: "cascade" }),
20165
21536
  agentId: uuid16("agent_id").notNull().references(() => agentTable.id, { onDelete: "cascade" })
20166
- }, (table) => ({
20167
- pk: primaryKey3({ columns: [table.serverId, table.agentId] })
20168
- }));
21537
+ }, (table) => [primaryKey3({ columns: [table.messageServerId, table.agentId] })]);
20169
21538
  // src/base.ts
20170
21539
  class BaseDrizzleAdapter extends DatabaseAdapter {
20171
21540
  maxRetries = 3;
@@ -20227,10 +21596,19 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
20227
21596
  const backoffDelay = Math.min(this.baseDelay * 2 ** (attempt - 1), this.maxDelay);
20228
21597
  const jitter = Math.random() * this.jitterMax;
20229
21598
  const delay = backoffDelay + jitter;
20230
- logger7.warn(`Database operation failed (attempt ${attempt}/${this.maxRetries}): ${error instanceof Error ? error.message : String(error)}, nextRetryIn: ${(delay / 1000).toFixed(1)}s`);
21599
+ logger9.warn({
21600
+ src: "plugin:sql",
21601
+ attempt,
21602
+ maxRetries: this.maxRetries,
21603
+ error: error instanceof Error ? error.message : String(error)
21604
+ }, "Database operation failed, retrying");
20231
21605
  await new Promise((resolve) => setTimeout(resolve, delay));
20232
21606
  } else {
20233
- logger7.error(`Max retry attempts reached: ${error instanceof Error ? error.message : String(error)}, totalAttempts: ${attempt}`);
21607
+ logger9.error({
21608
+ src: "plugin:sql",
21609
+ totalAttempts: attempt,
21610
+ error: error instanceof Error ? error.message : String(error)
21611
+ }, "Max retry attempts reached");
20234
21612
  throw error instanceof Error ? error : new Error(String(error));
20235
21613
  }
20236
21614
  }
@@ -20239,7 +21617,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
20239
21617
  }
20240
21618
  async ensureEmbeddingDimension(dimension) {
20241
21619
  return this.withDatabase(async () => {
20242
- const existingMemory = await this.db.select().from(memoryTable).innerJoin(embeddingTable, eq(embeddingTable.memoryId, memoryTable.id)).where(eq(memoryTable.agentId, this.agentId)).limit(1);
21620
+ const existingMemory = await this.db.select().from(memoryTable).innerJoin(embeddingTable, eq2(embeddingTable.memoryId, memoryTable.id)).where(eq2(memoryTable.agentId, this.agentId)).limit(1);
20243
21621
  if (existingMemory.length > 0) {
20244
21622
  Object.entries(DIMENSION_MAP).find(([_, colName]) => existingMemory[0].embeddings[colName] !== null);
20245
21623
  }
@@ -20248,7 +21626,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
20248
21626
  }
20249
21627
  async getAgent(agentId) {
20250
21628
  return this.withDatabase(async () => {
20251
- const rows = await this.db.select().from(agentTable).where(eq(agentTable.id, agentId)).limit(1);
21629
+ const rows = await this.db.select().from(agentTable).where(eq2(agentTable.id, agentId)).limit(1);
20252
21630
  if (rows.length === 0)
20253
21631
  return null;
20254
21632
  const row = rows[0];
@@ -20282,9 +21660,9 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
20282
21660
  return this.withDatabase(async () => {
20283
21661
  try {
20284
21662
  if (agent.id) {
20285
- const existing = await this.db.select({ id: agentTable.id }).from(agentTable).where(eq(agentTable.id, agent.id)).limit(1);
21663
+ const existing = await this.db.select({ id: agentTable.id }).from(agentTable).where(eq2(agentTable.id, agent.id)).limit(1);
20286
21664
  if (existing.length > 0) {
20287
- logger7.warn(`Attempted to create an agent with a duplicate ID. ID: ${agent.id}`);
21665
+ logger9.warn({ src: "plugin:sql", agentId: agent.id }, "Attempted to create agent with duplicate ID");
20288
21666
  return false;
20289
21667
  }
20290
21668
  }
@@ -20295,10 +21673,13 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
20295
21673
  updatedAt: new Date(agent.updatedAt || Date.now())
20296
21674
  });
20297
21675
  });
20298
- logger7.debug(`Agent created successfully: ${agent.id}`);
20299
21676
  return true;
20300
21677
  } catch (error) {
20301
- logger7.error(`Error creating agent: ${error instanceof Error ? error.message : String(error)}, agentId: ${agent.id}`);
21678
+ logger9.error({
21679
+ src: "plugin:sql",
21680
+ agentId: agent.id,
21681
+ error: error instanceof Error ? error.message : String(error)
21682
+ }, "Failed to create agent");
20302
21683
  return false;
20303
21684
  }
20304
21685
  });
@@ -20330,18 +21711,21 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
20330
21711
  } else {
20331
21712
  updateData.updatedAt = new Date;
20332
21713
  }
20333
- await tx.update(agentTable).set(updateData).where(eq(agentTable.id, agentId));
21714
+ await tx.update(agentTable).set(updateData).where(eq2(agentTable.id, agentId));
20334
21715
  });
20335
- logger7.debug(`Agent updated successfully: ${agentId}`);
20336
21716
  return true;
20337
21717
  } catch (error) {
20338
- logger7.error(`Error updating agent: ${error instanceof Error ? error.message : String(error)}, agentId: ${agentId}`);
21718
+ logger9.error({
21719
+ src: "plugin:sql",
21720
+ agentId,
21721
+ error: error instanceof Error ? error.message : String(error)
21722
+ }, "Failed to update agent");
20339
21723
  return false;
20340
21724
  }
20341
21725
  });
20342
21726
  }
20343
21727
  async mergeAgentSettings(tx, agentId, updatedSettings) {
20344
- const currentAgent = await tx.select({ settings: agentTable.settings }).from(agentTable).where(eq(agentTable.id, agentId)).limit(1);
21728
+ const currentAgent = await tx.select({ settings: agentTable.settings }).from(agentTable).where(eq2(agentTable.id, agentId)).limit(1);
20345
21729
  const currentSettings = currentAgent.length > 0 && currentAgent[0].settings ? currentAgent[0].settings : {};
20346
21730
  const deepMerge = (target, source) => {
20347
21731
  if (source === null) {
@@ -20377,22 +21761,20 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
20377
21761
  return finalSettings === undefined ? {} : finalSettings;
20378
21762
  }
20379
21763
  async deleteAgent(agentId) {
20380
- logger7.debug(`[DB] Deleting agent with ID: ${agentId}`);
20381
21764
  return this.withDatabase(async () => {
20382
21765
  try {
20383
- const result = await this.db.delete(agentTable).where(eq(agentTable.id, agentId)).returning();
21766
+ const result = await this.db.delete(agentTable).where(eq2(agentTable.id, agentId)).returning();
20384
21767
  if (result.length === 0) {
20385
- logger7.warn(`[DB] Agent ${agentId} not found`);
21768
+ logger9.warn({ src: "plugin:sql", agentId }, "Agent not found for deletion");
20386
21769
  return false;
20387
21770
  }
20388
- logger7.success(`[DB] Agent ${agentId} and all related data successfully deleted via cascade`);
20389
21771
  return true;
20390
21772
  } catch (error) {
20391
- logger7.error(`[DB] Failed to delete agent ${agentId}: ${error instanceof Error ? error.message : String(error)}`);
20392
- if (error instanceof Error) {
20393
- logger7.error(`[DB] Error details: ${error.name} - ${error.message}`);
20394
- logger7.error(`[DB] Stack trace: ${error.stack}`);
20395
- }
21773
+ logger9.error({
21774
+ src: "plugin:sql",
21775
+ agentId,
21776
+ error: error instanceof Error ? error.message : String(error)
21777
+ }, "Failed to delete agent");
20396
21778
  throw error;
20397
21779
  }
20398
21780
  });
@@ -20403,7 +21785,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
20403
21785
  const result = await this.db.select({ count: count() }).from(agentTable);
20404
21786
  return result[0]?.count || 0;
20405
21787
  } catch (error) {
20406
- logger7.error(`Error counting agents: ${error instanceof Error ? error.message : String(error)}`);
21788
+ logger9.error({ src: "plugin:sql", error: error instanceof Error ? error.message : String(error) }, "Failed to count agents");
20407
21789
  return 0;
20408
21790
  }
20409
21791
  });
@@ -20412,9 +21794,8 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
20412
21794
  return this.withDatabase(async () => {
20413
21795
  try {
20414
21796
  await this.db.delete(agentTable);
20415
- logger7.success("Successfully cleaned up agent table");
20416
21797
  } catch (error) {
20417
- logger7.error(`Error cleaning up agent table: ${error instanceof Error ? error.message : String(error)}`);
21798
+ logger9.error({ src: "plugin:sql", error: error instanceof Error ? error.message : String(error) }, "Failed to clean up agent table");
20418
21799
  throw error;
20419
21800
  }
20420
21801
  });
@@ -20424,7 +21805,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
20424
21805
  const result = await this.db.select({
20425
21806
  entity: entityTable,
20426
21807
  components: componentTable
20427
- }).from(entityTable).leftJoin(componentTable, eq(componentTable.entityId, entityTable.id)).where(inArray(entityTable.id, entityIds));
21808
+ }).from(entityTable).leftJoin(componentTable, eq2(componentTable.entityId, entityTable.id)).where(inArray(entityTable.id, entityIds));
20428
21809
  if (result.length === 0)
20429
21810
  return [];
20430
21811
  const entities = {};
@@ -20450,11 +21831,11 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
20450
21831
  const query = this.db.select({
20451
21832
  entity: entityTable,
20452
21833
  ...includeComponents && { components: componentTable }
20453
- }).from(participantTable).leftJoin(entityTable, and(eq(participantTable.entityId, entityTable.id), eq(entityTable.agentId, this.agentId)));
21834
+ }).from(participantTable).leftJoin(entityTable, and(eq2(participantTable.entityId, entityTable.id), eq2(entityTable.agentId, this.agentId)));
20454
21835
  if (includeComponents) {
20455
- query.leftJoin(componentTable, eq(componentTable.entityId, entityTable.id));
21836
+ query.leftJoin(componentTable, eq2(componentTable.entityId, entityTable.id));
20456
21837
  }
20457
- const result = await query.where(eq(participantTable.roomId, roomId));
21838
+ const result = await query.where(eq2(participantTable.roomId, roomId));
20458
21839
  const entitiesByIdMap = new Map;
20459
21840
  for (const row of result) {
20460
21841
  if (!row.entity)
@@ -20493,21 +21874,21 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
20493
21874
  metadata: entity.metadata || {}
20494
21875
  }));
20495
21876
  await tx.insert(entityTable).values(normalizedEntities);
20496
- logger7.debug(`${entities.length} Entities created successfully`);
20497
21877
  return true;
20498
21878
  });
20499
21879
  } catch (error) {
20500
- logger7.error(`Error creating entities, entityId: ${entities[0].id}, (metadata?.)name: ${entities[0].metadata?.name}`, error instanceof Error ? error.message : String(error));
20501
- if (error instanceof Error && error.stack) {
20502
- logger7.trace("Stack trace:", error.stack);
20503
- }
21880
+ logger9.error({
21881
+ src: "plugin:sql",
21882
+ entityId: entities[0]?.id,
21883
+ error: error instanceof Error ? error.message : String(error)
21884
+ }, "Failed to create entities");
20504
21885
  return false;
20505
21886
  }
20506
21887
  });
20507
21888
  }
20508
21889
  async ensureEntityExists(entity) {
20509
21890
  if (!entity.id) {
20510
- logger7.error("Entity ID is required for ensureEntityExists");
21891
+ logger9.error({ src: "plugin:sql" }, "Entity ID is required for ensureEntityExists");
20511
21892
  return false;
20512
21893
  }
20513
21894
  try {
@@ -20517,7 +21898,11 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
20517
21898
  }
20518
21899
  return true;
20519
21900
  } catch (error) {
20520
- logger7.error(`Error ensuring entity exists: ${error instanceof Error ? error.message : String(error)}, entityId: ${entity.id}`);
21901
+ logger9.error({
21902
+ src: "plugin:sql",
21903
+ entityId: entity.id,
21904
+ error: error instanceof Error ? error.message : String(error)
21905
+ }, "Failed to ensure entity exists");
20521
21906
  return false;
20522
21907
  }
20523
21908
  }
@@ -20531,25 +21916,25 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
20531
21916
  names: this.normalizeEntityNames(entity.names),
20532
21917
  metadata: entity.metadata || {}
20533
21918
  };
20534
- await this.db.update(entityTable).set(normalizedEntity).where(eq(entityTable.id, entity.id));
21919
+ await this.db.update(entityTable).set(normalizedEntity).where(eq2(entityTable.id, entity.id));
20535
21920
  });
20536
21921
  }
20537
21922
  async deleteEntity(entityId) {
20538
21923
  return this.withDatabase(async () => {
20539
21924
  await this.db.transaction(async (tx) => {
20540
- await tx.delete(componentTable).where(or(eq(componentTable.entityId, entityId), eq(componentTable.sourceEntityId, entityId)));
20541
- await tx.delete(entityTable).where(eq(entityTable.id, entityId));
21925
+ await tx.delete(componentTable).where(or(eq2(componentTable.entityId, entityId), eq2(componentTable.sourceEntityId, entityId)));
21926
+ await tx.delete(entityTable).where(eq2(entityTable.id, entityId));
20542
21927
  });
20543
21928
  });
20544
21929
  }
20545
21930
  async getEntitiesByNames(params) {
20546
21931
  return this.withDatabase(async () => {
20547
21932
  const { names, agentId } = params;
20548
- const nameConditions = names.map((name) => sql23`${name} = ANY(${entityTable.names})`);
20549
- const query = sql23`
21933
+ const nameConditions = names.map((name) => sql25`${name} = ANY(${entityTable.names})`);
21934
+ const query = sql25`
20550
21935
  SELECT * FROM ${entityTable}
20551
21936
  WHERE ${entityTable.agentId} = ${agentId}
20552
- AND (${sql23.join(nameConditions, sql23` OR `)})
21937
+ AND (${sql25.join(nameConditions, sql25` OR `)})
20553
21938
  `;
20554
21939
  const result = await this.db.execute(query);
20555
21940
  return result.rows.map((row) => ({
@@ -20564,7 +21949,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
20564
21949
  return this.withDatabase(async () => {
20565
21950
  const { query, agentId, limit = 10 } = params;
20566
21951
  if (!query || query.trim() === "") {
20567
- const result2 = await this.db.select().from(entityTable).where(eq(entityTable.agentId, agentId)).limit(limit);
21952
+ const result2 = await this.db.select().from(entityTable).where(eq2(entityTable.agentId, agentId)).limit(limit);
20568
21953
  return result2.map((row) => ({
20569
21954
  id: row.id,
20570
21955
  agentId: row.agentId,
@@ -20572,7 +21957,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
20572
21957
  metadata: row.metadata || {}
20573
21958
  }));
20574
21959
  }
20575
- const searchQuery = sql23`
21960
+ const searchQuery = sql25`
20576
21961
  SELECT * FROM ${entityTable}
20577
21962
  WHERE ${entityTable.agentId} = ${agentId}
20578
21963
  AND EXISTS (
@@ -20592,12 +21977,12 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
20592
21977
  }
20593
21978
  async getComponent(entityId, type, worldId, sourceEntityId) {
20594
21979
  return this.withDatabase(async () => {
20595
- const conditions = [eq(componentTable.entityId, entityId), eq(componentTable.type, type)];
21980
+ const conditions = [eq2(componentTable.entityId, entityId), eq2(componentTable.type, type)];
20596
21981
  if (worldId) {
20597
- conditions.push(eq(componentTable.worldId, worldId));
21982
+ conditions.push(eq2(componentTable.worldId, worldId));
20598
21983
  }
20599
21984
  if (sourceEntityId) {
20600
- conditions.push(eq(componentTable.sourceEntityId, sourceEntityId));
21985
+ conditions.push(eq2(componentTable.sourceEntityId, sourceEntityId));
20601
21986
  }
20602
21987
  const result = await this.db.select().from(componentTable).where(and(...conditions));
20603
21988
  if (result.length === 0)
@@ -20618,12 +22003,12 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
20618
22003
  }
20619
22004
  async getComponents(entityId, worldId, sourceEntityId) {
20620
22005
  return this.withDatabase(async () => {
20621
- const conditions = [eq(componentTable.entityId, entityId)];
22006
+ const conditions = [eq2(componentTable.entityId, entityId)];
20622
22007
  if (worldId) {
20623
- conditions.push(eq(componentTable.worldId, worldId));
22008
+ conditions.push(eq2(componentTable.worldId, worldId));
20624
22009
  }
20625
22010
  if (sourceEntityId) {
20626
- conditions.push(eq(componentTable.sourceEntityId, sourceEntityId));
22011
+ conditions.push(eq2(componentTable.sourceEntityId, sourceEntityId));
20627
22012
  }
20628
22013
  const result = await this.db.select({
20629
22014
  id: componentTable.id,
@@ -20667,7 +22052,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
20667
22052
  await this.db.update(componentTable).set({
20668
22053
  ...component,
20669
22054
  updatedAt: new Date
20670
- }).where(eq(componentTable.id, component.id));
22055
+ }).where(eq2(componentTable.id, component.id));
20671
22056
  } catch (e) {
20672
22057
  console.error("updateComponent error", e);
20673
22058
  }
@@ -20675,7 +22060,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
20675
22060
  }
20676
22061
  async deleteComponent(componentId) {
20677
22062
  return this.withDatabase(async () => {
20678
- await this.db.delete(componentTable).where(eq(componentTable.id, componentId));
22063
+ await this.db.delete(componentTable).where(eq2(componentTable.id, componentId));
20679
22064
  });
20680
22065
  }
20681
22066
  async getMemories(params) {
@@ -20685,30 +22070,27 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
20685
22070
  if (offset !== undefined && offset < 0) {
20686
22071
  throw new Error("offset must be a non-negative number");
20687
22072
  }
20688
- return this.withDatabase(async () => {
20689
- const conditions = [eq(memoryTable.type, tableName)];
22073
+ return this.withEntityContext(entityId ?? null, async (tx) => {
22074
+ const conditions = [eq2(memoryTable.type, tableName)];
20690
22075
  if (start) {
20691
22076
  conditions.push(gte(memoryTable.createdAt, new Date(start)));
20692
22077
  }
20693
- if (entityId) {
20694
- conditions.push(eq(memoryTable.entityId, entityId));
20695
- }
20696
22078
  if (roomId) {
20697
- conditions.push(eq(memoryTable.roomId, roomId));
22079
+ conditions.push(eq2(memoryTable.roomId, roomId));
20698
22080
  }
20699
22081
  if (worldId) {
20700
- conditions.push(eq(memoryTable.worldId, worldId));
22082
+ conditions.push(eq2(memoryTable.worldId, worldId));
20701
22083
  }
20702
22084
  if (end) {
20703
22085
  conditions.push(lte(memoryTable.createdAt, new Date(end)));
20704
22086
  }
20705
22087
  if (unique3) {
20706
- conditions.push(eq(memoryTable.unique, true));
22088
+ conditions.push(eq2(memoryTable.unique, true));
20707
22089
  }
20708
22090
  if (agentId) {
20709
- conditions.push(eq(memoryTable.agentId, agentId));
22091
+ conditions.push(eq2(memoryTable.agentId, agentId));
20710
22092
  }
20711
- const baseQuery = this.db.select({
22093
+ const baseQuery = tx.select({
20712
22094
  memory: {
20713
22095
  id: memoryTable.id,
20714
22096
  type: memoryTable.type,
@@ -20721,7 +22103,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
20721
22103
  metadata: memoryTable.metadata
20722
22104
  },
20723
22105
  embedding: embeddingTable[this.embeddingDimension]
20724
- }).from(memoryTable).leftJoin(embeddingTable, eq(embeddingTable.memoryId, memoryTable.id)).where(and(...conditions)).orderBy(desc(memoryTable.createdAt));
22106
+ }).from(memoryTable).leftJoin(embeddingTable, eq2(embeddingTable.memoryId, memoryTable.id)).where(and(...conditions)).orderBy(desc(memoryTable.createdAt));
20725
22107
  const rows = await (async () => {
20726
22108
  if (params.count && offset !== undefined && offset > 0) {
20727
22109
  return baseQuery.limit(params.count).offset(offset);
@@ -20752,10 +22134,10 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
20752
22134
  if (params.roomIds.length === 0)
20753
22135
  return [];
20754
22136
  const conditions = [
20755
- eq(memoryTable.type, params.tableName),
22137
+ eq2(memoryTable.type, params.tableName),
20756
22138
  inArray(memoryTable.roomId, params.roomIds)
20757
22139
  ];
20758
- conditions.push(eq(memoryTable.agentId, this.agentId));
22140
+ conditions.push(eq2(memoryTable.agentId, this.agentId));
20759
22141
  const query = this.db.select({
20760
22142
  id: memoryTable.id,
20761
22143
  type: memoryTable.type,
@@ -20785,7 +22167,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
20785
22167
  const result = await this.db.select({
20786
22168
  memory: memoryTable,
20787
22169
  embedding: embeddingTable[this.embeddingDimension]
20788
- }).from(memoryTable).leftJoin(embeddingTable, eq(memoryTable.id, embeddingTable.memoryId)).where(eq(memoryTable.id, id)).limit(1);
22170
+ }).from(memoryTable).leftJoin(embeddingTable, eq2(memoryTable.id, embeddingTable.memoryId)).where(eq2(memoryTable.id, id)).limit(1);
20789
22171
  if (result.length === 0)
20790
22172
  return null;
20791
22173
  const row = result[0];
@@ -20808,12 +22190,12 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
20808
22190
  return [];
20809
22191
  const conditions = [inArray(memoryTable.id, memoryIds)];
20810
22192
  if (tableName) {
20811
- conditions.push(eq(memoryTable.type, tableName));
22193
+ conditions.push(eq2(memoryTable.type, tableName));
20812
22194
  }
20813
22195
  const rows = await this.db.select({
20814
22196
  memory: memoryTable,
20815
22197
  embedding: embeddingTable[this.embeddingDimension]
20816
- }).from(memoryTable).leftJoin(embeddingTable, eq(embeddingTable.memoryId, memoryTable.id)).where(and(...conditions)).orderBy(desc(memoryTable.createdAt));
22198
+ }).from(memoryTable).leftJoin(embeddingTable, eq2(embeddingTable.memoryId, memoryTable.id)).where(and(...conditions)).orderBy(desc(memoryTable.createdAt));
20817
22199
  return rows.map((row) => ({
20818
22200
  id: row.memory.id,
20819
22201
  createdAt: row.memory.createdAt.getTime(),
@@ -20830,7 +22212,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
20830
22212
  async getCachedEmbeddings(opts) {
20831
22213
  return this.withDatabase(async () => {
20832
22214
  try {
20833
- const results = await this.db.execute(sql23`
22215
+ const results = await this.db.execute(sql25`
20834
22216
  WITH content_text AS (
20835
22217
  SELECT
20836
22218
  m.id,
@@ -20870,7 +22252,12 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
20870
22252
  levenshtein_score: Number(row.levenshtein_score)
20871
22253
  })).filter((row) => Array.isArray(row.embedding));
20872
22254
  } catch (error) {
20873
- logger7.error(`Error in getCachedEmbeddings: ${error instanceof Error ? error.message : String(error)}, tableName: ${opts.query_table_name}, fieldName: ${opts.query_field_name}`);
22255
+ logger9.error({
22256
+ src: "plugin:sql",
22257
+ tableName: opts.query_table_name,
22258
+ fieldName: opts.query_field_name,
22259
+ error: error instanceof Error ? error.message : String(error)
22260
+ }, "Failed to get cached embeddings");
20874
22261
  if (error instanceof Error && error.message === "levenshtein argument exceeds maximum length of 255 characters") {
20875
22262
  return [];
20876
22263
  }
@@ -20883,16 +22270,22 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
20883
22270
  try {
20884
22271
  const sanitizedBody = this.sanitizeJsonObject(params.body);
20885
22272
  const jsonString = JSON.stringify(sanitizedBody);
20886
- await this.db.transaction(async (tx) => {
22273
+ await this.withEntityContext(params.entityId, async (tx) => {
20887
22274
  await tx.insert(logTable).values({
20888
- body: sql23`${jsonString}::jsonb`,
22275
+ body: sql25`${jsonString}::jsonb`,
20889
22276
  entityId: params.entityId,
20890
22277
  roomId: params.roomId,
20891
22278
  type: params.type
20892
22279
  });
20893
22280
  });
20894
22281
  } catch (error) {
20895
- logger7.error(`Failed to create log entry: ${error instanceof Error ? error.message : String(error)}, type: ${params.type}, roomId: ${params.roomId}, entityId: ${params.entityId}`);
22282
+ logger9.error({
22283
+ src: "plugin:sql",
22284
+ type: params.type,
22285
+ roomId: params.roomId,
22286
+ entityId: params.entityId,
22287
+ error: error instanceof Error ? error.message : String(error)
22288
+ }, "Failed to create log entry");
20896
22289
  throw error;
20897
22290
  }
20898
22291
  });
@@ -20925,8 +22318,8 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
20925
22318
  }
20926
22319
  async getLogs(params) {
20927
22320
  const { entityId, roomId, type, count: count2, offset } = params;
20928
- return this.withDatabase(async () => {
20929
- const result = await this.db.select().from(logTable).where(and(eq(logTable.entityId, entityId), roomId ? eq(logTable.roomId, roomId) : undefined, type ? eq(logTable.type, type) : undefined)).orderBy(desc(logTable.createdAt)).limit(count2 ?? 10).offset(offset ?? 0);
22321
+ return this.withEntityContext(entityId ?? null, async (tx) => {
22322
+ const result = await tx.select().from(logTable).where(and(roomId ? eq2(logTable.roomId, roomId) : undefined, type ? eq2(logTable.type, type) : undefined)).orderBy(desc(logTable.createdAt)).limit(count2 ?? 10).offset(offset ?? 0);
20930
22323
  const logs = result.map((log2) => ({
20931
22324
  ...log2,
20932
22325
  id: log2.id,
@@ -20944,15 +22337,15 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
20944
22337
  const limit = Math.min(Math.max(params.limit ?? 20, 1), 100);
20945
22338
  const fromDate = typeof params.from === "number" ? new Date(params.from) : undefined;
20946
22339
  const toDate = typeof params.to === "number" ? new Date(params.to) : undefined;
20947
- return this.withDatabase(async () => {
22340
+ return this.withEntityContext(params.entityId ?? null, async (tx) => {
20948
22341
  const runMap = new Map;
20949
22342
  const conditions = [
20950
- eq(logTable.type, "run_event"),
20951
- sql23`${logTable.body} ? 'runId'`,
20952
- eq(roomTable.agentId, this.agentId)
22343
+ eq2(logTable.type, "run_event"),
22344
+ sql25`${logTable.body} ? 'runId'`,
22345
+ eq2(roomTable.agentId, this.agentId)
20953
22346
  ];
20954
22347
  if (params.roomId) {
20955
- conditions.push(eq(logTable.roomId, params.roomId));
22348
+ conditions.push(eq2(logTable.roomId, params.roomId));
20956
22349
  }
20957
22350
  if (fromDate) {
20958
22351
  conditions.push(gte(logTable.createdAt, fromDate));
@@ -20962,15 +22355,15 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
20962
22355
  }
20963
22356
  const whereClause = and(...conditions);
20964
22357
  const eventLimit = Math.max(limit * 20, 200);
20965
- const runEventRows = await this.db.select({
20966
- runId: sql23`(${logTable.body} ->> 'runId')`,
20967
- status: sql23`(${logTable.body} ->> 'status')`,
20968
- messageId: sql23`(${logTable.body} ->> 'messageId')`,
22358
+ const runEventRows = await tx.select({
22359
+ runId: sql25`(${logTable.body} ->> 'runId')`,
22360
+ status: sql25`(${logTable.body} ->> 'status')`,
22361
+ messageId: sql25`(${logTable.body} ->> 'messageId')`,
20969
22362
  rawBody: logTable.body,
20970
22363
  createdAt: logTable.createdAt,
20971
22364
  roomId: logTable.roomId,
20972
22365
  entityId: logTable.entityId
20973
- }).from(logTable).innerJoin(roomTable, eq(roomTable.id, logTable.roomId)).where(whereClause).orderBy(desc(logTable.createdAt)).limit(eventLimit);
22366
+ }).from(logTable).innerJoin(roomTable, eq2(roomTable.id, logTable.roomId)).where(whereClause).orderBy(desc(logTable.createdAt)).limit(eventLimit);
20974
22367
  for (const row of runEventRows) {
20975
22368
  const runId = row.runId;
20976
22369
  if (!runId)
@@ -21039,8 +22432,8 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
21039
22432
  }
21040
22433
  const runIds = limitedRuns.map((run) => run.runId).filter(Boolean);
21041
22434
  if (runIds.length > 0) {
21042
- const runIdArray = sql23`array[${sql23.join(runIds.map((id) => sql23`${id}`), sql23`, `)}]::text[]`;
21043
- const actionSummary = await this.db.execute(sql23`
22435
+ const runIdArray = sql25`array[${sql25.join(runIds.map((id) => sql25`${id}`), sql25`, `)}]::text[]`;
22436
+ const actionSummary = await this.db.execute(sql25`
21044
22437
  SELECT
21045
22438
  body->>'runId' as "runId",
21046
22439
  COUNT(*)::int as "actions",
@@ -21060,7 +22453,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
21060
22453
  counts.errors += Number(row.errors ?? 0);
21061
22454
  counts.modelCalls += Number(row.modelCalls ?? 0);
21062
22455
  }
21063
- const evaluatorSummary = await this.db.execute(sql23`
22456
+ const evaluatorSummary = await this.db.execute(sql25`
21064
22457
  SELECT
21065
22458
  body->>'runId' as "runId",
21066
22459
  COUNT(*)::int as "evaluators"
@@ -21076,7 +22469,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
21076
22469
  continue;
21077
22470
  counts.evaluators += Number(row.evaluators ?? 0);
21078
22471
  }
21079
- const genericSummary = await this.db.execute(sql23`
22472
+ const genericSummary = await this.db.execute(sql25`
21080
22473
  SELECT
21081
22474
  body->>'runId' as "runId",
21082
22475
  COUNT(*) FILTER (WHERE type LIKE 'useModel:%')::int as "modelLogs",
@@ -21112,7 +22505,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
21112
22505
  }
21113
22506
  async deleteLog(logId) {
21114
22507
  return this.withDatabase(async () => {
21115
- await this.db.delete(logTable).where(eq(logTable.id, logId));
22508
+ await this.db.delete(logTable).where(eq2(logTable.id, logId));
21116
22509
  });
21117
22510
  }
21118
22511
  async searchMemories(params) {
@@ -21129,20 +22522,20 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
21129
22522
  async searchMemoriesByEmbedding(embedding, params) {
21130
22523
  return this.withDatabase(async () => {
21131
22524
  const cleanVector = embedding.map((n) => Number.isFinite(n) ? Number(n.toFixed(6)) : 0);
21132
- const similarity = sql23`1 - (${cosineDistance(embeddingTable[this.embeddingDimension], cleanVector)})`;
21133
- const conditions = [eq(memoryTable.type, params.tableName)];
22525
+ const similarity = sql25`1 - (${cosineDistance(embeddingTable[this.embeddingDimension], cleanVector)})`;
22526
+ const conditions = [eq2(memoryTable.type, params.tableName)];
21134
22527
  if (params.unique) {
21135
- conditions.push(eq(memoryTable.unique, true));
22528
+ conditions.push(eq2(memoryTable.unique, true));
21136
22529
  }
21137
- conditions.push(eq(memoryTable.agentId, this.agentId));
22530
+ conditions.push(eq2(memoryTable.agentId, this.agentId));
21138
22531
  if (params.roomId) {
21139
- conditions.push(eq(memoryTable.roomId, params.roomId));
22532
+ conditions.push(eq2(memoryTable.roomId, params.roomId));
21140
22533
  }
21141
22534
  if (params.worldId) {
21142
- conditions.push(eq(memoryTable.worldId, params.worldId));
22535
+ conditions.push(eq2(memoryTable.worldId, params.worldId));
21143
22536
  }
21144
22537
  if (params.entityId) {
21145
- conditions.push(eq(memoryTable.entityId, params.entityId));
22538
+ conditions.push(eq2(memoryTable.entityId, params.entityId));
21146
22539
  }
21147
22540
  if (params.match_threshold) {
21148
22541
  conditions.push(gte(similarity, params.match_threshold));
@@ -21151,7 +22544,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
21151
22544
  memory: memoryTable,
21152
22545
  similarity,
21153
22546
  embedding: embeddingTable[this.embeddingDimension]
21154
- }).from(embeddingTable).innerJoin(memoryTable, eq(memoryTable.id, embeddingTable.memoryId)).where(and(...conditions)).orderBy(desc(similarity)).limit(params.count ?? 10);
22547
+ }).from(embeddingTable).innerJoin(memoryTable, eq2(memoryTable.id, embeddingTable.memoryId)).where(and(...conditions)).orderBy(desc(similarity)).limit(params.count ?? 10);
21155
22548
  return results.map((row) => ({
21156
22549
  id: row.memory.id,
21157
22550
  type: row.memory.type,
@@ -21169,11 +22562,9 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
21169
22562
  });
21170
22563
  }
21171
22564
  async createMemory(memory, tableName) {
21172
- logger7.debug(`DrizzleAdapter createMemory: memoryId: ${memory.id}, embeddingLength: ${memory.embedding?.length}, contentLength: ${memory.content?.text?.length}`);
21173
22565
  const memoryId = memory.id ?? v4_default();
21174
22566
  const existing = await this.getMemoryById(memoryId);
21175
22567
  if (existing) {
21176
- logger7.debug(`Memory already exists, skipping creation: ${memoryId}`);
21177
22568
  return memoryId;
21178
22569
  }
21179
22570
  if (memory.unique === undefined) {
@@ -21192,13 +22583,13 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
21192
22583
  }
21193
22584
  const contentToInsert = typeof memory.content === "string" ? memory.content : JSON.stringify(memory.content ?? {});
21194
22585
  const metadataToInsert = typeof memory.metadata === "string" ? memory.metadata : JSON.stringify(memory.metadata ?? {});
21195
- await this.db.transaction(async (tx) => {
22586
+ await this.withEntityContext(memory.entityId, async (tx) => {
21196
22587
  await tx.insert(memoryTable).values([
21197
22588
  {
21198
22589
  id: memoryId,
21199
22590
  type: tableName,
21200
- content: sql23`${contentToInsert}::jsonb`,
21201
- metadata: sql23`${metadataToInsert}::jsonb`,
22591
+ content: sql25`${contentToInsert}::jsonb`,
22592
+ metadata: sql25`${metadataToInsert}::jsonb`,
21202
22593
  entityId: memory.entityId,
21203
22594
  roomId: memory.roomId,
21204
22595
  worldId: memory.worldId,
@@ -21223,28 +22614,27 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
21223
22614
  async updateMemory(memory) {
21224
22615
  return this.withDatabase(async () => {
21225
22616
  try {
21226
- logger7.debug(`Updating memory: memoryId: ${memory.id}, hasEmbedding: ${!!memory.embedding}`);
21227
22617
  await this.db.transaction(async (tx) => {
21228
22618
  if (memory.content) {
21229
22619
  const contentToUpdate = typeof memory.content === "string" ? memory.content : JSON.stringify(memory.content ?? {});
21230
22620
  const metadataToUpdate = typeof memory.metadata === "string" ? memory.metadata : JSON.stringify(memory.metadata ?? {});
21231
22621
  await tx.update(memoryTable).set({
21232
- content: sql23`${contentToUpdate}::jsonb`,
21233
- ...memory.metadata && { metadata: sql23`${metadataToUpdate}::jsonb` }
21234
- }).where(eq(memoryTable.id, memory.id));
22622
+ content: sql25`${contentToUpdate}::jsonb`,
22623
+ ...memory.metadata && { metadata: sql25`${metadataToUpdate}::jsonb` }
22624
+ }).where(eq2(memoryTable.id, memory.id));
21235
22625
  } else if (memory.metadata) {
21236
22626
  const metadataToUpdate = typeof memory.metadata === "string" ? memory.metadata : JSON.stringify(memory.metadata ?? {});
21237
22627
  await tx.update(memoryTable).set({
21238
- metadata: sql23`${metadataToUpdate}::jsonb`
21239
- }).where(eq(memoryTable.id, memory.id));
22628
+ metadata: sql25`${metadataToUpdate}::jsonb`
22629
+ }).where(eq2(memoryTable.id, memory.id));
21240
22630
  }
21241
22631
  if (memory.embedding && Array.isArray(memory.embedding)) {
21242
22632
  const cleanVector = memory.embedding.map((n) => Number.isFinite(n) ? Number(n.toFixed(6)) : 0);
21243
- const existingEmbedding = await tx.select({ id: embeddingTable.id }).from(embeddingTable).where(eq(embeddingTable.memoryId, memory.id)).limit(1);
22633
+ const existingEmbedding = await tx.select({ id: embeddingTable.id }).from(embeddingTable).where(eq2(embeddingTable.memoryId, memory.id)).limit(1);
21244
22634
  if (existingEmbedding.length > 0) {
21245
22635
  const updateValues = {};
21246
22636
  updateValues[this.embeddingDimension] = cleanVector;
21247
- await tx.update(embeddingTable).set(updateValues).where(eq(embeddingTable.memoryId, memory.id));
22637
+ await tx.update(embeddingTable).set(updateValues).where(eq2(embeddingTable.memoryId, memory.id));
21248
22638
  } else {
21249
22639
  const embeddingValues = {
21250
22640
  id: v4_default(),
@@ -21255,10 +22645,13 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
21255
22645
  }
21256
22646
  }
21257
22647
  });
21258
- logger7.debug(`Memory updated successfully: ${memory.id}`);
21259
22648
  return true;
21260
22649
  } catch (error) {
21261
- logger7.error(`Error updating memory: ${error instanceof Error ? error.message : String(error)}, memoryId: ${memory.id}`);
22650
+ logger9.error({
22651
+ src: "plugin:sql",
22652
+ memoryId: memory.id,
22653
+ error: error instanceof Error ? error.message : String(error)
22654
+ }, "Failed to update memory");
21262
22655
  return false;
21263
22656
  }
21264
22657
  });
@@ -21267,10 +22660,9 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
21267
22660
  return this.withDatabase(async () => {
21268
22661
  await this.db.transaction(async (tx) => {
21269
22662
  await this.deleteMemoryFragments(tx, memoryId);
21270
- await tx.delete(embeddingTable).where(eq(embeddingTable.memoryId, memoryId));
21271
- await tx.delete(memoryTable).where(eq(memoryTable.id, memoryId));
22663
+ await tx.delete(embeddingTable).where(eq2(embeddingTable.memoryId, memoryId));
22664
+ await tx.delete(memoryTable).where(eq2(memoryTable.id, memoryId));
21272
22665
  });
21273
- logger7.debug(`Memory and related fragments removed successfully: ${memoryId}`);
21274
22666
  });
21275
22667
  }
21276
22668
  async deleteManyMemories(memoryIds) {
@@ -21289,7 +22681,6 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
21289
22681
  await tx.delete(memoryTable).where(inArray(memoryTable.id, batch));
21290
22682
  }
21291
22683
  });
21292
- logger7.debug(`Batch memory deletion completed successfully: ${memoryIds.length}`);
21293
22684
  });
21294
22685
  }
21295
22686
  async deleteMemoryFragments(tx, documentId) {
@@ -21298,40 +22689,38 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
21298
22689
  const fragmentIds = fragmentsToDelete.map((f) => f.id);
21299
22690
  await tx.delete(embeddingTable).where(inArray(embeddingTable.memoryId, fragmentIds));
21300
22691
  await tx.delete(memoryTable).where(inArray(memoryTable.id, fragmentIds));
21301
- logger7.debug(`Deleted related fragments: documentId: ${documentId}, fragmentCount: ${fragmentsToDelete.length}`);
21302
22692
  }
21303
22693
  }
21304
22694
  async getMemoryFragments(tx, documentId) {
21305
- const fragments = await tx.select({ id: memoryTable.id }).from(memoryTable).where(and(eq(memoryTable.agentId, this.agentId), sql23`${memoryTable.metadata}->>'documentId' = ${documentId}`));
22695
+ const fragments = await tx.select({ id: memoryTable.id }).from(memoryTable).where(and(eq2(memoryTable.agentId, this.agentId), sql25`${memoryTable.metadata}->>'documentId' = ${documentId}`));
21306
22696
  return fragments.map((f) => ({ id: f.id }));
21307
22697
  }
21308
22698
  async deleteAllMemories(roomId, tableName) {
21309
22699
  return this.withDatabase(async () => {
21310
22700
  await this.db.transaction(async (tx) => {
21311
- const rows = await tx.select({ id: memoryTable.id }).from(memoryTable).where(and(eq(memoryTable.roomId, roomId), eq(memoryTable.type, tableName)));
22701
+ const rows = await tx.select({ id: memoryTable.id }).from(memoryTable).where(and(eq2(memoryTable.roomId, roomId), eq2(memoryTable.type, tableName)));
21312
22702
  const ids = rows.map((r) => r.id);
21313
- logger7.debug(`[deleteAllMemories] memory IDs to delete: roomId: ${roomId}, tableName: ${tableName}, ids: ${JSON.stringify(ids)}`);
22703
+ logger9.debug({ src: "plugin:sql", roomId, tableName, memoryCount: ids.length }, "Deleting all memories");
21314
22704
  if (ids.length === 0) {
21315
22705
  return;
21316
22706
  }
21317
22707
  await Promise.all(ids.map(async (memoryId) => {
21318
22708
  await this.deleteMemoryFragments(tx, memoryId);
21319
- await tx.delete(embeddingTable).where(eq(embeddingTable.memoryId, memoryId));
22709
+ await tx.delete(embeddingTable).where(eq2(embeddingTable.memoryId, memoryId));
21320
22710
  }));
21321
- await tx.delete(memoryTable).where(and(eq(memoryTable.roomId, roomId), eq(memoryTable.type, tableName)));
22711
+ await tx.delete(memoryTable).where(and(eq2(memoryTable.roomId, roomId), eq2(memoryTable.type, tableName)));
21322
22712
  });
21323
- logger7.debug(`All memories removed successfully: roomId: ${roomId}, tableName: ${tableName}`);
21324
22713
  });
21325
22714
  }
21326
22715
  async countMemories(roomId, unique3 = true, tableName = "") {
21327
22716
  if (!tableName)
21328
22717
  throw new Error("tableName is required");
21329
22718
  return this.withDatabase(async () => {
21330
- const conditions = [eq(memoryTable.roomId, roomId), eq(memoryTable.type, tableName)];
22719
+ const conditions = [eq2(memoryTable.roomId, roomId), eq2(memoryTable.type, tableName)];
21331
22720
  if (unique3) {
21332
- conditions.push(eq(memoryTable.unique, true));
22721
+ conditions.push(eq2(memoryTable.unique, true));
21333
22722
  }
21334
- const result = await this.db.select({ count: sql23`count(*)` }).from(memoryTable).where(and(...conditions));
22723
+ const result = await this.db.select({ count: sql25`count(*)` }).from(memoryTable).where(and(...conditions));
21335
22724
  return Number(result[0]?.count ?? 0);
21336
22725
  });
21337
22726
  }
@@ -21342,18 +22731,19 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
21342
22731
  name: roomTable.name,
21343
22732
  channelId: roomTable.channelId,
21344
22733
  agentId: roomTable.agentId,
21345
- serverId: roomTable.serverId,
22734
+ messageServerId: roomTable.messageServerId,
21346
22735
  worldId: roomTable.worldId,
21347
22736
  type: roomTable.type,
21348
22737
  source: roomTable.source,
21349
22738
  metadata: roomTable.metadata
21350
- }).from(roomTable).where(and(inArray(roomTable.id, roomIds), eq(roomTable.agentId, this.agentId)));
22739
+ }).from(roomTable).where(and(inArray(roomTable.id, roomIds), eq2(roomTable.agentId, this.agentId)));
21351
22740
  const rooms = result.map((room) => ({
21352
22741
  ...room,
21353
22742
  id: room.id,
21354
22743
  name: room.name ?? undefined,
21355
22744
  agentId: room.agentId,
21356
- serverId: room.serverId,
22745
+ messageServerId: room.messageServerId,
22746
+ serverId: room.messageServerId,
21357
22747
  worldId: room.worldId,
21358
22748
  channelId: room.channelId,
21359
22749
  type: room.type,
@@ -21364,13 +22754,14 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
21364
22754
  }
21365
22755
  async getRoomsByWorld(worldId) {
21366
22756
  return this.withDatabase(async () => {
21367
- const result = await this.db.select().from(roomTable).where(eq(roomTable.worldId, worldId));
22757
+ const result = await this.db.select().from(roomTable).where(eq2(roomTable.worldId, worldId));
21368
22758
  const rooms = result.map((room) => ({
21369
22759
  ...room,
21370
22760
  id: room.id,
21371
22761
  name: room.name ?? undefined,
21372
22762
  agentId: room.agentId,
21373
- serverId: room.serverId,
22763
+ messageServerId: room.messageServerId,
22764
+ serverId: room.messageServerId,
21374
22765
  worldId: room.worldId,
21375
22766
  channelId: room.channelId,
21376
22767
  type: room.type,
@@ -21381,7 +22772,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
21381
22772
  }
21382
22773
  async updateRoom(room) {
21383
22774
  return this.withDatabase(async () => {
21384
- await this.db.update(roomTable).set({ ...room, agentId: this.agentId }).where(eq(roomTable.id, room.id));
22775
+ await this.db.update(roomTable).set({ ...room, agentId: this.agentId }).where(eq2(roomTable.id, room.id));
21385
22776
  });
21386
22777
  }
21387
22778
  async createRooms(rooms) {
@@ -21401,19 +22792,19 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
21401
22792
  throw new Error("Room ID is required");
21402
22793
  return this.withDatabase(async () => {
21403
22794
  await this.db.transaction(async (tx) => {
21404
- await tx.delete(roomTable).where(eq(roomTable.id, roomId));
22795
+ await tx.delete(roomTable).where(eq2(roomTable.id, roomId));
21405
22796
  });
21406
22797
  });
21407
22798
  }
21408
22799
  async getRoomsForParticipant(entityId) {
21409
22800
  return this.withDatabase(async () => {
21410
- const result = await this.db.select({ roomId: participantTable.roomId }).from(participantTable).innerJoin(roomTable, eq(participantTable.roomId, roomTable.id)).where(and(eq(participantTable.entityId, entityId), eq(roomTable.agentId, this.agentId)));
22801
+ const result = await this.db.select({ roomId: participantTable.roomId }).from(participantTable).innerJoin(roomTable, eq2(participantTable.roomId, roomTable.id)).where(and(eq2(participantTable.entityId, entityId), eq2(roomTable.agentId, this.agentId)));
21411
22802
  return result.map((row) => row.roomId);
21412
22803
  });
21413
22804
  }
21414
22805
  async getRoomsForParticipants(entityIds) {
21415
22806
  return this.withDatabase(async () => {
21416
- const result = await this.db.selectDistinct({ roomId: participantTable.roomId }).from(participantTable).innerJoin(roomTable, eq(participantTable.roomId, roomTable.id)).where(and(inArray(participantTable.entityId, entityIds), eq(roomTable.agentId, this.agentId)));
22807
+ const result = await this.db.selectDistinct({ roomId: participantTable.roomId }).from(participantTable).innerJoin(roomTable, eq2(participantTable.roomId, roomTable.id)).where(and(inArray(participantTable.entityId, entityIds), eq2(roomTable.agentId, this.agentId)));
21417
22808
  return result.map((row) => row.roomId);
21418
22809
  });
21419
22810
  }
@@ -21427,7 +22818,13 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
21427
22818
  }).onConflictDoNothing();
21428
22819
  return true;
21429
22820
  } catch (error) {
21430
- logger7.error(`Error adding participant to room: ${error instanceof Error ? error.message : String(error)}, entityId: ${entityId}, roomId: ${roomId}, agentId: ${this.agentId}`);
22821
+ logger9.error({
22822
+ src: "plugin:sql",
22823
+ entityId,
22824
+ roomId,
22825
+ agentId: this.agentId,
22826
+ error: error instanceof Error ? error.message : String(error)
22827
+ }, "Failed to add participant to room");
21431
22828
  return false;
21432
22829
  }
21433
22830
  });
@@ -21441,10 +22838,14 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
21441
22838
  agentId: this.agentId
21442
22839
  }));
21443
22840
  await this.db.insert(participantTable).values(values).onConflictDoNothing().execute();
21444
- logger7.debug(`${entityIds.length} Entities linked successfully`);
21445
22841
  return true;
21446
22842
  } catch (error) {
21447
- logger7.error(`Error adding participants to room: ${error instanceof Error ? error.message : String(error)}, entityIdSample: ${entityIds[0]}, roomId: ${roomId}, agentId: ${this.agentId}`);
22843
+ logger9.error({
22844
+ src: "plugin:sql",
22845
+ roomId,
22846
+ agentId: this.agentId,
22847
+ error: error instanceof Error ? error.message : String(error)
22848
+ }, "Failed to add participants to room");
21448
22849
  return false;
21449
22850
  }
21450
22851
  });
@@ -21453,13 +22854,17 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
21453
22854
  return this.withDatabase(async () => {
21454
22855
  try {
21455
22856
  const result = await this.db.transaction(async (tx) => {
21456
- return await tx.delete(participantTable).where(and(eq(participantTable.entityId, entityId), eq(participantTable.roomId, roomId))).returning();
22857
+ return await tx.delete(participantTable).where(and(eq2(participantTable.entityId, entityId), eq2(participantTable.roomId, roomId))).returning();
21457
22858
  });
21458
22859
  const removed = result.length > 0;
21459
- logger7.debug(`Participant ${removed ? "removed" : "not found"}: entityId: ${entityId}, roomId: ${roomId}, removed: ${removed}`);
21460
22860
  return removed;
21461
22861
  } catch (error) {
21462
- logger7.error(`Error removing participant from room: ${error instanceof Error ? error.message : String(error)}, entityId: ${entityId}, roomId: ${roomId}`);
22862
+ logger9.error({
22863
+ src: "plugin:sql",
22864
+ entityId,
22865
+ roomId,
22866
+ error: error instanceof Error ? error.message : String(error)
22867
+ }, "Failed to remove participant from room");
21463
22868
  return false;
21464
22869
  }
21465
22870
  });
@@ -21470,7 +22875,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
21470
22875
  id: participantTable.id,
21471
22876
  entityId: participantTable.entityId,
21472
22877
  roomId: participantTable.roomId
21473
- }).from(participantTable).where(eq(participantTable.entityId, entityId));
22878
+ }).from(participantTable).where(eq2(participantTable.entityId, entityId));
21474
22879
  const entities = await this.getEntitiesByIds([entityId]);
21475
22880
  if (!entities || !entities.length) {
21476
22881
  return [];
@@ -21483,13 +22888,19 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
21483
22888
  }
21484
22889
  async getParticipantsForRoom(roomId) {
21485
22890
  return this.withDatabase(async () => {
21486
- const result = await this.db.select({ entityId: participantTable.entityId }).from(participantTable).where(eq(participantTable.roomId, roomId));
22891
+ const result = await this.db.select({ entityId: participantTable.entityId }).from(participantTable).where(eq2(participantTable.roomId, roomId));
21487
22892
  return result.map((row) => row.entityId);
21488
22893
  });
21489
22894
  }
22895
+ async isRoomParticipant(roomId, entityId) {
22896
+ return this.withDatabase(async () => {
22897
+ const result = await this.db.select().from(participantTable).where(and(eq2(participantTable.roomId, roomId), eq2(participantTable.entityId, entityId))).limit(1);
22898
+ return result.length > 0;
22899
+ });
22900
+ }
21490
22901
  async getParticipantUserState(roomId, entityId) {
21491
22902
  return this.withDatabase(async () => {
21492
- const result = await this.db.select({ roomState: participantTable.roomState }).from(participantTable).where(and(eq(participantTable.roomId, roomId), eq(participantTable.entityId, entityId), eq(participantTable.agentId, this.agentId))).limit(1);
22903
+ const result = await this.db.select({ roomState: participantTable.roomState }).from(participantTable).where(and(eq2(participantTable.roomId, roomId), eq2(participantTable.entityId, entityId), eq2(participantTable.agentId, this.agentId))).limit(1);
21493
22904
  return result[0]?.roomState ?? null;
21494
22905
  });
21495
22906
  }
@@ -21497,10 +22908,16 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
21497
22908
  return this.withDatabase(async () => {
21498
22909
  try {
21499
22910
  await this.db.transaction(async (tx) => {
21500
- await tx.update(participantTable).set({ roomState: state }).where(and(eq(participantTable.roomId, roomId), eq(participantTable.entityId, entityId), eq(participantTable.agentId, this.agentId)));
22911
+ await tx.update(participantTable).set({ roomState: state }).where(and(eq2(participantTable.roomId, roomId), eq2(participantTable.entityId, entityId), eq2(participantTable.agentId, this.agentId)));
21501
22912
  });
21502
22913
  } catch (error) {
21503
- logger7.error(`Error setting participant follow state: roomId: ${roomId}, entityId: ${entityId}, state: ${state}, error: ${error instanceof Error ? error.message : String(error)}`);
22914
+ logger9.error({
22915
+ src: "plugin:sql",
22916
+ roomId,
22917
+ entityId,
22918
+ state,
22919
+ error: error instanceof Error ? error.message : String(error)
22920
+ }, "Failed to set participant follow state");
21504
22921
  throw error;
21505
22922
  }
21506
22923
  });
@@ -21520,7 +22937,12 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
21520
22937
  await this.db.insert(relationshipTable).values(saveParams);
21521
22938
  return true;
21522
22939
  } catch (error) {
21523
- logger7.error(`Error creating relationship: ${error instanceof Error ? error.message : String(error)}, saveParams: ${JSON.stringify(saveParams)}`);
22940
+ logger9.error({
22941
+ src: "plugin:sql",
22942
+ agentId: this.agentId,
22943
+ error: error instanceof Error ? error.message : String(error),
22944
+ saveParams
22945
+ }, "Error creating relationship");
21524
22946
  return false;
21525
22947
  }
21526
22948
  });
@@ -21531,9 +22953,14 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
21531
22953
  await this.db.update(relationshipTable).set({
21532
22954
  tags: relationship.tags || [],
21533
22955
  metadata: relationship.metadata || {}
21534
- }).where(eq(relationshipTable.id, relationship.id));
22956
+ }).where(eq2(relationshipTable.id, relationship.id));
21535
22957
  } catch (error) {
21536
- logger7.error(`Error updating relationship: ${error instanceof Error ? error.message : String(error)}, relationship: ${JSON.stringify(relationship)}`);
22958
+ logger9.error({
22959
+ src: "plugin:sql",
22960
+ agentId: this.agentId,
22961
+ error: error instanceof Error ? error.message : String(error),
22962
+ relationshipId: relationship.id
22963
+ }, "Error updating relationship");
21537
22964
  throw error;
21538
22965
  }
21539
22966
  });
@@ -21541,7 +22968,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
21541
22968
  async getRelationship(params) {
21542
22969
  return this.withDatabase(async () => {
21543
22970
  const { sourceEntityId, targetEntityId } = params;
21544
- const result = await this.db.select().from(relationshipTable).where(and(eq(relationshipTable.sourceEntityId, sourceEntityId), eq(relationshipTable.targetEntityId, targetEntityId)));
22971
+ const result = await this.db.select().from(relationshipTable).where(and(eq2(relationshipTable.sourceEntityId, sourceEntityId), eq2(relationshipTable.targetEntityId, targetEntityId)));
21545
22972
  if (result.length === 0)
21546
22973
  return null;
21547
22974
  const relationship = result[0];
@@ -21562,13 +22989,13 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
21562
22989
  const { entityId, tags } = params;
21563
22990
  let query;
21564
22991
  if (tags && tags.length > 0) {
21565
- query = sql23`
22992
+ query = sql25`
21566
22993
  SELECT * FROM ${relationshipTable}
21567
22994
  WHERE (${relationshipTable.sourceEntityId} = ${entityId} OR ${relationshipTable.targetEntityId} = ${entityId})
21568
- AND ${relationshipTable.tags} && CAST(ARRAY[${sql23.join(tags, sql23`, `)}] AS text[])
22995
+ AND ${relationshipTable.tags} && CAST(ARRAY[${sql25.join(tags, sql25`, `)}] AS text[])
21569
22996
  `;
21570
22997
  } else {
21571
- query = sql23`
22998
+ query = sql25`
21572
22999
  SELECT * FROM ${relationshipTable}
21573
23000
  WHERE ${relationshipTable.sourceEntityId} = ${entityId} OR ${relationshipTable.targetEntityId} = ${entityId}
21574
23001
  `;
@@ -21577,25 +23004,30 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
21577
23004
  return result.rows.map((relationship) => ({
21578
23005
  ...relationship,
21579
23006
  id: relationship.id,
21580
- sourceEntityId: relationship.sourceEntityId,
21581
- targetEntityId: relationship.targetEntityId,
21582
- agentId: relationship.agentId,
23007
+ sourceEntityId: relationship.source_entity_id || relationship.sourceEntityId,
23008
+ targetEntityId: relationship.target_entity_id || relationship.targetEntityId,
23009
+ agentId: relationship.agent_id || relationship.agentId,
21583
23010
  tags: relationship.tags ?? [],
21584
23011
  metadata: relationship.metadata ?? {},
21585
- createdAt: relationship.createdAt ? relationship.createdAt instanceof Date ? relationship.createdAt.toISOString() : new Date(relationship.createdAt).toISOString() : new Date().toISOString()
23012
+ createdAt: relationship.created_at || relationship.createdAt ? (relationship.created_at || relationship.createdAt) instanceof Date ? (relationship.created_at || relationship.createdAt).toISOString() : new Date(relationship.created_at || relationship.createdAt).toISOString() : new Date().toISOString()
21586
23013
  }));
21587
23014
  });
21588
23015
  }
21589
23016
  async getCache(key) {
21590
23017
  return this.withDatabase(async () => {
21591
23018
  try {
21592
- const result = await this.db.select({ value: cacheTable.value }).from(cacheTable).where(and(eq(cacheTable.agentId, this.agentId), eq(cacheTable.key, key))).limit(1);
23019
+ const result = await this.db.select({ value: cacheTable.value }).from(cacheTable).where(and(eq2(cacheTable.agentId, this.agentId), eq2(cacheTable.key, key))).limit(1);
21593
23020
  if (result && result.length > 0 && result[0]) {
21594
23021
  return result[0].value;
21595
23022
  }
21596
23023
  return;
21597
23024
  } catch (error) {
21598
- logger7.error(`Error fetching cache: ${error instanceof Error ? error.message : String(error)}, key: ${key}, agentId: ${this.agentId}`);
23025
+ logger9.error({
23026
+ src: "plugin:sql",
23027
+ agentId: this.agentId,
23028
+ error: error instanceof Error ? error.message : String(error),
23029
+ key
23030
+ }, "Error fetching cache");
21599
23031
  return;
21600
23032
  }
21601
23033
  });
@@ -21615,7 +23047,12 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
21615
23047
  });
21616
23048
  return true;
21617
23049
  } catch (error) {
21618
- logger7.error(`Error setting cache: ${error instanceof Error ? error.message : String(error)}, key: ${key}, agentId: ${this.agentId}`);
23050
+ logger9.error({
23051
+ src: "plugin:sql",
23052
+ agentId: this.agentId,
23053
+ error: error instanceof Error ? error.message : String(error),
23054
+ key
23055
+ }, "Error setting cache");
21619
23056
  return false;
21620
23057
  }
21621
23058
  });
@@ -21624,11 +23061,16 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
21624
23061
  return this.withDatabase(async () => {
21625
23062
  try {
21626
23063
  await this.db.transaction(async (tx) => {
21627
- await tx.delete(cacheTable).where(and(eq(cacheTable.agentId, this.agentId), eq(cacheTable.key, key)));
23064
+ await tx.delete(cacheTable).where(and(eq2(cacheTable.agentId, this.agentId), eq2(cacheTable.key, key)));
21628
23065
  });
21629
23066
  return true;
21630
23067
  } catch (error) {
21631
- logger7.error(`Error deleting cache: ${error instanceof Error ? error.message : String(error)}, key: ${key}, agentId: ${this.agentId}`);
23068
+ logger9.error({
23069
+ src: "plugin:sql",
23070
+ agentId: this.agentId,
23071
+ error: error instanceof Error ? error.message : String(error),
23072
+ key
23073
+ }, "Error deleting cache");
21632
23074
  return false;
21633
23075
  }
21634
23076
  });
@@ -21646,24 +23088,24 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
21646
23088
  }
21647
23089
  async getWorld(id) {
21648
23090
  return this.withDatabase(async () => {
21649
- const result = await this.db.select().from(worldTable).where(eq(worldTable.id, id));
23091
+ const result = await this.db.select().from(worldTable).where(eq2(worldTable.id, id));
21650
23092
  return result.length > 0 ? result[0] : null;
21651
23093
  });
21652
23094
  }
21653
23095
  async getAllWorlds() {
21654
23096
  return this.withDatabase(async () => {
21655
- const result = await this.db.select().from(worldTable).where(eq(worldTable.agentId, this.agentId));
23097
+ const result = await this.db.select().from(worldTable).where(eq2(worldTable.agentId, this.agentId));
21656
23098
  return result;
21657
23099
  });
21658
23100
  }
21659
23101
  async updateWorld(world) {
21660
23102
  return this.withDatabase(async () => {
21661
- await this.db.update(worldTable).set(world).where(eq(worldTable.id, world.id));
23103
+ await this.db.update(worldTable).set(world).where(eq2(worldTable.id, world.id));
21662
23104
  });
21663
23105
  }
21664
23106
  async removeWorld(id) {
21665
23107
  return this.withDatabase(async () => {
21666
- await this.db.delete(worldTable).where(eq(worldTable.id, id));
23108
+ await this.db.delete(worldTable).where(eq2(worldTable.id, id));
21667
23109
  });
21668
23110
  }
21669
23111
  async createTask(task) {
@@ -21694,8 +23136,8 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
21694
23136
  async getTasks(params) {
21695
23137
  return this.withRetry(async () => {
21696
23138
  return this.withDatabase(async () => {
21697
- const result = await this.db.select().from(taskTable).where(and(eq(taskTable.agentId, this.agentId), ...params.roomId ? [eq(taskTable.roomId, params.roomId)] : [], ...params.tags && params.tags.length > 0 ? [
21698
- sql23`${taskTable.tags} @> ARRAY[${sql23.raw(params.tags.map((t) => `'${t.replace(/'/g, "''")}'`).join(", "))}]::text[]`
23139
+ const result = await this.db.select().from(taskTable).where(and(eq2(taskTable.agentId, this.agentId), ...params.roomId ? [eq2(taskTable.roomId, params.roomId)] : [], ...params.tags && params.tags.length > 0 ? [
23140
+ sql25`${taskTable.tags} @> ARRAY[${sql25.raw(params.tags.map((t) => `'${t.replace(/'/g, "''")}'`).join(", "))}]::text[]`
21699
23141
  ] : []));
21700
23142
  return result.map((row) => ({
21701
23143
  id: row.id,
@@ -21712,7 +23154,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
21712
23154
  async getTasksByName(name) {
21713
23155
  return this.withRetry(async () => {
21714
23156
  return this.withDatabase(async () => {
21715
- const result = await this.db.select().from(taskTable).where(and(eq(taskTable.name, name), eq(taskTable.agentId, this.agentId)));
23157
+ const result = await this.db.select().from(taskTable).where(and(eq2(taskTable.name, name), eq2(taskTable.agentId, this.agentId)));
21716
23158
  return result.map((row) => ({
21717
23159
  id: row.id,
21718
23160
  name: row.name,
@@ -21728,7 +23170,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
21728
23170
  async getTask(id) {
21729
23171
  return this.withRetry(async () => {
21730
23172
  return this.withDatabase(async () => {
21731
- const result = await this.db.select().from(taskTable).where(and(eq(taskTable.id, id), eq(taskTable.agentId, this.agentId))).limit(1);
23173
+ const result = await this.db.select().from(taskTable).where(and(eq2(taskTable.id, id), eq2(taskTable.agentId, this.agentId))).limit(1);
21732
23174
  if (result.length === 0) {
21733
23175
  return null;
21734
23176
  }
@@ -21763,18 +23205,18 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
21763
23205
  if (task.metadata !== undefined) {
21764
23206
  updateValues.metadata = task.metadata;
21765
23207
  }
21766
- await this.db.update(taskTable).set(updateValues).where(and(eq(taskTable.id, id), eq(taskTable.agentId, this.agentId)));
23208
+ await this.db.update(taskTable).set(updateValues).where(and(eq2(taskTable.id, id), eq2(taskTable.agentId, this.agentId)));
21767
23209
  });
21768
23210
  });
21769
23211
  }
21770
23212
  async deleteTask(id) {
21771
23213
  return this.withDatabase(async () => {
21772
- await this.db.delete(taskTable).where(eq(taskTable.id, id));
23214
+ await this.db.delete(taskTable).where(eq2(taskTable.id, id));
21773
23215
  });
21774
23216
  }
21775
23217
  async getMemoriesByWorldId(params) {
21776
23218
  return this.withDatabase(async () => {
21777
- const rooms = await this.db.select({ id: roomTable.id }).from(roomTable).where(and(eq(roomTable.worldId, params.worldId), eq(roomTable.agentId, this.agentId)));
23219
+ const rooms = await this.db.select({ id: roomTable.id }).from(roomTable).where(and(eq2(roomTable.worldId, params.worldId), eq2(roomTable.agentId, this.agentId)));
21778
23220
  if (rooms.length === 0) {
21779
23221
  return [];
21780
23222
  }
@@ -21789,27 +23231,27 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
21789
23231
  }
21790
23232
  async deleteRoomsByWorldId(worldId) {
21791
23233
  return this.withDatabase(async () => {
21792
- const rooms = await this.db.select({ id: roomTable.id }).from(roomTable).where(and(eq(roomTable.worldId, worldId), eq(roomTable.agentId, this.agentId)));
23234
+ const rooms = await this.db.select({ id: roomTable.id }).from(roomTable).where(and(eq2(roomTable.worldId, worldId), eq2(roomTable.agentId, this.agentId)));
21793
23235
  if (rooms.length === 0) {
21794
- logger7.debug(`No rooms found for worldId ${worldId} and agentId ${this.agentId} to delete.`);
21795
23236
  return;
21796
23237
  }
21797
23238
  const roomIds = rooms.map((room) => room.id);
21798
23239
  if (roomIds.length > 0) {
21799
23240
  await this.db.delete(logTable).where(inArray(logTable.roomId, roomIds));
21800
- logger7.debug(`Deleted logs for ${roomIds.length} rooms in world ${worldId}.`);
21801
23241
  await this.db.delete(participantTable).where(inArray(participantTable.roomId, roomIds));
21802
- logger7.debug(`Deleted participants for ${roomIds.length} rooms in world ${worldId}.`);
21803
23242
  const memoriesInRooms = await this.db.select({ id: memoryTable.id }).from(memoryTable).where(inArray(memoryTable.roomId, roomIds));
21804
23243
  const memoryIdsInRooms = memoriesInRooms.map((m) => m.id);
21805
23244
  if (memoryIdsInRooms.length > 0) {
21806
23245
  await this.db.delete(embeddingTable).where(inArray(embeddingTable.memoryId, memoryIdsInRooms));
21807
- logger7.debug(`Deleted embeddings for ${memoryIdsInRooms.length} memories in world ${worldId}.`);
21808
23246
  await this.db.delete(memoryTable).where(inArray(memoryTable.id, memoryIdsInRooms));
21809
- logger7.debug(`Deleted ${memoryIdsInRooms.length} memories in world ${worldId}.`);
21810
23247
  }
21811
23248
  await this.db.delete(roomTable).where(inArray(roomTable.id, roomIds));
21812
- logger7.debug(`Deleted ${roomIds.length} rooms for worldId ${worldId}.`);
23249
+ logger9.debug({
23250
+ src: "plugin:sql",
23251
+ worldId,
23252
+ roomsDeleted: roomIds.length,
23253
+ memoriesDeleted: memoryIdsInRooms.length
23254
+ }, "World cleanup completed");
21813
23255
  }
21814
23256
  });
21815
23257
  }
@@ -21828,7 +23270,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
21828
23270
  };
21829
23271
  await this.db.insert(messageServerTable).values(serverToInsert).onConflictDoNothing();
21830
23272
  if (data.id) {
21831
- const existing = await this.db.select().from(messageServerTable).where(eq(messageServerTable.id, data.id)).limit(1);
23273
+ const existing = await this.db.select().from(messageServerTable).where(eq2(messageServerTable.id, data.id)).limit(1);
21832
23274
  if (existing.length > 0) {
21833
23275
  return {
21834
23276
  id: existing[0].id,
@@ -21861,7 +23303,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
21861
23303
  }
21862
23304
  async getMessageServerById(serverId) {
21863
23305
  return this.withDatabase(async () => {
21864
- const results = await this.db.select().from(messageServerTable).where(eq(messageServerTable.id, serverId)).limit(1);
23306
+ const results = await this.db.select().from(messageServerTable).where(eq2(messageServerTable.id, serverId)).limit(1);
21865
23307
  return results.length > 0 ? {
21866
23308
  id: results[0].id,
21867
23309
  name: results[0].name,
@@ -21873,6 +23315,26 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
21873
23315
  } : null;
21874
23316
  });
21875
23317
  }
23318
+ async getMessageServerByRlsServerId(rlsServerId) {
23319
+ return this.withDatabase(async () => {
23320
+ const results = await this.db.execute(sql25`
23321
+ SELECT id, name, source_type, source_id, metadata, created_at, updated_at
23322
+ FROM message_servers
23323
+ WHERE server_id = ${rlsServerId}
23324
+ LIMIT 1
23325
+ `);
23326
+ const rows = results.rows || results;
23327
+ return rows.length > 0 ? {
23328
+ id: rows[0].id,
23329
+ name: rows[0].name,
23330
+ sourceType: rows[0].source_type,
23331
+ sourceId: rows[0].source_id || undefined,
23332
+ metadata: rows[0].metadata || undefined,
23333
+ createdAt: new Date(rows[0].created_at),
23334
+ updatedAt: new Date(rows[0].updated_at)
23335
+ } : null;
23336
+ });
23337
+ }
21876
23338
  async createChannel(data, participantIds) {
21877
23339
  return this.withDatabase(async () => {
21878
23340
  const newId = data.id || v4_default();
@@ -21892,9 +23354,9 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
21892
23354
  await this.db.transaction(async (tx) => {
21893
23355
  await tx.insert(channelTable).values(channelToInsert);
21894
23356
  if (participantIds && participantIds.length > 0) {
21895
- const participantValues = participantIds.map((userId) => ({
23357
+ const participantValues = participantIds.map((entityId) => ({
21896
23358
  channelId: newId,
21897
- userId
23359
+ entityId
21898
23360
  }));
21899
23361
  await tx.insert(channelParticipantsTable).values(participantValues).onConflictDoNothing();
21900
23362
  }
@@ -21902,9 +23364,9 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
21902
23364
  return channelToInsert;
21903
23365
  });
21904
23366
  }
21905
- async getChannelsForServer(serverId) {
23367
+ async getChannelsForMessageServer(messageServerId) {
21906
23368
  return this.withDatabase(async () => {
21907
- const results = await this.db.select().from(channelTable).where(eq(channelTable.messageServerId, serverId));
23369
+ const results = await this.db.select().from(channelTable).where(eq2(channelTable.messageServerId, messageServerId));
21908
23370
  return results.map((r) => ({
21909
23371
  id: r.id,
21910
23372
  messageServerId: r.messageServerId,
@@ -21921,7 +23383,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
21921
23383
  }
21922
23384
  async getChannelDetails(channelId) {
21923
23385
  return this.withDatabase(async () => {
21924
- const results = await this.db.select().from(channelTable).where(eq(channelTable.id, channelId)).limit(1);
23386
+ const results = await this.db.select().from(channelTable).where(eq2(channelTable.id, channelId)).limit(1);
21925
23387
  return results.length > 0 ? {
21926
23388
  id: results[0].id,
21927
23389
  messageServerId: results[0].messageServerId,
@@ -21959,7 +23421,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
21959
23421
  }
21960
23422
  async getMessageById(id) {
21961
23423
  return this.withDatabase(async () => {
21962
- const rows = await this.db.select().from(messageTable).where(eq(messageTable.id, id)).limit(1);
23424
+ const rows = await this.db.select().from(messageTable).where(eq2(messageTable.id, id)).limit(1);
21963
23425
  return rows?.[0] ?? null;
21964
23426
  });
21965
23427
  }
@@ -21978,7 +23440,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
21978
23440
  inReplyToRootMessageId: patch.inReplyToRootMessageId ?? existing.inReplyToRootMessageId,
21979
23441
  updatedAt
21980
23442
  };
21981
- await this.db.update(messageTable).set(next).where(eq(messageTable.id, id));
23443
+ await this.db.update(messageTable).set(next).where(eq2(messageTable.id, id));
21982
23444
  return {
21983
23445
  ...existing,
21984
23446
  ...next
@@ -21987,7 +23449,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
21987
23449
  }
21988
23450
  async getMessagesForChannel(channelId, limit = 50, beforeTimestamp) {
21989
23451
  return this.withDatabase(async () => {
21990
- const conditions = [eq(messageTable.channelId, channelId)];
23452
+ const conditions = [eq2(messageTable.channelId, channelId)];
21991
23453
  if (beforeTimestamp) {
21992
23454
  conditions.push(lt(messageTable.createdAt, beforeTimestamp));
21993
23455
  }
@@ -22010,7 +23472,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
22010
23472
  }
22011
23473
  async deleteMessage(messageId) {
22012
23474
  return this.withDatabase(async () => {
22013
- await this.db.delete(messageTable).where(eq(messageTable.id, messageId));
23475
+ await this.db.delete(messageTable).where(eq2(messageTable.id, messageId));
22014
23476
  });
22015
23477
  }
22016
23478
  async updateChannel(channelId, updates) {
@@ -22022,13 +23484,13 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
22022
23484
  updateData.name = updates.name;
22023
23485
  if (updates.metadata !== undefined)
22024
23486
  updateData.metadata = updates.metadata;
22025
- await tx.update(channelTable).set(updateData).where(eq(channelTable.id, channelId));
23487
+ await tx.update(channelTable).set(updateData).where(eq2(channelTable.id, channelId));
22026
23488
  if (updates.participantCentralUserIds !== undefined) {
22027
- await tx.delete(channelParticipantsTable).where(eq(channelParticipantsTable.channelId, channelId));
23489
+ await tx.delete(channelParticipantsTable).where(eq2(channelParticipantsTable.channelId, channelId));
22028
23490
  if (updates.participantCentralUserIds.length > 0) {
22029
- const participantValues = updates.participantCentralUserIds.map((userId) => ({
23491
+ const participantValues = updates.participantCentralUserIds.map((entityId) => ({
22030
23492
  channelId,
22031
- userId
23493
+ entityId
22032
23494
  }));
22033
23495
  await tx.insert(channelParticipantsTable).values(participantValues).onConflictDoNothing();
22034
23496
  }
@@ -22044,53 +23506,59 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
22044
23506
  async deleteChannel(channelId) {
22045
23507
  return this.withDatabase(async () => {
22046
23508
  await this.db.transaction(async (tx) => {
22047
- await tx.delete(messageTable).where(eq(messageTable.channelId, channelId));
22048
- await tx.delete(channelParticipantsTable).where(eq(channelParticipantsTable.channelId, channelId));
22049
- await tx.delete(channelTable).where(eq(channelTable.id, channelId));
23509
+ await tx.delete(messageTable).where(eq2(messageTable.channelId, channelId));
23510
+ await tx.delete(channelParticipantsTable).where(eq2(channelParticipantsTable.channelId, channelId));
23511
+ await tx.delete(channelTable).where(eq2(channelTable.id, channelId));
22050
23512
  });
22051
23513
  });
22052
23514
  }
22053
- async addChannelParticipants(channelId, userIds) {
23515
+ async addChannelParticipants(channelId, entityIds) {
22054
23516
  return this.withDatabase(async () => {
22055
- if (!userIds || userIds.length === 0)
23517
+ if (!entityIds || entityIds.length === 0)
22056
23518
  return;
22057
- const participantValues = userIds.map((userId) => ({
23519
+ const participantValues = entityIds.map((entityId) => ({
22058
23520
  channelId,
22059
- userId
23521
+ entityId
22060
23522
  }));
22061
23523
  await this.db.insert(channelParticipantsTable).values(participantValues).onConflictDoNothing();
22062
23524
  });
22063
23525
  }
22064
23526
  async getChannelParticipants(channelId) {
22065
23527
  return this.withDatabase(async () => {
22066
- const results = await this.db.select({ userId: channelParticipantsTable.userId }).from(channelParticipantsTable).where(eq(channelParticipantsTable.channelId, channelId));
22067
- return results.map((r) => r.userId);
23528
+ const results = await this.db.select({ entityId: channelParticipantsTable.entityId }).from(channelParticipantsTable).where(eq2(channelParticipantsTable.channelId, channelId));
23529
+ return results.map((r) => r.entityId);
23530
+ });
23531
+ }
23532
+ async isChannelParticipant(channelId, entityId) {
23533
+ return this.withDatabase(async () => {
23534
+ const result = await this.db.select().from(channelParticipantsTable).where(and(eq2(channelParticipantsTable.channelId, channelId), eq2(channelParticipantsTable.entityId, entityId))).limit(1);
23535
+ return result.length > 0;
22068
23536
  });
22069
23537
  }
22070
- async addAgentToServer(serverId, agentId) {
23538
+ async addAgentToMessageServer(messageServerId, agentId) {
22071
23539
  return this.withDatabase(async () => {
22072
- await this.db.insert(serverAgentsTable).values({
22073
- serverId,
23540
+ await this.db.insert(messageServerAgentsTable).values({
23541
+ messageServerId,
22074
23542
  agentId
22075
23543
  }).onConflictDoNothing();
22076
23544
  });
22077
23545
  }
22078
- async getAgentsForServer(serverId) {
23546
+ async getAgentsForMessageServer(messageServerId) {
22079
23547
  return this.withDatabase(async () => {
22080
- const results = await this.db.select({ agentId: serverAgentsTable.agentId }).from(serverAgentsTable).where(eq(serverAgentsTable.serverId, serverId));
23548
+ const results = await this.db.select({ agentId: messageServerAgentsTable.agentId }).from(messageServerAgentsTable).where(eq2(messageServerAgentsTable.messageServerId, messageServerId));
22081
23549
  return results.map((r) => r.agentId);
22082
23550
  });
22083
23551
  }
22084
- async removeAgentFromServer(serverId, agentId) {
23552
+ async removeAgentFromMessageServer(messageServerId, agentId) {
22085
23553
  return this.withDatabase(async () => {
22086
- await this.db.delete(serverAgentsTable).where(and(eq(serverAgentsTable.serverId, serverId), eq(serverAgentsTable.agentId, agentId)));
23554
+ await this.db.delete(messageServerAgentsTable).where(and(eq2(messageServerAgentsTable.messageServerId, messageServerId), eq2(messageServerAgentsTable.agentId, agentId)));
22087
23555
  });
22088
23556
  }
22089
23557
  async findOrCreateDmChannel(user1Id, user2Id, messageServerId) {
22090
23558
  return this.withDatabase(async () => {
22091
23559
  const ids = [user1Id, user2Id].sort();
22092
23560
  const dmChannelName = `DM-${ids[0]}-${ids[1]}`;
22093
- const existingChannels = await this.db.select().from(channelTable).where(and(eq(channelTable.type, ChannelType.DM), eq(channelTable.name, dmChannelName), eq(channelTable.messageServerId, messageServerId))).limit(1);
23561
+ const existingChannels = await this.db.select().from(channelTable).where(and(eq2(channelTable.type, ChannelType.DM), eq2(channelTable.name, dmChannelName), eq2(channelTable.messageServerId, messageServerId))).limit(1);
22094
23562
  if (existingChannels.length > 0) {
22095
23563
  return {
22096
23564
  id: existingChannels[0].id,
@@ -22124,11 +23592,14 @@ class PgliteDatabaseAdapter extends BaseDrizzleAdapter {
22124
23592
  this.manager = manager;
22125
23593
  this.db = drizzle(this.manager.getConnection());
22126
23594
  }
23595
+ async withEntityContext(_entityId, callback) {
23596
+ return this.db.transaction(callback);
23597
+ }
22127
23598
  async getEntityByIds(entityIds) {
22128
23599
  return this.getEntitiesByIds(entityIds);
22129
23600
  }
22130
23601
  async getMemoriesByServerId(_params) {
22131
- logger8.warn("getMemoriesByServerId called but not implemented - returning empty array");
23602
+ logger10.warn({ src: "plugin:sql" }, "getMemoriesByServerId called but not implemented");
22132
23603
  return [];
22133
23604
  }
22134
23605
  async ensureAgentExists(agent) {
@@ -22153,13 +23624,13 @@ class PgliteDatabaseAdapter extends BaseDrizzleAdapter {
22153
23624
  }
22154
23625
  async withDatabase(operation) {
22155
23626
  if (this.manager.isShuttingDown()) {
22156
- logger8.warn("Database is shutting down");
23627
+ logger10.warn({ src: "plugin:sql" }, "Database is shutting down");
22157
23628
  return null;
22158
23629
  }
22159
23630
  return operation();
22160
23631
  }
22161
23632
  async init() {
22162
- logger8.debug("PGliteDatabaseAdapter initialized, skipping automatic migrations.");
23633
+ logger10.debug({ src: "plugin:sql" }, "PGliteDatabaseAdapter initialized");
22163
23634
  }
22164
23635
  async isReady() {
22165
23636
  return !this.manager.isShuttingDown();
@@ -22223,17 +23694,17 @@ var plugin = {
22223
23694
  priority: 0,
22224
23695
  schema: exports_schema,
22225
23696
  init: async (_config, runtime) => {
22226
- logger9.info("plugin-sql (browser) init starting...");
23697
+ logger11.info({ src: "plugin:sql" }, "plugin-sql (browser) init starting");
22227
23698
  try {
22228
23699
  const isReady = await runtime.isReady();
22229
23700
  if (isReady) {
22230
- logger9.info("Database adapter already registered, skipping creation");
23701
+ logger11.info({ src: "plugin:sql" }, "Database adapter already registered, skipping creation");
22231
23702
  return;
22232
23703
  }
22233
23704
  } catch (error) {}
22234
23705
  const dbAdapter = createDatabaseAdapter({}, runtime.agentId);
22235
23706
  runtime.registerDatabaseAdapter(dbAdapter);
22236
- logger9.info("Browser database adapter (PGlite) created and registered");
23707
+ logger11.info({ src: "plugin:sql" }, "Browser database adapter (PGlite) created and registered");
22237
23708
  }
22238
23709
  };
22239
23710
  var index_browser_default = plugin;
@@ -22244,5 +23715,5 @@ export {
22244
23715
  DatabaseMigrationService
22245
23716
  };
22246
23717
 
22247
- //# debugId=5D30F97F3F7F064964756E2164756E21
23718
+ //# debugId=A4CD118ECB5E333164756E2164756E21
22248
23719
  //# sourceMappingURL=index.browser.js.map