@isdk/ai-tool 0.5.8 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (497) hide show
  1. package/README.cn.md +103 -237
  2. package/README.md +101 -186
  3. package/dist/chunk-LNTIQQNN.mjs +1 -0
  4. package/dist/chunk-VIG2GB47.mjs +1 -1
  5. package/dist/funcs.d.mts +1 -1
  6. package/dist/funcs.d.ts +1 -1
  7. package/dist/funcs.js +1 -1
  8. package/dist/funcs.mjs +1 -1
  9. package/dist/index-BCco-g_I.d.mts +1781 -0
  10. package/dist/index-BCco-g_I.d.ts +1781 -0
  11. package/dist/index.d.mts +1083 -650
  12. package/dist/index.d.ts +1083 -650
  13. package/dist/index.js +1 -1
  14. package/dist/index.mjs +1 -1
  15. package/dist/test/util.js +1 -1
  16. package/docs/api/README.md +165 -0
  17. package/docs/{_media → api/_media}/CONTRIBUTING.md +3 -3
  18. package/docs/api/_media/pubsub.md +326 -0
  19. package/docs/api/_media/server_client_tools.md +88 -0
  20. package/docs/api/_media/toolFunc.md +183 -0
  21. package/docs/api/_media/transport.md +137 -0
  22. package/docs/{classes → api/classes}/AbortError.md +139 -54
  23. package/docs/api/classes/AlreadyExistsError.md +431 -0
  24. package/docs/api/classes/BaseError.md +440 -0
  25. package/docs/{classes → api/classes}/BinarySemaphore.md +25 -25
  26. package/docs/{classes → api/classes}/CancelableAbility.md +25 -25
  27. package/docs/api/classes/ClientToolTransport.md +310 -0
  28. package/docs/{classes → api/classes}/ClientTools.md +642 -180
  29. package/docs/{classes → api/classes}/CommonError.md +139 -54
  30. package/docs/api/classes/ConfigFile.md +218 -0
  31. package/docs/{classes → api/classes}/EnvPromptTemplate.md +308 -65
  32. package/docs/{classes → api/classes}/EventClient.md +725 -232
  33. package/docs/{classes → api/classes}/EventEmitter.md +12 -12
  34. package/docs/{classes → api/classes}/EventServer.md +658 -205
  35. package/docs/{classes → api/classes}/EventToolFunc.md +561 -109
  36. package/docs/{classes → api/classes}/FStringPromptTemplate.md +309 -66
  37. package/docs/{classes → api/classes}/FewShotPromptTemplate.md +290 -63
  38. package/docs/{classes → api/classes}/GolangPromptTemplate.md +308 -65
  39. package/docs/api/classes/HttpClientToolTransport.md +324 -0
  40. package/docs/api/classes/HttpServerToolTransport.md +324 -0
  41. package/docs/{classes → api/classes}/IntSet.md +12 -12
  42. package/docs/{classes → api/classes}/LRUCache.md +26 -26
  43. package/docs/api/classes/NotFoundError.md +431 -0
  44. package/docs/api/classes/NotImplementationError.md +431 -0
  45. package/docs/{classes → api/classes}/PromptExampleSelector.md +9 -9
  46. package/docs/{classes → api/classes}/PromptTemplate.md +303 -63
  47. package/docs/api/classes/ReadableStreamError.md +451 -0
  48. package/docs/api/classes/ResClientTools.md +2878 -0
  49. package/docs/api/classes/ResServerTools.md +2856 -0
  50. package/docs/api/classes/SSEChannel.md +272 -0
  51. package/docs/{classes → api/classes}/Semaphore.md +26 -26
  52. package/docs/api/classes/ServerToolTransport.md +323 -0
  53. package/docs/{classes → api/classes}/ServerTools.md +579 -120
  54. package/docs/{classes → api/classes}/SignalGate.md +9 -9
  55. package/docs/api/classes/SseClientPubSubTransport.md +92 -0
  56. package/docs/api/classes/SseServerPubSubTransport.md +234 -0
  57. package/docs/{classes → api/classes}/TaskAbortController.md +9 -9
  58. package/docs/api/classes/ToolFunc.md +2665 -0
  59. package/docs/api/classes/ToolTransport.md +143 -0
  60. package/docs/api/classes/YamlTypeBaseObject.md +31 -0
  61. package/docs/api/enumerations/AsyncFeatureBits.md +33 -0
  62. package/docs/api/enumerations/AsyncFeatures.md +33 -0
  63. package/docs/api/enumerations/ErrorCode.md +177 -0
  64. package/docs/api/enumerations/HashAlgorithm.md +97 -0
  65. package/docs/{functions → api/functions}/AIArgProcessor.md +1 -1
  66. package/docs/{functions → api/functions}/AIStream.md +1 -1
  67. package/docs/{functions → api/functions}/ChoiceArgProcessor.md +1 -1
  68. package/docs/api/functions/DefaultDateFormat.md +21 -0
  69. package/docs/{functions → api/functions}/ObjectArgsToArgsInfo.md +1 -1
  70. package/docs/{functions → api/functions}/RateLimit.md +1 -1
  71. package/docs/{functions → api/functions}/TemplateArgProcessor.md +1 -1
  72. package/docs/api/functions/addDate.md +71 -0
  73. package/docs/{functions → api/functions}/assignDirs.md +1 -1
  74. package/docs/{functions → api/functions}/backendEventable.md +1 -1
  75. package/docs/{functions → api/functions}/beforeShutdown.md +1 -1
  76. package/docs/api/functions/calcPerplexity.md +60 -0
  77. package/docs/api/functions/calcPerplexitySimple.md +42 -0
  78. package/docs/api/functions/canonicalize.md +33 -0
  79. package/docs/{functions → api/functions}/completeSentences.md +1 -1
  80. package/docs/{functions → api/functions}/concatText.md +1 -1
  81. package/docs/{functions → api/functions}/countLLMTokens.md +1 -1
  82. package/docs/{functions → api/functions}/countRegexMatches.md +1 -1
  83. package/docs/{functions → api/functions}/createAbilityInjector.md +4 -4
  84. package/docs/{functions → api/functions}/createCallbacksTransformer.md +1 -1
  85. package/docs/{functions → api/functions}/createEmptyReadableStream.md +1 -1
  86. package/docs/{functions → api/functions}/createEndWithRepetitionDetector.md +1 -1
  87. package/docs/{functions → api/functions}/createError.md +1 -1
  88. package/docs/{functions → api/functions}/createEventStreamTransformer.md +1 -1
  89. package/docs/{functions → api/functions}/createHfValueFunc.md +1 -1
  90. package/docs/{functions → api/functions}/createLRUCache.md +1 -1
  91. package/docs/{functions → api/functions}/createYamlObjectTag.md +1 -1
  92. package/docs/{functions → api/functions}/dateToText.md +1 -1
  93. package/docs/{functions → api/functions}/decodeCharset.md +1 -1
  94. package/docs/api/functions/defaultsWithConcat.md +74 -0
  95. package/docs/{functions → api/functions}/detectCharset.md +1 -1
  96. package/docs/{functions → api/functions}/encodeLLMTokens.md +1 -1
  97. package/docs/{functions → api/functions}/ensureQuoted.md +1 -1
  98. package/docs/{functions → api/functions}/eventable.md +1 -1
  99. package/docs/api/functions/expandConfig.md +25 -0
  100. package/docs/{functions → api/functions}/expandEnv.md +4 -4
  101. package/docs/{functions → api/functions}/expandObjEnv.md +4 -4
  102. package/docs/{functions → api/functions}/expandPath.md +1 -1
  103. package/docs/api/functions/expandPathInObject.md +29 -0
  104. package/docs/api/functions/expandPaths.md +25 -0
  105. package/docs/{functions → api/functions}/extNameLevel.md +1 -1
  106. package/docs/{functions → api/functions}/fileIsExists.md +1 -1
  107. package/docs/{functions → api/functions}/filterValidFnScope.md +1 -1
  108. package/docs/{functions → api/functions}/findIndexNonEmptyFrom.md +1 -1
  109. package/docs/{functions → api/functions}/findPort.md +1 -1
  110. package/docs/{functions → api/functions}/formatISO.md +1 -1
  111. package/docs/{functions → api/functions}/formatTextWithSpace.md +1 -1
  112. package/docs/api/functions/funcGetMeta.md +27 -0
  113. package/docs/api/functions/funcWithMeta.md +41 -0
  114. package/docs/api/functions/genUrlParamsStr.md +27 -0
  115. package/docs/{functions → api/functions}/getAllEnumKeys.md +1 -1
  116. package/docs/{functions → api/functions}/getConfigFileNames.md +1 -1
  117. package/docs/{functions → api/functions}/getConfigs.md +1 -1
  118. package/docs/{functions → api/functions}/getEnvVairables.md +1 -1
  119. package/docs/{functions → api/functions}/getFileMetaInfo.md +1 -1
  120. package/docs/{functions → api/functions}/getHashAlgoBySize.md +1 -1
  121. package/docs/{functions → api/functions}/getKeysPath.md +1 -1
  122. package/docs/{functions → api/functions}/getLLMTokenizer.md +1 -1
  123. package/docs/{functions → api/functions}/getMultiLevelExtname.md +4 -4
  124. package/docs/{functions → api/functions}/getPackageDir.md +1 -1
  125. package/docs/{functions → api/functions}/getRealFilepath.md +1 -1
  126. package/docs/{functions → api/functions}/getResponseErrorReadableStream.md +1 -1
  127. package/docs/{functions → api/functions}/getXDGConfigs.md +1 -1
  128. package/docs/{functions → api/functions}/hasDirectoryIn.md +1 -1
  129. package/docs/{functions → api/functions}/hash.md +1 -1
  130. package/docs/{functions → api/functions}/hashFile.md +1 -1
  131. package/docs/api/functions/hashObject.md +25 -0
  132. package/docs/{functions → api/functions}/hashStream.md +1 -1
  133. package/docs/api/functions/initShutdown.md +15 -0
  134. package/docs/{functions → api/functions}/isLangUsingSpaces.md +1 -1
  135. package/docs/{functions → api/functions}/isListItemString.md +1 -1
  136. package/docs/{functions → api/functions}/isModelNameMatched.md +1 -1
  137. package/docs/{functions → api/functions}/isPunctuationChar.md +1 -1
  138. package/docs/{functions → api/functions}/isQuoted.md +1 -1
  139. package/docs/{functions → api/functions}/isRegExp.md +1 -1
  140. package/docs/{functions → api/functions}/isSameString.md +1 -1
  141. package/docs/{functions → api/functions}/isSectionString.md +1 -1
  142. package/docs/{functions → api/functions}/isSentenceEnding.md +1 -1
  143. package/docs/{functions → api/functions}/isSepLineString.md +1 -1
  144. package/docs/{functions → api/functions}/isStrWrapped.md +1 -1
  145. package/docs/{functions → api/functions}/isSubdirectory.md +2 -2
  146. package/docs/{functions → api/functions}/isTitleString.md +1 -1
  147. package/docs/{functions → api/functions}/isValidFilename.md +1 -1
  148. package/docs/{functions → api/functions}/isValidFilepath.md +1 -1
  149. package/docs/{functions → api/functions}/isWebStream.md +1 -1
  150. package/docs/api/functions/joinSplitWords.md +46 -0
  151. package/docs/{functions → api/functions}/jsonFilterToWhere.md +1 -1
  152. package/docs/{functions → api/functions}/jsonToMarkdownStr.md +9 -1
  153. package/docs/{functions → api/functions}/loadAIConfig.md +1 -1
  154. package/docs/{functions → api/functions}/loadConfig.md +1 -1
  155. package/docs/{functions → api/functions}/loadConfigFile.md +1 -1
  156. package/docs/{functions → api/functions}/loadFileFromPaths.md +1 -1
  157. package/docs/{functions → api/functions}/loadTextFromPaths.md +1 -1
  158. package/docs/{functions → api/functions}/lrucache.md +1 -1
  159. package/docs/{functions → api/functions}/makeToolFuncCancelable.md +1 -1
  160. package/docs/{functions → api/functions}/matchUrlProtocol.md +1 -1
  161. package/docs/{functions → api/functions}/memoize.md +1 -1
  162. package/docs/api/functions/mergeArray.md +57 -0
  163. package/docs/{functions → api/functions}/messagesToText.md +1 -1
  164. package/docs/api/functions/normalizePath.md +21 -0
  165. package/docs/{functions → api/functions}/paramsSizeToScaleStr.md +1 -1
  166. package/docs/{functions → api/functions}/parseCommand.md +1 -1
  167. package/docs/{functions → api/functions}/parseDateFormat.md +1 -1
  168. package/docs/{functions → api/functions}/parseISO.md +1 -1
  169. package/docs/{functions → api/functions}/parseJsJson.md +1 -1
  170. package/docs/{functions → api/functions}/parseJsJsonSimpleSync.md +1 -1
  171. package/docs/{functions → api/functions}/parseObjectArgInfo.md +1 -1
  172. package/docs/{functions → api/functions}/parseObjectArgumentInfos.md +1 -1
  173. package/docs/{functions → api/functions}/parseObjectArguments.md +1 -1
  174. package/docs/{functions → api/functions}/parseObjectArgumentsAsArgInfos.md +1 -1
  175. package/docs/api/functions/parseYaml.md +45 -0
  176. package/docs/api/functions/pruneSubdirectories.md +35 -0
  177. package/docs/api/functions/pruneSubdirectoriesInPlace.md +38 -0
  178. package/docs/{functions → api/functions}/quoteStr.md +1 -1
  179. package/docs/{functions → api/functions}/readFilenamesRecursiveSync.md +7 -1
  180. package/docs/{functions → api/functions}/readTextFileChunks.md +1 -1
  181. package/docs/{functions → api/functions}/readTextFileChunksEx.md +1 -1
  182. package/docs/{functions → api/functions}/readableFromAsyncIterable.md +1 -1
  183. package/docs/{functions → api/functions}/registerCoreTools.md +1 -1
  184. package/docs/api/functions/registerYamlTag.md +37 -0
  185. package/docs/{functions → api/functions}/removeMarkdownBold.md +1 -1
  186. package/docs/{functions → api/functions}/removeMarkdownBoldAndItalic.md +1 -1
  187. package/docs/{functions → api/functions}/removeMarkdownItalic.md +1 -1
  188. package/docs/{functions → api/functions}/replaceWithPlaceholder.md +1 -1
  189. package/docs/{functions → api/functions}/restoreFromPlacehoders.md +1 -1
  190. package/docs/{functions → api/functions}/sanitizeFilename.md +4 -4
  191. package/docs/{functions → api/functions}/sanitizeFilepath.md +4 -4
  192. package/docs/{functions → api/functions}/saveConfigFile.md +1 -1
  193. package/docs/{functions → api/functions}/scaleStrToParamsSize.md +1 -1
  194. package/docs/{functions → api/functions}/shutdown.md +1 -1
  195. package/docs/{functions → api/functions}/simplifyObjectArguments.md +1 -1
  196. package/docs/api/functions/sleep.md +36 -0
  197. package/docs/{functions → api/functions}/sortedValues.md +1 -1
  198. package/docs/{functions → api/functions}/splitChunks.md +1 -1
  199. package/docs/{functions → api/functions}/splitParagraph.md +1 -1
  200. package/docs/{functions → api/functions}/splitSentence.md +1 -1
  201. package/docs/api/functions/splitWords.md +42 -0
  202. package/docs/api/functions/stringifyYaml.md +45 -0
  203. package/docs/{functions → api/functions}/stripConsoleColor.md +1 -1
  204. package/docs/{functions → api/functions}/textToDate.md +1 -1
  205. package/docs/{functions → api/functions}/throwError.md +3 -3
  206. package/docs/{functions → api/functions}/toDate.md +1 -1
  207. package/docs/{functions → api/functions}/toDateTime.md +1 -1
  208. package/docs/{functions → api/functions}/toRegExp.md +1 -1
  209. package/docs/{functions → api/functions}/trimStartOfStreamHelper.md +1 -1
  210. package/docs/{functions → api/functions}/truncTo.md +1 -1
  211. package/docs/{functions → api/functions}/truncateByToken.md +1 -1
  212. package/docs/{functions → api/functions}/truncateToTokenLimit.md +1 -1
  213. package/docs/{functions → api/functions}/truncateToTokenLimitEx.md +1 -1
  214. package/docs/{functions → api/functions}/uuid.md +1 -1
  215. package/docs/{functions → api/functions}/uuidParse.md +1 -1
  216. package/docs/{functions → api/functions}/uuidStringify.md +1 -1
  217. package/docs/{functions → api/functions}/uuidValidate.md +1 -1
  218. package/docs/{functions → api/functions}/uuidVersion.md +1 -1
  219. package/docs/{functions → api/functions}/uuidv1.md +9 -5
  220. package/docs/{functions → api/functions}/uuidv4.md +9 -5
  221. package/docs/{functions → api/functions}/uuidv5.md +9 -5
  222. package/docs/api/functions/wait.md +45 -0
  223. package/docs/{functions → api/functions}/wrapEventEmitter.md +1 -1
  224. package/docs/{functions → api/functions}/xxhash.md +1 -1
  225. package/docs/{functions → api/functions}/xxhash32.md +1 -1
  226. package/docs/{functions → api/functions}/xxhash64.md +1 -1
  227. package/docs/{functions → api/functions}/xxhashAsStr.md +1 -1
  228. package/docs/api/functions/yieldExec.md +27 -0
  229. package/docs/{globals.md → api/globals.md} +44 -24
  230. package/docs/api/interfaces/AIChatAssistantMessageParam.md +129 -0
  231. package/docs/api/interfaces/AIChatContentPartImage.md +29 -0
  232. package/docs/api/interfaces/AIChatContentPartText.md +25 -0
  233. package/docs/api/interfaces/AIChatMessageParamBase.md +68 -0
  234. package/docs/api/interfaces/AIChatMessageToolCall.md +41 -0
  235. package/docs/{interfaces → api/interfaces}/AIChatSystemMessageParam.md +9 -9
  236. package/docs/api/interfaces/AIChatToolChoiceFuncObject.md +37 -0
  237. package/docs/api/interfaces/AIChatToolChoiceObject.md +25 -0
  238. package/docs/api/interfaces/AIChatToolFunc.md +41 -0
  239. package/docs/api/interfaces/AIChatToolFuncParam.md +37 -0
  240. package/docs/api/interfaces/AIChatToolMessageParam.md +113 -0
  241. package/docs/api/interfaces/AIChatToolParam.md +25 -0
  242. package/docs/api/interfaces/AIChatToolTypeObject.md +17 -0
  243. package/docs/api/interfaces/AIChatUserMessageParam.md +137 -0
  244. package/docs/api/interfaces/AIChoiceConfig.md +65 -0
  245. package/docs/api/interfaces/AIResult.md +65 -0
  246. package/docs/{interfaces → api/interfaces}/AIStreamParser.md +2 -2
  247. package/docs/api/interfaces/AIStreamParserOptions.md +21 -0
  248. package/docs/api/interfaces/BaseFunc.md +299 -0
  249. package/docs/api/interfaces/BaseFuncItem.md +221 -0
  250. package/docs/api/interfaces/BinarySemaphoreAcquireOptions.md +25 -0
  251. package/docs/api/interfaces/BinarySemaphoreOptions.md +57 -0
  252. package/docs/api/interfaces/BinarySemaphoreReleaseOptions.md +25 -0
  253. package/docs/api/interfaces/BinarySemaphoreReleaserFunc.md +37 -0
  254. package/docs/api/interfaces/CancelableAbilityOptions.md +113 -0
  255. package/docs/api/interfaces/ClientFuncItem.md +326 -0
  256. package/docs/api/interfaces/EventClientFuncParams.md +51 -0
  257. package/docs/api/interfaces/EventServerFuncParams.md +73 -0
  258. package/docs/api/interfaces/FewShotPromptTemplateOptions.md +159 -0
  259. package/docs/api/interfaces/FuncItem.md +281 -0
  260. package/docs/api/interfaces/FuncParam.md +51 -0
  261. package/docs/api/interfaces/FuncParams.md +28 -0
  262. package/docs/api/interfaces/Funcs.md +15 -0
  263. package/docs/api/interfaces/HashAlgoParams.md +33 -0
  264. package/docs/api/interfaces/IClientToolTransport.md +155 -0
  265. package/docs/api/interfaces/IFileMetaInfo.md +65 -0
  266. package/docs/api/interfaces/IPubSubClientTransport.md +70 -0
  267. package/docs/api/interfaces/IPubSubServerTransport.md +241 -0
  268. package/docs/{interfaces → api/interfaces}/IReadTextFileChunksOptions.md +12 -12
  269. package/docs/api/interfaces/IServerToolTransport.md +159 -0
  270. package/docs/api/interfaces/IToolTransport.md +73 -0
  271. package/docs/api/interfaces/ITruncateToTokenLimitOptions.md +99 -0
  272. package/docs/api/interfaces/JsonFilter.md +13 -0
  273. package/docs/api/interfaces/ParseObjectArgumentOptions.md +89 -0
  274. package/docs/api/interfaces/ProbabilityItem.md +41 -0
  275. package/docs/api/interfaces/PromptExampleSelectorOptions.md +34 -0
  276. package/docs/api/interfaces/PromptTemplateOptions.md +73 -0
  277. package/docs/api/interfaces/PubSubClient.md +27 -0
  278. package/docs/api/interfaces/PubSubClientStream.md +196 -0
  279. package/docs/api/interfaces/PubSubServerSession.md +103 -0
  280. package/docs/api/interfaces/RemoteFuncItem.md +316 -0
  281. package/docs/api/interfaces/ReplacePlacehoderOptions.md +41 -0
  282. package/docs/api/interfaces/ResClientFuncParams.md +37 -0
  283. package/docs/api/interfaces/ResServerFuncParams.md +73 -0
  284. package/docs/api/interfaces/SanitizeFilenameOptions.md +25 -0
  285. package/docs/api/interfaces/SectionStringOptions.md +25 -0
  286. package/docs/api/interfaces/SemaphoreOptions.md +89 -0
  287. package/docs/api/interfaces/SemaphoreTaskItem.md +73 -0
  288. package/docs/api/interfaces/ServerFuncItem.md +339 -0
  289. package/docs/api/interfaces/ServerFuncParams.md +41 -0
  290. package/docs/api/interfaces/SplitSentenceOptions.md +41 -0
  291. package/docs/{interfaces → api/interfaces}/StreamCallbacksAndOptions.md +5 -5
  292. package/docs/{interfaces → api/interfaces}/TaskAbortControllers.md +1 -1
  293. package/docs/{interfaces → api/interfaces}/TaskPromise.md +6 -6
  294. package/docs/api/interfaces/ToolFuncPackage.md +57 -0
  295. package/docs/{namespaces → api/namespaces}/EventStates/variables/ABORT.md +1 -1
  296. package/docs/{namespaces → api/namespaces}/EventStates/variables/CONTINUE.md +1 -1
  297. package/docs/{namespaces → api/namespaces}/EventStates/variables/DONE.md +1 -1
  298. package/docs/{namespaces → api/namespaces}/EventStates/variables/STOPPED.md +1 -1
  299. package/docs/{namespaces → api/namespaces}/uuidv5/variables/DNS.md +1 -1
  300. package/docs/{namespaces → api/namespaces}/uuidv5/variables/URL.md +1 -1
  301. package/docs/{type-aliases → api/type-aliases}/AIChatContentPart.md +1 -1
  302. package/docs/{type-aliases → api/type-aliases}/AIChatMessageParam.md +1 -1
  303. package/docs/{type-aliases → api/type-aliases}/AIChatRole.md +1 -1
  304. package/docs/{type-aliases → api/type-aliases}/AIChatToolChoiceParam.md +1 -1
  305. package/docs/{type-aliases → api/type-aliases}/AIMessageType.md +1 -1
  306. package/docs/api/type-aliases/AIModelNameRule.md +14 -0
  307. package/docs/api/type-aliases/AIModelNameRuleFn.md +28 -0
  308. package/docs/api/type-aliases/AIModelNameRules.md +13 -0
  309. package/docs/{type-aliases → api/type-aliases}/AITextGenerationFinishReason.md +1 -1
  310. package/docs/api/type-aliases/ActionName.md +13 -0
  311. package/docs/api/type-aliases/ArrayMergeWay.md +11 -0
  312. package/docs/api/type-aliases/AsyncTaskId.md +11 -0
  313. package/docs/{type-aliases → api/type-aliases}/BeforeShutdownListener.md +1 -1
  314. package/docs/{type-aliases → api/type-aliases}/EventErrorListenerFn.md +1 -1
  315. package/docs/{type-aliases → api/type-aliases}/EventListenerFn.md +1 -1
  316. package/docs/api/type-aliases/FuncParamType.md +13 -0
  317. package/docs/{type-aliases → api/type-aliases}/PromptExamples.md +1 -1
  318. package/docs/api/type-aliases/PubSubClientId.md +14 -0
  319. package/docs/api/type-aliases/PubSubCtx.md +37 -0
  320. package/docs/api/type-aliases/RpcMethodHandler.md +34 -0
  321. package/docs/{type-aliases → api/type-aliases}/SemaphoreIsReadyFuncType.md +1 -1
  322. package/docs/api/type-aliases/TFunc.md +33 -0
  323. package/docs/{variables → api/variables}/AIChatRoles.md +1 -1
  324. package/docs/{variables → api/variables}/AIMessageTypes.md +1 -1
  325. package/docs/{variables → api/variables}/AITextGenerationFinishReasons.md +1 -1
  326. package/docs/{variables → api/variables}/AbortErrorCode.md +1 -1
  327. package/docs/api/variables/ActionNames.md +13 -0
  328. package/docs/{variables → api/variables}/AlreadyExistsErrorCode.md +1 -1
  329. package/docs/api/variables/ArrayMergeWay.md +25 -0
  330. package/docs/api/variables/ArrayMergeWaySymbol.md +11 -0
  331. package/docs/api/variables/ClientToolFuncSchema.md +83 -0
  332. package/docs/{variables → api/variables}/DEFAULT_CONFIG_NAME.md +1 -1
  333. package/docs/{variables → api/variables}/DefaultAsyncSemaphoreCapacity.md +1 -1
  334. package/docs/api/variables/EventBusName.md +11 -0
  335. package/docs/api/variables/EventName.md +11 -0
  336. package/docs/{variables → api/variables}/FilenameReservedRegex.md +1 -1
  337. package/docs/api/variables/FuncMetaSymbol.md +15 -0
  338. package/docs/{variables → api/variables}/InternalErrorCode.md +1 -1
  339. package/docs/{variables → api/variables}/LLM_TOKENIZER_NAMES.md +1 -1
  340. package/docs/{variables → api/variables}/LLM_TOKENIZER_NAMES_MAP.md +1 -1
  341. package/docs/{variables → api/variables}/NotFoundErrorCode.md +1 -1
  342. package/docs/{variables → api/variables}/NotImplementedErrorCode.md +1 -1
  343. package/docs/api/variables/PASSING_SCORE.md +13 -0
  344. package/docs/api/variables/RStreamErrCode.md +11 -0
  345. package/docs/api/variables/RemoteToolFuncSchema.md +84 -0
  346. package/docs/api/variables/ResponseRStreamErrCode.md +11 -0
  347. package/docs/{variables → api/variables}/SHUTDOWN_SIGNALS.md +1 -1
  348. package/docs/{variables → api/variables}/SSEChannelAlreadyClosedErrCode.md +1 -1
  349. package/docs/api/variables/SecondaryCache.md +11 -0
  350. package/docs/api/variables/ServerToolFuncSchema.md +83 -0
  351. package/docs/api/variables/StrangeHumanName.md +11 -0
  352. package/docs/api/variables/ToolAsyncCancelableBit.md +11 -0
  353. package/docs/api/variables/ToolAsyncMultiTaskBit.md +11 -0
  354. package/docs/api/variables/ToolAsyncPriorityBit.md +11 -0
  355. package/docs/{variables → api/variables}/ToolFuncSchema.md +14 -1
  356. package/docs/{variables → api/variables}/WindowsReservedNameRegex.md +1 -1
  357. package/docs/api/variables/base32768.md +11 -0
  358. package/docs/api/variables/defaultTemplateFormat.md +11 -0
  359. package/docs/api/variables/event.md +11 -0
  360. package/docs/api/variables/eventClient.md +11 -0
  361. package/docs/api/variables/eventServer.md +11 -0
  362. package/docs/api/variables/lrucache.md +11 -0
  363. package/docs/{variables → api/variables}/mimeType.md +1 -1
  364. package/docs/{variables → api/variables}/uuidNIL.md +1 -1
  365. package/docs/pubsub.md +326 -0
  366. package/docs/server_client_tools.md +88 -0
  367. package/docs/toolFunc.md +183 -0
  368. package/docs/transport.md +137 -0
  369. package/package.json +38 -38
  370. package/dist/chunk-YVFGQB4L.mjs +0 -1
  371. package/dist/index-BkwhCK1q.d.mts +0 -899
  372. package/dist/index-BkwhCK1q.d.ts +0 -899
  373. package/docs/README.md +0 -250
  374. package/docs/classes/AlreadyExistsError.md +0 -346
  375. package/docs/classes/BaseError.md +0 -359
  376. package/docs/classes/ConfigFile.md +0 -353
  377. package/docs/classes/HFEnvironment.md +0 -184
  378. package/docs/classes/HFInterpreter.md +0 -77
  379. package/docs/classes/HFTemplate.md +0 -67
  380. package/docs/classes/HfPromptTemplate.md +0 -1158
  381. package/docs/classes/NotFoundError.md +0 -346
  382. package/docs/classes/NotImplementationError.md +0 -346
  383. package/docs/classes/ReadableStreamError.md +0 -366
  384. package/docs/classes/ResClientTools.md +0 -2451
  385. package/docs/classes/ResServerTools.md +0 -2427
  386. package/docs/classes/SSEChannel.md +0 -270
  387. package/docs/classes/ToolFunc.md +0 -2201
  388. package/docs/classes/YamlTypeBaseObject.md +0 -31
  389. package/docs/enumerations/AsyncFeatureBits.md +0 -33
  390. package/docs/enumerations/AsyncFeatures.md +0 -33
  391. package/docs/enumerations/ErrorCode.md +0 -177
  392. package/docs/enumerations/HashAlgorithm.md +0 -97
  393. package/docs/functions/canonicalize.md +0 -21
  394. package/docs/functions/expandConfig.md +0 -25
  395. package/docs/functions/filenameReservedRegex.md +0 -20
  396. package/docs/functions/hfParse.md +0 -24
  397. package/docs/functions/hfTokenize.md +0 -27
  398. package/docs/functions/initShutdown.md +0 -15
  399. package/docs/functions/interpolateEnv.md +0 -29
  400. package/docs/functions/interpolateFString.md +0 -29
  401. package/docs/functions/interpolateGolangTemplate.md +0 -35
  402. package/docs/functions/parseFString.md +0 -26
  403. package/docs/functions/parseYaml.md +0 -25
  404. package/docs/functions/reControlCharsRegex.md +0 -19
  405. package/docs/functions/registerYamlTag.md +0 -21
  406. package/docs/functions/stringifyYaml.md +0 -25
  407. package/docs/functions/wait.md +0 -21
  408. package/docs/interfaces/AIChatAssistantMessageParam.md +0 -129
  409. package/docs/interfaces/AIChatContentPartImage.md +0 -29
  410. package/docs/interfaces/AIChatContentPartText.md +0 -25
  411. package/docs/interfaces/AIChatMessageParamBase.md +0 -68
  412. package/docs/interfaces/AIChatMessageToolCall.md +0 -41
  413. package/docs/interfaces/AIChatToolChoiceFuncObject.md +0 -37
  414. package/docs/interfaces/AIChatToolChoiceObject.md +0 -25
  415. package/docs/interfaces/AIChatToolFunc.md +0 -41
  416. package/docs/interfaces/AIChatToolFuncParam.md +0 -37
  417. package/docs/interfaces/AIChatToolMessageParam.md +0 -113
  418. package/docs/interfaces/AIChatToolParam.md +0 -25
  419. package/docs/interfaces/AIChatToolTypeObject.md +0 -17
  420. package/docs/interfaces/AIChatUserMessageParam.md +0 -137
  421. package/docs/interfaces/AIChoiceConfig.md +0 -65
  422. package/docs/interfaces/AIResult.md +0 -65
  423. package/docs/interfaces/AIStreamParserOptions.md +0 -21
  424. package/docs/interfaces/BaseFunc.md +0 -157
  425. package/docs/interfaces/BaseFuncItem.md +0 -101
  426. package/docs/interfaces/BinarySemaphoreAcquireOptions.md +0 -25
  427. package/docs/interfaces/BinarySemaphoreOptions.md +0 -57
  428. package/docs/interfaces/BinarySemaphoreReleaseOptions.md +0 -25
  429. package/docs/interfaces/BinarySemaphoreReleaserFunc.md +0 -37
  430. package/docs/interfaces/CancelableAbilityOptions.md +0 -113
  431. package/docs/interfaces/ClientFuncItem.md +0 -175
  432. package/docs/interfaces/DotenvExpandOptions.md +0 -43
  433. package/docs/interfaces/DotenvExpandOutput.md +0 -25
  434. package/docs/interfaces/DotenvParseInput.md +0 -13
  435. package/docs/interfaces/DotenvParseOutput.md +0 -13
  436. package/docs/interfaces/DotenvPopulateInput.md +0 -13
  437. package/docs/interfaces/EventClientFuncParams.md +0 -51
  438. package/docs/interfaces/EventServerFuncParams.md +0 -67
  439. package/docs/interfaces/FewShotPromptTemplateOptions.md +0 -147
  440. package/docs/interfaces/FuncItem.md +0 -143
  441. package/docs/interfaces/FuncParam.md +0 -61
  442. package/docs/interfaces/FuncParams.md +0 -13
  443. package/docs/interfaces/Funcs.md +0 -13
  444. package/docs/interfaces/HashAlgoParams.md +0 -33
  445. package/docs/interfaces/IFileMetaInfo.md +0 -65
  446. package/docs/interfaces/ITruncateToTokenLimitOptions.md +0 -99
  447. package/docs/interfaces/JsonFilter.md +0 -13
  448. package/docs/interfaces/ParseObjectArgumentOptions.md +0 -89
  449. package/docs/interfaces/PromptExampleSelectorOptions.md +0 -34
  450. package/docs/interfaces/PromptTemplateOptions.md +0 -65
  451. package/docs/interfaces/RemoteFuncItem.md +0 -164
  452. package/docs/interfaces/ReplacePlacehoderOptions.md +0 -41
  453. package/docs/interfaces/ResClientFuncParams.md +0 -37
  454. package/docs/interfaces/ResServerFuncParams.md +0 -69
  455. package/docs/interfaces/SanitizeFilenameOptions.md +0 -25
  456. package/docs/interfaces/SectionStringOptions.md +0 -25
  457. package/docs/interfaces/SemaphoreOptions.md +0 -89
  458. package/docs/interfaces/SemaphoreTaskItem.md +0 -73
  459. package/docs/interfaces/ServerFuncItem.md +0 -183
  460. package/docs/interfaces/ServerFuncParams.md +0 -35
  461. package/docs/interfaces/SplitSentenceOptions.md +0 -41
  462. package/docs/interfaces/ToolFuncPackage.md +0 -47
  463. package/docs/type-aliases/AIModelNameRule.md +0 -11
  464. package/docs/type-aliases/AIModelNameRuleFn.md +0 -21
  465. package/docs/type-aliases/AIModelNameRules.md +0 -11
  466. package/docs/type-aliases/ActionName.md +0 -11
  467. package/docs/type-aliases/AsyncTaskId.md +0 -11
  468. package/docs/type-aliases/FStringPromptTemplateNode.md +0 -14
  469. package/docs/type-aliases/FuncParamType.md +0 -11
  470. package/docs/type-aliases/PromptTemplateType.md +0 -11
  471. package/docs/type-aliases/PromptType.md +0 -11
  472. package/docs/type-aliases/TFunc.md +0 -25
  473. package/docs/variables/ActionNames.md +0 -11
  474. package/docs/variables/ClientToolFuncSchema.md +0 -101
  475. package/docs/variables/EventBusName.md +0 -11
  476. package/docs/variables/EventName.md +0 -11
  477. package/docs/variables/HFBuiltins.md +0 -122
  478. package/docs/variables/PASSING_SCORE.md +0 -11
  479. package/docs/variables/PromptTemplateTypes.md +0 -11
  480. package/docs/variables/PromptTypes.md +0 -14
  481. package/docs/variables/RStreamErrCode.md +0 -11
  482. package/docs/variables/RemoteToolFuncSchema.md +0 -101
  483. package/docs/variables/ResponseRStreamErrCode.md +0 -11
  484. package/docs/variables/SecondaryCache.md +0 -11
  485. package/docs/variables/ServerToolFuncSchema.md +0 -101
  486. package/docs/variables/ToolAsyncCancelableBit.md +0 -11
  487. package/docs/variables/ToolAsyncMultiTaskBit.md +0 -11
  488. package/docs/variables/ToolAsyncPriorityBit.md +0 -11
  489. package/docs/variables/base32768.md +0 -11
  490. package/docs/variables/defaultTemplateFormat.md +0 -11
  491. package/docs/variables/event.md +0 -11
  492. package/docs/variables/eventClient.md +0 -11
  493. package/docs/variables/eventServer.md +0 -11
  494. package/docs/variables/lrucache.md +0 -11
  495. /package/docs/{_media → api/_media}/LICENSE-MIT +0 -0
  496. /package/docs/{namespaces → api/namespaces}/EventStates/README.md +0 -0
  497. /package/docs/{namespaces → api/namespaces}/uuidv5/README.md +0 -0
@@ -0,0 +1,1781 @@
1
+ import { EventEmitter, Event } from 'events-ex';
2
+ import { AdvancePropertyManager } from 'property-manager';
3
+ import { AbilityOptions } from 'custom-ability';
4
+ import { CommonError } from '@isdk/common-error';
5
+ import { Cache, ICacheOptions } from 'secondary-cache';
6
+ import { IncomingMessage, ServerResponse } from 'http';
7
+
8
+ /**
9
+ * Represents the data type of a function parameter as a string (e.g., `'string'`, `'number'`).
10
+ */
11
+ type FuncParamType = string;
12
+ /**
13
+ * Describes a single function parameter, including its name, type, and description.
14
+ * @interface
15
+ */
16
+ interface FuncParam {
17
+ /**
18
+ * The name of the parameter.
19
+ * @type {string}
20
+ */
21
+ name?: string;
22
+ /**
23
+ * The data type of the parameter, represented as a string identifier (e.g., 'string', 'number').
24
+ * @type {FuncParamType}
25
+ */
26
+ type?: FuncParamType;
27
+ /**
28
+ * Indicates whether the parameter is required.
29
+ * @type {boolean}
30
+ */
31
+ required?: boolean;
32
+ /**
33
+ * A description of the parameter, explaining its purpose and usage.
34
+ * @type {string}
35
+ */
36
+ description?: string;
37
+ }
38
+ /**
39
+ * A map of function parameters, where each key is the parameter name.
40
+ * The value can be either a detailed `FuncParam` object or a simple type string.
41
+ *
42
+ * @example
43
+ * const params: FuncParams = {
44
+ * userId: 'string',
45
+ * profile: {
46
+ * type: 'object',
47
+ * description: 'User profile data'
48
+ * }
49
+ * };
50
+ */
51
+ interface FuncParams {
52
+ [name: string]: FuncParam | FuncParamType;
53
+ }
54
+ /**
55
+ * Defines the signature for a tool function's implementation.
56
+ *
57
+ * @param {ToolFunc} this - The `this` context is bound to the `ToolFunc` instance.
58
+ * @param {...any[]} params - Variadic arguments passed to the function.
59
+ * @returns {any} The result of the function's execution.
60
+ */
61
+ type TFunc = (this: ToolFunc, ...params: any[]) => any;
62
+ /**
63
+ * Base configuration for defining a tool function.
64
+ * @interface
65
+ */
66
+ interface BaseFuncItem {
67
+ /**
68
+ * The unique name of the function.
69
+ * @type {string}
70
+ */
71
+ name?: string;
72
+ /**
73
+ * Parameter definitions, which can be an object mapping names to definitions or an array for positional parameters.
74
+ * @type {FuncParams | FuncParam[]}
75
+ */
76
+ params?: FuncParams | FuncParam[];
77
+ /**
78
+ * The expected return type of the function, described as a string or a JSON schema object.
79
+ * @type {string | Record<string, any>}
80
+ */
81
+ result?: string | Record<string, any>;
82
+ /**
83
+ * The execution scope or context (`this`) for the function.
84
+ * @type {any}
85
+ */
86
+ scope?: any;
87
+ /**
88
+ * Tags for grouping or filtering functions.
89
+ * @type {string | string[]}
90
+ */
91
+ tags?: string | string[];
92
+ /**
93
+ * A lifecycle hook called once during the `ToolFunc` instance's initialization.
94
+ * It allows for initial setup, state configuration, or property modification on the instance
95
+ * before it is used or registered. The `this` context is the `ToolFunc` instance itself.
96
+ *
97
+ * @param {FuncItem} [options] - The configuration options for the function.
98
+ * @example
99
+ * const myFunc = new ToolFunc({
100
+ * name: 'myFunc',
101
+ * customState: 'initial',
102
+ * setup() {
103
+ * // `this` is the myFunc instance
104
+ * this.customState = 'configured';
105
+ * }
106
+ * });
107
+ * console.log(myFunc.customState); // Outputs: 'configured'
108
+ */
109
+ setup?: (this: ToolFunc, options?: FuncItem) => void;
110
+ /**
111
+ * If true, indicates that this function should be treated as a server-side API.
112
+ * @type {boolean}
113
+ */
114
+ isApi?: boolean;
115
+ /**
116
+ * If true, indicates that the function has the *capability* to stream its output.
117
+ * Whether a specific call is streamed is determined by a `stream` property in the runtime parameters.
118
+ * @type {boolean}
119
+ */
120
+ stream?: boolean;
121
+ /**
122
+ * Optional aliases for the function name.
123
+ * @type {string | string[]}
124
+ */
125
+ alias?: string | string[];
126
+ /**
127
+ * A bitmask representing asynchronous features supported by the function, built from `AsyncFeatureBits`.
128
+ * This allows the system to understand if a function supports capabilities like cancellation or multi-tasking.
129
+ * @see AsyncFeatureBits from `@src/utils/cancelable-ability.ts`
130
+ * @type {number}
131
+ * @example
132
+ * import { AsyncFeatures } from './utils';
133
+ * const func = new ToolFunc({
134
+ * name: 'cancellableTask',
135
+ * asyncFeatures: AsyncFeatures.Cancelable | AsyncFeatures.MultiTask,
136
+ * // ...
137
+ * });
138
+ */
139
+ asyncFeatures?: number;
140
+ /**
141
+ * A map of dependencies this function has on other tool functions.
142
+ * Declaring dependencies ensures that they are automatically registered when this function is registered.
143
+ * This is crucial for building modular functions that rely on each other without needing to manage registration order manually.
144
+ *
145
+ * @type {{ [name: string]: ToolFunc }}
146
+ * @example
147
+ * const helperFunc = new ToolFunc({ name: 'helper', func: () => 'world' });
148
+ * const mainFunc = new ToolFunc({
149
+ * name: 'main',
150
+ * depends: {
151
+ * helper: helperFunc,
152
+ * },
153
+ * func() {
154
+ * // We can now safely run the dependency
155
+ * const result = this.runSync('helper');
156
+ * return `Hello, ${result}`;
157
+ * }
158
+ * });
159
+ * // When mainFunc is registered, helperFunc will be registered automatically.
160
+ * mainFunc.register();
161
+ */
162
+ depends?: {
163
+ [name: string]: ToolFunc;
164
+ };
165
+ /**
166
+ * A detailed description of what the function does.
167
+ * @type {string}
168
+ */
169
+ description?: string;
170
+ /**
171
+ * A concise, human-readable title for the function, often used in UI or by AI.
172
+ * @type {string}
173
+ */
174
+ title?: string;
175
+ }
176
+ /**
177
+ * Extends `BaseFuncItem` to include the actual function implementation.
178
+ * @interface
179
+ */
180
+ interface FuncItem extends BaseFuncItem {
181
+ /**
182
+ * The implementation of the tool function.
183
+ * @type {TFunc}
184
+ */
185
+ func?: TFunc;
186
+ }
187
+ /**
188
+ * Represents a fully-defined tool function where the implementation is mandatory.
189
+ * @interface
190
+ */
191
+ interface BaseFunc extends BaseFuncItem {
192
+ /**
193
+ * The actual function implementation.
194
+ * @param {...any} params - The parameters for the function.
195
+ * @returns {any} The result of the function.
196
+ */
197
+ func(...params: any): any;
198
+ }
199
+ /**
200
+ * A map of registered `ToolFunc` instances, indexed by their names.
201
+ */
202
+ interface Funcs {
203
+ [name: string]: ToolFunc;
204
+ }
205
+ /**
206
+ * Describes a package of tool functions, including methods for registration and unregistration.
207
+ * @interface
208
+ */
209
+ interface ToolFuncPackage {
210
+ /**
211
+ * The name of the tool function package.
212
+ * @type {string}
213
+ */
214
+ name: string;
215
+ /**
216
+ * A method to register all functions within the package.
217
+ * @param {any} [data] - Optional data to pass to the registration process.
218
+ */
219
+ register: (data?: any) => void;
220
+ /**
221
+ * An optional method to unregister all functions within the package.
222
+ */
223
+ unregister?: () => void;
224
+ }
225
+ /**
226
+ * Declaration merging to extend the `ToolFunc` class with `BaseFunc` properties and allow arbitrary properties.
227
+ */
228
+ declare interface ToolFunc extends BaseFunc {
229
+ [name: string]: any;
230
+ }
231
+ /**
232
+ * A manager for creating, registering, and executing reusable tool functions.
233
+ *
234
+ * `ToolFunc` provides a robust framework for defining functions with rich metadata,
235
+ * managing their lifecycle, and executing them through a centralized registry.
236
+ * It is the core component for creating modular and discoverable tools.
237
+ *
238
+ * Key Features:
239
+ * - **Rich Metadata**: Define functions with descriptions, parameters, tags, and titles, making them self-documenting.
240
+ * - **Static Registry**: A global, static registry (`ToolFunc.items`) allows any part of an application to access and run registered functions by name.
241
+ * - **Dependency Management**: Use the `depends` property to declare dependencies on other `ToolFunc`s, which are then auto-registered.
242
+ * - **Aliasing**: Assign multiple names to a function for flexibility.
243
+ * - **Lifecycle Hooks**: Use the `setup` method for one-time initialization logic when a `ToolFunc` instance is created.
244
+ * - **Parameter Handling**: Automatically handles both positional and named parameters.
245
+ *
246
+ * @extends AdvancePropertyManager
247
+ *
248
+ * @example
249
+ * // 1. Define a helper function
250
+ * const getUser = new ToolFunc({
251
+ * name: 'getUser',
252
+ * description: 'Retrieves a user by ID.',
253
+ * params: { id: { type: 'string', required: true } },
254
+ * func: (params) => ({ id: params.id, name: 'John Doe' }),
255
+ * });
256
+ *
257
+ * // 2. Define a main function that depends on the helper
258
+ * const welcomeUser = new ToolFunc({
259
+ * name: 'welcomeUser',
260
+ * title: 'Welcome User',
261
+ * description: 'Generates a welcome message for a user.',
262
+ * params: { userId: 'string' },
263
+ * depends: {
264
+ * // By declaring this dependency, `getUser` will be auto-registered
265
+ * // when `welcomeUser` is registered.
266
+ * userFetcher: getUser,
267
+ * },
268
+ * func: function(params) {
269
+ * // `this` is the ToolFunc instance, so we can use `runSync`
270
+ * const user = this.runSync('userFetcher', { id: params.userId });
271
+ * return `Hello, ${user.name}!`;
272
+ * },
273
+ * });
274
+ *
275
+ * // 3. Register the main function. The dependency is registered automatically.
276
+ * welcomeUser.register();
277
+ *
278
+ * // 4. Run the function from anywhere using the static runner.
279
+ * async function main() {
280
+ * const message = await ToolFunc.run('welcomeUser', { userId: '123' });
281
+ * console.log(message); // Outputs: "Hello, John Doe!"
282
+ * }
283
+ *
284
+ * main();
285
+ */
286
+ declare class ToolFunc extends AdvancePropertyManager {
287
+ /**
288
+ * A static registry of all `ToolFunc` instances, indexed by name.
289
+ * @type {Funcs}
290
+ */
291
+ static items: Funcs;
292
+ /**
293
+ * A static map of aliases to their corresponding function names.
294
+ * @type {{ [name: string]: string }}
295
+ */
296
+ static aliases: {
297
+ [name: string]: string;
298
+ };
299
+ /**
300
+ * A conventional property to designate a file path for saving the registered `ToolFunc` data.
301
+ * Note: The `ToolFunc` class itself does not implement persistence logic. It is up to the
302
+ * developer to use this path to save and load the `ToolFunc.items` registry if needed.
303
+ * @type {string}
304
+ */
305
+ static dataPath: string;
306
+ /**
307
+ * Retrieves a registered function by its name or alias.
308
+ * @param {string} name - The name or alias of the function to retrieve.
309
+ * @returns {ToolFunc | undefined} The `ToolFunc` instance if found, otherwise `undefined`.
310
+ */
311
+ static get(name: string): ToolFunc;
312
+ /**
313
+ * Returns the complete map of all registered functions.
314
+ * @returns {Funcs} The map of `ToolFunc` instances.
315
+ */
316
+ static list(): Funcs;
317
+ /**
318
+ * Finds the first registered function that has a specific tag.
319
+ * @param {string} tagName - The tag to search for.
320
+ * @returns {ToolFunc | undefined} The first matching `ToolFunc` instance, or `undefined` if none is found.
321
+ */
322
+ static getByTag(tagName: string): ToolFunc | undefined;
323
+ /**
324
+ * Retrieves all registered functions that have a specific tag.
325
+ * @param {string} tagName - The tag to search for.
326
+ * @returns {ToolFunc[]} An array of matching `ToolFunc` instances.
327
+ */
328
+ static getAllByTag(tagName: string): ToolFunc[];
329
+ /**
330
+ * Checks if any registered function has a specific asynchronous feature.
331
+ * @param {AsyncFeatureBits} feature - The async feature bit to check for.
332
+ * @returns {boolean} `true` if the feature is present in any function, otherwise `false`.
333
+ */
334
+ static hasAsyncFeature(feature: AsyncFeatureBits): boolean;
335
+ /**
336
+ * Asynchronously executes a registered function by name with named parameters.
337
+ * @param {string} name - The name of the function to run.
338
+ * @param {any} [params] - The parameters object for the function.
339
+ * @returns {Promise<any>} A promise that resolves with the function's result.
340
+ * @throws {NotFoundError} If the function with the given name is not found.
341
+ */
342
+ static run(name: string, params?: any): Promise<any>;
343
+ /**
344
+ * Synchronously executes a registered function by name with named parameters.
345
+ * @param {string} name - The name of the function to run.
346
+ * @param {any} [params] - The parameters object for the function.
347
+ * @returns {any} The result of the function's execution.
348
+ * @throws {NotFoundError} If the function with the given name is not found.
349
+ */
350
+ static runSync(name: string, params?: any): any;
351
+ /**
352
+ * Retrieves a bound, runnable function reference for a registered function.
353
+ * This reference is suitable for execution with an object of named parameters.
354
+ * @param {string} name - The name of the function.
355
+ * @returns {Function | undefined} A bound function reference, or `undefined` if not found.
356
+ */
357
+ static getFunc(name: string): any;
358
+ /**
359
+ * Asynchronously executes a function using positional arguments.
360
+ * @param {string} name - The name of the function to run.
361
+ * @param {...any[]} params - Positional arguments to pass to the function.
362
+ * @returns {Promise<any>} A promise that resolves with the function's result.
363
+ * @throws {NotFoundError} If the function with the given name is not found.
364
+ */
365
+ static runWithPos(name: string, ...params: any[]): Promise<any>;
366
+ /**
367
+ * Synchronously executes a function using positional arguments.
368
+ * @param {string} name - The name of the function to run.
369
+ * @param {...any[]} params - Positional arguments to pass to the function.
370
+ * @returns {any} The result of the function's execution.
371
+ * @throws {NotFoundError} If the function with the given name is not found.
372
+ */
373
+ static runWithPosSync(name: string, ...params: any[]): any;
374
+ /**
375
+ * Retrieves a bound, runnable function reference for a registered function.
376
+ * This reference is suitable for execution with positional arguments.
377
+ * @param {string} name - The name of the function.
378
+ * @returns {Function | undefined} A bound function reference, or `undefined` if not found.
379
+ */
380
+ static getFuncWithPos(name: string): any;
381
+ /**
382
+ * Registers a new tool function.
383
+ *
384
+ * @overload
385
+ * @param {string} name - The name of the function.
386
+ * @param {FuncItem} options - The function's configuration.
387
+ * @returns {boolean | ToolFunc} The new `ToolFunc` instance, or `false` if a function with that name already exists.
388
+ *
389
+ * @overload
390
+ * @param {Function} func - The function implementation.
391
+ * @param {FuncItem} options - The function's configuration.
392
+ * @returns {boolean | ToolFunc} The new `ToolFunc` instance, or `false` if a function with that name already exists.
393
+ *
394
+ * @overload
395
+ * @param {string | ToolFunc | Function | FuncItem} name - A name, `ToolFunc` instance, function, or configuration object.
396
+ * @param {FuncItem} [options] - Additional configuration.
397
+ * @returns {boolean | ToolFunc} The new `ToolFunc` instance, or `false` if a function with that name already exists.
398
+ */
399
+ static register(name: string, options: FuncItem): boolean | ToolFunc;
400
+ static register(func: Function, options: FuncItem): boolean | ToolFunc;
401
+ static register(name: string | ToolFunc | Function | FuncItem, options?: FuncItem): boolean | ToolFunc;
402
+ /**
403
+ * Unregisters a function by its name, also removing any associated aliases.
404
+ * @param {string} name - The name of the function to unregister.
405
+ * @returns {ToolFunc | undefined} The unregistered `ToolFunc` instance, or `undefined` if it was not found.
406
+ */
407
+ static unregister(name: string): ToolFunc | undefined;
408
+ /**
409
+ * Initializes a new `ToolFunc` instance.
410
+ *
411
+ * @param {string | Function | FuncItem} name - Can be a function name, a function implementation, or a configuration object.
412
+ * @param {FuncItem | any} [options={}] - Configuration options if not provided in the first argument.
413
+ */
414
+ constructor(name: string | Function | FuncItem, options?: FuncItem | any);
415
+ /**
416
+ * Registers the current `ToolFunc` instance into the static registry.
417
+ * Also registers any declared dependencies.
418
+ * @returns {boolean | ToolFunc} The instance itself upon successful registration, or `false` if it already exists.
419
+ */
420
+ register(): boolean | ToolFunc;
421
+ /**
422
+ * Removes the current `ToolFunc` instance from the static registry.
423
+ * @returns {ToolFunc | undefined} The instance that was unregistered.
424
+ */
425
+ unregister(): any;
426
+ /**
427
+ * Converts an array of positional arguments into a named parameters object.
428
+ * This is used internally to support functions defined with named parameters.
429
+ * @param {any[]} params - An array of positional arguments.
430
+ * @returns {any[]} An array containing a single parameters object.
431
+ */
432
+ arr2ObjParams(params: any[]): any[];
433
+ /**
434
+ * Converts a named parameters object into an array of positional arguments.
435
+ * This is used for functions defined with positional parameters.
436
+ * @param {any} [params] - A named parameters object.
437
+ * @returns {any[]} An array of positional arguments.
438
+ */
439
+ obj2ArrParams(params?: any): any[];
440
+ /**
441
+ * Executes the function synchronously with a named parameters object.
442
+ * @param {any} [params] - The parameters object for the function.
443
+ * @returns {any} The result of the function execution.
444
+ * @throws Will throw an error if an array of parameters is passed to a function that expects an object.
445
+ */
446
+ runSync(params?: any): any;
447
+ /**
448
+ * Executes the function asynchronously with a named parameters object.
449
+ * @param {any} [params] - The parameters object for the function.
450
+ * @returns {Promise<any>} A promise that resolves with the function's result.
451
+ */
452
+ run(params?: any): Promise<any>;
453
+ /**
454
+ * Asynchronously executes another registered function by name.
455
+ * This method delegates to `runAsSync()` internally.
456
+ * @param {string} name - The name of the target function to run.
457
+ * @param {any} [params] - Optional parameters to pass to the function.
458
+ * @returns {Promise<any>} A promise that resolves with the result of the function execution.
459
+ */
460
+ runAs(name: string, params?: any): Promise<any>;
461
+ /**
462
+ * Synchronously executes another registered function by name.
463
+ * This is a convenience method that forwards the call to the static `runSync()` method.
464
+ * @param {string} name - The name of the target function to run.
465
+ * @param {any} [params] - Optional parameters to pass to the function.
466
+ * @returns {any} The result of the function execution.
467
+ */
468
+ runAsSync(name: string, params?: any): any;
469
+ /**
470
+ * Gets a bound function reference for execution with named parameters.
471
+ * If a name is provided, it retrieves a different function from the registry.
472
+ * Otherwise, it returns a bound version of this instance's `runSync`.
473
+ * @param {string} [name] - Optional name of the function to retrieve.
474
+ * @returns {Function | undefined} A function reference or `undefined` if not found.
475
+ */
476
+ getFunc(name?: string): any;
477
+ /**
478
+ * Executes the function synchronously using positional arguments.
479
+ * If the function expects named parameters, it converts the arguments automatically.
480
+ * @param {...any[]} params - Positional arguments passed to the function.
481
+ * @returns {any} The result of the function execution.
482
+ */
483
+ runWithPosSync(...params: any[]): any;
484
+ /**
485
+ * Synchronously executes another function by name using positional arguments.
486
+ * This is a convenience wrapper around the static `runWithPosSync()` method.
487
+ * @param {string} name - The name of the target function to run.
488
+ * @param {...any[]} params - Positional arguments to pass to the function.
489
+ * @returns {any} The result of the function execution.
490
+ */
491
+ runWithPosAsSync(name: string, ...params: any[]): any;
492
+ /**
493
+ * Executes the function asynchronously using positional arguments.
494
+ * Delegates to `runWithPosSync()` internally.
495
+ * @param {...any[]} params - Positional arguments passed to the function.
496
+ * @returns {Promise<any>} A promise that resolves with the result of the function execution.
497
+ */
498
+ runWithPos(...params: any[]): Promise<any>;
499
+ /**
500
+ * Asynchronously executes another function by name using positional arguments.
501
+ * Delegates to `runWithPosAsSync()` internally.
502
+ * @param {string} name - The name of the target function to run.
503
+ * @param {...any[]} params - Positional arguments to pass to the function.
504
+ * @returns {Promise<any>} A promise that resolves with the result of the function execution.
505
+ */
506
+ runWithPosAs(name: string, ...params: any[]): Promise<any>;
507
+ /**
508
+ * Gets a bound function reference suitable for positional argument execution.
509
+ * If a name is provided, it retrieves a different function from the registry.
510
+ * Otherwise, it returns a bound version of this instance's `runWithPosSync`.
511
+ * @param {string} [name] - Optional name of the function to retrieve.
512
+ * @returns {Function | undefined} A function reference or `undefined` if not found.
513
+ */
514
+ getFuncWithPos(name?: string): any;
515
+ /**
516
+ * Checks if the current function instance supports a specific async feature.
517
+ * @param {AsyncFeatureBits} feature - The async feature bit to check for.
518
+ * @returns {boolean} `true` if the feature is supported, otherwise `false`.
519
+ */
520
+ hasAsyncFeature(feature: AsyncFeatureBits): boolean;
521
+ /**
522
+ * Determines if a function call should produce a stream.
523
+ *
524
+ * The logic is as follows:
525
+ * 1. It first checks if the function is generally capable of streaming (`this.stream`).
526
+ * 2. If it is, it then checks if a `stream` parameter is formally declared in the function's `params` definition.
527
+ * 3. If both are true, the method returns the value of the `stream` property from the runtime `params` object.
528
+ * Otherwise, it returns the function's static `stream` capability.
529
+ *
530
+ * @param {any} params - The runtime parameters passed to the function call.
531
+ * @returns {boolean | undefined} `true` if the call should be streamed, `false` or `undefined` otherwise.
532
+ */
533
+ isStream(params: any): boolean | undefined;
534
+ }
535
+ /**
536
+ * Defines the schema for `ToolFunc` properties, used by `AdvancePropertyManager`.
537
+ * This controls how properties are assigned and exported.
538
+ * @internal
539
+ */
540
+ declare const ToolFuncSchema: {
541
+ name: {
542
+ type: string;
543
+ };
544
+ description: {
545
+ type: string;
546
+ };
547
+ title: {
548
+ type: string;
549
+ };
550
+ func: {
551
+ type: string;
552
+ assign(value: Function | string, dest: ToolFunc, src?: ToolFunc, name?: string, options?: any): string | Function;
553
+ };
554
+ params: {
555
+ type: string;
556
+ };
557
+ result: {
558
+ type: string;
559
+ };
560
+ setup: {
561
+ type: string;
562
+ };
563
+ depends: {
564
+ type: string;
565
+ exported: boolean;
566
+ };
567
+ tags: {
568
+ type: string[];
569
+ };
570
+ isApi: {
571
+ type: string;
572
+ };
573
+ stream: {
574
+ type: string;
575
+ };
576
+ asyncFeatures: {
577
+ type: string;
578
+ };
579
+ alias: {
580
+ type: string[];
581
+ };
582
+ };
583
+ /**
584
+ * A unique symbol used to attach metadata to a function object.
585
+ * @internal
586
+ */
587
+ declare const FuncMetaSymbol: unique symbol;
588
+ /**
589
+ * Attaches metadata to a function or `ToolFunc` object.
590
+ *
591
+ * This utility merges the provided metadata with any existing metadata on the target.
592
+ *
593
+ * @param {Function | ToolFunc} fn - The function or `ToolFunc` instance to which metadata will be added.
594
+ * @param {any} meta - The metadata object to attach. The operation is skipped if this is not a non-null object.
595
+ * @param {boolean} [ignoreExists=true] - If `true`, new metadata overwrites existing keys. If `false`, it merges deeply, preserving existing values.
596
+ * @returns {Function | ToolFunc | undefined} The updated function or `ToolFunc` with metadata, or `undefined` if the operation was skipped.
597
+ */
598
+ declare function funcWithMeta(fn: Function | ToolFunc, meta: any, ignoreExists?: boolean): Function | ToolFunc | undefined;
599
+ /**
600
+ * Retrieves metadata associated with a function or `ToolFunc` instance.
601
+ *
602
+ * @param {Function | ToolFunc} fn - The function or `ToolFunc` instance from which to retrieve metadata.
603
+ * @returns {any} The metadata as a plain object, or `undefined` if no metadata is found.
604
+ */
605
+ declare function funcGetMeta(fn: Function | ToolFunc): any;
606
+
607
+ /**
608
+ * A constant representing a passing score, likely used for similarity or relevance thresholds.
609
+ */
610
+ declare const PASSING_SCORE = 0.618;
611
+ /**
612
+ * A tuple of supported action names for remote tool interactions.
613
+ */
614
+ declare const ActionNames: readonly ["get", "post", "put", "delete", "patch", "list", "res"];
615
+ /**
616
+ * Represents a valid action name for a remote tool, derived from the `ActionNames` tuple.
617
+ */
618
+ type ActionName = typeof ActionNames[number];
619
+ /**
620
+ * Defines the signature for a function that processes an AI model's name,
621
+ * typically for matching or validation purposes.
622
+ * @param name - The model name string.
623
+ * @returns A string, a RegExp execution array, or undefined if no match is found.
624
+ */
625
+ type AIModelNameRuleFn = (name: string) => string | RegExpExecArray | undefined;
626
+ /**
627
+ * Defines a single rule for matching an AI model name. It can be a simple string,
628
+ * a regular expression, or a custom function.
629
+ */
630
+ type AIModelNameRule = string | RegExp | AIModelNameRuleFn;
631
+ /**
632
+ * Represents a collection of one or more AI model name matching rules.
633
+ */
634
+ type AIModelNameRules = AIModelNameRule | AIModelNameRule[];
635
+ /**
636
+ * A schema object defining properties common to all remote tool functions.
637
+ * This is used by `AdvancePropertyManager` to define how these properties are handled.
638
+ * @internal
639
+ */
640
+ declare const RemoteToolFuncSchema: {
641
+ /**
642
+ * The action for the remote call. This is primarily interpreted as an RPC method name.
643
+ * For HTTP transports, it defaults to being sent as a custom RPC method name (e.g., via POST).
644
+ * Only specific RESTful server implementations might map certain 'action' values (like 'get', 'delete')
645
+ * to corresponding HTTP methods. Defaults to 'post'.
646
+ */
647
+ action: {
648
+ type: string;
649
+ assign(value: ActionName, dest: any, src?: any, name?: string, options?: any): "get" | "post" | "put" | "delete" | "patch" | "list" | "res";
650
+ };
651
+ /**
652
+ * Optional fetch options, primarily for use with HTTP-based transports.
653
+ * @deprecated Use `transport` instead.
654
+ */
655
+ fetchOptions: {
656
+ type: string;
657
+ };
658
+ /**
659
+ * If true, allows the function's body to be exported to the client for local execution.
660
+ * This is a server-side setting.
661
+ */
662
+ allowExportFunc: {
663
+ type: string;
664
+ };
665
+ };
666
+ /**
667
+ * Base interface for a remote function's configuration, extending `BaseFuncItem`
668
+ * with properties required for remote execution.
669
+ */
670
+ interface RemoteFuncItem extends BaseFuncItem {
671
+ /**
672
+ * The root endpoint for the remote service.
673
+ * @type {string}
674
+ * @deprecated Use `transport` instead.
675
+ */
676
+ apiRoot?: string;
677
+ /**
678
+ * The action to be used for the remote call. This typically represents an RPC method name.
679
+ * Only for RESTful HTTP transports, it might be mapped to a standard HTTP method (e.g., GET, POST)
680
+ * @type {ActionName}
681
+ */
682
+ action?: ActionName;
683
+ /**
684
+ * Options to be passed to the underlying `fetch` call in an HTTP transport.
685
+ * @type {any}
686
+ * @deprecated Use `transport` instead.
687
+ */
688
+ fetchOptions?: any;
689
+ }
690
+
691
+ declare class Deque<T = any> extends Array<T> {
692
+ private _capacity;
693
+ private _length;
694
+ private _front;
695
+ private _disableAutoResize?;
696
+ constructor(capacity?: number | T[], disableAutoResize?: boolean);
697
+ push(item: T): number;
698
+ unshift(item: T): number;
699
+ /**
700
+ * Removes and returns the element at the back of the deque.
701
+ *
702
+ * @param skipNull When `true`, skips trailing `null`/`undefined` values until a valid element is found or all elements are processed.
703
+ * @returns The removed element, or `undefined` if the deque is empty or all elements are skipped.
704
+ *
705
+ * @example
706
+ * // Normal pop without skipping
707
+ * const deque = new Deque([1, 2, 3]);
708
+ * deque.pop(); // 3
709
+ *
710
+ * @example
711
+ * // Skipping null values
712
+ * const nullDeque = new Deque([null, 4, null]);
713
+ * nullDeque.pop(true); // 4
714
+ * nullDeque.pop(true); // undefined (skipped remaining nulls)
715
+ *
716
+ * @example
717
+ * // Mixed elements with skip
718
+ * const mixedDeque = new Deque([5, null, 6, null]);
719
+ * mixedDeque.pop(true); // 6
720
+ * mixedDeque.pop(false); // null (explicitly not skipping)
721
+ */
722
+ pop(skipNull?: boolean): T | undefined;
723
+ /**
724
+ * Removes and returns the element at the front of the deque.
725
+ *
726
+ * @param skipNull When `true`, skips leading `null`/`undefined` values until a valid element is found or all elements are processed.
727
+ * @returns The removed element, or `undefined` if the deque is empty or all elements are skipped.
728
+ *
729
+ * @example
730
+ * // Normal shift without skipping
731
+ * const deque = new Deque([1, 2, 3]);
732
+ * deque.shift(); // 1
733
+ *
734
+ * @example
735
+ * // Skipping null values
736
+ * const nullDeque = new Deque([null, 4, null]);
737
+ * nullDeque.shift(true); // 4
738
+ * nullDeque.shift(true); // undefined (skipped remaining nulls)
739
+ *
740
+ * @example
741
+ * // Mixed elements with skip
742
+ * const mixedDeque = new Deque([null, 5, null, 6]);
743
+ * mixedDeque.shift(true); // 5
744
+ * mixedDeque.shift(false); // null (explicitly not skipping)
745
+ */
746
+ shift(skipNull?: boolean): T | undefined;
747
+ /**
748
+ * Gets the number of elements in the deque.
749
+ *
750
+ * @returns The current count of elements in the deque.
751
+ *
752
+ * @example
753
+ * const deque = new Deque([1, 2, 3]);
754
+ * console.log(deque.size); // 3
755
+ *
756
+ * @important
757
+ * Do NOT use the native `Array.length` property. The Deque implementation uses a circular buffer with capacity management, so the native `length` reflects the underlying array capacity, not the actual element count. Always use `size` to get the correct element count.
758
+ */
759
+ get size(): number;
760
+ get(index: number): T | undefined;
761
+ peekBack(): T | undefined;
762
+ peekFront(): T | undefined;
763
+ clear(): void;
764
+ isEmpty(): boolean;
765
+ /**
766
+ * Removes the element at the specified index.
767
+ * @param index Logical index position (0 represents the front, length-1 represents the back)
768
+ * @returns The removed element
769
+ */
770
+ removeAt(index: number): T | undefined;
771
+ private checkCapacity;
772
+ private resizeTo;
773
+ }
774
+
775
+ declare const DefaultAsyncSemaphoreCapacity = 32;
776
+ type SemaphoreIsReadyFuncType = () => Promise<boolean> | boolean;
777
+ interface BinarySemaphoreOptions {
778
+ initFn?: () => any;
779
+ pauseFn?: () => void;
780
+ resumeFn?: () => void;
781
+ capacity?: number;
782
+ }
783
+ interface BinarySemaphoreAcquireOptions {
784
+ signal?: AbortSignal;
785
+ [n: string]: any;
786
+ }
787
+ interface BinarySemaphoreReleaseOptions {
788
+ token?: any;
789
+ [n: string]: any;
790
+ }
791
+ interface BinarySemaphoreReleaserFunc extends BinarySemaphoreReleaseOptions {
792
+ (): void;
793
+ }
794
+ interface SemaphoreOptions extends BinarySemaphoreOptions {
795
+ maxConcurrency?: number;
796
+ isReadyFn?: SemaphoreIsReadyFuncType;
797
+ }
798
+ interface SemaphoreTaskItem extends BinarySemaphoreAcquireOptions {
799
+ resolve: (value: any) => void;
800
+ reject: (reason?: any) => void;
801
+ token?: any;
802
+ }
803
+ /**
804
+ * A binary semaphore implementation for managing concurrency in asynchronous operations.
805
+ * Unlike a general semaphore, a binary semaphore allows only one caller to acquire the semaphore at a time.
806
+ * It provides methods to acquire, release, and manage waiting tasks efficiently.
807
+ *
808
+ * Example usage:
809
+ *
810
+ * ```typescript
811
+ * const semaphore = new Semaphore(5); // Allows 5 concurrent operations.
812
+ *
813
+ * const semaphore = new Semaphore(
814
+ * 4, // Allow 4 concurrent async calls
815
+ * {
816
+ * capacity: 100 // Prealloc space for 100 tokens
817
+ * }
818
+ * );
819
+ *
820
+ * async function fetchData(x) {
821
+ * await semaphore.acquire()
822
+ * try {
823
+ * console.log(semaphore.pendingCount + ' calls to fetch are waiting')
824
+ * // ... do some async stuff with x
825
+ * } finally {
826
+ * semaphore.release();
827
+ * }
828
+ * }
829
+ *
830
+ * const data = await Promise.all(array.map(fetchData));
831
+ * ```
832
+ */
833
+ declare class BinarySemaphore {
834
+ readonly waiting: Deque<SemaphoreTaskItem | undefined>;
835
+ protected free: any;
836
+ protected emitter: EventEmitter;
837
+ protected useDefaultTokens: boolean;
838
+ protected pauseFn?: () => void;
839
+ protected resumeFn?: () => void;
840
+ protected initTokenFn: (token?: any) => void;
841
+ protected paused: boolean;
842
+ protected _activeCount: number;
843
+ /**
844
+ * Creates a binary semaphore object for managing concurrency in asynchronous operations.
845
+ *
846
+ * @param options.initFn Function that is used to initialize the tokens used to manage the semaphore. The default is () => '1'.
847
+ * @param options.pauseFn An optional fuction that is called to opportunistically request pausing the the incoming stream of data,
848
+ * instead of piling up waiting promises and possibly running out of memory. See examples/pausing.js.
849
+ * @param options.resumeFn An optional function that is called when there is room again to accept new waiters on the semaphore.
850
+ * This function must be declared if a pauseFn is declared.
851
+ * @param options.capacity Sets the size of the preallocated waiting list inside the semaphore.
852
+ * This is typically used by high performance where the developer can make a rough estimate of the number of concurrent users of a semaphore.
853
+ *
854
+ * ```ts
855
+ * const readline = require('readline');
856
+ *
857
+ * const rl = readline.createInterface({
858
+ * input: process.stdin,
859
+ * output: process.stdout,
860
+ * terminal: false
861
+ * });
862
+ *
863
+ * function pause() {
864
+ * console.log('Pausing the stream');
865
+ * rl.pause();
866
+ * }
867
+ *
868
+ * function resume() {
869
+ * console.log('Resuming the stream');
870
+ * rl.resume();
871
+ * }
872
+ *
873
+ * const s = new BinarySemaphore({ pauseFn: pause, resumeFn: resume });
874
+ *
875
+ * async function parse(line) {
876
+ * await s.acquire();
877
+ *
878
+ * console.log(line);
879
+ *
880
+ * s.release();
881
+ * }
882
+ *
883
+ * rl.on('line', line => {
884
+ * parse(line).catch(console.error);
885
+ * });
886
+ * ```
887
+ *
888
+ */
889
+ constructor(options?: BinarySemaphoreOptions);
890
+ initFree(options?: BinarySemaphoreOptions): void;
891
+ onReleased(options?: BinarySemaphoreReleaseOptions): void;
892
+ init(options: BinarySemaphoreOptions): void;
893
+ _newReleaser(options?: BinarySemaphoreReleaseOptions): BinarySemaphoreReleaserFunc;
894
+ _dispatchTask(task: SemaphoreTaskItem, options?: BinarySemaphoreReleaseOptions): void;
895
+ lock(options?: BinarySemaphoreAcquireOptions): any;
896
+ unlock(token?: any): void;
897
+ /**
898
+ * Attempt to acquire a token from the semaphore, if one is available immediately. Otherwise, return undefined.
899
+ *
900
+ * @return Returns a token if the semaphore is not full; otherwise, returns `undefined`.
901
+ */
902
+ tryAcquire(options?: BinarySemaphoreAcquireOptions): any | undefined;
903
+ /**
904
+ * Acquire a token from the semaphore, thus decrement the number of available execution slots. If initFn is not used then the return value of the function can be discarded.
905
+ * @param options.signal An optional AbortSignal to abort the acquisition process. If aborted, the promise will reject with an AbortError.
906
+ * @return A promise that resolves to a release function when a token is acquired. If the semaphore is full, the caller will be added to a waiting queue.
907
+ */
908
+ acquire(options?: BinarySemaphoreAcquireOptions): Promise<BinarySemaphoreReleaserFunc>;
909
+ /**
910
+ * Releases the semaphore, incrementing the number of free execution slots. If there are tasks in the waiting queue, the next task will be dispatched.
911
+ * @param options.token Optional token returned by `acquire()` when using a custom `initFn`. If provided, it will be used to unlock the semaphore.
912
+ */
913
+ release(options?: BinarySemaphoreReleaseOptions): void;
914
+ /**
915
+ * Drains the semaphore and returns all the initialized tokens in an array. Draining is an ideal way to ensure there are no pending async tasks, for example before a process will terminate.
916
+ */
917
+ drain(): Promise<any[]>;
918
+ abort(reason?: any): void;
919
+ /**
920
+ * Get the total count of all active operations.
921
+ *
922
+ * This method returns the number of operations that are either:
923
+ * - Waiting in the queue to acquire the semaphore (`pendingCount`).
924
+ * - Already acquired the semaphore but have not yet released it.
925
+ *
926
+ * @returns {number} The total count of active operations, including both waiting and ongoing tasks.
927
+ */
928
+ get activeCount(): number;
929
+ /**
930
+ * Get the number of callers waiting on the semaphore, i.e. the number of pending promises.
931
+ *
932
+ * @returns The number of waiters in the waiting list.
933
+ */
934
+ get pendingCount(): number;
935
+ }
936
+ /**
937
+ * A Semaphore implementation for managing concurrency in asynchronous operations.
938
+ * Semaphores allow a fixed number of resources to be accessed concurrently.
939
+ * This class extends BinarySemaphore and adds support for a maximum concurrency limit and an optional readiness check.
940
+ *
941
+ * Example usage:
942
+ *
943
+ * ```typescript
944
+ * const semaphore = new Semaphore(5); // Allows 5 concurrent operations.
945
+ *
946
+ * const semaphore = new Semaphore(
947
+ * 4, // Allow 4 concurrent async calls
948
+ * {
949
+ * capacity: 100, // Prealloc space for 100 tokens
950
+ * isReadyFn: async () => {
951
+ * // Check if the system is ready to handle more requests
952
+ * return true;
953
+ * },
954
+ * pauseFn: () => {
955
+ * console.log('Pausing the stream');
956
+ * },
957
+ * resumeFn: () => {
958
+ * console.log('Resuming the stream');
959
+ * }
960
+ * }
961
+ * );
962
+ *
963
+ * async function fetchData(x) {
964
+ * await semaphore.acquire()
965
+ * try {
966
+ * console.log(semaphore.pendingCount() + ' calls to fetch are waiting')
967
+ * // ... do some async stuff with x
968
+ * } finally {
969
+ * semaphore.release();
970
+ * }
971
+ * }
972
+ *
973
+ * const data = await Promise.all(array.map(fetchData));
974
+ * ```
975
+ */
976
+ declare class Semaphore extends BinarySemaphore {
977
+ readonly maxConcurrency: number;
978
+ protected free: Deque<any>;
979
+ private isReady?;
980
+ /**
981
+ * Creates a semaphore object. The first argument is the maximum concurrently number and the second argument is optional.
982
+ *
983
+ * @param maxConcurrency The maximum number of callers allowed to acquire the semaphore concurrently.
984
+ * @param options.initFn Function that is used to initialize the tokens used to manage the semaphore. The default is () => '1'.
985
+ * @param options.pauseFn An optional function that is called to opportunistically request pausing the incoming stream of data,
986
+ * instead of piling up waiting promises and possibly running out of memory. See examples/pausing.js.
987
+ * @param options.resumeFn An optional function that is called when there is room again to accept new waiters on the semaphore.
988
+ * This function must be declared if a pauseFn is declared.
989
+ * @param options.capacity Sets the size of the preallocated waiting list inside the semaphore.
990
+ * This is typically used by high performance where the developer can make a rough estimate of the number of concurrent users of a semaphore.
991
+ * @param options.isReadyFn An optional function that returns a boolean or a promise that resolves to a boolean indicating whether the semaphore is ready to accept new requests.
992
+ */
993
+ constructor(maxConcurrency: number | SemaphoreOptions, options?: SemaphoreOptions);
994
+ initFree(options: SemaphoreOptions): void;
995
+ tryAcquire(options?: BinarySemaphoreAcquireOptions): Promise<any | undefined> | any | undefined;
996
+ unlock(token?: any): void;
997
+ lock(options?: BinarySemaphoreAcquireOptions): any;
998
+ drain(): Promise<any[]>;
999
+ }
1000
+ /**
1001
+ * Creates a rate limiter function that blocks with a promise whenever the rate limit is hit and resolves the promise once the call rate is within the limit set by rps. The second argument is optional.
1002
+ *
1003
+ * @param rps
1004
+ * @param options.timeUnit The `timeUnit` is an optional argument setting the width of the rate limiting window in milliseconds.
1005
+ * The default `timeUnit` is 1000 ms, therefore making the rps argument act as requests per second limit.
1006
+ * @param options.uniformDistribution The `uniformDistribution` argument enforces a discrete uniform distribution over time,
1007
+ * instead of the default that allows hitting the function rps time and then pausing for timeWindow milliseconds. Setting
1008
+ * the `uniformDistribution` option is mainly useful in a situation where the flow of rate limit function calls is continuous
1009
+ * and and occuring faster than timeUnit (e.g. reading a file) and not enabling it would cause the maximum number of calls to
1010
+ * resolve immediately (thus exhaust the limit immediately) and therefore the next bunch calls would need to wait for timeWindow
1011
+ * milliseconds. However if the flow is sparse then this option may make the code run slower with no advantages.
1012
+ *
1013
+ * Examples:
1014
+ *
1015
+ * ```ts
1016
+ * async function f() {
1017
+ * const lim = RateLimit(5); // rps
1018
+ *
1019
+ * for (let i = 0; i < n; i++) {
1020
+ * await lim();
1021
+ * // ... do something async
1022
+ * }
1023
+ * }
1024
+ * ```
1025
+ *
1026
+ *
1027
+ */
1028
+ declare function RateLimit(rps: number, { timeUnit, uniformDistribution, }?: {
1029
+ timeUnit?: number;
1030
+ uniformDistribution?: boolean;
1031
+ }): () => Promise<void>;
1032
+
1033
+ declare const ToolAsyncMultiTaskBit = 0;
1034
+ declare const ToolAsyncCancelableBit = 1;
1035
+ declare const ToolAsyncPriorityBit = 2;
1036
+ declare enum AsyncFeatureBits {
1037
+ MultiTask = 0,
1038
+ Cancelable = 1,
1039
+ Priority = 2
1040
+ }
1041
+ declare enum AsyncFeatures {
1042
+ MultiTask = 1,// B0001
1043
+ Cancelable = 2,// B010
1044
+ Priority = 4
1045
+ }
1046
+ type AsyncTaskId = string | number;
1047
+ interface CancelableAbilityOptions extends AbilityOptions {
1048
+ asyncFeatures?: AsyncFeatures;
1049
+ maxTaskConcurrency?: number;
1050
+ isReadyFn?: SemaphoreIsReadyFuncType;
1051
+ }
1052
+ declare class TaskAbortController extends AbortController {
1053
+ id?: AsyncTaskId;
1054
+ timeoutId?: any;
1055
+ streamController?: ReadableStreamDefaultController;
1056
+ parent: CancelableAbility;
1057
+ constructor(parent: CancelableAbility);
1058
+ abort(reason?: string | Error | CommonError, data?: any): void;
1059
+ throwRejected(alreadyRejected?: boolean): true | undefined;
1060
+ }
1061
+ interface TaskAbortControllers {
1062
+ [k: AsyncTaskId]: TaskAbortController | undefined;
1063
+ }
1064
+ interface TaskPromise<T = any> extends Promise<T> {
1065
+ task?: TaskAbortController;
1066
+ }
1067
+ declare interface CancelableAbility {
1068
+ _asyncFeatures?: number;
1069
+ _maxTaskConcurrency: number | undefined;
1070
+ _isReadyFn?: SemaphoreIsReadyFuncType;
1071
+ [name: string]: any;
1072
+ }
1073
+ declare class CancelableAbility {
1074
+ generateAsyncTaskId: (taskId?: AsyncTaskId, aborters?: TaskAbortControllers) => AsyncTaskId;
1075
+ cleanMultiTaskAborter: (id: AsyncTaskId, aborters: TaskAbortControllers) => void;
1076
+ __task_aborter: TaskAbortController | TaskAbortControllers | undefined;
1077
+ __task_semaphore: Semaphore | undefined;
1078
+ get maxTaskConcurrency(): number | undefined;
1079
+ get semaphore(): Semaphore | undefined;
1080
+ getSemaphore(isReadyFn?: SemaphoreIsReadyFuncType | undefined): Semaphore | undefined;
1081
+ static hasAsyncFeature(feature: AsyncFeatureBits): boolean;
1082
+ hasAsyncFeature(feature: AsyncFeatureBits): boolean;
1083
+ isAborted(taskId?: AsyncTaskId): boolean;
1084
+ getRunningTask(taskId?: AsyncTaskId): TaskAbortController | undefined;
1085
+ getRunningTaskCount(): number;
1086
+ _generateAsyncTaskId(taskId?: AsyncTaskId, aborters?: TaskAbortControllers): AsyncTaskId;
1087
+ $generateAsyncTaskId(taskId?: AsyncTaskId, aborters?: TaskAbortControllers): AsyncTaskId | undefined;
1088
+ createAborter(params?: any, taskId?: AsyncTaskId, raiseError?: boolean): TaskAbortController;
1089
+ $cleanMultiTaskAborter(id: AsyncTaskId, aborters: TaskAbortControllers): void;
1090
+ cleanTaskAborter(aborter: TaskAbortController): void;
1091
+ _cleanMultiTaskAborter(id: AsyncTaskId, aborters: TaskAbortControllers): void;
1092
+ createTaskPromise<Output = any>(runTask: (params: Record<string, any>, aborter: TaskAbortController) => Promise<Output>, params: Record<string, any>, options?: {
1093
+ taskId?: AsyncTaskId;
1094
+ raiseError?: boolean;
1095
+ }): TaskPromise<Output>;
1096
+ runAsyncCancelableTask<Output = any>(params: Record<string, any> | undefined, runTask: (params: Record<string, any>, aborter: TaskAbortController) => Promise<Output>, options?: {
1097
+ taskId?: AsyncTaskId;
1098
+ raiseError?: boolean;
1099
+ isReadyFn?: SemaphoreIsReadyFuncType;
1100
+ }): TaskPromise<Output>;
1101
+ abort(reason?: string, data?: any): void;
1102
+ }
1103
+ declare const makeToolFuncCancelable: <T extends Function | (new (...args: any[]) => any)>(targetClass?: T | undefined, options?: AbilityOptions) => T & typeof CancelableAbility & (T extends new (...args: any[]) => any ? InstanceType<T> : T) & CancelableAbility;
1104
+
1105
+ declare global {
1106
+ // eslint-disable-next-line @typescript-eslint/consistent-type-definitions -- It has to be an `interface` so that it can be merged.
1107
+ interface SymbolConstructor {
1108
+ readonly observable: symbol;
1109
+ }
1110
+ }
1111
+
1112
+ /**
1113
+ * @file Defines common types used across transports.
1114
+ */
1115
+
1116
+ /**
1117
+ * The generic handler for a remote procedure call (RPC) method.
1118
+ * It receives the parameters and returns the result.
1119
+ * @param params - The parameters for the RPC method.
1120
+ * @param context - Optional context, like the raw request object from the underlying framework.
1121
+ * @returns The result of the RPC method.
1122
+ */
1123
+ type RpcMethodHandler = (params: any, context?: any) => Promise<any> | any;
1124
+ interface IToolTransport {
1125
+ Tools: typeof ToolFunc;
1126
+ /**
1127
+ * The root endpoint for the remote service.
1128
+ * For HTTP, this is a URL. For IPC, it could be a channel name.
1129
+ */
1130
+ apiRoot: string;
1131
+ /**
1132
+ * Additional options for the transport start or fetch, passed by mount.
1133
+ */
1134
+ options?: any;
1135
+ mount(Tools: typeof ToolFunc, apiRoot?: string, options?: any): any | Promise<any>;
1136
+ [name: string]: any;
1137
+ }
1138
+ declare abstract class ToolTransport implements IToolTransport {
1139
+ apiRoot: string;
1140
+ Tools: typeof ToolFunc;
1141
+ options?: any;
1142
+ setApiRoot(apiRoot: string): void;
1143
+ mount(Tools: typeof ToolFunc, apiRoot?: string, options?: any): any;
1144
+ abstract _mount(Tools: typeof ToolFunc, apiRoot: string, options?: any): any | Promise<any>;
1145
+ }
1146
+
1147
+ /**
1148
+ * Defines the public interface for a client-side transport,
1149
+ * responsible for communicating with a ServerTransport.
1150
+ */
1151
+ interface IClientToolTransport extends IToolTransport {
1152
+ /**
1153
+ * Connects to the server's discovery endpoint to get the list of available tools.
1154
+ * @returns A promise that resolves to a map of tool function metadata.
1155
+ */
1156
+ loadApis(): Promise<Funcs>;
1157
+ mount(clientTools: typeof ClientTools, apiPrefix?: string, options?: any): any | Promise<any>;
1158
+ /**
1159
+ * Fetches data from the server.
1160
+ * @param name The name of the tool function to fetch.
1161
+ * @param args The object parameters to pass to the server.
1162
+ * @param act The action to perform on the server.
1163
+ * @param subName The name of the sub-resource to fetch.
1164
+ * @param options Additional options for the fetch call.
1165
+ * @returns A promise that resolves with the fetched data.
1166
+ */
1167
+ fetch(name: string, args?: any, act?: ActionName | string, subName?: any, options?: any): any | Promise<any>;
1168
+ [name: string]: any;
1169
+ }
1170
+ /**
1171
+ * A concrete client transport implementation that uses the browser/node `fetch` API.
1172
+ */
1173
+ declare abstract class ClientToolTransport extends ToolTransport implements IClientToolTransport {
1174
+ apiRoot: string;
1175
+ Tools: typeof ClientTools;
1176
+ constructor(apiRoot: string);
1177
+ _mount(clientTools: typeof ClientTools, apiPrefix: string, options?: any): Promise<Funcs>;
1178
+ /**
1179
+ * Connects to the server's discovery endpoint to get the list of available tools.
1180
+ * @returns A promise that resolves to a map of tool function metadata.
1181
+ */
1182
+ loadApis(): Promise<Funcs>;
1183
+ fetch(name: string, args?: any, act?: ActionName | string, subName?: any, fetchOptions?: any): Promise<any>;
1184
+ abstract _fetch(name: string, args?: any, act?: ActionName | string, subName?: any, fetchOptions?: any): any | Promise<any>;
1185
+ abstract toObject(res: any, args?: any): any | Promise<any>;
1186
+ }
1187
+
1188
+ /**
1189
+ * Alias for `RemoteFuncItem` on the client side.
1190
+ */
1191
+ interface ClientFuncItem extends RemoteFuncItem {
1192
+ }
1193
+ /**
1194
+ * Declaration merging to extend the `ClientTools` class with `ClientFuncItem` properties.
1195
+ */
1196
+ declare interface ClientTools extends ClientFuncItem {
1197
+ [name: string]: any;
1198
+ }
1199
+ /**
1200
+ * Represents a client-side proxy for a remote tool function.
1201
+ *
1202
+ * A `ClientTools` instance is a `ToolFunc` that, when executed, does not run
1203
+ * local code. Instead, it serializes the parameters and uses an injected
1204
+ * transport layer (`IClientToolTransport`) to make a remote procedure call
1205
+ * to its corresponding `ServerTools` counterpart.
1206
+ *
1207
+ * These tools are typically created dynamically by loading definitions from a server.
1208
+ */
1209
+ declare class ClientTools extends ToolFunc {
1210
+ static action?: ActionName | string;
1211
+ private static _transport;
1212
+ /**
1213
+ * @deprecated This property is now mainly for informational purposes.
1214
+ * The actual endpoint is managed by the transport.
1215
+ */
1216
+ static get apiRoot(): string;
1217
+ /**
1218
+ * Injects the client-side transport implementation. This is a crucial step
1219
+ * to enable communication with the server.
1220
+ * @param {IClientToolTransport} transport - The transport instance to use for all client-server communication.
1221
+ */
1222
+ static setTransport(transport: IClientToolTransport): void;
1223
+ static get transport(): IClientToolTransport;
1224
+ /**
1225
+ * Loads tool definitions from the remote server via the configured transport.
1226
+ * This method populates the local `ToolFunc` registry with `ClientTools` stubs.
1227
+ */
1228
+ static loadFrom(items?: Funcs): Promise<Funcs>;
1229
+ /**
1230
+ * Synchronously loads tool definitions from a provided object, registering
1231
+ * each one as a `ClientTools` instance.
1232
+ * @param items - A map of tool function metadata, typically from a server.
1233
+ */
1234
+ static loadFromSync(items: Funcs): void;
1235
+ static fetch(name: string, objParam?: any, ...args: any[]): Promise<any>;
1236
+ /**
1237
+ * @deprecated This property is now mainly for informational purposes.
1238
+ * The actual endpoint is managed by the transport.
1239
+ */
1240
+ get apiRoot(): string;
1241
+ fetch(objParam?: any, act?: ActionName, subName?: any): Promise<any>;
1242
+ /**
1243
+ * The core implementation for a client-side tool. When a `ClientTools` instance
1244
+ * is "run", this `func` method is executed. It delegates the call to the
1245
+ * configured transport, which handles the network communication.
1246
+ *
1247
+ * @param objParam - The parameters to send to the remote tool.
1248
+ * @param objParam.stream [boolean] - the optional stream flag. if true, the tool will return a stream(ReadableStream).
1249
+ * @returns The result from the remote tool.
1250
+ */
1251
+ func(objParam: any): Promise<any>;
1252
+ }
1253
+ /**
1254
+ * The schema definition for `ClientTools` properties.
1255
+ * @internal
1256
+ */
1257
+ declare const ClientToolFuncSchema: {
1258
+ action: {
1259
+ type: string;
1260
+ assign(value: ActionName, dest: any, src?: any, name?: string, options?: any): "get" | "post" | "put" | "delete" | "patch" | "list" | "res";
1261
+ };
1262
+ fetchOptions: {
1263
+ type: string;
1264
+ };
1265
+ allowExportFunc: {
1266
+ type: string;
1267
+ };
1268
+ };
1269
+
1270
+ /**
1271
+ * Defines the structure for parameters passed to a `ServerTools` function.
1272
+ * By convention, it includes optional `_req` and `_res` properties for direct
1273
+ * access to the underlying transport's request and response objects (e.g., from Node.js http).
1274
+ */
1275
+ interface ServerFuncParams {
1276
+ /**
1277
+ * The underlying request object from the transport layer (e.g., `IncomingMessage`).
1278
+ * @type {any}
1279
+ */
1280
+ _req?: any;
1281
+ /**
1282
+ * The underlying response or reply object from the transport layer (e.g., `ServerResponse`).
1283
+ * @type {any}
1284
+ */
1285
+ _res?: any;
1286
+ [name: string]: any;
1287
+ }
1288
+ /**
1289
+ * Configuration interface for a `ServerTools` item.
1290
+ * Extends `RemoteFuncItem` with server-specific options.
1291
+ */
1292
+ interface ServerFuncItem extends RemoteFuncItem {
1293
+ /**
1294
+ * If set to true, the body of the function (`func`) will be serialized and sent
1295
+ * to the client when tools are loaded. This allows the client to execute the
1296
+ * function locally instead of making a remote call. Defaults to false.
1297
+ * @type {boolean}
1298
+ */
1299
+ allowExportFunc?: boolean;
1300
+ }
1301
+ /**
1302
+ * Declaration merging to extend the `ServerTools` class with `ServerFuncItem` properties.
1303
+ */
1304
+ declare interface ServerTools extends ServerFuncItem {
1305
+ [name: string]: any;
1306
+ }
1307
+ /**
1308
+ * Represents a function that runs on a server and can be exposed to clients.
1309
+ *
1310
+ * `ServerTools` extends `ToolFunc` by adding logic for serialization and handling
1311
+ * server-side execution contexts. It is designed to work with a transport layer
1312
+ * (see `transports`) to expose its registered functions over a network.
1313
+ */
1314
+ declare class ServerTools extends ToolFunc {
1315
+ private static _apiRoot?;
1316
+ /**
1317
+ * The conventional root path for the API endpoint.
1318
+ */
1319
+ static get apiRoot(): string | undefined;
1320
+ static setApiRoot(v: string): void;
1321
+ /**
1322
+ * Serializes all registered `ServerTools` instances into a JSON object.
1323
+ * This method is typically called by a transport's discovery endpoint.
1324
+ *
1325
+ * It filters for tools that are instances of `ServerTools` or marked as `isApi`.
1326
+ * It omits the `func` body from the output unless `allowExportFunc` is true.
1327
+ *
1328
+ * @returns A map of serializable tool definitions.
1329
+ */
1330
+ static toJSON(): {
1331
+ [name: string]: ServerTools;
1332
+ };
1333
+ /**
1334
+ * Overrides the base `run` method to inject transport-specific context.
1335
+ * If a `context` object containing `req` and `reply` is provided, these are
1336
+ * added to the parameters as `_req` and `_res` before execution.
1337
+ *
1338
+ * @param {ServerFuncParams} params - The parameters for the function.
1339
+ * @param {{ req: any, reply: any }} [context] - The transport-level context.
1340
+ * @returns The result of the function execution.
1341
+ */
1342
+ run(params: ServerFuncParams, context?: {
1343
+ req: any;
1344
+ reply: any;
1345
+ }): Promise<any>;
1346
+ /**
1347
+ * Placeholder for the actual server-side function implementation.
1348
+ * This method is intended to be defined when a `ServerTools` instance is created.
1349
+ * @param params - The parameters for the function.
1350
+ * @returns The result of the function.
1351
+ */
1352
+ func(params: ServerFuncParams): Promise<any> | any;
1353
+ }
1354
+ /**
1355
+ * The schema definition for `ServerTools` properties.
1356
+ * @internal
1357
+ */
1358
+ declare const ServerToolFuncSchema: {
1359
+ action: {
1360
+ type: string;
1361
+ assign(value: ActionName, dest: any, src?: any, name?: string, options?: any): "get" | "post" | "put" | "delete" | "patch" | "list" | "res";
1362
+ };
1363
+ fetchOptions: {
1364
+ type: string;
1365
+ };
1366
+ allowExportFunc: {
1367
+ type: string;
1368
+ };
1369
+ };
1370
+
1371
+ declare class EventToolFunc extends ToolFunc {
1372
+ _emitter: EventEmitter;
1373
+ description: string;
1374
+ result: string;
1375
+ get emitter(): EventEmitter;
1376
+ func(): EventEmitter;
1377
+ }
1378
+ declare const event: EventToolFunc;
1379
+
1380
+ declare const SecondaryCache: typeof Cache;
1381
+ declare function _lrucache(this: ToolFunc, { key, value, options }?: {
1382
+ key?: string;
1383
+ value?: any;
1384
+ options?: ICacheOptions | number;
1385
+ }): Cache;
1386
+ declare function createLRUCache(name: string, options?: ICacheOptions | number): ToolFunc;
1387
+ declare const lrucache: ToolFunc;
1388
+
1389
+ interface RpcMethodsClientFuncParams {
1390
+ act?: string;
1391
+ [name: string]: any;
1392
+ }
1393
+ declare class RpcMethodsClientTool extends ClientTools {
1394
+ fetch(options: RpcMethodsClientFuncParams, action: ActionName, subName?: any): Promise<any>;
1395
+ _func(action: ActionName, options: RpcMethodsClientFuncParams): Promise<any>;
1396
+ func(options: RpcMethodsClientFuncParams): Promise<any>;
1397
+ assignMethods(methods: string[]): void;
1398
+ }
1399
+
1400
+ interface ResClientFuncParams extends RpcMethodsClientFuncParams {
1401
+ id?: string | number;
1402
+ }
1403
+ interface ResClientTools {
1404
+ get?({ id }: ResClientFuncParams): any;
1405
+ post?(options: ResClientFuncParams): any;
1406
+ put?({ id }: ResClientFuncParams): any;
1407
+ delete?({ id }: ResClientFuncParams): any;
1408
+ list?(options?: ResClientFuncParams): any;
1409
+ }
1410
+ declare class ResClientTools extends RpcMethodsClientTool {
1411
+ fetch(options: ResClientFuncParams, action: ActionName): Promise<any>;
1412
+ }
1413
+
1414
+ type PubSubCtx<T = any> = {
1415
+ event: string;
1416
+ id?: string;
1417
+ ts?: number;
1418
+ from?: string;
1419
+ meta?: any;
1420
+ };
1421
+
1422
+ /**
1423
+ * Represents the client-side stream for a PubSub connection.
1424
+ *
1425
+ * This interface abstracts the underlying connection object (like an `EventSource`
1426
+ * or `WebSocket` client) into a standardized event-based stream. It provides
1427
+ * methods for listening to events, sending messages (for bidirectional transports),
1428
+ * and managing the connection state.
1429
+ */
1430
+ interface PubSubClientStream {
1431
+ /**
1432
+ * The protocol being used for this stream (e.g., 'sse', 'ws', 'ipc').
1433
+ */
1434
+ protocol: 'sse' | 'ws' | 'ipc' | string;
1435
+ /**
1436
+ * Optional. Represents the state of the connection.
1437
+ * This is provided for compatibility with the `EventSource.readyState`
1438
+ * and `WebSocket.readyState` properties.
1439
+ * (e.g., 0 for connecting, 1 for open, 2 for closed).
1440
+ */
1441
+ readyState?: number;
1442
+ /**
1443
+ * Registers a listener for a specific event from the server.
1444
+ * @param event The name of the event to listen for.
1445
+ * @param listener The callback function to execute when the event is received.
1446
+ * It receives the event data and an optional context object.
1447
+ */
1448
+ on: (event: string, listener: (data: any, ctx?: PubSubCtx) => void) => any;
1449
+ /**
1450
+ * Removes a previously registered event listener.
1451
+ * @param event The name of the event.
1452
+ * @param listener The listener function to remove.
1453
+ */
1454
+ off: (event: string, listener: (data: any, ctx?: PubSubCtx) => void) => void;
1455
+ /**
1456
+ * Closes the connection stream.
1457
+ */
1458
+ close: () => void;
1459
+ /**
1460
+ * Optional. Sends a message from the client to the server.
1461
+ * This method is only available for bidirectional transports like WebSockets or IPC.
1462
+ * It is not supported by unidirectional transports like Server-Sent Events (SSE).
1463
+ * @param event The name of the event to send.
1464
+ * @param data The payload for the event.
1465
+ * @param ctx Optional context for the PubSub operation.
1466
+ */
1467
+ send?: (event: string, data: any, ctx?: PubSubCtx) => void;
1468
+ /**
1469
+ * Optional alias for the `on` method for compatibility with the
1470
+ * standard `EventTarget` interface.
1471
+ */
1472
+ addEventListener?: PubSubClientStream['on'];
1473
+ /**
1474
+ * Optional alias for the `off` method for compatibility with the
1475
+ * standard `EventTarget` interface.
1476
+ */
1477
+ removeEventListener?: PubSubClientStream['off'];
1478
+ }
1479
+ /**
1480
+ * Defines the interface for a client-side PubSub transport.
1481
+ *
1482
+ * This abstraction is responsible for creating and managing the connection
1483
+ * stream (`PubSubClientStream`) to the server.
1484
+ */
1485
+ interface IPubSubClientTransport {
1486
+ /**
1487
+ * Establishes a connection to a server endpoint.
1488
+ * @param url The URL of the server's PubSub endpoint.
1489
+ * @param params Optional parameters for the connection, which might include
1490
+ * things like authentication tokens, initial subscription topics, or a client ID.
1491
+ * @returns A `PubSubClientStream` instance that represents the active connection.
1492
+ */
1493
+ connect: (url: string, params?: Record<string, any>) => PubSubClientStream;
1494
+ /**
1495
+ * Optional. Disconnects a given stream.
1496
+ * While the `close` method exists on the stream itself, placing `disconnect`
1497
+ * on the transport can be semantically clearer in some architectures.
1498
+ * By default, this should delegate to `stream.close()`.
1499
+ * @param stream The stream to disconnect.
1500
+ */
1501
+ disconnect?: (stream: PubSubClientStream) => void;
1502
+ }
1503
+
1504
+ /**
1505
+ * Represents the unique identifier for a client connected to the PubSub transport.
1506
+ * This ID is used for targeted message publishing.
1507
+ */
1508
+ type PubSubClientId = string;
1509
+ /**
1510
+ * Represents a client as seen by the transport layer after a subscription is made.
1511
+ * It contains the client's ID and can hold other transport-specific metadata.
1512
+ */
1513
+ interface PubSubClient {
1514
+ /**
1515
+ * The unique identifier for this client.
1516
+ * This can be assigned by the client during connection or generated by the server.
1517
+ */
1518
+ clientId?: PubSubClientId;
1519
+ /**
1520
+ * Allows for storing additional, transport-specific properties about the client.
1521
+ */
1522
+ [k: string]: any;
1523
+ }
1524
+ /**
1525
+ * Represents an active client connection session on the server.
1526
+ * This object provides a standardized way for the `EventServer` to interact
1527
+ * with a connection, regardless of the underlying transport protocol.
1528
+ */
1529
+ interface PubSubServerSession {
1530
+ /**
1531
+ * A unique identifier for the session, typically generated by the transport layer upon connection.
1532
+ */
1533
+ id: string;
1534
+ /**
1535
+ * The unique identifier for the client associated with this session.
1536
+ */
1537
+ clientId?: PubSubClientId;
1538
+ /**
1539
+ * The protocol being used for this session (e.g., 'sse', 'ws', 'ipc').
1540
+ */
1541
+ protocol: 'sse' | 'ws' | 'ipc' | string;
1542
+ /**
1543
+ * Sends an event and data to the client associated with this session.
1544
+ * @param event The name of the event to send.
1545
+ * @param data The payload for the event.
1546
+ * @param ctx Optional context for the PubSub operation.
1547
+ */
1548
+ send: (event: string, data: any, ctx?: PubSubCtx) => void;
1549
+ /**
1550
+ * Closes the connection for this session.
1551
+ */
1552
+ close: () => void;
1553
+ /**
1554
+ * A reference to the raw, underlying connection object or handle
1555
+ * (e.g., a Node.js `ServerResponse` for SSE, or a WebSocket instance).
1556
+ * Use with caution as it is transport-specific.
1557
+ */
1558
+ raw?: any;
1559
+ }
1560
+ /**
1561
+ * Defines the interface for a server-side PubSub transport layer.
1562
+ *
1563
+ * This abstraction allows the `EventServer` to operate independently of the
1564
+ * underlying real-time communication protocol (e.g., SSE, WebSockets, IPC).
1565
+ * An implementation of this interface is responsible for managing client
1566
+ * connections, subscriptions, and message passing.
1567
+ */
1568
+ interface IPubSubServerTransport {
1569
+ /**
1570
+ * A unique, human-readable name for the transport (e.g., 'sse', 'websocket').
1571
+ */
1572
+ readonly name: string;
1573
+ /**
1574
+ * The protocol identifier.
1575
+ */
1576
+ readonly protocol: 'sse' | 'ws' | 'ipc' | string;
1577
+ /**
1578
+ * Optional method to mount or register the transport's endpoint with an HTTP
1579
+ * server or framework. This is typically required for protocols like SSE or
1580
+ * WebSockets that need to handle incoming HTTP requests at a specific path.
1581
+ *
1582
+ * @param path The URL path to handle (e.g., '/api/events').
1583
+ * @param options Additional options for mounting, specific to the framework.
1584
+ */
1585
+ mount?: (path: string, options?: Record<string, any>) => void;
1586
+ /**
1587
+ * Establishes a connection with a client and subscribes it to an event stream.
1588
+ *
1589
+ * This method is designed to be generic. Transport-specific details, such as
1590
+ * HTTP request/response objects or connection handles, should be passed
1591
+ * inside the `options` parameter to avoid polluting the abstraction layer.
1592
+ *
1593
+ * @param events Optional array of event names to initially subscribe the client to.
1594
+ * @param options A container for transport-specific parameters.
1595
+ * @param options.req The underlying request object (e.g., `http.IncomingMessage`).
1596
+ * @param options.res The underlying response object (e.g., `http.ServerResponse`).
1597
+ * @param options.clientId An optional ID provided by the client. If not provided,
1598
+ * the transport should generate one.
1599
+ * @param options.headers HTTP headers from the client request.
1600
+ * @returns A `PubSubClient` object representing the newly connected client.
1601
+ */
1602
+ subscribe: (events?: string[], options?: {
1603
+ req?: any;
1604
+ res?: any;
1605
+ clientId?: PubSubClientId;
1606
+ headers?: Record<string, string>;
1607
+ [k: string]: any;
1608
+ }) => PubSubClient;
1609
+ /**
1610
+ * Publishes an event from the server to connected clients.
1611
+ *
1612
+ * The transport implementation should handle broadcasting to all relevant
1613
+ * clients or targeting specific clients based on the `target` parameter.
1614
+ *
1615
+ * @param event The name of the event to publish.
1616
+ * @param data The payload for the event.
1617
+ * @param target Optional. Specifies the recipient(s) of the event.
1618
+ * If omitted, the event is typically broadcast to all subscribed clients.
1619
+ * @param target.clientId A single `PubSubClientId` or an array of IDs to
1620
+ * send the event to.
1621
+ * @param ctx Optional context for the PubSub operation.
1622
+ */
1623
+ publish: (event: string, data: any, target?: {
1624
+ clientId?: PubSubClientId | PubSubClientId[];
1625
+ }, ctx?: PubSubCtx) => void;
1626
+ /**
1627
+ * Registers a callback to be invoked when a new client connection is established
1628
+ * and a session is created.
1629
+ * @param cb The callback function that receives the new `PubSubServerSession`.
1630
+ */
1631
+ onConnection: (cb: (session: PubSubServerSession) => void) => void;
1632
+ /**
1633
+ * Registers a callback to be invoked when a client disconnects.
1634
+ * @param cb The callback function that receives the `PubSubServerSession` of the
1635
+ * disconnected client.
1636
+ */
1637
+ onDisconnect: (cb: (session: PubSubServerSession) => void) => void;
1638
+ /**
1639
+ * Optional. Registers a callback to handle incoming messages from clients.
1640
+ * This is only necessary for bidirectional transport protocols like WebSockets or IPC.
1641
+ *
1642
+ * @param cb The callback function that receives the session, event name, data, and context.
1643
+ */
1644
+ onMessage?: (cb: (session: PubSubServerSession, event: string, data: any, ctx?: PubSubCtx) => void) => void;
1645
+ }
1646
+
1647
+ interface EventClientFuncParams {
1648
+ event?: string | string[];
1649
+ data?: any;
1650
+ act?: 'sub' | 'pub' | 'unsub' | 'init';
1651
+ listener?: (...args: any[]) => void;
1652
+ }
1653
+ declare class EventClient extends ResClientTools {
1654
+ static _pubSubTransport: IPubSubClientTransport | undefined;
1655
+ static setPubSubTransport(t?: IPubSubClientTransport): void;
1656
+ static get pubSubTransport(): IPubSubClientTransport;
1657
+ _stream: PubSubClientStream | undefined;
1658
+ _streamEvents: string[] | undefined;
1659
+ _sseListeners: Record<string, (data: any, ctx?: PubSubCtx) => void>;
1660
+ _forwardEvents: Set<string>;
1661
+ get evtSource(): PubSubClientStream;
1662
+ get active(): boolean;
1663
+ set active(v: boolean);
1664
+ description: string;
1665
+ initEventStream(events?: string | string[]): PubSubClientStream;
1666
+ esListener(evtType: string, data: any, ctx?: PubSubCtx): void;
1667
+ ebListener: (this: Event, ...data: any[]) => Promise<void>;
1668
+ /**
1669
+ * subscribe server sent event(SSE)
1670
+ * @param events
1671
+ */
1672
+ subscribe(events: string | string[]): Promise<any>;
1673
+ /**
1674
+ * unsubscribe server sent event(SSE)
1675
+ * @param events
1676
+ */
1677
+ unsubscribe(events: string | string[]): Promise<any>;
1678
+ /**
1679
+ * forward local event(s) to server
1680
+ *
1681
+ * subscribe these local events to forward/publish to server
1682
+ *
1683
+ * Note: pls backendEventable(ClientTools or EventClient) first
1684
+ * @param events
1685
+ */
1686
+ forwardEvent(events: string | string[]): void;
1687
+ /**
1688
+ * unforward local event(s) to server
1689
+ *
1690
+ * unsubscribe these local events not to forward/publish to server
1691
+ *
1692
+ * Note: pls backendEventable(ClientTools or EventClient) first
1693
+ * @param events
1694
+ */
1695
+ unforwardEvent(events: string | string[]): void;
1696
+ init(events: string | string[]): Promise<any>;
1697
+ close(): void;
1698
+ }
1699
+ declare const eventClient: EventClient;
1700
+
1701
+ interface RpcMethodsServerFuncParams extends ServerFuncParams {
1702
+ act?: string;
1703
+ }
1704
+ interface RpcMethodsServerTool {
1705
+ methods: string[];
1706
+ }
1707
+ declare class RpcMethodsServerTool extends ServerTools {
1708
+ static SpecialRpcMethodNames?: string[];
1709
+ params: FuncParams;
1710
+ get SpecialRpcMethodNames(): any;
1711
+ initRpcMethods(methods?: string[]): void;
1712
+ constructor(name: string | Function | FuncItem, options?: FuncItem | any);
1713
+ cast(key: string, value: any): any;
1714
+ getMethodFromParams(params: RpcMethodsServerFuncParams): string | undefined;
1715
+ castParams(params: RpcMethodsServerFuncParams): RpcMethodsServerFuncParams;
1716
+ func(params: RpcMethodsServerFuncParams): any;
1717
+ }
1718
+
1719
+ interface ResServerFuncParams extends RpcMethodsServerFuncParams {
1720
+ id?: string | number;
1721
+ val?: any;
1722
+ }
1723
+ interface ResServerTools {
1724
+ get?({ id }: ResServerFuncParams): any;
1725
+ post?(options: ResServerFuncParams): any;
1726
+ put?({ id }: ResServerFuncParams): any;
1727
+ delete?({ id }: ResServerFuncParams): any;
1728
+ list?(options?: ResServerFuncParams): any;
1729
+ }
1730
+ declare class ResServerTools extends RpcMethodsServerTool {
1731
+ static SpecialRpcMethodNames: any;
1732
+ action: ActionName;
1733
+ params: FuncParams;
1734
+ constructor(name: string | Function | FuncItem, options?: FuncItem | any);
1735
+ getMethodFromParams(params: ResServerFuncParams): any;
1736
+ castParams(params: RpcMethodsServerFuncParams): RpcMethodsServerFuncParams;
1737
+ }
1738
+
1739
+ interface EventServerFuncParams extends ServerFuncParams {
1740
+ event?: string | string[];
1741
+ data?: any;
1742
+ act?: 'sub' | 'pub' | 'unsub';
1743
+ }
1744
+ declare class EventServer extends ResServerTools {
1745
+ private static _boundEbListener?;
1746
+ static _pubSubTransport: IPubSubServerTransport | undefined;
1747
+ static setPubSubTransport(t?: IPubSubServerTransport): void;
1748
+ static get pubSubTransport(): IPubSubServerTransport | undefined;
1749
+ description: string;
1750
+ result: string;
1751
+ depends: {
1752
+ "event-bus": EventToolFunc;
1753
+ };
1754
+ get pubSubTransport(): IPubSubServerTransport | undefined;
1755
+ static publish(data: any, event: string, target?: {
1756
+ clientId?: string | string[];
1757
+ }): void | undefined;
1758
+ static ebListener(eventType: string, ...data: any[]): void;
1759
+ static subscribe(req: IncomingMessage, res: ServerResponse, events?: string[], options?: any): PubSubClient | undefined;
1760
+ static alreadyForward(event: string): true | undefined;
1761
+ publishSSE(data: any, event: string): any;
1762
+ subscribeSSE(req: IncomingMessage, res: ServerResponse, events?: string | string[]): any;
1763
+ forward(events: string | string[]): void;
1764
+ unforward(events: string | string[]): void;
1765
+ list({ _req, _res, event }: EventServerFuncParams): void;
1766
+ $sub({ event }: EventServerFuncParams): {
1767
+ event: string | string[];
1768
+ };
1769
+ $unsub({ event }: EventServerFuncParams): {
1770
+ event: string | string[];
1771
+ };
1772
+ $publish({ event: events, data }: EventServerFuncParams): {
1773
+ event: string[];
1774
+ };
1775
+ isStream(params: ServerFuncParams): boolean;
1776
+ }
1777
+ declare const eventServer: EventServer;
1778
+
1779
+ declare function registerCoreTools(): void;
1780
+
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 };