@elizaos/core 1.0.0-beta.41 → 1.0.0-beta.43
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +12 -26
- package/dist/index.js +14 -15
- package/package.json +2 -2
package/dist/index.d.ts
CHANGED
|
@@ -1592,7 +1592,7 @@ declare function formatActions(actions: Action[]): string;
|
|
|
1592
1592
|
*
|
|
1593
1593
|
* @template DB - The type of the database instance.
|
|
1594
1594
|
* @abstract
|
|
1595
|
-
*
|
|
1595
|
+
* implements IDatabaseAdapter
|
|
1596
1596
|
*/
|
|
1597
1597
|
declare abstract class DatabaseAdapter<DB = unknown> implements IDatabaseAdapter {
|
|
1598
1598
|
/**
|
|
@@ -2089,15 +2089,15 @@ declare let logger: pino.Logger<string, boolean>;
|
|
|
2089
2089
|
declare const elizaLogger: pino.Logger<string, boolean>;
|
|
2090
2090
|
|
|
2091
2091
|
/**
|
|
2092
|
-
* Convert all double-brace bindings
|
|
2093
|
-
* to triple-brace bindings
|
|
2092
|
+
* Convert all double-brace bindings in a Handlebars template
|
|
2093
|
+
* to triple-brace bindings, so the output is NOT HTML-escaped.
|
|
2094
2094
|
*
|
|
2095
2095
|
* - Ignores block/partial/comment tags that start with # / ! >.
|
|
2096
|
-
* - Ignores the
|
|
2096
|
+
* - Ignores the else keyword.
|
|
2097
2097
|
* - Ignores bindings that are already triple-braced.
|
|
2098
2098
|
*
|
|
2099
|
-
* @param
|
|
2100
|
-
* @return
|
|
2099
|
+
* @param tpl Handlebars template source
|
|
2100
|
+
* @return Transformed template
|
|
2101
2101
|
*/
|
|
2102
2102
|
declare function upgradeDoubleToTriple(tpl: any): any;
|
|
2103
2103
|
/**
|
|
@@ -2260,9 +2260,6 @@ type ActionResponse = {
|
|
|
2260
2260
|
quote?: boolean;
|
|
2261
2261
|
reply?: boolean;
|
|
2262
2262
|
};
|
|
2263
|
-
declare const parseActionResponseFromText: (text: string) => {
|
|
2264
|
-
actions: ActionResponse;
|
|
2265
|
-
};
|
|
2266
2263
|
/**
|
|
2267
2264
|
* Truncate text to fit within the character limit, ensuring it ends at a complete sentence.
|
|
2268
2265
|
*/
|
|
@@ -2345,21 +2342,11 @@ declare class Semaphore {
|
|
|
2345
2342
|
release(): void;
|
|
2346
2343
|
}
|
|
2347
2344
|
/**
|
|
2348
|
-
*
|
|
2349
|
-
*
|
|
2350
|
-
|
|
2351
|
-
|
|
2352
|
-
*
|
|
2353
|
-
* @class
|
|
2354
|
-
* @implements { IAgentRuntime }
|
|
2355
|
-
* @property { number } #conversationLength - The maximum length of a conversation.
|
|
2356
|
-
* @property { UUID } agentId - The unique identifier for the agent.
|
|
2357
|
-
* @property { Character } character - The character associated with the agent.
|
|
2358
|
-
* @property { IDatabaseAdapter } adapter - The adapter for interacting with the database.
|
|
2359
|
-
* @property {Action[]} actions - The list of actions available to the agent.
|
|
2360
|
-
* @property {Evaluator[]} evaluators - The list of evaluators for decision making.
|
|
2361
|
-
* @property {Provider[]} providers - The list of providers for external services.
|
|
2362
|
-
* @property {Plugin[]} plugins - The list of plugins to extend functionality.
|
|
2345
|
+
* AgentRuntime provides the core runtime environment and lifecycle management for agents.
|
|
2346
|
+
*
|
|
2347
|
+
* Implements the IAgentRuntime interface, managing agent state, actions, plugins, providers, and database interaction.
|
|
2348
|
+
*
|
|
2349
|
+
* implements IAgentRuntime
|
|
2363
2350
|
*/
|
|
2364
2351
|
declare class AgentRuntime implements IAgentRuntime {
|
|
2365
2352
|
#private;
|
|
@@ -2766,7 +2753,6 @@ declare function initializeOnboarding(runtime: IAgentRuntime, world: World, conf
|
|
|
2766
2753
|
/**
|
|
2767
2754
|
* Encrypts sensitive data in a Character object
|
|
2768
2755
|
* @param {Character} character - The character object to encrypt secrets for
|
|
2769
|
-
* @param {IAgentRuntime} runtime - The runtime information needed for salt generation
|
|
2770
2756
|
* @returns {Character} - A copy of the character with encrypted secrets
|
|
2771
2757
|
*/
|
|
2772
2758
|
declare function encryptedCharacter(character: Character): Character;
|
|
@@ -2870,4 +2856,4 @@ declare function getCloudflareGatewayBaseURL(runtime: IAgentRuntime, provider: s
|
|
|
2870
2856
|
*/
|
|
2871
2857
|
declare function getProviderBaseURL(runtime: IAgentRuntime, provider: string, defaultBaseURL: string): string;
|
|
2872
2858
|
|
|
2873
|
-
export { type Action, type ActionEventPayload, type ActionExample, type Agent, AgentRuntime, AgentStatus, type AudioProcessingParams, type BaseMetadata, type BaseModelParams, CacheKeyPrefix, ChannelType, type Character, type ChunkRow, type Component, type ComponentData, type Content, type ControlMessage, type CustomMetadata, DatabaseAdapter, type DbConnection, type DeriveKeyAttestationData, type DescriptionMetadata, type DetokenizeTextParams, type DirectoryItem, type DocumentMetadata, type EmbeddingSearchResult, type EnhancedState, type Entity, type EntityPayload, type EvaluationExample, type Evaluator, type EvaluatorEventPayload, type EventDataObject, type EventHandler, type EventPayload, type EventPayloadMap, EventType, type FragmentMetadata, type GenerateTextParams, type Handler, type HandlerCallback, type IAgentRuntime, type IBrowserService, type IDatabaseAdapter, type IFileService, type IInstrumentationService, type IPdfService, type IVideoService, type ImageDescriptionParams, type ImageGenerationParams, type InstrumentationConfig, InstrumentationService, type InvokePayload, type JSONSchema, type KnowledgeItem, KnowledgeScope, type Log, type Media, type Memory, type MemoryMetadata, type MemoryRetrievalOptions, type MemoryScope, type MemorySearchOptions, MemoryType, type MemoryTypeAlias, type MessageExample, type MessageMemory, type MessageMetadata, type MessagePayload, type MessageReceivedHandlerParams, type MetadataObject, type ModelEventPayload, type ModelHandler, type ModelParamsMap, type ModelResultMap, ModelType, type ModelTypeName, type MultiRoomMemoryOptions, type ObjectGenerationParams, type OnboardingConfig, type Participant, PlatformPrefix, type Plugin, type Project, type ProjectAgent, type Provider, type ProviderResult, type Relationship, type RemoteAttestationMessage, type RemoteAttestationQuote, Role, type Room, type Route, type RunEventPayload, type RuntimeSettings, SOCKET_MESSAGE_TYPE, Semaphore, type ServerOwnershipState, Service, type ServiceConfig, type ServiceError, ServiceType, type ServiceTypeName, type Setting, type State, type StateArray, type StateObject, type StateValue, TEEMode, type Task, type TaskWorker, type TeeAgent, type TeePluginConfig, TeeType, type TeeVendorConfig, type TemplateType, type TestCase, type TestSuite, type TextEmbeddingParams, type TextGenerationParams, type TextToSpeechParams, type TokenizeTextParams, type TranscriptionParams, type TypedEventHandler, type TypedService, type UUID, type UnifiedMemoryOptions, type UnifiedSearchOptions, VECTOR_DIMS, type Validator, type VideoProcessingParams, type World, type WorldPayload, type WorldSettings, addHeader, asUUID, booleanFooter, composeActionExamples, composePrompt, composePromptFromState, composeRandomUser, createMessageMemory, createServiceError, createSettingFromConfig, createUniqueUuid, decryptObjectValues, decryptStringValue as decryptSecret, decryptStringValue, decryptedCharacter, elizaLogger, encryptObjectValues, encryptStringValue, encryptedCharacter, findEntityByName, findWorldsForOwner, formatActionNames, formatActions, formatEntities, formatMessages, formatPosts, formatTimestamp, getBrowserService, getCloudflareGatewayBaseURL, getEntityDetails, getFileService, getMemoryText, getPdfService, getProviderBaseURL, getSalt, getTypedService, getUserServerRole, getVideoService, getWavHeader, getWorldSettings, initializeOnboarding, isCustomMetadata, isDescriptionMetadata, isDocumentMemory, isDocumentMetadata, isFragmentMemory, isFragmentMetadata, isMessageMetadata, logger, messageHandlerTemplate, normalizeJsonString,
|
|
2859
|
+
export { type Action, type ActionEventPayload, type ActionExample, type ActionResponse, type Agent, AgentRuntime, AgentStatus, type AudioProcessingParams, type BaseMetadata, type BaseModelParams, CacheKeyPrefix, ChannelType, type Character, type ChunkRow, type Component, type ComponentData, type Content, type ControlMessage, type CustomMetadata, DatabaseAdapter, type DbConnection, type DeriveKeyAttestationData, type DescriptionMetadata, type DetokenizeTextParams, type DirectoryItem, type DocumentMetadata, type EmbeddingSearchResult, type EnhancedState, type Entity, type EntityPayload, type EvaluationExample, type Evaluator, type EvaluatorEventPayload, type EventDataObject, type EventHandler, type EventPayload, type EventPayloadMap, EventType, type FragmentMetadata, type GenerateTextParams, type Handler, type HandlerCallback, type IAgentRuntime, type IBrowserService, type IDatabaseAdapter, type IFileService, type IInstrumentationService, type IPdfService, type IVideoService, type ImageDescriptionParams, type ImageGenerationParams, type InstrumentationConfig, InstrumentationService, type InvokePayload, type JSONSchema, type KnowledgeItem, KnowledgeScope, type Log, type Media, type Memory, type MemoryMetadata, type MemoryRetrievalOptions, type MemoryScope, type MemorySearchOptions, MemoryType, type MemoryTypeAlias, type MessageExample, type MessageMemory, type MessageMetadata, type MessagePayload, type MessageReceivedHandlerParams, type MetadataObject, type ModelEventPayload, type ModelHandler, type ModelParamsMap, type ModelResultMap, ModelType, type ModelTypeName, type MultiRoomMemoryOptions, type ObjectGenerationParams, type OnboardingConfig, type Participant, PlatformPrefix, type Plugin, type Project, type ProjectAgent, type Provider, type ProviderResult, type Relationship, type RemoteAttestationMessage, type RemoteAttestationQuote, Role, type Room, type Route, type RunEventPayload, type RuntimeSettings, SOCKET_MESSAGE_TYPE, Semaphore, type ServerOwnershipState, Service, type ServiceConfig, type ServiceError, ServiceType, type ServiceTypeName, type Setting, type State, type StateArray, type StateObject, type StateValue, TEEMode, type Task, type TaskWorker, type TeeAgent, type TeePluginConfig, TeeType, type TeeVendorConfig, type TemplateType, type TestCase, type TestSuite, type TextEmbeddingParams, type TextGenerationParams, type TextToSpeechParams, type TokenizeTextParams, type TranscriptionParams, type TypedEventHandler, type TypedService, type UUID, type UnifiedMemoryOptions, type UnifiedSearchOptions, VECTOR_DIMS, type Validator, type VideoProcessingParams, type World, type WorldPayload, type WorldSettings, addHeader, asUUID, booleanFooter, composeActionExamples, composePrompt, composePromptFromState, composeRandomUser, createMessageMemory, createServiceError, createSettingFromConfig, createUniqueUuid, decryptObjectValues, decryptStringValue as decryptSecret, decryptStringValue, decryptedCharacter, elizaLogger, encryptObjectValues, encryptStringValue, encryptedCharacter, findEntityByName, findWorldsForOwner, formatActionNames, formatActions, formatEntities, formatMessages, formatPosts, formatTimestamp, getBrowserService, getCloudflareGatewayBaseURL, getEntityDetails, getFileService, getMemoryText, getPdfService, getProviderBaseURL, getSalt, getTypedService, getUserServerRole, getVideoService, getWavHeader, getWorldSettings, initializeOnboarding, isCustomMetadata, isDescriptionMetadata, isDocumentMemory, isDocumentMetadata, isFragmentMemory, isFragmentMetadata, isMessageMetadata, logger, messageHandlerTemplate, normalizeJsonString, parseBooleanFromText, parseJSONObjectFromText, parseKeyValueXml, postCreationTemplate, prependWavHeader, safeReplacer, saltSettingValue, saltWorldSettings, shouldRespondTemplate, splitChunks, stringToUuid, trimTokens, truncateToCompleteSentence, unsaltSettingValue, unsaltWorldSettings, updateWorldSettings, upgradeDoubleToTriple, uuidSchema, validateUuid };
|
package/dist/index.js
CHANGED
|
@@ -1,26 +1,26 @@
|
|
|
1
|
-
var v=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var f=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var mt=f(jr=>{"use strict";jr.parse=function(n,e){return new lt(n,e).parse()};var lt=class n{constructor(e,t){this.source=e,this.transform=t||sa,this.position=0,this.entries=[],this.recorded=[],this.dimension=0}isEof(){return this.position>=this.source.length}nextCharacter(){var e=this.source[this.position++];return e==="\\"?{value:this.source[this.position++],escaped:!0}:{value:e,escaped:!1}}record(e){this.recorded.push(e)}newEntry(e){var t;(this.recorded.length>0||e)&&(t=this.recorded.join(""),t==="NULL"&&!e&&(t=null),t!==null&&(t=this.transform(t)),this.entries.push(t),this.recorded=[])}consumeDimensions(){if(this.source[0]==="[")for(;!this.isEof();){var e=this.nextCharacter();if(e.value==="=")break}}parse(e){var t,r,s;for(this.consumeDimensions();!this.isEof();)if(t=this.nextCharacter(),t.value==="{"&&!s)this.dimension++,this.dimension>1&&(r=new n(this.source.substr(this.position-1),this.transform),this.entries.push(r.parse(!0)),this.position+=r.position-2);else if(t.value==="}"&&!s){if(this.dimension--,!this.dimension&&(this.newEntry(),e))return this.entries}else t.value==='"'&&!t.escaped?(s&&this.newEntry(!0),s=!s):t.value===","&&!s?this.newEntry():this.record(t.value);if(this.dimension!==0)throw new Error("array dimension not balanced");return this.entries}};function sa(n){return n}});var Et=f((jm,Qr)=>{var ia=mt();Qr.exports={create:function(n,e){return{parse:function(){return ia.parse(n,e)}}}}});var Jr=f((Qm,Xr)=>{"use strict";var oa=/(\d{1,})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})(\.\d{1,})?.*?( BC)?$/,aa=/^(\d{1,})-(\d{2})-(\d{2})( BC)?$/,ca=/([Z+-])(\d{2})?:?(\d{2})?:?(\d{2})?/,ua=/^-?infinity$/;Xr.exports=function(e){if(ua.test(e))return Number(e.replace("i","I"));var t=oa.exec(e);if(!t)return da(e)||null;var r=!!t[8],s=parseInt(t[1],10);r&&(s=zr(s));var i=parseInt(t[2],10)-1,o=t[3],a=parseInt(t[4],10),c=parseInt(t[5],10),u=parseInt(t[6],10),d=t[7];d=d?1e3*parseFloat(d):0;var l,m=la(e);return m!=null?(l=new Date(Date.UTC(s,i,o,a,c,u,d)),pt(s)&&l.setUTCFullYear(s),m!==0&&l.setTime(l.getTime()-m)):(l=new Date(s,i,o,a,c,u,d),pt(s)&&l.setFullYear(s)),l};function da(n){var e=aa.exec(n);if(e){var t=parseInt(e[1],10),r=!!e[4];r&&(t=zr(t));var s=parseInt(e[2],10)-1,i=e[3],o=new Date(t,s,i);return pt(t)&&o.setFullYear(t),o}}function la(n){if(n.endsWith("+00"))return 0;var e=ca.exec(n.split(" ")[1]);if(e){var t=e[1];if(t==="Z")return 0;var r=t==="-"?-1:1,s=parseInt(e[2],10)*3600+parseInt(e[3]||0,10)*60+parseInt(e[4]||0,10);return s*r*1e3}}function zr(n){return-(n-1)}function pt(n){return n>=0&&n<100}});var en=f((zm,Zr)=>{Zr.exports=Ea;var ma=Object.prototype.hasOwnProperty;function Ea(n){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var r in t)ma.call(t,r)&&(n[r]=t[r])}return n}});var nn=f((Xm,rn)=>{"use strict";var pa=en();rn.exports=te;function te(n){if(!(this instanceof te))return new te(n);pa(this,Ia(n))}var ha=["seconds","minutes","hours","days","months","years"];te.prototype.toPostgres=function(){var n=ha.filter(this.hasOwnProperty,this);return this.milliseconds&&n.indexOf("seconds")<0&&n.push("seconds"),n.length===0?"0":n.map(function(e){var t=this[e]||0;return e==="seconds"&&this.milliseconds&&(t=(t+this.milliseconds/1e3).toFixed(6).replace(/\.?0+$/,"")),t+" "+e},this).join(" ")};var _a={years:"Y",months:"M",days:"D",hours:"H",minutes:"M",seconds:"S"},Sa=["years","months","days"],ga=["hours","minutes","seconds"];te.prototype.toISOString=te.prototype.toISO=function(){var n=Sa.map(t,this).join(""),e=ga.map(t,this).join("");return"P"+n+"T"+e;function t(r){var s=this[r]||0;return r==="seconds"&&this.milliseconds&&(s=(s+this.milliseconds/1e3).toFixed(6).replace(/0+$/,"")),s+_a[r]}};var ht="([+-]?\\d+)",fa=ht+"\\s+years?",Ta=ht+"\\s+mons?",Aa=ht+"\\s+days?",ya="([+-])?([\\d]*):(\\d\\d):(\\d\\d)\\.?(\\d{1,6})?",Ra=new RegExp([fa,Ta,Aa,ya].map(function(n){return"("+n+")?"}).join("\\s*")),tn={years:2,months:4,days:6,hours:9,minutes:10,seconds:11,milliseconds:12},Ma=["hours","minutes","seconds","milliseconds"];function va(n){var e=n+"000000".slice(n.length);return parseInt(e,10)/1e3}function Ia(n){if(!n)return{};var e=Ra.exec(n),t=e[8]==="-";return Object.keys(tn).reduce(function(r,s){var i=tn[s],o=e[i];return!o||(o=s==="milliseconds"?va(o):parseInt(o,10),!o)||(t&&~Ma.indexOf(s)&&(o*=-1),r[s]=o),r},{})}});var on=f((Jm,sn)=>{"use strict";sn.exports=function(e){if(/^\\x/.test(e))return new Buffer(e.substr(2),"hex");for(var t="",r=0;r<e.length;)if(e[r]!=="\\")t+=e[r],++r;else if(/[0-7]{3}/.test(e.substr(r+1,3)))t+=String.fromCharCode(parseInt(e.substr(r+1,3),8)),r+=4;else{for(var s=1;r+s<e.length&&e[r+s]==="\\";)s++;for(var i=0;i<Math.floor(s/2);++i)t+="\\";r+=Math.floor(s/2)*2}return new Buffer(t,"binary")}});var En=f((Zm,mn)=>{var pe=mt(),he=Et(),xe=Jr(),cn=nn(),un=on();function we(n){return function(t){return t===null?t:n(t)}}function dn(n){return n===null?n:n==="TRUE"||n==="t"||n==="true"||n==="y"||n==="yes"||n==="on"||n==="1"}function Pa(n){return n?pe.parse(n,dn):null}function Ua(n){return parseInt(n,10)}function _t(n){return n?pe.parse(n,we(Ua)):null}function La(n){return n?pe.parse(n,we(function(e){return ln(e).trim()})):null}var Oa=function(n){if(!n)return null;var e=he.create(n,function(t){return t!==null&&(t=Tt(t)),t});return e.parse()},St=function(n){if(!n)return null;var e=he.create(n,function(t){return t!==null&&(t=parseFloat(t)),t});return e.parse()},V=function(n){if(!n)return null;var e=he.create(n);return e.parse()},gt=function(n){if(!n)return null;var e=he.create(n,function(t){return t!==null&&(t=xe(t)),t});return e.parse()},ba=function(n){if(!n)return null;var e=he.create(n,function(t){return t!==null&&(t=cn(t)),t});return e.parse()},Ca=function(n){return n?pe.parse(n,we(un)):null},ft=function(n){return parseInt(n,10)},ln=function(n){var e=String(n);return/^\d+$/.test(e)?e:n},an=function(n){return n?pe.parse(n,we(JSON.parse)):null},Tt=function(n){return n[0]!=="("?null:(n=n.substring(1,n.length-1).split(","),{x:parseFloat(n[0]),y:parseFloat(n[1])})},Na=function(n){if(n[0]!=="<"&&n[1]!=="(")return null;for(var e="(",t="",r=!1,s=2;s<n.length-1;s++){if(r||(e+=n[s]),n[s]===")"){r=!0;continue}else if(!r)continue;n[s]!==","&&(t+=n[s])}var i=Tt(e);return i.radius=parseFloat(t),i},Da=function(n){n(20,ln),n(21,ft),n(23,ft),n(26,ft),n(700,parseFloat),n(701,parseFloat),n(16,dn),n(1082,xe),n(1114,xe),n(1184,xe),n(600,Tt),n(651,V),n(718,Na),n(1e3,Pa),n(1001,Ca),n(1005,_t),n(1007,_t),n(1028,_t),n(1016,La),n(1017,Oa),n(1021,St),n(1022,St),n(1231,St),n(1014,V),n(1015,V),n(1008,V),n(1009,V),n(1040,V),n(1041,V),n(1115,gt),n(1182,gt),n(1185,gt),n(1186,cn),n(1187,ba),n(17,un),n(114,JSON.parse.bind(JSON)),n(3802,JSON.parse.bind(JSON)),n(199,an),n(3807,an),n(3907,V),n(2951,V),n(791,V),n(1183,V),n(1270,V)};mn.exports={init:Da}});var hn=f((eE,pn)=>{"use strict";var x=1e6;function xa(n){var e=n.readInt32BE(0),t=n.readUInt32BE(4),r="";e<0&&(e=~e+(t===0),t=~t+1>>>0,r="-");var s="",i,o,a,c,u,d;{if(i=e%x,e=e/x>>>0,o=4294967296*i+t,t=o/x>>>0,a=""+(o-x*t),t===0&&e===0)return r+a+s;for(c="",u=6-a.length,d=0;d<u;d++)c+="0";s=c+a+s}{if(i=e%x,e=e/x>>>0,o=4294967296*i+t,t=o/x>>>0,a=""+(o-x*t),t===0&&e===0)return r+a+s;for(c="",u=6-a.length,d=0;d<u;d++)c+="0";s=c+a+s}{if(i=e%x,e=e/x>>>0,o=4294967296*i+t,t=o/x>>>0,a=""+(o-x*t),t===0&&e===0)return r+a+s;for(c="",u=6-a.length,d=0;d<u;d++)c+="0";s=c+a+s}return i=e%x,o=4294967296*i+t,a=""+o%x,r+a+s}pn.exports=xa});var Tn=f((tE,fn)=>{var wa=hn(),I=function(n,e,t,r,s){t=t||0,r=r||!1,s=s||function(E,p,g){return E*Math.pow(2,g)+p};var i=t>>3,o=function(E){return r?~E&255:E},a=255,c=8-t%8;e<c&&(a=255<<8-e&255,c=e),t&&(a=a>>t%8);var u=0;t%8+e>=8&&(u=s(0,o(n[i])&a,c));for(var d=e+t>>3,l=i+1;l<d;l++)u=s(u,o(n[l]),8);var m=(e+t)%8;return m>0&&(u=s(u,o(n[d])>>8-m,m)),u},gn=function(n,e,t){var r=Math.pow(2,t-1)-1,s=I(n,1),i=I(n,t,1);if(i===0)return 0;var o=1,a=function(u,d,l){u===0&&(u=1);for(var m=1;m<=l;m++)o/=2,(d&1<<l-m)>0&&(u+=o);return u},c=I(n,e,t+1,!1,a);return i==Math.pow(2,t+1)-1?c===0?s===0?1/0:-1/0:NaN:(s===0?1:-1)*Math.pow(2,i-r)*c},ka=function(n){return I(n,1)==1?-1*(I(n,15,1,!0)+1):I(n,15,1)},_n=function(n){return I(n,1)==1?-1*(I(n,31,1,!0)+1):I(n,31,1)},Va=function(n){return gn(n,23,8)},Fa=function(n){return gn(n,52,11)},Ga=function(n){var e=I(n,16,32);if(e==49152)return NaN;for(var t=Math.pow(1e4,I(n,16,16)),r=0,s=[],i=I(n,16),o=0;o<i;o++)r+=I(n,16,64+16*o)*t,t/=1e4;var a=Math.pow(10,I(n,16,48));return(e===0?1:-1)*Math.round(r*a)/a},Sn=function(n,e){var t=I(e,1),r=I(e,63,1),s=new Date((t===0?1:-1)*r/1e3+9466848e5);return n||s.setTime(s.getTime()+s.getTimezoneOffset()*6e4),s.usec=r%1e3,s.getMicroSeconds=function(){return this.usec},s.setMicroSeconds=function(i){this.usec=i},s.getUTCMicroSeconds=function(){return this.usec},s},_e=function(n){for(var e=I(n,32),t=I(n,32,32),r=I(n,32,64),s=96,i=[],o=0;o<e;o++)i[o]=I(n,32,s),s+=32,s+=32;var a=function(u){var d=I(n,32,s);if(s+=32,d==4294967295)return null;var l;if(u==23||u==20)return l=I(n,d*8,s),s+=d*8,l;if(u==25)return l=n.toString(this.encoding,s>>3,(s+=d<<3)>>3),l;console.log("ERROR: ElementType not implemented: "+u)},c=function(u,d){var l=[],m;if(u.length>1){var E=u.shift();for(m=0;m<E;m++)l[m]=c(u,d);u.unshift(E)}else for(m=0;m<u[0];m++)l[m]=a(d);return l};return c(i,r)},Ba=function(n){return n.toString("utf8")},Wa=function(n){return n===null?null:I(n,8)>0},qa=function(n){n(20,wa),n(21,ka),n(23,_n),n(26,_n),n(1700,Ga),n(700,Va),n(701,Fa),n(16,Wa),n(1114,Sn.bind(null,!1)),n(1184,Sn.bind(null,!0)),n(1e3,_e),n(1007,_e),n(1016,_e),n(1008,_e),n(1009,_e),n(25,Ba)};fn.exports={init:qa}});var yn=f((rE,An)=>{An.exports={BOOL:16,BYTEA:17,CHAR:18,INT8:20,INT2:21,INT4:23,REGPROC:24,TEXT:25,OID:26,TID:27,XID:28,CID:29,JSON:114,XML:142,PG_NODE_TREE:194,SMGR:210,PATH:602,POLYGON:604,CIDR:650,FLOAT4:700,FLOAT8:701,ABSTIME:702,RELTIME:703,TINTERVAL:704,CIRCLE:718,MACADDR8:774,MONEY:790,MACADDR:829,INET:869,ACLITEM:1033,BPCHAR:1042,VARCHAR:1043,DATE:1082,TIME:1083,TIMESTAMP:1114,TIMESTAMPTZ:1184,INTERVAL:1186,TIMETZ:1266,BIT:1560,VARBIT:1562,NUMERIC:1700,REFCURSOR:1790,REGPROCEDURE:2202,REGOPER:2203,REGOPERATOR:2204,REGCLASS:2205,REGTYPE:2206,UUID:2950,TXID_SNAPSHOT:2970,PG_LSN:3220,PG_NDISTINCT:3361,PG_DEPENDENCIES:3402,TSVECTOR:3614,TSQUERY:3615,GTSVECTOR:3642,REGCONFIG:3734,REGDICTIONARY:3769,JSONB:3802,REGNAMESPACE:4089,REGROLE:4096}});var fe=f(ge=>{var Ka=En(),Ha=Tn(),$a=Et(),Ya=yn();ge.getTypeParser=ja;ge.setTypeParser=Qa;ge.arrayParser=$a;ge.builtins=Ya;var Se={text:{},binary:{}};function Rn(n){return String(n)}function ja(n,e){return e=e||"text",Se[e]&&Se[e][n]||Rn}function Qa(n,e,t){typeof e=="function"&&(t=e,e="text"),Se[e][n]=t}Ka.init(function(n,e){Se.text[n]=e});Ha.init(function(n,e){Se.binary[n]=e})});var Te=f((sE,At)=>{"use strict";At.exports={host:"localhost",user:process.platform==="win32"?process.env.USERNAME:process.env.USER,database:void 0,password:null,connectionString:void 0,port:5432,rows:0,binary:!1,max:10,idleTimeoutMillis:3e4,client_encoding:"",ssl:!1,application_name:void 0,fallback_application_name:void 0,options:void 0,parseInputDatesAsUTC:!1,statement_timeout:!1,lock_timeout:!1,idle_in_transaction_session_timeout:!1,query_timeout:!1,connect_timeout:0,keepalives:1,keepalives_idle:0};var re=fe(),za=re.getTypeParser(20,"text"),Xa=re.getTypeParser(1016,"text");At.exports.__defineSetter__("parseInt8",function(n){re.setTypeParser(20,"text",n?re.getTypeParser(23,"text"):za),re.setTypeParser(1016,"text",n?re.getTypeParser(1007,"text"):Xa)})});var ne=f((iE,vn)=>{"use strict";var Ja=Te();function Za(n){var e=n.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return'"'+e+'"'}function Mn(n){for(var e="{",t=0;t<n.length;t++)if(t>0&&(e=e+","),n[t]===null||typeof n[t]>"u")e=e+"NULL";else if(Array.isArray(n[t]))e=e+Mn(n[t]);else if(ArrayBuffer.isView(n[t])){var r=n[t];if(!(r instanceof Buffer)){var s=Buffer.from(r.buffer,r.byteOffset,r.byteLength);s.length===r.byteLength?r=s:r=s.slice(r.byteOffset,r.byteOffset+r.byteLength)}e+="\\\\x"+r.toString("hex")}else e+=Za(ke(n[t]));return e=e+"}",e}var ke=function(n,e){if(n==null)return null;if(typeof n=="object"){if(n instanceof Buffer)return n;if(ArrayBuffer.isView(n)){var t=Buffer.from(n.buffer,n.byteOffset,n.byteLength);return t.length===n.byteLength?t:t.slice(n.byteOffset,n.byteOffset+n.byteLength)}return n instanceof Date?Ja.parseInputDatesAsUTC?rc(n):tc(n):Array.isArray(n)?Mn(n):ec(n,e)}return n.toString()};function ec(n,e){if(n&&typeof n.toPostgres=="function"){if(e=e||[],e.indexOf(n)!==-1)throw new Error('circular reference detected while preparing "'+n+'" for query');return e.push(n),ke(n.toPostgres(ke),e)}return JSON.stringify(n)}function tc(n){var e=-n.getTimezoneOffset(),t=n.getFullYear(),r=t<1;r&&(t=Math.abs(t)+1);var s=String(t).padStart(4,"0")+"-"+String(n.getMonth()+1).padStart(2,"0")+"-"+String(n.getDate()).padStart(2,"0")+"T"+String(n.getHours()).padStart(2,"0")+":"+String(n.getMinutes()).padStart(2,"0")+":"+String(n.getSeconds()).padStart(2,"0")+"."+String(n.getMilliseconds()).padStart(3,"0");return e<0?(s+="-",e*=-1):s+="+",s+=String(Math.floor(e/60)).padStart(2,"0")+":"+String(e%60).padStart(2,"0"),r&&(s+=" BC"),s}function rc(n){var e=n.getUTCFullYear(),t=e<1;t&&(e=Math.abs(e)+1);var r=String(e).padStart(4,"0")+"-"+String(n.getUTCMonth()+1).padStart(2,"0")+"-"+String(n.getUTCDate()).padStart(2,"0")+"T"+String(n.getUTCHours()).padStart(2,"0")+":"+String(n.getUTCMinutes()).padStart(2,"0")+":"+String(n.getUTCSeconds()).padStart(2,"0")+"."+String(n.getUTCMilliseconds()).padStart(3,"0");return r+="+00:00",t&&(r+=" BC"),r}function nc(n,e,t){return n=typeof n=="string"?{text:n}:n,e&&(typeof e=="function"?n.callback=e:n.values=e),t&&(n.callback=t),n}var sc=function(n){return'"'+n.replace(/"/g,'""')+'"'},ic=function(n){for(var e=!1,t="'",r=0;r<n.length;r++){var s=n[r];s==="'"?t+=s+s:s==="\\"?(t+=s+s,e=!0):t+=s}return t+="'",e===!0&&(t=" E"+t),t};vn.exports={prepareValue:function(e){return ke(e)},normalizeQueryConfig:nc,escapeIdentifier:sc,escapeLiteral:ic}});var Pn=f((oE,In)=>{"use strict";var se=v("crypto");function yt(n){return se.createHash("md5").update(n,"utf-8").digest("hex")}function oc(n,e,t){var r=yt(e+n),s=yt(Buffer.concat([Buffer.from(r),t]));return"md5"+s}function ac(n){return se.createHash("sha256").update(n).digest()}function cc(n,e){return n=n.replace(/(\D)-/,"$1"),se.createHash(n).update(e).digest()}function uc(n,e){return se.createHmac("sha256",n).update(e).digest()}async function dc(n,e,t){return se.pbkdf2Sync(n,e,t,32,"sha256")}In.exports={postgresMd5PasswordHash:oc,randomBytes:se.randomBytes,deriveKey:dc,sha256:ac,hashByName:cc,hmacSha256:uc,md5:yt}});var bn=f((aE,On)=>{var Un=v("crypto");On.exports={postgresMd5PasswordHash:mc,randomBytes:lc,deriveKey:_c,sha256:Ec,hashByName:pc,hmacSha256:hc,md5:Rt};var Ln=Un.webcrypto||globalThis.crypto,Q=Ln.subtle,Mt=new TextEncoder;function lc(n){return Ln.getRandomValues(Buffer.alloc(n))}async function Rt(n){try{return Un.createHash("md5").update(n,"utf-8").digest("hex")}catch{let t=typeof n=="string"?Mt.encode(n):n,r=await Q.digest("MD5",t);return Array.from(new Uint8Array(r)).map(s=>s.toString(16).padStart(2,"0")).join("")}}async function mc(n,e,t){var r=await Rt(e+n),s=await Rt(Buffer.concat([Buffer.from(r),t]));return"md5"+s}async function Ec(n){return await Q.digest("SHA-256",n)}async function pc(n,e){return await Q.digest(n,e)}async function hc(n,e){let t=await Q.importKey("raw",n,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return await Q.sign("HMAC",t,Mt.encode(e))}async function _c(n,e,t){let r=await Q.importKey("raw",Mt.encode(n),"PBKDF2",!1,["deriveBits"]),s={name:"PBKDF2",hash:"SHA-256",salt:e,iterations:t};return await Q.deriveBits(s,r,32*8,["deriveBits"])}});var It=f((cE,vt)=>{"use strict";var Sc=parseInt(process.versions&&process.versions.node&&process.versions.node.split(".")[0])<15;Sc?vt.exports=Pn():vt.exports=bn()});var Dn=f((uE,Nn)=>{function z(n,e){return new Error("SASL channel binding: "+n+" when parsing public certificate "+e.toString("base64"))}function Pt(n,e){let t=n[e++];if(t<128)return{length:t,index:e};let r=t&127;if(r>4)throw z("bad length",n);t=0;for(let s=0;s<r;s++)t=t<<8|n[e++];return{length:t,index:e}}function Cn(n,e){if(n[e++]!==6)throw z("non-OID data",n);let{length:t,index:r}=Pt(n,e);e=r;let s=e+t,i=n[e++],o=(i/40>>0)+"."+i%40;for(;e<s;){let a=0;for(;e<s;){let c=n[e++];if(a=a<<7|c&127,c<128)break}o+="."+a}return{oid:o,index:e}}function Ae(n,e){if(n[e++]!==48)throw z("non-sequence data",n);return Pt(n,e)}function gc(n,e){e===void 0&&(e=0),e=Ae(n,e).index;let{length:t,index:r}=Ae(n,e);e=r+t,e=Ae(n,e).index;let{oid:s,index:i}=Cn(n,e);switch(s){case"1.2.840.113549.1.1.4":return"MD5";case"1.2.840.113549.1.1.5":return"SHA-1";case"1.2.840.113549.1.1.11":return"SHA-256";case"1.2.840.113549.1.1.12":return"SHA-384";case"1.2.840.113549.1.1.13":return"SHA-512";case"1.2.840.113549.1.1.14":return"SHA-224";case"1.2.840.113549.1.1.15":return"SHA512-224";case"1.2.840.113549.1.1.16":return"SHA512-256";case"1.2.840.10045.4.1":return"SHA-1";case"1.2.840.10045.4.3.1":return"SHA-224";case"1.2.840.10045.4.3.2":return"SHA-256";case"1.2.840.10045.4.3.3":return"SHA-384";case"1.2.840.10045.4.3.4":return"SHA-512";case"1.2.840.113549.1.1.10":{if(e=i,e=Ae(n,e).index,n[e++]!==160)throw z("non-tag data",n);e=Pt(n,e).index,e=Ae(n,e).index;let{oid:o}=Cn(n,e);switch(o){case"1.2.840.113549.2.5":return"MD5";case"1.3.14.3.2.26":return"SHA-1";case"2.16.840.1.101.3.4.2.1":return"SHA-256";case"2.16.840.1.101.3.4.2.2":return"SHA-384";case"2.16.840.1.101.3.4.2.3":return"SHA-512"}throw z("unknown hash OID "+o,n)}case"1.3.101.110":case"1.3.101.112":return"SHA-512";case"1.3.101.111":case"1.3.101.113":throw z("Ed448 certificate channel binding is not currently supported by Postgres")}throw z("unknown OID "+s,n)}Nn.exports={signatureAlgorithmHashFromCertificate:gc}});var Vn=f((dE,kn)=>{"use strict";var H=It(),{signatureAlgorithmHashFromCertificate:fc}=Dn();function Tc(n,e){let t=["SCRAM-SHA-256"];e&&t.unshift("SCRAM-SHA-256-PLUS");let r=t.find(o=>n.includes(o));if(!r)throw new Error("SASL: Only mechanism(s) "+t.join(" and ")+" are supported");if(r==="SCRAM-SHA-256-PLUS"&&typeof e.getPeerCertificate!="function")throw new Error("SASL: Mechanism SCRAM-SHA-256-PLUS requires a certificate");let s=H.randomBytes(18).toString("base64");return{mechanism:r,clientNonce:s,response:(r==="SCRAM-SHA-256-PLUS"?"p=tls-server-end-point":e?"y":"n")+",,n=*,r="+s,message:"SASLInitialResponse"}}async function Ac(n,e,t,r){if(n.message!=="SASLInitialResponse")throw new Error("SASL: Last message was not SASLInitialResponse");if(typeof e!="string")throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string");if(e==="")throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a non-empty string");if(typeof t!="string")throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: serverData must be a string");let s=Mc(t);if(s.nonce.startsWith(n.clientNonce)){if(s.nonce.length===n.clientNonce.length)throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce is too short")}else throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce does not start with client nonce");var i="n=*,r="+n.clientNonce,o="r="+s.nonce+",s="+s.salt+",i="+s.iteration;let a=r?"eSws":"biws";if(n.mechanism==="SCRAM-SHA-256-PLUS"){let O=r.getPeerCertificate().raw,M=fc(O);(M==="MD5"||M==="SHA-1")&&(M="SHA-256");let S=await H.hashByName(M,O);a=Buffer.concat([Buffer.from("p=tls-server-end-point,,"),Buffer.from(S)]).toString("base64")}var c="c="+a+",r="+s.nonce,u=i+","+o+","+c,d=Buffer.from(s.salt,"base64"),l=await H.deriveKey(e,d,s.iteration),m=await H.hmacSha256(l,"Client Key"),E=await H.sha256(m),p=await H.hmacSha256(E,u),g=Ic(Buffer.from(m),Buffer.from(p)).toString("base64"),A=await H.hmacSha256(l,"Server Key"),R=await H.hmacSha256(A,u);n.message="SASLResponse",n.serverSignature=Buffer.from(R).toString("base64"),n.response=c+",p="+g}function yc(n,e){if(n.message!=="SASLResponse")throw new Error("SASL: Last message was not SASLResponse");if(typeof e!="string")throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: serverData must be a string");let{serverSignature:t}=vc(e);if(t!==n.serverSignature)throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature does not match")}function Rc(n){if(typeof n!="string")throw new TypeError("SASL: text must be a string");return n.split("").map((e,t)=>n.charCodeAt(t)).every(e=>e>=33&&e<=43||e>=45&&e<=126)}function xn(n){return/^(?:[a-zA-Z0-9+/]{4})*(?:[a-zA-Z0-9+/]{2}==|[a-zA-Z0-9+/]{3}=)?$/.test(n)}function wn(n){if(typeof n!="string")throw new TypeError("SASL: attribute pairs text must be a string");return new Map(n.split(",").map(e=>{if(!/^.=/.test(e))throw new Error("SASL: Invalid attribute pair entry");let t=e[0],r=e.substring(2);return[t,r]}))}function Mc(n){let e=wn(n),t=e.get("r");if(t){if(!Rc(t))throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce must only contain printable characters")}else throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce missing");let r=e.get("s");if(r){if(!xn(r))throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: salt must be base64")}else throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: salt missing");let s=e.get("i");if(s){if(!/^[1-9][0-9]*$/.test(s))throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: invalid iteration count")}else throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: iteration missing");let i=parseInt(s,10);return{nonce:t,salt:r,iteration:i}}function vc(n){let t=wn(n).get("v");if(t){if(!xn(t))throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature must be base64")}else throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature is missing");return{serverSignature:t}}function Ic(n,e){if(!Buffer.isBuffer(n))throw new TypeError("first argument must be a Buffer");if(!Buffer.isBuffer(e))throw new TypeError("second argument must be a Buffer");if(n.length!==e.length)throw new Error("Buffer lengths must match");if(n.length===0)throw new Error("Buffers cannot be empty");return Buffer.from(n.map((t,r)=>n[r]^e[r]))}kn.exports={startSession:Tc,continueSession:Ac,finalizeSession:yc}});var Fe=f((lE,Fn)=>{"use strict";var Pc=fe();function Ve(n){this._types=n||Pc,this.text={},this.binary={}}Ve.prototype.getOverrides=function(n){switch(n){case"text":return this.text;case"binary":return this.binary;default:return{}}};Ve.prototype.setTypeParser=function(n,e,t){typeof e=="function"&&(t=e,e="text"),this.getOverrides(e)[n]=t};Ve.prototype.getTypeParser=function(n,e){return e=e||"text",this.getOverrides(e)[n]||this._types.getTypeParser(n,e)};Fn.exports=Ve});var Wn=f((mE,Bn)=>{"use strict";function ie(n,e={}){if(n.charAt(0)==="/"){let c=n.split(" ");return{host:c[0],database:c[1]}}let t={},r,s=!1;/ |%[^a-f0-9]|%[a-f0-9][^a-f0-9]/i.test(n)&&(n=encodeURI(n).replace(/%25(\d\d)/g,"%$1"));try{r=new URL(n,"postgres://base")}catch{r=new URL(n.replace("@/","@___DUMMY___/"),"postgres://base"),s=!0}for(let c of r.searchParams.entries())t[c[0]]=c[1];if(t.user=t.user||decodeURIComponent(r.username),t.password=t.password||decodeURIComponent(r.password),r.protocol=="socket:")return t.host=decodeURI(r.pathname),t.database=r.searchParams.get("db"),t.client_encoding=r.searchParams.get("encoding"),t;let i=s?"":r.hostname;t.host?i&&/^%2f/i.test(i)&&(r.pathname=i+r.pathname):t.host=decodeURIComponent(i),t.port||(t.port=r.port);let o=r.pathname.slice(1)||null;t.database=o?decodeURI(o):null,(t.ssl==="true"||t.ssl==="1")&&(t.ssl=!0),t.ssl==="0"&&(t.ssl=!1),(t.sslcert||t.sslkey||t.sslrootcert||t.sslmode)&&(t.ssl={});let a=t.sslcert||t.sslkey||t.sslrootcert?v("fs"):null;if(t.sslcert&&(t.ssl.cert=a.readFileSync(t.sslcert).toString()),t.sslkey&&(t.ssl.key=a.readFileSync(t.sslkey).toString()),t.sslrootcert&&(t.ssl.ca=a.readFileSync(t.sslrootcert).toString()),e.useLibpqCompat&&t.uselibpqcompat)throw new Error("Both useLibpqCompat and uselibpqcompat are set. Please use only one of them.");if(t.uselibpqcompat==="true"||e.useLibpqCompat)switch(t.sslmode){case"disable":{t.ssl=!1;break}case"prefer":{t.ssl.rejectUnauthorized=!1;break}case"require":{t.sslrootcert?t.ssl.checkServerIdentity=function(){}:t.ssl.rejectUnauthorized=!1;break}case"verify-ca":{if(!t.ssl.ca)throw new Error("SECURITY WARNING: Using sslmode=verify-ca requires specifying a CA with sslrootcert. If a public CA is used, verify-ca allows connections to a server that somebody else may have registered with the CA, making you vulnerable to Man-in-the-Middle attacks. Either specify a custom CA certificate with sslrootcert parameter or use sslmode=verify-full for proper security.");t.ssl.checkServerIdentity=function(){};break}case"verify-full":break}else switch(t.sslmode){case"disable":{t.ssl=!1;break}case"prefer":case"require":case"verify-ca":case"verify-full":break;case"no-verify":{t.ssl.rejectUnauthorized=!1;break}}return t}function Uc(n){return Object.entries(n).reduce((t,[r,s])=>(s!=null&&(t[r]=s),t),{})}function Gn(n){return Object.entries(n).reduce((t,[r,s])=>{if(r==="ssl"){let i=s;typeof i=="boolean"?t[r]=i:typeof i=="object"&&(t[r]=Uc(i))}else if(s!=null)if(r==="port"){if(s!==""){let i=parseInt(s,10);if(isNaN(i))throw new Error(`Invalid ${r}: ${s}`);t[r]=i}}else t[r]=s;return t},{})}function Lc(n){return Gn(ie(n))}Bn.exports=ie;ie.parse=ie;ie.toClientConfig=Gn;ie.parseIntoClientConfig=Lc});var Lt=f((EE,Hn)=>{"use strict";var Oc=v("dns"),Kn=Te(),qn=Wn().parse,D=function(n,e,t){return t===void 0?t=process.env["PG"+n.toUpperCase()]:t===!1||(t=process.env[t]),e[n]||t||Kn[n]},bc=function(){switch(process.env.PGSSLMODE){case"disable":return!1;case"prefer":case"require":case"verify-ca":case"verify-full":return!0;case"no-verify":return{rejectUnauthorized:!1}}return Kn.ssl},oe=function(n){return"'"+(""+n).replace(/\\/g,"\\\\").replace(/'/g,"\\'")+"'"},F=function(n,e,t){var r=e[t];r!=null&&n.push(t+"="+oe(r))},Ut=class{constructor(e){e=typeof e=="string"?qn(e):e||{},e.connectionString&&(e=Object.assign({},e,qn(e.connectionString))),this.user=D("user",e),this.database=D("database",e),this.database===void 0&&(this.database=this.user),this.port=parseInt(D("port",e),10),this.host=D("host",e),Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:D("password",e)}),this.binary=D("binary",e),this.options=D("options",e),this.ssl=typeof e.ssl>"u"?bc():e.ssl,typeof this.ssl=="string"&&this.ssl==="true"&&(this.ssl=!0),this.ssl==="no-verify"&&(this.ssl={rejectUnauthorized:!1}),this.ssl&&this.ssl.key&&Object.defineProperty(this.ssl,"key",{enumerable:!1}),this.client_encoding=D("client_encoding",e),this.replication=D("replication",e),this.isDomainSocket=!(this.host||"").indexOf("/"),this.application_name=D("application_name",e,"PGAPPNAME"),this.fallback_application_name=D("fallback_application_name",e,!1),this.statement_timeout=D("statement_timeout",e,!1),this.lock_timeout=D("lock_timeout",e,!1),this.idle_in_transaction_session_timeout=D("idle_in_transaction_session_timeout",e,!1),this.query_timeout=D("query_timeout",e,!1),e.connectionTimeoutMillis===void 0?this.connect_timeout=process.env.PGCONNECT_TIMEOUT||0:this.connect_timeout=Math.floor(e.connectionTimeoutMillis/1e3),e.keepAlive===!1?this.keepalives=0:e.keepAlive===!0&&(this.keepalives=1),typeof e.keepAliveInitialDelayMillis=="number"&&(this.keepalives_idle=Math.floor(e.keepAliveInitialDelayMillis/1e3))}getLibpqConnectionString(e){var t=[];F(t,this,"user"),F(t,this,"password"),F(t,this,"port"),F(t,this,"application_name"),F(t,this,"fallback_application_name"),F(t,this,"connect_timeout"),F(t,this,"options");var r=typeof this.ssl=="object"?this.ssl:this.ssl?{sslmode:this.ssl}:{};if(F(t,r,"sslmode"),F(t,r,"sslca"),F(t,r,"sslkey"),F(t,r,"sslcert"),F(t,r,"sslrootcert"),this.database&&t.push("dbname="+oe(this.database)),this.replication&&t.push("replication="+oe(this.replication)),this.host&&t.push("host="+oe(this.host)),this.isDomainSocket)return e(null,t.join(" "));this.client_encoding&&t.push("client_encoding="+oe(this.client_encoding)),Oc.lookup(this.host,function(s,i){return s?e(s,null):(t.push("hostaddr="+oe(i)),e(null,t.join(" ")))})}};Hn.exports=Ut});var bt=f((pE,Yn)=>{"use strict";var Cc=fe(),$n=/^([A-Za-z]+)(?: (\d+))?(?: (\d+))?/,Ot=class{constructor(e,t){this.command=null,this.rowCount=null,this.oid=null,this.rows=[],this.fields=[],this._parsers=void 0,this._types=t,this.RowCtor=null,this.rowAsArray=e==="array",this.rowAsArray&&(this.parseRow=this._parseRowAsArray),this._prebuiltEmptyResultObject=null}addCommandComplete(e){var t;e.text?t=$n.exec(e.text):t=$n.exec(e.command),t&&(this.command=t[1],t[3]?(this.oid=parseInt(t[2],10),this.rowCount=parseInt(t[3],10)):t[2]&&(this.rowCount=parseInt(t[2],10)))}_parseRowAsArray(e){for(var t=new Array(e.length),r=0,s=e.length;r<s;r++){var i=e[r];i!==null?t[r]=this._parsers[r](i):t[r]=null}return t}parseRow(e){for(var t={...this._prebuiltEmptyResultObject},r=0,s=e.length;r<s;r++){var i=e[r],o=this.fields[r].name;i!==null?t[o]=this._parsers[r](i):t[o]=null}return t}addRow(e){this.rows.push(e)}addFields(e){this.fields=e,this.fields.length&&(this._parsers=new Array(e.length));for(var t={},r=0;r<e.length;r++){var s=e[r];t[s.name]=null,this._types?this._parsers[r]=this._types.getTypeParser(s.dataTypeID,s.format||"text"):this._parsers[r]=Cc.getTypeParser(s.dataTypeID,s.format||"text")}this._prebuiltEmptyResultObject={...t}}};Yn.exports=Ot});var Xn=f((hE,zn)=>{"use strict";var{EventEmitter:Nc}=v("events"),jn=bt(),Qn=ne(),Ct=class extends Nc{constructor(e,t,r){super(),e=Qn.normalizeQueryConfig(e,t,r),this.text=e.text,this.values=e.values,this.rows=e.rows,this.types=e.types,this.name=e.name,this.queryMode=e.queryMode,this.binary=e.binary,this.portal=e.portal||"",this.callback=e.callback,this._rowMode=e.rowMode,process.domain&&e.callback&&(this.callback=process.domain.bind(e.callback)),this._result=new jn(this._rowMode,this.types),this._results=this._result,this._canceledDueToError=!1}requiresPreparation(){return this.queryMode==="extended"||this.name||this.rows?!0:!this.text||!this.values?!1:this.values.length>0}_checkForMultirow(){this._result.command&&(Array.isArray(this._results)||(this._results=[this._result]),this._result=new jn(this._rowMode,this._result._types),this._results.push(this._result))}handleRowDescription(e){this._checkForMultirow(),this._result.addFields(e.fields),this._accumulateRows=this.callback||!this.listeners("row").length}handleDataRow(e){let t;if(!this._canceledDueToError){try{t=this._result.parseRow(e.fields)}catch(r){this._canceledDueToError=r;return}this.emit("row",t,this._result),this._accumulateRows&&this._result.addRow(t)}}handleCommandComplete(e,t){this._checkForMultirow(),this._result.addCommandComplete(e),this.rows&&t.sync()}handleEmptyQuery(e){this.rows&&e.sync()}handleError(e,t){if(this._canceledDueToError&&(e=this._canceledDueToError,this._canceledDueToError=!1),this.callback)return this.callback(e);this.emit("error",e)}handleReadyForQuery(e){if(this._canceledDueToError)return this.handleError(this._canceledDueToError,e);if(this.callback)try{this.callback(null,this._results)}catch(t){process.nextTick(()=>{throw t})}this.emit("end",this._results)}submit(e){if(typeof this.text!="string"&&typeof this.name!="string")return new Error("A query must have either text or a name. Supplying neither is unsupported.");let t=e.parsedStatements[this.name];if(this.text&&t&&this.text!==t)return new Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`);if(this.values&&!Array.isArray(this.values))return new Error("Query values must be an array");if(this.requiresPreparation()){e.stream.cork&&e.stream.cork();try{this.prepare(e)}finally{e.stream.uncork&&e.stream.uncork()}}else e.query(this.text);return null}hasBeenParsed(e){return this.name&&e.parsedStatements[this.name]}handlePortalSuspended(e){this._getRows(e,this.rows)}_getRows(e,t){e.execute({portal:this.portal,rows:t}),t?e.flush():e.sync()}prepare(e){this.hasBeenParsed(e)||e.parse({text:this.text,name:this.name,types:this.types});try{e.bind({portal:this.portal,statement:this.name,values:this.values,binary:this.binary,valueMapper:Qn.prepareValue})}catch(t){this.handleError(t,e);return}e.describe({type:"P",name:this.portal||""}),this._getRows(e,this.rows)}handleCopyInResponse(e){e.sendCopyFail("No source stream defined")}handleCopyData(e,t){}};zn.exports=Ct});var Yt=f(_=>{"use strict";Object.defineProperty(_,"__esModule",{value:!0});_.NoticeMessage=_.DataRowMessage=_.CommandCompleteMessage=_.ReadyForQueryMessage=_.NotificationResponseMessage=_.BackendKeyDataMessage=_.AuthenticationMD5Password=_.ParameterStatusMessage=_.ParameterDescriptionMessage=_.RowDescriptionMessage=_.Field=_.CopyResponse=_.CopyDataMessage=_.DatabaseError=_.copyDone=_.emptyQuery=_.replicationStart=_.portalSuspended=_.noData=_.closeComplete=_.bindComplete=_.parseComplete=void 0;_.parseComplete={name:"parseComplete",length:5};_.bindComplete={name:"bindComplete",length:5};_.closeComplete={name:"closeComplete",length:5};_.noData={name:"noData",length:5};_.portalSuspended={name:"portalSuspended",length:5};_.replicationStart={name:"replicationStart",length:4};_.emptyQuery={name:"emptyQuery",length:4};_.copyDone={name:"copyDone",length:4};var Nt=class extends Error{constructor(e,t,r){super(e),this.length=t,this.name=r}};_.DatabaseError=Nt;var Dt=class{constructor(e,t){this.length=e,this.chunk=t,this.name="copyData"}};_.CopyDataMessage=Dt;var xt=class{constructor(e,t,r,s){this.length=e,this.name=t,this.binary=r,this.columnTypes=new Array(s)}};_.CopyResponse=xt;var wt=class{constructor(e,t,r,s,i,o,a){this.name=e,this.tableID=t,this.columnID=r,this.dataTypeID=s,this.dataTypeSize=i,this.dataTypeModifier=o,this.format=a}};_.Field=wt;var kt=class{constructor(e,t){this.length=e,this.fieldCount=t,this.name="rowDescription",this.fields=new Array(this.fieldCount)}};_.RowDescriptionMessage=kt;var Vt=class{constructor(e,t){this.length=e,this.parameterCount=t,this.name="parameterDescription",this.dataTypeIDs=new Array(this.parameterCount)}};_.ParameterDescriptionMessage=Vt;var Ft=class{constructor(e,t,r){this.length=e,this.parameterName=t,this.parameterValue=r,this.name="parameterStatus"}};_.ParameterStatusMessage=Ft;var Gt=class{constructor(e,t){this.length=e,this.salt=t,this.name="authenticationMD5Password"}};_.AuthenticationMD5Password=Gt;var Bt=class{constructor(e,t,r){this.length=e,this.processID=t,this.secretKey=r,this.name="backendKeyData"}};_.BackendKeyDataMessage=Bt;var Wt=class{constructor(e,t,r,s){this.length=e,this.processId=t,this.channel=r,this.payload=s,this.name="notification"}};_.NotificationResponseMessage=Wt;var qt=class{constructor(e,t){this.length=e,this.status=t,this.name="readyForQuery"}};_.ReadyForQueryMessage=qt;var Kt=class{constructor(e,t){this.length=e,this.text=t,this.name="commandComplete"}};_.CommandCompleteMessage=Kt;var Ht=class{constructor(e,t){this.length=e,this.fields=t,this.name="dataRow",this.fieldCount=t.length}};_.DataRowMessage=Ht;var $t=class{constructor(e,t){this.length=e,this.message=t,this.name="notice"}};_.NoticeMessage=$t});var Jn=f(Ge=>{"use strict";Object.defineProperty(Ge,"__esModule",{value:!0});Ge.Writer=void 0;var jt=class{constructor(e=256){this.size=e,this.offset=5,this.headerPosition=0,this.buffer=Buffer.allocUnsafe(e)}ensure(e){var t=this.buffer.length-this.offset;if(t<e){var r=this.buffer,s=r.length+(r.length>>1)+e;this.buffer=Buffer.allocUnsafe(s),r.copy(this.buffer)}}addInt32(e){return this.ensure(4),this.buffer[this.offset++]=e>>>24&255,this.buffer[this.offset++]=e>>>16&255,this.buffer[this.offset++]=e>>>8&255,this.buffer[this.offset++]=e>>>0&255,this}addInt16(e){return this.ensure(2),this.buffer[this.offset++]=e>>>8&255,this.buffer[this.offset++]=e>>>0&255,this}addCString(e){if(!e)this.ensure(1);else{var t=Buffer.byteLength(e);this.ensure(t+1),this.buffer.write(e,this.offset,"utf-8"),this.offset+=t}return this.buffer[this.offset++]=0,this}addString(e=""){var t=Buffer.byteLength(e);return this.ensure(t),this.buffer.write(e,this.offset),this.offset+=t,this}add(e){return this.ensure(e.length),e.copy(this.buffer,this.offset),this.offset+=e.length,this}join(e){if(e){this.buffer[this.headerPosition]=e;let t=this.offset-(this.headerPosition+1);this.buffer.writeInt32BE(t,this.headerPosition+1)}return this.buffer.slice(e?0:5,this.offset)}flush(e){var t=this.join(e);return this.offset=5,this.headerPosition=0,this.buffer=Buffer.allocUnsafe(this.size),t}};Ge.Writer=jt});var es=f(We=>{"use strict";Object.defineProperty(We,"__esModule",{value:!0});We.serialize=void 0;var Qt=Jn(),P=new Qt.Writer,Dc=n=>{P.addInt16(3).addInt16(0);for(let r of Object.keys(n))P.addCString(r).addCString(n[r]);P.addCString("client_encoding").addCString("UTF8");var e=P.addCString("").flush(),t=e.length+4;return new Qt.Writer().addInt32(t).add(e).flush()},xc=()=>{let n=Buffer.allocUnsafe(8);return n.writeInt32BE(8,0),n.writeInt32BE(80877103,4),n},wc=n=>P.addCString(n).flush(112),kc=function(n,e){return P.addCString(n).addInt32(Buffer.byteLength(e)).addString(e),P.flush(112)},Vc=function(n){return P.addString(n).flush(112)},Fc=n=>P.addCString(n).flush(81),Zn=[],Gc=n=>{let e=n.name||"";e.length>63&&(console.error("Warning! Postgres only supports 63 characters for query names."),console.error("You supplied %s (%s)",e,e.length),console.error("This can cause conflicts and silent errors executing queries"));let t=n.types||Zn;for(var r=t.length,s=P.addCString(e).addCString(n.text).addInt16(r),i=0;i<r;i++)s.addInt32(t[i]);return P.flush(80)},ae=new Qt.Writer,Bc=function(n,e){for(let t=0;t<n.length;t++){let r=e?e(n[t],t):n[t];r==null?(P.addInt16(0),ae.addInt32(-1)):r instanceof Buffer?(P.addInt16(1),ae.addInt32(r.length),ae.add(r)):(P.addInt16(0),ae.addInt32(Buffer.byteLength(r)),ae.addString(r))}},Wc=(n={})=>{let e=n.portal||"",t=n.statement||"",r=n.binary||!1,s=n.values||Zn,i=s.length;return P.addCString(e).addCString(t),P.addInt16(i),Bc(s,n.valueMapper),P.addInt16(i),P.add(ae.flush()),P.addInt16(r?1:0),P.flush(66)},qc=Buffer.from([69,0,0,0,9,0,0,0,0,0]),Kc=n=>{if(!n||!n.portal&&!n.rows)return qc;let e=n.portal||"",t=n.rows||0,r=Buffer.byteLength(e),s=4+r+1+4,i=Buffer.allocUnsafe(1+s);return i[0]=69,i.writeInt32BE(s,1),i.write(e,5,"utf-8"),i[r+5]=0,i.writeUInt32BE(t,i.length-4),i},Hc=(n,e)=>{let t=Buffer.allocUnsafe(16);return t.writeInt32BE(16,0),t.writeInt16BE(1234,4),t.writeInt16BE(5678,6),t.writeInt32BE(n,8),t.writeInt32BE(e,12),t},zt=(n,e)=>{let r=4+Buffer.byteLength(e)+1,s=Buffer.allocUnsafe(1+r);return s[0]=n,s.writeInt32BE(r,1),s.write(e,5,"utf-8"),s[r]=0,s},$c=P.addCString("P").flush(68),Yc=P.addCString("S").flush(68),jc=n=>n.name?zt(68,`${n.type}${n.name||""}`):n.type==="P"?$c:Yc,Qc=n=>{let e=`${n.type}${n.name||""}`;return zt(67,e)},zc=n=>P.add(n).flush(100),Xc=n=>zt(102,n),Be=n=>Buffer.from([n,0,0,0,4]),Jc=Be(72),Zc=Be(83),eu=Be(88),tu=Be(99),ru={startup:Dc,password:wc,requestSsl:xc,sendSASLInitialResponseMessage:kc,sendSCRAMClientFinalMessage:Vc,query:Fc,parse:Gc,bind:Wc,execute:Kc,describe:jc,close:Qc,flush:()=>Jc,sync:()=>Zc,end:()=>eu,copyData:zc,copyDone:()=>tu,copyFail:Xc,cancel:Hc};We.serialize=ru});var ts=f(qe=>{"use strict";Object.defineProperty(qe,"__esModule",{value:!0});qe.BufferReader=void 0;var nu=Buffer.allocUnsafe(0),Xt=class{constructor(e=0){this.offset=e,this.buffer=nu,this.encoding="utf-8"}setBuffer(e,t){this.offset=e,this.buffer=t}int16(){let e=this.buffer.readInt16BE(this.offset);return this.offset+=2,e}byte(){let e=this.buffer[this.offset];return this.offset++,e}int32(){let e=this.buffer.readInt32BE(this.offset);return this.offset+=4,e}uint32(){let e=this.buffer.readUInt32BE(this.offset);return this.offset+=4,e}string(e){let t=this.buffer.toString(this.encoding,this.offset,this.offset+e);return this.offset+=e,t}cstring(){let e=this.offset,t=e;for(;this.buffer[t++]!==0;);return this.offset=t,this.buffer.toString(this.encoding,e,t-1)}bytes(e){let t=this.buffer.slice(this.offset,this.offset+e);return this.offset+=e,t}};qe.BufferReader=Xt});var ss=f(Ke=>{"use strict";Object.defineProperty(Ke,"__esModule",{value:!0});Ke.Parser=void 0;var U=Yt(),su=ts(),Jt=1,iu=4,rs=Jt+iu,ns=Buffer.allocUnsafe(0),Zt=class{constructor(e){if(this.buffer=ns,this.bufferLength=0,this.bufferOffset=0,this.reader=new su.BufferReader,e?.mode==="binary")throw new Error("Binary mode not supported yet");this.mode=e?.mode||"text"}parse(e,t){this.mergeBuffer(e);let r=this.bufferOffset+this.bufferLength,s=this.bufferOffset;for(;s+rs<=r;){let i=this.buffer[s],o=this.buffer.readUInt32BE(s+Jt),a=Jt+o;if(a+s<=r){let c=this.handlePacket(s+rs,i,o,this.buffer);t(c),s+=a}else break}s===r?(this.buffer=ns,this.bufferLength=0,this.bufferOffset=0):(this.bufferLength=r-s,this.bufferOffset=s)}mergeBuffer(e){if(this.bufferLength>0){let t=this.bufferLength+e.byteLength;if(t+this.bufferOffset>this.buffer.byteLength){let s;if(t<=this.buffer.byteLength&&this.bufferOffset>=this.bufferLength)s=this.buffer;else{let i=this.buffer.byteLength*2;for(;t>=i;)i*=2;s=Buffer.allocUnsafe(i)}this.buffer.copy(s,0,this.bufferOffset,this.bufferOffset+this.bufferLength),this.buffer=s,this.bufferOffset=0}e.copy(this.buffer,this.bufferOffset+this.bufferLength),this.bufferLength=t}else this.buffer=e,this.bufferOffset=0,this.bufferLength=e.byteLength}handlePacket(e,t,r,s){switch(t){case 50:return U.bindComplete;case 49:return U.parseComplete;case 51:return U.closeComplete;case 110:return U.noData;case 115:return U.portalSuspended;case 99:return U.copyDone;case 87:return U.replicationStart;case 73:return U.emptyQuery;case 68:return this.parseDataRowMessage(e,r,s);case 67:return this.parseCommandCompleteMessage(e,r,s);case 90:return this.parseReadyForQueryMessage(e,r,s);case 65:return this.parseNotificationMessage(e,r,s);case 82:return this.parseAuthenticationResponse(e,r,s);case 83:return this.parseParameterStatusMessage(e,r,s);case 75:return this.parseBackendKeyData(e,r,s);case 69:return this.parseErrorMessage(e,r,s,"error");case 78:return this.parseErrorMessage(e,r,s,"notice");case 84:return this.parseRowDescriptionMessage(e,r,s);case 116:return this.parseParameterDescriptionMessage(e,r,s);case 71:return this.parseCopyInMessage(e,r,s);case 72:return this.parseCopyOutMessage(e,r,s);case 100:return this.parseCopyData(e,r,s);default:return new U.DatabaseError("received invalid response: "+t.toString(16),r,"error")}}parseReadyForQueryMessage(e,t,r){this.reader.setBuffer(e,r);let s=this.reader.string(1);return new U.ReadyForQueryMessage(t,s)}parseCommandCompleteMessage(e,t,r){this.reader.setBuffer(e,r);let s=this.reader.cstring();return new U.CommandCompleteMessage(t,s)}parseCopyData(e,t,r){let s=r.slice(e,e+(t-4));return new U.CopyDataMessage(t,s)}parseCopyInMessage(e,t,r){return this.parseCopyMessage(e,t,r,"copyInResponse")}parseCopyOutMessage(e,t,r){return this.parseCopyMessage(e,t,r,"copyOutResponse")}parseCopyMessage(e,t,r,s){this.reader.setBuffer(e,r);let i=this.reader.byte()!==0,o=this.reader.int16(),a=new U.CopyResponse(t,s,i,o);for(let c=0;c<o;c++)a.columnTypes[c]=this.reader.int16();return a}parseNotificationMessage(e,t,r){this.reader.setBuffer(e,r);let s=this.reader.int32(),i=this.reader.cstring(),o=this.reader.cstring();return new U.NotificationResponseMessage(t,s,i,o)}parseRowDescriptionMessage(e,t,r){this.reader.setBuffer(e,r);let s=this.reader.int16(),i=new U.RowDescriptionMessage(t,s);for(let o=0;o<s;o++)i.fields[o]=this.parseField();return i}parseField(){let e=this.reader.cstring(),t=this.reader.uint32(),r=this.reader.int16(),s=this.reader.uint32(),i=this.reader.int16(),o=this.reader.int32(),a=this.reader.int16()===0?"text":"binary";return new U.Field(e,t,r,s,i,o,a)}parseParameterDescriptionMessage(e,t,r){this.reader.setBuffer(e,r);let s=this.reader.int16(),i=new U.ParameterDescriptionMessage(t,s);for(let o=0;o<s;o++)i.dataTypeIDs[o]=this.reader.int32();return i}parseDataRowMessage(e,t,r){this.reader.setBuffer(e,r);let s=this.reader.int16(),i=new Array(s);for(let o=0;o<s;o++){let a=this.reader.int32();i[o]=a===-1?null:this.reader.string(a)}return new U.DataRowMessage(t,i)}parseParameterStatusMessage(e,t,r){this.reader.setBuffer(e,r);let s=this.reader.cstring(),i=this.reader.cstring();return new U.ParameterStatusMessage(t,s,i)}parseBackendKeyData(e,t,r){this.reader.setBuffer(e,r);let s=this.reader.int32(),i=this.reader.int32();return new U.BackendKeyDataMessage(t,s,i)}parseAuthenticationResponse(e,t,r){this.reader.setBuffer(e,r);let s=this.reader.int32(),i={name:"authenticationOk",length:t};switch(s){case 0:break;case 3:i.length===8&&(i.name="authenticationCleartextPassword");break;case 5:if(i.length===12){i.name="authenticationMD5Password";let o=this.reader.bytes(4);return new U.AuthenticationMD5Password(t,o)}break;case 10:{i.name="authenticationSASL",i.mechanisms=[];let o;do o=this.reader.cstring(),o&&i.mechanisms.push(o);while(o)}break;case 11:i.name="authenticationSASLContinue",i.data=this.reader.string(t-8);break;case 12:i.name="authenticationSASLFinal",i.data=this.reader.string(t-8);break;default:throw new Error("Unknown authenticationOk message type "+s)}return i}parseErrorMessage(e,t,r,s){this.reader.setBuffer(e,r);let i={},o=this.reader.string(1);for(;o!=="\0";)i[o]=this.reader.cstring(),o=this.reader.string(1);let a=i.M,c=s==="notice"?new U.NoticeMessage(t,a):new U.DatabaseError(a,t,s);return c.severity=i.S,c.code=i.C,c.detail=i.D,c.hint=i.H,c.position=i.P,c.internalPosition=i.p,c.internalQuery=i.q,c.where=i.W,c.schema=i.s,c.table=i.t,c.column=i.c,c.dataType=i.d,c.constraint=i.n,c.file=i.F,c.line=i.L,c.routine=i.R,c}};Ke.Parser=Zt});var er=f($=>{"use strict";Object.defineProperty($,"__esModule",{value:!0});$.DatabaseError=$.serialize=$.parse=void 0;var ou=Yt();Object.defineProperty($,"DatabaseError",{enumerable:!0,get:function(){return ou.DatabaseError}});var au=es();Object.defineProperty($,"serialize",{enumerable:!0,get:function(){return au.serialize}});var cu=ss();function uu(n,e){let t=new cu.Parser;return n.on("data",r=>t.parse(r,e)),new Promise(r=>n.on("end",()=>r()))}$.parse=uu});var is=f(He=>{"use strict";Object.defineProperty(He,"__esModule",{value:!0});He.CloudflareSocket=void 0;var du=v("events"),tr=class extends du.EventEmitter{constructor(e){super(),this.ssl=e,this.writable=!1,this.destroyed=!1,this._upgrading=!1,this._upgraded=!1,this._cfSocket=null,this._cfWriter=null,this._cfReader=null}setNoDelay(){return this}setKeepAlive(){return this}ref(){return this}unref(){return this}async connect(e,t,r){try{k("connecting"),r&&this.once("connect",r);let s=this.ssl?{secureTransport:"starttls"}:{},o=(await import("cloudflare:sockets")).connect;return this._cfSocket=o(`${t}:${e}`,s),this._cfWriter=this._cfSocket.writable.getWriter(),this._addClosedHandler(),this._cfReader=this._cfSocket.readable.getReader(),this.ssl?this._listenOnce().catch(a=>this.emit("error",a)):this._listen().catch(a=>this.emit("error",a)),await this._cfWriter.ready,k("socket ready"),this.writable=!0,this.emit("connect"),this}catch(s){this.emit("error",s)}}async _listen(){for(;;){k("awaiting receive from CF socket");let{done:e,value:t}=await this._cfReader.read();if(k("CF socket received:",e,t),e){k("done");break}this.emit("data",Buffer.from(t))}}async _listenOnce(){k("awaiting first receive from CF socket");let{done:e,value:t}=await this._cfReader.read();k("First CF socket received:",e,t),this.emit("data",Buffer.from(t))}write(e,t="utf8",r=()=>{}){return e.length===0?r():(typeof e=="string"&&(e=Buffer.from(e,t)),k("sending data direct:",e),this._cfWriter.write(e).then(()=>{k("data sent"),r()},s=>{k("send error",s),r(s)}),!0)}end(e=Buffer.alloc(0),t="utf8",r=()=>{}){return k("ending CF socket"),this.write(e,t,s=>{this._cfSocket.close(),r&&r(s)}),this}destroy(e){return k("destroying CF socket",e),this.destroyed=!0,this.end()}startTls(e){if(this._upgraded){this.emit("error","Cannot call `startTls()` more than once on a socket");return}this._cfWriter.releaseLock(),this._cfReader.releaseLock(),this._upgrading=!0,this._cfSocket=this._cfSocket.startTls(e),this._cfWriter=this._cfSocket.writable.getWriter(),this._cfReader=this._cfSocket.readable.getReader(),this._addClosedHandler(),this._listen().catch(t=>this.emit("error",t))}_addClosedHandler(){this._cfSocket.closed.then(()=>{this._upgrading?(this._upgrading=!1,this._upgraded=!0):(k("CF socket closed"),this._cfSocket=null,this.emit("close"))}).catch(e=>this.emit("error",e))}};He.CloudflareSocket=tr;var lu=!1;function mu(n){if(n instanceof Uint8Array||n instanceof ArrayBuffer){let e=Buffer.from(n).toString("hex");return`
|
|
1
|
+
var v=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var f=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var mt=f(jr=>{"use strict";jr.parse=function(n,e){return new lt(n,e).parse()};var lt=class n{constructor(e,t){this.source=e,this.transform=t||sa,this.position=0,this.entries=[],this.recorded=[],this.dimension=0}isEof(){return this.position>=this.source.length}nextCharacter(){var e=this.source[this.position++];return e==="\\"?{value:this.source[this.position++],escaped:!0}:{value:e,escaped:!1}}record(e){this.recorded.push(e)}newEntry(e){var t;(this.recorded.length>0||e)&&(t=this.recorded.join(""),t==="NULL"&&!e&&(t=null),t!==null&&(t=this.transform(t)),this.entries.push(t),this.recorded=[])}consumeDimensions(){if(this.source[0]==="[")for(;!this.isEof();){var e=this.nextCharacter();if(e.value==="=")break}}parse(e){var t,r,s;for(this.consumeDimensions();!this.isEof();)if(t=this.nextCharacter(),t.value==="{"&&!s)this.dimension++,this.dimension>1&&(r=new n(this.source.substr(this.position-1),this.transform),this.entries.push(r.parse(!0)),this.position+=r.position-2);else if(t.value==="}"&&!s){if(this.dimension--,!this.dimension&&(this.newEntry(),e))return this.entries}else t.value==='"'&&!t.escaped?(s&&this.newEntry(!0),s=!s):t.value===","&&!s?this.newEntry():this.record(t.value);if(this.dimension!==0)throw new Error("array dimension not balanced");return this.entries}};function sa(n){return n}});var Et=f((Ym,zr)=>{var ia=mt();zr.exports={create:function(n,e){return{parse:function(){return ia.parse(n,e)}}}}});var Jr=f((jm,Xr)=>{"use strict";var oa=/(\d{1,})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})(\.\d{1,})?.*?( BC)?$/,aa=/^(\d{1,})-(\d{2})-(\d{2})( BC)?$/,ca=/([Z+-])(\d{2})?:?(\d{2})?:?(\d{2})?/,ua=/^-?infinity$/;Xr.exports=function(e){if(ua.test(e))return Number(e.replace("i","I"));var t=oa.exec(e);if(!t)return da(e)||null;var r=!!t[8],s=parseInt(t[1],10);r&&(s=Qr(s));var i=parseInt(t[2],10)-1,o=t[3],a=parseInt(t[4],10),u=parseInt(t[5],10),c=parseInt(t[6],10),d=t[7];d=d?1e3*parseFloat(d):0;var l,m=la(e);return m!=null?(l=new Date(Date.UTC(s,i,o,a,u,c,d)),pt(s)&&l.setUTCFullYear(s),m!==0&&l.setTime(l.getTime()-m)):(l=new Date(s,i,o,a,u,c,d),pt(s)&&l.setFullYear(s)),l};function da(n){var e=aa.exec(n);if(e){var t=parseInt(e[1],10),r=!!e[4];r&&(t=Qr(t));var s=parseInt(e[2],10)-1,i=e[3],o=new Date(t,s,i);return pt(t)&&o.setFullYear(t),o}}function la(n){if(n.endsWith("+00"))return 0;var e=ca.exec(n.split(" ")[1]);if(e){var t=e[1];if(t==="Z")return 0;var r=t==="-"?-1:1,s=parseInt(e[2],10)*3600+parseInt(e[3]||0,10)*60+parseInt(e[4]||0,10);return s*r*1e3}}function Qr(n){return-(n-1)}function pt(n){return n>=0&&n<100}});var en=f((zm,Zr)=>{Zr.exports=Ea;var ma=Object.prototype.hasOwnProperty;function Ea(n){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var r in t)ma.call(t,r)&&(n[r]=t[r])}return n}});var nn=f((Qm,rn)=>{"use strict";var pa=en();rn.exports=te;function te(n){if(!(this instanceof te))return new te(n);pa(this,Ia(n))}var ha=["seconds","minutes","hours","days","months","years"];te.prototype.toPostgres=function(){var n=ha.filter(this.hasOwnProperty,this);return this.milliseconds&&n.indexOf("seconds")<0&&n.push("seconds"),n.length===0?"0":n.map(function(e){var t=this[e]||0;return e==="seconds"&&this.milliseconds&&(t=(t+this.milliseconds/1e3).toFixed(6).replace(/\.?0+$/,"")),t+" "+e},this).join(" ")};var _a={years:"Y",months:"M",days:"D",hours:"H",minutes:"M",seconds:"S"},Sa=["years","months","days"],ga=["hours","minutes","seconds"];te.prototype.toISOString=te.prototype.toISO=function(){var n=Sa.map(t,this).join(""),e=ga.map(t,this).join("");return"P"+n+"T"+e;function t(r){var s=this[r]||0;return r==="seconds"&&this.milliseconds&&(s=(s+this.milliseconds/1e3).toFixed(6).replace(/0+$/,"")),s+_a[r]}};var ht="([+-]?\\d+)",fa=ht+"\\s+years?",Ta=ht+"\\s+mons?",Aa=ht+"\\s+days?",ya="([+-])?([\\d]*):(\\d\\d):(\\d\\d)\\.?(\\d{1,6})?",Ra=new RegExp([fa,Ta,Aa,ya].map(function(n){return"("+n+")?"}).join("\\s*")),tn={years:2,months:4,days:6,hours:9,minutes:10,seconds:11,milliseconds:12},Ma=["hours","minutes","seconds","milliseconds"];function va(n){var e=n+"000000".slice(n.length);return parseInt(e,10)/1e3}function Ia(n){if(!n)return{};var e=Ra.exec(n),t=e[8]==="-";return Object.keys(tn).reduce(function(r,s){var i=tn[s],o=e[i];return!o||(o=s==="milliseconds"?va(o):parseInt(o,10),!o)||(t&&~Ma.indexOf(s)&&(o*=-1),r[s]=o),r},{})}});var on=f((Xm,sn)=>{"use strict";sn.exports=function(e){if(/^\\x/.test(e))return new Buffer(e.substr(2),"hex");for(var t="",r=0;r<e.length;)if(e[r]!=="\\")t+=e[r],++r;else if(/[0-7]{3}/.test(e.substr(r+1,3)))t+=String.fromCharCode(parseInt(e.substr(r+1,3),8)),r+=4;else{for(var s=1;r+s<e.length&&e[r+s]==="\\";)s++;for(var i=0;i<Math.floor(s/2);++i)t+="\\";r+=Math.floor(s/2)*2}return new Buffer(t,"binary")}});var En=f((Jm,mn)=>{var pe=mt(),he=Et(),xe=Jr(),cn=nn(),un=on();function we(n){return function(t){return t===null?t:n(t)}}function dn(n){return n===null?n:n==="TRUE"||n==="t"||n==="true"||n==="y"||n==="yes"||n==="on"||n==="1"}function Pa(n){return n?pe.parse(n,dn):null}function Ua(n){return parseInt(n,10)}function _t(n){return n?pe.parse(n,we(Ua)):null}function La(n){return n?pe.parse(n,we(function(e){return ln(e).trim()})):null}var Oa=function(n){if(!n)return null;var e=he.create(n,function(t){return t!==null&&(t=Tt(t)),t});return e.parse()},St=function(n){if(!n)return null;var e=he.create(n,function(t){return t!==null&&(t=parseFloat(t)),t});return e.parse()},V=function(n){if(!n)return null;var e=he.create(n);return e.parse()},gt=function(n){if(!n)return null;var e=he.create(n,function(t){return t!==null&&(t=xe(t)),t});return e.parse()},ba=function(n){if(!n)return null;var e=he.create(n,function(t){return t!==null&&(t=cn(t)),t});return e.parse()},Ca=function(n){return n?pe.parse(n,we(un)):null},ft=function(n){return parseInt(n,10)},ln=function(n){var e=String(n);return/^\d+$/.test(e)?e:n},an=function(n){return n?pe.parse(n,we(JSON.parse)):null},Tt=function(n){return n[0]!=="("?null:(n=n.substring(1,n.length-1).split(","),{x:parseFloat(n[0]),y:parseFloat(n[1])})},Na=function(n){if(n[0]!=="<"&&n[1]!=="(")return null;for(var e="(",t="",r=!1,s=2;s<n.length-1;s++){if(r||(e+=n[s]),n[s]===")"){r=!0;continue}else if(!r)continue;n[s]!==","&&(t+=n[s])}var i=Tt(e);return i.radius=parseFloat(t),i},Da=function(n){n(20,ln),n(21,ft),n(23,ft),n(26,ft),n(700,parseFloat),n(701,parseFloat),n(16,dn),n(1082,xe),n(1114,xe),n(1184,xe),n(600,Tt),n(651,V),n(718,Na),n(1e3,Pa),n(1001,Ca),n(1005,_t),n(1007,_t),n(1028,_t),n(1016,La),n(1017,Oa),n(1021,St),n(1022,St),n(1231,St),n(1014,V),n(1015,V),n(1008,V),n(1009,V),n(1040,V),n(1041,V),n(1115,gt),n(1182,gt),n(1185,gt),n(1186,cn),n(1187,ba),n(17,un),n(114,JSON.parse.bind(JSON)),n(3802,JSON.parse.bind(JSON)),n(199,an),n(3807,an),n(3907,V),n(2951,V),n(791,V),n(1183,V),n(1270,V)};mn.exports={init:Da}});var hn=f((Zm,pn)=>{"use strict";var x=1e6;function xa(n){var e=n.readInt32BE(0),t=n.readUInt32BE(4),r="";e<0&&(e=~e+(t===0),t=~t+1>>>0,r="-");var s="",i,o,a,u,c,d;{if(i=e%x,e=e/x>>>0,o=4294967296*i+t,t=o/x>>>0,a=""+(o-x*t),t===0&&e===0)return r+a+s;for(u="",c=6-a.length,d=0;d<c;d++)u+="0";s=u+a+s}{if(i=e%x,e=e/x>>>0,o=4294967296*i+t,t=o/x>>>0,a=""+(o-x*t),t===0&&e===0)return r+a+s;for(u="",c=6-a.length,d=0;d<c;d++)u+="0";s=u+a+s}{if(i=e%x,e=e/x>>>0,o=4294967296*i+t,t=o/x>>>0,a=""+(o-x*t),t===0&&e===0)return r+a+s;for(u="",c=6-a.length,d=0;d<c;d++)u+="0";s=u+a+s}return i=e%x,o=4294967296*i+t,a=""+o%x,r+a+s}pn.exports=xa});var Tn=f((eE,fn)=>{var wa=hn(),I=function(n,e,t,r,s){t=t||0,r=r||!1,s=s||function(E,p,g){return E*Math.pow(2,g)+p};var i=t>>3,o=function(E){return r?~E&255:E},a=255,u=8-t%8;e<u&&(a=255<<8-e&255,u=e),t&&(a=a>>t%8);var c=0;t%8+e>=8&&(c=s(0,o(n[i])&a,u));for(var d=e+t>>3,l=i+1;l<d;l++)c=s(c,o(n[l]),8);var m=(e+t)%8;return m>0&&(c=s(c,o(n[d])>>8-m,m)),c},gn=function(n,e,t){var r=Math.pow(2,t-1)-1,s=I(n,1),i=I(n,t,1);if(i===0)return 0;var o=1,a=function(c,d,l){c===0&&(c=1);for(var m=1;m<=l;m++)o/=2,(d&1<<l-m)>0&&(c+=o);return c},u=I(n,e,t+1,!1,a);return i==Math.pow(2,t+1)-1?u===0?s===0?1/0:-1/0:NaN:(s===0?1:-1)*Math.pow(2,i-r)*u},ka=function(n){return I(n,1)==1?-1*(I(n,15,1,!0)+1):I(n,15,1)},_n=function(n){return I(n,1)==1?-1*(I(n,31,1,!0)+1):I(n,31,1)},Va=function(n){return gn(n,23,8)},Fa=function(n){return gn(n,52,11)},Ga=function(n){var e=I(n,16,32);if(e==49152)return NaN;for(var t=Math.pow(1e4,I(n,16,16)),r=0,s=[],i=I(n,16),o=0;o<i;o++)r+=I(n,16,64+16*o)*t,t/=1e4;var a=Math.pow(10,I(n,16,48));return(e===0?1:-1)*Math.round(r*a)/a},Sn=function(n,e){var t=I(e,1),r=I(e,63,1),s=new Date((t===0?1:-1)*r/1e3+9466848e5);return n||s.setTime(s.getTime()+s.getTimezoneOffset()*6e4),s.usec=r%1e3,s.getMicroSeconds=function(){return this.usec},s.setMicroSeconds=function(i){this.usec=i},s.getUTCMicroSeconds=function(){return this.usec},s},_e=function(n){for(var e=I(n,32),t=I(n,32,32),r=I(n,32,64),s=96,i=[],o=0;o<e;o++)i[o]=I(n,32,s),s+=32,s+=32;var a=function(c){var d=I(n,32,s);if(s+=32,d==4294967295)return null;var l;if(c==23||c==20)return l=I(n,d*8,s),s+=d*8,l;if(c==25)return l=n.toString(this.encoding,s>>3,(s+=d<<3)>>3),l;console.log("ERROR: ElementType not implemented: "+c)},u=function(c,d){var l=[],m;if(c.length>1){var E=c.shift();for(m=0;m<E;m++)l[m]=u(c,d);c.unshift(E)}else for(m=0;m<c[0];m++)l[m]=a(d);return l};return u(i,r)},Ba=function(n){return n.toString("utf8")},Wa=function(n){return n===null?null:I(n,8)>0},qa=function(n){n(20,wa),n(21,ka),n(23,_n),n(26,_n),n(1700,Ga),n(700,Va),n(701,Fa),n(16,Wa),n(1114,Sn.bind(null,!1)),n(1184,Sn.bind(null,!0)),n(1e3,_e),n(1007,_e),n(1016,_e),n(1008,_e),n(1009,_e),n(25,Ba)};fn.exports={init:qa}});var yn=f((tE,An)=>{An.exports={BOOL:16,BYTEA:17,CHAR:18,INT8:20,INT2:21,INT4:23,REGPROC:24,TEXT:25,OID:26,TID:27,XID:28,CID:29,JSON:114,XML:142,PG_NODE_TREE:194,SMGR:210,PATH:602,POLYGON:604,CIDR:650,FLOAT4:700,FLOAT8:701,ABSTIME:702,RELTIME:703,TINTERVAL:704,CIRCLE:718,MACADDR8:774,MONEY:790,MACADDR:829,INET:869,ACLITEM:1033,BPCHAR:1042,VARCHAR:1043,DATE:1082,TIME:1083,TIMESTAMP:1114,TIMESTAMPTZ:1184,INTERVAL:1186,TIMETZ:1266,BIT:1560,VARBIT:1562,NUMERIC:1700,REFCURSOR:1790,REGPROCEDURE:2202,REGOPER:2203,REGOPERATOR:2204,REGCLASS:2205,REGTYPE:2206,UUID:2950,TXID_SNAPSHOT:2970,PG_LSN:3220,PG_NDISTINCT:3361,PG_DEPENDENCIES:3402,TSVECTOR:3614,TSQUERY:3615,GTSVECTOR:3642,REGCONFIG:3734,REGDICTIONARY:3769,JSONB:3802,REGNAMESPACE:4089,REGROLE:4096}});var fe=f(ge=>{var Ka=En(),Ha=Tn(),$a=Et(),Ya=yn();ge.getTypeParser=ja;ge.setTypeParser=za;ge.arrayParser=$a;ge.builtins=Ya;var Se={text:{},binary:{}};function Rn(n){return String(n)}function ja(n,e){return e=e||"text",Se[e]&&Se[e][n]||Rn}function za(n,e,t){typeof e=="function"&&(t=e,e="text"),Se[e][n]=t}Ka.init(function(n,e){Se.text[n]=e});Ha.init(function(n,e){Se.binary[n]=e})});var Te=f((nE,At)=>{"use strict";At.exports={host:"localhost",user:process.platform==="win32"?process.env.USERNAME:process.env.USER,database:void 0,password:null,connectionString:void 0,port:5432,rows:0,binary:!1,max:10,idleTimeoutMillis:3e4,client_encoding:"",ssl:!1,application_name:void 0,fallback_application_name:void 0,options:void 0,parseInputDatesAsUTC:!1,statement_timeout:!1,lock_timeout:!1,idle_in_transaction_session_timeout:!1,query_timeout:!1,connect_timeout:0,keepalives:1,keepalives_idle:0};var re=fe(),Qa=re.getTypeParser(20,"text"),Xa=re.getTypeParser(1016,"text");At.exports.__defineSetter__("parseInt8",function(n){re.setTypeParser(20,"text",n?re.getTypeParser(23,"text"):Qa),re.setTypeParser(1016,"text",n?re.getTypeParser(1007,"text"):Xa)})});var ne=f((sE,vn)=>{"use strict";var Ja=Te();function Za(n){var e=n.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return'"'+e+'"'}function Mn(n){for(var e="{",t=0;t<n.length;t++)if(t>0&&(e=e+","),n[t]===null||typeof n[t]>"u")e=e+"NULL";else if(Array.isArray(n[t]))e=e+Mn(n[t]);else if(ArrayBuffer.isView(n[t])){var r=n[t];if(!(r instanceof Buffer)){var s=Buffer.from(r.buffer,r.byteOffset,r.byteLength);s.length===r.byteLength?r=s:r=s.slice(r.byteOffset,r.byteOffset+r.byteLength)}e+="\\\\x"+r.toString("hex")}else e+=Za(ke(n[t]));return e=e+"}",e}var ke=function(n,e){if(n==null)return null;if(typeof n=="object"){if(n instanceof Buffer)return n;if(ArrayBuffer.isView(n)){var t=Buffer.from(n.buffer,n.byteOffset,n.byteLength);return t.length===n.byteLength?t:t.slice(n.byteOffset,n.byteOffset+n.byteLength)}return n instanceof Date?Ja.parseInputDatesAsUTC?rc(n):tc(n):Array.isArray(n)?Mn(n):ec(n,e)}return n.toString()};function ec(n,e){if(n&&typeof n.toPostgres=="function"){if(e=e||[],e.indexOf(n)!==-1)throw new Error('circular reference detected while preparing "'+n+'" for query');return e.push(n),ke(n.toPostgres(ke),e)}return JSON.stringify(n)}function tc(n){var e=-n.getTimezoneOffset(),t=n.getFullYear(),r=t<1;r&&(t=Math.abs(t)+1);var s=String(t).padStart(4,"0")+"-"+String(n.getMonth()+1).padStart(2,"0")+"-"+String(n.getDate()).padStart(2,"0")+"T"+String(n.getHours()).padStart(2,"0")+":"+String(n.getMinutes()).padStart(2,"0")+":"+String(n.getSeconds()).padStart(2,"0")+"."+String(n.getMilliseconds()).padStart(3,"0");return e<0?(s+="-",e*=-1):s+="+",s+=String(Math.floor(e/60)).padStart(2,"0")+":"+String(e%60).padStart(2,"0"),r&&(s+=" BC"),s}function rc(n){var e=n.getUTCFullYear(),t=e<1;t&&(e=Math.abs(e)+1);var r=String(e).padStart(4,"0")+"-"+String(n.getUTCMonth()+1).padStart(2,"0")+"-"+String(n.getUTCDate()).padStart(2,"0")+"T"+String(n.getUTCHours()).padStart(2,"0")+":"+String(n.getUTCMinutes()).padStart(2,"0")+":"+String(n.getUTCSeconds()).padStart(2,"0")+"."+String(n.getUTCMilliseconds()).padStart(3,"0");return r+="+00:00",t&&(r+=" BC"),r}function nc(n,e,t){return n=typeof n=="string"?{text:n}:n,e&&(typeof e=="function"?n.callback=e:n.values=e),t&&(n.callback=t),n}var sc=function(n){return'"'+n.replace(/"/g,'""')+'"'},ic=function(n){for(var e=!1,t="'",r=0;r<n.length;r++){var s=n[r];s==="'"?t+=s+s:s==="\\"?(t+=s+s,e=!0):t+=s}return t+="'",e===!0&&(t=" E"+t),t};vn.exports={prepareValue:function(e){return ke(e)},normalizeQueryConfig:nc,escapeIdentifier:sc,escapeLiteral:ic}});var Pn=f((iE,In)=>{"use strict";var se=v("crypto");function yt(n){return se.createHash("md5").update(n,"utf-8").digest("hex")}function oc(n,e,t){var r=yt(e+n),s=yt(Buffer.concat([Buffer.from(r),t]));return"md5"+s}function ac(n){return se.createHash("sha256").update(n).digest()}function cc(n,e){return n=n.replace(/(\D)-/,"$1"),se.createHash(n).update(e).digest()}function uc(n,e){return se.createHmac("sha256",n).update(e).digest()}async function dc(n,e,t){return se.pbkdf2Sync(n,e,t,32,"sha256")}In.exports={postgresMd5PasswordHash:oc,randomBytes:se.randomBytes,deriveKey:dc,sha256:ac,hashByName:cc,hmacSha256:uc,md5:yt}});var bn=f((oE,On)=>{var Un=v("crypto");On.exports={postgresMd5PasswordHash:mc,randomBytes:lc,deriveKey:_c,sha256:Ec,hashByName:pc,hmacSha256:hc,md5:Rt};var Ln=Un.webcrypto||globalThis.crypto,z=Ln.subtle,Mt=new TextEncoder;function lc(n){return Ln.getRandomValues(Buffer.alloc(n))}async function Rt(n){try{return Un.createHash("md5").update(n,"utf-8").digest("hex")}catch{let t=typeof n=="string"?Mt.encode(n):n,r=await z.digest("MD5",t);return Array.from(new Uint8Array(r)).map(s=>s.toString(16).padStart(2,"0")).join("")}}async function mc(n,e,t){var r=await Rt(e+n),s=await Rt(Buffer.concat([Buffer.from(r),t]));return"md5"+s}async function Ec(n){return await z.digest("SHA-256",n)}async function pc(n,e){return await z.digest(n,e)}async function hc(n,e){let t=await z.importKey("raw",n,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return await z.sign("HMAC",t,Mt.encode(e))}async function _c(n,e,t){let r=await z.importKey("raw",Mt.encode(n),"PBKDF2",!1,["deriveBits"]),s={name:"PBKDF2",hash:"SHA-256",salt:e,iterations:t};return await z.deriveBits(s,r,32*8,["deriveBits"])}});var It=f((aE,vt)=>{"use strict";var Sc=parseInt(process.versions&&process.versions.node&&process.versions.node.split(".")[0])<15;Sc?vt.exports=Pn():vt.exports=bn()});var Dn=f((cE,Nn)=>{function Q(n,e){return new Error("SASL channel binding: "+n+" when parsing public certificate "+e.toString("base64"))}function Pt(n,e){let t=n[e++];if(t<128)return{length:t,index:e};let r=t&127;if(r>4)throw Q("bad length",n);t=0;for(let s=0;s<r;s++)t=t<<8|n[e++];return{length:t,index:e}}function Cn(n,e){if(n[e++]!==6)throw Q("non-OID data",n);let{length:t,index:r}=Pt(n,e);e=r;let s=e+t,i=n[e++],o=(i/40>>0)+"."+i%40;for(;e<s;){let a=0;for(;e<s;){let u=n[e++];if(a=a<<7|u&127,u<128)break}o+="."+a}return{oid:o,index:e}}function Ae(n,e){if(n[e++]!==48)throw Q("non-sequence data",n);return Pt(n,e)}function gc(n,e){e===void 0&&(e=0),e=Ae(n,e).index;let{length:t,index:r}=Ae(n,e);e=r+t,e=Ae(n,e).index;let{oid:s,index:i}=Cn(n,e);switch(s){case"1.2.840.113549.1.1.4":return"MD5";case"1.2.840.113549.1.1.5":return"SHA-1";case"1.2.840.113549.1.1.11":return"SHA-256";case"1.2.840.113549.1.1.12":return"SHA-384";case"1.2.840.113549.1.1.13":return"SHA-512";case"1.2.840.113549.1.1.14":return"SHA-224";case"1.2.840.113549.1.1.15":return"SHA512-224";case"1.2.840.113549.1.1.16":return"SHA512-256";case"1.2.840.10045.4.1":return"SHA-1";case"1.2.840.10045.4.3.1":return"SHA-224";case"1.2.840.10045.4.3.2":return"SHA-256";case"1.2.840.10045.4.3.3":return"SHA-384";case"1.2.840.10045.4.3.4":return"SHA-512";case"1.2.840.113549.1.1.10":{if(e=i,e=Ae(n,e).index,n[e++]!==160)throw Q("non-tag data",n);e=Pt(n,e).index,e=Ae(n,e).index;let{oid:o}=Cn(n,e);switch(o){case"1.2.840.113549.2.5":return"MD5";case"1.3.14.3.2.26":return"SHA-1";case"2.16.840.1.101.3.4.2.1":return"SHA-256";case"2.16.840.1.101.3.4.2.2":return"SHA-384";case"2.16.840.1.101.3.4.2.3":return"SHA-512"}throw Q("unknown hash OID "+o,n)}case"1.3.101.110":case"1.3.101.112":return"SHA-512";case"1.3.101.111":case"1.3.101.113":throw Q("Ed448 certificate channel binding is not currently supported by Postgres")}throw Q("unknown OID "+s,n)}Nn.exports={signatureAlgorithmHashFromCertificate:gc}});var Vn=f((uE,kn)=>{"use strict";var H=It(),{signatureAlgorithmHashFromCertificate:fc}=Dn();function Tc(n,e){let t=["SCRAM-SHA-256"];e&&t.unshift("SCRAM-SHA-256-PLUS");let r=t.find(o=>n.includes(o));if(!r)throw new Error("SASL: Only mechanism(s) "+t.join(" and ")+" are supported");if(r==="SCRAM-SHA-256-PLUS"&&typeof e.getPeerCertificate!="function")throw new Error("SASL: Mechanism SCRAM-SHA-256-PLUS requires a certificate");let s=H.randomBytes(18).toString("base64");return{mechanism:r,clientNonce:s,response:(r==="SCRAM-SHA-256-PLUS"?"p=tls-server-end-point":e?"y":"n")+",,n=*,r="+s,message:"SASLInitialResponse"}}async function Ac(n,e,t,r){if(n.message!=="SASLInitialResponse")throw new Error("SASL: Last message was not SASLInitialResponse");if(typeof e!="string")throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string");if(e==="")throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a non-empty string");if(typeof t!="string")throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: serverData must be a string");let s=Mc(t);if(s.nonce.startsWith(n.clientNonce)){if(s.nonce.length===n.clientNonce.length)throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce is too short")}else throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce does not start with client nonce");var i="n=*,r="+n.clientNonce,o="r="+s.nonce+",s="+s.salt+",i="+s.iteration;let a=r?"eSws":"biws";if(n.mechanism==="SCRAM-SHA-256-PLUS"){let O=r.getPeerCertificate().raw,M=fc(O);(M==="MD5"||M==="SHA-1")&&(M="SHA-256");let S=await H.hashByName(M,O);a=Buffer.concat([Buffer.from("p=tls-server-end-point,,"),Buffer.from(S)]).toString("base64")}var u="c="+a+",r="+s.nonce,c=i+","+o+","+u,d=Buffer.from(s.salt,"base64"),l=await H.deriveKey(e,d,s.iteration),m=await H.hmacSha256(l,"Client Key"),E=await H.sha256(m),p=await H.hmacSha256(E,c),g=Ic(Buffer.from(m),Buffer.from(p)).toString("base64"),A=await H.hmacSha256(l,"Server Key"),R=await H.hmacSha256(A,c);n.message="SASLResponse",n.serverSignature=Buffer.from(R).toString("base64"),n.response=u+",p="+g}function yc(n,e){if(n.message!=="SASLResponse")throw new Error("SASL: Last message was not SASLResponse");if(typeof e!="string")throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: serverData must be a string");let{serverSignature:t}=vc(e);if(t!==n.serverSignature)throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature does not match")}function Rc(n){if(typeof n!="string")throw new TypeError("SASL: text must be a string");return n.split("").map((e,t)=>n.charCodeAt(t)).every(e=>e>=33&&e<=43||e>=45&&e<=126)}function xn(n){return/^(?:[a-zA-Z0-9+/]{4})*(?:[a-zA-Z0-9+/]{2}==|[a-zA-Z0-9+/]{3}=)?$/.test(n)}function wn(n){if(typeof n!="string")throw new TypeError("SASL: attribute pairs text must be a string");return new Map(n.split(",").map(e=>{if(!/^.=/.test(e))throw new Error("SASL: Invalid attribute pair entry");let t=e[0],r=e.substring(2);return[t,r]}))}function Mc(n){let e=wn(n),t=e.get("r");if(t){if(!Rc(t))throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce must only contain printable characters")}else throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce missing");let r=e.get("s");if(r){if(!xn(r))throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: salt must be base64")}else throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: salt missing");let s=e.get("i");if(s){if(!/^[1-9][0-9]*$/.test(s))throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: invalid iteration count")}else throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: iteration missing");let i=parseInt(s,10);return{nonce:t,salt:r,iteration:i}}function vc(n){let t=wn(n).get("v");if(t){if(!xn(t))throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature must be base64")}else throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature is missing");return{serverSignature:t}}function Ic(n,e){if(!Buffer.isBuffer(n))throw new TypeError("first argument must be a Buffer");if(!Buffer.isBuffer(e))throw new TypeError("second argument must be a Buffer");if(n.length!==e.length)throw new Error("Buffer lengths must match");if(n.length===0)throw new Error("Buffers cannot be empty");return Buffer.from(n.map((t,r)=>n[r]^e[r]))}kn.exports={startSession:Tc,continueSession:Ac,finalizeSession:yc}});var Fe=f((dE,Fn)=>{"use strict";var Pc=fe();function Ve(n){this._types=n||Pc,this.text={},this.binary={}}Ve.prototype.getOverrides=function(n){switch(n){case"text":return this.text;case"binary":return this.binary;default:return{}}};Ve.prototype.setTypeParser=function(n,e,t){typeof e=="function"&&(t=e,e="text"),this.getOverrides(e)[n]=t};Ve.prototype.getTypeParser=function(n,e){return e=e||"text",this.getOverrides(e)[n]||this._types.getTypeParser(n,e)};Fn.exports=Ve});var Wn=f((lE,Bn)=>{"use strict";function ie(n,e={}){if(n.charAt(0)==="/"){let u=n.split(" ");return{host:u[0],database:u[1]}}let t={},r,s=!1;/ |%[^a-f0-9]|%[a-f0-9][^a-f0-9]/i.test(n)&&(n=encodeURI(n).replace(/%25(\d\d)/g,"%$1"));try{r=new URL(n,"postgres://base")}catch{r=new URL(n.replace("@/","@___DUMMY___/"),"postgres://base"),s=!0}for(let u of r.searchParams.entries())t[u[0]]=u[1];if(t.user=t.user||decodeURIComponent(r.username),t.password=t.password||decodeURIComponent(r.password),r.protocol=="socket:")return t.host=decodeURI(r.pathname),t.database=r.searchParams.get("db"),t.client_encoding=r.searchParams.get("encoding"),t;let i=s?"":r.hostname;t.host?i&&/^%2f/i.test(i)&&(r.pathname=i+r.pathname):t.host=decodeURIComponent(i),t.port||(t.port=r.port);let o=r.pathname.slice(1)||null;t.database=o?decodeURI(o):null,(t.ssl==="true"||t.ssl==="1")&&(t.ssl=!0),t.ssl==="0"&&(t.ssl=!1),(t.sslcert||t.sslkey||t.sslrootcert||t.sslmode)&&(t.ssl={});let a=t.sslcert||t.sslkey||t.sslrootcert?v("fs"):null;if(t.sslcert&&(t.ssl.cert=a.readFileSync(t.sslcert).toString()),t.sslkey&&(t.ssl.key=a.readFileSync(t.sslkey).toString()),t.sslrootcert&&(t.ssl.ca=a.readFileSync(t.sslrootcert).toString()),e.useLibpqCompat&&t.uselibpqcompat)throw new Error("Both useLibpqCompat and uselibpqcompat are set. Please use only one of them.");if(t.uselibpqcompat==="true"||e.useLibpqCompat)switch(t.sslmode){case"disable":{t.ssl=!1;break}case"prefer":{t.ssl.rejectUnauthorized=!1;break}case"require":{t.sslrootcert?t.ssl.checkServerIdentity=function(){}:t.ssl.rejectUnauthorized=!1;break}case"verify-ca":{if(!t.ssl.ca)throw new Error("SECURITY WARNING: Using sslmode=verify-ca requires specifying a CA with sslrootcert. If a public CA is used, verify-ca allows connections to a server that somebody else may have registered with the CA, making you vulnerable to Man-in-the-Middle attacks. Either specify a custom CA certificate with sslrootcert parameter or use sslmode=verify-full for proper security.");t.ssl.checkServerIdentity=function(){};break}case"verify-full":break}else switch(t.sslmode){case"disable":{t.ssl=!1;break}case"prefer":case"require":case"verify-ca":case"verify-full":break;case"no-verify":{t.ssl.rejectUnauthorized=!1;break}}return t}function Uc(n){return Object.entries(n).reduce((t,[r,s])=>(s!=null&&(t[r]=s),t),{})}function Gn(n){return Object.entries(n).reduce((t,[r,s])=>{if(r==="ssl"){let i=s;typeof i=="boolean"?t[r]=i:typeof i=="object"&&(t[r]=Uc(i))}else if(s!=null)if(r==="port"){if(s!==""){let i=parseInt(s,10);if(isNaN(i))throw new Error(`Invalid ${r}: ${s}`);t[r]=i}}else t[r]=s;return t},{})}function Lc(n){return Gn(ie(n))}Bn.exports=ie;ie.parse=ie;ie.toClientConfig=Gn;ie.parseIntoClientConfig=Lc});var Lt=f((mE,Hn)=>{"use strict";var Oc=v("dns"),Kn=Te(),qn=Wn().parse,D=function(n,e,t){return t===void 0?t=process.env["PG"+n.toUpperCase()]:t===!1||(t=process.env[t]),e[n]||t||Kn[n]},bc=function(){switch(process.env.PGSSLMODE){case"disable":return!1;case"prefer":case"require":case"verify-ca":case"verify-full":return!0;case"no-verify":return{rejectUnauthorized:!1}}return Kn.ssl},oe=function(n){return"'"+(""+n).replace(/\\/g,"\\\\").replace(/'/g,"\\'")+"'"},F=function(n,e,t){var r=e[t];r!=null&&n.push(t+"="+oe(r))},Ut=class{constructor(e){e=typeof e=="string"?qn(e):e||{},e.connectionString&&(e=Object.assign({},e,qn(e.connectionString))),this.user=D("user",e),this.database=D("database",e),this.database===void 0&&(this.database=this.user),this.port=parseInt(D("port",e),10),this.host=D("host",e),Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:D("password",e)}),this.binary=D("binary",e),this.options=D("options",e),this.ssl=typeof e.ssl>"u"?bc():e.ssl,typeof this.ssl=="string"&&this.ssl==="true"&&(this.ssl=!0),this.ssl==="no-verify"&&(this.ssl={rejectUnauthorized:!1}),this.ssl&&this.ssl.key&&Object.defineProperty(this.ssl,"key",{enumerable:!1}),this.client_encoding=D("client_encoding",e),this.replication=D("replication",e),this.isDomainSocket=!(this.host||"").indexOf("/"),this.application_name=D("application_name",e,"PGAPPNAME"),this.fallback_application_name=D("fallback_application_name",e,!1),this.statement_timeout=D("statement_timeout",e,!1),this.lock_timeout=D("lock_timeout",e,!1),this.idle_in_transaction_session_timeout=D("idle_in_transaction_session_timeout",e,!1),this.query_timeout=D("query_timeout",e,!1),e.connectionTimeoutMillis===void 0?this.connect_timeout=process.env.PGCONNECT_TIMEOUT||0:this.connect_timeout=Math.floor(e.connectionTimeoutMillis/1e3),e.keepAlive===!1?this.keepalives=0:e.keepAlive===!0&&(this.keepalives=1),typeof e.keepAliveInitialDelayMillis=="number"&&(this.keepalives_idle=Math.floor(e.keepAliveInitialDelayMillis/1e3))}getLibpqConnectionString(e){var t=[];F(t,this,"user"),F(t,this,"password"),F(t,this,"port"),F(t,this,"application_name"),F(t,this,"fallback_application_name"),F(t,this,"connect_timeout"),F(t,this,"options");var r=typeof this.ssl=="object"?this.ssl:this.ssl?{sslmode:this.ssl}:{};if(F(t,r,"sslmode"),F(t,r,"sslca"),F(t,r,"sslkey"),F(t,r,"sslcert"),F(t,r,"sslrootcert"),this.database&&t.push("dbname="+oe(this.database)),this.replication&&t.push("replication="+oe(this.replication)),this.host&&t.push("host="+oe(this.host)),this.isDomainSocket)return e(null,t.join(" "));this.client_encoding&&t.push("client_encoding="+oe(this.client_encoding)),Oc.lookup(this.host,function(s,i){return s?e(s,null):(t.push("hostaddr="+oe(i)),e(null,t.join(" ")))})}};Hn.exports=Ut});var bt=f((EE,Yn)=>{"use strict";var Cc=fe(),$n=/^([A-Za-z]+)(?: (\d+))?(?: (\d+))?/,Ot=class{constructor(e,t){this.command=null,this.rowCount=null,this.oid=null,this.rows=[],this.fields=[],this._parsers=void 0,this._types=t,this.RowCtor=null,this.rowAsArray=e==="array",this.rowAsArray&&(this.parseRow=this._parseRowAsArray),this._prebuiltEmptyResultObject=null}addCommandComplete(e){var t;e.text?t=$n.exec(e.text):t=$n.exec(e.command),t&&(this.command=t[1],t[3]?(this.oid=parseInt(t[2],10),this.rowCount=parseInt(t[3],10)):t[2]&&(this.rowCount=parseInt(t[2],10)))}_parseRowAsArray(e){for(var t=new Array(e.length),r=0,s=e.length;r<s;r++){var i=e[r];i!==null?t[r]=this._parsers[r](i):t[r]=null}return t}parseRow(e){for(var t={...this._prebuiltEmptyResultObject},r=0,s=e.length;r<s;r++){var i=e[r],o=this.fields[r].name;i!==null?t[o]=this._parsers[r](i):t[o]=null}return t}addRow(e){this.rows.push(e)}addFields(e){this.fields=e,this.fields.length&&(this._parsers=new Array(e.length));for(var t={},r=0;r<e.length;r++){var s=e[r];t[s.name]=null,this._types?this._parsers[r]=this._types.getTypeParser(s.dataTypeID,s.format||"text"):this._parsers[r]=Cc.getTypeParser(s.dataTypeID,s.format||"text")}this._prebuiltEmptyResultObject={...t}}};Yn.exports=Ot});var Xn=f((pE,Qn)=>{"use strict";var{EventEmitter:Nc}=v("events"),jn=bt(),zn=ne(),Ct=class extends Nc{constructor(e,t,r){super(),e=zn.normalizeQueryConfig(e,t,r),this.text=e.text,this.values=e.values,this.rows=e.rows,this.types=e.types,this.name=e.name,this.queryMode=e.queryMode,this.binary=e.binary,this.portal=e.portal||"",this.callback=e.callback,this._rowMode=e.rowMode,process.domain&&e.callback&&(this.callback=process.domain.bind(e.callback)),this._result=new jn(this._rowMode,this.types),this._results=this._result,this._canceledDueToError=!1}requiresPreparation(){return this.queryMode==="extended"||this.name||this.rows?!0:!this.text||!this.values?!1:this.values.length>0}_checkForMultirow(){this._result.command&&(Array.isArray(this._results)||(this._results=[this._result]),this._result=new jn(this._rowMode,this._result._types),this._results.push(this._result))}handleRowDescription(e){this._checkForMultirow(),this._result.addFields(e.fields),this._accumulateRows=this.callback||!this.listeners("row").length}handleDataRow(e){let t;if(!this._canceledDueToError){try{t=this._result.parseRow(e.fields)}catch(r){this._canceledDueToError=r;return}this.emit("row",t,this._result),this._accumulateRows&&this._result.addRow(t)}}handleCommandComplete(e,t){this._checkForMultirow(),this._result.addCommandComplete(e),this.rows&&t.sync()}handleEmptyQuery(e){this.rows&&e.sync()}handleError(e,t){if(this._canceledDueToError&&(e=this._canceledDueToError,this._canceledDueToError=!1),this.callback)return this.callback(e);this.emit("error",e)}handleReadyForQuery(e){if(this._canceledDueToError)return this.handleError(this._canceledDueToError,e);if(this.callback)try{this.callback(null,this._results)}catch(t){process.nextTick(()=>{throw t})}this.emit("end",this._results)}submit(e){if(typeof this.text!="string"&&typeof this.name!="string")return new Error("A query must have either text or a name. Supplying neither is unsupported.");let t=e.parsedStatements[this.name];if(this.text&&t&&this.text!==t)return new Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`);if(this.values&&!Array.isArray(this.values))return new Error("Query values must be an array");if(this.requiresPreparation()){e.stream.cork&&e.stream.cork();try{this.prepare(e)}finally{e.stream.uncork&&e.stream.uncork()}}else e.query(this.text);return null}hasBeenParsed(e){return this.name&&e.parsedStatements[this.name]}handlePortalSuspended(e){this._getRows(e,this.rows)}_getRows(e,t){e.execute({portal:this.portal,rows:t}),t?e.flush():e.sync()}prepare(e){this.hasBeenParsed(e)||e.parse({text:this.text,name:this.name,types:this.types});try{e.bind({portal:this.portal,statement:this.name,values:this.values,binary:this.binary,valueMapper:zn.prepareValue})}catch(t){this.handleError(t,e);return}e.describe({type:"P",name:this.portal||""}),this._getRows(e,this.rows)}handleCopyInResponse(e){e.sendCopyFail("No source stream defined")}handleCopyData(e,t){}};Qn.exports=Ct});var Yt=f(_=>{"use strict";Object.defineProperty(_,"__esModule",{value:!0});_.NoticeMessage=_.DataRowMessage=_.CommandCompleteMessage=_.ReadyForQueryMessage=_.NotificationResponseMessage=_.BackendKeyDataMessage=_.AuthenticationMD5Password=_.ParameterStatusMessage=_.ParameterDescriptionMessage=_.RowDescriptionMessage=_.Field=_.CopyResponse=_.CopyDataMessage=_.DatabaseError=_.copyDone=_.emptyQuery=_.replicationStart=_.portalSuspended=_.noData=_.closeComplete=_.bindComplete=_.parseComplete=void 0;_.parseComplete={name:"parseComplete",length:5};_.bindComplete={name:"bindComplete",length:5};_.closeComplete={name:"closeComplete",length:5};_.noData={name:"noData",length:5};_.portalSuspended={name:"portalSuspended",length:5};_.replicationStart={name:"replicationStart",length:4};_.emptyQuery={name:"emptyQuery",length:4};_.copyDone={name:"copyDone",length:4};var Nt=class extends Error{constructor(e,t,r){super(e),this.length=t,this.name=r}};_.DatabaseError=Nt;var Dt=class{constructor(e,t){this.length=e,this.chunk=t,this.name="copyData"}};_.CopyDataMessage=Dt;var xt=class{constructor(e,t,r,s){this.length=e,this.name=t,this.binary=r,this.columnTypes=new Array(s)}};_.CopyResponse=xt;var wt=class{constructor(e,t,r,s,i,o,a){this.name=e,this.tableID=t,this.columnID=r,this.dataTypeID=s,this.dataTypeSize=i,this.dataTypeModifier=o,this.format=a}};_.Field=wt;var kt=class{constructor(e,t){this.length=e,this.fieldCount=t,this.name="rowDescription",this.fields=new Array(this.fieldCount)}};_.RowDescriptionMessage=kt;var Vt=class{constructor(e,t){this.length=e,this.parameterCount=t,this.name="parameterDescription",this.dataTypeIDs=new Array(this.parameterCount)}};_.ParameterDescriptionMessage=Vt;var Ft=class{constructor(e,t,r){this.length=e,this.parameterName=t,this.parameterValue=r,this.name="parameterStatus"}};_.ParameterStatusMessage=Ft;var Gt=class{constructor(e,t){this.length=e,this.salt=t,this.name="authenticationMD5Password"}};_.AuthenticationMD5Password=Gt;var Bt=class{constructor(e,t,r){this.length=e,this.processID=t,this.secretKey=r,this.name="backendKeyData"}};_.BackendKeyDataMessage=Bt;var Wt=class{constructor(e,t,r,s){this.length=e,this.processId=t,this.channel=r,this.payload=s,this.name="notification"}};_.NotificationResponseMessage=Wt;var qt=class{constructor(e,t){this.length=e,this.status=t,this.name="readyForQuery"}};_.ReadyForQueryMessage=qt;var Kt=class{constructor(e,t){this.length=e,this.text=t,this.name="commandComplete"}};_.CommandCompleteMessage=Kt;var Ht=class{constructor(e,t){this.length=e,this.fields=t,this.name="dataRow",this.fieldCount=t.length}};_.DataRowMessage=Ht;var $t=class{constructor(e,t){this.length=e,this.message=t,this.name="notice"}};_.NoticeMessage=$t});var Jn=f(Ge=>{"use strict";Object.defineProperty(Ge,"__esModule",{value:!0});Ge.Writer=void 0;var jt=class{constructor(e=256){this.size=e,this.offset=5,this.headerPosition=0,this.buffer=Buffer.allocUnsafe(e)}ensure(e){var t=this.buffer.length-this.offset;if(t<e){var r=this.buffer,s=r.length+(r.length>>1)+e;this.buffer=Buffer.allocUnsafe(s),r.copy(this.buffer)}}addInt32(e){return this.ensure(4),this.buffer[this.offset++]=e>>>24&255,this.buffer[this.offset++]=e>>>16&255,this.buffer[this.offset++]=e>>>8&255,this.buffer[this.offset++]=e>>>0&255,this}addInt16(e){return this.ensure(2),this.buffer[this.offset++]=e>>>8&255,this.buffer[this.offset++]=e>>>0&255,this}addCString(e){if(!e)this.ensure(1);else{var t=Buffer.byteLength(e);this.ensure(t+1),this.buffer.write(e,this.offset,"utf-8"),this.offset+=t}return this.buffer[this.offset++]=0,this}addString(e=""){var t=Buffer.byteLength(e);return this.ensure(t),this.buffer.write(e,this.offset),this.offset+=t,this}add(e){return this.ensure(e.length),e.copy(this.buffer,this.offset),this.offset+=e.length,this}join(e){if(e){this.buffer[this.headerPosition]=e;let t=this.offset-(this.headerPosition+1);this.buffer.writeInt32BE(t,this.headerPosition+1)}return this.buffer.slice(e?0:5,this.offset)}flush(e){var t=this.join(e);return this.offset=5,this.headerPosition=0,this.buffer=Buffer.allocUnsafe(this.size),t}};Ge.Writer=jt});var es=f(We=>{"use strict";Object.defineProperty(We,"__esModule",{value:!0});We.serialize=void 0;var zt=Jn(),P=new zt.Writer,Dc=n=>{P.addInt16(3).addInt16(0);for(let r of Object.keys(n))P.addCString(r).addCString(n[r]);P.addCString("client_encoding").addCString("UTF8");var e=P.addCString("").flush(),t=e.length+4;return new zt.Writer().addInt32(t).add(e).flush()},xc=()=>{let n=Buffer.allocUnsafe(8);return n.writeInt32BE(8,0),n.writeInt32BE(80877103,4),n},wc=n=>P.addCString(n).flush(112),kc=function(n,e){return P.addCString(n).addInt32(Buffer.byteLength(e)).addString(e),P.flush(112)},Vc=function(n){return P.addString(n).flush(112)},Fc=n=>P.addCString(n).flush(81),Zn=[],Gc=n=>{let e=n.name||"";e.length>63&&(console.error("Warning! Postgres only supports 63 characters for query names."),console.error("You supplied %s (%s)",e,e.length),console.error("This can cause conflicts and silent errors executing queries"));let t=n.types||Zn;for(var r=t.length,s=P.addCString(e).addCString(n.text).addInt16(r),i=0;i<r;i++)s.addInt32(t[i]);return P.flush(80)},ae=new zt.Writer,Bc=function(n,e){for(let t=0;t<n.length;t++){let r=e?e(n[t],t):n[t];r==null?(P.addInt16(0),ae.addInt32(-1)):r instanceof Buffer?(P.addInt16(1),ae.addInt32(r.length),ae.add(r)):(P.addInt16(0),ae.addInt32(Buffer.byteLength(r)),ae.addString(r))}},Wc=(n={})=>{let e=n.portal||"",t=n.statement||"",r=n.binary||!1,s=n.values||Zn,i=s.length;return P.addCString(e).addCString(t),P.addInt16(i),Bc(s,n.valueMapper),P.addInt16(i),P.add(ae.flush()),P.addInt16(r?1:0),P.flush(66)},qc=Buffer.from([69,0,0,0,9,0,0,0,0,0]),Kc=n=>{if(!n||!n.portal&&!n.rows)return qc;let e=n.portal||"",t=n.rows||0,r=Buffer.byteLength(e),s=4+r+1+4,i=Buffer.allocUnsafe(1+s);return i[0]=69,i.writeInt32BE(s,1),i.write(e,5,"utf-8"),i[r+5]=0,i.writeUInt32BE(t,i.length-4),i},Hc=(n,e)=>{let t=Buffer.allocUnsafe(16);return t.writeInt32BE(16,0),t.writeInt16BE(1234,4),t.writeInt16BE(5678,6),t.writeInt32BE(n,8),t.writeInt32BE(e,12),t},Qt=(n,e)=>{let r=4+Buffer.byteLength(e)+1,s=Buffer.allocUnsafe(1+r);return s[0]=n,s.writeInt32BE(r,1),s.write(e,5,"utf-8"),s[r]=0,s},$c=P.addCString("P").flush(68),Yc=P.addCString("S").flush(68),jc=n=>n.name?Qt(68,`${n.type}${n.name||""}`):n.type==="P"?$c:Yc,zc=n=>{let e=`${n.type}${n.name||""}`;return Qt(67,e)},Qc=n=>P.add(n).flush(100),Xc=n=>Qt(102,n),Be=n=>Buffer.from([n,0,0,0,4]),Jc=Be(72),Zc=Be(83),eu=Be(88),tu=Be(99),ru={startup:Dc,password:wc,requestSsl:xc,sendSASLInitialResponseMessage:kc,sendSCRAMClientFinalMessage:Vc,query:Fc,parse:Gc,bind:Wc,execute:Kc,describe:jc,close:zc,flush:()=>Jc,sync:()=>Zc,end:()=>eu,copyData:Qc,copyDone:()=>tu,copyFail:Xc,cancel:Hc};We.serialize=ru});var ts=f(qe=>{"use strict";Object.defineProperty(qe,"__esModule",{value:!0});qe.BufferReader=void 0;var nu=Buffer.allocUnsafe(0),Xt=class{constructor(e=0){this.offset=e,this.buffer=nu,this.encoding="utf-8"}setBuffer(e,t){this.offset=e,this.buffer=t}int16(){let e=this.buffer.readInt16BE(this.offset);return this.offset+=2,e}byte(){let e=this.buffer[this.offset];return this.offset++,e}int32(){let e=this.buffer.readInt32BE(this.offset);return this.offset+=4,e}uint32(){let e=this.buffer.readUInt32BE(this.offset);return this.offset+=4,e}string(e){let t=this.buffer.toString(this.encoding,this.offset,this.offset+e);return this.offset+=e,t}cstring(){let e=this.offset,t=e;for(;this.buffer[t++]!==0;);return this.offset=t,this.buffer.toString(this.encoding,e,t-1)}bytes(e){let t=this.buffer.slice(this.offset,this.offset+e);return this.offset+=e,t}};qe.BufferReader=Xt});var ss=f(Ke=>{"use strict";Object.defineProperty(Ke,"__esModule",{value:!0});Ke.Parser=void 0;var U=Yt(),su=ts(),Jt=1,iu=4,rs=Jt+iu,ns=Buffer.allocUnsafe(0),Zt=class{constructor(e){if(this.buffer=ns,this.bufferLength=0,this.bufferOffset=0,this.reader=new su.BufferReader,e?.mode==="binary")throw new Error("Binary mode not supported yet");this.mode=e?.mode||"text"}parse(e,t){this.mergeBuffer(e);let r=this.bufferOffset+this.bufferLength,s=this.bufferOffset;for(;s+rs<=r;){let i=this.buffer[s],o=this.buffer.readUInt32BE(s+Jt),a=Jt+o;if(a+s<=r){let u=this.handlePacket(s+rs,i,o,this.buffer);t(u),s+=a}else break}s===r?(this.buffer=ns,this.bufferLength=0,this.bufferOffset=0):(this.bufferLength=r-s,this.bufferOffset=s)}mergeBuffer(e){if(this.bufferLength>0){let t=this.bufferLength+e.byteLength;if(t+this.bufferOffset>this.buffer.byteLength){let s;if(t<=this.buffer.byteLength&&this.bufferOffset>=this.bufferLength)s=this.buffer;else{let i=this.buffer.byteLength*2;for(;t>=i;)i*=2;s=Buffer.allocUnsafe(i)}this.buffer.copy(s,0,this.bufferOffset,this.bufferOffset+this.bufferLength),this.buffer=s,this.bufferOffset=0}e.copy(this.buffer,this.bufferOffset+this.bufferLength),this.bufferLength=t}else this.buffer=e,this.bufferOffset=0,this.bufferLength=e.byteLength}handlePacket(e,t,r,s){switch(t){case 50:return U.bindComplete;case 49:return U.parseComplete;case 51:return U.closeComplete;case 110:return U.noData;case 115:return U.portalSuspended;case 99:return U.copyDone;case 87:return U.replicationStart;case 73:return U.emptyQuery;case 68:return this.parseDataRowMessage(e,r,s);case 67:return this.parseCommandCompleteMessage(e,r,s);case 90:return this.parseReadyForQueryMessage(e,r,s);case 65:return this.parseNotificationMessage(e,r,s);case 82:return this.parseAuthenticationResponse(e,r,s);case 83:return this.parseParameterStatusMessage(e,r,s);case 75:return this.parseBackendKeyData(e,r,s);case 69:return this.parseErrorMessage(e,r,s,"error");case 78:return this.parseErrorMessage(e,r,s,"notice");case 84:return this.parseRowDescriptionMessage(e,r,s);case 116:return this.parseParameterDescriptionMessage(e,r,s);case 71:return this.parseCopyInMessage(e,r,s);case 72:return this.parseCopyOutMessage(e,r,s);case 100:return this.parseCopyData(e,r,s);default:return new U.DatabaseError("received invalid response: "+t.toString(16),r,"error")}}parseReadyForQueryMessage(e,t,r){this.reader.setBuffer(e,r);let s=this.reader.string(1);return new U.ReadyForQueryMessage(t,s)}parseCommandCompleteMessage(e,t,r){this.reader.setBuffer(e,r);let s=this.reader.cstring();return new U.CommandCompleteMessage(t,s)}parseCopyData(e,t,r){let s=r.slice(e,e+(t-4));return new U.CopyDataMessage(t,s)}parseCopyInMessage(e,t,r){return this.parseCopyMessage(e,t,r,"copyInResponse")}parseCopyOutMessage(e,t,r){return this.parseCopyMessage(e,t,r,"copyOutResponse")}parseCopyMessage(e,t,r,s){this.reader.setBuffer(e,r);let i=this.reader.byte()!==0,o=this.reader.int16(),a=new U.CopyResponse(t,s,i,o);for(let u=0;u<o;u++)a.columnTypes[u]=this.reader.int16();return a}parseNotificationMessage(e,t,r){this.reader.setBuffer(e,r);let s=this.reader.int32(),i=this.reader.cstring(),o=this.reader.cstring();return new U.NotificationResponseMessage(t,s,i,o)}parseRowDescriptionMessage(e,t,r){this.reader.setBuffer(e,r);let s=this.reader.int16(),i=new U.RowDescriptionMessage(t,s);for(let o=0;o<s;o++)i.fields[o]=this.parseField();return i}parseField(){let e=this.reader.cstring(),t=this.reader.uint32(),r=this.reader.int16(),s=this.reader.uint32(),i=this.reader.int16(),o=this.reader.int32(),a=this.reader.int16()===0?"text":"binary";return new U.Field(e,t,r,s,i,o,a)}parseParameterDescriptionMessage(e,t,r){this.reader.setBuffer(e,r);let s=this.reader.int16(),i=new U.ParameterDescriptionMessage(t,s);for(let o=0;o<s;o++)i.dataTypeIDs[o]=this.reader.int32();return i}parseDataRowMessage(e,t,r){this.reader.setBuffer(e,r);let s=this.reader.int16(),i=new Array(s);for(let o=0;o<s;o++){let a=this.reader.int32();i[o]=a===-1?null:this.reader.string(a)}return new U.DataRowMessage(t,i)}parseParameterStatusMessage(e,t,r){this.reader.setBuffer(e,r);let s=this.reader.cstring(),i=this.reader.cstring();return new U.ParameterStatusMessage(t,s,i)}parseBackendKeyData(e,t,r){this.reader.setBuffer(e,r);let s=this.reader.int32(),i=this.reader.int32();return new U.BackendKeyDataMessage(t,s,i)}parseAuthenticationResponse(e,t,r){this.reader.setBuffer(e,r);let s=this.reader.int32(),i={name:"authenticationOk",length:t};switch(s){case 0:break;case 3:i.length===8&&(i.name="authenticationCleartextPassword");break;case 5:if(i.length===12){i.name="authenticationMD5Password";let o=this.reader.bytes(4);return new U.AuthenticationMD5Password(t,o)}break;case 10:{i.name="authenticationSASL",i.mechanisms=[];let o;do o=this.reader.cstring(),o&&i.mechanisms.push(o);while(o)}break;case 11:i.name="authenticationSASLContinue",i.data=this.reader.string(t-8);break;case 12:i.name="authenticationSASLFinal",i.data=this.reader.string(t-8);break;default:throw new Error("Unknown authenticationOk message type "+s)}return i}parseErrorMessage(e,t,r,s){this.reader.setBuffer(e,r);let i={},o=this.reader.string(1);for(;o!=="\0";)i[o]=this.reader.cstring(),o=this.reader.string(1);let a=i.M,u=s==="notice"?new U.NoticeMessage(t,a):new U.DatabaseError(a,t,s);return u.severity=i.S,u.code=i.C,u.detail=i.D,u.hint=i.H,u.position=i.P,u.internalPosition=i.p,u.internalQuery=i.q,u.where=i.W,u.schema=i.s,u.table=i.t,u.column=i.c,u.dataType=i.d,u.constraint=i.n,u.file=i.F,u.line=i.L,u.routine=i.R,u}};Ke.Parser=Zt});var er=f($=>{"use strict";Object.defineProperty($,"__esModule",{value:!0});$.DatabaseError=$.serialize=$.parse=void 0;var ou=Yt();Object.defineProperty($,"DatabaseError",{enumerable:!0,get:function(){return ou.DatabaseError}});var au=es();Object.defineProperty($,"serialize",{enumerable:!0,get:function(){return au.serialize}});var cu=ss();function uu(n,e){let t=new cu.Parser;return n.on("data",r=>t.parse(r,e)),new Promise(r=>n.on("end",()=>r()))}$.parse=uu});var is=f(He=>{"use strict";Object.defineProperty(He,"__esModule",{value:!0});He.CloudflareSocket=void 0;var du=v("events"),tr=class extends du.EventEmitter{constructor(e){super(),this.ssl=e,this.writable=!1,this.destroyed=!1,this._upgrading=!1,this._upgraded=!1,this._cfSocket=null,this._cfWriter=null,this._cfReader=null}setNoDelay(){return this}setKeepAlive(){return this}ref(){return this}unref(){return this}async connect(e,t,r){try{k("connecting"),r&&this.once("connect",r);let s=this.ssl?{secureTransport:"starttls"}:{},o=(await import("cloudflare:sockets")).connect;return this._cfSocket=o(`${t}:${e}`,s),this._cfWriter=this._cfSocket.writable.getWriter(),this._addClosedHandler(),this._cfReader=this._cfSocket.readable.getReader(),this.ssl?this._listenOnce().catch(a=>this.emit("error",a)):this._listen().catch(a=>this.emit("error",a)),await this._cfWriter.ready,k("socket ready"),this.writable=!0,this.emit("connect"),this}catch(s){this.emit("error",s)}}async _listen(){for(;;){k("awaiting receive from CF socket");let{done:e,value:t}=await this._cfReader.read();if(k("CF socket received:",e,t),e){k("done");break}this.emit("data",Buffer.from(t))}}async _listenOnce(){k("awaiting first receive from CF socket");let{done:e,value:t}=await this._cfReader.read();k("First CF socket received:",e,t),this.emit("data",Buffer.from(t))}write(e,t="utf8",r=()=>{}){return e.length===0?r():(typeof e=="string"&&(e=Buffer.from(e,t)),k("sending data direct:",e),this._cfWriter.write(e).then(()=>{k("data sent"),r()},s=>{k("send error",s),r(s)}),!0)}end(e=Buffer.alloc(0),t="utf8",r=()=>{}){return k("ending CF socket"),this.write(e,t,s=>{this._cfSocket.close(),r&&r(s)}),this}destroy(e){return k("destroying CF socket",e),this.destroyed=!0,this.end()}startTls(e){if(this._upgraded){this.emit("error","Cannot call `startTls()` more than once on a socket");return}this._cfWriter.releaseLock(),this._cfReader.releaseLock(),this._upgrading=!0,this._cfSocket=this._cfSocket.startTls(e),this._cfWriter=this._cfSocket.writable.getWriter(),this._cfReader=this._cfSocket.readable.getReader(),this._addClosedHandler(),this._listen().catch(t=>this.emit("error",t))}_addClosedHandler(){this._cfSocket.closed.then(()=>{this._upgrading?(this._upgrading=!1,this._upgraded=!0):(k("CF socket closed"),this._cfSocket=null,this.emit("close"))}).catch(e=>this.emit("error",e))}};He.CloudflareSocket=tr;var lu=!1;function mu(n){if(n instanceof Uint8Array||n instanceof ArrayBuffer){let e=Buffer.from(n).toString("hex");return`
|
|
2
2
|
>>> STR: "${new TextDecoder().decode(n).replace(/\n/g,"\\n")}"
|
|
3
3
|
>>> HEX: ${e}
|
|
4
|
-
`}else return n}function k(...n){lu&&console.log(...n.map(mu))}});var as=f((
|
|
5
|
-
`);ye.write(ps.format.apply(ps,e))}}Object.defineProperty(W.exports,"isWin",{get:function(){return Ye},set:function(n){Ye=n}});W.exports.warnTo=function(n){var e=ye;return ye=n,e};W.exports.getFileName=function(n){var e=n||process.env,t=e.PGPASSFILE||(Ye?Es.join(e.APPDATA||"./","postgresql","pgpass.conf"):Es.join(e.HOME||"./",".pgpass"));return t};W.exports.usePgPass=function(n,e){return Object.prototype.hasOwnProperty.call(process.env,"PGPASSWORD")?!1:Ye?!0:(e=e||"<unkn>",Vu(n.mode)?n.mode&(Du|xu)?(ir('WARNING: password file "%s" has group or world access; permissions should be u=rw (0600) or less',e),!1):!0:(ir('WARNING: password file "%s" is not a plain file',e),!1))};var Gu=W.exports.match=function(n,e){return ce.slice(0,-1).reduce(function(t,r,s){return s==1&&Number(n[r]||Nu)===Number(e[r])?t&&!0:t&&(e[r]==="*"||e[r]===n[r])},!0)};W.exports.getPassword=function(n,e,t){var r,s=e.pipe(Cu());function i(c){var u=Bu(c);u&&Wu(u)&&Gu(n,u)&&(r=u[Fu],s.end())}var o=function(){e.destroy(),t(r)},a=function(c){e.destroy(),ir("WARNING: error on reading file: %s",c),t(void 0)};e.on("error",a),s.on("data",i).on("end",o).on("error",a)};var Bu=W.exports.parseLine=function(n){if(n.length<11||n.match(/^\s+#/))return null;for(var e="",t="",r=0,s=0,i=0,o={},a=!1,c=function(d,l,m){var E=n.substring(l,m);Object.hasOwnProperty.call(process.env,"PGPASS_NO_DEESCAPE")||(E=E.replace(/\\([:\\])/g,"$1")),o[ce[d]]=E},u=0;u<n.length-1;u+=1){if(e=n.charAt(u+1),t=n.charAt(u),a=r==sr-1,a){c(r,s);break}u>=0&&e==":"&&t!=="\\"&&(c(r,s,u+1),s=u+2,r+=1)}return o=Object.keys(o).length===sr?o:null,o},Wu=W.exports.isValidEntry=function(n){for(var e={0:function(o){return o.length>0},1:function(o){return o==="*"?!0:(o=Number(o),isFinite(o)&&o>0&&o<9007199254740992&&Math.floor(o)===o)},2:function(o){return o.length>0},3:function(o){return o.length>0},4:function(o){return o.length>0}},t=0;t<ce.length;t+=1){var r=e[t],s=n[ce[t]]||"",i=r(s);if(!i)return!1}return!0}});var Ss=f((UE,or)=>{"use strict";var PE=v("path"),_s=v("fs"),je=hs();or.exports=function(n,e){var t=je.getFileName();_s.stat(t,function(r,s){if(r||!je.usePgPass(s,t))return e(void 0);var i=_s.createReadStream(t);je.getPassword(n,i,e)})};or.exports.warnTo=je.warnTo});var As=f((LE,Ts)=>{"use strict";var qu=v("events").EventEmitter,gs=ne(),ar=Vn(),Ku=Fe(),Hu=Lt(),fs=Xn(),$u=Te(),Yu=nr(),ju=It(),Qe=class extends qu{constructor(e){super(),this.connectionParameters=new Hu(e),this.user=this.connectionParameters.user,this.database=this.connectionParameters.database,this.port=this.connectionParameters.port,this.host=this.connectionParameters.host,Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:this.connectionParameters.password}),this.replication=this.connectionParameters.replication;var t=e||{};this._Promise=t.Promise||global.Promise,this._types=new Ku(t.types),this._ending=!1,this._ended=!1,this._connecting=!1,this._connected=!1,this._connectionError=!1,this._queryable=!0,this.enableChannelBinding=!!t.enableChannelBinding,this.connection=t.connection||new Yu({stream:t.stream,ssl:this.connectionParameters.ssl,keepAlive:t.keepAlive||!1,keepAliveInitialDelayMillis:t.keepAliveInitialDelayMillis||0,encoding:this.connectionParameters.client_encoding||"utf8"}),this.queryQueue=[],this.binary=t.binary||$u.binary,this.processID=null,this.secretKey=null,this.ssl=this.connectionParameters.ssl||!1,this.ssl&&this.ssl.key&&Object.defineProperty(this.ssl,"key",{enumerable:!1}),this._connectionTimeoutMillis=t.connectionTimeoutMillis||0}_errorAllQueries(e){let t=r=>{process.nextTick(()=>{r.handleError(e,this.connection)})};this.activeQuery&&(t(this.activeQuery),this.activeQuery=null),this.queryQueue.forEach(t),this.queryQueue.length=0}_connect(e){var t=this,r=this.connection;if(this._connectionCallback=e,this._connecting||this._connected){let s=new Error("Client has already been connected. You cannot reuse a client.");process.nextTick(()=>{e(s)});return}this._connecting=!0,this._connectionTimeoutMillis>0&&(this.connectionTimeoutHandle=setTimeout(()=>{r._ending=!0,r.stream.destroy(new Error("timeout expired"))},this._connectionTimeoutMillis),this.connectionTimeoutHandle.unref&&this.connectionTimeoutHandle.unref()),this.host&&this.host.indexOf("/")===0?r.connect(this.host+"/.s.PGSQL."+this.port):r.connect(this.port,this.host),r.on("connect",function(){t.ssl?r.requestSsl():r.startup(t.getStartupConf())}),r.on("sslconnect",function(){r.startup(t.getStartupConf())}),this._attachListeners(r),r.once("end",()=>{let s=this._ending?new Error("Connection terminated"):new Error("Connection terminated unexpectedly");clearTimeout(this.connectionTimeoutHandle),this._errorAllQueries(s),this._ended=!0,this._ending||(this._connecting&&!this._connectionError?this._connectionCallback?this._connectionCallback(s):this._handleErrorEvent(s):this._connectionError||this._handleErrorEvent(s)),process.nextTick(()=>{this.emit("end")})})}connect(e){if(e){this._connect(e);return}return new this._Promise((t,r)=>{this._connect(s=>{s?r(s):t()})})}_attachListeners(e){e.on("authenticationCleartextPassword",this._handleAuthCleartextPassword.bind(this)),e.on("authenticationMD5Password",this._handleAuthMD5Password.bind(this)),e.on("authenticationSASL",this._handleAuthSASL.bind(this)),e.on("authenticationSASLContinue",this._handleAuthSASLContinue.bind(this)),e.on("authenticationSASLFinal",this._handleAuthSASLFinal.bind(this)),e.on("backendKeyData",this._handleBackendKeyData.bind(this)),e.on("error",this._handleErrorEvent.bind(this)),e.on("errorMessage",this._handleErrorMessage.bind(this)),e.on("readyForQuery",this._handleReadyForQuery.bind(this)),e.on("notice",this._handleNotice.bind(this)),e.on("rowDescription",this._handleRowDescription.bind(this)),e.on("dataRow",this._handleDataRow.bind(this)),e.on("portalSuspended",this._handlePortalSuspended.bind(this)),e.on("emptyQuery",this._handleEmptyQuery.bind(this)),e.on("commandComplete",this._handleCommandComplete.bind(this)),e.on("parseComplete",this._handleParseComplete.bind(this)),e.on("copyInResponse",this._handleCopyInResponse.bind(this)),e.on("copyData",this._handleCopyData.bind(this)),e.on("notification",this._handleNotification.bind(this))}_checkPgPass(e){let t=this.connection;if(typeof this.password=="function")this._Promise.resolve().then(()=>this.password()).then(r=>{if(r!==void 0){if(typeof r!="string"){t.emit("error",new TypeError("Password must be a string"));return}this.connectionParameters.password=this.password=r}else this.connectionParameters.password=this.password=null;e()}).catch(r=>{t.emit("error",r)});else if(this.password!==null)e();else try{Ss()(this.connectionParameters,s=>{s!==void 0&&(this.connectionParameters.password=this.password=s),e()})}catch(r){this.emit("error",r)}}_handleAuthCleartextPassword(e){this._checkPgPass(()=>{this.connection.password(this.password)})}_handleAuthMD5Password(e){this._checkPgPass(async()=>{try{let t=await ju.postgresMd5PasswordHash(this.user,this.password,e.salt);this.connection.password(t)}catch(t){this.emit("error",t)}})}_handleAuthSASL(e){this._checkPgPass(()=>{try{this.saslSession=ar.startSession(e.mechanisms,this.enableChannelBinding&&this.connection.stream),this.connection.sendSASLInitialResponseMessage(this.saslSession.mechanism,this.saslSession.response)}catch(t){this.connection.emit("error",t)}})}async _handleAuthSASLContinue(e){try{await ar.continueSession(this.saslSession,this.password,e.data,this.enableChannelBinding&&this.connection.stream),this.connection.sendSCRAMClientFinalMessage(this.saslSession.response)}catch(t){this.connection.emit("error",t)}}_handleAuthSASLFinal(e){try{ar.finalizeSession(this.saslSession,e.data),this.saslSession=null}catch(t){this.connection.emit("error",t)}}_handleBackendKeyData(e){this.processID=e.processID,this.secretKey=e.secretKey}_handleReadyForQuery(e){this._connecting&&(this._connecting=!1,this._connected=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback&&(this._connectionCallback(null,this),this._connectionCallback=null),this.emit("connect"));let{activeQuery:t}=this;this.activeQuery=null,this.readyForQuery=!0,t&&t.handleReadyForQuery(this.connection),this._pulseQueryQueue()}_handleErrorWhileConnecting(e){if(!this._connectionError){if(this._connectionError=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback)return this._connectionCallback(e);this.emit("error",e)}}_handleErrorEvent(e){if(this._connecting)return this._handleErrorWhileConnecting(e);this._queryable=!1,this._errorAllQueries(e),this.emit("error",e)}_handleErrorMessage(e){if(this._connecting)return this._handleErrorWhileConnecting(e);let t=this.activeQuery;if(!t){this._handleErrorEvent(e);return}this.activeQuery=null,t.handleError(e,this.connection)}_handleRowDescription(e){this.activeQuery.handleRowDescription(e)}_handleDataRow(e){this.activeQuery.handleDataRow(e)}_handlePortalSuspended(e){this.activeQuery.handlePortalSuspended(this.connection)}_handleEmptyQuery(e){this.activeQuery.handleEmptyQuery(this.connection)}_handleCommandComplete(e){if(this.activeQuery==null){let t=new Error("Received unexpected commandComplete message from backend.");this._handleErrorEvent(t);return}this.activeQuery.handleCommandComplete(e,this.connection)}_handleParseComplete(){if(this.activeQuery==null){let e=new Error("Received unexpected parseComplete message from backend.");this._handleErrorEvent(e);return}this.activeQuery.name&&(this.connection.parsedStatements[this.activeQuery.name]=this.activeQuery.text)}_handleCopyInResponse(e){this.activeQuery.handleCopyInResponse(this.connection)}_handleCopyData(e){this.activeQuery.handleCopyData(e,this.connection)}_handleNotification(e){this.emit("notification",e)}_handleNotice(e){this.emit("notice",e)}getStartupConf(){var e=this.connectionParameters,t={user:e.user,database:e.database},r=e.application_name||e.fallback_application_name;return r&&(t.application_name=r),e.replication&&(t.replication=""+e.replication),e.statement_timeout&&(t.statement_timeout=String(parseInt(e.statement_timeout,10))),e.lock_timeout&&(t.lock_timeout=String(parseInt(e.lock_timeout,10))),e.idle_in_transaction_session_timeout&&(t.idle_in_transaction_session_timeout=String(parseInt(e.idle_in_transaction_session_timeout,10))),e.options&&(t.options=e.options),t}cancel(e,t){if(e.activeQuery===t){var r=this.connection;this.host&&this.host.indexOf("/")===0?r.connect(this.host+"/.s.PGSQL."+this.port):r.connect(this.port,this.host),r.on("connect",function(){r.cancel(e.processID,e.secretKey)})}else e.queryQueue.indexOf(t)!==-1&&e.queryQueue.splice(e.queryQueue.indexOf(t),1)}setTypeParser(e,t,r){return this._types.setTypeParser(e,t,r)}getTypeParser(e,t){return this._types.getTypeParser(e,t)}escapeIdentifier(e){return gs.escapeIdentifier(e)}escapeLiteral(e){return gs.escapeLiteral(e)}_pulseQueryQueue(){if(this.readyForQuery===!0)if(this.activeQuery=this.queryQueue.shift(),this.activeQuery){this.readyForQuery=!1,this.hasExecuted=!0;let e=this.activeQuery.submit(this.connection);e&&process.nextTick(()=>{this.activeQuery.handleError(e,this.connection),this.readyForQuery=!0,this._pulseQueryQueue()})}else this.hasExecuted&&(this.activeQuery=null,this.emit("drain"))}query(e,t,r){var s,i,o,a,c;if(e==null)throw new TypeError("Client was passed a null or undefined query");return typeof e.submit=="function"?(o=e.query_timeout||this.connectionParameters.query_timeout,i=s=e,typeof t=="function"&&(s.callback=s.callback||t)):(o=e.query_timeout||this.connectionParameters.query_timeout,s=new fs(e,t,r),s.callback||(i=new this._Promise((u,d)=>{s.callback=(l,m)=>l?d(l):u(m)}).catch(u=>{throw Error.captureStackTrace(u),u}))),o&&(c=s.callback,a=setTimeout(()=>{var u=new Error("Query read timeout");process.nextTick(()=>{s.handleError(u,this.connection)}),c(u),s.callback=()=>{};var d=this.queryQueue.indexOf(s);d>-1&&this.queryQueue.splice(d,1),this._pulseQueryQueue()},o),s.callback=(u,d)=>{clearTimeout(a),c(u,d)}),this.binary&&!s.binary&&(s.binary=!0),s._result&&!s._result._types&&(s._result._types=this._types),this._queryable?this._ending?(process.nextTick(()=>{s.handleError(new Error("Client was closed and is not queryable"),this.connection)}),i):(this.queryQueue.push(s),this._pulseQueryQueue(),i):(process.nextTick(()=>{s.handleError(new Error("Client has encountered a connection error and is not queryable"),this.connection)}),i)}ref(){this.connection.ref()}unref(){this.connection.unref()}end(e){if(this._ending=!0,!this.connection._connecting||this._ended)if(e)e();else return this._Promise.resolve();if(this.activeQuery||!this._queryable?this.connection.stream.destroy():this.connection.end(),e)this.connection.once("end",e);else return new this._Promise(t=>{this.connection.once("end",t)})}};Qe.Query=fs;Ts.exports=Qe});var vs=f((OE,Ms)=>{"use strict";var Qu=v("events").EventEmitter,ys=function(){},Rs=(n,e)=>{let t=n.findIndex(e);return t===-1?void 0:n.splice(t,1)[0]},cr=class{constructor(e,t,r){this.client=e,this.idleListener=t,this.timeoutId=r}},ue=class{constructor(e){this.callback=e}};function zu(){throw new Error("Release called on client which has already been released to the pool.")}function ze(n,e){if(e)return{callback:e,result:void 0};let t,r,s=function(o,a){o?t(o):r(a)},i=new n(function(o,a){r=o,t=a}).catch(o=>{throw Error.captureStackTrace(o),o});return{callback:s,result:i}}function Xu(n,e){return function t(r){r.client=e,e.removeListener("error",t),e.on("error",()=>{n.log("additional client error after disconnection due to error",r)}),n._remove(e),n.emit("error",r,e)}}var ur=class extends Qu{constructor(e,t){super(),this.options=Object.assign({},e),e!=null&&"password"in e&&Object.defineProperty(this.options,"password",{configurable:!0,enumerable:!1,writable:!0,value:e.password}),e!=null&&e.ssl&&e.ssl.key&&Object.defineProperty(this.options.ssl,"key",{enumerable:!1}),this.options.max=this.options.max||this.options.poolSize||10,this.options.maxUses=this.options.maxUses||1/0,this.options.allowExitOnIdle=this.options.allowExitOnIdle||!1,this.options.maxLifetimeSeconds=this.options.maxLifetimeSeconds||0,this.log=this.options.log||function(){},this.Client=this.options.Client||t||dr().Client,this.Promise=this.options.Promise||global.Promise,typeof this.options.idleTimeoutMillis>"u"&&(this.options.idleTimeoutMillis=1e4),this._clients=[],this._idle=[],this._expired=new WeakSet,this._pendingQueue=[],this._endCallback=void 0,this.ending=!1,this.ended=!1}_isFull(){return this._clients.length>=this.options.max}_pulseQueue(){if(this.log("pulse queue"),this.ended){this.log("pulse queue ended");return}if(this.ending){this.log("pulse queue on ending"),this._idle.length&&this._idle.slice().map(t=>{this._remove(t.client)}),this._clients.length||(this.ended=!0,this._endCallback());return}if(!this._pendingQueue.length){this.log("no queued requests");return}if(!this._idle.length&&this._isFull())return;let e=this._pendingQueue.shift();if(this._idle.length){let t=this._idle.pop();clearTimeout(t.timeoutId);let r=t.client;r.ref&&r.ref();let s=t.idleListener;return this._acquireClient(r,e,s,!1)}if(!this._isFull())return this.newClient(e);throw new Error("unexpected condition")}_remove(e){let t=Rs(this._idle,r=>r.client===e);t!==void 0&&clearTimeout(t.timeoutId),this._clients=this._clients.filter(r=>r!==e),e.end(),this.emit("remove",e)}connect(e){if(this.ending){let s=new Error("Cannot use a pool after calling end on the pool");return e?e(s):this.Promise.reject(s)}let t=ze(this.Promise,e),r=t.result;if(this._isFull()||this._idle.length){if(this._idle.length&&process.nextTick(()=>this._pulseQueue()),!this.options.connectionTimeoutMillis)return this._pendingQueue.push(new ue(t.callback)),r;let s=(a,c,u)=>{clearTimeout(o),t.callback(a,c,u)},i=new ue(s),o=setTimeout(()=>{Rs(this._pendingQueue,a=>a.callback===s),i.timedOut=!0,t.callback(new Error("timeout exceeded when trying to connect"))},this.options.connectionTimeoutMillis);return o.unref&&o.unref(),this._pendingQueue.push(i),r}return this.newClient(new ue(t.callback)),r}newClient(e){let t=new this.Client(this.options);this._clients.push(t);let r=Xu(this,t);this.log("checking client timeout");let s,i=!1;this.options.connectionTimeoutMillis&&(s=setTimeout(()=>{this.log("ending client due to timeout"),i=!0,t.connection?t.connection.stream.destroy():t.end()},this.options.connectionTimeoutMillis)),this.log("connecting new client"),t.connect(o=>{if(s&&clearTimeout(s),t.on("error",r),o)this.log("client failed to connect",o),this._clients=this._clients.filter(a=>a!==t),i&&(o=new Error("Connection terminated due to connection timeout",{cause:o})),this._pulseQueue(),e.timedOut||e.callback(o,void 0,ys);else{if(this.log("new client connected"),this.options.maxLifetimeSeconds!==0){let a=setTimeout(()=>{this.log("ending client due to expired lifetime"),this._expired.add(t),this._idle.findIndex(u=>u.client===t)!==-1&&this._acquireClient(t,new ue((u,d,l)=>l()),r,!1)},this.options.maxLifetimeSeconds*1e3);a.unref(),t.once("end",()=>clearTimeout(a))}return this._acquireClient(t,e,r,!0)}})}_acquireClient(e,t,r,s){s&&this.emit("connect",e),this.emit("acquire",e),e.release=this._releaseOnce(e,r),e.removeListener("error",r),t.timedOut?s&&this.options.verify?this.options.verify(e,e.release):e.release():s&&this.options.verify?this.options.verify(e,i=>{if(i)return e.release(i),t.callback(i,void 0,ys);t.callback(void 0,e,e.release)}):t.callback(void 0,e,e.release)}_releaseOnce(e,t){let r=!1;return s=>{r&&zu(),r=!0,this._release(e,t,s)}}_release(e,t,r){if(e.on("error",t),e._poolUseCount=(e._poolUseCount||0)+1,this.emit("release",r,e),r||this.ending||!e._queryable||e._ending||e._poolUseCount>=this.options.maxUses){e._poolUseCount>=this.options.maxUses&&this.log("remove expended client"),this._remove(e),this._pulseQueue();return}if(this._expired.has(e)){this.log("remove expired client"),this._expired.delete(e),this._remove(e),this._pulseQueue();return}let i;this.options.idleTimeoutMillis&&(i=setTimeout(()=>{this.log("remove idle client"),this._remove(e)},this.options.idleTimeoutMillis),this.options.allowExitOnIdle&&i.unref()),this.options.allowExitOnIdle&&e.unref(),this._idle.push(new cr(e,t,i)),this._pulseQueue()}query(e,t,r){if(typeof e=="function"){let i=ze(this.Promise,e);return setImmediate(function(){return i.callback(new Error("Passing a function as the first parameter to pool.query is not supported"))}),i.result}typeof t=="function"&&(r=t,t=void 0);let s=ze(this.Promise,r);return r=s.callback,this.connect((i,o)=>{if(i)return r(i);let a=!1,c=u=>{a||(a=!0,o.release(u),r(u))};o.once("error",c),this.log("dispatching query");try{o.query(e,t,(u,d)=>{if(this.log("query dispatched"),o.removeListener("error",c),!a)return a=!0,o.release(u),u?r(u):r(void 0,d)})}catch(u){return o.release(u),r(u)}}),s.result}end(e){if(this.log("ending"),this.ending){let r=new Error("Called end on pool more than once");return e?e(r):this.Promise.reject(r)}this.ending=!0;let t=ze(this.Promise,e);return this._endCallback=t.callback,this._pulseQueue(),t.result}get waitingCount(){return this._pendingQueue.length}get idleCount(){return this._idle.length}get expiredCount(){return this._clients.reduce((e,t)=>e+(this._expired.has(t)?1:0),0)}get totalCount(){return this._clients.length}};Ms.exports=ur});var Us=f((bE,Ps)=>{"use strict";var Is=v("events").EventEmitter,Ju=v("util"),lr=ne(),de=Ps.exports=function(n,e,t){Is.call(this),n=lr.normalizeQueryConfig(n,e,t),this.text=n.text,this.values=n.values,this.name=n.name,this.queryMode=n.queryMode,this.callback=n.callback,this.state="new",this._arrayMode=n.rowMode==="array",this._emitRowEvents=!1,this.on("newListener",function(r){r==="row"&&(this._emitRowEvents=!0)}.bind(this))};Ju.inherits(de,Is);var Zu={sqlState:"code",statementPosition:"position",messagePrimary:"message",context:"where",schemaName:"schema",tableName:"table",columnName:"column",dataTypeName:"dataType",constraintName:"constraint",sourceFile:"file",sourceLine:"line",sourceFunction:"routine"};de.prototype.handleError=function(n){var e=this.native.pq.resultErrorFields();if(e)for(var t in e){var r=Zu[t]||t;n[r]=e[t]}this.callback?this.callback(n):this.emit("error",n),this.state="error"};de.prototype.then=function(n,e){return this._getPromise().then(n,e)};de.prototype.catch=function(n){return this._getPromise().catch(n)};de.prototype._getPromise=function(){return this._promise?this._promise:(this._promise=new Promise(function(n,e){this._once("end",n),this._once("error",e)}.bind(this)),this._promise)};de.prototype.submit=function(n){this.state="running";var e=this;this.native=n.native,n.native.arrayMode=this._arrayMode;var t=function(i,o,a){if(n.native.arrayMode=!1,setImmediate(function(){e.emit("_done")}),i)return e.handleError(i);e._emitRowEvents&&(a.length>1?o.forEach((c,u)=>{c.forEach(d=>{e.emit("row",d,a[u])})}):o.forEach(function(c){e.emit("row",c,a)})),e.state="end",e.emit("end",a),e.callback&&e.callback(null,a)};if(process.domain&&(t=process.domain.bind(t)),this.name){this.name.length>63&&(console.error("Warning! Postgres only supports 63 characters for query names."),console.error("You supplied %s (%s)",this.name,this.name.length),console.error("This can cause conflicts and silent errors executing queries"));var r=(this.values||[]).map(lr.prepareValue);if(n.namedQueries[this.name]){if(this.text&&n.namedQueries[this.name]!==this.text){let i=new Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`);return t(i)}return n.native.execute(this.name,r,t)}return n.native.prepare(this.name,this.text,r.length,function(i){return i?t(i):(n.namedQueries[e.name]=e.text,e.native.execute(e.name,r,t))})}else if(this.values){if(!Array.isArray(this.values)){let i=new Error("Query values must be an array");return t(i)}var s=this.values.map(lr.prepareValue);n.native.query(this.text,s,t)}else this.queryMode==="extended"?n.native.query(this.text,[],t):n.native.query(this.text,t)}});var Ns=f((CE,Cs)=>{"use strict";var Ls;try{Ls=v("pg-native")}catch(n){throw n}var ed=Fe(),Os=v("events").EventEmitter,td=v("util"),rd=Lt(),bs=Us(),w=Cs.exports=function(n){Os.call(this),n=n||{},this._Promise=n.Promise||global.Promise,this._types=new ed(n.types),this.native=new Ls({types:this._types}),this._queryQueue=[],this._ending=!1,this._connecting=!1,this._connected=!1,this._queryable=!0;var e=this.connectionParameters=new rd(n);n.nativeConnectionString&&(e.nativeConnectionString=n.nativeConnectionString),this.user=e.user,Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:e.password}),this.database=e.database,this.host=e.host,this.port=e.port,this.namedQueries={}};w.Query=bs;td.inherits(w,Os);w.prototype._errorAllQueries=function(n){let e=t=>{process.nextTick(()=>{t.native=this.native,t.handleError(n)})};this._hasActiveQuery()&&(e(this._activeQuery),this._activeQuery=null),this._queryQueue.forEach(e),this._queryQueue.length=0};w.prototype._connect=function(n){var e=this;if(this._connecting){process.nextTick(()=>n(new Error("Client has already been connected. You cannot reuse a client.")));return}this._connecting=!0,this.connectionParameters.getLibpqConnectionString(function(t,r){if(e.connectionParameters.nativeConnectionString&&(r=e.connectionParameters.nativeConnectionString),t)return n(t);e.native.connect(r,function(s){if(s)return e.native.end(),n(s);e._connected=!0,e.native.on("error",function(i){e._queryable=!1,e._errorAllQueries(i),e.emit("error",i)}),e.native.on("notification",function(i){e.emit("notification",{channel:i.relname,payload:i.extra})}),e.emit("connect"),e._pulseQueryQueue(!0),n()})})};w.prototype.connect=function(n){if(n){this._connect(n);return}return new this._Promise((e,t)=>{this._connect(r=>{r?t(r):e()})})};w.prototype.query=function(n,e,t){var r,s,i,o,a;if(n==null)throw new TypeError("Client was passed a null or undefined query");if(typeof n.submit=="function")i=n.query_timeout||this.connectionParameters.query_timeout,s=r=n,typeof e=="function"&&(n.callback=e);else if(i=n.query_timeout||this.connectionParameters.query_timeout,r=new bs(n,e,t),!r.callback){let c,u;s=new this._Promise((d,l)=>{c=d,u=l}).catch(d=>{throw Error.captureStackTrace(d),d}),r.callback=(d,l)=>d?u(d):c(l)}return i&&(a=r.callback,o=setTimeout(()=>{var c=new Error("Query read timeout");process.nextTick(()=>{r.handleError(c,this.connection)}),a(c),r.callback=()=>{};var u=this._queryQueue.indexOf(r);u>-1&&this._queryQueue.splice(u,1),this._pulseQueryQueue()},i),r.callback=(c,u)=>{clearTimeout(o),a(c,u)}),this._queryable?this._ending?(r.native=this.native,process.nextTick(()=>{r.handleError(new Error("Client was closed and is not queryable"))}),s):(this._queryQueue.push(r),this._pulseQueryQueue(),s):(r.native=this.native,process.nextTick(()=>{r.handleError(new Error("Client has encountered a connection error and is not queryable"))}),s)};w.prototype.end=function(n){var e=this;this._ending=!0,this._connected||this.once("connect",this.end.bind(this,n));var t;return n||(t=new this._Promise(function(r,s){n=i=>i?s(i):r()})),this.native.end(function(){e._errorAllQueries(new Error("Connection terminated")),process.nextTick(()=>{e.emit("end"),n&&n()})}),t};w.prototype._hasActiveQuery=function(){return this._activeQuery&&this._activeQuery.state!=="error"&&this._activeQuery.state!=="end"};w.prototype._pulseQueryQueue=function(n){if(this._connected&&!this._hasActiveQuery()){var e=this._queryQueue.shift();if(!e){n||this.emit("drain");return}this._activeQuery=e,e.submit(this);var t=this;e.once("_done",function(){t._pulseQueryQueue()})}};w.prototype.cancel=function(n){this._activeQuery===n?this.native.cancel(function(){}):this._queryQueue.indexOf(n)!==-1&&this._queryQueue.splice(this._queryQueue.indexOf(n),1)};w.prototype.ref=function(){};w.prototype.unref=function(){};w.prototype.setTypeParser=function(n,e,t){return this._types.setTypeParser(n,e,t)};w.prototype.getTypeParser=function(n,e){return this._types.getTypeParser(n,e)}});var mr=f((NE,Ds)=>{"use strict";Ds.exports=Ns()});var dr=f((xE,Re)=>{"use strict";var nd=As(),sd=Te(),id=nr(),od=bt(),ad=ne(),cd=vs(),ud=Fe(),{DatabaseError:dd}=er(),{escapeIdentifier:ld,escapeLiteral:md}=ne(),Ed=n=>class extends cd{constructor(t){super(t,n)}},Er=function(n){this.defaults=sd,this.Client=n,this.Query=this.Client.Query,this.Pool=Ed(this.Client),this._pools=[],this.Connection=id,this.types=fe(),this.DatabaseError=dd,this.TypeOverrides=ud,this.escapeIdentifier=ld,this.escapeLiteral=md,this.Result=od,this.utils=ad};typeof process.env.NODE_PG_FORCE_NATIVE<"u"?Re.exports=new Er(mr()):(Re.exports=new Er(nd),Object.defineProperty(Re.exports,"native",{configurable:!0,enumerable:!1,get(){var n=null;try{n=new Er(mr())}catch(e){if(e.code!=="MODULE_NOT_FOUND")throw e}return Object.defineProperty(Re.exports,"native",{value:n}),n}}))});function qd(n){if(!n||!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(n))throw new Error(`Invalid UUID format: ${n}`);return n}var N={SMALL:"TEXT_SMALL",MEDIUM:"TEXT_LARGE",LARGE:"TEXT_LARGE",TEXT_SMALL:"TEXT_SMALL",TEXT_LARGE:"TEXT_LARGE",TEXT_EMBEDDING:"TEXT_EMBEDDING",TEXT_TOKENIZER_ENCODE:"TEXT_TOKENIZER_ENCODE",TEXT_TOKENIZER_DECODE:"TEXT_TOKENIZER_DECODE",TEXT_REASONING_SMALL:"REASONING_SMALL",TEXT_REASONING_LARGE:"REASONING_LARGE",TEXT_COMPLETION:"TEXT_COMPLETION",IMAGE:"IMAGE",IMAGE_DESCRIPTION:"IMAGE_DESCRIPTION",TRANSCRIPTION:"TRANSCRIPTION",TEXT_TO_SPEECH:"TEXT_TO_SPEECH",AUDIO:"AUDIO",VIDEO:"VIDEO",OBJECT_SMALL:"OBJECT_SMALL",OBJECT_LARGE:"OBJECT_LARGE"},Ue={TRANSCRIPTION:"transcription",VIDEO:"video",BROWSER:"browser",PDF:"pdf",REMOTE_FILES:"aws_s3",WEB_SEARCH:"web_search",EMAIL:"email",TEE:"tee",TASK:"task",INSTRUMENTATION:"instrumentation"},fr=(i=>(i.DOCUMENT="document",i.FRAGMENT="fragment",i.MESSAGE="message",i.DESCRIPTION="description",i.CUSTOM="custom",i))(fr||{}),Tr=(d=>(d.SELF="SELF",d.DM="dm",d.GROUP="group",d.VOICE_DM="VOICE_DM",d.VOICE_GROUP="VOICE_GROUP",d.FEED="FEED",d.THREAD="THREAD",d.WORLD="WORLD",d.FORUM="FORUM",d.API="API",d))(Tr||{}),Pe=class{runtime;constructor(e){e&&(this.runtime=e)}static serviceType;config;static async start(e){throw new Error("Not implemented")}static async stop(e){throw new Error("Not implemented")}},qs=(t=>(t.ACTIVE="active",t.INACTIVE="inactive",t))(qs||{}),Ks=(t=>(t.SHARED="shared",t.PRIVATE="private",t))(Ks||{}),Hs=(e=>(e.KNOWLEDGE="knowledge",e))(Hs||{}),$s=(s=>(s.OFF="OFF",s.LOCAL="LOCAL",s.DOCKER="DOCKER",s.PRODUCTION="PRODUCTION",s))($s||{}),Ys=(e=>(e.TDX_DSTACK="tdx_dstack",e))(Ys||{}),Ar=(r=>(r.OWNER="OWNER",r.ADMIN="ADMIN",r.NONE="NONE",r))(Ar||{}),yr=(y=>(y.WORLD_JOINED="WORLD_JOINED",y.WORLD_CONNECTED="WORLD_CONNECTED",y.WORLD_LEFT="WORLD_LEFT",y.ENTITY_JOINED="ENTITY_JOINED",y.ENTITY_LEFT="ENTITY_LEFT",y.ENTITY_UPDATED="ENTITY_UPDATED",y.ROOM_JOINED="ROOM_JOINED",y.ROOM_LEFT="ROOM_LEFT",y.MESSAGE_RECEIVED="MESSAGE_RECEIVED",y.MESSAGE_SENT="MESSAGE_SENT",y.VOICE_MESSAGE_RECEIVED="VOICE_MESSAGE_RECEIVED",y.VOICE_MESSAGE_SENT="VOICE_MESSAGE_SENT",y.REACTION_RECEIVED="REACTION_RECEIVED",y.POST_GENERATED="POST_GENERATED",y.INTERACTION_RECEIVED="INTERACTION_RECEIVED",y.RUN_STARTED="RUN_STARTED",y.RUN_ENDED="RUN_ENDED",y.RUN_TIMEOUT="RUN_TIMEOUT",y.ACTION_STARTED="ACTION_STARTED",y.ACTION_COMPLETED="ACTION_COMPLETED",y.EVALUATOR_STARTED="EVALUATOR_STARTED",y.EVALUATOR_COMPLETED="EVALUATOR_COMPLETED",y.MODEL_USED="MODEL_USED",y))(yr||{}),js=(r=>(r.DISCORD="DISCORD",r.TELEGRAM="TELEGRAM",r.TWITTER="TWITTER",r))(js||{}),Qs=(o=>(o[o.ROOM_JOINING=1]="ROOM_JOINING",o[o.SEND_MESSAGE=2]="SEND_MESSAGE",o[o.MESSAGE=3]="MESSAGE",o[o.ACK=4]="ACK",o[o.THINKING=5]="THINKING",o[o.CONTROL=6]="CONTROL",o))(Qs||{});function Kd(n){return{...n,createdAt:Date.now(),metadata:{type:"message",timestamp:Date.now(),scope:n.agentId?"private":"shared"}}}function Hd(n,e){return n.getService(e)}function $d(n){return n.type==="document"}function Yd(n){return n.type==="fragment"}function jd(n){return n.type==="message"}function Qd(n){return n.type==="description"}function zd(n){return n.type!=="document"&&n.type!=="fragment"&&n.type!=="message"&&n.type!=="description"}function Xd(n){return n.getService(Ue.VIDEO)}function Jd(n){return n.getService(Ue.BROWSER)}function Zd(n){return n.getService(Ue.PDF)}function el(n){return n.getService(Ue.REMOTE_FILES)}function tl(n){return n.metadata?.type==="document"}function rl(n){return n.metadata?.type==="fragment"}function nl(n,e=""){return n.content.text??e}function sl(n,e="UNKNOWN_ERROR"){return n instanceof Error?{code:e,message:n.message,cause:n}:{code:e,message:String(n)}}var il={SMALL:384,MEDIUM:512,LARGE:768,XL:1024,XXL:1536,XXXL:3072};import{names as zs,uniqueNamesGenerator as Xs}from"unique-names-generator";var cl=(n,e)=>{let t=n.map(o=>[...o.examples]),r=[],s=t.length;for(let o=0;o<e&&s;o++){let a=o%s,c=t[a];if(c.length){let u=~~(Math.random()*c.length);r[o]=c.splice(u,1)[0]}else o--;c.length===0&&(t.splice(a,1),s--)}return r.map(o=>{let a=Array.from({length:5},()=>Xs({dictionaries:[zs]}));return`
|
|
6
|
-
${o.map(
|
|
4
|
+
`}else return n}function k(...n){lu&&console.log(...n.map(mu))}});var as=f((yE,os)=>{var{getStream:Eu,getSecureStream:pu}=gu();os.exports={getStream:Eu,getSecureStream:pu};function hu(){function n(t){let r=v("net");return new r.Socket}function e(t){var r=v("tls");return r.connect(t)}return{getStream:n,getSecureStream:e}}function _u(){function n(t){let{CloudflareSocket:r}=is();return new r(t)}function e(t){return t.socket.startTls(t),t.socket}return{getStream:n,getSecureStream:e}}function Su(){if(typeof navigator=="object"&&navigator!==null&&typeof navigator.userAgent=="string")return navigator.userAgent==="Cloudflare-Workers";if(typeof Response=="function"){let n=new Response(null,{cf:{thing:!0}});if(typeof n.cf=="object"&&n.cf!==null&&n.cf.thing)return!0}return!1}function gu(){return Su()?_u():hu()}});var nr=f((RE,cs)=>{"use strict";var fu=v("events").EventEmitter,{parse:Tu,serialize:b}=er(),{getStream:Au,getSecureStream:yu}=as(),Ru=b.flush(),Mu=b.sync(),vu=b.end(),rr=class extends fu{constructor(e){super(),e=e||{},this.stream=e.stream||Au(e.ssl),typeof this.stream=="function"&&(this.stream=this.stream(e)),this._keepAlive=e.keepAlive,this._keepAliveInitialDelayMillis=e.keepAliveInitialDelayMillis,this.lastBuffer=!1,this.parsedStatements={},this.ssl=e.ssl||!1,this._ending=!1,this._emitMessage=!1;var t=this;this.on("newListener",function(r){r==="message"&&(t._emitMessage=!0)})}connect(e,t){var r=this;this._connecting=!0,this.stream.setNoDelay(!0),this.stream.connect(e,t),this.stream.once("connect",function(){r._keepAlive&&r.stream.setKeepAlive(!0,r._keepAliveInitialDelayMillis),r.emit("connect")});let s=function(i){r._ending&&(i.code==="ECONNRESET"||i.code==="EPIPE")||r.emit("error",i)};if(this.stream.on("error",s),this.stream.on("close",function(){r.emit("end")}),!this.ssl)return this.attachListeners(this.stream);this.stream.once("data",function(i){var o=i.toString("utf8");switch(o){case"S":break;case"N":return r.stream.end(),r.emit("error",new Error("The server does not support SSL connections"));default:return r.stream.end(),r.emit("error",new Error("There was an error establishing an SSL connection"))}let a={socket:r.stream};r.ssl!==!0&&(Object.assign(a,r.ssl),"key"in r.ssl&&(a.key=r.ssl.key));var u=v("net");u.isIP&&u.isIP(t)===0&&(a.servername=t);try{r.stream=yu(a)}catch(c){return r.emit("error",c)}r.attachListeners(r.stream),r.stream.on("error",s),r.emit("sslconnect")})}attachListeners(e){Tu(e,t=>{var r=t.name==="error"?"errorMessage":t.name;this._emitMessage&&this.emit("message",t),this.emit(r,t)})}requestSsl(){this.stream.write(b.requestSsl())}startup(e){this.stream.write(b.startup(e))}cancel(e,t){this._send(b.cancel(e,t))}password(e){this._send(b.password(e))}sendSASLInitialResponseMessage(e,t){this._send(b.sendSASLInitialResponseMessage(e,t))}sendSCRAMClientFinalMessage(e){this._send(b.sendSCRAMClientFinalMessage(e))}_send(e){return this.stream.writable?this.stream.write(e):!1}query(e){this._send(b.query(e))}parse(e){this._send(b.parse(e))}bind(e){this._send(b.bind(e))}execute(e){this._send(b.execute(e))}flush(){this.stream.writable&&this.stream.write(Ru)}sync(){this._ending=!0,this._send(Mu)}ref(){this.stream.ref()}unref(){this.stream.unref()}end(){if(this._ending=!0,!this._connecting||!this.stream.writable){this.stream.end();return}return this.stream.write(vu,()=>{this.stream.end()})}close(e){this._send(b.close(e))}describe(e){this._send(b.describe(e))}sendCopyFromChunk(e){this._send(b.copyData(e))}endCopyFrom(){this._send(b.copyDone())}sendCopyFail(e){this._send(b.copyFail(e))}};cs.exports=rr});var ms=f((ME,ls)=>{"use strict";var{Transform:Iu}=v("stream"),{StringDecoder:Pu}=v("string_decoder"),Y=Symbol("last"),$e=Symbol("decoder");function Uu(n,e,t){let r;if(this.overflow){if(r=this[$e].write(n).split(this.matcher),r.length===1)return t();r.shift(),this.overflow=!1}else this[Y]+=this[$e].write(n),r=this[Y].split(this.matcher);this[Y]=r.pop();for(let s=0;s<r.length;s++)try{ds(this,this.mapper(r[s]))}catch(i){return t(i)}if(this.overflow=this[Y].length>this.maxLength,this.overflow&&!this.skipOverflow){t(new Error("maximum buffer reached"));return}t()}function Lu(n){if(this[Y]+=this[$e].end(),this[Y])try{ds(this,this.mapper(this[Y]))}catch(e){return n(e)}n()}function ds(n,e){e!==void 0&&n.push(e)}function us(n){return n}function Ou(n,e,t){switch(n=n||/\r?\n/,e=e||us,t=t||{},arguments.length){case 1:typeof n=="function"?(e=n,n=/\r?\n/):typeof n=="object"&&!(n instanceof RegExp)&&!n[Symbol.split]&&(t=n,n=/\r?\n/);break;case 2:typeof n=="function"?(t=e,e=n,n=/\r?\n/):typeof e=="object"&&(t=e,e=us)}t=Object.assign({},t),t.autoDestroy=!0,t.transform=Uu,t.flush=Lu,t.readableObjectMode=!0;let r=new Iu(t);return r[Y]="",r[$e]=new Pu("utf8"),r.matcher=n,r.mapper=e,r.maxLength=t.maxLength,r.skipOverflow=t.skipOverflow||!1,r.overflow=!1,r._destroy=function(s,i){this._writableState.errorEmitted=!1,i(s)},r}ls.exports=Ou});var hs=f((vE,W)=>{"use strict";var Es=v("path"),bu=v("stream").Stream,Cu=ms(),ps=v("util"),Nu=5432,Ye=process.platform==="win32",ye=process.stderr,Du=56,xu=7,wu=61440,ku=32768;function Vu(n){return(n&wu)==ku}var ce=["host","port","database","user","password"],sr=ce.length,Fu=ce[sr-1];function ir(){var n=ye instanceof bu&&ye.writable===!0;if(n){var e=Array.prototype.slice.call(arguments).concat(`
|
|
5
|
+
`);ye.write(ps.format.apply(ps,e))}}Object.defineProperty(W.exports,"isWin",{get:function(){return Ye},set:function(n){Ye=n}});W.exports.warnTo=function(n){var e=ye;return ye=n,e};W.exports.getFileName=function(n){var e=n||process.env,t=e.PGPASSFILE||(Ye?Es.join(e.APPDATA||"./","postgresql","pgpass.conf"):Es.join(e.HOME||"./",".pgpass"));return t};W.exports.usePgPass=function(n,e){return Object.prototype.hasOwnProperty.call(process.env,"PGPASSWORD")?!1:Ye?!0:(e=e||"<unkn>",Vu(n.mode)?n.mode&(Du|xu)?(ir('WARNING: password file "%s" has group or world access; permissions should be u=rw (0600) or less',e),!1):!0:(ir('WARNING: password file "%s" is not a plain file',e),!1))};var Gu=W.exports.match=function(n,e){return ce.slice(0,-1).reduce(function(t,r,s){return s==1&&Number(n[r]||Nu)===Number(e[r])?t&&!0:t&&(e[r]==="*"||e[r]===n[r])},!0)};W.exports.getPassword=function(n,e,t){var r,s=e.pipe(Cu());function i(u){var c=Bu(u);c&&Wu(c)&&Gu(n,c)&&(r=c[Fu],s.end())}var o=function(){e.destroy(),t(r)},a=function(u){e.destroy(),ir("WARNING: error on reading file: %s",u),t(void 0)};e.on("error",a),s.on("data",i).on("end",o).on("error",a)};var Bu=W.exports.parseLine=function(n){if(n.length<11||n.match(/^\s+#/))return null;for(var e="",t="",r=0,s=0,i=0,o={},a=!1,u=function(d,l,m){var E=n.substring(l,m);Object.hasOwnProperty.call(process.env,"PGPASS_NO_DEESCAPE")||(E=E.replace(/\\([:\\])/g,"$1")),o[ce[d]]=E},c=0;c<n.length-1;c+=1){if(e=n.charAt(c+1),t=n.charAt(c),a=r==sr-1,a){u(r,s);break}c>=0&&e==":"&&t!=="\\"&&(u(r,s,c+1),s=c+2,r+=1)}return o=Object.keys(o).length===sr?o:null,o},Wu=W.exports.isValidEntry=function(n){for(var e={0:function(o){return o.length>0},1:function(o){return o==="*"?!0:(o=Number(o),isFinite(o)&&o>0&&o<9007199254740992&&Math.floor(o)===o)},2:function(o){return o.length>0},3:function(o){return o.length>0},4:function(o){return o.length>0}},t=0;t<ce.length;t+=1){var r=e[t],s=n[ce[t]]||"",i=r(s);if(!i)return!1}return!0}});var Ss=f((PE,or)=>{"use strict";var IE=v("path"),_s=v("fs"),je=hs();or.exports=function(n,e){var t=je.getFileName();_s.stat(t,function(r,s){if(r||!je.usePgPass(s,t))return e(void 0);var i=_s.createReadStream(t);je.getPassword(n,i,e)})};or.exports.warnTo=je.warnTo});var As=f((UE,Ts)=>{"use strict";var qu=v("events").EventEmitter,gs=ne(),ar=Vn(),Ku=Fe(),Hu=Lt(),fs=Xn(),$u=Te(),Yu=nr(),ju=It(),ze=class extends qu{constructor(e){super(),this.connectionParameters=new Hu(e),this.user=this.connectionParameters.user,this.database=this.connectionParameters.database,this.port=this.connectionParameters.port,this.host=this.connectionParameters.host,Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:this.connectionParameters.password}),this.replication=this.connectionParameters.replication;var t=e||{};this._Promise=t.Promise||global.Promise,this._types=new Ku(t.types),this._ending=!1,this._ended=!1,this._connecting=!1,this._connected=!1,this._connectionError=!1,this._queryable=!0,this.enableChannelBinding=!!t.enableChannelBinding,this.connection=t.connection||new Yu({stream:t.stream,ssl:this.connectionParameters.ssl,keepAlive:t.keepAlive||!1,keepAliveInitialDelayMillis:t.keepAliveInitialDelayMillis||0,encoding:this.connectionParameters.client_encoding||"utf8"}),this.queryQueue=[],this.binary=t.binary||$u.binary,this.processID=null,this.secretKey=null,this.ssl=this.connectionParameters.ssl||!1,this.ssl&&this.ssl.key&&Object.defineProperty(this.ssl,"key",{enumerable:!1}),this._connectionTimeoutMillis=t.connectionTimeoutMillis||0}_errorAllQueries(e){let t=r=>{process.nextTick(()=>{r.handleError(e,this.connection)})};this.activeQuery&&(t(this.activeQuery),this.activeQuery=null),this.queryQueue.forEach(t),this.queryQueue.length=0}_connect(e){var t=this,r=this.connection;if(this._connectionCallback=e,this._connecting||this._connected){let s=new Error("Client has already been connected. You cannot reuse a client.");process.nextTick(()=>{e(s)});return}this._connecting=!0,this._connectionTimeoutMillis>0&&(this.connectionTimeoutHandle=setTimeout(()=>{r._ending=!0,r.stream.destroy(new Error("timeout expired"))},this._connectionTimeoutMillis),this.connectionTimeoutHandle.unref&&this.connectionTimeoutHandle.unref()),this.host&&this.host.indexOf("/")===0?r.connect(this.host+"/.s.PGSQL."+this.port):r.connect(this.port,this.host),r.on("connect",function(){t.ssl?r.requestSsl():r.startup(t.getStartupConf())}),r.on("sslconnect",function(){r.startup(t.getStartupConf())}),this._attachListeners(r),r.once("end",()=>{let s=this._ending?new Error("Connection terminated"):new Error("Connection terminated unexpectedly");clearTimeout(this.connectionTimeoutHandle),this._errorAllQueries(s),this._ended=!0,this._ending||(this._connecting&&!this._connectionError?this._connectionCallback?this._connectionCallback(s):this._handleErrorEvent(s):this._connectionError||this._handleErrorEvent(s)),process.nextTick(()=>{this.emit("end")})})}connect(e){if(e){this._connect(e);return}return new this._Promise((t,r)=>{this._connect(s=>{s?r(s):t()})})}_attachListeners(e){e.on("authenticationCleartextPassword",this._handleAuthCleartextPassword.bind(this)),e.on("authenticationMD5Password",this._handleAuthMD5Password.bind(this)),e.on("authenticationSASL",this._handleAuthSASL.bind(this)),e.on("authenticationSASLContinue",this._handleAuthSASLContinue.bind(this)),e.on("authenticationSASLFinal",this._handleAuthSASLFinal.bind(this)),e.on("backendKeyData",this._handleBackendKeyData.bind(this)),e.on("error",this._handleErrorEvent.bind(this)),e.on("errorMessage",this._handleErrorMessage.bind(this)),e.on("readyForQuery",this._handleReadyForQuery.bind(this)),e.on("notice",this._handleNotice.bind(this)),e.on("rowDescription",this._handleRowDescription.bind(this)),e.on("dataRow",this._handleDataRow.bind(this)),e.on("portalSuspended",this._handlePortalSuspended.bind(this)),e.on("emptyQuery",this._handleEmptyQuery.bind(this)),e.on("commandComplete",this._handleCommandComplete.bind(this)),e.on("parseComplete",this._handleParseComplete.bind(this)),e.on("copyInResponse",this._handleCopyInResponse.bind(this)),e.on("copyData",this._handleCopyData.bind(this)),e.on("notification",this._handleNotification.bind(this))}_checkPgPass(e){let t=this.connection;if(typeof this.password=="function")this._Promise.resolve().then(()=>this.password()).then(r=>{if(r!==void 0){if(typeof r!="string"){t.emit("error",new TypeError("Password must be a string"));return}this.connectionParameters.password=this.password=r}else this.connectionParameters.password=this.password=null;e()}).catch(r=>{t.emit("error",r)});else if(this.password!==null)e();else try{Ss()(this.connectionParameters,s=>{s!==void 0&&(this.connectionParameters.password=this.password=s),e()})}catch(r){this.emit("error",r)}}_handleAuthCleartextPassword(e){this._checkPgPass(()=>{this.connection.password(this.password)})}_handleAuthMD5Password(e){this._checkPgPass(async()=>{try{let t=await ju.postgresMd5PasswordHash(this.user,this.password,e.salt);this.connection.password(t)}catch(t){this.emit("error",t)}})}_handleAuthSASL(e){this._checkPgPass(()=>{try{this.saslSession=ar.startSession(e.mechanisms,this.enableChannelBinding&&this.connection.stream),this.connection.sendSASLInitialResponseMessage(this.saslSession.mechanism,this.saslSession.response)}catch(t){this.connection.emit("error",t)}})}async _handleAuthSASLContinue(e){try{await ar.continueSession(this.saslSession,this.password,e.data,this.enableChannelBinding&&this.connection.stream),this.connection.sendSCRAMClientFinalMessage(this.saslSession.response)}catch(t){this.connection.emit("error",t)}}_handleAuthSASLFinal(e){try{ar.finalizeSession(this.saslSession,e.data),this.saslSession=null}catch(t){this.connection.emit("error",t)}}_handleBackendKeyData(e){this.processID=e.processID,this.secretKey=e.secretKey}_handleReadyForQuery(e){this._connecting&&(this._connecting=!1,this._connected=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback&&(this._connectionCallback(null,this),this._connectionCallback=null),this.emit("connect"));let{activeQuery:t}=this;this.activeQuery=null,this.readyForQuery=!0,t&&t.handleReadyForQuery(this.connection),this._pulseQueryQueue()}_handleErrorWhileConnecting(e){if(!this._connectionError){if(this._connectionError=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback)return this._connectionCallback(e);this.emit("error",e)}}_handleErrorEvent(e){if(this._connecting)return this._handleErrorWhileConnecting(e);this._queryable=!1,this._errorAllQueries(e),this.emit("error",e)}_handleErrorMessage(e){if(this._connecting)return this._handleErrorWhileConnecting(e);let t=this.activeQuery;if(!t){this._handleErrorEvent(e);return}this.activeQuery=null,t.handleError(e,this.connection)}_handleRowDescription(e){this.activeQuery.handleRowDescription(e)}_handleDataRow(e){this.activeQuery.handleDataRow(e)}_handlePortalSuspended(e){this.activeQuery.handlePortalSuspended(this.connection)}_handleEmptyQuery(e){this.activeQuery.handleEmptyQuery(this.connection)}_handleCommandComplete(e){if(this.activeQuery==null){let t=new Error("Received unexpected commandComplete message from backend.");this._handleErrorEvent(t);return}this.activeQuery.handleCommandComplete(e,this.connection)}_handleParseComplete(){if(this.activeQuery==null){let e=new Error("Received unexpected parseComplete message from backend.");this._handleErrorEvent(e);return}this.activeQuery.name&&(this.connection.parsedStatements[this.activeQuery.name]=this.activeQuery.text)}_handleCopyInResponse(e){this.activeQuery.handleCopyInResponse(this.connection)}_handleCopyData(e){this.activeQuery.handleCopyData(e,this.connection)}_handleNotification(e){this.emit("notification",e)}_handleNotice(e){this.emit("notice",e)}getStartupConf(){var e=this.connectionParameters,t={user:e.user,database:e.database},r=e.application_name||e.fallback_application_name;return r&&(t.application_name=r),e.replication&&(t.replication=""+e.replication),e.statement_timeout&&(t.statement_timeout=String(parseInt(e.statement_timeout,10))),e.lock_timeout&&(t.lock_timeout=String(parseInt(e.lock_timeout,10))),e.idle_in_transaction_session_timeout&&(t.idle_in_transaction_session_timeout=String(parseInt(e.idle_in_transaction_session_timeout,10))),e.options&&(t.options=e.options),t}cancel(e,t){if(e.activeQuery===t){var r=this.connection;this.host&&this.host.indexOf("/")===0?r.connect(this.host+"/.s.PGSQL."+this.port):r.connect(this.port,this.host),r.on("connect",function(){r.cancel(e.processID,e.secretKey)})}else e.queryQueue.indexOf(t)!==-1&&e.queryQueue.splice(e.queryQueue.indexOf(t),1)}setTypeParser(e,t,r){return this._types.setTypeParser(e,t,r)}getTypeParser(e,t){return this._types.getTypeParser(e,t)}escapeIdentifier(e){return gs.escapeIdentifier(e)}escapeLiteral(e){return gs.escapeLiteral(e)}_pulseQueryQueue(){if(this.readyForQuery===!0)if(this.activeQuery=this.queryQueue.shift(),this.activeQuery){this.readyForQuery=!1,this.hasExecuted=!0;let e=this.activeQuery.submit(this.connection);e&&process.nextTick(()=>{this.activeQuery.handleError(e,this.connection),this.readyForQuery=!0,this._pulseQueryQueue()})}else this.hasExecuted&&(this.activeQuery=null,this.emit("drain"))}query(e,t,r){var s,i,o,a,u;if(e==null)throw new TypeError("Client was passed a null or undefined query");return typeof e.submit=="function"?(o=e.query_timeout||this.connectionParameters.query_timeout,i=s=e,typeof t=="function"&&(s.callback=s.callback||t)):(o=e.query_timeout||this.connectionParameters.query_timeout,s=new fs(e,t,r),s.callback||(i=new this._Promise((c,d)=>{s.callback=(l,m)=>l?d(l):c(m)}).catch(c=>{throw Error.captureStackTrace(c),c}))),o&&(u=s.callback,a=setTimeout(()=>{var c=new Error("Query read timeout");process.nextTick(()=>{s.handleError(c,this.connection)}),u(c),s.callback=()=>{};var d=this.queryQueue.indexOf(s);d>-1&&this.queryQueue.splice(d,1),this._pulseQueryQueue()},o),s.callback=(c,d)=>{clearTimeout(a),u(c,d)}),this.binary&&!s.binary&&(s.binary=!0),s._result&&!s._result._types&&(s._result._types=this._types),this._queryable?this._ending?(process.nextTick(()=>{s.handleError(new Error("Client was closed and is not queryable"),this.connection)}),i):(this.queryQueue.push(s),this._pulseQueryQueue(),i):(process.nextTick(()=>{s.handleError(new Error("Client has encountered a connection error and is not queryable"),this.connection)}),i)}ref(){this.connection.ref()}unref(){this.connection.unref()}end(e){if(this._ending=!0,!this.connection._connecting||this._ended)if(e)e();else return this._Promise.resolve();if(this.activeQuery||!this._queryable?this.connection.stream.destroy():this.connection.end(),e)this.connection.once("end",e);else return new this._Promise(t=>{this.connection.once("end",t)})}};ze.Query=fs;Ts.exports=ze});var vs=f((LE,Ms)=>{"use strict";var zu=v("events").EventEmitter,ys=function(){},Rs=(n,e)=>{let t=n.findIndex(e);return t===-1?void 0:n.splice(t,1)[0]},cr=class{constructor(e,t,r){this.client=e,this.idleListener=t,this.timeoutId=r}},ue=class{constructor(e){this.callback=e}};function Qu(){throw new Error("Release called on client which has already been released to the pool.")}function Qe(n,e){if(e)return{callback:e,result:void 0};let t,r,s=function(o,a){o?t(o):r(a)},i=new n(function(o,a){r=o,t=a}).catch(o=>{throw Error.captureStackTrace(o),o});return{callback:s,result:i}}function Xu(n,e){return function t(r){r.client=e,e.removeListener("error",t),e.on("error",()=>{n.log("additional client error after disconnection due to error",r)}),n._remove(e),n.emit("error",r,e)}}var ur=class extends zu{constructor(e,t){super(),this.options=Object.assign({},e),e!=null&&"password"in e&&Object.defineProperty(this.options,"password",{configurable:!0,enumerable:!1,writable:!0,value:e.password}),e!=null&&e.ssl&&e.ssl.key&&Object.defineProperty(this.options.ssl,"key",{enumerable:!1}),this.options.max=this.options.max||this.options.poolSize||10,this.options.maxUses=this.options.maxUses||1/0,this.options.allowExitOnIdle=this.options.allowExitOnIdle||!1,this.options.maxLifetimeSeconds=this.options.maxLifetimeSeconds||0,this.log=this.options.log||function(){},this.Client=this.options.Client||t||dr().Client,this.Promise=this.options.Promise||global.Promise,typeof this.options.idleTimeoutMillis>"u"&&(this.options.idleTimeoutMillis=1e4),this._clients=[],this._idle=[],this._expired=new WeakSet,this._pendingQueue=[],this._endCallback=void 0,this.ending=!1,this.ended=!1}_isFull(){return this._clients.length>=this.options.max}_pulseQueue(){if(this.log("pulse queue"),this.ended){this.log("pulse queue ended");return}if(this.ending){this.log("pulse queue on ending"),this._idle.length&&this._idle.slice().map(t=>{this._remove(t.client)}),this._clients.length||(this.ended=!0,this._endCallback());return}if(!this._pendingQueue.length){this.log("no queued requests");return}if(!this._idle.length&&this._isFull())return;let e=this._pendingQueue.shift();if(this._idle.length){let t=this._idle.pop();clearTimeout(t.timeoutId);let r=t.client;r.ref&&r.ref();let s=t.idleListener;return this._acquireClient(r,e,s,!1)}if(!this._isFull())return this.newClient(e);throw new Error("unexpected condition")}_remove(e){let t=Rs(this._idle,r=>r.client===e);t!==void 0&&clearTimeout(t.timeoutId),this._clients=this._clients.filter(r=>r!==e),e.end(),this.emit("remove",e)}connect(e){if(this.ending){let s=new Error("Cannot use a pool after calling end on the pool");return e?e(s):this.Promise.reject(s)}let t=Qe(this.Promise,e),r=t.result;if(this._isFull()||this._idle.length){if(this._idle.length&&process.nextTick(()=>this._pulseQueue()),!this.options.connectionTimeoutMillis)return this._pendingQueue.push(new ue(t.callback)),r;let s=(a,u,c)=>{clearTimeout(o),t.callback(a,u,c)},i=new ue(s),o=setTimeout(()=>{Rs(this._pendingQueue,a=>a.callback===s),i.timedOut=!0,t.callback(new Error("timeout exceeded when trying to connect"))},this.options.connectionTimeoutMillis);return o.unref&&o.unref(),this._pendingQueue.push(i),r}return this.newClient(new ue(t.callback)),r}newClient(e){let t=new this.Client(this.options);this._clients.push(t);let r=Xu(this,t);this.log("checking client timeout");let s,i=!1;this.options.connectionTimeoutMillis&&(s=setTimeout(()=>{this.log("ending client due to timeout"),i=!0,t.connection?t.connection.stream.destroy():t.end()},this.options.connectionTimeoutMillis)),this.log("connecting new client"),t.connect(o=>{if(s&&clearTimeout(s),t.on("error",r),o)this.log("client failed to connect",o),this._clients=this._clients.filter(a=>a!==t),i&&(o=new Error("Connection terminated due to connection timeout",{cause:o})),this._pulseQueue(),e.timedOut||e.callback(o,void 0,ys);else{if(this.log("new client connected"),this.options.maxLifetimeSeconds!==0){let a=setTimeout(()=>{this.log("ending client due to expired lifetime"),this._expired.add(t),this._idle.findIndex(c=>c.client===t)!==-1&&this._acquireClient(t,new ue((c,d,l)=>l()),r,!1)},this.options.maxLifetimeSeconds*1e3);a.unref(),t.once("end",()=>clearTimeout(a))}return this._acquireClient(t,e,r,!0)}})}_acquireClient(e,t,r,s){s&&this.emit("connect",e),this.emit("acquire",e),e.release=this._releaseOnce(e,r),e.removeListener("error",r),t.timedOut?s&&this.options.verify?this.options.verify(e,e.release):e.release():s&&this.options.verify?this.options.verify(e,i=>{if(i)return e.release(i),t.callback(i,void 0,ys);t.callback(void 0,e,e.release)}):t.callback(void 0,e,e.release)}_releaseOnce(e,t){let r=!1;return s=>{r&&Qu(),r=!0,this._release(e,t,s)}}_release(e,t,r){if(e.on("error",t),e._poolUseCount=(e._poolUseCount||0)+1,this.emit("release",r,e),r||this.ending||!e._queryable||e._ending||e._poolUseCount>=this.options.maxUses){e._poolUseCount>=this.options.maxUses&&this.log("remove expended client"),this._remove(e),this._pulseQueue();return}if(this._expired.has(e)){this.log("remove expired client"),this._expired.delete(e),this._remove(e),this._pulseQueue();return}let i;this.options.idleTimeoutMillis&&(i=setTimeout(()=>{this.log("remove idle client"),this._remove(e)},this.options.idleTimeoutMillis),this.options.allowExitOnIdle&&i.unref()),this.options.allowExitOnIdle&&e.unref(),this._idle.push(new cr(e,t,i)),this._pulseQueue()}query(e,t,r){if(typeof e=="function"){let i=Qe(this.Promise,e);return setImmediate(function(){return i.callback(new Error("Passing a function as the first parameter to pool.query is not supported"))}),i.result}typeof t=="function"&&(r=t,t=void 0);let s=Qe(this.Promise,r);return r=s.callback,this.connect((i,o)=>{if(i)return r(i);let a=!1,u=c=>{a||(a=!0,o.release(c),r(c))};o.once("error",u),this.log("dispatching query");try{o.query(e,t,(c,d)=>{if(this.log("query dispatched"),o.removeListener("error",u),!a)return a=!0,o.release(c),c?r(c):r(void 0,d)})}catch(c){return o.release(c),r(c)}}),s.result}end(e){if(this.log("ending"),this.ending){let r=new Error("Called end on pool more than once");return e?e(r):this.Promise.reject(r)}this.ending=!0;let t=Qe(this.Promise,e);return this._endCallback=t.callback,this._pulseQueue(),t.result}get waitingCount(){return this._pendingQueue.length}get idleCount(){return this._idle.length}get expiredCount(){return this._clients.reduce((e,t)=>e+(this._expired.has(t)?1:0),0)}get totalCount(){return this._clients.length}};Ms.exports=ur});var Us=f((OE,Ps)=>{"use strict";var Is=v("events").EventEmitter,Ju=v("util"),lr=ne(),de=Ps.exports=function(n,e,t){Is.call(this),n=lr.normalizeQueryConfig(n,e,t),this.text=n.text,this.values=n.values,this.name=n.name,this.queryMode=n.queryMode,this.callback=n.callback,this.state="new",this._arrayMode=n.rowMode==="array",this._emitRowEvents=!1,this.on("newListener",function(r){r==="row"&&(this._emitRowEvents=!0)}.bind(this))};Ju.inherits(de,Is);var Zu={sqlState:"code",statementPosition:"position",messagePrimary:"message",context:"where",schemaName:"schema",tableName:"table",columnName:"column",dataTypeName:"dataType",constraintName:"constraint",sourceFile:"file",sourceLine:"line",sourceFunction:"routine"};de.prototype.handleError=function(n){var e=this.native.pq.resultErrorFields();if(e)for(var t in e){var r=Zu[t]||t;n[r]=e[t]}this.callback?this.callback(n):this.emit("error",n),this.state="error"};de.prototype.then=function(n,e){return this._getPromise().then(n,e)};de.prototype.catch=function(n){return this._getPromise().catch(n)};de.prototype._getPromise=function(){return this._promise?this._promise:(this._promise=new Promise(function(n,e){this._once("end",n),this._once("error",e)}.bind(this)),this._promise)};de.prototype.submit=function(n){this.state="running";var e=this;this.native=n.native,n.native.arrayMode=this._arrayMode;var t=function(i,o,a){if(n.native.arrayMode=!1,setImmediate(function(){e.emit("_done")}),i)return e.handleError(i);e._emitRowEvents&&(a.length>1?o.forEach((u,c)=>{u.forEach(d=>{e.emit("row",d,a[c])})}):o.forEach(function(u){e.emit("row",u,a)})),e.state="end",e.emit("end",a),e.callback&&e.callback(null,a)};if(process.domain&&(t=process.domain.bind(t)),this.name){this.name.length>63&&(console.error("Warning! Postgres only supports 63 characters for query names."),console.error("You supplied %s (%s)",this.name,this.name.length),console.error("This can cause conflicts and silent errors executing queries"));var r=(this.values||[]).map(lr.prepareValue);if(n.namedQueries[this.name]){if(this.text&&n.namedQueries[this.name]!==this.text){let i=new Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`);return t(i)}return n.native.execute(this.name,r,t)}return n.native.prepare(this.name,this.text,r.length,function(i){return i?t(i):(n.namedQueries[e.name]=e.text,e.native.execute(e.name,r,t))})}else if(this.values){if(!Array.isArray(this.values)){let i=new Error("Query values must be an array");return t(i)}var s=this.values.map(lr.prepareValue);n.native.query(this.text,s,t)}else this.queryMode==="extended"?n.native.query(this.text,[],t):n.native.query(this.text,t)}});var Ns=f((bE,Cs)=>{"use strict";var Ls;try{Ls=v("pg-native")}catch(n){throw n}var ed=Fe(),Os=v("events").EventEmitter,td=v("util"),rd=Lt(),bs=Us(),w=Cs.exports=function(n){Os.call(this),n=n||{},this._Promise=n.Promise||global.Promise,this._types=new ed(n.types),this.native=new Ls({types:this._types}),this._queryQueue=[],this._ending=!1,this._connecting=!1,this._connected=!1,this._queryable=!0;var e=this.connectionParameters=new rd(n);n.nativeConnectionString&&(e.nativeConnectionString=n.nativeConnectionString),this.user=e.user,Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:e.password}),this.database=e.database,this.host=e.host,this.port=e.port,this.namedQueries={}};w.Query=bs;td.inherits(w,Os);w.prototype._errorAllQueries=function(n){let e=t=>{process.nextTick(()=>{t.native=this.native,t.handleError(n)})};this._hasActiveQuery()&&(e(this._activeQuery),this._activeQuery=null),this._queryQueue.forEach(e),this._queryQueue.length=0};w.prototype._connect=function(n){var e=this;if(this._connecting){process.nextTick(()=>n(new Error("Client has already been connected. You cannot reuse a client.")));return}this._connecting=!0,this.connectionParameters.getLibpqConnectionString(function(t,r){if(e.connectionParameters.nativeConnectionString&&(r=e.connectionParameters.nativeConnectionString),t)return n(t);e.native.connect(r,function(s){if(s)return e.native.end(),n(s);e._connected=!0,e.native.on("error",function(i){e._queryable=!1,e._errorAllQueries(i),e.emit("error",i)}),e.native.on("notification",function(i){e.emit("notification",{channel:i.relname,payload:i.extra})}),e.emit("connect"),e._pulseQueryQueue(!0),n()})})};w.prototype.connect=function(n){if(n){this._connect(n);return}return new this._Promise((e,t)=>{this._connect(r=>{r?t(r):e()})})};w.prototype.query=function(n,e,t){var r,s,i,o,a;if(n==null)throw new TypeError("Client was passed a null or undefined query");if(typeof n.submit=="function")i=n.query_timeout||this.connectionParameters.query_timeout,s=r=n,typeof e=="function"&&(n.callback=e);else if(i=n.query_timeout||this.connectionParameters.query_timeout,r=new bs(n,e,t),!r.callback){let u,c;s=new this._Promise((d,l)=>{u=d,c=l}).catch(d=>{throw Error.captureStackTrace(d),d}),r.callback=(d,l)=>d?c(d):u(l)}return i&&(a=r.callback,o=setTimeout(()=>{var u=new Error("Query read timeout");process.nextTick(()=>{r.handleError(u,this.connection)}),a(u),r.callback=()=>{};var c=this._queryQueue.indexOf(r);c>-1&&this._queryQueue.splice(c,1),this._pulseQueryQueue()},i),r.callback=(u,c)=>{clearTimeout(o),a(u,c)}),this._queryable?this._ending?(r.native=this.native,process.nextTick(()=>{r.handleError(new Error("Client was closed and is not queryable"))}),s):(this._queryQueue.push(r),this._pulseQueryQueue(),s):(r.native=this.native,process.nextTick(()=>{r.handleError(new Error("Client has encountered a connection error and is not queryable"))}),s)};w.prototype.end=function(n){var e=this;this._ending=!0,this._connected||this.once("connect",this.end.bind(this,n));var t;return n||(t=new this._Promise(function(r,s){n=i=>i?s(i):r()})),this.native.end(function(){e._errorAllQueries(new Error("Connection terminated")),process.nextTick(()=>{e.emit("end"),n&&n()})}),t};w.prototype._hasActiveQuery=function(){return this._activeQuery&&this._activeQuery.state!=="error"&&this._activeQuery.state!=="end"};w.prototype._pulseQueryQueue=function(n){if(this._connected&&!this._hasActiveQuery()){var e=this._queryQueue.shift();if(!e){n||this.emit("drain");return}this._activeQuery=e,e.submit(this);var t=this;e.once("_done",function(){t._pulseQueryQueue()})}};w.prototype.cancel=function(n){this._activeQuery===n?this.native.cancel(function(){}):this._queryQueue.indexOf(n)!==-1&&this._queryQueue.splice(this._queryQueue.indexOf(n),1)};w.prototype.ref=function(){};w.prototype.unref=function(){};w.prototype.setTypeParser=function(n,e,t){return this._types.setTypeParser(n,e,t)};w.prototype.getTypeParser=function(n,e){return this._types.getTypeParser(n,e)}});var mr=f((CE,Ds)=>{"use strict";Ds.exports=Ns()});var dr=f((DE,Re)=>{"use strict";var nd=As(),sd=Te(),id=nr(),od=bt(),ad=ne(),cd=vs(),ud=Fe(),{DatabaseError:dd}=er(),{escapeIdentifier:ld,escapeLiteral:md}=ne(),Ed=n=>class extends cd{constructor(t){super(t,n)}},Er=function(n){this.defaults=sd,this.Client=n,this.Query=this.Client.Query,this.Pool=Ed(this.Client),this._pools=[],this.Connection=id,this.types=fe(),this.DatabaseError=dd,this.TypeOverrides=ud,this.escapeIdentifier=ld,this.escapeLiteral=md,this.Result=od,this.utils=ad};typeof process.env.NODE_PG_FORCE_NATIVE<"u"?Re.exports=new Er(mr()):(Re.exports=new Er(nd),Object.defineProperty(Re.exports,"native",{configurable:!0,enumerable:!1,get(){var n=null;try{n=new Er(mr())}catch(e){if(e.code!=="MODULE_NOT_FOUND")throw e}return Object.defineProperty(Re.exports,"native",{value:n}),n}}))});function qd(n){if(!n||!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(n))throw new Error(`Invalid UUID format: ${n}`);return n}var N={SMALL:"TEXT_SMALL",MEDIUM:"TEXT_LARGE",LARGE:"TEXT_LARGE",TEXT_SMALL:"TEXT_SMALL",TEXT_LARGE:"TEXT_LARGE",TEXT_EMBEDDING:"TEXT_EMBEDDING",TEXT_TOKENIZER_ENCODE:"TEXT_TOKENIZER_ENCODE",TEXT_TOKENIZER_DECODE:"TEXT_TOKENIZER_DECODE",TEXT_REASONING_SMALL:"REASONING_SMALL",TEXT_REASONING_LARGE:"REASONING_LARGE",TEXT_COMPLETION:"TEXT_COMPLETION",IMAGE:"IMAGE",IMAGE_DESCRIPTION:"IMAGE_DESCRIPTION",TRANSCRIPTION:"TRANSCRIPTION",TEXT_TO_SPEECH:"TEXT_TO_SPEECH",AUDIO:"AUDIO",VIDEO:"VIDEO",OBJECT_SMALL:"OBJECT_SMALL",OBJECT_LARGE:"OBJECT_LARGE"},Ue={TRANSCRIPTION:"transcription",VIDEO:"video",BROWSER:"browser",PDF:"pdf",REMOTE_FILES:"aws_s3",WEB_SEARCH:"web_search",EMAIL:"email",TEE:"tee",TASK:"task",INSTRUMENTATION:"instrumentation"},fr=(i=>(i.DOCUMENT="document",i.FRAGMENT="fragment",i.MESSAGE="message",i.DESCRIPTION="description",i.CUSTOM="custom",i))(fr||{}),Tr=(d=>(d.SELF="SELF",d.DM="dm",d.GROUP="group",d.VOICE_DM="VOICE_DM",d.VOICE_GROUP="VOICE_GROUP",d.FEED="FEED",d.THREAD="THREAD",d.WORLD="WORLD",d.FORUM="FORUM",d.API="API",d))(Tr||{}),Pe=class{runtime;constructor(e){e&&(this.runtime=e)}static serviceType;config;static async start(e){throw new Error("Not implemented")}static async stop(e){throw new Error("Not implemented")}},qs=(t=>(t.ACTIVE="active",t.INACTIVE="inactive",t))(qs||{}),Ks=(t=>(t.SHARED="shared",t.PRIVATE="private",t))(Ks||{}),Hs=(e=>(e.KNOWLEDGE="knowledge",e))(Hs||{}),$s=(s=>(s.OFF="OFF",s.LOCAL="LOCAL",s.DOCKER="DOCKER",s.PRODUCTION="PRODUCTION",s))($s||{}),Ys=(e=>(e.TDX_DSTACK="tdx_dstack",e))(Ys||{}),Ar=(r=>(r.OWNER="OWNER",r.ADMIN="ADMIN",r.NONE="NONE",r))(Ar||{}),yr=(y=>(y.WORLD_JOINED="WORLD_JOINED",y.WORLD_CONNECTED="WORLD_CONNECTED",y.WORLD_LEFT="WORLD_LEFT",y.ENTITY_JOINED="ENTITY_JOINED",y.ENTITY_LEFT="ENTITY_LEFT",y.ENTITY_UPDATED="ENTITY_UPDATED",y.ROOM_JOINED="ROOM_JOINED",y.ROOM_LEFT="ROOM_LEFT",y.MESSAGE_RECEIVED="MESSAGE_RECEIVED",y.MESSAGE_SENT="MESSAGE_SENT",y.VOICE_MESSAGE_RECEIVED="VOICE_MESSAGE_RECEIVED",y.VOICE_MESSAGE_SENT="VOICE_MESSAGE_SENT",y.REACTION_RECEIVED="REACTION_RECEIVED",y.POST_GENERATED="POST_GENERATED",y.INTERACTION_RECEIVED="INTERACTION_RECEIVED",y.RUN_STARTED="RUN_STARTED",y.RUN_ENDED="RUN_ENDED",y.RUN_TIMEOUT="RUN_TIMEOUT",y.ACTION_STARTED="ACTION_STARTED",y.ACTION_COMPLETED="ACTION_COMPLETED",y.EVALUATOR_STARTED="EVALUATOR_STARTED",y.EVALUATOR_COMPLETED="EVALUATOR_COMPLETED",y.MODEL_USED="MODEL_USED",y))(yr||{}),js=(r=>(r.DISCORD="DISCORD",r.TELEGRAM="TELEGRAM",r.TWITTER="TWITTER",r))(js||{}),zs=(o=>(o[o.ROOM_JOINING=1]="ROOM_JOINING",o[o.SEND_MESSAGE=2]="SEND_MESSAGE",o[o.MESSAGE=3]="MESSAGE",o[o.ACK=4]="ACK",o[o.THINKING=5]="THINKING",o[o.CONTROL=6]="CONTROL",o))(zs||{});function Kd(n){return{...n,createdAt:Date.now(),metadata:{type:"message",timestamp:Date.now(),scope:n.agentId?"private":"shared"}}}function Hd(n,e){return n.getService(e)}function $d(n){return n.type==="document"}function Yd(n){return n.type==="fragment"}function jd(n){return n.type==="message"}function zd(n){return n.type==="description"}function Qd(n){return n.type!=="document"&&n.type!=="fragment"&&n.type!=="message"&&n.type!=="description"}function Xd(n){return n.getService(Ue.VIDEO)}function Jd(n){return n.getService(Ue.BROWSER)}function Zd(n){return n.getService(Ue.PDF)}function el(n){return n.getService(Ue.REMOTE_FILES)}function tl(n){return n.metadata?.type==="document"}function rl(n){return n.metadata?.type==="fragment"}function nl(n,e=""){return n.content.text??e}function sl(n,e="UNKNOWN_ERROR"){return n instanceof Error?{code:e,message:n.message,cause:n}:{code:e,message:String(n)}}var il={SMALL:384,MEDIUM:512,LARGE:768,XL:1024,XXL:1536,XXXL:3072};import{names as Qs,uniqueNamesGenerator as Xs}from"unique-names-generator";var cl=(n,e)=>{let t=n.map(o=>[...o.examples]),r=[],s=t.length;for(let o=0;o<e&&s;o++){let a=o%s,u=t[a];if(u.length){let c=~~(Math.random()*u.length);r[o]=u.splice(c,1)[0]}else o--;u.length===0&&(t.splice(a,1),s--)}return r.map(o=>{let a=Array.from({length:5},()=>Xs({dictionaries:[Qs]}));return`
|
|
6
|
+
${o.map(u=>{let c=`${u.name}: ${u.content.text}${u.content.action?` (action: ${u.content.action})`:""}${u.content.actions?` (actions: ${u.content.actions.join(", ")})`:""}`;for(let d=0;d<a.length;d++)c=c.replaceAll(`{{name${d+1}}}`,a[d]);return c}).join(`
|
|
7
7
|
`)}`}).join(`
|
|
8
8
|
`)};function ul(n){return n.sort(()=>.5-Math.random()).map(e=>`${e.name}`).join(", ")}function dl(n){return n.sort(()=>.5-Math.random()).map(e=>`${e.name}: ${e.description}`).join(`,
|
|
9
9
|
`)}var Rr=class{db};import Ir from"handlebars";import{RecursiveCharacterTextSplitter as ni}from"langchain/text_splitter";import{names as si,uniqueNamesGenerator as ii}from"unique-names-generator";import tt from"pino";function Js(n){if(!n)return!1;let e=["YES","Y","TRUE","T","1","ON","ENABLE"],t=["NO","N","FALSE","F","0","OFF","DISABLE"],r=n.trim().toUpperCase();return e.includes(r)?!0:(t.includes(r),!1)}var J=class{logs=[];maxLogs=1e3;stream;constructor(e){this.stream=e}write(e){let t,r;if(typeof e=="string"){r=e;try{t=JSON.parse(e)}catch{this.stream&&this.stream.write(e);return}}else t=e,r=JSON.stringify(e);t.time||(t.time=Date.now());let s=(process?.env?.LOG_LEVEL||"").toLowerCase()==="debug",i=!!process?.env?.LOG_DIAGNOSTIC;if(i&&(t.diagnostic=!0),!s&&t.agentName&&t.agentId){let o=t.msg||"";if(typeof o=="string"&&(o.includes("registered successfully")||o.includes("Registering")||o.includes("Success:")||o.includes("linked to")||o.includes("Started"))){i&&console.error("Filtered log:",r);return}}this.logs.push(t),this.logs.length>this.maxLogs&&this.logs.shift(),this.stream&&this.stream.write(r)}recentLogs(){return this.logs}clear(){this.logs=[]}},Zs={fatal:60,error:50,warn:40,info:30,log:29,progress:28,success:27,debug:20,trace:10},rt=Js(process?.env?.LOG_JSON_FORMAT)||!1,ei=(process?.env?.LOG_LEVEL||"").toLowerCase()==="debug",ti=ei?"debug":process?.env?.DEFAULT_LOG_LEVEL||"info",Mr=()=>({colorize:!0,translateTime:"yyyy-mm-dd HH:MM:ss",ignore:"pid,hostname",levelColors:{60:"red",50:"red",40:"yellow",30:"blue",29:"green",28:"cyan",27:"greenBright",20:"magenta",10:"grey","*":"white"},customPrettifiers:{level:n=>{let e;typeof n=="object"&&n!==null?e=n.level||n.value:e=n;let t={10:"TRACE",20:"DEBUG",27:"SUCCESS",28:"PROGRESS",29:"LOG",30:"INFO",40:"WARN",50:"ERROR",60:"FATAL"};return typeof e=="number"?t[e]||`LEVEL${e}`:e==null?"UNKNOWN":String(e).toUpperCase()},msg:n=>n.replace(/ERROR \([^)]+\):/g,"ERROR:")},messageFormat:"{msg}"}),ri=async()=>rt?void 0:(await import("pino-pretty")).default(Mr()),nt={level:ti,customLevels:Zs,hooks:{logMethod(n,e){let[t,...r]=n,s=i=>({message:`(${i.name}) ${i.message}`,stack:i.stack?.split(`
|
|
10
|
-
`).map(o=>o.trim())});if(typeof t=="object")if(t instanceof Error)e.apply(this,[{error:s(t)}]);else{let o=r.map(a=>typeof a=="string"?a:JSON.stringify(a)).join(" ");e.apply(this,[t,o])}else{let i={},o=[t,...r].map(
|
|
10
|
+
`).map(o=>o.trim())});if(typeof t=="object")if(t instanceof Error)e.apply(this,[{error:s(t)}]);else{let o=r.map(a=>typeof a=="string"?a:JSON.stringify(a)).join(" ");e.apply(this,[t,o])}else{let i={},o=[t,...r].map(c=>c instanceof Error?s(c):c),a=o.filter(c=>typeof c=="string").join(" "),u=o.filter(c=>typeof c=="object");Object.assign(i,...u),e.apply(this,[i,a])}}}},T=tt(nt);if(typeof process<"u"){let n=null;if(!rt)try{let e=v("pino-pretty");n=e.default?e.default(Mr()):null}catch{ri().then(t=>{let r=new J(t);T=tt(nt,r),T[Symbol.for("pino-destination")]=r,T.clear=()=>{let s=T[Symbol.for("pino-destination")];s instanceof J&&s.clear()}})}if(n!==null||rt){let e=new J(n);T=tt(nt,e),T[Symbol.for("pino-destination")]=e,T.clear=()=>{let t=T[Symbol.for("pino-destination")];t instanceof J&&t.clear()}}}var h=T,G=T;function Pr(n){return n.replace(/(?<!{){{(?![{#\/!>])([\s\S]*?)}}/g,(e,t)=>t.trim()==="else"?`{{${t}}}`:`{{{${t}}}}`)}var Ur=({state:n,template:e})=>{let t=typeof e=="function"?e({state:n}):e,r=Ir.compile(Pr(t));return Lr(r(n),10)},Tl=({state:n,template:e})=>{let t=typeof e=="function"?e({state:n}):e,r=Ir.compile(Pr(t)),o=Object.keys(n).filter(u=>!["text","values","data"].includes(u)).reduce((u,c)=>(u[c]=n[c],u),{});return Lr(r({...o,...n.values}),10)},Al=(n,e)=>e.length>0?`${n&&`${n}
|
|
11
11
|
`}${e}
|
|
12
|
-
`:"",Lr=(n,e)=>{let t=Array.from({length:e},()=>ii({dictionaries:[si]})),r=n;for(let s=0;s<t.length;s++)r=r.replaceAll(`{{name${s+1}}}`,t[s]);return r},yl=({messages:n,entities:e,conversationHeader:t=!0})=>{let r={};return n.forEach(o=>{o.roomId&&(r[o.roomId]||(r[o.roomId]=[]),r[o.roomId].push(o))}),Object.values(r).forEach(o=>{o.sort((a,
|
|
12
|
+
`:"",Lr=(n,e)=>{let t=Array.from({length:e},()=>ii({dictionaries:[si]})),r=n;for(let s=0;s<t.length;s++)r=r.replaceAll(`{{name${s+1}}}`,t[s]);return r},yl=({messages:n,entities:e,conversationHeader:t=!0})=>{let r={};return n.forEach(o=>{o.roomId&&(r[o.roomId]||(r[o.roomId]=[]),r[o.roomId].push(o))}),Object.values(r).forEach(o=>{o.sort((a,u)=>a.createdAt-u.createdAt)}),Object.entries(r).sort(([,o],[,a])=>a[a.length-1].createdAt-o[o.length-1].createdAt).map(([o,a])=>{let u=a.filter(d=>d.entityId).map(d=>{let l=e.find(p=>p.id===d.entityId),m=l?.names[0]||"Unknown User",E=l?.names[0]||"unknown";return`Name: ${m} (@${E} EntityID:${d.entityId})
|
|
13
13
|
MessageID: ${d.id}${d.content.inReplyTo?`
|
|
14
14
|
In reply to: ${d.content.inReplyTo}`:""}
|
|
15
15
|
Source: ${d.content.source}
|
|
16
16
|
Date: ${Or(d.createdAt)}
|
|
17
17
|
Text:
|
|
18
18
|
${d.content.text}`});return`${t?`Conversation: ${o.slice(-5)}
|
|
19
|
-
`:""}${
|
|
19
|
+
`:""}${u.join(`
|
|
20
20
|
|
|
21
21
|
`)}`}).join(`
|
|
22
22
|
|
|
23
|
-
`)},Rl=({messages:n,entities:e})=>n.reverse().filter(r=>r.entityId).map(r=>{let s=r.content.text,i=r.content.actions,o=r.content.thought,a=e.find(S=>S.id===r.entityId)?.names[0]||"Unknown User",
|
|
23
|
+
`)},Rl=({messages:n,entities:e})=>n.reverse().filter(r=>r.entityId).map(r=>{let s=r.content.text,i=r.content.actions,o=r.content.thought,a=e.find(S=>S.id===r.entityId)?.names[0]||"Unknown User",u=r.content.attachments,c=u&&u.length>0?` (Attachments: ${u.map(S=>`[${S.id} - ${S.title} (${S.url})]`).join(", ")})`:null,d=new Date(r.createdAt),l=d.getHours().toString().padStart(2,"0"),m=d.getMinutes().toString().padStart(2,"0"),E=`${l}:${m}`,p=Or(r.createdAt),g=o?`(${a}'s internal thought: ${o})`:null,A=`${E} (${p}) [${r.entityId}]`,R=s?`${A} ${a}: ${s}`:null,O=i&&i.length>0?`${R?"":A} (${a}'s actions: ${i.join(", ")})`:null;return[R,g,O,c].filter(Boolean).join(`
|
|
24
24
|
`)}).join(`
|
|
25
25
|
`),Or=n=>{let t=new Date().getTime()-n,r=Math.abs(t),s=Math.floor(r/1e3),i=Math.floor(s/60),o=Math.floor(i/60),a=Math.floor(o/24);return r<6e4?"just now":i<60?`${i} minute${i!==1?"s":""} ago`:o<24?`${o} hour${o!==1?"s":""} ago`:`${a} day${a!==1?"s":""} ago`},oi=/```json\n([\s\S]*?)\n```/,Ml=`<task>Decide on behalf of {{agentName}} whether they should respond to the message, ignore it or stop the conversation.</task>
|
|
26
26
|
|
|
@@ -118,8 +118,7 @@ Your output should be formatted in XML like this:
|
|
|
118
118
|
The "post" field should be the post you want to send. Do not including any thinking or internal reflection in the "post" field.
|
|
119
119
|
The "imagePrompt" field is optional and should be a prompt for an image that is relevant to the post. It should be a single sentence that captures the essence of the post. ONLY USE THIS FIELD if it makes sense that the post would benefit from an image.
|
|
120
120
|
The "thought" field should be a short description of what the agent is thinking about before responding, inlcuding a brief justification for the response. Includate an explanation how the post is relevant to the topic but unique and different than other posts.
|
|
121
|
-
Your reponse should ONLY contain the XML block.`,Pl="Respond with only a YES or a NO.";function Ul(n){if(!n)return null;let e=n.match(/<(\w+)>([\s\S]*?)<\/\1>/);if(!e)return G.warn("Could not find XML block in text"),null;let t=e[2],r={},s=/<([\w-]+)>([\s\S]*?)<\/([\w-]+)>/g,i;for(;(i=s.exec(t))!==null;)if(i[1]===i[3]){let o=i[1],a=i[2].replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&").replace(/"/g,'"').replace(/'/g,"'").trim();o==="actions"||o==="providers"||o==="evaluators"?r[o]=a?a.split(",").map(
|
|
122
|
-
`);for(let a of o){let c=a.trim();c==="[LIKE]"&&(e.like=!0),c==="[RETWEET]"&&(e.retweet=!0),c==="[QUOTE]"&&(e.quote=!0),c==="[REPLY]"&&(e.reply=!0)}return{actions:e}};function Ol(n,e){if(n.length<=e)return n;let t=n.lastIndexOf(".",e-1);if(t!==-1){let i=n.slice(0,t+1).trim();if(i.length>0)return i}let r=n.lastIndexOf(" ",e-1);if(r!==-1){let i=n.slice(0,r).trim();if(i.length>0)return`${i}...`}return`${n.slice(0,e-3).trim()}...`}async function Cr(n,e=512,t=20){G.debug("[splitChunks] Starting text split");let s=await new ni({chunkSize:Number(e),chunkOverlap:Number(t)}).splitText(n);return G.debug("[splitChunks] Split complete:",{numberOfChunks:s.length,averageChunkSize:s.reduce((i,o)=>i+o.length,0)/s.length}),s}async function bl(n,e,t){if(!n)throw new Error("Trim tokens received a null prompt");if(n.length<e/5)return n;if(e<=0)throw new Error("maxTokens must be positive");try{let r=await t.useModel(N.TEXT_TOKENIZER_ENCODE,{prompt:n});if(r.length<=e)return n;let s=r.slice(-e);return await t.useModel(N.TEXT_TOKENIZER_DECODE,{tokens:s})}catch(r){return G.error("Error in trimTokens:",r),n.slice(-e*4)}}var ai=`# Task: Resolve Entity Name
|
|
121
|
+
Your reponse should ONLY contain the XML block.`,Pl="Respond with only a YES or a NO.";function Ul(n){if(!n)return null;let e=n.match(/<(\w+)>([\s\S]*?)<\/\1>/);if(!e)return G.warn("Could not find XML block in text"),null;let t=e[2],r={},s=/<([\w-]+)>([\s\S]*?)<\/([\w-]+)>/g,i;for(;(i=s.exec(t))!==null;)if(i[1]===i[3]){let o=i[1],a=i[2].replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&").replace(/"/g,'"').replace(/'/g,"'").trim();o==="actions"||o==="providers"||o==="evaluators"?r[o]=a?a.split(",").map(u=>u.trim()):[]:o==="simple"?r[o]=a.toLowerCase()==="true":r[o]=a}else G.warn(`Mismatched XML tags found: <${i[1]}> and </${i[3]}>`);return Object.keys(r).length===0?(G.warn("No key-value pairs extracted from XML content"),null):r}function br(n){let e=null,t=n.match(oi);try{t?e=JSON.parse(vr(t[1].trim())):e=JSON.parse(vr(n.trim()))}catch{return null}return e&&typeof e=="object"&&!Array.isArray(e)?e:null}var vr=n=>(n=n.replace(/\{\s+/,"{").replace(/\s+\}/,"}").trim(),n=n.replace(/("[\w\d_-]+")\s*: \s*(?!"|\[)([\s\S]+?)(?=(,\s*"|\}$))/g,'$1: "$2"'),n=n.replace(/"([^"]+)"\s*:\s*'([^']*)'/g,(e,t,r)=>`"${t}": "${r}"`),n=n.replace(/("[\w\d_-]+")\s*:\s*([A-Za-z_]+)(?!["\w])/g,'$1: "$2"'),n);function Ll(n,e){if(n.length<=e)return n;let t=n.lastIndexOf(".",e-1);if(t!==-1){let i=n.slice(0,t+1).trim();if(i.length>0)return i}let r=n.lastIndexOf(" ",e-1);if(r!==-1){let i=n.slice(0,r).trim();if(i.length>0)return`${i}...`}return`${n.slice(0,e-3).trim()}...`}async function Cr(n,e=512,t=20){G.debug("[splitChunks] Starting text split");let s=await new ni({chunkSize:Number(e),chunkOverlap:Number(t)}).splitText(n);return G.debug("[splitChunks] Split complete:",{numberOfChunks:s.length,averageChunkSize:s.reduce((i,o)=>i+o.length,0)/s.length}),s}async function Ol(n,e,t){if(!n)throw new Error("Trim tokens received a null prompt");if(n.length<e/5)return n;if(e<=0)throw new Error("maxTokens must be positive");try{let r=await t.useModel(N.TEXT_TOKENIZER_ENCODE,{prompt:n});if(r.length<=e)return n;let s=r.slice(-e);return await t.useModel(N.TEXT_TOKENIZER_DECODE,{tokens:s})}catch(r){return G.error("Error in trimTokens:",r),n.slice(-e*4)}}var ai=`# Task: Resolve Entity Name
|
|
123
122
|
Message Sender: {{senderName}} (ID: {{senderId}})
|
|
124
123
|
Agent: {{agentName}} (ID: {{agentId}})
|
|
125
124
|
|
|
@@ -151,12 +150,12 @@ Return a JSON object with:
|
|
|
151
150
|
\`\`\`
|
|
152
151
|
|
|
153
152
|
Make sure to include the \`\`\`json\`\`\` tags around the JSON object.
|
|
154
|
-
`;async function ci(n,e,t,r,s){let i=[],o=await n.getMemories({tableName:"messages",roomId:r,count:20});for(let a of t){let
|
|
153
|
+
`;async function ci(n,e,t,r,s){let i=[],o=await n.getMemories({tableName:"messages",roomId:r,count:20});for(let a of t){let u=[],c=0,d=o.filter(E=>E.entityId===e&&E.content.inReplyTo===a.id||E.entityId===a.id&&E.content.inReplyTo===e);u.push(...d);let l=s.find(E=>E.sourceEntityId===e&&E.targetEntityId===a.id||E.targetEntityId===e&&E.sourceEntityId===a.id);l?.metadata?.interactions&&(c=l.metadata.interactions),c+=d.length;let m=[...new Set(u)];i.push({entity:a,interactions:m.slice(-5),count:Math.round(c)})}return i.sort((a,u)=>u.count-a.count)}async function xl(n,e,t){try{let r=t.data.room??await n.getRoom(e.roomId);if(!r)return T.warn("Room not found for entity search"),null;let s=r.worldId?await n.getWorld(r.worldId):null,i=await n.getEntitiesForRoom(r.id,!0),o=await Promise.all(i.map(async p=>{if(!p.components)return p;let g=s?.metadata?.roles||{};return p.components=p.components.filter(A=>{if(A.sourceEntityId===e.entityId)return!0;if(s&&A.sourceEntityId){let R=g[A.sourceEntityId];if(R==="OWNER"||R==="ADMIN")return!0}return A.sourceEntityId===n.agentId}),p})),a=await n.getRelationships({entityId:e.entityId}),u=await Promise.all(a.map(async p=>{let g=p.sourceEntityId===e.entityId?p.targetEntityId:p.sourceEntityId;return n.getEntityById(g)})),c=[...o,...u.filter(p=>p!==null)],d=await ci(n,e.entityId,c,r.id,a),l=Ur({state:{roomName:r.name||r.id,worldName:s?.name||"Unknown",entitiesInRoom:JSON.stringify(o,null,2),entityId:e.entityId,senderId:e.entityId},template:ai}),m=await n.useModel(N.TEXT_SMALL,{prompt:l,stopSequences:[]}),E=br(m);if(!E)return T.warn("Failed to parse entity resolution result"),null;if(E.type==="EXACT_MATCH"&&E.entityId){let p=await n.getEntityById(E.entityId);if(p){if(p.components){let g=s?.metadata?.roles||{};p.components=p.components.filter(A=>{if(A.sourceEntityId===e.entityId)return!0;if(s&&A.sourceEntityId){let R=g[A.sourceEntityId];if(R==="OWNER"||R==="ADMIN")return!0}return A.sourceEntityId===n.agentId})}return p}}if(E.matches?.[0]?.name){let p=E.matches[0].name.toLowerCase(),g=c.find(A=>A.names.some(R=>R.toLowerCase()===p)?!0:A.components?.some(R=>R.data.username?.toLowerCase()===p||R.data.handle?.toLowerCase()===p));if(g)if(E.type==="RELATIONSHIP_MATCH"){let A=d.find(R=>R.entity.id===g.id);if(A&&A.count>0)return g}else return g}return null}catch(r){return T.error("Error in findEntityByName:",r),null}}var B=(n,e)=>{if(e===n.agentId)return n.agentId;let t=`${e}:${n.agentId}`;return Le(t)};async function wl({runtime:n,roomId:e}){let[t,r]=await Promise.all([n.getRoom(e),n.getEntitiesForRoom(e,!0)]),s=new Map;for(let i of r){if(s.has(i.id))continue;let o={};for(let u of i.components||[])Object.assign(o,u.data);let a={};for(let[u,c]of Object.entries(o)){if(!a[u]){a[u]=c;continue}Array.isArray(a[u])&&Array.isArray(c)?a[u]=[...new Set([...a[u],...c])]:typeof a[u]=="object"&&typeof c=="object"&&(a[u]={...a[u],...c})}s.set(i.id,{id:i.id,name:i.metadata[t.source]?.name||i.names[0],names:i.names,data:JSON.stringify({...a,...i.metadata})})}return Array.from(s.values())}function kl({entities:n}){return n.map(t=>`"${t.names.join('" aka "')}"
|
|
155
154
|
ID: ${t.id}${t.metadata&&Object.keys(t.metadata).length>0?`
|
|
156
155
|
Data: ${JSON.stringify(t.metadata)}
|
|
157
156
|
`:`
|
|
158
157
|
`}`).join(`
|
|
159
|
-
`)}async function
|
|
158
|
+
`)}async function Wl(n,e,t){try{let r=B(n,t),s=await n.getWorld(r);return!s||!s.metadata?.roles?"NONE":s.metadata.roles[e]||s.metadata.roles[e]?s.metadata.roles[e]:"NONE"}catch(r){return T.error(`Error getting user role: ${r}`),"NONE"}}async function ql(n,e){try{if(!e)return T.error("User ID is required to find server"),null;let t=await n.getAllWorlds();if(!t||t.length===0)return T.info("No worlds found for this agent"),null;let r=[];for(let s of t)s.metadata?.ownership?.ownerId===e&&r.push(s);return r.length?r:null}catch(t){return T.error(`Error finding server for owner: ${t}`),null}}import{SpanStatusCode as L,context as Ze,trace as Od}from"@opentelemetry/api";import{v4 as bd}from"uuid";import{diag as pd,DiagConsoleLogger as hd,DiagLogLevel as _d,metrics as xs,trace as Sd}from"@opentelemetry/api";import{diag as Gr}from"@opentelemetry/api";var ui="service.name";var di="telemetry.sdk.name",li="telemetry.sdk.language",mi="telemetry.sdk.version";var Nr=ui;var st=di,it=li,ot=mi;var Dr="1.26.0";var Ei="process.runtime.name";var pi="telemetry.sdk.name",hi="telemetry.sdk.language",_i="telemetry.sdk.version";var xr=Ei;var wr=pi,kr=hi,Vr=_i;var Si="nodejs";var Fr=Si;var Z,j=(Z={},Z[wr]="opentelemetry",Z[xr]="node",Z[kr]=Fr,Z[Vr]=Dr,Z);function Oe(){return"unknown_service:"+process.argv0}var K=function(){return K=Object.assign||function(n){for(var e,t=1,r=arguments.length;t<r;t++){e=arguments[t];for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&(n[s]=e[s])}return n},K.apply(this,arguments)},vi=function(n,e,t,r){function s(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(d){try{c(r.next(d))}catch(l){o(l)}}function u(d){try{c(r.throw(d))}catch(l){o(l)}}function c(d){d.done?i(d.value):s(d.value).then(a,u)}c((r=r.apply(n,e||[])).next())})},Ii=function(n,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},r,s,i,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(c){return function(d){return u([c,d])}}function u(c){if(r)throw new TypeError("Generator is already executing.");for(;t;)try{if(r=1,s&&(i=c[0]&2?s.return:c[0]?s.throw||((i=s.return)&&i.call(s),0):s.next)&&!(i=i.call(s,c[1])).done)return i;switch(s=0,i&&(c=[c[0]&2,i.value]),c[0]){case 0:case 1:i=c;break;case 4:return t.label++,{value:c[1],done:!1};case 5:t.label++,s=c[1],c=[0];continue;case 7:c=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(c[0]===6||c[0]===2)){t=0;continue}if(c[0]===3&&(!i||c[1]>i[0]&&c[1]<i[3])){t.label=c[1];break}if(c[0]===6&&t.label<i[1]){t.label=i[1],i=c;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(c);break}i[2]&&t.ops.pop(),t.trys.pop();continue}c=e.call(n,t)}catch(d){c=[6,d],s=0}finally{r=i=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}},Pi=function(n,e){var t=typeof Symbol=="function"&&n[Symbol.iterator];if(!t)return n;var r=t.call(n),s,i=[],o;try{for(;(e===void 0||e-- >0)&&!(s=r.next()).done;)i.push(s.value)}catch(a){o={error:a}}finally{try{s&&!s.done&&(t=r.return)&&t.call(r)}finally{if(o)throw o.error}}return i},at=function(){function n(e,t){var r=this,s;this._attributes=e,this.asyncAttributesPending=t!=null,this._syncAttributes=(s=this._attributes)!==null&&s!==void 0?s:{},this._asyncAttributesPromise=t?.then(function(i){return r._attributes=Object.assign({},r._attributes,i),r.asyncAttributesPending=!1,i},function(i){return Gr.debug("a resource's async attributes promise rejected: %s",i),r.asyncAttributesPending=!1,{}})}return n.empty=function(){return n.EMPTY},n.default=function(){var e;return new n((e={},e[Nr]=Oe(),e[it]=j[it],e[st]=j[st],e[ot]=j[ot],e))},Object.defineProperty(n.prototype,"attributes",{get:function(){var e;return this.asyncAttributesPending&&Gr.error("Accessing resource attributes before async attributes settled"),(e=this._attributes)!==null&&e!==void 0?e:{}},enumerable:!1,configurable:!0}),n.prototype.waitForAsyncAttributes=function(){return vi(this,void 0,void 0,function(){return Ii(this,function(e){switch(e.label){case 0:return this.asyncAttributesPending?[4,this._asyncAttributesPromise]:[3,2];case 1:e.sent(),e.label=2;case 2:return[2]}})})},n.prototype.merge=function(e){var t=this,r;if(!e)return this;var s=K(K({},this._syncAttributes),(r=e._syncAttributes)!==null&&r!==void 0?r:e.attributes);if(!this._asyncAttributesPromise&&!e._asyncAttributesPromise)return new n(s);var i=Promise.all([this._asyncAttributesPromise,e._asyncAttributesPromise]).then(function(o){var a,u=Pi(o,2),c=u[0],d=u[1];return K(K(K(K({},t._syncAttributes),c),(a=e._syncAttributes)!==null&&a!==void 0?a:e.attributes),d)});return new n(s,i)},n.EMPTY=new n({}),n}();function Br(n){let e={},t=n.length;for(let r=0;r<t;r++){let s=n[r];s&&(e[String(s).toUpperCase().replace(/[-.]/g,"_")]=s)}return e}var Ui="cloud.provider",Li="cloud.account.id",Oi="cloud.region",bi="cloud.availability_zone",Ci="cloud.platform",Ni="aws.ecs.container.arn",Di="aws.ecs.cluster.arn",xi="aws.ecs.launchtype",wi="aws.ecs.task.arn",ki="aws.ecs.task.family",Vi="aws.ecs.task.revision",Fi="aws.eks.cluster.arn",Gi="aws.log.group.names",Bi="aws.log.group.arns",Wi="aws.log.stream.names",qi="aws.log.stream.arns",Ki="container.name",Hi="container.id",$i="container.runtime",Yi="container.image.name",ji="container.image.tag",zi="deployment.environment",Qi="device.id",Xi="device.model.identifier",Ji="device.model.name",Zi="faas.name",eo="faas.id",to="faas.version",ro="faas.instance",no="faas.max_memory",so="host.id",io="host.name",oo="host.type",ao="host.arch",co="host.image.name",uo="host.image.id",lo="host.image.version",mo="k8s.cluster.name",Eo="k8s.node.name",po="k8s.node.uid",ho="k8s.namespace.name",_o="k8s.pod.uid",So="k8s.pod.name",go="k8s.container.name",fo="k8s.replicaset.uid",To="k8s.replicaset.name",Ao="k8s.deployment.uid",yo="k8s.deployment.name",Ro="k8s.statefulset.uid",Mo="k8s.statefulset.name",vo="k8s.daemonset.uid",Io="k8s.daemonset.name",Po="k8s.job.uid",Uo="k8s.job.name",Lo="k8s.cronjob.uid",Oo="k8s.cronjob.name",bo="os.type",Co="os.description",No="os.name",Do="os.version",xo="process.pid",wo="process.executable.name",ko="process.executable.path",Vo="process.command",Fo="process.command_line",Go="process.command_args",Bo="process.owner",Wo="process.runtime.name",qo="process.runtime.version",Ko="process.runtime.description",Ho="service.name",$o="service.namespace",Yo="service.instance.id",jo="service.version",zo="telemetry.sdk.name",Qo="telemetry.sdk.language",Xo="telemetry.sdk.version",Jo="telemetry.auto.version",Zo="webengine.name",ea="webengine.version",ta="webengine.description";var Wr=Br([Ui,Li,Oi,bi,Ci,Ni,Di,xi,wi,ki,Vi,Fi,Gi,Bi,Wi,qi,Ki,Hi,$i,Yi,ji,zi,Qi,Xi,Ji,Zi,eo,to,ro,no,so,io,oo,ao,co,uo,lo,mo,Eo,po,ho,_o,So,go,fo,To,Ao,yo,Ro,Mo,vo,Io,Po,Uo,Lo,Oo,bo,Co,No,Do,xo,wo,ko,Vo,Fo,Go,Bo,Wo,qo,Ko,Ho,$o,Yo,jo,zo,Qo,Xo,Jo,Zo,ea,ta]);import{NodeTracerProvider as gd}from"@opentelemetry/sdk-trace-node";import{MeterProvider as fd}from"@opentelemetry/sdk-metrics";import{trace as ra,metrics as na}from"@opentelemetry/api";var le=class{emit(e){}},qr=new le;var ct=class{getLogger(e,t,r){return new le}},be=new ct;var Ce=class{constructor(e,t,r,s){this._provider=e,this.name=t,this.version=r,this.options=s}emit(e){this._getLogger().emit(e)}_getLogger(){if(this._delegate)return this._delegate;let e=this._provider.getDelegateLogger(this.name,this.version,this.options);return e?(this._delegate=e,this._delegate):qr}};var me=class{getLogger(e,t,r){var s;return(s=this.getDelegateLogger(e,t,r))!==null&&s!==void 0?s:new Ce(this,e,t,r)}getDelegate(){var e;return(e=this._delegate)!==null&&e!==void 0?e:be}setDelegate(e){this._delegate=e}getDelegateLogger(e,t,r){var s;return(s=this._delegate)===null||s===void 0?void 0:s.getLogger(e,t,r)}};var Ne=typeof globalThis=="object"?globalThis:global;var Ee=Symbol.for("io.opentelemetry.js.api.logs"),ee=Ne;function Kr(n,e,t){return r=>r===n?e:t}var ut=1;var De=class n{constructor(){this._proxyLoggerProvider=new me}static getInstance(){return this._instance||(this._instance=new n),this._instance}setGlobalLoggerProvider(e){return ee[Ee]?this.getLoggerProvider():(ee[Ee]=Kr(ut,e,be),this._proxyLoggerProvider.setDelegate(e),e)}getLoggerProvider(){var e,t;return(t=(e=ee[Ee])===null||e===void 0?void 0:e.call(ee,ut))!==null&&t!==void 0?t:this._proxyLoggerProvider}getLogger(e,t,r){return this.getLoggerProvider().getLogger(e,t,r)}disable(){delete ee[Ee],this._proxyLoggerProvider=new me}};var Hr=De.getInstance();function $r(n,e,t,r){for(let s=0,i=n.length;s<i;s++){let o=n[s];e&&o.setTracerProvider(e),t&&o.setMeterProvider(t),r&&o.setLoggerProvider&&o.setLoggerProvider(r),o.getConfig().enabled||o.enable()}}function Yr(n){n.forEach(e=>e.disable())}function dt(n){let e=n.tracerProvider||ra.getTracerProvider(),t=n.meterProvider||na.getMeterProvider(),r=n.loggerProvider||Hr.getLoggerProvider(),s=n.instrumentations?.flat()??[];return $r(s,e,t,r),()=>{Yr(s)}}import{PgInstrumentation as Td}from"@opentelemetry/instrumentation-pg";var ws,Ad="eliza-agent",pr=class{pgClient=null;isInitialized=!1;isConnected=!1;constructor(e){try{ws=dr()}catch{h.error("\u274C Failed to dynamically require 'pg'. Are you running in a non-Node environment?");return}if(h.info("\u{1F504} Initializing PostgreSQL Span Processor with provided URL."),!e){h.error("\u274C Cannot initialize PostgreSQL Span Processor: Connection string is empty.");return}try{this.pgClient=new ws.Client({connectionString:e}),h.info("\u{1F504} Connecting to PostgreSQL..."),this.pgClient.connect(t=>{if(t){h.error(`\u274C Failed to connect to PostgreSQL in constructor: ${t}`),this.pgClient=null;return}this.isConnected=!0,h.info("\u2705 Connected to PostgreSQL database"),this.pgClient.query(`
|
|
160
159
|
CREATE TABLE IF NOT EXISTS traces (
|
|
161
160
|
id SERIAL PRIMARY KEY,
|
|
162
161
|
trace_id TEXT NOT NULL,
|
|
@@ -190,7 +189,7 @@ Data: ${JSON.stringify(t.metadata)}
|
|
|
190
189
|
CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, 0,
|
|
191
190
|
'test', 'test', 'test', 'test'
|
|
192
191
|
) ON CONFLICT (trace_id, span_id) DO NOTHING;
|
|
193
|
-
`,(a,
|
|
192
|
+
`,(a,u)=>{a?h.error(`\u274C Failed to insert test record: ${a}`):h.info("\u2705 Test record inserted or verified.")})})})}catch(t){h.error(`\u274C Failed to initialize PostgreSQL client: ${t}`),t instanceof Error&&t.stack&&h.error(`Stack trace: ${t.stack}`),this.pgClient=null}}onStart(e){h.debug("\u{1F7E2} Span started:",e.name)}onEnd(e){if(!this.pgClient||!this.isConnected||!this.isInitialized){h.warn(`\u26A0\uFE0F Cannot record span ${e.name} - PostgreSQL processor is not fully initialized (Connected: ${this.isConnected}, Initialized: ${this.isInitialized})`);return}h.debug(`\u{1F504} Processing span: ${e.name}`);let t=e.spanContext(),r=e.startTime[0]*1e3+e.startTime[1]/1e6,s=e.endTime[0]*1e3+e.endTime[1]/1e6,i=Math.floor(s-r),o=e.attributes||{},a=e.resource?.attributes||{},u=d=>{if(typeof d!="string")return null;let l=d.trim();return l.length>0?l:null},c={trace_id:t.traceId,span_id:t.spanId,parent_span_id:e.parentSpanId||null,trace_state:t.traceState?.toString()||null,span_name:e.name,span_kind:e.kind,start_time:new Date(r).toISOString(),end_time:new Date(s).toISOString(),duration_ms:i,status_code:e.status.code,status_message:e.status.message||null,attributes:o,events:e.events||[],links:e.links||[],resource:a,agent_id:u(o["agent.id"])||u(o.agentId)||u(a["service.instance.id"])||"unknown",session_id:u(o["session.id"])||u(o.sessionId)||u(a["session.id"])||"unknown",environment:u(o.environment)||u(a["deployment.environment"])||process.env.NODE_ENV||"development",room_id:u(o["room.id"])||u(o.roomId)||"unknown"};h.debug(`\u{1F504} Inserting span into PostgreSQL: ${e.name}`),this.insertTrace(c)}async insertTrace(e){if(!this.pgClient||!this.isConnected)return;h.debug(`\u{1F504} Begin insertTrace for span: ${e.span_name}`);let t="traces",r=`
|
|
194
193
|
INSERT INTO ${t} (
|
|
195
194
|
trace_id,
|
|
196
195
|
span_id,
|
|
@@ -215,5 +214,5 @@ Data: ${JSON.stringify(t.metadata)}
|
|
|
215
214
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19)
|
|
216
215
|
ON CONFLICT (trace_id, span_id) DO NOTHING
|
|
217
216
|
RETURNING id;
|
|
218
|
-
`,s=[e.trace_id,e.span_id,e.parent_span_id,e.trace_state,e.span_name,e.span_kind,e.start_time,e.end_time,e.duration_ms,e.status_code,e.status_message,JSON.stringify(e.attributes||{}),JSON.stringify(e.events||[]),JSON.stringify(e.links||[]),JSON.stringify(e.resource||{}),e.agent_id,e.session_id,e.environment,e.room_id];try{h.debug(`Executing direct insert for span: ${e.span_name}`),h.debug(`Span trace_id: ${e.trace_id}, span_id: ${e.span_id}`);let i=await this.pgClient.query(r,s);if(i.rows&&i.rows.length>0){let o=i.rows[0].id;h.info(`\u2705 Span inserted with ID ${o}: ${e.span_name}`)}else i.rowCount>0?h.info(`\u2705 Span inserted (rowCount=${i.rowCount}): ${e.span_name}`):h.warn(`\u26A0\uFE0F No row inserted for span (likely conflict): ${e.span_name}`);try{let o=`SELECT id FROM ${t} WHERE trace_id = $1 AND span_id = $2`,a=await this.pgClient.query(o,[e.trace_id,e.span_id]);a.rows.length>0?h.info(`\u2705 Verified span in database with ID ${a.rows[0].id}`):h.warn("\u26A0\uFE0F Verification failed: Span not found in database after insert")}catch(o){h.error(`\u274C Error verifying span insertion: ${o}`)}}catch(i){h.error("\u274C Error inserting span into PostgreSQL DB:",i),i instanceof Error&&(h.error(`Error message: ${i.message}`),h.error(`Error stack: ${i.stack}`)),h.error(`Failed span data: ${JSON.stringify({span_name:e.span_name,trace_id:e.trace_id,span_id:e.span_id,agent_id:e.agent_id,session_id:e.session_id,room_id:e.room_id})}`)}}shutdown(){return this.pgClient&&this.isConnected&&(this.pgClient.end(),this.isConnected=!1,h.info("PostgreSQL database connection closed")),Promise.resolve()}forceFlush(){return Promise.resolve()}},Xe=class n extends Pe{name="INSTRUMENTATION";capabilityDescription="Provides OpenTelemetry tracing and metrics capabilities.";instrumentationConfig;resource;tracerProvider=null;meterProvider=null;postgresSpanProcessor=null;isShutdown=!1;constructor(e){super();let t=e?.enabled||!1;this.instrumentationConfig={serviceName:e?.serviceName||process.env.OTEL_SERVICE_NAME||Ad,enabled:t},this.resource=new at({[Wr.SERVICE_NAME]:this.instrumentationConfig.serviceName}),this.isEnabled()?(this.initializeProviders(),h.info(`\u{1F4CA} Instrumentation Service configured as enabled for '${this.instrumentationConfig.serviceName}'.`)):h.info("\u{1F4CA} Instrumentation Service configured as disabled.")}initializeProviders(){if(!this.isEnabled())return;this.tracerProvider=new gd({resource:this.resource});let e=process.env.POSTGRES_URL_INSTRUMENTATION;if(!e)h.error("Cannot initialize PostgreSQL Span Processor: POSTGRES_URL_INSTRUMENTATION is not set.");else try{this.postgresSpanProcessor=new pr(e),this.postgresSpanProcessor&&this.postgresSpanProcessor.pgClient?(this.tracerProvider.addSpanProcessor(this.postgresSpanProcessor),h.info("\u{1F4CA} Added PostgreSQL span processor for telemetry data storage.")):h.error("Failed to add PostgreSQL span processor likely due to initialization errors.")}catch(t){h.error("Error creating PostgreSQL Span Processor instance:",t)}this.tracerProvider.register();try{h.info("Attempting to register PostgreSQL instrumentation..."),dt({tracerProvider:this.tracerProvider,instrumentations:[new Td({enhancedDatabaseReporting:!0})]}),h.info("\u2705 Successfully registered OpenTelemetry instrumentations (pg).")}catch(t){h.error("\u274C Failed to register instrumentations:",t)}this.meterProvider=new fd({resource:this.resource}),h.warn("Metrics export is currently disabled."),xs.setGlobalMeterProvider(this.meterProvider)}isEnabled(){return!!this.instrumentationConfig.enabled&&!this.isShutdown}getTracer(e,t){return!this.isEnabled()||!this.tracerProvider?Sd.getTracer(e||this.instrumentationConfig.serviceName,t):this.tracerProvider.getTracer(e||this.instrumentationConfig.serviceName,t)}getMeter(e,t){return xs.getMeter(e||this.instrumentationConfig.serviceName,t)}async flush(){if(!(!this.isEnabled()||this.isShutdown)){h.debug("\u{1F4CA} Flushing OpenTelemetry providers...");try{(await Promise.allSettled([this.tracerProvider?.forceFlush(),this.meterProvider?.forceFlush()])).forEach((t,r)=>{if(t.status==="rejected"){let s=r===0?"Tracer":"Meter";h.error(`Error flushing OpenTelemetry ${s} provider:`,t.reason)}}),h.debug("\u{1F4CA} OpenTelemetry providers flush attempt complete.")}catch(e){h.error("Unexpected error during instrumentation flush: ",e)}}}async stop(){if(!(!this.isEnabled()||this.isShutdown)){this.isShutdown=!0,h.info("\u{1F4CA} Shutting down Instrumentation Service...");try{(await Promise.allSettled([this.tracerProvider?.shutdown(),this.meterProvider?.shutdown()])).forEach((t,r)=>{if(t.status==="rejected"){let s=r===0?"Tracer":"Meter";h.error(`Error shutting down OpenTelemetry ${s} provider:`,t.reason)}}),h.info("\u{1F4CA} Instrumentation Service shutdown attempt complete.")}catch(e){h.error("Unexpected error during instrumentation shutdown: ",e)}}}static async start(e,t){return pd.setLogger(new hd,_d.DEBUG),new n(t)}};var q=n=>{switch(n){case 97:case 101:case 105:case 111:case 117:case 121:return!0;default:return!1}},yd=n=>{switch(n){case 97:case 101:case 105:case 111:case 117:case 121:case 119:case 120:case 89:return!0;default:return!1}},Rd=n=>{switch(n){case 99:case 100:case 101:case 103:case 104:case 107:case 109:case 110:case 114:case 116:return!0;default:return!1}},Md=n=>{switch(n){case 98:case 100:case 102:case 103:case 109:case 110:case 112:case 114:case 116:return!0;default:return!1}},ks=(n,e)=>e>=2&&q(n[e-2])&&(e===2&&!q(n[e-1])||e>=3&&!q(n[e-3])&&!yd(n[e-1])),vd=n=>{if(n.length<3)return n;if(n.length<=6)switch(n){case"ski":return"ski";case"skies":return"sky";case"dying":return"die";case"lying":return"lie";case"tying":return"tie";case"idly":return"idl";case"gently":return"gentl";case"ugly":return"ugli";case"early":return"earli";case"only":return"onli";case"singly":return"singl";case"sky":case"news":case"howe":case"atlas":case"cosmos":case"bias":case"andes":return n}for(var e=n.charCodeAt(0)===39?1:0,t=n.length-e,r=new Array(t),s=!1,i=0;i<t;++i){var o=n.charCodeAt(i+e);if(o===121&&(i===0||q(r[i-1]))){s=!0,r[i]=89;continue}r[i]=o}r[t-1]===39&&--t,t>=2&&r[t-2]===39&&r[t-1]===115&&(t-=2);for(var a=0;a<t&&!q(r[a]);)++a;a<t&&++a;var c=a;if(t>=5&&(r[0]===103&&r[1]===101&&r[2]===110&&r[3]===101&&r[4]===114||r[0]===97&&r[1]===114&&r[2]===115&&r[3]===101&&r[4]===110))c=5;else if(t>=6&&r[0]===99&&r[1]===111&&r[2]===109&&r[3]===109&&r[4]===117&&r[5]===110)c=6;else{for(;c<t&&q(r[c]);)++c;c<t&&++c}for(var u=c,d=!1;u<t&&!q(r[u]);)++u;for(;u<t&&q(r[u]);)++u;if(u<t&&++u,t>=3&&(r[t-1]===115?t>=4&&r[t-2]===101&&r[t-3]===115&&r[t-4]===115?t-=2:r[t-2]===101&&r[t-3]===105?t-=t>=5?2:1:r[t-2]!==117&&r[t-2]!==115&&a<t-1&&(t-=1):r[t-1]===100&&r[t-2]===101&&r[t-3]===105&&(t-=t>=5?2:1)),t===6&&(r[0]===105&&r[1]===110&&r[2]===110&&r[3]===105&&r[4]===110&&r[5]===103||r[0]===111&&r[1]===117&&r[2]===116&&r[3]===105&&r[4]===110&&r[5]===103||r[0]===101&&r[1]===120&&r[2]===99&&r[3]===101&&r[4]===101&&r[5]===100)||t===7&&(r[0]===99&&r[1]===97&&r[2]===110&&r[3]===110&&r[4]===105&&r[5]===110&&r[6]===103||r[0]===104&&r[1]===101&&r[2]===114&&r[3]===114&&r[4]===105&&r[5]===110&&r[6]===103||r[0]===101&&r[1]===97&&r[2]===114&&r[3]===114&&r[4]===105&&r[5]===110&&r[6]===103||r[0]===112&&r[1]===114&&r[2]===111&&r[3]===99&&r[4]===101&&r[5]===101&&r[6]===100||r[0]===115&&r[1]===117&&r[2]===99&&r[3]===99&&r[4]===101&&r[5]===101&&r[6]===100)){for(var l="",i=0;i<t;++i)l+=String.fromCharCode(r[i]);return l}var m=t>=2&&r[t-1]===121&&r[t-2]===108?t-2:t;if(m>=3&&(r[m-3]===101&&r[m-2]===101&&r[m-1]===100?m>=c+3&&(t=m-1):(r[m-2]===101&&r[m-1]===100?m-=2:r[m-3]===105&&r[m-2]===110&&r[m-1]===103?m-=3:m=-1,m>=0&&a<=m&&(t=m,t>=2&&(r[t-1]===116&&r[t-2]===97||r[t-1]===108&&r[t-2]===98||r[t-1]===122&&r[t-2]===105?(r[t]=101,++t):r[t-2]===r[t-1]&&Md(r[t-1])?--t:c>=t&&ks(r,t)&&(r[t]=101,++t))))),t>=3&&(r[t-1]===89||r[t-1]===121)&&!q(r[t-2])&&(r[t-1]=105),t>=c+2)switch(r[t-1]){case 108:t>=c+6&&r[t-2]===97&&r[t-3]===110&&r[t-4]===111&&r[t-5]===105&&r[t-6]===116&&(t>=7&&r[t-7]===97?t>=c+7&&(t-=4,r[t-1]=101):t-=2);break;case 110:t>=c+5&&r[t-2]===111&&r[t-3]===105&&r[t-4]===116&&r[t-5]===97&&(t>=7&&r[t-6]===122&&r[t-7]===105?t>=c+7&&(t-=4,r[t-1]=101):(t-=2,r[t-1]=101));break;case 114:t>=c+4&&(r[t-2]===101?r[t-3]===122&&r[t-4]===105&&--t:r[t-2]===111&&r[t-3]===116&&r[t-4]===97&&(--t,r[t-1]=101));break;case 115:t>=c+7&&r[t-2]===115&&r[t-3]===101&&r[t-4]===110&&(r[t-5]===108&&r[t-6]===117&&r[t-7]===102||r[t-5]===115&&r[t-6]===117&&r[t-7]===111||r[t-5]===101&&r[t-6]===118&&r[t-7]===105)&&(t-=4);break;case 109:t>=c+5&&r[t-2]===115&&r[t-3]===105&&r[t-4]===108&&r[t-5]===97&&(t-=3);break;case 105:r[t-2]===99?t>=c+4&&(r[t-4]===101||r[t-4]===97)&&r[t-3]===110&&(r[t-1]=101):r[t-2]===103?t>=c+3&&t>=4&&r[t-2]===103&&r[t-3]===111&&r[t-4]===108&&--t:r[t-2]===116?t>=c+5&&r[t-3]===105&&(r[t-4]===108?t>=6&&r[t-5]===105&&r[t-6]===98?t>=c+6&&(t-=3,r[t-2]=108,r[t-1]=101):r[t-4]===108&&r[t-5]===97&&(t-=3):r[t-4]===118&&r[t-5]===105&&(t-=2,r[t-1]=101)):r[t-2]===108&&t>=3&&(r[t-3]===98?t>=4&&r[t-4]===97?t>=c+4&&(r[t-1]=101):t>=c+3&&(r[t-1]=101):r[t-3]===108?t>=5&&r[t-4]===117&&r[t-5]===102?t>=c+5&&(t-=2):t>=c+4&&r[t-4]===97&&(t-=2):r[t-3]===115?t>=6&&r[t-4]===115&&r[t-5]===101&&r[t-6]===108?t>=c+6&&(t-=2):t>=c+5&&r[t-4]===117&&r[t-5]===111&&(t-=2):t>=5&&r[t-3]===116&&r[t-4]===110&&r[t-5]===101?t>=c+5&&(t-=2):Rd(r[t-3])&&(t-=2))}if(t>=c+3)switch(r[t-1]){case 108:r[t-3]===99?t>=c+4&&r[t-4]===105&&r[t-2]===97&&(t-=2):r[t-3]===102?r[t-2]===117&&(t-=3):r[t-3]===110&&t>=c+6&&r[t-2]===97&&r[t-4]===111&&r[t-5]===105&&r[t-6]===116&&(t>=7&&r[t-7]===97?t>=c+7&&(t-=4,r[t-1]=101):t-=2);break;case 101:r[t-2]===122?t>=c+5&&r[t-3]===105&&r[t-4]===108&&r[t-5]===97&&(t-=3):r[t-2]===116?t>=c+5&&r[t-3]===97&&r[t-4]===99&&r[t-5]===105&&(t-=3):r[t-2]===118&&t>=u+5&&r[t-3]===105&&r[t-4]===116&&r[t-5]===97&&(t-=5);break;case 105:t>=c+5&&r[t-2]===116&&r[t-3]===105&&r[t-4]===99&&r[t-5]===105&&(t-=3);break;case 115:t>=c+4&&r[t-2]===115&&r[t-3]===101&&r[t-4]===110&&(t-=4)}if(t>=u+2)switch(r[t-1]){case 110:t>=u+3&&r[t-2]===111&&r[t-3]===105&&(r[t-4]===115||r[t-4]===116)&&(t-=3);break;case 108:r[t-2]===97&&(t-=2);break;case 114:r[t-2]===101&&(t-=2);break;case 99:r[t-2]===105&&(t-=2);break;case 109:t>=u+3&&r[t-2]===115&&r[t-3]===105&&(t-=3);break;case 105:t>=u+3&&r[t-2]===116&&r[t-3]===105&&(t-=3);break;case 115:t>=u+3&&r[t-2]===117&&r[t-3]===111&&(t-=3);break;case 116:t>=u+3&&r[t-2]===110&&(r[t-3]===97?t-=3:r[t-3]===101&&(t>=4&&r[t-4]===109?t>=5&&r[t-5]===101?t>=u+5&&(t-=5):t>=u+4&&(t-=4):t-=3));break;case 101:r[t-2]===99?t>=u+4&&r[t-3]===110&&(r[t-4]===97||r[t-4]===101)&&(t-=4):r[t-2]===108?t>=u+4&&r[t-3]===98&&(r[t-4]===97||r[t-4]===105)&&(t-=4):r[t-2]===116?t>=u+3&&r[t-3]===97&&(t-=3):t>=u+3&&(r[t-2]===118||r[t-2]===122)&&r[t-3]===105&&(t-=3)}t>=c+1&&(t>=u+1&&r[t-1]===108&&r[t-2]===108||r[t-1]===101&&(t>=u+1||!ks(r,t-1)))&&--t;var E="";if(s)for(var i=0;i<t;++i)E+=String.fromCharCode(r[i]===89?121:r[i]);else for(var i=0;i<t;++i)E+=String.fromCharCode(r[i]);return E},Id={k1:1.2,b:.75,minLength:2,stopWords:new Set(["a","an","and","are","as","at","be","by","for","from","has","he","in","is","it","its","of","on","that","the","to","was","were","will","with"]),stemming:!1,stemWords:n=>n},hr=class n{stopWords;minLength;stemming;stemmingRules;static DEFAULT_OPTIONS={stopWords:new Set,minLength:2,stemming:!1,stemmingRules:[]};constructor(e={}){let t={...n.DEFAULT_OPTIONS,...e};this.stopWords=t.stopWords,this.minLength=t.minLength,this.stemming=t.stemming,this.stemmingRules=t.stemmingRules.map(r=>({...r,pattern:typeof r.pattern=="string"?new RegExp(r.pattern):r.pattern}))}tokenize(e,t=!1){if(!e)throw new Error("Input text cannot be null or empty");let r=Date.now(),s=e.split(/\s+/).filter(c=>c.length>0),o=this.cleanText(e).split(/\s+/).filter(c=>this.isValidToken(c)).map(c=>this.stemming?this.stemWord(c):c),a=t?{originalWordCount:s.length,stopWordsRemoved:s.length-o.length,stemmedWords:this.stemming?o.length:0,processingTimeMs:Date.now()-r}:{originalWordCount:0,stopWordsRemoved:0,stemmedWords:0,processingTimeMs:0};return{tokens:o,stats:a}}cleanText(e){return e.toLowerCase().normalize("NFKD").replace(/[\u0000-\u001F\u007F-\u009F\u200B-\u200D\uFEFF]/g,"").replace(/[\u0300-\u036f]/g,"").replace(/[\p{Emoji_Presentation}\p{Extended_Pictographic}]/gu,"").replace(/[™®©℠‼]/g,"").replace(/[\p{P}]/gu," ").replace(/[^a-z0-9\u3040-\u30FF\u3400-\u4DBF\u4E00-\u9FFF\uAC00-\uD7AF\s]/gu," ").replace(/\s+/g," ").trim()}isValidToken(e){let t=/^\d+$/.test(e);return(e.length>=this.minLength||t)&&!this.stopWords.has(e)}stemWord(e){if(e.length<3)return e;let t=!1,r=e;for(let s of this.stemmingRules)r.match(s.pattern)&&(t=!0,(!s.minMeasure||this.measure(r)>=s.minMeasure)&&(s.replacement,r=r.replace(s.pattern,s.replacement)));return t||(r=vd(r)),r}isConsonant(e,t){let r=e[t];return"aeiou".includes(r)?!1:r!=="y"||(t===0?!0:!this.isConsonant(e,t-1))}measure(e){let t=0,r=!1;for(let s=0;s<e.length;s++)this.isConsonant(e,s)?r&&(t++,r=!1):r=!0;return t}},Je=class{termFrequencySaturation;lengthNormalizationFactor;tokenizer;documentLengths;averageDocLength;termToIndex;documentFrequency;termFrequencies;fieldBoosts;documents;constructor(e,t={}){console.log("*** docs",e);let r={...Id,...t};if(this.termFrequencySaturation=r.k1,this.lengthNormalizationFactor=r.b,this.tokenizer=new hr(r),this.fieldBoosts=r.fieldBoosts||{},this.documents=[],this.documentLengths=new Uint32Array(0),this.termToIndex=new Map,this.documentFrequency=new Uint32Array(0),this.averageDocLength=0,this.termFrequencies=new Map,e&&e.length>0){console.log("doing indexing"),this.documents=[...e];let{documentLengths:s,termToIndex:i,documentFrequency:o,averageDocLength:a,termFrequencies:c}=this.processDocuments(e);this.documentLengths=s,this.termToIndex=i,this.documentFrequency=o,this.averageDocLength=a,this.termFrequencies=c}}processDocuments(e){console.log("*** processing documents");let t=e.length,r=new Uint32Array(t),s=new Map,i=new Map,o=new Map,a=0,c=0;e.forEach((d,l)=>{console.log("*** doc",d);let m=0,E=new Map;Object.entries(d).forEach(([p,g])=>{if(typeof g!="string")return;let A=this.fieldBoosts[p]||1,{tokens:R}=this.tokenizer.tokenize(g),O=R.length*A;m+=O,R.forEach(M=>{s.has(M)||s.set(M,c++);let S=s.get(M);i.has(M)||i.set(M,new Set),i.get(M).add(l);let C=E.get(S)||0;E.set(S,C+A)})}),r[l]=m,a+=m,E.forEach((p,g)=>{o.has(g)||o.set(g,new Map),o.get(g).set(l,p)})});let u=new Uint32Array(s.size);return i.forEach((d,l)=>{let m=s.get(l);u[m]=d.size}),{documentLengths:r,termToIndex:s,documentFrequency:u,averageDocLength:t>0?a/t:0,termFrequencies:o}}async addDocumentsParallel(e){if(!e||e.length===0)return;let t,r;try{t=(await import("worker_threads")).Worker,r=await import("os")}catch(a){throw console.error("Failed to load Node.js modules for parallel processing (worker_threads, os):",a),new Error("`addDocumentsParallel` failed to load required Node.js modules. This method is likely not supported in the current environment (e.g., browser, Deno, Bun worker without --allow-node-builtins).")}let s=Math.max(1,Math.floor(r.cpus().length/2)),i=Math.ceil(e.length/s),o=[];try{let a=Array.from({length:s},(m,E)=>{let p=E*i,g=Math.min(p+i,e.length);if(p>=g)return Promise.resolve(null);let A=new t(new URL("./worker.js",import.meta.url),{workerData:{docs:e.slice(p,g),tokenizerOptions:{stopWords:Array.from(this.tokenizer.stopWords),minLength:this.tokenizer.minLength,stemming:this.tokenizer.stemming,stemmingRules:this.tokenizer.stemmingRules.map(R=>({...R,pattern:R.pattern.toString()}))},fieldBoosts:this.fieldBoosts,startIndex:this.documents.length+p}});return o.push(A),new Promise((R,O)=>{A.on("message",M=>{M&&M.termFrequencies&&(M.termFrequencies=new Map(M.termFrequencies.map(([S,C])=>[S,new Map(C)]))),M&&M.termToIndex&&(M.termToIndex=new Map(M.termToIndex)),R(M)}),A.on("error",O),A.on("exit",M=>{M!==0&&O(new Error(`Worker stopped with exit code ${M}`))})})}),c=(await Promise.all(a)).filter(m=>m!==null),u=this.documentLengths.length,d=e.length,l=new Uint32Array(u+d);l.set(this.documentLengths,0),this.documents.push(...e),c.forEach(m=>{m&&(l.set(m.documentLengths,m.startIndex),m.termToIndex.forEach((E,p)=>{let g;this.termToIndex.has(p)?g=this.termToIndex.get(p):(g=this.termToIndex.size,this.termToIndex.set(p,g));let A=m.termFrequencies.get(E);if(A){this.termFrequencies.has(g)||this.termFrequencies.set(g,new Map);let R=this.termFrequencies.get(g);A.forEach((O,M)=>{R.set(M,O)})}}))}),this.documentLengths=l,this.updateDocumentFrequency(),this.recalculateAverageLength()}finally{o.forEach(a=>a.terminate())}}updateDocumentFrequency(){let e=this.termToIndex.size;if(this.documentFrequency.length<e){let t=this.documentFrequency;this.documentFrequency=new Uint32Array(Math.max(e,t.length*2)),this.documentFrequency.set(t,0)}else this.documentFrequency.length>e&&this.documentFrequency.fill(0,e);this.termFrequencies.forEach((t,r)=>{this.documentFrequency[r]=t.size});for(let t=this.termFrequencies.size;t<this.documentFrequency.length;t++)this.documentFrequency[t]=0}recalculateAverageLength(){if(this.documentLengths.length===0){this.averageDocLength=0;return}let e=Array.prototype.reduce.call(this.documentLengths,(t,r)=>t+r,0);this.averageDocLength=e/this.documentLengths.length}search(e,t=10){let{tokens:r}=this.tokenizer.tokenize(e),s=new Float32Array(this.documentLengths.length).fill(0);return r.forEach(i=>{let o=this.termToIndex.get(i);if(o===void 0)return;let a=this.calculateIDF(o);if(a<=0)return;let c=this.termFrequencies.get(o);c&&c.forEach((u,d)=>{let l=this.documentLengths[d],m=u*(this.termFrequencySaturation+1),E=u+this.termFrequencySaturation*(1-this.lengthNormalizationFactor+this.lengthNormalizationFactor*l/this.averageDocLength);s[d]+=a*(m/E)})}),Array.from({length:s.length},(i,o)=>({index:o,score:s[o]})).filter(i=>i.score>0).sort((i,o)=>o.score-i.score).slice(0,t)}searchPhrase(e,t=10){let{tokens:r}=this.tokenizer.tokenize(e);if(r.length===0)return[];let s=null;for(let o of r){let a=this.termToIndex.get(o);if(a===void 0)return[];let c=this.termFrequencies.get(a)?.keys();if(!c)return[];let u=new Set(c);if(s===null?s=u:s=new Set([...s].filter(d=>u.has(d))),s.size===0)return[]}if(s===null||s.size===0)return[];let i=new Map;return s.forEach(o=>{let a=this.getDocument(o),c=!1;Object.entries(a).forEach(([u,d])=>{if(typeof d!="string"||c)return;let l=this.fieldBoosts[u]||1,{tokens:m}=this.tokenizer.tokenize(d);for(let E=0;E<=m.length-r.length;E++){let p=!0;for(let g=0;g<r.length;g++)if(m[E+g]!==r[g]){p=!1;break}if(p){let g=this.calculatePhraseScore(r,o)*l;i.set(o,(i.get(o)||0)+g),c=!0;break}}})}),Array.from(i.entries()).map(([o,a])=>({index:o,score:a})).sort((o,a)=>a.score-o.score).slice(0,t)}calculatePhraseScore(e,t){return e.reduce((r,s)=>{let i=this.termToIndex.get(s);if(i===void 0)return r;let o=this.calculateIDF(i),a=this.termFrequencies.get(i)?.get(t)||0,c=this.documentLengths[t],u=a*(this.termFrequencySaturation+1),d=a+this.termFrequencySaturation*(1-this.lengthNormalizationFactor+this.lengthNormalizationFactor*c/this.averageDocLength);return r+o*(u/d)},0)}async addDocument(e){if(!e)throw new Error("Document cannot be null");let t=this.documentLengths.length;this.documents.push(e);let r=new Uint32Array(t+1);r.set(this.documentLengths,0),this.documentLengths=r;let s=0,i=new Map;Object.entries(e).forEach(([o,a])=>{if(typeof a!="string")return;let c=this.fieldBoosts[o]||1,{tokens:u}=this.tokenizer.tokenize(a);s+=u.length*c,u.forEach(d=>{let l;if(this.termToIndex.has(d))l=this.termToIndex.get(d);else{if(l=this.termToIndex.size,this.termToIndex.set(d,l),this.documentFrequency.length<=l){let E=this.documentFrequency,p=Math.max(l+1,E.length*2);this.documentFrequency=new Uint32Array(p),this.documentFrequency.set(E,0)}this.documentFrequency[l]=0}let m=i.get(l)||0;i.set(l,m+c)})}),this.documentLengths[t]=s,i.forEach((o,a)=>{this.termFrequencies.has(a)||this.termFrequencies.set(a,new Map),this.termFrequencies.get(a).set(t,o),this.documentFrequency[a]++}),this.recalculateAverageLength()}calculateIDF(e){if(e<0||e>=this.documentFrequency.length)return 0;let t=this.documentFrequency[e];if(t<=0||t>this.documentLengths.length)return 0;let s=this.documentLengths.length-t+.5,i=t+.5;return Math.log(1+s/i)}getTermFrequency(e,t){return this.termFrequencies.get(e)?.get(t)||0}getDocument(e){if(e<0||e>=this.documents.length)throw new Error(`Document index ${e} out of bounds (0-${this.documents.length-1})`);return this.documents[e]}clearDocuments(){this.documents=[],this.documentLengths=new Uint32Array(0),this.termToIndex.clear(),this.documentFrequency=new Uint32Array(0),this.averageDocLength=0,this.termFrequencies.clear()}getDocumentCount(){return this.documents.length}async addDocuments(e){await Promise.all(e.map(t=>this.addDocument(t)))}};import{sha1 as Pd}from"js-sha1";import{z as Ud}from"zod";var Ld=Ud.string().uuid();function ZE(n){let e=Ld.safeParse(n);return e.success?e.data:null}function Le(n){if(typeof n=="number"&&(n=n.toString()),typeof n!="string")throw TypeError("Value must be string");let e=a=>{let c=a>>4,u=a-(c<<4),d="0123456789abcdef".split("");return d[c]+d[u]},t=a=>{let c="";for(let u=0;u<a.length;u++)c+=e(a[u]);return c},r=encodeURIComponent(n),s=new Uint8Array(r.length);for(let a=0;a<r.length;a++)s[a]=r[a].charCodeAt(0);let i=Pd(s),o=new Uint8Array(i.length/2);for(let a=0;a<i.length;a+=2)o[a/2]=Number.parseInt(i.slice(a,a+2),16);return`${t(o.slice(0,4))}-${t(o.slice(4,6))}-${e(o[6]&15)}${e(o[7])}-${e(o[8]&63|128)}${e(o[9])}-${t(o.slice(10,16))}`}var Cd={},_r=class{permits;waiting=[];constructor(e){this.permits=e}async acquire(){return this.permits>0?(this.permits-=1,Promise.resolve()):new Promise(e=>{this.waiting.push(e)})}release(){this.permits+=1;let e=this.waiting.shift();e&&this.permits>0&&(this.permits-=1,e())}},Vs=class{#e=32;agentId;character;adapter;actions=[];evaluators=[];providers=[];plugins=[];isInitialized=!1;events=new Map;stateCache=new Map;fetch=fetch;services=new Map;models=new Map;routes=[];taskWorkers=new Map;eventHandlers=new Map;runtimeLogger;knowledgeProcessingSemaphore=new _r(10);settings;servicesInitQueue=new Set;instrumentationService;tracer;constructor(e){this.agentId=e.character?.id??e?.agentId??Le(e.character?.name??bd()),this.character=e.character;let t=process.env.LOG_LEVEL||"info";this.runtimeLogger=G.child({agentName:this.character?.name,agentId:this.agentId,level:t==="debug"?"debug":"error"}),this.runtimeLogger.debug(`[AgentRuntime] Process working directory: ${process.cwd()}`),this.#e=e.conversationLength??this.#e,e.adapter&&this.registerDatabaseAdapter(e.adapter),this.fetch=e.fetch??this.fetch,this.settings=e.settings??Cd;let r=e?.plugins??[];this.plugins=r;try{this.instrumentationService=new Xe({serviceName:`agent-${this.character?.name||"unknown"}-${this.agentId}`,enabled:process.env.INSTRUMENTATION_ENABLED==="true"}),this.tracer=this.instrumentationService.getTracer("agent-runtime"),this.runtimeLogger.debug(`Instrumentation service initialized for agent ${this.agentId}`)}catch(s){this.runtimeLogger.warn(`Failed to initialize instrumentation: ${s.message}`),this.instrumentationService={getTracer:()=>null,start:async()=>{},stop:async()=>{},isStarted:()=>!1,isEnabled:()=>!1,name:"INSTRUMENTATION",capabilityDescription:"Disabled instrumentation service (fallback)",instrumentationConfig:{enabled:!1},getMeter:()=>null,flush:async()=>{}},this.tracer=null}this.runtimeLogger.debug(`Success: Agent ID: ${this.agentId}`)}async startSpan(e,t,r){return!this.instrumentationService?.isEnabled?.()||!this.tracer?t({setStatus:()=>{},setAttribute:()=>{},setAttributes:()=>{},recordException:()=>{},addEvent:()=>{},end:()=>{},isRecording:()=>!1,spanContext:()=>({traceId:"",spanId:"",traceFlags:0}),updateName:()=>{},addLink:()=>{},addLinks:()=>{}}):this.tracer.startActiveSpan(e,r,void 0,async s=>{try{s.setAttributes({"agent.id":this.agentId,"agent.name":this.character?.name||"unknown"});let i=await t(s);return s.setStatus({code:L.OK}),s.end(),i}catch(i){throw s.recordException(i),s.setStatus({code:L.ERROR,message:i.message}),s.end(),i}})}endSpan(e,t){}startActiveSpan(e,t={}){return!this.instrumentationService?.isEnabled?.()||!this.tracer?{setStatus:()=>{},setAttribute:()=>{},setAttributes:()=>{},recordException:()=>{},addEvent:()=>{},end:()=>{},isRecording:()=>!1,spanContext:()=>({traceId:"",spanId:"",traceFlags:0}),updateName:()=>{},addLink:()=>{},addLinks:()=>{}}:this.tracer.startSpan(e,t)}async registerPlugin(e){return this.startSpan("AgentRuntime.registerPlugin",async t=>{if(t.setAttributes({"plugin.name":e?.name||"unknown","agent.id":this.agentId}),!e)throw t.setStatus({code:L.ERROR,message:"Plugin is undefined"}),this.runtimeLogger.error("*** registerPlugin plugin is undefined"),new Error("*** registerPlugin plugin is undefined");if(this.plugins.some(r=>r.name===e.name)||(this.plugins.push(e),t.addEvent("plugin_added_to_array"),this.runtimeLogger.debug(`Success: Plugin ${e.name} registered successfully`)),e.init)try{t.addEvent("initializing_plugin"),await e.init(e.config||{},this),t.addEvent("plugin_initialized"),this.runtimeLogger.debug(`Success: Plugin ${e.name} initialized successfully`)}catch(r){let s=r instanceof Error?r.message:String(r);if(t.setAttributes({"error.message":s,"error.type":r instanceof Error?r.constructor.name:"Unknown"}),s.includes("API key")||s.includes("environment variables")||s.includes("Invalid plugin configuration"))console.warn(`Plugin ${e.name} requires configuration. ${s}`),console.warn("Please check your environment variables and ensure all required API keys are set."),console.warn("You can set these in your .eliza/.env file."),t.addEvent("plugin_configuration_warning");else throw t.setStatus({code:L.ERROR,message:s}),r}if(e.adapter&&(t.addEvent("registering_adapter"),this.runtimeLogger.debug(`Registering database adapter for plugin ${e.name}`),this.registerDatabaseAdapter(e.adapter)),e.actions){t.addEvent("registering_actions");for(let r of e.actions)this.registerAction(r)}if(e.evaluators){t.addEvent("registering_evaluators");for(let r of e.evaluators)this.registerEvaluator(r)}if(e.providers){t.addEvent("registering_providers");for(let r of e.providers)this.registerContextProvider(r)}if(e.models){t.addEvent("registering_models");for(let[r,s]of Object.entries(e.models))this.registerModel(r,s)}if(e.routes){t.addEvent("registering_routes");for(let r of e.routes)this.routes.push(r)}if(e.events){t.addEvent("registering_events");for(let[r,s]of Object.entries(e.events))for(let i of s)this.registerEvent(r,i)}if(e.services){t.addEvent("registering_services");for(let r of e.services)this.isInitialized?await this.registerService(r):this.servicesInitQueue.add(r)}t.addEvent("plugin_registration_complete")})}getAllServices(){return this.services}async stop(){return this.startSpan("AgentRuntime.stop",async e=>{e.setAttributes({"agent.id":this.agentId,"agent.name":this.character?.name||"unknown"}),this.runtimeLogger.debug(`runtime::stop - character ${this.character.name}`),e.addEvent("stopping_services");for(let[t,r]of this.services)this.runtimeLogger.debug(`runtime::stop - requesting service stop for ${t}`),e.addEvent(`stopping_service_${t}`),await r.stop();e.addEvent("all_services_stopped")})}async initialize(){return this.startSpan("AgentRuntime.initialize",async e=>{if(e.setAttributes({"agent.id":this.agentId,"agent.name":this.character?.name||"unknown","plugins.count":this.plugins.length}),this.isInitialized){e.addEvent("agent_already_initialized"),this.runtimeLogger.warn("Agent already initialized");return}e.addEvent("initialization_started");let t=new Set,r=[];for(let i of[...this.plugins])i&&!t.has(i.name)&&(t.add(i.name),r.push(await this.registerPlugin(i)));if(e.addEvent("plugins_setup"),e.setAttributes({registered_plugins:Array.from(t).join(",")}),!this.adapter)throw this.runtimeLogger.error("Database adapter not initialized. Make sure @elizaos/plugin-sql is included in your plugins."),new Error("Database adapter not initialized. The SQL plugin (@elizaos/plugin-sql) is required for agent initialization. Please ensure it is included in your character configuration.");try{await this.adapter.init(),e.addEvent("adapter_initialized");let i=await this.adapter.ensureAgentExists(this.character);if(e.addEvent("agent_exists_verified"),!i){let a=`Agent ${this.character.name} does not exist in database after ensureAgentExists call`;throw e.setStatus({code:L.ERROR,message:a}),new Error(a)}let o=await this.adapter.getEntityById(this.agentId);if(o)e.addEvent("agent_entity_exists");else{if(e.addEvent("creating_agent_entity"),!await this.createEntity({id:this.agentId,agentId:i.id,names:Array.from(new Set([this.character.name].filter(Boolean))),metadata:{}})){let c=`Failed to create entity for agent ${this.agentId}`;throw e.setStatus({code:L.ERROR,message:c}),new Error(c)}if(o=await this.adapter.getEntityById(this.agentId),!o)throw new Error(`Agent entity not found for ${this.agentId}`);this.runtimeLogger.debug(`Success: Agent entity created successfully for ${this.character.name}`),e.addEvent("agent_entity_created")}}catch(i){let o=i instanceof Error?i.message:String(i);throw e.recordException(i),e.setStatus({code:L.ERROR,message:o}),this.runtimeLogger.error(`Failed to create agent entity: ${o}`),i}try{e.addEvent("creating_group_and_registering_plugins"),await Promise.all([this.ensureRoomExists({id:this.agentId,name:this.character.name,source:"self",type:"SELF"}),...r]),e.addEvent("room_created_and_plugins_registered")}catch(i){let o=i instanceof Error?i.message:String(i);throw e.recordException(i),e.setStatus({code:L.ERROR,message:o}),this.runtimeLogger.error(`Failed to initialize: ${o}`),i}try{if(e.addEvent("adding_agent_as_participant"),(await this.adapter.getParticipantsForRoom(this.agentId)).includes(this.agentId))e.addEvent("agent_already_participant");else{if(!await this.adapter.addParticipant(this.agentId,this.agentId)){let a=`Failed to add agent ${this.agentId} as participant to its own room`;throw e.setStatus({code:L.ERROR,message:a}),new Error(a)}this.runtimeLogger.debug(`Agent ${this.character.name} linked to its own room successfully`),e.addEvent("agent_added_as_participant")}}catch(i){let o=i instanceof Error?i.message:String(i);throw e.recordException(i),e.setStatus({code:L.ERROR,message:o}),this.runtimeLogger.error(`Failed to add agent as participant: ${o}`),i}if(this.getModel(N.TEXT_EMBEDDING)?(e.addEvent("setting_up_embedding_dimension"),await this.ensureEmbeddingDimension(),e.addEvent("embedding_dimension_setup_complete")):(e.addEvent("embedding_model_missing"),this.runtimeLogger.warn(`[AgentRuntime][${this.character.name}] No TEXT_EMBEDDING model registered. Skipping embedding dimension setup.`)),this.character?.knowledge&&this.character.knowledge.length>0){e.addEvent("processing_character_knowledge"),e.setAttributes({"knowledge.count":this.character.knowledge.length});let i=this.character.knowledge.filter(o=>typeof o=="string");await this.processCharacterKnowledge(i),e.addEvent("character_knowledge_processed")}e.addEvent("starting_deferred_services"),e.setAttributes({"deferred_services.count":this.servicesInitQueue.size});for(let i of this.servicesInitQueue)await this.registerService(i);e.addEvent("initialization_completed")})}async handleProcessingError(e,t){throw this.runtimeLogger.error(`Error ${t}:`,e?.message||e||"Unknown error"),e}async checkExistingKnowledge(e){return!!await this.getMemoryById(e)}async getKnowledge(e,t){return console.log("*** getKnowledge",e),this.startSpan("AgentRuntime.getKnowledge",async r=>{if(!e?.content?.text)return r.addEvent("invalid_message"),r.setStatus({code:L.ERROR,message:"Invalid message for knowledge query"}),this.runtimeLogger.warn("Invalid message for knowledge query:",{message:e,content:e?.content,text:e?.content?.text}),[];if(!e?.content?.text||e?.content?.text.trim().length===0)return r.addEvent("empty_text"),r.setStatus({code:L.ERROR,message:"Empty text for knowledge query"}),this.runtimeLogger.warn("Empty text for knowledge query"),[];r.setAttributes({"message.id":e.id,"query.length":e.content.text.length,"agent.id":this.agentId}),r.addEvent("generating_embedding");let s=await this.useModel(N.TEXT_EMBEDDING,{text:e?.content?.text});r.addEvent("searching_memories"),r.setAttributes({"embedding.length":s.length}),console.log("*** searching memories");let i={};t?.roomId&&(i.roomId=t.roomId),t?.worldId&&(i.worldId=t.worldId),t?.entityId&&(i.entityId=t.entityId),r.addEvent("determined_filter_scope",{...i.roomId&&{"filter.roomId":i.roomId},...i.worldId&&{"filter.worldId":i.worldId},...i.entityId&&{"filter.entityId":i.entityId}});let o=await this.searchMemories({tableName:"knowledge",embedding:s,query:e?.content?.text,...i,count:20,match_threshold:.1});return console.log("*** fragments",o),r.addEvent("knowledge_retrieved"),r.setAttributes({"fragments.count":o.length}),o.map(a=>({id:a.id,content:a.content,similarity:a.similarity,metadata:a.metadata,worldId:a.worldId}))})}async addKnowledge(e,t={targetTokens:1500,overlap:200,modelContextSize:4096},r){return this.startSpan("AgentRuntime.addKnowledge",async s=>{s.setAttributes({"item.id":e.id,"agent.id":this.agentId,"options.targetTokens":t.targetTokens,"options.overlap":t.overlap,"scope.roomId":r?.roomId,"scope.worldId":r?.worldId,"scope.entityId":r?.entityId});let i={roomId:r?.roomId??this.agentId,worldId:r?.worldId,entityId:r?.entityId??this.agentId},o={id:e.id,agentId:this.agentId,roomId:i.roomId,worldId:i.worldId,entityId:i.entityId,content:e.content,metadata:e.metadata||{type:"document",timestamp:Date.now()}};s.addEvent("storing_document"),await this.createMemory(o,"documents"),s.addEvent("document_stored"),s.addEvent("splitting_chunks");let a=await Cr(e.content.text,t.targetTokens,t.overlap);s.setAttributes({"fragments.count":a.length}),s.addEvent("chunks_split");let c=0;s.addEvent("storing_fragments");for(let u=0;u<a.length;u++)try{s.addEvent(`generating_embedding_${u}`);let d=await this.useModel(N.TEXT_EMBEDDING,a[u]),l={id:B(this,`${e.id}-fragment-${u}`),agentId:this.agentId,roomId:i.roomId,worldId:i.worldId,entityId:i.entityId,embedding:d,content:{text:a[u]},metadata:{type:"fragment",documentId:e.id,position:u,timestamp:Date.now()}};await this.createMemory(l,"knowledge"),c++}catch(d){let l=d instanceof Error?d.message:String(d);s.recordException(d),s.setAttributes({"error.fragment":u,"error.message":l}),this.runtimeLogger.error(`Error processing fragment ${u}: ${l}`)}s.setAttributes({"fragments.processed":c,"fragments.success_rate":c/a.length}),s.addEvent("knowledge_processing_complete")})}async processCharacterKnowledge(e){let t=e.map(async r=>{await this.knowledgeProcessingSemaphore.acquire();try{let s=B(this,r);if(await this.checkExistingKnowledge(s))return;this.runtimeLogger.debug("Processing knowledge for ",this.character.name," - ",r.slice(0,100));let i={type:"document",timestamp:Date.now()},o=r.match(/^Path: (.+?)(?:\n|\r\n)/);if(o){let a=o[1].trim(),c=a.split(".").pop()||"",u=a.split("/").pop()||"",d=u.replace(`.${c}`,"");i={...i,path:a,filename:u,fileExt:c,title:d,fileType:`text/${c||"plain"}`,fileSize:r.length,source:"character"}}await this.addKnowledge({id:s,content:{text:r},metadata:i},void 0,{roomId:this.agentId,entityId:this.agentId,worldId:null})}catch(s){await this.handleProcessingError(s,"processing character knowledge")}finally{this.knowledgeProcessingSemaphore.release()}});await Promise.all(t)}setSetting(e,t,r=!1){r?(this.character.secrets||(this.character.secrets={}),this.character.secrets[e]=t):(this.character.settings||(this.character.settings={}),this.character.settings[e]=t)}getSetting(e){let t=this.character.secrets?.[e]||this.character.settings?.[e]||this.character.settings?.secrets?.[e]||this.settings[e],r=et(t,X());return r==="true"?!0:r==="false"?!1:r||null}getConversationLength(){return this.#e}registerDatabaseAdapter(e){this.adapter?this.runtimeLogger.warn("Database adapter already registered. Additional adapters will be ignored. This may lead to unexpected behavior."):(this.adapter=e,this.runtimeLogger.debug("Success: Database adapter registered successfully."))}registerProvider(e){this.providers.push(e),this.runtimeLogger.debug(`Success: Provider ${e.name} registered successfully.`)}registerAction(e){this.runtimeLogger.debug(`${this.character.name}(${this.agentId}) - Registering action: ${e.name}`),this.actions.find(t=>t.name===e.name)?this.runtimeLogger.warn(`${this.character.name}(${this.agentId}) - Action ${e.name} already exists. Skipping registration.`):(this.actions.push(e),this.runtimeLogger.debug(`${this.character.name}(${this.agentId}) - Action ${e.name} registered successfully.`))}registerEvaluator(e){this.evaluators.push(e)}registerContextProvider(e){this.providers.push(e)}async processActions(e,t,r,s){return this.startSpan("AgentRuntime.processActions",async i=>{i.setAttributes({"message.id":e.id,"responses.count":t.length,"agent.id":this.agentId});for(let o of t){let c=function(u){return u.toLowerCase().replace("_","")};if(!o.content?.actions||o.content.actions.length===0){i.addEvent("no_actions_in_response"),this.runtimeLogger.warn("No action found in the response content.");continue}let a=o.content.actions;i.setAttributes({"actions.count":a.length,"actions.names":JSON.stringify(a)}),this.runtimeLogger.debug(`Found actions: ${this.actions.map(u=>c(u.name))}`);for(let u of a){i.addEvent(`processing_action_${u}`),r=await this.composeState(e,["RECENT_MESSAGES"]),this.runtimeLogger.debug(`Success: Calling action: ${u}`);let d=c(u),l=this.actions.find(m=>c(m.name).includes(d)||d.includes(c(m.name)));if(l)i.addEvent(`found_exact_action_${l.name}`),this.runtimeLogger.debug(`Success: Found action: ${l?.name}`);else{i.addEvent("looking_for_similar_action"),this.runtimeLogger.debug("Attempting to find action in similes.");for(let m of this.actions)if(m.similes?.find(p=>p.toLowerCase().replace("_","").includes(d)||d.includes(p.toLowerCase().replace("_","")))){l=m,i.addEvent(`found_similar_action_${l.name}`),this.runtimeLogger.debug(`Success: Action found in similes: ${l.name}`);break}}if(!l){let m=`No action found for: ${u}`;i.addEvent("action_not_found"),i.setAttributes({"error.action":u}),this.runtimeLogger.error(m);continue}if(!l.handler){i.addEvent("action_has_no_handler"),i.setAttributes({"error.action":l.name}),this.runtimeLogger.error(`Action ${l.name} has no handler.`);continue}try{i.addEvent(`executing_action_${l.name}`),this.runtimeLogger.debug(`Executing handler for action: ${l.name}`),await this.startSpan(`Action.${l.name}`,async m=>{m.setAttributes({"action.name":l.name,"parent_span.id":i.spanContext().spanId}),m.addEvent("action.input",{"message.id":e.id,"state.keys":r?JSON.stringify(Object.keys(r.values)):"none",options:JSON.stringify({}),"responses.count":t?.length??0,"responses.ids":JSON.stringify(t?.map(E=>E.id)??[])});try{let E=await l.handler(this,e,r,{},s,t);m.addEvent("action.output",{status:"success",result:JSON.stringify(E,Me())}),m.setStatus({code:L.OK})}catch(E){let p=E instanceof Error?E.message:String(E);throw m.recordException(E),m.setStatus({code:L.ERROR,message:p}),m.setAttributes({"error.message":p}),m.addEvent("action.output",{status:"error",error:p}),E}}),i.addEvent(`action_executed_successfully_${l.name}`),this.runtimeLogger.debug(`Success: Action ${l.name} executed successfully.`),this.adapter.log({entityId:e.entityId,roomId:e.roomId,type:"action",body:{action:l.name,message:e.content.text,messageId:e.id,state:r,responses:t}})}catch(m){let E=m instanceof Error?m.message:String(m);throw i.recordException(m),i.setStatus({code:L.ERROR,message:E}),i.setAttributes({"error.action":l.name,"error.message":E}),this.runtimeLogger.error(m),m}}}})}async evaluate(e,t,r,s,i){return this.startSpan("AgentRuntime.evaluate",async o=>{o.setAttributes({"agent.id":this.agentId,"character.name":this.character?.name,"message.id":e?.id,"room.id":e?.roomId,"entity.id":e?.entityId,did_respond:r,responses_count:i?.length||0}),o.addEvent("evaluation_started");let a=this.evaluators.map(async u=>!u.handler||!r&&!u.alwaysRun?null:await u.validate(this,e,t)?u:null),c=(await Promise.all(a)).filter(Boolean);return o.setAttribute("selected_evaluators_count",c.length),o.addEvent("evaluator_selection_complete",{"evaluator.names":JSON.stringify(c.map(u=>u.name))}),c.length===0?(o.addEvent("no_evaluators_selected"),[]):(t=await this.composeState(e,["RECENT_MESSAGES","EVALUATORS"]),o.addEvent("evaluator_execution_start"),await Promise.all(c.map(async u=>{u.handler&&(await u.handler(this,e,t,{},s,i),this.adapter.log({entityId:e.entityId,roomId:e.roomId,type:"evaluator",body:{evaluator:u.name,messageId:e.id,message:e.content.text,state:t}}))})),o.addEvent("evaluator_execution_complete"),o.addEvent("evaluation_complete"),c)})}async ensureConnection({entityId:e,roomId:t,userName:r,name:s,source:i,type:o,channelId:a,serverId:c,worldId:u,userId:d}){if(e===this.agentId)throw new Error("Agent should not connect to itself");!u&&c&&(u=B(this,c));let l=[s,r].filter(Boolean),m={[i]:{id:d,name:s,userName:r}};try{let E=await this.adapter.getEntityById(e);if(E)await this.adapter.updateEntity({id:e,names:[...new Set([...E.names||[],...l])].filter(Boolean),metadata:{...E.metadata,[i]:{...E.metadata?.[i],name:s,userName:r}},agentId:this.agentId});else try{if(await this.adapter.createEntity({id:e,names:l,metadata:m,agentId:this.agentId}))this.runtimeLogger.debug(`Created new entity ${e} for user ${s||r||"unknown"}`);else throw new Error(`Failed to create entity ${e}`)}catch(p){if(p.message?.includes("duplicate key")||p.code==="23505")this.runtimeLogger.debug(`Entity ${e} exists in database but not for this agent. This is normal in multi-agent setups.`);else throw p}u&&await this.ensureWorldExists({id:u,name:c?`World for server ${c}`:`World for room ${t}`,agentId:this.agentId,serverId:c||"default",metadata:m}),await this.ensureRoomExists({id:t,name:s,source:i,type:o,channelId:a,serverId:c,worldId:u});try{await this.ensureParticipantInRoom(e,t)}catch(p){if(p.message?.includes("not found")){if(!await this.adapter.addParticipant(e,t))throw new Error(`Failed to add participant ${e} to room ${t}`);this.runtimeLogger.debug(`Added participant ${e} to room ${t} directly`)}else throw p}await this.ensureParticipantInRoom(this.agentId,t),this.runtimeLogger.debug(`Success: Successfully connected entity ${e} in room ${t}`)}catch(E){throw this.runtimeLogger.error(`Failed to ensure connection: ${E instanceof Error?E.message:String(E)}`),E}}async ensureParticipantInRoom(e,t){let r=await this.adapter.getEntityById(e);if(!r&&e!==this.agentId)this.runtimeLogger.warn(`Entity ${e} not directly accessible to agent ${this.agentId}. Will attempt to add as participant anyway.`);else if(!r)throw new Error(`User ${e} not found`);if(!(await this.adapter.getParticipantsForRoom(t)).includes(e)){if(!await this.adapter.addParticipant(e,t))throw new Error(`Failed to add participant ${e} to room ${t}`);e===this.agentId?this.runtimeLogger.debug(`Agent ${this.character.name} linked to room ${t} successfully.`):this.runtimeLogger.debug(`User ${e} linked to room ${t} successfully.`)}}async removeParticipant(e,t){return await this.adapter.removeParticipant(e,t)}async getParticipantsForEntity(e){return await this.adapter.getParticipantsForEntity(e)}async getParticipantsForRoom(e){return await this.adapter.getParticipantsForRoom(e)}async addParticipant(e,t){return await this.adapter.addParticipant(e,t)}async ensureWorldExists({id:e,name:t,serverId:r,metadata:s}){await this.getWorld(e)||(this.runtimeLogger.debug("Creating world:",{id:e,name:t,serverId:r,agentId:this.agentId}),await this.adapter.createWorld({id:e,name:t,agentId:this.agentId,serverId:r||"default",metadata:s}),this.runtimeLogger.debug(`World ${e} created successfully.`))}async ensureRoomExists({id:e,name:t,source:r,type:s,channelId:i,serverId:o,worldId:a,metadata:c}){await this.adapter.getRoom(e)||(await this.adapter.createRoom({id:e,name:t,agentId:this.agentId,source:r,type:s,channelId:i,serverId:o,worldId:a,metadata:c}),this.runtimeLogger.debug(`Room ${e} created successfully.`))}async composeState(e,t=null,r=null){return this.startSpan("AgentRuntime.composeState",async s=>{s.setAttributes({"message.id":e.id,"agent.id":this.agentId,filter_list:t?JSON.stringify(t):"none",include_list:r?JSON.stringify(r):"none"}),s.addEvent("state_composition_started");let i=await this.stateCache.get(e.id)||{values:{},data:{},text:""},o=i.data.providers?Object.keys(i.data.providers):[];s.setAttributes({cached_state_exists:!!i.data.providers,existing_providers_count:o.length,existing_providers:JSON.stringify(o)});let a=new Set;t&&t.length>0?t.forEach(S=>a.add(S)):this.providers.filter(S=>!S.private&&!S.dynamic&&!o.includes(S.name)).forEach(S=>a.add(S.name)),r&&r.length>0&&r.forEach(S=>a.add(S));let c=Array.from(new Set(this.providers.filter(S=>a.has(S.name)))).sort((S,C)=>(S.position||0)-(C.position||0)),u=c.map(S=>S.name);s.setAttributes({providers_to_get_count:c.length,providers_to_get:JSON.stringify(u)}),s.addEvent("starting_provider_fetch");let d=await Promise.all(c.map(async S=>this.startSpan(`provider.${S.name}`,async C=>{let Sr=Date.now();try{let y=await S.get(this,e,i),Ie=Date.now()-Sr;return C.setAttributes({"provider.name":S.name,"provider.duration_ms":Ie,"result.has_text":!!y.text,"result.values_keys":y.values?JSON.stringify(Object.keys(y.values)):"[]"}),C.addEvent("provider_fetch_complete"),this.runtimeLogger.debug(`${S.name} Provider took ${Ie}ms to respond`),{...y,providerName:S.name}}catch(y){let Ie=Date.now()-Sr,gr=y instanceof Error?y.message:String(y);return C.recordException(y),C.setStatus({code:L.ERROR,message:gr}),C.setAttributes({"provider.name":S.name,"provider.duration_ms":Ie,"error.message":gr}),C.addEvent("provider_fetch_error"),{values:{},text:"",providerName:S.name}}}))),m={...i.data.providers||{}};for(let S of d)m[S.providerName]=S.values||{};let E=d.map(S=>S.text).filter(S=>S!=="").join("\\n"),p="";i.text&&E?p=`${i.text}\\n${E}`:E?p=E:i.text&&(p=i.text);let g={...i.values||{}};for(let S in m){let C=m[S];C&&typeof C=="object"&&Object.assign(g,C)}let A={values:{...g,providers:p},data:{...i.data||{},providers:m},text:p};this.stateCache.set(e.id,A);let R=Object.keys(m).length,O=Object.keys(m),M=Object.keys(A.values);return s.setAttributes({"context.sources.provider_count":R,"context.sources.provider_names":JSON.stringify(O),"context.state.value_keys":JSON.stringify(M),"context.state.text_length":p.length,"context.sources.used_memory":O.includes("RECENT_MESSAGES"),"context.sources.used_knowledge":O.includes("KNOWLEDGE"),"context.sources.used_character":O.includes("CHARACTER"),"context.sources.used_actions":O.includes("ACTIONS"),"context.sources.used_facts":O.includes("FACTS")}),s.addEvent("context.composed",{"context.final_string":p.length>1e3?p.substring(0,997)+"...":p,"context.final_length":p.length}),s.addEvent("state_composition_complete"),A})}getService(e){let t=this.services.get(e);return t||(this.runtimeLogger.debug(`Service ${e} not found`),null)}async registerService(e){return this.startSpan("AgentRuntime.registerService",async t=>{let r=e.serviceType;if(t.setAttributes({"service.type":r||"unknown","agent.id":this.agentId}),!r){t.addEvent("service_missing_type");return}if(this.runtimeLogger.debug(`${this.character.name}(${this.agentId}) - Registering service:`,r),this.services.has(r)){t.addEvent("service_already_registered"),this.runtimeLogger.warn(`${this.character.name}(${this.agentId}) - Service ${r} is already registered. Skipping registration.`);return}try{t.addEvent("starting_service");let s=await e.start(this);this.services.set(r,s),t.addEvent("service_registered"),this.runtimeLogger.debug(`${this.character.name}(${this.agentId}) - Service ${r} registered successfully`)}catch(s){let i=s instanceof Error?s.message:String(s);throw t.recordException(s),t.setStatus({code:L.ERROR,message:i}),this.runtimeLogger.error(`${this.character.name}(${this.agentId}) - Failed to register service ${r}: ${i}`),s}})}registerModel(e,t){let r=typeof e=="string"?e:N[e];this.models.has(r)||this.models.set(r,[]),this.models.get(r)?.push(t)}getModel(e){let t=typeof e=="string"?e:N[e],r=this.models.get(t);if(r?.length)return r[0]}async useModel(e,t){return this.startSpan(`AgentRuntime.useModel.${e}`,async r=>{let s=typeof e=="string"?e:N[e],i=t?.prompt||t?.input||(Array.isArray(t?.messages)?JSON.stringify(t.messages):null);r.setAttributes({"llm.request.model":s,"agent.id":this.agentId,"llm.request.temperature":t?.temperature,"llm.request.top_p":t?.top_p,"llm.request.max_tokens":t?.max_tokens||t?.max_tokens_to_sample}),r.addEvent("model_parameters",{params:JSON.stringify(t,Me())}),i&&r.addEvent("llm.prompt",{"prompt.content":i});let o=this.getModel(s);if(!o){let u=`No handler found for delegate type: ${s}`;throw r.setStatus({code:L.ERROR,message:u}),new Error(u)}this.runtimeLogger.debug(`[useModel] ${s} input:`,JSON.stringify(t,Me(),2).replace(/\\n/g,`
|
|
219
|
-
`));let a;t==null||typeof t!="object"||Array.isArray(t)||typeof Buffer<"u"&&Buffer.isBuffer(t)?a=t:a={...t,runtime:this};let c=performance.now();r.addEvent("model_execution_start");try{let u=await o(this,a),d=performance.now()-c;return r.setAttributes({"llm.duration_ms":d,"llm.usage.prompt_tokens":u?.usage?.prompt_tokens,"llm.usage.completion_tokens":u?.usage?.completion_tokens,"llm.usage.total_tokens":u?.usage?.total_tokens}),r.addEvent("model_response",{response:JSON.stringify(u,Me())}),this.runtimeLogger.debug(`[useModel] ${s} completed in ${Number(d.toFixed(2)).toLocaleString()}ms`),this.runtimeLogger.debug(`[useModel] ${s} output:`,Array.isArray(u)?`${JSON.stringify(u.slice(0,5))}...${JSON.stringify(u.slice(-5))} (${u.length} items)`:JSON.stringify(u)),this.adapter.log({entityId:this.agentId,roomId:this.agentId,body:{modelType:e,modelKey:s,params:t?typeof t=="object"?Object.keys(t):typeof t:null,response:Array.isArray(u)&&u.every(l=>typeof l=="number")?"[array]":u},type:`useModel:${s}`}),r.addEvent("model_execution_complete"),r.setStatus({code:L.OK}),u}catch(u){let d=performance.now()-c,l=u instanceof Error?u.message:String(u);throw r.recordException(u),r.setStatus({code:L.ERROR,message:l}),r.setAttributes({"error.time_ms":d,"error.message":l}),r.addEvent("model_execution_error"),u}})}registerEvent(e,t){this.events.has(e)||this.events.set(e,[]),this.events.get(e)?.push(t)}getEvent(e){return this.events.get(e)}async emitEvent(e,t){let r=Array.isArray(e)?e:[e];for(let s of r){let i=s==="MESSAGE_RECEIVED",o=this.instrumentationService?.isEnabled?.()&&this.tracer,a=this.events.get(s);if(a)if(i&&o){let c=t?.message,u=this.tracer.startSpan("AgentRuntime.handleMessageEvent",{attributes:{"agent.id":this.agentId,"character.name":this.character?.name,"room.id":c?.roomId||"unknown","user.id":c?.entityId||"unknown","message.id":c?.id||"unknown","event.name":s}}),d=Od.setSpan(Ze.active(),u);try{u.addEvent("processing_started"),await Ze.with(d,async()=>{await Promise.all(a.map(l=>{let m=Ze.active();return Ze.with(m,()=>l(t))}))}),u.setStatus({code:L.OK})}catch(l){this.runtimeLogger.error(`Error during instrumented handler execution for event ${s}:`,l),u.recordException(l),u.setStatus({code:L.ERROR,message:l.message})}finally{u.addEvent("processing_ended"),u.end()}}else try{await Promise.all(a.map(c=>c(t)))}catch(c){this.runtimeLogger.error(`Error during emitEvent for ${s} (handler execution):`,c)}}}async ensureEmbeddingDimension(){if(this.runtimeLogger.debug(`[AgentRuntime][${this.character.name}] Starting ensureEmbeddingDimension`),!this.adapter)throw new Error(`[AgentRuntime][${this.character.name}] Database adapter not initialized before ensureEmbeddingDimension`);try{if(!this.getModel(N.TEXT_EMBEDDING))throw new Error(`[AgentRuntime][${this.character.name}] No TEXT_EMBEDDING model registered`);this.runtimeLogger.debug(`[AgentRuntime][${this.character.name}] Getting embedding dimensions`);let t=await this.useModel(N.TEXT_EMBEDDING,null);if(!t||!t.length)throw new Error(`[AgentRuntime][${this.character.name}] Invalid embedding received`);this.runtimeLogger.debug(`[AgentRuntime][${this.character.name}] Setting embedding dimension: ${t.length}`),await this.adapter.ensureEmbeddingDimension(t.length),this.runtimeLogger.debug(`[AgentRuntime][${this.character.name}] Successfully set embedding dimension`)}catch(e){throw this.runtimeLogger.debug(`[AgentRuntime][${this.character.name}] Error in ensureEmbeddingDimension:`,e),e}}registerTaskWorker(e){this.taskWorkers.has(e.name)&&this.runtimeLogger.warn(`Task definition ${e.name} already registered. Will be overwritten.`),this.taskWorkers.set(e.name,e)}getTaskWorker(e){return this.taskWorkers.get(e)}get db(){return this.adapter.db}async init(){await this.adapter.init()}async close(){await this.adapter.close()}async getAgent(e){return await this.adapter.getAgent(e)}async getAgents(){return await this.adapter.getAgents()}async createAgent(e){return await this.adapter.createAgent(e)}async updateAgent(e,t){return await this.adapter.updateAgent(e,t)}async deleteAgent(e){return await this.adapter.deleteAgent(e)}async ensureAgentExists(e){return await this.adapter.ensureAgentExists(e)}async getEntityById(e){return await this.adapter.getEntityById(e)}async getEntitiesForRoom(e,t){return await this.adapter.getEntitiesForRoom(e,t)}async createEntity(e){return e.agentId||(e.agentId=this.agentId),await this.adapter.createEntity(e)}async updateEntity(e){await this.adapter.updateEntity(e)}async getComponent(e,t,r,s){return await this.adapter.getComponent(e,t,r,s)}async getComponents(e,t,r){return await this.adapter.getComponents(e,t,r)}async createComponent(e){return await this.adapter.createComponent(e)}async updateComponent(e){await this.adapter.updateComponent(e)}async deleteComponent(e){await this.adapter.deleteComponent(e)}async addEmbeddingToMemory(e){if(e.embedding)return e;let t=e.content.text;if(!t)throw new Error("Cannot generate embedding: Memory content is empty");try{e.embedding=await this.useModel(N.TEXT_EMBEDDING,{text:t})}catch(r){G.error("Failed to generate embedding:",r),e.embedding=await this.useModel(N.TEXT_EMBEDDING,null)}return e}async getMemories(e){return await this.adapter.getMemories(e)}async getMemoryById(e){return await this.adapter.getMemoryById(e)}async getMemoriesByIds(e,t){return await this.adapter.getMemoriesByIds(e,t)}async getMemoriesByRoomIds(e){return await this.adapter.getMemoriesByRoomIds(e)}async getCachedEmbeddings(e){return await this.adapter.getCachedEmbeddings(e)}async log(e){await this.adapter.log(e)}async searchMemories(e){let t=await this.adapter.searchMemories(e);return e.query?await this.rerankMemories(e.query,t):t}async rerankMemories(e,t){let r=t.map(o=>({title:o.id,content:o.content.text}));return new Je(r).search(e,t.length).map(o=>t[o.index])}async createMemory(e,t,r){return await this.adapter.createMemory(e,t,r)}async updateMemory(e){return await this.adapter.updateMemory(e)}async deleteMemory(e){await this.adapter.deleteMemory(e)}async deleteAllMemories(e,t){await this.adapter.deleteAllMemories(e,t)}async countMemories(e,t,r){return await this.adapter.countMemories(e,t,r)}async getLogs(e){return await this.adapter.getLogs(e)}async deleteLog(e){await this.adapter.deleteLog(e)}async createWorld(e){return await this.adapter.createWorld(e)}async getWorld(e){return await this.adapter.getWorld(e)}async getAllWorlds(){return await this.adapter.getAllWorlds()}async updateWorld(e){await this.adapter.updateWorld(e)}async getRoom(e){return await this.adapter.getRoom(e)}async createRoom({id:e,name:t,source:r,type:s,channelId:i,serverId:o,worldId:a}){return await this.adapter.createRoom({id:e,name:t,source:r,type:s,channelId:i,serverId:o,worldId:a})}async deleteRoom(e){await this.adapter.deleteRoom(e)}async updateRoom(e){await this.adapter.updateRoom(e)}async getRoomsForParticipant(e){return await this.adapter.getRoomsForParticipant(e)}async getRoomsForParticipants(e){return await this.adapter.getRoomsForParticipants(e)}async getRooms(e){return await this.adapter.getRooms(e)}async getParticipantUserState(e,t){return await this.adapter.getParticipantUserState(e,t)}async setParticipantUserState(e,t,r){await this.adapter.setParticipantUserState(e,t,r)}async createRelationship(e){return await this.adapter.createRelationship(e)}async updateRelationship(e){await this.adapter.updateRelationship(e)}async getRelationship(e){return await this.adapter.getRelationship(e)}async getRelationships(e){return await this.adapter.getRelationships(e)}async getCache(e){return await this.adapter.getCache(e)}async setCache(e,t){return await this.adapter.setCache(e,t)}async deleteCache(e){return await this.adapter.deleteCache(e)}async createTask(e){return await this.adapter.createTask(e)}async getTasks(e){return await this.adapter.getTasks(e)}async getTask(e){return await this.adapter.getTask(e)}async getTasksByName(e){return await this.adapter.getTasksByName(e)}async updateTask(e,t){await this.adapter.updateTask(e,t)}async deleteTask(e){await this.adapter.deleteTask(e)}on(e,t){this.eventHandlers.has(e)||this.eventHandlers.set(e,[]),this.eventHandlers.get(e).push(t)}off(e,t){if(!this.eventHandlers.has(e))return;let r=this.eventHandlers.get(e),s=r.indexOf(t);s!==-1&&r.splice(s,1)}emit(e,t){if(this.eventHandlers.has(e))for(let r of this.eventHandlers.get(e))r(t)}async sendControlMessage(e){try{let{roomId:t,action:r,target:s}=e,i={type:"control",payload:{action:r,target:s},roomId:t};await this.emitEvent("CONTROL_MESSAGE",{runtime:this,message:i,source:"agent"}),this.runtimeLogger.debug(`Sent control message: ${r} to room ${t}`)}catch(t){this.runtimeLogger.error(`Error sending control message: ${t}`)}}};import ve from"crypto-browserify";function Nd(n){return{name:n.name,description:n.description,usageDescription:n.usageDescription||"",value:null,required:n.required,validation:n.validation||null,public:n.public||!1,secret:n.secret||!1,dependsOn:n.dependsOn||[],onSetAction:n.onSetAction||null,visibleIf:n.visibleIf||null}}function X(){let n=(typeof process<"u"?process.env.SECRET_SALT:import.meta.env.SECRET_SALT)||"secretsalt";n||T.error("SECRET_SALT is not set");let e=n;return T.debug(`Generated salt with length: ${e.length} (truncated for security)`),e}function Bs(n,e){try{if(n==null)return T.debug("Attempted to encrypt undefined or null value"),n;if(typeof n=="boolean"||typeof n=="number")return T.debug("Value is a boolean or number, returning as is"),n;if(typeof n!="string")return T.debug(`Value is not a string (type: ${typeof n}), returning as is`),n;let t=n.split(":");if(t.length===2)try{if(Buffer.from(t[0],"hex").length===16)return T.debug("Value appears to be already encrypted, skipping re-encryption"),n}catch{}let r=ve.createHash("sha256").update(e).digest().slice(0,32),s=ve.randomBytes(16),i=ve.createCipheriv("aes-256-cbc",r,s),o=i.update(n,"utf8","hex");return o+=i.final("hex"),`${s.toString("hex")}:${o}`}catch(t){return T.error(`Error encrypting value: ${t}`),n}}function et(n,e){try{if(n==null)return T.debug("Attempted to decrypt undefined or null value"),n;if(typeof n=="boolean"||typeof n=="number")return T.debug("Value is a boolean or number, returning as is"),n;if(typeof n!="string")return T.debug(`Value is not a string (type: ${typeof n}), returning as is`),n;let t=n.split(":");if(t.length!==2)return T.debug("Invalid encrypted value format - expected 'iv:encrypted', returning original value"),n;let r=Buffer.from(t[0],"hex"),s=t[1];if(r.length!==16)return T.debug(`Invalid IV length (${r.length}) - expected 16 bytes`),n;let i=ve.createHash("sha256").update(e).digest().slice(0,32),o=ve.createDecipheriv("aes-256-cbc",i,r),a=o.update(s,"hex","utf8");return a+=o.final("utf8"),a}catch(t){return T.error(`Error decrypting value: ${t}`),n}}function Dd(n,e){let t={...n};return n.secret===!0&&typeof n.value=="string"&&n.value&&(t.value=Bs(n.value,e)),t}function xd(n,e){let t={...n};return n.secret===!0&&typeof n.value=="string"&&n.value&&(t.value=et(n.value,e)),t}function wd(n,e){let t={};for(let[r,s]of Object.entries(n))t[r]=Dd(s,e);return t}function Ws(n,e){let t={};for(let[r,s]of Object.entries(n))t[r]=xd(s,e);return t}async function _p(n,e,t){try{let r=B(n,e),s=await n.getWorld(r);if(!s)return T.error(`No world found for server ${e}`),!1;s.metadata||(s.metadata={});let i=X(),o=wd(t,i);return s.metadata.settings=o,await n.updateWorld(s),!0}catch(r){return T.error(`Error updating settings state: ${r}`),!1}}async function Sp(n,e){try{let t=B(n,e),r=await n.getWorld(t);if(!r||!r.metadata?.settings)return null;let s=r.metadata.settings,i=X();return Ws(s,i)}catch(t){return T.error(`Error getting settings state: ${t}`),null}}async function gp(n,e,t){try{if(e.metadata?.settings){T.info(`Onboarding state already exists for server ${e.serverId}`);let s=e.metadata.settings,i=X();return Ws(s,i)}let r={};if(t.settings)for(let[s,i]of Object.entries(t.settings))r[s]=Nd(i);return e.metadata||(e.metadata={}),e.metadata.settings=r,await n.updateWorld(e),T.info(`Initialized settings config for server ${e.serverId}`),r}catch(r){return T.error(`Error initializing settings config: ${r}`),null}}function fp(n){let e=JSON.parse(JSON.stringify(n)),t=X();return e.settings?.secrets&&(e.settings.secrets=Fs(e.settings.secrets,t)),e.secrets&&(e.secrets=Fs(e.secrets,t)),e}function Tp(n,e){let t=JSON.parse(JSON.stringify(n)),r=X();return t.settings?.secrets&&(t.settings.secrets=Gs(t.settings.secrets,r)),t.secrets&&(t.secrets=Gs(t.secrets,r)),t}function Fs(n,e){let t={};for(let[r,s]of Object.entries(n))typeof s=="string"&&s?t[r]=Bs(s,e):t[r]=s;return t}function Gs(n,e){let t={};for(let[r,s]of Object.entries(n))typeof s=="string"&&s?t[r]=et(s,e):t[r]=s;return t}import kd from"stream-browserify";import{Buffer as Fd}from"buffer";var{PassThrough:Vd,Readable:Rp}=kd;function Gd(n,e,t=1,r=16){let s=Fd.alloc(44);return s.write("RIFF",0),s.writeUInt32LE(36+n,4),s.write("WAVE",8),s.write("fmt ",12),s.writeUInt32LE(16,16),s.writeUInt16LE(1,20),s.writeUInt16LE(t,22),s.writeUInt32LE(e,24),s.writeUInt32LE(e*r*t/8,28),s.writeUInt16LE(r*t/8,32),s.writeUInt16LE(r,34),s.write("data",36),s.writeUInt32LE(n,40),s}function vp(n,e,t,r=1,s=16){let i=Gd(e,t,r,s),o=!1,a=new Vd;return n.on("data",c=>{o||(a.push(i),o=!0),a.push(c)}),n.on("end",()=>{a.end()}),a}function Me(){let n=new WeakSet;return function(e,t){if(typeof t=="object"&&t!==null){if(n.has(t))return"[Circular]";n.add(t)}return t}}function Pp(n){if(!n)return!1;let e=["YES","Y","TRUE","T","1","ON","ENABLE"],t=["NO","N","FALSE","F","0","OFF","DISABLE"],r=n.trim().toUpperCase();return e.includes(r)?!0:(t.includes(r),!1)}function Bd(n,e){let t=n.getSetting("CLOUDFLARE_GW_ENABLED")==="true",r=n.getSetting("CLOUDFLARE_AI_ACCOUNT_ID"),s=n.getSetting("CLOUDFLARE_AI_GATEWAY_ID");if(h.debug("Cloudflare Gateway Configuration:",{isEnabled:t,hasAccountId:!!r,hasGatewayId:!!s,provider:e}),!t){h.debug("Cloudflare Gateway is not enabled");return}if(!r){h.warn("Cloudflare Gateway is enabled but CLOUDFLARE_AI_ACCOUNT_ID is not set");return}if(!s){h.warn("Cloudflare Gateway is enabled but CLOUDFLARE_AI_GATEWAY_ID is not set");return}let i=`https://gateway.ai.cloudflare.com/v1/${r}/${s}/${e.toLowerCase()}`;return h.info("Using Cloudflare Gateway:",{provider:e,baseURL:i,accountId:r,gatewayId:s}),i}function Op(n,e,t){return Bd(n,e)??t}export{Vs as AgentRuntime,qs as AgentStatus,Hs as CacheKeyPrefix,Tr as ChannelType,Rr as DatabaseAdapter,yr as EventType,Xe as InstrumentationService,Ks as KnowledgeScope,fr as MemoryType,N as ModelType,js as PlatformPrefix,Ar as Role,Qs as SOCKET_MESSAGE_TYPE,_r as Semaphore,Pe as Service,Ue as ServiceType,$s as TEEMode,Ys as TeeType,il as VECTOR_DIMS,Al as addHeader,qd as asUUID,Pl as booleanFooter,cl as composeActionExamples,Ur as composePrompt,Tl as composePromptFromState,Lr as composeRandomUser,Kd as createMessageMemory,sl as createServiceError,Nd as createSettingFromConfig,B as createUniqueUuid,Gs as decryptObjectValues,et as decryptSecret,et as decryptStringValue,Tp as decryptedCharacter,h as elizaLogger,Fs as encryptObjectValues,Bs as encryptStringValue,fp as encryptedCharacter,wl as findEntityByName,Kl as findWorldsForOwner,ul as formatActionNames,dl as formatActions,Vl as formatEntities,Rl as formatMessages,yl as formatPosts,Or as formatTimestamp,Jd as getBrowserService,Bd as getCloudflareGatewayBaseURL,kl as getEntityDetails,el as getFileService,nl as getMemoryText,Zd as getPdfService,Op as getProviderBaseURL,X as getSalt,Hd as getTypedService,ql as getUserServerRole,Xd as getVideoService,Gd as getWavHeader,Sp as getWorldSettings,gp as initializeOnboarding,zd as isCustomMetadata,Qd as isDescriptionMetadata,tl as isDocumentMemory,$d as isDocumentMetadata,rl as isFragmentMemory,Yd as isFragmentMetadata,jd as isMessageMetadata,T as logger,vl as messageHandlerTemplate,vr as normalizeJsonString,Ll as parseActionResponseFromText,Pp as parseBooleanFromText,br as parseJSONObjectFromText,Ul as parseKeyValueXml,Il as postCreationTemplate,vp as prependWavHeader,Me as safeReplacer,Dd as saltSettingValue,wd as saltWorldSettings,Ml as shouldRespondTemplate,Cr as splitChunks,Le as stringToUuid,bl as trimTokens,Ol as truncateToCompleteSentence,xd as unsaltSettingValue,Ws as unsaltWorldSettings,_p as updateWorldSettings,Pr as upgradeDoubleToTriple,Ld as uuidSchema,ZE as validateUuid};
|
|
217
|
+
`,s=[e.trace_id,e.span_id,e.parent_span_id,e.trace_state,e.span_name,e.span_kind,e.start_time,e.end_time,e.duration_ms,e.status_code,e.status_message,JSON.stringify(e.attributes||{}),JSON.stringify(e.events||[]),JSON.stringify(e.links||[]),JSON.stringify(e.resource||{}),e.agent_id,e.session_id,e.environment,e.room_id];try{h.debug(`Executing direct insert for span: ${e.span_name}`),h.debug(`Span trace_id: ${e.trace_id}, span_id: ${e.span_id}`);let i=await this.pgClient.query(r,s);if(i.rows&&i.rows.length>0){let o=i.rows[0].id;h.info(`\u2705 Span inserted with ID ${o}: ${e.span_name}`)}else i.rowCount>0?h.info(`\u2705 Span inserted (rowCount=${i.rowCount}): ${e.span_name}`):h.warn(`\u26A0\uFE0F No row inserted for span (likely conflict): ${e.span_name}`);try{let o=`SELECT id FROM ${t} WHERE trace_id = $1 AND span_id = $2`,a=await this.pgClient.query(o,[e.trace_id,e.span_id]);a.rows.length>0?h.info(`\u2705 Verified span in database with ID ${a.rows[0].id}`):h.warn("\u26A0\uFE0F Verification failed: Span not found in database after insert")}catch(o){h.error(`\u274C Error verifying span insertion: ${o}`)}}catch(i){h.error("\u274C Error inserting span into PostgreSQL DB:",i),i instanceof Error&&(h.error(`Error message: ${i.message}`),h.error(`Error stack: ${i.stack}`)),h.error(`Failed span data: ${JSON.stringify({span_name:e.span_name,trace_id:e.trace_id,span_id:e.span_id,agent_id:e.agent_id,session_id:e.session_id,room_id:e.room_id})}`)}}shutdown(){return this.pgClient&&this.isConnected&&(this.pgClient.end(),this.isConnected=!1,h.info("PostgreSQL database connection closed")),Promise.resolve()}forceFlush(){return Promise.resolve()}},Xe=class n extends Pe{name="INSTRUMENTATION";capabilityDescription="Provides OpenTelemetry tracing and metrics capabilities.";instrumentationConfig;resource;tracerProvider=null;meterProvider=null;postgresSpanProcessor=null;isShutdown=!1;constructor(e){super();let t=e?.enabled||!1;this.instrumentationConfig={serviceName:e?.serviceName||process.env.OTEL_SERVICE_NAME||Ad,enabled:t},this.resource=new at({[Wr.SERVICE_NAME]:this.instrumentationConfig.serviceName}),this.isEnabled()?(this.initializeProviders(),h.info(`\u{1F4CA} Instrumentation Service configured as enabled for '${this.instrumentationConfig.serviceName}'.`)):h.info("\u{1F4CA} Instrumentation Service configured as disabled.")}initializeProviders(){if(!this.isEnabled())return;this.tracerProvider=new gd({resource:this.resource});let e=process.env.POSTGRES_URL_INSTRUMENTATION;if(!e)h.error("Cannot initialize PostgreSQL Span Processor: POSTGRES_URL_INSTRUMENTATION is not set.");else try{this.postgresSpanProcessor=new pr(e),this.postgresSpanProcessor&&this.postgresSpanProcessor.pgClient?(this.tracerProvider.addSpanProcessor(this.postgresSpanProcessor),h.info("\u{1F4CA} Added PostgreSQL span processor for telemetry data storage.")):h.error("Failed to add PostgreSQL span processor likely due to initialization errors.")}catch(t){h.error("Error creating PostgreSQL Span Processor instance:",t)}this.tracerProvider.register();try{h.info("Attempting to register PostgreSQL instrumentation..."),dt({tracerProvider:this.tracerProvider,instrumentations:[new Td({enhancedDatabaseReporting:!0})]}),h.info("\u2705 Successfully registered OpenTelemetry instrumentations (pg).")}catch(t){h.error("\u274C Failed to register instrumentations:",t)}this.meterProvider=new fd({resource:this.resource}),h.warn("Metrics export is currently disabled."),xs.setGlobalMeterProvider(this.meterProvider)}isEnabled(){return!!this.instrumentationConfig.enabled&&!this.isShutdown}getTracer(e,t){return!this.isEnabled()||!this.tracerProvider?Sd.getTracer(e||this.instrumentationConfig.serviceName,t):this.tracerProvider.getTracer(e||this.instrumentationConfig.serviceName,t)}getMeter(e,t){return xs.getMeter(e||this.instrumentationConfig.serviceName,t)}async flush(){if(!(!this.isEnabled()||this.isShutdown)){h.debug("\u{1F4CA} Flushing OpenTelemetry providers...");try{(await Promise.allSettled([this.tracerProvider?.forceFlush(),this.meterProvider?.forceFlush()])).forEach((t,r)=>{if(t.status==="rejected"){let s=r===0?"Tracer":"Meter";h.error(`Error flushing OpenTelemetry ${s} provider:`,t.reason)}}),h.debug("\u{1F4CA} OpenTelemetry providers flush attempt complete.")}catch(e){h.error("Unexpected error during instrumentation flush: ",e)}}}async stop(){if(!(!this.isEnabled()||this.isShutdown)){this.isShutdown=!0,h.info("\u{1F4CA} Shutting down Instrumentation Service...");try{(await Promise.allSettled([this.tracerProvider?.shutdown(),this.meterProvider?.shutdown()])).forEach((t,r)=>{if(t.status==="rejected"){let s=r===0?"Tracer":"Meter";h.error(`Error shutting down OpenTelemetry ${s} provider:`,t.reason)}}),h.info("\u{1F4CA} Instrumentation Service shutdown attempt complete.")}catch(e){h.error("Unexpected error during instrumentation shutdown: ",e)}}}static async start(e,t){return pd.setLogger(new hd,_d.DEBUG),new n(t)}};var q=n=>{switch(n){case 97:case 101:case 105:case 111:case 117:case 121:return!0;default:return!1}},yd=n=>{switch(n){case 97:case 101:case 105:case 111:case 117:case 121:case 119:case 120:case 89:return!0;default:return!1}},Rd=n=>{switch(n){case 99:case 100:case 101:case 103:case 104:case 107:case 109:case 110:case 114:case 116:return!0;default:return!1}},Md=n=>{switch(n){case 98:case 100:case 102:case 103:case 109:case 110:case 112:case 114:case 116:return!0;default:return!1}},ks=(n,e)=>e>=2&&q(n[e-2])&&(e===2&&!q(n[e-1])||e>=3&&!q(n[e-3])&&!yd(n[e-1])),vd=n=>{if(n.length<3)return n;if(n.length<=6)switch(n){case"ski":return"ski";case"skies":return"sky";case"dying":return"die";case"lying":return"lie";case"tying":return"tie";case"idly":return"idl";case"gently":return"gentl";case"ugly":return"ugli";case"early":return"earli";case"only":return"onli";case"singly":return"singl";case"sky":case"news":case"howe":case"atlas":case"cosmos":case"bias":case"andes":return n}for(var e=n.charCodeAt(0)===39?1:0,t=n.length-e,r=new Array(t),s=!1,i=0;i<t;++i){var o=n.charCodeAt(i+e);if(o===121&&(i===0||q(r[i-1]))){s=!0,r[i]=89;continue}r[i]=o}r[t-1]===39&&--t,t>=2&&r[t-2]===39&&r[t-1]===115&&(t-=2);for(var a=0;a<t&&!q(r[a]);)++a;a<t&&++a;var u=a;if(t>=5&&(r[0]===103&&r[1]===101&&r[2]===110&&r[3]===101&&r[4]===114||r[0]===97&&r[1]===114&&r[2]===115&&r[3]===101&&r[4]===110))u=5;else if(t>=6&&r[0]===99&&r[1]===111&&r[2]===109&&r[3]===109&&r[4]===117&&r[5]===110)u=6;else{for(;u<t&&q(r[u]);)++u;u<t&&++u}for(var c=u,d=!1;c<t&&!q(r[c]);)++c;for(;c<t&&q(r[c]);)++c;if(c<t&&++c,t>=3&&(r[t-1]===115?t>=4&&r[t-2]===101&&r[t-3]===115&&r[t-4]===115?t-=2:r[t-2]===101&&r[t-3]===105?t-=t>=5?2:1:r[t-2]!==117&&r[t-2]!==115&&a<t-1&&(t-=1):r[t-1]===100&&r[t-2]===101&&r[t-3]===105&&(t-=t>=5?2:1)),t===6&&(r[0]===105&&r[1]===110&&r[2]===110&&r[3]===105&&r[4]===110&&r[5]===103||r[0]===111&&r[1]===117&&r[2]===116&&r[3]===105&&r[4]===110&&r[5]===103||r[0]===101&&r[1]===120&&r[2]===99&&r[3]===101&&r[4]===101&&r[5]===100)||t===7&&(r[0]===99&&r[1]===97&&r[2]===110&&r[3]===110&&r[4]===105&&r[5]===110&&r[6]===103||r[0]===104&&r[1]===101&&r[2]===114&&r[3]===114&&r[4]===105&&r[5]===110&&r[6]===103||r[0]===101&&r[1]===97&&r[2]===114&&r[3]===114&&r[4]===105&&r[5]===110&&r[6]===103||r[0]===112&&r[1]===114&&r[2]===111&&r[3]===99&&r[4]===101&&r[5]===101&&r[6]===100||r[0]===115&&r[1]===117&&r[2]===99&&r[3]===99&&r[4]===101&&r[5]===101&&r[6]===100)){for(var l="",i=0;i<t;++i)l+=String.fromCharCode(r[i]);return l}var m=t>=2&&r[t-1]===121&&r[t-2]===108?t-2:t;if(m>=3&&(r[m-3]===101&&r[m-2]===101&&r[m-1]===100?m>=u+3&&(t=m-1):(r[m-2]===101&&r[m-1]===100?m-=2:r[m-3]===105&&r[m-2]===110&&r[m-1]===103?m-=3:m=-1,m>=0&&a<=m&&(t=m,t>=2&&(r[t-1]===116&&r[t-2]===97||r[t-1]===108&&r[t-2]===98||r[t-1]===122&&r[t-2]===105?(r[t]=101,++t):r[t-2]===r[t-1]&&Md(r[t-1])?--t:u>=t&&ks(r,t)&&(r[t]=101,++t))))),t>=3&&(r[t-1]===89||r[t-1]===121)&&!q(r[t-2])&&(r[t-1]=105),t>=u+2)switch(r[t-1]){case 108:t>=u+6&&r[t-2]===97&&r[t-3]===110&&r[t-4]===111&&r[t-5]===105&&r[t-6]===116&&(t>=7&&r[t-7]===97?t>=u+7&&(t-=4,r[t-1]=101):t-=2);break;case 110:t>=u+5&&r[t-2]===111&&r[t-3]===105&&r[t-4]===116&&r[t-5]===97&&(t>=7&&r[t-6]===122&&r[t-7]===105?t>=u+7&&(t-=4,r[t-1]=101):(t-=2,r[t-1]=101));break;case 114:t>=u+4&&(r[t-2]===101?r[t-3]===122&&r[t-4]===105&&--t:r[t-2]===111&&r[t-3]===116&&r[t-4]===97&&(--t,r[t-1]=101));break;case 115:t>=u+7&&r[t-2]===115&&r[t-3]===101&&r[t-4]===110&&(r[t-5]===108&&r[t-6]===117&&r[t-7]===102||r[t-5]===115&&r[t-6]===117&&r[t-7]===111||r[t-5]===101&&r[t-6]===118&&r[t-7]===105)&&(t-=4);break;case 109:t>=u+5&&r[t-2]===115&&r[t-3]===105&&r[t-4]===108&&r[t-5]===97&&(t-=3);break;case 105:r[t-2]===99?t>=u+4&&(r[t-4]===101||r[t-4]===97)&&r[t-3]===110&&(r[t-1]=101):r[t-2]===103?t>=u+3&&t>=4&&r[t-2]===103&&r[t-3]===111&&r[t-4]===108&&--t:r[t-2]===116?t>=u+5&&r[t-3]===105&&(r[t-4]===108?t>=6&&r[t-5]===105&&r[t-6]===98?t>=u+6&&(t-=3,r[t-2]=108,r[t-1]=101):r[t-4]===108&&r[t-5]===97&&(t-=3):r[t-4]===118&&r[t-5]===105&&(t-=2,r[t-1]=101)):r[t-2]===108&&t>=3&&(r[t-3]===98?t>=4&&r[t-4]===97?t>=u+4&&(r[t-1]=101):t>=u+3&&(r[t-1]=101):r[t-3]===108?t>=5&&r[t-4]===117&&r[t-5]===102?t>=u+5&&(t-=2):t>=u+4&&r[t-4]===97&&(t-=2):r[t-3]===115?t>=6&&r[t-4]===115&&r[t-5]===101&&r[t-6]===108?t>=u+6&&(t-=2):t>=u+5&&r[t-4]===117&&r[t-5]===111&&(t-=2):t>=5&&r[t-3]===116&&r[t-4]===110&&r[t-5]===101?t>=u+5&&(t-=2):Rd(r[t-3])&&(t-=2))}if(t>=u+3)switch(r[t-1]){case 108:r[t-3]===99?t>=u+4&&r[t-4]===105&&r[t-2]===97&&(t-=2):r[t-3]===102?r[t-2]===117&&(t-=3):r[t-3]===110&&t>=u+6&&r[t-2]===97&&r[t-4]===111&&r[t-5]===105&&r[t-6]===116&&(t>=7&&r[t-7]===97?t>=u+7&&(t-=4,r[t-1]=101):t-=2);break;case 101:r[t-2]===122?t>=u+5&&r[t-3]===105&&r[t-4]===108&&r[t-5]===97&&(t-=3):r[t-2]===116?t>=u+5&&r[t-3]===97&&r[t-4]===99&&r[t-5]===105&&(t-=3):r[t-2]===118&&t>=c+5&&r[t-3]===105&&r[t-4]===116&&r[t-5]===97&&(t-=5);break;case 105:t>=u+5&&r[t-2]===116&&r[t-3]===105&&r[t-4]===99&&r[t-5]===105&&(t-=3);break;case 115:t>=u+4&&r[t-2]===115&&r[t-3]===101&&r[t-4]===110&&(t-=4)}if(t>=c+2)switch(r[t-1]){case 110:t>=c+3&&r[t-2]===111&&r[t-3]===105&&(r[t-4]===115||r[t-4]===116)&&(t-=3);break;case 108:r[t-2]===97&&(t-=2);break;case 114:r[t-2]===101&&(t-=2);break;case 99:r[t-2]===105&&(t-=2);break;case 109:t>=c+3&&r[t-2]===115&&r[t-3]===105&&(t-=3);break;case 105:t>=c+3&&r[t-2]===116&&r[t-3]===105&&(t-=3);break;case 115:t>=c+3&&r[t-2]===117&&r[t-3]===111&&(t-=3);break;case 116:t>=c+3&&r[t-2]===110&&(r[t-3]===97?t-=3:r[t-3]===101&&(t>=4&&r[t-4]===109?t>=5&&r[t-5]===101?t>=c+5&&(t-=5):t>=c+4&&(t-=4):t-=3));break;case 101:r[t-2]===99?t>=c+4&&r[t-3]===110&&(r[t-4]===97||r[t-4]===101)&&(t-=4):r[t-2]===108?t>=c+4&&r[t-3]===98&&(r[t-4]===97||r[t-4]===105)&&(t-=4):r[t-2]===116?t>=c+3&&r[t-3]===97&&(t-=3):t>=c+3&&(r[t-2]===118||r[t-2]===122)&&r[t-3]===105&&(t-=3)}t>=u+1&&(t>=c+1&&r[t-1]===108&&r[t-2]===108||r[t-1]===101&&(t>=c+1||!ks(r,t-1)))&&--t;var E="";if(s)for(var i=0;i<t;++i)E+=String.fromCharCode(r[i]===89?121:r[i]);else for(var i=0;i<t;++i)E+=String.fromCharCode(r[i]);return E},Id={k1:1.2,b:.75,minLength:2,stopWords:new Set(["a","an","and","are","as","at","be","by","for","from","has","he","in","is","it","its","of","on","that","the","to","was","were","will","with"]),stemming:!1,stemWords:n=>n},hr=class n{stopWords;minLength;stemming;stemmingRules;static DEFAULT_OPTIONS={stopWords:new Set,minLength:2,stemming:!1,stemmingRules:[]};constructor(e={}){let t={...n.DEFAULT_OPTIONS,...e};this.stopWords=t.stopWords,this.minLength=t.minLength,this.stemming=t.stemming,this.stemmingRules=t.stemmingRules.map(r=>({...r,pattern:typeof r.pattern=="string"?new RegExp(r.pattern):r.pattern}))}tokenize(e,t=!1){if(!e)throw new Error("Input text cannot be null or empty");let r=Date.now(),s=e.split(/\s+/).filter(u=>u.length>0),o=this.cleanText(e).split(/\s+/).filter(u=>this.isValidToken(u)).map(u=>this.stemming?this.stemWord(u):u),a=t?{originalWordCount:s.length,stopWordsRemoved:s.length-o.length,stemmedWords:this.stemming?o.length:0,processingTimeMs:Date.now()-r}:{originalWordCount:0,stopWordsRemoved:0,stemmedWords:0,processingTimeMs:0};return{tokens:o,stats:a}}cleanText(e){return e.toLowerCase().normalize("NFKD").replace(/[\u0000-\u001F\u007F-\u009F\u200B-\u200D\uFEFF]/g,"").replace(/[\u0300-\u036f]/g,"").replace(/[\p{Emoji_Presentation}\p{Extended_Pictographic}]/gu,"").replace(/[™®©℠‼]/g,"").replace(/[\p{P}]/gu," ").replace(/[^a-z0-9\u3040-\u30FF\u3400-\u4DBF\u4E00-\u9FFF\uAC00-\uD7AF\s]/gu," ").replace(/\s+/g," ").trim()}isValidToken(e){let t=/^\d+$/.test(e);return(e.length>=this.minLength||t)&&!this.stopWords.has(e)}stemWord(e){if(e.length<3)return e;let t=!1,r=e;for(let s of this.stemmingRules)r.match(s.pattern)&&(t=!0,(!s.minMeasure||this.measure(r)>=s.minMeasure)&&(s.replacement,r=r.replace(s.pattern,s.replacement)));return t||(r=vd(r)),r}isConsonant(e,t){let r=e[t];return"aeiou".includes(r)?!1:r!=="y"||(t===0?!0:!this.isConsonant(e,t-1))}measure(e){let t=0,r=!1;for(let s=0;s<e.length;s++)this.isConsonant(e,s)?r&&(t++,r=!1):r=!0;return t}},Je=class{termFrequencySaturation;lengthNormalizationFactor;tokenizer;documentLengths;averageDocLength;termToIndex;documentFrequency;termFrequencies;fieldBoosts;documents;constructor(e,t={}){console.log("*** docs",e);let r={...Id,...t};if(this.termFrequencySaturation=r.k1,this.lengthNormalizationFactor=r.b,this.tokenizer=new hr(r),this.fieldBoosts=r.fieldBoosts||{},this.documents=[],this.documentLengths=new Uint32Array(0),this.termToIndex=new Map,this.documentFrequency=new Uint32Array(0),this.averageDocLength=0,this.termFrequencies=new Map,e&&e.length>0){console.log("doing indexing"),this.documents=[...e];let{documentLengths:s,termToIndex:i,documentFrequency:o,averageDocLength:a,termFrequencies:u}=this.processDocuments(e);this.documentLengths=s,this.termToIndex=i,this.documentFrequency=o,this.averageDocLength=a,this.termFrequencies=u}}processDocuments(e){console.log("*** processing documents");let t=e.length,r=new Uint32Array(t),s=new Map,i=new Map,o=new Map,a=0,u=0;e.forEach((d,l)=>{console.log("*** doc",d);let m=0,E=new Map;Object.entries(d).forEach(([p,g])=>{if(typeof g!="string")return;let A=this.fieldBoosts[p]||1,{tokens:R}=this.tokenizer.tokenize(g),O=R.length*A;m+=O,R.forEach(M=>{s.has(M)||s.set(M,u++);let S=s.get(M);i.has(M)||i.set(M,new Set),i.get(M).add(l);let C=E.get(S)||0;E.set(S,C+A)})}),r[l]=m,a+=m,E.forEach((p,g)=>{o.has(g)||o.set(g,new Map),o.get(g).set(l,p)})});let c=new Uint32Array(s.size);return i.forEach((d,l)=>{let m=s.get(l);c[m]=d.size}),{documentLengths:r,termToIndex:s,documentFrequency:c,averageDocLength:t>0?a/t:0,termFrequencies:o}}async addDocumentsParallel(e){if(!e||e.length===0)return;let t,r;try{t=(await import("worker_threads")).Worker,r=await import("os")}catch(a){throw console.error("Failed to load Node.js modules for parallel processing (worker_threads, os):",a),new Error("`addDocumentsParallel` failed to load required Node.js modules. This method is likely not supported in the current environment (e.g., browser, Deno, Bun worker without --allow-node-builtins).")}let s=Math.max(1,Math.floor(r.cpus().length/2)),i=Math.ceil(e.length/s),o=[];try{let a=Array.from({length:s},(m,E)=>{let p=E*i,g=Math.min(p+i,e.length);if(p>=g)return Promise.resolve(null);let A=new t(new URL("./worker.js",import.meta.url),{workerData:{docs:e.slice(p,g),tokenizerOptions:{stopWords:Array.from(this.tokenizer.stopWords),minLength:this.tokenizer.minLength,stemming:this.tokenizer.stemming,stemmingRules:this.tokenizer.stemmingRules.map(R=>({...R,pattern:R.pattern.toString()}))},fieldBoosts:this.fieldBoosts,startIndex:this.documents.length+p}});return o.push(A),new Promise((R,O)=>{A.on("message",M=>{M&&M.termFrequencies&&(M.termFrequencies=new Map(M.termFrequencies.map(([S,C])=>[S,new Map(C)]))),M&&M.termToIndex&&(M.termToIndex=new Map(M.termToIndex)),R(M)}),A.on("error",O),A.on("exit",M=>{M!==0&&O(new Error(`Worker stopped with exit code ${M}`))})})}),u=(await Promise.all(a)).filter(m=>m!==null),c=this.documentLengths.length,d=e.length,l=new Uint32Array(c+d);l.set(this.documentLengths,0),this.documents.push(...e),u.forEach(m=>{m&&(l.set(m.documentLengths,m.startIndex),m.termToIndex.forEach((E,p)=>{let g;this.termToIndex.has(p)?g=this.termToIndex.get(p):(g=this.termToIndex.size,this.termToIndex.set(p,g));let A=m.termFrequencies.get(E);if(A){this.termFrequencies.has(g)||this.termFrequencies.set(g,new Map);let R=this.termFrequencies.get(g);A.forEach((O,M)=>{R.set(M,O)})}}))}),this.documentLengths=l,this.updateDocumentFrequency(),this.recalculateAverageLength()}finally{o.forEach(a=>a.terminate())}}updateDocumentFrequency(){let e=this.termToIndex.size;if(this.documentFrequency.length<e){let t=this.documentFrequency;this.documentFrequency=new Uint32Array(Math.max(e,t.length*2)),this.documentFrequency.set(t,0)}else this.documentFrequency.length>e&&this.documentFrequency.fill(0,e);this.termFrequencies.forEach((t,r)=>{this.documentFrequency[r]=t.size});for(let t=this.termFrequencies.size;t<this.documentFrequency.length;t++)this.documentFrequency[t]=0}recalculateAverageLength(){if(this.documentLengths.length===0){this.averageDocLength=0;return}let e=Array.prototype.reduce.call(this.documentLengths,(t,r)=>t+r,0);this.averageDocLength=e/this.documentLengths.length}search(e,t=10){let{tokens:r}=this.tokenizer.tokenize(e),s=new Float32Array(this.documentLengths.length).fill(0);return r.forEach(i=>{let o=this.termToIndex.get(i);if(o===void 0)return;let a=this.calculateIDF(o);if(a<=0)return;let u=this.termFrequencies.get(o);u&&u.forEach((c,d)=>{let l=this.documentLengths[d],m=c*(this.termFrequencySaturation+1),E=c+this.termFrequencySaturation*(1-this.lengthNormalizationFactor+this.lengthNormalizationFactor*l/this.averageDocLength);s[d]+=a*(m/E)})}),Array.from({length:s.length},(i,o)=>({index:o,score:s[o]})).filter(i=>i.score>0).sort((i,o)=>o.score-i.score).slice(0,t)}searchPhrase(e,t=10){let{tokens:r}=this.tokenizer.tokenize(e);if(r.length===0)return[];let s=null;for(let o of r){let a=this.termToIndex.get(o);if(a===void 0)return[];let u=this.termFrequencies.get(a)?.keys();if(!u)return[];let c=new Set(u);if(s===null?s=c:s=new Set([...s].filter(d=>c.has(d))),s.size===0)return[]}if(s===null||s.size===0)return[];let i=new Map;return s.forEach(o=>{let a=this.getDocument(o),u=!1;Object.entries(a).forEach(([c,d])=>{if(typeof d!="string"||u)return;let l=this.fieldBoosts[c]||1,{tokens:m}=this.tokenizer.tokenize(d);for(let E=0;E<=m.length-r.length;E++){let p=!0;for(let g=0;g<r.length;g++)if(m[E+g]!==r[g]){p=!1;break}if(p){let g=this.calculatePhraseScore(r,o)*l;i.set(o,(i.get(o)||0)+g),u=!0;break}}})}),Array.from(i.entries()).map(([o,a])=>({index:o,score:a})).sort((o,a)=>a.score-o.score).slice(0,t)}calculatePhraseScore(e,t){return e.reduce((r,s)=>{let i=this.termToIndex.get(s);if(i===void 0)return r;let o=this.calculateIDF(i),a=this.termFrequencies.get(i)?.get(t)||0,u=this.documentLengths[t],c=a*(this.termFrequencySaturation+1),d=a+this.termFrequencySaturation*(1-this.lengthNormalizationFactor+this.lengthNormalizationFactor*u/this.averageDocLength);return r+o*(c/d)},0)}async addDocument(e){if(!e)throw new Error("Document cannot be null");let t=this.documentLengths.length;this.documents.push(e);let r=new Uint32Array(t+1);r.set(this.documentLengths,0),this.documentLengths=r;let s=0,i=new Map;Object.entries(e).forEach(([o,a])=>{if(typeof a!="string")return;let u=this.fieldBoosts[o]||1,{tokens:c}=this.tokenizer.tokenize(a);s+=c.length*u,c.forEach(d=>{let l;if(this.termToIndex.has(d))l=this.termToIndex.get(d);else{if(l=this.termToIndex.size,this.termToIndex.set(d,l),this.documentFrequency.length<=l){let E=this.documentFrequency,p=Math.max(l+1,E.length*2);this.documentFrequency=new Uint32Array(p),this.documentFrequency.set(E,0)}this.documentFrequency[l]=0}let m=i.get(l)||0;i.set(l,m+u)})}),this.documentLengths[t]=s,i.forEach((o,a)=>{this.termFrequencies.has(a)||this.termFrequencies.set(a,new Map),this.termFrequencies.get(a).set(t,o),this.documentFrequency[a]++}),this.recalculateAverageLength()}calculateIDF(e){if(e<0||e>=this.documentFrequency.length)return 0;let t=this.documentFrequency[e];if(t<=0||t>this.documentLengths.length)return 0;let s=this.documentLengths.length-t+.5,i=t+.5;return Math.log(1+s/i)}getTermFrequency(e,t){return this.termFrequencies.get(e)?.get(t)||0}getDocument(e){if(e<0||e>=this.documents.length)throw new Error(`Document index ${e} out of bounds (0-${this.documents.length-1})`);return this.documents[e]}clearDocuments(){this.documents=[],this.documentLengths=new Uint32Array(0),this.termToIndex.clear(),this.documentFrequency=new Uint32Array(0),this.averageDocLength=0,this.termFrequencies.clear()}getDocumentCount(){return this.documents.length}async addDocuments(e){await Promise.all(e.map(t=>this.addDocument(t)))}};import{sha1 as Pd}from"js-sha1";import{z as Ud}from"zod";var Ld=Ud.string().uuid();function JE(n){let e=Ld.safeParse(n);return e.success?e.data:null}function Le(n){if(typeof n=="number"&&(n=n.toString()),typeof n!="string")throw TypeError("Value must be string");let e=a=>{let u=a>>4,c=a-(u<<4),d="0123456789abcdef".split("");return d[u]+d[c]},t=a=>{let u="";for(let c=0;c<a.length;c++)u+=e(a[c]);return u},r=encodeURIComponent(n),s=new Uint8Array(r.length);for(let a=0;a<r.length;a++)s[a]=r[a].charCodeAt(0);let i=Pd(s),o=new Uint8Array(i.length/2);for(let a=0;a<i.length;a+=2)o[a/2]=Number.parseInt(i.slice(a,a+2),16);return`${t(o.slice(0,4))}-${t(o.slice(4,6))}-${e(o[6]&15)}${e(o[7])}-${e(o[8]&63|128)}${e(o[9])}-${t(o.slice(10,16))}`}var Cd={},_r=class{permits;waiting=[];constructor(e){this.permits=e}async acquire(){return this.permits>0?(this.permits-=1,Promise.resolve()):new Promise(e=>{this.waiting.push(e)})}release(){this.permits+=1;let e=this.waiting.shift();e&&this.permits>0&&(this.permits-=1,e())}},Vs=class{#e=32;agentId;character;adapter;actions=[];evaluators=[];providers=[];plugins=[];isInitialized=!1;events=new Map;stateCache=new Map;fetch=fetch;services=new Map;models=new Map;routes=[];taskWorkers=new Map;eventHandlers=new Map;runtimeLogger;knowledgeProcessingSemaphore=new _r(10);settings;servicesInitQueue=new Set;instrumentationService;tracer;constructor(e){this.agentId=e.character?.id??e?.agentId??Le(e.character?.name??bd()),this.character=e.character;let t=process.env.LOG_LEVEL||"info";this.runtimeLogger=G.child({agentName:this.character?.name,agentId:this.agentId,level:t==="debug"?"debug":"error"}),this.runtimeLogger.debug(`[AgentRuntime] Process working directory: ${process.cwd()}`),this.#e=e.conversationLength??this.#e,e.adapter&&this.registerDatabaseAdapter(e.adapter),this.fetch=e.fetch??this.fetch,this.settings=e.settings??Cd;let r=e?.plugins??[];this.plugins=r;try{this.instrumentationService=new Xe({serviceName:`agent-${this.character?.name||"unknown"}-${this.agentId}`,enabled:process.env.INSTRUMENTATION_ENABLED==="true"}),this.tracer=this.instrumentationService.getTracer("agent-runtime"),this.runtimeLogger.debug(`Instrumentation service initialized for agent ${this.agentId}`)}catch(s){this.runtimeLogger.warn(`Failed to initialize instrumentation: ${s.message}`),this.instrumentationService={getTracer:()=>null,start:async()=>{},stop:async()=>{},isStarted:()=>!1,isEnabled:()=>!1,name:"INSTRUMENTATION",capabilityDescription:"Disabled instrumentation service (fallback)",instrumentationConfig:{enabled:!1},getMeter:()=>null,flush:async()=>{}},this.tracer=null}this.runtimeLogger.debug(`Success: Agent ID: ${this.agentId}`)}async startSpan(e,t,r){return!this.instrumentationService?.isEnabled?.()||!this.tracer?t({setStatus:()=>{},setAttribute:()=>{},setAttributes:()=>{},recordException:()=>{},addEvent:()=>{},end:()=>{},isRecording:()=>!1,spanContext:()=>({traceId:"",spanId:"",traceFlags:0}),updateName:()=>{},addLink:()=>{},addLinks:()=>{}}):this.tracer.startActiveSpan(e,r,void 0,async s=>{try{s.setAttributes({"agent.id":this.agentId,"agent.name":this.character?.name||"unknown"});let i=await t(s);return s.setStatus({code:L.OK}),s.end(),i}catch(i){throw s.recordException(i),s.setStatus({code:L.ERROR,message:i.message}),s.end(),i}})}endSpan(e,t){}startActiveSpan(e,t={}){return!this.instrumentationService?.isEnabled?.()||!this.tracer?{setStatus:()=>{},setAttribute:()=>{},setAttributes:()=>{},recordException:()=>{},addEvent:()=>{},end:()=>{},isRecording:()=>!1,spanContext:()=>({traceId:"",spanId:"",traceFlags:0}),updateName:()=>{},addLink:()=>{},addLinks:()=>{}}:this.tracer.startSpan(e,t)}async registerPlugin(e){return this.startSpan("AgentRuntime.registerPlugin",async t=>{if(t.setAttributes({"plugin.name":e?.name||"unknown","agent.id":this.agentId}),!e)throw t.setStatus({code:L.ERROR,message:"Plugin is undefined"}),this.runtimeLogger.error("*** registerPlugin plugin is undefined"),new Error("*** registerPlugin plugin is undefined");if(this.plugins.some(r=>r.name===e.name)||(this.plugins.push(e),t.addEvent("plugin_added_to_array"),this.runtimeLogger.debug(`Success: Plugin ${e.name} registered successfully`)),e.init)try{t.addEvent("initializing_plugin"),await e.init(e.config||{},this),t.addEvent("plugin_initialized"),this.runtimeLogger.debug(`Success: Plugin ${e.name} initialized successfully`)}catch(r){let s=r instanceof Error?r.message:String(r);if(t.setAttributes({"error.message":s,"error.type":r instanceof Error?r.constructor.name:"Unknown"}),s.includes("API key")||s.includes("environment variables")||s.includes("Invalid plugin configuration"))console.warn(`Plugin ${e.name} requires configuration. ${s}`),console.warn("Please check your environment variables and ensure all required API keys are set."),console.warn("You can set these in your .eliza/.env file."),t.addEvent("plugin_configuration_warning");else throw t.setStatus({code:L.ERROR,message:s}),r}if(e.adapter&&(t.addEvent("registering_adapter"),this.runtimeLogger.debug(`Registering database adapter for plugin ${e.name}`),this.registerDatabaseAdapter(e.adapter)),e.actions){t.addEvent("registering_actions");for(let r of e.actions)this.registerAction(r)}if(e.evaluators){t.addEvent("registering_evaluators");for(let r of e.evaluators)this.registerEvaluator(r)}if(e.providers){t.addEvent("registering_providers");for(let r of e.providers)this.registerContextProvider(r)}if(e.models){t.addEvent("registering_models");for(let[r,s]of Object.entries(e.models))this.registerModel(r,s)}if(e.routes){t.addEvent("registering_routes");for(let r of e.routes)this.routes.push(r)}if(e.events){t.addEvent("registering_events");for(let[r,s]of Object.entries(e.events))for(let i of s)this.registerEvent(r,i)}if(e.services){t.addEvent("registering_services");for(let r of e.services)this.isInitialized?await this.registerService(r):this.servicesInitQueue.add(r)}t.addEvent("plugin_registration_complete")})}getAllServices(){return this.services}async stop(){return this.startSpan("AgentRuntime.stop",async e=>{e.setAttributes({"agent.id":this.agentId,"agent.name":this.character?.name||"unknown"}),this.runtimeLogger.debug(`runtime::stop - character ${this.character.name}`),e.addEvent("stopping_services");for(let[t,r]of this.services)this.runtimeLogger.debug(`runtime::stop - requesting service stop for ${t}`),e.addEvent(`stopping_service_${t}`),await r.stop();e.addEvent("all_services_stopped")})}async initialize(){return this.startSpan("AgentRuntime.initialize",async e=>{if(e.setAttributes({"agent.id":this.agentId,"agent.name":this.character?.name||"unknown","plugins.count":this.plugins.length}),this.isInitialized){e.addEvent("agent_already_initialized"),this.runtimeLogger.warn("Agent already initialized");return}e.addEvent("initialization_started");let t=new Set,r=[];for(let i of[...this.plugins])i&&!t.has(i.name)&&(t.add(i.name),r.push(await this.registerPlugin(i)));if(e.addEvent("plugins_setup"),e.setAttributes({registered_plugins:Array.from(t).join(",")}),!this.adapter)throw this.runtimeLogger.error("Database adapter not initialized. Make sure @elizaos/plugin-sql is included in your plugins."),new Error("Database adapter not initialized. The SQL plugin (@elizaos/plugin-sql) is required for agent initialization. Please ensure it is included in your character configuration.");try{await this.adapter.init(),e.addEvent("adapter_initialized");let i=await this.adapter.ensureAgentExists(this.character);if(e.addEvent("agent_exists_verified"),!i){let a=`Agent ${this.character.name} does not exist in database after ensureAgentExists call`;throw e.setStatus({code:L.ERROR,message:a}),new Error(a)}let o=await this.adapter.getEntityById(this.agentId);if(o)e.addEvent("agent_entity_exists");else{if(e.addEvent("creating_agent_entity"),!await this.createEntity({id:this.agentId,agentId:i.id,names:Array.from(new Set([this.character.name].filter(Boolean))),metadata:{}})){let u=`Failed to create entity for agent ${this.agentId}`;throw e.setStatus({code:L.ERROR,message:u}),new Error(u)}if(o=await this.adapter.getEntityById(this.agentId),!o)throw new Error(`Agent entity not found for ${this.agentId}`);this.runtimeLogger.debug(`Success: Agent entity created successfully for ${this.character.name}`),e.addEvent("agent_entity_created")}}catch(i){let o=i instanceof Error?i.message:String(i);throw e.recordException(i),e.setStatus({code:L.ERROR,message:o}),this.runtimeLogger.error(`Failed to create agent entity: ${o}`),i}try{e.addEvent("creating_group_and_registering_plugins"),await Promise.all([this.ensureRoomExists({id:this.agentId,name:this.character.name,source:"self",type:"SELF"}),...r]),e.addEvent("room_created_and_plugins_registered")}catch(i){let o=i instanceof Error?i.message:String(i);throw e.recordException(i),e.setStatus({code:L.ERROR,message:o}),this.runtimeLogger.error(`Failed to initialize: ${o}`),i}try{if(e.addEvent("adding_agent_as_participant"),(await this.adapter.getParticipantsForRoom(this.agentId)).includes(this.agentId))e.addEvent("agent_already_participant");else{if(!await this.adapter.addParticipant(this.agentId,this.agentId)){let a=`Failed to add agent ${this.agentId} as participant to its own room`;throw e.setStatus({code:L.ERROR,message:a}),new Error(a)}this.runtimeLogger.debug(`Agent ${this.character.name} linked to its own room successfully`),e.addEvent("agent_added_as_participant")}}catch(i){let o=i instanceof Error?i.message:String(i);throw e.recordException(i),e.setStatus({code:L.ERROR,message:o}),this.runtimeLogger.error(`Failed to add agent as participant: ${o}`),i}if(this.getModel(N.TEXT_EMBEDDING)?(e.addEvent("setting_up_embedding_dimension"),await this.ensureEmbeddingDimension(),e.addEvent("embedding_dimension_setup_complete")):(e.addEvent("embedding_model_missing"),this.runtimeLogger.warn(`[AgentRuntime][${this.character.name}] No TEXT_EMBEDDING model registered. Skipping embedding dimension setup.`)),this.character?.knowledge&&this.character.knowledge.length>0){e.addEvent("processing_character_knowledge"),e.setAttributes({"knowledge.count":this.character.knowledge.length});let i=this.character.knowledge.filter(o=>typeof o=="string");await this.processCharacterKnowledge(i),e.addEvent("character_knowledge_processed")}e.addEvent("starting_deferred_services"),e.setAttributes({"deferred_services.count":this.servicesInitQueue.size});for(let i of this.servicesInitQueue)await this.registerService(i);e.addEvent("initialization_completed")})}async handleProcessingError(e,t){throw this.runtimeLogger.error(`Error ${t}:`,e?.message||e||"Unknown error"),e}async checkExistingKnowledge(e){return!!await this.getMemoryById(e)}async getKnowledge(e,t){return console.log("*** getKnowledge",e),this.startSpan("AgentRuntime.getKnowledge",async r=>{if(!e?.content?.text)return r.addEvent("invalid_message"),r.setStatus({code:L.ERROR,message:"Invalid message for knowledge query"}),this.runtimeLogger.warn("Invalid message for knowledge query:",{message:e,content:e?.content,text:e?.content?.text}),[];if(!e?.content?.text||e?.content?.text.trim().length===0)return r.addEvent("empty_text"),r.setStatus({code:L.ERROR,message:"Empty text for knowledge query"}),this.runtimeLogger.warn("Empty text for knowledge query"),[];r.setAttributes({"message.id":e.id,"query.length":e.content.text.length,"agent.id":this.agentId}),r.addEvent("generating_embedding");let s=await this.useModel(N.TEXT_EMBEDDING,{text:e?.content?.text});r.addEvent("searching_memories"),r.setAttributes({"embedding.length":s.length}),console.log("*** searching memories");let i={};t?.roomId&&(i.roomId=t.roomId),t?.worldId&&(i.worldId=t.worldId),t?.entityId&&(i.entityId=t.entityId),r.addEvent("determined_filter_scope",{...i.roomId&&{"filter.roomId":i.roomId},...i.worldId&&{"filter.worldId":i.worldId},...i.entityId&&{"filter.entityId":i.entityId}});let o=await this.searchMemories({tableName:"knowledge",embedding:s,query:e?.content?.text,...i,count:20,match_threshold:.1});return console.log("*** fragments",o),r.addEvent("knowledge_retrieved"),r.setAttributes({"fragments.count":o.length}),o.map(a=>({id:a.id,content:a.content,similarity:a.similarity,metadata:a.metadata,worldId:a.worldId}))})}async addKnowledge(e,t={targetTokens:1500,overlap:200,modelContextSize:4096},r){return this.startSpan("AgentRuntime.addKnowledge",async s=>{s.setAttributes({"item.id":e.id,"agent.id":this.agentId,"options.targetTokens":t.targetTokens,"options.overlap":t.overlap,"scope.roomId":r?.roomId,"scope.worldId":r?.worldId,"scope.entityId":r?.entityId});let i={roomId:r?.roomId??this.agentId,worldId:r?.worldId,entityId:r?.entityId??this.agentId},o={id:e.id,agentId:this.agentId,roomId:i.roomId,worldId:i.worldId,entityId:i.entityId,content:e.content,metadata:e.metadata||{type:"document",timestamp:Date.now()}};s.addEvent("storing_document"),await this.createMemory(o,"documents"),s.addEvent("document_stored"),s.addEvent("splitting_chunks");let a=await Cr(e.content.text,t.targetTokens,t.overlap);s.setAttributes({"fragments.count":a.length}),s.addEvent("chunks_split");let u=0;s.addEvent("storing_fragments");for(let c=0;c<a.length;c++)try{s.addEvent(`generating_embedding_${c}`);let d=await this.useModel(N.TEXT_EMBEDDING,a[c]),l={id:B(this,`${e.id}-fragment-${c}`),agentId:this.agentId,roomId:i.roomId,worldId:i.worldId,entityId:i.entityId,embedding:d,content:{text:a[c]},metadata:{type:"fragment",documentId:e.id,position:c,timestamp:Date.now()}};await this.createMemory(l,"knowledge"),u++}catch(d){let l=d instanceof Error?d.message:String(d);s.recordException(d),s.setAttributes({"error.fragment":c,"error.message":l}),this.runtimeLogger.error(`Error processing fragment ${c}: ${l}`)}s.setAttributes({"fragments.processed":u,"fragments.success_rate":u/a.length}),s.addEvent("knowledge_processing_complete")})}async processCharacterKnowledge(e){let t=e.map(async r=>{await this.knowledgeProcessingSemaphore.acquire();try{let s=B(this,r);if(await this.checkExistingKnowledge(s))return;this.runtimeLogger.debug("Processing knowledge for ",this.character.name," - ",r.slice(0,100));let i={type:"document",timestamp:Date.now()},o=r.match(/^Path: (.+?)(?:\n|\r\n)/);if(o){let a=o[1].trim(),u=a.split(".").pop()||"",c=a.split("/").pop()||"",d=c.replace(`.${u}`,"");i={...i,path:a,filename:c,fileExt:u,title:d,fileType:`text/${u||"plain"}`,fileSize:r.length,source:"character"}}await this.addKnowledge({id:s,content:{text:r},metadata:i},void 0,{roomId:this.agentId,entityId:this.agentId,worldId:null})}catch(s){await this.handleProcessingError(s,"processing character knowledge")}finally{this.knowledgeProcessingSemaphore.release()}});await Promise.all(t)}setSetting(e,t,r=!1){r?(this.character.secrets||(this.character.secrets={}),this.character.secrets[e]=t):(this.character.settings||(this.character.settings={}),this.character.settings[e]=t)}getSetting(e){let t=this.character.secrets?.[e]||this.character.settings?.[e]||this.character.settings?.secrets?.[e]||this.settings[e],r=et(t,X());return r==="true"?!0:r==="false"?!1:r||null}getConversationLength(){return this.#e}registerDatabaseAdapter(e){this.adapter?this.runtimeLogger.warn("Database adapter already registered. Additional adapters will be ignored. This may lead to unexpected behavior."):(this.adapter=e,this.runtimeLogger.debug("Success: Database adapter registered successfully."))}registerProvider(e){this.providers.push(e),this.runtimeLogger.debug(`Success: Provider ${e.name} registered successfully.`)}registerAction(e){this.runtimeLogger.debug(`${this.character.name}(${this.agentId}) - Registering action: ${e.name}`),this.actions.find(t=>t.name===e.name)?this.runtimeLogger.warn(`${this.character.name}(${this.agentId}) - Action ${e.name} already exists. Skipping registration.`):(this.actions.push(e),this.runtimeLogger.debug(`${this.character.name}(${this.agentId}) - Action ${e.name} registered successfully.`))}registerEvaluator(e){this.evaluators.push(e)}registerContextProvider(e){this.providers.push(e)}async processActions(e,t,r,s){return this.startSpan("AgentRuntime.processActions",async i=>{i.setAttributes({"message.id":e.id,"responses.count":t.length,"agent.id":this.agentId});for(let o of t){let u=function(c){return c.toLowerCase().replace("_","")};if(!o.content?.actions||o.content.actions.length===0){i.addEvent("no_actions_in_response"),this.runtimeLogger.warn("No action found in the response content.");continue}let a=o.content.actions;i.setAttributes({"actions.count":a.length,"actions.names":JSON.stringify(a)}),this.runtimeLogger.debug(`Found actions: ${this.actions.map(c=>u(c.name))}`);for(let c of a){i.addEvent(`processing_action_${c}`),r=await this.composeState(e,["RECENT_MESSAGES"]),this.runtimeLogger.debug(`Success: Calling action: ${c}`);let d=u(c),l=this.actions.find(m=>u(m.name).includes(d)||d.includes(u(m.name)));if(l)i.addEvent(`found_exact_action_${l.name}`),this.runtimeLogger.debug(`Success: Found action: ${l?.name}`);else{i.addEvent("looking_for_similar_action"),this.runtimeLogger.debug("Attempting to find action in similes.");for(let m of this.actions)if(m.similes?.find(p=>p.toLowerCase().replace("_","").includes(d)||d.includes(p.toLowerCase().replace("_","")))){l=m,i.addEvent(`found_similar_action_${l.name}`),this.runtimeLogger.debug(`Success: Action found in similes: ${l.name}`);break}}if(!l){let m=`No action found for: ${c}`;i.addEvent("action_not_found"),i.setAttributes({"error.action":c}),this.runtimeLogger.error(m);continue}if(!l.handler){i.addEvent("action_has_no_handler"),i.setAttributes({"error.action":l.name}),this.runtimeLogger.error(`Action ${l.name} has no handler.`);continue}try{i.addEvent(`executing_action_${l.name}`),this.runtimeLogger.debug(`Executing handler for action: ${l.name}`),await this.startSpan(`Action.${l.name}`,async m=>{m.setAttributes({"action.name":l.name,"parent_span.id":i.spanContext().spanId}),m.addEvent("action.input",{"message.id":e.id,"state.keys":r?JSON.stringify(Object.keys(r.values)):"none",options:JSON.stringify({}),"responses.count":t?.length??0,"responses.ids":JSON.stringify(t?.map(E=>E.id)??[])});try{let E=await l.handler(this,e,r,{},s,t);m.addEvent("action.output",{status:"success",result:JSON.stringify(E,Me())}),m.setStatus({code:L.OK})}catch(E){let p=E instanceof Error?E.message:String(E);throw m.recordException(E),m.setStatus({code:L.ERROR,message:p}),m.setAttributes({"error.message":p}),m.addEvent("action.output",{status:"error",error:p}),E}}),i.addEvent(`action_executed_successfully_${l.name}`),this.runtimeLogger.debug(`Success: Action ${l.name} executed successfully.`),this.adapter.log({entityId:e.entityId,roomId:e.roomId,type:"action",body:{action:l.name,message:e.content.text,messageId:e.id,state:r,responses:t}})}catch(m){let E=m instanceof Error?m.message:String(m);throw i.recordException(m),i.setStatus({code:L.ERROR,message:E}),i.setAttributes({"error.action":l.name,"error.message":E}),this.runtimeLogger.error(m),m}}}})}async evaluate(e,t,r,s,i){return this.startSpan("AgentRuntime.evaluate",async o=>{o.setAttributes({"agent.id":this.agentId,"character.name":this.character?.name,"message.id":e?.id,"room.id":e?.roomId,"entity.id":e?.entityId,did_respond:r,responses_count:i?.length||0}),o.addEvent("evaluation_started");let a=this.evaluators.map(async c=>!c.handler||!r&&!c.alwaysRun?null:await c.validate(this,e,t)?c:null),u=(await Promise.all(a)).filter(Boolean);return o.setAttribute("selected_evaluators_count",u.length),o.addEvent("evaluator_selection_complete",{"evaluator.names":JSON.stringify(u.map(c=>c.name))}),u.length===0?(o.addEvent("no_evaluators_selected"),[]):(t=await this.composeState(e,["RECENT_MESSAGES","EVALUATORS"]),o.addEvent("evaluator_execution_start"),await Promise.all(u.map(async c=>{c.handler&&(await c.handler(this,e,t,{},s,i),this.adapter.log({entityId:e.entityId,roomId:e.roomId,type:"evaluator",body:{evaluator:c.name,messageId:e.id,message:e.content.text,state:t}}))})),o.addEvent("evaluator_execution_complete"),o.addEvent("evaluation_complete"),u)})}async ensureConnection({entityId:e,roomId:t,userName:r,name:s,source:i,type:o,channelId:a,serverId:u,worldId:c,userId:d}){if(e===this.agentId)throw new Error("Agent should not connect to itself");!c&&u&&(c=B(this,u));let l=[s,r].filter(Boolean),m={[i]:{id:d,name:s,userName:r}};try{let E=await this.adapter.getEntityById(e);if(E)await this.adapter.updateEntity({id:e,names:[...new Set([...E.names||[],...l])].filter(Boolean),metadata:{...E.metadata,[i]:{...E.metadata?.[i],name:s,userName:r}},agentId:this.agentId});else try{if(await this.adapter.createEntity({id:e,names:l,metadata:m,agentId:this.agentId}))this.runtimeLogger.debug(`Created new entity ${e} for user ${s||r||"unknown"}`);else throw new Error(`Failed to create entity ${e}`)}catch(p){if(p.message?.includes("duplicate key")||p.code==="23505")this.runtimeLogger.debug(`Entity ${e} exists in database but not for this agent. This is normal in multi-agent setups.`);else throw p}c&&await this.ensureWorldExists({id:c,name:u?`World for server ${u}`:`World for room ${t}`,agentId:this.agentId,serverId:u||"default",metadata:m}),await this.ensureRoomExists({id:t,name:s,source:i,type:o,channelId:a,serverId:u,worldId:c});try{await this.ensureParticipantInRoom(e,t)}catch(p){if(p.message?.includes("not found")){if(!await this.adapter.addParticipant(e,t))throw new Error(`Failed to add participant ${e} to room ${t}`);this.runtimeLogger.debug(`Added participant ${e} to room ${t} directly`)}else throw p}await this.ensureParticipantInRoom(this.agentId,t),this.runtimeLogger.debug(`Success: Successfully connected entity ${e} in room ${t}`)}catch(E){throw this.runtimeLogger.error(`Failed to ensure connection: ${E instanceof Error?E.message:String(E)}`),E}}async ensureParticipantInRoom(e,t){let r=await this.adapter.getEntityById(e);if(!r&&e!==this.agentId)this.runtimeLogger.warn(`Entity ${e} not directly accessible to agent ${this.agentId}. Will attempt to add as participant anyway.`);else if(!r)throw new Error(`User ${e} not found`);if(!(await this.adapter.getParticipantsForRoom(t)).includes(e)){if(!await this.adapter.addParticipant(e,t))throw new Error(`Failed to add participant ${e} to room ${t}`);e===this.agentId?this.runtimeLogger.debug(`Agent ${this.character.name} linked to room ${t} successfully.`):this.runtimeLogger.debug(`User ${e} linked to room ${t} successfully.`)}}async removeParticipant(e,t){return await this.adapter.removeParticipant(e,t)}async getParticipantsForEntity(e){return await this.adapter.getParticipantsForEntity(e)}async getParticipantsForRoom(e){return await this.adapter.getParticipantsForRoom(e)}async addParticipant(e,t){return await this.adapter.addParticipant(e,t)}async ensureWorldExists({id:e,name:t,serverId:r,metadata:s}){await this.getWorld(e)||(this.runtimeLogger.debug("Creating world:",{id:e,name:t,serverId:r,agentId:this.agentId}),await this.adapter.createWorld({id:e,name:t,agentId:this.agentId,serverId:r||"default",metadata:s}),this.runtimeLogger.debug(`World ${e} created successfully.`))}async ensureRoomExists({id:e,name:t,source:r,type:s,channelId:i,serverId:o,worldId:a,metadata:u}){await this.adapter.getRoom(e)||(await this.adapter.createRoom({id:e,name:t,agentId:this.agentId,source:r,type:s,channelId:i,serverId:o,worldId:a,metadata:u}),this.runtimeLogger.debug(`Room ${e} created successfully.`))}async composeState(e,t=null,r=null){return this.startSpan("AgentRuntime.composeState",async s=>{s.setAttributes({"message.id":e.id,"agent.id":this.agentId,filter_list:t?JSON.stringify(t):"none",include_list:r?JSON.stringify(r):"none"}),s.addEvent("state_composition_started");let i=await this.stateCache.get(e.id)||{values:{},data:{},text:""},o=i.data.providers?Object.keys(i.data.providers):[];s.setAttributes({cached_state_exists:!!i.data.providers,existing_providers_count:o.length,existing_providers:JSON.stringify(o)});let a=new Set;t&&t.length>0?t.forEach(S=>a.add(S)):this.providers.filter(S=>!S.private&&!S.dynamic&&!o.includes(S.name)).forEach(S=>a.add(S.name)),r&&r.length>0&&r.forEach(S=>a.add(S));let u=Array.from(new Set(this.providers.filter(S=>a.has(S.name)))).sort((S,C)=>(S.position||0)-(C.position||0)),c=u.map(S=>S.name);s.setAttributes({providers_to_get_count:u.length,providers_to_get:JSON.stringify(c)}),s.addEvent("starting_provider_fetch");let d=await Promise.all(u.map(async S=>this.startSpan(`provider.${S.name}`,async C=>{let Sr=Date.now();try{let y=await S.get(this,e,i),Ie=Date.now()-Sr;return C.setAttributes({"provider.name":S.name,"provider.duration_ms":Ie,"result.has_text":!!y.text,"result.values_keys":y.values?JSON.stringify(Object.keys(y.values)):"[]"}),C.addEvent("provider_fetch_complete"),this.runtimeLogger.debug(`${S.name} Provider took ${Ie}ms to respond`),{...y,providerName:S.name}}catch(y){let Ie=Date.now()-Sr,gr=y instanceof Error?y.message:String(y);return C.recordException(y),C.setStatus({code:L.ERROR,message:gr}),C.setAttributes({"provider.name":S.name,"provider.duration_ms":Ie,"error.message":gr}),C.addEvent("provider_fetch_error"),{values:{},text:"",providerName:S.name}}}))),m={...i.data.providers||{}};for(let S of d)m[S.providerName]=S.values||{};let E=d.map(S=>S.text).filter(S=>S!=="").join("\\n"),p="";i.text&&E?p=`${i.text}\\n${E}`:E?p=E:i.text&&(p=i.text);let g={...i.values||{}};for(let S in m){let C=m[S];C&&typeof C=="object"&&Object.assign(g,C)}let A={values:{...g,providers:p},data:{...i.data||{},providers:m},text:p};this.stateCache.set(e.id,A);let R=Object.keys(m).length,O=Object.keys(m),M=Object.keys(A.values);return s.setAttributes({"context.sources.provider_count":R,"context.sources.provider_names":JSON.stringify(O),"context.state.value_keys":JSON.stringify(M),"context.state.text_length":p.length,"context.sources.used_memory":O.includes("RECENT_MESSAGES"),"context.sources.used_knowledge":O.includes("KNOWLEDGE"),"context.sources.used_character":O.includes("CHARACTER"),"context.sources.used_actions":O.includes("ACTIONS"),"context.sources.used_facts":O.includes("FACTS")}),s.addEvent("context.composed",{"context.final_string":p.length>1e3?p.substring(0,997)+"...":p,"context.final_length":p.length}),s.addEvent("state_composition_complete"),A})}getService(e){let t=this.services.get(e);return t||(this.runtimeLogger.debug(`Service ${e} not found`),null)}async registerService(e){return this.startSpan("AgentRuntime.registerService",async t=>{let r=e.serviceType;if(t.setAttributes({"service.type":r||"unknown","agent.id":this.agentId}),!r){t.addEvent("service_missing_type");return}if(this.runtimeLogger.debug(`${this.character.name}(${this.agentId}) - Registering service:`,r),this.services.has(r)){t.addEvent("service_already_registered"),this.runtimeLogger.warn(`${this.character.name}(${this.agentId}) - Service ${r} is already registered. Skipping registration.`);return}try{t.addEvent("starting_service");let s=await e.start(this);this.services.set(r,s),t.addEvent("service_registered"),this.runtimeLogger.debug(`${this.character.name}(${this.agentId}) - Service ${r} registered successfully`)}catch(s){let i=s instanceof Error?s.message:String(s);throw t.recordException(s),t.setStatus({code:L.ERROR,message:i}),this.runtimeLogger.error(`${this.character.name}(${this.agentId}) - Failed to register service ${r}: ${i}`),s}})}registerModel(e,t){let r=typeof e=="string"?e:N[e];this.models.has(r)||this.models.set(r,[]),this.models.get(r)?.push(t)}getModel(e){let t=typeof e=="string"?e:N[e],r=this.models.get(t);if(r?.length)return r[0]}async useModel(e,t){return this.startSpan(`AgentRuntime.useModel.${e}`,async r=>{let s=typeof e=="string"?e:N[e],i=t?.prompt||t?.input||(Array.isArray(t?.messages)?JSON.stringify(t.messages):null);r.setAttributes({"llm.request.model":s,"agent.id":this.agentId,"llm.request.temperature":t?.temperature,"llm.request.top_p":t?.top_p,"llm.request.max_tokens":t?.max_tokens||t?.max_tokens_to_sample}),r.addEvent("model_parameters",{params:JSON.stringify(t,Me())}),i&&r.addEvent("llm.prompt",{"prompt.content":i});let o=this.getModel(s);if(!o){let c=`No handler found for delegate type: ${s}`;throw r.setStatus({code:L.ERROR,message:c}),new Error(c)}this.runtimeLogger.debug(`[useModel] ${s} input:`,JSON.stringify(t,Me(),2).replace(/\\n/g,`
|
|
218
|
+
`));let a;t==null||typeof t!="object"||Array.isArray(t)||typeof Buffer<"u"&&Buffer.isBuffer(t)?a=t:a={...t,runtime:this};let u=performance.now();r.addEvent("model_execution_start");try{let c=await o(this,a),d=performance.now()-u;return r.setAttributes({"llm.duration_ms":d,"llm.usage.prompt_tokens":c?.usage?.prompt_tokens,"llm.usage.completion_tokens":c?.usage?.completion_tokens,"llm.usage.total_tokens":c?.usage?.total_tokens}),r.addEvent("model_response",{response:JSON.stringify(c,Me())}),this.runtimeLogger.debug(`[useModel] ${s} completed in ${Number(d.toFixed(2)).toLocaleString()}ms`),this.runtimeLogger.debug(`[useModel] ${s} output:`,Array.isArray(c)?`${JSON.stringify(c.slice(0,5))}...${JSON.stringify(c.slice(-5))} (${c.length} items)`:JSON.stringify(c)),this.adapter.log({entityId:this.agentId,roomId:this.agentId,body:{modelType:e,modelKey:s,params:t?typeof t=="object"?Object.keys(t):typeof t:null,response:Array.isArray(c)&&c.every(l=>typeof l=="number")?"[array]":c},type:`useModel:${s}`}),r.addEvent("model_execution_complete"),r.setStatus({code:L.OK}),c}catch(c){let d=performance.now()-u,l=c instanceof Error?c.message:String(c);throw r.recordException(c),r.setStatus({code:L.ERROR,message:l}),r.setAttributes({"error.time_ms":d,"error.message":l}),r.addEvent("model_execution_error"),c}})}registerEvent(e,t){this.events.has(e)||this.events.set(e,[]),this.events.get(e)?.push(t)}getEvent(e){return this.events.get(e)}async emitEvent(e,t){let r=Array.isArray(e)?e:[e];for(let s of r){let i=s==="MESSAGE_RECEIVED",o=this.instrumentationService?.isEnabled?.()&&this.tracer,a=this.events.get(s);if(a)if(i&&o){let u=t?.message,c=this.tracer.startSpan("AgentRuntime.handleMessageEvent",{attributes:{"agent.id":this.agentId,"character.name":this.character?.name,"room.id":u?.roomId||"unknown","user.id":u?.entityId||"unknown","message.id":u?.id||"unknown","event.name":s}}),d=Od.setSpan(Ze.active(),c);try{c.addEvent("processing_started"),await Ze.with(d,async()=>{await Promise.all(a.map(l=>{let m=Ze.active();return Ze.with(m,()=>l(t))}))}),c.setStatus({code:L.OK})}catch(l){this.runtimeLogger.error(`Error during instrumented handler execution for event ${s}:`,l),c.recordException(l),c.setStatus({code:L.ERROR,message:l.message})}finally{c.addEvent("processing_ended"),c.end()}}else try{await Promise.all(a.map(u=>u(t)))}catch(u){this.runtimeLogger.error(`Error during emitEvent for ${s} (handler execution):`,u)}}}async ensureEmbeddingDimension(){if(this.runtimeLogger.debug(`[AgentRuntime][${this.character.name}] Starting ensureEmbeddingDimension`),!this.adapter)throw new Error(`[AgentRuntime][${this.character.name}] Database adapter not initialized before ensureEmbeddingDimension`);try{if(!this.getModel(N.TEXT_EMBEDDING))throw new Error(`[AgentRuntime][${this.character.name}] No TEXT_EMBEDDING model registered`);this.runtimeLogger.debug(`[AgentRuntime][${this.character.name}] Getting embedding dimensions`);let t=await this.useModel(N.TEXT_EMBEDDING,null);if(!t||!t.length)throw new Error(`[AgentRuntime][${this.character.name}] Invalid embedding received`);this.runtimeLogger.debug(`[AgentRuntime][${this.character.name}] Setting embedding dimension: ${t.length}`),await this.adapter.ensureEmbeddingDimension(t.length),this.runtimeLogger.debug(`[AgentRuntime][${this.character.name}] Successfully set embedding dimension`)}catch(e){throw this.runtimeLogger.debug(`[AgentRuntime][${this.character.name}] Error in ensureEmbeddingDimension:`,e),e}}registerTaskWorker(e){this.taskWorkers.has(e.name)&&this.runtimeLogger.warn(`Task definition ${e.name} already registered. Will be overwritten.`),this.taskWorkers.set(e.name,e)}getTaskWorker(e){return this.taskWorkers.get(e)}get db(){return this.adapter.db}async init(){await this.adapter.init()}async close(){await this.adapter.close()}async getAgent(e){return await this.adapter.getAgent(e)}async getAgents(){return await this.adapter.getAgents()}async createAgent(e){return await this.adapter.createAgent(e)}async updateAgent(e,t){return await this.adapter.updateAgent(e,t)}async deleteAgent(e){return await this.adapter.deleteAgent(e)}async ensureAgentExists(e){return await this.adapter.ensureAgentExists(e)}async getEntityById(e){return await this.adapter.getEntityById(e)}async getEntitiesForRoom(e,t){return await this.adapter.getEntitiesForRoom(e,t)}async createEntity(e){return e.agentId||(e.agentId=this.agentId),await this.adapter.createEntity(e)}async updateEntity(e){await this.adapter.updateEntity(e)}async getComponent(e,t,r,s){return await this.adapter.getComponent(e,t,r,s)}async getComponents(e,t,r){return await this.adapter.getComponents(e,t,r)}async createComponent(e){return await this.adapter.createComponent(e)}async updateComponent(e){await this.adapter.updateComponent(e)}async deleteComponent(e){await this.adapter.deleteComponent(e)}async addEmbeddingToMemory(e){if(e.embedding)return e;let t=e.content.text;if(!t)throw new Error("Cannot generate embedding: Memory content is empty");try{e.embedding=await this.useModel(N.TEXT_EMBEDDING,{text:t})}catch(r){G.error("Failed to generate embedding:",r),e.embedding=await this.useModel(N.TEXT_EMBEDDING,null)}return e}async getMemories(e){return await this.adapter.getMemories(e)}async getMemoryById(e){return await this.adapter.getMemoryById(e)}async getMemoriesByIds(e,t){return await this.adapter.getMemoriesByIds(e,t)}async getMemoriesByRoomIds(e){return await this.adapter.getMemoriesByRoomIds(e)}async getCachedEmbeddings(e){return await this.adapter.getCachedEmbeddings(e)}async log(e){await this.adapter.log(e)}async searchMemories(e){let t=await this.adapter.searchMemories(e);return e.query?await this.rerankMemories(e.query,t):t}async rerankMemories(e,t){let r=t.map(o=>({title:o.id,content:o.content.text}));return new Je(r).search(e,t.length).map(o=>t[o.index])}async createMemory(e,t,r){return await this.adapter.createMemory(e,t,r)}async updateMemory(e){return await this.adapter.updateMemory(e)}async deleteMemory(e){await this.adapter.deleteMemory(e)}async deleteAllMemories(e,t){await this.adapter.deleteAllMemories(e,t)}async countMemories(e,t,r){return await this.adapter.countMemories(e,t,r)}async getLogs(e){return await this.adapter.getLogs(e)}async deleteLog(e){await this.adapter.deleteLog(e)}async createWorld(e){return await this.adapter.createWorld(e)}async getWorld(e){return await this.adapter.getWorld(e)}async getAllWorlds(){return await this.adapter.getAllWorlds()}async updateWorld(e){await this.adapter.updateWorld(e)}async getRoom(e){return await this.adapter.getRoom(e)}async createRoom({id:e,name:t,source:r,type:s,channelId:i,serverId:o,worldId:a}){return await this.adapter.createRoom({id:e,name:t,source:r,type:s,channelId:i,serverId:o,worldId:a})}async deleteRoom(e){await this.adapter.deleteRoom(e)}async updateRoom(e){await this.adapter.updateRoom(e)}async getRoomsForParticipant(e){return await this.adapter.getRoomsForParticipant(e)}async getRoomsForParticipants(e){return await this.adapter.getRoomsForParticipants(e)}async getRooms(e){return await this.adapter.getRooms(e)}async getParticipantUserState(e,t){return await this.adapter.getParticipantUserState(e,t)}async setParticipantUserState(e,t,r){await this.adapter.setParticipantUserState(e,t,r)}async createRelationship(e){return await this.adapter.createRelationship(e)}async updateRelationship(e){await this.adapter.updateRelationship(e)}async getRelationship(e){return await this.adapter.getRelationship(e)}async getRelationships(e){return await this.adapter.getRelationships(e)}async getCache(e){return await this.adapter.getCache(e)}async setCache(e,t){return await this.adapter.setCache(e,t)}async deleteCache(e){return await this.adapter.deleteCache(e)}async createTask(e){return await this.adapter.createTask(e)}async getTasks(e){return await this.adapter.getTasks(e)}async getTask(e){return await this.adapter.getTask(e)}async getTasksByName(e){return await this.adapter.getTasksByName(e)}async updateTask(e,t){await this.adapter.updateTask(e,t)}async deleteTask(e){await this.adapter.deleteTask(e)}on(e,t){this.eventHandlers.has(e)||this.eventHandlers.set(e,[]),this.eventHandlers.get(e).push(t)}off(e,t){if(!this.eventHandlers.has(e))return;let r=this.eventHandlers.get(e),s=r.indexOf(t);s!==-1&&r.splice(s,1)}emit(e,t){if(this.eventHandlers.has(e))for(let r of this.eventHandlers.get(e))r(t)}async sendControlMessage(e){try{let{roomId:t,action:r,target:s}=e,i={type:"control",payload:{action:r,target:s},roomId:t};await this.emitEvent("CONTROL_MESSAGE",{runtime:this,message:i,source:"agent"}),this.runtimeLogger.debug(`Sent control message: ${r} to room ${t}`)}catch(t){this.runtimeLogger.error(`Error sending control message: ${t}`)}}};import ve from"crypto-browserify";function Nd(n){return{name:n.name,description:n.description,usageDescription:n.usageDescription||"",value:null,required:n.required,validation:n.validation||null,public:n.public||!1,secret:n.secret||!1,dependsOn:n.dependsOn||[],onSetAction:n.onSetAction||null,visibleIf:n.visibleIf||null}}function X(){let n=(typeof process<"u"?process.env.SECRET_SALT:import.meta.env.SECRET_SALT)||"secretsalt";n||T.error("SECRET_SALT is not set");let e=n;return T.debug(`Generated salt with length: ${e.length} (truncated for security)`),e}function Bs(n,e){try{if(n==null)return T.debug("Attempted to encrypt undefined or null value"),n;if(typeof n=="boolean"||typeof n=="number")return T.debug("Value is a boolean or number, returning as is"),n;if(typeof n!="string")return T.debug(`Value is not a string (type: ${typeof n}), returning as is`),n;let t=n.split(":");if(t.length===2)try{if(Buffer.from(t[0],"hex").length===16)return T.debug("Value appears to be already encrypted, skipping re-encryption"),n}catch{}let r=ve.createHash("sha256").update(e).digest().slice(0,32),s=ve.randomBytes(16),i=ve.createCipheriv("aes-256-cbc",r,s),o=i.update(n,"utf8","hex");return o+=i.final("hex"),`${s.toString("hex")}:${o}`}catch(t){return T.error(`Error encrypting value: ${t}`),n}}function et(n,e){try{if(n==null)return T.debug("Attempted to decrypt undefined or null value"),n;if(typeof n=="boolean"||typeof n=="number")return T.debug("Value is a boolean or number, returning as is"),n;if(typeof n!="string")return T.debug(`Value is not a string (type: ${typeof n}), returning as is`),n;let t=n.split(":");if(t.length!==2)return T.debug("Invalid encrypted value format - expected 'iv:encrypted', returning original value"),n;let r=Buffer.from(t[0],"hex"),s=t[1];if(r.length!==16)return T.debug(`Invalid IV length (${r.length}) - expected 16 bytes`),n;let i=ve.createHash("sha256").update(e).digest().slice(0,32),o=ve.createDecipheriv("aes-256-cbc",i,r),a=o.update(s,"hex","utf8");return a+=o.final("utf8"),a}catch(t){return T.error(`Error decrypting value: ${t}`),n}}function Dd(n,e){let t={...n};return n.secret===!0&&typeof n.value=="string"&&n.value&&(t.value=Bs(n.value,e)),t}function xd(n,e){let t={...n};return n.secret===!0&&typeof n.value=="string"&&n.value&&(t.value=et(n.value,e)),t}function wd(n,e){let t={};for(let[r,s]of Object.entries(n))t[r]=Dd(s,e);return t}function Ws(n,e){let t={};for(let[r,s]of Object.entries(n))t[r]=xd(s,e);return t}async function hp(n,e,t){try{let r=B(n,e),s=await n.getWorld(r);if(!s)return T.error(`No world found for server ${e}`),!1;s.metadata||(s.metadata={});let i=X(),o=wd(t,i);return s.metadata.settings=o,await n.updateWorld(s),!0}catch(r){return T.error(`Error updating settings state: ${r}`),!1}}async function _p(n,e){try{let t=B(n,e),r=await n.getWorld(t);if(!r||!r.metadata?.settings)return null;let s=r.metadata.settings,i=X();return Ws(s,i)}catch(t){return T.error(`Error getting settings state: ${t}`),null}}async function Sp(n,e,t){try{if(e.metadata?.settings){T.info(`Onboarding state already exists for server ${e.serverId}`);let s=e.metadata.settings,i=X();return Ws(s,i)}let r={};if(t.settings)for(let[s,i]of Object.entries(t.settings))r[s]=Nd(i);return e.metadata||(e.metadata={}),e.metadata.settings=r,await n.updateWorld(e),T.info(`Initialized settings config for server ${e.serverId}`),r}catch(r){return T.error(`Error initializing settings config: ${r}`),null}}function gp(n){let e=JSON.parse(JSON.stringify(n)),t=X();return e.settings?.secrets&&(e.settings.secrets=Fs(e.settings.secrets,t)),e.secrets&&(e.secrets=Fs(e.secrets,t)),e}function fp(n,e){let t=JSON.parse(JSON.stringify(n)),r=X();return t.settings?.secrets&&(t.settings.secrets=Gs(t.settings.secrets,r)),t.secrets&&(t.secrets=Gs(t.secrets,r)),t}function Fs(n,e){let t={};for(let[r,s]of Object.entries(n))typeof s=="string"&&s?t[r]=Bs(s,e):t[r]=s;return t}function Gs(n,e){let t={};for(let[r,s]of Object.entries(n))typeof s=="string"&&s?t[r]=et(s,e):t[r]=s;return t}import kd from"stream-browserify";import{Buffer as Fd}from"buffer";var{PassThrough:Vd,Readable:yp}=kd;function Gd(n,e,t=1,r=16){let s=Fd.alloc(44);return s.write("RIFF",0),s.writeUInt32LE(36+n,4),s.write("WAVE",8),s.write("fmt ",12),s.writeUInt32LE(16,16),s.writeUInt16LE(1,20),s.writeUInt16LE(t,22),s.writeUInt32LE(e,24),s.writeUInt32LE(e*r*t/8,28),s.writeUInt16LE(r*t/8,32),s.writeUInt16LE(r,34),s.write("data",36),s.writeUInt32LE(n,40),s}function Mp(n,e,t,r=1,s=16){let i=Gd(e,t,r,s),o=!1,a=new Vd;return n.on("data",u=>{o||(a.push(i),o=!0),a.push(u)}),n.on("end",()=>{a.end()}),a}function Me(){let n=new WeakSet;return function(e,t){if(typeof t=="object"&&t!==null){if(n.has(t))return"[Circular]";n.add(t)}return t}}function Ip(n){if(!n)return!1;let e=["YES","Y","TRUE","T","1","ON","ENABLE"],t=["NO","N","FALSE","F","0","OFF","DISABLE"],r=n.trim().toUpperCase();return e.includes(r)?!0:(t.includes(r),!1)}function Bd(n,e){let t=n.getSetting("CLOUDFLARE_GW_ENABLED")==="true",r=n.getSetting("CLOUDFLARE_AI_ACCOUNT_ID"),s=n.getSetting("CLOUDFLARE_AI_GATEWAY_ID");if(h.debug("Cloudflare Gateway Configuration:",{isEnabled:t,hasAccountId:!!r,hasGatewayId:!!s,provider:e}),!t){h.debug("Cloudflare Gateway is not enabled");return}if(!r){h.warn("Cloudflare Gateway is enabled but CLOUDFLARE_AI_ACCOUNT_ID is not set");return}if(!s){h.warn("Cloudflare Gateway is enabled but CLOUDFLARE_AI_GATEWAY_ID is not set");return}let i=`https://gateway.ai.cloudflare.com/v1/${r}/${s}/${e.toLowerCase()}`;return h.info("Using Cloudflare Gateway:",{provider:e,baseURL:i,accountId:r,gatewayId:s}),i}function Lp(n,e,t){return Bd(n,e)??t}export{Vs as AgentRuntime,qs as AgentStatus,Hs as CacheKeyPrefix,Tr as ChannelType,Rr as DatabaseAdapter,yr as EventType,Xe as InstrumentationService,Ks as KnowledgeScope,fr as MemoryType,N as ModelType,js as PlatformPrefix,Ar as Role,zs as SOCKET_MESSAGE_TYPE,_r as Semaphore,Pe as Service,Ue as ServiceType,$s as TEEMode,Ys as TeeType,il as VECTOR_DIMS,Al as addHeader,qd as asUUID,Pl as booleanFooter,cl as composeActionExamples,Ur as composePrompt,Tl as composePromptFromState,Lr as composeRandomUser,Kd as createMessageMemory,sl as createServiceError,Nd as createSettingFromConfig,B as createUniqueUuid,Gs as decryptObjectValues,et as decryptSecret,et as decryptStringValue,fp as decryptedCharacter,h as elizaLogger,Fs as encryptObjectValues,Bs as encryptStringValue,gp as encryptedCharacter,xl as findEntityByName,ql as findWorldsForOwner,ul as formatActionNames,dl as formatActions,kl as formatEntities,Rl as formatMessages,yl as formatPosts,Or as formatTimestamp,Jd as getBrowserService,Bd as getCloudflareGatewayBaseURL,wl as getEntityDetails,el as getFileService,nl as getMemoryText,Zd as getPdfService,Lp as getProviderBaseURL,X as getSalt,Hd as getTypedService,Wl as getUserServerRole,Xd as getVideoService,Gd as getWavHeader,_p as getWorldSettings,Sp as initializeOnboarding,Qd as isCustomMetadata,zd as isDescriptionMetadata,tl as isDocumentMemory,$d as isDocumentMetadata,rl as isFragmentMemory,Yd as isFragmentMetadata,jd as isMessageMetadata,T as logger,vl as messageHandlerTemplate,vr as normalizeJsonString,Ip as parseBooleanFromText,br as parseJSONObjectFromText,Ul as parseKeyValueXml,Il as postCreationTemplate,Mp as prependWavHeader,Me as safeReplacer,Dd as saltSettingValue,wd as saltWorldSettings,Ml as shouldRespondTemplate,Cr as splitChunks,Le as stringToUuid,Ol as trimTokens,Ll as truncateToCompleteSentence,xd as unsaltSettingValue,Ws as unsaltWorldSettings,hp as updateWorldSettings,Pr as upgradeDoubleToTriple,Ld as uuidSchema,JE as validateUuid};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@elizaos/core",
|
|
3
|
-
"version": "1.0.0-beta.
|
|
3
|
+
"version": "1.0.0-beta.43",
|
|
4
4
|
"description": "",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -71,5 +71,5 @@
|
|
|
71
71
|
"publishConfig": {
|
|
72
72
|
"access": "public"
|
|
73
73
|
},
|
|
74
|
-
"gitHead": "
|
|
74
|
+
"gitHead": "450ee2991cbe30af349aa6eebdce1c70b100473a"
|
|
75
75
|
}
|