@isdk/ai-tool 0.8.2 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (405) hide show
  1. package/dist/chunk-BIJ2JH4U.mjs +1 -0
  2. package/dist/chunk-OYMVHUDZ.mjs +1 -0
  3. package/dist/funcs.d.mts +16 -5
  4. package/dist/funcs.d.ts +16 -5
  5. package/dist/funcs.js +1 -1
  6. package/dist/funcs.mjs +1 -1
  7. package/dist/index.d.mts +839 -563
  8. package/dist/index.d.ts +839 -563
  9. package/dist/index.js +1 -1
  10. package/dist/index.mjs +1 -1
  11. package/dist/test/util.d.mts +1 -1
  12. package/dist/test/util.d.ts +1 -1
  13. package/dist/test/util.js +1 -1
  14. package/dist/test/util.mjs +1 -1
  15. package/docs/api/@isdk/namespaces/ClientTools/README.md +11 -0
  16. package/docs/api/@isdk/namespaces/ClientTools/functions/get.md +27 -0
  17. package/docs/api/@isdk/namespaces/EventStates/variables/ABORT.md +1 -1
  18. package/docs/api/@isdk/namespaces/EventStates/variables/CONTINUE.md +1 -1
  19. package/docs/api/@isdk/namespaces/EventStates/variables/DONE.md +1 -1
  20. package/docs/api/@isdk/namespaces/EventStates/variables/STOPPED.md +1 -1
  21. package/docs/api/classes/BinarySemaphore.md +148 -67
  22. package/docs/api/classes/CancelableAbility.md +95 -43
  23. package/docs/api/classes/ClientToolTransport.md +31 -16
  24. package/docs/api/classes/ClientTools.md +868 -158
  25. package/docs/api/classes/CmdArgLexer.md +82 -0
  26. package/docs/api/classes/CmdArgParser.md +56 -0
  27. package/docs/api/classes/ConfigFile.md +6 -6
  28. package/docs/api/classes/EnvPromptTemplate.md +224 -52
  29. package/docs/api/classes/EventClient.md +902 -192
  30. package/docs/api/classes/EventEmitter.md +62 -12
  31. package/docs/api/classes/EventServer.md +895 -182
  32. package/docs/api/classes/EventToolFunc.md +801 -123
  33. package/docs/api/classes/FStringPromptTemplate.md +224 -52
  34. package/docs/api/classes/FewShotPromptTemplate.md +231 -59
  35. package/docs/api/classes/GolangPromptTemplate.md +224 -52
  36. package/docs/api/classes/HttpClientToolTransport.md +33 -19
  37. package/docs/api/classes/HttpServerToolTransport.md +15 -15
  38. package/docs/api/classes/IntSet.md +21 -21
  39. package/docs/api/classes/MailboxClientTransport.md +398 -0
  40. package/docs/api/classes/MailboxServerTransport.md +433 -0
  41. package/docs/api/classes/PromptExampleSelector.md +11 -11
  42. package/docs/api/classes/PromptTemplate.md +199 -51
  43. package/docs/api/classes/ReadableStreamError.md +2 -2
  44. package/docs/api/classes/ResClientTools.md +875 -165
  45. package/docs/api/classes/ResServerTools.md +869 -156
  46. package/docs/api/classes/RpcMethodsClientTool.md +870 -160
  47. package/docs/api/classes/RpcMethodsServerTool.md +865 -152
  48. package/docs/api/classes/SSEChannel.md +23 -23
  49. package/docs/api/classes/Semaphore.md +148 -76
  50. package/docs/api/classes/ServerToolTransport.md +14 -13
  51. package/docs/api/classes/ServerTools.md +854 -138
  52. package/docs/api/classes/SignalGate.md +12 -12
  53. package/docs/api/classes/SseClientPubSubTransport.md +4 -4
  54. package/docs/api/classes/SseServerPubSubTransport.md +13 -13
  55. package/docs/api/classes/TaskAbortController.md +33 -11
  56. package/docs/api/classes/ToolFunc.md +725 -119
  57. package/docs/api/classes/ToolTransport.md +7 -7
  58. package/docs/api/classes/YamlTypeBaseObject.md +2 -2
  59. package/docs/api/enumerations/AsyncFeatureBits.md +4 -4
  60. package/docs/api/enumerations/AsyncFeatures.md +4 -4
  61. package/docs/api/enumerations/CmdArgTokenType.md +129 -0
  62. package/docs/api/enumerations/HashAlgorithm.md +38 -12
  63. package/docs/api/functions/AIArgProcessor.md +8 -17
  64. package/docs/api/functions/AIStream.md +1 -1
  65. package/docs/api/functions/ChoiceArgProcessor.md +13 -15
  66. package/docs/api/functions/DefaultDateFormat.md +1 -1
  67. package/docs/api/functions/ObjectArgsToArgsInfo.md +11 -9
  68. package/docs/api/functions/RateLimit.md +33 -6
  69. package/docs/api/functions/TemplateArgProcessor.md +13 -15
  70. package/docs/api/functions/assignDirs.md +1 -1
  71. package/docs/api/functions/beforeShutdown.md +3 -3
  72. package/docs/api/functions/calcPerplexity.md +3 -3
  73. package/docs/api/functions/calcPerplexitySimple.md +3 -3
  74. package/docs/api/functions/cmdArgEvaluate.md +28 -0
  75. package/docs/api/functions/cmdArgsToMergedObject.md +34 -0
  76. package/docs/api/functions/completeSentences.md +1 -1
  77. package/docs/api/functions/concatText.md +1 -1
  78. package/docs/api/functions/countLLMTokens.md +1 -1
  79. package/docs/api/functions/countRegexMatches.md +1 -1
  80. package/docs/api/functions/createCallbacksTransformer.md +23 -19
  81. package/docs/api/functions/createEmptyReadableStream.md +1 -1
  82. package/docs/api/functions/createEndWithRepetitionDetector.md +4 -4
  83. package/docs/api/functions/createEventStreamTransformer.md +1 -1
  84. package/docs/api/functions/createHfValueFunc.md +1 -1
  85. package/docs/api/functions/createLRUCache.md +1 -1
  86. package/docs/api/functions/createYamlObjectTag.md +1 -1
  87. package/docs/api/functions/dateToText.md +1 -1
  88. package/docs/api/functions/decodeCharset.md +1 -1
  89. package/docs/api/functions/defaultsWithConcat.md +1 -1
  90. package/docs/api/functions/detectCharset.md +1 -1
  91. package/docs/api/functions/encodeLLMTokens.md +1 -1
  92. package/docs/api/functions/ensureQuoted.md +3 -1
  93. package/docs/api/functions/evaluateExpression.md +40 -0
  94. package/docs/api/functions/eventable.md +1 -1
  95. package/docs/api/functions/expandConfig.md +1 -1
  96. package/docs/api/functions/expandEnv.md +1 -1
  97. package/docs/api/functions/expandObjEnv.md +1 -1
  98. package/docs/api/functions/expandPath.md +1 -1
  99. package/docs/api/functions/expandPathInObject.md +1 -1
  100. package/docs/api/functions/expandPaths.md +1 -1
  101. package/docs/api/functions/extNameLevel.md +1 -1
  102. package/docs/api/functions/extractCodeBlock.md +51 -0
  103. package/docs/api/functions/fileIsExists.md +3 -3
  104. package/docs/api/functions/filterValidFnScope.md +3 -3
  105. package/docs/api/functions/findIndexNonEmptyFrom.md +1 -1
  106. package/docs/api/functions/findPort.md +13 -5
  107. package/docs/api/functions/formatTextWithSpace.md +1 -1
  108. package/docs/api/functions/funcGetMeta.md +1 -1
  109. package/docs/api/functions/funcWithMeta.md +4 -4
  110. package/docs/api/functions/genUrlParamsStr.md +1 -1
  111. package/docs/api/functions/getAllEnumKeys.md +1 -1
  112. package/docs/api/functions/getConfigFileNames.md +1 -1
  113. package/docs/api/functions/getConfigs.md +1 -1
  114. package/docs/api/functions/getEnvVairables.md +1 -1
  115. package/docs/api/functions/getFileMetaInfo.md +1 -1
  116. package/docs/api/functions/getHashAlgoBySize.md +1 -1
  117. package/docs/api/functions/getKeysPath.md +1 -1
  118. package/docs/api/functions/getLLMTokenizer.md +1 -1
  119. package/docs/api/functions/getMultiLevelExtname.md +1 -1
  120. package/docs/api/functions/getPackageDir.md +1 -1
  121. package/docs/api/functions/getRealFilepath.md +1 -1
  122. package/docs/api/functions/getResponseErrorReadableStream.md +2 -2
  123. package/docs/api/functions/getXDGConfigs.md +1 -1
  124. package/docs/api/functions/hasDirectoryIn.md +3 -3
  125. package/docs/api/functions/hash.md +25 -4
  126. package/docs/api/functions/hashFile.md +1 -1
  127. package/docs/api/functions/hashObject.md +23 -1
  128. package/docs/api/functions/hashStream.md +25 -4
  129. package/docs/api/functions/initShutdown.md +1 -1
  130. package/docs/api/functions/isIdentifier.md +30 -0
  131. package/docs/api/functions/isLangUsingSpaces.md +1 -1
  132. package/docs/api/functions/isListItemString.md +3 -3
  133. package/docs/api/functions/isModelNameMatched.md +3 -3
  134. package/docs/api/functions/isPathIdentifier.md +23 -0
  135. package/docs/api/functions/isPunctuationChar.md +1 -1
  136. package/docs/api/functions/isQuoted.md +4 -1
  137. package/docs/api/functions/isRegExp.md +20 -1
  138. package/docs/api/functions/isSameString.md +1 -1
  139. package/docs/api/functions/isSectionString.md +3 -3
  140. package/docs/api/functions/isSentenceEnding.md +1 -1
  141. package/docs/api/functions/isSepLineString.md +3 -3
  142. package/docs/api/functions/isStrWrapped.md +3 -1
  143. package/docs/api/functions/isSubdirectory.md +1 -1
  144. package/docs/api/functions/isTitleString.md +3 -3
  145. package/docs/api/functions/isValidFilename.md +1 -1
  146. package/docs/api/functions/isValidFilepath.md +1 -1
  147. package/docs/api/functions/isWebStream.md +1 -1
  148. package/docs/api/functions/joinSplitWords.md +1 -1
  149. package/docs/api/functions/jsonFilterToWhere.md +1 -1
  150. package/docs/api/functions/jsonToMarkdownStr.md +1 -1
  151. package/docs/api/functions/loadAIConfig.md +1 -1
  152. package/docs/api/functions/loadConfig.md +1 -1
  153. package/docs/api/functions/loadConfigFile.md +1 -1
  154. package/docs/api/functions/loadFileFromPaths.md +1 -1
  155. package/docs/api/functions/loadTextFromPaths.md +1 -1
  156. package/docs/api/functions/lrucache.md +1 -1
  157. package/docs/api/functions/matchUrlProtocol.md +3 -3
  158. package/docs/api/functions/memoize.md +1 -1
  159. package/docs/api/functions/mergeArray.md +1 -1
  160. package/docs/api/functions/messagesToText.md +1 -1
  161. package/docs/api/functions/normalizePath.md +1 -1
  162. package/docs/api/functions/paramsSizeToScaleStr.md +1 -1
  163. package/docs/api/functions/parseCommand.md +21 -4
  164. package/docs/api/functions/parseJsJson.md +1 -1
  165. package/docs/api/functions/parseJsJsonSimpleSync.md +1 -1
  166. package/docs/api/functions/parseObjectArguments.md +17 -33
  167. package/docs/api/functions/parseYaml.md +1 -1
  168. package/docs/api/functions/prependNewlineIfMultiline.md +39 -0
  169. package/docs/api/functions/pruneSubdirectories.md +1 -1
  170. package/docs/api/functions/pruneSubdirectoriesInPlace.md +1 -1
  171. package/docs/api/functions/quoteStr.md +4 -1
  172. package/docs/api/functions/readFilenamesRecursiveSync.md +1 -1
  173. package/docs/api/functions/readTextFileChunks.md +1 -1
  174. package/docs/api/functions/readTextFileChunksEx.md +1 -1
  175. package/docs/api/functions/readableFromAsyncIterable.md +1 -1
  176. package/docs/api/functions/registerCoreTools.md +1 -1
  177. package/docs/api/functions/registerYamlTag.md +2 -2
  178. package/docs/api/functions/removeMarkdownBold.md +1 -1
  179. package/docs/api/functions/removeMarkdownBoldAndItalic.md +1 -1
  180. package/docs/api/functions/removeMarkdownItalic.md +1 -1
  181. package/docs/api/functions/replaceWithPlaceholder.md +3 -18
  182. package/docs/api/functions/restoreFromPlacehoders.md +2 -20
  183. package/docs/api/functions/sanitizeFilename.md +1 -1
  184. package/docs/api/functions/sanitizeFilepath.md +1 -1
  185. package/docs/api/functions/saveConfigFile.md +1 -1
  186. package/docs/api/functions/scaleStrToParamsSize.md +1 -1
  187. package/docs/api/functions/shutdown.md +2 -2
  188. package/docs/api/functions/simplifyObjectArguments.md +4 -1
  189. package/docs/api/functions/simplifyResult.md +34 -0
  190. package/docs/api/functions/sleep.md +1 -1
  191. package/docs/api/functions/sortedValues.md +1 -1
  192. package/docs/api/functions/splitChunks.md +1 -1
  193. package/docs/api/functions/splitParagraph.md +1 -1
  194. package/docs/api/functions/splitSentence.md +1 -1
  195. package/docs/api/functions/splitWords.md +1 -1
  196. package/docs/api/functions/stringifyYaml.md +1 -1
  197. package/docs/api/functions/stripConsoleColor.md +1 -1
  198. package/docs/api/functions/textToDate.md +1 -1
  199. package/docs/api/functions/textify.md +43 -0
  200. package/docs/api/functions/toDateTime.md +3 -3
  201. package/docs/api/functions/toRegExp.md +1 -1
  202. package/docs/api/functions/trimStartOfStreamHelper.md +1 -1
  203. package/docs/api/functions/truncTo.md +1 -1
  204. package/docs/api/functions/truncateByToken.md +1 -1
  205. package/docs/api/functions/truncateToTokenLimit.md +1 -1
  206. package/docs/api/functions/truncateToTokenLimitEx.md +1 -1
  207. package/docs/api/functions/uuid.md +1 -1
  208. package/docs/api/functions/wrapEventEmitter.md +1 -1
  209. package/docs/api/functions/wrapFlagValue.md +29 -0
  210. package/docs/api/functions/xxhash.md +27 -6
  211. package/docs/api/functions/xxhash32.md +22 -4
  212. package/docs/api/functions/xxhash64.md +22 -4
  213. package/docs/api/functions/xxhashAsStr.md +27 -6
  214. package/docs/api/functions/yieldExec.md +1 -1
  215. package/docs/api/globals.md +51 -18
  216. package/docs/api/interfaces/AIChatAssistantMessageParam.md +14 -14
  217. package/docs/api/interfaces/AIChatContentPartBase.md +26 -0
  218. package/docs/api/interfaces/AIChatContentPartImage.md +15 -3
  219. package/docs/api/interfaces/AIChatContentPartText.md +15 -3
  220. package/docs/api/interfaces/AIChatMessageParamBase.md +9 -9
  221. package/docs/api/interfaces/AIChatMessageToolCall.md +12 -8
  222. package/docs/api/interfaces/AIChatSystemMessageParam.md +10 -10
  223. package/docs/api/interfaces/AIChatToolChoiceFuncObject.md +3 -3
  224. package/docs/api/interfaces/AIChatToolChoiceObject.md +2 -2
  225. package/docs/api/interfaces/AIChatToolDefinition.md +45 -0
  226. package/docs/api/interfaces/AIChatToolFunc.md +5 -5
  227. package/docs/api/interfaces/AIChatToolFuncParam.md +3 -3
  228. package/docs/api/interfaces/AIChatToolMessageParam.md +13 -13
  229. package/docs/api/interfaces/AIChatToolParam.md +2 -2
  230. package/docs/api/interfaces/AIChatToolTypeObject.md +2 -2
  231. package/docs/api/interfaces/AIChatUserMessageParam.md +14 -14
  232. package/docs/api/interfaces/AIResult.md +7 -7
  233. package/docs/api/interfaces/AIStreamParser.md +2 -2
  234. package/docs/api/interfaces/AIStreamParserOptions.md +2 -2
  235. package/docs/api/interfaces/BaseFunc.md +15 -15
  236. package/docs/api/interfaces/BaseFuncItem.md +16 -16
  237. package/docs/api/interfaces/BinarySemaphoreAcquireOptions.md +9 -2
  238. package/docs/api/interfaces/BinarySemaphoreOptions.md +22 -5
  239. package/docs/api/interfaces/BinarySemaphoreReleaseOptions.md +7 -5
  240. package/docs/api/interfaces/CancelableAbilityOptions.md +4 -4
  241. package/docs/api/interfaces/ClientFuncItem.md +70 -19
  242. package/docs/api/interfaces/CmdArgAIChoiceConfig.md +97 -0
  243. package/docs/api/interfaces/CmdArgArgsInfo.md +31 -0
  244. package/docs/api/interfaces/CmdArgContext.md +103 -0
  245. package/docs/api/interfaces/CmdArgFlagMetadata.md +21 -0
  246. package/docs/api/interfaces/CmdArgMapResult.md +41 -0
  247. package/docs/api/interfaces/CmdArgParseResult.md +51 -0
  248. package/docs/api/interfaces/CmdArgParsedCommand.md +41 -0
  249. package/docs/api/interfaces/CmdArgParserOptions.md +225 -0
  250. package/docs/api/interfaces/CmdArgProcessorResultOptions.md +22 -0
  251. package/docs/api/interfaces/CmdArgSimplifyOptions.md +101 -0
  252. package/docs/api/interfaces/CmdArgToken.md +51 -0
  253. package/docs/api/interfaces/EventClientFuncParams.md +5 -5
  254. package/docs/api/interfaces/EventServerFuncParams.md +21 -7
  255. package/docs/api/interfaces/FewShotPromptTemplateOptions.md +18 -6
  256. package/docs/api/interfaces/FuncItem.md +19 -15
  257. package/docs/api/interfaces/FuncParam.md +5 -5
  258. package/docs/api/interfaces/FuncParams.md +1 -1
  259. package/docs/api/interfaces/Funcs.md +1 -1
  260. package/docs/api/interfaces/HashAlgoParams.md +36 -5
  261. package/docs/api/interfaces/IClientToolTransport.md +24 -10
  262. package/docs/api/interfaces/IFileMetaInfo.md +8 -8
  263. package/docs/api/interfaces/IPubSubClientTransport.md +4 -4
  264. package/docs/api/interfaces/IPubSubServerTransport.md +14 -14
  265. package/docs/api/interfaces/IReadTextFileChunksOptions.md +11 -11
  266. package/docs/api/interfaces/IServerToolTransport.md +8 -8
  267. package/docs/api/interfaces/IToolTransport.md +5 -5
  268. package/docs/api/interfaces/ITruncateToTokenLimitOptions.md +10 -10
  269. package/docs/api/interfaces/JsonFilter.md +1 -1
  270. package/docs/api/interfaces/MailboxClientOptions.md +74 -0
  271. package/docs/api/interfaces/MailboxServerOptions.md +69 -0
  272. package/docs/api/interfaces/ProbabilityItem.md +4 -4
  273. package/docs/api/interfaces/PromptExampleSelectorOptions.md +3 -3
  274. package/docs/api/interfaces/PromptTemplateOptions.md +8 -0
  275. package/docs/api/interfaces/PubSubClientStream.md +11 -11
  276. package/docs/api/interfaces/PubSubServerSession.md +8 -8
  277. package/docs/api/interfaces/RegisterOptions.md +298 -0
  278. package/docs/api/interfaces/RemoteFuncItem.md +63 -20
  279. package/docs/api/interfaces/ReplacePlacehoderOptions.md +5 -5
  280. package/docs/api/interfaces/ResClientFuncParams.md +3 -3
  281. package/docs/api/interfaces/ResServerFuncParams.md +20 -6
  282. package/docs/api/interfaces/RpcMethodsClientFuncParams.md +2 -2
  283. package/docs/api/interfaces/RpcMethodsServerFuncParams.md +18 -4
  284. package/docs/api/interfaces/SanitizeFilenameOptions.md +3 -3
  285. package/docs/api/interfaces/SectionStringOptions.md +3 -3
  286. package/docs/api/interfaces/SemaphoreOptions.md +30 -7
  287. package/docs/api/interfaces/SemaphoreTaskItem.md +18 -5
  288. package/docs/api/interfaces/ServerFuncItem.md +71 -20
  289. package/docs/api/interfaces/ServerFuncParams.md +14 -4
  290. package/docs/api/interfaces/SplitSentenceOptions.md +5 -5
  291. package/docs/api/interfaces/StreamCallbacksAndOptions.md +80 -7
  292. package/docs/api/interfaces/TaskAbortControllers.md +2 -2
  293. package/docs/api/interfaces/TaskPromise.md +6 -6
  294. package/docs/api/interfaces/TextifyInlineOptions.md +51 -0
  295. package/docs/api/interfaces/TextifyOptions.md +108 -0
  296. package/docs/api/interfaces/ToolFuncContext.md +73 -0
  297. package/docs/api/interfaces/ToolFuncPackage.md +4 -4
  298. package/docs/api/interfaces/ToolFuncRegistryIsolateOptions.md +41 -0
  299. package/docs/api/interfaces/UnregisterOptions.md +56 -0
  300. package/docs/api/type-aliases/AIChatContentPart.md +2 -2
  301. package/docs/api/type-aliases/AIChatMessageParam.md +1 -1
  302. package/docs/api/type-aliases/AIChatRole.md +2 -2
  303. package/docs/api/type-aliases/AIChatTemplateCaps.md +239 -0
  304. package/docs/api/type-aliases/AIChatToolChoiceParam.md +1 -1
  305. package/docs/api/type-aliases/AIMessageType.md +1 -1
  306. package/docs/api/type-aliases/AIModelNameRule.md +1 -1
  307. package/docs/api/type-aliases/AIModelNameRuleFn.md +1 -1
  308. package/docs/api/type-aliases/AIModelNameRules.md +1 -1
  309. package/docs/api/type-aliases/AITextGenerationFinishReason.md +1 -1
  310. package/docs/api/type-aliases/ActionName.md +1 -1
  311. package/docs/api/type-aliases/ArgProcessor.md +24 -0
  312. package/docs/api/type-aliases/ArrayMergeWay.md +1 -1
  313. package/docs/api/type-aliases/AsyncTaskId.md +1 -1
  314. package/docs/api/type-aliases/BeforeShutdownListener.md +1 -1
  315. package/docs/api/type-aliases/CmdArgFlagValue.md +14 -0
  316. package/docs/api/type-aliases/CmdArgFlagsRecord.md +13 -0
  317. package/docs/api/type-aliases/EventErrorListenerFn.md +1 -1
  318. package/docs/api/type-aliases/EventListenerFn.md +1 -1
  319. package/docs/api/type-aliases/FuncParamType.md +1 -1
  320. package/docs/api/type-aliases/PromptExamples.md +1 -1
  321. package/docs/api/type-aliases/PubSubClientId.md +1 -1
  322. package/docs/api/type-aliases/PubSubCtx.md +6 -6
  323. package/docs/api/type-aliases/RpcMethodHandler.md +1 -1
  324. package/docs/api/type-aliases/SSEClient.md +5 -5
  325. package/docs/api/type-aliases/SemaphoreIsReadyFuncType.md +4 -1
  326. package/docs/api/type-aliases/SimplifiedResultType.md +14 -0
  327. package/docs/api/type-aliases/StreamCloseStatus.md +16 -0
  328. package/docs/api/type-aliases/TFunc.md +1 -1
  329. package/docs/api/type-aliases/TextifyInlineStyleMode.md +16 -0
  330. package/docs/api/type-aliases/TextifyStringQuoting.md +16 -0
  331. package/docs/api/type-aliases/UUIDVersions.md +3 -1
  332. package/docs/api/variables/AIChatRoles.md +2 -2
  333. package/docs/api/variables/AIMessageTypes.md +1 -1
  334. package/docs/api/variables/AITextGenerationFinishReasons.md +1 -1
  335. package/docs/api/variables/ActionNames.md +1 -1
  336. package/docs/api/variables/ArrayMergeWay.md +1 -1
  337. package/docs/api/variables/ArrayMergeWaySymbol.md +1 -1
  338. package/docs/api/variables/CMD_ARG_FLAG_SYMBOL.md +21 -0
  339. package/docs/api/variables/CMD_ARG_PROCESSOR_RESULT.md +22 -0
  340. package/docs/api/variables/CMD_ARG_UNRESOLVED_SYMBOL.md +16 -0
  341. package/docs/api/variables/ClientEventPrefix.md +2 -2
  342. package/docs/api/variables/ClientToolFuncSchema.md +27 -17
  343. package/docs/api/variables/DEFAULT_CONFIG_NAME.md +1 -1
  344. package/docs/api/variables/DefaultAsyncSemaphoreCapacity.md +4 -1
  345. package/docs/api/variables/EventBusName.md +2 -2
  346. package/docs/api/variables/EventName.md +2 -2
  347. package/docs/api/variables/FilenameReservedRegex.md +1 -1
  348. package/docs/api/variables/FuncMetaSymbol.md +2 -2
  349. package/docs/api/variables/IDENTIFIER_REGEX.md +14 -0
  350. package/docs/api/variables/LLM_TOKENIZER_NAMES.md +1 -1
  351. package/docs/api/variables/LLM_TOKENIZER_NAMES_MAP.md +1 -1
  352. package/docs/api/variables/PASSING_SCORE.md +1 -1
  353. package/docs/api/variables/PATH_IDENTIFIER_REGEX.md +13 -0
  354. package/docs/api/variables/RESERVED_WORDS.md +13 -0
  355. package/docs/api/variables/RStreamErrCode.md +1 -1
  356. package/docs/api/variables/RemoteToolFuncSchema.md +36 -4
  357. package/docs/api/variables/ResponseRStreamErrCode.md +1 -1
  358. package/docs/api/variables/RpcMethodsClientToolSchema.md +2 -2
  359. package/docs/api/variables/RpcMethodsServerToolSchema.md +2 -2
  360. package/docs/api/variables/SHUTDOWN_SIGNALS.md +1 -1
  361. package/docs/api/variables/SSEChannelAlreadyClosedErrCode.md +1 -1
  362. package/docs/api/variables/SecondaryCache.md +1 -1
  363. package/docs/api/variables/ServerToolFuncSchema.md +27 -17
  364. package/docs/api/variables/StrangeHumanName.md +1 -1
  365. package/docs/api/variables/ToolAsyncCancelableBit.md +1 -1
  366. package/docs/api/variables/ToolAsyncMultiTaskBit.md +1 -1
  367. package/docs/api/variables/ToolAsyncPriorityBit.md +1 -1
  368. package/docs/api/variables/ToolFuncSchema.md +13 -13
  369. package/docs/api/variables/WindowsReservedNameRegex.md +1 -1
  370. package/docs/api/variables/backendEventable.md +23 -3
  371. package/docs/api/variables/base32768.md +2 -2
  372. package/docs/api/variables/event.md +1 -1
  373. package/docs/api/variables/eventClient.md +1 -1
  374. package/docs/api/variables/eventServer.md +1 -1
  375. package/docs/api/variables/lrucache.md +1 -1
  376. package/docs/api/variables/makeToolFuncCancelable.md +23 -3
  377. package/docs/api/variables/wait.md +1 -1
  378. package/docs/transport.dev.md +206 -0
  379. package/package.json +12 -10
  380. package/dist/chunk-4FKBOPZI.mjs +0 -1
  381. package/dist/chunk-TGTHY57V.mjs +0 -1
  382. package/dist/find-port-qS1CZ9c-.d.mts +0 -3
  383. package/dist/find-port-qS1CZ9c-.d.ts +0 -3
  384. package/dist/index-BLW3R7VS.d.mts +0 -1826
  385. package/dist/index-BLW3R7VS.d.ts +0 -1826
  386. package/docs/api/@isdk/namespaces/uuidv5/README.md +0 -12
  387. package/docs/api/@isdk/namespaces/uuidv5/variables/DNS.md +0 -11
  388. package/docs/api/@isdk/namespaces/uuidv5/variables/URL.md +0 -11
  389. package/docs/api/functions/nanoid.md +0 -45
  390. package/docs/api/functions/parseObjectArgInfo.md +0 -33
  391. package/docs/api/functions/parseObjectArgumentInfos.md +0 -29
  392. package/docs/api/functions/parseObjectArgumentsAsArgInfos.md +0 -46
  393. package/docs/api/functions/uuidParse.md +0 -21
  394. package/docs/api/functions/uuidStringify.md +0 -25
  395. package/docs/api/functions/uuidValidate.md +0 -21
  396. package/docs/api/functions/uuidVersion.md +0 -21
  397. package/docs/api/functions/uuidv1.md +0 -61
  398. package/docs/api/functions/uuidv4.md +0 -61
  399. package/docs/api/functions/uuidv5.md +0 -69
  400. package/docs/api/functions/uuidv6.md +0 -61
  401. package/docs/api/functions/uuidv7.md +0 -61
  402. package/docs/api/interfaces/AIChoiceConfig.md +0 -65
  403. package/docs/api/interfaces/BinarySemaphoreReleaserFunc.md +0 -37
  404. package/docs/api/interfaces/ParseObjectArgumentOptions.md +0 -89
  405. package/docs/api/variables/uuidNIL.md +0 -11
package/dist/index.d.ts CHANGED
@@ -1,31 +1,46 @@
1
- import * as custom_ability from 'custom-ability';
1
+ import { AsyncTaskId } from '@isdk/tool-func';
2
+ export * from '@isdk/tool-func';
3
+ export * from '@isdk/tool-rpc';
4
+ export * from '@isdk/tool-event';
2
5
  export { createAbilityInjector } from 'custom-ability';
3
6
  export { toRegExp } from 'util-ex';
4
- import { A as AsyncTaskId, a as AIModelNameRules, I as IPubSubServerTransport, P as PubSubServerSession, b as PubSubClientId, c as IPubSubClientTransport, d as PubSubClientStream, e as IToolTransport, S as ServerTools, T as ToolTransport, C as ClientToolTransport, F as Funcs, f as ActionName } from './index-BLW3R7VS.js';
5
- export { j as AIModelNameRule, i as AIModelNameRuleFn, h as ActionNames, x as AsyncFeatureBits, y as AsyncFeatures, V as BaseFunc, Q as BaseFuncItem, r as BinarySemaphore, m as BinarySemaphoreAcquireOptions, B as BinarySemaphoreOptions, n as BinarySemaphoreReleaseOptions, o as BinarySemaphoreReleaserFunc, J as CancelableAbility, z as CancelableAbilityOptions, ag as ClientEventPrefix, a1 as ClientFuncItem, a2 as ClientToolFuncSchema, a0 as ClientTools, D as DefaultAsyncSemaphoreCapacity, ae as EventClient, ad as EventClientFuncParams, ai as EventServer, ah as EventServerFuncParams, a7 as EventToolFunc, U as FuncItem, Z as FuncMetaSymbol, M as FuncParam, L as FuncParamType, N as FuncParams, av as IClientToolTransport, g as PASSING_SCORE, aw as PubSubCtx, t as RateLimit, k as RemoteFuncItem, R as RemoteToolFuncSchema, aq as ResClientFuncParams, ar as ResClientTools, as as ResServerFuncParams, at as ResServerTools, au as RpcMethodHandler, ak as RpcMethodsClientFuncParams, al as RpcMethodsClientTool, am as RpcMethodsClientToolSchema, an as RpcMethodsServerFuncParams, ao as RpcMethodsServerTool, ap as RpcMethodsServerToolSchema, a9 as SecondaryCache, s as Semaphore, l as SemaphoreIsReadyFuncType, p as SemaphoreOptions, q as SemaphoreTaskItem, a4 as ServerFuncItem, a3 as ServerFuncParams, a5 as ServerToolFuncSchema, O as TFunc, E as TaskAbortController, G as TaskAbortControllers, H as TaskPromise, v as ToolAsyncCancelableBit, u as ToolAsyncMultiTaskBit, w as ToolAsyncPriorityBit, X as ToolFunc, W as ToolFuncPackage, Y as ToolFuncSchema, aa as _lrucache, ab as createLRUCache, a8 as event, af as eventClient, aj as eventServer, $ as funcGetMeta, _ as funcWithMeta, ac as lrucache, K as makeToolFuncCancelable, a6 as registerCoreTools } from './index-BLW3R7VS.js';
6
- import * as _isdk_common_error from '@isdk/common-error';
7
7
  import { BaseError } from '@isdk/common-error';
8
8
  export { AbortError, AbortErrorCode, AlreadyExistsError, AlreadyExistsErrorCode, BaseError, CommonError, ErrorCode, InternalErrorCode, NotFoundError, NotFoundErrorCode, NotImplementationError, NotImplementedErrorCode, createError, throwError } from '@isdk/common-error';
9
9
  import { StringTemplateOptions, StringTemplate } from '@isdk/template-engines';
10
10
  export { EnvStringTemplate as EnvPromptTemplate, FStringTemplate as FStringPromptTemplate, GolangStringTemplate as GolangPromptTemplate, StringTemplate as PromptTemplate, StringTemplateOptions as PromptTemplateOptions, createHfValueFunc, defaultTemplateFormat, expandEnv, expandObjEnv, getEnvVairables } from '@isdk/template-engines';
11
- import { Event, EventEmitter } from 'events-ex';
12
- export { EventEmitter, states as EventStates, eventable, wrapEventEmitter } from 'events-ex';
13
- import http, { IncomingMessage, ServerResponse } from 'http';
14
- export { nanoid } from 'nanoid';
15
- import { v1, v4, v5, v6, v7 } from 'uuid';
16
- export { NIL as uuidNIL, parse as uuidParse, stringify as uuidStringify, validate as uuidValidate, version as uuidVersion, v1 as uuidv1, v4 as uuidv4, v5 as uuidv5, v6 as uuidv6, v7 as uuidv7 } from 'uuid';
17
- import * as _base32768 from 'base32768';
18
- import { IDataType } from 'hash-wasm';
19
- export { ConfigFile, FilenameReservedRegex, SanitizeFilenameOptions, WindowsReservedNameRegex, extNameLevel, getMultiLevelExtname, isValidFilename, isValidFilepath, parseYaml, registerYamlTag, sanitizeFilename, sanitizeFilepath, stringifyYaml } from '@isdk/util';
11
+ import { sleep } from '@isdk/util';
12
+ export { BinarySemaphore, BinarySemaphoreAcquireOptions, BinarySemaphoreOptions, BinarySemaphoreReleaseOptions, ConfigFile, DefaultAsyncSemaphoreCapacity, FilenameReservedRegex, IntSet, RateLimit, SanitizeFilenameOptions, Semaphore, SemaphoreIsReadyFuncType, SemaphoreOptions, SemaphoreTaskItem, SignalGate, WindowsReservedNameRegex, extNameLevel, extractCodeBlock, findPort, getMultiLevelExtname, isValidFilename, isValidFilepath, parseYaml, registerYamlTag, sanitizeFilename, sanitizeFilepath, sleep, stringifyYaml, yieldExec } from '@isdk/util';
13
+ import { HashAlgoParams, HashAlgorithm } from '@isdk/hash';
14
+ export { HashAlgoParams, HashAlgorithm, UUIDVersions, base32768, hash, hashObject, hashStream, uuid, xxhash, xxhash32, xxhash64, xxhashAsStr } from '@isdk/hash';
20
15
  import * as fs from 'fs';
21
16
  import _memoize, { Options } from 'memoizee';
22
- export { f as findPort } from './find-port-qS1CZ9c-.js';
23
17
  import { PreTrainedTokenizer } from '@huggingface/transformers';
24
18
  export { canonicalize } from 'json-canonicalize';
19
+ export { SecondaryCache, _lrucache, createLRUCache, lrucache, registerCoreTools } from './funcs.js';
25
20
  export { mimeType } from 'mime-type/with-db';
26
21
  export { add as addDate, formatISO, parse as parseDateFormat, parseISO, toDate } from 'date-fns';
27
22
  export { LRUCache } from 'secondary-cache';
28
- import 'property-manager';
23
+
24
+ /**
25
+ * A constant representing a passing score, likely used for similarity or relevance thresholds.
26
+ */
27
+ declare const PASSING_SCORE = 0.618;
28
+ /**
29
+ * Defines the signature for a function that processes an AI model's name,
30
+ * typically for matching or validation purposes.
31
+ * @param name - The model name string.
32
+ * @returns A string, a RegExp execution array, or undefined if no match is found.
33
+ */
34
+ type AIModelNameRuleFn = (name: string) => string | RegExpExecArray | undefined;
35
+ /**
36
+ * Defines a single rule for matching an AI model name. It can be a simple string,
37
+ * a regular expression, or a custom function.
38
+ */
39
+ type AIModelNameRule = string | RegExp | AIModelNameRuleFn;
40
+ /**
41
+ * Represents a collection of one or more AI model name matching rules.
42
+ */
43
+ type AIModelNameRules = AIModelNameRule | AIModelNameRule[];
29
44
 
30
45
  declare const AITextGenerationFinishReasons: readonly ["stop", "length", "content_filter", "tool_calls", "function_call", "abort", "error", "other", null];
31
46
  type AITextGenerationFinishReason = typeof AITextGenerationFinishReasons[number];
@@ -48,16 +63,25 @@ interface AIResult<TValue = any, TOptions = any> {
48
63
  }
49
64
  declare const AIMessageTypes: readonly ["human", "ai", "generic", "system", "tool"];
50
65
  type AIMessageType = typeof AIMessageTypes[number];
51
- declare const AIChatRoles: readonly ["user", "assistant", "system", "tool", "tool_calls"];
66
+ declare const AIChatRoles: readonly ["user", "assistant", "system", "tool"];
67
+ type AIChatRole = (typeof AIChatRoles[number]) | (string & {});
52
68
  declare const StrangeHumanName = "\u964C\u751F\u4EBA";
53
- type AIChatRole = (typeof AIChatRoles[number]) & string;
69
+ interface AIChatToolDefinition {
70
+ name?: string;
71
+ type: 'function';
72
+ function: {
73
+ name: string;
74
+ description?: string;
75
+ parameters?: any;
76
+ };
77
+ }
54
78
  type AIChatMessageParam = AIChatMessageParamBase | AIChatSystemMessageParam | AIChatUserMessageParam | AIChatAssistantMessageParam | AIChatToolMessageParam;
55
79
  interface AIChatMessageParamBase {
56
- role: string;
80
+ role: AIChatRole;
57
81
  toRole?: string | string[] | Record<string, Partial<AIChatMessageParam>>;
58
82
  replies?: Record<string, Partial<AIChatMessageParam>>;
59
83
  private?: boolean;
60
- tools?: Record<string, string>;
84
+ tools?: AIChatToolDefinition[];
61
85
  thinking?: string;
62
86
  [name: string]: any;
63
87
  }
@@ -75,14 +99,18 @@ interface AIChatUserMessageParam extends AIChatMessageParamBase {
75
99
  from?: 'speech' | string;
76
100
  templateFormat?: string;
77
101
  }
78
- type AIChatContentPart = AIChatContentPartText | AIChatContentPartImage;
79
- interface AIChatContentPartImage {
102
+ type AIChatContentPart = AIChatContentPartBase | AIChatContentPartText | AIChatContentPartImage;
103
+ interface AIChatContentPartBase {
104
+ type: 'text' | 'image_url' | string;
105
+ [name: string]: any;
106
+ }
107
+ interface AIChatContentPartImage extends AIChatContentPartBase {
80
108
  type: 'image_url';
81
109
  image_url: {
82
110
  url: string;
83
111
  };
84
112
  }
85
- interface AIChatContentPartText {
113
+ interface AIChatContentPartText extends AIChatContentPartBase {
86
114
  type: 'text';
87
115
  text: string;
88
116
  }
@@ -96,16 +124,17 @@ interface AIChatAssistantMessageParam extends AIChatMessageParamBase {
96
124
  }
97
125
  interface AIChatMessageToolCall {
98
126
  type: 'function';
99
- id: string;
127
+ id?: string;
100
128
  function: {
101
- arguments: string;
102
129
  name: string;
130
+ arguments?: string | any;
131
+ description?: string;
103
132
  };
104
133
  }
105
134
  interface AIChatToolMessageParam extends AIChatMessageParamBase {
106
135
  role: 'tool';
107
136
  content: string;
108
- tool_call_id: string;
137
+ tool_call_id?: string;
109
138
  templateFormat?: string;
110
139
  }
111
140
  interface AIChatToolParam {
@@ -135,6 +164,150 @@ interface AIChatToolTypeObject {
135
164
  name: string;
136
165
  }
137
166
  declare function messagesToText(messages: AIChatMessageParamBase[]): string;
167
+ /**
168
+ * Capabilities detected for a chat template (ChatML-like) with respect to
169
+ * OpenAI-compatible function/tool calling in llama.cpp-style pipelines.
170
+ *
171
+ * Each flag describes what the template can (or must) do when rendering messages/tools,
172
+ * so your caller can adapt message shaping, tool-calling strategy, and fallbacks.
173
+ *
174
+ * Detection is typically performed by rendering small “probe” conversations against
175
+ * the template and inspecting the resulting text.
176
+ *
177
+ */
178
+ type AIChatTemplateCaps = {
179
+ /**
180
+ * Whether the template requires OpenAI-style "typed content" parts instead of a plain string.
181
+ *
182
+ * @remarks
183
+ * - true: A message like `{ content: "..." }` is ignored, while
184
+ * `{ content: [{ type: "text", text: "..." }] }` renders correctly.
185
+ * - false: Both plain strings and typed parts render.
186
+ *
187
+ * @impact
188
+ * - If true, wrap all string content as text parts before rendering:
189
+ * `{ content: [{ type: "text", text }] }`.
190
+ *
191
+ * @example
192
+ * if (caps.requiresTypedContent && typeof msg.content === "string") {
193
+ * msg.content = [{ type: "text", text: msg.content }];
194
+ * }
195
+ */
196
+ requiresTypedContent: boolean;
197
+ /**
198
+ * Whether the template actually includes role=system messages in the rendered prompt.
199
+ *
200
+ * @remarks
201
+ * - true: You can pass `messages: [{ role: "system", ... }, ...]` and expect
202
+ * the system text to appear at the top of the prompt.
203
+ * - false: The template ignores system; move your “system rules” into the first user/assistant turn or edit the template.
204
+ *
205
+ * @impact
206
+ * - If false, critical behavior instructions should be injected via the template itself
207
+ * or merged into the first turn.
208
+ */
209
+ supportsSystemRole: boolean;
210
+ /**
211
+ * Whether the template consumes the top-level `tools` array (function catalog) and renders it into the prompt.
212
+ *
213
+ * @remarks
214
+ * - true: The model sees a readable list of available functions (names, descriptions, schemas).
215
+ * - false: The template doesn’t show the catalog; tool-calling can still work, but the model
216
+ * may be less aware of function options unless you add guidance text.
217
+ *
218
+ * @impact
219
+ * - If false, consider adding a short “How to call tools” section or a generated example to the template.
220
+ */
221
+ supportsTools: boolean;
222
+ /**
223
+ * Whether the template properly renders an assistant message that contains `tool_calls` (OpenAI format).
224
+ *
225
+ * @remarks
226
+ * - true: An assistant message with `tool_calls: [{ type: "function", function: { name, arguments }}, ...]`
227
+ * gets serialized in the template’s tool-call section.
228
+ * - false: The template does not serialize tool calls correctly; switch template/handler,
229
+ * fall back to a Generic handler, or use the “pure JSON intent” two-turn strategy.
230
+ *
231
+ * @impact
232
+ * - If false, do not rely on OpenAI `tool_calls` in a single assistant turn.
233
+ */
234
+ supportsToolCalls: boolean;
235
+ /**
236
+ * Whether the template expects `function.arguments` to be a JSON object (not a JSON-string literal).
237
+ *
238
+ * @remarks
239
+ * - true: Pass arguments as an object: `{ arguments: { ... } }`. Supplying a stringified JSON may double-escape or break parsing.
240
+ * - false: Both object and string are accepted (object is still recommended for stricter grammar alignment).
241
+ *
242
+ * @impact
243
+ * - Honor this when constructing assistant messages that contain `tool_calls`.
244
+ *
245
+ * @example
246
+ * const args = caps.requiresObjectArguments ? { city: "SF" } : JSON.stringify({ city: "SF" });
247
+ */
248
+ requiresObjectArguments: boolean;
249
+ /**
250
+ * Whether a single assistant message can contain multiple tool calls and be rendered correctly.
251
+ *
252
+ * @remarks
253
+ * - true: The template can serialize an array of calls in one assistant turn.
254
+ * - Note this only opens the possibility; the runtime must also allow it
255
+ * (e.g., request `parallel_tool_calls: true` and use a grammar with an array top rule),
256
+ * and the model must actually choose to emit multiple calls.
257
+ * - false: Even if the API flag is set, only 0/1 call will practically work per turn.
258
+ *
259
+ * @impact
260
+ * - Enable/disable “same-turn multi-call” orchestration accordingly.
261
+ */
262
+ supportsParallelToolCalls: boolean;
263
+ /**
264
+ * Whether the template renders role=tool messages (tool/function execution results) back into the prompt context.
265
+ *
266
+ * @remarks
267
+ * - true: The model can see tool outputs (often near the next assistant generation).
268
+ * - false: Tool results aren’t visible; inject them as user/system text instead, or update the template to render tool messages.
269
+ *
270
+ * @impact
271
+ * - Critical for the standard call→execute→return→answer loop to converge.
272
+ */
273
+ supportsToolResponses: boolean;
274
+ /**
275
+ * Whether the template surfaces `tool_call_id` when rendering role=tool results, enabling strict mapping back to the call.
276
+ *
277
+ * @remarks
278
+ * - true: Each tool output can be visibly tied to its originating call (important for multi-call turns).
279
+ * - false: The mapping is implicit; include the call id in the text or restrict to single calls per turn.
280
+ *
281
+ * @impact
282
+ * - Strongly recommended when parallel/multiple tool calls are possible.
283
+ */
284
+ supportsToolCallId: boolean;
285
+ /**
286
+ * Whether the template forbids `assistant.content` being `null` (requires an empty string instead).
287
+ *
288
+ * @remarks
289
+ * - true: Use `content: ""` as a placeholder when the assistant turn only carries `tool_calls`.
290
+ * - false: `null` or `""` both work.
291
+ *
292
+ * @impact
293
+ * - Prevents template branches from swallowing messages when content is `null`.
294
+ */
295
+ requiresNonNullContent: boolean;
296
+ /**
297
+ * A generated “how to call a tool” example snippet, inferred only when the template doesn’t render the tools catalog.
298
+ *
299
+ * @remarks
300
+ * - Present when {@link ChatTemplateCaps.supportsTools} is false and the probe could
301
+ * derive a stable example by diffing “prefix only” vs “prefix + a fake tool call”.
302
+ * - Useful to inject into the template/system text to teach the expected call format.
303
+ *
304
+ * @example
305
+ * if (!caps.supportsTools && caps.toolCallExample) {
306
+ * system += "\n\nTool call example:\n" + caps.toolCallExample;
307
+ * }
308
+ */
309
+ toolCallExample?: string;
310
+ };
138
311
 
139
312
  type PromptExamples<T = any> = Iterable<PromiseLike<T> | T> | AsyncIterable<T>;
140
313
  interface PromptExampleSelectorOptions {
@@ -253,7 +426,7 @@ declare class FewShotPromptTemplate<T = any> extends StringTemplate {
253
426
  static from<T = any>(options: FewShotPromptTemplateOptions<T>): FewShotPromptTemplate<T>;
254
427
  constructor(options: FewShotPromptTemplateOptions<T>);
255
428
  _initialize(options?: FewShotPromptTemplateOptions<T>): void;
256
- _format(data: Record<string, any>): Promise<string>;
429
+ _format(data: Record<string, any>): Promise<any>;
257
430
  toJSON(options?: this): FewShotPromptTemplateOptions<T>;
258
431
  }
259
432
 
@@ -338,18 +511,6 @@ declare function splitParagraph(value: string, options?: SplitSentenceOptions):
338
511
  */
339
512
  declare function truncTo(n: number, dec?: number, up?: number): number;
340
513
 
341
- /**
342
- * Suspends execution for a specified number of milliseconds
343
- * @param ms - The number of milliseconds to pause execution
344
- * @example
345
- * ```ts
346
- * await sleep(500); // Pause for half a second
347
- * ```
348
- * @remarks
349
- * This implementation uses `setTimeout` under the hood and is more precise
350
- * for longer durations than `setImmediate`-based approaches
351
- */
352
- declare function sleep(ms: number): Promise<void>;
353
514
  /**
354
515
  * @alias sleep
355
516
  * @deprecated Use {@link sleep} for clearer intent
@@ -358,154 +519,6 @@ declare function sleep(ms: number): Promise<void>;
358
519
  * Prefer the more explicit `sleep` naming in new code.
359
520
  */
360
521
  declare const wait: typeof sleep;
361
- /**
362
- * Yields execution control to the event loop, allowing pending I/O operations
363
- * and scheduled tasks to run before continuing.
364
- *
365
- * @remarks
366
- * This method creates a microtask checkpoint using `setImmediate`, which helps:
367
- * - Interleave CPU-intensive work with I/O events
368
- * - Prevent event loop blocking
369
- * - Maintain application responsiveness
370
- *
371
- * Particularly useful for breaking up long synchronous operations in Node.js.
372
- */
373
- declare function yieldExec(): Promise<void>;
374
-
375
- declare const EventName = "event";
376
- declare const EventBusName = "event-bus";
377
- type EventListenerFn = (this: Event, name: string, ...args: any) => any;
378
- type EventErrorListenerFn = (this: Event, err: Error, name: string, ...args: any) => any;
379
- declare function getEventableClass(Backend: any, options?: {
380
- eventBusName?: string;
381
- }): {
382
- new (): {
383
- name: string;
384
- _events: any;
385
- readonly emitter: any;
386
- on(eventName: string, listener: EventListenerFn): EventEmitter | void;
387
- once(eventName: string, listener: EventListenerFn): EventEmitter | void;
388
- off(type: string, listener: EventListenerFn): EventEmitter;
389
- emit(eventName: string, ...args: any[]): any;
390
- emitError(err: any, ...args: any[]): any;
391
- emitAsync(eventName: string, ...args: any[]): Promise<any>;
392
- };
393
- _emitter: any;
394
- readonly emitter: any;
395
- };
396
- declare const backendEventable: <T extends Function | (new (...args: any[]) => any)>(targetClass?: T | undefined, options?: custom_ability.AbilityOptions) => T & typeof getEventableClass & (T extends new (...args: any[]) => any ? InstanceType<T> : T);
397
-
398
- type Events = (string | RegExp)[];
399
- /**
400
- * Represents a client connected to the SSE channel.
401
- */
402
- type SSEClient = {
403
- /** The incoming HTTP request from the client. */
404
- req: IncomingMessage;
405
- /** The server response object used to send events to the client. */
406
- res: ServerResponse;
407
- /** An array of event names or patterns that the client is subscribed to. */
408
- events?: Events;
409
- /**
410
- * A unique identifier for the client.
411
- */
412
- clientId: string;
413
- };
414
- declare const SSEChannelAlreadyClosedErrCode = 498;
415
- /**
416
- * A class for creating Server-Sent Events (SSE) channels.
417
- * @example
418
- * const sseChannel = new SSEChannel({ pingInterval: 5000 })
419
- * sseChannel.publish('Hello, world!', 'greeting')
420
- */
421
- declare class SSEChannel {
422
- _active: boolean;
423
- clients: Map<string, SSEClient>;
424
- messages: Record<string, any>[];
425
- nextID: number;
426
- options: Record<string, any>;
427
- pingTimer?: NodeJS.Timeout;
428
- /**
429
- * Gets the active status of the channel.
430
- * @returns True if the channel is active, false otherwise.
431
- */
432
- get active(): boolean;
433
- set active(v: boolean);
434
- /**
435
- * Creates a new SSE channel.
436
- * @param options - The options for the SSE channel.
437
- * @param options.pingInterval - Interval in milliseconds to send ping messages (default: 3000).
438
- * @param options.maxStreamDuration - Maximum duration of a client connection in milliseconds (default: 30000).
439
- * @param options.clientRetryInterval - Interval in milliseconds for clients to retry connection (default: 1000).
440
- * @param options.startId - Starting ID for messages (default: 1).
441
- * @param options.historySize - Maximum number of messages to keep in history (default: 100).
442
- * @param options.rewind - Number of historical messages to send to new clients (default: 0).
443
- * @param options.cors - Whether to enable CORS headers (default: false).
444
- */
445
- constructor(options?: Record<string, any>);
446
- /**
447
- * Publishes data to the channel.
448
- *
449
- * @param data The data to send. Can be a string or a serializable object.
450
- * @param eventName Optional name for the event.
451
- * @param target Optional. If provided, the message will be sent only to clients with matching `clientId`s, bypassing event subscriptions.
452
- * @returns The ID of the message, or `undefined` if no message was sent.
453
- * @throws An error if the channel is closed.
454
- */
455
- publish(data?: string | Record<string, any>, eventName?: string, target?: {
456
- clientId?: string | string[];
457
- }): number | undefined;
458
- /**
459
- * Adds event subscriptions to an active client.
460
- * @param clientId The ID of the client to modify.
461
- * @param events An array of event names or patterns to add.
462
- * @returns `true` if the client was found and updated, otherwise `false`.
463
- */
464
- subscribe(clientId: string, events: Events): boolean;
465
- /**
466
- * Removes event subscriptions from an active client.
467
- * @param clientId The ID of the client to modify.
468
- * @param events An array of event names or patterns to remove.
469
- * @returns `true` if the client was found and updated, otherwise `false`.
470
- */
471
- unsubscribe(clientId: string, events: Events): boolean;
472
- /**
473
- * Finds a client instance by its unique ID.
474
- * @param clientId The unique ID of the client.
475
- * @returns The matching SSEClient, or undefined if not found.
476
- */
477
- getClient(clientId: string): SSEClient | undefined;
478
- /**
479
- * Establishes a new SSE connection with a client and adds it to the channel.
480
- *
481
- * @param req The incoming HTTP request from the client.
482
- * @param res The server response object used to send events to the client.
483
- * @param events An array of event names or patterns that the client wants to subscribe to.
484
- * @param clientId An optional unique identifier for the client. If not provided, one will be generated based on the client's IP and port.
485
- * @returns The newly created client object representing the connected client.
486
- * @throws An error if the channel is closed or if a client ID cannot be determined.
487
- */
488
- connect(req: IncomingMessage, res: ServerResponse, events?: Events, clientId?: string): SSEClient;
489
- /**
490
- * Disconnects a client from the SSE channel and cleans up resources.
491
- * @param c - The client to disconnect.
492
- */
493
- disconnect(c: SSEClient): void;
494
- /**
495
- * Disconnects all clients from the SSE channel.
496
- */
497
- clearClients(): void;
498
- /**
499
- * Lists the clients connected to the SSE channel grouped by IP address.
500
- * @returns - Returns an object where the keys are the IP addresses and the values are the number of clients connected from each IP.
501
- */
502
- listClients(): Record<string, number>;
503
- /**
504
- * Gets the number of clients subscribed to the SSE channel.
505
- * @returns - Returns the number of clients.
506
- */
507
- getSubscriberCount(): number;
508
- }
509
522
 
510
523
  declare function isWebStream(val: any): val is ReadableStream<any> | WritableStream<any>;
511
524
 
@@ -590,94 +603,6 @@ declare function AIStream<T = any, TOptions = any>(response: Response, customPar
590
603
  */
591
604
  declare function readableFromAsyncIterable<T>(iterable: AsyncIterable<T>): ReadableStream<T>;
592
605
 
593
- /**
594
- * Configuration options and helper callback methods for stream lifecycle events.
595
- * @interface
596
- */
597
- interface StreamCallbacksAndOptions<I = any, O = any> {
598
- /** `onStart`: Called once when the stream is initialized. */
599
- onStart?: (controller: TransformStreamDefaultController) => Promise<void> | void;
600
- /** `onToken`: Called for each tokenized message. */
601
- onTransform?: (chunk: I, controller: TransformStreamDefaultController) => Promise<O | void> | O | void;
602
- /** `onFinal`: Called once when the stream is closed with the final completion message. */
603
- onFinal?: (controller: TransformStreamDefaultController) => Promise<void> | void;
604
- onError?: (error: Error) => Promise<void> | void;
605
- }
606
- /**
607
- * Creates a transform stream that invokes optional callback functions.
608
- * The transform stream uses the provided callbacks to execute custom logic at different stages of the stream's lifecycle.
609
- * - `onStart`: Called once when the stream is initialized.
610
- * - `onTransform`: Called for each tokenized message.
611
- * - `onCompletion`: Called every time an AIStream completion message is received. This can occur multiple times when using e.g. OpenAI functions
612
- * - `onFinal`: Called once when the stream is closed with the final completion message.
613
- *
614
- * This function is useful when you want to process a stream of messages and perform specific actions during the stream's lifecycle.
615
- *
616
- * @param [callbacks] - An object containing the callback functions.
617
- * @return A transform stream that encodes input messages as Uint8Array and allows the execution of custom logic through callbacks.
618
- *
619
- * @example
620
- * const callbacks = {
621
- * onStart: async () => console.log('Stream started'),
622
- * onTransform: async (chunk) => console.log('Token:',chunk),
623
- * onFinal: async () => data.close()
624
- * };
625
- * const transformer = createCallbacksTransformer(callbacks);
626
- */
627
- declare function createCallbacksTransformer<I = any, O = any>(cb: StreamCallbacksAndOptions<I, O> | undefined): TransformStream<I, O>;
628
-
629
- declare const uuids: {
630
- 1: typeof v1;
631
- 4: typeof v4;
632
- 5: typeof v5;
633
- 6: typeof v6;
634
- 7: typeof v7;
635
- };
636
- type UUIDVersions = keyof typeof uuids;
637
- /**
638
- * Generates a UUID (Universally Unique Identifier) based on the specified version and encoding options.
639
- *
640
- * @param encode - Whether to encode the generated UUID using Base32768 encoding. Defaults to `false`.
641
- *
642
- * @returns A string representing the generated UUID. If `encode` is `true`, the UUID will be encoded in Base32768 format.
643
- *
644
- * @example
645
- * // Generate an encoded UUID version 1 using Base32768
646
- * const encodedUuid1 = uuid(true);
647
- */
648
- declare function uuid(encode?: boolean): string;
649
-
650
- declare enum HashAlgorithm {
651
- md5 = 1,
652
- sha1 = 2,
653
- ripemd = 3,
654
- sha256 = 8,
655
- sha384 = 9,
656
- sha512 = 10,
657
- sha224 = 11,
658
- xxhash = 111,
659
- xxhash64 = 111,
660
- xxhash32 = 112,
661
- xxhash128 = 113
662
- }
663
-
664
- declare function xxhash32(value: string | object, radix?: number): string;
665
- declare function xxhash64(value: string | object, radix?: number): string;
666
- type HashValue = string | ArrayBuffer | Buffer;
667
- declare function xxhash(value: HashValue, hashAlgo?: HashAlgorithm, seed?: number): Uint8Array;
668
- declare function xxhashAsStr(value: string | Uint8Array, hashAlgo?: HashAlgorithm, seed?: number): string;
669
-
670
- declare const base32768: typeof _base32768;
671
-
672
- interface HashAlgoParams {
673
- hashAlgo?: HashAlgorithm;
674
- seed?: number;
675
- outputType?: 'hex' | 'binary' | 'string';
676
- }
677
- declare function hashStream(stream: ReadableStream, { hashAlgo, seed, outputType }?: HashAlgoParams): Promise<string | Uint8Array<ArrayBufferLike>>;
678
- declare function hash(value: IDataType, { hashAlgo, seed, outputType }?: HashAlgoParams): Promise<string | Uint8Array<ArrayBufferLike>>;
679
- declare function hashObject(value: any, options?: HashAlgoParams): Promise<string | Uint8Array<ArrayBufferLike>>;
680
-
681
606
  /**
682
607
  * Checks if the provided model name matches the given rule.
683
608
  * @param modelName The name of the model to check.
@@ -912,205 +837,521 @@ declare function textToDate(date: string, format?: string): Date;
912
837
  declare function dateToText(date: Date, format?: string): string;
913
838
 
914
839
  /**
915
- * Represents a set of integers using a bit field.
916
- * Each bit in the bit field represents an integer starting from 0,
917
- * where the flag value 0 represents the 0th bit, 1 represents the 1st bit, and so on.
840
+ * Counts the number of matches for a given regular expression in a specified string.
841
+ * This function ensures that the regular expression is used globally by adding the 'g' flag,
842
+ * if it is not already present.
843
+ *
844
+ * @param content - The string to search within.
845
+ * @param regex - The regular expression to use for matching.
846
+ * @returns The total number of matches found.
847
+ */
848
+ declare function countRegexMatches(content: string, regex: RegExp): number;
849
+
850
+ /**
851
+ * Lexical analyzer for command arguments.
852
+ * Responsible for breaking down the raw input string into a sequence of basic tokens.
918
853
  */
919
- declare class IntSet {
920
- private bitField;
921
- static has(bitField: number, flag: number): boolean;
922
- static add(bitField: number, flag: number): number;
923
- static delete(bitField: number, flag: number): number;
924
- constructor(bitField?: number);
854
+ declare class CmdArgLexer {
855
+ input: string;
856
+ private pos;
857
+ private delimiter;
858
+ private assigner;
859
+ constructor(input: string, options?: CmdArgParserOptions);
925
860
  /**
926
- * Adds an element to the set.
927
- *
928
- * @param flag - The flag value representing the bit position to set.
929
- * Note: the flag value 0 represents the 0th bit, and so on.
861
+ * Peeks at the next CmdArgToken without consuming it.
930
862
  */
931
- add(flag: number): this;
863
+ peekToken(): CmdArgToken;
932
864
  /**
933
- * Removes an element from the set.
934
- *
935
- * @param flag - The flag value representing the bit position to set. 0 represents the 0th bit
865
+ * Retrieves the next CmdArgToken and advances the position pointer.
936
866
  */
937
- delete(flag: number): this;
867
+ nextToken(): CmdArgToken;
938
868
  /**
939
- * Determines whether an element is in the set.
869
+ * Reads a quoted string with escape support.
870
+ */
871
+ private readString;
872
+ /**
873
+ * Reads a raw text segment.
874
+ */
875
+ private readRaw;
876
+ private skipWhitespace;
877
+ reset(): void;
878
+ }
879
+
880
+ /**
881
+ * Structured command argument CmdArgParser.
882
+ * Supports positional arguments, named arguments (k=v), nested structures,
883
+ * and Symbol-based extension protocols.
884
+ */
885
+ declare class CmdArgParser {
886
+ private lexer;
887
+ private options;
888
+ constructor(lexer: CmdArgLexer, options?: CmdArgParserOptions);
889
+ /**
890
+ * Executes the parsing process.
940
891
  *
941
- * @param flag - The flag value representing the bit position to set. 0 represents the 0th bit
942
- * @returns true if the element is in the set; otherwise, false.
892
+ * Core logic priority:
893
+ * 1. Collect top-level arguments (respecting bracket nesting depth).
894
+ * 2. Identify explicit named arguments (k=v) or flag shorthands.
895
+ * 3. Pre-check if a positional argument fits identifier/path format for auto-mapping.
896
+ * 4. Invoke Evaluator to get the value and unpack any Symbol Protocols.
897
+ * 5. Distribute results to 'args' and 'namedArgs', maintaining index consistency.
898
+ */
899
+ parse(): Promise<CmdArgParseResult>;
900
+ /**
901
+ * Collects tokens until a top-level delimiter is encountered.
902
+ */
903
+ private collectUntilDelimiter;
904
+ /**
905
+ * Attempts to split a named key (k=v) or flag (!k=v) from the CmdArgToken sequence.
943
906
  */
944
- has(flag: number): boolean;
907
+ private splitNamedArgument;
908
+ private isLeftBracket;
909
+ private isRightBracket;
945
910
  /**
946
- * Clears all elements from the set.
911
+ * Consumes the current delimiter CmdArgToken.
947
912
  */
948
- clear(): this;
949
- valueOf(): number;
950
- toString(): string;
951
- toJSON(): number;
913
+ private consumeDelimiter;
952
914
  }
953
915
 
954
916
  /**
955
- * An asynchronous signal gate that blocks operations until a signal is emitted.
956
- * This class allows multiple awaiters to wait for a signal and resolves all pending promises with the emitted value.
957
- * The gate can be reset to reuse for subsequent signals.
917
+ * Symbol used to mark a result object returned by an ArgProcessor.
918
+ * The processor should return an object where this Symbol is the key.
958
919
  *
959
920
  * @example
921
+ * ```ts
922
+ * return {
923
+ * [CMD_ARG_PROCESSOR_RESULT]: [parsedValue, 'suggestedName', { excludePositional: true }]
924
+ * };
925
+ * ```
926
+ */
927
+ declare const CMD_ARG_PROCESSOR_RESULT: unique symbol;
928
+ /**
929
+ * Internal Symbol used to mark values that have fallen back to their raw string
930
+ * representation due to a ReferenceError (undefined variable).
931
+ * This allows the CmdArgParser to distinguish between a deliberate string "undefined"
932
+ * and a failed variable lookup.
933
+ */
934
+ declare const CMD_ARG_UNRESOLVED_SYMBOL: unique symbol;
935
+ /**
936
+ * Symbol used to mark special parameters (Flags) in a wrapped object.
937
+ * Stored as a non-enumerable property on the wrapped value (e.g., Boolean, String).
960
938
  *
961
- * ```typescript
962
- * // Default type is void, can call signal() without parameters
963
- * const gate = new SignalGate();
964
- * gate.signal(); // No parameters required
965
- *
966
- * // Example with explicit type
967
- * const valueGate = new SignalGate<number>();
968
- * valueGate.signal(42); // Must provide a number value
939
+ * @example
940
+ * ```ts
941
+ * const CmdArgFlagValue = flags['debug'];
942
+ * const prefix = CmdArgFlagValue[CMD_ARG_FLAG_SYMBOL]; // returns '!'
969
943
  * ```
970
944
  */
971
- declare class SignalGate<T = void> {
972
- protected _isSignaled: boolean;
973
- protected _signalValue: T | undefined;
974
- protected waitQueue: Array<{
975
- resolve: (value: T) => void;
976
- reject: (error: any) => void;
977
- }>;
978
- get signaled(): boolean;
945
+ declare const CMD_ARG_FLAG_SYMBOL: unique symbol;
946
+ /**
947
+ * Metadata attached to flag values.
948
+ */
949
+ interface CmdArgFlagMetadata {
950
+ /** The prefix used to define this flag (e.g., '!', '#') */
951
+ [CMD_ARG_FLAG_SYMBOL]: string;
952
+ }
953
+ /**
954
+ * A flag value is a wrapped primitive (Boolean, String, Number) or object
955
+ * that carries its prefix metadata via CMD_ARG_FLAG_SYMBOL.
956
+ */
957
+ type CmdArgFlagValue = (Boolean | String | Number | any) & CmdArgFlagMetadata;
958
+ /**
959
+ * A map of flag names to their wrapped values.
960
+ */
961
+ type CmdArgFlagsRecord = Record<string, CmdArgFlagValue>;
962
+ /**
963
+ * CmdArgToken types for lexical analysis.
964
+ */
965
+ declare enum CmdArgTokenType {
966
+ EOF = "EOF",
967
+ /** Argument delimiter (default: ',') */
968
+ COMMA = "COMMA",
969
+ /** Assignment operator (default: '=' or ':') */
970
+ ASSIGN = "ASSIGN",
971
+ /** Left parenthesis '(' */
972
+ L_PAREN = "L_PAREN",
973
+ /** Right parenthesis ')' */
974
+ R_PAREN = "R_PAREN",
975
+ /** Left square bracket '[' */
976
+ L_BRACKET = "L_BRACKET",
977
+ /** Right square bracket ']' */
978
+ R_BRACKET = "R_BRACKET",
979
+ /** Left curly brace '{' */
980
+ L_BRACE = "L_BRACE",
981
+ /** Right curly brace '}' */
982
+ R_BRACE = "R_BRACE",
983
+ /** Quoted string "..." or '...' or `...` */
984
+ STRING = "STRING",
985
+ /** Valid JS identifier (excluding reserved words like true/false) */
986
+ IDENTIFIER = "IDENTIFIER",
987
+ /** Raw text segment, used for expressions or unquoted strings */
988
+ RAW = "RAW"
989
+ }
990
+ /**
991
+ * Represents a lexical CmdArgToken with its type, value, and source position.
992
+ */
993
+ interface CmdArgToken {
994
+ /** The type of the CmdArgToken */
995
+ type: CmdArgTokenType;
996
+ /** The literal string value of the CmdArgToken */
997
+ value: string;
998
+ /** Starting index in the input string */
999
+ start: number;
1000
+ /** Ending index in the input string */
1001
+ end: number;
1002
+ }
1003
+ /**
1004
+ * Options for processors to control how the parsed value is distributed in the final result.
1005
+ */
1006
+ interface CmdArgProcessorResultOptions {
979
1007
  /**
980
- * Emits the signal with an optional value, resolving all pending {@link wait} promises.
981
- * Subsequent calls have no effect until {@link reset} is called.
982
- *
983
- * @param value The value to emit with the signal (only required if T is not void).
1008
+ * If true, the argument will be excluded from the positional `args` array.
1009
+ * Useful when a positional argument is intended to be treated as a named parameter only.
984
1010
  */
985
- signal(value?: T): void;
1011
+ excludePositional?: boolean;
1012
+ }
1013
+
1014
+ /**
1015
+ * Symbol used to mark a result object returned by an ArgProcessor.
1016
+ ...
1017
+ */
1018
+ interface CmdArgContext {
1019
+ /** True if the argument was explicitly assigned using an assigner (e.g., k=v) */
1020
+ isNamed: boolean;
1021
+ /** The raw input substring of this argument (after stripping the name and assigner if present) */
1022
+ rawValue: string;
1023
+ /** The explicitly specified name (k) in a `k=v` pair */
1024
+ name?: string;
986
1025
  /**
987
- * Resets the gate to its initial state, allowing a new signal to be emitted.
1026
+ * If the argument is positional and its raw text is a valid identifier,
1027
+ * this holds that identifier name (used for auto-mapping).
988
1028
  */
989
- reset(): void;
1029
+ identifierAsName?: string;
1030
+ /** All lexical tokens belonging to this argument */
1031
+ tokens: CmdArgToken[];
1032
+ /** The 0-based index of this argument in the positional sequence */
1033
+ index: number;
1034
+ /** The evaluation scope containing variables and functions */
1035
+ scope?: Record<string, any>;
1036
+ /** The configuration options used by the CmdArgParser */
1037
+ options: CmdArgParserOptions;
1038
+ /** Reference to the CmdArgParser instance for recursive parsing */
1039
+ CmdArgParser: CmdArgParser;
1040
+ }
1041
+ /**
1042
+ * Type definition for an argument processor function.
1043
+ * It can return a plain value (for standard evaluation) or a Protocol-compliant object.
1044
+ */
1045
+ type ArgProcessor = (ctx: CmdArgContext) => any | Promise<any>;
1046
+ /**
1047
+ * Detailed configuration for result simplification (convergence).
1048
+ */
1049
+ interface CmdArgSimplifyOptions {
990
1050
  /**
991
- * Aborts all pending waits, rejecting their promises with an error.
992
- * This does **not** reset the signal state (the gate remains signaled or unsignaled).
993
- *
994
- * @param reason The reason for aborting the waits.
1051
+ * [Single Value Simplification]
1052
+ * If there is exactly one positional argument and no named arguments, return the value directly.
1053
+ * @example parse("123") -> 123 (instead of [123])
1054
+ * @default true
1055
+ */
1056
+ singleValue?: boolean;
1057
+ /**
1058
+ * [Identical Pair Singularization]
1059
+ * If there are exactly two entries (index 0 and a named key) and their values are identical,
1060
+ * collapse them into a single value. This often happens when `idAsName` is enabled.
1061
+ * @example parse("name=John") -> "John" (instead of {0: "John", name: "John"})
1062
+ * @default true
995
1063
  */
996
- abort(reason?: any): void;
1064
+ identicalPairSingular?: boolean;
997
1065
  /**
998
- * Returns a promise that resolves with the emitted signal value.
999
- * If called after the signal has been emitted, resolves immediately with the stored value.
1066
+ * [Pure Positional as Array]
1067
+ * If there are multiple positional arguments and no named arguments, return a pure array.
1068
+ * @example parse("1, 2, 3") -> [1, 2, 3] (instead of {0: 1, 1: 2, 2: 3})
1069
+ * @default true
1070
+ */
1071
+ purePositionalAsArray?: boolean;
1072
+ /**
1073
+ * [Output Mode]
1074
+ * - 'auto': Apply the simplification flags above (default).
1075
+ * - 'array': Always return an array of positional args. Named args are hidden in the '.namedArgs' property.
1076
+ * - 'object': Always return a merged object with both numeric and string keys.
1077
+ * - 'map': Always return the full structure { args: [], namedArgs: {}, flags: {} }.
1078
+ * @default 'auto'
1079
+ */
1080
+ mode?: 'auto' | 'array' | 'object' | 'map';
1081
+ }
1082
+ /**
1083
+ * Configuration options for the CmdArgParser and main API functions.
1084
+ */
1085
+ interface CmdArgParserOptions {
1086
+ /**
1087
+ * Character used to separate arguments.
1088
+ * @example delimiter: ';' -> "arg1; arg2"
1089
+ * @default ','
1090
+ */
1091
+ delimiter?: string;
1092
+ /**
1093
+ * Character used for name-value assignment.
1094
+ * @example assigner: ':' -> "key:value"
1095
+ * @default '='
1096
+ */
1097
+ assigner?: string;
1098
+ /**
1099
+ * Prefix(es) for special parameters (Flags).
1100
+ * @example flagPrefix: '!' -> "!debug, !verbose=false"
1101
+ */
1102
+ flagPrefix?: string | string[];
1103
+ /** Custom logic to process each argument before standard evaluation */
1104
+ argProcessor?: ArgProcessor;
1105
+ /** Format used by TemplateArgProcessor (e.g., 'mustache') */
1106
+ templateFormat?: string;
1107
+ /** Additional data for template variable substitution */
1108
+ templateData?: Record<string, any>;
1109
+ /**
1110
+ * If true, the positional index of an argument that has been automatically
1111
+ * mapped as a named argument (via `idAsName`) will be excluded from the
1112
+ * merged result object.
1000
1113
  *
1001
- * @returns A promise resolving to the signal value (type T).
1114
+ * @example parse("John") -> {John: "John"} (instead of {0: "John", John: "John"})
1115
+ */
1116
+ excludeAutoNamedFromPositional?: boolean;
1117
+ /** If true, return the variable name as a string when it's not found in scope instead of undefined */
1118
+ preserveUnresolvedName?: boolean;
1119
+ /**
1120
+ * If true, explicitly named arguments (e.g., `k=v`) do not occupy a slot
1121
+ * in the positional `args` array.
1122
+ * @default true
1002
1123
  */
1003
- wait(): Promise<T>;
1124
+ namedExcludePositional?: boolean;
1125
+ /**
1126
+ * If true, a positional argument that is a valid identifier (e.g., "John")
1127
+ * is automatically mapped as a named argument (e.g., {John: "John"}).
1128
+ * @default true
1129
+ */
1130
+ idAsName?: boolean;
1131
+ /** If true, JS expressions (like arithmetic or function calls) are not evaluated */
1132
+ skipExpression?: boolean;
1133
+ /** Control the simplification of the final result. Set to `false` to disable (returns a merged object). */
1134
+ simplify?: boolean | CmdArgSimplifyOptions;
1135
+ /** If true, any parsing or evaluation error will be thrown */
1136
+ raiseError?: boolean;
1137
+ /** If true, ReferenceErrors (missing variables) will be thrown. Defaults to `raiseError`. */
1138
+ raiseReferenceError?: boolean;
1139
+ /** An object containing variables accessible to expressions in the input string */
1140
+ scope?: Record<string, any>;
1141
+ /** @internal Used to prevent infinite recursion in internal calls */
1142
+ isInternal?: boolean;
1004
1143
  }
1005
-
1006
1144
  /**
1007
- * Counts the number of matches for a given regular expression in a specified string.
1008
- * This function ensures that the regular expression is used globally by adding the 'g' flag,
1009
- * if it is not already present.
1145
+ * Configuration for AI selection logic (used by ChoiceArgProcessor).
1010
1146
  *
1011
- * @param content - The string to search within.
1012
- * @param regex - The regular expression to use for matching.
1013
- * @returns The total number of matches found.
1147
+ * @example "|item1|item2:maxPick=2"
1014
1148
  */
1015
- declare function countRegexMatches(content: string, regex: RegExp): number;
1016
-
1017
- type ArgInfo = [boolean, string];
1018
- type ArgProcessor = (arg: ArgInfo, ix: number, scope?: Record<string, any>, options?: ParseObjectArgumentOptions) => string | void | Promise<string | void>;
1019
- interface AIChoiceConfig {
1149
+ interface CmdArgAIChoiceConfig {
1150
+ /** List of items to choose from */
1020
1151
  items?: string[];
1152
+ /** Maximum number of items that can be picked */
1021
1153
  maxPick?: number;
1154
+ /** Minimum number of items that must be picked */
1022
1155
  minPick?: number;
1156
+ /** Separator for the resulting choice string */
1023
1157
  separator?: string;
1158
+ /** Prefix to add to the result */
1024
1159
  prefix?: string;
1160
+ /** Suffix to add to the result */
1161
+ suffix?: string;
1162
+ /** Selection strategy: 'random' for random pick, 'ai' for AI-assisted pick */
1025
1163
  type?: 'random' | 'ai';
1164
+ /** Closing character/string for the selection UI */
1026
1165
  end?: string;
1027
1166
  }
1028
- interface ParseObjectArgumentOptions {
1029
- delimiter?: string;
1030
- assigner?: string;
1031
- argProcessor?: ArgProcessor;
1032
- returnArrayOnly?: boolean;
1033
- templateFormat?: string;
1034
- templateData?: Record<string, any>;
1035
- ignoreIndexNamed?: boolean;
1036
- preserveUnresolvedName?: boolean;
1037
- skipExpression?: boolean;
1038
- raiseError?: boolean;
1167
+ /**
1168
+ * The internal structured result of the parsing process.
1169
+ */
1170
+ interface CmdArgParseResult {
1171
+ /** Positional arguments array. Indices correspond to the appearance order. */
1172
+ args: any[];
1173
+ /** Named arguments map, combining explicit `k=v`, auto-mapped IDs, and Processor results. */
1174
+ namedArgs: Record<string, any>;
1175
+ /** Special parameters (Flags) map. Values are usually Boolean but can be any type. */
1176
+ flags: CmdArgFlagsRecord;
1177
+ /** A set of numeric indices that were populated by explicitly named arguments. */
1178
+ namedIndices: Set<number>;
1179
+ }
1180
+ /**
1181
+ * Simplified argument result.
1182
+ * Could be a single value, an array, or an object based on CmdArgSimplifyOptions.
1183
+ */
1184
+ type SimplifiedResultType = any;
1185
+ /**
1186
+ * Result structure when mode is 'map'.
1187
+ */
1188
+ interface CmdArgMapResult {
1189
+ /** Positional arguments array */
1190
+ args: any[];
1191
+ /** Named arguments map */
1192
+ namedArgs: Record<string, any>;
1193
+ /** Special parameters (Flags) map */
1194
+ flags?: CmdArgFlagsRecord;
1195
+ }
1196
+ /**
1197
+ * The full structure of a parsed command.
1198
+ */
1199
+ interface CmdArgParsedCommand {
1200
+ /** The command name (the identifier before the parentheses) */
1201
+ command: string;
1202
+ /** The parsed arguments, either simplified or in map format */
1203
+ args: SimplifiedResultType | CmdArgMapResult;
1204
+ /** Special parameters (Flags) map (if present) */
1205
+ flags?: CmdArgFlagsRecord;
1206
+ }
1207
+ /**
1208
+ * Normalized argument information, typically used for final consumption.
1209
+ */
1210
+ interface CmdArgArgsInfo {
1211
+ /** Positional arguments array */
1212
+ args: any[];
1213
+ /** Named arguments map */
1214
+ namedArgs?: Record<string, any>;
1039
1215
  }
1216
+
1217
+ /**
1218
+ * Evaluates the value of an argument.
1219
+ *
1220
+ * Priority:
1221
+ * 1. Attempt to call a custom processor (ArgProcessor).
1222
+ * 2. If the processor returns a source string, recursively call evaluateExpression.
1223
+ * 3. Default to evaluateExpression (handles literals, scope variables, and JS expressions).
1224
+ */
1225
+ declare function cmdArgEvaluate(ctx: CmdArgContext): Promise<any>;
1226
+ /**
1227
+ * Evaluates an expression string to its value.
1228
+ *
1229
+ * Logic sequence:
1230
+ * 1. Check if evaluation should be skipped.
1231
+ * 2. Match simple JS literals (true, false, null, undefined, NaN, Infinity).
1232
+ * 3. Check if it's a number.
1233
+ * 4. Perform path lookup in the scope (getByPath).
1234
+ * 5. Attempt execution as a JS expression or arrow function.
1235
+ * 6. Catch ReferenceError: Decide whether to fall back to raw text or return undefined based on options.
1236
+ * 7. Final fallback: Handle unquoting for quoted strings.
1237
+ */
1238
+ declare function evaluateExpression(code: string, scope: any, options: CmdArgParserOptions): Promise<any>;
1239
+
1240
+ /**
1241
+ * Choice argument processor (ChoiceArgProcessor).
1242
+ *
1243
+ * Syntax: |item1|item2:maxPick=2:separator=";"
1244
+ *
1245
+ * Logic:
1246
+ * 1. Identifies positional arguments starting with '|'.
1247
+ * 2. Recursively uses the CmdArgParser to parse subsequent configuration items (delimited by ':').
1248
+ * 3. Constructs an CmdArgAIChoiceConfig object.
1249
+ * 4. Returns the result using the Symbol Protocol, named 'choice' and excluded from positional indexing.
1250
+ */
1251
+ declare function ChoiceArgProcessor(ctx: CmdArgContext): Promise<{
1252
+ [CMD_ARG_PROCESSOR_RESULT]: (string | CmdArgAIChoiceConfig | {
1253
+ excludePositional: boolean;
1254
+ })[];
1255
+ } | undefined>;
1256
+ /**
1257
+ * Template variable processor (TemplateArgProcessor).
1258
+ *
1259
+ * Syntax: msg="Hello {{name}}"
1260
+ *
1261
+ * Logic:
1262
+ * 1. Calls PromptTemplate.formatIf for variable substitution.
1263
+ * 2. If the substitution results in a bare string (no quotes and not JS literal source),
1264
+ * it is JSON-escaped to ensure it's recognized as a string literal in subsequent evaluation.
1265
+ * 3. Returns the substituted source string for re-evaluation by the Evaluator.
1266
+ */
1267
+ declare function TemplateArgProcessor(ctx: CmdArgContext): Promise<{
1268
+ [CMD_ARG_PROCESSOR_RESULT]: any[];
1269
+ } | undefined>;
1270
+ /**
1271
+ * Combined AI processor (AIArgProcessor).
1272
+ * Sequentially attempts choice selection and template variable processing.
1273
+ */
1274
+ declare function AIArgProcessor(ctx: CmdArgContext): Promise<{
1275
+ [CMD_ARG_PROCESSOR_RESULT]: (string | CmdArgAIChoiceConfig | {
1276
+ excludePositional: boolean;
1277
+ })[];
1278
+ } | undefined>;
1279
+
1040
1280
  /**
1041
- * Asynchronously parses a string of object arguments into an actual object.
1042
- * @param argsStr The string of arguments to be parsed.
1043
- * @param scope An optional scope object that provides values for variables during parsing.
1044
- * @param options An optional configuration object containing the delimiter and argument processor.
1045
- * @returns The parsed object or undefined.
1046
- *
1047
- * This function first parses the argument string into an object string and then converts it
1048
- * into a proper JavaScript/JSON object based on the parsing results and configuration options.
1049
- * It handles the conversion of single objects, arrays, and key-value pairs. The default delimiter
1050
- * between parameters is a comma (`,`), but this can be customized using the `options.delimiter`.
1051
- * Parameter assignment always uses an equal sign (`=`) and cannot be modified.
1052
- *
1053
- * The function returns:
1054
- * - An object if the input string represents a set of key-value pairs.
1055
- * - An array if the input string represents a sequence of elements, where each element can be
1056
- * parsed as a number (indices are used as keys).
1057
- * - A single value if the input string represents a single value or a single key-value pair.
1058
- * - `undefined` if the input string is empty or cannot be parsed into a valid object.
1281
+ * Parses an object-style argument string into a structured result.
1282
+ * Supports positional args, named args, JS expressions, and custom processors.
1283
+ *
1284
+ * @param argsStr The argument string to parse.
1285
+ * @param scope Optional evaluation scope for resolving variables.
1286
+ * @param options CmdArgParser configuration options.
1287
+ * @returns The parsed and simplified result.
1059
1288
  *
1060
1289
  * @example
1061
- * ```typescript
1062
- * // Example call with default delimiter
1063
- * const result = await parseObjectArguments("name=John,age=30");
1064
- * console.log(result); // Output: { name: 'John', age: '30' }
1290
+ * ```ts
1291
+ * // 1. Simple positional
1292
+ * await parseObjectArguments("123") // returns 123
1065
1293
  *
1066
- * // Example call with custom delimiter
1067
- * const resultCustomDelimiter = await parseObjectArguments("name=John|age=30", undefined, { delimiter: '|' });
1068
- * console.log(resultCustomDelimiter); // Output: { name: 'John', age: '30' }
1294
+ * // 2. Multiple positional
1295
+ * await parseObjectArguments("1, 2, 3") // returns [1, 2, 3]
1069
1296
  *
1070
- * // Example with a single value
1071
- * const singleValue = await parseObjectArguments("42");
1072
- * console.log(singleValue); // Output: 42
1297
+ * // 3. Named arguments
1298
+ * await parseObjectArguments("name='John', age=25") // returns {name: 'John', age: 25}
1073
1299
  *
1074
- * // Example with an array
1075
- * const arrayResult = await parseObjectArguments("1,2,3");
1076
- * console.log(arrayResult); // Output: [1, 2, 3]
1300
+ * // 4. Mixed (idAsName enabled by default)
1301
+ * await parseObjectArguments("John, age=25") // returns {0: 'John', John: 'John', age: 25}
1077
1302
  * ```
1078
1303
  */
1079
- declare function parseObjectArguments(argsStr: string, scope?: Record<string, any>, options?: ParseObjectArgumentOptions): Promise<any>;
1080
- declare function ObjectArgsToArgsInfo(args: any): {
1081
- args: any[];
1082
- kvArgs?: Record<string, any>;
1083
- };
1084
- declare function simplifyObjectArguments(args: any): any;
1085
- declare function parseObjectArgumentInfos(args: ArgInfo[], scope?: Record<string, any>, options?: ParseObjectArgumentOptions): Promise<any>;
1086
- declare function ChoiceArgProcessor(argInfo: ArgInfo, _ix: number, scope?: Record<string, any>, options?: ParseObjectArgumentOptions): string | undefined;
1087
- declare function TemplateArgProcessor([isNamedArg, arg]: ArgInfo, ix: number, scope?: Record<string, any>, options?: ParseObjectArgumentOptions): Promise<string | undefined>;
1088
- declare function AIArgProcessor(argInfo: ArgInfo, ix: number, scope?: Record<string, any>, options?: ParseObjectArgumentOptions): Promise<string | undefined>;
1089
- declare function isQuoted(s: string): boolean;
1090
- declare function isStrWrapped(s: string, pairs?: string[]): boolean;
1091
- declare function ensureQuoted(s: string, quoteChar?: string): string;
1092
- declare function quoteStr(str: string): string;
1093
- declare function parseObjectArgInfo(argInfo: ArgInfo, ix: number, scope?: Record<string, any>, options?: ParseObjectArgumentOptions): Promise<string>;
1304
+ declare function parseObjectArguments(argsStr: string, scope?: Record<string, any>, options?: CmdArgParserOptions): Promise<SimplifiedResultType | CmdArgMapResult | undefined>;
1094
1305
  /**
1095
- * Parses an object arguments string into an array of ArgInfo.
1306
+ * Merges parsing results into a single flattened object.
1307
+ * Numeric indices are used for positional arguments.
1096
1308
  *
1097
- * This function processes a parameter string and parses it according to specific rules, allowing for custom delimiters.
1098
- * It can handle quotes, escape characters, and expressions within brackets. The parsing is designed to interpret
1099
- * object literal strings from dynamic languages, such as JSON objects or similar custom formats.
1309
+ * @param result The raw parse result.
1310
+ * @param options CmdArgParser configuration options.
1311
+ * @returns A merged object containing all arguments.
1312
+ */
1313
+ declare function cmdArgsToMergedObject(result: CmdArgParseResult, options?: CmdArgParserOptions): Record<string | number, any>;
1314
+ /**
1315
+ * Simplifies the raw parsing result into a more intuitive format.
1316
+ * The behavior is controlled by `options.simplify`.
1100
1317
  *
1101
- * @param argsStr The string containing the arguments to be parsed.
1102
- * @param scope An optional scope object used for further processing of the parsed arguments. Default is undefined.
1103
- * @param options Parsing options, including:
1104
- * - delimiter: The character used to separate arguments. Default is ','.
1105
- * - argProcessor: An optional instance of ArgProcessor used for further processing of the parsed arguments.
1106
- * @returns An array of parsed argument information, where each item contains a boolean indicating whether the argument is named,
1107
- * and the string representation of the argument.
1318
+ * @param result The raw parse result.
1319
+ * @param options CmdArgParser configuration options.
1320
+ * @returns A simplified value, array, or object.
1108
1321
  */
1109
- declare function parseObjectArgumentsAsArgInfos(argsStr: string, scope?: Record<string, any>, options?: ParseObjectArgumentOptions): ArgInfo[];
1110
- declare function parseCommand(commandStr: string, scope?: Record<string, any>, options?: ParseObjectArgumentOptions): Promise<{
1111
- command: string;
1112
- args?: Record<string, any>;
1113
- } | undefined>;
1322
+ declare function simplifyResult(result: CmdArgParseResult, options?: CmdArgParserOptions): SimplifiedResultType | CmdArgMapResult;
1323
+ /**
1324
+ * Deeply simplifies object-style arguments (recursive convergence).
1325
+ * Useful for normalizing complex argument structures.
1326
+ */
1327
+ declare function simplifyObjectArguments(args: any): SimplifiedResultType;
1328
+ /**
1329
+ * Normalizes various simplified result formats back into an `{args, namedArgs}` info structure.
1330
+ *
1331
+ * @example
1332
+ * ```ts
1333
+ * ObjectArgsToArgsInfo("val") // returns {args: ["val"]}
1334
+ * ObjectArgsToArgsInfo([1, 2]) // returns {args: [1, 2]}
1335
+ * ObjectArgsToArgsInfo({name: "John"}) // returns {args: [], namedArgs: {name: "John"}}
1336
+ * ```
1337
+ */
1338
+ declare function ObjectArgsToArgsInfo(args: any): CmdArgArgsInfo;
1339
+ /**
1340
+ * Parses a full command string including the command name and its parenthesized arguments.
1341
+ *
1342
+ * @param commandStr The command string, e.g., 'myCmd(arg1, k=v, !flag)'
1343
+ * @param scope Evaluation scope.
1344
+ * @param options CmdArgParser configuration options.
1345
+ * @returns An object containing the command name, parsed args, and optional flags.
1346
+ *
1347
+ * @example
1348
+ * ```ts
1349
+ * await parseCommand("sum(1, 2)") // returns {command: "sum", args: [1, 2]}
1350
+ * await parseCommand("search(query='abc', !caseSensitive)") // returns {command: "search", args: {query: 'abc'}, flags: {caseSensitive: true}}
1351
+ * ```
1352
+ */
1353
+ declare function parseCommand(commandStr: string, scope?: Record<string, any>, options?: CmdArgParserOptions): Promise<CmdArgParsedCommand | undefined>;
1354
+
1114
1355
  interface ReplacePlacehoderOptions {
1115
1356
  startChar?: string | string[];
1116
1357
  endChar?: string | string[];
@@ -1118,36 +1359,60 @@ interface ReplacePlacehoderOptions {
1118
1359
  placehoders?: string[];
1119
1360
  }
1120
1361
  /**
1121
- * Replaces substrings in the given content with placeholders.
1122
- *
1123
- * @param content - The string content to process.
1124
- * @param options - Optional configuration object with the following properties:
1125
- * - `startChar` - The starting character(s) of the substrings to replace. Can be a single character or an array of characters. Defaults to `["\"", "'"]`.
1126
- * - `endChar` - The ending character(s) of the substrings to replace. Can be a single character or an array of characters. Defaults to the value of `startChar`.
1127
- * - `placeholder` - The prefix for the placeholder names. Defaults to `defaultPlaceholderName`.
1128
- * - `placehoders` - An array of placeholders to use instead of generating new one.
1129
- * @returns An array containing:
1130
- * - `content` - The modified content with placeholders.
1131
- * - `placehoders` - An array of the original substrings that were replaced.
1132
- * @throws {Error} If the lengths of `startChar` and `endChar` are not the same.
1362
+ * List of JS reserved words used to filter identifiers that should not be automatically mapped to names.
1363
+ */
1364
+ declare const RESERVED_WORDS: string[];
1365
+ /**
1366
+ * Unicode-aware JS identifier regex (ES2015+ u flag).
1367
+ * Allows $, _, and Unicode identifier start/continue characters.
1368
+ */
1369
+ declare const IDENTIFIER_REGEX: RegExp;
1370
+ /**
1371
+ * Regex for dot-separated path identifiers (e.g., test.a.b).
1372
+ */
1373
+ declare const PATH_IDENTIFIER_REGEX: RegExp;
1374
+ /**
1375
+ * Checks if a string is a valid JS identifier and not a reserved word.
1376
+ * Supports optional flag prefix stripping.
1377
+ */
1378
+ declare function isIdentifier(s: string, options?: {
1379
+ flagPrefix?: string | string[];
1380
+ }): boolean;
1381
+ /**
1382
+ * Wraps a value with a Flag Symbol.
1383
+ * For primitive types (Boolean, String, Number), uses wrapper objects to support
1384
+ * non-enumerable property attachment.
1385
+ */
1386
+ declare function wrapFlagValue(value: any, prefix: string): any;
1387
+ /**
1388
+ * Checks if a string is a valid path identifier (dot-separated identifiers).
1389
+ */
1390
+ declare function isPathIdentifier(s: string): boolean;
1391
+ /**
1392
+ * Checks if a string is wrapped in quotes (", ', `).
1393
+ * Leading and trailing whitespace are ignored.
1394
+ */
1395
+ declare function isQuoted(s: string): boolean;
1396
+ /**
1397
+ * Checks if a string is wrapped by specified character pairs.
1398
+ */
1399
+ declare function isStrWrapped(s: string, pairs?: string[]): boolean;
1400
+ /**
1401
+ * Ensures a string is wrapped in quotes.
1402
+ */
1403
+ declare function ensureQuoted(s: string, quoteChar?: string): string;
1404
+ /**
1405
+ * Escapes and wraps a string in double quotes.
1406
+ * Avoids redundant escaping.
1407
+ */
1408
+ declare function quoteStr(str: string): string;
1409
+ /**
1410
+ * Replaces specific wrapped substrings within a string with placeholders.
1411
+ * Useful for processing strings while ignoring quoted or bracketed content.
1133
1412
  */
1134
1413
  declare function replaceWithPlaceholder(content: string, options?: ReplacePlacehoderOptions): [string, string[]];
1135
1414
  /**
1136
- * Restores the original substrings from placeholders in the given content.
1137
- *
1138
- * @param content - The string content containing placeholders to be restored.
1139
- * @param placehoders - An array of the original substrings that were replaced by placeholders.
1140
- * @param options - Optional configuration object with the following properties:
1141
- * - `placeholder` - The prefix for the placeholder names. Defaults to `__PlacEhoLdeR_`.
1142
- * @returns The modified content with the original substrings restored.
1143
- *
1144
- * @example
1145
- * ```typescript
1146
- * const contentWithPlaceholders = "Hello __PlacEhoLdeR_0, welcome to __PlacEhoLdeR_1!";
1147
- * const originalSubstrings = ["World", "the site"];
1148
- * const restoredContent = restoreFromPlacehoders(contentWithPlaceholders, originalSubstrings);
1149
- * console.log(restoredContent); // Output: "Hello World, welcome to the site!"
1150
- * ```
1415
+ * Restores original string content from placeholders.
1151
1416
  */
1152
1417
  declare function restoreFromPlacehoders(content: string, placehoders: string[], options?: ReplacePlacehoderOptions): string;
1153
1418
 
@@ -1238,6 +1503,24 @@ declare function pruneSubdirectories(paths: string[]): string[];
1238
1503
  declare function pruneSubdirectoriesInPlace(paths: string[]): void;
1239
1504
  declare function normalizePath(inputPath: string): string;
1240
1505
 
1506
+ /**
1507
+ * Checks if the provided value is a regular expression.
1508
+ *
1509
+ * This function determines whether the given value is a regular expression
1510
+ * by using both string-based and object-based validation methods.
1511
+ *
1512
+ * @param value - The value to be checked for being a regular expression
1513
+ * @returns `true` if the value is a regular expression, otherwise `false`
1514
+ *
1515
+ * @example
1516
+ * ```typescript
1517
+ * isRegExp(/abc/); // true
1518
+ * isRegExp(new RegExp('abc')); // true
1519
+ * isRegExp('/abc/'); // true
1520
+ * isRegExp('abc'); // false
1521
+ * isRegExp(123); // false
1522
+ * ```
1523
+ */
1241
1524
  declare function isRegExp(value: any): boolean;
1242
1525
 
1243
1526
  declare function stripConsoleColor(str: any): any;
@@ -1326,6 +1609,13 @@ declare function truncateToTokenLimit(content: string, options?: ITruncateToToke
1326
1609
  declare function truncateToTokenLimitEx(sentences: string[], options?: ITruncateToTokenLimitOptions): Promise<string[]>;
1327
1610
  declare function truncateByToken(content: string, options?: ITruncateToTokenLimitOptions): Promise<void>;
1328
1611
 
1612
+ declare global {
1613
+ // eslint-disable-next-line @typescript-eslint/consistent-type-definitions -- It has to be an `interface` so that it can be merged.
1614
+ interface SymbolConstructor {
1615
+ readonly observable: symbol;
1616
+ }
1617
+ }
1618
+
1329
1619
  /**
1330
1620
  Extract all optional keys from the given type.
1331
1621
 
@@ -2359,132 +2649,118 @@ declare function joinSplitWords(input: string, separator?: string): string;
2359
2649
  declare function splitWords(input: string): string[];
2360
2650
 
2361
2651
  /**
2362
- * Utility to serialize an object into a URL query parameter string.
2363
- * @param objParam The parameter object.
2364
- * @param omitQuestionMark If true, omits the leading '?' from the result. Defaults to false.
2365
- * @returns The URL-encoded query string or an empty string.
2366
- */
2367
- declare function genUrlParamsStr(objParam: any, omitQuestionMark?: boolean): string;
2368
-
2369
- declare class SseServerPubSubTransport implements IPubSubServerTransport {
2370
- readonly name = "sse";
2371
- readonly protocol: "sse";
2372
- private channel;
2373
- private sessions;
2374
- private onConn?;
2375
- private onDis?;
2376
- connect(options?: {
2377
- req: IncomingMessage;
2378
- res: ServerResponse;
2379
- clientId?: string;
2380
- events?: string[];
2381
- }): PubSubServerSession;
2382
- getSessionFromReq(req: IncomingMessage): PubSubServerSession | undefined;
2383
- subscribe(session: PubSubServerSession, events: string[]): void;
2384
- unsubscribe(session: PubSubServerSession, events: string[]): void;
2385
- publish(event: string, data: any, target?: {
2386
- clientId?: PubSubClientId | PubSubClientId[];
2387
- }): void;
2388
- onConnection(cb: (s: PubSubServerSession) => void): void;
2389
- onDisconnect(cb: (s: PubSubServerSession) => void): void;
2390
- }
2391
-
2392
- declare class SseClientPubSubTransport implements IPubSubClientTransport {
2393
- private apiRoot;
2394
- setApiRoot(apiRoot: string): void;
2395
- connect(url: string, params?: any): Promise<PubSubClientStream>;
2396
- disconnect(stream: PubSubClientStream): void;
2397
- }
2652
+ * Prepends a newline character to the beginning of the input text if it is multiline and does not already start with a newline.
2653
+ *
2654
+ * This function checks whether the provided text contains multiple lines by looking for newline characters (`\n`).
2655
+ * If the text is determined to be multiline and its first non-whitespace character is not a newline,
2656
+ * a newline character will be added at the beginning of the text.
2657
+ *
2658
+ * @param text - The input string to check and potentially modify.
2659
+ * @returns The processed string, which may have a prepended newline if conditions are met.
2660
+ *
2661
+ * @example
2662
+ * ```typescript
2663
+ * console.log(prependNewlineIfMultiline(" hello\nworld")); // Output: "\n hello\nworld"
2664
+ * console.log(prependNewlineIfMultiline("\nhello\nworld")); // Output: "\nhello\nworld" (unchanged)
2665
+ * console.log(prependNewlineIfMultiline("single line")); // Output: "single line" (unchanged)
2666
+ * ```
2667
+ */
2668
+ declare function prependNewlineIfMultiline(text: string): string;
2398
2669
 
2399
2670
  /**
2400
- * Defines the public interface for a server-side transport,
2401
- * responsible for exposing ServerTools to the network.
2671
+ * 行内化样式模式
2672
+ * - 'auto': 根据阈值自动决定
2673
+ * - 'always': 始终行内化 (除非包含换行符)
2674
+ * - 'never': 始终使用块状样式
2402
2675
  */
2403
- interface IServerToolTransport extends IToolTransport {
2404
- /**
2405
- * Mounts the ServerTools registry, creating the necessary API routes.
2406
- *
2407
- * This method is responsible for integrating the tool-handling logic with a
2408
- * running server instance.
2409
- *
2410
- * @param serverTools The ServerTools class containing the tool definitions.
2411
- * @param apiPrefix An optional prefix for all API routes (e.g., '/api').
2412
- * @param options A container for transport-specific options. For example,
2413
- * an HTTP-based transport would expect an `{ server: http.Server }` object
2414
- * to attach its route handlers to.
2415
- */
2416
- mount(serverTools: typeof ServerTools, apiPrefix?: string, options?: any): void;
2417
- /**
2418
- * Starts the transport layer, making it listen for incoming connections.
2419
- * @param options Protocol-specific options (e.g., { port, host }).
2420
- */
2421
- start(options?: any): Promise<any>;
2422
- /**
2423
- * Stops the server instance gracefully.
2424
- * @param force - Optional flag to force shutdown immediately
2425
- * @returns Promise<void> when server is fully stopped
2426
- */
2427
- stop(force?: boolean): Promise<void>;
2428
- /**
2429
- * Gets the underlying raw server instance.
2430
- */
2431
- getRaw?(): any;
2432
- }
2676
+ type TextifyInlineStyleMode = 'auto' | 'always' | 'never';
2433
2677
  /**
2434
- * An abstract base class for server-side transport implementations.
2435
- * It provides the generic tool-mounting logic.
2436
- */
2437
- declare abstract class ServerToolTransport extends ToolTransport implements IServerToolTransport {
2438
- apiRoot: string;
2439
- Tools: typeof ServerTools;
2440
- options?: any;
2441
- _mount(Tools: typeof ServerTools, apiPrefix: string, options?: any): void;
2442
- start(options?: any): Promise<any>;
2443
- abstract addDiscoveryHandler(path: string, handler: () => any): void;
2444
- abstract addRpcHandler(serverTools: typeof ServerTools, apiPrefix: string, options?: any): void;
2445
- abstract _start(options?: any): Promise<any>;
2446
- abstract stop(force?: boolean): Promise<void>;
2447
- abstract getRaw?(): any;
2448
- }
2449
-
2678
+ * 字符串引用策略 (是否用引号包裹)
2679
+ * - 'auto': 遇到特殊字符、保留字或数字外观时自动加引号
2680
+ * - 'always': 所有字符串始终加引号
2681
+ * - 'never': 尽可能不加引号
2682
+ */
2683
+ type TextifyStringQuoting = 'auto' | 'always' | 'never';
2450
2684
  /**
2451
- * A concrete server transport implementation using Node.js's built-in HTTP server.
2452
- */
2453
- declare class HttpServerToolTransport extends ServerToolTransport {
2454
- server: http.Server;
2455
- private discoveryHandlerInfo;
2456
- constructor(options?: http.ServerOptions);
2457
- private requestListener;
2458
- addDiscoveryHandler(apiPrefix: string, handler: () => any): void;
2459
- addRpcHandler(serverTools: typeof ServerTools, apiPrefix: string, options?: any): void;
2460
- private handleRpcRequest;
2461
- private getRequestBody;
2462
- _start(options: {
2463
- port: number;
2464
- host?: string;
2465
- }): Promise<void>;
2466
- stop(force?: boolean): Promise<void>;
2467
- getRaw(): http.Server;
2685
+ * 行内化详细配置
2686
+ */
2687
+ interface TextifyInlineOptions {
2688
+ /** 模式 (默认:'auto') */
2689
+ mode?: TextifyInlineStyleMode;
2690
+ /** 自动行内化的字符长度阈值 (默认:40) */
2691
+ threshold?: number;
2692
+ /** 逗号和冒号后是否保留空格 (默认:true) */
2693
+ spaceAfterSeparator?: boolean;
2694
+ /** 括号/大括号内侧是否保留空格 (默认:false) */
2695
+ spaceInBraces?: boolean;
2468
2696
  }
2469
-
2470
2697
  /**
2471
- * A concrete client transport implementation that uses the browser/node `fetch` API.
2698
+ * 文本化配置选项
2699
+ *
2700
+ * @description
2701
+ * 该工具旨在生成易于人类阅读的、类 YAML 格式的文本表示。
2702
+ *
2703
+ * **核心渲染规则:**
2704
+ * 1. **对象数组 (Object Array)**: 采用 YAML 风格的紧凑模式。
2705
+ * 当对象作为数组项时,会忽略对象自身的 `objectPrefix`,并将第一个键值对紧跟在数组前缀 `-` 后。
2706
+ * 示例:`[{a: 1, b: 2}]` -> `- a: 1\n b: 2`
2707
+ *
2708
+ * 2. **嵌套数组 (Nested Array)**: 采用阶梯式 (Block Style)。
2709
+ * 内层数组会从新的一行开始,并相对于父级缩进。
2710
+ * 示例:`[[1, 2]]` -> `-\n - 1\n - 2`
2711
+ *
2712
+ * 3. **多行字符串对齐**: 自动计算前缀和键名的长度,确保多行文本的后续行与首行左对齐。
2713
+ *
2714
+ * **高级特性:**
2715
+ * - **智能行内化 (Inline Style)**: 自动将短对象或数组转换为 `{a: 1}` 格式。
2716
+ * - **混合模式 (Mixed Mode)**: 根据内容长度自动决定嵌套项是行内还是块状显示。
2717
+ * - **自动引用 (Auto Quoting)**: 智能识别需要引号包裹的字符串(包含特殊字符、保留字或数字外观)。
2472
2718
  */
2473
- declare class HttpClientToolTransport extends ClientToolTransport {
2719
+ interface TextifyOptions {
2720
+ /** 缩进单位,可以是空格数或具体的字符串 (默认:2 个空格) */
2721
+ indent?: string | number;
2722
+ /** 数组项前缀 (默认:'-') */
2723
+ arrayPrefix?: string;
2724
+ /** 对象键值对前缀 (默认:'*') */
2725
+ objectPrefix?: string;
2726
+ /** 最大递归深度,防止过深 (默认:10) */
2727
+ maxDepth?: number;
2474
2728
  /**
2475
- * Connects to the server's discovery endpoint to get the list of available tools.
2476
- * @returns A promise that resolves to a map of tool function metadata.
2729
+ * 是否确保多行字符串强制换行
2730
+ * (默认:false)
2477
2731
  */
2478
- loadApis(): Promise<Funcs>;
2479
- _fetch(name: string, args?: any, act?: ActionName | string, subName?: any, fetchOptions?: any): Promise<Response>;
2732
+ ensureNewLineForMultiline?: boolean;
2480
2733
  /**
2481
- * @internal
2482
- * A helper to create a structured error from a failed `fetch` response.
2483
- * @param res - The HTTP response.
2484
- * @returns A structured error object.
2734
+ * 行内化配置
2735
+ * - 'auto': 基于阈值自动切换 (默认)
2736
+ * - 'always': 强制行内化 (遇到换行符除外)
2737
+ * - 'never': 强制块状化
2485
2738
  */
2486
- errorFrom(name: string, res: Response): Promise<_isdk_common_error.CommonError>;
2487
- toObject(res: any, args?: any): Promise<any>;
2739
+ inlineStyle?: TextifyInlineStyleMode | TextifyInlineOptions;
2740
+ /**
2741
+ * 字符串引用策略 (是否加双引号)
2742
+ * - 'auto': 遇到特殊字符 (:, #, [, ], {, }, *, -, ")、首尾空格、保留字或数字外观时自动加引号 (默认)
2743
+ * - 'always': 所有字符串始终加引号
2744
+ * - 'never': 除非结构必须,否则不加引号
2745
+ */
2746
+ stringQuoting?: TextifyStringQuoting;
2488
2747
  }
2748
+ /**
2749
+ * 将任意数据转换为易读的类 YAML 文本
2750
+ *
2751
+ * @param data - 要转换的数据
2752
+ * @param options - 配置选项
2753
+ * @returns 格式化后的文本字符串
2754
+ *
2755
+ * @example
2756
+ * ```ts
2757
+ * const text = textify([{ name: 'Alice', age: 20 }, { name: 'Bob' }]);
2758
+ * // 输出:
2759
+ * // - name: Alice
2760
+ * // age: 20
2761
+ * // - name: Bob
2762
+ * ```
2763
+ */
2764
+ declare function textify(data: any, options?: TextifyOptions): string;
2489
2765
 
2490
- export { AIArgProcessor, type AIChatAssistantMessageParam, type AIChatContentPart, type AIChatContentPartImage, type AIChatContentPartText, type AIChatMessageParam, type AIChatMessageParamBase, type AIChatMessageToolCall, type AIChatRole, AIChatRoles, type AIChatSystemMessageParam, type AIChatToolChoiceFuncObject, type AIChatToolChoiceObject, type AIChatToolChoiceParam, type AIChatToolFunc, type AIChatToolFuncParam, type AIChatToolMessageParam, type AIChatToolParam, type AIChatToolTypeObject, type AIChatUserMessageParam, type AIChoiceConfig, type AIMessageType, AIMessageTypes, AIModelNameRules, type AIResult, AIStream, type AIStreamParser, type AIStreamParserOptions, type AITextGenerationFinishReason, AITextGenerationFinishReasons, ActionName, ArrayMergeWay, ArrayMergeWaySymbol, AsyncTaskId, type BeforeShutdownListener, ChoiceArgProcessor, ClientToolTransport, DEFAULT_CONFIG_NAME, DefaultDateFormat, EventBusName, type EventErrorListenerFn, type EventListenerFn, EventName, FewShotPromptTemplate, type FewShotPromptTemplateOptions, Funcs, type HashAlgoParams, HashAlgorithm, HttpClientToolTransport, HttpServerToolTransport, type IFileMetaInfo, IPubSubClientTransport, IPubSubServerTransport, type IReadTextFileChunksOptions, type IServerToolTransport, IToolTransport, type ITruncateToTokenLimitOptions, IntSet, type JsonFilter, LLM_TOKENIZER_NAMES, LLM_TOKENIZER_NAMES_MAP, ObjectArgsToArgsInfo, type ParseObjectArgumentOptions, type ProbabilityItem, PromptExampleSelector, type PromptExampleSelectorOptions, type PromptExamples, PubSubClientId, PubSubClientStream, PubSubServerSession, RStreamErrCode, ReadableStreamError, type ReplacePlacehoderOptions, ResponseRStreamErrCode, SHUTDOWN_SIGNALS, SSEChannel, SSEChannelAlreadyClosedErrCode, type SSEClient, type SectionStringOptions, ServerToolTransport, ServerTools, SignalGate, type SplitSentenceOptions, SseClientPubSubTransport, SseServerPubSubTransport, StrangeHumanName, type StreamCallbacksAndOptions, TemplateArgProcessor, ToolTransport, type UUIDVersions, YamlTypeBaseObject, assignDirs, backendEventable, base32768, beforeShutdown, calcPerplexity, calcPerplexitySimple, completeSentences, concatText, countLLMTokens, countRegexMatches, createCallbacksTransformer, createEmptyReadableStream, createEndWithRepetitionDetector, createEventStreamTransformer, createYamlObjectTag, dateToText, decodeCharset, defaultsWithConcat, detectCharset, encodeLLMTokens, ensureQuoted, expandConfig, expandPath, expandPathInObject, expandPaths, fileIsExists, filterValidFnScope, findIndexNonEmptyFrom, formatTextWithSpace, genUrlParamsStr, getAllEnumKeys, getConfigFileNames, getConfigs, getFileMetaInfo, getHashAlgoBySize, getKeysPath, getLLMTokenizer, getPackageDir, getRealFilepath, getResponseErrorReadableStream, getXDGConfigs, hasDirectoryIn, hash, hashFile, hashObject, hashStream, initShutdown, isLangUsingSpaces, isListItemString, isModelNameMatched, isPunctuationChar, isQuoted, isRegExp, isSameString, isSectionString, isSentenceEnding, isSepLineString, isStrWrapped, isSubdirectory, isTitleString, isWebStream, joinSplitWords, jsonFilterToWhere, jsonToMarkdownStr, loadAIConfig, loadConfig, loadConfigFile, loadFileFromPaths, loadTextFromPaths, matchUrlProtocol, memoize, mergeArray, messagesToText, normalizePath, paramsSizeToScaleStr, parseCommand, parseJsJson, parseJsJsonSimpleSync, parseObjectArgInfo, parseObjectArgumentInfos, parseObjectArguments, parseObjectArgumentsAsArgInfos, pruneSubdirectories, pruneSubdirectoriesInPlace, quoteStr, readFilenamesRecursiveSync, readTextFileChunks, readTextFileChunksEx, readableFromAsyncIterable, removeMarkdownBold, removeMarkdownBoldAndItalic, removeMarkdownItalic, replaceWithPlaceholder, restoreFromPlacehoders, saveConfigFile, scaleStrToParamsSize, shutdown, simplifyObjectArguments, sleep, sortedValues, splitChunks, splitParagraph, splitSentence, splitWords, stripConsoleColor, textToDate, toDateTime, trimStartOfStreamHelper, truncTo, truncateByToken, truncateToTokenLimit, truncateToTokenLimitEx, uuid, wait, xxhash, xxhash32, xxhash64, xxhashAsStr, yieldExec };
2766
+ export { AIArgProcessor, type AIChatAssistantMessageParam, type AIChatContentPart, type AIChatContentPartBase, type AIChatContentPartImage, type AIChatContentPartText, type AIChatMessageParam, type AIChatMessageParamBase, type AIChatMessageToolCall, type AIChatRole, AIChatRoles, type AIChatSystemMessageParam, type AIChatTemplateCaps, type AIChatToolChoiceFuncObject, type AIChatToolChoiceObject, type AIChatToolChoiceParam, type AIChatToolDefinition, type AIChatToolFunc, type AIChatToolFuncParam, type AIChatToolMessageParam, type AIChatToolParam, type AIChatToolTypeObject, type AIChatUserMessageParam, type AIMessageType, AIMessageTypes, type AIModelNameRule, type AIModelNameRuleFn, type AIModelNameRules, type AIResult, AIStream, type AIStreamParser, type AIStreamParserOptions, type AITextGenerationFinishReason, AITextGenerationFinishReasons, type ArgProcessor, ArrayMergeWay, ArrayMergeWaySymbol, type BeforeShutdownListener, CMD_ARG_FLAG_SYMBOL, CMD_ARG_PROCESSOR_RESULT, CMD_ARG_UNRESOLVED_SYMBOL, ChoiceArgProcessor, type CmdArgAIChoiceConfig, type CmdArgArgsInfo, type CmdArgContext, type CmdArgFlagMetadata, type CmdArgFlagValue, type CmdArgFlagsRecord, CmdArgLexer, type CmdArgMapResult, type CmdArgParseResult, type CmdArgParsedCommand, CmdArgParser, type CmdArgParserOptions, type CmdArgProcessorResultOptions, type CmdArgSimplifyOptions, type CmdArgToken, CmdArgTokenType, DEFAULT_CONFIG_NAME, DefaultDateFormat, FewShotPromptTemplate, type FewShotPromptTemplateOptions, IDENTIFIER_REGEX, type IFileMetaInfo, type IReadTextFileChunksOptions, type ITruncateToTokenLimitOptions, type JsonFilter, LLM_TOKENIZER_NAMES, LLM_TOKENIZER_NAMES_MAP, ObjectArgsToArgsInfo, PASSING_SCORE, PATH_IDENTIFIER_REGEX, type ProbabilityItem, PromptExampleSelector, type PromptExampleSelectorOptions, type PromptExamples, RESERVED_WORDS, RStreamErrCode, ReadableStreamError, type ReplacePlacehoderOptions, ResponseRStreamErrCode, SHUTDOWN_SIGNALS, type SectionStringOptions, type SimplifiedResultType, type SplitSentenceOptions, StrangeHumanName, TemplateArgProcessor, type TextifyInlineOptions, type TextifyInlineStyleMode, type TextifyOptions, type TextifyStringQuoting, YamlTypeBaseObject, assignDirs, beforeShutdown, calcPerplexity, calcPerplexitySimple, cmdArgEvaluate, cmdArgsToMergedObject, completeSentences, concatText, countLLMTokens, countRegexMatches, createEmptyReadableStream, createEndWithRepetitionDetector, createEventStreamTransformer, createYamlObjectTag, dateToText, decodeCharset, defaultsWithConcat, detectCharset, encodeLLMTokens, ensureQuoted, evaluateExpression, expandConfig, expandPath, expandPathInObject, expandPaths, fileIsExists, filterValidFnScope, findIndexNonEmptyFrom, formatTextWithSpace, getAllEnumKeys, getConfigFileNames, getConfigs, getFileMetaInfo, getHashAlgoBySize, getKeysPath, getLLMTokenizer, getPackageDir, getRealFilepath, getResponseErrorReadableStream, getXDGConfigs, hasDirectoryIn, hashFile, initShutdown, isIdentifier, isLangUsingSpaces, isListItemString, isModelNameMatched, isPathIdentifier, isPunctuationChar, isQuoted, isRegExp, isSameString, isSectionString, isSentenceEnding, isSepLineString, isStrWrapped, isSubdirectory, isTitleString, isWebStream, joinSplitWords, jsonFilterToWhere, jsonToMarkdownStr, loadAIConfig, loadConfig, loadConfigFile, loadFileFromPaths, loadTextFromPaths, matchUrlProtocol, memoize, mergeArray, messagesToText, normalizePath, paramsSizeToScaleStr, parseCommand, parseJsJson, parseJsJsonSimpleSync, parseObjectArguments, prependNewlineIfMultiline, pruneSubdirectories, pruneSubdirectoriesInPlace, quoteStr, readFilenamesRecursiveSync, readTextFileChunks, readTextFileChunksEx, readableFromAsyncIterable, removeMarkdownBold, removeMarkdownBoldAndItalic, removeMarkdownItalic, replaceWithPlaceholder, restoreFromPlacehoders, saveConfigFile, scaleStrToParamsSize, shutdown, simplifyObjectArguments, simplifyResult, sortedValues, splitChunks, splitParagraph, splitSentence, splitWords, stripConsoleColor, textToDate, textify, toDateTime, trimStartOfStreamHelper, truncTo, truncateByToken, truncateToTokenLimit, truncateToTokenLimitEx, wait, wrapFlagValue };