@isdk/ai-tool 0.6.0 → 0.7.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 (467) hide show
  1. package/README.cn.md +103 -237
  2. package/README.md +101 -186
  3. package/dist/chunk-LNTIQQNN.mjs +1 -0
  4. package/dist/chunk-VIG2GB47.mjs +1 -1
  5. package/dist/funcs.d.mts +1 -1
  6. package/dist/funcs.d.ts +1 -1
  7. package/dist/funcs.js +1 -1
  8. package/dist/funcs.mjs +1 -1
  9. package/dist/index-BCco-g_I.d.mts +1781 -0
  10. package/dist/index-BCco-g_I.d.ts +1781 -0
  11. package/dist/index.d.mts +1068 -9
  12. package/dist/index.d.ts +1068 -9
  13. package/dist/index.js +1 -1
  14. package/dist/index.mjs +1 -1
  15. package/dist/test/util.js +1 -1
  16. package/docs/api/README.md +165 -0
  17. package/docs/{_media → api/_media}/CONTRIBUTING.md +3 -3
  18. package/docs/api/_media/pubsub.md +326 -0
  19. package/docs/api/_media/server_client_tools.md +88 -0
  20. package/docs/api/_media/toolFunc.md +183 -0
  21. package/docs/api/_media/transport.md +137 -0
  22. package/docs/{classes → api/classes}/AbortError.md +139 -54
  23. package/docs/api/classes/AlreadyExistsError.md +431 -0
  24. package/docs/api/classes/BaseError.md +440 -0
  25. package/docs/{classes → api/classes}/BinarySemaphore.md +25 -25
  26. package/docs/{classes → api/classes}/CancelableAbility.md +25 -25
  27. package/docs/api/classes/ClientToolTransport.md +310 -0
  28. package/docs/{classes → api/classes}/ClientTools.md +642 -180
  29. package/docs/{classes → api/classes}/CommonError.md +139 -54
  30. package/docs/{classes → api/classes}/ConfigFile.md +54 -5
  31. package/docs/{classes → api/classes}/EnvPromptTemplate.md +94 -48
  32. package/docs/{classes → api/classes}/EventClient.md +725 -232
  33. package/docs/{classes → api/classes}/EventEmitter.md +12 -12
  34. package/docs/{classes → api/classes}/EventServer.md +658 -205
  35. package/docs/{classes → api/classes}/EventToolFunc.md +561 -109
  36. package/docs/{classes → api/classes}/FStringPromptTemplate.md +94 -48
  37. package/docs/{classes → api/classes}/FewShotPromptTemplate.md +100 -52
  38. package/docs/{classes → api/classes}/GolangPromptTemplate.md +99 -53
  39. package/docs/api/classes/HttpClientToolTransport.md +324 -0
  40. package/docs/api/classes/HttpServerToolTransport.md +324 -0
  41. package/docs/{classes → api/classes}/IntSet.md +12 -12
  42. package/docs/{classes → api/classes}/LRUCache.md +26 -26
  43. package/docs/api/classes/NotFoundError.md +431 -0
  44. package/docs/api/classes/NotImplementationError.md +431 -0
  45. package/docs/{classes → api/classes}/PromptExampleSelector.md +9 -9
  46. package/docs/{classes → api/classes}/PromptTemplate.md +91 -47
  47. package/docs/api/classes/ReadableStreamError.md +451 -0
  48. package/docs/api/classes/ResClientTools.md +2878 -0
  49. package/docs/api/classes/ResServerTools.md +2856 -0
  50. package/docs/api/classes/SSEChannel.md +272 -0
  51. package/docs/{classes → api/classes}/Semaphore.md +26 -26
  52. package/docs/api/classes/ServerToolTransport.md +323 -0
  53. package/docs/{classes → api/classes}/ServerTools.md +579 -120
  54. package/docs/{classes → api/classes}/SignalGate.md +9 -9
  55. package/docs/api/classes/SseClientPubSubTransport.md +92 -0
  56. package/docs/api/classes/SseServerPubSubTransport.md +234 -0
  57. package/docs/{classes → api/classes}/TaskAbortController.md +9 -9
  58. package/docs/api/classes/ToolFunc.md +2665 -0
  59. package/docs/api/classes/ToolTransport.md +143 -0
  60. package/docs/api/classes/YamlTypeBaseObject.md +31 -0
  61. package/docs/api/enumerations/AsyncFeatureBits.md +33 -0
  62. package/docs/api/enumerations/AsyncFeatures.md +33 -0
  63. package/docs/api/enumerations/ErrorCode.md +177 -0
  64. package/docs/api/enumerations/HashAlgorithm.md +97 -0
  65. package/docs/{functions → api/functions}/AIArgProcessor.md +1 -1
  66. package/docs/{functions → api/functions}/AIStream.md +1 -1
  67. package/docs/{functions → api/functions}/ChoiceArgProcessor.md +1 -1
  68. package/docs/api/functions/DefaultDateFormat.md +21 -0
  69. package/docs/{functions → api/functions}/ObjectArgsToArgsInfo.md +1 -1
  70. package/docs/{functions → api/functions}/RateLimit.md +1 -1
  71. package/docs/{functions → api/functions}/TemplateArgProcessor.md +1 -1
  72. package/docs/api/functions/addDate.md +71 -0
  73. package/docs/{functions → api/functions}/assignDirs.md +1 -1
  74. package/docs/{functions → api/functions}/backendEventable.md +1 -1
  75. package/docs/{functions → api/functions}/beforeShutdown.md +1 -1
  76. package/docs/api/functions/calcPerplexity.md +60 -0
  77. package/docs/api/functions/calcPerplexitySimple.md +42 -0
  78. package/docs/api/functions/canonicalize.md +33 -0
  79. package/docs/{functions → api/functions}/completeSentences.md +1 -1
  80. package/docs/{functions → api/functions}/concatText.md +1 -1
  81. package/docs/{functions → api/functions}/countLLMTokens.md +1 -1
  82. package/docs/{functions → api/functions}/countRegexMatches.md +1 -1
  83. package/docs/{functions → api/functions}/createAbilityInjector.md +4 -4
  84. package/docs/{functions → api/functions}/createCallbacksTransformer.md +1 -1
  85. package/docs/{functions → api/functions}/createEmptyReadableStream.md +1 -1
  86. package/docs/{functions → api/functions}/createEndWithRepetitionDetector.md +1 -1
  87. package/docs/{functions → api/functions}/createError.md +1 -1
  88. package/docs/{functions → api/functions}/createEventStreamTransformer.md +1 -1
  89. package/docs/{functions → api/functions}/createHfValueFunc.md +1 -1
  90. package/docs/{functions → api/functions}/createLRUCache.md +1 -1
  91. package/docs/{functions → api/functions}/createYamlObjectTag.md +1 -1
  92. package/docs/{functions → api/functions}/dateToText.md +1 -1
  93. package/docs/{functions → api/functions}/decodeCharset.md +1 -1
  94. package/docs/api/functions/defaultsWithConcat.md +74 -0
  95. package/docs/{functions → api/functions}/detectCharset.md +1 -1
  96. package/docs/{functions → api/functions}/encodeLLMTokens.md +1 -1
  97. package/docs/{functions → api/functions}/ensureQuoted.md +1 -1
  98. package/docs/{functions → api/functions}/eventable.md +1 -1
  99. package/docs/{functions → api/functions}/expandConfig.md +1 -1
  100. package/docs/{functions → api/functions}/expandEnv.md +1 -1
  101. package/docs/{functions → api/functions}/expandObjEnv.md +1 -1
  102. package/docs/{functions → api/functions}/expandPath.md +1 -1
  103. package/docs/api/functions/expandPathInObject.md +29 -0
  104. package/docs/api/functions/expandPaths.md +25 -0
  105. package/docs/{functions → api/functions}/extNameLevel.md +1 -1
  106. package/docs/{functions → api/functions}/fileIsExists.md +1 -1
  107. package/docs/{functions → api/functions}/filterValidFnScope.md +1 -1
  108. package/docs/{functions → api/functions}/findIndexNonEmptyFrom.md +1 -1
  109. package/docs/{functions → api/functions}/findPort.md +1 -1
  110. package/docs/{functions → api/functions}/formatISO.md +1 -1
  111. package/docs/{functions → api/functions}/formatTextWithSpace.md +1 -1
  112. package/docs/api/functions/funcGetMeta.md +27 -0
  113. package/docs/api/functions/funcWithMeta.md +41 -0
  114. package/docs/api/functions/genUrlParamsStr.md +27 -0
  115. package/docs/{functions → api/functions}/getAllEnumKeys.md +1 -1
  116. package/docs/{functions → api/functions}/getConfigFileNames.md +1 -1
  117. package/docs/{functions → api/functions}/getConfigs.md +1 -1
  118. package/docs/{functions → api/functions}/getEnvVairables.md +1 -1
  119. package/docs/{functions → api/functions}/getFileMetaInfo.md +1 -1
  120. package/docs/{functions → api/functions}/getHashAlgoBySize.md +1 -1
  121. package/docs/{functions → api/functions}/getKeysPath.md +1 -1
  122. package/docs/{functions → api/functions}/getLLMTokenizer.md +1 -1
  123. package/docs/{functions → api/functions}/getMultiLevelExtname.md +1 -1
  124. package/docs/{functions → api/functions}/getPackageDir.md +1 -1
  125. package/docs/{functions → api/functions}/getRealFilepath.md +1 -1
  126. package/docs/{functions → api/functions}/getResponseErrorReadableStream.md +1 -1
  127. package/docs/{functions → api/functions}/getXDGConfigs.md +1 -1
  128. package/docs/{functions → api/functions}/hasDirectoryIn.md +1 -1
  129. package/docs/{functions → api/functions}/hash.md +1 -1
  130. package/docs/{functions → api/functions}/hashFile.md +1 -1
  131. package/docs/api/functions/hashObject.md +25 -0
  132. package/docs/{functions → api/functions}/hashStream.md +1 -1
  133. package/docs/api/functions/initShutdown.md +15 -0
  134. package/docs/{functions → api/functions}/isLangUsingSpaces.md +1 -1
  135. package/docs/{functions → api/functions}/isListItemString.md +1 -1
  136. package/docs/{functions → api/functions}/isModelNameMatched.md +1 -1
  137. package/docs/{functions → api/functions}/isPunctuationChar.md +1 -1
  138. package/docs/{functions → api/functions}/isQuoted.md +1 -1
  139. package/docs/{functions → api/functions}/isRegExp.md +1 -1
  140. package/docs/{functions → api/functions}/isSameString.md +1 -1
  141. package/docs/{functions → api/functions}/isSectionString.md +1 -1
  142. package/docs/{functions → api/functions}/isSentenceEnding.md +1 -1
  143. package/docs/{functions → api/functions}/isSepLineString.md +1 -1
  144. package/docs/{functions → api/functions}/isStrWrapped.md +1 -1
  145. package/docs/{functions → api/functions}/isSubdirectory.md +2 -2
  146. package/docs/{functions → api/functions}/isTitleString.md +1 -1
  147. package/docs/{functions → api/functions}/isValidFilename.md +1 -1
  148. package/docs/{functions → api/functions}/isValidFilepath.md +1 -1
  149. package/docs/{functions → api/functions}/isWebStream.md +1 -1
  150. package/docs/api/functions/joinSplitWords.md +46 -0
  151. package/docs/{functions → api/functions}/jsonFilterToWhere.md +1 -1
  152. package/docs/{functions → api/functions}/jsonToMarkdownStr.md +9 -1
  153. package/docs/{functions → api/functions}/loadAIConfig.md +1 -1
  154. package/docs/{functions → api/functions}/loadConfig.md +1 -1
  155. package/docs/{functions → api/functions}/loadConfigFile.md +1 -1
  156. package/docs/{functions → api/functions}/loadFileFromPaths.md +1 -1
  157. package/docs/{functions → api/functions}/loadTextFromPaths.md +1 -1
  158. package/docs/{functions → api/functions}/lrucache.md +1 -1
  159. package/docs/{functions → api/functions}/makeToolFuncCancelable.md +1 -1
  160. package/docs/{functions → api/functions}/matchUrlProtocol.md +1 -1
  161. package/docs/{functions → api/functions}/memoize.md +1 -1
  162. package/docs/api/functions/mergeArray.md +57 -0
  163. package/docs/{functions → api/functions}/messagesToText.md +1 -1
  164. package/docs/api/functions/normalizePath.md +21 -0
  165. package/docs/{functions → api/functions}/paramsSizeToScaleStr.md +1 -1
  166. package/docs/{functions → api/functions}/parseCommand.md +1 -1
  167. package/docs/{functions → api/functions}/parseDateFormat.md +1 -1
  168. package/docs/{functions → api/functions}/parseISO.md +1 -1
  169. package/docs/{functions → api/functions}/parseJsJson.md +1 -1
  170. package/docs/{functions → api/functions}/parseJsJsonSimpleSync.md +1 -1
  171. package/docs/{functions → api/functions}/parseObjectArgInfo.md +1 -1
  172. package/docs/{functions → api/functions}/parseObjectArgumentInfos.md +1 -1
  173. package/docs/{functions → api/functions}/parseObjectArguments.md +1 -1
  174. package/docs/{functions → api/functions}/parseObjectArgumentsAsArgInfos.md +1 -1
  175. package/docs/{functions → api/functions}/parseYaml.md +1 -1
  176. package/docs/api/functions/pruneSubdirectories.md +35 -0
  177. package/docs/api/functions/pruneSubdirectoriesInPlace.md +38 -0
  178. package/docs/{functions → api/functions}/quoteStr.md +1 -1
  179. package/docs/{functions → api/functions}/readFilenamesRecursiveSync.md +1 -1
  180. package/docs/{functions → api/functions}/readTextFileChunks.md +1 -1
  181. package/docs/{functions → api/functions}/readTextFileChunksEx.md +1 -1
  182. package/docs/{functions → api/functions}/readableFromAsyncIterable.md +1 -1
  183. package/docs/{functions → api/functions}/registerCoreTools.md +1 -1
  184. package/docs/{functions → api/functions}/registerYamlTag.md +1 -1
  185. package/docs/{functions → api/functions}/removeMarkdownBold.md +1 -1
  186. package/docs/{functions → api/functions}/removeMarkdownBoldAndItalic.md +1 -1
  187. package/docs/{functions → api/functions}/removeMarkdownItalic.md +1 -1
  188. package/docs/{functions → api/functions}/replaceWithPlaceholder.md +1 -1
  189. package/docs/{functions → api/functions}/restoreFromPlacehoders.md +1 -1
  190. package/docs/{functions → api/functions}/sanitizeFilename.md +1 -1
  191. package/docs/{functions → api/functions}/sanitizeFilepath.md +1 -1
  192. package/docs/{functions → api/functions}/saveConfigFile.md +1 -1
  193. package/docs/{functions → api/functions}/scaleStrToParamsSize.md +1 -1
  194. package/docs/{functions → api/functions}/shutdown.md +1 -1
  195. package/docs/{functions → api/functions}/simplifyObjectArguments.md +1 -1
  196. package/docs/api/functions/sleep.md +36 -0
  197. package/docs/{functions → api/functions}/sortedValues.md +1 -1
  198. package/docs/{functions → api/functions}/splitChunks.md +1 -1
  199. package/docs/{functions → api/functions}/splitParagraph.md +1 -1
  200. package/docs/{functions → api/functions}/splitSentence.md +1 -1
  201. package/docs/api/functions/splitWords.md +42 -0
  202. package/docs/{functions → api/functions}/stringifyYaml.md +1 -1
  203. package/docs/{functions → api/functions}/stripConsoleColor.md +1 -1
  204. package/docs/{functions → api/functions}/textToDate.md +1 -1
  205. package/docs/{functions → api/functions}/throwError.md +3 -3
  206. package/docs/{functions → api/functions}/toDate.md +1 -1
  207. package/docs/{functions → api/functions}/toDateTime.md +1 -1
  208. package/docs/{functions → api/functions}/toRegExp.md +1 -1
  209. package/docs/{functions → api/functions}/trimStartOfStreamHelper.md +1 -1
  210. package/docs/{functions → api/functions}/truncTo.md +1 -1
  211. package/docs/{functions → api/functions}/truncateByToken.md +1 -1
  212. package/docs/{functions → api/functions}/truncateToTokenLimit.md +1 -1
  213. package/docs/{functions → api/functions}/truncateToTokenLimitEx.md +1 -1
  214. package/docs/{functions → api/functions}/uuid.md +1 -1
  215. package/docs/{functions → api/functions}/uuidParse.md +1 -1
  216. package/docs/{functions → api/functions}/uuidStringify.md +1 -1
  217. package/docs/{functions → api/functions}/uuidValidate.md +1 -1
  218. package/docs/{functions → api/functions}/uuidVersion.md +1 -1
  219. package/docs/{functions → api/functions}/uuidv1.md +9 -5
  220. package/docs/{functions → api/functions}/uuidv4.md +9 -5
  221. package/docs/{functions → api/functions}/uuidv5.md +9 -5
  222. package/docs/api/functions/wait.md +45 -0
  223. package/docs/{functions → api/functions}/wrapEventEmitter.md +1 -1
  224. package/docs/{functions → api/functions}/xxhash.md +1 -1
  225. package/docs/{functions → api/functions}/xxhash32.md +1 -1
  226. package/docs/{functions → api/functions}/xxhash64.md +1 -1
  227. package/docs/{functions → api/functions}/xxhashAsStr.md +1 -1
  228. package/docs/api/functions/yieldExec.md +27 -0
  229. package/docs/{globals.md → api/globals.md} +44 -1
  230. package/docs/api/interfaces/AIChatAssistantMessageParam.md +129 -0
  231. package/docs/api/interfaces/AIChatContentPartImage.md +29 -0
  232. package/docs/api/interfaces/AIChatContentPartText.md +25 -0
  233. package/docs/api/interfaces/AIChatMessageParamBase.md +68 -0
  234. package/docs/api/interfaces/AIChatMessageToolCall.md +41 -0
  235. package/docs/{interfaces → api/interfaces}/AIChatSystemMessageParam.md +9 -9
  236. package/docs/api/interfaces/AIChatToolChoiceFuncObject.md +37 -0
  237. package/docs/api/interfaces/AIChatToolChoiceObject.md +25 -0
  238. package/docs/api/interfaces/AIChatToolFunc.md +41 -0
  239. package/docs/api/interfaces/AIChatToolFuncParam.md +37 -0
  240. package/docs/api/interfaces/AIChatToolMessageParam.md +113 -0
  241. package/docs/api/interfaces/AIChatToolParam.md +25 -0
  242. package/docs/api/interfaces/AIChatToolTypeObject.md +17 -0
  243. package/docs/api/interfaces/AIChatUserMessageParam.md +137 -0
  244. package/docs/api/interfaces/AIChoiceConfig.md +65 -0
  245. package/docs/api/interfaces/AIResult.md +65 -0
  246. package/docs/{interfaces → api/interfaces}/AIStreamParser.md +2 -2
  247. package/docs/api/interfaces/AIStreamParserOptions.md +21 -0
  248. package/docs/api/interfaces/BaseFunc.md +299 -0
  249. package/docs/api/interfaces/BaseFuncItem.md +221 -0
  250. package/docs/api/interfaces/BinarySemaphoreAcquireOptions.md +25 -0
  251. package/docs/api/interfaces/BinarySemaphoreOptions.md +57 -0
  252. package/docs/api/interfaces/BinarySemaphoreReleaseOptions.md +25 -0
  253. package/docs/api/interfaces/BinarySemaphoreReleaserFunc.md +37 -0
  254. package/docs/api/interfaces/CancelableAbilityOptions.md +113 -0
  255. package/docs/api/interfaces/ClientFuncItem.md +326 -0
  256. package/docs/api/interfaces/EventClientFuncParams.md +51 -0
  257. package/docs/api/interfaces/EventServerFuncParams.md +73 -0
  258. package/docs/{interfaces → api/interfaces}/FewShotPromptTemplateOptions.md +24 -12
  259. package/docs/api/interfaces/FuncItem.md +281 -0
  260. package/docs/api/interfaces/FuncParam.md +51 -0
  261. package/docs/api/interfaces/FuncParams.md +28 -0
  262. package/docs/api/interfaces/Funcs.md +15 -0
  263. package/docs/api/interfaces/HashAlgoParams.md +33 -0
  264. package/docs/api/interfaces/IClientToolTransport.md +155 -0
  265. package/docs/api/interfaces/IFileMetaInfo.md +65 -0
  266. package/docs/api/interfaces/IPubSubClientTransport.md +70 -0
  267. package/docs/api/interfaces/IPubSubServerTransport.md +241 -0
  268. package/docs/api/interfaces/IReadTextFileChunksOptions.md +143 -0
  269. package/docs/api/interfaces/IServerToolTransport.md +159 -0
  270. package/docs/api/interfaces/IToolTransport.md +73 -0
  271. package/docs/api/interfaces/ITruncateToTokenLimitOptions.md +99 -0
  272. package/docs/api/interfaces/JsonFilter.md +13 -0
  273. package/docs/api/interfaces/ParseObjectArgumentOptions.md +89 -0
  274. package/docs/api/interfaces/ProbabilityItem.md +41 -0
  275. package/docs/api/interfaces/PromptExampleSelectorOptions.md +34 -0
  276. package/docs/{interfaces → api/interfaces}/PromptTemplateOptions.md +15 -7
  277. package/docs/api/interfaces/PubSubClient.md +27 -0
  278. package/docs/api/interfaces/PubSubClientStream.md +196 -0
  279. package/docs/api/interfaces/PubSubServerSession.md +103 -0
  280. package/docs/api/interfaces/RemoteFuncItem.md +316 -0
  281. package/docs/api/interfaces/ReplacePlacehoderOptions.md +41 -0
  282. package/docs/api/interfaces/ResClientFuncParams.md +37 -0
  283. package/docs/api/interfaces/ResServerFuncParams.md +73 -0
  284. package/docs/api/interfaces/SanitizeFilenameOptions.md +25 -0
  285. package/docs/api/interfaces/SectionStringOptions.md +25 -0
  286. package/docs/api/interfaces/SemaphoreOptions.md +89 -0
  287. package/docs/api/interfaces/SemaphoreTaskItem.md +73 -0
  288. package/docs/api/interfaces/ServerFuncItem.md +339 -0
  289. package/docs/api/interfaces/ServerFuncParams.md +41 -0
  290. package/docs/api/interfaces/SplitSentenceOptions.md +41 -0
  291. package/docs/{interfaces → api/interfaces}/StreamCallbacksAndOptions.md +5 -5
  292. package/docs/{interfaces → api/interfaces}/TaskAbortControllers.md +1 -1
  293. package/docs/{interfaces → api/interfaces}/TaskPromise.md +6 -6
  294. package/docs/api/interfaces/ToolFuncPackage.md +57 -0
  295. package/docs/{namespaces → api/namespaces}/EventStates/variables/ABORT.md +1 -1
  296. package/docs/{namespaces → api/namespaces}/EventStates/variables/CONTINUE.md +1 -1
  297. package/docs/{namespaces → api/namespaces}/EventStates/variables/DONE.md +1 -1
  298. package/docs/{namespaces → api/namespaces}/EventStates/variables/STOPPED.md +1 -1
  299. package/docs/{namespaces → api/namespaces}/uuidv5/variables/DNS.md +1 -1
  300. package/docs/{namespaces → api/namespaces}/uuidv5/variables/URL.md +1 -1
  301. package/docs/{type-aliases → api/type-aliases}/AIChatContentPart.md +1 -1
  302. package/docs/{type-aliases → api/type-aliases}/AIChatMessageParam.md +1 -1
  303. package/docs/{type-aliases → api/type-aliases}/AIChatRole.md +1 -1
  304. package/docs/{type-aliases → api/type-aliases}/AIChatToolChoiceParam.md +1 -1
  305. package/docs/{type-aliases → api/type-aliases}/AIMessageType.md +1 -1
  306. package/docs/api/type-aliases/AIModelNameRule.md +14 -0
  307. package/docs/api/type-aliases/AIModelNameRuleFn.md +28 -0
  308. package/docs/api/type-aliases/AIModelNameRules.md +13 -0
  309. package/docs/{type-aliases → api/type-aliases}/AITextGenerationFinishReason.md +1 -1
  310. package/docs/api/type-aliases/ActionName.md +13 -0
  311. package/docs/api/type-aliases/ArrayMergeWay.md +11 -0
  312. package/docs/api/type-aliases/AsyncTaskId.md +11 -0
  313. package/docs/{type-aliases → api/type-aliases}/BeforeShutdownListener.md +1 -1
  314. package/docs/{type-aliases → api/type-aliases}/EventErrorListenerFn.md +1 -1
  315. package/docs/{type-aliases → api/type-aliases}/EventListenerFn.md +1 -1
  316. package/docs/api/type-aliases/FuncParamType.md +13 -0
  317. package/docs/{type-aliases → api/type-aliases}/PromptExamples.md +1 -1
  318. package/docs/api/type-aliases/PubSubClientId.md +14 -0
  319. package/docs/api/type-aliases/PubSubCtx.md +37 -0
  320. package/docs/api/type-aliases/RpcMethodHandler.md +34 -0
  321. package/docs/{type-aliases → api/type-aliases}/SemaphoreIsReadyFuncType.md +1 -1
  322. package/docs/api/type-aliases/TFunc.md +33 -0
  323. package/docs/{variables → api/variables}/AIChatRoles.md +1 -1
  324. package/docs/{variables → api/variables}/AIMessageTypes.md +1 -1
  325. package/docs/{variables → api/variables}/AITextGenerationFinishReasons.md +1 -1
  326. package/docs/{variables → api/variables}/AbortErrorCode.md +1 -1
  327. package/docs/api/variables/ActionNames.md +13 -0
  328. package/docs/{variables → api/variables}/AlreadyExistsErrorCode.md +1 -1
  329. package/docs/api/variables/ArrayMergeWay.md +25 -0
  330. package/docs/api/variables/ArrayMergeWaySymbol.md +11 -0
  331. package/docs/api/variables/ClientToolFuncSchema.md +83 -0
  332. package/docs/{variables → api/variables}/DEFAULT_CONFIG_NAME.md +1 -1
  333. package/docs/{variables → api/variables}/DefaultAsyncSemaphoreCapacity.md +1 -1
  334. package/docs/api/variables/EventBusName.md +11 -0
  335. package/docs/api/variables/EventName.md +11 -0
  336. package/docs/{variables → api/variables}/FilenameReservedRegex.md +1 -1
  337. package/docs/api/variables/FuncMetaSymbol.md +15 -0
  338. package/docs/{variables → api/variables}/InternalErrorCode.md +1 -1
  339. package/docs/{variables → api/variables}/LLM_TOKENIZER_NAMES.md +1 -1
  340. package/docs/{variables → api/variables}/LLM_TOKENIZER_NAMES_MAP.md +1 -1
  341. package/docs/{variables → api/variables}/NotFoundErrorCode.md +1 -1
  342. package/docs/{variables → api/variables}/NotImplementedErrorCode.md +1 -1
  343. package/docs/api/variables/PASSING_SCORE.md +13 -0
  344. package/docs/api/variables/RStreamErrCode.md +11 -0
  345. package/docs/api/variables/RemoteToolFuncSchema.md +84 -0
  346. package/docs/api/variables/ResponseRStreamErrCode.md +11 -0
  347. package/docs/{variables → api/variables}/SHUTDOWN_SIGNALS.md +1 -1
  348. package/docs/{variables → api/variables}/SSEChannelAlreadyClosedErrCode.md +1 -1
  349. package/docs/api/variables/SecondaryCache.md +11 -0
  350. package/docs/api/variables/ServerToolFuncSchema.md +83 -0
  351. package/docs/api/variables/StrangeHumanName.md +11 -0
  352. package/docs/api/variables/ToolAsyncCancelableBit.md +11 -0
  353. package/docs/api/variables/ToolAsyncMultiTaskBit.md +11 -0
  354. package/docs/api/variables/ToolAsyncPriorityBit.md +11 -0
  355. package/docs/{variables → api/variables}/ToolFuncSchema.md +14 -1
  356. package/docs/{variables → api/variables}/WindowsReservedNameRegex.md +1 -1
  357. package/docs/api/variables/base32768.md +11 -0
  358. package/docs/{variables → api/variables}/defaultTemplateFormat.md +1 -1
  359. package/docs/api/variables/event.md +11 -0
  360. package/docs/api/variables/eventClient.md +11 -0
  361. package/docs/api/variables/eventServer.md +11 -0
  362. package/docs/api/variables/lrucache.md +11 -0
  363. package/docs/{variables → api/variables}/mimeType.md +1 -1
  364. package/docs/{variables → api/variables}/uuidNIL.md +1 -1
  365. package/docs/pubsub.md +326 -0
  366. package/docs/server_client_tools.md +88 -0
  367. package/docs/toolFunc.md +183 -0
  368. package/docs/transport.md +137 -0
  369. package/package.json +38 -40
  370. package/dist/chunk-OYDBRUZJ.mjs +0 -1
  371. package/dist/index-BkwhCK1q.d.mts +0 -899
  372. package/dist/index-BkwhCK1q.d.ts +0 -899
  373. package/docs/README.md +0 -250
  374. package/docs/classes/AlreadyExistsError.md +0 -346
  375. package/docs/classes/BaseError.md +0 -359
  376. package/docs/classes/NotFoundError.md +0 -346
  377. package/docs/classes/NotImplementationError.md +0 -346
  378. package/docs/classes/ReadableStreamError.md +0 -366
  379. package/docs/classes/ResClientTools.md +0 -2451
  380. package/docs/classes/ResServerTools.md +0 -2427
  381. package/docs/classes/SSEChannel.md +0 -270
  382. package/docs/classes/ToolFunc.md +0 -2201
  383. package/docs/classes/YamlTypeBaseObject.md +0 -31
  384. package/docs/enumerations/AsyncFeatureBits.md +0 -33
  385. package/docs/enumerations/AsyncFeatures.md +0 -33
  386. package/docs/enumerations/ErrorCode.md +0 -177
  387. package/docs/enumerations/HashAlgorithm.md +0 -97
  388. package/docs/functions/canonicalize.md +0 -21
  389. package/docs/functions/initShutdown.md +0 -15
  390. package/docs/functions/wait.md +0 -21
  391. package/docs/interfaces/AIChatAssistantMessageParam.md +0 -129
  392. package/docs/interfaces/AIChatContentPartImage.md +0 -29
  393. package/docs/interfaces/AIChatContentPartText.md +0 -25
  394. package/docs/interfaces/AIChatMessageParamBase.md +0 -68
  395. package/docs/interfaces/AIChatMessageToolCall.md +0 -41
  396. package/docs/interfaces/AIChatToolChoiceFuncObject.md +0 -37
  397. package/docs/interfaces/AIChatToolChoiceObject.md +0 -25
  398. package/docs/interfaces/AIChatToolFunc.md +0 -41
  399. package/docs/interfaces/AIChatToolFuncParam.md +0 -37
  400. package/docs/interfaces/AIChatToolMessageParam.md +0 -113
  401. package/docs/interfaces/AIChatToolParam.md +0 -25
  402. package/docs/interfaces/AIChatToolTypeObject.md +0 -17
  403. package/docs/interfaces/AIChatUserMessageParam.md +0 -137
  404. package/docs/interfaces/AIChoiceConfig.md +0 -65
  405. package/docs/interfaces/AIResult.md +0 -65
  406. package/docs/interfaces/AIStreamParserOptions.md +0 -21
  407. package/docs/interfaces/BaseFunc.md +0 -157
  408. package/docs/interfaces/BaseFuncItem.md +0 -101
  409. package/docs/interfaces/BinarySemaphoreAcquireOptions.md +0 -25
  410. package/docs/interfaces/BinarySemaphoreOptions.md +0 -57
  411. package/docs/interfaces/BinarySemaphoreReleaseOptions.md +0 -25
  412. package/docs/interfaces/BinarySemaphoreReleaserFunc.md +0 -37
  413. package/docs/interfaces/CancelableAbilityOptions.md +0 -113
  414. package/docs/interfaces/ClientFuncItem.md +0 -175
  415. package/docs/interfaces/EventClientFuncParams.md +0 -51
  416. package/docs/interfaces/EventServerFuncParams.md +0 -67
  417. package/docs/interfaces/FuncItem.md +0 -143
  418. package/docs/interfaces/FuncParam.md +0 -61
  419. package/docs/interfaces/FuncParams.md +0 -13
  420. package/docs/interfaces/Funcs.md +0 -13
  421. package/docs/interfaces/HashAlgoParams.md +0 -33
  422. package/docs/interfaces/IFileMetaInfo.md +0 -65
  423. package/docs/interfaces/IReadTextFileChunksOptions.md +0 -143
  424. package/docs/interfaces/ITruncateToTokenLimitOptions.md +0 -99
  425. package/docs/interfaces/JsonFilter.md +0 -13
  426. package/docs/interfaces/ParseObjectArgumentOptions.md +0 -89
  427. package/docs/interfaces/PromptExampleSelectorOptions.md +0 -34
  428. package/docs/interfaces/RemoteFuncItem.md +0 -164
  429. package/docs/interfaces/ReplacePlacehoderOptions.md +0 -41
  430. package/docs/interfaces/ResClientFuncParams.md +0 -37
  431. package/docs/interfaces/ResServerFuncParams.md +0 -69
  432. package/docs/interfaces/SanitizeFilenameOptions.md +0 -25
  433. package/docs/interfaces/SectionStringOptions.md +0 -25
  434. package/docs/interfaces/SemaphoreOptions.md +0 -89
  435. package/docs/interfaces/SemaphoreTaskItem.md +0 -73
  436. package/docs/interfaces/ServerFuncItem.md +0 -183
  437. package/docs/interfaces/ServerFuncParams.md +0 -35
  438. package/docs/interfaces/SplitSentenceOptions.md +0 -41
  439. package/docs/interfaces/ToolFuncPackage.md +0 -47
  440. package/docs/type-aliases/AIModelNameRule.md +0 -11
  441. package/docs/type-aliases/AIModelNameRuleFn.md +0 -21
  442. package/docs/type-aliases/AIModelNameRules.md +0 -11
  443. package/docs/type-aliases/ActionName.md +0 -11
  444. package/docs/type-aliases/AsyncTaskId.md +0 -11
  445. package/docs/type-aliases/FuncParamType.md +0 -11
  446. package/docs/type-aliases/TFunc.md +0 -25
  447. package/docs/variables/ActionNames.md +0 -11
  448. package/docs/variables/ClientToolFuncSchema.md +0 -101
  449. package/docs/variables/EventBusName.md +0 -11
  450. package/docs/variables/EventName.md +0 -11
  451. package/docs/variables/PASSING_SCORE.md +0 -11
  452. package/docs/variables/RStreamErrCode.md +0 -11
  453. package/docs/variables/RemoteToolFuncSchema.md +0 -101
  454. package/docs/variables/ResponseRStreamErrCode.md +0 -11
  455. package/docs/variables/SecondaryCache.md +0 -11
  456. package/docs/variables/ServerToolFuncSchema.md +0 -101
  457. package/docs/variables/ToolAsyncCancelableBit.md +0 -11
  458. package/docs/variables/ToolAsyncMultiTaskBit.md +0 -11
  459. package/docs/variables/ToolAsyncPriorityBit.md +0 -11
  460. package/docs/variables/base32768.md +0 -11
  461. package/docs/variables/event.md +0 -11
  462. package/docs/variables/eventClient.md +0 -11
  463. package/docs/variables/eventServer.md +0 -11
  464. package/docs/variables/lrucache.md +0 -11
  465. /package/docs/{_media → api/_media}/LICENSE-MIT +0 -0
  466. /package/docs/{namespaces → api/namespaces}/EventStates/README.md +0 -0
  467. /package/docs/{namespaces → api/namespaces}/uuidv5/README.md +0 -0
package/dist/index.js CHANGED
@@ -1 +1 @@
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()}
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:()=>Te,AIChatRoles:()=>A,AIMessageTypes:()=>$,AIStream:()=>Rt,AITextGenerationFinishReasons:()=>k,AbortError:()=>y.AbortError,AbortErrorCode:()=>y.AbortErrorCode,ActionNames:()=>p,AlreadyExistsError:()=>y.AlreadyExistsError,AlreadyExistsErrorCode:()=>y.AlreadyExistsErrorCode,ArrayMergeWay:()=>gi,ArrayMergeWaySymbol:()=>vi,AsyncFeatureBits:()=>Wn,AsyncFeatures:()=>Hn,BaseError:()=>y.BaseError,BinarySemaphore:()=>Fn,CancelableAbility:()=>Kn,ChoiceArgProcessor:()=>be,ClientToolFuncSchema:()=>Mi,ClientToolTransport:()=>os,ClientTools:()=>Ri,CommonError:()=>y.CommonError,ConfigFile:()=>pn.ConfigFile,DEFAULT_CONFIG_NAME:()=>Jr,DefaultAsyncSemaphoreCapacity:()=>qn,DefaultDateFormat:()=>b,EnvPromptTemplate:()=>O.EnvStringTemplate,ErrorCode:()=>y.ErrorCode,EventBusName:()=>bt,EventClient:()=>Ki,EventEmitter:()=>vt.EventEmitter,EventName:()=>gt,EventServer:()=>ns,EventStates:()=>vt.states,EventToolFunc:()=>zi,FStringPromptTemplate:()=>O.FStringTemplate,FewShotPromptTemplate:()=>I,FilenameReservedRegex:()=>ae.FilenameReservedRegex,FuncMetaSymbol:()=>Ni,GolangPromptTemplate:()=>O.GolangStringTemplate,HashAlgorithm:()=>Wt,HttpClientToolTransport:()=>ds,HttpServerToolTransport:()=>fs,IntSet:()=>xn,InternalErrorCode:()=>y.InternalErrorCode,LLM_TOKENIZER_NAMES:()=>$r,LLM_TOKENIZER_NAMES_MAP:()=>Ar,LRUCache:()=>Bi.LRUCache,NotFoundError:()=>y.NotFoundError,NotFoundErrorCode:()=>y.NotFoundErrorCode,NotImplementationError:()=>y.NotImplementationError,NotImplementedErrorCode:()=>y.NotImplementedErrorCode,ObjectArgsToArgsInfo:()=>we,PASSING_SCORE:()=>d,PromptExampleSelector:()=>M,PromptTemplate:()=>O.StringTemplate,RStreamErrCode:()=>At,RateLimit:()=>Ln,ReadableStreamError:()=>Ct,RemoteToolFuncSchema:()=>m,ResClientTools:()=>Zi,ResServerTools:()=>ts,ResponseRStreamErrCode:()=>xt,SHUTDOWN_SIGNALS:()=>ni,SSEChannel:()=>kt,SSEChannelAlreadyClosedErrCode:()=>Et,SecondaryCache:()=>Xi,Semaphore:()=>Pn,ServerToolFuncSchema:()=>Pi,ServerToolTransport:()=>cs,ServerTools:()=>Fi,SignalGate:()=>Dn,SseClientPubSubTransport:()=>ms,SseServerPubSubTransport:()=>ps,StrangeHumanName:()=>x,TaskAbortController:()=>Zn,TemplateArgProcessor:()=>Se,ToolAsyncCancelableBit:()=>Gn,ToolAsyncMultiTaskBit:()=>Jn,ToolAsyncPriorityBit:()=>Un,ToolFunc:()=>Ci,ToolFuncSchema:()=>Oi,ToolTransport:()=>ss,WindowsReservedNameRegex:()=>ae.WindowsReservedNameRegex,YamlTypeBaseObject:()=>zr,_lrucache:()=>Ji,addDate:()=>v.add,assignDirs:()=>lr,backendEventable:()=>St,base32768:()=>re,beforeShutdown:()=>ci,calcPerplexity:()=>pi,calcPerplexitySimple:()=>mi,canonicalize:()=>ee.canonicalize,completeSentences:()=>V,concatText:()=>Y,countLLMTokens:()=>Or,countRegexMatches:()=>Yn,createAbilityInjector:()=>l.createAbilityInjector,createCallbacksTransformer:()=>Ft,createEmptyReadableStream:()=>Nt,createEndWithRepetitionDetector:()=>Ue,createError:()=>y.createError,createEventStreamTransformer:()=>It,createHfValueFunc:()=>O.createHfValueFunc,createLRUCache:()=>Gi,createYamlObjectTag:()=>_r,dateToText:()=>E,decodeCharset:()=>en,defaultTemplateFormat:()=>O.defaultTemplateFormat,defaultsWithConcat:()=>bi,detectCharset:()=>cn,encodeLLMTokens:()=>Cr,ensureQuoted:()=>$e,event:()=>_i,eventClient:()=>Vi,eventServer:()=>rs,eventable:()=>vt.eventable,expandConfig:()=>Ur,expandEnv:()=>O.expandEnv,expandObjEnv:()=>O.expandObjEnv,expandPath:()=>Kr,expandPathInObject:()=>Qr,expandPaths:()=>Vr,extNameLevel:()=>ae.extNameLevel,fileIsExists:()=>Ve,filterValidFnScope:()=>Xe,findIndexNonEmptyFrom:()=>ct,findPort:()=>ir,formatISO:()=>v.formatISO,formatTextWithSpace:()=>Nr,funcGetMeta:()=>Ii,funcWithMeta:()=>ji,genUrlParamsStr:()=>ki,getAllEnumKeys:()=>he,getConfigFileNames:()=>mn,getConfigs:()=>yn,getEnvVairables:()=>O.getEnvVairables,getFileMetaInfo:()=>on,getHashAlgoBySize:()=>an,getKeysPath:()=>Je,getLLMTokenizer:()=>xr,getMultiLevelExtname:()=>ae.getMultiLevelExtname,getPackageDir:()=>ar,getRealFilepath:()=>rn,getResponseErrorReadableStream:()=>Ot,getXDGConfigs:()=>Zr,hasDirectoryIn:()=>hr,hash:()=>se,hashFile:()=>sn,hashObject:()=>oe,hashStream:()=>ie,initShutdown:()=>ui,isLangUsingSpaces:()=>at,isListItemString:()=>rt,isModelNameMatched:()=>ue,isPunctuationChar:()=>st,isQuoted:()=>Ee,isRegExp:()=>yr,isSameString:()=>Dr,isSectionString:()=>et,isSentenceEnding:()=>tt,isSepLineString:()=>it,isStrWrapped:()=>ke,isSubdirectory:()=>ur,isTitleString:()=>nt,isValidFilename:()=>ae.isValidFilename,isValidFilepath:()=>ae.isValidFilepath,isWebStream:()=>$t,joinSplitWords:()=>Ti,jsonFilterToWhere:()=>Tn,jsonToMarkdownStr:()=>An,loadAIConfig:()=>Hr,loadConfig:()=>Wr,loadConfigFile:()=>Gr,loadFileFromPaths:()=>Qe,loadTextFromPaths:()=>tn,lrucache:()=>Ui,makeToolFuncCancelable:()=>Qn,matchUrlProtocol:()=>En,memoize:()=>nr,mergeArray:()=>Si,messagesToText:()=>C,mimeType:()=>dn.mimeType,normalizePath:()=>pr,paramsSizeToScaleStr:()=>kn,parseCommand:()=>Ie,parseDateFormat:()=>w.parse,parseISO:()=>v.parseISO,parseJsJson:()=>ze,parseJsJsonSimpleSync:()=>_e,parseObjectArgInfo:()=>Ne,parseObjectArgumentInfos:()=>ge,parseObjectArguments:()=>me,parseObjectArgumentsAsArgInfos:()=>je,parseYaml:()=>pn.parseYaml,pruneSubdirectories:()=>fr,pruneSubdirectoriesInPlace:()=>dr,quoteStr:()=>Ae,readFilenamesRecursiveSync:()=>nn,readTextFileChunks:()=>Mr,readTextFileChunksEx:()=>Fr,readableFromAsyncIterable:()=>Mt,registerCoreTools:()=>is,registerYamlTag:()=>pn.registerYamlTag,removeMarkdownBold:()=>ut,removeMarkdownBoldAndItalic:()=>lt,removeMarkdownItalic:()=>ht,replaceWithPlaceholder:()=>Re,restoreFromPlacehoders:()=>Me,sanitizeFilename:()=>ae.sanitizeFilename,sanitizeFilepath:()=>ae.sanitizeFilepath,saveConfigFile:()=>wn,scaleStrToParamsSize:()=>$n,shutdown:()=>ai,simplifyObjectArguments:()=>ve,sleep:()=>pt,sortedValues:()=>j,splitChunks:()=>Pr,splitParagraph:()=>ft,splitSentence:()=>K,splitWords:()=>Ei,stringifyYaml:()=>pn.stringifyYaml,stripConsoleColor:()=>wr,textToDate:()=>T,throwError:()=>y.throwError,toDate:()=>v.toDate,toDateTime:()=>S,toRegExp:()=>f.toRegExp,trimStartOfStreamHelper:()=>qt,truncTo:()=>dt,truncateByToken:()=>qr,truncateToTokenLimit:()=>jr,truncateToTokenLimitEx:()=>Ir,uuid:()=>Dt,uuidNIL:()=>zt.NIL,uuidParse:()=>zt.parse,uuidStringify:()=>zt.stringify,uuidValidate:()=>zt.validate,uuidVersion:()=>zt.version,uuidv1:()=>zt.v1,uuidv4:()=>zt.v4,uuidv5:()=>zt.v5,wait:()=>mt,wrapEventEmitter:()=>vt.wrapEventEmitter,xxhash:()=>Yt,xxhash32:()=>Vt,xxhash64:()=>Qt,xxhashAsStr:()=>te,yieldExec:()=>yt}),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,p=["get","post","put","delete","patch","list","res"],m={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"),v=require("date-fns"),g="MMMM d, y 'at' h:m:s b 'GMT'x";function b(t){return t&&(g=t),g}function S(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 T(t,e=g){return(0,w.parse)(t,e,new Date)}function E(t,e=g){return(0,w.format)(t,e)}var k=["stop","length","content_filter","tool_calls","function_call","abort","error","other",null],$=["human","ai","generic","system","tool"],A=["user","assistant","system","tool","tool_calls"],x="陌生人";function C(t){let e="";for(const n of t)if(n.content){e+=n.role.toLowerCase()+":";let t=n.createdAt;if(t){const n=S(t);n&&(e+=" ["+E(n)+"]")}e+=" "+n.content+"\n"}return e}var O=require("@isdk/template-engines"),N=require("@isdk/template-engines");function j(t){return Object.keys(t).sort().map(e=>t[e])}var I=class extends N.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 N.StringTemplate?t.examplePrompt:N.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=j(t);n.length>0&&e.push(...n)}const n=[this.prefix,...e,this.suffix].join(this.exampleSeparator),r=this.templateFormat;return await N.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 q(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}N.StringTemplate.register(I,{name:"fewshot",aliases:["few_shot"]});var R=!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=>{R=t});var M=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,R?r:q(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()}},F=require("@isdk/detect-text-language"),P="@",L=/(\S.+?[.!?])(?=\s+|$)|(\S.+?)(?=[\n]|$)/g,z=/([A-Z][a-z]{1,2}\.)\s(\w)/g,_=/(\.[a-zA-Z]\.)\s(\w)/g,D=new RegExp("([A-Z][a-z]{1,2}\\.)"+P+"(\\w)","g"),B=new RegExp("(\\.[a-zA-Z]\\.)"+P+"(\\w)","g"),X=/(```)([\s\S]*?)(```)/g,J=">>>CODE_BLOCK<<<",G=/([*_`]{1,3})(\S.*?\S)\1/,U=">>> INLINE_BLOCK ",W=/>>> INLINE_BLOCK (\d+) <<</,H=1e4;function Z(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 K(t,{best:e=!0,completeSentence:n,isMarkdown:r,ignoreEmptyLine:i}={}){const s=[],o=[];let a,c=0;for(;c++<H&&(a=X.exec(t));){const e=a[0];s.push(e),t=t.replace(e,"\n"+J+(s.length-1)+"\n")}for(c=0;c++<H&&(a=G.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];nt(n,{isMarkdown:r,nextLine:e[t+1]})&&(s.push(n),e[t]=J+(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(J)){h.push(s[Number(n.slice(J.length))]);continue}if(r&&nt(n,{isMarkdown:r,nextLine:u[t+1]})){h.push(n);continue}if(!e){h.push(n);continue}let a=Z(n,P,[z,_]),c=Array.from(a.matchAll(L)),l=[];if(c.length)for(let t=0;t<c.length;t++)l.push(Z(c[t][0]," ",[D,B]));else l.push(n);h.push(...l.map(t=>ot(o,t)))}return n&&(h=V(h,{isMarkdown:r,ignoreEmptyLine:i})),h}function V(t,{isMarkdown:e,ignoreEmptyLine:n}={}){const r=[];let i=0,s="";for(n=!e&&n;i<t.length;){let o=t[i];if(o){let a;if(n){const n=ct(t,i+1);a=et(t[n],{isMarkdown:e,nextLine:-1===n?"":t[n+1]})}else a=et(t[i+1],{isMarkdown:e,nextLine:t[i+2]});Q(o,{isMarkdown:e,nextLine:t[i+1]})||""===t[i+1]||a?(s&&(o=Y(s,o),s=""),r.push(o)):(s&&(o=Y(s,o)),s=o)}else n||r[r.length-1]&&r.push(o);i++}return s&&r.push(s),r}function Q(t,e){return tt(t)||et(t,e)}function Y(t,e){const n=t+" "+e,r=(0,F.detectTextLanguage)(n,{isoCode:!0});return r&&!at(r)?(st(t)&&(t+=" "),e=t+e):e=t.endsWith("-")?(t=t.slice(0,-1))+e:n,e}function tt(t){if(!t)return!1;return/(([.。!!??]\s*['"”’]?)|```)\s*$/.test(t)}function et(t,e){let n=nt(t,e);return n||(n=rt(t)),n||(n=it(t)),n}function nt(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 rt(t){return/^\s*([*+-]|\d+[.、])\s*(?<item>.*)(?=\n|$)/.exec(t)}function it(t){return/^[-=_]{3,}$/.exec(t)}function st(t){return/[。!??,、;;::'""“”‘’~~《》<>〈〉【】(){}【】\[\]\(\)…·]$/.test(t)}function ot(t,e){let n,r=0;for(;r++<H&&(n=W.exec(e));){const r=Number(n[1]);e=e.replace(n[0],t[r])}return e}function at(t){return!["zh","ja","th","lo","ta","ko"].includes(t)}function ct(t,e=0){for(let n=e;n<t.length;n++){const e=t[n];if(null!=e&&""!==e)return n}return-1}function ut(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 ht(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 lt(t,e){return t=ht(t=ut(t,e),e)}function ft(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||nt(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 dt(t,e=2,n=.5){const r=10**e;return Math.trunc((t+Number.EPSILON+n/r)*r)/r}async function pt(t){return new Promise(e=>setTimeout(e,t))}var mt=pt;async function yt(){return new Promise(t=>{setImmediate(t)})}var wt=require("custom-ability"),vt=require("events-ex"),gt="event",bt="event-bus";var St=(0,wt.createAbilityInjector)(function(t){return class{static get emitter(){if(!this._emitter){const t=this.get(bt)?.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 Tt(t,e){return!t||t.some(t=>t instanceof RegExp?t.test(e):t===e)}var Et=498,kt=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,n){let r,i;this.active||(0,y.throwError)("Channel closed","SSEChannel",Et);let s=e;if(t||e)i=this.nextID++,"object"==typeof t&&(t.event?(s=t.event,void 0!==t.data&&(t=JSON.stringify(t.data))):t=JSON.stringify(t)),t=t?t.split(/[\r\n]+/).map(t=>"data: "+t).join("\n"):"",r="id: "+i+"\n"+(e?"event: "+e+"\n":"")+(t||"data: ")+"\n\n",this.messages.push({id:i,_eventName:s,output:r});else{if(!this.clients.size)return;r="data: \n\n"}if(n?.clientId){const t=Array.isArray(n.clientId)?n.clientId:[n.clientId];[...this.clients].filter(e=>e.clientId&&t.includes(e.clientId)).forEach(t=>t.res.write(r))}else[...this.clients].filter(t=>!s||Tt(t.events,s)).forEach((t,e)=>{t.res.write(r)});for(;this.messages.length>this.options.historySize;)this.messages.shift();return i}subscribe(t,e,n,r){if(this.active||(0,y.throwError)("Channel closed","SSEChannel",Et),!r){const{remoteAddress:e,remotePort:n}=t.socket;e&&n&&(r=`${e}:${n}`)}const i={req:t,res:e,events:n,clientId:r},s=this.options.maxStreamDuration;let o="max-age=0, stale-while-revalidate=0, stale-if-error=0, no-transform";s>0&&(o+=", s-maxage="+(Math.floor(s/1e3)-1));const a={"Content-Type":"text/event-stream","Cache-Control":o,Connection:"keep-alive"};this.options.cors&&(a["access-control-allow-origin"]="*"),i.req.socket.setNoDelay(!0),i.res.writeHead(200,a);let c="retry: "+this.options.clientRetryInterval+"\n\n";const u=Number.parseInt(t.headers["last-event-id"],10),h=Number.isNaN(u)?this.options.rewind:this.nextID-1-u;return h&&this.messages.filter(t=>Tt(i.events,t.eventName)).slice(0-h).forEach(t=>{c+=t.output}),i.res.write(c),this.clients.add(i),s>0&&setTimeout(()=>{i.res.writableEnded||this.unsubscribe(i)},s),i.res.on("close",()=>this.unsubscribe(i)),i}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 $t(t){return t instanceof ReadableStream||t instanceof WritableStream}var At=600,xt=601,Ct=class extends y.BaseError{constructor(t,e=At){super(t,500)}};function Ot(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 Ct(`Response error: ${e}`,xt))}}})}return new ReadableStream({start(t){t.error(new Ct("Response error: No response body",xt))}})}function Nt(){return new ReadableStream({start(t){t.close()}})}var jt=require("eventsource-parser");function It(t){const e=new TextDecoder;let n;return new TransformStream({async start(e){n=(0,jt.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 qt(){let t=!0;return e=>(t&&(e=e.trimStart())&&(t=!1),e)}function Rt(t,e){if(!t.ok)return Ot(t.body);let n=t.body||new ReadableStream({start(t){t.close()}});return n instanceof ReadableStream||(n=ReadableStream.from(n)),n.pipeThrough(It(e))}function Mt(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 Ft(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 Pt=require("uuid"),Lt=c(require("base32768")),zt=require("uuid"),_t={1:Pt.v1,4:Pt.v4,5:Pt.v5};function Dt(t=1,e){const n=_t[t];return e?Lt.encode(n(null,[])):n()}var Bt=c(require("xxhashjs")),Xt=c(require("base32768")),Jt=require("json-canonicalize"),Gt=require("hash-wasm"),Ut=588213,Wt=(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))(Wt||{}),Ht={1:Gt.createMD5,2:Gt.createSHA1,8:Gt.createSHA256,10:Gt.createSHA512,11:Gt.createSHA224,3:Gt.createRIPEMD160,112:Gt.createXXHash32,111:Gt.createXXHash64,113:Gt.createXXHash128},{h32:Zt,h64:Kt}=Bt.default;function Vt(t,e=16){return"object"==typeof t&&(t=(0,Jt.canonicalize)(t)),Zt(t.normalize(),Ut).toString(e)}function Qt(t,e=16){return"object"==typeof t&&(t=(0,Jt.canonicalize)(t)),Kt(t.normalize(),Ut).toString(e)}function Yt(t,e=111,n=Ut){let r;return t.buffer&&(t=t.buffer),112!==e?(r=Kt(t,n),r=new Uint16Array([r._a00,r._a16,r._a32,r._a48]),r=new Uint8Array(r.buffer)):(r=Zt(t,n),r=new Uint16Array([r._low,r._high]),r=new Uint8Array(r.buffer)),r}function te(t,e=111,n=Ut){return Xt.encode(Yt(t,e,n))}var ee=require("json-canonicalize"),ne=c(require("base32768")),re=ne;async function ie(t,{hashAlgo:e=111,seed:n=Ut,outputType:r="string"}={}){const i=await Ht[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):ne.encode(i.digest("binary"))}async function se(t,{hashAlgo:e=111,seed:n=Ut,outputType:r="string"}={}){const i=await Ht[e](n);i.init(),i.update(t);return"string"!==r?i.digest(r):ne.encode(i.digest("binary"))}async function oe(t,e){return se(t=(0,ee.canonicalize)(t),e)}var ae=require("@isdk/util"),ce=require("util-ex");function ue(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,ce.isRegExpStr)(e)){const n=(e=(0,ce.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,ce.isRegExpStr)(n)){const r=(e=(0,ce.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 he(t){return Object.keys(t).filter(t=>Number.isNaN(Number(t)))}var le=require("lodash-es"),fe=require("util-ex"),de=require("lodash-es"),pe=require("util-ex");async function me(t,e,n){return ge(je(t,e,n),e,n)}function ye(t){for(let e=1;e<t.length;e++)if(t[e]<=t[e-1])return!1;return!0}function we(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)))&&ye(n.map(t=>parseInt(t))))t=Object.values(t);else if("0"===r[0]&&ye(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 ve(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 ge(t,e,n){if(t.length){const r=await Promise.all(t.map((t,r)=>Ne(t,r,e,n))),i=n?.returnArrayOnly;let s;if(r?.length){s=_e(`{${r.map(t=>t).join(",")}}`,e)}return s&&!i&&(s=ve(s)),s}}function be(t,e,n,r){const[i,s]=t;if(!i&&"|"===s[0])return"choice: {"+function(t,e,n){const r=je(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=>$e(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(Ee(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 Se([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,de.omitBy)(r,(t,e)=>!e||"_"===e[0]||"function"==typeof t),...i?.templateData}};i?.templateFormat&&(a.templateFormat=i.templateFormat);const c=await O.StringTemplate.formatIf(a);if(c)return o=Ee(c)?c:JSON.stringify(c),s+":"+o}async function Te(t,e,n,r){let i=be(t,0,n,r);return i||(i=await Se(t,e,n,r)),i}function Ee(t){const e=t[0];return('"'===e||"'"===e)&&t[t.length-1]===e}function ke(t,e=['""',"''","{}"]){return e.some(e=>t[0]===e[0]&&t[t.length-1]===e[1])}function $e(t,e='"'){return Ee(t)?t:e+t+e}function Ae(t){return'"'+t.replace(/(?<!\\)"(?!\\)/g,'\\"')+'"'}var xe=["true","false","null","undefined","NaN","Infinity"];async function Ce(t,e,n){const r=(0,pe.newFunction)("async expression",[],`return ${t};`,Xe(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 Oe(t,e,n){let r=t;if(["true","false"].includes(t.toLowerCase()))r=r.toLowerCase();else if(!(i=t,ke(i)||!Number.isNaN(parseFloat(i))||xe.includes(i)||Le(i)||e&&void 0!==(0,de.get)(e,t)||Le(t)))try{r=n?.skipExpression?Ae(t):await Ce.call(this,t,e,n?.preserveUnresolvedName)}catch(e){r=Ae(t)}var i;return r}async function Ne(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 Oe(s.slice(t+1).trim(),n,r)}{const t=s.trim();if(n&&void 0!==(0,de.get)(n,t)){return(a?"":e+":"+t+",")+'"'+t+'":'+t}return e+":"+await Oe(s.trim(),n,r)}}function je(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 Ie(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 me(s,e,n)),{command:i.trim(),args:o}}var qe="__PlacEhoLdeR_";function Re(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??qe,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 Me(t,e,n){const r=n?.placeholder??qe;return e.reduce((t,e,n)=>t.replace(new RegExp(r+n,"g"),e),t)}var Fe="[a-zA-Z_$][a-zA-Z_\\d$]*",Pe=new RegExp(`^\\s*(\\(\\s*\\)|${Fe}|\\(${`${Fe}\\s*(,\\s*${Fe})*`}\\))\\s*=>`);function Le(t){return Pe.test(t)}async function ze(t,e){if(e&&(e=Xe(e)),e&&(t=t.trim()).startsWith("{")&&t.endsWith("}")){return await me(t.slice(1,-1),e,{assigner:":",ignoreIndexNamed:!0})}return _e(t,e)}function _e(t,e){if(e&&(e=Xe(e)),e){const n=Object.keys(e);if(n.length){const r=Object.values(e);let i=0;for(;i++<100;)try{return(0,fe.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,fe.newFunction)("expression",[],`return ${t}`)()}var De=/^[a-zA-Z_$][0-9a-zA-Z_$.]*$/,Be=t=>De.test(t);function Xe(t){if(t){const e=Object.keys(t),n=e.length,r=e.filter(e=>Be(e)&&null!==t[e]);if(n===r.length)return t;if(r.length)return t=(0,le.pick)(t,r)}}function Je(t){return t?Ge(t,[],{dot:""}):[]}function Ge(t,e,{dot:n=".",visited:r=new Set}={}){return r.has(t)?[e.join("")]:Array.isArray(t)?(r.add(t),t.flatMap((t,n)=>Ge(t,[...e,`[${n}]`],{dot:".",visited:r}))):(i=t)&&i.constructor===Object?(r.add(t),Object.entries(t).flatMap(([t,i])=>Ge(i,[...e,n+t],{dot:".",visited:r}))):[e.join("")];var i}function Ue(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 We=c(require("path")),He=c(require("fs")),Ze=c(require("mime-type/with-db")),Ke=c(require("jschardet"));function Ve(t){const e=He.statSync(t,{throwIfNoEntry:!1});return e?.isFile()}function Qe(t,e,n,r){const i=r?.signal,s=r?.exclude;let o;if(We.default.isAbsolute(t)?o=Ve(t)?t:Ye(We.default.basename(t),[We.default.dirname(t)],{extNames:n,exclude:s,signal:i}):(e||(e=["."]),o=Ye(t,e,{extNames:n,exclude:s,signal:i})),!o)throw new y.NotFoundError(t,"loadFileFromPaths");{const t=o;o=He.readFileSync(o),r&&(r.filepath=t)}return o}function Ye(t,e,{extNames:n,signal:r,exclude:i=[]}){let s;const o=n?n.map(e=>(0,ae.getMultiLevelExtname)(t,(0,ae.extNameLevel)(e))):void 0;"string"==typeof i&&(i=[i]);for(const a of e){if(r?.aborted)throw r.reason;const e=We.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)&&Ve(r)){s=r;break}}else if(!i.includes(e)&&Ve(e)){s=e;break}}return s}function tn(t,e,n,r,i){let s;"string"==typeof r?(s=r,r=void 0):s=r?.encoding;return en(Qe(t,e,n,r),s)}function en(t,e){void 0===e&&(e=cn(t)??"utf8");return new TextDecoder(e).decode(t)}function nn(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?rn(t.dir):t.dir,h=We.default.resolve(e);if(i.has(h))continue;i.add(h);const l=He.statSync(e,{throwIfNoEntry:!1});if(l?.isDirectory()){u=t.level+1;const i=He.readdirSync(e,{withFileTypes:!0});for(let t=0;t<i.length;t++){let s=i[t],h=We.default.join(e,s.name);const l=h;if(s.isSymbolicLink()){const t=We.default.dirname(h);if(h=He.readlinkSync(h),h=We.default.resolve(t,h),s=He.statSync(h,{throwIfNoEntry:!1}),!s)continue}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 rn(t){const e=He.lstatSync(t,{throwIfNoEntry:!1});return e?.isSymbolicLink()&&(t=He.readlinkSync(t)),t}async function sn(t,e){return ie(ReadableStream.from(He.createReadStream(t)),e)}async function on(t){const e=We.default.basename(t);t=We.default.resolve(t);const n=await He.promises.stat(t),r=n.mtime,i=n.ctime,s=n.size,o=an(s),a=await sn(t,{hashAlgo:o}),c=Ze.default.lookup(t);return{name:e,mtime:r,ctime:i,size:s,hash:Wt[o]+":"+a,mimeType:c,id:"file://"+t}}function an(t){let e=111;return t<=2048?e=112:t<=1048576?e=111:t<=10485760?e=113:t>10485760&&(e=10),e}function cn(t,e){return Ke.default.detect(t,e).encoding}var un=require("fs"),hn=c(require("path")),ln=require("@isdk/util"),fn=require("yaml-types"),dn=require("mime-type/with-db"),pn=require("@isdk/util");function mn(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,ln.traverseFolderSync)(t,(t,e)=>{if(i?.includes(t)||!e.isFile())return;const o=hn.default.extname(t),a=(0,un.statSync)(t);if(s.includes(o)){if(r?.hasOwnProperty(t)&&a.mtimeMs<=r[t])return;n.push(t)}}),n}function yn(t,e){return mn(t,e).map(t=>ln.ConfigFile.loadSync(t)).filter(t=>void 0!==t)}function wn(t,e,n=1){return ln.ConfigFile.saveSync(t,e,{extLevel:n})}function vn(t){t instanceof Date&&(t=t.toISOString());return function(t,e){return t?`'${e}'`:String(e)}("string"==typeof t,t)}function gn(t,e){return t.map(t=>Tn(t,e)).join(" AND ")}function bn(t,e){return t.map(t=>Tn(t,e)).join(" OR ")}function Sn(t,e){const n=[];return Object.keys(e).forEach(r=>{const i=e[r];switch(r){case"$lt":case"<":n.push(`${t} < ${vn(i)}`);break;case"<=":case"$lte":n.push(`${t} <= ${vn(i)}`);break;case"$gt":case">":n.push(`${t} > ${vn(i)}`);break;case"$gte":case">=":n.push(`${t} >= ${vn(i)}`);break;case"$ne":case"!=":n.push(`${t} != ${vn(i)}`);break;case"=":case"$eq":n.push(`${t} = ${vn(i)}`);break;case"$in":n.push(`${t} IN (${i.map(t=>vn(t)).join(", ")})`);break;case"$nin":n.push(`${t} NOT IN (${i.map(t=>vn(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 Tn(t,e){const n=[];if("function"!=typeof e&&(e=t=>t),Array.isArray(t))n.push(gn(t,e));else for(const[r,i]of Object.entries(t))if("$and"===r)n.push(`(${gn(t[r],e)})`);else if("$or"===r)n.push(`(${bn(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(Sn(e(r),i))}return n.length>1?n.join(" AND "):n[0]}function En(t){const e=t.indexOf("://");if(e>0)return t.substring(0,e)}function kn(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 $n(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 An(t,e){const n=e?.level||0,r=e?.visiting||new Set,i=e?.objectTag||"*",s=e?.arrayTag||"-",o=!0===e?.title?"name":e?.title;let a=[];const c=" ".repeat(2*n);if(null!=t)switch(typeof t){case"object":r.has(t)?a=["[Circular]"]:(r.add(t),a=Array.isArray(t)?t.map(e=>s+u(e,t)):Object.entries(t).map(([e,n])=>i+" `"+e+"`:"+u(n,t)));break;case"string":return t;default:return JSON.stringify(t)}else a=["null"];return a.length?c+a.join("\n"+c):"";function u(t,e){const i=null!=t&&"object"==typeof t;let s="";return o&&"string"==typeof o&&i&&t[o]&&"string"==typeof t[o]&&(s=" "+t[o],delete t[o]),(i?s+"\n":" ")+An(t,{level:n+1,visiting:r,parent:e})}}(0,ln.registerYamlTag)(fn.regexp);var xn=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}},Cn=require("util-ex"),On=require("events-ex");function Nn(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 jn=class extends Array{constructor(t,e){Array.isArray(t)?(super(...t),this._length=t.length,t=void 0):(super(),this._length=0),this._capacity=Nn(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(Nn(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)}}},In=require("@isdk/common-error"),qn=32;function Rn(t){return"function"==typeof t}function Mn(){return"1"}var Fn=class{constructor(t={}){const{initFn:e=Mn,pauseFn:n,resumeFn:r,capacity:i=qn}=t;if(Rn(n)!==Rn(r))throw new Error("pauseFn and resumeFn must be both set for pausing");this.waiting=new jn(i),this.emitter=new On.EventEmitter,this.useDefaultTokens=e===Mn,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 In.AbortError(e.reason||"aborted");e.alreadyRejected=!0,r(t)}),n};let r=this.tryAcquire(t);const i=r&&(0,Cn.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 In.AbortError(t))}get activeCount(){return this._activeCount}get pendingCount(){return this.waiting.size}},Pn=class extends Fn{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 jn(e);for(let t=0;t<e;t++)this.free.push(this.initTokenFn())}tryAcquire(t){let e=this.isReady;if(e&&(0,Cn.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 Ln(t,{timeUnit:e=1e3,uniformDistribution:n=!1}={}){const r=new Pn(n?1:t),i=n?e/t:e;return async function(){await r.acquire(),setTimeout(()=>r.release(),i)}}var zn,_n=require("@isdk/common-error"),Dn=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 _n.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})})}},Bn=require("custom-ability"),Xn=require("util-ex"),Jn=0,Gn=1,Un=2,Wn=(t=>(t[t.MultiTask=Jn]="MultiTask",t[t.Cancelable=Gn]="Cancelable",t[t.Priority=Un]="Priority",t))(Wn||{}),Hn=((zn=Hn||{})[zn.MultiTask=1<<Jn]="MultiTask",zn[zn.Cancelable=1<<Gn]="Cancelable",zn[zn.Priority=1<<Un]="Priority",zn),Zn=class extends AbortController{constructor(t){super(),(0,Xn.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")}}},Kn=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 Pn(e-1,{isReadyFn:t})),n}static hasAsyncFeature(t){const e=this.prototype;let n=e.asyncFeatures;return e._asyncFeatures&&(n|=e._asyncFeatures),xn.has(n,t)}hasAsyncFeature(t){let e=this.asyncFeatures;return this._asyncFeatures&&(e|=this._asyncFeatures),xn.has(e,t)}isAborted(t){const e=this.hasAsyncFeature(Jn);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(Jn);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(Jn)){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(Jn);if(!r&&n&&this.getRunningTask())throw new y.CommonError("The task is running",this.name,y.ErrorCode.TooManyRequests);const i=t?.aborter||new Zn(this);if(!(i instanceof Zn)){if(!(i instanceof AbortController))throw new y.CommonError("aborter should be an AbortController",this.name,y.ErrorCode.InvalidArgument);Object.setPrototypeOf(i,new Zn(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=[...Vn(t?.signal),...Vn(t?.signals)];s.length&&function(t,e){if(!e.length)return;const n=[],r=()=>{for(const t of n)try{t()}catch{}n.length=0},i=e.find(t=>t.aborted);if(i){const e=i.reason;try{t.abort(e||"aborted")}catch{}return}for(const r of e){const e=()=>{const e=r.reason;try{t.abort(e||"aborted")}catch(t){console.log(t)}};r.addEventListener("abort",e,{once:!0}),n.push(()=>r.removeEventListener("abort",e))}const s=()=>r();t.signal.addEventListener("abort",s,{once:!0}),n.push(()=>t.signal.removeEventListener("abort",s))}(i,s);const o=t?.timeout;return o>0&&(i.timeoutId=setTimeout(()=>{i.timeoutId=void 0,this.abort("timeout",{timeout:o})},o)),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{try{i.streamController?.error?.(e.reason)}catch{}}}),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(Jn)){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=Ft({onStart:t=>{(0,Xn.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(Jn)){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)}}};function Vn(t){return t?Array.isArray(t)?t.filter(Boolean):[t]:[]}Kn.prototype.generateAsyncTaskId=function(t,e){return this._generateAsyncTaskId(t,e)},Kn.prototype.cleanMultiTaskAborter=function(t,e){return this._cleanMultiTaskAborter(t,e)};var Qn=(0,Bn.createAbilityInjector)(Kn,"abort",{afterInjection:function(t,e){let n=t.prototype._asyncFeatures||0;n|=Hn.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 Yn(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 tr=c(require("memoizee")),er=require("json-canonicalize");function nr(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,tr.default)(t,{...e,normalizer:t=>{if(r){const e=r(t);if("string"===e)return e;e&&(t=e)}return te((0,er.canonicalize)(t))}})}var rr=c(require("net"));async function ir(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=rr.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 sr=c(require("path")),or=require("package-directory");function ar(t){const e=(0,or.packageDirectorySync)({cwd:t});if(e)return e;const n=t.split(sr.default.sep);let r=n.lastIndexOf("dist");if(r>0)return n.slice(0,r).join(sr.default.sep);if(r=n.lastIndexOf("src"),r>0)return n.slice(0,r).join(sr.default.sep);throw new Error("can not find package directory")}var cr=c(require("path"));function ur(t,e){try{const n=cr.default.relative(cr.default.resolve(t),cr.default.resolve(e));return!n.startsWith("..")&&!cr.default.isAbsolute(n)}catch{return!1}}function hr(t,e){return e?.some(e=>ur(e,t))}function lr(t,e){for(const n of e)hr(n,t)||t.push(n);return t}function fr(t){const e=t.slice();return dr(e),e}function dr(t){const e=t.length;if(e<=1)return;const n=new Map,r=[];for(let i=0;i<e;i++){const e=pr(t[i]);n.has(e)||(r.push(e),n.set(e,i))}const i=[...r].sort(),s=new Set;for(let t=0;t<i.length;t++){const e=i[t];let n=!1;for(const t of s)if(ur(t,e)){n=!0;break}n||s.add(e)}let o=0;for(let n=0;n<e;n++)s.has(r[n])&&(o!==n&&(t[o]=t[n]),o++);t.length=o}function pr(t){let e=cr.default.normalize(t);return e=e.split(/[/\\]/).join(cr.default.posix.sep),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e}var mr=require("util-ex");function yr(t){return(0,mr.isRegExpStr)(t)||(0,mr.isRegExp)(t)}function wr(t){return t.replace(/\x1B[[(?);]{0,2}(;?\d)*./g,"")}var vr=c(require("path")),gr=require("url"),br=require("@huggingface/transformers"),Sr=(0,gr.fileURLToPath)(h),Tr=vr.default.dirname(Sr),Er=vr.default.join(ar(Tr),".cache"),kr=new Map,$r={"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"},Ar={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 xr(t){let e=kr.get(t);return e||(e=br.AutoTokenizer.from_pretrained(t,{cache_dir:Er}),kr.set(t,e)),e}async function Cr(t,e="qwen2.5"){Ar[e]&&(e=Ar[e]);return(await xr(e)).encode(t)}async function Or(t,e="qwen2.5"){return(await Cr(t,e)).length}function Nr(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 jr(t,e){let n,r=1984,i=!0,s=!1,o=!0,a=Or,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??K(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&&et(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 Ir(t,e){let n,r=1984,i=!0,s=Or,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&&et(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 qr(t,e){let n,r=1984,i=Or;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 Rr=c(require("fs"));async function*Mr(t,e){const n=(e={...e,completeSentence:!1,corrected:!1}).size??1984,r=e.modelId,i=e.metaInfo?.size??(await Rr.default.promises.stat(t)).size;let s=Math.trunc(i/2);if(s<=n){let i=en(await Rr.default.promises.readFile(t));if(s=await Or(i,r),s<=n)yield i;else do{const t=await jr(i,{...e,modelId:r,size:n});yield t,i=i.slice(t.length)}while(i)}else{const i=ReadableStream.from(Rr.default.createReadStream(t)).getReader();let s="";for(;;){const{done:t,value:o}=await i.read();if(t)break;s+=en(o);const a=K(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 jr(s,{...e,modelId:r,size:n,sentences:a});s=s.slice(t.length),yield t}for(;s.length>n;){const t=K(s,e),i=await jr(s,{...e,modelId:r,size:n,sentences:t});s=s.slice(i.length),yield i}void 0!==c&&(s+=c)}for(;s;){const t=K(s,e),i=await jr(s,{...e,modelId:r,size:n,sentences:t});s=s.slice(i.length),yield i}}}async function*Fr(t,e){const n=e?.size??1984,r=e?.modelId,i=e?.metaInfo?.size??(await Rr.default.promises.stat(t)).size;let s=Math.trunc(i/2);if(s<=n){let i=en(await Rr.default.promises.readFile(t));if(s=await Or(i,r),s<=n)yield K(i,e);else{let t=K(i,e);do{const i=await Ir(t,{...e,modelId:r,size:n});yield i,t=t.slice(i.length)}while(t.length)}}else{const i=ReadableStream.from(Rr.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+=en(o),u=K(s,e);let a=u.pop();if(s.length>=n){const t=await Ir(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 Ir(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 Ir(u,{...e,modelId:r,size:n});u=u.slice(t.length),yield t}}}async function Pr(t,e){const n=e?.size??1984,r=e?.modelId;let i=K(t,e);const s=[];if(await Or(t,r)<=n)s.push(i);else do{const t=await Ir(i,{...e,modelId:r,size:n});s.push(t),i=i.slice(t.length)}while(i.length);return s}var Lr=require("yaml"),zr=class{constructor(t){t&&Object.assign(this,t)}};function _r(t,e){class n extends Lr.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 Dr(t,e){let n=t.length===e.length;if(n){const r=Yt(t),i=Yt(e);n=r.every((t,e)=>t===i[e])}return n}var Br=require("lodash-es"),Xr=c(require("path")),Jr=".ai";function Gr(t,e=["."]){if(Xr.default.isAbsolute(t))return pn.ConfigFile.loadSync(t);const n=e.map(e=>pn.ConfigFile.loadSync(Xr.default.resolve(e,t))).filter(Boolean);return(0,Br.defaultsDeep)({},...n.reverse())}function Ur(t,e){const n={...process.env,...e};return(0,O.expandObjEnv)(t,{processEnv:n,parsed:n})}function Wr(t,e){let n=pn.ConfigFile.loadSync(Xr.default.resolve(e.configDir,t));n||(n={configDirs:["$XDG_BIN_HOME",e.configDir,"$HOME"],brainDir:Xr.default.join(e.dataDir,"brain"),agentDirs:[Xr.default.join(e.dataDir,"agent")],promptDirs:[Xr.default.join(e.dataDir,"prompt")],chatsDir:Xr.default.join(e.dataDir,"log","chats"),inputsDir:Xr.default.join(e.dataDir,"log","inputs")});const r=Zr(e);for(const[t,e]of Object.entries(r))n[t]=e;Ur(n,n);const i=n.configDirs;n.AI_CONFIG_BASENAME&&(t=n.AI_CONFIG_BASENAME);const s=Ur(Gr(t,i),n);return(0,Br.defaultsDeep)(s,(0,Br.omit)(n,Object.keys(r))),Qr(s),s}function Hr(t){return Wr(Jr,t)}function Zr(t){return{XDG_CONFIG_HOME:t.configDir,XDG_DATA_HOME:t.dataDir,XDG_CACHE_HOME:t.cacheDir,XDG_BIN_HOME:Xr.default.dirname(t.options.root)}}function Kr(t,e){t.startsWith("~")&&(t="$HOME"+t.slice(1));return Ur(t,e)}function Vr(t,e){return t.map(t=>Kr(t,e))}function Qr(t,e=["configDirs","brainDir","agentDirs","promptDirs","chatsDir","inputsDir"],n){for(const r of e){const e=(0,Br.get)(t,r);if(!e)continue;let i;Array.isArray(e)&&e.length?i=Vr(e,n):"string"==typeof e&&(i=Kr(e,n)),i&&(0,Br.set)(t,r,i)}}var{exit:Yr}=process,ti=!1,ei=!1,ni=["SIGINT","SIGTERM","exit"],ri=3e5,ii=[],si=(t,e)=>t.forEach(t=>process.once(t,e)),oi=t=>()=>{setTimeout(()=>(console.warn(`Could not close resources gracefully after ${t}ms: forcing shutdown`),Yr(1)),t).unref()};async function ai(t="shutdown",e=0){if(!ti){ti=!0,"number"==typeof t&&(e=t,t="shutdown");for(const e of ii)try{await e(t)}catch(t){console.warn(`A shutdown handler failed before completing with: ${t.message||t}`)}return Yr(e)}console.warn(`Shutdown already in progress, ignoring [${t}] signal`)}function ci(t){if(ei||ui(),!ii.some(e=>e===t))return ii.push(t),t}function ui(){ei||(ei=!0,process.exit=t=>{ti||ai(void 0,t).then()},si(ni,oi(ri)),si(ni,ai))}var hi=["<BOS>","<EOS>","<PAD>","<UNK>"],li=".,!?;?!",fi=[" ","\n","\t","▁"," "],di=["the","a","an","的","是","在"];function pi(t,e){const n=e?.exclude?function(t){const e=new Set;if(t.controlSymbols&&hi.forEach(t=>e.add(t)),t.punctuation)for(let t=0;t<li.length;t++)e.add(li[t]);return t.stopWords&&di.forEach(t=>e.add(t)),t.whitespace&&fi.forEach(t=>e.add(t)),Array.isArray(t.tokens)&&t.tokens.forEach(t=>e.add(t)),[...e]}(e.exclude):void 0;return n&&n.length&&(t=t.filter(t=>!n.includes(t.token.trim()))),mi(t)}function mi(t){if(!Array.isArray(t)||0===t.length)return;const e=t.reduce((t,e)=>t+e.probability,0);return Math.exp(-e/t.length)}var yi=require("lodash-es"),wi=/^\s*@inheritMerge\s*(?:[(]\s*(?<arg>\.start|\.end|false)[)])?/,vi=Symbol("MergeWay"),gi={replace:0,start:1,end:2};function bi(t,...e){return(0,yi.mergeWith)(t,...e,(t,e)=>Array.isArray(t)&&Array.isArray(e)?Si(t,e):void 0!==t&&"object"!=typeof t?t:void 0)}function Si(t,e){let n=t[vi];return void 0===n&&(t=function(t){const e=t[0];let n=".start";if("string"==typeof e){const r=wi.exec(e);r&&(r.groups?.arg&&(n=r.groups?.arg),t=t.slice(1))}else e&&"object"==typeof e&&e.hasOwnProperty("@inheritMerge")&&(n=e["@inheritMerge"]||n,t=t.slice(1));n&&(n=n.toLowerCase());let r=gi.start;"false"===n||"no"===n||"not"===n?r=gi.replace:".end"===n&&(r=gi.end);return Object.defineProperty(t,vi,{value:r,enumerable:!1}),t}(t),n=t[vi]),t=n===gi.replace?e:n===gi.end?t.concat(e):e.concat(t),Object.defineProperty(t,vi,{value:n,enumerable:!1}),t}function Ti(t,e=" "){return Ei(t).join(e)}function Ei(t){return t.split(/(?<=[a-z])(?=[A-Z])|(?<=\d)(?=[A-Za-z])|(?<=[A-Z])(?=[A-Z][a-z])|[\s_]+/g).filter(t=>t.length>0)}function ki(t){if(void 0!==t){const e=JSON.stringify(t);if("{}"!==e&&"[]"!==e&&'""'!==e)return"?p="+encodeURIComponent(e)}return""}var $i=require("lodash-es"),Ai=require("property-manager"),xi=require("util-ex"),Ci=class t extends Ai.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??0;return e._asyncFeatures&&(n|=e._asyncFeatures),xn.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??0;return this._asyncFeatures&&(e|=this._asyncFeatures),xn.has(e,t)}isStream(t){let e=this.stream;if(e){const n=this.params;n?.stream&&(e=t?.stream)}return e}},Oi={name:{type:"string"},description:{type:"string"},title:{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,xi._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"]}};Ci.defineProperties(Ci,Oi);var Ni=Symbol("meta");function ji(t,e,n=!0){if(e&&"object"==typeof e){if("function"==typeof t)return e=n?(0,$i.assign)({},t[Ni],e):(0,$i.defaultsDeep)({},t[Ni],e),t[Ni]=e,t;if(t instanceof Ci)return t.assign(e)}}function Ii(t){return"function"==typeof t?t[Ni]:t instanceof Ci?t.toObject():void 0}var qi="A client transport has not been set. Use ClientTools.setTransport() or transport.mount(ClientTools) first.",Ri=class t extends Ci{static get apiRoot(){return this._transport||(0,y.throwError)(qi,"ClientTools"),this._transport.apiRoot}static setTransport(t){if(t){this._transport=t;const e=this.constructor;t.Tools!==e&&(t.Tools=e)}}static get transport(){return this._transport}static async loadFrom(t){return t||(this._transport||(0,y.throwError)(qi,"ClientTools"),t=await this._transport.loadApis()),t&&this.loadFromSync(t),t}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,...n){const r=this.get(t);if(r&&r.fetch)return r.fetch(e,...n)}get apiRoot(){return this.constructor.apiRoot}async fetch(t,e,n){const r=this.constructor;if(r._transport)return r._transport.fetch(this.name,t,e,n,this.fetchOptions);(0,y.throwError)(qi,"ClientTools")}async func(t){return await this.fetch(t)}},Mi={...m};Ri.defineProperties(Ri,Mi);var Fi=class t extends Ci{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}run(t,e){return e&&(t._req=e.req,t._res=e.reply),super.run(t)}func(t){}},Pi={...m};Fi.defineProperties(Fi,Pi);var Li=require("events-ex"),zi=class extends Ci{constructor(){super(...arguments),this._emitter=new Li.EventEmitter,this.description="Return event bus",this.result="event"}get emitter(){return this._emitter}func(){return this.emitter}},_i=new zi(bt),Di=require("secondary-cache"),Bi=require("secondary-cache"),Xi=Di.Cache;function Ji({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 Gi(t,e){let n=Ci.get(t);return n||(n=new Ci(t,{func:Ji,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 Di.Cache(e)),n}var Ui=Gi("lrucache"),Wi=class extends Ri{async fetch(t,e,n){return t||(t={}),e?.startsWith("$")&&(t.act=e,e="post"),await super.fetch(t,e,n)}async _func(t,e){return await this.fetch(e,t)}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))}}},Hi={methods:{type:"array",assign(t,e,n,r,i){i?.isExported||e.assignMethods(t)}}};Wi.defineProperties(Wi,Hi);var Zi=class extends Wi{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)}},Ki=class extends Zi{constructor(){super(...arguments),this._sseListeners={},this._forwardEvents=new Set,this.description="subscribe server event",this.ebListener=async function(...t){const e=this.type;this.target.publish&&await this.target.publish({data:t,event:e})}}static setPubSubTransport(t){this._pubSubTransport=t}static get pubSubTransport(){if(!this._pubSubTransport)throw new Error("EventClient pubSubTransport not set");return this._pubSubTransport}get evtSource(){let t=this._stream;return t&&2!==t.readyState||(t=this.initEventStream(this._streamEvents)),t}get active(){return!!this._stream&&2!==this._stream.readyState}set active(t){t!==this.active&&(t?this.initEventStream(this._streamEvents):this._stream&&this.close())}initEventStream(t){const e="string"==typeof t?[t]:t;if(this._stream&&2!==this._stream.readyState){if(!this._streamEvents||e&&e.every(t=>this._streamEvents.includes(t)))return this._stream;this._stream.close()}const n=e?ki({event:e}):"",r=`${this.apiRoot}/${this.name}${n}`,i=this._stream=this.constructor.pubSubTransport.connect(r);return Object.entries(this._sseListeners).forEach(([t,e])=>{i.on(t,e)}),this._streamEvents=e,i}esListener(t,e,n){if(!this._forwardEvents.has(t)){const n=this.emitter;n&&t&&(Array.isArray(e)?n.emit(t,...e):n.emit(t,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._sseListeners[e]){const t=this._sseListeners[e]=(t,n)=>this.esListener(e,t,n);n.on(e,t)}return e}async unsubscribe(t){"string"==typeof t&&(t=[t]);const e=await this.unsub({event:t}),n=this.evtSource;for(const e of t){const t=this._sseListeners[e];t&&(delete this._sseListeners[e],n.off(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.initEventStream(t),t)return await this.subscribe(t)}close(){const t=this._stream;if(t)return this._stream=void 0,t.close()}},Vi=new Ki(gt),Qi=require("util-ex"),Yi=class extends Fi{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,Qi.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)}};Yi.defineProperties(Yi,{methods:{type:"array"}});var ts=class extends Yi{constructor(t,e={}){super(t,e),this.action="res",this.params={id:{type:"string"},val:{type:"any"}}}static{this.SpecialRpcMethodNames=p}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}},es=_i.runSync(),ns=class t extends ts{constructor(){super(...arguments),this.description="subscribe server event",this.result="event",this.depends={[bt]:_i}}static setPubSubTransport(t){this._pubSubTransport=t}static get pubSubTransport(){return this._pubSubTransport||console.warn("EventServer pubSubTransport not set"),this._pubSubTransport}get pubSubTransport(){return this.constructor.pubSubTransport}static publish(t,e,n){return this.pubSubTransport?.publish(e,t,n)}static ebListener(t,...e){this.pubSubTransport?.publish(t,e)}static subscribe(t,e,n,r){return this.pubSubTransport?.subscribe(n,{...r,req:t,res:e})}static alreadyForward(t){const e=es.listeners(t);for(const t of e)if(t===this._boundEbListener)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]);const n=this.constructor;n._boundEbListener||(n._boundEbListener=function(...t){return n.ebListener(this.type,...t)});for(const r of e)t.alreadyForward(r)||es.on(r,n._boundEbListener)}unforward(t){"string"==typeof t&&(t=[t]);const e=this.constructor;if(e._boundEbListener)for(const n of t)es.off(n,e._boundEbListener)}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)}},rs=new ns(gt);function is(){_i.register(),Ui.register()}var ss=class{setApiRoot(t){this.apiRoot=t}mount(t,e,n){if(e)this.setApiRoot(e);else if(!(e=this.apiRoot))throw new Error("apiRoot is required");return this.Tools=t,this.options=n,this._mount(t,e,n)}},os=class extends ss{constructor(t){if(!t)throw new Error("apiRoot is required for HttpClientTransport");super(),this.setApiRoot(t)}async _mount(t,e,n){return t.setTransport(this),t.loadFrom()}async loadApis(){return this.fetch("",void 0,"get",void 0,{headers:{"Content-Type":"application/json"}})}async fetch(t,e,n,r,i){i={...this.options,...i};const s=await this._fetch(t,e,n,r,i);if(e?.stream)return s;return await this.toObject(s,e)}},as=require("lodash-es"),cs=class extends ss{_mount(t,e,n){this.addDiscoveryHandler(e,()=>t),this.addRpcHandler(t,e,n)}start(t){return this.options&&(t=(0,as.defaultsDeep)(t,this.options)),this._start(t)}},us=c(require("http")),hs=require("url"),ls=require("lodash-es"),fs=class extends cs{constructor(t){super(),this.discoveryHandlerInfo=null,this.rpcHandlerInfo=null,this.server=t?us.default.createServer(t,this.requestListener.bind(this)):us.default.createServer(this.requestListener.bind(this))}async requestListener(t,e){const{url:n,method:r}=t;if(!n)return e.statusCode=400,e.setHeader("Content-Type","application/json"),void e.end(JSON.stringify({error:"Bad Request"}));if(this.discoveryHandlerInfo&&"GET"===r&&n===this.discoveryHandlerInfo.prefix)try{const t=this.discoveryHandlerInfo.handler();e.setHeader("Content-Type","application/json"),e.statusCode=200,e.end(JSON.stringify(t)),console.log(`[HttpServerTransport] Handled GET ${n} for discovery`)}catch(t){e.statusCode=500,e.setHeader("Content-Type","application/json"),e.end(JSON.stringify({error:t.message||"Internal Server Error"}))}else this.rpcHandlerInfo&&n.startsWith(this.rpcHandlerInfo.prefix)?await this.handleRpcRequest(t,e):(e.statusCode=404,e.setHeader("Content-Type","application/json"),e.end(JSON.stringify({error:"Not Found"})))}addDiscoveryHandler(t,e){this.discoveryHandlerInfo={prefix:t,handler:e},console.log(`[HttpServerTransport] Mapped GET ${t} for discovery`)}addRpcHandler(t,e,n){e.endsWith("/")||(e+="/"),this.rpcHandlerInfo={prefix:e,serverTools:t,options:n},console.log(`[HttpServerTransport] Mapped RPC calls for prefix ${e}`)}async handleRpcRequest(t,e){if(!this.rpcHandlerInfo||!t.url)return e.statusCode=500,e.setHeader("Content-Type","application/json"),void e.end(JSON.stringify({error:"RPC handler not configured"}));const{serverTools:n,prefix:r}=this.rpcHandlerInfo,i=t.url.split("?")[0].substring(r.length),[s,o]=i.split("/"),a=n.get(s);if(!a)return e.statusCode=404,e.setHeader("Content-Type","application/json"),void e.end(JSON.stringify({error:`${s} Not Found`,data:{what:s}}));let c;const u=t.method;try{if("GET"===u||"DELETE"===u){const e=new hs.URL(t.url,`http://${t.headers.host}`).searchParams.get("p");c=e?JSON.parse(e):{}}else{const e=await this.getRequestBody(t);c=e?JSON.parse(e):{}}c._req=t,c._res=e,void 0!==o&&(c.id=o);let n=await a.run(c);a.isStream(c)?n&&"function"==typeof n.pipe?n.pipe(e):e.writableEnded||e.end():(e.setHeader("Content-Type","application/json"),e.statusCode=200,e.end(JSON.stringify(n)))}catch(t){if(console.error("Error during RPC execution:",t),e.headersSent)return;e.setHeader("Content-Type","application/json"),t.code&&"number"==typeof t.code?(e.statusCode=t.code,t.stack&&(t.stack=void 0),e.end(JSON.stringify(t))):(e.statusCode=500,e.end(JSON.stringify({error:t.message||"Internal Server Error"})))}}getRequestBody(t){return new Promise((e,n)=>{let r="";t.on("data",t=>{r+=t.toString()}),t.on("end",()=>{e(r)}),t.on("error",t=>{n(t)})})}async _start(t){const{port:e,host:n="0.0.0.0"}=(0,ls.defaultsDeep)(t,{port:3e3});return new Promise((t,r)=>{this.server.on("error",t=>{console.error("[HttpServerTransport] Server error:",t),r(t)}),this.server.listen(e,n,()=>{const e=this.server.address(),n="string"==typeof e?e:`${e?.address}:${e?.port}`;console.log(`[HttpServerTransport] Server listening on ${n}`),t()})})}async stop(){return new Promise((t,e)=>{if(!this.server.listening)return t();this.server.close(n=>{if(n)return e(n);t()})})}getRaw(){return this.server}},ds=class extends os{async loadApis(){const t=await fetch(this.apiRoot,{headers:{"Content-Type":"application/json"}});if(!t.ok)throw new Error(`Failed to load tools from ${this.apiRoot}: ${t.statusText}`);return await t.json()}async _fetch(t,e,n,r,i){const s=["post","put","patch"];let o;n||(n=this.Tools.action||"post"),"res"===n&&(n="get"),i.headers&&i.headers["Content-Type"]||!s.includes(n)||(i.headers={"Content-Type":"application/json",...i.headers}),e?.stream&&!i.headers.Connection&&(i.headers.Connection="keep-alive"),r?("string"!=typeof r&&(r=JSON.stringify(r)),t&&(r=t+"/"+r)):r=t,i.method=n.toUpperCase(),"get"===n||"delete"===n?o=r+ki(e):(i.body=JSON.stringify(e),o=r),i.headers&&!s.includes(n)&&delete i.headers["Content-Type"];const a=await fetch(`${this.apiRoot}/${o}`,i);if(!a.ok){throw await this.errorFrom(t,a)}return a}async errorFrom(t,e){let n,r=e.status,i=e.statusText;if(e.body){const r=await e.text();try{const e=JSON.parse(r);e&&(e.error&&(i=e.error),e.name&&(t=e.name),e.data&&(n=e.data,n.name=t,n.what&&(n.msg=i,i=n.what)),e.message&&(i=i+":"+e.message))}catch(t){console.warn("🚀 ~ parse error body to json:",t)}}return(0,y.createError)(i,t,r)}async toObject(t,e){return await t.json()}},ps=class{constructor(){this.name="sse",this.protocol="sse",this.channel=new kt}mount(){}subscribe(t,e){const{req:n,res:r,clientId:i}=e??{};if(!n||!r)throw new Error("SSE subscribe requires options.req and options.res");const s=this.channel.subscribe(n,r,t,i),o={id:`${Date.now()}-${Math.random().toString(36).slice(2)}`,clientId:s.clientId,protocol:"sse",send:(t,e)=>{r.write(`event: ${t}\n`),r.write(`data: ${JSON.stringify(e)}\n\n`)},close:()=>r.end?.(),raw:r};return this.onConn?.(o),n.on("close",()=>this.onDis?.(o)),s}publish(t,e,n){this.channel.publish(e,t,n)}onConnection(t){this.onConn=t}onDisconnect(t){this.onDis=t}},ms=class{connect(t,e){const n=e?`?${new URLSearchParams(e).toString()}`:"",r=new EventSource(`${t}${n}`),i=new Map,s=(t,e)=>{const n=n=>{const r=n.data,i=r?"string"==typeof r?JSON.parse(r):r:void 0;e(i,{...n,event:t})};let s=i.get(t);s||(s=new Map,i.set(t,s)),s.set(e,n),r.addEventListener(t,n)},o=(t,e)=>{const n=i.get(t),s=n?.get(e);s&&(r.removeEventListener(t,s),n.delete(e))};return{protocol:"sse",get readyState(){return r.readyState},on:s,off:o,addEventListener:s,removeEventListener:o,close:()=>r.close()}}disconnect(t){return t.close()}};
package/dist/index.mjs CHANGED
@@ -1 +1 @@
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};
1
+ import{AIArgProcessor as t,AIChatRoles as e,AIMessageTypes as r,AIStream as s,AITextGenerationFinishReasons as o,AbortError as n,AbortErrorCode as i,ActionNames as a,AlreadyExistsError as c,AlreadyExistsErrorCode as p,ArrayMergeWay as h,ArrayMergeWaySymbol as l,AsyncFeatureBits as u,AsyncFeatures as d,BaseError as f,BinarySemaphore as v,CancelableAbility as y,ChoiceArgProcessor as m,ClientToolFuncSchema as S,ClientTools as w,CommonError as T,ConfigFile as N,DEFAULT_CONFIG_NAME as E,DefaultAsyncSemaphoreCapacity as $,DefaultDateFormat as O,EnvStringTemplate as C,ErrorCode as J,EventBusName as g,EventClient as j,EventEmitter as R,EventName as P,EventServer as x,EventToolFunc as q,FStringTemplate as H,FewShotPromptTemplate as b,FilenameReservedRegex as G,FuncMetaSymbol as I,GolangStringTemplate as L,HashAlgorithm as D,IntSet as F,InternalErrorCode as M,LLM_TOKENIZER_NAMES as _,LLM_TOKENIZER_NAMES_MAP as k,LRUCache as A,NIL as B,NotFoundError as V,NotFoundErrorCode as Q,NotImplementationError as U,NotImplementedErrorCode as z,ObjectArgsToArgsInfo as K,PASSING_SCORE as W,PromptExampleSelector as X,RStreamErrCode as Y,RateLimit as Z,ReadableStreamError as tt,RemoteToolFuncSchema as et,ResClientTools as rt,ResServerTools as st,ResponseRStreamErrCode as ot,SHUTDOWN_SIGNALS as nt,SSEChannel as it,SSEChannelAlreadyClosedErrCode as at,SecondaryCache as ct,Semaphore as pt,ServerToolFuncSchema as ht,ServerTools as lt,SignalGate as ut,StrangeHumanName as dt,StringTemplate as ft,TaskAbortController as vt,TemplateArgProcessor as yt,ToolAsyncCancelableBit as mt,ToolAsyncMultiTaskBit as St,ToolAsyncPriorityBit as wt,ToolFunc as Tt,ToolFuncSchema as Nt,WindowsReservedNameRegex as Et,YamlTypeBaseObject as $t,_lrucache as Ot,add as Ct,assignDirs as Jt,backendEventable as gt,base32768 as jt,beforeShutdown as Rt,calcPerplexity as Pt,calcPerplexitySimple as xt,canonicalize as qt,completeSentences as Ht,concatText as bt,countLLMTokens as Gt,countRegexMatches as It,createAbilityInjector as Lt,createCallbacksTransformer as Dt,createEmptyReadableStream as Ft,createEndWithRepetitionDetector as Mt,createError as _t,createEventStreamTransformer as kt,createHfValueFunc as At,createLRUCache as Bt,createYamlObjectTag as Vt,dateToText as Qt,decodeCharset as Ut,defaultTemplateFormat as zt,defaultsWithConcat as Kt,detectCharset as Wt,encodeLLMTokens as Xt,ensureQuoted as Yt,event as Zt,eventClient as te,eventServer as ee,eventable as re,expandConfig as se,expandEnv as oe,expandObjEnv as ne,expandPath as ie,expandPathInObject as ae,expandPaths as ce,extNameLevel as pe,fileIsExists as he,filterValidFnScope as le,findIndexNonEmptyFrom as ue,formatISO as de,formatTextWithSpace as fe,funcGetMeta as ve,funcWithMeta as ye,genUrlParamsStr as me,getAllEnumKeys as Se,getConfigFileNames as we,getConfigs as Te,getEnvVairables as Ne,getFileMetaInfo as Ee,getHashAlgoBySize as $e,getKeysPath as Oe,getLLMTokenizer as Ce,getMultiLevelExtname as Je,getPackageDir as ge,getRealFilepath as je,getResponseErrorReadableStream as Re,getXDGConfigs as Pe,hasDirectoryIn as xe,hash as qe,hashFile as He,hashObject as be,hashStream as Ge,initShutdown as Ie,isLangUsingSpaces as Le,isListItemString as De,isModelNameMatched as Fe,isPunctuationChar as Me,isQuoted as _e,isRegExp as ke,isSameString as Ae,isSectionString as Be,isSentenceEnding as Ve,isSepLineString as Qe,isStrWrapped as Ue,isSubdirectory as ze,isTitleString as Ke,isValidFilename as We,isValidFilepath as Xe,isWebStream as Ye,joinSplitWords as Ze,jsonFilterToWhere as tr,jsonToMarkdownStr as er,loadAIConfig as rr,loadConfig as sr,loadConfigFile as or,loadFileFromPaths as nr,loadTextFromPaths as ir,lrucache as ar,makeToolFuncCancelable as cr,matchUrlProtocol as pr,memoize as hr,mergeArray as lr,messagesToText as ur,mimeType as dr,normalizePath as fr,paramsSizeToScaleStr as vr,parse as yr,parseCommand as mr,parseDateFormat as Sr,parseISO as wr,parseJsJson as Tr,parseJsJsonSimpleSync as Nr,parseObjectArgInfo as Er,parseObjectArgumentInfos as $r,parseObjectArguments as Or,parseObjectArgumentsAsArgInfos as Cr,parseYaml as Jr,pruneSubdirectories as gr,pruneSubdirectoriesInPlace as jr,quoteStr as Rr,readFilenamesRecursiveSync as Pr,readTextFileChunks as xr,readTextFileChunksEx as qr,readableFromAsyncIterable as Hr,registerCoreTools as br,registerYamlTag as Gr,removeMarkdownBold as Ir,removeMarkdownBoldAndItalic as Lr,removeMarkdownItalic as Dr,replaceWithPlaceholder as Fr,restoreFromPlacehoders as Mr,sanitizeFilename as _r,sanitizeFilepath as kr,saveConfigFile as Ar,scaleStrToParamsSize as Br,shutdown as Vr,simplifyObjectArguments as Qr,sleep as Ur,sortedValues as zr,splitChunks as Kr,splitParagraph as Wr,splitSentence as Xr,splitWords as Yr,states as Zr,stringify as ts,stringifyYaml as es,stripConsoleColor as rs,textToDate as ss,throwError as os,toDate as ns,toDateTime as is,toRegExp as as,trimStartOfStreamHelper as cs,truncTo as ps,truncateByToken as hs,truncateToTokenLimit as ls,truncateToTokenLimitEx as us,uuid as ds,v1 as fs,v4 as vs,v5 as ys,validate as ms,version as Ss,wait as ws,wrapEventEmitter as Ts,xxhash as Ns,xxhash32 as Es,xxhash64 as $s,xxhashAsStr as Os,yieldExec as Cs}from"./chunk-LNTIQQNN.mjs";import{findPort as Js}from"./chunk-VIG2GB47.mjs";var gs=class{setApiRoot(t){this.apiRoot=t}mount(t,e,r){if(e)this.setApiRoot(e);else if(!(e=this.apiRoot))throw new Error("apiRoot is required");return this.Tools=t,this.options=r,this._mount(t,e,r)}},js=class extends gs{constructor(t){if(!t)throw new Error("apiRoot is required for HttpClientTransport");super(),this.setApiRoot(t)}async _mount(t,e,r){return t.setTransport(this),t.loadFrom()}async loadApis(){return this.fetch("",void 0,"get",void 0,{headers:{"Content-Type":"application/json"}})}async fetch(t,e,r,s,o){o={...this.options,...o};const n=await this._fetch(t,e,r,s,o);if(e?.stream)return n;return await this.toObject(n,e)}};import{defaultsDeep as Rs}from"lodash-es";var Ps=class extends gs{_mount(t,e,r){this.addDiscoveryHandler(e,()=>t),this.addRpcHandler(t,e,r)}start(t){return this.options&&(t=Rs(t,this.options)),this._start(t)}};import xs from"http";import{URL as qs}from"url";import{defaultsDeep as Hs}from"lodash-es";var bs=class extends Ps{constructor(t){super(),this.discoveryHandlerInfo=null,this.rpcHandlerInfo=null,this.server=t?xs.createServer(t,this.requestListener.bind(this)):xs.createServer(this.requestListener.bind(this))}async requestListener(t,e){const{url:r,method:s}=t;if(!r)return e.statusCode=400,e.setHeader("Content-Type","application/json"),void e.end(JSON.stringify({error:"Bad Request"}));if(this.discoveryHandlerInfo&&"GET"===s&&r===this.discoveryHandlerInfo.prefix)try{const t=this.discoveryHandlerInfo.handler();e.setHeader("Content-Type","application/json"),e.statusCode=200,e.end(JSON.stringify(t)),console.log(`[HttpServerTransport] Handled GET ${r} for discovery`)}catch(t){e.statusCode=500,e.setHeader("Content-Type","application/json"),e.end(JSON.stringify({error:t.message||"Internal Server Error"}))}else this.rpcHandlerInfo&&r.startsWith(this.rpcHandlerInfo.prefix)?await this.handleRpcRequest(t,e):(e.statusCode=404,e.setHeader("Content-Type","application/json"),e.end(JSON.stringify({error:"Not Found"})))}addDiscoveryHandler(t,e){this.discoveryHandlerInfo={prefix:t,handler:e},console.log(`[HttpServerTransport] Mapped GET ${t} for discovery`)}addRpcHandler(t,e,r){e.endsWith("/")||(e+="/"),this.rpcHandlerInfo={prefix:e,serverTools:t,options:r},console.log(`[HttpServerTransport] Mapped RPC calls for prefix ${e}`)}async handleRpcRequest(t,e){if(!this.rpcHandlerInfo||!t.url)return e.statusCode=500,e.setHeader("Content-Type","application/json"),void e.end(JSON.stringify({error:"RPC handler not configured"}));const{serverTools:r,prefix:s}=this.rpcHandlerInfo,o=t.url.split("?")[0].substring(s.length),[n,i]=o.split("/"),a=r.get(n);if(!a)return e.statusCode=404,e.setHeader("Content-Type","application/json"),void e.end(JSON.stringify({error:`${n} Not Found`,data:{what:n}}));let c;const p=t.method;try{if("GET"===p||"DELETE"===p){const e=new qs(t.url,`http://${t.headers.host}`).searchParams.get("p");c=e?JSON.parse(e):{}}else{const e=await this.getRequestBody(t);c=e?JSON.parse(e):{}}c._req=t,c._res=e,void 0!==i&&(c.id=i);let r=await a.run(c);a.isStream(c)?r&&"function"==typeof r.pipe?r.pipe(e):e.writableEnded||e.end():(e.setHeader("Content-Type","application/json"),e.statusCode=200,e.end(JSON.stringify(r)))}catch(t){if(console.error("Error during RPC execution:",t),e.headersSent)return;e.setHeader("Content-Type","application/json"),t.code&&"number"==typeof t.code?(e.statusCode=t.code,t.stack&&(t.stack=void 0),e.end(JSON.stringify(t))):(e.statusCode=500,e.end(JSON.stringify({error:t.message||"Internal Server Error"})))}}getRequestBody(t){return new Promise((e,r)=>{let s="";t.on("data",t=>{s+=t.toString()}),t.on("end",()=>{e(s)}),t.on("error",t=>{r(t)})})}async _start(t){const{port:e,host:r="0.0.0.0"}=Hs(t,{port:3e3});return new Promise((t,s)=>{this.server.on("error",t=>{console.error("[HttpServerTransport] Server error:",t),s(t)}),this.server.listen(e,r,()=>{const e=this.server.address(),r="string"==typeof e?e:`${e?.address}:${e?.port}`;console.log(`[HttpServerTransport] Server listening on ${r}`),t()})})}async stop(){return new Promise((t,e)=>{if(!this.server.listening)return t();this.server.close(r=>{if(r)return e(r);t()})})}getRaw(){return this.server}},Gs=class extends js{async loadApis(){const t=await fetch(this.apiRoot,{headers:{"Content-Type":"application/json"}});if(!t.ok)throw new Error(`Failed to load tools from ${this.apiRoot}: ${t.statusText}`);return await t.json()}async _fetch(t,e,r,s,o){const n=["post","put","patch"];let i;r||(r=this.Tools.action||"post"),"res"===r&&(r="get"),o.headers&&o.headers["Content-Type"]||!n.includes(r)||(o.headers={"Content-Type":"application/json",...o.headers}),e?.stream&&!o.headers.Connection&&(o.headers.Connection="keep-alive"),s?("string"!=typeof s&&(s=JSON.stringify(s)),t&&(s=t+"/"+s)):s=t,o.method=r.toUpperCase(),"get"===r||"delete"===r?i=s+me(e):(o.body=JSON.stringify(e),i=s),o.headers&&!n.includes(r)&&delete o.headers["Content-Type"];const a=await fetch(`${this.apiRoot}/${i}`,o);if(!a.ok){throw await this.errorFrom(t,a)}return a}async errorFrom(t,e){let r,s=e.status,o=e.statusText;if(e.body){const s=await e.text();try{const e=JSON.parse(s);e&&(e.error&&(o=e.error),e.name&&(t=e.name),e.data&&(r=e.data,r.name=t,r.what&&(r.msg=o,o=r.what)),e.message&&(o=o+":"+e.message))}catch(t){console.warn("🚀 ~ parse error body to json:",t)}}return _t(o,t,s)}async toObject(t,e){return await t.json()}},Is=class{constructor(){this.name="sse",this.protocol="sse",this.channel=new it}mount(){}subscribe(t,e){const{req:r,res:s,clientId:o}=e??{};if(!r||!s)throw new Error("SSE subscribe requires options.req and options.res");const n=this.channel.subscribe(r,s,t,o),i={id:`${Date.now()}-${Math.random().toString(36).slice(2)}`,clientId:n.clientId,protocol:"sse",send:(t,e)=>{s.write(`event: ${t}\n`),s.write(`data: ${JSON.stringify(e)}\n\n`)},close:()=>s.end?.(),raw:s};return this.onConn?.(i),r.on("close",()=>this.onDis?.(i)),n}publish(t,e,r){this.channel.publish(e,t,r)}onConnection(t){this.onConn=t}onDisconnect(t){this.onDis=t}},Ls=class{connect(t,e){const r=e?`?${new URLSearchParams(e).toString()}`:"",s=new EventSource(`${t}${r}`),o=new Map,n=(t,e)=>{const r=r=>{const s=r.data,o=s?"string"==typeof s?JSON.parse(s):s:void 0;e(o,{...r,event:t})};let n=o.get(t);n||(n=new Map,o.set(t,n)),n.set(e,r),s.addEventListener(t,r)},i=(t,e)=>{const r=o.get(t),n=r?.get(e);n&&(s.removeEventListener(t,n),r.delete(e))};return{protocol:"sse",get readyState(){return s.readyState},on:n,off:i,addEventListener:n,removeEventListener:i,close:()=>s.close()}}disconnect(t){return t.close()}};export{t as AIArgProcessor,e as AIChatRoles,r as AIMessageTypes,s as AIStream,o as AITextGenerationFinishReasons,n as AbortError,i as AbortErrorCode,a as ActionNames,c as AlreadyExistsError,p as AlreadyExistsErrorCode,h as ArrayMergeWay,l as ArrayMergeWaySymbol,u as AsyncFeatureBits,d as AsyncFeatures,f as BaseError,v as BinarySemaphore,y as CancelableAbility,m as ChoiceArgProcessor,S as ClientToolFuncSchema,js as ClientToolTransport,w as ClientTools,T as CommonError,N as ConfigFile,E as DEFAULT_CONFIG_NAME,$ as DefaultAsyncSemaphoreCapacity,O as DefaultDateFormat,C as EnvPromptTemplate,J as ErrorCode,g as EventBusName,j as EventClient,R as EventEmitter,P as EventName,x as EventServer,Zr as EventStates,q as EventToolFunc,H as FStringPromptTemplate,b as FewShotPromptTemplate,G as FilenameReservedRegex,I as FuncMetaSymbol,L as GolangPromptTemplate,D as HashAlgorithm,Gs as HttpClientToolTransport,bs as HttpServerToolTransport,F as IntSet,M as InternalErrorCode,_ as LLM_TOKENIZER_NAMES,k as LLM_TOKENIZER_NAMES_MAP,A as LRUCache,V as NotFoundError,Q as NotFoundErrorCode,U as NotImplementationError,z as NotImplementedErrorCode,K as ObjectArgsToArgsInfo,W as PASSING_SCORE,X as PromptExampleSelector,ft as PromptTemplate,Y as RStreamErrCode,Z as RateLimit,tt as ReadableStreamError,et as RemoteToolFuncSchema,rt as ResClientTools,st as ResServerTools,ot as ResponseRStreamErrCode,nt as SHUTDOWN_SIGNALS,it as SSEChannel,at as SSEChannelAlreadyClosedErrCode,ct as SecondaryCache,pt as Semaphore,ht as ServerToolFuncSchema,Ps as ServerToolTransport,lt as ServerTools,ut as SignalGate,Ls as SseClientPubSubTransport,Is as SseServerPubSubTransport,dt as StrangeHumanName,vt as TaskAbortController,yt as TemplateArgProcessor,mt as ToolAsyncCancelableBit,St as ToolAsyncMultiTaskBit,wt as ToolAsyncPriorityBit,Tt as ToolFunc,Nt as ToolFuncSchema,gs as ToolTransport,Et as WindowsReservedNameRegex,$t as YamlTypeBaseObject,Ot as _lrucache,Ct as addDate,Jt as assignDirs,gt as backendEventable,jt as base32768,Rt as beforeShutdown,Pt as calcPerplexity,xt as calcPerplexitySimple,qt as canonicalize,Ht as completeSentences,bt as concatText,Gt as countLLMTokens,It as countRegexMatches,Lt as createAbilityInjector,Dt as createCallbacksTransformer,Ft as createEmptyReadableStream,Mt as createEndWithRepetitionDetector,_t as createError,kt as createEventStreamTransformer,At as createHfValueFunc,Bt as createLRUCache,Vt as createYamlObjectTag,Qt as dateToText,Ut as decodeCharset,zt as defaultTemplateFormat,Kt as defaultsWithConcat,Wt as detectCharset,Xt as encodeLLMTokens,Yt as ensureQuoted,Zt as event,te as eventClient,ee as eventServer,re as eventable,se as expandConfig,oe as expandEnv,ne as expandObjEnv,ie as expandPath,ae as expandPathInObject,ce as expandPaths,pe as extNameLevel,he as fileIsExists,le as filterValidFnScope,ue as findIndexNonEmptyFrom,Js as findPort,de as formatISO,fe as formatTextWithSpace,ve as funcGetMeta,ye as funcWithMeta,me as genUrlParamsStr,Se as getAllEnumKeys,we as getConfigFileNames,Te as getConfigs,Ne as getEnvVairables,Ee as getFileMetaInfo,$e as getHashAlgoBySize,Oe as getKeysPath,Ce as getLLMTokenizer,Je as getMultiLevelExtname,ge as getPackageDir,je as getRealFilepath,Re as getResponseErrorReadableStream,Pe as getXDGConfigs,xe as hasDirectoryIn,qe as hash,He as hashFile,be as hashObject,Ge as hashStream,Ie as initShutdown,Le as isLangUsingSpaces,De as isListItemString,Fe as isModelNameMatched,Me as isPunctuationChar,_e as isQuoted,ke as isRegExp,Ae as isSameString,Be as isSectionString,Ve as isSentenceEnding,Qe as isSepLineString,Ue as isStrWrapped,ze as isSubdirectory,Ke as isTitleString,We as isValidFilename,Xe as isValidFilepath,Ye as isWebStream,Ze as joinSplitWords,tr as jsonFilterToWhere,er as jsonToMarkdownStr,rr as loadAIConfig,sr as loadConfig,or as loadConfigFile,nr as loadFileFromPaths,ir as loadTextFromPaths,ar as lrucache,cr as makeToolFuncCancelable,pr as matchUrlProtocol,hr as memoize,lr as mergeArray,ur as messagesToText,dr as mimeType,fr as normalizePath,vr as paramsSizeToScaleStr,mr as parseCommand,Sr as parseDateFormat,wr as parseISO,Tr as parseJsJson,Nr as parseJsJsonSimpleSync,Er as parseObjectArgInfo,$r as parseObjectArgumentInfos,Or as parseObjectArguments,Cr as parseObjectArgumentsAsArgInfos,Jr as parseYaml,gr as pruneSubdirectories,jr as pruneSubdirectoriesInPlace,Rr as quoteStr,Pr as readFilenamesRecursiveSync,xr as readTextFileChunks,qr as readTextFileChunksEx,Hr as readableFromAsyncIterable,br as registerCoreTools,Gr as registerYamlTag,Ir as removeMarkdownBold,Lr as removeMarkdownBoldAndItalic,Dr as removeMarkdownItalic,Fr as replaceWithPlaceholder,Mr as restoreFromPlacehoders,_r as sanitizeFilename,kr as sanitizeFilepath,Ar as saveConfigFile,Br as scaleStrToParamsSize,Vr as shutdown,Qr as simplifyObjectArguments,Ur as sleep,zr as sortedValues,Kr as splitChunks,Wr as splitParagraph,Xr as splitSentence,Yr as splitWords,es as stringifyYaml,rs as stripConsoleColor,ss as textToDate,os as throwError,ns as toDate,is as toDateTime,as as toRegExp,cs as trimStartOfStreamHelper,ps as truncTo,hs as truncateByToken,ls as truncateToTokenLimit,us as truncateToTokenLimitEx,ds as uuid,B as uuidNIL,yr as uuidParse,ts as uuidStringify,ms as uuidValidate,Ss as uuidVersion,fs as uuidv1,vs as uuidv4,ys as uuidv5,ws as wait,Ts as wrapEventEmitter,Ns as xxhash,Es as xxhash32,$s as xxhash64,Os as xxhashAsStr,Cs as yieldExec};
package/dist/test/util.js CHANGED
@@ -1 +1 @@
1
- "use strict";var e,r=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,u=Object.getOwnPropertyNames,o=Object.getPrototypeOf,c=Object.prototype.hasOwnProperty,i=(e,r,o,i)=>{if(r&&"object"==typeof r||"function"==typeof r)for(let f of u(r))c.call(e,f)||f===o||t(e,f,{get:()=>r[f],enumerable:!(i=n(r,f))||i.enumerable});return e},f={};function a(e,r){expect(e.length).toBeGreaterThanOrEqual(r.length);for(let t=0;t<r.length;t++)if(e[t]!==r[t])return!1;return!0}((e,r)=>{for(var n in r)t(e,n,{get:r[n],enumerable:!0})})(f,{compareStr:()=>a,findPort:()=>s,rmFile:()=>m}),module.exports=(e=f,i(t({},"__esModule",{value:!0}),e));var l=((e,n,u)=>(u=null!=e?r(o(e)):{},i(!n&&e&&e.__esModule?u:t(u,"default",{value:e,enumerable:!0}),e)))(require("net"));async function s(e,r=10){return new Promise(((t,n)=>{void 0===e?e=0:("string"==typeof e&&(e=parseInt(e)),e>=0||(e=0));const u=l.default.createServer();u.on("error",(t=>{"EADDRINUSE"===t.code&&(e++,--r>0)?u.listen(e):n(t)})),u.on("listening",(async()=>{const e=u.address().port;u.close(),t(e)})),u.listen(e)}))}var b=require("fs");function m(e){(0,b.existsSync)(e)&&(0,b.rmSync)(e,{recursive:!0}),(0,b.existsSync)(e+".temp")&&(0,b.rmSync)(e+".temp",{recursive:!0})}
1
+ "use strict";var e,r=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,u=Object.getOwnPropertyNames,o=Object.getPrototypeOf,c=Object.prototype.hasOwnProperty,i=(e,r,o,i)=>{if(r&&"object"==typeof r||"function"==typeof r)for(let f of u(r))c.call(e,f)||f===o||t(e,f,{get:()=>r[f],enumerable:!(i=n(r,f))||i.enumerable});return e},f={};function a(e,r){expect(e.length).toBeGreaterThanOrEqual(r.length);for(let t=0;t<r.length;t++)if(e[t]!==r[t])return!1;return!0}((e,r)=>{for(var n in r)t(e,n,{get:r[n],enumerable:!0})})(f,{compareStr:()=>a,findPort:()=>s,rmFile:()=>m}),module.exports=(e=f,i(t({},"__esModule",{value:!0}),e));var l=((e,n,u)=>(u=null!=e?r(o(e)):{},i(!n&&e&&e.__esModule?u:t(u,"default",{value:e,enumerable:!0}),e)))(require("net"));async function s(e,r=10){return new Promise((t,n)=>{void 0===e?e=0:("string"==typeof e&&(e=parseInt(e)),e>=0||(e=0));const u=l.default.createServer();u.on("error",t=>{"EADDRINUSE"===t.code&&(e++,--r>0)?u.listen(e):n(t)}),u.on("listening",async()=>{const e=u.address().port;u.close(),t(e)}),u.listen(e)})}var b=require("fs");function m(e){(0,b.existsSync)(e)&&(0,b.rmSync)(e,{recursive:!0}),(0,b.existsSync)(e+".temp")&&(0,b.rmSync)(e+".temp",{recursive:!0})}