@isdk/ai-tool 0.5.7 → 0.6.0

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 (292) hide show
  1. package/dist/chunk-OYDBRUZJ.mjs +1 -0
  2. package/dist/funcs.js +1 -1
  3. package/dist/funcs.mjs +1 -1
  4. package/dist/index.d.mts +11 -637
  5. package/dist/index.d.ts +11 -637
  6. package/dist/index.js +1 -1
  7. package/dist/index.mjs +1 -1
  8. package/docs/classes/BinarySemaphore.md +25 -25
  9. package/docs/classes/CancelableAbility.md +25 -25
  10. package/docs/classes/ClientTools.md +57 -57
  11. package/docs/classes/ConfigFile.md +78 -262
  12. package/docs/classes/EnvPromptTemplate.md +233 -36
  13. package/docs/classes/EventClient.md +80 -80
  14. package/docs/classes/EventServer.md +81 -81
  15. package/docs/classes/EventToolFunc.md +49 -49
  16. package/docs/classes/FStringPromptTemplate.md +234 -37
  17. package/docs/classes/FewShotPromptTemplate.md +213 -34
  18. package/docs/classes/GolangPromptTemplate.md +230 -33
  19. package/docs/classes/IntSet.md +12 -12
  20. package/docs/classes/PromptExampleSelector.md +9 -9
  21. package/docs/classes/PromptTemplate.md +230 -34
  22. package/docs/classes/ReadableStreamError.md +2 -2
  23. package/docs/classes/ResClientTools.md +64 -64
  24. package/docs/classes/ResServerTools.md +65 -65
  25. package/docs/classes/SSEChannel.md +16 -16
  26. package/docs/classes/Semaphore.md +26 -26
  27. package/docs/classes/ServerTools.md +53 -53
  28. package/docs/classes/SignalGate.md +9 -9
  29. package/docs/classes/TaskAbortController.md +8 -8
  30. package/docs/classes/ToolFunc.md +46 -46
  31. package/docs/classes/YamlTypeBaseObject.md +2 -2
  32. package/docs/enumerations/AsyncFeatureBits.md +4 -4
  33. package/docs/enumerations/AsyncFeatures.md +4 -4
  34. package/docs/enumerations/HashAlgorithm.md +12 -12
  35. package/docs/functions/AIArgProcessor.md +1 -1
  36. package/docs/functions/AIStream.md +1 -1
  37. package/docs/functions/ChoiceArgProcessor.md +1 -1
  38. package/docs/functions/ObjectArgsToArgsInfo.md +1 -1
  39. package/docs/functions/RateLimit.md +1 -1
  40. package/docs/functions/TemplateArgProcessor.md +1 -1
  41. package/docs/functions/assignDirs.md +1 -1
  42. package/docs/functions/backendEventable.md +1 -1
  43. package/docs/functions/beforeShutdown.md +1 -1
  44. package/docs/functions/completeSentences.md +1 -1
  45. package/docs/functions/concatText.md +1 -1
  46. package/docs/functions/countLLMTokens.md +1 -1
  47. package/docs/functions/countRegexMatches.md +1 -1
  48. package/docs/functions/createCallbacksTransformer.md +1 -1
  49. package/docs/functions/createEmptyReadableStream.md +1 -1
  50. package/docs/functions/createEndWithRepetitionDetector.md +1 -1
  51. package/docs/functions/createEventStreamTransformer.md +1 -1
  52. package/docs/functions/createHfValueFunc.md +1 -1
  53. package/docs/functions/createLRUCache.md +1 -1
  54. package/docs/functions/createYamlObjectTag.md +1 -1
  55. package/docs/functions/dateToText.md +1 -1
  56. package/docs/functions/decodeCharset.md +1 -1
  57. package/docs/functions/detectCharset.md +1 -1
  58. package/docs/functions/encodeLLMTokens.md +1 -1
  59. package/docs/functions/ensureQuoted.md +1 -1
  60. package/docs/functions/expandConfig.md +3 -3
  61. package/docs/functions/expandEnv.md +4 -4
  62. package/docs/functions/expandObjEnv.md +4 -4
  63. package/docs/functions/expandPath.md +1 -1
  64. package/docs/functions/extNameLevel.md +1 -1
  65. package/docs/functions/fileIsExists.md +1 -1
  66. package/docs/functions/filterValidFnScope.md +1 -1
  67. package/docs/functions/findIndexNonEmptyFrom.md +1 -1
  68. package/docs/functions/findPort.md +1 -1
  69. package/docs/functions/formatTextWithSpace.md +1 -1
  70. package/docs/functions/getAllEnumKeys.md +1 -1
  71. package/docs/functions/getConfigFileNames.md +1 -1
  72. package/docs/functions/getConfigs.md +1 -1
  73. package/docs/functions/getEnvVairables.md +1 -1
  74. package/docs/functions/getFileMetaInfo.md +1 -1
  75. package/docs/functions/getHashAlgoBySize.md +1 -1
  76. package/docs/functions/getKeysPath.md +1 -1
  77. package/docs/functions/getLLMTokenizer.md +1 -1
  78. package/docs/functions/getMultiLevelExtname.md +4 -4
  79. package/docs/functions/getPackageDir.md +1 -1
  80. package/docs/functions/getRealFilepath.md +1 -1
  81. package/docs/functions/getResponseErrorReadableStream.md +1 -1
  82. package/docs/functions/getXDGConfigs.md +1 -1
  83. package/docs/functions/hasDirectoryIn.md +1 -1
  84. package/docs/functions/hash.md +1 -1
  85. package/docs/functions/hashFile.md +1 -1
  86. package/docs/functions/hashStream.md +1 -1
  87. package/docs/functions/initShutdown.md +1 -1
  88. package/docs/functions/isLangUsingSpaces.md +1 -1
  89. package/docs/functions/isListItemString.md +1 -1
  90. package/docs/functions/isModelNameMatched.md +1 -1
  91. package/docs/functions/isPunctuationChar.md +1 -1
  92. package/docs/functions/isQuoted.md +1 -1
  93. package/docs/functions/isRegExp.md +1 -1
  94. package/docs/functions/isSameString.md +1 -1
  95. package/docs/functions/isSectionString.md +1 -1
  96. package/docs/functions/isSentenceEnding.md +1 -1
  97. package/docs/functions/isSepLineString.md +1 -1
  98. package/docs/functions/isStrWrapped.md +1 -1
  99. package/docs/functions/isSubdirectory.md +1 -1
  100. package/docs/functions/isTitleString.md +1 -1
  101. package/docs/functions/isValidFilename.md +1 -1
  102. package/docs/functions/isValidFilepath.md +1 -1
  103. package/docs/functions/isWebStream.md +1 -1
  104. package/docs/functions/jsonFilterToWhere.md +1 -1
  105. package/docs/functions/jsonToMarkdownStr.md +1 -1
  106. package/docs/functions/loadAIConfig.md +1 -1
  107. package/docs/functions/loadConfig.md +1 -1
  108. package/docs/functions/loadConfigFile.md +1 -1
  109. package/docs/functions/loadFileFromPaths.md +1 -1
  110. package/docs/functions/loadTextFromPaths.md +1 -1
  111. package/docs/functions/lrucache.md +1 -1
  112. package/docs/functions/makeToolFuncCancelable.md +1 -1
  113. package/docs/functions/matchUrlProtocol.md +1 -1
  114. package/docs/functions/memoize.md +1 -1
  115. package/docs/functions/messagesToText.md +1 -1
  116. package/docs/functions/paramsSizeToScaleStr.md +1 -1
  117. package/docs/functions/parseCommand.md +1 -1
  118. package/docs/functions/parseJsJson.md +1 -1
  119. package/docs/functions/parseJsJsonSimpleSync.md +1 -1
  120. package/docs/functions/parseObjectArgInfo.md +1 -1
  121. package/docs/functions/parseObjectArgumentInfos.md +1 -1
  122. package/docs/functions/parseObjectArguments.md +1 -1
  123. package/docs/functions/parseObjectArgumentsAsArgInfos.md +1 -1
  124. package/docs/functions/parseYaml.md +21 -1
  125. package/docs/functions/quoteStr.md +1 -1
  126. package/docs/functions/readFilenamesRecursiveSync.md +7 -1
  127. package/docs/functions/readTextFileChunks.md +1 -1
  128. package/docs/functions/readTextFileChunksEx.md +1 -1
  129. package/docs/functions/readableFromAsyncIterable.md +1 -1
  130. package/docs/functions/registerCoreTools.md +1 -1
  131. package/docs/functions/registerYamlTag.md +18 -2
  132. package/docs/functions/removeMarkdownBold.md +1 -1
  133. package/docs/functions/removeMarkdownBoldAndItalic.md +1 -1
  134. package/docs/functions/removeMarkdownItalic.md +1 -1
  135. package/docs/functions/replaceWithPlaceholder.md +1 -1
  136. package/docs/functions/restoreFromPlacehoders.md +1 -1
  137. package/docs/functions/sanitizeFilename.md +4 -4
  138. package/docs/functions/sanitizeFilepath.md +4 -4
  139. package/docs/functions/saveConfigFile.md +1 -1
  140. package/docs/functions/scaleStrToParamsSize.md +1 -1
  141. package/docs/functions/shutdown.md +1 -1
  142. package/docs/functions/simplifyObjectArguments.md +1 -1
  143. package/docs/functions/sortedValues.md +1 -1
  144. package/docs/functions/splitChunks.md +1 -1
  145. package/docs/functions/splitParagraph.md +1 -1
  146. package/docs/functions/splitSentence.md +1 -1
  147. package/docs/functions/stringifyYaml.md +21 -1
  148. package/docs/functions/stripConsoleColor.md +1 -1
  149. package/docs/functions/textToDate.md +1 -1
  150. package/docs/functions/toDateTime.md +1 -1
  151. package/docs/functions/trimStartOfStreamHelper.md +1 -1
  152. package/docs/functions/truncTo.md +1 -1
  153. package/docs/functions/truncateByToken.md +1 -1
  154. package/docs/functions/truncateToTokenLimit.md +1 -1
  155. package/docs/functions/truncateToTokenLimitEx.md +1 -1
  156. package/docs/functions/uuid.md +1 -1
  157. package/docs/functions/wait.md +1 -1
  158. package/docs/functions/xxhash.md +1 -1
  159. package/docs/functions/xxhash32.md +1 -1
  160. package/docs/functions/xxhash64.md +1 -1
  161. package/docs/functions/xxhashAsStr.md +1 -1
  162. package/docs/globals.md +0 -23
  163. package/docs/interfaces/AIChatAssistantMessageParam.md +12 -12
  164. package/docs/interfaces/AIChatContentPartImage.md +3 -3
  165. package/docs/interfaces/AIChatContentPartText.md +3 -3
  166. package/docs/interfaces/AIChatMessageParamBase.md +7 -7
  167. package/docs/interfaces/AIChatMessageToolCall.md +4 -4
  168. package/docs/interfaces/AIChatSystemMessageParam.md +9 -9
  169. package/docs/interfaces/AIChatToolChoiceFuncObject.md +3 -3
  170. package/docs/interfaces/AIChatToolChoiceObject.md +2 -2
  171. package/docs/interfaces/AIChatToolFunc.md +5 -5
  172. package/docs/interfaces/AIChatToolFuncParam.md +3 -3
  173. package/docs/interfaces/AIChatToolMessageParam.md +10 -10
  174. package/docs/interfaces/AIChatToolParam.md +2 -2
  175. package/docs/interfaces/AIChatToolTypeObject.md +2 -2
  176. package/docs/interfaces/AIChatUserMessageParam.md +13 -13
  177. package/docs/interfaces/AIChoiceConfig.md +8 -8
  178. package/docs/interfaces/AIResult.md +6 -6
  179. package/docs/interfaces/AIStreamParser.md +2 -2
  180. package/docs/interfaces/AIStreamParserOptions.md +2 -2
  181. package/docs/interfaces/BaseFunc.md +11 -11
  182. package/docs/interfaces/BaseFuncItem.md +10 -10
  183. package/docs/interfaces/BinarySemaphoreAcquireOptions.md +2 -2
  184. package/docs/interfaces/BinarySemaphoreOptions.md +5 -5
  185. package/docs/interfaces/BinarySemaphoreReleaseOptions.md +2 -2
  186. package/docs/interfaces/BinarySemaphoreReleaserFunc.md +3 -3
  187. package/docs/interfaces/CancelableAbilityOptions.md +4 -4
  188. package/docs/interfaces/ClientFuncItem.md +13 -13
  189. package/docs/interfaces/EventClientFuncParams.md +5 -5
  190. package/docs/interfaces/EventServerFuncParams.md +6 -6
  191. package/docs/interfaces/FewShotPromptTemplateOptions.md +12 -12
  192. package/docs/interfaces/FuncItem.md +11 -11
  193. package/docs/interfaces/FuncParam.md +7 -7
  194. package/docs/interfaces/FuncParams.md +1 -1
  195. package/docs/interfaces/Funcs.md +1 -1
  196. package/docs/interfaces/HashAlgoParams.md +4 -4
  197. package/docs/interfaces/IFileMetaInfo.md +8 -8
  198. package/docs/interfaces/IReadTextFileChunksOptions.md +11 -11
  199. package/docs/interfaces/ITruncateToTokenLimitOptions.md +10 -10
  200. package/docs/interfaces/JsonFilter.md +1 -1
  201. package/docs/interfaces/ParseObjectArgumentOptions.md +11 -11
  202. package/docs/interfaces/PromptExampleSelectorOptions.md +3 -3
  203. package/docs/interfaces/PromptTemplateOptions.md +7 -7
  204. package/docs/interfaces/RemoteFuncItem.md +13 -13
  205. package/docs/interfaces/ReplacePlacehoderOptions.md +5 -5
  206. package/docs/interfaces/ResClientFuncParams.md +3 -3
  207. package/docs/interfaces/ResServerFuncParams.md +6 -6
  208. package/docs/interfaces/SanitizeFilenameOptions.md +3 -3
  209. package/docs/interfaces/SectionStringOptions.md +3 -3
  210. package/docs/interfaces/SemaphoreOptions.md +7 -7
  211. package/docs/interfaces/SemaphoreTaskItem.md +5 -5
  212. package/docs/interfaces/ServerFuncItem.md +14 -14
  213. package/docs/interfaces/ServerFuncParams.md +3 -3
  214. package/docs/interfaces/SplitSentenceOptions.md +5 -5
  215. package/docs/interfaces/StreamCallbacksAndOptions.md +5 -5
  216. package/docs/interfaces/TaskAbortControllers.md +1 -1
  217. package/docs/interfaces/TaskPromise.md +2 -2
  218. package/docs/interfaces/ToolFuncPackage.md +4 -4
  219. package/docs/type-aliases/AIChatContentPart.md +1 -1
  220. package/docs/type-aliases/AIChatMessageParam.md +1 -1
  221. package/docs/type-aliases/AIChatRole.md +1 -1
  222. package/docs/type-aliases/AIChatToolChoiceParam.md +1 -1
  223. package/docs/type-aliases/AIMessageType.md +1 -1
  224. package/docs/type-aliases/AIModelNameRule.md +1 -1
  225. package/docs/type-aliases/AIModelNameRuleFn.md +1 -1
  226. package/docs/type-aliases/AIModelNameRules.md +1 -1
  227. package/docs/type-aliases/AITextGenerationFinishReason.md +1 -1
  228. package/docs/type-aliases/ActionName.md +1 -1
  229. package/docs/type-aliases/AsyncTaskId.md +1 -1
  230. package/docs/type-aliases/BeforeShutdownListener.md +1 -1
  231. package/docs/type-aliases/EventErrorListenerFn.md +1 -1
  232. package/docs/type-aliases/EventListenerFn.md +1 -1
  233. package/docs/type-aliases/FuncParamType.md +1 -1
  234. package/docs/type-aliases/PromptExamples.md +1 -1
  235. package/docs/type-aliases/SemaphoreIsReadyFuncType.md +1 -1
  236. package/docs/type-aliases/TFunc.md +1 -1
  237. package/docs/variables/AIChatRoles.md +1 -1
  238. package/docs/variables/AIMessageTypes.md +1 -1
  239. package/docs/variables/AITextGenerationFinishReasons.md +1 -1
  240. package/docs/variables/ActionNames.md +1 -1
  241. package/docs/variables/ClientToolFuncSchema.md +1 -1
  242. package/docs/variables/DEFAULT_CONFIG_NAME.md +1 -1
  243. package/docs/variables/DefaultAsyncSemaphoreCapacity.md +1 -1
  244. package/docs/variables/EventBusName.md +1 -1
  245. package/docs/variables/EventName.md +1 -1
  246. package/docs/variables/FilenameReservedRegex.md +1 -1
  247. package/docs/variables/LLM_TOKENIZER_NAMES.md +1 -1
  248. package/docs/variables/LLM_TOKENIZER_NAMES_MAP.md +1 -1
  249. package/docs/variables/PASSING_SCORE.md +1 -1
  250. package/docs/variables/RStreamErrCode.md +1 -1
  251. package/docs/variables/RemoteToolFuncSchema.md +1 -1
  252. package/docs/variables/ResponseRStreamErrCode.md +1 -1
  253. package/docs/variables/SHUTDOWN_SIGNALS.md +1 -1
  254. package/docs/variables/SSEChannelAlreadyClosedErrCode.md +1 -1
  255. package/docs/variables/SecondaryCache.md +1 -1
  256. package/docs/variables/ServerToolFuncSchema.md +1 -1
  257. package/docs/variables/ToolAsyncCancelableBit.md +1 -1
  258. package/docs/variables/ToolAsyncMultiTaskBit.md +1 -1
  259. package/docs/variables/ToolAsyncPriorityBit.md +1 -1
  260. package/docs/variables/ToolFuncSchema.md +1 -1
  261. package/docs/variables/WindowsReservedNameRegex.md +1 -1
  262. package/docs/variables/base32768.md +1 -1
  263. package/docs/variables/defaultTemplateFormat.md +2 -2
  264. package/docs/variables/event.md +1 -1
  265. package/docs/variables/eventClient.md +1 -1
  266. package/docs/variables/eventServer.md +1 -1
  267. package/docs/variables/lrucache.md +1 -1
  268. package/package.json +5 -3
  269. package/dist/chunk-XLXW6OPN.mjs +0 -1
  270. package/docs/classes/HFEnvironment.md +0 -184
  271. package/docs/classes/HFInterpreter.md +0 -77
  272. package/docs/classes/HFTemplate.md +0 -67
  273. package/docs/classes/HfPromptTemplate.md +0 -1158
  274. package/docs/functions/filenameReservedRegex.md +0 -20
  275. package/docs/functions/hfParse.md +0 -24
  276. package/docs/functions/hfTokenize.md +0 -27
  277. package/docs/functions/interpolateEnv.md +0 -29
  278. package/docs/functions/interpolateFString.md +0 -29
  279. package/docs/functions/interpolateGolangTemplate.md +0 -35
  280. package/docs/functions/parseFString.md +0 -26
  281. package/docs/functions/reControlCharsRegex.md +0 -19
  282. package/docs/interfaces/DotenvExpandOptions.md +0 -43
  283. package/docs/interfaces/DotenvExpandOutput.md +0 -25
  284. package/docs/interfaces/DotenvParseInput.md +0 -13
  285. package/docs/interfaces/DotenvParseOutput.md +0 -13
  286. package/docs/interfaces/DotenvPopulateInput.md +0 -13
  287. package/docs/type-aliases/FStringPromptTemplateNode.md +0 -14
  288. package/docs/type-aliases/PromptTemplateType.md +0 -11
  289. package/docs/type-aliases/PromptType.md +0 -11
  290. package/docs/variables/HFBuiltins.md +0 -122
  291. package/docs/variables/PromptTemplateTypes.md +0 -11
  292. package/docs/variables/PromptTypes.md +0 -14
package/dist/index.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,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},c=(t,r,s)=>(s=null!=t?e(i(t)):{},a(!r&&t&&t.__esModule?s:n(s,"default",{value:t,enumerable:!0}),t)),u={};((t,e)=>{for(var r in e)n(t,r,{get:e[r],enumerable:!0})})(u,{AIArgProcessor:()=>nr,AIChatRoles:()=>$,AIMessageTypes:()=>S,AIStream:()=>tn,AITextGenerationFinishReasons:()=>k,AbortError:()=>m.AbortError,AbortErrorCode:()=>m.AbortErrorCode,ActionNames:()=>w,AlreadyExistsError:()=>m.AlreadyExistsError,AlreadyExistsErrorCode:()=>m.AlreadyExistsErrorCode,AsyncFeatureBits:()=>js,AsyncFeatures:()=>Ns,BaseError:()=>m.BaseError,BinarySemaphore:()=>bs,CancelableAbility:()=>Ms,ChoiceArgProcessor:()=>tr,ClientToolFuncSchema:()=>Ji,ClientTools:()=>Xi,CommonError:()=>m.CommonError,ConfigFile:()=>Dr.Config,DEFAULT_CONFIG_NAME:()=>ki,DefaultAsyncSemaphoreCapacity:()=>ms,EnvPromptTemplate:()=>ne,ErrorCode:()=>m.ErrorCode,EventBusName:()=>Be,EventClient:()=>ao,EventEmitter:()=>Pe.EventEmitter,EventName:()=>_e,EventServer:()=>po,EventStates:()=>Pe.states,EventToolFunc:()=>Ki,FStringPromptTemplate:()=>Jt,FewShotPromptTemplate:()=>se,FilenameReservedRegex:()=>Cn,GolangPromptTemplate:()=>Ht,HFBuiltins:()=>Ft,HFEnvironment:()=>Lt,HFInterpreter:()=>jt,HFTemplate:()=>qt,HashAlgorithm:()=>wn,HfPromptTemplate:()=>zt,IntSet:()=>ls,InternalErrorCode:()=>m.InternalErrorCode,LLM_TOKENIZER_NAMES:()=>si,LLM_TOKENIZER_NAMES_MAP:()=>ii,LRUCache:()=>Yi.LRUCache,NotFoundError:()=>m.NotFoundError,NotFoundErrorCode:()=>m.NotFoundErrorCode,NotImplementationError:()=>m.NotImplementationError,NotImplementedErrorCode:()=>m.NotImplementedErrorCode,ObjectArgsToArgsInfo:()=>Zn,PASSING_SCORE:()=>p,PromptExampleSelector:()=>F,PromptTemplate:()=>N,PromptTemplateTypes:()=>C,PromptTypes:()=>T,RStreamErrCode:()=>Je,RateLimit:()=>Es,ReadableStreamError:()=>We,RemoteToolFuncSchema:()=>d,ResClientTools:()=>oo,ResServerTools:()=>fo,ResponseRStreamErrCode:()=>Ge,SHUTDOWN_SIGNALS:()=>Mi,SSEChannel:()=>De,SSEChannelAlreadyClosedErrCode:()=>Ue,SecondaryCache:()=>to,Semaphore:()=>vs,ServerToolFuncSchema:()=>Wi,ServerTools:()=>Gi,SignalGate:()=>Ss,TaskAbortController:()=>Is,TemplateArgProcessor:()=>er,ToolAsyncCancelableBit:()=>Cs,ToolAsyncMultiTaskBit:()=>Ts,ToolAsyncPriorityBit:()=>Os,ToolFunc:()=>Ui,ToolFuncSchema:()=>Di,WindowsReservedNameRegex:()=>On,YamlTypeBaseObject:()=>gi,_lrucache:()=>eo,assignDirs:()=>Gs,backendEventable:()=>ze,base32768:()=>Sn,beforeShutdown:()=>_i,canonicalize:()=>xn.canonicalize,completeSentences:()=>ve,concatText:()=>Ee,countLLMTokens:()=>ci,countRegexMatches:()=>Rs,createAbilityInjector:()=>f.createAbilityInjector,createCallbacksTransformer:()=>nn,createEmptyReadableStream:()=>Ke,createEndWithRepetitionDetector:()=>Ar,createError:()=>m.createError,createEventStreamTransformer:()=>Qe,createHfValueFunc:()=>Vt,createLRUCache:()=>no,createYamlObjectTag:()=>bi,dateToText:()=>x,decodeCharset:()=>Rr,defaultTemplateFormat:()=>j,detectCharset:()=>zr,encodeLLMTokens:()=>ai,ensureQuoted:()=>ir,event:()=>Zi,eventClient:()=>co,eventServer:()=>wo,eventable:()=>Pe.eventable,expandConfig:()=>$i,expandEnv:()=>te,expandObjEnv:()=>ee,expandPath:()=>Oi,extNameLevel:()=>zn,fileIsExists:()=>Nr,filenameReservedRegex:()=>Fn,filterValidFnScope:()=>kr,findIndexNonEmptyFrom:()=>je,findPort:()=>Bs,formatISO:()=>g.formatISO,formatTextWithSpace:()=>ui,getAllEnumKeys:()=>Dn,getConfigFileNames:()=>Qr,getConfigs:()=>Yr,getEnvVairables:()=>Qt,getFileMetaInfo:()=>_r,getHashAlgoBySize:()=>Br,getKeysPath:()=>Sr,getLLMTokenizer:()=>oi,getMultiLevelExtname:()=>Bn,getPackageDir:()=>Us,getRealFilepath:()=>qr,getResponseErrorReadableStream:()=>He,getXDGConfigs:()=>Ci,hasDirectoryIn:()=>Js,hash:()=>An,hashFile:()=>Pr,hashStream:()=>$n,hfParse:()=>wt,hfTokenize:()=>V,initShutdown:()=>Bi,interpolateEnv:()=>Yt,interpolateFString:()=>Dt,interpolateGolangTemplate:()=>Wt,isLangUsingSpaces:()=>Oe,isListItemString:()=>$e,isModelNameMatched:()=>Un,isPunctuationChar:()=>Te,isQuoted:()=>rr,isRegExp:()=>Hs,isSameString:()=>vi,isSectionString:()=>ke,isSentenceEnding:()=>xe,isSepLineString:()=>Ae,isStrWrapped:()=>sr,isSubdirectory:()=>Xs,isTitleString:()=>Se,isValidFilename:()=>Ln,isValidFilepath:()=>qn,isWebStream:()=>Xe,jsonFilterToWhere:()=>is,jsonToMarkdownStr:()=>us,loadAIConfig:()=>Ti,loadConfig:()=>Ai,loadConfigFile:()=>Si,loadFileFromPaths:()=>Ir,loadTextFromPaths:()=>Fr,lrucache:()=>ro,makeToolFuncCancelable:()=>Fs,matchUrlProtocol:()=>os,memoize:()=>Ps,messagesToText:()=>A,mimeType:()=>Gr.mimeType,paramsSizeToScaleStr:()=>as,parseCommand:()=>hr,parseDateFormat:()=>y.parse,parseFString:()=>Ut,parseISO:()=>g.parseISO,parseJsJson:()=>br,parseJsJsonSimpleSync:()=>vr,parseObjectArgInfo:()=>lr,parseObjectArgumentInfos:()=>Yn,parseObjectArguments:()=>Hn,parseObjectArgumentsAsArgInfos:()=>fr,parseYaml:()=>Kr,quoteStr:()=>or,reControlCharsRegex:()=>Rn,readFilenamesRecursiveSync:()=>Lr,readTextFileChunks:()=>wi,readTextFileChunksEx:()=>di,readableFromAsyncIterable:()=>en,registerCoreTools:()=>mo,registerYamlTag:()=>Hr,removeMarkdownBold:()=>Ne,removeMarkdownBoldAndItalic:()=>Me,removeMarkdownItalic:()=>Ie,replaceWithPlaceholder:()=>wr,restoreFromPlacehoders:()=>dr,sanitizeFilename:()=>Pn,sanitizeFilepath:()=>_n,saveConfigFile:()=>ts,scaleStrToParamsSize:()=>cs,shutdown:()=>Pi,simplifyObjectArguments:()=>Qn,sortedValues:()=>re,splitChunks:()=>mi,splitParagraph:()=>Fe,splitSentence:()=>be,stringifyYaml:()=>Zr,stripConsoleColor:()=>Ks,textToDate:()=>E,throwError:()=>m.throwError,toDate:()=>g.toDate,toDateTime:()=>v,toRegExp:()=>h.toRegExp,trimStartOfStreamHelper:()=>Ye,truncTo:()=>Re,truncateByToken:()=>hi,truncateToTokenLimit:()=>li,truncateToTokenLimitEx:()=>fi,uuid:()=>cn,uuidNIL:()=>on.NIL,uuidParse:()=>on.parse,uuidStringify:()=>on.stringify,uuidValidate:()=>on.validate,uuidVersion:()=>on.version,uuidv1:()=>on.v1,uuidv4:()=>on.v4,uuidv5:()=>on.v5,wait:()=>Le,wrapEventEmitter:()=>Pe.wrapEventEmitter,xxhash:()=>vn,xxhash32:()=>gn,xxhash64:()=>bn,xxhashAsStr:()=>En}),module.exports=(t=u,a(n({},"__esModule",{value:!0}),t));var l=(()=>"undefined"==typeof document?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.src||new URL("main.js",document.baseURI).href)(),f=require("custom-ability"),h=require("util-ex"),p=.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"}},m=require("@isdk/common-error"),y=require("date-fns"),g=require("date-fns"),b="MMMM d, y 'at' h:m:s b 'GMT'x";function v(t){let e;try{"string"==typeof t?e=(0,y.parseISO)(t):"number"==typeof t?e=new Date(t):t instanceof Date&&(e=t)}catch(t){console.error(t)}return e}function E(t,e=b){return(0,y.parse)(t,e,new Date)}function x(t,e=b){return(0,y.format)(t,e)}var k=["stop","length","content_filter","tool_calls","function_call","abort","error","other",null],S=["human","ai","generic","system","tool"],$=["user","assistant","system","tool","tool_calls"];function A(t){let e="";for(const n of t)if(n.content){e+=n.role.toLowerCase()+":";let t=n.createdAt;if(t){const n=v(t);n&&(e+=" ["+x(n)+"]")}e+=" "+n.content+"\n"}return e}var T=["chat","char","plan"],C=["internal","hf","fill"],O=require("custom-factory");var j="default",N=class t extends O.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||j,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||j);if(e)return Reflect.construct(e,arguments);throw new m.CommonError(`Prompt template type ${r} not found`,"PromptTemplate",m.ErrorCode.InvalidArgument)}}_initialize(t){throw new m.NotImplementationError("Not implemented","PromptTemplate")}initialize(e){this.constructor!==t&&(Object.assign(this,this.toJSON(e)),e?.ignoreInitialize||this._initialize(e))}_format(t){throw new m.NotImplementationError("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 I(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 M=!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=>{M=t}));var F=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,M?r:I(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()}},R=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",BooleanLiteral:"BooleanLiteral",NullLiteral:"NullLiteral",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",Macro:"Macro",EndMacro:"EndMacro"}),L=Object.freeze({set:R.Set,for:R.For,in:R.In,is:R.Is,if:R.If,else:R.Else,endif:R.EndIf,elif:R.ElseIf,endfor:R.EndFor,and:R.And,or:R.Or,not:R.Not,"not in":R.NotIn,macro:R.Macro,endmacro:R.EndMacro,true:R.BooleanLiteral,false:R.BooleanLiteral,none:R.NullLiteral,True:R.BooleanLiteral,False:R.BooleanLiteral,None:R.NullLiteral}),q=class{constructor(t,e){this.value=t,this.type=e}};function P(t){return/\w/.test(t)}function _(t){return/[0-9]/.test(t)}var B=[["{%",R.OpenStatement],["%}",R.CloseStatement],["{{",R.OpenExpression],["}}",R.CloseExpression],["(",R.OpenParen],[")",R.CloseParen],["{",R.OpenCurlyBracket],["}",R.CloseCurlyBracket],["[",R.OpenSquareBracket],["]",R.CloseSquareBracket],[",",R.Comma],[".",R.Dot],[":",R.Colon],["|",R.Pipe],["<=",R.ComparisonBinaryOperator],[">=",R.ComparisonBinaryOperator],["==",R.ComparisonBinaryOperator],["!=",R.ComparisonBinaryOperator],["<",R.ComparisonBinaryOperator],[">",R.ComparisonBinaryOperator],["+",R.AdditiveBinaryOperator],["-",R.AdditiveBinaryOperator],["*",R.MultiplicativeBinaryOperator],["/",R.MultiplicativeBinaryOperator],["%",R.MultiplicativeBinaryOperator],["=",R.Equals]],z=new Map([["n","\n"],["t","\t"],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function V(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=z.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===R.CloseStatement||t===R.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 q(t,R.Text));continue}}i((t=>/\s/.test(t)));const e=r[s];if("-"===e||"+"===e){const t=n.at(-1)?.type;if(t===R.Text||void 0===t)throw new SyntaxError(`Unexpected character: ${e}`);switch(t){case R.Identifier:case R.NumericLiteral:case R.BooleanLiteral:case R.NullLiteral:case R.StringLiteral:case R.CloseParen:case R.CloseSquareBracket:break;default:{++s;const t=i(_);n.push(new q(`${e}${t}`,t.length>0?R.NumericLiteral:R.UnaryOperator));continue}}}for(const[t,e]of B){if(r.slice(s,s+t.length)===t){n.push(new q(t,e)),s+=t.length;continue t}}if("'"!==e&&'"'!==e)if(_(e)){const t=i(_);n.push(new q(t,R.NumericLiteral))}else{if(!P(e))throw new SyntaxError(`Unexpected character: ${e}`);{const t=i(P),e=Object.hasOwn(L,t)?L[t]:R.Identifier;e===R.In&&n.at(-1)?.type===R.Not?(n.pop(),n.push(new q("not in",R.NotIn))):n.push(new q(t,e))}}else{++s;const t=i((t=>t!==e));n.push(new q(t,R.StringLiteral)),++s}}return n}var U=class{constructor(){this.type="Statement"}},D=class extends U{constructor(t){super(),this.body=t,this.type="Program"}},X=class extends U{constructor(t,e,n){super(),this.test=t,this.body=e,this.alternate=n,this.type="If"}},J=class extends U{constructor(t,e,n,r){super(),this.loopvar=t,this.iterable=e,this.body=n,this.defaultBlock=r,this.type="For"}},G=class extends U{constructor(t,e){super(),this.assignee=t,this.value=e,this.type="Set"}},W=class extends U{constructor(t,e,n){super(),this.name=t,this.args=e,this.body=n,this.type="Macro"}},H=class extends U{constructor(){super(...arguments),this.type="Expression"}},K=class extends H{constructor(t,e,n){super(),this.object=t,this.property=e,this.computed=n,this.type="MemberExpression"}},Z=class extends H{constructor(t,e){super(),this.callee=t,this.args=e,this.type="CallExpression"}},Q=class extends H{constructor(t){super(),this.value=t,this.type="Identifier"}},Y=class extends H{constructor(t){super(),this.value=t,this.type="Literal"}},tt=class extends Y{constructor(){super(...arguments),this.type="NumericLiteral"}},et=class extends Y{constructor(){super(...arguments),this.type="StringLiteral"}},nt=class extends Y{constructor(){super(...arguments),this.type="BooleanLiteral"}},rt=class extends Y{constructor(){super(...arguments),this.type="NullLiteral"}},st=class extends Y{constructor(){super(...arguments),this.type="ArrayLiteral"}},it=class extends Y{constructor(){super(...arguments),this.type="TupleLiteral"}},ot=class extends Y{constructor(){super(...arguments),this.type="ObjectLiteral"}},at=class extends H{constructor(t,e,n){super(),this.operator=t,this.left=e,this.right=n,this.type="BinaryExpression"}},ct=class extends H{constructor(t,e){super(),this.operand=t,this.filter=e,this.type="FilterExpression"}},ut=class extends H{constructor(t,e){super(),this.iterable=t,this.test=e,this.type="SelectExpression"}},lt=class extends H{constructor(t,e,n){super(),this.operand=t,this.negate=e,this.test=n,this.type="TestExpression"}},ft=class extends H{constructor(t,e){super(),this.operator=t,this.argument=e,this.type="UnaryExpression"}},ht=class extends H{constructor(t=void 0,e=void 0,n=void 0){super(),this.start=t,this.stop=e,this.step=n,this.type="SliceExpression"}},pt=class extends H{constructor(t,e){super(),this.key=t,this.value=e,this.type="KeywordArgumentExpression"}};function wt(t){const e=new D([]);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 R.Text:e=new et(r(R.Text,"Expected text token").value);break;case R.OpenStatement:e=function(){let e;switch(r(R.OpenStatement,"Expected opening statement token"),t[n].type){case R.Set:++n,e=a(),r(R.CloseStatement,"Expected closing statement token");break;case R.If:++n,e=c(),r(R.OpenStatement,"Expected {% token"),r(R.EndIf,"Expected endif token"),r(R.CloseStatement,"Expected %} token");break;case R.Macro:++n,e=function(){const t=E();if("Identifier"!==t.type)throw new SyntaxError("Expected identifier following macro statement");const e=m();r(R.CloseStatement,"Expected closing statement token");const n=[];for(;i(R.OpenStatement,R.EndMacro);)n.push(s());return new W(t,e,n)}(),r(R.OpenStatement,"Expected {% token"),r(R.EndMacro,"Expected endmacro token"),r(R.CloseStatement,"Expected %} token");break;case R.For:++n,e=function(){const t=u(!0);if(!(t instanceof Q||t instanceof it))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${t.type} instead`);r(R.In,"Expected `in` keyword following loop variable");const e=l();r(R.CloseStatement,"Expected closing statement token");const a=[];for(;i(R.OpenStatement,R.EndFor)&&i(R.OpenStatement,R.Else);)a.push(s());const c=[];if(o(R.OpenStatement,R.Else))for(++n,++n,r(R.CloseStatement,"Expected closing statement token");i(R.OpenStatement,R.EndFor);)c.push(s());return new J(t,e,a,c)}(),r(R.OpenStatement,"Expected {% token"),r(R.EndFor,"Expected endfor token"),r(R.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${t[n].type} ${t[n].value}`)}return e}(),e.isStatement=!0;break;case R.OpenExpression:e=function(){r(R.OpenExpression,"Expected opening expression token");const t=l();return r(R.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(R.Equals)){++n;const e=a();return new G(t,e)}return t}function c(){const e=l();r(R.CloseStatement,"Expected closing statement token");const i=[],a=[];for(;t[n]?.type!==R.OpenStatement||t[n+1]?.type!==R.ElseIf&&t[n+1]?.type!==R.Else&&t[n+1]?.type!==R.EndIf;)i.push(s());if(t[n]?.type===R.OpenStatement&&t[n+1]?.type!==R.EndIf)if(++n,o(R.ElseIf))r(R.ElseIf,"Expected elseif token"),a.push(c());else for(r(R.Else,"Expected else token"),r(R.CloseStatement,"Expected closing statement token");t[n]?.type!==R.OpenStatement||t[n+1]?.type!==R.EndIf;)a.push(s());return new X(e,i,a)}function u(t=!1){const e=t?E:l,r=[e()],s=o(R.Comma);for(;s&&(++n,r.push(e()),o(R.Comma)););return s?new it(r):r[0]}function l(){return function(){const t=f();if(o(R.If)){++n;const e=f();if(o(R.Else)){++n;const r=f();return new X(e,[t],[r])}return new ut(t,e)}return t}()}function f(){let e=h();for(;o(R.Or);){const r=t[n];++n;const s=h();e=new at(r,e,s)}return e}function h(){let e=p();for(;o(R.And);){const r=t[n];++n;const s=p();e=new at(r,e,s)}return e}function p(){let e;for(;o(R.Not);){const r=t[n];++n;const s=p();e=new ft(r,s)}return e??function(){let e=w();for(;o(R.ComparisonBinaryOperator)||o(R.In)||o(R.NotIn);){const r=t[n];++n;const s=w();e=new at(r,e,s)}return e}()}function w(){let e=b();for(;o(R.AdditiveBinaryOperator);){const r=t[n];++n;const s=b();e=new at(r,e,s)}return e}function d(t){let e=new Z(t,m());return e=g(e),o(R.OpenParen)&&(e=d(e)),e}function m(){r(R.OpenParen,"Expected opening parenthesis for arguments list");const t=function(){const t=[];for(;!o(R.CloseParen);){let e=l();if(o(R.Equals)){if(++n,!(e instanceof Q))throw new SyntaxError("Expected identifier for keyword argument");const t=l();e=new pt(e,t)}t.push(e),o(R.Comma)&&++n}return t}();return r(R.CloseParen,"Expected closing parenthesis for arguments list"),t}function y(){const t=[];let e=!1;for(;!o(R.CloseSquareBracket);)o(R.Colon)?(t.push(void 0),++n,e=!0):(t.push(l()),o(R.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 ht(...t)}return t[0]}function g(e){for(;o(R.Dot)||o(R.OpenSquareBracket);){const s=t[n];let i;++n;const o=s.type!==R.Dot;if(o)i=y(),r(R.CloseSquareBracket,"Expected closing square bracket");else if(i=E(),"Identifier"!==i.type)throw new SyntaxError("Expected identifier following dot operator");e=new K(e,i,o)}return e}function b(){let e=v();for(;o(R.MultiplicativeBinaryOperator);){const r=t[n];++n;const s=v();e=new at(r,e,s)}return e}function v(){let t=function(){let t=function(){const t=g(E());return o(R.OpenParen)?d(t):t}();for(;o(R.Pipe);){++n;let e=E();if(!(e instanceof Q))throw new SyntaxError("Expected identifier for the filter");o(R.OpenParen)&&(e=d(e)),t=new ct(t,e)}return t}();for(;o(R.Is);){++n;const e=o(R.Not);e&&++n;let r=E();if(r instanceof nt?r=new Q(r.value.toString()):r instanceof rt&&(r=new Q("none")),!(r instanceof Q))throw new SyntaxError("Expected identifier for the test");t=new lt(t,e,r)}return t}function E(){const e=t[n];switch(e.type){case R.NumericLiteral:return++n,new tt(Number(e.value));case R.StringLiteral:return++n,new et(e.value);case R.BooleanLiteral:return++n,new nt("true"===e.value.toLowerCase());case R.NullLiteral:return++n,new rt(null);case R.Identifier:return++n,new Q(e.value);case R.OpenParen:{++n;const e=u();if(t[n].type!==R.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${t[n].type} instead`);return++n,e}case R.OpenSquareBracket:{++n;const t=[];for(;!o(R.CloseSquareBracket);)t.push(l()),o(R.Comma)&&++n;return++n,new st(t)}case R.OpenCurlyBracket:{++n;const t=new Map;for(;!o(R.CloseCurlyBracket);){const e=l();r(R.Colon,"Expected colon between key and value in object literal");const s=l();t.set(e,s),o(R.Comma)&&++n}return++n,new ot(t)}default:throw new SyntaxError(`Unexpected token: ${e.type}`)}}for(;n<t.length;)e.body.push(s());return e}function dt(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 mt(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 yt(t){return t.replace(/\b\w/g,(t=>t.toUpperCase()))}var gt=class{constructor(t=void 0){this.type="RuntimeValue",this.builtins=new Map,this.value=t}__bool__(){return new Et(!!this.value)}toString(){return""+this.value}toJSON(){return this.value}},bt=class extends gt{constructor(){super(...arguments),this.type="NumericValue"}},vt=class t extends gt{constructor(){super(...arguments),this.type="StringValue",this.builtins=new Map([["upper",new At((()=>new t(this.value.toUpperCase())))],["lower",new At((()=>new t(this.value.toLowerCase())))],["strip",new At((()=>new t(this.value.trim())))],["title",new At((()=>new t(yt(this.value))))],["length",new bt(this.value.length)],["rstrip",new At((()=>new t(this.value.trimEnd())))],["lstrip",new At((()=>new t(this.value.trimStart())))],["split",new At((e=>{const n=e[0]??new Tt;if(!(n instanceof t||n instanceof Tt))throw new Error("sep argument must be a string or null");const r=e[1]??new bt(-1);if(!(r instanceof bt))throw new Error("maxsplit argument must be a number");let s=[];if(n instanceof Tt){const t=this.value.trimStart();for(const{0:e,index:n}of t.matchAll(/\S+/g)){if(-1!==r.value&&s.length>=r.value&&void 0!==n){s.push(e+t.slice(n+e.length));break}s.push(e)}}else{if(""===n.value)throw new Error("empty separator");s=this.value.split(n.value),-1!==r.value&&s.length>r.value&&s.push(s.splice(r.value).join(n.value))}return new St(s.map((e=>new t(e))))}))]])}},Et=class extends gt{constructor(){super(...arguments),this.type="BooleanValue"}},xt=class extends gt{constructor(t,e){super(t),this.orgValue=e,this.type="ObjectValue",this.builtins=new Map([["get",new At((([t,e])=>{if(!(t instanceof vt))throw new Error(`Object key must be a string: got ${t.type}`);return this.value.get(t.value)??e??new Tt}))],["items",new At((()=>new St(Array.from(this.value.entries()).map((([t,e])=>new St([new vt(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 Et(this.value.size>0)}},kt=class extends xt{constructor(){super(...arguments),this.type="KeywordArgumentsValue"}},St=class extends gt{constructor(){super(...arguments),this.type="ArrayValue",this.builtins=new Map([["length",new bt(this.value.length)]])}__bool__(){return new Et(this.value.length>0)}},$t=class extends St{constructor(){super(...arguments),this.type="TupleValue"}},At=class extends gt{constructor(){super(...arguments),this.type="FunctionValue"}},Tt=class extends gt{constructor(){super(...arguments),this.type="NullValue"}},Ct=class extends gt{constructor(){super(...arguments),this.type="UndefinedValue"}},Ot=class{constructor(t){this.parent=t,this.variables=new Map([["namespace",new At((t=>{if(0===t.length)return new xt(new Map);if(1!==t.length||!(t[0]instanceof xt))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 At],["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],["string",t=>"StringValue"===t.type],["number",t=>"NumericValue"===t.type],["integer",t=>"NumericValue"===t.type&&Number.isInteger(t.value)],["iterable",t=>t instanceof St||t instanceof vt],["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],["eq",(t,e)=>t.value===e.value]])}set(t,e){return this.declareVariable(t,Nt(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 Ct}catch{return new Ct}}},jt=class{constructor(t){this.global=t??new Ot}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 Et(n.value==r.value);case"!=":return new Et(n.value!=r.value)}if(n instanceof Ct||r instanceof Ct)throw new Error("Cannot perform operation on undefined values");if(n instanceof Tt||r instanceof Tt)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 Et(n.value<r.value);case">":return new Et(n.value>r.value);case">=":return new Et(n.value>=r.value);case"<=":return new Et(n.value<=r.value)}else if(n instanceof St&&r instanceof St){if("+"===t.operator.value)return new St(n.value.concat(r.value))}else if(r instanceof St){const e=void 0!==r.value.find((t=>t.value===n.value));switch(t.operator.value){case"in":return new Et(e);case"not in":return new Et(!e)}}if((n instanceof vt||r instanceof vt)&&"+"===t.operator.value)return new vt(n.toString()+r.toString());if(n instanceof vt&&r instanceof vt)switch(t.operator.value){case"in":return new Et(r.value.includes(n.value));case"not in":return new Et(!r.value.includes(n.value))}if(n instanceof vt&&r instanceof xt)switch(t.operator.value){case"in":return new Et(r.value.has(n.value));case"not in":return new Et(!r.value.has(n.value))}throw new SyntaxError(`Unknown operator "${t.operator.value}" between ${n.type} and ${r.type}`)}evaluateArguments(t,e){const n=[],r=new Map;for(const s of t)if("KeywordArgumentExpression"===s.type){const t=s;r.set(t.key.value,this.evaluate(t.value,e))}else{if(r.size>0)throw new Error("Positional arguments must come before keyword arguments");n.push(this.evaluate(s,e))}return[n,r]}evaluateFilterExpression(t,e){const n=this.evaluate(t.operand,e);if("Identifier"===t.filter.type){const r=t.filter,s=e.lookupVariable(r.value);if(s instanceof At)return s.value([n],e);if(n instanceof St)switch(r.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 St(n.value.reverse());case"sort":return new St(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"join":return new vt(n.value.map((t=>t.value)).join(""));default:throw new Error(`Unknown ArrayValue filter: ${r.value}`)}else if(n instanceof vt)switch(r.value){case"length":return new bt(n.value.length);case"upper":return new vt(n.value.toUpperCase());case"lower":return new vt(n.value.toLowerCase());case"title":return new vt(yt(n.value));case"capitalize":return new vt(n.value.charAt(0).toUpperCase()+n.value.slice(1));case"trim":return new vt(n.value.trim());case"trimStart":return new vt(n.value.trimStart());case"trimEnd":return new vt(n.value.trimEnd());case"indent":return new vt(n.value.split("\n").map(((t,e)=>0===e||0===t.length?t:" "+t)).join("\n"));case"join":case"string":return n;default:throw new Error(`Unknown StringValue filter: ${r.value}`)}else{if(n instanceof bt){if("abs"===r.value)return new bt(Math.abs(n.value));throw new Error(`Unknown NumericValue filter: ${r.value}`)}if(n instanceof xt)switch(r.value){case"items":return new St(Array.from(n.value.entries()).map((([t,e])=>new St([new vt(t),e]))));case"length":return new bt(n.value.size);case"string":return new vt(n.toString());default:throw new Error(`Unknown ObjectValue filter: ${r.value}`)}}throw new Error(`Cannot apply filter "${r.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 At){const[t,s]=this.evaluateArguments(r.args,e);return s.size>0&&t.push(new kt(s)),i.value([n,...t],e)}if(n instanceof St){switch(s){case"selectattr":{if(n.value.some((t=>!(t instanceof xt))))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 St(a)}case"map":{const[,t]=this.evaluateArguments(r.args,e);if(t.has("attribute")){const e=t.get("attribute");if(!(e instanceof vt))throw new Error("attribute must be a string");const r=t.get("default"),s=n.value.map((t=>{if(!(t instanceof xt))throw new Error("items in map must be an object");return t.value.get(e.value)??r??new Ct}));return new St(s)}throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${s}`)}if(n instanceof vt){if("indent"===s){const[t,s]=this.evaluateArguments(r.args,e),i=t.at(0)??s.get("width")??new bt(4);if(!(i instanceof bt))throw new Error("width must be a number");const o=t.at(1)??s.get("first")??new Et(!1),a=t.at(2)??s.get("blank")??new Et(!1),c=n.value.split("\n"),u=" ".repeat(i.value),l=c.map(((t,e)=>!o.value&&0===e||!a.value&&0===t.length?t:u+t));return new vt(l.join("\n"))}throw new Error(`Unknown StringValue 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 Et(t.negate?!s:s)}evaluateUnaryExpression(t,e){const n=this.evaluate(t.argument,e);if("not"===t.operator.value)return new Et(!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 vt(n)}evaluateIdentifier(t,e){return e.lookupVariable(t.value)}evaluateCallExpression(t,e){const[n,r]=this.evaluateArguments(t.args,e);r.size>0&&n.push(new kt(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 St||t instanceof vt))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 Ct))throw new Error("Slice start must be numeric or undefined");if(!(s instanceof bt||s instanceof Ct))throw new Error("Slice stop must be numeric or undefined");if(!(i instanceof bt||i instanceof Ct))throw new Error("Slice step must be numeric or undefined");return t instanceof St?new St(mt(t.value,r.value,s.value,i.value)):new vt(mt(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 vt(t.property.value);if(n instanceof xt){if(!(r instanceof vt))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 St||n instanceof vt)if(r instanceof bt)s=n.value.at(r.value),n instanceof vt&&(s=new vt(n.value.at(r.value)));else{if(!(r instanceof vt))throw new Error(`Cannot access property with non-string/non-number: got ${r.type}`);s=n.builtins.get(r.value)}else{if(!(r instanceof vt))throw new Error(`Cannot access property with non-string: got ${r.type}`);s=n.builtins.get(r.value)}return s instanceof gt?s:new Ct}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 xt))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 Tt}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 Ot(e);let r,s;if("SelectExpression"===t.iterable.type){const e=t.iterable;s=this.evaluate(e.iterable,n),r=e.test}else s=this.evaluate(t.iterable,n);if(!(s instanceof St))throw new Error(`Expected iterable type in for loop: got ${s.type}`);const i=[],o=[];for(let e=0;e<s.value.length;++e){const a=new Ot(n),c=s.value[e];let u;if("Identifier"===t.loopvar.type)u=e=>e.setVariable(t.loopvar.value,c);else{if("TupleLiteral"!==t.loopvar.type)throw new Error(`Invalid loop variable(s): ${t.loopvar.type}`);{const e=t.loopvar;if("ArrayValue"!==c.type)throw new Error(`Cannot unpack non-iterable type: ${c.type}`);const n=c;if(e.value.length!==n.value.length)throw new Error(`Too ${e.value.length>n.value.length?"few":"many"} items to unpack`);u=t=>{for(let r=0;r<e.value.length;++r){if("Identifier"!==e.value[r].type)throw new Error(`Cannot unpack non-identifier type: ${e.value[r].type}`);t.setVariable(e.value[r].value,n.value[r])}}}}if(r){u(a);if(!this.evaluate(r,a).__bool__().value)continue}i.push(c),o.push(u)}let a="",c=!0;for(let e=0;e<i.length;++e){const r=new Map([["index",new bt(e+1)],["index0",new bt(e)],["revindex",new bt(i.length-e)],["revindex0",new bt(i.length-e-1)],["first",new Et(0===e)],["last",new Et(e===i.length-1)],["length",new bt(i.length)],["previtem",e>0?i[e-1]:new Ct],["nextitem",e<i.length-1?i[e+1]:new Ct]]);n.setVariable("loop",new xt(r)),o[e](n);a+=this.evaluateBlock(t.body,n).value,c=!1}if(c){a+=this.evaluateBlock(t.defaultBlock,n).value}return new vt(a)}evaluateMacro(t,e){return e.setVariable(t.name.value,new At(((e,n)=>{const r=new Ot(n);let s;e=e.slice(),"KeywordArgumentsValue"===e.at(-1)?.type&&(s=e.pop());for(let n=0;n<t.args.length;++n){const i=t.args[n],o=e[n];if("Identifier"===i.type){const t=i;if(!o)throw new Error(`Missing positional argument: ${t.value}`);r.setVariable(t.value,o)}else{if("KeywordArgumentExpression"!==i.type)throw new Error(`Unknown argument type: ${i.type}`);{const t=i,e=o??s?.value.get(t.key.value)??this.evaluate(t.value,r);r.setVariable(t.key.value,e)}}}return this.evaluateBlock(t.body,r)}))),new Tt}evaluate(t,e){if(void 0===t)return new Ct;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"Macro":return this.evaluateMacro(t,e);case"NumericLiteral":return new bt(Number(t.value));case"StringLiteral":return new vt(t.value);case"BooleanLiteral":return new Et(t.value);case"NullLiteral":return new Tt(t.value);case"ArrayLiteral":return new St(t.value.map((t=>this.evaluate(t,e))));case"TupleLiteral":return new $t(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 vt))throw new Error(`Object keys must be strings: got ${t.type}`);n.set(t.value,this.evaluate(s,e))}return new xt(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 Nt(t){switch(typeof t){case"number":return new bt(t);case"string":return new vt(t);case"boolean":return new Et(t);case"undefined":return new Ct;case"object":return null===t?new Tt:Array.isArray(t)?new St(t.map(Nt)):new xt(new Map(Object.entries(t).map((([t,e])=>[t,Nt(e)]))),t);case"function":return new At(((e,n)=>{const r=e.map((t=>It(t)));return Nt(t(...r)??null)}));default:throw new Error(`Cannot convert to runtime value: ${t}`)}}function It(t){let e=t;if(Array.isArray(t))e=t.map((t=>It(t)));else if(t instanceof Map)e={},t.forEach(((t,n)=>{e[n]=It(t)}));else switch(t.type){case"NullValue":e=null;break;case"UndefinedValue":e=void 0;break;case"ArrayValue":e=t.value.map((t=>It(t)));break;case"KeywordArgumentsValue":case"ObjectValue":e=t.orgValue?t.orgValue:It(t.value),"KeywordArgumentsValue"===t.type&&Object.setPrototypeOf(e,{jinja_kargs:!0});break;default:t.type&&(e=t.value)}return e}function Mt(t,e=0){return Math.floor(Math.random()*(t-e+1))+e}var Ft={randomInt:Mt,select:function(t,e){if(Array.isArray(t)||"string"==typeof t)return void 0===e?e=Mt(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[Mt(n.length-1)]}return t[e]}},tojson:function(t,e,n){return e&&"object"==typeof e&&(e.depth&&(n=e.depth),e=e.indent),Rt(t,e,n)},join:function(t,e=","){return Array.isArray(t)?t.join(e):t}};function Rt(t,e,n){let r="";const s=n??0;if(null===t)r="null";else{const n=typeof t;switch(n){case"undefined":r="null";case"number":case"string":case"boolean":return JSON.stringify(t);case"object":{const n=e?" ".repeat(e):"",r="\n"+n.repeat(s),i=r+n;if(Array.isArray(t)){const n=t.map((t=>Rt(t,e,s+1)));return e?`[${i}${n.join(`,${i}`)}${r}]`:`[${n.join(", ")}]`}{const n=Array.from(Object.entries(t)).map((([t,n])=>{const r=`"${t}": ${Rt(n,e,s+1)}`;return e?`${i}${r}`:r}));return e?`{${n.join(",")}${r}}`:`{${n.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${n}`)}}return r}var Lt=class extends Ot{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()}},qt=class t{static{this.global=new Lt}constructor(t,e={}){const n=V(t,e={lstrip_blocks:!0,trim_blocks:!0,...e});this.parsed=wt(n)}render(e){const n=new Ot(t.global);if(n.set("false",!1),n.set("true",!0),n.set("raise_exception",(t=>{throw new Error(t)})),n.set("range",dt),e)for(const[t,r]of Object.entries(e))n.set(t,r);return new jt(n).run(this.parsed).toString()}};function Pt(t,e){let n;switch(t.type){case"Identifier":n=t.value;break;case"MemberExpression":n=Pt(t.object,e);break;case"FilterExpression":n=Pt(t.operand,e);break;case"Set":{e||(e=[]);const r=Pt(t.assignee);r&&e.push(r),n=Pt(t.value,e);break}}return n&&e?.includes(n)&&(n=void 0),n}function _t(t){let e;if("Program"===t.type)e=t.body.some((t=>_t(t)));else e=t.isStatement;return e}function Bt(t,e){let n=[];if(Array.isArray(t))n=t.map((t=>Bt(t,e))).filter(Boolean).flat();else switch(t.type){case"Program":n=t.body.map((t=>Bt(t,e))).filter(Boolean).flat();break;case"If":n=[Pt(t.test,e),...Bt(t.body,e),...Bt(t.alternate,e)].filter(Boolean);break;case"BinaryExpression":n=[Pt(t.left,e),Pt(t.right,e)].filter(Boolean);break;case"For":{const r=Pt(t.loopvar);r&&(e||(e=[]),e.push(r)),n=[Pt(t.iterable,e),...Bt(t.body,e)].filter(Boolean);break}case"CallExpression":n=[Pt(t.callee,e),...Bt(t.args,e)].filter(Boolean);break;default:n=[Pt(t,e)].filter(Boolean)}return n}qt.global.assign(Ft);var zt=class extends N{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 qt(n)}catch(t){}return e&&(r=_t(e.parsed)),r}getVariables(t=this.compiledTemplate){return Bt(t.parsed,[]).filter(((t,e,n)=>n.indexOf(t)===e))}_initialize(t){const e=t?.template;if("string"!=typeof e)throw new m.CommonError("Prompt template must be a string","PromptTemplate",m.ErrorCode.InvalidArgument);this.compiledTemplate=new qt(e),this.inputVariables=Array.isArray(t?.inputVariables)?t.inputVariables:this.getVariables()}_format(t){return this.compiledTemplate.render(t)}};function Vt(t){return function(e){return t}}function Ut(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 Dt(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 Xt(t){const e=new Set;return t.forEach((t=>{"variable"===t.type&&e.add(t.name)})),[...e]}N.register(zt,{name:"hf",aliases:["huggingface","internal","default"]});var Jt=class extends N{static isTemplate(t){let e,n,r=!1;if("object"==typeof t?(n=t.template,e=t.compiledTemplate):n=t,!e&&n)try{e=Ut(n)}catch(t){}if(e){r=Xt(e).length>0}return r}getVariables(t=this.compiledTemplate){return Xt(t)}_initialize(t){const e=t?.template;if("string"!=typeof e)throw new m.CommonError("Prompt template must be a string","PromptTemplate",m.ErrorCode.InvalidArgument);this.compiledTemplate=Ut(e),this.inputVariables=Array.isArray(t?.inputVariables)?t.inputVariables:this.getVariables()}_format(t){return Dt(this.compiledTemplate,t)}};function Gt(t,e){return"string"==typeof e&&(e=e.split(".").filter((t=>t.length))),e.reduce(((t,e)=>t?.[e]),t)}function Wt(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 Gt(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):Gt(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=Gt(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=Gt(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):Gt(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=Gt(e,r);let o;return o=isNaN(s)?i[s.substring(1,s.length-1)]:i[parseInt(s,10)],o||""}))}(r,e,n),r}N.register(Jt,{name:"fstring",aliases:["python","f-string","langchain"]});var Ht=class extends N{static isTemplate(t){const e="string"==typeof t?t:t.template;return e?.includes("{{")&&e.includes("}}")}getVariables(t){const e={};return Wt(t,e,!0),[...Object.keys(e)]}_initialize(t){const e=t?.template;if("string"!=typeof e)throw new m.CommonError("Prompt template must be a string","PromptTemplate",m.ErrorCode.InvalidArgument);this.inputVariables=Array.isArray(t?.inputVariables)?t.inputVariables:this.getVariables(e)}_format(t){return Wt(this.template,t)}};N.register(Ht,{name:"golang",aliases:["localai","ollama"]});var Kt=/(\\)?(\$)(?!\()(\{?)([\w.]+)(?::?-((?:\$\{(?:\$\{(?:\$\{[^}]*\}|[^}])*}|[^}])*}|[^}])+))?(\}?)/gi;function Zt(t){return t.replace(/\\\$/g,"$")}function Qt(t){const e=new Set;let n;for(;n=Kt.exec(t);){const t=n[3],r=n[6];if(t&&r||!t&&!r){const t=n[4];e.add(t)}}return[...e]}function Yt(t,e,n){return t.replace(Kt,((r,s,i,o,a,c,u)=>o&&!u?r:"\\"===s?r.slice(1):e[a]?e[a]===n?.[a]?e[a]:Yt(e[a],e,n):n?.[a]?n[a]===t?n[a]:Yt(n[a],e,n):c?c.startsWith("$")?Yt(c,e,n):c:""))}function te(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]?Yt(r,e,t.parsed):e[n]:Yt(r,e,t.parsed),t.parsed[n]=r?Zt(r):r}for(const n in t.parsed)e[n]=t.parsed[n];return t}function ee(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=Yt(t,e.processEnv,e.parsed);break;case"object":if(n.has(t)||null===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]=ee(t[r],e,n))}else for(const[r,s]of Object.entries(t))"string"!=typeof s&&"object"!=typeof s||(t[r]=ee(s,e,n))}return t}var ne=class extends N{static isTemplate(t){let e,n=!1;e="object"==typeof t?t.template:t;return n=Qt(e).length>0,n}getVariables(t=this.template){return Qt(t)}_initialize(t){const e=t?.template;if("string"!=typeof e)throw new m.CommonError("Prompt template must be a string","PromptTemplate",m.ErrorCode.InvalidArgument);this.inputVariables=Array.isArray(t?.inputVariables)?t.inputVariables:this.getVariables()}_format(t){const e={...process.env};return Yt(this.template,e,t)}};function re(t){return Object.keys(t).sort().map((e=>t[e]))}N.register(ne,{name:"env",aliases:["js","javascript"]});var se=class extends N{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 N?t.examplePrompt:N.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=re(t);n.length>0&&e.push(...n)}const n=[this.prefix,...e,this.suffix].join(this.exampleSeparator),r=this.templateFormat;return await N.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}};N.register(se,{name:"fewshot",aliases:["few_shot"]});var ie=require("@isdk/detect-text-language"),oe="@",ae=/(\S.+?[.!?])(?=\s+|$)|(\S.+?)(?=[\n]|$)/g,ce=/([A-Z][a-z]{1,2}\.)\s(\w)/g,ue=/(\.[a-zA-Z]\.)\s(\w)/g,le=new RegExp("([A-Z][a-z]{1,2}\\.)"+oe+"(\\w)","g"),fe=new RegExp("(\\.[a-zA-Z]\\.)"+oe+"(\\w)","g"),he=/(```)([\s\S]*?)(```)/g,pe=">>>CODE_BLOCK<<<",we=/([*_`]{1,3})(\S.*?\S)\1/,de=">>> INLINE_BLOCK ",me=/>>> INLINE_BLOCK (\d+) <<</,ye=1e4;function ge(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 be(t,{best:e=!0,completeSentence:n,isMarkdown:r,ignoreEmptyLine:s}={}){const i=[],o=[];let a,c=0;for(;c++<ye&&(a=he.exec(t));){const e=a[0];i.push(e),t=t.replace(e,"\n"+pe+(i.length-1)+"\n")}for(c=0;c++<ye&&(a=we.exec(t));){const e=a[0];o.push(e),t=t.replace(e,de+(o.length-1)+" <<<")}if(r){const e=t.split("\n");for(let t=0;t<e.length;t++){const n=e[t];Se(n,{isMarkdown:r,nextLine:e[t+1]})&&(i.push(n),e[t]=pe+(i.length-1))}t=e.join("\n")}const u=(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 l=[];for(let t=0;t<u.length;t++){let n=u[t].trimEnd();if(!n){!r&&s||l.push("");continue}if(n.startsWith(pe)){l.push(i[Number(n.slice(pe.length))]);continue}if(r&&Se(n,{isMarkdown:r,nextLine:u[t+1]})){l.push(n);continue}if(!e){l.push(n);continue}let a=ge(n,oe,[ce,ue]),c=Array.from(a.matchAll(ae)),f=[];if(c.length)for(let t=0;t<c.length;t++)f.push(ge(c[t][0]," ",[le,fe]));else f.push(n);l.push(...f.map((t=>Ce(o,t))))}return n&&(l=ve(l,{isMarkdown:r,ignoreEmptyLine:s})),l}function ve(t,{isMarkdown:e,ignoreEmptyLine:n}={}){const r=[];let s=0,i="";for(n=!e&&n;s<t.length;){let c=t[s];if(c){let u;if(n){const n=je(t,s+1);u=ke(t[n],{isMarkdown:e,nextLine:-1===n?"":t[n+1]})}else u=ke(t[s+1],{isMarkdown:e,nextLine:t[s+2]});o=c,a={isMarkdown:e,nextLine:t[s+1]},xe(o)||ke(o,a)||""===t[s+1]||u?(i&&(c=Ee(i,c),i=""),r.push(c)):(i&&(c=Ee(i,c)),i=c)}else n||r[r.length-1]&&r.push(c);s++}var o,a;return i&&r.push(i),r}function Ee(t,e){const n=t+" "+e,r=(0,ie.detectTextLanguage)(n,{isoCode:!0});return r&&!Oe(r)?(Te(t)&&(t+=" "),e=t+e):e=t.endsWith("-")?(t=t.slice(0,-1))+e:n,e}function xe(t){if(!t)return!1;return/(([.。!!??]\s*['"”’]?)|```)\s*$/.test(t)}function ke(t,e){let n=Se(t,e);return n||(n=$e(t)),n||(n=Ae(t)),n}function Se(t,e){if(!t)return null;let n=/^\s*第?\s*[壹贰叁肆伍陆柒捌玖拾一二三四五六七八九十百千萬万\d]+\s*([章節节编回部篇卷幕场場辑集段册冊期片題]|片段|段落|篇[章目]|小[节節]|(子)?部分|卷[册冊]|[单單]元|章[节節回]|[.、])[ \t]*(?<title>.*)(?=\n|$)/.exec(t);if(n||(n=/^\s*(Chapter|Book|Article|Part|Paragraph|Subsection|Subpart|Volume|Episode|Issue|Unit|Section|Segment|Act|Scene)\s*\d+.*(?=\n|$)/i.exec(t)),!n&&e?.isMarkdown){n=/^[ \t]{0,3}(#+)\s+(?<title>\S.*)$/.exec(t);const r=/^[ \t]{0,3}([-=]+)(?=\n|$)/;!n&&e.nextLine&&!r.test(t)&&/^[ \t]{0,3}\S/.test(t)&&r.test(e.nextLine)&&(n=/^\s*(?<title>.*)(?=\n|$)/.exec(t))}return n}function $e(t){return/^\s*([*+-]|\d+[.、])\s*(?<item>.*)(?=\n|$)/.exec(t)}function Ae(t){return/^[-=_]{3,}$/.exec(t)}function Te(t){return/[。!??,、;;::'""“”‘’~~《》<>〈〉【】(){}【】\[\]\(\)…·]$/.test(t)}function Ce(t,e){let n,r=0;for(;r++<ye&&(n=me.exec(e));){const r=Number(n[1]);e=e.replace(n[0],t[r])}return e}function Oe(t){return!["zh","ja","th","lo","ta","ko"].includes(t)}function je(t,e=0){for(let n=e;n<t.length;n++){const e=t[n];if(null!=e&&""!==e)return n}return-1}function Ne(t,e){const n=/(?!\\)([*_])\1(?![ \t]|\1)(.+?)(?<!\\)\1{2}/;let r;for(;(r=n.exec(t))&&(t=t.slice(0,r.index)+r[2]+t.slice(r.index+r[0].length),!e););return t}function Ie(t,e){const n=/(?!\\)([*_])(?![ \t]|\1)(.+?)(?<!\\)\1/;let r;for(;(r=n.exec(t))&&(t=t.slice(0,r.index)+r[2]+t.slice(r.index+r[0].length),!e););return t}function Me(t,e){return t=Ie(t=Ne(t,e),e)}function Fe(t,e){const n=[],r=[],s=t.split("\n");for(let t=0;t<s.length;t++){let i=s[t];const o=0===i.trim().length;o||Se(i,{...e,nextLine:s[t+1]})?(r.length&&n.push([...r]),r.length=0,o||r.push(i)):r.push(i)}return r.length&&n.push([...r]),n}function Re(t,e=2,n=.5){const r=10**e;return Math.trunc((t+Number.EPSILON+n/r)*r)/r}async function Le(t){return new Promise((e=>setTimeout(e,t)))}var qe=require("custom-ability"),Pe=require("events-ex"),_e="event",Be="event-bus";var ze=(0,qe.createAbilityInjector)((function(t){return class{static get emitter(){if(!this._emitter){const t=this.get(Be)?.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 Ve(t,e){return!t||t.some((t=>t instanceof RegExp?t.test(e):t===e))}var Ue=498,De=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||(0,m.throwError)("Channel closed","SSEChannel",Ue);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||Ve(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||(0,m.throwError)("Channel closed","SSEChannel",Ue);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=>Ve(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}};function Xe(t){return t instanceof ReadableStream||t instanceof WritableStream}var Je=600,Ge=601,We=class extends m.BaseError{constructor(t,e=Je){super(t,500)}};function He(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 We(`Response error: ${e}`,Ge))}}})}return new ReadableStream({start(t){t.error(new We("Response error: No response body",Ge))}})}function Ke(){return new ReadableStream({start(t){t.close()}})}var Ze=require("eventsource-parser");function Qe(t){const e=new TextDecoder;let n;return new TransformStream({async start(e){n=(0,Ze.createParser)({onEvent:n=>{if("data"in n&&"[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 Ye(){let t=!0;return e=>(t&&(e=e.trimStart())&&(t=!1),e)}function tn(t,e){if(!t.ok)return He(t.body);let n=t.body||new ReadableStream({start(t){t.close()}});return n instanceof ReadableStream||(n=ReadableStream.from(n)),n.pipeThrough(Qe(e))}function en(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))}})}function nn(t){const e=t||{};return new TransformStream({async start(t){const n=t.error;if(t.error=r=>{n.call(t,r),e.onError&&e.onError(r)},e.onStart)try{await e.onStart(t)}catch(e){t.error(e)}},async transform(t,n){try{let r;e.onTransform&&(r=await e.onTransform(t,n)),r||(r=t),n.enqueue(r)}catch(t){n.error(t)}},async flush(t){if(e.onFinal)try{await e.onFinal(t)}catch(e){return t.error(e)}t.terminate()}})}var rn=require("uuid"),sn=c(require("base32768")),on=require("uuid"),an={1:rn.v1,4:rn.v4,5:rn.v5};function cn(t=1,e){const n=an[t];return e?sn.encode(n(null,[])):n()}var un=c(require("xxhashjs")),ln=c(require("base32768")),fn=require("json-canonicalize"),hn=require("hash-wasm"),pn=588213,wn=(t=>(t[t.md5=1]="md5",t[t.sha1=2]="sha1",t[t.ripemd=3]="ripemd",t[t.sha256=8]="sha256",t[t.sha384=9]="sha384",t[t.sha512=10]="sha512",t[t.sha224=11]="sha224",t[t.xxhash=111]="xxhash",t[t.xxhash64=111]="xxhash64",t[t.xxhash32=112]="xxhash32",t[t.xxhash128=113]="xxhash128",t))(wn||{}),dn={1:hn.createMD5,2:hn.createSHA1,8:hn.createSHA256,10:hn.createSHA512,11:hn.createSHA224,3:hn.createRIPEMD160,112:hn.createXXHash32,111:hn.createXXHash64,113:hn.createXXHash128},{h32:mn,h64:yn}=un.default;function gn(t,e=16){return"object"==typeof t&&(t=(0,fn.canonicalize)(t)),mn(t.normalize(),pn).toString(e)}function bn(t,e=16){return"object"==typeof t&&(t=(0,fn.canonicalize)(t)),yn(t.normalize(),pn).toString(e)}function vn(t,e=111,n=pn){let r;return t.buffer&&(t=t.buffer),112!==e?(r=yn(t,n),r=new Uint16Array([r._a00,r._a16,r._a32,r._a48]),r=new Uint8Array(r.buffer)):(r=mn(t,n),r=new Uint16Array([r._low,r._high]),r=new Uint8Array(r.buffer)),r}function En(t,e=111,n=pn){return ln.encode(vn(t,e,n))}var xn=require("json-canonicalize"),kn=c(require("base32768")),Sn=kn;async function $n(t,{hashAlgo:e=111,seed:n=pn,outputType:r="string"}={}){const s=await dn[e](n);s.init();const i=t.getReader();for(;;){const{done:t,value:e}=await i.read();if(t)break;s.update(e)}return"string"!==r?s.digest(r):kn.encode(s.digest("binary"))}async function An(t,{hashAlgo:e=111,seed:n=pn,outputType:r="string"}={}){const s=await dn[e](n);s.init(),s.update(t);return"string"!==r?s.digest(r):kn.encode(s.digest("binary"))}var Tn=c(require("path")),Cn=/[<>:"/\\|?*\u0000-\u001F]/,On=/^(con|prn|aux|nul|com\d|lpt\d)$/i,jn=100,Nn=/^\.+(\\|\/)|^\.+$/,In=/\.+$/,Mn=/[\u0000-\u001F\u0080-\u009F\u200E\u200F\u202A-\u202E\u2066-\u2069]/;function Fn(){return new RegExp(Cn.source,"g")}function Rn(){return new RegExp(Mn.source,"g")}function Ln(t){return t&&!(Cn.test(t)||Rn().test(t)||Nn.test(t)||In.test(t))}function qn(t){const e=t.split(Tn.default.sep);return("/"===t[0]||e[0]&&Tn.default.dirname(e[0])===e[0])&&e.shift(),e.every(Ln)}function Pn(t,e={}){const n=e.replacement||"!";if((Cn.test(n)||Mn.test(n))&&(0,m.throwError)("Replacement string cannot contain reserved filename characters","sanitizeFilename",m.ErrorCode.InvalidArgument),n.length>0){const e=/([<>:"/\\|?*\u0000-\u001F]){2,}/;t=t.replace(e,"$1")}if(t=(t=(t=(t=(t=t.normalize("NFD")).replace(Nn,n)).replace(Fn(),n)).replace(Rn(),n)).replace(In,""),n.length>0){"."===t[0]||"."!==t[0]||(t=n+t),"."===t[t.length-1]&&(t+=n)}t=On.test(t)?t+n:t;const r="number"==typeof e.maxLength?e.maxLength:jn;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 _n(t,e={}){const n=t.split(Tn.default.sep);let r;("/"===t[0]||n[0]&&Tn.default.dirname(n[0])===n[0])&&(r=n.shift());const s=n.map((t=>Pn(t,e)));return void 0!==r&&s.unshift(r),s.join(Tn.default.sep)}function Bn(t,e=1){let n="";for(;e--;){const e=Tn.default.extname(t);if(!e)break;n=e+n,t=Tn.default.basename(t,e)}return n}function zn(t){return t.split(".").length-1}var Vn=require("util-ex");function Un(t,e){if("string"!=typeof t)throw new m.CommonError("modelName must be a string","isModelNameMatched",m.ErrorCode.InvalidArgument);switch(typeof e){case"string":if((0,Vn.isRegExpStr)(e)){const n=(e=(0,Vn.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,Vn.isRegExpStr)(n)){const r=(e=(0,Vn.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 Dn(t){return Object.keys(t).filter((t=>Number.isNaN(Number(t))))}var Xn=require("lodash-es"),Jn=require("util-ex"),Gn=require("lodash-es"),Wn=require("util-ex");async function Hn(t,e,n){return Yn(fr(t,e,n),e,n)}function Kn(t){for(let e=1;e<t.length;e++)if(t[e]<=t[e-1])return!1;return!0}function Zn(t){if(t&&!Array.isArray(t)&&"object"==typeof t){const e=Object.entries(t),n=Object.keys(t),r=n.filter((t=>!isNaN(parseInt(t))));if(1===e.length)void 0!==t[0]&&(t=[t[0]]);else if(n.every((t=>!isNaN(parseInt(t))))&&Kn(n.map((t=>parseInt(t)))))t=Object.values(t);else if("0"===r[0]&&Kn(r.map((t=>parseInt(t))))){const n=e.filter((([t,e])=>isNaN(parseInt(t))));t=e.filter((([t,e])=>!isNaN(parseInt(t)))).map((([t,e])=>e));let r=0;const s=[];for(;r<n.length&&n[r][1]===t[r];)s.push(r),r++;for(;s.length;)n.splice(s.pop(),1);t={args:t,kvArgs:Object.fromEntries(n)}}else t={args:[],kvArgs:t}}return Array.isArray(t)&&(t={args:t}),t}function Qn(t){if(t&&!Array.isArray(t)&&"object"==typeof t){const e=Object.entries(t),n=Object.keys(t);1===e.length&&void 0!==t[0]?t=t[0]:n.every((t=>!isNaN(parseInt(t))))?t=n.sort(((t,e)=>parseInt(t)-parseInt(e))).map((e=>t[e])):2===e.length&&"0"===e[0][0]&&e[0][1]===e[1][1]&&(t=t[0])}return t}async function Yn(t,e,n){if(t.length){const r=await Promise.all(t.map(((t,r)=>lr(t,r,e,n)))),s=n?.returnArrayOnly;let i;if(r?.length){i=vr(`{${r.map((t=>t)).join(",")}}`,e)}return i&&!s&&(i=Qn(i)),i}}function tr(t,e,n,r){const[s,i]=t;if(!s&&"|"===i[0])return"choice: {"+function(t,e,n){const r=fr(t,e,{...n,delimiter:":"}),s={},i=r.map((([t,e],n)=>{if(t){const t=e.indexOf(":"),n=e.slice(0,t).trim();if(s[n])throw new Error("Only one "+n+" is allowed");return s[n]=!0,e}{if("|"===e[0]){if(s.items)throw new Error("Only one items is allowed");return s.items=!0,"items:["+function(t,e='"'){return t.map((t=>ir(t,e)))}(e.split("|").filter(Boolean))+"]"}const t=parseInt(e.trim());if(!isNaN(t)){if(s.maxPick)throw new Error("Only one maxPick is allowed");return s.maxPick=!0,"maxPick:"+t}if("random"===e||"ai"===e)return s.type=!0,'type:"'+e+'"';if(rr(e)){if(s.separator)throw new Error("Only one separator is allowed");return s.separator=!0,"separator:"+e}}}));return i}(i,n,r)+"}"}async function er([t,e],n,r,s){let i,o;if(r||(r={}),t){const t=e.split(":");i=t[0].trim(),o=t[1].trim()}else o=e,i=n+"";const a={template:o,data:{...(0,Gn.omitBy)(r,((t,e)=>!e||"_"===e[0]||"function"==typeof t)),...s?.templateData}};s?.templateFormat&&(a.templateFormat=s.templateFormat);const c=await N.formatIf(a);if(c)return o=rr(c)?c:JSON.stringify(c),i+":"+o}async function nr(t,e,n,r){let s=tr(t,0,n,r);return s||(s=await er(t,e,n,r)),s}function rr(t){const e=t[0];return('"'===e||"'"===e)&&t[t.length-1]===e}function sr(t,e=['""',"''","{}"]){return e.some((e=>t[0]===e[0]&&t[t.length-1]===e[1]))}function ir(t,e='"'){return rr(t)?t:e+t+e}function or(t){return'"'+t.replace(/(?<!\\)"(?!\\)/g,'\\"')+'"'}var ar=["true","false","null","undefined","NaN","Infinity"];async function cr(t,e,n){const r=(0,Wn.newFunction)("async expression",[],`return ${t};`,kr(e));let s;try{s=await r.call(this)}catch(t){if(n||!(t instanceof ReferenceError))throw t}switch(typeof s){case"number":case"boolean":case"undefined":return s;case"function":return r.toString();default:return JSON.stringify(s)}}async function ur(t,e,n){let r=t;if(["true","false"].includes(t.toLowerCase()))r=r.toLowerCase();else if(!(s=t,sr(s)||!Number.isNaN(parseFloat(s))||ar.includes(s)||gr(s)||e&&void 0!==(0,Gn.get)(e,t)||gr(t)))try{r=n?.skipExpression?or(t):await cr.call(this,t,e,n?.preserveUnresolvedName)}catch(e){r=or(t)}var s;return r}async function lr(t,e,n,r){const[s,i]=t,o=r?.argProcessor,a=r?.ignoreIndexNamed;if("function"==typeof o){const s=await o(t,e,n,r);if(s)return s}if(s){const t=i.indexOf(":");return i.slice(0,t).trim()+":"+await ur(i.slice(t+1).trim(),n,r)}{const t=i.trim();if(n&&void 0!==(0,Gn.get)(n,t)){return(a?"":e+":"+t+",")+'"'+t+'":'+t}return e+":"+await ur(i.trim(),n,r)}}function fr(t,e,n){const r=n?.delimiter??",",s=n?.assigner??"=";let i=[],o=!1,a="",c="",u=!1,l="";for(let e=0;e<t.length;e++){const n=t[e];if(n!==r||o||l)if("\\"===n)c+=n,e++,c+=t[e];else if("("!==n&&"["!==n||o)if(l&&n===l)l="",c+=n;else if("{"!==n||o)'"'===n||"'"===n?(o&&n===a?o=!1:o||(o=!0,a=n),c+=n):n!==s||o||u||!/^[\p{L}\p{N}_ ]+$/u.test(c)?c+=n:(c+=":",u=!0);else{let r,s=e,i=!1,o="",a=-1;for(;s<t.length&&("}"!==(r=t[s])||i||a>0);)"\\"===r?s++:"{"!==r||i?"}"!==r||i?'"'!==r&&"'"!==r||(i&&n===o?i=!1:i||(i=!0,o=n)):a--:a++,s++;s<t.length&&(c+=t.substring(e,s+1),e=s)}else l="("===n?")":"]",c+=n;else c=c.trim(),c.endsWith(":")&&(c+="undefined"),i.push([u,c]),c="",u=!1}return c&&(c=c.trim(),c.endsWith(":")&&(c+="undefined"),i.push([u,c])),i}async function hr(t,e,n){const r=t.match(/^([^(]+)(?:\((.*)\))?$/);if(!r){if(n?.raiseError)throw new Error("Invalid command format");return}const[,s,i]=r;let o;return i&&(o=await Hn(i,e,n)),{command:s.trim(),args:o}}var pr="__PlacEhoLdeR_";function wr(t,e){let n=e?.startChar?Array.isArray(e.startChar)?e.startChar:[e.startChar]:['"',"'"],r=e?.endChar?Array.isArray(e.endChar)?e.endChar:[e.endChar]:n;if(n.length!==r.length)throw new Error("start and end characters must have the same length");const s=e?.placeholder??pr,i=n.every(((t,e)=>t===r[e])),o=e?.placehoders??[];if(i){n=n.map((t=>"\\"+t));const e=new RegExp(`(?<!\\\\)(${n.join("|")}).*?(?<!\\\\)\\1`);let r;for(;null!==(r=e.exec(t));){const e=`${s}${o.length}`;t=t.replace(r[0],e),o.push(r[0])}}else{n=n.map((t=>"\\"+t)),r=r.map((t=>"\\"+t));for(let e=0;e<n.length;e++){const i=new RegExp(`(?<!\\\\)${n[e]}.*?(?<!\\\\)${r[e]}`);let a;for(;null!==(a=i.exec(t));){const e=`${s}${o.length}`;t=t.replace(a[0],e),o.push(a[0])}}}return[t,o]}function dr(t,e,n){const r=n?.placeholder??pr;return e.reduce(((t,e,n)=>t.replace(new RegExp(r+n,"g"),e)),t)}var mr="[a-zA-Z_$][a-zA-Z_\\d$]*",yr=new RegExp(`^\\s*(\\(\\s*\\)|${mr}|\\(${`${mr}\\s*(,\\s*${mr})*`}\\))\\s*=>`);function gr(t){return yr.test(t)}async function br(t,e){if(e&&(e=kr(e)),e&&(t=t.trim()).startsWith("{")&&t.endsWith("}")){return await Hn(t.slice(1,-1),e,{assigner:":",ignoreIndexNamed:!0})}return vr(t,e)}function vr(t,e){if(e&&(e=kr(e)),e){const n=Object.keys(e);if(n.length){const r=Object.values(e);let s=0;for(;s++<100;)try{return(0,Jn.newFunction)("expression",n,`return ${t}`)(...r)}catch(t){if(!(t instanceof ReferenceError))throw t;{const e=/(.+)\s+is not defined/.exec(t.message);if(!e)throw t;n.push(e[1]),r.push(void 0)}}}}return(0,Jn.newFunction)("expression",[],`return ${t}`)()}var Er=/^[a-zA-Z_$][0-9a-zA-Z_$.]*$/,xr=t=>Er.test(t);function kr(t){if(t){const e=Object.keys(t),n=e.length,r=e.filter((e=>xr(e)&&null!==t[e]));if(n===r.length)return t;if(r.length)return t=(0,Xn.pick)(t,r)}}function Sr(t){return t?$r(t,[],{dot:""}):[]}function $r(t,e,{dot:n=".",visited:r=new Set}={}){return r.has(t)?[e.join("")]:Array.isArray(t)?(r.add(t),t.flatMap(((t,n)=>$r(t,[...e,`[${n}]`],{dot:".",visited:r})))):(s=t)&&s.constructor===Object?(r.add(t),Object.entries(t).flatMap((([t,s])=>$r(s,[...e,n+t],{dot:".",visited:r})))):[e.join("")];var s}function Ar(t){if(t<2)throw new m.CommonError("repetitionThreshold must be greater than 1","createEndWithRepetitionDetector",m.ErrorCode.InvalidArgument);const e=new RegExp(`([\\S\\s]+)(\\1{${t-1},})$`);return function(t){return e.exec(t)}}var Tr=c(require("path")),Cr=c(require("fs")),Or=c(require("mime-type/with-db")),jr=c(require("jschardet"));function Nr(t){const e=Cr.statSync(t,{throwIfNoEntry:!1});return e?.isFile()}function Ir(t,e,n,r){const s=r?.signal,i=r?.exclude;let o;if(Tr.default.isAbsolute(t)?o=Nr(t)?t:Mr(Tr.default.basename(t),[Tr.default.dirname(t)],{extNames:n,exclude:i,signal:s}):(e||(e=["."]),o=Mr(t,e,{extNames:n,exclude:i,signal:s})),!o)throw new m.NotFoundError(t,"loadFileFromPaths");{const t=o;o=Cr.readFileSync(o),r&&(r.filepath=t)}return o}function Mr(t,e,{extNames:n,signal:r,exclude:s=[]}){let i;const o=n?n.map((e=>Bn(t,zn(e)))):void 0;"string"==typeof s&&(s=[s]);for(const a of e){if(r?.aborted)throw r.reason;const e=Tr.default.resolve(a,t);if(o)for(let t=0;t<o.length;t++){const r=e+(o[t]!==n[t]?n[t]:"");if(!s.includes(r)&&Nr(r)){i=r;break}}else if(!s.includes(e)&&Nr(e)){i=e;break}}return i}function Fr(t,e,n,r,s){let i;"string"==typeof r?(i=r,r=void 0):i=r?.encoding;return Rr(Ir(t,e,n,r),i)}function Rr(t,e){void 0===e&&(e=zr(t)??"utf8");return new TextDecoder(e).decode(t)}function Lr(t,e){const n=[],r="string"==typeof t?[{dir:t,level:0}]:[...t.map((t=>({dir:t,level:0})))],s=new Set,i=e?.signal,o=e?.isFileMatched,a=e?.level;let c=0;for(;r.length>0;){if(i?.aborted)throw i.reason;const t=r.pop(),e=qr(t.dir),u=Tr.default.resolve(e);if(s.has(u))continue;s.add(u);const l=Cr.statSync(e,{throwIfNoEntry:!1});if(l?.isDirectory()){c=t.level+1;const s=Cr.readdirSync(e,{withFileTypes:!0});for(let t=0;t<s.length;t++){let i=s[t],u=Tr.default.join(e,i.name);if(i.isSymbolicLink()){const t=Tr.default.dirname(u);u=Cr.readlinkSync(u),u=Tr.default.resolve(t,u),i=Cr.statSync(u)}i.isDirectory()?(!a||c<a)&&(o&&!o(u,i)||r.push({dir:u,level:c})):!i.isFile()||o&&!o(u,i)||n.includes(u)||n.push(u)}}}return n}function qr(t){const e=Cr.lstatSync(t,{throwIfNoEntry:!1});return e?.isSymbolicLink()&&(t=Cr.readlinkSync(t)),t}async function Pr(t,e){return $n(ReadableStream.from(Cr.createReadStream(t)),e)}async function _r(t){const e=Tr.default.basename(t);t=Tr.default.resolve(t);const n=await Cr.promises.stat(t),r=n.mtime,s=n.ctime,i=n.size,o=Br(i),a=await Pr(t,{hashAlgo:o}),c=Or.default.lookup(t);return{name:e,mtime:r,ctime:s,size:i,hash:wn[o]+":"+a,mimeType:c,id:"file://"+t}}function Br(t){let e=111;return t<=2048?e=112:t<=1048576?e=111:t<=10485760?e=113:t>10485760&&(e=10),e}function zr(t,e){return jr.default.detect(t,e).encoding}var Vr=require("fs"),Ur=c(require("path")),Dr=require("load-config-file"),Xr=require("yaml"),Jr=require("yaml-types"),Gr=require("mime-type/with-db"),Wr=[Jr.regexp];function Hr(t){Array.isArray(t)||(t=[t]);for(const e of t){-1===Wr.indexOf(e)&&Wr.push(e)}}function Kr(t,e){if(e)if(e.customTags){if(Array.isArray(e.customTags))e.customTags=Wr.concat(e.customTags);else if("function"==typeof e.customTags){const t=e.customTags;e.customTags=e=>t(Wr.concat(e))}}else e.customTags=Wr;else e={customTags:Wr};return(0,Xr.parse)(t,e)}function Zr(t,e){if(e)if(e.customTags){if(Array.isArray(e.customTags))e.customTags=Wr.concat(e.customTags);else if("function"==typeof e.customTags){const t=e.customTags;e.customTags=e=>t(Wr.concat(e))}}else e.customTags=Wr;else e={customTags:Wr};return(0,Xr.stringify)(t,e)}function Qr(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,Vr.readdirSync)(t,{withFileTypes:!0,recursive:!0});for(const r of n){const n=Ur.default.join(t,r.name);r.isFile()&&e(n,r)}}(t,((t,e)=>{if(s?.includes(t))return;const o=Ur.default.extname(t),a=(0,Vr.statSync)(t);if(i.includes(o)){if(r?.hasOwnProperty(t)&&a.mtimeMs<=r[t])return;n.push(t)}})),n}function Yr(t,e){return Qr(t,e).map((t=>Dr.Config.loadSync(t))).filter((t=>void 0!==t))}function ts(t,e,n=1){"."===t[0]&&n++;const r=Bn(t,n);(!r||r.split(".").length<=1)&&(t+=".yaml");const s=Gr.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=Zr(e)}const i=Ur.default.dirname(t);return(0,Vr.existsSync)(i)||(0,Vr.mkdirSync)(i,{recursive:!0}),(0,Vr.writeFileSync)(t,e,{encoding:"utf8"}),t}function es(t){t instanceof Date&&(t=t.toISOString());return function(t,e){return t?`'${e}'`:String(e)}("string"==typeof t,t)}function ns(t,e){return t.map((t=>is(t,e))).join(" AND ")}function rs(t,e){return t.map((t=>is(t,e))).join(" OR ")}function ss(t,e){const n=[];return Object.keys(e).forEach((r=>{const s=e[r];switch(r){case"$lt":case"<":n.push(`${t} < ${es(s)}`);break;case"<=":case"$lte":n.push(`${t} <= ${es(s)}`);break;case"$gt":case">":n.push(`${t} > ${es(s)}`);break;case"$gte":case">=":n.push(`${t} >= ${es(s)}`);break;case"$ne":case"!=":n.push(`${t} != ${es(s)}`);break;case"=":case"$eq":n.push(`${t} = ${es(s)}`);break;case"$in":n.push(`${t} IN (${s.map((t=>es(t))).join(", ")})`);break;case"$nin":n.push(`${t} NOT IN (${s.map((t=>es(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 is(t,e){const n=[];if("function"!=typeof e&&(e=t=>t),Array.isArray(t))n.push(ns(t,e));else for(const[r,s]of Object.entries(t))if("$and"===r)n.push(`(${ns(t[r],e)})`);else if("$or"===r)n.push(`(${rs(t[r],e)})`);else{const t=typeof s;if(null==s)n.push(`${e(r)} IS NULL`);else if(s instanceof Date)n.push(`${e(r)}='${s.toISOString()}'`);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(ss(e(r),s))}return n.length>1?n.join(" AND "):n[0]}function os(t){const e=t.indexOf("://");if(e>0)return t.substring(0,e)}function as(t,e=0){let n,r=t*10**e;return t>=1e12?(r=Math.round(r/1e12),n="T"):t>=1e9?(r=Math.round(r/1e9),n="B"):t>=1e6?(r=Math.round(r/1e6),n="M"):t>=1e3?(r=Math.round(r/1e3),n="K"):(r=Math.round(r),n=""),r/=10**e,r.toFixed(e)+n}function cs(t){const e=t.match(/^\s*[+]?(\d+(?:[.]\d+)?)\s*([TBMK])?\s*$/i);if(!e)throw new m.CommonError("Invalid formatted parameter size string.","scaleToSize",m.ErrorCode.InvalidArgument);const n=parseFloat(e[1]),r=e[2]?.toLowerCase();switch(r){case"t":return 1e12*n;case"b":return 1e9*n;case"m":return 1e6*n;case"k":return 1e3*n;default:return n}}function us(t,e){const n=e?.level||0,r=e?.visiting||new Set,s=e?.objectTag||"*",i=e?.arrayTag||"-";let o=[];const a=" ".repeat(2*n);if(null!=t)switch(typeof t){case"object":r.has(t)?o=["[Circular]"]:(r.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":" ")+us(t,{level:n+1,visiting:r})}}Dr.Config.register([".yml",".yaml"],Kr),Dr.Config.register([".json"],(function(t){return JSON.parse(t)}));var ls=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}},fs=require("util-ex"),hs=require("events-ex");function ps(t=0){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 ws=class extends Array{constructor(t,e){Array.isArray(t)?(super(...t),this._length=t.length,t=void 0):(super(),this._length=0),this._capacity=ps(t),this._front=0,this._disableAutoResize=e}push(t){let e=this._length;this.checkCapacity(e+1);const n=this._front+e&this._capacity-1;return this[n]=t,++e<=this._capacity&&(this._length=e),n}unshift(t){let e=this._length;this.checkCapacity(++e);const n=this._capacity,r=(this._front-1&n-1^n)-n;return this[r]=t,this._front=r,e<=this._capacity&&(this._length=e),r}pop(t){let e=this._length;if(0===e)return;let n=this._front+e-1&this._capacity-1,r=this[n];for(;--e>0&&t&&null==r;)n--,r=this[n];return this[n]=void 0,this._length=e,r}shift(t){let e=this._length;if(0===e)return;let n=this._front,r=this[n];for(;--e>0&&t&&null==r;)n=n+1&this._capacity-1,r=this[n];return this[n]=void 0,this._front=n+1&this._capacity-1,this._length=e,r}get size(){return this._length}get(t){let e;if(t===(0|t)){const n=this._length;t<0&&(t+=n),t>=0&&t<n&&(e=this[this._front+t&this._capacity-1])}return e}peekBack(){const t=this._length;if(0===t)return;return this[this._front+t-1&this._capacity-1]}peekFront(){if(0!==this._length)return this[this._front]}clear(){const t=this._length,e=this._front,n=this._capacity;for(let r=0;r<t;++r)this[e+r&n-1]=void 0;this._length=0,this._front=0}isEmpty(){return 0===this._length}removeAt(t){const e=this._length;if(t<0||t>=e)return;const n=this._front,r=this._capacity-1,s=n+t&r,i=this[s];if(t<e/2)this.copyWithin(n+1&r,n,n+t&r),this[n]=void 0,this._front=n+1&r;else{this.copyWithin(s,s+1&r,n+e&r);this[n+e-1&r]=void 0}return this._length=e-1,i}checkCapacity(t){this._capacity<t&&!this._disableAutoResize&&this.resizeTo(ps(1.5*this._capacity+16))}resizeTo(t){const e=this._capacity;this._capacity=t;const n=this._front,r=this._length;if(n+r>e){!function(t,e,n,r,s){for(let i=0;i<s;++i)n[i+r]=t[i+e],t[i+e]=void 0}(this,0,this,e,n+r&e-1)}}},ds=require("@isdk/common-error"),ms=32;function ys(t){return"function"==typeof t}function gs(){return"1"}var bs=class{constructor(t={}){const{initFn:e=gs,pauseFn:n,resumeFn:r,capacity:s=ms}=t;if(ys(n)!==ys(r))throw new Error("pauseFn and resumeFn must be both set for pausing");this.waiting=new ws(s),this.emitter=new hs.EventEmitter,this.useDefaultTokens=e===gs,this.pauseFn=n,this.resumeFn=r,this.initTokenFn=e,this.paused=!1,this._activeCount=0,this.initFree(t),this.init(t)}initFree(t){this.free=this.initTokenFn()}onReleased(t){const e=t?.token,n=this.waiting.shift(!0);n?this._dispatchTask(n,t):(this.resumeFn&&this.paused&&(this.paused=!1,this.resumeFn()),this.unlock(e))}init(t){this.emitter.on("release",(t=>{this.onReleased(t)}))}_newReleaser(t){let e=!1;const n=()=>{e||(e=!0,this.release(t))};return t&&Object.assign(n,t),n}_dispatchTask(t,e){const{resolve:n}=t;n(this._newReleaser(e))}lock(t){let e=this.free;if(e)return this.free=void 0,e}unlock(t){this.free=this.useDefaultTokens?"1":t??this.initTokenFn()}tryAcquire(t){return this.lock(t)}async acquire(t){this._activeCount++;const e=t?.signal,n=t=>{this.pauseFn&&!this.paused&&(this.paused=!0,this.pauseFn());const n=this.waiting.push(t),r=t.reject;return e&&e.addEventListener("abort",(()=>{this.waiting[n]=void 0;const t=e.reason instanceof Error?e.reason:new ds.AbortError(e.reason||"aborted");e.alreadyRejected=!0,r(t)})),n};let r=this.tryAcquire(t);const s=r&&(0,fs.isAsync)(r),i=e=>new Promise(((r,s)=>{const i={...t,resolve:r,reject:s,token:e};void 0===e?n(i):this._dispatchTask(i,{...t,token:e})}));return s?r.then((t=>i(t))):i(r)}release(t){this._activeCount--,this.emitter.emit("release",t)}drain(){const t=[this.acquire()];return Promise.all(t)}abort(t){let e;for(;e=this.waiting.shift(!0);)e.reject(new ds.AbortError(t))}get activeCount(){return this._activeCount}get pendingCount(){return this.waiting.size}},vs=class extends bs{constructor(t,e){if("number"==typeof t)(e=e||{}).maxConcurrency=t;else{if("number"!=typeof(e=t).maxConcurrency)throw new Error("maxConcurrency must be set");t=e.maxConcurrency}super(e),this.maxConcurrency=e.maxConcurrency,e.isReadyFn&&(this.isReady=e.isReadyFn)}initFree(t){const e=t.maxConcurrency=Math.max(1,t.maxConcurrency);this.free=new ws(e);for(let t=0;t<e;t++)this.free.push(this.initTokenFn())}tryAcquire(t){let e=this.isReady;if(e&&(0,fs.isAsync)(e)){return e instanceof Promise||(e=e()),e.then((e=>{if(e)return this.lock(t)}))}if(!e||e())return this.lock(t)}unlock(t){this.free.push(this.useDefaultTokens?"1":t??this.initTokenFn())}lock(t){return this.free.pop()}drain(){const t=new Array(this.maxConcurrency);for(let e=0;e<this.maxConcurrency;e++)t[e]=this.acquire();return Promise.all(t)}};function Es(t,{timeUnit:e=1e3,uniformDistribution:n=!1}={}){const r=new vs(n?1:t),s=n?e/t:e;return async function(){await r.acquire(),setTimeout((()=>r.release()),s)}}var xs,ks=require("@isdk/common-error"),Ss=class{constructor(){this._isSignaled=!1,this.waitQueue=[]}get signaled(){return this._isSignaled}signal(t){if(this._isSignaled)return;this._isSignaled=!0,this._signalValue=t;const e=this.waitQueue.slice();for(this.waitQueue.length=0;e.length>0;){const t=e.shift();t?.resolve(this._signalValue)}}reset(){this._isSignaled=!1,this._signalValue=void 0,this.waitQueue.length=0}abort(t){if(this.waitQueue.length){const e=this.waitQueue.slice();this.waitQueue.length=0;const n=new ks.AbortError(t);for(;e.length>0;){const{reject:t}=e.shift();t(n)}}}async wait(){return new Promise(((t,e)=>{this._isSignaled?t(this._signalValue):this.waitQueue.push({resolve:t,reject:e})}))}},$s=require("custom-ability"),As=require("util-ex"),Ts=0,Cs=1,Os=2,js=(t=>(t[t.MultiTask=Ts]="MultiTask",t[t.Cancelable=Cs]="Cancelable",t[t.Priority=Os]="Priority",t))(js||{}),Ns=((xs=Ns||{})[xs.MultiTask=1<<Ts]="MultiTask",xs[xs.Cancelable=1<<Cs]="Cancelable",xs[xs.Priority=1<<Os]="Priority",xs),Is=class extends AbortController{constructor(t){super(),(0,As.defineProperty)(this,"parent",t)}abort(t,e){this.signal.aborted||("string"==typeof t&&(t=new m.AbortError(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 m.AbortError(e.reason||"aborted")}}},Ms=class{get maxTaskConcurrency(){return this._maxTaskConcurrency}get semaphore(){return this.getSemaphore()}getSemaphore(t=this._isReadyFn){let e=this._maxTaskConcurrency,n=this.__task_semaphore;return e>0&&!n&&(t&&(t=t.bind(this)),n=this.__task_semaphore=new vs(e-1,{isReadyFn:t})),n}static hasAsyncFeature(t){const e=this.prototype;let n=e.asyncFeatures;return e._asyncFeatures&&(n|=e._asyncFeatures),ls.has(n,t)}hasAsyncFeature(t){let e=this.asyncFeatures;return this._asyncFeatures&&(e|=this._asyncFeatures),ls.has(e,t)}isAborted(t){const e=this.hasAsyncFeature(Ts);let n=this.__task_aborter;if(n&&e){if(null==t)throw new m.CommonError("Missing taskId",this.name+".isAborted",m.ErrorCode.InvalidArgument);n=n[t]}return!n||n.signal.aborted}getRunningTask(t){const e=this.hasAsyncFeature(Ts);let n=this.__task_aborter;if(n&&e){if(null==t)throw new m.CommonError("Missing taskId",this.name+".getRunningTask",m.ErrorCode.InvalidArgument);n=n[t]}return n?.signal.aborted&&(e?this.__task_aborter[t]=void 0:this.__task_aborter=void 0,n=void 0),n}getRunningTaskCount(){let t;if(this.hasAsyncFeature(Ts)){const e=this.__task_aborter;t=e&&Object.entries(e).filter((([t,n])=>{if(!n?.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 n=this.super,r=this.self||this;return t=n?n.call(r,t):this._generateAsyncTaskId(t,e)}createAborter(t,e,n=!0){const r=this.hasAsyncFeature(Ts);if(!r&&n&&this.getRunningTask())throw new m.CommonError("The task is running",this.name,m.ErrorCode.TooManyRequests);const s=t?.aborter||new Is(this);if(!(s instanceof Is)){if(!(s instanceof AbortController))throw new m.CommonError("aborter should be an AbortController",this.name,m.ErrorCode.InvalidArgument);Object.setPrototypeOf(s,new Is(this))}if(r){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 n=this.super,r=this.self||this;n?n.call(r,t,e):r._cleanMultiTaskAborter(t,e)}cleanTaskAborter(t){if(this.hasAsyncFeature(Ts)){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,n){const r=this.createAborter(e,n?.taskId,n?.raiseError);void 0===e&&(e={}),"object"==typeof e&&(e.aborter=r);let s=t(e,r).then((t=>{if(t&&t instanceof ReadableStream){const e=()=>{this.cleanTaskAborter(r)},n=nn({onStart:t=>{(0,As.defineProperty)(r,"streamController",t)},onFinal:e,onError:e,onTransform:(t,e)=>(t&&"object"==typeof t&&(t.taskId=r.id),t)});t=t.pipeThrough(n)}else this.cleanTaskAborter(r);return t})).catch((t=>{throw this.cleanTaskAborter(r),t})).finally((()=>{r.timeoutId&&(clearTimeout(r.timeoutId),r.timeoutId=void 0)}));return s.task=r,s}runAsyncCancelableTask(t={},e,n){let r=this.createTaskPromise(e,t,n);const s=this.getSemaphore(n?.isReadyFn);if(s){const t=r,e=t.task;r=s.acquire({signal:e.signal}).then((()=>t)).finally((()=>{s.release()})),r.task=e}return r}abort(t,e){let n=this.__task_aborter;if(n){const r=n;if(this.hasAsyncFeature(Ts)){const t=e?.taskId;if(null==t)throw new m.CommonError("Missing data.taskId",this.name+".abort",m.ErrorCode.InvalidArgument);n=n[t],this.cleanMultiTaskAborter(t,r)}else this.__task_aborter=void 0;n&&!n.signal.aborted&&n.abort(t,e)}}};Ms.prototype.generateAsyncTaskId=function(t,e){return this._generateAsyncTaskId(t,e)},Ms.prototype.cleanMultiTaskAborter=function(t,e){return this._cleanMultiTaskAborter(t,e)};var Fs=(0,$s.createAbilityInjector)(Ms,"abort",{afterInjection:function(t,e){let n=t.prototype._asyncFeatures||0;n|=Ns.Cancelable,e&&(e.asyncFeatures&&(n|=e.asyncFeatures),e.maxTaskConcurrency>0&&(t.prototype._maxTaskConcurrency=e.maxTaskConcurrency),e.isReadyFn&&"function"==typeof e.isReadyFn&&(t.prototype._isReadyFn=e.isReadyFn)),t.prototype._asyncFeatures=n}});function Rs(t,e){const n=e.global?e:new RegExp(e.source,`${e.flags}g`);let r,s=0;for(;null!==(r=n.exec(t));)s++;return s}var Ls=c(require("memoizee")),qs=require("json-canonicalize");function Ps(t,e){var n;void 0!==e?.promise||!function(t){return"function"==typeof t&&"AsyncFunction"===t.constructor.name}(t)&&(!(n=t)||"object"!=typeof n&&"function"!=typeof n||"function"!=typeof n.then)||(e={promise:!0,...e}),void 0===e?.length&&(e={length:!1,...e});const r=e?.normalizer;return(0,Ls.default)(t,{...e,normalizer:t=>{if(r){const e=r(t);if("string"===e)return e;e&&(t=e)}return En((0,qs.canonicalize)(t))}})}var _s=c(require("net"));async function Bs(t,e=10){return new Promise(((n,r)=>{void 0===t?t=0:("string"==typeof t&&(t=parseInt(t)),t>=0||(t=0));const s=_s.default.createServer();s.on("error",(n=>{"EADDRINUSE"===n.code&&(t++,--e>0)?s.listen(t):r(n)})),s.on("listening",(async()=>{const t=s.address().port;s.close(),n(t)})),s.listen(t)}))}var zs=c(require("path")),Vs=require("pkg-dir");function Us(t){const e=(0,Vs.packageDirectorySync)({cwd:t});if(e)return e;const n=t.split(zs.default.sep);let r=n.lastIndexOf("dist");if(r>0)return n.slice(0,r).join(zs.default.sep);if(r=n.lastIndexOf("src"),r>0)return n.slice(0,r).join(zs.default.sep);throw new Error("can not find package directory")}var Ds=c(require("path"));function Xs(t,e){try{const n=Ds.default.relative(Ds.default.resolve(t),Ds.default.resolve(e));return!n.startsWith("..")&&!Ds.default.isAbsolute(n)}catch{return!1}}function Js(t,e){return e?.some((e=>Xs(e,t)))}function Gs(t,e){for(const n of e)Js(n,t)||t.push(n);return t}var Ws=require("util-ex");function Hs(t){return(0,Ws.isRegExpStr)(t)||(0,Ws.isRegExp)(t)}function Ks(t){return t.replace(/\x1B[[(?);]{0,2}(;?\d)*./g,"")}var Zs=c(require("path")),Qs=require("url"),Ys=require("@xenova/transformers"),ti=(0,Qs.fileURLToPath)(l),ei=Zs.default.dirname(ti),ni=Zs.default.join(Us(ei),".cache"),ri=new Map,si={"deepseek-ai/DeepSeek-V2-Lite-Chat":"deepseek2","Qwen/Qwen2.5-0.5B":"Qwen2.5","Xenova/gpt-4":"gpt-4 / gpt-3.5-turbo / text-embedding-ada-002","Xenova/text-davinci-003":"text-davinci-003 / text-davinci-002","Xenova/gpt-3":"gpt-3","Xenova/grok-1-tokenizer":"Grok-1","Xenova/claude-tokenizer":"Claude","Xenova/mistral-tokenizer-v3":"Mistral v3","Xenova/mistral-tokenizer-v1":"Mistral v1","Xenova/gemma-tokenizer":"Gemma","Xenova/gemma2-tokenizer":"Gemma2","Xenova/llama3-tokenizer-new":"Llama 3","unsloth/Llama-3.2-1B-Instruct":"Llama 3.2","Xenova/llama-tokenizer":"LLaMA / Llama 2","Xenova/c4ai-command-r-v01-tokenizer":"Cohere Command-R","Xenova/t5-small":"T5","Xenova/bert-base-cased":"bert-base-cased"},ii={deepseek2:"deepseek-ai/DeepSeek-V2-Lite-Chat","qwen2.5":"Qwen/Qwen2.5-0.5B","gpt-4":"Xenova/gpt-4","gpt-3.5-turbo":"Xenova/gpt-4","text-embedding-ada-002":"Xenova/gpt-4","text-davinci-003":"Xenova/text-davinci-003","text-davinci-002":"Xenova/text-davinci-003","gpt-3":"Xenova/gpt-3","grok-1":"Xenova/grok-1-tokenizer",claude:"Xenova/claude-tokenizer",mistral:"Xenova/mistral-tokenizer-v3",mistral3:"Xenova/mistral-tokenizer-v3",mistral1:"Xenova/mistral-tokenizer-v1",gemma:"Xenova/gemma-tokenizer",gemma2:"Xenova/gemma2-tokenizer",llama3:"Xenova/llama3-tokenizer-new",llama2:"Xenova/llama-tokenizer",llama:"Xenova/llama-tokenizer","llama3.2":"unsloth/Llama-3.2-1B-Instruct","cohere-command-r":"Xenova/c4ai-command-r-v01-tokenizer",t5:"Xenova/t5-small","bert-cased":"Xenova/bert-base-cased"};async function oi(t){let e=ri.get(t);return e||(e=Ys.AutoTokenizer.from_pretrained(t,{cache_dir:ni}),ri.set(t,e)),e}async function ai(t,e="qwen2.5"){ii[e]&&(e=ii[e]);return(await oi(e)).encode(t)}async function ci(t,e="qwen2.5"){return(await ai(t,e)).length}function ui(t,e){const n=e?.capitalize??!0;let r=e?.delimiter??/[_-]/g;r instanceof RegExp&&(r.flags.includes("g")||(r=new RegExp(r.source,r.flags+"g")));let s=(t=t.replace(r," ")).split(" ").map((t=>t.trim())).filter(Boolean);return n&&(s=s.map((t=>t.charAt(0).toUpperCase()+t.slice(1)))),t=s.join(" ")}async function li(t,e){let n,r=1984,s=!0,i=!1,o=!0,a=ci,c=!0;if(e&&(n=e.modelId,e.size>=0&&(r=e.size),void 0!==e.corrected&&(s=e.corrected),void 0!==e.completeSentence&&(i=e.completeSentence),void 0!==e.truncLastSection&&(o=e.truncLastSection),"function"==typeof e.countLLMTokens&&(a=e.countLLMTokens),void 0!==e.bySentence&&(c=e.bySentence)),!c)throw new m.NotImplementationError("truncateToTokenLimit only implemented by sentence","truncateToTokenLimit");if(r>0){let c=await a(t,n);const u=e?.sentences??be(t,e);if(c>r)for(c=await a(u.join("\n"),n);c>r&&u.length;){const e=u.pop();if(e){if(c-=await a(e+"\n",n),i||s)t=u.join("\n");else{const n=t.lastIndexOf(e);if(-1===n)throw new m.CommonError(`Can not find sentence: ${e}`,"truncateContentToTokenLimit");t=t.slice(0,n)}if(c<=1)throw new m.CommonError(`Can not truncate content to fit within the token limit: ${r}`,"truncateContentToTokenLimit");if(c<=r&&o){const e=u[u.length-1];if(e&&ke(e)){if(c-await a(e,n)>9){const n=t.lastIndexOf(e);if(-1===n)throw new m.CommonError(`Can not find sentence: ${e}`,"truncateContentToTokenLimit");t=t.slice(0,n).trimEnd()}}}}else c--}else t=u.join("\n")}if(!t)throw new m.CommonError(`Can not truncate content to fit within the token limit: ${r}`,"truncateContentToTokenLimit");return t}async function fi(t,e){let n,r=1984,s=!0,i=ci,o=!0;if(e&&(n=e.modelId,e.size>=0&&(r=e.size),void 0!==e.truncLastSection&&(s=e.truncLastSection),"function"==typeof e.countLLMTokens&&(i=e.countLLMTokens),void 0!==e.bySentence&&(o=e.bySentence)),!o)throw new m.NotImplementationError("truncateToTokenLimit only implemented by sentence","truncateToTokenLimit");if(r>0){const e=(t=t.slice()).join("\n");let o=await i(e,n);if(o>r)for(;o>r&&t.length;){const e=t.pop();if(e){if(o-=await i(e,n),o<=1)throw new m.CommonError(`Can not truncate content to fit within the token limit: ${r}`,"truncateContentToTokenLimit");if(o<=r&&s){const e=t[t.length-1];if(e&&ke(e)){o-await i(e,n)>9&&t.pop()}}}}}if(!t.length)throw new m.CommonError(`Empty. Can not truncate content to fit within the token limit: ${r}`,"truncateContentToTokenLimit");return t}async function hi(t,e){let n,r=1984,s=ci;if(e&&(n=e.modelId,"function"==typeof e.countLLMTokens&&(e.size>=0&&(r=e.size),s=e.countLLMTokens)),r>0){await s(t,n)}}var pi=c(require("fs"));async function*wi(t,e){const n=(e={...e,completeSentence:!1,corrected:!1}).size??1984,r=e.modelId,s=e.metaInfo?.size??(await pi.default.promises.stat(t)).size;let i=Math.trunc(s/2);if(i<=n){let s=Rr(await pi.default.promises.readFile(t));if(i=await ci(s,r),i<=n)yield s;else do{const t=await li(s,{...e,modelId:r,size:n});yield t,s=s.slice(t.length)}while(s)}else{const s=ReadableStream.from(pi.default.createReadStream(t)).getReader();let i="";for(;;){const{done:t,value:o}=await s.read();if(t)break;i+=Rr(o);const a=be(i,e);let c=a.pop();if(c){const t=i.lastIndexOf(c);c=i.slice(t),i=i.slice(0,t)}if(i.length>=n){const t=await li(i,{...e,modelId:r,size:n,sentences:a});i=i.slice(t.length),yield t}for(;i.length>n;){const t=be(i,e),s=await li(i,{...e,modelId:r,size:n,sentences:t});i=i.slice(s.length),yield s}void 0!==c&&(i+=c)}for(;i;){const t=be(i,e),s=await li(i,{...e,modelId:r,size:n,sentences:t});i=i.slice(s.length),yield s}}}async function*di(t,e){const n=e?.size??1984,r=e?.modelId,s=e?.metaInfo?.size??(await pi.default.promises.stat(t)).size;let i=Math.trunc(s/2);if(i<=n){let s=Rr(await pi.default.promises.readFile(t));if(i=await ci(s,r),i<=n)yield be(s,e);else{let t=be(s,e);do{const s=await fi(t,{...e,modelId:r,size:n});yield s,t=t.slice(s.length)}while(t.length)}}else{const s=ReadableStream.from(pi.default.createReadStream(t)).getReader();let i="";const o=e?.completeSentence,a=e?.corrected,c=!o&&!a;let u;for(;;){const{done:t,value:o}=await s.read();if(t)break;i+=Rr(o),u=be(i,e);let a=u.pop();if(i.length>=n){const t=await fi(u,{...e,modelId:r,size:n});i=c?i.slice(t.length):u.join("\n"),u=u.slice(t.length),i=u.join("\n"),yield t}for(;i.length>n;){const t=await fi(u,{...e,modelId:r,size:n});u=u.slice(t.length),i=u.join("\n"),yield t}a&&u.push(a)}if(u)for(;u.length;){const t=await fi(u,{...e,modelId:r,size:n});u=u.slice(t.length),yield t}}}async function mi(t,e){const n=e?.size??1984,r=e?.modelId;let s=be(t,e);const i=[];if(await ci(t,r)<=n)i.push(s);else do{const t=await fi(s,{...e,modelId:r,size:n});i.push(t),s=s.slice(t.length)}while(s.length);return i}var yi=require("yaml"),gi=class{constructor(t){t&&Object.assign(this,t)}};function bi(t,e){class n extends yi.YAMLMap{constructor(){super(...arguments),this.tag=t}toJSON(t,n){n={...n,mapAsMap:!1};const r=super.toJSON(t,n);return new e(r)}}return{tag:t,collection:"map",nodeClass:n,identify:t=>t instanceof e}}function vi(t,e){let n=t.length===e.length;if(n){const r=vn(t),s=vn(e);n=r.every(((t,e)=>t===s[e]))}return n}var Ei=require("lodash-es"),xi=c(require("path")),ki=".ai";function Si(t,e=["."]){if(xi.default.isAbsolute(t))return Dr.Config.loadSync(t);const n=e.map((e=>Dr.Config.loadSync(xi.default.resolve(e,t)))).filter(Boolean);return(0,Ei.defaultsDeep)({},...n.reverse())}function $i(t,e){const n={...process.env,...e};return ee(t,{processEnv:n,parsed:n})}function Ai(t,e){let n=Dr.Config.loadSync(xi.default.resolve(e.configDir,t));n||(n={configDirs:["$XDG_BIN_HOME",e.configDir,"$HOME"],brainDir:[xi.default.join(e.dataDir,"brain")],agentDirs:[xi.default.join(e.dataDir,"agent")],promptDirs:[xi.default.join(e.dataDir,"prompt")],chatsDir:xi.default.join(e.dataDir,"log","chats"),inputsDir:xi.default.join(e.dataDir,"log","inputs")});const r=Ci(e);for(const[t,e]of Object.entries(r))n[t]=e;$i(n,n);const s=n.configDirs;n.AI_CONFIG_BASENAME&&(t=n.AI_CONFIG_BASENAME);const i=$i(Si(t,s),n);return(0,Ei.defaultsDeep)(i,(0,Ei.omit)(n,Object.keys(r)))}function Ti(t){return Ai(ki,t)}function Ci(t){return{XDG_CONFIG_HOME:t.configDir,XDG_DATA_HOME:t.dataDir,XDG_CACHE_HOME:t.cacheDir,XDG_BIN_HOME:xi.default.dirname(t.options.root)}}function Oi(t,e){t.startsWith("~")&&(t="$HOME"+t.slice(1));return $i(t,e)}var{exit:ji}=process,Ni=!1,Ii=!1,Mi=["SIGINT","SIGTERM","exit"],Fi=3e5,Ri=[],Li=(t,e)=>t.forEach((t=>process.once(t,e))),qi=t=>()=>{setTimeout((()=>(console.warn(`Could not close resources gracefully after ${t}ms: forcing shutdown`),ji(1))),t).unref()};async function Pi(t="shutdown",e=0){if(!Ni){Ni=!0,"number"==typeof t&&(e=t,t="shutdown");for(const e of Ri)try{await e(t)}catch(t){console.warn(`A shutdown handler failed before completing with: ${t.message||t}`)}return ji(e)}console.warn(`Shutdown already in progress, ignoring [${t}] signal`)}function _i(t){if(Ii||Bi(),!Ri.some((e=>e===t)))return Ri.push(t),t}function Bi(){Ii||(Ii=!0,process.exit=t=>{Ni||Pi(void 0,t).then()},Li(Mi,qi(Fi)),Li(Mi,Pi))}var zi=require("property-manager"),Vi=require("util-ex"),Ui=class t extends zi.AdvancePropertyManager{static{this.items={}}static{this.aliases={}}static get(t){let e=this.items[t];return!e&&(t=this.aliases[t])&&(e=this.items[t]),e}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 hasAsyncFeature(t){const e=this.prototype;let n=e.asyncFeatures;return e._asyncFeatures&&(n|=e._asyncFeatures),ls.has(n,t)}static run(t,e){const n=this.get(t);if(n)return n.run(e);throw new m.NotFoundError(`${t} to run`,this.name)}static runSync(t,e){const n=this.get(t);if(n)return n.runSync(e);throw new m.NotFoundError(`${t} to run`,this.name)}static getFunc(t){const e=this.get(t);return e?.getFunc()}static runWithPos(t,...e){const n=this.get(t);if(n)return n.runWithPos(...e);throw new m.NotFoundError(`${t} to run`,this.name)}static runWithPosSync(t,...e){const n=this.get(t);if(n)return n.runWithPosSync(...e);throw new m.NotFoundError(`${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();if(this.items[e]=n,n.alias){const t=n.alias;if("string"==typeof t)this.aliases[t]&&(0,m.throwError)(`Alias ${t} already exists for ${e}`),this.aliases[t]=e;else if(Array.isArray(t))for(const n of t)this.aliases[n]&&(0,m.throwError)(`Alias ${n} already exists for ${e}`),this.aliases[n]=e}r=n}return r}static unregister(t){const e=this.get(t);if(e&&(delete this.items[t],e.alias)){const t=e.alias;if("string"==typeof t)delete this.aliases[t];else if(Array.isArray(t))for(const e of t)delete this.aliases[e]}return 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);(0,m.throwError)("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),ls.has(e,t)}isStream(t){return this.stream}},Di={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,Vi._createFunction)(t,e.scope)),i}},params:{type:"object"},result:{type:"any"},setup:{type:"function"},depends:{type:"object",exported:!1},tags:{type:["array","string"]},isApi:{type:"boolean"},stream:{type:"boolean"},asyncFeatures:{type:"number"},alias:{type:["array","string"]}};Ui.defineProperties(Ui,Di);var Xi=class t extends Ui{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(0,m.throwError)("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):(0,m.throwError)(`${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},s=["post","put","patch"];let i;e||(e=this.action||"post"),"res"===e&&(e="get"),r.headers&&r.headers["Content-Type"]||!s.includes(e)||(r.headers={"Content-Type":"application/json",...r.headers}),t?.stream&&!r.headers.Connection&&(r.headers.Connection="keep-alive"),n?("string"!=typeof n&&(n=JSON.stringify(n)),n=this.name+"/"+n):n=this.name,r.method=e.toUpperCase(),"get"===e||"delete"===e?i=n+this.getUrlParams(t):(r.body=JSON.stringify(t),i=n),r.headers&&!s.includes(e)&&delete r.headers["Content-Type"];const o=await fetch(`${this.apiRoot}/${i}`,r);if(!o.ok){throw await this.errorFrom(o)}return o}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(0,m.createError)(r,s,n)}async func(t){const e=await this.fetch(t);if(t?.stream)return e;return await e.json()}},Ji={...d};Xi.defineProperties(Xi,Ji);var Gi=class t extends Ui{static get apiRoot(){return this._apiRoot}static setApiRoot(t){this._apiRoot=t}static toJSON(){const e={};for(const n in this.items){let r=this.items[n];(r instanceof t||r.isApi)&&(r.allowExportFunc||(r=r.toJSON(),delete r.func),e[n]=r)}return e}func({}){}},Wi={...d};Gi.defineProperties(Gi,Wi);var Hi=require("events-ex"),Ki=class extends Ui{constructor(){super(...arguments),this._emitter=new Hi.EventEmitter,this.description="Return event bus",this.result="event"}get emitter(){return this._emitter}func(){return this.emitter}},Zi=new Ki(Be),Qi=require("secondary-cache"),Yi=require("secondary-cache"),to=Qi.Cache;function eo({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 no(t,e){let n=Ui.get(t);return n||(n=new Ui(t,{func:eo,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 Qi.Cache(e)),n}var ro=no("lrucache"),so=class extends Xi{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))}}},io={methods:{type:"array",assign(t,e,n,r,s){s?.isExported||e.assignMethods(t)}}};so.defineProperties(so,io);var oo=class extends so{async fetch(t,e){if(t||(t={}),e&&"res"===this.action){if("get"===e||"delete"===e){let n=t.id;return n||(0,m.throwError)("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)}},ao=class extends oo{constructor(){super(...arguments),this._sseEvents={},this._forwardEvents=new Set,this.name=_e,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)}},co=new ao(_e),uo=require("util-ex"),lo=class extends Gi{constructor(t,e={}){super(t,e),this.params={act:{type:"string"}};const n=this.methods=[];this.initRpcMethods(n)}get SpecialRpcMethodNames(){return this.constructor.SpecialRpcMethodNames}initRpcMethods(t=this.methods){const e=this.SpecialRpcMethodNames;if(Array.isArray(e))for(const n of e)"function"==typeof this[n]&&t.push(n);(0,uo.getAllNames)(Object.getPrototypeOf(this)).filter((t=>t.startsWith("$")&&"function"==typeof this[t])).forEach((e=>{t.push(e);const n=e.slice(1);void 0===this[n]&&(this[n]=this[e])}))}cast(t,e){let n=this.params[t];return n&&("string"!=typeof n&&(n=n.type),"number"===n&&(e=Number(e))),e}getMethodFromParams(t){const e=t?.act;return e}castParams(t){return t}func(t){const e=this.getMethodFromParams(t);if(e&&"function"==typeof this[e])return t=this.castParams(t),this[e](t);throw new m.NotFoundError(e,this.name)}};lo.defineProperties(lo,{methods:{type:"array"}});var fo=class extends lo{constructor(t,e={}){super(t,e),this.action="res",this.params={id:{type:"string"},val:{type:"any"}}}static{this.SpecialRpcMethodNames=w}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}castParams(t){return void 0!==t.id&&(t.id=this.cast("id",t.id)),t}},ho=Zi.runSync(),po=class t extends fo{constructor(){super(...arguments),this.name=_e,this.description="subscribe server sent event",this.result="event",this.depends={[Be]:Zi}}static get sse(){return this._sse||(this._sse=new De),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=ho.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)||ho.on(n,t.ebListener)}unforward(e){"string"==typeof e&&(e=[e]);for(const n of e)ho.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};(0,m.throwError)("event is required","sub",m.ErrorCode.InvalidArgument)}$unsub({event:t}){if(t)return this.unforward(t),{event:t};(0,m.throwError)("event is required","unsub",m.ErrorCode.InvalidArgument)}$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}}(0,m.throwError)("event or data is required","pub",m.ErrorCode.InvalidArgument)}isStream(t){return"list"===this.getMethodFromParams(t)}},wo=new po(_e);function mo(){Zi.register(),ro.register()}
1
+ "use strict";var t,e=Object.create,n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,s=Object.getPrototypeOf,o=Object.prototype.hasOwnProperty,a=(t,e,s,a)=>{if(e&&"object"==typeof e||"function"==typeof e)for(let c of i(e))o.call(t,c)||c===s||n(t,c,{get:()=>e[c],enumerable:!(a=r(e,c))||a.enumerable});return t},c=(t,r,i)=>(i=null!=t?e(s(t)):{},a(!r&&t&&t.__esModule?i:n(i,"default",{value:t,enumerable:!0}),t)),u={};((t,e)=>{for(var r in e)n(t,r,{get:e[r],enumerable:!0})})(u,{AIArgProcessor:()=>ye,AIChatRoles:()=>$,AIMessageTypes:()=>T,AIStream:()=>It,AITextGenerationFinishReasons:()=>E,AbortError:()=>y.AbortError,AbortErrorCode:()=>y.AbortErrorCode,ActionNames:()=>m,AlreadyExistsError:()=>y.AlreadyExistsError,AlreadyExistsErrorCode:()=>y.AlreadyExistsErrorCode,AsyncFeatureBits:()=>Dn,AsyncFeatures:()=>Xn,BaseError:()=>y.BaseError,BinarySemaphore:()=>On,CancelableAbility:()=>Un,ChoiceArgProcessor:()=>me,ClientToolFuncSchema:()=>ri,ClientTools:()=>ni,CommonError:()=>y.CommonError,ConfigFile:()=>cn.ConfigFile,DEFAULT_CONFIG_NAME:()=>qr,DefaultAsyncSemaphoreCapacity:()=>An,EnvPromptTemplate:()=>A.EnvStringTemplate,ErrorCode:()=>y.ErrorCode,EventBusName:()=>pt,EventClient:()=>gi,EventEmitter:()=>dt.EventEmitter,EventName:()=>mt,EventServer:()=>Ti,EventStates:()=>dt.states,EventToolFunc:()=>ai,FStringPromptTemplate:()=>A.FStringTemplate,FewShotPromptTemplate:()=>O,FilenameReservedRegex:()=>ee.FilenameReservedRegex,GolangPromptTemplate:()=>A.GolangStringTemplate,HashAlgorithm:()=>Xt,IntSet:()=>Sn,InternalErrorCode:()=>y.InternalErrorCode,LLM_TOKENIZER_NAMES:()=>pr,LLM_TOKENIZER_NAMES_MAP:()=>yr,LRUCache:()=>hi.LRUCache,NotFoundError:()=>y.NotFoundError,NotFoundErrorCode:()=>y.NotFoundErrorCode,NotImplementationError:()=>y.NotImplementationError,NotImplementedErrorCode:()=>y.NotImplementedErrorCode,ObjectArgsToArgsInfo:()=>le,PASSING_SCORE:()=>d,PromptExampleSelector:()=>R,PromptTemplate:()=>A.StringTemplate,RStreamErrCode:()=>St,RateLimit:()=>jn,ReadableStreamError:()=>Et,RemoteToolFuncSchema:()=>p,ResClientTools:()=>wi,ResServerTools:()=>ki,ResponseRStreamErrCode:()=>kt,SHUTDOWN_SIGNALS:()=>Ur,SSEChannel:()=>vt,SSEChannelAlreadyClosedErrCode:()=>gt,SecondaryCache:()=>li,Semaphore:()=>Nn,ServerToolFuncSchema:()=>si,ServerTools:()=>ii,SignalGate:()=>Mn,TaskAbortController:()=>Bn,TemplateArgProcessor:()=>pe,ToolAsyncCancelableBit:()=>zn,ToolAsyncMultiTaskBit:()=>Pn,ToolAsyncPriorityBit:()=>_n,ToolFunc:()=>ti,ToolFuncSchema:()=>ei,WindowsReservedNameRegex:()=>ee.WindowsReservedNameRegex,YamlTypeBaseObject:()=>Ir,_lrucache:()=>fi,assignDirs:()=>ir,backendEventable:()=>yt,base32768:()=>Qt,beforeShutdown:()=>Vr,canonicalize:()=>Vt.canonicalize,completeSentences:()=>K,concatText:()=>V,countLLMTokens:()=>vr,countRegexMatches:()=>Wn,createAbilityInjector:()=>l.createAbilityInjector,createCallbacksTransformer:()=>Nt,createEmptyReadableStream:()=>$t,createEndWithRepetitionDetector:()=>_e,createError:()=>y.createError,createEventStreamTransformer:()=>At,createHfValueFunc:()=>A.createHfValueFunc,createLRUCache:()=>di,createYamlObjectTag:()=>Or,dateToText:()=>k,decodeCharset:()=>Ke,defaultTemplateFormat:()=>A.defaultTemplateFormat,detectCharset:()=>en,encodeLLMTokens:()=>gr,ensureQuoted:()=>ve,event:()=>ci,eventClient:()=>vi,eventServer:()=>$i,eventable:()=>dt.eventable,expandConfig:()=>Fr,expandEnv:()=>A.expandEnv,expandObjEnv:()=>A.expandObjEnv,expandPath:()=>_r,extNameLevel:()=>ee.extNameLevel,fileIsExists:()=>Ge,filterValidFnScope:()=>Le,findIndexNonEmptyFrom:()=>st,findPort:()=>Zn,formatISO:()=>g.formatISO,formatTextWithSpace:()=>br,getAllEnumKeys:()=>ie,getConfigFileNames:()=>un,getConfigs:()=>hn,getEnvVairables:()=>A.getEnvVairables,getFileMetaInfo:()=>Ye,getHashAlgoBySize:()=>tn,getKeysPath:()=>Pe,getLLMTokenizer:()=>wr,getMultiLevelExtname:()=>ee.getMultiLevelExtname,getPackageDir:()=>tr,getRealFilepath:()=>Ze,getResponseErrorReadableStream:()=>Tt,getXDGConfigs:()=>zr,hasDirectoryIn:()=>rr,hash:()=>te,hashFile:()=>Qe,hashStream:()=>Yt,initShutdown:()=>Zr,isLangUsingSpaces:()=>it,isListItemString:()=>tt,isModelNameMatched:()=>re,isPunctuationChar:()=>nt,isQuoted:()=>we,isRegExp:()=>or,isSameString:()=>Nr,isSectionString:()=>Q,isSentenceEnding:()=>Z,isSepLineString:()=>et,isStrWrapped:()=>ge,isSubdirectory:()=>nr,isTitleString:()=>Y,isValidFilename:()=>ee.isValidFilename,isValidFilepath:()=>ee.isValidFilepath,isWebStream:()=>bt,jsonFilterToWhere:()=>yn,jsonToMarkdownStr:()=>bn,loadAIConfig:()=>Pr,loadConfig:()=>Lr,loadConfigFile:()=>Mr,loadFileFromPaths:()=>We,loadTextFromPaths:()=>He,lrucache:()=>mi,makeToolFuncCancelable:()=>Gn,matchUrlProtocol:()=>wn,memoize:()=>Kn,messagesToText:()=>x,mimeType:()=>an.mimeType,paramsSizeToScaleStr:()=>gn,parseCommand:()=>xe,parseDateFormat:()=>w.parse,parseISO:()=>g.parseISO,parseJsJson:()=>Re,parseJsJsonSimpleSync:()=>qe,parseObjectArgInfo:()=>Te,parseObjectArgumentInfos:()=>de,parseObjectArguments:()=>ue,parseObjectArgumentsAsArgInfos:()=>$e,parseYaml:()=>cn.parseYaml,quoteStr:()=>be,readFilenamesRecursiveSync:()=>Ve,readTextFileChunks:()=>$r,readTextFileChunksEx:()=>xr,readableFromAsyncIterable:()=>Ot,registerCoreTools:()=>xi,registerYamlTag:()=>cn.registerYamlTag,removeMarkdownBold:()=>ot,removeMarkdownBoldAndItalic:()=>ct,removeMarkdownItalic:()=>at,replaceWithPlaceholder:()=>Ce,restoreFromPlacehoders:()=>Ie,sanitizeFilename:()=>ee.sanitizeFilename,sanitizeFilepath:()=>ee.sanitizeFilepath,saveConfigFile:()=>ln,scaleStrToParamsSize:()=>vn,shutdown:()=>Kr,simplifyObjectArguments:()=>fe,sortedValues:()=>I,splitChunks:()=>Ar,splitParagraph:()=>ut,splitSentence:()=>H,stringifyYaml:()=>cn.stringifyYaml,stripConsoleColor:()=>ar,textToDate:()=>S,throwError:()=>y.throwError,toDate:()=>g.toDate,toDateTime:()=>b,toRegExp:()=>f.toRegExp,trimStartOfStreamHelper:()=>Ct,truncTo:()=>ht,truncateByToken:()=>Er,truncateToTokenLimit:()=>Sr,truncateToTokenLimitEx:()=>kr,uuid:()=>Ft,uuidNIL:()=>qt.NIL,uuidParse:()=>qt.parse,uuidStringify:()=>qt.stringify,uuidValidate:()=>qt.validate,uuidVersion:()=>qt.version,uuidv1:()=>qt.v1,uuidv4:()=>qt.v4,uuidv5:()=>qt.v5,wait:()=>lt,wrapEventEmitter:()=>dt.wrapEventEmitter,xxhash:()=>Ht,xxhash32:()=>Wt,xxhash64:()=>Jt,xxhashAsStr:()=>Kt}),module.exports=(t=u,a(n({},"__esModule",{value:!0}),t));var h=(()=>"undefined"==typeof document?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.src||new URL("main.js",document.baseURI).href)(),l=require("custom-ability"),f=require("util-ex"),d=.618,m=["get","post","put","delete","patch","list","res"],p={apiRoot:{type:"string",get(){return this._apiRoot??this.constructor.apiRoot},set(t){this._apiRoot=t}},action:{type:"string",assign:(t,e,n,r,i)=>t||"post"},fetchOptions:{type:"object"},allowExportFunc:{type:"boolean"}},y=require("@isdk/common-error"),w=require("date-fns"),g=require("date-fns"),v="MMMM d, y 'at' h:m:s b 'GMT'x";function b(t){let e;try{"string"==typeof t?e=(0,w.parseISO)(t):"number"==typeof t?e=new Date(t):t instanceof Date&&(e=t)}catch(t){console.error(t)}return e}function S(t,e=v){return(0,w.parse)(t,e,new Date)}function k(t,e=v){return(0,w.format)(t,e)}var E=["stop","length","content_filter","tool_calls","function_call","abort","error","other",null],T=["human","ai","generic","system","tool"],$=["user","assistant","system","tool","tool_calls"];function x(t){let e="";for(const n of t)if(n.content){e+=n.role.toLowerCase()+":";let t=n.createdAt;if(t){const n=b(t);n&&(e+=" ["+k(n)+"]")}e+=" "+n.content+"\n"}return e}var A=require("@isdk/template-engines"),C=require("@isdk/template-engines");function I(t){return Object.keys(t).sort().map((e=>t[e]))}var O=class extends C.StringTemplate{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 C.StringTemplate?t.examplePrompt:C.StringTemplate.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=I(t);n.length>0&&e.push(...n)}const n=[this.prefix,...e,this.suffix].join(this.exampleSeparator),r=this.templateFormat;return await C.StringTemplate.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}};function N(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}C.StringTemplate.register(O,{name:"fewshot",aliases:["few_shot"]});var j=!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=>{j=t}));var R=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,j?r:N(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()}},q=require("@isdk/detect-text-language"),M="@",F=/(\S.+?[.!?])(?=\s+|$)|(\S.+?)(?=[\n]|$)/g,L=/([A-Z][a-z]{1,2}\.)\s(\w)/g,P=/(\.[a-zA-Z]\.)\s(\w)/g,z=new RegExp("([A-Z][a-z]{1,2}\\.)"+M+"(\\w)","g"),_=new RegExp("(\\.[a-zA-Z]\\.)"+M+"(\\w)","g"),D=/(```)([\s\S]*?)(```)/g,X=">>>CODE_BLOCK<<<",B=/([*_`]{1,3})(\S.*?\S)\1/,U=">>> INLINE_BLOCK ",G=/>>> INLINE_BLOCK (\d+) <<</,W=1e4;function J(t,e,n){const r="$1"+e+"$2";let i=t;for(let t=0;t<n.length;t++)i=i.replace(n[t],r);return i}function H(t,{best:e=!0,completeSentence:n,isMarkdown:r,ignoreEmptyLine:i}={}){const s=[],o=[];let a,c=0;for(;c++<W&&(a=D.exec(t));){const e=a[0];s.push(e),t=t.replace(e,"\n"+X+(s.length-1)+"\n")}for(c=0;c++<W&&(a=B.exec(t));){const e=a[0];o.push(e),t=t.replace(e,U+(o.length-1)+" <<<")}if(r){const e=t.split("\n");for(let t=0;t<e.length;t++){const n=e[t];Y(n,{isMarkdown:r,nextLine:e[t+1]})&&(s.push(n),e[t]=X+(s.length-1))}t=e.join("\n")}const u=(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 h=[];for(let t=0;t<u.length;t++){let n=u[t].trimEnd();if(!n){!r&&i||h.push("");continue}if(n.startsWith(X)){h.push(s[Number(n.slice(X.length))]);continue}if(r&&Y(n,{isMarkdown:r,nextLine:u[t+1]})){h.push(n);continue}if(!e){h.push(n);continue}let a=J(n,M,[L,P]),c=Array.from(a.matchAll(F)),l=[];if(c.length)for(let t=0;t<c.length;t++)l.push(J(c[t][0]," ",[z,_]));else l.push(n);h.push(...l.map((t=>rt(o,t))))}return n&&(h=K(h,{isMarkdown:r,ignoreEmptyLine:i})),h}function K(t,{isMarkdown:e,ignoreEmptyLine:n}={}){const r=[];let i=0,s="";for(n=!e&&n;i<t.length;){let c=t[i];if(c){let u;if(n){const n=st(t,i+1);u=Q(t[n],{isMarkdown:e,nextLine:-1===n?"":t[n+1]})}else u=Q(t[i+1],{isMarkdown:e,nextLine:t[i+2]});o=c,a={isMarkdown:e,nextLine:t[i+1]},Z(o)||Q(o,a)||""===t[i+1]||u?(s&&(c=V(s,c),s=""),r.push(c)):(s&&(c=V(s,c)),s=c)}else n||r[r.length-1]&&r.push(c);i++}var o,a;return s&&r.push(s),r}function V(t,e){const n=t+" "+e,r=(0,q.detectTextLanguage)(n,{isoCode:!0});return r&&!it(r)?(nt(t)&&(t+=" "),e=t+e):e=t.endsWith("-")?(t=t.slice(0,-1))+e:n,e}function Z(t){if(!t)return!1;return/(([.。!!??]\s*['"”’]?)|```)\s*$/.test(t)}function Q(t,e){let n=Y(t,e);return n||(n=tt(t)),n||(n=et(t)),n}function Y(t,e){if(!t)return null;let n=/^\s*第?\s*[壹贰叁肆伍陆柒捌玖拾一二三四五六七八九十百千萬万\d]+\s*([章節节编回部篇卷幕场場辑集段册冊期片題]|片段|段落|篇[章目]|小[节節]|(子)?部分|卷[册冊]|[单單]元|章[节節回]|[.、])[ \t]*(?<title>.*)(?=\n|$)/.exec(t);if(n||(n=/^\s*(Chapter|Book|Article|Part|Paragraph|Subsection|Subpart|Volume|Episode|Issue|Unit|Section|Segment|Act|Scene)\s*\d+.*(?=\n|$)/i.exec(t)),!n&&e?.isMarkdown){n=/^[ \t]{0,3}(#+)\s+(?<title>\S.*)$/.exec(t);const r=/^[ \t]{0,3}([-=]+)(?=\n|$)/;!n&&e.nextLine&&!r.test(t)&&/^[ \t]{0,3}\S/.test(t)&&r.test(e.nextLine)&&(n=/^\s*(?<title>.*)(?=\n|$)/.exec(t))}return n}function tt(t){return/^\s*([*+-]|\d+[.、])\s*(?<item>.*)(?=\n|$)/.exec(t)}function et(t){return/^[-=_]{3,}$/.exec(t)}function nt(t){return/[。!??,、;;::'""“”‘’~~《》<>〈〉【】(){}【】\[\]\(\)…·]$/.test(t)}function rt(t,e){let n,r=0;for(;r++<W&&(n=G.exec(e));){const r=Number(n[1]);e=e.replace(n[0],t[r])}return e}function it(t){return!["zh","ja","th","lo","ta","ko"].includes(t)}function st(t,e=0){for(let n=e;n<t.length;n++){const e=t[n];if(null!=e&&""!==e)return n}return-1}function ot(t,e){const n=/(?!\\)([*_])\1(?![ \t]|\1)(.+?)(?<!\\)\1{2}/;let r;for(;(r=n.exec(t))&&(t=t.slice(0,r.index)+r[2]+t.slice(r.index+r[0].length),!e););return t}function at(t,e){const n=/(?!\\)([*_])(?![ \t]|\1)(.+?)(?<!\\)\1/;let r;for(;(r=n.exec(t))&&(t=t.slice(0,r.index)+r[2]+t.slice(r.index+r[0].length),!e););return t}function ct(t,e){return t=at(t=ot(t,e),e)}function ut(t,e){const n=[],r=[],i=t.split("\n");for(let t=0;t<i.length;t++){let s=i[t];const o=0===s.trim().length;o||Y(s,{...e,nextLine:i[t+1]})?(r.length&&n.push([...r]),r.length=0,o||r.push(s)):r.push(s)}return r.length&&n.push([...r]),n}function ht(t,e=2,n=.5){const r=10**e;return Math.trunc((t+Number.EPSILON+n/r)*r)/r}async function lt(t){return new Promise((e=>setTimeout(e,t)))}var ft=require("custom-ability"),dt=require("events-ex"),mt="event",pt="event-bus";var yt=(0,ft.createAbilityInjector)((function(t){return class{static get emitter(){if(!this._emitter){const t=this.get(pt)?.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 wt(t,e){return!t||t.some((t=>t instanceof RegExp?t.test(e):t===e))}var gt=498,vt=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||(0,y.throwError)("Channel closed","SSEChannel",gt);let i=e;if(t||e)r=this.nextID++,"object"==typeof t&&(t.event?(i=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:i,output:n});else{if(!this.clients.size)return;n="data: \n\n"}for([...this.clients].filter((t=>!i||wt(t.events,i))).forEach(((t,e)=>{t.res.write(n)}));this.messages.length>this.options.historySize;)this.messages.shift();return r}subscribe(t,e,n){this.active||(0,y.throwError)("Channel closed","SSEChannel",gt);const r={req:t,res:e,events:n},i=this.options.maxStreamDuration;let s="max-age=0, stale-while-revalidate=0, stale-if-error=0, no-transform";i>0&&(s+=", s-maxage="+(Math.floor(i/1e3)-1));const o={"Content-Type":"text/event-stream","Cache-Control":s,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=>wt(r.events,t.eventName))).slice(0-u).forEach((t=>{a+=t.output})),r.res.write(a),this.clients.add(r),i>0&&setTimeout((()=>{r.res.writableEnded||this.unsubscribe(r)}),i),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}};function bt(t){return t instanceof ReadableStream||t instanceof WritableStream}var St=600,kt=601,Et=class extends y.BaseError{constructor(t,e=St){super(t,500)}};function Tt(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 Et(`Response error: ${e}`,kt))}}})}return new ReadableStream({start(t){t.error(new Et("Response error: No response body",kt))}})}function $t(){return new ReadableStream({start(t){t.close()}})}var xt=require("eventsource-parser");function At(t){const e=new TextDecoder;let n;return new TransformStream({async start(e){n=(0,xt.createParser)({onEvent:n=>{if("data"in n&&"[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 Ct(){let t=!0;return e=>(t&&(e=e.trimStart())&&(t=!1),e)}function It(t,e){if(!t.ok)return Tt(t.body);let n=t.body||new ReadableStream({start(t){t.close()}});return n instanceof ReadableStream||(n=ReadableStream.from(n)),n.pipeThrough(At(e))}function Ot(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))}})}function Nt(t){const e=t||{};return new TransformStream({async start(t){const n=t.error;if(t.error=r=>{n.call(t,r),e.onError&&e.onError(r)},e.onStart)try{await e.onStart(t)}catch(e){t.error(e)}},async transform(t,n){try{let r;e.onTransform&&(r=await e.onTransform(t,n)),r||(r=t),n.enqueue(r)}catch(t){n.error(t)}},async flush(t){if(e.onFinal)try{await e.onFinal(t)}catch(e){return t.error(e)}t.terminate()}})}var jt=require("uuid"),Rt=c(require("base32768")),qt=require("uuid"),Mt={1:jt.v1,4:jt.v4,5:jt.v5};function Ft(t=1,e){const n=Mt[t];return e?Rt.encode(n(null,[])):n()}var Lt=c(require("xxhashjs")),Pt=c(require("base32768")),zt=require("json-canonicalize"),_t=require("hash-wasm"),Dt=588213,Xt=(t=>(t[t.md5=1]="md5",t[t.sha1=2]="sha1",t[t.ripemd=3]="ripemd",t[t.sha256=8]="sha256",t[t.sha384=9]="sha384",t[t.sha512=10]="sha512",t[t.sha224=11]="sha224",t[t.xxhash=111]="xxhash",t[t.xxhash64=111]="xxhash64",t[t.xxhash32=112]="xxhash32",t[t.xxhash128=113]="xxhash128",t))(Xt||{}),Bt={1:_t.createMD5,2:_t.createSHA1,8:_t.createSHA256,10:_t.createSHA512,11:_t.createSHA224,3:_t.createRIPEMD160,112:_t.createXXHash32,111:_t.createXXHash64,113:_t.createXXHash128},{h32:Ut,h64:Gt}=Lt.default;function Wt(t,e=16){return"object"==typeof t&&(t=(0,zt.canonicalize)(t)),Ut(t.normalize(),Dt).toString(e)}function Jt(t,e=16){return"object"==typeof t&&(t=(0,zt.canonicalize)(t)),Gt(t.normalize(),Dt).toString(e)}function Ht(t,e=111,n=Dt){let r;return t.buffer&&(t=t.buffer),112!==e?(r=Gt(t,n),r=new Uint16Array([r._a00,r._a16,r._a32,r._a48]),r=new Uint8Array(r.buffer)):(r=Ut(t,n),r=new Uint16Array([r._low,r._high]),r=new Uint8Array(r.buffer)),r}function Kt(t,e=111,n=Dt){return Pt.encode(Ht(t,e,n))}var Vt=require("json-canonicalize"),Zt=c(require("base32768")),Qt=Zt;async function Yt(t,{hashAlgo:e=111,seed:n=Dt,outputType:r="string"}={}){const i=await Bt[e](n);i.init();const s=t.getReader();for(;;){const{done:t,value:e}=await s.read();if(t)break;i.update(e)}return"string"!==r?i.digest(r):Zt.encode(i.digest("binary"))}async function te(t,{hashAlgo:e=111,seed:n=Dt,outputType:r="string"}={}){const i=await Bt[e](n);i.init(),i.update(t);return"string"!==r?i.digest(r):Zt.encode(i.digest("binary"))}var ee=require("@isdk/util"),ne=require("util-ex");function re(t,e){if("string"!=typeof t)throw new y.CommonError("modelName must be a string","isModelNameMatched",y.ErrorCode.InvalidArgument);switch(typeof e){case"string":if((0,ne.isRegExpStr)(e)){const n=(e=(0,ne.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,ne.isRegExpStr)(n)){const r=(e=(0,ne.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 ie(t){return Object.keys(t).filter((t=>Number.isNaN(Number(t))))}var se=require("lodash-es"),oe=require("util-ex"),ae=require("lodash-es"),ce=require("util-ex");async function ue(t,e,n){return de($e(t,e,n),e,n)}function he(t){for(let e=1;e<t.length;e++)if(t[e]<=t[e-1])return!1;return!0}function le(t){if(t&&!Array.isArray(t)&&"object"==typeof t){const e=Object.entries(t),n=Object.keys(t),r=n.filter((t=>!isNaN(parseInt(t))));if(1===e.length)void 0!==t[0]&&(t=[t[0]]);else if(n.every((t=>!isNaN(parseInt(t))))&&he(n.map((t=>parseInt(t)))))t=Object.values(t);else if("0"===r[0]&&he(r.map((t=>parseInt(t))))){const n=e.filter((([t,e])=>isNaN(parseInt(t))));t=e.filter((([t,e])=>!isNaN(parseInt(t)))).map((([t,e])=>e));let r=0;const i=[];for(;r<n.length&&n[r][1]===t[r];)i.push(r),r++;for(;i.length;)n.splice(i.pop(),1);t={args:t,kvArgs:Object.fromEntries(n)}}else t={args:[],kvArgs:t}}return Array.isArray(t)&&(t={args:t}),t}function fe(t){if(t&&!Array.isArray(t)&&"object"==typeof t){const e=Object.entries(t),n=Object.keys(t);1===e.length&&void 0!==t[0]?t=t[0]:n.every((t=>!isNaN(parseInt(t))))?t=n.sort(((t,e)=>parseInt(t)-parseInt(e))).map((e=>t[e])):2===e.length&&"0"===e[0][0]&&e[0][1]===e[1][1]&&(t=t[0])}return t}async function de(t,e,n){if(t.length){const r=await Promise.all(t.map(((t,r)=>Te(t,r,e,n)))),i=n?.returnArrayOnly;let s;if(r?.length){s=qe(`{${r.map((t=>t)).join(",")}}`,e)}return s&&!i&&(s=fe(s)),s}}function me(t,e,n,r){const[i,s]=t;if(!i&&"|"===s[0])return"choice: {"+function(t,e,n){const r=$e(t,e,{...n,delimiter:":"}),i={},s=r.map((([t,e],n)=>{if(t){const t=e.indexOf(":"),n=e.slice(0,t).trim();if(i[n])throw new Error("Only one "+n+" is allowed");return i[n]=!0,e}{if("|"===e[0]){if(i.items)throw new Error("Only one items is allowed");return i.items=!0,"items:["+function(t,e='"'){return t.map((t=>ve(t,e)))}(e.split("|").filter(Boolean))+"]"}const t=parseInt(e.trim());if(!isNaN(t)){if(i.maxPick)throw new Error("Only one maxPick is allowed");return i.maxPick=!0,"maxPick:"+t}if("random"===e||"ai"===e)return i.type=!0,'type:"'+e+'"';if(we(e)){if(i.separator)throw new Error("Only one separator is allowed");return i.separator=!0,"separator:"+e}}}));return s}(s,n,r)+"}"}async function pe([t,e],n,r,i){let s,o;if(r||(r={}),t){const t=e.split(":");s=t[0].trim(),o=t[1].trim()}else o=e,s=n+"";const a={template:o,data:{...(0,ae.omitBy)(r,((t,e)=>!e||"_"===e[0]||"function"==typeof t)),...i?.templateData}};i?.templateFormat&&(a.templateFormat=i.templateFormat);const c=await A.StringTemplate.formatIf(a);if(c)return o=we(c)?c:JSON.stringify(c),s+":"+o}async function ye(t,e,n,r){let i=me(t,0,n,r);return i||(i=await pe(t,e,n,r)),i}function we(t){const e=t[0];return('"'===e||"'"===e)&&t[t.length-1]===e}function ge(t,e=['""',"''","{}"]){return e.some((e=>t[0]===e[0]&&t[t.length-1]===e[1]))}function ve(t,e='"'){return we(t)?t:e+t+e}function be(t){return'"'+t.replace(/(?<!\\)"(?!\\)/g,'\\"')+'"'}var Se=["true","false","null","undefined","NaN","Infinity"];async function ke(t,e,n){const r=(0,ce.newFunction)("async expression",[],`return ${t};`,Le(e));let i;try{i=await r.call(this)}catch(t){if(n||!(t instanceof ReferenceError))throw t}switch(typeof i){case"number":case"boolean":case"undefined":return i;case"function":return r.toString();default:return JSON.stringify(i)}}async function Ee(t,e,n){let r=t;if(["true","false"].includes(t.toLowerCase()))r=r.toLowerCase();else if(!(i=t,ge(i)||!Number.isNaN(parseFloat(i))||Se.includes(i)||je(i)||e&&void 0!==(0,ae.get)(e,t)||je(t)))try{r=n?.skipExpression?be(t):await ke.call(this,t,e,n?.preserveUnresolvedName)}catch(e){r=be(t)}var i;return r}async function Te(t,e,n,r){const[i,s]=t,o=r?.argProcessor,a=r?.ignoreIndexNamed;if("function"==typeof o){const i=await o(t,e,n,r);if(i)return i}if(i){const t=s.indexOf(":");return s.slice(0,t).trim()+":"+await Ee(s.slice(t+1).trim(),n,r)}{const t=s.trim();if(n&&void 0!==(0,ae.get)(n,t)){return(a?"":e+":"+t+",")+'"'+t+'":'+t}return e+":"+await Ee(s.trim(),n,r)}}function $e(t,e,n){const r=n?.delimiter??",",i=n?.assigner??"=";let s=[],o=!1,a="",c="",u=!1,h="";for(let e=0;e<t.length;e++){const n=t[e];if(n!==r||o||h)if("\\"===n)c+=n,e++,c+=t[e];else if("("!==n&&"["!==n||o)if(h&&n===h)h="",c+=n;else if("{"!==n||o)'"'===n||"'"===n?(o&&n===a?o=!1:o||(o=!0,a=n),c+=n):n!==i||o||u||!/^[\p{L}\p{N}_ ]+$/u.test(c)?c+=n:(c+=":",u=!0);else{let r,i=e,s=!1,o="",a=-1;for(;i<t.length&&("}"!==(r=t[i])||s||a>0);)"\\"===r?i++:"{"!==r||s?"}"!==r||s?'"'!==r&&"'"!==r||(s&&n===o?s=!1:s||(s=!0,o=n)):a--:a++,i++;i<t.length&&(c+=t.substring(e,i+1),e=i)}else h="("===n?")":"]",c+=n;else c=c.trim(),c.endsWith(":")&&(c+="undefined"),s.push([u,c]),c="",u=!1}return c&&(c=c.trim(),c.endsWith(":")&&(c+="undefined"),s.push([u,c])),s}async function xe(t,e,n){const r=t.match(/^([^(]+)(?:\((.*)\))?$/);if(!r){if(n?.raiseError)throw new Error("Invalid command format");return}const[,i,s]=r;let o;return s&&(o=await ue(s,e,n)),{command:i.trim(),args:o}}var Ae="__PlacEhoLdeR_";function Ce(t,e){let n=e?.startChar?Array.isArray(e.startChar)?e.startChar:[e.startChar]:['"',"'"],r=e?.endChar?Array.isArray(e.endChar)?e.endChar:[e.endChar]:n;if(n.length!==r.length)throw new Error("start and end characters must have the same length");const i=e?.placeholder??Ae,s=n.every(((t,e)=>t===r[e])),o=e?.placehoders??[];if(s){n=n.map((t=>"\\"+t));const e=new RegExp(`(?<!\\\\)(${n.join("|")}).*?(?<!\\\\)\\1`);let r;for(;null!==(r=e.exec(t));){const e=`${i}${o.length}`;t=t.replace(r[0],e),o.push(r[0])}}else{n=n.map((t=>"\\"+t)),r=r.map((t=>"\\"+t));for(let e=0;e<n.length;e++){const s=new RegExp(`(?<!\\\\)${n[e]}.*?(?<!\\\\)${r[e]}`);let a;for(;null!==(a=s.exec(t));){const e=`${i}${o.length}`;t=t.replace(a[0],e),o.push(a[0])}}}return[t,o]}function Ie(t,e,n){const r=n?.placeholder??Ae;return e.reduce(((t,e,n)=>t.replace(new RegExp(r+n,"g"),e)),t)}var Oe="[a-zA-Z_$][a-zA-Z_\\d$]*",Ne=new RegExp(`^\\s*(\\(\\s*\\)|${Oe}|\\(${`${Oe}\\s*(,\\s*${Oe})*`}\\))\\s*=>`);function je(t){return Ne.test(t)}async function Re(t,e){if(e&&(e=Le(e)),e&&(t=t.trim()).startsWith("{")&&t.endsWith("}")){return await ue(t.slice(1,-1),e,{assigner:":",ignoreIndexNamed:!0})}return qe(t,e)}function qe(t,e){if(e&&(e=Le(e)),e){const n=Object.keys(e);if(n.length){const r=Object.values(e);let i=0;for(;i++<100;)try{return(0,oe.newFunction)("expression",n,`return ${t}`)(...r)}catch(t){if(!(t instanceof ReferenceError))throw t;{const e=/(.+)\s+is not defined/.exec(t.message);if(!e)throw t;n.push(e[1]),r.push(void 0)}}}}return(0,oe.newFunction)("expression",[],`return ${t}`)()}var Me=/^[a-zA-Z_$][0-9a-zA-Z_$.]*$/,Fe=t=>Me.test(t);function Le(t){if(t){const e=Object.keys(t),n=e.length,r=e.filter((e=>Fe(e)&&null!==t[e]));if(n===r.length)return t;if(r.length)return t=(0,se.pick)(t,r)}}function Pe(t){return t?ze(t,[],{dot:""}):[]}function ze(t,e,{dot:n=".",visited:r=new Set}={}){return r.has(t)?[e.join("")]:Array.isArray(t)?(r.add(t),t.flatMap(((t,n)=>ze(t,[...e,`[${n}]`],{dot:".",visited:r})))):(i=t)&&i.constructor===Object?(r.add(t),Object.entries(t).flatMap((([t,i])=>ze(i,[...e,n+t],{dot:".",visited:r})))):[e.join("")];var i}function _e(t){if(t<2)throw new y.CommonError("repetitionThreshold must be greater than 1","createEndWithRepetitionDetector",y.ErrorCode.InvalidArgument);const e=new RegExp(`([\\S\\s]+)(\\1{${t-1},})$`);return function(t){return e.exec(t)}}var De=c(require("path")),Xe=c(require("fs")),Be=c(require("mime-type/with-db")),Ue=c(require("jschardet"));function Ge(t){const e=Xe.statSync(t,{throwIfNoEntry:!1});return e?.isFile()}function We(t,e,n,r){const i=r?.signal,s=r?.exclude;let o;if(De.default.isAbsolute(t)?o=Ge(t)?t:Je(De.default.basename(t),[De.default.dirname(t)],{extNames:n,exclude:s,signal:i}):(e||(e=["."]),o=Je(t,e,{extNames:n,exclude:s,signal:i})),!o)throw new y.NotFoundError(t,"loadFileFromPaths");{const t=o;o=Xe.readFileSync(o),r&&(r.filepath=t)}return o}function Je(t,e,{extNames:n,signal:r,exclude:i=[]}){let s;const o=n?n.map((e=>(0,ee.getMultiLevelExtname)(t,(0,ee.extNameLevel)(e)))):void 0;"string"==typeof i&&(i=[i]);for(const a of e){if(r?.aborted)throw r.reason;const e=De.default.resolve(a,t);if(o)for(let t=0;t<o.length;t++){const r=e+(o[t]!==n[t]?n[t]:"");if(!i.includes(r)&&Ge(r)){s=r;break}}else if(!i.includes(e)&&Ge(e)){s=e;break}}return s}function He(t,e,n,r,i){let s;"string"==typeof r?(s=r,r=void 0):s=r?.encoding;return Ke(We(t,e,n,r),s)}function Ke(t,e){void 0===e&&(e=en(t)??"utf8");return new TextDecoder(e).decode(t)}function Ve(t,e){const n=[],r="string"==typeof t?[{dir:t,level:0}]:[...t.map((t=>({dir:t,level:0})))],i=new Set,s=e?.signal,o=e?.isFileMatched,a=e?.level,c=e?.resolveSymlinks??!0;let u=0;for(;r.length>0;){if(s?.aborted)throw s.reason;const t=r.pop(),e=c?Ze(t.dir):t.dir,h=De.default.resolve(e);if(i.has(h))continue;i.add(h);const l=Xe.statSync(e,{throwIfNoEntry:!1});if(l?.isDirectory()){u=t.level+1;const i=Xe.readdirSync(e,{withFileTypes:!0});for(let t=0;t<i.length;t++){let s=i[t],h=De.default.join(e,s.name);const l=h;if(s.isSymbolicLink()){const t=De.default.dirname(h);h=Xe.readlinkSync(h),h=De.default.resolve(t,h),s=Xe.statSync(h)}if(s.isDirectory())(!a||u<a)&&(o&&!o(h,s)||r.push({dir:h,level:u}));else if(s.isFile()&&(!o||o(h,s))){const t=c?h:l;n.includes(t)||n.push(t)}}}}return n}function Ze(t){const e=Xe.lstatSync(t,{throwIfNoEntry:!1});return e?.isSymbolicLink()&&(t=Xe.readlinkSync(t)),t}async function Qe(t,e){return Yt(ReadableStream.from(Xe.createReadStream(t)),e)}async function Ye(t){const e=De.default.basename(t);t=De.default.resolve(t);const n=await Xe.promises.stat(t),r=n.mtime,i=n.ctime,s=n.size,o=tn(s),a=await Qe(t,{hashAlgo:o}),c=Be.default.lookup(t);return{name:e,mtime:r,ctime:i,size:s,hash:Xt[o]+":"+a,mimeType:c,id:"file://"+t}}function tn(t){let e=111;return t<=2048?e=112:t<=1048576?e=111:t<=10485760?e=113:t>10485760&&(e=10),e}function en(t,e){return Ue.default.detect(t,e).encoding}var nn=require("fs"),rn=c(require("path")),sn=require("@isdk/util"),on=require("yaml-types"),an=require("mime-type/with-db"),cn=require("@isdk/util");function un(t,e){const n=[],r=e?.after,i=e?.exclude?"string"==typeof e.exclude?[e.exclude]:e.exclude:void 0,s=e?.extensions?"string"==typeof e.extensions?[e.extensions]:e.extensions.map((t=>t.startsWith(".")?t:"."+t)):[".yml",".yaml",".json"];return(0,sn.traverseFolderSync)(t,((t,e)=>{if(i?.includes(t)||!e.isFile())return;const o=rn.default.extname(t),a=(0,nn.statSync)(t);if(s.includes(o)){if(r?.hasOwnProperty(t)&&a.mtimeMs<=r[t])return;n.push(t)}})),n}function hn(t,e){return un(t,e).map((t=>sn.ConfigFile.loadSync(t))).filter((t=>void 0!==t))}function ln(t,e,n=1){return sn.ConfigFile.saveSync(t,e,{extLevel:n})}function fn(t){t instanceof Date&&(t=t.toISOString());return function(t,e){return t?`'${e}'`:String(e)}("string"==typeof t,t)}function dn(t,e){return t.map((t=>yn(t,e))).join(" AND ")}function mn(t,e){return t.map((t=>yn(t,e))).join(" OR ")}function pn(t,e){const n=[];return Object.keys(e).forEach((r=>{const i=e[r];switch(r){case"$lt":case"<":n.push(`${t} < ${fn(i)}`);break;case"<=":case"$lte":n.push(`${t} <= ${fn(i)}`);break;case"$gt":case">":n.push(`${t} > ${fn(i)}`);break;case"$gte":case">=":n.push(`${t} >= ${fn(i)}`);break;case"$ne":case"!=":n.push(`${t} != ${fn(i)}`);break;case"=":case"$eq":n.push(`${t} = ${fn(i)}`);break;case"$in":n.push(`${t} IN (${i.map((t=>fn(t))).join(", ")})`);break;case"$nin":n.push(`${t} NOT IN (${i.map((t=>fn(t))).join(", ")})`);break;case"$regex":n.push(`${t} REGEXP '${i.source}'`);break;case"$like":n.push(`${t} LIKE '${i}'`);break;case"$nlike":n.push(`${t} NOT LIKE '${i}'`);break;case"$glob":n.push(`${t} GLOB '${i}'`);break;case"$nglob":n.push(`${t} NOT GLOB '${i}'`);break;default:throw new Error(`Unsupported condition operator: ${r}`)}})),n.join(" AND ")}function yn(t,e){const n=[];if("function"!=typeof e&&(e=t=>t),Array.isArray(t))n.push(dn(t,e));else for(const[r,i]of Object.entries(t))if("$and"===r)n.push(`(${dn(t[r],e)})`);else if("$or"===r)n.push(`(${mn(t[r],e)})`);else{const t=typeof i;if(null==i)n.push(`${e(r)} IS NULL`);else if(i instanceof Date)n.push(`${e(r)}='${i.toISOString()}'`);else if("object"!==t||Array.isArray(i))if("string"===t)n.push(`${e(r)}='${i}'`);else{if("number"!==t&&"boolean"!==t)throw new Error(`Unsupported value type for key ${r}`);n.push(`${e(r)}=${i}`)}else n.push(pn(e(r),i))}return n.length>1?n.join(" AND "):n[0]}function wn(t){const e=t.indexOf("://");if(e>0)return t.substring(0,e)}function gn(t,e=0){let n,r=t*10**e;return t>=1e12?(r=Math.round(r/1e12),n="T"):t>=1e9?(r=Math.round(r/1e9),n="B"):t>=1e6?(r=Math.round(r/1e6),n="M"):t>=1e3?(r=Math.round(r/1e3),n="K"):(r=Math.round(r),n=""),r/=10**e,r.toFixed(e)+n}function vn(t){const e=t.match(/^\s*[+]?(\d+(?:[.]\d+)?)\s*([TBMK])?\s*$/i);if(!e)throw new y.CommonError("Invalid formatted parameter size string.","scaleToSize",y.ErrorCode.InvalidArgument);const n=parseFloat(e[1]),r=e[2]?.toLowerCase();switch(r){case"t":return 1e12*n;case"b":return 1e9*n;case"m":return 1e6*n;case"k":return 1e3*n;default:return n}}function bn(t,e){const n=e?.level||0,r=e?.visiting||new Set,i=e?.objectTag||"*",s=e?.arrayTag||"-";let o=[];const a=" ".repeat(2*n);if(null!=t)switch(typeof t){case"object":r.has(t)?o=["[Circular]"]:(r.add(t),o=Array.isArray(t)?t.map((t=>s+c(t))):Object.entries(t).map((([t,e])=>i+" `"+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":" ")+bn(t,{level:n+1,visiting:r})}}(0,sn.registerYamlTag)(on.regexp);var Sn=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}},kn=require("util-ex"),En=require("events-ex");function Tn(t=0){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 $n=class extends Array{constructor(t,e){Array.isArray(t)?(super(...t),this._length=t.length,t=void 0):(super(),this._length=0),this._capacity=Tn(t),this._front=0,this._disableAutoResize=e}push(t){let e=this._length;this.checkCapacity(e+1);const n=this._front+e&this._capacity-1;return this[n]=t,++e<=this._capacity&&(this._length=e),n}unshift(t){let e=this._length;this.checkCapacity(++e);const n=this._capacity,r=(this._front-1&n-1^n)-n;return this[r]=t,this._front=r,e<=this._capacity&&(this._length=e),r}pop(t){let e=this._length;if(0===e)return;let n=this._front+e-1&this._capacity-1,r=this[n];for(;--e>0&&t&&null==r;)n--,r=this[n];return this[n]=void 0,this._length=e,r}shift(t){let e=this._length;if(0===e)return;let n=this._front,r=this[n];for(;--e>0&&t&&null==r;)n=n+1&this._capacity-1,r=this[n];return this[n]=void 0,this._front=n+1&this._capacity-1,this._length=e,r}get size(){return this._length}get(t){let e;if(t===(0|t)){const n=this._length;t<0&&(t+=n),t>=0&&t<n&&(e=this[this._front+t&this._capacity-1])}return e}peekBack(){const t=this._length;if(0===t)return;return this[this._front+t-1&this._capacity-1]}peekFront(){if(0!==this._length)return this[this._front]}clear(){const t=this._length,e=this._front,n=this._capacity;for(let r=0;r<t;++r)this[e+r&n-1]=void 0;this._length=0,this._front=0}isEmpty(){return 0===this._length}removeAt(t){const e=this._length;if(t<0||t>=e)return;const n=this._front,r=this._capacity-1,i=n+t&r,s=this[i];if(t<e/2)this.copyWithin(n+1&r,n,n+t&r),this[n]=void 0,this._front=n+1&r;else{this.copyWithin(i,i+1&r,n+e&r);this[n+e-1&r]=void 0}return this._length=e-1,s}checkCapacity(t){this._capacity<t&&!this._disableAutoResize&&this.resizeTo(Tn(1.5*this._capacity+16))}resizeTo(t){const e=this._capacity;this._capacity=t;const n=this._front,r=this._length;if(n+r>e){!function(t,e,n,r,i){for(let s=0;s<i;++s)n[s+r]=t[s+e],t[s+e]=void 0}(this,0,this,e,n+r&e-1)}}},xn=require("@isdk/common-error"),An=32;function Cn(t){return"function"==typeof t}function In(){return"1"}var On=class{constructor(t={}){const{initFn:e=In,pauseFn:n,resumeFn:r,capacity:i=An}=t;if(Cn(n)!==Cn(r))throw new Error("pauseFn and resumeFn must be both set for pausing");this.waiting=new $n(i),this.emitter=new En.EventEmitter,this.useDefaultTokens=e===In,this.pauseFn=n,this.resumeFn=r,this.initTokenFn=e,this.paused=!1,this._activeCount=0,this.initFree(t),this.init(t)}initFree(t){this.free=this.initTokenFn()}onReleased(t){const e=t?.token,n=this.waiting.shift(!0);n?this._dispatchTask(n,t):(this.resumeFn&&this.paused&&(this.paused=!1,this.resumeFn()),this.unlock(e))}init(t){this.emitter.on("release",(t=>{this.onReleased(t)}))}_newReleaser(t){let e=!1;const n=()=>{e||(e=!0,this.release(t))};return t&&Object.assign(n,t),n}_dispatchTask(t,e){const{resolve:n}=t;n(this._newReleaser(e))}lock(t){let e=this.free;if(e)return this.free=void 0,e}unlock(t){this.free=this.useDefaultTokens?"1":t??this.initTokenFn()}tryAcquire(t){return this.lock(t)}async acquire(t){this._activeCount++;const e=t?.signal,n=t=>{this.pauseFn&&!this.paused&&(this.paused=!0,this.pauseFn());const n=this.waiting.push(t),r=t.reject;return e&&e.addEventListener("abort",(()=>{this.waiting[n]=void 0;const t=e.reason instanceof Error?e.reason:new xn.AbortError(e.reason||"aborted");e.alreadyRejected=!0,r(t)})),n};let r=this.tryAcquire(t);const i=r&&(0,kn.isAsync)(r),s=e=>new Promise(((r,i)=>{const s={...t,resolve:r,reject:i,token:e};void 0===e?n(s):this._dispatchTask(s,{...t,token:e})}));return i?r.then((t=>s(t))):s(r)}release(t){this._activeCount--,this.emitter.emit("release",t)}drain(){const t=[this.acquire()];return Promise.all(t)}abort(t){let e;for(;e=this.waiting.shift(!0);)e.reject(new xn.AbortError(t))}get activeCount(){return this._activeCount}get pendingCount(){return this.waiting.size}},Nn=class extends On{constructor(t,e){if("number"==typeof t)(e=e||{}).maxConcurrency=t;else{if("number"!=typeof(e=t).maxConcurrency)throw new Error("maxConcurrency must be set");t=e.maxConcurrency}super(e),this.maxConcurrency=e.maxConcurrency,e.isReadyFn&&(this.isReady=e.isReadyFn)}initFree(t){const e=t.maxConcurrency=Math.max(1,t.maxConcurrency);this.free=new $n(e);for(let t=0;t<e;t++)this.free.push(this.initTokenFn())}tryAcquire(t){let e=this.isReady;if(e&&(0,kn.isAsync)(e)){return e instanceof Promise||(e=e()),e.then((e=>{if(e)return this.lock(t)}))}if(!e||e())return this.lock(t)}unlock(t){this.free.push(this.useDefaultTokens?"1":t??this.initTokenFn())}lock(t){return this.free.pop()}drain(){const t=new Array(this.maxConcurrency);for(let e=0;e<this.maxConcurrency;e++)t[e]=this.acquire();return Promise.all(t)}};function jn(t,{timeUnit:e=1e3,uniformDistribution:n=!1}={}){const r=new Nn(n?1:t),i=n?e/t:e;return async function(){await r.acquire(),setTimeout((()=>r.release()),i)}}var Rn,qn=require("@isdk/common-error"),Mn=class{constructor(){this._isSignaled=!1,this.waitQueue=[]}get signaled(){return this._isSignaled}signal(t){if(this._isSignaled)return;this._isSignaled=!0,this._signalValue=t;const e=this.waitQueue.slice();for(this.waitQueue.length=0;e.length>0;){const t=e.shift();t?.resolve(this._signalValue)}}reset(){this._isSignaled=!1,this._signalValue=void 0,this.waitQueue.length=0}abort(t){if(this.waitQueue.length){const e=this.waitQueue.slice();this.waitQueue.length=0;const n=new qn.AbortError(t);for(;e.length>0;){const{reject:t}=e.shift();t(n)}}}async wait(){return new Promise(((t,e)=>{this._isSignaled?t(this._signalValue):this.waitQueue.push({resolve:t,reject:e})}))}},Fn=require("custom-ability"),Ln=require("util-ex"),Pn=0,zn=1,_n=2,Dn=(t=>(t[t.MultiTask=Pn]="MultiTask",t[t.Cancelable=zn]="Cancelable",t[t.Priority=_n]="Priority",t))(Dn||{}),Xn=((Rn=Xn||{})[Rn.MultiTask=1<<Pn]="MultiTask",Rn[Rn.Cancelable=1<<zn]="Cancelable",Rn[Rn.Priority=1<<_n]="Priority",Rn),Bn=class extends AbortController{constructor(t){super(),(0,Ln.defineProperty)(this,"parent",t)}abort(t,e){this.signal.aborted||("string"==typeof t&&(t=new y.AbortError(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 y.AbortError(e.reason||"aborted")}}},Un=class{get maxTaskConcurrency(){return this._maxTaskConcurrency}get semaphore(){return this.getSemaphore()}getSemaphore(t=this._isReadyFn){let e=this._maxTaskConcurrency,n=this.__task_semaphore;return e>0&&!n&&(t&&(t=t.bind(this)),n=this.__task_semaphore=new Nn(e-1,{isReadyFn:t})),n}static hasAsyncFeature(t){const e=this.prototype;let n=e.asyncFeatures;return e._asyncFeatures&&(n|=e._asyncFeatures),Sn.has(n,t)}hasAsyncFeature(t){let e=this.asyncFeatures;return this._asyncFeatures&&(e|=this._asyncFeatures),Sn.has(e,t)}isAborted(t){const e=this.hasAsyncFeature(Pn);let n=this.__task_aborter;if(n&&e){if(null==t)throw new y.CommonError("Missing taskId",this.name+".isAborted",y.ErrorCode.InvalidArgument);n=n[t]}return!n||n.signal.aborted}getRunningTask(t){const e=this.hasAsyncFeature(Pn);let n=this.__task_aborter;if(n&&e){if(null==t)throw new y.CommonError("Missing taskId",this.name+".getRunningTask",y.ErrorCode.InvalidArgument);n=n[t]}return n?.signal.aborted&&(e?this.__task_aborter[t]=void 0:this.__task_aborter=void 0,n=void 0),n}getRunningTaskCount(){let t;if(this.hasAsyncFeature(Pn)){const e=this.__task_aborter;t=e&&Object.entries(e).filter((([t,n])=>{if(!n?.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 n=this.super,r=this.self||this;return t=n?n.call(r,t):this._generateAsyncTaskId(t,e)}createAborter(t,e,n=!0){const r=this.hasAsyncFeature(Pn);if(!r&&n&&this.getRunningTask())throw new y.CommonError("The task is running",this.name,y.ErrorCode.TooManyRequests);const i=t?.aborter||new Bn(this);if(!(i instanceof Bn)){if(!(i instanceof AbortController))throw new y.CommonError("aborter should be an AbortController",this.name,y.ErrorCode.InvalidArgument);Object.setPrototypeOf(i,new Bn(this))}if(r){null==this.__task_aborter&&(this.__task_aborter={});const t=this.__task_aborter;null==e&&(e=this.generateAsyncTaskId(e,t)),i.id=e,t[e]=i}else this.__task_aborter=i;const s=t?.timeout;return s>0&&(i.timeoutId=setTimeout((()=>{i.timeoutId=void 0,this.abort("timeout",{timeout:s})}),s)),i.signal.addEventListener("abort",(()=>{const t=i.timeoutId;t&&(i.timeoutId=void 0,clearTimeout(t));const e=i.signal;try{this.emit&&this.emit("aborting",e.reason,e.reason?.data)}finally{i.streamController?.error(e.reason)}})),i}$cleanMultiTaskAborter(t,e){const n=this.super,r=this.self||this;n?n.call(r,t,e):r._cleanMultiTaskAborter(t,e)}cleanTaskAborter(t){if(this.hasAsyncFeature(Pn)){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,n){const r=this.createAborter(e,n?.taskId,n?.raiseError);void 0===e&&(e={}),"object"==typeof e&&(e.aborter=r);let i=t(e,r).then((t=>{if(t&&t instanceof ReadableStream){const e=()=>{this.cleanTaskAborter(r)},n=Nt({onStart:t=>{(0,Ln.defineProperty)(r,"streamController",t)},onFinal:e,onError:e,onTransform:(t,e)=>(t&&"object"==typeof t&&(t.taskId=r.id),t)});t=t.pipeThrough(n)}else this.cleanTaskAborter(r);return t})).catch((t=>{throw this.cleanTaskAborter(r),t})).finally((()=>{r.timeoutId&&(clearTimeout(r.timeoutId),r.timeoutId=void 0)}));return i.task=r,i}runAsyncCancelableTask(t={},e,n){let r=this.createTaskPromise(e,t,n);const i=this.getSemaphore(n?.isReadyFn);if(i){const t=r,e=t.task;r=i.acquire({signal:e.signal}).then((()=>t)).finally((()=>{i.release()})),r.task=e}return r}abort(t,e){let n=this.__task_aborter;if(n){const r=n;if(this.hasAsyncFeature(Pn)){const t=e?.taskId;if(null==t)throw new y.CommonError("Missing data.taskId",this.name+".abort",y.ErrorCode.InvalidArgument);n=n[t],this.cleanMultiTaskAborter(t,r)}else this.__task_aborter=void 0;n&&!n.signal.aborted&&n.abort(t,e)}}};Un.prototype.generateAsyncTaskId=function(t,e){return this._generateAsyncTaskId(t,e)},Un.prototype.cleanMultiTaskAborter=function(t,e){return this._cleanMultiTaskAborter(t,e)};var Gn=(0,Fn.createAbilityInjector)(Un,"abort",{afterInjection:function(t,e){let n=t.prototype._asyncFeatures||0;n|=Xn.Cancelable,e&&(e.asyncFeatures&&(n|=e.asyncFeatures),e.maxTaskConcurrency>0&&(t.prototype._maxTaskConcurrency=e.maxTaskConcurrency),e.isReadyFn&&"function"==typeof e.isReadyFn&&(t.prototype._isReadyFn=e.isReadyFn)),t.prototype._asyncFeatures=n}});function Wn(t,e){const n=e.global?e:new RegExp(e.source,`${e.flags}g`);let r,i=0;for(;null!==(r=n.exec(t));)i++;return i}var Jn=c(require("memoizee")),Hn=require("json-canonicalize");function Kn(t,e){var n;void 0!==e?.promise||!function(t){return"function"==typeof t&&"AsyncFunction"===t.constructor.name}(t)&&(!(n=t)||"object"!=typeof n&&"function"!=typeof n||"function"!=typeof n.then)||(e={promise:!0,...e}),void 0===e?.length&&(e={length:!1,...e});const r=e?.normalizer;return(0,Jn.default)(t,{...e,normalizer:t=>{if(r){const e=r(t);if("string"===e)return e;e&&(t=e)}return Kt((0,Hn.canonicalize)(t))}})}var Vn=c(require("net"));async function Zn(t,e=10){return new Promise(((n,r)=>{void 0===t?t=0:("string"==typeof t&&(t=parseInt(t)),t>=0||(t=0));const i=Vn.default.createServer();i.on("error",(n=>{"EADDRINUSE"===n.code&&(t++,--e>0)?i.listen(t):r(n)})),i.on("listening",(async()=>{const t=i.address().port;i.close(),n(t)})),i.listen(t)}))}var Qn=c(require("path")),Yn=require("pkg-dir");function tr(t){const e=(0,Yn.packageDirectorySync)({cwd:t});if(e)return e;const n=t.split(Qn.default.sep);let r=n.lastIndexOf("dist");if(r>0)return n.slice(0,r).join(Qn.default.sep);if(r=n.lastIndexOf("src"),r>0)return n.slice(0,r).join(Qn.default.sep);throw new Error("can not find package directory")}var er=c(require("path"));function nr(t,e){try{const n=er.default.relative(er.default.resolve(t),er.default.resolve(e));return!n.startsWith("..")&&!er.default.isAbsolute(n)}catch{return!1}}function rr(t,e){return e?.some((e=>nr(e,t)))}function ir(t,e){for(const n of e)rr(n,t)||t.push(n);return t}var sr=require("util-ex");function or(t){return(0,sr.isRegExpStr)(t)||(0,sr.isRegExp)(t)}function ar(t){return t.replace(/\x1B[[(?);]{0,2}(;?\d)*./g,"")}var cr=c(require("path")),ur=require("url"),hr=require("@xenova/transformers"),lr=(0,ur.fileURLToPath)(h),fr=cr.default.dirname(lr),dr=cr.default.join(tr(fr),".cache"),mr=new Map,pr={"deepseek-ai/DeepSeek-V2-Lite-Chat":"deepseek2","Qwen/Qwen2.5-0.5B":"Qwen2.5","Xenova/gpt-4":"gpt-4 / gpt-3.5-turbo / text-embedding-ada-002","Xenova/text-davinci-003":"text-davinci-003 / text-davinci-002","Xenova/gpt-3":"gpt-3","Xenova/grok-1-tokenizer":"Grok-1","Xenova/claude-tokenizer":"Claude","Xenova/mistral-tokenizer-v3":"Mistral v3","Xenova/mistral-tokenizer-v1":"Mistral v1","Xenova/gemma-tokenizer":"Gemma","Xenova/gemma2-tokenizer":"Gemma2","Xenova/llama3-tokenizer-new":"Llama 3","unsloth/Llama-3.2-1B-Instruct":"Llama 3.2","Xenova/llama-tokenizer":"LLaMA / Llama 2","Xenova/c4ai-command-r-v01-tokenizer":"Cohere Command-R","Xenova/t5-small":"T5","Xenova/bert-base-cased":"bert-base-cased"},yr={deepseek2:"deepseek-ai/DeepSeek-V2-Lite-Chat","qwen2.5":"Qwen/Qwen2.5-0.5B","gpt-4":"Xenova/gpt-4","gpt-3.5-turbo":"Xenova/gpt-4","text-embedding-ada-002":"Xenova/gpt-4","text-davinci-003":"Xenova/text-davinci-003","text-davinci-002":"Xenova/text-davinci-003","gpt-3":"Xenova/gpt-3","grok-1":"Xenova/grok-1-tokenizer",claude:"Xenova/claude-tokenizer",mistral:"Xenova/mistral-tokenizer-v3",mistral3:"Xenova/mistral-tokenizer-v3",mistral1:"Xenova/mistral-tokenizer-v1",gemma:"Xenova/gemma-tokenizer",gemma2:"Xenova/gemma2-tokenizer",llama3:"Xenova/llama3-tokenizer-new",llama2:"Xenova/llama-tokenizer",llama:"Xenova/llama-tokenizer","llama3.2":"unsloth/Llama-3.2-1B-Instruct","cohere-command-r":"Xenova/c4ai-command-r-v01-tokenizer",t5:"Xenova/t5-small","bert-cased":"Xenova/bert-base-cased"};async function wr(t){let e=mr.get(t);return e||(e=hr.AutoTokenizer.from_pretrained(t,{cache_dir:dr}),mr.set(t,e)),e}async function gr(t,e="qwen2.5"){yr[e]&&(e=yr[e]);return(await wr(e)).encode(t)}async function vr(t,e="qwen2.5"){return(await gr(t,e)).length}function br(t,e){const n=e?.capitalize??!0;let r=e?.delimiter??/[_-]/g;r instanceof RegExp&&(r.flags.includes("g")||(r=new RegExp(r.source,r.flags+"g")));let i=(t=t.replace(r," ")).split(" ").map((t=>t.trim())).filter(Boolean);return n&&(i=i.map((t=>t.charAt(0).toUpperCase()+t.slice(1)))),t=i.join(" ")}async function Sr(t,e){let n,r=1984,i=!0,s=!1,o=!0,a=vr,c=!0;if(e&&(n=e.modelId,e.size>=0&&(r=e.size),void 0!==e.corrected&&(i=e.corrected),void 0!==e.completeSentence&&(s=e.completeSentence),void 0!==e.truncLastSection&&(o=e.truncLastSection),"function"==typeof e.countLLMTokens&&(a=e.countLLMTokens),void 0!==e.bySentence&&(c=e.bySentence)),!c)throw new y.NotImplementationError("truncateToTokenLimit only implemented by sentence","truncateToTokenLimit");if(r>0){let c=await a(t,n);const u=e?.sentences??H(t,e);if(c>r)for(c=await a(u.join("\n"),n);c>r&&u.length;){const e=u.pop();if(e){if(c-=await a(e+"\n",n),s||i)t=u.join("\n");else{const n=t.lastIndexOf(e);if(-1===n)throw new y.CommonError(`Can not find sentence: ${e}`,"truncateContentToTokenLimit");t=t.slice(0,n)}if(c<=1)throw new y.CommonError(`Can not truncate content to fit within the token limit: ${r}`,"truncateContentToTokenLimit");if(c<=r&&o){const e=u[u.length-1];if(e&&Q(e)){if(c-await a(e,n)>9){const n=t.lastIndexOf(e);if(-1===n)throw new y.CommonError(`Can not find sentence: ${e}`,"truncateContentToTokenLimit");t=t.slice(0,n).trimEnd()}}}}else c--}else t=u.join("\n")}if(!t)throw new y.CommonError(`Can not truncate content to fit within the token limit: ${r}`,"truncateContentToTokenLimit");return t}async function kr(t,e){let n,r=1984,i=!0,s=vr,o=!0;if(e&&(n=e.modelId,e.size>=0&&(r=e.size),void 0!==e.truncLastSection&&(i=e.truncLastSection),"function"==typeof e.countLLMTokens&&(s=e.countLLMTokens),void 0!==e.bySentence&&(o=e.bySentence)),!o)throw new y.NotImplementationError("truncateToTokenLimit only implemented by sentence","truncateToTokenLimit");if(r>0){const e=(t=t.slice()).join("\n");let o=await s(e,n);if(o>r)for(;o>r&&t.length;){const e=t.pop();if(e){if(o-=await s(e,n),o<=1)throw new y.CommonError(`Can not truncate content to fit within the token limit: ${r}`,"truncateContentToTokenLimit");if(o<=r&&i){const e=t[t.length-1];if(e&&Q(e)){o-await s(e,n)>9&&t.pop()}}}}}if(!t.length)throw new y.CommonError(`Empty. Can not truncate content to fit within the token limit: ${r}`,"truncateContentToTokenLimit");return t}async function Er(t,e){let n,r=1984,i=vr;if(e&&(n=e.modelId,"function"==typeof e.countLLMTokens&&(e.size>=0&&(r=e.size),i=e.countLLMTokens)),r>0){await i(t,n)}}var Tr=c(require("fs"));async function*$r(t,e){const n=(e={...e,completeSentence:!1,corrected:!1}).size??1984,r=e.modelId,i=e.metaInfo?.size??(await Tr.default.promises.stat(t)).size;let s=Math.trunc(i/2);if(s<=n){let i=Ke(await Tr.default.promises.readFile(t));if(s=await vr(i,r),s<=n)yield i;else do{const t=await Sr(i,{...e,modelId:r,size:n});yield t,i=i.slice(t.length)}while(i)}else{const i=ReadableStream.from(Tr.default.createReadStream(t)).getReader();let s="";for(;;){const{done:t,value:o}=await i.read();if(t)break;s+=Ke(o);const a=H(s,e);let c=a.pop();if(c){const t=s.lastIndexOf(c);c=s.slice(t),s=s.slice(0,t)}if(s.length>=n){const t=await Sr(s,{...e,modelId:r,size:n,sentences:a});s=s.slice(t.length),yield t}for(;s.length>n;){const t=H(s,e),i=await Sr(s,{...e,modelId:r,size:n,sentences:t});s=s.slice(i.length),yield i}void 0!==c&&(s+=c)}for(;s;){const t=H(s,e),i=await Sr(s,{...e,modelId:r,size:n,sentences:t});s=s.slice(i.length),yield i}}}async function*xr(t,e){const n=e?.size??1984,r=e?.modelId,i=e?.metaInfo?.size??(await Tr.default.promises.stat(t)).size;let s=Math.trunc(i/2);if(s<=n){let i=Ke(await Tr.default.promises.readFile(t));if(s=await vr(i,r),s<=n)yield H(i,e);else{let t=H(i,e);do{const i=await kr(t,{...e,modelId:r,size:n});yield i,t=t.slice(i.length)}while(t.length)}}else{const i=ReadableStream.from(Tr.default.createReadStream(t)).getReader();let s="";const o=e?.completeSentence,a=e?.corrected,c=!o&&!a;let u;for(;;){const{done:t,value:o}=await i.read();if(t)break;s+=Ke(o),u=H(s,e);let a=u.pop();if(s.length>=n){const t=await kr(u,{...e,modelId:r,size:n});s=c?s.slice(t.length):u.join("\n"),u=u.slice(t.length),s=u.join("\n"),yield t}for(;s.length>n;){const t=await kr(u,{...e,modelId:r,size:n});u=u.slice(t.length),s=u.join("\n"),yield t}a&&u.push(a)}if(u)for(;u.length;){const t=await kr(u,{...e,modelId:r,size:n});u=u.slice(t.length),yield t}}}async function Ar(t,e){const n=e?.size??1984,r=e?.modelId;let i=H(t,e);const s=[];if(await vr(t,r)<=n)s.push(i);else do{const t=await kr(i,{...e,modelId:r,size:n});s.push(t),i=i.slice(t.length)}while(i.length);return s}var Cr=require("yaml"),Ir=class{constructor(t){t&&Object.assign(this,t)}};function Or(t,e){class n extends Cr.YAMLMap{constructor(){super(...arguments),this.tag=t}toJSON(t,n){n={...n,mapAsMap:!1};const r=super.toJSON(t,n);return new e(r)}}return{tag:t,collection:"map",nodeClass:n,identify:t=>t instanceof e}}function Nr(t,e){let n=t.length===e.length;if(n){const r=Ht(t),i=Ht(e);n=r.every(((t,e)=>t===i[e]))}return n}var jr=require("lodash-es"),Rr=c(require("path")),qr=".ai";function Mr(t,e=["."]){if(Rr.default.isAbsolute(t))return cn.ConfigFile.loadSync(t);const n=e.map((e=>cn.ConfigFile.loadSync(Rr.default.resolve(e,t)))).filter(Boolean);return(0,jr.defaultsDeep)({},...n.reverse())}function Fr(t,e){const n={...process.env,...e};return(0,A.expandObjEnv)(t,{processEnv:n,parsed:n})}function Lr(t,e){let n=cn.ConfigFile.loadSync(Rr.default.resolve(e.configDir,t));n||(n={configDirs:["$XDG_BIN_HOME",e.configDir,"$HOME"],brainDir:[Rr.default.join(e.dataDir,"brain")],agentDirs:[Rr.default.join(e.dataDir,"agent")],promptDirs:[Rr.default.join(e.dataDir,"prompt")],chatsDir:Rr.default.join(e.dataDir,"log","chats"),inputsDir:Rr.default.join(e.dataDir,"log","inputs")});const r=zr(e);for(const[t,e]of Object.entries(r))n[t]=e;Fr(n,n);const i=n.configDirs;n.AI_CONFIG_BASENAME&&(t=n.AI_CONFIG_BASENAME);const s=Fr(Mr(t,i),n);return(0,jr.defaultsDeep)(s,(0,jr.omit)(n,Object.keys(r)))}function Pr(t){return Lr(qr,t)}function zr(t){return{XDG_CONFIG_HOME:t.configDir,XDG_DATA_HOME:t.dataDir,XDG_CACHE_HOME:t.cacheDir,XDG_BIN_HOME:Rr.default.dirname(t.options.root)}}function _r(t,e){t.startsWith("~")&&(t="$HOME"+t.slice(1));return Fr(t,e)}var{exit:Dr}=process,Xr=!1,Br=!1,Ur=["SIGINT","SIGTERM","exit"],Gr=3e5,Wr=[],Jr=(t,e)=>t.forEach((t=>process.once(t,e))),Hr=t=>()=>{setTimeout((()=>(console.warn(`Could not close resources gracefully after ${t}ms: forcing shutdown`),Dr(1))),t).unref()};async function Kr(t="shutdown",e=0){if(!Xr){Xr=!0,"number"==typeof t&&(e=t,t="shutdown");for(const e of Wr)try{await e(t)}catch(t){console.warn(`A shutdown handler failed before completing with: ${t.message||t}`)}return Dr(e)}console.warn(`Shutdown already in progress, ignoring [${t}] signal`)}function Vr(t){if(Br||Zr(),!Wr.some((e=>e===t)))return Wr.push(t),t}function Zr(){Br||(Br=!0,process.exit=t=>{Xr||Kr(void 0,t).then()},Jr(Ur,Hr(Gr)),Jr(Ur,Kr))}var Qr=require("property-manager"),Yr=require("util-ex"),ti=class t extends Qr.AdvancePropertyManager{static{this.items={}}static{this.aliases={}}static get(t){let e=this.items[t];return!e&&(t=this.aliases[t])&&(e=this.items[t]),e}static list(){return this.items}static getByTag(t){let e;for(const n in this.list()){const r=this.get(n);let i=r.tags;if("string"==typeof i){if(i===t){e=r;break}}else if(Array.isArray(i)&&i.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 i=r.tags;"string"==typeof i?i===t&&e.push(r):Array.isArray(i)&&i.indexOf(t)>=0&&e.push(r)}return e}static hasAsyncFeature(t){const e=this.prototype;let n=e.asyncFeatures;return e._asyncFeatures&&(n|=e._asyncFeatures),Sn.has(n,t)}static run(t,e){const n=this.get(t);if(n)return n.run(e);throw new y.NotFoundError(`${t} to run`,this.name)}static runSync(t,e){const n=this.get(t);if(n)return n.runSync(e);throw new y.NotFoundError(`${t} to run`,this.name)}static getFunc(t){const e=this.get(t);return e?.getFunc()}static runWithPos(t,...e){const n=this.get(t);if(n)return n.runWithPos(...e);throw new y.NotFoundError(`${t} to run`,this.name)}static runWithPosSync(t,...e){const n=this.get(t);if(n)return n.runWithPosSync(...e);throw new y.NotFoundError(`${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();if(this.items[e]=n,n.alias){const t=n.alias;if("string"==typeof t)this.aliases[t]&&(0,y.throwError)(`Alias ${t} already exists for ${e}`),this.aliases[t]=e;else if(Array.isArray(t))for(const n of t)this.aliases[n]&&(0,y.throwError)(`Alias ${n} already exists for ${e}`),this.aliases[n]=e}r=n}return r}static unregister(t){const e=this.get(t);if(e&&(delete this.items[t],e.alias)){const t=e.alias;if("string"==typeof t)delete this.aliases[t];else if(Array.isArray(t))for(const e of t)delete this.aliases[e]}return 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 i=0;i<r;i++)e[n[i]]=t[i];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 i=0;i<r;i++)e.push(t[n[i]])}return e}runSync(t){const e=this.params&&Array.isArray(this.params);if(Array.isArray(t)){if(e)return this.func(...t);(0,y.throwError)("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),Sn.has(e,t)}isStream(t){return this.stream}},ei={name:{type:"string"},description:{type:"string"},func:{type:"function",assign(t,e,n,r,i){let s=t;const o=typeof t;return i.isExported?s="function"===o?t.toString():t:t&&("string"!==o&&(t=t.toString()),s=(0,Yr._createFunction)(t,e.scope)),s}},params:{type:"object"},result:{type:"any"},setup:{type:"function"},depends:{type:"object",exported:!1},tags:{type:["array","string"]},isApi:{type:"boolean"},stream:{type:"boolean"},asyncFeatures:{type:"number"},alias:{type:["array","string"]}};ti.defineProperties(ti,ei);var ni=class t extends ti{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(0,y.throwError)("missing apiRoot to load tools","ClientTools")}static loadFromSync(e){for(const n in e){const r=this.get(n),i=e[n];r?r instanceof t?r.assign(i):(0,y.throwError)(`${n} already registered as ${r.constructor.name}`,"ClientTools"):this.register(i)}}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},i=["post","put","patch"];let s;e||(e=this.action||"post"),"res"===e&&(e="get"),r.headers&&r.headers["Content-Type"]||!i.includes(e)||(r.headers={"Content-Type":"application/json",...r.headers}),t?.stream&&!r.headers.Connection&&(r.headers.Connection="keep-alive"),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),r.headers&&!i.includes(e)&&delete r.headers["Content-Type"];const o=await fetch(`${this.apiRoot}/${s}`,r);if(!o.ok){throw await this.errorFrom(o)}return o}async errorFrom(t){let e,n=t.status,r=t.statusText,i=this.name;if(t.body){const n=await t.text();try{const t=JSON.parse(n);t&&(t.error&&(r=t.error),t.name&&(i=t.name),t.data&&(e=t.data,e.name=i,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(0,y.createError)(r,i,n)}async func(t){const e=await this.fetch(t);if(t?.stream)return e;return await e.json()}},ri={...p};ni.defineProperties(ni,ri);var ii=class t extends ti{static get apiRoot(){return this._apiRoot}static setApiRoot(t){this._apiRoot=t}static toJSON(){const e={};for(const n in this.items){let r=this.items[n];(r instanceof t||r.isApi)&&(r.allowExportFunc||(r=r.toJSON(),delete r.func),e[n]=r)}return e}func({}){}},si={...p};ii.defineProperties(ii,si);var oi=require("events-ex"),ai=class extends ti{constructor(){super(...arguments),this._emitter=new oi.EventEmitter,this.description="Return event bus",this.result="event"}get emitter(){return this._emitter}func(){return this.emitter}},ci=new ai(pt),ui=require("secondary-cache"),hi=require("secondary-cache"),li=ui.Cache;function fi({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 di(t,e){let n=ti.get(t);return n||(n=new ti(t,{func:fi,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 ui.Cache(e)),n}var mi=di("lrucache"),pi=class extends ni{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))}}},yi={methods:{type:"array",assign(t,e,n,r,i){i?.isExported||e.assignMethods(t)}}};pi.defineProperties(pi,yi);var wi=class extends pi{async fetch(t,e){if(t||(t={}),e&&"res"===this.action){if("get"===e||"delete"===e){let n=t.id;return n||(0,y.throwError)("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)}},gi=class extends wi{constructor(){super(...arguments),this._sseEvents={},this._forwardEvents=new Set,this.name=mt,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)}},vi=new gi(mt),bi=require("util-ex"),Si=class extends ii{constructor(t,e={}){super(t,e),this.params={act:{type:"string"}};const n=this.methods=[];this.initRpcMethods(n)}get SpecialRpcMethodNames(){return this.constructor.SpecialRpcMethodNames}initRpcMethods(t=this.methods){const e=this.SpecialRpcMethodNames;if(Array.isArray(e))for(const n of e)"function"==typeof this[n]&&t.push(n);(0,bi.getAllNames)(Object.getPrototypeOf(this)).filter((t=>t.startsWith("$")&&"function"==typeof this[t])).forEach((e=>{t.push(e);const n=e.slice(1);void 0===this[n]&&(this[n]=this[e])}))}cast(t,e){let n=this.params[t];return n&&("string"!=typeof n&&(n=n.type),"number"===n&&(e=Number(e))),e}getMethodFromParams(t){const e=t?.act;return e}castParams(t){return t}func(t){const e=this.getMethodFromParams(t);if(e&&"function"==typeof this[e])return t=this.castParams(t),this[e](t);throw new y.NotFoundError(e,this.name)}};Si.defineProperties(Si,{methods:{type:"array"}});var ki=class extends Si{constructor(t,e={}){super(t,e),this.action="res",this.params={id:{type:"string"},val:{type:"any"}}}static{this.SpecialRpcMethodNames=m}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}castParams(t){return void 0!==t.id&&(t.id=this.cast("id",t.id)),t}},Ei=ci.runSync(),Ti=class t extends ki{constructor(){super(...arguments),this.name=mt,this.description="subscribe server sent event",this.result="event",this.depends={[pt]:ci}}static get sse(){return this._sse||(this._sse=new vt),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=Ei.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)||Ei.on(n,t.ebListener)}unforward(e){"string"==typeof e&&(e=[e]);for(const n of e)Ei.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};(0,y.throwError)("event is required","sub",y.ErrorCode.InvalidArgument)}$unsub({event:t}){if(t)return this.unforward(t),{event:t};(0,y.throwError)("event is required","unsub",y.ErrorCode.InvalidArgument)}$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}}(0,y.throwError)("event or data is required","pub",y.ErrorCode.InvalidArgument)}isStream(t){return"list"===this.getMethodFromParams(t)}},$i=new Ti(mt);function xi(){ci.register(),mi.register()}
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{AIArgProcessor as s,AIChatRoles as a,AIMessageTypes as u,AIStream as i,AITextGenerationFinishReasons as e,AbortError as r,AbortErrorCode as t,ActionNames as n,AlreadyExistsError as d,AlreadyExistsErrorCode as m,AsyncFeatureBits as o,AsyncFeatures as f,BaseError as p,BinarySemaphore as v,CancelableAbility as h,ChoiceArgProcessor as F,ClientToolFuncSchema as H,ClientTools as k,CommonError as l,ConfigFile as I,DEFAULT_CONFIG_NAME as P,DefaultAsyncSemaphoreCapacity as V,EnvPromptTemplate as c,EnvironmentEx as j,ErrorCode as B,EventBusName as E,EventClient as G,EventEmitter as L,EventName as N,EventServer as S,EventToolFunc as T,FStringPromptTemplate as X,FewShotPromptTemplate as g,FilenameReservedRegex as x,GolangPromptTemplate as y,HashAlgorithm as z,HfPromptTemplate as O,IntSet as W,InternalErrorCode as b,Interpreter as q,LLM_TOKENIZER_NAMES as w,LLM_TOKENIZER_NAMES_MAP as A,LRUCache as C,NIL as D,NotFoundError as J,NotFoundErrorCode as K,NotImplementationError as M,NotImplementedErrorCode as Q,ObjectArgsToArgsInfo as R,PASSING_SCORE as U,PromptExampleSelector as Y,PromptTemplate as Z,PromptTemplateTypes as $,PromptTypes as _,RStreamErrCode as ss,RateLimit as as,ReadableStreamError as us,RemoteToolFuncSchema as is,ResClientTools as es,ResServerTools as rs,ResponseRStreamErrCode as ts,SHUTDOWN_SIGNALS as ns,SSEChannel as ds,SSEChannelAlreadyClosedErrCode as ms,SecondaryCache as os,Semaphore as fs,ServerToolFuncSchema as ps,ServerTools as vs,SignalGate as hs,TaskAbortController as Fs,Template as Hs,TemplateArgProcessor as ks,ToolAsyncCancelableBit as ls,ToolAsyncMultiTaskBit as Is,ToolAsyncPriorityBit as Ps,ToolFunc as Vs,ToolFuncSchema as cs,WindowsReservedNameRegex as js,YamlTypeBaseObject as Bs,_lrucache as Es,assignDirs as Gs,backendEventable as Ls,base32768 as Ns,beforeShutdown as Ss,builtins as Ts,canonicalize as Xs,completeSentences as gs,concatText as xs,countLLMTokens as ys,countRegexMatches as zs,createAbilityInjector as Os,createCallbacksTransformer as Ws,createEmptyReadableStream as bs,createEndWithRepetitionDetector as qs,createError as ws,createEventStreamTransformer as As,createHfValueFunc as Cs,createLRUCache as Ds,createYamlObjectTag as Js,dateToText as Ks,decodeCharset as Ms,defaultTemplateFormat as Qs,detectCharset as Rs,encodeLLMTokens as Us,ensureQuoted as Ys,event as Zs,eventClient as $s,eventServer as _s,eventable as sa,expandConfig as aa,expandEnv as ua,expandObjEnv as ia,expandPath as ea,extNameLevel as ra,fileIsExists as ta,filenameReservedRegex as na,filterValidFnScope as da,findIndexNonEmptyFrom as ma,formatISO as oa,formatTextWithSpace as fa,getAllEnumKeys as pa,getConfigFileNames as va,getConfigs as ha,getEnvVairables as Fa,getFileMetaInfo as Ha,getHashAlgoBySize as ka,getKeysPath as la,getLLMTokenizer as Ia,getMultiLevelExtname as Pa,getPackageDir as Va,getRealFilepath as ca,getResponseErrorReadableStream as ja,getXDGConfigs as Ba,hasDirectoryIn as Ea,hash as Ga,hashFile as La,hashStream as Na,initShutdown as Sa,interpolateEnv as Ta,interpolateFString as Xa,interpolateGolangTemplate as ga,isLangUsingSpaces as xa,isListItemString as ya,isModelNameMatched as za,isPunctuationChar as Oa,isQuoted as Wa,isRegExp as ba,isSameString as qa,isSectionString as wa,isSentenceEnding as Aa,isSepLineString as Ca,isStrWrapped as Da,isSubdirectory as Ja,isTitleString as Ka,isValidFilename as Ma,isValidFilepath as Qa,isWebStream as Ra,jsonFilterToWhere as Ua,jsonToMarkdownStr as Ya,loadAIConfig as Za,loadConfig as $a,loadConfigFile as _a,loadFileFromPaths as su,loadTextFromPaths as au,lrucache as uu,makeToolFuncCancelable as iu,matchUrlProtocol as eu,memoize as ru,messagesToText as tu,mimeType as nu,paramsSizeToScaleStr as du,parse as mu,parse2 as ou,parseCommand as fu,parseDateFormat as pu,parseFString as vu,parseISO as hu,parseJsJson as Fu,parseJsJsonSimpleSync as Hu,parseObjectArgInfo as ku,parseObjectArgumentInfos as lu,parseObjectArguments as Iu,parseObjectArgumentsAsArgInfos as Pu,parseYaml as Vu,quoteStr as cu,reControlCharsRegex as ju,readFilenamesRecursiveSync as Bu,readTextFileChunks as Eu,readTextFileChunksEx as Gu,readableFromAsyncIterable as Lu,registerCoreTools as Nu,registerYamlTag as Su,removeMarkdownBold as Tu,removeMarkdownBoldAndItalic as Xu,removeMarkdownItalic as gu,replaceWithPlaceholder as xu,restoreFromPlacehoders as yu,sanitizeFilename as zu,sanitizeFilepath as Ou,saveConfigFile as Wu,scaleStrToParamsSize as bu,shutdown as qu,simplifyObjectArguments as wu,sortedValues as Au,splitChunks as Cu,splitParagraph as Du,splitSentence as Ju,states as Ku,stringify as Mu,stringifyYaml as Qu,stripConsoleColor as Ru,textToDate as Uu,throwError as Yu,toDate as Zu,toDateTime as $u,toRegExp as _u,tokenize as si,trimStartOfStreamHelper as ai,truncTo as ui,truncateByToken as ii,truncateToTokenLimit as ei,truncateToTokenLimitEx as ri,uuid as ti,v1 as ni,v4 as di,v5 as mi,validate as oi,version as fi,wait as pi,wrapEventEmitter as vi,xxhash as hi,xxhash32 as Fi,xxhash64 as Hi,xxhashAsStr as ki}from"./chunk-XLXW6OPN.mjs";import{findPort as li}from"./chunk-VIG2GB47.mjs";export{s as AIArgProcessor,a as AIChatRoles,u as AIMessageTypes,i as AIStream,e as AITextGenerationFinishReasons,r as AbortError,t as AbortErrorCode,n as ActionNames,d as AlreadyExistsError,m as AlreadyExistsErrorCode,o as AsyncFeatureBits,f as AsyncFeatures,p as BaseError,v as BinarySemaphore,h as CancelableAbility,F as ChoiceArgProcessor,H as ClientToolFuncSchema,k as ClientTools,l as CommonError,I as ConfigFile,P as DEFAULT_CONFIG_NAME,V as DefaultAsyncSemaphoreCapacity,c as EnvPromptTemplate,B as ErrorCode,E as EventBusName,G as EventClient,L as EventEmitter,N as EventName,S as EventServer,Ku as EventStates,T as EventToolFunc,X as FStringPromptTemplate,g as FewShotPromptTemplate,x as FilenameReservedRegex,y as GolangPromptTemplate,Ts as HFBuiltins,j as HFEnvironment,q as HFInterpreter,Hs as HFTemplate,z as HashAlgorithm,O as HfPromptTemplate,W as IntSet,b as InternalErrorCode,w as LLM_TOKENIZER_NAMES,A as LLM_TOKENIZER_NAMES_MAP,C as LRUCache,J as NotFoundError,K as NotFoundErrorCode,M as NotImplementationError,Q as NotImplementedErrorCode,R as ObjectArgsToArgsInfo,U as PASSING_SCORE,Y as PromptExampleSelector,Z as PromptTemplate,$ as PromptTemplateTypes,_ as PromptTypes,ss as RStreamErrCode,as as RateLimit,us as ReadableStreamError,is as RemoteToolFuncSchema,es as ResClientTools,rs as ResServerTools,ts as ResponseRStreamErrCode,ns as SHUTDOWN_SIGNALS,ds as SSEChannel,ms as SSEChannelAlreadyClosedErrCode,os as SecondaryCache,fs as Semaphore,ps as ServerToolFuncSchema,vs as ServerTools,hs as SignalGate,Fs as TaskAbortController,ks as TemplateArgProcessor,ls as ToolAsyncCancelableBit,Is as ToolAsyncMultiTaskBit,Ps as ToolAsyncPriorityBit,Vs as ToolFunc,cs as ToolFuncSchema,js as WindowsReservedNameRegex,Bs as YamlTypeBaseObject,Es as _lrucache,Gs as assignDirs,Ls as backendEventable,Ns as base32768,Ss as beforeShutdown,Xs as canonicalize,gs as completeSentences,xs as concatText,ys as countLLMTokens,zs as countRegexMatches,Os as createAbilityInjector,Ws as createCallbacksTransformer,bs as createEmptyReadableStream,qs as createEndWithRepetitionDetector,ws as createError,As as createEventStreamTransformer,Cs as createHfValueFunc,Ds as createLRUCache,Js as createYamlObjectTag,Ks as dateToText,Ms as decodeCharset,Qs as defaultTemplateFormat,Rs as detectCharset,Us as encodeLLMTokens,Ys as ensureQuoted,Zs as event,$s as eventClient,_s as eventServer,sa as eventable,aa as expandConfig,ua as expandEnv,ia as expandObjEnv,ea as expandPath,ra as extNameLevel,ta as fileIsExists,na as filenameReservedRegex,da as filterValidFnScope,ma as findIndexNonEmptyFrom,li as findPort,oa as formatISO,fa as formatTextWithSpace,pa as getAllEnumKeys,va as getConfigFileNames,ha as getConfigs,Fa as getEnvVairables,Ha as getFileMetaInfo,ka as getHashAlgoBySize,la as getKeysPath,Ia as getLLMTokenizer,Pa as getMultiLevelExtname,Va as getPackageDir,ca as getRealFilepath,ja as getResponseErrorReadableStream,Ba as getXDGConfigs,Ea as hasDirectoryIn,Ga as hash,La as hashFile,Na as hashStream,mu as hfParse,si as hfTokenize,Sa as initShutdown,Ta as interpolateEnv,Xa as interpolateFString,ga as interpolateGolangTemplate,xa as isLangUsingSpaces,ya as isListItemString,za as isModelNameMatched,Oa as isPunctuationChar,Wa as isQuoted,ba as isRegExp,qa as isSameString,wa as isSectionString,Aa as isSentenceEnding,Ca as isSepLineString,Da as isStrWrapped,Ja as isSubdirectory,Ka as isTitleString,Ma as isValidFilename,Qa as isValidFilepath,Ra as isWebStream,Ua as jsonFilterToWhere,Ya as jsonToMarkdownStr,Za as loadAIConfig,$a as loadConfig,_a as loadConfigFile,su as loadFileFromPaths,au as loadTextFromPaths,uu as lrucache,iu as makeToolFuncCancelable,eu as matchUrlProtocol,ru as memoize,tu as messagesToText,nu as mimeType,du as paramsSizeToScaleStr,fu as parseCommand,pu as parseDateFormat,vu as parseFString,hu as parseISO,Fu as parseJsJson,Hu as parseJsJsonSimpleSync,ku as parseObjectArgInfo,lu as parseObjectArgumentInfos,Iu as parseObjectArguments,Pu as parseObjectArgumentsAsArgInfos,Vu as parseYaml,cu as quoteStr,ju as reControlCharsRegex,Bu as readFilenamesRecursiveSync,Eu as readTextFileChunks,Gu as readTextFileChunksEx,Lu as readableFromAsyncIterable,Nu as registerCoreTools,Su as registerYamlTag,Tu as removeMarkdownBold,Xu as removeMarkdownBoldAndItalic,gu as removeMarkdownItalic,xu as replaceWithPlaceholder,yu as restoreFromPlacehoders,zu as sanitizeFilename,Ou as sanitizeFilepath,Wu as saveConfigFile,bu as scaleStrToParamsSize,qu as shutdown,wu as simplifyObjectArguments,Au as sortedValues,Cu as splitChunks,Du as splitParagraph,Ju as splitSentence,Qu as stringifyYaml,Ru as stripConsoleColor,Uu as textToDate,Yu as throwError,Zu as toDate,$u as toDateTime,_u as toRegExp,ai as trimStartOfStreamHelper,ui as truncTo,ii as truncateByToken,ei as truncateToTokenLimit,ri as truncateToTokenLimitEx,ti as uuid,D as uuidNIL,ou as uuidParse,Mu as uuidStringify,oi as uuidValidate,fi as uuidVersion,ni as uuidv1,di as uuidv4,mi as uuidv5,pi as wait,vi as wrapEventEmitter,hi as xxhash,Fi as xxhash32,Hi as xxhash64,ki as xxhashAsStr};
1
+ import{AIArgProcessor as a,AIChatRoles as s,AIMessageTypes as u,AIStream as t,AITextGenerationFinishReasons as i,AbortError as e,AbortErrorCode as m,ActionNames as r,AlreadyExistsError as o,AlreadyExistsErrorCode as p,AsyncFeatureBits as d,AsyncFeatures as n,BaseError as l,BinarySemaphore as v,CancelableAbility as P,ChoiceArgProcessor as T,ClientToolFuncSchema as f,ClientTools as g,CommonError as G,ConfigFile as S,DEFAULT_CONFIG_NAME as V,DefaultAsyncSemaphoreCapacity as c,EnvStringTemplate as h,ErrorCode as j,EventBusName as k,EventClient as B,EventEmitter as E,EventName as I,EventServer as x,EventToolFunc as y,FStringTemplate as D,FewShotPromptTemplate as F,FilenameReservedRegex as J,GolangStringTemplate as L,HashAlgorithm as N,IntSet as O,InternalErrorCode as R,LLM_TOKENIZER_NAMES as U,LLM_TOKENIZER_NAMES_MAP as Y,LRUCache as Z,NIL as b,NotFoundError as q,NotFoundErrorCode as w,NotImplementationError as z,NotImplementedErrorCode as A,ObjectArgsToArgsInfo as C,PASSING_SCORE as H,PromptExampleSelector as K,RStreamErrCode as M,RateLimit as Q,ReadableStreamError as W,RemoteToolFuncSchema as X,ResClientTools as $,ResServerTools as _,ResponseRStreamErrCode as aa,SHUTDOWN_SIGNALS as sa,SSEChannel as ua,SSEChannelAlreadyClosedErrCode as ta,SecondaryCache as ia,Semaphore as ea,ServerToolFuncSchema as ma,ServerTools as ra,SignalGate as oa,StringTemplate as pa,TaskAbortController as da,TemplateArgProcessor as na,ToolAsyncCancelableBit as la,ToolAsyncMultiTaskBit as va,ToolAsyncPriorityBit as Pa,ToolFunc as Ta,ToolFuncSchema as fa,WindowsReservedNameRegex as ga,YamlTypeBaseObject as Ga,_lrucache as Sa,assignDirs as Va,backendEventable as ca,base32768 as ha,beforeShutdown as ja,canonicalize as ka,completeSentences as Ba,concatText as Ea,countLLMTokens as Ia,countRegexMatches as xa,createAbilityInjector as ya,createCallbacksTransformer as Da,createEmptyReadableStream as Fa,createEndWithRepetitionDetector as Ja,createError as La,createEventStreamTransformer as Na,createHfValueFunc as Oa,createLRUCache as Ra,createYamlObjectTag as Ua,dateToText as Ya,decodeCharset as Za,defaultTemplateFormat as ba,detectCharset as qa,encodeLLMTokens as wa,ensureQuoted as za,event as Aa,eventClient as Ca,eventServer as Ha,eventable as Ka,expandConfig as Ma,expandEnv as Qa,expandObjEnv as Wa,expandPath as Xa,extNameLevel as $a,fileIsExists as _a,filterValidFnScope as as,findIndexNonEmptyFrom as ss,formatISO as us,formatTextWithSpace as ts,getAllEnumKeys as is,getConfigFileNames as es,getConfigs as ms,getEnvVairables as rs,getFileMetaInfo as os,getHashAlgoBySize as ps,getKeysPath as ds,getLLMTokenizer as ns,getMultiLevelExtname as ls,getPackageDir as vs,getRealFilepath as Ps,getResponseErrorReadableStream as Ts,getXDGConfigs as fs,hasDirectoryIn as gs,hash as Gs,hashFile as Ss,hashStream as Vs,initShutdown as cs,isLangUsingSpaces as hs,isListItemString as js,isModelNameMatched as ks,isPunctuationChar as Bs,isQuoted as Es,isRegExp as Is,isSameString as xs,isSectionString as ys,isSentenceEnding as Ds,isSepLineString as Fs,isStrWrapped as Js,isSubdirectory as Ls,isTitleString as Ns,isValidFilename as Os,isValidFilepath as Rs,isWebStream as Us,jsonFilterToWhere as Ys,jsonToMarkdownStr as Zs,loadAIConfig as bs,loadConfig as qs,loadConfigFile as ws,loadFileFromPaths as zs,loadTextFromPaths as As,lrucache as Cs,makeToolFuncCancelable as Hs,matchUrlProtocol as Ks,memoize as Ms,messagesToText as Qs,mimeType as Ws,paramsSizeToScaleStr as Xs,parse as $s,parseCommand as _s,parseDateFormat as au,parseISO as su,parseJsJson as uu,parseJsJsonSimpleSync as tu,parseObjectArgInfo as iu,parseObjectArgumentInfos as eu,parseObjectArguments as mu,parseObjectArgumentsAsArgInfos as ru,parseYaml as ou,quoteStr as pu,readFilenamesRecursiveSync as du,readTextFileChunks as nu,readTextFileChunksEx as lu,readableFromAsyncIterable as vu,registerCoreTools as Pu,registerYamlTag as Tu,removeMarkdownBold as fu,removeMarkdownBoldAndItalic as gu,removeMarkdownItalic as Gu,replaceWithPlaceholder as Su,restoreFromPlacehoders as Vu,sanitizeFilename as cu,sanitizeFilepath as hu,saveConfigFile as ju,scaleStrToParamsSize as ku,shutdown as Bu,simplifyObjectArguments as Eu,sortedValues as Iu,splitChunks as xu,splitParagraph as yu,splitSentence as Du,states as Fu,stringify as Ju,stringifyYaml as Lu,stripConsoleColor as Nu,textToDate as Ou,throwError as Ru,toDate as Uu,toDateTime as Yu,toRegExp as Zu,trimStartOfStreamHelper as bu,truncTo as qu,truncateByToken as wu,truncateToTokenLimit as zu,truncateToTokenLimitEx as Au,uuid as Cu,v1 as Hu,v4 as Ku,v5 as Mu,validate as Qu,version as Wu,wait as Xu,wrapEventEmitter as $u,xxhash as _u,xxhash32 as at,xxhash64 as st,xxhashAsStr as ut}from"./chunk-OYDBRUZJ.mjs";import{findPort as tt}from"./chunk-VIG2GB47.mjs";export{a as AIArgProcessor,s as AIChatRoles,u as AIMessageTypes,t as AIStream,i as AITextGenerationFinishReasons,e as AbortError,m as AbortErrorCode,r as ActionNames,o as AlreadyExistsError,p as AlreadyExistsErrorCode,d as AsyncFeatureBits,n as AsyncFeatures,l as BaseError,v as BinarySemaphore,P as CancelableAbility,T as ChoiceArgProcessor,f as ClientToolFuncSchema,g as ClientTools,G as CommonError,S as ConfigFile,V as DEFAULT_CONFIG_NAME,c as DefaultAsyncSemaphoreCapacity,h as EnvPromptTemplate,j as ErrorCode,k as EventBusName,B as EventClient,E as EventEmitter,I as EventName,x as EventServer,Fu as EventStates,y as EventToolFunc,D as FStringPromptTemplate,F as FewShotPromptTemplate,J as FilenameReservedRegex,L as GolangPromptTemplate,N as HashAlgorithm,O as IntSet,R as InternalErrorCode,U as LLM_TOKENIZER_NAMES,Y as LLM_TOKENIZER_NAMES_MAP,Z as LRUCache,q as NotFoundError,w as NotFoundErrorCode,z as NotImplementationError,A as NotImplementedErrorCode,C as ObjectArgsToArgsInfo,H as PASSING_SCORE,K as PromptExampleSelector,pa as PromptTemplate,M as RStreamErrCode,Q as RateLimit,W as ReadableStreamError,X as RemoteToolFuncSchema,$ as ResClientTools,_ as ResServerTools,aa as ResponseRStreamErrCode,sa as SHUTDOWN_SIGNALS,ua as SSEChannel,ta as SSEChannelAlreadyClosedErrCode,ia as SecondaryCache,ea as Semaphore,ma as ServerToolFuncSchema,ra as ServerTools,oa as SignalGate,da as TaskAbortController,na as TemplateArgProcessor,la as ToolAsyncCancelableBit,va as ToolAsyncMultiTaskBit,Pa as ToolAsyncPriorityBit,Ta as ToolFunc,fa as ToolFuncSchema,ga as WindowsReservedNameRegex,Ga as YamlTypeBaseObject,Sa as _lrucache,Va as assignDirs,ca as backendEventable,ha as base32768,ja as beforeShutdown,ka as canonicalize,Ba as completeSentences,Ea as concatText,Ia as countLLMTokens,xa as countRegexMatches,ya as createAbilityInjector,Da as createCallbacksTransformer,Fa as createEmptyReadableStream,Ja as createEndWithRepetitionDetector,La as createError,Na as createEventStreamTransformer,Oa as createHfValueFunc,Ra as createLRUCache,Ua as createYamlObjectTag,Ya as dateToText,Za as decodeCharset,ba as defaultTemplateFormat,qa as detectCharset,wa as encodeLLMTokens,za as ensureQuoted,Aa as event,Ca as eventClient,Ha as eventServer,Ka as eventable,Ma as expandConfig,Qa as expandEnv,Wa as expandObjEnv,Xa as expandPath,$a as extNameLevel,_a as fileIsExists,as as filterValidFnScope,ss as findIndexNonEmptyFrom,tt as findPort,us as formatISO,ts as formatTextWithSpace,is as getAllEnumKeys,es as getConfigFileNames,ms as getConfigs,rs as getEnvVairables,os as getFileMetaInfo,ps as getHashAlgoBySize,ds as getKeysPath,ns as getLLMTokenizer,ls as getMultiLevelExtname,vs as getPackageDir,Ps as getRealFilepath,Ts as getResponseErrorReadableStream,fs as getXDGConfigs,gs as hasDirectoryIn,Gs as hash,Ss as hashFile,Vs as hashStream,cs as initShutdown,hs as isLangUsingSpaces,js as isListItemString,ks as isModelNameMatched,Bs as isPunctuationChar,Es as isQuoted,Is as isRegExp,xs as isSameString,ys as isSectionString,Ds as isSentenceEnding,Fs as isSepLineString,Js as isStrWrapped,Ls as isSubdirectory,Ns as isTitleString,Os as isValidFilename,Rs as isValidFilepath,Us as isWebStream,Ys as jsonFilterToWhere,Zs as jsonToMarkdownStr,bs as loadAIConfig,qs as loadConfig,ws as loadConfigFile,zs as loadFileFromPaths,As as loadTextFromPaths,Cs as lrucache,Hs as makeToolFuncCancelable,Ks as matchUrlProtocol,Ms as memoize,Qs as messagesToText,Ws as mimeType,Xs as paramsSizeToScaleStr,_s as parseCommand,au as parseDateFormat,su as parseISO,uu as parseJsJson,tu as parseJsJsonSimpleSync,iu as parseObjectArgInfo,eu as parseObjectArgumentInfos,mu as parseObjectArguments,ru as parseObjectArgumentsAsArgInfos,ou as parseYaml,pu as quoteStr,du as readFilenamesRecursiveSync,nu as readTextFileChunks,lu as readTextFileChunksEx,vu as readableFromAsyncIterable,Pu as registerCoreTools,Tu as registerYamlTag,fu as removeMarkdownBold,gu as removeMarkdownBoldAndItalic,Gu as removeMarkdownItalic,Su as replaceWithPlaceholder,Vu as restoreFromPlacehoders,cu as sanitizeFilename,hu as sanitizeFilepath,ju as saveConfigFile,ku as scaleStrToParamsSize,Bu as shutdown,Eu as simplifyObjectArguments,Iu as sortedValues,xu as splitChunks,yu as splitParagraph,Du as splitSentence,Lu as stringifyYaml,Nu as stripConsoleColor,Ou as textToDate,Ru as throwError,Uu as toDate,Yu as toDateTime,Zu as toRegExp,bu as trimStartOfStreamHelper,qu as truncTo,wu as truncateByToken,zu as truncateToTokenLimit,Au as truncateToTokenLimitEx,Cu as uuid,b as uuidNIL,$s as uuidParse,Ju as uuidStringify,Qu as uuidValidate,Wu as uuidVersion,Hu as uuidv1,Ku as uuidv4,Mu as uuidv5,Xu as wait,$u as wrapEventEmitter,_u as xxhash,at as xxhash32,st as xxhash64,ut as xxhashAsStr};