@isdk/ai-tool 0.7.0 → 0.7.1

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 (296) hide show
  1. package/dist/{chunk-LNTIQQNN.mjs → chunk-4XRPAC7C.mjs} +1 -1
  2. package/dist/funcs.d.mts +1 -1
  3. package/dist/funcs.d.ts +1 -1
  4. package/dist/funcs.mjs +1 -1
  5. package/dist/{index-BCco-g_I.d.mts → index-DEUnmyUq.d.mts} +12 -1
  6. package/dist/{index-BCco-g_I.d.ts → index-DEUnmyUq.d.ts} +12 -1
  7. package/dist/index.d.mts +3 -3
  8. package/dist/index.d.ts +3 -3
  9. package/dist/index.js +1 -1
  10. package/dist/index.mjs +1 -1
  11. package/docs/api/classes/BinarySemaphore.md +25 -25
  12. package/docs/api/classes/CancelableAbility.md +25 -25
  13. package/docs/api/classes/ClientToolTransport.md +12 -12
  14. package/docs/api/classes/ClientTools.md +65 -61
  15. package/docs/api/classes/EventClient.md +105 -90
  16. package/docs/api/classes/EventServer.md +96 -88
  17. package/docs/api/classes/EventToolFunc.md +52 -52
  18. package/docs/api/classes/FewShotPromptTemplate.md +11 -11
  19. package/docs/api/classes/HttpClientToolTransport.md +13 -13
  20. package/docs/api/classes/HttpServerToolTransport.md +24 -16
  21. package/docs/api/classes/IntSet.md +12 -12
  22. package/docs/api/classes/PromptExampleSelector.md +9 -9
  23. package/docs/api/classes/ReadableStreamError.md +2 -2
  24. package/docs/api/classes/ResClientTools.md +560 -73
  25. package/docs/api/classes/ResServerTools.md +560 -74
  26. package/docs/api/classes/RpcMethodsClientTool.md +3275 -0
  27. package/docs/api/classes/RpcMethodsServerTool.md +3224 -0
  28. package/docs/api/classes/SSEChannel.md +16 -16
  29. package/docs/api/classes/Semaphore.md +26 -26
  30. package/docs/api/classes/ServerToolTransport.md +13 -13
  31. package/docs/api/classes/ServerTools.md +61 -57
  32. package/docs/api/classes/SignalGate.md +9 -9
  33. package/docs/api/classes/SseClientPubSubTransport.md +3 -3
  34. package/docs/api/classes/SseServerPubSubTransport.md +8 -8
  35. package/docs/api/classes/TaskAbortController.md +8 -8
  36. package/docs/api/classes/ToolFunc.md +50 -50
  37. package/docs/api/classes/ToolTransport.md +7 -7
  38. package/docs/api/classes/YamlTypeBaseObject.md +2 -2
  39. package/docs/api/enumerations/AsyncFeatureBits.md +4 -4
  40. package/docs/api/enumerations/AsyncFeatures.md +4 -4
  41. package/docs/api/enumerations/HashAlgorithm.md +12 -12
  42. package/docs/api/functions/AIArgProcessor.md +1 -1
  43. package/docs/api/functions/AIStream.md +1 -1
  44. package/docs/api/functions/ChoiceArgProcessor.md +1 -1
  45. package/docs/api/functions/DefaultDateFormat.md +1 -1
  46. package/docs/api/functions/ObjectArgsToArgsInfo.md +1 -1
  47. package/docs/api/functions/RateLimit.md +1 -1
  48. package/docs/api/functions/TemplateArgProcessor.md +1 -1
  49. package/docs/api/functions/assignDirs.md +1 -1
  50. package/docs/api/functions/backendEventable.md +1 -1
  51. package/docs/api/functions/beforeShutdown.md +1 -1
  52. package/docs/api/functions/calcPerplexity.md +1 -1
  53. package/docs/api/functions/calcPerplexitySimple.md +1 -1
  54. package/docs/api/functions/completeSentences.md +1 -1
  55. package/docs/api/functions/concatText.md +1 -1
  56. package/docs/api/functions/countLLMTokens.md +1 -1
  57. package/docs/api/functions/countRegexMatches.md +1 -1
  58. package/docs/api/functions/createCallbacksTransformer.md +1 -1
  59. package/docs/api/functions/createEmptyReadableStream.md +1 -1
  60. package/docs/api/functions/createEndWithRepetitionDetector.md +1 -1
  61. package/docs/api/functions/createEventStreamTransformer.md +1 -1
  62. package/docs/api/functions/createLRUCache.md +1 -1
  63. package/docs/api/functions/createYamlObjectTag.md +1 -1
  64. package/docs/api/functions/dateToText.md +1 -1
  65. package/docs/api/functions/decodeCharset.md +1 -1
  66. package/docs/api/functions/defaultsWithConcat.md +1 -1
  67. package/docs/api/functions/detectCharset.md +1 -1
  68. package/docs/api/functions/encodeLLMTokens.md +1 -1
  69. package/docs/api/functions/ensureQuoted.md +1 -1
  70. package/docs/api/functions/expandConfig.md +1 -1
  71. package/docs/api/functions/expandPath.md +1 -1
  72. package/docs/api/functions/expandPathInObject.md +1 -1
  73. package/docs/api/functions/expandPaths.md +1 -1
  74. package/docs/api/functions/fileIsExists.md +1 -1
  75. package/docs/api/functions/filterValidFnScope.md +1 -1
  76. package/docs/api/functions/findIndexNonEmptyFrom.md +1 -1
  77. package/docs/api/functions/findPort.md +1 -1
  78. package/docs/api/functions/formatTextWithSpace.md +1 -1
  79. package/docs/api/functions/funcGetMeta.md +1 -1
  80. package/docs/api/functions/funcWithMeta.md +1 -1
  81. package/docs/api/functions/genUrlParamsStr.md +1 -1
  82. package/docs/api/functions/getAllEnumKeys.md +1 -1
  83. package/docs/api/functions/getConfigFileNames.md +1 -1
  84. package/docs/api/functions/getConfigs.md +1 -1
  85. package/docs/api/functions/getFileMetaInfo.md +1 -1
  86. package/docs/api/functions/getHashAlgoBySize.md +1 -1
  87. package/docs/api/functions/getKeysPath.md +1 -1
  88. package/docs/api/functions/getLLMTokenizer.md +1 -1
  89. package/docs/api/functions/getPackageDir.md +1 -1
  90. package/docs/api/functions/getRealFilepath.md +1 -1
  91. package/docs/api/functions/getResponseErrorReadableStream.md +1 -1
  92. package/docs/api/functions/getXDGConfigs.md +1 -1
  93. package/docs/api/functions/hasDirectoryIn.md +1 -1
  94. package/docs/api/functions/hash.md +1 -1
  95. package/docs/api/functions/hashFile.md +1 -1
  96. package/docs/api/functions/hashObject.md +1 -1
  97. package/docs/api/functions/hashStream.md +1 -1
  98. package/docs/api/functions/initShutdown.md +1 -1
  99. package/docs/api/functions/isLangUsingSpaces.md +1 -1
  100. package/docs/api/functions/isListItemString.md +1 -1
  101. package/docs/api/functions/isModelNameMatched.md +1 -1
  102. package/docs/api/functions/isPunctuationChar.md +1 -1
  103. package/docs/api/functions/isQuoted.md +1 -1
  104. package/docs/api/functions/isRegExp.md +1 -1
  105. package/docs/api/functions/isSameString.md +1 -1
  106. package/docs/api/functions/isSectionString.md +1 -1
  107. package/docs/api/functions/isSentenceEnding.md +1 -1
  108. package/docs/api/functions/isSepLineString.md +1 -1
  109. package/docs/api/functions/isStrWrapped.md +1 -1
  110. package/docs/api/functions/isSubdirectory.md +1 -1
  111. package/docs/api/functions/isTitleString.md +1 -1
  112. package/docs/api/functions/isWebStream.md +1 -1
  113. package/docs/api/functions/joinSplitWords.md +1 -1
  114. package/docs/api/functions/jsonFilterToWhere.md +1 -1
  115. package/docs/api/functions/jsonToMarkdownStr.md +1 -1
  116. package/docs/api/functions/loadAIConfig.md +1 -1
  117. package/docs/api/functions/loadConfig.md +1 -1
  118. package/docs/api/functions/loadConfigFile.md +1 -1
  119. package/docs/api/functions/loadFileFromPaths.md +1 -1
  120. package/docs/api/functions/loadTextFromPaths.md +1 -1
  121. package/docs/api/functions/lrucache.md +1 -1
  122. package/docs/api/functions/makeToolFuncCancelable.md +1 -1
  123. package/docs/api/functions/matchUrlProtocol.md +1 -1
  124. package/docs/api/functions/memoize.md +1 -1
  125. package/docs/api/functions/mergeArray.md +1 -1
  126. package/docs/api/functions/messagesToText.md +1 -1
  127. package/docs/api/functions/normalizePath.md +1 -1
  128. package/docs/api/functions/paramsSizeToScaleStr.md +1 -1
  129. package/docs/api/functions/parseCommand.md +1 -1
  130. package/docs/api/functions/parseJsJson.md +1 -1
  131. package/docs/api/functions/parseJsJsonSimpleSync.md +1 -1
  132. package/docs/api/functions/parseObjectArgInfo.md +1 -1
  133. package/docs/api/functions/parseObjectArgumentInfos.md +1 -1
  134. package/docs/api/functions/parseObjectArguments.md +1 -1
  135. package/docs/api/functions/parseObjectArgumentsAsArgInfos.md +1 -1
  136. package/docs/api/functions/pruneSubdirectories.md +1 -1
  137. package/docs/api/functions/pruneSubdirectoriesInPlace.md +1 -1
  138. package/docs/api/functions/quoteStr.md +1 -1
  139. package/docs/api/functions/readFilenamesRecursiveSync.md +1 -1
  140. package/docs/api/functions/readTextFileChunks.md +1 -1
  141. package/docs/api/functions/readTextFileChunksEx.md +1 -1
  142. package/docs/api/functions/readableFromAsyncIterable.md +1 -1
  143. package/docs/api/functions/registerCoreTools.md +1 -1
  144. package/docs/api/functions/removeMarkdownBold.md +1 -1
  145. package/docs/api/functions/removeMarkdownBoldAndItalic.md +1 -1
  146. package/docs/api/functions/removeMarkdownItalic.md +1 -1
  147. package/docs/api/functions/replaceWithPlaceholder.md +1 -1
  148. package/docs/api/functions/restoreFromPlacehoders.md +1 -1
  149. package/docs/api/functions/saveConfigFile.md +1 -1
  150. package/docs/api/functions/scaleStrToParamsSize.md +1 -1
  151. package/docs/api/functions/shutdown.md +1 -1
  152. package/docs/api/functions/simplifyObjectArguments.md +1 -1
  153. package/docs/api/functions/sleep.md +1 -1
  154. package/docs/api/functions/sortedValues.md +1 -1
  155. package/docs/api/functions/splitChunks.md +1 -1
  156. package/docs/api/functions/splitParagraph.md +1 -1
  157. package/docs/api/functions/splitSentence.md +1 -1
  158. package/docs/api/functions/splitWords.md +1 -1
  159. package/docs/api/functions/stripConsoleColor.md +1 -1
  160. package/docs/api/functions/textToDate.md +1 -1
  161. package/docs/api/functions/toDateTime.md +1 -1
  162. package/docs/api/functions/trimStartOfStreamHelper.md +1 -1
  163. package/docs/api/functions/truncTo.md +1 -1
  164. package/docs/api/functions/truncateByToken.md +1 -1
  165. package/docs/api/functions/truncateToTokenLimit.md +1 -1
  166. package/docs/api/functions/truncateToTokenLimitEx.md +1 -1
  167. package/docs/api/functions/uuid.md +1 -1
  168. package/docs/api/functions/wait.md +1 -1
  169. package/docs/api/functions/xxhash.md +1 -1
  170. package/docs/api/functions/xxhash32.md +1 -1
  171. package/docs/api/functions/xxhash64.md +1 -1
  172. package/docs/api/functions/xxhashAsStr.md +1 -1
  173. package/docs/api/functions/yieldExec.md +1 -1
  174. package/docs/api/globals.md +6 -0
  175. package/docs/api/interfaces/AIChatAssistantMessageParam.md +12 -12
  176. package/docs/api/interfaces/AIChatContentPartImage.md +3 -3
  177. package/docs/api/interfaces/AIChatContentPartText.md +3 -3
  178. package/docs/api/interfaces/AIChatMessageParamBase.md +7 -7
  179. package/docs/api/interfaces/AIChatMessageToolCall.md +4 -4
  180. package/docs/api/interfaces/AIChatSystemMessageParam.md +9 -9
  181. package/docs/api/interfaces/AIChatToolChoiceFuncObject.md +3 -3
  182. package/docs/api/interfaces/AIChatToolChoiceObject.md +2 -2
  183. package/docs/api/interfaces/AIChatToolFunc.md +5 -5
  184. package/docs/api/interfaces/AIChatToolFuncParam.md +3 -3
  185. package/docs/api/interfaces/AIChatToolMessageParam.md +10 -10
  186. package/docs/api/interfaces/AIChatToolParam.md +2 -2
  187. package/docs/api/interfaces/AIChatToolTypeObject.md +2 -2
  188. package/docs/api/interfaces/AIChatUserMessageParam.md +13 -13
  189. package/docs/api/interfaces/AIChoiceConfig.md +8 -8
  190. package/docs/api/interfaces/AIResult.md +6 -6
  191. package/docs/api/interfaces/AIStreamParser.md +2 -2
  192. package/docs/api/interfaces/AIStreamParserOptions.md +2 -2
  193. package/docs/api/interfaces/BaseFunc.md +15 -15
  194. package/docs/api/interfaces/BaseFuncItem.md +14 -14
  195. package/docs/api/interfaces/BinarySemaphoreAcquireOptions.md +2 -2
  196. package/docs/api/interfaces/BinarySemaphoreOptions.md +5 -5
  197. package/docs/api/interfaces/BinarySemaphoreReleaseOptions.md +2 -2
  198. package/docs/api/interfaces/BinarySemaphoreReleaserFunc.md +3 -3
  199. package/docs/api/interfaces/CancelableAbilityOptions.md +4 -4
  200. package/docs/api/interfaces/ClientFuncItem.md +17 -17
  201. package/docs/api/interfaces/EventClientFuncParams.md +5 -5
  202. package/docs/api/interfaces/EventServerFuncParams.md +6 -6
  203. package/docs/api/interfaces/FewShotPromptTemplateOptions.md +6 -6
  204. package/docs/api/interfaces/FuncItem.md +15 -15
  205. package/docs/api/interfaces/FuncParam.md +5 -5
  206. package/docs/api/interfaces/FuncParams.md +1 -1
  207. package/docs/api/interfaces/Funcs.md +1 -1
  208. package/docs/api/interfaces/HashAlgoParams.md +4 -4
  209. package/docs/api/interfaces/IClientToolTransport.md +7 -7
  210. package/docs/api/interfaces/IFileMetaInfo.md +8 -8
  211. package/docs/api/interfaces/IPubSubClientTransport.md +3 -3
  212. package/docs/api/interfaces/IPubSubServerTransport.md +9 -9
  213. package/docs/api/interfaces/IReadTextFileChunksOptions.md +11 -11
  214. package/docs/api/interfaces/IServerToolTransport.md +8 -8
  215. package/docs/api/interfaces/IToolTransport.md +5 -5
  216. package/docs/api/interfaces/ITruncateToTokenLimitOptions.md +10 -10
  217. package/docs/api/interfaces/JsonFilter.md +1 -1
  218. package/docs/api/interfaces/ParseObjectArgumentOptions.md +11 -11
  219. package/docs/api/interfaces/ProbabilityItem.md +4 -4
  220. package/docs/api/interfaces/PromptExampleSelectorOptions.md +3 -3
  221. package/docs/api/interfaces/PubSubClient.md +2 -2
  222. package/docs/api/interfaces/PubSubClientStream.md +9 -9
  223. package/docs/api/interfaces/PubSubServerSession.md +7 -7
  224. package/docs/api/interfaces/RemoteFuncItem.md +17 -17
  225. package/docs/api/interfaces/ReplacePlacehoderOptions.md +5 -5
  226. package/docs/api/interfaces/ResClientFuncParams.md +5 -5
  227. package/docs/api/interfaces/ResServerFuncParams.md +14 -10
  228. package/docs/api/interfaces/RpcMethodsClientFuncParams.md +25 -0
  229. package/docs/api/interfaces/RpcMethodsServerFuncParams.md +61 -0
  230. package/docs/api/interfaces/SectionStringOptions.md +3 -3
  231. package/docs/api/interfaces/SemaphoreOptions.md +7 -7
  232. package/docs/api/interfaces/SemaphoreTaskItem.md +5 -5
  233. package/docs/api/interfaces/ServerFuncItem.md +18 -18
  234. package/docs/api/interfaces/ServerFuncParams.md +4 -3
  235. package/docs/api/interfaces/SplitSentenceOptions.md +5 -5
  236. package/docs/api/interfaces/StreamCallbacksAndOptions.md +5 -5
  237. package/docs/api/interfaces/TaskAbortControllers.md +1 -1
  238. package/docs/api/interfaces/TaskPromise.md +2 -2
  239. package/docs/api/interfaces/ToolFuncPackage.md +4 -4
  240. package/docs/api/type-aliases/AIChatContentPart.md +1 -1
  241. package/docs/api/type-aliases/AIChatMessageParam.md +1 -1
  242. package/docs/api/type-aliases/AIChatRole.md +1 -1
  243. package/docs/api/type-aliases/AIChatToolChoiceParam.md +1 -1
  244. package/docs/api/type-aliases/AIMessageType.md +1 -1
  245. package/docs/api/type-aliases/AIModelNameRule.md +1 -1
  246. package/docs/api/type-aliases/AIModelNameRuleFn.md +1 -1
  247. package/docs/api/type-aliases/AIModelNameRules.md +1 -1
  248. package/docs/api/type-aliases/AITextGenerationFinishReason.md +1 -1
  249. package/docs/api/type-aliases/ActionName.md +1 -1
  250. package/docs/api/type-aliases/ArrayMergeWay.md +1 -1
  251. package/docs/api/type-aliases/AsyncTaskId.md +1 -1
  252. package/docs/api/type-aliases/BeforeShutdownListener.md +1 -1
  253. package/docs/api/type-aliases/EventErrorListenerFn.md +1 -1
  254. package/docs/api/type-aliases/EventListenerFn.md +1 -1
  255. package/docs/api/type-aliases/FuncParamType.md +1 -1
  256. package/docs/api/type-aliases/PromptExamples.md +1 -1
  257. package/docs/api/type-aliases/PubSubClientId.md +1 -1
  258. package/docs/api/type-aliases/PubSubCtx.md +1 -1
  259. package/docs/api/type-aliases/RpcMethodHandler.md +1 -1
  260. package/docs/api/type-aliases/SemaphoreIsReadyFuncType.md +1 -1
  261. package/docs/api/type-aliases/TFunc.md +1 -1
  262. package/docs/api/variables/AIChatRoles.md +1 -1
  263. package/docs/api/variables/AIMessageTypes.md +1 -1
  264. package/docs/api/variables/AITextGenerationFinishReasons.md +1 -1
  265. package/docs/api/variables/ActionNames.md +1 -1
  266. package/docs/api/variables/ArrayMergeWay.md +1 -1
  267. package/docs/api/variables/ArrayMergeWaySymbol.md +1 -1
  268. package/docs/api/variables/ClientToolFuncSchema.md +1 -1
  269. package/docs/api/variables/DEFAULT_CONFIG_NAME.md +1 -1
  270. package/docs/api/variables/DefaultAsyncSemaphoreCapacity.md +1 -1
  271. package/docs/api/variables/EventBusName.md +1 -1
  272. package/docs/api/variables/EventName.md +1 -1
  273. package/docs/api/variables/FuncMetaSymbol.md +1 -1
  274. package/docs/api/variables/LLM_TOKENIZER_NAMES.md +1 -1
  275. package/docs/api/variables/LLM_TOKENIZER_NAMES_MAP.md +1 -1
  276. package/docs/api/variables/PASSING_SCORE.md +1 -1
  277. package/docs/api/variables/RStreamErrCode.md +1 -1
  278. package/docs/api/variables/RemoteToolFuncSchema.md +1 -1
  279. package/docs/api/variables/ResponseRStreamErrCode.md +1 -1
  280. package/docs/api/variables/RpcMethodsClientToolSchema.md +49 -0
  281. package/docs/api/variables/RpcMethodsServerToolSchema.md +21 -0
  282. package/docs/api/variables/SHUTDOWN_SIGNALS.md +1 -1
  283. package/docs/api/variables/SSEChannelAlreadyClosedErrCode.md +1 -1
  284. package/docs/api/variables/SecondaryCache.md +1 -1
  285. package/docs/api/variables/ServerToolFuncSchema.md +1 -1
  286. package/docs/api/variables/StrangeHumanName.md +1 -1
  287. package/docs/api/variables/ToolAsyncCancelableBit.md +1 -1
  288. package/docs/api/variables/ToolAsyncMultiTaskBit.md +1 -1
  289. package/docs/api/variables/ToolAsyncPriorityBit.md +1 -1
  290. package/docs/api/variables/ToolFuncSchema.md +1 -1
  291. package/docs/api/variables/base32768.md +1 -1
  292. package/docs/api/variables/event.md +1 -1
  293. package/docs/api/variables/eventClient.md +1 -1
  294. package/docs/api/variables/eventServer.md +1 -1
  295. package/docs/api/variables/lrucache.md +1 -1
  296. package/package.json +3 -3
@@ -1 +1 @@
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 O,toDate as I}from"date-fns";var C="MMMM d, y 'at' h:m:s b 'GMT'x";function N(t){return t&&(C=t),C}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=C){return S(t,e,new Date)}function z(t,e=C){return A(t,e)}var L=["stop","length","content_filter","tool_calls","function_call","abort","error","other",null],_=["human","ai","generic","system","tool"],X=["user","assistant","system","tool","tool_calls"],D="陌生人";function P(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 Ot(t,e){return t=jt(t=Tt(t,e),e)}function It(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 Ct(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 Lt,eventable as _t,states as Xt,wrapEventEmitter as Dt}from"events-ex";var Pt="event",Ft="event-bus";var Bt=zt(function(t){return class{static get emitter(){if(!this._emitter){const t=this.get(Ft)?.emitter;t&&(this._emitter=t,this.prototype._events=t._events)}return this._emitter}get emitter(){return this.constructor._emitter}on(e,n){const r=t.emitter;if(!r)throw new TypeError("EventBackend required");return r.on(e,n)}once(e,n){const r=t.emitter;if(!r)throw new TypeError("EventBackend required");return r.once(e,n)}off(e,n){const r=t.emitter;if(!r)throw new TypeError("EventBackend required");return r.off(e,n)}emit(e,...n){const r=t.emitter;if(!r)throw new TypeError("EventBackend required");return"error"===e?this.emitError.apply(this,n):r.emit.call(this,e,this.name,...n)}emitError(e,...n){const r=t.emitter;if(!r)throw new TypeError("EventBackend required");return r.emit.call(this,"error",e,this.name,...n)}async emitAsync(e,...n){const r=t.emitter;if(!r)throw new TypeError("EventBackend required");return r.emitAsync.call(this,e,this.name,...n)}}},!0);function qt(t,e){return!t||t.some(t=>t instanceof RegExp?t.test(e):t===e)}var Ut=498,Gt=class{get active(){return this._active}set active(t){t!==this._active&&(t?(this.pingTimer&&(clearInterval(this.pingTimer),this.pingTimer=void 0),this.options.pingInterval>0&&(this.pingTimer=setInterval(()=>this.publish(),this.options.pingInterval))):(this.clients.size&&this.clearClients(),this.pingTimer&&(clearInterval(this.pingTimer),this.pingTimer=void 0)),this._active=t)}constructor(t){this.options=Object.assign({},{pingInterval:3e3,maxStreamDuration:3e4,clientRetryInterval:1e3,startId:1,historySize:100,rewind:0,cors:!1},t),this.nextID=this.options.startId,this.clients=new Set,this.messages=[],this.active=!0}publish(t,e,n){let r,i;this.active||b("Channel closed","SSEChannel",498);let s=e;if(t||e)i=this.nextID++,"object"==typeof t&&(t.event?(s=t.event,void 0!==t.data&&(t=JSON.stringify(t.data))):t=JSON.stringify(t)),t=t?t.split(/[\r\n]+/).map(t=>"data: "+t).join("\n"):"",r="id: "+i+"\n"+(e?"event: "+e+"\n":"")+(t||"data: ")+"\n\n",this.messages.push({id:i,_eventName:s,output:r});else{if(!this.clients.size)return;r="data: \n\n"}if(n?.clientId){const t=Array.isArray(n.clientId)?n.clientId:[n.clientId];[...this.clients].filter(e=>e.clientId&&t.includes(e.clientId)).forEach(t=>t.res.write(r))}else[...this.clients].filter(t=>!s||qt(t.events,s)).forEach((t,e)=>{t.res.write(r)});for(;this.messages.length>this.options.historySize;)this.messages.shift();return i}subscribe(t,e,n,r){if(this.active||b("Channel closed","SSEChannel",498),!r){const{remoteAddress:e,remotePort:n}=t.socket;e&&n&&(r=`${e}:${n}`)}const i={req:t,res:e,events:n,clientId:r},s=this.options.maxStreamDuration;let o="max-age=0, stale-while-revalidate=0, stale-if-error=0, no-transform";s>0&&(o+=", s-maxage="+(Math.floor(s/1e3)-1));const a={"Content-Type":"text/event-stream","Cache-Control":o,Connection:"keep-alive"};this.options.cors&&(a["access-control-allow-origin"]="*"),i.req.socket.setNoDelay(!0),i.res.writeHead(200,a);let c="retry: "+this.options.clientRetryInterval+"\n\n";const u=Number.parseInt(t.headers["last-event-id"],10),f=Number.isNaN(u)?this.options.rewind:this.nextID-1-u;return f&&this.messages.filter(t=>qt(i.events,t.eventName)).slice(0-f).forEach(t=>{c+=t.output}),i.res.write(c),this.clients.add(i),s>0&&setTimeout(()=>{i.res.writableEnded||this.unsubscribe(i)},s),i.res.on("close",()=>this.unsubscribe(i)),i}unsubscribe(t){t.res.end(),this.clients.delete(t)}clearClients(){this.clients.forEach(t=>t.res.end()),this.clients.clear()}listClients(){const t={};return this.clients.forEach(e=>{const n=e.req.socket.remoteAddress??"";n in t||(t[n]=0),t[n]++}),t}getSubscriberCount(){return this.clients.size}};function Wt(t){return t instanceof ReadableStream||t instanceof WritableStream}var Zt=600,Jt=601,Ht=class extends u{constructor(t,e=600){super(t,500)}};function Kt(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 Ht(`Response error: ${e}`,601))}}})}return new ReadableStream({start(t){t.error(new Ht("Response error: No response body",601))}})}function Qt(){return new ReadableStream({start(t){t.close()}})}import{createParser as Vt}from"eventsource-parser";function Yt(t){const e=new TextDecoder;let n;return new TransformStream({async start(e){n=Vt({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 te(){let t=!0;return e=>(t&&(e=e.trimStart())&&(t=!1),e)}function ee(t,e){if(!t.ok)return Kt(t.body);let n=t.body||new ReadableStream({start(t){t.close()}});return n instanceof ReadableStream||(n=ReadableStream.from(n)),n.pipeThrough(Yt(e))}function ne(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 re(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{v1 as ie,v5 as se,v4 as oe}from"uuid";import*as ae from"base32768";import{v1 as ce,v4 as ue,v5 as fe,stringify as he,parse as le,validate as me,version as pe,NIL as de}from"uuid";var ye={1:ie,4:oe,5:se};function we(t=1,e){const n=ye[t];return e?ae.encode(n(null,[])):n()}import be from"xxhashjs";import*as ve from"base32768";import{canonicalize as ge}from"json-canonicalize";import{createMD5 as ke,createRIPEMD160 as $e,createSHA1 as xe,createSHA224 as Ae,createSHA256 as Se,createSHA512 as Ee,createXXHash128 as Te,createXXHash32 as je,createXXHash64 as Oe}from"hash-wasm";var Ie=588213,Ce=(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))(Ce||{}),Ne={1:ke,2:xe,8:Se,10:Ee,11:Ae,3:$e,112:je,111:Oe,113:Te},{h32:Me,h64:Re}=be;function ze(t,e=16){return"object"==typeof t&&(t=ge(t)),Me(t.normalize(),Ie).toString(e)}function Le(t,e=16){return"object"==typeof t&&(t=ge(t)),Re(t.normalize(),Ie).toString(e)}function _e(t,e=111,n=Ie){let r;return t.buffer&&(t=t.buffer),112!==e?(r=Re(t,n),r=new Uint16Array([r._a00,r._a16,r._a32,r._a48]),r=new Uint8Array(r.buffer)):(r=Me(t,n),r=new Uint16Array([r._low,r._high]),r=new Uint8Array(r.buffer)),r}function Xe(t,e=111,n=Ie){return ve.encode(_e(t,e,n))}import{canonicalize as De}from"json-canonicalize";import*as Pe from"base32768";var Fe=Pe;async function Be(t,{hashAlgo:e=111,seed:n=Ie,outputType:r="string"}={}){const i=await Ne[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):Pe.encode(i.digest("binary"))}async function qe(t,{hashAlgo:e=111,seed:n=Ie,outputType:r="string"}={}){const i=await Ne[e](n);i.init(),i.update(t);return"string"!==r?i.digest(r):Pe.encode(i.digest("binary"))}async function Ue(t,e){return qe(t=De(t),e)}import{extNameLevel as Ge,FilenameReservedRegex as We,getMultiLevelExtname as Ze,isValidFilename as Je,isValidFilepath as He,sanitizeFilename as Ke,sanitizeFilepath as Qe,WindowsReservedNameRegex as Ve}from"@isdk/util";import{isRegExpStr as Ye,toRegExp as tn}from"util-ex";function en(t,e){if("string"!=typeof t)throw new f("modelName must be a string","isModelNameMatched",l.InvalidArgument);switch(typeof e){case"string":if(Ye(e)){const n=(e=tn(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(Ye(n)){const r=(e=tn(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 nn(t){return Object.keys(t).filter(t=>Number.isNaN(Number(t)))}import{pick as rn}from"lodash-es";import{newFunction as sn}from"util-ex";import{get as on,omitBy as an}from"lodash-es";import{newFunction as cn}from"util-ex";async function un(t,e,n){return mn(Sn(t,e,n),e,n)}function fn(t){for(let e=1;e<t.length;e++)if(t[e]<=t[e-1])return!1;return!0}function hn(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)))&&fn(n.map(t=>parseInt(t))))t=Object.values(t);else if("0"===r[0]&&fn(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 ln(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 mn(t,e,n){if(t.length){const r=await Promise.all(t.map((t,r)=>An(t,r,e,n))),i=n?.returnArrayOnly;let s;if(r?.length){s=Rn(`{${r.map(t=>t).join(",")}}`,e)}return s&&!i&&(s=ln(s)),s}}function pn(t,e,n,r){const[i,s]=t;if(!i&&"|"===s[0])return"choice: {"+function(t,e,n){const r=Sn(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=>vn(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(wn(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 dn([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:{...an(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=wn(c)?c:JSON.stringify(c),s+":"+o}async function yn(t,e,n,r){let i=pn(t,0,n,r);return i||(i=await dn(t,e,n,r)),i}function wn(t){const e=t[0];return('"'===e||"'"===e)&&t[t.length-1]===e}function bn(t,e=['""',"''","{}"]){return e.some(e=>t[0]===e[0]&&t[t.length-1]===e[1])}function vn(t,e='"'){return wn(t)?t:e+t+e}function gn(t){return'"'+t.replace(/(?<!\\)"(?!\\)/g,'\\"')+'"'}var kn=["true","false","null","undefined","NaN","Infinity"];async function $n(t,e,n){const r=cn("async expression",[],`return ${t};`,_n(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 xn(t,e,n){let r=t;if(["true","false"].includes(t.toLowerCase()))r=r.toLowerCase();else if(!(i=t,bn(i)||!Number.isNaN(parseFloat(i))||kn.includes(i)||Nn(i)||e&&void 0!==on(e,t)||Nn(t)))try{r=n?.skipExpression?gn(t):await $n.call(this,t,e,n?.preserveUnresolvedName)}catch(e){r=gn(t)}var i;return r}async function An(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 xn(s.slice(t+1).trim(),n,r)}{const t=s.trim();if(n&&void 0!==on(n,t)){return(a?"":e+":"+t+",")+'"'+t+'":'+t}return e+":"+await xn(s.trim(),n,r)}}function Sn(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 En(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 un(s,e,n)),{command:i.trim(),args:o}}var Tn="__PlacEhoLdeR_";function jn(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??Tn,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 On(t,e,n){const r=n?.placeholder??Tn;return e.reduce((t,e,n)=>t.replace(new RegExp(r+n,"g"),e),t)}var In="[a-zA-Z_$][a-zA-Z_\\d$]*",Cn=new RegExp(`^\\s*(\\(\\s*\\)|${In}|\\(${`${In}\\s*(,\\s*${In})*`}\\))\\s*=>`);function Nn(t){return Cn.test(t)}async function Mn(t,e){if(e&&(e=_n(e)),e&&(t=t.trim()).startsWith("{")&&t.endsWith("}")){return await un(t.slice(1,-1),e,{assigner:":",ignoreIndexNamed:!0})}return Rn(t,e)}function Rn(t,e){if(e&&(e=_n(e)),e){const n=Object.keys(e);if(n.length){const r=Object.values(e);let i=0;for(;i++<100;)try{return sn("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 sn("expression",[],`return ${t}`)()}var zn=/^[a-zA-Z_$][0-9a-zA-Z_$.]*$/,Ln=t=>zn.test(t);function _n(t){if(t){const e=Object.keys(t),n=e.length,r=e.filter(e=>Ln(e)&&null!==t[e]);if(n===r.length)return t;if(r.length)return t=rn(t,r)}}function Xn(t){return t?Dn(t,[],{dot:""}):[]}function Dn(t,e,{dot:n=".",visited:r=new Set}={}){return r.has(t)?[e.join("")]:Array.isArray(t)?(r.add(t),t.flatMap((t,n)=>Dn(t,[...e,`[${n}]`],{dot:".",visited:r}))):(i=t)&&i.constructor===Object?(r.add(t),Object.entries(t).flatMap(([t,i])=>Dn(i,[...e,n+t],{dot:".",visited:r}))):[e.join("")];var i}function Pn(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 Fn from"path";import*as Bn from"fs";import qn from"mime-type/with-db";import Un from"jschardet";function Gn(t){const e=Bn.statSync(t,{throwIfNoEntry:!1});return e?.isFile()}function Wn(t,e,n,r){const i=r?.signal,s=r?.exclude;let o;if(Fn.isAbsolute(t)?o=Gn(t)?t:Zn(Fn.basename(t),[Fn.dirname(t)],{extNames:n,exclude:s,signal:i}):(e||(e=["."]),o=Zn(t,e,{extNames:n,exclude:s,signal:i})),!o)throw new d(t,"loadFileFromPaths");{const t=o;o=Bn.readFileSync(o),r&&(r.filepath=t)}return o}function Zn(t,e,{extNames:n,signal:r,exclude:i=[]}){let s;const o=n?n.map(e=>Ze(t,Ge(e))):void 0;"string"==typeof i&&(i=[i]);for(const a of e){if(r?.aborted)throw r.reason;const e=Fn.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)&&Gn(r)){s=r;break}}else if(!i.includes(e)&&Gn(e)){s=e;break}}return s}function Jn(t,e,n,r,i){let s;"string"==typeof r?(s=r,r=void 0):s=r?.encoding;return Hn(Wn(t,e,n,r),s)}function Hn(t,e){void 0===e&&(e=er(t)??"utf8");return new TextDecoder(e).decode(t)}function Kn(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?Qn(t.dir):t.dir,f=Fn.resolve(e);if(i.has(f))continue;i.add(f);const h=Bn.statSync(e,{throwIfNoEntry:!1});if(h?.isDirectory()){u=t.level+1;const i=Bn.readdirSync(e,{withFileTypes:!0});for(let t=0;t<i.length;t++){let s=i[t],f=Fn.join(e,s.name);const h=f;if(s.isSymbolicLink()){const t=Fn.dirname(f);if(f=Bn.readlinkSync(f),f=Fn.resolve(t,f),s=Bn.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 Qn(t){const e=Bn.lstatSync(t,{throwIfNoEntry:!1});return e?.isSymbolicLink()&&(t=Bn.readlinkSync(t)),t}async function Vn(t,e){return Be(ReadableStream.from(Bn.createReadStream(t)),e)}async function Yn(t){const e=Fn.basename(t);t=Fn.resolve(t);const n=await Bn.promises.stat(t),r=n.mtime,i=n.ctime,s=n.size,o=tr(s),a=await Vn(t,{hashAlgo:o}),c=qn.lookup(t);return{name:e,mtime:r,ctime:i,size:s,hash:Ce[o]+":"+a,mimeType:c,id:"file://"+t}}function tr(t){let e=111;return t<=2048?e=112:t<=1048576?e=111:t<=10485760?e=113:t>10485760&&(e=10),e}function er(t,e){return Un.detect(t,e).encoding}import{statSync as nr}from"fs";import rr from"path";import{ConfigFile as ir,registerYamlTag as sr,traverseFolderSync as or}from"@isdk/util";import{regexp as ar}from"yaml-types";import{mimeType as cr}from"mime-type/with-db";import{ConfigFile as ur,registerYamlTag as fr,parseYaml as hr,stringifyYaml as lr}from"@isdk/util";function mr(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 or(t,(t,e)=>{if(i?.includes(t)||!e.isFile())return;const o=rr.extname(t),a=nr(t);if(s.includes(o)){if(r?.hasOwnProperty(t)&&a.mtimeMs<=r[t])return;n.push(t)}}),n}function pr(t,e){return mr(t,e).map(t=>ir.loadSync(t)).filter(t=>void 0!==t)}function dr(t,e,n=1){return ir.saveSync(t,e,{extLevel:n})}function yr(t){t instanceof Date&&(t=t.toISOString());return function(t,e){return t?`'${e}'`:String(e)}("string"==typeof t,t)}function wr(t,e){return t.map(t=>gr(t,e)).join(" AND ")}function br(t,e){return t.map(t=>gr(t,e)).join(" OR ")}function vr(t,e){const n=[];return Object.keys(e).forEach(r=>{const i=e[r];switch(r){case"$lt":case"<":n.push(`${t} < ${yr(i)}`);break;case"<=":case"$lte":n.push(`${t} <= ${yr(i)}`);break;case"$gt":case">":n.push(`${t} > ${yr(i)}`);break;case"$gte":case">=":n.push(`${t} >= ${yr(i)}`);break;case"$ne":case"!=":n.push(`${t} != ${yr(i)}`);break;case"=":case"$eq":n.push(`${t} = ${yr(i)}`);break;case"$in":n.push(`${t} IN (${i.map(t=>yr(t)).join(", ")})`);break;case"$nin":n.push(`${t} NOT IN (${i.map(t=>yr(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 gr(t,e){const n=[];if("function"!=typeof e&&(e=t=>t),Array.isArray(t))n.push(wr(t,e));else for(const[r,i]of Object.entries(t))if("$and"===r)n.push(`(${wr(t[r],e)})`);else if("$or"===r)n.push(`(${br(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(vr(e(r),i))}return n.length>1?n.join(" AND "):n[0]}function kr(t){const e=t.indexOf("://");if(e>0)return t.substring(0,e)}function $r(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 xr(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 Ar(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":" ")+Ar(t,{level:n+1,visiting:r,parent:e})}}sr(ar);var Sr=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 Er}from"util-ex";import{EventEmitter as Tr}from"events-ex";function jr(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 Or=class extends Array{constructor(t,e){Array.isArray(t)?(super(...t),this._length=t.length,t=void 0):(super(),this._length=0),this._capacity=jr(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(jr(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 Ir}from"@isdk/common-error";var Cr=32;function Nr(t){return"function"==typeof t}function Mr(){return"1"}var Rr=class{constructor(t={}){const{initFn:e=Mr,pauseFn:n,resumeFn:r,capacity:i=Cr}=t;if(Nr(n)!==Nr(r))throw new Error("pauseFn and resumeFn must be both set for pausing");this.waiting=new Or(i),this.emitter=new Tr,this.useDefaultTokens=e===Mr,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 Ir(e.reason||"aborted");e.alreadyRejected=!0,r(t)}),n};let r=this.tryAcquire(t);const i=r&&Er(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 Ir(t))}get activeCount(){return this._activeCount}get pendingCount(){return this.waiting.size}},zr=class extends Rr{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 Or(e);for(let t=0;t<e;t++)this.free.push(this.initTokenFn())}tryAcquire(t){let e=this.isReady;if(e&&Er(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 Lr(t,{timeUnit:e=1e3,uniformDistribution:n=!1}={}){const r=new zr(n?1:t),i=n?e/t:e;return async function(){await r.acquire(),setTimeout(()=>r.release(),i)}}import{AbortError as _r}from"@isdk/common-error";var Xr=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 _r(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 Dr}from"custom-ability";import{defineProperty as Pr}from"util-ex";var Fr,Br=0,qr=1,Ur=2,Gr=(t=>(t[t.MultiTask=0]="MultiTask",t[t.Cancelable=1]="Cancelable",t[t.Priority=2]="Priority",t))(Gr||{}),Wr=((Fr=Wr||{})[Fr.MultiTask=1]="MultiTask",Fr[Fr.Cancelable=2]="Cancelable",Fr[Fr.Priority=4]="Priority",Fr),Zr=class extends AbortController{constructor(t){super(),Pr(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")}}},Jr=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 zr(e-1,{isReadyFn:t})),n}static hasAsyncFeature(t){const e=this.prototype;let n=e.asyncFeatures;return e._asyncFeatures&&(n|=e._asyncFeatures),Sr.has(n,t)}hasAsyncFeature(t){let e=this.asyncFeatures;return this._asyncFeatures&&(e|=this._asyncFeatures),Sr.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 Zr(this);if(!(i instanceof Zr)){if(!(i instanceof AbortController))throw new f("aborter should be an AbortController",this.name,l.InvalidArgument);Object.setPrototypeOf(i,new Zr(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=[...Hr(t?.signal),...Hr(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=re({onStart:t=>{Pr(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 Hr(t){return t?Array.isArray(t)?t.filter(Boolean):[t]:[]}Jr.prototype.generateAsyncTaskId=function(t,e){return this._generateAsyncTaskId(t,e)},Jr.prototype.cleanMultiTaskAborter=function(t,e){return this._cleanMultiTaskAborter(t,e)};var Kr=Dr(Jr,"abort",{afterInjection:function(t,e){let n=t.prototype._asyncFeatures||0;n|=Wr.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 Qr(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 Vr from"memoizee";import{canonicalize as Yr}from"json-canonicalize";function ti(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 Vr(t,{...e,normalizer:t=>{if(r){const e=r(t);if("string"===e)return e;e&&(t=e)}return Xe(Yr(t))}})}import ei from"path";import{packageDirectorySync as ni}from"package-directory";function ri(t){const e=ni({cwd:t});if(e)return e;const n=t.split(ei.sep);let r=n.lastIndexOf("dist");if(r>0)return n.slice(0,r).join(ei.sep);if(r=n.lastIndexOf("src"),r>0)return n.slice(0,r).join(ei.sep);throw new Error("can not find package directory")}import ii from"path";function si(t,e){try{const n=ii.relative(ii.resolve(t),ii.resolve(e));return!n.startsWith("..")&&!ii.isAbsolute(n)}catch{return!1}}function oi(t,e){return e?.some(e=>si(e,t))}function ai(t,e){for(const n of e)oi(n,t)||t.push(n);return t}function ci(t){const e=t.slice();return ui(e),e}function ui(t){const e=t.length;if(e<=1)return;const n=new Map,r=[];for(let i=0;i<e;i++){const e=fi(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(si(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 fi(t){let e=ii.normalize(t);return e=e.split(/[/\\]/).join(ii.posix.sep),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e}import{isRegExp as hi,isRegExpStr as li}from"util-ex";function mi(t){return li(t)||hi(t)}function pi(t){return t.replace(/\x1B[[(?);]{0,2}(;?\d)*./g,"")}import di from"path";import{fileURLToPath as yi}from"url";import{AutoTokenizer as wi}from"@huggingface/transformers";var bi=yi(import.meta.url),vi=di.dirname(bi),gi=di.join(ri(vi),".cache"),ki=new Map,$i={"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"},xi={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 Ai(t){let e=ki.get(t);return e||(e=wi.from_pretrained(t,{cache_dir:gi}),ki.set(t,e)),e}async function Si(t,e="qwen2.5"){xi[e]&&(e=xi[e]);return(await Ai(e)).encode(t)}async function Ei(t,e="qwen2.5"){return(await Si(t,e)).length}function Ti(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 ji(t,e){let n,r=1984,i=!0,s=!1,o=!0,a=Ei,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 Oi(t,e){let n,r=1984,i=!0,s=Ei,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 Ii(t,e){let n,r=1984,i=Ei;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 Ci from"fs";async function*Ni(t,e){const n=(e={...e,completeSentence:!1,corrected:!1}).size??1984,r=e.modelId,i=e.metaInfo?.size??(await Ci.promises.stat(t)).size;let s=Math.trunc(i/2);if(s<=n){let i=Hn(await Ci.promises.readFile(t));if(s=await Ei(i,r),s<=n)yield i;else do{const t=await ji(i,{...e,modelId:r,size:n});yield t,i=i.slice(t.length)}while(i)}else{const i=ReadableStream.from(Ci.createReadStream(t)).getReader();let s="";for(;;){const{done:t,value:o}=await i.read();if(t)break;s+=Hn(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 ji(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 ji(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 ji(s,{...e,modelId:r,size:n,sentences:t});s=s.slice(i.length),yield i}}}async function*Mi(t,e){const n=e?.size??1984,r=e?.modelId,i=e?.metaInfo?.size??(await Ci.promises.stat(t)).size;let s=Math.trunc(i/2);if(s<=n){let i=Hn(await Ci.promises.readFile(t));if(s=await Ei(i,r),s<=n)yield pt(i,e);else{let t=pt(i,e);do{const i=await Oi(t,{...e,modelId:r,size:n});yield i,t=t.slice(i.length)}while(t.length)}}else{const i=ReadableStream.from(Ci.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+=Hn(o),u=pt(s,e);let a=u.pop();if(s.length>=n){const t=await Oi(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 Oi(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 Oi(u,{...e,modelId:r,size:n});u=u.slice(t.length),yield t}}}async function Ri(t,e){const n=e?.size??1984,r=e?.modelId;let i=pt(t,e);const s=[];if(await Ei(t,r)<=n)s.push(i);else do{const t=await Oi(i,{...e,modelId:r,size:n});s.push(t),i=i.slice(t.length)}while(i.length);return s}import{YAMLMap as zi}from"yaml";var Li=class{constructor(t){t&&Object.assign(this,t)}};function _i(t,e){const n={tag:t,collection:"map",nodeClass:class extends zi{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 Xi(t,e){let n=t.length===e.length;if(n){const r=_e(t),i=_e(e);n=r.every((t,e)=>t===i[e])}return n}import{defaultsDeep as Di,get as Pi,omit as Fi,set as Bi}from"lodash-es";import qi from"path";var Ui=".ai";function Gi(t,e=["."]){if(qi.isAbsolute(t))return ur.loadSync(t);const n=e.map(e=>ur.loadSync(qi.resolve(e,t))).filter(Boolean);return Di({},...n.reverse())}function Wi(t,e){const n={...process.env,...e};return W(t,{processEnv:n,parsed:n})}function Zi(t,e){let n=ur.loadSync(qi.resolve(e.configDir,t));n||(n={configDirs:["$XDG_BIN_HOME",e.configDir,"$HOME"],brainDir:qi.join(e.dataDir,"brain"),agentDirs:[qi.join(e.dataDir,"agent")],promptDirs:[qi.join(e.dataDir,"prompt")],chatsDir:qi.join(e.dataDir,"log","chats"),inputsDir:qi.join(e.dataDir,"log","inputs")});const r=Hi(e);for(const[t,e]of Object.entries(r))n[t]=e;Wi(n,n);const i=n.configDirs;n.AI_CONFIG_BASENAME&&(t=n.AI_CONFIG_BASENAME);const s=Wi(Gi(t,i),n);return Di(s,Fi(n,Object.keys(r))),Vi(s),s}function Ji(t){return Zi(".ai",t)}function Hi(t){return{XDG_CONFIG_HOME:t.configDir,XDG_DATA_HOME:t.dataDir,XDG_CACHE_HOME:t.cacheDir,XDG_BIN_HOME:qi.dirname(t.options.root)}}function Ki(t,e){t.startsWith("~")&&(t="$HOME"+t.slice(1));return Wi(t,e)}function Qi(t,e){return t.map(t=>Ki(t,e))}function Vi(t,e=["configDirs","brainDir","agentDirs","promptDirs","chatsDir","inputsDir"],n){for(const r of e){const e=Pi(t,r);if(!e)continue;let i;Array.isArray(e)&&e.length?i=Qi(e,n):"string"==typeof e&&(i=Ki(e,n)),i&&Bi(t,r,i)}}var{exit:Yi}=process,ts=!1,es=!1,ns=["SIGINT","SIGTERM","exit"],rs=[],is=(t,e)=>t.forEach(t=>process.once(t,e));async function ss(t="shutdown",e=0){if(!ts){ts=!0,"number"==typeof t&&(e=t,t="shutdown");for(const e of rs)try{await e(t)}catch(t){console.warn(`A shutdown handler failed before completing with: ${t.message||t}`)}return Yi(e)}console.warn(`Shutdown already in progress, ignoring [${t}] signal`)}function os(t){if(es||as(),!rs.some(e=>e===t))return rs.push(t),t}function as(){var t;es||(es=!0,process.exit=t=>{ts||ss(void 0,t).then()},is(ns,(t=3e5,()=>{setTimeout(()=>(console.warn(`Could not close resources gracefully after ${t}ms: forcing shutdown`),Yi(1)),t).unref()})),is(ns,ss))}var cs=["<BOS>","<EOS>","<PAD>","<UNK>"],us=".,!?;?!",fs=[" ","\n","\t","▁"," "],hs=["the","a","an","的","是","在"];function ls(t,e){const n=e?.exclude?function(t){const e=new Set;if(t.controlSymbols&&cs.forEach(t=>e.add(t)),t.punctuation)for(let t=0;t<7;t++)e.add(us[t]);return t.stopWords&&hs.forEach(t=>e.add(t)),t.whitespace&&fs.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()))),ms(t)}function ms(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 ps}from"lodash-es";var ds=/^\s*@inheritMerge\s*(?:[(]\s*(?<arg>\.start|\.end|false)[)])?/,ys=Symbol("MergeWay"),ws={replace:0,start:1,end:2};function bs(t,...e){return ps(t,...e,(t,e)=>Array.isArray(t)&&Array.isArray(e)?vs(t,e):void 0!==t&&"object"!=typeof t?t:void 0)}function vs(t,e){let n=t[ys];return void 0===n&&(t=function(t){const e=t[0];let n=".start";if("string"==typeof e){const r=ds.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=ws.start;"false"===n||"no"===n||"not"===n?r=ws.replace:".end"===n&&(r=ws.end);return Object.defineProperty(t,ys,{value:r,enumerable:!1}),t}(t),n=t[ys]),t=n===ws.replace?e:n===ws.end?t.concat(e):e.concat(t),Object.defineProperty(t,ys,{value:n,enumerable:!1}),t}function gs(t,e=" "){return ks(t).join(e)}function ks(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 $s(t){if(void 0!==t){const e=JSON.stringify(t);if("{}"!==e&&"[]"!==e&&'""'!==e)return"?p="+encodeURIComponent(e)}return""}var xs=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),Sr.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),Sr.has(e,t)}isStream(t){let e=this.stream;if(e){const n=this.params;n?.stream&&(e=t?.stream)}return e}},As={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"]}};xs.defineProperties(xs,As);var Ss=Symbol("meta");function Es(t,r,i=!0){if(r&&"object"==typeof r){if("function"==typeof t)return r=i?e({},t[Ss],r):n({},t[Ss],r),t[Ss]=r,t;if(t instanceof xs)return t.assign(r)}}function Ts(t){return"function"==typeof t?t[Ss]:t instanceof xs?t.toObject():void 0}var js=class extends xs{constructor(){super(...arguments),this._emitter=new t,this.description="Return event bus",this.result="event"}get emitter(){return this._emitter}func(){return this.emitter}},Os=new js(Ft);import{Cache as Is}from"secondary-cache";import{LRUCache as Cs}from"secondary-cache";var Ns=Is;function Ms({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 Rs(t,e){let n=xs.get(t);return n||(n=new xs(t,{func:Ms,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 Is(e)),n}var zs=Rs("lrucache"),Ls="A client transport has not been set. Use ClientTools.setTransport() or transport.mount(ClientTools) first.",_s=class t extends xs{static get apiRoot(){return this._transport||b(Ls,"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(Ls,"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){const r=this.constructor;if(r._transport)return r._transport.fetch(this.name,t,e,n,this.fetchOptions);b(Ls,"ClientTools")}async func(t){return await this.fetch(t)}},Xs={...x};_s.defineProperties(_s,Xs);var Ds=class extends _s{async fetch(t,e,n){return t||(t={}),e?.startsWith("$")&&(t.act=e,e="post"),await super.fetch(t,e,n)}async _func(t,e){return await this.fetch(e,t)}async func(t){const e=t.action;return e&&delete t.action,this._func(e,t)}assignMethods(t){if(Array.isArray(t))for(const e of t){const t=e.startsWith("$")?e.slice(1):e;this[t]||(this[t]=(t=>this._func.bind(this,t))(e))}}},Ps={methods:{type:"array",assign(t,e,n,r,i){i?.isExported||e.assignMethods(t)}}};Ds.defineProperties(Ds,Ps);var Fs=class extends Ds{async fetch(t,e){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)}},Bs=class extends Fs{constructor(){super(...arguments),this._sseListeners={},this._forwardEvents=new Set,this.description="subscribe server event",this.ebListener=async function(...t){const e=this.type;this.target.publish&&await this.target.publish({data:t,event:e})}}static setPubSubTransport(t){this._pubSubTransport=t}static get pubSubTransport(){if(!this._pubSubTransport)throw new Error("EventClient pubSubTransport not set");return this._pubSubTransport}get evtSource(){let t=this._stream;return t&&2!==t.readyState||(t=this.initEventStream(this._streamEvents)),t}get active(){return!!this._stream&&2!==this._stream.readyState}set active(t){t!==this.active&&(t?this.initEventStream(this._streamEvents):this._stream&&this.close())}initEventStream(t){const e="string"==typeof t?[t]:t;if(this._stream&&2!==this._stream.readyState){if(!this._streamEvents||e&&e.every(t=>this._streamEvents.includes(t)))return this._stream;this._stream.close()}const n=e?$s({event:e}):"",r=`${this.apiRoot}/${this.name}${n}`,i=this._stream=this.constructor.pubSubTransport.connect(r);return Object.entries(this._sseListeners).forEach(([t,e])=>{i.on(t,e)}),this._streamEvents=e,i}esListener(t,e,n){if(!this._forwardEvents.has(t)){const n=this.emitter;n&&t&&(Array.isArray(e)?n.emit(t,...e):n.emit(t,e))}}async subscribe(t){const e=await this.sub({event:t});"string"==typeof t&&(t=[t]);const n=this.evtSource;for(const e of t)if(!this._sseListeners[e]){const t=this._sseListeners[e]=(t,n)=>this.esListener(e,t,n);n.on(e,t)}return e}async unsubscribe(t){"string"==typeof t&&(t=[t]);const e=await this.unsub({event:t}),n=this.evtSource;for(const e of t){const t=this._sseListeners[e];t&&(delete this._sseListeners[e],n.off(e,t))}return e}forwardEvent(t){"string"==typeof t&&(t=[t]);for(const e of t)this._forwardEvents.has(e)||(this._forwardEvents.add(e),this.on&&this.on(e,this.ebListener))}unforwardEvent(t){"string"==typeof t&&(t=[t]);for(const e of t)this._forwardEvents.has(e)&&(this._forwardEvents.delete(e),this.off&&this.off(e,this.ebListener))}async init(t){if(this.active=!1,this.initEventStream(t),t)return await this.subscribe(t)}close(){const t=this._stream;if(t)return this._stream=void 0,t.close()}},qs=new Bs(Pt);import{getAllNames as Us}from"util-ex";var Gs=class t extends xs{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){}},Ws={...x};Gs.defineProperties(Gs,Ws);var Zs=class extends Gs{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);Us(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)}};Zs.defineProperties(Zs,{methods:{type:"array"}});var Js=class extends Zs{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"),"post"===e&&t.act&&(e=t.act),e}castParams(t){return void 0!==t.id&&(t.id=this.cast("id",t.id)),t}},Hs=Os.runSync(),Ks=class t extends Js{constructor(){super(...arguments),this.description="subscribe server event",this.result="event",this.depends={[Ft]:Os}}static setPubSubTransport(t){this._pubSubTransport=t}static get pubSubTransport(){return this._pubSubTransport||console.warn("EventServer pubSubTransport not set"),this._pubSubTransport}get pubSubTransport(){return this.constructor.pubSubTransport}static publish(t,e,n){return this.pubSubTransport?.publish(e,t,n)}static ebListener(t,...e){this.pubSubTransport?.publish(t,e)}static subscribe(t,e,n,r){return this.pubSubTransport?.subscribe(n,{...r,req:t,res:e})}static alreadyForward(t){const e=Hs.listeners(t);for(const t of e)if(t===this._boundEbListener)return!0}publishSSE(t,e){return this.constructor.publish(t,e)}subscribeSSE(t,e,n){return"string"==typeof n&&(n=[n]),this.constructor.subscribe(t,e,n)}forward(e){Array.isArray(e)||(e=[e]);const n=this.constructor;n._boundEbListener||(n._boundEbListener=function(...t){return n.ebListener(this.type,...t)});for(const r of e)t.alreadyForward(r)||Hs.on(r,n._boundEbListener)}unforward(t){"string"==typeof t&&(t=[t]);const e=this.constructor;if(e._boundEbListener)for(const n of t)Hs.off(n,e._boundEbListener)}list({_req:t,_res:e,event:n}){t&&e&&this.subscribeSSE(t,e,n)}$sub({event:t}){if(t)return this.forward(t),{event:t};b("event is required","sub",l.InvalidArgument)}$unsub({event:t}){if(t)return this.unforward(t),{event:t};b("event is required","unsub",l.InvalidArgument)}$publish({event:t,data:e}){if(t&&e){"string"==typeof t&&(t=[t]);for(const n of t)this.publishSSE(e,n);return{event:t}}b("event or data is required","pub",l.InvalidArgument)}isStream(t){return"list"===this.getMethodFromParams(t)}},Qs=new Ks(Pt);function Vs(){Os.register(),zs.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,O as parseISO,I as toDate,L as AITextGenerationFinishReasons,_ as AIMessageTypes,X as AIChatRoles,D as StrangeHumanName,P 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,Ot as removeMarkdownBoldAndItalic,It as splitParagraph,Ct as truncTo,Nt as sleep,Mt as wait,Rt as yieldExec,Pt as EventName,Ft as EventBusName,Bt as backendEventable,Lt as EventEmitter,_t as eventable,Xt as states,Dt as wrapEventEmitter,Ut as SSEChannelAlreadyClosedErrCode,Gt as SSEChannel,Wt as isWebStream,Zt as RStreamErrCode,Jt as ResponseRStreamErrCode,Ht as ReadableStreamError,Kt as getResponseErrorReadableStream,Qt as createEmptyReadableStream,Yt as createEventStreamTransformer,te as trimStartOfStreamHelper,ee as AIStream,ne as readableFromAsyncIterable,re as createCallbacksTransformer,we as uuid,ce as v1,ue as v4,fe as v5,he as stringify,le as parse,me as validate,pe as version,de as NIL,Ce as HashAlgorithm,ze as xxhash32,Le as xxhash64,_e as xxhash,Xe as xxhashAsStr,De as canonicalize,Fe as base32768,Be as hashStream,qe as hash,Ue as hashObject,Ge as extNameLevel,We as FilenameReservedRegex,Ze as getMultiLevelExtname,Je as isValidFilename,He as isValidFilepath,Ke as sanitizeFilename,Qe as sanitizeFilepath,Ve as WindowsReservedNameRegex,en as isModelNameMatched,nn as getAllEnumKeys,un as parseObjectArguments,hn as ObjectArgsToArgsInfo,ln as simplifyObjectArguments,mn as parseObjectArgumentInfos,pn as ChoiceArgProcessor,dn as TemplateArgProcessor,yn as AIArgProcessor,wn as isQuoted,bn as isStrWrapped,vn as ensureQuoted,gn as quoteStr,An as parseObjectArgInfo,Sn as parseObjectArgumentsAsArgInfos,En as parseCommand,jn as replaceWithPlaceholder,On as restoreFromPlacehoders,Mn as parseJsJson,Rn as parseJsJsonSimpleSync,_n as filterValidFnScope,Xn as getKeysPath,Pn as createEndWithRepetitionDetector,Gn as fileIsExists,Wn as loadFileFromPaths,Jn as loadTextFromPaths,Hn as decodeCharset,Kn as readFilenamesRecursiveSync,Qn as getRealFilepath,Vn as hashFile,Yn as getFileMetaInfo,tr as getHashAlgoBySize,er as detectCharset,mr as getConfigFileNames,pr as getConfigs,dr as saveConfigFile,cr as mimeType,ur as ConfigFile,fr as registerYamlTag,hr as parseYaml,lr as stringifyYaml,gr as jsonFilterToWhere,kr as matchUrlProtocol,$r as paramsSizeToScaleStr,xr as scaleStrToParamsSize,Ar as jsonToMarkdownStr,Sr as IntSet,Cr as DefaultAsyncSemaphoreCapacity,Rr as BinarySemaphore,zr as Semaphore,Lr as RateLimit,Xr as SignalGate,Br as ToolAsyncMultiTaskBit,qr as ToolAsyncCancelableBit,Ur as ToolAsyncPriorityBit,Gr as AsyncFeatureBits,Wr as AsyncFeatures,Zr as TaskAbortController,Jr as CancelableAbility,Kr as makeToolFuncCancelable,Qr as countRegexMatches,ti as memoize,ri as getPackageDir,si as isSubdirectory,oi as hasDirectoryIn,ai as assignDirs,ci as pruneSubdirectories,ui as pruneSubdirectoriesInPlace,fi as normalizePath,mi as isRegExp,pi as stripConsoleColor,$i as LLM_TOKENIZER_NAMES,xi as LLM_TOKENIZER_NAMES_MAP,Ai as getLLMTokenizer,Si as encodeLLMTokens,Ei as countLLMTokens,Ti as formatTextWithSpace,ji as truncateToTokenLimit,Oi as truncateToTokenLimitEx,Ii as truncateByToken,Ni as readTextFileChunks,Mi as readTextFileChunksEx,Ri as splitChunks,Li as YamlTypeBaseObject,_i as createYamlObjectTag,Xi as isSameString,Ui as DEFAULT_CONFIG_NAME,Gi as loadConfigFile,Wi as expandConfig,Zi as loadConfig,Ji as loadAIConfig,Hi as getXDGConfigs,Ki as expandPath,Qi as expandPaths,Vi as expandPathInObject,ns as SHUTDOWN_SIGNALS,ss as shutdown,os as beforeShutdown,as as initShutdown,ls as calcPerplexity,ms as calcPerplexitySimple,ys as ArrayMergeWaySymbol,ws as ArrayMergeWay,bs as defaultsWithConcat,vs as mergeArray,gs as joinSplitWords,ks as splitWords,$s as genUrlParamsStr,v as createAbilityInjector,g as toRegExp,xs as ToolFunc,As as ToolFuncSchema,Ss as FuncMetaSymbol,Es as funcWithMeta,Ts as funcGetMeta,_s as ClientTools,Xs as ClientToolFuncSchema,Gs as ServerTools,Ws as ServerToolFuncSchema,js as EventToolFunc,Os as event,Ns as SecondaryCache,Ms as _lrucache,Rs as createLRUCache,zs as lrucache,Cs as LRUCache,Fs as ResClientTools,Bs as EventClient,qs as eventClient,Js as ResServerTools,Ks as EventServer,Qs as eventServer,Vs as registerCoreTools};
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 O,toDate as I}from"date-fns";var C="MMMM d, y 'at' h:m:s b 'GMT'x";function N(t){return t&&(C=t),C}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=C){return S(t,e,new Date)}function z(t,e=C){return A(t,e)}var L=["stop","length","content_filter","tool_calls","function_call","abort","error","other",null],_=["human","ai","generic","system","tool"],X=["user","assistant","system","tool","tool_calls"],D="陌生人";function P(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 Ot(t,e){return t=jt(t=Tt(t,e),e)}function It(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 Ct(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 Lt,eventable as _t,states as Xt,wrapEventEmitter as Dt}from"events-ex";var Pt="event",Ft="event-bus";var Bt=zt(function(t){return class{static get emitter(){if(!this._emitter){const t=this.get(Ft)?.emitter;t&&(this._emitter=t,this.prototype._events=t._events)}return this._emitter}get emitter(){return this.constructor._emitter}on(e,n){const r=t.emitter;if(!r)throw new TypeError("EventBackend required");return r.on(e,n)}once(e,n){const r=t.emitter;if(!r)throw new TypeError("EventBackend required");return r.once(e,n)}off(e,n){const r=t.emitter;if(!r)throw new TypeError("EventBackend required");return r.off(e,n)}emit(e,...n){const r=t.emitter;if(!r)throw new TypeError("EventBackend required");return"error"===e?this.emitError.apply(this,n):r.emit.call(this,e,this.name,...n)}emitError(e,...n){const r=t.emitter;if(!r)throw new TypeError("EventBackend required");return r.emit.call(this,"error",e,this.name,...n)}async emitAsync(e,...n){const r=t.emitter;if(!r)throw new TypeError("EventBackend required");return r.emitAsync.call(this,e,this.name,...n)}}},!0);function qt(t,e){return!t||t.some(t=>t instanceof RegExp?t.test(e):t===e)}var Ut=498,Gt=class{get active(){return this._active}set active(t){t!==this._active&&(t?(this.pingTimer&&(clearInterval(this.pingTimer),this.pingTimer=void 0),this.options.pingInterval>0&&(this.pingTimer=setInterval(()=>this.publish(),this.options.pingInterval))):(this.clients.size&&this.clearClients(),this.pingTimer&&(clearInterval(this.pingTimer),this.pingTimer=void 0)),this._active=t)}constructor(t){this.options=Object.assign({},{pingInterval:3e3,maxStreamDuration:3e4,clientRetryInterval:1e3,startId:1,historySize:100,rewind:0,cors:!1},t),this.nextID=this.options.startId,this.clients=new Set,this.messages=[],this.active=!0}publish(t,e,n){let r,i;this.active||b("Channel closed","SSEChannel",498);let s=e;if(t||e)i=this.nextID++,"object"==typeof t&&(t.event?(s=t.event,void 0!==t.data&&(t=JSON.stringify(t.data))):t=JSON.stringify(t)),t=t?t.split(/[\r\n]+/).map(t=>"data: "+t).join("\n"):"",r="id: "+i+"\n"+(e?"event: "+e+"\n":"")+(t||"data: ")+"\n\n",this.messages.push({id:i,_eventName:s,output:r});else{if(!this.clients.size)return;r="data: \n\n"}if(n?.clientId){const t=Array.isArray(n.clientId)?n.clientId:[n.clientId];[...this.clients].filter(e=>e.clientId&&t.includes(e.clientId)).forEach(t=>t.res.write(r))}else[...this.clients].filter(t=>!s||qt(t.events,s)).forEach((t,e)=>{t.res.write(r)});for(;this.messages.length>this.options.historySize;)this.messages.shift();return i}subscribe(t,e,n,r){if(this.active||b("Channel closed","SSEChannel",498),!r){const{remoteAddress:e,remotePort:n}=t.socket;e&&n&&(r=`${e}:${n}`)}const i={req:t,res:e,events:n,clientId:r},s=this.options.maxStreamDuration;let o="max-age=0, stale-while-revalidate=0, stale-if-error=0, no-transform";s>0&&(o+=", s-maxage="+(Math.floor(s/1e3)-1));const a={"Content-Type":"text/event-stream","Cache-Control":o,Connection:"keep-alive"};this.options.cors&&(a["access-control-allow-origin"]="*"),i.req.socket.setNoDelay(!0),i.res.writeHead(200,a);let c="retry: "+this.options.clientRetryInterval+"\n\n";const u=Number.parseInt(t.headers["last-event-id"],10),f=Number.isNaN(u)?this.options.rewind:this.nextID-1-u;return f&&this.messages.filter(t=>qt(i.events,t.eventName)).slice(0-f).forEach(t=>{c+=t.output}),i.res.write(c),this.clients.add(i),s>0&&setTimeout(()=>{i.res.writableEnded||this.unsubscribe(i)},s),i.res.on("close",()=>this.unsubscribe(i)),i}unsubscribe(t){t.res.end(),this.clients.delete(t)}clearClients(){this.clients.forEach(t=>t.res.end()),this.clients.clear()}listClients(){const t={};return this.clients.forEach(e=>{const n=e.req.socket.remoteAddress??"";n in t||(t[n]=0),t[n]++}),t}getSubscriberCount(){return this.clients.size}};function Wt(t){return t instanceof ReadableStream||t instanceof WritableStream}var Zt=600,Jt=601,Ht=class extends u{constructor(t,e=600){super(t,500)}};function Kt(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 Ht(`Response error: ${e}`,601))}}})}return new ReadableStream({start(t){t.error(new Ht("Response error: No response body",601))}})}function Qt(){return new ReadableStream({start(t){t.close()}})}import{createParser as Vt}from"eventsource-parser";function Yt(t){const e=new TextDecoder;let n;return new TransformStream({async start(e){n=Vt({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 te(){let t=!0;return e=>(t&&(e=e.trimStart())&&(t=!1),e)}function ee(t,e){if(!t.ok)return Kt(t.body);let n=t.body||new ReadableStream({start(t){t.close()}});return n instanceof ReadableStream||(n=ReadableStream.from(n)),n.pipeThrough(Yt(e))}function ne(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 re(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{v1 as ie,v5 as se,v4 as oe}from"uuid";import*as ae from"base32768";import{v1 as ce,v4 as ue,v5 as fe,stringify as he,parse as le,validate as me,version as pe,NIL as de}from"uuid";var ye={1:ie,4:oe,5:se};function we(t=1,e){const n=ye[t];return e?ae.encode(n(null,[])):n()}import be from"xxhashjs";import*as ve from"base32768";import{canonicalize as ge}from"json-canonicalize";import{createMD5 as ke,createRIPEMD160 as $e,createSHA1 as xe,createSHA224 as Ae,createSHA256 as Se,createSHA512 as Ee,createXXHash128 as Te,createXXHash32 as je,createXXHash64 as Oe}from"hash-wasm";var Ie=588213,Ce=(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))(Ce||{}),Ne={1:ke,2:xe,8:Se,10:Ee,11:Ae,3:$e,112:je,111:Oe,113:Te},{h32:Me,h64:Re}=be;function ze(t,e=16){return"object"==typeof t&&(t=ge(t)),Me(t.normalize(),Ie).toString(e)}function Le(t,e=16){return"object"==typeof t&&(t=ge(t)),Re(t.normalize(),Ie).toString(e)}function _e(t,e=111,n=Ie){let r;return t.buffer&&(t=t.buffer),112!==e?(r=Re(t,n),r=new Uint16Array([r._a00,r._a16,r._a32,r._a48]),r=new Uint8Array(r.buffer)):(r=Me(t,n),r=new Uint16Array([r._low,r._high]),r=new Uint8Array(r.buffer)),r}function Xe(t,e=111,n=Ie){return ve.encode(_e(t,e,n))}import{canonicalize as De}from"json-canonicalize";import*as Pe from"base32768";var Fe=Pe;async function Be(t,{hashAlgo:e=111,seed:n=Ie,outputType:r="string"}={}){const i=await Ne[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):Pe.encode(i.digest("binary"))}async function qe(t,{hashAlgo:e=111,seed:n=Ie,outputType:r="string"}={}){const i=await Ne[e](n);i.init(),i.update(t);return"string"!==r?i.digest(r):Pe.encode(i.digest("binary"))}async function Ue(t,e){return qe(t=De(t),e)}import{extNameLevel as Ge,FilenameReservedRegex as We,getMultiLevelExtname as Ze,isValidFilename as Je,isValidFilepath as He,sanitizeFilename as Ke,sanitizeFilepath as Qe,WindowsReservedNameRegex as Ve}from"@isdk/util";import{isRegExpStr as Ye,toRegExp as tn}from"util-ex";function en(t,e){if("string"!=typeof t)throw new f("modelName must be a string","isModelNameMatched",l.InvalidArgument);switch(typeof e){case"string":if(Ye(e)){const n=(e=tn(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(Ye(n)){const r=(e=tn(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 nn(t){return Object.keys(t).filter(t=>Number.isNaN(Number(t)))}import{pick as rn}from"lodash-es";import{newFunction as sn}from"util-ex";import{get as on,omitBy as an}from"lodash-es";import{newFunction as cn}from"util-ex";async function un(t,e,n){return mn(Sn(t,e,n),e,n)}function fn(t){for(let e=1;e<t.length;e++)if(t[e]<=t[e-1])return!1;return!0}function hn(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)))&&fn(n.map(t=>parseInt(t))))t=Object.values(t);else if("0"===r[0]&&fn(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 ln(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 mn(t,e,n){if(t.length){const r=await Promise.all(t.map((t,r)=>An(t,r,e,n))),i=n?.returnArrayOnly;let s;if(r?.length){s=Rn(`{${r.map(t=>t).join(",")}}`,e)}return s&&!i&&(s=ln(s)),s}}function pn(t,e,n,r){const[i,s]=t;if(!i&&"|"===s[0])return"choice: {"+function(t,e,n){const r=Sn(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=>vn(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(wn(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 dn([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:{...an(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=wn(c)?c:JSON.stringify(c),s+":"+o}async function yn(t,e,n,r){let i=pn(t,0,n,r);return i||(i=await dn(t,e,n,r)),i}function wn(t){const e=t[0];return('"'===e||"'"===e)&&t[t.length-1]===e}function bn(t,e=['""',"''","{}"]){return e.some(e=>t[0]===e[0]&&t[t.length-1]===e[1])}function vn(t,e='"'){return wn(t)?t:e+t+e}function gn(t){return'"'+t.replace(/(?<!\\)"(?!\\)/g,'\\"')+'"'}var kn=["true","false","null","undefined","NaN","Infinity"];async function $n(t,e,n){const r=cn("async expression",[],`return ${t};`,_n(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 xn(t,e,n){let r=t;if(["true","false"].includes(t.toLowerCase()))r=r.toLowerCase();else if(!(i=t,bn(i)||!Number.isNaN(parseFloat(i))||kn.includes(i)||Nn(i)||e&&void 0!==on(e,t)||Nn(t)))try{r=n?.skipExpression?gn(t):await $n.call(this,t,e,n?.preserveUnresolvedName)}catch(e){r=gn(t)}var i;return r}async function An(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 xn(s.slice(t+1).trim(),n,r)}{const t=s.trim();if(n&&void 0!==on(n,t)){return(a?"":e+":"+t+",")+'"'+t+'":'+t}return e+":"+await xn(s.trim(),n,r)}}function Sn(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 En(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 un(s,e,n)),{command:i.trim(),args:o}}var Tn="__PlacEhoLdeR_";function jn(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??Tn,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 On(t,e,n){const r=n?.placeholder??Tn;return e.reduce((t,e,n)=>t.replace(new RegExp(r+n,"g"),e),t)}var In="[a-zA-Z_$][a-zA-Z_\\d$]*",Cn=new RegExp(`^\\s*(\\(\\s*\\)|${In}|\\(${`${In}\\s*(,\\s*${In})*`}\\))\\s*=>`);function Nn(t){return Cn.test(t)}async function Mn(t,e){if(e&&(e=_n(e)),e&&(t=t.trim()).startsWith("{")&&t.endsWith("}")){return await un(t.slice(1,-1),e,{assigner:":",ignoreIndexNamed:!0})}return Rn(t,e)}function Rn(t,e){if(e&&(e=_n(e)),e){const n=Object.keys(e);if(n.length){const r=Object.values(e);let i=0;for(;i++<100;)try{return sn("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 sn("expression",[],`return ${t}`)()}var zn=/^[a-zA-Z_$][0-9a-zA-Z_$.]*$/,Ln=t=>zn.test(t);function _n(t){if(t){const e=Object.keys(t),n=e.length,r=e.filter(e=>Ln(e)&&null!==t[e]);if(n===r.length)return t;if(r.length)return t=rn(t,r)}}function Xn(t){return t?Dn(t,[],{dot:""}):[]}function Dn(t,e,{dot:n=".",visited:r=new Set}={}){return r.has(t)?[e.join("")]:Array.isArray(t)?(r.add(t),t.flatMap((t,n)=>Dn(t,[...e,`[${n}]`],{dot:".",visited:r}))):(i=t)&&i.constructor===Object?(r.add(t),Object.entries(t).flatMap(([t,i])=>Dn(i,[...e,n+t],{dot:".",visited:r}))):[e.join("")];var i}function Pn(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 Fn from"path";import*as Bn from"fs";import qn from"mime-type/with-db";import Un from"jschardet";function Gn(t){const e=Bn.statSync(t,{throwIfNoEntry:!1});return e?.isFile()}function Wn(t,e,n,r){const i=r?.signal,s=r?.exclude;let o;if(Fn.isAbsolute(t)?o=Gn(t)?t:Zn(Fn.basename(t),[Fn.dirname(t)],{extNames:n,exclude:s,signal:i}):(e||(e=["."]),o=Zn(t,e,{extNames:n,exclude:s,signal:i})),!o)throw new d(t,"loadFileFromPaths");{const t=o;o=Bn.readFileSync(o),r&&(r.filepath=t)}return o}function Zn(t,e,{extNames:n,signal:r,exclude:i=[]}){let s;const o=n?n.map(e=>Ze(t,Ge(e))):void 0;"string"==typeof i&&(i=[i]);for(const a of e){if(r?.aborted)throw r.reason;const e=Fn.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)&&Gn(r)){s=r;break}}else if(!i.includes(e)&&Gn(e)){s=e;break}}return s}function Jn(t,e,n,r,i){let s;"string"==typeof r?(s=r,r=void 0):s=r?.encoding;return Hn(Wn(t,e,n,r),s)}function Hn(t,e){void 0===e&&(e=er(t)??"utf8");return new TextDecoder(e).decode(t)}function Kn(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?Qn(t.dir):t.dir,f=Fn.resolve(e);if(i.has(f))continue;i.add(f);const h=Bn.statSync(e,{throwIfNoEntry:!1});if(h?.isDirectory()){u=t.level+1;const i=Bn.readdirSync(e,{withFileTypes:!0});for(let t=0;t<i.length;t++){let s=i[t],f=Fn.join(e,s.name);const h=f;if(s.isSymbolicLink()){const t=Fn.dirname(f);if(f=Bn.readlinkSync(f),f=Fn.resolve(t,f),s=Bn.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 Qn(t){const e=Bn.lstatSync(t,{throwIfNoEntry:!1});return e?.isSymbolicLink()&&(t=Bn.readlinkSync(t)),t}async function Vn(t,e){return Be(ReadableStream.from(Bn.createReadStream(t)),e)}async function Yn(t){const e=Fn.basename(t);t=Fn.resolve(t);const n=await Bn.promises.stat(t),r=n.mtime,i=n.ctime,s=n.size,o=tr(s),a=await Vn(t,{hashAlgo:o}),c=qn.lookup(t);return{name:e,mtime:r,ctime:i,size:s,hash:Ce[o]+":"+a,mimeType:c,id:"file://"+t}}function tr(t){let e=111;return t<=2048?e=112:t<=1048576?e=111:t<=10485760?e=113:t>10485760&&(e=10),e}function er(t,e){return Un.detect(t,e).encoding}import{statSync as nr}from"fs";import rr from"path";import{ConfigFile as ir,registerYamlTag as sr,traverseFolderSync as or}from"@isdk/util";import{regexp as ar}from"yaml-types";import{mimeType as cr}from"mime-type/with-db";import{ConfigFile as ur,registerYamlTag as fr,parseYaml as hr,stringifyYaml as lr}from"@isdk/util";function mr(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 or(t,(t,e)=>{if(i?.includes(t)||!e.isFile())return;const o=rr.extname(t),a=nr(t);if(s.includes(o)){if(r?.hasOwnProperty(t)&&a.mtimeMs<=r[t])return;n.push(t)}}),n}function pr(t,e){return mr(t,e).map(t=>ir.loadSync(t)).filter(t=>void 0!==t)}function dr(t,e,n=1){return ir.saveSync(t,e,{extLevel:n})}function yr(t){t instanceof Date&&(t=t.toISOString());return function(t,e){return t?`'${e}'`:String(e)}("string"==typeof t,t)}function wr(t,e){return t.map(t=>gr(t,e)).join(" AND ")}function br(t,e){return t.map(t=>gr(t,e)).join(" OR ")}function vr(t,e){const n=[];return Object.keys(e).forEach(r=>{const i=e[r];switch(r){case"$lt":case"<":n.push(`${t} < ${yr(i)}`);break;case"<=":case"$lte":n.push(`${t} <= ${yr(i)}`);break;case"$gt":case">":n.push(`${t} > ${yr(i)}`);break;case"$gte":case">=":n.push(`${t} >= ${yr(i)}`);break;case"$ne":case"!=":n.push(`${t} != ${yr(i)}`);break;case"=":case"$eq":n.push(`${t} = ${yr(i)}`);break;case"$in":n.push(`${t} IN (${i.map(t=>yr(t)).join(", ")})`);break;case"$nin":n.push(`${t} NOT IN (${i.map(t=>yr(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 gr(t,e){const n=[];if("function"!=typeof e&&(e=t=>t),Array.isArray(t))n.push(wr(t,e));else for(const[r,i]of Object.entries(t))if("$and"===r)n.push(`(${wr(t[r],e)})`);else if("$or"===r)n.push(`(${br(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(vr(e(r),i))}return n.length>1?n.join(" AND "):n[0]}function kr(t){const e=t.indexOf("://");if(e>0)return t.substring(0,e)}function $r(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 xr(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 Ar(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":" ")+Ar(t,{level:n+1,visiting:r,parent:e})}}sr(ar);var Sr=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 Er}from"util-ex";import{EventEmitter as Tr}from"events-ex";function jr(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 Or=class extends Array{constructor(t,e){Array.isArray(t)?(super(...t),this._length=t.length,t=void 0):(super(),this._length=0),this._capacity=jr(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(jr(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 Ir}from"@isdk/common-error";var Cr=32;function Nr(t){return"function"==typeof t}function Mr(){return"1"}var Rr=class{constructor(t={}){const{initFn:e=Mr,pauseFn:n,resumeFn:r,capacity:i=Cr}=t;if(Nr(n)!==Nr(r))throw new Error("pauseFn and resumeFn must be both set for pausing");this.waiting=new Or(i),this.emitter=new Tr,this.useDefaultTokens=e===Mr,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 Ir(e.reason||"aborted");e.alreadyRejected=!0,r(t)}),n};let r=this.tryAcquire(t);const i=r&&Er(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 Ir(t))}get activeCount(){return this._activeCount}get pendingCount(){return this.waiting.size}},zr=class extends Rr{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 Or(e);for(let t=0;t<e;t++)this.free.push(this.initTokenFn())}tryAcquire(t){let e=this.isReady;if(e&&Er(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 Lr(t,{timeUnit:e=1e3,uniformDistribution:n=!1}={}){const r=new zr(n?1:t),i=n?e/t:e;return async function(){await r.acquire(),setTimeout(()=>r.release(),i)}}import{AbortError as _r}from"@isdk/common-error";var Xr=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 _r(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 Dr}from"custom-ability";import{defineProperty as Pr}from"util-ex";var Fr,Br=0,qr=1,Ur=2,Gr=(t=>(t[t.MultiTask=0]="MultiTask",t[t.Cancelable=1]="Cancelable",t[t.Priority=2]="Priority",t))(Gr||{}),Wr=((Fr=Wr||{})[Fr.MultiTask=1]="MultiTask",Fr[Fr.Cancelable=2]="Cancelable",Fr[Fr.Priority=4]="Priority",Fr),Zr=class extends AbortController{constructor(t){super(),Pr(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")}}},Jr=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 zr(e-1,{isReadyFn:t})),n}static hasAsyncFeature(t){const e=this.prototype;let n=e.asyncFeatures;return e._asyncFeatures&&(n|=e._asyncFeatures),Sr.has(n,t)}hasAsyncFeature(t){let e=this.asyncFeatures;return this._asyncFeatures&&(e|=this._asyncFeatures),Sr.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 Zr(this);if(!(i instanceof Zr)){if(!(i instanceof AbortController))throw new f("aborter should be an AbortController",this.name,l.InvalidArgument);Object.setPrototypeOf(i,new Zr(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=[...Hr(t?.signal),...Hr(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=re({onStart:t=>{Pr(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 Hr(t){return t?Array.isArray(t)?t.filter(Boolean):[t]:[]}Jr.prototype.generateAsyncTaskId=function(t,e){return this._generateAsyncTaskId(t,e)},Jr.prototype.cleanMultiTaskAborter=function(t,e){return this._cleanMultiTaskAborter(t,e)};var Kr=Dr(Jr,"abort",{afterInjection:function(t,e){let n=t.prototype._asyncFeatures||0;n|=Wr.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 Qr(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 Vr from"memoizee";import{canonicalize as Yr}from"json-canonicalize";function ti(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 Vr(t,{...e,normalizer:t=>{if(r){const e=r(t);if("string"===e)return e;e&&(t=e)}return Xe(Yr(t))}})}import ei from"path";import{packageDirectorySync as ni}from"package-directory";function ri(t){const e=ni({cwd:t});if(e)return e;const n=t.split(ei.sep);let r=n.lastIndexOf("dist");if(r>0)return n.slice(0,r).join(ei.sep);if(r=n.lastIndexOf("src"),r>0)return n.slice(0,r).join(ei.sep);throw new Error("can not find package directory")}import ii from"path";function si(t,e){try{const n=ii.relative(ii.resolve(t),ii.resolve(e));return!n.startsWith("..")&&!ii.isAbsolute(n)}catch{return!1}}function oi(t,e){return e?.some(e=>si(e,t))}function ai(t,e){for(const n of e)oi(n,t)||t.push(n);return t}function ci(t){const e=t.slice();return ui(e),e}function ui(t){const e=t.length;if(e<=1)return;const n=new Map,r=[];for(let i=0;i<e;i++){const e=fi(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(si(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 fi(t){let e=ii.normalize(t);return e=e.split(/[/\\]/).join(ii.posix.sep),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e}import{isRegExp as hi,isRegExpStr as li}from"util-ex";function mi(t){return li(t)||hi(t)}function pi(t){return t.replace(/\x1B[[(?);]{0,2}(;?\d)*./g,"")}import di from"path";import{fileURLToPath as yi}from"url";import{AutoTokenizer as wi}from"@huggingface/transformers";var bi=yi(import.meta.url),vi=di.dirname(bi),gi=di.join(ri(vi),".cache"),ki=new Map,$i={"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"},xi={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 Ai(t){let e=ki.get(t);return e||(e=wi.from_pretrained(t,{cache_dir:gi}),ki.set(t,e)),e}async function Si(t,e="qwen2.5"){xi[e]&&(e=xi[e]);return(await Ai(e)).encode(t)}async function Ei(t,e="qwen2.5"){return(await Si(t,e)).length}function Ti(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 ji(t,e){let n,r=1984,i=!0,s=!1,o=!0,a=Ei,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 Oi(t,e){let n,r=1984,i=!0,s=Ei,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 Ii(t,e){let n,r=1984,i=Ei;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 Ci from"fs";async function*Ni(t,e){const n=(e={...e,completeSentence:!1,corrected:!1}).size??1984,r=e.modelId,i=e.metaInfo?.size??(await Ci.promises.stat(t)).size;let s=Math.trunc(i/2);if(s<=n){let i=Hn(await Ci.promises.readFile(t));if(s=await Ei(i,r),s<=n)yield i;else do{const t=await ji(i,{...e,modelId:r,size:n});yield t,i=i.slice(t.length)}while(i)}else{const i=ReadableStream.from(Ci.createReadStream(t)).getReader();let s="";for(;;){const{done:t,value:o}=await i.read();if(t)break;s+=Hn(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 ji(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 ji(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 ji(s,{...e,modelId:r,size:n,sentences:t});s=s.slice(i.length),yield i}}}async function*Mi(t,e){const n=e?.size??1984,r=e?.modelId,i=e?.metaInfo?.size??(await Ci.promises.stat(t)).size;let s=Math.trunc(i/2);if(s<=n){let i=Hn(await Ci.promises.readFile(t));if(s=await Ei(i,r),s<=n)yield pt(i,e);else{let t=pt(i,e);do{const i=await Oi(t,{...e,modelId:r,size:n});yield i,t=t.slice(i.length)}while(t.length)}}else{const i=ReadableStream.from(Ci.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+=Hn(o),u=pt(s,e);let a=u.pop();if(s.length>=n){const t=await Oi(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 Oi(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 Oi(u,{...e,modelId:r,size:n});u=u.slice(t.length),yield t}}}async function Ri(t,e){const n=e?.size??1984,r=e?.modelId;let i=pt(t,e);const s=[];if(await Ei(t,r)<=n)s.push(i);else do{const t=await Oi(i,{...e,modelId:r,size:n});s.push(t),i=i.slice(t.length)}while(i.length);return s}import{YAMLMap as zi}from"yaml";var Li=class{constructor(t){t&&Object.assign(this,t)}};function _i(t,e){const n={tag:t,collection:"map",nodeClass:class extends zi{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 Xi(t,e){let n=t.length===e.length;if(n){const r=_e(t),i=_e(e);n=r.every((t,e)=>t===i[e])}return n}import{defaultsDeep as Di,get as Pi,omit as Fi,set as Bi}from"lodash-es";import qi from"path";var Ui=".ai";function Gi(t,e=["."]){if(qi.isAbsolute(t))return ur.loadSync(t);const n=e.map(e=>ur.loadSync(qi.resolve(e,t))).filter(Boolean);return Di({},...n.reverse())}function Wi(t,e){const n={...process.env,...e};return W(t,{processEnv:n,parsed:n})}function Zi(t,e){let n=ur.loadSync(qi.resolve(e.configDir,t));n||(n={configDirs:["$XDG_BIN_HOME",e.configDir,"$HOME"],brainDir:qi.join(e.dataDir,"brain"),agentDirs:[qi.join(e.dataDir,"agent")],promptDirs:[qi.join(e.dataDir,"prompt")],chatsDir:qi.join(e.dataDir,"log","chats"),inputsDir:qi.join(e.dataDir,"log","inputs")});const r=Hi(e);for(const[t,e]of Object.entries(r))n[t]=e;Wi(n,n);const i=n.configDirs;n.AI_CONFIG_BASENAME&&(t=n.AI_CONFIG_BASENAME);const s=Wi(Gi(t,i),n);return Di(s,Fi(n,Object.keys(r))),Vi(s),s}function Ji(t){return Zi(".ai",t)}function Hi(t){return{XDG_CONFIG_HOME:t.configDir,XDG_DATA_HOME:t.dataDir,XDG_CACHE_HOME:t.cacheDir,XDG_BIN_HOME:qi.dirname(t.options.root)}}function Ki(t,e){t.startsWith("~")&&(t="$HOME"+t.slice(1));return Wi(t,e)}function Qi(t,e){return t.map(t=>Ki(t,e))}function Vi(t,e=["configDirs","brainDir","agentDirs","promptDirs","chatsDir","inputsDir"],n){for(const r of e){const e=Pi(t,r);if(!e)continue;let i;Array.isArray(e)&&e.length?i=Qi(e,n):"string"==typeof e&&(i=Ki(e,n)),i&&Bi(t,r,i)}}var{exit:Yi}=process,ts=!1,es=!1,ns=["SIGINT","SIGTERM","exit"],rs=[],is=(t,e)=>t.forEach(t=>process.once(t,e));async function ss(t="shutdown",e=0){if(!ts){ts=!0,"number"==typeof t&&(e=t,t="shutdown");for(const e of rs)try{await e(t)}catch(t){console.warn(`A shutdown handler failed before completing with: ${t.message||t}`)}return Yi(e)}console.warn(`Shutdown already in progress, ignoring [${t}] signal`)}function os(t){if(es||as(),!rs.some(e=>e===t))return rs.push(t),t}function as(){var t;es||(es=!0,process.exit=t=>{ts||ss(void 0,t).then()},is(ns,(t=3e5,()=>{setTimeout(()=>(console.warn(`Could not close resources gracefully after ${t}ms: forcing shutdown`),Yi(1)),t).unref()})),is(ns,ss))}var cs=["<BOS>","<EOS>","<PAD>","<UNK>"],us=".,!?;?!",fs=[" ","\n","\t","▁"," "],hs=["the","a","an","的","是","在"];function ls(t,e){const n=e?.exclude?function(t){const e=new Set;if(t.controlSymbols&&cs.forEach(t=>e.add(t)),t.punctuation)for(let t=0;t<7;t++)e.add(us[t]);return t.stopWords&&hs.forEach(t=>e.add(t)),t.whitespace&&fs.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()))),ms(t)}function ms(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 ps}from"lodash-es";var ds=/^\s*@inheritMerge\s*(?:[(]\s*(?<arg>\.start|\.end|false)[)])?/,ys=Symbol("MergeWay"),ws={replace:0,start:1,end:2};function bs(t,...e){return ps(t,...e,(t,e)=>Array.isArray(t)&&Array.isArray(e)?vs(t,e):void 0!==t&&"object"!=typeof t?t:void 0)}function vs(t,e){let n=t[ys];return void 0===n&&(t=function(t){const e=t[0];let n=".start";if("string"==typeof e){const r=ds.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=ws.start;"false"===n||"no"===n||"not"===n?r=ws.replace:".end"===n&&(r=ws.end);return Object.defineProperty(t,ys,{value:r,enumerable:!1}),t}(t),n=t[ys]),t=n===ws.replace?e:n===ws.end?t.concat(e):e.concat(t),Object.defineProperty(t,ys,{value:n,enumerable:!1}),t}function gs(t,e=" "){return ks(t).join(e)}function ks(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 $s(t){if(void 0!==t){const e=JSON.stringify(t);if("{}"!==e&&"[]"!==e&&'""'!==e)return"?p="+encodeURIComponent(e)}return""}var xs=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),Sr.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),Sr.has(e,t)}isStream(t){let e=this.stream;if(e){const n=this.params;n?.stream&&(e=t?.stream)}return e}},As={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"]}};xs.defineProperties(xs,As);var Ss=Symbol("meta");function Es(t,r,i=!0){if(r&&"object"==typeof r){if("function"==typeof t)return r=i?e({},t[Ss],r):n({},t[Ss],r),t[Ss]=r,t;if(t instanceof xs)return t.assign(r)}}function Ts(t){return"function"==typeof t?t[Ss]:t instanceof xs?t.toObject():void 0}var js=class extends xs{constructor(){super(...arguments),this._emitter=new t,this.description="Return event bus",this.result="event"}get emitter(){return this._emitter}func(){return this.emitter}},Os=new js(Ft);import{Cache as Is}from"secondary-cache";import{LRUCache as Cs}from"secondary-cache";var Ns=Is;function Ms({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 Rs(t,e){let n=xs.get(t);return n||(n=new xs(t,{func:Ms,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 Is(e)),n}var zs=Rs("lrucache"),Ls="A client transport has not been set. Use ClientTools.setTransport() or transport.mount(ClientTools) first.",_s=class t extends xs{static get apiRoot(){return this._transport||b(Ls,"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(Ls,"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){const r=this.constructor;if(r._transport)return r._transport.fetch(this.name,t,e,n,this.fetchOptions);b(Ls,"ClientTools")}async func(t){return await this.fetch(t)}},Xs={...x};_s.defineProperties(_s,Xs);var Ds=class extends _s{async fetch(t,e,n){return t||(t={}),e?.startsWith("$")&&(t.act=e,e="post"),await super.fetch(t,e,n)}async _func(t,e){return await this.fetch(e,t)}async func(t){const e=t.action;return e&&delete t.action,this._func(e,t)}assignMethods(t){if(Array.isArray(t))for(const e of t){const t=e.startsWith("$")?e.slice(1):e;this[t]||(this[t]=(t=>this._func.bind(this,t))(e))}}},Ps={methods:{type:"array",assign(t,e,n,r,i){i?.isExported||e.assignMethods(t)}}};Ds.defineProperties(Ds,Ps);var Fs=class extends Ds{async fetch(t,e){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)}},Bs=class extends Fs{constructor(){super(...arguments),this._sseListeners={},this._forwardEvents=new Set,this.description="subscribe server event",this.ebListener=async function(...t){const e=this.type;this.target.publish&&await this.target.publish({data:t,event:e})}}static setPubSubTransport(t){this._pubSubTransport=t}static get pubSubTransport(){if(!this._pubSubTransport)throw new Error("EventClient pubSubTransport not set");return this._pubSubTransport}get evtSource(){let t=this._stream;return t&&2!==t.readyState||(t=this.initEventStream(this._streamEvents)),t}get active(){return!!this._stream&&2!==this._stream.readyState}set active(t){t!==this.active&&(t?this.initEventStream(this._streamEvents):this._stream&&this.close())}initEventStream(t){const e="string"==typeof t?[t]:t;if(this._stream&&2!==this._stream.readyState){if(!this._streamEvents||e&&e.every(t=>this._streamEvents.includes(t)))return this._stream;this._stream.close()}const n=e?$s({event:e}):"",r=`${this.apiRoot}/${this.name}${n}`,i=this._stream=this.constructor.pubSubTransport.connect(r);return Object.entries(this._sseListeners).forEach(([t,e])=>{i.on(t,e)}),this._streamEvents=e,i}esListener(t,e,n){if(!this._forwardEvents.has(t)){const n=this.emitter;n&&t&&(Array.isArray(e)?n.emit(t,...e):n.emit(t,e))}}async subscribe(t){const e=await this.sub({event:t});"string"==typeof t&&(t=[t]);const n=this.evtSource;for(const e of t)if(!this._sseListeners[e]){const t=this._sseListeners[e]=(t,n)=>this.esListener(e,t,n);n.on(e,t)}return e}async unsubscribe(t){"string"==typeof t&&(t=[t]);const e=await this.unsub({event:t}),n=this.evtSource;for(const e of t){const t=this._sseListeners[e];t&&(delete this._sseListeners[e],n.off(e,t))}return e}forwardEvent(t){"string"==typeof t&&(t=[t]);for(const e of t)this._forwardEvents.has(e)||(this._forwardEvents.add(e),this.on&&this.on(e,this.ebListener))}unforwardEvent(t){"string"==typeof t&&(t=[t]);for(const e of t)this._forwardEvents.has(e)&&(this._forwardEvents.delete(e),this.off&&this.off(e,this.ebListener))}async init(t){if(this.active=!1,this.initEventStream(t),t)return await this.subscribe(t)}close(){const t=this._stream;if(t)return this._stream=void 0,t.close()}},qs=new Bs(Pt);import{getAllNames as Us}from"util-ex";var Gs=class t extends xs{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){}},Ws={...x};Gs.defineProperties(Gs,Ws);var Zs=class extends Gs{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);Us(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)}},Js={methods:{type:"array"}};Zs.defineProperties(Zs,Js);var Hs=class extends Zs{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"),"post"===e&&t.act&&(e=t.act),e}castParams(t){return void 0!==t.id&&(t.id=this.cast("id",t.id)),t}},Ks=Os.runSync(),Qs=class t extends Hs{constructor(){super(...arguments),this.description="subscribe server event",this.result="event",this.depends={[Ft]:Os}}static setPubSubTransport(t){this._pubSubTransport=t}static get pubSubTransport(){return this._pubSubTransport||console.warn("EventServer pubSubTransport not set"),this._pubSubTransport}get pubSubTransport(){return this.constructor.pubSubTransport}static publish(t,e,n){return this.pubSubTransport?.publish(e,t,n)}static ebListener(t,...e){this.pubSubTransport?.publish(t,e)}static subscribe(t,e,n,r){return this.pubSubTransport?.subscribe(n,{...r,req:t,res:e})}static alreadyForward(t){const e=Ks.listeners(t);for(const t of e)if(t===this._boundEbListener)return!0}publishSSE(t,e){return this.constructor.publish(t,e)}subscribeSSE(t,e,n){return"string"==typeof n&&(n=[n]),this.constructor.subscribe(t,e,n)}forward(e){Array.isArray(e)||(e=[e]);const n=this.constructor;n._boundEbListener||(n._boundEbListener=function(...t){return n.ebListener(this.type,...t)});for(const r of e)t.alreadyForward(r)||Ks.on(r,n._boundEbListener)}unforward(t){"string"==typeof t&&(t=[t]);const e=this.constructor;if(e._boundEbListener)for(const n of t)Ks.off(n,e._boundEbListener)}list({_req:t,_res:e,event:n}){t&&e&&this.subscribeSSE(t,e,n)}$sub({event:t}){if(t)return this.forward(t),{event:t};b("event is required","sub",l.InvalidArgument)}$unsub({event:t}){if(t)return this.unforward(t),{event:t};b("event is required","unsub",l.InvalidArgument)}$publish({event:t,data:e}){if(t&&e){"string"==typeof t&&(t=[t]);for(const n of t)this.publishSSE(e,n);return{event:t}}b("event or data is required","pub",l.InvalidArgument)}isStream(t){return"list"===this.getMethodFromParams(t)}},Vs=new Qs(Pt);function Ys(){Os.register(),zs.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,O as parseISO,I as toDate,L as AITextGenerationFinishReasons,_ as AIMessageTypes,X as AIChatRoles,D as StrangeHumanName,P 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,Ot as removeMarkdownBoldAndItalic,It as splitParagraph,Ct as truncTo,Nt as sleep,Mt as wait,Rt as yieldExec,Pt as EventName,Ft as EventBusName,Bt as backendEventable,Lt as EventEmitter,_t as eventable,Xt as states,Dt as wrapEventEmitter,Ut as SSEChannelAlreadyClosedErrCode,Gt as SSEChannel,Wt as isWebStream,Zt as RStreamErrCode,Jt as ResponseRStreamErrCode,Ht as ReadableStreamError,Kt as getResponseErrorReadableStream,Qt as createEmptyReadableStream,Yt as createEventStreamTransformer,te as trimStartOfStreamHelper,ee as AIStream,ne as readableFromAsyncIterable,re as createCallbacksTransformer,we as uuid,ce as v1,ue as v4,fe as v5,he as stringify,le as parse,me as validate,pe as version,de as NIL,Ce as HashAlgorithm,ze as xxhash32,Le as xxhash64,_e as xxhash,Xe as xxhashAsStr,De as canonicalize,Fe as base32768,Be as hashStream,qe as hash,Ue as hashObject,Ge as extNameLevel,We as FilenameReservedRegex,Ze as getMultiLevelExtname,Je as isValidFilename,He as isValidFilepath,Ke as sanitizeFilename,Qe as sanitizeFilepath,Ve as WindowsReservedNameRegex,en as isModelNameMatched,nn as getAllEnumKeys,un as parseObjectArguments,hn as ObjectArgsToArgsInfo,ln as simplifyObjectArguments,mn as parseObjectArgumentInfos,pn as ChoiceArgProcessor,dn as TemplateArgProcessor,yn as AIArgProcessor,wn as isQuoted,bn as isStrWrapped,vn as ensureQuoted,gn as quoteStr,An as parseObjectArgInfo,Sn as parseObjectArgumentsAsArgInfos,En as parseCommand,jn as replaceWithPlaceholder,On as restoreFromPlacehoders,Mn as parseJsJson,Rn as parseJsJsonSimpleSync,_n as filterValidFnScope,Xn as getKeysPath,Pn as createEndWithRepetitionDetector,Gn as fileIsExists,Wn as loadFileFromPaths,Jn as loadTextFromPaths,Hn as decodeCharset,Kn as readFilenamesRecursiveSync,Qn as getRealFilepath,Vn as hashFile,Yn as getFileMetaInfo,tr as getHashAlgoBySize,er as detectCharset,mr as getConfigFileNames,pr as getConfigs,dr as saveConfigFile,cr as mimeType,ur as ConfigFile,fr as registerYamlTag,hr as parseYaml,lr as stringifyYaml,gr as jsonFilterToWhere,kr as matchUrlProtocol,$r as paramsSizeToScaleStr,xr as scaleStrToParamsSize,Ar as jsonToMarkdownStr,Sr as IntSet,Cr as DefaultAsyncSemaphoreCapacity,Rr as BinarySemaphore,zr as Semaphore,Lr as RateLimit,Xr as SignalGate,Br as ToolAsyncMultiTaskBit,qr as ToolAsyncCancelableBit,Ur as ToolAsyncPriorityBit,Gr as AsyncFeatureBits,Wr as AsyncFeatures,Zr as TaskAbortController,Jr as CancelableAbility,Kr as makeToolFuncCancelable,Qr as countRegexMatches,ti as memoize,ri as getPackageDir,si as isSubdirectory,oi as hasDirectoryIn,ai as assignDirs,ci as pruneSubdirectories,ui as pruneSubdirectoriesInPlace,fi as normalizePath,mi as isRegExp,pi as stripConsoleColor,$i as LLM_TOKENIZER_NAMES,xi as LLM_TOKENIZER_NAMES_MAP,Ai as getLLMTokenizer,Si as encodeLLMTokens,Ei as countLLMTokens,Ti as formatTextWithSpace,ji as truncateToTokenLimit,Oi as truncateToTokenLimitEx,Ii as truncateByToken,Ni as readTextFileChunks,Mi as readTextFileChunksEx,Ri as splitChunks,Li as YamlTypeBaseObject,_i as createYamlObjectTag,Xi as isSameString,Ui as DEFAULT_CONFIG_NAME,Gi as loadConfigFile,Wi as expandConfig,Zi as loadConfig,Ji as loadAIConfig,Hi as getXDGConfigs,Ki as expandPath,Qi as expandPaths,Vi as expandPathInObject,ns as SHUTDOWN_SIGNALS,ss as shutdown,os as beforeShutdown,as as initShutdown,ls as calcPerplexity,ms as calcPerplexitySimple,ys as ArrayMergeWaySymbol,ws as ArrayMergeWay,bs as defaultsWithConcat,vs as mergeArray,gs as joinSplitWords,ks as splitWords,$s as genUrlParamsStr,v as createAbilityInjector,g as toRegExp,xs as ToolFunc,As as ToolFuncSchema,Ss as FuncMetaSymbol,Es as funcWithMeta,Ts as funcGetMeta,_s as ClientTools,Xs as ClientToolFuncSchema,Gs as ServerTools,Ws as ServerToolFuncSchema,js as EventToolFunc,Os as event,Ns as SecondaryCache,Ms as _lrucache,Rs as createLRUCache,zs as lrucache,Cs as LRUCache,Ds as RpcMethodsClientTool,Ps as RpcMethodsClientToolSchema,Fs as ResClientTools,Bs as EventClient,qs as eventClient,Zs as RpcMethodsServerTool,Js as RpcMethodsServerToolSchema,Hs as ResServerTools,Qs as EventServer,Vs as eventServer,Ys as registerCoreTools};
package/dist/funcs.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- export { ae as EventClient, ad as EventClientFuncParams, ah as EventServer, ag as EventServerFuncParams, a7 as EventToolFunc, a9 as SecondaryCache, aa as _lrucache, ab as createLRUCache, a8 as event, af as eventClient, ai as eventServer, ac as lrucache, a6 as registerCoreTools } from './index-BCco-g_I.mjs';
1
+ export { ae as EventClient, ad as EventClientFuncParams, ah as EventServer, ag as EventServerFuncParams, a7 as EventToolFunc, a9 as SecondaryCache, aa as _lrucache, ab as createLRUCache, a8 as event, af as eventClient, ai as eventServer, ac as lrucache, a6 as registerCoreTools } from './index-DEUnmyUq.mjs';
2
2
  export { LRUCache } from 'secondary-cache';
3
3
  import 'events-ex';
4
4
  import 'property-manager';
package/dist/funcs.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { ae as EventClient, ad as EventClientFuncParams, ah as EventServer, ag as EventServerFuncParams, a7 as EventToolFunc, a9 as SecondaryCache, aa as _lrucache, ab as createLRUCache, a8 as event, af as eventClient, ai as eventServer, ac as lrucache, a6 as registerCoreTools } from './index-BCco-g_I.js';
1
+ export { ae as EventClient, ad as EventClientFuncParams, ah as EventServer, ag as EventServerFuncParams, a7 as EventToolFunc, a9 as SecondaryCache, aa as _lrucache, ab as createLRUCache, a8 as event, af as eventClient, ai as eventServer, ac as lrucache, a6 as registerCoreTools } from './index-DEUnmyUq.js';
2
2
  export { LRUCache } from 'secondary-cache';
3
3
  import 'events-ex';
4
4
  import 'property-manager';
package/dist/funcs.mjs CHANGED
@@ -1 +1 @@
1
- import{EventClient as m,EventServer as o,EventToolFunc as r,LRUCache as p,SecondaryCache as t,_lrucache as N,createLRUCache as c,event as h,eventClient as i,eventServer as j,lrucache as k,registerCoreTools as n}from"./chunk-LNTIQQNN.mjs";import"./chunk-VIG2GB47.mjs";export{m as EventClient,o as EventServer,r as EventToolFunc,p as LRUCache,t as SecondaryCache,N as _lrucache,c as createLRUCache,h as event,i as eventClient,j as eventServer,k as lrucache,n as registerCoreTools};
1
+ import{EventClient as m,EventServer as o,EventToolFunc as r,LRUCache as p,SecondaryCache as t,_lrucache as c,createLRUCache as h,event as i,eventClient as j,eventServer as k,lrucache as n,registerCoreTools as s}from"./chunk-4XRPAC7C.mjs";import"./chunk-VIG2GB47.mjs";export{m as EventClient,o as EventServer,r as EventToolFunc,p as LRUCache,t as SecondaryCache,c as _lrucache,h as createLRUCache,i as event,j as eventClient,k as eventServer,n as lrucache,s as registerCoreTools};
@@ -1396,6 +1396,12 @@ declare class RpcMethodsClientTool extends ClientTools {
1396
1396
  func(options: RpcMethodsClientFuncParams): Promise<any>;
1397
1397
  assignMethods(methods: string[]): void;
1398
1398
  }
1399
+ declare const RpcMethodsClientToolSchema: {
1400
+ methods: {
1401
+ type: string;
1402
+ assign(value: string[], dest: RpcMethodsClientTool, src?: any, name?: string, options?: any): void;
1403
+ };
1404
+ };
1399
1405
 
1400
1406
  interface ResClientFuncParams extends RpcMethodsClientFuncParams {
1401
1407
  id?: string | number;
@@ -1715,6 +1721,11 @@ declare class RpcMethodsServerTool extends ServerTools {
1715
1721
  castParams(params: RpcMethodsServerFuncParams): RpcMethodsServerFuncParams;
1716
1722
  func(params: RpcMethodsServerFuncParams): any;
1717
1723
  }
1724
+ declare const RpcMethodsServerToolSchema: {
1725
+ methods: {
1726
+ type: string;
1727
+ };
1728
+ };
1718
1729
 
1719
1730
  interface ResServerFuncParams extends RpcMethodsServerFuncParams {
1720
1731
  id?: string | number;
@@ -1778,4 +1789,4 @@ declare const eventServer: EventServer;
1778
1789
 
1779
1790
  declare function registerCoreTools(): void;
1780
1791
 
1781
- export { funcGetMeta as $, type AsyncTaskId as A, type BinarySemaphoreOptions as B, ClientToolTransport as C, DefaultAsyncSemaphoreCapacity as D, TaskAbortController as E, type Funcs as F, type TaskAbortControllers as G, type TaskPromise as H, type IPubSubServerTransport as I, CancelableAbility as J, makeToolFuncCancelable as K, type FuncParamType as L, type FuncParam as M, type FuncParams as N, type TFunc as O, type PubSubClientId as P, type BaseFuncItem as Q, RemoteToolFuncSchema as R, ServerTools as S, ToolTransport as T, type FuncItem as U, type BaseFunc as V, type ToolFuncPackage as W, ToolFunc as X, ToolFuncSchema as Y, FuncMetaSymbol as Z, funcWithMeta as _, type AIModelNameRules as a, ClientTools as a0, type ClientFuncItem as a1, ClientToolFuncSchema as a2, type ServerFuncParams as a3, type ServerFuncItem as a4, ServerToolFuncSchema as a5, registerCoreTools as a6, EventToolFunc as a7, event as a8, SecondaryCache as a9, _lrucache as aa, createLRUCache as ab, lrucache as ac, type EventClientFuncParams as ad, EventClient as ae, eventClient as af, type EventServerFuncParams as ag, EventServer as ah, eventServer as ai, type ResClientFuncParams as aj, ResClientTools as ak, type ResServerFuncParams as al, ResServerTools as am, type RpcMethodHandler as an, type IClientToolTransport as ao, type PubSubCtx as ap, type PubSubClient as aq, type PubSubServerSession as b, type IPubSubClientTransport as c, type PubSubClientStream as d, type IToolTransport as e, type ActionName as f, PASSING_SCORE as g, ActionNames as h, type AIModelNameRuleFn as i, type AIModelNameRule as j, type RemoteFuncItem as k, type SemaphoreIsReadyFuncType as l, type BinarySemaphoreAcquireOptions as m, type BinarySemaphoreReleaseOptions as n, type BinarySemaphoreReleaserFunc as o, type SemaphoreOptions as p, type SemaphoreTaskItem as q, BinarySemaphore as r, Semaphore as s, RateLimit as t, ToolAsyncMultiTaskBit as u, ToolAsyncCancelableBit as v, ToolAsyncPriorityBit as w, AsyncFeatureBits as x, AsyncFeatures as y, type CancelableAbilityOptions as z };
1792
+ export { funcGetMeta as $, type AsyncTaskId as A, type BinarySemaphoreOptions as B, ClientToolTransport as C, DefaultAsyncSemaphoreCapacity as D, TaskAbortController as E, type Funcs as F, type TaskAbortControllers as G, type TaskPromise as H, type IPubSubServerTransport as I, CancelableAbility as J, makeToolFuncCancelable as K, type FuncParamType as L, type FuncParam as M, type FuncParams as N, type TFunc as O, type PubSubClientId as P, type BaseFuncItem as Q, RemoteToolFuncSchema as R, ServerTools as S, ToolTransport as T, type FuncItem as U, type BaseFunc as V, type ToolFuncPackage as W, ToolFunc as X, ToolFuncSchema as Y, FuncMetaSymbol as Z, funcWithMeta as _, type AIModelNameRules as a, ClientTools as a0, type ClientFuncItem as a1, ClientToolFuncSchema as a2, type ServerFuncParams as a3, type ServerFuncItem as a4, ServerToolFuncSchema as a5, registerCoreTools as a6, EventToolFunc as a7, event as a8, SecondaryCache as a9, _lrucache as aa, createLRUCache as ab, lrucache as ac, type EventClientFuncParams as ad, EventClient as ae, eventClient as af, type EventServerFuncParams as ag, EventServer as ah, eventServer as ai, type RpcMethodsClientFuncParams as aj, RpcMethodsClientTool as ak, RpcMethodsClientToolSchema as al, type RpcMethodsServerFuncParams as am, RpcMethodsServerTool as an, RpcMethodsServerToolSchema as ao, type ResClientFuncParams as ap, ResClientTools as aq, type ResServerFuncParams as ar, ResServerTools as as, type RpcMethodHandler as at, type IClientToolTransport as au, type PubSubCtx as av, type PubSubClient as aw, type PubSubServerSession as b, type IPubSubClientTransport as c, type PubSubClientStream as d, type IToolTransport as e, type ActionName as f, PASSING_SCORE as g, ActionNames as h, type AIModelNameRuleFn as i, type AIModelNameRule as j, type RemoteFuncItem as k, type SemaphoreIsReadyFuncType as l, type BinarySemaphoreAcquireOptions as m, type BinarySemaphoreReleaseOptions as n, type BinarySemaphoreReleaserFunc as o, type SemaphoreOptions as p, type SemaphoreTaskItem as q, BinarySemaphore as r, Semaphore as s, RateLimit as t, ToolAsyncMultiTaskBit as u, ToolAsyncCancelableBit as v, ToolAsyncPriorityBit as w, AsyncFeatureBits as x, AsyncFeatures as y, type CancelableAbilityOptions as z };
@@ -1396,6 +1396,12 @@ declare class RpcMethodsClientTool extends ClientTools {
1396
1396
  func(options: RpcMethodsClientFuncParams): Promise<any>;
1397
1397
  assignMethods(methods: string[]): void;
1398
1398
  }
1399
+ declare const RpcMethodsClientToolSchema: {
1400
+ methods: {
1401
+ type: string;
1402
+ assign(value: string[], dest: RpcMethodsClientTool, src?: any, name?: string, options?: any): void;
1403
+ };
1404
+ };
1399
1405
 
1400
1406
  interface ResClientFuncParams extends RpcMethodsClientFuncParams {
1401
1407
  id?: string | number;
@@ -1715,6 +1721,11 @@ declare class RpcMethodsServerTool extends ServerTools {
1715
1721
  castParams(params: RpcMethodsServerFuncParams): RpcMethodsServerFuncParams;
1716
1722
  func(params: RpcMethodsServerFuncParams): any;
1717
1723
  }
1724
+ declare const RpcMethodsServerToolSchema: {
1725
+ methods: {
1726
+ type: string;
1727
+ };
1728
+ };
1718
1729
 
1719
1730
  interface ResServerFuncParams extends RpcMethodsServerFuncParams {
1720
1731
  id?: string | number;
@@ -1778,4 +1789,4 @@ declare const eventServer: EventServer;
1778
1789
 
1779
1790
  declare function registerCoreTools(): void;
1780
1791
 
1781
- export { funcGetMeta as $, type AsyncTaskId as A, type BinarySemaphoreOptions as B, ClientToolTransport as C, DefaultAsyncSemaphoreCapacity as D, TaskAbortController as E, type Funcs as F, type TaskAbortControllers as G, type TaskPromise as H, type IPubSubServerTransport as I, CancelableAbility as J, makeToolFuncCancelable as K, type FuncParamType as L, type FuncParam as M, type FuncParams as N, type TFunc as O, type PubSubClientId as P, type BaseFuncItem as Q, RemoteToolFuncSchema as R, ServerTools as S, ToolTransport as T, type FuncItem as U, type BaseFunc as V, type ToolFuncPackage as W, ToolFunc as X, ToolFuncSchema as Y, FuncMetaSymbol as Z, funcWithMeta as _, type AIModelNameRules as a, ClientTools as a0, type ClientFuncItem as a1, ClientToolFuncSchema as a2, type ServerFuncParams as a3, type ServerFuncItem as a4, ServerToolFuncSchema as a5, registerCoreTools as a6, EventToolFunc as a7, event as a8, SecondaryCache as a9, _lrucache as aa, createLRUCache as ab, lrucache as ac, type EventClientFuncParams as ad, EventClient as ae, eventClient as af, type EventServerFuncParams as ag, EventServer as ah, eventServer as ai, type ResClientFuncParams as aj, ResClientTools as ak, type ResServerFuncParams as al, ResServerTools as am, type RpcMethodHandler as an, type IClientToolTransport as ao, type PubSubCtx as ap, type PubSubClient as aq, type PubSubServerSession as b, type IPubSubClientTransport as c, type PubSubClientStream as d, type IToolTransport as e, type ActionName as f, PASSING_SCORE as g, ActionNames as h, type AIModelNameRuleFn as i, type AIModelNameRule as j, type RemoteFuncItem as k, type SemaphoreIsReadyFuncType as l, type BinarySemaphoreAcquireOptions as m, type BinarySemaphoreReleaseOptions as n, type BinarySemaphoreReleaserFunc as o, type SemaphoreOptions as p, type SemaphoreTaskItem as q, BinarySemaphore as r, Semaphore as s, RateLimit as t, ToolAsyncMultiTaskBit as u, ToolAsyncCancelableBit as v, ToolAsyncPriorityBit as w, AsyncFeatureBits as x, AsyncFeatures as y, type CancelableAbilityOptions as z };
1792
+ export { funcGetMeta as $, type AsyncTaskId as A, type BinarySemaphoreOptions as B, ClientToolTransport as C, DefaultAsyncSemaphoreCapacity as D, TaskAbortController as E, type Funcs as F, type TaskAbortControllers as G, type TaskPromise as H, type IPubSubServerTransport as I, CancelableAbility as J, makeToolFuncCancelable as K, type FuncParamType as L, type FuncParam as M, type FuncParams as N, type TFunc as O, type PubSubClientId as P, type BaseFuncItem as Q, RemoteToolFuncSchema as R, ServerTools as S, ToolTransport as T, type FuncItem as U, type BaseFunc as V, type ToolFuncPackage as W, ToolFunc as X, ToolFuncSchema as Y, FuncMetaSymbol as Z, funcWithMeta as _, type AIModelNameRules as a, ClientTools as a0, type ClientFuncItem as a1, ClientToolFuncSchema as a2, type ServerFuncParams as a3, type ServerFuncItem as a4, ServerToolFuncSchema as a5, registerCoreTools as a6, EventToolFunc as a7, event as a8, SecondaryCache as a9, _lrucache as aa, createLRUCache as ab, lrucache as ac, type EventClientFuncParams as ad, EventClient as ae, eventClient as af, type EventServerFuncParams as ag, EventServer as ah, eventServer as ai, type RpcMethodsClientFuncParams as aj, RpcMethodsClientTool as ak, RpcMethodsClientToolSchema as al, type RpcMethodsServerFuncParams as am, RpcMethodsServerTool as an, RpcMethodsServerToolSchema as ao, type ResClientFuncParams as ap, ResClientTools as aq, type ResServerFuncParams as ar, ResServerTools as as, type RpcMethodHandler as at, type IClientToolTransport as au, type PubSubCtx as av, type PubSubClient as aw, type PubSubServerSession as b, type IPubSubClientTransport as c, type PubSubClientStream as d, type IToolTransport as e, type ActionName as f, PASSING_SCORE as g, ActionNames as h, type AIModelNameRuleFn as i, type AIModelNameRule as j, type RemoteFuncItem as k, type SemaphoreIsReadyFuncType as l, type BinarySemaphoreAcquireOptions as m, type BinarySemaphoreReleaseOptions as n, type BinarySemaphoreReleaserFunc as o, type SemaphoreOptions as p, type SemaphoreTaskItem as q, BinarySemaphore as r, Semaphore as s, RateLimit as t, ToolAsyncMultiTaskBit as u, ToolAsyncCancelableBit as v, ToolAsyncPriorityBit as w, AsyncFeatureBits as x, AsyncFeatures as y, type CancelableAbilityOptions as z };
package/dist/index.d.mts CHANGED
@@ -1,8 +1,8 @@
1
1
  import * as custom_ability from 'custom-ability';
2
2
  export { createAbilityInjector } from 'custom-ability';
3
3
  export { toRegExp } from 'util-ex';
4
- import { A as AsyncTaskId, a as AIModelNameRules, I as IPubSubServerTransport, P as PubSubClientId, b as PubSubServerSession, c as IPubSubClientTransport, d as PubSubClientStream, e as IToolTransport, S as ServerTools, T as ToolTransport, C as ClientToolTransport, F as Funcs, f as ActionName } from './index-BCco-g_I.mjs';
5
- export { j as AIModelNameRule, i as AIModelNameRuleFn, h as ActionNames, x as AsyncFeatureBits, y as AsyncFeatures, V as BaseFunc, Q as BaseFuncItem, r as BinarySemaphore, m as BinarySemaphoreAcquireOptions, B as BinarySemaphoreOptions, n as BinarySemaphoreReleaseOptions, o as BinarySemaphoreReleaserFunc, J as CancelableAbility, z as CancelableAbilityOptions, a1 as ClientFuncItem, a2 as ClientToolFuncSchema, a0 as ClientTools, D as DefaultAsyncSemaphoreCapacity, ae as EventClient, ad as EventClientFuncParams, ah as EventServer, ag as EventServerFuncParams, a7 as EventToolFunc, U as FuncItem, Z as FuncMetaSymbol, M as FuncParam, L as FuncParamType, N as FuncParams, ao as IClientToolTransport, g as PASSING_SCORE, aq as PubSubClient, ap as PubSubCtx, t as RateLimit, k as RemoteFuncItem, R as RemoteToolFuncSchema, aj as ResClientFuncParams, ak as ResClientTools, al as ResServerFuncParams, am as ResServerTools, an as RpcMethodHandler, a9 as SecondaryCache, s as Semaphore, l as SemaphoreIsReadyFuncType, p as SemaphoreOptions, q as SemaphoreTaskItem, a4 as ServerFuncItem, a3 as ServerFuncParams, a5 as ServerToolFuncSchema, O as TFunc, E as TaskAbortController, G as TaskAbortControllers, H as TaskPromise, v as ToolAsyncCancelableBit, u as ToolAsyncMultiTaskBit, w as ToolAsyncPriorityBit, X as ToolFunc, W as ToolFuncPackage, Y as ToolFuncSchema, aa as _lrucache, ab as createLRUCache, a8 as event, af as eventClient, ai as eventServer, $ as funcGetMeta, _ as funcWithMeta, ac as lrucache, K as makeToolFuncCancelable, a6 as registerCoreTools } from './index-BCco-g_I.mjs';
4
+ import { A as AsyncTaskId, a as AIModelNameRules, I as IPubSubServerTransport, P as PubSubClientId, b as PubSubServerSession, c as IPubSubClientTransport, d as PubSubClientStream, e as IToolTransport, S as ServerTools, T as ToolTransport, C as ClientToolTransport, F as Funcs, f as ActionName } from './index-DEUnmyUq.mjs';
5
+ export { j as AIModelNameRule, i as AIModelNameRuleFn, h as ActionNames, x as AsyncFeatureBits, y as AsyncFeatures, V as BaseFunc, Q as BaseFuncItem, r as BinarySemaphore, m as BinarySemaphoreAcquireOptions, B as BinarySemaphoreOptions, n as BinarySemaphoreReleaseOptions, o as BinarySemaphoreReleaserFunc, J as CancelableAbility, z as CancelableAbilityOptions, a1 as ClientFuncItem, a2 as ClientToolFuncSchema, a0 as ClientTools, D as DefaultAsyncSemaphoreCapacity, ae as EventClient, ad as EventClientFuncParams, ah as EventServer, ag as EventServerFuncParams, a7 as EventToolFunc, U as FuncItem, Z as FuncMetaSymbol, M as FuncParam, L as FuncParamType, N as FuncParams, au as IClientToolTransport, g as PASSING_SCORE, aw as PubSubClient, av as PubSubCtx, t as RateLimit, k as RemoteFuncItem, R as RemoteToolFuncSchema, ap as ResClientFuncParams, aq as ResClientTools, ar as ResServerFuncParams, as as ResServerTools, at as RpcMethodHandler, aj as RpcMethodsClientFuncParams, ak as RpcMethodsClientTool, al as RpcMethodsClientToolSchema, am as RpcMethodsServerFuncParams, an as RpcMethodsServerTool, ao as RpcMethodsServerToolSchema, a9 as SecondaryCache, s as Semaphore, l as SemaphoreIsReadyFuncType, p as SemaphoreOptions, q as SemaphoreTaskItem, a4 as ServerFuncItem, a3 as ServerFuncParams, a5 as ServerToolFuncSchema, O as TFunc, E as TaskAbortController, G as TaskAbortControllers, H as TaskPromise, v as ToolAsyncCancelableBit, u as ToolAsyncMultiTaskBit, w as ToolAsyncPriorityBit, X as ToolFunc, W as ToolFuncPackage, Y as ToolFuncSchema, aa as _lrucache, ab as createLRUCache, a8 as event, af as eventClient, ai as eventServer, $ as funcGetMeta, _ as funcWithMeta, ac as lrucache, K as makeToolFuncCancelable, a6 as registerCoreTools } from './index-DEUnmyUq.mjs';
6
6
  import * as _isdk_common_error from '@isdk/common-error';
7
7
  import { BaseError } from '@isdk/common-error';
8
8
  export { AbortError, AbortErrorCode, AlreadyExistsError, AlreadyExistsErrorCode, BaseError, CommonError, ErrorCode, InternalErrorCode, NotFoundError, NotFoundErrorCode, NotImplementationError, NotImplementedErrorCode, createError, throwError } from '@isdk/common-error';
@@ -2400,7 +2400,7 @@ declare class HttpServerToolTransport extends ServerToolTransport {
2400
2400
  port: number;
2401
2401
  host?: string;
2402
2402
  }): Promise<void>;
2403
- stop(): Promise<void>;
2403
+ stop(force?: boolean): Promise<void>;
2404
2404
  getRaw(): http.Server;
2405
2405
  }
2406
2406
 
package/dist/index.d.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  import * as custom_ability from 'custom-ability';
2
2
  export { createAbilityInjector } from 'custom-ability';
3
3
  export { toRegExp } from 'util-ex';
4
- import { A as AsyncTaskId, a as AIModelNameRules, I as IPubSubServerTransport, P as PubSubClientId, b as PubSubServerSession, c as IPubSubClientTransport, d as PubSubClientStream, e as IToolTransport, S as ServerTools, T as ToolTransport, C as ClientToolTransport, F as Funcs, f as ActionName } from './index-BCco-g_I.js';
5
- export { j as AIModelNameRule, i as AIModelNameRuleFn, h as ActionNames, x as AsyncFeatureBits, y as AsyncFeatures, V as BaseFunc, Q as BaseFuncItem, r as BinarySemaphore, m as BinarySemaphoreAcquireOptions, B as BinarySemaphoreOptions, n as BinarySemaphoreReleaseOptions, o as BinarySemaphoreReleaserFunc, J as CancelableAbility, z as CancelableAbilityOptions, a1 as ClientFuncItem, a2 as ClientToolFuncSchema, a0 as ClientTools, D as DefaultAsyncSemaphoreCapacity, ae as EventClient, ad as EventClientFuncParams, ah as EventServer, ag as EventServerFuncParams, a7 as EventToolFunc, U as FuncItem, Z as FuncMetaSymbol, M as FuncParam, L as FuncParamType, N as FuncParams, ao as IClientToolTransport, g as PASSING_SCORE, aq as PubSubClient, ap as PubSubCtx, t as RateLimit, k as RemoteFuncItem, R as RemoteToolFuncSchema, aj as ResClientFuncParams, ak as ResClientTools, al as ResServerFuncParams, am as ResServerTools, an as RpcMethodHandler, a9 as SecondaryCache, s as Semaphore, l as SemaphoreIsReadyFuncType, p as SemaphoreOptions, q as SemaphoreTaskItem, a4 as ServerFuncItem, a3 as ServerFuncParams, a5 as ServerToolFuncSchema, O as TFunc, E as TaskAbortController, G as TaskAbortControllers, H as TaskPromise, v as ToolAsyncCancelableBit, u as ToolAsyncMultiTaskBit, w as ToolAsyncPriorityBit, X as ToolFunc, W as ToolFuncPackage, Y as ToolFuncSchema, aa as _lrucache, ab as createLRUCache, a8 as event, af as eventClient, ai as eventServer, $ as funcGetMeta, _ as funcWithMeta, ac as lrucache, K as makeToolFuncCancelable, a6 as registerCoreTools } from './index-BCco-g_I.js';
4
+ import { A as AsyncTaskId, a as AIModelNameRules, I as IPubSubServerTransport, P as PubSubClientId, b as PubSubServerSession, c as IPubSubClientTransport, d as PubSubClientStream, e as IToolTransport, S as ServerTools, T as ToolTransport, C as ClientToolTransport, F as Funcs, f as ActionName } from './index-DEUnmyUq.js';
5
+ export { j as AIModelNameRule, i as AIModelNameRuleFn, h as ActionNames, x as AsyncFeatureBits, y as AsyncFeatures, V as BaseFunc, Q as BaseFuncItem, r as BinarySemaphore, m as BinarySemaphoreAcquireOptions, B as BinarySemaphoreOptions, n as BinarySemaphoreReleaseOptions, o as BinarySemaphoreReleaserFunc, J as CancelableAbility, z as CancelableAbilityOptions, a1 as ClientFuncItem, a2 as ClientToolFuncSchema, a0 as ClientTools, D as DefaultAsyncSemaphoreCapacity, ae as EventClient, ad as EventClientFuncParams, ah as EventServer, ag as EventServerFuncParams, a7 as EventToolFunc, U as FuncItem, Z as FuncMetaSymbol, M as FuncParam, L as FuncParamType, N as FuncParams, au as IClientToolTransport, g as PASSING_SCORE, aw as PubSubClient, av as PubSubCtx, t as RateLimit, k as RemoteFuncItem, R as RemoteToolFuncSchema, ap as ResClientFuncParams, aq as ResClientTools, ar as ResServerFuncParams, as as ResServerTools, at as RpcMethodHandler, aj as RpcMethodsClientFuncParams, ak as RpcMethodsClientTool, al as RpcMethodsClientToolSchema, am as RpcMethodsServerFuncParams, an as RpcMethodsServerTool, ao as RpcMethodsServerToolSchema, a9 as SecondaryCache, s as Semaphore, l as SemaphoreIsReadyFuncType, p as SemaphoreOptions, q as SemaphoreTaskItem, a4 as ServerFuncItem, a3 as ServerFuncParams, a5 as ServerToolFuncSchema, O as TFunc, E as TaskAbortController, G as TaskAbortControllers, H as TaskPromise, v as ToolAsyncCancelableBit, u as ToolAsyncMultiTaskBit, w as ToolAsyncPriorityBit, X as ToolFunc, W as ToolFuncPackage, Y as ToolFuncSchema, aa as _lrucache, ab as createLRUCache, a8 as event, af as eventClient, ai as eventServer, $ as funcGetMeta, _ as funcWithMeta, ac as lrucache, K as makeToolFuncCancelable, a6 as registerCoreTools } from './index-DEUnmyUq.js';
6
6
  import * as _isdk_common_error from '@isdk/common-error';
7
7
  import { BaseError } from '@isdk/common-error';
8
8
  export { AbortError, AbortErrorCode, AlreadyExistsError, AlreadyExistsErrorCode, BaseError, CommonError, ErrorCode, InternalErrorCode, NotFoundError, NotFoundErrorCode, NotImplementationError, NotImplementedErrorCode, createError, throwError } from '@isdk/common-error';
@@ -2400,7 +2400,7 @@ declare class HttpServerToolTransport extends ServerToolTransport {
2400
2400
  port: number;
2401
2401
  host?: string;
2402
2402
  }): Promise<void>;
2403
- stop(): Promise<void>;
2403
+ stop(force?: boolean): Promise<void>;
2404
2404
  getRaw(): http.Server;
2405
2405
  }
2406
2406