@isdk/ai-tool 0.0.7 → 0.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/README.cn.md +49 -15
  2. package/README.md +245 -2
  3. package/dist/chunk-PDXMSKQH.mjs +1 -0
  4. package/dist/funcs.d.mts +1 -1
  5. package/dist/funcs.d.ts +1 -1
  6. package/dist/funcs.js +1 -1
  7. package/dist/funcs.mjs +1 -1
  8. package/dist/{index-japi6bEq.d.mts → index-Dgo3ZXPQ.d.mts} +28 -2
  9. package/dist/{index-japi6bEq.d.ts → index-Dgo3ZXPQ.d.ts} +28 -2
  10. package/dist/index.d.mts +369 -53
  11. package/dist/index.d.ts +369 -53
  12. package/dist/index.js +1 -1
  13. package/dist/index.mjs +1 -1
  14. package/docs/README.md +245 -2
  15. package/docs/classes/AbortError.md +8 -8
  16. package/docs/classes/AlreadyExistsError.md +8 -8
  17. package/docs/classes/BaseError.md +8 -8
  18. package/docs/classes/CancelableAbility.md +431 -0
  19. package/docs/classes/ClientTools.md +101 -51
  20. package/docs/classes/CommonError.md +8 -8
  21. package/docs/classes/EventClient.md +123 -73
  22. package/docs/classes/EventServer.md +121 -71
  23. package/docs/classes/EventToolFunc.md +91 -41
  24. package/docs/classes/FStringPromptTemplate.md +18 -18
  25. package/docs/classes/FewShotPromptTemplate.md +22 -22
  26. package/docs/classes/GolangPromptTemplate.md +18 -18
  27. package/docs/classes/HFEnvironment.md +9 -9
  28. package/docs/classes/HFInterpreter.md +39 -17
  29. package/docs/classes/HFTemplate.md +4 -4
  30. package/docs/classes/HfPromptTemplate.md +18 -18
  31. package/docs/classes/IntSet.md +249 -0
  32. package/docs/classes/NotFoundError.md +8 -8
  33. package/docs/classes/NotImplementationError.md +8 -8
  34. package/docs/classes/PromptExampleSelector.md +8 -8
  35. package/docs/classes/PromptTemplate.md +17 -17
  36. package/docs/classes/ReadableStreamError.md +8 -8
  37. package/docs/classes/ResClientTools.md +107 -57
  38. package/docs/classes/ResServerTools.md +105 -55
  39. package/docs/classes/SSEChannel.md +15 -15
  40. package/docs/classes/Semaphore.md +273 -0
  41. package/docs/classes/ServerTools.md +98 -48
  42. package/docs/classes/TaskAbortController.md +157 -0
  43. package/docs/classes/ToolFunc.md +80 -38
  44. package/docs/enums/AsyncFeatureBits.md +41 -0
  45. package/docs/enums/AsyncFeatures.md +41 -0
  46. package/docs/enums/ErrorCode.md +41 -19
  47. package/docs/enums/XXHashAlgorithm.md +2 -2
  48. package/docs/interfaces/AIChatAssistantMessageParam.md +6 -6
  49. package/docs/interfaces/AIChatContentPartImage.md +2 -2
  50. package/docs/interfaces/AIChatContentPartText.md +2 -2
  51. package/docs/interfaces/AIChatMessageParamBase.md +1 -1
  52. package/docs/interfaces/AIChatMessageToolCall.md +3 -3
  53. package/docs/interfaces/AIChatSystemMessageParam.md +3 -3
  54. package/docs/interfaces/AIChatToolMessageParam.md +4 -4
  55. package/docs/interfaces/AIChatUserMessageParam.md +7 -7
  56. package/docs/interfaces/AIResult.md +16 -5
  57. package/docs/interfaces/AIStreamParser.md +1 -1
  58. package/docs/interfaces/AIStreamParserOptions.md +1 -1
  59. package/docs/interfaces/BaseFunc.md +7 -7
  60. package/docs/interfaces/BaseFuncItem.md +6 -6
  61. package/docs/interfaces/CancelableAbilityOptions.md +126 -0
  62. package/docs/interfaces/ClientFuncItem.md +10 -10
  63. package/docs/interfaces/DotenvExpandOptions.md +3 -3
  64. package/docs/interfaces/DotenvExpandOutput.md +2 -2
  65. package/docs/interfaces/EventClientFuncParams.md +4 -4
  66. package/docs/interfaces/EventServerFuncParams.md +5 -5
  67. package/docs/interfaces/FewShotPromptTemplateOptions.md +11 -11
  68. package/docs/interfaces/FuncItem.md +7 -7
  69. package/docs/interfaces/FuncParam.md +16 -5
  70. package/docs/interfaces/PromptExampleSelectorOptions.md +2 -2
  71. package/docs/interfaces/PromptTemplateOptions.md +6 -6
  72. package/docs/interfaces/RemoteFuncItem.md +10 -10
  73. package/docs/interfaces/ResClientFuncParams.md +2 -2
  74. package/docs/interfaces/ResServerFuncParams.md +5 -5
  75. package/docs/interfaces/SanitizeFilenameOptions.md +2 -2
  76. package/docs/interfaces/ServerFuncItem.md +11 -11
  77. package/docs/interfaces/ServerFuncParams.md +2 -2
  78. package/docs/interfaces/StreamCallbacksAndOptions.md +124 -0
  79. package/docs/interfaces/TaskAbortControllers.md +7 -0
  80. package/docs/interfaces/TaskPromise.md +151 -0
  81. package/docs/interfaces/ToolFuncPackage.md +63 -0
  82. package/docs/modules.md +1130 -123
  83. package/package.json +3 -2
  84. package/dist/chunk-PYM7DCYB.mjs +0 -1
  85. package/docs/interfaces/AIStreamCallbacksAndOptions.md +0 -158
package/dist/funcs.js CHANGED
@@ -1 +1 @@
1
- "use strict";var t,e=Object.create,n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,s=Object.getOwnPropertyNames,i=Object.getPrototypeOf,o=Object.prototype.hasOwnProperty,a=(t,e)=>{for(var r in e)n(t,r,{get:e[r],enumerable:!0})},c=(t,e,i,a)=>{if(e&&"object"==typeof e||"function"==typeof e)for(let c of s(e))o.call(t,c)||c===i||n(t,c,{get:()=>e[c],enumerable:!(a=r(e,c))||a.enumerable});return t},u=(t,e,n)=>(c(t,e,"default"),n&&c(n,e,"default")),l=(t,r,s)=>(s=null!=t?e(i(t)):{},c(!r&&t&&t.__esModule?s:n(s,"default",{value:t,enumerable:!0}),t)),f={};a(f,{EventClient:()=>ir,EventServer:()=>hr,EventToolFunc:()=>V,_lrucache:()=>M,createLRUCache:()=>L,event:()=>U,eventClient:()=>or,eventServer:()=>pr,lrucache:()=>_,registerCoreTools:()=>wr}),module.exports=(t=f,c(n({},"__esModule",{value:!0}),t));var h=require("events-ex"),p=require("property-manager"),w=require("util-ex"),d=require("abstract-error"),m=(t=>(t[t.OK=200]="OK",t[t.BadRequest=400]="BadRequest",t[t.InvalidArgument=400]="InvalidArgument",t[t.Unauthorized=401]="Unauthorized",t[t.PaymentRequired=402]="PaymentRequired",t[t.Forbidden=403]="Forbidden",t[t.NotFound=404]="NotFound",t[t.MethodNotAllowed=405]="MethodNotAllowed",t[t.NotAcceptable=406]="NotAcceptable",t[t.RequestTimeout=408]="RequestTimeout",t[t.Conflict=409]="Conflict",t[t.Corruption=409]="Corruption",t[t.Aborted=499]="Aborted",t[t.InternalError=500]="InternalError",t[t.NotImplemented=501]="NotImplemented",t[t.NotSupported=501]="NotSupported",t[t.BadGateway=502]="BadGateway",t[t.ServiceUnavailable=503]="ServiceUnavailable",t[t.GatewayTimeout=504]="GatewayTimeout",t))(m||{}),y=500,b=404,g=409,x=499,E=class t extends d.AbstractError{static createErrorClass(e,n,r=t){return(0,d.createErrorClass)(e,n,r)}constructor(t,e,n){super(t,e);const r=this.constructor;null!=e?this.code=e:r.code?this.code=r.code:this.code=r.name,n?"string"==typeof n?this.name=n:Object.assign(this,n):"string"==typeof this.code?this.name=this.code:this.name=r.name}toJSON(){const t={name:this.name,code:this.code,data:this.data,caller:this.caller,error:this.message,stack:this.stack};return Object.keys(t).forEach((e=>void 0===t[e]&&delete t[e])),t}fromJSON(e){const n=new t(e.message);return n.code=e.code,n.data=e.data,n.caller=e.caller,n.message=e.error,n.stack=e.stack,n}},v=class extends E{constructor(t,e,n=y){super(t,n,e)}},$=class extends v{constructor(t,e){t||(t="Not Implementation."),super(t,e,501)}};v[501]=$;var S=class extends v{static{this.code=b}constructor(t,e){super(`Could not find ${t}.`,e,b),this.data={what:t}}};v[404]=S;var k=class extends v{static{this.code=g}constructor(t,e){super(`The ${t} already exists.`,e,g),this.data={what:t}}};v[409]=k;var O=class extends v{static{this.code=x}constructor(t,e){super(t?`The operation was aborted for ${t}.`:"The operation was aborted.",e,x),t&&(this.data={what:t})}};function C(t,e,n=y){const r=new(v[n]||v)(t,e,n);return"number"!=typeof r.code&&(r.code=n),r}function j(t,e,n=y){throw C(t,e,n)}v[499]=O;var A=class t extends p.AdvancePropertyManager{static{this.items={}}static get(t){return this.items[t]}static list(){return this.items}static getByTag(t){let e;for(const n in this.list()){const r=this.get(n);let s=r.tags;if("string"==typeof s){if(s===t){e=r;break}}else if(Array.isArray(s)&&s.indexOf(t)>=0){e=r;break}}return e}static getAllByTag(t){let e=[];for(const n in this.list()){const r=this.get(n);let s=r.tags;"string"==typeof s?s===t&&e.push(r):Array.isArray(s)&&s.indexOf(t)>=0&&e.push(r)}return e}static async run(t,e){const n=this.get(t);if(n)return await n.run(e);throw new S(`${t} to run`,this.name)}static runSync(t,e){const n=this.get(t);if(n)return n.runSync(e);throw new S(`${t} to run`,this.name)}static getFunc(t){const e=this.get(t);return e?.getFunc()}static async runWithPos(t,...e){const n=this.get(t);if(n)return await n.runWithPos(...e);throw new S(`${t} to run`,this.name)}static runWithPosSync(t,...e){const n=this.get(t);if(n)return n.runWithPosSync(...e);throw new S(`${t} to run`,this.name)}static getFuncWithPos(t){const e=this.get(t);return e?.getFuncWithPos()}static register(e,n={}){switch(typeof e){case"string":n.name=e;break;case"function":n.func=e;break;case"object":n=e}e=n.name;let r=!!this.get(e);if(r)r=!1;else{if(!(n instanceof t))return r=new this(n),r.register();this.items[e]=n,r=n}return r}static unregister(t){const e=this.items[t];return e&&delete this.items[t],e}constructor(t,e={}){switch(super(),typeof t){case"string":e.name=t;break;case"function":e.func=t;break;case"object":e=t}this.name=t=e.name,e.scope&&(this.scope=e.scope),"function"==typeof e.setup&&e.setup.call(this,e),this.initialize(e)}register(){const e=this.constructor,n=this.depends;if(n){const e=Object.keys(n);for(const r of e){const e=n[r];e instanceof t&&e.register()}}return e.register(this)}unregister(){return this.constructor.unregister(this.name)}arr2ObjParams(t){if(this.params&&(t.length>1||Array.isArray(t[0])||t[0]&&"object"!=typeof t[0])){const e={},n=Object.keys(this.params);let r=Math.min(n.length,t.length);for(let s=0;s<r;s++)e[n[s]]=t[s];t=[e]}return t}obj2ArrParams(t){const e=[];if(t&&this.params&&Array.isArray(this.params)){const n=Object.keys(t);let r=Math.min(n.length,this.params.length);for(let s=0;s<r;s++)e.push(t[n[s]])}return e}runSync(t){const e=this.params&&Array.isArray(this.params);if(Array.isArray(t)){if(e)return this.func(...t);j("the function is not support array params, the params must be object!",this.name)}return e?(t=this.obj2ArrParams(t),console.warn('Warning:Use runWithPos() instead of run() for the "'+this.name+'" is function with position params'),this.func(...t)):this.func(t)}async run(t){return await this.runSync(t)}async runAs(t,e){return await this.constructor.run(t,e)}runAsSync(t,e){return this.constructor.runSync(t,e)}getFunc(t){return t?this.constructor.getFunc(t):this.runSync.bind(this)}runWithPosSync(...t){return this.params&&!Array.isArray(this.params)&&(t=this.arr2ObjParams(t)),this.func(...t)}runWithPosAsSync(t,...e){return this.constructor.runWithPosSync(t,...e)}async runWithPos(...t){return await this.runWithPosSync(...t)}async runWithPosAs(t,...e){return await this.constructor.runWithPos(t,...e)}getFuncWithPos(t){return t?this.constructor.getFuncWithPos(t):this.runWithPosSync.bind(this)}},N={name:{type:"string"},description:{type:"string"},func:{type:"function",assign(t,e,n,r,s){let i=t;const o=typeof t;return s.isExported?i="function"===o?t.toString():t:t&&("string"!==o&&(t=t.toString()),i=(0,w._createFunction)(t,e.scope)),i}},params:{type:"object"},result:{type:"any"},setup:{type:"function"},depends:{type:"object",exported:!1},tags:{type:["array","string"]}};A.defineProperties(A,N);var T=require("custom-ability"),F="event",I="event-bus";var R=(0,T.createAbilityInjector)((function(t){return class{static get emitter(){if(!this._emitter){const t=this.get(I)?.emitter;t&&(this._emitter=t,this.prototype._events=t._events)}return this._emitter}get emitter(){return this.constructor._emitter}on(e,n){const r=t.emitter;if(!r)throw new TypeError("EventBackend required");return r.on(e,n)}once(e,n){const r=t.emitter;if(!r)throw new TypeError("EventBackend required");return r.once(e,n)}off(e,n){const r=t.emitter;if(!r)throw new TypeError("EventBackend required");return r.off(e,n)}emit(e,...n){const r=t.emitter;if(!r)throw new TypeError("EventBackend required");return"error"===e?this.emitError.apply(this,n):r.emit.call(this,e,this.name,...n)}emitError(e,...n){const r=t.emitter;if(!r)throw new TypeError("EventBackend required");return r.emit.call(this,"error",e,this.name,...n)}async emitAsync(e,...n){const r=t.emitter;if(!r)throw new TypeError("EventBackend required");return r.emitAsync.call(this,e,this.name,...n)}}}),!0);function P(t,e){return!t||t.some((t=>t instanceof RegExp?t.test(e):t===e))}var q=class{get active(){return this._active}set active(t){t!==this._active&&(t?(this.pingTimer&&(clearInterval(this.pingTimer),this.pingTimer=void 0),this.options.pingInterval>0&&(this.pingTimer=setInterval((()=>this.publish()),this.options.pingInterval))):(this.clients.size&&this.clearClients(),this.pingTimer&&(clearInterval(this.pingTimer),this.pingTimer=void 0)),this._active=t)}constructor(t){this.options=Object.assign({},{pingInterval:3e3,maxStreamDuration:3e4,clientRetryInterval:1e3,startId:1,historySize:100,rewind:0,cors:!1},t),this.nextID=this.options.startId,this.clients=new Set,this.messages=[],this.active=!0}publish(t,e){let n,r;this.active||j("Channel closed","SSEChannel",498);let s=e;if(t||e)r=this.nextID++,"object"==typeof t&&(t.event?(s=t.event,void 0!==t.data&&(t=JSON.stringify(t.data))):t=JSON.stringify(t)),t=t?t.split(/[\r\n]+/).map((t=>"data: "+t)).join("\n"):"",n="id: "+r+"\n"+(e?"event: "+e+"\n":"")+(t||"data: ")+"\n\n",this.messages.push({id:r,_eventName:s,output:n});else{if(!this.clients.size)return;n="data: \n\n"}for([...this.clients].filter((t=>!s||P(t.events,s))).forEach(((t,e)=>{t.res.write(n)}));this.messages.length>this.options.historySize;)this.messages.shift();return r}subscribe(t,e,n){this.active||j("Channel closed","SSEChannel",498);const r={req:t,res:e,events:n},s=this.options.maxStreamDuration;let i="max-age=0, stale-while-revalidate=0, stale-if-error=0, no-transform";s>0&&(i+=", s-maxage="+(Math.floor(s/1e3)-1));const o={"Content-Type":"text/event-stream","Cache-Control":i,Connection:"keep-alive"};this.options.cors&&(o["access-control-allow-origin"]="*"),r.req.socket.setNoDelay(!0),r.res.writeHead(200,o);let a="retry: "+this.options.clientRetryInterval+"\n\n";const c=Number.parseInt(t.headers["last-event-id"],10),u=Number.isNaN(c)?this.options.rewind:this.nextID-1-c;return u&&this.messages.filter((t=>P(r.events,t.eventName))).slice(0-u).forEach((t=>{a+=t.output})),r.res.write(a),this.clients.add(r),s>0&&setTimeout((()=>{r.res.writableEnded||this.unsubscribe(r)}),s),r.res.on("close",(()=>this.unsubscribe(r))),r}unsubscribe(t){t.res.end(),this.clients.delete(t)}clearClients(){this.clients.forEach((t=>t.res.end())),this.clients.clear()}listClients(){const t={};return this.clients.forEach((e=>{const n=e.req.socket.remoteAddress??"";n in t||(t[n]=0),t[n]++})),t}getSubscriberCount(){return this.clients.size}},V=class extends A{constructor(){super(...arguments),this._emitter=new h.EventEmitter,this.description="Return event bus",this.result="event"}get emitter(){return this._emitter}func(){return this.emitter}},U=new V(I),B=require("secondary-cache");function M({key:t,value:e,options:n}={}){return void 0!==t?null===e?this.cache.del(t):void 0!==e?this.cache.set(t,e,n):this.cache.get(t):(n&&this.cache.setDefaultOptions(n),this.cache)}function L(t,e){let n=A.get(t);return n||(n=new A(t,{func:M,description:"get/set LRU cache or return the LRUCache object",params:{key:{name:"key",type:"string",description:"the key is undefined means change the default cache options"},value:{name:"value",type:"any",description:"the value to store, if value is null means remove the key"},options:{name:"options",type:"object|number",description:"the optional cache options:{capacity,expires,cleanInterval} or expires"}},result:"any"}),n.cache=new B.Cache(e)),n}var _=L("lrucache"),J={};a(J,{AIChatRoles:()=>K,AIMessageTypes:()=>G,AIStream:()=>Me,AITextGenerationFinishReasons:()=>H,AbortError:()=>O,AbortErrorCode:()=>x,ActionNames:()=>W,AlreadyExistsError:()=>k,AlreadyExistsErrorCode:()=>g,BaseError:()=>E,CommonError:()=>v,ConfigFile:()=>Un.Config,ErrorCode:()=>m,EventBusName:()=>I,EventName:()=>F,FStringPromptTemplate:()=>le,FewShotPromptTemplate:()=>de,FilenameReservedRegex:()=>un,GolangPromptTemplate:()=>pe,HFBuiltins:()=>Qt,HFEnvironment:()=>te,HFInterpreter:()=>Kt,HFTemplate:()=>ee,HfPromptTemplate:()=>ie,InternalErrorCode:()=>y,NotFoundError:()=>S,NotFoundErrorCode:()=>b,NotImplementationError:()=>$,NotImplementedErrorCode:()=>501,PASSING_SCORE:()=>z,PromptExampleSelector:()=>rt,PromptTemplate:()=>tt,PromptTemplateTypes:()=>Z,PromptTypes:()=>X,RStreamErrCode:()=>Te,ReadableStreamError:()=>Ie,RemoteToolFuncSchema:()=>D,ResponseRStreamErrCode:()=>Fe,SSEChannel:()=>q,SSEChannelAlreadyClosedErrCode:()=>498,WindowsReservedNameRegex:()=>ln,XXHashAlgorithm:()=>sn,backendEventable:()=>R,base32768:()=>Ye,createCallbacksTransformer:()=>Ue,createEmptyReadableStream:()=>Pe,createEndWithRepetitionDetector:()=>Nn,createError:()=>C,createEventStreamTransformer:()=>Ve,createHfValueFunc:()=>oe,defaultTemplateFormat:()=>Q,expandEnv:()=>ge,expandObjEnv:()=>xe,extNameLevel:()=>vn,filenameReservedRegex:()=>dn,getAllEnumKeys:()=>kn,getConfigFileNames:()=>Dn,getConfigs:()=>Hn,getKeysPath:()=>jn,getMultiLevelExtname:()=>En,getResponseErrorReadableStream:()=>Re,hfParse:()=>Rt,hfTokenize:()=>ft,interpolateEnv:()=>be,interpolateFString:()=>ce,interpolateGolangTemplate:()=>he,isModelNameMatched:()=>Sn,isValidFilename:()=>yn,isValidFilepath:()=>bn,jsonFilterToWhere:()=>Qn,loadFileFromPaths:()=>In,loadTextFromPaths:()=>Pn,matchUrlProtocol:()=>tr,mimeType:()=>Ln.mimeType,parseFString:()=>ae,parseJsJson:()=>Cn,parseYaml:()=>Wn,reControlCharsRegex:()=>mn,readableFromAsyncIterable:()=>Le,registerYamlTag:()=>zn,sanitizeFilename:()=>gn,sanitizeFilepath:()=>xn,saveConfigFile:()=>Gn,sortedValues:()=>we,splitSentence:()=>je,stringifyYaml:()=>_n.stringify,throwError:()=>j,trimStartOfStreamHelper:()=>Be,truncTo:()=>Ae,uuid:()=>He,uuidNIL:()=>We.NIL,uuidParse:()=>We.parse,uuidStringify:()=>We.stringify,uuidValidate:()=>We.validate,uuidVersion:()=>We.version,uuidv1:()=>We.v1,uuidv4:()=>We.v4,uuidv5:()=>We.v5,wait:()=>Ne,xxhash:()=>on,xxhash32:()=>nn,xxhash64:()=>rn,xxhashAsStr:()=>an});var z=.618,W=["get","post","put","delete","patch","list","res"],D={apiRoot:{type:"string",get(){return this._apiRoot??this.constructor.apiRoot},set(t){this._apiRoot=t}},action:{type:"string",assign:(t,e,n,r,s)=>t||"post"},fetchOptions:{type:"object"},allowExportFunc:{type:"boolean"},stream:{type:"boolean"}},H=["stop","length","content-filter","tool-calls","abort","error","other",null],G=["human","ai","generic","system","tool"],K=["user","assistant","system","tool","tool_calls"],X=["chat","char","plan"],Z=["internal","hf","fill"],Y=require("custom-factory");var Q="default",tt=class t extends Y.BaseFactory{static from(t,e){return new this(t,e)}static async format(t){return new this(t).format()}static async formatIf(t){if(this.isTemplate(t)){return new this(t).format()}}static isTemplate(e){if(e?.template){const n=e.templateFormat||Q,r=t.get(n);return r.isTemplate!==t.isTemplate&&r.isTemplate(e)}}filterData(t){return Array.isArray(this.inputVariables)&&(t=Object.fromEntries(Object.entries(t).filter((([t])=>this.inputVariables.includes(t))))),t}constructor(e,n){"string"==typeof e?(n||(n={}),n.template=e):e&&(e=(n=e).template);const{templateFormat:r}=n||{};if(super(n),this.constructor===t){const e=t.get(r||Q);if(e)return Reflect.construct(e,arguments);throw new v(`Prompt template type ${r} not found`,"PromptTemplate",400)}}_initialize(t){throw new $("Not implemented","PromptTemplate")}initialize(e){this.constructor!==t&&(Object.assign(this,this.toJSON(e)),e?.ignoreInitialize||this._initialize(e))}_format(t){throw new $("Not implemented","PromptTemplate")}async format(e){const n=this.data;if(e={...n,...e},n)for(const[t,r]of Object.entries(n))e[t]===r&&"function"==typeof r&&(delete e[t],e[t]=await r(e));for(const[n,r]of Object.entries(e))r instanceof t&&(delete e[n],e[n]=await r.format(e));return this._format(e)}partial(t){t={...this.data,...t};const e=this.toJSON();return e.data=t,e.ignoreInitialize=!0,new this.constructor(e)}toJSON(e=this){let n={template:e.template,data:e.data,inputVariables:e.inputVariables,compiledTemplate:e.compiledTemplate};var r;return e.templateFormat&&t.get(e.templateFormat)!==this.constructor&&(n.templateFormat=e.templateFormat),r=n,n=Object.keys(r).reduce(((t,e)=>{const n=r[e];return null!=n&&(t[e]=n),t}),{}),n}};function et(t){return(e=t)&&"function"==typeof e[Symbol.iterator]?async function*(t){const e=t[Symbol.iterator]();let n;try{for(;;){n=!1;const t=e.next();if(n=!0,t.done)return n=!1,await t.value;yield await t.value}}finally{n&&await(e.return?.().value)}}(t):t;var e}var nt=!1;(async function(){let t=!1,e=!1;try{for await(const e of function*(){try{yield Promise.reject()}finally{t=!0}}())throw new Error("impossible")}catch{e=!0}return e&&t})().then((t=>{nt=t}));var rt=class{constructor(t,e){this.initialize(t,e)}initialize(t,e){const n=e?.maxLength;var r;n>0&&(this.maxLength=n),void 0!==e?.threshold&&(!0===e.threshold?this.threshold=.5:!1!==e.threshold&&(this.threshold=e.threshold)),this.examples=(r=t,nt?r:et(r))}selectExample(t,e){if(void 0===e||e<=this.threshold)return t}async*selectExamples(t=this.examples){let e=this.maxLength||1/0;for await(const n of t){const t="number"==typeof this.threshold?Math.random():void 0;if(this.selectExample(n,t)){if(--e<0)break;yield n}}}async*[Symbol.asyncIterator](){yield*this.selectExamples()}},st=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",BooleanLiteral:"BooleanLiteral",StringLiteral:"StringLiteral",Identifier:"Identifier",Equals:"Equals",OpenParen:"OpenParen",CloseParen:"CloseParen",OpenStatement:"OpenStatement",CloseStatement:"CloseStatement",OpenExpression:"OpenExpression",CloseExpression:"CloseExpression",OpenSquareBracket:"OpenSquareBracket",CloseSquareBracket:"CloseSquareBracket",OpenCurlyBracket:"OpenCurlyBracket",CloseCurlyBracket:"CloseCurlyBracket",Comma:"Comma",Dot:"Dot",Colon:"Colon",Pipe:"Pipe",CallOperator:"CallOperator",AdditiveBinaryOperator:"AdditiveBinaryOperator",MultiplicativeBinaryOperator:"MultiplicativeBinaryOperator",ComparisonBinaryOperator:"ComparisonBinaryOperator",UnaryOperator:"UnaryOperator",Set:"Set",If:"If",For:"For",In:"In",Is:"Is",NotIn:"NotIn",Else:"Else",EndIf:"EndIf",ElseIf:"ElseIf",EndFor:"EndFor",And:"And",Or:"Or",Not:"UnaryOperator"}),it=Object.freeze({set:st.Set,for:st.For,in:st.In,is:st.Is,if:st.If,else:st.Else,endif:st.EndIf,elif:st.ElseIf,endfor:st.EndFor,and:st.And,or:st.Or,not:st.Not,"not in":st.NotIn,true:st.BooleanLiteral,false:st.BooleanLiteral}),ot=class{constructor(t,e){this.value=t,this.type=e}};function at(t){return/\w/.test(t)}function ct(t){return/[0-9]/.test(t)}var ut=[["{%",st.OpenStatement],["%}",st.CloseStatement],["{{",st.OpenExpression],["}}",st.CloseExpression],["(",st.OpenParen],[")",st.CloseParen],["{",st.OpenCurlyBracket],["}",st.CloseCurlyBracket],["[",st.OpenSquareBracket],["]",st.CloseSquareBracket],[",",st.Comma],[".",st.Dot],[":",st.Colon],["|",st.Pipe],["<=",st.ComparisonBinaryOperator],[">=",st.ComparisonBinaryOperator],["==",st.ComparisonBinaryOperator],["!=",st.ComparisonBinaryOperator],["<",st.ComparisonBinaryOperator],[">",st.ComparisonBinaryOperator],["+",st.AdditiveBinaryOperator],["-",st.AdditiveBinaryOperator],["*",st.MultiplicativeBinaryOperator],["/",st.MultiplicativeBinaryOperator],["%",st.MultiplicativeBinaryOperator],["=",st.Equals]],lt=new Map([["n","\n"],["t","\t"],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function ft(t,e={}){const n=[],r=function(t,e={}){return t.endsWith("\n")&&(t=t.slice(0,-1)),t=t.replace(/{#.*?#}/gs,"{##}"),e.lstrip_blocks&&(t=t.replace(/^[ \t]*({[#%])/gm,"$1")),e.trim_blocks&&(t=t.replace(/([#%]})\n/g,"$1")),t.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}(t,e);let s=0;const i=t=>{let e="";for(;t(r[s]);)if("\\"!==r[s]){if(e+=r[s++],s>=r.length)throw new SyntaxError("Unexpected end of input")}else{if(++s,s>=r.length)throw new SyntaxError("Unexpected end of input");const t=r[s++],n=lt.get(t);if(void 0===n)throw new SyntaxError(`Unexpected escaped character: ${t}`);e+=n}return e};t:for(;s<r.length;){const t=n.at(-1)?.type;if(void 0===t||t===st.CloseStatement||t===st.CloseExpression){let t="";for(;s<r.length&&("{"!==r[s]||"%"!==r[s+1]&&"{"!==r[s+1]);)t+=r[s++];if(t.length>0){n.push(new ot(t,st.Text));continue}}i((t=>/\s/.test(t)));const e=r[s];if("-"===e||"+"===e){const t=n.at(-1)?.type;if(t===st.Text||void 0===t)throw new SyntaxError(`Unexpected character: ${e}`);switch(t){case st.Identifier:case st.NumericLiteral:case st.BooleanLiteral:case st.StringLiteral:case st.CloseParen:case st.CloseSquareBracket:break;default:{++s;const t=i(ct);n.push(new ot(`${e}${t}`,t.length>0?st.NumericLiteral:st.UnaryOperator));continue}}}for(const[t,e]of ut){if(r.slice(s,s+t.length)===t){n.push(new ot(t,e)),s+=t.length;continue t}}if("'"!==e&&'"'!==e)if(ct(e)){const t=i(ct);n.push(new ot(t,st.NumericLiteral))}else{if(!at(e))throw new SyntaxError(`Unexpected character: ${e}`);{const t=i(at),e=Object.hasOwn(it,t)?it[t]:st.Identifier;e===st.In&&n.at(-1)?.type===st.Not?(n.pop(),n.push(new ot("not in",st.NotIn))):n.push(new ot(t,e))}}else{++s;const t=i((t=>t!==e));n.push(new ot(t,st.StringLiteral)),++s}}return n}var ht=class{constructor(){this.type="Statement"}},pt=class extends ht{constructor(t){super(),this.body=t,this.type="Program"}},wt=class extends ht{constructor(t,e,n){super(),this.test=t,this.body=e,this.alternate=n,this.type="If"}},dt=class extends ht{constructor(t,e,n){super(),this.loopvar=t,this.iterable=e,this.body=n,this.type="For"}},mt=class extends ht{constructor(t,e){super(),this.assignee=t,this.value=e,this.type="Set"}},yt=class extends ht{constructor(){super(...arguments),this.type="Expression"}},bt=class extends yt{constructor(t,e,n){super(),this.object=t,this.property=e,this.computed=n,this.type="MemberExpression"}},gt=class extends yt{constructor(t,e){super(),this.callee=t,this.args=e,this.type="CallExpression"}},xt=class extends yt{constructor(t){super(),this.value=t,this.type="Identifier"}},Et=class extends yt{constructor(t){super(),this.value=t,this.type="Literal"}},vt=class extends Et{constructor(){super(...arguments),this.type="NumericLiteral"}},$t=class extends Et{constructor(){super(...arguments),this.type="StringLiteral"}},St=class extends Et{constructor(){super(...arguments),this.type="BooleanLiteral"}},kt=class extends Et{constructor(){super(...arguments),this.type="ArrayLiteral"}},Ot=class extends Et{constructor(){super(...arguments),this.type="TupleLiteral"}},Ct=class extends Et{constructor(){super(...arguments),this.type="ObjectLiteral"}},jt=class extends yt{constructor(t,e,n){super(),this.operator=t,this.left=e,this.right=n,this.type="BinaryExpression"}},At=class extends yt{constructor(t,e){super(),this.operand=t,this.filter=e,this.type="FilterExpression"}},Nt=class extends yt{constructor(t,e,n){super(),this.operand=t,this.negate=e,this.test=n,this.type="TestExpression"}},Tt=class extends yt{constructor(t,e){super(),this.operator=t,this.argument=e,this.type="UnaryExpression"}},Ft=class extends yt{constructor(t=void 0,e=void 0,n=void 0){super(),this.start=t,this.stop=e,this.step=n,this.type="SliceExpression"}},It=class extends yt{constructor(t,e){super(),this.key=t,this.value=e,this.type="KeywordArgumentExpression"}};function Rt(t){const e=new pt([]);let n=0;function r(e,r){const s=t[n++];if(!s||s.type!==e)throw new Error(`Parser Error: ${r}. ${s.type} !== ${e}.`);return s}function s(){let e;switch(t[n].type){case st.Text:e=new $t(r(st.Text,"Expected text token").value);break;case st.OpenStatement:e=function(){let e;switch(r(st.OpenStatement,"Expected opening statement token"),t[n].type){case st.Set:++n,e=a(),r(st.CloseStatement,"Expected closing statement token");break;case st.If:++n,e=c(),r(st.OpenStatement,"Expected {% token"),r(st.EndIf,"Expected endif token"),r(st.CloseStatement,"Expected %} token");break;case st.For:++n,e=function(){const t=u(!0);if(!(t instanceof xt||t instanceof Ot))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${t.type} instead`);r(st.In,"Expected `in` keyword following loop variable");const e=l();r(st.CloseStatement,"Expected closing statement token");const n=[];for(;i(st.OpenStatement,st.EndFor);)n.push(s());return new dt(t,e,n)}(),r(st.OpenStatement,"Expected {% token"),r(st.EndFor,"Expected endfor token"),r(st.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${t[n].type}`)}return e}(),e.isStatement=!0;break;case st.OpenExpression:e=function(){r(st.OpenExpression,"Expected opening expression token");const t=l();return r(st.CloseExpression,"Expected closing expression token"),t}(),e.isStatement=!0;break;default:throw new SyntaxError(`Unexpected token type: ${t[n].type}`)}return e}function i(...e){return n+e.length<=t.length&&e.some(((e,r)=>e!==t[n+r].type))}function o(...e){return n+e.length<=t.length&&e.every(((e,r)=>e===t[n+r].type))}function a(){const t=l();if(o(st.Equals)){++n;const e=a();return new mt(t,e)}return t}function c(){const e=l();r(st.CloseStatement,"Expected closing statement token");const i=[],a=[];for(;t[n]?.type!==st.OpenStatement||t[n+1]?.type!==st.ElseIf&&t[n+1]?.type!==st.Else&&t[n+1]?.type!==st.EndIf;)i.push(s());if(t[n]?.type===st.OpenStatement&&t[n+1]?.type!==st.EndIf)if(++n,o(st.ElseIf))r(st.ElseIf,"Expected elseif token"),a.push(c());else for(r(st.Else,"Expected else token"),r(st.CloseStatement,"Expected closing statement token");t[n]?.type!==st.OpenStatement||t[n+1]?.type!==st.EndIf;)a.push(s());return new wt(e,i,a)}function u(t=!1){const e=t?x:l,r=[e()],s=o(st.Comma);for(;s&&(++n,r.push(e()),o(st.Comma)););return s?new Ot(r):r[0]}function l(){return function(){const t=f();if(o(st.If)){++n;const e=f();r(st.Else,"Expected else token");const s=f();return new wt(e,[t],[s])}return t}()}function f(){let e=h();for(;o(st.Or);){const r=t[n];++n;const s=h();e=new jt(r,e,s)}return e}function h(){let e=p();for(;o(st.And);){const r=t[n];++n;const s=p();e=new jt(r,e,s)}return e}function p(){let e;for(;o(st.Not);){const r=t[n];++n;const s=p();e=new Tt(r,s)}return e??function(){let e=w();for(;o(st.ComparisonBinaryOperator)||o(st.In)||o(st.NotIn);){const r=t[n];++n;const s=w();e=new jt(r,e,s)}return e}()}function w(){let e=b();for(;o(st.AdditiveBinaryOperator);){const r=t[n];++n;const s=b();e=new jt(r,e,s)}return e}function d(){const e=function(){let e=x();for(;o(st.Dot)||o(st.OpenSquareBracket);){const s=t[n];let i;++n;const o=s.type!==st.Dot;if(o)i=y(),r(st.CloseSquareBracket,"Expected closing square bracket");else if(i=x(),"Identifier"!==i.type)throw new SyntaxError("Expected identifier following dot operator");e=new bt(e,i,o)}return e}();return o(st.OpenParen)?m(e):e}function m(t){let e=new gt(t,function(){r(st.OpenParen,"Expected opening parenthesis for arguments list");const t=function(){const t=[];for(;!o(st.CloseParen);){let e=l();if(o(st.Equals)){if(++n,!(e instanceof xt))throw new SyntaxError("Expected identifier for keyword argument");const t=l();e=new It(e,t)}t.push(e),o(st.Comma)&&++n}return t}();return r(st.CloseParen,"Expected closing parenthesis for arguments list"),t}());return o(st.OpenParen)&&(e=m(e)),e}function y(){const t=[];let e=!1;for(;!o(st.CloseSquareBracket);)o(st.Colon)?(t.push(void 0),++n,e=!0):(t.push(l()),o(st.Colon)&&(++n,e=!0));if(0===t.length)throw new SyntaxError("Expected at least one argument for member/slice expression");if(e){if(t.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new Ft(...t)}return t[0]}function b(){let e=g();for(;o(st.MultiplicativeBinaryOperator);){const r=t[n];++n;const s=g();e=new jt(r,e,s)}return e}function g(){let t=function(){let t=d();for(;o(st.Pipe);){++n;let e=x();if(!(e instanceof xt))throw new SyntaxError("Expected identifier for the filter");o(st.OpenParen)&&(e=m(e)),t=new At(t,e)}return t}();for(;o(st.Is);){++n;const e=o(st.Not);e&&++n;let r=x();if(r instanceof St&&(r=new xt(r.value.toString())),!(r instanceof xt))throw new SyntaxError("Expected identifier for the test");t=new Nt(t,e,r)}return t}function x(){const e=t[n];switch(e.type){case st.NumericLiteral:return++n,new vt(Number(e.value));case st.StringLiteral:return++n,new $t(e.value);case st.BooleanLiteral:return++n,new St("true"===e.value);case st.Identifier:return++n,new xt(e.value);case st.OpenParen:{++n;const e=u();if(t[n].type!==st.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${t[n].type} instead`);return++n,e}case st.OpenSquareBracket:{++n;const t=[];for(;!o(st.CloseSquareBracket);)t.push(l()),o(st.Comma)&&++n;return++n,new kt(t)}case st.OpenCurlyBracket:{++n;const t=new Map;for(;!o(st.CloseCurlyBracket);){const e=l();r(st.Colon,"Expected colon between key and value in object literal");const s=l();t.set(e,s),o(st.Comma)&&++n}return++n,new Ct(t)}default:throw new SyntaxError(`Unexpected token: ${e.type}`)}}for(;n<t.length;)e.body.push(s());return e}function Pt(t,e,n=1){void 0===e&&(e=t,t=0);const r=[];for(let s=t;s<e;s+=n)r.push(s);return r}function qt(t,e,n,r=1){const s=Math.sign(r);s>=0?(e=(e??=0)<0?Math.max(t.length+e,0):Math.min(e,t.length),n=(n??=t.length)<0?Math.max(t.length+n,0):Math.min(n,t.length)):(e=(e??=t.length-1)<0?Math.max(t.length+e,-1):Math.min(e,t.length-1),n=(n??=-1)<-1?Math.max(t.length+n,-1):Math.min(n,t.length-1));const i=[];for(let o=e;s*o<s*n;o+=r)i.push(t[o]);return i}function Vt(t){return t.replace(/\b\w/g,(t=>t.toUpperCase()))}var Ut=class{constructor(t=void 0){this.type="RuntimeValue",this.builtins=new Map,this.value=t}__bool__(){return new Lt(!!this.value)}toString(){return""+this.value}toJSON(){return this.value}},Bt=class extends Ut{constructor(){super(...arguments),this.type="NumericValue"}},Mt=class t extends Ut{constructor(){super(...arguments),this.type="StringValue",this.builtins=new Map([["upper",new Wt((()=>new t(this.value.toUpperCase())))],["lower",new Wt((()=>new t(this.value.toLowerCase())))],["strip",new Wt((()=>new t(this.value.trim())))],["title",new Wt((()=>new t(Vt(this.value))))],["length",new Bt(this.value.length)],["rstrip",new Wt((()=>new t(this.value.trimEnd())))],["lstrip",new Wt((()=>new t(this.value.trimStart())))]])}},Lt=class extends Ut{constructor(){super(...arguments),this.type="BooleanValue"}},_t=class extends Ut{constructor(t,e){super(t),this.orgValue=e,this.type="ObjectValue",this.builtins=new Map([["get",new Wt((([t,e])=>{if(!(t instanceof Mt))throw new Error(`Object key must be a string: got ${t.type}`);return this.value.get(t.value)??e??new Dt}))],["items",new Wt((()=>new Jt(Array.from(this.value.entries()).map((([t,e])=>new Jt([new Mt(t),e]))))))]])}toString(){let t;return t=this.orgValue&&this.orgValue.toString!==Object.prototype.toString?this.orgValue.toString():JSON.stringify(Object.fromEntries(this.value.entries())),t}toJSON(){return this.orgValue?this.orgValue:Object.fromEntries(this.value.entries())}__bool__(){return new Lt(this.value.size>0)}},Jt=class extends Ut{constructor(){super(...arguments),this.type="ArrayValue",this.builtins=new Map([["length",new Bt(this.value.length)]])}__bool__(){return new Lt(this.value.length>0)}},zt=class extends Jt{constructor(){super(...arguments),this.type="TupleValue"}},Wt=class extends Ut{constructor(){super(...arguments),this.type="FunctionValue"}},Dt=class extends Ut{constructor(){super(...arguments),this.type="NullValue"}},Ht=class extends Ut{constructor(){super(...arguments),this.type="UndefinedValue"}},Gt=class{constructor(t){this.parent=t,this.variables=new Map([["namespace",new Wt((t=>{if(0===t.length)return new _t(new Map);if(1!==t.length||!(t[0]instanceof _t))throw new Error("`namespace` expects either zero arguments or a single object argument");return t[0]}))]]),this.tests=new Map([["boolean",t=>"BooleanValue"===t.type],["callable",t=>t instanceof Wt],["odd",t=>{if("NumericValue"!==t.type)throw new Error(`Cannot apply test "odd" to type: ${t.type}`);return t.value%2!=0}],["even",t=>{if("NumericValue"!==t.type)throw new Error(`Cannot apply test "even" to type: ${t.type}`);return t.value%2==0}],["false",t=>"BooleanValue"===t.type&&!t.value],["true",t=>"BooleanValue"===t.type&&t.value],["number",t=>"NumericValue"===t.type],["integer",t=>"NumericValue"===t.type&&Number.isInteger(t.value)],["iterable",t=>t instanceof Jt||t instanceof Mt],["lower",t=>{const e=t.value;return"StringValue"===t.type&&e===e.toLowerCase()}],["upper",t=>{const e=t.value;return"StringValue"===t.type&&e===e.toUpperCase()}],["none",t=>"NullValue"===t.type],["defined",t=>"UndefinedValue"!==t.type],["undefined",t=>"UndefinedValue"===t.type],["equalto",(t,e)=>t.value===e.value]])}set(t,e){return this.declareVariable(t,Xt(e))}declareVariable(t,e){if(this.variables.has(t))throw new SyntaxError(`Variable already declared: ${t}`);return this.variables.set(t,e),e}setVariable(t,e){return this.variables.set(t,e),e}resolve(t){if(this.variables.has(t))return this;if(this.parent)return this.parent.resolve(t);throw new Error(`Unknown variable: ${t}`)}lookupVariable(t){try{return this.resolve(t).variables.get(t)??new Ht}catch{return new Ht}}},Kt=class{constructor(t){this.global=t??new Gt}run(t){return this.evaluate(t,this.global)}evaluateBinaryExpression(t,e){const n=this.evaluate(t.left,e);switch(t.operator.value){case"and":return n.__bool__().value?this.evaluate(t.right,e):n;case"or":return n.__bool__().value?n:this.evaluate(t.right,e)}const r=this.evaluate(t.right,e);switch(t.operator.value){case"==":return new Lt(n.value==r.value);case"!=":return new Lt(n.value!=r.value)}if(n instanceof Ht||r instanceof Ht)throw new Error("Cannot perform operation on undefined values");if(n instanceof Dt||r instanceof Dt)throw new Error("Cannot perform operation on null values");if(n instanceof Bt&&r instanceof Bt)switch(t.operator.value){case"+":return new Bt(n.value+r.value);case"-":return new Bt(n.value-r.value);case"*":return new Bt(n.value*r.value);case"/":return new Bt(n.value/r.value);case"%":return new Bt(n.value%r.value);case"<":return new Lt(n.value<r.value);case">":return new Lt(n.value>r.value);case">=":return new Lt(n.value>=r.value);case"<=":return new Lt(n.value<=r.value)}else if(n instanceof Jt&&r instanceof Jt){if("+"===t.operator.value)return new Jt(n.value.concat(r.value))}else if(r instanceof Jt){const e=void 0!==r.value.find((t=>t.value===n.value));switch(t.operator.value){case"in":return new Lt(e);case"not in":return new Lt(!e)}}if((n instanceof Mt||r instanceof Mt)&&"+"===t.operator.value)return new Mt(n.toString()+r.toString());if(n instanceof Mt&&r instanceof Mt)switch(t.operator.value){case"in":return new Lt(r.value.includes(n.value));case"not in":return new Lt(!r.value.includes(n.value))}if(n instanceof Mt&&r instanceof _t)switch(t.operator.value){case"in":return new Lt(r.value.has(n.value));case"not in":return new Lt(!r.value.has(n.value))}throw new SyntaxError(`Unknown operator "${t.operator.value}" between ${n.type} and ${r.type}`)}evaluateFilterExpression(t,e){const n=this.evaluate(t.operand,e);if("Identifier"===t.filter.type){const e=t.filter;if(n instanceof Jt)switch(e.value){case"list":return n;case"first":return n.value[0];case"last":return n.value[n.value.length-1];case"length":return new Bt(n.value.length);case"reverse":return new Jt(n.value.reverse());case"sort":return new Jt(n.value.sort(((t,e)=>{if(t.type!==e.type)throw new Error(`Cannot compare different types: ${t.type} and ${e.type}`);switch(t.type){case"NumericValue":return t.value-e.value;case"StringValue":return t.value.localeCompare(e.value);default:throw new Error(`Cannot compare type: ${t.type}`)}})));case"tojson":return new Mt(JSON.stringify(n.value));default:throw new Error(`Unknown ArrayValue filter: ${e.value}`)}else if(n instanceof Mt)switch(e.value){case"length":return new Bt(n.value.length);case"upper":return new Mt(n.value.toUpperCase());case"lower":return new Mt(n.value.toLowerCase());case"title":return new Mt(Vt(n.value));case"capitalize":return new Mt(n.value.charAt(0).toUpperCase()+n.value.slice(1));case"trim":return new Mt(n.value.trim());case"trimStart":return new Mt(n.value.trimStart());case"trimEnd":return new Mt(n.value.trimEnd());default:throw new Error(`Unknown StringValue filter: ${e.value}`)}else{if(n instanceof Bt){if("abs"===e.value)return new Bt(Math.abs(n.value));throw new Error(`Unknown NumericValue filter: ${e.value}`)}if(n instanceof _t)switch(e.value){case"items":return new Jt(Array.from(n.value.entries()).map((([t,e])=>new Jt([new Mt(t),e]))));case"length":return new Bt(n.value.size);case"tojson":return new Mt(JSON.stringify(n));case"string":return new Mt(n.toString());default:throw new Error(`Unknown ObjectValue filter: ${e.value}`)}}throw new Error(`Cannot apply filter "${e.value}" to type: ${n.type}`)}if("CallExpression"===t.filter.type){const r=t.filter;if("Identifier"!==r.callee.type)throw new Error(`Unknown filter: ${r.callee.type}`);const s=r.callee.value,i=e.lookupVariable(s);if(i instanceof Wt)return i.value([n,...r.args.map((t=>this.evaluate(t,e)))],e);if(n instanceof Jt){if("selectattr"===s){if(n.value.some((t=>!(t instanceof _t))))throw new Error("`selectattr` can only be applied to array of objects");if(r.args.some((t=>"StringLiteral"!==t.type)))throw new Error("arguments of `selectattr` must be strings");const[t,s,i]=r.args.map((t=>this.evaluate(t,e)));let o;if(s){const t=e.tests.get(s.value);if(!t)throw new Error(`Unknown test: ${s.value}`);o=t}else o=(...t)=>t[0].__bool__().value;const a=n.value.filter((e=>{const n=e.value.get(t.value);return!!n&&o(n,i)}));return new Jt(a)}throw new Error(`Unknown ArrayValue filter: ${s}`)}throw new Error(`Cannot apply filter "${s}" to type: ${n.type}`)}throw new Error(`Unknown filter: ${t.filter.type}`)}evaluateTestExpression(t,e){const n=this.evaluate(t.operand,e),r=e.tests.get(t.test.value);if(!r)throw new Error(`Unknown test: ${t.test.value}`);const s=r(n);return new Lt(t.negate?!s:s)}evaluateUnaryExpression(t,e){const n=this.evaluate(t.argument,e);if("not"===t.operator.value)return new Lt(!n.value);throw new SyntaxError(`Unknown operator: ${t.operator.value}`)}evalProgram(t,e){return this.evaluateBlock(t.body,e)}evaluateBlock(t,e){let n="";for(const r of t){const t=this.evaluate(r,e);"NullValue"!==t.type&&"UndefinedValue"!==t.type&&(n+=t)}return new Mt(n)}evaluateIdentifier(t,e){return e.lookupVariable(t.value)}evaluateCallExpression(t,e){const n=[],r=new Map;for(const s of t.args)if("KeywordArgumentExpression"===s.type){const t=s;r.set(t.key.value,this.evaluate(t.value,e))}else n.push(this.evaluate(s,e));r.size>0&&n.push(new _t(r));const s=this.evaluate(t.callee,e);if("FunctionValue"!==s.type)throw new Error(`Cannot call something that is not a function: got ${s.type}`);return s.value(n,e)}evaluateSliceExpression(t,e,n){if(!(t instanceof Jt||t instanceof Mt))throw new Error("Slice object must be an array or string");const r=this.evaluate(e.start,n),s=this.evaluate(e.stop,n),i=this.evaluate(e.step,n);if(!(r instanceof Bt||r instanceof Ht))throw new Error("Slice start must be numeric or undefined");if(!(s instanceof Bt||s instanceof Ht))throw new Error("Slice stop must be numeric or undefined");if(!(i instanceof Bt||i instanceof Ht))throw new Error("Slice step must be numeric or undefined");return t instanceof Jt?new Jt(qt(t.value,r.value,s.value,i.value)):new Mt(qt(Array.from(t.value),r.value,s.value,i.value).join(""))}evaluateMemberExpression(t,e){const n=this.evaluate(t.object,e);let r,s;if(t.computed){if("SliceExpression"===t.property.type)return this.evaluateSliceExpression(n,t.property,e);r=this.evaluate(t.property,e)}else r=new Mt(t.property.value);if(n instanceof _t){if(!(r instanceof Mt))throw new Error(`Cannot access property with non-string: got ${r.type}`);s=n.value.get(r.value)??n.builtins.get(r.value)}else if(n instanceof Jt||n instanceof Mt)if(r instanceof Bt)s=n.value.at(r.value),n instanceof Mt&&(s=new Mt(n.value.at(r.value)));else{if(!(r instanceof Mt))throw new Error(`Cannot access property with non-string/non-number: got ${r.type}`);s=n.builtins.get(r.value)}else{if(!(r instanceof Mt))throw new Error(`Cannot access property with non-string: got ${r.type}`);s=n.builtins.get(r.value)}return s instanceof Ut?s:new Ht}evaluateSet(t,e){const n=this.evaluate(t.value,e);if("Identifier"===t.assignee.type){const r=t.assignee.value;e.setVariable(r,n)}else{if("MemberExpression"!==t.assignee.type)throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(t.assignee)}`);{const r=t.assignee,s=this.evaluate(r.object,e);if(!(s instanceof _t))throw new Error("Cannot assign to member of non-object");if("Identifier"!==r.property.type)throw new Error("Cannot assign to member with non-identifier property");s.value.set(r.property.value,n)}}return new Dt}evaluateIf(t,e){const n=this.evaluate(t.test,e);return this.evaluateBlock(n.__bool__().value?t.body:t.alternate,e)}evaluateFor(t,e){const n=new Gt(e),r=this.evaluate(t.iterable,n);if(!(r instanceof Jt))throw new Error(`Expected iterable type in for loop: got ${r.type}`);let s="";for(let e=0;e<r.value.length;++e){const i=new Map([["index",new Bt(e+1)],["index0",new Bt(e)],["revindex",new Bt(r.value.length-e)],["revindex0",new Bt(r.value.length-e-1)],["first",new Lt(0===e)],["last",new Lt(e===r.value.length-1)],["length",new Bt(r.value.length)],["previtem",e>0?r.value[e-1]:new Ht],["nextitem",e<r.value.length-1?r.value[e+1]:new Ht]]);n.setVariable("loop",new _t(i));const o=r.value[e];if("Identifier"===t.loopvar.type)n.setVariable(t.loopvar.value,o);else if("TupleLiteral"===t.loopvar.type){const e=t.loopvar;if("ArrayValue"!==o.type)throw new Error(`Cannot unpack non-iterable type: ${o.type}`);const r=o;if(e.value.length!==r.value.length)throw new Error(`Too ${e.value.length>r.value.length?"few":"many"} items to unpack`);for(let t=0;t<e.value.length;++t){if("Identifier"!==e.value[t].type)throw new Error(`Cannot unpack non-identifier type: ${e.value[t].type}`);n.setVariable(e.value[t].value,r.value[t])}}s+=this.evaluateBlock(t.body,n).value}return new Mt(s)}evaluate(t,e){if(void 0===t)return new Ht;switch(t.type){case"Program":return this.evalProgram(t,e);case"Set":return this.evaluateSet(t,e);case"If":return this.evaluateIf(t,e);case"For":return this.evaluateFor(t,e);case"NumericLiteral":return new Bt(Number(t.value));case"StringLiteral":return new Mt(t.value);case"BooleanLiteral":return new Lt(t.value);case"ArrayLiteral":return new Jt(t.value.map((t=>this.evaluate(t,e))));case"TupleLiteral":return new zt(t.value.map((t=>this.evaluate(t,e))));case"ObjectLiteral":{const n=new Map;for(const[r,s]of t.value){const t=this.evaluate(r,e);if(!(t instanceof Mt))throw new Error(`Object keys must be strings: got ${t.type}`);n.set(t.value,this.evaluate(s,e))}return new _t(n,t.value)}case"Identifier":return this.evaluateIdentifier(t,e);case"CallExpression":return this.evaluateCallExpression(t,e);case"MemberExpression":return this.evaluateMemberExpression(t,e);case"UnaryExpression":return this.evaluateUnaryExpression(t,e);case"BinaryExpression":return this.evaluateBinaryExpression(t,e);case"FilterExpression":return this.evaluateFilterExpression(t,e);case"TestExpression":return this.evaluateTestExpression(t,e);default:throw new SyntaxError(`Unknown node type: ${t.type}`)}}};function Xt(t){switch(typeof t){case"number":return new Bt(t);case"string":return new Mt(t);case"boolean":return new Lt(t);case"object":return null===t?new Dt:Array.isArray(t)?new Jt(t.map(Xt)):new _t(new Map(Object.entries(t).map((([t,e])=>[t,Xt(e)]))),t);case"function":return new Wt(((e,n)=>{const r=e.map((t=>Zt(t)));return Xt(t(...r)??null)}));default:throw new Error(`Cannot convert to runtime value: ${t}`)}}function Zt(t){let e=t;return Array.isArray(t)?e=t.map((t=>Zt(t))):t instanceof Map?(e={},t.forEach(((t,n)=>{e[n]=Zt(t)}))):"ObjectValue"===t.type?t.orgValue?e=t.orgValue:(e={},t.forEach(((t,n)=>{e[n]=Zt(t)}))):"ArrayValue"===t.type?e=t.value.map((t=>Zt(t))):t.type&&(e=t.value),e}function Yt(t,e=0){return Math.floor(Math.random()*(t-e+1))+e}var Qt={randomInt:Yt,select:function(t,e){if(Array.isArray(t)||"string"==typeof t)return void 0===e?e=Yt(t.length-1):"string"==typeof e&&(e=parseInt(e)),e<0&&(e=t.length+e),t[e];if(t&&"object"==typeof t){if(void 0===e){const n=Object.keys(t);e=n[Yt(n.length-1)]}return t[e]}}},te=class extends Gt{constructor(t){super(t),this.parent=t}assign(t){for(const[e,n]of Object.entries(t))this.set(e,n)}clear(){this.variables.clear()}},ee=class t{static{this.global=new te}constructor(t,e={}){const n=ft(t,e={lstrip_blocks:!0,trim_blocks:!0,...e});this.parsed=Rt(n)}render(e){const n=new Gt(t.global);n.set("false",!1),n.set("true",!0),n.set("raise_exception",(t=>{throw new Error(t)})),n.set("range",Pt);for(const[t,r]of Object.entries(e))n.set(t,r);return new Kt(n).run(this.parsed).toString()}};function ne(t,e){let n;switch(t.type){case"Identifier":n=t.value;break;case"MemberExpression":n=ne(t.object,e);break;case"FilterExpression":n=ne(t.operand,e);break;case"Set":{e||(e=[]);const r=ne(t.assignee);r&&e.push(r),n=ne(t.value,e);break}}return n&&e?.includes(n)&&(n=void 0),n}function re(t){let e;if("Program"===t.type)e=t.body.some((t=>re(t)));else e=t.isStatement;return e}function se(t,e){let n=[];if(Array.isArray(t))n=t.map((t=>se(t,e))).filter(Boolean).flat();else switch(t.type){case"Program":n=t.body.map((t=>se(t,e))).filter(Boolean).flat();break;case"If":n=[ne(t.test,e),...se(t.body,e),...se(t.alternate,e)].filter(Boolean);break;case"BinaryExpression":n=[ne(t.left,e),ne(t.right,e)].filter(Boolean);break;case"For":{const r=ne(t.loopvar);r&&(e||(e=[]),e.push(r)),n=[ne(t.iterable,e),...se(t.body,e)].filter(Boolean);break}case"CallExpression":n=[ne(t.callee,e),...se(t.args,e)].filter(Boolean);break;default:n=[ne(t,e)].filter(Boolean)}return n}ee.global.assign(Qt);var ie=class extends tt{static isTemplate(t){let e,n,r=!1;if("object"==typeof t?(n=t.template,e=t.compiledTemplate):n=t,!e&&n)try{e=new ee(n)}catch(t){}return e&&(r=re(e.parsed)),r}getVariables(t=this.compiledTemplate){return se(t.parsed,[]).filter(((t,e,n)=>n.indexOf(t)===e))}_initialize(t){const e=t?.template;if("string"!=typeof e)throw new v("Prompt template must be a string","PromptTemplate",400);this.compiledTemplate=new ee(e),this.inputVariables=Array.isArray(t?.inputVariables)?t.inputVariables:this.getVariables()}_format(t){return this.compiledTemplate.render(t)}};function oe(t){return function(e){return t}}function ae(t){const e=t.split(""),n=[],r=(t,n)=>{for(let r=n;r<e.length;r+=1)if(t.includes(e[r]))return r;return-1};let s=0;for(;s<e.length;)if("{"===e[s]&&s+1<e.length&&"{"===e[s+1])n.push({type:"literal",text:"{"}),s+=2;else if("}"===e[s]&&s+1<e.length&&"}"===e[s+1])n.push({type:"literal",text:"}"}),s+=2;else if("{"===e[s]){const t=r("}",s);if(t<0)throw new Error("Unclosed '{' in template.");n.push({type:"variable",name:e.slice(s+1,t).join("")}),s=t+1}else{if("}"===e[s])throw new Error("Single '}' in template.");{const t=r("{}",s),i=(t<0?e.slice(s):e.slice(s,t)).join("");n.push({type:"literal",text:i}),s=t<0?e.length:t}}return n}function ce(t,e){return t.reduce(((t,n)=>{let r;return r="variable"===n.type?n.name in e?t+e[n.name]:t:t+n.text,r}),"")}function ue(t){const e=new Set;return t.forEach((t=>{"variable"===t.type&&e.add(t.name)})),[...e]}tt.register(ie,{name:"hf",aliases:["huggingface","internal","default"]});var le=class extends tt{static isTemplate(t){let e,n,r=!1;if("object"==typeof t?(n=t.template,e=t.compiledTemplate):n=t,!e&&n)try{e=ae(n)}catch(t){}if(e){r=ue(e).length>0}return r}getVariables(t=this.compiledTemplate){return ue(t)}_initialize(t){const e=t?.template;if("string"!=typeof e)throw new v("Prompt template must be a string","PromptTemplate",400);this.compiledTemplate=ae(e),this.inputVariables=Array.isArray(t?.inputVariables)?t.inputVariables:this.getVariables()}_format(t){return ce(this.compiledTemplate,t)}};function fe(t,e){return"string"==typeof e&&(e=e.split(".").filter((t=>t.length))),e.reduce(((t,e)=>t?.[e]),t)}function he(t,e,n){let r=function(t,e,n){return t.replace(/{{\s*re_replace\s+\.(.+?)\s+(["'])([^\2]*?)\2\s+(["'])([^\4]*?)\4\s*}}/g,((t,r,s,i,o,a)=>{if(n)return e[r]=null,t;const c=new RegExp(i,"g");return fe(e,r).replace(c,a)}))}(t,e,n);return r=function(t,e,n){return t.replace(/{{\s*join\s+\.(.+?)\s+(["'])([^\2]*?)\2\s*}}/g,((t,r,s,i)=>n?(e[r]=null,t):fe(e,r).join(i)))}(r,e,n),r=function(t,e,n){return t.replace(/{{\s*if\s*(\S+?)\s*}}([^{]*)({{\s*else\s*}}([^{]*))?{{\s*end\s*}}/g,((t,r,s,i,o)=>{if(n)return r.startsWith(".")&&(r=r.substring(1)),e[r]=null,t;let a;if(!r.startsWith("."))throw new Error("Functionality not implemented");{const t=fe(e,r.substring(1));if(null==t)a=o??"";else if("string"==typeof t)a=t.length>0?s:o??"";else if(Array.isArray(t))a=t.length>0?s:o??"";else{if("boolean"!=typeof t)throw new Error(`Unexpected type for variable ${r}: ${typeof t}`);a=t?s:o??""}}return a}))}(r,e,n),r=function(t,e,n){return t.replace(/{{\s*range\s*[.$]([^{}\s]+?)\s*}}([^{]*?){{\.}}([^{]*?){{\s*end\s*}}/g,((t,r,s,i)=>{if(n)return e[r]=null,t;const o=fe(e,r);if(Array.isArray(o)){let t="";for(const e of o)t+=`${s}${e}${i}`;return t}return t}))}(r,e,n),r=function(t,e,n){return t.replace(/{{\s*\.([^{}\s]+?)\s*}}/g,((t,r)=>n?(e[r]=null,t):fe(e,r)||""))}(r,e,n),r=function(t,e,n){return t.replace(/{{\s*index\s*\.(.+?)\s+(.+?)\s*}}/g,((t,r,s)=>{if(n)return e[r]=null,t;const i=fe(e,r);let o;return o=isNaN(s)?i[s.substring(1,s.length-1)]:i[parseInt(s,10)],o||""}))}(r,e,n),r}tt.register(le,{name:"fstring",aliases:["python","f-string","langchain"]});var pe=class extends tt{static isTemplate(t){const e="string"==typeof t?t:t.template;return e?.includes("{{")&&e.includes("}}")}getVariables(t){const e={};return he(t,e,!0),[...Object.keys(e)]}_initialize(t){const e=t?.template;if("string"!=typeof e)throw new v("Prompt template must be a string","PromptTemplate",400);this.inputVariables=Array.isArray(t?.inputVariables)?t.inputVariables:this.getVariables(e)}_format(t){return he(this.template,t)}};function we(t){return Object.keys(t).sort().map((e=>t[e]))}tt.register(pe,{name:"golang",aliases:["localai","ollama"]});var de=class extends tt{static from(t){return new this(t)}constructor(t){super(t)}_initialize(t){t&&(t.suffix&&(this.suffix=t.suffix),t.exampleSeparator&&(this.exampleSeparator=t.exampleSeparator),t.prefix&&(this.prefix=t.prefix),t.examplePrompt&&(this.examplePrompt=t.examplePrompt instanceof tt?t.examplePrompt:tt.from(t.examplePrompt)),t.examples&&(this.examples=t.examples)),this.prefix||(this.prefix=""),this.exampleSeparator||(this.exampleSeparator="\n\n"),this.suffix||(this.suffix="")}async _format(t){const e=[];for await(const t of this.examples)if(this.examplePrompt){const n=await this.examplePrompt.format(t);e.push(n)}else if("string"==typeof t)e.push(t);else if(t){const n=we(t);n.length>0&&e.push(...n)}const n=[this.prefix,...e,this.suffix].join(this.exampleSeparator),r=this.templateFormat;return await tt.format({template:n,data:t,templateFormat:r})}toJSON(t=this){const e=super.toJSON(t);return t.suffix&&(e.suffix=t.suffix),t.exampleSeparator&&(e.exampleSeparator=t.exampleSeparator),t.prefix&&(e.prefix=t.prefix),t.examplePrompt&&(e.examplePrompt=t.examplePrompt),t.examples&&(e.examples=t.examples),e}};tt.register(de,{name:"fewshot",aliases:["few_shot"]});var me=/(\\)?(\$)(?!\()(\{?)([\w.]+)(?::?-((?:\$\{(?:\$\{(?:\$\{[^}]*\}|[^}])*}|[^}])*}|[^}])+))?(\}?)/gi;function ye(t){return t.replace(/\\\$/g,"$")}function be(t,e,n){return t.replace(me,((r,s,i,o,a,c,u)=>"\\"===s?r.slice(1):e[a]?e[a]===n[a]?e[a]:be(e[a],e,n):n[a]?n[a]===t?n[a]:be(n[a],e,n):c?c.startsWith("$")?be(c,e,n):c:""))}function ge(t){let e=process.env;t&&null!=t.processEnv&&(e=t.processEnv);for(const n in t.parsed){let r=t.parsed[n];if(!r)continue;r=Object.prototype.hasOwnProperty.call(e,n)?e[n]===t.parsed[n]?be(r,e,t.parsed):e[n]:be(r,e,t.parsed),t.parsed[n]=r?ye(r):r}for(const n in t.parsed)e[n]=t.parsed[n];return t}function xe(t,e={},n){switch(n||(n=new WeakSet),e.processEnv||(e.processEnv={...process.env}),e.parsed||(e.parsed=e.processEnv),typeof t){case"string":t=be(t,e.processEnv,e.parsed);break;case"object":if(n.has(t))return t;if(n.add(t),Array.isArray(t))for(let r=0;r<t.length;r++){const s=t[r];"string"!=typeof s&&"object"!=typeof s||(t[r]=xe(t[r],e,n))}else for(const[r,s]of Object.entries(t))"string"!=typeof s&&"object"!=typeof s||(t[r]=xe(s,e,n))}return t}var Ee="@",ve=/(\S.+?[.!?])(?=\s+|$)|(\S.+?)(?=[\n]|$)/g,$e=/([A-Z][a-z]{1,2}\.)\s(\w)/g,Se=/(\.[a-zA-Z]\.)\s(\w)/g,ke=new RegExp("([A-Z][a-z]{1,2}\\.)"+Ee+"(\\w)","g"),Oe=new RegExp("(\\.[a-zA-Z]\\.)"+Ee+"(\\w)","g");function Ce(t,e,n){const r="$1"+e+"$2";let s=t;for(let t=0;t<n.length;t++)s=s.replace(n[t],r);return s}function je(t,e=!0){const n=(t=(t=(t=(t=t.replace(/([。!??])([^”’])/g,"$1\n$2")).replace(/(\.{6})([^”’])/g,"$1\n$2")).replace(/(…{2})([^”’])/g,"$1\n$2")).replace(/([。!??][”’])([^,。!??])/g,"$1\n$2")).split("\n");let r=[];for(let t=0;t<n.length;t++){let s=n[t].trim();if(!s)continue;if(!e){r.push(s);continue}let i=Ce(s,Ee,[$e,Se]),o=Array.from(i.matchAll(ve));if(o.length)for(let t=0;t<o.length;t++){let e=Ce(o[t][0]," ",[ke,Oe]);r.push(e)}else r.push(s)}return r}function Ae(t,e=2,n=.5){const r=10**e;return Math.trunc((t+Number.EPSILON+n/r)*r)/r}async function Ne(t){return new Promise((e=>setTimeout(e,t)))}var Te=600,Fe=601,Ie=class extends E{constructor(t,e=Te){super(t,500)}};function Re(t){if(t){const e=t.getReader();return new ReadableStream({async start(t){const{done:n,value:r}=await e.read();if(!n){const e=(new TextDecoder).decode(r);t.error(new Ie(`Response error: ${e}`,Fe))}}})}return new ReadableStream({start(t){t.error(new Ie("Response error: No response body",Fe))}})}function Pe(){return new ReadableStream({start(t){t.close()}})}var qe=require("eventsource-parser");function Ve(t){const e=new TextDecoder;let n;return new TransformStream({async start(e){n=(0,qe.createParser)((n=>{if("data"in n&&"event"===n.type&&"[DONE]"===n.data||"done"===n.event)e.terminate();else if("data"in n){const r=t?t(n.data,{event:n.event}):n.data;r&&e.enqueue(r)}}))},transform(t){n.feed(e.decode(t))}})}function Ue(t){const e=new TextEncoder;let n="";const r=t||{};return new TransformStream({async start(){r.onStart&&await r.onStart()},async transform(t,s){const i="string"==typeof t?t:t.content;s.enqueue(e.encode(i)),n+=i,r.onToken&&await r.onToken(i),r.onText&&"string"==typeof t&&await r.onText(t)},async flush(){r.onCompletion&&await r.onCompletion(n),r.onFinal&&await r.onFinal(n)}})}function Be(){let t=!0;return e=>(t&&(e=e.trimStart())&&(t=!1),e)}function Me(t,e){if(!t.ok)return Re(t.body);let n=t.body||new ReadableStream({start(t){t.close()}});return n instanceof ReadableStream||(n=ReadableStream.from(n)),n.pipeThrough(Ve(e))}function Le(t){let e=t[Symbol.asyncIterator]();return new ReadableStream({async pull(t){const{done:n,value:r}=await e.next();n?t.close():t.enqueue(r)},async cancel(t){await(e.return?.(t))}})}var _e={};a(_e,{XXHashAlgorithm:()=>sn,base32768:()=>Ye,uuid:()=>He,uuidNIL:()=>We.NIL,uuidParse:()=>We.parse,uuidStringify:()=>We.stringify,uuidValidate:()=>We.validate,uuidVersion:()=>We.version,uuidv1:()=>We.v1,uuidv4:()=>We.v4,uuidv5:()=>We.v5,xxhash:()=>on,xxhash32:()=>nn,xxhash64:()=>rn,xxhashAsStr:()=>an});var Je=require("uuid"),ze=l(require("base32768")),We=require("uuid"),De={1:Je.v1,4:Je.v4,5:Je.v5};function He(t=1,e){const n=De[t];return e?ze.encode(n(null,[])):n()}var Ge={};a(Ge,{XXHashAlgorithm:()=>sn,base32768:()=>Ye,xxhash:()=>on,xxhash32:()=>nn,xxhash64:()=>rn,xxhashAsStr:()=>an});var Ke=l(require("xxhashjs")),Xe=l(require("base32768")),Ze=require("json-canonicalize");u(Ge,require("json-canonicalize"));var Ye=Xe,{h32:Qe,h64:tn}=Ke.default,en=588213;function nn(t,e=16){return"object"==typeof t&&(t=(0,Ze.canonicalize)(t)),Qe(t,en).toString(e)}function rn(t,e=16){return"object"==typeof t&&(t=(0,Ze.canonicalize)(t)),tn(t,en).toString(e)}var sn=(t=>(t[t.xxhash64=111]="xxhash64",t[t.xxhash32=112]="xxhash32",t))(sn||{});function on(t,e=111,n=en){let r;return t.buffer&&(t=t.buffer),112!==e?(r=tn(t,n),r=new Uint16Array([r._a00,r._a16,r._a32,r._a48]),r=new Uint8Array(r.buffer)):(r=Qe(t,n),r=new Uint16Array([r._low,r._high]),r=new Uint8Array(r.buffer)),r}function an(t,e=111,n=en){return Xe.encode(on(t,e,n))}u(_e,Ge),u(J,_e);var cn=l(require("path")),un=/[<>:"/\\|?*\u0000-\u001F]/,ln=/^(con|prn|aux|nul|com\d|lpt\d)$/i,fn=100,hn=/^\.+(\\|\/)|^\.+$/,pn=/\.+$/,wn=/[\u0000-\u001F\u0080-\u009F\u200E\u200F\u202A-\u202E\u2066-\u2069]/;function dn(){return new RegExp(un.source,"g")}function mn(){return new RegExp(wn.source,"g")}function yn(t){return t&&!(un.test(t)||mn().test(t)||hn.test(t)||pn.test(t))}function bn(t){const e=t.split(cn.default.sep);return("/"===t[0]||e[0]&&cn.default.dirname(e[0])===e[0])&&e.shift(),e.every(yn)}function gn(t,e={}){const n=e.replacement||"!";if((un.test(n)||wn.test(n))&&j("Replacement string cannot contain reserved filename characters","sanitizeFilename",400),n.length>0){const e=/([<>:"/\\|?*\u0000-\u001F]){2,}/;t=t.replace(e,"$1")}if(t=(t=(t=(t=(t=t.normalize("NFD")).replace(hn,n)).replace(dn(),n)).replace(mn(),n)).replace(pn,""),n.length>0){"."===t[0]||"."!==t[0]||(t=n+t),"."===t[t.length-1]&&(t+=n)}t=ln.test(t)?t+n:t;const r="number"==typeof e.maxLength?e.maxLength:fn;if(t.length>r){const e=t.lastIndexOf(".");if(-1===e)t=t.slice(0,r);else{const n=t.slice(0,e),s=t.slice(e);t=n.slice(0,Math.max(1,r-s.length))+s}}return t}function xn(t,e={}){const n=t.split(cn.default.sep);let r;("/"===t[0]||n[0]&&cn.default.dirname(n[0])===n[0])&&(r=n.shift());const s=n.map((t=>gn(t,e)));return void 0!==r&&s.unshift(r),s.join(cn.default.sep)}function En(t,e=1){let n="";for(;e--;){const e=cn.default.extname(t);if(!e)break;n=e+n,t=cn.default.basename(t,e)}return n}function vn(t){return t.split(".").length-1}var $n=require("util-ex");function Sn(t,e){if("string"!=typeof t)throw new v("modelName must be a string","isModelNameMatched",400);switch(typeof e){case"string":if((0,$n.isRegExpStr)(e)){const n=(e=(0,$n.toRegExp)(e)).exec(t);if(n)return n}else if(t.toLowerCase()===e.toLowerCase())return e;break;case"object":if(Array.isArray(e)){for(const n of e)if("string"==typeof n){if((0,$n.isRegExpStr)(n)){const r=(e=(0,$n.toRegExp)(n)).exec(t);if(r)return r}else if(t.toLowerCase()===n.toLowerCase())return n}else if(n instanceof RegExp){const e=n.exec(t);if(e)return e}else if("function"==typeof n){const e=n.call(this,t);if(e)return e}}else if(e instanceof RegExp){const n=e.exec(t);if(n)return n}break;case"function":const n=e.call(this,t);if(n)return n}}function kn(t){return Object.keys(t).filter((t=>Number.isNaN(Number(t))))}var On=require("util-ex");function Cn(t,e){if(e){const n=Object.keys(e);if(n.length){const r=Object.values(e);return(0,On.newFunction)("expression",n,`return ${t}`)(...r)}}return(0,On.newFunction)("expression",[],`return ${t}`)()}function jn(t){return t?An(t,[],""):[]}function An(t,e,n="."){return Array.isArray(t)?t.flatMap(((t,n)=>An(t,[...e,`[${n}]`]))):(r=t)&&r.constructor===Object?Object.entries(t).flatMap((([t,r])=>An(r,[...e,n+t]))):[e.join("")];var r}function Nn(t){if(t<2)throw new v("repetitionThreshold must be greater than 1","createEndWithRepetitionDetector",400);const e=new RegExp(`([\\S\\s]+)(\\1{${t-1},})$`);return function(t){return e.test(t)}}var Tn=l(require("path")),Fn=l(require("fs"));function In(t,e,n,r){let s;if(Tn.default.isAbsolute(t)?s=Fn.existsSync(t)?t:Rn(Tn.default.basename(t),[Tn.default.dirname(t)],n):(e||(e=["."]),s=Rn(t,e,n)),!s)throw new S(t,"loadFileFromPaths");{const t=s;s=Fn.readFileSync(s),r&&(r.filepath=t)}return s}function Rn(t,e,n){let r;const s=n?n.map((e=>En(t,vn(e)))):void 0;for(const i of e){const e=Tn.default.resolve(i,t);if(s)for(let t=0;t<s.length;t++){const i=e+(s[t]!==n[t]?n[t]:"");if(Fn.existsSync(i)){r=i;break}}else if(Fn.existsSync(e)){r=e;break}}return r}function Pn(t,e,n,r){let s;"string"==typeof r?(s=r,r=void 0):s=r?.encoding??"utf8";return In(t,e,n,r).toString(s)}var qn=require("fs"),Vn=l(require("path")),Un=require("load-config-file"),Bn=require("yaml"),Mn=require("yaml-types"),Ln=require("mime-type/with-db"),_n=require("yaml"),Jn=[Mn.regexp];function zn(t){Array.isArray(t)||(t=[t]);for(const e of t){-1===Jn.indexOf(e)&&Jn.push(e)}}function Wn(t){return(0,Bn.parse)(t,{customTags:Jn})}function Dn(t,e){const n=[],r=e?.after,s=e?.exclude?"string"==typeof e.exclude?[e.exclude]:e.exclude:void 0,i=e?.extensions?"string"==typeof e.extensions?[e.extensions]:e.extensions.map((t=>t.startsWith(".")?t:"."+t)):[".yml",".yaml",".json"];return function(t,e){const n=(0,qn.readdirSync)(t,{withFileTypes:!0,recursive:!0});for(const r of n){const n=Vn.default.join(t,r.name);r.isFile()&&e(n,r)}}(t,((t,e)=>{if(s?.includes(t))return;const o=Vn.default.extname(t),a=(0,qn.statSync)(t);if(i.includes(o)){if(r?.hasOwnProperty(t)&&a.mtimeMs<=r[t])return;n.push(t)}})),n}function Hn(t,e){return Dn(t,e).map((t=>Un.Config.loadSync(t))).filter((t=>void 0!==t))}function Gn(t,e,n=1){"."===t[0]&&n++;const r=En(t,n);(!r||r.split(".").length<=1)&&(t+=".yaml");const s=Ln.mimeType.lookup(t);if("application/json"===s)e=JSON.stringify(e,null,2);else{if("text/yaml"!==s)throw new Error(`${t} unsupported mime type: ${s}`);e=(0,Bn.stringify)(e)}const i=Vn.default.dirname(t);(0,qn.existsSync)(i)||(0,qn.mkdirSync)(i,{recursive:!0}),(0,qn.writeFileSync)(t,e,{encoding:"utf8"})}function Kn(t,e){return t?`'${e}'`:String(e)}function Xn(t,e){return t.map((t=>Qn(t,e))).join(" AND ")}function Zn(t,e){return t.map((t=>Qn(t,e))).join(" OR ")}function Yn(t,e){const n=[];return Object.keys(e).forEach((r=>{const s=e[r];let i="string"==typeof e[r];switch(r){case"$lt":case"<":n.push(`${t} < ${Kn(i,s)}`);break;case"<=":case"$lte":n.push(`${t} <= ${Kn(i,s)}`);break;case"$gt":case">":n.push(`${t} > ${Kn(i,s)}`);break;case"$gte":case">=":n.push(`${t} >= ${Kn(i,s)}`);break;case"$ne":case"!=":n.push(`${t} != ${Kn(i,s)}`);break;case"=":case"$eq":n.push(`${t} = ${Kn(i,s)}`);break;case"$in":n.push(`${t} IN (${s.map((t=>Kn(!0,t))).join(", ")})`);break;case"$nin":n.push(`${t} NOT IN (${s.map((t=>Kn(!0,t))).join(", ")})`);break;case"$regex":n.push(`${t} REGEXP '${s.source}'`);break;case"$like":n.push(`${t} LIKE '${s}'`);break;case"$nlike":n.push(`${t} NOT LIKE '${s}'`);break;case"$glob":n.push(`${t} GLOB '${s}'`);break;case"$nglob":n.push(`${t} NOT GLOB '${s}'`);break;default:throw new Error(`Unsupported condition operator: ${r}`)}})),n.join(" AND ")}function Qn(t,e){const n=[];if("function"!=typeof e&&(e=t=>t),Array.isArray(t))n.push(Xn(t,e));else for(const[r,s]of Object.entries(t))if("$and"===r)n.push(`(${Xn(t[r],e)})`);else if("$or"===r)n.push(`(${Zn(t[r],e)})`);else{const t=typeof s;if(null==s)n.push(`${e(r)} IS NULL`);else if("object"!==t||Array.isArray(s))if("string"===t)n.push(`${e(r)}='${s}'`);else{if("number"!==t&&"boolean"!==t)throw new Error(`Unsupported value type for key ${r}`);n.push(`${e(r)}=${s}`)}else n.push(Yn(e(r),s))}return n.length>1?n.join(" AND "):n[0]}function tr(t){const e=t.indexOf("://");if(e>0)return t.substring(0,e)}Un.Config.register([".yml",".yaml"],Wn),Un.Config.register([".json"],(function(t){return JSON.parse(t)}));var er=class t extends A{static get apiRoot(){return t._apiRoot}static setApiRoot(e){t._apiRoot=e}static async loadFrom(){if(this._apiRoot){const t=await fetch(this._apiRoot,{headers:{"Content-Type":"application/json"}}),e=await t.json();e&&this.loadFromSync(e)}else j("missing apiRoot to load tools","ClientTools")}static loadFromSync(e){for(const n in e){const r=this.get(n),s=e[n];r?r instanceof t?r.assign(s):j(`${n} already registered as ${r.constructor.name}`,"ClientTools"):this.register(s)}}static async fetch(t,e){const n=this.get(t);if(n&&n.fetch)return n.fetch(e)}getUrlParams(t){if(void 0!==t){const e=JSON.stringify(t);if("{}"!==e&&"[]"!==e&&'""'!==e)return"?p="+encodeURIComponent(e)}return""}async fetch(t,e,n){const r={...this.fetchOptions};let s;r.headers&&r.headers["Content-Type"]||(r.headers={"Content-Type":"application/json",...r.headers}),t?.stream&&!r.headers.Connection&&(r.headers.Connection="keep-alive"),e||(e=this.action||"post"),"res"===e&&(e="get"),n?("string"!=typeof n&&(n=JSON.stringify(n)),n=this.name+"/"+n):n=this.name,r.method=e.toUpperCase(),"get"===e||"delete"===e?s=n+this.getUrlParams(t):(r.body=JSON.stringify(t),s=n);const i=await fetch(`${this.apiRoot}/${s}`,r);if(!i.ok){throw await this.errorFrom(i)}return i}async errorFrom(t){let e,n=t.status,r=t.statusText,s=this.name;if(t.body){const n=await t.text();try{const t=JSON.parse(n);t&&(t.error&&(r=t.error),t.name&&(s=t.name),t.data&&(e=t.data,e.name=s,e.what&&(e.msg=r,r=e.what)),t.message&&(r=r+":"+t.message))}catch(t){console.warn("🚀 ~ parse error body to json:",t)}}return C(r,s,n)}async func(t){const e=await this.fetch(t);if(t?.stream)return e;return await e.json()}},nr={...D};er.defineProperties(er,nr);var rr=class extends er{async fetch(t,e){if(t||(t={}),e&&"res"===this.action){if("get"===e||"delete"===e){let n=t.id;return n||j("id is required"),"string"==typeof n&&(n=encodeURIComponent(n)),delete t.id,super.fetch(t,e,n)}"list"===e?e="get":e.startsWith("$")&&(t.act=e,e="post")}return await super.fetch(t,e)}async _func(t,e){const n=await this.fetch(e,t);if(e?.stream)return n;return await n.json()}async func(t){const e=t.action;return e&&delete t.action,this._func(e,t)}assignMethods(t){if(Array.isArray(t))for(const e of t){const t=e.startsWith("$")?e.slice(1):e;this[t]||(this[t]=(t=>this._func.bind(this,t))(e))}}},sr={methods:{type:"array",assign(t,e,n,r,s){s?.isExported||e.assignMethods(t)}}};rr.defineProperties(rr,sr);var ir=class extends rr{constructor(){super(...arguments),this._sseEvents={},this._forwardEvents=new Set,this.name=F,this.description="subscribe server sent event",this.ebListener=async function(...t){const e=this.type;this.target.publish&&await this.target.publish({data:t,event:e})}}get evtSource(){let t=this._es;return t&&t.readyState!==EventSource.CLOSED||(t=this.initEventSource(this._esEvents)),t}get active(){return!!this._es&&this._es.readyState!==EventSource.CLOSED}set active(t){t!==this.active&&(t?this.initEventSource(this._esEvents):this._es&&(this._es.close(),this._es=void 0))}initEventSource(t){if("string"==typeof t&&(t=[t]),this._es&&this._es.readyState!==EventSource.CLOSED){if(!this._esEvents||t&&t.every((t=>this._esEvents.includes(t))))return this._es;this._es.close()}const e=t?this.getUrlParams({event:t}):"",n=`${this.apiRoot}/${this.name}${e}`,r=this._es=new EventSource(n);return Object.entries(this._sseEvents).forEach((([t,e])=>{r.addEventListener(t,e)})),this._esEvents=t,r}esListener(t){const e=t.data?JSON.parse(t.data):void 0,n=t.type;if(!this._forwardEvents.has(n)){const t=this.emitter;t&&e&&n&&(Array.isArray(e)?t.emit(n,...e):t.emit(n,e))}}async subscribe(t){const e=await this.sub({event:t});"string"==typeof t&&(t=[t]);const n=this.evtSource;for(const e of t)if(!this._sseEvents[e]){const t=this._sseEvents[e]=this.esListener.bind(this);n.addEventListener(e,t)}return e}async unsubscribe(t){const e=await this.unsub({event:t});"string"==typeof t&&(t=[t]);for(const e of t){const t=this._sseEvents[e];t&&(delete this._sseEvents[e],this.evtSource.removeEventListener(e,t))}return e}forwardEvent(t){"string"==typeof t&&(t=[t]);for(const e of t)this._forwardEvents.has(e)||(this._forwardEvents.add(e),this.on&&this.on(e,this.ebListener))}unforwardEvent(t){"string"==typeof t&&(t=[t]);for(const e of t)this._forwardEvents.has(e)&&(this._forwardEvents.delete(e),this.off&&this.off(e,this.ebListener))}async init(t){if(this.active=!1,this.initEventSource(t),t)return await this.subscribe(t)}},or=new ir(F),ar=require("util-ex"),cr=class t extends A{static get apiRoot(){return t._apiRoot}static setApiRoot(e){t._apiRoot=e}static toJSON(){const e={};for(const n in this.items){let r=this.items[n];r instanceof t&&(r.allowExportFunc||(r=r.toJSON(),delete r.func),e[n]=r)}return e}isStream(t){return this.stream}func({}){}},ur={...D};cr.defineProperties(cr,ur);var lr=class extends cr{constructor(t,e={}){super(t,e),this.action="res",this.params={id:{type:"string"},val:{type:"any"}};const n=this.methods=[];for(const t of W)"function"==typeof this[t]&&n.push(t);(0,ar.getAllNames)(Object.getPrototypeOf(this)).filter((t=>t.startsWith("$")&&"function"==typeof this[t])).forEach((t=>{n.push(t);const e=t.slice(1);void 0===this[e]&&(this[e]=this[t])}))}cast(t,e){let n=this.params[t];return n&&("string"!=typeof n&&(n=n.type),"number"===n&&(e=Number(e))),e}getMethodFromParams(t){let e=t?._req?.method?.toLowerCase();return"get"===e&&void 0===t.id&&(e="list"),"post"===e&&t.act&&(e=t.act),e}func(t){const e=this.getMethodFromParams(t);if(e&&"function"==typeof this[e])return void 0!==t.id&&(t.id=this.cast("id",t.id)),this[e](t);throw new S(e,this.name)}};lr.defineProperties(lr,{methods:{type:"array"}});var fr=U.runSync(),hr=class t extends lr{constructor(){super(...arguments),this.name=F,this.description="subscribe server sent event",this.result="event",this.depends={[I]:U}}static get sse(){return this._sse||(this._sse=new q),this._sse}get sse(){return this.constructor.sse}static publish(e,n){return t.sse.publish(e,n)}static{this.ebListener=function(...e){t.sse.publish(e,this.type)}}static subscribe(e,n,r){return t.sse.subscribe(e,n,r)}static alreadyForward(e){const n=fr.listeners(e);for(const e of n)if(e===t.ebListener)return!0}publishSSE(t,e){return this.constructor.publish(t,e)}subscribeSSE(t,e,n){return"string"==typeof n&&(n=[n]),this.constructor.subscribe(t,e,n)}forward(e){Array.isArray(e)||(e=[e]);for(const n of e)t.alreadyForward(n)||fr.on(n,t.ebListener)}unforward(e){"string"==typeof e&&(e=[e]);for(const n of e)fr.off(n,t.ebListener)}list({_req:t,_res:e,event:n}){t&&e&&this.subscribeSSE(t,e,n)}$sub({event:t}){if(t)return this.forward(t),{event:t};j("event is required","sub",400)}$unsub({event:t}){if(t)return this.unforward(t),{event:t};j("event is required","unsub",400)}$publish({event:t,data:e}){if(t&&e){"string"==typeof t&&(t=[t]);for(const n of t)this.publishSSE(e,n);return{event:t}}j("event or data is required","pub",400)}isStream(t){return"list"===this.getMethodFromParams(t)}},pr=new hr(F);function wr(){U.register(),_.register()}
1
+ "use strict";var t,e=Object.create,r=Object.defineProperty,n=Object.getOwnPropertyDescriptor,s=Object.getOwnPropertyNames,i=Object.getPrototypeOf,o=Object.prototype.hasOwnProperty,a=(t,e)=>{for(var n in e)r(t,n,{get:e[n],enumerable:!0})},c=(t,e,i,a)=>{if(e&&"object"==typeof e||"function"==typeof e)for(let c of s(e))o.call(t,c)||c===i||r(t,c,{get:()=>e[c],enumerable:!(a=n(e,c))||a.enumerable});return t},u=(t,e,r)=>(c(t,e,"default"),r&&c(r,e,"default")),h=(t,n,s)=>(s=null!=t?e(i(t)):{},c(!n&&t&&t.__esModule?s:r(s,"default",{value:t,enumerable:!0}),t)),l={};a(l,{EventClient:()=>Bn,EventServer:()=>Dn,EventToolFunc:()=>Tn,_lrucache:()=>Nn,createLRUCache:()=>Fn,event:()=>jn,eventClient:()=>Un,eventServer:()=>Wn,lrucache:()=>In,registerCoreTools:()=>Hn}),module.exports=(t=l,c(r({},"__esModule",{value:!0}),t));var f=require("events-ex"),p=require("property-manager"),w=require("util-ex"),d=require("abstract-error"),m=(t=>(t[t.OK=200]="OK",t[t.Accepted=202]="Accepted",t[t.BadRequest=400]="BadRequest",t[t.InvalidArgument=400]="InvalidArgument",t[t.Unauthorized=401]="Unauthorized",t[t.PaymentRequired=402]="PaymentRequired",t[t.Forbidden=403]="Forbidden",t[t.NotFound=404]="NotFound",t[t.MethodNotAllowed=405]="MethodNotAllowed",t[t.NotAcceptable=406]="NotAcceptable",t[t.RequestTimeout=408]="RequestTimeout",t[t.Conflict=409]="Conflict",t[t.Corruption=409]="Corruption",t[t.TooManyRequests=429]="TooManyRequests",t[t.Aborted=499]="Aborted",t[t.InternalError=500]="InternalError",t[t.NotImplemented=501]="NotImplemented",t[t.NotSupported=501]="NotSupported",t[t.BadGateway=502]="BadGateway",t[t.ServiceUnavailable=503]="ServiceUnavailable",t[t.GatewayTimeout=504]="GatewayTimeout",t))(m||{}),y=500,b=404,g=409,v=499,x=class t extends d.AbstractError{static createErrorClass(e,r,n=t){return(0,d.createErrorClass)(e,r,n)}constructor(t,e,r){super(t,e);const n=this.constructor;null!=e?this.code=e:n.code?this.code=n.code:this.code=n.name,r?"string"==typeof r?this.name=r:Object.assign(this,r):"string"==typeof this.code?this.name=this.code:this.name=n.name}toJSON(){const t={name:this.name,code:this.code,data:this.data,caller:this.caller,error:this.message,stack:this.stack};return Object.keys(t).forEach((e=>void 0===t[e]&&delete t[e])),t}fromJSON(e){const r=new t(e.message);return r.code=e.code,r.data=e.data,r.caller=e.caller,r.message=e.error,r.stack=e.stack,r}},E=class extends x{constructor(t,e,r=y){super(t,r,e)}},S=class extends E{constructor(t,e){t||(t="Not Implementation."),super(t,e,501)}};E[501]=S;var $=class extends E{static{this.code=b}constructor(t,e){super(`Could not find ${t}.`,e,b),this.data={what:t}}};E[404]=$;var k=class extends E{static{this.code=g}constructor(t,e){super(`The ${t} already exists.`,e,g),this.data={what:t}}};E[409]=k;var O=class extends E{static{this.code=v}constructor(t,e){e||(e="AbortError"),super(t?`The operation was aborted for ${t}.`:"The operation was aborted.",e,v),t&&(this.data={what:t})}};function A(t,e,r=y){const n=new(E[r]||E)(t,e,r);return"number"!=typeof n.code&&(n.code=r),n}function T(t,e,r=y){throw A(t,e,r)}E[499]=O;var j={};a(j,{AIChatRoles:()=>L,AIMessageTypes:()=>_,AIStream:()=>_e,AITextGenerationFinishReasons:()=>V,AbortError:()=>O,AbortErrorCode:()=>v,ActionNames:()=>F,AlreadyExistsError:()=>k,AlreadyExistsErrorCode:()=>g,BaseError:()=>x,CancelableAbility:()=>xn,CommonError:()=>E,ConfigFile:()=>_r.Config,DefaultAsyncSemaphoreCapacity:()=>hn,ErrorCode:()=>m,EventBusName:()=>Ae,EventName:()=>Oe,FStringPromptTemplate:()=>se,FewShotPromptTemplate:()=>ue,FilenameReservedRegex:()=>hr,GolangPromptTemplate:()=>ae,HFBuiltins:()=>Ht,HFEnvironment:()=>Gt,HFInterpreter:()=>zt,HFTemplate:()=>Kt,HfPromptTemplate:()=>Qt,IntSet:()=>cn,InternalErrorCode:()=>y,NotFoundError:()=>$,NotFoundErrorCode:()=>b,NotImplementationError:()=>S,NotImplementedErrorCode:()=>501,PASSING_SCORE:()=>N,PromptExampleSelector:()=>Z,PromptTemplate:()=>G,PromptTemplateTypes:()=>D,PromptTypes:()=>J,RStreamErrCode:()=>Ie,RateLimit:()=>yn,ReadableStreamError:()=>Re,RemoteToolFuncSchema:()=>I,ResponseRStreamErrCode:()=>Me,SSEChannel:()=>Ne,SSEChannelAlreadyClosedErrCode:()=>Ce,Semaphore:()=>mn,TaskAbortController:()=>vn,WindowsReservedNameRegex:()=>lr,XXHashAlgorithm:()=>or,backendEventable:()=>Te,base32768:()=>tr,createAbilityInjector:()=>C.createAbilityInjector,createCallbacksTransformer:()=>ze,createEmptyReadableStream:()=>qe,createEndWithRepetitionDetector:()=>Nr,createError:()=>A,createEventStreamTransformer:()=>Ue,createHfValueFunc:()=>te,dateToText:()=>U,defaultTemplateFormat:()=>H,expandEnv:()=>pe,expandObjEnv:()=>we,extNameLevel:()=>Sr,filenameReservedRegex:()=>mr,formatISO:()=>R.formatISO,getAllEnumKeys:()=>Or,getConfigFileNames:()=>Kr,getConfigs:()=>Xr,getKeysPath:()=>jr,getMultiLevelExtname:()=>Er,getRealFilepath:()=>Br,getResponseErrorReadableStream:()=>Pe,hfParse:()=>Tt,hfTokenize:()=>it,interpolateEnv:()=>fe,interpolateFString:()=>re,interpolateGolangTemplate:()=>oe,isModelNameMatched:()=>kr,isValidFilename:()=>br,isValidFilepath:()=>gr,isWebStream:()=>Fe,jsonFilterToWhere:()=>rn,jsonToMarkdownStr:()=>an,loadFileFromPaths:()=>Mr,loadTextFromPaths:()=>Pr,makeToolFuncCancelable:()=>Sn,matchUrlProtocol:()=>nn,messagesToText:()=>z,mimeType:()=>Jr.mimeType,paramsSizeToScaleStr:()=>sn,parseDateFormat:()=>M.parse,parseFString:()=>ee,parseISO:()=>R.parseISO,parseJsJson:()=>Tr,parseYaml:()=>Gr,reControlCharsRegex:()=>yr,readFilenamesRecursiveSync:()=>qr,readableFromAsyncIterable:()=>Le,registerYamlTag:()=>Hr,sanitizeFilename:()=>vr,sanitizeFilepath:()=>xr,saveConfigFile:()=>Zr,scaleStrToParamsSize:()=>on,sortedValues:()=>ce,splitSentence:()=>Ee,stringifyYaml:()=>Dr.stringify,textToDate:()=>B,throwError:()=>T,toDate:()=>R.toDate,toDateTime:()=>q,trimStartOfStreamHelper:()=>Ve,truncTo:()=>Se,uuid:()=>Ke,uuidNIL:()=>He.NIL,uuidParse:()=>He.parse,uuidStringify:()=>He.stringify,uuidValidate:()=>He.validate,uuidVersion:()=>He.version,uuidv1:()=>He.v1,uuidv4:()=>He.v4,uuidv5:()=>He.v5,wait:()=>$e,xxhash:()=>ar,xxhash32:()=>sr,xxhash64:()=>ir,xxhashAsStr:()=>cr});var C=require("custom-ability"),N=.618,F=["get","post","put","delete","patch","list","res"],I={apiRoot:{type:"string",get(){return this._apiRoot??this.constructor.apiRoot},set(t){this._apiRoot=t}},action:{type:"string",assign:(t,e,r,n,s)=>t||"post"},fetchOptions:{type:"object"},allowExportFunc:{type:"boolean"},stream:{type:"boolean"}},M=require("date-fns"),R=require("date-fns"),P="MMMM d, y 'at' h:m:s b 'GMT'x";function q(t){let e;try{"string"==typeof t?e=(0,M.parseISO)(t):"number"==typeof t?e=new Date(t):t instanceof Date&&(e=t)}catch(t){console.error(t)}return e}function B(t,e=P){return(0,M.parse)(t,e,new Date)}function U(t,e=P){return(0,M.format)(t,e)}var V=["stop","length","content-filter","tool-calls","abort","error","other",null],_=["human","ai","generic","system","tool"],L=["user","assistant","system","tool","tool_calls"];function z(t){let e="";for(const r of t)if(r.content){e+=r.role.toLowerCase()+":";let t=r.createdAt;if(t){const r=q(t);r&&(e+=" ["+U(r)+"]")}e+=" "+r.content+"\n"}return e}var J=["chat","char","plan"],D=["internal","hf","fill"],W=require("custom-factory");var H="default",G=class t extends W.BaseFactory{static from(t,e){return new this(t,e)}static async format(t){return new this(t).format()}static async formatIf(t){if(this.isTemplate(t)){return new this(t).format()}}static isTemplate(e){if(e?.template){const r=e.templateFormat||H,n=t.get(r);return n.isTemplate!==t.isTemplate&&n.isTemplate(e)}}filterData(t){return Array.isArray(this.inputVariables)&&(t=Object.fromEntries(Object.entries(t).filter((([t])=>this.inputVariables.includes(t))))),t}constructor(e,r){"string"==typeof e?(r||(r={}),r.template=e):e&&(e=(r=e).template);const{templateFormat:n}=r||{};if(super(r),this.constructor===t){const e=t.get(n||H);if(e)return Reflect.construct(e,arguments);throw new E(`Prompt template type ${n} not found`,"PromptTemplate",400)}}_initialize(t){throw new S("Not implemented","PromptTemplate")}initialize(e){this.constructor!==t&&(Object.assign(this,this.toJSON(e)),e?.ignoreInitialize||this._initialize(e))}_format(t){throw new S("Not implemented","PromptTemplate")}async format(e){const r=this.data;if(e={...r,...e},r)for(const[t,n]of Object.entries(r))e[t]===n&&"function"==typeof n&&(delete e[t],e[t]=await n(e));for(const[r,n]of Object.entries(e))n instanceof t&&(delete e[r],e[r]=await n.format(e));return this._format(e)}partial(t){t={...this.data,...t};const e=this.toJSON();return e.data=t,e.ignoreInitialize=!0,new this.constructor(e)}toJSON(e=this){let r={template:e.template,data:e.data,inputVariables:e.inputVariables,compiledTemplate:e.compiledTemplate};var n;return e.templateFormat&&t.get(e.templateFormat)!==this.constructor&&(r.templateFormat=e.templateFormat),n=r,r=Object.keys(n).reduce(((t,e)=>{const r=n[e];return null!=r&&(t[e]=r),t}),{}),r}};function K(t){return(e=t)&&"function"==typeof e[Symbol.iterator]?async function*(t){const e=t[Symbol.iterator]();let r;try{for(;;){r=!1;const t=e.next();if(r=!0,t.done)return r=!1,await t.value;yield await t.value}}finally{r&&await(e.return?.().value)}}(t):t;var e}var X=!1;(async function(){let t=!1,e=!1;try{for await(const e of function*(){try{yield Promise.reject()}finally{t=!0}}())throw new Error("impossible")}catch{e=!0}return e&&t})().then((t=>{X=t}));var Z=class{constructor(t,e){this.initialize(t,e)}initialize(t,e){const r=e?.maxLength;var n;r>0&&(this.maxLength=r),void 0!==e?.threshold&&(!0===e.threshold?this.threshold=.5:!1!==e.threshold&&(this.threshold=e.threshold)),this.examples=(n=t,X?n:K(n))}selectExample(t,e){if(void 0===e||e<=this.threshold)return t}async*selectExamples(t=this.examples){let e=this.maxLength||1/0;for await(const r of t){const t="number"==typeof this.threshold?Math.random():void 0;if(this.selectExample(r,t)){if(--e<0)break;yield r}}}async*[Symbol.asyncIterator](){yield*this.selectExamples()}},Y=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",BooleanLiteral:"BooleanLiteral",StringLiteral:"StringLiteral",Identifier:"Identifier",Equals:"Equals",OpenParen:"OpenParen",CloseParen:"CloseParen",OpenStatement:"OpenStatement",CloseStatement:"CloseStatement",OpenExpression:"OpenExpression",CloseExpression:"CloseExpression",OpenSquareBracket:"OpenSquareBracket",CloseSquareBracket:"CloseSquareBracket",OpenCurlyBracket:"OpenCurlyBracket",CloseCurlyBracket:"CloseCurlyBracket",Comma:"Comma",Dot:"Dot",Colon:"Colon",Pipe:"Pipe",CallOperator:"CallOperator",AdditiveBinaryOperator:"AdditiveBinaryOperator",MultiplicativeBinaryOperator:"MultiplicativeBinaryOperator",ComparisonBinaryOperator:"ComparisonBinaryOperator",UnaryOperator:"UnaryOperator",Set:"Set",If:"If",For:"For",In:"In",Is:"Is",NotIn:"NotIn",Else:"Else",EndIf:"EndIf",ElseIf:"ElseIf",EndFor:"EndFor",And:"And",Or:"Or",Not:"UnaryOperator"}),Q=Object.freeze({set:Y.Set,for:Y.For,in:Y.In,is:Y.Is,if:Y.If,else:Y.Else,endif:Y.EndIf,elif:Y.ElseIf,endfor:Y.EndFor,and:Y.And,or:Y.Or,not:Y.Not,"not in":Y.NotIn,true:Y.BooleanLiteral,false:Y.BooleanLiteral}),tt=class{constructor(t,e){this.value=t,this.type=e}};function et(t){return/\w/.test(t)}function rt(t){return/[0-9]/.test(t)}var nt=[["{%",Y.OpenStatement],["%}",Y.CloseStatement],["{{",Y.OpenExpression],["}}",Y.CloseExpression],["(",Y.OpenParen],[")",Y.CloseParen],["{",Y.OpenCurlyBracket],["}",Y.CloseCurlyBracket],["[",Y.OpenSquareBracket],["]",Y.CloseSquareBracket],[",",Y.Comma],[".",Y.Dot],[":",Y.Colon],["|",Y.Pipe],["<=",Y.ComparisonBinaryOperator],[">=",Y.ComparisonBinaryOperator],["==",Y.ComparisonBinaryOperator],["!=",Y.ComparisonBinaryOperator],["<",Y.ComparisonBinaryOperator],[">",Y.ComparisonBinaryOperator],["+",Y.AdditiveBinaryOperator],["-",Y.AdditiveBinaryOperator],["*",Y.MultiplicativeBinaryOperator],["/",Y.MultiplicativeBinaryOperator],["%",Y.MultiplicativeBinaryOperator],["=",Y.Equals]],st=new Map([["n","\n"],["t","\t"],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function it(t,e={}){const r=[],n=function(t,e={}){return t.endsWith("\n")&&(t=t.slice(0,-1)),t=t.replace(/{#.*?#}/gs,"{##}"),e.lstrip_blocks&&(t=t.replace(/^[ \t]*({[#%])/gm,"$1")),e.trim_blocks&&(t=t.replace(/([#%]})\n/g,"$1")),t.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}(t,e);let s=0;const i=t=>{let e="";for(;t(n[s]);)if("\\"!==n[s]){if(e+=n[s++],s>=n.length)throw new SyntaxError("Unexpected end of input")}else{if(++s,s>=n.length)throw new SyntaxError("Unexpected end of input");const t=n[s++],r=st.get(t);if(void 0===r)throw new SyntaxError(`Unexpected escaped character: ${t}`);e+=r}return e};t:for(;s<n.length;){const t=r.at(-1)?.type;if(void 0===t||t===Y.CloseStatement||t===Y.CloseExpression){let t="";for(;s<n.length&&("{"!==n[s]||"%"!==n[s+1]&&"{"!==n[s+1]);)t+=n[s++];if(t.length>0){r.push(new tt(t,Y.Text));continue}}i((t=>/\s/.test(t)));const e=n[s];if("-"===e||"+"===e){const t=r.at(-1)?.type;if(t===Y.Text||void 0===t)throw new SyntaxError(`Unexpected character: ${e}`);switch(t){case Y.Identifier:case Y.NumericLiteral:case Y.BooleanLiteral:case Y.StringLiteral:case Y.CloseParen:case Y.CloseSquareBracket:break;default:{++s;const t=i(rt);r.push(new tt(`${e}${t}`,t.length>0?Y.NumericLiteral:Y.UnaryOperator));continue}}}for(const[t,e]of nt){if(n.slice(s,s+t.length)===t){r.push(new tt(t,e)),s+=t.length;continue t}}if("'"!==e&&'"'!==e)if(rt(e)){const t=i(rt);r.push(new tt(t,Y.NumericLiteral))}else{if(!et(e))throw new SyntaxError(`Unexpected character: ${e}`);{const t=i(et),e=Object.hasOwn(Q,t)?Q[t]:Y.Identifier;e===Y.In&&r.at(-1)?.type===Y.Not?(r.pop(),r.push(new tt("not in",Y.NotIn))):r.push(new tt(t,e))}}else{++s;const t=i((t=>t!==e));r.push(new tt(t,Y.StringLiteral)),++s}}return r}var ot=class{constructor(){this.type="Statement"}},at=class extends ot{constructor(t){super(),this.body=t,this.type="Program"}},ct=class extends ot{constructor(t,e,r){super(),this.test=t,this.body=e,this.alternate=r,this.type="If"}},ut=class extends ot{constructor(t,e,r){super(),this.loopvar=t,this.iterable=e,this.body=r,this.type="For"}},ht=class extends ot{constructor(t,e){super(),this.assignee=t,this.value=e,this.type="Set"}},lt=class extends ot{constructor(){super(...arguments),this.type="Expression"}},ft=class extends lt{constructor(t,e,r){super(),this.object=t,this.property=e,this.computed=r,this.type="MemberExpression"}},pt=class extends lt{constructor(t,e){super(),this.callee=t,this.args=e,this.type="CallExpression"}},wt=class extends lt{constructor(t){super(),this.value=t,this.type="Identifier"}},dt=class extends lt{constructor(t){super(),this.value=t,this.type="Literal"}},mt=class extends dt{constructor(){super(...arguments),this.type="NumericLiteral"}},yt=class extends dt{constructor(){super(...arguments),this.type="StringLiteral"}},bt=class extends dt{constructor(){super(...arguments),this.type="BooleanLiteral"}},gt=class extends dt{constructor(){super(...arguments),this.type="ArrayLiteral"}},vt=class extends dt{constructor(){super(...arguments),this.type="TupleLiteral"}},xt=class extends dt{constructor(){super(...arguments),this.type="ObjectLiteral"}},Et=class extends lt{constructor(t,e,r){super(),this.operator=t,this.left=e,this.right=r,this.type="BinaryExpression"}},St=class extends lt{constructor(t,e){super(),this.operand=t,this.filter=e,this.type="FilterExpression"}},$t=class extends lt{constructor(t,e,r){super(),this.operand=t,this.negate=e,this.test=r,this.type="TestExpression"}},kt=class extends lt{constructor(t,e){super(),this.operator=t,this.argument=e,this.type="UnaryExpression"}},Ot=class extends lt{constructor(t=void 0,e=void 0,r=void 0){super(),this.start=t,this.stop=e,this.step=r,this.type="SliceExpression"}},At=class extends lt{constructor(t,e){super(),this.key=t,this.value=e,this.type="KeywordArgumentExpression"}};function Tt(t){const e=new at([]);let r=0;function n(e,n){const s=t[r++];if(!s||s.type!==e)throw new Error(`Parser Error: ${n}. ${s.type} !== ${e}.`);return s}function s(){let e;switch(t[r].type){case Y.Text:e=new yt(n(Y.Text,"Expected text token").value);break;case Y.OpenStatement:e=function(){let e;switch(n(Y.OpenStatement,"Expected opening statement token"),t[r].type){case Y.Set:++r,e=a(),n(Y.CloseStatement,"Expected closing statement token");break;case Y.If:++r,e=c(),n(Y.OpenStatement,"Expected {% token"),n(Y.EndIf,"Expected endif token"),n(Y.CloseStatement,"Expected %} token");break;case Y.For:++r,e=function(){const t=u(!0);if(!(t instanceof wt||t instanceof vt))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${t.type} instead`);n(Y.In,"Expected `in` keyword following loop variable");const e=h();n(Y.CloseStatement,"Expected closing statement token");const r=[];for(;i(Y.OpenStatement,Y.EndFor);)r.push(s());return new ut(t,e,r)}(),n(Y.OpenStatement,"Expected {% token"),n(Y.EndFor,"Expected endfor token"),n(Y.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${t[r].type} ${t[r].value}`)}return e}(),e.isStatement=!0;break;case Y.OpenExpression:e=function(){n(Y.OpenExpression,"Expected opening expression token");const t=h();return n(Y.CloseExpression,"Expected closing expression token"),t}(),e.isStatement=!0;break;default:throw new SyntaxError(`Unexpected token type: ${t[r].type}`)}return e}function i(...e){return r+e.length<=t.length&&e.some(((e,n)=>e!==t[r+n].type))}function o(...e){return r+e.length<=t.length&&e.every(((e,n)=>e===t[r+n].type))}function a(){const t=h();if(o(Y.Equals)){++r;const e=a();return new ht(t,e)}return t}function c(){const e=h();n(Y.CloseStatement,"Expected closing statement token");const i=[],a=[];for(;t[r]?.type!==Y.OpenStatement||t[r+1]?.type!==Y.ElseIf&&t[r+1]?.type!==Y.Else&&t[r+1]?.type!==Y.EndIf;)i.push(s());if(t[r]?.type===Y.OpenStatement&&t[r+1]?.type!==Y.EndIf)if(++r,o(Y.ElseIf))n(Y.ElseIf,"Expected elseif token"),a.push(c());else for(n(Y.Else,"Expected else token"),n(Y.CloseStatement,"Expected closing statement token");t[r]?.type!==Y.OpenStatement||t[r+1]?.type!==Y.EndIf;)a.push(s());return new ct(e,i,a)}function u(t=!1){const e=t?v:h,n=[e()],s=o(Y.Comma);for(;s&&(++r,n.push(e()),o(Y.Comma)););return s?new vt(n):n[0]}function h(){return function(){const t=l();if(o(Y.If)){++r;const e=l();n(Y.Else,"Expected else token");const s=l();return new ct(e,[t],[s])}return t}()}function l(){let e=f();for(;o(Y.Or);){const n=t[r];++r;const s=f();e=new Et(n,e,s)}return e}function f(){let e=p();for(;o(Y.And);){const n=t[r];++r;const s=p();e=new Et(n,e,s)}return e}function p(){let e;for(;o(Y.Not);){const n=t[r];++r;const s=p();e=new kt(n,s)}return e??function(){let e=w();for(;o(Y.ComparisonBinaryOperator)||o(Y.In)||o(Y.NotIn);){const n=t[r];++r;const s=w();e=new Et(n,e,s)}return e}()}function w(){let e=b();for(;o(Y.AdditiveBinaryOperator);){const n=t[r];++r;const s=b();e=new Et(n,e,s)}return e}function d(){const e=function(){let e=v();for(;o(Y.Dot)||o(Y.OpenSquareBracket);){const s=t[r];let i;++r;const o=s.type!==Y.Dot;if(o)i=y(),n(Y.CloseSquareBracket,"Expected closing square bracket");else if(i=v(),"Identifier"!==i.type)throw new SyntaxError("Expected identifier following dot operator");e=new ft(e,i,o)}return e}();return o(Y.OpenParen)?m(e):e}function m(t){let e=new pt(t,function(){n(Y.OpenParen,"Expected opening parenthesis for arguments list");const t=function(){const t=[];for(;!o(Y.CloseParen);){let e=h();if(o(Y.Equals)){if(++r,!(e instanceof wt))throw new SyntaxError("Expected identifier for keyword argument");const t=h();e=new At(e,t)}t.push(e),o(Y.Comma)&&++r}return t}();return n(Y.CloseParen,"Expected closing parenthesis for arguments list"),t}());return o(Y.OpenParen)&&(e=m(e)),e}function y(){const t=[];let e=!1;for(;!o(Y.CloseSquareBracket);)o(Y.Colon)?(t.push(void 0),++r,e=!0):(t.push(h()),o(Y.Colon)&&(++r,e=!0));if(0===t.length)throw new SyntaxError("Expected at least one argument for member/slice expression");if(e){if(t.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new Ot(...t)}return t[0]}function b(){let e=g();for(;o(Y.MultiplicativeBinaryOperator);){const n=t[r];++r;const s=g();e=new Et(n,e,s)}return e}function g(){let t=function(){let t=d();for(;o(Y.Pipe);){++r;let e=v();if(!(e instanceof wt))throw new SyntaxError("Expected identifier for the filter");o(Y.OpenParen)&&(e=m(e)),t=new St(t,e)}return t}();for(;o(Y.Is);){++r;const e=o(Y.Not);e&&++r;let n=v();if(n instanceof bt&&(n=new wt(n.value.toString())),!(n instanceof wt))throw new SyntaxError("Expected identifier for the test");t=new $t(t,e,n)}return t}function v(){const e=t[r];switch(e.type){case Y.NumericLiteral:return++r,new mt(Number(e.value));case Y.StringLiteral:return++r,new yt(e.value);case Y.BooleanLiteral:return++r,new bt("true"===e.value);case Y.Identifier:return++r,new wt(e.value);case Y.OpenParen:{++r;const e=u();if(t[r].type!==Y.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${t[r].type} instead`);return++r,e}case Y.OpenSquareBracket:{++r;const t=[];for(;!o(Y.CloseSquareBracket);)t.push(h()),o(Y.Comma)&&++r;return++r,new gt(t)}case Y.OpenCurlyBracket:{++r;const t=new Map;for(;!o(Y.CloseCurlyBracket);){const e=h();n(Y.Colon,"Expected colon between key and value in object literal");const s=h();t.set(e,s),o(Y.Comma)&&++r}return++r,new xt(t)}default:throw new SyntaxError(`Unexpected token: ${e.type}`)}}for(;r<t.length;)e.body.push(s());return e}function jt(t,e,r=1){void 0===e&&(e=t,t=0);const n=[];for(let s=t;s<e;s+=r)n.push(s);return n}function Ct(t,e,r,n=1){const s=Math.sign(n);s>=0?(e=(e??=0)<0?Math.max(t.length+e,0):Math.min(e,t.length),r=(r??=t.length)<0?Math.max(t.length+r,0):Math.min(r,t.length)):(e=(e??=t.length-1)<0?Math.max(t.length+e,-1):Math.min(e,t.length-1),r=(r??=-1)<-1?Math.max(t.length+r,-1):Math.min(r,t.length-1));const i=[];for(let o=e;s*o<s*r;o+=n)i.push(t[o]);return i}function Nt(t){return t.replace(/\b\w/g,(t=>t.toUpperCase()))}var Ft=class{constructor(t=void 0){this.type="RuntimeValue",this.builtins=new Map,this.value=t}__bool__(){return new Rt(!!this.value)}toString(){return""+this.value}toJSON(){return this.value}},It=class extends Ft{constructor(){super(...arguments),this.type="NumericValue"}},Mt=class t extends Ft{constructor(){super(...arguments),this.type="StringValue",this.builtins=new Map([["upper",new Ut((()=>new t(this.value.toUpperCase())))],["lower",new Ut((()=>new t(this.value.toLowerCase())))],["strip",new Ut((()=>new t(this.value.trim())))],["title",new Ut((()=>new t(Nt(this.value))))],["length",new It(this.value.length)],["rstrip",new Ut((()=>new t(this.value.trimEnd())))],["lstrip",new Ut((()=>new t(this.value.trimStart())))]])}},Rt=class extends Ft{constructor(){super(...arguments),this.type="BooleanValue"}},Pt=class extends Ft{constructor(t,e){super(t),this.orgValue=e,this.type="ObjectValue",this.builtins=new Map([["get",new Ut((([t,e])=>{if(!(t instanceof Mt))throw new Error(`Object key must be a string: got ${t.type}`);return this.value.get(t.value)??e??new Vt}))],["items",new Ut((()=>new qt(Array.from(this.value.entries()).map((([t,e])=>new qt([new Mt(t),e]))))))]])}toString(){let t;return t=this.orgValue&&this.orgValue.toString!==Object.prototype.toString?this.orgValue.toString():JSON.stringify(Object.fromEntries(this.value.entries())),t}toJSON(){return this.orgValue?this.orgValue:Object.fromEntries(this.value.entries())}__bool__(){return new Rt(this.value.size>0)}},qt=class extends Ft{constructor(){super(...arguments),this.type="ArrayValue",this.builtins=new Map([["length",new It(this.value.length)]])}__bool__(){return new Rt(this.value.length>0)}},Bt=class extends qt{constructor(){super(...arguments),this.type="TupleValue"}},Ut=class extends Ft{constructor(){super(...arguments),this.type="FunctionValue"}},Vt=class extends Ft{constructor(){super(...arguments),this.type="NullValue"}},_t=class extends Ft{constructor(){super(...arguments),this.type="UndefinedValue"}},Lt=class{constructor(t){this.parent=t,this.variables=new Map([["namespace",new Ut((t=>{if(0===t.length)return new Pt(new Map);if(1!==t.length||!(t[0]instanceof Pt))throw new Error("`namespace` expects either zero arguments or a single object argument");return t[0]}))]]),this.tests=new Map([["boolean",t=>"BooleanValue"===t.type],["callable",t=>t instanceof Ut],["odd",t=>{if("NumericValue"!==t.type)throw new Error(`Cannot apply test "odd" to type: ${t.type}`);return t.value%2!=0}],["even",t=>{if("NumericValue"!==t.type)throw new Error(`Cannot apply test "even" to type: ${t.type}`);return t.value%2==0}],["false",t=>"BooleanValue"===t.type&&!t.value],["true",t=>"BooleanValue"===t.type&&t.value],["number",t=>"NumericValue"===t.type],["integer",t=>"NumericValue"===t.type&&Number.isInteger(t.value)],["iterable",t=>t instanceof qt||t instanceof Mt],["lower",t=>{const e=t.value;return"StringValue"===t.type&&e===e.toLowerCase()}],["upper",t=>{const e=t.value;return"StringValue"===t.type&&e===e.toUpperCase()}],["none",t=>"NullValue"===t.type],["defined",t=>"UndefinedValue"!==t.type],["undefined",t=>"UndefinedValue"===t.type],["equalto",(t,e)=>t.value===e.value]])}set(t,e){return this.declareVariable(t,Jt(e))}declareVariable(t,e){if(this.variables.has(t))throw new SyntaxError(`Variable already declared: ${t}`);return this.variables.set(t,e),e}setVariable(t,e){return this.variables.set(t,e),e}resolve(t){if(this.variables.has(t))return this;if(this.parent)return this.parent.resolve(t);throw new Error(`Unknown variable: ${t}`)}lookupVariable(t){try{return this.resolve(t).variables.get(t)??new _t}catch{return new _t}}},zt=class{constructor(t){this.global=t??new Lt}run(t){return this.evaluate(t,this.global)}evaluateBinaryExpression(t,e){const r=this.evaluate(t.left,e);switch(t.operator.value){case"and":return r.__bool__().value?this.evaluate(t.right,e):r;case"or":return r.__bool__().value?r:this.evaluate(t.right,e)}const n=this.evaluate(t.right,e);switch(t.operator.value){case"==":return new Rt(r.value==n.value);case"!=":return new Rt(r.value!=n.value)}if(r instanceof _t||n instanceof _t)throw new Error("Cannot perform operation on undefined values");if(r instanceof Vt||n instanceof Vt)throw new Error("Cannot perform operation on null values");if(r instanceof It&&n instanceof It)switch(t.operator.value){case"+":return new It(r.value+n.value);case"-":return new It(r.value-n.value);case"*":return new It(r.value*n.value);case"/":return new It(r.value/n.value);case"%":return new It(r.value%n.value);case"<":return new Rt(r.value<n.value);case">":return new Rt(r.value>n.value);case">=":return new Rt(r.value>=n.value);case"<=":return new Rt(r.value<=n.value)}else if(r instanceof qt&&n instanceof qt){if("+"===t.operator.value)return new qt(r.value.concat(n.value))}else if(n instanceof qt){const e=void 0!==n.value.find((t=>t.value===r.value));switch(t.operator.value){case"in":return new Rt(e);case"not in":return new Rt(!e)}}if((r instanceof Mt||n instanceof Mt)&&"+"===t.operator.value)return new Mt(r.toString()+n.toString());if(r instanceof Mt&&n instanceof Mt)switch(t.operator.value){case"in":return new Rt(n.value.includes(r.value));case"not in":return new Rt(!n.value.includes(r.value))}if(r instanceof Mt&&n instanceof Pt)switch(t.operator.value){case"in":return new Rt(n.value.has(r.value));case"not in":return new Rt(!n.value.has(r.value))}throw new SyntaxError(`Unknown operator "${t.operator.value}" between ${r.type} and ${n.type}`)}evaluateFilterExpression(t,e){const r=this.evaluate(t.operand,e);if("Identifier"===t.filter.type){const e=t.filter;if(r instanceof qt)switch(e.value){case"list":return r;case"first":return r.value[0];case"last":return r.value[r.value.length-1];case"length":return new It(r.value.length);case"reverse":return new qt(r.value.reverse());case"sort":return new qt(r.value.sort(((t,e)=>{if(t.type!==e.type)throw new Error(`Cannot compare different types: ${t.type} and ${e.type}`);switch(t.type){case"NumericValue":return t.value-e.value;case"StringValue":return t.value.localeCompare(e.value);default:throw new Error(`Cannot compare type: ${t.type}`)}})));case"tojson":return new Mt(JSON.stringify(r.value));default:throw new Error(`Unknown ArrayValue filter: ${e.value}`)}else if(r instanceof Mt)switch(e.value){case"length":return new It(r.value.length);case"upper":return new Mt(r.value.toUpperCase());case"lower":return new Mt(r.value.toLowerCase());case"title":return new Mt(Nt(r.value));case"capitalize":return new Mt(r.value.charAt(0).toUpperCase()+r.value.slice(1));case"trim":return new Mt(r.value.trim());case"trimStart":return new Mt(r.value.trimStart());case"trimEnd":return new Mt(r.value.trimEnd());default:throw new Error(`Unknown StringValue filter: ${e.value}`)}else{if(r instanceof It){if("abs"===e.value)return new It(Math.abs(r.value));throw new Error(`Unknown NumericValue filter: ${e.value}`)}if(r instanceof Pt)switch(e.value){case"items":return new qt(Array.from(r.value.entries()).map((([t,e])=>new qt([new Mt(t),e]))));case"length":return new It(r.value.size);case"tojson":return new Mt(JSON.stringify(r));case"string":return new Mt(r.toString());default:throw new Error(`Unknown ObjectValue filter: ${e.value}`)}}throw new Error(`Cannot apply filter "${e.value}" to type: ${r.type}`)}if("CallExpression"===t.filter.type){const n=t.filter;if("Identifier"!==n.callee.type)throw new Error(`Unknown filter: ${n.callee.type}`);const s=n.callee.value,i=e.lookupVariable(s);if(i instanceof Ut)return i.value([r,...this.evaluateArgumentsExpression(n.args,e)],e);if(r instanceof qt){if("selectattr"===s){if(r.value.some((t=>!(t instanceof Pt))))throw new Error("`selectattr` can only be applied to array of objects");if(n.args.some((t=>"StringLiteral"!==t.type)))throw new Error("arguments of `selectattr` must be strings");const[t,s,i]=n.args.map((t=>this.evaluate(t,e)));let o;if(s){const t=e.tests.get(s.value);if(!t)throw new Error(`Unknown test: ${s.value}`);o=t}else o=(...t)=>t[0].__bool__().value;const a=r.value.filter((e=>{const r=e.value.get(t.value);return!!r&&o(r,i)}));return new qt(a)}throw new Error(`Unknown ArrayValue filter: ${s}`)}throw new Error(`Cannot apply filter "${s}" to type: ${r.type}`)}throw new Error(`Unknown filter: ${t.filter.type}`)}evaluateTestExpression(t,e){const r=this.evaluate(t.operand,e),n=e.tests.get(t.test.value);if(!n)throw new Error(`Unknown test: ${t.test.value}`);const s=n(r);return new Rt(t.negate?!s:s)}evaluateUnaryExpression(t,e){const r=this.evaluate(t.argument,e);if("not"===t.operator.value)return new Rt(!r.value);throw new SyntaxError(`Unknown operator: ${t.operator.value}`)}evalProgram(t,e){return this.evaluateBlock(t.body,e)}evaluateBlock(t,e){let r="";for(const n of t){const t=this.evaluate(n,e);"NullValue"!==t.type&&"UndefinedValue"!==t.type&&(r+=t)}return new Mt(r)}evaluateIdentifier(t,e){return e.lookupVariable(t.value)}evaluateArgumentsExpression(t,e){const r=[],n=new Map;for(const s of t)if("KeywordArgumentExpression"===s.type){const t=s;n.set(t.key.value,this.evaluate(t.value,e))}else r.push(this.evaluate(s,e));return n.size>0&&r.push(new Pt(n)),r}evaluateCallExpression(t,e){const r=this.evaluateArgumentsExpression(t.args,e),n=this.evaluate(t.callee,e);if("FunctionValue"!==n.type)throw new Error(`Cannot call something that is not a function: got ${n.type}`);return n.value(r,e)}evaluateSliceExpression(t,e,r){if(!(t instanceof qt||t instanceof Mt))throw new Error("Slice object must be an array or string");const n=this.evaluate(e.start,r),s=this.evaluate(e.stop,r),i=this.evaluate(e.step,r);if(!(n instanceof It||n instanceof _t))throw new Error("Slice start must be numeric or undefined");if(!(s instanceof It||s instanceof _t))throw new Error("Slice stop must be numeric or undefined");if(!(i instanceof It||i instanceof _t))throw new Error("Slice step must be numeric or undefined");return t instanceof qt?new qt(Ct(t.value,n.value,s.value,i.value)):new Mt(Ct(Array.from(t.value),n.value,s.value,i.value).join(""))}evaluateMemberExpression(t,e){const r=this.evaluate(t.object,e);let n,s;if(t.computed){if("SliceExpression"===t.property.type)return this.evaluateSliceExpression(r,t.property,e);n=this.evaluate(t.property,e)}else n=new Mt(t.property.value);if(r instanceof Pt){if(!(n instanceof Mt))throw new Error(`Cannot access property with non-string: got ${n.type}`);s=r.value.get(n.value)??r.builtins.get(n.value)}else if(r instanceof qt||r instanceof Mt)if(n instanceof It)s=r.value.at(n.value),r instanceof Mt&&(s=new Mt(r.value.at(n.value)));else{if(!(n instanceof Mt))throw new Error(`Cannot access property with non-string/non-number: got ${n.type}`);s=r.builtins.get(n.value)}else{if(!(n instanceof Mt))throw new Error(`Cannot access property with non-string: got ${n.type}`);s=r.builtins.get(n.value)}return s instanceof Ft?s:new _t}evaluateSet(t,e){const r=this.evaluate(t.value,e);if("Identifier"===t.assignee.type){const n=t.assignee.value;e.setVariable(n,r)}else{if("MemberExpression"!==t.assignee.type)throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(t.assignee)}`);{const n=t.assignee,s=this.evaluate(n.object,e);if(!(s instanceof Pt))throw new Error("Cannot assign to member of non-object");if("Identifier"!==n.property.type)throw new Error("Cannot assign to member with non-identifier property");s.value.set(n.property.value,r)}}return new Vt}evaluateIf(t,e){const r=this.evaluate(t.test,e);return this.evaluateBlock(r.__bool__().value?t.body:t.alternate,e)}evaluateFor(t,e){const r=new Lt(e),n=this.evaluate(t.iterable,r);if(!(n instanceof qt))throw new Error(`Expected iterable type in for loop: got ${n.type}`);let s="";for(let e=0;e<n.value.length;++e){const i=new Map([["index",new It(e+1)],["index0",new It(e)],["revindex",new It(n.value.length-e)],["revindex0",new It(n.value.length-e-1)],["first",new Rt(0===e)],["last",new Rt(e===n.value.length-1)],["length",new It(n.value.length)],["previtem",e>0?n.value[e-1]:new _t],["nextitem",e<n.value.length-1?n.value[e+1]:new _t]]);r.setVariable("loop",new Pt(i));const o=n.value[e];if("Identifier"===t.loopvar.type)r.setVariable(t.loopvar.value,o);else if("TupleLiteral"===t.loopvar.type){const e=t.loopvar;if("ArrayValue"!==o.type)throw new Error(`Cannot unpack non-iterable type: ${o.type}`);const n=o;if(e.value.length!==n.value.length)throw new Error(`Too ${e.value.length>n.value.length?"few":"many"} items to unpack`);for(let t=0;t<e.value.length;++t){if("Identifier"!==e.value[t].type)throw new Error(`Cannot unpack non-identifier type: ${e.value[t].type}`);r.setVariable(e.value[t].value,n.value[t])}}s+=this.evaluateBlock(t.body,r).value}return new Mt(s)}evaluate(t,e){if(void 0===t)return new _t;switch(t.type){case"Program":return this.evalProgram(t,e);case"Set":return this.evaluateSet(t,e);case"If":return this.evaluateIf(t,e);case"For":return this.evaluateFor(t,e);case"NumericLiteral":return new It(Number(t.value));case"StringLiteral":return new Mt(t.value);case"BooleanLiteral":return new Rt(t.value);case"ArrayLiteral":return new qt(t.value.map((t=>this.evaluate(t,e))));case"TupleLiteral":return new Bt(t.value.map((t=>this.evaluate(t,e))));case"ObjectLiteral":{const r=new Map;for(const[n,s]of t.value){const t=this.evaluate(n,e);if(!(t instanceof Mt))throw new Error(`Object keys must be strings: got ${t.type}`);r.set(t.value,this.evaluate(s,e))}return new Pt(r,t.value)}case"Identifier":return this.evaluateIdentifier(t,e);case"CallExpression":return this.evaluateCallExpression(t,e);case"MemberExpression":return this.evaluateMemberExpression(t,e);case"UnaryExpression":return this.evaluateUnaryExpression(t,e);case"BinaryExpression":return this.evaluateBinaryExpression(t,e);case"FilterExpression":return this.evaluateFilterExpression(t,e);case"TestExpression":return this.evaluateTestExpression(t,e);default:throw new SyntaxError(`Unknown node type: ${t.type}`)}}};function Jt(t){switch(typeof t){case"number":return new It(t);case"string":return new Mt(t);case"boolean":return new Rt(t);case"object":return null===t?new Vt:Array.isArray(t)?new qt(t.map(Jt)):new Pt(new Map(Object.entries(t).map((([t,e])=>[t,Jt(e)]))),t);case"function":return new Ut(((e,r)=>{const n=e.map((t=>Dt(t)));return Jt(t(...n)??null)}));case"undefined":return new Vt;default:throw new Error(`Cannot convert to runtime value: ${t}`)}}function Dt(t){let e=t;return Array.isArray(t)?e=t.map((t=>Dt(t))):t instanceof Map?(e={},t.forEach(((t,r)=>{e[r]=Dt(t)}))):"ObjectValue"===t.type?t.orgValue?e=t.orgValue:t.forEach?(e={},t.forEach(((t,r)=>{e[r]=Dt(t)}))):e=Dt(t.value):"ArrayValue"===t.type?e=t.value.map((t=>Dt(t))):t.type&&(e=t.value),e}function Wt(t,e=0){return Math.floor(Math.random()*(t-e+1))+e}var Ht={randomInt:Wt,select:function(t,e){if(Array.isArray(t)||"string"==typeof t)return void 0===e?e=Wt(t.length-1):"string"==typeof e&&(e=parseInt(e)),e<0&&(e=t.length+e),t[e];if(t&&"object"==typeof t){if(void 0===e){const r=Object.keys(t);e=r[Wt(r.length-1)]}return t[e]}},tojson:function(t,e){return e&&"object"==typeof e&&(e=e.indent),JSON.stringify(t,null,e)}},Gt=class extends Lt{constructor(t){super(t),this.parent=t}assign(t){for(const[e,r]of Object.entries(t))this.set(e,r)}clear(){this.variables.clear()}},Kt=class t{static{this.global=new Gt}constructor(t,e={}){const r=it(t,e={lstrip_blocks:!0,trim_blocks:!0,...e});this.parsed=Tt(r)}render(e){const r=new Lt(t.global);r.set("false",!1),r.set("true",!0),r.set("raise_exception",(t=>{throw new Error(t)})),r.set("range",jt);for(const[t,n]of Object.entries(e))r.set(t,n);return new zt(r).run(this.parsed).toString()}};function Xt(t,e){let r;switch(t.type){case"Identifier":r=t.value;break;case"MemberExpression":r=Xt(t.object,e);break;case"FilterExpression":r=Xt(t.operand,e);break;case"Set":{e||(e=[]);const n=Xt(t.assignee);n&&e.push(n),r=Xt(t.value,e);break}}return r&&e?.includes(r)&&(r=void 0),r}function Zt(t){let e;if("Program"===t.type)e=t.body.some((t=>Zt(t)));else e=t.isStatement;return e}function Yt(t,e){let r=[];if(Array.isArray(t))r=t.map((t=>Yt(t,e))).filter(Boolean).flat();else switch(t.type){case"Program":r=t.body.map((t=>Yt(t,e))).filter(Boolean).flat();break;case"If":r=[Xt(t.test,e),...Yt(t.body,e),...Yt(t.alternate,e)].filter(Boolean);break;case"BinaryExpression":r=[Xt(t.left,e),Xt(t.right,e)].filter(Boolean);break;case"For":{const n=Xt(t.loopvar);n&&(e||(e=[]),e.push(n)),r=[Xt(t.iterable,e),...Yt(t.body,e)].filter(Boolean);break}case"CallExpression":r=[Xt(t.callee,e),...Yt(t.args,e)].filter(Boolean);break;default:r=[Xt(t,e)].filter(Boolean)}return r}Kt.global.assign(Ht);var Qt=class extends G{static isTemplate(t){let e,r,n=!1;if("object"==typeof t?(r=t.template,e=t.compiledTemplate):r=t,!e&&r)try{e=new Kt(r)}catch(t){}return e&&(n=Zt(e.parsed)),n}getVariables(t=this.compiledTemplate){return Yt(t.parsed,[]).filter(((t,e,r)=>r.indexOf(t)===e))}_initialize(t){const e=t?.template;if("string"!=typeof e)throw new E("Prompt template must be a string","PromptTemplate",400);this.compiledTemplate=new Kt(e),this.inputVariables=Array.isArray(t?.inputVariables)?t.inputVariables:this.getVariables()}_format(t){return this.compiledTemplate.render(t)}};function te(t){return function(e){return t}}function ee(t){const e=t.split(""),r=[],n=(t,r)=>{for(let n=r;n<e.length;n+=1)if(t.includes(e[n]))return n;return-1};let s=0;for(;s<e.length;)if("{"===e[s]&&s+1<e.length&&"{"===e[s+1])r.push({type:"literal",text:"{"}),s+=2;else if("}"===e[s]&&s+1<e.length&&"}"===e[s+1])r.push({type:"literal",text:"}"}),s+=2;else if("{"===e[s]){const t=n("}",s);if(t<0)throw new Error("Unclosed '{' in template.");r.push({type:"variable",name:e.slice(s+1,t).join("")}),s=t+1}else{if("}"===e[s])throw new Error("Single '}' in template.");{const t=n("{}",s),i=(t<0?e.slice(s):e.slice(s,t)).join("");r.push({type:"literal",text:i}),s=t<0?e.length:t}}return r}function re(t,e){return t.reduce(((t,r)=>{let n;return n="variable"===r.type?r.name in e?t+e[r.name]:t:t+r.text,n}),"")}function ne(t){const e=new Set;return t.forEach((t=>{"variable"===t.type&&e.add(t.name)})),[...e]}G.register(Qt,{name:"hf",aliases:["huggingface","internal","default"]});var se=class extends G{static isTemplate(t){let e,r,n=!1;if("object"==typeof t?(r=t.template,e=t.compiledTemplate):r=t,!e&&r)try{e=ee(r)}catch(t){}if(e){n=ne(e).length>0}return n}getVariables(t=this.compiledTemplate){return ne(t)}_initialize(t){const e=t?.template;if("string"!=typeof e)throw new E("Prompt template must be a string","PromptTemplate",400);this.compiledTemplate=ee(e),this.inputVariables=Array.isArray(t?.inputVariables)?t.inputVariables:this.getVariables()}_format(t){return re(this.compiledTemplate,t)}};function ie(t,e){return"string"==typeof e&&(e=e.split(".").filter((t=>t.length))),e.reduce(((t,e)=>t?.[e]),t)}function oe(t,e,r){let n=function(t,e,r){return t.replace(/{{\s*re_replace\s+\.(.+?)\s+(["'])([^\2]*?)\2\s+(["'])([^\4]*?)\4\s*}}/g,((t,n,s,i,o,a)=>{if(r)return e[n]=null,t;const c=new RegExp(i,"g");return ie(e,n).replace(c,a)}))}(t,e,r);return n=function(t,e,r){return t.replace(/{{\s*join\s+\.(.+?)\s+(["'])([^\2]*?)\2\s*}}/g,((t,n,s,i)=>r?(e[n]=null,t):ie(e,n).join(i)))}(n,e,r),n=function(t,e,r){return t.replace(/{{\s*if\s*(\S+?)\s*}}([^{]*)({{\s*else\s*}}([^{]*))?{{\s*end\s*}}/g,((t,n,s,i,o)=>{if(r)return n.startsWith(".")&&(n=n.substring(1)),e[n]=null,t;let a;if(!n.startsWith("."))throw new Error("Functionality not implemented");{const t=ie(e,n.substring(1));if(null==t)a=o??"";else if("string"==typeof t)a=t.length>0?s:o??"";else if(Array.isArray(t))a=t.length>0?s:o??"";else{if("boolean"!=typeof t)throw new Error(`Unexpected type for variable ${n}: ${typeof t}`);a=t?s:o??""}}return a}))}(n,e,r),n=function(t,e,r){return t.replace(/{{\s*range\s*[.$]([^{}\s]+?)\s*}}([^{]*?){{\.}}([^{]*?){{\s*end\s*}}/g,((t,n,s,i)=>{if(r)return e[n]=null,t;const o=ie(e,n);if(Array.isArray(o)){let t="";for(const e of o)t+=`${s}${e}${i}`;return t}return t}))}(n,e,r),n=function(t,e,r){return t.replace(/{{\s*\.([^{}\s]+?)\s*}}/g,((t,n)=>r?(e[n]=null,t):ie(e,n)||""))}(n,e,r),n=function(t,e,r){return t.replace(/{{\s*index\s*\.(.+?)\s+(.+?)\s*}}/g,((t,n,s)=>{if(r)return e[n]=null,t;const i=ie(e,n);let o;return o=isNaN(s)?i[s.substring(1,s.length-1)]:i[parseInt(s,10)],o||""}))}(n,e,r),n}G.register(se,{name:"fstring",aliases:["python","f-string","langchain"]});var ae=class extends G{static isTemplate(t){const e="string"==typeof t?t:t.template;return e?.includes("{{")&&e.includes("}}")}getVariables(t){const e={};return oe(t,e,!0),[...Object.keys(e)]}_initialize(t){const e=t?.template;if("string"!=typeof e)throw new E("Prompt template must be a string","PromptTemplate",400);this.inputVariables=Array.isArray(t?.inputVariables)?t.inputVariables:this.getVariables(e)}_format(t){return oe(this.template,t)}};function ce(t){return Object.keys(t).sort().map((e=>t[e]))}G.register(ae,{name:"golang",aliases:["localai","ollama"]});var ue=class extends G{static from(t){return new this(t)}constructor(t){super(t)}_initialize(t){t&&(t.suffix&&(this.suffix=t.suffix),t.exampleSeparator&&(this.exampleSeparator=t.exampleSeparator),t.prefix&&(this.prefix=t.prefix),t.examplePrompt&&(this.examplePrompt=t.examplePrompt instanceof G?t.examplePrompt:G.from(t.examplePrompt)),t.examples&&(this.examples=t.examples)),this.prefix||(this.prefix=""),this.exampleSeparator||(this.exampleSeparator="\n\n"),this.suffix||(this.suffix="")}async _format(t){const e=[];for await(const t of this.examples)if(this.examplePrompt){const r=await this.examplePrompt.format(t);e.push(r)}else if("string"==typeof t)e.push(t);else if(t){const r=ce(t);r.length>0&&e.push(...r)}const r=[this.prefix,...e,this.suffix].join(this.exampleSeparator),n=this.templateFormat;return await G.format({template:r,data:t,templateFormat:n})}toJSON(t=this){const e=super.toJSON(t);return t.suffix&&(e.suffix=t.suffix),t.exampleSeparator&&(e.exampleSeparator=t.exampleSeparator),t.prefix&&(e.prefix=t.prefix),t.examplePrompt&&(e.examplePrompt=t.examplePrompt),t.examples&&(e.examples=t.examples),e}};G.register(ue,{name:"fewshot",aliases:["few_shot"]});var he=/(\\)?(\$)(?!\()(\{?)([\w.]+)(?::?-((?:\$\{(?:\$\{(?:\$\{[^}]*\}|[^}])*}|[^}])*}|[^}])+))?(\}?)/gi;function le(t){return t.replace(/\\\$/g,"$")}function fe(t,e,r){return t.replace(he,((n,s,i,o,a,c,u)=>"\\"===s?n.slice(1):e[a]?e[a]===r[a]?e[a]:fe(e[a],e,r):r[a]?r[a]===t?r[a]:fe(r[a],e,r):c?c.startsWith("$")?fe(c,e,r):c:""))}function pe(t){let e=process.env;t&&null!=t.processEnv&&(e=t.processEnv);for(const r in t.parsed){let n=t.parsed[r];if(!n)continue;n=Object.prototype.hasOwnProperty.call(e,r)?e[r]===t.parsed[r]?fe(n,e,t.parsed):e[r]:fe(n,e,t.parsed),t.parsed[r]=n?le(n):n}for(const r in t.parsed)e[r]=t.parsed[r];return t}function we(t,e={},r){switch(r||(r=new WeakSet),e.processEnv||(e.processEnv={...process.env}),e.parsed||(e.parsed=e.processEnv),typeof t){case"string":t=fe(t,e.processEnv,e.parsed);break;case"object":if(r.has(t))return t;if(r.add(t),Array.isArray(t))for(let n=0;n<t.length;n++){const s=t[n];"string"!=typeof s&&"object"!=typeof s||(t[n]=we(t[n],e,r))}else for(const[n,s]of Object.entries(t))"string"!=typeof s&&"object"!=typeof s||(t[n]=we(s,e,r))}return t}var de="@",me=/(\S.+?[.!?])(?=\s+|$)|(\S.+?)(?=[\n]|$)/g,ye=/([A-Z][a-z]{1,2}\.)\s(\w)/g,be=/(\.[a-zA-Z]\.)\s(\w)/g,ge=new RegExp("([A-Z][a-z]{1,2}\\.)"+de+"(\\w)","g"),ve=new RegExp("(\\.[a-zA-Z]\\.)"+de+"(\\w)","g");function xe(t,e,r){const n="$1"+e+"$2";let s=t;for(let t=0;t<r.length;t++)s=s.replace(r[t],n);return s}function Ee(t,e=!0){const r=(t=(t=(t=(t=(t=t.replace(/([。!??])\1+/g,"$1")).replace(/([。!??])([^”’])/g,"$1\n$2")).replace(/(\.{6})([^”’])/g,"$1\n$2")).replace(/(…{2})([^”’])/g,"$1\n$2")).replace(/([。!??][”’])([^,。!??])/g,"$1\n$2")).split("\n");let n=[];for(let t=0;t<r.length;t++){let s=r[t].trim();if(!s)continue;if(!e){n.push(s);continue}let i=xe(s,de,[ye,be]),o=Array.from(i.matchAll(me));if(o.length)for(let t=0;t<o.length;t++){let e=xe(o[t][0]," ",[ge,ve]);n.push(e)}else n.push(s)}return n}function Se(t,e=2,r=.5){const n=10**e;return Math.trunc((t+Number.EPSILON+r/n)*n)/n}async function $e(t){return new Promise((e=>setTimeout(e,t)))}var ke=require("custom-ability"),Oe="event",Ae="event-bus";var Te=(0,ke.createAbilityInjector)((function(t){return class{static get emitter(){if(!this._emitter){const t=this.get(Ae)?.emitter;t&&(this._emitter=t,this.prototype._events=t._events)}return this._emitter}get emitter(){return this.constructor._emitter}on(e,r){const n=t.emitter;if(!n)throw new TypeError("EventBackend required");return n.on(e,r)}once(e,r){const n=t.emitter;if(!n)throw new TypeError("EventBackend required");return n.once(e,r)}off(e,r){const n=t.emitter;if(!n)throw new TypeError("EventBackend required");return n.off(e,r)}emit(e,...r){const n=t.emitter;if(!n)throw new TypeError("EventBackend required");return"error"===e?this.emitError.apply(this,r):n.emit.call(this,e,this.name,...r)}emitError(e,...r){const n=t.emitter;if(!n)throw new TypeError("EventBackend required");return n.emit.call(this,"error",e,this.name,...r)}async emitAsync(e,...r){const n=t.emitter;if(!n)throw new TypeError("EventBackend required");return n.emitAsync.call(this,e,this.name,...r)}}}),!0);function je(t,e){return!t||t.some((t=>t instanceof RegExp?t.test(e):t===e))}var Ce=498,Ne=class{get active(){return this._active}set active(t){t!==this._active&&(t?(this.pingTimer&&(clearInterval(this.pingTimer),this.pingTimer=void 0),this.options.pingInterval>0&&(this.pingTimer=setInterval((()=>this.publish()),this.options.pingInterval))):(this.clients.size&&this.clearClients(),this.pingTimer&&(clearInterval(this.pingTimer),this.pingTimer=void 0)),this._active=t)}constructor(t){this.options=Object.assign({},{pingInterval:3e3,maxStreamDuration:3e4,clientRetryInterval:1e3,startId:1,historySize:100,rewind:0,cors:!1},t),this.nextID=this.options.startId,this.clients=new Set,this.messages=[],this.active=!0}publish(t,e){let r,n;this.active||T("Channel closed","SSEChannel",Ce);let s=e;if(t||e)n=this.nextID++,"object"==typeof t&&(t.event?(s=t.event,void 0!==t.data&&(t=JSON.stringify(t.data))):t=JSON.stringify(t)),t=t?t.split(/[\r\n]+/).map((t=>"data: "+t)).join("\n"):"",r="id: "+n+"\n"+(e?"event: "+e+"\n":"")+(t||"data: ")+"\n\n",this.messages.push({id:n,_eventName:s,output:r});else{if(!this.clients.size)return;r="data: \n\n"}for([...this.clients].filter((t=>!s||je(t.events,s))).forEach(((t,e)=>{t.res.write(r)}));this.messages.length>this.options.historySize;)this.messages.shift();return n}subscribe(t,e,r){this.active||T("Channel closed","SSEChannel",Ce);const n={req:t,res:e,events:r},s=this.options.maxStreamDuration;let i="max-age=0, stale-while-revalidate=0, stale-if-error=0, no-transform";s>0&&(i+=", s-maxage="+(Math.floor(s/1e3)-1));const o={"Content-Type":"text/event-stream","Cache-Control":i,Connection:"keep-alive"};this.options.cors&&(o["access-control-allow-origin"]="*"),n.req.socket.setNoDelay(!0),n.res.writeHead(200,o);let a="retry: "+this.options.clientRetryInterval+"\n\n";const c=Number.parseInt(t.headers["last-event-id"],10),u=Number.isNaN(c)?this.options.rewind:this.nextID-1-c;return u&&this.messages.filter((t=>je(n.events,t.eventName))).slice(0-u).forEach((t=>{a+=t.output})),n.res.write(a),this.clients.add(n),s>0&&setTimeout((()=>{n.res.writableEnded||this.unsubscribe(n)}),s),n.res.on("close",(()=>this.unsubscribe(n))),n}unsubscribe(t){t.res.end(),this.clients.delete(t)}clearClients(){this.clients.forEach((t=>t.res.end())),this.clients.clear()}listClients(){const t={};return this.clients.forEach((e=>{const r=e.req.socket.remoteAddress??"";r in t||(t[r]=0),t[r]++})),t}getSubscriberCount(){return this.clients.size}};function Fe(t){return t instanceof ReadableStream||t instanceof WritableStream}var Ie=600,Me=601,Re=class extends x{constructor(t,e=Ie){super(t,500)}};function Pe(t){if(t){const e=t.getReader();return new ReadableStream({async start(t){const{done:r,value:n}=await e.read();if(!r){const e=(new TextDecoder).decode(n);t.error(new Re(`Response error: ${e}`,Me))}}})}return new ReadableStream({start(t){t.error(new Re("Response error: No response body",Me))}})}function qe(){return new ReadableStream({start(t){t.close()}})}var Be=require("eventsource-parser");function Ue(t){const e=new TextDecoder;let r;return new TransformStream({async start(e){r=(0,Be.createParser)((r=>{if("data"in r&&"event"===r.type&&"[DONE]"===r.data||"done"===r.event)e.terminate();else if("data"in r){const n=t?t(r.data,{event:r.event}):r.data;n&&e.enqueue(n)}}))},transform(t){r.feed(e.decode(t))}})}function Ve(){let t=!0;return e=>(t&&(e=e.trimStart())&&(t=!1),e)}function _e(t,e){if(!t.ok)return Pe(t.body);let r=t.body||new ReadableStream({start(t){t.close()}});return r instanceof ReadableStream||(r=ReadableStream.from(r)),r.pipeThrough(Ue(e))}function Le(t){let e=t[Symbol.asyncIterator]();return new ReadableStream({async pull(t){const{done:r,value:n}=await e.next();r?t.close():t.enqueue(n)},async cancel(t){await(e.return?.(t))}})}function ze(t){const e=t||{};return new TransformStream({async start(t){const r=t.error;if(t.error=n=>{r.call(t,n),e.onError&&e.onError(n)},e.onStart)try{await e.onStart(t)}catch(e){t.error(e)}},async transform(t,r){try{let n;e.onTransform&&(n=await e.onTransform(t,r)),n||(n=t),r.enqueue(n)}catch(t){r.error(t)}},async flush(t){if(e.onFinal)try{await e.onFinal(t)}catch(e){return t.error(e)}t.terminate()}})}var Je={};a(Je,{XXHashAlgorithm:()=>or,base32768:()=>tr,uuid:()=>Ke,uuidNIL:()=>He.NIL,uuidParse:()=>He.parse,uuidStringify:()=>He.stringify,uuidValidate:()=>He.validate,uuidVersion:()=>He.version,uuidv1:()=>He.v1,uuidv4:()=>He.v4,uuidv5:()=>He.v5,xxhash:()=>ar,xxhash32:()=>sr,xxhash64:()=>ir,xxhashAsStr:()=>cr});var De=require("uuid"),We=h(require("base32768")),He=require("uuid"),Ge={1:De.v1,4:De.v4,5:De.v5};function Ke(t=1,e){const r=Ge[t];return e?We.encode(r(null,[])):r()}var Xe={};a(Xe,{XXHashAlgorithm:()=>or,base32768:()=>tr,xxhash:()=>ar,xxhash32:()=>sr,xxhash64:()=>ir,xxhashAsStr:()=>cr});var Ze=h(require("xxhashjs")),Ye=h(require("base32768")),Qe=require("json-canonicalize");u(Xe,require("json-canonicalize"));var tr=Ye,{h32:er,h64:rr}=Ze.default,nr=588213;function sr(t,e=16){return"object"==typeof t&&(t=(0,Qe.canonicalize)(t)),er(t,nr).toString(e)}function ir(t,e=16){return"object"==typeof t&&(t=(0,Qe.canonicalize)(t)),rr(t,nr).toString(e)}var or=(t=>(t[t.xxhash64=111]="xxhash64",t[t.xxhash32=112]="xxhash32",t))(or||{});function ar(t,e=111,r=nr){let n;return t.buffer&&(t=t.buffer),112!==e?(n=rr(t,r),n=new Uint16Array([n._a00,n._a16,n._a32,n._a48]),n=new Uint8Array(n.buffer)):(n=er(t,r),n=new Uint16Array([n._low,n._high]),n=new Uint8Array(n.buffer)),n}function cr(t,e=111,r=nr){return Ye.encode(ar(t,e,r))}u(Je,Xe),u(j,Je);var ur=h(require("path")),hr=/[<>:"/\\|?*\u0000-\u001F]/,lr=/^(con|prn|aux|nul|com\d|lpt\d)$/i,fr=100,pr=/^\.+(\\|\/)|^\.+$/,wr=/\.+$/,dr=/[\u0000-\u001F\u0080-\u009F\u200E\u200F\u202A-\u202E\u2066-\u2069]/;function mr(){return new RegExp(hr.source,"g")}function yr(){return new RegExp(dr.source,"g")}function br(t){return t&&!(hr.test(t)||yr().test(t)||pr.test(t)||wr.test(t))}function gr(t){const e=t.split(ur.default.sep);return("/"===t[0]||e[0]&&ur.default.dirname(e[0])===e[0])&&e.shift(),e.every(br)}function vr(t,e={}){const r=e.replacement||"!";if((hr.test(r)||dr.test(r))&&T("Replacement string cannot contain reserved filename characters","sanitizeFilename",400),r.length>0){const e=/([<>:"/\\|?*\u0000-\u001F]){2,}/;t=t.replace(e,"$1")}if(t=(t=(t=(t=(t=t.normalize("NFD")).replace(pr,r)).replace(mr(),r)).replace(yr(),r)).replace(wr,""),r.length>0){"."===t[0]||"."!==t[0]||(t=r+t),"."===t[t.length-1]&&(t+=r)}t=lr.test(t)?t+r:t;const n="number"==typeof e.maxLength?e.maxLength:fr;if(t.length>n){const e=t.lastIndexOf(".");if(-1===e)t=t.slice(0,n);else{const r=t.slice(0,e),s=t.slice(e);t=r.slice(0,Math.max(1,n-s.length))+s}}return t}function xr(t,e={}){const r=t.split(ur.default.sep);let n;("/"===t[0]||r[0]&&ur.default.dirname(r[0])===r[0])&&(n=r.shift());const s=r.map((t=>vr(t,e)));return void 0!==n&&s.unshift(n),s.join(ur.default.sep)}function Er(t,e=1){let r="";for(;e--;){const e=ur.default.extname(t);if(!e)break;r=e+r,t=ur.default.basename(t,e)}return r}function Sr(t){return t.split(".").length-1}var $r=require("util-ex");function kr(t,e){if("string"!=typeof t)throw new E("modelName must be a string","isModelNameMatched",400);switch(typeof e){case"string":if((0,$r.isRegExpStr)(e)){const r=(e=(0,$r.toRegExp)(e)).exec(t);if(r)return r}else if(t.toLowerCase()===e.toLowerCase())return e;break;case"object":if(Array.isArray(e)){for(const r of e)if("string"==typeof r){if((0,$r.isRegExpStr)(r)){const n=(e=(0,$r.toRegExp)(r)).exec(t);if(n)return n}else if(t.toLowerCase()===r.toLowerCase())return r}else if(r instanceof RegExp){const e=r.exec(t);if(e)return e}else if("function"==typeof r){const e=r.call(this,t);if(e)return e}}else if(e instanceof RegExp){const r=e.exec(t);if(r)return r}break;case"function":const r=e.call(this,t);if(r)return r}}function Or(t){return Object.keys(t).filter((t=>Number.isNaN(Number(t))))}var Ar=require("util-ex");function Tr(t,e){if(e){const r=Object.keys(e);if(r.length){const n=Object.values(e);return(0,Ar.newFunction)("expression",r,`return ${t}`)(...n)}}return(0,Ar.newFunction)("expression",[],`return ${t}`)()}function jr(t){return t?Cr(t,[],""):[]}function Cr(t,e,r="."){return Array.isArray(t)?t.flatMap(((t,r)=>Cr(t,[...e,`[${r}]`]))):(n=t)&&n.constructor===Object?Object.entries(t).flatMap((([t,n])=>Cr(n,[...e,r+t]))):[e.join("")];var n}function Nr(t){if(t<2)throw new E("repetitionThreshold must be greater than 1","createEndWithRepetitionDetector",400);const e=new RegExp(`([\\S\\s]+)(\\1{${t-1},})$`);return function(t){return e.exec(t)}}var Fr=h(require("path")),Ir=h(require("fs"));function Mr(t,e,r,n){const s=n?.signal,i=n?.exclude;let o;if(Fr.default.isAbsolute(t)?o=Ir.existsSync(t)?t:Rr(Fr.default.basename(t),[Fr.default.dirname(t)],{extNames:r,exclude:i,signal:s}):(e||(e=["."]),o=Rr(t,e,{extNames:r,exclude:i,signal:s})),!o)throw new $(t,"loadFileFromPaths");{const t=o;o=Ir.readFileSync(o),n&&(n.filepath=t)}return o}function Rr(t,e,{extNames:r,signal:n,exclude:s=[]}){let i;const o=r?r.map((e=>Er(t,Sr(e)))):void 0;"string"==typeof s&&(s=[s]);for(const a of e){if(n?.aborted)throw n.reason;const e=Fr.default.resolve(a,t);if(o)for(let t=0;t<o.length;t++){const n=e+(o[t]!==r[t]?r[t]:"");if(!s.includes(n)&&Ir.existsSync(n)){i=n;break}}else if(!s.includes(e)&&Ir.existsSync(e)){i=e;break}}return i}function Pr(t,e,r,n,s){let i;"string"==typeof n?(i=n,n=void 0):i=n?.encoding??"utf8";return Mr(t,e,r,n).toString(i)}function qr(t,e,r){const n=[],s="string"==typeof t?[t]:[...t],i=new Set;for(;s.length>0;){if(r?.aborted)throw r.reason;const t=Br(s.pop()),o=Fr.default.resolve(t);if(i.has(o))continue;i.add(o);const a=Ir.statSync(t,{throwIfNoEntry:!1});if(a?.isDirectory()){const r=Ir.readdirSync(t,{withFileTypes:!0});for(let i=0;i<r.length;i++){const o=r[i],a=Fr.default.join(t,o.name);o.isDirectory()?s.push(a):!o.isFile()||e&&!e(a)||n.push(a)}}}return n}function Br(t){const e=Ir.lstatSync(t,{throwIfNoEntry:!1});return e?.isSymbolicLink()&&(t=Ir.readlinkSync(t)),t}var Ur=require("fs"),Vr=h(require("path")),_r=require("load-config-file"),Lr=require("yaml"),zr=require("yaml-types"),Jr=require("mime-type/with-db"),Dr=require("yaml"),Wr=[zr.regexp];function Hr(t){Array.isArray(t)||(t=[t]);for(const e of t){-1===Wr.indexOf(e)&&Wr.push(e)}}function Gr(t){return(0,Lr.parse)(t,{customTags:Wr})}function Kr(t,e){const r=[],n=e?.after,s=e?.exclude?"string"==typeof e.exclude?[e.exclude]:e.exclude:void 0,i=e?.extensions?"string"==typeof e.extensions?[e.extensions]:e.extensions.map((t=>t.startsWith(".")?t:"."+t)):[".yml",".yaml",".json"];return function(t,e){const r=(0,Ur.readdirSync)(t,{withFileTypes:!0,recursive:!0});for(const n of r){const r=Vr.default.join(t,n.name);n.isFile()&&e(r,n)}}(t,((t,e)=>{if(s?.includes(t))return;const o=Vr.default.extname(t),a=(0,Ur.statSync)(t);if(i.includes(o)){if(n?.hasOwnProperty(t)&&a.mtimeMs<=n[t])return;r.push(t)}})),r}function Xr(t,e){return Kr(t,e).map((t=>_r.Config.loadSync(t))).filter((t=>void 0!==t))}function Zr(t,e,r=1){"."===t[0]&&r++;const n=Er(t,r);(!n||n.split(".").length<=1)&&(t+=".yaml");const s=Jr.mimeType.lookup(t);if("application/json"===s)e=JSON.stringify(e,null,2);else{if("text/yaml"!==s)throw new Error(`${t} unsupported mime type: ${s}`);e=(0,Lr.stringify)(e)}const i=Vr.default.dirname(t);return(0,Ur.existsSync)(i)||(0,Ur.mkdirSync)(i,{recursive:!0}),(0,Ur.writeFileSync)(t,e,{encoding:"utf8"}),t}function Yr(t){t instanceof Date&&(t=t.toISOString());return function(t,e){return t?`'${e}'`:String(e)}("string"==typeof t,t)}function Qr(t,e){return t.map((t=>rn(t,e))).join(" AND ")}function tn(t,e){return t.map((t=>rn(t,e))).join(" OR ")}function en(t,e){const r=[];return Object.keys(e).forEach((n=>{const s=e[n];switch(n){case"$lt":case"<":r.push(`${t} < ${Yr(s)}`);break;case"<=":case"$lte":r.push(`${t} <= ${Yr(s)}`);break;case"$gt":case">":r.push(`${t} > ${Yr(s)}`);break;case"$gte":case">=":r.push(`${t} >= ${Yr(s)}`);break;case"$ne":case"!=":r.push(`${t} != ${Yr(s)}`);break;case"=":case"$eq":r.push(`${t} = ${Yr(s)}`);break;case"$in":r.push(`${t} IN (${s.map((t=>Yr(t))).join(", ")})`);break;case"$nin":r.push(`${t} NOT IN (${s.map((t=>Yr(t))).join(", ")})`);break;case"$regex":r.push(`${t} REGEXP '${s.source}'`);break;case"$like":r.push(`${t} LIKE '${s}'`);break;case"$nlike":r.push(`${t} NOT LIKE '${s}'`);break;case"$glob":r.push(`${t} GLOB '${s}'`);break;case"$nglob":r.push(`${t} NOT GLOB '${s}'`);break;default:throw new Error(`Unsupported condition operator: ${n}`)}})),r.join(" AND ")}function rn(t,e){const r=[];if("function"!=typeof e&&(e=t=>t),Array.isArray(t))r.push(Qr(t,e));else for(const[n,s]of Object.entries(t))if("$and"===n)r.push(`(${Qr(t[n],e)})`);else if("$or"===n)r.push(`(${tn(t[n],e)})`);else{const t=typeof s;if(null==s)r.push(`${e(n)} IS NULL`);else if(s instanceof Date)r.push(`${e(n)}='${s.toISOString()}'`);else if("object"!==t||Array.isArray(s))if("string"===t)r.push(`${e(n)}='${s}'`);else{if("number"!==t&&"boolean"!==t)throw new Error(`Unsupported value type for key ${n}`);r.push(`${e(n)}=${s}`)}else r.push(en(e(n),s))}return r.length>1?r.join(" AND "):r[0]}function nn(t){const e=t.indexOf("://");if(e>0)return t.substring(0,e)}function sn(t,e=0){let r,n=t*10**e;return t>=1e12?(n=Math.round(n/1e12),r="T"):t>=1e9?(n=Math.round(n/1e9),r="B"):t>=1e6?(n=Math.round(n/1e6),r="M"):t>=1e3?(n=Math.round(n/1e3),r="K"):(n=Math.round(n),r=""),n/=10**e,n.toFixed(e)+r}function on(t){const e=t.match(/^\s*[+]?(\d+(?:[.]\d+)?)\s*([TBMK])?\s*$/i);if(!e)throw new E("Invalid formatted parameter size string.","scaleToSize",400);const r=parseFloat(e[1]),n=e[2]?.toLowerCase();switch(n){case"t":return 1e12*r;case"b":return 1e9*r;case"m":return 1e6*r;case"k":return 1e3*r;default:return r}}function an(t,e){const r=e?.level||0,n=e?.visiting||new Set,s=e?.objectTag||"*",i=e?.arrayTag||"-";let o=[];const a=" ".repeat(2*r);if(null!=t)switch(typeof t){case"object":n.has(t)?o=["[Circular]"]:(n.add(t),o=Array.isArray(t)?t.map((t=>i+c(t))):Object.entries(t).map((([t,e])=>s+" `"+t+"`:"+c(e))));break;case"string":return t;default:return JSON.stringify(t)}else o=["null"];return o.length?a+o.join("\n"+a):"";function c(t){return(null!=t&&"object"==typeof t?"\n":" ")+an(t,{level:r+1,visiting:n})}}_r.Config.register([".yml",".yaml"],Gr),_r.Config.register([".json"],(function(t){return JSON.parse(t)}));var cn=class t{constructor(t=0){this.bitField=t}static has(t,e){return!!(t&1<<e)}static add(t,e){return t|1<<e}static delete(t,e){return t&~(1<<e)}add(t){return this.bitField|=1<<t,this}delete(t){return this.bitField&=~(1<<t),this}has(e){return t.has(this.bitField,e)}clear(){return this.bitField=0,this}valueOf(){return this.bitField}toString(){return this.bitField.toString()}toJSON(){return this.bitField}},un=require("events-ex"),hn=32;function ln(t){return e=Math.min(Math.max(16,t),1073741824),e>>>=0,e-=1,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,1+(e|=e>>16);var e}var fn=class{constructor(t){this._capacity=ln(t),this._length=0,this._front=0,this.arr=[]}push(t){const e=this._length;this.checkCapacity(e+1);const r=this._front+e&this._capacity-1;return this.arr[r]=t,this._length=e+1,r}pop(){const t=this._length;if(0===t)return;const e=this._front+t-1&this._capacity-1,r=this.arr[e];return this.arr[e]=void 0,this._length=t-1,r}shift(){const t=this._length;if(0===t)return;const e=this._front,r=this.arr[e];return this.arr[e]=void 0,this._front=e+1&this._capacity-1,this._length=t-1,r}get length(){return this._length}checkCapacity(t){this._capacity<t&&this.resizeTo(ln(1.5*this._capacity+16))}resizeTo(t){const e=this._capacity;this._capacity=t;const r=this._front,n=this._length;if(r+n>e){const t=r+n&e-1;!function(t,e,r,n,s){for(let i=0;i<s;++i)r[i+n]=t[i+e],t[i+e]=void 0}(this.arr,0,this.arr,e,t)}}},pn=class extends un.EventEmitter{};function wn(t){return"function"==typeof t}function dn(){return"1"}var mn=class{constructor(t,{initFn:e=dn,pauseFn:r,resumeFn:n,capacity:s=hn}={}){if(wn(r)!==wn(n))throw new Error("pauseFn and resumeFn must be both set for pausing");this.maxConcurrency=t,this.free=new fn(t),this.waiting=new fn(s),this.releaseEmitter=new pn,this.useDefaultTokens=e===dn,this.pauseFn=r,this.resumeFn=n,this.paused=!1,this.releaseEmitter.on("release",(t=>{const e=this.waiting.shift();e?e.resolve(t):(this.resumeFn&&this.paused&&(this.paused=!1,this.resumeFn()),this.free.push(t))}));for(let r=0;r<t;r++)this.free.push(e())}tryAcquire(){return this.free.pop()}acquire(t){let e=this.tryAcquire();return void 0!==e?Promise.resolve(e):new Promise(((e,r)=>{this.pauseFn&&!this.paused&&(this.paused=!0,this.pauseFn());const n=this.waiting.push({resolve:e,reject:r});return t&&t.addEventListener("abort",(()=>{this.waiting[n]=void 0;const e=t.reason instanceof Error?t.reason:new Error(t.reason||"aborted");t.alreadyRejected=!0,r(e)})),n}))}release(t){this.releaseEmitter.emit("release",this.useDefaultTokens?"1":t)}drain(){const t=new Array(this.maxConcurrency);for(let e=0;e<this.maxConcurrency;e++)t[e]=this.acquire();return Promise.all(t)}pendingCount(){return this.waiting.length}};function yn(t,{timeUnit:e=1e3,uniformDistribution:r=!1}={}){const n=new mn(r?1:t),s=r?e/t:e;return async function(){await n.acquire(),setTimeout((()=>n.release()),s)}}var bn=require("custom-ability"),gn=require("util-ex"),vn=class extends AbortController{constructor(t){super(),(0,gn.defineProperty)(this,"parent",t)}abort(t,e){this.signal.aborted||("string"==typeof t&&(t=new O(t)),t&&e&&"object"==typeof t&&Object.assign(t.data,e),super.abort(t))}throwRejected(t){const e=this.signal;if(e.aborted){if(void 0===t&&(t=e.alreadyRejected),t)return!0;throw e.reason instanceof Error?e.reason:new O(e.reason||"aborted")}}},xn=class{get maxTaskConcurrency(){return this._maxTaskConcurrency}get semaphore(){const t=this._maxTaskConcurrency;let e=this.__task_semaphore;return t>0&&!e&&(e=this.__task_semaphore=new mn(t-1)),e}isAborted(t){const e=this.hasAsyncFeature($n);let r=this.__task_aborter;if(r&&e){if(null==t)throw new E("Missing taskId",this.name+".isAborted",400);r=r[t]}return!r||r.signal.aborted}getRunningTask(t){const e=this.hasAsyncFeature($n);let r=this.__task_aborter;if(r&&e){if(null==t)throw new E("Missing taskId",this.name+".getRunningTask",400);r=r[t]}return r?.signal.aborted&&(e?this.__task_aborter[t]=void 0:this.__task_aborter=void 0,r=void 0),r}getRunningTaskCount(){let t;if(this.hasAsyncFeature($n)){const e=this.__task_aborter;t=e&&Object.entries(e).filter((([t,r])=>{if(!r?.signal.aborted)return!0;e[t]=void 0})).length}else{const e=this.__task_aborter;t=e?.signal.aborted?0:1}return t}_generateAsyncTaskId(t,e){if(e||(e=this.__task_aborter),null==t&&(t=0,e))for(;e[t];)t++;return t}$generateAsyncTaskId(t,e){const r=this.super,n=this.self||this;return t=r?r.call(n,t):this._generateAsyncTaskId(t,e)}createAborter(t,e,r=!0){const n=this.hasAsyncFeature($n);if(!n&&r&&this.getRunningTask())throw new E("The task is running",this.name,429);const s=t?.aborter||new vn(this);if(!(s instanceof vn)){if(!(s instanceof AbortController))throw new E("aborter should be an AbortController",this.name,400);Object.setPrototypeOf(s,new vn(this))}if(n){null==this.__task_aborter&&(this.__task_aborter={});const t=this.__task_aborter;null==e&&(e=this.generateAsyncTaskId(e,t)),s.id=e,t[e]=s}else this.__task_aborter=s;const i=t?.timeout;return i>0&&(s.timeoutId=setTimeout((()=>{s.timeoutId=void 0,this.abort("timeout",{timeout:i})}),i)),s.signal.addEventListener("abort",(()=>{const t=s.timeoutId;t&&(s.timeoutId=void 0,clearTimeout(t));const e=s.signal;try{this.emit&&this.emit("aborting",e.reason,e.reason?.data)}finally{s.streamController?.error(e.reason)}})),s}$cleanMultiTaskAborter(t,e){const r=this.super,n=this.self||this;r?r.call(n,t,e):n._cleanMultiTaskAborter(t,e)}cleanTaskAborter(t){if(this.hasAsyncFeature($n)){const e=this.__task_aborter;this.cleanMultiTaskAborter(t.id,e)}else this.__task_aborter=void 0}_cleanMultiTaskAborter(t,e){"number"==typeof t?e[t]=void 0:delete e[t]}createTaskPromise(t,e,r){const n=this.createAborter(e,r?.taskId,r?.raiseError);void 0===e&&(e={}),"object"==typeof e&&(e.aborter=n);let s=t(e,n).then((t=>{if(t&&t instanceof ReadableStream){const e=()=>{this.cleanTaskAborter(n)},r=ze({onStart:t=>{(0,gn.defineProperty)(n,"streamController",t)},onFinal:e,onError:e,onTransform:(t,e)=>(t&&"object"==typeof t&&(t.taskId=n.id),t)});t=t.pipeThrough(r)}else this.cleanTaskAborter(n);return t})).catch((t=>{throw this.cleanTaskAborter(n),t})).finally((()=>{n.timeoutId&&(clearTimeout(n.timeoutId),n.timeoutId=void 0)}));return s.task=n,s}runAsyncCancelableTask(t={},e,r){let n=this.createTaskPromise(e,t,r);const s=this.semaphore;if(s){const t=n,e=t.task;n=s.acquire(e.signal).then((()=>t)).finally((()=>{s.release()})),n.task=e}return n}abort(t,e){let r=this.__task_aborter;if(r){const n=r;if(this.hasAsyncFeature($n)){const t=e?.taskId;if(null==t)throw new E("Missing data.taskId",this.name+".abort",400);r=r[t],this.cleanMultiTaskAborter(t,n)}else this.__task_aborter=void 0;r&&!r.signal.aborted&&r.abort(t,e)}}};xn.prototype.generateAsyncTaskId=function(t,e){return this._generateAsyncTaskId(t,e)},xn.prototype.cleanMultiTaskAborter=function(t,e){return this._cleanMultiTaskAborter(t,e)};var En,Sn=(0,bn.createAbilityInjector)(xn,"abort",{afterInjection:function(t,e){let r=t.prototype._asyncFeatures||0;r|=kn.Cancelable,e&&(e.asyncFeatures&&(r|=e.asyncFeatures),e.maxTaskConcurrency>0&&(t.prototype._maxTaskConcurrency=e.maxTaskConcurrency)),t.prototype._asyncFeatures=r}}),$n=0,kn=((En=kn||{})[En.MultiTask=1<<$n]="MultiTask",En[En.Cancelable=2]="Cancelable",En[En.Priority=4]="Priority",En),On=class t extends p.AdvancePropertyManager{static{this.items={}}static get(t){return this.items[t]}static list(){return this.items}static getByTag(t){let e;for(const r in this.list()){const n=this.get(r);let s=n.tags;if("string"==typeof s){if(s===t){e=n;break}}else if(Array.isArray(s)&&s.indexOf(t)>=0){e=n;break}}return e}static getAllByTag(t){let e=[];for(const r in this.list()){const n=this.get(r);let s=n.tags;"string"==typeof s?s===t&&e.push(n):Array.isArray(s)&&s.indexOf(t)>=0&&e.push(n)}return e}static hasAsyncFeature(t){const e=this.prototype;let r=e.asyncFeatures;return e._asyncFeatures&&(r|=e._asyncFeatures),cn.has(r,t)}static run(t,e){const r=this.get(t);if(r)return r.run(e);throw new $(`${t} to run`,this.name)}static runSync(t,e){const r=this.get(t);if(r)return r.runSync(e);throw new $(`${t} to run`,this.name)}static getFunc(t){const e=this.get(t);return e?.getFunc()}static runWithPos(t,...e){const r=this.get(t);if(r)return r.runWithPos(...e);throw new $(`${t} to run`,this.name)}static runWithPosSync(t,...e){const r=this.get(t);if(r)return r.runWithPosSync(...e);throw new $(`${t} to run`,this.name)}static getFuncWithPos(t){const e=this.get(t);return e?.getFuncWithPos()}static register(e,r={}){switch(typeof e){case"string":r.name=e;break;case"function":r.func=e;break;case"object":r=e}e=r.name;let n=!!this.get(e);if(n)n=!1;else{if(!(r instanceof t))return n=new this(r),n.register();this.items[e]=r,n=r}return n}static unregister(t){const e=this.items[t];return e&&delete this.items[t],e}constructor(t,e={}){switch(super(),typeof t){case"string":e.name=t;break;case"function":e.func=t;break;case"object":e=t}this.name=t=e.name,e.scope&&(this.scope=e.scope),"function"==typeof e.setup&&e.setup.call(this,e),this.initialize(e)}register(){const e=this.constructor,r=this.depends;if(r){const e=Object.keys(r);for(const n of e){const e=r[n];e instanceof t&&e.register()}}return e.register(this)}unregister(){return this.constructor.unregister(this.name)}arr2ObjParams(t){if(this.params&&(t.length>1||Array.isArray(t[0])||t[0]&&"object"!=typeof t[0])){const e={},r=Object.keys(this.params);let n=Math.min(r.length,t.length);for(let s=0;s<n;s++)e[r[s]]=t[s];t=[e]}return t}obj2ArrParams(t){const e=[];if(t&&this.params&&Array.isArray(this.params)){const r=Object.keys(t);let n=Math.min(r.length,this.params.length);for(let s=0;s<n;s++)e.push(t[r[s]])}return e}runSync(t){const e=this.params&&Array.isArray(this.params);if(Array.isArray(t)){if(e)return this.func(...t);T("the function is not support array params, the params must be object!",this.name)}return e?(t=this.obj2ArrParams(t),console.warn('Warning:Use runWithPos() instead of run() for the "'+this.name+'" is function with position params'),this.func(...t)):this.func(t)}run(t){return this.runSync(t)}runAs(t,e){return this.runAsSync(t,e)}runAsSync(t,e){return this.constructor.runSync(t,e)}getFunc(t){return t?this.constructor.getFunc(t):this.runSync.bind(this)}runWithPosSync(...t){return this.params&&!Array.isArray(this.params)&&(t=this.arr2ObjParams(t)),this.func(...t)}runWithPosAsSync(t,...e){return this.constructor.runWithPosSync(t,...e)}runWithPos(...t){return this.runWithPosSync(...t)}runWithPosAs(t,...e){return this.runWithPosAsSync(t,...e)}getFuncWithPos(t){return t?this.constructor.getFuncWithPos(t):this.runWithPosSync.bind(this)}hasAsyncFeature(t){let e=this.asyncFeatures;return this._asyncFeatures&&(e|=this._asyncFeatures),cn.has(e,t)}},An={name:{type:"string"},description:{type:"string"},func:{type:"function",assign(t,e,r,n,s){let i=t;const o=typeof t;return s.isExported?i="function"===o?t.toString():t:t&&("string"!==o&&(t=t.toString()),i=(0,w._createFunction)(t,e.scope)),i}},params:{type:"object"},result:{type:"any"},setup:{type:"function"},depends:{type:"object",exported:!1},tags:{type:["array","string"]},asyncFeatures:{type:"number"}};On.defineProperties(On,An);var Tn=class extends On{constructor(){super(...arguments),this._emitter=new f.EventEmitter,this.description="Return event bus",this.result="event"}get emitter(){return this._emitter}func(){return this.emitter}},jn=new Tn(Ae),Cn=require("secondary-cache");function Nn({key:t,value:e,options:r}={}){return void 0!==t?null===e?this.cache.del(t):void 0!==e?this.cache.set(t,e,r):this.cache.get(t):(r&&this.cache.setDefaultOptions(r),this.cache)}function Fn(t,e){let r=On.get(t);return r||(r=new On(t,{func:Nn,description:"get/set LRU cache or return the LRUCache object",params:{key:{name:"key",type:"string",description:"the key is undefined means change the default cache options"},value:{name:"value",type:"any",description:"the value to store, if value is null means remove the key"},options:{name:"options",type:"object|number",description:"the optional cache options:{capacity,expires,cleanInterval} or expires"}},result:"any"}),r.cache=new Cn.Cache(e)),r}var In=Fn("lrucache"),Mn=class t extends On{static get apiRoot(){return t._apiRoot}static setApiRoot(e){t._apiRoot=e}static async loadFrom(){if(this._apiRoot){const t=await fetch(this._apiRoot,{headers:{"Content-Type":"application/json"}}),e=await t.json();e&&this.loadFromSync(e)}else T("missing apiRoot to load tools","ClientTools")}static loadFromSync(e){for(const r in e){const n=this.get(r),s=e[r];n?n instanceof t?n.assign(s):T(`${r} already registered as ${n.constructor.name}`,"ClientTools"):this.register(s)}}static async fetch(t,e){const r=this.get(t);if(r&&r.fetch)return r.fetch(e)}getUrlParams(t){if(void 0!==t){const e=JSON.stringify(t);if("{}"!==e&&"[]"!==e&&'""'!==e)return"?p="+encodeURIComponent(e)}return""}async fetch(t,e,r){const n={...this.fetchOptions};let s;n.headers&&n.headers["Content-Type"]||(n.headers={"Content-Type":"application/json",...n.headers}),t?.stream&&!n.headers.Connection&&(n.headers.Connection="keep-alive"),e||(e=this.action||"post"),"res"===e&&(e="get"),r?("string"!=typeof r&&(r=JSON.stringify(r)),r=this.name+"/"+r):r=this.name,n.method=e.toUpperCase(),"get"===e||"delete"===e?s=r+this.getUrlParams(t):(n.body=JSON.stringify(t),s=r);const i=await fetch(`${this.apiRoot}/${s}`,n);if(!i.ok){throw await this.errorFrom(i)}return i}async errorFrom(t){let e,r=t.status,n=t.statusText,s=this.name;if(t.body){const r=await t.text();try{const t=JSON.parse(r);t&&(t.error&&(n=t.error),t.name&&(s=t.name),t.data&&(e=t.data,e.name=s,e.what&&(e.msg=n,n=e.what)),t.message&&(n=n+":"+t.message))}catch(t){console.warn("🚀 ~ parse error body to json:",t)}}return A(n,s,r)}async func(t){const e=await this.fetch(t);if(t?.stream)return e;return await e.json()}},Rn={...I};Mn.defineProperties(Mn,Rn);var Pn=class extends Mn{async fetch(t,e){if(t||(t={}),e&&"res"===this.action){if("get"===e||"delete"===e){let r=t.id;return r||T("id is required"),"string"==typeof r&&(r=encodeURIComponent(r)),delete t.id,super.fetch(t,e,r)}"list"===e?e="get":e.startsWith("$")&&(t.act=e,e="post")}return await super.fetch(t,e)}async _func(t,e){const r=await this.fetch(e,t);if(e?.stream)return r;return await r.json()}async func(t){const e=t.action;return e&&delete t.action,this._func(e,t)}assignMethods(t){if(Array.isArray(t))for(const e of t){const t=e.startsWith("$")?e.slice(1):e;this[t]||(this[t]=(t=>this._func.bind(this,t))(e))}}},qn={methods:{type:"array",assign(t,e,r,n,s){s?.isExported||e.assignMethods(t)}}};Pn.defineProperties(Pn,qn);var Bn=class extends Pn{constructor(){super(...arguments),this._sseEvents={},this._forwardEvents=new Set,this.name=Oe,this.description="subscribe server sent event",this.ebListener=async function(...t){const e=this.type;this.target.publish&&await this.target.publish({data:t,event:e})}}get evtSource(){let t=this._es;return t&&t.readyState!==EventSource.CLOSED||(t=this.initEventSource(this._esEvents)),t}get active(){return!!this._es&&this._es.readyState!==EventSource.CLOSED}set active(t){t!==this.active&&(t?this.initEventSource(this._esEvents):this._es&&(this._es.close(),this._es=void 0))}initEventSource(t){if("string"==typeof t&&(t=[t]),this._es&&this._es.readyState!==EventSource.CLOSED){if(!this._esEvents||t&&t.every((t=>this._esEvents.includes(t))))return this._es;this._es.close()}const e=t?this.getUrlParams({event:t}):"",r=`${this.apiRoot}/${this.name}${e}`,n=this._es=new EventSource(r);return Object.entries(this._sseEvents).forEach((([t,e])=>{n.addEventListener(t,e)})),this._esEvents=t,n}esListener(t){const e=t.data?JSON.parse(t.data):void 0,r=t.type;if(!this._forwardEvents.has(r)){const t=this.emitter;t&&e&&r&&(Array.isArray(e)?t.emit(r,...e):t.emit(r,e))}}async subscribe(t){const e=await this.sub({event:t});"string"==typeof t&&(t=[t]);const r=this.evtSource;for(const e of t)if(!this._sseEvents[e]){const t=this._sseEvents[e]=this.esListener.bind(this);r.addEventListener(e,t)}return e}async unsubscribe(t){const e=await this.unsub({event:t});"string"==typeof t&&(t=[t]);for(const e of t){const t=this._sseEvents[e];t&&(delete this._sseEvents[e],this.evtSource.removeEventListener(e,t))}return e}forwardEvent(t){"string"==typeof t&&(t=[t]);for(const e of t)this._forwardEvents.has(e)||(this._forwardEvents.add(e),this.on&&this.on(e,this.ebListener))}unforwardEvent(t){"string"==typeof t&&(t=[t]);for(const e of t)this._forwardEvents.has(e)&&(this._forwardEvents.delete(e),this.off&&this.off(e,this.ebListener))}async init(t){if(this.active=!1,this.initEventSource(t),t)return await this.subscribe(t)}},Un=new Bn(Oe),Vn=require("util-ex"),_n=class t extends On{static get apiRoot(){return t._apiRoot}static setApiRoot(e){t._apiRoot=e}static toJSON(){const e={};for(const r in this.items){let n=this.items[r];n instanceof t&&(n.allowExportFunc||(n=n.toJSON(),delete n.func),e[r]=n)}return e}isStream(t){return this.stream}func({}){}},Ln={...I};_n.defineProperties(_n,Ln);var zn=class extends _n{constructor(t,e={}){super(t,e),this.action="res",this.params={id:{type:"string"},val:{type:"any"}};const r=this.methods=[];for(const t of F)"function"==typeof this[t]&&r.push(t);(0,Vn.getAllNames)(Object.getPrototypeOf(this)).filter((t=>t.startsWith("$")&&"function"==typeof this[t])).forEach((t=>{r.push(t);const e=t.slice(1);void 0===this[e]&&(this[e]=this[t])}))}cast(t,e){let r=this.params[t];return r&&("string"!=typeof r&&(r=r.type),"number"===r&&(e=Number(e))),e}getMethodFromParams(t){let e=t?._req?.method?.toLowerCase();return"get"===e&&void 0===t.id&&(e="list"),"post"===e&&t.act&&(e=t.act),e}func(t){const e=this.getMethodFromParams(t);if(e&&"function"==typeof this[e])return void 0!==t.id&&(t.id=this.cast("id",t.id)),this[e](t);throw new $(e,this.name)}};zn.defineProperties(zn,{methods:{type:"array"}});var Jn=jn.runSync(),Dn=class t extends zn{constructor(){super(...arguments),this.name=Oe,this.description="subscribe server sent event",this.result="event",this.depends={[Ae]:jn}}static get sse(){return this._sse||(this._sse=new Ne),this._sse}get sse(){return this.constructor.sse}static publish(e,r){return t.sse.publish(e,r)}static{this.ebListener=function(...e){t.sse.publish(e,this.type)}}static subscribe(e,r,n){return t.sse.subscribe(e,r,n)}static alreadyForward(e){const r=Jn.listeners(e);for(const e of r)if(e===t.ebListener)return!0}publishSSE(t,e){return this.constructor.publish(t,e)}subscribeSSE(t,e,r){return"string"==typeof r&&(r=[r]),this.constructor.subscribe(t,e,r)}forward(e){Array.isArray(e)||(e=[e]);for(const r of e)t.alreadyForward(r)||Jn.on(r,t.ebListener)}unforward(e){"string"==typeof e&&(e=[e]);for(const r of e)Jn.off(r,t.ebListener)}list({_req:t,_res:e,event:r}){t&&e&&this.subscribeSSE(t,e,r)}$sub({event:t}){if(t)return this.forward(t),{event:t};T("event is required","sub",400)}$unsub({event:t}){if(t)return this.unforward(t),{event:t};T("event is required","unsub",400)}$publish({event:t,data:e}){if(t&&e){"string"==typeof t&&(t=[t]);for(const r of t)this.publishSSE(e,r);return{event:t}}T("event or data is required","pub",400)}isStream(t){return"list"===this.getMethodFromParams(t)}},Wn=new Dn(Oe);function Hn(){jn.register(),In.register()}
package/dist/funcs.mjs CHANGED
@@ -1 +1 @@
1
- import{EventClient as m,EventServer as o,EventToolFunc as r,_lrucache as p,createLRUCache as t,event as D,eventClient as Y,eventServer as c,lrucache as h,registerCoreTools as i}from"./chunk-PYM7DCYB.mjs";import"./chunk-U5DDQYSF.mjs";export{m as EventClient,o as EventServer,r as EventToolFunc,p as _lrucache,t as createLRUCache,D as event,Y as eventClient,c as eventServer,h as lrucache,i as registerCoreTools};
1
+ import{EventClient as m,EventServer as o,EventToolFunc as r,_lrucache as p,createLRUCache as t,event as D,eventClient as c,eventServer as h,lrucache as i,registerCoreTools as j}from"./chunk-PDXMSKQH.mjs";import"./chunk-U5DDQYSF.mjs";export{m as EventClient,o as EventServer,r as EventToolFunc,p as _lrucache,t as createLRUCache,D as event,c as eventClient,h as eventServer,i as lrucache,j as registerCoreTools};
@@ -4,12 +4,26 @@ import { ICacheOptions, Cache } from 'secondary-cache';
4
4
  import { AbstractError } from 'abstract-error';
5
5
  import { IncomingMessage, ServerResponse } from 'http';
6
6
 
7
+ declare const ToolAsyncMultiTaskBit = 0;
8
+ declare const ToolAsyncCancelableBit = 1;
9
+ declare const ToolAsyncPriorityBit = 2;
10
+ declare enum AsyncFeatureBits {
11
+ MultiTask = 0,
12
+ Cancelable = 1,
13
+ Priority = 2
14
+ }
15
+ declare enum AsyncFeatures {
16
+ MultiTask = 1,// B0001
17
+ Cancelable = 2,// B010
18
+ Priority = 4
19
+ }
7
20
  type FuncParamType = string;
8
21
  interface FuncParam {
9
22
  name?: string;
10
23
  type?: FuncParamType;
11
24
  required?: boolean;
12
25
  description?: string;
26
+ asyncFeatures?: number;
13
27
  depends?: {
14
28
  [name: string]: ToolFunc;
15
29
  };
@@ -35,6 +49,11 @@ interface BaseFunc extends BaseFuncItem {
35
49
  interface Funcs {
36
50
  [name: string]: ToolFunc;
37
51
  }
52
+ interface ToolFuncPackage {
53
+ name: string;
54
+ register: (data?: any) => void;
55
+ unregister?: () => void;
56
+ }
38
57
  declare interface ToolFunc extends BaseFunc {
39
58
  [name: string]: any;
40
59
  }
@@ -45,6 +64,7 @@ declare class ToolFunc extends AdvancePropertyManager {
45
64
  static list(): Funcs;
46
65
  static getByTag(tagName: string): ToolFunc | undefined;
47
66
  static getAllByTag(tagName: string): ToolFunc[];
67
+ static hasAsyncFeature(feature: AsyncFeatureBits): boolean;
48
68
  static run(name: string, params?: any): Promise<any>;
49
69
  static runSync(name: string, params?: any): any;
50
70
  static getFunc(name: string): any;
@@ -70,6 +90,7 @@ declare class ToolFunc extends AdvancePropertyManager {
70
90
  runWithPos(...params: any[]): Promise<any>;
71
91
  runWithPosAs(name: string, ...params: any[]): Promise<any>;
72
92
  getFuncWithPos(name?: string): any;
93
+ hasAsyncFeature(feature: AsyncFeatureBits): boolean;
73
94
  }
74
95
  declare const ToolFuncSchema: {
75
96
  name: {
@@ -98,6 +119,9 @@ declare const ToolFuncSchema: {
98
119
  tags: {
99
120
  type: string[];
100
121
  };
122
+ asyncFeatures: {
123
+ type: string;
124
+ };
101
125
  };
102
126
 
103
127
  declare const PASSING_SCORE = 0.618;
@@ -136,6 +160,7 @@ interface RemoteFuncItem extends BaseFuncItem {
136
160
  type ErrorCodeType = number | string;
137
161
  declare enum ErrorCode {
138
162
  OK = 200,
163
+ Accepted = 202,
139
164
  BadRequest = 400,
140
165
  InvalidArgument = 400,
141
166
  Unauthorized = 401,
@@ -147,12 +172,13 @@ declare enum ErrorCode {
147
172
  RequestTimeout = 408,
148
173
  Conflict = 409,
149
174
  Corruption = 409,
175
+ TooManyRequests = 429,
150
176
  Aborted = 499,
151
177
  InternalError = 500,
152
178
  NotImplemented = 501,
153
179
  NotSupported = 501,
154
180
  BadGateway = 502,
155
- ServiceUnavailable = 503,
181
+ ServiceUnavailable = 503,// task is processing and Retry-After
156
182
  GatewayTimeout = 504
157
183
  }
158
184
  declare const InternalErrorCode = ErrorCode.InternalError;
@@ -592,4 +618,4 @@ declare const eventServer: EventServer;
592
618
 
593
619
  declare function registerCoreTools(): void;
594
620
 
595
- export { eventServer as $, type AIModelNameRules as A, BaseError as B, CommonError as C, ClientToolFuncSchema as D, type ErrorCodeType as E, type FuncParamType as F, type ServerFuncParams as G, type ServerFuncItem as H, InternalErrorCode as I, ServerTools as J, ServerToolFuncSchema as K, registerCoreTools as L, EventToolFunc as M, NotImplementedErrorCode as N, event as O, PASSING_SCORE as P, createLRUCache as Q, RemoteToolFuncSchema as R, SSEChannelAlreadyClosedErrCode as S, type TFunc as T, lrucache as U, type EventClientFuncParams as V, EventClient as W, eventClient as X, type EventServerFuncParams as Y, EventServer as Z, _lrucache as _, ActionNames as a, type ResClientFuncParams as a0, ResClientTools as a1, ResClientToolsSchema as a2, type ResServerFuncParams as a3, ResServerTools as a4, ResServerToolsSchema as a5, type ActionName as b, type AIModelNameRuleFn as c, type AIModelNameRule as d, type RemoteFuncItem as e, ErrorCode as f, NotFoundErrorCode as g, AlreadyExistsErrorCode as h, AbortErrorCode as i, NotImplementationError as j, NotFoundError as k, AlreadyExistsError as l, AbortError as m, createError as n, SSEChannel as o, type FuncParam as p, type FuncParams as q, type BaseFuncItem as r, type FuncItem as s, throwError as t, type BaseFunc as u, type Funcs as v, ToolFunc as w, ToolFuncSchema as x, type ClientFuncItem as y, ClientTools as z };
621
+ export { lrucache as $, AsyncFeatures as A, BaseError as B, CommonError as C, type BaseFunc as D, type ErrorCodeType as E, type FuncParamType as F, type Funcs as G, type ToolFuncPackage as H, InternalErrorCode as I, ToolFuncSchema as J, type ClientFuncItem as K, ClientTools as L, ClientToolFuncSchema as M, NotImplementedErrorCode as N, type ServerFuncParams as O, PASSING_SCORE as P, type ServerFuncItem as Q, RemoteToolFuncSchema as R, SSEChannelAlreadyClosedErrCode as S, ToolFunc as T, ServerTools as U, ServerToolFuncSchema as V, registerCoreTools as W, EventToolFunc as X, event as Y, createLRUCache as Z, _lrucache as _, type AIModelNameRules as a, type EventClientFuncParams as a0, EventClient as a1, eventClient as a2, type EventServerFuncParams as a3, EventServer as a4, eventServer as a5, type ResClientFuncParams as a6, ResClientTools as a7, ResClientToolsSchema as a8, type ResServerFuncParams as a9, ResServerTools as aa, ResServerToolsSchema as ab, ActionNames as b, type ActionName as c, type AIModelNameRuleFn as d, type AIModelNameRule as e, type RemoteFuncItem as f, ErrorCode as g, NotFoundErrorCode as h, AlreadyExistsErrorCode as i, AbortErrorCode as j, NotImplementationError as k, NotFoundError as l, AlreadyExistsError as m, AbortError as n, createError as o, SSEChannel as p, ToolAsyncMultiTaskBit as q, ToolAsyncCancelableBit as r, ToolAsyncPriorityBit as s, throwError as t, AsyncFeatureBits as u, type FuncParam as v, type FuncParams as w, type TFunc as x, type BaseFuncItem as y, type FuncItem as z };
@@ -4,12 +4,26 @@ import { ICacheOptions, Cache } from 'secondary-cache';
4
4
  import { AbstractError } from 'abstract-error';
5
5
  import { IncomingMessage, ServerResponse } from 'http';
6
6
 
7
+ declare const ToolAsyncMultiTaskBit = 0;
8
+ declare const ToolAsyncCancelableBit = 1;
9
+ declare const ToolAsyncPriorityBit = 2;
10
+ declare enum AsyncFeatureBits {
11
+ MultiTask = 0,
12
+ Cancelable = 1,
13
+ Priority = 2
14
+ }
15
+ declare enum AsyncFeatures {
16
+ MultiTask = 1,// B0001
17
+ Cancelable = 2,// B010
18
+ Priority = 4
19
+ }
7
20
  type FuncParamType = string;
8
21
  interface FuncParam {
9
22
  name?: string;
10
23
  type?: FuncParamType;
11
24
  required?: boolean;
12
25
  description?: string;
26
+ asyncFeatures?: number;
13
27
  depends?: {
14
28
  [name: string]: ToolFunc;
15
29
  };
@@ -35,6 +49,11 @@ interface BaseFunc extends BaseFuncItem {
35
49
  interface Funcs {
36
50
  [name: string]: ToolFunc;
37
51
  }
52
+ interface ToolFuncPackage {
53
+ name: string;
54
+ register: (data?: any) => void;
55
+ unregister?: () => void;
56
+ }
38
57
  declare interface ToolFunc extends BaseFunc {
39
58
  [name: string]: any;
40
59
  }
@@ -45,6 +64,7 @@ declare class ToolFunc extends AdvancePropertyManager {
45
64
  static list(): Funcs;
46
65
  static getByTag(tagName: string): ToolFunc | undefined;
47
66
  static getAllByTag(tagName: string): ToolFunc[];
67
+ static hasAsyncFeature(feature: AsyncFeatureBits): boolean;
48
68
  static run(name: string, params?: any): Promise<any>;
49
69
  static runSync(name: string, params?: any): any;
50
70
  static getFunc(name: string): any;
@@ -70,6 +90,7 @@ declare class ToolFunc extends AdvancePropertyManager {
70
90
  runWithPos(...params: any[]): Promise<any>;
71
91
  runWithPosAs(name: string, ...params: any[]): Promise<any>;
72
92
  getFuncWithPos(name?: string): any;
93
+ hasAsyncFeature(feature: AsyncFeatureBits): boolean;
73
94
  }
74
95
  declare const ToolFuncSchema: {
75
96
  name: {
@@ -98,6 +119,9 @@ declare const ToolFuncSchema: {
98
119
  tags: {
99
120
  type: string[];
100
121
  };
122
+ asyncFeatures: {
123
+ type: string;
124
+ };
101
125
  };
102
126
 
103
127
  declare const PASSING_SCORE = 0.618;
@@ -136,6 +160,7 @@ interface RemoteFuncItem extends BaseFuncItem {
136
160
  type ErrorCodeType = number | string;
137
161
  declare enum ErrorCode {
138
162
  OK = 200,
163
+ Accepted = 202,
139
164
  BadRequest = 400,
140
165
  InvalidArgument = 400,
141
166
  Unauthorized = 401,
@@ -147,12 +172,13 @@ declare enum ErrorCode {
147
172
  RequestTimeout = 408,
148
173
  Conflict = 409,
149
174
  Corruption = 409,
175
+ TooManyRequests = 429,
150
176
  Aborted = 499,
151
177
  InternalError = 500,
152
178
  NotImplemented = 501,
153
179
  NotSupported = 501,
154
180
  BadGateway = 502,
155
- ServiceUnavailable = 503,
181
+ ServiceUnavailable = 503,// task is processing and Retry-After
156
182
  GatewayTimeout = 504
157
183
  }
158
184
  declare const InternalErrorCode = ErrorCode.InternalError;
@@ -592,4 +618,4 @@ declare const eventServer: EventServer;
592
618
 
593
619
  declare function registerCoreTools(): void;
594
620
 
595
- export { eventServer as $, type AIModelNameRules as A, BaseError as B, CommonError as C, ClientToolFuncSchema as D, type ErrorCodeType as E, type FuncParamType as F, type ServerFuncParams as G, type ServerFuncItem as H, InternalErrorCode as I, ServerTools as J, ServerToolFuncSchema as K, registerCoreTools as L, EventToolFunc as M, NotImplementedErrorCode as N, event as O, PASSING_SCORE as P, createLRUCache as Q, RemoteToolFuncSchema as R, SSEChannelAlreadyClosedErrCode as S, type TFunc as T, lrucache as U, type EventClientFuncParams as V, EventClient as W, eventClient as X, type EventServerFuncParams as Y, EventServer as Z, _lrucache as _, ActionNames as a, type ResClientFuncParams as a0, ResClientTools as a1, ResClientToolsSchema as a2, type ResServerFuncParams as a3, ResServerTools as a4, ResServerToolsSchema as a5, type ActionName as b, type AIModelNameRuleFn as c, type AIModelNameRule as d, type RemoteFuncItem as e, ErrorCode as f, NotFoundErrorCode as g, AlreadyExistsErrorCode as h, AbortErrorCode as i, NotImplementationError as j, NotFoundError as k, AlreadyExistsError as l, AbortError as m, createError as n, SSEChannel as o, type FuncParam as p, type FuncParams as q, type BaseFuncItem as r, type FuncItem as s, throwError as t, type BaseFunc as u, type Funcs as v, ToolFunc as w, ToolFuncSchema as x, type ClientFuncItem as y, ClientTools as z };
621
+ export { lrucache as $, AsyncFeatures as A, BaseError as B, CommonError as C, type BaseFunc as D, type ErrorCodeType as E, type FuncParamType as F, type Funcs as G, type ToolFuncPackage as H, InternalErrorCode as I, ToolFuncSchema as J, type ClientFuncItem as K, ClientTools as L, ClientToolFuncSchema as M, NotImplementedErrorCode as N, type ServerFuncParams as O, PASSING_SCORE as P, type ServerFuncItem as Q, RemoteToolFuncSchema as R, SSEChannelAlreadyClosedErrCode as S, ToolFunc as T, ServerTools as U, ServerToolFuncSchema as V, registerCoreTools as W, EventToolFunc as X, event as Y, createLRUCache as Z, _lrucache as _, type AIModelNameRules as a, type EventClientFuncParams as a0, EventClient as a1, eventClient as a2, type EventServerFuncParams as a3, EventServer as a4, eventServer as a5, type ResClientFuncParams as a6, ResClientTools as a7, ResClientToolsSchema as a8, type ResServerFuncParams as a9, ResServerTools as aa, ResServerToolsSchema as ab, ActionNames as b, type ActionName as c, type AIModelNameRuleFn as d, type AIModelNameRule as e, type RemoteFuncItem as f, ErrorCode as g, NotFoundErrorCode as h, AlreadyExistsErrorCode as i, AbortErrorCode as j, NotImplementationError as k, NotFoundError as l, AlreadyExistsError as m, AbortError as n, createError as o, SSEChannel as p, ToolAsyncMultiTaskBit as q, ToolAsyncCancelableBit as r, ToolAsyncPriorityBit as s, throwError as t, AsyncFeatureBits as u, type FuncParam as v, type FuncParams as w, type TFunc as x, type BaseFuncItem as y, type FuncItem as z };