@isdk/ai-tool 0.8.2 → 0.9.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 (405) hide show
  1. package/dist/chunk-BIJ2JH4U.mjs +1 -0
  2. package/dist/chunk-OYMVHUDZ.mjs +1 -0
  3. package/dist/funcs.d.mts +16 -5
  4. package/dist/funcs.d.ts +16 -5
  5. package/dist/funcs.js +1 -1
  6. package/dist/funcs.mjs +1 -1
  7. package/dist/index.d.mts +839 -563
  8. package/dist/index.d.ts +839 -563
  9. package/dist/index.js +1 -1
  10. package/dist/index.mjs +1 -1
  11. package/dist/test/util.d.mts +1 -1
  12. package/dist/test/util.d.ts +1 -1
  13. package/dist/test/util.js +1 -1
  14. package/dist/test/util.mjs +1 -1
  15. package/docs/api/@isdk/namespaces/ClientTools/README.md +11 -0
  16. package/docs/api/@isdk/namespaces/ClientTools/functions/get.md +27 -0
  17. package/docs/api/@isdk/namespaces/EventStates/variables/ABORT.md +1 -1
  18. package/docs/api/@isdk/namespaces/EventStates/variables/CONTINUE.md +1 -1
  19. package/docs/api/@isdk/namespaces/EventStates/variables/DONE.md +1 -1
  20. package/docs/api/@isdk/namespaces/EventStates/variables/STOPPED.md +1 -1
  21. package/docs/api/classes/BinarySemaphore.md +148 -67
  22. package/docs/api/classes/CancelableAbility.md +95 -43
  23. package/docs/api/classes/ClientToolTransport.md +31 -16
  24. package/docs/api/classes/ClientTools.md +868 -158
  25. package/docs/api/classes/CmdArgLexer.md +82 -0
  26. package/docs/api/classes/CmdArgParser.md +56 -0
  27. package/docs/api/classes/ConfigFile.md +6 -6
  28. package/docs/api/classes/EnvPromptTemplate.md +224 -52
  29. package/docs/api/classes/EventClient.md +902 -192
  30. package/docs/api/classes/EventEmitter.md +62 -12
  31. package/docs/api/classes/EventServer.md +895 -182
  32. package/docs/api/classes/EventToolFunc.md +801 -123
  33. package/docs/api/classes/FStringPromptTemplate.md +224 -52
  34. package/docs/api/classes/FewShotPromptTemplate.md +231 -59
  35. package/docs/api/classes/GolangPromptTemplate.md +224 -52
  36. package/docs/api/classes/HttpClientToolTransport.md +33 -19
  37. package/docs/api/classes/HttpServerToolTransport.md +15 -15
  38. package/docs/api/classes/IntSet.md +21 -21
  39. package/docs/api/classes/MailboxClientTransport.md +398 -0
  40. package/docs/api/classes/MailboxServerTransport.md +433 -0
  41. package/docs/api/classes/PromptExampleSelector.md +11 -11
  42. package/docs/api/classes/PromptTemplate.md +199 -51
  43. package/docs/api/classes/ReadableStreamError.md +2 -2
  44. package/docs/api/classes/ResClientTools.md +875 -165
  45. package/docs/api/classes/ResServerTools.md +869 -156
  46. package/docs/api/classes/RpcMethodsClientTool.md +870 -160
  47. package/docs/api/classes/RpcMethodsServerTool.md +865 -152
  48. package/docs/api/classes/SSEChannel.md +23 -23
  49. package/docs/api/classes/Semaphore.md +148 -76
  50. package/docs/api/classes/ServerToolTransport.md +14 -13
  51. package/docs/api/classes/ServerTools.md +854 -138
  52. package/docs/api/classes/SignalGate.md +12 -12
  53. package/docs/api/classes/SseClientPubSubTransport.md +4 -4
  54. package/docs/api/classes/SseServerPubSubTransport.md +13 -13
  55. package/docs/api/classes/TaskAbortController.md +33 -11
  56. package/docs/api/classes/ToolFunc.md +725 -119
  57. package/docs/api/classes/ToolTransport.md +7 -7
  58. package/docs/api/classes/YamlTypeBaseObject.md +2 -2
  59. package/docs/api/enumerations/AsyncFeatureBits.md +4 -4
  60. package/docs/api/enumerations/AsyncFeatures.md +4 -4
  61. package/docs/api/enumerations/CmdArgTokenType.md +129 -0
  62. package/docs/api/enumerations/HashAlgorithm.md +38 -12
  63. package/docs/api/functions/AIArgProcessor.md +8 -17
  64. package/docs/api/functions/AIStream.md +1 -1
  65. package/docs/api/functions/ChoiceArgProcessor.md +13 -15
  66. package/docs/api/functions/DefaultDateFormat.md +1 -1
  67. package/docs/api/functions/ObjectArgsToArgsInfo.md +11 -9
  68. package/docs/api/functions/RateLimit.md +33 -6
  69. package/docs/api/functions/TemplateArgProcessor.md +13 -15
  70. package/docs/api/functions/assignDirs.md +1 -1
  71. package/docs/api/functions/beforeShutdown.md +3 -3
  72. package/docs/api/functions/calcPerplexity.md +3 -3
  73. package/docs/api/functions/calcPerplexitySimple.md +3 -3
  74. package/docs/api/functions/cmdArgEvaluate.md +28 -0
  75. package/docs/api/functions/cmdArgsToMergedObject.md +34 -0
  76. package/docs/api/functions/completeSentences.md +1 -1
  77. package/docs/api/functions/concatText.md +1 -1
  78. package/docs/api/functions/countLLMTokens.md +1 -1
  79. package/docs/api/functions/countRegexMatches.md +1 -1
  80. package/docs/api/functions/createCallbacksTransformer.md +23 -19
  81. package/docs/api/functions/createEmptyReadableStream.md +1 -1
  82. package/docs/api/functions/createEndWithRepetitionDetector.md +4 -4
  83. package/docs/api/functions/createEventStreamTransformer.md +1 -1
  84. package/docs/api/functions/createHfValueFunc.md +1 -1
  85. package/docs/api/functions/createLRUCache.md +1 -1
  86. package/docs/api/functions/createYamlObjectTag.md +1 -1
  87. package/docs/api/functions/dateToText.md +1 -1
  88. package/docs/api/functions/decodeCharset.md +1 -1
  89. package/docs/api/functions/defaultsWithConcat.md +1 -1
  90. package/docs/api/functions/detectCharset.md +1 -1
  91. package/docs/api/functions/encodeLLMTokens.md +1 -1
  92. package/docs/api/functions/ensureQuoted.md +3 -1
  93. package/docs/api/functions/evaluateExpression.md +40 -0
  94. package/docs/api/functions/eventable.md +1 -1
  95. package/docs/api/functions/expandConfig.md +1 -1
  96. package/docs/api/functions/expandEnv.md +1 -1
  97. package/docs/api/functions/expandObjEnv.md +1 -1
  98. package/docs/api/functions/expandPath.md +1 -1
  99. package/docs/api/functions/expandPathInObject.md +1 -1
  100. package/docs/api/functions/expandPaths.md +1 -1
  101. package/docs/api/functions/extNameLevel.md +1 -1
  102. package/docs/api/functions/extractCodeBlock.md +51 -0
  103. package/docs/api/functions/fileIsExists.md +3 -3
  104. package/docs/api/functions/filterValidFnScope.md +3 -3
  105. package/docs/api/functions/findIndexNonEmptyFrom.md +1 -1
  106. package/docs/api/functions/findPort.md +13 -5
  107. package/docs/api/functions/formatTextWithSpace.md +1 -1
  108. package/docs/api/functions/funcGetMeta.md +1 -1
  109. package/docs/api/functions/funcWithMeta.md +4 -4
  110. package/docs/api/functions/genUrlParamsStr.md +1 -1
  111. package/docs/api/functions/getAllEnumKeys.md +1 -1
  112. package/docs/api/functions/getConfigFileNames.md +1 -1
  113. package/docs/api/functions/getConfigs.md +1 -1
  114. package/docs/api/functions/getEnvVairables.md +1 -1
  115. package/docs/api/functions/getFileMetaInfo.md +1 -1
  116. package/docs/api/functions/getHashAlgoBySize.md +1 -1
  117. package/docs/api/functions/getKeysPath.md +1 -1
  118. package/docs/api/functions/getLLMTokenizer.md +1 -1
  119. package/docs/api/functions/getMultiLevelExtname.md +1 -1
  120. package/docs/api/functions/getPackageDir.md +1 -1
  121. package/docs/api/functions/getRealFilepath.md +1 -1
  122. package/docs/api/functions/getResponseErrorReadableStream.md +2 -2
  123. package/docs/api/functions/getXDGConfigs.md +1 -1
  124. package/docs/api/functions/hasDirectoryIn.md +3 -3
  125. package/docs/api/functions/hash.md +25 -4
  126. package/docs/api/functions/hashFile.md +1 -1
  127. package/docs/api/functions/hashObject.md +23 -1
  128. package/docs/api/functions/hashStream.md +25 -4
  129. package/docs/api/functions/initShutdown.md +1 -1
  130. package/docs/api/functions/isIdentifier.md +30 -0
  131. package/docs/api/functions/isLangUsingSpaces.md +1 -1
  132. package/docs/api/functions/isListItemString.md +3 -3
  133. package/docs/api/functions/isModelNameMatched.md +3 -3
  134. package/docs/api/functions/isPathIdentifier.md +23 -0
  135. package/docs/api/functions/isPunctuationChar.md +1 -1
  136. package/docs/api/functions/isQuoted.md +4 -1
  137. package/docs/api/functions/isRegExp.md +20 -1
  138. package/docs/api/functions/isSameString.md +1 -1
  139. package/docs/api/functions/isSectionString.md +3 -3
  140. package/docs/api/functions/isSentenceEnding.md +1 -1
  141. package/docs/api/functions/isSepLineString.md +3 -3
  142. package/docs/api/functions/isStrWrapped.md +3 -1
  143. package/docs/api/functions/isSubdirectory.md +1 -1
  144. package/docs/api/functions/isTitleString.md +3 -3
  145. package/docs/api/functions/isValidFilename.md +1 -1
  146. package/docs/api/functions/isValidFilepath.md +1 -1
  147. package/docs/api/functions/isWebStream.md +1 -1
  148. package/docs/api/functions/joinSplitWords.md +1 -1
  149. package/docs/api/functions/jsonFilterToWhere.md +1 -1
  150. package/docs/api/functions/jsonToMarkdownStr.md +1 -1
  151. package/docs/api/functions/loadAIConfig.md +1 -1
  152. package/docs/api/functions/loadConfig.md +1 -1
  153. package/docs/api/functions/loadConfigFile.md +1 -1
  154. package/docs/api/functions/loadFileFromPaths.md +1 -1
  155. package/docs/api/functions/loadTextFromPaths.md +1 -1
  156. package/docs/api/functions/lrucache.md +1 -1
  157. package/docs/api/functions/matchUrlProtocol.md +3 -3
  158. package/docs/api/functions/memoize.md +1 -1
  159. package/docs/api/functions/mergeArray.md +1 -1
  160. package/docs/api/functions/messagesToText.md +1 -1
  161. package/docs/api/functions/normalizePath.md +1 -1
  162. package/docs/api/functions/paramsSizeToScaleStr.md +1 -1
  163. package/docs/api/functions/parseCommand.md +21 -4
  164. package/docs/api/functions/parseJsJson.md +1 -1
  165. package/docs/api/functions/parseJsJsonSimpleSync.md +1 -1
  166. package/docs/api/functions/parseObjectArguments.md +17 -33
  167. package/docs/api/functions/parseYaml.md +1 -1
  168. package/docs/api/functions/prependNewlineIfMultiline.md +39 -0
  169. package/docs/api/functions/pruneSubdirectories.md +1 -1
  170. package/docs/api/functions/pruneSubdirectoriesInPlace.md +1 -1
  171. package/docs/api/functions/quoteStr.md +4 -1
  172. package/docs/api/functions/readFilenamesRecursiveSync.md +1 -1
  173. package/docs/api/functions/readTextFileChunks.md +1 -1
  174. package/docs/api/functions/readTextFileChunksEx.md +1 -1
  175. package/docs/api/functions/readableFromAsyncIterable.md +1 -1
  176. package/docs/api/functions/registerCoreTools.md +1 -1
  177. package/docs/api/functions/registerYamlTag.md +2 -2
  178. package/docs/api/functions/removeMarkdownBold.md +1 -1
  179. package/docs/api/functions/removeMarkdownBoldAndItalic.md +1 -1
  180. package/docs/api/functions/removeMarkdownItalic.md +1 -1
  181. package/docs/api/functions/replaceWithPlaceholder.md +3 -18
  182. package/docs/api/functions/restoreFromPlacehoders.md +2 -20
  183. package/docs/api/functions/sanitizeFilename.md +1 -1
  184. package/docs/api/functions/sanitizeFilepath.md +1 -1
  185. package/docs/api/functions/saveConfigFile.md +1 -1
  186. package/docs/api/functions/scaleStrToParamsSize.md +1 -1
  187. package/docs/api/functions/shutdown.md +2 -2
  188. package/docs/api/functions/simplifyObjectArguments.md +4 -1
  189. package/docs/api/functions/simplifyResult.md +34 -0
  190. package/docs/api/functions/sleep.md +1 -1
  191. package/docs/api/functions/sortedValues.md +1 -1
  192. package/docs/api/functions/splitChunks.md +1 -1
  193. package/docs/api/functions/splitParagraph.md +1 -1
  194. package/docs/api/functions/splitSentence.md +1 -1
  195. package/docs/api/functions/splitWords.md +1 -1
  196. package/docs/api/functions/stringifyYaml.md +1 -1
  197. package/docs/api/functions/stripConsoleColor.md +1 -1
  198. package/docs/api/functions/textToDate.md +1 -1
  199. package/docs/api/functions/textify.md +43 -0
  200. package/docs/api/functions/toDateTime.md +3 -3
  201. package/docs/api/functions/toRegExp.md +1 -1
  202. package/docs/api/functions/trimStartOfStreamHelper.md +1 -1
  203. package/docs/api/functions/truncTo.md +1 -1
  204. package/docs/api/functions/truncateByToken.md +1 -1
  205. package/docs/api/functions/truncateToTokenLimit.md +1 -1
  206. package/docs/api/functions/truncateToTokenLimitEx.md +1 -1
  207. package/docs/api/functions/uuid.md +1 -1
  208. package/docs/api/functions/wrapEventEmitter.md +1 -1
  209. package/docs/api/functions/wrapFlagValue.md +29 -0
  210. package/docs/api/functions/xxhash.md +27 -6
  211. package/docs/api/functions/xxhash32.md +22 -4
  212. package/docs/api/functions/xxhash64.md +22 -4
  213. package/docs/api/functions/xxhashAsStr.md +27 -6
  214. package/docs/api/functions/yieldExec.md +1 -1
  215. package/docs/api/globals.md +51 -18
  216. package/docs/api/interfaces/AIChatAssistantMessageParam.md +14 -14
  217. package/docs/api/interfaces/AIChatContentPartBase.md +26 -0
  218. package/docs/api/interfaces/AIChatContentPartImage.md +15 -3
  219. package/docs/api/interfaces/AIChatContentPartText.md +15 -3
  220. package/docs/api/interfaces/AIChatMessageParamBase.md +9 -9
  221. package/docs/api/interfaces/AIChatMessageToolCall.md +12 -8
  222. package/docs/api/interfaces/AIChatSystemMessageParam.md +10 -10
  223. package/docs/api/interfaces/AIChatToolChoiceFuncObject.md +3 -3
  224. package/docs/api/interfaces/AIChatToolChoiceObject.md +2 -2
  225. package/docs/api/interfaces/AIChatToolDefinition.md +45 -0
  226. package/docs/api/interfaces/AIChatToolFunc.md +5 -5
  227. package/docs/api/interfaces/AIChatToolFuncParam.md +3 -3
  228. package/docs/api/interfaces/AIChatToolMessageParam.md +13 -13
  229. package/docs/api/interfaces/AIChatToolParam.md +2 -2
  230. package/docs/api/interfaces/AIChatToolTypeObject.md +2 -2
  231. package/docs/api/interfaces/AIChatUserMessageParam.md +14 -14
  232. package/docs/api/interfaces/AIResult.md +7 -7
  233. package/docs/api/interfaces/AIStreamParser.md +2 -2
  234. package/docs/api/interfaces/AIStreamParserOptions.md +2 -2
  235. package/docs/api/interfaces/BaseFunc.md +15 -15
  236. package/docs/api/interfaces/BaseFuncItem.md +16 -16
  237. package/docs/api/interfaces/BinarySemaphoreAcquireOptions.md +9 -2
  238. package/docs/api/interfaces/BinarySemaphoreOptions.md +22 -5
  239. package/docs/api/interfaces/BinarySemaphoreReleaseOptions.md +7 -5
  240. package/docs/api/interfaces/CancelableAbilityOptions.md +4 -4
  241. package/docs/api/interfaces/ClientFuncItem.md +70 -19
  242. package/docs/api/interfaces/CmdArgAIChoiceConfig.md +97 -0
  243. package/docs/api/interfaces/CmdArgArgsInfo.md +31 -0
  244. package/docs/api/interfaces/CmdArgContext.md +103 -0
  245. package/docs/api/interfaces/CmdArgFlagMetadata.md +21 -0
  246. package/docs/api/interfaces/CmdArgMapResult.md +41 -0
  247. package/docs/api/interfaces/CmdArgParseResult.md +51 -0
  248. package/docs/api/interfaces/CmdArgParsedCommand.md +41 -0
  249. package/docs/api/interfaces/CmdArgParserOptions.md +225 -0
  250. package/docs/api/interfaces/CmdArgProcessorResultOptions.md +22 -0
  251. package/docs/api/interfaces/CmdArgSimplifyOptions.md +101 -0
  252. package/docs/api/interfaces/CmdArgToken.md +51 -0
  253. package/docs/api/interfaces/EventClientFuncParams.md +5 -5
  254. package/docs/api/interfaces/EventServerFuncParams.md +21 -7
  255. package/docs/api/interfaces/FewShotPromptTemplateOptions.md +18 -6
  256. package/docs/api/interfaces/FuncItem.md +19 -15
  257. package/docs/api/interfaces/FuncParam.md +5 -5
  258. package/docs/api/interfaces/FuncParams.md +1 -1
  259. package/docs/api/interfaces/Funcs.md +1 -1
  260. package/docs/api/interfaces/HashAlgoParams.md +36 -5
  261. package/docs/api/interfaces/IClientToolTransport.md +24 -10
  262. package/docs/api/interfaces/IFileMetaInfo.md +8 -8
  263. package/docs/api/interfaces/IPubSubClientTransport.md +4 -4
  264. package/docs/api/interfaces/IPubSubServerTransport.md +14 -14
  265. package/docs/api/interfaces/IReadTextFileChunksOptions.md +11 -11
  266. package/docs/api/interfaces/IServerToolTransport.md +8 -8
  267. package/docs/api/interfaces/IToolTransport.md +5 -5
  268. package/docs/api/interfaces/ITruncateToTokenLimitOptions.md +10 -10
  269. package/docs/api/interfaces/JsonFilter.md +1 -1
  270. package/docs/api/interfaces/MailboxClientOptions.md +74 -0
  271. package/docs/api/interfaces/MailboxServerOptions.md +69 -0
  272. package/docs/api/interfaces/ProbabilityItem.md +4 -4
  273. package/docs/api/interfaces/PromptExampleSelectorOptions.md +3 -3
  274. package/docs/api/interfaces/PromptTemplateOptions.md +8 -0
  275. package/docs/api/interfaces/PubSubClientStream.md +11 -11
  276. package/docs/api/interfaces/PubSubServerSession.md +8 -8
  277. package/docs/api/interfaces/RegisterOptions.md +298 -0
  278. package/docs/api/interfaces/RemoteFuncItem.md +63 -20
  279. package/docs/api/interfaces/ReplacePlacehoderOptions.md +5 -5
  280. package/docs/api/interfaces/ResClientFuncParams.md +3 -3
  281. package/docs/api/interfaces/ResServerFuncParams.md +20 -6
  282. package/docs/api/interfaces/RpcMethodsClientFuncParams.md +2 -2
  283. package/docs/api/interfaces/RpcMethodsServerFuncParams.md +18 -4
  284. package/docs/api/interfaces/SanitizeFilenameOptions.md +3 -3
  285. package/docs/api/interfaces/SectionStringOptions.md +3 -3
  286. package/docs/api/interfaces/SemaphoreOptions.md +30 -7
  287. package/docs/api/interfaces/SemaphoreTaskItem.md +18 -5
  288. package/docs/api/interfaces/ServerFuncItem.md +71 -20
  289. package/docs/api/interfaces/ServerFuncParams.md +14 -4
  290. package/docs/api/interfaces/SplitSentenceOptions.md +5 -5
  291. package/docs/api/interfaces/StreamCallbacksAndOptions.md +80 -7
  292. package/docs/api/interfaces/TaskAbortControllers.md +2 -2
  293. package/docs/api/interfaces/TaskPromise.md +6 -6
  294. package/docs/api/interfaces/TextifyInlineOptions.md +51 -0
  295. package/docs/api/interfaces/TextifyOptions.md +108 -0
  296. package/docs/api/interfaces/ToolFuncContext.md +73 -0
  297. package/docs/api/interfaces/ToolFuncPackage.md +4 -4
  298. package/docs/api/interfaces/ToolFuncRegistryIsolateOptions.md +41 -0
  299. package/docs/api/interfaces/UnregisterOptions.md +56 -0
  300. package/docs/api/type-aliases/AIChatContentPart.md +2 -2
  301. package/docs/api/type-aliases/AIChatMessageParam.md +1 -1
  302. package/docs/api/type-aliases/AIChatRole.md +2 -2
  303. package/docs/api/type-aliases/AIChatTemplateCaps.md +239 -0
  304. package/docs/api/type-aliases/AIChatToolChoiceParam.md +1 -1
  305. package/docs/api/type-aliases/AIMessageType.md +1 -1
  306. package/docs/api/type-aliases/AIModelNameRule.md +1 -1
  307. package/docs/api/type-aliases/AIModelNameRuleFn.md +1 -1
  308. package/docs/api/type-aliases/AIModelNameRules.md +1 -1
  309. package/docs/api/type-aliases/AITextGenerationFinishReason.md +1 -1
  310. package/docs/api/type-aliases/ActionName.md +1 -1
  311. package/docs/api/type-aliases/ArgProcessor.md +24 -0
  312. package/docs/api/type-aliases/ArrayMergeWay.md +1 -1
  313. package/docs/api/type-aliases/AsyncTaskId.md +1 -1
  314. package/docs/api/type-aliases/BeforeShutdownListener.md +1 -1
  315. package/docs/api/type-aliases/CmdArgFlagValue.md +14 -0
  316. package/docs/api/type-aliases/CmdArgFlagsRecord.md +13 -0
  317. package/docs/api/type-aliases/EventErrorListenerFn.md +1 -1
  318. package/docs/api/type-aliases/EventListenerFn.md +1 -1
  319. package/docs/api/type-aliases/FuncParamType.md +1 -1
  320. package/docs/api/type-aliases/PromptExamples.md +1 -1
  321. package/docs/api/type-aliases/PubSubClientId.md +1 -1
  322. package/docs/api/type-aliases/PubSubCtx.md +6 -6
  323. package/docs/api/type-aliases/RpcMethodHandler.md +1 -1
  324. package/docs/api/type-aliases/SSEClient.md +5 -5
  325. package/docs/api/type-aliases/SemaphoreIsReadyFuncType.md +4 -1
  326. package/docs/api/type-aliases/SimplifiedResultType.md +14 -0
  327. package/docs/api/type-aliases/StreamCloseStatus.md +16 -0
  328. package/docs/api/type-aliases/TFunc.md +1 -1
  329. package/docs/api/type-aliases/TextifyInlineStyleMode.md +16 -0
  330. package/docs/api/type-aliases/TextifyStringQuoting.md +16 -0
  331. package/docs/api/type-aliases/UUIDVersions.md +3 -1
  332. package/docs/api/variables/AIChatRoles.md +2 -2
  333. package/docs/api/variables/AIMessageTypes.md +1 -1
  334. package/docs/api/variables/AITextGenerationFinishReasons.md +1 -1
  335. package/docs/api/variables/ActionNames.md +1 -1
  336. package/docs/api/variables/ArrayMergeWay.md +1 -1
  337. package/docs/api/variables/ArrayMergeWaySymbol.md +1 -1
  338. package/docs/api/variables/CMD_ARG_FLAG_SYMBOL.md +21 -0
  339. package/docs/api/variables/CMD_ARG_PROCESSOR_RESULT.md +22 -0
  340. package/docs/api/variables/CMD_ARG_UNRESOLVED_SYMBOL.md +16 -0
  341. package/docs/api/variables/ClientEventPrefix.md +2 -2
  342. package/docs/api/variables/ClientToolFuncSchema.md +27 -17
  343. package/docs/api/variables/DEFAULT_CONFIG_NAME.md +1 -1
  344. package/docs/api/variables/DefaultAsyncSemaphoreCapacity.md +4 -1
  345. package/docs/api/variables/EventBusName.md +2 -2
  346. package/docs/api/variables/EventName.md +2 -2
  347. package/docs/api/variables/FilenameReservedRegex.md +1 -1
  348. package/docs/api/variables/FuncMetaSymbol.md +2 -2
  349. package/docs/api/variables/IDENTIFIER_REGEX.md +14 -0
  350. package/docs/api/variables/LLM_TOKENIZER_NAMES.md +1 -1
  351. package/docs/api/variables/LLM_TOKENIZER_NAMES_MAP.md +1 -1
  352. package/docs/api/variables/PASSING_SCORE.md +1 -1
  353. package/docs/api/variables/PATH_IDENTIFIER_REGEX.md +13 -0
  354. package/docs/api/variables/RESERVED_WORDS.md +13 -0
  355. package/docs/api/variables/RStreamErrCode.md +1 -1
  356. package/docs/api/variables/RemoteToolFuncSchema.md +36 -4
  357. package/docs/api/variables/ResponseRStreamErrCode.md +1 -1
  358. package/docs/api/variables/RpcMethodsClientToolSchema.md +2 -2
  359. package/docs/api/variables/RpcMethodsServerToolSchema.md +2 -2
  360. package/docs/api/variables/SHUTDOWN_SIGNALS.md +1 -1
  361. package/docs/api/variables/SSEChannelAlreadyClosedErrCode.md +1 -1
  362. package/docs/api/variables/SecondaryCache.md +1 -1
  363. package/docs/api/variables/ServerToolFuncSchema.md +27 -17
  364. package/docs/api/variables/StrangeHumanName.md +1 -1
  365. package/docs/api/variables/ToolAsyncCancelableBit.md +1 -1
  366. package/docs/api/variables/ToolAsyncMultiTaskBit.md +1 -1
  367. package/docs/api/variables/ToolAsyncPriorityBit.md +1 -1
  368. package/docs/api/variables/ToolFuncSchema.md +13 -13
  369. package/docs/api/variables/WindowsReservedNameRegex.md +1 -1
  370. package/docs/api/variables/backendEventable.md +23 -3
  371. package/docs/api/variables/base32768.md +2 -2
  372. package/docs/api/variables/event.md +1 -1
  373. package/docs/api/variables/eventClient.md +1 -1
  374. package/docs/api/variables/eventServer.md +1 -1
  375. package/docs/api/variables/lrucache.md +1 -1
  376. package/docs/api/variables/makeToolFuncCancelable.md +23 -3
  377. package/docs/api/variables/wait.md +1 -1
  378. package/docs/transport.dev.md +206 -0
  379. package/package.json +12 -10
  380. package/dist/chunk-4FKBOPZI.mjs +0 -1
  381. package/dist/chunk-TGTHY57V.mjs +0 -1
  382. package/dist/find-port-qS1CZ9c-.d.mts +0 -3
  383. package/dist/find-port-qS1CZ9c-.d.ts +0 -3
  384. package/dist/index-BLW3R7VS.d.mts +0 -1826
  385. package/dist/index-BLW3R7VS.d.ts +0 -1826
  386. package/docs/api/@isdk/namespaces/uuidv5/README.md +0 -12
  387. package/docs/api/@isdk/namespaces/uuidv5/variables/DNS.md +0 -11
  388. package/docs/api/@isdk/namespaces/uuidv5/variables/URL.md +0 -11
  389. package/docs/api/functions/nanoid.md +0 -45
  390. package/docs/api/functions/parseObjectArgInfo.md +0 -33
  391. package/docs/api/functions/parseObjectArgumentInfos.md +0 -29
  392. package/docs/api/functions/parseObjectArgumentsAsArgInfos.md +0 -46
  393. package/docs/api/functions/uuidParse.md +0 -21
  394. package/docs/api/functions/uuidStringify.md +0 -25
  395. package/docs/api/functions/uuidValidate.md +0 -21
  396. package/docs/api/functions/uuidVersion.md +0 -21
  397. package/docs/api/functions/uuidv1.md +0 -61
  398. package/docs/api/functions/uuidv4.md +0 -61
  399. package/docs/api/functions/uuidv5.md +0 -69
  400. package/docs/api/functions/uuidv6.md +0 -61
  401. package/docs/api/functions/uuidv7.md +0 -61
  402. package/docs/api/interfaces/AIChoiceConfig.md +0 -65
  403. package/docs/api/interfaces/BinarySemaphoreReleaserFunc.md +0 -37
  404. package/docs/api/interfaces/ParseObjectArgumentOptions.md +0 -89
  405. package/docs/api/variables/uuidNIL.md +0 -11
@@ -0,0 +1,206 @@
1
+ # AI-Tools Transport Layer: A Developer's Guide
2
+
3
+ This guide provides a comprehensive overview of the `ai-tool` transport layer, a powerful system designed to facilitate communication between server-side functions and client-side applications. It enables seamless Remote Procedure Calls (RPC) by abstracting the underlying network protocol.
4
+
5
+ **Prerequisite:** This document assumes you have a basic understanding of the `ToolFunc` framework. If not, please review the [`toolFunc-readme.md`](./toolFunc-readme.md) first.
6
+
7
+ ## Core Architecture
8
+
9
+ The transport layer consists of three main parts:
10
+
11
+ 1. **Tool Hierarchy**: A set of classes (`ServerTools`, `ClientTools`, and their derivatives) that define the structure and behavior of server-side and client-side functions.
12
+ 2. **Transport Abstractions**: A collection of interfaces and abstract base classes (`IToolTransport`, `IServerToolTransport`, `IClientToolTransport`) that define the communication contract.
13
+ 3. **Concrete Implementations**: Ready-to-use classes that implement the transport protocol, such as `FastifyServerToolTransport` for the server and `HttpClientToolTransport` for the client.
14
+
15
+ ```mermaid
16
+ graph TD
17
+ subgraph Client-Side
18
+ A[Client Application] --> B{ResClientTools};
19
+ B --> C{RpcMethodsClientTool};
20
+ C --> D{ClientTools};
21
+ end
22
+ subgraph Transport Layer
23
+ D --> |Uses| E[IClientToolTransport];
24
+ E -- HTTP Request --> F[IServerToolTransport];
25
+ end
26
+ subgraph Server-Side
27
+ F -->|Calls| G{ServerTools};
28
+ H{ResServerTools} --> I{RpcMethodsServerTool};
29
+ I --> G;
30
+ end
31
+
32
+ A -- Calls method on --> B;
33
+ B -- Transparently calls --> E;
34
+ F -- Receives request and finds --> H;
35
+ H -- Executes business logic --> H;
36
+ H -- Returns result through --> F;
37
+ F -- Sends HTTP Response --> E;
38
+ E -- Returns result to --> B;
39
+ B -- Returns result to --> A;
40
+ ```
41
+
42
+ ---
43
+
44
+ ## 1. The Tool Hierarchy
45
+
46
+ The entire system is built upon `ToolFunc`, with specialized classes for server and client operations.
47
+
48
+ ### `ServerTools` / `ClientTools`
49
+
50
+ - **`ServerTools`**: The foundation for any function you want to expose over the network. It runs on the server and contains the actual execution logic. Its static `toJSON()` method is crucial for serializing the list of available tools for clients.
51
+ - **`ClientTools`**: The client-side counterpart. It acts as a proxy or "stub" for a remote `ServerTools` instance. When a method is called on a `ClientTools` instance, it doesn't execute any logic itself; instead, it uses the configured transport to send the request to the server.
52
+
53
+ ### `RpcMethodsServerTool` / `RpcMethodsClientTool`
54
+
55
+ This pair extends the base tools to create a more powerful RPC-style tool.
56
+
57
+ - **`RpcMethodsServerTool`**: Allows you to group multiple functions (methods) within a single "tool". It automatically discovers methods in your class that start with a `$` prefix (e.g., `$add`, `$customMethod`) and exposes them. A special `act` parameter in the request is used to specify which method to call.
58
+ - **`RpcMethodsClientTool`**: The corresponding client class. When it's initialized from the server's definition, it dynamically creates proxy methods on the instance (e.g., `add()`, `customMethod()`) that automatically handle passing the correct `act` parameter to the transport.
59
+
60
+ ### `ResServerTools` / `ResClientTools`
61
+
62
+ This is the highest-level abstraction, providing a RESTful-like interface over the RPC mechanism.
63
+
64
+ - **`ResServerTools`**: Extends `RpcMethodsServerTool` to map standard HTTP-like verbs to specific class methods.
65
+ - `GET /<toolName>/:id` maps to the `get({id})` method.
66
+ - `GET /<toolName>` maps to the `list()` method.
67
+ - `POST /<toolName>` maps to the `post({val})` method.
68
+ - `DELETE /<toolName>/:id` maps to the `delete({id})` method.
69
+ - It still supports custom `$`-prefixed methods, which are typically invoked via `POST`.
70
+ - **`ResClientTools`**: The client-side proxy that provides a natural, REST-like API (`.get()`, `.list()`, `.post()`, etc.) for interacting with a `ResServerTools` endpoint.
71
+
72
+ ---
73
+
74
+ ## 2. Transport Abstractions & Implementations
75
+
76
+ - **`IServerToolTransport`**: The contract for server-side transports. Its key methods are `mount()` (to set up API endpoints for the tools), `start()` (to begin listening for connections) and `stop()` (to stop listening).
77
+ - **`IClientToolTransport`**: The contract for client-side transports. Its key methods are `loadApis()` (to fetch tool definitions from the server) and `fetch()` (to execute a remote tool).
78
+ - **`FastifyServerToolTransport`**: A concrete server implementation using the [Fastify](https://www.fastify.io/) framework. It automatically creates two types of endpoints when mounted:
79
+ 1. **Discovery Endpoint**: A `GET` route on the `apiRoot` (e.g., `GET /api`) which returns a JSON list of all registered `ServerTools`.
80
+ 2. **RPC Endpoint**: A general-purpose `ALL` route (e.g., `ALL /api/:toolId/:id?`) that catches all tool calls, finds the appropriate tool by name (`:toolId`), and executes it with the request parameters.
81
+ - **`HttpClientToolTransport`**: A concrete client implementation using the standard `fetch` API. It's compatible with browsers and Node.js.
82
+
83
+ ---
84
+
85
+ ## 3. End-to-End Developer Workflow
86
+
87
+ This example, based on `test/rpc-transport.test.ts`, demonstrates how to create, expose, and consume a full-featured RESTful tool.
88
+
89
+ ### Step 1: Define a Server-Side Tool
90
+
91
+ Create a class that extends `ResServerTools`. Implement the standard methods (`get`, `list`, etc.) and any custom business logic in methods prefixed with `$`.
92
+
93
+ ```typescript
94
+ // In your server-side code (e.g., /tools/TestResTool.ts)
95
+ import { ResServerTools, ResServerFuncParams, NotFoundError } from '@isdk/ai-tool';
96
+
97
+ class TestResTool extends ResServerTools {
98
+ // In-memory data for demonstration
99
+ items: Record<string, any> = {
100
+ '1': { id: '1', name: 'Item 1' },
101
+ '2': { id: '2', name: 'Item 2' },
102
+ };
103
+
104
+ // A custom RPC-style method
105
+ $customMethod({ id }: ResServerFuncParams) {
106
+ const item = this.items[id as string];
107
+ if (!item) throw new NotFoundError(id, 'res');
108
+ return { ...item, custom: true };
109
+ }
110
+
111
+ // Standard RESTful methods
112
+ get({ id }: ResServerFuncParams) {
113
+ const item = this.items[id as string];
114
+ if (!item) throw new NotFoundError(id, 'res');
115
+ return item;
116
+ }
117
+
118
+ list() {
119
+ return this.items;
120
+ }
121
+
122
+ delete({ id }: ResServerFuncParams) {
123
+ if (!this.items[id as string]) throw new NotFoundError(id, 'res');
124
+ delete this.items[id as string];
125
+ return { id, status: 'deleted' };
126
+ }
127
+ }
128
+ ```
129
+
130
+ ### Step 2: Set Up the Server
131
+
132
+ In your main server file, instantiate your tools, register them, and then mount and start the transport.
133
+
134
+ ```typescript
135
+ // In your server entry file (e.g., server.ts)
136
+ import { ResServerTools, FastifyServerToolTransport } from '@isdk/ai-tool';
137
+ import { TestResTool } from './tools/TestResTool'; // Assuming you created the class above
138
+
139
+ async function main() {
140
+ // 1. Instantiate and register your tool(s).
141
+ // The name 'resTest' will be used as the URL part.
142
+ new TestResTool('resTest').register();
143
+
144
+ // 2. Initialize the server transport.
145
+ const serverTransport = new FastifyServerToolTransport();
146
+
147
+ // 3. Mount the tool's base class. The transport will find all registered
148
+ // instances of ResServerTools (and its children).
149
+ // This creates endpoints under the '/api' prefix.
150
+ serverTransport.mount(ResServerTools, '/api');
151
+
152
+ // 4. Start the server.
153
+ const port = 3003;
154
+ await serverTransport.start({ port });
155
+ console.log(`Server listening at http://localhost:${port}/api`);
156
+ }
157
+
158
+ main();
159
+ ```
160
+
161
+ ### Step 3: Set Up and Use the Client
162
+
163
+ On the client-side, you initialize the transport and use it to automatically configure the `ClientTools` classes.
164
+
165
+ ```typescript
166
+ // In your client-side code
167
+ import { ResClientTools, HttpClientToolTransport } from '@isdk/ai-tool';
168
+
169
+ async function main() {
170
+ const apiRoot = 'http://localhost:3003/api';
171
+
172
+ // 1. Initialize the client transport with the server's URL.
173
+ const clientTransport = new HttpClientToolTransport(apiRoot);
174
+
175
+ // 2. Mount the client tools. This is a helper that does two things:
176
+ // a. Calls ResClientTools.setTransport(clientTransport)
177
+ // b. Calls ResClientTools.loadFrom() to fetch definitions from the server
178
+ // and create the client-side proxy tools.
179
+ await clientTransport.mount(ResClientTools);
180
+
181
+ // 3. Get the dynamically created proxy for your remote tool.
182
+ const resTool = ResClientTools.get('resTest') as ResClientTools & { customMethod: Function };
183
+ if (!resTool) {
184
+ throw new Error('Remote tool "resTest" not found!');
185
+ }
186
+
187
+ // 4. Call the methods as if they were local!
188
+
189
+ // Calls GET /api/resTest
190
+ const allItems = await resTool.list!();
191
+ console.log('All Items:', allItems);
192
+
193
+ // Calls GET /api/resTest/1
194
+ const item1 = await resTool.get!({ id: 1 });
195
+ console.log('Item 1:', item1);
196
+
197
+ // Calls the custom method via POST /api/resTest
198
+ // The client tool wrapper knows to send { act: '$customMethod' } in the body.
199
+ const customResult = await resTool.customMethod({ id: 2 });
200
+ console.log('Custom Method Result:', customResult);
201
+ }
202
+
203
+ main();
204
+ ```
205
+
206
+ This architecture provides a clean, powerful, and extensible way to build and consume APIs, separating business logic from the complexities of network communication.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@isdk/ai-tool",
3
- "version": "0.8.2",
3
+ "version": "0.9.0",
4
4
  "author": "Riceball LEE <snowyu.lee@gmail.com>",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.mjs",
@@ -22,15 +22,15 @@
22
22
  }
23
23
  },
24
24
  "dependencies": {
25
- "@huggingface/transformers": "^3.7.2",
25
+ "@huggingface/transformers": "^3.8.1",
26
26
  "@isdk/common-error": "^0.2.0",
27
- "@isdk/util": "^0.3.2",
27
+ "@isdk/util": "^0.3.8",
28
28
  "abstract-error": "^2.0.0",
29
29
  "base32768": "^5.0.0",
30
30
  "custom-ability": "^2.0.1",
31
31
  "custom-factory": "2.3.0",
32
32
  "date-fns": "^4.1.0",
33
- "events-ex": "^2.1.0",
33
+ "events-ex": "^2.1.1",
34
34
  "eventsource-parser": "^3.0.6",
35
35
  "hash-wasm": "^4.12.0",
36
36
  "jschardet": "^3.1.4",
@@ -44,13 +44,15 @@
44
44
  "property-manager": "^3.0.3",
45
45
  "secondary-cache": "^2.0.1",
46
46
  "secure-json-parse": "^4.0.0",
47
- "util-ex": "2.3.0",
48
- "uuid": "^11.1.0",
49
- "xxhashjs": "^0.2.2",
47
+ "util-ex": "^2.5.2",
50
48
  "yaml": "^2.8.1",
51
49
  "yaml-types": "^0.4.0",
52
- "@isdk/template-engines": "^0.6.6",
53
- "@isdk/detect-text-language": "^0.1.2"
50
+ "@isdk/detect-text-language": "^0.1.2",
51
+ "@isdk/hash": "^0.1.1",
52
+ "@isdk/template-engines": "^0.6.9",
53
+ "@isdk/tool-func": "^0.1.1",
54
+ "@isdk/tool-rpc": "^0.1.1",
55
+ "@isdk/tool-event": "^0.1.2"
54
56
  },
55
57
  "devDependencies": {
56
58
  "@antfu/eslint-config": "^4.10.1",
@@ -72,7 +74,7 @@
72
74
  "tsup": "^8.5.0",
73
75
  "tsx": "^4.20.5",
74
76
  "type-fest": "^4.41.0",
75
- "typedoc": "^0.28.13",
77
+ "typedoc": "^0.28.16",
76
78
  "typedoc-plugin-markdown": "^4.8.1",
77
79
  "typescript": "~5.7.3",
78
80
  "vite": "^7.1.4",
@@ -1 +0,0 @@
1
- import{EventEmitter as t}from"events-ex";import{assign as e,defaultsDeep as n}from"lodash-es";import{AdvancePropertyManager as r}from"property-manager";import{_createFunction as i}from"util-ex";import{AbortError as s,AbortErrorCode as o,AlreadyExistsError as a,AlreadyExistsErrorCode as c,BaseError as u,CommonError as f,createError as h,ErrorCode as l,InternalErrorCode as m,NotFoundErrorCode as p,NotFoundError as d,NotImplementedErrorCode as y,NotImplementationError as w,throwError as b}from"@isdk/common-error";import{createAbilityInjector as v}from"custom-ability";import{toRegExp as g}from"util-ex";var k=.618,$=["get","post","put","delete","patch","list","res"],x={action:{type:"string",assign:(t,e,n,r,i)=>t||"post"},fetchOptions:{type:"object"},allowExportFunc:{type:"boolean"}};import{format as A,parse as S,parseISO as E}from"date-fns";import{add as T,formatISO as j,parseISO as I,toDate as C}from"date-fns";var O="MMMM d, y 'at' h:m:s b 'GMT'x";function N(t){return t&&(O=t),O}function M(t){let e;try{"string"==typeof t?e=E(t):"number"==typeof t?e=new Date(t):t instanceof Date&&(e=t)}catch(t){console.error(t)}return e}function R(t,e=O){return S(t,e,new Date)}function z(t,e=O){return A(t,e)}var _=["stop","length","content_filter","tool_calls","function_call","abort","error","other",null],L=["human","ai","generic","system","tool"],D=["user","assistant","system","tool","tool_calls"],P="陌生人";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=M(t);n&&(e+=" ["+z(n)+"]")}e+=" "+n.content+"\n"}return e}import{StringTemplate as F,EnvStringTemplate as B,FStringTemplate as q,GolangStringTemplate as U,expandEnv as G,expandObjEnv as W,defaultTemplateFormat as Z,getEnvVairables as J,createHfValueFunc as H}from"@isdk/template-engines";import{StringTemplate as K}from"@isdk/template-engines";function Q(t){return Object.keys(t).sort().map(e=>t[e])}var V=class extends K{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 K?t.examplePrompt:K.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=Q(t);n.length>0&&e.push(...n)}const n=[this.prefix,...e,this.suffix].join(this.exampleSeparator),r=this.templateFormat;return await K.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 Y(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}K.register(V,{name:"fewshot",aliases:["few_shot"]});var tt=!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=>{tt=t});var et=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,tt?r:Y(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()}};import{detectTextLanguage as nt}from"@isdk/detect-text-language";var rt=/(\S.+?[.!?])(?=\s+|$)|(\S.+?)(?=[\n]|$)/g,it=/([A-Z][a-z]{1,2}\.)\s(\w)/g,st=/(\.[a-zA-Z]\.)\s(\w)/g,ot=new RegExp("([A-Z][a-z]{1,2}\\.)@(\\w)","g"),at=new RegExp("(\\.[a-zA-Z]\\.)@(\\w)","g"),ct=/(```)([\s\S]*?)(```)/g,ut=">>>CODE_BLOCK<<<",ft=/([*_`]{1,3})(\S.*?\S)\1/,ht=/>>> INLINE_BLOCK (\d+) <<</,lt=1e4;function mt(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 pt(t,{best:e=!0,completeSentence:n,isMarkdown:r,ignoreEmptyLine:i}={}){const s=[],o=[];let a,c=0;for(;c++<lt&&(a=ct.exec(t));){const e=a[0];s.push(e),t=t.replace(e,"\n"+ut+(s.length-1)+"\n")}for(c=0;c++<lt&&(a=ft.exec(t));){const e=a[0];o.push(e),t=t.replace(e,">>> INLINE_BLOCK "+(o.length-1)+" <<<")}if(r){const e=t.split("\n");for(let t=0;t<e.length;t++){const n=e[t];gt(n,{isMarkdown:r,nextLine:e[t+1]})&&(s.push(n),e[t]=ut+(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 f=[];for(let t=0;t<u.length;t++){let n=u[t].trimEnd();if(!n){!r&&i||f.push("");continue}if(n.startsWith(ut)){f.push(s[Number(n.slice(16))]);continue}if(r&&gt(n,{isMarkdown:r,nextLine:u[t+1]})){f.push(n);continue}if(!e){f.push(n);continue}let a=mt(n,"@",[it,st]),c=Array.from(a.matchAll(rt)),h=[];if(c.length)for(let t=0;t<c.length;t++)h.push(mt(c[t][0]," ",[ot,at]));else h.push(n);f.push(...h.map(t=>At(o,t)))}return n&&(f=dt(f,{isMarkdown:r,ignoreEmptyLine:i})),f}function dt(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=Et(t,i+1);a=vt(t[n],{isMarkdown:e,nextLine:-1===n?"":t[n+1]})}else a=vt(t[i+1],{isMarkdown:e,nextLine:t[i+2]});yt(o,{isMarkdown:e,nextLine:t[i+1]})||""===t[i+1]||a?(s&&(o=wt(s,o),s=""),r.push(o)):(s&&(o=wt(s,o)),s=o)}else n||r[r.length-1]&&r.push(o);i++}return s&&r.push(s),r}function yt(t,e){return bt(t)||vt(t,e)}function wt(t,e){const n=t+" "+e,r=nt(n,{isoCode:!0});return r&&!St(r)?(xt(t)&&(t+=" "),e=t+e):e=t.endsWith("-")?(t=t.slice(0,-1))+e:n,e}function bt(t){if(!t)return!1;return/(([.。!!??]\s*['"”’]?)|```)\s*$/.test(t)}function vt(t,e){let n=gt(t,e);return n||(n=kt(t)),n||(n=$t(t)),n}function gt(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 kt(t){return/^\s*([*+-]|\d+[.、])\s*(?<item>.*)(?=\n|$)/.exec(t)}function $t(t){return/^[-=_]{3,}$/.exec(t)}function xt(t){return/[。!??,、;;::'""“”‘’~~《》<>〈〉【】(){}【】\[\]\(\)…·]$/.test(t)}function At(t,e){let n,r=0;for(;r++<lt&&(n=ht.exec(e));){const r=Number(n[1]);e=e.replace(n[0],t[r])}return e}function St(t){return!["zh","ja","th","lo","ta","ko"].includes(t)}function Et(t,e=0){for(let n=e;n<t.length;n++){const e=t[n];if(null!=e&&""!==e)return n}return-1}function Tt(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 jt(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 It(t,e){return t=jt(t=Tt(t,e),e)}function Ct(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||gt(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 Ot(t,e=2,n=.5){const r=10**e;return Math.trunc((t+Number.EPSILON+n/r)*r)/r}async function Nt(t){return new Promise(e=>setTimeout(e,t))}var Mt=Nt;async function Rt(){return new Promise(t=>{setImmediate(t)})}import{createAbilityInjector as zt}from"custom-ability";import{EventEmitter as _t,eventable as Lt,states as Dt,wrapEventEmitter as Pt}from"events-ex";var Xt="event",Ft="event-bus";var Bt=zt(function(t,e){const n=e?.eventBusName||Ft;return class{static get emitter(){if(!this._emitter){const t=this.get(n)?.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);import{nanoid as qt}from"nanoid";import{v1 as Ut,v5 as Gt,v4 as Wt,v6 as Zt,v7 as Jt}from"uuid";import*as Ht from"base32768";import{v1 as Kt,v4 as Qt,v5 as Vt,v6 as Yt,v7 as te,stringify as ee,parse as ne,validate as re,version as ie,NIL as se}from"uuid";var oe={1:Ut,4:Wt,5:Gt,6:Zt,7:Jt};function ae(t,e){!0===t&&(e=!0),"number"==typeof t&&oe[t]||(t=1);const n=oe[t];return e?Ht.encode(n(null,new Uint8Array(16))):n()}import ce from"xxhashjs";import*as ue from"base32768";import{canonicalize as fe}from"json-canonicalize";import{createMD5 as he,createRIPEMD160 as le,createSHA1 as me,createSHA224 as pe,createSHA256 as de,createSHA512 as ye,createXXHash128 as we,createXXHash32 as be,createXXHash64 as ve}from"hash-wasm";var ge=588213,ke=(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))(ke||{}),$e={1:he,2:me,8:de,10:ye,11:pe,3:le,112:be,111:ve,113:we},{h32:xe,h64:Ae}=ce;function Se(t,e=16){return"object"==typeof t&&(t=fe(t)),xe(t.normalize(),ge).toString(e)}function Ee(t,e=16){return"object"==typeof t&&(t=fe(t)),Ae(t.normalize(),ge).toString(e)}function Te(t,e=111,n=ge){let r;return t.buffer&&(t=t.buffer),112!==e?(r=Ae(t,n),r=new Uint16Array([r._a00,r._a16,r._a32,r._a48]),r=new Uint8Array(r.buffer)):(r=xe(t,n),r=new Uint16Array([r._low,r._high]),r=new Uint8Array(r.buffer)),r}function je(t,e=111,n=ge){return ue.encode(Te(t,e,n))}import{canonicalize as Ie}from"json-canonicalize";import*as Ce from"base32768";var Oe=Ce;async function Ne(t,{hashAlgo:e=111,seed:n=ge,outputType:r="string"}={}){const i=await $e[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):Ce.encode(i.digest("binary"))}async function Me(t,{hashAlgo:e=111,seed:n=ge,outputType:r="string"}={}){const i=await $e[e](n);i.init(),i.update(t);return"string"!==r?i.digest(r):Ce.encode(i.digest("binary"))}async function Re(t,e){return Me(t=Ie(t),e)}function ze(t,e){return!t||t.some(t=>t instanceof RegExp?t.test(e):t===e)}var _e=498,Le=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 Map,this.messages=[],this.active=!0}publish(t,e,n){let r,i;this.active||b("Channel closed","SSEChannel",_e);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&&"string"!=typeof t&&(t=""+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){(Array.isArray(n.clientId)?n.clientId:[n.clientId]).forEach(t=>{const e=this.clients.get(t);e&&e.res.write(r)})}else this.clients.forEach(t=>{s&&!ze(t.events,s)||t.res.write(r)});for(;this.messages.length>this.options.historySize;)this.messages.shift();return i}subscribe(t,e){this.active||b("Channel closed","SSEChannel",_e),(e instanceof RegExp||"string"==typeof e)&&(e=[e]);const n=this.clients.get(t);if(n){n.events||(n.events=[]);for(const t of e)n.events.some(e=>e.toString()===t.toString())||n.events.push(t);return!0}return!1}unsubscribe(t,e){this.active||b("Channel closed","SSEChannel",_e),(e instanceof RegExp||"string"==typeof e)&&(e=[e]);const n=this.clients.get(t);return!!n&&(n.events&&(n.events=n.events.filter(t=>!e.some(e=>e.toString()===t.toString()))),!0)}getClient(t){return this.clients.get(t)}connect(t,e,n,r){this.active||b("Channel closed","SSEChannel",_e);const i=ae();if(this.clients.has(i)){const t=this.clients.get(i);t&&this.disconnect(t)}(n instanceof RegExp||"string"==typeof n)&&(n=[n]);const s={req:t,res:e,events:n,clientId:i},o=this.options.maxStreamDuration;let a="max-age=0, stale-while-revalidate=0, stale-if-error=0, no-transform";o>0&&(a+=", s-maxage="+(Math.floor(o/1e3)-1));const c={"Content-Type":"text/event-stream","Cache-Control":a,Connection:"keep-alive"};this.options.cors&&(c["Access-Control-Allow-Origin"]="*"),s.req.socket.setNoDelay(!0),s.res.writeHead(200,c);let u="retry: "+this.options.clientRetryInterval+"\n\n";const f=Number.parseInt(t.headers["last-event-id"],10),h=Number.isNaN(f)?this.options.rewind:this.nextID-1-f;return h&&this.messages.filter(t=>ze(s.events,t.eventName)).slice(0-h).forEach(t=>{u+=t.output}),s.res.write(u),this.clients.set(s.clientId,s),this.publish({clientId:i},"welcome",{clientId:i}),o>0&&setTimeout(()=>{s.res.writableEnded||this.disconnect(s)},o),s.res.on("close",()=>this.disconnect(s)),s}disconnect(t){t.res.end(),this.clients.delete(t.clientId)}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 De(t){return t instanceof ReadableStream||t instanceof WritableStream}var Pe=600,Xe=601,Fe=class extends u{constructor(t,e=600){super(t,500)}};function Be(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 Fe(`Response error: ${e}`,601))}}})}return new ReadableStream({start(t){t.error(new Fe("Response error: No response body",601))}})}function qe(){return new ReadableStream({start(t){t.close()}})}import{createParser as Ue}from"eventsource-parser";function Ge(t){const e=new TextDecoder;let n;return new TransformStream({async start(e){n=Ue({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 We(){let t=!0;return e=>(t&&(e=e.trimStart())&&(t=!1),e)}function Ze(t,e){if(!t.ok)return Be(t.body);let n=t.body||new ReadableStream({start(t){t.close()}});return n instanceof ReadableStream||(n=ReadableStream.from(n)),n.pipeThrough(Ge(e))}function Je(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 He(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()}})}import{extNameLevel as Ke,FilenameReservedRegex as Qe,getMultiLevelExtname as Ve,isValidFilename as Ye,isValidFilepath as tn,sanitizeFilename as en,sanitizeFilepath as nn,WindowsReservedNameRegex as rn}from"@isdk/util";import{isRegExpStr as sn,toRegExp as on}from"util-ex";function an(t,e){if("string"!=typeof t)throw new f("modelName must be a string","isModelNameMatched",l.InvalidArgument);switch(typeof e){case"string":if(sn(e)){const n=(e=on(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(sn(n)){const r=(e=on(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 cn(t){return Object.keys(t).filter(t=>Number.isNaN(Number(t)))}import{pick as un}from"lodash-es";import{newFunction as fn}from"util-ex";import{get as hn,omitBy as ln}from"lodash-es";import{newFunction as mn}from"util-ex";async function pn(t,e,n){return bn(Cn(t,e,n),e,n)}function dn(t){for(let e=1;e<t.length;e++)if(t[e]<=t[e-1])return!1;return!0}function yn(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)))&&dn(n.map(t=>parseInt(t))))t=Object.values(t);else if("0"===r[0]&&dn(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 wn(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 bn(t,e,n){if(t.length){const r=await Promise.all(t.map((t,r)=>In(t,r,e,n))),i=n?.returnArrayOnly;let s;if(r?.length){s=Pn(`{${r.map(t=>t).join(",")}}`,e)}return s&&!i&&(s=wn(s)),s}}function vn(t,e,n,r){const[i,s]=t;if(!i&&"|"===s[0])return"choice: {"+function(t,e,n){const r=Cn(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=>An(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($n(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 gn([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:{...ln(r,(t,e)=>!e||"_"===e[0]||"function"==typeof t),...i?.templateData}};i?.templateFormat&&(a.templateFormat=i.templateFormat);const c=await F.formatIf(a);if(c)return o=$n(c)?c:JSON.stringify(c),s+":"+o}async function kn(t,e,n,r){let i=vn(t,0,n,r);return i||(i=await gn(t,e,n,r)),i}function $n(t){const e=t[0];return('"'===e||"'"===e)&&t[t.length-1]===e}function xn(t,e=['""',"''","{}"]){return e.some(e=>t[0]===e[0]&&t[t.length-1]===e[1])}function An(t,e='"'){return $n(t)?t:e+t+e}function Sn(t){return'"'+t.replace(/(?<!\\)"(?!\\)/g,'\\"')+'"'}var En=["true","false","null","undefined","NaN","Infinity"];async function Tn(t,e,n){const r=mn("async expression",[],`return ${t};`,Bn(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 jn(t,e,n){let r=t;if(["true","false"].includes(t.toLowerCase()))r=r.toLowerCase();else if(!(i=t,xn(i)||!Number.isNaN(parseFloat(i))||En.includes(i)||Ln(i)||e&&void 0!==hn(e,t)||Ln(t)))try{r=n?.skipExpression?Sn(t):await Tn.call(this,t,e,n?.preserveUnresolvedName)}catch(e){r=Sn(t)}var i;return r}async function In(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 jn(s.slice(t+1).trim(),n,r)}{const t=s.trim();if(n&&void 0!==hn(n,t)){return(a?"":e+":"+t+",")+'"'+t+'":'+t}return e+":"+await jn(s.trim(),n,r)}}function Cn(t,e,n){const r=n?.delimiter??",",i=n?.assigner??"=";let s=[],o=!1,a="",c="",u=!1,f="";for(let e=0;e<t.length;e++){const n=t[e];if(n!==r||o||f)if("\\"===n)c+=n,e++,c+=t[e];else if("("!==n&&"["!==n||o)if(f&&n===f)f="",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 f="("===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 On(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 pn(s,e,n)),{command:i.trim(),args:o}}var Nn="__PlacEhoLdeR_";function Mn(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??Nn,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 Rn(t,e,n){const r=n?.placeholder??Nn;return e.reduce((t,e,n)=>t.replace(new RegExp(r+n,"g"),e),t)}var zn="[a-zA-Z_$][a-zA-Z_\\d$]*",_n=new RegExp(`^\\s*(\\(\\s*\\)|${zn}|\\(${`${zn}\\s*(,\\s*${zn})*`}\\))\\s*=>`);function Ln(t){return _n.test(t)}async function Dn(t,e){if(e&&(e=Bn(e)),e&&(t=t.trim()).startsWith("{")&&t.endsWith("}")){return await pn(t.slice(1,-1),e,{assigner:":",ignoreIndexNamed:!0})}return Pn(t,e)}function Pn(t,e){if(e&&(e=Bn(e)),e){const n=Object.keys(e);if(n.length){const r=Object.values(e);let i=0;for(;i++<100;)try{return fn("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 fn("expression",[],`return ${t}`)()}var Xn=/^[a-zA-Z_$][0-9a-zA-Z_$.]*$/,Fn=t=>Xn.test(t);function Bn(t){if(t){const e=Object.keys(t),n=e.length,r=e.filter(e=>Fn(e)&&null!==t[e]);if(n===r.length)return t;if(r.length)return t=un(t,r)}}function qn(t){return t?Un(t,[],{dot:""}):[]}function Un(t,e,{dot:n=".",visited:r=new Set}={}){return r.has(t)?[e.join("")]:Array.isArray(t)?(r.add(t),t.flatMap((t,n)=>Un(t,[...e,`[${n}]`],{dot:".",visited:r}))):(i=t)&&i.constructor===Object?(r.add(t),Object.entries(t).flatMap(([t,i])=>Un(i,[...e,n+t],{dot:".",visited:r}))):[e.join("")];var i}function Gn(t){if(t<2)throw new f("repetitionThreshold must be greater than 1","createEndWithRepetitionDetector",l.InvalidArgument);const e=new RegExp(`([\\S\\s]+)(\\1{${t-1},})$`);return function(t){return e.exec(t)}}import Wn from"path";import*as Zn from"fs";import Jn from"mime-type/with-db";import Hn from"jschardet";function Kn(t){const e=Zn.statSync(t,{throwIfNoEntry:!1});return e?.isFile()}function Qn(t,e,n,r){const i=r?.signal,s=r?.exclude;let o;if(Wn.isAbsolute(t)?o=Kn(t)?t:Vn(Wn.basename(t),[Wn.dirname(t)],{extNames:n,exclude:s,signal:i}):(e||(e=["."]),o=Vn(t,e,{extNames:n,exclude:s,signal:i})),!o)throw new d(t,"loadFileFromPaths");{const t=o;o=Zn.readFileSync(o),r&&(r.filepath=t)}return o}function Vn(t,e,{extNames:n,signal:r,exclude:i=[]}){let s;const o=n?n.map(e=>Ve(t,Ke(e))):void 0;"string"==typeof i&&(i=[i]);for(const a of e){if(r?.aborted)throw r.reason;const e=Wn.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)&&Kn(r)){s=r;break}}else if(!i.includes(e)&&Kn(e)){s=e;break}}return s}function Yn(t,e,n,r,i){let s;"string"==typeof r?(s=r,r=void 0):s=r?.encoding;return tr(Qn(t,e,n,r),s)}function tr(t,e){void 0===e&&(e=or(t)??"utf8");return new TextDecoder(e).decode(t)}function er(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?nr(t.dir):t.dir,f=Wn.resolve(e);if(i.has(f))continue;i.add(f);const h=Zn.statSync(e,{throwIfNoEntry:!1});if(h?.isDirectory()){u=t.level+1;const i=Zn.readdirSync(e,{withFileTypes:!0});for(let t=0;t<i.length;t++){let s=i[t],f=Wn.join(e,s.name);const h=f;if(s.isSymbolicLink()){const t=Wn.dirname(f);if(f=Zn.readlinkSync(f),f=Wn.resolve(t,f),s=Zn.statSync(f,{throwIfNoEntry:!1}),!s)continue}if(s.isDirectory())(!a||u<a)&&(o&&!o(f,s)||r.push({dir:f,level:u}));else if(s.isFile()&&(!o||o(f,s))){const t=c?f:h;n.includes(t)||n.push(t)}}}}return n}function nr(t){const e=Zn.lstatSync(t,{throwIfNoEntry:!1});return e?.isSymbolicLink()&&(t=Zn.readlinkSync(t)),t}async function rr(t,e){return Ne(ReadableStream.from(Zn.createReadStream(t)),e)}async function ir(t){const e=Wn.basename(t);t=Wn.resolve(t);const n=await Zn.promises.stat(t),r=n.mtime,i=n.ctime,s=n.size,o=sr(s),a=await rr(t,{hashAlgo:o}),c=Jn.lookup(t);return{name:e,mtime:r,ctime:i,size:s,hash:ke[o]+":"+a,mimeType:c,id:"file://"+t}}function sr(t){let e=111;return t<=2048?e=112:t<=1048576?e=111:t<=10485760?e=113:t>10485760&&(e=10),e}function or(t,e){return Hn.detect(t,e).encoding}import{statSync as ar}from"fs";import cr from"path";import{ConfigFile as ur,registerYamlTag as fr,traverseFolderSync as hr}from"@isdk/util";import{regexp as lr}from"yaml-types";import{mimeType as mr}from"mime-type/with-db";import{ConfigFile as pr,registerYamlTag as dr,parseYaml as yr,stringifyYaml as wr}from"@isdk/util";function br(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 hr(t,(t,e)=>{if(i?.includes(t)||!e.isFile())return;const o=cr.extname(t),a=ar(t);if(s.includes(o)){if(r?.hasOwnProperty(t)&&a.mtimeMs<=r[t])return;n.push(t)}}),n}function vr(t,e){return br(t,e).map(t=>ur.loadSync(t)).filter(t=>void 0!==t)}function gr(t,e,n=1){return ur.saveSync(t,e,{extLevel:n})}function kr(t){t instanceof Date&&(t=t.toISOString());return function(t,e){return t?`'${e}'`:String(e)}("string"==typeof t,t)}function $r(t,e){return t.map(t=>Sr(t,e)).join(" AND ")}function xr(t,e){return t.map(t=>Sr(t,e)).join(" OR ")}function Ar(t,e){const n=[];return Object.keys(e).forEach(r=>{const i=e[r];switch(r){case"$lt":case"<":n.push(`${t} < ${kr(i)}`);break;case"<=":case"$lte":n.push(`${t} <= ${kr(i)}`);break;case"$gt":case">":n.push(`${t} > ${kr(i)}`);break;case"$gte":case">=":n.push(`${t} >= ${kr(i)}`);break;case"$ne":case"!=":n.push(`${t} != ${kr(i)}`);break;case"=":case"$eq":n.push(`${t} = ${kr(i)}`);break;case"$in":n.push(`${t} IN (${i.map(t=>kr(t)).join(", ")})`);break;case"$nin":n.push(`${t} NOT IN (${i.map(t=>kr(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 Sr(t,e){const n=[];if("function"!=typeof e&&(e=t=>t),Array.isArray(t))n.push($r(t,e));else for(const[r,i]of Object.entries(t))if("$and"===r)n.push(`(${$r(t[r],e)})`);else if("$or"===r)n.push(`(${xr(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(Ar(e(r),i))}return n.length>1?n.join(" AND "):n[0]}function Er(t){const e=t.indexOf("://");if(e>0)return t.substring(0,e)}function Tr(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 jr(t){const e=t.match(/^\s*[+]?(\d+(?:[.]\d+)?)\s*([TBMK])?\s*$/i);if(!e)throw new f("Invalid formatted parameter size string.","scaleToSize",l.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 Ir(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":" ")+Ir(t,{level:n+1,visiting:r,parent:e})}}fr(lr);var Cr=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}};import{isAsync as Or}from"util-ex";import{EventEmitter as Nr}from"events-ex";function Mr(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 Rr=class extends Array{constructor(t,e){Array.isArray(t)?(super(...t),this._length=t.length,t=void 0):(super(),this._length=0),this._capacity=Mr(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(Mr(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)}}};import{AbortError as zr}from"@isdk/common-error";var _r=32;function Lr(t){return"function"==typeof t}function Dr(){return"1"}var Pr=class{constructor(t={}){const{initFn:e=Dr,pauseFn:n,resumeFn:r,capacity:i=_r}=t;if(Lr(n)!==Lr(r))throw new Error("pauseFn and resumeFn must be both set for pausing");this.waiting=new Rr(i),this.emitter=new Nr,this.useDefaultTokens=e===Dr,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 zr(e.reason||"aborted");e.alreadyRejected=!0,r(t)}),n};let r=this.tryAcquire(t);const i=r&&Or(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 zr(t))}get activeCount(){return this._activeCount}get pendingCount(){return this.waiting.size}},Xr=class extends Pr{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 Rr(e);for(let t=0;t<e;t++)this.free.push(this.initTokenFn())}tryAcquire(t){let e=this.isReady;if(e&&Or(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 Fr(t,{timeUnit:e=1e3,uniformDistribution:n=!1}={}){const r=new Xr(n?1:t),i=n?e/t:e;return async function(){await r.acquire(),setTimeout(()=>r.release(),i)}}import{AbortError as Br}from"@isdk/common-error";var qr=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 Br(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})})}};import{createAbilityInjector as Ur}from"custom-ability";import{defineProperty as Gr}from"util-ex";var Wr,Zr=0,Jr=1,Hr=2,Kr=(t=>(t[t.MultiTask=0]="MultiTask",t[t.Cancelable=1]="Cancelable",t[t.Priority=2]="Priority",t))(Kr||{}),Qr=((Wr=Qr||{})[Wr.MultiTask=1]="MultiTask",Wr[Wr.Cancelable=2]="Cancelable",Wr[Wr.Priority=4]="Priority",Wr),Vr=class extends AbortController{constructor(t){super(),Gr(this,"parent",t)}abort(t,e){this.signal.aborted||("string"==typeof t&&(t=new s(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 s(e.reason||"aborted")}}},Yr=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 Xr(e-1,{isReadyFn:t})),n}static hasAsyncFeature(t){const e=this.prototype;let n=e.asyncFeatures;return e._asyncFeatures&&(n|=e._asyncFeatures),Cr.has(n,t)}hasAsyncFeature(t){let e=this.asyncFeatures;return this._asyncFeatures&&(e|=this._asyncFeatures),Cr.has(e,t)}isAborted(t){const e=this.hasAsyncFeature(0);let n=this.__task_aborter;if(n&&e){if(null==t)throw new f("Missing taskId",this.name+".isAborted",l.InvalidArgument);n=n[t]}return!n||n.signal.aborted}getRunningTask(t){const e=this.hasAsyncFeature(0);let n=this.__task_aborter;if(n&&e){if(null==t)throw new f("Missing taskId",this.name+".getRunningTask",l.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(0)){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(0);if(!r&&n&&this.getRunningTask())throw new f("The task is running",this.name,l.TooManyRequests);const i=t?.aborter||new Vr(this);if(!(i instanceof Vr)){if(!(i instanceof AbortController))throw new f("aborter should be an AbortController",this.name,l.InvalidArgument);Object.setPrototypeOf(i,new Vr(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=[...ti(t?.signal),...ti(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(0)){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=He({onStart:t=>{Gr(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(0)){const t=e?.taskId;if(null==t)throw new f("Missing data.taskId",this.name+".abort",l.InvalidArgument);n=n[t],this.cleanMultiTaskAborter(t,r)}else this.__task_aborter=void 0;n&&!n.signal.aborted&&n.abort(t,e)}}};function ti(t){return t?Array.isArray(t)?t.filter(Boolean):[t]:[]}Yr.prototype.generateAsyncTaskId=function(t,e){return this._generateAsyncTaskId(t,e)},Yr.prototype.cleanMultiTaskAborter=function(t,e){return this._cleanMultiTaskAborter(t,e)};var ei=Ur(Yr,"abort",{afterInjection:function(t,e){let n=t.prototype._asyncFeatures||0;n|=Qr.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 ni(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}import ri from"memoizee";import{canonicalize as ii}from"json-canonicalize";function si(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 ri(t,{...e,normalizer:t=>{if(r){const e=r(t);if("string"===e)return e;e&&(t=e)}return je(ii(t))}})}import oi from"path";import{packageDirectorySync as ai}from"package-directory";function ci(t){const e=ai({cwd:t});if(e)return e;const n=t.split(oi.sep);let r=n.lastIndexOf("dist");if(r>0)return n.slice(0,r).join(oi.sep);if(r=n.lastIndexOf("src"),r>0)return n.slice(0,r).join(oi.sep);throw new Error("can not find package directory")}import ui from"path";function fi(t,e){try{const n=ui.relative(ui.resolve(t),ui.resolve(e));return!n.startsWith("..")&&!ui.isAbsolute(n)}catch{return!1}}function hi(t,e){return e?.some(e=>fi(e,t))}function li(t,e){for(const n of e)hi(n,t)||t.push(n);return t}function mi(t){const e=t.slice();return pi(e),e}function pi(t){const e=t.length;if(e<=1)return;const n=new Map,r=[];for(let i=0;i<e;i++){const e=di(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(fi(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 di(t){let e=ui.normalize(t);return e=e.split(/[/\\]/).join(ui.posix.sep),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e}import{isRegExp as yi,isRegExpStr as wi}from"util-ex";function bi(t){return wi(t)||yi(t)}function vi(t){return t.replace(/\x1B[[(?);]{0,2}(;?\d)*./g,"")}import gi from"path";import{fileURLToPath as ki}from"url";import{AutoTokenizer as $i}from"@huggingface/transformers";var xi=ki(import.meta.url),Ai=gi.dirname(xi),Si=gi.join(ci(Ai),".cache"),Ei=new Map,Ti={"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"},ji={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 Ii(t){let e=Ei.get(t);return e||(e=$i.from_pretrained(t,{cache_dir:Si}),Ei.set(t,e)),e}async function Ci(t,e="qwen2.5"){ji[e]&&(e=ji[e]);return(await Ii(e)).encode(t)}async function Oi(t,e="qwen2.5"){return(await Ci(t,e)).length}function Ni(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 Mi(t,e){let n,r=1984,i=!0,s=!1,o=!0,a=Oi,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 w("truncateToTokenLimit only implemented by sentence","truncateToTokenLimit");if(r>0){let c=await a(t,n);const u=e?.sentences??pt(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 f(`Can not find sentence: ${e}`,"truncateContentToTokenLimit");t=t.slice(0,n)}if(c<=1)throw new f(`Can not truncate content to fit within the token limit: ${r}`,"truncateContentToTokenLimit");if(c<=r&&o){const e=u[u.length-1];if(e&&vt(e)){if(c-await a(e,n)>9){const n=t.lastIndexOf(e);if(-1===n)throw new f(`Can not find sentence: ${e}`,"truncateContentToTokenLimit");t=t.slice(0,n).trimEnd()}}}}else c--}else t=u.join("\n")}if(!t)throw new f(`Can not truncate content to fit within the token limit: ${r}`,"truncateContentToTokenLimit");return t}async function Ri(t,e){let n,r=1984,i=!0,s=Oi,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 w("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 f(`Can not truncate content to fit within the token limit: ${r}`,"truncateContentToTokenLimit");if(o<=r&&i){const e=t[t.length-1];if(e&&vt(e)){o-await s(e,n)>9&&t.pop()}}}}}if(!t.length)throw new f(`Empty. Can not truncate content to fit within the token limit: ${r}`,"truncateContentToTokenLimit");return t}async function zi(t,e){let n,r=1984,i=Oi;if(e&&(n=e.modelId,"function"==typeof e.countLLMTokens&&(e.size>=0&&(r=e.size),i=e.countLLMTokens)),r>0){await i(t,n)}}import _i from"fs";async function*Li(t,e){const n=(e={...e,completeSentence:!1,corrected:!1}).size??1984,r=e.modelId,i=e.metaInfo?.size??(await _i.promises.stat(t)).size;let s=Math.trunc(i/2);if(s<=n){let i=tr(await _i.promises.readFile(t));if(s=await Oi(i,r),s<=n)yield i;else do{const t=await Mi(i,{...e,modelId:r,size:n});yield t,i=i.slice(t.length)}while(i)}else{const i=ReadableStream.from(_i.createReadStream(t)).getReader();let s="";for(;;){const{done:t,value:o}=await i.read();if(t)break;s+=tr(o);const a=pt(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 Mi(s,{...e,modelId:r,size:n,sentences:a});s=s.slice(t.length),yield t}for(;s.length>n;){const t=pt(s,e),i=await Mi(s,{...e,modelId:r,size:n,sentences:t});s=s.slice(i.length),yield i}void 0!==c&&(s+=c)}for(;s;){const t=pt(s,e),i=await Mi(s,{...e,modelId:r,size:n,sentences:t});s=s.slice(i.length),yield i}}}async function*Di(t,e){const n=e?.size??1984,r=e?.modelId,i=e?.metaInfo?.size??(await _i.promises.stat(t)).size;let s=Math.trunc(i/2);if(s<=n){let i=tr(await _i.promises.readFile(t));if(s=await Oi(i,r),s<=n)yield pt(i,e);else{let t=pt(i,e);do{const i=await Ri(t,{...e,modelId:r,size:n});yield i,t=t.slice(i.length)}while(t.length)}}else{const i=ReadableStream.from(_i.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+=tr(o),u=pt(s,e);let a=u.pop();if(s.length>=n){const t=await Ri(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 Ri(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 Ri(u,{...e,modelId:r,size:n});u=u.slice(t.length),yield t}}}async function Pi(t,e){const n=e?.size??1984,r=e?.modelId;let i=pt(t,e);const s=[];if(await Oi(t,r)<=n)s.push(i);else do{const t=await Ri(i,{...e,modelId:r,size:n});s.push(t),i=i.slice(t.length)}while(i.length);return s}import{YAMLMap as Xi}from"yaml";var Fi=class{constructor(t){t&&Object.assign(this,t)}};function Bi(t,e){const n={tag:t,collection:"map",nodeClass:class extends Xi{constructor(){super(...arguments),this.tag=t}toJSON(t,n){n={...n,mapAsMap:!1};const r=super.toJSON(t,n);return new e(r)}},identify:t=>t instanceof e};return n}function qi(t,e){let n=t.length===e.length;if(n){const r=Te(t),i=Te(e);n=r.every((t,e)=>t===i[e])}return n}import{defaultsDeep as Ui,get as Gi,omit as Wi,set as Zi}from"lodash-es";import Ji from"path";var Hi=".ai";function Ki(t,e=["."]){if(Ji.isAbsolute(t))return pr.loadSync(t);const n=e.map(e=>pr.loadSync(Ji.resolve(e,t))).filter(Boolean);return Ui({},...n.reverse())}function Qi(t,e){const n={...process.env,...e};return n.HOME||(n.HOME=process.env.USERPROFILE),W(t,{processEnv:n,parsed:n})}function Vi(t,e){let n=pr.loadSync(Ji.resolve(e.configDir,t));n||(n={configDirs:["$XDG_BIN_HOME",e.configDir,"$HOME"],brainDir:Ji.join(e.dataDir,"brain"),agentDirs:[Ji.join(e.dataDir,"agent")],promptDirs:[Ji.join(e.dataDir,"prompt")],chatsDir:Ji.join(e.dataDir,"log","chats"),inputsDir:Ji.join(e.dataDir,"log","inputs")});const r=ts(e);for(const[t,e]of Object.entries(r))n[t]=e;Qi(n,n);const i=n.configDirs;n.AI_CONFIG_BASENAME&&(t=n.AI_CONFIG_BASENAME);const s=Qi(Ki(t,i),n);return Ui(s,Wi(n,Object.keys(r))),rs(s),s}function Yi(t){return Vi(".ai",t)}function ts(t){return{XDG_CONFIG_HOME:t.configDir,XDG_DATA_HOME:t.dataDir,XDG_CACHE_HOME:t.cacheDir,XDG_BIN_HOME:Ji.dirname(t.options.root)}}function es(t,e){t.startsWith("~")&&(t="$HOME"+t.slice(1));return Qi(t,e)}function ns(t,e){return t.map(t=>es(t,e))}function rs(t,e=["configDirs","brainDir","agentDirs","promptDirs","chatsDir","inputsDir"],n){for(const r of e){const e=Gi(t,r);if(!e)continue;let i;Array.isArray(e)&&e.length?i=ns(e,n):"string"==typeof e&&(i=es(e,n)),i&&Zi(t,r,i)}}var{exit:is}=process,ss=!1,os=!1,as=["SIGINT","SIGTERM","exit"],cs=[],us=(t,e)=>t.forEach(t=>process.once(t,e));async function fs(t="shutdown",e=0){if(!ss){ss=!0,"number"==typeof t&&(e=t,t="shutdown");for(const e of cs)try{await e(t)}catch(t){console.warn(`A shutdown handler failed before completing with: ${t.message||t}`)}return is(e)}console.warn(`Shutdown already in progress, ignoring [${t}] signal`)}function hs(t){if(os||ls(),!cs.some(e=>e===t))return cs.push(t),t}function ls(){var t;os||(os=!0,process.exit=t=>{ss||fs(void 0,t).then()},us(as,(t=3e5,()=>{setTimeout(()=>(console.warn(`Could not close resources gracefully after ${t}ms: forcing shutdown`),is(1)),t).unref()})),us(as,fs))}var ms=["<BOS>","<EOS>","<PAD>","<UNK>"],ps=".,!?;?!",ds=[" ","\n","\t","▁"," "],ys=["the","a","an","的","是","在"];function ws(t,e){const n=e?.exclude?function(t){const e=new Set;if(t.controlSymbols&&ms.forEach(t=>e.add(t)),t.punctuation)for(let t=0;t<7;t++)e.add(ps[t]);return t.stopWords&&ys.forEach(t=>e.add(t)),t.whitespace&&ds.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()))),bs(t)}function bs(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)}import{mergeWith as vs}from"lodash-es";var gs=/^\s*@inheritMerge\s*(?:[(]\s*(?<arg>\.start|\.end|false)[)])?/,ks=Symbol("MergeWay"),$s={replace:0,start:1,end:2};function xs(t,...e){return vs(t,...e,(t,e)=>Array.isArray(t)&&Array.isArray(e)?As(t,e):void 0!==t&&"object"!=typeof t?t:void 0)}function As(t,e){let n=t[ks];return void 0===n&&(t=function(t){const e=t[0];let n=".start";if("string"==typeof e){const r=gs.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=$s.start;"false"===n||"no"===n||"not"===n?r=$s.replace:".end"===n&&(r=$s.end);return Object.defineProperty(t,ks,{value:r,enumerable:!1}),t}(t),n=t[ks]),t=n===$s.replace?e:n===$s.end?t.concat(e):e.concat(t),Object.defineProperty(t,ks,{value:n,enumerable:!1}),t}function Ss(t,e=" "){return Es(t).join(e)}function Es(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 Ts(t,e){if(void 0!==t){const n=JSON.stringify(t);if("{}"!==n&&"[]"!==n&&'""'!==n){const t="p="+encodeURIComponent(n);return e?t:"?"+t}}return""}var js=class t extends r{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),Cr.has(n,t)}static run(t,e){const n=this.get(t);if(n)return n.run(e);throw new d(`${t} to run`,this.name)}static runSync(t,e){const n=this.get(t);if(n)return n.runSync(e);throw new d(`${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 d(`${t} to run`,this.name)}static runWithPosSync(t,...e){const n=this.get(t);if(n)return n.runWithPosSync(...e);throw new d(`${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]&&b(`Alias ${t} already exists for ${e}`),this.aliases[t]=e;else if(Array.isArray(t))for(const n of t)this.aliases[n]&&b(`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);b("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),Cr.has(e,t)}isStream(t){let e=this.stream;if(e){const n=this.params;n?.stream&&(e=t?.stream)}return e}},Is={name:{type:"string"},description:{type:"string"},title:{type:"string"},func:{type:"function",assign(t,e,n,r,s){let o=t;const a=typeof t;return s.isExported?o="function"===a?t.toString():t:t&&("string"!==a&&(t=t.toString()),o=i(t,e.scope)),o}},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"]}};js.defineProperties(js,Is);var Cs=Symbol("meta");function Os(t,r,i=!0){if(r&&"object"==typeof r){if("function"==typeof t)return r=i?e({},t[Cs],r):n({},t[Cs],r),t[Cs]=r,t;if(t instanceof js)return t.assign(r)}}function Ns(t){return"function"==typeof t?t[Cs]:t instanceof js?t.toObject():void 0}var Ms=class extends js{constructor(){super(...arguments),this._emitter=new t,this.description="Return event bus",this.result="event"}get emitter(){return this._emitter}func(){return this.emitter}},Rs=new Ms(Ft);import{Cache as zs}from"secondary-cache";import{LRUCache as _s}from"secondary-cache";var Ls=zs;function Ds({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 Ps(t,e){let n=js.get(t);return n||(n=new js(t,{func:Ds,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 zs(e)),n}var Xs=Ps("lrucache");import{defaultsDeep as Fs}from"lodash-es";var Bs="A client transport has not been set. Use ClientTools.setTransport() or transport.mount(ClientTools) first.",qs=class t extends js{static get apiRoot(){return this._transport||b(Bs,"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||b(Bs,"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):b(`${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,r){const i=this.constructor;if(i._transport)return r=Fs(r,this.fetchOptions),i._transport.fetch(this.name,t,e,n,r);b(Bs,"ClientTools")}async func(t){return await this.fetch(t)}},Us={...x};qs.defineProperties(qs,Us);var Gs=class extends qs{async fetch(t,e,n,r){return t||(t={}),e?.startsWith("$")&&(t.act=e,e="post"),await super.fetch(t,e,n,r)}async _func(t,e,n){return await this.fetch(e,t,null,n)}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))}}},Ws={methods:{type:"array",assign(t,e,n,r,i){i?.isExported||e.assignMethods(t)}}};Gs.defineProperties(Gs,Ws);var Zs=class extends Gs{async fetch(t,e,...n){if(t||(t={}),e&&"res"===this.action){if("get"===e||"delete"===e){let n=t.id;return n||b("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,...n)}};import{defaultsDeep as Js}from"lodash-es";var Hs=class extends Zs{constructor(){super(...arguments),this._sseListeners={},this._forwardEvents=new Set,this.description="subscribe server event",this.ebListener=async function(...t){const e=t[0];let n=t[1];const r=this.type;("string"!=typeof e||n&&"object"!=typeof n||t.length>2)&&(n=t,e&&e===this.target.name&&(n=t.slice(1))),this.target.publish&&await this.target.publish({data:n,event:r})}}static setPubSubTransport(t){t?.setApiRoot&&this.apiRoot&&t.setApiRoot(this.apiRoot),this._pubSubTransport=t}static get pubSubTransport(){if(!this._pubSubTransport)throw new Error("EventClient pubSubTransport not set");return this._pubSubTransport}get clientId(){return this._stream?.clientId}async getEvtSource(){let t=this._stream;return t&&2!==t.readyState||(t=await this.initEventStream(this._streamEvents)),t}get active(){return!!this._stream&&2!==this._stream.readyState}async setActive(t){t!==this.active&&(t?await this.initEventStream(this._streamEvents):this._stream&&this.close())}async 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?{event:e}:void 0,r=this._stream=await this.constructor.pubSubTransport.connect(this.name,n);return r.clientId&&(this.fetchOptions=Js({clientId:r.clientId},this.fetchOptions)),Object.entries(this._sseListeners).forEach(([t,e])=>{r.on(t,e)}),this._streamEvents=e,r}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){this.active||await this.initEventStream(t);const e=await this.sub({event:t});"string"==typeof t&&(t=[t]);const n=await this.getEvtSource();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=await this.getEvtSource();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.setActive(!1),await this.initEventStream(t),t)return await this.subscribe(t)}close(){const t=this._stream;if(t)return this._stream=void 0,t.close()}},Ks=new Hs(Xt);import{getAllNames as Qs}from"util-ex";var Vs=class t extends js{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){}},Ys={...x};Vs.defineProperties(Vs,Ys);var to=class extends Vs{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);Qs(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 d(e,this.name)}},eo={methods:{type:"array"}};to.defineProperties(to,eo);var no=class extends to{constructor(t,e={}){super(t,e),this.action="res",this.params={id:{type:"string"},val:{type:"any"}}}static{this.SpecialRpcMethodNames=$}getMethodFromParams(t){let e=t?._req?.method?.toLowerCase();return"get"===e&&void 0===t.id?e="list":t.act&&(e=t.act),e}castParams(t){return void 0!==t.id&&(t.id=this.cast("id",t.id)),t}},ro=Rs.runSync(),io="client:",so=class t extends no{constructor(){super(...arguments),this.description="subscribe server event",this.result="event",this.depends={[Ft]:Rs}}static{this.autoInjectToLocalBus=!1}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(t,e,n)}static ebListener(t,...e){this.pubSubTransport?.publish(t,e)}static alreadyForward(t){const e=ro.listeners(t);for(const t of e)if(t===this._boundEbListener)return!0}publishServerEvent(t,e){return this.constructor.publish(t,e)}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)||ro.on(r,n._boundEbListener)}unforward(t){"string"==typeof t&&(t=[t]);const e=this.constructor;if(e._boundEbListener)for(const n of t)ro.off(n,e._boundEbListener)}list({_req:t,_res:e,event:n}){if(this.pubSubTransport)return this.pubSubTransport.connect({req:t,res:e,events:n});b("PubSub transport not available","list",l.NotImplemented)}$sub({event:t,_req:e}){if(this.pubSubTransport||b("PubSub transport not available","sub",l.NotImplemented),t){this.forward(t);const n=e&&this.pubSubTransport.getSessionFromReq?.(e);return n?(this.pubSubTransport.subscribe(n,Array.isArray(t)?t:[t]),{forward:!0,subscribed:!0,event:t,clientId:n.clientId}):(this.pubSubTransport.getSessionFromReq?console.warn("$sub: No session found for request"):e?console.warn(`$sub: The ${this.pubSubTransport.name} Transport does not support dynamic subscription`):console.warn("$sub: missing _req"),{forward:!0,event:t})}b("event is required","sub",l.InvalidArgument)}$unsub({event:t,_req:e}){if(this.pubSubTransport||b("PubSub transport not available","unsub",l.NotImplemented),t){this.unforward(t);const n=e&&this.pubSubTransport.getSessionFromReq?.(e);return n?(this.pubSubTransport.unsubscribe(n,Array.isArray(t)?t:[t]),{forward:!1,subscribed:!1,event:t,clientId:n.clientId}):(this.pubSubTransport.getSessionFromReq?console.warn("$unsub: No session found for request"):e?console.warn(`$unsub: The ${this.pubSubTransport.name} Transport does not support dynamic subscription`):console.warn("$sub: missing _req"),{forward:!1,event:t})}b("event is required","unsub",l.InvalidArgument)}$publish({event:t,data:e,_req:n}){if(t&&e){const r=n&&this.pubSubTransport?.getSessionFromReq?.(n),i=r?.clientId,s=this.constructor;"string"==typeof t&&(t=[t]);for(const n of t)s.autoInjectToLocalBus&&ro.emit(io+n,e,{event:n,sender:r}),this.publishServerEvent(n,e);return{event:t,senderId:i}}b("event or data is required","pub",l.InvalidArgument)}isStream(t){return"list"===this.getMethodFromParams(t)}},oo=new so(Xt);function ao(){Rs.register(),Xs.register()}export{k as PASSING_SCORE,$ as ActionNames,x as RemoteToolFuncSchema,s as AbortError,o as AbortErrorCode,a as AlreadyExistsError,c as AlreadyExistsErrorCode,u as BaseError,f as CommonError,h as createError,l as ErrorCode,m as InternalErrorCode,p as NotFoundErrorCode,d as NotFoundError,y as NotImplementedErrorCode,w as NotImplementationError,b as throwError,S as parseDateFormat,N as DefaultDateFormat,M as toDateTime,R as textToDate,z as dateToText,T as add,j as formatISO,I as parseISO,C as toDate,_ as AITextGenerationFinishReasons,L as AIMessageTypes,D as AIChatRoles,P as StrangeHumanName,X as messagesToText,Q as sortedValues,V as FewShotPromptTemplate,et as PromptExampleSelector,F as StringTemplate,B as EnvStringTemplate,q as FStringTemplate,U as GolangStringTemplate,G as expandEnv,W as expandObjEnv,Z as defaultTemplateFormat,J as getEnvVairables,H as createHfValueFunc,pt as splitSentence,dt as completeSentences,wt as concatText,bt as isSentenceEnding,vt as isSectionString,gt as isTitleString,kt as isListItemString,$t as isSepLineString,xt as isPunctuationChar,St as isLangUsingSpaces,Et as findIndexNonEmptyFrom,Tt as removeMarkdownBold,jt as removeMarkdownItalic,It as removeMarkdownBoldAndItalic,Ct as splitParagraph,Ot as truncTo,Nt as sleep,Mt as wait,Rt as yieldExec,Xt as EventName,Ft as EventBusName,Bt as backendEventable,_t as EventEmitter,Lt as eventable,Dt as states,Pt as wrapEventEmitter,ae as uuid,Kt as v1,Qt as v4,Vt as v5,Yt as v6,te as v7,ee as stringify,ne as parse,re as validate,ie as version,se as NIL,ke as HashAlgorithm,Se as xxhash32,Ee as xxhash64,Te as xxhash,je as xxhashAsStr,Ie as canonicalize,Oe as base32768,Ne as hashStream,Me as hash,Re as hashObject,qt as nanoid,_e as SSEChannelAlreadyClosedErrCode,Le as SSEChannel,De as isWebStream,Pe as RStreamErrCode,Xe as ResponseRStreamErrCode,Fe as ReadableStreamError,Be as getResponseErrorReadableStream,qe as createEmptyReadableStream,Ge as createEventStreamTransformer,We as trimStartOfStreamHelper,Ze as AIStream,Je as readableFromAsyncIterable,He as createCallbacksTransformer,Ke as extNameLevel,Qe as FilenameReservedRegex,Ve as getMultiLevelExtname,Ye as isValidFilename,tn as isValidFilepath,en as sanitizeFilename,nn as sanitizeFilepath,rn as WindowsReservedNameRegex,an as isModelNameMatched,cn as getAllEnumKeys,pn as parseObjectArguments,yn as ObjectArgsToArgsInfo,wn as simplifyObjectArguments,bn as parseObjectArgumentInfos,vn as ChoiceArgProcessor,gn as TemplateArgProcessor,kn as AIArgProcessor,$n as isQuoted,xn as isStrWrapped,An as ensureQuoted,Sn as quoteStr,In as parseObjectArgInfo,Cn as parseObjectArgumentsAsArgInfos,On as parseCommand,Mn as replaceWithPlaceholder,Rn as restoreFromPlacehoders,Dn as parseJsJson,Pn as parseJsJsonSimpleSync,Bn as filterValidFnScope,qn as getKeysPath,Gn as createEndWithRepetitionDetector,Kn as fileIsExists,Qn as loadFileFromPaths,Yn as loadTextFromPaths,tr as decodeCharset,er as readFilenamesRecursiveSync,nr as getRealFilepath,rr as hashFile,ir as getFileMetaInfo,sr as getHashAlgoBySize,or as detectCharset,br as getConfigFileNames,vr as getConfigs,gr as saveConfigFile,mr as mimeType,pr as ConfigFile,dr as registerYamlTag,yr as parseYaml,wr as stringifyYaml,Sr as jsonFilterToWhere,Er as matchUrlProtocol,Tr as paramsSizeToScaleStr,jr as scaleStrToParamsSize,Ir as jsonToMarkdownStr,Cr as IntSet,_r as DefaultAsyncSemaphoreCapacity,Pr as BinarySemaphore,Xr as Semaphore,Fr as RateLimit,qr as SignalGate,Zr as ToolAsyncMultiTaskBit,Jr as ToolAsyncCancelableBit,Hr as ToolAsyncPriorityBit,Kr as AsyncFeatureBits,Qr as AsyncFeatures,Vr as TaskAbortController,Yr as CancelableAbility,ei as makeToolFuncCancelable,ni as countRegexMatches,si as memoize,ci as getPackageDir,fi as isSubdirectory,hi as hasDirectoryIn,li as assignDirs,mi as pruneSubdirectories,pi as pruneSubdirectoriesInPlace,di as normalizePath,bi as isRegExp,vi as stripConsoleColor,Ti as LLM_TOKENIZER_NAMES,ji as LLM_TOKENIZER_NAMES_MAP,Ii as getLLMTokenizer,Ci as encodeLLMTokens,Oi as countLLMTokens,Ni as formatTextWithSpace,Mi as truncateToTokenLimit,Ri as truncateToTokenLimitEx,zi as truncateByToken,Li as readTextFileChunks,Di as readTextFileChunksEx,Pi as splitChunks,Fi as YamlTypeBaseObject,Bi as createYamlObjectTag,qi as isSameString,Hi as DEFAULT_CONFIG_NAME,Ki as loadConfigFile,Qi as expandConfig,Vi as loadConfig,Yi as loadAIConfig,ts as getXDGConfigs,es as expandPath,ns as expandPaths,rs as expandPathInObject,as as SHUTDOWN_SIGNALS,fs as shutdown,hs as beforeShutdown,ls as initShutdown,ws as calcPerplexity,bs as calcPerplexitySimple,ks as ArrayMergeWaySymbol,$s as ArrayMergeWay,xs as defaultsWithConcat,As as mergeArray,Ss as joinSplitWords,Es as splitWords,Ts as genUrlParamsStr,v as createAbilityInjector,g as toRegExp,js as ToolFunc,Is as ToolFuncSchema,Cs as FuncMetaSymbol,Os as funcWithMeta,Ns as funcGetMeta,qs as ClientTools,Us as ClientToolFuncSchema,Vs as ServerTools,Ys as ServerToolFuncSchema,Ms as EventToolFunc,Rs as event,Ls as SecondaryCache,Ds as _lrucache,Ps as createLRUCache,Xs as lrucache,_s as LRUCache,Gs as RpcMethodsClientTool,Ws as RpcMethodsClientToolSchema,Zs as ResClientTools,Hs as EventClient,Ks as eventClient,to as RpcMethodsServerTool,eo as RpcMethodsServerToolSchema,no as ResServerTools,io as ClientEventPrefix,so as EventServer,oo as eventServer,ao as registerCoreTools};
@@ -1 +0,0 @@
1
- import n from"net";async function r(r,t=10){return new Promise((o,e)=>{void 0===r?r=0:("string"==typeof r&&(r=parseInt(r)),r>=0||(r=0));const s=n.createServer();s.on("error",n=>{"EADDRINUSE"===n.code&&(r++,--t>0)?s.listen(r):e(n)}),s.on("listening",async()=>{const n=s.address().port;s.close(r=>{r?e(r):o(n)})}),s.listen(r)})}export{r as findPort};
@@ -1,3 +0,0 @@
1
- declare function findPort(port: string | number, portRetryCount?: number): Promise<number>;
2
-
3
- export { findPort as f };
@@ -1,3 +0,0 @@
1
- declare function findPort(port: string | number, portRetryCount?: number): Promise<number>;
2
-
3
- export { findPort as f };