@isdk/ai-tool 0.6.0 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (473) hide show
  1. package/README.cn.md +103 -237
  2. package/README.md +101 -186
  3. package/dist/chunk-4XRPAC7C.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-DEUnmyUq.d.mts +1792 -0
  10. package/dist/index-DEUnmyUq.d.ts +1792 -0
  11. package/dist/index.d.mts +1068 -9
  12. package/dist/index.d.ts +1068 -9
  13. package/dist/index.js +1 -1
  14. package/dist/index.mjs +1 -1
  15. package/dist/test/util.js +1 -1
  16. package/docs/api/README.md +165 -0
  17. package/docs/{_media → api/_media}/CONTRIBUTING.md +3 -3
  18. package/docs/api/_media/pubsub.md +326 -0
  19. package/docs/api/_media/server_client_tools.md +88 -0
  20. package/docs/api/_media/toolFunc.md +183 -0
  21. package/docs/api/_media/transport.md +137 -0
  22. package/docs/{classes → api/classes}/AbortError.md +139 -54
  23. package/docs/api/classes/AlreadyExistsError.md +431 -0
  24. package/docs/api/classes/BaseError.md +440 -0
  25. package/docs/{classes → api/classes}/BinarySemaphore.md +25 -25
  26. package/docs/{classes → api/classes}/CancelableAbility.md +25 -25
  27. package/docs/api/classes/ClientToolTransport.md +310 -0
  28. package/docs/{classes → api/classes}/ClientTools.md +646 -180
  29. package/docs/{classes → api/classes}/CommonError.md +139 -54
  30. package/docs/{classes → api/classes}/ConfigFile.md +54 -5
  31. package/docs/{classes → api/classes}/EnvPromptTemplate.md +94 -48
  32. package/docs/{classes → api/classes}/EventClient.md +742 -234
  33. package/docs/{classes → api/classes}/EventEmitter.md +12 -12
  34. package/docs/{classes → api/classes}/EventServer.md +670 -209
  35. package/docs/{classes → api/classes}/EventToolFunc.md +561 -109
  36. package/docs/{classes → api/classes}/FStringPromptTemplate.md +94 -48
  37. package/docs/{classes → api/classes}/FewShotPromptTemplate.md +100 -52
  38. package/docs/{classes → api/classes}/GolangPromptTemplate.md +99 -53
  39. package/docs/api/classes/HttpClientToolTransport.md +324 -0
  40. package/docs/api/classes/HttpServerToolTransport.md +332 -0
  41. package/docs/{classes → api/classes}/IntSet.md +12 -12
  42. package/docs/{classes → api/classes}/LRUCache.md +26 -26
  43. package/docs/api/classes/NotFoundError.md +431 -0
  44. package/docs/api/classes/NotImplementationError.md +431 -0
  45. package/docs/{classes → api/classes}/PromptExampleSelector.md +9 -9
  46. package/docs/{classes → api/classes}/PromptTemplate.md +91 -47
  47. package/docs/api/classes/ReadableStreamError.md +451 -0
  48. package/docs/api/classes/ResClientTools.md +3365 -0
  49. package/docs/api/classes/ResServerTools.md +3342 -0
  50. package/docs/api/classes/RpcMethodsClientTool.md +3275 -0
  51. package/docs/api/classes/RpcMethodsServerTool.md +3224 -0
  52. package/docs/api/classes/SSEChannel.md +272 -0
  53. package/docs/{classes → api/classes}/Semaphore.md +26 -26
  54. package/docs/api/classes/ServerToolTransport.md +323 -0
  55. package/docs/{classes → api/classes}/ServerTools.md +583 -120
  56. package/docs/{classes → api/classes}/SignalGate.md +9 -9
  57. package/docs/api/classes/SseClientPubSubTransport.md +92 -0
  58. package/docs/api/classes/SseServerPubSubTransport.md +234 -0
  59. package/docs/{classes → api/classes}/TaskAbortController.md +9 -9
  60. package/docs/api/classes/ToolFunc.md +2665 -0
  61. package/docs/api/classes/ToolTransport.md +143 -0
  62. package/docs/api/classes/YamlTypeBaseObject.md +31 -0
  63. package/docs/api/enumerations/AsyncFeatureBits.md +33 -0
  64. package/docs/api/enumerations/AsyncFeatures.md +33 -0
  65. package/docs/api/enumerations/ErrorCode.md +177 -0
  66. package/docs/api/enumerations/HashAlgorithm.md +97 -0
  67. package/docs/{functions → api/functions}/AIArgProcessor.md +1 -1
  68. package/docs/{functions → api/functions}/AIStream.md +1 -1
  69. package/docs/{functions → api/functions}/ChoiceArgProcessor.md +1 -1
  70. package/docs/api/functions/DefaultDateFormat.md +21 -0
  71. package/docs/{functions → api/functions}/ObjectArgsToArgsInfo.md +1 -1
  72. package/docs/{functions → api/functions}/RateLimit.md +1 -1
  73. package/docs/{functions → api/functions}/TemplateArgProcessor.md +1 -1
  74. package/docs/api/functions/addDate.md +71 -0
  75. package/docs/{functions → api/functions}/assignDirs.md +1 -1
  76. package/docs/{functions → api/functions}/backendEventable.md +1 -1
  77. package/docs/{functions → api/functions}/beforeShutdown.md +1 -1
  78. package/docs/api/functions/calcPerplexity.md +60 -0
  79. package/docs/api/functions/calcPerplexitySimple.md +42 -0
  80. package/docs/api/functions/canonicalize.md +33 -0
  81. package/docs/{functions → api/functions}/completeSentences.md +1 -1
  82. package/docs/{functions → api/functions}/concatText.md +1 -1
  83. package/docs/{functions → api/functions}/countLLMTokens.md +1 -1
  84. package/docs/{functions → api/functions}/countRegexMatches.md +1 -1
  85. package/docs/{functions → api/functions}/createAbilityInjector.md +4 -4
  86. package/docs/{functions → api/functions}/createCallbacksTransformer.md +1 -1
  87. package/docs/{functions → api/functions}/createEmptyReadableStream.md +1 -1
  88. package/docs/{functions → api/functions}/createEndWithRepetitionDetector.md +1 -1
  89. package/docs/{functions → api/functions}/createError.md +1 -1
  90. package/docs/{functions → api/functions}/createEventStreamTransformer.md +1 -1
  91. package/docs/{functions → api/functions}/createHfValueFunc.md +1 -1
  92. package/docs/{functions → api/functions}/createLRUCache.md +1 -1
  93. package/docs/{functions → api/functions}/createYamlObjectTag.md +1 -1
  94. package/docs/{functions → api/functions}/dateToText.md +1 -1
  95. package/docs/{functions → api/functions}/decodeCharset.md +1 -1
  96. package/docs/api/functions/defaultsWithConcat.md +74 -0
  97. package/docs/{functions → api/functions}/detectCharset.md +1 -1
  98. package/docs/{functions → api/functions}/encodeLLMTokens.md +1 -1
  99. package/docs/{functions → api/functions}/ensureQuoted.md +1 -1
  100. package/docs/{functions → api/functions}/eventable.md +1 -1
  101. package/docs/{functions → api/functions}/expandConfig.md +1 -1
  102. package/docs/{functions → api/functions}/expandEnv.md +1 -1
  103. package/docs/{functions → api/functions}/expandObjEnv.md +1 -1
  104. package/docs/{functions → api/functions}/expandPath.md +1 -1
  105. package/docs/api/functions/expandPathInObject.md +29 -0
  106. package/docs/api/functions/expandPaths.md +25 -0
  107. package/docs/{functions → api/functions}/extNameLevel.md +1 -1
  108. package/docs/{functions → api/functions}/fileIsExists.md +1 -1
  109. package/docs/{functions → api/functions}/filterValidFnScope.md +1 -1
  110. package/docs/{functions → api/functions}/findIndexNonEmptyFrom.md +1 -1
  111. package/docs/{functions → api/functions}/findPort.md +1 -1
  112. package/docs/{functions → api/functions}/formatISO.md +1 -1
  113. package/docs/{functions → api/functions}/formatTextWithSpace.md +1 -1
  114. package/docs/api/functions/funcGetMeta.md +27 -0
  115. package/docs/api/functions/funcWithMeta.md +41 -0
  116. package/docs/api/functions/genUrlParamsStr.md +27 -0
  117. package/docs/{functions → api/functions}/getAllEnumKeys.md +1 -1
  118. package/docs/{functions → api/functions}/getConfigFileNames.md +1 -1
  119. package/docs/{functions → api/functions}/getConfigs.md +1 -1
  120. package/docs/{functions → api/functions}/getEnvVairables.md +1 -1
  121. package/docs/{functions → api/functions}/getFileMetaInfo.md +1 -1
  122. package/docs/{functions → api/functions}/getHashAlgoBySize.md +1 -1
  123. package/docs/{functions → api/functions}/getKeysPath.md +1 -1
  124. package/docs/{functions → api/functions}/getLLMTokenizer.md +1 -1
  125. package/docs/{functions → api/functions}/getMultiLevelExtname.md +1 -1
  126. package/docs/{functions → api/functions}/getPackageDir.md +1 -1
  127. package/docs/{functions → api/functions}/getRealFilepath.md +1 -1
  128. package/docs/{functions → api/functions}/getResponseErrorReadableStream.md +1 -1
  129. package/docs/{functions → api/functions}/getXDGConfigs.md +1 -1
  130. package/docs/{functions → api/functions}/hasDirectoryIn.md +1 -1
  131. package/docs/{functions → api/functions}/hash.md +1 -1
  132. package/docs/{functions → api/functions}/hashFile.md +1 -1
  133. package/docs/api/functions/hashObject.md +25 -0
  134. package/docs/{functions → api/functions}/hashStream.md +1 -1
  135. package/docs/api/functions/initShutdown.md +15 -0
  136. package/docs/{functions → api/functions}/isLangUsingSpaces.md +1 -1
  137. package/docs/{functions → api/functions}/isListItemString.md +1 -1
  138. package/docs/{functions → api/functions}/isModelNameMatched.md +1 -1
  139. package/docs/{functions → api/functions}/isPunctuationChar.md +1 -1
  140. package/docs/{functions → api/functions}/isQuoted.md +1 -1
  141. package/docs/{functions → api/functions}/isRegExp.md +1 -1
  142. package/docs/{functions → api/functions}/isSameString.md +1 -1
  143. package/docs/{functions → api/functions}/isSectionString.md +1 -1
  144. package/docs/{functions → api/functions}/isSentenceEnding.md +1 -1
  145. package/docs/{functions → api/functions}/isSepLineString.md +1 -1
  146. package/docs/{functions → api/functions}/isStrWrapped.md +1 -1
  147. package/docs/{functions → api/functions}/isSubdirectory.md +2 -2
  148. package/docs/{functions → api/functions}/isTitleString.md +1 -1
  149. package/docs/{functions → api/functions}/isValidFilename.md +1 -1
  150. package/docs/{functions → api/functions}/isValidFilepath.md +1 -1
  151. package/docs/{functions → api/functions}/isWebStream.md +1 -1
  152. package/docs/api/functions/joinSplitWords.md +46 -0
  153. package/docs/{functions → api/functions}/jsonFilterToWhere.md +1 -1
  154. package/docs/{functions → api/functions}/jsonToMarkdownStr.md +9 -1
  155. package/docs/{functions → api/functions}/loadAIConfig.md +1 -1
  156. package/docs/{functions → api/functions}/loadConfig.md +1 -1
  157. package/docs/{functions → api/functions}/loadConfigFile.md +1 -1
  158. package/docs/{functions → api/functions}/loadFileFromPaths.md +1 -1
  159. package/docs/{functions → api/functions}/loadTextFromPaths.md +1 -1
  160. package/docs/{functions → api/functions}/lrucache.md +1 -1
  161. package/docs/{functions → api/functions}/makeToolFuncCancelable.md +1 -1
  162. package/docs/{functions → api/functions}/matchUrlProtocol.md +1 -1
  163. package/docs/{functions → api/functions}/memoize.md +1 -1
  164. package/docs/api/functions/mergeArray.md +57 -0
  165. package/docs/{functions → api/functions}/messagesToText.md +1 -1
  166. package/docs/api/functions/normalizePath.md +21 -0
  167. package/docs/{functions → api/functions}/paramsSizeToScaleStr.md +1 -1
  168. package/docs/{functions → api/functions}/parseCommand.md +1 -1
  169. package/docs/{functions → api/functions}/parseDateFormat.md +1 -1
  170. package/docs/{functions → api/functions}/parseISO.md +1 -1
  171. package/docs/{functions → api/functions}/parseJsJson.md +1 -1
  172. package/docs/{functions → api/functions}/parseJsJsonSimpleSync.md +1 -1
  173. package/docs/{functions → api/functions}/parseObjectArgInfo.md +1 -1
  174. package/docs/{functions → api/functions}/parseObjectArgumentInfos.md +1 -1
  175. package/docs/{functions → api/functions}/parseObjectArguments.md +1 -1
  176. package/docs/{functions → api/functions}/parseObjectArgumentsAsArgInfos.md +1 -1
  177. package/docs/{functions → api/functions}/parseYaml.md +1 -1
  178. package/docs/api/functions/pruneSubdirectories.md +35 -0
  179. package/docs/api/functions/pruneSubdirectoriesInPlace.md +38 -0
  180. package/docs/{functions → api/functions}/quoteStr.md +1 -1
  181. package/docs/{functions → api/functions}/readFilenamesRecursiveSync.md +1 -1
  182. package/docs/{functions → api/functions}/readTextFileChunks.md +1 -1
  183. package/docs/{functions → api/functions}/readTextFileChunksEx.md +1 -1
  184. package/docs/{functions → api/functions}/readableFromAsyncIterable.md +1 -1
  185. package/docs/{functions → api/functions}/registerCoreTools.md +1 -1
  186. package/docs/{functions → api/functions}/registerYamlTag.md +1 -1
  187. package/docs/{functions → api/functions}/removeMarkdownBold.md +1 -1
  188. package/docs/{functions → api/functions}/removeMarkdownBoldAndItalic.md +1 -1
  189. package/docs/{functions → api/functions}/removeMarkdownItalic.md +1 -1
  190. package/docs/{functions → api/functions}/replaceWithPlaceholder.md +1 -1
  191. package/docs/{functions → api/functions}/restoreFromPlacehoders.md +1 -1
  192. package/docs/{functions → api/functions}/sanitizeFilename.md +1 -1
  193. package/docs/{functions → api/functions}/sanitizeFilepath.md +1 -1
  194. package/docs/{functions → api/functions}/saveConfigFile.md +1 -1
  195. package/docs/{functions → api/functions}/scaleStrToParamsSize.md +1 -1
  196. package/docs/{functions → api/functions}/shutdown.md +1 -1
  197. package/docs/{functions → api/functions}/simplifyObjectArguments.md +1 -1
  198. package/docs/api/functions/sleep.md +36 -0
  199. package/docs/{functions → api/functions}/sortedValues.md +1 -1
  200. package/docs/{functions → api/functions}/splitChunks.md +1 -1
  201. package/docs/{functions → api/functions}/splitParagraph.md +1 -1
  202. package/docs/{functions → api/functions}/splitSentence.md +1 -1
  203. package/docs/api/functions/splitWords.md +42 -0
  204. package/docs/{functions → api/functions}/stringifyYaml.md +1 -1
  205. package/docs/{functions → api/functions}/stripConsoleColor.md +1 -1
  206. package/docs/{functions → api/functions}/textToDate.md +1 -1
  207. package/docs/{functions → api/functions}/throwError.md +3 -3
  208. package/docs/{functions → api/functions}/toDate.md +1 -1
  209. package/docs/{functions → api/functions}/toDateTime.md +1 -1
  210. package/docs/{functions → api/functions}/toRegExp.md +1 -1
  211. package/docs/{functions → api/functions}/trimStartOfStreamHelper.md +1 -1
  212. package/docs/{functions → api/functions}/truncTo.md +1 -1
  213. package/docs/{functions → api/functions}/truncateByToken.md +1 -1
  214. package/docs/{functions → api/functions}/truncateToTokenLimit.md +1 -1
  215. package/docs/{functions → api/functions}/truncateToTokenLimitEx.md +1 -1
  216. package/docs/{functions → api/functions}/uuid.md +1 -1
  217. package/docs/{functions → api/functions}/uuidParse.md +1 -1
  218. package/docs/{functions → api/functions}/uuidStringify.md +1 -1
  219. package/docs/{functions → api/functions}/uuidValidate.md +1 -1
  220. package/docs/{functions → api/functions}/uuidVersion.md +1 -1
  221. package/docs/{functions → api/functions}/uuidv1.md +9 -5
  222. package/docs/{functions → api/functions}/uuidv4.md +9 -5
  223. package/docs/{functions → api/functions}/uuidv5.md +9 -5
  224. package/docs/api/functions/wait.md +45 -0
  225. package/docs/{functions → api/functions}/wrapEventEmitter.md +1 -1
  226. package/docs/{functions → api/functions}/xxhash.md +1 -1
  227. package/docs/{functions → api/functions}/xxhash32.md +1 -1
  228. package/docs/{functions → api/functions}/xxhash64.md +1 -1
  229. package/docs/{functions → api/functions}/xxhashAsStr.md +1 -1
  230. package/docs/api/functions/yieldExec.md +27 -0
  231. package/docs/{globals.md → api/globals.md} +50 -1
  232. package/docs/api/interfaces/AIChatAssistantMessageParam.md +129 -0
  233. package/docs/api/interfaces/AIChatContentPartImage.md +29 -0
  234. package/docs/api/interfaces/AIChatContentPartText.md +25 -0
  235. package/docs/api/interfaces/AIChatMessageParamBase.md +68 -0
  236. package/docs/api/interfaces/AIChatMessageToolCall.md +41 -0
  237. package/docs/{interfaces → api/interfaces}/AIChatSystemMessageParam.md +9 -9
  238. package/docs/api/interfaces/AIChatToolChoiceFuncObject.md +37 -0
  239. package/docs/api/interfaces/AIChatToolChoiceObject.md +25 -0
  240. package/docs/api/interfaces/AIChatToolFunc.md +41 -0
  241. package/docs/api/interfaces/AIChatToolFuncParam.md +37 -0
  242. package/docs/api/interfaces/AIChatToolMessageParam.md +113 -0
  243. package/docs/api/interfaces/AIChatToolParam.md +25 -0
  244. package/docs/api/interfaces/AIChatToolTypeObject.md +17 -0
  245. package/docs/api/interfaces/AIChatUserMessageParam.md +137 -0
  246. package/docs/api/interfaces/AIChoiceConfig.md +65 -0
  247. package/docs/api/interfaces/AIResult.md +65 -0
  248. package/docs/{interfaces → api/interfaces}/AIStreamParser.md +2 -2
  249. package/docs/api/interfaces/AIStreamParserOptions.md +21 -0
  250. package/docs/api/interfaces/BaseFunc.md +299 -0
  251. package/docs/api/interfaces/BaseFuncItem.md +221 -0
  252. package/docs/api/interfaces/BinarySemaphoreAcquireOptions.md +25 -0
  253. package/docs/api/interfaces/BinarySemaphoreOptions.md +57 -0
  254. package/docs/api/interfaces/BinarySemaphoreReleaseOptions.md +25 -0
  255. package/docs/api/interfaces/BinarySemaphoreReleaserFunc.md +37 -0
  256. package/docs/api/interfaces/CancelableAbilityOptions.md +113 -0
  257. package/docs/api/interfaces/ClientFuncItem.md +326 -0
  258. package/docs/api/interfaces/EventClientFuncParams.md +51 -0
  259. package/docs/api/interfaces/EventServerFuncParams.md +73 -0
  260. package/docs/{interfaces → api/interfaces}/FewShotPromptTemplateOptions.md +24 -12
  261. package/docs/api/interfaces/FuncItem.md +281 -0
  262. package/docs/api/interfaces/FuncParam.md +51 -0
  263. package/docs/api/interfaces/FuncParams.md +28 -0
  264. package/docs/api/interfaces/Funcs.md +15 -0
  265. package/docs/api/interfaces/HashAlgoParams.md +33 -0
  266. package/docs/api/interfaces/IClientToolTransport.md +155 -0
  267. package/docs/api/interfaces/IFileMetaInfo.md +65 -0
  268. package/docs/api/interfaces/IPubSubClientTransport.md +70 -0
  269. package/docs/api/interfaces/IPubSubServerTransport.md +241 -0
  270. package/docs/api/interfaces/IReadTextFileChunksOptions.md +143 -0
  271. package/docs/api/interfaces/IServerToolTransport.md +159 -0
  272. package/docs/api/interfaces/IToolTransport.md +73 -0
  273. package/docs/api/interfaces/ITruncateToTokenLimitOptions.md +99 -0
  274. package/docs/api/interfaces/JsonFilter.md +13 -0
  275. package/docs/api/interfaces/ParseObjectArgumentOptions.md +89 -0
  276. package/docs/api/interfaces/ProbabilityItem.md +41 -0
  277. package/docs/api/interfaces/PromptExampleSelectorOptions.md +34 -0
  278. package/docs/{interfaces → api/interfaces}/PromptTemplateOptions.md +15 -7
  279. package/docs/api/interfaces/PubSubClient.md +27 -0
  280. package/docs/api/interfaces/PubSubClientStream.md +196 -0
  281. package/docs/api/interfaces/PubSubServerSession.md +103 -0
  282. package/docs/api/interfaces/RemoteFuncItem.md +316 -0
  283. package/docs/api/interfaces/ReplacePlacehoderOptions.md +41 -0
  284. package/docs/api/interfaces/ResClientFuncParams.md +37 -0
  285. package/docs/api/interfaces/ResServerFuncParams.md +77 -0
  286. package/docs/api/interfaces/RpcMethodsClientFuncParams.md +25 -0
  287. package/docs/api/interfaces/RpcMethodsServerFuncParams.md +61 -0
  288. package/docs/api/interfaces/SanitizeFilenameOptions.md +25 -0
  289. package/docs/api/interfaces/SectionStringOptions.md +25 -0
  290. package/docs/api/interfaces/SemaphoreOptions.md +89 -0
  291. package/docs/api/interfaces/SemaphoreTaskItem.md +73 -0
  292. package/docs/api/interfaces/ServerFuncItem.md +339 -0
  293. package/docs/api/interfaces/ServerFuncParams.md +42 -0
  294. package/docs/api/interfaces/SplitSentenceOptions.md +41 -0
  295. package/docs/{interfaces → api/interfaces}/StreamCallbacksAndOptions.md +5 -5
  296. package/docs/{interfaces → api/interfaces}/TaskAbortControllers.md +1 -1
  297. package/docs/{interfaces → api/interfaces}/TaskPromise.md +6 -6
  298. package/docs/api/interfaces/ToolFuncPackage.md +57 -0
  299. package/docs/{namespaces → api/namespaces}/EventStates/variables/ABORT.md +1 -1
  300. package/docs/{namespaces → api/namespaces}/EventStates/variables/CONTINUE.md +1 -1
  301. package/docs/{namespaces → api/namespaces}/EventStates/variables/DONE.md +1 -1
  302. package/docs/{namespaces → api/namespaces}/EventStates/variables/STOPPED.md +1 -1
  303. package/docs/{namespaces → api/namespaces}/uuidv5/variables/DNS.md +1 -1
  304. package/docs/{namespaces → api/namespaces}/uuidv5/variables/URL.md +1 -1
  305. package/docs/{type-aliases → api/type-aliases}/AIChatContentPart.md +1 -1
  306. package/docs/{type-aliases → api/type-aliases}/AIChatMessageParam.md +1 -1
  307. package/docs/{type-aliases → api/type-aliases}/AIChatRole.md +1 -1
  308. package/docs/{type-aliases → api/type-aliases}/AIChatToolChoiceParam.md +1 -1
  309. package/docs/{type-aliases → api/type-aliases}/AIMessageType.md +1 -1
  310. package/docs/api/type-aliases/AIModelNameRule.md +14 -0
  311. package/docs/api/type-aliases/AIModelNameRuleFn.md +28 -0
  312. package/docs/api/type-aliases/AIModelNameRules.md +13 -0
  313. package/docs/{type-aliases → api/type-aliases}/AITextGenerationFinishReason.md +1 -1
  314. package/docs/api/type-aliases/ActionName.md +13 -0
  315. package/docs/api/type-aliases/ArrayMergeWay.md +11 -0
  316. package/docs/api/type-aliases/AsyncTaskId.md +11 -0
  317. package/docs/{type-aliases → api/type-aliases}/BeforeShutdownListener.md +1 -1
  318. package/docs/{type-aliases → api/type-aliases}/EventErrorListenerFn.md +1 -1
  319. package/docs/{type-aliases → api/type-aliases}/EventListenerFn.md +1 -1
  320. package/docs/api/type-aliases/FuncParamType.md +13 -0
  321. package/docs/{type-aliases → api/type-aliases}/PromptExamples.md +1 -1
  322. package/docs/api/type-aliases/PubSubClientId.md +14 -0
  323. package/docs/api/type-aliases/PubSubCtx.md +37 -0
  324. package/docs/api/type-aliases/RpcMethodHandler.md +34 -0
  325. package/docs/{type-aliases → api/type-aliases}/SemaphoreIsReadyFuncType.md +1 -1
  326. package/docs/api/type-aliases/TFunc.md +33 -0
  327. package/docs/{variables → api/variables}/AIChatRoles.md +1 -1
  328. package/docs/{variables → api/variables}/AIMessageTypes.md +1 -1
  329. package/docs/{variables → api/variables}/AITextGenerationFinishReasons.md +1 -1
  330. package/docs/{variables → api/variables}/AbortErrorCode.md +1 -1
  331. package/docs/api/variables/ActionNames.md +13 -0
  332. package/docs/{variables → api/variables}/AlreadyExistsErrorCode.md +1 -1
  333. package/docs/api/variables/ArrayMergeWay.md +25 -0
  334. package/docs/api/variables/ArrayMergeWaySymbol.md +11 -0
  335. package/docs/api/variables/ClientToolFuncSchema.md +83 -0
  336. package/docs/{variables → api/variables}/DEFAULT_CONFIG_NAME.md +1 -1
  337. package/docs/{variables → api/variables}/DefaultAsyncSemaphoreCapacity.md +1 -1
  338. package/docs/api/variables/EventBusName.md +11 -0
  339. package/docs/api/variables/EventName.md +11 -0
  340. package/docs/{variables → api/variables}/FilenameReservedRegex.md +1 -1
  341. package/docs/api/variables/FuncMetaSymbol.md +15 -0
  342. package/docs/{variables → api/variables}/InternalErrorCode.md +1 -1
  343. package/docs/{variables → api/variables}/LLM_TOKENIZER_NAMES.md +1 -1
  344. package/docs/{variables → api/variables}/LLM_TOKENIZER_NAMES_MAP.md +1 -1
  345. package/docs/{variables → api/variables}/NotFoundErrorCode.md +1 -1
  346. package/docs/{variables → api/variables}/NotImplementedErrorCode.md +1 -1
  347. package/docs/api/variables/PASSING_SCORE.md +13 -0
  348. package/docs/api/variables/RStreamErrCode.md +11 -0
  349. package/docs/api/variables/RemoteToolFuncSchema.md +84 -0
  350. package/docs/api/variables/ResponseRStreamErrCode.md +11 -0
  351. package/docs/api/variables/RpcMethodsClientToolSchema.md +49 -0
  352. package/docs/api/variables/RpcMethodsServerToolSchema.md +21 -0
  353. package/docs/{variables → api/variables}/SHUTDOWN_SIGNALS.md +1 -1
  354. package/docs/{variables → api/variables}/SSEChannelAlreadyClosedErrCode.md +1 -1
  355. package/docs/api/variables/SecondaryCache.md +11 -0
  356. package/docs/api/variables/ServerToolFuncSchema.md +83 -0
  357. package/docs/api/variables/StrangeHumanName.md +11 -0
  358. package/docs/api/variables/ToolAsyncCancelableBit.md +11 -0
  359. package/docs/api/variables/ToolAsyncMultiTaskBit.md +11 -0
  360. package/docs/api/variables/ToolAsyncPriorityBit.md +11 -0
  361. package/docs/{variables → api/variables}/ToolFuncSchema.md +14 -1
  362. package/docs/{variables → api/variables}/WindowsReservedNameRegex.md +1 -1
  363. package/docs/api/variables/base32768.md +11 -0
  364. package/docs/{variables → api/variables}/defaultTemplateFormat.md +1 -1
  365. package/docs/api/variables/event.md +11 -0
  366. package/docs/api/variables/eventClient.md +11 -0
  367. package/docs/api/variables/eventServer.md +11 -0
  368. package/docs/api/variables/lrucache.md +11 -0
  369. package/docs/{variables → api/variables}/mimeType.md +1 -1
  370. package/docs/{variables → api/variables}/uuidNIL.md +1 -1
  371. package/docs/pubsub.md +326 -0
  372. package/docs/server_client_tools.md +88 -0
  373. package/docs/toolFunc.md +183 -0
  374. package/docs/transport.md +137 -0
  375. package/package.json +37 -39
  376. package/dist/chunk-OYDBRUZJ.mjs +0 -1
  377. package/dist/index-BkwhCK1q.d.mts +0 -899
  378. package/dist/index-BkwhCK1q.d.ts +0 -899
  379. package/docs/README.md +0 -250
  380. package/docs/classes/AlreadyExistsError.md +0 -346
  381. package/docs/classes/BaseError.md +0 -359
  382. package/docs/classes/NotFoundError.md +0 -346
  383. package/docs/classes/NotImplementationError.md +0 -346
  384. package/docs/classes/ReadableStreamError.md +0 -366
  385. package/docs/classes/ResClientTools.md +0 -2451
  386. package/docs/classes/ResServerTools.md +0 -2427
  387. package/docs/classes/SSEChannel.md +0 -270
  388. package/docs/classes/ToolFunc.md +0 -2201
  389. package/docs/classes/YamlTypeBaseObject.md +0 -31
  390. package/docs/enumerations/AsyncFeatureBits.md +0 -33
  391. package/docs/enumerations/AsyncFeatures.md +0 -33
  392. package/docs/enumerations/ErrorCode.md +0 -177
  393. package/docs/enumerations/HashAlgorithm.md +0 -97
  394. package/docs/functions/canonicalize.md +0 -21
  395. package/docs/functions/initShutdown.md +0 -15
  396. package/docs/functions/wait.md +0 -21
  397. package/docs/interfaces/AIChatAssistantMessageParam.md +0 -129
  398. package/docs/interfaces/AIChatContentPartImage.md +0 -29
  399. package/docs/interfaces/AIChatContentPartText.md +0 -25
  400. package/docs/interfaces/AIChatMessageParamBase.md +0 -68
  401. package/docs/interfaces/AIChatMessageToolCall.md +0 -41
  402. package/docs/interfaces/AIChatToolChoiceFuncObject.md +0 -37
  403. package/docs/interfaces/AIChatToolChoiceObject.md +0 -25
  404. package/docs/interfaces/AIChatToolFunc.md +0 -41
  405. package/docs/interfaces/AIChatToolFuncParam.md +0 -37
  406. package/docs/interfaces/AIChatToolMessageParam.md +0 -113
  407. package/docs/interfaces/AIChatToolParam.md +0 -25
  408. package/docs/interfaces/AIChatToolTypeObject.md +0 -17
  409. package/docs/interfaces/AIChatUserMessageParam.md +0 -137
  410. package/docs/interfaces/AIChoiceConfig.md +0 -65
  411. package/docs/interfaces/AIResult.md +0 -65
  412. package/docs/interfaces/AIStreamParserOptions.md +0 -21
  413. package/docs/interfaces/BaseFunc.md +0 -157
  414. package/docs/interfaces/BaseFuncItem.md +0 -101
  415. package/docs/interfaces/BinarySemaphoreAcquireOptions.md +0 -25
  416. package/docs/interfaces/BinarySemaphoreOptions.md +0 -57
  417. package/docs/interfaces/BinarySemaphoreReleaseOptions.md +0 -25
  418. package/docs/interfaces/BinarySemaphoreReleaserFunc.md +0 -37
  419. package/docs/interfaces/CancelableAbilityOptions.md +0 -113
  420. package/docs/interfaces/ClientFuncItem.md +0 -175
  421. package/docs/interfaces/EventClientFuncParams.md +0 -51
  422. package/docs/interfaces/EventServerFuncParams.md +0 -67
  423. package/docs/interfaces/FuncItem.md +0 -143
  424. package/docs/interfaces/FuncParam.md +0 -61
  425. package/docs/interfaces/FuncParams.md +0 -13
  426. package/docs/interfaces/Funcs.md +0 -13
  427. package/docs/interfaces/HashAlgoParams.md +0 -33
  428. package/docs/interfaces/IFileMetaInfo.md +0 -65
  429. package/docs/interfaces/IReadTextFileChunksOptions.md +0 -143
  430. package/docs/interfaces/ITruncateToTokenLimitOptions.md +0 -99
  431. package/docs/interfaces/JsonFilter.md +0 -13
  432. package/docs/interfaces/ParseObjectArgumentOptions.md +0 -89
  433. package/docs/interfaces/PromptExampleSelectorOptions.md +0 -34
  434. package/docs/interfaces/RemoteFuncItem.md +0 -164
  435. package/docs/interfaces/ReplacePlacehoderOptions.md +0 -41
  436. package/docs/interfaces/ResClientFuncParams.md +0 -37
  437. package/docs/interfaces/ResServerFuncParams.md +0 -69
  438. package/docs/interfaces/SanitizeFilenameOptions.md +0 -25
  439. package/docs/interfaces/SectionStringOptions.md +0 -25
  440. package/docs/interfaces/SemaphoreOptions.md +0 -89
  441. package/docs/interfaces/SemaphoreTaskItem.md +0 -73
  442. package/docs/interfaces/ServerFuncItem.md +0 -183
  443. package/docs/interfaces/ServerFuncParams.md +0 -35
  444. package/docs/interfaces/SplitSentenceOptions.md +0 -41
  445. package/docs/interfaces/ToolFuncPackage.md +0 -47
  446. package/docs/type-aliases/AIModelNameRule.md +0 -11
  447. package/docs/type-aliases/AIModelNameRuleFn.md +0 -21
  448. package/docs/type-aliases/AIModelNameRules.md +0 -11
  449. package/docs/type-aliases/ActionName.md +0 -11
  450. package/docs/type-aliases/AsyncTaskId.md +0 -11
  451. package/docs/type-aliases/FuncParamType.md +0 -11
  452. package/docs/type-aliases/TFunc.md +0 -25
  453. package/docs/variables/ActionNames.md +0 -11
  454. package/docs/variables/ClientToolFuncSchema.md +0 -101
  455. package/docs/variables/EventBusName.md +0 -11
  456. package/docs/variables/EventName.md +0 -11
  457. package/docs/variables/PASSING_SCORE.md +0 -11
  458. package/docs/variables/RStreamErrCode.md +0 -11
  459. package/docs/variables/RemoteToolFuncSchema.md +0 -101
  460. package/docs/variables/ResponseRStreamErrCode.md +0 -11
  461. package/docs/variables/SecondaryCache.md +0 -11
  462. package/docs/variables/ServerToolFuncSchema.md +0 -101
  463. package/docs/variables/ToolAsyncCancelableBit.md +0 -11
  464. package/docs/variables/ToolAsyncMultiTaskBit.md +0 -11
  465. package/docs/variables/ToolAsyncPriorityBit.md +0 -11
  466. package/docs/variables/base32768.md +0 -11
  467. package/docs/variables/event.md +0 -11
  468. package/docs/variables/eventClient.md +0 -11
  469. package/docs/variables/eventServer.md +0 -11
  470. package/docs/variables/lrucache.md +0 -11
  471. /package/docs/{_media → api/_media}/LICENSE-MIT +0 -0
  472. /package/docs/{namespaces → api/namespaces}/EventStates/README.md +0 -0
  473. /package/docs/{namespaces → api/namespaces}/uuidv5/README.md +0 -0
@@ -0,0 +1,165 @@
1
+ **@isdk/ai-tool**
2
+
3
+ ***
4
+
5
+ # @isdk/ai-tool
6
+
7
+ A powerful TypeScript framework for creating, managing, and communicating with modular functions. It's perfect for building AI agent tools, backend services, and extensible plugin systems with a clean, decoupled architecture.
8
+
9
+ ## Core Features
10
+
11
+ - **Modular & Inheritable Tools:** Define functions in a structured way with a clear class hierarchy (`ToolFunc` -> `ServerTools` -> `ResServerTools`).
12
+ - **Pluggable RPC Transport:** Decouple your business logic from the network layer. Communicate between client and server using HTTP, IPC, or any custom protocol.
13
+ - **Pluggable PubSub Transport:** Create real-time, bidirectional event buses for features like notifications and live updates. Implementations for SSE (Server-Sent Events) and Electron IPC are included.
14
+ - **Global Registry:** Easily access any registered function from anywhere in your application.
15
+
16
+ ## Installation
17
+
18
+ ```bash
19
+ npm install @isdk/ai-tool
20
+ ```
21
+
22
+ ## Core Architecture: Tool Inheritance
23
+
24
+ `@isdk/ai-tool` is built on a foundation of extensible classes. Understanding their hierarchy and design is key to using the library effectively.
25
+
26
+ ### Design Philosophy: Static vs. Instance
27
+
28
+ A key design principle in `ToolFunc` is the separation of roles between the static class and its instances:
29
+
30
+ - **The Static Class as Manager:** The static side of `ToolFunc` (e.g., `ToolFunc.register`, `ToolFunc.run`, `ToolFunc.get`) acts as a global **registry** and **executor**. It manages all tool definitions, allowing any part of your application to discover and run tools by name without needing a direct reference to the tool's instance.
31
+
32
+ - **The Instance as the Tool:** An instance (`new ToolFunc(...)`) represents a single, concrete **tool**. It holds the actual function logic, all its metadata (name, description, parameters), and any internal state.
33
+
34
+ This separation provides the best of both worlds: the power of object-oriented encapsulation for defining individual tools and the convenience of a globally accessible service for managing and executing them.
35
+
36
+ ### Tool Inheritance Hierarchy
37
+
38
+ The library follows a clear inheritance path, adding specialized features at each level. For a detailed breakdown of each type and how they separate business logic from communication, see the [**Guide to Server & Client Tools**](_media/server_client_tools.md).
39
+
40
+ **Server-Side Inheritance:**
41
+ `ToolFunc` -> `ServerTools` -> `RpcMethodsServerTool` -> `ResServerTools`
42
+
43
+ - **`ToolFunc`**: The base for any function, containing core logic and metadata. For more details, see the [ToolFunc Guide](_media/toolFunc.md).
44
+ - **`ServerTools`**: Extends `ToolFunc` to be discoverable and callable by remote clients.
45
+ - **`RpcMethodsServerTool`**: Extends `ServerTools` to allow a single tool to expose multiple methods (e.g., a `Math` tool with `add` and `subtract` methods).
46
+ - **`ResServerTools`**: Extends `RpcMethodsServerTool` to automatically provide a resource-oriented (CRUD) interface.
47
+
48
+ **Client-Side Inheritance:**
49
+ A parallel hierarchy exists for the client, designed to seamlessly call the server-side tools.
50
+ `ToolFunc` -> `ClientTools` -> `RpcMethodsClientTool` -> `ResClientTools`
51
+
52
+ ## Client-Server RPC with Transports
53
+
54
+ The framework shines in a client-server setup, allowing you to call backend functions as if they were local.
55
+
56
+ ### Server-Side Example
57
+
58
+ Use `ServerTools` to define a backend function and `FastifyServerToolTransport` to expose it over HTTP.
59
+
60
+ ```typescript
61
+ // server.ts
62
+ import { ServerTools, FastifyServerToolTransport } from '@isdk/ai-tool';
63
+
64
+ // Define a tool that can be called remotely
65
+ ServerTools.register({
66
+ name: 'getUserProfile',
67
+ params: { id: { type: 'string' } },
68
+ func: async ({ id }: { id: string }) => {
69
+ return { id, name: 'Jane Doe', email: 'jane.doe@example.com' };
70
+ },
71
+ });
72
+
73
+ // Create a transport and mount the tools under the '/api' prefix
74
+ const serverTransport = new FastifyServerToolTransport();
75
+ serverTransport.mount(ServerTools, '/api');
76
+
77
+ // Start the server
78
+ serverTransport.start({ port: 3000 });
79
+ ```
80
+
81
+ ### Client-Side Example
82
+
83
+ The `mount` method handles both setting the transport and loading tool definitions from the server in one step.
84
+
85
+ ```typescript
86
+ // client.ts
87
+ import { ClientTools, HttpClientToolTransport } from '@isdk/ai-tool';
88
+
89
+ async function main() {
90
+ const apiRoot = 'http://localhost:3000/api';
91
+
92
+ // 1. Setup the client transport and mount the tools
93
+ const clientTransport = new HttpClientToolTransport(apiRoot);
94
+ await clientTransport.mount(ClientTools);
95
+
96
+ // 2. Get the remote tool and run it
97
+ const getUserProfile = ClientTools.get('getUserProfile');
98
+ const profile = await getUserProfile.run({ id: '123' });
99
+
100
+ console.log(profile);
101
+ }
102
+ main();
103
+ ```
104
+
105
+ > For a deeper dive into how transports work, see the [Transport Layer Guide](_media/transport.md).
106
+
107
+ ## Real-Time Events with PubSub
108
+
109
+ `@isdk/ai-tool` includes a powerful event system for real-time communication, built on a pluggable PubSub transport layer.
110
+
111
+ ### Quick Example: SSE (Server-Sent Events)
112
+
113
+ **Server-Side:**
114
+ ```typescript
115
+ // server.ts (additions)
116
+ import { EventServer, SseServerPubSubTransport, eventServer } from '@isdk/ai-tool';
117
+
118
+ // Set the PubSub transport for the EventServer
119
+ EventServer.setPubSubTransport(new SseServerPubSubTransport());
120
+ eventServer.register(); // Register the default event tool
121
+
122
+ // Now you can publish events from anywhere in your backend
123
+ setInterval(() => {
124
+ EventServer.publish('server-time', { time: new Date().toISOString() });
125
+ }, 2000);
126
+ ```
127
+
128
+ **Client-Side:**
129
+ ```typescript
130
+ // client.ts (additions)
131
+ import { EventClient, SseClientPubSubTransport, eventClient, backendEventable } from '@isdk/ai-tool';
132
+
133
+ // Set the PubSub transport for the EventClient
134
+ EventClient.setPubSubTransport(new SseClientPubSubTransport());
135
+
136
+ // Make the client event-aware and register it
137
+ backendEventable(EventClient);
138
+ eventClient.setApiRoot('http://localhost:3000/api'); // Your API root
139
+ eventClient.register();
140
+
141
+ // Subscribe to and listen for server events
142
+ await eventClient.subscribe('server-time');
143
+ eventClient.on('server-time', (data) => {
144
+ console.log('Live time from server:', data.time);
145
+ });
146
+ ```
147
+
148
+ > For more detailed examples, including the Electron IPC transport, see the [**Real-time Events (PubSub) Guide**](_media/pubsub.md).
149
+
150
+ ## Contribution
151
+
152
+ If you would like to contribute to the project, please read the [CONTRIBUTING.md](_media/CONTRIBUTING.md) file for guidelines on how to get started.
153
+
154
+ ## License
155
+
156
+ The project is licensed under the MIT License. See the [LICENSE-MIT](_media/LICENSE-MIT) file for more details.
157
+
158
+ ## Credit
159
+
160
+ This project is inspired by and uses code from several excellent open-source projects:
161
+
162
+ * [@huggingface/jinja](https://github.com/huggingface/huggingface.js)
163
+ * [eventsource-parser](https://github.com/rexxars/eventsource-parser)
164
+ * [async-sema](https://github.com/vercel/async-sema)
165
+ * [modelfusion](https://github.com/vercel/modelfusion)
@@ -5,7 +5,7 @@ Please feel free to file GitHub Issues or propose Pull Requests. We're always ha
5
5
  ## Testing
6
6
 
7
7
  ```shell
8
- npm test
8
+ pnpm test
9
9
  ```
10
10
 
11
11
  ## Releasing
@@ -13,6 +13,6 @@ npm test
13
13
  Releases are supposed to be done from master, version bumping is automated through [`standard-version`](https://github.com/absolute-version/commit-and-tag-version):
14
14
 
15
15
  ```shell
16
- npm run release -- --dry-run # verify output manually
17
- npm run release # follow the instructions from the output of this command
16
+ pnpm run release -- --dry-run # verify output manually
17
+ pnpm run release # follow the instructions from the output of this command
18
18
  ```
@@ -0,0 +1,326 @@
1
+ # Developer's Guide: Real-time Events with EventServer & EventClient
2
+
3
+ This guide provides a comprehensive overview of the `EventServer` and `EventClient` tools, a powerful system for real-time, bidirectional communication. It is built on a **pluggable PubSub transport layer**, making it independent of the underlying communication protocol. You can use Server-Sent Events (SSE), WebSockets, IPC, or any other protocol by providing a corresponding transport implementation.
4
+
5
+ **Prerequisite:** This document assumes you understand the base transport layer. If not, please review the [`transport_readme.md`](./transport_readme.md) first.
6
+
7
+ ## Core Concept: The Unified Event Bus
8
+
9
+ The primary goal of this system is to create a seamless event bus that spans both the server and the client. It uses an abstract, pluggable PubSub transport for server-to-client messages and standard RPC calls for client-to-server messages.
10
+
11
+ The key feature is the ability to **"forward"** events. You can configure the server to automatically listen for events on its internal, global `eventBus` and relay them to clients. Likewise, you can configure the client to forward its local events to the server. This creates a powerful, decoupled architecture where different parts of your application can communicate without direct dependencies.
12
+
13
+ ### Aspect-Oriented Programming (AoP) and Event Emitters
14
+
15
+ A crucial concept is that `EventClient` (and `ClientTools` in general) can be enhanced with event emitter capabilities. By using a library like `events-ex`, you can give your client-side tool instances standard `on`, `off`, and `emit` methods. This allows `EventClient` to act as a local event bus that is transparently synchronized with the server.
16
+
17
+ ## Example 1: HTTP and Server-Sent Events (SSE)
18
+
19
+ ### Architecture (SSE)
20
+
21
+ The following diagram illustrates how the components interact when using the provided SSE-based transport. Other transports (like WebSockets or IPC) would follow a similar pattern.
22
+
23
+ ```mermaid
24
+ graph TD
25
+ subgraph Client-Side
26
+ C_App[Client Application]
27
+ C_EventBus(Local Event Emitter)
28
+ EC[EventClient] -- "uses" --> C_PubSub[SseClientPubSubTransport]
29
+ C_Transport[HttpClientToolTransport]
30
+
31
+ C_App -- "emit/on" --> C_EventBus
32
+ EC -- "decorated with" --> C_EventBus
33
+ C_PubSub -- "HTTP GET (SSE)" --> S_PubSub
34
+ EC -- "RPC calls" --> C_Transport
35
+ end
36
+
37
+ subgraph Server-Side
38
+ S_Transport[FastifyServerToolTransport] -- "receives RPC" --> ES[EventServer]
39
+ ES -- "uses" --> S_PubSub[SseServerPubSubTransport]
40
+ S_PubSub -- "handles SSE connections" --> ES
41
+ ES -- "interacts with" --> S_EventBus[Global Server EventBus]
42
+ OtherServices[Other Server Logic] -- "emit/on" --> S_EventBus
43
+ end
44
+
45
+ subgraph "Network (HTTP)"
46
+ C_Transport -- "RPC: POST /api/event" --> S_Transport
47
+ end
48
+ ```
49
+
50
+ ### Server-Side Setup (SSE)
51
+
52
+ In your server setup, you must first tell `EventServer` which transport to use, then register the `eventServer` instance.
53
+
54
+ ```typescript
55
+ // In your server entry file (e.g., server.ts)
56
+ import {
57
+ eventServer,
58
+ FastifyServerToolTransport,
59
+ ResServerTools,
60
+ EventServer, // Import EventServer class
61
+ SseServerPubSubTransport // Import the SSE transport
62
+ } from '@isdk/ai-tool';
63
+
64
+ async function main() {
65
+ // **Crucial Step: Set the PubSub transport for the server**
66
+ EventServer.setPubSubTransport(new SseServerPubSubTransport());
67
+
68
+ // Register the eventServer tool instance
69
+ eventServer.register();
70
+
71
+ const serverTransport = new FastifyServerToolTransport();
72
+ // Mount the base class; the transport finds all registered tools
73
+ serverTransport.mount(ResServerTools, '/api');
74
+
75
+ // ... start server
76
+ await serverTransport.start({port: 3000})
77
+ }
78
+ ```
79
+
80
+ ### Client-Side Setup (SSE)
81
+
82
+ On the client, you must set the appropriate PubSub transport (matching the server's), enhance the `EventClient` with `EventEmitter` capabilities, and register the instance.
83
+
84
+ ```typescript
85
+ // In your client-side code
86
+ import {
87
+ backendEventable,
88
+ EventClient,
89
+ eventClient,
90
+ HttpClientToolTransport,
91
+ ResClientTools,
92
+ SseClientPubSubTransport // Import the SSE transport
93
+ } from '@isdk/ai-tool';
94
+
95
+ async function main() {
96
+ const apiRoot = 'http://localhost:3003/api';
97
+ const clientTransport = new HttpClientToolTransport(apiRoot);
98
+ await clientTransport.mount(ResClientTools);
99
+
100
+ // **Crucial Step 1: Set the PubSub transport for the client**
101
+ EventClient.setPubSubTransport(new SseClientPubSubTransport());
102
+
103
+ // **Crucial Step 2: Make the client eventable**
104
+ backendEventable(EventClient);
105
+ eventClient.register();
106
+
107
+ // Now you can use eventClient.on, .off, .emit
108
+ }
109
+ ```
110
+
111
+ ---
112
+
113
+ ## Example 2: Electron IPC Transport
114
+
115
+ This transport uses Electron's Inter-Process Communication (IPC) to create an event bus between the main process (server) and renderer processes (clients).
116
+
117
+ ### Server-Side Setup (Electron Main Process)
118
+
119
+ In your Electron main process, you instantiate an `ElectronServerPubSubTransport` with a unique namespace. This namespace acts like an `apiRoot` and ensures that different event buses don't conflict.
120
+
121
+ ```typescript
122
+ // In your Electron main process (e.g., main.ts)
123
+ import {
124
+ EventServer,
125
+ eventServer,
126
+ ElectronServerPubSubTransport,
127
+ } from '@isdk/ai-tool';
128
+
129
+ // 1. Define a unique namespace for this event bus
130
+ const electronApiRoot = '/electron/events';
131
+
132
+ // 2. Create a transport instance for this specific namespace
133
+ const electronTransport = new ElectronServerPubSubTransport(electronApiRoot);
134
+
135
+ // 3. Set the transport on the EventServer
136
+ // Note: This is a static property. For multiple, different event servers
137
+ // (e.g., one for SSE, one for Electron), you would create subclasses of EventServer
138
+ // to hold each static transport instance separately.
139
+ EventServer.setPubSubTransport(electronTransport);
140
+
141
+ // 4. Register the eventServer tool instance. It will now use the Electron transport.
142
+ eventServer.register();
143
+
144
+ // Now you can use the global eventBus to emit events, and the EventServer
145
+ // will forward them to any connected renderer process.
146
+ ```
147
+
148
+ ### Client-Side Setup (Electron Renderer Process)
149
+
150
+ In the renderer process, you must use the same namespace (`apiRoot`) to connect to the correct event bus in the main process.
151
+
152
+ **Important:** The `EventClient` still relies on an RPC mechanism for actions like `subscribe` and `unsubscribe`. You must have a corresponding RPC transport set up between the renderer and main process for the full functionality to work. The example below focuses only on setting up the PubSub portion.
153
+
154
+ ```typescript
155
+ // In your Electron renderer process (e.g., preload.ts or renderer.ts)
156
+ import {
157
+ EventClient,
158
+ eventClient,
159
+ ElectronClientPubSubTransport,
160
+ backendEventable,
161
+ } from '@isdk/ai-tool';
162
+
163
+ // 1. The apiRoot MUST match the namespace used in the main process
164
+ const electronApiRoot = '/electron/events';
165
+
166
+ // 2. Set the PubSub transport on the EventClient class
167
+ EventClient.setPubSubTransport(new ElectronClientPubSubTransport());
168
+
169
+ // 3. Make the EventClient class event-aware
170
+ backendEventable(EventClient);
171
+
172
+ // 4. Configure the eventClient INSTANCE
173
+ // This tells the client which event bus to connect to.
174
+ eventClient.setApiRoot(electronApiRoot);
175
+ eventClient.register();
176
+
177
+ // 5. Now you can use the event client
178
+ async function setupEvents() {
179
+ await eventClient.subscribe('some-event-from-main');
180
+
181
+ eventClient.on('some-event-from-main', (data) => {
182
+ console.log('Received event from main process:', data);
183
+ });
184
+
185
+ // Forward a local event to the main process
186
+ eventClient.forwardEvent('event-from-renderer');
187
+ eventClient.emit('event-from-renderer', { my: 'data' });
188
+ }
189
+
190
+ setupEvents();
191
+ ```
192
+
193
+ ---
194
+
195
+ ## General Usage (Transport-Agnostic)
196
+
197
+ Once the setup is complete, the API for using the event bus is the same regardless of the underlying transport.
198
+
199
+ ### Forwarding and Publishing Events (Server-Side)
200
+
201
+ The server can push events to clients either by forwarding them from a central event bus or by publishing them directly. With the latest updates, the `publish` method now supports targeted delivery to specific clients, in addition to broadcasting.
202
+
203
+ **Note:** The availability of targeted publishing depends on the underlying transport implementation. While the `EventServer` API supports it, some transports (like the current SSE transport) may only be capable of broadcasting.
204
+
205
+ ```typescript
206
+ import { eventServer, EventServer } from '@isdk/ai-tool';
207
+ import { event } from '@isdk/ai-tool/funcs/event'; // The global eventBus
208
+
209
+ const eventBus = event.runSync();
210
+
211
+ // **Forwarding (Recommended)**
212
+ // Automatically relay events from the global eventBus to subscribed clients.
213
+ eventServer.forward(['user-updated', 'item-added']);
214
+
215
+ // Now, any other part of your server can simply emit events on the bus:
216
+ function updateUser(user: any) {
217
+ eventBus.emit('user-updated', { userId: user.id, status: 'active' });
218
+ }
219
+
220
+ // **Direct Publishing**
221
+ // The `EventServer.publish` method allows sending an event directly to clients.
222
+ // Its signature is: `publish(event: string, data: any, target?: { clientId: string | string[] })`.
223
+
224
+ // 1. Broadcast to all clients subscribed to 'broadcast-message'.
225
+ // This is the default behavior when `target` is omitted.
226
+ function sendBroadcast() {
227
+ EventServer.publish('broadcast-message', { message: 'Server is restarting soon!' });
228
+ }
229
+
230
+ // 2. Send a targeted event to a specific client.
231
+ // This requires knowing the `clientId` of the recipient.
232
+ function sendDirectMessage(clientId: string, message: string) {
233
+ const target = { clientId };
234
+ EventServer.publish('private-message', { text: message }, target);
235
+ }
236
+
237
+ // 3. Send an event to a group of specific clients.
238
+ function sendToGroup(clientIds: string[], message: string) {
239
+ const target = { clientId: clientIds };
240
+ EventServer.publish('group-message', { text: message }, target);
241
+ }
242
+
243
+ // **Receiving Client Events**
244
+ // Listen for events that were published or forwarded from a client.
245
+ eventBus.on('client-action', (data: any, event: any) => {
246
+ console.log(`Received event "$\{event.type\}" from a client:`, data);
247
+ });
248
+ ```
249
+
250
+ ### Subscribing, Listening, and Publishing (Client-Side)
251
+
252
+ ```typescript
253
+ // **Subscribe and Listen**
254
+ await eventClient.subscribe(['user-updated', 'broadcast-message']);
255
+
256
+ eventClient.on('user-updated', (data: any) => {
257
+ console.log('User updated on server!', data);
258
+ });
259
+
260
+ // **Publish an Event to the Server**
261
+ eventClient.publish({
262
+ event: 'client-action',
263
+ data: { action: 'button-click', value: 123 }
264
+ });
265
+
266
+ // **Forwarding Client Events (Recommended)**
267
+ eventClient.forwardEvent(['user-settings-changed']);
268
+
269
+ function onSettingsSave(newSettings: any) {
270
+ eventClient.emit('user-settings-changed', newSettings);
271
+ }
272
+ ```
273
+
274
+ This transport-agnostic architecture provides a clean, powerful, and decoupled way to build real-time, interactive applications. By separating the event logic from the communication protocol, you can choose the best transport for your needs while maintaining a consistent, unified event model.
275
+
276
+ ---
277
+
278
+ ## Implementing a Custom PubSub Transport
279
+
280
+ For developers who need to integrate a different messaging protocol (e.g., WebSockets, MQTT), you can create your own transport by implementing the `IPubSubServerTransport` interface from `@isdk/ai-tool/transports/pubsub/server`.
281
+
282
+ The core interface is defined as follows:
283
+
284
+ ```typescript
285
+ export interface IPubSubServerTransport {
286
+ readonly name: string;
287
+ readonly protocol: string;
288
+
289
+ // Optional: For transports that need to hook into an HTTP server
290
+ mount?: (path: string, options?: Record<string, any>) => void;
291
+
292
+ // Establish a connection with a client and subscribe them to events.
293
+ // The `options` object is a generic container for transport-specific
294
+ // parameters, like HTTP request/response objects for SSE.
295
+ subscribe: (
296
+ events?: string[],
297
+ options?: {
298
+ req?: any;
299
+ res?: any;
300
+ clientId?: string;
301
+ [k: string]: any;
302
+ }
303
+ ) => PubSubClient; // Return a client object, minimally with a `clientId`.
304
+
305
+ // Publish an event from the server to clients.
306
+ // The `target` parameter allows for broadcasting (default) or
307
+ // targeted delivery to specific client IDs.
308
+ publish: (
309
+ event: string,
310
+ data: any,
311
+ target?: { clientId?: string | string[] }
312
+ ) => void;
313
+
314
+ // Lifecycle hooks to let the EventServer know about connections.
315
+ onConnection: (cb: (session: PubSubServerSession) => void) => void;
316
+ onDisconnect: (cb: (session: PubSubServerSession) => void) => void;
317
+
318
+ // Optional: For bidirectional transports (e.g., WebSockets)
319
+ // to handle messages received from the client.
320
+ onMessage?: (
321
+ cb: (session: PubSubServerSession, event: string, data: any) => void
322
+ ) => void;
323
+ }
324
+ ```
325
+
326
+ By implementing this interface, your custom transport can be plugged directly into the `EventServer` using `EventServer.setPubSubTransport(new YourCustomTransport())`, enabling the entire real-time event system over your chosen protocol.
@@ -0,0 +1,88 @@
1
+ # Guide: Server & Client Tool Types
2
+
3
+ This guide provides a detailed description of the different `ServerTools` and `ClientTools` subclasses. It focuses on their specific purpose and how each one separates its business logic from the communication logic handled by the transport layer.
4
+
5
+ ## 1. `ServerTools` / `ClientTools`
6
+
7
+ This is the most fundamental pair for client-server communication.
8
+
9
+ ### `ServerTools`
10
+
11
+ - **Purpose:** To define a single, remotely callable function.
12
+ - **Business Logic:** Your code is placed entirely within the `func` property when the tool is defined. This function contains the logic you want to execute on the server.
13
+ - **Communication Logic:** This class has **no** communication logic. It is a simple container for your business logic. The transport layer is entirely responsible for receiving a network request and invoking the tool's `func`.
14
+
15
+ ```typescript
16
+ // Business logic is self-contained in 'func'.
17
+ ServerTools.register({
18
+ name: 'mySimpleTool',
19
+ func: async (params) => {
20
+ // ... your logic here ...
21
+ return { success: true, ...params };
22
+ },
23
+ });
24
+ ```
25
+
26
+ ### `ClientTools`
27
+
28
+ - **Purpose:** To act as a local proxy for a remote `ServerTools` instance.
29
+ - **Business Logic:** This class contains **no** business logic.
30
+ - **Communication Logic:** When you call `.run()` on a `ClientTools` instance, its only job is to delegate the call to the configured **client transport**. The transport handles all aspects of serialization, network requests, and response handling.
31
+
32
+ ---
33
+
34
+ ## 2. `RpcMethodsServerTool` / `RpcMethodsClientTool`
35
+
36
+ This pair is designed to group multiple related functions into a single, cohesive tool, like methods on a class.
37
+
38
+ ### `RpcMethodsServerTool`
39
+
40
+ - **Purpose:** To serve as a container for multiple, related functions under a single tool name.
41
+ - **Business Logic:** You define your logic in class methods prefixed with a `$` (e.g., `$add`, `$subtract`). Each method represents a distinct operation.
42
+ - **Communication Logic:** This class contains a small amount of **routing logic**. Its main `func` (which is invoked by the transport) acts as a simple dispatcher. It inspects the `act` parameter from the incoming request and calls the corresponding internal `$` method. It does not handle any direct network communication.
43
+
44
+ ```typescript
45
+ // Business logic is in the $add and $subtract methods.
46
+ class CalculatorTool extends RpcMethodsServerTool {
47
+ $add({ a, b }) { return a + b; }
48
+ $subtract({ a, b }) { return a - b; }
49
+ }
50
+
51
+ // The main 'func' inherited from the base class handles the routing.
52
+ new CalculatorTool('calculator').register();
53
+ ```
54
+
55
+ ### `RpcMethodsClientTool`
56
+
57
+ - **Purpose:** To be a user-friendly proxy for a remote `RpcMethodsServerTool`.
58
+ - **Business Logic:** None.
59
+ - **Communication Logic:** This class has more advanced communication logic than a basic `ClientTools` instance. When it's created, it dynamically adds proxy methods to itself (e.g., `.add()`, `.subtract()`). When you call one of these proxy methods, it automatically constructs the correct request body (e.g., `{ act: '$add', a, b }`) before passing it to the client transport for sending.
60
+
61
+ ---
62
+
63
+ ## 3. `ResServerTools` / `ResClientTools`
64
+
65
+ This is the highest-level abstraction, designed for creating resource-oriented APIs that follow RESTful conventions.
66
+
67
+ ### `ResServerTools`
68
+
69
+ - **Purpose:** To provide a conventional, resource-oriented (CRUD) API.
70
+ - **Business Logic:** You place your logic in conventionally-named methods like `get`, `list`, `post`, `put`, and `delete`.
71
+ - **Communication Logic:** This class has the most advanced **routing logic**. It is designed to work with a transport that can provide HTTP context (like the verb and URL parameters). It maps HTTP request details (e.g., `GET /api/users/123`) to the appropriate business logic method (e.g., `get({ id: '123' })`). It still relies on the transport to handle the actual network connection.
72
+
73
+ ```typescript
74
+ // Business logic is in the get, list, etc. methods.
75
+ class UserResource extends ResServerTools {
76
+ get({ id }) { /* ... find user by id ... */ }
77
+ list() { /* ... return all users ... */ }
78
+ }
79
+
80
+ // The tool's internal logic maps HTTP requests to these methods.
81
+ new UserResource('users').register();
82
+ ```
83
+
84
+ ### `ResClientTools`
85
+
86
+ - **Purpose:** To be an intuitive proxy for a remote `ResServerTools` instance.
87
+ - **Business Logic:** None.
88
+ - **Communication Logic:** It provides a conventional client-side API (e.g., `.get()`, `.list()`). Calling one of these methods signals to the client transport *how* to construct the underlying HTTP request. For example, calling `userClient.get({ id: '123' })` instructs the transport to make an `HTTP GET` request to the appropriate URL (`/api/users/123`).